repo_name
stringlengths
5
114
repo_url
stringlengths
24
133
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
directory_id
stringlengths
40
40
branch_name
stringclasses
209 values
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
9.83k
683M
star_events_count
int64
0
22.6k
fork_events_count
int64
0
4.15k
gha_license_id
stringclasses
17 values
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_language
stringclasses
115 values
files
listlengths
1
13.2k
num_files
int64
1
13.2k
sshertuk/document-classification-aiva
https://github.com/sshertuk/document-classification-aiva
e56f4fea7ac2de3ef831bc8c151f41d92711b42c
b78f1a9e9fe7b8a2362a5555aca7ba9b5498675e
8c45b2e018c61b7e38bb00f540367b70e248f152
refs/heads/master
2020-03-10T04:25:03.786309
2018-04-18T17:47:35
2018-04-18T17:47:35
129,191,592
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7092511057853699, "alphanum_fraction": 0.7092511057853699, "avg_line_length": 31.428571701049805, "blob_id": "c321a4c8299e0cc98732a62097b2ac0eb9e23e9b", "content_id": "c2e1c3b4ec070ed29507ba36b11d6586b9b5c0b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 227, "license_type": "no_license", "max_line_length": 89, "num_lines": 7, "path": "/webapps/urls.py", "repo_name": "sshertuk/document-classification-aiva", "src_encoding": "UTF-8", "text": "from django.conf.urls import include, url\nfrom fileclassifier import views\n\nurlpatterns = [\n url(r'^$', views.base_view), #base url\n url(r'^get_response$', views.get_response, name='get_response'), #process request url\n]\n" }, { "alpha_fraction": 0.7864077687263489, "alphanum_fraction": 0.7864077687263489, "avg_line_length": 19.600000381469727, "blob_id": "9c76558089d89b52c2644f2c636a11f56e09f131", "content_id": "198b7188f531439d16688ffc3aec2de506b8f7ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 103, "license_type": "no_license", "max_line_length": 38, "num_lines": 5, "path": "/fileclassifier/apps.py", "repo_name": "sshertuk/document-classification-aiva", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass FileclassifierConfig(AppConfig):\n name = 'fileclassifier'\n" }, { "alpha_fraction": 0.737187922000885, "alphanum_fraction": 0.7667542695999146, "avg_line_length": 32.79999923706055, "blob_id": "aa4e6aa2676771bbf458e2b92a00e1cce7f8c49c", "content_id": "7c9d26852afd99f578285ae57a7210335cad3118", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1522, "license_type": "no_license", "max_line_length": 163, "num_lines": 45, "path": "/README.md", "repo_name": "sshertuk/document-classification-aiva", "src_encoding": "UTF-8", "text": "# FileClassifier API - Classification Test\n\nHelping train AIVA.\n\n## Getting Started\n\nThe web application (hosted on AWS EC2 Ubuntu dev server) can be accessed at: http://13.58.127.83:8000\n\nThe application uses the REST API deploy on AWS infrastrcture: https://rb2pqd7dte.execute-api.us-east-2.amazonaws.com/dev\n\nAddtionally, following instructions will get you a copy of the project up and running on your local machine for development and testing purposes.\n\n### Prerequisites\n\nThe following plugins/dependecies have been used for development. Please ensure you have atleast these versions installed.\n\n```\nPython 3, Django 1.11, Bootsrap 4, Font-Awesome 5.0.8\n```\n\n### Installing\n1. Clone repository and run the following command to create required migration files\n```\npython manage.py makemigrations\n```\n2. Apply created migration files to the database by running\n```\npython manage.py migrate\n```\n3. Run application on localhost\n```\npython manage.py runserver\n```\n\n### Description\n```\na. This is a web application built on the Django MVC framework v1.11\nb. The application interacts with the file classifier REST API built and deploy on AWS using its storage(S3), compute(lambda), and API (API Gateway) infrastructure\n```\n\n### Directions to Use\n```\na.After accessing the website (http://13.58.127.83:8000), input the words (in the same format as the provided data) from the file to classified\nb.Click on Predict to trigger the process. The predicted value would be shown once the classification is run on the model.\n```\n\n" }, { "alpha_fraction": 0.726883053779602, "alphanum_fraction": 0.7385180592536926, "avg_line_length": 33.04166793823242, "blob_id": "bc5faf048c98def376ecf6222782f65be085fc76", "content_id": "088e1e6cc7078b1c32828eafb1e21c087a2cc6b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1633, "license_type": "no_license", "max_line_length": 103, "num_lines": 48, "path": "/fileclassifier/views.py", "repo_name": "sshertuk/document-classification-aiva", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nimport requests\nfrom django.shortcuts import render, redirect\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponse, Http404\nimport json\nimport zlib\nimport base64\n\n\n#Base view for first page re-direction\ndef base_view(request):\n\treturn render(request, 'fileclassifier/input_view.html', {'prediction':'Processing not initiated...'})\n\n#request handler and processor\ndef get_response(request):\n\tcontext = {}\n\tdata = request.POST.get('data')\n\tcontext['prediction'] = 'Processing not initiated...'\n\n\t#if data is blank throw error\n\tif not data:\n\t\tcontext['error'] = 'Please enter valid words data!'\n\t\tcontext['prediction'] = 'Error Encounter while processing...'\n\t\treturn render(request, 'fileclassifier/input_view.html', context)\n\n\t#process API calls and build output\n\ttry:\n\t\tdata1 = str.encode(data)\n\t\tenc_data = base64.b64encode(zlib.compress(data1,9))\n\n\t\turl = 'https://rb2pqd7dte.execute-api.us-east-2.amazonaws.com/dev'\n\t\t#url = 'http://localhost:5000'\n\t\tparam = {\"words\": enc_data.strip()}\n\t\theaders = {'content-type': \"application/json\"}\n\t\tapi_response = requests.get(url, params=param, headers=headers)\n\t\t#print(api_response)\n\t\t#print(api_response.content.decode())\n\t\t#print(api_response.content)\n\t\ttestres = json.loads(api_response.content.decode())\n\n\t\t#set output\n\t\tcontext['prediction'] = testres['prediction']\n\t\treturn render(request, 'fileclassifier/input_view.html', context)\n\texcept Exception as e:\n\t\tcontext['prediction'] = 'Error Encounter while processing...'\n\t\tcontext['error'] = str(e)\n\t\treturn render(request, 'fileclassifier/input_view.html', context)" } ]
4
galaxy3-net/roku
https://github.com/galaxy3-net/roku
b165c07a8cc6344b0fa605a195e87662add1e491
f72bfcd0797da8007e0750a1946382b9d98478fc
312fe2be69c0b223accf451d91f73463f0cca14d
refs/heads/master
2022-12-09T09:57:52.147132
2020-09-09T04:30:13
2020-09-09T04:30:13
293,999,160
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.559256374835968, "alphanum_fraction": 0.6065065860748291, "avg_line_length": 22.053571701049805, "blob_id": "e1072090e6ba62ca5aeba87c5474a9d3322f500e", "content_id": "75e6c98edc7ffef439c4bb23463ac5b541204214", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1291, "license_type": "no_license", "max_line_length": 87, "num_lines": 56, "path": "/create.py", "repo_name": "galaxy3-net/roku", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/python3\n\nimport json\nfrom datetime import datetime, date, time\n\nmy_feed = dict()\n\nmy_feed['providerName'] = \"Galaxy3.net\"\nmy_feed['language'] = \"en-US\"\nmy_feed['lastUpdated'] = datetime.now().astimezone().replace(microsecond=0).isoformat()\n# https://stackoverflow.com/questions/2150739/iso-time-iso-8601-in-python\n\nmy_feed['categories'] = [ {\n \"name\": \"Cooking Shows\",\n \"query\": \"cooking AND reality shows\",\n \"order\": \"most_popular\"\n} ]\n\nmy_feed['movies'] = [\n{ \n \"id\":\"1509428502952\",\n \"title\":\"Sample Movie\",\n \"content\":{ \n \t\"dateAdded\": datetime.now().astimezone().replace(microsecond=0).isoformat(),\n \t\"videos\": [\n \t {\n \t\t\"url\": \"https://mnmedias.api.telequebec.tv/m3u8/29880.m3u8\",\n \t \t\"quality\": \"HD\",\n \t \t\"videoType\": \"MP4\"\n \t }\n\t]\n },\n \"genres\":[ \n \"drama\",\n \"comedy\",\n \"horror\"\n ],\n \"thumbnail\":\"https://example.org/cdn/thumbnails/1509428502952/1\",\n \"releaseDate\":\"2016-01-01\",\n \"shortDescription\":\"Incredible movie description\",\n \"longDescription\":\"Even more incredible and longer movie description\",\n \"tags\":[ \n \"amazing\",\n \"drama\",\n \"comedy\",\n \"horror\"\n ]\n}]\n\njson_obj = json.dumps(my_feed, indent=4)\n\nfh = open(\"feed.json\", \"w\")\n\nfh.write(json_obj)\n\nfh.close()\n" } ]
1
calvinwhealton/SALib
https://github.com/calvinwhealton/SALib
fce80e33f15dfb3d32817d4b5cff3fa038d479fa
34d40ca1415d70d33c2d25c25a01498f1835af00
b238fcc2a5aeb8d953b7c58015072dbca8b0327e
refs/heads/master
2021-01-15T22:01:03.402659
2016-02-02T21:21:21
2016-02-02T21:21:21
50,427,803
0
1
null
2016-01-26T12:39:17
2016-01-15T05:02:06
2016-01-22T16:30:33
null
[ { "alpha_fraction": 0.5328769087791443, "alphanum_fraction": 0.5378124713897705, "avg_line_length": 37.75316619873047, "blob_id": "458813a536d32f88a916eb6e398485ea3442bec3", "content_id": "3d38388469c80048839d9d8469acc8a572891101", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6281, "license_type": "permissive", "max_line_length": 104, "num_lines": 158, "path": "/SALib/sample/saltelli.py", "repo_name": "calvinwhealton/SALib", "src_encoding": "UTF-8", "text": "from __future__ import division\r\n\r\nimport numpy as np\r\n\r\nfrom . import common_args\r\nfrom . import sobol_sequence\r\nfrom ..util import scale_samples, nonuniform_scale_samples, read_param_file\r\n\r\n\r\ndef sample(problem, N, calc_second_order=True):\r\n \"\"\"Generates model inputs using Saltelli's extension of the Sobol sequence.\r\n\r\n Returns a NumPy matrix containing the model inputs using Saltelli's sampling\r\n scheme. Saltelli's scheme extends the Sobol sequence in a way to reduce\r\n the error rates in the resulting sensitivity index calculations. If\r\n calc_second_order is False, the resulting matrix has N * (D + 2)\r\n rows, where D is the number of parameters. If calc_second_order is True,\r\n the resulting matrix has N * (2D + 2) rows. These model inputs are\r\n intended to be used with :func:`SALib.analyze.sobol.analyze`.\r\n\r\n Parameters\r\n ----------\r\n problem : dict\r\n The problem definition\r\n N : int\r\n The number of samples to generate\r\n calc_second_order : bool\r\n Calculate second-order sensitivities (default True)\r\n \"\"\"\r\n D = problem['num_vars']\r\n\r\n if not problem.get('groups'):\r\n groups = False\r\n Dg = problem['num_vars']\r\n else:\r\n groups = True\r\n # condition for when problem was defined from parameter file\r\n # can access the 'groups' tuple (matrix, list of unique group names)\r\n # to determine the number of groups\r\n # if problem defined as a dictionary in the code, find the number\r\n # of unique group names\r\n # also make matrix to account for group names\r\n if len(problem['groups']) == 2:\r\n Dg = len(problem['groups'][1])\r\n else:\r\n Dg = len(np.unique(problem['groups']))\r\n gp_mat = np.zeros([D, Dg])\r\n for i in range(Dg):\r\n # group name to check for equivalency\r\n groupNameIt = np.unique(problem['groups'])[i]\r\n for j in range(D):\r\n if problem['groups'][j] == groupNameIt:\r\n gp_mat[j,i] = 1\r\n # making a tuple similar to the one made by the read_param_file\r\n # for use later in the code\r\n problem['groups'] = (gp_mat,np.unique(problem['groups']))\r\n\r\n # How many values of the Sobol sequence to skip\r\n skip_values = 1000\r\n\r\n # Create base sequence - could be any type of sampling\r\n base_sequence = sobol_sequence.sample(N + skip_values, 2 * D)\r\n\r\n if calc_second_order:\r\n saltelli_sequence = np.empty([(2 * Dg + 2) * N, D])\r\n else:\r\n saltelli_sequence = np.empty([(Dg + 2) * N, D])\r\n index = 0\r\n\r\n for i in range(skip_values, N + skip_values):\r\n\r\n # Copy matrix \"A\"\r\n for j in range(D):\r\n saltelli_sequence[index, j] = base_sequence[i, j]\r\n\r\n index += 1\r\n\r\n # Cross-sample elements of \"B\" into \"A\"\r\n # condition for group sampling (groups is True)\r\n if groups:\r\n # method of cross-sampling \"B\" into \"A\" for groups\r\n # groups that are \"off-diagional\" (l != m) will be form \"A\"\r\n # groups that are \"on-diagional\" (l = m) will be from \"B\"\r\n for l in range(Dg):\r\n for m in range(D):\r\n if problem['groups'][0][m,l] == 1:\r\n saltelli_sequence[index, m] = base_sequence[i, m + D]\r\n else:\r\n saltelli_sequence[index, m] = base_sequence[i, m]\r\n\r\n index += 1\r\n else:\r\n for k in range(D):\r\n for j in range(D):\r\n if j == k:\r\n saltelli_sequence[index, j] = base_sequence[i, j + D]\r\n else:\r\n saltelli_sequence[index, j] = base_sequence[i, j]\r\n\r\n index += 1\r\n\r\n # Cross-sample elements of \"A\" into \"B\"\r\n # Only needed if you're doing second-order indices (true by default)\r\n if calc_second_order:\r\n # condition for group sampling (groups is True)\r\n if groups:\r\n # method of cross-sampling \"A\" into \"B\" for groups\r\n # groups that are \"off-diagional\" (l != m) will be form \"B\"\r\n # groups that are \"on-diagional\" (l = m) will be from \"A\"\r\n for l in range(Dg):\r\n for m in range(D):\r\n if problem['groups'][0][m,l] == 1:\r\n saltelli_sequence[index, m] = base_sequence[i, m]\r\n else:\r\n saltelli_sequence[index, m] = base_sequence[i, m + D]\r\n\r\n index += 1\r\n else:\r\n for k in range(D):\r\n for j in range(D):\r\n if j == k:\r\n saltelli_sequence[index, j] = base_sequence[i, j]\r\n else:\r\n saltelli_sequence[index, j] = base_sequence[i, j + D]\r\n\r\n index += 1\r\n\r\n # Copy matrix \"B\"\r\n for j in range(D):\r\n saltelli_sequence[index, j] = base_sequence[i, j + D]\r\n\r\n index += 1\r\n if not problem.get('dists'):\r\n # scaling values out of 0-1 range with uniform distributions\r\n scale_samples(saltelli_sequence,problem['bounds'])\r\n return saltelli_sequence\r\n else:\r\n # scaling values to other distributions based on inverse CDFs\r\n scaled_saltelli = nonuniform_scale_samples(saltelli_sequence,problem['bounds'],problem['dists'])\r\n return scaled_saltelli\r\n\r\nif __name__ == \"__main__\":\r\n\r\n parser = common_args.create()\r\n\r\n parser.add_argument(\r\n '-n', '--samples', type=int, required=True, help='Number of Samples')\r\n\r\n parser.add_argument('--max-order', type=int, required=False, default=2,\r\n choices=[1, 2], help='Maximum order of sensitivity indices to calculate')\r\n args = parser.parse_args()\r\n\r\n np.random.seed(args.seed)\r\n problem = read_param_file(args.paramfile)\r\n\r\n param_values = sample(problem, args.samples, calc_second_order=(args.max_order == 2))\r\n np.savetxt(args.output, param_values, delimiter=args.delimiter,\r\n fmt='%.' + str(args.precision) + 'e')\r\n" }, { "alpha_fraction": 0.6139954924583435, "alphanum_fraction": 0.6139954924583435, "avg_line_length": 22.3157901763916, "blob_id": "e2f31fa3a4c987526153e66345fb02167cd0290b", "content_id": "c4d7b9ec0f4e1d7eac944dd2281b1450dfc77f06", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 886, "license_type": "permissive", "max_line_length": 72, "num_lines": 38, "path": "/docs/api.rst", "repo_name": "calvinwhealton/SALib", "src_encoding": "UTF-8", "text": "=============\nAPI Reference\n=============\n\nThis page documents the sensitivity analysis methods supported by SALib.\n\nFAST - Fourier Amplitude Sensitivity Test\n-----------------------------------------\n\n.. autofunction:: SALib.sample.fast_sampler.sample\n\n.. autofunction:: SALib.analyze.fast.analyze\n\nMethod of Morris\n----------------\n\n.. autofunction:: SALib.sample.morris.sample\n\n.. autofunction:: SALib.analyze.morris.analyze\n\nSobol Sensitivity Analysis\n--------------------------\n\n.. autofunction:: SALib.sample.saltelli.sample\n\n.. autofunction:: SALib.analyze.sobol.analyze\n\nDelta Moment-Independent Measure\n--------------------------------\n\n.. autofunction:: SALib.sample.latin.sample\n\n.. autofunction:: SALib.analyze.delta.analyze\n\nDerivative-based Global Sensitivity Measure (DGSM)\n--------------------------------------------------\n\n.. autofunction:: SALib.analyze.dgsm.analyze\n" }, { "alpha_fraction": 0.5656148791313171, "alphanum_fraction": 0.573085606098175, "avg_line_length": 37.38867950439453, "blob_id": "fcdcd27a8d8e51c941afb15a161c1befad2d5d3d", "content_id": "a1d4097f5729262931dfab2c364192a023aedd95", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10173, "license_type": "permissive", "max_line_length": 97, "num_lines": 265, "path": "/SALib/util/__init__.py", "repo_name": "calvinwhealton/SALib", "src_encoding": "UTF-8", "text": "__all__ = [\"scale_samples\", \"read_param_file\"]\nfrom collections import OrderedDict\nimport csv\nfrom warnings import warn\n\nimport numpy as np\nimport scipy as sp\n\ndef scale_samples(params, bounds):\n '''\n Rescales samples in 0-to-1 range to arbitrary bounds.\n\n Arguments:\n bounds - list of lists of dimensions num_params-by-2\n params - numpy array of dimensions num_params-by-N,\n where N is the number of samples\n '''\n # Check bounds are legal (upper bound is greater than lower bound)\n b = np.array(bounds)\n lower_bounds = b[:, 0]\n upper_bounds = b[:, 1]\n\n if np.any(lower_bounds >= upper_bounds):\n raise ValueError(\"Bounds are not legal\")\n\n # This scales the samples in-place, by using the optional output\n # argument for the numpy ufunctions\n # The calculation is equivalent to:\n # sample * (upper_bound - lower_bound) + lower_bound\n np.add(np.multiply(params,\n (upper_bounds - lower_bounds),\n out=params),\n lower_bounds,\n out=params)\n\ndef unscale_samples(params, bounds):\n '''\n Rescales samples from arbitrary bounds back to [0,1] range.\n\n Arguments:\n bounds - list of lists of dimensions num_params-by-2\n params - numpy array of dimensions num_params-by-N,\n where N is the number of samples\n '''\n # Check bounds are legal (upper bound is greater than lower bound)\n b = np.array(bounds)\n lower_bounds = b[:, 0]\n upper_bounds = b[:, 1]\n\n if np.any(lower_bounds >= upper_bounds):\n raise ValueError(\"Bounds are not legal\")\n\n # This scales the samples in-place, by using the optional output\n # argument for the numpy ufunctions\n # The calculation is equivalent to:\n # (sample - lower_bound) / (upper_bound - lower_bound)\n np.divide(np.subtract(params, lower_bounds, out=params),\n np.subtract(upper_bounds, lower_bounds),\n out=params)\n\ndef nonuniform_scale_samples(params, bounds, dists):\n '''\n Rescales samples in 0-to-1 range to other distributions.\n\n Arguments:\n problem - problem definition including bounds\n params - numpy array of dimensions num_params-by-N,\n where N is the number of samples\n dists-list of distributions, one for each parameter\n unif: uniform with lower and upper bounds\n triang: triangular with width (scale) and location of peak\n location of peak is in percentage of width\n lower bound assumed to be zero\n norm: normal distribution with mean and standard deviation\n lognorm: lognormal with ln-space mean and standard deviation\n '''\n b = np.array(bounds)\n\n if len(params[0]) != len(dists):\n print('Incorrect number of distributions specified')\n print('Original parameters returned')\n return params\n else:\n # initializing matrix for converted values\n conv_params = np.empty([len(params),len(params[0])])\n\n # loop over the parameters\n for i in range(len(conv_params[0])):\n # setting first and second arguments for distributions\n arg1 = b[i][0]\n arg2 = b[i][1]\n\n # triangular distribution\n # paramters are width (scale) and location of peak\n # location of peak is relative to scale\n # e.g., 0.25 means peak is 25% of the width distance from zero\n if dists[i] == 'triang':\n # checking for correct parameters\n if arg1 <= 0:\n print('Scale must be greater than zero')\n print('Parameter not converted')\n conv_params[:,i] = params[:,i]\n elif (arg2 <= 0) or (arg2 >= 1):\n print('Peak must be on interval [0,1]')\n print('Parameter not converted')\n conv_params[:,i] = params[:,i]\n else:\n conv_params[:,i] = sp.stats.triang.ppf(params[:,i],c=arg2,scale=arg1,loc=0)\n\n # uniform distribution\n # parameters are lower and upper bounds\n elif dists[i] == 'unif':\n # checking that upper bound is greater than lower bound\n if arg1 >= arg2:\n print('Lower bound greater than upper bound')\n print('Parameter not converted')\n conv_params[:,i] = params[:,i]\n else:\n conv_params[:,i] = params[:,i]*(arg2-arg1) + arg1\n\n # normal distribution\n # paramters are mean and standard deviation\n elif dists[i] == 'norm':\n # checking for valid parameters\n if arg2 <= 0:\n print('Scale must be greater than zero')\n print('Parameter not converted')\n conv_params[:,i] = params[:,i]\n else:\n conv_params[:,i] = sp.stats.norm.ppf(params[:,i],loc=arg1,scale=arg2)\n\n # lognormal distribution (ln-space, not base-10)\n # paramters are ln-space mean and standard deviation\n elif dists[i] == 'lognorm':\n # checking for valid parameters\n if arg2 <= 0:\n print('Scale must be greater than zero')\n print('Parameter not converted')\n conv_params[:,i] = params[:,i]\n else:\n conv_params[:,i] = np.exp(sp.stats.norm.ppf(params[:,i],loc=arg1,scale=arg2))\n\n else:\n print('No valid distribution selected')\n return(conv_params)\n\ndef read_param_file(filename, delimiter=None):\n '''\n Reads a parameter file of format:\n Param1,0,1,Group1,dist1\n Param2,0,1,Group2,dist2\n Param3,0,1,Group3,dist3\n And returns a dictionary containing:\n - names - the names of the parameters\n - bounds - a list of lists of lower and upper bounds\n - num_vars - a scalar indicating the number of variables\n (the length of names)\n - groups - a tuple containing i) a group matrix assigning parameters to\n groups\n ii) a list of unique group names\n - dists - a list of distributions for the problem,\n None if not specified or all uniform\n '''\n names = []\n bounds = []\n group_list = []\n dist_list = []\n num_vars = 0\n fieldnames = ['name', 'lower_bound', 'upper_bound', 'group', 'dist']\n dist_none_count = 0 # used when evaluating if non-uniform distributions are specified\n\n with open(filename, 'rU') as csvfile:\n dialect = csv.Sniffer().sniff(csvfile.read(1024), delimiters=delimiter)\n csvfile.seek(0)\n reader = csv.DictReader(\n csvfile, fieldnames=fieldnames, dialect=dialect)\n for row in reader:\n if row['name'].strip().startswith('#'):\n pass\n else:\n num_vars += 1\n names.append(row['name'])\n bounds.append(\n [float(row['lower_bound']), float(row['upper_bound'])])\n\n # If the fourth column does not contain a group name, use\n # the parameter name\n if row['group'] is None:\n group_list.append(row['name'])\n elif row['group'] is 'NA':\n group_list.append(row['name'])\n else:\n group_list.append(row['group'])\n\n # If the fifth column does not contain a distribution\n # use uniform\n if row['dist'] is None:\n dist_list.append('unif')\n dist_none_count += 1\n else:\n dist_list.append(row['dist'])\n\n group_matrix, group_names = compute_groups_from_parameter_file(\n group_list, num_vars)\n\n # setting group_tuple to zero if no groups are defined\n # or all groups are 'NA'\n if np.all(group_matrix == np.eye(num_vars)):\n group_tuple = None\n elif len(np.unique(group_list)) == 1:\n group_tuple = None\n else:\n group_tuple = (group_matrix, group_names)\n\n # setting dist list to none if all are uniform\n # because non-uniform scaling is not needed\n if dist_none_count == num_vars:\n dist_list = None\n\n return {'names': names, 'bounds': bounds, 'num_vars': num_vars,\n 'groups': group_tuple, 'dists': dist_list}\n\n\ndef compute_groups_from_parameter_file(group_list, num_vars):\n '''\n Computes a k-by-g matrix which notes factor membership of groups\n where:\n k is the number of variables (factors)\n g is the number of groups\n Also returns a g-length list of unique group_names whose positions\n correspond to the order of groups in the k-by-g matrix\n '''\n # Get a unique set of the group names\n unique_group_names = list(OrderedDict.fromkeys(group_list))\n number_of_groups = len(unique_group_names)\n\n indices = dict([(x, i) for (i, x) in enumerate(unique_group_names)])\n\n output = np.zeros((num_vars, number_of_groups), dtype=np.int)\n\n for parameter_row, group_membership in enumerate(group_list):\n group_index = indices[group_membership]\n output[parameter_row, group_index] = 1\n\n return np.matrix(output), unique_group_names\n\n\ndef requires_gurobipy(_has_gurobi):\n '''\n Decorator function which takes a boolean _has_gurobi as an argument.\n Use decorate any functions which require gurobi.\n Raises an import error at runtime if gurobi is not present.\n Note that all runtime errors should be avoided in the working code,\n using brute force options as preference.\n '''\n def _outer_wrapper(wrapped_function):\n def _wrapper(*args, **kwargs):\n if _has_gurobi:\n result = wrapped_function(*args, **kwargs)\n else:\n warn(\"Gurobi not available\", ImportWarning)\n result = None\n return result\n return _wrapper\n return _outer_wrapper\n" } ]
3
karthikgvsk/remo
https://github.com/karthikgvsk/remo
48d8a5ade4dc4bb898b1575d21d9dac39d62ec94
dff7c7a4af24a8238f2d6c4c843bea8bd53cbcdb
b65e63970b014023262738a8c8f019cc1eefcbf2
refs/heads/master
2021-01-20T23:21:17.111358
2013-03-15T15:52:18
2013-03-15T15:52:18
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6430976390838623, "alphanum_fraction": 0.6481481194496155, "avg_line_length": 29.461538314819336, "blob_id": "6e84ff2e56b5589e0b376633f740379a7e697b0d", "content_id": "9c1afa5487470aac254cc0a96f0a03fb9a33abde", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1188, "license_type": "no_license", "max_line_length": 71, "num_lines": 39, "path": "/remo/voting/views.py", "repo_name": "karthikgvsk/remo", "src_encoding": "UTF-8", "text": "from datetime import datetime\n\nfrom django.shortcuts import get_object_or_404, render\n\nfrom remo.base.decorators import permission_check\nfrom remo.voting.models import Poll\n\n\n@permission_check()\ndef list_votings(request):\n \"\"\"List votings view.\"\"\"\n user = request.user\n now = datetime.now()\n polls = Poll.objects.all()\n if not user.groups.filter(name='Admin').exists():\n polls = Poll.objects.filter(valid_groups__in=user.groups.all())\n\n past_polls = polls.filter(end__lt=now)\n current_polls = polls.filter(start__lt=now, end__gt=now)\n future_polls = polls.filter(start__gt=now)\n\n return render(request, 'list_votings.html',\n {'user': user,\n 'past_polls': past_polls,\n 'current_polls': current_polls,\n 'future_polls': future_polls})\n\n\n@permission_check(group='Admin')\ndef edit_voting(request, slug=None):\n \"\"\"Create/Edit voting view.\"\"\"\n return render(request, 'edit_voting.html')\n\n\n@permission_check()\ndef view_voting(request, slug):\n \"\"\"View voting view.\"\"\"\n voting = get_object_or_404(Poll, slug=slug)\n return render(request, 'view_voting.html', {'voting': voting})\n" }, { "alpha_fraction": 0.7177798748016357, "alphanum_fraction": 0.7215427756309509, "avg_line_length": 20.693878173828125, "blob_id": "b5c0b80718c59026762b474af787dff9337b4491", "content_id": "d6d1e061492314628632bcff565a7eae31da2434", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1063, "license_type": "no_license", "max_line_length": 74, "num_lines": 49, "path": "/remo/voting/admin.py", "repo_name": "karthikgvsk/remo", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom models import Poll, PollRange, PollRangeVotes, PollRadio, PollChoices\n\n\n# Poll Range\nclass PollRangeVotesInline(admin.StackedInline):\n \"\"\"Poll Range Votes Inline.\"\"\"\n model = PollRangeVotes\n extra = 2\n\n\nclass PollRangeInline(admin.StackedInline):\n \"\"\"Poll Range Inline.\"\"\"\n model = PollRange\n extra = 1\n\n\n# Radio votes\nclass PollChoicesInline(admin.StackedInline):\n \"\"\"Poll Choices Inline.\"\"\"\n model = PollChoices\n extra = 1\n\n\nclass PollRadioInline(admin.StackedInline):\n \"\"\"Poll Radio Inline.\"\"\"\n model = PollRadio\n extra = 1\n\n\nclass PollRadioAdmin(admin.ModelAdmin):\n inlines = [PollChoicesInline]\n\n\nclass PollRangeAdmin(admin.ModelAdmin):\n inlines = [PollRangeVotesInline]\n\n\nclass PollAdmin(admin.ModelAdmin):\n \"\"\"Voting Admin.\"\"\"\n inlines = [PollRangeInline, PollRadioInline]\n search_fields = ['name']\n date_hierarchy = 'created_on'\n\n\nadmin.site.register(PollRange, PollRangeAdmin)\nadmin.site.register(PollRadio, PollRadioAdmin)\nadmin.site.register(Poll, PollAdmin)\n" }, { "alpha_fraction": 0.6417657136917114, "alphanum_fraction": 0.6511035561561584, "avg_line_length": 30, "blob_id": "f0b869082e242cd991532ce11846b796443e4702", "content_id": "000a2455b0443a9ce284d256660f4ba0de767bd5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2356, "license_type": "no_license", "max_line_length": 76, "num_lines": 76, "path": "/remo/voting/models.py", "repo_name": "karthikgvsk/remo", "src_encoding": "UTF-8", "text": "from django.core.validators import MaxLengthValidator, MinLengthValidator\nfrom django.contrib.auth.models import Group, User\nfrom django.db import models\n\nfrom uuslug import uuslug as slugify\n\n\nclass Poll(models.Model):\n \"\"\"Poll Abstract Model.\"\"\"\n name = models.CharField(max_length=100)\n slug = models.SlugField(blank=True, max_length=100)\n start = models.DateTimeField()\n end = models.DateTimeField()\n valid_groups = models.ForeignKey(Group, related_name='valid_polls')\n created_on = models.DateField(auto_now_add=True)\n description = models.TextField(validators=[MaxLengthValidator(500),\n MinLengthValidator(20)])\n created_by = models.ForeignKey(User, related_name='polls_range_created')\n users_voted = models.ManyToManyField(User, related_name='polls_voted',\n through='Vote')\n\n def __unicode__(self):\n return self.name\n\n class Meta:\n ordering = ['-created_on']\n\n def save(self, *args, **kwargs):\n if not self.pk:\n self.slug = slugify(self.name)\n super(Poll, self).save(*args, **kwargs)\n\n\nclass Vote(models.Model):\n \"\"\"Vote model.\"\"\"\n user = models.ForeignKey(User)\n ranged_poll = models.ForeignKey('Poll')\n date_voted = models.DateField(auto_now_add=True)\n\n def __unicode__(self):\n return '%s %s' % (self.user, self.ranged_poll)\n\n\nclass PollRange(models.Model):\n \"\"\"Poll Model for range voting.\"\"\"\n name = models.CharField(max_length=500, default='')\n poll = models.ForeignKey('Poll')\n\n def __unicode__(self):\n return self.name\n\n\nclass PollRangeVotes(models.Model):\n \"\"\" Poll Range model to count votes.\"\"\"\n votes = models.IntegerField(default=0)\n poll_range = models.ForeignKey('PollRange')\n nominee = models.ForeignKey(User)\n\n\nclass PollRadio(models.Model):\n \"\"\"Poll Model for radio (Boolean) voting.\"\"\"\n title = models.CharField(max_length=500)\n poll = models.ForeignKey('Poll')\n\n def __unicode__(self):\n return self.title\n\n\nclass PollChoices(models.Model):\n \"\"\"Poll Model with available choices for radio voting.\"\"\"\n answer = models.CharField(max_length=500)\n votes = models.IntegerField(default=0)\n radio_poll = models.ForeignKey('PollRadio')\n\n def __unicode__(self):\n return self.answer\n" }, { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 21.75, "blob_id": "83e234478dab8c88bcd3e94e70a6f37d74911803", "content_id": "4901baf56bfb226dc98d25b3d7260529674dddf7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 182, "license_type": "no_license", "max_line_length": 65, "num_lines": 8, "path": "/remo/voting/helpers.py", "repo_name": "karthikgvsk/remo", "src_encoding": "UTF-8", "text": "from jingo import register\n\n\[email protected]\ndef get_users_voted(poll):\n \"\"\"Returns the number of users voted to the specific poll.\"\"\"\n\n return poll.users_voted.all().count()\n" } ]
4
muhammadghazyy/mask_detector
https://github.com/muhammadghazyy/mask_detector
98867a183c5a0788a6e3d69d6b3af1b13342e8e7
38b029df98877bd96637acec27f5c12f8598ca92
838183e0d22174a07898e173dd94fda5ee87a127
refs/heads/main
2023-06-01T11:19:29.861534
2021-06-16T11:46:39
2021-06-16T11:46:39
376,897,000
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5769534111022949, "alphanum_fraction": 0.6400946974754333, "avg_line_length": 27.177778244018555, "blob_id": "178fd57614dcb3f65e13fc6006be616f957497e8", "content_id": "18357a02f338dab7b360efd9758dedbf235c359d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1267, "license_type": "no_license", "max_line_length": 99, "num_lines": 45, "path": "/mask_detector.py", "repo_name": "muhammadghazyy/mask_detector", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\nimport os\nimport tensorflow as tf\n\n# Mask Detection\n\ninput_shape = (128,128,3)\nlabels_dict = {0:'Mask On' , 1:'Mask Off'}\ncolor_dict = {0:(61,235,52) , 1:(0,0,255)}\nmodel = tf.keras.models.load_model('mask_mnv2.h5')\nface_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + \"haarcascade_frontalface_default.xml\")\nsize = 4\n\ncapture = cv2.VideoCapture(1)\n\nwhile True:\n ret,frame = capture.read()\n font = cv2.FONT_HERSHEY_SIMPLEX\n\n #small = cv2.resize(frame ,(0,0),fx=0.5,fy=0.5)\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n face = face_cascade.detectMultiScale(gray,1.3,5)\n\n for (x,y,w,h) in face:\n face_image = frame[y:y+h, x:x+w]\n\n resized = cv2.resize(face_image, (input_shape[0], input_shape[1]))\n reshaped = np.reshape(resized, (1,input_shape[0], input_shape[1],3))\n\n result = model.predict(reshaped)\n\n label = np.argmax(result,axis=1)[0]\n\n cv2.rectangle(frame , (x,y), (x+w,y+h), color_dict[label],2)\n cv2.rectangle(frame,(x,y-40), (x+w,y), color_dict[label],-1)\n cv2.putText(frame,labels_dict[label],(x,y-10),font,1,(255,255,255),2)\n\n cv2.imshow(\"Frame\",frame)\n\n if cv2.waitKey(1) == 27:\n break\n\ncapture.release()\ncv2.destroyAllWindows()" }, { "alpha_fraction": 0.772680938243866, "alphanum_fraction": 0.7747196555137634, "avg_line_length": 74.53845977783203, "blob_id": "3325261a84e00790cf5aacd7cc357ffb426385a7", "content_id": "9a492a07ceb42c0053f7460ebf603dd204251078", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 981, "license_type": "no_license", "max_line_length": 357, "num_lines": 13, "path": "/README.md", "repo_name": "muhammadghazyy/mask_detector", "src_encoding": "UTF-8", "text": "# mask_detector\n\nThis is my first ML project. Wish me luck.\n\nMy aim is to create a simple python script that open live camera then giving a sign wether the mask is being used or not. My plan is to use tensorflow model and opencv to predict and detect faces. Perhaps I could put my work into a website so that people can try what I have done.\n\nSo far I have created\n- Machine Learning model that can detect people wearing their mask or not. I am using EfficientNetB7 mainly for the convolutional part of my model. And I am getting a pretty good accuracy with the model. But the size is too big and the parameters are to many. I also opted to use MobileNetv2 if I needed smaller model. I create the model using google colab.\n- OpenCV script that can detect faces. I am using Haar Cascade method to detect faces.\n- Script that can open the computer's webcam then detect faces + mask on or off. \n\nTo Do List:\n- Put the whole thing into a website. But I still don't know how to do this." } ]
2
Rafael260/TestesSurfmappers
https://github.com/Rafael260/TestesSurfmappers
ce56e1df89ec660effb94d04d97a725ece61a3d9
d80f94eb081b2c395df210a851c07607c936ca63
0059f7ece6be04148b19cb7ca05c4f960bec752d
refs/heads/master
2021-08-23T22:47:09.351948
2017-12-06T23:27:15
2017-12-06T23:27:15
113,251,244
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7347480058670044, "alphanum_fraction": 0.7347480058670044, "avg_line_length": 22.4375, "blob_id": "07246390a231b5b04129d38db002b6e3cb5b531b", "content_id": "d059c6239639ffe72113370ef2efd41e862d2ac7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 377, "license_type": "no_license", "max_line_length": 50, "num_lines": 16, "path": "/LoginPage.py", "repo_name": "Rafael260/TestesSurfmappers", "src_encoding": "UTF-8", "text": "import sys\nsys.path.append('..')\nsys.path.append('...')\nimport utilidades\nfrom BasePage import *\nfrom HomePage import *\n\nclass LoginPage(BasePage):\n\n\tdef __init__(self,browser,baseUrl):\n\t\tsuper(LoginPage,self).__init__(browser, baseUrl)\n\t\tpass\n\n\tdef fazer_login(self,usuario,senha):\n\t\tutilidades.logar(self.browser,usuario,senha)\n\t\treturn HomePage(self.browser,self.baseUrl)\n\t\t" }, { "alpha_fraction": 0.7686567306518555, "alphanum_fraction": 0.7711442708969116, "avg_line_length": 28.77777862548828, "blob_id": "ca8069f07df4db28e0eb375a385a1c9ba29de4f8", "content_id": "093e00fed6c1531c7f94383247c0b7145a9c681e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 804, "license_type": "no_license", "max_line_length": 75, "num_lines": 27, "path": "/HomePage.py", "repo_name": "Rafael260/TestesSurfmappers", "src_encoding": "UTF-8", "text": "from selenium.webdriver.common.by import By\nimport sys\nsys.path.append('..')\nimport utilidades\nfrom BasePage import *\nfrom LoginPage import *\nfrom BuscaSessaoPage import *\nfrom SessionPage import *\n\nclass HomePage(BasePage):\n\n\tdef __init__(self,browser, baseUrl):\n\t\tsuper(HomePage,self).__init__(browser,baseUrl)\n\t\tpass\n\n\tdef abrir_pagina_busca(self):\n\t\tutilidades.clicar(self.browser,By.LINK_TEXT,\"Encontre sua Foto\")\n\t\tutilidades.esperar_elemento(self.browser,By.ID,\"searchbar_search_btn\",30)\n\t\treturn BuscaSessaoPage(self.browser,self.baseUrl)\n\n\tdef abrir_pagina_criar_session(self):\n\t\tutilidades.acessar(self.browser,self.baseUrl+\"/p/schedule\")\n\t\treturn SessionPage(self.browser,self.baseUrl)\n\n\tdef sair_do_sistema(self):\n\t\tutilidades.sair(self.browser)\n\t\treturn LoginPage(self.browser,self.baseUrl)\n" }, { "alpha_fraction": 0.7774447202682495, "alphanum_fraction": 0.7856875061988831, "avg_line_length": 34.1315803527832, "blob_id": "8b385ebfa5a0fbc33fed7dea7f583beead3a8650", "content_id": "a4a96076031cd29a5caa6c1022bb663543ae74ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2669, "license_type": "no_license", "max_line_length": 139, "num_lines": 76, "path": "/utilidades.py", "repo_name": "Rafael260/TestesSurfmappers", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import Select\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.common.exceptions import NoAlertPresentException\nimport os\nimport sys\n\ndef acessar(driver, url):\n\tdriver.get(url)\n\tpass\n\ndef logar(driver, usuario, senha):\n\tclicar(driver,By.LINK_TEXT,\"Entrar\")\n\tesperar_elemento(driver,By.ID,\"btn-login\",30)\n\tdigitar(driver,By.NAME,\"email\",usuario)\n\tdigitar(driver,By.NAME,\"password\",senha)\n\tclicar(driver,By.ID,\"btn-login\")\n\tesperar_elemento(driver,By.LINK_TEXT,\"Vender Fotos\", 60)\n\tpass\n\ndef sair(driver):\n\tacessar(driver,\"http://200.17.142.223:6500/logout\")\n\tpass\n\n\ndef esperar_elemento(driver, maneiraProcura, elemento, tempoLimite):\n\tWebDriverWait(driver, tempoLimite).until(\n EC.presence_of_element_located((maneiraProcura, elemento)))\n\ttime.sleep(2)\n\tpass\n\ndef esperar_elemento_visivel(driver, maneiraProcura, elemento, tempoLimite):\n\tWebDriverWait(driver, tempoLimite).until(\n EC.visibility_of_element_located((By.CLASS_NAME,\"searchbar_option\")))\n\ttime.sleep(1)\n\tpass\n\ndef encontrar_elemento(driver, maneiraProcura, elemento):\n\treturn driver.find_element(maneiraProcura,elemento)\n\ndef encontrar_elementos(driver, elemento, maneiraProcura):\n\treturn driver.find_elements(maneiraProcura,elemento)\n\ndef clicar(driver, maneiraProcura, elemento):\n\telemento = encontrar_elemento(driver, maneiraProcura, elemento)\n\tif (elemento != None):\n\t\telemento.click()\n\tpass\n\ndef digitar(driver, maneiraProcura, elemento, texto):\n\telemento = encontrar_elemento(driver,maneiraProcura,elemento)\n\tif (elemento != None):\n\t\telemento.clear()\n\t\telemento.send_keys(texto)\n\tpass\n\ndef coletar_nome_para_url(nome,separador):\n\treturn nome.lower().replace(\" \", separador)\n\ndef selecionar_opcao_combobox(driver,procuraSelect,elementoCb,selecionado):\n\texpressaoXpath = \"//select[@procuraSelect='elementoCb']/option[text()='selecionado']\"\n\texpressaoXpath = expressaoXpath.replace(\"procuraSelect\",procuraSelect).replace(\"elementoCb\",elementoCb).replace(\"selecionado\",selecionado)\n\tdriver.find_element_by_xpath(expressaoXpath).click()\n\tpass\n\ndef clicar_no_botao(driver,tipoElementoHtml,textoBotao):\n\texpressaoXpath = \"//tipoElementoHtml[contains(text(), 'textoBotao')]\"\n\texpressaoXpath = expressaoXpath.replace(\"tipoElementoHtml\", tipoElementoHtml).replace(\"textoBotao\",textoBotao)\n\tdriver.find_element_by_xpath(expressaoXpath).click()\n\tpass" }, { "alpha_fraction": 0.6699386239051819, "alphanum_fraction": 0.6723926663398743, "avg_line_length": 31.639999389648438, "blob_id": "5bf94fd5f197a8ecd0bc99af8739dd0bdef4542d", "content_id": "1f5c159e09e1b1ee9debe1c7f18802332f402dd9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 815, "license_type": "no_license", "max_line_length": 127, "num_lines": 25, "path": "/BuscaSessaoPage.py", "repo_name": "Rafael260/TestesSurfmappers", "src_encoding": "UTF-8", "text": "import sys\nsys.path.append('..')\nimport utilidades\nfrom BasePage import *\nfrom selenium.webdriver.common.by import By\nimport time\n\nclass BuscaSessaoPage(BasePage):\n\n def __init__(self,browser,baseUrl):\n super(BuscaSessaoPage,self).__init__(browser,baseUrl)\n pass\n\n def buscar_praia(self, estado, nomePraia):\n estadoUrl = utilidades.coletar_nome_para_url(estado,\"-\")\n nomePraiaUrl = utilidades.coletar_nome_para_url(nomePraia,\"_\")\n utilidades.acessar(self.browser,self.baseUrl+\"/album/list?country=brazil&state=\" + estadoUrl + \"&spot=\" + nomePraiaUrl)\n pass\n\n def possui_resultados(self, nomePraia):\n try:\n utilidades.esperar_elemento(self.browser,By.PARTIAL_LINK_TEXT,nomePraia,10)\n return True\n except:\n return False" }, { "alpha_fraction": 0.7204641103744507, "alphanum_fraction": 0.7225738167762756, "avg_line_length": 32.85714340209961, "blob_id": "859907536335bb067608afc121b61b79299d349d", "content_id": "ac899088dbf4c9a9f50a48eea10e20d12817f534", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 948, "license_type": "no_license", "max_line_length": 112, "num_lines": 28, "path": "/SessionPage.py", "repo_name": "Rafael260/TestesSurfmappers", "src_encoding": "UTF-8", "text": "from selenium.webdriver.common.by import By\nimport sys\nsys.path.append('..')\nsys.path.append('...')\nimport utilidades\nfrom BasePage import *\nfrom HomePage import *\n\nclass SessionPage(BasePage):\n\n def __init__(self,browser,baseUrl):\n super(SessionPage,self).__init__(browser, baseUrl)\n pass\n\n def preencher_informacoes_session(self,nomePraia,dia,hora):\n utilidades.selecionar_opcao_combobox(self.browser,\"id\",\"spots\",nomePraia)\n #self.browser.find_element_by_xpath(\"//select[@id='spots']/option[text()='Areia Preta - Natal/RN']\").click()\n utilidades.digitar(self.browser,By.ID,\"entryDate\",dia + \" \" + hora)\n pass\n\n def salvar_session(self):\n utilidades.clicar_no_botao(self.browser,\"button\",\"Salvar\")\n utilidades.esperar_elemento(self.browser,By.CLASS_NAME,\"profile-photo\",20)\n pass\n\n def ir_para_pagina_principal(self):\n utilidades.acessar(self.browser,self.baseUrl)\n return HomePage(self.browser,self.baseUrl)\n" }, { "alpha_fraction": 0.7042801380157471, "alphanum_fraction": 0.7042801380157471, "avg_line_length": 17.428571701049805, "blob_id": "b4035f2887dbdafbf771273e4c64e6c91d126186", "content_id": "049b80412091cc085a289177cadf8fb58dd2acc6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 257, "license_type": "no_license", "max_line_length": 38, "num_lines": 14, "path": "/BasePage.py", "repo_name": "Rafael260/TestesSurfmappers", "src_encoding": "UTF-8", "text": "import sys\nsys.path.append('..')\nsys.path.append('...')\nimport utilidades\n\nclass BasePage:\n\tdef __init__(self, browser, baseUrl):\n\t\tself.browser = browser\n\t\tself.baseUrl = baseUrl\n\t\tpass\n\n\tdef acessar(self,url):\n\t\tutilidades.acessar(self.browser,url)\n\t\tpass" }, { "alpha_fraction": 0.7479935884475708, "alphanum_fraction": 0.7704654932022095, "avg_line_length": 30.200000762939453, "blob_id": "70ac52defc1eea64c63295029a2f00eadc6750ef", "content_id": "8fd506c5a7fdec86fcaa8e5c7605914a409e89aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 624, "license_type": "no_license", "max_line_length": 66, "num_lines": 20, "path": "/buscas.py", "repo_name": "Rafael260/TestesSurfmappers", "src_encoding": "UTF-8", "text": "from selenium.webdriver.common.by import By\nimport time, os, sys\nimport utilidades\nfrom selenium import webdriver\nfrom LoginPage import *\n\ndriver = webdriver.Chrome()\ndriver.implicitly_wait(30)\nbase_url = \"http://200.17.142.223:6500\"\nutilidades.acessar(driver,base_url)\npaginaLogin = LoginPage(driver,base_url)\npaginaPrincipal = paginaLogin.fazer_login(\"[email protected]\",\"rafaelteste\")\npaginaBusca = paginaPrincipal.abrir_pagina_busca()\npaginaBusca.buscar_praia(\"Rio Grande do Norte\",\"Ponta negra\")\nif(paginaBusca.possui_resultados(\"Ponta Negra\")):\n print(\"Busca OK\")\nelse:\n print(\"Busca não retornou resultado!\")\n\ndriver.quit()" }, { "alpha_fraction": 0.6869069933891296, "alphanum_fraction": 0.6869069933891296, "avg_line_length": 29.705883026123047, "blob_id": "836bb8ef589563a1b0c744acb61244ed0921052a", "content_id": "a51b620935d12762d7a554006c41b4c271ab6cdc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 527, "license_type": "no_license", "max_line_length": 77, "num_lines": 17, "path": "/ListaSessoesPage.py", "repo_name": "Rafael260/TestesSurfmappers", "src_encoding": "UTF-8", "text": "from selenium.webdriver.common.by import By\nimport sys\nsys.path.append('..')\nsys.path.append('...')\nimport utilidades\nfrom BasePage import *\n\nclass ListaSessoesPage(BasePage):\n\n def __init__(self,browser,baseUrl):\n super(ListaSessoesPage,self).__init__(browser, baseUrl)\n pass\n\n def possui_sessao(self,nomePraia,dia,hora):\n linhaEsperada = \"<td>dia hora</td>\"\n linhaEsperada = linhaEsperada.replace(\"dia\",dia).replace(\"hora\",hora)\n return linhaEsperada in self.browser.page_source\n\n " }, { "alpha_fraction": 0.7291666865348816, "alphanum_fraction": 0.7763158082962036, "avg_line_length": 34.11538314819336, "blob_id": "95a9eaa8148bd2abe60964cc5dc94f5a18fd1433", "content_id": "23a37e2b2afd630048fb0df54dc0b719acb904e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 915, "license_type": "no_license", "max_line_length": 89, "num_lines": 26, "path": "/criarSessao.py", "repo_name": "Rafael260/TestesSurfmappers", "src_encoding": "UTF-8", "text": "from selenium.webdriver.common.by import By\nimport time, os, sys\nimport utilidades\nfrom selenium import webdriver\nfrom LoginPage import *\nfrom ListaSessoesPage import *\n\ndriver = webdriver.Chrome()\ndriver.implicitly_wait(30)\nbase_url = \"http://200.17.142.223:6500\"\nutilidades.acessar(driver,base_url)\npaginaLogin = LoginPage(driver,base_url)\npaginaPrincipal = paginaLogin.fazer_login(\"[email protected]\",\"rafaelteste\")\npaginaSessao = paginaPrincipal.abrir_pagina_criar_session()\npaginaSessao.preencher_informacoes_session(\"Areia Preta - Natal/RN\",\"15/12/2017\",\"18:30\")\npaginaSessao.salvar_session()\ntime.sleep(2)\nutilidades.acessar(driver,base_url+\"/p/sheduled_sessions/\")\npaginaListaSessoes = ListaSessoesPage(driver,base_url)\nif(paginaListaSessoes.possui_sessao(\"Areia Preta - Natal/RN\",\"15/12/2017\",\"18:30\")):\n print(\"Sessão criada e encontrada\")\nelse:\n print(\"Sessão não encontrada\")\n\ntime.sleep(5)\ndriver.quit()" } ]
9
misterned/bloc2
https://github.com/misterned/bloc2
564b0d240d4ba58004f4338edc65f31504caa6a8
b84eaf34d5f813856c70ecc1ab71132c1f233559
5ac0ee7890c3cfa702cf680bbcecd33d9b468b71
refs/heads/master
2020-06-05T01:16:35.849986
2019-06-20T04:22:25
2019-06-20T04:22:25
192,263,270
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7397260069847107, "alphanum_fraction": 0.767123281955719, "avg_line_length": 23.33333396911621, "blob_id": "4791f3f02f6622472b88e62325ac1d004837c540", "content_id": "50d51cdbb979aceabc498996ad01f2157bab8796", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 146, "license_type": "no_license", "max_line_length": 53, "num_lines": 6, "path": "/README.md", "repo_name": "misterned/bloc2", "src_encoding": "UTF-8", "text": "# bloc2\nDocuments pour le DU ESNSI bloc 2\n\n## Pour travailler sur les notebook via Binder \n\nhttps://mybinder.org/v2/gh/misterned/bloc2.git/master\n" }, { "alpha_fraction": 0.5279411673545837, "alphanum_fraction": 0.574999988079071, "avg_line_length": 20.25, "blob_id": "f388fac082268911cb996cd24f00cb002cbcc1b4", "content_id": "aa9e95bd271bd6c29a62a4f301cd19183b049b65", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 689, "license_type": "no_license", "max_line_length": 72, "num_lines": 32, "path": "/corrections/exo_somme_liste.py", "repo_name": "misterned/bloc2", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom nbautoeval.exercise_function import ExerciseFunction\nfrom nbautoeval.args import Args\n\n\n# @BEG@ name=somme_liste\ndef somme_liste(T, S):\n '''partant d’une liste T, on détermine si la somme des éléments de T\nest ou non supérieure à une valeur entière donnée S.'''\n N = len(T)\n i , sss , sp = 0 , False , 0\n while not(i == N):\n sss = sss or (sp + T[i]>S)\n sp = sp + T[i]\n i += 1\n return sss\n# @END@\n\n\n\ninputs_somme_liste = [\n Args([10, 3, 5],20),\n Args([10, 13, 5],20),\n Args([10, 3, 5, 4],20),\n Args([10, 3, 5, 1, 0],23),\n \n]\n\n\n\nexo_somme_liste = ExerciseFunction(\n somme_liste, inputs_somme_liste)\n" }, { "alpha_fraction": 0.6598984599113464, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 20.10714340209961, "blob_id": "2741ae4e8d24e002358e0141ce65339ab7fe55a9", "content_id": "c450df757c32b1a48057cb6ef297cfcc61666f2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 593, "license_type": "no_license", "max_line_length": 68, "num_lines": 28, "path": "/corrections/exo_longueur_chaine.py", "repo_name": "misterned/bloc2", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom nbautoeval.exercise_function import ExerciseFunction\nfrom nbautoeval.args import Args\n\n\n# @BEG@ name=longueur_chaine\ndef longueur_chaine(ch):\n '''ch est la chaine de caractères dont on cherche la longueur'''\n if not ch :\n return 0\n else :\n return 1+ longueur_chaine(ch[1:])\n# @END@\n\n\n\ninputs_longueur_chaine = [\n Args(\"Bonjour\"),\n Args(\"Bonjour les collègues\"),\n Args(\"anticonstitutionnellement\"),\n Args(\"le chocolat c'est bon !\"),\n \n]\n\n\n\nexo_longueur_chaine = ExerciseFunction(\n longueur_chaine, inputs_longueur_chaine)\n" }, { "alpha_fraction": 0.5410072207450867, "alphanum_fraction": 0.5784172415733337, "avg_line_length": 21.419355392456055, "blob_id": "7b30850e3bb3d5c3bee8e6d8af308663b69f4981", "content_id": "90d90d0917e37f96d88c5051ab85689ad3e5c294", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 699, "license_type": "no_license", "max_line_length": 77, "num_lines": 31, "path": "/corrections/exo_tri_selection.py", "repo_name": "misterned/bloc2", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom nbautoeval.exercise_function import ExerciseFunction\nfrom nbautoeval.args import Args\n\n\n# @BEG@ name=tri_selection\ndef tri_selection(list):\n '''la liste list est triée à l'aide de la méthode du tri par sélection'''\n for i in range(len(list)):\n mini = i\n for j in range(i, len(list)):\n if list[j] < list[mini]:\n mini = j\n list[i], list[mini] = list[mini], list[i]\n return list\n# @END@\n\n\n\ninputs_tri_selection = [\n Args([1, 10, 3, 5]),\n Args([10, 2, 8, 1, 0]),\n Args([5, 1, 3]),\n Args([15, 10, 14, 12, 8, 21]),\n \n]\n\n\n\nexo_tri_selection = ExerciseFunction(\n tri_selection, inputs_tri_selection)\n" }, { "alpha_fraction": 0.5119549632072449, "alphanum_fraction": 0.5682137608528137, "avg_line_length": 20.545454025268555, "blob_id": "12c3100bb2f0dfd663d75c7b2e762f05a191a996", "content_id": "ea796cddaa98bc7b3f95977e760b6bb4cb882ea5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 720, "license_type": "no_license", "max_line_length": 72, "num_lines": 33, "path": "/corrections/exo_somme_indice.py", "repo_name": "misterned/bloc2", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom nbautoeval.exercise_function import ExerciseFunction\nfrom nbautoeval.args import Args\n\n\n# @BEG@ name=somme_indice\ndef somme_indice(T, S):\n '''partant d’une liste T, on détermine si la somme des éléments de T\nest ou non supérieure à une valeur entière donnée S.'''\n N = len(T)\n i , sp = 0 , 0\n while not((i == N)or (sp + T[i]>S)):\n sp = sp + T[i]\n i += 1\n sss = not(i == N)\n return sss, i\n# @END@\n\n\n\ninputs_somme_indice = [\n Args([10, 3, 5],20),\n Args([10, 13, 5],20),\n Args([10, 3, 5, 4],20),\n Args([10, 3, 5, 1, 0],23),\n Args([10, 3, 5, 1, 0],12),\n \n]\n\n\n\nexo_somme_indice = ExerciseFunction(\n somme_indice, inputs_somme_indice)\n" }, { "alpha_fraction": 0.6036363840103149, "alphanum_fraction": 0.614545464515686, "avg_line_length": 17.965517044067383, "blob_id": "845d861e84699146bd4dd948ca4ad5cd5d362b88", "content_id": "a714eee41694a8eea35ab87d3f7b3ab7092efb15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 551, "license_type": "no_license", "max_line_length": 57, "num_lines": 29, "path": "/corrections/exo_palindrome.py", "repo_name": "misterned/bloc2", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom nbautoeval.exercise_function import ExerciseFunction\nfrom nbautoeval.args import Args\n\n\n# @BEG@ name=palindrome\ndef palindrome(ch):\n '''on vérifie si la chaine ch est un palindrome'''\n if len( ch )==1:\n return True\n if ch [0]== ch [ -1]:\n return palindrome ( ch [1: len ( ch ) -1])\n return False\n# @END@\n\n\n\ninputs_palindrome = [\n Args('kayak'),\n Args('bonjour'),\n Args('laval'),\n Args('bref ici ferb'),\n \n]\n\n\n\nexo_palindrome = ExerciseFunction(\n palindrome, inputs_palindrome)\n" }, { "alpha_fraction": 0.5306427478790283, "alphanum_fraction": 0.5769805908203125, "avg_line_length": 19.90625, "blob_id": "cdf0cc43f51d3ffa3eb6442ce0005f12df3afafc", "content_id": "710746eaffb335f671f22f5702692d59fda1c362", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 672, "license_type": "no_license", "max_line_length": 77, "num_lines": 32, "path": "/corrections/exo_tri_insertion.py", "repo_name": "misterned/bloc2", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom nbautoeval.exercise_function import ExerciseFunction\nfrom nbautoeval.args import Args\n\n\n# @BEG@ name=tri_insertion\ndef tri_insertion(list):\n '''la liste list est triée à l'aide de la méthode du tri par insertion'''\n for k in range(1,len(list)):\n temp=list[k]\n j=k\n while j>0 and temp<list[j-1]:\n list[j]=list[j-1]\n j-=1\n list[j]=temp\n return list\n# @END@\n\n\n\ninputs_tri_insertion = [\n Args([1, 10, 3, 5]),\n Args([10, 2, 8, 1, 0]),\n Args([5, 1, 3]),\n Args([15, 10, 14, 12, 8, 21]),\n \n]\n\n\n\nexo_tri_insertion = ExerciseFunction(\n tri_insertion, inputs_tri_insertion)\n" } ]
7
tmedeirosb/django_essencial
https://github.com/tmedeirosb/django_essencial
05c13fc8f1ee332ea9b004c41b1714ebf2661a52
85908f286339ef65a49948bffa83729bc9f580d0
8dcc6236e3889fae3891ed940c72717ddb997c2b
refs/heads/master
2021-01-10T02:38:36.992221
2016-02-16T10:22:19
2016-02-16T10:22:19
51,090,607
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7108433842658997, "alphanum_fraction": 0.7349397540092468, "avg_line_length": 15.600000381469727, "blob_id": "b5d753b53c86dbb7e28fdcdd3378aae6ecac8015", "content_id": "b7abf5cccf80d77100099d0e28532812fc85d89f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 83, "license_type": "no_license", "max_line_length": 33, "num_lines": 5, "path": "/django_essencial/cap3/apps.py", "repo_name": "tmedeirosb/django_essencial", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass Cap3Config(AppConfig):\n name = 'cap3'\n" }, { "alpha_fraction": 0.6358024477958679, "alphanum_fraction": 0.6512345671653748, "avg_line_length": 21.627906799316406, "blob_id": "bee75d9f930d417c6018788af768d0fff485447c", "content_id": "ef56f1c776a63e9f759596035768e503b01deb9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 976, "license_type": "no_license", "max_line_length": 66, "num_lines": 43, "path": "/django_essencial/cap3/views.py", "repo_name": "tmedeirosb/django_essencial", "src_encoding": "UTF-8", "text": "import os\n\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.conf import settings\nfrom django.http import Http404\nfrom django.template import Template\nfrom django.utils._os import safe_join\n\n# Create your views here.\n\ndef index(request):\n dados = {'nome': 'Thiago Medeiros Barros'}\n response = render(request,'index.html', dados)\n\n return response\n\n\ndef get_page_or_404(name):\n try:\n file_path = safe_join(settings.SITE_PAGES_DIRECTORY, name)\n except ValueError:\n raise Http404('Página não encontrada!')\n else:\n if not os.path.exists(file_path):\n raise Http404('Página não encontrada!')\n\n with open(file_path, 'r') as f:\n page = Template(f.read())\n\n return page\n\n\ndef page(request, slug='index'):\n file_name = '{}.html'.format(slug)\n page = get_page_or_404(file_name)\n\n context = {\n 'slug': slug,\n 'page': page,\n }\n\n return render(request, 'page.html', context)" }, { "alpha_fraction": 0.6770981550216675, "alphanum_fraction": 0.6842105388641357, "avg_line_length": 27, "blob_id": "1aa697615daad91b2e5e028b3f2d5824140a372c", "content_id": "f02ace3130585438047e7f395ec5b0340bba2aea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 704, "license_type": "no_license", "max_line_length": 78, "num_lines": 25, "path": "/django_essencial/cap1/views.py", "repo_name": "tmedeirosb/django_essencial", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.core.urlresolvers import reverse\nfrom . import forms\n\n\n# Create your views here.\ndef index(request):\n example = reverse('placeholder', kwargs={'width': 50, 'height': 50})\n\n dados = {'nome': 'thiago medeiros', 'example': request.build_absolute_uri(example)}\n\n response = render(request,'cap1/index.html', dados)\n\n return response\n\n\ndef placeholder(request, width, height):\n form = forms.ImageForm({'height': height, 'width': width})\n if form.is_valid():\n image = form.generate()\n\n return HttpResponse(image, content_type='image/png')\n else:\n return HttpResponse('tamanho inválido!')\n\n\n\n" } ]
3
chickin/datacheck
https://github.com/chickin/datacheck
47215cb4003157f3424f5bb7b8b0f04d73748f6d
e96cf514ea0e0600c88e15d5f8d78b435714ce86
84c6c42a699eb35c3ab6e641988bfcd6da7675b8
refs/heads/main
2023-07-15T10:39:19.883598
2021-09-03T05:16:30
2021-09-03T05:16:30
402,651,552
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6045235395431519, "alphanum_fraction": 0.6272154450416565, "avg_line_length": 30.507009506225586, "blob_id": "14abd6a661fb389a0838c63879b35bbaa8e5de11", "content_id": "e2ff048c31c328bdc90cd6bf20a1dc5b8d43dbe4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13485, "license_type": "no_license", "max_line_length": 126, "num_lines": 428, "path": "/datacheck.py", "repo_name": "chickin/datacheck", "src_encoding": "UTF-8", "text": "###############################################################################\n# ParselTongue datacheck.py\n'''\nCheck SPIRALS correlated data.\nv0.1 2020-08-25\nv0.2 2020-08-30\nv0.3 2020-08-31\nv0.4 2020-09-01\nAIPS part is fine. Needs still:\n- make and put plot files in correct subfolder\n- run from corr_scripts/.\n- help file and comments in code\n- put on git\n'''\n###############################################################################\n\n# Call in some python and parseltongue packages.\nfrom AIPS import AIPS\nfrom AIPSTask import AIPSTask, AIPSList\nfrom AIPSData import AIPSUVData, AIPSImage\nimport os, sys, subprocess, re, glob, argparse\n\n# Help file and input arguments.\nparser = argparse.ArgumentParser(add_help=True, description = '''\n A description of what the script does.\n ''')\nparser.add_argument('exper', help='experiment code in lower case, e.g. s001a')\nparser.add_argument('-l', '--load', help='fitld data into AIPS and list scans (fitld)', action='store_true')\nparser.add_argument('-c', '--calibrate', help='fringe fit data and find maser peak (fring)', action='store_true')\nparser.add_argument('-p', '--plot', help='make some plots of spectra (possm)', action='store_true')\nparser.add_argument('-d', '--delete', help='delete data in AIPS catalog (zap)', action='store_true')\nargs = parser.parse_args()\n\n###############################################################################\n\n# Get experiment code from positional argument.\nexperiment = args.exper\n\n# Define correlation folder and data archive paths.\npath_correlations = '/home/observer/correlations2/'\npath_archive = '/mnt/parallax/spirals/'\n\n# Set AIPS ID based on experiment code. s=28 (extended hex),source#,epoch#\nif len(experiment) == 5:\n AIPS.userno=int(str(int(experiment[0],36))+experiment[2:4]+str(ord(experiment[4])-(ord('a')-1)))\nelse:\n print('\\nExperiment code should be in s001a format. See --help. \\n')\n sys.exit(0)\n\n# Check if geo fits exists and define path.\nif os.path.exists(path_correlations+experiment+'/geo/'+experiment+'-geo.fits'):\n path_geo = path_correlations+experiment+'/geo/'\nelif os.path.exists(path_correlations+experiment+'/'+experiment+'-geo.fits'):\n path_geo = path_correlations+experiment+'/'\nelif os.path.exists(path_archive+experiment+'/'+experiment+'-geo.fits'):\n path_geo = path_archive+experiment+'/'\nelse:\n print \"\\nCannot find, experiment\"+\"-geo.fits in correlation or archive (parallax) folders. See --help.\\n\"\n\n# Check if cont fits exists and define path.\nif os.path.exists(path_correlations+experiment+'/cont/'+experiment+'-cont.fits'):\n path_cont = path_correlations+experiment+'/cont/'\nelif os.path.exists(path_correlations+experiment+'/'+experiment+'-cont.fits'):\n path_cont = path_correlations+experiment+'/'\nelif os.path.exists(path_archive+experiment+'/'+experiment+'-cont.fits'):\n path_cont = path_archive+experiment+'/'\nelse:\n print \"\\nCannot find, experiment\"+\"-cont.fits in correlation or archive (parallax) folders. See --help.\\n\"\n\n# Check if line fits exists and define path.\nif os.path.exists(path_correlations+experiment+'/line/'+experiment+'-line.fits'):\n path_line = path_correlations+experiment+'/line/'\nelif os.path.exists(path_correlations+experiment+'/'+experiment+'-line.fits'):\n path_line = path_correlations+experiment+'/'\nelif os.path.exists(path_archive+experiment+'/'+experiment+'-line.fits'):\n path_line = path_archive+experiment+'/'\nelse:\n print \"\\nCannot find, experiment\"+\"-line.fits in correlation or archive (parallax) folders. See --help.\\n\"\n sys.exit(0)\n\n# Define data tags for AIPS.\nfits_geo = path_geo + experiment + '-geo.fits'\nfits_cont = path_cont + experiment + '-cont.fits'\nfits_line = path_line + experiment + '-line.fits'\nname_geo = experiment.upper() + '.G'\nname_cont = experiment.upper() + '.C'\nname_line = experiment.upper() + '.L'\ndata_geo = AIPSUVData(name_geo,'UVDATA',1,1)\ndata_cont = AIPSUVData(name_cont,'UVDATA',1,1)\ndata_line = AIPSUVData(name_line,'UVDATA',1,1)\n\n# Make output folder for datacheck files in experiment correlation folder.\nif os.path.exists(path_correlations+experiment+'/datacheck/'):\n path_datacheck = path_correlations+experiment+'/datacheck/'\nelse:\n os.mkdir(path_correlations+experiment+'/datacheck/')\n path_datacheck = path_correlations+experiment+'/datacheck/'\n\n# Remove existing auxiliary files (scans lists, source tables, spectra, AIPS plots).\nfor item in glob.glob(path_datacheck+'*.txt'):\n os.remove(item)\nfor item in glob.glob(path_datacheck+'*.ps'):\n os.remove(item)\n\n###############################################################################\n\n# (--load) Load data into AIPS and make some auxiliary files.\nif args.load == True or (args.load == False and args.calibrate == False and args.plot == False and args.delete == False):\n cowsload\n\n # Delete esixting data in AIPS catalog.\n if data_geo.exists():\n data_geo.clrstat()\n data_geo.zap()\n if data_cont.exists():\n data_cont.clrstat()\n data_cont.zap()\n if data_line.exists():\n data_line.clrstat()\n data_line.zap()\n\n # Fitld geo, cont, line data.\n fitld = AIPSTask('FITLD')\n fitld.datain = fits_geo\n fitld.outname = name_geo\n fitld()\n fitld.datain = fits_cont\n fitld.outname = name_cont\n fitld()\n fitld.datain = fits_line\n fitld.outname = name_line\n fitld()\n\n # Make scan lists for geo, cont, line data.\n listr = AIPSTask('LISTR')\n listr.optype = 'SCAN'\n listr.indata = data_geo\n listr.outprint = './listr-geo.txt'\n listr()\n listr.indata = data_cont\n listr.outprint = './listr-cont.txt'\n listr()\n listr.indata = data_line\n listr.outprint = './listr-line.txt'\n listr()\n\n # Print SU source table of cont/line data.\n prtab = AIPSTask('PRTAB')\n prtab.indata = data_cont\n prtab.inext = 'SU'\n prtab.outprint = './SU.txt'\n prtab()\n\n\n# A few FRINGs and finding the maser\n\nif args.calibrate == True or (args.load == False and args.calibrate == False and args.plot == False and args.delete == False):\n cowsfring\n\n maser = subprocess.check_output(['awk', '/G[0-9]/ {print $3}', 'SU.txt']).split()\n \n fringe_finder = subprocess.check_output(['awk', '/F[0-9]/ {print $3}', 'SU.txt']).split()\n f1 = subprocess.Popen(['awk', '{print $2, $3}', 'SU.txt'], stdout=subprocess.PIPE)\n f2 = subprocess.Popen(['awk', '$1 == \"1\" {print $2}'], stdin=f1.stdout, stdout=subprocess.PIPE)\n f1.stdout.close()\n f3,err = f2.communicate()\n fringe_check = f3.split()\n calibrators = fringe_check + fringe_finder\n\n data_geo.zap_table('SN',-1)\n data_cont.zap_table('SN',-1)\n data_line.zap_table('SN',-1)\n\n fring = AIPSTask('FRING')\n fring.aparm = AIPSList([3,0,0,0,0,2,3,0,0,0])\n fring.solint = -1\n fring.indata = data_geo\n fring()\n fring.indata = data_cont\n fring.calsour = AIPSList(calibrators)\n fring()\n fring.indata = data_line\n fring.calsour = AIPSList(calibrators)\n fring.dparm[8] = 5\n fring()\n\n while data_geo.table_highver('AIPS CL') > 1:\n data_geo.zap_table('AIPS CL', 0)\n while data_cont.table_highver('AIPS CL') > 1:\n data_cont.zap_table('AIPS CL', 0)\n while data_line.table_highver('AIPS CL') > 1:\n data_line.zap_table('AIPS CL', 0)\n\n clcal = AIPSTask('CLCAL')\n clcal.snver = 1\n clcal.gainver = 1\n clcal.gainuse = 2\n clcal.indata = data_geo\n clcal()\n clcal.indata = data_cont\n clcal()\n clcal.indata = data_line\n clcal()\n\n# Find and fring maser peak\n possm = AIPSTask('POSSM')\n possm.indata = data_line\n possm.solint = 0\n possm.stokes = 'I'\n possm.sources = AIPSList(maser)\n possm.nplots = 0\n possm.docal = -1\n possm.aparm[1] = -1\n possm.outtext = './maser-spectrum.txt'\n possm()\n\n maser_peak = subprocess.check_output(\"sort -k6 -n maser-spectrum.txt | tail -n 1\", shell=True).split()\n maser_channel = int(maser_peak[0])\n print(\"Maser peak channel: \", maser_channel)\n\n fring = AIPSTask('FRING')\n fring.indata = data_line\n fring.calsour = AIPSList(maser)\n fring.aparm = AIPSList([3,0,3,0,0,2,3,0,0,0])\n fring.dparm = AIPSList([3,-1,0])\n fring.solint = -1\n fring.docal = 1\n fring.gainuse = 2\n fring.bchan = maser_channel\n fring.echan = maser_channel\n fring()\n\n clcal = AIPSTask('CLCAL')\n clcal.indata = data_line\n clcal.snver = 2\n clcal.gainver = 2\n clcal.gainuse = 3\n clcal.sources = AIPSList(maser)\n clcal()\n\n\n# Plotting some stuff\nif args.plot == True or (args.load == False and args.calibrate == False and args.plot == False and args.delete == False):\n cowsplot\n\n data_geo.zap_table('PL',-1)\n data_cont.zap_table('PL',-1)\n data_line.zap_table('PL',-1)\n\n# SN tables from fring\n snplt = AIPSTask('SNPLT')\n snplt.inext = 'SN'\n snplt.inver = 1\n snplt.opcode = 'ALSI'\n snplt.do3co = 1\n snplt.nplots = 4\n snplt.indata = data_geo\n snplt.optype = 'DELA'\n snplt.pixrange = AIPSList([-200e-9,200e-9])\n snplt()\n snplt.indata = data_cont\n snplt.optype = 'DELA'\n snplt.pixrange = AIPSList([-200e-9,200e-9])\n snplt()\n snplt.indata = data_line\n snplt.inver = 2\n snplt.optype = 'PHAS'\n snplt.pixrange = AIPSList([-180,180])\n snplt()\n\n lwpla = AIPSTask('LWPLA')\n lwpla.plver = 1\n lwpla.lpen = 1\n lwpla.dparm = AIPSList([0,1,0,0,0,4,41,8,0])\n lwpla.indata = data_geo\n lwpla.inver = data_geo.table_highver('PL')\n lwpla.outfile = './fringSN-geo.ps'\n lwpla()\n lwpla.indata = data_cont\n lwpla.inver = data_cont.table_highver('PL')\n lwpla.outfile = './fringSN-cont.ps'\n lwpla()\n lwpla.indata = data_line\n lwpla.inver = data_line.table_highver('PL')\n lwpla.outfile = './fringSN-line.ps'\n lwpla()\n\n data_geo.zap_table('PL',-1)\n data_cont.zap_table('PL',-1)\n data_line.zap_table('PL',-1)\n\n# Raw spectra for each baseline\n possm = AIPSTask('POSSM')\n possm.docal = 0\n possm.solint = -1\n possm.nplots = 6\n possm.aparm = AIPSList([0,1,0,0,-180,180,0,0,3,0])\n possm.indata = data_geo\n possm()\n possm.indata = data_cont\n possm.sources = AIPSList(calibrators)\n possm()\n possm.indata = data_line\n possm.sources = AIPSList(maser)\n possm.codetype = 'AMP'\n possm.aparm[1] = -1\n possm.aparm[8] = 0\n possm.solint = 0\n possm()\n possm.nplots = 4\n possm.aparm[8] = 1\n possm.stokes = 'HALF'\n possm()\n\n lwpla = AIPSTask('LWPLA')\n lwpla.plver = 1\n lwpla.lpen = 1\n lwpla.dparm = AIPSList([0,1,0,0,0,4,41,8,0])\n lwpla.indata = data_geo\n lwpla.inver = data_geo.table_highver('PL')\n lwpla.outfile = './spectrumRAW-geo.ps'\n lwpla()\n lwpla.indata = data_cont\n lwpla.inver = data_cont.table_highver('PL')\n lwpla.outfile = './spectrumRAW-cont.ps'\n lwpla()\n lwpla.indata = data_line\n lwpla.inver = data_line.table_highver('PL')\n lwpla.outfile = './spectrumRAW-line.ps'\n lwpla()\n\n data_geo.zap_table('PL',-1)\n data_cont.zap_table('PL',-1)\n data_line.zap_table('PL',-1)\n\n# Calibrated spectra and superarray\n possm = AIPSTask('POSSM')\n possm.docal = 1\n possm.solint = -1\n possm.nplots = 6\n possm.aparm = AIPSList([0,1,0,0,-180,180,0,0,3,0])\n possm.stokes = 'HALF'\n possm.indata = data_geo\n possm.gainuse = 2\n possm()\n possm.indata = data_cont\n possm.gainuse = 2\n possm.sources = AIPSList(calibrators)\n possm()\n possm.indata = data_line\n possm.sources = AIPSList(maser)\n possm.aparm[1] = 0\n possm.aparm[8] = 0\n possm.stokes = 'HALF'\n possm.solint = 0\n possm.gainuse = 3\n possm.bchan = maser_channel-100\n possm.echan = maser_channel+100\n possm()\n possm.stokes = 'I'\n possm.aparm[1] = 0\n possm.nplots = 0\n possm()\n possm.aparm[1] = -1\n possm()\n\n lwpla = AIPSTask('LWPLA')\n lwpla.plver = 1\n lwpla.lpen = 1\n lwpla.dparm = AIPSList([0,1,0,0,0,4,41,8,0])\n lwpla.indata = data_geo\n lwpla.inver = data_geo.table_highver('PL')\n lwpla.outfile = './spectrumCAL-geo.ps'\n lwpla()\n lwpla.indata = data_cont\n lwpla.inver = data_cont.table_highver('PL')\n lwpla.outfile = './spectrumCAL-cont.ps'\n lwpla()\n lwpla.indata = data_line\n lwpla.inver = data_line.table_highver('PL')\n lwpla.outfile = './spectrumCAL-line.ps'\n lwpla()\n\n data_geo.zap_table('PL',-1)\n data_cont.zap_table('PL',-1)\n data_line.zap_table('PL',-1)\n\n# VPLOT on maser channel\n vplot = AIPSTask('VPLOT')\n vplot.indata = data_line\n vplot.sources = AIPSList(maser)\n vplot.bchan = maser_channel\n vplot.echan = maser_channel\n vplot.bparm = AIPSList([0,2,1,0,0,-180,180,-180,180,0])\n vplot.nplots = 6\n vplot.docal = 0\n vplot()\n vplot.docal = 1\n vplot.gainuse = 3\n vplot()\n\n lwpla = AIPSTask('LWPLA')\n lwpla.indata = data_line\n lwpla.plver = 1\n lwpla.lpen = 1\n lwpla.dparm = AIPSList([0,1,0,0,0,4,41,8,0])\n lwpla.inver = data_line.table_highver('PL')\n lwpla.outfile = './maserpeakVPLOT.ps'\n lwpla()\n\n data_line.zap_table('PL',-1)\n\n # Clean up AIPS catalog\nif args.delete == True:\n\n if data_geo.exists():\n data_geo.clrstat()\n data_geo.zap()\n if data_cont.exists():\n data_cont.clrstat()\n data_cont.zap()\n if data_line.exists():\n data_line.clrstat()\n data_line.zap()\n\n print \"\\nData of\", experiment, \"deleted from AIPS user number:\", AIPS.userno\n\nprint(\"\\n######### \\nFinished. See --help for details. \\n######### \\n\")\n" } ]
1
d-snyder/statdiff
https://github.com/d-snyder/statdiff
593fe88efc3aff6e97623a84a3e65426f29e0bfb
1b240bc606e8d306c87a6662cae424beb36673e1
681d2048d5b560b3101d8ef5b6c948d5211ff96f
refs/heads/master
2016-09-06T19:25:49.084815
2012-06-12T01:14:21
2012-06-12T01:14:21
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.563459038734436, "alphanum_fraction": 0.56814044713974, "avg_line_length": 38.03045654296875, "blob_id": "e00b0485b88f068175ebf958efcb3b5e30670b74", "content_id": "12390dc6442a064630fb6f67baf9f74ff8408401", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7690, "license_type": "no_license", "max_line_length": 129, "num_lines": 197, "path": "/statdiff.py", "repo_name": "d-snyder/statdiff", "src_encoding": "UTF-8", "text": "#!python\n\nimport sys, re, os, pipes\nfrom optparse import OptionParser\nfrom datetime import datetime\n\n#Suppress md5 deprecation warning.\nimport warnings\nwith warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n try:\n import paramiko\n except Exception, e:\n paramiko = None\n\nclass StatDiff():\n _STAT_FORMAT = '%A %U %G %s %X %Y %Z %n'\n _STAT_REGEX = '(\\S+)\\s(\\S+)\\s(\\S+)\\s(\\S+)\\s(\\S+)\\s(\\S+)\\s(.+)'\n _STAT_CMD = \"find %s -mindepth 1 -maxdepth 1 -exec stat --format=\\'%s\\' {} \\\\;\"\n _p = re.compile(_STAT_REGEX)\n _USAGE = 'usage: %prog [options] [host:]path1 [host:]path2'\n\n subject_left = None\n subject_right = None\n def __init__(self,argv):\n parser = OptionParser(self._USAGE)\n parser.add_option('-v','--verbose',action=\"store_true\", dest=\"verbose\", default=False, help=\"Turns on additional output\")\n parser.add_option('-l','--long',action=\"store_true\", dest=\"long\", default=False, help=\"Turns on long output mode.\")\n parser.add_option('-1','--short',action=\"store_true\", dest=\"short\", default=False, help=\"Turns on short output mode.\")\n parser.add_option('-a','--all',action=\"store_true\", dest=\"all\", default=False, help=\"Includes normally hidden files\")\n parser.add_option('--rights',action=\"store_true\", dest=\"rights\", default=False, help=\"Compare access rights of files.\")\n parser.add_option('--owner',action=\"store_true\", dest=\"owner\", default=False, help=\"Compare owner name of files\")\n parser.add_option('--group',action=\"store_true\", dest=\"group\", default=False, help=\"Compare group name of files\")\n parser.add_option('--atime',action=\"store_true\", dest=\"atime\", default=False, help=\"Compare access time of files\")\n parser.add_option('--mtime',action=\"store_true\", dest=\"mtime\", default=False, help=\"Compare modify time of files\")\n parser.add_option('--size',action=\"store_true\", dest=\"size\", default=False, help=\"Compare size of files\")\n (options,args) = parser.parse_args(argv)\n self.options = options\n if(len(args) < 3):\n raise Exception('You must provide at least two subjects to compare')\n self.subject_left = args[1]\n self.subject_right = args[2]\n\n self.ckeys = set()\n if(options.rights): self.ckeys.add('rights')\n if(options.owner): self.ckeys.add('owner')\n if(options.group): self.ckeys.add('group')\n if(options.atime): self.ckeys.add('atime')\n if(options.mtime): self.ckeys.add('mtime')\n if(options.size): self.ckeys.add('size')\n if len(self.ckeys) == 0: self.ckeys = None\n\n def _parse_statlines(self,statlines):\n stats = dict()\n for line in statlines:\n stat = self._parse_statline(line)\n if self.options.all or not stat['filename'].startswith('.'):\n stats[stat['filename']] = stat\n return stats\n\n def _parse_statline(self,statline):\n m = self._p.search(statline)\n stat = dict()\n if m:\n stat['rights'] = m.group(1)\n stat['owner'] = m.group(2)\n stat['group'] = m.group(3)\n stat['size'] = m.group(4)\n stat['atime'] = m.group(5)\n stat['mtime'] = m.group(6)\n fnpath = m.group(7).split('/')\n stat['filename'] = fnpath.pop()\n return stat\n\n def _exec_stat(self,path):\n pathelem = path.split(':')\n cmd = self._STAT_CMD % (pathelem.pop(),self._STAT_FORMAT)\n if self.options.verbose:\n print \"Executing command: \" + cmd\n if(pathelem):\n return self._exec_remote(pathelem.pop(),cmd)\n else:\n return self._exec_local(cmd)\n\n def _exec_local(self,cmd):\n stream = os.popen(cmd)\n out = stream.readlines()\n exit = stream.close()\n if(not exit):\n return out\n else:\n raise Exception(os.WEXITSTATUS(exit))\n\n def _exec_remote(self,host,cmd):\n if(paramiko):\n client = paramiko.SSHClient()\n client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n client.load_system_host_keys()\n client.connect(host)\n stdin, stdout, stderr = client.exec_command(cmd)\n return stdout.readlines()\n else:\n raise Exception('paramiko library was not loaded and is required for remote diff support')\n\n def _gen_diff(self,lsubject,rsubject,compare_keys = None):\n lkeys = set(lsubject)\n rkeys = set(rsubject)\n\n lextras = lkeys.difference(rkeys)\n rextras = rkeys.difference(lkeys)\n\n different = dict()\n for key in lkeys.intersection(rkeys):\n if compare_keys:\n ckeys = compare_keys\n else:\n ckeys = set(lsubject[key])\n for ckey in ckeys:\n if(lsubject[key][ckey] != rsubject[key][ckey]):\n if key not in different:\n different[key] = dict()\n different[key][ckey] = [lsubject[key][ckey],rsubject[key][ckey]]\n\n return (different,lextras,rextras)\n\n def do_diff(self):\n try:\n lsubjects = self._parse_statlines(self._exec_stat(self.subject_left))\n rsubjects = self._parse_statlines(self._exec_stat(self.subject_right))\n (difference,lextras,rextras) = self._gen_diff(lsubjects,rsubjects,self.ckeys)\n return self.format_diff(lsubjects,rsubjects,difference,lextras,rextras)\n except Exception,e:\n print str(e)\n return\n\n def format_diff(self,lsubjects,rsubjects,difference,lextras,rextras):\n if(len(difference)==0 and len(lextras)==0 and len(rextras)==0):\n return\n output = []\n output.append('--- %s' % (self.subject_left))\n output.append('+++ %s' % (self.subject_right))\n\n keylist = list(set(difference).union(lextras).union(rextras))\n keylist.sort()\n\n maxlen = max(map(len,keylist))\n\n if not self.options.short:\n if maxlen > 40: maxlen = 40\n\n for key in keylist:\n dkey = key\n if len(key) > maxlen:\n dkey = (key[0:maxlen-1] + '*')\n dkey = dkey.ljust(maxlen)\n if key in lextras:\n output.append('- %s %s' %\n (dkey,self.format_subject(lsubjects[key])))\n if key in rextras:\n output.append('+ %s %s' %\n (dkey,self.format_subject(rsubjects[key])))\n if key in difference:\n output.append('- %s %s' %\n (dkey,self.format_subject(lsubjects[key])))\n output.append('+ %s %s' %\n (dkey,self.format_subject(rsubjects[key])))\n return '\\n'.join(output)\n\n def format_subject(self,subject):\n rights = subject['rights']\n group = subject['group']\n owner = subject['owner']\n size = subject['size']\n atime = subject['atime']\n mtime = subject['mtime']\n filename = subject['filename']\n\n datime = datetime.fromtimestamp(int(atime))\n dmtime = datetime.fromtimestamp(int(mtime))\n\n if self.options.long:\n return '%10s - %8s %8s %10s %8s (Access: %8s)' % (rights,owner,group,size,dmtime,datime)\n elif not self.options.short:\n return '%8s %8s' % (size,dmtime)\n else:\n return ''\n\ndef statdiff_main():\n sd = StatDiff(sys.argv)\n output = sd.do_diff()\n if output:\n print output\n elif sd.options.verbose:\n print \"No Differences Found.\"\n\nif __name__ == '__main__':\n statdiff_main()\n\n" }, { "alpha_fraction": 0.5795454382896423, "alphanum_fraction": 0.5856643319129944, "avg_line_length": 25, "blob_id": "1d3fde860be695b888b5dd031b48b36a4c0caf2d", "content_id": "d1277775aaa3de7c99eb32c40ce84b151c31a9f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1144, "license_type": "no_license", "max_line_length": 108, "num_lines": 44, "path": "/setup.py", "repo_name": "d-snyder/statdiff", "src_encoding": "UTF-8", "text": "import os\nfrom setuptools import setup\n\nkwds = {}\n\n# Read the long description from the README.txt\nthisdir = os.path.abspath(os.path.dirname(__file__))\nf = open(os.path.join(thisdir, 'README.txt'))\nkwds['long_description'] = f.read()\nf.close()\n\n\nsetup(\n name = 'statdiff',\n version = '0.1.0',\n author = 'David Snyder',\n author_email = '[email protected]',\n description = \"Utility to compare file statistic differences between two directories, local or remote.\",\n license = \"LGPL\",\n classifiers = [\n \"License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)\",\n \"Development Status :: 3 - Alpha\",\n \"Environment :: Console\",\n \"Intended Audience :: System Administrators\",\n \"Operating System :: Unix\",\n \"Programming Language :: Python\",\n \"Topic :: Utilities\",\n ],\n\n py_modules = [\"statdiff\"],\n entry_points = dict(\n console_scripts = [\n \"statdiff = statdiff:statdiff_main\",\n ],\n ),\n install_requires = [\n 'paramiko',\n ],\n tests_require = [\n 'nose >= 0.10',\n ],\n test_suite = 'nose.collector',\n **kwds\n)\n" }, { "alpha_fraction": 0.57421875, "alphanum_fraction": 0.631911039352417, "avg_line_length": 37.69767379760742, "blob_id": "458e51c710e4ac6425bc9d62430030d71009cefd", "content_id": "db9d96b6ed063c8fe6481620347550c6b675d058", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3328, "license_type": "no_license", "max_line_length": 168, "num_lines": 86, "path": "/tests/test_statdiff.py", "repo_name": "d-snyder/statdiff", "src_encoding": "UTF-8", "text": "import nose\nimport sys\n\nsys.path.append(\"..\")\nimport statdiff\n\nargline = 'statdiff.py host:/var/opt/something/ host2:/var/opt/something/else'\nstatlines1 = [\"-rw-r--r-- drsnyder agroup 6 1268680848 1268680849 {this is a test}.jpg .hey\", \"-rw-r--r-x joe joegroup 42 1268681848 1268681849 file2.jpg\"]\nstatlines2 = [ \"-rw-r--rwx fred differentgroup 37 1268680998 1268680999 {this is a test}.jpg .hey\", \"-rw-r--r-x fred differentgroup 37 1268680998 1268680999 file3.jpg\"]\n\ndef test_args():\n subject = statdiff.StatDiff(argline.split(' '))\n print subject.subject_left\n assert 'host:/var/opt/something/' == subject.subject_left\n print subject.subject_right\n assert 'host2:/var/opt/something/else' == subject.subject_right\n\ndef test_noargs():\n exc = False\n try:\n subject = statdiff.StatDiff([])\n except Exception, e:\n assert 'You must provide at least two subjects to compare' == str(e)\n exc = True\n assert(exc)\n\ndef test_onearg():\n exc = False\n try:\n subject = statdiff.StatDiff(['this is an arg'])\n except Exception, e:\n assert 'You must provide at least two subjects to compare' == str(e)\n exc = True\n assert(exc)\n\ndef test_parselines():\n subject = statdiff.StatDiff(['fake','fake','fake'])\n stats = subject._parse_statlines(statlines1)\n\n stat = stats['{this is a test}.jpg .hey']\n\n assert stat['rights'] == '-rw-r--r--'\n assert stat['owner'] == 'drsnyder'\n assert stat['group'] == 'agroup'\n assert stat['size'] == '6'\n assert stat['atime'] == '1268680848'\n assert stat['mtime'] == '1268680849'\n assert stat['filename'] == '{this is a test}.jpg .hey'\n\n stat = stats['file2.jpg']\n\n assert stat['rights'] == '-rw-r--r-x'\n assert stat['owner'] == 'joe'\n assert stat['group'] == 'joegroup'\n assert stat['size'] == '42'\n assert stat['atime'] == '1268681848'\n assert stat['mtime'] == '1268681849'\n assert stat['filename'] == 'file2.jpg'\n\ndef test_gen_diff():\n subject = statdiff.StatDiff(['fake','fake','fake'])\n lstats = subject._parse_statlines(statlines1)\n rstats = subject._parse_statlines(statlines2)\n\n (diff,lextra,rextra) = subject._gen_diff(lstats,rstats)\n assert len(diff['{this is a test}.jpg .hey']) == 6\n assert diff['{this is a test}.jpg .hey']['rights'] == ['-rw-r--r--','-rw-r--rwx']\n assert diff['{this is a test}.jpg .hey']['group'] == ['agroup','differentgroup']\n assert diff['{this is a test}.jpg .hey']['owner'] == ['drsnyder','fred']\n assert diff['{this is a test}.jpg .hey']['size'] == ['6','37']\n assert diff['{this is a test}.jpg .hey']['atime'] == ['1268680848','1268680998']\n assert diff['{this is a test}.jpg .hey']['mtime'] == ['1268680849','1268680999']\n assert 'filename' not in diff['{this is a test}.jpg .hey']\n assert 'file2.jpg' in lextra\n assert 'file3.jpg' in rextra\n assert len(lextra) == 1\n assert len(rextra) == 1\n\ndef test_gen_diff_specific_keys():\n subject = statdiff.StatDiff(['fake','fake','fake'])\n lstats = subject._parse_statlines(statlines1)\n rstats = subject._parse_statlines(statlines2)\n\n (diff,lextra,rextra) = subject._gen_diff(lstats,rstats,['group'])\n assert len(diff['{this is a test}.jpg .hey']) == 1\n assert diff['{this is a test}.jpg .hey']['group'] == ['agroup','differentgroup']\n" } ]
3
jingyuexing/MathLib
https://github.com/jingyuexing/MathLib
b98bf279b2a22ba0e1e5019d998eea560f4e3085
76315d5ce8250026fe0e1c2abc772cadc3084620
c38db4b7e66f10c98b41131a1d558ff1d5ab8c32
refs/heads/master
2023-06-25T21:33:48.248206
2023-06-14T03:24:43
2023-06-14T03:24:43
174,944,104
52
11
MIT
2019-03-11T07:05:04
2020-08-03T14:03:01
2020-09-17T18:22:50
TypeScript
[ { "alpha_fraction": 0.6913946866989136, "alphanum_fraction": 0.6913946866989136, "avg_line_length": 23.071428298950195, "blob_id": "1f8880a4c55823a37f4e3640ac4f1f1f5308fc2f", "content_id": "4656fb9ad6fb9c2e0482e727c3437be66256cb71", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 337, "license_type": "permissive", "max_line_length": 52, "num_lines": 14, "path": "/statistics/C/include/queue.h", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "#ifndef __QUEUE_H__\n#define __QUEUE_H__\n#include <stdlib.h>\ntypedef struct _s{\n struct _s *child;\n int isRoot;\n int index;\n double element;\n}Node;\nNode *init(double element,int isRoot);\nNode *insert(Node *root,double item,double element);\nNode *remove(Node *root,double item);\nNode *insert(Node *root,double element);\n#endif\n" }, { "alpha_fraction": 0.6969696879386902, "alphanum_fraction": 0.6969696879386902, "avg_line_length": 7.5, "blob_id": "8cee8c22f86f8f700131cf3ba2a4e25eee3ccfc8", "content_id": "33f5dabe680fbba33ee6fbf8f3aab7706cc4c3d0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 33, "license_type": "permissive", "max_line_length": 16, "num_lines": 4, "path": "/statistics/TypeScript/src/tensor.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "class Tensor{\n\n}\nexport {Tensor};" }, { "alpha_fraction": 0.5368421077728271, "alphanum_fraction": 0.5368421077728271, "avg_line_length": 8.600000381469727, "blob_id": "649e0888086306f2296cced6b311842c34e51246", "content_id": "5ca172396a7ffe6620fe76f078d4394233a044b7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 133, "license_type": "permissive", "max_line_length": 26, "num_lines": 10, "path": "/statistics/TypeScript/src/Bayes.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/**\n * 贝叶斯\n * 后验概率 = (似然性*先验概率)/标准化常量\n */\nclass bayes{\n\tconstructor(){\n\t}\n\t\n}\nexport { bayes };" }, { "alpha_fraction": 0.6181102395057678, "alphanum_fraction": 0.6466535329818726, "avg_line_length": 16.824562072753906, "blob_id": "397f67aa192ae2374d9ea8d39aca83ca5cd25b41", "content_id": "27a780629e6c8d250a6a07a918f390bf1a96fb91", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 1016, "license_type": "permissive", "max_line_length": 50, "num_lines": 57, "path": "/statistics/Go/mathlib/Link.go", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: Admin\n* @Date: 2021-05-06 14:27:53\n* @Last Modified by: admin\n* @Last Modified time: 2022-04-14 20:48:40\n */\npackage mathlib\n\ntype Node struct {\n\tprev *Node\n\tnext *Node\n\telement interface{}\n}\n\ntype Link struct {\n\thead *Node\n\tpos *Node\n\tlength int\n}\n\ntype ILink interface {\n\tappend(item interface{})\n\tremove(item interface{})\n\tfind(item interface{})\n\tinit() Link\n}\n\nfunc (l *Link) init() {\n\tl.head = nil\n\tl.pos = nil\n\tl.length = 0\n}\n\n/**\n * [func description]\n * @param {interface{}} item\n * @return {[type]} [description]\n */\nfunc (l *Link) append(item interface{}) {\n\tvar newNode = new(Node)\n\tl.pos = l.head.next\n\tl.length++\n\tl.pos = newNode\n}\nfunc (l *Link) remove(item interface{}) {\n\tfindOne := l.find(item)\n\tfindOne.element = findOne.next.element\n\tfindOne.next = findOne.next.next\n}\nfunc (l *Link) find(item interface{}) Node {\n\tvar currNode = new(Node)\n\tcurrNode = l.head.next\n\tfor currNode.element != item && currNode != nil {\n\t\tcurrNode = currNode.next\n\t}\n\treturn *currNode\n}\n" }, { "alpha_fraction": 0.4545454680919647, "alphanum_fraction": 0.5909090638160706, "avg_line_length": 23.299999237060547, "blob_id": "73e0895df132dbc8ace5f8129948fbd1da22308b", "content_id": "81e9471c889085028ebba3962c3172f131631542", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 242, "license_type": "permissive", "max_line_length": 42, "num_lines": 10, "path": "/statistics/python/src/Harmonic.py", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Author: Admin\n# @Date: 2020-01-10 01:32:22\n# @Last Modified by: Admin\n# @Last Modified time: 2020-01-10 01:33:59\ndef harmonic(n=0):\n total = 0\n for x in range(1,n):\n total=total+1/i\n return total" }, { "alpha_fraction": 0.516339898109436, "alphanum_fraction": 0.529411792755127, "avg_line_length": 18.25, "blob_id": "4d0e64920e14b8b4df2990e60110d7dd94005eaf", "content_id": "a5dc4b8ab97263ff804b2e44cf07f22007a7b9a7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 153, "license_type": "permissive", "max_line_length": 34, "num_lines": 8, "path": "/statistics/es6/mean.es6.js", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "function mean(...num){\n \"use strict\";\n let total =0;\n for(let i=0;i<num.length;i++){\n total+=num[i];\n }\n return total/num.length;\n}" }, { "alpha_fraction": 0.522088348865509, "alphanum_fraction": 0.5301204919815063, "avg_line_length": 19.75, "blob_id": "0bf3bee245d27886cb5a8ed227377ffce4d210b4", "content_id": "8009c0e222d954fe660eb7338c655ed55277244f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 253, "license_type": "permissive", "max_line_length": 46, "num_lines": 12, "path": "/statistics/TypeScript/src/Summation.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "\n/**\n * 求和\n * @param {Array<number>} ...num [description]\n */\nfunction Summation([...num]: Array<number>) {\n var total: number = 0;\n for (let i = 0; i < num.length; i++) {\n total += num[i];\n }\n return total;\n}\nexport { Summation }" }, { "alpha_fraction": 0.7236841917037964, "alphanum_fraction": 0.7368420958518982, "avg_line_length": 24.5, "blob_id": "313d1e914c51dbbdf510f15b779e51bcfcf294ee", "content_id": "06aa9656aad113fdbe7d3514f287d16a8f882997", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 152, "license_type": "permissive", "max_line_length": 50, "num_lines": 6, "path": "/statistics/TypeScript/src/powerFactorial.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "import {Factorial as Fac} from \"./Factorial\"\nfunction powerFactorial(x:number,n:number):number{\n\n\treturn Fac(x+n-1)/Fac(x-1);\n}\nexport {powerFactorial};" }, { "alpha_fraction": 0.6231579184532166, "alphanum_fraction": 0.6456140279769897, "avg_line_length": 20.590909957885742, "blob_id": "9adf60666592b5b04953eb3cbd9476bac10a6fef", "content_id": "116f48f1a1d8e66729dd6a4f1bf7c265f12db2a0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 1425, "license_type": "permissive", "max_line_length": 58, "num_lines": 66, "path": "/statistics/Lua/src/Link.lua", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "-- @Author: admin\n-- @Date: 2021-12-14 13:14:23\n-- @Last Modified by: admin\n-- @Last Modified time: 2021-12-23 03:50:55\nlocal Node = {\n element= nil,\n prev = nil,\n next = nil\n}\n\nfunction Node.new(element)\n local node = {element=element}\n setmetatable(node,{__index=Node})\n return node\nend\n\nlocal Link = {\n head = nil,\n pos = nil,\n length = 0\n}\n\nfunction Link.new()\n local link = {}\n setmetatable(link,{__index=Link})\n return link\nend\n\nfunction Link.append(self,element)\n local newNode = Node.new(element)\n if self.head == nil then\n self.head = newNode\n self.pos = self.head\n else\n self.pos.next = newNode\n newNode.prev = self.pos\n self.pos = self.pos.next\n end\n self.length = self.length+1\nend\n\nfunction Link.remove(self,element)\n local findOne = self.find(self,element)\n findOne.prev.next = findOne.next\n findOne.next.prev = findOne.prev\n self.length = self.length - 1\nend\n\nfunction Link.insert(self,target,element)\n local findOne = self.find(self,target)\n local newNode = Node.new(element)\n newNode.next = findOne.next.next\n newNode.prev = findOne\n findOne.next = newNode\n self.length= self.length+1\nend\n\nfunction Link.find(self,element)\n local current = self.head;\n while current.element ~= element and current ~= nil do\n current = current.next\n end\n return current\nend\n\nreturn Link\n" }, { "alpha_fraction": 0.5092838406562805, "alphanum_fraction": 0.604774534702301, "avg_line_length": 28, "blob_id": "5b7006febdb3172751bcab35d887757e550a8055", "content_id": "dec42aaee27543cb7f3e004a50349a5666800985", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 377, "license_type": "permissive", "max_line_length": 66, "num_lines": 13, "path": "/statistics/python/src/Median.py", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Author: Jingyuexing\n# @Date: 2020-01-11 17:41:48\n# @Last Modified by: Jingyuexing\n# @Last Modified time: 2020-12-03 14:08:31\nfrom Rnak import Rank\ndef median(data=[]):\n data = Rank.bubbleSort(data)\n if len(data)%2 == 0:\n return data[len(data)/2];\n else:\n return (data[int(len(data)/2)]+data[int(len(data)/2)+1])/2\n pass\n" }, { "alpha_fraction": 0.5013405084609985, "alphanum_fraction": 0.51474529504776, "avg_line_length": 17.04838752746582, "blob_id": "257e0f1e08a0cc3c064ce120c962dae3ddcd1430", "content_id": "cc461841e51a7c6fb4383d3311f574cc7e3b7a99", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1183, "license_type": "permissive", "max_line_length": 81, "num_lines": 62, "path": "/statistics/TypeScript/src/Rank.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "// 排序算法\nclass Rank{\n\t/**\n\t * 插入排序\n\t * @param {Array<number>} ...a [需要排序的数据]\n\t */\n\tstatic insert([...a]:Array<number>):Array<number>{\n\t\tvar key:number,j:number;\n\t\tfor(var i:number=2;i <= a.length;i++){\n\t\t\tkey = a[i];\n\t\t\tj = i-1;\n\t\t\twhile(i>0 && a[j]>key){\n\t\t\t\ta[j+1]=a[j];\n\t\t\t\tj=j-1;\n\t\t\t\ta[j+1]=key;\n\t\t\t}\n\t\t}\n\t\treturn a;\n\t}\n\t/**\n\t * 冒泡排序\n\t * @param {Array<number>} ...a [需要排序的数据]\n\t * @return {Array<number>} [排序好的数据]\n\t */\n\tstatic bubbleSort([...a]:Array<number>):Array<number>{\n\t\tlet temp:number=0;\n\t\tfor(let i=0;i<a.length-1;i++){\n\t\t\tfor(let j=0;j<a.length-i;j++){\n\t\t\t\tif(a[j]>a[j+1]){\n\t\t\t\t\ttemp=a[j];\n\t\t\t\t\ta[j] = a[j+1];\n\t\t\t\t\ta[j+1] = temp;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn a;\n\t}\n\n\tstatic SelectSort(){\n\n\t}\n\tstatic quickSort([...arry]:Array<number>,begin:number,end:number):Array<number>{\n\t\tvar i=begin,j=end,key=arry[begin];\n\t\twhile(i<j){\n\t\t\twhile(i<j&&arry[j]>=key) j--;\n\t\t\tif (i<j) {\n\t\t\t\tarry[i]=arry[j];\n\t\t\t\ti++;\n\t\t\t}\n\t\t\twhile(i<j&&arry[i]<key) i++;\n\t\t\tif(i<j){\n\t\t\t\tarry[j]=arry[i];\n\t\t\t\tj--;\n\t\t\t}\n\t\t}\n\t\tarry[i]=key;\n\t\tRank.quickSort(arry,begin,i-1);\n\t\tRank.quickSort(arry,i+1,end);\n\t\treturn arry;\n\t}\n}\nexport {Rank};\n" }, { "alpha_fraction": 0.5339806079864502, "alphanum_fraction": 0.5339806079864502, "avg_line_length": 17.727272033691406, "blob_id": "1469c755972ed0d2642c6c04646a76b95610bbbe", "content_id": "e4eac2265be8974e6c37241e1422e880233efb20", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 244, "license_type": "permissive", "max_line_length": 51, "num_lines": 11, "path": "/statistics/TypeScript/src/Mean.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/**\n * 平均值\n */\n /**\n * 初始化一个数列\n * @param {Array<number>} ...input [需要求平均值的数据]\n */\nfunction Mean([...input]:Array<number>){\n return input.reduce((x,y)=>(x+y)/input.length);\n}\nexport {Mean}\n" }, { "alpha_fraction": 0.41886791586875916, "alphanum_fraction": 0.5245283246040344, "avg_line_length": 16.733333587646484, "blob_id": "7b08140fb891488b55bd536fe668631b45463060", "content_id": "09e36f2d8d6ff6cb900332dba1c47ba0743fa637", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 265, "license_type": "permissive", "max_line_length": 42, "num_lines": 15, "path": "/statistics/CS/src/Matrix.cs", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: Admin\n* @Date: 2020-07-23 18:51:04\n* @Last Modified by: Admin\n* @Last Modified time: 2020-07-23 19:00:26\n*/\nnamespace MathLib{\n class Matrix{\n int col;\n int row;\n double[][] data; \n static Matrix(){\n }\n }\n}" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.699999988079071, "avg_line_length": 19.733333587646484, "blob_id": "b312516badf1a96f9db54abb5c4768943811cfa0", "content_id": "12fc3b14054053b8bd3064aa6cd5022c70eaaf67", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 322, "license_type": "permissive", "max_line_length": 67, "num_lines": 15, "path": "/statistics/TypeScript/src/Gaussian_distribution.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "import {Gaussiandistribution as GD} from \"./Gaussian_distribution\";\nimport {Variance as Vc} from \"./Variance\";\nimport {StandardDeviation as SD} from \"./Standard_Deviation\";\n/**\n * 高斯正态分布\n */\n\nexport class Gaussiandistribution{\n\tE:number;\n\tPI:number;\n\tconstructor(){\n\t\tthis.E = Math.E;\n\t\tthis.PI = Math.PI;\n\t}\n}" }, { "alpha_fraction": 0.44552528858184814, "alphanum_fraction": 0.5252918004989624, "avg_line_length": 22.363636016845703, "blob_id": "e0089d8a4a393a047eb40407561284e8f6242621", "content_id": "9d2cbe5e714b2b17757079d58fb0b957f59bde01", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 514, "license_type": "permissive", "max_line_length": 42, "num_lines": 22, "path": "/statistics/python/src/Summation.py", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Author: Admin\n# @Date: 2020-01-10 00:58:26\n# @Last Modified by: Jingyuexing\n# @Last Modified time: 2021-02-10 13:45:37\n\n\ndef summation(*args):\n total = 0\n tempList = []\n for x in args:\n if isinstance(x, (tuple, list)):\n for i in x:\n tempList.append(i)\n else:\n tempList.append(x)\n for k in tempList:\n total = total + k\n return total\nif __name__ == '__main__':\n s = summation([12,34,56,78,90,0])\n print(s)\n" }, { "alpha_fraction": 0.4935622215270996, "alphanum_fraction": 0.4935622215270996, "avg_line_length": 14.863636016845703, "blob_id": "53228875723cbb013aa4de6893ea649c9f67f3c9", "content_id": "468fc49244e252a692b42e5198250613b787a76f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 919, "license_type": "permissive", "max_line_length": 40, "num_lines": 44, "path": "/statistics/TypeScript/src/Collection.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "\n/**\n *\n */\nclass Collection{\n data:any[];\n constructor(){\n }\n /**\n * 判定集合是否是相等的\n * 当集合当中所有元素都相等,那么这两个集合则相等\n * @param {Collection} C 进行判断的集合\n */\n isEqual(C:Collection){\n }\n /**\n * 为集合当中添加元素,集合的元素不要求顺序,\n * 但是集合的元素是\n * @param {any} element 需要添加的元素\n */\n addElement(element:any){\n }\n /**\n * 元素是否在集合当中\n * @param {any} element 查询的元素\n */\n isIn(element:any):boolean{\n var is:boolean = false;\n return is;\n }\n /**\n * 集合的减法运算\n * @param {Collection} C 需要进行相减操作的集合\n */\n mult(C:Collection){\n\n }\n /**\n * [unitElemnt description]\n * @return {number} 单位元\n */\n unitElemnt(){\n\n }\n}\n" }, { "alpha_fraction": 0.614130437374115, "alphanum_fraction": 0.614130437374115, "avg_line_length": 27.384614944458008, "blob_id": "e1ff39cfd7239fae3bacb75ff5204c3e4f16cbbd", "content_id": "33d5adf3dd417648ecfe788193b0fdce21abee00", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": true, "language": "TypeScript", "length_bytes": 368, "license_type": "permissive", "max_line_length": 43, "num_lines": 13, "path": "/@type/statistics.d.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/// <reference path=\"covariance.d.ts\" />\n/// <reference path=\"Matrix.d.ts\" />\n/// <reference path=\"Mean.d.ts\" />\n/// <reference path=\"product.d.ts\" />\n/// <reference path=\"product.d.ts\" />\n/// <reference path=\"rank.d.ts\" />\n/// <reference path=\"trigonometric.d.ts\" />\n/// <reference path=\"tensor.d.ts\" />\n/// <reference path=\"vector.d.ts\" />\n\ninterface statistics{\n\t\n}" }, { "alpha_fraction": 0.375, "alphanum_fraction": 0.375, "avg_line_length": 7, "blob_id": "d0d576fd41af976dd06982d0a7e799dfe3a186dc", "content_id": "f7f7c826743959310467d2f1053256a6e1357256", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 12, "license_type": "permissive", "max_line_length": 7, "num_lines": 1, "path": "/statistics/CS/README.md", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "# C# 实现\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5, "avg_line_length": 7, "blob_id": "340685f73fa155ba56144808a2b8821874e6818f", "content_id": "e878919af765b8981534d72bcd0a4c268fb83498", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 12, "license_type": "permissive", "max_line_length": 7, "num_lines": 1, "path": "/statistics/Go/README.md", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "# GO 实现\n" }, { "alpha_fraction": 0.6156250238418579, "alphanum_fraction": 0.621874988079071, "avg_line_length": 14.285714149475098, "blob_id": "50112c398b83766e449f3d825c507ac7ea246fd5", "content_id": "417744e894969b636dbd4df5409a0de986e7a05a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 346, "license_type": "permissive", "max_line_length": 50, "num_lines": 21, "path": "/statistics/TypeScript/src/Permutations.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/**\n * 求阶乘\n * @param {number} n 阶乘数值\n * @return {number} 阶乘\n */\nfunction factorial(n:number):number{\n\tlet total:number=1;\n\tfor(let i:number=1;i<=n;i++){\n\t\ttotal*=i;\n\t}\n\treturn total;\n}\n/**\n * 排列组合\n */\nclass Permu{\n\tconstructor(m:number,n:number){\n\t\treturn factorial(n)/factorial(m)*factorial(n-m);\n\t}\n}\nexport {Permu}" }, { "alpha_fraction": 0.7299670577049255, "alphanum_fraction": 0.7299670577049255, "avg_line_length": 42.42856979370117, "blob_id": "4359649101185c1bb21eff2624aa4213dc9118f5", "content_id": "5fbf585d18a82ee15480d178a006ba70c4b249fd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 923, "license_type": "permissive", "max_line_length": 126, "num_lines": 21, "path": "/statistics/TypeScript/src/index.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "import {Gaussiandistribution as GD} from \"./Gaussian_distribution\";\nimport {Variance as Vc} from \"./Variance\";\nimport {StandardDeviation as SD} from \"./Standard_Deviation\";\nimport {bayes} from \"./Bayes\";\nimport {Mean} from \"./Mean\"\nimport {Median} from \"./Median\";\nimport {weigthVariance as WeiVar} from \"./weigth_variance\";\nimport {QuantilePlot as QuanPlot} from \"./QuantilePlot\";\nimport {Matrix} from \"./Matrix\";\nimport {Factorial as fator} from \"./factorial\";\nimport {Permu} from \"./Permutations\"\nimport {Vector} from \"./vector\";\nimport {sigmoid} from \"./sigmoid\";\nimport {Rank} from \"./Rank\";\nimport {Tensor} from \"./tensor\";\nimport {LeastSquare} from \"./LeastSquare\";\nimport {gcd} from \"./gcd\";\nimport {Harmonic as Har} from \"./harmonic\";\nimport Complex from \"./Complex\"\n//导出多个模块\nexport {GD,Vc,SD,Har,bayes,Rank,Mean,Median,Permu,fator,Matrix,QuanPlot,WeiVar,Vector,sigmoid,Tensor,LeastSquare,gcd,Complex};" }, { "alpha_fraction": 0.5441595315933228, "alphanum_fraction": 0.62678062915802, "avg_line_length": 19.647058486938477, "blob_id": "4208bc4fb316c5c070385cfc7ff5f8bd7b883d24", "content_id": "3fda73b47b83b2b30e0ef802066488567d3882da", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 351, "license_type": "permissive", "max_line_length": 60, "num_lines": 17, "path": "/statistics/python/src/corrlation.py", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Author: Jingyuexing\n# @Date: 2020-05-30 03:44:39\n# @Last Modified by: jingyuexing\n# @Last Modified time: 2020-05-30 04:10:16\n\nimport var\nimport math\n\n\ndef corrlation(dataX:list, dataY:list):\n t = dataX\n for i in dataY:\n t.append(i)\n \n b = math.sqrt(var.variance(dataX) * var.variance(dataY))\n pass\n" }, { "alpha_fraction": 0.4241071343421936, "alphanum_fraction": 0.5491071343421936, "avg_line_length": 15.071428298950195, "blob_id": "185a32c153335fc87b3d0e6b46fcaa104b511020", "content_id": "43301f8b892585b98b66629034876cfd853cfacf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 224, "license_type": "permissive", "max_line_length": 42, "num_lines": 14, "path": "/statistics/CS/src/Permutations.cs", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: Admin\n* @Date: 2020-07-23 18:51:51\n* @Last Modified by: Admin\n* @Last Modified time: 2020-07-23 19:03:59\n*/\n\nnamespace MathLib{\n class Permutations{\n Permutations(){\n \n }\n }\n}" }, { "alpha_fraction": 0.5071942210197449, "alphanum_fraction": 0.6079136729240417, "avg_line_length": 17.600000381469727, "blob_id": "5963d62efb2831977980b634a13f3cb4e8454feb", "content_id": "bf97ca9876f3cc2dc65479291a961c25a6f5ec42", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 278, "license_type": "permissive", "max_line_length": 50, "num_lines": 15, "path": "/statistics/Java/com/mathlib/Mathlib.java", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "package com.mathlib;\n/*\n* @Author: jingyuexing\n* @Date: 2021-04-14 18:20:38\n* @Last Modified by: admin\n* @Last Modified time: 2021-06-05 09:19:06\n*/\n\n\nclass Mathlib{\n public static void main(final String[] args) {\n final String a = new String(\"\");\n \n }\n}" }, { "alpha_fraction": 0.5992779731750488, "alphanum_fraction": 0.6010830402374268, "avg_line_length": 16.3125, "blob_id": "5bc174f6d4aaf6eb58d667bcfceb021f0507e19f", "content_id": "0b2847efaabffe98e32733a533fad39939f3c384", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1304, "license_type": "permissive", "max_line_length": 45, "num_lines": 64, "path": "/statistics/C/include/List.h", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "#ifndef __LIST_H__\n#define __LIST_H__\n#include <stdlib.h>\ntypedef struct Node{\n struct Node *next;\n int index;\n void *element;\n}ListNode;\nstruct list{\n struct list *self;\n ListNode *postion;\n ListNode *head;\n struct list *(*init)(double element);\n ListNode *(*indexOf)(int index);\n void (*insert)();\n void (*remove)(int index);\n ListNode *(*find)(double item);\n};\ntypedef struct list List;\n/**\n * 删除列表节点\n * @param l 需要操作的列表\n * @param index 下标\n */\nvoid remove(List l,int index);\n/**\n * 向列表当中插入元素\n * @param l 目标列表\n * @param index 下表\n * @param element 元素\n */\nvoid insert(List l,int index,double element);\n\n/**\n * 列表是否为空\n * @param l 需要判断的列表\n * @return 0 or 1\n */\nint isEmpty(List l);\n/**\n * 删除列表\n * @param l 目标列表\n */\nvoid deleteList(List l);\n/**\n * 查找列表当中下表为index的节点\n * @param l 列表\n * @param index 下标\n * @return 节点\n */\nListNode *indexOf(List l,int index);\n/**\n * 遍历查找\n * @param item 元素内容\n * @return 节点\n */\nListNode *find(double item);\n/**\n * 添加元素,默认添加到末尾\n * @param l 目标列表\n * @param element 元素\n */\nvoid append(List l,double element);\n#endif\n" }, { "alpha_fraction": 0.6136606335639954, "alphanum_fraction": 0.6446104645729065, "avg_line_length": 14.881356239318848, "blob_id": "d18f47d91c8a9261da2cb5b7934d62c2765975be", "content_id": "0ea4526b395bf436b66e67016e7df93814e9a68b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 937, "license_type": "permissive", "max_line_length": 50, "num_lines": 59, "path": "/statistics/Go/mathlib/List.go", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: Jingyuexing\n* @Date: 2021-08-07 10:50:14\n* @Last Modified by: Jingyuexing\n* @Last Modified time: 2021-08-08 16:52:11\n */\n\npackage List\n\ntype Node struct {\n\tnext *Node\n\telement interface{}\n}\n\ntype List struct {\n\thead *Node\n\tpos *Node\n\tlength int\n}\n\ntype IList interface {\n\tinit()\n\tappend(item interface{})\n\tremove(item interface{})\n\tfind(item interface{})\n}\n\nfunc (l *List) init() {\n\tl.head = nil\n\tl.pos = nil\n\tl.length = 0\n}\n\nfunc (l *List) append(item interface{}) {\n\tvar newNode = new(Node)\n\tif l.head == nil {\n\t\tl.head = newNode\n\t} else {\n\t\tl.pos.next = newNode\n\t}\n\tl.pos = newNode\n\tl.length++\n}\n\nfunc (l *List) remove(item interface{}) Node {\n\tvar findOne = l.find(item)\n\tfindOne = *findOne.next\n\treturn findOne\n}\nfunc (l *List) find(item interface{}) Node {\n\tvar currNode = new(Node)\n\tcurrNode = l.head\n\tfor currNode.element != item && currNode != nil {\n\t\tcurrNode = currNode.next\n\t}\n\n\treturn *currNode\n\n}\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 11, "blob_id": "04bdb0aa5e4ac8cd76d120efafe11680f27c3a64", "content_id": "b530606724e680f87fafee45283680375a22b9e6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 16, "license_type": "permissive", "max_line_length": 11, "num_lines": 1, "path": "/statistics/python/README.md", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "# Python 实现\n" }, { "alpha_fraction": 0.4285714328289032, "alphanum_fraction": 0.44688645005226135, "avg_line_length": 15.058823585510254, "blob_id": "6c2763706c69b83b1bda00cb84a7cb6f2abf022b", "content_id": "50f2fc6b3b61bbe9b236e0f49dadf46a6bf46473", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 337, "license_type": "permissive", "max_line_length": 35, "num_lines": 17, "path": "/statistics/TypeScript/src/binExp.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "\n/**\n * 快速幂\n * 其核心思想是将n转化为几个2次幂的和而后进行对乘机求和\n * @param {number} a 底数\n * @param {number} n 指数\n */\nfunction binExp(a:number,n:number){\n var k:number = 1;\n while(n){\n if((n&1)==1){\n k *=a;\n }\n a *= a;\n n = n>>1;\n }\n return k;\n}" }, { "alpha_fraction": 0.5099999904632568, "alphanum_fraction": 0.6499999761581421, "avg_line_length": 19, "blob_id": "86a2f4290225a85b201692ce26bab1b098c17a3e", "content_id": "4ab7db7ebfdba3d7119f6c9a73b39ca9e7c466e5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 200, "license_type": "permissive", "max_line_length": 42, "num_lines": 10, "path": "/statistics/C/src/BRTree.c", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: Admin\n* @Date: 2021-05-11 06:00:15\n* @Last Modified by: Admin\n* @Last Modified time: 2021-05-11 16:01:09\n*/\n#include \"../include/BRTree.h\"\nvoid append(Node *tree,double element){\n\n}\n" }, { "alpha_fraction": 0.5533661842346191, "alphanum_fraction": 0.5582922697067261, "avg_line_length": 28.047618865966797, "blob_id": "774be29e47e55de2c8023a0b7f839ca5726db109", "content_id": "976893a7a663f4e77aa46d37c91b64af27f2760c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 665, "license_type": "permissive", "max_line_length": 97, "num_lines": 21, "path": "/statistics/TypeScript/src/weigth_variance.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/**\n * 加权平均数\n */\n /**\n * 计算加权平均数\n * @param {Array<number>} numberData 要计算的值\n * @param {Array<number>} weigth 权值\n */\n function weigthVariance([...numberData]: Array < number > , [...weigth]: Array < number > ) {\n \tlet totalWigth:number=0,totaNumber:number=0;\n if (numberData.length == weigth.length) {\n \tfor(let i:number =0;i<=numberData.length;i++){\n \t\ttotalWigth+=weigth[i];\n \t\ttotaNumber+=numberData[i]*weigth[i];\n \t}\n }else{\n \tthrow Error(\"权重值和数据不匹配!\");\n }\n return totaNumber/totalWigth;\n }\nexport {weigthVariance};" }, { "alpha_fraction": 0.5568862557411194, "alphanum_fraction": 0.559880256652832, "avg_line_length": 24.730770111083984, "blob_id": "a594b63b5a819ade8ce39db1a6f9722c014ccf01", "content_id": "974feae7e34f3cb1effeefab8575e61f6cf2f6cc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 740, "license_type": "permissive", "max_line_length": 75, "num_lines": 26, "path": "/statistics/TypeScript/src/Covariance.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/**\n * 协方差\n */\nimport {Mean} from \"./Mean\";\n/**\n * 求取两数组胡协方差\n *\n * @param {Array<number>} [...value_a]:Array<number> 第一个数组\n * @param {Array<number>} [...value_b]:Array<number> 第二个数组\n *\n * @return {number} 求得的协方差值\n */\nfunction Covariance([...value_a]:Array<number>,[...value_b]:Array<number>){\n\t\tif(value_a.length==value_b.length){\n\t\t\tlet mean:any = Mean([...value_a]);\n\t\t\tlet mean_b:any = Mean([...value_b]);\n\t\t\tlet total:number=0;\n\t\t\tfor(let i=0;i<=value_a.length;i++){\n\t\t\t\ttotal+=(value_a[i]-mean)*(value_b[i]-mean_b);\n\t\t\t} \n\t\t\treturn total/value_a.length;\n\t\t}else{\n\t\t\tthrow Error(\"两个集合不均等!\");\n\t\t}\n\t}\nexport {Covariance as Cov};" }, { "alpha_fraction": 0.6091205477714539, "alphanum_fraction": 0.6221498250961304, "avg_line_length": 21, "blob_id": "fa80986ceadb2b50bbfb72d2829816d73d68a30d", "content_id": "f9341d905072f65680b34f0bcd94fcdc1c07f382", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 347, "license_type": "permissive", "max_line_length": 44, "num_lines": 14, "path": "/statistics/TypeScript/src/Variance.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "import {Mean} from \"./Mean\";\n\t/**\n\t * 方差的正平方根称为该随机变量的标准差\n\t * 方差\n\t */\nfunction Variance([...value]:Array<number>){\n\t\tvar mean:any = Mean([...value]);\n\t\tvar total:number=0;\n\t\tfor(let i:number=0;i<value.length-1;i++){\n\t\t\ttotal+=Math.pow((value[i]-mean),2);\n\t\t}\n\t\treturn total/value.length;\n\t}\nexport {Variance}" }, { "alpha_fraction": 0.42703670263290405, "alphanum_fraction": 0.44494181871414185, "avg_line_length": 26.580245971679688, "blob_id": "43daa771f0dc0f971f398d084d416f1ebb603117", "content_id": "4eea3f5b51fb195d0f48968355bf6b1cbe52bbd6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2300, "license_type": "permissive", "max_line_length": 64, "num_lines": 81, "path": "/statistics/CS/src/Mathlib.cs", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: Jingyuexing\n* @Date: 2020-12-04 10:27:40\n* @Last Modified by: Jingyuexing\n* @Last Modified time: 2020-12-04 11:15:23\n*/\n\n\nusing System;\n\nnamespace Mathlib{\n class Mathlib{\n /**\n * 最大公约数\n * @param {int} p\n * @param {int} q [description]\n * @return {int} [description]\n */\n public static int gcd(int p,int q){\n if(q==0) return p;\n int r = p % q;\n return gcd(q, r);\n }\n\n /**\n * 平均值\n * @param {Array<double>} data 需要求平均值的数值\n * @return {double} final 平均值\n */\n public static double mean(double[] data){\n return summation(data)/data.Length;\n }\n /**\n * 求和\n * @param {double[]} data 数据\n * @return {double} 总和\n */\n public static double summation(double[] data){\n double total = 0;\n for(int i =0;i<data.Length;i++){\n total+=data[i];\n }\n return total;\n }\n /**\n * [softmax description]\n * @param {[type]} double[] value [description]\n * @return {[type]} [description]\n */\n public static double[] softmax(double[] value){\n double[] softmax = null;\n double total = summation(value);\n for(int i =0;i<value.Length;i++){\n softmax[i] = sigmoid(Math.Exp(value[i]/total));\n }\n return softmax;\n }\n /**\n * [sigmoid description]\n * @param {[type]} double value [description]\n * @return {[type]} [description]\n */\n public static double sigmoid(double value){\n return 1.0/(1.0+Math.Pow(Math.E, -value));\n }\n public static double median(){\n return 0;\n }\n /**\n * 计算信息熵\n * @param {Array<double>} argument 参数\n */\n public static double H(double[] argument){\n double total = 0;\n for(int i =0;i<argument.Length;i++){\n total += -argument[i]*Math.Log(argument[i],2);\n }\n return total;\n }\n }\n}\n" }, { "alpha_fraction": 0.4091823697090149, "alphanum_fraction": 0.4241814613342285, "avg_line_length": 24.90995216369629, "blob_id": "eefffbe94b461b7f1ed83ef2c2a3d70bbbf81391", "content_id": "6aa371b851e9efe369d3a967f02d37b85a3e99f7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5783, "license_type": "permissive", "max_line_length": 77, "num_lines": 211, "path": "/statistics/python/src/Matrix.py", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Author: Jingyuexing\n# @Date: 2019-07-11 23:56:22\n# @Last Modified by: Admin\n# @Last Modified time: 2020-09-18 01:31:32\nimport Vector\n\n\nclass Matrix:\n \"\"\"docstring for Matrix\n row 行数\n col 列数\n data 矩阵数据\n \"\"\"\n\n def __init__(self, row=0, col=0, data=[]):\n if isinstance(row, (list, tuple)):\n self.row = len(row)\n self.col = len(row[0])\n self.data = row\n self.shape = (self.row, self.col)\n else:\n self.row = row\n self.col = col\n self.data = []\n for x in range(0, self.row):\n self.data.append([])\n for i in range(0, self.col):\n self.data[x].append([])\n self.shape = (self.row, self.col)\n\n def indentity(self):\n '''初始化为单位矩阵\n\n [description]\n\n Returns:\n [type] -- [description]\n '''\n for i in range(0, self.col):\n for j in range(0, self.row):\n if i == j:\n self.data[i][j] = 1\n else:\n self.data[i][j] = 0\n return self\n\n def product(self, Mb):\n \"\"\"矩阵相乘\n\n 其他矩阵和其自身相乘\n\n Arguments:\n Mb {Matrix} -- 相乘的矩阵\n\n Returns:\n Matrix -- 相乘后的矩阵\n \"\"\"\n if isinstance(Mb, Matrix) and self.col == Mb.row:\n i = 0\n tempMatrix = Matrix(self.row, Mb.col)\n while(i < self.row):\n j = 0\n while j < Mb.col:\n tempMatrix.data[i][j] = 0\n n = 0\n while n < self.col:\n tempMatrix.data[i][j] = tempMatrix.data[i][\n j] + (self.data[i][n] * Mb.data[n][j])\n n = n + 1\n j = j + 1\n i = i + 1\n return tempMatrix\n\n def hardamard(self, data):\n '''[summary]\n\n [description]\n\n Arguments:\n data {[type]} -- [description]\n\n Returns:\n | -- [description]\n '''\n if isinstance(data, Matrix):\n tempMatrix = Matrix(data.row, data.col)\n for i in range(0, data.col):\n for j in range(data.row):\n tempMatrix.data[i][j] = self.data[i][j] * data.data[i][j]\n return tempMatrix\n if isinstance(data, Vector):\n tempVector = []\n if len(data.data) == len(self.data):\n for i in range(0, len(data.data)):\n for j in range(0, len(self.row)):\n tempVector = data.data[i] * self.data[i][j]\n return tempVector\n\n def tr(self):\n '''[summary]\n\n 矩阵迹运算\n\n Arguments:\n Ma {Matrix} -- 需要迹运算的矩阵\n\n Returns:\n number -- 迹运算结果值\n '''\n total = 0\n for i in range(0, self.col):\n for j in range(0, self.row):\n if i == j:\n total = total + self.data[i][j]\n return total\n\n def frobenius(self):\n '''[summary]\n\n 矩阵范数\n\n Arguments:\n A {Matrix} -- 需要求范数的矩阵\n\n Returns:\n number -- 范数值\n '''\n tempNums = 0\n for i in range(0, self.row):\n for j in range(0, self.col):\n tempNums = tempNums + self.data[i][j]**2\n return tempNums**0.5\n\n def tran(self):\n \"\"\"矩阵转置\n A 需要被转置的矩阵\n \"\"\"\n NMatrix = Matrix(self.col, self.row)\n for i in range(0, self.row):\n for j in range(0, self.col):\n NMatrix.data[j][i] = self.data[i][j]\n return NMatrix\n\n def map(self):\n '''[summary]\n\n [description]\n\n Returns:\n list -- 返回数组\n '''\n tempArray = []\n for x in range(0, self.row):\n for i in range(0, self.col):\n tempArray.append(self.data[x][i])\n return tempArray\n\n def insertData(self, *args):\n '''[summary]\n\n 为矩阵插入数据\n\n Arguments:\n *args {Number} -- 数据\n '''\n n = 0\n for i in range(0, self.row):\n for j in range(0, self.col):\n if n >= len(args):\n if isinstance(args, (list, tuple)):\n for x in args[n]:\n self.data[i][j] = x\n self.data[i][j] = args[n]\n n = n + 1\n return self\n\n def pooling(self, value):\n '''矩阵池化\n ```md\n 矩阵池化是将一个大的矩阵划分成小的矩阵,然后选取小的矩阵当中的最大数形成新的矩阵\n ```\n [description]\n\n Arguments:\n value {int} -- 一个整型数据\n\n Returns:\n Matrix -- 返回池化后的矩阵\n '''\n if isinstance(value, Matrix):\n h, w = value.shape\n tempMatrix = Matrix(value.row, value.col)\n for i in range(h):\n for j in range(w):\n for n in range(0, h):\n s = self.data[i + n][j:j + w]\n if len(s[0]) == h:\n tempMatrix.insertData(s)\n elif isinstance(value, (tuple, list)):\n tempMatrix = Matrix(value)\n self.pooling(tempMatrix)\n return tempMatrix\n\n def flat(self):\n return self.map()\n\n\nif __name__ == \"__main__\":\n Cover = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n Cover.pooling([[1, 2, 3], [4, 5, 6]])\n" }, { "alpha_fraction": 0.6216216087341309, "alphanum_fraction": 0.6257796287536621, "avg_line_length": 27.352941513061523, "blob_id": "48774a5ae34aec2b81e8577bd8c1541d18459530", "content_id": "a7063853b0005de7e3c5e92e5cbafde71366b8d1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 481, "license_type": "permissive", "max_line_length": 57, "num_lines": 17, "path": "/statistics/TypeScript/src/softmax.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "import {Summation} from \"./Summation\";\nfunction exp(x:number):number{\n return Math.pow(Math.E,x);\n}\nfunction softmax([...value]:Array<number>):Array<number>{\n var softmaxValue:Array<number> = [];\n var cache:Array<number> = [];\n for(let x=0;x<value.length;x++){\n cache.push(exp(value[x]));\n }\n var total = Summation(cache);\n for(let x=0;x<value.length;x++){\n softmaxValue.push(exp(value[x])/total)\n }\n return softmaxValue;\n}\nexport {softmax}" }, { "alpha_fraction": 0.5491657853126526, "alphanum_fraction": 0.5491657853126526, "avg_line_length": 23.284482955932617, "blob_id": "da2b20d968d1d8741aafafb7edc82229d010aed5", "content_id": "a4ca1c39879f856249d3efc27d7e3308c98b67ab", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": true, "language": "TypeScript", "length_bytes": 3455, "license_type": "permissive", "max_line_length": 97, "num_lines": 116, "path": "/@type/MathLib.d.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "declare class Matrix{\n /**\n\t * 初始化为一个单位矩阵\n\t */\n Indentity():Matrix;\n /**\n\t * 元素对应乘积\n\t * @param data 矩阵或者向量\n\t */\n Hardamard(data:Matrix|Vector):Matrix;\n /**\n\t * 矩阵迹运算\n\t * @param {Matrix} matrix [迹运算对象]\n\t * @return {number} [返回总和]\n\t */\n Tr(matrix:Matrix):number;\n /**\n\t * 将矩阵降维为数组\n\t * @param {Matrix} matrix [需要降维的矩阵]\n\t * @return {Array<number>} [降维后返回的数组]\n\t */\n downDimensionality(matrix:Matrix):Array<number>;\n /**\n\t * 求矩阵范数\n\t * @param {Matrix} A [description]\n\t */\n\tfrobenius(A:Matrix):number;\n\t/**\n\t * 矩阵的转置\n\t * [tran description]\n\t * @param {Matrix} A [需被转置的矩阵]\n\t * @return {Matrix} [转置后的结果]\n\t */\n\ttran(A:Matrix):Matrix;\n}\ndeclare interface Vector{\n /**\n\t * [向量和]\n\t * @param {Vector} data [需要求和向量]\n\t * @return {Array<number>} [求和后结果]\n\t */\n add(data:Vector):Array<number>;\n /**\n * [向量差]\n * @param {Vector} data [向量]\n * @return {Array<Number>} [求差结果]\n */\n mult(data:Vector):Array<Number>;\n /**\n * [向量求模]\n * @param {Array<number>|Vector} data [需要求模的数据或矩阵]\n * @return {number} [模的值]\n */\n mod(data:Array<number>|Vector):number;\n /**\n * 该方法允许输入数字,向量对象和数组\n * 数字与向量相乘结果为向量,两个向量相乘结果为数值\n * [向量积]\n * @param {number|Array<number>|Vector} data [求积的矩阵或者数据]\n * @return {number} [结果值]\n */\n product(data:number|Array<number>|Vector):number|Array<number>;\n /**\n * 判断是否和另一个向量垂直,垂直返回真,不垂直返回假\n * @param {vector|Array<number>} dada [和向量比较的向量或数据]\n * @return {boolean} [结果]\n */\n isVertical(dada:Vector|Array<number>):boolean\n /**\n * 求两个向量的余弦,返回值为余弦值\n * [angle 向量夹角]\n * @param {vector|Array<number>} data [向量或者向量数据]\n * @return {number} [结果值]\n */\n angle(data:Vector|Array<number>):number;\n}\n\n/**\n * 求取两数组胡协方差\n *\n * @param {Array<number>} [...value_a]:Array<number> 第一个数组\n * @param {Array<number>} [...value_b]:Array<number> 第二个数组\n *\n * @return {number} 求得的协方差值\n */\ndeclare function Covariance([...value_a]:Array<number>,[...value_b]:Array<number>):Array<number>;\n\n/**\n * [expetation 期望值]\n * @param {Array<number>} ...x [样本空间]\n * @param {Array<number>} ...y [值域]\n * @return {number} [期望值]\n */\ndeclare function expetation([...x]:Array<number>,[...y]:Array<number>):number;\n\n\n/**\n * @param {Array<number>} ...input [需要求平均值的数据]\n * @return {number} 平均值\n */\ndeclare function Mean([...input]:Array<number>):number;\n\n/**\n * 分位数图\n * @param {Array<number>} ...values [输入值]\n */\ndeclare function QuantilePlot([...values]: Array<number>): Array<number>;\n\n/**\n * 中位数\n *\n * @param {Array} number 需要取中位数的数组\n *\n * @return {number} 取得的中位数\n */\ndeclare function Median(number:Array<number>):number\n" }, { "alpha_fraction": 0.5111111402511597, "alphanum_fraction": 0.5333333611488342, "avg_line_length": 16.384614944458008, "blob_id": "3d3f3bf9f02dd556917e1e0746f8ca11d4f22034", "content_id": "25c10d495cbf2aff0ee82e352dc206c0291ba063", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 241, "license_type": "permissive", "max_line_length": 27, "num_lines": 13, "path": "/statistics/es6/factorial.es6.js", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/**\n * [Factorial 阶乘]\n * @param {number} n [阶乘数]\n * @return {number} [阶乘值]\n */\nfunction Factorial(n){\n let total=1,k=n%1;\n for(let i=1;i<=n;i++){\n total*=i;\n }\n return total;\n}\nconsole.log(Factorial(10))" }, { "alpha_fraction": 0.6905829310417175, "alphanum_fraction": 0.6905829310417175, "avg_line_length": 12.9375, "blob_id": "fcaebdd43edd41c67c56d175827e93b81cbb8f08", "content_id": "2f3d9be094be7b67fa36502a2cb18ea82bfc7795", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 251, "license_type": "permissive", "max_line_length": 22, "num_lines": 16, "path": "/statistics/C/include/statistics.h", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "#ifndef _STATISTICS_H\n#define _STATISTICS_H\n#define isTrue(x) !!x\n//引入阶乘\n#include \"factorial.h\"\n//引入求最大公约数\n#include \"gcd.h\"\n// 引入sigmoid\n#include \"sigmoid.h\"\n\n#include \"Link.h\"\n\n#include \"LLink.h\"\n\n#include \"List.h\"\n#endif\n" }, { "alpha_fraction": 0.4760383367538452, "alphanum_fraction": 0.5654951930046082, "avg_line_length": 17.41176414489746, "blob_id": "bdfec5a4ae7467c7f51c9041f6adf39a1336c9c3", "content_id": "cb0587d074038f032e64bf52bd688c3d91f0b835", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 313, "license_type": "permissive", "max_line_length": 43, "num_lines": 17, "path": "/statistics/php/src/ILink.php", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "<?php\n\n/**\n * @Author: Admin\n * @Date: 2021-04-12 22:26:01\n * @Last Modified by: Admin\n * @Last Modified time: 2021-04-12 22:31:49\n *\n */\n interface ILink{\n function search($element);\n function remove($node);\n function append($node);\n function update($item,$element);\n }\n\n?>\n" }, { "alpha_fraction": 0.5717922449111938, "alphanum_fraction": 0.6109979748725891, "avg_line_length": 18.254901885986328, "blob_id": "6742d722b82292e2da19f0b86ef9f586578c2575", "content_id": "c136b39898008e7be6d2d4a56120d80dddfe68b3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 1990, "license_type": "permissive", "max_line_length": 51, "num_lines": 102, "path": "/statistics/Go/mathlib/Vector.go", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: jingyuexing\n* @Date: 2020-11-06 22:21:38\n* @Last Modified by: jingyuexing\n* @Last Modified time: 2020-11-06 22:24:55\n */\n\npackage mathlib\n\nimport (\n\t\"math\"\n)\n\n/**\n * 定义矩阵接口\n */\ntype vector interface {\n\tMult(data Vector) *Vector\n\tAdd(data Vector) *Vector\n\tMod() float64\n\tDot(data Vector) float64\n\tIsVertical(data Vector) bool\n\tIsHorizontal(data Vector) bool\n\tAngle(data Vector) float64\n}\n\n/**\n * 定义矩阵结构体\n */\ntype Vector struct {\n\tData []int64\n}\n\nfunc shorterLength(a []int64, b []int64) int {\n length := len(a)\n if len(b) < len(a) {\n length = len(b)\n }\n return length\n}\n\nfunc (v *Vector) Mult(data Vector) *Vector {\n\tnewVector := Vector{\n\t\tData: []int64{},\n\t}\n\tlength := shorterLength(v.Data, data.Data)\n\ttemp := make([]int64, 0)\n\tfor i := 0; i < length; i++ {\n\t\ttemp = append(temp, v.Data[i]-data.Data[i])\n\t}\n\tnewVector.Data = temp\n\treturn &newVector\n}\n\nfunc (v *Vector) Add(data Vector) *Vector {\n\tnewVector := Vector{\n\t\tData: []int64{},\n\t}\n\tlength := shorterLength(v.Data, data.Data)\n\ttemp := make([]int64, 0)\n\tfor i := 0; i < length; i++ {\n\t\ttemp = append(temp, v.Data[i]+data.Data[i])\n\t}\n\tnewVector.Data = temp\n\treturn &newVector\n}\n\nfunc (v *Vector) Mod() float64 {\n\tlength := len(v.Data)\n\ttotal := 0.0\n\tfor i := 0; i < length; i++ {\n\t\ttotal += math.Pow(float64(v.Data[i]), 2.0)\n\t}\n\treturn math.Sqrt(total)\n}\n\nfunc (v *Vector) dot(data Vector) float64 {\n\tlength := shorterLength(v.Data, data.Data)\n\ttotal := 0.0\n\tfor i := 0; i < length; i++ {\n\t\ttotal += float64(data.Data[i] * v.Data[i])\n\t}\n\treturn total\n}\n\nfunc (v *Vector) Angle(data Vector) float64 {\n\ttotal := 0.0\n\tif len(data.Data) == len(v.Data) {\n\t\tfor i := 0; i < len(v.Data); i++ {\n\t\t\ttotal += float64(v.Data[i] * data.Data[i])\n\t\t}\n\t}\n\treturn total / (v.Mod() * data.Mod())\n}\n\nfunc (v *Vector) IsHorizontal(data Vector) bool {\n\treturn v.Mod()*data.Mod() == 0\n}\n\nfunc (v *Vector) IsVertical(data Vector) bool {\n\treturn (v.Mod() * data.Mod() * v.Angle(data)) == 0\n}\n" }, { "alpha_fraction": 0.7017543911933899, "alphanum_fraction": 0.7017543911933899, "avg_line_length": 27, "blob_id": "9d3147e7706b857a0f41f22e48dc5019f90ff6fa", "content_id": "25be18ab22c27e6695b3abdee3fe7a36a91548e1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 57, "license_type": "permissive", "max_line_length": 28, "num_lines": 2, "path": "/index.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "import \"./calculus/index\";\nimport \"./statistics/index\";\n\n" }, { "alpha_fraction": 0.48134326934814453, "alphanum_fraction": 0.5932835936546326, "avg_line_length": 19.615385055541992, "blob_id": "3d9221181dc308eb890ffd486d29eeed0ac1ed65", "content_id": "1cb006fb70046951a1b8f7229fbc0c746dd46e06", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 268, "license_type": "permissive", "max_line_length": 42, "num_lines": 13, "path": "/statistics/python/src/Gamma.py", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Author: Jingyuexing\n# @Date: 2020-01-12 16:41:34\n# @Last Modified by: Jingyuexing\n# @Last Modified time: 2020-12-18 00:25:48\n\n\ndef gamma(value):\n if(value > 0):\n pass\n elif(isinstance(value, complex)):\n pass\n pass\n" }, { "alpha_fraction": 0.6811594367027283, "alphanum_fraction": 0.6811594367027283, "avg_line_length": 7.75, "blob_id": "d576b10134b631442bee9346e6374bb5a3672180", "content_id": "d4aa3247b7e745ede815ab0d944da5b50a003225", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 69, "license_type": "permissive", "max_line_length": 16, "num_lines": 8, "path": "/statistics/TypeScript/src/tree.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "interface TNode{\n\tparent:any;\n\tdata:any;\n\tchild:any;\n}\nclass Tree{\n\n}" }, { "alpha_fraction": 0.5756097435951233, "alphanum_fraction": 0.5804877877235413, "avg_line_length": 16.16666603088379, "blob_id": "6682132b965a3832d99817b61235c5fe771b12b5", "content_id": "57e51cc370d847d28db4d300b492311e627285a9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 215, "license_type": "permissive", "max_line_length": 35, "num_lines": 12, "path": "/statistics/es6/gcd.es6.js", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/**\n * gcd 最大公约数\n * @param {number} p [description]\n * @param {number} q [description]\n * @return {number} [description]\n */\nfunction gcd(p,q){\n\tif(q===0) return p;\n\tlet r =p % q;\n\treturn gcd(q,r);\n}\ng" }, { "alpha_fraction": 0.5874999761581421, "alphanum_fraction": 0.5874999761581421, "avg_line_length": 22.52941131591797, "blob_id": "07b21c9cb7fe24b84fd4ca63d5f535f3a7556dc1", "content_id": "4e44a13bb89a27ed885745a3a5c19f27dc6a9463", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 400, "license_type": "permissive", "max_line_length": 54, "num_lines": 17, "path": "/statistics/Java/com/mathlib/Rank.java", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "package com.mathlib;\n\npublic final class Rank<T>{\n public static double[] insertSort(double... args){\n double[] temArray={};\n\n return temArray;\n }\n public static double[] bubbleSort(double... args){\n double[] temArray={};\n return temArray;\n }\n public static double[] quickSort(double... args){\n double[] temArray={};\n return temArray;\n }\n}\n" }, { "alpha_fraction": 0.4411154091358185, "alphanum_fraction": 0.444378525018692, "avg_line_length": 26.19354820251465, "blob_id": "19caafd7c6556f7acff0e3374368b21df2be32f3", "content_id": "5a908d1d1b55a660289f082e7d7bb952768fbe9f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3729, "license_type": "permissive", "max_line_length": 73, "num_lines": 124, "path": "/statistics/es6/Vector.es6.js", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "class Vector{\n /**\n * 向量\n * @param {Array<number>} ...data [向量数据]\n */\n constructor([...data]){\n this.data =data;\n }\n /**\n * 向量的和\n * @param {vector} data [求和向量]\n * @return {Array<number>} [向量数据矩阵]\n */\n add(data){\n let tempAry=[];\n if(data instanceof Vector&& data.data.length==this.data.length){\n for(let i=0;i<data.data.length;i++){\n tempAry.push(this.data[i]+data.data[i])\n }\n return (this,tempAry);\n }\n }\n /**\n * 向量的差\n * @param {vector} data [向量]\n * @return {Array<Number>} [返回向量数组]\n */\n mult(data){\n let tempAry = [];\n if(data instanceof Vector && data.data.length==this.data.length){\n for(let i=0;i<data.data.length;i++){\n tempAry.push(data.data[i]-this.data[i]);\n }\n return (this,tempAry);\n }else{\n throw Error(\"参数必须是向量实例或两个向量长度需相同\");\n }\n }\n /**\n * 对向量求模\n * @param {Array<number>|Vector} data [求模的数据或向量]\n * @return {number} [结果]\n */\n mod(data){\n let total =0;\n if(data instanceof Array || data instanceof Vector){\n if(data instanceof Array){\n for(let i =0;i<data.length;i++){\n total+=data[i]**2\n }\n return (this,Math.sqrt(total));\n }\n if(data instanceof Vector){\n return this.mod(data.data);\n }else{\n throw TypeError(\"参数类型错误,参数必须是向量类或者数组类\");\n }\n }\n }\n /**\n * 向量积\n * @param {number|Array<number>|vector} data [求积的向量或者数组]\n * @return {number} [结果值]\n */\n product(data){\n let total =0;\n //倍数向量\n if(typeof data ===\"number\"){\n for(let i =0;i<this.data.length;i++){\n this.data[i]*=data;\n }\n }\n //乘积(点积)\n if(data instanceof Array){\n if(this.data.length==data.length){\n for(let i =0;i<data.length;i++){\n total+=(this.data[i]*data[i]);\n }\n return (this,total);\n }else{\n throw TypeError(\"参数长度不一致!\")\n }\n }\n //乘积(点积)\n if(data instanceof Vector){\n return (this,this.product(data.data));\n }\n }\n /**\n * 判断是否和另一个向量垂直,垂直返回真,不垂直返回假\n * @param {vector|Array<number>} dada [和向量比较的向量或数据]\n * @return {boolean} [结果]\n */\n isVertical(data){//点积的值为零返回真\n if(data instanceof Array){\n if(this.product(dada)==0){\n return true;\n }\n }\n if(data instanceof Vector){\n this.isVertical(dada.data)\n }\n return (this,false);\n }\n /**\n * [angle 向量夹角]\n * @param {vector|Array<number>} data [向量或者向量数据]\n * @return {number} [结果值]\n */\n angle(data){\n if(data instanceof Array){\n var total =0;\n if(data.length==this.data.length){\n for(let i=0;i<data.length;i++){\n total+=(this.data[i]*data[i]);\n }\n }\n return (this,total/(this.mod(data)*this.mod(this.data)));\n }\n if(data instanceof Vector){\n this.angle(data.data);\n }\n }\n}" }, { "alpha_fraction": 0.39336493611335754, "alphanum_fraction": 0.5260663628578186, "avg_line_length": 15.307692527770996, "blob_id": "2ae8282aea5418d34c44edab45f7ace9b586e5d7", "content_id": "b0561d6cddd9639269d774cedb71a250681b3f57", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 211, "license_type": "permissive", "max_line_length": 42, "num_lines": 13, "path": "/statistics/CS/src/Tensor.cs", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: Admin\n* @Date: 2020-07-23 18:53:15\n* @Last Modified by: Admin\n* @Last Modified time: 2020-07-23 19:30:00\n*/\nnamespace MathLib{\n class Tensor{\n Tensor(){\n \n }\n }\n}" }, { "alpha_fraction": 0.5829268097877502, "alphanum_fraction": 0.6560975313186646, "avg_line_length": 18.5238094329834, "blob_id": "b4a7d659ea1a54464dc4dc52c5cfd6b36e996a45", "content_id": "fe2e5371ef58808e9d8a1a3a6f70eee64c8a0630", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 410, "license_type": "permissive", "max_line_length": 60, "num_lines": 21, "path": "/statistics/Lua/src/Array.lua", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "-- @Author: admin\n-- @Date: 2022-03-14 15:19:53\n-- @Last Modified by: admin\n-- @Last Modified time: 2022-03-14 15:29:12\n\nlocal Array = {\n array={},\n length = 0\n}\nfunction Array:push(value)\n self.array = table.insert(self.array,self.length,value);\n self.length = #self.array\nend\n\nfunction Array:pop()\n table.remove(self.array,self.length)\n self.length = self.length - 1\nend\n\n\nreturn Array\n" }, { "alpha_fraction": 0.48750001192092896, "alphanum_fraction": 0.5714285969734192, "avg_line_length": 21.399999618530273, "blob_id": "f4fbd9d53c24b17dbcbae04700fab9c66c31946e", "content_id": "40394a800581bf329ce163b00e0e200c2e5e37d6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 560, "license_type": "permissive", "max_line_length": 43, "num_lines": 25, "path": "/statistics/python/src/softmax.py", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Author: Admin\n# @Date: 2020-01-10 01:34:45\n# @Last Modified by: jingyuexing\n# @Last Modified time: 2020-07-19 05:41:21\n\n\ndef exp(x=0):\n E = 2.718281828459045\n return E**x\n\n\ndef softmax(*values):\n softmaxValue = []\n thisValues = []\n total = 0\n for k in values:\n if isinstance(k, (list, tuple)):\n for m in k:\n thisValues.append(m)\n for i in thisValues:\n total = total + exp(i)\n for n in thisValues:\n softmaxValue.append(exp(n) / total)\n return softmaxValue\n" }, { "alpha_fraction": 0.612500011920929, "alphanum_fraction": 0.612500011920929, "avg_line_length": 12.333333015441895, "blob_id": "06499234bb024489e9016bc60d03889def4d64b6", "content_id": "e231041515e2825e8cd5496b20e2fcd7225a2d07", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 80, "license_type": "permissive", "max_line_length": 17, "num_lines": 6, "path": "/statistics/C/include/Map.h", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "#ifndef __MAP_H__\ntypedef struct{\n char *key;\n double value;\n}Map;\n#endif\n" }, { "alpha_fraction": 0.49399814009666443, "alphanum_fraction": 0.5438596606254578, "avg_line_length": 21.102041244506836, "blob_id": "368fc89c4d87e65a92acb9327db377a47daeecb0", "content_id": "12cb2108d245a669fcac800a26de2a0258815819", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1083, "license_type": "permissive", "max_line_length": 65, "num_lines": 49, "path": "/statistics/C/src/HashMap.c", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: Admin\n* @Date: 2021-03-28 00:25:58\n* @Last Modified by: admin\n* @Last Modified time: 2021-06-21 16:32:24\n*/\n#include \"../include/HashMap.h\"\n#include <inttypes.h>\nHashNode *newHashNode(void *key,void *value){\n HashNode *map = (HashNode *)malloc(sizeof(HashNode));\n map->next = NULL;\n map->right = NULL;\n map->left = NULL;\n return map;\n}\n\nint router(HashNode hashNode,void *table){\n return (sizeof(table) -1)& hashNode.hashValue;\n}\n\nunsigned int hashCode(const char *string){\n unsigned int full = 0xffffffff;\n int i = 0;\n while (string[i] != '\\0') {\n uint8_t byte = string[i];\n full = full ^ byte;\n for (uint8_t j = 8; j > 0; --j)\n {\n full = (full >> 1) ^ (0xEDB88320 & (-(full & 1)));\n }\n\n i++;\n }\n return full ^ 0xffffffff;\n}\nint hash(HashNode node){\n unsigned int h;\n return (node.key == NULL)?0:(h = hashCode(node.key))^(h>>16);\n}\n\nint tableSize(int length){\n int n = length;\n n |= n>>1;\n n |= n>>2;\n n |= n>>4;\n n |= n>>8;\n n |= n>>16;\n return n;\n}\n" }, { "alpha_fraction": 0.6177884340286255, "alphanum_fraction": 0.620192289352417, "avg_line_length": 13.857142448425293, "blob_id": "ebedd8b9f40ab7c48f03bafc094528671ed3759b", "content_id": "b79aa37dd59f31ef057e5c1116cb42e1f63ac542", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 416, "license_type": "permissive", "max_line_length": 48, "num_lines": 28, "path": "/statistics/Java/com/mathlib/List.java", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "package com.mathlib;\n\n// import java.util.List;\n\n\nclass List<T>{\n int length=0;\n T data;\n T next;\n List(final T...args){\n\n }\n public Boolean push(final double... args){\n return null;\n }\n public Boolean shift(){\n return true;\n }\n public int getLength(){\n return this.length;\n }\n\n}\nclass Main{\n public static void main(final String[] args) {\n final List<String> ina = new List<String>();\n }\n}\n" }, { "alpha_fraction": 0.7540983557701111, "alphanum_fraction": 0.7540983557701111, "avg_line_length": 7.714285850524902, "blob_id": "5c2196c7ff4ef0d9f2bd45f9d251344007c7028f", "content_id": "accc542ba5282c530d7cbf687d5b9409da59cab6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 99, "license_type": "permissive", "max_line_length": 11, "num_lines": 7, "path": "/statistics/C/README.md", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "# C实现\n\nList 单项链表\nLink 双向链表\nRBTree 红黑树\nBTree 二叉树\nHashMap 哈希表\n" }, { "alpha_fraction": 0.5598886013031006, "alphanum_fraction": 0.5598886013031006, "avg_line_length": 18.94444465637207, "blob_id": "81a35036eb6a50d941effc8bf1175a7eb27cf0a2", "content_id": "70ec1255eae9bcb4776116755c32a7aa92b2f443", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": true, "language": "TypeScript", "length_bytes": 882, "license_type": "permissive", "max_line_length": 52, "num_lines": 36, "path": "/@type/Matrix.d.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/// <reference path=\"./vector.d.ts\" />\ndeclare class Matrix{\n /**\n\t * 初始化为一个单位矩阵\n\t */\n Indentity():Matrix;\n /**\n\t * 元素对应乘积\n\t * @param data 矩阵或者向量\n\t */\n Hardamard(data:Matrix|Vector):Matrix;\n /**\n\t * 矩阵迹运算\n\t * @param {Matrix} matrix [迹运算对象]\n\t * @return {number} [返回总和]\n\t */\n Tr(matrix:Matrix):number;\n /**\n\t * 将矩阵降维为数组\n\t * @param {Matrix} matrix [需要降维的矩阵]\n\t * @return {Array<number>} [降维后返回的数组]\n\t */\n downDimensionality(matrix:Matrix):Array<number>;\n /**\n\t * 求矩阵范数\n\t * @param {Matrix} A [description]\n\t */\n\tfrobenius(A:Matrix):number;\n\t/**\n\t * 矩阵的转置\n\t * [tran description]\n\t * @param {Matrix} A [需被转置的矩阵]\n\t * @return {Matrix} [转置后的结果]\n\t */\n\ttran(A:Matrix):Matrix;\n}\n" }, { "alpha_fraction": 0.496595561504364, "alphanum_fraction": 0.5115751028060913, "avg_line_length": 20.598039627075195, "blob_id": "eb56bd97cd7b518ac2aeaecd4d7df9c63d06a144", "content_id": "057c323c26a142bf91e0e44214f90aa2a26a8069", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2381, "license_type": "permissive", "max_line_length": 72, "num_lines": 102, "path": "/statistics/python/src/List.py", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Author: Admin\n# @Date: 2020-09-18 01:33:20\n# @Last Modified by: Admin\n# @Last Modified time: 2020-09-18 02:08:01\n\n\nclass Node:\n parent = None\n child = None\n element = None\n \"\"\"docstring for Node\"\"\"\n\n def __init__(self, item):\n self.element = item\n\n\nclass List:\n \"\"\"docstring for List\"\"\"\n head = None\n length = 0\n posion = None\n def __init__(self):\n self.length = 0\n self.posion = self.head = Node(\"root\")\n\n def find(self, item):\n \"\"\"查找节点\n\n [description]\n\n Arguments:\n item {dynamic} -- 需要查找的元素存储的内容\n\n Returns:\n Node -- 返回查找到的节点\n \"\"\"\n currNode = self.head\n while(currNode.element != item):\n currNode = currNode.child\n return currNode\n\n def findPrevious(self, item):\n \"\"\"[summary]\n\n [description]\n\n Arguments:\n item {dynamic} -- [description]\n\n Returns:\n dynamic -- [description]\n \"\"\"\n node = self.find(item)\n while(not(node.child != None) and (node.child.element != item)):\n node = node.child\n return self\n\n def insert(self, ele, item=None):\n \"\"\"在列表中插入元素\n\n [description]\n\n Arguments:\n ele {dynamic} -- 需要插入的元素\n item {dynamic} -- 目标节点 在目标节点的后面插入值为ele的新节点\n\n Returns:\n List -- 列表\n \"\"\"\n if(item==None):\n currNode = self.posion\n else:\n currNode = self.find(item)\n newNode = Node(ele)\n newNode.parent = currNode #新的节点其父节点是\n self.posion = currNode.child = newNode\n self.length = self.length+1\n return self\n\n def remove(self, item):\n \"\"\"移除节点\n\n [description]\n\n Arguments:\n item {dynamic} -- 需要移除的节点\n\n Returns:\n List -- 完成操作后的列表\n \"\"\"\n prevNode = self.findPrevious(item)\n if(not (prevNode.child == None)):\n prevNode.child = prevNode.child.child\n self.length = self.length -1\n return self\n\n\nif __name__ == '__main__':\n l = List()\n l.insert(\"Hello word\").insert(\"Fuck\").insert(\"Nice\")\n print(l)\n" }, { "alpha_fraction": 0.46101438999176025, "alphanum_fraction": 0.4809487760066986, "avg_line_length": 24.403846740722656, "blob_id": "c2d83a18a2337f335941bd057199f03e5c024c97", "content_id": "256e2c9e980aca26f969ee02695ca47bb23dd4f2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4239, "license_type": "permissive", "max_line_length": 73, "num_lines": 156, "path": "/statistics/python/src/Vector.py", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Author: Jingyuexing\n# @Date: 2019-07-12 00:24:07\n# @Last Modified by: admin\n# @Last Modified time: 2021-06-24 20:58:06\n\n\nclass Vector:\n \"\"\"docstring for Vector\n 向量\n \"\"\"\n\n def __init__(self, data=[]):\n if isinstance(data, list):\n self.data = data\n else:\n print(\"Error:data type is not list\")\n\n def add(self, data):\n '''向量相加\n\n [description]\n\n Arguments:\n data {Vector} -- 相加的向量\n\n Returns:\n list -- 向量和值\n '''\n tempAry = []\n if isinstance(data, Vector) and len(data.data) == len(self.data):\n for i in range(0, len(data.data)):\n tempAry.append(self.data[i] + data.data[i])\n return tempAry\n\n def mult(self, data):\n \"\"\"[对向量两个向量进行求差]\n\n [description]\n\n Arguments:\n data {[Vector]} -- [相减向量]\n\n Returns:\n [list] -- [向量和结果值]\n \"\"\"\n tempAry = []\n if isinstance(data, Vector) and len(data.data) == len(self.data):\n for i in range(0, len(data.data)):\n tempAry.append(data.data[i] - self.data[i])\n return tempAry\n else:\n print(\"Error:参数必须是向量实例或两个向量长度需相同\")\n\n def mod(self, data):\n '''向量求模\n\n [description]\n\n Arguments:\n data {Vecotr} -- 向量\n\n Returns:\n number -- 模值\n '''\n total = 0\n if isinstance(data, Vector):\n for i in range(0, len(data.data)):\n total = total + data.data[i]**2\n return total**(1 / 2)\n else:\n return TypeError(data + \"is not Vector\")\n\n def product(self, data):\n '''向量乘积\n\n >>>Vector_1 = Vector([2,3,4,5,6,7])\n >>>Vector_2 = Vector([12,5,78,2,12])\n >>>Vector_2.product(Vector_1) return 748:number\n >>>Vector_2.product(8) return [96, 40, 624, 16, 96, 360]\n Arguments:\n data {number | list | Vector} -- 求点积或者向量乘积\n\n Returns:\n number|list -- 向量乘积值\n '''\n total = 0\n if isinstance(data, int) or isinstance(data, float):\n for i in range(0, len(self.data)):\n self.data[i] = self.data[i] * data\n if isinstance(data, list):\n if len(self.data) == data.__len__():\n for i in range(0, len(data)):\n total = total + self.data[i] * data[i]\n return total\n else:\n return TypeError(\"参数长度不一致!\")\n if isinstance(data, Vector):\n return self.product(data.data)\n\n def isVertical(self, data):\n '''判断是否和另外的向量垂直,垂直返回真,不垂直返回假\n\n\n\n Arguments:\n data { Vector|List<number> } -- 和自身比较的向量\n\n Returns:\n bool -- 是否垂直\n '''\n if isinstance(data, list) and self.product(data) == 0:\n return True\n if isinstance(data, Vector):\n self.isVertical(data.data)\n return False\n\n def map(self):\n return self.data\n\n def angle(self, data):\n '''向量夹角\n Arguments:\n data { Vector | list<number>} -- 向量或者向量数据\n\n Returns:\n number -- 结果值\n '''\n if isinstance(data, list):\n total = 0\n if len(data) == len(self.data):\n for i in range(0, len(data)):\n total = total + self.data[i] * data[i]\n return total / self.mod(data) * self.mod(self.data)\n if isinstance(data, Vector):\n self.angle(data.data)\n\n def insertData(self, *args):\n for i in args:\n self.data.append(i)\n return self\n\n def fill(self, value):\n \"\"\"[summary]\n\n [description]\n\n Arguments:\n value {[type]} -- [description]\n\n Returns:\n [type] -- [description]\n \"\"\"\n for x in range(len(self.data)):\n self.data[x] = value\n return self\n" }, { "alpha_fraction": 0.7838095426559448, "alphanum_fraction": 0.7838095426559448, "avg_line_length": 27.37837791442871, "blob_id": "2fac25b4a157ebd9041cb453cc7bdcdcf8133538", "content_id": "c23035cbda0adc597386148f1f82daa871980077", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1084, "license_type": "permissive", "max_line_length": 70, "num_lines": 37, "path": "/statistics/C/CMakeLists.txt", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "project(MathLib)\n\ninclude(CheckFunctionExists)\ninclude(CheckIncludeFiles)\ninclude_directories(\"include\")\n# 检查头文件是否存在\ncheck_include_files(binTree.h HAVE_BINTREE)\n# 检查函数是否存在\ncheck_function_exists()\n# generate the share library from LINK\nadd_library(Link SHARED src/Link.c)\ntarget_include_directories(Link PUBLIC ${PROJECT_SOURCE_DIR}/include)\n\n# generate the share library from LIST\nadd_library(List SHARED src/List.c)\ntarget_include_directories(List PUBLIC ${PROJECT_SOURCE_DIR}/include)\n# generate the share library from LLINK\nadd_library(LLink SHARED src/LLink.c)\ntarget_include_directories(LLink PUBLIC ${PROJECT_SOURCE_DIR}/include)\n\n# set install direactories\nif(NOT DEFINED INSTALL_LIB_DIR)\n set(INSTALL_LIB_DIR lib)\nendif()\nif(NOT DEFINED INSTALL_BIN_DIR)\n set(INSTALL_BIN_DIR bin)\nendif()\nif(NOT DEFINED INSTALL_INCLUDE_DIR)\n set(INSTALL_INCLUDE_DIR include)\nendif()\nset(LIBRARY_OUTPUT_PATH ${INSTALL_LIB_DIR})\nset(EXECUTABLE_OUTPUT_PATH ${INSTALL_BIN_DIR})\n\n\n# randomstr test\n\nadd_executable(randomstr_test test/RandomString_test.c)\n" }, { "alpha_fraction": 0.6335403919219971, "alphanum_fraction": 0.6832298040390015, "avg_line_length": 17, "blob_id": "37f53b0a3f20944854cd91523fb8db7dd189d243", "content_id": "bf3f150d9076529787080710d8af10c427903f78", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 181, "license_type": "permissive", "max_line_length": 36, "num_lines": 9, "path": "/statistics/TypeScript/src/angule.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "function deg2rad(deg:number):number{\n\t//角度转弧度\n\t// body...\n\treturn deg*(Math.PI/180);\n}\nfunction rad2deg(rad:number):number{\n\t//弧度转角度\n\treturn rad*(180/Math.PI);\n}" }, { "alpha_fraction": 0.5134575366973877, "alphanum_fraction": 0.5776397585868835, "avg_line_length": 20, "blob_id": "ed43445c4c7ff625d7cd70b467260ebcc756a91f", "content_id": "aadc02a27e5b70b6c004e4d6faf6c2105b235ab8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 483, "license_type": "permissive", "max_line_length": 55, "num_lines": 23, "path": "/statistics/python/src/var.py", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Author: Jingyuexing\n# @Date: 2020-05-30 03:45:48\n# @Last Modified by: jingyuexing\n# @Last Modified time: 2020-07-19 05:46:11\n\nimport Mean\nimport math\n\n\ndef variance(*arg):\n for i in arg:\n data = i\n mean = Mean.mean(data)\n total = 0\n for i in range(len(data)):\n total = total + math.pow(data[i] - mean, 2)\n total = total / len(data)\n return total\n\n\ndef cov(data):\n return math.sqrt(variance(data))\n" }, { "alpha_fraction": 0.6190476417541504, "alphanum_fraction": 0.6190476417541504, "avg_line_length": 30.66666603088379, "blob_id": "d15540ae13f66b67253597adc8e5f180a1ac3c82", "content_id": "6c3917f710e15b115b8a2479a9901e74f0a5a705", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": true, "language": "TypeScript", "length_bytes": 189, "license_type": "permissive", "max_line_length": 62, "num_lines": 6, "path": "/@type/main.d.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/// <reference path=\"Mean.d.ts\" />\n/// <reference path=\"Matrix.d.ts\" />\n/// <reference path=\"vector.d.ts\" />\ninterface main{\n\texpetation([...x]:Array<number>,[...y]:Array<number>):number;\n}" }, { "alpha_fraction": 0.4482758641242981, "alphanum_fraction": 0.6091954112052917, "avg_line_length": 16.399999618530273, "blob_id": "f184de9f40e8ca91836ee4c35ce299f4c46cda06", "content_id": "aacb7dc50d6486d3f3569c26a3cb598998f527ff", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 174, "license_type": "permissive", "max_line_length": 42, "num_lines": 10, "path": "/statistics/CS/src/Vector.cs", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: Admin\n* @Date: 2020-07-23 18:53:48\n* @Last Modified by: Admin\n* @Last Modified time: 2020-09-21 01:26:32\n*/\nnamespace MathLib{\n class Vector<T>{\n }\n}\n" }, { "alpha_fraction": 0.4475524425506592, "alphanum_fraction": 0.6433566212654114, "avg_line_length": 19.428571701049805, "blob_id": "5c578ec6fd086a7b59ec0603eb9a7303305cd559", "content_id": "47313676a8e5a269ca172712239fa04a8003d7ef", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 143, "license_type": "permissive", "max_line_length": 42, "num_lines": 7, "path": "/statistics/Go/mathlib/Link_test.go", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: Admin\n* @Date: 2021-05-07 23:48:36\n* @Last Modified by: Admin\n* @Last Modified time: 2021-05-07 23:48:53\n */\npackage mathlib\n" }, { "alpha_fraction": 0.7093023061752319, "alphanum_fraction": 0.7093023061752319, "avg_line_length": 16.399999618530273, "blob_id": "e820c4be7c8a72a6d2a29a5213560ba6a9353016", "content_id": "a005d518d32a527a7ac943e54007271b25f386d0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 94, "license_type": "permissive", "max_line_length": 26, "num_lines": 5, "path": "/statistics/C/include/factorial.h", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "#ifndef _FACTORIAL_H\n#define _FACTORIAL_H\n// 定义阶乘\nlong int Factorial(int n);\n#endif" }, { "alpha_fraction": 0.5138888955116272, "alphanum_fraction": 0.579365074634552, "avg_line_length": 30.5, "blob_id": "9fa488c6120d725550ee85aab49b0a67a1db4816", "content_id": "0bf70eaae6f7925cc616fe3c88e56891e6bae8f3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 504, "license_type": "permissive", "max_line_length": 65, "num_lines": 16, "path": "/statistics/python/src/weigth_variance.py", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Author: Admin\n# @Date: 2020-01-10 01:44:06\n# @Last Modified by: Jingyuexing\n# @Last Modified time: 2020-10-29 21:52:16\n\n\ndef weigthVariance(numberData=[], weigth=[]):\n totalWigth, totalNumebr = 0, 0\n if numberData.__len__() == weigth.__len__():\n i = 0\n while i <= len(numberData):\n totalWigth = totalWigth + weigth[i]\n totalNumebr = totalNumebr + numberData[i] * weigth[i]\n i = i + 1\n return totalNumebr / totalWigth\n" }, { "alpha_fraction": 0.38684019446372986, "alphanum_fraction": 0.4215473532676697, "avg_line_length": 29.733333587646484, "blob_id": "449f52c4614f8114a5a47482eb4c0d0702bf8cb6", "content_id": "93a1348630ffdfad40320b6052a697a730442239", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1391, "license_type": "permissive", "max_line_length": 63, "num_lines": 45, "path": "/statistics/python/src/Rnak.py", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Author: Admin\n# @Date: 2020-01-10 00:58:05\n# @Last Modified by: Jingyuexing\n# @Last Modified time: 2020-12-03 14:07:09\n\n\nclass Rank(object):\n \"\"\"排序算法\"\"\"\n @staticmethod\n def insert(self, data=[]):\n if isinstance(data, list):\n for i in range(2, len(data)):\n key = data[i]\n j = i - 1\n while i > 0 and data[j] > key:\n data[j + 1] = data[j]\n j = j - 1\n data[j + 1] = key\n return data\n @staticmethod\n def bubbleSort(self, data=[]):\n for i in range(1, len(data)):\n for j in range(0, len(data) - i):\n if data[j] > data[j + 1]:\n data[j], data[j + 1] = data[j + 1], data[j]\n return data\n @staticmethod\n def quickSort(self, array=[], begin=0, end=0):\n i, j, key = begin, end, array[begin]\n while i < j:\n while i < j and array[j] >= key:\n j = j - 1\n if i < j:\n array[i] = array[j]\n i = i - 1\n while i < j and array[i] < key:\n i = i + 1\n if i < j:\n array[j] = array[i]\n j = j - 1\n array[i] = key\n self.quickSort(array, begin, i - 1)\n self.quickSort(array, i + 1, end)\n return array\n" }, { "alpha_fraction": 0.5033407807350159, "alphanum_fraction": 0.5345211625099182, "avg_line_length": 20.90243911743164, "blob_id": "42bf61de1be63f4eba9d39c4f0db21950a5d4877", "content_id": "4508662bac99dbd066fb4783e9e537a15a51d4c9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 898, "license_type": "permissive", "max_line_length": 46, "num_lines": 41, "path": "/statistics/php/src/LLink.php", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "<?php\n\n/**\n * @Author: Admin\n * @Date: 2021-04-12 23:34:50\n * @Last Modified by: jingyuexing\n * @Last Modified time: 2021-05-03 15:57:55\n */\nrequire \"ILink.php\";\nclass Node{\n var $next;\n var $content;\n var $parent;\n}\nclass LLink implements ILink{\n var $head;\n var $pos;\n function LLink(){\n $this->pos = $this->head = new Node();\n }\n function search($element){\n $currNode = $this->head;\n while($currNode->content!=$element){\n $currNode = $currNode->next;\n }\n return $currNode;\n }\n function remove($node=new Node()){\n $node->parent = $node->next;\n unset($node);\n }\n function append($node = new Node()){\n $this->pos->next = $node;\n $this->pos = $node;\n }\n function update($item,$element){\n $currNode = $this->search($item);\n $currNode->content = $element;\n }\n}\n?>\n" }, { "alpha_fraction": 0.6976743936538696, "alphanum_fraction": 0.6976743936538696, "avg_line_length": 13.666666984558105, "blob_id": "339b2f211aa39389cb8d2f7ab68084f6df4cb24c", "content_id": "bcd574423937a5ed3d3c107c2950dcd149388124", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": true, "language": "TypeScript", "length_bytes": 43, "license_type": "permissive", "max_line_length": 22, "num_lines": 3, "path": "/@type/product.d.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "interface product{\n constructor():any;\n}" }, { "alpha_fraction": 0.47376543283462524, "alphanum_fraction": 0.47773367166519165, "avg_line_length": 28.842105865478516, "blob_id": "594440b1a823774b4442de823b4c07a999828712", "content_id": "d5ebf92cbed285ef843dd74187753db40196a133", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4998, "license_type": "permissive", "max_line_length": 80, "num_lines": 152, "path": "/statistics/TypeScript/src/Vector.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "import {Matrix} from \"./Matrix\";\nclass Vector{\n data:Array<number>;\n /**\n * 向量\n * @param {Array<number>} ...data [向量数据]\n */\n constructor([...data]:Array<number>){\n this.data =data;\n }\n /**\n * 向量的和\n * @param {vector} data [求和向量]\n * @return {Array<number>} [向量数据矩阵]\n */\n add(data:Vector):Array<number>|undefined{\n let tempAry:Array<number>=[];\n if(data instanceof Vector&& data.data.length==this.data.length){\n for(let i=0;i<data.data.length;i++){\n tempAry.push(this.data[i]+data.data[i])\n }\n return tempAry;\n }\n }\n /**\n * 向量的差\n * @param {vector} data [向量]\n * @return {Array<Number>} [返回向量数组]\n */\n mult(data:Vector):Array<Number>{\n let tempAry:Array<number> = [];\n if(data instanceof Vector && data.data.length==this.data.length){\n for(let i=0;i<data.data.length;i++){\n tempAry.push(data.data[i]-this.data[i]);\n }\n return (this,tempAry);\n }else{\n throw Error(\"参数必须是向量实例或两个向量长度需相同\");\n }\n }\n /**\n * 对向量求模\n * @param {Array<number>|Vector} data [求模的数据或向量]\n * @return {number} [结果]\n */\n mod(data:Array<number>|Vector):number|undefined{\n let total:number =0;\n if(data instanceof Array || data instanceof Vector){\n if(data instanceof Array){\n for(let i =0;i<data.length;i++){\n total+=data[i]**2\n }\n return (this,Math.sqrt(total));\n }\n if(data instanceof Vector){\n return this.mod(data.data);\n }else{\n throw TypeError(\"参数类型错误,参数必须是向量类或者数组类\");\n }\n }\n }\n /**\n * 向量积\n * 向量点乘 dot product 为 x_{1}x_{2} + y_{1}y_{2}\n * 向量叉乘 为 |v_{1}|* |v_{2}| * Sin(angle)\n * @param {number|Array<number>|vector} data [求积的向量或者数组]\n * @return {number} [结果值]\n */\n dotProduct(data:number|Array<number>|Vector):number|Array<number>|undefined{\n let total:number =0;\n //倍数向量\n if(typeof data ===\"number\"){\n for(let i =0;i<this.data.length;i++){\n this.data[i]*=data;\n }\n }\n //乘积(点积)\n if(data instanceof Array){\n if(this.data.length==data.length){\n for(let i =0;i<data.length;i++){\n total+=(this.data[i]*data[i]);\n }\n return (this,total);\n }else{\n throw TypeError(\"参数长度不一致!\")\n }\n }\n //乘积(点积)\n if(data instanceof Vector){\n return (this,this.dotProduct(data.data));\n }\n }\n /**\n * 向量的叉乘 可视作 一行 n列矩阵相乘 向量 A 向量 B 相乘\n * 可视作 A_{n*m} * B_{n*m} = A_{m*n} * B_{n*m}\n *\n * @param {number|Array<number>|Vector} data [description]\n * @return {any} [description]\n */\n product(data:number|Array<number>|Vector):any{\n }\n /**\n * 判断是否和另一个向量垂直,垂直返回真,不垂直返回假\n * @param {vector|Array<number>} dada [和向量比较的向量或数据]\n * @return {boolean} [结果]\n */\n isVertical(dada:Vector|Array<number>):boolean{//点积的值为零返回真\n if(dada instanceof Array){\n if(this.dotProduct(dada)==0){\n return true;\n }\n }\n if(dada instanceof Vector){\n this.isVertical(dada.data)\n }\n return (this,false);\n }\n /**\n * [isHorizontal description]\n * 向量的叉积为零,可判定此两个向量平行\n * @param {Vector|Array<number>} data [description]\n * @return {boolean} [description]\n */\n isHorizontal(data:Vector):boolean{\n let product = this.mod(this.data)*this.mod(data) * this.angle(data);\n if(product == 0){\n return true;\n }else{\n return false;\n }\n }\n /**\n * [angle 向量夹角]\n * @param {vector|Array<number>} data [向量或者向量数据]\n * @return {number} [结果值]\n */\n angle(data:Vector|Array<number>):number{\n if(data instanceof Array){\n var total:number =0;\n if(data.length==this.data.length){\n for(let i=0;i<data.length;i++){\n total+=(this.data[i]*data[i]);\n }\n }\n return (this,total/(this.mod(data)*this.mod(this.data)));\n }\n if(data instanceof Vector){\n this.angle(data.data);\n }\n }\n}\nexport {Vector};\n" }, { "alpha_fraction": 0.6899999976158142, "alphanum_fraction": 0.6899999976158142, "avg_line_length": 22.076923370361328, "blob_id": "0d50e5654873ed2f5683f791011157022d8d0115", "content_id": "b640a9737e608ed1a97a17486903b38695a9325a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 300, "license_type": "permissive", "max_line_length": 52, "num_lines": 13, "path": "/statistics/C/include/Link.h", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "#ifndef __LINK__\n#define __LINK__\n#include <stdlib.h>\ntypedef struct Link{\n struct Link *child;\n struct Link *parent;\n int index;\n double element;\n}Node;\nNode *insert(Node *root,double item,double element);\nNode *remove(Node *root,double item);\nNode *find(Node *root,double item);\n#endif\n" }, { "alpha_fraction": 0.7078651785850525, "alphanum_fraction": 0.7078651785850525, "avg_line_length": 17, "blob_id": "8042cb3bbe6ed405630ef73ff68c1e6e434e1d0b", "content_id": "8df5bffb968c0364e2d2bb97fdda3976981180f0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 131, "license_type": "permissive", "max_line_length": 45, "num_lines": 5, "path": "/statistics/TypeScript/src/Standard_Deviation.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "export class StandardDeviation{\n\t/**\n\t * 标准差,又称标准偏差、均方差,英语:Standard Deviation,缩写SD\n\t */\n}" }, { "alpha_fraction": 0.483146071434021, "alphanum_fraction": 0.5355805158615112, "avg_line_length": 21.25, "blob_id": "eb9a8630febe2a0b8a74f8d305db973e633bd84a", "content_id": "3498146c5037031034cbf28f0cb0461490f410b0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 534, "license_type": "permissive", "max_line_length": 57, "num_lines": 24, "path": "/statistics/CS/src/Rank.cs", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: Jingyuexing\n* @Date: 2020-12-04 10:51:38\n* @Last Modified by: Jingyuexing\n* @Last Modified time: 2020-12-04 10:55:18\n*/\n\nnamespace Mathlib{\n class Rank{\n public static double[] insertSort(double[] data){\n double[] final=null;\n return final;\n }\n public static double[] bubbleSort(){\n double[] final=null;\n return final;\n\n }\n public static double[] quickSort(){\n double[] final=null;\n return final;\n }\n }\n}\n" }, { "alpha_fraction": 0.5643410682678223, "alphanum_fraction": 0.5798449516296387, "avg_line_length": 17.457143783569336, "blob_id": "e87941d55c89e502d7d961cb13017fa967d8af3a", "content_id": "a547d930c86cad774a4ec59a6a51b22d00f68af8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 749, "license_type": "permissive", "max_line_length": 86, "num_lines": 35, "path": "/statistics/TypeScript/src/Median.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/**\n * 中位数\n */\nimport {Rank} from \"./Rank\"\n/**\n * 取整\n * @param {x} x [输入数]\n * @return {~~x} [返回数字]\n */\nfunction int(x:number):number{\n\treturn ~~x;\n}\n/**\n * 中位数\n *\n * @param {Array} number 需要取中位数的数组\n *\n * @return {number} 取得的中位数\n */\nfunction Median(number:Array<number>):number{\n\tvar number = Rank.insert(number);\n\tif(number.length%2==0){\n\t\t\t/**\n\t\t\t * 当数组长度为偶数,中位数为\n\t\t\t */\n\t\t\treturn number[number.length/2];\n\t}else{\n\t\t\t/**\n\t\t\t * 数组长度为奇数,返回\n\t\t\t * @param {[number]} number[number.length/2]+number[number.length/2+1 [description]\n\t\t\t */\n\t\t\treturn (number[int(number.length/2)]+number[int(number.length/2)+1])/2;\n\t}\n}\nexport {Median};" }, { "alpha_fraction": 0.4170854389667511, "alphanum_fraction": 0.5577889680862427, "avg_line_length": 15.666666984558105, "blob_id": "9b21ec472773b7796d50ce76e1956ac35197972a", "content_id": "e9e5952e39f59283852181d3aa7012bee387b0f6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 199, "license_type": "permissive", "max_line_length": 42, "num_lines": 12, "path": "/statistics/CS/src/Gcd.cs", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: Admin\n* @Date: 2020-07-23 18:50:31\n* @Last Modified by: Admin\n* @Last Modified time: 2020-07-23 18:56:00\n*/\nnamespace MathLib{\n class Gcd{\n static Gcd(){\n }\n }\n}" }, { "alpha_fraction": 0.4925742447376251, "alphanum_fraction": 0.5173267126083374, "avg_line_length": 15.15999984741211, "blob_id": "91a9bac2c2bb7f2545eeabeb3dcc1f8ca9d14cd0", "content_id": "f8d31e5303482b5f83301e779949168cbb22f60e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 476, "license_type": "permissive", "max_line_length": 39, "num_lines": 25, "path": "/statistics/C/src/binExp.c", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/**\n * 快速幂\n * 其核心思想是将n转化为几个2次幂的和而后进行对乘机求和\n * @param int a 底数\n * @param int n 指数\n *\n * @return double 运算结果\n */\n#include <stdio.h>\n#include <sys/timeb.h>\ndouble binExp(long double a,int n){\n double k = 1.0;\n while (n){\n if((n&1)==1){\n k *= a;\n }\n a *= a;\n n = n>>1;\n }\n return k;\n}\nint main(int argc, char const *argv[]){\n printf(\"%lf\",binExp(2,44));\n return 0;\n}\n" }, { "alpha_fraction": 0.5309992432594299, "alphanum_fraction": 0.5331874489784241, "avg_line_length": 21.47541046142578, "blob_id": "1de773eec6752895b6e24f6124032ca63182fa9c", "content_id": "63c578836487dec4197bb1d6a6e0f6c28a3180af", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1395, "license_type": "permissive", "max_line_length": 65, "num_lines": 61, "path": "/statistics/Java/com/mathlib/Matrix.java", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "package com.mathlib;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nclass Matrix<T>{\n private List<List<T>> data;\n public int row;\n public int col;\n Matrix(int row,int col){\n this.col = col;\n this.row = row;\n this.data = new ArrayList<>(row);\n for(int i = 0; i< this.col;i++){\n List<T> columnItem = new ArrayList<>(this.row);\n this.data.set(i, columnItem);\n }\n }\n Matrix(int row){\n this.row = row;\n this.col = row;\n }\n Matrix(List<List<T>> data){\n }\n Matrix<T> indentity(){\n Matrix<T> tempMatrix = new Matrix<T>(this.col,this.row);\n \n return tempMatrix;\n }\n Matrix<T> product(Matrix<T> data){\n Matrix<T> tempMatrix = new Matrix<T>(this.row, data.col);\n\n return tempMatrix;\n }\n Matrix<T> hardamard(Matrix<T> data){\n Matrix<T> tempMatrix = new Matrix<T>(data.row,data.col);\n\n return tempMatrix;\n }\n T tr(Matrix<T> matrix){\n \n return null;\n }\n void downDimesionality(Matrix<T> matrix){\n }\n T frobenius(Matrix<T> A){\n double num = 0.0;\n return null;\n }\n /**\n * 矩阵转置\n * @return Matrix 返回转置后的矩阵\n */\n Matrix<T> tran(){\n Matrix<T> NMatrix = new Matrix<T>(this.col,this.row);\n return NMatrix;\n }\n void flat(){\n\n }\n}\n" }, { "alpha_fraction": 0.6868686676025391, "alphanum_fraction": 0.6868686676025391, "avg_line_length": 32.33333206176758, "blob_id": "0ab9a97cc02fe7e3906e08e96b79b30d144079bc", "content_id": "9c1e48da3e6bf5bf8fabb3fbf5f5e67cc5f292fa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": true, "language": "TypeScript", "length_bytes": 99, "license_type": "permissive", "max_line_length": 81, "num_lines": 3, "path": "/@type/covariance.d.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "interface main{\n\tCovariance([...value_a]:Array<number>,[...value_b]:Array<number>):Array<number>;\n}" }, { "alpha_fraction": 0.7464788556098938, "alphanum_fraction": 0.7464788556098938, "avg_line_length": 27.600000381469727, "blob_id": "4ebab7fc259337e890661f0a155d0f9b235d66b0", "content_id": "3feda88a7b3e3744d65f962267355d69b17cc1de", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 142, "license_type": "permissive", "max_line_length": 48, "num_lines": 5, "path": "/statistics/TypeScript/src/subFactorial.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "import {Factorial as Fac} from \"./Factorial\"\nfunction subFactorial(x:number,n:number):number{\n\treturn Fac(x)/Fac(x-n);\n}\nexport {subFactorial}" }, { "alpha_fraction": 0.6285714507102966, "alphanum_fraction": 0.6285714507102966, "avg_line_length": 19, "blob_id": "3a9ddc6b52c4c09b2019de1042ed61b5d28705a3", "content_id": "2f86d22f8337e94d8b5770133a98a874d2d22f10", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 140, "license_type": "permissive", "max_line_length": 27, "num_lines": 7, "path": "/statistics/C/include/stack.h", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "#ifndef __MATHLIB_STACK_H__\n#define __MATHLIB_STACK_H__\ntypedef struct Stack{\n // struct Stack New();\n // void Push();\n}Stack;\n#endif\n" }, { "alpha_fraction": 0.6025104522705078, "alphanum_fraction": 0.6066945791244507, "avg_line_length": 19, "blob_id": "11fb2b283da7906022c4a103d8bb374794ccb095", "content_id": "1a21073094d4b6fc7feeff981b7ec469f3158a71", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 249, "license_type": "permissive", "max_line_length": 40, "num_lines": 12, "path": "/statistics/TypeScript/src/gcd.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/**\n * gcd 最大公约数\n * @param {number} p [description]\n * @param {number} q [description]\n * @return {number} [description]\n */\nfunction gcd(p:number,q:number):number {\n\tif(q===0) return p;\n\tlet r =p % q;\n\treturn gcd(q,r);\n}\nexport {gcd};" }, { "alpha_fraction": 0.5724138021469116, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 15.222222328186035, "blob_id": "8d898911f22cef05302c705f08688444c0b4bdeb", "content_id": "deb40e39036b2b52b2b52810e6cafa9177475a3e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 145, "license_type": "permissive", "max_line_length": 34, "num_lines": 9, "path": "/statistics/TypeScript/src/sigmoid.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/**\n * \n * @param x inputValue\n * @return number 0 to 1\n */\nfunction sigmoid(x:number):number{\n return 1/(1+Math.E**(-x));\n}\nexport {sigmoid};" }, { "alpha_fraction": 0.5982532501220703, "alphanum_fraction": 0.5982532501220703, "avg_line_length": 13.135802268981934, "blob_id": "3bb6c71389ecd71f49ef57b6631db2297c0a13fe", "content_id": "b14a3d44d373c3238964cfc1a20c471a024a688d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1251, "license_type": "permissive", "max_line_length": 45, "num_lines": 81, "path": "/statistics/C/src/matrix.c", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "#include \"matrix.h\"\n#include <stdio.h>\n\n/**\n * 初始化为单位矩阵\n * @return [description]\n */\nMatrix Indentity(Matrix *ma){\n auto Matrix m;\n auto Matrix *s;\n m.Product(s);\n s->Hardamard(s);\n return *ma;\n\n}\n\n/**\n * 矩阵相乘\n * @param matrix 需要相乘的矩阵\n * @return [description]\n */\nMatrix Product(Matrix matrix){\n\n}\n\n/**\n * [Hardamard description]\n * @param data [description]\n * @return [description]\n */\nMatrix Hardamard(Matrix data){\n Matrix matrix;\n}\n\n\n/**\n * 矩阵迹运算\n * @param matrix [description]\n * @return [description]\n */\nMatrix Tr(Matrix matrix){\n}\nMatrix DownDimensionality(Matrix matrix){\n}\n\n/**\n * 矩阵范数\n * @param matrix 矩阵自身\n * @return 范数值\n */\ndouble* Frobenius(Matrix *matrix){\n\n}\n\n/**\n * [Tran description]\n * @param matrix [description]\n * @return [description]\n */\nMatrix Tran(Matrix *matrix){\n\n}\n/**\n * [Flat description]\n * @param matrix [description]\n * @return [description]\n */\ndouble* Flat(Matrix *matrix){\n\n}\n\n/**\n * 矩阵池化\n * @param matrix 矩阵自身\n * @param arry 数组\n * @return 返回池化后的矩阵\n */\nMatrix *pooling(Matrix *matrix,double *arry){\n Matrix *ma;\n return ma;\n}\n" }, { "alpha_fraction": 0.539130449295044, "alphanum_fraction": 0.5449275374412537, "avg_line_length": 20.625, "blob_id": "5bf5ed895a856a6a6c46df410da701cb2cb73b41", "content_id": "06ee799d95c1cb69a13e68608f8a864dfeee6840", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 369, "license_type": "permissive", "max_line_length": 70, "num_lines": 16, "path": "/statistics/TypeScript/src/expetation.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/**\n * [expetation 期望值]\n * @param {Array<number>} ...x [样本空间]\n * @param {Array<number>} ...y [值域]\n * @return {number} [期望值]\n */\nfunction expetation([...x]:Array<number>,[...y]:Array<number>):number{\n\tlet sum=0;\n\tif(x.length==y.length){\n\t\tfor(let i =0;i<y.length;i++){\n\t\t\tsum += x[i]*y[i];\n\t\t}\n\t}\n\treturn sum;\n}\nexport {expetation};" }, { "alpha_fraction": 0.5153061151504517, "alphanum_fraction": 0.5153061151504517, "avg_line_length": 27.658536911010742, "blob_id": "d0aaac3b3eed030430047c26b663081d2127588c", "content_id": "407b9b4ba653de2517d14d8122b3ae5175fce835", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": true, "language": "TypeScript", "length_bytes": 1500, "license_type": "permissive", "max_line_length": 67, "num_lines": 41, "path": "/@type/vector.d.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": " declare class Vector{\n\t/**\n\t * [向量和]\n\t * @param {Vector} data [需要求和向量]\n\t * @return {Array<number>} [求和后结果]\n\t */\n add(data:Vector):Array<number>;\n /**\n * [向量差]\n * @param {Vector} data [向量]\n * @return {Array<Number>} [求差结果]\n */\n mult(data:Vector):Array<Number>;\n /**\n * [向量求模]\n * @param {Array<number>|Vector} data [需要求模的数据或矩阵]\n * @return {number} [模的值]\n */\n mod(data:Array<number>|Vector):number;\n /**\n * 该方法允许输入数字,向量对象和数组\n * 数字与向量相乘结果为向量,两个向量相乘结果为数值\n * [向量积]\n * @param {number|Array<number>|Vector} data [求积的矩阵或者数据]\n * @return {number} [结果值]\n */\n product(data:number|Array<number>|Vector):number|Array<number>;\n /**\n * 判断是否和另一个向量垂直,垂直返回真,不垂直返回假\n * @param {vector|Array<number>} dada [和向量比较的向量或数据]\n * @return {boolean} [结果]\n */\n isVertical(dada:Vector|Array<number>):boolean\n /**\n * 求两个向量的余弦,返回值为余弦值\n * [angle 向量夹角]\n * @param {vector|Array<number>} data [向量或者向量数据]\n * @return {number} [结果值]\n */\n angle(data:Vector|Array<number>):number;\n}\n" }, { "alpha_fraction": 0.6769663095474243, "alphanum_fraction": 0.6769663095474243, "avg_line_length": 18.77777862548828, "blob_id": "582c873bc6de4c60913234fc2a497c93bed508e5", "content_id": "454897c3e18a0395f1ce07826b9af18b429093b5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 356, "license_type": "permissive", "max_line_length": 43, "num_lines": 18, "path": "/statistics/C/include/HashMap.h", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "#ifndef __HASHMAP_H__\n#include <stdlib.h>\ntypedef struct Map{\n void *key;\n void *value;\n long hashValue;\n struct Node *next;\n struct Node *left;\n struct Node *right;\n}MapNode;\ntypedef int *key;\nMapNode *newHashMap(void *key,void *value);\nvoid setKey();\nvoid putValue();\nvoid getValue(key);\nint nodeEquals();\nMapNode *extenArray();\n#endif\n" }, { "alpha_fraction": 0.6357285380363464, "alphanum_fraction": 0.6497005820274353, "avg_line_length": 21.0219783782959, "blob_id": "a3688a2593b3131eb4f24d8a44e20d697f3239bf", "content_id": "8f21d1389e417dd4ed562aba9fa29e39e2978424", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2160, "license_type": "permissive", "max_line_length": 56, "num_lines": 91, "path": "/statistics/C/src/LLink.c", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: Admin\n* @Date: 2021-04-06 22:29:32\n* @Last Modified by: Jingyuexing\n* @Last Modified time: 2021-08-08 17:53:30\n*/\n\n/**\n * 此链表为单向链表\n */\n\n\n#include \"LLink.h\"\n#include <stdlib.h>\n\n#ifndef _L_FUN\n#define _L_FUN\nLLNode *LLinkNewNode(double element);\nLLNode *LLinkSearch(Link *self,double item);\nvoid LLinkRemove(Link *self,double item);\nvoid LLinkInsert(Link *self,double item,double element);\n#endif\n\nLLNode *LLinkNewNode(double element){\n LLNode *newNode = (LLNode *)malloc(sizeof(LLNode));\n newNode->element= element;\n newNode->next = NULL;\n return newNode;\n}\n\nLink *New(){\n Link *newLink = (Link*)malloc(sizeof(Link));\n newLink->pos = NULL;\n newLink->head = NULL;\n newLink->LLinkInsert = LLinkInsert;\n newLink->LLinkNewNode = LLinkNewNode;\n newLink->LLinkRemove = LLinkRemove;\n newLink->LLinkSearch = LLinkSearch;\n newLink->New = New;\n return newLink;\n}\n\n// 面对对象设计\n\n\nvoid append(Link *self,double item){\n LLNode *newNode = self->LLinkNewNode(item);\n if(self->head != NULL){\n self->pos->next = newNode;\n }else{\n self->head = newNode;\n }\n self->pos = newNode;\n}\n\n/**\n * 单向链表的查找\n * @param root 根节点\n * @param item 需要查询的元素项\n * @return 查询到的节点\n */\nLLNode *LLinkSearch(Link *self,double item){\n LLNode *currNode = self->head;\n while (currNode->element != item) {\n currNode = currNode->next;\n }\n return currNode;\n}\n/**\n * 删除单向链表当中的节点\n * @param node 需要删除的节点\n */\nvoid LLinkRemove(Link *self,double item){\n LLNode *findOne = self->LLinkSearch(self,item);\n LLNode *posNext = findOne->next;\n findOne->element = posNext->element;\n findOne->next = findOne->next->next;\n free(posNext);\n}\n\n/**\n * 向单向链表当中的制定位置插入一个元素\n * @param node 节点\n * @param element 元素\n */\nvoid LLinkInsert(Link *self,double item,double element){\n LLNode findOne = *(self->LLinkSearch(self,item));\n LLNode newNode = *(self->LLinkNewNode(element));\n newNode.next = findOne.next->next;\n findOne.next = &newNode;\n}\n" }, { "alpha_fraction": 0.7336152195930481, "alphanum_fraction": 0.7336152195930481, "avg_line_length": 22.649999618530273, "blob_id": "2561dcad0a8dbde38b1b79e0ac281f4b09132f59", "content_id": "426bd3f9cc40b4bdb665100b9dfc79f2506bde20", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 473, "license_type": "permissive", "max_line_length": 46, "num_lines": 20, "path": "/statistics/C/include/binTree.h", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "#ifndef __MATHLIB_BINTREE_H__\n#define __MATHLIB_BINTREE_H__\ntypedef struct binTreeNode{\n struct binTreeNode *left;\n struct binTreeNode *right;\n struct binTreeNode *parent;\n double element;\n}binTreeNode;\n\ntypedef struct BinTree{\n binTreeNode *root;\n int depth;\n}BinTree;\n\nbinTreeNode *find(BinTree *tree, double item);\nvoid del(double item);\nvoid update(binTreeNode *node,double value);\nBinTree *craete();\nvoid append(BinTree *tree,double element);\n#endif\n" }, { "alpha_fraction": 0.42500001192092896, "alphanum_fraction": 0.5027777552604675, "avg_line_length": 14.65217399597168, "blob_id": "cdd15b9708247ca4cb3a88f8640dd30eda402365", "content_id": "bd91b8a4f405418de1e26c529c4543b509d49100", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 360, "license_type": "permissive", "max_line_length": 42, "num_lines": 23, "path": "/statistics/CS/src/Main.cs", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: Admin\n* @Date: 2020-07-23 18:45:47\n* @Last Modified by: Admin\n* @Last Modified time: 2020-07-23 18:59:20\n*/\n\nnamespace MathLib{\n class Rank{\n static void insert(){\n\n }\n static void bubbleSort(){\n }\n static void quickSort(){\n }\n }\n class Main{\n static void main(){\n\n }\n }\n}\n" }, { "alpha_fraction": 0.546875, "alphanum_fraction": 0.5558035969734192, "avg_line_length": 13.966666221618652, "blob_id": "3c52d94f53c3918d94a0836c881d2cf4bed92de9", "content_id": "7b73a2acfdecece3504cc2f8934578dd655651d7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 492, "license_type": "permissive", "max_line_length": 43, "num_lines": 30, "path": "/statistics/TypeScript/src/product.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "class product{\n\ttotal:number=0;\n\tary:Array<number>=[];\n\t/**\n\t * 初始化一个product对象\n\t * @param {Array<number>} ...index [数据:数组]\n\t */\n\tconstructor([...index]:Array<number>){\n\t\tfor(let i=0;i<index.length;i++){\n\t\t\tthis.total+=index[i];\n\t\t\tthis.ary.push(index[i]);\n\t\t}\n\t}\n\t/**\n\t * 返回总和\n\t */\n\tSum(){\n\t\treturn this.total;\n\t}\n\t/**\n\t * 返回数据的乘积\n\t */\n\tproduct(){\n\t\tlet total=1;\n\t\tfor(let n=0;n<this.ary.length;n++){\n\t\t\ttotal*=this.ary[n];\n\t\t}\n\t\treturn total;\n\t}\n}" }, { "alpha_fraction": 0.4979757070541382, "alphanum_fraction": 0.6113360524177551, "avg_line_length": 16.64285659790039, "blob_id": "b93399bdbb0cfc78c02a6092fd3b58c791d30909", "content_id": "24f381e4718ec27e6f403e94d51517998fad6b19", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 247, "license_type": "permissive", "max_line_length": 42, "num_lines": 14, "path": "/statistics/CS/src/PowerFactorial.cs", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: Admin\n* @Date: 2020-07-23 18:52:09\n* @Last Modified by: Admin\n* @Last Modified time: 2021-03-29 13:05:23\n*/\nusing System.Dynamic;\nnamespace MathLib{\n class PowerFactorial{\n public static void main(){\n\n }\n }\n}\n" }, { "alpha_fraction": 0.5608108043670654, "alphanum_fraction": 0.587837815284729, "avg_line_length": 15.44444465637207, "blob_id": "76b2d6b6f6d44fee9638c35f582a80946c04c8af", "content_id": "30b33195534683b58ba14053554b49493006502f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 162, "license_type": "permissive", "max_line_length": 27, "num_lines": 9, "path": "/statistics/C/src/sigmoid.c", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "#include \"sigmoid.h\"\n/**\n * [sigmoid description]\n * @param x 输入数\n * @return 0-1之间的数\n */\ndouble sigmoid(double x){\n return 1/(1+pow(E,-x));\n}\n" }, { "alpha_fraction": 0.6801470518112183, "alphanum_fraction": 0.6801470518112183, "avg_line_length": 18.428571701049805, "blob_id": "79cfb21578b4280295c905d84298228af7ec3162", "content_id": "05be367c63dea0a708e99bd5f9e13b1686934f68", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 272, "license_type": "permissive", "max_line_length": 40, "num_lines": 14, "path": "/statistics/C/include/BRTree.h", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "#ifndef __MATHLIB_BRTREE_H__\n#define __MATHLIB_BRTREE_H__\ntypedef enum NodeType{\n RED,\n BLACK\n}NodeType;\ntypedef struct Node{\n NodeType type;\n struct Node *Red;\n struct Node *Black;\n double element;\n}Node;\nvoid append(Node *tree, double element);\n#endif\n" }, { "alpha_fraction": 0.5847347974777222, "alphanum_fraction": 0.5886157751083374, "avg_line_length": 14.479999542236328, "blob_id": "0a81202be6b387effdf9e79aa4abeaf7e4a7a114", "content_id": "10b0a70e417d989b189ad7c0c504fce3f72e4834", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 805, "license_type": "permissive", "max_line_length": 65, "num_lines": 50, "path": "/statistics/TypeScript/src/trigonometric.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/**\n * 三角函数\n */\nfunction trigonometric(x:number,y:number):Object{\n\tlet r:number = Math.sqrt(x*x)+Math.sqrt(y*y);\n\tlet sin,//正弦函数\n\t\tcos,//余弦函数\n\t\ttan,//正切函数\n\t\tcot,//\n\t\tsec,\n\t\tcsc;\n\treturn {};\n}\nclass tri{\n\tx:number;\n\ty:number;\n\tr:number;\n\tconstructor(x:number,y:number){\n\t\tthis.x=x;\n\t\tthis.y=y;\n\t\tthis.r=Math.sqrt(x*x)+Math.sqrt(y*y);\n\t}\n\tsin(){\n\t\treturn this.y/this.r;\n\t}\n\tcos(){\n\t\treturn this.x/this.r;\n\t}\n\ttan(){\n\t\treturn this.y/this.x;\n\t}\n\tcot(){\n\t\treturn this.x/this.y;\n\t}\n\tsec(){\n\t\treturn this.r/this.x;\n\t}\n\tcsc(){\n\t\treturn this.r/this.y;\n\t}\n\tpointXY(x:number,y:number){\n\t\tlet new_x:number = x-this.x;\n\t\tlet new_y:number=y-this.y;\n\t\tlet new_r:number=Math.sqrt(new_x*new_x)+Math.sqrt(new_y*new_y);\n\t\treturn {x:new_x,y:new_y,r:new_r};\n\t}\n\t/**\n\t * sin^2_X+cos^2_x=1\n\t */\n}" }, { "alpha_fraction": 0.6032906770706177, "alphanum_fraction": 0.6617915630340576, "avg_line_length": 20.8799991607666, "blob_id": "89ba5a5203867ce8e544a3826182f2eba8703c18", "content_id": "4f6a9208f21b35cac5938668133486ac63e5d6fa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 547, "license_type": "permissive", "max_line_length": 70, "num_lines": 25, "path": "/statistics/C/src/binTree.c", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: Admin\n* @Date: 2021-05-11 05:39:14\n* @Last Modified by: Admin\n* @Last Modified time: 2021-05-11 05:58:22\n*/\n#include \"../include/binTree.h\"\n#include <stdlib.h>\n\nbinTreeNode *initNode(){\n binTreeNode *newNode = (binTreeNode *)malloc(sizeof(binTreeNode));\n newNode->left = NULL;\n newNode->right = NULL;\n newNode->parent = NULL;\n newNode->element = 0.000;\n return newNode;\n}\nbinTreeNode *find(BinTree *tree,double item){\n return initNode();\n}\nvoid append(BinTree *tree,double item){\n}\nvoid del(double item){\n\n}\n" }, { "alpha_fraction": 0.4912280738353729, "alphanum_fraction": 0.5592105388641357, "avg_line_length": 18, "blob_id": "74ae27cc48195a687ee74b8aa1c461750cf15bc7", "content_id": "2b145168606d7820cede210d647932e35d5b3494", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 474, "license_type": "permissive", "max_line_length": 52, "num_lines": 24, "path": "/statistics/python/src/Mean.py", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Author: Admin\n# @Date: 2020-01-10 00:57:06\n# @Last Modified by: jingyuexing\n# @Last Modified time: 2020-05-30 04:11:27\n\nfrom Rnak import Rank\n\n\ndef mean(data=[]):\n '''平均值\n\n [description]\n\n Keyword Arguments:\n data {list} -- [description] (default: {[]})\n\n Returns:\n float -- 返回的平均值\n '''\n total = 0\n for i in range(0, len(data)):\n total = total + data[i]\n return total / len(data)\n" }, { "alpha_fraction": 0.5716652870178223, "alphanum_fraction": 0.5973488092422485, "avg_line_length": 18.770492553710938, "blob_id": "36e5d8fd4971e22e038d25fced4b395754ef1d0e", "content_id": "711a34e91ef65a9eba28d34b8f0dd2f4c671ba4d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1295, "license_type": "permissive", "max_line_length": 52, "num_lines": 61, "path": "/statistics/C/src/queue.c", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: Jingyuexing\n* @Date: 2020-12-02 21:07:17\n* @Last Modified by: Admin\n* @Last Modified time: 2021-04-06 23:10:55\n*/\n\n#include \"queue.h\"\n\n/**\n * 初始化节点\n * @param element 元素\n * @param isRoot 是否是根节点(0 否 1 是)\n * @return [description]\n */\nNode *init(double element,int isRoot){\n Node *newNode = (Node *)malloc(sizeof(Node));\n newNode->element = element;\n newNode->isRoot = isRoot;\n newNode->child = newNode;\n return newNode;\n}\n\n/**\n * 查找元素\n * @param node 链表\n * @param item 查找项\n * @return node\n */\nNode *find(Node *node,double item){\n while (node->element != item) {\n node = node->child;\n }\n return node;\n}\n\n/**\n * 插入节点\n * @param root 根节点\n * @param item 选项\n * @param element 需要插入的元素\n * @return root\n */\nNode *insert(Node *root,double item,double element){\n Node *findOne = find(root,item);\n Node *newNode = init(element,0);\n newNode->child = findOne->child->child;\n findOne->child = newNode;\n return root;\n}\n\n/**\n * 移除节点\n * @param root [description]\n * @param item [description]\n * @return [description]\n */\nNode *remove(Node *root,double index){\n Node *findOne = find(root,index);\n return findOne;\n}\n\n" }, { "alpha_fraction": 0.39336493611335754, "alphanum_fraction": 0.5260663628578186, "avg_line_length": 15.307692527770996, "blob_id": "a2508ba3dcd428d04f50c69c7a50a20c80c2f0e5", "content_id": "83b9a6adc1ab5a11147cddab8c0fd5db0a4ca1c4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 211, "license_type": "permissive", "max_line_length": 42, "num_lines": 13, "path": "/statistics/CS/src/Median.cs", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: Admin\n* @Date: 2020-07-23 18:51:29\n* @Last Modified by: Admin\n* @Last Modified time: 2020-07-23 19:03:17\n*/\nnamespace MathLib{\n class Median{\n Median(){\n \n }\n }\n}" }, { "alpha_fraction": 0.4994232952594757, "alphanum_fraction": 0.535755455493927, "avg_line_length": 15.358490943908691, "blob_id": "18c1179eff8258b119ffb267c729535a136e7612", "content_id": "b2fe85724ec2e2592956280fc87a3f083a8b43d0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 1760, "license_type": "permissive", "max_line_length": 53, "num_lines": 106, "path": "/statistics/Go/mathlib/Matrix.go", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "package mathlib\n\nimport \"math\"\n\n/*\n* @Author: jingyuexing\n* @Date: 2020-11-06 22:21:48\n* @Last Modified by: admin\n* @Last Modified time: 2021-07-04 02:10:53\n */\n\n/**\n * 定义矩阵接口\n */\ntype matrix interface {\n\tAdd(mat Matrix) Matrix\n\tIndentity() Matrix\n\tHardamard(m Matrix) Matrix\n\tTr() float64\n\tFrobenius() float64\n\tTran() Matrix\n}\n\n/**\n * 定义矩阵结构体\n */\ntype Matrix struct {\n\tCol int\n\tRow int\n\tData [][]float64\n}\n\nfunc (m *Matrix) New(col int, row int) {\n\tm.Col = col\n\tm.Row = row\n\tm.Data = make([][]float64, row)\n\tfor i := 0; i < row; i++ {\n\t\tm.Data[i] = make([]float64, col)\n\t}\n}\n\nfunc (m *Matrix) Add() Matrix {\n\n}\n\nfunc (m *Matrix) Indentity() Matrix {\n\tnewMatrix = Matrix{\n\t\tData: [][]float64{},\n\t}\n\ttemp := make([][]float64, m.Col)\n\tfor i := 0; i < m.Col; i++ {\n\t\ttemp[i] = make([]float64, m.Row)\n\t\tfor j := 0; j < m.Row; j++ {\n\t\t\tif i == j {\n\t\t\t\ttemp[i][j] = 1\n\t\t\t} else {\n\t\t\t\ttemp[i][j] = 0\n\t\t\t}\n\t\t}\n\t}\n\tnewMatrix.Data = temp\n\treturn newMatrix\n}\n\nfunc (m *Matrix) Hardamard() {\n\tnewMatrix = &Matrix{}\n\tnewMatrix.New(m.Row, m.Col)\n\tfor c := 0; r < m.Col; c++ {\n\t\tfor r := 0; r < m.Row; r++ {\n\t\t\tnewMatrix.Data[c][r] = m.Data[c][r] * m.Data[c][r]\n\t\t}\n\t}\n}\n\nfunc (m *Matrix) Tr() float64 {\n\ttotal := 0.0\n\tfor r := 0; r < m.Row; r++ {\n\t\tfor c := 0; c < m.Col; c++ {\n\t\t\tif r == c {\n\t\t\t\ttotal += m.Data[r][c]\n\t\t\t}\n\t\t}\n\t}\n\treturn total\n}\n\nfunc (m *Matrix) Frobenius() {\n\ttotal := 0.0\n\tfor r := 0; r < m.Row; r++ {\n\t\tfor c := 0; c < m.Col; c++ {\n\t\t\ttotal += m.Data[r][c] * m.Data[r][c]\n\t\t}\n\t}\n\treturn math.Sqrt(total)\n}\n\nfunc (m *Matrix) Tran() Matrix {\n\tnewMatrix := &Matrix{}\n\tnewMatrix.New(m.Col, m.Row)\n\tfor c := 0; c < m.Row; c++ {\n\t\tfor r := 0; r < m.Col; r++ {\n\t\t\tnewMatrix.Data[c][r] = m.Data[r][c]\n\t\t}\n\t}\n\treturn newMatrix\n}\n" }, { "alpha_fraction": 0.602090060710907, "alphanum_fraction": 0.6262058019638062, "avg_line_length": 18.13846206665039, "blob_id": "dbd062bd116d7445a04a21555501169816f285f7", "content_id": "3b91a5376e2ee3d04359e71a7cd4e795d4af895c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 1244, "license_type": "permissive", "max_line_length": 48, "num_lines": 65, "path": "/statistics/Lua/src/List.lua", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "-- @Author: admin\n-- @Date: 2021-12-12 09:31:48\n-- @Last Modified by: admin\n-- @Last Modified time: 2021-12-23 03:51:12\n\n\n\nlocal List = {\n head=nil,\n pos=nil,\n length=0\n}\nlocal NULL = {}\nlocal Node = {\n element= nil,\n next = NULL\n}\nfunction Node.new(element)\n local node = {\n }\n setmetatable(node,{__index=Node})\n node.element = element\n node.next = NULL\n return node\nend\n\n\nfunction List.new()\n local self = {}\n setmetatable(self,{__index=List})\n return self\nend\n\nfunction List.append(self,element)\n local Node = Node.new(element)\n if self.head ~= nil then\n self.pos.next = Node\n self.pos = self.pos.next\n else\n self.head = {}\n self.pos = {}\n self.head = Node\n self.pos = self.head\n end\n self.length = self.length+1\nend\n\nfunction List.find(self,element)\n local current = self.head\n while current.element ~= element do\n current = current.next\n end\n return current\nend\n\nfunction List.remove(self,element)\n local targetNode = self.find(self,element)\n targetNode.element = targetNode.next.element\n local nextNode = targetNode.next\n targetNode.next = nextNode.next\n nextNode=nil\n return self\nend\n\nreturn List\n" }, { "alpha_fraction": 0.5570583343505859, "alphanum_fraction": 0.6094674468040466, "avg_line_length": 15.205479621887207, "blob_id": "5c9f50ca559393420ee0e80d1a2e3754f57a3b96", "content_id": "c2918f9c485fba21e1c3d0cbcef5f64f767f91d1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 1183, "license_type": "permissive", "max_line_length": 47, "num_lines": 73, "path": "/statistics/Go/mathlib/mathlib.go", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: jingyuexing\n* @Date: 2020-11-06 19:20:32\n* @Last Modified by: Jingyuexing\n* @Last Modified time: 2022-11-14 22:08:20\n */\n\npackage mathlib\n\n/**\n * @param {float64} input\n * @return {uintptr} length\n */\nfunc length(input []float64) int {\n\treturn len(input)\n}\n\nfunc mean(input []float64) float64 {\n\tvar total = 0.0\n\tfor i := 0; i < len(input); i++ {\n\t\ttotal += input[i]\n\t}\n\t// len = length(input)\n\treturn total / float64(len(input))\n}\n\nfunc sum(num []float64) float64 {\n\ttotal := 0.0\n\tfor i := 0; i < len(num); i++ {\n\t\ttotal += num[i]\n\t}\n\treturn total\n}\n\nfunc gcd(p int, q int) int {\n\tif q == 0 || q == 0 {\n\t\treturn p\n\t}\n\tvar r = p % q\n\treturn gcd(q, r)\n}\n\n/**\n * [isOdd description]\n * @return {Boolean} [description]\n */\nfunc isEven(p int) bool {\n\treturn p&1 == 1\n}\n\n/**\n * return {Boolean}\n */\nfunc isOdd(p int) bool {\n\treturn !isEven(p)\n}\n\n/**\n * @param {[]float64} value\n * @return {[]float64} softmax\n */\nfunc softmax(value []float64) []float64 {\n\tvar softmax []float64\n\treturn softmax\n}\nfunc covariance()\n\nfunc PadSlice(slice []int, padding int) []int {\n\tnewLen := len(slice) + padding\n\tnewSlice := make([]int, newLen)\n\tcopy(newSlice, slice)\n\treturn newSlice\n}\n" }, { "alpha_fraction": 0.5588235259056091, "alphanum_fraction": 0.5588235259056091, "avg_line_length": 18.571428298950195, "blob_id": "ec43161a76019add58fa05158eb40c1f93be2fe9", "content_id": "5098433ce39fc91b2b92cef7eb1249bc22817267", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": true, "language": "TypeScript", "length_bytes": 168, "license_type": "permissive", "max_line_length": 48, "num_lines": 7, "path": "/@type/Mean.d.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "interface Math{\n /**\n \t * 初始化一个数列\n \t * @param {Array<number>} ...input [需要求平均值的数据]\n \t */\n Mean([...input]:Array<number>):number;\n}" }, { "alpha_fraction": 0.41269105672836304, "alphanum_fraction": 0.41917553544044495, "avg_line_length": 24.399999618530273, "blob_id": "c5f4bfdb1d4964a46672db9e95b59b46e7987f39", "content_id": "d56bd5f447e0d88fb51e439fed134e432d4b7b54", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4630, "license_type": "permissive", "max_line_length": 83, "num_lines": 170, "path": "/statistics/TypeScript/src/Matrix.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "import { Vector } from \"./vector\";\n/**\n * 实现矩阵的加减以及逆运算\n */\nclass Matrix{\n /**\n * 矩阵行数\n */\n row:number;\n /**\n * 矩阵列数\n */\n col:number;\n /**\n * 矩阵数据\n */\n data:number[][];\n //初始化二维矩阵\n /**\n * 初始化矩阵\n * @param {number} row [行数]\n * @param {number} col [列数]\n */\n constructor(row:number,col:number,data=[]){\n this.row=row;//行\n this.col=col;//列\n this.data = Array(this.row);\n for(let i=0;i<this.row;i++){\n this.data[i] = new Array(this.col)\n }\n }\n /**\n * 初始化为一个单位矩阵\n */\n Indentity():Matrix{\n for(let i=0;i<this.col;i++){\n for(let j=0;j<this.row;j++){\n if(i==j){\n this.data[i][j]=1;\n }else{\n this.data[i][j]=0;\n }\n }\n }\n return this;\n }\n /**\n * 矩阵乘法\n * @param {Matrix} matrix [相乘矩阵]\n * @return {Matrix} [生成的新矩阵]\n */\n product(matrix:Matrix):Matrix|undefined{\n let tempMatrix = new Matrix(this.row,matrix.col);\n if(matrix instanceof Matrix){\n if(this.col==matrix.row){\n for(let i=0;i<this.row;i++){\n for(let j=0;j<matrix.col;j++){\n tempMatrix.data[i][j]=0;\n for(let k=0;k<this.col;k++){\n tempMatrix.data[i][j] += this.data[i][k]*matrix.data[k][j];\n }\n }\n }\n return (this,tempMatrix);\n }\n }\n\n }\n /**\n * 元素对应乘积\n * @param data 矩阵或者向量\n * @returns 矩阵或者是向量\n */\n Hardamard(data:Matrix|Vector):Matrix|Vector{\n if(data instanceof Matrix){\n let tempMatrix = new Matrix(data.row,data.col);\n for(let i=0;i<data.col;i++){\n for (let j = 0; j < data.row; j++) {\n tempMatrix[i][j] = this.data[i][j]*data.data[i][j];\n }\n }\n return tempMatrix;\n }\n if(data instanceof Vector){\n let tempV = new Vector(new Array(data.data.length));\n if(data.data.length==this.data.length){\n for(let i=0;i<data.data.length;i++){\n for(let j=0;j< this.row;j++){\n tempV[i] = data.data[i]*this.data[i][j];\n }\n }\n }\n return tempV;\n }\n }\n /**\n * 矩阵迹运算\n * @param {Matrix} matrix [迹运算对象]\n * @return {number} [返回总和]\n */\n Tr(matrix:Matrix):number{\n let total:number=0;\n for(let i=0;i<matrix.col;i++){\n for(let j=0;j<matrix.row;j++){\n if(i==j){\n total+=matrix.data[i][j];\n }\n }\n }\n return (this,total);\n }\n /**\n * 将矩阵降维为数组\n * @param {Matrix} matrix [需要降维的矩阵]\n * @return {Array<number>} [降维后返回的数组]\n */\n downDimensionality(matrix_:Matrix):Array<number>{\n let tempAry:Array<number>=[];\n if(matrix_ instanceof Matrix){\n for(let i=0;i<matrix_.col;i++){\n for(let j=0;j<matrix_.row;j++){\n tempAry.push(matrix_[i][j]);\n }\n }\n }\n return tempAry;\n }\n /**\n * 求矩阵范数\n * @param {Matrix} A [description]\n */\n frobenius(A:Matrix){\n let tempNums:number=0;\n for(let i=0;i<A.row;i++){\n for(let j=0;j<A.col;j++){\n tempNums+= A.data[i][j]**2\n }\n }\n return (this,tempNums**(1/2));\n }\n /**\n * 矩阵的转置\n * [tran description]\n * @param {Matrix} A [需被转置的矩阵]\n * @return {Matrix} [转置后的结果]\n */\n tran(A:Matrix):Matrix{\n let NMatrix = new Matrix(A.col,A.row);\n for(let i=0;i<A.row;i++){\n for(let j=0;j<A.col;j++){\n NMatrix.data[j][i]=A.data[i][j];\n }\n }\n return NMatrix;\n }\n /**\n * @param {void} 无输入\n * @returns {Array} 将矩阵转换成一维\n */\n flat():Array<number>{\n var tempAry:Array<number> = [];\n for(let i =0;i<this.row;i++){\n for(let j=0;j<this.col;j++){\n tempAry.push(this.data[i][j]);\n }\n }\n return tempAry;\n }\n}\nexport {Matrix};\n" }, { "alpha_fraction": 0.36000001430511475, "alphanum_fraction": 0.4923076927661896, "avg_line_length": 18.117647171020508, "blob_id": "9d8c46475e96ad727e795ac5981d85b50e0b1251", "content_id": "7e2697dd682e31e4f311102c848f4fe4bde3df2b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 325, "license_type": "permissive", "max_line_length": 44, "num_lines": 17, "path": "/statistics/python/src/Gcd.py", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Author: Admin\n# @Date: 2020-01-10 00:57:24\n# @Last Modified by: Jingyuexing\n# @Last Modified time: 2021-02-10 13:24:25\n\n\ndef gcd(p=0, q=0):\n if q == 0:\n return p\n r = p % q\n return gcd(q, r)\n\n\nif __name__ == '__main__':\n s = sum([2, 3, 4, 5, 6, 7, 8, 9, 0, 12])\n print(s)\n" }, { "alpha_fraction": 0.6071428656578064, "alphanum_fraction": 0.6428571343421936, "avg_line_length": 26.947368621826172, "blob_id": "059e471199d5183b12d7210f77e9b170d209aba8", "content_id": "0f844ade98195b40ff95a96bca50059a8f097d70", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1002, "license_type": "permissive", "max_line_length": 93, "num_lines": 19, "path": "/statistics/TypeScript/README.md", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "# TypeScript 实现\n\n## 图(Graph)\n在有向图中,两结点间(包括结点自身间)若有同始点和同终点的几条边,则这几条边成为平行边\n在无向图中,两节点间(包括节点自身)若有几条边,则这几条边称为平行边,两结点a、b间相互平行的边的条数称为边(a,b)或`<a,b>`的**重数**.\n含有平行边的图称为多重图(multigraph);非多重图称为线图(line graph) 无环的图称为简单图(simple graph)\n\n## 图 按有无权值分类\n赋权图(weighted graph)G是一个三重组`<V,E,g>`或四重组`<V,E,f,g>`,其中,V是结点集合,E是边的集合,f是从V到非负实数集合的函数(即结点得到权值函数)\ng是从E到非负实数集合的函数(即边的权值函数)。相应的,边或结点均无权值的称为无权图\n\n$$G_{2}=<v_{1},v_{2}> = 5$$\n $v_{1}$到$v_{2}$的边的权值是5\n$$G_{2}=<v_{1},v_{3}> = 6$$\n$$G_{2}=<v_{1},v_{4}> = 7$$\n$$G_{2}=<v_{2},v_{3}> = 6$$\n\n\n**除了边有权值,结点也会有权值**\n\n" }, { "alpha_fraction": 0.5067920684814453, "alphanum_fraction": 0.5360501408576965, "avg_line_length": 21.785715103149414, "blob_id": "f1ce45e3d1bc54efea9bae27eb5209a95646f7ab", "content_id": "1a8e2711edbcefb746ef7f33ab09ce2ec45a9bf7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 957, "license_type": "permissive", "max_line_length": 46, "num_lines": 42, "path": "/statistics/php/src/Link.php", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "<?php\n\n/**\n * @Author: Admin\n * @Date: 2021-04-12 22:32:07\n * @Last Modified by: jingyuexing\n * @Last Modified time: 2021-05-03 15:47:51\n */\nrequire \"ILink.php\";\nclass Node{\n var $next;\n var $content;\n}\nclass Link implements ILink{\n var $head;\n var $pos;\n function Link(){\n $this->head = new Node();\n $this->head->next = null;\n $this->head->content = null;\n $this->pos = $this->head;\n }\n function search($element){\n $currNode = $this->head;\n while($currNode->content != $element){\n $currNode = $currNode->next;\n }\n return $currNode;\n }\n function remove($node=new Node()){\n $node->content = $node->next->content;\n $node->next->next;\n\n }\n function append($node=new Node()){\n $this->head->next = $node;\n }\n function update($item,$element){\n $currNode = $this->search($item);\n $currNode->content = $element;\n }\n}\n" }, { "alpha_fraction": 0.5844471454620361, "alphanum_fraction": 0.5856621861457825, "avg_line_length": 14.240740776062012, "blob_id": "bf6235bc56abe2cd4d5496a1ea83dca91f9482e3", "content_id": "4a50a4fb2e33e5a82f6d3cef00cda809174c9c24", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 823, "license_type": "permissive", "max_line_length": 46, "num_lines": 54, "path": "/statistics/Go/mathlib/Set.go", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "package mathlib\n\ntype Set map[string]bool\n\n\nfunc (s Set) Add(items ...string){\n\tfor _,v := range items {\n\t\ts[v] = true\n\t}\n}\n\nfunc (s Set) Contains(item string) bool {\n _, ok := s[item]\n return ok\n}\n\nfunc (s Set) Remove(items ...string){\n\tfor _,item := range items {\n\t\tdelete(s,item)\n\t}\n}\n\nfunc (s Set) Length() int{\n\treturn len(s)\n}\n\nfunc (s Set) IsEmpty() bool {\n\treturn s.Length() == 0\n}\n\nfunc (s Set) Union(other ...Set) Set {\n\tunion := make(Set)\n\tfor k, v := range s {\n\t\tunion[k] = v\n\t}\n\tfor _, otherSet := range other {\n\t\tfor k, v := range otherSet {\n\t\t\tunion[k] = v\n\t\t}\n\t}\n\treturn union\n}\n\nfunc (s Set) Intersection(others ...Set) Set {\n\tintersection := make(Set)\n\tfor k := range s {\n\t\tfor _, otherSet := range others {\n\t\t\tif otherSet.Contains(k) {\n\t\t\t\tintersection[k] = true\n\t\t\t}\n\t\t}\n\t}\n\treturn intersection\n}\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 8.699999809265137, "blob_id": "81e1c7fcbe2c7c798bcbe8681380c60fa1df3f30", "content_id": "d563a1b451e6a31f240236a064bc43ad1c0445fa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 96, "license_type": "permissive", "max_line_length": 35, "num_lines": 10, "path": "/statistics/Go/mathlib/Vector_test.go", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "package mathlib_test\n\nimport (\n\t\"testing\"\n)\n\n\nfunc TestVectorMult(t *testing.T) {\n\tt.Error(\"\")\n}" }, { "alpha_fraction": 0.5504587292671204, "alphanum_fraction": 0.5642201900482178, "avg_line_length": 18.636363983154297, "blob_id": "50d1fa66c57815d79a4b31ea77e916413a5a6848", "content_id": "950a3021b68d2f0885f636d18b3f3b159e6596a5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 228, "license_type": "permissive", "max_line_length": 55, "num_lines": 11, "path": "/statistics/TypeScript/src/h.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "\n/**\n * 计算熵\n * @param {number} argument 概率\n */\nexport function H() {\n var total:number=0;\n for(let i =0;i<arguments.length;i++){\n total += -arguments[i]*Math.log2(arguments[i]);\n }\n return total;\n}\n\n" }, { "alpha_fraction": 0.4166666567325592, "alphanum_fraction": 0.6499999761581421, "avg_line_length": 29, "blob_id": "804c4a9dbbeea179ab493ab1269ee83cda80a5ab", "content_id": "6863c183a587ac8415455113cd94709637a63f74", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 120, "license_type": "permissive", "max_line_length": 42, "num_lines": 4, "path": "/calculus/st.sh", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "# @Author: Admin\n# @Date: 2019-11-12 06:01:22\n# @Last Modified by: Admin\n# @Last Modified time: 2019-12-20 16:08:38\n" }, { "alpha_fraction": 0.46794870495796204, "alphanum_fraction": 0.6474359035491943, "avg_line_length": 18.5, "blob_id": "cfeb8a4f464cf93caf514f5a7cc9311e5344b993", "content_id": "013064b707ebfa1ab52607d99fc26da35a5a3ad2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 156, "license_type": "permissive", "max_line_length": 42, "num_lines": 8, "path": "/statistics/C/src/Map.c", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: Jingyuexing\n* @Date: 2020-12-09 20:22:35\n* @Last Modified by: Jingyuexing\n* @Last Modified time: 2020-12-09 20:25:16\n*/\n\n#include \"Map.h\"\n" }, { "alpha_fraction": 0.4122137427330017, "alphanum_fraction": 0.5190839767456055, "avg_line_length": 14.470588684082031, "blob_id": "ca029c3903c67646bbd6227121dee127d67ea6ad", "content_id": "f61855cc23c7424bb638a50a26dfa32a827acdb0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 262, "license_type": "permissive", "max_line_length": 42, "num_lines": 17, "path": "/statistics/CS/src/Mean.cs", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: Admin\n* @Date: 2020-07-23 18:51:13\n* @Last Modified by: Admin\n* @Last Modified time: 2020-07-23 19:02:46\n*/\nnamespace MathLib{\n class Mean{\n static Mean(){\n\n }\n }\n class Test{\n static void main(){\n }\n }\n}" }, { "alpha_fraction": 0.5804311633110046, "alphanum_fraction": 0.5887230634689331, "avg_line_length": 17.649484634399414, "blob_id": "4ff3d232024c23d1b68b3879db830bb0716b2f26", "content_id": "6432396b7cf023de2ffca0ef86b076a6770c3fd4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1951, "license_type": "permissive", "max_line_length": 61, "num_lines": 97, "path": "/statistics/C/src/Link.c", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: Jingyuexing\n* @Date: 2020-10-25 21:40:25\n* @Last Modified by: jingyuexing\n*/\n\n#include \"Link.h\"\n\n\n/**\n * 初始化元素\n * @param element 元素\n * @return 新的节点\n * @privie\n */\nNode *init(double element){\n Node *newNode = (Node *)malloc(sizeof(Node));\n (*newNode).child = NULL;\n (*newNode).parent = NULL;\n (*newNode).element = element;\n return newNode;\n}\n\n/**\n * 插入节点\n * @param root 根节点\n * @param item 根节点中的元素\n * @param element 元素\n * @return 根节点\n */\nNode *insert(Node *root,double item,double element){\n Node *newNode = init(element);\n Node *findOne = find(root,item);\n newNode->parent = findOne;\n findOne->child = newNode;\n return root;\n}\n\n\n\n\n/**\n * 移除节点\n * @param root 根节点\n * @param item 元素项\n * @return [description]\n */\nNode *remove(Node *root,double item){\n Node *findOne = find(root,item);\n findOne->parent = findOne->child;\n findOne->child->parent = findOne->parent;\n free(findOne);\n return root;\n}\n\n/**\n * 查找节点\n * @param root 根节点\n * @param item 需要查找的元素\n * @return 返回查找到的节点\n */\nNode *find(Node *root,double item){\n Node *currNode =NULL;\n currNode = root;\n while (currNode->element!=item) {\n currNode = currNode->child;\n }\n return currNode;\n}\n\n/**\n * [findPrevious description]\n * @param root [description]\n * @param item [description]\n * @return [description]\n */\nNode *findPrevious(Node *root,double item){\n Node *node = find(root,item);\n while (!(node->child==0) && node->child->element!=item) {\n node = node->child;\n }\n return node;\n}\n\n/**\n * 最后一个节点\n * @param root 根节点\n * @return node\n */\nNode last(Node *root){\n Node *currNode;\n currNode = root->child;\n while (currNode != NULL) {\n currNode = currNode->child;\n }\n return *currNode;\n}\n" }, { "alpha_fraction": 0.4032258093357086, "alphanum_fraction": 0.6290322542190552, "avg_line_length": 30, "blob_id": "b634b9804946564d225a462d278be5b68aecc9d8", "content_id": "25428881766cd9e50bb77f24c5e28086817e4792", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 124, "license_type": "permissive", "max_line_length": 43, "num_lines": 4, "path": "/statistics/Lua/src/Complex.lua", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "-- @Author: admin\n-- @Date: 2022-03-14 15:15:36\n-- @Last Modified by: admin\n-- @Last Modified time: 2022-03-14 15:15:38\n" }, { "alpha_fraction": 0.4444444477558136, "alphanum_fraction": 0.5555555820465088, "avg_line_length": 8, "blob_id": "c994e15acce86f7d7ae2261344ea89b96a7c91cf", "content_id": "a9b3e7de0af783badcdb8ada7289a2ad711bdce4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 13, "license_type": "permissive", "max_line_length": 8, "num_lines": 1, "path": "/statistics/es6/README.md", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "# ES6 实现\n" }, { "alpha_fraction": 0.5252525210380554, "alphanum_fraction": 0.5252525210380554, "avg_line_length": 27.285715103149414, "blob_id": "ad6191e3a42808f575886a6b049328d37e61882b", "content_id": "7accaef5bf6fa5d2611618ad7cf8a918fb344db0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": true, "language": "TypeScript", "length_bytes": 464, "license_type": "permissive", "max_line_length": 58, "num_lines": 14, "path": "/@type/rank.d.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "declare class Rank{\n /**\n * [insert 插入排序]\n * @param {Array<number>} ...a [需要排序的数据]\n * @return {Array<number>} [排序后的数据]\n */\n static insert([...a]:Array<number>):Array<number>;\n /**\n * [bubbleSort 冒泡排序]\n * @param {Array<number>} ...a [需要排序的数据]\n * @return {Array<number>} [排序后的数据]\n */\n static bubbleSort([...a]:Array<number>):Array<number>;\n}\n" }, { "alpha_fraction": 0.6051502227783203, "alphanum_fraction": 0.6180257797241211, "avg_line_length": 17, "blob_id": "8b89a65ac7847bafeec29081b143cced0f6aa5a5", "content_id": "201c6ff48e334e6bc952f3bd315a85f33a331cc6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 239, "license_type": "permissive", "max_line_length": 35, "num_lines": 13, "path": "/statistics/TypeScript/src/harmonic.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/**\n * [Harmonic 调和数]\n * @param {number} n [description]\n * @return {number} [description]\n */\nfunction Harmonic(n:number):number{\n\tvar total=0;\n\tfor(let i:number=1;i<=n;i++){\n\t\ttotal+=(1/i);\n\t}\n\treturn total;\n}\nexport {Harmonic};" }, { "alpha_fraction": 0.42592594027519226, "alphanum_fraction": 0.42592594027519226, "avg_line_length": 11, "blob_id": "1dc37bce3f84fe095971eaae27201036054f5b96", "content_id": "713240a322961bf0c7c6cded82f2822adcbc9ddb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 112, "license_type": "permissive", "max_line_length": 18, "num_lines": 9, "path": "/statistics/es6/Matrix.es6.js", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "class Matrix{\n row;//行\n col;//列\n data = [];\n constructor(){\n \n }\n}\nexport { Matrix };\n" }, { "alpha_fraction": 0.5811293721199036, "alphanum_fraction": 0.6082916259765625, "avg_line_length": 19.880596160888672, "blob_id": "18a6aafde42f1212a002f55bab9f5f1ecdae4aa0", "content_id": "56397686d501f510916e6f6fe13ae5c323de1c6d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1407, "license_type": "permissive", "max_line_length": 61, "num_lines": 67, "path": "/statistics/C/src/List.c", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: Jingyuexing\n* @Date: 2020-12-09 19:19:21\n* @Last Modified by: Jingyuexing\n* @Last Modified time: 2020-12-09 20:21:46\n*/\n#include \"List.h\"\n\nListNode *init(double element){\n ListNode *newNode = (ListNode *)malloc(sizeof(ListNode));\n newNode->next = NULL;\n newNode->element = element;\n return newNode;\n}\n\nvoid remove(){\n\n}\nvoid insert(List l,int index,double element){\n\n}\nvoid append(List l,double element){\n l.postion->next = init(element);\n l.postion = l.postion->next;\n};\nint isEmpty(List l){\n return l.head->next == NULL;\n}\n\n/**\n * 创建一个List\n * @param element [description]\n * @return [description]\n */\nList newList(double element){\n auto List *newList = (List *)malloc(sizeof(List));\n (*newList).head = init(0x000);\n (*newList).head->next = init(element);\n (*newList).self = &newList;\n (*newList).head = NULL;\n return *newList;\n}\nvoid deleteList(List l){\n free(&l);\n}\nListNode *indexOf(List l,int index){\n ListNode *target = NULL;\n target = l.head->next;\n while (target!=NULL && target->index != index) {\n target = target->next;\n }\n return target;\n}\n\nint main(int argc, char const *argv[])\n{\n List myList;\n myList.head = init(0x000);\n ListNode *currNode;\n currNode = myList.head->next;\n int i =0;\n while (currNode != NULL) {\n currNode->index = i;\n i++;\n }\n return 0;\n}\n" }, { "alpha_fraction": 0.6478873491287231, "alphanum_fraction": 0.6478873491287231, "avg_line_length": 13.399999618530273, "blob_id": "0178d24fc98f1feeefe4af4ef05ce6a2a0ef96f1", "content_id": "1c27dd68dd57b815c4887b4393d714a9dc771910", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 85, "license_type": "permissive", "max_line_length": 21, "num_lines": 5, "path": "/statistics/C/include/gcd.h", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "#ifndef _GCD_H\n#define _GCD_H\n// 定义最大公约数\nint gcd(int p,int q);\n#endif" }, { "alpha_fraction": 0.5322532057762146, "alphanum_fraction": 0.5322532057762146, "avg_line_length": 21.362415313720703, "blob_id": "1409caa349af8ce47d3f18bbcebd2fcbf3b55d82", "content_id": "3b2674cdc8258dde7519efbcabc675390eb0fa5c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3607, "license_type": "permissive", "max_line_length": 56, "num_lines": 149, "path": "/docs/InterfaceDefines.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "interface IVector{\n /**\n * 向量模\n * @return {number} [description]\n */\n mod():number;\n /**\n * 向量加法\n * @return {IVector} [description]\n */\n add(vector:IVector):IVector;\n /**\n * 向量减法\n * @param {IVector} vector another vector\n * @return {IVector} [description]\n */\n sub(vector:IVector):IVector;\n /**\n * 向量夹角\n * @param {IVector} vector another vector\n * @return {number} [description]\n */\n angle(vector:IVector):number;\n /**\n * 向量点乘\n * @param {IVector} vector 相乘向量\n * @return {number} [description]\n */\n dotProduct(vector:IVector):number;\n /**\n * 向量叉乘\n * @param {IVector} vector 相乘向量\n * @return {IVector} [description]\n */\n product(vector:IVector):IVector;\n /**\n * 判断自身和向量 vector 向量是否是平行\n * @param {IVector} vector [description]\n * @return {boolean} [description]\n */\n isHorizontal(vector:IVector):boolean;\n /**\n * 判断自身和向量 vector 向量是否是垂直\n * @param {IVector} vector another vector\n * @return {boolean} [description]\n */\n isVertical(vector:IVector):boolean;\n}\n\ninterface IMatrix{\n /**\n * 矩阵加法\n * @param {IVector} matrix another matrix\n * @return {IMatrix} [description]\n */\n add(matrix:IMatrix):IMatrix;\n /**\n * 矩阵减法\n * @param {IVector} matrix another matrix\n * @return {IMatrix} [description]\n */\n sub(matrix:IMatrix):IMatrix;\n /**\n * 将自身初始化为单位矩阵\n * @return {IMatrix} [description]\n */\n indentity():IMatrix;\n /**\n * 矩阵乘法\n * @param {IVector} matrix another matrix\n * @return {IMatrix} [description]\n */\n product(matrix:IMatrix):IMatrix;\n /**\n * 矩阵转置\n * @return {IMatrix} [description]\n */\n transform():IMatrix;\n}\ninterface IRank{\n /**\n * 插入排序\n *\n * @param {number[]} data [data description]\n *\n * @return {number[]} [return description]\n */\n insertSort(data:number[]):number[];\n /**\n * 冒泡排序\n * @param {number[]} data [description]\n * @return {number[]} [description]\n */\n bubbleSort(data:number[]):number[];\n /**\n * 快排\n * @param {number[]} data [description]\n * @return {number[]} [description]\n */\n quickSort(data:number[]):number[];\n /**\n * 选择排序\n * @param {number[]} data [description]\n * @return {number[]} [description]\n */\n SelectSort(data:number[]):number[];\n /**\n * 归并排序\n * @param {number[]} data [description]\n * @return {number[]} [description]\n */\n mergeSort(data:number[]):number[];\n}\ninterface INode{}\n\n/**\n * List 是双向链表或单向链表 环形链表的统一接口\n */\ninterface IList{\n insert():INode;\n find():INode;\n remove():INode;\n findPrevious():INode;\n last():INode;\n}\n\ninterface IStack {\n /**\n * 入栈\n * @param {number} item 入栈元素\n * @return {number} 元素下标\n */\n push(item:number):number;\n /**\n * [pop description]\n * @param {number} item 出栈元素\n * @return {number} [description]\n */\n pop(item:number):number;\n /**\n * [indexOf description]\n * @param {number} index [description]\n * @return {any} [description]\n */\n indexOf(index:number):any;\n\n}\n\ninterface ITree extends IList {}\n\n" }, { "alpha_fraction": 0.4675324559211731, "alphanum_fraction": 0.649350643157959, "avg_line_length": 16.11111068725586, "blob_id": "21745f8e9d6ab665508f9e74acff4eb54bd25ca0", "content_id": "ca3d9a238abf7c5e41a6b9bba93250526393b089", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 154, "license_type": "permissive", "max_line_length": 42, "num_lines": 9, "path": "/statistics/CS/src/Covariance.cs", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: Admin\n* @Date: 2020-07-23 18:49:42\n* @Last Modified by: Jingyuexing\n* @Last Modified time: 2020-12-04 10:26:55\n*/\nnamespace MathLib{\n\n}\n" }, { "alpha_fraction": 0.4803493320941925, "alphanum_fraction": 0.6069868803024292, "avg_line_length": 16.615385055541992, "blob_id": "42953e6ebd4b7b32dedd766257ada89e90e0be59", "content_id": "b53d43e76c26edd18af943786ed6a620ab89fc72", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 229, "license_type": "permissive", "max_line_length": 42, "num_lines": 13, "path": "/statistics/C/src/stack.c", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: Jingyuexing\n* @Date: 2020-12-02 21:07:36\n* @Last Modified by: admin\n* @Last Modified time: 2021-07-04 02:26:28\n*/\n#include \"stack.h\"\n\nint main(int argc, char const *argv[])\n{\n printf(\"%s\\n\");\n return 0;\n}\n" }, { "alpha_fraction": 0.6772152185440063, "alphanum_fraction": 0.6772152185440063, "avg_line_length": 26.882352828979492, "blob_id": "9f7cddfecc8538375e8bead86c81c259bd41ac46", "content_id": "354627ed428c6a5f375f443cb3c84e7c8a86f833", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 474, "license_type": "permissive", "max_line_length": 65, "num_lines": 17, "path": "/statistics/C/src/LLink.h", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "#ifndef __LLINK_H__\n#define __LLINK_H__\n#include <stdlib.h>\ntypedef struct LLNode{\n double element;\n struct LLNode *next;\n}LLNode;\ntypedef struct Link{\n LLNode *head;\n LLNode *pos;\n struct Link *(*New)();\n struct LLNode *(*LLinkNewNode)(double element);\n void (*LLinkRemove)(struct Link *self,double item);\n void (*LLinkInsert)(LLNode *node,double item,double element);\n struct LLNode *(*LLinkSearch)(struct Link *self,double item);\n}Link;\n#endif\n" }, { "alpha_fraction": 0.6266173720359802, "alphanum_fraction": 0.6340110898017883, "avg_line_length": 29.05555534362793, "blob_id": "72b03b3a1207100652afbbfad3291a3894ac5193", "content_id": "5f9ae138073231b2225ec609cdee6edd7a882d6a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 541, "license_type": "permissive", "max_line_length": 55, "num_lines": 18, "path": "/statistics/C/include/matrix.h", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "#ifndef _MATRIX_H\n#define _MATRIX_H\ntypedef struct T{\n int row;\n int col;\n double data[10][10];\n struct T *self;\n struct T (*Indentity)(struct T *matrix);\n struct T (*Product)(struct T *matrix);\n struct T (*Hardamard)(struct T *data);\n struct T (*Tr)(struct T *matrix);\n struct T (*DownDimensionality)(struct T *matrix);\n double (*Frobenius)(struct T *matrix);\n struct T (*Tran)(struct T *matrix);\n double*(*flat)(struct T *matrix);\n struct T (*pooling)(struct T *matrix,double *arry);\n}Matrix;\n#endif\n" }, { "alpha_fraction": 0.4583333432674408, "alphanum_fraction": 0.5879629850387573, "avg_line_length": 15.692307472229004, "blob_id": "3b0acd28a1b98ab4638d5f0e5d3b4ada828b518a", "content_id": "0cc47605d7d4ac237fd74d1345df69456901d077", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 216, "license_type": "permissive", "max_line_length": 42, "num_lines": 13, "path": "/statistics/CS/src/LeastSquare.cs", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: Admin\n* @Date: 2020-07-23 18:50:53\n* @Last Modified by: Admin\n* @Last Modified time: 2020-07-23 18:57:30\n*/\nnamespace MathLib{\n class LeastSquare{\n static LeastSquare(){\n\n }\n }\n}" }, { "alpha_fraction": 0.545045018196106, "alphanum_fraction": 0.5540540814399719, "avg_line_length": 16.153846740722656, "blob_id": "46afb53dd460cd0595f7cca4170f93ca8b1bcd0a", "content_id": "d97c57e36148b81c6623812c861087ca36163655", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 226, "license_type": "permissive", "max_line_length": 26, "num_lines": 13, "path": "/statistics/C/src/factorial.c", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "#include \"factorial.h\"\n/**\n * [Factorial 阶乘]\n * @param n [description]\n * @return [description]\n */\nlong int Factorial(int n){\n long int total=1;\n for(int i=1;i<=n;i++){\n total*=i;\n }\n return total;\n}" }, { "alpha_fraction": 0.4189189076423645, "alphanum_fraction": 0.545045018196106, "avg_line_length": 16.153846740722656, "blob_id": "a2d8f9209127447402c64db5ae4e14e37119a465", "content_id": "83a128b03cded3ffa55ea64ce834e22e6dbd543e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 222, "license_type": "permissive", "max_line_length": 42, "num_lines": 13, "path": "/statistics/CS/src/Harmonic.cs", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: Admin\n* @Date: 2020-07-23 18:50:42\n* @Last Modified by: Admin\n* @Last Modified time: 2020-07-23 18:56:34\n*/\nnamespace MathLib{\n class Harmonic{\n static Harmonic(){\n \n }\n }\n}" }, { "alpha_fraction": 0.5396039485931396, "alphanum_fraction": 0.5445544719696045, "avg_line_length": 15.916666984558105, "blob_id": "616077ab4add1150ac9ef75cac0ef2b7ecb1272c", "content_id": "a09d3426097ef4fc704435afa3a2f46052a894ec", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 214, "license_type": "permissive", "max_line_length": 26, "num_lines": 12, "path": "/statistics/C/src/gcd.c", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "#include \"gcd.h\"\n/**\n * 求最大公约数\n * @param p [description]\n * @param q [description]\n * @return [description]\n */\nint gcd(int p,int q){\n if(q==0) return p;\n int r = p % q;\n return gcd(q,r);\n}" }, { "alpha_fraction": 0.6577681303024292, "alphanum_fraction": 0.7046657204627991, "avg_line_length": 36.11606979370117, "blob_id": "01c0d8c6f69bbd63836207484103f63485e4dca1", "content_id": "c3912371441335de92dfb777682ad38d19ad2c23", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5822, "license_type": "permissive", "max_line_length": 198, "num_lines": 112, "path": "/README.md", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "# MathLib\n在calculus中有微积分为微积分实现方法,目前还未进行实现 在`statistics`中包含统计学相关的算法,如协方差,方差,求中位数,平均值,分位数图计算\n### statistics\n- ----`index`:[当前库的主要导出文件](statistics/TypeScript/src/index.ts)\n- ----`Variance`:[方差实现方法](statistics/TypeScript/src/Variance.ts) [python](statistics/python/src/var.py)\n- ----`weigth_variance`:[加权平均数实现方法](statistics/TypeScript/src/weigth_variance.ts)\n- ----`QuantilePlot`:[分位数图](statistics/TypeScript/src/src/QuantilePlot.ts)\n- ----`Covariance`:[协方差](statistics/TypeScript/src/Covariance.ts)\n- ----`Mean`:[平均值](statistics/TypeScript/src/Mean.ts) [py](statistics/python/src/Mean.py)\n- ----`harmonic`:[调和数](statistics/TypeScript/src/harmonic.ts)\n- ----`LeastSquare`:[二乘法](statistics/TypeScript/src/LeastSquare.ts)\n- ----`Media`:[中位数](statistics/TypeScript/src/Median.ts) [py](statistics/python/src/Median.py)\n- ----`Matrix`:[矩阵类](statistics/TypeScript/src/Matrix.ts) [C](statistics/C/src/matrix.c) [py](statistics/python/src/Matrix.py) [haxe](statistics/Haxe/src/mathlib/Matrix.hx),实现矩阵的计算,诸如相加,相减,矩阵的逆,矩阵转置\n- ----`rank`:[排序](statistics/TypeScript/src/Rank.ts) [py](statistics/python/src/Rnak.py) 的实现(未完全实现)\n- ----`StandardDeviation`:[标准差](statistics/TypeScript/src/Standard_Deviation.ts)\n- ----`vector`:[向量](statistics/TypeScript/src/vector.ts)的运算 [py](statistics/python/src/Vector.py)\n- ----`Permutations`:[阶乘](statistics/TypeScript/src/Permutations.ts)\n- ----`expetation`:[期望值](statistics/TypeScript/src/expetation.ts)\n- ----`sigmoid`:[激活函数](statistics/TypeScript/src/sigmoid.ts) [py](statistics/python/src/sigmoid.py)\n- ----`angule`:[角度和弧度转换](statistics/TypeScript/src/angule.ts)\n- ----`gcd`:[求最大公约数](statistics/TypeScript/src/gcd.ts)\n- ----`Factorial`:[求n的阶乘](statistics/TypeScript/src/Factorial.ts)\n- ----`softmax`:[softmax](statistics/TypeScript/src/softmax.ts) [py](statistics/python/src/softmax.py)\n\n---\n增加链式调用,Matrix类以及Vector类\n\n----\n用法:\n* ***Variance***\n此方法求取数据的方差,返回的是方差值,若需要标准差,只需要将该方法返回值开方即可\n```js\n//Variance([...value]:Array<number>);\nconsole.log(Variance([2,3,5,7,8,9,12,40,66,92,103,88]));//NaN,unknow Error\n```\n* ***weigth_variance***\n此方法返回加权平均值\n函数第一个参数数组为数据,第二个数组参数为权重值\n```js\n//weigthVariance([...numberData]: Array < number > , [...weigth]: Array < number > )\nconsole.log(weigthVariance([2,3,5,8,9,12,44],[1,1,1,2,3,2,1]))\n```\n\n### todolist\n- ☐ 完成Matrix算法的 C 实现\n- ☐ 完成Matrix算法的 CPP 实现\n- ☐ 完成Matrix算法的 CS 实现\n- ☐ 完成Matrix算法的 JS 实现\n- ☐ 完成Matrix算法的 GO 实现\n- ☐ 完成Matrix算法的 Haxe 实现\n- ☐ 完成Matrix算法的 Java 实现\n- ☐ 完成Matrix算法的 Python 实现\n- ☐ 完成link链表的 CPP 的实现\n- ☐ 完成link链表的 JS 的实现\n- ☐ 完成link链表的 Haxe 的实现\n- ☐ 完成link链表的 Java 的实现\n- ☐ 完成link链表的 Python 的实现\n- ☐ 完成Vector向量 C 的实现\n- ☐ 完成Vector向量 CPP 的实现\n- ☐ 完成Vector向量 CS 的实现\n- ☐ 完成Vector向量 JS 的实现\n- ☐ 完成Vector向量 Go 的实现\n- ☐ 完成Vector向量 Haxe 的实现\n- ☐ 完成Vector向量 Java 的实现\n- ☐ 完成Rank排序 C 的算法的实现\n- ☐ 完成Rank排序 CPP 的算法的实现\n- ☐ 完成Rank排序 JS 的算法的实现\n- ☐ 完成Rank排序 Go 的算法的实现\n- ☐ 完成Rank排序 Haxe 的算法的实现\n- ☐ 完成Rank排序 Java 的算法的实现\n- ☐ 完成Sgmoid算法的 C 实现\n- ☐ 完成Sgmoid算法的 CPP 实现\n- ☐ 完成Sgmoid算法的 JS 实现\n- ☐ 完成Sgmoid算法的 TS 实现\n- ☐ 完成Sgmoid算法的 Go 实现\n- ☐ 完成Sgmoid算法的 Haxe 实现\n- ☐ 完成Sgmoid算法的 Java 实现\n- ☐ 完成Softmax算法的 C 实现\n- ☐ 完成Softmax算法的 CPP 实现\n- ☐ 完成Softmax算法的 JS 实现\n- ☐ 完成Softmax算法的 GO 实现\n- ☐ 完成Softmax算法的 Haxe 实现\n- ☐ 完成Softmax算法的 Java 实现\n- ☐ 完成Rank排序各类语言算法的实现\n- ☐ 完成Sgmoid算法的各类语言实现\n- ☐ 完成Vector各类语言的实现\n- ☐ 完成link链表的各类语言的实现\n- ☐ 完成Matrix算法的各类语言实现\n\n---\n\nArchive:\n- ✔ 完成List链表的 Go 的实现 @done (21-08-07 11:31)\n- ✔ 完成link链表的 Go 的实现 @done (21-08-07 11:29)\n- ✔ 完成link链表的 C 的实现 @done (20-12-08 20:38)\n- ✔ 完成Sgmoid算法的 CS 实现 @done (20-12-04 12:12)\n- ✔ 完成link链表的 CS 的实现 @done (20-12-04 12:03)\n- ✔ 完成Softmax算法的 CS 实现 @done (20-12-04 11:17)\n- ✔ 完成Sgmoid算法的 CS 实现 @done (20-12-04 11:16)\n- ✔ 完成Vector向量 Python 的实现 @done (20-12-03 14:41)\n- ✔ 完成Softmax算法的 Python 实现 @done (20-12-03 14:41)\n- ✔ 完成Softmax算法的 TS 实现 @done (20-12-03 14:28)\n- ✔ 完成link链表的 TS 的实现 @done (20-12-03 14:27)\n- ✔ 完成Vector向量 TS 的实现 @done (20-12-03 14:27)\n- ✔ 完成Rank排序 TS 的算法的实现 @done (20-12-03 14:27)\n- ✔ 完成Rank排序 Python 的算法的实现 @done (20-12-03 14:27)\n- ✔ 完成Matrix算法的 TS 实现 @done (20-12-03 14:27)\n- ✔ 完成Sgmoid算法的 Python 实现 @done (20-12-03 14:26)\n\n---\n关于这个数学库如果有意见可以和我[一起修改我的github仓库](https://github.com/jingyuexing/MathLib)\n你也可以到[gitee码云](https://gitee.com/jingyuexing/MathLib)查询这个库的镜像\n\n" }, { "alpha_fraction": 0.7179487347602844, "alphanum_fraction": 0.7948718070983887, "avg_line_length": 12, "blob_id": "97545e4a4b03379d126a278cc9807ec38864e5ef", "content_id": "d6b71bbdbc75785020fd84954740dde31c33760b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go Module", "length_bytes": 39, "license_type": "permissive", "max_line_length": 29, "num_lines": 3, "path": "/statistics/Go/mathlib/go.mod", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "module jingyuexing.io/mathlib\n\ngo 1.18\n" }, { "alpha_fraction": 0.5680751204490662, "alphanum_fraction": 0.6244131326675415, "avg_line_length": 11.588234901428223, "blob_id": "27775eb3d7c3e3454af1da28cd6d20118e45e6ff", "content_id": "e7cbddecb15c36852d25fb5d8e7cc2448186ad1e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 213, "license_type": "permissive", "max_line_length": 34, "num_lines": 17, "path": "/statistics/Go/mathlib/Set_test.go", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "package mathlib_test\n\nimport (\n\t\"testing\"\n\n\t\"jingyuexing.io/mathlib\"\n)\n\nfunc TestSet(t *testing.T) {\n\tvar s mathlib.Set\n\n\ts.Add(\"12\",\"45\",\"67\",\"89\")\n\n\tif !s.Contains(\"12\") {\n\t\tt.Error(\"this should be has 12\")\n\t}\n}" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6075471639633179, "avg_line_length": 21.08333396911621, "blob_id": "b1f9fe57177edee0d5ea087be4b7b43fec5583d0", "content_id": "9046ffb67fab26316c8e9a1c8c4bd0b964293a4c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 279, "license_type": "permissive", "max_line_length": 66, "num_lines": 12, "path": "/statistics/TypeScript/src/QuantilePlot.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "\n/**\n * 分位数图\n * @param {Array<number>} ...values [输入值]\n */\nfunction QuantilePlot([...values]: Array<number>): Array<number> {\n\tlet arry: Array<number> = [];\n\tfor (let i of values) {\n\t\tarry.push((i - 0.5) / values.length);\n\t}\n\treturn arry;\n}\nexport { QuantilePlot };" }, { "alpha_fraction": 0.6452513933181763, "alphanum_fraction": 0.6452513933181763, "avg_line_length": 18.94444465637207, "blob_id": "713171a46713805d34f2bfa86d313c2ee56e802b", "content_id": "1fdb96580dead0191e3c2cd454d59626c128afff", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 358, "license_type": "permissive", "max_line_length": 56, "num_lines": 18, "path": "/statistics/TypeScript/src/Complex.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "class Complex{\n real:number;\n img:number;\n constructor(real:number,img:number){\n this.real = real;\n this.img = img;\n }\n public add(a:Complex){\n return new Complex(a.real+this.real,a.img+this.img);\n }\n public mult(a:Complex){\n return new Complex(a.real-this.real,a.img-this.img);\n }\n public product(){\n \n }\n}\nexport default {Complex};" }, { "alpha_fraction": 0.5079929232597351, "alphanum_fraction": 0.5577264428138733, "avg_line_length": 24.590909957885742, "blob_id": "d7c3b39e22e983ee468724c5dd177250b6b35e42", "content_id": "d6a795095faddb78df4b0ad6eca7ba219e3d0fd6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 563, "license_type": "permissive", "max_line_length": 64, "num_lines": 22, "path": "/statistics/CS/src/Complex.cs", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: Jingyuexing\n* @Date: 2020-12-04 11:16:34\n* @Last Modified by: Jingyuexing\n* @Last Modified time: 2020-12-04 11:21:03\n*/\nnamespace Mathlib{\n class Complex{\n double real;\n double img;\n Complex(double real,double img){\n this.real = real;\n this.img = img;\n }\n public Complex add(Complex a){\n return new Complex(a.real+this.real,a.img+this.img);\n }\n public Complex mult(Complex a){\n return new Complex(a.real-this.real,a.img-this.img);\n }\n }\n}\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.75, "avg_line_length": 15, "blob_id": "9a7cc0c0a8c6ad10f1ea66f43d43854e739c02c8", "content_id": "77807fae5b7be75d1bacda359596a80ef7f06620", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 16, "license_type": "permissive", "max_line_length": 15, "num_lines": 1, "path": "/statistics/Lua/READEME.md", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "# Lua implement\n" }, { "alpha_fraction": 0.41333332657814026, "alphanum_fraction": 0.6222222447395325, "avg_line_length": 24, "blob_id": "1670b67a131e1384ee9e61adfe35e3d860a563c2", "content_id": "3a225c5502fc207bd0ed1c68aa43d3c1504ae0e9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 225, "license_type": "permissive", "max_line_length": 42, "num_lines": 9, "path": "/statistics/python/src/sigmoid.py", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Author: Admin\n# @Date: 2020-01-10 02:04:02\n# @Last Modified by: jingyuexing\n# @Last Modified time: 2020-07-19 05:51:20\n\ndef sigmoid(value):\n E = 2.718281828459045\n return 1/(1+E** -value)\n" }, { "alpha_fraction": 0.4366925060749054, "alphanum_fraction": 0.44272178411483765, "avg_line_length": 24.2391300201416, "blob_id": "33bd3a9edfd92104cf2a167b2f99e61c7eefd5fb", "content_id": "91da208a3ca0aeb740be40891f0a4f85b1e00188", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2510, "license_type": "permissive", "max_line_length": 70, "num_lines": 92, "path": "/statistics/TypeScript/src/AdjacencyMatrix.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "import { Matrix } from \"./Matrix\";\n\ninterface Point {\n\n}\n\n\n\nexport class AdjacencyMatrix extends Matrix {\n points: Point[];\n /**\n * 创建邻接矩阵\n * @param {Point[]} ...pointGroup 点集合\n */\n constructor([...pointGroup]: Point[]) {\n super(pointGroup.length, pointGroup.length)\n this.points = pointGroup;\n }\n /**\n * 为矩阵添加邻接矩阵数据\n * @param {number[]} ...point 节点集\n * @param {boolean} haveBorders 是否是有边的 默认为 false\n */\n push([...point]: number[], haveBorders: boolean = false) {\n let x = point[0];\n let y = point[1];\n if (haveBorders) {\n this.data[x][y] = 1\n } else {\n this.data[x][y] = 0\n }\n }\n /**\n * 生成G图的补图的邻接矩阵\n */\n complement() {\n for (let i = 0; i <= this.data.length; i++) {\n for (let j = 0; i <= this.data.length; i++) {\n if (i == j) {\n this.data[i][j] = 0;\n } else {\n this.data[i][j] = 1 - this.data[i][j];\n }\n }\n }\n }\n /**\n * 求一个结点的总度数\n * @param {number} point [description]\n * @param {Boolean} isVector = false [description]\n */\n deg(point: number, isVector = false){\n return this.degIn(point,isVector)+this.degOut(point,isVector);\n }\n /**\n * 邻接矩阵计算出度\n * @param {number} point 第i个结点\n * @param {boolean} isVector 是否是有向图\n */\n degOut(point: number, isVector = false) {\n let deg = 0;\n if (isVector) {\n // 如果是有向图\n for(let i=0;i<this.data.length;i++){\n deg += this.data[i][point]\n }\n } else {\n for(let i=0;i<this.col;i++){\n deg += this.data[i][point]+this.data[i][i];\n }\n }\n return deg;\n }\n /**\n * 邻接矩阵计算入度\n * @param {} point 第i个结点\n * @param {boolean} isVector 是否是有向图\n */\n degIn(point: number, isVector = false) {\n let deg = 0;\n if (isVector) {\n for(let i=0;i<this.data.length;i++){\n deg += this.data[point][i];\n }\n } else {\n for (let i = 0; i < this.data.length; i++) {\n deg += this.data[point][i] + this.data[i][i];\n }\n }\n return deg;\n }\n}\n" }, { "alpha_fraction": 0.5313469767570496, "alphanum_fraction": 0.5493482351303101, "avg_line_length": 28.83333396911621, "blob_id": "71acbe280c1916cc95433449edc9a602d9db3377", "content_id": "ebf4577f569c02a9fb76eefd7088de49fe889bed", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1611, "license_type": "permissive", "max_line_length": 65, "num_lines": 54, "path": "/statistics/CS/src/Link.cs", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/*\n* @Author: Jingyuexing\n* @Date: 2020-12-04 11:36:19\n* @Last Modified by: Jingyuexing\n* @Last Modified time: 2020-12-04 12:02:16\n*/\n\nnamespace Mathlib{\n class LinkNode{\n public LinkNode parent;\n public LinkNode child;\n public double element;\n public LinkNode(double element){\n this.element = element;\n this.parent = null;\n this.child = null;\n }\n }\n class Link{\n public LinkNode head;\n public LinkNode position;\n Link(){\n this.position = this.head = new LinkNode(0);\n }\n public void append(double element){\n this.position.child = new LinkNode(element);\n this.position.child.parent = this.position;\n }\n public void insert(double item,double element){\n LinkNode currNode = this.find(item);\n LinkNode newNode = new LinkNode(element);\n newNode.child = currNode.child.child;\n newNode.parent = currNode;\n }\n public LinkNode find(double element){\n LinkNode currNode = null;\n currNode = this.head.child;\n while(currNode!=null && currNode.element != element){\n currNode = currNode.child;\n }\n return currNode;\n }\n public void remove(double item){\n LinkNode currNode = this.find(item);\n currNode.parent = currNode.child;\n }\n public LinkNode frist(){\n return this.head.child;\n }\n public LinkNode last(){\n return this.position;\n }\n }\n}\n" }, { "alpha_fraction": 0.614814817905426, "alphanum_fraction": 0.644444465637207, "avg_line_length": 17, "blob_id": "c9b180ec9c3c50c79a820398b26f72029493aa44", "content_id": "a7e9560d81860174c018c7f017fa8c7d0c7e2f29", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 286, "license_type": "permissive", "max_line_length": 43, "num_lines": 15, "path": "/statistics/TypeScript/src/random.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "\n/**\n * [randomFloat description]\n */\nfunction randomFloat() {\n return Math.random()*100\n}\n\n/**\n * 生成整数型随机数\n * @param {number} max [description]\n * @param {number} min [description]\n */\nfunction randomInt(max:number,min:number) {\n return ~~(Math.random()*10000);\n}" }, { "alpha_fraction": 0.46992480754852295, "alphanum_fraction": 0.48120301961898804, "avg_line_length": 28.58333396911621, "blob_id": "9f08c8a581a1941420f17daeb720a18e0e8d3aad", "content_id": "f86e500d925244266cd3dd132f603d5521628aca", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1178, "license_type": "permissive", "max_line_length": 98, "num_lines": 36, "path": "/statistics/TypeScript/src/LeastSquare.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "import {Mean} from \"./Mean\";\ninterface Point{\n x:number;\n y:number;\n}\n/**\n * 最小二乘法\n * @param {Array<number>} ...a [数据集]\n * @param {Array<number>} ...b [数据集]\n * @param {number} n [回归线取值范围]\n * @return {Array<any>} [线性回归数据集]\n */\nfunction LeastSquare([...a]:Array<number>,[...b]:Array<number>,n:number):Array<any>{\n if(a instanceof Array && b instanceof Array){\n let __x__ = Mean(a); //求得x的平均值\n let __y__ = Mean(b); //求得y的平均值\n var total_1:number=0,total_2:number=0,_a_:number,_b_:number,y_:number,temp:Array<Point>=[];\n if(a.length!=b.length){\n throw TypeError(\"两个数组数据不符合\")\n }\n for(let i=0;i<a.length;i++){\n total_1= a[i]*b[i]-(a.length*__x__*__y__);\n total_2 = a[i]**2-(a.length*__x__**2); \n }\n _b_=total_1/total_2;\n _a_ = __y__ - _b_*__x__;\n for(let j=1;j<n;j++){\n y_=_b_*j+_a_;\n temp.push({x:j,y:y_});\n }\n return temp;\n }else{\n throw TypeError(\"参数必须是数组类型数据\");\n }\n}\nexport {LeastSquare};" }, { "alpha_fraction": 0.3333333432674408, "alphanum_fraction": 0.3333333432674408, "avg_line_length": 8, "blob_id": "cf95c4b9b604f92b02dbe8f22b868964e88c4ef4", "content_id": "e893984ac5ce815de846b3dcffab6a2d703d2453", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 13, "license_type": "permissive", "max_line_length": 8, "num_lines": 1, "path": "/statistics/CPP/README.md", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "# C++ 实现\n" }, { "alpha_fraction": 0.5793991684913635, "alphanum_fraction": 0.5922746658325195, "avg_line_length": 17, "blob_id": "24a3d297fcc88451e82415dd98c4e5f0c958ea3b", "content_id": "e2ce6b20b5ee26c4aaa146e7a4b1cf0e138d973b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 249, "license_type": "permissive", "max_line_length": 36, "num_lines": 13, "path": "/statistics/TypeScript/src/factorial.ts", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "/**\n * [Factorial 阶乘]\n * @param {number} n [阶乘数]\n * @return {number} [阶乘值]\n */\nfunction Factorial(n:number):number{\n\t\tlet total:number=1,k:number=n%1;\n\t\tfor(let i=1;i<=n;i++){\n\t\t\ttotal*=i;\n\t\t}\n\t\treturn total;\n\t}\nexport {Factorial}" }, { "alpha_fraction": 0.6153846383094788, "alphanum_fraction": 0.752136766910553, "avg_line_length": 18.5, "blob_id": "c012dcefeb57fb652fd9db0ff0bc60b46b9103dd", "content_id": "44b5d7f18be256741ab609f065e7dee130078447", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 117, "license_type": "permissive", "max_line_length": 27, "num_lines": 6, "path": "/statistics/C/include/sigmoid.h", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "#ifndef _SIGMOID_H\n#define _SIGMOID_H\n#include <math.h>\n#define E 2.718281828459045\ndouble sigmoid(double x);\n#endif\n" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 9, "blob_id": "e0a448914c3ba9eb1d2707f8beddefa12b6d9fa9", "content_id": "2043d37708a2b3b27b411e99e71e6b845383212f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 14, "license_type": "permissive", "max_line_length": 9, "num_lines": 1, "path": "/statistics/Java/README.md", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "# Java 实现\n" }, { "alpha_fraction": 0.45512819290161133, "alphanum_fraction": 0.6410256624221802, "avg_line_length": 30.200000762939453, "blob_id": "4e066a98e64739d39723041d91822e894db7df9b", "content_id": "4360ddccb00a9e8b5bc09e2d3471e463b0412f74", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 156, "license_type": "permissive", "max_line_length": 42, "num_lines": 5, "path": "/statistics/python/src/cov.py", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Author: Jingyuexing\n# @Date: 2020-05-30 03:45:37\n# @Last Modified by: Jingyuexing\n# @Last Modified time: 2020-05-30 03:45:45\n" }, { "alpha_fraction": 0.5568181872367859, "alphanum_fraction": 0.5795454382896423, "avg_line_length": 15.090909004211426, "blob_id": "20b15d57fbd1c33d5b5df72fee46c87abad4ecd3", "content_id": "48d48a96b94b093ccf478d3b2a45665b5d6536a1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 176, "license_type": "permissive", "max_line_length": 39, "num_lines": 11, "path": "/statistics/Java/com/mathlib/Harmonic.java", "repo_name": "jingyuexing/MathLib", "src_encoding": "UTF-8", "text": "package com.mathlib;\n\nclass Harmonic{\n public static double Harmonic(int n){\n double total =0.0;\n for(int i=0;i<n;i++){\n total+=(1/i);\n }\n return total;\n }\n}" } ]
145
apotoczek/axp_sandbox
https://github.com/apotoczek/axp_sandbox
36e6d5a9479752955d6809fdce82c896223f22df
a6395299873a0facf5f21b262e3391b9060f0f27
0e7acf691c2ffdff4be230cc305fbe9e3b164843
refs/heads/master
2023-09-01T01:20:22.659186
2021-09-22T16:40:31
2021-09-22T16:40:31
251,689,503
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5264623761177063, "alphanum_fraction": 0.5705664157867432, "avg_line_length": 16.933332443237305, "blob_id": "7c19b3fa635cd2d187c799448ee00f435b8fbdab", "content_id": "5e162e304b9b5ffafc8b127c7b6817634b19ec28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2154, "license_type": "no_license", "max_line_length": 80, "num_lines": 120, "path": "/sandbox.py", "repo_name": "apotoczek/axp_sandbox", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\n# import random\n#\n# res = random.sample(range(0, 7), 7)\n#\n# print(\"Random number list is : \" + str(res))\n#\n# print(res[6])\n\n\n# def isprime(n):\n#\t'''check if integer n is a prime'''\n#\n#\t# make sure n is a positive integer\n#\tn = abs(int(n))\n#\n#\t# 0 and 1 are not primes\n#\tif n < 2:\n#\t\treturn False\n#\n#\t# 2 is the only even prime number\n#\tif n == 2:\n#\t\treturn True\n#\n#\t# all other even numbers are not primes\n##\tif not n & 1:\n##\t\treturn False\n#\n#\t# range starts with 3 and only needs to go up\n#\t# the square root of n for all odd numbers\n#\tfor x in range(3, int(n**0.5) + 1, 2):\n#\t\tif n % x == 0:\n#\t\t\treturn False\n#\n#\treturn True\n#\n# print(isprime(11))\n\n\n#\n# try:\n#\tl = (1, 2, 3, 4)\n# except Ex\n# print(l.index(5))\n\n\n# import random\n# my_randoms = random.sample(xrange(0, 10), 10)\n# print(my_randoms)\n\n\n# import random\n# my_randoms = [random.randrange(0,10,1) for _ in range(10)]\n# print(my_randoms)\n\n\nimport uuid\n\nfoo = []\nbar = []\nfor i in range(0, 10, 1):\n foo.append(uuid.uuid4().hex)\n bar.append(uuid.uuid4().hex)\n\n# foo = [2, 9, 8, 4, 5, 6, 0, 1, 7, 3]\n# bar = [2, 8, 7, 1, 9, 3, 4, 5, 0, 6]\n\n# foo = [2, 9, 8, 4, 5, 6, 0, 1, 2, 2]\n# bar = [2, 8, 7, 1, 9, 3, 4, 5, 0, 0]\n\n\nsfoo = set(foo)\nsbar = set(bar)\n\n# print('sfoo: ' + str(sfoo))\n# print('sbar: ' + str(sbar))\n\ndelta_foo = sfoo.difference(sbar)\n# if not delta_foo:\n# print('foo - no difference: ' + str(delta_foo))\n# else:\n# print('foo - difference: bar missing ' + str(delta_foo))\n\ndelta_bar = sbar.difference(sfoo)\n# if not delta_bar:\n# print('bar - no difference: ' + str(delta_bar))\n# else:\n# print('bar - difference: foo missing ' + str(delta_bar))\n\nlength = 0\nif len(sfoo) > len(sbar):\n length = len(sfoo)\nelse:\n length = len(sbar)\n\nslength = 0\nif len(delta_foo) > len(delta_bar):\n slength = len(delta_foo)\nelse:\n slength = len(delta_bar)\n\n# print(\n#\tstr(length) + ' - (' + str(len(delta_foo)) + ' + ' + str(len(delta_bar)) + ')'\n#\t)\nprint(\n str(length) + ' - ' + str(slength)\n)\n\n# import uuid\n#\n# l1 = []\n# l2 = []\n#\n# for i in range(0, 10, 1):\n#\tl1.append(uuid.uuid4().hex)\n#\tl2.append(uuid.uuid4().hex)\n\n# print(l1)\n# print(l2)\n\n\n" }, { "alpha_fraction": 0.5983899831771851, "alphanum_fraction": 0.6109123229980469, "avg_line_length": 20.5, "blob_id": "a1c6a928fc9e3c5ede8fbbed8cd48126160b1830", "content_id": "f53644a9d7307e3e1cdf25e5a20a6470c35e3f0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1118, "license_type": "no_license", "max_line_length": 94, "num_lines": 52, "path": "/csvdif.py", "repo_name": "apotoczek/axp_sandbox", "src_encoding": "UTF-8", "text": "import sys\nimport argparse\nimport csv\nimport pprint\n\n\ndef get_dataset(f):\n dataset = set(map(tuple, csv.reader(f)))\n pprint.pprint(dataset)\n return dataset\n\n\ndef main(f1, f2, outfile, sorting_column):\n set1 = get_dataset(f1)\n set2 = get_dataset(f2)\n different = set1 ^ set2\n\n output = csv.writer(outfile)\n\n for row in sorted(different, key=lambda x: x[sorting_column], reverse=True):\n output.writerow(row)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n parser.add_argument('infile', nargs=2, type=argparse.FileType('r'))\n parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'), default=sys.stdout)\n parser.add_argument('-sc', '--sorting-column', nargs='?', type=int, default=0)\n\n args = parser.parse_args()\n\n main(*args.infile, args.outfile, args.sorting_column)\n\n# import sys\n#\n#\n# def csv_compare(*args):\n# if len(args) == 2:\n# print(args)\n# else:\n# print(len(args))\n#\n#\n# def main():\n# csv_compare('one', 'two')\n# csv_compare()\n# csv_compare(1,2,3)\n#\n#\n# if __name__ == \"__main__\":\n# main()\n" }, { "alpha_fraction": 0.4895288050174713, "alphanum_fraction": 0.5314136147499084, "avg_line_length": 20.22222137451172, "blob_id": "31675ae0d5f7f93bf64a1fe22b380cc309cac0f3", "content_id": "c22e9e7368c6a58d42dbf59bfdad7aa4a7366a94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 382, "license_type": "no_license", "max_line_length": 64, "num_lines": 18, "path": "/csvdif3.py", "repo_name": "apotoczek/axp_sandbox", "src_encoding": "UTF-8", "text": "f1 = open('fixtures/a.csv', 'r')\nf2 = open('fixtures/b.csv', 'r')\nline = 0\n\nprint('Differences Found')\n\nwhile True:\n lineF1 = f1.readline().strip()\n lineF2 = f2.readline().strip()\n line += 1\n\n if lineF1 or lineF2:\n if lineF1 != lineF2:\n print(\"Line %d (%s vs %s)\" % (line, lineF1, lineF2))\n else:\n f1.close()\n f2.close()\n break\n" }, { "alpha_fraction": 0.6521739363670349, "alphanum_fraction": 0.7028985619544983, "avg_line_length": 22, "blob_id": "182311ca67fd067df1170d3ff06ab6aff4beac84", "content_id": "26023e924e994b59dd452c54110a8de5d4465620", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 138, "license_type": "no_license", "max_line_length": 39, "num_lines": 6, "path": "/csvpan.py", "repo_name": "apotoczek/axp_sandbox", "src_encoding": "UTF-8", "text": "import pandas as pd\n\nf1 = pd.read_csv('fixtures/pana.csv')\nf2 = pd.read_csv('fixtures/panb.csv')\n\nprint(f2[~f2.column1.isin(f1.column1)])\n" }, { "alpha_fraction": 0.5076320767402649, "alphanum_fraction": 0.5236790776252747, "avg_line_length": 26.180850982666016, "blob_id": "fddb5697225cbb61446987a349d613aa897f30c8", "content_id": "bdc21490907f36eac1fbc3f54fe2d2ef732650ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2555, "license_type": "no_license", "max_line_length": 118, "num_lines": 94, "path": "/compare.py", "repo_name": "apotoczek/axp_sandbox", "src_encoding": "UTF-8", "text": "import sys\nimport getopt\nimport uuid\nimport time\n\n\ndef gen_files(n, c):\n print('Generating files with ' + str(n) + ' strings, ' + str(c) + ' in common:')\n\n foo_name = 'foo_' + str(int(time.time())) + '.txt'\n print(foo_name)\n\n bar_name = 'bar_' + str(int(time.time())) + '.txt'\n print(bar_name)\n\n foo = []\n bar = []\n if 0 < c <= n:\n for i in range(0, n, 1):\n foo.append(uuid.uuid4().hex)\n bar = foo[:c]\n for i in range(0, n - c, 1):\n bar.append(uuid.uuid4().hex)\n else:\n for i in range(0, n, 1):\n foo.append(uuid.uuid4().hex)\n bar.append(uuid.uuid4().hex)\n\n with open(foo_name, 'w') as f:\n for s in foo:\n f.write(\"%s\\n\" % s)\n\n with open(bar_name, 'w') as f:\n for s in bar:\n f.write(\"%s\\n\" % s)\n\n\ndef compare(foo_name, bar_name):\n print('Processing ' + foo_name + '...')\n foo = [line.rstrip('\\n') for line in open(foo_name)]\n print('Processing ' + bar_name + '...')\n bar = [line.rstrip('\\n') for line in open(bar_name)]\n\n sfoo = set(foo)\n sbar = set(bar)\n delta_foo = sfoo.difference(sbar)\n delta_bar = sbar.difference(sfoo)\n\n length = 0\n if len(sfoo) > len(sbar):\n length = len(sfoo)\n else:\n length = len(sbar)\n\n slength = 0\n if len(delta_foo) > len(delta_bar):\n slength = len(delta_foo)\n else:\n slength = len(delta_bar)\n\n common = length - slength\n print('There are ' + str(common) + ' strings in common between the files')\n\n\ndef main(argv):\n n = 0\n c = 0\n try:\n opts, args = getopt.getopt(argv, 'hn:c:', ['nstrings=', 'common='])\n except getopt.GetoptError:\n print('compare.py -n <gen files with n strings gte 1 lte 1M> -c <number of common strings between files>')\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n print('compare.py -n <gen files with n strings gte 1 lte 1M> -c <number of common strings between files>')\n sys.exit()\n elif opt in (\"-n\", \"--nstrings\"):\n n = int(arg)\n elif opt in (\"-c\", \"--common\"):\n c = int(arg)\n\n if 1 <= n <= 1000000 and 0 <= c <= 1000000:\n gen_files(n, c)\n elif n == 0:\n foo_name = input('File foo: ')\n bar_name = input('File bar: ')\n compare(foo_name, bar_name)\n else:\n print('compare.py -n <gen files with n strings gte 1 lte 1M> -c <number of common strings between files>')\n sys.exit(2)\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n" }, { "alpha_fraction": 0.5206286907196045, "alphanum_fraction": 0.5579567551612854, "avg_line_length": 25.789474487304688, "blob_id": "cade480f09c4c4626fdd5d1195c5bd6923bd7605", "content_id": "16f169dc87a3c200b3b334f3696d9a380afa97a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 509, "license_type": "no_license", "max_line_length": 65, "num_lines": 19, "path": "/csvdif2.py", "repo_name": "apotoczek/axp_sandbox", "src_encoding": "UTF-8", "text": "import time\n\n\ndef main(f1, f2, outfile):\n with open(f1, 'r') as csv1, open(f2, 'r') as csv2:\n lines1 = csv1.readlines()\n lines2 = csv2.readlines()\n\n with open(outfile, 'w') as outFile:\n for line in lines2:\n if line not in lines1:\n outFile.write(line)\n\n\nif __name__ == '__main__':\n input1 = input('CSV 1: ')\n input2 = input('CSV 2: ')\n default_outfile = 'csvdif2_' + str(int(time.time())) + '.txt'\n main(input1, input2, outfile=default_outfile)\n" }, { "alpha_fraction": 0.5229358077049255, "alphanum_fraction": 0.538226306438446, "avg_line_length": 26.25, "blob_id": "1a1af2965aac6fb0b6ac1cb6b5d125512dbe6d8a", "content_id": "98f98dcc972d97fd8fa83e7ccd600a0a5cd7541b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1635, "license_type": "no_license", "max_line_length": 109, "num_lines": 60, "path": "/distinct.py", "repo_name": "apotoczek/axp_sandbox", "src_encoding": "UTF-8", "text": "import sys\nimport getopt\nimport random\n\n\ndef random_num(n, distinct):\n print('\\n')\n if distinct:\n print('Distinct seed list:')\n my_randoms = random.sample(range(0, n), n)\n else:\n print('Non-distinct seed list:')\n my_randoms = [random.randrange(0, n, 1) for _ in range(n)]\n\n print(my_randoms)\n print('\\n')\n return my_randoms\n\n\ndef distinct_num(ran_list):\n unq_list = []\n j = 0\n for i in range(len(ran_list)):\n if i > 0 and j != 0 or i == 0:\n if ran_list[j] in unq_list:\n break\n unq_list.append(ran_list[j])\n j = ran_list[j]\n\n print('Distinct values found using algorithm and their count:')\n print(str(unq_list) + \" \" + str(len(unq_list)))\n print('\\n')\n\n\ndef main(argv):\n n = 0\n d = False\n try:\n opts, args = getopt.getopt(argv, 'hn:d:', ['nlength=', 'distinct='])\n except getopt.GetoptError:\n print('distinct.py -n <seed list length gt 1 lte 1M> -d <seed with distinct ints default False>')\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n print('distinct.py -n <seed list length gt 1 lte 1M> -d <seed with distinct ints True or False>')\n sys.exit()\n elif opt in (\"-n\", \"--nlength\"):\n n = int(arg)\n elif opt in (\"-d\", \"--distinct\"):\n d = (arg.lower() == 'true')\n\n if 1 < n <= 1000000:\n distinct_num(random_num(n, d))\n else:\n print('distinct.py -n <seed list length gt 1 lte 1M> -d <seed with distinct ints True or False>')\n sys.exit(2)\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n" }, { "alpha_fraction": 0.6969011425971985, "alphanum_fraction": 0.7349016070365906, "avg_line_length": 41.932037353515625, "blob_id": "4b93c23dd3a3c0af1d66517dd53332dee6a676b3", "content_id": "251f608de881b38678d9fd00f2729cfdfaad5489", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4425, "license_type": "no_license", "max_line_length": 518, "num_lines": 103, "path": "/README.md", "repo_name": "apotoczek/axp_sandbox", "src_encoding": "UTF-8", "text": "# Assessment\n\n1. [Distinct Numbers](#1-distinct-numbers)\n2. [Strings Comparison](#2-strings-comparison)\n\n## 1. Distinct Numbers\n\n#### Question:\n\n> The generator starts by returning the value at index 0. ​It then uses that value as the index for the next value to return, and so on​. If the generator was seeded with the list [1, 2, 0], the first number it would return would be 1, then 2, then 0, and then it would repeat the sequence. Thus, the number of distinct values would be 3.\"\n\n#### Part a:\n\n> Write a function that takes as input the seed list of the random number generator of up to 1 million integers and returns the count of distinct integers the random number generator would return.\n\n#### Solution:\n\nPython script `distinct.py`, executable from CLI, e.g.: `python distinct.py -n 10 -d False`\n\nArgs:\n\n`-n, --nlength` length of the random integer seed list, 1 < n <= 1M\n\n`-d, --distinct` True or False, generate seed list of distinct or non-distinct ints\n\n#### Examples:\n\n```\n$ python distinct.py -n 10 -d True\nDistinct seed list:\n[2, 9, 8, 4, 5, 6, 0, 1, 7, 3]\nDistinct values found using algorithm and their count:\n[2, 8, 7, 1, 9, 3, 4, 5, 6, 0] 10\n```\n\n```\n$ python distinct.py -n 10 -d False\nNon-distinct seed list:\n[3, 9, 5, 6, 8, 7, 1, 6, 9, 3]\nDistinct values found using algorithm and their count:\n[3, 6, 1, 9] 4\n```\n\n> Note: per requirements, the final count number (10, or 4 in examples) stops checking for further distinct ints once a dupe is found; the bottom list printed shows the ints counted.\n\n> Note: script developed with Python 3.8.2 using virtualenv, but works in 2.7, 3.4, 3.6\n\n#### Implementation:\n\nScript executes the seed generator `random_num(n, distinct)` and passes the seed list to the algorithm in `distinct_num(ran_list)`, which traverses the seed list and saves each distinct value to a new list, for comparison to the next loop iteration, until a duplicate is found or the whole list has been checked. The new list length then represents the count of distinct values in the seed list, according to the algorithm defined in the requirements. Once a duplicate is found, no further distinct ints are counted.\n\n#### Part b:\n\n> Can part a be done with O(1) auxiliary space (i.e. using only a constant amount of additional memory)? If so, write a function that does it. If not, why not?\n\n#### Answer:\n\nThe algorithm takes a seed list of arbitrary length based on user input, so it cannot be assigned a Constant complexity. It is O(n), Linear complexity based on the length of the seed list iterated through in a loop. \n\n\n## 2. Strings Comparison\n\n#### Question:\n\n> Write a program that reads in the names of two files from STDIN and outputs the number of strings they have in common to STDOUT. Each file contains 1 million strings of 32 characters, 1 per line.\n\n#### Part a:\n\nPython script `compare.py` executable from CLI can generate two sample txt files of -n number 32 char strings, either distinct, or some strings in common -c.\n\nArgs:\n\n**Generate sample files (foo.. and bar..):**\n\n`-n, --nstrings` Number of strings to generate in files, 1 <= n <= 1000000\n\n`-c, --common` Number of common strings between the generated files, 0 <= c <= 1000000 (if n == c the files will be identical)\n\nE.g.: `compare.py -n 10 -c 0` or `compare.py -n 10 -c 3`\n```\n$ python compare.py -n 10 -c 3\nGenerating files with 10 strings, 3 in common:\nfoo_1585939656.txt\nbar_1585939656.txt\n```\n\n**Process files and print number of strings in common:**\n\nCalling `compare.py` without arguments will prompt to enter the two filesnames for compare. Function `compare(foo_name, bar_name)` creates a list of strings for each file, then compares the lists to calculate number of common strings.\n\nE.g.:\n```\n$ python compare.py\nFile foo: foo_1585939656.txt\nFile bar: bar_1585939656.txt\nProcessing foo_1585939656.txt...\nProcessing bar_1585939656.txt...\nThere are 3 strings in common between the files\n``` \n\n#### Part b:\n\nThe standard file processing and lists, as implemented in this solution, are not well suited for billions of strings. Beyond a million, there are libraries that can be leveraged for better analysis and advanced data structures like numpy, pandas, and tools like jupiter notebooks. Alternately, instead of reading the files and converting them to lists within the function, the data could be loaded into a database, which would be better suited for reading/writing large amounts of data." } ]
8
warrenregister/GEMSEC_web_prototype
https://github.com/warrenregister/GEMSEC_web_prototype
af63ad732feca496daea68ae85d6653d747ead5d
2fc26629165913899672f76998fc3184848cef7f
f299c2f594fbc9f2821d3d9d7c4d64ab60517ab9
refs/heads/master
2022-11-16T14:54:05.153061
2020-07-10T21:17:47
2020-07-10T21:17:47
278,734,193
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6584938764572144, "alphanum_fraction": 0.6725043654441833, "avg_line_length": 29.105262756347656, "blob_id": "3d884a3ec63efc510a6260d3d2447cd130777d4e", "content_id": "8d2a63c150c84a6007eb7d29dbe03240d1d8528d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 571, "license_type": "no_license", "max_line_length": 92, "num_lines": 19, "path": "/flask_website/static/js/script.js", "repo_name": "warrenregister/GEMSEC_web_prototype", "src_encoding": "UTF-8", "text": "var button = document.getElementById('enter_button');\nvar input = document.getElementById('input');\nvar ul = document.getElementById('results')\n\nfunction performQuery(){\n if (input.value.length > 0) {\n var li = document.createElement('li');\n li.appendChild(document.createTextNode('3123 ngs_mos1_conv.csv Warren Register'));\n ul.appendChild(li);\n }\n}\n\nbutton.addEventListener(\"click\", performQuery);\ninput.addEventListener(\"keyup\", function(event) {\n event.preventDefault();\n if (event.keyCode === 13) {\n button.click();\n }\n})" }, { "alpha_fraction": 0.7234042286872864, "alphanum_fraction": 0.7446808218955994, "avg_line_length": 28.736841201782227, "blob_id": "f71a0f783f337f697b08a06960b85737dec0daa6", "content_id": "d33280ddd7c1b644756a7179e13b770b722b0bc3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 564, "license_type": "no_license", "max_line_length": 108, "num_lines": 19, "path": "/fastAPI_website/main.py", "repo_name": "warrenregister/GEMSEC_web_prototype", "src_encoding": "UTF-8", "text": "from fastapi import FastAPI, Request\nfrom fastapi.staticfiles import StaticFiles\nfrom fastapi.templating import Jinja2Templates\nimport uvicorn\n\napp = FastAPI(debug=True)\n\napp.mount(\"/static\", StaticFiles(directory='static'), name=\"static\") # Mount static files, specify directory\n\n\ntemplates = Jinja2Templates(directory='templates') #Template Directory\n\n\[email protected](\"/data/\")\nasync def read_data(request: Request):\n return templates.TemplateResponse(\"about.html\", {\"request\": request})\n\nif __name__ == '__main__':\n uvicorn.run(app, host=\"127.0.0.1\", port=8000)" }, { "alpha_fraction": 0.5517241358757019, "alphanum_fraction": 0.5632184147834778, "avg_line_length": 20.8125, "blob_id": "3e86e7183c7a902fbd1f046320cee095c70af9c9", "content_id": "14086a509ab8a702725f8ca6c5e5baa5c3f47cf7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 348, "license_type": "no_license", "max_line_length": 59, "num_lines": 16, "path": "/fastAPI_website/templates/index.html", "repo_name": "warrenregister/GEMSEC_web_prototype", "src_encoding": "UTF-8", "text": "{% extends 'base.html' %}\n\n{% block head %}\n<h1>Template</h1>\n{% endblock %}\n\n{% block body%}\n <h1>Meta Data Search Test</h1>\n <div id='search'>\n <input id='input' type=\"text\" placeholder=\"Search..\">\n <button id='enter_button' type=\"submit\">Submit</button>\n </div>\n <ul id='results'>\n <li>test</li>\n </ul>\n{% endblock %}" }, { "alpha_fraction": 0.5393548607826233, "alphanum_fraction": 0.5645161271095276, "avg_line_length": 43.31428527832031, "blob_id": "a636780aeec68b4fe544e53101db7fce1030010e", "content_id": "e8582912b7bed1968b1edb35eceaf8a7307be02d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1550, "license_type": "no_license", "max_line_length": 115, "num_lines": 35, "path": "/py_scripts/fake_db.sql", "repo_name": "warrenregister/GEMSEC_web_prototype", "src_encoding": "UTF-8", "text": "DROP TABLE IF EXISTS desc_files;\nDROP TABLE IF EXISTS ngs;\n\nCREATE TABLE ngs(\n file_id TEXT PRIMARY KEY,\n code TEXT references desc_files,\n file_loc TEXT\n );\n\nCREATE TABLE md(\n file_id TEXT PRIMARY KEY,\n code TEXT references desc_files,\n file_loc TEXT\n);\n\nCREATE TABLE desc_files(\n code TEXT PRIMARY KEY,\n file_loc TEXT\n);\n\nINSERT INTO ngs VALUES ('ngs_0', 'code1_code5', './ngs/ngs1.csv'),\n ('ngs_1', 'code1_code6', './ngs/ngs1.csv');\n\nINSERT INTO md VALUES ('md_0', 'code2_code3_code5', './ngs/ngs1.csv'),\n ('md_1', 'code2_code3_code6', './ngs/ngs1.csv'),\n ('md_2', 'code2_code4_code5', './ngs/ngs1.csv'),\n ('md_3', 'code2_code4_code6', './ngs/ngs1.csv'),\n ('md_4', 'code2_code3_code5', './ngs/ngs1.csv');\n \nINSERT INTO desc_files VALUES ('code1', '/Users/warren/Documents/Meta_Data_Site/descriptions/ngs_description.txt'),\n ('code2', '/Users/warren/Documents/Meta_Data_Site/descriptions/md_description.txt'),\n ('code3', '/Users/warren/Documents/Meta_Data_Site/descriptions/parameters_A.txt'),\n ('code4', '/Users/warren/Documents/Meta_Data_Site/descriptions/parameters_B.txt'),\n ('code5', '/Users/warren/Documents/Meta_Data_Site/descriptions/jackson_frank.txt'),\n ('code6', '/Users/warren/Documents/Meta_Data_Site/descriptions/warren_register.txt');" }, { "alpha_fraction": 0.6126401424407959, "alphanum_fraction": 0.6233435273170471, "avg_line_length": 27.042856216430664, "blob_id": "93310a5b74bb1b5474490693832dde5d83476fd8", "content_id": "29b2d9e3d85a294b32b64f3d182dbf46f3ec33e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1962, "license_type": "no_license", "max_line_length": 72, "num_lines": 70, "path": "/flask_website/fake_server.py", "repo_name": "warrenregister/GEMSEC_web_prototype", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, request\nfrom flask_sqlalchemy import SQLAlchemy\nfrom datetime import datetime\nimport sys, os\nsys.path.insert(0, os.path.dirname(sys.path[0]) + '/py_scripts/')\nfrom make_query import query_db\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'\ndb = SQLAlchemy(app)\n\nclass NGS(db.Model):\n '''\n SQLAlchemy Table schema descriptor class for NGS files\n '''\n file_id = db.Column(db.String(10), primary_key=True, nullable=False)\n code = db.Column(db.String(15), nullable=False)\n file_loc = db.Column(db.String(200), nullable=False)\n\n def __repr__(self):\n return'<NGS %r>' % self.file_loc\n \n def __str__(self):\n return 'ngs'\n\n\nclass MD(db.Model):\n '''\n SQLAlchemy Table schema descriptor class for MD files\n '''\n file_id = db.Column(db.String(10), primary_key=True, nullable=False)\n code = db.Column(db.String(15), nullable=False)\n file_loc = db.Column(db.String(200), nullable=False)\n\n def __repr__(self):\n return'<MD %r>' % self.file_loc\n \n def __str__(self):\n return 'md'\n\n\nclass Descriptions(db.Model):\n '''\n SQLAlchemy Table schema descriptor class for Description files\n '''\n code = db.Column(db.String(10), primary_key=True, nullable=False)\n file_loc = db.Column(db.String(200), nullable=False)\n\n def __repr__(self):\n return'<Description %r>' % self.file_loc\n \n def __str__(self):\n return ('descriptions')\n\n\[email protected]('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'POST':\n search_query = request.form['search_bar']\n rows = query_db(search_query, [NGS, MD], Descriptions)\n if rows != None:\n return render_template('about.html', results=rows)\n else:\n return render_template('about.html')\n else:\n return render_template('about.html')\n\n\nif __name__ == '__main__':\n app.run(debug=True)" }, { "alpha_fraction": 0.8399999737739563, "alphanum_fraction": 0.8399999737739563, "avg_line_length": 24, "blob_id": "3d7c1caee740247a98bc47946f8ef14990f3c4c9", "content_id": "77bcdba24f0268dc3632a1b4201eb6951800ef2b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 25, "license_type": "no_license", "max_line_length": 24, "num_lines": 1, "path": "/README.md", "repo_name": "warrenregister/GEMSEC_web_prototype", "src_encoding": "UTF-8", "text": "Meta Data Site Prototype\n" }, { "alpha_fraction": 0.5450623035430908, "alphanum_fraction": 0.5469798445701599, "avg_line_length": 27.589040756225586, "blob_id": "7b56d04a2b1057a4726607dfcfca6bfc171b69e5", "content_id": "ccd682b733b808d8fbd2d72a6060c7db0ce535d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2086, "license_type": "no_license", "max_line_length": 78, "num_lines": 73, "path": "/py_scripts/document.py", "repo_name": "warrenregister/GEMSEC_web_prototype", "src_encoding": "UTF-8", "text": "'''\nThis class implements the Document class which provides functionality for\nunderstanding and analyzing the contents of local documents.\n'''\n\nimport re\n\n\nclass Document():\n def __init__(self, file_names, code, entry):\n '''\n Initializes Document object with a dictionary of each unique token\n in the given file and its frequency in that file.\n\n name: file path of a document\n '''\n self._file_names = file_names\n self._terms = {}\n self._code = code\n self._entry = entry\n for file_name in self._file_names:\n with open(file_name) as f:\n words = f.read().split()\n for word in words:\n word = self._ignore_case_punct(word)\n if word not in self._terms:\n self._terms[word] = 0\n self._terms[word] += 1 / len(words)\n\n def term_frequency(self, term):\n '''\n Returns the frequency of a given term in the docment initialized upon,\n if the term isn't in the document, returns 0.\n '''\n term = self._ignore_case_punct(term)\n return(self._terms[term] if term in self._terms else 0)\n\n def get_path(self):\n '''\n Returns the path of the document.\n '''\n return self._file_name\n\n def get_words(self):\n '''\n Returns a list of the unique terms in the document.\n '''\n return list(self._terms.keys())\n \n def get_code(self):\n '''\n Returns description file code.\n '''\n return self._code\n\n def get_file_id(self):\n '''\n Returns file_id for file being represented by description files.\n '''\n return self._entry.file_id\n\n def get_entry(self):\n '''\n Returns row object from database.\n '''\n return self._entry\n\n def _ignore_case_punct(self, word):\n '''\n Takes in a string and returns the string in lower case with any\n punctuation removed.\n '''\n return re.sub(r'\\W+', '', word.lower())" }, { "alpha_fraction": 0.64161616563797, "alphanum_fraction": 0.6428282856941223, "avg_line_length": 25.89130401611328, "blob_id": "1bf1c245bef52ad4a35986de809a518354d1e707", "content_id": "8e14b41fe9de500c46688801c01a16710df30acf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2475, "license_type": "no_license", "max_line_length": 75, "num_lines": 92, "path": "/py_scripts/make_query.py", "repo_name": "warrenregister/GEMSEC_web_prototype", "src_encoding": "UTF-8", "text": "'''\nFile contains method for making sql query to database.\n'''\n\nimport pandas as pd\nfrom document import Document\nfrom search_engine import SearchEngine\n\n\ndef get_descriptions(Descriptions):\n '''\n Returns the code and file path each file in the Descriptions\n table in an SQLite database.\n Arguments ----\n Descriptions: SQLAlchemy object for Descriptions table\n '''\n descs = Descriptions.query.all()\n tups = []\n for desc in descs:\n tups.append((desc.code, desc.file_loc))\n return tups\n\ndef get_codes(tables):\n '''\n Returns the result of a query of tables in an SQLite databse for their\n codes and file_ids.\n Arguments ----\n tables: list of SQLAlchemy table objects in SQLite databse.\n '''\n entries = []\n files = []\n for table in tables:\n entries += table.query.all()\n return entries\n\n\ndef generate_documents(files, descs):\n '''\n Returns Document objects generated for files stored in the SQLite\n database based on their associated description files.\n\n Arguments ----\n files: list of file_ids and codes for files in SQLite database.\n descs: list of codes and file paths for description files stored in\n SQLite database.\n '''\n docs = []\n for file in files:\n codes = file.code\n rel_descs = []\n for desc in descs:\n if desc[0] in codes:\n rel_descs.append(desc[1])\n docs.append(Document(rel_descs, file.code, file))\n return docs\n \n\ndef query_results(results, tables):\n '''\n Returns results of query for files which match results of search engine\n query.\n\n Arguments ----\n results: Output of search engine, ranked list of files based on\n relatedness to inputed search query.\n cursor: SQLlite connection cursor on databse with given information.\n '''\n table_data = []\n tables_str = ['ngs', 'md']\n for id in results:\n for i, table in enumerate(tables):\n if tables_str[i] == id.split('_')[0]:\n result = table.query.filter_by(file_id=id).first()\n table_data.append(result)\n return table_data\n\n\n\ndef query_db(query, tables, Descriptions):\n files = get_codes(tables)\n desc_files = get_descriptions(Descriptions)\n docs = generate_documents(files, desc_files)\n\n\n engine = SearchEngine(docs)\n search_results = engine.search(query)\n\n return search_results\n\n\nif __name__ == '__main__':\n query_db('warren register, ngs')\n\n" }, { "alpha_fraction": 0.576117992401123, "alphanum_fraction": 0.5789723992347717, "avg_line_length": 34.04999923706055, "blob_id": "6b96bff11b13b69b01b6e525fdf803586ebc0eca", "content_id": "b2a3f11e21d4e9e919ef63310d686fc41cb36143", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2102, "license_type": "no_license", "max_line_length": 78, "num_lines": 60, "path": "/py_scripts/search_engine.py", "repo_name": "warrenregister/GEMSEC_web_prototype", "src_encoding": "UTF-8", "text": "'''\nThis class implements a basic search engine on local files\n'''\n\nfrom document import Document\nimport os\nimport math\nimport re\n\n\nclass SearchEngine():\n def __init__(self, documents):\n '''\n Method to initialize Search Engine object and analyze each document in\n given directory to create inverse index with the words as keys and\n a list of each document containting each word as the values.\n '''\n self._docs = documents\n self._inverse_index = {}\n for doc in self._docs:\n for word in doc.get_words():\n if word not in self._inverse_index:\n self._inverse_index[word] = []\n self._inverse_index[word].append(doc)\n self._docs = len(self._docs)\n\n def _calculate_idf(self, term):\n '''\n Returns the inverse document frequency of a given term in the corpus\n of documents in the directory this object was initialized upon. If the\n given term is not in corpus, returns 0.\n '''\n if term in self._inverse_index:\n return math.log(self._docs / len(self._inverse_index[term]))\n else:\n return 0\n\n def search(self, terms):\n '''\n Returns a list of all documents containing the given term(s) sorted by\n the Term Frequency * Inverse Document Frequency of the term(s). If the\n given term(s) is / are not in any documents, returns None.\n '''\n terms = [re.sub(r'\\W+', '', term.lower()) for term in terms.split()]\n rankings = []\n rel_docs = set()\n for term in terms:\n if term in self._inverse_index.keys():\n rel_docs = set(list(rel_docs) + self._inverse_index[term])\n\n if len(rel_docs) == 0:\n return None\n\n for doc in rel_docs:\n tfidf = 0\n for term in terms:\n tfidf += doc.term_frequency(term) * self._calculate_idf(term)\n rankings.append((doc.get_entry(), tfidf))\n rankings.sort(key=lambda x: x[1], reverse=True)\n return([x[0] for x in rankings])" }, { "alpha_fraction": 0.5788273811340332, "alphanum_fraction": 0.5986970663070679, "avg_line_length": 29.709999084472656, "blob_id": "1a7a46d1fc1756554248621e779f16291b3d6f4d", "content_id": "a550cfc548767b565ac8cee96174fec14432aa45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3070, "license_type": "no_license", "max_line_length": 84, "num_lines": 100, "path": "/flask_website/setup.py", "repo_name": "warrenregister/GEMSEC_web_prototype", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, request\nfrom flask_sqlalchemy import SQLAlchemy\nfrom datetime import datetime\nimport sys, os\n\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'\ndb = SQLAlchemy(app)\n\nclass NGS(db.Model):\n '''\n SQLAlchemy Table schema descriptor class for NGS files\n '''\n file_id = db.Column(db.String(10), primary_key=True, nullable=False)\n code = db.Column(db.String(15), nullable=False)\n file_loc = db.Column(db.String(200), nullable=False)\n\n def __repr__(self):\n return'<NGS %r>' % self.file_loc\n \n def __str__(self):\n return 'ngs'\n\n\nclass MD(db.Model):\n '''\n SQLAlchemy Table schema descriptor class for MD files\n '''\n file_id = db.Column(db.String(10), primary_key=True, nullable=False)\n code = db.Column(db.String(15), nullable=False)\n file_loc = db.Column(db.String(200), nullable=False)\n\n def __repr__(self):\n return'<MD %r>' % self.file_loc\n \n def __str__(self):\n return 'md'\n\n\nclass Descriptions(db.Model):\n '''\n SQLAlchemy Table schema descriptor class for Description files\n '''\n code = db.Column(db.String(10), primary_key=True, nullable=False)\n file_loc = db.Column(db.String(200), nullable=False)\n\n def __repr__(self):\n return'<Description %r>' % self.file_loc\n \n def __str__(self):\n return ('descriptions')\n\n\ndef do_insert():\n '''\n Calls insert into function with parameters below.\n '''\n directory = os.path.dirname(sys.path[0])\n ids = ['ngs_0', 'ngs_1', 'md_0', 'md_1', 'md_2', 'md_3', 'md_4']\n paths = ['./ngs/ngs0.csv', './ngs/ngs1.csv', './md/md0.md', './md/md1.md',\n './md/md2.md', './md/md3.md', './md/md4.md',\n directory + '/descriptions/ngs_description.txt', \n directory + '/descriptions/md_description.txt',\n directory + '/descriptions/parameters_A.txt',\n directory + '/descriptions/parameters_B.txt', \n directory + '/descriptions/jackson_frank.txt',\n directory + '/descriptions/warren_register.txt']\n codes = ['code1_code5', 'code1_code6', 'code2_code3_code5', 'code2_code3_code6',\n 'code2_code4_code5', 'code2_code4_code6', 'code2_code3_code5', 'code1', \n 'code2', 'code3', 'code4', 'code5', 'code6']\n\n insert_into(ids, paths, codes)\n\n\ndef insert_into(ids, file_paths, codes) :\n '''\n Function which creates test databse by taking in a set number of file\n ids, paths, and codes.\n '''\n\n for index, path in enumerate(file_paths):\n entry = None\n if index < 2: # NGS files\n entry = NGS(file_id=ids[index], code=codes[index], file_loc=path)\n elif index < 7: # MD files\n entry = MD(file_id=ids[index], code=codes[index], file_loc=path)\n else: # Description files\n entry = Descriptions(code=codes[index], file_loc=path)\n db.session.add(entry)\n db.session.commit()\n\n\ndef main():\n db.create_all()\n do_insert()\n\n\nif __name__ == '__main__':\n main()" } ]
10
djmor12/Metis
https://github.com/djmor12/Metis
124e79843377510bd54e1c010ae43a109450d692
e194361d7d59641b085ed44dfcf330ad1995a1b5
809cc8cb71007512ef97aa745cbb656f0a716276
refs/heads/master
2020-03-09T20:57:11.926509
2018-09-23T02:07:37
2018-09-23T02:07:37
128,997,225
0
2
null
null
null
null
null
[ { "alpha_fraction": 0.5905118584632874, "alphanum_fraction": 0.6317103505134583, "avg_line_length": 27.60714340209961, "blob_id": "011701ba18f73ef4633bc9da586a3dd6817f5a66", "content_id": "028f1f763be86cd63fe8ddcad852bd3a012fd365", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1602, "license_type": "permissive", "max_line_length": 121, "num_lines": 56, "path": "/Talking Data/Flask/cat.py", "repo_name": "djmor12/Metis", "src_encoding": "UTF-8", "text": "import flask\nimport json\nimport numpy as np\nimport operator\nfrom catboost import CatBoostRegressor, CatBoostClassifier, Pool\n#import urllib2\n\napp = flask.Flask(__name__)\n\n#CatBoost\nmodel=CatBoostClassifier(iterations=20, depth=7, learning_rate=0.1, loss_function = 'MultiClass')\nmodel.load_model('catboost_model3.dump')\[email protected](\"/\")\ndef viz_page():\n \"\"\"\n Homepage: serve our visualization page\n \"\"\"\n with open(\"index.html\", 'r') as viz_file:\n return viz_file.read()\n\[email protected](\"/score\", methods=[\"POST\"])\ndef score():\n \"\"\"\n When A POST request with json data is made to this uri,\n Read the example from the json, predict probability and\n send it with a response\n \"\"\"\n # Get decision score for our example that came with the request\n data = flask.request.json\n color='#00dbfb'\n x = data[\"example\"]\n score = model.predict_proba([x])\n print(score)\n list1=[]\n for i in score[0]:\n list1.append(i)\n index, value = max(enumerate(list1), key=operator.itemgetter(1))\n print(index)\n clas = ['F23-', 'F24-26','F27-28','F29-32', 'F33-42', 'F43+', 'M22-', 'M23-26', 'M27-28', 'M29-31', 'M32-38', 'M39+']\n label = clas[index]\n if index <= 5:\n color ='#FF75A3'\n else:\n color ='#00dbfb'\n print(label)\n print(color)\n # Put the result in a nice dict so we can send it as json\n results = {\"score\":label,\"color\":color}\n return flask.jsonify(results)\n\n#--------- RUN WEB APP SERVER ------------#\n\n# Start the app server on port 80\n# (The default website port)\n#app.run(host='0.0.0.0')\n# app.run(debug=True)\n" }, { "alpha_fraction": 0.5129310488700867, "alphanum_fraction": 0.5431034564971924, "avg_line_length": 24.77777862548828, "blob_id": "d153e492800a852e2a4a78cd9c4c66d56e0f6660", "content_id": "0fa8c3336b28f5697bb403c15f810c86909f6ada", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 232, "license_type": "permissive", "max_line_length": 32, "num_lines": 9, "path": "/Talking Data/Flask/static/mod_dd.js", "repo_name": "djmor12/Metis", "src_encoding": "UTF-8", "text": "var d_dd = [\n {value: 6, text: 'Sunday'},\n {value: 0, text: 'Monday'},\n {value: 1, text: 'Tuesday'},\n {value: 2, text: 'Wednesday'},\n {value: 3, text: 'Thursday'},\n {value: 4, text: 'Friday'},\n {value: 5, text: 'Saturday'}\n]\n" }, { "alpha_fraction": 0.6698811054229736, "alphanum_fraction": 0.6833891868591309, "avg_line_length": 52.51632308959961, "blob_id": "e9ef3c2b2fd2fe2de4010c8e5ea63ea03198de19", "content_id": "7acbe8ae1fd37438ab419287848b1fe2273db356", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 656651, "license_type": "permissive", "max_line_length": 172, "num_lines": 12252, "path": "/TeaRecommendations/Flask/static/drop_down.js", "repo_name": "djmor12/Metis", "src_encoding": "UTF-8", "text": "var dropdown =[{value: 'Tuo Cha Pu-erh', text: 'Tuo Cha Pu-erh'},\n {value: 'Genmaicha Brown Rice Tea', text: 'Genmaicha Brown Rice Tea'},\n {value: 'Lapsang Souchong', text: 'Lapsang Souchong'},\n {value: 'Moonlight White', text: 'Moonlight White'},\n {value: 'Pu Er Vrac 28 (1998)', text: 'Pu Er Vrac 28 (1998)'},\n {value: 'Dong Fang Hong Wudong', text: 'Dong Fang Hong Wudong'},\n {value: 'Chai Matcha', text: 'Chai Matcha'},\n {value: 'Cherry Vanilla', text: 'Cherry Vanilla'},\n {value: 'Houji-cha (Premium Tea Bag)', text: 'Houji-cha (Premium Tea Bag)'},\n {value: 'Mint Chocolate Chip Black Tea', text: 'Mint Chocolate Chip Black Tea'},\n {value: 'Green Tea Plus Glow', text: 'Green Tea Plus Glow'},\n {value: 'Victorian Afternoon Tea', text: 'Victorian Afternoon Tea'},\n {value: 'Aged Tie Guan Yin', text: 'Aged Tie Guan Yin'},\n {value: 'Kenyan Sunrise', text: 'Kenyan Sunrise'},\n {value: 'Nutty for Almonds', text: 'Nutty for Almonds'},\n {value: 'Toasted Coconut', text: 'Toasted Coconut'},\n {value: 'Lapsong Souchong', text: 'Lapsong Souchong'},\n {value: 'Caribbean Punch', text: 'Caribbean Punch'},\n {value: 'Tazo Chai', text: 'Tazo Chai'},\n {value: 'Hao Ya A', text: 'Hao Ya A'},\n {value: 'Random Steepings', text: 'Random Steepings'},\n {value: 'On the Waterfront', text: 'On the Waterfront'},\n {value: 'Pom Power', text: 'Pom Power'},\n {value: 'Lao Shu Bing Cha', text: 'Lao Shu Bing Cha'},\n {value: '2008 Xiaguan FT Exquisite Elegance',text: '2008 Xiaguan FT Exquisite Elegance'},\n {value: 'Sweet Lily', text: 'Sweet Lily'},\n {value: 'Place Saint Marc', text: 'Place Saint Marc'},\n {value: 'China Sweet Gui Hua', text: 'China Sweet Gui Hua'},\n {value: 'Golden Pu erh', text: 'Golden Pu erh'},\n {value: 'Cinnamon Samba', text: 'Cinnamon Samba'},\n {value: 'Oolong Earl Grey', text: 'Oolong Earl Grey'},\n {value: 'Xingyang Golden Buds Black (Dian Hong)',\n text: 'Xingyang Golden Buds Black (Dian Hong)'},\n {value: 'Earl Grey', text: 'Earl Grey'},\n {value: 'Senna Herbal Tea', text: 'Senna Herbal Tea'},\n {value: 'Strawberry Rhubarb Parfait', text: 'Strawberry Rhubarb Parfait'},\n {value: 'Morocco', text: 'Morocco'},\n {value: 'Autumn Harvest Rooibos', text: 'Autumn Harvest Rooibos'},\n {value: 'Phoenix Oolong Xing Ren Xiang',\n text: 'Phoenix Oolong Xing Ren Xiang'},\n {value: 'Yong De Mao Cha', text: 'Yong De Mao Cha'},\n {value: 'Imuno Rooibos', text: 'Imuno Rooibos'},\n {value: 'Orange Spice', text: 'Orange Spice'},\n {value: 'Caramel-Toffee', text: 'Caramel-Toffee'},\n {value: 'Bohea Imperial Organic (ZK72)',\n text: 'Bohea Imperial Organic (ZK72)'},\n {value: 'Fine Formosa Oolong', text: 'Fine Formosa Oolong'},\n {value: 'Vanilla Mint', text: 'Vanilla Mint'},\n {value: 'Ontario Ice Wine', text: 'Ontario Ice Wine'},\n {value: 'Black Tea flavoured with Orange &amp; Cinnamon',\n text: 'Black Tea flavoured with Orange &amp; Cinnamon'},\n {value: 'The Emperors Bride', text: 'The Emperors Bride'},\n {value: 'Cranberry Black', text: 'Cranberry Black'},\n {value: 'Vanilla Almond', text: 'Vanilla Almond'},\n {value: 'Organic Gui Fei', text: 'Organic Gui Fei'},\n {value: 'Mao Feng White', text: 'Mao Feng White'},\n {value: 'Leo (The Zodiac Series)', text: 'Leo (The Zodiac Series)'},\n {value: 'Decaffeinated Earl Grey', text: 'Decaffeinated Earl Grey'},\n {value: 'Orange', text: 'Orange'},\n {value: 'Pomegranate Green', text: 'Pomegranate Green'},\n {value: 'Tulsi', text: 'Tulsi'},\n {value: 'Zesty Ginger Fair Trade Organic Rooibos',\n text: 'Zesty Ginger Fair Trade Organic Rooibos'},\n {value: 'Decaffeinated Black Tea', text: 'Decaffeinated Black Tea'},\n {value: 'Pi Lo Chun', text: 'Pi Lo Chun'},\n {value: 'Dream On (organic)', text: 'Dream On (organic)'},\n {value: 'Midsummer Fling', text: 'Midsummer Fling'},\n {value: 'Wellness', text: 'Wellness'},\n {value: 'Plantation Peach', text: 'Plantation Peach'},\n {value: 'Passionfruit Oolong', text: 'Passionfruit Oolong'},\n {value: 'Ripened Aged Pu-erh Mini Tuocha',\n text: 'Ripened Aged Pu-erh Mini Tuocha'},\n {value: 'Orange Jaipur', text: 'Orange Jaipur'},\n {value: 'Golden Monkey Tea-Organic', text: 'Golden Monkey Tea-Organic'},\n {value: 'Jasmine Dragon Phoenix Pearl',\n text: 'Jasmine Dragon Phoenix Pearl'},\n {value: '2009 Menghai Dayi Da Yi Jia Ji Tuo',\n text: '2009 Menghai Dayi Da Yi Jia Ji Tuo'},\n {value: 'English Rose', text: 'English Rose'},\n {value: 'Starlight Rose', text: 'Starlight Rose'},\n {value: 'Organic Sencha Warashina Supreme',\n text: 'Organic Sencha Warashina Supreme'},\n {value: 'Pomegranate Rose', text: 'Pomegranate Rose'},\n {value: 'Chinese Jasmine', text: 'Chinese Jasmine'},\n {value: 'Coconut Oolong', text: 'Coconut Oolong'},\n {value: 'Raspberry Nectar', text: 'Raspberry Nectar'},\n {value: 'Rotbuschtee Vanille', text: 'Rotbuschtee Vanille'},\n {value: 'Stanleys Blend', text: 'Stanleys Blend'},\n {value: 'Scottish Morn', text: 'Scottish Morn'},\n {value: 'Jasmine Dragon Pearls', text: 'Jasmine Dragon Pearls'},\n {value: 'Pai Mu Tan', text: 'Pai Mu Tan'},\n {value: 'Singbulli 1F10', text: 'Singbulli 1F10'},\n {value: 'Chai Green Tea', text: 'Chai Green Tea'},\n {value: 'Yunnan Jig', text: 'Yunnan Jig'},\n {value: 'Organic Chamomile with Lavender',\n text: 'Organic Chamomile with Lavender'},\n {value: 'Dragonwell (Lung Ching)', text: 'Dragonwell (Lung Ching)'},\n {value: 'Barley Tea', text: 'Barley Tea'},\n {value: 'Organic Guranse', text: 'Organic Guranse'},\n {value: 'Capital of Heaven Keemun Black Tea',\n text: 'Capital of Heaven Keemun Black Tea'},\n {value: 'Lemon Ginger Tea', text: 'Lemon Ginger Tea'},\n {value: 'Sen-Cha Fukamushi Select (Blenders Series)',\n text: 'Sen-Cha Fukamushi Select (Blenders Series)'},\n {value: 'Dragonheart', text: 'Dragonheart'},\n {value: 'Strawberry &amp; Vanilla', text: 'Strawberry &amp; Vanilla'},\n {value: 'Starbucks Black Iced Tea', text: 'Starbucks Black Iced Tea'},\n {value: 'Pear Caramel', text: 'Pear Caramel'},\n {value: 'Peach Blossom', text: 'Peach Blossom'},\n {value: 'Okayti Estate Darjeeling Tresor Black Tea',\n text: 'Okayti Estate Darjeeling Tresor Black Tea'},\n {value: 'Whole Leaf Organic Oolong Tea',\n text: 'Whole Leaf Organic Oolong Tea'},\n {value: 'Bangkok Lemongrass', text: 'Bangkok Lemongrass'},\n {value: 'Clarity: Blueberry Ginseng with Gingko',\n text: 'Clarity: Blueberry Ginseng with Gingko'},\n {value: 'Genmaicha Extra Green', text: 'Genmaicha Extra Green'},\n {value: 'Rhubarb Green', text: 'Rhubarb Green'},\n {value: 'Wu Ling (武陵) Oolong Tea', text: 'Wu Ling (武陵) Oolong Tea'},\n {value: 'Ginger Oolong (Water Sprite)',\n text: 'Ginger Oolong (Water Sprite)'},\n {value: 'Island Coconut', text: 'Island Coconut'},\n {value: 'Tropical Fruit Cool Brew Iced Tea',\n text: 'Tropical Fruit Cool Brew Iced Tea'},\n {value: 'Orange Passion Fruit Tea', text: 'Orange Passion Fruit Tea'},\n {value: 'Green Twirl', text: 'Green Twirl'},\n {value: 'Figue Fraîche', text: 'Figue Fraîche'},\n {value: 'Rooibos Chai', text: 'Rooibos Chai'},\n {value: 'Keemun Imperial', text: 'Keemun Imperial'},\n {value: 'Maharani', text: 'Maharani'},\n {value: 'Strawberry', text: 'Strawberry'},\n {value: 'Wuyi Amber', text: 'Wuyi Amber'},\n {value: 'Imperial Label', text: 'Imperial Label'},\n {value: 'Organic Sencha', text: 'Organic Sencha'},\n {value: 'Joint Comfort', text: 'Joint Comfort'},\n {value: 'scottish blend', text: 'scottish blend'},\n {value: 'Berry Good (organic)', text: 'Berry Good (organic)'},\n {value: 'Strawberry Paraiso', text: 'Strawberry Paraiso'},\n {value: 'China White Tea', text: 'China White Tea'},\n {value: 'Organic Gaba Tea', text: 'Organic Gaba Tea'},\n {value: 'Chá Mate Tostado', text: 'Chá Mate Tostado'},\n {value: 'Suns Up', text: 'Suns Up'},\n {value: 'Da Hong Pao 1997', text: 'Da Hong Pao 1997'},\n {value: 'Gunpowder Green (loose leaf)',\n text: 'Gunpowder Green (loose leaf)'},\n {value: 'Chrysanthemum Pu-erh Tuocha',\n text: 'Chrysanthemum Pu-erh Tuocha'},\n {value: 'Rainforest Mint Guayusa', text: 'Rainforest Mint Guayusa'},\n {value: '2011 Darjeeling First Flush Jungpana Black Tea',\n text: '2011 Darjeeling First Flush Jungpana Black Tea'},\n {value: 'Chocolate Chip Truffle', text: 'Chocolate Chip Truffle'},\n {value: '/h1', text: '/h1'},\n {value: 'Banaspaty Estate FTGFOP1 Organic (TA19)',\n text: 'Banaspaty Estate FTGFOP1 Organic (TA19)'},\n {value: 'Vietnam Black OP1', text: 'Vietnam Black OP1'},\n {value: 'Echinacea Brain Brew', text: 'Echinacea Brain Brew'},\n {value: 'Mango', text: 'Mango'},\n {value: 'Vanilla Nut Java Mate', text: 'Vanilla Nut Java Mate'},\n {value: 'Nestea', text: 'Nestea'},\n {value: 'Bois Cheri Black Tea Vanilla Flavoured',\n text: 'Bois Cheri Black Tea Vanilla Flavoured'},\n {value: 'Gypsy Rose', text: 'Gypsy Rose'},\n {value: 'Tulsi Lemon Ginger', text: 'Tulsi Lemon Ginger'},\n {value: 'Bourbon Street Vanilla', text: 'Bourbon Street Vanilla'},\n {value: 'Wild Encounter ', text: 'Wild Encounter '},\n {value: 'Big Red Robe', text: 'Big Red Robe'},\n {value: 'Citrus Punch Organic Oolong',\n text: 'Citrus Punch Organic Oolong'},\n {value: 'Russian Caravan', text: 'Russian Caravan'},\n {value: 'White Peony', text: 'White Peony'},\n {value: 'Genmaicha Green Tea Bags', text: 'Genmaicha Green Tea Bags'},\n {value: 'Sweet Shanghaï', text: 'Sweet Shanghaï'},\n {value: '2006 Xiaguan Tibetan Flame Brick (06年下关宝焰砖)',\n text: '2006 Xiaguan Tibetan Flame Brick (06年下关宝焰砖)'},\n {value: 'Xin Yang Mao Jian', text: 'Xin Yang Mao Jian'},\n {value: 'tie luo han', text: 'tie luo han'},\n {value: 'Bai Mu Dan', text: 'Bai Mu Dan'},\n {value: 'Rolling Clouds', text: 'Rolling Clouds'},\n {value: 'Nepal FTGFOP 1 Maloom First Flush',\n text: 'Nepal FTGFOP 1 Maloom First Flush'},\n {value: 'Irish Breakfast Blend', text: 'Irish Breakfast Blend'},\n {value: 'Savannah', text: 'Savannah'},\n {value: 'Tie Guan Yin (Mild Oxidation)',\n text: 'Tie Guan Yin (Mild Oxidation)'},\n {value: 'French Vanilla', text: 'French Vanilla'},\n {value: 'Mountain Grey', text: 'Mountain Grey'},\n {value: 'Tieguanyin Traditional-Style Traditionally-Grown',\n text: 'Tieguanyin Traditional-Style Traditionally-Grown'},\n {value: 'Chocolate Puerh', text: 'Chocolate Puerh'},\n {value: 'Teas Tea Golden Oolong', text: 'Teas Tea Golden Oolong'},\n {value: 'Laoshan Black', text: 'Laoshan Black'},\n {value: 'Gunpowder Green Tea', text: 'Gunpowder Green Tea'},\n {value: 'Organic Berry Berry Scarlet',\n text: 'Organic Berry Berry Scarlet'},\n {value: 'Taiwan Ruby Black (Hong Yue)',\n text: 'Taiwan Ruby Black (Hong Yue)'},\n {value: 'English Breakfast', text: 'English Breakfast'},\n {value: 'Mayan Chocolate Truffle', text: 'Mayan Chocolate Truffle'},\n {value: 'Kurihara Heritage Gyokuro', text: 'Kurihara Heritage Gyokuro'},\n {value: 'Golden Silk', text: 'Golden Silk'},\n {value: 'Tarry Souchong', text: 'Tarry Souchong'},\n {value: 'Black Tea', text: 'Black Tea'},\n {value: 'Caramel Tea (Thé Caramel)', text: 'Caramel Tea (Thé Caramel)'},\n {value: 'Aniseed', text: 'Aniseed'},\n {value: 'Sen-Cha (Traditional Series)',\n text: 'Sen-Cha (Traditional Series)'},\n {value: 'Slim Tea', text: 'Slim Tea'},\n {value: 'Organic Tie Guan Yin “Iron Goddess” Oolong Tea',\n text: 'Organic Tie Guan Yin “Iron Goddess” Oolong Tea'},\n {value: 'Relaxation Blend', text: 'Relaxation Blend'},\n {value: 'Queen of Tarts (organic)', text: 'Queen of Tarts (organic)'},\n {value: 'Yunnan Golden Chai', text: 'Yunnan Golden Chai'},\n {value: 'Scallop spitting pearl flowers?',\n text: 'Scallop spitting pearl flowers?'},\n {value: 'Gaucho Fuerte', text: 'Gaucho Fuerte'},\n {value: 'Chamomile Lemon', text: 'Chamomile Lemon'},\n {value: 'Organic Pu-erh', text: 'Organic Pu-erh'},\n {value: 'Tie Kwan Yin Oolong', text: 'Tie Kwan Yin Oolong'},\n {value: 'bamboo fragrance puerh', text: 'bamboo fragrance puerh'},\n {value: 'Sencha House', text: 'Sencha House'},\n {value: '2008 Menghai Peacock of Bulang Raw',\n text: '2008 Menghai Peacock of Bulang Raw'},\n {value: 'Si Ji Chun', text: 'Si Ji Chun'},\n {value: 'Root Beer Float', text: 'Root Beer Float'},\n {value: 'Foxy Roxy’s Banana Walnut Treat',\n text: 'Foxy Roxy’s Banana Walnut Treat'},\n {value: 'Chrysanthemum Pu Erh Mini Tuocha',\n text: 'Chrysanthemum Pu Erh Mini Tuocha'},\n {value: 'Teh-o', text: 'Teh-o'},\n {value: 'White Ambrosia Dream', text: 'White Ambrosia Dream'},\n {value: 'Kuradashi Gyokuro Pinnacle', text: 'Kuradashi Gyokuro Pinnacle'},\n {value: 'White Peony (Bai Mu Dan) Organic',\n text: 'White Peony (Bai Mu Dan) Organic'},\n {value: 'Almond Oolong', text: 'Almond Oolong'},\n {value: 'Ceylon Orange Pekoe Tea', text: 'Ceylon Orange Pekoe Tea'},\n {value: 'Superfruit Red Goji &amp; Raspberry',\n text: 'Superfruit Red Goji &amp; Raspberry'},\n {value: 'Ulitmate Chocolate Rooibos', text: 'Ulitmate Chocolate Rooibos'},\n {value: 'Dragon Well (Long Jing) Competition Grade',\n text: 'Dragon Well (Long Jing) Competition Grade'},\n {value: 'Organic Wu Yi Rare Orchid', text: 'Organic Wu Yi Rare Orchid'},\n {value: 'Da Hong Pao (big red robe)', text: 'Da Hong Pao (big red robe)'},\n {value: 'Pomegranate White Tea', text: 'Pomegranate White Tea'},\n {value: 'White Tea', text: 'White Tea'},\n {value: 'Thé du Loup', text: 'Thé du Loup'},\n {value: 'Oolong Baozhong', text: 'Oolong Baozhong'},\n {value: 'Finnigans Wakeup', text: 'Finnigans Wakeup'},\n {value: 'English Afternoon Tea', text: 'English Afternoon Tea'},\n {value: 'Assam Mangalam', text: 'Assam Mangalam'},\n {value: 'French Vanilla Matcha', text: 'French Vanilla Matcha'},\n {value: 'Cocoa Amore', text: 'Cocoa Amore'},\n {value: 'Think 02', text: 'Think 02'},\n {value: 'Pomi-berry', text: 'Pomi-berry'},\n {value: 'Yin Long', text: 'Yin Long'},\n {value: 'Forest Berries', text: 'Forest Berries'},\n {value: 'Tea Grapefruit made with Taiwan Wuyi',\n text: 'Tea Grapefruit made with Taiwan Wuyi'},\n {value: 'India Tea Mango', text: 'India Tea Mango'},\n {value: 'Caramel Rooibos', text: 'Caramel Rooibos'},\n {value: 'American Spearmint', text: 'American Spearmint'},\n {value: 'Sencha Zuiko', text: 'Sencha Zuiko'},\n {value: 'Kyoto Cosmo', text: 'Kyoto Cosmo'},\n {value: 'Da Yu Ling Winter 2011', text: 'Da Yu Ling Winter 2011'},\n {value: '2008 Pu-erh Zhuan Cha-Tea Brick Lao Cang-08LCZ',\n text: '2008 Pu-erh Zhuan Cha-Tea Brick Lao Cang-08LCZ'},\n {value: 'Gokubo Fukamushi Kukicha (First Flush) Japanese Green Tea',\n text: 'Gokubo Fukamushi Kukicha (First Flush)'},\n {value: 'Mayan Cocoa', text: 'Mayan Cocoa'},\n {value: 'Sweet Lemongrass', text: 'Sweet Lemongrass'},\n {value: '2007 Menghai Dayi Yun Xiang Ripe',\n text: '2007 Menghai Dayi Yun Xiang Ripe'},\n {value: 'Jasmine Earl Grey', text: 'Jasmine Earl Grey'},\n {value: 'Artisan Earl Grey', text: 'Artisan Earl Grey'},\n {value: 'Nonpareil Te Gong Huang Shan Mao Feng Green Tea',\n text: 'Nonpareil Te Gong Huang Shan Mao Feng Green Tea'},\n {value: 'Raspberry Nectar (organic)', text: 'Raspberry Nectar (organic)'},\n {value: 'Taurus (The Zodiac Series)', text: 'Taurus (The Zodiac Series)'},\n {value: 'Organic Sencha Whole Leaf Teabag',\n text: 'Organic Sencha Whole Leaf Teabag'},\n {value: 'Bohemian Raspberry', text: 'Bohemian Raspberry'},\n {value: 'Plum Oolong', text: 'Plum Oolong'},\n {value: 'San Mateo Yerba Mate', text: 'San Mateo Yerba Mate'},\n {value: 'Inspire - Summerberry', text: 'Inspire - Summerberry'},\n {value: 'White Jasmine Rose', text: 'White Jasmine Rose'},\n {value: 'Tai Ping Hou Kui', text: 'Tai Ping Hou Kui'},\n {value: 'Jasmine Pearls', text: 'Jasmine Pearls'},\n {value: 'Darjeeling Mountian Tea', text: 'Darjeeling Mountian Tea'},\n {value: 'The Killer’s Vanilla', text: 'The Killer’s Vanilla'},\n {value: 'Hairy Crab (Mao Xie)', text: 'Hairy Crab (Mao Xie)'},\n {value: 'Zhong Huo Oolong', text: 'Zhong Huo Oolong'},\n {value: 'Puttabong FTGFOP1 First Flush',\n text: 'Puttabong FTGFOP1 First Flush'},\n {value: 'Empress Grey', text: 'Empress Grey'},\n {value: 'White Melon', text: 'White Melon'},\n {value: 'Duvet de Dragon', text: 'Duvet de Dragon'},\n {value: 'Peppermint', text: 'Peppermint'},\n {value: 'Fine Ti Kuan Yin', text: 'Fine Ti Kuan Yin'},\n {value: 'Castleton Estate Darjeeling',\n text: 'Castleton Estate Darjeeling'},\n {value: 'Milk Ginseng Oolong', text: 'Milk Ginseng Oolong'},\n {value: 'Earl of Grey', text: 'Earl of Grey'},\n {value: 'Wild Blossoms &amp; Berries',\n text: 'Wild Blossoms &amp; Berries'},\n {value: 'Jasmine White Monkey', text: 'Jasmine White Monkey'},\n {value: 'Spring Bud Green Tea (春芽綠茶)',\n text: 'Spring Bud Green Tea (春芽綠茶)'},\n {value: 'Snow Dragon', text: 'Snow Dragon'},\n {value: 'Hunan Aged Green Cake [Out of Stock]',\n text: 'Hunan Aged Green Cake [Out of Stock]'},\n {value: 'Champagne &amp; Rose Cream', text: 'Champagne &amp; Rose Cream'},\n {value: 'Vihreä Sitruuna-Kamomilla - Green Lemon-Camomille',\n text: 'Vihreä Sitruuna-Kamomilla - Green Lemon-Camomille'},\n {value: 'Jasmine Tea', text: 'Jasmine Tea'},\n {value: 'Fruit Sangria', text: 'Fruit Sangria'},\n {value: 'The Au Jasmine', text: 'The Au Jasmine'},\n {value: 'Wild Strawberry', text: 'Wild Strawberry'},\n {value: 'Lúcia-Lima', text: 'Lúcia-Lima'},\n {value: 'Green Tea with Jasmine Flowers',\n text: 'Green Tea with Jasmine Flowers'},\n {value: 'Sleepy Time Tea', text: 'Sleepy Time Tea'},\n {value: 'Tropical Explosion White Tea',\n text: 'Tropical Explosion White Tea'},\n {value: 'China Keemun Imperial (No. 502)',\n text: 'China Keemun Imperial (No. 502)'},\n {value: 'Apfel', text: 'Apfel'},\n {value: 'Ruby Red Chai Spiced Rooibos',\n text: 'Ruby Red Chai Spiced Rooibos'},\n {value: 'Irish Breakfast', text: 'Irish Breakfast'},\n {value: 'Organic Chun Mee', text: 'Organic Chun Mee'},\n {value: '2009 Menghai Dayi Da Yi Gong Tuo',\n text: '2009 Menghai Dayi Da Yi Gong Tuo'},\n {value: 'Chai White', text: 'Chai White'},\n {value: 'Lemon Green', text: 'Lemon Green'},\n {value: 'Organic Peach White', text: 'Organic Peach White'},\n {value: 'Welsh Morning', text: 'Welsh Morning'},\n {value: 'Four Red Fruits', text: 'Four Red Fruits'},\n {value: 'Deep Sleep', text: 'Deep Sleep'},\n {value: 'Brazillionaire', text: 'Brazillionaire'},\n {value: 'Ginger Peach', text: 'Ginger Peach'},\n {value: 'Aged Beauty 1979', text: 'Aged Beauty 1979'},\n {value: 'An Xi Mao Xie Hairy Crab', text: 'An Xi Mao Xie Hairy Crab'},\n {value: 'Tangerine Orange (Fair Trade Certified)',\n text: 'Tangerine Orange (Fair Trade Certified)'},\n {value: 'Earl Grey White', text: 'Earl Grey White'},\n {value: 'PG Tips Decaf', text: 'PG Tips Decaf'},\n {value: 'The Road To Hana', text: 'The Road To Hana'},\n {value: 'Hazelnut Truffle', text: 'Hazelnut Truffle'},\n {value: 'Organic Japanese Sencha', text: 'Organic Japanese Sencha'},\n {value: 'Da Du Gang Ancient Tree Large Disk 2000',\n text: 'Da Du Gang Ancient Tree Large Disk 2000'},\n {value: 'Earl Grey with Bergamot', text: 'Earl Grey with Bergamot'},\n {value: 'Kagoshima Sencha Yutaka Midori Kaoru Supreme LE',\n text: 'Kagoshima Sencha Yutaka Midori Kaoru Supreme LE'},\n {value: 'Houjicha Gold (Roasted Bancha)',\n text: 'Houjicha Gold (Roasted Bancha)'},\n {value: 'Boston Tea Party - English Breakfast',\n text: 'Boston Tea Party - English Breakfast'},\n {value: 'Green Tea Jasmine', text: 'Green Tea Jasmine'},\n {value: 'Ginger-Peach Black Tea', text: 'Ginger-Peach Black Tea'},\n {value: 'Tie Guan Yin “Iron Goddess” Oolong Tea',\n text: 'Tie Guan Yin “Iron Goddess” Oolong Tea'},\n {value: 'Rooibos Chocolate Rum', text: 'Rooibos Chocolate Rum'},\n {value: 'Sessa B Estate STGFOP1(S) (TA25)',\n text: 'Sessa B Estate STGFOP1(S) (TA25)'},\n {value: 'Mocha Nut Mate', text: 'Mocha Nut Mate'},\n {value: 'Organic Stevia', text: 'Organic Stevia'},\n {value: 'Tindharia Estate 1st Fl Darjeeling Green Oolong (EX-10)',\n text: 'Tindharia Estate 1st Fl Darjeeling Green Oolong (EX-10)'},\n {value: 'Golden Gong Ting - 2005', text: 'Golden Gong Ting - 2005'},\n {value: 'Chá Leão Branco', text: 'Chá Leão Branco'},\n {value: 'Aged Oolong Tea', text: 'Aged Oolong Tea'},\n {value: 'Pina Colada', text: 'Pina Colada'},\n {value: 'Guangzhou Milk Oolong', text: 'Guangzhou Milk Oolong'},\n {value: 'Beatles Blend', text: 'Beatles Blend'},\n {value: 'Turkish Apple Tea', text: 'Turkish Apple Tea'},\n {value: 'Jasmin Mandarin', text: 'Jasmin Mandarin'},\n {value: 'Keemun Extra Superior', text: 'Keemun Extra Superior'},\n {value: 'Assam Pure Organic', text: 'Assam Pure Organic'},\n {value: 'Bossa Nova (No. 993)', text: 'Bossa Nova (No. 993)'},\n {value: 'East Frisian TGFOP (TB52)', text: 'East Frisian TGFOP (TB52)'},\n {value: 'Roasted Chocolate Pineapple Mate',\n text: 'Roasted Chocolate Pineapple Mate'},\n {value: 'Ceylon FOP (organic)', text: 'Ceylon FOP (organic)'},\n {value: 'Jasmine Green Tea', text: 'Jasmine Green Tea'},\n {value: 'Grapefruit Lemon', text: 'Grapefruit Lemon'},\n {value: '2011 Spring Mt Wudong Imperial Da Wu Ye(big black leaf) Phoenic Dancong Oolong Tea',\n text: '2011 Spring Mt Wudong Imperial Da Wu Ye Oolong'},\n {value: 'Tea Apple', text: 'Tea Apple'},\n {value: 'Ali-Shan High Mountain Top Grade',\n text: 'Ali-Shan High Mountain Top Grade'},\n {value: 'Fu Ding Bai Mu Dan', text: 'Fu Ding Bai Mu Dan'},\n {value: 'Raspberry Rendezvous', text: 'Raspberry Rendezvous'},\n {value: 'Earl Gold', text: 'Earl Gold'},\n {value: 'Yamacha', text: 'Yamacha'},\n {value: 'Jasmine 12', text: 'Jasmine 12'},\n {value: 'Trá Oolong Cao Cấp', text: 'Trá Oolong Cao Cấp'},\n {value: 'Genmaicha- Metro Tea', text: 'Genmaicha- Metro Tea'},\n {value: 'Silverpot Legendary Estates Assam Second Flush',\n text: 'Silverpot Legendary Estates Assam Second Flush'},\n {value: 'Kilauea', text: 'Kilauea'},\n {value: 'Organic Lavender Earl Grey', text: 'Organic Lavender Earl Grey'},\n {value: 'Formosa Oolong - Top Fancy -',\n text: 'Formosa Oolong - Top Fancy -'},\n {value: 'Amaretti Cookie', text: 'Amaretti Cookie'},\n {value: 'Dragon Well - West Lake Standard',\n text: 'Dragon Well - West Lake Standard'},\n {value: 'Earl Grey Tea with Pomegranate',\n text: 'Earl Grey Tea with Pomegranate'},\n {value: 'Darjeeling Tea', text: 'Darjeeling Tea'},\n {value: 'Ambrosia', text: 'Ambrosia'},\n {value: 'Earl Grey Imperial', text: 'Earl Grey Imperial'},\n {value: 'Ali Shan 1991', text: 'Ali Shan 1991'},\n {value: 'Bubbies Baklava', text: 'Bubbies Baklava'},\n {value: 'Boston Blend', text: 'Boston Blend'},\n {value: 'Wu Yi Fujian Oolong', text: 'Wu Yi Fujian Oolong'},\n {value: 'Cinnamon Apple Chamomile', text: 'Cinnamon Apple Chamomile'},\n {value: 'Cacao Chai', text: 'Cacao Chai'},\n {value: 'English Breakfast Decaf', text: 'English Breakfast Decaf'},\n {value: 'Sencha Uji', text: 'Sencha Uji'},\n {value: 'Tropical Green Tea Pineapple',\n text: 'Tropical Green Tea Pineapple'},\n {value: 'Mi Lan Xiang (Honey Orchid)',\n text: 'Mi Lan Xiang (Honey Orchid)'},\n {value: 'Decaf Earl Grey', text: 'Decaf Earl Grey'},\n {value: 'Apple Green Tea', text: 'Apple Green Tea'},\n {value: 'Hazelnut Chai', text: 'Hazelnut Chai'},\n {value: 'Keemun Hao Ya A', text: 'Keemun Hao Ya A'},\n {value: 'green tea with peach', text: 'green tea with peach'},\n {value: 'Anji Bai Cha Superior Summit',\n text: 'Anji Bai Cha Superior Summit'},\n {value: 'Black Lava Rush', text: 'Black Lava Rush'},\n {value: 'Equator Breakfast', text: 'Equator Breakfast'},\n {value: 'Organic Dark Roast Yerba Mate',\n text: 'Organic Dark Roast Yerba Mate'},\n {value: 'Rize Cay', text: 'Rize Cay'},\n {value: 'White Tea Elderflower &amp; Apricot',\n text: 'White Tea Elderflower &amp; Apricot'},\n {value: 'Nantou Four Seasons', text: 'Nantou Four Seasons'},\n {value: 'Irish Breakfast Kerfuffle', text: 'Irish Breakfast Kerfuffle'},\n {value: 'China Sencha', text: 'China Sencha'},\n {value: 'African Autumn', text: 'African Autumn'},\n {value: 'Berry Black™ - Raspberry Darjeeling Black Tea',\n text: 'Berry Black™ - Raspberry Darjeeling Black Tea'},\n {value: 'Organic Iced Black Tea', text: 'Organic Iced Black Tea'},\n {value: 'Maple Tea', text: 'Maple Tea'},\n {value: 'Dong Ding', text: 'Dong Ding'},\n {value: 'Tulsi Infusion', text: 'Tulsi Infusion'},\n {value: 'Earl Grey White Tip', text: 'Earl Grey White Tip'},\n {value: 'Coffee Puerh', text: 'Coffee Puerh'},\n {value: 'Relief', text: 'Relief'},\n {value: 'Magic Yunnan', text: 'Magic Yunnan'},\n {value: 'Mount Wellington', text: 'Mount Wellington'},\n {value: 'Fireberry', text: 'Fireberry'},\n {value: 'Ingwer Limone', text: 'Ingwer Limone'},\n {value: 'Dancong Aria', text: 'Dancong Aria'},\n {value: 'Apricot Essence', text: 'Apricot Essence'},\n {value: 'Keemun Organic Fair Trade Black Tea',\n text: 'Keemun Organic Fair Trade Black Tea'},\n {value: 'GABA Tea', text: 'GABA Tea'},\n {value: 'Anthony Adam', text: 'Anthony Adam'},\n {value: '2010 Bangwai', text: '2010 Bangwai'},\n {value: 'Mint Chocolate Delight', text: 'Mint Chocolate Delight'},\n {value: '100% White Tea/Emperors White Tea',\n text: '100% White Tea/Emperors White Tea'},\n {value: 'Egg Noggin', text: 'Egg Noggin'},\n {value: 'Raspberry Cream Pie', text: 'Raspberry Cream Pie'},\n {value: 'Ginger Lemon Green Tea', text: 'Ginger Lemon Green Tea'},\n {value: 'Wintergreen Woods', text: 'Wintergreen Woods'},\n {value: 'Maghreb Mint', text: 'Maghreb Mint'},\n {value: 'Blueberry Jam (organic)', text: 'Blueberry Jam (organic)'},\n {value: 'Yun Ding Ti Kuan Yin', text: 'Yun Ding Ti Kuan Yin'},\n {value: 'Masala Chai', text: 'Masala Chai'},\n {value: 'Green Tea with Mandarin Orange',\n text: 'Green Tea with Mandarin Orange'},\n {value: 'Phoenix in the Forest', text: 'Phoenix in the Forest'},\n {value: 'Hibiscus', text: 'Hibiscus'},\n {value: 'Coconut Pouchong', text: 'Coconut Pouchong'},\n {value: 'Honey Lemon', text: 'Honey Lemon'},\n {value: '99% Oxidized Purple Oolong', text: '99% Oxidized Purple Oolong'},\n {value: 'Strawberry Orange Scone', text: 'Strawberry Orange Scone'},\n {value: 'Black Currant Cassis', text: 'Black Currant Cassis'},\n {value: 'Chocolate Cake Honeybush', text: 'Chocolate Cake Honeybush'},\n {value: 'Big Ben G.F.O.P.', text: 'Big Ben G.F.O.P.'},\n {value: 'Nilgiri', text: 'Nilgiri'},\n {value: 'Menghai 2009 Zi Yun Ripe Pu-erh tea',\n text: 'Menghai 2009 Zi Yun Ripe Pu-erh tea'},\n {value: 'Pure Black', text: 'Pure Black'},\n {value: 'Organic Pan-Fired Pagoda [discontinued]',\n text: 'Organic Pan-Fired Pagoda [discontinued]'},\n {value: '1989 Suncha Blend', text: '1989 Suncha Blend'},\n {value: 'Ultimate Citrus Spice Flavored Black',\n text: 'Ultimate Citrus Spice Flavored Black'},\n {value: 'Regular White', text: 'Regular White'},\n {value: 'Eros', text: 'Eros'},\n {value: 'Spring Orchid * Organic Phoenix Dancong Oolong',\n text: 'Spring Orchid * Organic Phoenix Dancong Oolong'},\n {value: 'Dragonwell', text: 'Dragonwell'},\n {value: 'Rooibos &amp; Cinnamon', text: 'Rooibos &amp; Cinnamon'},\n {value: 'Green Mountain Green Water', text: 'Green Mountain Green Water'},\n {value: 'Oprah Chai Tea', text: 'Oprah Chai Tea'},\n {value: 'Mini Green Pu-Erh Tuocha', text: 'Mini Green Pu-Erh Tuocha'},\n {value: 'Honeybush', text: 'Honeybush'},\n {value: 'Green Tea Lemon', text: 'Green Tea Lemon'},\n {value: 'Choco - Aztec Spice', text: 'Choco - Aztec Spice'},\n {value: 'Pistachio Apple Pie', text: 'Pistachio Apple Pie'},\n {value: 'Kashmiri Chai', text: 'Kashmiri Chai'},\n {value: 'Instant Gingerbread Chai', text: 'Instant Gingerbread Chai'},\n {value: 'Afternoon Darjeeling', text: 'Afternoon Darjeeling'},\n {value: 'Irresistible', text: 'Irresistible'},\n{value: 'Peppermint Amour (organic)', text: 'Peppermint Amour (organic)'},\n {value: 'Chocolate Raspberry Razzle Dazzle',\n text: 'Chocolate Raspberry Razzle Dazzle'},\n {value: 'Alice in Wonderland', text: 'Alice in Wonderland'},\n {value: 'Formosa Fancy Superior Oolong Taifu (630)',\n text: 'Formosa Fancy Superior Oolong Taifu (630)'},\n {value: 'Read My Lips', text: 'Read My Lips'},\n {value: 'Christmas Bakery', text: 'Christmas Bakery'},\n {value: 'Bao Zhong', text: 'Bao Zhong'},\n {value: 'White Peony White Tea and Rosebuds',\n text: 'White Peony White Tea and Rosebuds'},\n {value: 'Lucid Dream Tea', text: 'Lucid Dream Tea'},\n {value: 'Key Lime Cheesecake Flavored Black Tea',\n text: 'Key Lime Cheesecake Flavored Black Tea'},\n {value: 'Citron', text: 'Citron'},\n {value: 'Yerba Mate', text: 'Yerba Mate'},\n {value: 'Countess of Seville (organic)',\n text: 'Countess of Seville (organic)'},\n {value: 'Keemun I', text: 'Keemun I'},\n {value: '2012 Darjeeling First Flush Himalayan Ranee',\n text: '2012 Darjeeling First Flush Himalayan Ranee'},\n {value: '2009 Yi Dian Hong', text: '2009 Yi Dian Hong'},\n {value: 'Liu An Gua Pian Green Tea', text: 'Liu An Gua Pian Green Tea'},\n {value: 'Green', text: 'Green'},\n {value: 'Canadian Ice Wine Tea', text: 'Canadian Ice Wine Tea'},\n {value: 'Assam Mangalam FTGFOP1 (CL/SP) (No. 264)',\n text: 'Assam Mangalam FTGFOP1 (CL/SP) (No. 264)'},\n {value: 'Ten Fu High Mountain Oolong',\n text: 'Ten Fu High Mountain Oolong'},\n {value: 'Formosa Dung Ti Oolong', text: 'Formosa Dung Ti Oolong'},\n {value: 'Yunnan Golden Buds', text: 'Yunnan Golden Buds'},\n {value: 'Ginsing Vitality', text: 'Ginsing Vitality'},\n {value: 'Pure Iced Tea', text: 'Pure Iced Tea'},\n {value: 'Anti Acid - HeartBurn Tea', text: 'Anti Acid - HeartBurn Tea'},\n {value: 'Carolina Honey', text: 'Carolina Honey'},\n {value: 'Formosa Oolong Fine Grade (TT15)',\n text: 'Formosa Oolong Fine Grade (TT15)'},\n {value: 'Cream Earl Grey', text: 'Cream Earl Grey'},\n {value: 'Raspberry Rooibos', text: 'Raspberry Rooibos'},\n {value: 'The King by Kristina Moy', text: 'The King by Kristina Moy'},\n {value: 'Singtom Estate Green', text: 'Singtom Estate Green'},\n {value: 'Zhejiang Gunpowder Green Tea Early Fall 2010',\n text: 'Zhejiang Gunpowder Green Tea Early Fall 2010'},\n {value: 'Santas White Christmas', text: 'Santas White Christmas'},\n {value: 'Shin-cha 88th Night - 2010 edition',\n text: 'Shin-cha 88th Night - 2010 edition'},\n {value: '2011 YS Ban Po Lao Zhai Spring Raw',\n text: '2011 YS Ban Po Lao Zhai Spring Raw'},\n {value: 'Breakfast Blend', text: 'Breakfast Blend'},\n {value: 'Darjeeling Risheehat', text: 'Darjeeling Risheehat'},\n {value: 'En Shi Yu Lu (Green Tea)', text: 'En Shi Yu Lu (Green Tea)'},\n {value: 'Root Beer Float (organic)', text: 'Root Beer Float (organic)'},\n {value: 'Lu Shan Clouds &amp; Mist', text: 'Lu Shan Clouds &amp; Mist'},\n {value: 'Mate Sweet Energy', text: 'Mate Sweet Energy'},\n {value: 'Chamomile', text: 'Chamomile'},\n {value: 'Mint Mojito', text: 'Mint Mojito'},\n {value: 'Camellia Joy', text: 'Camellia Joy'},\n {value: 'Le Bonheur à Paris', text: 'Le Bonheur à Paris'},\n {value: '2005 Wild Arbor Tree Pu-erh Tea Brick',\n text: '2005 Wild Arbor Tree Pu-erh Tea Brick'},\n {value: 'Alishan Spring 2009', text: 'Alishan Spring 2009'},\n {value: 'The Fifth of November', text: 'The Fifth of November'},\n {value: 'Dragon Well West Lake Standard Green Tea',\n text: 'Dragon Well West Lake Standard Green Tea'},\n {value: 'Mao Feng', text: 'Mao Feng'},\n {value: 'Organic Ceremonial Matcha', text: 'Organic Ceremonial Matcha'},\n {value: 'Organic Genmaicha with Matcha',\n text: 'Organic Genmaicha with Matcha'},\n {value: 'Organic White Monkey', text: 'Organic White Monkey'},\n {value: 'Sweet &amp; Spicy Red Tea', text: 'Sweet &amp; Spicy Red Tea'},\n {value: 'Strawberry Misaki', text: 'Strawberry Misaki'},\n {value: 'Save the Cave &amp; The Last Resort 5000 Shou',\n text: 'Save the Cave &amp; The Last Resort 5000 Shou'},\n {value: 'Valley Peak (Ding Gu Da Fang)',\n text: 'Valley Peak (Ding Gu Da Fang)'},\n {value: 'Organic Pearl River', text: 'Organic Pearl River'},\n {value: 'Passion (full leaf)', text: 'Passion (full leaf)'},\n {value: 'Cherry Cola (organic)', text: 'Cherry Cola (organic)'},\n {value: 'Sunburst Raspberry', text: 'Sunburst Raspberry'},\n {value: 'Darjeeling FTGFOP1 Thurbo Estate Special Crop 2008',\n text: 'Darjeeling FTGFOP1 Thurbo Estate Special Crop 2008'},\n {value: 'Marzipan Sunset', text: 'Marzipan Sunset'},\n {value: 'Organic Earl Green', text: 'Organic Earl Green'},\n {value: 'New Sensation - Hibiscus &amp; Mint',\n text: 'New Sensation - Hibiscus &amp; Mint'},\n {value: '1706 (English Strong Breakfast)',\n text: '1706 (English Strong Breakfast)'},\n {value: 'Green Almond Chai', text: 'Green Almond Chai'},\n {value: 'Mint Chocolate Chip', text: 'Mint Chocolate Chip'},\n {value: 'Kenmare Ceylon', text: 'Kenmare Ceylon'},\n {value: 'Unbridled Love Fruit Tea', text: 'Unbridled Love Fruit Tea'},\n {value: 'Dragon Well Green Tea', text: 'Dragon Well Green Tea'},\n {value: 'Kuki Yerba Mate', text: 'Kuki Yerba Mate'},\n {value: 'Darjeeling First Flush', text: 'Darjeeling First Flush'},\n {value: 'Botswana blossom', text: 'Botswana blossom'},\n {value: 'Afternoon Delight', text: 'Afternoon Delight'},\n {value: 'Drum Mountain White Cloud (Gu Shan Bai Yuan)',\n text: 'Drum Mountain White Cloud (Gu Shan Bai Yuan)'},\n {value: 'All Day Breakfast', text: 'All Day Breakfast'},\n {value: 'Ancient Phoenix', text: 'Ancient Phoenix'},\n {value: 'Green Earl Grey (newer)', text: 'Green Earl Grey (newer)'},\n {value: 'Guayusa and Chocolate Tea', text: 'Guayusa and Chocolate Tea'},\n {value: 'Tamarind Pop', text: 'Tamarind Pop'},\n {value: 'Melon Oolong', text: 'Melon Oolong'},\n {value: 'Milk Oolong', text: 'Milk Oolong'},\n {value: 'Drunken Princess', text: 'Drunken Princess'},\n {value: 'Tieguanyin Clear and Fragrant-Style Traditionally-Grown',\n text: 'Tieguanyin Clear and Fragrant-Style'},\n {value: 'Pomberry Green Tea', text: 'Pomberry Green Tea'},\n {value: 'Sunny Citrus', text: 'Sunny Citrus'},\n {value: '(Black) Currant', text: '(Black) Currant'},\n {value: '2009 Menghai Dayi V93 ripe', text: '2009 Menghai Dayi V93 ripe'},\n {value: 'Houjicha - Smoky Roast', text: 'Houjicha - Smoky Roast'},\n {value: 'China Wuyuan Jasmine - 536', text: 'China Wuyuan Jasmine - 536'},\n {value: 'Gingerbread', text: 'Gingerbread'},\n {value: 'Pearl Ku Ding', text: 'Pearl Ku Ding'},\n {value: 'Tigerhill Estate Nilgiri', text: 'Tigerhill Estate Nilgiri'},\n {value: 'Genmaicha (Brown Rice Green Tea)',\n text: 'Genmaicha (Brown Rice Green Tea)'},\n {value: 'Liquorice Legs', text: 'Liquorice Legs'},\n {value: 'Dao Ren Organic', text: 'Dao Ren Organic'},\n {value: 'Hong Jing Luo', text: 'Hong Jing Luo'},\n {value: 'Wild Root', text: 'Wild Root'},\n {value: 'Earl Grey Tea No. 42 (bagged)',\n text: 'Earl Grey Tea No. 42 (bagged)'},\n {value: 'Rooibush Chocolate', text: 'Rooibush Chocolate'},\n {value: 'Luan Melon Seed Green', text: 'Luan Melon Seed Green'},\n {value: '2006 Feng Hua Qi Cha Sheng Pu Erh Tea',\n text: '2006 Feng Hua Qi Cha Sheng Pu Erh Tea'},\n {value: 'Mi Xian Black', text: 'Mi Xian Black'},\n {value: 'Vanilla Rooibos Tea Latte', text: 'Vanilla Rooibos Tea Latte'},\n {value: 'Maharaja Chai Oolong and Samuri Chai Mate Oolong Tea',\n text: 'Maharaja Chai Oolong and Samuri Chai Mate Oolong Tea'},\n {value: 'Dragon Pearl Jasmine', text: 'Dragon Pearl Jasmine'},\n {value: 'Kabuse Sencha', text: 'Kabuse Sencha'},\n {value: 'Weißer Tee mit Tee- und Rosenblüten',\n text: 'Weißer Tee mit Tee- und Rosenblüten'},\n {value: 'Les Classiques', text: 'Les Classiques'},\n {value: 'Shan Lin Xi Winter Harvest', text: 'Shan Lin Xi Winter Harvest'},\n {value: 'Earl Grey Cream', text: 'Earl Grey Cream'},\n {value: 'otaka cha', text: 'otaka cha'},\n {value: 'Pumpkin Chai', text: 'Pumpkin Chai'},\n {value: 'The Original Chai Tea Tea Latte Concentrate',\n text: 'The Original Chai Tea Tea Latte Concentrate'},\n {value: 'Vanilla and Canadian Maple', text: 'Vanilla and Canadian Maple'},\n {value: 'Maple Cream Black Tea', text: 'Maple Cream Black Tea'},\n {value: 'Bountiful Black', text: 'Bountiful Black'},\n {value: 'Rosehip &amp; Hibiscus', text: 'Rosehip &amp; Hibiscus'},\n {value: 'Three Friends (Orange Marshmallow Chocolate)',\n text: 'Three Friends (Orange Marshmallow Chocolate)'},\n {value: 'Darjeeling Margarets Hope FTGFOP1',\n text: 'Darjeeling Margarets Hope FTGFOP1'},\n {value: 'Scottish Caramel Toffee Pu Erh',\n text: 'Scottish Caramel Toffee Pu Erh'},\n {value: 'Super Irish Breakfast', text: 'Super Irish Breakfast'},\n {value: 'Pumpkin Spice Black', text: 'Pumpkin Spice Black'},\n {value: 'Tindharia Estate FTGFOP1 Second Flush (DJ-59) Organic (TDA7)',\n text: 'Tindharia Estate FTGFOP1 Second Flush (DJ-59) Organic (TDA7)'},\n {value: 'Organic Darjeeling Goomtee', text: 'Organic Darjeeling Goomtee'},\n {value: 'Bi Luo Chun', text: 'Bi Luo Chun'},\n {value: 'Sweet Velvet Fog', text: 'Sweet Velvet Fog'},\n {value: 'Green Tea Matcha Blend', text: 'Green Tea Matcha Blend'},\n {value: 'Lucari Chai', text: 'Lucari Chai'},\n {value: 'Ginger Pear', text: 'Ginger Pear'},\n {value: 'organic rooibos', text: 'organic rooibos'},\n {value: 'Ureshino Tama Ryokucha', text: 'Ureshino Tama Ryokucha'},\n {value: 'Ayres House Victorian Blend',\n text: 'Ayres House Victorian Blend'},\n {value: 'Strawberry Kiwi', text: 'Strawberry Kiwi'},\n {value: 'Caipirinha', text: 'Caipirinha'},\n {value: 'Valentines', text: 'Valentines'},\n {value: 'White Tip Oolong', text: 'White Tip Oolong'},\n {value: 'Honeybush Caramel Tea', text: 'Honeybush Caramel Tea'},\n {value: 'Mango Ceylon with Vanilla', text: 'Mango Ceylon with Vanilla'},\n {value: 'Strawberry Sencha Green Tea',\n text: 'Strawberry Sencha Green Tea'},\n {value: 'Mountain Dragon Green', text: 'Mountain Dragon Green'},\n {value: 'Melon', text: 'Melon'},\n {value: 'Organic Singbulli SFTGFOP1Q First Flush Darjeeling',\n text: 'Organic Singbulli SFTGFOP1Q First Flush Darjeeling'},\n {value: 'Blueberry Cheesecake', text: 'Blueberry Cheesecake'},\n {value: 'Lemon Youkou &amp; Gyokuro Imperial Blend',\n text: 'Lemon Youkou &amp; Gyokuro Imperial Blend'},\n {value: 'Mangalam Broken-Leaf [duplicate]',\n text: 'Mangalam Broken-Leaf [duplicate]'},\n {value: 'Raspberry Royale', text: 'Raspberry Royale'},\n {value: 'Copacabana', text: 'Copacabana'},\n {value: 'Earl Grey Organic', text: 'Earl Grey Organic'},\n {value: 'Ginger', text: 'Ginger'},\n {value: 'Golden Fleece', text: 'Golden Fleece'},\n {value: 'Muse', text: 'Muse'},\n {value: 'Yun Wu Clouds Mist Fair Trade Green Tea',\n text: 'Yun Wu Clouds Mist Fair Trade Green Tea'},\n {value: 'Sungma Darjeeling Second Flush',\n text: 'Sungma Darjeeling Second Flush'},\n {value: 'Forest Fruit', text: 'Forest Fruit'},\n {value: 'Berries n Cream', text: 'Berries n Cream'},\n {value: 'Mélange des Chérubins', text: 'Mélange des Chérubins'},\n {value: 'Ti Quan Yin - Spring Floral',\n text: 'Ti Quan Yin - Spring Floral'},\n {value: 'Organic Hill Station [discontinued]',\n text: 'Organic Hill Station [discontinued]'},\n {value: 'Green Sea Anemone', text: 'Green Sea Anemone'},\n {value: 'Exotic Lime Green Organic Tea',\n text: 'Exotic Lime Green Organic Tea'},\n {value: 'Luzianne Decaf Tea', text: 'Luzianne Decaf Tea'},\n {value: 'Ginger Matcha', text: 'Ginger Matcha'},\n {value: 'Organic Breakfast', text: 'Organic Breakfast'},\n {value: 'Fusion Red White and Blueberry',\n text: 'Fusion Red White and Blueberry'},\n {value: 'Original Kombucha', text: 'Original Kombucha'},\n {value: 'Rose Tea', text: 'Rose Tea'},\n {value: 'iced Peach Oolong', text: 'iced Peach Oolong'},\n {value: 'Yunnan FOP', text: 'Yunnan FOP'},\n {value: 'PG Tips', text: 'PG Tips'},\n {value: 'Elderberry Green Tea', text: 'Elderberry Green Tea'},\n {value: 'Tai Chai', text: 'Tai Chai'},\n {value: 'Dragon ZenFusion', text: 'Dragon ZenFusion'},\n {value: 'Honey Ginseng Decaf', text: 'Honey Ginseng Decaf'},\n {value: 'Mlesna Colonial Tea', text: 'Mlesna Colonial Tea'},\n {value: 'Peppermint Rose Green Tea', text: 'Peppermint Rose Green Tea'},\n {value: 'Chocolate Caramel Black Dessert Tea',\n text: 'Chocolate Caramel Black Dessert Tea'},\n {value: 'Elaichi (Cardamom) Tea', text: 'Elaichi (Cardamom) Tea'},\n {value: 'Erva-Doce', text: 'Erva-Doce'},\n {value: 'Cinnamon Star', text: 'Cinnamon Star'},\n {value: 'Hot Cinnamon Spice', text: 'Hot Cinnamon Spice'},\n {value: 'Emperors Chai', text: 'Emperors Chai'},\n {value: 'Tea Puerh Mini Toucha', text: 'Tea Puerh Mini Toucha'},\n {value: 'Classic Black Tea (USA)', text: 'Classic Black Tea (USA)'},\n {value: 'Genmaicha', text: 'Genmaicha'},\n {value: '2003 Yiwu Mountain Imperial Grade Ripe Pu-erh',\n text: '2003 Yiwu Mountain Imperial Grade Ripe Pu-erh'},\n {value: 'Berry Earl Grey', text: 'Berry Earl Grey'},\n {value: 'Caramel Harmony', text: 'Caramel Harmony'},\n {value: 'Orange Pu-erh (No. 841)', text: 'Orange Pu-erh (No. 841)'},\n {value: 'Cold Season', text: 'Cold Season'},\n {value: 'TJ60: Shizuoka 2 Sencha', text: 'TJ60: Shizuoka 2 Sencha'},\n {value: 'Decaffeinated English Breakfast Ceylon OP (TC09)',\n text: 'Decaffeinated English Breakfast Ceylon OP (TC09)'},\n {value: 'Loquat Tea', text: 'Loquat Tea'},\n {value: 'Orange Pekoe and Pekoe Cut Black Tea',\n text: 'Orange Pekoe and Pekoe Cut Black Tea'},\n {value: 'The des Vahines - Green', text: 'The des Vahines - Green'},\n {value: 'Holiday 2010', text: 'Holiday 2010'},\n {value: 'Hibiscus Apple', text: 'Hibiscus Apple'},\n {value: 'Golden Orchid', text: 'Golden Orchid'},\n {value: 'Caffeine-Free Rooibos', text: 'Caffeine-Free Rooibos'},\n {value: 'Premium Formosa Oolong Choicest TT17',\n text: 'Premium Formosa Oolong Choicest TT17'},\n {value: 'diplomat earl grey', text: 'diplomat earl grey'},\n {value: 'China Keemun OP', text: 'China Keemun OP'},\n {value: 'Tropical Fire', text: 'Tropical Fire'},\n {value: 'Gyokuro', text: 'Gyokuro'},\n {value: 'St. John’s Wort Blues Away', text: 'St. John’s Wort Blues Away'},\n {value: 'Acai Green', text: 'Acai Green'},\n {value: 'Enchanted Forest', text: 'Enchanted Forest'},\n {value: 'morning dew', text: 'morning dew'},\n {value: 'Cucumber Mint', text: 'Cucumber Mint'},\n {value: 'Organic Makaibari Estate Darjeeling 2nd Flush Black Tea',\n text: 'Organic Makaibari Estate Darjeeling 2nd Flush Black Tea'},\n {value: 'Miss Jasmin ', text: 'Miss Jasmin '},\n {value: 'Pumpkin Milkshake', text: 'Pumpkin Milkshake'},\n {value: 'Bamboozled', text: 'Bamboozled'},\n {value: 'Mad Tea Party', text: 'Mad Tea Party'},\n {value: 'Sunny Dream Organic', text: 'Sunny Dream Organic'},\n {value: 'White Coconut Creme', text: 'White Coconut Creme'},\n {value: 'On Wisconsin Jade Oolong', text: 'On Wisconsin Jade Oolong'},\n {value: 'Golden Monkey King', text: 'Golden Monkey King'},\n {value: 'Blue Mountain Nilgiri', text: 'Blue Mountain Nilgiri'},\n {value: 'Viennese Earl Grey', text: 'Viennese Earl Grey'},\n {value: 'Virgin Fuzzy Navel Green Tea',\n text: 'Virgin Fuzzy Navel Green Tea'},\n {value: 'Wintertraum', text: 'Wintertraum'},\n {value: 'Special Grade Shui Jin Gui', text: 'Special Grade Shui Jin Gui'},\n {value: 'Turkish Delight', text: 'Turkish Delight'},\n {value: 'Ceylon Vithanakanda Estate Extra Special',\n text: 'Ceylon Vithanakanda Estate Extra Special'},\n {value: 'formosa specialty oolong', text: 'formosa specialty oolong'},\n {value: 'White Tea With Peppermint', text: 'White Tea With Peppermint'},\n {value: 'Iron Buddha (Tie Guan Yin)', text: 'Iron Buddha (Tie Guan Yin)'},\n {value: 'Earl Grey Supreme', text: 'Earl Grey Supreme'},\n {value: 'Organic Chocolate Roasted Mate',\n text: 'Organic Chocolate Roasted Mate'},\n {value: 'Assam Black', text: 'Assam Black'},\n {value: 'Sumatra Oolong Barisan (860)',\n text: 'Sumatra Oolong Barisan (860)'},\n {value: 'Moms Apple Pie', text: 'Moms Apple Pie'},\n {value: 'Blue Spring Oolong', text: 'Blue Spring Oolong'},\n {value: 'genmaicha', text: 'genmaicha'},\n {value: 'Te Rojo', text: 'Te Rojo'},\n {value: '2000 Pu Er Meng Hai', text: '2000 Pu Er Meng Hai'},\n {value: 'Lemon Ginger Green', text: 'Lemon Ginger Green'},\n {value: 'Organic Green Tea with Ginger',\n text: 'Organic Green Tea with Ginger'},\n {value: 'Okayti Estate White Tips Special Production',\n text: 'Okayti Estate White Tips Special Production'},\n {value: 'Phoenix Bird Oolong (Fenghuang Dancong)',\n text: 'Phoenix Bird Oolong (Fenghuang Dancong)'},\n {value: 'China Fujian Oolong Tea', text: 'China Fujian Oolong Tea'},\n {value: 'China Green Tips (full leaf)',\n text: 'China Green Tips (full leaf)'},\n {value: 'Ambrosia Plum', text: 'Ambrosia Plum'},\n {value: 'Rose Buds', text: 'Rose Buds'},\n {value: 'Empress of China', text: 'Empress of China'},\n {value: 'Lapsang Souchang', text: 'Lapsang Souchang'},\n {value: 'Vanilla Chai', text: 'Vanilla Chai'},\n {value: 'Daily Green Tea The Peoples Green Tea',\n text: 'Daily Green Tea The Peoples Green Tea'},\n {value: 'Cranberry Tea', text: 'Cranberry Tea'},\n {value: 'English Breakfast Organic-T',\n text: 'English Breakfast Organic-T'},\n {value: 'Darjeeling First Flush Oolong',\n text: 'Darjeeling First Flush Oolong'},\n {value: 'Almond Rooibos', text: 'Almond Rooibos'},\n {value: 'Troika', text: 'Troika'},\n {value: '2009 Douji Red Yu Dou Raw Pu-erh',\n text: '2009 Douji Red Yu Dou Raw Pu-erh'},\n {value: 'Organic Gun Powder Green', text: 'Organic Gun Powder Green'},\n {value: 'Lapsang Souchong and Assam Blend',\n text: 'Lapsang Souchong and Assam Blend'},\n {value: 'Ginger Green Tea', text: 'Ginger Green Tea'},\n {value: 'Si Ji Chun Oolong (Spring 2011)',\n text: 'Si Ji Chun Oolong (Spring 2011)'},\n {value: 'Pomegranate Acai Yumberry Green',\n text: 'Pomegranate Acai Yumberry Green'},\n {value: 'Sencha Hachiju-hachiya', text: 'Sencha Hachiju-hachiya'},\n {value: '2005 CNNP Grand Red in Red Pu-erh Cake',\n text: '2005 CNNP Grand Red in Red Pu-erh Cake'},\n {value: 'Tung Ting Oolong', text: 'Tung Ting Oolong'},\n {value: 'Hunan Red Oolong', text: 'Hunan Red Oolong'},\n {value: 'Gunpowder Green', text: 'Gunpowder Green'},\n {value: 'Plum Loven', text: 'Plum Loven'},\n {value: 'Baby Snow Dragon', text: 'Baby Snow Dragon'},\n {value: 'Blueberry Heather', text: 'Blueberry Heather'},\n {value: 'Strawberry Cream', text: 'Strawberry Cream'},\n {value: 'Classic Apple Pie', text: 'Classic Apple Pie'},\n {value: 'Darjeeling Blend', text: 'Darjeeling Blend'},\n {value: 'Starry Night', text: 'Starry Night'},\n {value: 'Sticky Toffee Pudding', text: 'Sticky Toffee Pudding'},\n {value: 'Green Tea Tropical', text: 'Green Tea Tropical'},\n {value: 'Kyoto Sunset', text: 'Kyoto Sunset'},\n {value: 'Young Pu-Erh', text: 'Young Pu-Erh'},\n {value: 'Green Snail Spring (Bi Luo Chun)',\n text: 'Green Snail Spring (Bi Luo Chun)'},\n {value: 'Welcome', text: 'Welcome'},\n {value: 'Bai Hao Yin Zhen', text: 'Bai Hao Yin Zhen'},\n {value: 'China Imperial Golden Monkey - ZP86',\n text: 'China Imperial Golden Monkey - ZP86'},\n {value: 'Tzar Alexandre', text: 'Tzar Alexandre'},\n {value: 'Onyx', text: 'Onyx'},\n {value: 'Organic Enlightenment Tea', text: 'Organic Enlightenment Tea'},\n {value: 'Monkey-Picked Oolong', text: 'Monkey-Picked Oolong'},\n {value: 'Don Juan', text: 'Don Juan'},\n {value: 'Risheehat Darjeeling Second Flush',\n text: 'Risheehat Darjeeling Second Flush'},\n {value: 'Bogart', text: 'Bogart'},\n {value: 'Matcha Powder', text: 'Matcha Powder'},\n {value: '2010 Premium Mao Feng', text: '2010 Premium Mao Feng'},\n {value: 'Tokyo Lime', text: 'Tokyo Lime'},\n {value: 'Mango Madness', text: 'Mango Madness'},\n {value: 'Silver Bud Ya Bao', text: 'Silver Bud Ya Bao'},\n {value: 'Decaf Iced Black Tea', text: 'Decaf Iced Black Tea'},\n {value: '2010 Bai Hao', text: '2010 Bai Hao'},\n {value: 'Get Gorgeous - No. 1 (Wellness Collection)',\n text: 'Get Gorgeous - No. 1 (Wellness Collection)'},\n {value: 'Raspberry Cream Cheese Danish Honeybush',\n text: 'Raspberry Cream Cheese Danish Honeybush'},\n {value: 'Golden Assam', text: 'Golden Assam'},\n {value: 'Bi Tan Piao Xue', text: 'Bi Tan Piao Xue'},\n {value: 'Mangoooooo', text: 'Mangoooooo'},\n {value: 'Pure Heart Alishan Oolong', text: 'Pure Heart Alishan Oolong'},\n {value: 'Almond Green Tea (Thé Vert à lAmande',\n text: 'Almond Green Tea (Thé Vert à lAmande'},\n {value: 'Ready for Bed Ritual Tea', text: 'Ready for Bed Ritual Tea'},\n {value: 'Snow Pear (Xue Li)', text: 'Snow Pear (Xue Li)'},\n {value: 'Milky Oolong', text: 'Milky Oolong'},\n {value: 'Green Tea', text: 'Green Tea'},\n {value: 'Sinu-blend', text: 'Sinu-blend'},\n {value: '2009 Six Famous Tea Mountain Yunnan Moon Pu-erh tea cake',\n text: '2009 Six Famous Tea Mountain Yunnan Moon Pu-erh tea cake'},\n {value: 'Oolong Green Dragon', text: 'Oolong Green Dragon'},\n {value: 'Chai &amp; Mighty', text: 'Chai &amp; Mighty'},\n {value: 'Fujian Rain', text: 'Fujian Rain'},\n {value: 'Island Mango', text: 'Island Mango'},\n {value: 'Pineapple Sencha', text: 'Pineapple Sencha'},\n {value: 'Darjeeling 1', text: 'Darjeeling 1'},\n {value: '2005 White Dragon Jinggu Tea Factory * Raw Pu-erh Cake - 357 gram Jing Gu Mountain Large Leaf Pekoe Varietal cake',\n text: '2005 White Dragon Jing Gu Mountain Large Leaf cake'},\n {value: 'GenmaiMatcha', text: 'GenmaiMatcha'},\n {value: 'China Oolong Qi Lan Dan Cong',\n text: 'China Oolong Qi Lan Dan Cong'},\n {value: 'Dragon Well (Lung Ching)', text: 'Dragon Well (Lung Ching)'},\n {value: 'Tie kuan Qin', text: 'Tie kuan Qin'},\n {value: 'Matcha-Style Powdered Green Tea',\n text: 'Matcha-Style Powdered Green Tea'},\n {value: 'Keemun', text: 'Keemun'},\n {value: 'Tea Haus 150 Assam SFTGOP1 Mangalam',\n text: 'Tea Haus 150 Assam SFTGOP1 Mangalam'},\n {value: 'Organic Honeybush', text: 'Organic Honeybush'},\n {value: 'Black Currant', text: 'Black Currant'},\n {value: '2007 Purple Leaf Pu-erh Tea Cake',\n text: '2007 Purple Leaf Pu-erh Tea Cake'},\n {value: 'China Yunnan FOP', text: 'China Yunnan FOP'},\n {value: 'Decorative Cake', text: 'Decorative Cake'},\n {value: 'Golden Chamomile', text: 'Golden Chamomile'},\n {value: 'Calgary Stampede Tea', text: 'Calgary Stampede Tea'},\n {value: 'Breakfast in Bed', text: 'Breakfast in Bed'},\n {value: 'Super Fruit Sencha', text: 'Super Fruit Sencha'},\n {value: 'Yunnan Pure Gold', text: 'Yunnan Pure Gold'},\n {value: 'Alpine Punch', text: 'Alpine Punch'},\n {value: 'Peach Green', text: 'Peach Green'},\n {value: 'La La Lemon (organic)', text: 'La La Lemon (organic)'},\n {value: 'Toasty Almond', text: 'Toasty Almond'},\n {value: 'Winter Blend', text: 'Winter Blend'},\n {value: 'CO2 Premium Decaffeinated Assam',\n text: 'CO2 Premium Decaffeinated Assam'},\n {value: 'Professor Grey', text: 'Professor Grey'},\n {value: 'Pomegranate Fruit Blend', text: 'Pomegranate Fruit Blend'},\n {value: 'Matcha Hekisui', text: 'Matcha Hekisui'},\n {value: 'Black coffee', text: 'Black coffee'},\n {value: 'Thé Champagne', text: 'Thé Champagne'},\n {value: 'Heritage Aijiao', text: 'Heritage Aijiao'},\n {value: 'Golden Dan Chong', text: 'Golden Dan Chong'},\n {value: 'Peach Oolong', text: 'Peach Oolong'},\n {value: 'Earl Grey House Blend', text: 'Earl Grey House Blend'},\n {value: 'Irish Blend', text: 'Irish Blend'},\n {value: 'Lao Shan Cha', text: 'Lao Shan Cha'},\n {value: 'Balance Tea', text: 'Balance Tea'},\n {value: 'Tsugaru Green', text: 'Tsugaru Green'},\n {value: 'Root Beer (Iced Tea Series)',\n text: 'Root Beer (Iced Tea Series)'},\n {value: 'Natural Organic Raw Green Bush Tea',\n text: 'Natural Organic Raw Green Bush Tea'},\n {value: 'Darjeeling First Flush Thurbo 2009',\n text: 'Darjeeling First Flush Thurbo 2009'},\n {value: 'Echinacea Winter Infusion', text: 'Echinacea Winter Infusion'},\n {value: 'Hot Cinnamon', text: 'Hot Cinnamon'},\n {value: 'Yang Yan Gou Qing', text: 'Yang Yan Gou Qing'},\n {value: 'Happy Valley', text: 'Happy Valley'},\n {value: 'Throat Comfort', text: 'Throat Comfort'},\n {value: 'Scottish Caramel Toffee Pu-erh',\n text: 'Scottish Caramel Toffee Pu-erh'},\n {value: 'Eastern Beauty', text: 'Eastern Beauty'},\n {value: 'San Bei Xiang Green', text: 'San Bei Xiang Green'},\n {value: 'YMY 1690 China Oolong', text: 'YMY 1690 China Oolong'},\n {value: 'Dream Camomile Lemon', text: 'Dream Camomile Lemon'},\n {value: 'Rose Black Tea', text: 'Rose Black Tea'},\n {value: 'Darjeeling Sungma Summer (22)',\n text: 'Darjeeling Sungma Summer (22)'},\n {value: 'Ya Bao', text: 'Ya Bao'},\n {value: 'Se Chung Oolong', text: 'Se Chung Oolong'},\n {value: 'Gourmet Herbal (No. 1237)', text: 'Gourmet Herbal (No. 1237)'},\n {value: 'Verveine (Lemon Verbena)', text: 'Verveine (Lemon Verbena)'},\n {value: 'Earl Grey Lavender', text: 'Earl Grey Lavender'},\n {value: 'Shouju no Shiro', text: 'Shouju no Shiro'},\n {value: 'Jamaïque', text: 'Jamaïque'},\n {value: 'Coconut Cabana', text: 'Coconut Cabana'},\n {value: 'October', text: 'October'},\n {value: 'Nepal Top Oolong', text: 'Nepal Top Oolong'},\n {value: 'Assam Mokalbari SFTGBOP CL', text: 'Assam Mokalbari SFTGBOP CL'},\n {value: 'Pure Japanese Matcha', text: 'Pure Japanese Matcha'},\n {value: 'Pirkka Earl Grey', text: 'Pirkka Earl Grey'},\n {value: 'Darjeeling Lucky Hill', text: 'Darjeeling Lucky Hill'},\n {value: 'Chá verde Inverno', text: 'Chá verde Inverno'},\n {value: 'Mint Green', text: 'Mint Green'},\n {value: 'Lemon Solstice', text: 'Lemon Solstice'},\n {value: 'Le Bonheur (Happiness)', text: 'Le Bonheur (Happiness)'},\n {value: 'Extra BOLD Masala Chai', text: 'Extra BOLD Masala Chai'},\n {value: 'Organic Lemon Echinacea Throat Coat',\n text: 'Organic Lemon Echinacea Throat Coat'},\n {value: '2010 Autumn Yong De Cha Hua Camellia Sinensis Assamica Tea Flower',\n text: '2010 Autumn Yong De Cha Hua'},\n {value: 'Chamomile Clementine', text: 'Chamomile Clementine'},\n {value: '2004 Nanjian Fenghuang Tuo Sheng superior grade',\n text: '2004 Nanjian Fenghuang Tuo Sheng superior grade'},\n {value: 'Darjeeling First Flush 2009 FTGFOP1',\n text: 'Darjeeling First Flush 2009 FTGFOP1'},\n {value: 'Yunnan Golden Pu-erh Tea', text: 'Yunnan Golden Pu-erh Tea'},\n {value: 'Japan Sencha', text: 'Japan Sencha'},\n {value: 'Cocomint Cream', text: 'Cocomint Cream'},\n {value: 'Tropical Green Tea', text: 'Tropical Green Tea'},\n {value: 'Peppermint Rooibos', text: 'Peppermint Rooibos'},\n {value: 'Green Tea Powder', text: 'Green Tea Powder'},\n {value: 'ChocolaTEA', text: 'ChocolaTEA'},\n {value: 'White Pear', text: 'White Pear'},\n {value: 'Organic Dong Ding (dark) Oolong',\n text: 'Organic Dong Ding (dark) Oolong'},\n {value: 'Brioche Organic Tea', text: 'Brioche Organic Tea'},\n {value: 'Mild Orange Green Tea', text: 'Mild Orange Green Tea'},\n {value: 'Bai Hao Yin Zhen (Silver Needle) White Tea (Organic)',\n text: 'Bai Hao Yin Zhen (Silver Needle) White Tea (Organic)'},\n {value: 'Garden Tea', text: 'Garden Tea'},\n {value: 'Coco Caramel', text: 'Coco Caramel'},\n {value: '2007 Xingyang Imperial Shu', text: '2007 Xingyang Imperial Shu'},\n {value: 'Echinacea and Raspberry', text: 'Echinacea and Raspberry'},\n {value: '1998 Chung-Cha 8582', text: '1998 Chung-Cha 8582'},\n {value: 'Mandarin Orange Organic', text: 'Mandarin Orange Organic'},\n {value: 'Assam Tippy Golden', text: 'Assam Tippy Golden'},\n {value: 'Premium Organic Matcha Ceremonial Green Tea',\n text: 'Premium Organic Matcha Ceremonial Green Tea'},\n {value: 'Red-Tailed Hawk', text: 'Red-Tailed Hawk'},\n {value: 'Wuyi Shui Xian (Water Fairy)',\n text: 'Wuyi Shui Xian (Water Fairy)'},\n {value: 'Green Kick by Now Real Foods',\n text: 'Green Kick by Now Real Foods'},\n {value: '2000 CNNP Lincang Ripe Cake Puerh',\n text: '2000 CNNP Lincang Ripe Cake Puerh'},\n {value: 'No.51 Sencha', text: 'No.51 Sencha'},\n {value: 'Castleton Autumnal TGFOP1', text: 'Castleton Autumnal TGFOP1'},\n {value: 'Zin Hsuan Oolong', text: 'Zin Hsuan Oolong'},\n {value: 'English Breakfast Tea', text: 'English Breakfast Tea'},\n {value: 'Apricot Cheesecake Shou Mei',\n text: 'Apricot Cheesecake Shou Mei'},\n {value: 'Raspberry Riot Lemon Mate', text: 'Raspberry Riot Lemon Mate'},\n {value: 'Organic Korakundah', text: 'Organic Korakundah'},\n {value: 'Camomile', text: 'Camomile'},\n {value: 'Tingxi Orchid Green', text: 'Tingxi Orchid Green'},\n {value: 'China Fancy White Peony (Organic)',\n text: 'China Fancy White Peony (Organic)'},\n {value: 'Sencha of the Autumn Moon', text: 'Sencha of the Autumn Moon'},\n {value: 'Grüner Tee', text: 'Grüner Tee'},\n {value: 'Ceylon King', text: 'Ceylon King'},\n {value: 'Mount Everest Breakfast Blend (805)',\n text: 'Mount Everest Breakfast Blend (805)'},\n {value: '2008 Yi Heng Xiang Pigtails Old Tree raw/sheng',\n text: '2008 Yi Heng Xiang Pigtails Old Tree raw/sheng'},\n {value: 'Rooibos Kalahari', text: 'Rooibos Kalahari'},\n {value: 'Monkey Picked Iron Goddess of Mercy',\n text: 'Monkey Picked Iron Goddess of Mercy'},\n {value: 'Tranquil Dream', text: 'Tranquil Dream'},\n {value: 'Karigane', text: 'Karigane'},\n {value: 'French Earl Grey', text: 'French Earl Grey'},\n {value: 'Wu Yi Shan Phoenix Oolong 2011 Early Spring',\n text: 'Wu Yi Shan Phoenix Oolong 2011 Early Spring'},\n {value: 'Winter Solstice', text: 'Winter Solstice'},\n {value: 'Tippy South Cloud', text: 'Tippy South Cloud'},\n {value: 'Special Milk Tea', text: 'Special Milk Tea'},\n {value: 'Reishi Mushroom Tea', text: 'Reishi Mushroom Tea'},\n {value: 'Maple Creme', text: 'Maple Creme'},\n {value: 'Pure Guayusa', text: 'Pure Guayusa'},\n {value: 'Shan Lin Xi', text: 'Shan Lin Xi'},\n {value: 'Decaf Tea', text: 'Decaf Tea'},\n {value: 'Organic Jasmine Pearl Green Tea',\n text: 'Organic Jasmine Pearl Green Tea'},\n {value: 'Matcha Izumi', text: 'Matcha Izumi'},\n {value: 'Banana Pudding Black Tea', text: 'Banana Pudding Black Tea'},\n {value: 'Blueberry Vanilla', text: 'Blueberry Vanilla'},\n {value: 'Hwang Cha (Partially Oxidized Tea)',\n text: 'Hwang Cha (Partially Oxidized Tea)'},\n {value: 'Licorice Fennel Lemon Balm (Tisana Dopo Pasto)',\n text: 'Licorice Fennel Lemon Balm (Tisana Dopo Pasto)'},\n {value: 'Oothu White', text: 'Oothu White'},\n {value: 'Root Beer Rooibos', text: 'Root Beer Rooibos'},\n {value: 'Ancient Yellow Buds', text: 'Ancient Yellow Buds'},\n {value: 'Allergi-TEA', text: 'Allergi-TEA'},\n {value: 'Holiday Chai', text: 'Holiday Chai'},\n {value: 'mini pu-erh balls', text: 'mini pu-erh balls'},\n {value: 'Monks Blend', text: 'Monks Blend'},\n {value: 'Libre Tea Travel Glass', text: 'Libre Tea Travel Glass'},\n {value: 'Ooooh Darjeeling', text: 'Ooooh Darjeeling'},\n {value: 'Green Monkey King (Tai Ping Hou Kui)',\n text: 'Green Monkey King (Tai Ping Hou Kui)'},\n {value: 'Afternoon Tea', text: 'Afternoon Tea'},\n {value: 'Jade Oolong 18', text: 'Jade Oolong 18'},\n {value: 'Pumpkin Ginger', text: 'Pumpkin Ginger'},\n {value: 'Mao Xie', text: 'Mao Xie'},\n {value: 'Cocoa Canela (organic)', text: 'Cocoa Canela (organic)'},\n {value: 'Phoenix Oolong', text: 'Phoenix Oolong'},\n {value: 'Chamomile &amp; Lavender', text: 'Chamomile &amp; Lavender'},\n {value: 'Mystery Hong Cha', text: 'Mystery Hong Cha'},\n {value: 'Peach Cobbler Green Tea', text: 'Peach Cobbler Green Tea'},\n {value: 'Lemon Oolong', text: 'Lemon Oolong'},\n {value: 'Chocolate Chai', text: 'Chocolate Chai'},\n {value: 'Darjeeling Giddapahar Estate Second Flush',\n text: 'Darjeeling Giddapahar Estate Second Flush'},\n {value: 'Rich Pioneer Tea', text: 'Rich Pioneer Tea'},\n {value: 'Organic Green Tea', text: 'Organic Green Tea'},\n {value: 'Oolong Dan Cong', text: 'Oolong Dan Cong'},\n {value: 'Rooibos Pomegranate Acai Berry',\n text: 'Rooibos Pomegranate Acai Berry'},\n {value: '2007 Menghai Dayi Secret Fragrance (Anxiang) Ripe',\n text: '2007 Menghai Dayi Secret Fragrance (Anxiang) Ripe'},\n {value: '2017 Haiwan Good Tea For Everyone Raw Puerh',\n text: '2017 Haiwan Good Tea For Everyone Raw Puerh'},\n {value: 'Singbulli Estate SFTGFOP1 Cl/Fl First Flush (DJ-14) Organic (TD95)',\n text: 'Singbulli Estate SFTGFOP1 Cl/Fl First Flush'},\n {value: 'Wenshan Aromatic Bamboo Roasted Pu-erh',\n text: 'Wenshan Aromatic Bamboo Roasted Pu-erh'},\n {value: 'Sencha', text: 'Sencha'},\n {value: 'Nansan Village 2004 Sheng', text: 'Nansan Village 2004 Sheng'},\n {value: 'Sorapot', text: 'Sorapot'},\n {value: 'Puttabong dj5 clonal queen 1st Flush 2010',\n text: 'Puttabong dj5 clonal queen 1st Flush 2010'},\n {value: 'Earl Grey Blue Flower', text: 'Earl Grey Blue Flower'},\n {value: 'Kao Shan (High Mountain) Oolong',\n text: 'Kao Shan (High Mountain) Oolong'},\n {value: '2010 Fall Diamond Grade Tie Guan Yin',\n text: '2010 Fall Diamond Grade Tie Guan Yin'},\n {value: 'Formosa Alishan Oolong', text: 'Formosa Alishan Oolong'},\n {value: 'Vanilla Mint Chai', text: 'Vanilla Mint Chai'},\n {value: 'Sencha eple/kanel', text: 'Sencha eple/kanel'},\n {value: 'Pear Luna', text: 'Pear Luna'},\n {value: 'Vanilla Mint Escape', text: 'Vanilla Mint Escape'},\n {value: 'Guayusa and Rooibos Tea', text: 'Guayusa and Rooibos Tea'},\n {value: 'Peppermint Joy', text: 'Peppermint Joy'},\n {value: 'Silver Needle', text: 'Silver Needle'},\n {value: '2006 Manzhuan Arbor Tree Pu-erh Tea Brick',\n text: '2006 Manzhuan Arbor Tree Pu-erh Tea Brick'},\n {value: 'Zhao Li Qiao', text: 'Zhao Li Qiao'},\n {value: 'Framboise Caramel', text: 'Framboise Caramel'},\n {value: 'Lemolicious Ecuadorian Guayusa',\n text: 'Lemolicious Ecuadorian Guayusa'},\n {value: 'Tasty Toasted Almond', text: 'Tasty Toasted Almond'},\n {value: '2014 Darjeeling First Flush from Monteviot Garden',\n text: '2014 Darjeeling First Flush from Monteviot Garden'},\n {value: 'Silver Needle White Tea (Fuding Bai Hao Yin Zhen)',\n text: 'Silver Needle White Tea (Fuding Bai Hao Yin Zhen)'},\n {value: 'Apple Cinnamon', text: 'Apple Cinnamon'},\n {value: 'Bancha Kyoto', text: 'Bancha Kyoto'},\n {value: 'Green Earl Grey', text: 'Green Earl Grey'},\n {value: '2013 Sheng Puerh - Spring', text: '2013 Sheng Puerh - Spring'},\n {value: 'Sweet Kiss (Cherry Strawberry)',\n text: 'Sweet Kiss (Cherry Strawberry)'},\n {value: 'Corn Tea', text: 'Corn Tea'},\n {value: 'Big Red Robe - Premium Grade Light Roast',\n text: 'Big Red Robe - Premium Grade Light Roast'},\n {value: 'Vanilla Cream', text: 'Vanilla Cream'},\n {value: 'African Pride Tea', text: 'African Pride Tea'},\n {value: 'Peach Apricot', text: 'Peach Apricot'},\n {value: 'Sweet Indulgence Hydrangea', text: 'Sweet Indulgence Hydrangea'},\n {value: 'Arya Pearl First Flush White Darjeeling',\n text: 'Arya Pearl First Flush White Darjeeling'},\n {value: 'Nilgiri Woodland', text: 'Nilgiri Woodland'},\n {value: 'Blackberry Sage', text: 'Blackberry Sage'},\n {value: 'Twelve Gentlemen Pu-Erh Raw (Sheng) 357g 2006 Zui Tai Ping beeng',\n text: 'Twelve Gentlemen Pu-Erh Raw (Sheng) 357g 2006 Zui Tai Ping beeng'},\n {value: 'Chamana Verde', text: 'Chamana Verde'},\n {value: 'Golden Sail Brand Special Toucha',\n text: 'Golden Sail Brand Special Toucha'},\n {value: 'INTP Personali-tea', text: 'INTP Personali-tea'},\n {value: 'Hei Wulong (Black Oolong)', text: 'Hei Wulong (Black Oolong)'},\n {value: 'Assam Sewpur TGBOP (organic)',\n text: 'Assam Sewpur TGBOP (organic)'},\n {value: 'Chandernagor', text: 'Chandernagor'},\n {value: 'Organic Irish Breakfast', text: 'Organic Irish Breakfast'},\n {value: 'Talis Masala Chai', text: 'Talis Masala Chai'},\n {value: 'Nana Tea', text: 'Nana Tea'},\n {value: 'I Love Lemon', text: 'I Love Lemon'},\n {value: 'TF18: Apricot', text: 'TF18: Apricot'},\n {value: 'Strawberry Zabaglione', text: 'Strawberry Zabaglione'},\n {value: '2013 Winter Ali Shan', text: '2013 Winter Ali Shan'},\n {value: 'Zhen Qu', text: 'Zhen Qu'},\n {value: 'Citron Sonata',\n text: 'Citron Sonata'},\n {value: 'Rooibos', text: 'Rooibos'},\n {value: 'Ti Kuan Yin', text: 'Ti Kuan Yin'},\n {value: 'Classic Escapade Collection',\n text: 'Classic Escapade Collection'},\n {value: 'Jade Dragon', text: 'Jade Dragon'},\n {value: '2009 Gu Shu Lan Xiang', text: '2009 Gu Shu Lan Xiang'},\n {value: 'Ceremonial Matcha', text: 'Ceremonial Matcha'},\n {value: 'Bi Lo Chun Reserve', text: 'Bi Lo Chun Reserve'},\n {value: 'China Lapsang Souchong', text: 'China Lapsang Souchong'},\n {value: 'Turmeric Ginger', text: 'Turmeric Ginger'},\n {value: 'Spring Sonata', text: 'Spring Sonata'},\n {value: 'Ming Xiang Oolong', text: 'Ming Xiang Oolong'},\n {value: 'Earl Grey Royal (No. 822)', text: 'Earl Grey Royal (No. 822)'},\n {value: 'Fairtrade Tea', text: 'Fairtrade Tea'},\n {value: 'Wild Forest Black', text: 'Wild Forest Black'},\n {value: 'Blue People', text: 'Blue People'},\n {value: 'Traditional Ti Kuan Yin No. 2244',\n text: 'Traditional Ti Kuan Yin No. 2244'},\n {value: 'Je TAime', text: 'Je TAime'},\n {value: 'Qian Jia Feng 2009 (Jin Zhu Shan)',\n text: 'Qian Jia Feng 2009 (Jin Zhu Shan)'},\n {value: 'Breathe Deep', text: 'Breathe Deep'},\n {value: 'Caramel Pumpkin Cheesecake', text: 'Caramel Pumpkin Cheesecake'},\n {value: 'Tippy Yunnan', text: 'Tippy Yunnan'},\n {value: 'RELAX: TranquilyTea – Passionflower Linden Chamomile',\n text: 'RELAX: TranquilyTea – Passionflower Linden Chamomile'},\n {value: 'Jasmine Green', text: 'Jasmine Green'},\n {value: 'Shizuoka Sen-Cha', text: 'Shizuoka Sen-Cha'},\n {value: 'With Masala Natural Flavour',\n text: 'With Masala Natural Flavour'},\n {value: 'Second Flush Darjeeling FTGFOP1 Ambootia (Organic)',\n text: 'Second Flush Darjeeling FTGFOP1 Ambootia (Organic)'},\n {value: 'TWG Earl Grey Gentleman', text: 'TWG Earl Grey Gentleman'},\n {value: 'Chestnut', text: 'Chestnut'},\n {value: 'Traditional Dong Ding (2009 Winter)',\n text: 'Traditional Dong Ding (2009 Winter)'},\n {value: 'Meditation Tea', text: 'Meditation Tea'},\n {value: 'Apricot Green', text: 'Apricot Green'},\n {value: 'Cha Cha', text: 'Cha Cha'},\n {value: 'Black Mango', text: 'Black Mango'},\n {value: 'Organic Huangshan Mao Feng', text: 'Organic Huangshan Mao Feng'},\n {value: 'China Lung Ching 1st grade', text: 'China Lung Ching 1st grade'},\n {value: '2010 Autumn Jin Guan Yin Anxi Oolong Tea',\n text: '2010 Autumn Jin Guan Yin Anxi Oolong Tea'},\n {value: 'Organic Royal Matcha', text: 'Organic Royal Matcha'},\n {value: 'Earl Grey London', text: 'Earl Grey London'},\n {value: 'Mboma Estate BOP', text: 'Mboma Estate BOP'},\n {value: 'Samovar Blend Tsarina', text: 'Samovar Blend Tsarina'},\n {value: 'Persian Mint Spice', text: 'Persian Mint Spice'},\n {value: 'Mountain Mint', text: 'Mountain Mint'},\n {value: 'Muscat Green Oolong', text: 'Muscat Green Oolong'},\n {value: 'Formosa Oolong Finest', text: 'Formosa Oolong Finest'},\n {value: 'Carävan', text: 'Carävan'},\n {value: 'Hand Picked Bao Zhong', text: 'Hand Picked Bao Zhong'},\n {value: 'Clouds and Mist', text: 'Clouds and Mist'},\n {value: 'Better Than Sex', text: 'Better Than Sex'},\n {value: 'Decaf Assam', text: 'Decaf Assam'},\n {value: 'Agrumance', text: 'Agrumance'},\n {value: 'Bai Hao Silver Needle', text: 'Bai Hao Silver Needle'},\n {value: 'Matcha', text: 'Matcha'},\n {value: 'Herfst Storm', text: 'Herfst Storm'},\n {value: 'Mugicha (Barley)', text: 'Mugicha (Barley)'},\n {value: 'Early Spring 2011 Yunnan Bi Luo Chun Green tea',\n text: 'Early Spring 2011 Yunnan Bi Luo Chun Green tea'},\n {value: 'Chrysanthemum Pu-er', text: 'Chrysanthemum Pu-er'},\n {value: 'Christmas Cookie', text: 'Christmas Cookie'},\n {value: '2008 Menghai Dayi V93 Ripe Pu-erh tea',\n text: '2008 Menghai Dayi V93 Ripe Pu-erh tea'},\n {value: 'Zombie Blood Orange', text: 'Zombie Blood Orange'},\n {value: 'Japanese Cherry', text: 'Japanese Cherry'},\n {value: 'Lucky Irish Breakfast', text: 'Lucky Irish Breakfast'},\n {value: 'Tangerine Almond', text: 'Tangerine Almond'},\n {value: 'Hashiri Shincha', text: 'Hashiri Shincha'},\n {value: 'Mango Tango', text: 'Mango Tango'},\n {value: 'Lychee Osmanthus', text: 'Lychee Osmanthus'},\n {value: 'Aged Tie Guan Yin Mini Packs',\n text: 'Aged Tie Guan Yin Mini Packs'},\n {value: 'Meditative Mind', text: 'Meditative Mind'},\n {value: 'Mokalbari STGBOP', text: 'Mokalbari STGBOP'},\n {value: 'honey ginseng', text: 'honey ginseng'},\n {value: 'Earl White', text: 'Earl White'},\n {value: '2011 Menghai Dayi V93', text: '2011 Menghai Dayi V93'},\n {value: 'Caribbean Sencha', text: 'Caribbean Sencha'},\n {value: 'Egyptian Nights:', text: 'Egyptian Nights:'},\n {value: 'Organic Earl Grey', text: 'Organic Earl Grey'},\n {value: '1978 Green Loose Leaf Pu-erh',\n text: '1978 Green Loose Leaf Pu-erh'},\n {value: 'turkish black', text: 'turkish black'},\n {value: 'African Rooibos Strawberry and Vanilla',\n text: 'African Rooibos Strawberry and Vanilla'},\n {value: 'DISCONTINUED - Cinnamon Rooibos (Formerly Honey Graham Cracker)',\n text: 'DISCONTINUED - Cinnamon Rooibos'},\n {value: 'Rose Silver Needle', text: 'Rose Silver Needle'},\n {value: 'Korakundah Earl Grey', text: 'Korakundah Earl Grey'},\n {value: 'Formosa Oolong', text: 'Formosa Oolong'},\n {value: 'Raspberry Honey Tea', text: 'Raspberry Honey Tea'},\n {value: 'Orange Chocolat', text: 'Orange Chocolat'},\n {value: 'White White Cocoa', text: 'White White Cocoa'},\n {value: 'Golden Dragon Oolong', text: 'Golden Dragon Oolong'},\n {value: 'Very Berry/Fig Sencha', text: 'Very Berry/Fig Sencha'},\n {value: 'Nutcracker Sweet', text: 'Nutcracker Sweet'},\n {value: 'Rosehips and Hibiscus', text: 'Rosehips and Hibiscus'},\n {value: 'LEnchanteresse', text: 'LEnchanteresse'},\n {value: 'Huang Jin Gui', text: 'Huang Jin Gui'},\n {value: 'Cinnamon Toddy', text: 'Cinnamon Toddy'},\n {value: 'White Tea with Island Mango and Peach',\n text: 'White Tea with Island Mango and Peach'},\n {value: 'Oolong Chocolate Chai', text: 'Oolong Chocolate Chai'},\n {value: 'Blood Orange', text: 'Blood Orange'},\n {value: 'Mandela Masala', text: 'Mandela Masala'},\n {value: 'Premium Mountain Oolong', text: 'Premium Mountain Oolong'},\n {value: 'Ginger Bounce Rooibos', text: 'Ginger Bounce Rooibos'},\n {value: 'Chai', text: 'Chai'},\n {value: 'Bedtime', text: 'Bedtime'},\n {value: 'Black Dragon Pearls', text: 'Black Dragon Pearls'},\n {value: '1970s Tong Qing Hao Sheng Puerh',\n text: '1970s Tong Qing Hao Sheng Puerh'},\n {value: 'Lemon and Ginger Green Tea', text: 'Lemon and Ginger Green Tea'},\n {value: 'Da Hong Pao', text: 'Da Hong Pao'},\n {value: 'Organic Sencha Fuji', text: 'Organic Sencha Fuji'},\n {value: 'Temple of Heaven Gunpowder', text: 'Temple of Heaven Gunpowder'},\n {value: 'Sweet Matcha Original', text: 'Sweet Matcha Original'},\n {value: 'Windsor Castle', text: 'Windsor Castle'},\n {value: 'Vanilla Green', text: 'Vanilla Green'},\n {value: 'ChocoNut', text: 'ChocoNut'},\n {value: 'Organic Dragons Well Green Tea',\n text: 'Organic Dragons Well Green Tea'},\n {value: 'Assam Gold Rain', text: 'Assam Gold Rain'},\n {value: 'Vanilla Creme Earl Grey', text: 'Vanilla Creme Earl Grey'},\n {value: 'Vanilla Coconut', text: 'Vanilla Coconut'},\n {value: 'Organic Cherry Blossom White Tea Blend',\n text: 'Organic Cherry Blossom White Tea Blend'},\n {value: 'Tropical Fruits (Frutas tropicales)',\n text: 'Tropical Fruits (Frutas tropicales)'},\n {value: 'English Estate Earl Grey', text: 'English Estate Earl Grey'},\n {value: 'Chocolate Oo Strawberry Mocha',\n text: 'Chocolate Oo Strawberry Mocha'},\n {value: 'Green Chai', text: 'Green Chai'},\n {value: 'Thai Mountain Oolong', text: 'Thai Mountain Oolong'},\n {value: 'Wenshan Baozhong', text: 'Wenshan Baozhong'},\n {value: 'Phatty Cake II: The Sequel', text: 'Phatty Cake II: The Sequel'},\n {value: 'Sakura Cherry Rose', text: 'Sakura Cherry Rose'},\n {value: 'Nostalgia', text: 'Nostalgia'},\n {value: 'Ilam Silver Needle', text: 'Ilam Silver Needle'},\n {value: 'Morrocan Mint', text: 'Morrocan Mint'},\n {value: 'keenum', text: 'keenum'},\n {value: 'Maui Wowi', text: 'Maui Wowi'},\n {value: 'Almond Delight', text: 'Almond Delight'},\n {value: 'Blueberry Lemon', text: 'Blueberry Lemon'},\n {value: 'Cinnamon Stick', text: 'Cinnamon Stick'},\n {value: 'Premium Lu Shan Yun Wu', text: 'Premium Lu Shan Yun Wu'},\n {value: 'White Swiss Truffle Rooibos',\n text: 'White Swiss Truffle Rooibos'},\n {value: 'Black Rose', text: 'Black Rose'},\n {value: '2006 Bulang Mountain Old Tree Raw Pu-erh',\n text: '2006 Bulang Mountain Old Tree Raw Pu-erh'},\n {value: 'Decaf Mandarin Green', text: 'Decaf Mandarin Green'},\n {value: 'Green Tea with Jasmine', text: 'Green Tea with Jasmine'},\n {value: 'Original Earl Grey (TE10)', text: 'Original Earl Grey (TE10)'},\n {value: 'White Nectarine', text: 'White Nectarine'},\n {value: 'English Apple', text: 'English Apple'},\n {value: 'Indian Summer', text: 'Indian Summer'},\n {value: 'Pumpkin Spice', text: 'Pumpkin Spice'},\n {value: 'Morning Matcha', text: 'Morning Matcha'},\n {value: 'Orange Blossom Oolong', text: 'Orange Blossom Oolong'},\n {value: 'Multiple Teas', text: 'Multiple Teas'},\n {value: '2010 Fall Lao Tai Di (Old Plantation) Qing Xin',\n text: '2010 Fall Lao Tai Di (Old Plantation) Qing Xin'},\n {value: 'Cha Cha Chai (Organic &amp; Fair Trade)',\n text: 'Cha Cha Chai (Organic Fair Trade)'},\n {value: 'Organic Morning Rouge', text: 'Organic Morning Rouge'},\n {value: 'Wu Yi Water Fairy Oolong', text: 'Wu Yi Water Fairy Oolong'},\n {value: 'Organic Hong Songzhen (Pine Needle) Black Tea',\n text: 'Organic Hong Songzhen (Pine Needle) Black Tea'},\n {value: '2007 Organic Menghai Banzhang Old Tree Pu-erh',\n text: '2007 Organic Menghai Banzhang Old Tree Pu-erh'},\n {value: 'Kukicha', text: 'Kukicha'},\n {value: 'Truffle Black', text: 'Truffle Black'},\n {value: 'Formosa Ali Shan', text: 'Formosa Ali Shan'},\n {value: 'Cinnamon Crackle', text: 'Cinnamon Crackle'},\n {value: 'Yixing Mao Feng', text: 'Yixing Mao Feng'},\n {value: 'Tahitian Vanilla Hazelnut', text: 'Tahitian Vanilla Hazelnut'},\n {value: 'ZW60: Special Grade Shou Mei White Tea',\n text: 'ZW60: Special Grade Shou Mei White Tea'},\n {value: 'Harmonise', text: 'Harmonise'},\n {value: 'Green Rooibos', text: 'Green Rooibos'},\n {value: 'Cha Wang Huang Shan Mao Feng Spring 2011',\n text: 'Cha Wang Huang Shan Mao Feng Spring 2011'},\n {value: 'Russian Blend', text: 'Russian Blend'},\n {value: 'The Goose Is Loose 28', text: 'The Goose Is Loose 28'},\n {value: 'Japanese Sencha', text: 'Japanese Sencha'},\n {value: 'Cooked Puerh (Fuhai Factory 2000)',\n text: 'Cooked Puerh (Fuhai Factory 2000)'},\n {value: 'Pu-Erh Black Tea', text: 'Pu-Erh Black Tea'},\n {value: 'Kenya Milima', text: 'Kenya Milima'},\n {value: 'Shan Tuyet Snow Green', text: 'Shan Tuyet Snow Green'},\n {value: 'Organic Lapsang Souchong Black Tea',\n text: 'Organic Lapsang Souchong Black Tea'},\n {value: 'Japanese Green Tea', text: 'Japanese Green Tea'},\n {value: 'Napuk FTGFOP1', text: 'Napuk FTGFOP1'},\n {value: '919 Kings Tea', text: '919 Kings Tea'},\n {value: 'Kai Hua Crescendo', text: 'Kai Hua Crescendo'},\n {value: 'Premium Taiwanese Assam', text: 'Premium Taiwanese Assam'},\n {value: 'Brazil Roasted Mate Hazelnut',\n text: 'Brazil Roasted Mate Hazelnut'},\n {value: 'Nepalese Oolong', text: 'Nepalese Oolong'},\n {value: 'Iskandar', text: 'Iskandar'},\n {value: 'Fukimushi Shizuoka', text: 'Fukimushi Shizuoka'},\n {value: 'Quangzhou Milk Oolong', text: 'Quangzhou Milk Oolong'},\n {value: 'Fusion Red and White', text: 'Fusion Red and White'},\n {value: 'Golden Yunnan', text: 'Golden Yunnan'},\n {value: 'Seasons Pick Yunnan FBOP (ZY02)',\n text: 'Seasons Pick Yunnan FBOP (ZY02)'},\n {value: 'sikkim Temi', text: 'sikkim Temi'},\n {value: 'Yorkshire Gold Bags', text: 'Yorkshire Gold Bags'},\n {value: '2011 Nan Mu Chun Jing Mai Gu Shu',\n text: '2011 Nan Mu Chun Jing Mai Gu Shu'},\n {value: 'Moroccan Mint', text: 'Moroccan Mint'},\n {value: 'Ginger Oolong', text: 'Ginger Oolong'},\n {value: 'Jasmine Flower Green Tea', text: 'Jasmine Flower Green Tea'},\n {value: 'Hawaii Mauka Oolong', text: 'Hawaii Mauka Oolong'},\n {value: 'Gong Xi Zhu Cha (Gunpowder) Organic Green Tea 2011',\n text: 'Gong Xi Zhu Cha (Gunpowder) Organic Green Tea 2011'},\n {value: 'Lemon Meringue Chai', text: 'Lemon Meringue Chai'},\n {value: 'Singtom Estate SFTGFOP1 Second Flush',\n text: 'Singtom Estate SFTGFOP1 Second Flush'},\n {value: 'Apple Cider Black Tea', text: 'Apple Cider Black Tea'},\n {value: 'Organic Mornings Journey [discontinued]',\n text: 'Organic Mornings Journey [discontinued]'},\n {value: 'Himalayan Travellers Tea (organic)',\n text: 'Himalayan Travellers Tea (organic)'},\n {value: 'White Champagne', text: 'White Champagne'},\n {value: 'China Rose', text: 'China Rose'},\n {value: 'French Vanilla Orchid', text: 'French Vanilla Orchid'},\n {value: 'White Peach', text: 'White Peach'},\n {value: 'Summer Pudding Tea', text: 'Summer Pudding Tea'},\n {value: 'Sweet Pear Punch', text: 'Sweet Pear Punch'},\n {value: 'Three Mint Tea', text: 'Three Mint Tea'},\n {value: 'Birthday Tea', text: 'Birthday Tea'},\n {value: 'Fuding White Treasure Organic (ZW85)',\n text: 'Fuding White Treasure Organic (ZW85)'},\n {value: 'Almond with Almond Pieces', text: 'Almond with Almond Pieces'},\n {value: 'Malawi White Peony', text: 'Malawi White Peony'},\n {value: 'Keemun Black Tea – Grade 2', text: 'Keemun Black Tea – Grade 2'},\n {value: 'Cardamom Chai', text: 'Cardamom Chai'},\n {value: 'Fine Earl Grey (820)', text: 'Fine Earl Grey (820)'},\n {value: 'Green Tea Masala', text: 'Green Tea Masala'},\n {value: 'Green Tea Matcha Latte', text: 'Green Tea Matcha Latte'},\n {value: 'South Sea Magic', text: 'South Sea Magic'},\n {value: 'Yogi Spice with cocoa', text: 'Yogi Spice with cocoa'},\n {value: 'Welsh Hedgerow', text: 'Welsh Hedgerow'},\n {value: 'Linden Mint Tea', text: 'Linden Mint Tea'},\n {value: 'Marrakech Mint', text: 'Marrakech Mint'},\n {value: 'Frosty Garden', text: 'Frosty Garden'},\n {value: 'Tie-Guan-Yin Vintage Style (Taiwan)',\n text: 'Tie-Guan-Yin Vintage Style (Taiwan)'},\n {value: 'Decaf Chai', text: 'Decaf Chai'},\n {value: 'Taiwan Longevity Oolong', text: 'Taiwan Longevity Oolong'},\n {value: 'Java Malabar OP', text: 'Java Malabar OP'},\n {value: 'Golden Sunrise', text: 'Golden Sunrise'},\n {value: 'Watermelon Xylophone', text: 'Watermelon Xylophone'},\n {value: 'Loose leaf white teas', text: 'Loose leaf white teas'},\n {value: 'Hu Hong Black', text: 'Hu Hong Black'},\n {value: 'lapsang souchong', text: 'lapsang souchong'},\n {value: 'Roasted La Creme', text: 'Roasted La Creme'},\n {value: 'Classic Raw Kombucha', text: 'Classic Raw Kombucha'},\n {value: 'Sandman P.M.', text: 'Sandman P.M.'},\n {value: '2005 Pu-erh Tuo Cha Phoenix Old Tea Tree',\n text: '2005 Pu-erh Tuo Cha Phoenix Old Tea Tree'},\n {value: 'Refreshing Mint ReVitalize Tea',\n text: 'Refreshing Mint ReVitalize Tea'},\n {value: 'Blueberry Bush', text: 'Blueberry Bush'},\n {value: 'Emeralds in the Dew', text: 'Emeralds in the Dew'},\n {value: '2011 WuYi High Fired Old Bush ShuiXian',\n text: '2011 WuYi High Fired Old Bush ShuiXian'},\n {value: 'Bombay Chai Tea', text: 'Bombay Chai Tea'},\n {value: 'Cinnamon', text: 'Cinnamon'},\n {value: 'Black tea scented with rose',\n text: 'Black tea scented with rose'},\n {value: 'Rose', text: 'Rose'},\n {value: 'Mate Tiramisu', text: 'Mate Tiramisu'},\n {value: 'Fruits Noirs', text: 'Fruits Noirs'},\n {value: 'Plum Berry', text: 'Plum Berry'},\n {value: 'Premium Sencha', text: 'Premium Sencha'},\n {value: 'JavaVana Mate', text: 'JavaVana Mate'},\n {value: 'Song Zhong - 2011 Spring Fenghuang Oolong Tea',\n text: 'Song Zhong - 2011 Spring Fenghuang Oolong Tea'},\n {value: '100% Natural Green tea', text: '100% Natural Green tea'},\n {value: 'Kenya Black Tea', text: 'Kenya Black Tea'},\n {value: 'Long Jing', text: 'Long Jing'},\n {value: 'Red Dragon', text: 'Red Dragon'},\n {value: 'Lemon Youkou', text: 'Lemon Youkou'},\n {value: 'Young Maiden Jasmine', text: 'Young Maiden Jasmine'},\n {value: 'Margarets Hope Darjeeling', text: 'Margarets Hope Darjeeling'},\n {value: 'Northern Wilds', text: 'Northern Wilds'},\n {value: 'Jasmine Ancient Beauty', text: 'Jasmine Ancient Beauty'},\n {value: '2005 Sheng Yiwu Lucky Brand Bing Cha',\n text: '2005 Sheng Yiwu Lucky Brand Bing Cha'},\n {value: 'Tulsi India Chai', text: 'Tulsi India Chai'},\n {value: 'Oasis Mango White', text: 'Oasis Mango White'},\n {value: 'Oriental Beauty', text: 'Oriental Beauty'},\n {value: 'Formosa Pouchong (WenShan BaoZhong)',\n text: 'Formosa Pouchong (WenShan BaoZhong)'},\n {value: 'Kiwi Pear', text: 'Kiwi Pear'},\n {value: 'Singalila Estate SFTGFOP1 (TM40)',\n text: 'Singalila Estate SFTGFOP1 (TM40)'},\n {value: 'Bilbos Dark Side', text: 'Bilbos Dark Side'},\n {value: 'Imperial Shou Puerh Toucha', text: 'Imperial Shou Puerh Toucha'},\n {value: 'Yunnan Gold', text: 'Yunnan Gold'},\n {value: 'Toasted Rice Green', text: 'Toasted Rice Green'},\n {value: 'Lotus', text: 'Lotus'},\n {value: 'Oriental Beauty Premium Grade',\n text: 'Oriental Beauty Premium Grade'},\n {value: 'Brazilian Fruit', text: 'Brazilian Fruit'},\n {value: 'Geisha Beauty', text: 'Geisha Beauty'},\n {value: 'Winter', text: 'Winter'},\n {value: 'Cocoa Cardamom Seduction', text: 'Cocoa Cardamom Seduction'},\n {value: 'Vanilla Bean', text: 'Vanilla Bean'},\n {value: 'Coco-Lemon Thai', text: 'Coco-Lemon Thai'},\n {value: '8 Treasures of the Shaolin', text: '8 Treasures of the Shaolin'},\n {value: 'Darjeeling Margarets Hope T.F.G.F.O.P. Second Flush',\n text: 'Darjeeling Margarets Hope T.F.G.F.O.P. Second Flush'},\n {value: 'Golden Yunnan Black Full-Leaf',\n text: 'Golden Yunnan Black Full-Leaf'},\n {value: 'Matcha Sendo', text: 'Matcha Sendo'},\n {value: 'Earl Grey Green', text: 'Earl Grey Green'},\n {value: 'Hattialli Golden Lion Assam',\n text: 'Hattialli Golden Lion Assam'},\n {value: 'Citrus Mint', text: 'Citrus Mint'},\n {value: 'Tangerine Blossom', text: 'Tangerine Blossom'},\n {value: 'Xingyang Chrysanthemum Puer',\n text: 'Xingyang Chrysanthemum Puer'},\n {value: 'Partridges English Breakfast Loose Tea',\n text: 'Partridges English Breakfast Loose Tea'},\n {value: 'Reverend Oldfield Blend', text: 'Reverend Oldfield Blend'},\n {value: 'Noches de verano (Summer Nights)',\n text: 'Noches de verano (Summer Nights)'},\n {value: 'Malama', text: 'Malama'},\n {value: 'Arabis Tuareg', text: 'Arabis Tuareg'},\n {value: 'Sun Dried Loose Leaf White Tea',\n text: 'Sun Dried Loose Leaf White Tea'},\n {value: 'Fukamushi Sencha', text: 'Fukamushi Sencha'},\n {value: 'Irish Whiskey', text: 'Irish Whiskey'},\n {value: 'Ceylon - Kenilworth Estate', text: 'Ceylon - Kenilworth Estate'},\n {value: 'Mango Fruit Tea', text: 'Mango Fruit Tea'},\n {value: 'Green Yerba Mate', text: 'Green Yerba Mate'},\n {value: 'Tangerine Tango', text: 'Tangerine Tango'},\n {value: 'Jun Shan Yin Zhen Yellow Tea',\n text: 'Jun Shan Yin Zhen Yellow Tea'},\n {value: 'Phoenix Mountain Dan Cong Oolong',\n text: 'Phoenix Mountain Dan Cong Oolong'},\n {value: 'Moroccan Green with Mint', text: 'Moroccan Green with Mint'},\n {value: 'Berry Medley', text: 'Berry Medley'},\n {value: 'Arya Estate Ruby Second Flush Darjeeling',\n text: 'Arya Estate Ruby Second Flush Darjeeling'},\n {value: 'Organic Assam GBOP', text: 'Organic Assam GBOP'},\n {value: '2011 First Flush', text: '2011 First Flush'},\n {value: 'Dong Ding Ming Xiang (冻顶蜜香)',\n text: 'Dong Ding Ming Xiang (冻顶蜜香)'},\n {value: 'Rose Red Premium Black', text: 'Rose Red Premium Black'},\n {value: 'Gunpowder', text: 'Gunpowder'},\n {value: 'White Chocolate Cashew Black Tea',\n text: 'White Chocolate Cashew Black Tea'},\n {value: 'Raspberry Jasmine', text: 'Raspberry Jasmine'},\n {value: 'Cardamom Spice Tea', text: 'Cardamom Spice Tea'},\n {value: 'Snow Geisha', text: 'Snow Geisha'},\n {value: 'Pêché Mignon', text: 'Pêché Mignon'},\n {value: 'Moonlight White 2011 Pressed Cake',\n text: 'Moonlight White 2011 Pressed Cake'},\n {value: 'Matcha (Powdered)', text: 'Matcha (Powdered)'},\n {value: 'China Oolong Dong Ding', text: 'China Oolong Dong Ding'},\n {value: 'Xiaguan 1992 Sheng Tuocha', text: 'Xiaguan 1992 Sheng Tuocha'},\n {value: 'Amber Rose Darjeeling FTGFOP1 3rd Flush',\n text: 'Amber Rose Darjeeling FTGFOP1 3rd Flush'},\n {value: 'Lychee', text: 'Lychee'},\n {value: 'Organic Osthmanthus Oolong', text: 'Organic Osthmanthus Oolong'},\n {value: 'Franken Chai', text: 'Franken Chai'},\n {value: 'Pai Mu Tan Imperial ZW55', text: 'Pai Mu Tan Imperial ZW55'},\n {value: 'Darjeeling SFTGFOP Imperial Second Flush',\n text: 'Darjeeling SFTGFOP Imperial Second Flush'},\n {value: 'Glenburn Estate Darjeeling First Flush 2010',\n text: 'Glenburn Estate Darjeeling First Flush 2010'},\n {value: 'Chinese Honey Dew White', text: 'Chinese Honey Dew White'},\n {value: 'Kukicha Tea', text: 'Kukicha Tea'},\n {value: 'Organic Matcha Kaoru', text: 'Organic Matcha Kaoru'},\n {value: 'Kenia G.F.O.P. Tinderet', text: 'Kenia G.F.O.P. Tinderet'},\n {value: 'City Harvest Black', text: 'City Harvest Black'},\n {value: 'Decaffeinated Earl Grey with citrus fruits',\n text: 'Decaffeinated Earl Grey with citrus fruits'},\n {value: 'Its Afternoon Somewhere', text: 'Its Afternoon Somewhere'},\n {value: 'Coconut Green Tea', text: 'Coconut Green Tea'},\n {value: 'Hattiali sf sftgfop1', text: 'Hattiali sf sftgfop1'},\n {value: 'Smoky Russian Caravan', text: 'Smoky Russian Caravan'},\n {value: 'Frances Bissells Special Blend',\n text: 'Frances Bissells Special Blend'},\n {value: 'Huo Shan Huang Ya-Mt.Huo Yellow Sprout',\n text: 'Huo Shan Huang Ya-Mt.Huo Yellow Sprout'},\n {value: 'After Eight', text: 'After Eight'},\n {value: 'Étoile de thé', text: 'Étoile de thé'},\n {value: 'Bamboo Tea', text: 'Bamboo Tea'},\n {value: 'Blueberry Rooibos Caffeine-Free Herbal Blend',\n text: 'Blueberry Rooibos Caffeine-Free Herbal Blend'},\n {value: 'Praline Horizon', text: 'Praline Horizon'},\n {value: 'Golden Snail Yunnan Black Tea',\n text: 'Golden Snail Yunnan Black Tea'},\n {value: 'Rouge Sahara', text: 'Rouge Sahara'},\n {value: 'Ersatz Coffee', text: 'Ersatz Coffee'},\n {value: 'Plum Brandy Cheesecake', text: 'Plum Brandy Cheesecake'},\n {value: 'GingerLove', text: 'GingerLove'},\n {value: 'Marshmallow Treat Genmaicha',\n text: 'Marshmallow Treat Genmaicha'},\n {value: 'The Original Ceylon Tea Co. 1001 nights',\n text: 'The Original Ceylon Tea Co. 1001 nights'},\n {value: 'Toffee Chocolate Hazelnut', text: 'Toffee Chocolate Hazelnut'},\n {value: 'Japanese Mint', text: 'Japanese Mint'},\n {value: 'Bohea', text: 'Bohea'},\n {value: 'Spiced Chai', text: 'Spiced Chai'},\n {value: 'Yellow Gold Oolong (Huang Jin Gu Wu Long)',\n text: 'Yellow Gold Oolong (Huang Jin Gu Wu Long)'},\n {value: 'Adams Peak Rare White', text: 'Adams Peak Rare White'},\n {value: 'Holiday blend', text: 'Holiday blend'},\n {value: 'Cardamom (Chai Tea Mix)', text: 'Cardamom (Chai Tea Mix)'},\n {value: 'Citron Green', text: 'Citron Green'},\n {value: '‘Island Green’ Tea', text: '‘Island Green’ Tea'},\n {value: 'Bamboo Integrity', text: 'Bamboo Integrity'},\n {value: 'Herbal Unwind - Egyptian camomile with delicate apples',\n text: 'Herbal Unwind'},\n {value: 'Cacao Mint Black', text: 'Cacao Mint Black'},\n {value: 'Kenya TGFOP1 Tinderet', text: 'Kenya TGFOP1 Tinderet'},\n {value: '2008 Spring Bud Silver Tip Pu-erh Tea Brick',\n text: '2008 Spring Bud Silver Tip Pu-erh Tea Brick'},\n {value: 'Dragon Pearls', text: 'Dragon Pearls'},\n {value: 'Menthos Anyone?', text: 'Menthos Anyone?'},\n {value: 'Gingerade', text: 'Gingerade'},\n {value: 'Chamomile Vanilla Bean', text: 'Chamomile Vanilla Bean'},\n {value: 'Fresh Lemon Zest', text: 'Fresh Lemon Zest'},\n {value: 'Lemongreen', text: 'Lemongreen'},\n {value: 'Mate Chino', text: 'Mate Chino'},\n {value: 'Natural Hibiscus', text: 'Natural Hibiscus'},\n {value: 'Winey Keemun English Breakfast',\n text: 'Winey Keemun English Breakfast'},\n {value: 'Fig Leaf Tea', text: 'Fig Leaf Tea'},\n {value: 'Green Rose', text: 'Green Rose'},\n {value: 'Passionate Peach', text: 'Passionate Peach'},\n {value: 'Almond Cinnamon Biscotti Blend',\n text: 'Almond Cinnamon Biscotti Blend'},\n {value: 'Sense of Peace', text: 'Sense of Peace'},\n {value: 'Anniversary Breakfast Blend 2013',\n text: 'Anniversary Breakfast Blend 2013'},\n {value: 'Green Tea with Thai Flavors',\n text: 'Green Tea with Thai Flavors'},\n {value: 'Green Gunpowder', text: 'Green Gunpowder'},\n {value: 'Golden Sikkim', text: 'Golden Sikkim'},\n {value: 'Assam Rani', text: 'Assam Rani'},\n {value: 'Forest Medley Frutos del Bosque',\n text: 'Forest Medley Frutos del Bosque'},\n {value: 'Hojicha Toasted Bancha Leaf',\n text: 'Hojicha Toasted Bancha Leaf'},\n {value: '2006 Guan Zi Zai Sheng Puerh Meng Ku Bing Dao',\n text: '2006 Guan Zi Zai Sheng Puerh Meng Ku Bing Dao'},\n {value: 'Copper Knot Hongcha', text: 'Copper Knot Hongcha'},\n {value: 'Pumpkin Cream Rooibos', text: 'Pumpkin Cream Rooibos'},\n {value: 'Sans Complexe', text: 'Sans Complexe'},\n {value: 'Lingia STGFOP Darjeeling', text: 'Lingia STGFOP Darjeeling'},\n {value: 'Artichoke Tea', text: 'Artichoke Tea'},\n {value: 'Rum', text: 'Rum'},\n {value: 'Amazing Vanilla', text: 'Amazing Vanilla'},\n {value: 'Carnival', text: 'Carnival'},\n {value: 'Lemongrass Bamboo Leaf Tea', text: 'Lemongrass Bamboo Leaf Tea'},\n {value: 'Risheehat First Flush Darjeeling Spring 2010',\n text: 'Risheehat First Flush Darjeeling Spring 2010'},\n {value: 'TF42: Mango Indica', text: 'TF42: Mango Indica'},\n {value: 'Bolero', text: 'Bolero'},\n {value: 'Madagascar Vanilla Sunday Blend',\n text: 'Madagascar Vanilla Sunday Blend'},\n {value: 'Pu-erh and Blood Orange Blend (Organic Red TIger Tea)',\n text: 'Pu-erh and Blood Orange Blend (Organic Red TIger Tea)'},\n {value: 'High Mountain Alishan', text: 'High Mountain Alishan'},\n {value: 'Tian Mu Long Zhu', text: 'Tian Mu Long Zhu'},\n {value: 'Spicy Rasam', text: 'Spicy Rasam'},\n {value: 'Chamomile Medley', text: 'Chamomile Medley'},\n {value: 'Wuyi Mountain Big Red Robe', text: 'Wuyi Mountain Big Red Robe'},\n {value: 'White Peony — Bai Mu Dan', text: 'White Peony — Bai Mu Dan'},\n {value: 'Pu-erh Classic', text: 'Pu-erh Classic'},\n {value: 'Black Forest Fruit', text: 'Black Forest Fruit'},\n {value: 'Chocolate Cake', text: 'Chocolate Cake'},\n {value: 'Ali Shan', text: 'Ali Shan'},\n {value: 'Huang Shan Mao Feng', text: 'Huang Shan Mao Feng'},\n {value: 'Valkoinen Joulu - White Christmas',\n text: 'Valkoinen Joulu - White Christmas'},\n {value: 'Red Jade', text: 'Red Jade'},\n {value: 'Jasmine Superior', text: 'Jasmine Superior'},\n {value: 'Fireside Chai', text: 'Fireside Chai'},\n {value: 'Maple Pecan Tea', text: 'Maple Pecan Tea'},\n {value: 'Gyokuro (Blenders Series)', text: 'Gyokuro (Blenders Series)'},\n {value: 'A Vampire Lemonade Tea', text: 'A Vampire Lemonade Tea'},\n {value: 'DJ Darjeeling Avongrove First Flush 2012 ( Euphoria Supreme)',\n text: 'DJ Darjeeling Avongrove First Flush 2012 ( Euphoria Supreme)'},\n {value: 'Apple-Vanilla White Chai', text: 'Apple-Vanilla White Chai'},\n {value: 'Orange Peach', text: 'Orange Peach'},\n {value: 'Dumbara Green Curls (TC36)', text: 'Dumbara Green Curls (TC36)'},\n {value: '2010 Impression Hongyu Pu-erh Tea Cake',\n text: '2010 Impression Hongyu Pu-erh Tea Cake'},\n {value: 'Citrus Tea', text: 'Citrus Tea'},\n {value: 'kings oolong', text: 'kings oolong'},\n {value: 'Peach Bellini Blush (formerly Joie de Vivre)',\n text: 'Peach Bellini Blush (formerly Joie de Vivre)'},\n {value: 'Lavender Sencha', text: 'Lavender Sencha'},\n {value: 'White Christmas', text: 'White Christmas'},\n {value: '2011 MGH 1104 Ripe Pu-erh Tea Brick',\n text: '2011 MGH 1104 Ripe Pu-erh Tea Brick'},\n {value: 'Rooibos Vanilla', text: 'Rooibos Vanilla'},\n {value: 'Autumn Laoshan Green', text: 'Autumn Laoshan Green'},\n {value: 'Bamboo Leaf Green Tea (Zhu Ye Qing)',\n text: 'Bamboo Leaf Green Tea (Zhu Ye Qing)'},\n {value: 'Yue Guang Bai', text: 'Yue Guang Bai'},\n {value: 'Banana Daiquiri', text: 'Banana Daiquiri'},\n {value: 'Malty Assam', text: 'Malty Assam'},\n {value: 'Shui Xian (Water Sprite)', text: 'Shui Xian (Water Sprite)'},\n {value: '2006 TongQing Hao', text: '2006 TongQing Hao'},\n {value: 'Zheng Shan Xiao Zhong Smoked Wuyi Black',\n text: 'Zheng Shan Xiao Zhong Smoked Wuyi Black'},\n {value: 'Japanese Supersencha Kamakura',\n text: 'Japanese Supersencha Kamakura'},\n {value: 'Spring 2010 Bi Luo Chun', text: 'Spring 2010 Bi Luo Chun'},\n {value: 'Peachy Keen', text: 'Peachy Keen'},\n {value: 'Chocolate Berry Earl Grey', text: 'Chocolate Berry Earl Grey'},\n {value: 'English Breakfast with Pomegranate',\n text: 'English Breakfast with Pomegranate'},\n {value: 'Caramel Matcha', text: 'Caramel Matcha'},\n {value: 'Pure Ceylon Leaf Tea', text: 'Pure Ceylon Leaf Tea'},\n {value: 'Lemon Cream', text: 'Lemon Cream'},\n {value: 'Phuguri SFTGFOP 1st Flush 2010 Darjeeling',\n text: 'Phuguri SFTGFOP 1st Flush 2010 Darjeeling'},\n {value: 'Shi Feng Long Jing pre-Qing Ming',\n text: 'Shi Feng Long Jing pre-Qing Ming'},\n {value: 'Rooibush Cream Caramel', text: 'Rooibush Cream Caramel'},\n {value: 'Raspberry Gardens Green Tea',\n text: 'Raspberry Gardens Green Tea'},\n {value: 'Supreme Chrysanthemum', text: 'Supreme Chrysanthemum'},\n {value: 'Pineapple Upside Down Cake', text: 'Pineapple Upside Down Cake'},\n {value: 'Green Tea with Ginseng', text: 'Green Tea with Ginseng'},\n {value: 'Artichoke Green', text: 'Artichoke Green'},\n {value: 'Chance Combinations', text: 'Chance Combinations'},\n {value: 'Butter Rum', text: 'Butter Rum'},\n {value: 'Agua di Jamaica', text: 'Agua di Jamaica'},\n {value: 'Jalapeno Tea', text: 'Jalapeno Tea'},\n {value: 'Blue Unicorn', text: 'Blue Unicorn'},\n {value: 'Chocolate Chili Tea', text: 'Chocolate Chili Tea'},\n {value: 'Ginger Peach Ceylon', text: 'Ginger Peach Ceylon'},\n {value: 'Earl Grey Double Bergamot', text: 'Earl Grey Double Bergamot'},\n {value: 'Chai Bora Luxury Blend', text: 'Chai Bora Luxury Blend'},\n {value: 'Camels Breath Pu-erh Tuocha',\n text: 'Camels Breath Pu-erh Tuocha'},\n {value: 'Russian Country', text: 'Russian Country'},\n {value: 'Herbal Caramel Dream', text: 'Herbal Caramel Dream'},\n {value: 'Darjeeling Champagne', text: 'Darjeeling Champagne'},\n {value: 'Tokio', text: 'Tokio'},\n {value: 'Darjeeling Avongrove', text: 'Darjeeling Avongrove'},\n {value: 'Dragonwell Style Laoshan Green: Autumn Harvest',\n text: 'Dragonwell Style Laoshan Green: Autumn Harvest'},\n {value: 'PM Mantra Chai', text: 'PM Mantra Chai'},\n {value: 'Wild Sweet Orange', text: 'Wild Sweet Orange'},\n {value: 'Chai Latte', text: 'Chai Latte'},\n {value: 'Assorted Melange', text: 'Assorted Melange'},\n {value: 'Constant Comment Decaffeinated',\n text: 'Constant Comment Decaffeinated'},\n {value: 'Crème de Menthe', text: 'Crème de Menthe'},\n {value: 'Cha Yen Thai', text: 'Cha Yen Thai'},\n {value: 'Yellow Tea', text: 'Yellow Tea'},\n {value: 'Organic Apricot White Tea', text: 'Organic Apricot White Tea'},\n {value: 'Acai Mango Zinger', text: 'Acai Mango Zinger'},\n {value: 'Hillton First Flush Darjeeling estate specific 2009',\n text: 'Hillton First Flush Darjeeling estate specific 2009'},\n {value: 'Rooibos Peach Bloom', text: 'Rooibos Peach Bloom'},\n {value: '2009 Yunnan Sourcing Mang Fei Raw Pu-erh tea cake',\n text: '2009 Yunnan Sourcing Mang Fei Raw Pu-erh tea cake'},\n {value: 'Taishan Fo Mei (Buddhas Eyebrow)',\n text: 'Taishan Fo Mei (Buddhas Eyebrow)'},\n {value: 'Coco La Ven', text: 'Coco La Ven'},\n {value: 'Mieta fix / Polish herbal mint tea',\n text: 'Mieta fix / Polish herbal mint tea'},\n {value: 'White Peony Longevity Brows',\n text: 'White Peony Longevity Brows'},\n {value: 'Cozy Chamomile', text: 'Cozy Chamomile'},\n {value: 'Ceylon Coppers Cup', text: 'Ceylon Coppers Cup'},\n {value: 'Kama Sutra Chai', text: 'Kama Sutra Chai'},\n {value: 'jasmine raw mini tuo', text: 'jasmine raw mini tuo'},\n {value: 'Organic Black', text: 'Organic Black'},\n {value: 'Jackee Muntz', text: 'Jackee Muntz'},\n {value: 'Pomegranate Pizzaz', text: 'Pomegranate Pizzaz'},\n {value: 'Tian e yun jian', text: 'Tian e yun jian'},\n {value: 'Litchi', text: 'Litchi'},\n {value: 'Filiz', text: 'Filiz'},\n {value: 'Suenas del Tripico', text: 'Suenas del Tripico'},\n {value: 'Goji Raspberry', text: 'Goji Raspberry'},\n {value: 'Lifeboat Tea', text: 'Lifeboat Tea'},\n {value: 'Rooibos Vanilla Cream', text: 'Rooibos Vanilla Cream'},\n {value: 'China Oolong', text: 'China Oolong'},\n {value: '2013 Spring Lishan: Hua Gang Oolong - 梨山華崗烏龍',\n text: '2013 Spring Lishan: Hua Gang Oolong - 梨山華崗烏龍'},\n {value: 'Blueberry Zabaglione', text: 'Blueberry Zabaglione'},\n {value: 'NYC Breakfast', text: 'NYC Breakfast'},\n {value: 'Assam Breakfast', text: 'Assam Breakfast'},\n {value: 'Organic Green Tea with Pomegranate &amp; Cranberry',\n text: 'Organic Green Tea with Pomegranate Cranberry'},\n {value: 'Yun Cui (organic)', text: 'Yun Cui (organic)'},\n {value: 'Carol', text: 'Carol'},\n {value: 'Ceylon Tea - Orange Pekoe', text: 'Ceylon Tea - Orange Pekoe'},\n {value: 'Gingerbread Rooibos', text: 'Gingerbread Rooibos'},\n {value: 'Berry Pear-adise', text: 'Berry Pear-adise'},\n {value: 'Patagonia Bee', text: 'Patagonia Bee'},\n {value: 'Teh Asli', text: 'Teh Asli'},\n {value: 'Fine Champagne', text: 'Fine Champagne'},\n {value: 'Uji Gyokuro Kame-Jiru-Shi', text: 'Uji Gyokuro Kame-Jiru-Shi'},\n {value: 'Almond Sugar Cookie', text: 'Almond Sugar Cookie'},\n {value: 'Fengqing Golden Buds Ripened Pu-erh Cake Tea 2005',\n text: 'Fengqing Golden Buds Ripened Pu-erh Cake Tea 2005'},\n {value: 'Darjeeling Thurbo 1st Flush 2009',\n text: 'Darjeeling Thurbo 1st Flush 2009'},\n {value: 'Slimful Chocolate Decadence',\n text: 'Slimful Chocolate Decadence'},\n {value: 'Teas the Season', text: 'Teas the Season'},\n {value: 'London Fog Tea Latte (Now called Earl Grey Latte)',\n text: 'London Fog Tea Latte (Now called Earl Grey Latte)'},\n {value: 'Fire Ginseng', text: 'Fire Ginseng'},\n {value: 'Mo Gan Huang Ya (Yellow tea) Yellow Tea (Organic) 2009',\n text: 'Mo Gan Huang Ya (Yellow tea) Yellow Tea (Organic) 2009'},\n {value: 'Vanilla Apple White Organic Tea',\n text: 'Vanilla Apple White Organic Tea'},\n {value: 'Wuyi Jin Fo Reserve', text: 'Wuyi Jin Fo Reserve'},\n {value: 'Pear Au Chocolat', text: 'Pear Au Chocolat'},\n {value: 'Green Tea with Lemon', text: 'Green Tea with Lemon'},\n {value: 'Utopian Jewel/Key Lime Blend',\n text: 'Utopian Jewel/Key Lime Blend'},\n {value: 'Girlie Grey', text: 'Girlie Grey'},\n {value: 'English Estate Classic Tea', text: 'English Estate Classic Tea'},\n {value: 'Orange Dulce', text: 'Orange Dulce'},\n {value: 'Berrys Tea English Breakfast',\n text: 'Berrys Tea English Breakfast'},\n {value: 'Earl Grey Vanilla', text: 'Earl Grey Vanilla'},\n {value: 'Chai Green', text: 'Chai Green'},\n {value: 'Wuyi Ensemble', text: 'Wuyi Ensemble'},\n {value: 'Jade Oolong', text: 'Jade Oolong'},\n {value: 'OLD VERSION - Manistee Moonrise - v93 (2011-4/2014)',\n text: 'OLD VERSION - Manistee Moonrise'},\n {value: 'River Song Tea Blend', text: 'River Song Tea Blend'},\n {value: 'Makaibari 1st Flush Darjeeling',\n text: 'Makaibari 1st Flush Darjeeling'},\n {value: 'Genmaicha with Matcha', text: 'Genmaicha with Matcha'},\n {value: 'Organic Chinese Black Chai', text: 'Organic Chinese Black Chai'},\n {value: 'Wedgwood English Breakfast', text: 'Wedgwood English Breakfast'},\n {value: 'Cherry Cheesecake Genmaicha',\n text: 'Cherry Cheesecake Genmaicha'},\n {value: 'Organic Apple Red', text: 'Organic Apple Red'},\n {value: 'Temple Garden', text: 'Temple Garden'},\n {value: 'Green Tea Mint', text: 'Green Tea Mint'},\n {value: 'Sakura Blue', text: 'Sakura Blue'},\n {value: 'White Mangosteen and Peach', text: 'White Mangosteen and Peach'},\n {value: '1970s Pinlin Aged Oolong', text: '1970s Pinlin Aged Oolong'},\n {value: 'Uji Sencha Otsuusan', text: 'Uji Sencha Otsuusan'},\n {value: 'Roasted Pistachio Green Tea',\n text: 'Roasted Pistachio Green Tea'},\n {value: '2002 Mengma Sheng', text: '2002 Mengma Sheng'},\n {value: 'Coconut Macaroon Green Rooibos',\n text: 'Coconut Macaroon Green Rooibos'},\n {value: '500 Mile Chai (organic)', text: '500 Mile Chai (organic)'},\n {value: 'Fengqing Ripened Tribute Pu-erh Cake Tea 2007',\n text: 'Fengqing Ripened Tribute Pu-erh Cake Tea 2007'},\n {value: 'Organic Milk Oolong (Jin Xuan)',\n text: 'Organic Milk Oolong (Jin Xuan)'},\n {value: 'Gyokuro Black (organic)', text: 'Gyokuro Black (organic)'},\n {value: 'Gu Zhu Zi Sun - Spring 2012',\n text: 'Gu Zhu Zi Sun - Spring 2012'},\n {value: 'Wizards Grey', text: 'Wizards Grey'},\n {value: 'Shiki Matcha Powder', text: 'Shiki Matcha Powder'},\n {value: 'Richmond Blend', text: 'Richmond Blend'},\n {value: 'Iron Goddess (Tie Guan Yin)',\n text: 'Iron Goddess (Tie Guan Yin)'},\n {value: 'Marrakech Mint Tea', text: 'Marrakech Mint Tea'},\n {value: 'Notting Hill', text: 'Notting Hill'},\n {value: 'Sleeping Dragon', text: 'Sleeping Dragon'},\n {value: 'Earl Grey Special', text: 'Earl Grey Special'},\n {value: 'Goji Berries Fruit Tea', text: 'Goji Berries Fruit Tea'},\n {value: 'Vanilla Hazelnut', text: 'Vanilla Hazelnut'},\n {value: 'TieGuanYin(Iron Goddess Mercy)-Oolong',\n text: 'TieGuanYin(Iron Goddess Mercy)-Oolong'},\n {value: 'Fuji-Yama', text: 'Fuji-Yama'},\n {value: 'White Silver Tip Tea', text: 'White Silver Tip Tea'},\n {value: 'Rooibos Lemon Chiffon', text: 'Rooibos Lemon Chiffon'},\n {value: 'Organic Pure Rooibos', text: 'Organic Pure Rooibos'},\n {value: 'Sencha Fuka-midori', text: 'Sencha Fuka-midori'},\n {value: 'Organic Se Chung Oolong', text: 'Organic Se Chung Oolong'},\n {value: 'Candy Cane Black', text: 'Candy Cane Black'},\n {value: 'Daintree', text: 'Daintree'},\n {value: 'Peeta', text: 'Peeta'},\n {value: 'Jungpana DJ9 Sample', text: 'Jungpana DJ9 Sample'},\n {value: 'Buddhist Tea (Fo Cha)', text: 'Buddhist Tea (Fo Cha)'},\n {value: 'Assam Mokalbari', text: 'Assam Mokalbari'},\n {value: 'Seeyok 2nd Flush 2010 [Out of Stock]',\n text: 'Seeyok 2nd Flush 2010 [Out of Stock]'},\n {value: 'Ripened Aged Loose Pu-erh Tea',\n text: 'Ripened Aged Loose Pu-erh Tea'},\n {value: 'Jasmine Silver Needles (organic)',\n text: 'Jasmine Silver Needles (organic)'},\n {value: 'Matcha - Ceremonial Grade', text: 'Matcha - Ceremonial Grade'},\n {value: 'My Friend', text: 'My Friend'},\n {value: 'Palace Earl Grey', text: 'Palace Earl Grey'},\n {value: 'English Breakfast Tea by Bigelow',\n text: 'English Breakfast Tea by Bigelow'},\n {value: 'Golden Monkey', text: 'Golden Monkey'},\n {value: 'Wild Blueberry', text: 'Wild Blueberry'},\n {value: 'Martinique', text: 'Martinique'},\n {value: 'Dreamtime Instant Tea', text: 'Dreamtime Instant Tea'},\n {value: 'Huo Shan Huang Ya', text: 'Huo Shan Huang Ya'},\n {value: 'Herbal Holiday', text: 'Herbal Holiday'},\n {value: 'Cassis &amp; Blueberry', text: 'Cassis &amp; Blueberry'},\n {value: '2007 Xiaguan Golden Ribbon 100 g Sheng Pu-Erh Tea Tuo Cha',\n text: '2007 Xiaguan Golden Ribbon'},\n {value: 'Zingiber Ginger Coconut', text: 'Zingiber Ginger Coconut'},\n {value: 'Belgian Chocolate Rooibos', text: 'Belgian Chocolate Rooibos'},\n {value: 'Imperial Dark - Bu Lang Gong Ting 2009',\n text: 'Imperial Dark - Bu Lang Gong Ting 2009'},\n {value: 'Guo Lu First Grade', text: 'Guo Lu First Grade'},\n {value: '2013 Yi Shan Lao Zhai Gu Shu Raw Pu-erh tea of Jinggu',\n text: '2013 Yi Shan Lao Zhai Gu Shu Raw Pu-erh tea of Jinggu'},\n {value: 'Jade Oolong (Lugu Taiwan)', text: 'Jade Oolong (Lugu Taiwan)'},\n {value: 'Better Off Red - Rooibos with Vanilla-Citrus Blush',\n text: 'Better Off Red - Rooibos with Vanilla-Citrus Blush'},\n {value: 'Framboise', text: 'Framboise'},\n {value: 'Organic Hangzhou Tian Mu Qing Ding Green Tea',\n text: 'Organic Hangzhou Tian Mu Qing Ding Green Tea'},\n {value: 'Darjeleeing White Tips', text: 'Darjeleeing White Tips'},\n {value: 'Banaspaty Estate TGBOP Organic (TA17)',\n text: 'Banaspaty Estate TGBOP Organic (TA17)'},\n {value: 'Fu Shou Mei Feng Qing Black Tea of Yunnan * Spring 2017',\n text: 'Fu Shou Mei Feng Qing Black Tea of Yunnan * Spring 2017'},\n {value: 'Monkey Picked Oolong', text: 'Monkey Picked Oolong'},\n {value: 'Biodynamic Darjeeling', text: 'Biodynamic Darjeeling'},\n {value: 'Alishan High Mountain Oolong',\n text: 'Alishan High Mountain Oolong'},\n {value: 'Nerada Blend Leaf tea', text: 'Nerada Blend Leaf tea'},\n {value: 'Alishan First-Pluck Winter 2008',\n text: 'Alishan First-Pluck Winter 2008'},\n {value: 'Organic Midnight Dreams', text: 'Organic Midnight Dreams'},\n {value: 'Oolong Tea', text: 'Oolong Tea'},\n {value: 'Sweet Almond (TF07)', text: 'Sweet Almond (TF07)'},\n {value: 'Summer Romance', text: 'Summer Romance'},\n {value: 'Pu-erh (Imperial Republic)', text: 'Pu-erh (Imperial Republic)'},\n {value: '2008 Panchen Lama Mushroom Tuo cha',\n text: '2008 Panchen Lama Mushroom Tuo cha'},\n {value: 'Nine Blend Black Dragon', text: 'Nine Blend Black Dragon'},\n {value: 'Raspberry Soiree', text: 'Raspberry Soiree'},\n {value: 'Blueberry Herbal Tea', text: 'Blueberry Herbal Tea'},\n {value: 'Staring at the Sea', text: 'Staring at the Sea'},\n {value: 'Ceylon OP', text: 'Ceylon OP'},\n {value: 'Bananas Foster', text: 'Bananas Foster'},\n {value: 'Gao Shan Oolong', text: 'Gao Shan Oolong'},\n {value: 'Organic Jasmine Pearls Green Tea',\n text: 'Organic Jasmine Pearls Green Tea'},\n {value: 'Original Redbush Tea', text: 'Original Redbush Tea'},\n {value: 'Giddapahar SFTGFOP 1 CH SPT- 1st Flush',\n text: 'Giddapahar SFTGFOP 1 CH SPT- 1st Flush'},\n {value: 'Perfectly Pear White Tea', text: 'Perfectly Pear White Tea'},\n {value: 'Summer Lemon', text: 'Summer Lemon'},\n {value: 'Chocolate &amp; Strawberry Puer',\n text: 'Chocolate &amp; Strawberry Puer'},\n {value: 'Gruner Tee Vanille', text: 'Gruner Tee Vanille'},\n {value: 'Relax', text: 'Relax'},\n {value: 'Mad Tea Party Blend', text: 'Mad Tea Party Blend'},\n {value: 'Bai Ya Qi Lan Oolong', text: 'Bai Ya Qi Lan Oolong'},\n {value: 'Tangerine Vanilla Oolong', text: 'Tangerine Vanilla Oolong'},\n {value: 'Keemun Superior', text: 'Keemun Superior'},\n {value: 'Ginger Sparkle', text: 'Ginger Sparkle'},\n {value: 'Large Leaf from Old Trees - Jing Gu Da Ye',\n text: 'Large Leaf from Old Trees - Jing Gu Da Ye'},\n {value: 'Australian Lemon Myrtle', text: 'Australian Lemon Myrtle'},\n {value: 'The Earls Garden', text: 'The Earls Garden'},\n {value: 'Japanese Rose Sencha Green Tea',\n text: 'Japanese Rose Sencha Green Tea'},\n {value: 'Lemon Ginger Herbal Tea', text: 'Lemon Ginger Herbal Tea'},\n {value: 'Yunnan Select', text: 'Yunnan Select'},\n {value: 'Tizona Tea - Signature Blend',\n text: 'Tizona Tea - Signature Blend'},\n {value: 'Apple Crumble', text: 'Apple Crumble'},\n {value: 'Chai of Zanzibar (Spice Islands Tea)',\n text: 'Chai of Zanzibar (Spice Islands Tea)'},\n {value: 'Youthberry', text: 'Youthberry'},\n {value: 'Earl Grey Black Tea', text: 'Earl Grey Black Tea'},\n {value: 'Pumpkin Cheesecake', text: 'Pumpkin Cheesecake'},\n {value: 'China Yunnan Matai Old Tree Black Tea',\n text: 'China Yunnan Matai Old Tree Black Tea'},\n {value: 'Vanilla and Cinnamon', text: 'Vanilla and Cinnamon'},\n {value: 'Smaug Tea', text: 'Smaug Tea'},\n {value: 'Almond Biscotti', text: 'Almond Biscotti'},\n {value: 'Mist Valley SFTGFOP1', text: 'Mist Valley SFTGFOP1'},\n {value: 'Bulang Gong Ting Shu 2009', text: 'Bulang Gong Ting Shu 2009'},\n {value: 'Apricot Caramel Torte', text: 'Apricot Caramel Torte'},\n {value: 'Wild Cherry Rooibos', text: 'Wild Cherry Rooibos'},\n {value: 'Precious Monkeys Pick Ti Kuan Yin 1136/110066',\n text: 'Precious Monkeys Pick Ti Kuan Yin 1136/110066'},\n {value: 'Mountain Berry (aka Northern Blue)',\n text: 'Mountain Berry (aka Northern Blue)'},\n {value: 'Matcha iri Genmaicha', text: 'Matcha iri Genmaicha'},\n {value: 'Vanilla Ceylon', text: 'Vanilla Ceylon'},\n {value: 'Pai Mu Tan Stockholm Blend', text: 'Pai Mu Tan Stockholm Blend'},\n {value: 'Ceylon Silver Tip White Tea',\n text: 'Ceylon Silver Tip White Tea'},\n {value: 'The Black Lotus', text: 'The Black Lotus'},\n {value: 'ZO97 Feng Huang Dan Cong', text: 'ZO97 Feng Huang Dan Cong'},\n {value: 'High Mountain Nilgiri', text: 'High Mountain Nilgiri'},\n {value: 'Mocha Me a Tea', text: 'Mocha Me a Tea'},\n {value: 'Vanilla Rooibos Parfait', text: 'Vanilla Rooibos Parfait'},\n {value: 'Orange Pekoe', text: 'Orange Pekoe'},\n {value: 'Raspberry', text: 'Raspberry'},\n {value: 'Chun Hao Jasmine Tea', text: 'Chun Hao Jasmine Tea'},\n {value: 'Singbulli Silk First Flush Garden Darjeeling.',\n text: 'Singbulli Silk First Flush Garden Darjeeling.'},\n {value: 'Egipcio (Egyptian)', text: 'Egipcio (Egyptian)'},\n {value: 'Honey Hon Cha', text: 'Honey Hon Cha'},\n {value: 'Assam', text: 'Assam'},\n {value: 'Lotus Tea', text: 'Lotus Tea'},\n {value: 'Spiced Chai Decaffeinated', text: 'Spiced Chai Decaffeinated'},\n {value: 'Coconut Carrot Cashew', text: 'Coconut Carrot Cashew'},\n {value: 'Imperial Pearl', text: 'Imperial Pearl'},\n {value: 'Korakundah Organic FOP Nilgiri Green Decaf',\n text: 'Korakundah Organic FOP Nilgiri Green Decaf'},\n {value: 'Orange Market Spice', text: 'Orange Market Spice'},\n {value: 'Banana Walnut', text: 'Banana Walnut'},\n {value: 'Caramel Blended Tea', text: 'Caramel Blended Tea'},\n {value: 'Gyokuro Super Premium', text: 'Gyokuro Super Premium'},\n {value: 'Aromatic Oolong Tea', text: 'Aromatic Oolong Tea'},\n {value: 'Iced Passion Tea', text: 'Iced Passion Tea'},\n {value: 'Organic Silver Needle', text: 'Organic Silver Needle'},\n {value: 'No. 1 Tippy Orthodox GFOP Darjeeling (TD50)',\n text: 'No. 1 Tippy Orthodox GFOP Darjeeling (TD50)'},\n {value: 'Yongchun Fo Shou (Bergamot) Oolong Superior Grade',\n text: 'Yongchun Fo Shou (Bergamot) Oolong Superior Grade'},\n {value: 'Chocolate Cream with Cocoa Pieces',\n text: 'Chocolate Cream with Cocoa Pieces'},\n {value: 'Black Cherry Berry', text: 'Black Cherry Berry'},\n {value: 'Chundavurrai Whole Leaf', text: 'Chundavurrai Whole Leaf'},\n {value: 'Toasted Nut Brulee Oolong', text: 'Toasted Nut Brulee Oolong'},\n {value: 'Darjeeling', text: 'Darjeeling'},\n {value: 'Youthberry White Tea', text: 'Youthberry White Tea'},\n {value: 'Green Tea with Coconut Ginger and Vanilla',\n text: 'Green Tea with Coconut Ginger and Vanilla'},\n {value: 'China Keemun Finest Chuen Cha',\n text: 'China Keemun Finest Chuen Cha'},\n {value: 'Citrus Spice Green', text: 'Citrus Spice Green'},\n {value: 'Coconut Bongo', text: 'Coconut Bongo'},\n {value: 'Lemon Grass', text: 'Lemon Grass'},\n {value: 'Italian Chamomile', text: 'Italian Chamomile'},\n {value: 'Citrus Punch', text: 'Citrus Punch'},\n {value: 'Green Tea With Brown Rice', text: 'Green Tea With Brown Rice'},\n {value: 'Heritage D’Istanbul', text: 'Heritage D’Istanbul'},\n {value: '2012 First Flush Castleton SFTGFOP1',\n text: '2012 First Flush Castleton SFTGFOP1'},\n {value: 'Formosa Fancy Oolong Organic',\n text: 'Formosa Fancy Oolong Organic'},\n {value: 'Rooibush k.b.a', text: 'Rooibush k.b.a'},\n {value: 'Roasted Almonds', text: 'Roasted Almonds'},\n {value: 'Asian Pear &amp; Ginger', text: 'Asian Pear &amp; Ginger'},\n {value: 'Tropical Blend Black Tea (TE66)',\n text: 'Tropical Blend Black Tea (TE66)'},\n {value: 'The Burglar Brew / Bilbo Brew',\n text: 'The Burglar Brew / Bilbo Brew'},\n {value: 'Sea Buckthorn Green Tea', text: 'Sea Buckthorn Green Tea'},\n {value: 'India Assam', text: 'India Assam'},\n {value: 'No. 47 Bungalow', text: 'No. 47 Bungalow'},\n {value: 'Maple Flavored Black', text: 'Maple Flavored Black'},\n {value: 'Darjeeling Loose', text: 'Darjeeling Loose'},\n {value: 'Hojicha', text: 'Hojicha'},\n {value: 'Ceylon', text: 'Ceylon'},\n {value: 'Organic Korean Jungjak Green Tea',\n text: 'Organic Korean Jungjak Green Tea'},\n {value: 'Black Chai', text: 'Black Chai'},\n {value: 'Monks Grenadine Blend', text: 'Monks Grenadine Blend'},\n {value: 'Mary Margaret Blend', text: 'Mary Margaret Blend'},\n {value: 'Taiwan Shan Lin Xi Oolong Tea',\n text: 'Taiwan Shan Lin Xi Oolong Tea'},\n {value: 'Herbal Sampler', text: 'Herbal Sampler'},\n {value: 'Xue Ya Ballad', text: 'Xue Ya Ballad'},\n {value: 'Master Bis Top Shelf Lapsang',\n text: 'Master Bis Top Shelf Lapsang'},\n {value: 'Strawberry Green Tea', text: 'Strawberry Green Tea'},\n {value: 'Lemon Blossom', text: 'Lemon Blossom'},\n {value: 'Rain Flower', text: 'Rain Flower'},\n {value: 'Ginger Pear Oolong', text: 'Ginger Pear Oolong'},\n {value: 'Wu Liang Mountain Xue Dian Mei Lan Yunnan Green Tea',\n text: 'Wu Liang Mountain Xue Dian Mei Lan Yunnan Green Tea'},\n {value: 'Jeong Seon', text: 'Jeong Seon'},\n {value: 'Rooibos Chai Tea', text: 'Rooibos Chai Tea'},\n {value: 'Buddhas Tears', text: 'Buddhas Tears'},\n {value: 'Sugar Plum', text: 'Sugar Plum'},\n {value: '2012 Spring Imperial Jin Mao Hou (Golden Monkey) Black Tea',\n text: '2012 Spring Imperial Jin Mao Hou (Golden Monkey) Black Tea'},\n {value: 'Organic Darjeeling Estate', text: 'Organic Darjeeling Estate'},\n {value: '2010 Menghai Spring of Menghai Raw Pu-erh tea * 357 grams',\n text: '2010 Menghai Spring of Menghai'},\n {value: 'Lychee Red', text: 'Lychee Red'},\n {value: 'Organic Assam', text: 'Organic Assam'},\n {value: 'Indian Chai', text: 'Indian Chai'},\n {value: 'Dragon Power', text: 'Dragon Power'},\n {value: 'Lemon Ginger Echinacea', text: 'Lemon Ginger Echinacea'},\n {value: 'Fukamushi-Sencha Yame', text: 'Fukamushi-Sencha Yame'},\n {value: 'Blueberry Green', text: 'Blueberry Green'},\n {value: 'Darjeeling Singbulli SFTGFOP1 2nd Flush Silver Tip',\n text: 'Darjeeling Singbulli SFTGFOP1 2nd Flush Silver Tip'},\n {value: 'Pineapple Angel Food Cake', text: 'Pineapple Angel Food Cake'},\n {value: 'ali shan zin hsuan', text: 'ali shan zin hsuan'},\n {value: '2007 Premium Ripe Pu-erh Brick Tea (勐库乔木老树熟砖)',\n text: '2007 Premium Ripe Pu-erh Brick Tea (勐库乔木老树熟砖)'},\n {value: 'Ye Sheng Wild White', text: 'Ye Sheng Wild White'},\n {value: 'South Sea Magic Tea', text: 'South Sea Magic Tea'},\n {value: 'Organic Peppermint', text: 'Organic Peppermint'},\n {value: 'Organic English Breakfast', text: 'Organic English Breakfast'},\n {value: '970 Oriental Moon', text: '970 Oriental Moon'},\n {value: 'Virgin White Tea', text: 'Virgin White Tea'},\n {value: 'Sarnia Plaiderie Estate BOP1 (TC54)',\n text: 'Sarnia Plaiderie Estate BOP1 (TC54)'},\n {value: 'Arbodr Pu-erh Tea CreamSunriseInstant Ripe Puer Tea Extracts Reduce Stress20g',\n text: 'Arbodr Pu-erh Tea Cream Sunrise'},\n {value: 'Mim Darjeeling TGFOP1', text: 'Mim Darjeeling TGFOP1'},\n {value: 'India Breakfast Tulsi Tea', text: 'India Breakfast Tulsi Tea'},\n {value: 'Tea &amp; Toast Tea', text: 'Tea &amp; Toast Tea'},\n {value: 'Mango Green Tea', text: 'Mango Green Tea'},\n {value: 'White Pomegranate', text: 'White Pomegranate'},\n {value: 'Jack Frost', text: 'Jack Frost'},\n {value: 'Bavarian Cream Matcha', text: 'Bavarian Cream Matcha'},\n {value: 'Original Blend', text: 'Original Blend'},\n {value: 'Himalayan Orange 2010 [Out of stock]',\n text: 'Himalayan Orange 2010 [Out of stock]'},\n {value: 'Rooibos Orange Vanilla Creme',\n text: 'Rooibos Orange Vanilla Creme'},\n {value: 'Fruit Punch', text: 'Fruit Punch'},\n {value: 'Zheng Shan Xiao Zhong', text: 'Zheng Shan Xiao Zhong'},\n {value: 'Ceylon Lovers Leap Broken Orange Pekoe',\n text: 'Ceylon Lovers Leap Broken Orange Pekoe'},\n {value: 'Vanilla Pineapple White', text: 'Vanilla Pineapple White'},\n {value: 'Holiday Tea', text: 'Holiday Tea'},\n {value: 'Mate Lemon', text: 'Mate Lemon'},\n {value: 'Kombucha Brooklyn - Red Ginger',\n text: 'Kombucha Brooklyn - Red Ginger'},\n {value: 'Sangria', text: 'Sangria'},\n {value: '1997 Heng Li Chang Bulang', text: '1997 Heng Li Chang Bulang'},\n {value: 'Sencha Pinnacle', text: 'Sencha Pinnacle'},\n {value: 'Black River Mountain Viet Nam border 1997',\n text: 'Black River Mountain Viet Nam border 1997'},\n {value: 'Stay in and Drink Tea', text: 'Stay in and Drink Tea'},\n {value: 'Paris', text: 'Paris'},\n {value: '2007 Menghai Dayi Hou Pu Ripe Bing',\n text: '2007 Menghai Dayi Hou Pu Ripe Bing'},\n {value: 'milk oolong', text: 'milk oolong'},\n {value: 'Organic Kamaaina Hawaiian Summer Oolong',\n text: 'Organic Kamaaina Hawaiian Summer Oolong'},\n {value: 'Pure White Tea', text: 'Pure White Tea'},\n {value: 'Rainbow Rooibos', text: 'Rainbow Rooibos'},\n {value: 'Organic Jasmine Green Tea', text: 'Organic Jasmine Green Tea'},\n {value: 'Krauter-mischung', text: 'Krauter-mischung'},\n {value: 'Grey Duchess', text: 'Grey Duchess'},\n {value: 'Honey Tea', text: 'Honey Tea'},\n {value: 'Lady Londonderry', text: 'Lady Londonderry'},\n {value: 'Jims Caravan', text: 'Jims Caravan'},\n {value: 'Double Knit Blend', text: 'Double Knit Blend'},\n {value: 'Adawatte Estate Ceylon Pekoe',\n text: 'Adawatte Estate Ceylon Pekoe'},\n {value: 'Mugicha - Iced Barley Tea Bags',\n text: 'Mugicha - Iced Barley Tea Bags'},\n {value: 'Relaxed Mind', text: 'Relaxed Mind'},\n {value: 'Teh Tarik', text: 'Teh Tarik'},\n {value: 'Earl Grey Organique', text: 'Earl Grey Organique'},\n {value: 'DZS Lung Jing', text: 'DZS Lung Jing'},\n {value: 'Thistle Tea', text: 'Thistle Tea'},\n {value: 'French Breakfast', text: 'French Breakfast'},\n {value: '2010 WuYi 3 Stamps Old Bush ShuiXian',\n text: '2010 WuYi 3 Stamps Old Bush ShuiXian'},\n {value: 'Chrysanthemum Nest', text: 'Chrysanthemum Nest'},\n {value: 'Ceylon Deluxe BOP', text: 'Ceylon Deluxe BOP'},\n {value: 'Organic Vanilla Blossoming Black Tea',\n text: 'Organic Vanilla Blossoming Black Tea'},\n {value: 'Royal Gold Yunnan Needle', text: 'Royal Gold Yunnan Needle'},\n {value: 'Pu Erh', text: 'Pu Erh'},\n {value: 'Chamomile Lavender', text: 'Chamomile Lavender'},\n {value: 'Jim Johns Blend', text: 'Jim Johns Blend'},\n {value: 'Grumpy Dinosaur', text: 'Grumpy Dinosaur'},\n {value: 'Gingerbread Orange', text: 'Gingerbread Orange'},\n {value: 'China Rose-Tea', text: 'China Rose-Tea'},\n {value: 'Mint and Honey Green Tea', text: 'Mint and Honey Green Tea'},\n {value: 'Library Blend', text: 'Library Blend'},\n {value: 'Organic Orange and Coconut', text: 'Organic Orange and Coconut'},\n {value: 'Gingerbread Cookie', text: 'Gingerbread Cookie'},\n {value: 'Madagascar Vanilla', text: 'Madagascar Vanilla'},\n {value: 'The Steeper', text: 'The Steeper'},\n {value: 'Magnolia Puerh', text: 'Magnolia Puerh'},\n {value: 'Pappys Sassafras Tea Concentrate',\n text: 'Pappys Sassafras Tea Concentrate'},\n {value: 'Vanilla Caramel Truffle', text: 'Vanilla Caramel Truffle'},\n {value: 'Get Some Zzzs - No. 5 (Wellness Collection)',\n text: 'Get Some Zzzs - No. 5 (Wellness Collection)'},\n {value: 'Kalilove', text: 'Kalilove'},\n {value: 'Cream', text: 'Cream'},\n {value: 'Arabische Nacht / Arabian Night - 901',\n text: 'Arabische Nacht / Arabian Night - 901'},\n {value: 'Pu-erh', text: 'Pu-erh'},\n {value: 'Ronnefeldt Teavelope® Verbena Herbal Tisane',\n text: 'Ronnefeldt Teavelope® Verbena Herbal Tisane'},\n {value: 'China Qi Feng Magnolia', text: 'China Qi Feng Magnolia'},\n {value: 'Victory Tea', text: 'Victory Tea'},\n {value: 'Ginseng Oolong', text: 'Ginseng Oolong'},\n {value: 'Go Go Goji', text: 'Go Go Goji'},\n {value: 'Spice Imperial', text: 'Spice Imperial'},\n {value: 'Apricot Orange Vanilla Wonder',\n text: 'Apricot Orange Vanilla Wonder'},\n {value: 'Tangerine Ginger', text: 'Tangerine Ginger'},\n {value: 'Organic Green Needles', text: 'Organic Green Needles'},\n {value: 'Organic Roasted Dandelion Root',\n text: 'Organic Roasted Dandelion Root'},\n {value: 'Maharaja Reserve', text: 'Maharaja Reserve'},\n {value: 'Organic Emerald Lily (Fair Trade)',\n text: 'Organic Emerald Lily (Fair Trade)'},\n {value: 'Orange Chocolate Green Tea', text: 'Orange Chocolate Green Tea'},\n {value: 'Lestrade Blend', text: 'Lestrade Blend'},\n {value: 'Green Tea with Pomegranate', text: 'Green Tea with Pomegranate'},\n {value: 'Pinapple Pizzazz', text: 'Pinapple Pizzazz'},\n {value: 'Darjeeling Thurbo Tippy FTGFOP1 F. F. CL',\n text: 'Darjeeling Thurbo Tippy FTGFOP1 F. F. CL'},\n {value: 'Feng Huang Dan Cong', text: 'Feng Huang Dan Cong'},\n {value: 'Gyokuro Kin', text: 'Gyokuro Kin'},\n {value: 'Bedtime Chai', text: 'Bedtime Chai'},\n {value: 'Ginger Peach Darjeeling', text: 'Ginger Peach Darjeeling'},\n {value: 'Dragon Bone', text: 'Dragon Bone'},\n {value: 'White Nectar Osmanthus Spring',\n text: 'White Nectar Osmanthus Spring'},\n {value: 'Dong Ding Autumn 2009', text: 'Dong Ding Autumn 2009'},\n {value: 'Rosy Earl Grey', text: 'Rosy Earl Grey'},\n {value: 'Pure Chai (organic)', text: 'Pure Chai (organic)'},\n {value: 'Kuradashi Gyokuro Premium', text: 'Kuradashi Gyokuro Premium'},\n {value: 'Berry Up', text: 'Berry Up'},\n {value: 'Puerh', text: 'Puerh'},\n {value: 'Organic Uji Gyokuro Yabukita',\n text: 'Organic Uji Gyokuro Yabukita'},\n {value: 'Detox Blend', text: 'Detox Blend'},\n {value: '2006 Menghai Dayi Wei Zui Yan Superb Taste',\n text: '2006 Menghai Dayi Wei Zui Yan Superb Taste'},\n {value: 'Black Oothu', text: 'Black Oothu'},\n {value: 'Apricot Chocolate', text: 'Apricot Chocolate'},\n {value: 'Silk Road', text: 'Silk Road'},\n {value: 'Sencha Sakura', text: 'Sencha Sakura'},\n {value: 'Rose Mojito (formerly Amore)',\n text: 'Rose Mojito (formerly Amore)'},\n {value: 'Sencha Hosen', text: 'Sencha Hosen'},\n {value: 'spring jasmine', text: 'spring jasmine'},\n {value: 'Ginger Pu Erh', text: 'Ginger Pu Erh'},\n {value: 'Princess Earl Grey', text: 'Princess Earl Grey'},\n {value: 'Timmys 1Up Jasmine Green', text: 'Timmys 1Up Jasmine Green'},\n {value: '2010 Winter Ali Shan High Mountain Oolong - 1500m Elev.',\n text: '2010 Winter Ali Shan High Mountain Oolong - 1500m Elev.'},\n {value: 'Passage du Desir', text: 'Passage du Desir'},\n {value: 'Dark Roast Anxi Tieguanyin', text: 'Dark Roast Anxi Tieguanyin'},\n {value: 'Darjeeling Thurbo Garden (2011 2nd Flush)',\n text: 'Darjeeling Thurbo Garden (2011 2nd Flush)'},\n {value: 'Orange Blossom', text: 'Orange Blossom'},\n {value: 'Temptation Summer Fruits', text: 'Temptation Summer Fruits'},\n {value: 'Champagne Rosé', text: 'Champagne Rosé'},\n {value: 'Finest Darjeeling', text: 'Finest Darjeeling'},\n {value: 'Organic Blueberry Green Tea',\n text: 'Organic Blueberry Green Tea'},\n {value: 'Original Chai', text: 'Original Chai'},\n {value: 'San Jose', text: 'San Jose'},\n {value: 'Gyokuro Jade Dew', text: 'Gyokuro Jade Dew'},\n {value: 'Red Label', text: 'Red Label'},\n {value: 'English Breakfast Fair Trade',\n text: 'English Breakfast Fair Trade'},\n {value: 'Pouchkine', text: 'Pouchkine'},\n {value: 'Berry Rooibos', text: 'Berry Rooibos'},\n {value: 'Sleepy Time', text: 'Sleepy Time'},\n {value: 'Japanese Black Tea - Osamu', text: 'Japanese Black Tea - Osamu'},\n {value: 'Blackout', text: 'Blackout'},\n {value: 'Golden Blend', text: 'Golden Blend'},\n {value: 'White Chocolate Mousse Café',\n text: 'White Chocolate Mousse Café'},\n {value: 'Lao Shu Cha - Tea of Old Treas',\n text: 'Lao Shu Cha - Tea of Old Treas'},\n {value: 'Authentic Green Tea with White Tea',\n text: 'Authentic Green Tea with White Tea'},\n {value: 'Taiwan High Mountain Oolong',\n text: 'Taiwan High Mountain Oolong'},\n {value: 'Momo', text: 'Momo'},\n {value: 'Imperial Pu Erh', text: 'Imperial Pu Erh'},\n {value: 'Iced Tea Blend', text: 'Iced Tea Blend'},\n {value: 'White Tea Rose Mélange', text: 'White Tea Rose Mélange'},\n {value: 'Irish Breakfast Decaffeinated',\n text: 'Irish Breakfast Decaffeinated'},\n {value: 'Jasmine Pearl', text: 'Jasmine Pearl'},\n {value: 'Pearl of Fruits', text: 'Pearl of Fruits'},\n {value: 'Spiced Chocolate (Chai)', text: 'Spiced Chocolate (Chai)'},\n {value: 'Spicy Chocolate', text: 'Spicy Chocolate'},\n {value: 'Yummy Chai', text: 'Yummy Chai'},\n {value: 'Rooibos Berry', text: 'Rooibos Berry'},\n {value: 'China Green Tea with many Jasmine blossoms',\n text: 'China Green Tea with many Jasmine blossoms'},\n {value: 'Red Rooibos with Sceletium', text: 'Red Rooibos with Sceletium'},\n {value: 'Lemongrass &amp; Ginger', text: 'Lemongrass &amp; Ginger'},\n {value: 'Citrus Spice Chamomile', text: 'Citrus Spice Chamomile'},\n {value: 'Silver Jade', text: 'Silver Jade'},\n {value: 'Organic Matcha Cermonial', text: 'Organic Matcha Cermonial'},\n {value: 'Copabanana', text: 'Copabanana'},\n {value: 'Jasmine Dragon Pearl', text: 'Jasmine Dragon Pearl'},\n {value: 'Tung Ting', text: 'Tung Ting'},\n {value: '2000 Mini Pu-erh Tea Brick', text: '2000 Mini Pu-erh Tea Brick'},\n {value: 'Jamaican Rum Cake', text: 'Jamaican Rum Cake'},\n {value: 'Summer Tea Blend (TE55)', text: 'Summer Tea Blend (TE55)'},\n {value: 'Always End Up Here', text: 'Always End Up Here'},\n {value: 'Dragons Well', text: 'Dragons Well'},\n {value: 'Slim and Slender', text: 'Slim and Slender'},\n {value: 'Eight Oasis', text: 'Eight Oasis'},\n {value: 'Da Hong Pao (Big Red Robe)', text: 'Da Hong Pao (Big Red Robe)'},\n {value: 'Baozhong Oolong', text: 'Baozhong Oolong'},\n {value: 'Silver Yin Zhen Pearls', text: 'Silver Yin Zhen Pearls'},\n {value: '2009 Douji Fragrant Pu-erh Tea Brick',\n text: '2009 Douji Fragrant Pu-erh Tea Brick'},\n {value: 'OSullivans Favorite', text: 'OSullivans Favorite'},\n {value: 'Douglas Fir Spring Tips', text: 'Douglas Fir Spring Tips'},\n {value: '2011 Menghai Dayi Old Tea Nubs',\n text: '2011 Menghai Dayi Old Tea Nubs'},\n {value: 'Superfine Dragon Well Lung Ching Green Tea ( ZG71)',\n text: 'Superfine Dragon Well Lung Ching Green Tea ( ZG71)'},\n {value: 'Cinnamon &amp; Orange Rooibos Caffeine-free',\n text: 'Cinnamon Orange Rooibos Caffeine-free'},\n {value: 'Earl Grey Classic', text: 'Earl Grey Classic'},\n {value: 'Green Tea with Pomegranate and Acai',\n text: 'Green Tea with Pomegranate and Acai'},\n {value: 'Peach Momotaro Artisan Tea', text: 'Peach Momotaro Artisan Tea'},\n {value: 'Iron Boddhisattva Classic Roast',\n text: 'Iron Boddhisattva Classic Roast'},\n {value: 'Chocolate Rose Romance', text: 'Chocolate Rose Romance'},\n {value: 'Wonderful White', text: 'Wonderful White'},\n {value: 'Keisarin Oolong - Emperors Oolong',\n text: 'Keisarin Oolong - Emperors Oolong'},\n {value: 'Cochin Masala', text: 'Cochin Masala'},\n {value: 'The de Ceylan a la Cerise', text: 'The de Ceylan a la Cerise'},\n {value: 'Hand-Concocted Pick-Me-Up', text: 'Hand-Concocted Pick-Me-Up'},\n {value: 'Lichee Black Tea', text: 'Lichee Black Tea'},\n {value: 'Cinnamon Somersault', text: 'Cinnamon Somersault'},\n {value: 'Caribbean Blue Lady', text: 'Caribbean Blue Lady'},\n {value: 'Sock It To Me', text: 'Sock It To Me'},\n {value: 'Nine Dragon Golden Needle Black Tea',\n text: 'Nine Dragon Golden Needle Black Tea'},\n {value: 'The Black Cat', text: 'The Black Cat'},\n {value: 'White Chocolate Moon', text: 'White Chocolate Moon'},\n {value: 'Rose Petal', text: 'Rose Petal'},\n {value: 'Montviot Darjeeling', text: 'Montviot Darjeeling'},\n {value: 'Flower Jewel', text: 'Flower Jewel'},\n {value: 'New Zealand Breakfast Tea', text: 'New Zealand Breakfast Tea'},\n {value: 'Jesses Tea', text: 'Jesses Tea'},\n {value: 'Decaf Chocolate Hazelnut', text: 'Decaf Chocolate Hazelnut'},\n {value: 'Sencha Ei', text: 'Sencha Ei'},\n {value: 'Organic Houjicha', text: 'Organic Houjicha'},\n {value: 'Spicy Mandarin', text: 'Spicy Mandarin'},\n {value: 'Cinnamon Swirl Bread', text: 'Cinnamon Swirl Bread'},\n {value: 'Japanese Houjicha (or Hoji-cha) Roasted Green Tea',\n text: 'Japanese Houjicha (or Hoji-cha) Roasted Green Tea'},\n {value: 'Juleps on the Veranda', text: 'Juleps on the Veranda'},\n {value: 'Classic Citrus Iced Tea', text: 'Classic Citrus Iced Tea'},\n {value: 'Sweet Revenge', text: 'Sweet Revenge'},\n {value: 'Ten Ren Green Tea', text: 'Ten Ren Green Tea'},\n {value: 'Grapefruit Oolong', text: 'Grapefruit Oolong'},\n {value: 'Ceylon Tea', text: 'Ceylon Tea'},\n {value: 'Fiji', text: 'Fiji'},\n {value: 'Summer Solstice', text: 'Summer Solstice'},\n {value: 'Kenya Chai', text: 'Kenya Chai'},\n {value: 'South African Honeybush Grade A (BA24)',\n text: 'South African Honeybush Grade A (BA24)'},\n {value: 'Nepal Kuwapani', text: 'Nepal Kuwapani'},\n {value: 'Holiday Dream (No. 918)', text: 'Holiday Dream (No. 918)'},\n {value: 'Anxi Ti Kuan Yin', text: 'Anxi Ti Kuan Yin'},\n {value: 'Jasmine White Needle', text: 'Jasmine White Needle'},\n {value: 'Secret Weapon', text: 'Secret Weapon'},\n {value: 'Citron Sonata Green Tea', text: 'Citron Sonata Green Tea'},\n {value: 'Gypsy Love', text: 'Gypsy Love'},\n {value: 'Earl Greyer', text: 'Earl Greyer'},\n {value: 'Black Bud', text: 'Black Bud'},\n {value: 'Nightly Beauty Tea', text: 'Nightly Beauty Tea'},\n {value: 'Potato Pancakes &amp; Applesauce (Holiday Series: Hanukkah)',\n text: 'Potato Pancakes Applesauce (Holiday Series: Hanukkah)'},\n {value: 'Chocolate Mint Oolong', text: 'Chocolate Mint Oolong'},\n {value: 'Imperial Shi Feng Long Jing green tea-2010 spring',\n text: 'Imperial Shi Feng Long Jing green tea-2010 spring'},\n {value: 'Banana Dulce', text: 'Banana Dulce'},\n {value: 'Sakura Thé Blanc', text: 'Sakura Thé Blanc'},\n {value: 'Gorgeous Geisha', text: 'Gorgeous Geisha'},\n {value: 'organic orchid oolong', text: 'organic orchid oolong'},\n {value: 'Peach Apple Crisp', text: 'Peach Apple Crisp'},\n {value: 'TDA4: Arya Estate Pearl Organic (EX-15)',\n text: 'TDA4: Arya Estate Pearl Organic (EX-15)'},\n {value: 'Moon Swirl White Tip', text: 'Moon Swirl White Tip'},\n {value: 'Paradise', text: 'Paradise'},\n {value: 'Lemon Tea', text: 'Lemon Tea'},\n {value: 'Monkey Tea', text: 'Monkey Tea'},\n {value: '2007 Yin Ya Tuo Cha', text: '2007 Yin Ya Tuo Cha'},\n {value: '2000 Zhong-Cha Kumming “Lan Tie”',\n text: '2000 Zhong-Cha Kumming “Lan Tie”'},\n {value: 'Noble Mark Ripe Puer Blend 2011',\n text: 'Noble Mark Ripe Puer Blend 2011'},\n {value: 'Rooibos des Amants', text: 'Rooibos des Amants'},\n {value: 'Wu Yi Shui Xian', text: 'Wu Yi Shui Xian'},\n {value: 'Formosa Fancy Oolong Top Grade',\n text: 'Formosa Fancy Oolong Top Grade'},\n {value: 'Ocean of Wisdom', text: 'Ocean of Wisdom'},\n {value: 'Golden Monkey (No. 510)', text: 'Golden Monkey (No. 510)'},\n {value: 'Licorice Spice', text: 'Licorice Spice'},\n {value: 'Cantaloupe Bai Mu Dan', text: 'Cantaloupe Bai Mu Dan'},\n {value: 'Meng Ding Huang Ya', text: 'Meng Ding Huang Ya'},\n {value: 'Sikkim 2nd Flush Temi TGFOP1(BI06)',\n text: 'Sikkim 2nd Flush Temi TGFOP1(BI06)'},\n {value: 'Assam CTC BOP Estate Blend Organic (TA15)',\n text: 'Assam CTC BOP Estate Blend Organic (TA15)'},\n {value: 'Strawberry Oolong', text: 'Strawberry Oolong'},\n {value: 'Red Sunset', text: 'Red Sunset'},\n {value: 'Peach Tranquility', text: 'Peach Tranquility'},\n {value: 'Spring Cherry Green Tea', text: 'Spring Cherry Green Tea'},\n {value: 'Gyokuro Genmaicha Green Tea',\n text: 'Gyokuro Genmaicha Green Tea'},\n {value: 'Imperial Formosa', text: 'Imperial Formosa'},\n {value: 'Giddapahar First Flush Darjeeling',\n text: 'Giddapahar First Flush Darjeeling'},\n {value: 'Cleanse: Lemon Balm and Honey',\n text: 'Cleanse: Lemon Balm and Honey'},\n {value: 'Herbal Hot Cinnamon Spice', text: 'Herbal Hot Cinnamon Spice'},\n {value: '2010 Spring Wu Liang Mtn - Xue Dian Mei Lan - Yunnan',\n text: '2010 Spring Wu Liang Mtn - Xue Dian Mei Lan - Yunnan'},\n {value: 'Equator', text: 'Equator'},\n {value: 'Citron Green Iced Tea', text: 'Citron Green Iced Tea'},\n {value: 'Organic Korakundah Nilgiri Black Tea',\n text: 'Organic Korakundah Nilgiri Black Tea'},\n {value: '2007 Haiwan Purple Bud Raw Pu-erh',\n text: '2007 Haiwan Purple Bud Raw Pu-erh'},\n {value: 'TARDIS (Blend)', text: 'TARDIS (Blend)'},\n {value: 'Kama Chai Sutra', text: 'Kama Chai Sutra'},\n {value: 'Iced Chai Tea Latte', text: 'Iced Chai Tea Latte'},\n {value: 'Marron Chocolat', text: 'Marron Chocolat'},\n {value: 'Oolong', text: 'Oolong'},\n {value: 'Nirvana', text: 'Nirvana'},\n {value: 'Hazelnut', text: 'Hazelnut'},\n {value: 'Decaffeinated Chai Agni (TX33)',\n text: 'Decaffeinated Chai Agni (TX33)'},\n {value: 'Guri-cha', text: 'Guri-cha'},\n {value: 'Keemun Mao Feng Treasure 2009 [Out of Stock]',\n text: 'Keemun Mao Feng Treasure 2009 [Out of Stock]'},\n {value: 'Applestrudel', text: 'Applestrudel'},\n {value: 'Peachy White', text: 'Peachy White'},\n {value: 'Taiwanese Orchid Oolong', text: 'Taiwanese Orchid Oolong'},\n {value: 'Green Citric Ginger', text: 'Green Citric Ginger'},\n {value: 'MarziPlum Delight', text: 'MarziPlum Delight'},\n {value: 'Kaminabend', text: 'Kaminabend'},\n {value: 'Sattwa Chai (Concentrate)', text: 'Sattwa Chai (Concentrate)'},\n {value: 'Emerald Bamboo Forest', text: 'Emerald Bamboo Forest'},\n {value: 'Organic Blend 333', text: 'Organic Blend 333'},\n {value: 'China Coungou Golden Monkey Pekoe (ZK57)',\n text: 'China Coungou Golden Monkey Pekoe (ZK57)'},\n {value: 'Assam Greenwood Supreme SFTGFOP',\n text: 'Assam Greenwood Supreme SFTGFOP'},\n {value: 'Apricot', text: 'Apricot'},\n {value: 'Hattialli Golden Paw Assam', text: 'Hattialli Golden Paw Assam'},\n {value: 'Formosa Ming Xiang', text: 'Formosa Ming Xiang'},\n {value: 'Oriental', text: 'Oriental'},\n {value: 'Yunnan TGFOP (ZY51)', text: 'Yunnan TGFOP (ZY51)'},\n {value: 'Ye Sheng Puer', text: 'Ye Sheng Puer'},\n {value: 'Orange-flavored Oolong', text: 'Orange-flavored Oolong'},\n {value: 'Peppermint Ice', text: 'Peppermint Ice'},\n {value: 'Mocha Hazelnut', text: 'Mocha Hazelnut'},\n {value: 'Chocolate Raspberry', text: 'Chocolate Raspberry'},\n {value: 'PG Tips Loose Leaf', text: 'PG Tips Loose Leaf'},\n {value: 'Jade Pole Supreme Yunnan Green Tea',\n text: 'Jade Pole Supreme Yunnan Green Tea'},\n {value: 'Get Growing - No.15 (Wellness Collection)',\n text: 'Get Growing - No.15 (Wellness Collection)'},\n {value: 'Moroccan Mint Mistake', text: 'Moroccan Mint Mistake'},\n {value: 'Organic White Peony', text: 'Organic White Peony'},\n {value: 'Golden Earl', text: 'Golden Earl'},\n {value: 'Dragonwell Green Tea', text: 'Dragonwell Green Tea'},\n {value: 'Silonibari BPS(CTC)', text: 'Silonibari BPS(CTC)'},\n {value: 'Jasmine Pearls (Imperial Republic)',\n text: 'Jasmine Pearls (Imperial Republic)'},\n {value: 'Strawberry White Tea (851)', text: 'Strawberry White Tea (851)'},\n {value: 'Twilight Ti Kuan Yin', text: 'Twilight Ti Kuan Yin'},\n {value: 'Mango Nut', text: 'Mango Nut'},\n {value: 'Sencha Ashikubo', text: 'Sencha Ashikubo'},\n {value: 'Rouge dAutomne', text: 'Rouge dAutomne'},\n {value: 'Strawberry Sensation', text: 'Strawberry Sensation'},\n {value: 'Snow Leopard', text: 'Snow Leopard'},\n {value: 'Sencha Orange Passion', text: 'Sencha Orange Passion'},\n {value: 'Ti Kuan Yin Iron Goddess', text: 'Ti Kuan Yin Iron Goddess'},\n {value: 'Champagne Cider', text: 'Champagne Cider'},\n {value: 'Limetless Watermelon', text: 'Limetless Watermelon'},\n {value: 'Ailaoshan Black Tea', text: 'Ailaoshan Black Tea'},\n {value: 'Walnut', text: 'Walnut'},\n {value: 'Banana Green Tea', text: 'Banana Green Tea'},\n {value: 'Smores', text: 'Smores'},\n {value: 'White with Blackcurrant', text: 'White with Blackcurrant'},\n {value: 'Roasted Yerba Maté (BH22)', text: 'Roasted Yerba Maté (BH22)'},\n {value: 'Elf Help', text: 'Elf Help'},\n {value: 'Xingyang 1998 Golden Leaf Puer',\n text: 'Xingyang 1998 Golden Leaf Puer'},\n {value: 'Puerla Tea Nest', text: 'Puerla Tea Nest'},\n {value: 'Hot Toboggan (organic)', text: 'Hot Toboggan (organic)'},\n {value: 'Royal Gyokuro “Kotobuki No Tsuyu” Green Tea',\n text: 'Royal Gyokuro “Kotobuki No Tsuyu” Green Tea'},\n {value: 'Pearl of the river of Nile', text: 'Pearl of the river of Nile'},\n {value: 'Spiced Nog', text: 'Spiced Nog'},\n {value: 'Ginger Dragon Ball', text: 'Ginger Dragon Ball'},\n {value: 'Raspberry Earl', text: 'Raspberry Earl'},\n {value: 'Summer Harvest Laoshan Green',\n text: 'Summer Harvest Laoshan Green'},\n {value: 'Chocolate Mint Rooibos', text: 'Chocolate Mint Rooibos'},\n {value: 'Lapsang souchong biologique',\n text: 'Lapsang souchong biologique'},\n {value: 'Strawberry Zabaglione Green Tea',\n text: 'Strawberry Zabaglione Green Tea'},\n {value: 'Apple &amp; Spice Tea', text: 'Apple Spice Tea'},\n {value: 'Morning Dew', text: 'Morning Dew'},\n {value: '2007 Seven Color Featured Pu-erh Tea Cake',\n text: '2007 Seven Color Featured Pu-erh Tea Cake'},\n {value: 'Tie Luo Han', text: 'Tie Luo Han'},\n {value: 'Pure Camomile', text: 'Pure Camomile'},\n {value: 'China Lychee', text: 'China Lychee'},\n {value: 'Shamrocks &amp; Shenanigans',\n text: 'Shamrocks &amp; Shenanigans'},\n {value: 'Cha Cha Chai', text: 'Cha Cha Chai'},\n {value: 'White Darjeeling', text: 'White Darjeeling'},\n {value: 'Lemon Pound Cake', text: 'Lemon Pound Cake'},\n {value: '2007 Sheng Golden Ribbon Tuo',\n text: '2007 Sheng Golden Ribbon Tuo'},\n {value: 'Prince of Wales (loose leaf)',\n text: 'Prince of Wales (loose leaf)'},\n {value: '2009 First Flush Long Jing (Dragonwell)',\n text: '2009 First Flush Long Jing (Dragonwell)'},\n {value: 'spiced caramel apple', text: 'spiced caramel apple'},\n {value: 'Prince Igor', text: 'Prince Igor'},\n {value: 'Ahhh Taste My Hot Sticky Buns',\n text: 'Ahhh Taste My Hot Sticky Buns'},\n {value: 'Vanilla Black Tea', text: 'Vanilla Black Tea'},\n {value: 'Formosa Oolong Choicest (mild)',\n text: 'Formosa Oolong Choicest (mild)'},\n {value: 'Pirkka Green Tea', text: 'Pirkka Green Tea'},\n {value: 'Ginger Peach loose leaf tea',\n text: 'Ginger Peach loose leaf tea'},\n {value: 'Assam Breeze Black Tea', text: 'Assam Breeze Black Tea'},\n {value: 'Gunpowder &amp; Mint', text: 'Gunpowder &amp; Mint'},\n {value: 'Sencha with Strawberry &amp; Lychee',\n text: 'Sencha with Strawberry Lychee'},\n {value: 'Passion Fruit Green Oolong with Osmanthus',\n text: 'Passion Fruit Green Oolong with Osmanthus'},\n {value: 'Decaffeinated Vanilla EA (TX91)',\n text: 'Decaffeinated Vanilla EA (TX91)'},\n {value: 'Ti Kuan Yin Oolong', text: 'Ti Kuan Yin Oolong'},\n {value: 'Hika Sencha', text: 'Hika Sencha'},\n {value: 'Emperor Jiaqings Tribute Tea',\n text: 'Emperor Jiaqings Tribute Tea'},\n {value: 'Malibu White Tea', text: 'Malibu White Tea'},\n {value: 'CasTea - Signature Blend', text: 'CasTea - Signature Blend'},\n {value: 'Flocons dÉpices', text: 'Flocons dÉpices'},\n {value: 'The Naughty Vicar', text: 'The Naughty Vicar'},\n {value: 'Gold Blend Tea Bags', text: 'Gold Blend Tea Bags'},\n {value: 'Organic Pure Ceylon Tea', text: 'Organic Pure Ceylon Tea'},\n {value: 'Tropical White', text: 'Tropical White'},\n {value: 'Organic Texas Iced Tea', text: 'Organic Texas Iced Tea'},\n {value: 'Jessies Tea', text: 'Jessies Tea'},\n {value: 'Assam Malty FBOP', text: 'Assam Malty FBOP'},\n {value: 'Lemon Everyday Detox Tea', text: 'Lemon Everyday Detox Tea'},\n {value: 'Assam Hattialli Estate TGFOP1',\n text: 'Assam Hattialli Estate TGFOP1'},\n {value: '2007 Summer Guei Fei Cha (Concubine tea)',\n text: '2007 Summer Guei Fei Cha (Concubine tea)'},\n {value: 'Raspberry Herbal', text: 'Raspberry Herbal'},\n {value: 'Singapore Breakfast', text: 'Singapore Breakfast'},\n {value: 'Mr. Ollivanders Magic Potion',\n text: 'Mr. Ollivanders Magic Potion'},\n {value: 'Bai Yun Oolong', text: 'Bai Yun Oolong'},\n {value: 'Formosa Wenshan Baochong Choice',\n text: 'Formosa Wenshan Baochong Choice'},\n {value: 'Kenya Oolong', text: 'Kenya Oolong'},\n {value: 'Ali Shan Jin Shuan SiaoSyue 2010 Winter',\n text: 'Ali Shan Jin Shuan SiaoSyue 2010 Winter'},\n {value: 'Sticky Rice Pu-erh', text: 'Sticky Rice Pu-erh'},\n {value: 'Mint Oolong', text: 'Mint Oolong'},\n {value: '2003 Fu Hai 7576', text: '2003 Fu Hai 7576'},\n {value: 'Honey Sweet Black', text: 'Honey Sweet Black'},\n {value: 'Acai and Goji Berry', text: 'Acai and Goji Berry'},\n {value: 'Austin Breakfast', text: 'Austin Breakfast'},\n {value: 'ZG30: Special Grade Temple of Heaven Gunpowder Green',\n text: 'ZG30: Special Grade Temple of Heaven Gunpowder Green'},\n {value: 'Chunky Cherry', text: 'Chunky Cherry'},\n {value: 'Coconut Grove', text: 'Coconut Grove'},\n {value: 'Bolivian Rio Negro (organic) BOP (BBo2)',\n text: 'Bolivian Rio Negro (organic) BOP (BBo2)'},\n {value: 'Tie Guan Yin', text: 'Tie Guan Yin'},\n {value: 'Pearl Queen of Jasmine Tea', text: 'Pearl Queen of Jasmine Tea'},\n {value: 'The London Cuppa', text: 'The London Cuppa'},\n {value: 'Lord John Grey', text: 'Lord John Grey'},\n {value: 'Cranberry Cream', text: 'Cranberry Cream'},\n {value: 'Papayarama', text: 'Papayarama'},\n {value: 'Evening Jazz', text: 'Evening Jazz'},\n {value: 'Wu Wei', text: 'Wu Wei'},\n {value: 'Lavender Dreams', text: 'Lavender Dreams'},\n {value: 'Lemon Shimmer', text: 'Lemon Shimmer'},\n {value: 'rosebud', text: 'rosebud'},\n {value: 'White Cherry', text: 'White Cherry'},\n {value: 'Raspberry Mint', text: 'Raspberry Mint'},\n {value: 'Mimosa', text: 'Mimosa'},\n {value: 'Pu Erh with Orange', text: 'Pu Erh with Orange'},\n {value: 'Ambootia SF', text: 'Ambootia SF'},\n {value: 'Organic Kundaly', text: 'Organic Kundaly'},\n {value: '2010 Spring Imperial Anxi Huang Jin Gui Oolong Tea',\n text: '2010 Spring Imperial Anxi Huang Jin Gui Oolong Tea'},\n {value: 'Julete', text: 'Julete'},\n {value: 'DeDe Instant Thai Tea with Cream /Sugar',\n text: 'DeDe Instant Thai Tea with Cream /Sugar'},\n {value: 'Chun Mee', text: 'Chun Mee'},\n {value: 'Mango Lassi', text: 'Mango Lassi'},\n {value: 'Black Pearl', text: 'Black Pearl'},\n {value: 'Formosa Pi Lo Chun (No. 601)',\n text: 'Formosa Pi Lo Chun (No. 601)'},\n {value: 'Bai Hao Yin Zhen Tradicional',\n text: 'Bai Hao Yin Zhen Tradicional'},\n {value: 'Smoky Earl Grey', text: 'Smoky Earl Grey'},\n {value: 'Chrysanthemum Tea', text: 'Chrysanthemum Tea'},\n {value: 'Hamburger Grutze Cream', text: 'Hamburger Grutze Cream'},\n {value: 'Happy New Year - Bai Mu Dan',\n text: 'Happy New Year - Bai Mu Dan'},\n {value: 'Apricot Cheesecake Flavored Black Tea',\n text: 'Apricot Cheesecake Flavored Black Tea'},\n {value: 'Bocha', text: 'Bocha'},\n {value: 'Ancient Tree Earl Grey Organic Fair Trade',\n text: 'Ancient Tree Earl Grey Organic Fair Trade'},\n {value: 'O Sullivans Favourite', text: 'O Sullivans Favourite'},\n {value: 'dragonwell early harvest', text: 'dragonwell early harvest'},\n {value: '2005 Lao Tong Zhi Raw Brick',\n text: '2005 Lao Tong Zhi Raw Brick'},\n {value: 'Pomegranate Black', text: 'Pomegranate Black'},\n {value: 'Four Seasons', text: 'Four Seasons'},\n {value: 'Orange Sun Sencha', text: 'Orange Sun Sencha'},\n {value: 'Puerh Tuo Cha', text: 'Puerh Tuo Cha'},\n {value: 'Blueberry Flavored Ceylon Black Tea',\n text: 'Blueberry Flavored Ceylon Black Tea'},\n {value: 'Nonsuch Estate Nilgiri', text: 'Nonsuch Estate Nilgiri'},\n {value: 'Berry Blast', text: 'Berry Blast'},\n {value: 'Ginkgo Temple of Heaven', text: 'Ginkgo Temple of Heaven'},\n {value: 'Winter Cinnamon Tea', text: 'Winter Cinnamon Tea'},\n {value: 'Prince Vladimir', text: 'Prince Vladimir'},\n {value: 'Chun Lu', text: 'Chun Lu'},\n {value: 'Genmai-Cha (Premium Tea Bag)',\n text: 'Genmai-Cha (Premium Tea Bag)'},\n {value: 'Luzianne', text: 'Luzianne'},\n {value: 'Caramel Mate', text: 'Caramel Mate'},\n {value: 'A Moment of Calm Chamomile Honey &amp; Vanilla',\n text: 'A Moment of Calm Chamomile Honey Vanilla'},\n {value: 'Sow Mee', text: 'Sow Mee'},\n {value: 'Cookie Dough', text: 'Cookie Dough'},\n {value: 'Darjeeling stupa oolong', text: 'Darjeeling stupa oolong'},\n {value: 'Prince of Wales', text: 'Prince of Wales'},\n {value: 'Friendship Lychee', text: 'Friendship Lychee'},\n {value: 'Organico Melograno', text: 'Organico Melograno'},\n {value: 'Wu Yi Oolong Tea', text: 'Wu Yi Oolong Tea'},\n {value: 'TP70: Premium Chinese Jasmine with Flowers',\n text: 'TP70: Premium Chinese Jasmine with Flowers'},\n {value: 'Risheehat Second Flush Darjeeling',\n text: 'Risheehat Second Flush Darjeeling'},\n {value: 'Tahitian Tangerine', text: 'Tahitian Tangerine'},\n {value: 'Ceylon Sonata Iced Tea', text: 'Ceylon Sonata Iced Tea'},\n {value: 'MatéChino™', text: 'MatéChino™'},\n {value: 'Iced Green Tea', text: 'Iced Green Tea'},\n {value: 'Huang Shan Mao Feng Reserve',\n text: 'Huang Shan Mao Feng Reserve'},\n {value: 'Matcha Super Premium', text: 'Matcha Super Premium'},\n {value: 'Taiwan Dongding Oolong Tea (Light Roasted)',\n text: 'Taiwan Dongding Oolong Tea (Light Roasted)'},\n {value: 'Almond Matcha', text: 'Almond Matcha'},\n {value: 'Li Zi Xiang', text: 'Li Zi Xiang'},\n {value: 'Menghai Palace Ripened Pu-erh Cake Tea 2008',\n text: 'Menghai Palace Ripened Pu-erh Cake Tea 2008'},\n {value: 'Sen-cha (Blenders Series)', text: 'Sen-cha (Blenders Series)'},\n {value: 'Coconut Black Tea', text: 'Coconut Black Tea'},\n {value: 'South China Black Dragon Organic',\n text: 'South China Black Dragon Organic'},\n {value: 'Seattle Breakfast Blend Tea',\n text: 'Seattle Breakfast Blend Tea'},\n {value: 'Miesna Christmas Tea', text: 'Miesna Christmas Tea'},\n {value: 'Roo Lemon Pie', text: 'Roo Lemon Pie'},\n {value: 'TC85: Kenilworth Estate OP', text: 'TC85: Kenilworth Estate OP'},\n {value: 'Hand Picked Spring Tieguanyin (2012)',\n text: 'Hand Picked Spring Tieguanyin (2012)'},\n {value: 'Orange Pekoe China Black', text: 'Orange Pekoe China Black'},\n {value: 'First Flush Darjeeling Nurbong',\n text: 'First Flush Darjeeling Nurbong'},\n {value: 'Organic Dragon Well Green Tea (Long Jing)',\n text: 'Organic Dragon Well Green Tea (Long Jing)'},\n {value: 'Guayusa', text: 'Guayusa'},\n {value: 'Organic Da Hong Pao Oolong', text: 'Organic Da Hong Pao Oolong'},\n {value: 'Bi Lou Chun', text: 'Bi Lou Chun'},\n {value: 'Egyptian Mint', text: 'Egyptian Mint'},\n {value: 'Scottish Breakfast', text: 'Scottish Breakfast'},\n {value: 'Chai - Loose Tea', text: 'Chai - Loose Tea'},\n {value: 'Uji Matcha Manten', text: 'Uji Matcha Manten'},\n {value: 'Double Dark Chocolate Mate', text: 'Double Dark Chocolate Mate'},\n {value: 'Ssangkye Roasting Sejak', text: 'Ssangkye Roasting Sejak'},\n {value: 'Nai Xiang Oolong', text: 'Nai Xiang Oolong'},\n {value: 'Bleu Peacock', text: 'Bleu Peacock'},\n {value: 'Zhen Qu Black Tea', text: 'Zhen Qu Black Tea'},\n {value: 'Tuo Cha Bonbons', text: 'Tuo Cha Bonbons'},\n {value: 'Taiwanese Dong Ding Oolong', text: 'Taiwanese Dong Ding Oolong'},\n {value: 'Glogg Green', text: 'Glogg Green'},\n {value: 'Vickys Sponge Cake', text: 'Vickys Sponge Cake'},\n {value: 'Chai Rooibos', text: 'Chai Rooibos'},\n {value: 'Tiramisu', text: 'Tiramisu'},\n {value: '2007 Purple Tip Pu-erh Raw', text: '2007 Purple Tip Pu-erh Raw'},\n {value: 'DISCONTINUED (cannot be verified 100% pesticide free) - Huang Zhi Xiang Phoenix Mountain Oolong',\n text: 'DISCONTINUED Huang Zhi Xiang Phoenix Mountain Oolong'},\n {value: 'First Love', text: 'First Love'},\n {value: 'The Woman (Blend)', text: 'The Woman (Blend)'},\n {value: 'Ancient Snow Sprout', text: 'Ancient Snow Sprout'},\n {value: '2010 Spring Yong De White Buds - Sun Dried White Tea',\n text: '2010 Spring Yong De White Buds - Sun Dried White Tea'},\n {value: 'Elyses Blend', text: 'Elyses Blend'},\n {value: 'Thirsty Elf Elixir Blend', text: 'Thirsty Elf Elixir Blend'},\n {value: 'A Me Sooo Horny Tea Blues Tea',\n text: 'A Me Sooo Horny Tea Blues Tea'},\n {value: 'Chocolate Orange Truffle', text: 'Chocolate Orange Truffle'},\n {value: 'Pu-Er Tea', text: 'Pu-Er Tea'},\n {value: 'Mango White', text: 'Mango White'},\n {value: 'Chamana Rojo', text: 'Chamana Rojo'},\n {value: 'Scottish Blend', text: 'Scottish Blend'},\n {value: 'Ali San', text: 'Ali San'},\n {value: '2007 Dehong Mini Ripe Pu-erh Beeng Cha',\n text: '2007 Dehong Mini Ripe Pu-erh Beeng Cha'},\n {value: 'Yerba Mate Latte', text: 'Yerba Mate Latte'},\n {value: 'Premium Huang Shan Mao Feng Green Tea',\n text: 'Premium Huang Shan Mao Feng Green Tea'},\n {value: 'Rooibos White Chocolate Toffee (No. 763)',\n text: 'Rooibos White Chocolate Toffee (No. 763)'},\n {value: 'Peachberry Jasmine Sutra with Strawberry Lemonade',\n text: 'Peachberry Jasmine Sutra with Strawberry Lemonade'},\n {value: 'Organic Lovely Lemon', text: 'Organic Lovely Lemon'},\n {value: 'Mint Verbena', text: 'Mint Verbena'},\n {value: 'Dragon Well Tea (Xi Hu Long Jing) Jipin Grade',\n text: 'Dragon Well Tea (Xi Hu Long Jing) Jipin Grade'},\n {value: 'Pure Darjeeling Tea', text: 'Pure Darjeeling Tea'},\n {value: 'Caramellissimo', text: 'Caramellissimo'},\n {value: 'Honeybush Mango Lemon', text: 'Honeybush Mango Lemon'},\n {value: 'Palm Court', text: 'Palm Court'},\n {value: 'Mackinaw Breeze', text: 'Mackinaw Breeze'},\n {value: 'Orange Spice Rooibos', text: 'Orange Spice Rooibos'},\n {value: 'Hokkori Sencha-Gyokuro Blend',\n text: 'Hokkori Sencha-Gyokuro Blend'},\n {value: 'Earl Grey Whole Leaf Organics',\n text: 'Earl Grey Whole Leaf Organics'},\n {value: 'China Black', text: 'China Black'},\n {value: 'Imperial', text: 'Imperial'},\n {value: 'Carävan Resurrected', text: 'Carävan Resurrected'},\n {value: 'Carob Matcha', text: 'Carob Matcha'},\n {value: '2009 Jinggu Purple Bud Big Tree Raw Pu Er Tuo Cha',\n text: '2009 Jinggu Purple Bud Big Tree Raw Pu Er Tuo Cha'},\n {value: 'Green Tea &amp; Peach', text: 'Green Tea &amp; Peach'},\n {value: 'Bai Mu Dan/Classic White Tea',\n text: 'Bai Mu Dan/Classic White Tea'},\n {value: 'White Tea with Pomegranate', text: 'White Tea with Pomegranate'},\n {value: 'Sun and Cloud Mist', text: 'Sun and Cloud Mist'},\n {value: 'Apricot Peach Fruit Blend', text: 'Apricot Peach Fruit Blend'},\n {value: 'Xin Yang Mao Jian Green Tea',\n text: 'Xin Yang Mao Jian Green Tea'},\n {value: 'Organic Tribute Red Jade 18 Ping Xi Taiwan Fall 2009',\n text: 'Organic Tribute Red Jade 18 Ping Xi Taiwan Fall 2009'},\n {value: 'Jasmine Silver Needle White Tea (Mo Li Yin Zhen)',\n text: 'Jasmine Silver Needle White Tea (Mo Li Yin Zhen)'},\n {value: 'Peppermint Leaves', text: 'Peppermint Leaves'},\n {value: 'Ruby 18', text: 'Ruby 18'},\n {value: 'Chili-Chocolate Black Tea', text: 'Chili-Chocolate Black Tea'},\n {value: 'Echinacea Elderberry with Cranberry &amp; Rooibos',\n text: 'Echinacea Elderberry with Cranberry &amp; Rooibos'},\n {value: 'Organic Spicy Ginger', text: 'Organic Spicy Ginger'},\n {value: 'green tea powder 250g pack', text: 'green tea powder 250g pack'},\n {value: 'Shaded Leaf', text: 'Shaded Leaf'},\n {value: 'Thiashola SFTGFOP1', text: 'Thiashola SFTGFOP1'},\n {value: 'Duke Cardiffs Black Tea Blend',\n text: 'Duke Cardiffs Black Tea Blend'},\n {value: '108th Nights Shincha Umegashima',\n text: '108th Nights Shincha Umegashima'},\n {value: 'Dragon Well Green', text: 'Dragon Well Green'},\n {value: 'Bhuddhas Hand Spring 2011', text: 'Bhuddhas Hand Spring 2011'},\n {value: 'Organic Makaibari Oolong Tea',\n text: 'Organic Makaibari Oolong Tea'},\n {value: 'Eight Immortals (Organic) 2008',\n text: 'Eight Immortals (Organic) 2008'},\n {value: 'Energy ChocoLatte Chai Tea Blend',\n text: 'Energy ChocoLatte Chai Tea Blend'},\n {value: 'Japanese Green Samurai Matcha',\n text: 'Japanese Green Samurai Matcha'},\n {value: 'Apple Crunch Black Tea', text: 'Apple Crunch Black Tea'},\n {value: 'White Symphony', text: 'White Symphony'},\n {value: 'Darjeeling Oaks SFTGFOP1', text: 'Darjeeling Oaks SFTGFOP1'},\n {value: 'Pan-Fried Darjeeling', text: 'Pan-Fried Darjeeling'},\n {value: 'Victorian Earl Grey', text: 'Victorian Earl Grey'},\n {value: 'Japan Sencha Fukujyu', text: 'Japan Sencha Fukujyu'},\n {value: 'Man Tang Xiang', text: 'Man Tang Xiang'},\n {value: 'Citrus Lavender Sage', text: 'Citrus Lavender Sage'},\n {value: 'Sencha Superior', text: 'Sencha Superior'},\n {value: 'Mi Lan Dan Cong', text: 'Mi Lan Dan Cong'},\n {value: 'Tulsi (Holy Basil)', text: 'Tulsi (Holy Basil)'},\n {value: 'Honeybush Mandarin &amp; Orange',\n text: 'Honeybush Mandarin Orange'},\n {value: 'Oolong Supreme', text: 'Oolong Supreme'},\n {value: '2006 Menghai Gongting Pu-erh Tea Cake',\n text: '2006 Menghai Gongting Pu-erh Tea Cake'},\n {value: 'Dragon Lily', text: 'Dragon Lily'},\n {value: 'The Jabberwocky', text: 'The Jabberwocky'},\n {value: 'Vanilla Basic Black', text: 'Vanilla Basic Black'},\n {value: 'Pure Peppermint', text: 'Pure Peppermint'},\n {value: 'Peach Black Tea', text: 'Peach Black Tea'},\n {value: 'Ginseng Green', text: 'Ginseng Green'},\n {value: 'Assam Banaspaty', text: 'Assam Banaspaty'},\n {value: 'Darjeeling Broken Orange Pekoe',\n text: 'Darjeeling Broken Orange Pekoe'},\n {value: 'Coconut Masala Chai', text: 'Coconut Masala Chai'},\n {value: 'Taiwan Muzha Ti Kuan Yin Tea',\n text: 'Taiwan Muzha Ti Kuan Yin Tea'},\n {value: 'Lemon Meringue Pie', text: 'Lemon Meringue Pie'},\n {value: 'Dreamsicle Tea', text: 'Dreamsicle Tea'},\n {value: 'Butterfly of Taiwan', text: 'Butterfly of Taiwan'},\n {value: 'Sencha Green Tea', text: 'Sencha Green Tea'},\n {value: '2007 Menghai Yunhai Puerh Ball',\n text: '2007 Menghai Yunhai Puerh Ball'},\n {value: 'Snowy Apple Pie', text: 'Snowy Apple Pie'},\n {value: 'Red Raspberry Herbal Tea', text: 'Red Raspberry Herbal Tea'},\n {value: 'Cassia Oolong Tea (Wuyi Rou Gui Wu Long)',\n text: 'Cassia Oolong Tea (Wuyi Rou Gui Wu Long)'},\n {value: 'Gen-Mai Cha Tealuxe 181', text: 'Gen-Mai Cha Tealuxe 181'},\n {value: 'Yunnan Noir', text: 'Yunnan Noir'},\n {value: 'Watermelon Green Honeybush', text: 'Watermelon Green Honeybush'},\n {value: 'China Pu-Erh', text: 'China Pu-Erh'},\n {value: 'Festivus Chai', text: 'Festivus Chai'},\n {value: 'Second Flush Darjeeling', text: 'Second Flush Darjeeling'},\n {value: 'Pu Ti Cha', text: 'Pu Ti Cha'},\n {value: 'Superberry White', text: 'Superberry White'},\n {value: 'Perfect Peach', text: 'Perfect Peach'},\n {value: 'Keemun Mao Feng', text: 'Keemun Mao Feng'},\n {value: 'Kuradashi Sencha', text: 'Kuradashi Sencha'},\n {value: 'Pirate Chai', text: 'Pirate Chai'},\n {value: 'Bengali Blend', text: 'Bengali Blend'},\n {value: 'Hai Lang Hao Cha Wang 2010', text: 'Hai Lang Hao Cha Wang 2010'},\n {value: 'Bai Hao Oolong (Oriental Beauty)',\n text: 'Bai Hao Oolong (Oriental Beauty)'},\n {value: 'Georgian Old Lady', text: 'Georgian Old Lady'},\n {value: 'Iced tea brew', text: 'Iced tea brew'},\n {value: 'Organic Better Rest Blend', text: 'Organic Better Rest Blend'},\n {value: 'Clipper Organic Chai', text: 'Clipper Organic Chai'},\n {value: 'Organic Jasmine Silver Needle',\n text: 'Organic Jasmine Silver Needle'},\n {value: 'Cloud and Mist Yun Wu', text: 'Cloud and Mist Yun Wu'},\n {value: 'Blue Lagoon', text: 'Blue Lagoon'},\n {value: 'Lapsang Souchong Imperial', text: 'Lapsang Souchong Imperial'},\n {value: 'Tè Rosso alla Vaniglia (Rooibos and Vanilla)',\n text: 'Tè Rosso alla Vaniglia (Rooibos and Vanilla)'},\n {value: 'Organic White Tea with Orange',\n text: 'Organic White Tea with Orange'},\n {value: 'Candy Cane', text: 'Candy Cane'},\n {value: 'Alberta Street Chai', text: 'Alberta Street Chai'},\n {value: 'Morning Red', text: 'Morning Red'},\n {value: '2014 Sheng Puerh - Autumn', text: '2014 Sheng Puerh - Autumn'},\n {value: 'Lemon Ginger plus Probiotics',\n text: 'Lemon Ginger plus Probiotics'},\n {value: 'Jasmine Silver Dragon', text: 'Jasmine Silver Dragon'},\n {value: 'Cafe Latte', text: 'Cafe Latte'},\n {value: 'Darjeeling-Makaibari Organic SFTGFOP',\n text: 'Darjeeling-Makaibari Organic SFTGFOP'},\n {value: 'Taiwan Da Yu Ling High Mountain Oolong',\n text: 'Taiwan Da Yu Ling High Mountain Oolong'},\n {value: 'Assam Golden Tip', text: 'Assam Golden Tip'},\n {value: 'Treasure Chocolate', text: 'Treasure Chocolate'},\n {value: 'Love Potion Sencha', text: 'Love Potion Sencha'},\n {value: 'Vanilla Oolong', text: 'Vanilla Oolong'},\n {value: 'Fruit Infusion Sweet Berry', text: 'Fruit Infusion Sweet Berry'},\n {value: 'Taiwan Lishan Oolong Tea', text: 'Taiwan Lishan Oolong Tea'},\n {value: 'Good Earth Original', text: 'Good Earth Original'},\n {value: 'Darjeeling 2nd Flush House Blend',\n text: 'Darjeeling 2nd Flush House Blend'},\n {value: 'Rongzhen Tribute Ripen', text: 'Rongzhen Tribute Ripen'},\n {value: 'Creme de la Earl Grey Decaf',\n text: 'Creme de la Earl Grey Decaf'},\n {value: 'Premium Roi Gui', text: 'Premium Roi Gui'},\n {value: 'Rooibos Orange', text: 'Rooibos Orange'},\n {value: 'Organic Schizandra White Tea',\n text: 'Organic Schizandra White Tea'},\n {value: 'Golden Oolong', text: 'Golden Oolong'},\n {value: 'Sakurambo Vert', text: 'Sakurambo Vert'},\n {value: 'Kenilworth', text: 'Kenilworth'},\n {value: 'Gyokuro Superior', text: 'Gyokuro Superior'},\n {value: 'Douji Yiwu Shan Qiao Mu (2006)',\n text: 'Douji Yiwu Shan Qiao Mu (2006)'},\n {value: 'Unknown Pu-erh Cake', text: 'Unknown Pu-erh Cake'},\n {value: 'Luminous Lemon Rooibos', text: 'Luminous Lemon Rooibos'},\n {value: 'Green Menthos', text: 'Green Menthos'},\n {value: 'Eight Treasures Yabao', text: 'Eight Treasures Yabao'},\n {value: 'Tiger Assam', text: 'Tiger Assam'},\n {value: 'Darjeeling Jungpana Estate SFTGFOP1 2009 1st Flush',\n text: 'Darjeeling Jungpana Estate SFTGFOP1 2009 1st Flush'},\n {value: 'Decaf Orange Pekoe &amp; pekoe cut black tea',\n text: 'Decaf Orange Pekoe'},\n {value: 'Strawberry Lemonade Herbal Tea',\n text: 'Strawberry Lemonade Herbal Tea'},\n {value: '2004 Xia Guan Jia Ji (Grade I) Tuo Sheng 100g',\n text: '2004 Xia Guan Jia Ji (Grade I) Tuo Sheng 100g'},\n {value: 'Moroccan Mint (Filter Bag)', text: 'Moroccan Mint (Filter Bag)'},\n {value: 'Old Stalk 2002 Lincang Bamboo Stuffed Raw Puer',\n text: 'Old Stalk 2002 Lincang Bamboo Stuffed Raw Puer'},\n {value: 'Spring Darjeeling', text: 'Spring Darjeeling'},\n {value: 'Flowering Tea', text: 'Flowering Tea'},\n {value: 'Go-Man-Go', text: 'Go-Man-Go'},\n {value: '2005 Xiaguan Tea Factory Yunnan Green Tuocha',\n text: '2005 Xiaguan Tea Factory Yunnan Green Tuocha'},\n {value: 'Chamomile Stroll', text: 'Chamomile Stroll'},\n {value: 'Caramel Dipped Apple', text: 'Caramel Dipped Apple'},\n {value: 'Sweet Apple Spice with Pomegranate',\n text: 'Sweet Apple Spice with Pomegranate'},\n {value: 'Assam Banaspaty Organic FTGFOP1',\n text: 'Assam Banaspaty Organic FTGFOP1'},\n {value: 'Lung Ching Dragonwell', text: 'Lung Ching Dragonwell'},\n {value: 'Steeped Tea', text: 'Steeped Tea'},\n {value: 'Lu Shan Clouds and Mist (Yun Wu)',\n text: 'Lu Shan Clouds and Mist (Yun Wu)'},\n {value: 'Organic Citrus Ginger Green Tea',\n text: 'Organic Citrus Ginger Green Tea'},\n {value: 'Matcha Green Tea', text: 'Matcha Green Tea'},\n {value: 'Three Kingdoms Mao Feng', text: 'Three Kingdoms Mao Feng'},\n {value: 'Hawaiian Colada', text: 'Hawaiian Colada'},\n {value: 'Thé de Vendome', text: 'Thé de Vendome'},\n {value: 'Mao Jian', text: 'Mao Jian'},\n {value: 'China Jade Oolong Super Fancy',\n text: 'China Jade Oolong Super Fancy'},\n {value: 'Yunnan Golden Needles', text: 'Yunnan Golden Needles'},\n {value: 'Fairy Lily', text: 'Fairy Lily'},\n {value: 'Heavenly Blue Peak (Tian Mu Qing Ding)',\n text: 'Heavenly Blue Peak (Tian Mu Qing Ding)'},\n {value: 'Imperial Oolong', text: 'Imperial Oolong'},\n {value: 'Tigre et dragon', text: 'Tigre et dragon'},\n {value: 'Rooibos Cocomint', text: 'Rooibos Cocomint'},\n {value: 'Cha Wang Tai Ping Hou Kui', text: 'Cha Wang Tai Ping Hou Kui'},\n {value: 'Roasted Mate', text: 'Roasted Mate'},\n {value: 'Virtonic', text: 'Virtonic'},\n {value: 'Thé Royal Ceylan', text: 'Thé Royal Ceylan'},\n {value: 'Emperors Clouds and Mist', text: 'Emperors Clouds and Mist'},\n {value: 'Matevana &amp; Rooibos Chai blend',\n text: 'Matevana &amp; Rooibos Chai blend'},\n {value: 'Green Tea &amp; Lemon', text: 'Green Tea &amp; Lemon'},\n {value: 'Ronnefeldt Winterdream', text: 'Ronnefeldt Winterdream'},\n {value: 'Dali Darjeeling', text: 'Dali Darjeeling'},\n {value: 'Oolong Orange Blossom', text: 'Oolong Orange Blossom'},\n {value: 'Choco Nut Blend', text: 'Choco Nut Blend'},\n {value: 'Lemon Cardamom Chun Mee', text: 'Lemon Cardamom Chun Mee'},\n {value: 'Formosa Fine Oolong', text: 'Formosa Fine Oolong'},\n {value: 'Liquorice Peppermint', text: 'Liquorice Peppermint'},\n {value: 'Tazo Thrive', text: 'Tazo Thrive'},\n {value: 'Ceylon Supreme', text: 'Ceylon Supreme'},\n {value: 'Yunnan Moon', text: 'Yunnan Moon'},\n {value: 'Organic Pomegranate Berry', text: 'Organic Pomegranate Berry'},\n {value: 'Le Voyageur', text: 'Le Voyageur'},\n {value: 'Madagascar Vanilla Rooibos', text: 'Madagascar Vanilla Rooibos'},\n {value: 'Lychee Blossom (Rare Tea Collection)',\n text: 'Lychee Blossom (Rare Tea Collection)'},\n {value: 'Sticky Rice Pu-erh Tuocha', text: 'Sticky Rice Pu-erh Tuocha'},\n {value: 'Rooibos Tropica', text: 'Rooibos Tropica'},\n {value: 'Green Flower Rooibos', text: 'Green Flower Rooibos'},\n {value: 'Mango Ceylon', text: 'Mango Ceylon'},\n {value: 'Mrs. Earl Grey', text: 'Mrs. Earl Grey'},\n {value: 'Thai Chai', text: 'Thai Chai'},\n {value: 'Whole Leaf Imperial Gunpowder Green Tea',\n text: 'Whole Leaf Imperial Gunpowder Green Tea'},\n {value: 'Wanderlust', text: 'Wanderlust'},\n {value: '2007 Liu Bao Tea Cake', text: '2007 Liu Bao Tea Cake'},\n {value: 'East of Rift Kenyan Kambaa Tea',\n text: 'East of Rift Kenyan Kambaa Tea'},\n {value: 'Peppermint Tea', text: 'Peppermint Tea'},\n {value: 'Cinnamon Plum', text: 'Cinnamon Plum'},\n {value: 'Imperial Mojiang Golden Bud Yunnan Black Tea',\n text: 'Imperial Mojiang Golden Bud Yunnan Black Tea'},\n {value: 'Chocolate Smooth Move', text: 'Chocolate Smooth Move'},\n {value: 'Decaf Apricot', text: 'Decaf Apricot'},\n {value: 'darjeeling singbulli', text: 'darjeeling singbulli'},\n {value: 'Arctic Raspberry', text: 'Arctic Raspberry'},\n {value: 'Cardamom Earl Grey', text: 'Cardamom Earl Grey'},\n {value: 'Cherry Fiesta', text: 'Cherry Fiesta'},\n {value: 'Kukicha Twig Tea', text: 'Kukicha Twig Tea'},\n {value: 'Herb Green (Tea Bag)', text: 'Herb Green (Tea Bag)'},\n {value: 'Luscious Raspberry Tea', text: 'Luscious Raspberry Tea'},\n {value: 'Organic Orchid Oolong', text: 'Organic Orchid Oolong'},\n {value: 'Royal Courtesan', text: 'Royal Courtesan'},\n {value: 'Lychee Oolong', text: 'Lychee Oolong'},\n {value: 'Nutcracker', text: 'Nutcracker'},\n {value: 'BF71: Cinnamon Plum Fruit Tea',\n text: 'BF71: Cinnamon Plum Fruit Tea'},\n {value: 'Double Spice Chai', text: 'Double Spice Chai'},\n {value: 'Chicory Dickory Dock (organic)',\n text: 'Chicory Dickory Dock (organic)'},\n {value: 'Almond Indulgence (Formerly Almond Cookie)',\n text: 'Almond Indulgence (Formerly Almond Cookie)'},\n {value: 'Kiwis Big Adventure', text: 'Kiwis Big Adventure'},\n {value: 'High Peak Wild Oolong', text: 'High Peak Wild Oolong'},\n {value: 'Phoenix Supreme', text: 'Phoenix Supreme'},\n {value: 'Organic Putharjhora Green Tea',\n text: 'Organic Putharjhora Green Tea'},\n {value: 'Exotic Assam', text: 'Exotic Assam'},\n {value: 'Davids Mason Jar', text: 'Davids Mason Jar'},\n {value: 'Lemon Ginger Snap', text: 'Lemon Ginger Snap'},\n {value: 'Thé Noir Anglais Breakfast', text: 'Thé Noir Anglais Breakfast'},\n {value: 'China Zhongshan Baiye Oolong 519',\n text: 'China Zhongshan Baiye Oolong 519'},\n {value: 'Organic Premium Green Tea', text: 'Organic Premium Green Tea'},\n {value: 'Cache-Cache', text: 'Cache-Cache'},\n {value: 'Chai Ultra Spice', text: 'Chai Ultra Spice'},\n {value: 'Shaktea Chai Organic', text: 'Shaktea Chai Organic'},\n {value: 'Scent of Mountains Sencha', text: 'Scent of Mountains Sencha'},\n {value: 'Chocolate Tea', text: 'Chocolate Tea'},\n {value: 'Secret Garden', text: 'Secret Garden'},\n {value: 'Menghai Green Brick', text: 'Menghai Green Brick'},\n {value: 'jasmine pearls', text: 'jasmine pearls'},\n {value: 'Vanilla Mint Mate', text: 'Vanilla Mint Mate'},\n {value: 'Huang Guan Yin - 2011 Spring Wuyi Oolong Tea',\n text: 'Huang Guan Yin - 2011 Spring Wuyi Oolong Tea'},\n {value: 'Lemon Sherbet', text: 'Lemon Sherbet'},\n {value: 'Sencha Shot', text: 'Sencha Shot'},\n {value: 'Mango Peach', text: 'Mango Peach'},\n {value: 'Taiwan Jin Xuan Milk Oolong Tea (Flavored)',\n text: 'Taiwan Jin Xuan Milk Oolong Tea (Flavored)'},\n {value: 'Wanja OP Black Tea', text: 'Wanja OP Black Tea'},\n {value: 'Kyoto Cherry Rose', text: 'Kyoto Cherry Rose'},\n {value: 'African Summer', text: 'African Summer'},\n {value: 'Huang Zhi Xiang (Orange Blossom Fragrance)',\n text: 'Huang Zhi Xiang (Orange Blossom Fragrance)'},\n {value: 'Sternenmarkt', text: 'Sternenmarkt'},\n {value: 'Black Dragon', text: 'Black Dragon'},\n {value: 'Lavender Oolong', text: 'Lavender Oolong'},\n {value: 'TJ10: Japanese Sencha', text: 'TJ10: Japanese Sencha'},\n {value: 'Pecan Tart', text: 'Pecan Tart'},\n {value: 'Peppermint Bark', text: 'Peppermint Bark'},\n {value: 'Gao Shan Lao Cong Shui Xian',\n text: 'Gao Shan Lao Cong Shui Xian'},\n {value: 'Organic Uji Gyokuro Gokou', text: 'Organic Uji Gyokuro Gokou'},\n {value: 'Green Tea with Citrus - To Go',\n text: 'Green Tea with Citrus - To Go'},\n {value: 'Organic Sunset Sen Cha', text: 'Organic Sunset Sen Cha'},\n {value: 'Chinese Matcha Tea', text: 'Chinese Matcha Tea'},\n {value: 'Jasmin Mandarin Special Grade',\n text: 'Jasmin Mandarin Special Grade'},\n {value: 'Tea Loves Coffee', text: 'Tea Loves Coffee'},\n {value: 'Premium Dragon Well Long Jing Green Tea',\n text: 'Premium Dragon Well Long Jing Green Tea'},\n {value: 'Tropical Peony', text: 'Tropical Peony'},\n {value: 'Premium Taiping Monkeys Pick Green Tea',\n text: 'Premium Taiping Monkeys Pick Green Tea'},\n {value: 'Gao Shan Zhai 2012 Spring', text: 'Gao Shan Zhai 2012 Spring'},\n {value: 'Mi Lan Dancong Black', text: 'Mi Lan Dancong Black'},\n {value: 'Dorian Grey Blend Loose Leaf Tea',\n text: 'Dorian Grey Blend Loose Leaf Tea'},\n {value: 'Licorice Mint Herbal', text: 'Licorice Mint Herbal'},\n {value: 'Smoked Breakfast', text: 'Smoked Breakfast'},\n {value: 'Monkey Picked Golden Hunan', text: 'Monkey Picked Golden Hunan'},\n {value: 'Earl Grey Organic/Fair Trade',\n text: 'Earl Grey Organic/Fair Trade'},\n {value: 'Xingyang Silk Road Spice', text: 'Xingyang Silk Road Spice'},\n {value: 'Monks Choice', text: 'Monks Choice'},\n {value: 'Spicy Mint Oolong', text: 'Spicy Mint Oolong'},\n {value: 'TenFus Fine White Tea', text: 'TenFus Fine White Tea'},\n {value: 'Tillerman Formosa Yancha', text: 'Tillerman Formosa Yancha'},\n {value: '2008 Wenshan Baozhong Subtropical Forest',\n text: '2008 Wenshan Baozhong Subtropical Forest'},\n {value: 'White Peony with Strawberries',\n text: 'White Peony with Strawberries'},\n {value: 'Darj Poobong White (559)', text: 'Darj Poobong White (559)'},\n {value: 'Lu Shan Yun Wu Green Tea', text: 'Lu Shan Yun Wu Green Tea'},\n {value: 'Sencha (Pyramid Tea Bag)', text: 'Sencha (Pyramid Tea Bag)'},\n {value: 'Gisovu black', text: 'Gisovu black'},\n {value: 'Mangalam FTGBOP1', text: 'Mangalam FTGBOP1'},\n {value: 'Green Tea Latte', text: 'Green Tea Latte'},\n {value: 'Big Apple', text: 'Big Apple'},\n {value: 'Date Nut Muffin Rooibos', text: 'Date Nut Muffin Rooibos'},\n {value: 'Green Times: So Simple So Good',\n text: 'Green Times: So Simple So Good'},\n {value: 'Almond vanilla cream', text: 'Almond vanilla cream'},\n {value: 'Coconut Ginger Calypso Green Tea',\n text: 'Coconut Ginger Calypso Green Tea'},\n {value: 'Crème Brulee', text: 'Crème Brulee'},\n {value: 'Spring Cleaning', text: 'Spring Cleaning'},\n {value: 'Assam - Full Leaf', text: 'Assam - Full Leaf'},\n {value: 'Triple C Tea', text: 'Triple C Tea'},\n {value: 'Plum Spice Oolong', text: 'Plum Spice Oolong'},\n {value: 'China Oolong Buddhas Palm ZO86',\n text: 'China Oolong Buddhas Palm ZO86'},\n {value: '2007 ChenXiang Laocha Pu-erh Tea Brick',\n text: '2007 ChenXiang Laocha Pu-erh Tea Brick'},\n {value: '2012 Xue Ju shu pu-erh with snow chrysanthemum',\n text: '2012 Xue Ju shu pu-erh with snow chrysanthemum'},\n {value: 'Kenya Marinyn', text: 'Kenya Marinyn'},\n {value: 'green tuocha pu-erh', text: 'green tuocha pu-erh'},\n {value: 'Premium Taiwan Oriental Beauty Oolong Tea',\n text: 'Premium Taiwan Oriental Beauty Oolong Tea'},\n {value: 'Orchid Oolong', text: 'Orchid Oolong'},\n {value: 'Toasted Sesame', text: 'Toasted Sesame'},\n {value: 'ingenuiTEA', text: 'ingenuiTEA'},\n {value: 'Wild Mint', text: 'Wild Mint'},\n {value: 'Kagoshima Sencha', text: 'Kagoshima Sencha'},\n {value: 'Kenya GFBOP1 Milma Estate (No. 355)',\n text: 'Kenya GFBOP1 Milma Estate (No. 355)'},\n {value: 'Pom Tango', text: 'Pom Tango'},\n {value: 'Houjicha (Bancha)', text: 'Houjicha (Bancha)'},\n {value: 'Angelwater', text: 'Angelwater'},\n {value: 'Novel Teas', text: 'Novel Teas'},\n {value: 'Madame Butterfly', text: 'Madame Butterfly'},\n {value: 'Concord Grape Bai Mu Dan', text: 'Concord Grape Bai Mu Dan'},\n {value: 'Cinnamon Apple', text: 'Cinnamon Apple'},\n {value: 'HoneyPie', text: 'HoneyPie'},\n {value: 'This Is Berry Delicious', text: 'This Is Berry Delicious'},\n {value: 'Georgian Old Gentleman', text: 'Georgian Old Gentleman'},\n {value: 'Genmai Cha (Organic)', text: 'Genmai Cha (Organic)'},\n {value: 'Moroccan Mint Tea', text: 'Moroccan Mint Tea'},\n {value: 'Assam Majulighur TGFOP', text: 'Assam Majulighur TGFOP'},\n {value: 'Honeybush Vanilla', text: 'Honeybush Vanilla'},\n {value: 'Sencha Gold', text: 'Sencha Gold'},\n {value: 'Supreme Dragon Well', text: 'Supreme Dragon Well'},\n {value: 'Cream Oolong', text: 'Cream Oolong'},\n {value: 'Enchanting White Tea', text: 'Enchanting White Tea'},\n {value: 'First Flush Darjeeling (SFTGFOP-1)',\n text: 'First Flush Darjeeling (SFTGFOP-1)'},\n {value: 'Oksusu Cha (Corn Tea)', text: 'Oksusu Cha (Corn Tea)'},\n {value: 'Berry Chai Infusion', text: 'Berry Chai Infusion'},\n {value: 'Kultainen Omena - Golden Apple',\n text: 'Kultainen Omena - Golden Apple'},\n {value: 'Pomegranate Vanilla Oolong Tea Latte',\n text: 'Pomegranate Vanilla Oolong Tea Latte'},\n {value: 'Earl Grey Black', text: 'Earl Grey Black'},\n {value: 'Pu-erh China Japan Collection',\n text: 'Pu-erh China Japan Collection'},\n {value: 'Tropical Green', text: 'Tropical Green'},\n {value: 'Fujian White Rose', text: 'Fujian White Rose'},\n {value: '2008 Gold Brick Pu-erh', text: '2008 Gold Brick Pu-erh'},\n {value: 'Boysenberry Matcha', text: 'Boysenberry Matcha'},\n {value: 'Green Oolong Tealeaf Powder',\n text: 'Green Oolong Tealeaf Powder'},\n {value: 'Oolong Shalimar', text: 'Oolong Shalimar'},\n {value: 'Sun Kissed Jasmine', text: 'Sun Kissed Jasmine'},\n {value: 'Lapsang Souchong Imperial - Bin 141',\n text: 'Lapsang Souchong Imperial - Bin 141'},\n {value: 'Chocolate Nilgiri Black Tea',\n text: 'Chocolate Nilgiri Black Tea'},\n {value: 'Castleton Moonlight (2011 2nd Flush)',\n text: 'Castleton Moonlight (2011 2nd Flush)'},\n {value: 'Peach', text: 'Peach'},\n {value: 'Ginger Peach Decaf', text: 'Ginger Peach Decaf'},\n {value: 'Ancient Golden Yunnan', text: 'Ancient Golden Yunnan'},\n {value: 'Peach With Pieces (TF73)', text: 'Peach With Pieces (TF73)'},\n {value: 'Rafia', text: 'Rafia'},\n {value: 'Cocoa Praline Tart Rooibos Tea',\n text: 'Cocoa Praline Tart Rooibos Tea'},\n {value: 'Snow Buds (Xue Ya)', text: 'Snow Buds (Xue Ya)'},\n {value: '2004 yong pin hao xiang ming wild arbor raw ra pu-erh tea cake',\n text: '2004 yong pin hao xiang ming wild arbor raw ra pu-erh tea cake'},\n {value: 'Vanilla Berry Truffle', text: 'Vanilla Berry Truffle'},\n {value: 'Harlequin rooibos', text: 'Harlequin rooibos'},\n {value: 'Premium Organic Sencha', text: 'Premium Organic Sencha'},\n {value: 'Rooibos Peach', text: 'Rooibos Peach'},\n {value: 'China Jasmine', text: 'China Jasmine'},\n {value: 'Lapsang Souchong Mainland China Classically smoked',\n text: 'Lapsang Souchong Mainland China Classically smoked'},\n {value: 'Marzipan', text: 'Marzipan'},\n {value: 'White Monkey', text: 'White Monkey'},\n {value: 'Jingmai Arbor(QiaoMu) Pu-erh Tea',\n text: 'Jingmai Arbor(QiaoMu) Pu-erh Tea'},\n {value: 'Mothola Estate White Tea (TA98)',\n text: 'Mothola Estate White Tea (TA98)'},\n {value: 'Black Tea with Raspberries', text: 'Black Tea with Raspberries'},\n {value: 'Mango Magnus', text: 'Mango Magnus'},\n {value: 'Darjeeling Yashodhara FTGFOP1 1st Flush',\n text: 'Darjeeling Yashodhara FTGFOP1 1st Flush'},\n {value: 'Chá preto Ilha dos Amores', text: 'Chá preto Ilha dos Amores'},\n {value: 'MateVana', text: 'MateVana'},\n {value: '2010 Six Famous Tea Mountain Yunnan Moon pu-erh tea cake',\n text: '2010 Six Famous Tea Mountain Yunnan Moon pu-erh tea cake'},\n {value: 'Organic Miyazaki Kamairicha Tsuyobi Shiage',\n text: 'Organic Miyazaki Kamairicha Tsuyobi Shiage'},\n {value: 'Old Version/Replaced - Smores',\n text: 'Old Version/Replaced - Smores'},\n {value: 'Premium Taiwan Milk Oolong * Silk Oolong',\n text: 'Premium Taiwan Milk Oolong * Silk Oolong'},\n {value: 'Lishan Spring 2009', text: 'Lishan Spring 2009'},\n {value: 'Touareg', text: 'Touareg'},\n {value: 'Japan Bancha', text: 'Japan Bancha'},\n {value: 'Goji Berry Pomegranate Green Tea',\n text: 'Goji Berry Pomegranate Green Tea'},\n {value: 'Oolong Châtaigne', text: 'Oolong Châtaigne'},\n {value: 'Apricot Decaf (Fair Trade Certified)',\n text: 'Apricot Decaf (Fair Trade Certified)'},\n {value: 'Scotlands Delight', text: 'Scotlands Delight'},\n {value: 'Caramel Mocha Chai', text: 'Caramel Mocha Chai'},\n {value: 'Tazo Chai Tea Concentrate', text: 'Tazo Chai Tea Concentrate'},\n {value: 'Matcha au Lait Mix - Strawberry',\n text: 'Matcha au Lait Mix - Strawberry'},\n {value: 'Calm', text: 'Calm'},\n {value: 'Winterzeit', text: 'Winterzeit'},\n {value: 'Milima G.F.B.O.P.', text: 'Milima G.F.B.O.P.'},\n {value: 'Lovers Leap', text: 'Lovers Leap'},\n {value: 'Opposites Attract', text: 'Opposites Attract'},\n {value: 'Kokos', text: 'Kokos'},\n {value: 'White Rose', text: 'White Rose'},\n {value: 'Jasmine Rose Fusion', text: 'Jasmine Rose Fusion'},\n {value: 'Sugar Plum Spice', text: 'Sugar Plum Spice'},\n {value: 'Mugwort', text: 'Mugwort'},\n {value: 'Big Red Robe Oolong Supreme (Da Hong Pao)',\n text: 'Big Red Robe Oolong Supreme (Da Hong Pao)'},\n {value: 'Lemongrass Herbal Infusion', text: 'Lemongrass Herbal Infusion'},\n {value: 'Uni Genmaicha', text: 'Uni Genmaicha'},\n {value: 'Fire Jade', text: 'Fire Jade'},\n {value: 'Gold Flake', text: 'Gold Flake'},\n {value: 'White Chocolate Frost', text: 'White Chocolate Frost'},\n {value: 'Orange Blossom White Tea', text: 'Orange Blossom White Tea'},\n {value: 'Feng Qing Premium Black Gold Pearls',\n text: 'Feng Qing Premium Black Gold Pearls'},\n {value: 'Throat Soothers Wellness Tea',\n text: 'Throat Soothers Wellness Tea'},\n {value: '2004 Yiwu Mountain sheng - Puerh raw',\n text: '2004 Yiwu Mountain sheng - Puerh raw'},\n {value: 'Wensan Pouchong', text: 'Wensan Pouchong'},\n {value: 'Organic Decaf English Breakfast Black Tea',\n text: 'Organic Decaf English Breakfast Black Tea'},\n {value: 'Frosted Carrot Cake Genmaicha',\n text: 'Frosted Carrot Cake Genmaicha'},\n {value: 'Dark Forest Blend', text: 'Dark Forest Blend'},\n {value: 'Easy Exotic Blooming Teas', text: 'Easy Exotic Blooming Teas'},\n {value: 'Vanilla Moon', text: 'Vanilla Moon'},\n {value: 'Chocolate Cream Truffles', text: 'Chocolate Cream Truffles'},\n {value: 'Red Velvet Cake', text: 'Red Velvet Cake'},\n {value: 'Darjeeling Tea Avongrove Pearl 2012 White',\n text: 'Darjeeling Tea Avongrove Pearl 2012 White'},\n {value: 'House Chai', text: 'House Chai'},\n {value: 'Bai Hao', text: 'Bai Hao'},\n {value: '2003 Chens Reserve', text: '2003 Chens Reserve'},\n {value: 'Samovar OP-A Blend (ZB28)', text: 'Samovar OP-A Blend (ZB28)'},\n {value: 'Bombay Chai', text: 'Bombay Chai'},\n {value: 'Jasmine Dragon Teas', text: 'Jasmine Dragon Teas'},\n {value: 'Premium', text: 'Premium'},\n {value: 'Fujian Province Yin Lan Zao',\n text: 'Fujian Province Yin Lan Zao'},\n {value: 'Thé Vert Marco Polo', text: 'Thé Vert Marco Polo'},\n {value: 'boldo', text: 'boldo'},\n {value: '2011 EoT Nannuo Puerh Tea', text: '2011 EoT Nannuo Puerh Tea'},\n {value: 'Sadaf Special Blend with Earl Grey',\n text: 'Sadaf Special Blend with Earl Grey'},\n {value: 'Houji-Cha Roasted (Traditional Series)',\n text: 'Houji-Cha Roasted (Traditional Series)'},\n {value: 'Queen of Hearts', text: 'Queen of Hearts'},\n {value: 'Sencha Special Hika', text: 'Sencha Special Hika'},\n {value: 'Her Majestys Blend', text: 'Her Majestys Blend'},\n {value: 'Assam SF Budla Beta', text: 'Assam SF Budla Beta'},\n {value: 'Organic Darjeeling', text: 'Organic Darjeeling'},\n {value: 'Sacher Blend - TE22', text: 'Sacher Blend - TE22'},\n {value: 'Spearmint', text: 'Spearmint'},\n {value: 'Sencha Hawaii', text: 'Sencha Hawaii'},\n {value: 'Cancer Fighting Tea', text: 'Cancer Fighting Tea'},\n {value: 'Young Hyson', text: 'Young Hyson'},\n {value: 'Pineapple Oolong', text: 'Pineapple Oolong'},\n {value: 'Huang Jin Bolero', text: 'Huang Jin Bolero'},\n {value: 'Doğadan Adaçayı (Dogadan Sage Tea)',\n text: 'Doğadan Adaçayı (Dogadan Sage Tea)'},\n {value: 'El Dorado Chai', text: 'El Dorado Chai'},\n {value: 'Mandarin Orange Spice', text: 'Mandarin Orange Spice'},\n {value: 'Tung Ting Jade', text: 'Tung Ting Jade'},\n {value: 'Heath® Bar Chocolate Toffee Black Tea',\n text: 'Heath® Bar Chocolate Toffee Black Tea'},\n {value: 'First Flush 2009 Darjeeling Glenburn estate',\n text: 'First Flush 2009 Darjeeling Glenburn estate'},\n {value: 'Sencha of the Earth', text: 'Sencha of the Earth'},\n {value: 'Moms Blend', text: 'Moms Blend'},\n {value: 'Mango Chili Raw Green Bush Tea',\n text: 'Mango Chili Raw Green Bush Tea'},\n {value: 'Sweet Nothings', text: 'Sweet Nothings'},\n {value: '2005 Xiaguan Wild Tree Raw Pu Er Tea Cake',\n text: '2005 Xiaguan Wild Tree Raw Pu Er Tea Cake'},\n {value: 'SororiTEA Sisters Special Blend',\n text: 'SororiTEA Sisters Special Blend'},\n {value: 'Organic Golden Peach Tea', text: 'Organic Golden Peach Tea'},\n {value: 'Organic Holiday Spice Black Tea',\n text: 'Organic Holiday Spice Black Tea'},\n {value: 'Special Blend', text: 'Special Blend'},\n {value: 'Rooibush Strawberry Pepper', text: 'Rooibush Strawberry Pepper'},\n {value: 'White Peony (Bai Mu Dan)', text: 'White Peony (Bai Mu Dan)'},\n {value: 'Winter Chai', text: 'Winter Chai'},\n {value: 'Daughter Ring', text: 'Daughter Ring'},\n {value: 'Green Tea with Dillseed', text: 'Green Tea with Dillseed'},\n {value: 'Je tAime', text: 'Je tAime'},\n {value: 'Second Breakfast', text: 'Second Breakfast'},\n {value: 'Golden Monkey (Reserve)', text: 'Golden Monkey (Reserve)'},\n {value: 'Assam Mangalam TGFOP1', text: 'Assam Mangalam TGFOP1'},\n {value: 'Silver Needle King', text: 'Silver Needle King'},\n {value: 'Lung-Ching Special Grade (ZG61)',\n text: 'Lung-Ching Special Grade (ZG61)'},\n {value: 'Coconut Custard', text: 'Coconut Custard'},\n {value: 'Thé des Amants', text: 'Thé des Amants'},\n {value: 'Golden Jade', text: 'Golden Jade'},\n {value: 'Dewy Cherry', text: 'Dewy Cherry'},\n {value: 'Baimidan Reserve Darjeeling',\n text: 'Baimidan Reserve Darjeeling'},\n {value: 'Honeydew', text: 'Honeydew'},\n {value: 'Zealong Dark', text: 'Zealong Dark'},\n {value: 'Laoshan Black Chocolate Genmaicha',\n text: 'Laoshan Black Chocolate Genmaicha'},\n {value: 'Spiced Green', text: 'Spiced Green'},\n {value: 'Yunnan Golden Silk', text: 'Yunnan Golden Silk'},\n {value: 'Vanilla Black', text: 'Vanilla Black'},\n {value: 'Silver Tips Imperial Darjeeling',\n text: 'Silver Tips Imperial Darjeeling'},\n {value: '1999 Yi Wu Cooked Brick', text: '1999 Yi Wu Cooked Brick'},\n {value: 'Shou Coin (organic)', text: 'Shou Coin (organic)'},\n {value: 'Blood Orange Fruit Tisane', text: 'Blood Orange Fruit Tisane'},\n {value: 'Black Apple Pie', text: 'Black Apple Pie'},\n {value: 'Sparrow Tongue Yellow Tea', text: 'Sparrow Tongue Yellow Tea'},\n {value: '2009 Winter Ruby Black Tea - Taiwan Black Tea',\n text: '2009 Winter Ruby Black Tea - Taiwan Black Tea'},\n {value: 'Orange Flower Oolong', text: 'Orange Flower Oolong'},\n {value: 'Mango-Papaya', text: 'Mango-Papaya'},\n {value: 'Green Tea Strawberry Vanilla',\n text: 'Green Tea Strawberry Vanilla'},\n {value: '2010 Spring Tie Guan Yin - Diamond Grade - Anxi Oolong Tea',\n text: '2010 Spring Tie Guan Yin - Diamond Grade - Anxi Oolong Tea'},\n {value: 'Brandons Snickerdoodle Black Tea',\n text: 'Brandons Snickerdoodle Black Tea'},\n {value: 'Coconut Red', text: 'Coconut Red'},\n {value: 'Ginger and Sweet Orange', text: 'Ginger and Sweet Orange'},\n {value: 'Pasir Nangka OP (TI70)', text: 'Pasir Nangka OP (TI70)'},\n {value: 'Orange Rooibos', text: 'Orange Rooibos'},\n {value: 'Prosperous Peach Oolong', text: 'Prosperous Peach Oolong'},\n {value: 'Mangalam Full-Leaf', text: 'Mangalam Full-Leaf'},\n {value: 'Jasmine Mint', text: 'Jasmine Mint'},\n {value: 'Mint Pu-erh', text: 'Mint Pu-erh'},\n {value: 'Black Beauty', text: 'Black Beauty'},\n {value: 'Apple Sencha', text: 'Apple Sencha'},\n {value: 'Sweet Ginger Peach Black Tea',\n text: 'Sweet Ginger Peach Black Tea'},\n {value: 'Assam Showdown', text: 'Assam Showdown'},\n {value: 'Wild Raspberry', text: 'Wild Raspberry'},\n {value: 'Organic Kukicha', text: 'Organic Kukicha'},\n {value: 'Amarettini', text: 'Amarettini'},\n {value: 'Tieguanyin', text: 'Tieguanyin'},\n {value: 'Ginger Citrus Guayusa', text: 'Ginger Citrus Guayusa'},\n {value: 'Jade Oolong Four Seasons Spring',\n text: 'Jade Oolong Four Seasons Spring'},\n {value: 'Rose Marzipan', text: 'Rose Marzipan'},\n {value: 'Fairtrade Extra Strong teabags',\n text: 'Fairtrade Extra Strong teabags'},\n {value: 'Gyokuro Konacha', text: 'Gyokuro Konacha'},\n {value: 'Bai Mu Dan (White Peony)', text: 'Bai Mu Dan (White Peony)'},\n {value: 'Ming Qian Dragonwell Panan 2011',\n text: 'Ming Qian Dragonwell Panan 2011'},\n {value: 'Organic Taimu Maojian Green Tea',\n text: 'Organic Taimu Maojian Green Tea'},\n {value: 'White Orchard', text: 'White Orchard'},\n {value: '145 gram Mengku Ripe Mini Cake 2006',\n text: '145 gram Mengku Ripe Mini Cake 2006'},\n {value: 'Wu Cha Oolong', text: 'Wu Cha Oolong'},\n {value: 'Ginger Bread Cookie', text: 'Ginger Bread Cookie'},\n {value: 'Lemon', text: 'Lemon'},\n {value: 'Get Lost - No. 6 (Wellness Collection)',\n text: 'Get Lost - No. 6 (Wellness Collection)'},\n {value: 'Organic Ginger', text: 'Organic Ginger'},\n {value: 'Finest Earl Grey (TE20)', text: 'Finest Earl Grey (TE20)'},\n {value: 'Birthday Cake', text: 'Birthday Cake'},\n {value: 'Assam silver needle', text: 'Assam silver needle'},\n {value: 'Organic Moroccan Mint Green Tea',\n text: 'Organic Moroccan Mint Green Tea'},\n {value: 'Kenya Pekoe', text: 'Kenya Pekoe'},\n {value: 'Ti Kuan Yin (monkey picked)',\n text: 'Ti Kuan Yin (monkey picked)'},\n {value: 'Elder Grove', text: 'Elder Grove'},\n {value: 'Ceylon 1', text: 'Ceylon 1'},\n {value: 'Mini bowls cooked', text: 'Mini bowls cooked'},\n {value: 'Mango Red Bubble Tea', text: 'Mango Red Bubble Tea'},\n {value: 'Lemon Crème Parfait', text: 'Lemon Crème Parfait'},\n {value: 'Tarajulie 2nd Flush Assam', text: 'Tarajulie 2nd Flush Assam'},\n {value: 'Peter Hale Blend', text: 'Peter Hale Blend'},\n {value: 'Green apple', text: 'Green apple'},\n {value: 'Golden Jasmine', text: 'Golden Jasmine'},\n {value: '2005 Guan Zi Zai Sheng Yi Wu Jing Xuan Ancient Tea Cake',\n text: '2005 Guan Zi Zai Sheng Yi Wu Jing Xuan Ancient Tea Cake'},\n {value: 'Apple Rosehip', text: 'Apple Rosehip'},\n {value: 'Chai Black', text: 'Chai Black'},\n {value: 'Flowery Earl Grey', text: 'Flowery Earl Grey'},\n {value: 'Tiger Hill Nilgiri', text: 'Tiger Hill Nilgiri'},\n {value: 'Ginger Peach Flavored Black Tea',\n text: 'Ginger Peach Flavored Black Tea'},\n {value: '2008 Menghai Dayi Red Makeup Pu-erh Tea Cake',\n text: '2008 Menghai Dayi Red Makeup Pu-erh Tea Cake'},\n {value: 'Ali Shan Oolong Tea (Taiwan Ali Shan Wu Long)',\n text: 'Ali Shan Oolong Tea (Taiwan Ali Shan Wu Long)'},\n {value: 'Maple Sugar', text: 'Maple Sugar'},\n {value: 'Cancer Fighting Tea - Lavender',\n text: 'Cancer Fighting Tea - Lavender'},\n {value: 'Yun Shan Yin Zhen', text: 'Yun Shan Yin Zhen'},\n {value: 'Hibiscus Berry Punch', text: 'Hibiscus Berry Punch'},\n {value: 'Aged Song Zhong Dan Cong', text: 'Aged Song Zhong Dan Cong'},\n {value: 'Blueberry Creme', text: 'Blueberry Creme'},\n {value: 'Happy Tummy', text: 'Happy Tummy'},\n {value: 'Khongea Golden Tippy Assam', text: 'Khongea Golden Tippy Assam'},\n {value: 'Young Puerh', text: 'Young Puerh'},\n {value: 'Weihnachts-Tee', text: 'Weihnachts-Tee'},\n {value: 'Thai Tea Blend', text: 'Thai Tea Blend'},\n {value: 'Fang Cha Pu-erh', text: 'Fang Cha Pu-erh'},\n {value: 'Fleur de Geisha', text: 'Fleur de Geisha'},\n {value: 'TB14: Scottish Breakfast Blend',\n text: 'TB14: Scottish Breakfast Blend'},\n {value: 'Keemun Panda 1', text: 'Keemun Panda 1'},\n {value: 'Decaf Vanilla Chai', text: 'Decaf Vanilla Chai'},\n {value: 'Winter Sunnier', text: 'Winter Sunnier'},\n {value: 'East Friesen', text: 'East Friesen'},\n {value: 'Black Currant Tea', text: 'Black Currant Tea'},\n {value: 'Shoo Fly Pie Coffee', text: 'Shoo Fly Pie Coffee'},\n {value: 'Vanilla and Cinnamon Black Tea',\n text: 'Vanilla and Cinnamon Black Tea'},\n {value: 'White Coconut Blondie', text: 'White Coconut Blondie'},\n {value: 'Ilam', text: 'Ilam'},\n {value: 'The Vanilla Marshmallow', text: 'The Vanilla Marshmallow'},\n {value: 'Sencha Premium', text: 'Sencha Premium'},\n {value: 'Makinohara Sencha', text: 'Makinohara Sencha'},\n {value: 'Yunnan Gold Tips (Limited Edition Chinese New Year 2014)',\n text: 'Yunnan Gold Tips (Limited Edition Chinese New Year 2014)'},\n {value: 'Joy', text: 'Joy'},\n {value: 'Decaf Raspberry', text: 'Decaf Raspberry'},\n {value: 'Mini Artisan Pu-erh Hearts', text: 'Mini Artisan Pu-erh Hearts'},\n {value: 'London Fog', text: 'London Fog'},\n {value: 'Assam Satrupa Estate', text: 'Assam Satrupa Estate'},\n {value: 'Casablanca', text: 'Casablanca'},\n {value: 'Gingerbread Cream Tea', text: 'Gingerbread Cream Tea'},\n {value: 'Basils Brew', text: 'Basils Brew'},\n {value: 'Darjeeling Nr. 9 TGFOP 1 Himalaya First Flush',\n text: 'Darjeeling Nr. 9 TGFOP 1 Himalaya First Flush'},\n {value: 'White Buds Bai Ya Cha Organic Fair Trade White Tea',\n text: 'White Buds Bai Ya Cha Organic Fair Trade White Tea'},\n {value: 'Organic Orange Rooibos', text: 'Organic Orange Rooibos'},\n {value: 'Silver Needle Reserve', text: 'Silver Needle Reserve'},\n {value: 'Apple Cinnamon Coffeecake', text: 'Apple Cinnamon Coffeecake'},\n {value: 'Laoshan Village Chai (summer)',\n text: 'Laoshan Village Chai (summer)'},\n {value: 'Tie Guan Yin (mild)', text: 'Tie Guan Yin (mild)'},\n {value: 'Mormon Tea', text: 'Mormon Tea'},\n {value: 'Betty Basic', text: 'Betty Basic'},\n {value: 'TP40: Rose Congou', text: 'TP40: Rose Congou'},\n {value: 'White Ambrosia', text: 'White Ambrosia'},\n {value: 'Amilla Rooibos Chai', text: 'Amilla Rooibos Chai'},\n {value: 'Tarocco Ruby Orange', text: 'Tarocco Ruby Orange'},\n {value: 'Violet Pouchong', text: 'Violet Pouchong'},\n {value: 'A Love Affair', text: 'A Love Affair'},\n {value: 'Happy Kombucha', text: 'Happy Kombucha'},\n {value: 'Plum', text: 'Plum'},\n {value: 'Tiramisu Treviso', text: 'Tiramisu Treviso'},\n {value: 'Aussie Green', text: 'Aussie Green'},\n {value: 'Palanquin Spiced Tea (Masala Chai)',\n text: 'Palanquin Spiced Tea (Masala Chai)'},\n {value: 'Passion Fruit', text: 'Passion Fruit'},\n {value: 'Organic Plum Oolong Tea', text: 'Organic Plum Oolong Tea'},\n {value: 'Tie Guan Yin (Iron Goddess)',\n text: 'Tie Guan Yin (Iron Goddess)'},\n {value: 'Echinacea Complete Care Wellness Tea',\n text: 'Echinacea Complete Care Wellness Tea'},\n {value: 'Semi-Wild Yulan Dancong Early Autumn 2011',\n text: 'Semi-Wild Yulan Dancong Early Autumn 2011'},\n {value: 'Zoubrovka', text: 'Zoubrovka'},\n {value: 'Assam Harishpur Estate FTGFOP1 CL',\n text: 'Assam Harishpur Estate FTGFOP1 CL'},\n {value: 'Gotcha Matcha Cafe Grade Matcha Tea',\n text: 'Gotcha Matcha Cafe Grade Matcha Tea'},\n {value: 'Organic Ceylon Rose', text: 'Organic Ceylon Rose'},\n {value: 'Blueberry Superfruit', text: 'Blueberry Superfruit'},\n {value: 'Coconut Almond Rooibos', text: 'Coconut Almond Rooibos'},\n {value: 'Zen', text: 'Zen'},\n {value: 'Dong Ding (Tung Ting)', text: 'Dong Ding (Tung Ting)'},\n {value: 'Chai Tea', text: 'Chai Tea'},\n {value: 'Sen-Cha Select (Blenders Series)',\n text: 'Sen-Cha Select (Blenders Series)'},\n {value: '1978 Vintage Dan Cong', text: '1978 Vintage Dan Cong'},\n {value: 'Candy Cane Lane', text: 'Candy Cane Lane'},\n {value: '2009 Lancang Gu Cha 0081 Jing Mai Ripe Tea cake',\n text: '2009 Lancang Gu Cha 0081 Jing Mai Ripe Tea cake'},\n {value: 'Almond Rocker Rooibos', text: 'Almond Rocker Rooibos'},\n {value: 'Last Century Pu-Erh (599)', text: 'Last Century Pu-Erh (599)'},\n {value: 'South of the Border Chocolate Tea',\n text: 'South of the Border Chocolate Tea'},\n {value: 'English Tradition Black Tea',\n text: 'English Tradition Black Tea'},\n {value: 'Green Tango', text: 'Green Tango'},\n {value: 'Organic Orange Spice Rooibos',\n text: 'Organic Orange Spice Rooibos'},\n {value: 'Vietnam FBOP Black Lion', text: 'Vietnam FBOP Black Lion'},\n {value: 'Malted Genmaicha', text: 'Malted Genmaicha'},\n {value: 'Mango Black Tea', text: 'Mango Black Tea'},\n {value: 'Pumpkin Pie Black', text: 'Pumpkin Pie Black'},\n {value: 'Toffee Delight', text: 'Toffee Delight'},\n {value: 'Earl Grey Impérial', text: 'Earl Grey Impérial'},\n {value: 'Pure Happiness', text: 'Pure Happiness'},\n {value: '90s Pu-erh Brick', text: '90s Pu-erh Brick'},\n {value: 'Big Red Robe Da Hong Pao', text: 'Big Red Robe Da Hong Pao'},\n {value: 'Caramel Apple - Discontinued',\n text: 'Caramel Apple - Discontinued'},\n {value: 'English Tea Blend', text: 'English Tea Blend'},\n {value: 'Mist Valley SFTGFOP Second Flush',\n text: 'Mist Valley SFTGFOP Second Flush'},\n {value: 'Wild Huckleberry Tea', text: 'Wild Huckleberry Tea'},\n {value: 'Organic Jade Sword Green Tea (Mao Jian)',\n text: 'Organic Jade Sword Green Tea (Mao Jian)'},\n {value: 'Aged Pumpkin Rum Puerh', text: 'Aged Pumpkin Rum Puerh'},\n {value: 'Brioche &amp; Choco*Late', text: 'Brioche &amp; Choco*Late'},\n {value: 'Pu-erh Loose Tea', text: 'Pu-erh Loose Tea'},\n {value: 'Jasmine Lovers', text: 'Jasmine Lovers'},\n {value: 'Coco Chai Rooibos', text: 'Coco Chai Rooibos'},\n {value: 'Darjeeling Chai', text: 'Darjeeling Chai'},\n {value: 'Kali Cha', text: 'Kali Cha'},\n {value: '2011 Thurbo FTGFOP 1 CL - EX 5',\n text: '2011 Thurbo FTGFOP 1 CL - EX 5'},\n {value: 'Rooibos Vanilla &amp; Pear', text: 'Rooibos Vanilla Pear'},\n {value: 'Matcha Jobetsugi (Thin Grade)',\n text: 'Matcha Jobetsugi (Thin Grade)'},\n {value: 'Passionfruit Jasmine', text: 'Passionfruit Jasmine'},\n {value: 'Caramel Vanilla Assam', text: 'Caramel Vanilla Assam'},\n {value: 'Keemun Congfu', text: 'Keemun Congfu'},\n {value: '2011 First Flush Darjeeling Marybong Estate',\n text: '2011 First Flush Darjeeling Marybong Estate'},\n {value: 'Meng Ding Gan Lu', text: 'Meng Ding Gan Lu'},\n {value: 'Mr. Morgans Tea', text: 'Mr. Morgans Tea'},\n {value: 'Cold Comfort', text: 'Cold Comfort'},\n {value: 'Darjeeling Makaibari', text: 'Darjeeling Makaibari'},\n {value: 'Genmaicha (GJ02)', text: 'Genmaicha (GJ02)'},\n {value: 'Kenilworth Ceylon Estate', text: 'Kenilworth Ceylon Estate'},\n {value: 'Moriartea (Blend)', text: 'Moriartea (Blend)'},\n {value: 'Libra (The Zodiac Series)', text: 'Libra (The Zodiac Series)'},\n {value: 'Rooibos Strawberry Cream', text: 'Rooibos Strawberry Cream'},\n {value: 'Jun Mee Golden Tip', text: 'Jun Mee Golden Tip'},\n {value: 'Kyoto Rice', text: 'Kyoto Rice'},\n {value: '2005 Menghai Jinzhen Bulang Mountain Wild Raw',\n text: '2005 Menghai Jinzhen Bulang Mountain Wild Raw'},\n {value: 'Oregon Chai Energía Herbal Chai',\n text: 'Oregon Chai Energía Herbal Chai'},\n {value: 'Mocha Rocha Rooibos', text: 'Mocha Rocha Rooibos'},\n {value: 'African Red Bush', text: 'African Red Bush'},\n {value: 'Mandarin Puer', text: 'Mandarin Puer'},\n {value: 'Fountain Blend', text: 'Fountain Blend'},\n {value: 'Powdered Sencha (1.07 oz)', text: 'Powdered Sencha (1.07 oz)'},\n {value: 'Pacific Sunrise', text: 'Pacific Sunrise'},\n {value: 'Cherry Sencha', text: 'Cherry Sencha'},\n {value: '2009 Mengku Jade Dew Raw 400g',\n text: '2009 Mengku Jade Dew Raw'},\n {value: '761 Rooibos Cream/Caramel', text: '761 Rooibos Cream/Caramel'},\n {value: 'Harmutty STGFOP 1 CL', text: 'Harmutty STGFOP 1 CL'},\n {value: 'Lung Ching', text: 'Lung Ching'},\n {value: 'Ying De Hong', text: 'Ying De Hong'},\n {value: 'Organic Miyazaki Oolong Tea Baisen',\n text: 'Organic Miyazaki Oolong Tea Baisen'},\n {value: 'Cochin Masala Chai', text: 'Cochin Masala Chai'},\n {value: 'Mate Chai', text: 'Mate Chai'},\n {value: 'Mate Lemon Blast', text: 'Mate Lemon Blast'},\n {value: 'Jasmine Oolong', text: 'Jasmine Oolong'},\n {value: 'Fruit Cocktail Green Tea', text: 'Fruit Cocktail Green Tea'},\n {value: 'Terrific Toffee', text: 'Terrific Toffee'},\n {value: 'Shan Lin Xi High Mountain Oolong',\n text: 'Shan Lin Xi High Mountain Oolong'},\n {value: 'Ultimate Chocolate Rooibos', text: 'Ultimate Chocolate Rooibos'},\n {value: 'Iron Goddess of Mercy - Ti Kuan Yin - Green',\n text: 'Iron Goddess of Mercy - Ti Kuan Yin - Green'},\n {value: 'Kambaa', text: 'Kambaa'},\n {value: 'TJ80: Gyokuro', text: 'TJ80: Gyokuro'},\n {value: 'Lady Grey', text: 'Lady Grey'},\n {value: 'Ginger Peach Apricot', text: 'Ginger Peach Apricot'},\n {value: 'Canadian Breakfast', text: 'Canadian Breakfast'},\n {value: 'Pomegranate Black Tea', text: 'Pomegranate Black Tea'},\n {value: 'French Breakfast Tea', text: 'French Breakfast Tea'},\n {value: 'Coconut Macadamia', text: 'Coconut Macadamia'},\n {value: 'Asmachilca', text: 'Asmachilca'},\n {value: 'White Chocolate Mousse Tea', text: 'White Chocolate Mousse Tea'},\n {value: 'Absolutely Apricot', text: 'Absolutely Apricot'},\n {value: 'Earl Grey Tea Latte', text: 'Earl Grey Tea Latte'},\n {value: 'Tetley Tea Bag', text: 'Tetley Tea Bag'},\n {value: 'Gunpowder Imperial Pinhead Spring 2009 organic',\n text: 'Gunpowder Imperial Pinhead Spring 2009 organic'},\n {value: 'Jade Bamboo', text: 'Jade Bamboo'},\n {value: 'Organic &amp; Fair Trade Quilan Oolong',\n text: 'Organic &amp; Fair Trade Quilan Oolong'},\n {value: 'Mangosteen Green with Matcha',\n text: 'Mangosteen Green with Matcha'},\n {value: 'Willow', text: 'Willow'},\n {value: 'Black Tie-Guan-Yin (ZK58)', text: 'Black Tie-Guan-Yin (ZK58)'},\n {value: 'Indonesian', text: 'Indonesian'},\n {value: 'Persian Earl Grey', text: 'Persian Earl Grey'},\n {value: 'Green Tea &amp; Blackcurrant',\n text: 'Green Tea &amp; Blackcurrant'},\n {value: 'Mint Mix', text: 'Mint Mix'},\n {value: 'Kenilworth Estate Ceylon', text: 'Kenilworth Estate Ceylon'},\n {value: 'Mainland China Oolong', text: 'Mainland China Oolong'},\n {value: '2010 Fancy Tie Guan Yin of Anxi',\n text: '2010 Fancy Tie Guan Yin of Anxi'},\n {value: 'Tazo® Chai Tea Latte', text: 'Tazo® Chai Tea Latte'},\n {value: 'The Loraxs Truffula Tree Tea',\n text: 'The Loraxs Truffula Tree Tea'},\n {value: 'Oolong Berry', text: 'Oolong Berry'},\n {value: 'Utopian Jewel', text: 'Utopian Jewel'},\n {value: 'Competition-Grade Tiě Guān Yīn',\n text: 'Competition-Grade Tiě Guān Yīn'},\n {value: 'Neapolitan Honeybush', text: 'Neapolitan Honeybush'},\n {value: 'Tropical Solstice', text: 'Tropical Solstice'},\n {value: 'Infusão Equador', text: 'Infusão Equador'},\n {value: 'Summer Breeze', text: 'Summer Breeze'},\n {value: 'Movie Night', text: 'Movie Night'},\n {value: 'Paris Ginza', text: 'Paris Ginza'},\n {value: 'Matcha Lychee', text: 'Matcha Lychee'},\n {value: '2007 Yong De Ecological Old Tree Ripe Cake',\n text: '2007 Yong De Ecological Old Tree Ripe Cake'},\n {value: 'Christmas Tradition', text: 'Christmas Tradition'},\n {value: 'Dragon Eye Oolong', text: 'Dragon Eye Oolong'},\n {value: 'Chai With Chocolate', text: 'Chai With Chocolate'},\n {value: 'Phoenix 1 Iron Goddess Oolong',\n text: 'Phoenix 1 Iron Goddess Oolong'},\n {value: 'Plum Oolong Tea Blend', text: 'Plum Oolong Tea Blend'},\n {value: 'Nilgiri OP', text: 'Nilgiri OP'},\n {value: 'Chocolate Orange', text: 'Chocolate Orange'},\n {value: 'Lemon Blossom Herbal', text: 'Lemon Blossom Herbal'},\n {value: 'No. 67 Meadow', text: 'No. 67 Meadow'},\n {value: 'Sweet Cherry White', text: 'Sweet Cherry White'},\n {value: 'Yame Gyokuro', text: 'Yame Gyokuro'},\n {value: 'Love Amber Rose', text: 'Love Amber Rose'},\n {value: 'Houjicha', text: 'Houjicha'},\n {value: 'Keemun Mao Fen', text: 'Keemun Mao Fen'},\n {value: 'White Tea Ceylon Silver Tips',\n text: 'White Tea Ceylon Silver Tips'},\n {value: 'Sikkim Temi', text: 'Sikkim Temi'},\n {value: 'Pu-Erh', text: 'Pu-Erh'},\n {value: 'Razzleberry Genmaicha', text: 'Razzleberry Genmaicha'},\n {value: 'tsa2 Seasons Pick Leafy Black Tea Organic ( Columbian )',\n text: 'tsa2 Seasons Pick Leafy Black Tea Organic ( Columbian )'},\n {value: 'Organic Mint Melange', text: 'Organic Mint Melange'},\n {value: 'Vietnam Oolong 4 season', text: 'Vietnam Oolong 4 season'},\n {value: 'Tie Guan Yin Grade II Modern Green Style',\n text: 'Tie Guan Yin Grade II Modern Green Style'},\n {value: 'Fancy Holidays Tea', text: 'Fancy Holidays Tea'},\n {value: 'Thai Ice Tea Mix', text: 'Thai Ice Tea Mix'},\n {value: 'No. 05 Ali Shan Oolong', text: 'No. 05 Ali Shan Oolong'},\n {value: 'Coconut Blossom', text: 'Coconut Blossom'},\n {value: 'Topsy Turvy Tea Blend', text: 'Topsy Turvy Tea Blend'},\n {value: 'China Rose Congou', text: 'China Rose Congou'},\n {value: 'Strawberry Passion', text: 'Strawberry Passion'},\n {value: 'CTC Assam', text: 'CTC Assam'},\n {value: '2010 Hai Lang Hao Lasting Fragrance Yi Wu Wild Arbor',\n text: '2010 Hai Lang Hao Lasting Fragrance Yi Wu Wild Arbor'},\n {value: 'Senchamental', text: 'Senchamental'},\n {value: 'Cui Yu', text: 'Cui Yu'},\n {value: 'Tea Sampler Gift Box by Tazo Tea',\n text: 'Tea Sampler Gift Box by Tazo Tea'},\n {value: 'Autumn Spice', text: 'Autumn Spice'},\n {value: 'Shui Xian Wuyi Oolong', text: 'Shui Xian Wuyi Oolong'},\n {value: 'Assam Kalgar BOP', text: 'Assam Kalgar BOP'},\n {value: 'Soureni Estate FTGFOP1 Cl. Spl. Second Flush (DJ-50)',\n text: 'Soureni Estate FTGFOP1 Cl. Spl. Second Flush (DJ-50)'},\n {value: 'Prairie Berry', text: 'Prairie Berry'},\n {value: 'Valkoinen Usva - White Mist',\n text: 'Valkoinen Usva - White Mist'},\n {value: 'Darjeeling Noble SFTGFOP1 First Flush',\n text: 'Darjeeling Noble SFTGFOP1 First Flush'},\n {value: 'Sweet Harvest Pumpkin', text: 'Sweet Harvest Pumpkin'},\n {value: 'Jasmine Dragon Phoenix Pearls',\n text: 'Jasmine Dragon Phoenix Pearls'},\n {value: 'Tikuanyin Traditional', text: 'Tikuanyin Traditional'},\n {value: 'Green Tea &amp; Mint', text: 'Green Tea &amp; Mint'},\n {value: 'Pheonix Mountain Dan Cong', text: 'Pheonix Mountain Dan Cong'},\n {value: 'Asian Jasmine White Tea', text: 'Asian Jasmine White Tea'},\n {value: 'Chai On Life', text: 'Chai On Life'},\n {value: 'nhs freeze dried instant tea granules',\n text: 'nhs freeze dried instant tea granules'},\n {value: 'Organic Ti Kuan Yin Oolong Tea',\n text: 'Organic Ti Kuan Yin Oolong Tea'},\n {value: '2008 Fuhai 7568 Pu-erh Tea Cake',\n text: '2008 Fuhai 7568 Pu-erh Tea Cake'},\n {value: 'Wild Elephant Valley AAA Organic Green Tea',\n text: 'Wild Elephant Valley AAA Organic Green Tea'},\n {value: 'Peppermint Patty', text: 'Peppermint Patty'},\n {value: 'Earl Grey Creme', text: 'Earl Grey Creme'},\n {value: 'Pu-Erh Tea', text: 'Pu-Erh Tea'},\n {value: 'Raspberry Green Tea', text: 'Raspberry Green Tea'},\n {value: 'Assam Gingia', text: 'Assam Gingia'},\n {value: 'rooibos durban', text: 'rooibos durban'},\n {value: 'Melange Rooibos', text: 'Melange Rooibos'},\n {value: 'Pussimbing Autumnal Darjeeling 2010 [Out of Stock]',\n text: 'Pussimbing Autumnal Darjeeling 2010 [Out of Stock]'},\n {value: 'Heavenly Oolong', text: 'Heavenly Oolong'},\n {value: 'Jasmine Downy Pearls', text: 'Jasmine Downy Pearls'},\n {value: 'Not A Rabbit', text: 'Not A Rabbit'},\n {value: 'Well Hello 40s', text: 'Well Hello 40s'},\n {value: 'White Velvet', text: 'White Velvet'},\n {value: '2006 Mengku Imperial Ripen Cake',\n text: '2006 Mengku Imperial Ripen Cake'},\n {value: 'Skin DeTox', text: 'Skin DeTox'},\n {value: 'Café Latte', text: 'Café Latte'},\n {value: 'Peppermint &amp; Lemon', text: 'Peppermint &amp; Lemon'},\n {value: 'Vienna Green', text: 'Vienna Green'},\n {value: 'Anji Bai Cha - Wild-growing Handmade Premium Green Tea',\n text: 'Anji Bai Cha - Wild-growing Handmade Premium Green Tea'},\n {value: 'Yunnan Gold Black Tea (Yunnan Dian Hong)',\n text: 'Yunnan Gold Black Tea (Yunnan Dian Hong)'},\n {value: 'Thomas Sampson', text: 'Thomas Sampson'},\n {value: 'White Chocolate Grasshopper Honeybush',\n text: 'White Chocolate Grasshopper Honeybush'},\n {value: 'Raspberry Black', text: 'Raspberry Black'},\n {value: 'White Chocolate Spice Chai', text: 'White Chocolate Spice Chai'},\n {value: 'Chinese Flower', text: 'Chinese Flower'},\n {value: 'Imperial Pu-Erh', text: 'Imperial Pu-Erh'},\n {value: 'orange jasmine', text: 'orange jasmine'},\n {value: 'Black Iced Tea', text: 'Black Iced Tea'},\n {value: 'Zhong Shu Hu Oolong Tea', text: 'Zhong Shu Hu Oolong Tea'},\n {value: 'Ceylon Black', text: 'Ceylon Black'},\n {value: 'Spearmint (organic)', text: 'Spearmint (organic)'},\n {value: 'Yun Nan Dian Hong Black Tea – Golden Tip',\n text: 'Yun Nan Dian Hong Black Tea – Golden Tip'},\n {value: 'Cranberry &amp; Ginseng', text: 'Cranberry &amp; Ginseng'},\n {value: 'Redbush', text: 'Redbush'},\n {value: 'Blood Orange Rooibos', text: 'Blood Orange Rooibos'},\n {value: 'Snap Crackle and Sip', text: 'Snap Crackle and Sip'},\n {value: 'Keemun Black Tea Grade II', text: 'Keemun Black Tea Grade II'},\n {value: 'Jade Tips Select China Green Tea (ZG62)',\n text: 'Jade Tips Select China Green Tea (ZG62)'},\n {value: 'Houji-Kukicha (Roasted Kukicha)',\n text: 'Houji-Kukicha (Roasted Kukicha)'},\n {value: 'Organic Feel Flawless', text: 'Organic Feel Flawless'},\n {value: 'Infusion-Herbal Warming Apple Cinnamon',\n text: 'Infusion-Herbal Warming Apple Cinnamon'},\n {value: 'Healthy GABA Taiwanese Gaba Tea (Enhanced version with more GABA)',\n text: 'Healthy GABA Taiwanese Gaba Tea'},\n {value: 'Jasmine Star Peach', text: 'Jasmine Star Peach'},\n {value: 'tealish', text: 'tealish'},\n {value: 'Masala Chai Tea Concentrate',\n text: 'Masala Chai Tea Concentrate'},\n {value: 'Blue Mango', text: 'Blue Mango'},\n {value: 'Crème de la Earl Grey', text: 'Crème de la Earl Grey'},\n {value: 'Grand Wailea', text: 'Grand Wailea'},\n {value: 'Chill-icious Chai Smoothie', text: 'Chill-icious Chai Smoothie'},\n {value: 'blackberry spice', text: 'blackberry spice'},\n {value: 'Raspberry Banana Honeybush', text: 'Raspberry Banana Honeybush'},\n {value: 'Horny Goat Weed', text: 'Horny Goat Weed'},\n {value: 'Ambrosia White Plum', text: 'Ambrosia White Plum'},\n {value: 'Peach Detox', text: 'Peach Detox'},\n {value: 'Traditional Tieguanyin', text: 'Traditional Tieguanyin'},\n {value: 'The Royal Wedding Champagne Raspberry Gourmet Tea',\n text: 'The Royal Wedding Champagne Raspberry Gourmet Tea'},\n {value: 'Assam Hajua - F.T.G.B.O.P. Second flush',\n text: 'Assam Hajua - F.T.G.B.O.P. Second flush'},\n {value: 'Pumpkin Spice Black Tea', text: 'Pumpkin Spice Black Tea'},\n {value: 'Adventure', text: 'Adventure'},\n {value: 'Tulsi Holy Basil', text: 'Tulsi Holy Basil'},\n {value: 'Vanilla Bean Cream Nilgiri Black Tea',\n text: 'Vanilla Bean Cream Nilgiri Black Tea'},\n {value: '2014 Yunnan Sourcing Autumn Da Qing Gu Shu',\n text: '2014 Yunnan Sourcing Autumn Da Qing Gu Shu'},\n {value: 'Malty Breakfast Blend', text: 'Malty Breakfast Blend'},\n {value: 'Watermelon Raspberry Green Tea',\n text: 'Watermelon Raspberry Green Tea'},\n {value: 'Kenya Tinderet', text: 'Kenya Tinderet'},\n {value: 'Pu-erh Blood Orange', text: 'Pu-erh Blood Orange'},\n {value: 'Premium Earl Grey', text: 'Premium Earl Grey'},\n {value: 'Ever Green (organic)', text: 'Ever Green (organic)'},\n {value: 'Dark Cherry', text: 'Dark Cherry'},\n {value: 'Muscat', text: 'Muscat'},\n {value: 'Premium Ceylon', text: 'Premium Ceylon'},\n {value: 'Yunnan Black', text: 'Yunnan Black'},\n {value: 'Safari Sunset', text: 'Safari Sunset'},\n {value: 'Alishan', text: 'Alishan'},\n {value: 'Smoked Russian', text: 'Smoked Russian'},\n {value: 'Mint Puerh', text: 'Mint Puerh'},\n {value: 'Tangerine Creamsicle', text: 'Tangerine Creamsicle'},\n {value: 'Darjeeling Samabeong DJ-1 organic &amp; Fair Trade 2011',\n text: 'Darjeeling Samabeong DJ-1 organic &amp; Fair Trade 2011'},\n {value: 'Organic Genmaicha', text: 'Organic Genmaicha'},\n {value: 'Captain Assam', text: 'Captain Assam'},\n {value: 'Emperors Puerh', text: 'Emperors Puerh'},\n {value: 'Fujian Mountain Jasmine Dragon Pearl',\n text: 'Fujian Mountain Jasmine Dragon Pearl'},\n {value: 'Select Jasmine Tea', text: 'Select Jasmine Tea'},\n {value: 'Smoky English Breakfast Tea',\n text: 'Smoky English Breakfast Tea'},\n {value: 'Jade Oolong - Huan Jin Gui', text: 'Jade Oolong - Huan Jin Gui'},\n {value: 'Rooibos &amp; Honeybush', text: 'Rooibos &amp; Honeybush'},\n {value: 'Raji-Tea', text: 'Raji-Tea'},\n {value: 'North African Mint (organic)',\n text: 'North African Mint (organic)'},\n {value: '2008 He Gang Ruby Red', text: '2008 He Gang Ruby Red'},\n {value: 'Long Life Organic Green Tea',\n text: 'Long Life Organic Green Tea'},\n {value: 'Minty Green Chai', text: 'Minty Green Chai'},\n {value: 'China Hairy Crab Oolong', text: 'China Hairy Crab Oolong'},\n {value: 'Gui Fei Mei Ren 2011', text: 'Gui Fei Mei Ren 2011'},\n {value: '100% Organic Tulsi Signature Blend',\n text: '100% Organic Tulsi Signature Blend'},\n {value: 'Cinnamon Bear', text: 'Cinnamon Bear'},\n {value: 'Castleton Darjeeling', text: 'Castleton Darjeeling'},\n {value: 'Keemun Encore', text: 'Keemun Encore'},\n {value: 'Superior Pu-Erh', text: 'Superior Pu-Erh'},\n {value: 'Fusion Green and White', text: 'Fusion Green and White'},\n {value: 'Capricorn (The Zodiac Series)',\n text: 'Capricorn (The Zodiac Series)'},\n {value: '2012 Yunnan Sourcing Wu Liang Mountain Wild Arbor Raw Pu-erh Tea cake',\n text: '2012 Wu Liang Mountain Wild Arbor Raw Pu-erh Teacake'},\n {value: 'Organic rose bud flower tea',\n text: 'Organic rose bud flower tea'},\n {value: 'Nepal', text: 'Nepal'},\n {value: '2006 Yong De Hand Braided Wild Arbor Pu Erh Tea',\n text: '2006 Yong De Hand Braided Wild Arbor Pu Erh Tea'},\n {value: 'Tempest Tea Paris', text: 'Tempest Tea Paris'},\n {value: 'China Lapsang Souchong Tea', text: 'China Lapsang Souchong Tea'},\n {value: 'Orange U Slim', text: 'Orange U Slim'},\n {value: 'Loves Labour Lychee', text: 'Loves Labour Lychee'},\n {value: 'Keemun Hao Ya A Grade Chinese Breakfast Tea',\n text: 'Keemun Hao Ya A Grade Chinese Breakfast Tea'},\n {value: 'Castleton Autumnal 2008', text: 'Castleton Autumnal 2008'},\n {value: 'Magnolia Oolong', text: 'Magnolia Oolong'},\n {value: 'Backyard Botanicals', text: 'Backyard Botanicals'},\n {value: 'Jun Shan Yin Zhen', text: 'Jun Shan Yin Zhen'},\n {value: 'Mateccino', text: 'Mateccino'},\n {value: 'Mellow Mango Peach', text: 'Mellow Mango Peach'},\n {value: 'Goji Pop', text: 'Goji Pop'},\n {value: 'King of Jasmine', text: 'King of Jasmine'},\n {value: 'Dreamsicle', text: 'Dreamsicle'},\n {value: 'Fengqing Dragon Pearl Black Tea',\n text: 'Fengqing Dragon Pearl Black Tea'},\n {value: 'The London Tea Room Blend', text: 'The London Tea Room Blend'},\n {value: 'Kopili Assam', text: 'Kopili Assam'},\n {value: 'Oriental Spice', text: 'Oriental Spice'},\n {value: 'Viva', text: 'Viva'},\n {value: 'Rooibos Chai (BA33)', text: 'Rooibos Chai (BA33)'},\n {value: 'Ginseng Lemon', text: 'Ginseng Lemon'},\n {value: 'Tension Tamer', text: 'Tension Tamer'},\n {value: 'Orchid Vanilla', text: 'Orchid Vanilla'},\n {value: 'Pumpkin Pie', text: 'Pumpkin Pie'},\n {value: 'Special Dark', text: 'Special Dark'},\n {value: 'Golden Lion Assam 1st Flush',\n text: 'Golden Lion Assam 1st Flush'},\n {value: 'Emperor Pu-erh', text: 'Emperor Pu-erh'},\n {value: 'Aida', text: 'Aida'},\n {value: 'Yin Zi Ya', text: 'Yin Zi Ya'},\n {value: '2008 Mengku 981007', text: '2008 Mengku 981007'},\n {value: 'Chocolate Caramel Turtle', text: 'Chocolate Caramel Turtle'},\n {value: 'Moroccan Pomegranate Red Tea',\n text: 'Moroccan Pomegranate Red Tea'},\n {value: '2006 YiWu Mt. Raw Puerh', text: '2006 YiWu Mt. Raw Puerh'},\n {value: 'Jasmine with Flowers', text: 'Jasmine with Flowers'},\n {value: 'Slim Mint', text: 'Slim Mint'},\n {value: 'Antioxidant Supplement Green Tea',\n text: 'Antioxidant Supplement Green Tea'},\n {value: 'Strawberry Fields', text: 'Strawberry Fields'},\n {value: 'Golden Monkey Black Tea', text: 'Golden Monkey Black Tea'},\n {value: 'Mediterranean', text: 'Mediterranean'},\n {value: 'Phoenix Dan Cong (Snow Flakes) Oolong',\n text: 'Phoenix Dan Cong (Snow Flakes) Oolong'},\n {value: 'Heirloom Lishan Spring Formosa Oolong',\n text: 'Heirloom Lishan Spring Formosa Oolong'},\n {value: 'Pineapple Kona Pop', text: 'Pineapple Kona Pop'},\n {value: 'Lemon balm', text: 'Lemon balm'},\n {value: 'Organic China White Paklum Tips (ZW97)',\n text: 'Organic China White Paklum Tips (ZW97)'},\n {value: 'Morning Blend', text: 'Morning Blend'},\n {value: 'Raspberry Blue Tea', text: 'Raspberry Blue Tea'},\n {value: 'Quietly Chamomile', text: 'Quietly Chamomile'},\n {value: 'Sencha Fukuyu', text: 'Sencha Fukuyu'},\n {value: 'Tuocha Jasmine', text: 'Tuocha Jasmine'},\n {value: 'Keemun Black', text: 'Keemun Black'},\n {value: 'Dragon Flames', text: 'Dragon Flames'},\n {value: 'Orange Smile', text: 'Orange Smile'},\n {value: 'Orange Chocolate - Dark', text: 'Orange Chocolate - Dark'},\n {value: 'Pomegranate Fruit', text: 'Pomegranate Fruit'},\n {value: 'Twinings Black Tea Orange', text: 'Twinings Black Tea Orange'},\n {value: 'Premium Golden Monkey Black Tea',\n text: 'Premium Golden Monkey Black Tea'},\n {value: 'Red Peach (Hong Tao Mao Feng)',\n text: 'Red Peach (Hong Tao Mao Feng)'},\n {value: 'Chocolate Rose Earl Grey', text: 'Chocolate Rose Earl Grey'},\n {value: 'Cherry Amaretto', text: 'Cherry Amaretto'},\n {value: 'Magnolia Moments', text: 'Magnolia Moments'},\n {value: 'Uji Sencha Musashi', text: 'Uji Sencha Musashi'},\n {value: 'Phénix', text: 'Phénix'},\n {value: 'Blueberry Pomegranate', text: 'Blueberry Pomegranate'},\n {value: 'Rooibos Laranja e Eucalipto',\n text: 'Rooibos Laranja e Eucalipto'},\n {value: 'Marco Polo Rouge', text: 'Marco Polo Rouge'},\n {value: 'Fig Matcha', text: 'Fig Matcha'},\n {value: 'Flower of Hawaii 912', text: 'Flower of Hawaii 912'},\n {value: 'Saveurs du Soir (Flavors of the Evening)',\n text: 'Saveurs du Soir (Flavors of the Evening)'},\n {value: 'China Congou Panyang (TP60)',\n text: 'China Congou Panyang (TP60)'},\n {value: 'Organic Irish Breakfast Black Tea',\n text: 'Organic Irish Breakfast Black Tea'},\n {value: 'Organic Royal Silver Needle',\n text: 'Organic Royal Silver Needle'},\n {value: 'Earl Lavender', text: 'Earl Lavender'},\n {value: 'Red Dragon Pearl', text: 'Red Dragon Pearl'},\n {value: 'Rose Dian Hong Black Tea', text: 'Rose Dian Hong Black Tea'},\n {value: 'Large Leaf from Old Trees Pu-erh',\n text: 'Large Leaf from Old Trees Pu-erh'},\n {value: 'Peanut Butter Matcha', text: 'Peanut Butter Matcha'},\n {value: 'Joy Pu Erh', text: 'Joy Pu Erh'},\n {value: 'Summer Snow', text: 'Summer Snow'},\n {value: 'Apricot Honey Green Tea', text: 'Apricot Honey Green Tea'},\n {value: 'Dragonwell Grade B', text: 'Dragonwell Grade B'},\n {value: '2008 Lang Cang Rice Scented Ripe Mini Tuo',\n text: '2008 Lang Cang Rice Scented Ripe Mini Tuo'},\n {value: 'Decaf Organic Green Berry', text: 'Decaf Organic Green Berry'},\n {value: 'Medium LiSan Oolong', text: 'Medium LiSan Oolong'},\n {value: 'South African Green Rooibos Superior Organic',\n text: 'South African Green Rooibos Superior Organic'},\n {value: 'Angel Peach', text: 'Angel Peach'},\n {value: 'Gout Russe 7 Agrumes', text: 'Gout Russe 7 Agrumes'},\n {value: 'After Dark', text: 'After Dark'},\n {value: 'Sunny Passion (Mango)', text: 'Sunny Passion (Mango)'},\n {value: 'Sakura 2000', text: 'Sakura 2000'},\n {value: 'Vanilla Cream Rooibos', text: 'Vanilla Cream Rooibos'},\n {value: 'Old Tea Nugget - Lao Cha Tou - 2005',\n text: 'Old Tea Nugget - Lao Cha Tou - 2005'},\n {value: 'Vanilla Rooibos', text: 'Vanilla Rooibos'},\n {value: '2014 Yunnan Sourcing Wu Liang Mountain Wild Arbor Raw Pu-erh Tea',\n text: '2014 Yunnan Sourcing Wu Liang Mountain Wild Arbor Raw Pu-erh Tea'},\n {value: 'Kenya Milima Estate FBOP1', text: 'Kenya Milima Estate FBOP1'},\n {value: 'Supreme Ceylon', text: 'Supreme Ceylon'},\n {value: '2010 Bulang Mountain Spring Bing',\n text: '2010 Bulang Mountain Spring Bing'},\n {value: 'Organic Kagoshima Sencha Magokoro',\n text: 'Organic Kagoshima Sencha Magokoro'},\n {value: 'Tulsi Organcis (assorted)', text: 'Tulsi Organcis (assorted)'},\n {value: 'Organic Bi Yu Xiang', text: 'Organic Bi Yu Xiang'},\n {value: 'Organic Nonpareil Silver Needle White Tea (Bai Hao Yin Zhen)',\n text: 'Organic Nonpareil Silver Needle White Tea (Bai Hao Yin Zhen)'},\n {value: 'Pineapple Bliss', text: 'Pineapple Bliss'},\n {value: 'Pai Mu Tan Peach', text: 'Pai Mu Tan Peach'},\n {value: 'Ninas Japon', text: 'Ninas Japon'},\n {value: 'China Keemun Special Grade', text: 'China Keemun Special Grade'},\n {value: 'Passion Fruit Black Tea', text: 'Passion Fruit Black Tea'},\n {value: 'Fancy Tie Guan Yin', text: 'Fancy Tie Guan Yin'},\n {value: 'Shangri-La White Silvertips Spring 2009',\n text: 'Shangri-La White Silvertips Spring 2009'},\n {value: 'Superfruit White Mangosteen with Peach',\n text: 'Superfruit White Mangosteen with Peach'},\n {value: 'Matcha (Miyako no shiro)', text: 'Matcha (Miyako no shiro)'},\n {value: 'watermelon patch', text: 'watermelon patch'},\n {value: 'White Tea Pomegranate', text: 'White Tea Pomegranate'},\n {value: 'Darjeeling Finest Selection',\n text: 'Darjeeling Finest Selection'},\n {value: 'Lemongrass Green', text: 'Lemongrass Green'},\n {value: 'Apple Cinnamon &amp; Raisin',\n text: 'Apple Cinnamon Raisin'},\n {value: 'Dragonwell Wild Mountain', text: 'Dragonwell Wild Mountain'},\n {value: 'Apricot Spice Mish-mash', text: 'Apricot Spice Mish-mash'},\n {value: 'Mint and Lemon Balm', text: 'Mint and Lemon Balm'},\n {value: 'Silver Mountain Water', text: 'Silver Mountain Water'},\n {value: 'Winter Spice', text: 'Winter Spice'},\n {value: 'Orange Blossom Organic and Fair Trade Green Tea',\n text: 'Orange Blossom Organic and Fair Trade Green Tea'},\n {value: 'Raspberry Iced Tea', text: 'Raspberry Iced Tea'},\n {value: 'British Blend', text: 'British Blend'},\n {value: 'Home-made Ginger Tea', text: 'Home-made Ginger Tea'},\n {value: 'Malcolm', text: 'Malcolm'},\n {value: 'Silk Oolong', text: 'Silk Oolong'},\n {value: 'Delicious Plum Spice Tea', text: 'Delicious Plum Spice Tea'},\n {value: 'Magnolia Oolong (sampler) by Tea Savant',\n text: 'Magnolia Oolong (sampler) by Tea Savant'},\n {value: 'Margarets Hope Oolong', text: 'Margarets Hope Oolong'},\n {value: 'Rooibos Cocoa', text: 'Rooibos Cocoa'},\n {value: 'Organic 1000mesh Matcha', text: 'Organic 1000mesh Matcha'},\n {value: 'Regenerate', text: 'Regenerate'},\n {value: 'Pumpkin Pie Matcha', text: 'Pumpkin Pie Matcha'},\n {value: 'TD20: Orthodox TGFOP Darjeeling',\n text: 'TD20: Orthodox TGFOP Darjeeling'},\n {value: 'Backwoods', text: 'Backwoods'},\n {value: 'Premium Wuyi Big Red Robe 1205/110137',\n text: 'Premium Wuyi Big Red Robe 1205/110137'},\n {value: 'Savasana', text: 'Savasana'},\n {value: '1992 Gong Ting Puer', text: '1992 Gong Ting Puer'},\n {value: '2007 White Bud 250g Sheng Pu-Erh Tea Cake',\n text: '2007 White Bud 250g Sheng Pu-Erh Tea Cake'},\n {value: 'Fairtrade pure origin Ceylon teabags',\n text: 'Fairtrade pure origin Ceylon teabags'},\n {value: 'Finest Darjeeling 2nd Flush Castleton',\n text: 'Finest Darjeeling 2nd Flush Castleton'},\n {value: 'Taffy Terror (organic)', text: 'Taffy Terror (organic)'},\n {value: 'Organic Ceylon', text: 'Organic Ceylon'},\n {value: 'Green Chamoflage (Custom Blend)',\n text: 'Green Chamoflage (Custom Blend)'},\n {value: 'Cinnamon Heart', text: 'Cinnamon Heart'},\n {value: 'North Tukvar Estate 1st Fl Darjeeling SFTGFOP1 (DJ-24) TD63',\n text: 'North Tukvar Estate 1st Fl Darjeeling SFTGFOP1 (DJ-24) TD63'},\n {value: 'Garden Aria White Tea', text: 'Garden Aria White Tea'},\n {value: 'Harvest Chai Latte', text: 'Harvest Chai Latte'},\n {value: 'Green Walnut', text: 'Green Walnut'},\n {value: 'Jasmine (loose leaf)', text: 'Jasmine (loose leaf)'},\n {value: 'Early Riser', text: 'Early Riser'},\n {value: 'Ceremonial Matcha (organic)',\n text: 'Ceremonial Matcha (organic)'},\n {value: 'Imperial Rou Gui Oolong', text: 'Imperial Rou Gui Oolong'},\n {value: 'Apple Cider Tea', text: 'Apple Cider Tea'},\n {value: 'Pomegranate Fruit Infusion', text: 'Pomegranate Fruit Infusion'},\n {value: 'White Vanilla Grapefruit', text: 'White Vanilla Grapefruit'},\n {value: 'Dimbula BOP Blend TC20', text: 'Dimbula BOP Blend TC20'},\n {value: 'Clear Green Orient', text: 'Clear Green Orient'},\n {value: 'Guayaki’s Yerba Mate', text: 'Guayaki’s Yerba Mate'},\n {value: 'Imperial Republic Lychee Black Tea',\n text: 'Imperial Republic Lychee Black Tea'},\n {value: 'Green Orange', text: 'Green Orange'},\n {value: 'Snow Sprout', text: 'Snow Sprout'},\n {value: 'Copley Vanilla Tea', text: 'Copley Vanilla Tea'},\n {value: 'Toffee Crunch', text: 'Toffee Crunch'},\n {value: 'Sencha Yamanoibuki', text: 'Sencha Yamanoibuki'},\n {value: 'Saffron Fusion Tea', text: 'Saffron Fusion Tea'},\n {value: 'Jade Tie Guan Yin', text: 'Jade Tie Guan Yin'},\n {value: '2011 Yunnan Sourcing Chen Yun Yuan Cha Wild Arbor Raw',\n text: '2011 Yunnan Sourcing Chen Yun Yuan Cha Wild Arbor Raw'},\n {value: 'Mini Ripe Rice Scented Tuocha',\n text: 'Mini Ripe Rice Scented Tuocha'},\n {value: 'Stress Reliever', text: 'Stress Reliever'},\n {value: 'Hangzhou Dragon Well', text: 'Hangzhou Dragon Well'},\n {value: 'Fellinis Folly', text: 'Fellinis Folly'},\n {value: 'English Caramel', text: 'English Caramel'},\n {value: 'TB20: River Shannon Breakfast Blend',\n text: 'TB20: River Shannon Breakfast Blend'},\n {value: 'Pu-erh classic', text: 'Pu-erh classic'},\n {value: 'Clear Jade Orchid', text: 'Clear Jade Orchid'},\n {value: 'Thé des Impressionnistes', text: 'Thé des Impressionnistes'},\n {value: 'Vanilla Strawberry Rose', text: 'Vanilla Strawberry Rose'},\n {value: 'Mint Medley', text: 'Mint Medley'},\n {value: 'Yunan Chi Tse Beeng Cha 1998',\n text: 'Yunan Chi Tse Beeng Cha 1998'},\n {value: 'Peach Cran-Tango Black Tea', text: 'Peach Cran-Tango Black Tea'},\n {value: 'California Fields', text: 'California Fields'},\n {value: 'Tao Tea - Rose', text: 'Tao Tea - Rose'},\n {value: 'Luna Lovegood', text: 'Luna Lovegood'},\n {value: 'Plantation Mint', text: 'Plantation Mint'},\n {value: 'Instant Hojicha', text: 'Instant Hojicha'},\n {value: 'Bossa Nova', text: 'Bossa Nova'},\n {value: 'Sunrise in Tibet', text: 'Sunrise in Tibet'},\n {value: 'China Yin Zhen Bai Hao Downy White Pekoe (ZW80)',\n text: 'China Yin Zhen Bai Hao Downy White Pekoe (ZW80)'},\n {value: 'Pineapple Chamomile Infusion',\n text: 'Pineapple Chamomile Infusion'},\n {value: 'Red Robe', text: 'Red Robe'},\n {value: 'Sunset Honeybush', text: 'Sunset Honeybush'},\n {value: 'Nantou Spring Tips Green Tea',\n text: 'Nantou Spring Tips Green Tea'},\n {value: 'Decaf Raspberry and White', text: 'Decaf Raspberry and White'},\n {value: 'Fengqing Paddy Flavor Raw Pu-erh Cake Tea 2006',\n text: 'Fengqing Paddy Flavor Raw Pu-erh Cake Tea 2006'},\n {value: 'Antique Pu Er', text: 'Antique Pu Er'},\n {value: 'Nanah Morocco', text: 'Nanah Morocco'},\n {value: 'Formosa Nut Oolong', text: 'Formosa Nut Oolong'},\n {value: 'Green Caramel', text: 'Green Caramel'},\n {value: 'King Kong Oolong', text: 'King Kong Oolong'},\n {value: 'Pu-erh Grapefruit Flavoured Tea',\n text: 'Pu-erh Grapefruit Flavoured Tea'},\n {value: 'White Tropics', text: 'White Tropics'},\n {value: 'English Tea No. 1', text: 'English Tea No. 1'},\n {value: 'White Temple tea', text: 'White Temple tea'},\n {value: 'Tie Kwan Yin (organic)', text: 'Tie Kwan Yin (organic)'},\n {value: 'Jasmine', text: 'Jasmine'},\n {value: 'Purple Rain', text: 'Purple Rain'},\n {value: 'kenya oolong', text: 'kenya oolong'},\n {value: 'Gemaicha', text: 'Gemaicha'},\n {value: 'Yu Lan Dan Cong', text: 'Yu Lan Dan Cong'},\n {value: 'Azteca Fire', text: 'Azteca Fire'},\n {value: 'Hot Apple Cider', text: 'Hot Apple Cider'},\n {value: 'Pu-erh Mini Tuo', text: 'Pu-erh Mini Tuo'},\n {value: 'Gano Tea SOD', text: 'Gano Tea SOD'},\n {value: 'Yanagi Bancha', text: 'Yanagi Bancha'},\n {value: 'Green Ginger', text: 'Green Ginger'},\n {value: 'Cookie Tea', text: 'Cookie Tea'},\n {value: '1st Flush Dragonwell', text: '1st Flush Dragonwell'},\n {value: 'Walnut Fudge Brownie', text: 'Walnut Fudge Brownie'},\n {value: 'Rooibos Mix', text: 'Rooibos Mix'},\n {value: 'Blood-Orange Smoothie', text: 'Blood-Orange Smoothie'},\n {value: 'Mate Com Guarana Extra Forte',\n text: 'Mate Com Guarana Extra Forte'},\n {value: 'Mayan Chocolate Puerh', text: 'Mayan Chocolate Puerh'},\n {value: 'Green Tea Citronella (TG30)',\n text: 'Green Tea Citronella (TG30)'},\n {value: 'White Okayti Estate Darjeeling Silver Tips',\n text: 'White Okayti Estate Darjeeling Silver Tips'},\n {value: 'Orchid Temple', text: 'Orchid Temple'},\n {value: 'Organic Spring Jasmine', text: 'Organic Spring Jasmine'},\n {value: 'Huo Shan Yellow Bud Green Tea',\n text: 'Huo Shan Yellow Bud Green Tea'},\n {value: 'Assam Reserve', text: 'Assam Reserve'},\n {value: 'St. James Ceylon', text: 'St. James Ceylon'},\n {value: 'Kukucha Japan', text: 'Kukucha Japan'},\n {value: 'Ice Wine', text: 'Ice Wine'},\n {value: 'Rooibos Earl Grey', text: 'Rooibos Earl Grey'},\n {value: 'Kawayanagi', text: 'Kawayanagi'},\n {value: 'Hubei Spring Needle', text: 'Hubei Spring Needle'},\n {value: 'Ti Kuan Yin - Iron Goddess Oolong',\n text: 'Ti Kuan Yin - Iron Goddess Oolong'},\n {value: 'Thé Noir Ceylan FP Bio Ceylon Breakfast - Premium',\n text: 'Thé Noir Ceylan FP Bio Ceylon Breakfast - Premium'},\n {value: 'Oatmeal Raisin Cookie', text: 'Oatmeal Raisin Cookie'},\n {value: 'Highland Grown Wush Wush', text: 'Highland Grown Wush Wush'},\n {value: 'Key Lime', text: 'Key Lime'},\n {value: 'Sweet Cinnamon Spice', text: 'Sweet Cinnamon Spice'},\n {value: 'Organic Traditional Iron Buddha Oolong (Tie Guan Yin Wu Long)',\n text: 'Organic Traditional Iron Buddha Oolong (Tie Guan Yin Wu Long)'},\n {value: 'Boston Tea Party Orange Spice Blend',\n text: 'Boston Tea Party Orange Spice Blend'},\n {value: 'Jade Oolong Autumn 2011', text: 'Jade Oolong Autumn 2011'},\n {value: '2010 American Hao 1005 Ripe Pu-erh',\n text: '2010 American Hao 1005 Ripe Pu-erh'},\n {value: 'Lotus Leaf', text: 'Lotus Leaf'},\n {value: 'Blackberry Black', text: 'Blackberry Black'},\n {value: 'Rooibos Melange', text: 'Rooibos Melange'},\n {value: 'ZG20: First Grade Gunpowder Green',\n text: 'ZG20: First Grade Gunpowder Green'},\n {value: 'Salted Caramel', text: 'Salted Caramel'},\n {value: '2006 Haiwan Certified Organic Pasha Mountain Raw',\n text: '2006 Haiwan Certified Organic Pasha Mountain Raw'},\n {value: 'Butterbeer', text: 'Butterbeer'},\n {value: 'PerfecTea Maker', text: 'PerfecTea Maker'},\n {value: '7 Parfums', text: '7 Parfums'},\n {value: 'Green Rooibos Vanilla', text: 'Green Rooibos Vanilla'},\n {value: 'Cest Parfait', text: 'Cest Parfait'},\n {value: 'Guayusa and Black Tea', text: 'Guayusa and Black Tea'},\n {value: 'Chrysanthemum', text: 'Chrysanthemum'},\n {value: 'Kagoshima Shincha Sae Midori',\n text: 'Kagoshima Shincha Sae Midori'},\n {value: 'Blue Flower Earl Grey', text: 'Blue Flower Earl Grey'},\n {value: 'Zeppelinmobile', text: 'Zeppelinmobile'},\n {value: 'Royal Yunnan', text: 'Royal Yunnan'},\n {value: 'Dragonwell Imperial Reserve',\n text: 'Dragonwell Imperial Reserve'},\n {value: 'Tencha-Kuki Houjicha', text: 'Tencha-Kuki Houjicha'},\n {value: 'Kirara Rice Tea', text: 'Kirara Rice Tea'},\n {value: 'Peppermint Pleasure', text: 'Peppermint Pleasure'},\n {value: 'Jin Kong Que (Golden Peacock) Organic Black Tea',\n text: 'Jin Kong Que (Golden Peacock) Organic Black Tea'},\n {value: 'Amber Dragon Oolong', text: 'Amber Dragon Oolong'},\n {value: 'Domestic Spearmint', text: 'Domestic Spearmint'},\n {value: 'Earl Grey &amp; Lavender', text: 'Earl Grey &amp; Lavender'},\n {value: 'Vithanakande OP1', text: 'Vithanakande OP1'},\n {value: 'Genmai Cha', text: 'Genmai Cha'},\n {value: '2008 Yuan Man: Chen Yuan Hao',\n text: '2008 Yuan Man: Chen Yuan Hao'},\n {value: 'Restful', text: 'Restful'},\n {value: 'Ginger Peach (White)', text: 'Ginger Peach (White)'},\n {value: 'Mountain Wūlóng', text: 'Mountain Wūlóng'},\n {value: 'zheng yuan mao cha', text: 'zheng yuan mao cha'},\n {value: 'Vanilla Apricot White', text: 'Vanilla Apricot White'},\n {value: 'Liu An Guapian', text: 'Liu An Guapian'},\n {value: 'Three Ginger', text: 'Three Ginger'},\n {value: 'Lemon Lime Kampai', text: 'Lemon Lime Kampai'},\n {value: 'Jasmine Pearls Organic', text: 'Jasmine Pearls Organic'},\n {value: 'Snow Flake', text: 'Snow Flake'},\n {value: 'Goji Cacao Berry', text: 'Goji Cacao Berry'},\n {value: 'Margarets Hope Est. 2nd Fl Darjeeling FTGFOP1 Musc (DJ-123)',\n text: 'Margarets Hope Est. 2nd Fl Darjeeling FTGFOP1 Musc (DJ-123)'},\n {value: 'SPORTea', text: 'SPORTea'},\n {value: 'Organic Japanese Puerh', text: 'Organic Japanese Puerh'},\n {value: 'Green Tea Red Antioxidant', text: 'Green Tea Red Antioxidant'},\n {value: 'Keemun Mao Feng Organic', text: 'Keemun Mao Feng Organic'},\n {value: 'Labrador', text: 'Labrador'},\n {value: 'Risheehat First Flush Darjeeling 2010 [Out of Stock]',\n text: 'Risheehat First Flush Darjeeling 2010 [Out of Stock]'},\n {value: 'Fuji Apple', text: 'Fuji Apple'},\n {value: 'Organic Genmaicha Whole Leaf Teabag',\n text: 'Organic Genmaicha Whole Leaf Teabag'},\n {value: 'Ronnefeldt Ginger and Herbs Tisane (Loose Tea)',\n text: 'Ronnefeldt Ginger and Herbs Tisane (Loose Tea)'},\n {value: 'Shanghai Orchid', text: 'Shanghai Orchid'},\n {value: 'Yunnan Pu Erh Gold', text: 'Yunnan Pu Erh Gold'},\n {value: 'Anniversary Blend', text: 'Anniversary Blend'},\n {value: 'Earl Grey Decaf', text: 'Earl Grey Decaf'},\n {value: 'Santas Secret', text: 'Santas Secret'},\n {value: 'Immune Support', text: 'Immune Support'},\n {value: 'Anhui Keemun', text: 'Anhui Keemun'},\n {value: 'Red Berry Rooibos (Red Tea)',\n text: 'Red Berry Rooibos (Red Tea)'},\n {value: 'Lemon Drop', text: 'Lemon Drop'},\n {value: 'Organic Tian Mu Mao Feng Green Tea',\n text: 'Organic Tian Mu Mao Feng Green Tea'},\n {value: 'Darjeeling Sunshine Earl Grey',\n text: 'Darjeeling Sunshine Earl Grey'},\n {value: 'Nokcha 2009', text: 'Nokcha 2009'},\n {value: 'Silk Oolong Formosa', text: 'Silk Oolong Formosa'},\n {value: 'Jungjak', text: 'Jungjak'},\n {value: '230 - Unity Blend Organic', text: '230 - Unity Blend Organic'},\n {value: 'Very Merry Berry Medley Rooibos',\n text: 'Very Merry Berry Medley Rooibos'},\n {value: '18 Different Flavor Puerh Tea ChaTao 14 Riped 4 Raw',\n text: '18 Different Flavor Puerh Tea ChaTao 14 Riped 4 Raw'},\n {value: 'Organic Mountain Wulong', text: 'Organic Mountain Wulong'},\n {value: 'Orange Passionfruit &amp; Jasmine Green',\n text: 'Orange Passionfruit Jasmine Green'},\n {value: 'Lemon and ginger', text: 'Lemon and ginger'},\n {value: 'Geisha Plum (organic)', text: 'Geisha Plum (organic)'},\n {value: 'The Queens Diamond Jubilee (Commemorative Blend) 1952-2012',\n text: 'The Queens Diamond Jubilee (Commemorative Blend) 1952-2012'},\n {value: 'Makai Black (Assam)', text: 'Makai Black (Assam)'},\n {value: 'Laoshan White', text: 'Laoshan White'},\n {value: 'Honeybush Hazelnut', text: 'Honeybush Hazelnut'},\n {value: 'Jasmine Pearl Scented Green Tea - Organic',\n text: 'Jasmine Pearl Scented Green Tea - Organic'},\n {value: 'camomile infusions', text: 'camomile infusions'},\n {value: 'Napoleon', text: 'Napoleon'},\n {value: 'Lady Grey Decaf', text: 'Lady Grey Decaf'},\n {value: 'Caribbean Breeze Sencha', text: 'Caribbean Breeze Sencha'},\n {value: 'Wensheng Pouchong', text: 'Wensheng Pouchong'},\n {value: 'Lichee Red', text: 'Lichee Red'},\n {value: 'milky oolong', text: 'milky oolong'},\n {value: 'Blueberry Black Tea', text: 'Blueberry Black Tea'},\n {value: 'Assam Finest', text: 'Assam Finest'},\n {value: 'Organic Fairmont Breakfast (India Kenya Sri Lanka China)',\n text: 'Organic Fairmont Breakfast (India Kenya Sri Lanka China)'},\n {value: 'Phoenix Mountain Oolong (25)',\n text: 'Phoenix Mountain Oolong (25)'},\n {value: 'Mint Magic', text: 'Mint Magic'},\n {value: 'Organic Lemon Ginger Green', text: 'Organic Lemon Ginger Green'},\n {value: 'Applemint', text: 'Applemint'},\n {value: 'Bai Ji Guan', text: 'Bai Ji Guan'},\n {value: 'Scottish Caramel Pu-Erh', text: 'Scottish Caramel Pu-Erh'},\n {value: 'Sweet Tea', text: 'Sweet Tea'},\n {value: 'Warmth – Cinnamon Spice', text: 'Warmth – Cinnamon Spice'},\n {value: 'China Golden Monkey (Fujian)',\n text: 'China Golden Monkey (Fujian)'},\n {value: 'Caramel with Caramel Pieces',\n text: 'Caramel with Caramel Pieces'},\n {value: 'China Lung Ching', text: 'China Lung Ching'},\n {value: 'Black Honey', text: 'Black Honey'},\n {value: 'Cherry Chocolate Marshmallow',\n text: 'Cherry Chocolate Marshmallow'},\n {value: 'Eaters Digest', text: 'Eaters Digest'},\n {value: 'Guayusa and Green Tea', text: 'Guayusa and Green Tea'},\n {value: 'Fruit and Flower Iced Tea', text: 'Fruit and Flower Iced Tea'},\n {value: 'Tiger Chai', text: 'Tiger Chai'},\n {value: 'Summertime Earl Grey', text: 'Summertime Earl Grey'},\n {value: '2005 Menghai Dayi 7572', text: '2005 Menghai Dayi 7572'},\n {value: 'Rooibos Rainbow', text: 'Rooibos Rainbow'},\n {value: 'Fils du Ciel', text: 'Fils du Ciel'},\n {value: 'Cherry Queen Rooibos', text: 'Cherry Queen Rooibos'},\n {value: 'China Oolong Se Chung (ZO10)',\n text: 'China Oolong Se Chung (ZO10)'},\n {value: 'Coffee Almond Tea', text: 'Coffee Almond Tea'},\n {value: 'Espresso Matcha', text: 'Espresso Matcha'},\n {value: 'Matcha (100g)', text: 'Matcha (100g)'},\n {value: 'Herbal Revive: lemon and ginger',\n text: 'Herbal Revive: lemon and ginger'},\n {value: 'West Country Loose Tea', text: 'West Country Loose Tea'},\n {value: 'Thé au Tibet', text: 'Thé au Tibet'},\n {value: 'Organic Roasted Mate', text: 'Organic Roasted Mate'},\n {value: 'Oolong Hairy Crab', text: 'Oolong Hairy Crab'},\n {value: 'Green Pekoe', text: 'Green Pekoe'},\n {value: 'Chinese Green Tea', text: 'Chinese Green Tea'},\n {value: 'Noël en Provence', text: 'Noël en Provence'},\n {value: 'Constant Companion', text: 'Constant Companion'},\n {value: 'Oolong de Frutos Vermelhos - Red Fruits Oolong',\n text: 'Oolong de Frutos Vermelhos - Red Fruits Oolong'},\n {value: 'Organic Matcha Coconut', text: 'Organic Matcha Coconut'},\n {value: 'Gold', text: 'Gold'},\n {value: 'White Goji Blossom', text: 'White Goji Blossom'},\n {value: 'Essence of Assam', text: 'Essence of Assam'},\n {value: 'Blackberries &amp; Cream Shou Mei',\n text: 'Blackberries &amp; Cream Shou Mei'},\n {value: 'Harmutty Estate Assam', text: 'Harmutty Estate Assam'},\n {value: '2007 Xi-Zhi-Hao Classic 8582',\n text: '2007 Xi-Zhi-Hao Classic 8582'},\n {value: 'Bubbly', text: 'Bubbly'},\n {value: 'Lemon Mate', text: 'Lemon Mate'},\n {value: 'Grape Sencha', text: 'Grape Sencha'},\n {value: 'Organic White Tea', text: 'Organic White Tea'},\n {value: 'Blueberry Harvest', text: 'Blueberry Harvest'},\n {value: 'Jolly Jellybean', text: 'Jolly Jellybean'},\n {value: 'Japanese Wild Cherry', text: 'Japanese Wild Cherry'},\n {value: 'Sabah Loose Tea', text: 'Sabah Loose Tea'},\n {value: 'Pomegranate Delight', text: 'Pomegranate Delight'},\n {value: 'Pu Ehr Orange (EP08)', text: 'Pu Ehr Orange (EP08)'},\n {value: 'Chocolate Panda', text: 'Chocolate Panda'},\n {value: 'Nepal Himalayan Spring 2011 Ramche-Exclusive Jun Chiyabari First Flush',\n text: 'Nepal 2011 Ramche-Exclusive Jun Chiyabari'},\n {value: 'Darjeeling Premium Decaf', text: 'Darjeeling Premium Decaf'},\n {value: 'China Pearl White Tea', text: 'China Pearl White Tea'},\n {value: 'Organic Darjeeling Black Pyramid Tea',\n text: 'Organic Darjeeling Black Pyramid Tea'},\n {value: 'Cran-Cherry Black', text: 'Cran-Cherry Black'},\n {value: 'Peppermint Leaf', text: 'Peppermint Leaf'},\n {value: 'Canton Green Tea', text: 'Canton Green Tea'},\n {value: 'Russian Spiced Tea', text: 'Russian Spiced Tea'},\n {value: 'Maple Taffy', text: 'Maple Taffy'},\n {value: 'Yunnan Green (Yunnan Lu Cha)',\n text: 'Yunnan Green (Yunnan Lu Cha)'},\n {value: 'Coconut Vanilla White', text: 'Coconut Vanilla White'},\n {value: 'Kauai Cocktail', text: 'Kauai Cocktail'},\n {value: 'Wang Pu-Erh (ZH45)', text: 'Wang Pu-Erh (ZH45)'},\n {value: 'African Honeybush', text: 'African Honeybush'},\n {value: 'Assam - Sessa 2nd Flush', text: 'Assam - Sessa 2nd Flush'},\n {value: 'Organic Nonpareil Heavily Roasted Tie Guan Yin “Iron Goddess” Oolong Tea',\n text: 'Organic Nonpareil Tie Guan Yin “Iron Goddess” Oolong Tea'},\n {value: 'Cherry Cordial', text: 'Cherry Cordial'},\n {value: 'Organic Mountain High Chai', text: 'Organic Mountain High Chai'},\n {value: 'Strawberry and Mango Fresh and Fruity',\n text: 'Strawberry and Mango Fresh and Fruity'},\n {value: 'Jun Chiyabari Nepalese Black Tea',\n text: 'Jun Chiyabari Nepalese Black Tea'},\n {value: 'Lichee Congou Emperor Tea', text: 'Lichee Congou Emperor Tea'},\n {value: 'Taiwanese Wild Mountain Black',\n text: 'Taiwanese Wild Mountain Black'},\n {value: 'Strawberry Lemonade Bai Mu Dan',\n text: 'Strawberry Lemonade Bai Mu Dan'},\n {value: 'Greenwood Estate Assam White Tea',\n text: 'Greenwood Estate Assam White Tea'},\n {value: 'Charcoal Roasted Pouchong (Baozhong)',\n text: 'Charcoal Roasted Pouchong (Baozhong)'},\n {value: 'Gyokuro Green Tea', text: 'Gyokuro Green Tea'},\n {value: 'Darjeeling Second Flush', text: 'Darjeeling Second Flush'},\n {value: 'Please Take Me Away', text: 'Please Take Me Away'},\n {value: 'Liquid Gold Tea Blend', text: 'Liquid Gold Tea Blend'},\n {value: 'Laoshan Genmaicha', text: 'Laoshan Genmaicha'},\n {value: 'Black Celebration', text: 'Black Celebration'},\n {value: 'Oolong Formosa', text: 'Oolong Formosa'},\n {value: 'Caricias para el Alma', text: 'Caricias para el Alma'},\n {value: 'Grilled Pineapple', text: 'Grilled Pineapple'},\n {value: 'Venture Irish Breakfast Pekoe',\n text: 'Venture Irish Breakfast Pekoe'},\n {value: 'Orange Ginger Zinger', text: 'Orange Ginger Zinger'},\n {value: 'Autumn 2015 Imperial Tie Guan Yin of Anxi',\n text: 'Autumn 2015 Imperial Tie Guan Yin of Anxi'},\n {value: 'Bella Coola', text: 'Bella Coola'},\n {value: 'Oolong Shui Hsien', text: 'Oolong Shui Hsien'},\n {value: 'ZW81: Downy White Tea Organic',\n text: 'ZW81: Downy White Tea Organic'},\n {value: 'Keemun Congou De-Luxe', text: 'Keemun Congou De-Luxe'},\n {value: 'Kangchenzodnga Sunset', text: 'Kangchenzodnga Sunset'},\n {value: 'Holy Hot Cinnamon', text: 'Holy Hot Cinnamon'},\n {value: 'Wu Yi Oolong', text: 'Wu Yi Oolong'},\n {value: 'Manuka Antioxidant', text: 'Manuka Antioxidant'},\n {value: 'Darjeeling 22', text: 'Darjeeling 22'},\n {value: 'Dawn', text: 'Dawn'},\n {value: 'Darjeeling TGFOP Margarets Hope (Autumnal)',\n text: 'Darjeeling TGFOP Margarets Hope (Autumnal)'},\n {value: 'All India Blend', text: 'All India Blend'},\n {value: '2010 Silver Strand', text: '2010 Silver Strand'},\n {value: 'Bancha (Ban Cha)', text: 'Bancha (Ban Cha)'},\n {value: 'Organic Chunmee Eyebrow Green Tea',\n text: 'Organic Chunmee Eyebrow Green Tea'},\n {value: 'Golden Monkey Paw', text: 'Golden Monkey Paw'},\n {value: '1992 Da Ye Loose Leaf Sheng Puerh',\n text: '1992 Da Ye Loose Leaf Sheng Puerh'},\n {value: 'Fruta bamba', text: 'Fruta bamba'},\n {value: 'Chocolate Mint', text: 'Chocolate Mint'},\n {value: 'Wild Blackberry', text: 'Wild Blackberry'},\n {value: 'Red Vanilla', text: 'Red Vanilla'},\n {value: '2013 First Flush Jungpana SFTGFOP1',\n text: '2013 First Flush Jungpana SFTGFOP1'},\n {value: '2009 Menghai Dayi 7542 Raw Pu Er Cake(901)',\n text: '2009 Menghai Dayi 7542 Raw Pu Er Cake(901)'},\n {value: 'Pi Lo Chun Bao Wei (ZG55)', text: 'Pi Lo Chun Bao Wei (ZG55)'},\n {value: 'Green Tea Triple Echinacea', text: 'Green Tea Triple Echinacea'},\n {value: 'Shanghai Lichee Jasmine', text: 'Shanghai Lichee Jasmine'},\n {value: 'Lumbini Estate OP1 - Ceylon Ruhuna Dist.',\n text: 'Lumbini Estate OP1 - Ceylon Ruhuna Dist.'},\n {value: 'Sleepytime Throat Tamer Wellness Tea',\n text: 'Sleepytime Throat Tamer Wellness Tea'},\n {value: 'Country Spice', text: 'Country Spice'},\n {value: 'Bond Street English Breakfast Blend (TB10)',\n text: 'Bond Street English Breakfast Blend (TB10)'},\n {value: 'Lime Fizz', text: 'Lime Fizz'},\n {value: 'Aged Bamboo Oolong 1990', text: 'Aged Bamboo Oolong 1990'},\n {value: 'Sugar and Spice', text: 'Sugar and Spice'},\n {value: 'Builders Tea', text: 'Builders Tea'},\n {value: 'Nilgiri Tiger Hill Supreme', text: 'Nilgiri Tiger Hill Supreme'},\n {value: 'Tung Ting Blue Tea', text: 'Tung Ting Blue Tea'},\n {value: 'Lemon Mint Black', text: 'Lemon Mint Black'},\n {value: 'Sapphire Earl Grey', text: 'Sapphire Earl Grey'},\n {value: 'Ceylon Paradise (470)', text: 'Ceylon Paradise (470)'},\n {value: 'Bollywood Star', text: 'Bollywood Star'},\n {value: 'Mango Sunrise', text: 'Mango Sunrise'},\n {value: 'Chaud Les Marrons', text: 'Chaud Les Marrons'},\n {value: 'White Himalaya Pineapple Spice',\n text: 'White Himalaya Pineapple Spice'},\n {value: 'Acai Mango Sweet Zinger Ice Tea',\n text: 'Acai Mango Sweet Zinger Ice Tea'},\n {value: 'Li Shan Oolong', text: 'Li Shan Oolong'},\n {value: 'Blueberry Kona Pop Tea Blend',\n text: 'Blueberry Kona Pop Tea Blend'},\n {value: '2005 Yunnan Yunhai Chi Tse Beeng Cha Ripe Puerh Tea',\n text: '2005 Yunnan Yunhai Chi Tse Beeng Cha Ripe Puerh Tea'},\n {value: 'Feliz Cumpleaños', text: 'Feliz Cumpleaños'},\n {value: 'Darjeeling Ambootia', text: 'Darjeeling Ambootia'},\n {value: 'China Seduction', text: 'China Seduction'},\n {value: 'Coco Chai', text: 'Coco Chai'},\n {value: 'Excuse Me Princess', text: 'Excuse Me Princess'},\n {value: '2007 Menghai Dayi 7262 Ripe',\n text: '2007 Menghai Dayi 7262 Ripe'},\n {value: 'Four Season Spring Oolong', text: 'Four Season Spring Oolong'},\n {value: 'Vintage Jasmine Liu An 2001',\n text: 'Vintage Jasmine Liu An 2001'},\n {value: '1960s (early) Guang Yun Gong Puerh',\n text: '1960s (early) Guang Yun Gong Puerh'},\n {value: 'Gen Mai Cha', text: 'Gen Mai Cha'},\n {value: '2010 Pre-QingMing 800m High Mountain Yuezhou Long Jing',\n text: '2010 Pre-QingMing 800m High Mountain Yuezhou Long Jing'},\n {value: 'Mint Fields (Organic)', text: 'Mint Fields (Organic)'},\n {value: 'Monkey Chops', text: 'Monkey Chops'},\n {value: 'English Breakfast Organic', text: 'English Breakfast Organic'},\n {value: 'Ginger Lemon Tea', text: 'Ginger Lemon Tea'},\n {value: 'Ceylon leaf tea', text: 'Ceylon leaf tea'},\n {value: 'Atlantis FOUND Tea', text: 'Atlantis FOUND Tea'},\n {value: 'Night Owl Tea', text: 'Night Owl Tea'},\n {value: 'Anteadote Green Tea Iced', text: 'Anteadote Green Tea Iced'},\n {value: 'Chocolate Macaroon', text: 'Chocolate Macaroon'},\n {value: 'Golden Raisin Oolong *Limited*',\n text: 'Golden Raisin Oolong *Limited*'},\n {value: 'Tribute', text: 'Tribute'},\n {value: 'Huang Zhi Xiang (Yellow Sprig) Dan Cong Oolong 2008',\n text: 'Huang Zhi Xiang (Yellow Sprig) Dan Cong Oolong 2008'},\n {value: 'Pure Mint', text: 'Pure Mint'},\n {value: 'Mu Zha (Spring 2009)', text: 'Mu Zha (Spring 2009)'},\n {value: 'Clear Green Citrus', text: 'Clear Green Citrus'},\n {value: 'Cantaloupe and Cream', text: 'Cantaloupe and Cream'},\n {value: 'YMY 1960 Genmai Green', text: 'YMY 1960 Genmai Green'},\n {value: 'Silk Tie Guan Yin', text: 'Silk Tie Guan Yin'},\n {value: 'Camomilla', text: 'Camomilla'},\n {value: 'Fujieda Sencha', text: 'Fujieda Sencha'},\n {value: 'Yorkshire Harrogate', text: 'Yorkshire Harrogate'},\n {value: 'Rooibos Vanilla (Red Tea)', text: 'Rooibos Vanilla (Red Tea)'},\n {value: 'Ginger &amp; Lemon Myrtle', text: 'Ginger &amp; Lemon Myrtle'},\n {value: 'Butterfly Jasmine', text: 'Butterfly Jasmine'},\n {value: 'Carrot Cake', text: 'Carrot Cake'},\n {value: 'Epice Noire Cerise Sauvage', text: 'Epice Noire Cerise Sauvage'},\n {value: 'Cookie', text: 'Cookie'},\n {value: 'Izu Matcha', text: 'Izu Matcha'},\n {value: 'Divine Temptation', text: 'Divine Temptation'},\n {value: 'Matte Leao', text: 'Matte Leao'},\n {value: 'Fairtrade Luxury Gold teabags',\n text: 'Fairtrade Luxury Gold teabags'},\n {value: 'Mélange du Jardin dAlix', text: 'Mélange du Jardin dAlix'},\n {value: 'Okayti Darjeeling', text: 'Okayti Darjeeling'},\n {value: 'Black Cherry Matcha', text: 'Black Cherry Matcha'},\n {value: 'Gen Mai Cha Green Tea', text: 'Gen Mai Cha Green Tea'},\n {value: 'Peach Paradise', text: 'Peach Paradise'},\n {value: 'Ti Kwan Yin (cubed)', text: 'Ti Kwan Yin (cubed)'},\n {value: 'Earl Grey Premium', text: 'Earl Grey Premium'},\n {value: 'Sakura Black Japanese Black Tea Blend',\n text: 'Sakura Black Japanese Black Tea Blend'},\n {value: 'Mango and Friends', text: 'Mango and Friends'},\n {value: 'Jun Chiyabari Estate Nepal Tea',\n text: 'Jun Chiyabari Estate Nepal Tea'},\n {value: 'Charcoal Roasted Dong Ding', text: 'Charcoal Roasted Dong Ding'},\n {value: 'Osmanthus Oolong Tea 2nd Grade',\n text: 'Osmanthus Oolong Tea 2nd Grade'},\n {value: 'Darjeeling Badamtam', text: 'Darjeeling Badamtam'},\n {value: '2007 Haiwan Ripe Pu-erh tea with Rose Mini tuo cha',\n text: '2007 Haiwan Ripe Pu-erh tea with Rose Mini tuo cha'},\n {value: 'Sakura Sencha', text: 'Sakura Sencha'},\n {value: 'Dian Hong Yunnan red tea', text: 'Dian Hong Yunnan red tea'},\n {value: 'Bai Lin Gong Fu', text: 'Bai Lin Gong Fu'},\n {value: 'Gen-mai Cha - (TJ21)', text: 'Gen-mai Cha - (TJ21)'},\n {value: 'Xiaguan Tuocha puerh 2008', text: 'Xiaguan Tuocha puerh 2008'},\n {value: 'Alishan High Mountain Oolong tea Lot 206',\n text: 'Alishan High Mountain Oolong tea Lot 206'},\n {value: 'CO2 Premium Decaffeinated Earl Grey (TXE9)',\n text: 'CO2 Premium Decaffeinated Earl Grey (TXE9)'},\n {value: 'Black Currant Nilgiri', text: 'Black Currant Nilgiri'},\n {value: 'Oolong Royal', text: 'Oolong Royal'},\n {value: 'Mint Green Tea', text: 'Mint Green Tea'},\n {value: 'Irish Breakfast Tea - Special Reserve',\n text: 'Irish Breakfast Tea - Special Reserve'},\n {value: 'Bedouin Chai', text: 'Bedouin Chai'},\n {value: 'Springtime Blossoms', text: 'Springtime Blossoms'},\n {value: 'Richmond', text: 'Richmond'},\n {value: 'Celebration', text: 'Celebration'},\n {value: 'green tea with orange and peppermint',\n text: 'green tea with orange and peppermint'},\n {value: 'Keemun Panda', text: 'Keemun Panda'},\n {value: 'Rooibos Lemon Drop', text: 'Rooibos Lemon Drop'},\n {value: 'Black Silk Chocolate Milk Qu Hao',\n text: 'Black Silk Chocolate Milk Qu Hao'},\n {value: 'Organic Eagle Nest Ever Drop',\n text: 'Organic Eagle Nest Ever Drop'},\n {value: 'bai hao yin zhen (silver needle)',\n text: 'bai hao yin zhen (silver needle)'},\n {value: 'EU Standard Handmade Premium High Mountain Wild-growing Long Jing (Dragon Well) Green Tea',\n text: 'Premium High Mountain Wild-growing Long Jing'},\n {value: 'Pai Mutan', text: 'Pai Mutan'},\n {value: 'Georgia Peach', text: 'Georgia Peach'},\n {value: 'Manhattan Tribute Blend', text: 'Manhattan Tribute Blend'},\n {value: 'Creme Caramel Rooibos', text: 'Creme Caramel Rooibos'},\n {value: 'Oorchid Oolong', text: 'Oorchid Oolong'},\n {value: 'Yunnan Spiral Buds', text: 'Yunnan Spiral Buds'},\n {value: '2009 Yin Gou Mei Cha', text: '2009 Yin Gou Mei Cha'},\n {value: 'Te Ji Pearl Jasmine', text: 'Te Ji Pearl Jasmine'},\n {value: 'Jin Xuan Oolong', text: 'Jin Xuan Oolong'},\n {value: 'Toasted Marshmallow', text: 'Toasted Marshmallow'},\n {value: 'Glitter &amp; Gold', text: 'Glitter &amp; Gold'},\n {value: 'Ceylon Fancy Silvertips', text: 'Ceylon Fancy Silvertips'},\n {value: 'Bee Pollen Matcha', text: 'Bee Pollen Matcha'},\n {value: 'Dancing Lily', text: 'Dancing Lily'},\n {value: 'Matcha Miyabi', text: 'Matcha Miyabi'},\n {value: 'Peach Fruit Tea', text: 'Peach Fruit Tea'},\n {value: 'Vanilla Orange Rooibos', text: 'Vanilla Orange Rooibos'},\n {value: 'Organic Mint', text: 'Organic Mint'},\n {value: 'Mintastic', text: 'Mintastic'},\n {value: 'Organic Cinnamon Vanilla Rooibos',\n text: 'Organic Cinnamon Vanilla Rooibos'},\n {value: 'Hunan Golden Twist [Out of stock]',\n text: 'Hunan Golden Twist [Out of stock]'},\n {value: 'Hibiscus Peppermint Refreshment',\n text: 'Hibiscus Peppermint Refreshment'},\n {value: 'Caramel Delight', text: 'Caramel Delight'},\n {value: 'Lemon Green Tea', text: 'Lemon Green Tea'},\n {value: 'Phoenix Mountain Oolong', text: 'Phoenix Mountain Oolong'},\n {value: 'Lapsang Souchong Smoky Black Tea (Yan Xun Zheng Shan Xiao Zhong)',\n text: 'Lapsang Souchong Smoky Black Tea (Yan Xun Zheng Shan Xiao Zhong)'},\n {value: 'Earl Grey Bravo', text: 'Earl Grey Bravo'},\n {value: 'Organic Chamomile Creamsicle',\n text: 'Organic Chamomile Creamsicle'},\n {value: 'Wild Cherry', text: 'Wild Cherry'},\n {value: 'Strawberry Santiago', text: 'Strawberry Santiago'},\n {value: 'Ginger Twist', text: 'Ginger Twist'},\n {value: 'extra fancy ceylon orange pekoe',\n text: 'extra fancy ceylon orange pekoe'},\n {value: 'Keemun Mao Feng Black Tea (Keemun Mao Feng Hong Cha)',\n text: 'Keemun Mao Feng Black Tea (Keemun Mao Feng Hong Cha)'},\n {value: 'Almond Happiness', text: 'Almond Happiness'},\n {value: 'Fancy Grade Formosa Oolong', text: 'Fancy Grade Formosa Oolong'},\n {value: 'Chocolate Orange Tea', text: 'Chocolate Orange Tea'},\n {value: 'Blueberry Pomegranate Tea', text: 'Blueberry Pomegranate Tea'},\n {value: 'Earl Grey Blue Flower (TE16)',\n text: 'Earl Grey Blue Flower (TE16)'},\n {value: 'Mango and Yogurt', text: 'Mango and Yogurt'},\n {value: 'Green Passionfruit', text: 'Green Passionfruit'},\n {value: 'Ration Tea', text: 'Ration Tea'},\n {value: 'Formosa Mingjian GABA Tea', text: 'Formosa Mingjian GABA Tea'},\n {value: 'Plum Blossom Oolong Reserve',\n text: 'Plum Blossom Oolong Reserve'},\n {value: 'Strawberry Lemonade', text: 'Strawberry Lemonade'},\n {value: 'The West Lake Dragon Well Tea',\n text: 'The West Lake Dragon Well Tea'},\n {value: 'Christmas Spice', text: 'Christmas Spice'},\n {value: 'Mango Silly Antro', text: 'Mango Silly Antro'},\n {value: 'Organic Cape Malay Rooibos Chai',\n text: 'Organic Cape Malay Rooibos Chai'},\n {value: 'ZP82: Pre-Chingming Golden Monkey 2011',\n text: 'ZP82: Pre-Chingming Golden Monkey 2011'},\n {value: 'Assam GFOP', text: 'Assam GFOP'},\n {value: 'Turkish Spice Mint', text: 'Turkish Spice Mint'},\n {value: 'Blood Orange Loves Mint', text: 'Blood Orange Loves Mint'},\n {value: 'Master Xus Rou Gui', text: 'Master Xus Rou Gui'},\n {value: 'Taiwan Sansia Bi Luo Chun Green Tea',\n text: 'Taiwan Sansia Bi Luo Chun Green Tea'},\n {value: 'Japan Sencha Extra Fine - 705',\n text: 'Japan Sencha Extra Fine - 705'},\n {value: 'Pu Erh Dante', text: 'Pu Erh Dante'},\n {value: 'Belgian Mint', text: 'Belgian Mint'},\n {value: 'Pineapple Waikiki', text: 'Pineapple Waikiki'},\n {value: 'Rooibos Rejuvenating', text: 'Rooibos Rejuvenating'},\n {value: 'Assam organic Oaklands TGFOP',\n text: 'Assam organic Oaklands TGFOP'},\n {value: 'Iced Princess', text: 'Iced Princess'},\n {value: 'Assam Organic', text: 'Assam Organic'},\n {value: 'Boston Harbour Tea', text: 'Boston Harbour Tea'},\n {value: 'Mt. Wu Dong Zhi Lan Orchid Dan Cong',\n text: 'Mt. Wu Dong Zhi Lan Orchid Dan Cong'},\n {value: 'Yunnan Dian', text: 'Yunnan Dian'},\n {value: 'Mo Li Long Tiao', text: 'Mo Li Long Tiao'},\n {value: 'Ice Cream Cake', text: 'Ice Cream Cake'},\n {value: 'Petrushka', text: 'Petrushka'},\n {value: 'white eagle', text: 'white eagle'},\n {value: 'Soba - Roasted Buckwheat', text: 'Soba - Roasted Buckwheat'},\n {value: 'Superfruit Kombucha (Antioxidant)',\n text: 'Superfruit Kombucha (Antioxidant)'},\n {value: 'Green Tea Chai with Pomegranate',\n text: 'Green Tea Chai with Pomegranate'},\n {value: 'Yin Gou Mei Cha', text: 'Yin Gou Mei Cha'},\n {value: 'Meijiawu Lung Ching', text: 'Meijiawu Lung Ching'},\n {value: 'Himalayan Shangri La White Organic',\n text: 'Himalayan Shangri La White Organic'},\n {value: 'Cranberry Raspberry and Elderflower',\n text: 'Cranberry Raspberry and Elderflower'},\n {value: 'Twinings Camomile &amp; Spiced Apple Tea',\n text: 'Twinings Camomile &amp; Spiced Apple Tea'},\n {value: 'Orange Brulee', text: 'Orange Brulee'},\n {value: 'Formosa Pouchong', text: 'Formosa Pouchong'},\n {value: 'Golden Strand Black Tea', text: 'Golden Strand Black Tea'},\n {value: 'Golden Needles', text: 'Golden Needles'},\n {value: 'Green Tea Chae Orient', text: 'Green Tea Chae Orient'},\n {value: 'Sweet Cranberry Black', text: 'Sweet Cranberry Black'},\n {value: 'Dragonwater Jasmine (Special)',\n text: 'Dragonwater Jasmine (Special)'},\n {value: 'Yunnan Gold Tip Black', text: 'Yunnan Gold Tip Black'},\n {value: 'Charleston Breakfast', text: 'Charleston Breakfast'},\n {value: '2012 Huron Gold Needle Shou Pu-erh Cake',\n text: '2012 Huron Gold Needle Shou Pu-erh Cake'},\n {value: 'Genmaicha Japan', text: 'Genmaicha Japan'},\n {value: 'Scarlet Cloud', text: 'Scarlet Cloud'},\n {value: 'Banane Chocolat', text: 'Banane Chocolat'},\n {value: 'Juicy Pear', text: 'Juicy Pear'},\n {value: 'White Mist', text: 'White Mist'},\n {value: 'Wu Yi Qi Zhong Rock Oolong (Organic) 2009',\n text: 'Wu Yi Qi Zhong Rock Oolong (Organic) 2009'},\n {value: 'Earl Grey Lavender Tea 16 single cup Infusers',\n text: 'Earl Grey Lavender Tea 16 single cup Infusers'},\n {value: 'Irish Creme Nite Cap', text: 'Irish Creme Nite Cap'},\n {value: 'Mint Chocolate Chip Honeybush',\n text: 'Mint Chocolate Chip Honeybush'},\n {value: '365 Every Day Organic Citrus Black Tea Blend',\n text: '365 Every Day Organic Citrus Black Tea Blend'},\n {value: '2015 Crimson Lotus Baiying Whispering Sunshine',\n text: '2015 Crimson Lotus Baiying Whispering Sunshine'},\n {value: 'Gyokuro Yamashiro', text: 'Gyokuro Yamashiro'},\n {value: 'Rose Violet Calendula Oolong',\n text: 'Rose Violet Calendula Oolong'},\n {value: 'Green &amp; Fruity', text: 'Green &amp; Fruity'},\n {value: 'Decision Maker', text: 'Decision Maker'},\n {value: 'Organic Sencha 10', text: 'Organic Sencha 10'},\n {value: 'Ginger Breakfast', text: 'Ginger Breakfast'},\n {value: 'Fanciest Formosa Oolong', text: 'Fanciest Formosa Oolong'},\n {value: 'Organic Jade Oolong Tea', text: 'Organic Jade Oolong Tea'},\n {value: 'Bavarian Cream Matcha (White Matcha Base)',\n text: 'Bavarian Cream Matcha (White Matcha Base)'},\n {value: 'LongJing (Dragon Well)', text: 'LongJing (Dragon Well)'},\n {value: 'Silky (Classic) Earl Grey', text: 'Silky (Classic) Earl Grey'},\n {value: 'Gingerbread Spice', text: 'Gingerbread Spice'},\n {value: 'Genmaicha Organic', text: 'Genmaicha Organic'},\n {value: 'Yin Hao Jasmine', text: 'Yin Hao Jasmine'},\n {value: 'Elaines Blend', text: 'Elaines Blend'},\n {value: 'Winter Frost', text: 'Winter Frost'},\n {value: 'Organic Manitou Masala Chai',\n text: 'Organic Manitou Masala Chai'},\n {value: 'Stu Tea', text: 'Stu Tea'},\n {value: 'BIO China Golden Yunnan Special Pekoe',\n text: 'BIO China Golden Yunnan Special Pekoe'},\n {value: 'Assam Melody', text: 'Assam Melody'},\n {value: 'Wanja Purple Tea', text: 'Wanja Purple Tea'},\n {value: 'Double Spice Chai Tea', text: 'Double Spice Chai Tea'},\n {value: 'Kyobancha', text: 'Kyobancha'},\n {value: 'Rose Tuocha', text: 'Rose Tuocha'},\n {value: 'Gyokuro Imperial', text: 'Gyokuro Imperial'},\n {value: 'Jasmine Dragon Tears', text: 'Jasmine Dragon Tears'},\n {value: 'Smooth Earl', text: 'Smooth Earl'},\n {value: 'Casablanca Twist', text: 'Casablanca Twist'},\n {value: 'Decaf Peach', text: 'Decaf Peach'},\n {value: 'Meng Ding Yellow Bud (Huang Ya) Traditional Style',\n text: 'Meng Ding Yellow Bud (Huang Ya) Traditional Style'},\n {value: 'Pink Grapefruit (Sip for the Cure)',\n text: 'Pink Grapefruit (Sip for the Cure)'},\n {value: 'citrus kiss', text: 'citrus kiss'},\n {value: 'Herbal Spiced Tea', text: 'Herbal Spiced Tea'},\n {value: '2007 Da Hong Pao by Hui Yuan Yan Cha Tea Factory',\n text: '2007 Da Hong Pao by Hui Yuan Yan Cha Tea Factory'},\n {value: 'Tienchi Flower Tea - Yunnan Imperial Pseudo Ginseng(Tianqi) Herbal Tea',\n text: 'Tienchi Flower Tea'},\n {value: 'Chocolate Mint Truffle', text: 'Chocolate Mint Truffle'},\n {value: 'Organic Pomegranate Rosehip',\n text: 'Organic Pomegranate Rosehip'},\n {value: 'Egyptian Chamomile and Delicate Apple',\n text: 'Egyptian Chamomile and Delicate Apple'},\n {value: 'Wuyi Oolong Tea', text: 'Wuyi Oolong Tea'},\n {value: 'Himalaya ginger harmony', text: 'Himalaya ginger harmony'},\n {value: 'Wissotzky Earl Grey', text: 'Wissotzky Earl Grey'},\n {value: 'Kuki-Cha Twig Tea With Matcha (Blenders Series)',\n text: 'Kuki-Cha Twig Tea With Matcha (Blenders Series)'},\n {value: 'Small Tribute Cake', text: 'Small Tribute Cake'},\n {value: 'Ali Shan High-Mountain Oolong',\n text: 'Ali Shan High-Mountain Oolong'},\n {value: 'White Pearl of Fujian', text: 'White Pearl of Fujian'},\n {value: 'Yin Zhen', text: 'Yin Zhen'},\n {value: 'Get Passionate - No.17 (Wellness Collection)',\n text: 'Get Passionate - No.17 (Wellness Collection)'},\n {value: '2012 First Flush Namring SFTGFOP1',\n text: '2012 First Flush Namring SFTGFOP1'},\n {value: 'Green Tea - With a Touch of Lemon',\n text: 'Green Tea - With a Touch of Lemon'},\n {value: 'TD75: Glenburn Estate FTGFOP1 Cl First Flush (DJ-4)',\n text: 'TD75: Glenburn Estate FTGFOP1 Cl First Flush (DJ-4)'},\n {value: '2012 First Flush Darjeeling Castleton Estate',\n text: '2012 First Flush Darjeeling Castleton Estate'},\n {value: 'Ultraviolet', text: 'Ultraviolet'},\n {value: 'Lavender Earl Grey Organic (TE12)',\n text: 'Lavender Earl Grey Organic (TE12)'},\n {value: 'Fujian Premium Black', text: 'Fujian Premium Black'},\n {value: 'Dragonwell AAA (longling)', text: 'Dragonwell AAA (longling)'},\n {value: 'Green Tea Strawberries And Cream',\n text: 'Green Tea Strawberries And Cream'},\n {value: 'Yuzu Sencha', text: 'Yuzu Sencha'},\n {value: '2009 Old Plantation Qing Xin',\n text: '2009 Old Plantation Qing Xin'},\n {value: 'Kericho Gold Tea', text: 'Kericho Gold Tea'},\n {value: 'Superfine Jasmine Downy Dragon Pearls Green Tea',\n text: 'Superfine Jasmine Downy Dragon Pearls Green Tea'},\n {value: 'Chinese Breakfast', text: 'Chinese Breakfast'},\n {value: 'Asian Mint', text: 'Asian Mint'},\n {value: 'Organic Vietnam Nam Lanh Black Tea',\n text: 'Organic Vietnam Nam Lanh Black Tea'},\n {value: 'Coconut Cream Pie', text: 'Coconut Cream Pie'},\n {value: 'Superfruit Unity', text: 'Superfruit Unity'},\n {value: 'Lemon Oolong (FO01)', text: 'Lemon Oolong (FO01)'},\n {value: 'peach flavored black tea', text: 'peach flavored black tea'},\n {value: 'Organic Bailin Gongfu Black Tea',\n text: 'Organic Bailin Gongfu Black Tea'},\n {value: 'Pouchong', text: 'Pouchong'},\n {value: 'Lemon Yunnan', text: 'Lemon Yunnan'},\n {value: 'White Cream Tea', text: 'White Cream Tea'},\n {value: 'President’s Tea Rare Darjeeling',\n text: 'President’s Tea Rare Darjeeling'},\n {value: 'Organic Hawaiian Dream', text: 'Organic Hawaiian Dream'},\n {value: 'Lemon Ginseng', text: 'Lemon Ginseng'},\n {value: 'Earl Grey Reserve', text: 'Earl Grey Reserve'},\n {value: 'Grandmas Pumpkin Pie', text: 'Grandmas Pumpkin Pie'},\n {value: 'Sweet Clementine Chamomile', text: 'Sweet Clementine Chamomile'},\n {value: 'Oriental Beauty Bai Hao Oolong Superior Grade',\n text: 'Oriental Beauty Bai Hao Oolong Superior Grade'},\n {value: 'Giddapahar Musk Second Flush',\n text: 'Giddapahar Musk Second Flush'},\n {value: 'Formosa Pouchong Xian Shan (TT07)',\n text: 'Formosa Pouchong Xian Shan (TT07)'},\n {value: 'Hoji-cha Roasted Green Tea', text: 'Hoji-cha Roasted Green Tea'},\n {value: 'Sassy Strawberry', text: 'Sassy Strawberry'},\n {value: 'Oh Canada', text: 'Oh Canada'},\n {value: 'Organic Madagascar Bourbon Vanilla',\n text: 'Organic Madagascar Bourbon Vanilla'},\n {value: 'Morning Thunder', text: 'Morning Thunder'},\n {value: 'Wenshan Baozhong Taiwan Pou Chong Oolong Loose Tea',\n text: 'Wenshan Baozhong Taiwan Pou Chong Oolong Loose Tea'},\n {value: 'Queen of Babylon', text: 'Queen of Babylon'},\n {value: 'Ichiban Sencha', text: 'Ichiban Sencha'},\n {value: 'Organic Buddhist Tea (Fo Cha)',\n text: 'Organic Buddhist Tea (Fo Cha)'},\n {value: 'Chocolate Delight', text: 'Chocolate Delight'},\n {value: 'Matcha Chai', text: 'Matcha Chai'},\n {value: 'Sunny Slopes', text: 'Sunny Slopes'},\n {value: 'Lime Bang', text: 'Lime Bang'},\n {value: 'Jin Jun Mei (Golden Eyebrow)',\n text: 'Jin Jun Mei (Golden Eyebrow)'},\n {value: 'Sweet Dreams', text: 'Sweet Dreams'},\n {value: 'Bhakti Chai', text: 'Bhakti Chai'},\n {value: 'Raspberry Oolong', text: 'Raspberry Oolong'},\n {value: 'Puer Velour', text: 'Puer Velour'},\n {value: 'Soiree dhiver', text: 'Soiree dhiver'},\n {value: 'Guayusa (organic)', text: 'Guayusa (organic)'},\n {value: 'Executus', text: 'Executus'},\n {value: 'Margeaux Vanilla', text: 'Margeaux Vanilla'},\n {value: 'Arabian Mint Tea with Honey',\n text: 'Arabian Mint Tea with Honey'},\n {value: 'Mind Boost Mint', text: 'Mind Boost Mint'},\n {value: 'Honey Lemon Ginseng Green Tea',\n text: 'Honey Lemon Ginseng Green Tea'},\n {value: '1980s Aged Sheng Wet-stored pu erh cake',\n text: '1980s Aged Sheng Wet-stored pu erh cake'},\n {value: '1999 Aged Liu An Basket of Anhui',\n text: '1999 Aged Liu An Basket of Anhui'},\n {value: 'China Zhen Mei Special', text: 'China Zhen Mei Special'},\n {value: '2009 winter wood-roasted shui xian',\n text: '2009 winter wood-roasted shui xian'},\n {value: 'Sweet Lemon Green Rooibos', text: 'Sweet Lemon Green Rooibos'},\n {value: 'Assam TGFOP1 Jonak', text: 'Assam TGFOP1 Jonak'},\n {value: 'Superior Teh Kuan Yin', text: 'Superior Teh Kuan Yin'},\n {value: 'Baked Apple Pie', text: 'Baked Apple Pie'},\n {value: 'Apple &amp; Cinnamon Twist', text: 'Apple &amp; Cinnamon Twist'},\n {value: 'Matcha Tea', text: 'Matcha Tea'},\n {value: 'Lychee Pear', text: 'Lychee Pear'},\n {value: 'Tower of London Blend', text: 'Tower of London Blend'},\n {value: '2010 Bulang Mountain Autumn Bing',\n text: '2010 Bulang Mountain Autumn Bing'},\n {value: 'Alishan Spring 2012', text: 'Alishan Spring 2012'},\n {value: 'Qimen Hong Gong Fu', text: 'Qimen Hong Gong Fu'},\n {value: 'Buddhas Tea - Jiu Hua Shan Fo Cha',\n text: 'Buddhas Tea - Jiu Hua Shan Fo Cha'},\n {value: 'Organic Peach Rooibos', text: 'Organic Peach Rooibos'},\n {value: 'Li Shan', text: 'Li Shan'},\n {value: 'Sencha Goji Berry', text: 'Sencha Goji Berry'},\n {value: 'Sore Throat Soother', text: 'Sore Throat Soother'},\n {value: 'Green Seduction (organic)', text: 'Green Seduction (organic)'},\n {value: 'Super Skinny Mandarin Orange',\n text: 'Super Skinny Mandarin Orange'},\n {value: 'Lincang Maofeng', text: 'Lincang Maofeng'},\n {value: '2005 Fuhai Golden Strand Early Spring Shu',\n text: '2005 Fuhai Golden Strand Early Spring Shu'},\n {value: 'Decaf Vanilla', text: 'Decaf Vanilla'},\n {value: 'Mango Orange Organic Tea', text: 'Mango Orange Organic Tea'},\n {value: 'Berry Poppins', text: 'Berry Poppins'},\n {value: 'Diplomats Tea™ - 765', text: 'Diplomats Tea™ - 765'},\n {value: 'Honeybush Citrus', text: 'Honeybush Citrus'},\n {value: 'Almond Blossom Oolong', text: 'Almond Blossom Oolong'},\n {value: 'Honeybee', text: 'Honeybee'},\n {value: 'Wuyi Dark Roast', text: 'Wuyi Dark Roast'},\n {value: 'Golden Pu-erh 5 Years', text: 'Golden Pu-erh 5 Years'},\n {value: 'Violette', text: 'Violette'},\n {value: 'Organic Masala Chai', text: 'Organic Masala Chai'},\n {value: 'Plum Good Tea', text: 'Plum Good Tea'},\n {value: 'Purple Bamboo', text: 'Purple Bamboo'},\n {value: 'Honeysuckle', text: 'Honeysuckle'},\n {value: 'UVA Highlands', text: 'UVA Highlands'},\n {value: 'ZG18: Chun Mee (Moon Palace)',\n text: 'ZG18: Chun Mee (Moon Palace)'},\n {value: 'Pineapple', text: 'Pineapple'},\n {value: 'Pomegranate Pai Mu Tan', text: 'Pomegranate Pai Mu Tan'},\n {value: 'Tuscan Garden', text: 'Tuscan Garden'},\n {value: 'Aloha', text: 'Aloha'},\n {value: '2006 Haiwan Peacock Quest 250 g Shu Pu-Erh Tea Brick',\n text: '2006 Haiwan Peacock Quest 250 g Shu Pu-Erh Tea Brick'},\n {value: 'Earl Grey Rooibos', text: 'Earl Grey Rooibos'},\n {value: 'Vanilla Spice Perfect Energy',\n text: 'Vanilla Spice Perfect Energy'},\n {value: 'Vitality Herbal Tea', text: 'Vitality Herbal Tea'},\n {value: 'T-99 Oolong Fancy', text: 'T-99 Oolong Fancy'},\n {value: 'Kings 913 Green Oolong 3rd Grade',\n text: 'Kings 913 Green Oolong 3rd Grade'},\n {value: 'Imperial Gold Oolong', text: 'Imperial Gold Oolong'},\n {value: 'Matcha Jo', text: 'Matcha Jo'},\n {value: 'Black Spiral', text: 'Black Spiral'},\n {value: 'Red Rooibos with Sutherlandia',\n text: 'Red Rooibos with Sutherlandia'},\n {value: 'Mt. Kenya Black', text: 'Mt. Kenya Black'},\n {value: 'Chai (White Coffee Infusion)',\n text: 'Chai (White Coffee Infusion)'},\n {value: 'Double Green Matcha Tea (Certified Organic)',\n text: 'Double Green Matcha Tea (Certified Organic)'},\n {value: 'Yin Zhen Silver Needle White Tea',\n text: 'Yin Zhen Silver Needle White Tea'},\n {value: 'Daoli Oriental Trip', text: 'Daoli Oriental Trip'},\n {value: 'Rooibos Espresso', text: 'Rooibos Espresso'},\n {value: 'Honey Vanilla White Tea Chai',\n text: 'Honey Vanilla White Tea Chai'},\n {value: 'Chocolate Pumpkin Pie', text: 'Chocolate Pumpkin Pie'},\n {value: 'Green Geisha', text: 'Green Geisha'},\n {value: 'Darjeeling Sungma Dj-149 2nd flush organic',\n text: 'Darjeeling Sungma Dj-149 2nd flush organic'},\n {value: 'Phoenix Yunnan Gold', text: 'Phoenix Yunnan Gold'},\n {value: 'Precious Eyebrow', text: 'Precious Eyebrow'},\n {value: 'Traditional Spring 2010 Lishan Oolong',\n text: 'Traditional Spring 2010 Lishan Oolong'},\n {value: 'Daydreamer', text: 'Daydreamer'},\n {value: 'Chocolate Strawberry Temptation',\n text: 'Chocolate Strawberry Temptation'},\n {value: 'Hibiscus Berry', text: 'Hibiscus Berry'},\n {value: 'Cotton Candy', text: 'Cotton Candy'},\n {value: 'Forest White', text: 'Forest White'},\n {value: 'Peppermint &amp; English Toffee',\n text: 'Peppermint English Toffee'},\n {value: 'pu-erh loose leaf 7-8 yr', text: 'pu-erh loose leaf 7-8 yr'},\n {value: 'Organic Nonpareil She Qian Dragon Well Long Jing Green Tea',\n text: 'Organic Nonpareil She Qian Dragon Well Long Jing Green Tea'},\n {value: 'Yunnan Leaping Tiger', text: 'Yunnan Leaping Tiger'},\n {value: 'Hepburn', text: 'Hepburn'},\n {value: 'Nilgiri Parkside', text: 'Nilgiri Parkside'},\n {value: 'Mulled Hibiscus Clove', text: 'Mulled Hibiscus Clove'},\n {value: 'Darjeeling 1st Flush', text: 'Darjeeling 1st Flush'},\n {value: 'To Life', text: 'To Life'},\n {value: 'Castleton FTGFOP', text: 'Castleton FTGFOP'},\n {value: 'Uji Genmai Matcha', text: 'Uji Genmai Matcha'},\n {value: 'Herbal Orange Spice', text: 'Herbal Orange Spice'},\n {value: '2006 Menghai Mount Elephant',\n text: '2006 Menghai Mount Elephant'},\n {value: '2006 FuHai 7576 Ripe', text: '2006 FuHai 7576 Ripe'},\n {value: 'Gyokuro Hoshino', text: 'Gyokuro Hoshino'},\n {value: 'Manderin Puerh', text: 'Manderin Puerh'},\n {value: 'Yerba Mate Pure Endurance', text: 'Yerba Mate Pure Endurance'},\n {value: 'Maple and Brown Sugar Oatmeal Black Tea',\n text: 'Maple and Brown Sugar Oatmeal Black Tea'},\n {value: 'Spiced Fig', text: 'Spiced Fig'},\n {value: 'Exotic Passion', text: 'Exotic Passion'},\n {value: 'Huangshan Mao Feng Supreme', text: 'Huangshan Mao Feng Supreme'},\n {value: 'Creme de la Earl Grey', text: 'Creme de la Earl Grey'},\n {value: 'Madagascan Vanilla', text: 'Madagascan Vanilla'},\n {value: 'New England Harvest Blend (TE57)',\n text: 'New England Harvest Blend (TE57)'},\n {value: 'Forest Dwarf', text: 'Forest Dwarf'},\n {value: 'Lemon Drops', text: 'Lemon Drops'},\n {value: 'Kyoto Cherry Blossom', text: 'Kyoto Cherry Blossom'},\n {value: 'Pussimbing Green', text: 'Pussimbing Green'},\n {value: 'Taiwan Sweet Summer Oolong', text: 'Taiwan Sweet Summer Oolong'},\n {value: 'Jazz Mint', text: 'Jazz Mint'},\n {value: 'Vanilla Creme Black Tea', text: 'Vanilla Creme Black Tea'},\n {value: 'Little Melon Seed (Lu An Gua Pian)',\n text: 'Little Melon Seed (Lu An Gua Pian)'},\n {value: 'Moment of calm: Orange Mango &amp; Cinnamon',\n text: 'Moment of calm: Orange Mango &amp; Cinnamon'},\n {value: 'Prince of Whales English Favourites Black Tea Blends',\n text: 'Prince of Whales English Favourites Black Tea Blends'},\n {value: '2016 Yunnan Sourcing Autumn Bing Dao Lao Zhai Raw Puerh Tea',\n text: '2016 Autumn Bing Dao Lao Zhai Raw Puerh Tea'},\n {value: 'Jade Snail', text: 'Jade Snail'},\n {value: 'Love Spell', text: 'Love Spell'},\n {value: 'Wuyi Yancha [Out of stock]', text: 'Wuyi Yancha [Out of stock]'},\n {value: 'ZY07: Seasons Pick Yunnan Black Snail',\n text: 'ZY07: Seasons Pick Yunnan Black Snail'},\n {value: 'Formosa Green Pi Lo Chun (TT61)',\n text: 'Formosa Green Pi Lo Chun (TT61)'},\n {value: 'Keemun A-Grade', text: 'Keemun A-Grade'},\n {value: 'WaghBakri', text: 'WaghBakri'},\n {value: 'Organic Silver Needle Premium',\n text: 'Organic Silver Needle Premium'},\n {value: '2012 Special Reserve Green', text: '2012 Special Reserve Green'},\n {value: 'Jasmine Jazz', text: 'Jasmine Jazz'},\n {value: 'Green Tea with Seaweed', text: 'Green Tea with Seaweed'},\n {value: 'Coconut Chai', text: 'Coconut Chai'},\n {value: 'Maccha au Lait', text: 'Maccha au Lait'},\n {value: 'Diet Partner Wellness Tea', text: 'Diet Partner Wellness Tea'},\n {value: 'Pu-erh Cabernet', text: 'Pu-erh Cabernet'},\n {value: 'Jin Jun Mei Souchong', text: 'Jin Jun Mei Souchong'},\n {value: 'Yunnan Golden Needle', text: 'Yunnan Golden Needle'},\n {value: 'China White Pai Mu Tan', text: 'China White Pai Mu Tan'},\n {value: 'Cocoa Praline Tart', text: 'Cocoa Praline Tart'},\n {value: 'China Keemun (No. 555)', text: 'China Keemun (No. 555)'},\n {value: 'Toasted Rice Green Tea - Japanese Genmaicha',\n text: 'Toasted Rice Green Tea - Japanese Genmaicha'},\n {value: 'Honey Lemon Tea', text: 'Honey Lemon Tea'},\n {value: 'Gyokuro Japanese Green Tea', text: 'Gyokuro Japanese Green Tea'},\n {value: 'organic puerh', text: 'organic puerh'},\n {value: 'Caramel', text: 'Caramel'},\n {value: 'Electric Lemon', text: 'Electric Lemon'},\n {value: 'Sungma Darjeeling', text: 'Sungma Darjeeling'},\n {value: 'Aged Traditional Anxi Tieguanyin',\n text: 'Aged Traditional Anxi Tieguanyin'},\n {value: 'Honeybush Mango', text: 'Honeybush Mango'},\n {value: 'Elixer of Immortality', text: 'Elixer of Immortality'},\n {value: 'Dokudami', text: 'Dokudami'},\n {value: 'Snow Bunny', text: 'Snow Bunny'},\n {value: 'Four Seasons Oolong', text: 'Four Seasons Oolong'},\n {value: 'Decaf Genmai Cha', text: 'Decaf Genmai Cha'},\n {value: 'Coconut Rum Creame Tea', text: 'Coconut Rum Creame Tea'},\n {value: 'Bai Mu Dan (White Peony) Organic White Tea',\n text: 'Bai Mu Dan (White Peony) Organic White Tea'},\n {value: 'Maple', text: 'Maple'},\n {value: 'Smokey Mountain Mate (Special Order)',\n text: 'Smokey Mountain Mate (Special Order)'},\n {value: 'Sencha Ariake', text: 'Sencha Ariake'},\n {value: 'East Frisian Leaf Blend Golden Tipped',\n text: 'East Frisian Leaf Blend Golden Tipped'},\n {value: 'Organic Turmeric Ginger', text: 'Organic Turmeric Ginger'},\n {value: 'Green Apple Watermelon', text: 'Green Apple Watermelon'},\n {value: 'Earl Green', text: 'Earl Green'},\n {value: 'Spezial Brocken Lecker Koppke',\n text: 'Spezial Brocken Lecker Koppke'},\n {value: 'Stems and Leaves', text: 'Stems and Leaves'},\n {value: 'Shanti Ayurvedic Tea', text: 'Shanti Ayurvedic Tea'},\n {value: '1997 Raw Loose Leaf Pu-erh Tea - Yunnan Broad Leaf Variety PL97',\n text: '1997 Raw Loose Leaf Pu-erh Tea - Yunnan Broad Leaf Variety PL97'},\n {value: 'Chamomile Mint', text: 'Chamomile Mint'},\n {value: 'Vanille Impériale', text: 'Vanille Impériale'},\n {value: 'Market Spice', text: 'Market Spice'},\n {value: 'Pai Mu Tan White Tea', text: 'Pai Mu Tan White Tea'},\n {value: 'Peach Paradise White Tea', text: 'Peach Paradise White Tea'},\n {value: 'Emperors Gold', text: 'Emperors Gold'},\n {value: 'Great White', text: 'Great White'},\n {value: 'Earl Grey a la Creme', text: 'Earl Grey a la Creme'},\n {value: 'Pomegranate Blend OG Decaf', text: 'Pomegranate Blend OG Decaf'},\n {value: 'Matcha Powder (Rare Tea Collection)',\n text: 'Matcha Powder (Rare Tea Collection)'},\n {value: 'Country Peach Passion', text: 'Country Peach Passion'},\n {value: 'Golden Yunan', text: 'Golden Yunan'},\n {value: 'Houji-Cha Roasted (Blenders Series)',\n text: 'Houji-Cha Roasted (Blenders Series)'},\n {value: 'Golden Pu-Erh', text: 'Golden Pu-Erh'},\n {value: 'Apple Ginger', text: 'Apple Ginger'},\n {value: 'Gypsy Cold Care', text: 'Gypsy Cold Care'},\n {value: 'Decaf Crème Caramel', text: 'Decaf Crème Caramel'},\n {value: 'Sencha Shinrikyu sampler', text: 'Sencha Shinrikyu sampler'},\n {value: 'the canterbury tea', text: 'the canterbury tea'},\n {value: 'Coconut Almond Delight', text: 'Coconut Almond Delight'},\n {value: 'Wild Yie Sheng Pu Erh', text: 'Wild Yie Sheng Pu Erh'},\n {value: 'Green Tea With Peach', text: 'Green Tea With Peach'},\n {value: 'Clipper Fairtrade Organic', text: 'Clipper Fairtrade Organic'},\n {value: '1997 imperial Shou Puerh', text: '1997 imperial Shou Puerh'},\n {value: 'natural rooibus', text: 'natural rooibus'},\n {value: 'Midnight Peony', text: 'Midnight Peony'},\n {value: 'Seasonal Eggnog Blend', text: 'Seasonal Eggnog Blend'},\n {value: 'Gin Shan Creme (White Dragon)',\n text: 'Gin Shan Creme (White Dragon)'},\n {value: 'Breakfast Blend (formerly Celtic Breakfast)',\n text: 'Breakfast Blend (formerly Celtic Breakfast)'},\n {value: 'Darjeeling 1st Flush Reserve',\n text: 'Darjeeling 1st Flush Reserve'},\n {value: 'Crimson Grove', text: 'Crimson Grove'},\n {value: 'Sexy Spicy Chai', text: 'Sexy Spicy Chai'},\n {value: 'Harvest Orange Spice', text: 'Harvest Orange Spice'},\n {value: 'Blueberry Black', text: 'Blueberry Black'},\n {value: 'Luscious Lemon Meringue', text: 'Luscious Lemon Meringue'},\n {value: 'Cacao Tea', text: 'Cacao Tea'},\n {value: 'Buckingham Palace Party', text: 'Buckingham Palace Party'},\n {value: 'Pomegranate Pizzazz', text: 'Pomegranate Pizzazz'},\n {value: 'Green Peony Rosette', text: 'Green Peony Rosette'},\n {value: 'Organic Queen Bee Balance', text: 'Organic Queen Bee Balance'},\n {value: 'Pu-erh Tuo Cha', text: 'Pu-erh Tuo Cha'},\n {value: 'China Da Zhang Shan Magnolia Organic Yellow',\n text: 'China Da Zhang Shan Magnolia Organic Yellow'},\n {value: 'Paradise Found', text: 'Paradise Found'},\n {value: 'Oriental Beauty Oolong Tea (Dong Fang Mei Ren Wu Long)',\n text: 'Oriental Beauty Oolong Tea (Dong Fang Mei Ren Wu Long)'},\n {value: 'Fuding Shou Mei White Tea Cake 2013',\n text: 'Fuding Shou Mei White Tea Cake 2013'},\n {value: 'Madura Pure Assam', text: 'Madura Pure Assam'},\n {value: 'Hojicha de la Creme', text: 'Hojicha de la Creme'},\n {value: 'Breakfast Tea Ritual - 2nd Flush Assam',\n text: 'Breakfast Tea Ritual - 2nd Flush Assam'},\n {value: 'Keemun Heng Ru Organic (ZK18)',\n text: 'Keemun Heng Ru Organic (ZK18)'},\n {value: 'Forest Berry Silver Needle', text: 'Forest Berry Silver Needle'},\n {value: 'Impérial Or', text: 'Impérial Or'},\n {value: 'All Spice Chai Overload', text: 'All Spice Chai Overload'},\n {value: 'Assam Moran BOP (BI02)', text: 'Assam Moran BOP (BI02)'},\n {value: 'Panyang Bohea Select', text: 'Panyang Bohea Select'},\n {value: 'YunLanXuan Lapsang Souchong',\n text: 'YunLanXuan Lapsang Souchong'},\n {value: 'Vintage Oolong', text: 'Vintage Oolong'},\n {value: 'Honyama Kukicha', text: 'Honyama Kukicha'},\n {value: 'Royal Wedding Commemmorative Blend',\n text: 'Royal Wedding Commemmorative Blend'},\n {value: 'Buccaneer', text: 'Buccaneer'},\n {value: 'Organic Vanilla Almond Rooibos',\n text: 'Organic Vanilla Almond Rooibos'},\n {value: 'Roastaroma', text: 'Roastaroma'},\n {value: 'Fauchon Blend Tea', text: 'Fauchon Blend Tea'},\n {value: 'Bestemors Frukthage', text: 'Bestemors Frukthage'},\n {value: 'Flavoured Apple Tea', text: 'Flavoured Apple Tea'},\n {value: 'Himalayan Oolong', text: 'Himalayan Oolong'},\n {value: 'Almond Black Tea', text: 'Almond Black Tea'},\n {value: 'Organic Chamomile (Camomila 100% da agricoltura biologica)',\n text: 'Organic Chamomile'},\n {value: 'TieGuanYin Monkey Picked-Oolong',\n text: 'TieGuanYin Monkey Picked-Oolong'},\n {value: '2011 Mansai', text: '2011 Mansai'},\n {value: 'Maple Cream Organic Black', text: 'Maple Cream Organic Black'},\n {value: 'Rooibos Rose Garden', text: 'Rooibos Rose Garden'},\n {value: 'Giddapahar SFTGFOP1 Ch Musc First Flush (DJ-28) (TDB6)',\n text: 'Giddapahar SFTGFOP1 Ch Musc First Flush (DJ-28) (TDB6)'},\n {value: 'Puer Cafe', text: 'Puer Cafe'},\n {value: 'Chamomile Citrus', text: 'Chamomile Citrus'},\n {value: 'Formosa oolong / berry witch',\n text: 'Formosa oolong / berry witch'},\n {value: 'Daily Club', text: 'Daily Club'},\n {value: 'Darjeeling Selimbong 2nd Flush',\n text: 'Darjeeling Selimbong 2nd Flush'},\n {value: 'Organic Indian Chai', text: 'Organic Indian Chai'},\n {value: 'Earl Grey Smoky', text: 'Earl Grey Smoky'},\n {value: 'Master Han’s Qianjiazhai Yunnan Green',\n text: 'Master Han’s Qianjiazhai Yunnan Green'},\n {value: 'Ile Maurice', text: 'Ile Maurice'},\n {value: 'Organic Fair Trade Darjeeling',\n text: 'Organic Fair Trade Darjeeling'},\n {value: 'Temi FTGFOP1', text: 'Temi FTGFOP1'},\n {value: 'Lemon Black tea', text: 'Lemon Black tea'},\n {value: 'Forget Him English Breakfast',\n text: 'Forget Him English Breakfast'},\n {value: 'Berlin Mix', text: 'Berlin Mix'},\n {value: 'Banana Jack', text: 'Banana Jack'},\n {value: '2017 Yunnan Sourcing Rooster King Ripe Pu-erh Tea Cake',\n text: '2017 Rooster King Ripe Pu-erh Tea Cake'},\n {value: '2009 Hong Yun', text: '2009 Hong Yun'},\n {value: 'Organic Mao Jian', text: 'Organic Mao Jian'},\n {value: 'Strong Aroma-Feng Huang Dan Cong Oolong-Premium Spring Tea-Deeply Fired',\n text: 'Strong Aroma-Feng Huang Dan Cong Oolong'},\n {value: 'Crimson Ceylon', text: 'Crimson Ceylon'},\n {value: 'Pink Pearls', text: 'Pink Pearls'},\n {value: 'Mountain Huckleberry', text: 'Mountain Huckleberry'},\n {value: 'Sakura Allure', text: 'Sakura Allure'},\n {value: 'Chamomile Blossoms', text: 'Chamomile Blossoms'},\n {value: 'Rooibos Sweet Amore', text: 'Rooibos Sweet Amore'},\n {value: 'Peanut Butter Chai', text: 'Peanut Butter Chai'},\n {value: 'A Minty-Fresh Monkey by Sarah Almon',\n text: 'A Minty-Fresh Monkey by Sarah Almon'},\n {value: '2000 Excellent Old Aged Ripe Pu-erh Tea Brick 250g',\n text: '2000 Excellent Old Aged Ripe Pu-erh Tea Brick 250g'},\n {value: 'Pineapple Paradise', text: 'Pineapple Paradise'},\n {value: 'Super Chocolate (organic)', text: 'Super Chocolate (organic)'},\n {value: 'Chocolate Covered Banana Honeybush',\n text: 'Chocolate Covered Banana Honeybush'},\n {value: 'Sweet Lemon Black Tea', text: 'Sweet Lemon Black Tea'},\n {value: 'No. 01 Rogue Whiskey Barrel Black Tea',\n text: 'No. 01 Rogue Whiskey Barrel Black Tea'},\n {value: 'Ceylon Kenilworth OP', text: 'Ceylon Kenilworth OP'},\n {value: 'Organic Dragonwell Lung Ching Green Tea',\n text: 'Organic Dragonwell Lung Ching Green Tea'},\n {value: 'Chocolate Covered Strawberry Puerh',\n text: 'Chocolate Covered Strawberry Puerh'},\n {value: 'Apple Blossom', text: 'Apple Blossom'},\n {value: 'Japan Kukicha Extra', text: 'Japan Kukicha Extra'},\n {value: 'Lychee Blossom', text: 'Lychee Blossom'},\n {value: 'Smoky Black T-Dust', text: 'Smoky Black T-Dust'},\n {value: 'Mengku Palace Ripened Golden Buds Loose Pu-erh Tea 2007',\n text: 'Mengku Palace Ripened Golden Buds Loose Pu-erh Tea 2007'},\n {value: 'Chocolate Raspberry Bliss', text: 'Chocolate Raspberry Bliss'},\n {value: 'Black Gold', text: 'Black Gold'},\n {value: 'Amba Tea Flower Tea', text: 'Amba Tea Flower Tea'},\n {value: 'Grapefruit Dragon', text: 'Grapefruit Dragon'},\n {value: 'Coconut', text: 'Coconut'},\n {value: 'Roasted Chestnut', text: 'Roasted Chestnut'},\n {value: 'Premium Organic Dragon Well',\n text: 'Premium Organic Dragon Well'},\n {value: 'Kenya Kapchorua Estate BP1 (TK35)',\n text: 'Kenya Kapchorua Estate BP1 (TK35)'},\n {value: 'Auspicious Ayame Wulong', text: 'Auspicious Ayame Wulong'},\n {value: 'Seasons Pick Vietnam CTC Black Tea (TV10)',\n text: 'Seasons Pick Vietnam CTC Black Tea (TV10)'},\n {value: '2011 Douji Xiang Dou Brick Raw Pu-erh Tea',\n text: '2011 Douji Xiang Dou Brick Raw Pu-erh Tea'},\n {value: 'Papaya Passion Fruit', text: 'Papaya Passion Fruit'},\n {value: 'Formosa Tung-Ting Milky Oolong (TT83)',\n text: 'Formosa Tung-Ting Milky Oolong (TT83)'},\n {value: 'Cream Earl Grey Black', text: 'Cream Earl Grey Black'},\n {value: 'Matcha Superior', text: 'Matcha Superior'},\n {value: 'Citron Oolong', text: 'Citron Oolong'},\n {value: 'Organic Earl Grey Black Tea',\n text: 'Organic Earl Grey Black Tea'},\n {value: 'Three Wishes Tea', text: 'Three Wishes Tea'},\n {value: 'Crazy Earl', text: 'Crazy Earl'},\n {value: 'Almond Cookie', text: 'Almond Cookie'},\n {value: 'Jasmine Silver Needle', text: 'Jasmine Silver Needle'},\n {value: 'Strawberry White', text: 'Strawberry White'},\n {value: 'Coconut Almond', text: 'Coconut Almond'},\n {value: 'Chocolate Cream', text: 'Chocolate Cream'},\n {value: 'Rum Butter', text: 'Rum Butter'},\n {value: 'Organic African Sunset', text: 'Organic African Sunset'},\n {value: 'Masalawalla Chai', text: 'Masalawalla Chai'},\n {value: 'Cranberry Fruit Tea', text: 'Cranberry Fruit Tea'},\n {value: 'Melbourne Breakfast', text: 'Melbourne Breakfast'},\n {value: 'Gui Fei Oolong', text: 'Gui Fei Oolong'},\n {value: 'Merry Cinna-Berry', text: 'Merry Cinna-Berry'},\n {value: 'Ceremonial Grade Matcha', text: 'Ceremonial Grade Matcha'},\n {value: 'Beer Tea', text: 'Beer Tea'},\n {value: 'Assam Medley', text: 'Assam Medley'},\n {value: 'Strawberry Shortcake', text: 'Strawberry Shortcake'},\n {value: 'Rooibos Masala Chai - Organic',\n text: 'Rooibos Masala Chai - Organic'},\n {value: 'Golden Buds Shu Puer Xingyang 2010',\n text: 'Golden Buds Shu Puer Xingyang 2010'},\n {value: 'Pingshui Gunpowder', text: 'Pingshui Gunpowder'},\n {value: 'Meyer Lemon', text: 'Meyer Lemon'},\n {value: 'Tomato Rebel Black Tea', text: 'Tomato Rebel Black Tea'},\n {value: 'Cold 911 (organic)', text: 'Cold 911 (organic)'},\n {value: 'Kona-Cha Sushi Tea (Blenders Series)',\n text: 'Kona-Cha Sushi Tea (Blenders Series)'},\n {value: 'Chili Chocolate', text: 'Chili Chocolate'},\n {value: 'Arya Estate 2nd Flush Darjeeling SFTGFOP1 (DJ-41)',\n text: 'Arya Estate 2nd Flush Darjeeling SFTGFOP1 (DJ-41)'},\n {value: 'Bolder Breakfast', text: 'Bolder Breakfast'},\n {value: 'Sheris Blend', text: 'Sheris Blend'},\n {value: 'Li Zi Nutcracker', text: 'Li Zi Nutcracker'},\n {value: 'Hu Shan Yellow Buds', text: 'Hu Shan Yellow Buds'},\n {value: 'Hualien Feng Mi', text: 'Hualien Feng Mi'},\n {value: 'Uva Ceylon', text: 'Uva Ceylon'},\n {value: 'Green Label', text: 'Green Label'},\n {value: 'Russian Samovar', text: 'Russian Samovar'},\n {value: 'Jin Die', text: 'Jin Die'},\n {value: 'Drum Mountain Clouds &amp; Mist (Gua Shan Yun Wu)',\n text: 'Drum Mountain Clouds Mist (Gua Shan Yun Wu)'},\n {value: 'Tochiotome Green', text: 'Tochiotome Green'},\n {value: 'Sugimoto Haruichis Shincha', text: 'Sugimoto Haruichis Shincha'},\n {value: 'China Yunnan', text: 'China Yunnan'},\n {value: 'Loke Lani', text: 'Loke Lani'},\n {value: 'Earl of Bengal Tea', text: 'Earl of Bengal Tea'},\n {value: 'Classic Formosa Oolong', text: 'Classic Formosa Oolong'},\n {value: 'Chamana Azul', text: 'Chamana Azul'},\n {value: 'Pear Oolong', text: 'Pear Oolong'},\n {value: 'Temi Sikkim Sk-3 1 st flush 2011',\n text: 'Temi Sikkim Sk-3 1 st flush 2011'},\n {value: 'Organic Vanilla Noir', text: 'Organic Vanilla Noir'},\n {value: 'DISCONTINUED - Spring Jade Tieguanyin (2012-2013)',\n text: 'DISCONTINUED - Spring Jade Tieguanyin (2012-2013)'},\n {value: 'Berry DeTox', text: 'Berry DeTox'},\n {value: 'DAVIDsTEA Noble Glass Travel Thermos',\n text: 'DAVIDsTEA Noble Glass Travel Thermos'},\n {value: 'Raw/Uncooked Pu-erh &amp; Lotus Leaf',\n text: 'Raw/Uncooked Pu-erh &amp; Lotus Leaf'},\n {value: 'Rainforest', text: 'Rainforest'},\n {value: 'Destiel', text: 'Destiel'},\n {value: 'Kotobuki', text: 'Kotobuki'},\n {value: 'Night Time', text: 'Night Time'},\n {value: 'South African Rooibos', text: 'South African Rooibos'},\n {value: 'Polar Berry', text: 'Polar Berry'},\n {value: 'Buckingham Palace Garden Party',\n text: 'Buckingham Palace Garden Party'},\n {value: 'Jin Shuan (Hualien)', text: 'Jin Shuan (Hualien)'},\n {value: 'Iced Raspberry', text: 'Iced Raspberry'},\n {value: 'Downy Sprout', text: 'Downy Sprout'},\n {value: 'Sternenglanz', text: 'Sternenglanz'},\n {value: 'Mugicha (Barley Tea)', text: 'Mugicha (Barley Tea)'},\n {value: 'Dong Cheon Dan-Cha Red Tea', text: 'Dong Cheon Dan-Cha Red Tea'},\n {value: 'Chocolate Mint Herbal Tea', text: 'Chocolate Mint Herbal Tea'},\n {value: 'Tea Merci Berry &amp; Rose', text: 'Tea Merci Berry &amp; Rose'},\n {value: 'Lilac', text: 'Lilac'},\n {value: 'Guayusa Spice', text: 'Guayusa Spice'},\n {value: 'Nepal SFTGFOP1 Sunderpani First Flush',\n text: 'Nepal SFTGFOP1 Sunderpani First Flush'},\n {value: 'Rosehip Hibiscus', text: 'Rosehip Hibiscus'},\n {value: 'China Green Tips', text: 'China Green Tips'},\n {value: 'Apricot Flavored Black Tea', text: 'Apricot Flavored Black Tea'},\n {value: 'Whisky Flavoured Tea', text: 'Whisky Flavoured Tea'},\n {value: 'Organic Fair Trade Ancient Sheng Pu-Erh Tuo Cha',\n text: 'Organic Fair Trade Ancient Sheng Pu-Erh Tuo Cha'},\n {value: 'Fujian Ti Kuan Yin', text: 'Fujian Ti Kuan Yin'},\n {value: 'Morning Rain', text: 'Morning Rain'},\n {value: 'Taiwan Oriental Beauty (Bai Hao) Oolong Tea',\n text: 'Taiwan Oriental Beauty (Bai Hao) Oolong Tea'},\n {value: '1993 Menghai 7542', text: '1993 Menghai 7542'},\n {value: 'Lavender Grey', text: 'Lavender Grey'},\n {value: 'Pistachio Matcha', text: 'Pistachio Matcha'},\n {value: '2 Doves Silver Needle', text: '2 Doves Silver Needle'},\n {value: 'Pu-erh Rose tea', text: 'Pu-erh Rose tea'},\n {value: 'White Chocolate Strawberry', text: 'White Chocolate Strawberry'},\n {value: 'Black Tea Latte', text: 'Black Tea Latte'},\n {value: 'Grapefruit Earl Grey', text: 'Grapefruit Earl Grey'},\n {value: 'White Peony King', text: 'White Peony King'},\n {value: 'Stress Blocker', text: 'Stress Blocker'},\n {value: 'Supreme Jasmine Pekoe Green Tea',\n text: 'Supreme Jasmine Pekoe Green Tea'},\n {value: '2012 Spring Harvest Bi Luo Chun',\n text: '2012 Spring Harvest Bi Luo Chun'},\n {value: 'Huang Jin Gui Golden Oolong',\n text: 'Huang Jin Gui Golden Oolong'},\n {value: 'Royal fruit', text: 'Royal fruit'},\n {value: 'Sweet Chamomile', text: 'Sweet Chamomile'},\n {value: 'Amaretto Cherry', text: 'Amaretto Cherry'},\n {value: '2007 Menghai Dayi 7532 Raw', text: '2007 Menghai Dayi 7532 Raw'},\n {value: 'Passionfruit', text: 'Passionfruit'},\n {value: 'Amore Tea', text: 'Amore Tea'},\n {value: 'Strawberry-Cream with Pieces',\n text: 'Strawberry-Cream with Pieces'},\n {value: 'Rooibos Mango', text: 'Rooibos Mango'},\n {value: 'Arya Emerald Second Flush Green Darjeeling',\n text: 'Arya Emerald Second Flush Green Darjeeling'},\n {value: 'Floral Passion', text: 'Floral Passion'},\n {value: 'Bangkok', text: 'Bangkok'},\n {value: 'Pele Black Tea', text: 'Pele Black Tea'},\n {value: 'Paradise Tropical Tea', text: 'Paradise Tropical Tea'},\n {value: 'Fairtrade pure origin Assam teabags',\n text: 'Fairtrade pure origin Assam teabags'},\n {value: 'Lapsang Souchong Imperial (ZS80)',\n text: 'Lapsang Souchong Imperial (ZS80)'},\n {value: 'Smokey Souchong', text: 'Smokey Souchong'},\n {value: 'Ceylon Bop Uva', text: 'Ceylon Bop Uva'},\n {value: 'Yellow Big Leaf', text: 'Yellow Big Leaf'},\n {value: 'Blue Lady', text: 'Blue Lady'},\n {value: 'Phoenix Bird Select', text: 'Phoenix Bird Select'},\n {value: 'Formosa Jade Dong Ding', text: 'Formosa Jade Dong Ding'},\n {value: 'Assam Hazelbank FTGFOP1', text: 'Assam Hazelbank FTGFOP1'},\n {value: '2008 Guan Zi Zai Manzhuan Xiao Zhuan Cha Raw 50g',\n text: '2008 Guan Zi Zai Manzhuan Xiao Zhuan Cha Raw 50g'},\n {value: 'Traditional Yerba Mate Tea Bags',\n text: 'Traditional Yerba Mate Tea Bags'},\n {value: 'Tulsi Pomegranate Green Tea',\n text: 'Tulsi Pomegranate Green Tea'},\n {value: 'Mango Melange', text: 'Mango Melange'},\n {value: 'Gao Li Gong Shan 60s', text: 'Gao Li Gong Shan 60s'},\n {value: 'Fruit Kiss', text: 'Fruit Kiss'},\n {value: 'Apple Cinnamon Oolong', text: 'Apple Cinnamon Oolong'},\n {value: 'Stomach Soother Blend', text: 'Stomach Soother Blend'},\n {value: 'Cest a toi', text: 'Cest a toi'},\n {value: 'Black Orange', text: 'Black Orange'},\n {value: 'Assam Harmutty GFBOP (S)', text: 'Assam Harmutty GFBOP (S)'},\n {value: 'Mango Preserves', text: 'Mango Preserves'},\n {value: 'Liquid Jade', text: 'Liquid Jade'},\n {value: 'mackintoshs fancy', text: 'mackintoshs fancy'},\n {value: '250 gram Mandala Silver Buds Raw - 2008',\n text: '250 gram Mandala Silver Buds Raw - 2008'},\n {value: 'Sleep Well', text: 'Sleep Well'},\n {value: 'Iron Goddess of Mercy', text: 'Iron Goddess of Mercy'},\n {value: '(Taiwan) Li Shan High Mountain Oolong',\n text: '(Taiwan) Li Shan High Mountain Oolong'},\n {value: 'Glorious Seed', text: 'Glorious Seed'},\n {value: 'British Breakfast', text: 'British Breakfast'},\n {value: 'Formosa Gaba Oolong', text: 'Formosa Gaba Oolong'},\n {value: 'Green Mountain Spice', text: 'Green Mountain Spice'},\n {value: 'Phoenix Mountain', text: 'Phoenix Mountain'},\n {value: 'Wild-Picked Yunnan Jin Jun Mei',\n text: 'Wild-Picked Yunnan Jin Jun Mei'},\n {value: 'Tea Trail 2004: Willow Grove Workshop',\n text: 'Tea Trail 2004: Willow Grove Workshop'},\n {value: 'Dolce Orange', text: 'Dolce Orange'},\n {value: 'Tongyu Mountain', text: 'Tongyu Mountain'},\n {value: 'Organic Decaf Green Tea', text: 'Organic Decaf Green Tea'},\n {value: '2003 Red in Red Pu-erh Tuocha',\n text: '2003 Red in Red Pu-erh Tuocha'},\n {value: 'Prairie Passion', text: 'Prairie Passion'},\n {value: 'Gold Tip Puerh', text: 'Gold Tip Puerh'},\n {value: 'Organic Green Ku-Ki Cha Kamakura',\n text: 'Organic Green Ku-Ki Cha Kamakura'},\n {value: 'Bai Hao Ya', text: 'Bai Hao Ya'},\n {value: 'Cin Gin Mate', text: 'Cin Gin Mate'},\n {value: 'Mayan Chocolate Chai', text: 'Mayan Chocolate Chai'},\n {value: 'Pin Lin Gunpowder', text: 'Pin Lin Gunpowder'},\n {value: 'Winter Cupcake', text: 'Winter Cupcake'},\n {value: 'The Sleeping Bear Blend', text: 'The Sleeping Bear Blend'},\n {value: 'Royal Phoenix Oolong', text: 'Royal Phoenix Oolong'},\n {value: 'Kyoto Cherry Rose (Organic)',\n text: 'Kyoto Cherry Rose (Organic)'},\n {value: 'Honeydew Mate', text: 'Honeydew Mate'},\n {value: 'Green Japan Cherry', text: 'Green Japan Cherry'},\n {value: 'Iron Goddess of Mercy - Ti Kuan Yin - Roasted',\n text: 'Iron Goddess of Mercy - Ti Kuan Yin - Roasted'},\n {value: 'Get Limber', text: 'Get Limber'},\n {value: 'Wang Fu Jing Hao (ZW86)', text: 'Wang Fu Jing Hao (ZW86)'},\n {value: 'Baked Apple', text: 'Baked Apple'},\n {value: 'Honey Vanilla', text: 'Honey Vanilla'},\n {value: 'Dragon Well - Lung Ching', text: 'Dragon Well - Lung Ching'},\n {value: 'Echinacea and Rasberry', text: 'Echinacea and Rasberry'},\n {value: '2006 Yun Chun TF Jinggu Lao Cha Tou - Ripe Tea Nugget 100g',\n text: '2006 Yun Chun TF Jinggu Lao Cha Tou - Ripe Tea Nugget 100g'},\n {value: 'Cherry Cosmo', text: 'Cherry Cosmo'},\n {value: 'Darjeeling Extra Fancy Kalimpong',\n text: 'Darjeeling Extra Fancy Kalimpong'},\n {value: 'Matcha Pinnacle', text: 'Matcha Pinnacle'},\n {value: 'Rouge Bourbon', text: 'Rouge Bourbon'},\n {value: 'Blood Orange &amp; Mandarin',\n text: 'Blood Orange Mandarin'},\n {value: 'Sweet Love', text: 'Sweet Love'},\n {value: 'Iced Green Tea: Peach', text: 'Iced Green Tea: Peach'},\n {value: 'Xiaguan Wild Seven Sons', text: 'Xiaguan Wild Seven Sons'},\n {value: 'Small Golden Shoot (Jin Ya Xiao Bian)',\n text: 'Small Golden Shoot (Jin Ya Xiao Bian)'},\n {value: 'Youle Shan Longpa Gushu 2009 Sheng Puerh',\n text: 'Youle Shan Longpa Gushu 2009 Sheng Puerh'},\n {value: 'King of PuErh', text: 'King of PuErh'},\n {value: 'Egyptian Camomile', text: 'Egyptian Camomile'},\n {value: 'Sevenberry Sangria Rooibos Tea',\n text: 'Sevenberry Sangria Rooibos Tea'},\n {value: 'Green organic Ceylon', text: 'Green organic Ceylon'},\n {value: 'Wild Berry Plum', text: 'Wild Berry Plum'},\n {value: 'Prince Of Wales', text: 'Prince Of Wales'},\n {value: 'Darjeeling Margarets Hope', text: 'Darjeeling Margarets Hope'},\n {value: 'Ceylon Chai', text: 'Ceylon Chai'},\n {value: 'Spring Sprout', text: 'Spring Sprout'},\n {value: 'Dragon Pearl Jasmine Supreme',\n text: 'Dragon Pearl Jasmine Supreme'},\n {value: 'Singell Second Flush FTGFOP1',\n text: 'Singell Second Flush FTGFOP1'},\n {value: 'The Earl of Lemon', text: 'The Earl of Lemon'},\n {value: 'French Vanilla Bean', text: 'French Vanilla Bean'},\n {value: 'Welsh Meadow', text: 'Welsh Meadow'},\n {value: 'Shin-cha 2009', text: 'Shin-cha 2009'},\n {value: 'Snow Peak Downy Tips', text: 'Snow Peak Downy Tips'},\n {value: 'Earl Grey Cream Tea', text: 'Earl Grey Cream Tea'},\n {value: 'Teas Tea Rose Green', text: 'Teas Tea Rose Green'},\n {value: 'Sen Cha', text: 'Sen Cha'},\n {value: 'Cherry Blossom', text: 'Cherry Blossom'},\n {value: 'Bokakhat Estate GTGFOP1', text: 'Bokakhat Estate GTGFOP1'},\n {value: 'Ginger Snap', text: 'Ginger Snap'},\n {value: 'Jin Guan Yin (Golden Tie Guan Yin) Anxi Wulong Tea',\n text: 'Jin Guan Yin (Golden Tie Guan Yin) Anxi Wulong Tea'},\n {value: 'China Lichee Black Tea', text: 'China Lichee Black Tea'},\n {value: 'gun powder green tea', text: 'gun powder green tea'},\n {value: 'Adams Peak White', text: 'Adams Peak White'},\n {value: 'Passion', text: 'Passion'},\n {value: 'Blood Orange Chocolate Red', text: 'Blood Orange Chocolate Red'},\n {value: 'Masterpiece Chai', text: 'Masterpiece Chai'},\n {value: 'Peaches and Cream', text: 'Peaches and Cream'},\n {value: 'Brahmaputra Valley Assam', text: 'Brahmaputra Valley Assam'},\n {value: 'Black Tea with Mango', text: 'Black Tea with Mango'},\n {value: 'High Grade Ben Shan Oolong', text: 'High Grade Ben Shan Oolong'},\n {value: 'Green Jasmine', text: 'Green Jasmine'},\n {value: 'Year of the Tiger Tea', text: 'Year of the Tiger Tea'},\n {value: 'DIGESTION: DigestTea – Passionflower Cilantro Lemongrass',\n text: 'DIGESTION: DigestTea – Passionflower Cilantro Lemongrass'},\n {value: 'Nepal Sunderpani Second Flush',\n text: 'Nepal Sunderpani Second Flush'},\n {value: 'Ceylon Osmanthus', text: 'Ceylon Osmanthus'},\n {value: 'Lao Ban Zhang Mao Cha Sheng Pu-erh Spring 2009',\n text: 'Lao Ban Zhang Mao Cha Sheng Pu-erh Spring 2009'},\n {value: 'Double Green Matcha (Doubles Collection)',\n text: 'Double Green Matcha (Doubles Collection)'},\n {value: 'Acai Matcha', text: 'Acai Matcha'},\n {value: 'Elixir of Life', text: 'Elixir of Life'},\n {value: 'Black General Oolong', text: 'Black General Oolong'},\n {value: 'Bergamot Sage', text: 'Bergamot Sage'},\n {value: 'Very Berry', text: 'Very Berry'},\n {value: 'Ceylon Super Single', text: 'Ceylon Super Single'},\n {value: 'Spice Masala Chai', text: 'Spice Masala Chai'},\n {value: 'Osmanthus Oolong Tea 1st Grade',\n text: 'Osmanthus Oolong Tea 1st Grade'},\n {value: 'First Flush Pure Green Tea', text: 'First Flush Pure Green Tea'},\n {value: 'Organic Vanilla Peach Rooibos',\n text: 'Organic Vanilla Peach Rooibos'},\n {value: 'High Elevation Darjeeling Tea',\n text: 'High Elevation Darjeeling Tea'},\n {value: 'Tea &amp; Herb', text: 'Tea &amp; Herb'},\n {value: 'Green Mate (organic)', text: 'Green Mate (organic)'},\n {value: 'Kenya Kangaita', text: 'Kenya Kangaita'},\n {value: 'Organic Black Tea', text: 'Organic Black Tea'},\n {value: 'Earl Grey De La Creme', text: 'Earl Grey De La Creme'},\n {value: 'Purple Açai and Blueberry Green Tea Superfruit',\n text: 'Purple Açai and Blueberry Green Tea Superfruit'},\n {value: 'China Jade Oolong Kuan Yin', text: 'China Jade Oolong Kuan Yin'},\n {value: 'Good Morning Mate', text: 'Good Morning Mate'},\n {value: 'Cheapest Pheonix Oolong Huang Zhi Xiang',\n text: 'Cheapest Pheonix Oolong Huang Zhi Xiang'},\n {value: '2008 Feng Qing Feng Shan Yi Hao',\n text: '2008 Feng Qing Feng Shan Yi Hao'},\n {value: 'China Rose Petal', text: 'China Rose Petal'},\n {value: 'Organic Ginger Root (BH10)', text: 'Organic Ginger Root (BH10)'},\n {value: 'Peach Flavored Oolong', text: 'Peach Flavored Oolong'},\n {value: 'TB51: East Frisian BOP', text: 'TB51: East Frisian BOP'},\n {value: 'Mrs. Li’s Early Spring Shi Feng Dragonwell Green Tea',\n text: 'Mrs. Li’s Early Spring Shi Feng Dragonwell Green Tea'},\n {value: 'Ceylon Vintage Silver Tips', text: 'Ceylon Vintage Silver Tips'},\n {value: 'Bear Trap', text: 'Bear Trap'},\n {value: 'Hand Picked Spring Tieguanyin (2015)',\n text: 'Hand Picked Spring Tieguanyin (2015)'},\n {value: 'Organic Gyokuro Green Tea', text: 'Organic Gyokuro Green Tea'},\n {value: 'Vanilla Bean Creme', text: 'Vanilla Bean Creme'},\n {value: 'Lemon Chiffon', text: 'Lemon Chiffon'},\n {value: 'Get Heart - No.12 (Wellness Collection)',\n text: 'Get Heart - No.12 (Wellness Collection)'},\n {value: 'The Doctors Blend', text: 'The Doctors Blend'},\n {value: 'Womans Moon Cycle', text: 'Womans Moon Cycle'},\n {value: 'New Zealand Breakfast', text: 'New Zealand Breakfast'},\n {value: 'Carrot Cake Rooibos', text: 'Carrot Cake Rooibos'},\n {value: 'Anxi Tie Guan Yin -haute montagne-',\n text: 'Anxi Tie Guan Yin -haute montagne-'},\n {value: 'Liver Cleanse Herbal', text: 'Liver Cleanse Herbal'},\n {value: 'Blackberry Twist', text: 'Blackberry Twist'},\n {value: 'Organic Mao Zhen Hair Needle Green',\n text: 'Organic Mao Zhen Hair Needle Green'},\n {value: 'Bai Hao Yin Zhen | Silver Needle',\n text: 'Bai Hao Yin Zhen | Silver Needle'},\n {value: 'Raspberry Truffle Chocolatte Red Tea',\n text: 'Raspberry Truffle Chocolatte Red Tea'},\n {value: 'Lychee (FS02)', text: 'Lychee (FS02)'},\n {value: '2009 Meng Song Dai Tribe Bamboo Raw Pu-erh',\n text: '2009 Meng Song Dai Tribe Bamboo Raw Pu-erh'},\n {value: 'Bancha', text: 'Bancha'},\n {value: 'Calypso Mango', text: 'Calypso Mango'},\n {value: 'Lime', text: 'Lime'},\n {value: 'Organic Ceylon BOP', text: 'Organic Ceylon BOP'},\n {value: 'Midsummers Peach', text: 'Midsummers Peach'},\n {value: 'Soldier Tea/Thank You for Your Service Tea',\n text: 'Soldier Tea/Thank You for Your Service Tea'},\n {value: 'Royal Spring Green Snail (Pi Lo Chun) 1110/110039',\n text: 'Royal Spring Green Snail (Pi Lo Chun) 1110/110039'},\n {value: 'Wild Black Yunnan', text: 'Wild Black Yunnan'},\n {value: 'Scorpio (The Zodiac Series)',\n text: 'Scorpio (The Zodiac Series)'},\n {value: 'Mystery Tea', text: 'Mystery Tea'},\n {value: 'All That Jazzmine', text: 'All That Jazzmine'},\n {value: 'Misty Mountain Green', text: 'Misty Mountain Green'},\n {value: 'Caribbean Dream', text: 'Caribbean Dream'},\n {value: 'Mount Gray', text: 'Mount Gray'},\n {value: 'IKEA HÄLSA Steel vacuum flask',\n text: 'IKEA HÄLSA Steel vacuum flask'},\n {value: 'Genmaimatcha', text: 'Genmaimatcha'},\n {value: 'Berry Herb Blend (BH44)', text: 'Berry Herb Blend (BH44)'},\n {value: 'Vanilla Chai-me', text: 'Vanilla Chai-me'},\n {value: 'Oolong Shot', text: 'Oolong Shot'},\n {value: 'Guizhou Fuzzy Tip', text: 'Guizhou Fuzzy Tip'},\n {value: '2011 Spring Ban Yan Wuyi Medium-Roasted Da Hong Pao Rock Tea',\n text: '2011 Spring Ban Yan Wuyi Medium-Roasted Da Hong Pao Rock Tea'},\n {value: 'Fu Lu Yuan Bing Cha 2007', text: 'Fu Lu Yuan Bing Cha 2007'},\n {value: 'Enlightenmint', text: 'Enlightenmint'},\n {value: 'Darjeeling Puttabong Summer (2)',\n text: 'Darjeeling Puttabong Summer (2)'},\n {value: 'Sinharaja', text: 'Sinharaja'},\n {value: 'Thé au Tiare (Tea Flavored with Tiare)',\n text: 'Thé au Tiare (Tea Flavored with Tiare)'},\n {value: 'Fujian Black Tea', text: 'Fujian Black Tea'},\n {value: 'Aztecs Gold', text: 'Aztecs Gold'},\n {value: 'Caramel MATCHAccino', text: 'Caramel MATCHAccino'},\n {value: 'Pina Colada Honeybush', text: 'Pina Colada Honeybush'},\n {value: 'Love Tea 7', text: 'Love Tea 7'},\n {value: 'Spiced Plum', text: 'Spiced Plum'},\n {value: '2008 Winter Awarded Song Po Oolong',\n text: '2008 Winter Awarded Song Po Oolong'},\n {value: 'Thailand Doi Tung Oolong Kings Grade',\n text: 'Thailand Doi Tung Oolong Kings Grade'},\n {value: 'Kangaita OP', text: 'Kangaita OP'},\n {value: 'Assam TGFOP-1 House Blend', text: 'Assam TGFOP-1 House Blend'},\n {value: 'Strawberry Green', text: 'Strawberry Green'},\n {value: 'Chinese Silver Needle', text: 'Chinese Silver Needle'},\n {value: 'Chelseas Chocolate Banana Rooibos',\n text: 'Chelseas Chocolate Banana Rooibos'},\n {value: 'Organic Easy Digestion', text: 'Organic Easy Digestion'},\n {value: 'Nonpareil Taiwan Li Shan Oolong Tea',\n text: 'Nonpareil Taiwan Li Shan Oolong Tea'},\n {value: 'Original Chai Tea Latte Mix',\n text: 'Original Chai Tea Latte Mix'},\n {value: 'Brewing Basket', text: 'Brewing Basket'},\n {value: 'Yanxins Reserve 04 Shu Nuggets',\n text: 'Yanxins Reserve 04 Shu Nuggets'},\n {value: 'Premium Sun Moon Lake Assam Black Tea Lot 154',\n text: 'Premium Sun Moon Lake Assam Black Tea Lot 154'},\n {value: 'Dong Ding Light', text: 'Dong Ding Light'},\n {value: 'First Flush Darjeeling 2010 Pattabong Clonal Queen',\n text: 'First Flush Darjeeling 2010 Pattabong Clonal Queen'},\n {value: 'Commonwealth Tradition', text: 'Commonwealth Tradition'},\n {value: 'Almond Sunset', text: 'Almond Sunset'},\n {value: 'Pre Rain Organic Dragon Well Supreme (Long Jing)',\n text: 'Pre Rain Organic Dragon Well Supreme (Long Jing)'},\n {value: 'Wild Wuyi Black [Out of stock]',\n text: 'Wild Wuyi Black [Out of stock]'},\n {value: 'Aged Oolong', text: 'Aged Oolong'},\n {value: 'Cucumber Melon Green Tea', text: 'Cucumber Melon Green Tea'},\n {value: 'Golden Yunnan (organic)', text: 'Golden Yunnan (organic)'},\n {value: 'Fruité Maté', text: 'Fruité Maté'},\n {value: 'ZS90: Lapsang Souchong Black Dragon',\n text: 'ZS90: Lapsang Souchong Black Dragon'},\n {value: 'LiberTEAs’ Tomato Basil &amp; Black Pepper',\n text: 'LiberTEAs’ Tomato Basil Black Pepper'},\n {value: 'Root Beer', text: 'Root Beer'},\n {value: 'Taiwan Green Tea', text: 'Taiwan Green Tea'},\n {value: 'Kamairicha Takachiho', text: 'Kamairicha Takachiho'},\n {value: 'Ceylon Special Blend with Cardamom',\n text: 'Ceylon Special Blend with Cardamom'},\n {value: 'Ronnefeldt Morgentau® Tea-Caddy® Flavored Green Tea',\n text: 'Ronnefeldt Morgentau® Tea-Caddy® Flavored Green Tea'},\n {value: 'Finest Earl Grey', text: 'Finest Earl Grey'},\n {value: 'Dreams of Sena', text: 'Dreams of Sena'},\n {value: 'No. 36 Ti Kwan Yin Oolong', text: 'No. 36 Ti Kwan Yin Oolong'},\n {value: 'Organic Farmers Market Caffeine Free Blend',\n text: 'Organic Farmers Market Caffeine Free Blend'},\n {value: 'YMY 1690 Kukicha Tea', text: 'YMY 1690 Kukicha Tea'},\n {value: 'Yorkshire Tea', text: 'Yorkshire Tea'},\n {value: 'Diānhóng (China Breakfast)', text: 'Diānhóng (China Breakfast)'},\n {value: 'First Darjeeling', text: 'First Darjeeling'},\n {value: 'Lady Lavender', text: 'Lady Lavender'},\n {value: 'VIP Tour Blend', text: 'VIP Tour Blend'},\n {value: 'Shizuoka Green Tea Daily Sencha',\n text: 'Shizuoka Green Tea Daily Sencha'},\n {value: 'Organic Detox Infusion', text: 'Organic Detox Infusion'},\n {value: 'Wild Rose', text: 'Wild Rose'},\n {value: 'Passionfruit Mango Green', text: 'Passionfruit Mango Green'},\n {value: 'Green Champaca', text: 'Green Champaca'},\n {value: 'China Golden Yunnan', text: 'China Golden Yunnan'},\n {value: 'Golden Pu-erh', text: 'Golden Pu-erh'},\n {value: 'pu-erh mini touchas', text: 'pu-erh mini touchas'},\n {value: 'Guang Dong Phoenix Dan Cong Oolong Tea',\n text: 'Guang Dong Phoenix Dan Cong Oolong Tea'},\n {value: 'chun mei', text: 'chun mei'},\n {value: 'Jasmine Monkey King', text: 'Jasmine Monkey King'},\n {value: 'Barrys Tea Green', text: 'Barrys Tea Green'},\n {value: 'China White Monkey King Green',\n text: 'China White Monkey King Green'},\n {value: 'Lemon-Lime Meringue Kukicha',\n text: 'Lemon-Lime Meringue Kukicha'},\n {value: 'Elderflower White Tea', text: 'Elderflower White Tea'},\n {value: 'The Glow (organic)', text: 'The Glow (organic)'},\n {value: 'Passionate Rose', text: 'Passionate Rose'},\n {value: 'Chocolate Covered Strawberry',\n text: 'Chocolate Covered Strawberry'},\n {value: '1st Flush Darjeeling - Giddapahar China Delight',\n text: '1st Flush Darjeeling - Giddapahar China Delight'},\n {value: 'Ginger Citrus', text: 'Ginger Citrus'},\n {value: 'Ashikubo Sencha', text: 'Ashikubo Sencha'},\n {value: '2009 Douji You Le', text: '2009 Douji You Le'},\n {value: 'Chocolate Storm', text: 'Chocolate Storm'},\n {value: '2009 Late-Winter Budset Yabao',\n text: '2009 Late-Winter Budset Yabao'},\n {value: 'Organic Assam Rani Estate', text: 'Organic Assam Rani Estate'},\n {value: 'Genghis Khan Super Horse 1206 AD',\n text: 'Genghis Khan Super Horse 1206 AD'},\n {value: 'Organic Black with Coconut', text: 'Organic Black with Coconut'},\n {value: 'TBD Moms Apple Pie', text: 'TBD Moms Apple Pie'},\n {value: 'Orange Starfruit', text: 'Orange Starfruit'},\n {value: 'Anastasia', text: 'Anastasia'},\n {value: 'West Cape Chai', text: 'West Cape Chai'},\n {value: 'Bonfire Toffee', text: 'Bonfire Toffee'},\n {value: 'Russian Earl Grey', text: 'Russian Earl Grey'},\n {value: 'Xaouen (White Silver Needle Green Rooibos Jasmine Pearl)',\n text: 'Xaouen (White Silver Needle Green Rooibos Jasmine Pearl)'},\n {value: 'Maritime Cranberry', text: 'Maritime Cranberry'},\n {value: 'A Candid Candied Apple - Signature Blend',\n text: 'A Candid Candied Apple - Signature Blend'},\n {value: 'Mint Tea', text: 'Mint Tea'},\n {value: 'Marangi Estate FTGFOP1 (TA84)',\n text: 'Marangi Estate FTGFOP1 (TA84)'},\n {value: 'Jin Yao Shi', text: 'Jin Yao Shi'},\n {value: 'Red Cloak Grande 2011', text: 'Red Cloak Grande 2011'},\n {value: 'TE94: Mélange de Chamonix', text: 'TE94: Mélange de Chamonix'},\n {value: 'Ming Qian Dragonwell Panan Supreme 2010',\n text: 'Ming Qian Dragonwell Panan Supreme 2010'},\n {value: 'Tulsi Dosha Chai', text: 'Tulsi Dosha Chai'},\n {value: 'Om', text: 'Om'},\n {value: 'White Pepper Mint', text: 'White Pepper Mint'},\n {value: 'Sakura Impérial', text: 'Sakura Impérial'},\n {value: 'Green Tea Kombucha Decaf', text: 'Green Tea Kombucha Decaf'},\n {value: 'Dahl House', text: 'Dahl House'},\n {value: 'Black Matcha', text: 'Black Matcha'},\n {value: 'Chocolate Midnight Black Tea',\n text: 'Chocolate Midnight Black Tea'},\n {value: '2010 Spring Meng Ding Huang Ya - Sichuan Yellow Tea',\n text: '2010 Spring Meng Ding Huang Ya - Sichuan Yellow Tea'},\n {value: 'DJ Darjeeling Tea Mim First Flush 2012 (FTGFOP1)',\n text: 'DJ Darjeeling Tea Mim First Flush 2012 (FTGFOP1)'},\n {value: 'Butterscotch &amp; Hazelnut Mocha Candies',\n text: 'Butterscotch &amp; Hazelnut Mocha Candies'},\n {value: 'Pineapple-Guava Green Tea', text: 'Pineapple-Guava Green Tea'},\n {value: 'Organic Lemon Ginger and Ginseng Infusion',\n text: 'Organic Lemon Ginger and Ginseng Infusion'},\n {value: 'Could You Be Loved', text: 'Could You Be Loved'},\n {value: 'Glitter and Gold', text: 'Glitter and Gold'},\n {value: 'Shanlinxi Sun-Link-Sea High Mountain Oolong Tea',\n text: 'Shanlinxi Sun-Link-Sea High Mountain Oolong Tea'},\n {value: 'Classic Chai', text: 'Classic Chai'},\n {value: 'Rose de Chine', text: 'Rose de Chine'},\n {value: 'Bing Cherry Black Tea', text: 'Bing Cherry Black Tea'},\n {value: 'Sakura Tea', text: 'Sakura Tea'},\n {value: 'Osmanthus Oolong (Rare Tea Collection)',\n text: 'Osmanthus Oolong (Rare Tea Collection)'},\n {value: 'Darjeeling Singbulli SF', text: 'Darjeeling Singbulli SF'},\n {value: 'Echinecia', text: 'Echinecia'},\n {value: 'Artisan Revival Banzhang 06 Sheng Puer',\n text: 'Artisan Revival Banzhang 06 Sheng Puer'},\n {value: 'Perfectly Passionate', text: 'Perfectly Passionate'},\n {value: 'African Dew', text: 'African Dew'},\n {value: 'Echinacea', text: 'Echinacea'},\n {value: 'Organic Coco De Menthe', text: 'Organic Coco De Menthe'},\n {value: 'sencha', text: 'sencha'},\n {value: 'Lipton Pyramid tea Lemon', text: 'Lipton Pyramid tea Lemon'},\n {value: 'Phoenix Single Grove Honey Fragrance',\n text: 'Phoenix Single Grove Honey Fragrance'},\n {value: 'Neem Nectar', text: 'Neem Nectar'},\n {value: 'Iron Goddess of Mercy (Ti Kuan Yin)',\n text: 'Iron Goddess of Mercy (Ti Kuan Yin)'},\n {value: 'Organic Lemon Drop', text: 'Organic Lemon Drop'},\n {value: 'Bright Mood', text: 'Bright Mood'},\n {value: 'Cocoa Cardamon Tango', text: 'Cocoa Cardamon Tango'},\n {value: '2009 Spring Diamond Grade Tie Guan Yin',\n text: '2009 Spring Diamond Grade Tie Guan Yin'},\n {value: 'Silver Jasmine Green Tea (Mo Li Yin Hao)',\n text: 'Silver Jasmine Green Tea (Mo Li Yin Hao)'},\n {value: 'Thousand Days Red Jasmine', text: 'Thousand Days Red Jasmine'},\n {value: 'Montagne dOr', text: 'Montagne dOr'},\n {value: 'Mu Zha Tie Guan Yin', text: 'Mu Zha Tie Guan Yin'},\n {value: 'Egyptian Chamomile (organic)',\n text: 'Egyptian Chamomile (organic)'},\n {value: 'old leaf pu-erh', text: 'old leaf pu-erh'},\n {value: 'Anxi Benshan Oolong', text: 'Anxi Benshan Oolong'},\n {value: 'Wild Oolong', text: 'Wild Oolong'},\n {value: '2006 Dehong High Plateau Pu-erh',\n text: '2006 Dehong High Plateau Pu-erh'},\n {value: 'BA38 Rooibos Vanilla', text: 'BA38 Rooibos Vanilla'},\n {value: 'Kukicha Midori', text: 'Kukicha Midori'},\n {value: 'Garofano Cannella', text: 'Garofano Cannella'},\n {value: 'Organic Nonpareil Ming Qian Dragon Well Long Jing Green Tea',\n text: 'Organic Nonpareil Ming Qian Dragon Well Long Jing Green Tea'},\n {value: 'Alexandria', text: 'Alexandria'},\n {value: 'Darjeeling SFTGFOP1 Muskatell Puttabong',\n text: 'Darjeeling SFTGFOP1 Muskatell Puttabong'},\n {value: 'Strawberry White (organic)', text: 'Strawberry White (organic)'},\n {value: 'TA04: Seasons Pick Assam GFOP',\n text: 'TA04: Seasons Pick Assam GFOP'},\n {value: 'Honey Ginseng', text: 'Honey Ginseng'},\n {value: 'Almond Tea', text: 'Almond Tea'},\n {value: 'India Spice Chai', text: 'India Spice Chai'},\n {value: 'Keemun Xiang Luo', text: 'Keemun Xiang Luo'},\n {value: 'Taimu Mountain Organic Mao Feng',\n text: 'Taimu Mountain Organic Mao Feng'},\n {value: 'Pomegranate Cherry Blueberry',\n text: 'Pomegranate Cherry Blueberry'},\n {value: 'Black Pekoe Tea', text: 'Black Pekoe Tea'},\n {value: 'Cider Guayusa', text: 'Cider Guayusa'},\n {value: 'Maple-flavoured Black Tea', text: 'Maple-flavoured Black Tea'},\n {value: 'Puer Tuocha (Xiao Tuo Cha)', text: 'Puer Tuocha (Xiao Tuo Cha)'},\n {value: 'Phoenix Eye Jasmine', text: 'Phoenix Eye Jasmine'},\n {value: 'Rou Gui - Wu Yi Rock Tea', text: 'Rou Gui - Wu Yi Rock Tea'},\n {value: 'Organic Golden Mango Green Tea',\n text: 'Organic Golden Mango Green Tea'},\n {value: 'Gingerbread Black', text: 'Gingerbread Black'},\n {value: 'Competition Flavor - Sijichun (Four Seasons)',\n text: 'Competition Flavor - Sijichun (Four Seasons)'},\n {value: 'Organic Passion Fruit Green',\n text: 'Organic Passion Fruit Green'},\n {value: 'TC93: Adams Peak Ceylon White',\n text: 'TC93: Adams Peak Ceylon White'},\n {value: 'Nilgiri Frost Wellback Estate',\n text: 'Nilgiri Frost Wellback Estate'},\n {value: 'Maya Chocolate Herbal Coffee',\n text: 'Maya Chocolate Herbal Coffee'},\n {value: 'Wild Leaf Sheng Pu-erh 1993',\n text: 'Wild Leaf Sheng Pu-erh 1993'},\n {value: 'Southern Sunrise', text: 'Southern Sunrise'},\n {value: 'Sencha Overture', text: 'Sencha Overture'},\n {value: 'China Black Gunpowder (Black Pearls)',\n text: 'China Black Gunpowder (Black Pearls)'},\n {value: 'Jasmine Dragon Pearl (Imperial Long Chu)',\n text: 'Jasmine Dragon Pearl (Imperial Long Chu)'},\n {value: 'Ming Qian Dragonwell Shifeng 2010',\n text: 'Ming Qian Dragonwell Shifeng 2010'},\n {value: 'A Blackberry Mint Julep', text: 'A Blackberry Mint Julep'},\n {value: 'Ginger Zinger', text: 'Ginger Zinger'},\n {value: '2009 Hand-Braided Wild Arbor Raw Pu-erh',\n text: '2009 Hand-Braided Wild Arbor Raw Pu-erh'},\n {value: 'Kapha Ayurvedic', text: 'Kapha Ayurvedic'},\n {value: 'Sour Apple', text: 'Sour Apple'},\n {value: 'Ujibashi San no Ma (Kirameki) Uji Asamushi Sencha',\n text: 'Ujibashi San no Ma (Kirameki) Uji Asamushi Sencha'},\n {value: 'Green Tea with wild berries and Passion Fruit',\n text: 'Green Tea with wild berries and Passion Fruit'},\n {value: 'Green Tuocha', text: 'Green Tuocha'},\n {value: 'Black', text: 'Black'},\n {value: 'Kenya Kaproret GFOP', text: 'Kenya Kaproret GFOP'},\n {value: 'Organic Chocolate Chai', text: 'Organic Chocolate Chai'},\n {value: 'Osmanthus Oolong', text: 'Osmanthus Oolong'},\n {value: 'Earl Grey Supreme Black Tea',\n text: 'Earl Grey Supreme Black Tea'},\n {value: 'A Tasting of Ten Teas', text: 'A Tasting of Ten Teas'},\n {value: 'Milky Gold', text: 'Milky Gold'},\n {value: 'Mt. Hood Vanilla', text: 'Mt. Hood Vanilla'},\n {value: 'Gentlemans Tea G.F.B.O.P', text: 'Gentlemans Tea G.F.B.O.P'},\n {value: 'Capetown Harvest', text: 'Capetown Harvest'},\n {value: 'Rosie Earl Grey', text: 'Rosie Earl Grey'},\n {value: 'Mugicha', text: 'Mugicha'},\n {value: 'Rooibos Masala Chai (Caffeine Free)',\n text: 'Rooibos Masala Chai (Caffeine Free)'},\n {value: '2015 HuaZhu Liangzi GuShu Raw',\n text: '2015 HuaZhu Liangzi GuShu Raw'},\n {value: 'Certified Organic Oolong Silver Label',\n text: 'Certified Organic Oolong Silver Label'},\n {value: '2007 Nanjian Phoenix Pu-erh',\n text: '2007 Nanjian Phoenix Pu-erh'},\n {value: '2011 Darjeeling First Flush Gopaldhara Wonder Tea',\n text: '2011 Darjeeling First Flush Gopaldhara Wonder Tea'},\n {value: 'Gielle Estate FTGFOP1 Second Flush (DJ-63) (TD42)',\n text: 'Gielle Estate FTGFOP1 Second Flush (DJ-63) (TD42)'},\n {value: 'Echinacea Plus', text: 'Echinacea Plus'},\n {value: 'Green Tea Blueberry Slim Life',\n text: 'Green Tea Blueberry Slim Life'},\n {value: 'Green White Tea', text: 'Green White Tea'},\n {value: 'Chen Yun Yuan Cha', text: 'Chen Yun Yuan Cha'},\n {value: 'Yulu Golden Pekoe', text: 'Yulu Golden Pekoe'},\n {value: 'Taiwan Jin Xuan Milk Oolong Tea',\n text: 'Taiwan Jin Xuan Milk Oolong Tea'},\n {value: 'Yunnan', text: 'Yunnan'},\n {value: 'Ceylon BOP1 Greenfield', text: 'Ceylon BOP1 Greenfield'},\n {value: 'Wei Chi Cha', text: 'Wei Chi Cha'},\n {value: 'White Mu Dan Peony', text: 'White Mu Dan Peony'},\n {value: 'Honeybush Apricot', text: 'Honeybush Apricot'},\n {value: 'Pure Green Decaf', text: 'Pure Green Decaf'},\n {value: 'Makai Black (Sinensis)', text: 'Makai Black (Sinensis)'},\n {value: 'Peaches and Cream Tea', text: 'Peaches and Cream Tea'},\n {value: 'Fit Active', text: 'Fit Active'},\n {value: 'Arnold Palmer Lite Green Tea Lemonade',\n text: 'Arnold Palmer Lite Green Tea Lemonade'},\n {value: 'Green Pear', text: 'Green Pear'},\n {value: 'Saffron Peony (FW04)', text: 'Saffron Peony (FW04)'},\n {value: 'High Mountain Oolong Supreme',\n text: 'High Mountain Oolong Supreme'},\n {value: 'Genmaicha Silver', text: 'Genmaicha Silver'},\n {value: 'Mothers Little Helper (organic)',\n text: 'Mothers Little Helper (organic)'},\n {value: 'Strawberry Ginger', text: 'Strawberry Ginger'},\n {value: 'White Peony with Rose Petals',\n text: 'White Peony with Rose Petals'},\n {value: 'Long Jing Tiger Spring', text: 'Long Jing Tiger Spring'},\n {value: 'Chai French Vanilla', text: 'Chai French Vanilla'},\n {value: 'Imperial Breakfast', text: 'Imperial Breakfast'},\n {value: 'Ceylon Ratnapura Estate BOP',\n text: 'Ceylon Ratnapura Estate BOP'},\n {value: 'Lapsang Souchong Supreme', text: 'Lapsang Souchong Supreme'},\n {value: 'Tai Ping Hou Kui Green Tea', text: 'Tai Ping Hou Kui Green Tea'},\n {value: 'Walter Bishop Honeybush', text: 'Walter Bishop Honeybush'},\n {value: 'Choco*Latte', text: 'Choco*Latte'},\n {value: 'Downeast Breakfast Blend', text: 'Downeast Breakfast Blend'},\n {value: 'Peony (Bai Mu Dan)', text: 'Peony (Bai Mu Dan)'},\n {value: 'Silk Dragon', text: 'Silk Dragon'},\n {value: 'Japan Kabusecha', text: 'Japan Kabusecha'},\n {value: 'The Buzz', text: 'The Buzz'},\n {value: 'Mandarin Green', text: 'Mandarin Green'},\n {value: 'Coquelicot Gourmand', text: 'Coquelicot Gourmand'},\n {value: 'Wild Raspberry Hibiscus', text: 'Wild Raspberry Hibiscus'},\n {value: 'Strawberry Magic', text: 'Strawberry Magic'},\n {value: 'Organic Ming Mei green tea', text: 'Organic Ming Mei green tea'},\n {value: 'Early Spring Yunnan Silver Needles',\n text: 'Early Spring Yunnan Silver Needles'},\n {value: 'CTC Irish Breakfast Blend (TB12)',\n text: 'CTC Irish Breakfast Blend (TB12)'},\n {value: 'Yerba Mate Mix', text: 'Yerba Mate Mix'},\n {value: 'Margarets Hope Darjeeling FTGFOP 1',\n text: 'Margarets Hope Darjeeling FTGFOP 1'},\n {value: 'Dragon Eye', text: 'Dragon Eye'},\n {value: 'Queen Mary', text: 'Queen Mary'},\n {value: 'Grand Yunnan Imperial', text: 'Grand Yunnan Imperial'},\n {value: 'Custom Blend from Teasons Garden',\n text: 'Custom Blend from Teasons Garden'},\n {value: 'Bedtime Story', text: 'Bedtime Story'},\n {value: 'Organic Wild Tree Pu-Erh Mini Tuo Cha',\n text: 'Organic Wild Tree Pu-Erh Mini Tuo Cha'},\n {value: 'Golden Monkey Superfine Grade',\n text: 'Golden Monkey Superfine Grade'},\n {value: 'Jade Organic', text: 'Jade Organic'},\n {value: 'Daoli Black Trip', text: 'Daoli Black Trip'},\n {value: 'Apple Cider', text: 'Apple Cider'},\n {value: 'Blueberry &amp; Apple', text: 'Blueberry &amp; Apple'},\n {value: 'Cocoa Raspberry Mate', text: 'Cocoa Raspberry Mate'},\n {value: 'Davids Darjeeling', text: 'Davids Darjeeling'},\n {value: 'Green Mulberry Leaf Tisane', text: 'Green Mulberry Leaf Tisane'},\n {value: 'Choco Strawberry Rooibos', text: 'Choco Strawberry Rooibos'},\n {value: 'Strawberry Paraiso White Tea',\n text: 'Strawberry Paraiso White Tea'},\n {value: 'Apple', text: 'Apple'},\n {value: 'Haumea Earth Goddess Black Tea',\n text: 'Haumea Earth Goddess Black Tea'},\n {value: 'Creme Caramel', text: 'Creme Caramel'},\n {value: 'Divine Temple', text: 'Divine Temple'},\n {value: 'Kiwi Lime Ginger', text: 'Kiwi Lime Ginger'},\n {value: 'breakfast black on VirginAmerica',\n text: 'breakfast black on VirginAmerica'},\n {value: 'Luscious Watermelon', text: 'Luscious Watermelon'},\n {value: 'Authentic Wu-Yi (Premium Blend) Tea',\n text: 'Authentic Wu-Yi (Premium Blend) Tea'},\n {value: 'Rilassante / Relaxing (valerian root lemonbalm mint lavender)',\n text: 'Rilassante / Relaxing (valerian root lemonbalm mint lavender)'},\n {value: 'Green Tea Peach', text: 'Green Tea Peach'},\n {value: 'Golden Tips Assam', text: 'Golden Tips Assam'},\n {value: 'Fenghuang Dan Cong Bai Xian 2016 Spring',\n text: 'Fenghuang Dan Cong Bai Xian 2016 Spring'},\n {value: 'Go Go Goa', text: 'Go Go Goa'},\n {value: 'Swampwater', text: 'Swampwater'},\n {value: 'Assam Golden Tips', text: 'Assam Golden Tips'},\n {value: 'Noël à Venise', text: 'Noël à Venise'},\n {value: 'Darjeeling Tea Avongrove 2012 White',\n text: 'Darjeeling Tea Avongrove 2012 White'},\n {value: 'Mango (Green)', text: 'Mango (Green)'},\n {value: 'Tea for Tango', text: 'Tea for Tango'},\n {value: 'Tropical Crimson Iced Tea', text: 'Tropical Crimson Iced Tea'},\n {value: '2008 Dong Pian - Si Ji Chun',\n text: '2008 Dong Pian - Si Ji Chun'},\n {value: 'Mate lemon', text: 'Mate lemon'},\n {value: 'Chocolate Spice', text: 'Chocolate Spice'},\n {value: 'Berry Mint Cassis', text: 'Berry Mint Cassis'},\n {value: 'Orange Red Carrot Raw Green Bush Tea',\n text: 'Orange Red Carrot Raw Green Bush Tea'},\n {value: '100 gram Yun Gui Jing Mai Mountain - 2007',\n text: '100 gram Yun Gui Jing Mai Mountain - 2007'},\n {value: 'Citrus Ginseng Green Tea', text: 'Citrus Ginseng Green Tea'},\n {value: 'Pure Green Tea', text: 'Pure Green Tea'},\n {value: 'Thé des Fakirs', text: 'Thé des Fakirs'},\n {value: 'Sterling Silver Needles Yin Zhen White Tea',\n text: 'Sterling Silver Needles Yin Zhen White Tea'},\n {value: 'Balade a Shanghai', text: 'Balade a Shanghai'},\n {value: 'Oolong (Loose)', text: 'Oolong (Loose)'},\n {value: 'Earl Grey and Cream', text: 'Earl Grey and Cream'},\n {value: 'Formosa Aged Wuyi Variety Oolong',\n text: 'Formosa Aged Wuyi Variety Oolong'},\n {value: 'Phenix', text: 'Phenix'},\n {value: 'India Chai', text: 'India Chai'},\n {value: 'DISCONTINUED - Mossy Cave Pu-erh Cups',\n text: 'DISCONTINUED - Mossy Cave Pu-erh Cups'},\n {value: 'Orange Pekoe Premium Blend', text: 'Orange Pekoe Premium Blend'},\n {value: 'Anxi Tie Guan Yin 2 autumnal 2011',\n text: 'Anxi Tie Guan Yin 2 autumnal 2011'},\n {value: 'Taisyou', text: 'Taisyou'},\n {value: 'Cloud Nine', text: 'Cloud Nine'},\n {value: 'Chocolate', text: 'Chocolate'},\n {value: 'Dan Cong Red Tea', text: 'Dan Cong Red Tea'},\n {value: 'Green Rooibos Citron', text: 'Green Rooibos Citron'},\n {value: 'Green Tea Ginger Twist', text: 'Green Tea Ginger Twist'},\n {value: 'Enchanted Forest: Sweet Almond',\n text: 'Enchanted Forest: Sweet Almond'},\n {value: 'Yun Wu Cloud Mist Green Apple Tea',\n text: 'Yun Wu Cloud Mist Green Apple Tea'},\n {value: 'Sun of the East', text: 'Sun of the East'},\n {value: 'Cinnamon Almond Black Tea', text: 'Cinnamon Almond Black Tea'},\n {value: 'Organic Spearmint', text: 'Organic Spearmint'},\n {value: 'Make Me A Martini', text: 'Make Me A Martini'},\n {value: 'Gunpowder Taffy', text: 'Gunpowder Taffy'},\n {value: 'Drum Mountain White Cloud', text: 'Drum Mountain White Cloud'},\n {value: 'Saikou Sencha', text: 'Saikou Sencha'},\n {value: 'Black Tea Chai', text: 'Black Tea Chai'},\n {value: 'Holiday Dream', text: 'Holiday Dream'},\n {value: 'Angels Dream', text: 'Angels Dream'},\n {value: 'Wu Yi Qu Hao', text: 'Wu Yi Qu Hao'},\n {value: 'Early Summer Laoshan Green', text: 'Early Summer Laoshan Green'},\n {value: 'Yellow and Blue', text: 'Yellow and Blue'},\n {value: 'Ti Kuan Yin Anxi Fuzhou', text: 'Ti Kuan Yin Anxi Fuzhou'},\n {value: 'Decaf Chai Spice', text: 'Decaf Chai Spice'},\n {value: 'Fruit Medley', text: 'Fruit Medley'},\n {value: 'Sour Cherry Serenade', text: 'Sour Cherry Serenade'},\n {value: 'Lemon and Ginger', text: 'Lemon and Ginger'},\n {value: 'Matcha Senjunomukashi (Thick Grade)',\n text: 'Matcha Senjunomukashi (Thick Grade)'},\n {value: 'rishi tropical hibiscus', text: 'rishi tropical hibiscus'},\n {value: 'Pluckley Tea', text: 'Pluckley Tea'},\n {value: 'Liu Bao 1970 Guangxi 6608', text: 'Liu Bao 1970 Guangxi 6608'},\n {value: 'Coincidence Noir', text: 'Coincidence Noir'},\n {value: 'Royal Silver Needle Yellow 1400/110230',\n text: 'Royal Silver Needle Yellow 1400/110230'},\n {value: 'Mango Mambo', text: 'Mango Mambo'},\n {value: 'orange pekoe with honey and lemon',\n text: 'orange pekoe with honey and lemon'},\n {value: 'Pink Flamingo', text: 'Pink Flamingo'},\n {value: 'Green Kukicha', text: 'Green Kukicha'},\n {value: 'Yunnan Feng Qing Imperial Dian Hong',\n text: 'Yunnan Feng Qing Imperial Dian Hong'},\n {value: 'Dragonwell Chamomile', text: 'Dragonwell Chamomile'},\n {value: 'Ceylon OP Classic Dimbula', text: 'Ceylon OP Classic Dimbula'},\n {value: 'Jasmine Chun Hao Green Tea', text: 'Jasmine Chun Hao Green Tea'},\n {value: 'Ruby Chai', text: 'Ruby Chai'},\n {value: 'Heritage Honey Oolong', text: 'Heritage Honey Oolong'},\n {value: 'Champagne Gold 3 LITER Water Boiler and Warmer',\n text: 'Champagne Gold 3 LITER Water Boiler and Warmer'},\n {value: 'Dan Cong Phenix', text: 'Dan Cong Phenix'},\n {value: 'Wild Orange Pu-erh', text: 'Wild Orange Pu-erh'},\n {value: 'Xi Hu Long Jing', text: 'Xi Hu Long Jing'},\n {value: 'Mangosteen Superfruit Tea', text: 'Mangosteen Superfruit Tea'},\n {value: 'Organic Yunnan English Breakfast',\n text: 'Organic Yunnan English Breakfast'},\n {value: 'Molly Hooper (Blend)', text: 'Molly Hooper (Blend)'},\n {value: 'Opal of Norway', text: 'Opal of Norway'},\n {value: 'Thailand Bold Leaf Green Tea',\n text: 'Thailand Bold Leaf Green Tea'},\n {value: 'Songyang White', text: 'Songyang White'},\n {value: 'Rote Grütze (Red Groats)', text: 'Rote Grütze (Red Groats)'},\n {value: 'Sweet Thai Delight', text: 'Sweet Thai Delight'},\n {value: 'Feeling Soothed - Peppermint Ginger and Fennel Herbal Tea',\n text: 'Feeling Soothed - Peppermint Ginger and Fennel Herbal Tea'},\n {value: 'moroccan mint', text: 'moroccan mint'},\n {value: 'Blueberry (Green)', text: 'Blueberry (Green)'},\n {value: 'Earl Grey (Tomurcuk Tea)', text: 'Earl Grey (Tomurcuk Tea)'},\n {value: 'Haiwan Supreme Tea Ripe Pu’er Tea 2008',\n text: 'Haiwan Supreme Tea Ripe Pu’er Tea 2008'},\n {value: 'Bai Mu dan (White Peony)', text: 'Bai Mu dan (White Peony)'},\n {value: 'Vanilla Date Flavored Black Tea with Coconut',\n text: 'Vanilla Date Flavored Black Tea with Coconut'},\n {value: 'Amba Ceylon', text: 'Amba Ceylon'},\n {value: 'Chamomile Safflower', text: 'Chamomile Safflower'},\n {value: '2009 Fall Diamond Grade Tie Guan Yin',\n text: '2009 Fall Diamond Grade Tie Guan Yin'},\n {value: 'China Tarry Souchong', text: 'China Tarry Souchong'},\n {value: 'Darjeeling Second Flush Puttabong Estate',\n text: 'Darjeeling Second Flush Puttabong Estate'},\n {value: 'Nepal masala chai', text: 'Nepal masala chai'},\n {value: 'Thé Tarte Tatin', text: 'Thé Tarte Tatin'},\n {value: '9 Treasures', text: '9 Treasures'},\n {value: 'Breakfast Tea', text: 'Breakfast Tea'},\n {value: 'Juliets Kiss', text: 'Juliets Kiss'},\n {value: 'Da Yu Ling Oolong', text: 'Da Yu Ling Oolong'},\n {value: 'Premium Silvestre - Rosa Silvestre Hibisco e Amora',\n text: 'Premium Silvestre - Rosa Silvestre Hibisco e Amora'},\n {value: 'Organic Keemum Panda 1', text: 'Organic Keemum Panda 1'},\n {value: 'Ancient Forest Black', text: 'Ancient Forest Black'},\n {value: 'Rose Congou Emperor', text: 'Rose Congou Emperor'},\n {value: 'Cactus Flower', text: 'Cactus Flower'},\n {value: 'Decaf Mango', text: 'Decaf Mango'},\n {value: 'Hunan Black Buds [Out of Stock]',\n text: 'Hunan Black Buds [Out of Stock]'},\n {value: 'Rooibos Africana', text: 'Rooibos Africana'},\n {value: 'White Tangerine', text: 'White Tangerine'},\n {value: 'Sencha Quince', text: 'Sencha Quince'},\n {value: 'Thé Blanc Marco Polo', text: 'Thé Blanc Marco Polo'},\n {value: 'Uji Kabuse', text: 'Uji Kabuse'},\n {value: 'Earl Grey Citrus', text: 'Earl Grey Citrus'},\n {value: 'Montagne Bleue', text: 'Montagne Bleue'},\n {value: 'Chinese Oolong', text: 'Chinese Oolong'},\n {value: 'Blackberry Raspberry (Mora Lampone)',\n text: 'Blackberry Raspberry (Mora Lampone)'},\n {value: 'Zing Me', text: 'Zing Me'},\n {value: 'Tenryu Misakubo Shincha', text: 'Tenryu Misakubo Shincha'},\n {value: 'Raspberry &amp; Vanilla', text: 'Raspberry &amp; Vanilla'},\n {value: 'India Tea Vanilla', text: 'India Tea Vanilla'},\n {value: 'White Peach Oolong', text: 'White Peach Oolong'},\n {value: 'Night of the Iguana Chocolate Chai',\n text: 'Night of the Iguana Chocolate Chai'},\n {value: 'Spicy Chai Latte', text: 'Spicy Chai Latte'},\n {value: 'Big Green Hojicha', text: 'Big Green Hojicha'},\n {value: 'Spring Cherry', text: 'Spring Cherry'},\n {value: 'Crimson Nectar', text: 'Crimson Nectar'},\n {value: 'White Monkey Picked', text: 'White Monkey Picked'},\n {value: 'Darjeeling FTGFOP No. 26', text: 'Darjeeling FTGFOP No. 26'},\n {value: 'Decaf Vanilla Nut Creme', text: 'Decaf Vanilla Nut Creme'},\n {value: 'Organic Yunnan FOP Select (ZY54)',\n text: 'Organic Yunnan FOP Select (ZY54)'},\n {value: 'English Green Tea with Jasmine Flowers',\n text: 'English Green Tea with Jasmine Flowers'},\n {value: 'Apple Pie Honeybush Custom Blend',\n text: 'Apple Pie Honeybush Custom Blend'},\n {value: 'Organic Dandelion Infusion', text: 'Organic Dandelion Infusion'},\n {value: 'Morrocan Mist', text: 'Morrocan Mist'},\n {value: '2010 Spring Snow Dragon - Hand Crafted Yunnan White Tea',\n text: '2010 Spring Snow Dragon - Hand Crafted Yunnan White Tea'},\n {value: 'Margarets Hope First Flush Darjeeling',\n text: 'Margarets Hope First Flush Darjeeling'},\n {value: 'Fair Trade Earl Grey', text: 'Fair Trade Earl Grey'},\n {value: 'Mike-the-Nerds Irish Creme Flavored Black Tea',\n text: 'Mike-the-Nerds Irish Creme Flavored Black Tea'},\n {value: 'Sleepytime Vanilla', text: 'Sleepytime Vanilla'},\n {value: 'Berry Berry Nice', text: 'Berry Berry Nice'},\n {value: 'Toppers Lemon &amp; Ginger', text: 'Toppers Lemon &amp; Ginger'},\n {value: 'Organic Pu-Erh Tea', text: 'Organic Pu-Erh Tea'},\n {value: 'Ginseng Vitality', text: 'Ginseng Vitality'},\n {value: 'Cream of Assam', text: 'Cream of Assam'},\n {value: 'Coconut French Toast with Cardamom Maple Syrup',\n text: 'Coconut French Toast with Cardamom Maple Syrup'},\n {value: 'Maple Blueberry', text: 'Maple Blueberry'},\n {value: 'The Cardio', text: 'The Cardio'},\n {value: 'Chocolate Caramel Enchantment Chai',\n text: 'Chocolate Caramel Enchantment Chai'},\n {value: 'Organic Breakfast Blend', text: 'Organic Breakfast Blend'},\n {value: 'Golden Lotus', text: 'Golden Lotus'},\n {value: 'Hoji Cha', text: 'Hoji Cha'},\n {value: 'Azafranda Saffron Tea', text: 'Azafranda Saffron Tea'},\n {value: 'Formosa Imperial Dragon', text: 'Formosa Imperial Dragon'},\n {value: 'Masala Chai (No. 920)', text: 'Masala Chai (No. 920)'},\n {value: 'Valkoinen Helmi - White Pearl',\n text: 'Valkoinen Helmi - White Pearl'},\n {value: 'Elephant Blanc', text: 'Elephant Blanc'},\n {value: 'Decaffeinated Hot Tea', text: 'Decaffeinated Hot Tea'},\n {value: 'Kiwi Berry', text: 'Kiwi Berry'},\n {value: 'Banana Cheesecake Genmaicha',\n text: 'Banana Cheesecake Genmaicha'},\n {value: 'Oconnors Cream', text: 'Oconnors Cream'},\n {value: '1980s Yunnan Hong Cha (150g)',\n text: '1980s Yunnan Hong Cha (150g)'},\n {value: 'Gyokuro Kuki-Cha Twig Tea (Blenders Series)',\n text: 'Gyokuro Kuki-Cha Twig Tea (Blenders Series)'},\n {value: 'Tangerine Dream (organic)', text: 'Tangerine Dream (organic)'},\n {value: 'Matcha Iri Genmaicha', text: 'Matcha Iri Genmaicha'},\n {value: 'Peppermint Punch', text: 'Peppermint Punch'},\n {value: 'Elegant Beauty * Single Bush Dancong Oolong',\n text: 'Elegant Beauty * Single Bush Dancong Oolong'},\n {value: 'Penzi', text: 'Penzi'},\n {value: 'Genmaicha', text: 'Genmaicha'},\n {value: 'Keemun Hao Ya', text: 'Keemun Hao Ya'},\n {value: 'You Are My Sunshine Flowering Tea',\n text: 'You Are My Sunshine Flowering Tea'},\n {value: 'devonshire cream', text: 'devonshire cream'},\n {value: 'Red Tea (Black Tea) 100% or Full Oxidized',\n text: 'Red Tea (Black Tea) 100% or Full Oxidized'},\n {value: 'Cameronian Gold Blend', text: 'Cameronian Gold Blend'},\n {value: 'Taiwan Ginseng (Lan Gui Ren) Oolong Tea',\n text: 'Taiwan Ginseng (Lan Gui Ren) Oolong Tea'},\n {value: 'Emperors 7 Treasures', text: 'Emperors 7 Treasures'},\n {value: 'Cold Brew Mint Green Tea', text: 'Cold Brew Mint Green Tea'},\n {value: 'Black Satin', text: 'Black Satin'},\n {value: 'Orange Blossom Honey and Lime Juice',\n text: 'Orange Blossom Honey and Lime Juice'},\n {value: 'Organic Slimming Ti Kuan Yin',\n text: 'Organic Slimming Ti Kuan Yin'},\n {value: 'Melon White Tea', text: 'Melon White Tea'},\n {value: '2007 Premium Calabash Shaped Tea 2 oz',\n text: '2007 Premium Calabash Shaped Tea 2 oz'},\n {value: 'Spring 2012 Yunnan Purple Beauty Black Tea of Simao',\n text: 'Spring 2012 Yunnan Purple Beauty Black Tea of Simao'},\n {value: 'Jade oolong', text: 'Jade oolong'},\n {value: 'Golden Bi Luo', text: 'Golden Bi Luo'},\n {value: 'Honeydew Melon', text: 'Honeydew Melon'},\n {value: 'Raspberry Earl Grey', text: 'Raspberry Earl Grey'},\n {value: '3pm Tea', text: '3pm Tea'},\n {value: 'Sichuan Zao Bei Jian (ZK55)',\n text: 'Sichuan Zao Bei Jian (ZK55)'},\n {value: 'Instant Vanilla Chai', text: 'Instant Vanilla Chai'},\n {value: 'Certified Organic * Bai Hao Yin Zhen * Silver Needle White Tea',\n text: 'Certified Organic * Bai Hao Yin Zhen * Silver Needle White Tea'},\n {value: 'Swiss Vervaine Melange', text: 'Swiss Vervaine Melange'},\n {value: 'Green Darjeeling', text: 'Green Darjeeling'},\n {value: 'White Peony Reserve (ZW84)', text: 'White Peony Reserve (ZW84)'},\n {value: 'Cowboy Creamsicle', text: 'Cowboy Creamsicle'},\n {value: 'Ben Shan Oolong', text: 'Ben Shan Oolong'},\n {value: 'Valentines Blend', text: 'Valentines Blend'},\n {value: 'Nannuo Shan Shou Puerh 1997',\n text: 'Nannuo Shan Shou Puerh 1997'},\n {value: 'Tian Di Ren Bulang 2006 Sheng Puer',\n text: 'Tian Di Ren Bulang 2006 Sheng Puer'},\n {value: 'Detox', text: 'Detox'},\n {value: '2010 Fall - Pasha Zhong Zhai Mao Cha - Loose Pu-Erh Tea',\n text: '2010 Fall - Pasha Zhong Zhai Mao Cha - Loose Pu-Erh Tea'},\n {value: 'Dark Rose Tea', text: 'Dark Rose Tea'},\n {value: 'Qianjiazhai Old Growth 2012 Sheng',\n text: 'Qianjiazhai Old Growth 2012 Sheng'},\n {value: 'Strawberry Pepper', text: 'Strawberry Pepper'},\n {value: 'apple cinnamon tea', text: 'apple cinnamon tea'},\n {value: 'Cucumber Mojo White Tea', text: 'Cucumber Mojo White Tea'},\n {value: 'Wild Berry Zinger', text: 'Wild Berry Zinger'},\n {value: 'West Coast Trail', text: 'West Coast Trail'},\n {value: 'Kiwi Peach', text: 'Kiwi Peach'},\n {value: 'Dragonwell Reserve', text: 'Dragonwell Reserve'},\n {value: 'MatéVana Herbal Tea', text: 'MatéVana Herbal Tea'},\n {value: 'Green Tea Super Antioxidant',\n text: 'Green Tea Super Antioxidant'},\n {value: 'Jun Shan Yin Zhen-Mt.Jun Silver Needle',\n text: 'Jun Shan Yin Zhen-Mt.Jun Silver Needle'},\n {value: 'Assam Ledo Estate', text: 'Assam Ledo Estate'},\n {value: 'Premium Golden Monkey', text: 'Premium Golden Monkey'},\n {value: 'Organic Earl Grey Black and Green',\n text: 'Organic Earl Grey Black and Green'},\n {value: 'jasmine blueberry', text: 'jasmine blueberry'},\n {value: 'Get Up n Goji Berry', text: 'Get Up n Goji Berry'},\n {value: 'Master Luos Hong Mei Black', text: 'Master Luos Hong Mei Black'},\n {value: 'Late Summer Love', text: 'Late Summer Love'},\n {value: 'CRAVINGS: DiabeTea – Gymnema Bitter Melon Chamomile',\n text: 'CRAVINGS: DiabeTea – Gymnema Bitter Melon Chamomile'},\n {value: 'Cheeky Lychee', text: 'Cheeky Lychee'},\n {value: 'Feel Better Tea', text: 'Feel Better Tea'},\n {value: 'Organic Yue Ming Xiang Green Oolong Wuyishan',\n text: 'Organic Yue Ming Xiang Green Oolong Wuyishan'},\n {value: 'Berryblossom White', text: 'Berryblossom White'},\n {value: 'English Afternoon', text: 'English Afternoon'},\n {value: 'Feng Huang Milan Dancong', text: 'Feng Huang Milan Dancong'},\n {value: '2005 Superior Puer Ripe', text: '2005 Superior Puer Ripe'},\n {value: 'Broken Leaf', text: 'Broken Leaf'},\n {value: 'Hunan Black', text: 'Hunan Black'},\n {value: '2007 CNNP Hunan Shouzhu Fuzhuan (hei cha)',\n text: '2007 CNNP Hunan Shouzhu Fuzhuan (hei cha)'},\n {value: '531 China Temple of Heaven Gunpowder',\n text: '531 China Temple of Heaven Gunpowder'},\n {value: 'Caramel Houjicha', text: 'Caramel Houjicha'},\n {value: 'Thé du Hammam', text: 'Thé du Hammam'},\n {value: 'Ming Jian Spring 09', text: 'Ming Jian Spring 09'},\n {value: 'Ti Kwan Yin', text: 'Ti Kwan Yin'},\n {value: 'Secret', text: 'Secret'},\n {value: 'Deep Green Embrace', text: 'Deep Green Embrace'},\n {value: 'Earl Grey White and Lavender Dreams',\n text: 'Earl Grey White and Lavender Dreams'},\n {value: 'Bancha Suruga', text: 'Bancha Suruga'},\n {value: 'Organic Pomegranate White Tea',\n text: 'Organic Pomegranate White Tea'},\n {value: 'Chamomile Herbal', text: 'Chamomile Herbal'},\n {value: 'Yorkshire Garden', text: 'Yorkshire Garden'},\n {value: 'Strawberry Pancake Green Tea',\n text: 'Strawberry Pancake Green Tea'},\n {value: 'Chocolate Chip', text: 'Chocolate Chip'},\n {value: 'Adams Peak', text: 'Adams Peak'},\n {value: 'Organic China White Fujian Silver Needle',\n text: 'Organic China White Fujian Silver Needle'},\n {value: 'Lemongrass Mate', text: 'Lemongrass Mate'},\n {value: 'Rumchata Genmaicha', text: 'Rumchata Genmaicha'},\n {value: 'Green Tea Ginger Orange', text: 'Green Tea Ginger Orange'},\n {value: 'Emerald Green', text: 'Emerald Green'},\n {value: 'Honey', text: 'Honey'},\n {value: '2006 Chen Sheng Hao Classic Raw',\n text: '2006 Chen Sheng Hao Classic Raw'},\n {value: '2007 Mengsa Arbor Raw Puer Cake',\n text: '2007 Mengsa Arbor Raw Puer Cake'},\n {value: 'Organic Original De-Caf', text: 'Organic Original De-Caf'},\n {value: 'Corazon De Melon', text: 'Corazon De Melon'},\n {value: 'Happiness', text: 'Happiness'},\n {value: 'Superior Long Jing (Dragon Well)',\n text: 'Superior Long Jing (Dragon Well)'},\n {value: 'Mini Tuocha Pu-erh', text: 'Mini Tuocha Pu-erh'},\n {value: 'Camoflage Puerh Tea Cake From The Phoenix Collection',\n text: 'Camoflage Puerh Tea Cake From The Phoenix Collection'},\n {value: 'Rooibos Lemon Cloud', text: 'Rooibos Lemon Cloud'},\n {value: 'Indian Night Decaf Black Vanilla',\n text: 'Indian Night Decaf Black Vanilla'},\n {value: 'Brick Aged White Tea', text: 'Brick Aged White Tea'},\n {value: 'Caramel Cherry Cheesecake', text: 'Caramel Cherry Cheesecake'},\n {value: 'Earl Grey no. 69', text: 'Earl Grey no. 69'},\n {value: 'Snowbud', text: 'Snowbud'},\n {value: 'Citrus Grove', text: 'Citrus Grove'},\n {value: 'La Creme', text: 'La Creme'},\n {value: 'Golden Lily Milk Oolong', text: 'Golden Lily Milk Oolong'},\n {value: 'Pai Mu Tan (白牡丹)', text: 'Pai Mu Tan (白牡丹)'},\n {value: 'Chai Spiced Apple', text: 'Chai Spiced Apple'},\n {value: 'Mate Cocido', text: 'Mate Cocido'},\n {value: 'Organic White Tea with Raspberry',\n text: 'Organic White Tea with Raspberry'},\n {value: 'Imperial Gold', text: 'Imperial Gold'},\n {value: '高級雁ヶ音ほうじ茶 (High Grade Karigane Houjicha)',\n text: '高級雁ヶ音ほうじ茶 (High Grade Karigane Houjicha)'},\n {value: 'Frutas del Bosque', text: 'Frutas del Bosque'},\n {value: 'Osmanthe DOr', text: 'Osmanthe DOr'},\n {value: 'Oolong Raspberry', text: 'Oolong Raspberry'},\n {value: '2003 Dayi Yiwu Arbor Pu-Erh',\n text: '2003 Dayi Yiwu Arbor Pu-Erh'},\n {value: 'Purple Tip', text: 'Purple Tip'},\n {value: 'Steamed Green Tea (Gen Mai Cha)',\n text: 'Steamed Green Tea (Gen Mai Cha)'},\n {value: 'Golden Wire', text: 'Golden Wire'},\n {value: 'Herbal Masala Chai', text: 'Herbal Masala Chai'},\n {value: 'Matcha Genmaicha', text: 'Matcha Genmaicha'},\n {value: 'Blood Orange Star Fruit Antioxidant Max (Green Tea)',\n text: 'Blood Orange Star Fruit Antioxidant Max (Green Tea)'},\n {value: 'Ripened Rose Pu-erh Mini Tuocha',\n text: 'Ripened Rose Pu-erh Mini Tuocha'},\n {value: 'Rose Garden', text: 'Rose Garden'},\n {value: 'Organic Miyazaki Sencha Sakimidori',\n text: 'Organic Miyazaki Sencha Sakimidori'},\n {value: 'Mengku Wild Arbor Assamica Black Tea * Spring 2017',\n text: 'Mengku Wild Arbor Assamica Black Tea * Spring 2017'},\n {value: 'Gyokuro (Premium Tea Bag)', text: 'Gyokuro (Premium Tea Bag)'},\n {value: 'Yogi Teas Vanilla Hazelnut &amp; Zhenas Gypsy Teas Coconut Chai',\n text: 'Yogi Teas Vanilla Hazelnut &amp; Zhenas Gypsy Teas Coconut Chai'},\n {value: 'English Breakfast (High Grown)',\n text: 'English Breakfast (High Grown)'},\n {value: 'Sakura Vert', text: 'Sakura Vert'},\n {value: 'Sencha Dong-yang', text: 'Sencha Dong-yang'},\n {value: 'East Frisian Sunday Tea (TB54)',\n text: 'East Frisian Sunday Tea (TB54)'},\n {value: 'Harmutty Golden Tippy Assam',\n text: 'Harmutty Golden Tippy Assam'},\n {value: 'Smoked Assam Oolong', text: 'Smoked Assam Oolong'},\n {value: 'Chili Rooibos T-Dust', text: 'Chili Rooibos T-Dust'},\n {value: 'Wild Cherry / Villikirsikka',\n text: 'Wild Cherry / Villikirsikka'},\n {value: 'China Mao Feng', text: 'China Mao Feng'},\n {value: 'Soureni FTGFOP 1 1st Flush 2010',\n text: 'Soureni FTGFOP 1 1st Flush 2010'},\n {value: 'Hunan Gold', text: 'Hunan Gold'},\n {value: 'Ceylon OP1', text: 'Ceylon OP1'},\n {value: 'China Keemun Dao Ming (organic ZK24)',\n text: 'China Keemun Dao Ming (organic ZK24)'},\n {value: 'Citrus Mate', text: 'Citrus Mate'},\n {value: 'Blended Sencha Super Premium',\n text: 'Blended Sencha Super Premium'},\n {value: 'Ceylon Dimbula', text: 'Ceylon Dimbula'},\n {value: '1996s Menghai 7532-Orange-in-orange',\n text: '1996s Menghai 7532-Orange-in-orange'},\n {value: 'Doke Oolong Bihar - ITFA - International Tea Farm Alliance',\n text: 'Doke Oolong Bihar - ITFA - International Tea Farm Alliance'},\n {value: 'Cascade Peppermint', text: 'Cascade Peppermint'},\n {value: 'Damn Fine Holiday Blend', text: 'Damn Fine Holiday Blend'},\n {value: 'Banana Peach Green', text: 'Banana Peach Green'},\n {value: '2011 Yang Pin Hao Jing Mai Raw Puerh Tea',\n text: '2011 Yang Pin Hao Jing Mai Raw Puerh Tea'},\n {value: 'Mambo', text: 'Mambo'},\n {value: 'Strawberry fields', text: 'Strawberry fields'},\n {value: 'Pomegranate Vanilla (Sip for the Cure)',\n text: 'Pomegranate Vanilla (Sip for the Cure)'},\n {value: 'Jasmine Silver Needle (Mo Li Yin Zhen)',\n text: 'Jasmine Silver Needle (Mo Li Yin Zhen)'},\n {value: 'Tsumi Sencha Green Tea', text: 'Tsumi Sencha Green Tea'},\n {value: 'Passionfruit Black', text: 'Passionfruit Black'},\n {value: 'Lapsang Souchong Star (organic)',\n text: 'Lapsang Souchong Star (organic)'},\n {value: 'Keemun Mao Feng (Premium)', text: 'Keemun Mao Feng (Premium)'},\n {value: 'Gong Fu Yunnan Black', text: 'Gong Fu Yunnan Black'},\n {value: 'CS Lewis Blend', text: 'CS Lewis Blend'},\n {value: 'Biwa-Cha (Loquat Tea)', text: 'Biwa-Cha (Loquat Tea)'},\n {value: 'Sweet Mystique', text: 'Sweet Mystique'},\n {value: 'Matcha Pumpkin Spice', text: 'Matcha Pumpkin Spice'},\n {value: 'Chocolate Coconut Chai', text: 'Chocolate Coconut Chai'},\n {value: 'Rooibos Natur', text: 'Rooibos Natur'},\n {value: 'Green tea with Ginkgo', text: 'Green tea with Ginkgo'},\n {value: 'Origins Chai', text: 'Origins Chai'},\n {value: 'Imperial Grade Laoshan Black Tea from Shandong * Spring 2016',\n text: 'Imperial Grade Laoshan Black Tea from Shandong * Spring 2016'},\n {value: 'Green Tea Frappuccino Blended Creme',\n text: 'Green Tea Frappuccino Blended Creme'},\n {value: 'gyokura matcha', text: 'gyokura matcha'},\n {value: 'Royal Black No 1', text: 'Royal Black No 1'},\n {value: 'Pu-erh Mini Tuocha Camels Breath',\n text: 'Pu-erh Mini Tuocha Camels Breath'},\n {value: 'black ti kuan yin', text: 'black ti kuan yin'},\n {value: 'Peppermint Herbal Tea (Caffeine Free)',\n text: 'Peppermint Herbal Tea (Caffeine Free)'},\n {value: '2004 Hai Lang Hao Nan Nuo Bai Hao Raw Pu-erh tea cake',\n text: '2004 Hai Lang Hao Nan Nuo Bai Hao Raw Pu-erh tea cake'},\n {value: 'Pecan Pie', text: 'Pecan Pie'},\n {value: '2007 Bulang Spring Buds Pu-erh Tea Cake',\n text: '2007 Bulang Spring Buds Pu-erh Tea Cake'},\n {value: 'Brown Rice Green Tea', text: 'Brown Rice Green Tea'},\n {value: 'Imperial Gold Needle Yunnan Black Tea',\n text: 'Imperial Gold Needle Yunnan Black Tea'},\n {value: 'Organic Gyokuro', text: 'Organic Gyokuro'},\n {value: 'Da Hong Pao 大红袍', text: 'Da Hong Pao 大红袍'},\n {value: 'Mango Fruit Punch', text: 'Mango Fruit Punch'},\n {value: 'Camomile Honey and Vanilla', text: 'Camomile Honey and Vanilla'},\n {value: 'White Sage and Wild Mint', text: 'White Sage and Wild Mint'},\n {value: 'English Earl Grey (Blue Knight Special)',\n text: 'English Earl Grey (Blue Knight Special)'},\n {value: 'Mandarin Orchard Green Tea (Decaf)',\n text: 'Mandarin Orchard Green Tea (Decaf)'},\n {value: 'Suma Root', text: 'Suma Root'},\n {value: 'Yin Zhen (Silver Needle)', text: 'Yin Zhen (Silver Needle)'},\n {value: 'Shan Lin Xi charcoal baked', text: 'Shan Lin Xi charcoal baked'},\n {value: 'Blood Orange Pu-erh', text: 'Blood Orange Pu-erh'},\n {value: '2008 Menghai Dayi Tea Factory * 8582 * Raw Pu-erh Tea cake',\n text: '2008 Menghai Dayi Tea Factory * 8582 * Raw Pu-erh Tea cake'},\n {value: 'Sandia Spice', text: 'Sandia Spice'},\n {value: 'Boulder Blues', text: 'Boulder Blues'},\n {value: 'A moment of calm selection', text: 'A moment of calm selection'},\n {value: 'Südindien White Oothu (Organic) - 349',\n text: 'Südindien White Oothu (Organic) - 349'},\n {value: 'Pure Lemongrass', text: 'Pure Lemongrass'},\n {value: 'Assam and Rooibos', text: 'Assam and Rooibos'},\n {value: 'Earl Grey Cream Metropolitan Blend',\n text: 'Earl Grey Cream Metropolitan Blend'},\n {value: 'White Tea - Rose Violet', text: 'White Tea - Rose Violet'},\n {value: '9 Ladies Dancing', text: '9 Ladies Dancing'},\n {value: '1990s Shou pu erh brick', text: '1990s Shou pu erh brick'},\n {value: 'Vanilla Sky', text: 'Vanilla Sky'},\n {value: 'Earl Grey Goût Russe', text: 'Earl Grey Goût Russe'},\n {value: 'Mentha Piperita L.', text: 'Mentha Piperita L.'},\n {value: 'East Frisian Leaf Blend', text: 'East Frisian Leaf Blend'},\n {value: 'Organic Ginger Root', text: 'Organic Ginger Root'},\n {value: 'Blue Earl Grey', text: 'Blue Earl Grey'},\n {value: 'Pi Lo Chun (Green Snail Spring) (ZG92)',\n text: 'Pi Lo Chun (Green Snail Spring) (ZG92)'},\n {value: 'The Jane Austen Mafia', text: 'The Jane Austen Mafia'},\n {value: 'Persimmon Leaves Tea', text: 'Persimmon Leaves Tea'},\n {value: 'Florence', text: 'Florence'},\n {value: 'Chocolate &amp; Ginger Spice',\n text: 'Chocolate &amp; Ginger Spice'},\n {value: 'Cherry', text: 'Cherry'},\n {value: 'Sencha Seogwang First Flush',\n text: 'Sencha Seogwang First Flush'},\n {value: 'Coconut Dream', text: 'Coconut Dream'},\n {value: 'Ginger Peach Herbal Tea', text: 'Ginger Peach Herbal Tea'},\n {value: 'Hampton Breakfast', text: 'Hampton Breakfast'},\n {value: 'Alexandra David-Néel', text: 'Alexandra David-Néel'},\n {value: 'Strawberry Seduction', text: 'Strawberry Seduction'},\n {value: 'Biltmore English Breakfast', text: 'Biltmore English Breakfast'},\n {value: 'Spiced Peach Cobbler', text: 'Spiced Peach Cobbler'},\n {value: 'Ancient Tree Earl Grey', text: 'Ancient Tree Earl Grey'},\n {value: 'Sugar Caramel Oolong', text: 'Sugar Caramel Oolong'},\n {value: 'Cinnamon Almond', text: 'Cinnamon Almond'},\n {value: 'Golden Champion Spring 2011',\n text: 'Golden Champion Spring 2011'},\n {value: 'Iron Goddess of Mercy - Monkey Picked',\n text: 'Iron Goddess of Mercy - Monkey Picked'},\n {value: 'The Immunizer', text: 'The Immunizer'},\n {value: 'Hubei Province Golden Tips Congou (ZK68)',\n text: 'Hubei Province Golden Tips Congou (ZK68)'},\n {value: 'Creamy Nut Oolong', text: 'Creamy Nut Oolong'},\n {value: 'French Canadian Maple', text: 'French Canadian Maple'},\n {value: 'Khumbu Green', text: 'Khumbu Green'},\n {value: 'White Ginger Pear', text: 'White Ginger Pear'},\n {value: 'Buddhas Hand Fo Shou Hon Cha',\n text: 'Buddhas Hand Fo Shou Hon Cha'},\n {value: 'Cozy Almond', text: 'Cozy Almond'},\n {value: 'Erva Cidreira', text: 'Erva Cidreira'},\n {value: 'Pancake Breakfast Black Tea',\n text: 'Pancake Breakfast Black Tea'},\n {value: 'Queens China Oolong', text: 'Queens China Oolong'},\n {value: 'Thailand Jin Xuan Sticky Rice Oolong Tea',\n text: 'Thailand Jin Xuan Sticky Rice Oolong Tea'},\n {value: 'Shapna Fine Black Tea', text: 'Shapna Fine Black Tea'},\n {value: 'Jardin Sauvage', text: 'Jardin Sauvage'},\n {value: 'Lemon Pie', text: 'Lemon Pie'},\n {value: 'Source Mountain - Ben Shan competition grade',\n text: 'Source Mountain - Ben Shan competition grade'},\n {value: 'Yunnan Jin', text: 'Yunnan Jin'},\n {value: 'China Green Tea - Dragon well',\n text: 'China Green Tea - Dragon well'},\n {value: 'Vanilla Citrus Spice', text: 'Vanilla Citrus Spice'},\n {value: 'Matcha Culinary Grade Organic Green Tea',\n text: 'Matcha Culinary Grade Organic Green Tea'},\n {value: 'Wen Shan Bao Zhong', text: 'Wen Shan Bao Zhong'},\n {value: 'Nonpareil Anxi Qing Xiang TieGuanYin Oolong Tea',\n text: 'Nonpareil Anxi Qing Xiang TieGuanYin Oolong Tea'},\n {value: 'Yunnan Golden Tips', text: 'Yunnan Golden Tips'},\n {value: 'Rooibos Apple Cider', text: 'Rooibos Apple Cider'},\n {value: 'Almond', text: 'Almond'},\n {value: 'Pu Erh Hazelberry', text: 'Pu Erh Hazelberry'},\n {value: 'Black Roses', text: 'Black Roses'},\n {value: 'Dan Cong Cha', text: 'Dan Cong Cha'},\n {value: 'Jasmine Garland', text: 'Jasmine Garland'},\n {value: 'Lime Darjeeling', text: 'Lime Darjeeling'},\n {value: 'Champagne Infused White Raspberry Tea',\n text: 'Champagne Infused White Raspberry Tea'},\n {value: 'Green Rooibos Bonita', text: 'Green Rooibos Bonita'},\n {value: 'Blackberry', text: 'Blackberry'},\n {value: 'Sky Between the Branches (Gu Zhang Mao Jian)',\n text: 'Sky Between the Branches (Gu Zhang Mao Jian)'},\n {value: 'White Tea Rose Mélange White Tea Blend',\n text: 'White Tea Rose Mélange White Tea Blend'},\n {value: 'Spring Morning', text: 'Spring Morning'},\n {value: 'Pineapple Ginger black tea', text: 'Pineapple Ginger black tea'},\n {value: 'Neptune', text: 'Neptune'},\n {value: 'Silver Needle Premium', text: 'Silver Needle Premium'},\n {value: 'Boulder Tangerine', text: 'Boulder Tangerine'},\n {value: 'Bamboo', text: 'Bamboo'},\n {value: 'Strawberry Lemonade/Blueberry Bliss',\n text: 'Strawberry Lemonade/Blueberry Bliss'},\n {value: 'Gold Rush', text: 'Gold Rush'},\n {value: 'Organic English Breakfast Tea',\n text: 'Organic English Breakfast Tea'},\n {value: '1991 Da Ye Aged Oolong', text: '1991 Da Ye Aged Oolong'},\n {value: 'Anis', text: 'Anis'},\n {value: 'Sagittarius (The Zodiac Series)',\n text: 'Sagittarius (The Zodiac Series)'},\n {value: 'cinnamon apple oolong', text: 'cinnamon apple oolong'},\n {value: 'Lost Malawi', text: 'Lost Malawi'},\n {value: 'Ceylon Gold', text: 'Ceylon Gold'},\n {value: 'Good Evening', text: 'Good Evening'},\n {value: 'French Caramel Creme Brulee',\n text: 'French Caramel Creme Brulee'},\n {value: 'White Ginger (Kevin Rose)', text: 'White Ginger (Kevin Rose)'},\n {value: 'Jade Cloud', text: 'Jade Cloud'},\n {value: 'Lemongrass Chai', text: 'Lemongrass Chai'},\n {value: 'Peach Blackberry Crumble', text: 'Peach Blackberry Crumble'},\n {value: 'Botswana Blossom (Red)', text: 'Botswana Blossom (Red)'},\n {value: 'Sweet Oolong Revolution', text: 'Sweet Oolong Revolution'},\n {value: '2007 Guoyan Classic 88 Pu-Erh',\n text: '2007 Guoyan Classic 88 Pu-Erh'},\n {value: 'Decaf Carol', text: 'Decaf Carol'},\n {value: 'Gone Surfing', text: 'Gone Surfing'},\n {value: 'Strawberry Black Tea', text: 'Strawberry Black Tea'},\n {value: 'Pomegranate Green Tea', text: 'Pomegranate Green Tea'},\n {value: 'Creme Brulee', text: 'Creme Brulee'},\n {value: 'Flora', text: 'Flora'},\n {value: 'Jasmine Petal', text: 'Jasmine Petal'},\n {value: 'Wet stored dayeqing', text: 'Wet stored dayeqing'},\n {value: 'Cakewalk', text: 'Cakewalk'},\n {value: 'Jhentea', text: 'Jhentea'},\n {value: 'Earl Grey (loose leaf)', text: 'Earl Grey (loose leaf)'},\n {value: '2002 Feng Qing Jia Ji Tuocha',\n text: '2002 Feng Qing Jia Ji Tuocha'},\n {value: 'Aged Pu-Erh Tea Brick', text: 'Aged Pu-Erh Tea Brick'},\n {value: 'Darjeeling Summer', text: 'Darjeeling Summer'},\n {value: 'Rose Green Oolong', text: 'Rose Green Oolong'},\n {value: 'wenshan baozhang 2012', text: 'wenshan baozhang 2012'},\n {value: 'Da Fo Long Jing (Big Buddha Dragon Well)',\n text: 'Da Fo Long Jing (Big Buddha Dragon Well)'},\n {value: 'ZO88: Tie-Guan-Yin Oolong Special Grade',\n text: 'ZO88: Tie-Guan-Yin Oolong Special Grade'},\n {value: 'TD68: Sungma Estate SFTGFOP1 Ch/Fl First Flush (DJ-2) Organic',\n text: 'TD68: Sungma Estate SFTGFOP1 Ch/Fl First Flush (DJ-2) Organic'},\n {value: 'Mint', text: 'Mint'},\n {value: 'Assam Duflating Premium Goldleaf STGFOP1 Spl. CL',\n text: 'Assam Duflating Premium Goldleaf STGFOP1 Spl. CL'},\n {value: 'Orange Spicer', text: 'Orange Spicer'},\n {value: 'China Aged Pu-Erh Celestial Tribute',\n text: 'China Aged Pu-Erh Celestial Tribute'},\n {value: 'Scent of Mountain Sencha', text: 'Scent of Mountain Sencha'},\n {value: 'longevitea', text: 'longevitea'},\n {value: 'Paris Market Day', text: 'Paris Market Day'},\n {value: 'Shaken Iced Tea Lemonade', text: 'Shaken Iced Tea Lemonade'},\n {value: 'Fujian Long Yuan Golden Pekoe',\n text: 'Fujian Long Yuan Golden Pekoe'},\n {value: '1910 (The Devoteas Premium English Breakfast renamed))',\n text: '1910 (The Devoteas Premium English Breakfast renamed))'},\n {value: 'Nuts for Cookies', text: 'Nuts for Cookies'},\n {value: 'Darjeeling Margarets Hope FTGFOP 1',\n text: 'Darjeeling Margarets Hope FTGFOP 1'},\n {value: '2011 Yunnan Sourcing Autumn Gua Feng Zhai Raw Pu-erh tea of Yi Wu',\n text: '2011 Autumn Gua Feng Zhai Raw Pu-erh tea of Yi Wu'},\n {value: 'Jasmine Scented White Peony',\n text: 'Jasmine Scented White Peony'},\n {value: 'Darjeeling Earl Grey', text: 'Darjeeling Earl Grey'},\n {value: 'Fruit Line Green Tea &amp; Wildberry',\n text: 'Fruit Line Green Tea Wildberry'},\n {value: 'Decaf Ceylon', text: 'Decaf Ceylon'},\n {value: 'SBT: Maple Marshmallow', text: 'SBT: Maple Marshmallow'},\n {value: '1001 Nights', text: '1001 Nights'},\n {value: 'Pineapple Bacon Rooibos', text: 'Pineapple Bacon Rooibos'},\n {value: 'Great Ocean Pu erh', text: 'Great Ocean Pu erh'},\n {value: 'Pine Tea', text: 'Pine Tea'},\n {value: 'The Colonel', text: 'The Colonel'},\n {value: 'Supreme Monkey Picked', text: 'Supreme Monkey Picked'},\n {value: 'WA - Darjeeling', text: 'WA - Darjeeling'},\n {value: 'Tea Forte Noir Caramel Nougat',\n text: 'Tea Forte Noir Caramel Nougat'},\n {value: 'Ceylon Dimbula B.O.P.', text: 'Ceylon Dimbula B.O.P.'},\n {value: 'Organic Herbal Cranberry Orange',\n text: 'Organic Herbal Cranberry Orange'},\n {value: 'Risheehat 2nd Flush 2010 [Out of Stock]',\n text: 'Risheehat 2nd Flush 2010 [Out of Stock]'},\n {value: 'Year of the Ox Tea 2009', text: 'Year of the Ox Tea 2009'},\n {value: 'Blueberry Red Iced Tea', text: 'Blueberry Red Iced Tea'},\n {value: 'Piccolo', text: 'Piccolo'},\n {value: 'Elizabethan Earl Grey', text: 'Elizabethan Earl Grey'},\n {value: 'Chocolate Truffle aka PMS Blend',\n text: 'Chocolate Truffle aka PMS Blend'},\n {value: 'Longjing / Dragonwell', text: 'Longjing / Dragonwell'},\n {value: '2009 Douji Jing Mai', text: '2009 Douji Jing Mai'},\n {value: 'Jasmine Bloom', text: 'Jasmine Bloom'},\n {value: 'Spiced Christmas Leaf Tea', text: 'Spiced Christmas Leaf Tea'},\n {value: 'BA04: Green Rooibos Poire Creme',\n text: 'BA04: Green Rooibos Poire Creme'},\n {value: 'Zealong Pure', text: 'Zealong Pure'},\n {value: 'Roasted Maté', text: 'Roasted Maté'},\n {value: '2011 Spring Premium Mt. Wudong Huang Zhi Xiang(Gardenia)',\n text: '2011 Spring Premium Mt. Wudong Huang Zhi Xiang(Gardenia)'},\n {value: 'Lemon Lavender Creamsicle', text: 'Lemon Lavender Creamsicle'},\n {value: 'Spearmint Black Tea', text: 'Spearmint Black Tea'},\n {value: 'TC47: Oliphant Estate OPA Green',\n text: 'TC47: Oliphant Estate OPA Green'},\n {value: 'Yunnan Purple Buds', text: 'Yunnan Purple Buds'},\n {value: 'Sechong Oolong', text: 'Sechong Oolong'},\n {value: 'Chá Leão Maçã com Canela', text: 'Chá Leão Maçã com Canela'},\n {value: 'Misfits Bliss', text: 'Misfits Bliss'},\n {value: 'Strawberry Pie Honeybush', text: 'Strawberry Pie Honeybush'},\n {value: 'Camomile &amp; Spearmint', text: 'Camomile &amp; Spearmint'},\n {value: '2011 Da Hong Paolo Wuyi Mount Chinese Oolong Tea',\n text: '2011 Da Hong Paolo Wuyi Mount Chinese Oolong Tea'},\n {value: 'Sleepytime', text: 'Sleepytime'},\n {value: 'Summer Treasure', text: 'Summer Treasure'},\n {value: 'Sexy Chai', text: 'Sexy Chai'},\n {value: 'Panyang Congou Select ZP20 (organic)',\n text: 'Panyang Congou Select ZP20 (organic)'},\n {value: 'Formosa Bai Hao (Oolong 40)',\n text: 'Formosa Bai Hao (Oolong 40)'},\n {value: 'Lemon Blueberry Cookie Dough',\n text: 'Lemon Blueberry Cookie Dough'},\n {value: 'Gemini (The Zodiac Series)', text: 'Gemini (The Zodiac Series)'},\n {value: 'Organic Keemun Panda 1', text: 'Organic Keemun Panda 1'},\n {value: 'Raspberry Truffle', text: 'Raspberry Truffle'},\n {value: 'Everyday Tea (old blend)', text: 'Everyday Tea (old blend)'},\n {value: 'Organic Passion Plum', text: 'Organic Passion Plum'},\n {value: 'Rooibos Strawberry', text: 'Rooibos Strawberry'},\n {value: 'Japanese Sencha Loose Leaf', text: 'Japanese Sencha Loose Leaf'},\n {value: 'Crowberry — Paurngaqutik', text: 'Crowberry — Paurngaqutik'},\n {value: 'Waterlilies Fruit Tea', text: 'Waterlilies Fruit Tea'},\n {value: 'Japan Gyokuro (720)', text: 'Japan Gyokuro (720)'},\n {value: 'Blueberry Bliss', text: 'Blueberry Bliss'},\n {value: '30 Year Aged Tieguanyin', text: '30 Year Aged Tieguanyin'},\n {value: 'Orange Marzipan Rooibos', text: 'Orange Marzipan Rooibos'},\n {value: 'Adawatte Estate OP', text: 'Adawatte Estate OP'},\n {value: 'Matcha au Lait Mix - Soybean Powder',\n text: 'Matcha au Lait Mix - Soybean Powder'},\n {value: 'Strawberry Sencha', text: 'Strawberry Sencha'},\n {value: 'Zealong Aromatic', text: 'Zealong Aromatic'},\n {value: 'Tamaryokucha', text: 'Tamaryokucha'},\n {value: 'Lulu´s Garden - Lychee Tea', text: 'Lulu´s Garden - Lychee Tea'},\n {value: 'Japan Tamaryokucha Yonkon', text: 'Japan Tamaryokucha Yonkon'},\n {value: 'Pineapple Green Tea', text: 'Pineapple Green Tea'},\n {value: 'Buttercream', text: 'Buttercream'},\n {value: 'Green Tea Orange &amp; Ginger',\n text: 'Green Tea Orange &amp; Ginger'},\n {value: 'Organic Darjeeling Autumnal',\n text: 'Organic Darjeeling Autumnal'},\n {value: 'Rose Pouchong', text: 'Rose Pouchong'},\n {value: 'Peachberry Jasmine Sutra', text: 'Peachberry Jasmine Sutra'},\n {value: 'Anxi Rou Gui', text: 'Anxi Rou Gui'},\n {value: 'Chocolate Coconut', text: 'Chocolate Coconut'},\n {value: 'Jungle Ju Ju', text: 'Jungle Ju Ju'},\n {value: 'Organic China Black FOP (ZK16)',\n text: 'Organic China Black FOP (ZK16)'},\n {value: 'Wenshan Bao Zhong Reserve', text: 'Wenshan Bao Zhong Reserve'},\n {value: 'Lil Leapin Lordy Lou', text: 'Lil Leapin Lordy Lou'},\n {value: 'Darjeeling (loose leaf)', text: 'Darjeeling (loose leaf)'},\n {value: 'English Teatime - Decaffeinated',\n text: 'English Teatime - Decaffeinated'},\n {value: 'Seamist', text: 'Seamist'},\n {value: 'Calming', text: 'Calming'},\n {value: 'Fruit Cup', text: 'Fruit Cup'},\n {value: 'Ma Liu Qi Ti Kuan Yin Tea', text: 'Ma Liu Qi Ti Kuan Yin Tea'},\n {value: 'Popcorn Tea', text: 'Popcorn Tea'},\n {value: 'Aztec Sweet Chili', text: 'Aztec Sweet Chili'},\n {value: 'Denong Wild (2009 vintage - mixed harvest)',\n text: 'Denong Wild (2009 vintage - mixed harvest)'},\n {value: 'Bouquet of Flowers No. 108', text: 'Bouquet of Flowers No. 108'},\n {value: 'Sleepytime Extra Wellness Tea',\n text: 'Sleepytime Extra Wellness Tea'},\n {value: 'Darjeeling Castelton FTGFOP',\n text: 'Darjeeling Castelton FTGFOP'},\n {value: 'High Grade Ginseng Oolong (OC03)',\n text: 'High Grade Ginseng Oolong (OC03)'},\n {value: 'Fu Shou Shan', text: 'Fu Shou Shan'},\n {value: 'Red Hot Cinnamon', text: 'Red Hot Cinnamon'},\n {value: 'Organic Yunnan Golden Needle',\n text: 'Organic Yunnan Golden Needle'},\n {value: 'An Ji Bai Cha', text: 'An Ji Bai Cha'},\n {value: 'The Diplomat', text: 'The Diplomat'},\n {value: 'Assam Heeleakah Second Flush TGFOP',\n text: 'Assam Heeleakah Second Flush TGFOP'},\n {value: 'Lu Da Hong Pao', text: 'Lu Da Hong Pao'},\n {value: 'Elder Naylors (herbal)Tea', text: 'Elder Naylors (herbal)Tea'},\n {value: 'Ceylon Vithanakande', text: 'Ceylon Vithanakande'},\n {value: 'So Long and Thanks for All the Licorice',\n text: 'So Long and Thanks for All the Licorice'},\n {value: 'Pumpkin Pecan Pie Flavored Black',\n text: 'Pumpkin Pecan Pie Flavored Black'},\n {value: 'Green Tea with Natural Orange Flavor and SGS',\n text: 'Green Tea with Natural Orange Flavor and SGS'},\n {value: 'Jasmine Silver Tip Tea', text: 'Jasmine Silver Tip Tea'},\n {value: 'Chá preto groselha negra', text: 'Chá preto groselha negra'},\n {value: 'Buttered Rum (organic)', text: 'Buttered Rum (organic)'},\n {value: 'Ceylon Lemon Gunpowder', text: 'Ceylon Lemon Gunpowder'},\n {value: 'Pure Spring Green Tea (Bilo Chun) by In Nature',\n text: 'Pure Spring Green Tea (Bilo Chun) by In Nature'},\n {value: 'Enertea', text: 'Enertea'},\n {value: 'Orange and Spice', text: 'Orange and Spice'},\n {value: 'Lapsang', text: 'Lapsang'},\n {value: 'Royal Palace Pu-erh', text: 'Royal Palace Pu-erh'},\n {value: 'Jasmine Pearls (Mo Li Zhen Zhu)',\n text: 'Jasmine Pearls (Mo Li Zhen Zhu)'},\n {value: 'Winter Cheers', text: 'Winter Cheers'},\n {value: 'Formosa Chun Mee (Organic)', text: 'Formosa Chun Mee (Organic)'},\n {value: 'Peppermint Whole Leaf', text: 'Peppermint Whole Leaf'},\n {value: 'Jin Xuan Milk Oolong', text: 'Jin Xuan Milk Oolong'},\n {value: 'Irish Cream', text: 'Irish Cream'},\n {value: 'Soothing Mint Get Regular', text: 'Soothing Mint Get Regular'},\n {value: 'Darjeeling Enigma Rohini', text: 'Darjeeling Enigma Rohini'},\n {value: 'Brown Sugar Fig Black Tea', text: 'Brown Sugar Fig Black Tea'},\n {value: 'Mélange de Chamonix (TE94)', text: 'Mélange de Chamonix (TE94)'},\n {value: 'Organic Houjicha 2nd Flush (Japan Kyoto Wazuka) Harvest June 2011 (ITFA - International Tea Farm Alliance)',\n text: 'Organic Houjicha (Japan Kyoto Wazuka) Harvest June 2011'},\n {value: 'Hazelnut Rooibos', text: 'Hazelnut Rooibos'},\n {value: 'Lapsang Souchong Organic', text: 'Lapsang Souchong Organic'},\n {value: 'Mocha Pu-Erh Truffle', text: 'Mocha Pu-Erh Truffle'},\n {value: 'Cacao', text: 'Cacao'},\n {value: 'Caramel Vanilla Chai', text: 'Caramel Vanilla Chai'},\n {value: 'Antioxidant Berry Burst', text: 'Antioxidant Berry Burst'},\n {value: 'All That Jazz-Mine', text: 'All That Jazz-Mine'},\n {value: 'Organic Pure Black Iced Tea',\n text: 'Organic Pure Black Iced Tea'},\n {value: 'Midori Sencha', text: 'Midori Sencha'},\n {value: 'Christmas (Rois Mages)', text: 'Christmas (Rois Mages)'},\n {value: 'Ceylon Star', text: 'Ceylon Star'},\n {value: 'Organic Honyama Tokujo Sencha',\n text: 'Organic Honyama Tokujo Sencha'},\n {value: 'Rooibos Lebkuchen', text: 'Rooibos Lebkuchen'},\n {value: 'Liu Bao Flower Buds', text: 'Liu Bao Flower Buds'},\n {value: 'China Chun Mee Organic', text: 'China Chun Mee Organic'},\n {value: 'Assam Deluxe FTGFOP', text: 'Assam Deluxe FTGFOP'},\n {value: 'Mao Feng Green Tea', text: 'Mao Feng Green Tea'},\n {value: 'Royal Elixir Tea', text: 'Royal Elixir Tea'},\n {value: 'Ceylon Apricot Ginger', text: 'Ceylon Apricot Ginger'},\n {value: 'Blue Mountain Spice', text: 'Blue Mountain Spice'},\n {value: 'Rooibos Toffee', text: 'Rooibos Toffee'},\n {value: 'Cardamon Tea', text: 'Cardamon Tea'},\n {value: 'Chocolate Raisin Black Tea', text: 'Chocolate Raisin Black Tea'},\n {value: 'China Jasmine Downy White Pekoe (ZJ98)',\n text: 'China Jasmine Downy White Pekoe (ZJ98)'},\n {value: 'Green Cactus', text: 'Green Cactus'},\n {value: 'Earl Grey Fortune', text: 'Earl Grey Fortune'},\n {value: 'Assam Pure', text: 'Assam Pure'},\n {value: 'Coconut Ginger Organic', text: 'Coconut Ginger Organic'},\n {value: 'Creamy Peppermint', text: 'Creamy Peppermint'},\n {value: 'Green Kukicha - Organic Green Tea',\n text: 'Green Kukicha - Organic Green Tea'},\n {value: 'Mount Fuji Sencha', text: 'Mount Fuji Sencha'},\n {value: 'Lion Mountain Keemun', text: 'Lion Mountain Keemun'},\n {value: 'Pekoe Gold hand-plucked HIGH GRADE Oriental Beauty Oolong Tea',\n text: 'Pekoe Gold hand-plucked HIGH GRADE Oriental Beauty Oolong Tea'},\n {value: 'Shimmer Punch', text: 'Shimmer Punch'},\n {value: 'Darjeeling Makaibari FTGFOP1S Organic',\n text: 'Darjeeling Makaibari FTGFOP1S Organic'},\n {value: 'Pumpkin Pie Flavored Black', text: 'Pumpkin Pie Flavored Black'},\n {value: 'Assam Marangi', text: 'Assam Marangi'},\n {value: 'Premium Keemun Black Tea (Organic) 2009',\n text: 'Premium Keemun Black Tea (Organic) 2009'},\n {value: 'Wild Berry Plum Decaf', text: 'Wild Berry Plum Decaf'},\n {value: 'Golden Ceylon', text: 'Golden Ceylon'},\n {value: 'Plum Blossom Fragrance (Mei Lan Xiang)',\n text: 'Plum Blossom Fragrance (Mei Lan Xiang)'},\n {value: 'Tra Que Chai', text: 'Tra Que Chai'},\n {value: '2007 Menghai Silver Dayi Sheng Pu-Erh',\n text: '2007 Menghai Silver Dayi Sheng Pu-Erh'},\n {value: '2010 Rongzhen Reserve Ripen Pu-erh Tea Cake',\n text: '2010 Rongzhen Reserve Ripen Pu-erh Tea Cake'},\n {value: '2011 Sun Moon lake Red Tea', text: '2011 Sun Moon lake Red Tea'},\n {value: 'China Nanyue Maofeng', text: 'China Nanyue Maofeng'},\n {value: 'Rooibus Infusion Smooth Vanilla',\n text: 'Rooibus Infusion Smooth Vanilla'},\n {value: 'Snow Day', text: 'Snow Day'},\n {value: '1996 Loose Menghai 8542 Raw Puerh',\n text: '1996 Loose Menghai 8542 Raw Puerh'},\n {value: 'Premium Jasmine Oolong', text: 'Premium Jasmine Oolong'},\n {value: 'Strawberry Slender', text: 'Strawberry Slender'},\n {value: 'Aries (The Zodiac Series)', text: 'Aries (The Zodiac Series)'},\n {value: 'Organic Blueberry Rooibos', text: 'Organic Blueberry Rooibos'},\n {value: 'Organic Daba Mountain Jade', text: 'Organic Daba Mountain Jade'},\n {value: '2012 Aka Zizao Bulang', text: '2012 Aka Zizao Bulang'},\n {value: 'English Breakfast Bend', text: 'English Breakfast Bend'},\n {value: 'Aged Yunnan Silver Needle White Cake',\n text: 'Aged Yunnan Silver Needle White Cake'},\n {value: 'Euphoria', text: 'Euphoria'},\n {value: '1981 Aged Dong Ding Oolong 50g',\n text: '1981 Aged Dong Ding Oolong 50g'},\n {value: 'Moroccan Madness', text: 'Moroccan Madness'},\n {value: 'Earl Greater Grey', text: 'Earl Greater Grey'},\n {value: 'Sumatra Highland Chin Chin', text: 'Sumatra Highland Chin Chin'},\n {value: 'Chombe Tea', text: 'Chombe Tea'},\n {value: 'Mhai Diva Green Tea', text: 'Mhai Diva Green Tea'},\n {value: '2008 Dayi 7572 Pu-erh', text: '2008 Dayi 7572 Pu-erh'},\n {value: 'Sommerfrische', text: 'Sommerfrische'},\n {value: 'Celestial Temple Peaks', text: 'Celestial Temple Peaks'},\n {value: 'China Superior Tian Mu Special Grade',\n text: 'China Superior Tian Mu Special Grade'},\n {value: 'Vanilla Choc Chip Chai', text: 'Vanilla Choc Chip Chai'},\n {value: 'Matcha - premium matcha - ura senke preferred matcha | 30g',\n text: 'Matcha - premium matcha - ura senke preferred matcha | 30g'},\n {value: 'Woodbridge Puerh', text: 'Woodbridge Puerh'},\n {value: 'Tender Tip Country Green', text: 'Tender Tip Country Green'},\n {value: 'Wild Cherry Fruit', text: 'Wild Cherry Fruit'},\n {value: 'Tikuanyin', text: 'Tikuanyin'},\n {value: 'Champagne Oolong', text: 'Champagne Oolong'},\n {value: 'Stomach Ease', text: 'Stomach Ease'},\n {value: 'Golden Mojito', text: 'Golden Mojito'},\n {value: 'Ruby Grapefruit White', text: 'Ruby Grapefruit White'},\n {value: 'Welsh Tea - Foiled Sealed Tea Bags',\n text: 'Welsh Tea - Foiled Sealed Tea Bags'},\n {value: 'Nishi 1st Flush Sencha', text: 'Nishi 1st Flush Sencha'},\n {value: 'Cha Wang Jun Shan Yin Zhen', text: 'Cha Wang Jun Shan Yin Zhen'},\n {value: 'Kama Matcha Ceremony Grade Thick Style Matcha Tea',\n text: 'Kama Matcha Ceremony Grade Thick Style Matcha Tea'},\n {value: 'Panyang Tippy Golden Needles Imperial (ZP77)',\n text: 'Panyang Tippy Golden Needles Imperial (ZP77)'},\n {value: 'Mellow Spice Blend 471', text: 'Mellow Spice Blend 471'},\n {value: 'Tai Ping Hou Kui (ZG47)', text: 'Tai Ping Hou Kui (ZG47)'},\n {value: 'Lemon Rose Teabags', text: 'Lemon Rose Teabags'},\n {value: 'Darjeeling Oolong', text: 'Darjeeling Oolong'},\n {value: 'Elijahs Leafy Cassis', text: 'Elijahs Leafy Cassis'},\n {value: 'Green Christmas', text: 'Green Christmas'},\n {value: 'Usucha', text: 'Usucha'},\n {value: 'Flowery Pineapple Oolong', text: 'Flowery Pineapple Oolong'},\n {value: 'Chamraj Nilgiri FOP', text: 'Chamraj Nilgiri FOP'},\n {value: 'No. 18 Brahmin', text: 'No. 18 Brahmin'},\n {value: 'Hawaii-Grown Black', text: 'Hawaii-Grown Black'},\n {value: 'Margarets Hope Euphoria First Flush Garden Darjeeling',\n text: 'Margarets Hope Euphoria First Flush Garden Darjeeling'},\n {value: 'Amaretto Explosion Fruit Tea',\n text: 'Amaretto Explosion Fruit Tea'},\n {value: 'Om Chai', text: 'Om Chai'},\n {value: '2004 Hai Lang Hao Big Snow Mountain Raw Puerh',\n text: '2004 Hai Lang Hao Big Snow Mountain Raw Puerh'},\n {value: 'Master Bis Jin Guan Yin Wuyi Oolong',\n text: 'Master Bis Jin Guan Yin Wuyi Oolong'},\n {value: 'New Vithanakande Estate FBOPF Ex. Spl. (TC27)',\n text: 'New Vithanakande Estate FBOPF Ex. Spl. (TC27)'},\n {value: 'Citrus Melon', text: 'Citrus Melon'},\n {value: 'Qi Hong Mao Feng', text: 'Qi Hong Mao Feng'},\n {value: 'Roobios Red and Assam Black Tea blend',\n text: 'Roobios Red and Assam Black Tea blend'},\n {value: 'Pear Caramel Truffle', text: 'Pear Caramel Truffle'},\n {value: 'Mojito Mint', text: 'Mojito Mint'},\n {value: 'Koyu Organic Premium Matcha',\n text: 'Koyu Organic Premium Matcha'},\n {value: 'Japanilainen Kastepisara - Japanese Dew Drops',\n text: 'Japanilainen Kastepisara - Japanese Dew Drops'},\n {value: 'Mandarin Matcha', text: 'Mandarin Matcha'},\n {value: 'Emperors Breakfast', text: 'Emperors Breakfast'},\n {value: 'An Afternoon in Paris (Un Après-Midi à Paris)',\n text: 'An Afternoon in Paris (Un Après-Midi à Paris)'},\n {value: 'Golden Puerh (organic)', text: 'Golden Puerh (organic)'},\n {value: 'Zhu Rong Yunnan Black', text: 'Zhu Rong Yunnan Black'},\n {value: 'Organic Nilgiri Blue', text: 'Organic Nilgiri Blue'},\n {value: 'Earl of Anxi', text: 'Earl of Anxi'},\n {value: 'Bal Masqué', text: 'Bal Masqué'},\n {value: 'The Mermaids Kiss', text: 'The Mermaids Kiss'},\n {value: 'Bai Hao Oolong (Amber Dragon)',\n text: 'Bai Hao Oolong (Amber Dragon)'},\n {value: '2012 Xiaguan Ma Hei', text: '2012 Xiaguan Ma Hei'},\n {value: 'Jasmine Extra Fancy', text: 'Jasmine Extra Fancy'},\n {value: 'King of Golden Needles', text: 'King of Golden Needles'},\n {value: 'Qi Lan', text: 'Qi Lan'},\n {value: 'Green Yerba Maté', text: 'Green Yerba Maté'},\n {value: 'Qi Hong-Keemun-Broken Tea', text: 'Qi Hong-Keemun-Broken Tea'},\n {value: 'Strawberry &amp; Cream Green',\n text: 'Strawberry &amp; Cream Green'},\n {value: 'Jasmin Chung Feng', text: 'Jasmin Chung Feng'},\n {value: 'Mountain Joy', text: 'Mountain Joy'},\n {value: 'Darjeeling de Triomphe', text: 'Darjeeling de Triomphe'},\n {value: 'Clotted Cream', text: 'Clotted Cream'},\n {value: 'Malachi McCormicks Blend', text: 'Malachi McCormicks Blend'},\n {value: 'Wise Mans Caravan', text: 'Wise Mans Caravan'},\n {value: '2007 Menghai Jade Luster Ripe',\n text: '2007 Menghai Jade Luster Ripe'},\n {value: 'Five OClock Tea', text: 'Five OClock Tea'},\n {value: 'Alwazah Tea with cardamom flavour',\n text: 'Alwazah Tea with cardamom flavour'},\n {value: 'Raspberry and Passionfruit Pyramid Teabags',\n text: 'Raspberry and Passionfruit Pyramid Teabags'},\n {value: 'Thé à lOpéra', text: 'Thé à lOpéra'},\n {value: 'Mango Green', text: 'Mango Green'},\n {value: 'Strawberry Slender Pu-Erh Tea',\n text: 'Strawberry Slender Pu-Erh Tea'},\n {value: 'Nocturnal Bliss', text: 'Nocturnal Bliss'},\n {value: 'English Breakfast Tea (bags)',\n text: 'English Breakfast Tea (bags)'},\n {value: 'Caramel Oasis', text: 'Caramel Oasis'},\n {value: 'Orange and Passion Fruit &amp; Jasmine',\n text: 'Orange and Passion Fruit &amp; Jasmine'},\n {value: 'Keemun Supreme', text: 'Keemun Supreme'},\n {value: 'Kings 313 Green Oolong 2nd Grade',\n text: 'Kings 313 Green Oolong 2nd Grade'},\n {value: 'Big Red Sun', text: 'Big Red Sun'},\n {value: 'Northern Berry Kyss', text: 'Northern Berry Kyss'},\n {value: 'Wuyi Mao Feng Organic', text: 'Wuyi Mao Feng Organic'},\n {value: 'Pomegranate Vanilla Red Tea',\n text: 'Pomegranate Vanilla Red Tea'},\n {value: 'Assam Margherita GFBOP', text: 'Assam Margherita GFBOP'},\n {value: 'Premium Green', text: 'Premium Green'},\n {value: 'Aunties Pumpkin Pie', text: 'Aunties Pumpkin Pie'},\n {value: 'Chocolate Strawberry', text: 'Chocolate Strawberry'},\n {value: 'Rose Congou', text: 'Rose Congou'},\n {value: 'Wuyi Oolong', text: 'Wuyi Oolong'},\n {value: 'Organic Berry Bomb', text: 'Organic Berry Bomb'},\n {value: 'Strawberry Ginger Peppercorn',\n text: 'Strawberry Ginger Peppercorn'},\n {value: 'Gunpowder Zhu Cha', text: 'Gunpowder Zhu Cha'},\n {value: 'Green Mao Feng', text: 'Green Mao Feng'},\n {value: 'Yuqian Dragonwell', text: 'Yuqian Dragonwell'},\n {value: 'Red Tea with Harvest Strawberry and Passionfruit',\n text: 'Red Tea with Harvest Strawberry and Passionfruit'},\n {value: 'Da Hong Pao Oolong', text: 'Da Hong Pao Oolong'},\n {value: 'Yunnan Golden Bud (Jinnah)', text: 'Yunnan Golden Bud (Jinnah)'},\n {value: 'Bohea especially blended for John Greenhow',\n text: 'Bohea especially blended for John Greenhow'},\n {value: 'Green Dragon Oolong', text: 'Green Dragon Oolong'},\n {value: 'Jasmine Plum', text: 'Jasmine Plum'},\n {value: 'Lapsang Souchong Extra Choice',\n text: 'Lapsang Souchong Extra Choice'},\n {value: 'Bombay Chai (Black)', text: 'Bombay Chai (Black)'},\n {value: 'Acai Matetini Mate Tea', text: 'Acai Matetini Mate Tea'},\n {value: 'Organic Premium Green', text: 'Organic Premium Green'},\n {value: 'Evening Blend', text: 'Evening Blend'},\n {value: 'Mate Carnival', text: 'Mate Carnival'},\n {value: 'SoHo Blend', text: 'SoHo Blend'},\n {value: 'Hunan Mao Jian', text: 'Hunan Mao Jian'},\n {value: 'Guiyuan Roasted Dong Ding', text: 'Guiyuan Roasted Dong Ding'},\n {value: 'Cocomint Green', text: 'Cocomint Green'},\n {value: 'Earl Grey Superior', text: 'Earl Grey Superior'},\n {value: 'Dream Journey', text: 'Dream Journey'},\n {value: 'Nut &amp; Honey Crunch', text: 'Nut &amp; Honey Crunch'},\n {value: 'Jade Spring', text: 'Jade Spring'},\n {value: 'DeTox', text: 'DeTox'},\n {value: 'Tibetan mushroom Pu-erh', text: 'Tibetan mushroom Pu-erh'},\n {value: 'Mangalam Golden Tippy Tea | Grade - SFTGFOP1 CLONAL SPECIAL',\n text: 'Mangalam Golden Tippy Tea | Grade - SFTGFOP1 CLONAL SPECIAL'},\n {value: 'Winterwolf', text: 'Winterwolf'},\n {value: 'Bella Berry', text: 'Bella Berry'},\n {value: 'Perfectly Protein Vanilla Chai Tea',\n text: 'Perfectly Protein Vanilla Chai Tea'},\n {value: 'Hairy Crab Oolong', text: 'Hairy Crab Oolong'},\n {value: 'Menghai Yue Chen Yue Xiang', text: 'Menghai Yue Chen Yue Xiang'},\n {value: 'Key Lime Hibiscus Tea', text: 'Key Lime Hibiscus Tea'},\n {value: 'Barberry Fling', text: 'Barberry Fling'},\n {value: '2009 Menghai Dayi Clouds High Mountain Ripe',\n text: '2009 Menghai Dayi Clouds High Mountain Ripe'},\n {value: 'Fireside Smores Tea', text: 'Fireside Smores Tea'},\n {value: 'Kashmir Tchai', text: 'Kashmir Tchai'},\n {value: '952 Rooibos ChocoMint', text: '952 Rooibos ChocoMint'},\n {value: 'Majulighur TGFOP', text: 'Majulighur TGFOP'},\n {value: 'Premium Ceylon New Vithanakande',\n text: 'Premium Ceylon New Vithanakande'},\n {value: 'Premium Keemun Hao Ya Black Tea',\n text: 'Premium Keemun Hao Ya Black Tea'},\n {value: 'Organic Melon White', text: 'Organic Melon White'},\n {value: 'Putuo Shan Fo Cha', text: 'Putuo Shan Fo Cha'},\n {value: 'Finest Jasmine Pearls', text: 'Finest Jasmine Pearls'},\n {value: 'Spicy Chai', text: 'Spicy Chai'},\n {value: 'Ceylon Orange Pekoe (loose leaf)',\n text: 'Ceylon Orange Pekoe (loose leaf)'},\n {value: 'Vanilla Rose', text: 'Vanilla Rose'},\n {value: 'Royal English Breakfast', text: 'Royal English Breakfast'},\n {value: 'Aloe vera Orange', text: 'Aloe vera Orange'},\n {value: 'Release Tea - For Stress Release',\n text: 'Release Tea - For Stress Release'},\n {value: 'Dong Ding special roast winter 2009',\n text: 'Dong Ding special roast winter 2009'},\n {value: 'Pure Buds Black', text: 'Pure Buds Black'},\n {value: 'Fujian Oolong', text: 'Fujian Oolong'},\n {value: 'Wild Arbor Lancang Sheng', text: 'Wild Arbor Lancang Sheng'},\n {value: 'Firefly', text: 'Firefly'},\n {value: 'Black Tea - Loose', text: 'Black Tea - Loose'},\n {value: 'Apple Cinnamon Crunch', text: 'Apple Cinnamon Crunch'},\n {value: 'Watermelon Mint Chiller White Tea',\n text: 'Watermelon Mint Chiller White Tea'},\n {value: 'Butter Pecan Black Tea', text: 'Butter Pecan Black Tea'},\n {value: 'White Chocolate Mousse', text: 'White Chocolate Mousse'},\n {value: 'Mangalam Full-Leaf [duplicate]',\n text: 'Mangalam Full-Leaf [duplicate]'},\n {value: 'Decaf Spice', text: 'Decaf Spice'},\n {value: 'Orange Pekoe and Pekoe Cut Black tea',\n text: 'Orange Pekoe and Pekoe Cut Black tea'},\n {value: 'Infusão Mar do Norte', text: 'Infusão Mar do Norte'},\n {value: 'Coconut Kukicha Masala Chai',\n text: 'Coconut Kukicha Masala Chai'},\n {value: 'Winter Dream', text: 'Winter Dream'},\n {value: 'Tea of Good Tidings', text: 'Tea of Good Tidings'},\n {value: 'Gyokuro Blend Sencha', text: 'Gyokuro Blend Sencha'},\n {value: 'Strawberry Sundae', text: 'Strawberry Sundae'},\n {value: 'Shincha Houryoku', text: 'Shincha Houryoku'},\n {value: 'African Fruit Bowl', text: 'African Fruit Bowl'},\n {value: 'Organic Bitter Melon Botanical Tea',\n text: 'Organic Bitter Melon Botanical Tea'},\n {value: 'Cran-Blackberry Rooibos', text: 'Cran-Blackberry Rooibos'},\n {value: 'Spiced Winter', text: 'Spiced Winter'},\n {value: 'Egyptian Chamomint', text: 'Egyptian Chamomint'},\n {value: 'Honey &amp; Pear', text: 'Honey &amp; Pear'},\n {value: 'Strawberry Kiwi Tea', text: 'Strawberry Kiwi Tea'},\n {value: 'Iron Buddha Oolong Tea (Tie Guan Yin Wu Long)',\n text: 'Iron Buddha Oolong Tea (Tie Guan Yin Wu Long)'},\n {value: 'Finca Kilimanjaro Cascara - El Salvador',\n text: 'Finca Kilimanjaro Cascara - El Salvador'},\n {value: 'Spiced Pumpkin', text: 'Spiced Pumpkin'},\n {value: '1000 Cranes Blend', text: '1000 Cranes Blend'},\n {value: 'Organic Golden Ginger', text: 'Organic Golden Ginger'},\n {value: 'Super Fruit', text: 'Super Fruit'},\n {value: 'Tropical Chai Spice Tea (TE34)',\n text: 'Tropical Chai Spice Tea (TE34)'},\n {value: 'Kanyam Estate 2nd Flush Golden Nepal (TM71)',\n text: 'Kanyam Estate 2nd Flush Golden Nepal (TM71)'},\n {value: 'Whittard Original', text: 'Whittard Original'},\n {value: 'Crimson Quartet', text: 'Crimson Quartet'},\n {value: 'Cranberry', text: 'Cranberry'},\n {value: 'Kalahari', text: 'Kalahari'},\n {value: 'Lemoncello', text: 'Lemoncello'},\n {value: 'Bi Lo Chun', text: 'Bi Lo Chun'},\n {value: 'Green and Fruity', text: 'Green and Fruity'},\n {value: 'Formosa Oolong 8', text: 'Formosa Oolong 8'},\n {value: 'Indian Assam Tea', text: 'Indian Assam Tea'},\n {value: 'Organic Chocolate O', text: 'Organic Chocolate O'},\n {value: 'First Flush Darjeeling (Organic)',\n text: 'First Flush Darjeeling (Organic)'},\n {value: 'Chocolate Pecan Honeybush', text: 'Chocolate Pecan Honeybush'},\n {value: 'Eskimo Kiss - DISCONTINUED', text: 'Eskimo Kiss - DISCONTINUED'},\n {value: 'Dong Ding Oolong of Taiwan/Sweet Osmanthus Odor Dype',\n text: 'Dong Ding Oolong of Taiwan/Sweet Osmanthus Odor Dype'},\n {value: 'Coconut Chai Rooibos', text: 'Coconut Chai Rooibos'},\n {value: 'Rice Tea Porridge', text: 'Rice Tea Porridge'},\n {value: 'Japanese Morning Dew', text: 'Japanese Morning Dew'},\n {value: '2004 Old Youle Ripe Pu-erh Tea Brick',\n text: '2004 Old Youle Ripe Pu-erh Tea Brick'},\n {value: 'Black Dragon Oolong', text: 'Black Dragon Oolong'},\n {value: 'Congo Bongo (organic)', text: 'Congo Bongo (organic)'},\n {value: 'Tahitian Limeade', text: 'Tahitian Limeade'},\n {value: 'Bai Long Jing', text: 'Bai Long Jing'},\n {value: 'Kitchen Sink Green Tea', text: 'Kitchen Sink Green Tea'},\n {value: 'Vanilla Almond Decaf', text: 'Vanilla Almond Decaf'},\n {value: 'Milk Jin Xuan Tea', text: 'Milk Jin Xuan Tea'},\n {value: 'Waikato Zealong', text: 'Waikato Zealong'},\n {value: 'Liquid Jade Matcha', text: 'Liquid Jade Matcha'},\n {value: 'Chiran Sencha', text: 'Chiran Sencha'},\n {value: 'Berries of the Forest', text: 'Berries of the Forest'},\n {value: 'Weight To Go', text: 'Weight To Go'},\n {value: 'Maple Blueberry Tea', text: 'Maple Blueberry Tea'},\n {value: 'Butterfly', text: 'Butterfly'},\n {value: 'Sen Cha Fukamushi Green Tea',\n text: 'Sen Cha Fukamushi Green Tea'},\n {value: 'Cocoa Cay', text: 'Cocoa Cay'},\n {value: 'Cactus Fig', text: 'Cactus Fig'},\n {value: 'Thé des Poètes', text: 'Thé des Poètes'},\n {value: 'Moonlight Spice Orange Spice White Tea',\n text: 'Moonlight Spice Orange Spice White Tea'},\n {value: 'Ceylon Green Curl Sivali Hill',\n text: 'Ceylon Green Curl Sivali Hill'},\n {value: 'Marrakesh', text: 'Marrakesh'},\n {value: 'One Touch Tea Maker', text: 'One Touch Tea Maker'},\n {value: 'Black Chocolate', text: 'Black Chocolate'},\n {value: 'Decaf Muscat', text: 'Decaf Muscat'},\n {value: 'Winter Fire', text: 'Winter Fire'},\n {value: 'Wild Berry', text: 'Wild Berry'},\n {value: 'Just Green Tea', text: 'Just Green Tea'},\n {value: 'Vanilla Bean Honeybush', text: 'Vanilla Bean Honeybush'},\n {value: 'Taiwan Green Tea Powder Matcha',\n text: 'Taiwan Green Tea Powder Matcha'},\n {value: 'Ceylon Black Tea Chai Spice',\n text: 'Ceylon Black Tea Chai Spice'},\n {value: 'Pede um Desejo', text: 'Pede um Desejo'},\n {value: 'Royal Wellness No 4256', text: 'Royal Wellness No 4256'},\n {value: 'Queen West Blend', text: 'Queen West Blend'},\n {value: 'Keemun Mao Feng (Quimen Mao Feng)',\n text: 'Keemun Mao Feng (Quimen Mao Feng)'},\n {value: 'Oregon Peppermint', text: 'Oregon Peppermint'},\n {value: 'Le Digestif (organic)', text: 'Le Digestif (organic)'},\n {value: 'Hazelnut Black Tea', text: 'Hazelnut Black Tea'},\n {value: 'After Midnight', text: 'After Midnight'},\n {value: 'Ginger Spice', text: 'Ginger Spice'},\n {value: 'Lemon-Lime Cheesecake Honeybush',\n text: 'Lemon-Lime Cheesecake Honeybush'},\n {value: 'Extra Fancy Formosa Oolong', text: 'Extra Fancy Formosa Oolong'},\n {value: 'Perfect Pear', text: 'Perfect Pear'},\n {value: '1999 Vietnamese Cooked Loose Puerh',\n text: '1999 Vietnamese Cooked Loose Puerh'},\n {value: 'White Dragon', text: 'White Dragon'},\n {value: 'Cinnamon Apple Spice', text: 'Cinnamon Apple Spice'},\n {value: 'Mycroft', text: 'Mycroft'},\n {value: 'La Creme des Earl Grey', text: 'La Creme des Earl Grey'},\n {value: 'Longan Black', text: 'Longan Black'},\n {value: 'Organic Rooibos Tea', text: 'Organic Rooibos Tea'},\n {value: '2006 Nan Qiao Jia Jia Cooked Beeng Cha',\n text: '2006 Nan Qiao Jia Jia Cooked Beeng Cha'},\n {value: '2006 Xiaguan Cooked (Shu) Pu-Erh Tuo 100g',\n text: '2006 Xiaguan Cooked (Shu) Pu-Erh Tuo 100g'},\n {value: 'Wildberry Plum Green Tea', text: 'Wildberry Plum Green Tea'},\n {value: 'Moroccan Sunset', text: 'Moroccan Sunset'},\n {value: 'Original', text: 'Original'},\n {value: 'Tan Xiang Oolong Charcoal-baked Dong Ding Oolong Tea',\n text: 'Tan Xiang Oolong Charcoal-baked Dong Ding Oolong Tea'},\n {value: 'Ntingwe Kwazulu', text: 'Ntingwe Kwazulu'},\n {value: 'Opus Rouge Rooibos', text: 'Opus Rouge Rooibos'},\n {value: 'Organic Arya Diamond Second Flush Darjeeling',\n text: 'Organic Arya Diamond Second Flush Darjeeling'},\n {value: 'Organic Sencha (Hao Di)', text: 'Organic Sencha (Hao Di)'},\n {value: 'Virgo (The Zodiac Series)', text: 'Virgo (The Zodiac Series)'},\n {value: 'Lemon Ginger', text: 'Lemon Ginger'},\n {value: '2012 Giant Steps Old Arbor Puer Blend',\n text: '2012 Giant Steps Old Arbor Puer Blend'},\n {value: 'Once Upon A Tea', text: 'Once Upon A Tea'},\n {value: '2007 Menghai Dayi 0782', text: '2007 Menghai Dayi 0782'},\n {value: 'Pine Smoked Black', text: 'Pine Smoked Black'},\n {value: '2011 Pure Mengsong Raw Puerh Tea',\n text: '2011 Pure Mengsong Raw Puerh Tea'},\n {value: 'Snow Buds (Xue YA)', text: 'Snow Buds (Xue YA)'},\n {value: 'Pink Lemonade (Sip for the Cure)',\n text: 'Pink Lemonade (Sip for the Cure)'},\n {value: 'Popped Rooibos', text: 'Popped Rooibos'},\n {value: 'Beefeater Peach Martini', text: 'Beefeater Peach Martini'},\n {value: 'Vivaldi', text: 'Vivaldi'},\n {value: 'Earl Grey Blue Star', text: 'Earl Grey Blue Star'},\n {value: 'Chamomile Court', text: 'Chamomile Court'},\n {value: 'Noël à Pékin', text: 'Noël à Pékin'},\n {value: 'Ceylon Cinnamon Spice', text: 'Ceylon Cinnamon Spice'},\n {value: 'Organic White Tea Sweet Citrus',\n text: 'Organic White Tea Sweet Citrus'},\n {value: 'Lao Ban Zhang Shou Been', text: 'Lao Ban Zhang Shou Been'},\n {value: 'Tungting', text: 'Tungting'},\n {value: 'Gyokuro Asahi', text: 'Gyokuro Asahi'},\n {value: 'Vata Ayurvedic', text: 'Vata Ayurvedic'},\n {value: 'Taiwan Paochung', text: 'Taiwan Paochung'},\n {value: 'Scarlet Robe Oolong', text: 'Scarlet Robe Oolong'},\n {value: 'Creme Brulee Matcha', text: 'Creme Brulee Matcha'},\n {value: 'Lychee Black', text: 'Lychee Black'},\n {value: '2011 Winter DaYuLing', text: '2011 Winter DaYuLing'},\n {value: 'Devils chocolate', text: 'Devils chocolate'},\n {value: 'Chun Jian Zang', text: 'Chun Jian Zang'},\n {value: 'Keemun Concerto', text: 'Keemun Concerto'},\n {value: 'Egyptian Licorice Mint', text: 'Egyptian Licorice Mint'},\n {value: 'Ceylon orange pekoe', text: 'Ceylon orange pekoe'},\n {value: 'Sweet Dew Gan Lu', text: 'Sweet Dew Gan Lu'},\n {value: 'Organic Gunpowder', text: 'Organic Gunpowder'},\n {value: 'Lemon Mango', text: 'Lemon Mango'},\n {value: 'Black Bourbon Vanilla', text: 'Black Bourbon Vanilla'},\n {value: 'Pure Assam Irish Breakfast', text: 'Pure Assam Irish Breakfast'},\n {value: 'bai hao yin zhen', text: 'bai hao yin zhen'},\n {value: 'GunPowder Green Tea', text: 'GunPowder Green Tea'},\n {value: 'Debaixo do Vulcão - Under the Vulcano',\n text: 'Debaixo do Vulcão - Under the Vulcano'},\n {value: 'Cancer (The Zodiac Series)', text: 'Cancer (The Zodiac Series)'},\n {value: 'Mandala Tea Phatty Cake', text: 'Mandala Tea Phatty Cake'},\n {value: 'Orchid Tea', text: 'Orchid Tea'},\n {value: 'Cocoa Paradiso (organic)', text: 'Cocoa Paradiso (organic)'},\n {value: 'Super Premium Sencha Green Tea',\n text: 'Super Premium Sencha Green Tea'},\n {value: 'Mandarin Orange Green Tea', text: 'Mandarin Orange Green Tea'},\n {value: 'Earl Green Cream', text: 'Earl Green Cream'},\n {value: 'Cardamom Pu-erh', text: 'Cardamom Pu-erh'},\n {value: 'Ancient Forest', text: 'Ancient Forest'},\n {value: 'Yellow Mu Dan', text: 'Yellow Mu Dan'},\n {value: 'China Hunan Golden Needle', text: 'China Hunan Golden Needle'},\n {value: 'YMY 1960 Genmai Green Tea', text: 'YMY 1960 Genmai Green Tea'},\n {value: 'Constant Comment', text: 'Constant Comment'},\n {value: 'Gong Fu Black', text: 'Gong Fu Black'},\n {value: 'Rooibos Renewal', text: 'Rooibos Renewal'},\n {value: 'Ginger Pear (organic)', text: 'Ginger Pear (organic)'},\n {value: 'Organic Tie Guan Yin “Iron Goddess” Oolong Tea with honey',\n text: 'Organic Tie Guan Yin “Iron Goddess” Oolong Tea with honey'},\n {value: 'Sweetie Pie Rooibos', text: 'Sweetie Pie Rooibos'},\n {value: 'Artisan Revival Stone-Pressed Banzhang 06 Sheng Puer',\n text: 'Artisan Revival Stone-Pressed Banzhang 06 Sheng Puer'},\n {value: 'Green Tea Energy', text: 'Green Tea Energy'},\n {value: 'China Anxi Oolong Select', text: 'China Anxi Oolong Select'},\n {value: 'Black Currant [duplicate]', text: 'Black Currant [duplicate]'},\n {value: 'Transsiberian Chai (Organic)',\n text: 'Transsiberian Chai (Organic)'},\n {value: 'Krampus Brew', text: 'Krampus Brew'},\n {value: 'Ginger Fresh', text: 'Ginger Fresh'},\n {value: 'Dulce &amp; Banana', text: 'Dulce &amp; Banana'},\n {value: 'Ceylon Black Tea', text: 'Ceylon Black Tea'},\n {value: 'South India Iyerpadi', text: 'South India Iyerpadi'},\n {value: 'Osmanthus Silver Needle', text: 'Osmanthus Silver Needle'},\n {value: 'Watson (Blend)', text: 'Watson (Blend)'},\n {value: 'Kiwi Lemon Oolong', text: 'Kiwi Lemon Oolong'},\n {value: 'Kagoshima Sencha Yutaka Midori (2011)',\n text: 'Kagoshima Sencha Yutaka Midori (2011)'},\n {value: 'Honeybush Lemon Ginger (organic)',\n text: 'Honeybush Lemon Ginger (organic)'},\n {value: 'After Dinner Mints', text: 'After Dinner Mints'},\n {value: 'Turmeric Snap (organic)', text: 'Turmeric Snap (organic)'},\n {value: 'Kenyan Earl Grey', text: 'Kenyan Earl Grey'},\n {value: 'Organic Chai Spice Black Tea',\n text: 'Organic Chai Spice Black Tea'},\n {value: 'Shiun- Purple Cloud', text: 'Shiun- Purple Cloud'},\n {value: 'Gourmet Silverpot Limited Edition Darjeeling Second Flush Silverpot Legendary Estates Darjeeling Second Flush and Silverpot Legendary Estates Assam Second Flush',\n text: 'Gourmet Silverpot Darjeeling Second Flush'},\n {value: 'Immortalitea', text: 'Immortalitea'},\n {value: 'Red Jade | Hong Yu', text: 'Red Jade | Hong Yu'},\n {value: 'Mauka Oolong', text: 'Mauka Oolong'},\n {value: '2011 Spring Organic-certified Classic 58 Fengqing',\n text: '2011 Spring Organic-certified Classic 58 Fengqing'},\n {value: 'Organic Gifu Sencha', text: 'Organic Gifu Sencha'},\n {value: 'Chocolat Pot de Tea', text: 'Chocolat Pot de Tea'},\n {value: 'Morning Rise Breakfast Blend',\n text: 'Morning Rise Breakfast Blend'},\n {value: 'Malted ChocoMaté', text: 'Malted ChocoMaté'},\n {value: 'Jin Shuan', text: 'Jin Shuan'},\n {value: 'Cherry Rose Beautify me', text: 'Cherry Rose Beautify me'},\n {value: 'Buddhas Eyebrow', text: 'Buddhas Eyebrow'},\n {value: 'Lavender Earl Grey', text: 'Lavender Earl Grey'},\n {value: 'Rose Scented', text: 'Rose Scented'},\n {value: 'Wan Gong Bing Cha 2011', text: 'Wan Gong Bing Cha 2011'},\n {value: 'Cup-O-Jane', text: 'Cup-O-Jane'},\n {value: 'Doke Silver Needle - ITFA - International Tea Farmer Association',\n text: 'Doke Silver Needle - ITFA - International Tea Farmer Association'},\n {value: 'Rooibos Creme Caramel', text: 'Rooibos Creme Caramel'},\n {value: 'Lovely Lavender', text: 'Lovely Lavender'},\n {value: 'China Gong Ting Wang-OZ', text: 'China Gong Ting Wang-OZ'},\n {value: 'Maple Chai', text: 'Maple Chai'},\n {value: '2010 Teng Chong Hui Long Zhai',\n text: '2010 Teng Chong Hui Long Zhai'},\n {value: 'Lemongrass Black', text: 'Lemongrass Black'},\n {value: 'Yerba Maté Chocolatté', text: 'Yerba Maté Chocolatté'},\n {value: 'Tie Guan Yin (Iron Goddess) Spring 2009',\n text: 'Tie Guan Yin (Iron Goddess) Spring 2009'},\n {value: 'Red Berries', text: 'Red Berries'},\n {value: 'Japanese Emperor Blend', text: 'Japanese Emperor Blend'},\n {value: 'Da Yu Ling', text: 'Da Yu Ling'},\n {value: 'Brisbane Breakfast', text: 'Brisbane Breakfast'},\n {value: 'Tazo Chai Tea Latte', text: 'Tazo Chai Tea Latte'},\n {value: 'Marani™', text: 'Marani™'},\n {value: 'BOO-berry', text: 'BOO-berry'},\n {value: 'Soba Cha Deep Roast', text: 'Soba Cha Deep Roast'},\n {value: '100 Monkeys', text: '100 Monkeys'},\n {value: 'Rivendell', text: 'Rivendell'},\n {value: 'Panda Pearls', text: 'Panda Pearls'},\n {value: 'Bing Cherry with Almond', text: 'Bing Cherry with Almond'},\n {value: 'Lapsang Souchong China Eagle',\n text: 'Lapsang Souchong China Eagle'},\n {value: 'Sencha Imari', text: 'Sencha Imari'},\n {value: '2006 Aromatic Bamboo Roasted Pu-erh Tea',\n text: '2006 Aromatic Bamboo Roasted Pu-erh Tea'},\n {value: 'Organic Honeybush Apple', text: 'Organic Honeybush Apple'},\n {value: 'Japan Sencha Uji', text: 'Japan Sencha Uji'},\n {value: 'unidentified decaf black', text: 'unidentified decaf black'},\n {value: 'Traditional Ti Kuan Yin', text: 'Traditional Ti Kuan Yin'},\n {value: 'Really Russian Caravan', text: 'Really Russian Caravan'},\n {value: 'Coarse cut lemon grass', text: 'Coarse cut lemon grass'},\n {value: 'Coconut Vanilla Chai', text: 'Coconut Vanilla Chai'},\n {value: 'Chocolate Phoenix Chai', text: 'Chocolate Phoenix Chai'},\n {value: '2009 Wuyi Medium-Roasted Da Hong Pao Rock Tea',\n text: '2009 Wuyi Medium-Roasted Da Hong Pao Rock Tea'},\n {value: 'Supreme Breakfast', text: 'Supreme Breakfast'},\n {value: 'Silver Jasmine', text: 'Silver Jasmine'},\n {value: 'Chocolate Cheesecake Chai', text: 'Chocolate Cheesecake Chai'},\n {value: 'Ali Shan High Mountain Beauty Summer 09',\n text: 'Ali Shan High Mountain Beauty Summer 09'},\n {value: 'Instant Ginger Honey Crystals',\n text: 'Instant Ginger Honey Crystals'},\n {value: 'China Guangxi Gui-Hua Osmanthus Tea',\n text: 'China Guangxi Gui-Hua Osmanthus Tea'},\n {value: 'Mélange Ô', text: 'Mélange Ô'},\n {value: 'Jade Pillar', text: 'Jade Pillar'},\n {value: 'Silver Cloud', text: 'Silver Cloud'},\n {value: 'Pu-Erh Tuo Cha', text: 'Pu-Erh Tuo Cha'},\n {value: 'Lemon Drop Cooler', text: 'Lemon Drop Cooler'},\n {value: 'Red Wellness', text: 'Red Wellness'},\n {value: 'Ali Shan High Mountain Oolong Fall 09',\n text: 'Ali Shan High Mountain Oolong Fall 09'},\n {value: 'African Nectar', text: 'African Nectar'},\n {value: 'huang shan mao feng 黄山毛峰', text: 'huang shan mao feng 黄山毛峰'},\n {value: 'Tan Yang Te Ji', text: 'Tan Yang Te Ji'},\n {value: 'Pure Assam', text: 'Pure Assam'},\n {value: 'Silverpot Limited Edition Darjeeling Second Flush',\n text: 'Silverpot Limited Edition Darjeeling Second Flush'},\n {value: 'Violet', text: 'Violet'},\n {value: 'Chocolate Mate Solstice', text: 'Chocolate Mate Solstice'},\n {value: 'Mother Of Pearl', text: 'Mother Of Pearl'},\n {value: 'Ocha-Zanmai Fukamushi Sencha',\n text: 'Ocha-Zanmai Fukamushi Sencha'},\n {value: '1999 Mengku', text: '1999 Mengku'},\n {value: 'Yunnan dOr', text: 'Yunnan dOr'},\n {value: 'Bushmens Brew Honeybush', text: 'Bushmens Brew Honeybush'},\n {value: 'Silver Needle Jasmine', text: 'Silver Needle Jasmine'},\n {value: 'Fukamushi Sencha Special', text: 'Fukamushi Sencha Special'},\n {value: 'Gyokuro Reserve (Growers Series)',\n text: 'Gyokuro Reserve (Growers Series)'},\n {value: 'No. 55 Lord Bergamot', text: 'No. 55 Lord Bergamot'},\n {value: 'Demitasse', text: 'Demitasse'},\n {value: 'Cola Matcha', text: 'Cola Matcha'},\n {value: 'Organic Darjeeling Bergamot',\n text: 'Organic Darjeeling Bergamot'},\n {value: 'Hoopla', text: 'Hoopla'},\n {value: 'Afternoon', text: 'Afternoon'},\n {value: 'instant tibetan yak butter tea/ po cha',\n text: 'instant tibetan yak butter tea/ po cha'},\n {value: 'Tropical Yerba Mate', text: 'Tropical Yerba Mate'},\n {value: 'Secret Mountain Yunnan', text: 'Secret Mountain Yunnan'},\n {value: 'Supreme Yunnan Puerh', text: 'Supreme Yunnan Puerh'},\n {value: 'Intense mint', text: 'Intense mint'},\n {value: 'Maple Cheesecake Ti Kwan Yin',\n text: 'Maple Cheesecake Ti Kwan Yin'},\n {value: 'SyanSyan', text: 'SyanSyan'},\n {value: 'Organic Breakfast Blend Pyramid Tea',\n text: 'Organic Breakfast Blend Pyramid Tea'},\n {value: 'Feng Huang Dan Cong Honey Orchid Gold Medalist No 1',\n text: 'Feng Huang Dan Cong Honey Orchid Gold Medalist No 1'},\n {value: 'Oolong tea', text: 'Oolong tea'},\n {value: 'Mrs. Lis Shi Feng Dragonwell Green Tea',\n text: 'Mrs. Lis Shi Feng Dragonwell Green Tea'},\n {value: 'Taiwan Osmanthus Oolong', text: 'Taiwan Osmanthus Oolong'},\n {value: 'China Oolong Restaurant Style',\n text: 'China Oolong Restaurant Style'},\n {value: 'Buddhas Blend', text: 'Buddhas Blend'},\n {value: 'Monkey King Jasmine Green Tea',\n text: 'Monkey King Jasmine Green Tea'},\n {value: 'Shou Mei', text: 'Shou Mei'},\n {value: 'Colored Species Oolong Tea An Xi Ben Shan',\n text: 'Colored Species Oolong Tea An Xi Ben Shan'},\n {value: 'Cherry Vanilla Cola Black Tea',\n text: 'Cherry Vanilla Cola Black Tea'},\n {value: 'Organic Wild Blueberry', text: 'Organic Wild Blueberry'},\n {value: '2010 Dian Yi Hao Naka Raw Puerh Brick 200g',\n text: '2010 Dian Yi Hao Naka Raw Puerh Brick 200g'},\n {value: '2008 Menghai V93 Premium Ripe Pu-erh tea',\n text: '2008 Menghai V93 Premium Ripe Pu-erh tea'},\n {value: 'Organic Mango', text: 'Organic Mango'},\n {value: 'Grand Pouchong', text: 'Grand Pouchong'},\n {value: 'Divja Češnja', text: 'Divja Češnja'},\n {value: 'Ginger Sage Winter Spa Blend',\n text: 'Ginger Sage Winter Spa Blend'},\n {value: 'Citrus Punch Oolong', text: 'Citrus Punch Oolong'},\n {value: 'Mi Lan Xiang Phoenix Mountain Dancong',\n text: 'Mi Lan Xiang Phoenix Mountain Dancong'},\n {value: 'Wuyi Yuan Cha (OC05)', text: 'Wuyi Yuan Cha (OC05)'},\n {value: 'Wuyi Da Hong Pao', text: 'Wuyi Da Hong Pao'},\n {value: 'Yunnan Golden Rings', text: 'Yunnan Golden Rings'},\n {value: 'Sakurambo', text: 'Sakurambo'},\n {value: 'Swedish Delight', text: 'Swedish Delight'},\n {value: '1st Flush Darjeeling Tukdah',\n text: '1st Flush Darjeeling Tukdah'},\n {value: 'Womans Tea Raspberry Leaf', text: 'Womans Tea Raspberry Leaf'},\n {value: 'SBT: Cotton Candy Green', text: 'SBT: Cotton Candy Green'},\n {value: 'Teaopias Tea Master', text: 'Teaopias Tea Master'},\n {value: 'Qianjiazhai Wild Picked Yunnan Black',\n text: 'Qianjiazhai Wild Picked Yunnan Black'},\n {value: 'Wednesday', text: 'Wednesday'},\n {value: 'Climbers High', text: 'Climbers High'},\n {value: 'Organic Vanilla Almond', text: 'Organic Vanilla Almond'},\n {value: 'Assam Mangalam Second Flush FTGFOP1',\n text: 'Assam Mangalam Second Flush FTGFOP1'},\n {value: 'Rose Kissed Jasmine', text: 'Rose Kissed Jasmine'},\n {value: 'Keemun Mao Feng Imperial', text: 'Keemun Mao Feng Imperial'},\n {value: 'Lemon Verbena', text: 'Lemon Verbena'},\n {value: 'Assam Maijian T.G.F.O.P. Second Flush',\n text: 'Assam Maijian T.G.F.O.P. Second Flush'},\n {value: 'Mate Lemon Green Tea - Rainforest Green',\n text: 'Mate Lemon Green Tea - Rainforest Green'},\n {value: 'Chamomile Lemongrass', text: 'Chamomile Lemongrass'},\n {value: 'Jade Dong Ding', text: 'Jade Dong Ding'},\n {value: 'Cafe Vanilla', text: 'Cafe Vanilla'},\n {value: 'Scottish Breakfast Tea', text: 'Scottish Breakfast Tea'},\n {value: 'Orange Spice White', text: 'Orange Spice White'},\n {value: 'Choco', text: 'Choco'},\n {value: 'Watermelon Matcha', text: 'Watermelon Matcha'},\n {value: 'Magic Moon', text: 'Magic Moon'},\n {value: 'Ruby Black', text: 'Ruby Black'},\n {value: 'Teaopia Holiday Blend (Black)',\n text: 'Teaopia Holiday Blend (Black)'},\n {value: 'Tahitian Blend', text: 'Tahitian Blend'},\n {value: 'Throat Soother', text: 'Throat Soother'},\n {value: 'Fast Lane Black Tea', text: 'Fast Lane Black Tea'},\n {value: 'Jasmine Golden Yunnan', text: 'Jasmine Golden Yunnan'},\n {value: 'gunpowder', text: 'gunpowder'},\n {value: 'YaYa Strawberry', text: 'YaYa Strawberry'},\n {value: 'Sri Lanka Silver Needles', text: 'Sri Lanka Silver Needles'},\n {value: 'Georgia Peach Rooibos', text: 'Georgia Peach Rooibos'},\n {value: 'Peach Rooibos Iced Tea', text: 'Peach Rooibos Iced Tea'},\n {value: 'Konacha (Sushi Bar Style Green Tea)',\n text: 'Konacha (Sushi Bar Style Green Tea)'},\n {value: '2008 Xiaguan Golden 8100', text: '2008 Xiaguan Golden 8100'},\n {value: 'Ruby Sipper', text: 'Ruby Sipper'},\n {value: 'Golden Blossom Chrysanthemum',\n text: 'Golden Blossom Chrysanthemum'},\n {value: 'Rooibos Chai Organic', text: 'Rooibos Chai Organic'},\n {value: 'Green Tea with Ginger and Turmeric',\n text: 'Green Tea with Ginger and Turmeric'},\n {value: 'Very Magic', text: 'Very Magic'},\n {value: 'Blueberry Hill', text: 'Blueberry Hill'},\n {value: 'Honeybush Chocolate', text: 'Honeybush Chocolate'},\n {value: 'Green Rooibos Key Largo', text: 'Green Rooibos Key Largo'},\n {value: 'China Yunnan Silver Tip Choice',\n text: 'China Yunnan Silver Tip Choice'},\n {value: 'Monkey Picked Tea Kwan Yin', text: 'Monkey Picked Tea Kwan Yin'},\n {value: 'Lichee Congou', text: 'Lichee Congou'},\n {value: 'Blueberry Afternoon', text: 'Blueberry Afternoon'},\n {value: '2011 Qi Lan Grade A Wuyi Mountain Oolong Tea',\n text: '2011 Qi Lan Grade A Wuyi Mountain Oolong Tea'},\n {value: 'Strawberry Champagne', text: 'Strawberry Champagne'},\n {value: 'Organically Grown Tea', text: 'Organically Grown Tea'},\n {value: 'Royal Tea', text: 'Royal Tea'},\n {value: 'Raspberry Champagne White', text: 'Raspberry Champagne White'},\n {value: 'Sunshine Green', text: 'Sunshine Green'},\n {value: 'Sencha Yuzu', text: 'Sencha Yuzu'},\n {value: 'Organic Greenfield Estate Ceylon Black Tea',\n text: 'Organic Greenfield Estate Ceylon Black Tea'},\n {value: 'Green Tea with Cherry', text: 'Green Tea with Cherry'},\n {value: 'Ceylon Sonata', text: 'Ceylon Sonata'},\n {value: '1999 Pu-erh Mini Tou cha', text: '1999 Pu-erh Mini Tou cha'},\n {value: 'Tarry Lapsang Souchong', text: 'Tarry Lapsang Souchong'},\n {value: 'Razzmatazz (organic)', text: 'Razzmatazz (organic)'},\n {value: 'Musta Keisarin Malja - Black Emperors Choice',\n text: 'Musta Keisarin Malja - Black Emperors Choice'},\n {value: 'Tiger Eye', text: 'Tiger Eye'},\n {value: 'Wild Brier with Rose of Sharon',\n text: 'Wild Brier with Rose of Sharon'},\n {value: 'pai mu tan', text: 'pai mu tan'},\n {value: '2005 Lincang Gu Shu Zhen Pin',\n text: '2005 Lincang Gu Shu Zhen Pin'},\n {value: 'Madagascar Vanilla Red', text: 'Madagascar Vanilla Red'},\n {value: 'Awake™ Full Leaf Tea', text: 'Awake™ Full Leaf Tea'},\n {value: 'Rani STGFOP 1st Flush 2010 Assam',\n text: 'Rani STGFOP 1st Flush 2010 Assam'},\n {value: 'jamaica red bush', text: 'jamaica red bush'},\n {value: 'Organic Qi Lan Oolong Tea', text: 'Organic Qi Lan Oolong Tea'},\n {value: 'Moonlight Beauty Raw Pu-erh Loose Tea',\n text: 'Moonlight Beauty Raw Pu-erh Loose Tea'},\n {value: 'Mid-90s Aged Feng Huang DanCong',\n text: 'Mid-90s Aged Feng Huang DanCong'},\n {value: 'Chocolate Covered Strawberry Tea',\n text: 'Chocolate Covered Strawberry Tea'},\n {value: 'Oktoberfest Blend', text: 'Oktoberfest Blend'},\n {value: 'Traditional Plum Pudding (Holiday Series: Yule)',\n text: 'Traditional Plum Pudding (Holiday Series: Yule)'},\n {value: 'Shalimar Oolong', text: 'Shalimar Oolong'},\n {value: 'Imperial Ceylon', text: 'Imperial Ceylon'},\n {value: 'Organic New World Mint', text: 'Organic New World Mint'},\n {value: '1886 Blend', text: '1886 Blend'},\n {value: 'Chai Bora Supreme', text: 'Chai Bora Supreme'},\n {value: 'Japanese Green Tea Powder CEREMONIAL GRADE MATCHA',\n text: 'Japanese Green Tea Powder CEREMONIAL GRADE MATCHA'},\n {value: 'organic green tea', text: 'organic green tea'},\n {value: 'Indian Market', text: 'Indian Market'},\n {value: 'Chocolate Monkey', text: 'Chocolate Monkey'},\n {value: 'Kamiya Papaya', text: 'Kamiya Papaya'},\n {value: 'Assam Gold', text: 'Assam Gold'},\n {value: 'Yunnan Wild Arbor Oriental Beauty Oolong',\n text: 'Yunnan Wild Arbor Oriental Beauty Oolong'},\n {value: '2006 Haiwan Purple Bud Sheng Puerh',\n text: '2006 Haiwan Purple Bud Sheng Puerh'},\n {value: 'Peachy Oolong Teabags', text: 'Peachy Oolong Teabags'},\n {value: 'Red Matcha', text: 'Red Matcha'},\n {value: 'Soba-Cha (Buckwheat Tea)', text: 'Soba-Cha (Buckwheat Tea)'},\n {value: 'Tankha', text: 'Tankha'},\n {value: 'Spring Huang Jin Gui', text: 'Spring Huang Jin Gui'},\n {value: 'Vanilla Orchid', text: 'Vanilla Orchid'},\n {value: 'Coconut Green', text: 'Coconut Green'},\n {value: '2008 Xiaguan FT Imperial Tribute Raw Pu-erh tea cake - 357 grams',\n text: '2008 Xiaguan FT Imperial Tribute Raw Pu-erh tea cake - 357 grams'},\n {value: 'Organic Misty Green', text: 'Organic Misty Green'},\n {value: 'Temple Stairs Loose Ripe Puer',\n text: 'Temple Stairs Loose Ripe Puer'},\n {value: 'Blueberry Bliss Rooibos', text: 'Blueberry Bliss Rooibos'},\n {value: 'Enchanted Rose', text: 'Enchanted Rose'},\n {value: 'Manhattan Earl Grey', text: 'Manhattan Earl Grey'},\n {value: 'Cherry Snowcone', text: 'Cherry Snowcone'},\n {value: 'Chrysanthemum Silver Needle',\n text: 'Chrysanthemum Silver Needle'},\n {value: 'Premium Green Tea (sample)', text: 'Premium Green Tea (sample)'},\n {value: 'Strawberry Matcha', text: 'Strawberry Matcha'},\n {value: 'Mellow Cream Oolong', text: 'Mellow Cream Oolong'},\n {value: 'Emperor’s Blend', text: 'Emperor’s Blend'},\n {value: 'Ceylon Cardamon', text: 'Ceylon Cardamon'},\n {value: 'Golden Snail [Out of Stock]',\n text: 'Golden Snail [Out of Stock]'},\n {value: 'Dragon Well Green Tea (Long Jing)',\n text: 'Dragon Well Green Tea (Long Jing)'},\n {value: 'Cafe Mocha', text: 'Cafe Mocha'},\n {value: 'White Matcha Organic', text: 'White Matcha Organic'},\n {value: 'Candied Almond', text: 'Candied Almond'},\n {value: 'Raspberry Vanilla', text: 'Raspberry Vanilla'},\n {value: 'Family Health Tea with Elderberries',\n text: 'Family Health Tea with Elderberries'},\n {value: 'Gong Fu Cha Wang (Tieguanyin)',\n text: 'Gong Fu Cha Wang (Tieguanyin)'},\n {value: 'Holy Basil Spa Blend', text: 'Holy Basil Spa Blend'},\n {value: 'Organic Lapsang Souchong', text: 'Organic Lapsang Souchong'},\n {value: 'Darjeeling Makaibari second flush - organic',\n text: 'Darjeeling Makaibari second flush - organic'},\n {value: 'Rose Earl Grey', text: 'Rose Earl Grey'},\n {value: 'Pumpkin Creme Brulee', text: 'Pumpkin Creme Brulee'},\n {value: 'Pink Lady Apple (Sip for the Cure)',\n text: 'Pink Lady Apple (Sip for the Cure)'},\n {value: 'Taiqing Temple Green', text: 'Taiqing Temple Green'},\n {value: 'Melon Citrus Mint Infusion', text: 'Melon Citrus Mint Infusion'},\n {value: '2011 Spring Medium Roast Premium Grade Tie Guan Yin Oolong Tea',\n text: '2011 Spring Medium Roast Premium Grade Tie Guan Yin Oolong Tea'},\n {value: 'Paris Morning', text: 'Paris Morning'},\n {value: 'Peanut Butter Cup Cheesecake Honeybush',\n text: 'Peanut Butter Cup Cheesecake Honeybush'},\n {value: 'Bolivian Whole Leaf Black Tea',\n text: 'Bolivian Whole Leaf Black Tea'},\n {value: 'Lavender Earl Grey Biodegradable Pyramid Sachets',\n text: 'Lavender Earl Grey Biodegradable Pyramid Sachets'},\n {value: 'Caramel Popcorn Matcha', text: 'Caramel Popcorn Matcha'},\n {value: 'Rooibos Tropic', text: 'Rooibos Tropic'},\n {value: 'Zen Chai', text: 'Zen Chai'},\n {value: 'Lao Man E 2012 Spring', text: 'Lao Man E 2012 Spring'},\n {value: 'Pleine Lune - Full Moon', text: 'Pleine Lune - Full Moon'},\n {value: 'Matcha Kirara Rice', text: 'Matcha Kirara Rice'},\n {value: 'Nectar Pu Erh', text: 'Nectar Pu Erh'},\n {value: 'Cherry Marzipan', text: 'Cherry Marzipan'},\n {value: 'Shin-cha Select - 2010 edition',\n text: 'Shin-cha Select - 2010 edition'},\n {value: 'iced green tea', text: 'iced green tea'},\n {value: '2007 Menghai Dayi Adorned in Red Ripe',\n text: '2007 Menghai Dayi Adorned in Red Ripe'},\n {value: 'Fabulous Feijoa', text: 'Fabulous Feijoa'},\n {value: 'Irish Morning Tea', text: 'Irish Morning Tea'},\n {value: 'Imperial Golden Monkey (ZP85)',\n text: 'Imperial Golden Monkey (ZP85)'},\n {value: 'Get Smart - No.16 (Wellness Collection)',\n text: 'Get Smart - No.16 (Wellness Collection)'},\n {value: 'Iron Goddess of Mercy (Tie Guanyin)',\n text: 'Iron Goddess of Mercy (Tie Guanyin)'},\n {value: 'Mandarin Jasmine Pearls', text: 'Mandarin Jasmine Pearls'},\n {value: 'Momoko Moon', text: 'Momoko Moon'},\n {value: 'Russian Caravan Original China Blend',\n text: 'Russian Caravan Original China Blend'},\n {value: 'Genmaicha Satsuki', text: 'Genmaicha Satsuki'},\n {value: 'Ayurvedic Passion', text: 'Ayurvedic Passion'},\n {value: 'Ceciliyan Estate FBOPF Ex. Spl.',\n text: 'Ceciliyan Estate FBOPF Ex. Spl.'},\n {value: 'Tomo Sencha', text: 'Tomo Sencha'},\n {value: 'Chá Vermelho Marco Polo', text: 'Chá Vermelho Marco Polo'},\n {value: 'Aloe Blossom Herbal Tea', text: 'Aloe Blossom Herbal Tea'},\n {value: 'Ché Xanh', text: 'Ché Xanh'},\n {value: 'Lovers Lane', text: 'Lovers Lane'},\n {value: 'Hawaii hand-made', text: 'Hawaii hand-made'},\n {value: 'Cranberry Blood Orange (Fair Trade Certified)',\n text: 'Cranberry Blood Orange (Fair Trade Certified)'},\n {value: 'Organic Merry Mint Green Tea',\n text: 'Organic Merry Mint Green Tea'},\n {value: 'Jasmine flower green tea', text: 'Jasmine flower green tea'},\n {value: 'Taiwan Bei-Pu Bai Hao', text: 'Taiwan Bei-Pu Bai Hao'},\n {value: 'Vanilla Red Tea (Rooibos)', text: 'Vanilla Red Tea (Rooibos)'},\n {value: 'Scent of the Night', text: 'Scent of the Night'},\n {value: 'Imperial Breakfast Blend', text: 'Imperial Breakfast Blend'},\n {value: 'RMS Titanic Tea Blend', text: 'RMS Titanic Tea Blend'},\n {value: 'Moulin Rouge Chai', text: 'Moulin Rouge Chai'},\n {value: 'Shanghai Rose', text: 'Shanghai Rose'},\n {value: 'Peach Jasmine Dragon Pearl Green Tea',\n text: 'Peach Jasmine Dragon Pearl Green Tea'},\n {value: 'Lapsang Souchong (ZS20)', text: 'Lapsang Souchong (ZS20)'},\n {value: 'Longyuanhao 2000 Big Leaf shu brick',\n text: 'Longyuanhao 2000 Big Leaf shu brick'},\n {value: 'Green Anji', text: 'Green Anji'},\n {value: 'Fuding Silver Needle Grand Cru Organic',\n text: 'Fuding Silver Needle Grand Cru Organic'},\n {value: '1990s Small Yellow Label', text: '1990s Small Yellow Label'},\n {value: 'Organic Zzz', text: 'Organic Zzz'},\n {value: '1995 Maokong Tie Guan Yin', text: '1995 Maokong Tie Guan Yin'},\n {value: 'Jasmine Pearl in a Shell - Blooming Tea',\n text: 'Jasmine Pearl in a Shell - Blooming Tea'},\n {value: 'Tropical Passion', text: 'Tropical Passion'},\n {value: 'Salada Black Tea', text: 'Salada Black Tea'},\n {value: 'Tea', text: 'Tea'},\n {value: 'Shade Grown Tie Guan Yin - 2011 Spring Anxi Oolong Tea',\n text: 'Shade Grown Tie Guan Yin - 2011 Spring Anxi Oolong Tea'},\n {value: 'Guayusa and Ginseng Oolong Tea',\n text: 'Guayusa and Ginseng Oolong Tea'},\n {value: 'Two Dragons and a Pearl Flower Tea',\n text: 'Two Dragons and a Pearl Flower Tea'},\n {value: 'Razmintazz', text: 'Razmintazz'},\n {value: 'Himalaya Chai', text: 'Himalaya Chai'},\n {value: 'Yunnan Premium Silver Thread Green Tea',\n text: 'Yunnan Premium Silver Thread Green Tea'},\n {value: 'Hot Cocoa', text: 'Hot Cocoa'},\n {value: 'Jing Mai Mountain Purple Needle Autumn 2015',\n text: 'Jing Mai Mountain Purple Needle Autumn 2015'},\n {value: '2002 Old Hongchang Pu-erh Tea Cake',\n text: '2002 Old Hongchang Pu-erh Tea Cake'},\n {value: 'Constant Comment Green', text: 'Constant Comment Green'},\n {value: 'Tension Tamer Extra Wellness Tea',\n text: 'Tension Tamer Extra Wellness Tea'},\n {value: 'Grönt te', text: 'Grönt te'},\n {value: 'Organic Fairtrade Mint Green',\n text: 'Organic Fairtrade Mint Green'},\n {value: 'Ceylon Organic Fair Trade', text: 'Ceylon Organic Fair Trade'},\n {value: 'English Teatime', text: 'English Teatime'},\n {value: 'Fantasy', text: 'Fantasy'},\n {value: 'Senacha', text: 'Senacha'},\n {value: 'Cinnamon Black', text: 'Cinnamon Black'},\n {value: 'Kaimosi Estate TGFOP1', text: 'Kaimosi Estate TGFOP1'},\n {value: 'Chai (Black Tea)', text: 'Chai (Black Tea)'},\n {value: 'Yunnan Bai Mu Dan White tea',\n text: 'Yunnan Bai Mu Dan White tea'},\n {value: 'Genmaicha (Pyramid Tea Bag)',\n text: 'Genmaicha (Pyramid Tea Bag)'},\n {value: 'Teguanyin Supreme (Anxi)', text: 'Teguanyin Supreme (Anxi)'},\n {value: 'Coonoor Nilgiri', text: 'Coonoor Nilgiri'},\n {value: 'Pu Erh Poe', text: 'Pu Erh Poe'},\n {value: 'Tie Guan Yin (Iron Buddha)', text: 'Tie Guan Yin (Iron Buddha)'},\n {value: 'Green Honeybush', text: 'Green Honeybush'},\n {value: '2012 Spring Harvest Imperial Green Oolong',\n text: '2012 Spring Harvest Imperial Green Oolong'},\n {value: 'Cerisier de Chine', text: 'Cerisier de Chine'},\n {value: 'Montagne Dong Ding', text: 'Montagne Dong Ding'},\n {value: 'Sweet Apple Chamomile', text: 'Sweet Apple Chamomile'},\n {value: 'Wild Arbor Buds', text: 'Wild Arbor Buds'},\n {value: 'wild forest oolong', text: 'wild forest oolong'},\n {value: 'Yellow Dragon', text: 'Yellow Dragon'},\n {value: 'Green Matcha', text: 'Green Matcha'},\n {value: 'Cherry Vanilla Chocolatte Red Tea',\n text: 'Cherry Vanilla Chocolatte Red Tea'},\n {value: 'Chocolate Mint Goji Black tea',\n text: 'Chocolate Mint Goji Black tea'},\n {value: 'Teas Tea Matcha', text: 'Teas Tea Matcha'},\n {value: 'Alishan 1500m Premium Oolong',\n text: 'Alishan 1500m Premium Oolong'},\n {value: 'All The Raj', text: 'All The Raj'},\n {value: 'Pumpkin Spice Latte Genmaicha',\n text: 'Pumpkin Spice Latte Genmaicha'},\n {value: 'Classic English Breakfast', text: 'Classic English Breakfast'},\n {value: 'Yunnan Feng Qing Imperial Dian Hong 2013 Early Spring Pluck',\n text: 'Yunnan Feng Qing Imperial Dian Hong 2013 Early Spring Pluck'},\n {value: 'Black Tea (Shu Puerh)', text: 'Black Tea (Shu Puerh)'},\n {value: 'Plum n Chunmee', text: 'Plum n Chunmee'},\n {value: 'Matsudas Sencha', text: 'Matsudas Sencha'},\n {value: 'Pink Sonoma', text: 'Pink Sonoma'},\n {value: 'Top Ti Quan Yin', text: 'Top Ti Quan Yin'},\n {value: 'Wild Cherry Black Tea', text: 'Wild Cherry Black Tea'},\n {value: 'Vanilla Apple Hibiscus', text: 'Vanilla Apple Hibiscus'},\n {value: 'Fruity Pebbles Slenderizer', text: 'Fruity Pebbles Slenderizer'},\n {value: 'New Vithanakande', text: 'New Vithanakande'},\n {value: 'Cherry Almond Genmaicha', text: 'Cherry Almond Genmaicha'},\n {value: 'Black Ginger', text: 'Black Ginger'},\n {value: 'Australian Breakfast', text: 'Australian Breakfast'},\n {value: 'Mountain Peak Silver Tip Tea',\n text: 'Mountain Peak Silver Tip Tea'},\n {value: 'Velvet', text: 'Velvet'},\n {value: 'Organic Dark Roast Yerba Mate Loose',\n text: 'Organic Dark Roast Yerba Mate Loose'},\n {value: 'Elderberry White Tea', text: 'Elderberry White Tea'},\n {value: 'East Friesian Broken Blend', text: 'East Friesian Broken Blend'},\n {value: 'Feisty Jade', text: 'Feisty Jade'},\n {value: 'Örtte', text: 'Örtte'},\n {value: 'Iron Goddess Monkey Picked', text: 'Iron Goddess Monkey Picked'},\n {value: 'Iron Buddha Oolong', text: 'Iron Buddha Oolong'},\n {value: 'Formosa Oolong Choicest (kräftig)',\n text: 'Formosa Oolong Choicest (kräftig)'},\n {value: 'China Gun Powder', text: 'China Gun Powder'},\n {value: 'Cloud Mist - Yunwu - Cloud Fog Tea',\n text: 'Cloud Mist - Yunwu - Cloud Fog Tea'},\n {value: 'Sijichun Taiwan Four Seasons Spring (Fruity) Oolong Tea',\n text: 'Sijichun Taiwan Four Seasons Spring (Fruity) Oolong Tea'},\n {value: 'Huangshan Maofeng-Mt.Yellow Downy Tip-Standard',\n text: 'Huangshan Maofeng-Mt.Yellow Downy Tip-Standard'},\n {value: '2002 Keyixing Ripen Pu-erh Tea Cake',\n text: '2002 Keyixing Ripen Pu-erh Tea Cake'},\n {value: '1980s Xiaguan Bamboo-wrapped Sheng Puerh Tuocha',\n text: '1980s Xiaguan Bamboo-wrapped Sheng Puerh Tuocha'},\n {value: 'Ba Xian Dan Cong', text: 'Ba Xian Dan Cong'},\n {value: 'Taimu Mountain Organic Bai Mu Dan White Tea',\n text: 'Taimu Mountain Organic Bai Mu Dan White Tea'},\n {value: 'Frontier Darjeeling', text: 'Frontier Darjeeling'},\n {value: 'Tibetan Brick Pu-erh 2002 250g High Grade',\n text: 'Tibetan Brick Pu-erh 2002 250g High Grade'},\n {value: 'Pu-erh Fitness', text: 'Pu-erh Fitness'},\n {value: 'Organic Cherry Sencha Green Tea',\n text: 'Organic Cherry Sencha Green Tea'},\n {value: 'Gingersnap Cookie Rooibos', text: 'Gingersnap Cookie Rooibos'},\n {value: 'Chamomile Ginger', text: 'Chamomile Ginger'},\n {value: 'citrus ginger', text: 'citrus ginger'},\n {value: 'Hot Cinnamon Sunset [Same as Hot Cinnamon Spice]',\n text: 'Hot Cinnamon Sunset [Same as Hot Cinnamon Spice]'},\n {value: 'French Vanilla Decaf', text: 'French Vanilla Decaf'},\n {value: '2006 Twin Elephants Tea Trail Commemorative Shu',\n text: '2006 Twin Elephants Tea Trail Commemorative Shu'},\n {value: 'Nova Scotia Blue', text: 'Nova Scotia Blue'},\n {value: 'Italienische Nespole', text: 'Italienische Nespole'},\n {value: 'Assam Rani FTGFOP1 Organic', text: 'Assam Rani FTGFOP1 Organic'},\n {value: 'Oo Nutty Delight', text: 'Oo Nutty Delight'},\n {value: 'Alpine Berry Herbal', text: 'Alpine Berry Herbal'},\n {value: 'Devonshire Tea', text: 'Devonshire Tea'},\n {value: 'Vanilla Bean Black Tea', text: 'Vanilla Bean Black Tea'},\n {value: 'Sour Wolf', text: 'Sour Wolf'},\n {value: 'Pu Er 1986 Yiwu', text: 'Pu Er 1986 Yiwu'},\n {value: 'Arabic Tea', text: 'Arabic Tea'},\n {value: 'Yunnan Gen Ben Shi', text: 'Yunnan Gen Ben Shi'},\n {value: 'Dream by the Fire', text: 'Dream by the Fire'},\n {value: 'Hot Apple Cider Tea', text: 'Hot Apple Cider Tea'},\n {value: 'Ginseng Energy Wellness Tea',\n text: 'Ginseng Energy Wellness Tea'},\n {value: 'Special Pina Colada Green', text: 'Special Pina Colada Green'},\n {value: '2006 Xiaguan Sheng / Raw Puerh Tuo Cha Humid Stored',\n text: '2006 Xiaguan Sheng / Raw Puerh Tuo Cha Humid Stored'},\n {value: 'Island Coconut Flavored Black Tea',\n text: 'Island Coconut Flavored Black Tea'},\n {value: 'Ginger and Lemon', text: 'Ginger and Lemon'},\n {value: 'Formosa Oolong Finest (OT01)',\n text: 'Formosa Oolong Finest (OT01)'},\n {value: 'Marrakesh Express Vanilla Spice',\n text: 'Marrakesh Express Vanilla Spice'},\n {value: 'Roasted Yerba Mate', text: 'Roasted Yerba Mate'},\n {value: 'Sleepytime Sinus Soother Wellness Tea',\n text: 'Sleepytime Sinus Soother Wellness Tea'},\n {value: 'Macha Green Tea', text: 'Macha Green Tea'},\n {value: 'Ceylon Vanilla', text: 'Ceylon Vanilla'},\n {value: 'Green Rooibos (Green Bush)', text: 'Green Rooibos (Green Bush)'},\n {value: 'Serenitea', text: 'Serenitea'},\n {value: 'Madagascar Vanilla Matcha', text: 'Madagascar Vanilla Matcha'},\n {value: 'Green Tea with Earl Grey', text: 'Green Tea with Earl Grey'},\n {value: 'Roasted Barley Tea', text: 'Roasted Barley Tea'},\n {value: 'Cherry Cheesecake Green Tea',\n text: 'Cherry Cheesecake Green Tea'},\n {value: 'Harmutty Gold Tips Assam', text: 'Harmutty Gold Tips Assam'},\n {value: 'Warwick Assam', text: 'Warwick Assam'},\n {value: 'Irish Morning', text: 'Irish Morning'},\n {value: 'Dragonwell (Organic)', text: 'Dragonwell (Organic)'},\n {value: 'Red Mellow Bush Rooibos', text: 'Red Mellow Bush Rooibos'},\n {value: 'Rose Marzipan Delight', text: 'Rose Marzipan Delight'},\n {value: 'Chai Town', text: 'Chai Town'},\n {value: 'Dong Ding Dark (Traditional)',\n text: 'Dong Ding Dark (Traditional)'},\n {value: 'Ginger Peach &amp; Apricot', text: 'Ginger Peach Apricot'},\n {value: 'Fuji The Ultimate', text: 'Fuji The Ultimate'},\n {value: 'Coconut Rush', text: 'Coconut Rush'},\n {value: 'Hibiscus Superflower Tea with Blueberry',\n text: 'Hibiscus Superflower Tea with Blueberry'},\n {value: 'Chocolate Chai Pu-Erh', text: 'Chocolate Chai Pu-Erh'},\n {value: 'Holiday Breakfast Blend', text: 'Holiday Breakfast Blend'},\n {value: 'Buttered Cranberry Orange Scone Honeybush',\n text: 'Buttered Cranberry Orange Scone Honeybush'},\n {value: 'Sencha Green Tea ...with milk honey and tapioca pearls',\n text: 'Sencha Green Tea ...with milk honey and tapioca pearls'},\n {value: 'Himalayan Blend', text: 'Himalayan Blend'},\n {value: 'Premium Kenyan Kericho', text: 'Premium Kenyan Kericho'},\n {value: 'Bonfire Blend', text: 'Bonfire Blend'},\n {value: 'Morning Mist - Organic', text: 'Morning Mist - Organic'},\n {value: 'Peaches &amp; Cream', text: 'Peaches &amp; Cream'},\n {value: 'Cococaramel Sea Salt Herbal Tea',\n text: 'Cococaramel Sea Salt Herbal Tea'},\n {value: 'Campfire Blend - v106 (2011-2013)',\n text: 'Campfire Blend - v106 (2011-2013)'},\n {value: 'Belgium Chocolate Matcha', text: 'Belgium Chocolate Matcha'},\n {value: 'Pu-erh Superior Grade', text: 'Pu-erh Superior Grade'},\n {value: 'Dark Goddess Oolong', text: 'Dark Goddess Oolong'},\n {value: 'Jiang Xi Tribute Tea', text: 'Jiang Xi Tribute Tea'},\n {value: 'Friendship Tea', text: 'Friendship Tea'},\n {value: 'Dark Obsession Chocolate Rose',\n text: 'Dark Obsession Chocolate Rose'},\n {value: '2014 Golden Spring Bud Dianhong',\n text: '2014 Golden Spring Bud Dianhong'},\n {value: 'OLD VERSION - Evergreen Spice',\n text: 'OLD VERSION - Evergreen Spice'},\n {value: 'Russian Evening No. 50', text: 'Russian Evening No. 50'},\n {value: 'Tanzania Black', text: 'Tanzania Black'},\n {value: 'Midsummers Peach (Decaf)', text: 'Midsummers Peach (Decaf)'},\n {value: 'Assam Panatola Estate', text: 'Assam Panatola Estate'},\n {value: 'Geishas Kiss', text: 'Geishas Kiss'},\n {value: 'A Citrus Twist Moroccan Mint',\n text: 'A Citrus Twist Moroccan Mint'},\n {value: 'Female Toner', text: 'Female Toner'},\n {value: 'Organic Hojicha', text: 'Organic Hojicha'},\n {value: 'Chocolate and Cream', text: 'Chocolate and Cream'},\n {value: 'Nan Nuo Mountain Sheng Pu Er - 2007',\n text: 'Nan Nuo Mountain Sheng Pu Er - 2007'},\n {value: 'Kabusecha', text: 'Kabusecha'},\n {value: 'India Assam Black Tea - BOP CTC',\n text: 'India Assam Black Tea - BOP CTC'},\n {value: 'Three Lemon Green (organic)',\n text: 'Three Lemon Green (organic)'},\n {value: 'Scottich Caramel', text: 'Scottich Caramel'},\n {value: 'English Breakfast Blend', text: 'English Breakfast Blend'},\n {value: 'Stampede Breakfast', text: 'Stampede Breakfast'},\n {value: 'Ceylon Yalt', text: 'Ceylon Yalt'},\n {value: 'Damanzhong Baihao Oolong', text: 'Damanzhong Baihao Oolong'},\n {value: 'Guangdong Province Jasmine Pearls ZJ85',\n text: 'Guangdong Province Jasmine Pearls ZJ85'},\n {value: 'Organic Westlake Long Jing 2012',\n text: 'Organic Westlake Long Jing 2012'},\n {value: 'Green Tea Mate', text: 'Green Tea Mate'},\n {value: 'Snowfields', text: 'Snowfields'},\n {value: 'Kenya', text: 'Kenya'},\n {value: '2011 Spring Old Tree Yue Guan Bai (White Moon Light ) Jinggu Tea',\n text: '2011 Spring Old Tree Yue Guan Bai (White Moon Light ) Jinggu Tea'},\n {value: 'Monkey Picked', text: 'Monkey Picked'},\n {value: '2008 Yi Wu Mountain Bamboo Roasted Pu-erh',\n text: '2008 Yi Wu Mountain Bamboo Roasted Pu-erh'},\n {value: 'Da Yu Ling High Mountain Oolong',\n text: 'Da Yu Ling High Mountain Oolong'},\n {value: 'Winter Dream Sencha', text: 'Winter Dream Sencha'},\n {value: 'Chocolate Truffle', text: 'Chocolate Truffle'},\n {value: 'Earl Greyer (Organic)', text: 'Earl Greyer (Organic)'},\n {value: 'Bao Zhong High Grade - Pouchong',\n text: 'Bao Zhong High Grade - Pouchong'},\n {value: 'Castleton In-Between Darjeeling FTGFOP1',\n text: 'Castleton In-Between Darjeeling FTGFOP1'},\n {value: 'Comfort and Joy', text: 'Comfort and Joy'},\n {value: 'Lemon Zinger', text: 'Lemon Zinger'},\n {value: 'Dong Ding Oolong traditional medium roast Competition Grade IV',\n text: 'Dong Ding Oolong traditional medium roast Competition Grade IV'},\n {value: 'The Iron Goddess', text: 'The Iron Goddess'},\n {value: 'Gingerbread Spice Tea', text: 'Gingerbread Spice Tea'},\n {value: 'Ligripookrie Estate BPS Assam',\n text: 'Ligripookrie Estate BPS Assam'},\n {value: 'Irish Breakfast Biodegradable Pyramid Sachets',\n text: 'Irish Breakfast Biodegradable Pyramid Sachets'},\n {value: 'Da Yeh Summer 2011', text: 'Da Yeh Summer 2011'},\n {value: 'Black Needles', text: 'Black Needles'},\n {value: 'Feng Huang Dan Cong Li Jai Ping Lao Cong',\n text: 'Feng Huang Dan Cong Li Jai Ping Lao Cong'},\n {value: 'Just Rose', text: 'Just Rose'},\n {value: 'Uji Asamushi Sencha Aoi', text: 'Uji Asamushi Sencha Aoi'},\n {value: 'Special Himalayan Organic Herbal Tulsi',\n text: 'Special Himalayan Organic Herbal Tulsi'},\n {value: 'Wild Purple Chrysanthemum flower tea',\n text: 'Wild Purple Chrysanthemum flower tea'},\n {value: 'Coconut Cream', text: 'Coconut Cream'},\n {value: 'Zi Mu Dan', text: 'Zi Mu Dan'},\n {value: 'Mandala Tea 2011 Wild Mountain Green Raw Puer',\n text: 'Mandala Tea 2011 Wild Mountain Green Raw Puer'},\n {value: 'Ancient Pu-erh Palace', text: 'Ancient Pu-erh Palace'},\n {value: 'Assam Malty Broken Mens Tea',\n text: 'Assam Malty Broken Mens Tea'},\n {value: 'Superior Ti Kuan Yin (Iron Goddess)',\n text: 'Superior Ti Kuan Yin (Iron Goddess)'},\n {value: 'Dark Chocolate Tea', text: 'Dark Chocolate Tea'},\n {value: 'Premium Anxi Huang Jin Gui Oolong Tea of Fujian * 2010 Autumn',\n text: 'Premium Anxi Huang Jin Gui Oolong Tea of Fujian * 2010 Autumn'},\n {value: 'China Special White Point Reserve (ZW90)',\n text: 'China Special White Point Reserve (ZW90)'},\n {value: 'Amethyst', text: 'Amethyst'},\n {value: 'Pineapple Ginger', text: 'Pineapple Ginger'},\n {value: 'Honey Green', text: 'Honey Green'},\n {value: 'Immortal Springs Laoshan White',\n text: 'Immortal Springs Laoshan White'},\n {value: 'Earl Grey with Rose Petals', text: 'Earl Grey with Rose Petals'},\n {value: 'ginger peach black full leaf',\n text: 'ginger peach black full leaf'},\n {value: 'jamaica redbush', text: 'jamaica redbush'},\n {value: 'Curled Dragon Silver Tips', text: 'Curled Dragon Silver Tips'},\n {value: 'Coconut Mate Masala Chai', text: 'Coconut Mate Masala Chai'},\n {value: 'Chamomile Citron', text: 'Chamomile Citron'},\n {value: 'peppermint rose white', text: 'peppermint rose white'},\n {value: 'Leaf Tea (Loose Leaf)', text: 'Leaf Tea (Loose Leaf)'},\n {value: 'Tsuei Luan Oolong Tea', text: 'Tsuei Luan Oolong Tea'},\n {value: 'No.25 Single Origin Darjeeling',\n text: 'No.25 Single Origin Darjeeling'},\n {value: 'GABA Oolong', text: 'GABA Oolong'},\n {value: 'Organic Apricot Ginger Black Tea',\n text: 'Organic Apricot Ginger Black Tea'},\n {value: 'Xi Hu Lung Ching', text: 'Xi Hu Lung Ching'},\n {value: 'Somerset Estate', text: 'Somerset Estate'},\n {value: 'Bonne Nuit', text: 'Bonne Nuit'},\n {value: 'White Peony (Pai Mu Tan) Organic China 557',\n text: 'White Peony (Pai Mu Tan) Organic China 557'},\n {value: 'China Jasmine Tea', text: 'China Jasmine Tea'},\n {value: 'Yogitea', text: 'Yogitea'},\n {value: 'Organic Gensis', text: 'Organic Gensis'},\n {value: 'Organic Green Dragon', text: 'Organic Green Dragon'},\n {value: 'Assam SFTGFOP1 Mokalbari (Second Flush)',\n text: 'Assam SFTGFOP1 Mokalbari (Second Flush)'},\n {value: 'Harvest', text: 'Harvest'},\n {value: 'M.T.W. Formosa Keemun', text: 'M.T.W. Formosa Keemun'},\n {value: 'Roasted Oolong (ZO20)', text: 'Roasted Oolong (ZO20)'},\n {value: 'Ma-Chai', text: 'Ma-Chai'},\n {value: 'Razzleberry Green', text: 'Razzleberry Green'},\n {value: 'Laguna Blend', text: 'Laguna Blend'},\n {value: 'Trail Mix Black Tea', text: 'Trail Mix Black Tea'},\n {value: 'YMY 1690 Chrysanthemum Pu-erh',\n text: 'YMY 1690 Chrysanthemum Pu-erh'},\n {value: 'Great Red Robe', text: 'Great Red Robe'},\n {value: 'Forever Nuts', text: 'Forever Nuts'},\n {value: 'Rose Chai', text: 'Rose Chai'},\n {value: 'Hint of Mint Herbal Tea', text: 'Hint of Mint Herbal Tea'},\n {value: 'Green Tea With Echinacea', text: 'Green Tea With Echinacea'},\n {value: 'Honeybush Organic', text: 'Honeybush Organic'},\n {value: 'Oi Ocha Dark', text: 'Oi Ocha Dark'},\n {value: 'Peacock Village 2004 Shu', text: 'Peacock Village 2004 Shu'},\n {value: 'Spicy Peach', text: 'Spicy Peach'},\n {value: 'Shui Hsien China Oolong Tea',\n text: 'Shui Hsien China Oolong Tea'},\n {value: 'Blueberry Green Tea', text: 'Blueberry Green Tea'},\n {value: 'Almond Cookies', text: 'Almond Cookies'},\n {value: 'Ghillidary Assam CTC Second Flush',\n text: 'Ghillidary Assam CTC Second Flush'},\n {value: 'darjeeling BPS', text: 'darjeeling BPS'},\n {value: 'Lu An Gua Pian', text: 'Lu An Gua Pian'},\n {value: 'Buckingham Palace', text: 'Buckingham Palace'},\n {value: 'PC Mulled Apple Herbal Tea', text: 'PC Mulled Apple Herbal Tea'},\n {value: 'Eight at the Fort', text: 'Eight at the Fort'},\n {value: 'Spiced Apple Chai', text: 'Spiced Apple Chai'},\n {value: 'Giddapahar Darjeeling Extra Special',\n text: 'Giddapahar Darjeeling Extra Special'},\n {value: 'Original Spice Tea', text: 'Original Spice Tea'},\n {value: 'Organic Huang Xiao Ya (Yellow Tea)',\n text: 'Organic Huang Xiao Ya (Yellow Tea)'},\n {value: 'Republic Chai', text: 'Republic Chai'},\n {value: 'Morrocan Mint Green Tea', text: 'Morrocan Mint Green Tea'},\n {value: 'Pumpkin Toffee Dragonwell', text: 'Pumpkin Toffee Dragonwell'},\n {value: 'Iron Goddess', text: 'Iron Goddess'},\n {value: 'Royal Garland', text: 'Royal Garland'},\n {value: 'Peach Ginger', text: 'Peach Ginger'},\n {value: 'Night Rose', text: 'Night Rose'},\n {value: 'Rum Vanilla', text: 'Rum Vanilla'},\n {value: 'Red Raspberry Leaf', text: 'Red Raspberry Leaf'},\n {value: 'Fragant Jade Oolong', text: 'Fragant Jade Oolong'},\n {value: 'Chai Spice', text: 'Chai Spice'},\n {value: 'Romanoff', text: 'Romanoff'},\n {value: 'Jamaica Blend Rooibos', text: 'Jamaica Blend Rooibos'},\n {value: 'Japan Genmaicha', text: 'Japan Genmaicha'},\n {value: 'Assam Tea', text: 'Assam Tea'},\n {value: 'Organic Peach Apricot Essence',\n text: 'Organic Peach Apricot Essence'},\n {value: 'Peach Brulée', text: 'Peach Brulée'},\n {value: 'Nepal Jun Chiyaburi (Finest Hand Rolled)',\n text: 'Nepal Jun Chiyaburi (Finest Hand Rolled)'},\n {value: 'Fukamushi Sencha Superior', text: 'Fukamushi Sencha Superior'},\n {value: 'Cinnamon Apple Organic Tea', text: 'Cinnamon Apple Organic Tea'},\n {value: 'Taiping Houkui', text: 'Taiping Houkui'},\n {value: 'Earl Grey with Lavender', text: 'Earl Grey with Lavender'},\n {value: 'Peach and Passionfruit', text: 'Peach and Passionfruit'},\n {value: 'Sencha Shin Ryoku', text: 'Sencha Shin Ryoku'},\n {value: 'Crimson Horizon', text: 'Crimson Horizon'},\n {value: 'Rooibush Ginger', text: 'Rooibush Ginger'},\n {value: 'Da Hong Pao Scarlet Robe', text: 'Da Hong Pao Scarlet Robe'},\n {value: 'Tong Tian Xiang Phoenix Mountain Dancong',\n text: 'Tong Tian Xiang Phoenix Mountain Dancong'},\n {value: 'No. 45 The White Wolf', text: 'No. 45 The White Wolf'},\n {value: 'Osthmanthus Green Tea', text: 'Osthmanthus Green Tea'},\n {value: 'Mint Green Tea (Decaf)', text: 'Mint Green Tea (Decaf)'},\n {value: 'Special B', text: 'Special B'},\n {value: 'Toffee Almond Supreme', text: 'Toffee Almond Supreme'},\n {value: 'Slightly Sweet Original Chai Tea Latte Concentrate',\n text: 'Slightly Sweet Original Chai Tea Latte Concentrate'},\n {value: 'celestial seasonings sleepytime Sinus Soother',\n text: 'celestial seasonings sleepytime Sinus Soother'},\n {value: 'Menghai Puer', text: 'Menghai Puer'},\n {value: 'Shincha Kunpu', text: 'Shincha Kunpu'},\n {value: 'Jasmine Chung Hao', text: 'Jasmine Chung Hao'},\n {value: 'Halmari Estate Assam FTGFOP',\n text: 'Halmari Estate Assam FTGFOP'},\n {value: 'Strawberry Pomegranate Red', text: 'Strawberry Pomegranate Red'},\n {value: 'Spring White Pearls (organic)',\n text: 'Spring White Pearls (organic)'},\n {value: 'China Fine Lung Ching Organic (No. 523)',\n text: 'China Fine Lung Ching Organic (No. 523)'},\n {value: 'Oolong Black Tea', text: 'Oolong Black Tea'},\n {value: 'Extra Bergamot Earl Grey', text: 'Extra Bergamot Earl Grey'},\n {value: 'Kochakaden Royal Milk Tea', text: 'Kochakaden Royal Milk Tea'},\n {value: 'Sweet Fruit Garden and Scarlet Cloud Blend',\n text: 'Sweet Fruit Garden and Scarlet Cloud Blend'},\n {value: 'Héritage Gourmand - Mousse au Chocolat',\n text: 'Héritage Gourmand - Mousse au Chocolat'},\n {value: 'Orchid Oolong (organic)', text: 'Orchid Oolong (organic)'},\n {value: 'Ancient Emerald Lily', text: 'Ancient Emerald Lily'},\n {value: 'Himalayan Majestic', text: 'Himalayan Majestic'},\n {value: 'amazonia 12', text: 'amazonia 12'},\n {value: 'Rooibos Yerba Mate', text: 'Rooibos Yerba Mate'},\n {value: 'Chaman Chai', text: 'Chaman Chai'},\n {value: 'Green Tea Rose Jasmine', text: 'Green Tea Rose Jasmine'},\n {value: 'Springtime Jubilee', text: 'Springtime Jubilee'},\n {value: 'Silver Needles', text: 'Silver Needles'},\n {value: '2012 Spring Imperial Jiang Hua Xiang(Ginger Flower/Tong Tian Xiang) Phoenix Dancong Oolong',\n text: '2012 Jiang Hua Xiang(Ginger Flower/Tong Tian Xiang) Oolong'},\n {value: 'Earl Grey Grand Classic', text: 'Earl Grey Grand Classic'},\n {value: 'Vanilla Almond Oolong', text: 'Vanilla Almond Oolong'},\n {value: 'Montana Gold', text: 'Montana Gold'},\n {value: 'Amber Oolong', text: 'Amber Oolong'},\n {value: 'South Indian Chai', text: 'South Indian Chai'},\n {value: 'Sticky Rice Puerh', text: 'Sticky Rice Puerh'},\n {value: 'Passion Blend', text: 'Passion Blend'},\n {value: 'Echinacea Immune Support', text: 'Echinacea Immune Support'},\n {value: '2007 Shu Puerh loose tea', text: '2007 Shu Puerh loose tea'},\n {value: 'Yuzu Oolong', text: 'Yuzu Oolong'},\n {value: 'Bai Lin Congfu', text: 'Bai Lin Congfu'},\n {value: 'Organic Camomile Blend', text: 'Organic Camomile Blend'},\n {value: 'Bengal Breakfast', text: 'Bengal Breakfast'},\n {value: 'Vienna Winter Green', text: 'Vienna Winter Green'},\n {value: 'Eggnoggn Tea', text: 'Eggnoggn Tea'},\n {value: 'Early Spring 2014 Sun-Dried Buds Wild Pu-erh tea varietal',\n text: 'Early Spring 2014 Sun-Dried Buds Wild Pu-erh tea varietal'},\n {value: 'Lavender Dream - Lavender Hibiscus White Tea',\n text: 'Lavender Dream - Lavender Hibiscus White Tea'},\n {value: 'Chamana Amarillo', text: 'Chamana Amarillo'},\n {value: 'DJ Darjeeling Tea Mim First Flush 2012 ( Clonal )',\n text: 'DJ Darjeeling Tea Mim First Flush 2012 ( Clonal )'},\n {value: 'Darjeeling FTGFOP', text: 'Darjeeling FTGFOP'},\n {value: 'Chilli Chai', text: 'Chilli Chai'},\n {value: 'Mélange de Galice', text: 'Mélange de Galice'},\n {value: 'Rose Black', text: 'Rose Black'},\n {value: 'Organic Purple Bud', text: 'Organic Purple Bud'},\n {value: 'Sun Moon Lake Black Tea - Ruby',\n text: 'Sun Moon Lake Black Tea - Ruby'},\n {value: '2009 Yunnan Feng Qing Dian Hong Wai Shi Li Cha',\n text: '2009 Yunnan Feng Qing Dian Hong Wai Shi Li Cha'},\n {value: '551 China Silver Needle White Tea',\n text: '551 China Silver Needle White Tea'},\n {value: 'Gyokuro Asahina Extra Fine', text: 'Gyokuro Asahina Extra Fine'},\n {value: 'Yunnan Golden Bud', text: 'Yunnan Golden Bud'},\n {value: 'Papaya Mango - Tropical Red Tea',\n text: 'Papaya Mango - Tropical Red Tea'},\n {value: 'Yin Jing Gu 2004', text: 'Yin Jing Gu 2004'},\n {value: 'Sallys Secret', text: 'Sallys Secret'},\n {value: 'KINARI (Shincha 09)', text: 'KINARI (Shincha 09)'},\n {value: 'Silver Buds Yabao', text: 'Silver Buds Yabao'},\n {value: 'Clari Tea', text: 'Clari Tea'},\n {value: 'Organic Red Rooibos', text: 'Organic Red Rooibos'},\n {value: 'Aracha Takusen', text: 'Aracha Takusen'},\n {value: 'Licorice Twist', text: 'Licorice Twist'},\n {value: 'Zi Cha / Purple Tea (Raw 2012)',\n text: 'Zi Cha / Purple Tea (Raw 2012)'},\n {value: 'Jasmine Pearls (Gold Medal Winner)',\n text: 'Jasmine Pearls (Gold Medal Winner)'},\n {value: 'Yellow Mountain Mao Feng B', text: 'Yellow Mountain Mao Feng B'},\n {value: 'Himalayan Gold', text: 'Himalayan Gold'},\n {value: 'Topaz Pu-er', text: 'Topaz Pu-er'},\n {value: 'Organic Kumamoto Yabe Supreme (Shincha 09)',\n text: 'Organic Kumamoto Yabe Supreme (Shincha 09)'},\n {value: 'Earl Black', text: 'Earl Black'},\n {value: 'Japan Matcha Hikari (powdered)',\n text: 'Japan Matcha Hikari (powdered)'},\n {value: 'Mrs. Dus Green Puerh', text: 'Mrs. Dus Green Puerh'},\n {value: 'Grand Earl Grey', text: 'Grand Earl Grey'},\n {value: 'Midnight Magic', text: 'Midnight Magic'},\n {value: 'Royal Wedding', text: 'Royal Wedding'},\n {value: 'Earl Grey Leaf Tea', text: 'Earl Grey Leaf Tea'},\n {value: 'Pitta Ayurvedic', text: 'Pitta Ayurvedic'},\n {value: 'Traditional Shui Xian', text: 'Traditional Shui Xian'},\n {value: 'Zhu Ye Qing', text: 'Zhu Ye Qing'},\n {value: 'Cranberry Matcha', text: 'Cranberry Matcha'},\n {value: 'Meyer Lemon Cream', text: 'Meyer Lemon Cream'},\n {value: 'Caramel &amp; Rum', text: 'Caramel &amp; Rum'},\n {value: 'Lemon Thriller', text: 'Lemon Thriller'},\n {value: 'Heavenly Blue Summit (Tian Mu Qing Ding)',\n text: 'Heavenly Blue Summit (Tian Mu Qing Ding)'},\n {value: 'Valkoinen Elefantti - White Elephant',\n text: 'Valkoinen Elefantti - White Elephant'},\n {value: 'Royal Wedding Commemorative Tea',\n text: 'Royal Wedding Commemorative Tea'},\n {value: 'Gaoshan Jinxuan Taiwan 12 Alishan Jin Xuan Oolong Tea',\n text: 'Gaoshan Jinxuan Taiwan 12 Alishan Jin Xuan Oolong Tea'},\n {value: 'Puer Tuo Cha', text: 'Puer Tuo Cha'},\n {value: 'Tangier Apricot', text: 'Tangier Apricot'},\n {value: 'Blue Moon Tea', text: 'Blue Moon Tea'},\n {value: 'Paul &amp; Virginie', text: 'Paul &amp; Virginie'},\n {value: 'Narcisse', text: 'Narcisse'},\n {value: '2009 original ecological Jasmine xiangzhu green tea',\n text: '2009 original ecological Jasmine xiangzhu green tea'},\n {value: 'Chamong FTGFOP1 Autumnal Black Tea',\n text: 'Chamong FTGFOP1 Autumnal Black Tea'},\n {value: 'Licorice Lemongrass Peppermint',\n text: 'Licorice Lemongrass Peppermint'},\n {value: 'Home Store Pu-Erh (2004)', text: 'Home Store Pu-Erh (2004)'},\n {value: 'Japan Sencha Hiki First Flush',\n text: 'Japan Sencha Hiki First Flush'},\n {value: 'Puttabong Estate SFTGFOP1 Ch Musc Second Flush (DJ-311)',\n text: 'Puttabong Estate SFTGFOP1 Ch Musc Second Flush (DJ-311)'},\n {value: '2008 Hai Lang Hao Star of Bu Lang',\n text: '2008 Hai Lang Hao Star of Bu Lang'},\n {value: '2001 Menghai Factory “Lu Yin” 7572 Recipe Ripe Bingcha',\n text: '2001 Menghai Factory “Lu Yin” 7572 Recipe Ripe Bingcha'},\n {value: 'Markesh Mint', text: 'Markesh Mint'},\n {value: 'Earl Grey Ceylon Select (TE17)',\n text: 'Earl Grey Ceylon Select (TE17)'},\n {value: 'Phoenix Honey Orchid Oolong Tea',\n text: 'Phoenix Honey Orchid Oolong Tea'},\n {value: 'Apple Cinnamon Herb Tea', text: 'Apple Cinnamon Herb Tea'},\n {value: 'Gunpowder Green Tea (Zhu Cha)',\n text: 'Gunpowder Green Tea (Zhu Cha)'},\n {value: 'Green Tea Hysson', text: 'Green Tea Hysson'},\n {value: '2015 Moonlight Sonata', text: '2015 Moonlight Sonata'},\n {value: 'Anti-Cyclone', text: 'Anti-Cyclone'},\n {value: 'Bengal Chai', text: 'Bengal Chai'},\n {value: 'Honey Green Almond', text: 'Honey Green Almond'},\n {value: 'Green Needle', text: 'Green Needle'},\n {value: 'Li Li Xian Guan Yin', text: 'Li Li Xian Guan Yin'},\n {value: 'Milk Caramel', text: 'Milk Caramel'},\n {value: 'Chocolate Mint Maté', text: 'Chocolate Mint Maté'},\n {value: 'Mighty Pomegranate', text: 'Mighty Pomegranate'},\n {value: 'Nepalese Afternoon Tea', text: 'Nepalese Afternoon Tea'},\n {value: 'Organic Chinese Sencha', text: 'Organic Chinese Sencha'},\n {value: 'Decaf Paris', text: 'Decaf Paris'},\n {value: 'Wheatgrass Matcha', text: 'Wheatgrass Matcha'},\n {value: 'Forest Fruits', text: 'Forest Fruits'},\n {value: 'Čarobni čaj keltske svećenice',\n text: 'Čarobni čaj keltske svećenice'},\n {value: 'No. 49 Assam FTGFOP1', text: 'No. 49 Assam FTGFOP1'},\n {value: 'Supreme Jasmine Slim Green Tea',\n text: 'Supreme Jasmine Slim Green Tea'},\n {value: 'Special Green', text: 'Special Green'},\n {value: 'Imperial Gold Bud Dian Hong',\n text: 'Imperial Gold Bud Dian Hong'},\n {value: 'White Peony (Bai MuDan) Tea',\n text: 'White Peony (Bai MuDan) Tea'},\n {value: 'Dark Chocolate Orange', text: 'Dark Chocolate Orange'},\n {value: 'GenMatcha', text: 'GenMatcha'},\n {value: 'Blood Orange Puerh', text: 'Blood Orange Puerh'},\n {value: 'Yunnan Golden Tip Imperial (ZY77)',\n text: 'Yunnan Golden Tip Imperial (ZY77)'},\n {value: 'Tourbillon', text: 'Tourbillon'},\n {value: 'Schnozberry', text: 'Schnozberry'},\n {value: 'French Lemon Ginger', text: 'French Lemon Ginger'},\n {value: 'Organic Nighty Night', text: 'Organic Nighty Night'},\n {value: 'Immortal Green', text: 'Immortal Green'},\n {value: 'darjeeling double malt', text: 'darjeeling double malt'},\n {value: 'Blue Sky', text: 'Blue Sky'},\n {value: 'Orange Mint Mate', text: 'Orange Mint Mate'},\n {value: 'Organic Chai Concentrate', text: 'Organic Chai Concentrate'},\n {value: 'First Flush Darjeeling', text: 'First Flush Darjeeling'},\n {value: 'Premium Chai', text: 'Premium Chai'},\n {value: 'Decadence', text: 'Decadence'},\n {value: 'Banana', text: 'Banana'},\n {value: 'Sikkim FTGFOP-1 Temi', text: 'Sikkim FTGFOP-1 Temi'},\n {value: 'Ceylon Gunpowder (Formerly called Royal Pavillion)',\n text: 'Ceylon Gunpowder (Formerly called Royal Pavillion)'},\n {value: 'Wild Rose Bai Mudan', text: 'Wild Rose Bai Mudan'},\n {value: 'Cinnamon Stonefruit', text: 'Cinnamon Stonefruit'},\n {value: 'Icewine Black Tea', text: 'Icewine Black Tea'},\n {value: 'Certified Organic Earl Grey',\n text: 'Certified Organic Earl Grey'},\n {value: 'Orange Cookie', text: 'Orange Cookie'},\n {value: '2003 Man Zhuan (Yiwu) Wild Tree',\n text: '2003 Man Zhuan (Yiwu) Wild Tree'},\n {value: 'Kenyan', text: 'Kenyan'},\n {value: 'Cucumber White', text: 'Cucumber White'},\n {value: 'Organic Vanilla Tea', text: 'Organic Vanilla Tea'},\n {value: 'North Winds', text: 'North Winds'},\n {value: 'Paris-Singapore', text: 'Paris-Singapore'},\n {value: 'Hawaii-Grown Oolong', text: 'Hawaii-Grown Oolong'},\n {value: 'Sweet Lime Green Tea', text: 'Sweet Lime Green Tea'},\n {value: 'Chocolate Aire', text: 'Chocolate Aire'},\n {value: 'Teh Melati', text: 'Teh Melati'},\n {value: 'Superior Earl Grey', text: 'Superior Earl Grey'},\n {value: 'Mellow Moments', text: 'Mellow Moments'},\n {value: 'Green Mate Fiesta', text: 'Green Mate Fiesta'},\n {value: 'Fine Matcha Green Tea Powder',\n text: 'Fine Matcha Green Tea Powder'},\n {value: 'Tea Bank FBOPF Ex. Spl. (TC34)',\n text: 'Tea Bank FBOPF Ex. Spl. (TC34)'},\n {value: 'Assam Kopili Estate Green Organic',\n text: 'Assam Kopili Estate Green Organic'},\n {value: 'Keemun Golden Buds', text: 'Keemun Golden Buds'},\n {value: 'Hand-picked Pouchong', text: 'Hand-picked Pouchong'},\n {value: 'Coffee Oolong', text: 'Coffee Oolong'},\n {value: 'Bourbon Sunday Blend', text: 'Bourbon Sunday Blend'},\n {value: 'Jin Shan', text: 'Jin Shan'},\n {value: 'Bien Etre', text: 'Bien Etre'},\n {value: 'TE13: Chocolate Earl Grey', text: 'TE13: Chocolate Earl Grey'},\n {value: 'Organic Kagoshima Oolong', text: 'Organic Kagoshima Oolong'},\n {value: 'Chai of Sri Lanka', text: 'Chai of Sri Lanka'},\n {value: 'Tea Jasmine Green', text: 'Tea Jasmine Green'},\n {value: 'Light Roast Da Hong Pao', text: 'Light Roast Da Hong Pao'},\n {value: 'decaf ceylon', text: 'decaf ceylon'},\n {value: 'Dokudami Umami Herbal Tea', text: 'Dokudami Umami Herbal Tea'},\n {value: 'Tanzania Livingstonia Estate',\n text: 'Tanzania Livingstonia Estate'},\n {value: 'Nilgiri Thiashola TGFOP (organic) (BI05)',\n text: 'Nilgiri Thiashola TGFOP (organic) (BI05)'},\n {value: 'Organic Green Tea with Pomegranate and Acai',\n text: 'Organic Green Tea with Pomegranate and Acai'},\n {value: 'Almost Nutella', text: 'Almost Nutella'},\n {value: 'Unsweetened Iced Tea', text: 'Unsweetened Iced Tea'},\n {value: 'Pot of Borengajuli this morning Nice &amp; brisk',\n text: 'Pot of Borengajuli this morning Nice &amp; brisk'},\n {value: 'Plumberry Black', text: 'Plumberry Black'},\n {value: 'Blueberry Bang Rooibos', text: 'Blueberry Bang Rooibos'},\n {value: 'Superberry (organic)', text: 'Superberry (organic)'},\n {value: 'Jin Xuan', text: 'Jin Xuan'},\n {value: 'Irish Breakfast - Extra Fancy',\n text: 'Irish Breakfast - Extra Fancy'},\n {value: 'Egyptian Mint Green Tea', text: 'Egyptian Mint Green Tea'},\n {value: 'Jin Xuan Spring 2010 Taiwan Green Tea',\n text: 'Jin Xuan Spring 2010 Taiwan Green Tea'},\n {value: 'White Peony (Pai Mu Tan)', text: 'White Peony (Pai Mu Tan)'},\n {value: 'China Moon Palace - Chun Mee',\n text: 'China Moon Palace - Chun Mee'},\n {value: 'Ripened Chrysanthemum Pu-erh Mini Tuocha',\n text: 'Ripened Chrysanthemum Pu-erh Mini Tuocha'},\n {value: 'Gunpowder (organic)', text: 'Gunpowder (organic)'},\n {value: 'Winterberry Wine', text: 'Winterberry Wine'},\n {value: 'Oriental Beauty (Dong Fang Mei Ren)',\n text: 'Oriental Beauty (Dong Fang Mei Ren)'},\n {value: 'Japanese Treasures', text: 'Japanese Treasures'},\n {value: 'Maloon FTGFOP', text: 'Maloon FTGFOP'},\n {value: 'wu liang mountain wild arbor raw pu-erh tea cake',\n text: 'wu liang mountain wild arbor raw pu-erh tea cake'},\n {value: 'Cold Brew', text: 'Cold Brew'},\n {value: 'Yunnan Black Gold Bi Luo Chun Spring 2010 Yunnan Black tea',\n text: 'Yunnan Black Gold Bi Luo Chun Spring 2010 Yunnan Black tea'},\n {value: 'Downton Abbey Grantham Breakfast Blend',\n text: 'Downton Abbey Grantham Breakfast Blend'},\n {value: 'Nepal First Flush', text: 'Nepal First Flush'},\n {value: 'Earl Grey Extra', text: 'Earl Grey Extra'},\n {value: '2007 Menghai Golden Needle &amp; White Lotus Ripe Pu-erh',\n text: '2007 Menghai Golden Needle &amp; White Lotus Ripe Pu-erh'},\n {value: 'Spirulina Stamina', text: 'Spirulina Stamina'},\n {value: 'Monks Mead', text: 'Monks Mead'},\n {value: 'Chocolate Jasmine', text: 'Chocolate Jasmine'},\n {value: 'Pineapple Upside-Down Cake Honeybush',\n text: 'Pineapple Upside-Down Cake Honeybush'},\n {value: 'Mist on the Gorges', text: 'Mist on the Gorges'},\n {value: 'Caramel Chai Pu-erh', text: 'Caramel Chai Pu-erh'},\n {value: 'Assam CTC Granular', text: 'Assam CTC Granular'},\n {value: 'Double Chocolate Decadence', text: 'Double Chocolate Decadence'},\n {value: 'Organic Golden Monkey', text: 'Organic Golden Monkey'},\n {value: 'Meyer Lemon Black Tea', text: 'Meyer Lemon Black Tea'},\n {value: 'Harmoni', text: 'Harmoni'},\n {value: 'Mengding Huangya', text: 'Mengding Huangya'},\n {value: 'Focus', text: 'Focus'},\n {value: 'Celebrate The Monk', text: 'Celebrate The Monk'},\n {value: 'Caramel Almond Amaretti', text: 'Caramel Almond Amaretti'},\n {value: 'Black Needle Yunnan', text: 'Black Needle Yunnan'},\n {value: 'Bai Lin Kung Fu', text: 'Bai Lin Kung Fu'},\n {value: 'Arcadian Apple', text: 'Arcadian Apple'},\n {value: 'Yunnan Golden Tips A', text: 'Yunnan Golden Tips A'},\n {value: 'Banana Nut Bread', text: 'Banana Nut Bread'},\n {value: 'Fuhai 2007 Sheng Puer', text: 'Fuhai 2007 Sheng Puer'},\n {value: 'Organic Cocoa for Coconuts', text: 'Organic Cocoa for Coconuts'},\n {value: 'TeaSource Darjeeling', text: 'TeaSource Darjeeling'},\n {value: 'White Tea - Vanilla Blend', text: 'White Tea - Vanilla Blend'},\n {value: 'Gaba Cha', text: 'Gaba Cha'},\n {value: 'Fancy Oolong', text: 'Fancy Oolong'},\n {value: 'Cinnamon Rooibos Chai (organic)',\n text: 'Cinnamon Rooibos Chai (organic)'},\n {value: 'Gooey Butter Cake', text: 'Gooey Butter Cake'},\n {value: 'Earl Grey Supreme TE14', text: 'Earl Grey Supreme TE14'},\n {value: 'Organic Tuoareg (Moroccan Mint)',\n text: 'Organic Tuoareg (Moroccan Mint)'},\n {value: 'Christmas', text: 'Christmas'},\n {value: 'Darjeeling Margarets Hope Autumnal (285)',\n text: 'Darjeeling Margarets Hope Autumnal (285)'},\n {value: 'Sleigh Ride', text: 'Sleigh Ride'},\n {value: 'Doke Silver Needle', text: 'Doke Silver Needle'},\n {value: 'Liu An', text: 'Liu An'},\n {value: 'Organic Jasmine Dragon Pearl',\n text: 'Organic Jasmine Dragon Pearl'},\n {value: 'Organic Chai', text: 'Organic Chai'},\n {value: 'Kukicha (organic)', text: 'Kukicha (organic)'},\n {value: 'Song Zhong Dan Chong', text: 'Song Zhong Dan Chong'},\n {value: 'French Super-Blue Lavender', text: 'French Super-Blue Lavender'},\n {value: 'African Solstice', text: 'African Solstice'},\n {value: 'Brandied Apricot', text: 'Brandied Apricot'},\n {value: 'Organically Grown Loose Leaf Tea',\n text: 'Organically Grown Loose Leaf Tea'},\n {value: 'Organic Kenchajangha', text: 'Organic Kenchajangha'},\n {value: 'Honyama Shincha', text: 'Honyama Shincha'},\n {value: 'Emperors Red', text: 'Emperors Red'},\n {value: 'Keemun Congou Special', text: 'Keemun Congou Special'},\n {value: '2003 Menghai Wild Arbor (Red Mark) Raw',\n text: '2003 Menghai Wild Arbor (Red Mark) Raw'},\n {value: 'Assam TGFOP Koomsong', text: 'Assam TGFOP Koomsong'},\n {value: 'Dark Roast 10 Year Aged Tieguanyin',\n text: 'Dark Roast 10 Year Aged Tieguanyin'},\n {value: 'Yunnan Silver Needle', text: 'Yunnan Silver Needle'},\n {value: 'Organic Lu An Gua Pian', text: 'Organic Lu An Gua Pian'},\n {value: 'Organic Acai White', text: 'Organic Acai White'},\n {value: 'Formosa Grand Pouchong', text: 'Formosa Grand Pouchong'},\n {value: 'Special Gunpowder Green Tea',\n text: 'Special Gunpowder Green Tea'},\n {value: 'A Nice Cup of Shut the Hell Up',\n text: 'A Nice Cup of Shut the Hell Up'},\n {value: 'Superfine Taiwan Moderately-Roasted Dong Ding Oolong Tea',\n text: 'Superfine Taiwan Dong Ding Oolong Tea'},\n {value: 'Welsh Moonlight', text: 'Welsh Moonlight'},\n {value: 'IYEMON Matcha Iri Genmaicha',\n text: 'IYEMON Matcha Iri Genmaicha'},\n {value: 'Summer Passion', text: 'Summer Passion'},\n {value: '2005 6FTM Jia Ji Raw Tuo Cha',\n text: '2005 6FTM Jia Ji Raw Tuo Cha'},\n {value: 'I Cant Tell You', text: 'I Cant Tell You'},\n {value: 'Chocolatte Green Tea Matcha Mint',\n text: 'Chocolatte Green Tea Matcha Mint'},\n {value: 'Assam Harmony', text: 'Assam Harmony'},\n {value: 'Yamakai Sencha - 2010 1st Harvest Shizuoka Sencha',\n text: 'Yamakai Sencha - 2010 1st Harvest Shizuoka Sencha'},\n {value: 'Cherries Jubilee Bai Mu Dan',\n text: 'Cherries Jubilee Bai Mu Dan'},\n {value: 'Buddhas Hand Spring 2010', text: 'Buddhas Hand Spring 2010'},\n {value: 'Second Flush Darjeeling Tea FTGFOP 1',\n text: 'Second Flush Darjeeling Tea FTGFOP 1'},\n {value: 'Organic Chamomile', text: 'Organic Chamomile'},\n {value: 'Moonlight White Cake', text: 'Moonlight White Cake'},\n {value: 'Brown Rice Tea (Genmaicha)', text: 'Brown Rice Tea (Genmaicha)'},\n {value: '深むし茶初美 (Fukamushicha Hatsumi)',\n text: '深むし茶初美 (Fukamushicha Hatsumi)'},\n {value: 'Chocolate Rocket', text: 'Chocolate Rocket'},\n {value: '2007 Jingmai Mountain Spring Raw Puer Cake',\n text: '2007 Jingmai Mountain Spring Raw Puer Cake'},\n {value: 'Royal Blooming No 1 Green Jasmin Blooming Tea',\n text: 'Royal Blooming No 1 Green Jasmin Blooming Tea'},\n {value: 'Organic Matcha (Yukimatchairi Kan)',\n text: 'Organic Matcha (Yukimatchairi Kan)'},\n {value: 'Forte', text: 'Forte'},\n {value: 'Powdered Green Tea (Matcha)',\n text: 'Powdered Green Tea (Matcha)'},\n {value: 'Hong Mao Feng', text: 'Hong Mao Feng'},\n {value: 'Chá verde Mar de Verão', text: 'Chá verde Mar de Verão'},\n {value: 'Superior Grade Fujian Wuyi Shan Tie Luo Han Oolong',\n text: 'Superior Grade Fujian Wuyi Shan Tie Luo Han Oolong'},\n {value: 'Ginseng Peppermint', text: 'Ginseng Peppermint'},\n {value: 'Snowflakes on Green Lake Bi Tan Piao Xue',\n text: 'Snowflakes on Green Lake Bi Tan Piao Xue'},\n {value: 'Oolong Rose tea', text: 'Oolong Rose tea'},\n {value: 'Pumpkin Maté', text: 'Pumpkin Maté'},\n {value: 'Da Hong Pao Red Robe', text: 'Da Hong Pao Red Robe'},\n {value: 'Organic Wuyi Yancha', text: 'Organic Wuyi Yancha'},\n {value: 'Cornfields Shu Tuocha', text: 'Cornfields Shu Tuocha'},\n {value: 'Formosa Gunpowder', text: 'Formosa Gunpowder'},\n {value: 'Awake', text: 'Awake'},\n {value: 'Nagobilevi Village', text: 'Nagobilevi Village'},\n {value: 'Honey Vanilla Chai', text: 'Honey Vanilla Chai'},\n {value: 'Mate and Lemongrass', text: 'Mate and Lemongrass'},\n {value: 'Bamboo Shoots', text: 'Bamboo Shoots'},\n {value: 'Coconut White Masala Chai', text: 'Coconut White Masala Chai'},\n {value: 'Kona Cha Japan Green', text: 'Kona Cha Japan Green'},\n {value: 'Gardens of Anxi', text: 'Gardens of Anxi'},\n {value: 'Lapsang Souchong Organic (No. 8311)',\n text: 'Lapsang Souchong Organic (No. 8311)'},\n {value: 'Guerriers', text: 'Guerriers'},\n {value: 'Vaniglia lampone (Heiße Liebe)',\n text: 'Vaniglia lampone (Heiße Liebe)'},\n {value: 'Marigold Blossoms', text: 'Marigold Blossoms'},\n {value: 'Winter Mao Xie Oolong Tea', text: 'Winter Mao Xie Oolong Tea'},\n {value: '2009 Mongshan Premium Zhu Ye Qing Tea',\n text: '2009 Mongshan Premium Zhu Ye Qing Tea'},\n {value: 'YMY 1690 Jasmine', text: 'YMY 1690 Jasmine'},\n {value: 'Strawberries and Cream', text: 'Strawberries and Cream'},\n {value: 'Ti Kuan Yin Mr. Wei', text: 'Ti Kuan Yin Mr. Wei'},\n {value: 'Mango Diablo', text: 'Mango Diablo'},\n {value: 'castleton ftgfop 1st flush super 2011',\n text: 'castleton ftgfop 1st flush super 2011'},\n {value: 'Two parts yunnan to one part assam',\n text: 'Two parts yunnan to one part assam'},\n {value: 'Sweet Strawberry', text: 'Sweet Strawberry'},\n {value: '1970s Da Ye Loose leaf Raw Puerh',\n text: '1970s Da Ye Loose leaf Raw Puerh'},\n {value: 'Shui Jin Gui Wuyi Oolong', text: 'Shui Jin Gui Wuyi Oolong'},\n {value: 'Sundew', text: 'Sundew'},\n {value: 'Orange Ginger Mint', text: 'Orange Ginger Mint'},\n {value: 'Cinnamon Cookie Puer', text: 'Cinnamon Cookie Puer'},\n {value: 'Authentic Chai', text: 'Authentic Chai'},\n {value: 'La Belle Epoque', text: 'La Belle Epoque'},\n {value: 'Green Mango', text: 'Green Mango'},\n {value: 'Champagne Mojito Green', text: 'Champagne Mojito Green'},\n {value: 'afternoon', text: 'afternoon'},\n {value: 'Blood Orange Black Tea', text: 'Blood Orange Black Tea'},\n {value: 'White Monkey Paw', text: 'White Monkey Paw'},\n {value: 'Thé Blanc Osmanthus - Shanghai Impérial',\n text: 'Thé Blanc Osmanthus - Shanghai Impérial'},\n {value: 'Green Lemon', text: 'Green Lemon'},\n {value: 'Kings Tea Taiwan Oolong', text: 'Kings Tea Taiwan Oolong'},\n {value: 'Campfire Blend', text: 'Campfire Blend'},\n {value: 'Orange Ginger', text: 'Orange Ginger'},\n {value: 'Organic Better Morning Blend',\n text: 'Organic Better Morning Blend'},\n {value: 'Rainforest Tea', text: 'Rainforest Tea'},\n {value: 'Sichuan Zao Bai Jian Spring',\n text: 'Sichuan Zao Bai Jian Spring'},\n {value: 'Tropicalia', text: 'Tropicalia'},\n {value: 'Fruta Bomba', text: 'Fruta Bomba'},\n {value: 'Taipei Memorial 2006 (Hong Tie)',\n text: 'Taipei Memorial 2006 (Hong Tie)'},\n {value: 'Banana Split', text: 'Banana Split'},\n {value: 'Rou Gui (Cinnebar) Wu Yi Cliff Tea',\n text: 'Rou Gui (Cinnebar) Wu Yi Cliff Tea'},\n {value: 'Taiwan Everspring Sijichun Kultivar',\n text: 'Taiwan Everspring Sijichun Kultivar'},\n {value: 'Pumpkin Cream Tea', text: 'Pumpkin Cream Tea'},\n {value: 'Youthberry / Wild Orange Blossom Blend',\n text: 'Youthberry / Wild Orange Blossom Blend'},\n {value: 'Lemon and Lime Twist', text: 'Lemon and Lime Twist'},\n {value: 'Earl Grey Le Creme', text: 'Earl Grey Le Creme'},\n {value: 'White Pineapple Coconut', text: 'White Pineapple Coconut'},\n {value: 'Eucalyptus Mint White Tea', text: 'Eucalyptus Mint White Tea'},\n {value: 'Cranberry Green Tea', text: 'Cranberry Green Tea'},\n {value: 'Organic Vanilla Bean Black Tea',\n text: 'Organic Vanilla Bean Black Tea'},\n {value: 'Organic Sugar Destroyer Royal Matcha',\n text: 'Organic Sugar Destroyer Royal Matcha'},\n {value: 'Alla Pesca', text: 'Alla Pesca'},\n {value: 'Chilli Chilli Bang Bang', text: 'Chilli Chilli Bang Bang'},\n {value: 'Yong De Wild Purple Ye Sheng Black Tea Spring 2015',\n text: 'Yong De Wild Purple Ye Sheng Black Tea Spring 2015'},\n {value: 'San Lin She Unroasted 2011 Spring',\n text: 'San Lin She Unroasted 2011 Spring'},\n {value: 'Assam Nahorhabi STGFOP1 CL Spl',\n text: 'Assam Nahorhabi STGFOP1 CL Spl'},\n {value: 'Organic Guayusa', text: 'Organic Guayusa'},\n {value: 'Jade Himalaya', text: 'Jade Himalaya'},\n {value: 'Spring Fling', text: 'Spring Fling'},\n {value: 'Peony White', text: 'Peony White'},\n {value: 'Earl Grey Moonlight', text: 'Earl Grey Moonlight'},\n {value: 'Teavana® Green Tea Latte', text: 'Teavana® Green Tea Latte'},\n {value: 'Eight Treasures Yabao Winter Blend',\n text: 'Eight Treasures Yabao Winter Blend'},\n {value: 'Hand Picked Tieguanyin Spring Oolong (2011)',\n text: 'Hand Picked Tieguanyin Spring Oolong (2011)'},\n {value: 'Sweet Mint', text: 'Sweet Mint'},\n {value: 'Cashew Turtle', text: 'Cashew Turtle'},\n {value: 'Decaf Strawberry', text: 'Decaf Strawberry'},\n {value: 'apple green tea', text: 'apple green tea'},\n {value: 'Vanilla Spice Herbal', text: 'Vanilla Spice Herbal'},\n {value: 'Skin Detox', text: 'Skin Detox'},\n {value: 'Shou Pu-erh 2000', text: 'Shou Pu-erh 2000'},\n {value: 'Mandala Wild Monk Tea - Mao Cha',\n text: 'Mandala Wild Monk Tea - Mao Cha'},\n {value: '2011 Yunnan Sourcing Yi Dian Hong Ripe Pu-erh Tea Mini Cake',\n text: '2011 Yunnan Sourcing Yi Dian Hong Ripe Pu-erh Tea Mini Cake'},\n {value: 'Blue Mist', text: 'Blue Mist'},\n {value: 'Bai Ye Phoenix Oolong', text: 'Bai Ye Phoenix Oolong'},\n {value: 'Nok Cha', text: 'Nok Cha'},\n {value: 'Ramonas Spiced Pear Bai Mu Dan',\n text: 'Ramonas Spiced Pear Bai Mu Dan'},\n {value: 'Lumbini FBOPFEXS', text: 'Lumbini FBOPFEXS'},\n {value: 'Tie Guan Yin (Ti Kuan Yin) - Iron Goddess of Mercy',\n text: 'Tie Guan Yin (Ti Kuan Yin) - Iron Goddess of Mercy'},\n {value: 'Mulberry Magic', text: 'Mulberry Magic'},\n {value: 'Assam Sree Sibari Estate SFTGFOP1',\n text: 'Assam Sree Sibari Estate SFTGFOP1'},\n {value: 'Grapefruit Green', text: 'Grapefruit Green'},\n {value: 'Usambara African Breakfast', text: 'Usambara African Breakfast'},\n {value: 'Pomme dAmour', text: 'Pomme dAmour'},\n {value: 'Sononokaori', text: 'Sononokaori'},\n {value: 'Dao Ren', text: 'Dao Ren'},\n {value: 'Golden Buds Yunnan Black', text: 'Golden Buds Yunnan Black'},\n {value: 'Sea Breeze Green Tea', text: 'Sea Breeze Green Tea'},\n {value: 'Mauritius', text: 'Mauritius'},\n {value: 'Wedding Impérial', text: 'Wedding Impérial'},\n {value: 'Lemon Myrtle (organic)', text: 'Lemon Myrtle (organic)'},\n {value: 'Gingerbread Matcha', text: 'Gingerbread Matcha'},\n {value: 'Tea for Liver and Kidney', text: 'Tea for Liver and Kidney'},\n {value: 'Spiced Ethiopian Tea', text: 'Spiced Ethiopian Tea'},\n {value: 'Banana Dream Pie', text: 'Banana Dream Pie'},\n {value: 'Snow White', text: 'Snow White'},\n {value: 'Kiwi Pear Decaf', text: 'Kiwi Pear Decaf'},\n {value: 'Sencha Vanilla', text: 'Sencha Vanilla'},\n {value: 'Yanagicha', text: 'Yanagicha'},\n {value: 'Himalaya Green Tea', text: 'Himalaya Green Tea'},\n {value: 'Royal Wedding Blend', text: 'Royal Wedding Blend'},\n {value: 'Meyer Lemon Cream Rooibos', text: 'Meyer Lemon Cream Rooibos'},\n {value: 'Velvet Garden White Rose', text: 'Velvet Garden White Rose'},\n {value: 'Spring 2013 Zheng Shan Xiao Zhong of Wu Yi Fujian Black tea',\n text: 'Spring 2013 Zheng Shan Xiao Zhong of Wu Yi Fujian Black tea'},\n {value: 'The Duke of Earl', text: 'The Duke of Earl'},\n {value: '60s Ba-Zhong Huang Yin', text: '60s Ba-Zhong Huang Yin'},\n {value: 'Darjeeling Peppermint', text: 'Darjeeling Peppermint'},\n {value: 'Brique de thé Pu-Erh du Yunnan (black tea compressé)',\n text: 'Brique de thé Pu-Erh du Yunnan (black tea compressé)'},\n {value: 'Kamanobicha', text: 'Kamanobicha'},\n {value: 'ceylon orange pekoe', text: 'ceylon orange pekoe'},\n {value: 'Jasmine Silver Needle King', text: 'Jasmine Silver Needle King'},\n {value: 'Certified Organic Peppermint (BH46)',\n text: 'Certified Organic Peppermint (BH46)'},\n {value: 'Paradise Green', text: 'Paradise Green'},\n {value: 'Amor', text: 'Amor'},\n {value: '2011 Mo Li Xiang - Jasmine Fragrance',\n text: '2011 Mo Li Xiang - Jasmine Fragrance'},\n {value: 'Superior Blueberry Buckle', text: 'Superior Blueberry Buckle'},\n {value: '2010 Damn Fine Holiday Blend',\n text: '2010 Damn Fine Holiday Blend'},\n {value: '2007 Xi-Zhi Hao Classic 8582',\n text: '2007 Xi-Zhi Hao Classic 8582'},\n {value: 'China Oolong Tit Kon Yum', text: 'China Oolong Tit Kon Yum'},\n {value: 'Rooibos Chocolate Chai', text: 'Rooibos Chocolate Chai'},\n {value: 'Wild Monk Sheng Puer (2012)',\n text: 'Wild Monk Sheng Puer (2012)'},\n {value: 'Medium Roast Monkey Picked Iron Goddess',\n text: 'Medium Roast Monkey Picked Iron Goddess'},\n {value: 'Lemon Sencha', text: 'Lemon Sencha'},\n {value: 'Pu-er Tuo Cha', text: 'Pu-er Tuo Cha'},\n {value: 'Organic Jasmine Blossom Green Tea',\n text: 'Organic Jasmine Blossom Green Tea'},\n {value: 'Strawberry &amp; Champagne Sencha',\n text: 'Strawberry Champagne Sencha'},\n {value: 'Black Tea with Cardamom', text: 'Black Tea with Cardamom'},\n {value: 'Chun Mei Green Tea (Zhen Mei)',\n text: 'Chun Mei Green Tea (Zhen Mei)'},\n {value: '2007 Banna Rongzhen ripe tuocha',\n text: '2007 Banna Rongzhen ripe tuocha'},\n {value: 'Moorish Mint', text: 'Moorish Mint'},\n {value: 'Superior Bai Lin Gong Fu', text: 'Superior Bai Lin Gong Fu'},\n {value: 'Yerba Mate con Palo', text: 'Yerba Mate con Palo'},\n {value: 'Mutan White', text: 'Mutan White'},\n {value: 'Orange Spice Tulsi', text: 'Orange Spice Tulsi'},\n {value: 'Wild Fruit', text: 'Wild Fruit'},\n {value: 'Peppermint Dream', text: 'Peppermint Dream'},\n {value: 'Hamburger Goldblatt', text: 'Hamburger Goldblatt'},\n {value: 'Coconut Chamomile - DISCONTINUED',\n text: 'Coconut Chamomile - DISCONTINUED'},\n {value: 'Darjeeling Avongrove Euphoria FTGFOP1',\n text: 'Darjeeling Avongrove Euphoria FTGFOP1'},\n {value: 'Lime Chiffon', text: 'Lime Chiffon'},\n {value: 'China Lichee Black', text: 'China Lichee Black'},\n {value: 'TM70: Mist Valley Estate SFTGFOP1 Tippy',\n text: 'TM70: Mist Valley Estate SFTGFOP1 Tippy'},\n {value: 'Mountain Nectar', text: 'Mountain Nectar'},\n {value: 'Green Pu-erh Large Leaf 1995',\n text: 'Green Pu-erh Large Leaf 1995'},\n {value: 'Nuwara Eliya', text: 'Nuwara Eliya'},\n {value: '2012 First Flush Ambootia FTGFOP1',\n text: '2012 First Flush Ambootia FTGFOP1'},\n {value: 'Yunnan Royal Gold', text: 'Yunnan Royal Gold'},\n {value: 'Le Marche Spiced tea', text: 'Le Marche Spiced tea'},\n {value: 'Blackcurrant and Hibiscus', text: 'Blackcurrant and Hibiscus'},\n {value: 'Chamomile &amp; Rooibos Tropica',\n text: 'Chamomile &amp; Rooibos Tropica'},\n {value: 'Choicest', text: 'Choicest'},\n {value: 'Lamington Brew', text: 'Lamington Brew'},\n {value: 'Ginseng Oolong (ZM87)', text: 'Ginseng Oolong (ZM87)'},\n {value: 'Snooze Blend', text: 'Snooze Blend'},\n {value: 'Smoked Maple', text: 'Smoked Maple'},\n {value: 'Pomegranate Superfruit', text: 'Pomegranate Superfruit'},\n {value: 'Mei Hua', text: 'Mei Hua'},\n {value: 'Sencha Sensation', text: 'Sencha Sensation'},\n {value: 'White Tea with Raspberry - Pai Mu Tan White Tea',\n text: 'White Tea with Raspberry - Pai Mu Tan White Tea'},\n {value: 'Saint Isaacs Blend TE06', text: 'Saint Isaacs Blend TE06'},\n {value: 'Jing Xuan', text: 'Jing Xuan'},\n {value: 'Menta com Chocolate', text: 'Menta com Chocolate'},\n {value: 'Sayamakaori Shincha', text: 'Sayamakaori Shincha'},\n {value: 'Wild Berry Hibiscus (limited edition)',\n text: 'Wild Berry Hibiscus (limited edition)'},\n {value: 'Selby Select Rooibos', text: 'Selby Select Rooibos'},\n {value: 'Géorgie OP', text: 'Géorgie OP'},\n {value: 'Superfine Keemun Fragrant Black Tea',\n text: 'Superfine Keemun Fragrant Black Tea'},\n {value: 'Sweet Dreamzzz', text: 'Sweet Dreamzzz'},\n {value: 'large leaf -lot 17', text: 'large leaf -lot 17'},\n {value: 'Some Velvet Morning', text: 'Some Velvet Morning'},\n {value: 'Golden Tip Assam', text: 'Golden Tip Assam'},\n {value: 'Pure Heart', text: 'Pure Heart'},\n {value: 'Tahitian Green T-Dust', text: 'Tahitian Green T-Dust'},\n {value: 'Mate Roasted 963', text: 'Mate Roasted 963'},\n {value: 'Dian hong (Yunnan Red)', text: 'Dian hong (Yunnan Red)'},\n {value: 'Lemon Meringue Rooibos', text: 'Lemon Meringue Rooibos'},\n {value: 'Partridgeberry in a Pear Tea',\n text: 'Partridgeberry in a Pear Tea'},\n {value: 'Pear Green Tea', text: 'Pear Green Tea'},\n {value: 'Organic Rose Hips with Hibiscus',\n text: 'Organic Rose Hips with Hibiscus'},\n {value: 'Vanilla', text: 'Vanilla'},\n {value: 'Afternoon Revival', text: 'Afternoon Revival'},\n {value: 'yi ji hong dan cong (first class dark dan cong) 2010',\n text: 'yi ji hong dan cong (first class dark dan cong) 2010'},\n {value: 'Classic Black', text: 'Classic Black'},\n {value: 'Silver Needle Yinzhen White Tea',\n text: 'Silver Needle Yinzhen White Tea'},\n {value: 'Organic Black Pearl', text: 'Organic Black Pearl'},\n {value: 'Lao Cong Shui Xian (Old Bush Narcissus) Rock Wulong 2011',\n text: 'Lao Cong Shui Xian (Old Bush Narcissus) Rock Wulong 2011'},\n {value: 'Snowflake', text: 'Snowflake'},\n {value: 'Organic Honey Vanilla White',\n text: 'Organic Honey Vanilla White'},\n {value: 'Wild Goddess ™ Oolong', text: 'Wild Goddess ™ Oolong'},\n {value: 'Longbourne Wedding Tea (Jane Austen Tea Series)',\n text: 'Longbourne Wedding Tea (Jane Austen Tea Series)'},\n {value: 'Tropical Savannah', text: 'Tropical Savannah'},\n {value: 'Chai Spice Black Tea', text: 'Chai Spice Black Tea'},\n {value: 'Peach Apricot Honeybush Tea',\n text: 'Peach Apricot Honeybush Tea'},\n {value: 'Buddhas Hand', text: 'Buddhas Hand'},\n {value: 'Corrines Lemon Rooibos', text: 'Corrines Lemon Rooibos'},\n {value: 'Spiced Tea - Indian Masala Blend',\n text: 'Spiced Tea - Indian Masala Blend'},\n {value: 'Merry Cranberry', text: 'Merry Cranberry'},\n {value: 'Partridgeberry', text: 'Partridgeberry'},\n {value: 'Makaibari 1st Flush Darjeeling 2011',\n text: 'Makaibari 1st Flush Darjeeling 2011'},\n {value: 'Gaoshan Qingxiang Lishan High Mt. Oolong Tea',\n text: 'Gaoshan Qingxiang Lishan High Mt. Oolong Tea'},\n {value: '125 gram Xiaguan FT Flame Raw - 2007',\n text: '125 gram Xiaguan FT Flame Raw - 2007'},\n {value: 'Ginger Black Tea', text: 'Ginger Black Tea'},\n {value: 'Chocolate Mint Mate', text: 'Chocolate Mint Mate'},\n {value: 'Capricorn - Zodiac Series - 2012',\n text: 'Capricorn - Zodiac Series - 2012'},\n {value: 'Oolong Tea Lemon Basil', text: 'Oolong Tea Lemon Basil'},\n {value: 'Ceylon Doomba', text: 'Ceylon Doomba'},\n {value: 'Rose Tyler Tea Blend', text: 'Rose Tyler Tea Blend'},\n {value: '525 China Oolong Kwai Flower',\n text: '525 China Oolong Kwai Flower'},\n {value: 'Gold Blend', text: 'Gold Blend'},\n {value: 'Kunlun Snow Chrysanthemum Flowers',\n text: 'Kunlun Snow Chrysanthemum Flowers'},\n {value: 'China Lapsang Souchong - 581',\n text: 'China Lapsang Souchong - 581'},\n {value: 'Da Yu Lin Oolong (Da Yie Lin)',\n text: 'Da Yu Lin Oolong (Da Yie Lin)'},\n {value: 'Caramel Sweetheart', text: 'Caramel Sweetheart'},\n {value: '100% Natural Decaffeinated Green',\n text: '100% Natural Decaffeinated Green'},\n {value: 'Old Pu-Erh Tea', text: 'Old Pu-Erh Tea'},\n {value: 'Assam FTGFOP1 2nd Flush Hazelbank Estate Supreme',\n text: 'Assam FTGFOP1 2nd Flush Hazelbank Estate Supreme'},\n {value: 'Palekaiko', text: 'Palekaiko'},\n {value: 'Behora TGFOP', text: 'Behora TGFOP'},\n {value: 'Dragon Feelers', text: 'Dragon Feelers'},\n {value: 'Silk Oolong Anxi', text: 'Silk Oolong Anxi'},\n {value: 'Christmas Tea', text: 'Christmas Tea'},\n {value: 'Dark Oolong 5th Grade', text: 'Dark Oolong 5th Grade'},\n {value: 'Organic Tropical Goji Berry',\n text: 'Organic Tropical Goji Berry'},\n {value: 'Golden Lily (Jin Xuan) Milk Oolong',\n text: 'Golden Lily (Jin Xuan) Milk Oolong'},\n {value: 'Sleep Tight', text: 'Sleep Tight'},\n {value: 'Zhu Lu Alishan High Mt. Oolong Tea',\n text: 'Zhu Lu Alishan High Mt. Oolong Tea'},\n {value: 'Osmanthus Oolong Rare Estate Tea',\n text: 'Osmanthus Oolong Rare Estate Tea'},\n {value: 'Darjeeling FTGFOP1 Phuguri', text: 'Darjeeling FTGFOP1 Phuguri'},\n {value: 'Peppermint Yerba Mate', text: 'Peppermint Yerba Mate'},\n {value: 'Citrus Lavender Sage/Opus Rouge Blend',\n text: 'Citrus Lavender Sage/Opus Rouge Blend'},\n {value: 'Lanikai', text: 'Lanikai'},\n {value: 'Sencha Fidji', text: 'Sencha Fidji'},\n {value: 'Boléro', text: 'Boléro'},\n {value: 'Cloud 9 Rooibos', text: 'Cloud 9 Rooibos'},\n {value: 'Matcha Tea Powder by hamasaen',\n text: 'Matcha Tea Powder by hamasaen'},\n {value: 'Organic Pu-Erh Mini Tuo Cha',\n text: 'Organic Pu-Erh Mini Tuo Cha'},\n {value: '2013 Menghai Dan Quing', text: '2013 Menghai Dan Quing'},\n {value: 'Eastern Chamomile', text: 'Eastern Chamomile'},\n {value: 'Nepal Mai Ilam First Flush', text: 'Nepal Mai Ilam First Flush'},\n {value: 'Mango oolong', text: 'Mango oolong'},\n {value: 'Alabaster', text: 'Alabaster'},\n {value: 'Ceylon Vithanakande FBOPF (EX)',\n text: 'Ceylon Vithanakande FBOPF (EX)'},\n {value: 'Rêverie dun soir sur la Néva',\n text: 'Rêverie dun soir sur la Néva'},\n {value: 'Sunrise Sensation', text: 'Sunrise Sensation'},\n {value: 'Republic Darjeeling', text: 'Republic Darjeeling'},\n {value: 'Luan Melon Seed', text: 'Luan Melon Seed'},\n {value: 'Roasted Dong Ding', text: 'Roasted Dong Ding'},\n {value: 'Tesco Finest Chocolate Tea', text: 'Tesco Finest Chocolate Tea'},\n {value: 'Oi Ocha', text: 'Oi Ocha'},\n {value: 'Organic 2nd Flush Darjeeling',\n text: 'Organic 2nd Flush Darjeeling'},\n {value: 'Dong Ting Bi Luo Chun', text: 'Dong Ting Bi Luo Chun'},\n {value: 'North Winds (Old Version)', text: 'North Winds (Old Version)'},\n {value: 'Candy Apple', text: 'Candy Apple'},\n {value: 'Lullaby Time', text: 'Lullaby Time'},\n {value: 'Infusão Catarina', text: 'Infusão Catarina'},\n {value: 'Decaf Extra BOLD Masala Chai',\n text: 'Decaf Extra BOLD Masala Chai'},\n {value: 'Gyokuro Matcha', text: 'Gyokuro Matcha'},\n {value: 'Pumpkin Milkshake 2.0', text: 'Pumpkin Milkshake 2.0'},\n {value: 'Tega Rooibos Red Tea', text: 'Tega Rooibos Red Tea'},\n {value: 'Zi Yun Shan Anxi Oolong (Organic)',\n text: 'Zi Yun Shan Anxi Oolong (Organic)'},\n {value: 'Ceylon Galle Berubeula', text: 'Ceylon Galle Berubeula'},\n {value: 'Margarets Hope Darjeeling TGFOP1 (M.H. Darjeeling)',\n text: 'Margarets Hope Darjeeling TGFOP1 (M.H. Darjeeling)'},\n {value: 'Shagadelic English Breakfast',\n text: 'Shagadelic English Breakfast'},\n {value: 'Kaimosi CTC', text: 'Kaimosi CTC'},\n {value: 'Genmaicha Japan 655', text: 'Genmaicha Japan 655'},\n {value: 'Organic Roasted Dandelion', text: 'Organic Roasted Dandelion'},\n {value: 'Organic Oolong Tea', text: 'Organic Oolong Tea'},\n {value: 'Nilgiri Glendale Estate Frost Tea SFTGFOP ',\n text: 'Nilgiri Glendale Estate Frost Tea SFTGFOP '},\n {value: 'Organic Everyday Amazing', text: 'Organic Everyday Amazing'},\n {value: 'White Tiger (organic)', text: 'White Tiger (organic)'},\n {value: 'Zambezi Red Chai', text: 'Zambezi Red Chai'},\n {value: 'Moon Madness Herbal Tea', text: 'Moon Madness Herbal Tea'},\n {value: 'Tuscany Orange Spice Black Tea',\n text: 'Tuscany Orange Spice Black Tea'},\n {value: 'Tulsi Tea', text: 'Tulsi Tea'},\n {value: 'Jade Wulong', text: 'Jade Wulong'},\n {value: 'Megami Sencha', text: 'Megami Sencha'},\n {value: '2009 He Kai', text: '2009 He Kai'},\n {value: 'Blackberry Ice Cream', text: 'Blackberry Ice Cream'},\n {value: 'White Cucumber', text: 'White Cucumber'},\n {value: 'Se Chung Special Oolong', text: 'Se Chung Special Oolong'},\n {value: '100% Pure White Tea', text: '100% Pure White Tea'},\n {value: 'Golden Monkey (Jin Hou)', text: 'Golden Monkey (Jin Hou)'},\n {value: 'Superfine Tan Yang Gong Fu Black Tea',\n text: 'Superfine Tan Yang Gong Fu Black Tea'},\n {value: 'Green Limon', text: 'Green Limon'},\n {value: 'Mist Valley Estate Nepal SFTGFOP1 TIP (TM56)',\n text: 'Mist Valley Estate Nepal SFTGFOP1 TIP (TM56)'},\n {value: 'Fenghuang Shuixian', text: 'Fenghuang Shuixian'},\n {value: '18 Piece Premium Mini Tuo Cha Puer Assortment',\n text: '18 Piece Premium Mini Tuo Cha Puer Assortment'},\n {value: 'Caramel Apple', text: 'Caramel Apple'},\n {value: 'Keemun Hao Ya B', text: 'Keemun Hao Ya B'},\n {value: 'Pu-erh Tuocha', text: 'Pu-erh Tuocha'},\n {value: 'Lemon Jasmine', text: 'Lemon Jasmine'},\n {value: 'Sanguine Sangria', text: 'Sanguine Sangria'},\n {value: 'Chan tea', text: 'Chan tea'},\n {value: 'Chocolate Peanut Butter Cup Black Tea',\n text: 'Chocolate Peanut Butter Cup Black Tea'},\n {value: 'Kamiya Papaya Oolong', text: 'Kamiya Papaya Oolong'},\n {value: '2009 Jinggu Wenshan Village Big Tree Raw Pu Er Cake-spring',\n text: '2009 Jinggu Wenshan Village Big Tree Raw Pu Er Cake-spring'},\n {value: 'Winter 2011 Da Yu Ling Oolong Tea',\n text: 'Winter 2011 Da Yu Ling Oolong Tea'},\n {value: 'The au Chocolat', text: 'The au Chocolat'},\n {value: 'Back Porch Blend', text: 'Back Porch Blend'},\n {value: '1980 Aged Tung Ting', text: '1980 Aged Tung Ting'},\n {value: 'Cocotte', text: 'Cocotte'},\n {value: 'Griottes (Chocolate Cherry)',\n text: 'Griottes (Chocolate Cherry)'},\n {value: 'Green Tea with Lemon &amp; Ginseng by Benner',\n text: 'Green Tea with Lemon Ginseng by Benner'},\n {value: 'Husets Urte Te', text: 'Husets Urte Te'},\n {value: 'Cthulhu Tea', text: 'Cthulhu Tea'},\n {value: 'Jasmine Snow Dragon', text: 'Jasmine Snow Dragon'},\n {value: 'Hojicha Roasted Green Tea', text: 'Hojicha Roasted Green Tea'},\n {value: 'China Fine Young Hyson', text: 'China Fine Young Hyson'},\n {value: 'Nanas Blend', text: 'Nanas Blend'},\n {value: 'Almond with Pieces', text: 'Almond with Pieces'},\n {value: 'Organic Hojicha Chai', text: 'Organic Hojicha Chai'},\n {value: 'Kirschblüten', text: 'Kirschblüten'},\n {value: 'Checkmate', text: 'Checkmate'},\n {value: 'Caramel Apple (Red)', text: 'Caramel Apple (Red)'},\n {value: 'Congo Bongo', text: 'Congo Bongo'},\n {value: 'Thé de Pâques', text: 'Thé de Pâques'},\n {value: 'Xin Yin Yu Lu', text: 'Xin Yin Yu Lu'},\n {value: 'Guangnan Green Pu-erh', text: 'Guangnan Green Pu-erh'},\n {value: 'Nie Jian Hou Kui', text: 'Nie Jian Hou Kui'},\n {value: 'Qianjiang Hubei Jade Organic ZG58',\n text: 'Qianjiang Hubei Jade Organic ZG58'},\n {value: 'Plum and Pear Green', text: 'Plum and Pear Green'},\n {value: 'Cranberry Autumn', text: 'Cranberry Autumn'},\n {value: 'Genmaicha – Japan', text: 'Genmaicha – Japan'},\n {value: 'Wuyi Cassia [Out of stock]', text: 'Wuyi Cassia [Out of stock]'},\n {value: 'Ceylon Nuwara Eliya OP', text: 'Ceylon Nuwara Eliya OP'},\n {value: 'Sultans Jewel (Ceylon w/Cardamom)',\n text: 'Sultans Jewel (Ceylon w/Cardamom)'},\n {value: 'China Pai Mu Tan (Organic)', text: 'China Pai Mu Tan (Organic)'},\n {value: 'Himalayan Darjeeling', text: 'Himalayan Darjeeling'},\n {value: 'Organic Blackberry Rooibos', text: 'Organic Blackberry Rooibos'},\n {value: 'Roasted Almond', text: 'Roasted Almond'},\n {value: 'Kagoshima Sencha Yutaka Midori',\n text: 'Kagoshima Sencha Yutaka Midori'},\n {value: 'Mangalam Assam', text: 'Mangalam Assam'},\n {value: 'Candied Apple Black Tea', text: 'Candied Apple Black Tea'},\n {value: 'Scrooges Blend', text: 'Scrooges Blend'},\n {value: 'Sungma Estate SFTGFOP1 Second Flush (TD16)',\n text: 'Sungma Estate SFTGFOP1 Second Flush (TD16)'},\n {value: 'Yerba Mate Hierbas Serranas',\n text: 'Yerba Mate Hierbas Serranas'},\n {value: 'Rose Petal Tea', text: 'Rose Petal Tea'},\n {value: 'Grand Cru Matcha', text: 'Grand Cru Matcha'},\n {value: 'Orange &amp; Spice', text: 'Orange &amp; Spice'},\n {value: 'Oolong Formosa Fancy', text: 'Oolong Formosa Fancy'},\n {value: 'Finest Russian Caravan (TB70)',\n text: 'Finest Russian Caravan (TB70)'},\n {value: 'Spring 2010 Xiang Zhen', text: 'Spring 2010 Xiang Zhen'},\n {value: 'White Night', text: 'White Night'},\n {value: 'Lemon Fruit', text: 'Lemon Fruit'},\n {value: 'Premium Green Tea', text: 'Premium Green Tea'},\n {value: 'Jasmine Fancy', text: 'Jasmine Fancy'},\n {value: 'Lavender Rooibos', text: 'Lavender Rooibos'},\n {value: 'Red Death Rooibos', text: 'Red Death Rooibos'},\n {value: 'Mojito', text: 'Mojito'},\n {value: 'Pu-erh - Lapsang Custom Blend',\n text: 'Pu-erh - Lapsang Custom Blend'},\n {value: 'Tulsi Rooibos Herbal', text: 'Tulsi Rooibos Herbal'},\n {value: 'Nuttier Than a Fruitcake', text: 'Nuttier Than a Fruitcake'},\n {value: 'Indian Nimbu', text: 'Indian Nimbu'},\n {value: '2012 Yunnan Sourcing Yong De Blue Label Ripe Pu-erh tea cake',\n text: '2012 Yunnan Sourcing Yong De Blue Label Ripe Pu-erh tea cake'},\n {value: 'Special Lung Ching (Dragon Well)',\n text: 'Special Lung Ching (Dragon Well)'},\n {value: 'Dark Rose Tea from yiqingyaun.com',\n text: 'Dark Rose Tea from yiqingyaun.com'},\n {value: 'Organic Mint Maté', text: 'Organic Mint Maté'},\n {value: 'Stone-Pressed 2004 Yiwu Wild Arbor Sheng',\n text: 'Stone-Pressed 2004 Yiwu Wild Arbor Sheng'},\n {value: 'Starfire Licorice', text: 'Starfire Licorice'},\n {value: 'Rooibos Almond', text: 'Rooibos Almond'},\n {value: 'Coconut Mango Wuyi Oolong', text: 'Coconut Mango Wuyi Oolong'},\n {value: 'Chocolate Raspberry Truffle',\n text: 'Chocolate Raspberry Truffle'},\n {value: 'Jamaican Rum', text: 'Jamaican Rum'},\n {value: 'Green Tea with Orange &amp; Lotus Flower',\n text: 'Green Tea with Orange &amp; Lotus Flower'},\n {value: 'Spring Mi Lan Dancong AAA', text: 'Spring Mi Lan Dancong AAA'},\n {value: 'Thé des Lords', text: 'Thé des Lords'},\n {value: 'Oxford Breakfast Tea', text: 'Oxford Breakfast Tea'},\n {value: 'Premium Peony White Tea', text: 'Premium Peony White Tea'},\n {value: 'Tikuanyin Comp. Reserve', text: 'Tikuanyin Comp. Reserve'},\n {value: 'Hot Lips (organic)', text: 'Hot Lips (organic)'},\n {value: 'Tour de France', text: 'Tour de France'},\n {value: 'Osmanthus', text: 'Osmanthus'},\n {value: 'Mamma Mia', text: 'Mamma Mia'},\n {value: 'Earl Grey Blue Flowers', text: 'Earl Grey Blue Flowers'},\n {value: 'Gypsy King Chai', text: 'Gypsy King Chai'},\n {value: 'Hojicha Creme (organic)', text: 'Hojicha Creme (organic)'},\n {value: 'Lipton Black Tea', text: 'Lipton Black Tea'},\n {value: 'Pao Blossom White Tea', text: 'Pao Blossom White Tea'},\n {value: 'Raspberry Patch', text: 'Raspberry Patch'},\n {value: 'dilmah breakfast tea', text: 'dilmah breakfast tea'},\n {value: 'Caramel Praline Delight', text: 'Caramel Praline Delight'},\n {value: 'Frutto Bianco Pearls', text: 'Frutto Bianco Pearls'},\n {value: 'Fenghuang Dan Cong Black 2011 Late Spring Pluck',\n text: 'Fenghuang Dan Cong Black 2011 Late Spring Pluck'},\n {value: 'Blood Orange Rooibos Biodegradable Pyramid Sachets',\n text: 'Blood Orange Rooibos Biodegradable Pyramid Sachets'},\n {value: 'Blazing Strawberries', text: 'Blazing Strawberries'},\n {value: 'Mango Shade', text: 'Mango Shade'},\n {value: 'Manohari Estate Assam', text: 'Manohari Estate Assam'},\n {value: 'Lemon Zest', text: 'Lemon Zest'},\n {value: 'Dark Oolong Tea 2nd Grade', text: 'Dark Oolong Tea 2nd Grade'},\n {value: 'Darjeeling Spring', text: 'Darjeeling Spring'},\n {value: 'Sencha Nagashima', text: 'Sencha Nagashima'},\n {value: 'Organic Fair Trade Antique Shu Pu-Erh',\n text: 'Organic Fair Trade Antique Shu Pu-Erh'},\n {value: 'Jeju Orchid Green Tea', text: 'Jeju Orchid Green Tea'},\n {value: 'Caribou Chai Tea Latte', text: 'Caribou Chai Tea Latte'},\n {value: 'Puerh Ginger (organic)', text: 'Puerh Ginger (organic)'},\n {value: 'Orange Jasmine', text: 'Orange Jasmine'},\n {value: 'China Oolong Qilan 1st grade',\n text: 'China Oolong Qilan 1st grade'},\n {value: 'Oothu FOP', text: 'Oothu FOP'},\n {value: 'Zhi Ran Tuocha - Mengha Factory - Lot 53 2004',\n text: 'Zhi Ran Tuocha - Mengha Factory - Lot 53 2004'},\n {value: 'China Yunnan PU ERH', text: 'China Yunnan PU ERH'},\n {value: 'Double Red Rooibos (Doubles Collection)',\n text: 'Double Red Rooibos (Doubles Collection)'},\n {value: 'The Mind and The Heart (Blend)',\n text: 'The Mind and The Heart (Blend)'},\n {value: '2009 Bai Ji Guan (White Cocks Comb)',\n text: '2009 Bai Ji Guan (White Cocks Comb)'},\n {value: 'Ayurvedic Men’s Activity Herb Tea Blend',\n text: 'Ayurvedic Men’s Activity Herb Tea Blend'},\n {value: 'Liquid Candy Corn', text: 'Liquid Candy Corn'},\n {value: 'Jasmine Orange', text: 'Jasmine Orange'},\n {value: 'Honey &amp; Lemon', text: 'Honey &amp; Lemon'},\n {value: 'Pu-Erh tea Lemon-flavoured red tea',\n text: 'Pu-Erh tea Lemon-flavoured red tea'},\n {value: 'Red Blossom Flower Tea', text: 'Red Blossom Flower Tea'},\n {value: 'Kenya Kosabei FTGFOP', text: 'Kenya Kosabei FTGFOP'},\n {value: 'Blossom Earl Grey', text: 'Blossom Earl Grey'},\n {value: 'Mirkwood', text: 'Mirkwood'},\n {value: 'Mint Rooibos Iced Tea', text: 'Mint Rooibos Iced Tea'},\n {value: 'Almond Cookie Green', text: 'Almond Cookie Green'},\n {value: 'Tropical Matcha', text: 'Tropical Matcha'},\n {value: 'Kawakawa Fire', text: 'Kawakawa Fire'},\n {value: 'DISCONTINUED (sold from 2012-2013)- Xin Yang Mao Jian',\n text: 'DISCONTINUED (sold from 2012-2013)- Xin Yang Mao Jian'},\n {value: 'Organic Mango Peach &amp; Pineapple Green Tea',\n text: 'Organic Mango Peach &amp; Pineapple Green Tea'},\n {value: 'Ginger Peach (Green)', text: 'Ginger Peach (Green)'},\n {value: 'Sweet Chai', text: 'Sweet Chai'},\n {value: 'Spiced Apple', text: 'Spiced Apple'},\n {value: 'Get Happy - No.13 (Wellness Collection)',\n text: 'Get Happy - No.13 (Wellness Collection)'},\n {value: 'Darjeeling-Ceylon Iced Tea Blend',\n text: 'Darjeeling-Ceylon Iced Tea Blend'},\n {value: 'Treasure of the Caribbean', text: 'Treasure of the Caribbean'},\n {value: 'Shikaicha - Signature Blend',\n text: 'Shikaicha - Signature Blend'},\n {value: 'Ice Wine Tea', text: 'Ice Wine Tea'},\n {value: 'Guava Cadabra', text: 'Guava Cadabra'},\n {value: 'Sencha Lemon', text: 'Sencha Lemon'},\n {value: 'Smooth Chai', text: 'Smooth Chai'},\n {value: 'Honey Orchid Black', text: 'Honey Orchid Black'},\n {value: 'Organic Green Breeze', text: 'Organic Green Breeze'},\n {value: 'Ti kuan yin', text: 'Ti kuan yin'},\n {value: 'Iced Tea', text: 'Iced Tea'},\n {value: 'Bourgeon de Thé au Jasmin', text: 'Bourgeon de Thé au Jasmin'},\n {value: 'Silver Tips White Tea', text: 'Silver Tips White Tea'},\n {value: 'Starter Matcha', text: 'Starter Matcha'},\n {value: 'Mountain Tea', text: 'Mountain Tea'},\n {value: 'High Mountain Green', text: 'High Mountain Green'},\n {value: 'Black Jasmine', text: 'Black Jasmine'},\n {value: 'Green Apple', text: 'Green Apple'},\n {value: 'Happiness Tea', text: 'Happiness Tea'},\n {value: 'Dark Tresure tea', text: 'Dark Tresure tea'},\n {value: 'Boston Tea Party Blend (Revolutionary Breakfast Tea)',\n text: 'Boston Tea Party Blend (Revolutionary Breakfast Tea)'},\n {value: 'Eat Pray Love - Blood Orange Cinnamon Tea',\n text: 'Eat Pray Love - Blood Orange Cinnamon Tea'},\n {value: 'Green Tea with Vanilla', text: 'Green Tea with Vanilla'},\n {value: 'Maofeng Noir Organic', text: 'Maofeng Noir Organic'},\n {value: 'Tangerine Orange Zinger', text: 'Tangerine Orange Zinger'},\n {value: 'Pomegranate Honeybush', text: 'Pomegranate Honeybush'},\n {value: '1960s Wuyi Shui Xian', text: '1960s Wuyi Shui Xian'},\n {value: 'Fuuki', text: 'Fuuki'},\n {value: 'Aquarius-The Zodiac Series-2012',\n text: 'Aquarius-The Zodiac Series-2012'},\n {value: 'Black Currant Cardamom Raw Green Bush Tea',\n text: 'Black Currant Cardamom Raw Green Bush Tea'},\n {value: 'Authentic Thai Iced Tea', text: 'Authentic Thai Iced Tea'},\n {value: 'Assam Mokalbari 2nd Flush SFTGFOP1',\n text: 'Assam Mokalbari 2nd Flush SFTGFOP1'},\n {value: 'Seasons Pick Yunnan FOP ZY06',\n text: 'Seasons Pick Yunnan FOP ZY06'},\n {value: 'Mangalam Assam TGFOP1', text: 'Mangalam Assam TGFOP1'},\n {value: 'China Jasmine Dragon Phoenix Pearl',\n text: 'China Jasmine Dragon Phoenix Pearl'},\n {value: 'Black Pearls', text: 'Black Pearls'},\n {value: 'Spiced Orange', text: 'Spiced Orange'},\n {value: 'Lavender Black Tea', text: 'Lavender Black Tea'},\n {value: 'Golden Monkey King of Black Tea',\n text: 'Golden Monkey King of Black Tea'},\n {value: 'Chamomile Mango', text: 'Chamomile Mango'},\n {value: 'Strawberry Rhubarb Crumble', text: 'Strawberry Rhubarb Crumble'},\n {value: '2012 Spring Nonpareil Mt. Wudong Song Variety Huang Zhi Xiang(Gardenia) Phoenix Dan Cong Oolong',\n text: '2012 Nonpareil Mt. Wudong Song Variety Huang Zhi Xiang(Gardenia) Oolong'},\n {value: 'Morning Sun', text: 'Morning Sun'},\n {value: 'Gold Thread', text: 'Gold Thread'},\n {value: '2011 EoT Guafengzhai', text: '2011 EoT Guafengzhai'},\n {value: 'Skala (Rooibos Berries)', text: 'Skala (Rooibos Berries)'},\n {value: 'Goût Russe Douchka', text: 'Goût Russe Douchka'},\n {value: 'Organic Yerba Mate Loose', text: 'Organic Yerba Mate Loose'},\n {value: 'Korean Ginseng Tea', text: 'Korean Ginseng Tea'},\n {value: 'Chai Indienne', text: 'Chai Indienne'},\n {value: 'Black Tea with Lemon (Lemon Twist)',\n text: 'Black Tea with Lemon (Lemon Twist)'},\n {value: 'Laoshan Village Chai', text: 'Laoshan Village Chai'},\n {value: 'Caramel Apple Delight', text: 'Caramel Apple Delight'},\n {value: 'Yellow Label', text: 'Yellow Label'},\n {value: 'Regents Park', text: 'Regents Park'},\n {value: 'Smokey Grey', text: 'Smokey Grey'},\n {value: 'Anxi Monkey King (Ma Liu Mie) Tie Guan Yin Oolong Tea',\n text: 'Anxi Monkey King (Ma Liu Mie) Tie Guan Yin Oolong Tea'},\n {value: 'Goji-Blueberry Pomegranate', text: 'Goji-Blueberry Pomegranate'},\n {value: 'White Persian Melon', text: 'White Persian Melon'},\n {value: 'Black and Blue', text: 'Black and Blue'},\n {value: 'Lady Grey Decaffeinated', text: 'Lady Grey Decaffeinated'},\n {value: 'Queen Catherine', text: 'Queen Catherine'},\n {value: 'Mudslide', text: 'Mudslide'},\n {value: 'CinnaZing', text: 'CinnaZing'},\n {value: 'Chamomile and Lavender', text: 'Chamomile and Lavender'},\n {value: 'Lapsang Souchong (Pine Smoked Black) (organic)',\n text: 'Lapsang Souchong (Pine Smoked Black) (organic)'},\n {value: 'Snow White Needle', text: 'Snow White Needle'},\n {value: 'Darjeeling 2nd Flush Muscatel',\n text: 'Darjeeling 2nd Flush Muscatel'},\n {value: 'Raspberry Lychee', text: 'Raspberry Lychee'},\n {value: '2000 Old Tree mini puer ripe',\n text: '2000 Old Tree mini puer ripe'},\n {value: 'PBJ Rooibos', text: 'PBJ Rooibos'},\n {value: 'Strawberry Hibiscus ', text: 'Strawberry Hibiscus '},\n {value: 'Organic Dehydrated Camellia',\n text: 'Organic Dehydrated Camellia'},\n {value: 'Orange Dulce de Leche', text: 'Orange Dulce de Leche'},\n {value: 'Leipziger Sommertraum', text: 'Leipziger Sommertraum'},\n {value: 'China Green', text: 'China Green'},\n {value: 'Spring Harvest', text: 'Spring Harvest'},\n {value: 'Milk Oolong-Goldfish Tea', text: 'Milk Oolong-Goldfish Tea'},\n {value: 'Mint Fusion Organic', text: 'Mint Fusion Organic'},\n {value: 'Blackcurrant Breeze', text: 'Blackcurrant Breeze'},\n {value: 'Davids Green Tea Private Reserve',\n text: 'Davids Green Tea Private Reserve'},\n {value: 'Li Shan Da Yu Ling Jade Oolong',\n text: 'Li Shan Da Yu Ling Jade Oolong'},\n {value: '2005 Jinuo Shan You Le Red Sun Drum Pu-erh tea',\n text: '2005 Jinuo Shan You Le Red Sun Drum Pu-erh tea'},\n {value: 'Red Rooibos', text: 'Red Rooibos'},\n {value: 'Monk Pear', text: 'Monk Pear'},\n {value: 'Gunpowder Mint - Pinhead', text: 'Gunpowder Mint - Pinhead'},\n {value: 'Lemon Basil Oolong', text: 'Lemon Basil Oolong'},\n {value: 'Coconut Banana Cream Pie Hojicha',\n text: 'Coconut Banana Cream Pie Hojicha'},\n {value: '1970s ZhiYe Loose leaf sheng puerh 100g',\n text: '1970s ZhiYe Loose leaf sheng puerh 100g'},\n {value: 'Organic Dragonwell', text: 'Organic Dragonwell'},\n {value: '甘露 (Kanrou)', text: '甘露 (Kanrou)'},\n {value: 'Puerh Tuo-Cha', text: 'Puerh Tuo-Cha'},\n {value: 'Green Tea Lemongrass', text: 'Green Tea Lemongrass'},\n {value: 'Rooibos Vanilla Chai', text: 'Rooibos Vanilla Chai'},\n {value: 'Rooibos de Provence', text: 'Rooibos de Provence'},\n {value: 'Matcha Latte', text: 'Matcha Latte'},\n {value: 'Nepal Ilam Mao Feng', text: 'Nepal Ilam Mao Feng'},\n {value: 'Blueberry Cocktail', text: 'Blueberry Cocktail'},\n {value: 'Fragrant Jasmine Green', text: 'Fragrant Jasmine Green'},\n {value: 'Get Gorgeous', text: 'Get Gorgeous'},\n {value: 'Trà Atisô', text: 'Trà Atisô'},\n {value: 'Wissotzky Classic', text: 'Wissotzky Classic'},\n {value: '2012 First Flush Arya FTGFOP1',\n text: '2012 First Flush Arya FTGFOP1'},\n {value: 'Mélange Hédiard', text: 'Mélange Hédiard'},\n {value: 'Get Active', text: 'Get Active'},\n {value: 'Barooti Gulabi', text: 'Barooti Gulabi'},\n {value: 'Nine Bend Black Dragon', text: 'Nine Bend Black Dragon'},\n {value: 'Badamtam First Flush (2012)',\n text: 'Badamtam First Flush (2012)'},\n {value: 'Summer Blackberry', text: 'Summer Blackberry'},\n {value: 'Assam Ramanugger Estate FTGFOP',\n text: 'Assam Ramanugger Estate FTGFOP'},\n {value: 'Ying Ming Yunnan', text: 'Ying Ming Yunnan'},\n {value: 'Velvet Tea', text: 'Velvet Tea'},\n {value: 'Cherry Oh Baby', text: 'Cherry Oh Baby'},\n {value: 'Rooibos Spices', text: 'Rooibos Spices'},\n {value: 'The Irishman by Kristina Moy',\n text: 'The Irishman by Kristina Moy'},\n {value: '2011 Bao Zhong Roasted No. 10',\n text: '2011 Bao Zhong Roasted No. 10'},\n {value: 'Lemon Grass Chai', text: 'Lemon Grass Chai'},\n {value: 'Echinacea Complete Care', text: 'Echinacea Complete Care'},\n {value: 'Chocolate Mint Flavored Black Tea',\n text: 'Chocolate Mint Flavored Black Tea'},\n {value: 'Coconut Cheesecake Honeybush',\n text: 'Coconut Cheesecake Honeybush'},\n {value: 'Organic Mango Ceylon', text: 'Organic Mango Ceylon'},\n {value: 'Lemon Mate Delight', text: 'Lemon Mate Delight'},\n {value: 'Organic GABA Oolong', text: 'Organic GABA Oolong'},\n {value: 'Apple Pomegranate', text: 'Apple Pomegranate'},\n {value: 'Butter Truffles', text: 'Butter Truffles'},\n {value: 'Vanilla Comoro', text: 'Vanilla Comoro'},\n {value: 'Keemun Black Tea – Grade 1', text: 'Keemun Black Tea – Grade 1'},\n {value: 'Anhui Emerald Seed', text: 'Anhui Emerald Seed'},\n {value: 'Decaf Tropics', text: 'Decaf Tropics'},\n {value: 'Banana Split Flavored Black',\n text: 'Banana Split Flavored Black'},\n {value: 'Pina Colada Matcha', text: 'Pina Colada Matcha'},\n {value: 'Maharaja Chai Oolong', text: 'Maharaja Chai Oolong'},\n {value: 'Cabernet Sauvignon', text: 'Cabernet Sauvignon'},\n {value: 'Coconut Cream Chai', text: 'Coconut Cream Chai'},\n {value: 'Egyptian Ruby', text: 'Egyptian Ruby'},\n {value: 'Irish Breakfast Tea', text: 'Irish Breakfast Tea'},\n {value: 'chamomile', text: 'chamomile'},\n {value: 'China Rose Petal Leaf Tea', text: 'China Rose Petal Leaf Tea'},\n {value: 'Gogo Geisha', text: 'Gogo Geisha'},\n {value: 'Lavender Lemon Chiffon', text: 'Lavender Lemon Chiffon'},\n {value: 'Slimming Tea', text: 'Slimming Tea'},\n {value: 'Coconut Mango Colada', text: 'Coconut Mango Colada'},\n {value: 'Nepal Himalayan Orange (SFTGFOP1) Jun Chiyabari First Flush',\n text: 'Nepal Himalayan Orange (SFTGFOP1) Jun Chiyabari First Flush'},\n {value: 'Organic Decaf Masala Chai', text: 'Organic Decaf Masala Chai'},\n {value: 'Private Reserve Matcha A23', text: 'Private Reserve Matcha A23'},\n {value: 'House Black', text: 'House Black'},\n {value: 'Ruby Red Chai Tea', text: 'Ruby Red Chai Tea'},\n {value: 'Sandkuphu Silver Tips', text: 'Sandkuphu Silver Tips'},\n {value: 'Yunnan Emerald Buds', text: 'Yunnan Emerald Buds'},\n {value: 'Houjicha - Dark Roast', text: 'Houjicha - Dark Roast'},\n {value: 'House Blend', text: 'House Blend'},\n {value: 'Cambridge Summer Blend', text: 'Cambridge Summer Blend'},\n {value: '2003 Yiwu Zhengshan Old Tree',\n text: '2003 Yiwu Zhengshan Old Tree'},\n {value: 'Jinjaa Citrus Twist', text: 'Jinjaa Citrus Twist'},\n {value: 'Formosa Tung-Ting Jade Oolong (TT86)',\n text: 'Formosa Tung-Ting Jade Oolong (TT86)'},\n {value: 'DMS Bai Yai Oolong Tea', text: 'DMS Bai Yai Oolong Tea'},\n {value: 'Supreme Pu Er 1990', text: 'Supreme Pu Er 1990'},\n {value: 'Huang Shan Mao Feng 黄山毛峰 Grade 1 from Spring 2010 harvest',\n text: 'Huang Shan Mao Feng 黄山毛峰 Grade 1 from Spring 2010 harvest'},\n {value: 'gold tea', text: 'gold tea'},\n {value: 'Goji', text: 'Goji'},\n {value: 'Rhaegals Fire', text: 'Rhaegals Fire'},\n {value: 'Green Peach', text: 'Green Peach'},\n {value: 'Rooibos Cream', text: 'Rooibos Cream'},\n {value: 'Gyokuro Kuradashi Vintage 2005',\n text: 'Gyokuro Kuradashi Vintage 2005'},\n {value: 'Mango Magic', text: 'Mango Magic'},\n {value: 'Devonshire Earl Grey TE19', text: 'Devonshire Earl Grey TE19'},\n {value: 'Fujian Congou Black Tea', text: 'Fujian Congou Black Tea'},\n {value: 'Butternut Toffee Rooibos', text: 'Butternut Toffee Rooibos'},\n {value: 'Aged Wenshan Baozhong ca. 1982',\n text: 'Aged Wenshan Baozhong ca. 1982'},\n {value: '2009 Lao Ban Zhang Premium Raw Pu-erh tea cake',\n text: '2009 Lao Ban Zhang Premium Raw Pu-erh tea cake'},\n {value: 'Mi Lan Xiang Feng Xi', text: 'Mi Lan Xiang Feng Xi'},\n {value: 'Ten Li (Tianli)', text: 'Ten Li (Tianli)'},\n {value: 'Superberry Cacao Berry Tea', text: 'Superberry Cacao Berry Tea'},\n {value: 'Cinnamon Orange Spice', text: 'Cinnamon Orange Spice'},\n {value: 'Star Empress', text: 'Star Empress'},\n {value: 'Rose With French Vanilla', text: 'Rose With French Vanilla'},\n {value: 'Yunnan Phoenix Puer Tuo Cha',\n text: 'Yunnan Phoenix Puer Tuo Cha'},\n {value: 'Pu-erh A', text: 'Pu-erh A'},\n {value: 'Ceylon Organic', text: 'Ceylon Organic'},\n {value: 'Spice imperial', text: 'Spice imperial'},\n {value: 'Pai Mu Tan Grapefruit', text: 'Pai Mu Tan Grapefruit'},\n {value: 'Pu-erh Chai', text: 'Pu-erh Chai'},\n {value: 'Tea Tongue', text: 'Tea Tongue'},\n {value: 'Feeling Calm - Camomile Citrus Herbal Tea',\n text: 'Feeling Calm - Camomile Citrus Herbal Tea'},\n {value: 'Pumpkin Spice Rooibos', text: 'Pumpkin Spice Rooibos'},\n {value: 'Shamrock Tea', text: 'Shamrock Tea'},\n {value: 'Cocoa Chai Tea', text: 'Cocoa Chai Tea'},\n {value: 'Premium Silky Green Tea', text: 'Premium Silky Green Tea'},\n {value: 'My Morning Mate', text: 'My Morning Mate'},\n {value: 'Eves Garden', text: 'Eves Garden'},\n {value: '2011 Tie Guan Yin Oolong 20g',\n text: '2011 Tie Guan Yin Oolong 20g'},\n {value: 'Cranberry Spice Black Tea', text: 'Cranberry Spice Black Tea'},\n {value: 'Summer Apricot Ceylon', text: 'Summer Apricot Ceylon'},\n {value: 'Northern Lights', text: 'Northern Lights'},\n {value: 'Maine Teaberry Tea', text: 'Maine Teaberry Tea'},\n {value: 'Cleansing', text: 'Cleansing'},\n {value: 'Gingers Oolong', text: 'Gingers Oolong'},\n {value: 'Berry Chocolate', text: 'Berry Chocolate'},\n {value: 'Batman (Fandom blend)', text: 'Batman (Fandom blend)'},\n {value: 'Darjeeling Fancy Oolong with Velvet Buds Singell',\n text: 'Darjeeling Fancy Oolong with Velvet Buds Singell'},\n {value: 'Phuguri Estate First Flush Darjeeling SFTGFOP1 (DJ-22)',\n text: 'Phuguri Estate First Flush Darjeeling SFTGFOP1 (DJ-22)'},\n {value: 'Jasmine Superior Molin Hua Dragon Pearls',\n text: 'Jasmine Superior Molin Hua Dragon Pearls'},\n {value: '2011 Bai Hao', text: '2011 Bai Hao'},\n {value: 'Select Estate Java BOP Blend (TB15)',\n text: 'Select Estate Java BOP Blend (TB15)'},\n {value: '2011 Spring Lapsang Souchong - HeGan',\n text: '2011 Spring Lapsang Souchong - HeGan'},\n {value: 'Vietnam Yen Bai OP - 870', text: 'Vietnam Yen Bai OP - 870'},\n {value: 'After Lunch', text: 'After Lunch'},\n {value: 'American Ginseng tea', text: 'American Ginseng tea'},\n {value: 'Olive Leaf Green', text: 'Olive Leaf Green'},\n {value: 'Vanilla Spring Fruit Tea', text: 'Vanilla Spring Fruit Tea'},\n {value: 'Voyage African tunda', text: 'Voyage African tunda'},\n {value: 'Ginger Peach Green', text: 'Ginger Peach Green'},\n {value: 'Nettle &amp; Sweet Fennel', text: 'Nettle &amp; Sweet Fennel'},\n {value: 'Tropical Goji Green', text: 'Tropical Goji Green'},\n {value: 'Jasmine Dragon Phoenix Pearls with Rooibos Tropica',\n text: 'Jasmine Dragon Phoenix Pearls with Rooibos Tropica'},\n {value: 'Tama Ryokucha', text: 'Tama Ryokucha'},\n {value: 'Bavarian Wild Berry', text: 'Bavarian Wild Berry'},\n {value: 'Sei Mee', text: 'Sei Mee'},\n {value: 'Tencha Chiyo no Sakae', text: 'Tencha Chiyo no Sakae'},\n {value: 'Orange Pekoe tagless tea bags',\n text: 'Orange Pekoe tagless tea bags'},\n {value: 'Berry Refreshing', text: 'Berry Refreshing'},\n {value: 'Jasmine Silver Needle White Tea',\n text: 'Jasmine Silver Needle White Tea'},\n {value: 'Dirty Chai', text: 'Dirty Chai'},\n {value: 'Japanese Sour Cherry', text: 'Japanese Sour Cherry'},\n {value: 'Sencha Green Tealeaf Powder',\n text: 'Sencha Green Tealeaf Powder'},\n {value: 'Tulsi Mint', text: 'Tulsi Mint'},\n {value: 'organic five peaks green dew',\n text: 'organic five peaks green dew'},\n {value: 'Sencha Sakura (FG08)', text: 'Sencha Sakura (FG08)'},\n {value: 'Dream of Fruits', text: 'Dream of Fruits'},\n {value: 'Je Mappelle Dorothee', text: 'Je Mappelle Dorothee'},\n {value: 'Maple Apple Cider', text: 'Maple Apple Cider'},\n {value: 'Orange-Chili Rooibos', text: 'Orange-Chili Rooibos'},\n {value: 'Baroness Grey', text: 'Baroness Grey'},\n {value: 'Phoenix Single Grove Honey Fragrance Oolong',\n text: 'Phoenix Single Grove Honey Fragrance Oolong'},\n {value: 'Organic Kyoto Cherry Rose', text: 'Organic Kyoto Cherry Rose'},\n {value: 'Aged Earl Grey', text: 'Aged Earl Grey'},\n {value: 'Organic Long Jing', text: 'Organic Long Jing'},\n {value: 'Superfruits Pomegranate &amp; Raspberry',\n text: 'Superfruits Pomegranate &amp; Raspberry'},\n {value: 'Pot O Gold', text: 'Pot O Gold'},\n {value: 'Ceylon Kenilworth', text: 'Ceylon Kenilworth'},\n {value: 'Samovar', text: 'Samovar'},\n {value: '2011 Ali Shan Zin Hsuan', text: '2011 Ali Shan Zin Hsuan'},\n {value: 'Colonille', text: 'Colonille'},\n {value: 'Iyemon Cha', text: 'Iyemon Cha'},\n {value: 'Queens Apple', text: 'Queens Apple'},\n {value: 'Matcha Genmaicha Green Tea Blend',\n text: 'Matcha Genmaicha Green Tea Blend'},\n {value: 'Earl Grey French Blue', text: 'Earl Grey French Blue'},\n {value: 'Rise N Shine', text: 'Rise N Shine'},\n {value: 'Oriental Beauty (Bai Hao Oolong)',\n text: 'Oriental Beauty (Bai Hao Oolong)'},\n {value: 'Lemon Lift', text: 'Lemon Lift'},\n {value: 'Chamomile and Yun Wu Green Tea Blend',\n text: 'Chamomile and Yun Wu Green Tea Blend'},\n {value: 'Verbena Mint Organic', text: 'Verbena Mint Organic'},\n {value: 'Lemon Zinger Green Tea', text: 'Lemon Zinger Green Tea'},\n {value: 'Daily Beauty Tea', text: 'Daily Beauty Tea'},\n {value: 'Sakura Sencha (cherry)', text: 'Sakura Sencha (cherry)'},\n {value: 'Kenyan Black Tea', text: 'Kenyan Black Tea'},\n {value: 'Kalami Assam', text: 'Kalami Assam'},\n {value: 'Dragon Balls (Long Qui)', text: 'Dragon Balls (Long Qui)'},\n {value: '2010 Menghai Dayi Yunding Ripe',\n text: '2010 Menghai Dayi Yunding Ripe'},\n {value: 'White Berry', text: 'White Berry'},\n {value: '4 Fruits Rouges', text: '4 Fruits Rouges'},\n {value: 'Peppermint Bark Herbal', text: 'Peppermint Bark Herbal'},\n {value: 'Black Dragon Pearl', text: 'Black Dragon Pearl'},\n {value: 'Pure Rooibos', text: 'Pure Rooibos'},\n {value: '1988 Taiwan Oolong', text: '1988 Taiwan Oolong'},\n {value: 'Yong Chun Fo Shou', text: 'Yong Chun Fo Shou'},\n {value: 'Pomegranate Raspberry Green',\n text: 'Pomegranate Raspberry Green'},\n {value: 'Four Season Oolong', text: 'Four Season Oolong'},\n {value: 'Goji Berry Green Tea with Matcha',\n text: 'Goji Berry Green Tea with Matcha'},\n {value: 'Sen Cha Fukamushi', text: 'Sen Cha Fukamushi'},\n {value: 'Matcha Green Tea Powder', text: 'Matcha Green Tea Powder'},\n {value: 'Morocco Mint and Spices', text: 'Morocco Mint and Spices'},\n {value: 'Goodnight Tea', text: 'Goodnight Tea'},\n {value: 'Yunnan Golden Tips (Dian Hong)',\n text: 'Yunnan Golden Tips (Dian Hong)'},\n {value: 'Singtom Estate Darjeeling 2nd Flush',\n text: 'Singtom Estate Darjeeling 2nd Flush'},\n {value: 'Skinny Chai Pu-erh', text: 'Skinny Chai Pu-erh'},\n {value: 'Green Tea Opuncia', text: 'Green Tea Opuncia'},\n {value: 'Rare Hou Shan Huang', text: 'Rare Hou Shan Huang'},\n {value: 'Arya Pearl Darjeeling First Flush 2012',\n text: 'Arya Pearl Darjeeling First Flush 2012'},\n {value: 'Marzipan Rooibostee', text: 'Marzipan Rooibostee'},\n {value: 'Yutaka Midori (Shincha 09)', text: 'Yutaka Midori (Shincha 09)'},\n {value: 'Houjicha Tea Bags', text: 'Houjicha Tea Bags'},\n {value: 'The Staunton Earl Grey', text: 'The Staunton Earl Grey'},\n {value: 'Just Peppermint', text: 'Just Peppermint'},\n {value: 'organic english breakfast', text: 'organic english breakfast'},\n {value: 'Nilagama Estate', text: 'Nilagama Estate'},\n {value: 'Peppermint Guayusa', text: 'Peppermint Guayusa'},\n {value: 'Safari Spice Red Tea', text: 'Safari Spice Red Tea'},\n {value: 'Blue Ginger', text: 'Blue Ginger'},\n {value: 'Creamsicle', text: 'Creamsicle'},\n {value: 'Chai Guarana', text: 'Chai Guarana'},\n {value: 'Apple Banana Chamomile Tea', text: 'Apple Banana Chamomile Tea'},\n {value: 'Hippy Redhead', text: 'Hippy Redhead'},\n {value: 'Imperial Acai Blueberry White Tea',\n text: 'Imperial Acai Blueberry White Tea'},\n {value: 'Gold Sen-Cha (Traditional Series)',\n text: 'Gold Sen-Cha (Traditional Series)'},\n {value: '2010 Douji Pure Series Nan Nuo Raw Puerh Tea Brick',\n text: '2010 Douji Pure Series Nan Nuo Raw Puerh Tea Brick'},\n {value: 'Vihreä Jasmiini - Green Jasmine Tea',\n text: 'Vihreä Jasmiini - Green Jasmine Tea'},\n {value: 'Yellow Label Loose Tea', text: 'Yellow Label Loose Tea'},\n {value: 'Golden Dragon Aged', text: 'Golden Dragon Aged'},\n {value: '2007 Winter Feng Huang Wu Dong Old Bush Dan Cong Ba Xian',\n text: '2007 Winter Feng Huang Wu Dong Old Bush Dan Cong Ba Xian'},\n {value: 'Chai Apricot', text: 'Chai Apricot'},\n {value: 'Zocolatte Spice Herbal Tea', text: 'Zocolatte Spice Herbal Tea'},\n {value: 'Lady Hannahs Whole Fruit', text: 'Lady Hannahs Whole Fruit'},\n {value: 'Lemon Meringue', text: 'Lemon Meringue'},\n {value: 'Bing Cherry Vanilla', text: 'Bing Cherry Vanilla'},\n {value: '2012 Ruiyuan NanNuo Old Arbor',\n text: '2012 Ruiyuan NanNuo Old Arbor'},\n {value: 'Accidental Awesome', text: 'Accidental Awesome'},\n {value: 'Bora Bora', text: 'Bora Bora'},\n {value: 'Premium blend Darjeeling first flush',\n text: 'Premium blend Darjeeling first flush'},\n {value: 'Tawaramine Shincha', text: 'Tawaramine Shincha'},\n {value: 'Darjeeling Margarets Hope 2nd Flush',\n text: 'Darjeeling Margarets Hope 2nd Flush'},\n {value: 'Sparkling Green Tea Strawberry-Kiwi',\n text: 'Sparkling Green Tea Strawberry-Kiwi'},\n {value: 'Fair Trade Pomegranate White tea',\n text: 'Fair Trade Pomegranate White tea'},\n {value: 'Menghai 7262', text: 'Menghai 7262'},\n {value: 'Cardamon', text: 'Cardamon'},\n {value: 'Xi-Zhi Hao 2007 Classic 7542 Raw',\n text: 'Xi-Zhi Hao 2007 Classic 7542 Raw'},\n {value: '2009 Yunnan Menghai Red Aura Round',\n text: '2009 Yunnan Menghai Red Aura Round'},\n {value: 'Darjeeling Margarets Hope Second Flush',\n text: 'Darjeeling Margarets Hope Second Flush'},\n {value: 'Pure White Tea with Cranberry',\n text: 'Pure White Tea with Cranberry'},\n {value: 'Liu Family White Tea from 800yo Wild Tea Trees',\n text: 'Liu Family White Tea from 800yo Wild Tea Trees'},\n {value: 'Matcha Premium', text: 'Matcha Premium'},\n {value: 'ZG53: Yunnan Silvertip Green Tea',\n text: 'ZG53: Yunnan Silvertip Green Tea'},\n {value: 'darjeeling 1st flush 2008 ftgfop 1',\n text: 'darjeeling 1st flush 2008 ftgfop 1'},\n {value: 'Gibraltar', text: 'Gibraltar'},\n {value: 'Rainforest Chai', text: 'Rainforest Chai'},\n {value: 'Osthmanthus Silver Needle', text: 'Osthmanthus Silver Needle'},\n {value: '2003 CNNP Mengsong Qiao Mu Iron Cake Raw Puerh',\n text: '2003 CNNP Mengsong Qiao Mu Iron Cake Raw Puerh'},\n {value: 'Espresso Yourself (organic)',\n text: 'Espresso Yourself (organic)'},\n {value: 'Diamond Jubilee', text: 'Diamond Jubilee'},\n {value: 'Matcha Powder - DUPLICATE', text: 'Matcha Powder - DUPLICATE'},\n {value: 'Alishan Jin Xuan Taiwan Oolong 2008',\n text: 'Alishan Jin Xuan Taiwan Oolong 2008'},\n {value: 'Hubei Province Keemun Ji Hong (ZK22)',\n text: 'Hubei Province Keemun Ji Hong (ZK22)'},\n {value: 'Wellness Tea', text: 'Wellness Tea'},\n {value: 'Xiao Hong Pao', text: 'Xiao Hong Pao'},\n {value: 'Soft Branch', text: 'Soft Branch'},\n {value: 'Supreme Dong Ding oolong', text: 'Supreme Dong Ding oolong'},\n {value: 'Punkin Spice - Signature Blend',\n text: 'Punkin Spice - Signature Blend'},\n {value: 'No. 39 Fez', text: 'No. 39 Fez'},\n {value: 'peony lychee white', text: 'peony lychee white'},\n {value: 'Strawberry Rhubarb', text: 'Strawberry Rhubarb'},\n {value: 'Organic Dong Ding Oolong', text: 'Organic Dong Ding Oolong'},\n {value: 'TA20: Tippy Orthodox FBOP Assam',\n text: 'TA20: Tippy Orthodox FBOP Assam'},\n {value: 'Assam Superb Tea', text: 'Assam Superb Tea'},\n {value: 'Sherlock Holmes (Blend)', text: 'Sherlock Holmes (Blend)'},\n {value: 'Good Hope Vanilla (Red)', text: 'Good Hope Vanilla (Red)'},\n {value: 'Kashmir Rose', text: 'Kashmir Rose'},\n {value: 'Republic Green Chai', text: 'Republic Green Chai'},\n {value: 'Chili Kakao Tee', text: 'Chili Kakao Tee'},\n {value: 'Oolong Magnolia', text: 'Oolong Magnolia'},\n {value: 'Numalighur Assam', text: 'Numalighur Assam'},\n {value: 'Medium Roast Ali Shan Oolong Winter 2008',\n text: 'Medium Roast Ali Shan Oolong Winter 2008'},\n {value: 'Green tea with orange papaya melon aloe vera.',\n text: 'Green tea with orange papaya melon aloe vera.'},\n {value: 'Iron Arhat Oolong Tea (Wuyi Tie Luo Han Wu Long)',\n text: 'Iron Arhat Oolong Tea (Wuyi Tie Luo Han Wu Long)'},\n {value: 'Organic Black Iced', text: 'Organic Black Iced'},\n {value: '2010 Hong Shang Dou', text: '2010 Hong Shang Dou'},\n {value: 'Lemon - AID', text: 'Lemon - AID'},\n {value: 'Chinese Breakfast Yunnan Black Tea',\n text: 'Chinese Breakfast Yunnan Black Tea'},\n {value: 'Apple Black Tea', text: 'Apple Black Tea'},\n {value: 'Ginger Ale Bai Mu Dan', text: 'Ginger Ale Bai Mu Dan'},\n {value: 'Sencha Shin-ryoku', text: 'Sencha Shin-ryoku'},\n {value: 'Mint Chocolate Matcha', text: 'Mint Chocolate Matcha'},\n {value: 'Razzleberry Flavored Black', text: 'Razzleberry Flavored Black'},\n {value: 'Fleurilège', text: 'Fleurilège'},\n {value: 'Darjeeling Pussimbing Estate Reserve',\n text: 'Darjeeling Pussimbing Estate Reserve'},\n {value: 'Bali Black Raspberry', text: 'Bali Black Raspberry'},\n {value: 'Sunday Morning', text: 'Sunday Morning'},\n {value: 'Ginger Snappish', text: 'Ginger Snappish'},\n {value: 'Pure Indian Zarin Tippy Kalmi',\n text: 'Pure Indian Zarin Tippy Kalmi'},\n {value: 'Thé des Moines', text: 'Thé des Moines'},\n {value: '100 gram Haiwan Ripe Square Brick - 2009',\n text: '100 gram Haiwan Ripe Square Brick - 2009'},\n {value: 'Assam Salonah TGFOP (246)', text: 'Assam Salonah TGFOP (246)'},\n {value: 'Earl Grey De La Cream', text: 'Earl Grey De La Cream'},\n {value: '2008 Makaibari Estate Standard - second flush',\n text: '2008 Makaibari Estate Standard - second flush'},\n {value: 'Afternoon Blend with Bergamot',\n text: 'Afternoon Blend with Bergamot'},\n {value: 'Cream of Earl Grey', text: 'Cream of Earl Grey'},\n {value: 'Tung Ting Vietnam', text: 'Tung Ting Vietnam'},\n {value: 'Water Sprite (Shui Xian)', text: 'Water Sprite (Shui Xian)'},\n {value: 'Okuyutaka Shincha', text: 'Okuyutaka Shincha'},\n {value: '2009 Wuliang Wild Puerh Sheng',\n text: '2009 Wuliang Wild Puerh Sheng'},\n {value: 'Black Currant Papaya Green Tea',\n text: 'Black Currant Papaya Green Tea'},\n {value: 'Pyramid Teabags', text: 'Pyramid Teabags'},\n {value: 'Tie Kuan Yin', text: 'Tie Kuan Yin'},\n {value: 'Rooibos Quince', text: 'Rooibos Quince'},\n {value: 'Master Hans Wild Picked Yunnan Black',\n text: 'Master Hans Wild Picked Yunnan Black'},\n {value: 'Tropical Grapefruit Green Tea',\n text: 'Tropical Grapefruit Green Tea'},\n {value: 'Pu Erh Spice', text: 'Pu Erh Spice'},\n {value: 'SIKKIM S.F.T.G.F.O.P.1 2nd flush TEMI',\n text: 'SIKKIM S.F.T.G.F.O.P.1 2nd flush TEMI'},\n {value: 'Cherry Potion', text: 'Cherry Potion'},\n {value: 'Black tea', text: 'Black tea'},\n {value: 'Apricot Blossom Green Tea', text: 'Apricot Blossom Green Tea'},\n {value: 'Organic Iced Green Tea', text: 'Organic Iced Green Tea'},\n {value: 'Assam Supreme Tonganagaon', text: 'Assam Supreme Tonganagaon'},\n {value: 'Man Behind the Green Curtain',\n text: 'Man Behind the Green Curtain'},\n {value: 'Gypsy Rose Black', text: 'Gypsy Rose Black'},\n {value: 'China Pu Erh Tuo Cha (Birds Nest)',\n text: 'China Pu Erh Tuo Cha (Birds Nest)'},\n {value: 'Sencha Caramel', text: 'Sencha Caramel'},\n {value: 'True Blueberry', text: 'True Blueberry'},\n {value: 'Strong Breakfast', text: 'Strong Breakfast'},\n {value: 'Chunmee Eyebrow', text: 'Chunmee Eyebrow'},\n {value: 'cranberry punch', text: 'cranberry punch'},\n {value: 'Zen Iced Green Tea', text: 'Zen Iced Green Tea'},\n {value: 'Quangzhou Milky Oolong', text: 'Quangzhou Milky Oolong'},\n {value: 'Feng Huang Hong Cha', text: 'Feng Huang Hong Cha'},\n {value: 'Hulu Green', text: 'Hulu Green'},\n {value: 'Aussie Spiced Chai', text: 'Aussie Spiced Chai'},\n {value: 'Ceylon Dimbulla OP', text: 'Ceylon Dimbulla OP'},\n {value: 'Harvest Moon', text: 'Harvest Moon'},\n {value: 'black fruits pai mu tan', text: 'black fruits pai mu tan'},\n {value: 'Green Tea with Spearmint (Thé Nanah à la menthe)',\n text: 'Green Tea with Spearmint (Thé Nanah à la menthe)'},\n {value: 'Papaya and Passion Fruit Green Tea',\n text: 'Papaya and Passion Fruit Green Tea'},\n {value: 'Kashmiri Spice Chai', text: 'Kashmiri Spice Chai'},\n {value: 'Green Spring', text: 'Green Spring'},\n {value: '250 gram Haiwan 7588 Brick - 2007',\n text: '250 gram Haiwan 7588 Brick - 2007'},\n {value: 'Classic Chai Cinnamon Spice - Organic',\n text: 'Classic Chai Cinnamon Spice - Organic'},\n {value: 'Darjeeling The First Flush', text: 'Darjeeling The First Flush'},\n {value: 'Sweet Tangerine Positive Energy',\n text: 'Sweet Tangerine Positive Energy'},\n {value: 'Green Tea with Lemongrass and Verbena',\n text: 'Green Tea with Lemongrass and Verbena'},\n {value: 'Chamong SFTGFOP1 Tippy 131', text: 'Chamong SFTGFOP1 Tippy 131'},\n {value: 'ARYA Rose dHimalaya SFTGFOP1',\n text: 'ARYA Rose dHimalaya SFTGFOP1'},\n {value: 'Te Med Blåbärssmak', text: 'Te Med Blåbärssmak'},\n {value: 'Celebration Ceylon', text: 'Celebration Ceylon'},\n {value: '2004 Nanjian Phoenix Superior Grade Yunnan Tuocha',\n text: '2004 Nanjian Phoenix Superior Grade Yunnan Tuocha'},\n {value: 'Pomegranate Hibiscus Green', text: 'Pomegranate Hibiscus Green'},\n {value: 'Seogwang Wulong', text: 'Seogwang Wulong'},\n {value: 'Anji Baicha', text: 'Anji Baicha'},\n {value: 'Thé de Lune', text: 'Thé de Lune'},\n {value: 'Earl Grey Fleurs Blanches', text: 'Earl Grey Fleurs Blanches'},\n {value: 'Dae-Jak Korean Green Tea TR55',\n text: 'Dae-Jak Korean Green Tea TR55'},\n {value: 'Rosehip &amp; Cherry with Hibiscus',\n text: 'Rosehip &amp; Cherry with Hibiscus'},\n {value: 'Liliuokalani', text: 'Liliuokalani'},\n {value: 'Soba Seed Stem', text: 'Soba Seed Stem'},\n {value: 'Southern Style Sweet Tea', text: 'Southern Style Sweet Tea'},\n {value: 'White Needle', text: 'White Needle'},\n {value: 'Yunnan Hongcha', text: 'Yunnan Hongcha'},\n {value: 'Funding Wild Curly - leaf from wild bushes',\n text: 'Funding Wild Curly - leaf from wild bushes'},\n {value: 'Southern Belle', text: 'Southern Belle'},\n {value: 'Tie Guan Yin Sup. 2010', text: 'Tie Guan Yin Sup. 2010'},\n {value: 'Hunan Hong Cha', text: 'Hunan Hong Cha'},\n {value: 'Graveyard Mist', text: 'Graveyard Mist'},\n {value: 'Wild Orchid Pearl Oolong', text: 'Wild Orchid Pearl Oolong'},\n {value: 'TB05: Mincing Lane Breakfast Blend',\n text: 'TB05: Mincing Lane Breakfast Blend'},\n {value: 'Menghai 7572 80s vintage', text: 'Menghai 7572 80s vintage'},\n {value: 'Li Li Xiang Anxi Oolong (Organic)',\n text: 'Li Li Xiang Anxi Oolong (Organic)'},\n {value: 'Peach Blossom Oolong', text: 'Peach Blossom Oolong'},\n {value: 'Choconut Oolong', text: 'Choconut Oolong'},\n {value: 'Jubilee', text: 'Jubilee'},\n {value: 'Keemun Special Leaf Tea', text: 'Keemun Special Leaf Tea'},\n {value: 'Organic Bolivian Green Tea', text: 'Organic Bolivian Green Tea'},\n {value: 'Royal Air Force', text: 'Royal Air Force'},\n {value: 'Organic Mint Chocolate Rooibos',\n text: 'Organic Mint Chocolate Rooibos'},\n {value: 'Smoky Bacon', text: 'Smoky Bacon'},\n {value: 'Good Medicine', text: 'Good Medicine'},\n {value: 'Chocolate Mint Black Tea', text: 'Chocolate Mint Black Tea'},\n {value: 'Russian blend', text: 'Russian blend'},\n {value: 'Imperial Mojiang Golden Bud Yunnan Black Tea Autumn 2013',\n text: 'Imperial Mojiang Golden Bud Yunnan Black Tea Autumn 2013'},\n {value: 'White Acai Luminesence', text: 'White Acai Luminesence'},\n {value: 'Iron Silk Puer', text: 'Iron Silk Puer'},\n {value: 'Yin Zhen Silver Needle', text: 'Yin Zhen Silver Needle'},\n {value: 'Four Seasons Taiwan Oolong', text: 'Four Seasons Taiwan Oolong'},\n {value: 'Earl Grey Fancy - Double Bergamot',\n text: 'Earl Grey Fancy - Double Bergamot'},\n {value: 'Hibiscus Ginger', text: 'Hibiscus Ginger'},\n {value: 'Keemun Red Emperor', text: 'Keemun Red Emperor'},\n {value: 'Monks Blend Tea Scented Ceylon / China (TE21S)',\n text: 'Monks Blend Tea Scented Ceylon / China (TE21S)'},\n {value: '2004 Ji Xing Yi Wu Raw Beeng Cha',\n text: '2004 Ji Xing Yi Wu Raw Beeng Cha'},\n {value: 'Assam Sessa Estate TGFOP', text: 'Assam Sessa Estate TGFOP'},\n {value: 'South African Rooibos (Red Bush) Superior Organic',\n text: 'South African Rooibos (Red Bush) Superior Organic'},\n {value: 'TT10: Formosa Oolong Standard Grade',\n text: 'TT10: Formosa Oolong Standard Grade'},\n {value: 'Blood Orange Fruit Melange', text: 'Blood Orange Fruit Melange'},\n {value: 'Taiwan Oolong (High Mountain) Tea',\n text: 'Taiwan Oolong (High Mountain) Tea'},\n {value: '2008 Honey Orchid Gold Medalist 1',\n text: '2008 Honey Orchid Gold Medalist 1'},\n {value: 'Jun Chiyabari Himalayan Evergreen',\n text: 'Jun Chiyabari Himalayan Evergreen'},\n {value: 'Snow Bunny (organic)', text: 'Snow Bunny (organic)'},\n {value: 'Wild Blueberry Acai', text: 'Wild Blueberry Acai'},\n {value: 'The Blanc de Cassis', text: 'The Blanc de Cassis'},\n {value: 'Vanilla Rhubarb', text: 'Vanilla Rhubarb'},\n {value: 'Port City', text: 'Port City'},\n {value: 'Shui Xian', text: 'Shui Xian'},\n {value: 'Yunnan Pu-erh', text: 'Yunnan Pu-erh'},\n {value: 'Chocolatey Chai', text: 'Chocolatey Chai'},\n {value: 'Jamaica Red Rooibos', text: 'Jamaica Red Rooibos'},\n {value: 'Citrus Dream', text: 'Citrus Dream'},\n {value: 'Green Dew Gunpowder', text: 'Green Dew Gunpowder'},\n {value: 'Dragon Well Loose Leaf Green Tea (lung ching)',\n text: 'Dragon Well Loose Leaf Green Tea (lung ching)'},\n {value: 'TT88: Formosa Oolong Spring Dragon',\n text: 'TT88: Formosa Oolong Spring Dragon'},\n {value: 'Nutty Weight Loss Blend', text: 'Nutty Weight Loss Blend'},\n {value: 'Woodland Mug - Winter Edition 2013',\n text: 'Woodland Mug - Winter Edition 2013'},\n {value: 'Toasted Walnut', text: 'Toasted Walnut'},\n {value: 'Ceylon Single Estate', text: 'Ceylon Single Estate'},\n {value: 'Decaf Ginger Lemon (Ginger Sun Lemon Decaf Green)',\n text: 'Decaf Ginger Lemon (Ginger Sun Lemon Decaf Green)'},\n {value: 'Lovers Leap Estate', text: 'Lovers Leap Estate'},\n {value: 'Bailin Gongfu Black Tea', text: 'Bailin Gongfu Black Tea'},\n {value: 'Green Tea Superfruit Passionfruit and Coconut',\n text: 'Green Tea Superfruit Passionfruit and Coconut'},\n {value: 'Laoshan Northern Green', text: 'Laoshan Northern Green'},\n {value: 'Bubble Tea', text: 'Bubble Tea'},\n {value: 'Qi Lan Black (Rare)', text: 'Qi Lan Black (Rare)'},\n {value: 'Darjeeling First Flush - Risheehat Estate -',\n text: 'Darjeeling First Flush - Risheehat Estate -'},\n {value: 'High Land Uolong Tea', text: 'High Land Uolong Tea'},\n {value: 'White Tea with Blueberry &amp; Pomegranate',\n text: 'White Tea with Blueberry &amp; Pomegranate'},\n {value: 'Gaoshan Yunwu Cha', text: 'Gaoshan Yunwu Cha'},\n {value: 'Buddhas Cup', text: 'Buddhas Cup'},\n {value: 'No. 33 Chai', text: 'No. 33 Chai'},\n {value: 'Organic Fresh Green Yerba Mate Loose',\n text: 'Organic Fresh Green Yerba Mate Loose'},\n {value: 'Get Relaxed - No.14 (Wellness Collection)',\n text: 'Get Relaxed - No.14 (Wellness Collection)'},\n {value: 'Japanese Genmaicha Green', text: 'Japanese Genmaicha Green'},\n {value: 'Dong Ding Oolong', text: 'Dong Ding Oolong'},\n {value: 'White Pearls', text: 'White Pearls'},\n {value: 'Thai Tea', text: 'Thai Tea'},\n {value: 'Brown Rice Tea', text: 'Brown Rice Tea'},\n {value: 'Black Raspberry', text: 'Black Raspberry'},\n {value: 'RadioactiviTEA', text: 'RadioactiviTEA'},\n {value: 'California Chai', text: 'California Chai'},\n {value: 'Oolong Caress', text: 'Oolong Caress'},\n {value: 'Kenya Silverback', text: 'Kenya Silverback'},\n {value: 'TT95: Formosa Special White Tea',\n text: 'TT95: Formosa Special White Tea'},\n {value: 'Pumpkin Spice DeCaf', text: 'Pumpkin Spice DeCaf'},\n {value: 'Japan Shincha Kirisakura', text: 'Japan Shincha Kirisakura'},\n {value: 'Premium St. Valentine Tea', text: 'Premium St. Valentine Tea'},\n {value: 'Lapsang Souchong (Organic)', text: 'Lapsang Souchong (Organic)'},\n {value: 'Kaki-cha', text: 'Kaki-cha'},\n {value: 'Muscat Oolong', text: 'Muscat Oolong'},\n {value: 'Walnut Brittle', text: 'Walnut Brittle'},\n {value: 'Pu-Erh Mini Tou-Cha', text: 'Pu-Erh Mini Tou-Cha'},\n {value: 'Formosa Aged Dongding Oolong',\n text: 'Formosa Aged Dongding Oolong'},\n {value: 'Thai Nguyen', text: 'Thai Nguyen'},\n {value: 'Berry Overload', text: 'Berry Overload'},\n {value: 'Organic Oolong Superior', text: 'Organic Oolong Superior'},\n {value: 'Sweet Desert Delight (aka Desert Blend)',\n text: 'Sweet Desert Delight (aka Desert Blend)'},\n {value: 'Cinnamon Apple Breakfast Tea',\n text: 'Cinnamon Apple Breakfast Tea'},\n {value: 'Tit Koon Yum', text: 'Tit Koon Yum'},\n {value: 'Sweet Orange', text: 'Sweet Orange'},\n {value: 'Sakura', text: 'Sakura'},\n {value: 'St. Petersburg', text: 'St. Petersburg'},\n {value: 'Silver Needle Yinzhen', text: 'Silver Needle Yinzhen'},\n {value: 'Earl Grey Yin Zhen', text: 'Earl Grey Yin Zhen'},\n {value: 'Monkey Picked Tea (Ma Nau Mi Ti Kaun Yin)',\n text: 'Monkey Picked Tea (Ma Nau Mi Ti Kaun Yin)'},\n {value: 'Darjeeling Black', text: 'Darjeeling Black'},\n {value: 'Carolina Honey (Bottled)', text: 'Carolina Honey (Bottled)'},\n {value: 'Relax Chamomile', text: 'Relax Chamomile'},\n {value: 'Dragon Well Select', text: 'Dragon Well Select'},\n {value: 'Bulang 2005 (Lao Chen de Cha)',\n text: 'Bulang 2005 (Lao Chen de Cha)'},\n {value: 'Duchess Grey Tea', text: 'Duchess Grey Tea'},\n {value: 'Premium Shincha (2009)', text: 'Premium Shincha (2009)'},\n {value: 'Sencha Matsuri', text: 'Sencha Matsuri'},\n {value: 'Matcha Organic Super Power Green',\n text: 'Matcha Organic Super Power Green'},\n {value: 'Dragon Eyes', text: 'Dragon Eyes'},\n {value: 'Organic Vanilla Rooibos', text: 'Organic Vanilla Rooibos'},\n {value: 'Refresh', text: 'Refresh'},\n {value: 'Blackcurrant Black Tea', text: 'Blackcurrant Black Tea'},\n {value: 'Sencha (Japanese Green Tea)',\n text: 'Sencha (Japanese Green Tea)'},\n {value: 'Amandine Rose', text: 'Amandine Rose'},\n {value: 'Yunnan Golden Tips Imperial (ZY85)',\n text: 'Yunnan Golden Tips Imperial (ZY85)'},\n {value: 'Vietnamese Marble Mountain (BV01)',\n text: 'Vietnamese Marble Mountain (BV01)'},\n {value: 'Darjeeling Oolong Singbulli (No. 2517)',\n text: 'Darjeeling Oolong Singbulli (No. 2517)'},\n {value: 'Darjeeling Namring Upper Estate',\n text: 'Darjeeling Namring Upper Estate'},\n {value: 'Jasmine Citrus Blossom', text: 'Jasmine Citrus Blossom'},\n {value: 'Fairtrade Organic Assam', text: 'Fairtrade Organic Assam'},\n {value: 'Sweet Roast Green Tea', text: 'Sweet Roast Green Tea'},\n {value: 'Foxtrot', text: 'Foxtrot'},\n {value: 'Womans Mother to Be', text: 'Womans Mother to Be'},\n {value: '2006 Autumn Yi Wu Yeh Cha', text: '2006 Autumn Yi Wu Yeh Cha'},\n {value: 'High-5', text: 'High-5'},\n {value: 'Sencha of the Summer Sun', text: 'Sencha of the Summer Sun'},\n {value: 'rosehips Organic', text: 'rosehips Organic'},\n {value: 'French Vanilla Tea', text: 'French Vanilla Tea'},\n {value: '2011 Spring Imprial Songzhong Zhi Lan Xiang(Orchid Aroma) Phoenix Dancong Oolong',\n text: '2011 Songzhong Zhi Lan Xiang(Orchid Aroma) Phoenix Dancong Oolong'},\n {value: 'Sweet Rose Tulsi Tea', text: 'Sweet Rose Tulsi Tea'},\n {value: 'Apricot Guayusa', text: 'Apricot Guayusa'},\n {value: 'Guricha', text: 'Guricha'},\n {value: 'English Toffee', text: 'English Toffee'},\n {value: 'Mokalbari STGFOP 1st Flush 2010 Assam',\n text: 'Mokalbari STGFOP 1st Flush 2010 Assam'},\n {value: 'Jade Oolong Chai (organic)', text: 'Jade Oolong Chai (organic)'},\n {value: 'Acai Green Tea', text: 'Acai Green Tea'},\n {value: 'Sushi Bar Green', text: 'Sushi Bar Green'},\n {value: 'Sato Matcha Genmaicha', text: 'Sato Matcha Genmaicha'},\n {value: 'Southern Fruits', text: 'Southern Fruits'},\n {value: 'Blueberry Muffin', text: 'Blueberry Muffin'},\n {value: 'Yunnan Chi Tse Beeng Puerh (Spring Bud)',\n text: 'Yunnan Chi Tse Beeng Puerh (Spring Bud)'},\n {value: 'Chá misto flores e frutas saboar maçã canela e caramelo',\n text: 'Chá misto flores e frutas saboar maçã canela e caramelo'},\n {value: 'Matcha Black Soybean Rice Tea',\n text: 'Matcha Black Soybean Rice Tea'},\n {value: '2nd Flush Darjeeling | Margarets Hope Silver Moon',\n text: '2nd Flush Darjeeling | Margarets Hope Silver Moon'},\n {value: 'Mint Iced Green Tea Bags', text: 'Mint Iced Green Tea Bags'},\n {value: 'Citron Potion', text: 'Citron Potion'},\n {value: 'TeaSource Gold', text: 'TeaSource Gold'},\n {value: 'Smooth Cocoamint', text: 'Smooth Cocoamint'},\n {value: 'Darjeeling Lingia First Flush',\n text: 'Darjeeling Lingia First Flush'},\n {value: 'Loose Jasmine', text: 'Loose Jasmine'},\n {value: 'Mixed Berry Green', text: 'Mixed Berry Green'},\n {value: 'Ceylon Dimbula (BOP)', text: 'Ceylon Dimbula (BOP)'},\n {value: 'Jumpy Monkey', text: 'Jumpy Monkey'},\n {value: 'Rooibos Caramel-Toffee', text: 'Rooibos Caramel-Toffee'},\n {value: 'Mandarin Peel', text: 'Mandarin Peel'},\n {value: 'Finnick Odair', text: 'Finnick Odair'},\n {value: 'Cool Breeze', text: 'Cool Breeze'},\n {value: '2009 Shincha', text: '2009 Shincha'},\n {value: 'Rose and Cherry Blossom', text: 'Rose and Cherry Blossom'},\n {value: 'Oolong Rouge', text: 'Oolong Rouge'},\n {value: 'Organic Orange Sencha Green Tea',\n text: 'Organic Orange Sencha Green Tea'},\n {value: 'Gao Shan High Mountain Black Tea',\n text: 'Gao Shan High Mountain Black Tea'},\n {value: 'Elderwood', text: 'Elderwood'},\n {value: 'Fukamushi Sencha Supreme', text: 'Fukamushi Sencha Supreme'},\n {value: 'Clear Green', text: 'Clear Green'},\n {value: 'Mint Julep', text: 'Mint Julep'},\n {value: 'Formosa Fancy Superior Choice Oolong (No. 625)',\n text: 'Formosa Fancy Superior Choice Oolong (No. 625)'},\n {value: 'Organic Kukicha Green Tea', text: 'Organic Kukicha Green Tea'},\n {value: 'Rooibos Raspberry Fresca', text: 'Rooibos Raspberry Fresca'},\n {value: 'Jun Shan Yin Zhen Yellow', text: 'Jun Shan Yin Zhen Yellow'},\n {value: 'Hand Picked Autumn Tieguanyin (2012)',\n text: 'Hand Picked Autumn Tieguanyin (2012)'},\n {value: 'Toyo Mukashi', text: 'Toyo Mukashi'},\n {value: 'Bergamot Rose Laoshan Black',\n text: 'Bergamot Rose Laoshan Black'},\n {value: 'Rooibos Gingerbread', text: 'Rooibos Gingerbread'},\n {value: 'Indian Tea', text: 'Indian Tea'},\n {value: 'Camomile &amp; Lemongrass', text: 'Camomile Lemongrass'},\n {value: 'Macaron Cassis Violette', text: 'Macaron Cassis Violette'},\n {value: 'Ceylon Black with Orange', text: 'Ceylon Black with Orange'},\n {value: 'Organic Dian Hong Yunnan Black Tea',\n text: 'Organic Dian Hong Yunnan Black Tea'},\n {value: 'Organic Matcha Ceremonial Grade',\n text: 'Organic Matcha Ceremonial Grade'},\n {value: 'Passionfruit/Grapefruit', text: 'Passionfruit/Grapefruit'},\n {value: 'Earl Grey Royal', text: 'Earl Grey Royal'},\n {value: 'Muscle and Joint Comfort Tea',\n text: 'Muscle and Joint Comfort Tea'},\n {value: 'Himalayan Apple Spice', text: 'Himalayan Apple Spice'},\n {value: 'Premium Ti Luo Han', text: 'Premium Ti Luo Han'},\n {value: 'San Lin Xi Formosa Oolong (Rich Aroma)',\n text: 'San Lin Xi Formosa Oolong (Rich Aroma)'},\n {value: 'Honey Lemon Ginseng Green', text: 'Honey Lemon Ginseng Green'},\n {value: 'Mindful Morning Blend', text: 'Mindful Morning Blend'},\n {value: 'Russian earl grey', text: 'Russian earl grey'},\n {value: 'Verona', text: 'Verona'},\n {value: 'Liu An Guan Pian (Finest Anhui Guapian)',\n text: 'Liu An Guan Pian (Finest Anhui Guapian)'},\n {value: 'Caramel Cream Mate', text: 'Caramel Cream Mate'},\n {value: 'Mango Tea', text: 'Mango Tea'},\n {value: 'Xanadu', text: 'Xanadu'},\n {value: 'Tea Earl Grey Hot', text: 'Tea Earl Grey Hot'},\n {value: 'Da Hong Pao (Big Red Robe) Wuyi Rock Oolong Tea Fujian',\n text: 'Da Hong Pao (Big Red Robe) Wuyi Rock Oolong Tea Fujian'},\n {value: 'Momo Oolong Super Grade', text: 'Momo Oolong Super Grade'},\n {value: 'Golden Monkey Imperial (ZY82)',\n text: 'Golden Monkey Imperial (ZY82)'},\n {value: 'Long Jing Meijawu', text: 'Long Jing Meijawu'},\n {value: 'Ying Kee Cooked Pu Erh Brick',\n text: 'Ying Kee Cooked Pu Erh Brick'},\n {value: 'Moon Crest (Dan Cong)', text: 'Moon Crest (Dan Cong)'},\n {value: 'Monkey-Picked Golden', text: 'Monkey-Picked Golden'},\n {value: 'Tescos', text: 'Tescos'},\n {value: 'Chocolate Chamomile Curiosity Brew',\n text: 'Chocolate Chamomile Curiosity Brew'},\n {value: 'China Golden Yunnan Organic',\n text: 'China Golden Yunnan Organic'},\n {value: 'Organic Green Tea Ginseng Mate',\n text: 'Organic Green Tea Ginseng Mate'},\n {value: 'Green tea with jasmine', text: 'Green tea with jasmine'},\n {value: 'Powdered Sencha', text: 'Powdered Sencha'},\n {value: 'Organic Yerba Mate', text: 'Organic Yerba Mate'},\n {value: 'Aap Ki Pasand Nilgiri', text: 'Aap Ki Pasand Nilgiri'},\n {value: 'Hot Buttered Banana Bread', text: 'Hot Buttered Banana Bread'},\n {value: 'Cha Yen Thai Black Tea', text: 'Cha Yen Thai Black Tea'},\n {value: 'Tian Di Ren Yiwu 2008 Shu Pu-er',\n text: 'Tian Di Ren Yiwu 2008 Shu Pu-er'},\n {value: '1st Flush Darjeeling', text: '1st Flush Darjeeling'},\n {value: 'Almond Amaretto', text: 'Almond Amaretto'},\n {value: 'Monkey Fart', text: 'Monkey Fart'},\n {value: 'Decaf Lemon and White Tea', text: 'Decaf Lemon and White Tea'},\n {value: 'Russian Georgian Black', text: 'Russian Georgian Black'},\n {value: 'strawberry sencha', text: 'strawberry sencha'},\n {value: '2006 Fengqing Raw Pu-erh Tea Tuocha 100g',\n text: '2006 Fengqing Raw Pu-erh Tea Tuocha 100g'},\n {value: 'Organic Special Grade Pu-Erh Tea',\n text: 'Organic Special Grade Pu-Erh Tea'},\n {value: 'Caramelized Pear', text: 'Caramelized Pear'},\n {value: 'Port', text: 'Port'},\n {value: 'Crimson Punch', text: 'Crimson Punch'},\n {value: 'Pumpkin Spice Tea', text: 'Pumpkin Spice Tea'},\n {value: 'An Xi Ti Kuan Yin', text: 'An Xi Ti Kuan Yin'},\n {value: 'Wild Forest Holy Basil Organic (BH03)',\n text: 'Wild Forest Holy Basil Organic (BH03)'},\n {value: 'Huang Zhi Xiang Phoenix Mountain Dancong Oolong',\n text: 'Huang Zhi Xiang Phoenix Mountain Dancong Oolong'},\n {value: 'Ryokucha', text: 'Ryokucha'},\n {value: 'Gold Peony White', text: 'Gold Peony White'},\n {value: 'Mediterranean Mandarin', text: 'Mediterranean Mandarin'},\n {value: 'Tarajulie Estate Assam', text: 'Tarajulie Estate Assam'},\n {value: 'Strong Fire Oolong', text: 'Strong Fire Oolong'},\n {value: 'Nepal Everest Dark Heart - Hand Rolled 2016 Late Summer Pluck',\n text: 'Nepal Everest Dark Heart - Hand Rolled 2016 Late Summer Pluck'},\n {value: 'Ayurvedic Anti-Strain', text: 'Ayurvedic Anti-Strain'},\n {value: 'Apricot Loose Leaf', text: 'Apricot Loose Leaf'},\n {value: 'Earl Grey Rose and Lavender',\n text: 'Earl Grey Rose and Lavender'},\n {value: 'OConnors Cream', text: 'OConnors Cream'},\n {value: 'Butter Truffle', text: 'Butter Truffle'},\n {value: 'Lapsang Souchong (Lightly Smoked)',\n text: 'Lapsang Souchong (Lightly Smoked)'},\n {value: 'Medium-roast Jin Xuan', text: 'Medium-roast Jin Xuan'},\n {value: 'Momoko', text: 'Momoko'},\n {value: 'Gold Monkey', text: 'Gold Monkey'},\n {value: 'Mount Everest', text: 'Mount Everest'},\n {value: 'Yi Mei Ren Wu Liang Mountain Yunnan Black Tea',\n text: 'Yi Mei Ren Wu Liang Mountain Yunnan Black Tea'},\n {value: '2012 Darjeeling First Flush Giddapahar China Special Black Tea',\n text: '2012 Darjeeling First Flush Giddapahar China Special Black Tea'},\n {value: 'China Pai Mu Tan (No. 531)', text: 'China Pai Mu Tan (No. 531)'},\n {value: '2015 Yunnan Sourcing Ye Zhu Tang Wild Arbor Raw Pu-erh tea cake',\n text: '2015 Yunnan Sourcing Ye Zhu Tang Wild Arbor Raw Pu-erh tea cake'},\n {value: 'Loki', text: 'Loki'},\n {value: 'Yerba Mate Mojito', text: 'Yerba Mate Mojito'},\n {value: 'Halmari Assam Orthodox Second Flush',\n text: 'Halmari Assam Orthodox Second Flush'},\n {value: 'My Morning Mate and Cacao Mint',\n text: 'My Morning Mate and Cacao Mint'},\n {value: 'Gunpowder - Organic', text: 'Gunpowder - Organic'},\n {value: 'Eternal Sunshine', text: 'Eternal Sunshine'},\n {value: 'Golden Milk Tea', text: 'Golden Milk Tea'},\n {value: 'Cherokee Mint', text: 'Cherokee Mint'},\n {value: 'Lishan Winter', text: 'Lishan Winter'},\n {value: 'Kukicha Twig (Organic Japanese)',\n text: 'Kukicha Twig (Organic Japanese)'},\n {value: 'End of the Line (aka Bucky Barnes)',\n text: 'End of the Line (aka Bucky Barnes)'},\n {value: 'North India Manjhee Valley Premium SFTGFOP1',\n text: 'North India Manjhee Valley Premium SFTGFOP1'},\n {value: 'Tropical Tulsi', text: 'Tropical Tulsi'},\n {value: 'Oolong - Champagne Formosa', text: 'Oolong - Champagne Formosa'},\n {value: '100% Organic Green Tea', text: '100% Organic Green Tea'},\n {value: 'Tangerine Hibiscus Superflower Tea',\n text: 'Tangerine Hibiscus Superflower Tea'},\n {value: 'Vanilla Assam', text: 'Vanilla Assam'},\n {value: 'Bourbon Vanilla', text: 'Bourbon Vanilla'},\n {value: 'Elma (Apple Fruit Tea)', text: 'Elma (Apple Fruit Tea)'},\n {value: 'Caramele', text: 'Caramele'},\n {value: 'Ancient Shu Pu-erh Tuo Cha', text: 'Ancient Shu Pu-erh Tuo Cha'},\n {value: 'Souvia Sushi (Uji Gen Mai Cha)',\n text: 'Souvia Sushi (Uji Gen Mai Cha)'},\n {value: 'Oolong Organic Tea', text: 'Oolong Organic Tea'},\n {value: 'Ginger Herbal Infusion', text: 'Ginger Herbal Infusion'},\n {value: 'Buttered Popcorn', text: 'Buttered Popcorn'},\n {value: 'Pineapple Lychee Hibiscus', text: 'Pineapple Lychee Hibiscus'},\n {value: 'TE98: Huang Shan Sunset Tea',\n text: 'TE98: Huang Shan Sunset Tea'},\n {value: '2010 Shincha Sencha Kinari', text: '2010 Shincha Sencha Kinari'},\n {value: 'DJ-13 of Giddapahar Eagles Cliff Darjeeling Tea',\n text: 'DJ-13 of Giddapahar Eagles Cliff Darjeeling Tea'},\n {value: 'Angels Dream Tea', text: 'Angels Dream Tea'},\n {value: 'Black Pearl Tea', text: 'Black Pearl Tea'},\n {value: 'Pineapple Bamboo', text: 'Pineapple Bamboo'},\n {value: '2006 Tiandiren Bulang', text: '2006 Tiandiren Bulang'},\n {value: 'Carnival Fruit Blend', text: 'Carnival Fruit Blend'},\n {value: 'Lipton PureLeaf Tea: Iced Tea with Raspberry',\n text: 'Lipton PureLeaf Tea: Iced Tea with Raspberry'},\n {value: 'Black Frost', text: 'Black Frost'},\n {value: 'Earl Grey (No. 69)', text: 'Earl Grey (No. 69)'},\n {value: '2008 LaoTong Zi Timber Raw Pu-erh',\n text: '2008 LaoTong Zi Timber Raw Pu-erh'},\n {value: 'Chamomile Nights', text: 'Chamomile Nights'},\n {value: 'Ketepa Pride Kenya Tea Bags',\n text: 'Ketepa Pride Kenya Tea Bags'},\n {value: 'Tea Room Blend Leaf Tea', text: 'Tea Room Blend Leaf Tea'},\n {value: 'Anji Bai Cha', text: 'Anji Bai Cha'},\n {value: 'Yi Mei Ren', text: 'Yi Mei Ren'},\n {value: 'Murgleis - Signature Blend', text: 'Murgleis - Signature Blend'},\n {value: 'Java green tea', text: 'Java green tea'},\n {value: 'Strawberry Burst', text: 'Strawberry Burst'},\n {value: 'Organic Green Tea with Citrus and Ginkgo',\n text: 'Organic Green Tea with Citrus and Ginkgo'},\n {value: 'Golden Chai - Spiced Assam', text: 'Golden Chai - Spiced Assam'},\n {value: 'viking glogg tea', text: 'viking glogg tea'},\n {value: 'UtiliTEA by Adagio', text: 'UtiliTEA by Adagio'},\n {value: '2013 Spring Shan Lin Xi: Long-Feng-Xia High Mountain Oolong - 衫林溪龍鳳峽烏龍',\n text: '2013 Shan Lin Xi: Long-Feng-Xia High Mountain Oolong'},\n {value: 'Sicilian Vespers', text: 'Sicilian Vespers'},\n {value: 'Raspberry Lime', text: 'Raspberry Lime'},\n {value: 'Cocoa Loco', text: 'Cocoa Loco'},\n {value: 'Scottish Breakfast Organic', text: 'Scottish Breakfast Organic'},\n {value: 'Blood Orange Fruit Tea', text: 'Blood Orange Fruit Tea'},\n {value: 'Ripe Mango Oolong', text: 'Ripe Mango Oolong'},\n {value: 'First Class Chai', text: 'First Class Chai'},\n {value: 'Lemongrass Ginger', text: 'Lemongrass Ginger'},\n {value: 'Chocolate Banana', text: 'Chocolate Banana'},\n {value: 'Lime in the Coconut', text: 'Lime in the Coconut'},\n {value: 'Shan Lin Shi (Roast)', text: 'Shan Lin Shi (Roast)'},\n {value: 'KaiMatcha Premium', text: 'KaiMatcha Premium'},\n {value: 'Darjeeling Lingia Organic', text: 'Darjeeling Lingia Organic'},\n {value: 'Berry Cool', text: 'Berry Cool'},\n {value: 'Hand Picked Summer Tieguanyin',\n text: 'Hand Picked Summer Tieguanyin'},\n {value: 'Ceremonial Grade DoMatcha', text: 'Ceremonial Grade DoMatcha'},\n {value: 'No. 46 Exceptional Iced Tea',\n text: 'No. 46 Exceptional Iced Tea'},\n {value: 'peach rooibos', text: 'peach rooibos'},\n {value: 'Rooibos Pretoria', text: 'Rooibos Pretoria'},\n {value: 'Alices Blend', text: 'Alices Blend'},\n {value: 'Chiran Fukamushi Superior', text: 'Chiran Fukamushi Superior'},\n {value: 'Caramel Candy Apple', text: 'Caramel Candy Apple'},\n {value: 'Nannuoshan puerh loose leaf tea',\n text: 'Nannuoshan puerh loose leaf tea'},\n {value: 'Japanese Sencha (organic)', text: 'Japanese Sencha (organic)'},\n {value: 'Toffee Dream', text: 'Toffee Dream'},\n {value: 'Banana Oolong (organic)', text: 'Banana Oolong (organic)'},\n {value: 'Yunnan Green Tea Grade A', text: 'Yunnan Green Tea Grade A'},\n {value: 'Pearfect White Tea', text: 'Pearfect White Tea'},\n {value: 'Tie Guan Yin (Oolong Tea) sampler by Zen Tea',\n text: 'Tie Guan Yin (Oolong Tea) sampler by Zen Tea'},\n {value: 'Tesco Disney kids tea', text: 'Tesco Disney kids tea'},\n {value: 'Dorian Grey', text: 'Dorian Grey'},\n {value: 'Pu Er 1996 Chung Cha', text: 'Pu Er 1996 Chung Cha'},\n {value: 'Black Powder', text: 'Black Powder'},\n {value: 'Vienna Cinnamon', text: 'Vienna Cinnamon'},\n {value: 'Black Pu Erh', text: 'Black Pu Erh'},\n {value: 'Peachy Oolong', text: 'Peachy Oolong'},\n {value: 'Mt Alee Taiwan Oolong Spring Tea',\n text: 'Mt Alee Taiwan Oolong Spring Tea'},\n {value: 'Creamy Earl Grey', text: 'Creamy Earl Grey'},\n {value: 'Organic Fairtrade Lime Green',\n text: 'Organic Fairtrade Lime Green'},\n {value: 'Shizuoka Sencha', text: 'Shizuoka Sencha'},\n {value: 'Light Roast Anxi Traditional Tieguanyin',\n text: 'Light Roast Anxi Traditional Tieguanyin'},\n {value: 'Holiday Blend', text: 'Holiday Blend'},\n {value: '2006 Spring Yi Wu Ma Hei Zhai Sun-dried Mao Cha',\n text: '2006 Spring Yi Wu Ma Hei Zhai Sun-dried Mao Cha'},\n {value: 'Celebrate Blooming Tea Ball',\n text: 'Celebrate Blooming Tea Ball'},\n {value: 'Great Buddhas Palm', text: 'Great Buddhas Palm'},\n {value: 'Silk Dragon Jasmine (organic)',\n text: 'Silk Dragon Jasmine (organic)'},\n {value: 'Decaffeinated British Blend',\n text: 'Decaffeinated British Blend'},\n {value: 'High Grown English Breakfast',\n text: 'High Grown English Breakfast'},\n {value: 'Te Med Rabarber - Vaniljsmak',\n text: 'Te Med Rabarber - Vaniljsmak'},\n {value: 'Lindenblüten', text: 'Lindenblüten'},\n {value: 'Pettiagalla Golden Ceylon', text: 'Pettiagalla Golden Ceylon'},\n {value: 'Dreamsicle Darjeeling', text: 'Dreamsicle Darjeeling'},\n {value: 'Buddha Hand High Mountain', text: 'Buddha Hand High Mountain'},\n {value: '2011 EoT Mannuo', text: '2011 EoT Mannuo'},\n {value: 'Organic Afternoon Blend Black Tea',\n text: 'Organic Afternoon Blend Black Tea'},\n {value: 'Sweet Almond Green Tea (TG14)',\n text: 'Sweet Almond Green Tea (TG14)'},\n {value: 'Autumn Harvest Laoshan Green',\n text: 'Autumn Harvest Laoshan Green'},\n {value: 'Blackflower Signature Chai', text: 'Blackflower Signature Chai'},\n {value: 'Bai Ji Guan (White Rooster White Coxcomb)',\n text: 'Bai Ji Guan (White Rooster White Coxcomb)'},\n {value: 'Oolong crème de la crème', text: 'Oolong crème de la crème'},\n {value: 'Decaf Pumpkin Spice', text: 'Decaf Pumpkin Spice'},\n {value: 'Cranberry Singapore Sling Rooibos Tea',\n text: 'Cranberry Singapore Sling Rooibos Tea'},\n {value: 'Spiced Pear', text: 'Spiced Pear'},\n {value: 'Dragonfruit Devotion', text: 'Dragonfruit Devotion'},\n {value: '2006 12 Gentlemen Yiwu', text: '2006 12 Gentlemen Yiwu'},\n {value: 'Momo &amp; Strawberry', text: 'Momo &amp; Strawberry'},\n {value: 'Golden Dragon', text: 'Golden Dragon'},\n {value: 'Republic Red Chai', text: 'Republic Red Chai'},\n {value: 'Darjeeling In Between FTGFOP1',\n text: 'Darjeeling In Between FTGFOP1'},\n {value: '1980s Xiaguan Zhubao', text: '1980s Xiaguan Zhubao'},\n {value: 'Strawberry Chocolate', text: 'Strawberry Chocolate'},\n {value: 'Red Zinger', text: 'Red Zinger'},\n {value: 'Morgen Tee', text: 'Morgen Tee'},\n {value: 'Sweetfern Tonic', text: 'Sweetfern Tonic'},\n {value: 'Passion Iced Tea Lemonade', text: 'Passion Iced Tea Lemonade'},\n {value: 'Organic Rooibos Lemon &amp; Honey',\n text: 'Organic Rooibos Lemon &amp; Honey'},\n {value: 'Key Lime Pie', text: 'Key Lime Pie'},\n {value: 'Nepal Gold Himalayan Shangri-La',\n text: 'Nepal Gold Himalayan Shangri-La'},\n {value: 'Spring Break', text: 'Spring Break'},\n {value: 'BaSien (Eight Immortals) Oolong Tea',\n text: 'BaSien (Eight Immortals) Oolong Tea'},\n {value: 'Earl Grey de la Creme', text: 'Earl Grey de la Creme'},\n {value: 'Tie Guan Yin Impérial', text: 'Tie Guan Yin Impérial'},\n {value: 'Darjeeling Makaibari Organic First Flush',\n text: 'Darjeeling Makaibari Organic First Flush'},\n {value: 'Rose Sencha', text: 'Rose Sencha'},\n {value: 'Masala Chai Tea', text: 'Masala Chai Tea'},\n {value: 'Turkish Apple and Cinnamon', text: 'Turkish Apple and Cinnamon'},\n {value: 'Rainforest Maté mixed with Ginger Twist',\n text: 'Rainforest Maté mixed with Ginger Twist'},\n {value: 'Man Zhuan 2012 Spring', text: 'Man Zhuan 2012 Spring'},\n {value: '2009 Nan Jian Qiao Mu Round Cake',\n text: '2009 Nan Jian Qiao Mu Round Cake'},\n {value: 'Ceylon Green Tea with Lemongrass',\n text: 'Ceylon Green Tea with Lemongrass'},\n {value: 'Rooibos Caramel Orange', text: 'Rooibos Caramel Orange'},\n {value: 'Rooibos Kimberley', text: 'Rooibos Kimberley'},\n {value: 'Rose Congou Green', text: 'Rose Congou Green'},\n {value: 'Japan Tamaryokucha (717)', text: 'Japan Tamaryokucha (717)'},\n {value: 'Afternoon Blend', text: 'Afternoon Blend'},\n {value: 'lychee peach black iced tea',\n text: 'lychee peach black iced tea'},\n {value: 'Organic Grapefruit Black', text: 'Organic Grapefruit Black'},\n {value: 'Gyokuro Green Tea Uji', text: 'Gyokuro Green Tea Uji'},\n {value: 'Baozhong', text: 'Baozhong'},\n {value: 'Honeydew Oolong', text: 'Honeydew Oolong'},\n {value: 'Chocolate Covered Almond', text: 'Chocolate Covered Almond'},\n {value: 'Dark Jade Sun Moon Lake', text: 'Dark Jade Sun Moon Lake'},\n {value: 'Royal Green No 3', text: 'Royal Green No 3'},\n {value: 'Organic Cascade Mint', text: 'Organic Cascade Mint'},\n {value: 'Formosa Amber Oolong (TT55)',\n text: 'Formosa Amber Oolong (TT55)'},\n {value: 'Dan Gui Flower', text: 'Dan Gui Flower'},\n {value: 'rainforest chai', text: 'rainforest chai'},\n {value: '2009 Xiaguan Te Ji (Premium Grade) Raw Pu-Erh',\n text: '2009 Xiaguan Te Ji (Premium Grade) Raw Pu-Erh'},\n {value: 'lipton pure leaf peach', text: 'lipton pure leaf peach'},\n {value: 'Chocolate Almond Coconut', text: 'Chocolate Almond Coconut'},\n {value: 'Ancient Gold', text: 'Ancient Gold'},\n {value: 'Rabarbra &amp; vanilje', text: 'Rabarbra &amp; vanilje'},\n {value: 'Papa Bears Hibernation Blend',\n text: 'Papa Bears Hibernation Blend'},\n {value: 'Cambric', text: 'Cambric'},\n {value: 'Ko-kei Cha (TJ30)', text: 'Ko-kei Cha (TJ30)'},\n {value: '2009 Menghai Dayi V93 Pu-erh Tuocha',\n text: '2009 Menghai Dayi V93 Pu-erh Tuocha'},\n {value: 'Red Rocks', text: 'Red Rocks'},\n {value: 'Alchemists Brew', text: 'Alchemists Brew'},\n {value: 'Across The Milky Way', text: 'Across The Milky Way'},\n {value: '2010 Gua Feng Zhai', text: '2010 Gua Feng Zhai'},\n {value: 'Bai Hao Yinzhen', text: 'Bai Hao Yinzhen'},\n {value: 'Gingerbread Chai', text: 'Gingerbread Chai'},\n {value: 'Noble Madam', text: 'Noble Madam'},\n {value: 'Autumn Harvest', text: 'Autumn Harvest'},\n {value: 'Le Touareg', text: 'Le Touareg'},\n {value: 'Fleurs dOranger Oolong', text: 'Fleurs dOranger Oolong'},\n {value: '2011 Douji Hong Shang Dou Raw Puerh Tea',\n text: '2011 Douji Hong Shang Dou Raw Puerh Tea'},\n {value: 'Kagoshima Sencha Sae Midori',\n text: 'Kagoshima Sencha Sae Midori'},\n {value: 'Peppermint Cut-Leaf Organic (No. 977)',\n text: 'Peppermint Cut-Leaf Organic (No. 977)'},\n {value: 'Note Bleue', text: 'Note Bleue'},\n {value: 'Rising Steadily Silver Needle Flower Tea',\n text: 'Rising Steadily Silver Needle Flower Tea'},\n {value: 'Bai Rui Xiang', text: 'Bai Rui Xiang'},\n {value: 'A Tisket A Tasket', text: 'A Tisket A Tasket'},\n {value: 'Red Ginseng Head', text: 'Red Ginseng Head'},\n {value: 'Mint (Menthe)', text: 'Mint (Menthe)'},\n {value: 'Pineapple Strawberry', text: 'Pineapple Strawberry'},\n {value: 'Organic Silver Needle White Tea',\n text: 'Organic Silver Needle White Tea'},\n {value: 'Tindharia Estate FOP First Flush (EX-1) Organic (TDB3)',\n text: 'Tindharia Estate FOP First Flush (EX-1) Organic (TDB3)'},\n {value: 'Honeydew Green', text: 'Honeydew Green'},\n {value: 'Pisces - The Zodiac Series - 2012',\n text: 'Pisces - The Zodiac Series - 2012'},\n {value: 'December', text: 'December'},\n {value: 'Snow Bud (Xue Ya)', text: 'Snow Bud (Xue Ya)'},\n {value: 'Star of India', text: 'Star of India'},\n {value: 'BF66: Peach Melba Fruit Tea',\n text: 'BF66: Peach Melba Fruit Tea'},\n {value: 'Angels Dream loose leaf', text: 'Angels Dream loose leaf'},\n {value: 'Ba Xian Eight Immortals Phoenix Dan Cong',\n text: 'Ba Xian Eight Immortals Phoenix Dan Cong'},\n {value: 'Tè Verde', text: 'Tè Verde'},\n {value: 'Russian Caravan (TB60)', text: 'Russian Caravan (TB60)'},\n {value: 'Pear &amp; Green Tea', text: 'Pear &amp; Green Tea'},\n {value: 'Rooibos Caramel', text: 'Rooibos Caramel'},\n {value: 'Orange Cinnamon Punch', text: 'Orange Cinnamon Punch'},\n {value: 'Irish Mocha LaTea', text: 'Irish Mocha LaTea'},\n {value: 'Gun Powder Green Tea', text: 'Gun Powder Green Tea'},\n {value: 'Sweet Lemon with Lemon Peels (917)',\n text: 'Sweet Lemon with Lemon Peels (917)'},\n {value: 'Organic Masala Chai Black Tea',\n text: 'Organic Masala Chai Black Tea'},\n {value: 'With Open Eyes', text: 'With Open Eyes'},\n {value: '2015 Organic Raw Puer. One Family. One Farm. One Tea.',\n text: '2015 Organic Raw Puer. One Family. One Farm. One Tea.'},\n {value: 'Hu Kwa', text: 'Hu Kwa'},\n {value: 'Cinnamon Chai with Rooibus Tea',\n text: 'Cinnamon Chai with Rooibus Tea'},\n {value: 'Vanilla with Pods - Black Tea',\n text: 'Vanilla with Pods - Black Tea'},\n {value: 'Main Squeeze', text: 'Main Squeeze'},\n {value: 'Asian Pear Hibiscus Superflower Tea',\n text: 'Asian Pear Hibiscus Superflower Tea'},\n {value: 'Mademoiselle', text: 'Mademoiselle'},\n {value: 'Darjeeling The Second Flush',\n text: 'Darjeeling The Second Flush'},\n {value: 'ZK98: China Keemun Mao Feng',\n text: 'ZK98: China Keemun Mao Feng'},\n {value: 'Nilgiri Tea', text: 'Nilgiri Tea'},\n {value: 'China Breakfast', text: 'China Breakfast'},\n {value: 'Honey Bee', text: 'Honey Bee'},\n {value: 'DJ Darjeeling Tea Mim HR First Flush 2012 FTGFOP1',\n text: 'DJ Darjeeling Tea Mim HR First Flush 2012 FTGFOP1'},\n {value: 'Okayti FTGFOP1', text: 'Okayti FTGFOP1'},\n {value: 'Chai Masala Tulsi Tea', text: 'Chai Masala Tulsi Tea'},\n {value: 'Organic Blink Bonnie', text: 'Organic Blink Bonnie'},\n {value: 'Sweet and Spicy', text: 'Sweet and Spicy'},\n {value: 'Keemun Hao Ya China', text: 'Keemun Hao Ya China'},\n {value: 'Spicy Romance Ginger-Cinnamon Tisane',\n text: 'Spicy Romance Ginger-Cinnamon Tisane'},\n {value: 'Traditional Masala', text: 'Traditional Masala'},\n {value: 'Splash', text: 'Splash'},\n {value: 'Stormy Night (organic)', text: 'Stormy Night (organic)'},\n {value: 'Ancient Trees Organic Pu-erh',\n text: 'Ancient Trees Organic Pu-erh'},\n {value: 'Yerba Mate Organic', text: 'Yerba Mate Organic'},\n {value: 'Peppermint Herbal Tisane', text: 'Peppermint Herbal Tisane'},\n {value: 'Natural Tanzania', text: 'Natural Tanzania'},\n {value: 'Wild Orange Blossom', text: 'Wild Orange Blossom'},\n {value: 'Organic Spring Twist', text: 'Organic Spring Twist'},\n {value: 'Lemon Chamomile Herbal Infusion',\n text: 'Lemon Chamomile Herbal Infusion'},\n {value: 'Fleur De Vie', text: 'Fleur De Vie'},\n {value: 'Orange Krush', text: 'Orange Krush'},\n {value: 'Peach Red Tea', text: 'Peach Red Tea'},\n {value: 'The Piemaker - Pushing Daisies - Signature Blend',\n text: 'The Piemaker - Pushing Daisies - Signature Blend'},\n {value: 'Chai Amazonia (organic)', text: 'Chai Amazonia (organic)'},\n {value: 'Fireside', text: 'Fireside'},\n {value: 'La Luotuo-De', text: 'La Luotuo-De'},\n {value: 'Khongeas Assam Leaf', text: 'Khongeas Assam Leaf'},\n {value: 'White Tea with a hint of Pomegranate',\n text: 'White Tea with a hint of Pomegranate'},\n {value: 'Rungmook Estate Darjeeling 2nd Flush Black Tea',\n text: 'Rungmook Estate Darjeeling 2nd Flush Black Tea'},\n {value: 'Flowering Jasmine and Lily Tea',\n text: 'Flowering Jasmine and Lily Tea'},\n {value: 'Jasmine Phoenix Pearls', text: 'Jasmine Phoenix Pearls'},\n {value: 'Flower Oolong Dong Fang Mei Ren',\n text: 'Flower Oolong Dong Fang Mei Ren'},\n {value: 'High Mountain Oolong Tea', text: 'High Mountain Oolong Tea'},\n {value: 'Ali Shan High Mountain Oolong',\n text: 'Ali Shan High Mountain Oolong'},\n {value: 'Mama Baby Tea', text: 'Mama Baby Tea'},\n {value: 'Lapsang Souchong (loose leaf)',\n text: 'Lapsang Souchong (loose leaf)'},\n {value: 'Decaf Hot Cinnamon Spice', text: 'Decaf Hot Cinnamon Spice'},\n {value: 'Borengajuli 2nd Flush F.B.O.P',\n text: 'Borengajuli 2nd Flush F.B.O.P'},\n {value: 'Floral Fusion', text: 'Floral Fusion'},\n {value: 'Dont Be Chai', text: 'Dont Be Chai'},\n {value: 'Rainbow Pu-erh', text: 'Rainbow Pu-erh'},\n {value: 'Tea Bags - Naturally Decaffeinated',\n text: 'Tea Bags - Naturally Decaffeinated'},\n {value: 'Golestan', text: 'Golestan'},\n {value: 'Coffee Chai (organic)', text: 'Coffee Chai (organic)'},\n {value: 'Sweet Merlot Black Tea', text: 'Sweet Merlot Black Tea'},\n {value: 'Persian Apple (organic)', text: 'Persian Apple (organic)'},\n {value: 'Shogun', text: 'Shogun'},\n {value: 'Pumpkin Spice Rooibos Herbal Blend',\n text: 'Pumpkin Spice Rooibos Herbal Blend'},\n {value: 'Chocolate - Almond', text: 'Chocolate - Almond'},\n {value: 'The Government and the Inspector',\n text: 'The Government and the Inspector'},\n {value: 'Acte II', text: 'Acte II'},\n {value: 'Pink Dragonfruit', text: 'Pink Dragonfruit'},\n {value: 'Ji Bian Oolong', text: 'Ji Bian Oolong'},\n {value: 'Orange Sencha', text: 'Orange Sencha'},\n {value: 'China Pu-Erh Tuocha (572)', text: 'China Pu-Erh Tuocha (572)'},\n {value: 'Shizuoka Black Tea', text: 'Shizuoka Black Tea'},\n {value: 'Cream of Avalon', text: 'Cream of Avalon'},\n {value: 'Cosi fan tutte', text: 'Cosi fan tutte'},\n {value: 'Mayfair English Breakfast', text: 'Mayfair English Breakfast'},\n {value: 'Bliss Pu Erh', text: 'Bliss Pu Erh'},\n {value: 'Darjeeling Rose Camélia', text: 'Darjeeling Rose Camélia'},\n {value: 'Maracuya Passion', text: 'Maracuya Passion'},\n {value: 'Taiwan Wuyi', text: 'Taiwan Wuyi'},\n {value: 'Smaug', text: 'Smaug'},\n {value: 'China Milky Oolong', text: 'China Milky Oolong'},\n {value: 'Organic White Peach', text: 'Organic White Peach'},\n {value: '2007 Premium Mengku Arbor Pu-erh Tea Brick',\n text: '2007 Premium Mengku Arbor Pu-erh Tea Brick'},\n {value: 'Earl Grey Chocolate Berry', text: 'Earl Grey Chocolate Berry'},\n {value: 'Ruby Pie', text: 'Ruby Pie'},\n {value: 'Indar', text: 'Indar'},\n {value: 'Star of Africa', text: 'Star of Africa'},\n {value: 'Asylum Signature Blend', text: 'Asylum Signature Blend'},\n {value: '2010 Menghai Dayi 7562 Ripe Pu-erh Tea Brick',\n text: '2010 Menghai Dayi 7562 Ripe Pu-erh Tea Brick'},\n {value: 'Wei Shan Mao Jian', text: 'Wei Shan Mao Jian'},\n {value: 'White Asian Plum', text: 'White Asian Plum'},\n {value: 'Ancient Pu Erh maiden', text: 'Ancient Pu Erh maiden'},\n {value: 'JAime Vert', text: 'JAime Vert'},\n {value: 'Organic Citrus Oolong', text: 'Organic Citrus Oolong'},\n {value: 'Lishan Oolong Tea (Taiwan Lishan Wu Long)',\n text: 'Lishan Oolong Tea (Taiwan Lishan Wu Long)'},\n {value: 'Yunnan Breakfast Tea Bag Organic Fair Trade Black Tea',\n text: 'Yunnan Breakfast Tea Bag Organic Fair Trade Black Tea'},\n {value: 'Kenya Golden Milima', text: 'Kenya Golden Milima'},\n {value: 'Po Tou (ginger flower fragrance) 2007 Dan Cong Phoenix Oolong',\n text: 'Po Tou (ginger flower fragrance) 2007 Dan Cong Phoenix Oolong'},\n {value: 'Pride of the Port', text: 'Pride of the Port'},\n {value: 'Kanpe Tea', text: 'Kanpe Tea'},\n {value: 'Master Hans Shu Puer 2002', text: 'Master Hans Shu Puer 2002'},\n {value: 'The au Lait', text: 'The au Lait'},\n {value: 'Dong Ding (Tung Ting) Mr.Nen Yu (cooked)',\n text: 'Dong Ding (Tung Ting) Mr.Nen Yu (cooked)'},\n {value: 'Acai Berry', text: 'Acai Berry'},\n {value: 'Softness and Chocolate - Douceur et Chocolat',\n text: 'Softness and Chocolate - Douceur et Chocolat'},\n {value: 'Phoenix Dancong', text: 'Phoenix Dancong'},\n {value: 'Sweet Coconut Thai Chai', text: 'Sweet Coconut Thai Chai'},\n {value: 'Indian Spiced Tea', text: 'Indian Spiced Tea'},\n {value: 'Pekoe Gold TOP GRADE Oriental Beauty Oolong Tea',\n text: 'Pekoe Gold TOP GRADE Oriental Beauty Oolong Tea'},\n {value: 'Single Steeps Sampler --Herbal Retreat',\n text: 'Single Steeps Sampler --Herbal Retreat'},\n {value: 'Pineapple Kawaii Blooming Tea',\n text: 'Pineapple Kawaii Blooming Tea'},\n {value: 'Guanabana', text: 'Guanabana'},\n {value: 'AllNighter', text: 'AllNighter'},\n {value: 'dragonweil', text: 'dragonweil'},\n {value: 'Tie Guan Yin Gande village', text: 'Tie Guan Yin Gande village'},\n {value: '2005 Twin Elephants Imperial Golden Buds Shu',\n text: '2005 Twin Elephants Imperial Golden Buds Shu'},\n {value: 'Very Very Berry Caffine Free Fruit Infusion',\n text: 'Very Very Berry Caffine Free Fruit Infusion'},\n {value: 'Herbal Unwind', text: 'Herbal Unwind'},\n {value: 'Love Elixir for Her', text: 'Love Elixir for Her'},\n {value: 'Chai Spice Mate', text: 'Chai Spice Mate'},\n {value: 'Caravan Earl Grey', text: 'Caravan Earl Grey'},\n {value: 'Heiße Liebe', text: 'Heiße Liebe'},\n {value: 'Organic Nepalese Guaranse SFTGFOP',\n text: 'Organic Nepalese Guaranse SFTGFOP'},\n {value: 'Huang Da Cha', text: 'Huang Da Cha'},\n {value: 'French Vanilla Chai', text: 'French Vanilla Chai'},\n {value: 'Instant Spiced Apple Chai', text: 'Instant Spiced Apple Chai'},\n {value: 'Superfine Taiwan Ali Shan Oolong Tea',\n text: 'Superfine Taiwan Ali Shan Oolong Tea'},\n {value: 'Lemon Meringue Mao Zhen Hair Needle',\n text: 'Lemon Meringue Mao Zhen Hair Needle'},\n {value: 'Steepsters Ho-dduk Ho-dduk Goose',\n text: 'Steepsters Ho-dduk Ho-dduk Goose'},\n {value: 'Body Mind White Tea', text: 'Body Mind White Tea'},\n {value: 'Tazo Rest Herbal Infusion', text: 'Tazo Rest Herbal Infusion'},\n {value: 'Tai Xing Jin Xuan', text: 'Tai Xing Jin Xuan'},\n {value: 'Fukamushi (Deep Steamed) Sencha Green Tea',\n text: 'Fukamushi (Deep Steamed) Sencha Green Tea'},\n {value: 'Jasmine Yin Hao', text: 'Jasmine Yin Hao'},\n {value: 'White Tea with Island Mango and Peach Flavor',\n text: 'White Tea with Island Mango and Peach Flavor'},\n {value: 'Almond ', text: 'Almond '},\n {value: 'Sweet Orange Spice', text: 'Sweet Orange Spice'},\n {value: 'Apricot Escape', text: 'Apricot Escape'},\n {value: 'Fairtrade Leaf Tea', text: 'Fairtrade Leaf Tea'},\n {value: 'Antioxidant Berry Burst - Young Hyson Green Tea',\n text: 'Antioxidant Berry Burst - Young Hyson Green Tea'},\n {value: 'Star Of China', text: 'Star Of China'},\n {value: 'Fine Earl Grey', text: 'Fine Earl Grey'},\n {value: 'Blue Eyes', text: 'Blue Eyes'},\n {value: 'Wuyuan Black', text: 'Wuyuan Black'},\n {value: 'Uji Matcha Kiri no Mori', text: 'Uji Matcha Kiri no Mori'},\n {value: 'Ban Tian Yao (WuYi Oolong)', text: 'Ban Tian Yao (WuYi Oolong)'},\n {value: 'Po Li Chun', text: 'Po Li Chun'},\n {value: 'Jasmine Green tea', text: 'Jasmine Green tea'},\n {value: 'Vanilla Dusk', text: 'Vanilla Dusk'},\n {value: 'sencha kura', text: 'sencha kura'},\n {value: '2006 CNNP Yellow Label', text: '2006 CNNP Yellow Label'},\n {value: 'Darjeeling No. 37', text: 'Darjeeling No. 37'},\n {value: 'All days tea', text: 'All days tea'},\n {value: 'Ragamuffin Tea', text: 'Ragamuffin Tea'},\n {value: 'Mango Matcha', text: 'Mango Matcha'},\n {value: 'Daybreak', text: 'Daybreak'},\n {value: 'Organic Rooibos', text: 'Organic Rooibos'},\n {value: 'Yunnan Golden Curls', text: 'Yunnan Golden Curls'},\n {value: 'Organic Ancient Pu-Erh Palace Tea',\n text: 'Organic Ancient Pu-Erh Palace Tea'},\n {value: 'Okayti Estate Darjeeling 2nd Flush Black Tea',\n text: 'Okayti Estate Darjeeling 2nd Flush Black Tea'},\n {value: 'Yunnan Wild Arbor Oriental Beauty',\n text: 'Yunnan Wild Arbor Oriental Beauty'},\n {value: 'Blueberry Crumble', text: 'Blueberry Crumble'},\n {value: 'Dong Ding Wulong 1', text: 'Dong Ding Wulong 1'},\n {value: '2012 Yunnan Sourcing Ye Sheng Cha Wild Tree Purple Tea of Dehong',\n text: '2012 Yunnan Sourcing Ye Sheng Cha Wild Tree Purple Tea of Dehong'},\n {value: 'No.96 Jasmine Silver Tip', text: 'No.96 Jasmine Silver Tip'},\n {value: 'Tropical Punch Black', text: 'Tropical Punch Black'},\n {value: 'Mango Maui', text: 'Mango Maui'},\n {value: 'Hazelnut Dolce', text: 'Hazelnut Dolce'},\n {value: 'Coconut Rum Tropical Green Tea',\n text: 'Coconut Rum Tropical Green Tea'},\n {value: 'Frozen Summit Dong Ding Oolong',\n text: 'Frozen Summit Dong Ding Oolong'},\n {value: 'TDG1: Tindharia Estate Green GFTGFOP1 (DJ-70) Organic',\n text: 'TDG1: Tindharia Estate Green GFTGFOP1 (DJ-70) Organic'},\n {value: 'Berry Creme Blended Tea', text: 'Berry Creme Blended Tea'},\n {value: 'Vermont Maple', text: 'Vermont Maple'},\n {value: 'Strawberry Cheesecake', text: 'Strawberry Cheesecake'},\n {value: 'Golden Puerh', text: 'Golden Puerh'},\n {value: 'Banana Matcha', text: 'Banana Matcha'},\n {value: 'Sade', text: 'Sade'},\n {value: 'Strawberry Kiwi Green', text: 'Strawberry Kiwi Green'},\n {value: 'Rainforest Light Black', text: 'Rainforest Light Black'},\n {value: 'Assam Extra Fancy', text: 'Assam Extra Fancy'},\n {value: 'Chai tea', text: 'Chai tea'},\n {value: 'Assam mangalam', text: 'Assam mangalam'},\n {value: 'French Toast', text: 'French Toast'},\n {value: 'Garden of Eden', text: 'Garden of Eden'},\n {value: 'Earl Grey Fantasy', text: 'Earl Grey Fantasy'},\n {value: 'Chamomile Blend', text: 'Chamomile Blend'},\n {value: 'Oriental Delight', text: 'Oriental Delight'},\n {value: 'Anteadote White Tea Iced', text: 'Anteadote White Tea Iced'},\n {value: 'Puerh Special Grade', text: 'Puerh Special Grade'},\n {value: 'Strawberry White Tea', text: 'Strawberry White Tea'},\n {value: 'Sweet Sakura Black Tea', text: 'Sweet Sakura Black Tea'},\n {value: 'Red Choc Mint', text: 'Red Choc Mint'},\n {value: 'White Lotus', text: 'White Lotus'},\n {value: 'Apricot Amaretto', text: 'Apricot Amaretto'},\n {value: 'Cranberry Apple Zinger', text: 'Cranberry Apple Zinger'},\n {value: 'Raspberry Mate', text: 'Raspberry Mate'},\n {value: 'Cinnamon Roll', text: 'Cinnamon Roll'},\n {value: 'Green Spiced Chai', text: 'Green Spiced Chai'},\n {value: 'Finest Lady Grey', text: 'Finest Lady Grey'},\n {value: 'Ruby Red', text: 'Ruby Red'},\n {value: '1980s WangZi loose leaf Sheng Puerh',\n text: '1980s WangZi loose leaf Sheng Puerh'},\n {value: 'Strawberry/Lichee Green', text: 'Strawberry/Lichee Green'},\n {value: 'Bai Hao Yin Zhen (organic)', text: 'Bai Hao Yin Zhen (organic)'},\n {value: 'Organic White Peony (Bai Mu Dan)',\n text: 'Organic White Peony (Bai Mu Dan)'},\n {value: 'Lemon French Macaron', text: 'Lemon French Macaron'},\n {value: 'Cream of Vanilla', text: 'Cream of Vanilla'},\n {value: 'ZG67: Lung-Ching (Long-Jing) Dragon Well',\n text: 'ZG67: Lung-Ching (Long-Jing) Dragon Well'},\n {value: 'Sweet Grace Vanilla Rooibos',\n text: 'Sweet Grace Vanilla Rooibos'},\n {value: 'Black Powder Blend', text: 'Black Powder Blend'},\n {value: 'Hand Picked Autumn Tieguanyin (2011)',\n text: 'Hand Picked Autumn Tieguanyin (2011)'},\n {value: 'Vanilla Tea', text: 'Vanilla Tea'},\n {value: 'Goji berry blueberry pomegranted green tea',\n text: 'Goji berry blueberry pomegranted green tea'},\n {value: 'Coconut Assam', text: 'Coconut Assam'},\n {value: 'Apple Lemon Pomegranate Rooibos',\n text: 'Apple Lemon Pomegranate Rooibos'},\n {value: 'Ice Age', text: 'Ice Age'},\n {value: 'Ceylon Vithanakande FBOPF1', text: 'Ceylon Vithanakande FBOPF1'},\n {value: 'Takibi', text: 'Takibi'},\n {value: 'Dieters Herbal Drink', text: 'Dieters Herbal Drink'},\n {value: 'Rooibos Tropics', text: 'Rooibos Tropics'},\n {value: 'Formosa Tung Ting Jade Oolong (618)',\n text: 'Formosa Tung Ting Jade Oolong (618)'},\n {value: 'memtea', text: 'memtea'},\n {value: 'Eight Candles', text: 'Eight Candles'},\n {value: 'Jiu Qu Hong Mei', text: 'Jiu Qu Hong Mei'},\n {value: 'Mandarin Orange Sencha', text: 'Mandarin Orange Sencha'},\n {value: 'Lady Bedford', text: 'Lady Bedford'},\n {value: 'Margarets Hope SFTGFOP1 - Autumnal Darjeeling - 173',\n text: 'Margarets Hope SFTGFOP1 - Autumnal Darjeeling - 173'},\n {value: 'Bao Zhong Royale Oolong', text: 'Bao Zhong Royale Oolong'},\n {value: '2006 Menghai V8 Pu-Erh Toucha',\n text: '2006 Menghai V8 Pu-Erh Toucha'},\n {value: 'Apricot Fusion', text: 'Apricot Fusion'},\n {value: 'Provence Rooibos', text: 'Provence Rooibos'},\n {value: 'San Lin Xi Oolong (Fragrant Aroma)',\n text: 'San Lin Xi Oolong (Fragrant Aroma)'},\n {value: 'Green Tea Decaf', text: 'Green Tea Decaf'},\n {value: 'Keemun Royal', text: 'Keemun Royal'},\n {value: 'Moroccan Mint No. 1580', text: 'Moroccan Mint No. 1580'},\n {value: 'Jasmine 3rd Grade', text: 'Jasmine 3rd Grade'},\n {value: 'Lime Gelato', text: 'Lime Gelato'},\n {value: 'Exotica', text: 'Exotica'},\n {value: 'Inca Rose', text: 'Inca Rose'},\n {value: 'Maharaja Chai/Samurai Chai Tea Blend',\n text: 'Maharaja Chai/Samurai Chai Tea Blend'},\n {value: 'Arjuna', text: 'Arjuna'},\n {value: 'Pomegranate Blackberry Iced Tea',\n text: 'Pomegranate Blackberry Iced Tea'},\n {value: 'Soho Spice', text: 'Soho Spice'},\n {value: 'Special Rare Assam Doomur Dulling',\n text: 'Special Rare Assam Doomur Dulling'},\n {value: 'Wild Purple Buds Puerh', text: 'Wild Purple Buds Puerh'},\n {value: 'Morning Mama', text: 'Morning Mama'},\n {value: 'BALANCE: Ladies’ TLC – Dong Quai Horsetail Rose Petals',\n text: 'BALANCE: Ladies’ TLC – Dong Quai Horsetail Rose Petals'},\n {value: 'Dejoo Estate STGFOP1S (TA44)',\n text: 'Dejoo Estate STGFOP1S (TA44)'},\n {value: 'Chai (Full-Leaf Tea)', text: 'Chai (Full-Leaf Tea)'},\n {value: 'Driven Innocence', text: 'Driven Innocence'},\n {value: 'Glenburn Green Darjeeling', text: 'Glenburn Green Darjeeling'},\n {value: 'Lemon Honey Chamomile', text: 'Lemon Honey Chamomile'},\n {value: 'Blackcurrent Bracer', text: 'Blackcurrent Bracer'},\n {value: 'Triple Threat Temptation', text: 'Triple Threat Temptation'},\n {value: 'Yunnan Tuo', text: 'Yunnan Tuo'},\n {value: 'Through the Grapevine', text: 'Through the Grapevine'},\n {value: 'The Tenth Doctor', text: 'The Tenth Doctor'},\n {value: 'Coconut Cream Chai Organic', text: 'Coconut Cream Chai Organic'},\n {value: 'Natural solutions -dulces sueños (sweet dreams)',\n text: 'Natural solutions -dulces sueños (sweet dreams)'},\n {value: 'Caramel Creme Brulee', text: 'Caramel Creme Brulee'},\n {value: 'Renaissance', text: 'Renaissance'},\n {value: 'Ti Kuan Yin China Oolong Tea',\n text: 'Ti Kuan Yin China Oolong Tea'},\n {value: 'Especial Yerba Mate', text: 'Especial Yerba Mate'},\n {value: 'Inukshuk Blueberry Icewine Tea',\n text: 'Inukshuk Blueberry Icewine Tea'},\n {value: 'Darjeeling SFTGFOP I ff Jungpana',\n text: 'Darjeeling SFTGFOP I ff Jungpana'},\n {value: 'Himalayan Shila Black', text: 'Himalayan Shila Black'},\n {value: 'Decaf White', text: 'Decaf White'},\n {value: 'Japanese Garden', text: 'Japanese Garden'},\n {value: 'Caramel Pu-erh', text: 'Caramel Pu-erh'},\n {value: 'Berry Sinful', text: 'Berry Sinful'},\n {value: 'Silver Needle White Tea', text: 'Silver Needle White Tea'},\n {value: 'Dongshan Dolce', text: 'Dongshan Dolce'},\n {value: 'Raspberry Truffle Matcha', text: 'Raspberry Truffle Matcha'},\n {value: 'fim do verão', text: 'fim do verão'},\n {value: 'Cotton Candy Black Tea', text: 'Cotton Candy Black Tea'},\n {value: 'Iron Roast Buddha', text: 'Iron Roast Buddha'},\n {value: 'Qing Beencha Golden Sail 2005',\n text: 'Qing Beencha Golden Sail 2005'},\n {value: 'Organic Gold-flecked Green', text: 'Organic Gold-flecked Green'},\n {value: 'Spicy Pear', text: 'Spicy Pear'},\n {value: 'Nokcha (Korea)', text: 'Nokcha (Korea)'},\n {value: 'Kenilworth Ceylon', text: 'Kenilworth Ceylon'},\n {value: 'Ambangulu - Tanzania', text: 'Ambangulu - Tanzania'},\n {value: 'Dawn Chorus', text: 'Dawn Chorus'},\n {value: 'Gold Genmai-Cha Brown Rice Tea (Traditional Series)',\n text: 'Gold Genmai-Cha Brown Rice Tea (Traditional Series)'},\n {value: 'Shizuoka Shincha', text: 'Shizuoka Shincha'},\n {value: 'Yuzu', text: 'Yuzu'},\n {value: 'Superior Breakfast Tea', text: 'Superior Breakfast Tea'},\n {value: 'Good Morning Sunshine', text: 'Good Morning Sunshine'},\n {value: 'Kava Stress Relief', text: 'Kava Stress Relief'},\n {value: 'Long Jing (Dragon Well)', text: 'Long Jing (Dragon Well)'},\n {value: 'Ali Shan Mr.Chen', text: 'Ali Shan Mr.Chen'},\n {value: 'Golden Tips No.19', text: 'Golden Tips No.19'},\n {value: 'China Classic Oolong', text: 'China Classic Oolong'},\n {value: 'Spicy Christmas White tea', text: 'Spicy Christmas White tea'},\n {value: 'Sunrise', text: 'Sunrise'},\n {value: 'Maidens Ecstasy', text: 'Maidens Ecstasy'},\n {value: 'Peach Tea', text: 'Peach Tea'},\n {value: 'lighthouse tea', text: 'lighthouse tea'},\n {value: 'Davids Breakfast Tea (organic)',\n text: 'Davids Breakfast Tea (organic)'},\n {value: 'Ali Shan 1991 (charcoal)', text: 'Ali Shan 1991 (charcoal)'},\n {value: 'Lychee Black Tea', text: 'Lychee Black Tea'},\n {value: 'Coconut Truffle', text: 'Coconut Truffle'},\n {value: 'Assam Chai', text: 'Assam Chai'},\n {value: 'Ceylon Derangala', text: 'Ceylon Derangala'},\n {value: 'Jasmine Green with Pomegranate',\n text: 'Jasmine Green with Pomegranate'},\n {value: 'Marakesh Mint (AKA Green Tea with Mint)',\n text: 'Marakesh Mint (AKA Green Tea with Mint)'},\n {value: 'Earl Grey Cheesecake', text: 'Earl Grey Cheesecake'},\n {value: 'Nishi Sencha 1st Flush', text: 'Nishi Sencha 1st Flush'},\n {value: 'Morgan Blend Tea', text: 'Morgan Blend Tea'},\n {value: 'Kekecha Yellow', text: 'Kekecha Yellow'},\n {value: 'East Fresian', text: 'East Fresian'},\n {value: 'Revontuli - Northern Lights',\n text: 'Revontuli - Northern Lights'},\n {value: 'Pre-Ming Fuxi Huangshan Maofeng',\n text: 'Pre-Ming Fuxi Huangshan Maofeng'},\n {value: 'Honey Vanilla Chamomile', text: 'Honey Vanilla Chamomile'},\n {value: 'Yun Nan Dian Hong Black Tea',\n text: 'Yun Nan Dian Hong Black Tea'},\n {value: 'Green PuErh', text: 'Green PuErh'},\n {value: 'Kombucha Lime', text: 'Kombucha Lime'},\n {value: '2009 Menghai Dayi 7542', text: '2009 Menghai Dayi 7542'},\n {value: 'Rose Petal Black', text: 'Rose Petal Black'},\n {value: 'Rice Tuocha', text: 'Rice Tuocha'},\n {value: 'Thé Mélange Russe (Russian Blend) (TE77)',\n text: 'Thé Mélange Russe (Russian Blend) (TE77)'},\n {value: 'ToLife', text: 'ToLife'},\n {value: 'Camellia Sinensis', text: 'Camellia Sinensis'},\n {value: 'Violet Mint', text: 'Violet Mint'},\n {value: 'Coffee Cake', text: 'Coffee Cake'},\n {value: 'Tipus Microground Instant Chai (DUPLICATE)',\n text: 'Tipus Microground Instant Chai (DUPLICATE)'},\n {value: 'Blueberry Flavoured White', text: 'Blueberry Flavoured White'},\n {value: '2007 Organic Banzhang Tribute Pu-erh Tea Cake',\n text: '2007 Organic Banzhang Tribute Pu-erh Tea Cake'},\n {value: 'Tropical Sun', text: 'Tropical Sun'},\n {value: 'Turzum clonal delight sftgfop-1 Organic 2nd Flush 2010',\n text: 'Turzum clonal delight sftgfop-1 Organic 2nd Flush 2010'},\n {value: 'Darjeeling Gopaldhara FTGFOP1',\n text: 'Darjeeling Gopaldhara FTGFOP1'},\n {value: 'Earl of Africa', text: 'Earl of Africa'},\n {value: 'Che Shun Hao Yiwu Been (04 Stone Pressed Sheng)',\n text: 'Che Shun Hao Yiwu Been (04 Stone Pressed Sheng)'},\n {value: 'Linden Flower', text: 'Linden Flower'},\n {value: 'Yunnan Puer / Puerh Brick Tea 7581 Ripe 2010',\n text: 'Yunnan Puer / Puerh Brick Tea 7581 Ripe 2010'},\n {value: '2011 Yunnan Sourcing Pasha Mountain Autumn Raw Puerh',\n text: '2011 Yunnan Sourcing Pasha Mountain Autumn Raw Puerh'},\n {value: 'Bai Hao 68', text: 'Bai Hao 68'},\n {value: 'Formosa Fancy King Oolong', text: 'Formosa Fancy King Oolong'},\n {value: 'Tie Guan Yin (Light Oxidation)',\n text: 'Tie Guan Yin (Light Oxidation)'},\n {value: 'Golden Needle King', text: 'Golden Needle King'},\n {value: 'Yinzhen Bai Hao (Silver Needle)',\n text: 'Yinzhen Bai Hao (Silver Needle)'},\n {value: 'White Chocolate Kisses', text: 'White Chocolate Kisses'},\n {value: 'Matcha Kaze', text: 'Matcha Kaze'},\n {value: 'Micro-fermented sencha from Sayama Musashi-kaori cultivar',\n text: 'Micro-fermented sencha from Sayama Musashi-kaori cultivar'},\n {value: 'Pu-erh Tuocha Tea', text: 'Pu-erh Tuocha Tea'},\n {value: 'Pure Green — Organic', text: 'Pure Green — Organic'},\n {value: 'Digestive', text: 'Digestive'},\n {value: 'Cocomama Lime', text: 'Cocomama Lime'},\n {value: 'Victorian Garden', text: 'Victorian Garden'},\n {value: 'Ginger Peach Oolong', text: 'Ginger Peach Oolong'},\n {value: 'Zhu Hai Jin Ming', text: 'Zhu Hai Jin Ming'},\n {value: 'Charcoal Roasted Gan De Village Tie Guan Yin * Autumn 2011',\n text: 'Charcoal Roasted Gan De Village Tie Guan Yin * Autumn 2011'},\n {value: 'Whisky White', text: 'Whisky White'},\n {value: 'Organic Green Tea Powder', text: 'Organic Green Tea Powder'},\n {value: '2012 Spring White-bud Pu-erh',\n text: '2012 Spring White-bud Pu-erh'},\n {value: 'Coco Truffle', text: 'Coco Truffle'},\n {value: 'Wildberry', text: 'Wildberry'},\n {value: 'Ahhh.....Mocha Nut Latte', text: 'Ahhh.....Mocha Nut Latte'},\n {value: 'Organic Sourenee Second Flush',\n text: 'Organic Sourenee Second Flush'},\n {value: 'Organic White Tea with Vanilla',\n text: 'Organic White Tea with Vanilla'},\n {value: 'Organic White Peony (Bai Mu Dan) Tea',\n text: 'Organic White Peony (Bai Mu Dan) Tea'},\n {value: 'Gyokoro', text: 'Gyokoro'},\n {value: 'Grape Oolong', text: 'Grape Oolong'},\n {value: 'Chamomile Flowers', text: 'Chamomile Flowers'},\n {value: 'Cranberry Pomegranate', text: 'Cranberry Pomegranate'},\n {value: 'Original Masala Chai', text: 'Original Masala Chai'},\n {value: 'Jasmine Chun Hao', text: 'Jasmine Chun Hao'},\n {value: '2010 Manmai', text: '2010 Manmai'},\n {value: 'Citrus Paradisi Earl Grey', text: 'Citrus Paradisi Earl Grey'},\n {value: 'Kensington Breakfast Blend', text: 'Kensington Breakfast Blend'},\n {value: 'Blueberry', text: 'Blueberry'},\n {value: 'Golden Grade Oolong', text: 'Golden Grade Oolong'},\n {value: 'Etoile de France', text: 'Etoile de France'},\n {value: 'Lapsang Souchong Superior Smoked Tea',\n text: 'Lapsang Souchong Superior Smoked Tea'},\n {value: 'Fairtrade Organic Assam Tea with Vanilla',\n text: 'Fairtrade Organic Assam Tea with Vanilla'},\n {value: 'Huo Shan Yellow Sprouting (2009 Pre-Qing Ming)',\n text: 'Huo Shan Yellow Sprouting (2009 Pre-Qing Ming)'},\n {value: 'Candy Cane Green Tea', text: 'Candy Cane Green Tea'},\n {value: 'Yun Nan Dian Hong Black Tea Full-Leaf',\n text: 'Yun Nan Dian Hong Black Tea Full-Leaf'},\n {value: 'Organic Coal Bakes Oolong', text: 'Organic Coal Bakes Oolong'},\n {value: 'Kenya CTC', text: 'Kenya CTC'},\n {value: 'Dan Cong Feng Huang', text: 'Dan Cong Feng Huang'},\n {value: 'Black Forest Rooibos', text: 'Black Forest Rooibos'},\n {value: '2009 Winter Tie Guan Yin - Taiwan Oolong Tea',\n text: '2009 Winter Tie Guan Yin - Taiwan Oolong Tea'},\n {value: 'Chocolate Flake Tea', text: 'Chocolate Flake Tea'},\n {value: 'Ginger Orange', text: 'Ginger Orange'},\n {value: 'Red Lavender', text: 'Red Lavender'},\n {value: 'Organic Relaxation', text: 'Organic Relaxation'},\n {value: '2011 Spring Long Mei Yunnan Green Tea of Zhenyuan',\n text: '2011 Spring Long Mei Yunnan Green Tea of Zhenyuan'},\n {value: 'Rum raisin biscotti', text: 'Rum raisin biscotti'},\n {value: 'Darjeeling Seeyok FTGFOP1 F.F.',\n text: 'Darjeeling Seeyok FTGFOP1 F.F.'},\n {value: 'Pure Jasmine Green Tea', text: 'Pure Jasmine Green Tea'},\n {value: 'China Gunpowder', text: 'China Gunpowder'},\n {value: 'Sweet Almond', text: 'Sweet Almond'},\n {value: 'Tan Yang Jing Zhi', text: 'Tan Yang Jing Zhi'},\n {value: 'PassionFruit Papaya', text: 'PassionFruit Papaya'},\n {value: 'Darjeeling Silver Tips', text: 'Darjeeling Silver Tips'},\n {value: 'Organic Silver Bud Melon Frost',\n text: 'Organic Silver Bud Melon Frost'},\n {value: 'Red Cherry (Sip for the Cure)',\n text: 'Red Cherry (Sip for the Cure)'},\n {value: 'Russian Wine', text: 'Russian Wine'},\n {value: 'Jasmine Blossom', text: 'Jasmine Blossom'},\n {value: 'Golden Tip Yunnan (ZY76)', text: 'Golden Tip Yunnan (ZY76)'},\n {value: 'Alotta Lemon &amp; Ginger', text: 'Alotta Lemon &amp; Ginger'},\n {value: 'White Milk Tea 3 in 1', text: 'White Milk Tea 3 in 1'},\n {value: 'Darjeeling Autumn Oolong', text: 'Darjeeling Autumn Oolong'},\n {value: 'Long Jing Huang Pao', text: 'Long Jing Huang Pao'},\n {value: 'Yu Lu Yan Cha Black', text: 'Yu Lu Yan Cha Black'},\n {value: '2003 Golden Sail Brand Yunnan Pu-erh',\n text: '2003 Golden Sail Brand Yunnan Pu-erh'},\n {value: '2006 Loose Golden Leaf Imperial Pu-Erh',\n text: '2006 Loose Golden Leaf Imperial Pu-Erh'},\n {value: 'Staufs Darjeeling FTGFOP1Autumnal Blend',\n text: 'Staufs Darjeeling FTGFOP1Autumnal Blend'},\n {value: 'Green Snail Spring (Bi Luo Chun) Competition Grade',\n text: 'Green Snail Spring (Bi Luo Chun) Competition Grade'},\n {value: '2007 Mu Ye Chun 002', text: '2007 Mu Ye Chun 002'},\n {value: 'Matcha Green Tea Powder by Hamasaen Br',\n text: 'Matcha Green Tea Powder by Hamasaen Br'},\n {value: 'Hubei Province China Keemun Ji Hong',\n text: 'Hubei Province China Keemun Ji Hong'},\n {value: 'Black Bear Darjeeling', text: 'Black Bear Darjeeling'},\n {value: 'Shizuoka Sencha Hatsumi', text: 'Shizuoka Sencha Hatsumi'},\n {value: 'Feng Qing Gold Bud Yunnan Black tea * Dian Hong * Autumn 2011',\n text: 'Feng Qing Gold Bud Yunnan Black tea'},\n {value: 'Premium Formosa Lapsang Souchong (TT70)',\n text: 'Premium Formosa Lapsang Souchong (TT70)'},\n {value: 'Coco Latte', text: 'Coco Latte'},\n {value: 'Russian Superior 2', text: 'Russian Superior 2'},\n {value: 'Green Tea with Fresh Jasmine',\n text: 'Green Tea with Fresh Jasmine'},\n {value: 'Song Yang', text: 'Song Yang'},\n {value: 'Decaf Darjeeling', text: 'Decaf Darjeeling'},\n {value: 'Organic Moroccan Mint', text: 'Organic Moroccan Mint'},\n {value: 'Mt Huang Sparrow Tongue', text: 'Mt Huang Sparrow Tongue'},\n {value: 'Ruby Chai Spiced Rooibos', text: 'Ruby Chai Spiced Rooibos'},\n {value: 'Coconut Euphoria', text: 'Coconut Euphoria'},\n {value: 'Castleton Moonlight Darjeeling Oolong',\n text: 'Castleton Moonlight Darjeeling Oolong'},\n {value: 'Caramel black', text: 'Caramel black'},\n {value: 'Herbal Spiced Chai', text: 'Herbal Spiced Chai'},\n {value: 'Blueberry Purple Tea', text: 'Blueberry Purple Tea'},\n {value: 'English Evening', text: 'English Evening'},\n {value: 'Cranberry Pear', text: 'Cranberry Pear'},\n {value: 'Blueberry/Blackberry Herbal tea (teabags are placed in one of Teamans canister)',\n text: 'Blueberry/Blackberry Herbal tea'},\n {value: 'Kagoshima Sencha Yutaka Midori Supreme',\n text: 'Kagoshima Sencha Yutaka Midori Supreme'},\n {value: 'A Chestnut Chai', text: 'A Chestnut Chai'},\n {value: 'Pomegranate', text: 'Pomegranate'},\n {value: 'Esprit de Noël - Noël', text: 'Esprit de Noël - Noël'},\n {value: 'Love Your Life', text: 'Love Your Life'},\n {value: 'Yerba Mate Peach', text: 'Yerba Mate Peach'},\n {value: 'Surabaya', text: 'Surabaya'},\n {value: 'Decaf Paris Vanilla', text: 'Decaf Paris Vanilla'},\n {value: 'Uva Highlands Ceylon BOP', text: 'Uva Highlands Ceylon BOP'},\n {value: 'Love Affair', text: 'Love Affair'},\n {value: 'Dancing Leaves (Organic)', text: 'Dancing Leaves (Organic)'},\n {value: 'Samurai Chai Maté', text: 'Samurai Chai Maté'},\n {value: 'Snow Buds', text: 'Snow Buds'},\n {value: 'Sarsaparilla', text: 'Sarsaparilla'},\n {value: 'Bi Luo Chun Green Tea (Pi Lo Chun)',\n text: 'Bi Luo Chun Green Tea (Pi Lo Chun)'},\n {value: 'White Hair Monkey Tea', text: 'White Hair Monkey Tea'},\n {value: 'Yunnan White Jasmine', text: 'Yunnan White Jasmine'},\n {value: 'Rui Feng Jin Xuan', text: 'Rui Feng Jin Xuan'},\n {value: 'Sencha of the Spring Sun', text: 'Sencha of the Spring Sun'},\n {value: 'Long Island Strawberry Sencha',\n text: 'Long Island Strawberry Sencha'},\n {value: 'Bavarian Cream Matcha (50/50 Matcha Base)',\n text: 'Bavarian Cream Matcha (50/50 Matcha Base)'},\n {value: 'Taiwan Da Yu Ling Oolong Tea',\n text: 'Taiwan Da Yu Ling Oolong Tea'},\n {value: '2012 First Flush Margarets Hope SFTGFOP1',\n text: '2012 First Flush Margarets Hope SFTGFOP1'},\n {value: 'Cold Zing (organic)', text: 'Cold Zing (organic)'},\n {value: 'Autumns Walk', text: 'Autumns Walk'},\n {value: 'Kabuse-Cha', text: 'Kabuse-Cha'},\n {value: 'Heavens Trash', text: 'Heavens Trash'},\n {value: 'Lord Petersham', text: 'Lord Petersham'},\n {value: '1980s (early) Snow Mark 7532',\n text: '1980s (early) Snow Mark 7532'},\n {value: 'Iced Mango Green', text: 'Iced Mango Green'},\n {value: 'Crimson Berry Tisane', text: 'Crimson Berry Tisane'},\n {value: 'Clipper Gold Loose Leaf', text: 'Clipper Gold Loose Leaf'},\n {value: 'Fusion Breakfast Green and Black',\n text: 'Fusion Breakfast Green and Black'},\n {value: 'Karigane 22', text: 'Karigane 22'},\n {value: '1992 loose pu-erh m3t', text: '1992 loose pu-erh m3t'},\n {value: 'Fantasy Island', text: 'Fantasy Island'},\n {value: 'Shui Xian Oolong', text: 'Shui Xian Oolong'},\n {value: 'Irish Cream Matcha', text: 'Irish Cream Matcha'},\n {value: 'Tung Ting Oolong No. 628', text: 'Tung Ting Oolong No. 628'},\n {value: 'Organic Matcha', text: 'Organic Matcha'},\n {value: 'Darjeeling Estate-8', text: 'Darjeeling Estate-8'},\n {value: 'Decaf Citron Green', text: 'Decaf Citron Green'},\n {value: 'Lime and Coconut Sencha', text: 'Lime and Coconut Sencha'},\n {value: 'Golden Kenya TGFOP (TK30)', text: 'Golden Kenya TGFOP (TK30)'},\n {value: 'Iron Goddess of Mercy - Yi Kuan Yin - Green',\n text: 'Iron Goddess of Mercy - Yi Kuan Yin - Green'},\n {value: 'Kenyan Tinderet', text: 'Kenyan Tinderet'},\n {value: 'Christmas Cake', text: 'Christmas Cake'},\n {value: 'Scarlet Sable', text: 'Scarlet Sable'},\n {value: 'Durbanville Rooibos', text: 'Durbanville Rooibos'},\n {value: 'Fired Up Fennel', text: 'Fired Up Fennel'},\n {value: 'Xu Fu Long Ya', text: 'Xu Fu Long Ya'},\n {value: 'Puttabong Estate - Second Flush Darjeeling SFTGFOP1',\n text: 'Puttabong Estate - Second Flush Darjeeling SFTGFOP1'},\n {value: 'Instant Korean Ginseng Tea', text: 'Instant Korean Ginseng Tea'},\n {value: 'Vanilla Jazz', text: 'Vanilla Jazz'},\n {value: 'Bi Lu Chun', text: 'Bi Lu Chun'},\n {value: 'Rhubarb &amp; Strawberry', text: 'Rhubarb &amp; Strawberry'},\n {value: 'Au Lait Verde', text: 'Au Lait Verde'},\n {value: 'Aavikkokerma - Desert Cream',\n text: 'Aavikkokerma - Desert Cream'},\n {value: 'Mengding Mountain Rock Essence (2009 Pre-Qing Ming)',\n text: 'Mengding Mountain Rock Essence (2009 Pre-Qing Ming)'},\n {value: 'Lime Jello Salad Green Tea', text: 'Lime Jello Salad Green Tea'},\n {value: 'Darjeeling Phoobsering 1st Flush Organic',\n text: 'Darjeeling Phoobsering 1st Flush Organic'},\n {value: 'Yi Fu Chun Black Tea', text: 'Yi Fu Chun Black Tea'},\n {value: 'Sparrows Tongue (Korea)', text: 'Sparrows Tongue (Korea)'},\n {value: 'Zest Tea', text: 'Zest Tea'},\n {value: 'Lemon Soleil', text: 'Lemon Soleil'},\n {value: 'Organic Arya Ruby First Flush Darjeeling',\n text: 'Organic Arya Ruby First Flush Darjeeling'},\n {value: 'Castleton Estate 1st Flush Darjeeling DJ-17',\n text: 'Castleton Estate 1st Flush Darjeeling DJ-17'},\n {value: 'Genmai-Cha Brown Rice Tea (Traditional Series)',\n text: 'Genmai-Cha Brown Rice Tea (Traditional Series)'},\n {value: 'Tae Guan Yin Iron Goddess of Mercy',\n text: 'Tae Guan Yin Iron Goddess of Mercy'},\n {value: 'Xue Lan Xiang (Snow Orchid) Dan Cong Oolong 2009',\n text: 'Xue Lan Xiang (Snow Orchid) Dan Cong Oolong 2009'},\n {value: 'Sencha Kyoto Cherry Rose Green Tea',\n text: 'Sencha Kyoto Cherry Rose Green Tea'},\n {value: 'Imperial Black Tea Blend', text: 'Imperial Black Tea Blend'},\n {value: 'Organic Green Leaf Kukicha', text: 'Organic Green Leaf Kukicha'},\n {value: 'Kashmir Khali-Kahwa', text: 'Kashmir Khali-Kahwa'},\n {value: 'Organic Ancient Green Pu-Erh Tuo Cha',\n text: 'Organic Ancient Green Pu-Erh Tuo Cha'},\n {value: 'English Breakfast Leaf Tea', text: 'English Breakfast Leaf Tea'},\n {value: 'Imperial Concubines Smile | Fei Zi Xiao',\n text: 'Imperial Concubines Smile | Fei Zi Xiao'},\n {value: 'Honey Pear', text: 'Honey Pear'},\n {value: 'Monsieur', text: 'Monsieur'},\n {value: 'Precious White Peach', text: 'Precious White Peach'},\n {value: 'Tea 380', text: 'Tea 380'},\n {value: 'Brigittes Blend', text: 'Brigittes Blend'},\n {value: 'Rooibos Apricot Cinnamon', text: 'Rooibos Apricot Cinnamon'},\n {value: 'Comforting', text: 'Comforting'},\n {value: 'Top Panyang Gold [Out of Stock]',\n text: 'Top Panyang Gold [Out of Stock]'},\n {value: 'Assam Mokalbari SFTGFOP1', text: 'Assam Mokalbari SFTGFOP1'},\n {value: 'Berry Berry', text: 'Berry Berry'},\n {value: 'Hoku', text: 'Hoku'},\n {value: 'Wild Blackcurrant', text: 'Wild Blackcurrant'},\n {value: 'India Darjeeling Tea', text: 'India Darjeeling Tea'},\n {value: 'Brown Rice Matcha', text: 'Brown Rice Matcha'},\n {value: 'Sugar Cookie Sleigh Ride', text: 'Sugar Cookie Sleigh Ride'},\n {value: 'Organic fair trade Darjeeling Seeyok Dj-6 1st flush',\n text: 'Organic fair trade Darjeeling Seeyok Dj-6 1st flush'},\n {value: 'Pu-erh Mini Toucha', text: 'Pu-erh Mini Toucha'},\n {value: 'Yue Guang Bai Cake', text: 'Yue Guang Bai Cake'},\n {value: 'Monkey Pick Green', text: 'Monkey Pick Green'},\n {value: 'Jardin Bleu', text: 'Jardin Bleu'},\n {value: 'Vietnam Goldblatt Nam Lanh', text: 'Vietnam Goldblatt Nam Lanh'},\n {value: 'Tranebær og Yougurt', text: 'Tranebær og Yougurt'},\n {value: 'Red grapefruit and orange (fruit wellness)',\n text: 'Red grapefruit and orange (fruit wellness)'},\n {value: 'Jasmine Passion', text: 'Jasmine Passion'},\n {value: 'Dragon 4 Flowers', text: 'Dragon 4 Flowers'},\n {value: 'Imperial Wild-Growing Long Jing Dragon Well',\n text: 'Imperial Wild-Growing Long Jing Dragon Well'},\n {value: 'Pina Colada Carmen Miranda', text: 'Pina Colada Carmen Miranda'},\n {value: 'Coconut Crème', text: 'Coconut Crème'},\n {value: 'White Tea Wu-long', text: 'White Tea Wu-long'},\n {value: 'Barrys Classic Blend', text: 'Barrys Classic Blend'},\n {value: 'Rose Green Tea', text: 'Rose Green Tea'},\n {value: 'serendipitea', text: 'serendipitea'},\n {value: 'Yi Chang Hao Yi Wu Zhengpin 2004 (Xiao Lan Zi)',\n text: 'Yi Chang Hao Yi Wu Zhengpin 2004 (Xiao Lan Zi)'},\n {value: 'Maeda-en Sen-cha Tea Bags', text: 'Maeda-en Sen-cha Tea Bags'},\n {value: 'Peach Oolong Tea', text: 'Peach Oolong Tea'},\n {value: 'China Jasmine Green', text: 'China Jasmine Green'},\n {value: 'Blissful Buds', text: 'Blissful Buds'},\n {value: 'Taiwan Dong Ding (Tung Ting) Oolong Tea',\n text: 'Taiwan Dong Ding (Tung Ting) Oolong Tea'},\n {value: '2010 Yunnan Sourcing NanNuo YaKouZhai Raw',\n text: '2010 Yunnan Sourcing NanNuo YaKouZhai Raw'},\n {value: 'Thousand Mountain Jasmine', text: 'Thousand Mountain Jasmine'},\n {value: 'Darjeeling Goomtee FTGFOP1 First Flush',\n text: 'Darjeeling Goomtee FTGFOP1 First Flush'},\n {value: '2007 Menghai Dayi Golden Needle White Lotus Ripe',\n text: '2007 Menghai Dayi Golden Needle White Lotus Ripe'},\n {value: 'Frutti di Bosco e Vitamine / Soft Fruits &amp; Vitamins',\n text: 'Frutti di Bosco e Vitamine / Soft Fruits &amp; Vitamins'},\n {value: 'Thé des Sables', text: 'Thé des Sables'},\n {value: 'Darjeeling Princeton TGFOP1',\n text: 'Darjeeling Princeton TGFOP1'},\n {value: 'Assam: Whole Leaf English Breakfast Blend',\n text: 'Assam: Whole Leaf English Breakfast Blend'},\n {value: 'Valkoinen Helmi Vanilja - White Pearl Vanilla',\n text: 'Valkoinen Helmi Vanilja - White Pearl Vanilla'},\n {value: 'TI88: Malabar Estate Java OP Clonal',\n text: 'TI88: Malabar Estate Java OP Clonal'},\n {value: 'Shanti', text: 'Shanti'},\n {value: 'Honeysuckle White Tea', text: 'Honeysuckle White Tea'},\n {value: 'Creamy Eggnog', text: 'Creamy Eggnog'},\n {value: 'Green Coconut', text: 'Green Coconut'},\n {value: 'Empress Garden', text: 'Empress Garden'},\n {value: 'Energizer Monkey', text: 'Energizer Monkey'},\n {value: 'French Blend', text: 'French Blend'},\n {value: 'Queen Victoria', text: 'Queen Victoria'},\n {value: 'Zhang Shu Lake Oolong', text: 'Zhang Shu Lake Oolong'},\n {value: 'Cold Relief', text: 'Cold Relief'},\n {value: 'Sen-Cha Fukamushi Reserve (Blenders Series)',\n text: 'Sen-Cha Fukamushi Reserve (Blenders Series)'},\n {value: 'Cape Cod Cranberry Rooibos', text: 'Cape Cod Cranberry Rooibos'},\n {value: 'Thé vert à la vanille', text: 'Thé vert à la vanille'},\n {value: 'Assam 1', text: 'Assam 1'},\n {value: 'Earl Grey Green Tea', text: 'Earl Grey Green Tea'},\n {value: 'First Flush Darjeeling Jungpana',\n text: 'First Flush Darjeeling Jungpana'},\n {value: 'Apricot Honey', text: 'Apricot Honey'},\n {value: 'Riesling', text: 'Riesling'},\n {value: 'Green Mango Peach', text: 'Green Mango Peach'},\n {value: 'Black and White Tea', text: 'Black and White Tea'},\n {value: 'Christmas Eve Herbal Tea', text: 'Christmas Eve Herbal Tea'},\n {value: 'At Romance Tea', text: 'At Romance Tea'},\n {value: 'Blooming Tiger', text: 'Blooming Tiger'},\n {value: 'Pomegranate Oolong Iced', text: 'Pomegranate Oolong Iced'},\n {value: 'Coconut Bao Zhong (Pouchong)',\n text: 'Coconut Bao Zhong (Pouchong)'},\n {value: 'Organic Assam (sachets)', text: 'Organic Assam (sachets)'},\n {value: 'Snowflakes (Drum mountain white Gu Shan Bai Yun)',\n text: 'Snowflakes (Drum mountain white Gu Shan Bai Yun)'},\n {value: 'Andalusia', text: 'Andalusia'},\n {value: 'Rooibos Frappuccino', text: 'Rooibos Frappuccino'},\n {value: 'Joyeux Noël', text: 'Joyeux Noël'},\n {value: 'Yunnan XiaGuan Tea Factory JiaJi TuoCha 2007 raw',\n text: 'Yunnan XiaGuan Tea Factory JiaJi TuoCha 2007 raw'},\n {value: 'Dr. Andrew Weils Green White',\n text: 'Dr. Andrew Weils Green White'},\n {value: '10 Year Wood-Fired Tieguanyin',\n text: '10 Year Wood-Fired Tieguanyin'},\n {value: 'Creamed Earl Grey', text: 'Creamed Earl Grey'},\n {value: 'Peach Oo-la-long', text: 'Peach Oo-la-long'},\n {value: 'Rooibos Cinnamon Apple', text: 'Rooibos Cinnamon Apple'},\n {value: 'Bangkok White Rose', text: 'Bangkok White Rose'},\n {value: 'Makiki', text: 'Makiki'},\n {value: 'TEA Ceylon Select Earl Grey Blend',\n text: 'TEA Ceylon Select Earl Grey Blend'},\n {value: 'Black Pu-erh Tuo Cha', text: 'Black Pu-erh Tuo Cha'},\n {value: 'Organic Lemon Spice Botanical Tea',\n text: 'Organic Lemon Spice Botanical Tea'},\n {value: 'Peppermint and Spearmint', text: 'Peppermint and Spearmint'},\n {value: 'Organic Sencha Green Tea', text: 'Organic Sencha Green Tea'},\n {value: 'Queen Mary Blend Black Tea', text: 'Queen Mary Blend Black Tea'},\n {value: 'Smoky Tarry Lapsang Souchong',\n text: 'Smoky Tarry Lapsang Souchong'},\n {value: 'Indian Spiced Chai', text: 'Indian Spiced Chai'},\n {value: 'Green Goji Berry', text: 'Green Goji Berry'},\n {value: 'Idulgashinna Ceylon', text: 'Idulgashinna Ceylon'},\n {value: 'Purple Pu-erh', text: 'Purple Pu-erh'},\n {value: 'Rooibos Bourbon', text: 'Rooibos Bourbon'},\n {value: 'Japanese Spirit', text: 'Japanese Spirit'},\n {value: 'Darjeeling First Flush Margarets Hope',\n text: 'Darjeeling First Flush Margarets Hope'},\n {value: 'Jade Tips (Mao Jian)', text: 'Jade Tips (Mao Jian)'},\n {value: 'Strawberry Rose Champagne Oolong Tea',\n text: 'Strawberry Rose Champagne Oolong Tea'},\n {value: 'Qinglin Bao Zhong 1978', text: 'Qinglin Bao Zhong 1978'},\n {value: 'Jangpana 2nd Flush Darjeeling',\n text: 'Jangpana 2nd Flush Darjeeling'},\n {value: 'Muo Li Yin Zhen-Jasmine Silver Needle',\n text: 'Muo Li Yin Zhen-Jasmine Silver Needle'},\n {value: 'Sweet Ginger Heat (organic)',\n text: 'Sweet Ginger Heat (organic)'},\n {value: 'Tie Guan Yin Competition Grade Monkey Picked Oolong',\n text: 'Tie Guan Yin Competition Grade Monkey Picked Oolong'},\n {value: 'ZG41: China Green Sencha', text: 'ZG41: China Green Sencha'},\n {value: 'Ceylon Breakfast Tea', text: 'Ceylon Breakfast Tea'},\n {value: 'Raspberry Black Tea', text: 'Raspberry Black Tea'},\n {value: 'Tung Ting Spring 2014', text: 'Tung Ting Spring 2014'},\n {value: 'Fujian Baroque', text: 'Fujian Baroque'},\n {value: 'Fukamushi-Sencha Maki', text: 'Fukamushi-Sencha Maki'},\n {value: 'Ginger Orange Peach', text: 'Ginger Orange Peach'},\n {value: 'Fragrant Leaf', text: 'Fragrant Leaf'},\n {value: 'Banana Bake', text: 'Banana Bake'},\n {value: 'ChocoLatte Black Tea - Hazelnut Mocha',\n text: 'ChocoLatte Black Tea - Hazelnut Mocha'},\n {value: 'Holy Basil Purple Leaf (BH02)',\n text: 'Holy Basil Purple Leaf (BH02)'},\n {value: 'Star Village Black', text: 'Star Village Black'},\n {value: 'Gyokuro Suimei', text: 'Gyokuro Suimei'},\n {value: 'Dandelion Root', text: 'Dandelion Root'},\n {value: 'Beautiful Night (Yue Ye Yue Mei)',\n text: 'Beautiful Night (Yue Ye Yue Mei)'},\n {value: 'Spa Day', text: 'Spa Day'},\n {value: 'Chai latte', text: 'Chai latte'},\n {value: 'Chestnut Green Tea', text: 'Chestnut Green Tea'},\n {value: 'Assam Breakfast Black Tea', text: 'Assam Breakfast Black Tea'},\n {value: 'Pirates Brew - Signature Blend',\n text: 'Pirates Brew - Signature Blend'},\n {value: '2009 Fo Shou', text: '2009 Fo Shou'},\n {value: 'Winter Chocolate Rooibos', text: 'Winter Chocolate Rooibos'},\n {value: 'Tamayokucha (Extremely Green Tea)',\n text: 'Tamayokucha (Extremely Green Tea)'},\n {value: 'Silver Needle Supreme', text: 'Silver Needle Supreme'},\n {value: 'Menghai Dayi High Mountain Charm Ripe 2010',\n text: 'Menghai Dayi High Mountain Charm Ripe 2010'},\n {value: 'Monte Cristo', text: 'Monte Cristo'},\n {value: 'Organic Lemon Rooibos', text: 'Organic Lemon Rooibos'},\n {value: 'Tummy Mint Wellness Tea', text: 'Tummy Mint Wellness Tea'},\n {value: 'Champagne', text: 'Champagne'},\n {value: 'Plantain Coconut Raw Green Bush Tea',\n text: 'Plantain Coconut Raw Green Bush Tea'},\n {value: 'Orange Spice Black Tea', text: 'Orange Spice Black Tea'},\n {value: 'Laos Black 05', text: 'Laos Black 05'},\n {value: 'Temi SFTGFOP Second Flush', text: 'Temi SFTGFOP Second Flush'},\n {value: 'China Lung Ching 1st Grade', text: 'China Lung Ching 1st Grade'},\n {value: 'Rooibos Black Currant', text: 'Rooibos Black Currant'},\n {value: 'Marrakech', text: 'Marrakech'},\n {value: 'Zen Treasure Matcha ™', text: 'Zen Treasure Matcha ™'},\n {value: 'Lemon grass - gingembre', text: 'Lemon grass - gingembre'},\n {value: 'Ying Ming Yunnan Tea', text: 'Ying Ming Yunnan Tea'},\n {value: 'Rooibos Red Bush Tea', text: 'Rooibos Red Bush Tea'},\n {value: 'Organic Biochai', text: 'Organic Biochai'},\n {value: 'Micro-fermented sencha from Sayama Sayama-kaori cultivar',\n text: 'Micro-fermented sencha from Sayama Sayama-kaori cultivar'},\n {value: 'Chocolate Orange Slice', text: 'Chocolate Orange Slice'},\n {value: 'Christmas Eve (Un Soir de Noël)',\n text: 'Christmas Eve (Un Soir de Noël)'},\n {value: 'Black Strawberry', text: 'Black Strawberry'},\n {value: 'Ginger &amp; Liquorice', text: 'Ginger &amp; Liquorice'},\n {value: 'Green White', text: 'Green White'},\n {value: 'Rare hand made darjeeling', text: 'Rare hand made darjeeling'},\n {value: 'Pleasure', text: 'Pleasure'},\n {value: 'Lemon &amp; Orange', text: 'Lemon &amp; Orange'},\n {value: 'Sencha Premier', text: 'Sencha Premier'},\n {value: 'Karkadé or كركديه', text: 'Karkadé or كركديه'},\n {value: 'Thé des Sources', text: 'Thé des Sources'},\n {value: 'Keemun (English Breakfast)', text: 'Keemun (English Breakfast)'},\n {value: 'West Lake Long Jing', text: 'West Lake Long Jing'},\n {value: '2007 Meng Ba Na Cooked Puerh',\n text: '2007 Meng Ba Na Cooked Puerh'},\n {value: 'Dragonwell Tea Green Tea', text: 'Dragonwell Tea Green Tea'},\n {value: 'Rainforest Strong Green Tea',\n text: 'Rainforest Strong Green Tea'},\n {value: 'Organic Kagoshima Sencha Saemidori',\n text: 'Organic Kagoshima Sencha Saemidori'},\n {value: 'Blackberry Cassis', text: 'Blackberry Cassis'},\n {value: 'Organic Jade Oolong', text: 'Organic Jade Oolong'},\n {value: 'Organic Taiwan Jin Xuan Milk Dong Ding Oolong',\n text: 'Organic Taiwan Jin Xuan Milk Dong Ding Oolong'},\n {value: 'Yellow Peach', text: 'Yellow Peach'},\n {value: 'Cranberry Hibiscus', text: 'Cranberry Hibiscus'},\n {value: 'Eric Northman tb', text: 'Eric Northman tb'},\n {value: 'Satrupa Estate Spring Reserve STGFOP (Assam)',\n text: 'Satrupa Estate Spring Reserve STGFOP (Assam)'},\n {value: 'Oasis', text: 'Oasis'},\n {value: 'Gunpowder Mint', text: 'Gunpowder Mint'},\n {value: 'Old Tree Bohea (ZK78)', text: 'Old Tree Bohea (ZK78)'},\n {value: 'Greek Saffron Herbal Tea with Honey Orange and Selected Herbs',\n text: 'Greek Saffron Herbal Tea with Honey Orange and Selected Herbs'},\n {value: 'Matin', text: 'Matin'},\n {value: 'pearl', text: 'pearl'},\n {value: '2009 Guan Zi Zai Zao Chun Nan Nuo Shan Raw Pu-erh tea',\n text: '2009 Guan Zi Zai Zao Chun Nan Nuo Shan Raw Pu-erh tea'},\n {value: 'Lapsang Souchong Black Tea Grade II',\n text: 'Lapsang Souchong Black Tea Grade II'},\n {value: 'Himalayan Black', text: 'Himalayan Black'},\n {value: 'Grateful Castaways Chilipaya Sweet Tropical Heat',\n text: 'Grateful Castaways Chilipaya Sweet Tropical Heat'},\n {value: 'Huang Zhi Xiang', text: 'Huang Zhi Xiang'},\n {value: 'Snow Dragon (No. 529)', text: 'Snow Dragon (No. 529)'},\n {value: 'Passion Fruit Rooibos', text: 'Passion Fruit Rooibos'},\n {value: 'Green Tea with Ginseng and Honey',\n text: 'Green Tea with Ginseng and Honey'},\n {value: 'Indian Chai - Voyage', text: 'Indian Chai - Voyage'},\n {value: 'Hangzhou Shi Feng Long Jing',\n text: 'Hangzhou Shi Feng Long Jing'},\n {value: 'Happy Birthday', text: 'Happy Birthday'},\n {value: 'Golden Imperial Lotus', text: 'Golden Imperial Lotus'},\n {value: 'Snooze', text: 'Snooze'},\n {value: 'Green Tea Rejuvenation', text: 'Green Tea Rejuvenation'},\n {value: 'Par Amour', text: 'Par Amour'},\n {value: 'Jasmine Tulsi Tea', text: 'Jasmine Tulsi Tea'},\n {value: 'Buttered Cinnamon Raisin Toast Flavored Black Tea',\n text: 'Buttered Cinnamon Raisin Toast Flavored Black Tea'},\n {value: 'Alishan Tsou High Mountain Tea',\n text: 'Alishan Tsou High Mountain Tea'},\n {value: 'Inspiration Blend Rooibos', text: 'Inspiration Blend Rooibos'},\n {value: 'Lan Gui Ren-Ginseng Oolong', text: 'Lan Gui Ren-Ginseng Oolong'},\n {value: 'Organic Superfine Dragon Well Long Jing Green Tea',\n text: 'Organic Superfine Dragon Well Long Jing Green Tea'},\n {value: 'Richmond Park Blend TB86', text: 'Richmond Park Blend TB86'},\n {value: 'Huo Mountain Yellow Buds Yellow Tea',\n text: 'Huo Mountain Yellow Buds Yellow Tea'},\n {value: 'Royal Coconut', text: 'Royal Coconut'},\n {value: 'Shan Lin Xi Gao Shan Cha', text: 'Shan Lin Xi Gao Shan Cha'},\n {value: 'Christmas Tea - Mélange Noël (TE90)',\n text: 'Christmas Tea - Mélange Noël (TE90)'},\n {value: 'Da Hong Pao Hand Crafted', text: 'Da Hong Pao Hand Crafted'},\n {value: 'Vanilla Creme', text: 'Vanilla Creme'},\n {value: 'Pu Erh Bold Leaf Organic (No. 591)',\n text: 'Pu Erh Bold Leaf Organic (No. 591)'},\n {value: '2008 Winter Luanze Oolong from Da Yu Ling (2400 m)',\n text: '2008 Winter Luanze Oolong from Da Yu Ling (2400 m)'},\n {value: '2005 Bulang Moutain Iron Jar Ripe Pu-Erh',\n text: '2005 Bulang Moutain Iron Jar Ripe Pu-Erh'},\n {value: 'Emperors White Tea', text: 'Emperors White Tea'},\n {value: 'Keisarin Kruunu - Emperors Yellow Tea',\n text: 'Keisarin Kruunu - Emperors Yellow Tea'},\n {value: 'Taiwan Monkey Picked (Ma Liu Mie) Tie Guan Yin Oolong Tea',\n text: 'Taiwan Monkey Picked (Ma Liu Mie) Tie Guan Yin Oolong Tea'},\n {value: 'Spring 2013 Premium Grade Jin Jun Mei Fujian Black Tea of Wu Yi Shan',\n text: '2013 Jin Jun Mei Fujian Black Tea of Wu Yi Shan'},\n {value: 'Sonoma', text: 'Sonoma'},\n {value: 'Mr. Hes 1st Picking Laoshan Black',\n text: 'Mr. Hes 1st Picking Laoshan Black'},\n {value: 'Chocolate Chili Chai', text: 'Chocolate Chili Chai'},\n {value: 'First Pick Korean Wild Green',\n text: 'First Pick Korean Wild Green'},\n {value: 'Bourbon Street Vanilla Rooibos',\n text: 'Bourbon Street Vanilla Rooibos'},\n {value: 'Imperial White Peach White Tea',\n text: 'Imperial White Peach White Tea'},\n {value: 'Festin de Pêches', text: 'Festin de Pêches'},\n {value: 'Peach Iced Tea', text: 'Peach Iced Tea'},\n {value: '2012 Yunnan Sourcing Yi Wu Purple Tea Raw Pu-erh tea cake',\n text: '2012 Yunnan Sourcing Yi Wu Purple Tea Raw Pu-erh tea cake'},\n {value: 'Cream Earl Gray', text: 'Cream Earl Gray'},\n {value: 'Grand Marnier', text: 'Grand Marnier'},\n {value: 'Tropic of Strawberry', text: 'Tropic of Strawberry'},\n {value: 'Canadian Ice Wine', text: 'Canadian Ice Wine'},\n {value: 'Winter Breakfast Blend', text: 'Winter Breakfast Blend'},\n {value: 'Pure Empower Mint', text: 'Pure Empower Mint'},\n {value: 'Peppermint Spearmint &amp; Strawberry',\n text: 'Peppermint Spearmint &amp; Strawberry'},\n {value: 'Citrus Blend', text: 'Citrus Blend'},\n {value: 'Maple Syrup Matcha', text: 'Maple Syrup Matcha'},\n {value: 'Earliest Green Tea of the Year - Frosty Spring Yunnan Roast Green',\n text: 'Frosty Spring Yunnan Roast Green'},\n {value: 'Yellow Stick Orchid Phoenix Oolong',\n text: 'Yellow Stick Orchid Phoenix Oolong'},\n {value: 'Fairtrade', text: 'Fairtrade'},\n {value: 'AriZona Peach Diet Iced Tea Mix',\n text: 'AriZona Peach Diet Iced Tea Mix'},\n {value: 'Mandarin orange pu-erh', text: 'Mandarin orange pu-erh'},\n {value: 'Super Charge', text: 'Super Charge'},\n {value: 'China Oolong Ginseng Tie-Guan-Yun (ZM87)',\n text: 'China Oolong Ginseng Tie-Guan-Yun (ZM87)'},\n {value: 'Red Bush Chai', text: 'Red Bush Chai'},\n {value: 'Darjeeling Special Spring Flowery Black',\n text: 'Darjeeling Special Spring Flowery Black'},\n {value: 'Pink Earl Grey', text: 'Pink Earl Grey'},\n {value: 'Darjeeling Pure Origine', text: 'Darjeeling Pure Origine'},\n {value: 'Puttabong 1st Flush Darjeeling 2012 [Out of Stock]',\n text: 'Puttabong 1st Flush Darjeeling 2012 [Out of Stock]'},\n {value: 'Organic Pilochun Tea', text: 'Organic Pilochun Tea'},\n {value: 'Caribe', text: 'Caribe'},\n {value: 'Rooibos red tea', text: 'Rooibos red tea'},\n {value: 'Bees Creek Oolong', text: 'Bees Creek Oolong'},\n {value: 'Wuyi Yan Cha Rou Gui granny tea (huang pian)',\n text: 'Wuyi Yan Cha Rou Gui granny tea (huang pian)'},\n {value: 'Matcha Shugyoku 抹茶珠玉', text: 'Matcha Shugyoku 抹茶珠玉'},\n {value: 'Christmas Morning', text: 'Christmas Morning'},\n {value: 'Levs Kombucha', text: 'Levs Kombucha'},\n {value: 'Phoenix Honey Iris Oolong', text: 'Phoenix Honey Iris Oolong'},\n {value: 'Formosa Oolong Spring Dragon',\n text: 'Formosa Oolong Spring Dragon'},\n {value: 'Willow White', text: 'Willow White'},\n {value: 'Zhenyuan Dongsa 2015 Sheng Puer',\n text: 'Zhenyuan Dongsa 2015 Sheng Puer'},\n {value: 'Egyptian Licorice', text: 'Egyptian Licorice'},\n {value: 'Molasses Chocolate Crackle (Custom Blend)',\n text: 'Molasses Chocolate Crackle (Custom Blend)'},\n {value: 'Assam FOP (organic)', text: 'Assam FOP (organic)'},\n {value: 'English Rose Tea', text: 'English Rose Tea'},\n {value: 'Green Rooibos - Sweet African Red',\n text: 'Green Rooibos - Sweet African Red'},\n {value: 'Intense Premium Tea', text: 'Intense Premium Tea'},\n {value: 'Two Friends', text: 'Two Friends'},\n {value: 'Fujian Jasmine Pearls', text: 'Fujian Jasmine Pearls'},\n {value: 'Jingle Bells', text: 'Jingle Bells'},\n {value: 'Fire Light Chai', text: 'Fire Light Chai'},\n {value: 'Berry Green', text: 'Berry Green'},\n {value: 'Bearonicas Berry Tea', text: 'Bearonicas Berry Tea'},\n {value: 'Cardamon Black', text: 'Cardamon Black'},\n {value: 'Zhen Quo Super China Black', text: 'Zhen Quo Super China Black'},\n {value: 'Berry Berry - Herb &amp; Fruit',\n text: 'Berry Berry - Herb &amp; Fruit'},\n {value: 'Lapsang Souchong Superior', text: 'Lapsang Souchong Superior'},\n {value: 'Organic Christmas Tea', text: 'Organic Christmas Tea'},\n {value: 'Dong Luo', text: 'Dong Luo'},\n {value: 'Strawberry Honey Black Tea', text: 'Strawberry Honey Black Tea'},\n {value: 'Milk Oolong Tea', text: 'Milk Oolong Tea'},\n {value: 'Green Spiral', text: 'Green Spiral'},\n {value: 'Bloody Rock God', text: 'Bloody Rock God'},\n {value: 'Coconut Rough', text: 'Coconut Rough'},\n {value: 'Get Charged - No. 3 (Wellness Collection)',\n text: 'Get Charged - No. 3 (Wellness Collection)'},\n {value: 'Red Jade Black Tea Lot 152',\n text: 'Red Jade Black Tea Lot 152'},\n {value: 'Tan Yang Gongfu Golden Tips',\n text: 'Tan Yang Gongfu Golden Tips'},\n {value: 'Buckingham Palace Garden Tea Party',\n text: 'Buckingham Palace Garden Tea Party'},\n {value: 'Honey Peach Tea', text: 'Honey Peach Tea'},\n {value: 'Violets Spring', text: 'Violets Spring'},\n {value: 'Lemonade', text: 'Lemonade'},\n {value: 'Mint Chocolate Rooibos', text: 'Mint Chocolate Rooibos'},\n {value: 'Rhubarb Oolong', text: 'Rhubarb Oolong'},\n {value: 'Organic Pregnancy Tea', text: 'Organic Pregnancy Tea'},\n {value: 'Organic Olive Leaf Infusion',\n text: 'Organic Olive Leaf Infusion'},\n {value: 'White Jasmine Sparkling Tea',\n text: 'White Jasmine Sparkling Tea'},\n {value: 'Harmony', text: 'Harmony'},\n {value: 'Organic Honey Bush', text: 'Organic Honey Bush'},\n {value: 'Japanese Hojicha Roasted Green Tea',\n text: 'Japanese Hojicha Roasted Green Tea'},\n {value: 'Ripe For Romance', text: 'Ripe For Romance'},\n {value: 'Rooibos ~ Organic &amp; Fair Trade',\n text: 'Rooibos ~ Organic &amp; Fair Trade'},\n {value: 'Organic Aquanjel Mystery', text: 'Organic Aquanjel Mystery'},\n {value: 'Mt. Wu Dong Mi Lan (Honey Orchid) Dan Cong',\n text: 'Mt. Wu Dong Mi Lan (Honey Orchid) Dan Cong'},\n {value: 'Jasmine Peach Bai Mudan', text: 'Jasmine Peach Bai Mudan'},\n {value: 'Wild Cherry (992)', text: 'Wild Cherry (992)'},\n {value: 'Choco-Menthe', text: 'Choco-Menthe'},\n {value: 'Tonganagaon SFTGFOP1 2nd Flush',\n text: 'Tonganagaon SFTGFOP1 2nd Flush'},\n {value: 'Organic Golden Green', text: 'Organic Golden Green'},\n {value: 'Saigon Chai (organic)', text: 'Saigon Chai (organic)'},\n {value: 'Peanut Butter Cup', text: 'Peanut Butter Cup'},\n {value: 'China Congou Ning Hong Jing Hao (ZK94)',\n text: 'China Congou Ning Hong Jing Hao (ZK94)'},\n {value: 'Vanilla Bean Cheesecake Chai',\n text: 'Vanilla Bean Cheesecake Chai'},\n {value: 'Voyage: Brazilian Baia ', text: 'Voyage: Brazilian Baia '},\n {value: 'White Chocolate Mocha Black Tea',\n text: 'White Chocolate Mocha Black Tea'},\n {value: 'Dian Lu Eshan Mao Feng', text: 'Dian Lu Eshan Mao Feng'},\n {value: 'Floral Eclipse', text: 'Floral Eclipse'},\n {value: 'Green Rooibos Sunsplash', text: 'Green Rooibos Sunsplash'},\n {value: '2010 Menghai 7572 Ripe Puerh',\n text: '2010 Menghai 7572 Ripe Puerh'},\n {value: 'Seffarine (Verbena Mint)', text: 'Seffarine (Verbena Mint)'},\n {value: 'Pearl of Jackfruit', text: 'Pearl of Jackfruit'},\n {value: 'Panyang Bohea Supreme', text: 'Panyang Bohea Supreme'},\n {value: 'Strawberry Colada', text: 'Strawberry Colada'},\n {value: 'Blue Moon', text: 'Blue Moon'},\n {value: 'OLD VERSION (2011-2014) River Rain',\n text: 'OLD VERSION (2011-2014) River Rain'},\n {value: 'Wu Yi Ensemble', text: 'Wu Yi Ensemble'},\n {value: 'Mate rooibos torrado com chocolate',\n text: 'Mate rooibos torrado com chocolate'},\n {value: 'Royal Puerh', text: 'Royal Puerh'},\n {value: 'Mate Spicy Ginger', text: 'Mate Spicy Ginger'},\n {value: 'Pomegranete Herbal Tea', text: 'Pomegranete Herbal Tea'},\n {value: 'Unity', text: 'Unity'},\n {value: 'Voyage Russian Taïga', text: 'Voyage Russian Taïga'},\n {value: 'Kenya Oolong Kangaita', text: 'Kenya Oolong Kangaita'},\n {value: 'Pi Lo Chun 2009', text: 'Pi Lo Chun 2009'},\n {value: 'Pink Grapefruit', text: 'Pink Grapefruit'},\n {value: 'elderflower tea', text: 'elderflower tea'},\n {value: 'TE01: Seasons Pick Earl Grey Creme Vanilla',\n text: 'TE01: Seasons Pick Earl Grey Creme Vanilla'},\n {value: 'Bingo Bango Mango', text: 'Bingo Bango Mango'},\n {value: 'Zhen Qu Golden Buds 112', text: 'Zhen Qu Golden Buds 112'},\n {value: 'Natelas Gold Standard', text: 'Natelas Gold Standard'},\n {value: 'Tijm (Thyme)', text: 'Tijm (Thyme)'},\n {value: 'Canton Orange', text: 'Canton Orange'},\n {value: 'Darjeeling FTGFOP 1 Soom No. 230',\n text: 'Darjeeling FTGFOP 1 Soom No. 230'},\n {value: 'Pure Chinese White Silvertip',\n text: 'Pure Chinese White Silvertip'},\n {value: 'Love Child', text: 'Love Child'},\n {value: 'Nil Rouge', text: 'Nil Rouge'},\n {value: 'Silverpot Legendary Estates Darjeeling Second Flush',\n text: 'Silverpot Legendary Estates Darjeeling Second Flush'},\n {value: 'Wūlu (Jade Green) Organic Green Tea',\n text: 'Wūlu (Jade Green) Organic Green Tea'},\n {value: 'Blood Orange Black', text: 'Blood Orange Black'},\n {value: 'hu kwa', text: 'hu kwa'},\n {value: 'Formosa Jade Oolong', text: 'Formosa Jade Oolong'},\n {value: 'Fine Ti Kuan Yin Oolong Tea',\n text: 'Fine Ti Kuan Yin Oolong Tea'},\n {value: 'Panyang Congou', text: 'Panyang Congou'},\n {value: 'White Blueberry', text: 'White Blueberry'},\n {value: 'TA40: Tippy Orthodox GFOP Assam',\n text: 'TA40: Tippy Orthodox GFOP Assam'},\n {value: 'Bon Bon', text: 'Bon Bon'},\n {value: 'Sensual Relaxation Tea Bags',\n text: 'Sensual Relaxation Tea Bags'},\n {value: 'Bancha (TJ06)', text: 'Bancha (TJ06)'},\n {value: 'Green Tea Pomegranate', text: 'Green Tea Pomegranate'},\n {value: 'supreme pu-erh', text: 'supreme pu-erh'},\n {value: 'Organic smoked maple oolong',\n text: 'Organic smoked maple oolong'},\n {value: 'Passion Fruit &amp; Papaya black tea',\n text: 'Passion Fruit &amp; Papaya black tea'},\n {value: 'Jasmine 5', text: 'Jasmine 5'},\n {value: 'Tea of Inquiry', text: 'Tea of Inquiry'},\n {value: 'Boracay Breeze (Limited Edition)',\n text: 'Boracay Breeze (Limited Edition)'},\n {value: 'Route 66', text: 'Route 66'},\n {value: '4 SEASONS (Summer)', text: '4 SEASONS (Summer)'},\n {value: 'Mango Ceylon Decaf', text: 'Mango Ceylon Decaf'},\n {value: 'Golden Osmanthus', text: 'Golden Osmanthus'},\n {value: 'bi luo chun 碧螺春', text: 'bi luo chun 碧螺春'},\n {value: 'Honey Chamomile Green Tea (Decaf)',\n text: 'Honey Chamomile Green Tea (Decaf)'},\n {value: 'Just a Trio of Tulsi', text: 'Just a Trio of Tulsi'},\n {value: 'Pear Iced Green Tea Bags', text: 'Pear Iced Green Tea Bags'},\n {value: 'Ancient Pu-Erh', text: 'Ancient Pu-Erh'},\n {value: 'Nachtmusik', text: 'Nachtmusik'},\n {value: 'Tastes of Summer', text: 'Tastes of Summer'},\n {value: 'Shui Jin Gui (Golden Water Turtle) Rock Wulong 2011',\n text: 'Shui Jin Gui (Golden Water Turtle) Rock Wulong 2011'},\n {value: 'Nepal - Shangri-Lâ Temple', text: 'Nepal - Shangri-Lâ Temple'},\n {value: 'Scarlet', text: 'Scarlet'},\n {value: 'After Dinner Mint', text: 'After Dinner Mint'},\n {value: 'Mango Darjeeling Organic Tea',\n text: 'Mango Darjeeling Organic Tea'},\n {value: 'Adelaide Breakfast', text: 'Adelaide Breakfast'},\n {value: 'Milky Wu Long', text: 'Milky Wu Long'},\n {value: 'Top Chingwo Congou', text: 'Top Chingwo Congou'},\n {value: 'Wake Me Up Before You Go-Go',\n text: 'Wake Me Up Before You Go-Go'},\n {value: 'Gyokuro Pine Breeze', text: 'Gyokuro Pine Breeze'},\n {value: 'De-Luxe Extra Fresh', text: 'De-Luxe Extra Fresh'},\n {value: '2004 Menghai Superior Grade',\n text: '2004 Menghai Superior Grade'},\n {value: 'Blueberry Matcha', text: 'Blueberry Matcha'},\n {value: 'Jazz Cats Meow', text: 'Jazz Cats Meow'},\n {value: 'Matcha Matsu', text: 'Matcha Matsu'},\n {value: 'Full-Steam Black Tea [renamed 100 Year]',\n text: 'Full-Steam Black Tea [renamed 100 Year]'},\n {value: 'Rooibush Panna Cotta Rhubarb Cream',\n text: 'Rooibush Panna Cotta Rhubarb Cream'},\n {value: 'Citrus Earl Grey (824)', text: 'Citrus Earl Grey (824)'},\n {value: 'Vanilla Orchid Darjeeling Black Tea',\n text: 'Vanilla Orchid Darjeeling Black Tea'},\n {value: 'Premium Jasmine Dragon Pearls Green Tea',\n text: 'Premium Jasmine Dragon Pearls Green Tea'},\n {value: 'Jian Xuan (Milk Oolong)', text: 'Jian Xuan (Milk Oolong)'},\n {value: 'Brain Power', text: 'Brain Power'},\n {value: 'Darjeeling - Margarets Hope 1st Flush (2009)',\n text: 'Darjeeling - Margarets Hope 1st Flush (2009)'},\n {value: 'Simply The Zest (organic)', text: 'Simply The Zest (organic)'},\n {value: 'Vinegar Black', text: 'Vinegar Black'},\n {value: 'Slim Lotus Tea', text: 'Slim Lotus Tea'},\n {value: 'Golden Bi Lo', text: 'Golden Bi Lo'},\n {value: 'Premium Yame Sencha Takumi', text: 'Premium Yame Sencha Takumi'},\n {value: 'Dragon Well pre-Qing Ming First Grade',\n text: 'Dragon Well pre-Qing Ming First Grade'},\n {value: 'Flowering Osmanthus Tea', text: 'Flowering Osmanthus Tea'},\n {value: 'Lavender Earl Green', text: 'Lavender Earl Green'},\n {value: 'Estate Darjeeling', text: 'Estate Darjeeling'},\n {value: 'Nilgiri BOP', text: 'Nilgiri BOP'},\n {value: 'Trifle - Signature Tea', text: 'Trifle - Signature Tea'},\n {value: 'Lapsang Strong Smoke', text: 'Lapsang Strong Smoke'},\n {value: 'Caribbean Calypso Mate', text: 'Caribbean Calypso Mate'},\n {value: 'Cheesecake Matcha', text: 'Cheesecake Matcha'},\n {value: 'Plum Crazy', text: 'Plum Crazy'},\n {value: 'albert heijn kaneel thee', text: 'albert heijn kaneel thee'},\n {value: 'jasmine pearl organic', text: 'jasmine pearl organic'},\n {value: 'Popped Caramel Corn', text: 'Popped Caramel Corn'},\n {value: 'Amaretto', text: 'Amaretto'},\n {value: 'Black Orchid', text: 'Black Orchid'},\n {value: 'Earl Grey Excelsior', text: 'Earl Grey Excelsior'},\n {value: 'Kenyan Kericho Premium Tea', text: 'Kenyan Kericho Premium Tea'},\n {value: 'White Grape', text: 'White Grape'},\n {value: '2010 Lishan High Mountain Oolong',\n text: '2010 Lishan High Mountain Oolong'},\n {value: 'Makaibari FTGFOP 1 - 2nd Flush',\n text: 'Makaibari FTGFOP 1 - 2nd Flush'},\n {value: 'Evening Escape', text: 'Evening Escape'},\n {value: 'China Black with Tropical Peach',\n text: 'China Black with Tropical Peach'},\n {value: 'Royal Blend', text: 'Royal Blend'},\n {value: 'Green Zoubrovka', text: 'Green Zoubrovka'},\n {value: 'Darjeeling Makaibari Organic Second Flush',\n text: 'Darjeeling Makaibari Organic Second Flush'},\n {value: 'Mixed Berry Red Rooibos', text: 'Mixed Berry Red Rooibos'},\n {value: 'Sen-Cha (Premium Tea Bag)', text: 'Sen-Cha (Premium Tea Bag)'},\n {value: 'Formosa Super Fancy Champagne Oolong',\n text: 'Formosa Super Fancy Champagne Oolong'},\n {value: 'Jin Xuan Green Tea - 2011 Spring Taiwan Green Tea',\n text: 'Jin Xuan Green Tea - 2011 Spring Taiwan Green Tea'},\n {value: 'Maui Mango Tropical Black Tea',\n text: 'Maui Mango Tropical Black Tea'},\n {value: 'Bold Leaf Lapacho (Pao Darcho)',\n text: 'Bold Leaf Lapacho (Pao Darcho)'},\n {value: 'Lime Mint', text: 'Lime Mint'},\n {value: 'Detox Tea', text: 'Detox Tea'},\n {value: 'French Vanilla Assam', text: 'French Vanilla Assam'},\n {value: 'Blueberry Amore', text: 'Blueberry Amore'},\n {value: 'Midnight in Paris', text: 'Midnight in Paris'},\n {value: 'Pom and Petals', text: 'Pom and Petals'},\n {value: 'Mango Passionfruit', text: 'Mango Passionfruit'},\n {value: 'Chloe', text: 'Chloe'},\n {value: 'White Malibu (organic)', text: 'White Malibu (organic)'},\n {value: '1001 Notte - 1001 Nights', text: '1001 Notte - 1001 Nights'},\n {value: 'Fujian Oolong Ti Kuwan Yin', text: 'Fujian Oolong Ti Kuwan Yin'},\n {value: 'Erva Cidreira / Lemon Balm', text: 'Erva Cidreira / Lemon Balm'},\n {value: 'Wuyi', text: 'Wuyi'},\n {value: 'China Keemun (TP12)', text: 'China Keemun (TP12)'},\n {value: 'Guangdong Province Jasmine Dragon Phoenix Pearl (ZJ91)',\n text: 'Guangdong Province Jasmine Dragon Phoenix Pearl (ZJ91)'},\n {value: 'Organic African Nectar', text: 'Organic African Nectar'},\n {value: 'Black Night', text: 'Black Night'},\n {value: 'Nutmeg Cream', text: 'Nutmeg Cream'},\n {value: 'Tangerine Dream', text: 'Tangerine Dream'},\n {value: 'Darjeeling Steinthal', text: 'Darjeeling Steinthal'},\n {value: 'The Labyrinth', text: 'The Labyrinth'},\n {value: 'Harmony Tulsi', text: 'Harmony Tulsi'},\n {value: 'Jasmine Pearl Tea', text: 'Jasmine Pearl Tea'},\n {value: 'Green Pu-Erh: Mandarin Orange',\n text: 'Green Pu-Erh: Mandarin Orange'},\n {value: 'Taiwan Dongding Oolong (Dark)',\n text: 'Taiwan Dongding Oolong (Dark)'},\n {value: 'Rendezvous', text: 'Rendezvous'},\n {value: 'Darjeeling Gopaldhara Wonder FTGFOP1 F.F. CL',\n text: 'Darjeeling Gopaldhara Wonder FTGFOP1 F.F. CL'},\n {value: 'Green Tea with Peppermint', text: 'Green Tea with Peppermint'},\n {value: 'Alwazah Green Tea', text: 'Alwazah Green Tea'},\n {value: 'Pure Chamomile', text: 'Pure Chamomile'},\n {value: 'Pink Christmas Organic', text: 'Pink Christmas Organic'},\n {value: 'Keemun Yi Ji', text: 'Keemun Yi Ji'},\n {value: 'Pistachio Ice Cream', text: 'Pistachio Ice Cream'},\n {value: 'Sweetened Iced Black Tea', text: 'Sweetened Iced Black Tea'},\n {value: 'La Vie En Rose Blanc Organic',\n text: 'La Vie En Rose Blanc Organic'},\n {value: 'Love', text: 'Love'},\n {value: 'Earl Grey Blue Lady', text: 'Earl Grey Blue Lady'},\n {value: 'Vanilla Cinnamon Ceylon Orange Pekoe',\n text: 'Vanilla Cinnamon Ceylon Orange Pekoe'},\n {value: 'Thé sur le Nil', text: 'Thé sur le Nil'},\n {value: 'Zheijiang Bi Luo Chun', text: 'Zheijiang Bi Luo Chun'},\n {value: 'Mate geröstet Biologischer Anbau (DE-013)',\n text: 'Mate geröstet Biologischer Anbau (DE-013)'},\n {value: 'Honey Fragrance Phoenix Mountain Oolong',\n text: 'Honey Fragrance Phoenix Mountain Oolong'},\n {value: 'Soursap', text: 'Soursap'},\n {value: 'Organic Cloud &amp; Mist', text: 'Organic Cloud &amp; Mist'},\n {value: 'Vanilla Caramel', text: 'Vanilla Caramel'},\n {value: 'Wild White Tea', text: 'Wild White Tea'},\n {value: 'Maroc', text: 'Maroc'},\n {value: 'Sailors Delight', text: 'Sailors Delight'},\n {value: 'Moonlight Lavender', text: 'Moonlight Lavender'},\n {value: 'Anji Bai Cha Green Tea', text: 'Anji Bai Cha Green Tea'},\n {value: 'Cranberry Rose', text: 'Cranberry Rose'},\n {value: 'Kenya Marinyn GFOP1', text: 'Kenya Marinyn GFOP1'},\n {value: 'Lotus Heart (Lian Xin Cha)', text: 'Lotus Heart (Lian Xin Cha)'},\n {value: 'Organic Houjicha Gold', text: 'Organic Houjicha Gold'},\n {value: 'Dragon Well (Long Jing)', text: 'Dragon Well (Long Jing)'},\n {value: 'Organic White Delight', text: 'Organic White Delight'},\n {value: 'Caramel Cocoa Loco', text: 'Caramel Cocoa Loco'},\n {value: 'Cranberry Orange', text: 'Cranberry Orange'},\n {value: 'China Yunnan Golden Downy Pekoe (571)',\n text: 'China Yunnan Golden Downy Pekoe (571)'},\n {value: 'Darjeeling 2nd Flush Margarets Hope Tea',\n text: 'Darjeeling 2nd Flush Margarets Hope Tea'},\n {value: 'The Skinny (organic)', text: 'The Skinny (organic)'},\n {value: 'Gail’s Cold Remedy (organic)',\n text: 'Gail’s Cold Remedy (organic)'},\n {value: 'DISCONTINUED (2012-2013) - Da Hong Pao Big Red Robe Oolong',\n text: 'DISCONTINUED (2012-2013) - Da Hong Pao Big Red Robe Oolong'},\n {value: 'Lobocha', text: 'Lobocha'},\n {value: 'Whispering Woods', text: 'Whispering Woods'},\n {value: 'Formosa Oolong (Green Jade)',\n text: 'Formosa Oolong (Green Jade)'},\n {value: 'Masala Chocolate Truffle', text: 'Masala Chocolate Truffle'},\n {value: 'Mountain Malt', text: 'Mountain Malt'},\n {value: 'Zheng Shan Xiao Zhong of Wu Yi Fujian Black tea * Spring 2014',\n text: 'Zheng Shan Xiao Zhong of Wu Yi Fujian Black tea * Spring 2014'},\n {value: 'Blackcurrant Ginseng and Vanilla',\n text: 'Blackcurrant Ginseng and Vanilla'},\n {value: 'Loris Lemon Tea', text: 'Loris Lemon Tea'},\n {value: 'Lychee (ライチ紅茶)', text: 'Lychee (ライチ紅茶)'},\n {value: 'Bettys tea room blend (tea bag version)',\n text: 'Bettys tea room blend (tea bag version)'},\n {value: 'Market Spice Tea', text: 'Market Spice Tea'},\n {value: 'Kaga Bocha', text: 'Kaga Bocha'},\n {value: 'Wild Monkey Marsala', text: 'Wild Monkey Marsala'},\n {value: 'Taiwan Gao Shan Yin Xuan', text: 'Taiwan Gao Shan Yin Xuan'},\n {value: 'Peppermint (Organic)', text: 'Peppermint (Organic)'},\n {value: 'Cranberry Apple Tart', text: 'Cranberry Apple Tart'},\n {value: 'Long Island Strawberry', text: 'Long Island Strawberry'},\n {value: 'Cream of Assam Full Leaf Tippy Satrupa',\n text: 'Cream of Assam Full Leaf Tippy Satrupa'},\n {value: 'Vert a la Menthe', text: 'Vert a la Menthe'},\n {value: 'Gold Bud Beencha', text: 'Gold Bud Beencha'},\n {value: 'TB75: Baker Street Blend', text: 'TB75: Baker Street Blend'},\n {value: 'Herbal Revive Tea', text: 'Herbal Revive Tea'},\n {value: 'Organic Makurazaki Black Tea Hime Fuki',\n text: 'Organic Makurazaki Black Tea Hime Fuki'},\n {value: 'Organic Emerald Cloud', text: 'Organic Emerald Cloud'},\n {value: 'China Fine Ti Kuan Yin Oolong',\n text: 'China Fine Ti Kuan Yin Oolong'},\n {value: 'Setouchi Limone', text: 'Setouchi Limone'},\n {value: 'Phoenix Sung Special', text: 'Phoenix Sung Special'},\n {value: 'White Chocolate Peppermint', text: 'White Chocolate Peppermint'},\n {value: 'Premium White', text: 'Premium White'},\n {value: 'Temple of Heaven', text: 'Temple of Heaven'},\n {value: 'Peppermint Dreams', text: 'Peppermint Dreams'},\n {value: 'Royal Star', text: 'Royal Star'},\n {value: 'Assam Mangalam SFTGFOP1', text: 'Assam Mangalam SFTGFOP1'},\n {value: '2009 Norbu Lao Cha Tou - 250g Shu Pu-Erh Tea Brick',\n text: '2009 Norbu Lao Cha Tou - 250g Shu Pu-Erh Tea Brick'},\n {value: 'Choco Cinnamon', text: 'Choco Cinnamon'},\n {value: 'Pisces (The Zodiac Series)', text: 'Pisces (The Zodiac Series)'},\n {value: 'Bombay Market', text: 'Bombay Market'},\n {value: 'Cream Caramel', text: 'Cream Caramel'},\n {value: 'PerfecTemp Cordless Electric Kettle',\n text: 'PerfecTemp Cordless Electric Kettle'},\n {value: 'Caribbean Breeze', text: 'Caribbean Breeze'},\n {value: 'Vanilla Black Tea &amp; Peppermint Leaves',\n text: 'Vanilla Black Tea Peppermint Leaves'},\n {value: 'Ashanti Gold Black Tea', text: 'Ashanti Gold Black Tea'},\n {value: 'China Emperors Red (Fujian)',\n text: 'China Emperors Red (Fujian)'},\n {value: '2013 Longjing Shi Feng Dragonwell',\n text: '2013 Longjing Shi Feng Dragonwell'},\n {value: 'Premium Tieguanyin', text: 'Premium Tieguanyin'},\n {value: 'Qing Tian Xiang Green Style Dong Ding Oolong Tea',\n text: 'Qing Tian Xiang Green Style Dong Ding Oolong Tea'},\n {value: 'Golden Dragon Special Grade',\n text: 'Golden Dragon Special Grade'},\n {value: 'Red Hunan Oolong', text: 'Red Hunan Oolong'},\n {value: 'Extra Bergamot English Earl Grey (TE11S)',\n text: 'Extra Bergamot English Earl Grey (TE11S)'},\n {value: 'golden pu-erh', text: 'golden pu-erh'},\n {value: 'Pure Assam Leaf Tea', text: 'Pure Assam Leaf Tea'},\n {value: 'Obukucha', text: 'Obukucha'},\n {value: 'Darjeeling Jungpana Muscatel SP',\n text: 'Darjeeling Jungpana Muscatel SP'},\n {value: 'Menghai 8892', text: 'Menghai 8892'},\n {value: 'Shan Tee', text: 'Shan Tee'},\n {value: 'Tindharia FF TGFOP', text: 'Tindharia FF TGFOP'},\n {value: 'Assam FTGFOP1 Mokalbari', text: 'Assam FTGFOP1 Mokalbari'},\n {value: 'Organic Wu Yi Rou Gui', text: 'Organic Wu Yi Rou Gui'},\n {value: 'Honeybush Vanilla (BA26)', text: 'Honeybush Vanilla (BA26)'},\n {value: 'Mt. Ali Milky Gold', text: 'Mt. Ali Milky Gold'},\n {value: 'Tibetan Organic Green Mao Feng Leaf Scented with Jasmine',\n text: 'Tibetan Organic Green Mao Feng Leaf Scented with Jasmine'},\n {value: 'Red Velvet', text: 'Red Velvet'},\n {value: 'Needle Ku Ding Tea', text: 'Needle Ku Ding Tea'},\n {value: 'Aged green pu-erh cake', text: 'Aged green pu-erh cake'},\n {value: 'Luigi Amaretto', text: 'Luigi Amaretto'},\n {value: 'Tai Ping', text: 'Tai Ping'},\n {value: 'Apples and Snowflakes', text: 'Apples and Snowflakes'},\n {value: 'Ton Tin (2008 Winter)', text: 'Ton Tin (2008 Winter)'},\n {value: 'Spice of Life', text: 'Spice of Life'},\n {value: 'Rainbow Sherbet', text: 'Rainbow Sherbet'},\n {value: 'Mao Feng Tranquility Green', text: 'Mao Feng Tranquility Green'},\n {value: 'Lion Xi Hu Long Jing', text: 'Lion Xi Hu Long Jing'},\n {value: 'Decaffeinated Spiced Apricot',\n text: 'Decaffeinated Spiced Apricot'},\n {value: 'Morningtime Tea', text: 'Morningtime Tea'},\n {value: 'American Classic Tea', text: 'American Classic Tea'},\n {value: 'Shin-cha 88th Night - 2009 edition',\n text: 'Shin-cha 88th Night - 2009 edition'},\n {value: 'Assam Banaspathy FOP', text: 'Assam Banaspathy FOP'},\n {value: 'Blueberry Blush', text: 'Blueberry Blush'},\n {value: 'Christmas Mystery', text: 'Christmas Mystery'},\n {value: 'Ginger - Rooibos', text: 'Ginger - Rooibos'},\n {value: 'Apricot Chai', text: 'Apricot Chai'},\n {value: 'Peaches &amp; Ginger', text: 'Peaches &amp; Ginger'},\n {value: '2007 Xiaguan Gold Ribbon Tuocha',\n text: '2007 Xiaguan Gold Ribbon Tuocha'},\n {value: 'Currant Black Tea', text: 'Currant Black Tea'},\n {value: 'Ti Kwan Yin Oolong', text: 'Ti Kwan Yin Oolong'},\n {value: 'Crannyberry', text: 'Crannyberry'},\n {value: 'Blue of London', text: 'Blue of London'},\n {value: 'Guayusa Tea with Chai', text: 'Guayusa Tea with Chai'},\n {value: 'Pu-Erh Organic', text: 'Pu-Erh Organic'},\n {value: 'Ryokucha Genmaicha', text: 'Ryokucha Genmaicha'},\n {value: 'White Licorice', text: 'White Licorice'},\n {value: 'Maojian Green Tea', text: 'Maojian Green Tea'},\n {value: 'Thin Mint Green', text: 'Thin Mint Green'},\n {value: 'Casablanca Chamomile', text: 'Casablanca Chamomile'},\n {value: 'Naturally Flavored Cinnamon Chai Tea - TE36',\n text: 'Naturally Flavored Cinnamon Chai Tea - TE36'},\n {value: 'Czar Nikolas II Premium Russian Tea',\n text: 'Czar Nikolas II Premium Russian Tea'},\n {value: 'Ginsing Oolong', text: 'Ginsing Oolong'},\n {value: 'Dong Ding Oolong traditional medium roast',\n text: 'Dong Ding Oolong traditional medium roast'},\n {value: 'Toasted Rice', text: 'Toasted Rice'},\n {value: 'White Grapefruit', text: 'White Grapefruit'},\n {value: 'Organic Red Delicious', text: 'Organic Red Delicious'},\n {value: 'No. 22 National Parks Dept.',\n text: 'No. 22 National Parks Dept.'},\n {value: 'Satemwa Black Tea', text: 'Satemwa Black Tea'},\n {value: 'TD31: Tindharia Est. FTGFOP1 Ch. 2nd Flush (DJ-97) Organic',\n text: 'TD31: Tindharia Est. FTGFOP1 Ch. 2nd Flush (DJ-97) Organic'},\n {value: 'Cherry Pineapple Green', text: 'Cherry Pineapple Green'},\n {value: 'Japanese Evening Mist', text: 'Japanese Evening Mist'},\n {value: '2010 Douji Pure Series Nan Nuo Raw Puerh Cake',\n text: '2010 Douji Pure Series Nan Nuo Raw Puerh Cake'},\n {value: 'Get Clean - No. 7 (Wellness Collection)',\n text: 'Get Clean - No. 7 (Wellness Collection)'},\n {value: 'Sweet Cinnamon Spice Herbal Tea',\n text: 'Sweet Cinnamon Spice Herbal Tea'},\n {value: '2010 Yunnan Camphor Tree Flavor Ripe Pu’er',\n text: '2010 Yunnan Camphor Tree Flavor Ripe Pu’er'},\n {value: 'Hot Cinnamon Herbal', text: 'Hot Cinnamon Herbal'},\n {value: 'Circulation - Vigne Rouge', text: 'Circulation - Vigne Rouge'},\n {value: 'BA15: South African Rooibos (Red Bush) Super Grade',\n text: 'BA15: South African Rooibos (Red Bush) Super Grade'},\n {value: 'Yu Lu Yan Chai', text: 'Yu Lu Yan Chai'},\n {value: 'Mangalam FTGFOP 1', text: 'Mangalam FTGFOP 1'},\n {value: 'Respiratory Rescue', text: 'Respiratory Rescue'},\n {value: 'Formosa Fancy Oolong', text: 'Formosa Fancy Oolong'},\n {value: 'Golden Osmanthus Summer 2011',\n text: 'Golden Osmanthus Summer 2011'},\n {value: 'Organic Hawaii Premium Green Tea',\n text: 'Organic Hawaii Premium Green Tea'},\n {value: 'Apple Caramel Green', text: 'Apple Caramel Green'},\n {value: 'An Xi Tie Guan Yin traditional charcoal roast',\n text: 'An Xi Tie Guan Yin traditional charcoal roast'},\n {value: 'Memories of South Africa Rooibos Citrus Spice',\n text: 'Memories of South Africa Rooibos Citrus Spice'},\n {value: 'After 5', text: 'After 5'},\n {value: 'Paï Mu Tan', text: 'Paï Mu Tan'},\n {value: 'Yemeni Tea', text: 'Yemeni Tea'},\n {value: 'Sichuan Gongfu', text: 'Sichuan Gongfu'},\n {value: 'Organic Matcha Infused Genmaicha',\n text: 'Organic Matcha Infused Genmaicha'},\n {value: 'Pure Ceylon Tea', text: 'Pure Ceylon Tea'},\n {value: 'Sultane', text: 'Sultane'},\n {value: 'China Jasmine Tea Dazhang Shan',\n text: 'China Jasmine Tea Dazhang Shan'},\n {value: 'White Tea Berry with Pomegranate',\n text: 'White Tea Berry with Pomegranate'},\n {value: 'Assam Dejoo STGFOP1', text: 'Assam Dejoo STGFOP1'},\n {value: 'World Peace', text: 'World Peace'},\n {value: 'Organic Sheng Pu-Er Tuo Cha',\n text: 'Organic Sheng Pu-Er Tuo Cha'},\n {value: 'Thiashola Carrington S.F.T.G.F.O.P.1',\n text: 'Thiashola Carrington S.F.T.G.F.O.P.1'},\n {value: 'Thé Yunnan Vert (yunnan green tea)',\n text: 'Thé Yunnan Vert (yunnan green tea)'},\n {value: 'Black Forest Bliss', text: 'Black Forest Bliss'},\n {value: 'Formosa Oolong (Champagne Oolong)',\n text: 'Formosa Oolong (Champagne Oolong)'},\n {value: 'Formosa Muzha Tie Guan Yin', text: 'Formosa Muzha Tie Guan Yin'},\n {value: '2006 Boyou Chinese New Year',\n text: '2006 Boyou Chinese New Year'},\n {value: '2006 Artisan Revival Stone-Pressed Sheng',\n text: '2006 Artisan Revival Stone-Pressed Sheng'},\n {value: 'Hong Xiang Luo Keemun', text: 'Hong Xiang Luo Keemun'},\n {value: 'Buckingham Palace Garden Party Tea',\n text: 'Buckingham Palace Garden Party Tea'},\n {value: 'China Oolong Kwai Flower', text: 'China Oolong Kwai Flower'},\n {value: 'Pu-Erh Ginger', text: 'Pu-Erh Ginger'},\n {value: 'Organic Blue Nettle', text: 'Organic Blue Nettle'},\n {value: 'Pomegranate Oolong', text: 'Pomegranate Oolong'},\n {value: 'Caramel Cheesecake Black Tea',\n text: 'Caramel Cheesecake Black Tea'},\n {value: 'Alishan Shi Zhao', text: 'Alishan Shi Zhao'},\n {value: 'Kehelwela Broken Orange Pekoe Special',\n text: 'Kehelwela Broken Orange Pekoe Special'},\n {value: 'Lemon Herbal Infusion', text: 'Lemon Herbal Infusion'},\n {value: 'Yunnan Gold - First Grade', text: 'Yunnan Gold - First Grade'},\n {value: 'Darjeeling Vidyaranya', text: 'Darjeeling Vidyaranya'},\n {value: 'Organic Mandarin Citrus White Tea',\n text: 'Organic Mandarin Citrus White Tea'},\n {value: 'shui jin gui 2012', text: 'shui jin gui 2012'},\n {value: 'Scarletts Romantic Tea', text: 'Scarletts Romantic Tea'},\n {value: 'Rooibos &amp; Honeybush Bushbabies',\n text: 'Rooibos &amp; Honeybush Bushbabies'},\n {value: 'Earl Grey Darjeeling', text: 'Earl Grey Darjeeling'},\n {value: 'Chamomile Dream', text: 'Chamomile Dream'},\n {value: 'Yunnan Gold Tips', text: 'Yunnan Gold Tips'},\n {value: 'Dragon Pearls (Long Zhu)', text: 'Dragon Pearls (Long Zhu)'},\n {value: 'Chamomile Tisane', text: 'Chamomile Tisane'},\n {value: 'Jasmine Coconut Green Tea', text: 'Jasmine Coconut Green Tea'},\n {value: 'Goji Green', text: 'Goji Green'},\n {value: 'Bai Mu Dan First Grade Superior',\n text: 'Bai Mu Dan First Grade Superior'},\n {value: 'Tiramisu Matcha', text: 'Tiramisu Matcha'},\n {value: 'Caffeine Free Herbal Tea', text: 'Caffeine Free Herbal Tea'},\n {value: 'organic jasmine 3rd grade', text: 'organic jasmine 3rd grade'},\n {value: 'Jasmine Dream', text: 'Jasmine Dream'},\n {value: 'Princess Blend', text: 'Princess Blend'},\n {value: 'Gyokuro Premium', text: 'Gyokuro Premium'},\n {value: 'lenier russian georgian', text: 'lenier russian georgian'},\n {value: 'Bloemfontein', text: 'Bloemfontein'},\n {value: 'Raspberry Sangria', text: 'Raspberry Sangria'},\n {value: 'Mango N Friends', text: 'Mango N Friends'},\n {value: 'Rohini Autumnal', text: 'Rohini Autumnal'},\n {value: 'Dubbele Chocolade', text: 'Dubbele Chocolade'},\n {value: 'Darjeeling Avongrove FTGFOP1 F.F.',\n text: 'Darjeeling Avongrove FTGFOP1 F.F.'},\n {value: 'Black Currant Bai Mu Dan', text: 'Black Currant Bai Mu Dan'},\n {value: 'Earl Grey Spoon Tea', text: 'Earl Grey Spoon Tea'},\n {value: 'Sweet Matcha Ginger', text: 'Sweet Matcha Ginger'},\n {value: 'Guangdong Black', text: 'Guangdong Black'},\n {value: 'SLIM: SlenderTea – Chai Garcinia Cambogia Gymnema',\n text: 'SLIM: SlenderTea – Chai Garcinia Cambogia Gymnema'},\n {value: 'Yorkshire Gold (Tea Bags)', text: 'Yorkshire Gold (Tea Bags)'},\n {value: 'Vietnam Pekoe', text: 'Vietnam Pekoe'},\n {value: 'Green Tea with Mint', text: 'Green Tea with Mint'},\n {value: 'Glass Test Tube Steeper', text: 'Glass Test Tube Steeper'},\n {value: 'Mango Black', text: 'Mango Black'},\n {value: 'TG House Blend', text: 'TG House Blend'},\n {value: 'Perfect World', text: 'Perfect World'},\n {value: 'Organic Simply Mango', text: 'Organic Simply Mango'},\n {value: 'Sun Dried Jingshan Green', text: 'Sun Dried Jingshan Green'},\n {value: 'Tea For One', text: 'Tea For One'},\n {value: '2010 Dayi Gongtuo Pu-erh', text: '2010 Dayi Gongtuo Pu-erh'},\n {value: 'White Peony White Tea (Fuding Bai Mu Dan)',\n text: 'White Peony White Tea (Fuding Bai Mu Dan)'},\n {value: 'Organic Bangkok Iced', text: 'Organic Bangkok Iced'},\n {value: '(Blue) Yerba Mate', text: '(Blue) Yerba Mate'},\n {value: 'Matcha-iri-Sencha', text: 'Matcha-iri-Sencha'},\n {value: 'Dragonwell Style Laoshan Green',\n text: 'Dragonwell Style Laoshan Green'},\n {value: 'Lapsang Souchong Extra Strong',\n text: 'Lapsang Souchong Extra Strong'},\n {value: 'Ancient Tree Mini Brick', text: 'Ancient Tree Mini Brick'},\n {value: 'Mmm... Caramel', text: 'Mmm... Caramel'},\n {value: 'Organic Peach', text: 'Organic Peach'},\n {value: 'Nepal Himalaya View', text: 'Nepal Himalaya View'},\n {value: 'Bombay Breakfast', text: 'Bombay Breakfast'},\n {value: 'Superior Four Season Spring Green Oolong',\n text: 'Superior Four Season Spring Green Oolong'},\n {value: 'Green Tea with Ginseng &amp; Honey',\n text: 'Green Tea with Ginseng &amp; Honey'},\n {value: 'Six Summits', text: 'Six Summits'},\n {value: 'Breakfast Smoothie Honeybush',\n text: 'Breakfast Smoothie Honeybush'},\n {value: 'Puerh Leaf', text: 'Puerh Leaf'},\n {value: '2001 White Dragon of Jinggu Ripe Pu-erh tea',\n text: '2001 White Dragon of Jinggu Ripe Pu-erh tea'},\n {value: 'Napa Blanc', text: 'Napa Blanc'},\n {value: 'Histoire Tibetaine', text: 'Histoire Tibetaine'},\n {value: 'Mengku Arbor Tree Ripened Puerh Cake Tea ZhenMu LingYa 2007',\n text: 'Mengku Arbor Tree Ripened Puerh Cake Tea ZhenMu LingYa 2007'},\n {value: 'Sunset Red', text: 'Sunset Red'},\n {value: 'earl grey tea', text: 'earl grey tea'},\n {value: 'Wuyi Shan Red Cape', text: 'Wuyi Shan Red Cape'},\n {value: 'My Boss Sucks', text: 'My Boss Sucks'},\n {value: 'Turkish Apple', text: 'Turkish Apple'},\n {value: 'Moroccan Orange Spice', text: 'Moroccan Orange Spice'},\n {value: 'Tippy Golden Darjeeling Earl Grey',\n text: 'Tippy Golden Darjeeling Earl Grey'},\n {value: 'Lemon Strawberry Tisane', text: 'Lemon Strawberry Tisane'},\n {value: 'Black Raven', text: 'Black Raven'},\n {value: 'Lemon Myrtle Green', text: 'Lemon Myrtle Green'},\n {value: '1996 Shou Pu-erh Loose-leaf',\n text: '1996 Shou Pu-erh Loose-leaf'},\n {value: 'Dancing Lemons', text: 'Dancing Lemons'},\n {value: 'Halo', text: 'Halo'},\n {value: 'Peach Cardamom', text: 'Peach Cardamom'},\n {value: '501 Week-end Á Paris', text: '501 Week-end Á Paris'},\n {value: 'Bravissimo', text: 'Bravissimo'},\n {value: 'Emerald Sun', text: 'Emerald Sun'},\n {value: 'Jasmine Harmony Lavender Green',\n text: 'Jasmine Harmony Lavender Green'},\n {value: 'Master Lins Heaven Scent 2010',\n text: 'Master Lins Heaven Scent 2010'},\n {value: 'Nathaniels Southern Sweet Tea',\n text: 'Nathaniels Southern Sweet Tea'},\n {value: 'Keemun Black Tea', text: 'Keemun Black Tea'},\n {value: 'Tropical Mist Sencha', text: 'Tropical Mist Sencha'},\n {value: 'Sencha Extra Green (with Matcha)',\n text: 'Sencha Extra Green (with Matcha)'},\n {value: 'Grilled Spiced Banana', text: 'Grilled Spiced Banana'},\n {value: '3-in-1 Instant Milk Tea', text: '3-in-1 Instant Milk Tea'},\n {value: 'High Mountain Oolong', text: 'High Mountain Oolong'},\n {value: 'Red Ginseng Powder', text: 'Red Ginseng Powder'},\n {value: 'Lemon Blossom Oolong', text: 'Lemon Blossom Oolong'},\n {value: 'Spring Wonder Green Tea', text: 'Spring Wonder Green Tea'},\n {value: 'White Peach Oolong Tea', text: 'White Peach Oolong Tea'},\n {value: 'Violet Rose Black Tea', text: 'Violet Rose Black Tea'},\n {value: 'Nantou Dawn - Jin Xuan', text: 'Nantou Dawn - Jin Xuan'},\n {value: 'Monkey Picked Ti Kuan Yin', text: 'Monkey Picked Ti Kuan Yin'},\n {value: 'Qi Lan - 2011 Spring Wu Yi Oolong Tea',\n text: 'Qi Lan - 2011 Spring Wu Yi Oolong Tea'},\n {value: 'Decaf Apricot Green', text: 'Decaf Apricot Green'},\n {value: 'Matcha Super Green', text: 'Matcha Super Green'},\n {value: 'Black &amp; Blue', text: 'Black &amp; Blue'},\n {value: '2009 Wuyi Da Hong Pao Rock Tea-Zheng Yan Spring Tea',\n text: '2009 Wuyi Da Hong Pao Rock Tea-Zheng Yan Spring Tea'},\n {value: '2012 First Flush Jungpana SFTGFOP1',\n text: '2012 First Flush Jungpana SFTGFOP1'},\n {value: 'Night Out', text: 'Night Out'},\n {value: 'Evening In Missoula', text: 'Evening In Missoula'},\n {value: 'Lemon Spice', text: 'Lemon Spice'},\n {value: 'Spring Harvest Laoshan Green',\n text: 'Spring Harvest Laoshan Green'},\n {value: '100% Natural Green', text: '100% Natural Green'},\n {value: 'Milk oolong', text: 'Milk oolong'},\n {value: 'Pumpkin Rooibos', text: 'Pumpkin Rooibos'},\n {value: 'Organic White Tea with Ginger',\n text: 'Organic White Tea with Ginger'},\n {value: 'Keemun Gongfu', text: 'Keemun Gongfu'},\n {value: 'Spiced Darjeeling', text: 'Spiced Darjeeling'},\n {value: 'Smores Oolong Tea', text: 'Smores Oolong Tea'},\n {value: 'Rainforest Maté', text: 'Rainforest Maté'},\n {value: 'Berry Sensation', text: 'Berry Sensation'},\n {value: 'Ancient Sheng Pu-erh Saiqing Ya Tuo Cha Vintage 2005 Organic &amp; Fair Trade Pu-erh Tea',\n text: 'Ancient Sheng Pu-erh Saiqing Ya Tuo Cha Vintage 2005'},\n {value: 'Wuyi Dark Rock', text: 'Wuyi Dark Rock'},\n {value: 'China Rose Congou (569)', text: 'China Rose Congou (569)'},\n {value: 'October Revelation', text: 'October Revelation'},\n {value: 'Ginger Lemon Grass (Fair Trade Certified)',\n text: 'Ginger Lemon Grass (Fair Trade Certified)'},\n {value: 'Oolong lemon nori', text: 'Oolong lemon nori'},\n {value: 'Red Velvet Chocolate', text: 'Red Velvet Chocolate'},\n {value: 'Bao Zhong Pouchong', text: 'Bao Zhong Pouchong'},\n {value: 'Baozhong (Light Roast)', text: 'Baozhong (Light Roast)'},\n {value: '2012 MGH 1203 Imperial Ripe Pu-erh Tea Brick',\n text: '2012 MGH 1203 Imperial Ripe Pu-erh Tea Brick'},\n {value: 'Premium Da Hong Pao', text: 'Premium Da Hong Pao'},\n {value: 'Turkish Tea', text: 'Turkish Tea'},\n {value: 'Jade Pouchong', text: 'Jade Pouchong'},\n {value: '2017 EoT Jingdong Ancient Wild',\n text: '2017 EoT Jingdong Ancient Wild'},\n {value: 'Peach Blend Organic White Tea',\n text: 'Peach Blend Organic White Tea'},\n {value: 'Yumberry Wulong Oolong', text: 'Yumberry Wulong Oolong'},\n {value: 'Honeysuckle Puerh', text: 'Honeysuckle Puerh'},\n {value: 'Ceylon Apple Tea', text: 'Ceylon Apple Tea'},\n {value: 'Vihreä Keisarin Malja - Emperors Choice Green Tea',\n text: 'Vihreä Keisarin Malja - Emperors Choice Green Tea'},\n {value: 'White Monkey (Bai Hou)', text: 'White Monkey (Bai Hou)'},\n {value: 'Mountain Kenya', text: 'Mountain Kenya'},\n {value: 'Formosa Silk', text: 'Formosa Silk'},\n {value: 'Blueberry Lagoon', text: 'Blueberry Lagoon'},\n {value: 'Eleven OClock Rooibos Super Grade',\n text: 'Eleven OClock Rooibos Super Grade'},\n {value: 'Mount Everest Breakfast', text: 'Mount Everest Breakfast'},\n {value: 'Singell FTGFOP1 2nd Flush Darjeeling',\n text: 'Singell FTGFOP1 2nd Flush Darjeeling'},\n {value: '2012 EoT Bangwei 33 Sheng', text: '2012 EoT Bangwei 33 Sheng'},\n {value: '2005 Nanjian Phoenix Green Tuocha',\n text: '2005 Nanjian Phoenix Green Tuocha'},\n {value: 'Fujian New Craft', text: 'Fujian New Craft'},\n {value: 'ZY84: Yunnan Rare Grade', text: 'ZY84: Yunnan Rare Grade'},\n {value: 'Nightly Calm (formerly Bedtime Blend)',\n text: 'Nightly Calm (formerly Bedtime Blend)'},\n {value: 'Gan Lu (2015 Pre-Qing Ming)',\n text: 'Gan Lu (2015 Pre-Qing Ming)'},\n {value: 'Honu Chai', text: 'Honu Chai'},\n {value: 'Cranberry Herbal Tea', text: 'Cranberry Herbal Tea'},\n {value: 'MARGARETS HOPE SUPREME SFTGFOP1 - DJ38/2014 Darjeeling First Flush 2014',\n text: 'DJ38/2014 Darjeeling First Flush 2014'},\n {value: 'Organic Jasmine Tea', text: 'Organic Jasmine Tea'},\n {value: 'Caramel Spice', text: 'Caramel Spice'},\n {value: 'Lemongrass Herbal Tea', text: 'Lemongrass Herbal Tea'},\n {value: 'Gen Mai Cha Sencha', text: 'Gen Mai Cha Sencha'},\n {value: 'Sichuan Caravan', text: 'Sichuan Caravan'},\n {value: 'Cinnazen Tang', text: 'Cinnazen Tang'},\n {value: 'Pink Passionfruit', text: 'Pink Passionfruit'},\n {value: 'Decaf Chai Tea', text: 'Decaf Chai Tea'},\n {value: 'North India Manjhee', text: 'North India Manjhee'},\n {value: 'Thé des Alizés', text: 'Thé des Alizés'},\n {value: 'Formosa Lapsang Souchong', text: 'Formosa Lapsang Souchong'},\n {value: 'Precious Dew Pearl', text: 'Precious Dew Pearl'},\n {value: 'Kilinoe', text: 'Kilinoe'},\n {value: 'Blooming Lemon Nirvana', text: 'Blooming Lemon Nirvana'},\n {value: 'Hoji-cha', text: 'Hoji-cha'},\n {value: 'Mlesna black', text: 'Mlesna black'},\n {value: 'Blue Beauty Oolong', text: 'Blue Beauty Oolong'},\n {value: 'Strawberry Vanilla (Little Citizens Herb Tea)',\n text: 'Strawberry Vanilla (Little Citizens Herb Tea)'},\n {value: 'Silencio Andino', text: 'Silencio Andino'},\n {value: 'Sweet Autumn Tea', text: 'Sweet Autumn Tea'},\n {value: 'Green Bouquet', text: 'Green Bouquet'},\n {value: 'RaJini Blend', text: 'RaJini Blend'},\n {value: 'Bamboo Berry', text: 'Bamboo Berry'},\n {value: 'Darjeeling Teesta Valley', text: 'Darjeeling Teesta Valley'},\n {value: 'Amba Ceylon OP1', text: 'Amba Ceylon OP1'},\n {value: 'Sleepless Sencha', text: 'Sleepless Sencha'},\n {value: 'Elderberry Fruit Blend', text: 'Elderberry Fruit Blend'},\n {value: 'Assam Tarajulie FBOP', text: 'Assam Tarajulie FBOP'},\n {value: 'Lemon Herbal Tea', text: 'Lemon Herbal Tea'},\n {value: 'Organic Mamaki Tea', text: 'Organic Mamaki Tea'},\n {value: 'English Breakfast Black Tea',\n text: 'English Breakfast Black Tea'},\n {value: 'Red Rosebuds', text: 'Red Rosebuds'},\n {value: 'Kyoto Sencha Cherry Rose', text: 'Kyoto Sencha Cherry Rose'},\n {value: 'TE47: Moroccan Green Mint', text: 'TE47: Moroccan Green Mint'},\n {value: 'Chocolate Orange Pu-erh', text: 'Chocolate Orange Pu-erh'},\n {value: 'Makaibari Autumnal Darjeeling',\n text: 'Makaibari Autumnal Darjeeling'},\n {value: '2011 First Flush Darjeeling Tea Singbulli Estate-SFTGFOP1 China Clonal',\n text: '2011 First Flush Darjeeling Tea Singbulli Estate'},\n {value: 'Se Chung Oolong Organic Loose',\n text: 'Se Chung Oolong Organic Loose'},\n {value: 'Grey Chocolate Creme', text: 'Grey Chocolate Creme'},\n {value: 'Rooibos Sweet Heart', text: 'Rooibos Sweet Heart'},\n {value: '2005 Aged Tie Guan Yin', text: '2005 Aged Tie Guan Yin'},\n {value: 'Dragon Well', text: 'Dragon Well'},\n {value: 'Assam Orangajuli FF', text: 'Assam Orangajuli FF'},\n {value: 'Smoky Chocolate', text: 'Smoky Chocolate'},\n {value: 'Cream of Earl Grey (organic)',\n text: 'Cream of Earl Grey (organic)'},\n {value: 'Long Jing (Dragon Well) Superior',\n text: 'Long Jing (Dragon Well) Superior'},\n {value: 'Iron Goddess (Tieguanyin)', text: 'Iron Goddess (Tieguanyin)'},\n {value: 'Darjeeling Nr. 10 TGFOP Rarität Second Flush',\n text: 'Darjeeling Nr. 10 TGFOP Rarität Second Flush'},\n {value: 'Mountain Organic Indonesian Oolong Tea',\n text: 'Mountain Organic Indonesian Oolong Tea'},\n {value: 'Superfruit green tea acai dragonfruit &amp; melon',\n text: 'Superfruit green tea acai dragonfruit &amp; melon'},\n {value: 'Organic Yunnan Black Tea', text: 'Organic Yunnan Black Tea'},\n {value: 'Blackberry Vanilla Infusion',\n text: 'Blackberry Vanilla Infusion'},\n {value: 'Plum Harvest', text: 'Plum Harvest'},\n {value: 'Tippy Earl Grey', text: 'Tippy Earl Grey'},\n {value: 'Original Tulsi', text: 'Original Tulsi'},\n {value: 'Mangalam Estate FTGFOP1 Cl. (TA57)',\n text: 'Mangalam Estate FTGFOP1 Cl. (TA57)'},\n {value: 'Strawberry Chamomile', text: 'Strawberry Chamomile'},\n {value: '7562 Menghai Dayi Pu-erh Brick 2006 250g Ripe',\n text: '7562 Menghai Dayi Pu-erh Brick 2006 250g Ripe'},\n {value: 'Tung Ting Charcoal Roasted', text: 'Tung Ting Charcoal Roasted'},\n {value: 'Blue Beauty', text: 'Blue Beauty'},\n {value: 'Organic Lychee Green', text: 'Organic Lychee Green'},\n {value: 'Bird of Paradise', text: 'Bird of Paradise'},\n {value: 'Chocolate Almond Allure', text: 'Chocolate Almond Allure'},\n {value: 'Matcha Maker', text: 'Matcha Maker'},\n {value: 'Bedtime Tea', text: 'Bedtime Tea'},\n {value: 'Chocolate Bacon Black Tea', text: 'Chocolate Bacon Black Tea'},\n {value: 'Caramel Corn', text: 'Caramel Corn'},\n {value: 'TDC2: Tindharia Estate Oolong (DJ-54)',\n text: 'TDC2: Tindharia Estate Oolong (DJ-54)'},\n {value: 'House Tieguanyin Lot No. 1', text: 'House Tieguanyin Lot No. 1'},\n {value: 'Grapefruit', text: 'Grapefruit'},\n {value: 'Matcha Japanese Green Tea [New Version]',\n text: 'Matcha Japanese Green Tea [New Version]'},\n {value: 'Brattle Street Blend', text: 'Brattle Street Blend'},\n {value: 'Green Tea Chai', text: 'Green Tea Chai'},\n {value: 'Royal Wedding English Breakfast Tea',\n text: 'Royal Wedding English Breakfast Tea'},\n {value: 'Darjeeling FTGFOP1 Soom First Flush',\n text: 'Darjeeling FTGFOP1 Soom First Flush'},\n {value: 'Heartburn Tea', text: 'Heartburn Tea'},\n {value: 'Coconut Cocoa', text: 'Coconut Cocoa'},\n {value: 'Fresh', text: 'Fresh'},\n {value: 'Premium Grade Matcha', text: 'Premium Grade Matcha'},\n {value: 'Satemwa White Twig', text: 'Satemwa White Twig'},\n {value: 'Darjeeling Arya Tea', text: 'Darjeeling Arya Tea'},\n {value: 'Macadamia Nut Rooibos', text: 'Macadamia Nut Rooibos'},\n {value: 'Lavender Lemon Mint', text: 'Lavender Lemon Mint'},\n {value: 'Orange Pekoe (organic)', text: 'Orange Pekoe (organic)'},\n {value: 'Darjeeling First Flush Giddaphar Estate 2009',\n text: 'Darjeeling First Flush Giddaphar Estate 2009'},\n {value: 'White Chocolate Infusion', text: 'White Chocolate Infusion'},\n {value: 'Assam FTGFOP1 Dirial', text: 'Assam FTGFOP1 Dirial'},\n {value: 'Sencha Kyoto Cherry Rose Festival',\n text: 'Sencha Kyoto Cherry Rose Festival'},\n {value: '357 gram Menghai Dayi Hong - 2008',\n text: '357 gram Menghai Dayi Hong - 2008'},\n {value: 'Juniper Berry', text: 'Juniper Berry'},\n {value: 'Cinnamon Chai', text: 'Cinnamon Chai'},\n {value: '2009 Liming HongYun Pu-erh', text: '2009 Liming HongYun Pu-erh'},\n {value: 'Lung Ching Grade 1 (Dragonswell)',\n text: 'Lung Ching Grade 1 (Dragonswell)'},\n {value: 'Russian Morning No. 24', text: 'Russian Morning No. 24'},\n {value: 'Mint Chocolat', text: 'Mint Chocolat'},\n {value: 'Yunnan Gongfu Fragrant Black Tea',\n text: 'Yunnan Gongfu Fragrant Black Tea'},\n {value: 'White Raspberry Champagne', text: 'White Raspberry Champagne'},\n {value: 'Starbucks Black Shaken Iced Tea Lemonade',\n text: 'Starbucks Black Shaken Iced Tea Lemonade'},\n {value: 'DETOX: PureTea – Rooibos Milk Thistle Burdock',\n text: 'DETOX: PureTea – Rooibos Milk Thistle Burdock'},\n {value: 'Tiramisu / Marscapone', text: 'Tiramisu / Marscapone'},\n {value: 'Tall Mountain', text: 'Tall Mountain'},\n {value: 'Sencha Reserve (Growers Series)',\n text: 'Sencha Reserve (Growers Series)'},\n {value: 'Sencha Peach', text: 'Sencha Peach'},\n {value: 'Ceylon Pekoe', text: 'Ceylon Pekoe'},\n {value: 'Green Butterfly', text: 'Green Butterfly'},\n {value: 'Hazelnut Vanilla', text: 'Hazelnut Vanilla'},\n {value: 'White Lemon', text: 'White Lemon'},\n {value: 'Haiwan 7578', text: 'Haiwan 7578'},\n {value: 'Iron Buddha Oolong &amp; Strawberry Slender Pu-erh',\n text: 'Iron Buddha Oolong &amp; Strawberry Slender Pu-erh'},\n {value: 'Sweet Fruit Garden', text: 'Sweet Fruit Garden'},\n {value: 'Peach Nectar Tea Bag', text: 'Peach Nectar Tea Bag'},\n {value: 'Infected Mushroom 2003 – Dali',\n text: 'Infected Mushroom 2003 – Dali'},\n {value: 'Blueberry Fruit Tea', text: 'Blueberry Fruit Tea'},\n {value: 'Kuki Matcha', text: 'Kuki Matcha'},\n {value: 'Ancient Tree Shou 1995', text: 'Ancient Tree Shou 1995'},\n {value: 'Fukamushi-Sencha Maromi', text: 'Fukamushi-Sencha Maromi'},\n {value: 'Pommier', text: 'Pommier'},\n {value: 'Decaffeinated China Green (ZG09)',\n text: 'Decaffeinated China Green (ZG09)'},\n {value: 'Assam Dimakusi CTCBOP', text: 'Assam Dimakusi CTCBOP'},\n {value: 'Thai Tea Powder', text: 'Thai Tea Powder'},\n {value: 'Nepal Black', text: 'Nepal Black'},\n {value: 'Arya Clonal Exclusive Autumn Flush',\n text: 'Arya Clonal Exclusive Autumn Flush'},\n {value: 'Tie Luo Han Spring Harvest 2009',\n text: 'Tie Luo Han Spring Harvest 2009'},\n {value: 'BIO Vanilla Lemon White', text: 'BIO Vanilla Lemon White'},\n {value: 'Monkey Picked Tieguanyin', text: 'Monkey Picked Tieguanyin'},\n {value: 'Chai Mate Supreme', text: 'Chai Mate Supreme'},\n {value: 'Organic Yunan Gold', text: 'Organic Yunan Gold'},\n {value: 'Peach Infusion', text: 'Peach Infusion'},\n {value: 'Red Ruby Black Tea', text: 'Red Ruby Black Tea'},\n {value: 'China Special Green Mao Feng',\n text: 'China Special Green Mao Feng'},\n {value: 'earl grey', text: 'earl grey'},\n {value: 'English Toffee Matcha', text: 'English Toffee Matcha'},\n {value: 'After The Snow Sprouting', text: 'After The Snow Sprouting'},\n {value: 'Dragon Pearl', text: 'Dragon Pearl'},\n {value: 'Get Lean', text: 'Get Lean'},\n {value: 'Jasmine White Needle - Yin Zhen',\n text: 'Jasmine White Needle - Yin Zhen'},\n {value: 'Yunnan Tuocha', text: 'Yunnan Tuocha'},\n {value: 'Rice-Scent Mini tuo', text: 'Rice-Scent Mini tuo'},\n {value: 'Keemun Hoa Ya A', text: 'Keemun Hoa Ya A'},\n {value: 'Green Tea with Orange Passionfruit &amp; Jasmine',\n text: 'Green Tea with Orange Passionfruit &amp; Jasmine'},\n {value: 'Earl Grey Russian', text: 'Earl Grey Russian'},\n {value: 'Sourenee Darjeeling 2nd Flush 2012',\n text: 'Sourenee Darjeeling 2nd Flush 2012'},\n {value: 'Fu Zhuan Tea Brick', text: 'Fu Zhuan Tea Brick'},\n {value: 'Matcha Green Tea Latte/Frappe Mix',\n text: 'Matcha Green Tea Latte/Frappe Mix'},\n {value: 'Milk &amp; Cookies', text: 'Milk &amp; Cookies'},\n {value: 'Smooth Strawberry Dream', text: 'Smooth Strawberry Dream'},\n {value: 'King of Fruits', text: 'King of Fruits'},\n {value: 'Top Leaf', text: 'Top Leaf'},\n {value: 'Green Dragon', text: 'Green Dragon'},\n {value: 'Maple Pecan Oolong', text: 'Maple Pecan Oolong'},\n {value: 'Dry Desert Lime', text: 'Dry Desert Lime'},\n {value: 'Double Bergamot Earl Grey', text: 'Double Bergamot Earl Grey'},\n {value: 'Organic Banaspaty Bliss', text: 'Organic Banaspaty Bliss'},\n {value: 'Cinnamon Roll Honeybush', text: 'Cinnamon Roll Honeybush'},\n {value: 'Jour J', text: 'Jour J'},\n {value: 'Darjeeling Castleton Spl. FTGFOP1 F. F. CH',\n text: 'Darjeeling Castleton Spl. FTGFOP1 F. F. CH'},\n {value: 'Forbidden Fruit', text: 'Forbidden Fruit'},\n {value: '2006 Jujube Aroma Puerh Tuocha',\n text: '2006 Jujube Aroma Puerh Tuocha'},\n {value: 'Green and Ginseng Tea Blend',\n text: 'Green and Ginseng Tea Blend'},\n {value: 'Gyokuro Gold', text: 'Gyokuro Gold'},\n {value: 'Vanille des Îles', text: 'Vanille des Îles'},\n {value: 'African Rooibos', text: 'African Rooibos'},\n {value: 'Pistachio Gelato', text: 'Pistachio Gelato'},\n {value: 'Zheng Yan Rou Gui', text: 'Zheng Yan Rou Gui'},\n {value: 'Shu Puerh Cake', text: 'Shu Puerh Cake'},\n {value: 'Yunnan Tippy Pu-Ehr', text: 'Yunnan Tippy Pu-Ehr'},\n {value: 'Thurbo Estate FTGF OP (first flush Darjeeling)',\n text: 'Thurbo Estate FTGF OP (first flush Darjeeling)'},\n {value: 'White Melon Yogurt', text: 'White Melon Yogurt'},\n {value: 'Spiced Carob (organic) / Dr. Chocolate',\n text: 'Spiced Carob (organic) / Dr. Chocolate'},\n {value: 'HarSha', text: 'HarSha'},\n {value: 'Mango Ice Cream', text: 'Mango Ice Cream'},\n {value: '2010 Xiang Dou', text: '2010 Xiang Dou'},\n {value: 'Champaign oolong', text: 'Champaign oolong'},\n {value: 'Pu-erh Vanilla Mint', text: 'Pu-erh Vanilla Mint'},\n {value: 'Pu Er 2006 Bulang Shan', text: 'Pu Er 2006 Bulang Shan'},\n {value: 'Thé des Légendes', text: 'Thé des Légendes'},\n {value: 'Yunnan Sweet Tips of Simao', text: 'Yunnan Sweet Tips of Simao'},\n {value: 'Angel Dream', text: 'Angel Dream'},\n {value: 'Jade Fire', text: 'Jade Fire'},\n {value: 'Korean Sejak', text: 'Korean Sejak'},\n {value: 'Silver Rain', text: 'Silver Rain'},\n {value: 'Mango Rose', text: 'Mango Rose'},\n {value: 'Plum (Sencha)', text: 'Plum (Sencha)'},\n {value: 'Blackberry Mojito', text: 'Blackberry Mojito'},\n {value: 'Tilleul', text: 'Tilleul'},\n {value: 'Tipus Microground Instant Chai',\n text: 'Tipus Microground Instant Chai'},\n {value: 'Sencha Red Forest', text: 'Sencha Red Forest'},\n {value: 'Keemun Rhapsody', text: 'Keemun Rhapsody'},\n {value: 'Royal Golden Safari', text: 'Royal Golden Safari'},\n {value: 'Maple Bacon', text: 'Maple Bacon'},\n {value: 'China Yellow Jun Shan Yin Zhen (ZG53)',\n text: 'China Yellow Jun Shan Yin Zhen (ZG53)'},\n {value: 'Queenstown Rooibos', text: 'Queenstown Rooibos'},\n {value: 'Ceylon Forest Green', text: 'Ceylon Forest Green'},\n {value: 'Sweet Potato Pie', text: 'Sweet Potato Pie'},\n {value: 'Hummingbirds Delight', text: 'Hummingbirds Delight'},\n {value: '2010 Xing Hai Raw Beeng Cha',\n text: '2010 Xing Hai Raw Beeng Cha'},\n {value: 'Midsummer Nights Dream', text: 'Midsummer Nights Dream'},\n {value: 'Snowberry Blends', text: 'Snowberry Blends'},\n {value: '2011 Spring Nan Nuo Mountain Ban Po Lao Zhai Old Tree &amp; Small Tree Tasting Pack',\n text: '2011 Spring Nan Nuo Mountain Ban Po Lao Zhai Old Tree'},\n {value: 'Rooibos Nutmeg &amp; Vanilla',\n text: 'Rooibos Nutmeg Vanilla'},\n {value: 'Spice With Black Tea', text: 'Spice With Black Tea'},\n {value: 'Shincha Sencha Kinari', text: 'Shincha Sencha Kinari'},\n {value: 'Gummy Bear', text: 'Gummy Bear'},\n {value: '2000 Jin Cha from Xia Guan (Tibetan Mushroom pu erh)',\n text: '2000 Jin Cha from Xia Guan (Tibetan Mushroom pu erh)'},\n {value: '2003 Reserve Four Season Oolong',\n text: '2003 Reserve Four Season Oolong'},\n {value: 'Jasmine Pearls Scented Tea', text: 'Jasmine Pearls Scented Tea'},\n {value: 'Hawaiian Pineapple', text: 'Hawaiian Pineapple'},\n {value: 'American Roots Herbal Tea', text: 'American Roots Herbal Tea'},\n {value: 'Anteadote Jasmine Tea Iced', text: 'Anteadote Jasmine Tea Iced'},\n {value: 'Love Potion', text: 'Love Potion'},\n {value: '2007 Imperial Concubine Aroma Pu-erh Tea Cake',\n text: '2007 Imperial Concubine Aroma Pu-erh Tea Cake'},\n {value: 'Black Jasmine Cream', text: 'Black Jasmine Cream'},\n {value: '2007 Banzhang Arbor King Pu-erh Tea Cake',\n text: '2007 Banzhang Arbor King Pu-erh Tea Cake'},\n {value: 'Anxi Oolong (Tian Hua)', text: 'Anxi Oolong (Tian Hua)'},\n {value: 'Yerba Mate Organic Roasted', text: 'Yerba Mate Organic Roasted'},\n {value: 'Matsukaze Matcha (Uji)', text: 'Matsukaze Matcha (Uji)'},\n {value: 'Midnight Blue Bai Mudan', text: 'Midnight Blue Bai Mudan'},\n {value: 'Superfine Taiwan Qing Xiang Dong Ding Oolong Tea',\n text: 'Superfine Taiwan Qing Xiang Dong Ding Oolong Tea'},\n {value: 'Indonesian Gold', text: 'Indonesian Gold'},\n {value: 'Organic Cinnamon Rooibos', text: 'Organic Cinnamon Rooibos'},\n {value: 'Mang Zhi 2004 Gu Yuan Chun Raw Puer',\n text: 'Mang Zhi 2004 Gu Yuan Chun Raw Puer'},\n {value: 'Potpourri', text: 'Potpourri'},\n {value: '2009 Lao Ban Zhang', text: '2009 Lao Ban Zhang'},\n {value: 'Chocolate Malt', text: 'Chocolate Malt'},\n {value: 'Shu Pu-erh Round Tea Cake', text: 'Shu Pu-erh Round Tea Cake'},\n {value: 'Strawberry Oolong Tea', text: 'Strawberry Oolong Tea'},\n {value: 'james buchanan', text: 'james buchanan'},\n {value: 'Carrot-Cupcake', text: 'Carrot-Cupcake'},\n {value: 'Darjeeling Makaibari Vintage Muscatel from the Leopards Lair',\n text: 'Darjeeling Makaibari Vintage Muscatel from the Leopards Lair'},\n {value: 'Xingyang Nuggets 2008 Shu', text: 'Xingyang Nuggets 2008 Shu'},\n {value: 'Harvest Brew', text: 'Harvest Brew'},\n {value: 'Organic Sencha Mint', text: 'Organic Sencha Mint'},\n {value: 'Mo Li Mao Jian', text: 'Mo Li Mao Jian'},\n {value: 'China Yunnan Simao Pure Bud Golden Snail Black',\n text: 'China Yunnan Simao Pure Bud Golden Snail Black'},\n {value: 'Green Machine Matcha', text: 'Green Machine Matcha'},\n {value: 'Vanilla Sencha', text: 'Vanilla Sencha'},\n {value: 'Darjeeling 1st Flush 2010 Micro-Lot DJ 3/10',\n text: 'Darjeeling 1st Flush 2010 Micro-Lot DJ 3/10'},\n {value: 'Mocha Matcha', text: 'Mocha Matcha'},\n {value: 'Cocoa/Orange', text: 'Cocoa/Orange'},\n {value: 'Fairy Dust', text: 'Fairy Dust'},\n {value: 'An Ji Bai', text: 'An Ji Bai'},\n {value: 'Rooibos des Vahines', text: 'Rooibos des Vahines'},\n {value: 'Red Peony Rosettes', text: 'Red Peony Rosettes'},\n {value: 'Darjeeling SFTGFOP1 North Tukvar',\n text: 'Darjeeling SFTGFOP1 North Tukvar'},\n {value: '18 Blooms Handmade Blooming Flower Tea (Jasmine Green)',\n text: '18 Blooms Handmade Blooming Flower Tea (Jasmine Green)'},\n {value: 'Honey I Dew', text: 'Honey I Dew'},\n {value: '2010 Winter Gao Shan Hung Shui Oolong',\n text: '2010 Winter Gao Shan Hung Shui Oolong'},\n {value: 'High Mountain Oolong (organic)',\n text: 'High Mountain Oolong (organic)'},\n {value: 'Holy Mate', text: 'Holy Mate'},\n {value: 'Golden Pak Fujian Oolong', text: 'Golden Pak Fujian Oolong'},\n {value: 'Gyokuro Souryuu', text: 'Gyokuro Souryuu'},\n {value: 'Assam BOP', text: 'Assam BOP'},\n {value: 'Castleton Autumnal', text: 'Castleton Autumnal'},\n {value: 'Darjeeling FTGFOP Kaley Valley Second Flush',\n text: 'Darjeeling FTGFOP Kaley Valley Second Flush'},\n {value: 'Blueberry Merlot', text: 'Blueberry Merlot'},\n {value: 'Cranberry Apple', text: 'Cranberry Apple'},\n {value: 'Gyokuro Select (Growers Series)',\n text: 'Gyokuro Select (Growers Series)'},\n {value: 'Pink Tea - Authentic Ceylon Tea',\n text: 'Pink Tea - Authentic Ceylon Tea'},\n {value: '40 kinds Flavour Puer Tea', text: '40 kinds Flavour Puer Tea'},\n {value: 'Lemongrass Mélange', text: 'Lemongrass Mélange'},\n {value: '2002 Collectors Puerh Beeng Cha',\n text: '2002 Collectors Puerh Beeng Cha'},\n {value: 'Big Leaf Puer', text: 'Big Leaf Puer'},\n {value: 'Mrs. Hudson', text: 'Mrs. Hudson'},\n {value: 'Ceylon &amp; India (Orange Pekoe)',\n text: 'Ceylon &amp; India (Orange Pekoe)'},\n {value: 'Red Bloom', text: 'Red Bloom'},\n {value: 'Voyage en Provence', text: 'Voyage en Provence'},\n {value: 'Landpartie', text: 'Landpartie'},\n {value: 'Sencha Jade Reserve', text: 'Sencha Jade Reserve'},\n {value: 'Taylors of Harrogate Vanilla',\n text: 'Taylors of Harrogate Vanilla'},\n {value: 'Tippy Orange Pekoe', text: 'Tippy Orange Pekoe'},\n {value: 'De-stress', text: 'De-stress'},\n {value: 'Organic Gunpowder Green Tea',\n text: 'Organic Gunpowder Green Tea'},\n {value: 'Fresh Fantasy', text: 'Fresh Fantasy'},\n {value: 'Darjeeling Highlands [Discontinued]',\n text: 'Darjeeling Highlands [Discontinued]'},\n {value: 'East Frisian', text: 'East Frisian'},\n {value: 'Taj Mahal', text: 'Taj Mahal'},\n {value: 'Ostfriesen-Tee (East Frisian Tea)',\n text: 'Ostfriesen-Tee (East Frisian Tea)'},\n {value: 'Rose Hip Green', text: 'Rose Hip Green'},\n {value: '2010 Mansai', text: '2010 Mansai'},\n {value: 'Yunnan Moonlight Buds - White Tea',\n text: 'Yunnan Moonlight Buds - White Tea'},\n {value: 'Kirkoswald Estate Ceylon Pekoe (TC29)',\n text: 'Kirkoswald Estate Ceylon Pekoe (TC29)'},\n {value: 'Cancer - The Zodiac Series', text: 'Cancer - The Zodiac Series'},\n {value: 'Sunkissed Sashay', text: 'Sunkissed Sashay'},\n {value: 'Te Verde', text: 'Te Verde'},\n {value: 'Organic Pai Mu Tan ZW56', text: 'Organic Pai Mu Tan ZW56'},\n {value: 'Peanut Butter Toast', text: 'Peanut Butter Toast'},\n {value: 'Yixing Travel Tea Tumbler', text: 'Yixing Travel Tea Tumbler'},\n {value: '2003 Farmers Cooperative (Mt. Banzhang) Wild Arbor Sheng',\n text: '2003 Farmers Cooperative (Mt. Banzhang) Wild Arbor Sheng'},\n {value: 'English Breakfast Blend no.14',\n text: 'English Breakfast Blend no.14'},\n {value: 'Cherry Cola', text: 'Cherry Cola'},\n {value: 'Anji Duet', text: 'Anji Duet'},\n {value: 'Cotton Candy Matcha', text: 'Cotton Candy Matcha'},\n {value: '2005 Menghai Shou Pu-erh', text: '2005 Menghai Shou Pu-erh'},\n {value: 'Organic Ceylon Black Tips', text: 'Organic Ceylon Black Tips'},\n {value: 'Black Dragon (OT02)', text: 'Black Dragon (OT02)'},\n {value: 'Apple Custard', text: 'Apple Custard'},\n {value: 'Angel Dreams', text: 'Angel Dreams'},\n {value: 'Winter White Earl Grey', text: 'Winter White Earl Grey'},\n {value: 'Golden Spring', text: 'Golden Spring'},\n {value: 'Perfect Ceylon', text: 'Perfect Ceylon'},\n {value: 'Throat Coat', text: 'Throat Coat'},\n {value: 'Mandarin Citrus', text: 'Mandarin Citrus'},\n {value: 'Premium Dragon Phoenix Pearls',\n text: 'Premium Dragon Phoenix Pearls'},\n {value: 'JING Assam Black Tea (Hajua Estate)',\n text: 'JING Assam Black Tea (Hajua Estate)'},\n {value: 'Royal ImmortaliTea', text: 'Royal ImmortaliTea'},\n {value: 'Ban Tian Yao Wu Yi Oolong', text: 'Ban Tian Yao Wu Yi Oolong'},\n {value: 'Camomile Smile', text: 'Camomile Smile'},\n {value: 'Japan Houjicha-Roasted Tea', text: 'Japan Houjicha-Roasted Tea'},\n {value: 'White Ayurvedic Chai', text: 'White Ayurvedic Chai'},\n {value: 'China Oolong (o) (OC04)', text: 'China Oolong (o) (OC04)'},\n {value: 'Orange Glow', text: 'Orange Glow'},\n {value: 'Keemun 1110', text: 'Keemun 1110'},\n {value: 'Organic Shui Xian Oolong Tea',\n text: 'Organic Shui Xian Oolong Tea'},\n {value: 'Yerba Mate Shade Grown', text: 'Yerba Mate Shade Grown'},\n {value: 'India Chai Latte', text: 'India Chai Latte'},\n {value: 'Raspberry Zinger', text: 'Raspberry Zinger'},\n {value: 'Hongyu Hongcha Nantou Ruby 18 SUN MOON LAKE BLACK TEA',\n text: 'Hongyu Hongcha Nantou Ruby 18 SUN MOON LAKE BLACK TEA'},\n {value: 'Select Tips', text: 'Select Tips'},\n {value: 'Organic Keemun Hao Ya A', text: 'Organic Keemun Hao Ya A'},\n {value: 'Osmanthus Milk Oolong', text: 'Osmanthus Milk Oolong'},\n {value: '2008 Menghai Dayi 7562 Premium Ripe',\n text: '2008 Menghai Dayi 7562 Premium Ripe'},\n {value: 'Formosa Pouchong Oolong Tea',\n text: 'Formosa Pouchong Oolong Tea'},\n {value: 'Ice black tea- té negro frío',\n text: 'Ice black tea- té negro frío'},\n {value: 'Organic Darjeeling - Goomtee 1st Flush FTGFOP1 (2009)',\n text: 'Organic Darjeeling - Goomtee 1st Flush FTGFOP1 (2009)'},\n {value: 'Pineapple Guava White Tea', text: 'Pineapple Guava White Tea'},\n {value: 'Pear-Lemon Panache', text: 'Pear-Lemon Panache'},\n {value: 'Cherry Kiwi Coconut Fruit', text: 'Cherry Kiwi Coconut Fruit'},\n {value: 'Nepalese Guranse', text: 'Nepalese Guranse'},\n {value: 'True Love Flower Tea', text: 'True Love Flower Tea'},\n {value: 'Kenyan Black Tea with Ginger',\n text: 'Kenyan Black Tea with Ginger'},\n {value: 'Wild Tree Purple Varietal Black Tea of Dehong Spring',\n text: 'Wild Tree Purple Varietal Black Tea of Dehong Spring'},\n {value: '2005 Xiaguan Jia Ji (1st Grade) Pu-erh',\n text: '2005 Xiaguan Jia Ji (1st Grade) Pu-erh'},\n {value: 'Chocolate tea', text: 'Chocolate tea'},\n {value: 'Refresh (Filter bag version)',\n text: 'Refresh (Filter bag version)'},\n {value: 'Roasted Tie Kuan Yin Tea', text: 'Roasted Tie Kuan Yin Tea'},\n {value: 'Raspberry Thriller Herbal Tea',\n text: 'Raspberry Thriller Herbal Tea'},\n {value: 'Japan Gyokuro', text: 'Japan Gyokuro'},\n {value: 'Marco Polo', text: 'Marco Polo'},\n {value: 'Hibiscus Mint', text: 'Hibiscus Mint'},\n {value: 'J.E Oolong Milky', text: 'J.E Oolong Milky'},\n {value: 'Longevity Brow (Shou Mei) White',\n text: 'Longevity Brow (Shou Mei) White'},\n {value: '2006 ShuangJiang Mengku Teji Qing Bing Cha',\n text: '2006 ShuangJiang Mengku Teji Qing Bing Cha'},\n {value: 'Ceylon [Discontinued]', text: 'Ceylon [Discontinued]'},\n {value: 'Sweet Green Tuocha Pu-Erh', text: 'Sweet Green Tuocha Pu-Erh'},\n {value: 'Powdered Sencha Green Tea', text: 'Powdered Sencha Green Tea'},\n {value: 'Mini Tou-Cha', text: 'Mini Tou-Cha'},\n {value: 'Thé du Hammam Rooibos', text: 'Thé du Hammam Rooibos'},\n {value: 'Alaskan Blue Beary Black Tea',\n text: 'Alaskan Blue Beary Black Tea'},\n {value: 'Lemon Cream Pie', text: 'Lemon Cream Pie'},\n {value: 'Cardamom French Toast', text: 'Cardamom French Toast'},\n {value: 'sweet sunrise', text: 'sweet sunrise'},\n {value: 'Golden Honey Dew', text: 'Golden Honey Dew'},\n {value: 'Saveur de Paris', text: 'Saveur de Paris'},\n {value: 'Provence', text: 'Provence'},\n {value: 'Rooibos Zanzibar Spice', text: 'Rooibos Zanzibar Spice'},\n {value: 'Honeydew White Tea', text: 'Honeydew White Tea'},\n {value: 'Nightcap', text: 'Nightcap'},\n {value: 'Pu-erh Ginger Tea Blend', text: 'Pu-erh Ginger Tea Blend'},\n {value: 'Giant Peach Iced Tea', text: 'Giant Peach Iced Tea'},\n {value: 'Castleton 2014 First Flush Darjeeling',\n text: 'Castleton 2014 First Flush Darjeeling'},\n {value: 'Cheery Cherry', text: 'Cheery Cherry'},\n {value: '2005 Big Leaf Puer', text: '2005 Big Leaf Puer'},\n {value: 'Organic Tropical Paradise', text: 'Organic Tropical Paradise'},\n {value: 'Tippy Assam Tea', text: 'Tippy Assam Tea'},\n {value: 'Rooibos Red Spice', text: 'Rooibos Red Spice'},\n {value: 'Mad Hatters Delight', text: 'Mad Hatters Delight'},\n {value: 'Something Rotten in Darthmark',\n text: 'Something Rotten in Darthmark'},\n {value: 'Tanyang Gongfu', text: 'Tanyang Gongfu'},\n {value: 'Formosa Oolong Fancy Grade', text: 'Formosa Oolong Fancy Grade'},\n {value: 'Christmas Leaf', text: 'Christmas Leaf'},\n {value: 'Phoenix Pearl', text: 'Phoenix Pearl'},\n {value: 'RELAX: TranquilyTea – Passionflower Linden',\n text: 'RELAX: TranquilyTea – Passionflower Linden'},\n {value: 'Zen Master', text: 'Zen Master'},\n {value: 'Caramel Sundae Escape', text: 'Caramel Sundae Escape'},\n {value: 'Cranberry Orange Gourmet', text: 'Cranberry Orange Gourmet'},\n {value: 'Apres Ski', text: 'Apres Ski'},\n {value: 'Re-Root', text: 'Re-Root'},\n {value: 'Pistachio Lime Yerba Mate', text: 'Pistachio Lime Yerba Mate'},\n {value: 'R29 Ceylon', text: 'R29 Ceylon'},\n {value: 'Sweet Pomegranate', text: 'Sweet Pomegranate'},\n {value: 'Raynies Rose Green Tea', text: 'Raynies Rose Green Tea'},\n {value: 'Keemun Black Tiger', text: 'Keemun Black Tiger'},\n {value: 'Harvest Spice Tea', text: 'Harvest Spice Tea'},\n {value: 'Xiaguan 1998', text: 'Xiaguan 1998'},\n {value: 'Yunnan Golden Buds Golden Needle',\n text: 'Yunnan Golden Buds Golden Needle'},\n {value: 'Mustikkametsä (Bilberry Forest)',\n text: 'Mustikkametsä (Bilberry Forest)'},\n {value: 'Matcha (organic)', text: 'Matcha (organic)'},\n {value: 'Weight Loss Tea', text: 'Weight Loss Tea'},\n {value: 'Rainforest Alliance Certified - Strong Black',\n text: 'Rainforest Alliance Certified - Strong Black'},\n {value: 'Kai Hua Long Ding Premium', text: 'Kai Hua Long Ding Premium'},\n {value: 'Huang Cha', text: 'Huang Cha'},\n {value: 'Hello Sweetie', text: 'Hello Sweetie'},\n {value: 'Formosa Natural Wuhe Honey Black Tea',\n text: 'Formosa Natural Wuhe Honey Black Tea'},\n {value: 'Sencha from Fuji Shizuoka Inzatsu 131 cultivar',\n text: 'Sencha from Fuji Shizuoka Inzatsu 131 cultivar'},\n {value: 'Sun Moon Lake Organic', text: 'Sun Moon Lake Organic'},\n {value: 'Spring Pouchong', text: 'Spring Pouchong'},\n {value: 'Sweet Caramel O Mine', text: 'Sweet Caramel O Mine'},\n {value: 'Serene Chai Biodegradable Pyramid Sachets',\n text: 'Serene Chai Biodegradable Pyramid Sachets'},\n {value: 'White Paradise', text: 'White Paradise'},\n {value: 'PMS Tea®', text: 'PMS Tea®'},\n {value: 'Wuyi Mountain Oolong', text: 'Wuyi Mountain Oolong'},\n {value: 'Choc Chip Chai', text: 'Choc Chip Chai'},\n {value: 'Vanilla Chai Spice', text: 'Vanilla Chai Spice'},\n {value: 'Cheericup Ceylon', text: 'Cheericup Ceylon'},\n {value: 'Certified Organic Chai', text: 'Certified Organic Chai'},\n {value: 'Pineapple Papaya Passion', text: 'Pineapple Papaya Passion'},\n {value: 'Caramel Pear', text: 'Caramel Pear'},\n {value: 'American Breakfast', text: 'American Breakfast'},\n {value: 'Pumpkin Spice Chai', text: 'Pumpkin Spice Chai'},\n {value: 'Lychee (Lichee) Oolong', text: 'Lychee (Lichee) Oolong'},\n {value: 'Green Tea with Lemongrass and Strawberry',\n text: 'Green Tea with Lemongrass and Strawberry'},\n {value: 'Dan Cong', text: 'Dan Cong'},\n {value: 'Wedding Tea', text: 'Wedding Tea'},\n {value: 'Just Peachy', text: 'Just Peachy'},\n {value: 'Ming Mei Jasmine', text: 'Ming Mei Jasmine'},\n {value: 'Sencha Chiran', text: 'Sencha Chiran'},\n {value: 'Cardamon Cinnamon', text: 'Cardamon Cinnamon'},\n {value: 'Organic Whole Leaf Peppermint',\n text: 'Organic Whole Leaf Peppermint'},\n {value: 'Foxfire Chai', text: 'Foxfire Chai'},\n {value: 'Mt. Everest Blend', text: 'Mt. Everest Blend'},\n {value: 'Milk Oolong Quangzhou', text: 'Milk Oolong Quangzhou'},\n {value: 'Jordbærte', text: 'Jordbærte'},\n {value: 'Smores Chai', text: 'Smores Chai'},\n {value: 'Yorkshire Gold', text: 'Yorkshire Gold'},\n {value: 'Hua Gang Oolong Tea', text: 'Hua Gang Oolong Tea'},\n {value: 'Vert Provence', text: 'Vert Provence'},\n {value: 'Chamana Fucsia', text: 'Chamana Fucsia'},\n {value: 'Yerba Mate sin Palo', text: 'Yerba Mate sin Palo'},\n {value: 'Gunpowder Temple of Heaven ',\n text: 'Gunpowder Temple of Heaven '},\n {value: 'Niagra Peach Sencha Green', text: 'Niagra Peach Sencha Green'},\n {value: 'Anjou Pear-adise Oolong Tea',\n text: 'Anjou Pear-adise Oolong Tea'},\n {value: 'Pure English Mint', text: 'Pure English Mint'},\n {value: 'Jasmine Blossoms', text: 'Jasmine Blossoms'},\n {value: 'Yogi Berry', text: 'Yogi Berry'},\n {value: 'Pride of Darjeeling - Rare Second Flush',\n text: 'Pride of Darjeeling - Rare Second Flush'},\n {value: 'China Pai Mu Tan', text: 'China Pai Mu Tan'},\n {value: 'Gina Amaretta', text: 'Gina Amaretta'},\n {value: 'Rooibos Jasmine', text: 'Rooibos Jasmine'},\n {value: '2007 Awazon Mijin Excellent Big Tea Tree Raw Pu-erh Tea Cake 357g',\n text: '2007 Awazon Mijin Excellent Big Tea Tree Raw Pu-erh Tea Cake'},\n {value: 'Red Rose Real Tea Enhancers',\n text: 'Red Rose Real Tea Enhancers'},\n {value: 'Golden Breakfast', text: 'Golden Breakfast'},\n {value: 'Boo-Berry Cotton Candy', text: 'Boo-Berry Cotton Candy'},\n {value: 'Green Tea with Citrus', text: 'Green Tea with Citrus'},\n {value: 'Party of the Jungle', text: 'Party of the Jungle'},\n {value: 'Peach Black', text: 'Peach Black'},\n {value: 'Ceylon Blend', text: 'Ceylon Blend'},\n {value: 'Thé au Sahara', text: 'Thé au Sahara'},\n {value: 'Spring Keemun', text: 'Spring Keemun'},\n {value: 'Organic Rembeng Assam Black Tea',\n text: 'Organic Rembeng Assam Black Tea'},\n {value: 'Goomtee Estate First Flush Darjeeling FTGFOP1 DJ 4 - 2015',\n text: 'Goomtee Estate First Flush Darjeeling FTGFOP1 DJ 4 - 2015'},\n {value: 'Nilgiri Thiashola SFTGFOP1 Organic',\n text: 'Nilgiri Thiashola SFTGFOP1 Organic'},\n {value: 'Vietnamese Imperial Oolong (OV01)',\n text: 'Vietnamese Imperial Oolong (OV01)'},\n {value: 'Anastasia Tea', text: 'Anastasia Tea'},\n {value: 'Organic Ginger Orange Pu-erh',\n text: 'Organic Ginger Orange Pu-erh'},\n {value: 'Earl Grey Polish blend N° 18',\n text: 'Earl Grey Polish blend N° 18'},\n {value: 'Japanese Lime', text: 'Japanese Lime'},\n {value: 'Chocolate Honeybush', text: 'Chocolate Honeybush'},\n {value: 'Hongcha', text: 'Hongcha'},\n {value: 'Congou Keemun', text: 'Congou Keemun'},\n {value: 'Green Tea Heaven', text: 'Green Tea Heaven'},\n {value: 'Jasmine Tea Bag Organic Fair Trade Green Tea Blend',\n text: 'Jasmine Tea Bag Organic Fair Trade Green Tea Blend'},\n {value: 'Poobong Oolong (Black Musk)',\n text: 'Poobong Oolong (Black Musk)'},\n {value: 'Caramel Apple Green Tea', text: 'Caramel Apple Green Tea'},\n {value: 'Peach Melba', text: 'Peach Melba'},\n {value: 'Ceylon Neeraja', text: 'Ceylon Neeraja'},\n {value: 'French Vanilla Matcha (Red Matcha Base)',\n text: 'French Vanilla Matcha (Red Matcha Base)'},\n {value: '2008 Winter GradeA Pin-Lin Bao Zhong Hand-Harvested',\n text: '2008 Winter GradeA Pin-Lin Bao Zhong'},\n {value: 'Spiced Cinnamon Chai Black tea',\n text: 'Spiced Cinnamon Chai Black tea'},\n {value: 'Long Life Oolong', text: 'Long Life Oolong'},\n {value: 'Roasted Kukicha', text: 'Roasted Kukicha'},\n {value: 'Tea In a Jar: Aloe Vera', text: 'Tea In a Jar: Aloe Vera'},\n {value: 'Caramel Vanilla', text: 'Caramel Vanilla'},\n {value: 'Pumpkin Chai La Tea', text: 'Pumpkin Chai La Tea'},\n {value: 'Wedding Cake', text: 'Wedding Cake'},\n {value: 'Emperor Long Jing', text: 'Emperor Long Jing'},\n {value: 'Foreign Affair', text: 'Foreign Affair'},\n {value: 'Fruits dAlsace', text: 'Fruits dAlsace'},\n {value: 'Darleeling House Blend', text: 'Darleeling House Blend'},\n {value: 'Long Feng Xia Oolong Tea', text: 'Long Feng Xia Oolong Tea'},\n {value: 'Sencha Special Grade Yamato (TJ16)',\n text: 'Sencha Special Grade Yamato (TJ16)'},\n {value: 'Macaron Mangue Jasmin', text: 'Macaron Mangue Jasmin'},\n {value: 'Lahore Chai', text: 'Lahore Chai'},\n {value: 'Strawberry Cream Fruit Melange',\n text: 'Strawberry Cream Fruit Melange'},\n {value: 'Carnaval de Rio', text: 'Carnaval de Rio'},\n {value: 'Organic Yunnan Select Dao Ming (ZY-64)',\n text: 'Organic Yunnan Select Dao Ming (ZY-64)'},\n {value: 'Berry Blues', text: 'Berry Blues'},\n {value: 'Mate Vanilla Mint', text: 'Mate Vanilla Mint'},\n {value: 'Green Spring Thunder', text: 'Green Spring Thunder'},\n {value: 'Hao Ya B', text: 'Hao Ya B'},\n {value: 'Assam Mangalam FBOP', text: 'Assam Mangalam FBOP'},\n {value: 'Yixing Gong Fu Hong Cha', text: 'Yixing Gong Fu Hong Cha'},\n {value: 'Italian Almond', text: 'Italian Almond'},\n {value: 'Redberry Tonic', text: 'Redberry Tonic'},\n {value: 'Spiderweb Oolong', text: 'Spiderweb Oolong'},\n {value: 'Xiaos Blend', text: 'Xiaos Blend'},\n {value: 'sticky toffee pudding', text: 'sticky toffee pudding'},\n {value: 'Water Sprite Oolong Tea (Wuyi Shui Xian Wu Long)',\n text: 'Water Sprite Oolong Tea (Wuyi Shui Xian Wu Long)'},\n {value: 'Mandarin Silk', text: 'Mandarin Silk'},\n {value: 'No. 8 Mao Feng Shui', text: 'No. 8 Mao Feng Shui'},\n {value: 'Ceylon Waltz', text: 'Ceylon Waltz'},\n {value: 'Gyokuro Yame', text: 'Gyokuro Yame'},\n {value: 'Shu Enso Maiden', text: 'Shu Enso Maiden'},\n {value: 'Whisper of the Woods', text: 'Whisper of the Woods'},\n {value: 'Peach blossom white', text: 'Peach blossom white'},\n {value: 'Cherry Almond Gunpowder', text: 'Cherry Almond Gunpowder'},\n {value: 'Tokyo', text: 'Tokyo'},\n {value: '2006 Zang Zhuan Cha', text: '2006 Zang Zhuan Cha'},\n {value: 'Awake English Breakfast', text: 'Awake English Breakfast'},\n {value: 'White Guava', text: 'White Guava'},\n {value: 'Taiwan Hong Cha (Sanxia)', text: 'Taiwan Hong Cha (Sanxia)'},\n {value: 'Sunny Passion', text: 'Sunny Passion'},\n {value: 'Brecon Breakfast', text: 'Brecon Breakfast'},\n {value: 'Mini Green Tuocha Rice Scented',\n text: 'Mini Green Tuocha Rice Scented'},\n {value: 'Grønn Gresshoppe', text: 'Grønn Gresshoppe'},\n {value: 'Cold &amp; Allergy', text: 'Cold &amp; Allergy'},\n {value: 'Assam Smoked Oolong', text: 'Assam Smoked Oolong'},\n {value: 'Mecha', text: 'Mecha'},\n {value: 'Anxi Fo Shou Black Tea', text: 'Anxi Fo Shou Black Tea'},\n {value: '2010 Sheng Pure Series Ban Zhang Brick',\n text: '2010 Sheng Pure Series Ban Zhang Brick'},\n {value: 'Apple Tea', text: 'Apple Tea'},\n {value: 'Pettiagalla-O.P.', text: 'Pettiagalla-O.P.'},\n {value: 'Rooibos African Spice', text: 'Rooibos African Spice'},\n {value: 'Star of Bulang Sheng', text: 'Star of Bulang Sheng'},\n {value: 'Oriental Beauty Cake', text: 'Oriental Beauty Cake'},\n {value: 'Typhoo Decaf', text: 'Typhoo Decaf'},\n {value: '2011 Phoenix Ku Fu Cha', text: '2011 Phoenix Ku Fu Cha'},\n {value: 'One Bush Oolong (Wu Dong Dan Cong)',\n text: 'One Bush Oolong (Wu Dong Dan Cong)'},\n {value: 'Classic India Spice', text: 'Classic India Spice'},\n {value: 'Signature Blend for Collar City Teas',\n text: 'Signature Blend for Collar City Teas'},\n {value: 'Raspberry Green', text: 'Raspberry Green'},\n {value: 'Comforting Chamomile', text: 'Comforting Chamomile'},\n {value: 'Uji Sencha Kyoto', text: 'Uji Sencha Kyoto'},\n {value: 'Loose and Luscious Lincang -2007',\n text: 'Loose and Luscious Lincang -2007'},\n {value: 'Sencha Pear (organic)', text: 'Sencha Pear (organic)'},\n {value: 'Pirates Spice', text: 'Pirates Spice'},\n {value: 'Iron Goddess Caramel Roast - Anxi Oolong',\n text: 'Iron Goddess Caramel Roast - Anxi Oolong'},\n {value: 'Nahorhabi Broken-leaf Assam',\n text: 'Nahorhabi Broken-leaf Assam'},\n {value: 'Red Christmas', text: 'Red Christmas'},\n {value: 'Red Green Vanilla', text: 'Red Green Vanilla'},\n {value: 'Swiss Mountain', text: 'Swiss Mountain'},\n {value: 'Darjeeling Earl Grey Singbulli Estate',\n text: 'Darjeeling Earl Grey Singbulli Estate'},\n {value: 'Mango Kiwi', text: 'Mango Kiwi'},\n {value: 'Pearl Jasmine Tea', text: 'Pearl Jasmine Tea'},\n {value: 'Organic Gunpowder Supreme Green Tea',\n text: 'Organic Gunpowder Supreme Green Tea'},\n {value: 'River Market Breakfast', text: 'River Market Breakfast'},\n {value: 'Nepal Emerald Green', text: 'Nepal Emerald Green'},\n {value: 'Wild Berry Black', text: 'Wild Berry Black'},\n {value: 'Etoile de Ba Jiao', text: 'Etoile de Ba Jiao'},\n {value: 'Mate Lemongrass', text: 'Mate Lemongrass'},\n {value: 'うまい緑茶 (Umai Midoricha)', text: 'うまい緑茶 (Umai Midoricha)'},\n {value: 'African Orange Mango Red Tea',\n text: 'African Orange Mango Red Tea'},\n {value: 'Oriental Beauty / Don Fang Mei Ren Cha',\n text: 'Oriental Beauty / Don Fang Mei Ren Cha'},\n {value: 'Pinglin Bao Zhong 1983', text: 'Pinglin Bao Zhong 1983'},\n {value: 'Fertilitea', text: 'Fertilitea'},\n {value: 'Citron Mate', text: 'Citron Mate'},\n {value: 'Champagne Grade Oolong', text: 'Champagne Grade Oolong'},\n {value: 'Lychee Red Tea', text: 'Lychee Red Tea'},\n {value: 'Emerald Mao Feng', text: 'Emerald Mao Feng'},\n {value: 'Pumphreys Blend', text: 'Pumphreys Blend'},\n {value: 'Chá Preto S. Valentim', text: 'Chá Preto S. Valentim'},\n {value: 'TP42: China Rose Special Chun Mee',\n text: 'TP42: China Rose Special Chun Mee'},\n {value: 'Marrakesh Mint', text: 'Marrakesh Mint'},\n {value: 'Japanese Mu Tea', text: 'Japanese Mu Tea'},\n {value: 'Apricot Ceylon', text: 'Apricot Ceylon'},\n {value: 'Yuzu Temple', text: 'Yuzu Temple'},\n {value: 'Little Rose Puer Black Tuo Cha',\n text: 'Little Rose Puer Black Tuo Cha'},\n {value: 'Silver Dew', text: 'Silver Dew'},\n {value: 'Soderblandning', text: 'Soderblandning'},\n {value: 'Barrys Gold Blend (Loose Leaf)',\n text: 'Barrys Gold Blend (Loose Leaf)'},\n {value: 'Autumn Foxtrot', text: 'Autumn Foxtrot'},\n {value: 'Blackberry Sage Decaf', text: 'Blackberry Sage Decaf'},\n {value: 'White Ginger', text: 'White Ginger'},\n {value: 'Duflating Estate FBOP (TA80)',\n text: 'Duflating Estate FBOP (TA80)'},\n {value: 'Darjeeling FTGFOP 1st flush',\n text: 'Darjeeling FTGFOP 1st flush'},\n {value: 'Ginger Lime Rooibos', text: 'Ginger Lime Rooibos'},\n {value: 'Taj Masala Chai Black Tea', text: 'Taj Masala Chai Black Tea'},\n {value: 'Pouchong Oolong', text: 'Pouchong Oolong'},\n {value: 'Hugs and Kisses', text: 'Hugs and Kisses'},\n {value: 'Guayusa and Yerba Mate', text: 'Guayusa and Yerba Mate'},\n {value: '2011 Yunnan Sourcing Ai Lao Mountain Wild Arbor Pu-erh tea cake',\n text: '2011 Yunnan Sourcing Ai Lao Mountain Wild Arbor Pu-erh tea cake'},\n {value: 'Wills Ambrosia Tea', text: 'Wills Ambrosia Tea'},\n {value: 'Winken Blinken and Nod', text: 'Winken Blinken and Nod'},\n {value: 'Gu Zhang Mao Jian', text: 'Gu Zhang Mao Jian'},\n {value: 'Traktir', text: 'Traktir'},\n {value: 'Matejuana', text: 'Matejuana'},\n {value: 'Green Tea Kombucha', text: 'Green Tea Kombucha'},\n {value: 'Chai Redbush', text: 'Chai Redbush'},\n {value: 'Haute Chocolate', text: 'Haute Chocolate'},\n {value: 'Assam TGFOP No. 30', text: 'Assam TGFOP No. 30'},\n {value: 'Keisarin Helmi - Emperors Pearl',\n text: 'Keisarin Helmi - Emperors Pearl'},\n {value: 'Sikkim Temi Estate FTGFOP (TN64)',\n text: 'Sikkim Temi Estate FTGFOP (TN64)'},\n {value: 'Samurai Chai Mate &amp; White Ayurvedic Chai Blend',\n text: 'Samurai Chai Mate &amp; White Ayurvedic Chai Blend'},\n {value: 'African Antlers', text: 'African Antlers'},\n {value: 'Traditional Yerba Mate', text: 'Traditional Yerba Mate'},\n {value: 'Big Smoke', text: 'Big Smoke'},\n {value: 'Razzleberry', text: 'Razzleberry'},\n {value: 'Blueberry Cream Cheese Danish Black Tea',\n text: 'Blueberry Cream Cheese Danish Black Tea'},\n {value: 'Super Green Tea', text: 'Super Green Tea'},\n {value: 'Java', text: 'Java'},\n {value: 'Kenya Rhino Premium White Tea',\n text: 'Kenya Rhino Premium White Tea'},\n {value: 'Jasmine Yin Hao (9)', text: 'Jasmine Yin Hao (9)'},\n {value: 'Twig Tea', text: 'Twig Tea'},\n {value: 'Franks Apple Cider Rooibos', text: 'Franks Apple Cider Rooibos'},\n {value: '2007 Jin Si Gong Bing Cha - Yunnan Branch China Tea Import and Export Co. Ltd',\n text: '2007 Jin Si Gong Bing Cha'},\n {value: 'Mojito Raspberry Mint', text: 'Mojito Raspberry Mint'},\n {value: '2013 First Flush Namring Poomong Upper FTGFOP1',\n text: '2013 First Flush Namring Poomong Upper FTGFOP1'},\n {value: 'China Beauty Ring', text: 'China Beauty Ring'},\n {value: 'Winter Pu-erh', text: 'Winter Pu-erh'},\n {value: 'Bengal Spice', text: 'Bengal Spice'},\n {value: 'unkown cliff tea', text: 'unkown cliff tea'},\n {value: 'Medium Roast Dong Ding Special Reserve',\n text: 'Medium Roast Dong Ding Special Reserve'},\n {value: 'Red Rooibos Organic', text: 'Red Rooibos Organic'},\n {value: 'Miriams Apple Honey Flavored Black',\n text: 'Miriams Apple Honey Flavored Black'},\n {value: 'Ginger Lemongrass', text: 'Ginger Lemongrass'},\n {value: 'Lavender Zen', text: 'Lavender Zen'},\n {value: 'Ceylon Black Tea Raspberry', text: 'Ceylon Black Tea Raspberry'},\n {value: 'Mélange de Kashmir', text: 'Mélange de Kashmir'},\n {value: 'Cinnamon Fig Rooibos', text: 'Cinnamon Fig Rooibos'},\n {value: 'Black Ikumi (TJ75)', text: 'Black Ikumi (TJ75)'},\n {value: 'White Tip Earl Grey (825)', text: 'White Tip Earl Grey (825)'},\n {value: 'Oh Ba Sang', text: 'Oh Ba Sang'},\n {value: 'Earl Grey (full leaf sachet)',\n text: 'Earl Grey (full leaf sachet)'},\n {value: 'Standard', text: 'Standard'},\n {value: 'Mayan Cocoa Spice', text: 'Mayan Cocoa Spice'},\n {value: 'White Tea (Original)', text: 'White Tea (Original)'},\n {value: 'Organic Raspberry Leaf', text: 'Organic Raspberry Leaf'},\n {value: 'Organic Breakfast Blend Black',\n text: 'Organic Breakfast Blend Black'},\n {value: 'Pear Sencha Green Tea', text: 'Pear Sencha Green Tea'},\n {value: 'Pan Asia', text: 'Pan Asia'},\n {value: 'satemwa', text: 'satemwa'},\n {value: 'Huang Shan Mao Feng Green Tea',\n text: 'Huang Shan Mao Feng Green Tea'},\n {value: 'Green Sense Aromatherapy - Green &amp; Aloe Vera',\n text: 'Green Sense Aromatherapy - Green &amp; Aloe Vera'},\n {value: 'Aquarius (The Zodiac Series)',\n text: 'Aquarius (The Zodiac Series)'},\n {value: 'Hvit Te', text: 'Hvit Te'},\n {value: 'East Frisian Leaf Blend Tea',\n text: 'East Frisian Leaf Blend Tea'},\n {value: 'Spicy Chocolate Rooibos', text: 'Spicy Chocolate Rooibos'},\n {value: 'Sencha Superieur', text: 'Sencha Superieur'},\n {value: 'Formosa Mandarin Oolong', text: 'Formosa Mandarin Oolong'},\n {value: 'Denong Pu-erh Brick (2006 vintage - autumn harvest)',\n text: 'Denong Pu-erh Brick (2006 vintage - autumn harvest)'},\n {value: 'Super Ginger (organic)', text: 'Super Ginger (organic)'},\n {value: 'Ryokucha Earl Grey', text: 'Ryokucha Earl Grey'},\n {value: '2012 spring-mt-wudong-imperial-bai-ye-dancong-black-tea',\n text: '2012 spring-mt-wudong-imperial-bai-ye-dancong-black-tea'},\n {value: 'Healthy Fasting', text: 'Healthy Fasting'},\n {value: 'Chai Spice Tea - TE33 / Blend No. 443',\n text: 'Chai Spice Tea - TE33 / Blend No. 443'},\n {value: 'Island Breeze', text: 'Island Breeze'},\n {value: 'Osmanthus Green', text: 'Osmanthus Green'},\n {value: 'Vanilla Jasmine', text: 'Vanilla Jasmine'},\n {value: 'Hong Tao Keemun (ZK12)', text: 'Hong Tao Keemun (ZK12)'},\n {value: 'A Caramel Buttercream Tea', text: 'A Caramel Buttercream Tea'},\n {value: 'Green Tea by Price Chopper', text: 'Green Tea by Price Chopper'},\n {value: 'Classic Laoshan Black', text: 'Classic Laoshan Black'},\n {value: 'Pi Lo Chun Imperial', text: 'Pi Lo Chun Imperial'},\n {value: 'Breathe Easy', text: 'Breathe Easy'}]\n" }, { "alpha_fraction": 0.5371997952461243, "alphanum_fraction": 0.5371997952461243, "avg_line_length": 35.319149017333984, "blob_id": "773ebb07316f86501ff3ae50ecd45943b2764149", "content_id": "0f5589ad5cb2e4f080063bdc8f6039b38620aed2", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1707, "license_type": "permissive", "max_line_length": 49, "num_lines": 47, "path": "/Talking Data/Flask/static/drop_down.js", "repo_name": "djmor12/Metis", "src_encoding": "UTF-8", "text": "var drop_down = [\n {value: 'Huawei', text: 'Huawei'},\n {value: 'OPPO', text: 'OPPO'},\n {value: 'xiaomi', text: 'xiaomi'},\n {value: 'vivo', text: 'vivo'},\n {value: 'meizu', text: 'meizu'},\n {value: 'samsung', text: 'samsung'},\n {value: 'HTC', text: 'HTC'},\n {value: 'lshi', text: 'lshi'},\n {value: 'kupai', text: 'kupai'},\n {value: 'oneplus', text: 'oneplus'},\n {value: 'yuxin', text: 'yuxin'},\n {value: 'nubia', text: 'nubia'},\n {value: 'meitu', text: 'meitu'},\n {value: 'zhongxing', text: 'zhongxing'},\n {value: 'jinli', text: 'jinli'},\n {value: 'koobee', text: 'koobee'},\n {value: 'ccmc', text: 'ccmc'},\n {value: 'hisense', text: 'hisense'},\n {value: 'Sony', text: 'Sony'},\n {value: 'lenovo', text: 'lenovo'},\n {value: 'dowe', text: 'dowe'},\n {value: 'Cool', text: 'Cool'},\n {value: 'LG', text: 'LG'},\n {value: 'nibilu', text: 'nibilu'},\n {value: 'hammer', text: 'hammer'},\n {value: 'moto', text: 'moto'},\n {value: 'Bailifeng', text: 'Bailifeng'},\n {value: 'TCL', text: 'TCL'},\n {value: 'QingCong', text: 'QingCong'},\n {value: 'Konka', text: 'Konka'},\n {value: 'ZUK', text: 'ZUK'},\n {value: 'Yitong', text: 'Yitong'},\n {value: 'newman', text: 'newman'},\n {value: 'micky', text: 'micky'},\n {value: 'Ktouch', text: 'Ktouch'},\n {value: 'nokia', text: 'nokia'},\n {value: 'Belfon', text: 'Belfon'},\n {value: 'fks', text: 'fks'},\n {value: 'Baimi', text: 'Baimi'},\n {value: 'aiyouni', text: 'aiyouni'},\n {value: 'bigcola', text: 'bigcola'},\n {value: 'Feixun', text: 'Feixun'},\n {value: 'asus', text: 'asus'},\n {value: 'yougo', text: 'yougo'},\n {value: 'Top Treasure', text: 'Top Treasure'},\n {value: 'wpf', text: 'wpf'}]\n" }, { "alpha_fraction": 0.3130990266799927, "alphanum_fraction": 0.5015974640846252, "avg_line_length": 27.454545974731445, "blob_id": "6bb9abb8ce0a3458cf2d0c8072775af7b3a5c1eb", "content_id": "b17e2f680e76767a5be9006833f3b7baab1312f2", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 313, "license_type": "permissive", "max_line_length": 30, "num_lines": 11, "path": "/TeaRecommendations/Flask/static/scoring.js", "repo_name": "djmor12/Metis", "src_encoding": "UTF-8", "text": "var score = [\n {value: 5, text: '0-10'},\n {value: 15, text: '10-20'},\n {value: 25, text: '20-30'},\n {value: 35, text: '30-40'},\n {value: 45, text: '40-50'},\n {value: 55, text: '50-60'},\n {value: 65, text: '60-70'},\n {value: 75, text: '70-80'},\n {value: 85, text: '80-90'},\n {value: 95, text: '90-100'}]\n" }, { "alpha_fraction": 0.6648745536804199, "alphanum_fraction": 0.6730205416679382, "avg_line_length": 41.03424835205078, "blob_id": "4365475fecbf06522b0b417bade7c040f0145b14", "content_id": "7a08d73331e4a2f6491b4c932fd22fcef87cc86f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6138, "license_type": "permissive", "max_line_length": 220, "num_lines": 146, "path": "/TeaRecommendations/Flask/cat.py", "repo_name": "djmor12/Metis", "src_encoding": "UTF-8", "text": "\nimport pandas as pd\nimport gensim\nimport os\nimport collections\nimport smart_open\nimport flask\nfrom flask import Flask\nimport pickle\nfrom surprise import SVDpp,SVD\nfrom surprise import Dataset\nfrom surprise import Reader\nimport nltk\nimport re\nfrom sklearn.metrics.pairwise import euclidean_distances\napp = Flask(__name__)\n#pulling in dataset, item list\nwith open('/Users/deven/Documents/pickleddata/projectfletcher/newdatalist.pkl', 'rb') as picklefile:\n itemdf = pickle.load(picklefile)\nwith open('/Users/deven/Documents/GitHub/Metis/ProjectFletcher/surprise_data.pkl', 'rb') as picklefile:\n newdf = pickle.load(picklefile)\nwith open('/Users/deven/Documents/pickleddata/projectfletcher/btrain.pkl', 'rb') as picklefile:\n btrain = pickle.load(picklefile)\nwith open('/Users/deven/Documents/GitHub/Metis/ProjectFletcher/doclen.pkl', 'rb') as picklefile:\n doclen = pickle.load(picklefile)\n#changing some tea names for easier calls\nitemdf = pd.DataFrame(itemdf)\nnewname=[]\n\nfor i in itemdf['Tea Name']:\n line = re.sub('[!@#$\\'\\\",]', '', i)\n newname.append(line)\nitemdf['Tea Name'] = newname\nalist= []\nfor i in itemdf['Flavor Profile Reviews']:\n alist.append(i)\nteadf = pd.DataFrame(alist)\n#initializing book list\nbookt = ['Emma by Jane Austen', 'Persuassion by Jane Austen', 'Sense and Sensibility by Jane Austen',\\\n 'Poems by William Blake', 'The Little People of the Snow by William Bryant', 'The Adventures of Buster Bear by Thornton Burgress'\\\n 'Alice in Wonderland by Lewis Carroll','The Ball and the Cross by G.K. Chesterton','The Wisdom of Father Brown by G.K. Chesterton'\\\n 'The Ball and the Cross by G.K. Chesterton', 'The Parents Assistant by Maria Edgeworth','Moby Dick by Herman Melville',\\\n 'Paradise Lost by John Milton', 'Shakespeares Works','Shakespeares Works','Shakespeares Works', 'Leaves of Grass by Walt Whitman']\n\nimagelocs = {'Emma by Jane Austen':'static/emma.jpg','Persuassion by Jane Austen':'static/persuassion.jpg','Sense and Sensibility by Jane Austen':'static/sense.jpg',\\\n'Poems by William Blake':'static/blake.jpg','The Little People of the Snow by William Bryant':'static/bryant.jpg','The Adventures of Buster Bear by Thornton Burgress':'static/the-adventures-of-buster-bear.jpg',\\\n'The Adventures of Buster Bear by Thornton BurgressAlice in Wonderland by Lewis Carroll':'static/alice.jpg', 'The Ball and the Cross by G.K. Chesterton':'static/ball.jpg','The Wisdom of Father Brown by G.K. Chesterton':'static/fatherbrown.jpg',\\\n'The Parents Assistant by Maria Edgeworth':'static/edge.jpg','Moby Dick by Herman Melville':'static/moby.jpg','Paradise Lost by John Milton':'static/paradise.jpg',\\\n'Shakespeares Works':'static/shake.jpg','Shakespeares Works':'static/shake.jpg','Shakespeares Works':'static/shake.jpg','Leaves of Grass by Walt Whitman':'static/leaves.jpg'}\n#Call function for top ratings\nfrom collections import defaultdict\ndef get_top_n(teaid,score,qq, n=10):\n # A reader is still needed but only the rating_scale param is requiered.\n qq = pd.concat([qq,pd.DataFrame([[score,teaid, 'user1']], columns = ['Score', 'Tea Name', 'User Name'])], ignore_index=True)\n reader = Reader(rating_scale=(0, 100))\n algo=SVD()\n # The columns must correspond to user id, item id and ratings (in that order).\n data = Dataset.load_from_df(qq[['User Name', 'Tea Name', 'Score']], reader)\n trainset = data.build_full_trainset()\n algo.fit(trainset)\n\n testset = trainset.build_anti_testset()\n predictions = algo.test(testset)\n\n\n '''Return the top-N recommendation for each user from a set of predictions.\n\n Args:\n predictions(list of Prediction objects): The list of predictions, as\n returned by the test method of an algorithm.\n n(int): The number of recommendation to output for each user. Default\n is 10.\n\n Returns:\n A dict where keys are user (raw) ids and values are lists of tuples:\n [(raw item id, rating estimation), ...] of size n.\n '''\n want= []\n for i in predictions:\n if i[0]== 'user1':\n want.append(i)\n # First map the predictions to each user.\n top_n = defaultdict(list)\n for uid, iid, true_r, est, _ in want:\n top_n[uid].append((iid, est))\n\n # Then sort the predictions for each user and retrieve the k highest ones.\n for uid, user_ratings in top_n.items():\n user_ratings.sort(key=lambda x: x[1], reverse=True)\n top_n[uid] = user_ratings[:10]\n teadist = []\n mindist = []\n eudist=0\n\n for i in top_n['user1']:\n eudis=(euclidean_distances(teadf.iloc[itemdf[itemdf['Tea Name']==teaid].index,:], \\\n teadf.iloc[(itemdf[itemdf['Tea Name']==i[0]].index),:]))\n teadist.append((i[0],eudist))\n mindist = sorted(teadist, key=lambda x:x[1])\n return mindist[0],mindist[1],mindist[2]\n\n\n\ndef getBookrec(iid):\n bookrec = gensim.models.doc2vec.Doc2Vec.load('/Users/deven/Documents/pickleddata/projectfletcher/bookrec.bin')\n test_corpus = itemdf[itemdf['Tea Name']==iid]['Review Adj'].values[0]\n inferred_vector = bookrec.infer_vector(test_corpus)\n sims = bookrec.docvecs.most_similar([inferred_vector])\n rec=''\n tot=0\n for ind, i in enumerate(doclen):\n tot+=i\n if sims[0][0]<tot:\n rec = bookt[ind-1]\n break\n return rec\[email protected](\"/\")\ndef viz_page():\n \"\"\"\n Homepage: serve our visualization page\n \"\"\"\n with open(\"index.html\", 'r') as viz_file:\n return viz_file.read()\n\[email protected](\"/score\", methods=[\"POST\"])\ndef score():\n \"\"\"\n When A POST request with json data is made to this uri,\n Read the example from the json, predict probability and\n send it with a response\n \"\"\"\n # Get decision score for our example that came with the request\n data = flask.request.json\n x = data[\"example\"]\n rec1,rec2,rec3 = get_top_n(x[0],x[2], newdf)\n bookrec= getBookrec(x[0])\n imgrec = imagelocs[bookrec]\n # Put the result in a nice dict so we can send it as json\n results = {\"tearec1\":rec1[0],\"tearec2\":rec2[0],\"tearec3\":rec3[0],\"bookrec\":bookrec, 'img':imgrec}\n return flask.jsonify(results)\n\n#--------- RUN WEB APP SERVER ------------#\n\n# Start the app server on port 80\n# (The default website port)\n#app.run(host='0.0.0.0')\n# app.run(debug=True)\n" }, { "alpha_fraction": 0.6944444179534912, "alphanum_fraction": 0.8055555820465088, "avg_line_length": 17, "blob_id": "9693b8ab98f9cf527d0459a94130521dcc577fe0", "content_id": "effd2fae30500b1615c2e2cb3879c47c1e2c28b7", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 36, "license_type": "permissive", "max_line_length": 27, "num_lines": 2, "path": "/README.md", "repo_name": "djmor12/Metis", "src_encoding": "UTF-8", "text": "# Metis\nMetis Projects Seattle 2018\n" } ]
7
sergeyprokudin/IGR
https://github.com/sergeyprokudin/IGR
dca2597e95de219e3b2a88a1c45f1b7248dbac3b
cf877ef8e930b2069c9a99846cf1f36ef355868a
d8242db9c9acc36b53d4ecea8f8034ee61784796
refs/heads/master
2023-04-07T23:29:05.925583
2023-03-28T12:50:27
2023-03-28T12:50:27
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5663247108459473, "alphanum_fraction": 0.5753448605537415, "avg_line_length": 29.0744686126709, "blob_id": "39fb04613d299e9ad4f023e949dc75103e69c73c", "content_id": "7bbeacaf543af7c2bc8a9b02add8c7e78267424d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5654, "license_type": "no_license", "max_line_length": 173, "num_lines": 188, "path": "/code/shapespace/interpolate.py", "repo_name": "sergeyprokudin/IGR", "src_encoding": "UTF-8", "text": "import os\nimport sys\nproject_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))\nsys.path.append(project_dir)\nos.chdir(project_dir)\nimport argparse\nimport json\nimport utils.general as utils\nimport torch\nimport numpy as np\nimport utils.plots as plt\nfrom pyhocon import ConfigFactory\nfrom shapespace.latent_optimizer import optimize_latent\n\n\ndef interpolate(network, interval, experiment_directory, checkpoint, split_file, epoch, resolution, uniform_grid):\n\n with open(split_file, \"r\") as f:\n split = json.load(f)\n\n ds = utils.get_class(conf.get_string('train.dataset'))(split=split, dataset_path=conf.get_string('train.dataset_path'), with_normals=True)\n\n points_1, normals_1, index_1 = ds[0]\n points_2, normals_2, index_2 = ds[1]\n\n pnts = torch.cat([points_1, points_2], dim=0).cuda()\n\n name_1 = str.join('_', ds.get_info(0))\n name_2 = str.join('_', ds.get_info(0))\n\n name = name_1 + '_and_' + name_2\n\n utils.mkdir_ifnotexists(os.path.join(experiment_directory, 'interpolate'))\n utils.mkdir_ifnotexists(os.path.join(experiment_directory, 'interpolate', str(checkpoint)))\n utils.mkdir_ifnotexists(os.path.join(experiment_directory, 'interpolate', str(checkpoint), name))\n\n my_path = os.path.join(experiment_directory, 'interpolate', str(checkpoint), name)\n\n latent_1 = optimize_latent(points_1.cuda(), normals_1.cuda(), conf, 800, network, 5e-3)\n latent_2 = optimize_latent(points_2.cuda(), normals_2.cuda(), conf, 800, network, 5e-3)\n\n pnts = torch.cat([latent_1.repeat(pnts.shape[0], 1), pnts], dim=-1)\n\n with torch.no_grad():\n network.eval()\n\n for alpha in np.linspace(0,1, interval):\n\n latent = (latent_1 * (1-alpha)) + (latent_2 * alpha)\n\n plt.plot_surface(with_points=False,\n points=pnts,\n decoder=network,\n latent=latent,\n path=my_path,\n epoch=epoch,\n shapename=str(alpha),\n resolution=resolution,\n mc_value=0,\n is_uniform_grid=uniform_grid,\n verbose=True,\n save_html=False,\n save_ply=True,\n overwrite=True,\n connected=True)\n\n\nif __name__ == '__main__':\n\n arg_parser = argparse.ArgumentParser()\n\n arg_parser.add_argument(\n \"--interval\",\n \"-i\",\n dest=\"interval\",\n default=3\n )\n\n arg_parser.add_argument(\n \"--gpu\",\n \"-g\",\n dest=\"gpu_num\",\n required=False,\n default='5'\n )\n\n arg_parser.add_argument(\n \"--timestamp\",\n \"-t\",\n dest=\"timestamp\",\n default='latest',\n required=False,\n )\n\n arg_parser.add_argument(\n \"--conf\",\n \"-f\",\n dest=\"conf\",\n default='dfaust_setup.conf',\n required=False,\n )\n\n arg_parser.add_argument(\n \"--split\",\n \"-s\",\n dest=\"split\",\n default='dfaust/interpolate.json',\n required=False,\n )\n\n arg_parser.add_argument(\n \"--exp-name\",\n \"-e\",\n dest=\"exp_name\",\n required=True,\n help=\"experiment name\",\n )\n\n arg_parser.add_argument(\n \"--exps-dir\",\n dest=\"exps_dir\",\n required=False,\n default='exps'\n )\n\n arg_parser.add_argument(\n \"--checkpoint\",\n \"-c\",\n dest=\"epoch\",\n default='latest',\n help=\"The checkpoint to test.\",\n )\n\n arg_parser.add_argument(\n \"--resolution\",\n \"-r\",\n dest=\"resolution\",\n help='resolution of marching cube grid',\n default=512\n )\n\n arg_parser.add_argument(\n \"--uniform-grid\",\n \"-u\",\n dest=\"uniform_grid\",\n help='use uniform grid in marching cube or non uniform',\n default=False\n )\n\n cur_dir = os.path.abspath('dfaust')\n\n args = arg_parser.parse_args()\n\n code_path = os.path.abspath(os.path.curdir)\n exps_path = os.path.join(os.path.abspath(os.path.pardir), args.exps_dir)\n\n if args.gpu_num != 'ignore':\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = '{0}'.format(args.gpu_num)\n\n conf = ConfigFactory.parse_file(os.path.join(code_path, 'shapespace', args.conf))\n\n experiment_directory = os.path.join(exps_path, args.exp_name)\n\n if args.timestamp == 'latest':\n timestamps = os.listdir(experiment_directory)\n timestamp = sorted(timestamps)[-1]\n else:\n timestamp = args.timestamp\n\n experiment_directory = os.path.join(experiment_directory, timestamp)\n saved_model_state = torch.load(os.path.join(experiment_directory, 'checkpoints', 'ModelParameters', args.epoch + \".pth\"))\n saved_model_epoch = saved_model_state[\"epoch\"]\n with_normals = conf.get_float('network.loss.normals_lambda') > 0\n network = utils.get_class(conf.get_string('train.network_class'))(d_in=conf.get_int('train.latent_size')+conf.get_int('train.d_in'), **conf.get_config('network.inputs'))\n\n network.load_state_dict({k.replace('module.', ''): v for k, v in saved_model_state[\"model_state_dict\"].items()})\n split_file = os.path.join(code_path, 'splits', args.split)\n\n interpolate(\n network=network.cuda(),\n interval=args.interval,\n experiment_directory=experiment_directory,\n checkpoint=saved_model_epoch,\n split_file=split_file,\n epoch=saved_model_epoch,\n resolution=args.resolution,\n uniform_grid=args.uniform_grid\n )\n" }, { "alpha_fraction": 0.5487743020057678, "alphanum_fraction": 0.5525650978088379, "avg_line_length": 38.56999969482422, "blob_id": "e8de034406a3f46dd8eac2064466dc77d314f335", "content_id": "3f6a21c7e148bdaa1ec1bf5acfee1e74c60941bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15828, "license_type": "no_license", "max_line_length": 160, "num_lines": 400, "path": "/code/shapespace/train.py", "repo_name": "sergeyprokudin/IGR", "src_encoding": "UTF-8", "text": "import os\nimport sys\nproject_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))\nsys.path.append(project_dir)\nos.chdir(project_dir)\nfrom datetime import datetime\nfrom pyhocon import ConfigFactory\nfrom time import time\nimport argparse\nimport json\nimport torch\nimport utils.general as utils\nfrom model.sample import Sampler\nfrom model.network import gradient\nfrom utils.plots import plot_surface, plot_cuts\n\n\nclass ShapeSpaceRunner:\n\n def run(self):\n\n print(\"running\")\n\n for epoch in range(self.startepoch, self.nepochs + 1):\n\n if epoch % self.conf.get_int('train.checkpoint_frequency') == 0:\n self.save_checkpoints(epoch)\n self.plot_validation_shapes(epoch)\n\n # change back to train mode\n self.network.train()\n self.adjust_learning_rate(epoch)\n\n # start epoch\n before_epoch = time()\n for data_index,(mnfld_pnts, normals, indices) in enumerate(self.train_dataloader):\n\n mnfld_pnts = mnfld_pnts.cuda()\n\n if self.with_normals:\n normals = normals.cuda()\n\n nonmnfld_pnts = self.sampler.get_points(mnfld_pnts)\n\n mnfld_pnts = self.add_latent(mnfld_pnts, indices)\n nonmnfld_pnts = self.add_latent(nonmnfld_pnts, indices)\n\n # forward pass\n\n mnfld_pnts.requires_grad_()\n nonmnfld_pnts.requires_grad_()\n\n mnfld_pred = self.network(mnfld_pnts)\n nonmnfld_pred = self.network(nonmnfld_pnts)\n\n mnfld_grad = gradient(mnfld_pnts, mnfld_pred)\n nonmnfld_grad = gradient(nonmnfld_pnts, nonmnfld_pred)\n\n # manifold loss\n\n mnfld_loss = (mnfld_pred.abs()).mean()\n\n # eikonal loss\n\n grad_loss = ((nonmnfld_grad.norm(2, dim=-1) - 1) ** 2).mean()\n\n loss = mnfld_loss + self.grad_lambda * grad_loss\n\n # normals loss\n if self.with_normals:\n normals = normals.view(-1, 3)\n normals_loss = ((mnfld_grad - normals).abs()).norm(2, dim=1).mean()\n loss = loss + self.normals_lambda * normals_loss\n else:\n normals_loss = torch.zeros(1)\n\n # latent loss\n\n latent_loss = self.latent_size_reg(indices.cuda())\n\n loss = loss + self.latent_lambda * latent_loss\n\n # back propagation\n\n self.optimizer.zero_grad()\n\n loss.backward()\n\n self.optimizer.step()\n\n # print status\n if data_index % self.conf.get_int('train.status_frequency') == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tTrain Loss: {:.6f}\\tManifold loss: {:.6f}'\n '\\tGrad loss: {:.6f}\\tLatent loss: {:.6f}\\tNormals Loss: {:.6f}'.format(\n epoch, data_index * self.batch_size, len(self.ds), 100. * data_index / len(self.train_dataloader),\n loss.item(), mnfld_loss.item(), grad_loss.item(), latent_loss.item(), normals_loss.item()))\n\n after_epoch = time()\n print('epoch time {0}'.format(str(after_epoch-before_epoch)))\n\n def plot_validation_shapes(self, epoch, with_cuts=False):\n # plot network validation shapes\n with torch.no_grad():\n\n print('plot validation epoch: ', epoch)\n\n self.network.eval()\n pnts, normals, idx = next(iter(self.eval_dataloader))\n pnts = utils.to_cuda(pnts)\n\n pnts = self.add_latent(pnts, idx)\n latent = self.lat_vecs[idx[0]]\n\n shapename = str.join('_', self.ds.get_info(idx))\n\n plot_surface(with_points=True,\n points=pnts,\n decoder=self.network,\n latent=latent,\n path=self.plots_dir,\n epoch=epoch,\n shapename=shapename,\n **self.conf.get_config('plot'))\n\n if with_cuts:\n plot_cuts(points=pnts,\n decoder=self.network,\n latent=latent,\n path=self.plots_dir,\n epoch=epoch,\n near_zero=False)\n\n def __init__(self,**kwargs):\n\n # config setting\n\n self.home_dir = os.path.abspath(os.pardir)\n\n if type(kwargs['conf']) == str:\n self.conf_filename = './shapespace/' + kwargs['conf']\n self.conf = ConfigFactory.parse_file(self.conf_filename)\n else:\n self.conf = kwargs['conf']\n\n self.expname = kwargs['expname']\n\n # GPU settings\n\n self.GPU_INDEX = kwargs['gpu_index']\n\n if not self.GPU_INDEX == 'ignore':\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = '{0}'.format(self.GPU_INDEX)\n\n self.num_of_gpus = torch.cuda.device_count()\n\n # settings for loading an existing experiment\n\n if kwargs['is_continue'] and kwargs['timestamp'] == 'latest':\n if os.path.exists(os.path.join(self.home_dir, 'exps', self.expname)):\n timestamps = os.listdir(os.path.join(self.home_dir, 'exps', self.expname))\n if (len(timestamps)) == 0:\n is_continue = False\n timestamp = None\n else:\n timestamp = sorted(timestamps)[-1]\n is_continue = True\n else:\n is_continue = False\n timestamp = None\n else:\n timestamp = kwargs['timestamp']\n is_continue = kwargs['is_continue']\n\n self.exps_folder_name = 'exps'\n\n utils.mkdir_ifnotexists(utils.concat_home_dir(os.path.join(self.home_dir, self.exps_folder_name)))\n\n self.expdir = utils.concat_home_dir(os.path.join(self.home_dir, self.exps_folder_name, self.expname))\n utils.mkdir_ifnotexists(self.expdir)\n\n if is_continue:\n self.timestamp = timestamp\n else:\n self.timestamp = '{:%Y_%m_%d_%H_%M_%S}'.format(datetime.now())\n\n self.cur_exp_dir = self.timestamp\n utils.mkdir_ifnotexists(os.path.join(self.expdir, self.cur_exp_dir))\n\n self.plots_dir = os.path.join(self.expdir, self.cur_exp_dir, 'plots')\n utils.mkdir_ifnotexists(self.plots_dir)\n\n self.checkpoints_path = os.path.join(self.expdir, self.cur_exp_dir, 'checkpoints')\n utils.mkdir_ifnotexists(self.checkpoints_path)\n\n self.checkpoints_path = os.path.join(self.expdir, self.cur_exp_dir, 'checkpoints')\n utils.mkdir_ifnotexists(self.checkpoints_path)\n\n self.model_params_subdir = \"ModelParameters\"\n self.optimizer_params_subdir = \"OptimizerParameters\"\n self.latent_codes_subdir = \"LatentCodes\"\n\n utils.mkdir_ifnotexists(os.path.join(self.checkpoints_path,self.model_params_subdir))\n utils.mkdir_ifnotexists(os.path.join(self.checkpoints_path, self.optimizer_params_subdir))\n utils.mkdir_ifnotexists(os.path.join(self.checkpoints_path, self.latent_codes_subdir))\n\n self.nepochs = kwargs['nepochs']\n\n self.batch_size = kwargs['batch_size']\n\n if self.num_of_gpus > 0:\n self.batch_size *= self.num_of_gpus\n\n self.parallel = self.num_of_gpus > 1\n\n self.global_sigma = self.conf.get_float('network.sampler.properties.global_sigma')\n self.local_sigma = self.conf.get_float('network.sampler.properties.local_sigma')\n self.sampler = Sampler.get_sampler(self.conf.get_string('network.sampler.sampler_type'))(self.global_sigma, self.local_sigma)\n\n train_split_file = './splits/{0}'.format(kwargs['split_file'])\n\n with open(train_split_file, \"r\") as f:\n train_split = json.load(f)\n\n self.d_in = self.conf.get_int('train.d_in')\n\n # latent preprocessing\n\n self.latent_size = self.conf.get_int('train.latent_size')\n\n self.latent_lambda = self.conf.get_float('network.loss.latent_lambda')\n self.grad_lambda = self.conf.get_float('network.loss.lambda')\n self.normals_lambda = self.conf.get_float('network.loss.normals_lambda')\n\n self.with_normals = self.normals_lambda > 0\n\n self.ds = utils.get_class(self.conf.get_string('train.dataset'))(split=train_split,\n with_normals=self.with_normals,\n dataset_path=self.conf.get_string(\n 'train.dataset_path'),\n points_batch=kwargs['points_batch'],\n )\n\n self.num_scenes = len(self.ds)\n\n self.train_dataloader = torch.utils.data.DataLoader(self.ds,\n batch_size=self.batch_size,\n shuffle=True,\n num_workers=kwargs['threads'], drop_last=True, pin_memory=True)\n self.eval_dataloader = torch.utils.data.DataLoader(self.ds,\n batch_size=1,\n shuffle=True,\n num_workers=0, drop_last=True)\n\n self.network = utils.get_class(self.conf.get_string('train.network_class'))(d_in=(self.d_in+self.latent_size), **self.conf.get_config('network.inputs'))\n\n if self.parallel:\n self.network = torch.nn.DataParallel(self.network)\n\n if torch.cuda.is_available():\n self.network.cuda()\n\n self.lr_schedules = self.get_learning_rate_schedules(self.conf.get_list('train.learning_rate_schedule'))\n self.weight_decay = self.conf.get_float('train.weight_decay')\n\n # optimizer and latent settings\n\n self.startepoch = 0\n\n self.lat_vecs = torch.zeros(self.num_scenes, self.latent_size).cuda()\n self.lat_vecs.requires_grad_()\n\n self.optimizer = torch.optim.Adam(\n [\n {\n \"params\": self.network.parameters(),\n \"lr\": self.lr_schedules[0].get_learning_rate(0),\n \"weight_decay\": self.weight_decay\n },\n {\n \"params\": self.lat_vecs,\n \"lr\": self.lr_schedules[1].get_learning_rate(0)\n },\n ])\n\n # if continue load checkpoints\n\n if is_continue:\n old_checkpnts_dir = os.path.join(self.expdir, timestamp, 'checkpoints')\n\n data = torch.load(os.path.join(old_checkpnts_dir, self.latent_codes_subdir, str(kwargs['checkpoint']) + '.pth'))\n self.lat_vecs = data[\"latent_codes\"].cuda()\n\n saved_model_state = torch.load(os.path.join(old_checkpnts_dir, 'ModelParameters', str(kwargs['checkpoint']) + \".pth\"))\n self.network.load_state_dict(saved_model_state[\"model_state_dict\"])\n\n data = torch.load(os.path.join(old_checkpnts_dir, 'OptimizerParameters', str(kwargs['checkpoint']) + \".pth\"))\n self.optimizer.load_state_dict(data[\"optimizer_state_dict\"])\n self.startepoch = saved_model_state['epoch']\n\n def latent_size_reg(self, indices):\n latents = torch.index_select(self.lat_vecs, 0, indices)\n latent_loss = latents.norm(dim=1).mean()\n return latent_loss\n\n def get_learning_rate_schedules(self,schedule_specs):\n\n schedules = []\n\n for schedule_specs in schedule_specs:\n\n if schedule_specs[\"Type\"] == \"Step\":\n schedules.append(\n utils.StepLearningRateSchedule(\n schedule_specs[\"Initial\"],\n schedule_specs[\"Interval\"],\n schedule_specs[\"Factor\"],\n )\n )\n\n else:\n raise Exception(\n 'no known learning rate schedule of type \"{}\"'.format(\n schedule_specs[\"Type\"]\n )\n )\n\n return schedules\n\n def add_latent(self, points, indices):\n batch_size, num_of_points, dim = points.shape\n points = points.reshape(batch_size * num_of_points, dim)\n latent_inputs = torch.zeros(0).cuda()\n\n for ind in indices.numpy():\n latent_ind = self.lat_vecs[ind]\n latent_repeat = latent_ind.expand(num_of_points, -1)\n latent_inputs = torch.cat([latent_inputs, latent_repeat], 0)\n points = torch.cat([latent_inputs, points], 1)\n return points\n\n def adjust_learning_rate(self, epoch):\n for i, param_group in enumerate(self.optimizer.param_groups):\n param_group[\"lr\"] = self.lr_schedules[i].get_learning_rate(epoch)\n\n def save_checkpoints(self,epoch):\n\n torch.save(\n {\"epoch\": epoch, \"model_state_dict\": self.network.state_dict()},\n os.path.join(self.checkpoints_path, self.model_params_subdir, str(epoch) + \".pth\"))\n torch.save(\n {\"epoch\": epoch, \"model_state_dict\": self.network.state_dict()},\n os.path.join(self.checkpoints_path, self.model_params_subdir, \"latest.pth\"))\n\n torch.save(\n {\"epoch\": epoch, \"optimizer_state_dict\": self.optimizer.state_dict()},\n os.path.join(self.checkpoints_path, self.optimizer_params_subdir, str(epoch) + \".pth\"))\n torch.save(\n {\"epoch\": epoch, \"optimizer_state_dict\": self.optimizer.state_dict()},\n os.path.join(self.checkpoints_path, self.optimizer_params_subdir, \"latest.pth\"))\n\n torch.save(\n {\"epoch\": epoch, \"latent_codes\": self.lat_vecs},\n os.path.join(self.checkpoints_path, self.latent_codes_subdir, str(epoch) + \".pth\"))\n torch.save(\n {\"epoch\": epoch, \"latent_codes\": self.lat_vecs},\n os.path.join(self.checkpoints_path, self.latent_codes_subdir, \"latest.pth\"))\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--batch_size', type=int, default=16, help='input batch size')\n parser.add_argument('--points_batch', type=int, default=8000, help='point batch size')\n parser.add_argument('--nepoch', type=int, default=10000, help='number of epochs to train for')\n parser.add_argument('--conf', type=str, default='dfaust_setup.conf')\n parser.add_argument('--expname', type=str, default='dfuast_shapespace')\n parser.add_argument('--gpu', type=str, default='0,1,2,3', help='GPU to use [default: GPU ignore]')\n parser.add_argument('--threads', type=int, default=32, help='num of threads for data loader')\n parser.add_argument('--is_continue', default=False, action=\"store_true\", help='continue')\n parser.add_argument('--timestamp', default='latest', type=str)\n parser.add_argument('--checkpoint', default='latest', type=str)\n parser.add_argument('--split', default='dfaust/train_all.json', type=str)\n\n args = parser.parse_args()\n\n trainrunner = ShapeSpaceRunner(\n conf=args.conf,\n batch_size=args.batch_size,\n points_batch=args.points_batch,\n nepochs=args.nepoch,\n expname=args.expname,\n gpu_index=args.gpu,\n threads=args.threads,\n is_continue=args.is_continue,\n timestamp=args.timestamp,\n checkpoint=args.checkpoint,\n split_file=args.split\n )\n\n trainrunner.run()\n" }, { "alpha_fraction": 0.5694625377655029, "alphanum_fraction": 0.5731820464134216, "avg_line_length": 28.054054260253906, "blob_id": "13b84c4ee5445876f019e2b8096cb0c7e93c6d2d", "content_id": "933f35b835b8d7574522820121ddebf632fbf58e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5377, "license_type": "no_license", "max_line_length": 173, "num_lines": 185, "path": "/code/shapespace/eval.py", "repo_name": "sergeyprokudin/IGR", "src_encoding": "UTF-8", "text": "import argparse\nimport os\nimport sys\nproject_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))\nsys.path.append(project_dir)\nos.chdir(project_dir)\nimport json\nimport utils.general as utils\nimport torch\nfrom pyhocon import ConfigFactory\nimport utils.plots as plt\nfrom shapespace.latent_optimizer import optimize_latent\n\n\ndef evaluate(network, experiment_directory, conf, checkpoint, split_file, epoch, resolution, uniform_grid):\n\n my_path = os.path.join(experiment_directory, 'evaluation', str(checkpoint))\n\n utils.mkdir_ifnotexists(os.path.join(experiment_directory, 'evaluation'))\n utils.mkdir_ifnotexists(my_path)\n\n with open(split_file, \"r\") as f:\n split = json.load(f)\n\n ds = utils.get_class(conf.get_string('train.dataset'))(split=split, dataset_path=conf.get_string('train.dataset_path'), with_normals=True)\n\n total_files = len(ds)\n print(\"total files : {0}\".format(total_files))\n counter = 0\n dataloader = torch.utils.data.DataLoader(ds, batch_size=1, shuffle=True, num_workers=1, drop_last=False, pin_memory=True)\n\n for (input_pc, normals, index) in dataloader:\n\n input_pc = input_pc.cuda().squeeze()\n normals = normals.cuda().squeeze()\n\n print(counter)\n counter = counter + 1\n\n network.train()\n\n latent = optimize_latent(input_pc, normals, conf, 800, network, lr=5e-3)\n\n all_latent = latent.repeat(input_pc.shape[0], 1)\n\n points = torch.cat([all_latent,input_pc], dim=-1)\n\n shapename = str.join('_', ds.get_info(index))\n\n with torch.no_grad():\n\n network.eval()\n\n plt.plot_surface(with_points=True,\n points=points,\n decoder=network,\n latent=latent,\n path=my_path,\n epoch=epoch,\n shapename=shapename,\n resolution=resolution,\n mc_value=0,\n is_uniform_grid=uniform_grid,\n verbose=True,\n save_html=True,\n save_ply=True,\n overwrite=True,\n connected=True)\n\n\nif __name__ == '__main__':\n\n arg_parser = argparse.ArgumentParser()\n\n arg_parser.add_argument(\n \"--gpu\",\n \"-g\",\n dest=\"gpu_num\",\n required=False,\n default='ignore'\n )\n\n arg_parser.add_argument(\n \"--exps-dir\",\n dest=\"exps_dir\",\n required=False,\n default='exps'\n )\n\n arg_parser.add_argument(\n \"--timestamp\",\n \"-t\",\n dest=\"timestamp\",\n default='latest',\n required=False,\n )\n\n arg_parser.add_argument(\n \"--conf\",\n \"-f\",\n dest=\"conf\",\n default='dfaust_setup.conf',\n required=False,\n )\n\n arg_parser.add_argument(\n \"--split\",\n \"-s\",\n dest=\"split\",\n default='dfaust/test_models.json',\n required=False,\n )\n\n arg_parser.add_argument(\n \"--exp-name\",\n \"-e\",\n dest=\"exp_name\",\n required=True,\n help=\"experiment name\",\n )\n\n arg_parser.add_argument(\n \"--checkpoint\",\n \"-c\",\n dest=\"epoch\",\n default='latest',\n help=\"checkpoint to test.\",\n )\n\n arg_parser.add_argument(\n \"--resolution\",\n \"-r\",\n dest=\"resolution\",\n help='resolution of marching cube grid',\n default=512\n )\n\n arg_parser.add_argument(\n \"--uniform-grid\",\n \"-u\",\n dest=\"uniform_grid\",\n help='use uniform grid in marching cube or non uniform',\n default=False\n )\n\n print('evaluating')\n\n args = arg_parser.parse_args()\n\n code_path = os.path.abspath(os.path.curdir)\n exps_path = os.path.join(os.path.abspath(os.path.pardir), args.exps_dir)\n\n if args.gpu_num != 'ignore':\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = '{0}'.format(args.gpu_num)\n\n conf = ConfigFactory.parse_file(os.path.join(code_path, 'shapespace', args.conf))\n\n experiment_directory = os.path.join(exps_path, args.exp_name)\n\n if args.timestamp == 'latest':\n timestamps = os.listdir(experiment_directory)\n timestamp = sorted(timestamps)[-1]\n else:\n timestamp = args.timestamp\n\n experiment_directory = os.path.join(experiment_directory, timestamp)\n saved_model_state = torch.load(os.path.join(experiment_directory, 'checkpoints', 'ModelParameters', args.epoch + \".pth\"))\n saved_model_epoch = saved_model_state[\"epoch\"]\n with_normals = conf.get_float('network.loss.normals_lambda') > 0\n network = utils.get_class(conf.get_string('train.network_class'))(d_in=conf.get_int('train.latent_size')+conf.get_int('train.d_in'), **conf.get_config('network.inputs'))\n\n network.load_state_dict({k.replace('module.', ''): v for k, v in saved_model_state[\"model_state_dict\"].items()})\n\n split_file = os.path.join(code_path, 'splits', args.split)\n\n evaluate(\n network=network.cuda(),\n experiment_directory=experiment_directory,\n conf=conf,\n checkpoint=saved_model_epoch,\n split_file=split_file,\n epoch=saved_model_epoch,\n resolution=args.resolution,\n uniform_grid=args.uniform_grid\n )\n\n\n" }, { "alpha_fraction": 0.5632228255271912, "alphanum_fraction": 0.570932924747467, "avg_line_length": 36.60869598388672, "blob_id": "6ec47d798e9b02305e606bcb394f3824b42e4e4a", "content_id": "275fa784573171229375b393ad04580366d4fd53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2594, "license_type": "no_license", "max_line_length": 122, "num_lines": 69, "path": "/code/datasets/dfaustdataset.py", "repo_name": "sergeyprokudin/IGR", "src_encoding": "UTF-8", "text": "import torch\nimport torch.utils.data as data\nimport numpy as np\nimport os\nimport utils.general as utils\n\n\nclass DFaustDataSet(data.Dataset):\n\n def __init__(self, dataset_path, split, points_batch=16384, d_in=3, with_gt=False, with_normals=False):\n\n base_dir = os.path.abspath(dataset_path)\n self.npyfiles_mnfld = get_instance_filenames(base_dir, split)\n self.points_batch = points_batch\n self.with_normals = with_normals\n self.d_in = d_in\n\n if with_gt:\n self.scans_files = get_instance_filenames(utils.concat_home_dir('datasets/dfaust/scans'), split, '','ply')\n self.scripts_files = get_instance_filenames(utils.concat_home_dir('datasets/dfaust/scripts'), split, '','obj')\n self.shapenames = [x.split('/')[-1].split('.ply')[0] for x in self.scans_files]\n\n def load_points(self, index):\n return np.load(self.npyfiles_mnfld[index])\n\n def get_info(self, index):\n shape_name, pose, tag = self.npyfiles_mnfld[index].split('/')[-3:]\n return shape_name, pose, tag[:tag.find('.npy')]\n\n def __getitem__(self, index):\n\n point_set_mnlfld = torch.from_numpy(self.load_points(index)).float()\n\n random_idx = torch.randperm(point_set_mnlfld.shape[0])[:self.points_batch]\n point_set_mnlfld = torch.index_select(point_set_mnlfld, 0, random_idx)\n\n if self.with_normals:\n normals = point_set_mnlfld[:, -self.d_in:] # todo adjust to case when we get no sigmas\n\n else:\n normals = torch.empty(0)\n\n return point_set_mnlfld[:, :self.d_in], normals, index\n\n def __len__(self):\n return len(self.npyfiles_mnfld)\n\n\ndef get_instance_filenames(base_dir, split, ext='', format='npy'):\n npyfiles = []\n l = 0\n for dataset in split:\n print(dataset)\n for class_name in split[dataset]:\n print(class_name)\n for instance_name in split[dataset][class_name]:\n j = 0\n for shape in split[dataset][class_name][instance_name]:\n\n instance_filename = os.path.join(base_dir, class_name, instance_name,\n shape + \"{0}.{1}\".format(ext, format))\n if not os.path.isfile(instance_filename):\n print(\n 'Requested non-existent file \"' + instance_filename + \"' {0} , {1}\".format(l, j)\n )\n l = l + 1\n j = j + 1\n npyfiles.append(instance_filename)\n return npyfiles" }, { "alpha_fraction": 0.542679488658905, "alphanum_fraction": 0.5559638142585754, "avg_line_length": 34.029701232910156, "blob_id": "7e941ad5a464b868b341270482166413fc00be74", "content_id": "145c1ca7a210b5d9afd864864a82d06ee47db995", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3538, "license_type": "no_license", "max_line_length": 118, "num_lines": 101, "path": "/code/preprocess/dfaust.py", "repo_name": "sergeyprokudin/IGR", "src_encoding": "UTF-8", "text": "import os\nimport sys\nproject_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))\nsys.path.append(project_dir)\nos.chdir(project_dir)\nfrom __future__ import print_function\nimport argparse\n\nimport trimesh\nfrom trimesh.sample import sample_surface\nimport os\nimport numpy as np\nimport json\nimport utils.general as utils\n\nSAMPLES = 250000\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--src-path', required=True, type=str, help='abs path of dfaust data directory')\n parser.add_argument('--out-path', required=True, type=str, help='abs path of parent of output directory')\n parser.add_argument('--mode', required=False, default=None, type=int, help='0 for train only 1 for test only')\n parser.add_argument('--names', required=False, default=None, type=str, help='format: 50002,50020,50021; o.w. all')\n parser.add_argument('--skip', default=False, action=\"store_true\", help='skip if already exists')\n\n code_path = os.path.abspath(os.curdir)\n\n print(\"running\")\n args = parser.parse_args()\n\n if args.mode == 0:\n\n modes = ['train']\n\n elif args.mode == 1:\n\n modes = ['test']\n\n else:\n\n modes = ['train', 'test']\n\n if args.names:\n names = args.names.split(',')\n else:\n names = None\n\n for mode in modes:\n\n print('starting preprocessing {0} mode'.format(mode))\n\n split_file = os.path.join(code_path, 'splits', 'dfaust', '{0}_all.json'.format(mode))\n with open(split_file, \"r\") as f:\n train_split = json.load(f)\n\n countera = 0\n counterb = 0\n counterc = 0\n scale = 1\n\n # os.chdir('/home/atzmonm/data/')\n for ds,cat_det in train_split['scans'].items():\n if names and ds not in names:\n continue\n print(\"ds :{0} , a:{1}\".format(ds,countera))\n countera = countera + 1\n counterb = 0\n\n for cat,shapes in cat_det.items():\n print(\"cat {0} : b{1}\".format(cat,counterb))\n counterb = counterb + 1\n source = os.path.abspath(os.path.join(args.src_path, 'scans', ds, cat))\n output = os.path.abspath(os.path.join(args.out_path, 'dfaust_processed'))\n utils.mkdir_ifnotexists(output)\n utils.mkdir_ifnotexists(os.path.join(output, ds))\n utils.mkdir_ifnotexists(os.path.join(output, ds, cat))\n counterc = 0\n\n for item,shape in enumerate(shapes):\n print(\"item {0} : c{1}\".format(cat, counterc))\n counterc = counterc + 1\n output_file = os.path.join(output,ds,cat,shape)\n print (output_file)\n if not (args.skip and os.path.isfile(output_file + '.npy')):\n print ('loading : {0}'.format(os.path.join(source,shape)))\n mesh = trimesh.load(os.path.join(source,shape) + '.ply')\n sample = sample_surface(mesh,SAMPLES)\n pnts = sample[0]\n normals = mesh.face_normals[sample[1]]\n center = np.mean(pnts, axis=0)\n\n pnts = pnts - np.expand_dims(center, axis=0)\n point_set = np.hstack([pnts, normals])\n\n np.save(output_file + '.npy', point_set)\n\n np.save(output_file + '_normalization.npy', {\"center\":center,\"scale\":scale})\n\n print (\"end!\")\n" }, { "alpha_fraction": 0.6551724076271057, "alphanum_fraction": 0.6649686694145203, "avg_line_length": 33.486488342285156, "blob_id": "c8516d36d9690f4ee8a4f0c8d42bdfe5bcab3b42", "content_id": "d2195667d0016225cadffee9db817f5adeeb49e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2552, "license_type": "no_license", "max_line_length": 115, "num_lines": 74, "path": "/code/shapespace/latent_optimizer.py", "repo_name": "sergeyprokudin/IGR", "src_encoding": "UTF-8", "text": "import os\nimport sys\nproject_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))\nsys.path.append(project_dir)\nos.chdir(project_dir)\nimport torch\nfrom model.network import gradient\nfrom model.sample import Sampler\n\n\ndef adjust_learning_rate(initial_lr, optimizer, iter):\n adjust_lr_every = 400\n lr = initial_lr * ((0.1) ** (iter // adjust_lr_every))\n for param_group in optimizer.param_groups:\n param_group[\"lr\"] = lr\n\n\ndef optimize_latent(points, normals, conf, num_of_iterations, network, lr=1.0e-2):\n\n latent_size = conf.get_int('train.latent_size')\n global_sigma = conf.get_float('network.sampler.properties.global_sigma')\n local_sigma = conf.get_float('network.sampler.properties.local_sigma')\n sampler = Sampler.get_sampler(conf.get_string('network.sampler.sampler_type'))(global_sigma, local_sigma)\n\n latent_lambda = conf.get_float('network.loss.latent_lambda')\n\n normals_lambda = conf.get_float('network.loss.normals_lambda')\n\n grad_lambda = conf.get_float('network.loss.lambda')\n\n num_of_points, dim = points.shape\n\n latent = torch.ones(latent_size).normal_(0, 1 / latent_size).cuda()\n # latent = torch.zeros(latent_size).cuda()\n\n latent.requires_grad = True\n\n optimizer = torch.optim.Adam([latent], lr=lr)\n\n for i in range(num_of_iterations):\n\n sample = sampler.get_points(points.unsqueeze(0)).squeeze()\n\n latent_all = latent.expand(num_of_points, -1)\n surface_pnts = torch.cat([latent_all, points], dim=1)\n\n sample_latent_all = latent.expand(sample.shape[0], -1)\n nonsurface_pnts = torch.cat([sample_latent_all, sample], dim=1)\n\n surface_pnts.requires_grad_()\n nonsurface_pnts.requires_grad_()\n\n surface_pred = network(surface_pnts)\n nonsurface_pred = network(nonsurface_pnts)\n\n surface_grad = gradient(surface_pnts, surface_pred)\n nonsurface_grad = gradient(nonsurface_pnts, nonsurface_pred)\n\n surface_loss = torch.abs(surface_pred).mean()\n grad_loss = torch.mean((nonsurface_grad.norm(2, dim=-1) - 1).pow(2))\n normals_loss = ((surface_grad - normals).abs()).norm(2, dim=1).mean()\n latent_loss = latent.abs().mean()\n loss = surface_loss + latent_lambda * latent_loss + normals_lambda * normals_loss + grad_lambda * grad_loss\n\n adjust_learning_rate(lr, optimizer, i)\n\n optimizer.zero_grad()\n\n loss.backward()\n optimizer.step()\n\n print('latent loss iter {0}:{1}'.format(i, loss.item()))\n\n return latent.unsqueeze(0)\n" }, { "alpha_fraction": 0.7148263454437256, "alphanum_fraction": 0.7415404915809631, "avg_line_length": 33.53845977783203, "blob_id": "c9f68ad75818b1f171672378ee7b3dba942351e8", "content_id": "50e7bd826e229d1f813b2b16bd65c0ce47e4b501", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4492, "license_type": "no_license", "max_line_length": 207, "num_lines": 130, "path": "/README.md", "repo_name": "sergeyprokudin/IGR", "src_encoding": "UTF-8", "text": "# IGR: Implicit Geometric Regualrization for Learning Shapes\n<p align=\"center\">\n <img src=\"IGR.png\"/>\n</p>\n\nThis repository contains an implementation to the ICML 2020 paper: \"Implicit Geometric Regualrization for Learning Shapes\".\n\nIGR is a deep learning approach for learning implicit signed distance representations directly from raw point clouds with or without normal data.\nOur method aims to find an SDF by optimizing the network to solve the eikonal equation with the input point cloud as boundary condition.\nAlthough this is an ill posed condition we enjoy an implicit regualrization coming from the optimization procedure itself which aims our method to simple natrual solutions as can be seen on the figure above.\n\nFor more details:\n\npaper: https://arxiv.org/abs/2002.10099.\n\nvideo: https://youtu.be/6cOvBGBQF9g.\n\n\n## Installation Requirmenets\nThe code is compatible with python 3.7 and pytorch 1.2. In addition, the following packages are required: \nnumpy, pyhocon, plotly, scikit-image, trimesh.\n\n## Usage\n\n\n### Surface reconstruction\n<p align=\"center\">\n <img src=\"recon3D.png\"/>\n</p>\n\nIGR can be used to reconstruct a single surface given a point cloud with or without normal data. Adjust reconstruction/setup.json to the\npath of the input 2D/3D point cloud:\n```\ntrain\n{\n ...\n d_in=D\n ...\n input_path = your_path\n ...\n}\n```\nWhere D=3 in case we use 3D data or 2 if we use 2D. We support xyz,npy,npz,ply files.\n\nThen, run training:\n```\ncd ./code\npython reconstruction/run.py \n```\nFinally, to produce the meshed surface, run:\n```\ncd ./code\npython reconstruction/run.py --eval --checkpoint CHECKPOINT\n```\nwhere CHECKPOINT is the epoch you wish to evaluate of 'latest' if you wish to take the most recent epoch.\n\n\n### Learning shapespace from the D-Faust oriented point clouds\n<p align=\"center\">\n <img src=\"interpolation.jpg\"/>\n</p>\n\n#### Data\nThe raw scans can be downloaded from http://dfaust.is.tue.mpg.de/downloads.\nIn order to sample point clouds with normals use:\n\n```\ncd ./code\npython preprocess/dfaust.py --src-path SRC_PATH --out-path OUT_PATH\n```\nwhere SRC_PATH is the absoule path of the directory with the original D-Faust scans, and OUT_PATH is the absolute path\nof the directory on which you wish to output the processed point clouds.\n\nIt is also possible to process only train\ndata with input --mode 0 our only test with --mode 1.\n \nIn case you wish to only process part of the data (e.g. for parallel processing) it is possible by adding --names NAME_1,NAME_2,...,NAME_k where NAME_i \nis one of D-Faust shapes e.g. 50002, 50020.\n\nAfter preprocessing ended adjust the file ./shapespace/dfaust_setup.conf to the cur path of the data:\n```\ntrain\n{\n ...\n dataset_path = OUT_PATH/dfaust_processed\n ...\n}\n```\n\n#### Predicting meshed surfaces with IGR pretrained network\nWe have uploaded IGR trained network. To produce predictions on unseen test scans, run:\n```\ncd ./code\npython shapespace/eval.py --checkpoint 1200 --exp-name dfaust_pretrained --split dfaust/test_all.json --exps-dir trained_models\n```\nIn case you wish to generate less models you can use --split dfaust/test_models.json\n\n#### Interpolating latents of IGR pretrained network\nTo meshs of latent interpolation between two shapes use:\n```\ncd ./code\npython shapespace/interpolate.py --interval INTERVAL --checkpoint 1200 --exp-name dfaust_pretrained --exps-dir trained_models\n```\nWhere INTERVAL is the number (int) linspace of latent interpolations.\n\nIn case you wish to interpolate different shapes adjust the file dfaust/interpolation.json\n \n#### Training\nIf you want to train IGR yourself, run:\n```\ncd ./code\npython shapespace/train.py\n```\n\n## Citation\nIf you find our work useful in your research, please consider citing:\n\n @incollection{icml2020_2086,\n author = {Gropp, Amos and Yariv, Lior and Haim, Niv and Atzmon, Matan and Lipman, Yaron},\n booktitle = {Proceedings of Machine Learning and Systems 2020},\n pages = {3569--3579},\n title = {Implicit Geometric Regularization for Learning Shapes},\n year = {2020}\n }\n \t\n## Related papers\n* [Yariv et al. - Multiview Neural Surface Reconstruction with Implicit Lighting and Material](https://arxiv.org/abs/2003.09852)\n* [Atzmon & Lipman. - SAL++: Sign Agnostic Learning with Derivatives (2020)](https://arxiv.org/abs/2006.05400)\n* [Atzmon & Lipman. - SAL: Sign Agnostic Learning of Shapes From Raw Data (2020)](https://arxiv.org/abs/1911.10414)\n* [Atzmon et al. - Controlling Neural Level Sets (2019)](https://arxiv.org/abs/1905.11911)\n\t\n" }, { "alpha_fraction": 0.5592969655990601, "alphanum_fraction": 0.563962996006012, "avg_line_length": 36.05763626098633, "blob_id": "bf0b118e60bb8cde947a7ae10a3e1f13530786ea", "content_id": "80f95a796b5887c1da9c989a3d9e112c09a0c5a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12859, "license_type": "no_license", "max_line_length": 124, "num_lines": 347, "path": "/code/reconstruction/run.py", "repo_name": "sergeyprokudin/IGR", "src_encoding": "UTF-8", "text": "import os\nimport sys\nproject_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))\nsys.path.append(project_dir)\nos.chdir(project_dir)\nfrom datetime import datetime\nfrom pyhocon import ConfigFactory\nimport numpy as np\nimport argparse\nimport GPUtil\nimport torch\nimport utils.general as utils\nfrom model.sample import Sampler\nfrom model.network import gradient\nfrom scipy.spatial import cKDTree\nfrom utils.plots import plot_surface, plot_cuts\nprint(torch.cuda.is_available())\n\nclass ReconstructionRunner:\n\n def run(self):\n\n print(\"running\")\n\n self.data = self.data.cuda()\n self.data.requires_grad_()\n\n if self.eval:\n\n print(\"evaluating epoch: {0}\".format(self.startepoch))\n my_path = os.path.join(self.cur_exp_dir, 'evaluation', str(self.startepoch))\n\n utils.mkdir_ifnotexists(os.path.join(self.cur_exp_dir, 'evaluation'))\n utils.mkdir_ifnotexists(my_path)\n self.plot_shapes(epoch=self.startepoch, path=my_path, with_cuts=True)\n return\n\n print(\"training\")\n\n for epoch in range(self.startepoch, self.nepochs + 1):\n\n indices = torch.tensor(np.random.choice(self.data.shape[0], self.points_batch, False))\n\n cur_data = self.data[indices]\n\n mnfld_pnts = cur_data[:, :self.d_in]\n mnfld_sigma = self.local_sigma[indices]\n\n if epoch % self.conf.get_int('train.checkpoint_frequency') == 0:\n print('saving checkpoint: ', epoch)\n self.save_checkpoints(epoch)\n print('plot validation epoch: ', epoch)\n self.plot_shapes(epoch)\n\n # change back to train mode\n self.network.train()\n self.adjust_learning_rate(epoch)\n\n nonmnfld_pnts = self.sampler.get_points(mnfld_pnts.unsqueeze(0), mnfld_sigma.unsqueeze(0)).squeeze()\n\n # forward pass\n\n mnfld_pred = self.network(mnfld_pnts)\n nonmnfld_pred = self.network(nonmnfld_pnts)\n\n # compute grad\n\n mnfld_grad = gradient(mnfld_pnts, mnfld_pred)\n nonmnfld_grad = gradient(nonmnfld_pnts, nonmnfld_pred)\n\n # manifold loss\n\n mnfld_loss = (mnfld_pred.abs()).mean()\n\n # eikonal loss\n\n grad_loss = ((nonmnfld_grad.norm(2, dim=-1) - 1) ** 2).mean()\n\n loss = mnfld_loss + self.grad_lambda * grad_loss\n\n # normals loss\n\n if self.with_normals:\n normals = cur_data[:, -self.d_in:]\n normals_loss = ((mnfld_grad - normals).abs()).norm(2, dim=1).mean()\n loss = loss + self.normals_lambda * normals_loss\n else:\n normals_loss = torch.zeros(1)\n\n # back propagation\n\n self.optimizer.zero_grad()\n\n loss.backward()\n\n self.optimizer.step()\n\n if epoch % self.conf.get_int('train.status_frequency') == 0:\n print('Train Epoch: [{}/{} ({:.0f}%)]\\tTrain Loss: {:.6f}\\tManifold loss: {:.6f}'\n '\\tGrad loss: {:.6f}\\tNormals Loss: {:.6f}'.format(\n epoch, self.nepochs, 100. * epoch / self.nepochs,\n loss.item(), mnfld_loss.item(), grad_loss.item(), normals_loss.item()))\n\n def plot_shapes(self, epoch, path=None, with_cuts=False):\n # plot network validation shapes\n with torch.no_grad():\n\n self.network.eval()\n\n if not path:\n path = self.plots_dir\n\n indices = torch.tensor(np.random.choice(self.data.shape[0], self.points_batch, False))\n\n pnts = self.data[indices, :3]\n\n plot_surface(with_points=True,\n points=pnts,\n decoder=self.network,\n path=path,\n epoch=epoch,\n shapename=self.expname,\n **self.conf.get_config('plot'))\n\n if with_cuts:\n plot_cuts(points=pnts,\n decoder=self.network,\n path=path,\n epoch=epoch,\n near_zero=False)\n\n def __init__(self, **kwargs):\n\n self.home_dir = os.path.abspath(os.pardir)\n\n # config setting\n\n if type(kwargs['conf']) == str:\n self.conf_filename = './reconstruction/' + kwargs['conf']\n self.conf = ConfigFactory.parse_file(self.conf_filename)\n else:\n self.conf = kwargs['conf']\n\n self.expname = kwargs['expname']\n\n # GPU settings\n\n self.GPU_INDEX = kwargs['gpu_index']\n\n if not self.GPU_INDEX == 'ignore':\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = '{0}'.format(self.GPU_INDEX)\n\n self.num_of_gpus = torch.cuda.device_count()\n\n self.eval = kwargs['eval']\n\n # settings for loading an existing experiment\n\n if (kwargs['is_continue'] or self.eval) and kwargs['timestamp'] == 'latest':\n if os.path.exists(os.path.join(self.home_dir, 'exps', self.expname)):\n timestamps = os.listdir(os.path.join(self.home_dir, 'exps', self.expname))\n if (len(timestamps)) == 0:\n is_continue = False\n timestamp = None\n else:\n timestamp = sorted(timestamps)[-1]\n is_continue = True\n else:\n is_continue = False\n timestamp = None\n else:\n timestamp = kwargs['timestamp']\n is_continue = kwargs['is_continue'] or self.eval\n\n self.exps_folder_name = 'exps'\n\n utils.mkdir_ifnotexists(utils.concat_home_dir(os.path.join(self.home_dir, self.exps_folder_name)))\n\n self.input_file = self.conf.get_string('train.input_path')\n self.data = utils.load_point_cloud_by_file_extension(self.input_file)\n\n sigma_set = []\n ptree = cKDTree(self.data)\n\n for p in np.array_split(self.data, 100, axis=0):\n d = ptree.query(p, 50 + 1)\n sigma_set.append(d[0][:, -1])\n\n sigmas = np.concatenate(sigma_set)\n self.local_sigma = torch.from_numpy(sigmas).float().cuda()\n\n self.expdir = utils.concat_home_dir(os.path.join(self.home_dir, self.exps_folder_name, self.expname))\n utils.mkdir_ifnotexists(self.expdir)\n\n if is_continue:\n self.timestamp = timestamp\n else:\n self.timestamp = '{:%Y_%m_%d_%H_%M_%S}'.format(datetime.now())\n\n self.cur_exp_dir = os.path.join(self.expdir, self.timestamp)\n utils.mkdir_ifnotexists(self.cur_exp_dir)\n\n self.plots_dir = os.path.join(self.cur_exp_dir, 'plots')\n utils.mkdir_ifnotexists(self.plots_dir)\n\n self.checkpoints_path = os.path.join(self.cur_exp_dir, 'checkpoints')\n utils.mkdir_ifnotexists(self.checkpoints_path)\n\n self.checkpoints_path = os.path.join(self.cur_exp_dir, 'checkpoints')\n utils.mkdir_ifnotexists(self.checkpoints_path)\n\n self.model_params_subdir = \"ModelParameters\"\n self.optimizer_params_subdir = \"OptimizerParameters\"\n\n utils.mkdir_ifnotexists(os.path.join(self.checkpoints_path, self.model_params_subdir))\n utils.mkdir_ifnotexists(os.path.join(self.checkpoints_path, self.optimizer_params_subdir))\n\n self.nepochs = kwargs['nepochs']\n\n self.points_batch = kwargs['points_batch']\n\n self.global_sigma = self.conf.get_float('network.sampler.properties.global_sigma')\n self.sampler = Sampler.get_sampler(self.conf.get_string('network.sampler.sampler_type'))(self.global_sigma,\n self.local_sigma)\n self.grad_lambda = self.conf.get_float('network.loss.lambda')\n self.normals_lambda = self.conf.get_float('network.loss.normals_lambda')\n\n # use normals if data has normals and normals_lambda is positive\n self.with_normals = self.normals_lambda > 0 and self.data.shape[-1] >= 6\n\n self.d_in = self.conf.get_int('train.d_in')\n\n self.network = utils.get_class(self.conf.get_string('train.network_class'))(d_in=self.d_in,\n **self.conf.get_config(\n 'network.inputs'))\n\n if torch.cuda.is_available():\n self.network.cuda()\n\n self.lr_schedules = self.get_learning_rate_schedules(self.conf.get_list('train.learning_rate_schedule'))\n self.weight_decay = self.conf.get_float('train.weight_decay')\n\n self.startepoch = 0\n\n self.optimizer = torch.optim.Adam(\n [\n {\n \"params\": self.network.parameters(),\n \"lr\": self.lr_schedules[0].get_learning_rate(0),\n \"weight_decay\": self.weight_decay\n },\n ])\n\n # if continue load checkpoints\n\n if is_continue:\n old_checkpnts_dir = os.path.join(self.expdir, timestamp, 'checkpoints')\n\n saved_model_state = torch.load(\n os.path.join(old_checkpnts_dir, 'ModelParameters', str(kwargs['checkpoint']) + \".pth\"))\n self.network.load_state_dict(saved_model_state[\"model_state_dict\"])\n\n data = torch.load(\n os.path.join(old_checkpnts_dir, 'OptimizerParameters', str(kwargs['checkpoint']) + \".pth\"))\n self.optimizer.load_state_dict(data[\"optimizer_state_dict\"])\n self.startepoch = saved_model_state['epoch']\n\n def get_learning_rate_schedules(self, schedule_specs):\n\n schedules = []\n\n for schedule_specs in schedule_specs:\n\n if schedule_specs[\"Type\"] == \"Step\":\n schedules.append(\n utils.StepLearningRateSchedule(\n schedule_specs[\"Initial\"],\n schedule_specs[\"Interval\"],\n schedule_specs[\"Factor\"],\n )\n )\n\n else:\n raise Exception(\n 'no known learning rate schedule of type \"{}\"'.format(\n schedule_specs[\"Type\"]\n )\n )\n\n return schedules\n\n def adjust_learning_rate(self, epoch):\n for i, param_group in enumerate(self.optimizer.param_groups):\n param_group[\"lr\"] = self.lr_schedules[i].get_learning_rate(epoch)\n\n def save_checkpoints(self, epoch):\n\n torch.save(\n {\"epoch\": epoch, \"model_state_dict\": self.network.state_dict()},\n os.path.join(self.checkpoints_path, self.model_params_subdir, str(epoch) + \".pth\"))\n torch.save(\n {\"epoch\": epoch, \"model_state_dict\": self.network.state_dict()},\n os.path.join(self.checkpoints_path, self.model_params_subdir, \"latest.pth\"))\n\n torch.save(\n {\"epoch\": epoch, \"optimizer_state_dict\": self.optimizer.state_dict()},\n os.path.join(self.checkpoints_path, self.optimizer_params_subdir, str(epoch) + \".pth\"))\n torch.save(\n {\"epoch\": epoch, \"optimizer_state_dict\": self.optimizer.state_dict()},\n os.path.join(self.checkpoints_path, self.optimizer_params_subdir, \"latest.pth\"))\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--points_batch', type=int, default=16384, help='point batch size')\n parser.add_argument('--nepoch', type=int, default=100000, help='number of epochs to train for')\n parser.add_argument('--conf', type=str, default='setup.conf')\n parser.add_argument('--expname', type=str, default='single_shape')\n parser.add_argument('--gpu', type=str, default='2', help='GPU to use [default: GPU auto]')\n parser.add_argument('--is_continue', default=False, action=\"store_true\", help='continue')\n parser.add_argument('--timestamp', default='latest', type=str)\n parser.add_argument('--checkpoint', default='latest', type=str)\n parser.add_argument('--eval', default=False, action=\"store_true\")\n\n args = parser.parse_args()\n\n if args.gpu == \"auto\":\n deviceIDs = GPUtil.getAvailable(order='memory', limit=1, maxLoad=0.5, maxMemory=0.5, includeNan=False, excludeID=[],\n excludeUUID=[])\n gpu = deviceIDs[0]\n else:\n gpu = args.gpu\n\n trainrunner = ReconstructionRunner(\n conf=args.conf,\n points_batch=args.points_batch,\n nepochs=args.nepoch,\n expname=args.expname,\n gpu_index=gpu,\n is_continue=args.is_continue,\n timestamp=args.timestamp,\n checkpoint=args.checkpoint,\n eval=args.eval\n )\n\n trainrunner.run()\n" }, { "alpha_fraction": 0.6383799314498901, "alphanum_fraction": 0.6460945010185242, "avg_line_length": 27.80555534362793, "blob_id": "07371de9f26ffaf2aa4183b2fe803b220125f087", "content_id": "03d234e24323c584f9c004449349b137022324d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1037, "license_type": "no_license", "max_line_length": 141, "num_lines": 36, "path": "/code/model/sample.py", "repo_name": "sergeyprokudin/IGR", "src_encoding": "UTF-8", "text": "import torch\nimport utils.general as utils\nimport abc\n\n\nclass Sampler(metaclass=abc.ABCMeta):\n\n @abc.abstractmethod\n def get_points(self,pc_input):\n pass\n\n @staticmethod\n def get_sampler(sampler_type):\n\n return utils.get_class(\"model.sample.{0}\".format(sampler_type))\n\n\nclass NormalPerPoint(Sampler):\n\n def __init__(self, global_sigma, local_sigma=0.01):\n self.global_sigma = global_sigma\n self.local_sigma = local_sigma\n\n def get_points(self, pc_input, local_sigma=None):\n batch_size, sample_size, dim = pc_input.shape\n\n if local_sigma is not None:\n sample_local = pc_input + (torch.randn_like(pc_input) * local_sigma.unsqueeze(-1))\n else:\n sample_local = pc_input + (torch.randn_like(pc_input) * self.local_sigma)\n\n sample_global = (torch.rand(batch_size, sample_size // 8, dim, device=pc_input.device) * (self.global_sigma * 2)) - self.global_sigma\n\n sample = torch.cat([sample_local, sample_global], dim=1)\n\n return sample\n" } ]
9
wanghaihong200/selenium_grid
https://github.com/wanghaihong200/selenium_grid
be9227c323ab66c3eb48cfb0e425f88946625411
45b00a76503dfb394132bfc25021b1c4abf8124e
f4f4a73909fee6a09462dfbe92e02fd5550efab6
refs/heads/master
2023-04-08T15:50:32.789615
2021-04-24T05:12:39
2021-04-24T05:12:39
361,075,245
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6263616681098938, "alphanum_fraction": 0.6503267884254456, "avg_line_length": 23, "blob_id": "eeba336bf742be23e71ca716815ba9c3010f0f7c", "content_id": "e7665e1c4c960644a0180744abd7e86ef986923b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 986, "license_type": "no_license", "max_line_length": 87, "num_lines": 38, "path": "/test_grid.py", "repo_name": "wanghaihong200/selenium_grid", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\n@author: wang\n@contact: [email protected]\n@file: test_grid\n@time: 2021/4/22 9:51 下午\n@desc:\n\"\"\"\nimport time\nfrom selenium.webdriver import DesiredCapabilities\nfrom selenium.webdriver import Remote\n\n\nclass TestGrid:\n \"\"\"\n selenium_grid : server上注册两个节点\n pytest-xdist插件进行并行测试, pytest test_grid.py -n 2\n 分发2个请求到2个节点上进行并行测试\n \"\"\"\n def setup(self):\n hub_url = \"http://localhost:4444/wd/hub\"\n capability = DesiredCapabilities.CHROME.copy()\n self.driver = Remote(command_executor=hub_url, desired_capabilities=capability)\n\n def teardown(self):\n self.driver.quit()\n\n def test_node1(self):\n self.driver.get(\"https://www.baidu.com\")\n print(self.driver.page_source)\n time.sleep(5)\n\n\n def test_node2(self):\n self.driver.get(\"https://www.baidu.com\")\n print(self.driver.page_source)\n time.sleep(5)\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.808080792427063, "alphanum_fraction": 0.808080792427063, "avg_line_length": 23.75, "blob_id": "32e3877f69fbacdd45b43ec47b53dd5345fb54b3", "content_id": "58f8dd9fa32fce5635d71d60563f8953c750882c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 171, "license_type": "no_license", "max_line_length": 48, "num_lines": 4, "path": "/readme.md", "repo_name": "wanghaihong200/selenium_grid", "src_encoding": "UTF-8", "text": "使用docker构建selenium-grid,创建了分布式服务器集群用于并行测试web ui。\n\n使用vnc viewer访问 Node节点,效果图如下:\n![img.png](img.png)\n" } ]
2
ku-asteam/Traffic-Monitoring
https://github.com/ku-asteam/Traffic-Monitoring
5c17dbfed08640b7b8b0f7acca33008be2531cbc
c4b79ef63247c1277b41ba422cb44db1ddb1e2cb
426cb9828f8f4f58d21cd0e542193d268b8f4188
refs/heads/main
2023-02-03T17:46:41.427057
2020-12-27T11:20:41
2020-12-27T11:20:41
324,742,482
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6101301312446594, "alphanum_fraction": 0.6175650358200073, "avg_line_length": 47.370784759521484, "blob_id": "083a4de3165d6075520baa398e020094b9d0b0cb", "content_id": "af6ab01a1711b458e72fe0e0bfb92d9ccfc79d67", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4304, "license_type": "no_license", "max_line_length": 187, "num_lines": 89, "path": "/LightGBM_Classifier.py", "repo_name": "ku-asteam/Traffic-Monitoring", "src_encoding": "UTF-8", "text": "from operator import attrgetter\n\nfrom ryu.app import simple_switch_13\nfrom ryu.controller import ofp_event\nfrom ryu.controller.handler import MAIN_DISPATCHER, DEAD_DISPATCHER\nfrom ryu.controller.handler import set_ev_cls\nfrom ryu.lib import hub\n\nimport pymysql\n\nclass SimpleMonitor(simple_switch_13.SimpleSwitch13):\n\n def __init__(self, *args, **kwargs):\n super(SimpleMonitor, self).__init__(*args, **kwargs)\n self.datapaths = {}\n self.monitor_thread = hub.spawn(self._monitor)\n self.mydb = mysql.connect(host=\"localhost\", user=\"root\", password=\"ab2900014\", database=\"sdn\")\n self.mycursor = self.mydb.cursor()\n\n @set_ev_cls(ofp_event.EventOFPStateChange, [MAIN_DISPATCHER, DEAD_DISPATCHER])\n def _state_change_handler(self, ev):\n datapath = ev.datapath\n if ev.state == MAIN_DISPATCHER:\n if not datapath.id in self.datapaths:\n self.logger.debug('register datapath: %016x', datapath.id)\n self.datapaths[datapath.id] = datapath\n elif ev.state == DEAD_DISPATCHER:\n if datapath.id in self.datapaths:\n self.logger.debug('unregister datapath: %016x', datapath.id)\n del self.datapaths[datapath.id]\n\n def _monitor(self):\n while True:\n for dp in self.datapaths.values():\n self._request_stats(dp)\n self._lightGBM_classification()\n hub.sleep(10)\n\n def _request_stats(self, datapath):\n self.logger.debug('send stats request: %016x', datapath.id)\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n\n req = parser.OFPFlowStatsRequest(datapath)\n datapath.send_msg(req)\n\n req = parser.OFPPortStatsRequest(datapath, 0, ofproto.OFPP_ANY)\n datapath.send_msg(req)\n\n @set_ev_cls(ofp_event.EventOFPFlowStatsReply, MAIN_DISPATCHER)\n def _flow_stats_reply_handler(self, ev):\n body = ev.msg.body\n for stat in sorted([flow for flow in body if flow.priority == 1], key=lambda flow: (flow.match['in_port'], flow.match['eth_dst'])):\n sql = \"INSERT into flowStats (datapath_id, in_port, eth_dst, packet_count, byte_count, duration_sec, length) VALUES (%s, %s, %s, %s, %s, %s, %s)\"\n val = (str(ev.msg.datapath.id), str(stat.match['in_port']), str(stat.match['eth_dst']), str(stat.packet_count), str(stat.byte_count), str(stat.duration_sec), str(stat.length))\n self.mycursor.execute(sql, val)\n self.mydb.commit()\n\n @set_ev_cls(ofp_event.EventOFPPortStatsReply, MAIN_DISPATCHER)\n def _port_stats_reply_handler(self, ev):\n body = ev.msg.body\n for stat in sorted(body, key=attrgetter('port_no')):\n sql = \"INSERT into portStats (datapath_id, port_no, rx_bytes, rx_packets, tx_bytes, tx_packets) VALUES (%s, %s, %s, %s, %s, %s)\"\n val = (str(ev.msg.datapath.id), str(stat.port_no), str(stat.rx_bytes), str(stat.rx_packets), str(stat.tx_bytes), str(stat.tx_packets))\n self.mycursor.execute(sql, val)\n self.mydb.commit()\n\n def _lightGBM_classification(self):\n mydb = mysql.connector.connect(host=\"localhost\", user=\"root\", passwd=\"ab2900014\", database=\"sdn\")\n mycursor = mydb.cursor()\n sql1 = \"select * from flowStats order by id desc limit 1\"\n mycursor.execute(sql1)\n row_f = mycursor.fetchall()\n sql2 = \"select * from portStats order by id desc limit 1\"\n mycursor.execute(sql2)\n row_p = mycursor.fetchall()\n\n if len(row_f)>0 and len(row_p)>0:\n flow = list(row_f[0])[:-1]\n port = list(row_p[0])[:-1]\n flow_df = pd.DataFrame([flow], columns=[\"datapath_id\", \"in_port\", \"eth_dst\", \"packet_count\", \"byte_count\", \"duration_sec\", \"lenght\"])\n port_df = pd.DataFrame([port], columns=[\"datapath_id\", \"port_no\", \"rx_bytes\", \"rx_packets\", \"tx_bytes\", \"tx_packets\"])\n df = pd.concat([flow_df, port_df], axis=1, join='inner')\n\n feature_list = ['in_port', 'packet_count', 'byte_count', 'duration_sec', 'length', 'port_no', 'rx_bytes', 'rx_packets', 'tx_bytes', 'tx_packets']\n df = df[feature_list]\n lightGBM_clf = joblib.load('lightGBM.pkl')\n res = lightGBM_clf.predict(df)\n print(res)" } ]
1
xyu40/cuDMRG
https://github.com/xyu40/cuDMRG
e7fb38de77257081d8dcdd96b718460d9cc0f05d
86163d58759aeba89bd8d9db4116e814f3cedb9f
2959cba7307e3d3909e90c9ef8d9121e7608e856
refs/heads/main
2023-03-16T16:19:42.045780
2021-03-12T04:37:16
2021-03-12T04:37:16
342,972,122
3
0
null
null
null
null
null
[ { "alpha_fraction": 0.5592694878578186, "alphanum_fraction": 0.5620262026786804, "avg_line_length": 27.73267364501953, "blob_id": "bcc52c38e6d148b49d0bc933852e6d3c95810523", "content_id": "459d1dae654af75f01bb74fc1d9c8dd5fcd561ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2902, "license_type": "no_license", "max_line_length": 77, "num_lines": 101, "path": "/cuDMRG/tensor/index.py", "repo_name": "xyu40/cuDMRG", "src_encoding": "UTF-8", "text": "import uuid\nfrom enum import Enum\nfrom typing import List, Tuple\nfrom ..utils import get_logger\n\nlogger = get_logger(__name__)\n\n\nclass IndexType(Enum):\n VIRTUAL = 1\n PHYSICAL = 2\n ANYTYPE = 3\n\n\nclass Index:\n def __init__(\n self,\n size: int,\n index_type: IndexType = IndexType.VIRTUAL,\n level: int = 0,\n ) -> None:\n self._id = uuid.uuid4()\n self._size: int = size\n self._index_type: IndexType = index_type\n self._level: int = level\n\n @property\n def size(self) -> int:\n return self._size\n\n @property\n def indexType(self) -> IndexType:\n return self._index_type\n\n @property\n def level(self) -> int:\n return self._level\n\n def setSize(self, size: int) -> \"Index\":\n self._size = size\n return self\n\n def raiseLevel(self, index_type=IndexType.ANYTYPE) -> \"Index\":\n if index_type is IndexType.ANYTYPE or self._index_type == index_type:\n self._level += 1\n return self\n\n def lowerLevel(self, index_type=IndexType.ANYTYPE) -> \"Index\":\n if index_type is IndexType.ANYTYPE or self._index_type == index_type:\n self._level -= 1\n return self\n\n def setLevel(self, level: int, index_type=IndexType.ANYTYPE) -> \"Index\":\n if index_type is IndexType.ANYTYPE or self._index_type == index_type:\n self._level = level\n return self\n\n def resetLevel(self, index_type=IndexType.ANYTYPE) -> \"Index\":\n if index_type is IndexType.ANYTYPE or self._index_type == index_type:\n self._level = 0\n return self\n\n def mapLevel(self,\n level_from: int,\n level_to: int,\n index_type=IndexType.ANYTYPE) -> \"Index\":\n if index_type is IndexType.ANYTYPE or self._index_type == index_type:\n if self._level == level_from:\n self._level = level_to\n return self\n\n def almostIndentical(self, rhs: \"Index\") -> bool:\n return self._id == rhs._id and self._level != rhs._level\n\n def __key(self) -> Tuple[int, int]:\n return (self._id.int, self._level)\n\n def __hash__(self) -> int:\n return hash(self.__key())\n\n def __eq__(self, rhs: object) -> bool:\n if isinstance(rhs, self.__class__):\n return self._id == rhs._id and self._level == rhs._level\n else:\n return False\n\n def __str__(self):\n return (f\"Index({self._size}, {self._index_type}, \"\n f\"{self._level}, {self._id})\")\n\n\ndef getEinsumRule(lhs: List[Index],\n rhs: List[Index]) -> Tuple[List[int], List[int]]:\n lhs_list = []\n rhs_list = []\n lhs_map = {index: i for i, index in enumerate(lhs)}\n for j, index in enumerate(rhs):\n if index in lhs_map:\n lhs_list.append(lhs_map[index])\n rhs_list.append(j)\n return lhs_list, rhs_list\n" }, { "alpha_fraction": 0.695652186870575, "alphanum_fraction": 0.695652186870575, "avg_line_length": 26.18181800842285, "blob_id": "1a37f8fc192a9d73a528be24e814fa7698006a6c", "content_id": "a5726444f9497cb2e44ad123bff8236dd388a9a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 299, "license_type": "no_license", "max_line_length": 77, "num_lines": 11, "path": "/cuDMRG/apps/__init__.py", "repo_name": "xyu40/cuDMRG", "src_encoding": "UTF-8", "text": "from .sites import Sites\nfrom .mps import MPS\nfrom .mpo import MPO, psiHphi\nfrom .heisenberg import Heisenberg\nfrom .solver import LinearOp, LinearMult, lanczos\nfrom .dmrg import DMRG\n\n__all__ = [\n \"Sites\", \"MPS\", \"MPO\", \"psiHphi\", \"Heisenberg\", \"LinearOp\", \"LinearMult\",\n \"lanczos\", \"DMRG\"\n]\n" }, { "alpha_fraction": 0.5005154609680176, "alphanum_fraction": 0.508247435092926, "avg_line_length": 26.714284896850586, "blob_id": "af714e7b764593860494bd5f87fb968094eea1e6", "content_id": "5f00eb87711f872333156437b7d5c2a66f153557", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1940, "license_type": "no_license", "max_line_length": 72, "num_lines": 70, "path": "/cuDMRG/apps/solver.py", "repo_name": "xyu40/cuDMRG", "src_encoding": "UTF-8", "text": "try:\n import cupy as xp\nexcept ImportError:\n import numpy as xp\nfrom abc import ABC, abstractmethod\nfrom typing import Tuple\nfrom ..tensor import Tensor\nfrom ..utils import get_logger\n\nlogger = get_logger(__name__)\n\n\nclass LinearOp(ABC):\n def __init__(self) -> None:\n pass\n\n @abstractmethod\n def __call__(self, t: Tensor):\n pass\n\n\nclass LinearMult(LinearOp):\n def __init__(self, lhs: Tensor, rhs: Tensor, x: Tensor) -> None:\n super().__init__()\n self._lhs = lhs\n self._rhs = rhs\n self._x = x.copy()\n\n def __call__(self, t: xp.ndarray) -> xp.ndarray:\n self._x._data = t\n res = self._lhs * self._x\n res *= self._rhs\n return res._data\n\n\ndef lanczos(op: LinearOp,\n x: Tensor,\n krylov_size: int,\n num_restarts: int,\n smallest: bool = True) -> Tuple[float, Tensor]:\n v_next = x._data.copy()\n beta = xp.zeros(krylov_size + 1)\n alpha = xp.zeros(krylov_size)\n for _ in range(num_restarts):\n beta[0] = 0.0\n v_prev = xp.zeros(x._data.shape)\n v_next /= xp.linalg.norm(v_next)\n V = xp.zeros([x.size, krylov_size])\n for i in range(0, krylov_size):\n w = op(v_next)\n alpha[i] = xp.dot(w.reshape(x.size), v_next.reshape(x.size))\n w -= (alpha[i] * v_next + beta[i] * v_prev)\n beta[i + 1] = xp.linalg.norm(w)\n v_prev = v_next.copy()\n v_next = w / beta[i + 1]\n V[:, i] = v_prev.reshape(x.size)\n\n tridiag = xp.diag(alpha)\n for i in range(0, krylov_size - 1):\n tridiag[i + 1, i] = beta[i + 1]\n d, v = xp.linalg.eigh(tridiag, UPLO=\"L\")\n\n if smallest:\n ev = d[0]\n v_next = (V @ v[:, 0]).reshape(x._data.shape)\n else:\n ev = d[-1]\n v_next = (V @ v[:, -1]).reshape(x._data.shape)\n x._data = v_next\n return ev, x\n" }, { "alpha_fraction": 0.7185184955596924, "alphanum_fraction": 0.770370364189148, "avg_line_length": 32.75, "blob_id": "0b3b7d2b328c5d72fb95e8e15cd827c6a07925e4", "content_id": "022eb7f55c44fa011033e6254e2bdcb0d702491b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 135, "license_type": "no_license", "max_line_length": 84, "num_lines": 4, "path": "/README.md", "repo_name": "xyu40/cuDMRG", "src_encoding": "UTF-8", "text": "# cuDMRG\nTesting cupy-based DMRG implementation.\n\npython 3.8, numpy >= 1.19, conda install -c conda-forge cupy cutensor cudatoolkit=11\n" }, { "alpha_fraction": 0.6491228342056274, "alphanum_fraction": 0.6491228342056274, "avg_line_length": 18, "blob_id": "9ebe05524ea336f8bc5a73f458434d7c046a9bd2", "content_id": "d6cb35888ef503d5106832066fde2fb06f9552e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 57, "license_type": "no_license", "max_line_length": 30, "num_lines": 3, "path": "/cuDMRG/utils/__init__.py", "repo_name": "xyu40/cuDMRG", "src_encoding": "UTF-8", "text": "from .logger import get_logger\n\n__all__ = [\"get_logger\"]\n" }, { "alpha_fraction": 0.5882353186607361, "alphanum_fraction": 0.5892857313156128, "avg_line_length": 25.44444465637207, "blob_id": "3f75bc42e64b2248cca3db0bbb310253105b82c5", "content_id": "da28d6daf1043aa845a9827143db8cdf801d23da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 952, "license_type": "no_license", "max_line_length": 70, "num_lines": 36, "path": "/cuDMRG/utils/logger.py", "repo_name": "xyu40/cuDMRG", "src_encoding": "UTF-8", "text": "import logging\nimport sys\n\ntry:\n from colorlog import ColoredFormatter\n FORMATTER = ColoredFormatter(\n \"%(log_color)s[%(asctime)s %(name)-8s%(levelname)s]%(reset)s \"\n \"%(white)s%(message)s\",\n datefmt=\"%H:%M:%S\",\n reset=True,\n log_colors={\n 'DEBUG': 'cyan',\n 'INFO': 'green',\n 'WARNING': 'yellow',\n 'ERROR': 'red',\n 'CRITICAL': 'red',\n })\nexcept ImportError:\n FORMATTER = logging.Formatter(\n \"%(asctime)s - %(name)s - %(levelname)s - %(message)s\",\n datefmt=\"%H:%M:%S\",\n )\n\n\ndef get_console_handler():\n console_handler = logging.StreamHandler(sys.stdout)\n console_handler.setFormatter(FORMATTER)\n return console_handler\n\n\ndef get_logger(logger_name):\n logger = logging.getLogger(logger_name)\n logger.setLevel(logging.DEBUG)\n logger.addHandler(get_console_handler())\n logger.propagate = False\n return logger\n" }, { "alpha_fraction": 0.6376146674156189, "alphanum_fraction": 0.6399082541465759, "avg_line_length": 25.42424201965332, "blob_id": "531ab0efece41607a64e309aaaef8c5847892151", "content_id": "f271e9e63282a5df3cf48ccae110d90a0bba1a4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 872, "license_type": "no_license", "max_line_length": 77, "num_lines": 33, "path": "/cuDMRG/apps/sites.py", "repo_name": "xyu40/cuDMRG", "src_encoding": "UTF-8", "text": "from copy import copy\nfrom typing import List\nfrom ..tensor import Index, IndexType\nfrom ..utils import get_logger\n\nlogger = get_logger(__name__)\n\n\nclass Sites:\n def __init__(self, length: int, physicalDim: int) -> None:\n self._length = length\n self._physicalDim = physicalDim\n\n self._physicalIndices = [\n Index(physicalDim, IndexType.PHYSICAL) for i in range(length)\n ]\n\n @property\n def length(self) -> int:\n return self._length\n\n @property\n def physicalDim(self) -> int:\n return self._physicalDim\n\n @property\n def virtualIndices(self) -> List[Index]:\n # must be freshly generated everytime\n return [Index(1, IndexType.VIRTUAL) for i in range(self._length + 1)]\n\n @property\n def physicalIndices(self) -> List[Index]:\n return [copy(idx) for idx in self._physicalIndices]\n" }, { "alpha_fraction": 0.6151202917098999, "alphanum_fraction": 0.6151202917098999, "avg_line_length": 35.375, "blob_id": "6290d16dbee5c542a917395cf7c679ef2f6264d3", "content_id": "c4c690f55bd1660031908c20aec5532f593cddb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 291, "license_type": "no_license", "max_line_length": 77, "num_lines": 8, "path": "/cuDMRG/__init__.py", "repo_name": "xyu40/cuDMRG", "src_encoding": "UTF-8", "text": "from .tensor import Index, Tensor, getEinsumRule\nfrom .apps import (Sites, MPS, MPO, psiHphi, Heisenberg, LinearMult, lanczos,\n DMRG)\n\n__all__ = [\n \"Index\", \"Tensor\", \"getEinsumRule\", \"Sites\", \"MPS\", \"MPO\", \"psiHphi\",\n \"Heisenberg\", \"LinearMult\", \"lanczos\", \"DMRG\"\n]\n" }, { "alpha_fraction": 0.5070422291755676, "alphanum_fraction": 0.5157843828201294, "avg_line_length": 25.740259170532227, "blob_id": "76a2a21eed9527b8f444768098919dc24153db71", "content_id": "86849bbbb10a772f1a5bfecd31ff0c2b80613ad9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2059, "license_type": "no_license", "max_line_length": 69, "num_lines": 77, "path": "/cuDMRG/apps/mps.py", "repo_name": "xyu40/cuDMRG", "src_encoding": "UTF-8", "text": "from copy import copy\nfrom typing import List\nfrom .sites import Sites\nfrom ..tensor import Tensor\nfrom ..utils import get_logger\n\nlogger = get_logger(__name__)\n\n\nclass MPS:\n def __init__(self, sites: Sites, VirtualDim: int = 1) -> None:\n self._center = 0\n self._length = sites.length\n self._physicalDim = sites.physicalDim\n\n physicalIndices = sites.physicalIndices\n virtualIndices = sites.virtualIndices\n for i, vidx in enumerate(virtualIndices):\n if i == 0 or i == self._length:\n vidx.setSize(1)\n else:\n vidx.setSize(VirtualDim)\n\n self._tensors: List[Tensor] = [\n Tensor([\n virtualIndices[i],\n physicalIndices[i],\n virtualIndices[i + 1],\n ]).setZero() for i in range(self._length)\n ]\n\n @property\n def length(self) -> int:\n return self._length\n\n @property\n def physicalDim(self) -> int:\n return self._physicalDim\n\n @property\n def leftIndex(self):\n return copy(self._tensors[0].indices[0])\n\n @property\n def rightIndex(self):\n return copy(self._tensors[-1].indices[-1])\n\n @property\n def tensors(self) -> List[Tensor]:\n return self._tensors\n\n def setZero(self) -> \"MPS\":\n for t in self._tensors:\n t.setZero()\n return self\n\n def setRandom(self) -> \"MPS\":\n for t in self._tensors:\n t.setRandom()\n return self\n\n def setOne(self) -> \"MPS\":\n for t in self._tensors:\n t.setOne()\n return self\n\n def canonicalize(self) -> \"MPS\":\n for i in range(self._length - 1, 0, -1):\n lhs, rhs, _, _ = self._tensors[i].decompose(lhs=[0],\n rhs=[1, 2],\n mergeV=False)\n self._tensors[i] = rhs\n self._tensors[i - 1] *= lhs\n\n self._tensors[0].normalize()\n self._center = 0\n return self\n" }, { "alpha_fraction": 0.5038681030273438, "alphanum_fraction": 0.5078446865081787, "avg_line_length": 35.981285095214844, "blob_id": "b1a6856c916f9502d00a71a043a9893dfedc205b", "content_id": "31764cd9bf313df1ed9c1af39124ae568b6bf9b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13831, "license_type": "no_license", "max_line_length": 79, "num_lines": 374, "path": "/cuDMRG/tensor/tensor.py", "repo_name": "xyu40/cuDMRG", "src_encoding": "UTF-8", "text": "try:\n import cupy as xp\n from cupy import cutensor\n USE_CUPY = True\nexcept ImportError:\n import numpy as xp\n USE_CUPY = False\nfrom numbers import Number\nfrom copy import copy\nfrom functools import reduce\nfrom typing import List, Tuple, Optional, Any\nfrom .index import Index, IndexType, getEinsumRule\nfrom ..utils import get_logger\n\nlogger = get_logger(__name__)\n\n\nclass Tensor:\n def __init__(self,\n indices: List[Index],\n data: Optional[xp.ndarray] = None,\n use_cutensor: bool = False) -> None:\n if data is not None and len(indices) != len(data.shape):\n error_msg = \"indices shape does not match data shape\"\n logger.error(error_msg)\n raise RuntimeError(error_msg)\n\n self._rank = len(indices)\n self._indices = [copy(idx) for idx in indices]\n if data is None:\n self.setZero()\n else:\n self._data = data\n self.use_cutensor = USE_CUPY and use_cutensor\n\n def copy(self) -> \"Tensor\":\n res = Tensor([])\n res._rank = self.rank\n res._indices = [copy(idx) for idx in self._indices]\n res._data = self._data\n return res\n\n def deepcopy(self) -> \"Tensor\":\n res = Tensor([])\n res._rank = self.rank\n res._indices = [copy(idx) for idx in self._indices]\n res._data = self._data.copy()\n return res\n\n def norm(self) -> float:\n return xp.linalg.norm(self._data)\n\n def normalize(self) -> \"Tensor\":\n self._data /= self.norm()\n return self\n\n def setZero(self) -> \"Tensor\":\n self._data = xp.zeros([idx.size for idx in self._indices])\n return self\n\n def setOne(self) -> \"Tensor\":\n self._data = xp.ones([idx.size for idx in self._indices])\n return self\n\n def setRandom(self) -> \"Tensor\":\n self._data = xp.random.random([idx.size for idx in self._indices])\n return self\n\n def raiseIndexLevel(self,\n indexType: IndexType = IndexType.ANYTYPE) -> \"Tensor\":\n for idx in self._indices:\n idx.raiseLevel(indexType)\n return self\n\n def lowerIndexLevel(self,\n indexType: IndexType = IndexType.ANYTYPE) -> \"Tensor\":\n for idx in self._indices:\n idx.lowerLevel(indexType)\n return self\n\n def resetIndexLevel(self,\n indexType: IndexType = IndexType.ANYTYPE) -> \"Tensor\":\n for idx in self._indices:\n idx.resetLevel(indexType)\n return self\n\n def mapIndexLevel(self,\n level_from: int,\n level_to: int,\n indexType: IndexType = IndexType.ANYTYPE) -> \"Tensor\":\n for idx in self._indices:\n idx.mapLevel(level_from, level_to, indexType)\n return self\n\n def transpose(self, axes, inplace=True) -> \"Tensor\":\n if len(set(axes)) != len(axes):\n msg = \"Invalid transpose input\"\n logger.error(msg)\n raise RuntimeError(msg)\n\n transpose_needed = False\n for i, j in enumerate(axes):\n if i != j:\n transpose_needed = True\n break\n\n if inplace:\n if transpose_needed:\n self._indices = [self._indices[i] for i in axes]\n self._data = xp.transpose(self._data, axes=axes)\n return self\n else:\n res = self.copy()\n if transpose_needed:\n res._indices = [res._indices[i] for i in axes]\n res._data = xp.transpose(res._data, axes=axes)\n return res\n\n def diagonal(self) -> \"Tensor\":\n if self._rank % 2 != 0:\n msg = \"Cannot get diagonal from Tensor with odd rank\"\n logger.error(msg)\n raise RuntimeError(msg)\n\n lhs_indices = []\n rhs_indices = []\n for i in range(self._rank):\n for j in range(i + 1, self._rank):\n if self._indices[i].almostIndentical(self._indices[j]):\n lhs_indices.append(i)\n rhs_indices.append(j)\n self.transpose(lhs_indices + rhs_indices)\n\n res_size = [self._indices[i].size for i in lhs_indices]\n diag_size = reduce(lambda x, y: x * y, res_size)\n res_indices = [\n copy(self._indices[i]).resetLevel() for i in lhs_indices\n ]\n res_data = xp.diag(self._data.reshape(diag_size, -1)).reshape(res_size)\n return Tensor(res_indices, res_data)\n\n def decompose(\n self,\n lhs: List[int],\n rhs: List[int],\n mergeV: bool = True,\n cutoff: float = 1e-12,\n maxdim: int = 2147483648\n ) -> Tuple[\"Tensor\", \"Tensor\", xp.array, int]:\n lhs_size = reduce(lambda x, y: x * y,\n [self._indices[i].size for i in lhs])\n rhs_size = reduce(lambda x, y: x * y,\n [self._indices[i].size for i in rhs])\n self.transpose(lhs + rhs)\n u, s, v = xp.linalg.svd(self._data.reshape([lhs_size, rhs_size]),\n full_matrices=False,\n compute_uv=True)\n\n s_norm = xp.linalg.norm(s)\n s_cutoff = (1 - cutoff) * s_norm * s_norm\n s_squared_cumsum = xp.cumsum(xp.power(s, 2))\n\n # dim = 0\n # for i in range(s.size):\n # dim += 1\n # if s_squared_cumsum[i] >= s_cutoff or (dim + 1) > maxdim:\n # break\n dim = int(xp.searchsorted(s_squared_cumsum[:maxdim], s_cutoff)) + 1\n dim = min(dim, s.size, maxdim)\n\n u = u[:, :dim]\n s = xp.clip(s[:dim] * s_norm / xp.sqrt(s_squared_cumsum[dim - 1]),\n a_min=1e-32,\n a_max=None)\n v = v[:dim, :]\n\n if mergeV:\n v = xp.diag(s) @ v\n else:\n u = u @ xp.diag(s)\n\n a = Index(dim)\n lhs_indices = self._indices[:len(lhs)] + [a]\n rhs_indices = [a] + self._indices[len(lhs):]\n lhs_tensor = Tensor(lhs_indices,\n u.reshape([idx.size for idx in lhs_indices]))\n rhs_tensor = Tensor(rhs_indices,\n v.reshape([idx.size for idx in rhs_indices]))\n return lhs_tensor, rhs_tensor, s, dim\n\n @property\n def rank(self) -> int:\n return self._rank\n\n @property\n def size(self) -> int:\n return self._data.size\n\n @property\n def indices(self) -> List[Index]:\n return self._indices\n\n def __add__(self, rhs: Any) -> \"Tensor\":\n if isinstance(rhs, Number) or isinstance(rhs, xp.ndarray):\n res_tensor = self.deepcopy()\n res_tensor._data += rhs\n return res_tensor\n elif isinstance(rhs, Tensor):\n res = self.deepcopy()\n res._data += rhs._data\n return res\n else:\n msg = f\"Unsupported __add__ with rhs of type {type(rhs)}\"\n logger.error(msg)\n raise RuntimeError(msg)\n\n def __iadd__(self, rhs: Any) -> \"Tensor\":\n if isinstance(rhs, Number) or isinstance(rhs, xp.ndarray):\n self._data += rhs\n elif isinstance(rhs, Tensor):\n self._data = self._data + rhs._data\n else:\n msg = f\"Unsupported __iadd__ with rhs of type {type(rhs)}\"\n logger.error(msg)\n raise RuntimeError(msg)\n return self\n\n def __sub__(self, rhs: Any) -> \"Tensor\":\n if isinstance(rhs, Number) or isinstance(rhs, xp.ndarray):\n res_tensor = self.deepcopy()\n res_tensor._data -= rhs\n return res_tensor\n elif isinstance(rhs, Tensor):\n res = self.deepcopy()\n res._data -= rhs._data\n return res\n else:\n msg = f\"Unsupported __sub__ with rhs of type {type(rhs)}\"\n logger.error(msg)\n raise RuntimeError(msg)\n\n def __isub__(self, rhs: Any) -> \"Tensor\":\n if isinstance(rhs, Number) or isinstance(rhs, xp.ndarray):\n self._data -= rhs\n elif isinstance(rhs, Tensor):\n self._data = self._data - rhs._data\n else:\n msg = f\"Unsupported __isub__ with rhs of type {type(rhs)}\"\n logger.error(msg)\n raise RuntimeError(msg)\n return self\n\n def __mul__(self, rhs: Any) -> \"Tensor\":\n if isinstance(rhs, Number) or isinstance(rhs, xp.ndarray):\n res_tensor = self.deepcopy()\n res_tensor._data *= rhs\n return res_tensor\n elif isinstance(rhs, Tensor):\n axes = getEinsumRule(self._indices, rhs._indices)\n res_indices = ([\n idx for i, idx in enumerate(self._indices) if i not in axes[0]\n ] + [\n idx for j, idx in enumerate(rhs._indices) if j not in axes[1]\n ])\n if not self.use_cutensor:\n res_data = xp.tensordot(self._data, rhs._data, axes=axes)\n return Tensor(res_indices, res_data)\n else:\n a = xp.ascontiguousarray(self._data)\n b = xp.ascontiguousarray(rhs._data)\n c = xp.zeros([idx.size for idx in res_indices])\n desc_a = cutensor.create_tensor_descriptor(a)\n desc_b = cutensor.create_tensor_descriptor(b)\n desc_c = cutensor.create_tensor_descriptor(c)\n mode_a = [chr(97 + i) for i in range(self._rank)]\n mode_b = [\n chr(97 + i)\n for i in range(self._rank, self._rank + rhs._rank)\n ]\n for i, j in zip(axes[0], axes[1]):\n mode_b[j] = mode_a[i]\n mode_c = (\n [mode_a[i]\n for i in range(self._rank) if i not in axes[0]] +\n [mode_b[j] for j in range(rhs._rank) if j not in axes[1]])\n mode_a = cutensor.create_mode(*mode_a)\n mode_b = cutensor.create_mode(*mode_b)\n mode_c = cutensor.create_mode(*mode_c)\n cutensor.contraction(1.0, a, desc_a, mode_a, b, desc_b, mode_b,\n 0.0, c, desc_c, mode_c)\n return Tensor(res_indices, c)\n else:\n msg = f\"Unsupported __mul__ with rhs of type {type(rhs)}\"\n logger.error(msg)\n raise RuntimeError(msg)\n\n def __imul__(self, rhs: Any) -> \"Tensor\":\n if isinstance(rhs, Number) or isinstance(rhs, xp.ndarray):\n self._data *= rhs\n elif isinstance(rhs, Tensor):\n axes = getEinsumRule(self._indices, rhs._indices)\n res_indices = ([\n idx for i, idx in enumerate(self._indices) if i not in axes[0]\n ] + [\n idx for j, idx in enumerate(rhs._indices) if j not in axes[1]\n ])\n if not self.use_cutensor:\n self._data = xp.tensordot(self._data, rhs._data, axes=axes)\n else:\n a = xp.ascontiguousarray(self._data)\n b = xp.ascontiguousarray(rhs._data)\n c = xp.zeros([idx.size for idx in res_indices])\n desc_a = cutensor.create_tensor_descriptor(a)\n desc_b = cutensor.create_tensor_descriptor(b)\n desc_c = cutensor.create_tensor_descriptor(c)\n mode_a = [chr(97 + i) for i in range(self._rank)]\n mode_b = [\n chr(97 + i)\n for i in range(self._rank, self._rank + rhs._rank)\n ]\n for i, j in zip(axes[0], axes[1]):\n mode_b[j] = mode_a[i]\n mode_c = (\n [mode_a[i]\n for i in range(self._rank) if i not in axes[0]] +\n [mode_b[j] for j in range(rhs._rank) if j not in axes[1]])\n mode_a = cutensor.create_mode(*mode_a)\n mode_b = cutensor.create_mode(*mode_b)\n mode_c = cutensor.create_mode(*mode_c)\n cutensor.contraction(1.0, a, desc_a, mode_a, b, desc_b, mode_b,\n 0.0, c, desc_c, mode_c)\n self._data = c\n self._indices = res_indices\n self._rank = len(self._indices)\n else:\n msg = f\"Unsupported __imul__ with rhs of type {type(rhs)}\"\n logger.error(msg)\n raise RuntimeError(msg)\n return self\n\n def __rmul__(self, lhs: Any) -> \"Tensor\":\n if isinstance(lhs, Number) or isinstance(lhs, xp.ndarray):\n res_tensor = self.deepcopy()\n res_tensor._data *= lhs\n return res_tensor\n else:\n msg = f\"Unsupported __rmul__ with lhs of type {type(lhs)}\"\n logger.error(msg)\n raise RuntimeError(msg)\n\n def __truediv__(self, rhs: Any) -> \"Tensor\":\n if isinstance(rhs, Number) or isinstance(rhs, xp.ndarray):\n res_tensor = self.deepcopy()\n res_tensor._data /= rhs\n return res_tensor\n else:\n msg = f\"Unsupported __truediv__ with rhs of type {type(rhs)}\"\n logger.error(msg)\n raise RuntimeError(msg)\n\n def __idiv__(self, rhs: Any) -> \"Tensor\":\n if isinstance(rhs, Number) or isinstance(rhs, xp.ndarray):\n self._data /= rhs\n return self\n else:\n msg = f\"Unsupported __idiv__ with rhs of type {type(rhs)}\"\n logger.error(msg)\n raise RuntimeError(msg)\n\n def __str__(self) -> str:\n rank_str = f\"rank = {self._rank}\"\n indices_str = \"\\n\".join([str(idx) for idx in self._indices])\n data_str = str(self._data.shape)\n return \"\\n\".join([rank_str, indices_str, data_str])\n" }, { "alpha_fraction": 0.4503464102745056, "alphanum_fraction": 0.4780600368976593, "avg_line_length": 24.979999542236328, "blob_id": "408b0922b83f4d8cc0c1e1baf55a3cae05a1840e", "content_id": "bbf2ab628433448a0678c58dd338ca3eaf15a39d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1299, "license_type": "no_license", "max_line_length": 71, "num_lines": 50, "path": "/test.py", "repo_name": "xyu40/cuDMRG", "src_encoding": "UTF-8", "text": "from cuDMRG import Index, Tensor, MPS, Sites, Heisenberg, psiHphi, DMRG\n\n\ndef test_basic_tensor():\n a = Index(6)\n b = Index(4)\n c = Index(3)\n d = Index(5)\n\n A = Tensor([a, b, c]).setRandom()\n B = Tensor([c, d]).setRandom()\n C = A * B\n C.normalize()\n\n if not -1e-9 <= (C.norm() - 1.0) <= 1e-9:\n print(\"Basic test failed\")\n else:\n lhs, rhs, _, _ = C.decompose(lhs=[0, 1],\n rhs=[2],\n mergeV=True,\n cutoff=1e-9,\n maxdim=8)\n\n if not -1e-9 <= (lhs * rhs - C).norm() <= 1e-9:\n print(\"Basic tensor test failed\")\n else:\n print(\"Basic tensor test passed\")\n\n\ndef test_basic_mps_mpo():\n sites = Sites(10, 2)\n psi = MPS(sites, 1).setOne().canonicalize()\n H = Heisenberg(sites, J=0, h=1).build()\n if not -1e-9 <= psiHphi(psi, H, psi) <= 1e-9:\n print(\"Basic mps mpo test failed\")\n else:\n print(\"Basic mps mpo test passed\")\n\n\ndef test_basic_dmrg():\n sites = Sites(100, 2)\n H = Heisenberg(sites, J=1, h=0).build()\n model = DMRG(sites, H)\n model.run()\n\n\nif __name__ == \"__main__\":\n test_basic_tensor()\n test_basic_mps_mpo()\n test_basic_dmrg()\n" }, { "alpha_fraction": 0.7194244861602783, "alphanum_fraction": 0.7194244861602783, "avg_line_length": 33.75, "blob_id": "06cbba1bce3c1eb2147cd850d808791c4d159ced", "content_id": "bfe690b7e5bdd7c44e61a20a4eb21c76efb50bb8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 139, "license_type": "no_license", "max_line_length": 59, "num_lines": 4, "path": "/cuDMRG/tensor/__init__.py", "repo_name": "xyu40/cuDMRG", "src_encoding": "UTF-8", "text": "from .index import Index, IndexType, getEinsumRule\nfrom .tensor import Tensor\n\n__all__ = [\"Index\", \"IndexType\", \"Tensor\", \"getEinsumRule\"]\n" }, { "alpha_fraction": 0.5727993249893188, "alphanum_fraction": 0.576554000377655, "avg_line_length": 26.872093200683594, "blob_id": "f34cbedaaf0b46fc14c9d95313a13256a70048a3", "content_id": "8263053cb5f551d58ed454690150dafb9addc310", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2397, "license_type": "no_license", "max_line_length": 75, "num_lines": 86, "path": "/cuDMRG/apps/mpo.py", "repo_name": "xyu40/cuDMRG", "src_encoding": "UTF-8", "text": "from abc import ABC, abstractmethod\nfrom copy import copy\nfrom typing import List\nfrom .sites import Sites\nfrom .mps import MPS\nfrom ..tensor import Tensor\nfrom ..utils import get_logger\n\nlogger = get_logger(__name__)\n\n\nclass MPO(ABC):\n def __init__(self, sites: Sites, VirtualDim: int = 1) -> None:\n self._length = sites.length\n self._physicalDim = sites.physicalDim\n\n physicalIndices = sites.physicalIndices\n physicalIndicesPrime = [\n copy(idx).raiseLevel() for idx in physicalIndices\n ]\n virtualIndices = sites.virtualIndices\n for i, vidx in enumerate(virtualIndices):\n if i == 0 or i == self._length:\n vidx.setSize(1)\n else:\n vidx.setSize(VirtualDim)\n\n self._tensors: List[Tensor] = [\n Tensor([\n virtualIndices[i],\n physicalIndicesPrime[i],\n physicalIndices[i],\n virtualIndices[i + 1],\n ]).setZero() for i in range(self._length)\n ]\n\n @property\n def length(self) -> int:\n return self._length\n\n @property\n def physicalDim(self) -> int:\n return self._physicalDim\n\n @property\n def tensors(self) -> List[Tensor]:\n return self._tensors\n\n @property\n def leftIndex(self):\n return copy(self._tensors[0].indices[0])\n\n @property\n def rightIndex(self):\n return copy(self._tensors[-1].indices[-1])\n\n @abstractmethod\n def build(self) -> \"MPO\":\n pass\n\n\ndef psiHphi(psi: MPS, H: MPO, phi: MPS) -> float:\n if (psi.length != H.length or psi.length != phi.length\n or psi.physicalDim != H.physicalDim\n or psi.physicalDim != phi.physicalDim):\n msg = \"Input dimensions do not match\"\n logger.error(msg)\n raise RuntimeError(msg)\n\n left_indices = [psi.leftIndex.raiseLevel(), H.leftIndex, phi.leftIndex]\n res = Tensor(left_indices).setOne()\n\n if psi is phi:\n for i in range(H.length):\n res *= psi.tensors[i].copy().raiseIndexLevel()\n res *= H.tensors[i]\n res *= phi.tensors[i]\n\n else:\n for i in range(H.length):\n res *= psi.tensors[i].raiseIndexLevel()\n res *= H.tensors[i]\n res *= phi.tensors[i]\n psi.tensors[i].lowerIndexLevel()\n\n return res._data.reshape(res._data.size)[0]\n" }, { "alpha_fraction": 0.49531763792037964, "alphanum_fraction": 0.5064540505409241, "avg_line_length": 33.35652160644531, "blob_id": "b13dd1dc0a63dbec98210103337923b05fff467e", "content_id": "e345c3a2a3b458c54c38f00aa854f2fbfb61a873", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3951, "license_type": "no_license", "max_line_length": 77, "num_lines": 115, "path": "/cuDMRG/apps/dmrg.py", "repo_name": "xyu40/cuDMRG", "src_encoding": "UTF-8", "text": "try:\n import cupy as xp\nexcept ImportError:\n import numpy as xp\nfrom copy import deepcopy\nfrom typing import Dict, Tuple, Any, Optional\nfrom .sites import Sites\nfrom .mps import MPS\nfrom .mpo import MPO\nfrom .solver import LinearMult, lanczos\nfrom ..tensor import Tensor\nfrom ..utils import get_logger\n\nlogger = get_logger(__name__)\n\nCONFIG: Dict[str, Any] = {\n \"num_sweeps\": 10,\n \"svd_error\": 1e-16,\n \"max_bond_dimension\": 1000,\n \"lanczos_search_size\": 3,\n \"lanczos_num_restart\": 1,\n \"lanczos_smallest\": True,\n \"log_every_step\": False\n}\n\n\nclass DMRG:\n def __init__(self,\n sites: Sites,\n H: MPO,\n psi: MPS = None,\n config: Optional[Dict[str, Any]] = None) -> None:\n if sites.length <= 2:\n msg = \"Length of the problem needs to be > 2\"\n logger.error(msg)\n raise RuntimeError(msg)\n\n self._sites = sites\n self._H = H\n\n if psi is None:\n self._psi = MPS(sites, 1).setRandom().canonicalize()\n else:\n self._psi = psi.canonicalize()\n\n self._config = deepcopy(CONFIG)\n if config is not None:\n for key in config:\n self._config[key] = config[key]\n\n self._lEnvs: Dict[int, Tensor] = {}\n self._rEnvs: Dict[int, Tensor] = {}\n self._buildEnv()\n\n def run(self) -> None:\n L = self._sites.length\n max_dim = 0\n for sweep in range(self._config[\"num_sweeps\"]):\n for i in range(1, L):\n ev, dim = self._update(i, move_right=True)\n max_dim = max(dim, max_dim)\n for i in range(L - 1, 0, -1):\n ev, dim = self._update(i, move_right=False)\n max_dim = max(dim, max_dim)\n logger.info(f\"sweep = {sweep}, E = {ev}, max_dim = {max_dim}\")\n\n def _buildEnv(self):\n L = self._sites.length\n\n self._lEnvs[0] = Tensor([\n self._psi.leftIndex.raiseLevel(), self._H.leftIndex,\n self._psi.leftIndex\n ]).setOne()\n\n self._rEnvs[L - 1] = Tensor([\n self._psi.rightIndex.raiseLevel(), self._H.rightIndex,\n self._psi.rightIndex\n ]).setOne()\n\n for i in range(L - 2, -1, -1):\n self._rEnvs[i] = (self._psi.tensors[i + 1].raiseIndexLevel() *\n self._rEnvs[i + 1])\n self._rEnvs[i] *= self._H.tensors[i + 1]\n self._rEnvs[i] *= self._psi.tensors[i + 1].lowerIndexLevel()\n\n def _update(self, i: int, move_right: bool = True) -> Tuple[float, int]:\n x = self._psi.tensors[i - 1] * self._psi.tensors[i]\n op = LinearMult(self._lEnvs[i - 1] * self._H.tensors[i - 1],\n self._H.tensors[i] * self._rEnvs[i], x)\n\n ev, x = lanczos(op, x, self._config[\"lanczos_search_size\"],\n self._config[\"lanczos_num_restart\"],\n self._config[\"lanczos_smallest\"])\n\n self._psi.tensors[i - 1], self._psi.tensors[i], s, dim = x.decompose(\n [0, 1], [2, 3], move_right, self._config[\"svd_error\"],\n self._config[\"max_bond_dimension\"])\n\n if self._config[\"log_every_step\"]:\n vnEE = -xp.sum(s * xp.log(s))\n logger.info(f\"Optimized bond ({i-1}, {i}), \"\n f\"dim = {dim}, vnEE = {vnEE}, E = {ev}\")\n\n if move_right:\n self._lEnvs[i] = (self._lEnvs[i - 1] *\n self._psi.tensors[i - 1].raiseIndexLevel())\n self._lEnvs[i] *= self._H.tensors[i - 1]\n self._lEnvs[i] *= self._psi.tensors[i - 1].lowerIndexLevel()\n else:\n self._rEnvs[i - 1] = (self._psi.tensors[i].raiseIndexLevel() *\n self._rEnvs[i])\n self._rEnvs[i - 1] *= self._H.tensors[i]\n self._rEnvs[i - 1] *= self._psi.tensors[i].lowerIndexLevel()\n\n return ev, dim\n" } ]
14
JosXa/twitch-native-streaming
https://github.com/JosXa/twitch-native-streaming
2338e713a2bfde57722e0e580a1dc3eb8991d3e0
069f4348606ef6420bd29431a12cfe3497428213
cb84d72f66d1ca21c4c04ef22a90e1518883f85d
refs/heads/master
2021-06-01T04:05:03.691948
2016-06-26T22:49:44
2016-06-26T22:49:44
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5722105503082275, "alphanum_fraction": 0.573894739151001, "avg_line_length": 30.456953048706055, "blob_id": "703e2cce5d7748928212c789bb48321c658ad3cc", "content_id": "e7775bdd4bf0eb69f63f0de26baaffb119ed07dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4750, "license_type": "no_license", "max_line_length": 114, "num_lines": 151, "path": "/twitch/twitch.py", "repo_name": "JosXa/twitch-native-streaming", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport re\nimport json\nfrom pprint import pprint\nfrom argparse import ArgumentParser\nfrom json import JSONDecodeError\nfrom subprocess import call\nimport urllib\nfrom os.path import expanduser\nfrom urllib.parse import urlparse\nimport requests\nimport sys\nfrom past.builtins import raw_input\n\n# call watch() if no arguments are supplied\nWATCH_AS_DEFAULT = True\n\n\nclass Twitch(object):\n _channel_list = []\n _storage_file = expanduser(\"~/.twitch-channels\")\n\n def __init__(self):\n self.load_channels()\n\n def load_channels(self):\n try:\n self._channel_list = json.load(open(self._storage_file, 'r'))\n except (JSONDecodeError, FileNotFoundError):\n self.save_channels()\n\n def save_channels(self):\n json.dump(self._channel_list, open(self._storage_file, 'w'))\n\n def add_channel(self, name: str):\n name = name.lower()\n if name not in self._channel_list:\n self._channel_list.append(name.lower())\n self.save_channels()\n return True\n else:\n return False\n\n def remove_channel(self, name: str):\n if name in self._channel_list:\n self._channel_list.remove(name.lower())\n self.save_channels()\n return True\n else:\n return False\n\n @property\n def channels(self):\n return self._channel_list\n\n\ndef query_streams(channel_list):\n print(\"Looking for currently streaming channels...\")\n online_streams = []\n for channel in channel_list:\n url = 'https://api.twitch.tv/kraken/streams/' + channel\n response = requests.get(url)\n\n # try:\n s = response.json()\n s = s[\"stream\"] if \"stream\" in s else None\n if not s:\n continue\n\n stream_url = s[\"channel\"][\"url\"]\n streamer = s[\"channel\"][\"display_name\"]\n game = s[\"game\"]\n stream_desc = s[\"channel\"][\"status\"]\n online_streams.append({'name': streamer, 'url': stream_url, 'game': game, 'desc': stream_desc})\n\n return online_streams\n\n\ndef watch(streams):\n if len(streams) > 0:\n print(\"Channels online:\")\n i = 1\n for s in streams:\n print(\"({}) {}: [{}] {}\".format(i, s['name'], s['game'], s['desc']))\n print(\"{} {}\".format(' ' * (2 + len(str(i))), s['url']))\n i += 1\n\n while True:\n print()\n input = raw_input(\"Enter number of stream to watch: \")\n\n try:\n stream_number = int(input)\n break\n except ValueError:\n print(\"Please specify the number of the stream to watch.\")\n continue\n\n command = \"livestreamer {} best\".format(streams[stream_number - 1]['url'])\n call(command.split(), shell=False)\n\n else:\n print(\"No streams online.\")\n\n\ndef main():\n parser = ArgumentParser(\n description=\"Add twitch channels and watch them directly with your native video application.\")\n parser.add_argument(\"watch\", nargs='?', help=\"Start watching streams!\")\n parser.add_argument(\"-a\", \"--add\", help=\"Add one or more channels by name or twitch url\", type=str, nargs='+')\n parser.add_argument(\"-r\", \"--remove\", help=\"Remove one or more channels by name\", type=str, nargs='+')\n parser.add_argument(\"-l\", \"--list\", help=\"List all added channels\", action='store_true')\n args = parser.parse_args()\n\n twitch = Twitch()\n\n if args.add:\n for channel in args.add:\n parsed = urlparse(channel)\n is_url = bool(parsed.scheme)\n\n if is_url:\n if \"twitch.tv\" not in parsed.netloc:\n sys.exit(\"The url {} is invalid.\".format(channel))\n channel = str(parsed.path).split('/').__getitem__(1)\n\n if twitch.add_channel(channel):\n print(\"Added {} to the list of channels.\".format(channel))\n else:\n print(\"{} is already in the list of channels.\".format(channel))\n\n if args.remove:\n for channel in args.remove:\n if twitch.remove_channel(channel):\n print(\"Removed {} from the list of channels.\".format(channel))\n else:\n print(\"{} is not in the list of channels. Nothing removed.\".format(channel))\n\n if args.list:\n print('Your channels: ' + ', '.join(twitch.channels))\n\n # default action\n if args.watch or (not any(vars(args).values()) and WATCH_AS_DEFAULT):\n if len(twitch.channels) == 0:\n parser.print_help()\n print()\n print('You have not added any channels yet. Try\\n twitch -a [NAME/URL]')\n else:\n # initialize\n watch(query_streams(twitch.channels))\n" }, { "alpha_fraction": 0.5456521511077881, "alphanum_fraction": 0.550000011920929, "avg_line_length": 22, "blob_id": "5d47062c752abc2bde21397fb96d027b7779e5b5", "content_id": "2c0318e457d7b92790deff9a32d28497377113dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 460, "license_type": "no_license", "max_line_length": 63, "num_lines": 20, "path": "/setup.py", "repo_name": "JosXa/twitch-native-streaming", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nfrom setuptools import setup\n\nsetup(name='twitch',\n version='1.0',\n description='Twitch Native Streaming',\n author='Joscha Götzer',\n author_email='[email protected]',\n url='http://github.com/Rostgnom/twitch-native-streaming',\n scripts=['twitch/twitch.py'],\n packages=['twitch'],\n\n # Executable\n entry_points={\n 'console_scripts': [\n 'twitch = twitch:main',\n ],\n },\n )\n" }, { "alpha_fraction": 0.7699386477470398, "alphanum_fraction": 0.7730061411857605, "avg_line_length": 28.636363983154297, "blob_id": "898c99f51e59bf608b1018974cc04a0199ef3e12", "content_id": "79edad9be23c079cff89c8546917328f1ebe0502", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 326, "license_type": "no_license", "max_line_length": 104, "num_lines": 11, "path": "/README.md", "repo_name": "JosXa/twitch-native-streaming", "src_encoding": "UTF-8", "text": "# twitch-native-streaming\nSee which twitch channels are online and watch on your native client\n\nJust my personal tool for viewing twitch without a browser, but probably some peps might find it useful.\n\n## Requirements\nlivestreamer\n`$ sudo pacman -S livestreamer`\n\n## Usage\nRun `$ python3 twitch --help` to see what you can do\n" } ]
3
cedricp/color_tray
https://github.com/cedricp/color_tray
70a467e4f1624a3df06baf19aac4aa9327fd709e
04eb7a7ba1f967ff0d06ab415453818db2fac8d1
f025aefcd61c038761667f36b64792dad15a7473
refs/heads/master
2023-06-12T10:05:55.861758
2021-07-08T12:31:07
2021-07-08T12:31:07
384,116,771
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 19, "blob_id": "aeeab0de1ad7268fb430596d81c41e469ad56234", "content_id": "b147502e4cf9f24476eaeee6109fafa62eeda545", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 60, "license_type": "no_license", "max_line_length": 45, "num_lines": 3, "path": "/README.md", "repo_name": "cedricp/color_tray", "src_encoding": "UTF-8", "text": "# color_tray\n\nLinux Systray applet to select color profiles\n" }, { "alpha_fraction": 0.5730358362197876, "alphanum_fraction": 0.5801612734794617, "avg_line_length": 32.97452163696289, "blob_id": "dece21042f8c1eba858d6c2b53774a886a205f91", "content_id": "588d92d41bf83cab7487364569aac1dd48afd71d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5333, "license_type": "no_license", "max_line_length": 132, "num_lines": 157, "path": "/color_tray.py", "repo_name": "cedricp/color_tray", "src_encoding": "UTF-8", "text": "#!/bin/python3\n\nimport wx.adv\nimport glob, os\n\nimport re\nimport subprocess\nfrom functools import partial\n\nSCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__))\nTRAY_TOOLTIP = 'Color Management'\nTRAY_ICON = SCRIPT_ROOT+'/icon.png'\n\ndispwincmd=\"/home/cedric/apps/Argyll_V2.1.2/bin/dispwin\"\n\ndef get_display_profiles():\n colrmgr = subprocess.run([\"colormgr\", \"get-devices-by-kind\", \"display\"],\n check = True,\n stdout=subprocess.PIPE)\n\n devices = []\n currentdev = None\n lines = [b.decode('utf-8') for b in colrmgr.stdout.split(b'\\n')]\n\n for i, line in enumerate(lines):\n if \"Object Path:\" in line[:12]:\n if currentdev is not None:\n devices.append(currentdev)\n currentdev = {}\n currentdev[\"profiles\"] = []\n currentdev[\"path\"] = line[15:]\n if line.startswith(\"Model:\"):\n currentdev[\"model\"] = line[15:]\n if line.startswith(\"Enabled:\"):\n currentdev[\"enabled\"] = line[15:]\n if line.startswith(\"Serial:\"):\n currentdev[\"serial\"] = line[15:]\n if line.startswith(\"Device ID:\"):\n currentdev[\"deviceid\"] = line[15:]\n if line.startswith(\"Metadata: XRANDR_name=\"):\n currentdev[\"xrandr_name\"] = line[27:]\n if \"Profile \" in line[:8]:\n profileid = line[15:]\n profilepath = lines[i+1][15:]\n currentdev[\"profiles\"].append((profileid, profilepath))\n if currentdev is not None:\n devices.append(currentdev)\n return devices\n\ndef get_dispwin_monitor_id(xrandr_name):\n dspwin = subprocess.run([dispwincmd, \"-h\"],\n check = False,\n stderr=subprocess.PIPE)\n lines = [b.decode('utf-8') for b in dspwin.stderr.split(b'\\n')]\n\n for i, line in enumerate(lines):\n if xrandr_name in line:\n match = re.search(\"[\\d]+ =\", line)\n monitor_id = line[match.start():match.end()-1]\n return monitor_id\n \n\ndef make_device_default(path, id, xrandr_name, iccpath):\n xrandr_id = get_dispwin_monitor_id(xrandr_name)\n if id != \"Disable\":\n dspwin = subprocess.run([dispwincmd, \"-d\", xrandr_id, \"-v\", \"-c\", \"-I\", iccpath],\n check = False,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n colrmgr = subprocess.run([\"colormgr\", \"device-set-enabled\", path, \"True\"],\n check = True,\n stdout=subprocess.PIPE)\n colrmgr = subprocess.run([\"colormgr\", \"device-make-profile-default\", path, id],\n check = True,\n stdout=subprocess.PIPE)\n else:\n dspwin = subprocess.run([dispwincmd, \"-d\", xrandr_id, \"-U\"],\n check = False,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n colrmgr = subprocess.run([\"colormgr\", \"device-set-enabled\", path, \"False\"],\n check = True,\n stdout=subprocess.PIPE)\n\nclass TaskBarIcon(wx.adv.TaskBarIcon):\n def __init__(self, frame):\n self.frame = frame\n super(TaskBarIcon, self).__init__()\n self.set_icon(TRAY_ICON)\n self.Bind(wx.adv.EVT_TASKBAR_LEFT_DOWN, self.on_left_down)\n\n def create_color_menu_item(self, menu, item, path, xrandr_name, disabled):\n label = item[1].split(\"/\")[-1]\n if disabled:\n label = \"* \" + label\n menuitem = wx.MenuItem(menu, -1, label)\n menu.Bind(wx.EVT_MENU, partial(self.on_change_profile, (path, item, xrandr_name, item[1])), id=menuitem.GetId())\n menu.Append(menuitem)\n if disabled:\n menuitem.Enable(False)\n return menuitem\n\n def create_menu_item(self, menu, label, func):\n menuitem = wx.MenuItem(menu, -1, label)\n menu.Bind(wx.EVT_MENU, func, id=menuitem.GetId())\n menu.Append(menuitem)\n return menuitem\n\n def create_submenu(self, menu, label, items):\n first = True\n if items[\"enabled\"] == \"No\":\n first = False\n submenu = wx.Menu()\n menu.AppendSubMenu(submenu, label[7:])\n for item in items[\"profiles\"]:\n self.create_color_menu_item(submenu, item, items[\"path\"], items[\"xrandr_name\"], first)\n first = False\n self.create_color_menu_item(submenu, [\"Disable\", \"/Disable\"], items[\"path\"], items[\"xrandr_name\"], items[\"enabled\"] == \"No\")\n\n def CreatePopupMenu(self):\n displays = get_display_profiles()\n menu = wx.Menu()\n for display in displays:\n self.create_submenu(menu, display[\"deviceid\"], display)\n menu.AppendSeparator()\n self.create_menu_item(menu, 'Exit', self.on_exit)\n return menu\n\n def set_icon(self, path):\n icon = wx.Icon(wx.Bitmap(path))\n self.SetIcon(icon, TRAY_TOOLTIP)\n\n def on_left_down(self, event):\n pass\n\n def on_exit(self, event):\n wx.CallAfter(self.Destroy)\n self.frame.Close()\n\n def on_change_profile(self, sel, e):\n path = sel[0]\n profile = sel[1][0]\n xrandr_name = sel[2]\n iccpath = sel[3]\n make_device_default(path, profile, xrandr_name, iccpath)\n\nclass App(wx.App):\n def OnInit(self):\n frame=wx.Frame(None)\n self.SetTopWindow(frame)\n TaskBarIcon(frame)\n return True\n\ndef main():\n app = App(False)\n app.MainLoop()\n\nif __name__ == '__main__':\n main()" } ]
2
contiv/contiv-ui
https://github.com/contiv/contiv-ui
24471b59ecdbf2706aec7076361b6b827e7d3eb2
b68d6df3c1c11f0c1776a4dc6c1f070cb68926b9
b38f2b1d4a68b62454ffdb5616882aba6739a326
refs/heads/master
2023-03-23T01:51:54.727001
2017-10-09T23:55:04
2017-10-09T23:55:04
52,047,595
10
13
null
2016-02-18T23:49:31
2017-06-06T09:48:55
2017-10-16T18:15:31
JavaScript
[ { "alpha_fraction": 0.5206853747367859, "alphanum_fraction": 0.5206853747367859, "avg_line_length": 37.337276458740234, "blob_id": "3e6ef4ca5b1e70f92e4ace60c11eab163cc2c4d8", "content_id": "61d7bbae17f14d041b3051761c8643cfe705c0e5", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6478, "license_type": "permissive", "max_line_length": 125, "num_lines": 169, "path": "/app/components/models/collection.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "import { Http, Response } from '@angular/http';\nimport { BaseCollection } from \"./basecollection\";\nimport * as _ from 'lodash';\nimport {ApiService} from \"../utils/apiservice\";\nimport {isUndefined} from \"util\";\n\nexport class Collection extends BaseCollection {\n inspectStats: any;\n cudOperationFlag: boolean;\n\n /**\n * Extends BaseCollection class to do create, update and delete using POST, PUT and DELETE verbs.\n * @param $http\n * @param $q\n * @param url Used for doing HTTP GET and fetch objects from server\n * @constructor\n */\n constructor(http: Http, url, apiService: ApiService) {\n super(http, url, apiService);\n this.inspectStats = {};\n this.cudOperationFlag = false;\n }\n\n /**\n *\n * @param model\n * @param url Optional if not passed it is constructed using key and url passed in constructor\n * @returns {*}\n */\n create(model, url, key?:string):Promise<any> {\n var collection = this;\n if(isUndefined(key))\n key='key';\n var promise = new Promise(function (resolve, reject) {\n if (url === undefined) url = collection.url + model.key + '/';\n collection.cudOperationFlag = true;\n collection.apiService.post(url, model).map((res: Response) => collection.filterAsyncReq(res)).toPromise()\n .then(function successCallback(response) {\n var responseData = response;\n //For rest endpoints that do not return created json object in response\n if ((responseData === undefined) || (responseData === '')) {\n responseData = model;\n }\n _.remove(collection.models, function (n) {\n return n[key] == model[key];\n });\n collection.models.push(responseData);\n collection.cudOperationFlag = false;\n resolve(responseData);\n }, function errorCallback(response) {\n collection.cudOperationFlag = false;\n reject(response);\n });\n });\n\n\n return promise;\n };\n\n /**\n * This is for netmaster specific endpoints and used by netmaster objects only.\n * TODO: Generalize\n * @param model\n * @param url Optional\n * @returns {*}\n */\n save(model):Promise<any> {\n var collection = this;\n var promise = new Promise(function (resolve, reject) {\n var url = collection.url + model.key + '/';\n collection.cudOperationFlag = true;\n collection.apiService.put(url, model).map((res: Response) => collection.filterAsyncReq(res)).toPromise()\n .then(function successCallback(response) {\n _.remove(collection.models, function (n) {\n return n['key'] == model['key'];\n });\n collection.models.push(response);\n collection.cudOperationFlag = false;\n resolve(response);\n }, function errorCallback(response) {\n collection.cudOperationFlag = false;\n reject(response);\n });\n });\n return promise;\n };\n\n /**\n * This is for netmaster specific endpoints and used by netmaster objects only.\n * TODO: Generalize\n * @param model\n * @returns {*}\n */\n delete(model):Promise<any> {\n var collection = this;\n var promise = new Promise(function (resolve, reject) {\n var url = collection.url + model.key + '/';\n collection.cudOperationFlag = true;\n collection.apiService.delete(url).map((res: Response) => collection.filterAsyncReq(res)).toPromise()\n .then(function successCallback(response) {\n _.remove(collection.models, function (n) {\n return n['key'] == model['key'];\n });\n collection.cudOperationFlag = false;\n resolve(response);\n }, function errorCallback(response) {\n collection.cudOperationFlag = false;\n reject(response);\n });\n });\n return promise;\n };\n\n /**\n *\n * @param key\n * @param keyname\n * @param url Optional if not passed it is constructed using key and url passed in constructor\n * @returns {*}\n */\n deleteUsingKey(key, keyname, url):Promise<any> {\n var collection = this;\n if (keyname === undefined) keyname = 'key';\n var promise = new Promise(function (resolve, reject) {\n if (url === undefined) url = collection.url + key + '/';\n collection.cudOperationFlag = true;\n collection.apiService.delete(url).map((res: Response) => {\n if (res.statusText==='No Content')\n return key;\n else\n return collection.filterAsyncReq(res);\n }).toPromise()\n .then(function successCallback(response) {\n _.remove(collection.models, function (n) {\n return n[keyname] == key;\n });\n collection.cudOperationFlag = false;\n resolve(response);\n }, function errorCallback(response) {\n collection.cudOperationFlag = false;\n reject(response);\n });\n });\n return promise;\n };\n\n\n getInspectByKey(key, url, refresh): Promise<any>{\n var collection = this;\n var promise = new Promise(function (resolve, reject) {\n if(key in collection.inspectStats && refresh == false){\n resolve(collection.inspectStats[key]);\n }\n else {\n collection.apiService.get(url + key + '/').map((res: Response) => collection.filterAsyncReq(res)).toPromise()\n .then(function successCallback(response) {\n var responseStats = response;\n collection.inspectStats[key] = responseStats;\n resolve(responseStats);\n }\n , function errorCallback(error) {\n reject(error);\n });\n }\n });\n\n return promise;\n };\n}" }, { "alpha_fraction": 0.6473429799079895, "alphanum_fraction": 0.6763284802436829, "avg_line_length": 19.799999237060547, "blob_id": "5d472e97d01b876f2f97aafb3bed74d3d891201e", "content_id": "bb935792fc0879b4d6cdeef291a10e60e64962cd", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 207, "license_type": "permissive", "max_line_length": 42, "num_lines": 10, "path": "/app/settings/settingsmenu.component.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 11/3/16.\n */\nimport { Component } from \"@angular/core\";\n\n@Component({\n selector: 'settingsmenu',\n templateUrl: './settingsmenu.html'\n})\nexport class SettingsMenuComponent {}" }, { "alpha_fraction": 0.5415751338005066, "alphanum_fraction": 0.5431440472602844, "avg_line_length": 29.941747665405273, "blob_id": "0f0673491e293e74b4d48b2de7cb0368df9f0f46", "content_id": "a58f80a19a2f2d3b61e4ae632592c217e459c267", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3187, "license_type": "permissive", "max_line_length": 117, "num_lines": 103, "path": "/app/components/utils/authguard.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 11/4/16.\n */\nimport { Injectable } from '@angular/core';\nimport { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot, CanActivateChild } from '@angular/router';\nimport { Subject } from \"rxjs\";\nimport { Observable } from 'rxjs/Observable';\nimport { AuthService } from \"./authservice\";\nimport { AuthMatrix } from \"./authMatrix\";\nimport { isNull } from \"util\";\nimport { FirstRunService } from \"./firstrunservice\";\n\n@Injectable()\nexport class AuthGuard implements CanActivate, CanActivateChild {\n\n accessMatrix:any;\n unguardedUrls: string[];\n\n constructor(private authService: AuthService,\n private firstRunService: FirstRunService,\n private router: Router) {\n this.accessMatrix = AuthMatrix;\n }\n\n canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {\n let url: string = state.url;\n return this.checkLogin(url);\n }\n\n canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {\n return this.canActivate(route, state);\n }\n\n checkLogin(url: string):any {\n\n if (this.authService.isLoggedIn) {\n if (this.checkAccess(url))\n if (this.authService.validateExpiry())\n return this.performFirstrunCheck(url);\n else{\n this.loadLogin(url);\n return false;\n }\n else{\n this.router.navigate(['/unauthorized']);\n return false;\n }\n\n }\n // Validate Token Expiration\n if (!isNull(localStorage.getItem(\"authToken\"))){\n this.authService.extractBody();\n if(this.authService.validateExpiry()){\n this.authService.isLoggedIn = true;\n if(this.checkAccess(url)){\n return this.performFirstrunCheck(url);\n }\n else{\n this.router.navigate(['/unauthorized']);\n return false;\n }\n }\n }\n\n this.loadLogin(url);\n return false;\n }\n\n loadLogin(url: string): void{\n // Store the attempted URL for redirecting\n this.authService.redirectUrl = url;\n // Navigate to the login page\n this.router.navigate(['/login']);\n }\n\n checkAccess(url:string): boolean{\n return this.authService.checkAccess(url);\n }\n\n isFirstRun():Promise<boolean>{\n return this.firstRunService.setFirstRun();\n }\n\n\n performFirstrunCheck(url: string): Promise<any>{\n return this.isFirstRun()\n .then((firstrun: boolean) => {\n if (((!/firstrun/.test(url)) && !firstrun) || ((/firstrun/.test(url) && (firstrun)))) {\n return true;\n } else {\n if(firstrun) {\n this.router.navigate(['/m/firstrun']);\n return false\n } else {\n this.router.navigate(['/m/dashboard']);\n return false;\n }\n }\n\n });\n }\n\n}\n" }, { "alpha_fraction": 0.5798319578170776, "alphanum_fraction": 0.605042040348053, "avg_line_length": 17.384614944458008, "blob_id": "ed488c45135d7d0480cfeeb6dcd68e09f01df2a6", "content_id": "f3c1cdc030da5c2a1ba4b609e6e0505e3b671438", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 238, "license_type": "permissive", "max_line_length": 42, "num_lines": 13, "path": "/app/settings/ldapconfiguration.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 12/18/16.\n */\nimport { Component } from \"@angular/core\";\n@Component({\n selector: 'ldapconfig',\n template:\n `\n <ldapsettings></ldapsettings>\n `\n})\n\nexport class LdapConfigComponent{}" }, { "alpha_fraction": 0.5852130055427551, "alphanum_fraction": 0.5921052694320679, "avg_line_length": 30.940000534057617, "blob_id": "1181e01646741c6675e9854793ccf671d28bc503", "content_id": "2c475318e870a75e2cc1e45d7abba3b82a0eef06", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1596, "license_type": "permissive", "max_line_length": 79, "num_lines": 50, "path": "/app/network_policies/contractgrouplist.component.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 12/13/16.\n */\nimport { Component, OnInit, OnDestroy, NgZone } from \"@angular/core\";\nimport { ContractGroupsModel } from \"../components/models/contractgroupsmodel\";\nimport { CRUDHelperService } from \"../components/utils/crudhelperservice\";\nimport { Subscription, Observable } from \"rxjs\";\n\n@Component({\n selector: 'contractgrouplist',\n templateUrl: './contractgrouplist.html'\n})\nexport class ContractGroupListComponent implements OnInit, OnDestroy {\n private refresh:Subscription;\n private contractGroups:any[];\n\n constructor(private contractGroupsModel:ContractGroupsModel,\n private crudHelperService:CRUDHelperService,\n private ngZone:NgZone) {\n this.refresh = Observable.interval(5000).subscribe(() => {\n this.getContractGroups(true);\n })\n }\n\n ngOnInit() {\n this.crudHelperService.startLoader(this);\n this.getContractGroups(false);\n }\n\n getContractGroups(reload:boolean) {\n let component = this;\n this.contractGroupsModel.get(reload)\n .then((result) => {\n component.contractGroups = result;\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n\n },\n (error) => {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n });\n }\n\n ngOnDestroy() {\n this.refresh.unsubscribe();\n }\n}" }, { "alpha_fraction": 0.6192758083343506, "alphanum_fraction": 0.6219382286071777, "avg_line_length": 39.83695602416992, "blob_id": "3e3a5b425cb1f2e3298eac275737e97e82b093b7", "content_id": "2eaeff518e5cbd8ebb39759cc8766332a8df8594", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3756, "license_type": "permissive", "max_line_length": 154, "num_lines": 92, "path": "/app/network_policies/isolationpolicystats.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 12/12/16.\n */\n\n\n\n\n\nimport {Component, OnInit, OnDestroy, Input, NgZone} from \"@angular/core\";\nimport {CRUDHelperService} from \"../components/utils/crudhelperservice\";\nimport {Subscription, Observable} from \"rxjs\";\nimport {InspectService} from \"../components/utils/inspectservice\";\nimport {ContivGlobals} from \"../components/models/contivglobals\";\nimport {isUndefined} from \"util\";\nimport {PoliciesModel} from \"../components/models/policiesmodel\";\n\n@Component({\n selector: 'isolationpolicystats',\n templateUrl: './isolationpolicystats.html'\n})\n\nexport class IsolationPolicyStatComponent implements OnInit, OnDestroy{\n public isolationPolicyStatsComp: any;\n @Input('statKey') statKey: string;\n private crudHelperService: CRUDHelperService;\n private refresh: Subscription;\n private policiesModel: PoliciesModel;\n private inspectSerrvice: InspectService;\n public showLoader: boolean\n isolationPolicyInspectStats:any; config:any; endpoints:any; filteredendpoints:any; containerDetails:any;\n constructor(policiesModel: PoliciesModel,\n crudHelperService: CRUDHelperService,\n inspectSerrvice: InspectService,\n private ngZone: NgZone){\n this.crudHelperService = crudHelperService;\n this.policiesModel = policiesModel;\n this.inspectSerrvice = inspectSerrvice;\n this.statKey = '';\n this.showLoader = true;\n this.refresh = Observable.interval(5000).subscribe(() => {\n if(this.statKey!='')\n this.getIsolationPolicyInspect(true);\n });\n this.isolationPolicyInspectStats= {\n numEndpoints: '',\n }\n this.config = {policyName: '', tenantName: ''}\n this.endpoints = []\n this.filteredendpoints = []\n this.containerDetails= {}\n this.isolationPolicyStatsComp = this;\n }\n\n ngOnInit(){\n this.crudHelperService.startLoader(this);\n if(this.statKey!='')\n this.getIsolationPolicyInspect(false);\n }\n\n getIsolationPolicyInspect(reload: boolean){\n var isolationPolicyStatsComp = this;\n this.policiesModel.getInspectByKey(this.statKey,\n ContivGlobals.POLICIES_INSPECT_ENDPOINT, reload)\n .then((result) => {\n isolationPolicyStatsComp['isolationPolicyInspectStats'] = result['Oper'];\n isolationPolicyStatsComp['config'] = result['Config'];\n if(!isUndefined(result['Oper'].endpoints)){\n var containerDetails = isolationPolicyStatsComp.inspectSerrvice.buildEndPoints(result['Oper'].endpoints);\n if(isolationPolicyStatsComp.inspectSerrvice.checkContainerChanged(isolationPolicyStatsComp['containerDetails'],containerDetails)){\n isolationPolicyStatsComp['endpoints'] = result['Oper'].endpoints;\n isolationPolicyStatsComp['containerDetails'] = containerDetails;\n }\n }\n else{\n isolationPolicyStatsComp['endpoints'] = []\n isolationPolicyStatsComp['containerDetails'] = {};\n }\n isolationPolicyStatsComp.ngZone.run(() => {\n isolationPolicyStatsComp.crudHelperService.stopLoader(isolationPolicyStatsComp);\n });\n },\n (error) => {\n isolationPolicyStatsComp.ngZone.run(() => {\n isolationPolicyStatsComp.crudHelperService.stopLoader(isolationPolicyStatsComp);\n });\n });\n }\n\n ngOnDestroy(){\n this.refresh.unsubscribe();\n }\n}" }, { "alpha_fraction": 0.7209035158157349, "alphanum_fraction": 0.7239663004875183, "avg_line_length": 36.869564056396484, "blob_id": "289597b12716ececc041e483d01f48abf7b853ad", "content_id": "d9858a8d770ec62d6cdc6c01ce6a0535313ee314", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2612, "license_type": "permissive", "max_line_length": 113, "num_lines": 69, "path": "/app/components/directives/directives.module.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 10/17/16.\n */\nimport { NgModule } from \"@angular/core\";\nimport { CommonModule } from \"@angular/common\";\nimport { ErrorMessageComponent } from \"./errormessagedirective\";\nimport { CtvTableComponent, CtvThComponent, CtvSearchComponent, CtvTpaginationComponent} from \"./tabledirective\";\nimport {FormsModule, ReactiveFormsModule} from \"@angular/forms\";\nimport { CtvAccordionComponent } from \"./accordiondirective\";\nimport { CtvCollapsibleComponent } from \"./collapsibledirective\";\nimport { CtvNamevalueComponent } from \"./namevaluedirective\";\nimport { NetworkSettingComponent } from \"./settings/networksettingcomponent\";\nimport { AciSettingComponent } from \"./settings/acisettingcomponent\";\nimport { LineGraphComponent } from \"./linegraphcomponent\";\nimport { ChartsModule } from \"ng2-charts\";\nimport { NotificationComponent } from \"./notification\";\nimport { LdapSettingsComponent } from \"./settings/ldapsettingcomponent\";\nimport { TooltipComponent } from \"./tooltip\";\nimport { UserProfileEditComponent } from \"./settings/userprofileedit\";\nimport { VerifydomDirective } from \"./verifydomdirective\";\nimport { NetworkCreateformComponent } from \"./settings/networkcreateform\";\nimport {OrganizationModule} from \"../../settings/tenants/organization.module\";\nimport {TenantCreateComponent} from \"./settings/tenantcreate\";\n@NgModule({\n imports: [\n CommonModule, FormsModule, ChartsModule, ReactiveFormsModule\n ],\n declarations: [\n ErrorMessageComponent,\n CtvTableComponent,\n CtvThComponent,\n CtvSearchComponent,\n CtvTpaginationComponent,\n CtvAccordionComponent,\n CtvCollapsibleComponent,\n CtvNamevalueComponent,\n VerifydomDirective,\n NetworkSettingComponent,\n AciSettingComponent,\n LineGraphComponent,\n NotificationComponent,\n LdapSettingsComponent,\n TooltipComponent,\n UserProfileEditComponent,\n NetworkCreateformComponent,\n TenantCreateComponent\n ],\n exports: [\n ErrorMessageComponent,\n CtvTableComponent,\n CtvThComponent,\n CtvSearchComponent,\n CtvTpaginationComponent,\n CtvAccordionComponent,\n CtvCollapsibleComponent,\n CtvNamevalueComponent,\n VerifydomDirective,\n NetworkSettingComponent,\n AciSettingComponent,\n LineGraphComponent,\n NotificationComponent,\n LdapSettingsComponent,\n TooltipComponent,\n UserProfileEditComponent,\n NetworkCreateformComponent,\n TenantCreateComponent\n ]\n})\nexport class DirectivesModule {}" }, { "alpha_fraction": 0.6619718074798584, "alphanum_fraction": 0.6649899482727051, "avg_line_length": 35.16363525390625, "blob_id": "35c130eaebf7107625f9b7b4380d1244bc55bbdf", "content_id": "1488e22abfa790a0da0612a19582a21d9109dcd4", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1988, "license_type": "permissive", "max_line_length": 114, "num_lines": 55, "path": "/app/applicationgroups/applicationgroupinfoctrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 11/18/16.\n */\nimport { Component, Input, OnInit, NgZone } from \"@angular/core\";\nimport { ActivatedRoute, Router } from \"@angular/router\";\nimport { CRUDHelperService } from \"../components/utils/crudhelperservice\";\nimport { ApplicationGroupsModel } from \"../components/models/applicationgroupsmodel\";\n\n@Component({\n selector: 'applicationgroupinfo',\n templateUrl: './applicationgroupinfo.html'\n})\n\nexport class ApplicationGroupInfoComponent{\n\n @Input('applicationGroup') applicationGroup: any;\n @Input('mode') mode: string;\n @Input('showLoader') showLoader: boolean;\n\n constructor(private activatedRoute: ActivatedRoute,\n private router: Router,\n private ngZone: NgZone,\n private applicationGroupsModel:ApplicationGroupsModel,\n private crudHelperService:CRUDHelperService){\n this.applicationGroup= {\n groupName: '',\n networkName: ''\n };\n this.mode = 'details';\n }\n\n returnToApplicationGroupDetails() {\n this.router.navigate(['../../details', this.applicationGroup.key], { relativeTo: this.activatedRoute });\n }\n\n cancelEditing() {\n this.returnToApplicationGroupDetails();\n }\n\n saveApplicationGroup() {\n var component = this;\n component.crudHelperService.startLoader(component);\n\n component.applicationGroupsModel.save(component.applicationGroup).then(\n function successCallback(result) {\n component.crudHelperService.stopLoader(component);\n component.crudHelperService.showNotification(\"Application group: Updated\", result.key.toString());\n component.returnToApplicationGroupDetails();\n }, function errorCallback(result) {\n component.crudHelperService.stopLoader(component);\n component.crudHelperService.showServerError(\"Application group: Update failed\", result);\n\n });\n }\n}" }, { "alpha_fraction": 0.5890411138534546, "alphanum_fraction": 0.6301369667053223, "avg_line_length": 20.899999618530273, "blob_id": "307e58d20fc082e495597c56ff06a24e0a4c0ec0", "content_id": "9d44629c3cbb51945113258b257d938d5dc24b09", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 438, "license_type": "permissive", "max_line_length": 60, "num_lines": 20, "path": "/config/webpack.test.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 4/10/17.\n */\n\n/**\n * Created by vjain3 on 1/13/17.\n */\nvar webpackMerge = require('webpack-merge');\nvar commonConfig = require('./webpack.common.js');\n\nmodule.exports = webpackMerge(commonConfig, {\n devtool: 'cheap-module-eval-source-map',\n debug: true,\n\n devServer: {\n historyApiFallback: true,\n watchOptions: { aggregateTimeout: 300, poll: 1000 },\n stats: 'minimal'\n }\n});\n" }, { "alpha_fraction": 0.5763869285583496, "alphanum_fraction": 0.5817922949790955, "avg_line_length": 39.88372039794922, "blob_id": "2e0050b92c97ca67cb3eda65c38343c412010f31", "content_id": "101ac3d47756bd1ebc3e824594593131b1062f1c", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3515, "license_type": "permissive", "max_line_length": 159, "num_lines": 86, "path": "/app/components/utils/chartservice.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "import {Injectable, OnInit} from \"@angular/core\";\nimport {Response} from \"@angular/http\";\nimport {Subscription, Observable, Subject} from \"rxjs\";\nimport {AuthService} from \"./authservice\";\nimport {ContivGlobals} from \"../models/contivglobals\";\nimport {ApiService} from \"./apiservice\";\nimport {isUndefined} from \"util\";\n\nexport enum EndpointType {\n Network,\n ApplicationGroup\n}\n\n@Injectable()\nexport class ChartService{\n private refresh: Subscription;\n private networks: any;\n private netInspect: any;\n public graphData: {};\n public source: Subject<any>;\n public stream: Observable<any>;\n constructor(private authService: AuthService,\n private apiService: ApiService){\n this.networks = [];\n this.netInspect = {};\n this.graphData = {0: {}, 1: {}};\n this.source = new Subject<any>();\n this.stream = this.source.asObservable();\n }\n\n private getInspectData(listEndPoint:string, inspectEndpoint:string, endpointtype:EndpointType){\n this.apiService.get(listEndPoint)\n .map((res: Response) => res.json())\n .subscribe((result1) => {\n for(var x of result1){\n var key = x['key'];\n this.apiService.get(inspectEndpoint + key + '/')\n .map((res: Response) => res.json())\n .subscribe((result2) => {\n var inspectkey = result2['Config']['key'];\n if(!isUndefined(result2['Oper']['numEndpoints'])){\n this.generateGraphData(inspectkey, result2['Oper']['numEndpoints'], endpointtype);\n }\n else{\n this.generateGraphData(inspectkey, 0, endpointtype);\n }\n },(error) => {});\n }\n },(error) => {});\n }\n\n private generateGraphData(key: string, count: number, type: EndpointType){\n if(isUndefined(this.graphData[type][key])){\n this.graphData[type][key]=[];\n for(var i=0; i<15; i++){\n this.graphData[type][key].push(count)\n }\n }\n else{\n this.graphData[type][key].push(count);\n this.source.next({iKey: key, count: count, type: type});\n }\n }\n\n /* This method is called by menuctrl.ts after the user logs out of the system */\n public cleanBuffer(){\n this.networks = [];\n this.netInspect = {};\n this.graphData = {0: {}, 1: {}};\n this.refresh.unsubscribe();\n }\n\n /* This method is called by loginctrl.ts after the user logs into the system */\n public startpolling(){\n if (this.authService.isLoggedIn){\n this.getInspectData(ContivGlobals.NETWORKS_ENDPOINT, ContivGlobals.NETWORKS_INSPECT_ENDPOINT, EndpointType.Network);\n this.getInspectData(ContivGlobals.APPLICATIONGROUPS_ENDPOINT, ContivGlobals.APPLICATIONGROUPS_INSPECT_ENDPOINT, EndpointType.ApplicationGroup);\n }\n this.refresh = Observable.interval(30000).subscribe(() => {\n if (this.authService.isLoggedIn){\n this.getInspectData(ContivGlobals.NETWORKS_ENDPOINT, ContivGlobals.NETWORKS_INSPECT_ENDPOINT, EndpointType.Network);\n this.getInspectData(ContivGlobals.APPLICATIONGROUPS_ENDPOINT, ContivGlobals.APPLICATIONGROUPS_INSPECT_ENDPOINT, EndpointType.ApplicationGroup);\n }\n });\n }\n}" }, { "alpha_fraction": 0.6515303254127502, "alphanum_fraction": 0.6537307500839233, "avg_line_length": 40.66666793823242, "blob_id": "d125ead2d2168a7a56dce0d0cb143ca92de8fc93", "content_id": "35e32a02d470b52d493c8e336af5cfe6fe4fd6fc", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4999, "license_type": "permissive", "max_line_length": 112, "num_lines": 120, "path": "/app/menu/menuCtrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 5/19/16.\n */\nimport { Component, Inject, ViewEncapsulation, OnInit, OnChanges, DoCheck, AfterViewInit } from '@angular/core';\nimport { ActivatedRoute, Router } from \"@angular/router\";\nimport { AuthService } from \"../components/utils/authservice\";\nimport { ContivGlobals } from \"../components/models/contivglobals\";\nimport { ChartService } from \"../components/utils/chartservice\";\nimport { ProfileDisplayType } from \"../components/directives/settings/userprofileedit\";\nimport { NetworksModel } from \"../components/models/networksmodel\";\nimport { ApplicationGroupsModel } from \"../components/models/applicationgroupsmodel\";\nimport { AppProfilesModel } from \"../components/models/appprofilesmodel\";\nimport { AuthorizationModel } from \"../components/models/authorizationmodel\";\nimport { BgpsModel } from \"../components/models/bgpsmodel\";\nimport { ContractGroupsModel } from \"../components/models/contractgroupsmodel\";\nimport { NetprofilesModel } from \"../components/models/netprofilesmodel\";\nimport { OrganizationsModel } from \"../components/models/organizationsmodel\";\nimport { PoliciesModel } from \"../components/models/policiesmodel\";\nimport { RulesModel } from \"../components/models/rulesmodel\";\nimport { ServicelbsModel } from \"../components/models/servicelbsmodel\";\nimport { UsersModel } from \"../components/models/usersmodel\";\nimport { FirstRunService } from \"../components/utils/firstrunservice\";\n\ndeclare var jQuery:any;\n\n@Component({\n selector: 'menu',\n templateUrl: './menu.html',\n styleUrls: ['./menu.css']\n})\n\nexport class MenuComponent implements AfterViewInit, DoCheck{\n public username: string;\n public localuser: boolean;\n public product_name:string = ContivGlobals.PRODUCT_NAME;\n public firstRun: boolean;\n public ProfileDisplayType = ProfileDisplayType;\n public loggedOut: boolean = false;\n\n constructor(private activatedRoute: ActivatedRoute,\n private router: Router,\n private authService: AuthService,\n private firstRunService: FirstRunService,\n private chartService: ChartService,\n private networksModel: NetworksModel,\n private applicationgroupsModel: ApplicationGroupsModel,\n private appprofilesModel: AppProfilesModel,\n private authorizationModel: AuthorizationModel,\n private bgpsModel: BgpsModel,\n private contractgroupsModel: ContractGroupsModel,\n private netprofilesModel: NetprofilesModel,\n private organizationsmodel: OrganizationsModel,\n private policiesModel: PoliciesModel,\n private rulesModel: RulesModel,\n private servicelbsModel: ServicelbsModel,\n private usersModel: UsersModel) {\n this.username = authService.username;\n this.firstRun = this.firstRunService.firstRun;\n this.localuser = this.authService.localUser;\n\n }\n\n ngDoCheck(){\n if(!this.loggedOut){\n if(!this.authService.isLoggedIn){\n this.loggedOut = true;\n this.logout();\n }\n }\n }\n\n ngAfterViewInit(){\n jQuery('.ui.dropdown').dropdown({action: 'hide', duration: 100});\n this.firstRunService.firstrunObservable.subscribe((res) => {\n this.firstRun = res;\n });\n this.chartService.startpolling();\n }\n\n help(){\n var win = window.open(\"http://contiv.github.io/\", '_blank');\n win.focus();\n }\n\n logout() {\n var component = this;\n component['timerId'] = window.setInterval(() => {\n if(jQuery('.ui.dropdown').dropdown('is hidden')){\n clearInterval(component['timerId']);\n component.cleanuplocalstorage();\n component.chartService.cleanBuffer();\n component.networksModel.clearModel();\n component.applicationgroupsModel.clearModel();\n component.appprofilesModel.clearModel();\n component.authorizationModel.clearModel();\n component.bgpsModel.clearModel();\n component.contractgroupsModel.clearModel();\n component.netprofilesModel.clearModel();\n component.organizationsmodel.clearModel();\n component.policiesModel.clearModel();\n component.rulesModel.clearModel();\n component.servicelbsModel.clearModel();\n component.usersModel.clearModel();\n component.firstRunService.resetCheck();\n component.router.navigate(['/logout'],{relativeTo: this.activatedRoute});\n }\n },10)\n }\n\n cleanuplocalstorage(): void{\n localStorage.removeItem(\"authToken\");\n localStorage.removeItem(\"lastAccessTime\");\n localStorage.removeItem(\"username\");\n this.authService.isLoggedIn = false;\n }\n\n closeProfile(){\n jQuery('#user-profile-modal').modal('hide');\n }\n}" }, { "alpha_fraction": 0.697650671005249, "alphanum_fraction": 0.7027578949928284, "avg_line_length": 32.7931022644043, "blob_id": "6f7474e82d4a1c0b2ae12bf0152358b387c7603e", "content_id": "ad6fd4558174ed7dae18131e76d1a01ba59add1f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 979, "license_type": "permissive", "max_line_length": 83, "num_lines": 29, "path": "/e2e-tests/networks/networkspagespec.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 7/27/16.\n */\n\nvar NetworksPage = require('./networkspageobject');\n\ndescribe(\"Testing Networks create and list\", function(){\n var networkList = new NetworksPage.netList();\n var networkCreate = new NetworksPage.netCreate();\n\n beforeEach(function(){\n browser.get(\"#/m/networks/list\");\n });\n\n it('Create a network', function(){\n testConfig.clickLink(networkList.createButton);\n networkCreate.newNetworkName.sendKeys(testConfig.networks.name);\n networkCreate.newNetworkEncap.click();\n networkCreate.newNetworkCidr.sendKeys(testConfig.networks.cidr);\n networkCreate.newNetworkGateway.sendKeys(testConfig.networks.gateway);\n networkCreate.newNetworkCreateButton.submit();\n expect(networkCreate.serverMessage.isPresent()).toBeFalsy();\n });\n\n it('Verify the network list', function(){\n testConfig.verifyCreate(networkList.networkName, testConfig.networks.name);\n });\n\n});" }, { "alpha_fraction": 0.4551644027233124, "alphanum_fraction": 0.4578213095664978, "avg_line_length": 37.589744567871094, "blob_id": "4e66609a3e1f7adcffb472a1843d0546196fe14b", "content_id": "c146e5738767152dfc234a5506b8fcaeae7059df", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 12044, "license_type": "permissive", "max_line_length": 124, "num_lines": 312, "path": "/app/components/graphobjects/policy/splitjoinnodepolicy.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * This policy is used for splitting a node into its children,\n * and joining them back to their parent.\n * Splits on double click, and joins on right click.\n * If multiple nodes are selected at the time of a split or join event,\n * it will split or join all of them.\n */\nangular.module('contiv.graph')\n .factory('SplitJoinNodePolicy', ['NodeSelectionPolicy', 'VisualizerNode', \n \t\tfunction (NodeSelectionPolicy, VisualizerNode) {\n\t\tclass SplitJoinNodePolicy extends NodeSelectionPolicy.Policy {\n\t\t\t/**\n\t\t\t * Constructs the object.\n\t\t\t */\n constructor() {\n super();\n this.policyName = \"SplitJoinNodePolicy\";\n }\n\n /**\n * Called when policy is installed\n *\n * @param {Graph} graph The graph\n */\n initialize(graph) {\n if (this.initialized) {\n return;\n }\n super.initialize(graph);\n var state = graph.state.SplitJoinNodePolicy = {};\n state.splitNodes = []; \n }\n\n /**\n * Triggering split on double click\n *\n * @param {D3Object} d3node The d3 node\n * @param {Object} d The matching data object\n */\n dblclick(d3node, d) {\n var thisGraph = this.graph,\n superState = thisGraph.state.SplitJoinNodePolicy;\n\n if (!d3.event.ctrlKey) {\n if (superState.selectedNodes.indexOf(d) > -1) {\n this.splitMultipleNodes(superState.selectedNodes);\n } else {\n this.removeAllSelectedNodes();\n this.splitNode(d);\n }\n }\n }\n\n /**\n * Triggering join on right click\n *\n * @param {D3Obj} d3node The d3 node\n * @param {Object} d The matching data object\n */\n contextmenu(d3node, d) {\n var thisGraph = this.graph,\n superState = thisGraph.state.NodeSelectionPolicy;\n d3.event.preventDefault();\n if (!d3.event.ctrlKey) {\n //if try to join a highlighted node while multiple nodes are selected,\n //we join all highlighted nodes\n var selectedNodes = superState.selectedNodes;\n if (selectedNodes.indexOf(d) > -1) {\n for (var i = 0; i < selectedNodes.length; i++) {\n this.joinNode(selectedNodes[i]);\n }\n } else {\n //if we try to join a node that isn't part of a highlight,\n //we remove all highlights and then join the clicked node\n this.removeAllSelectedNodes();\n this.joinNode(d);\n }\n }\n }\n \n /**\n * Splits a node.\n * used to share code between splitNode and splitMultipleNodes\n * while preventing the handlers for them both firing\n * \n * @param {Node} node The node being split\n * @return {Array} The new nodes created by the split\n */\n __splitNode(node) {\n var thisGraph = this.graph,\n state = thisGraph.state.SplitJoinNodePolicy;\n var name = node.id;\n var children_struct = thisGraph.dataSource.children_struct;\n //if it has no children to split into\n if (children_struct[name] === undefined || _.isEmpty(children_struct[name])) {\n return;\n }\n\n //removing the node from the list of nodes\n thisGraph.nodes = _.filter(thisGraph.nodes, function(graphNodes) {\n return graphNodes != node;\n });\n // console.log(thisGraph.nodes);\n thisGraph.spliceLinksForNode(node);\n\n //getting all the node id's for finding flow\n var node_names_set = [];\n for (var i = 0; i < thisGraph.nodes.length; i++) {\n node_names_set.push(thisGraph.nodes[i].id);\n }\n\n //set of nodes after the split\n var new_nodes = [];\n for (var i = 0; i < children_struct[name].length; i++) {\n node_names_set.push(children_struct[name][i]);\n new_nodes.push(children_struct[name][i]);\n }\n var retData = thisGraph.dataSource.getFlowBetweenSet(node_names_set);\n\n //formatting data for new nodes\n var xLoc = node.x;\n var yLoc = node.y;\n var ancestors = node.ancestors.slice();\n //keeping ordering that first in ancestor list is closest in relationship\n ancestors.splice(0, 0, node.id);\n var parent = node.id;\n var new_node_objs = [];\n var radius = node.radius * thisGraph.consts.radiusDecay;\n var nodeData = retData.nodeData;\n for (var i = 0; i < nodeData.length; i++) {\n //calculating which of the nodes in retData[0] are new\n if (new_nodes.indexOf(nodeData[i].id) > -1) {\n var id = nodeData[i].id;\n var text = nodeData[i].text;\n var new_node = new VisualizerNode.Node(null, null, id, text, radius, parent, ancestors, xLoc, yLoc);\n new_node.initialize(thisGraph);\n thisGraph.nodes.push(new_node);\n new_node_objs.push(new_node);\n }\n }\n thisGraph.links = thisGraph.dataSource.processLinkData(retData.linkData, thisGraph.nodes);\n thisGraph.initNodes();\n thisGraph.initLinks();\n\n state.splitNodes.push(node.id);\n return new_node_objs;\n }\n\n /**\n * Splits the give node\n *\n * @param {Node} node The node being split\n */\n splitNode(node) {\n var res = this.__splitNode(node);\n if (res == null) {\n return;\n }\n this.splitNodeEvent(res);\n\n }\n\n /**\n * Splits all the nodes passed in\n *\n * @param {Array} nodes Array of nodes to be split\n */\n splitMultipleNodes(nodes) {\n var thisGraph = this.graph;\n var resNodes = [];\n for (var i = 0; i < nodes.length; i++) {\n var res = this.__splitNode(nodes[i]);\n resNodes = resNodes.concat(res);\n }\n\n this.splitMultipleNodesEvent(res);\n }\n\n /**\n * Called after a single node is split\n *\n * @param {Array} newNodes The new nodes\n */\n splitNodeEvent(newNodes) {\n var thisGraph = this.graph;\n thisGraph.setPositions();\n thisGraph.updateGraph();\n }\n\n /**\n * Called after multiple nodes are split at once\n *\n * @param {Array} newNodes The new nodes\n */\n splitMultipleNodesEvent(newNodes) {\n var thisGraph = this.graph;\n thisGraph.setPositions();\n thisGraph.updateGraph();\n }\n\n /**\n * used to share code between joinNode and joinMultipleNode\n * while preventing both handlers firing\n * \n * @param {Node} node The node to join\n * @return {Node} The new node after the join\n */\n __joinNode(node) {\n var thisGraph = this.graph,\n state = thisGraph.state.SplitJoinNodePolicy;\n\n //check that node still exists\n if (thisGraph.nodes.indexOf(node) == -1) {\n return;\n }\n\n var children_struct = thisGraph.dataSource.children_struct;\n var name = node.id;\n //if it has no ancestor, nothing to join\n if (children_struct.topLevel.indexOf(name) > -1) {\n return;\n }\n\n var to_be_deleted = [];\n var node_names_set = [];\n for (var i = 0; i < thisGraph.nodes.length; i++) {\n //if node won't be collapsed\n if (thisGraph.nodes[i].ancestors.indexOf(node.parent) == -1) {\n node_names_set.push(thisGraph.nodes[i].id);\n } else {\n to_be_deleted.push(thisGraph.nodes[i]);\n }\n }\n var new_node_id = node.parent;\n node_names_set.push(node.parent);\n\n //formatting data\n var radius = node.radius / thisGraph.consts.radiusDecay; \n var xLoc = node.x;\n var yLoc = node.y;\n var parent = node.ancestors[1];\n var ancestors = node.ancestors.slice(1);\n var new_node = new VisualizerNode.Node(xLoc, yLoc, new_node_id, new_node_id, radius, parent, ancestors);\n thisGraph.nodes.push(new_node);\n\n var retData = thisGraph.dataSource.getFlowBetweenSet(node_names_set);\n //remove all nodes that will be joined\n for (var i = 0; i < to_be_deleted.length; i++) {\n var node_to_delete = to_be_deleted[i];\n thisGraph.nodes.splice(thisGraph.nodes.indexOf(node_to_delete), 1);\n thisGraph.spliceLinksForNode(node_to_delete);\n }\n thisGraph.links = thisGraph.dataSource.processLinkData(retData.linkData, thisGraph.nodes);\n thisGraph.initNodes();\n thisGraph.initLinks();\n\n state.splitNodes.splice(state.splitNodes.indexOf(new_node.id), 1);\n\n return new_node;\n }\n\n /**\n * Joins the given node\n *\n * @param {Node} node The node to join\n */\n joinNode(node) {\n var newNode = this.__joinNode(node);\n if (newNode != null) {\n \tthis.joinNodeEvent(newNode);\n }\n }\n\n /**\n * Joins all the given nodes\n *\n * @param {Array} nodes The nodes to join\n */\n joinMultipleNode(nodes) {\n var new_nodes = [];\n for (var i = 0; i < nodes.length; i++) {\n var res = this.__joinNode(nodes[i]);\n new_nodes.push(res);\n }\n this.joinMultipleNodesEvent(new_nodes);\n }\n\n /**\n * Called after a single node is joined\n *\n * @param {Node} newNode The new node\n */\n joinNodeEvent(newNode) {\n var thisGraph = this.graph;\n thisGraph.updateGraph();\n }\n\n /**\n * Called after multiple nodes are joined\n *\n * @param {Array} newNodes The new nodes\n */\n joinMultipleNodesEvent(newNodes) {\n var thisGraph = this.graph;\n thisGraph.updateGraph();\n }\n \n }\n return {\n Policy: SplitJoinNodePolicy\n }\n}]);\n\n\n\n\n" }, { "alpha_fraction": 0.6930091381072998, "alphanum_fraction": 0.7092198729515076, "avg_line_length": 28.84848403930664, "blob_id": "8ced8782b33b18a43a2daf14d597d2b8d398c20d", "content_id": "62df5d9b2b9e8f4c5a360bd9eb5862e0c12123b2", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 987, "license_type": "permissive", "max_line_length": 90, "num_lines": 33, "path": "/backend/backendConfig.sh", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "#script to generate the config file for telegraf\n#lookup all ips of nodes, passes them to a python script which\n#calls svcstats, and prints out all the endpoint IPs.\n#Output is then saved to the file.\nfilename=\"telegrafGen.conf\"\ncp configBase.conf $filename\necho \"servers = [\" >> $filename\nprefix='http://'\n\n##setting up the server addresses to poll from \nfor ip in $(etcdctl ls --recursive /contiv.io/service/netplugin/)\ndo\n ip=\"${ip##*/}\"\n ip=\"${ip%:*}\"\n svcStat=($prefix$ip)\n ret=$(python endpointExtract.py $svcStat)\n echo $ret >> $filename\n\ndone\n\necho \"]\" >> $filename\n\n##setting up the tags\necho \"## List of tag names to extract from top-level of JSON server response\" >> $filename\n\necho 'tag_keys = [\"EndpointIP\",\"ProviderIP\",\"ServiceIP\"]' >> $filename\n\n\n\nnohup docker run --net=host influxdb &\nwget https://dl.influxdata.com/telegraf/releases/telegraf-0.13.1.x86_64.rpm\nyes | yum localinstall telegraf-0.13.1.x86_64.rpm\nnohup telegraf -config telegrafGen.conf &\n\n\n" }, { "alpha_fraction": 0.5637137293815613, "alphanum_fraction": 0.5685022473335266, "avg_line_length": 33.814815521240234, "blob_id": "34cfff2ffff7e2fedbe6e56bec5e617cbe585ddf", "content_id": "10b577e892961544b4a372c47a818e7f745b6d6d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3759, "license_type": "permissive", "max_line_length": 85, "num_lines": 108, "path": "/app/dashboard/dashboardctrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 3/11/16.\n */\nimport { Component, OnDestroy, NgZone } from '@angular/core';\nimport { Observable } from 'rxjs/Observable';\nimport { Subscription } from 'rxjs/Subscription';\nimport { ApplicationGroupsModel } from \"../components/models/applicationgroupsmodel\";\nimport { PoliciesModel } from \"../components/models/policiesmodel\";\nimport { NetworksModel } from \"../components/models/networksmodel\";\nimport { ServicelbsModel } from \"../components/models/servicelbsmodel\";\nimport { isUndefined } from \"util\";\nimport { EndpointType } from \"../components/utils/chartservice\";\n\n@Component({\n selector: 'dashboard',\n templateUrl: './dashboard.html',\n styleUrls: ['./dashboard.css']\n\n})\nexport class DashboardComponent implements OnDestroy {\n public EndpointType = EndpointType;\n nodes: number = 0;\n networks: number = 0;\n groups: number = 0;\n networkList: any;\n applicationGroupList: any;\n networkpolicies: number = 0;\n servicelbs: number = 0;\n private subscription: Subscription;\n endpointType: EndpointType;\n public key: string;\n private setkeyflag: boolean;\n\n constructor(private networksModel:NetworksModel,\n private applicationGroupsModel:ApplicationGroupsModel,\n private policiesModel:PoliciesModel,\n private servicelbsModel: ServicelbsModel,\n private ngZone:NgZone) {\n var dashboardComponent = this;\n this.networkList = [];\n this.applicationGroupList = [];\n this.endpointType = EndpointType.Network;\n this.key = '';\n this.setkeyflag = true;\n function getDashboardInfo(reload) {\n ngZone.run(() => {\n networksModel.get(reload)\n .then(function (result) {\n dashboardComponent.networks = result.length;\n dashboardComponent.networkList = result;\n }, (err)=>{});\n applicationGroupsModel.get(reload)\n .then(function (result) {\n dashboardComponent.groups = result.length;\n dashboardComponent.applicationGroupList = result;\n }, (err)=>{});\n policiesModel.get(reload)\n .then(function (result) {\n dashboardComponent.networkpolicies = result.length;\n }, (err)=>{});\n servicelbsModel.get(reload)\n .then( function (result) {\n dashboardComponent.servicelbs = result.length;\n }, (err)=>{});\n })\n }\n\n //Load from cache for quick display initially\n getDashboardInfo(false);\n\n this.subscription = Observable.interval(5000).subscribe(() => {\n getDashboardInfo(true);\n })\n }\n\n\n ngOnDestroy() {\n this.subscription.unsubscribe();\n }\n\n switch(endpointType: EndpointType){\n if(endpointType == EndpointType.Network){\n if(this.endpointType !== EndpointType.Network){\n this.setkeyflag = true;\n this.endpointType = EndpointType.Network;\n }\n }\n else {\n if(this.endpointType !== EndpointType.ApplicationGroup){\n this.setkeyflag = true;\n this.endpointType = EndpointType.ApplicationGroup;\n }\n }\n }\n\n setKey(tempArr: any){\n if(!isUndefined(tempArr)){\n var temp = tempArr;\n if(tempArr.length > 0 && this.setkeyflag){\n Observable.timer(1).subscribe(() => {\n this.key = temp[0]['key'];\n })\n this.setkeyflag = false;\n }\n }\n }\n\n}" }, { "alpha_fraction": 0.7227488160133362, "alphanum_fraction": 0.7227488160133362, "avg_line_length": 34.25, "blob_id": "8830611a98f1b371ab2824acc3ac15202a229e22", "content_id": "d816410d3544ba4ae7fc6faddab29f9e042147a8", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 422, "license_type": "permissive", "max_line_length": 70, "num_lines": 12, "path": "/app/components/models/organizationsmodel.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { Http } from '@angular/http';\nimport { Collection } from \"./collection\";\nimport { ContivGlobals } from \"./contivglobals\";\nimport {ApiService} from \"../utils/apiservice\";\n\n@Injectable()\nexport class OrganizationsModel extends Collection {\n constructor(http: Http, apiService: ApiService) {\n super(http, ContivGlobals.ORGANIZATIONS_ENDPOINT, apiService);\n }\n}" }, { "alpha_fraction": 0.666800320148468, "alphanum_fraction": 0.6692060828208923, "avg_line_length": 44.345455169677734, "blob_id": "e5f26f9bb6c43ba14c3828ff7665db759c14ff64", "content_id": "3d02dae82de0d91307655211f05006b58f8b40a9", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4988, "license_type": "permissive", "max_line_length": 164, "num_lines": 110, "path": "/app/network_policies/bandwidthpolicydetailsctrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by hardik gandhi on 6/16/16.\n */\nimport { Component, Inject } from '@angular/core';\nimport { ActivatedRoute, Router } from \"@angular/router\";\nimport { NetprofilesModel } from \"../components/models/netprofilesmodel\";\nimport { CRUDHelperService } from \"../components/utils/crudhelperservice\";\nimport { PolicyTab } from \"./networkpoliciestabsctrl\";\n\n@Component({\n selector: 'bandwidthpolicydetails',\n templateUrl: './bandwidthpolicydetails.html'\n})\nexport class BandwidthPolicyDetailsComponent {\n bandwidthProfiles:any[] = [];\n policy:any = {};\n mode:string = 'details';\n\n constructor(private activatedRoute: ActivatedRoute,\n private router: Router,\n private netprofilesModel:NetprofilesModel,\n private crudHelperService:CRUDHelperService) {\n var bandwidthPolicyDetailsCtrl = this;\n\n /**\n * To show edit or details screen based on the route\n */\n function setMode() {\n if (activatedRoute.routeConfig.path.includes('edit')) {\n bandwidthPolicyDetailsCtrl.mode = 'edit';\n } else {\n bandwidthPolicyDetailsCtrl.mode = 'details';\n }\n }\n\n /* Get particular Profile for based on key*/\n bandwidthPolicyDetailsCtrl.netprofilesModel.getModelByKey(activatedRoute.snapshot.params['key'],false,undefined)\n .then(function (policy) {\n //To workaround netmaster not returning these properties if policy was saved with these values as 0\n if (policy.DSCP == null) policy.DSCP = 0;\n if (policy.burst == null) policy.burst = 0;\n bandwidthPolicyDetailsCtrl.policy = policy;\n var bandwidth = policy.bandwidth.split(' ');\n bandwidthPolicyDetailsCtrl.policy['bandwidthNumber'] = bandwidth[0];\n bandwidthPolicyDetailsCtrl.policy['bandwidthUnit'] = bandwidth[1];\n });\n bandwidthPolicyDetailsCtrl.crudHelperService.stopLoader(bandwidthPolicyDetailsCtrl);\n\n setMode();\n }\n\n deletePolicy() {\n var bandwidthPolicyDetailsCtrl = this;\n bandwidthPolicyDetailsCtrl.crudHelperService.startLoader(bandwidthPolicyDetailsCtrl);\n bandwidthPolicyDetailsCtrl.netprofilesModel.deleteUsingKey(bandwidthPolicyDetailsCtrl.policy.key, 'key', undefined).then(\n function successCallback(result) {\n bandwidthPolicyDetailsCtrl.crudHelperService.stopLoader(bandwidthPolicyDetailsCtrl);\n bandwidthPolicyDetailsCtrl.crudHelperService.showNotification(\"Bandwidth policy: Deleted\", result);\n bandwidthPolicyDetailsCtrl.returnToPolicies();\n }, function errorCallback(result) {\n bandwidthPolicyDetailsCtrl.crudHelperService.stopLoader(bandwidthPolicyDetailsCtrl);\n bandwidthPolicyDetailsCtrl.crudHelperService.showServerError(\"Bandwidth policy: Delete failed\", result);\n });\n }\n\n\n returnToPolicies() {\n this.router.navigate(['../../../list', {policyTab: PolicyTab.bandwidth}], { relativeTo: this.activatedRoute });\n }\n\n returnToPolicyDetails() {\n this.router.navigate(['../../details', this.policy.key], { relativeTo: this.activatedRoute });\n }\n\n editPolicy() {\n this.router.navigate(['../../edit', this.policy.key], { relativeTo: this.activatedRoute });\n }\n\n cancelEditing() {\n this.returnToPolicyDetails();\n }\n\n cancelDetails() {\n this.returnToPolicies();\n }\n\n savePolicy(validform: boolean) {\n var bandwidthPolicyDetailsCtrl = this;\n if (validform) {\n bandwidthPolicyDetailsCtrl.crudHelperService.startLoader(bandwidthPolicyDetailsCtrl);\n bandwidthPolicyDetailsCtrl.policy.bandwidth = bandwidthPolicyDetailsCtrl.policy.bandwidthNumber + \" \" + bandwidthPolicyDetailsCtrl.policy.bandwidthUnit;\n\n if (bandwidthPolicyDetailsCtrl.policy.DSCP == null) {//DSCP is null or undefined\n bandwidthPolicyDetailsCtrl.policy.DSCP = 0;\n }\n if (bandwidthPolicyDetailsCtrl.policy.burst == null) {//burst is null or undefined\n bandwidthPolicyDetailsCtrl.policy.burst = 0;\n }\n bandwidthPolicyDetailsCtrl.netprofilesModel.save(bandwidthPolicyDetailsCtrl.policy).then(function successCallback(result) {\n bandwidthPolicyDetailsCtrl.crudHelperService.stopLoader(bandwidthPolicyDetailsCtrl);\n bandwidthPolicyDetailsCtrl.crudHelperService.showNotification(\"Bandwidth policy: Updated\", result.key.toString());\n bandwidthPolicyDetailsCtrl.returnToPolicyDetails();\n }, function errorCallback(result) {\n bandwidthPolicyDetailsCtrl.crudHelperService.stopLoader(bandwidthPolicyDetailsCtrl);\n bandwidthPolicyDetailsCtrl.crudHelperService.showServerError(\"Bandwidth policy: Update failed\", result);\n });\n }\n }\n\n}\n" }, { "alpha_fraction": 0.642241358757019, "alphanum_fraction": 0.6659482717514038, "avg_line_length": 22.200000762939453, "blob_id": "a04a2438ca898f3b7719f95501c360c3ebf883df", "content_id": "79eb245ab2237c9417a248ec27d18766d9c296d8", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 464, "license_type": "permissive", "max_line_length": 63, "num_lines": 20, "path": "/backend/endpointExtract.py", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "#Takes in the IP address for which to call svcstats\n#iterates through JSON keys for the endpoints, and returns them\n\nimport json\nimport urllib2\nimport sys\n\ndef extract(arg):\n\targ = arg.strip('\\n')\n\tif (arg == \"\"):\n\t\treturn\n\turl = arg + \":9090/svcstats\"\n\tres = urllib2.urlopen(url).read()\n\tparsed = json.loads(str(res))\n\tfor item in parsed:\n\t\tkey = item['EndpointIP']\n\t\tprint('\"' + arg + ':4000/' + key + '\",')\n\treturn\n# print sys.stdin.read()\nextract(sys.argv[1])\n" }, { "alpha_fraction": 0.5846154093742371, "alphanum_fraction": 0.5923076868057251, "avg_line_length": 36.45762634277344, "blob_id": "5987abe65b80e8d06f7086e030603a6bfb532dab", "content_id": "1df4552ad3ae656a42ca575be1ee83c140a4efb8", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2210, "license_type": "permissive", "max_line_length": 119, "num_lines": 59, "path": "/app/components/utils/networkservice_test.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "'use strict';\n\ndescribe('contiv.utils module', function () {\n var networksettingData = [\n {\n \"key\": \"global\",\n \"name\": \"global\",\n \"networkInfraType\": \"default\",\n \"vlans\": \"1-4093\",\n \"vxlans\": \"1-10000\"\n }\n ];\n\n beforeEach(module('ui.router'));\n beforeEach(module('contiv.utils'));\n beforeEach(module('contiv.settings'));\n\n var $httpBackend;\n var NetworkService;\n beforeEach(inject(function (_$httpBackend_) {\n $httpBackend = _$httpBackend_;\n $httpBackend.when('GET', ContivGlobals.NETWORK_SETTINGS_ENDPOINT).respond(networksettingData);\n $httpBackend.when('POST', ContivGlobals.NETWORK_SETTINGS_ENDPOINT + networksettingData[0].key + '/').respond();\n }));\n\n afterEach(function () {\n $httpBackend.verifyNoOutstandingExpectation();\n $httpBackend.verifyNoOutstandingRequest();\n });\n\n describe(\"NetworkService\", function () {\n var $controller;\n var ctrl;\n beforeEach(inject(function ( _$controller_, $injector) {\n $controller = _$controller_;\n ctrl = $controller('NetworkSettingCtrl', { });\n\n NetworkService = $injector.get('NetworkService');\n $httpBackend = $injector.get('$httpBackend');\n }));\n it('should be defined', function () {\n expect(NetworkService).toBeDefined();\n $httpBackend.flush();\n });\n it('NetworkService.getSettings() should do a GET on /netmaster/api/v1/globals/', function () {\n NetworkService.getSettings(ctrl).then(function(response) {\n expect(response).toEqual(networksettingData[0]);\n });\n $httpBackend.expectGET(ContivGlobals.NETWORK_SETTINGS_ENDPOINT);\n $httpBackend.flush();\n });\n it('NetworkService.updateSettings() should do a POST on /netmaster/api/v1/globals/global/', function () {\n ctrl.key = networksettingData[0].key;\n NetworkService.updateSettings(ctrl);\n $httpBackend.expectPOST(ContivGlobals.NETWORK_SETTINGS_ENDPOINT + networksettingData[0].key + '/');\n $httpBackend.flush();\n });\n }); \n});\n" }, { "alpha_fraction": 0.5746039748191833, "alphanum_fraction": 0.5789021253585815, "avg_line_length": 27.376306533813477, "blob_id": "ce44bc0afa32338231e507fedd7ed5ffd3fb80cd", "content_id": "9af4bf1e3a4fad8bf6eae14262da266b7d2392b3", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 8143, "license_type": "permissive", "max_line_length": 121, "num_lines": 287, "path": "/app/components/directives/tabledirective.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 10/10/16.\n */\n\nimport {Component, Input, Output, OnInit, EventEmitter, OnChanges} from \"@angular/core\";\nimport {isUndefined} from \"util\";\nvar _ = require('lodash');\n\ninterface Chunk{\n selected: boolean;\n pageNo: number;\n}\n\ninterface Table {\n chunks: Chunk[];\n pageNo: number;\n tableSize: number;\n searchText: string;\n}\n\ninterface SortObj {\n field: string;\n reverse: boolean;\n iconDirection: Object;\n}\n\n@Component({\n selector: 'ctv-table',\n templateUrl: './table.html'\n\n})\n\nexport class CtvTableComponent implements OnChanges, OnInit {\n\n public table:Table;\n @Input('items') items: Object[];\n @Input('size') size:number;\n @Output('filtereditems') filteredinputitems: EventEmitter<any>;\n @Input('defaultSortColumn') defaultSortColumn: string;\n public pageChunks:Chunk[];\n public sortObj: SortObj\n public count:number;\n\n constructor(){\n this.filteredinputitems = new EventEmitter<any>();\n this.table = {chunks:[], pageNo: 0, tableSize: 12, searchText:''};\n this.pageChunks = [];\n this.defaultSortColumn='';\n this.size=12;\n this.items=[];\n this.sortObj = this.initializeSort(this.defaultSortColumn);\n }\n\n ngOnInit(){\n if(isNaN(this.size))\n this.size = 12;\n this.table.tableSize = this.size;\n this.sortObj = this.initializeSort(this.defaultSortColumn);\n this.showChunk(this.table.pageNo, this.table.searchText);\n }\n\n ngOnChanges(){\n this.showChunk(this.table.pageNo, this.table.searchText);\n }\n\n\n public showChunk(pageNo: number, searchText: string): boolean{\n this.table.searchText = searchText;\n\n /*\n This check is needed when you are having two tables on the same page and when you\n are trying to switch table views using ng-if, like the toggle between Networks and\n Application groups on the dashboard page.\n */\n if(this.sortObj.field.length == 0){\n this.sortObj = this.initializeSort(this.defaultSortColumn);\n }\n if(isUndefined(pageNo) || pageNo < 0){\n pageNo=0;\n }\n\n this.table.pageNo = pageNo;\n\n if(!(isUndefined(this.items))){\n var searchTextFilteredItems = this.filterItems(searchText);\n var sortedItems = this.sort(searchTextFilteredItems);\n var noOfChunks = Math.ceil(sortedItems.length / this.table.tableSize);\n if(noOfChunks == 0 ){\n noOfChunks=1;\n }\n\n this.table.chunks = [];\n\n for(var i=0; i< noOfChunks; i++){\n this.table.chunks.push({selected: false, pageNo: i});\n }\n\n if( pageNo >= this.table.chunks.length){\n this.table.pageNo = 0;\n }\n\n this.table.chunks[this.table.pageNo]['selected'] = true;\n\n if(this.table.chunks.length > 5){\n var sliceStart, sliceEnd;\n sliceStart = this.table.pageNo - 2;\n sliceEnd = this.table.pageNo + 3;\n if(sliceStart < 0 ){\n sliceEnd = sliceEnd = sliceStart;\n sliceStart = 0;\n }\n if(sliceEnd > this.table.chunks.length){\n sliceStart = sliceStart = (sliceEnd = this.table.chunks.length);\n sliceEnd = this.table.chunks.length;\n }\n this.pageChunks = this.table.chunks.slice(sliceStart,sliceEnd);\n }\n else{\n this.pageChunks = this.table.chunks;\n }\n var filtitems = this.limitItems(this.table.tableSize, this.table.pageNo * this.table.tableSize, sortedItems);\n this.filteredinputitems.emit(filtitems);\n this.count = filtitems.length;\n\n }\n return false;\n }\n\n public showPrevChunk(): any {\n var prevChunk;\n if(this.table.pageNo <=0 ) {\n prevChunk = 0;\n } else {\n prevChunk = this.table.pageNo - 1;\n }\n return this.showChunk(prevChunk, this.table.searchText);\n }\n\n public showNextChunk(): any {\n var nextChunk;\n\n nextChunk = this.table.pageNo + 1;\n if(nextChunk > this.table.chunks.length -1 ){\n nextChunk = this.table.chunks.length - 1;\n }\n\n return this.showChunk(nextChunk, this.table.searchText);\n }\n\n private filterItems(searchText: string): Object[]{\n var selectedItems = [];\n if(searchText.length === 0){\n return this.items;\n }\n for(var item of this.items){\n var str='';\n for(var key in item){\n str+=JSON.stringify(item[key]);\n }\n if (str.search(searchText) > -1){\n selectedItems.push(item);\n }\n }\n return selectedItems;\n }\n\n private limitItems(limitSize: number, start: number, items: Object[]): Object[]{\n var selectedItems = [];\n\n for(var i=start; (i<items.length) && (i<(start + limitSize)); i++){\n selectedItems.push(items[i]);\n }\n return selectedItems;\n }\n\n private initializeSort(sortfield: string): SortObj{\n return {\n field: sortfield,\n reverse: false,\n iconDirection: {\"down\": true, \"up\": false}\n }\n }\n\n public applysort(sortfield: string){\n if(sortfield == this.sortObj.field){\n this.sortObj.field = sortfield;\n this.sortObj.reverse = !this.sortObj.reverse;\n this.sortObj.iconDirection = {\n \"down\": !(this.sortObj.reverse),\n \"up\": this.sortObj.reverse\n }\n } else {\n this.sortObj = this.initializeSort(sortfield);\n }\n this.showChunk(this.table.pageNo, this.table.searchText);\n }\n\n private sort(items: Object[]): Object[]{\n var sortedItems: Object[];\n if(this.sortObj.field=='') return items;\n sortedItems = _.sortBy(items, [this.defaultSortColumn]);\n sortedItems = _.sortBy(sortedItems, [this.sortObj.field]);\n if(this.sortObj.reverse)\n sortedItems = _.reverse(sortedItems);\n return sortedItems;\n }\n}\n\n@Component({\n selector: \"ctv-th\",\n templateUrl: './tableheader.html'\n})\n\nexport class CtvThComponent implements OnInit{\n @Input('sortfield') sortfield: string;\n @Output('sortdata') sortdata: EventEmitter<any>;\n @Input('sortobject') sortobject: SortObj;\n constructor(){\n this.sortdata = new EventEmitter<any>();\n this.sortfield = '';\n this.sortobject = {field: '', iconDirection: {down: true, up: false}, reverse: false};\n }\n\n sortColumn(){\n this.sortdata.emit(this.sortfield);\n }\n\n ngOnInit(){\n }\n}\n\n@Component({\n selector: \"ctv-tpagination\",\n templateUrl:'./paginationmenu.html'\n})\n\nexport class CtvTpaginationComponent{\n\n @Input('chunks') chunks: Chunk[];\n @Output('showPage') showPage: EventEmitter<any>;\n @Output('prevChunk') prevChunk: EventEmitter<any>;\n @Output('nextChunk') nextChunk: EventEmitter<any>;\n\n constructor(){\n this.chunks = [];\n this.showPage = new EventEmitter<any>();\n this.prevChunk = new EventEmitter<any>();\n this.nextChunk = new EventEmitter<any>()\n }\n\n public showPrevChunk(){\n this.prevChunk.emit();\n }\n\n public showNextChunk(){\n this.nextChunk.emit();\n }\n\n public showClickedPage(pageNo: number){\n this.showPage.emit(pageNo);\n }\n\n}\n\n@Component({\n selector: 'ctv-search',\n templateUrl: './searchinput.html'\n})\n\nexport class CtvSearchComponent{\n\n public searchText: string;\n @Input('placeholder') placeholder: string;\n @Input('count') count: number;\n @Output('searchTextChange') searchTextChange: EventEmitter<any> = new EventEmitter<any>();\n public size:number;\n\n constructor(){\n this.searchText = '';\n this.size = 30;\n this.placeholder = 'Search';\n }\n\n public showChunk(event: any){\n this.searchTextChange.emit(event);\n }\n}" }, { "alpha_fraction": 0.5905207991600037, "alphanum_fraction": 0.5905207991600037, "avg_line_length": 36.8125, "blob_id": "566c7ba23b64e87206df7a9064850961632d066e", "content_id": "ccf2052a86da4b3cec1f865c5fe24e03a76d8d35", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3629, "license_type": "permissive", "max_line_length": 124, "num_lines": 96, "path": "/app/appprofiles/appprofiledetails.component.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "import { Component, Inject, NgZone } from '@angular/core';\nimport { ActivatedRoute, Router } from \"@angular/router\";\nimport { AppProfilesModel } from \"../components/models/appprofilesmodel\";\nimport { CRUDHelperService } from \"../components/utils/crudhelperservice\";\n\n@Component({\n selector: 'appprofiledetails',\n templateUrl: './appprofiledetails.html'\n})\nexport class AppProfileDetailsComponent {\n appProfile:any = {};\n mode:string = 'details';\n\n constructor(private activatedRoute: ActivatedRoute,\n private router: Router,\n private ngZone: NgZone,\n private appProfilesModel:AppProfilesModel,\n private crudHelperService:CRUDHelperService) {\n var component = this;\n\n /**\n * To show edit or details screen based on the route\n */\n function setMode() {\n if (activatedRoute.routeConfig.path.includes('edit')) {\n component.mode = 'edit';\n } else {\n component.mode = 'details';\n }\n }\n\n component.crudHelperService.stopLoader(component);\n\n component.appProfilesModel.getModelByKey(activatedRoute.snapshot.params['key'], false, 'key')\n .then(function (appProfile) {\n component.appProfile = appProfile;\n });\n\n setMode();\n }\n\n returnToAppProfile() {\n this.router.navigate(['../../list'], { relativeTo: this.activatedRoute });\n }\n\n returnToAppProfileDetails() {\n this.router.navigate(['../../details', this.appProfile.key], { relativeTo: this.activatedRoute });\n }\n\n editAppProfile() {\n this.router.navigate(['../../edit', this.appProfile.key], { relativeTo: this.activatedRoute });\n }\n\n cancelEditing() {\n this.returnToAppProfileDetails();\n }\n\n deleteAppProfile() {\n var component = this;\n component.crudHelperService.startLoader(component);\n component.appProfilesModel.delete(component.appProfile).then(\n function successCallback(result) {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n component.crudHelperService.showNotification(\"Application profile: Deleted\", result);\n });\n component.returnToAppProfile();\n }, function errorCallback(result) {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n component.crudHelperService.showServerError(\"Application profile: Delete failed\", result);\n });\n }\n\n saveAppProfile(formvalid: boolean) {\n var component = this;\n if (formvalid) {\n component.crudHelperService.startLoader(component);\n\n component.appProfilesModel.save(component.appProfile).then(\n function successCallback(result) {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n component.crudHelperService.showNotification(\"Application profile: Updated\", result.key.toString());\n });\n component.returnToAppProfileDetails();\n }, function errorCallback(result) {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n component.crudHelperService.showServerError(\"Application profile: Update failed\", result);\n });\n }\n }\n}" }, { "alpha_fraction": 0.5653365850448608, "alphanum_fraction": 0.5702101588249207, "avg_line_length": 24.59375, "blob_id": "1938ce916527e7f6f69b1d3f3161fb8742afc402", "content_id": "2be3f45d08e51403de559843c1cefd2914cce3a1", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3283, "license_type": "permissive", "max_line_length": 88, "num_lines": 128, "path": "/app/components/graphobjects/node/node.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * The base class for node objects for the graph.\n * Supports policies.\n * \n * To write your own Node object, create a new factory that uses the node\n * you want to inherit as a dependency, and extend its node class. \n * Return the class object with Node as key\n * \n */\nangular.module('contiv.graph')\n .factory('Node', [function () {\n\t\tclass Node {\n\t\t\t/**\n\t\t\t * Constructs the object.\n\t\t\t *\n\t\t\t * @param {number} x x location\n\t\t\t * @param {number} y y location\n\t\t\t * @param {string} id The identifier\n\t\t\t * @param {string} text The text to display\n\t\t\t * @param {number} radius The radius of the node\n\t\t\t */\n\t\t\tconstructor(x, y, id, text, radius) {\n\t\t\t\tthis.x = x;\n\t\t\t\tthis.y = y;\n\t\t\t\tthis.radius = radius;\n\t\t\t\tthis.id = id;\n\t\t\t\tthis.text = text;\n\t\t\t\tthis.radius = radius;\n\t\t\t\tthis.hasPolicy = false;\n\t\t\t\tthis.policy = null;\n\t\t\t\tthis.nodePolicies = [];\n\t\t\t\tthis.graph = null;\n\t\t\t\tthis.initialized = false;\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Called when a node is added to the graph\n\t\t\t *\n\t\t\t * @param {Graph} graph The graph it is added to\n\t\t\t */\n\t\t\tinitialize(graph) {\n\t\t\t\tif (this.initialized == false) {\n\t\t\t\t\tthis.initialized = true;\n\t\t\t\t\tthis.graph = graph;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Called during the update graph for existing links\n\t\t\t *\n\t\t\t * @param {D3Object} d3node The d3 node\n\t\t\t */\n\t\t\tupdateAttr(d3node, d) {\n\t\t\t\td3node.attr(\"transform\", function(d){return \"translate(\" + d.x + \",\" + d.y + \")\";});\n\t\t\t}\n\t\t\t\n\t\t\t/**\n\t\t\t * Called during the first update graph for a node\n\t\t\t * Hook for sub classes\n\t\t\t * \n\t\t\t * @param {D3Object} d3node The d3 node\n\t\t\t * @param {Node} d Matching Node Object\n\t\t\t */\n\t\t\tnewNodeAttr(d3node, d) {\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Sets the radius of the node.\n\t\t\t *\n\t\t\t * @param {number} radius The radius\n\t\t\t */\n\t\t\tsetRadius(radius) {\n\t\t\t\tthis.radius = radius;\n\t\t\t}\n\n\t\t /**\n\t\t * Used to install policies that are called when this\n\t\t * node has a mouse event\n\t\t *\n\t\t * @param {Policy} policy The policy to install\n\t\t */\n\t\t\tinstallNodePolicy(policy) {\n\t\t\t\tthis.hasPolicy = true;\n\t\t\t\tthis.nodePolicies.push(policy);\n\t\t\t\tpolicy.initialize(this.graph);\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Used to uninstall policy for this node\n\t\t\t *\n\t\t\t * @param {Policy|string} policyRemove The policy to remove\n\t\t\t */\t\t\t\n\t\t\tuninstallNodePolicy(policyRemove) {\n\t\t\t\tvar policyRemoveName;\n\t\t\t\tvar thisNode = this;\n\t\t\t\tif (typeof policyRemove === 'string') {\n\t\t\t\t\tpolicyRemoveName = policyRemove;\n\t\t\t\t} else {\n\t\t\t\t\tpolicyRemoveName = policyRemove.policyName;\n\t\t\t\t}\n\t\t\t\t_(thisNode.nodePolicies).forEach(function(policy, index) {\n\t\t\t\t\tif (policy.policyName === policyRemoveName) {\n\t\t\t\t\t\tpolicy.destroy();\n\t\t\t\t\t\tthisNode.nodePolicies.splice(index, 1);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tif (thisNode.nodePolicies.length === 0) {\n\t\t\t\t\tthisNode.hasPolicy = false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Called when there is a mouse event for this node\n\t\t\t *\n\t\t\t * @param {string} event The mouse event\n\t\t\t * @param {D3Object} d3node The d3 node\n\t\t\t * @param {Object} d The matching node object\n\t\t\t */\n\t\t\tnodePolicyEvent(event, d3node, d) {\n\t\t\t\t_.forEach(this.nodePolicies, function(policy) {\n\t\t\t\t\tpolicy[event](d3node, d);\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tNode: Node\n\t\t}\n}]);\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6614285707473755, "alphanum_fraction": 0.6714285612106323, "avg_line_length": 27.040000915527344, "blob_id": "aa0a66a28c4060614f98f664e3e27bad6e7edd17", "content_id": "e970e84c19986553a3b62e4db50c57e5f8001dee", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 700, "license_type": "permissive", "max_line_length": 81, "num_lines": 25, "path": "/app/components/models/contractgroupsmodel.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 12/13/16.\n */\nimport { Injectable } from '@angular/core';\nimport { Http } from '@angular/http';\nimport { Collection } from \"./collection\";\nimport { ContivGlobals } from \"./contivglobals\";\nimport { ApiService } from \"../utils/apiservice\";\n\n@Injectable()\nexport class ContractGroupsModel extends Collection {\n constructor(http: Http, apiService: ApiService) {\n super(http, ContivGlobals.CONTRACTS_ENDPOINT, apiService);\n }\n\n /**\n * Generate policy key to save policy on server\n * @param policy\n * @returns {string}\n */\n generateKey(contractGroup) {\n return contractGroup.tenantName + ':' + contractGroup.contractsGroupName;\n }\n\n}" }, { "alpha_fraction": 0.6096579432487488, "alphanum_fraction": 0.6122449040412903, "avg_line_length": 36.826087951660156, "blob_id": "10df295c7f018364920916408b25c574c48cf372", "content_id": "d50c1091b51bf9a22e09d5a21e0abdee857f59d6", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3479, "license_type": "permissive", "max_line_length": 127, "num_lines": 92, "path": "/app/network_policies/contractgroupcreate.component.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 12/13/16.\n */\nimport { Component, Inject, OnInit, NgZone } from '@angular/core';\nimport { ActivatedRoute, Router } from \"@angular/router\";\nimport { ContractGroupsModel } from \"../components/models/contractgroupsmodel\";\nimport { CRUDHelperService } from \"../components/utils/crudhelperservice\";\nimport { PolicyTab } from \"./networkpoliciestabsctrl\";\nimport { OrganizationsModel } from \"../components/models/organizationsmodel\";\n\n@Component({\n selector: 'contractgroupcreate',\n templateUrl: './contractgroupcreate.html'\n})\nexport class ContractGroupCreateComponent implements OnInit {\n newContractGroup:any;\n tenants:any[] = [];\n contractsString:string;\n\n constructor(private activatedRoute: ActivatedRoute,\n private router: Router,\n private ngZone: NgZone,\n private organizationsModel: OrganizationsModel,\n private contractGroupsModel: ContractGroupsModel,\n private crudHelperService: CRUDHelperService) {\n let component = this;\n\n function resetForm() {\n crudHelperService.stopLoader(component);\n component.newContractGroup = {\n contractGroupName: '',\n tenantName: '',\n contractsType: '',\n contracts: []\n };\n }\n\n resetForm();\n }\n\n ngOnInit() {\n let component = this;\n component.crudHelperService.startLoader(component);\n\n function getTenants(reload: boolean) {\n component.organizationsModel.get(reload)\n .then((result) => {\n component.tenants = result;\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n }, (error) => {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n });\n }\n\n getTenants(false);\n }\n\n returnToContractGroups() {\n this.router.navigate(['../../list', {policyTab: PolicyTab.contractGroup}], { relativeTo: this.activatedRoute });\n }\n\n cancelCreating() {\n this.returnToContractGroups();\n }\n\n parseContracts() {\n var re = /\\s*,\\s*/; //uses 0 or more spaces followed by , followed by 0 or more spaces as separator\n Array.prototype.push.apply(this.newContractGroup.contracts, this.contractsString.split(re));\n }\n\n createContractGroup(validform: boolean) {\n let component = this;\n if (validform) {\n component.crudHelperService.startLoader(component);\n component.newContractGroup.key =\n component.contractGroupsModel.generateKey(component.newContractGroup);\n component.parseContracts();\n component.contractGroupsModel.create(component.newContractGroup, undefined).then(function successCallback(result) {\n component.crudHelperService.stopLoader(component);\n component.crudHelperService.showNotification(\"External contract group: Created\", result.key);\n component.returnToContractGroups();\n }, function errorCallback(result) {\n component.crudHelperService.stopLoader(component);\n component.crudHelperService.showServerError(\"External contract group: Create failed\", result);\n });\n }\n }\n}" }, { "alpha_fraction": 0.45038434863090515, "alphanum_fraction": 0.45108315348625183, "avg_line_length": 35.08860778808594, "blob_id": "9e7500cb1a2595dc9f95cf68183280d5504cb838", "content_id": "7e5353977d2ebff89e7f9517194deab87ec59711", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2862, "license_type": "permissive", "max_line_length": 113, "num_lines": 79, "path": "/app/components/graphobjects/policy/pathchangeviewpolicy.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * This policy changes the view to the timegraph of link data on click.\n */\nangular.module('contiv.graph')\n .factory('PathChangeViewPolicy', ['Policy', function (Policy) {\n \tclass PathChangeViewPolicy extends Policy.Policy {\n /**\n * Called to build policy\n *\n * @param {Angular State} $state Used to change view\n */\n constructor($state) {\n super('PathChangeViewPolicy');\n this.$state = $state;\n }\n\n\n\n /**\n * Generates a list of all child containers of the service\n * Can handle nested services.\n *\n * @param {string} id Node ID\n */\n generateList(id) {\n var thisPolicy = this;\n var retList = [];\n var generateListHelper = function(id, retList) {\n var nodeIds = thisPolicy.graph.dataSource.children_struct[id];\n for (var i = 0; i < nodeIds.length; i++) {\n var childId = nodeIds[i];\n if (thisPolicy.graph.dataSource.hasChild(childId) === true) {\n var subRetList = generateListHelper(childId, retList);\n retList.concat(subRetList);\n } else {\n retList.push(childId);\n }\n }\n }\n generateListHelper(id, retList);\n return retList\n }\n\n /**\n * Used to reroute an edge when clicked\n *\n * @param {Link} edge The clicked edge\n */\n viewEdge(edge) {\n var sourceList = [];\n var targetList = [];\n var sourceId = edge.source.id;\n var targetId = edge.target.id;\n\n if (this.graph.dataSource.hasChild(sourceId) === true) {//Not a container node, need to aggregate\n sourceList = this.generateList(sourceId);\n } else {\n sourceList = [sourceId];\n }\n\n if (this.graph.dataSource.hasChild(targetId) === true) {//Not a container node, need to aggregate\n targetList = this.generateList(targetId);\n } else {\n targetList = [targetId];\n }\n this.$state.go('contiv.menu.visualization.edge', \n {sourceName: sourceId, targetName: targetId,\n sourceList: sourceList, targetList: targetList});\n }\n\n mousedown(d3path, d) {\n this.viewEdge(d);\n }\n\n }\n return {\n Policy: PathChangeViewPolicy\n }\n}]);\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5565449595451355, "alphanum_fraction": 0.5609973073005676, "avg_line_length": 30.19444465637207, "blob_id": "8415914300008ec7675ace9ebf6d4b91a71ffe86", "content_id": "f9d9af5dcaa56e4b3454d8975ff920c87c87dcc4", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2246, "license_type": "permissive", "max_line_length": 97, "num_lines": 72, "path": "/app/settings/nodes/nodestats.component.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 12/7/16.\n */\nimport { Component, NgZone, Input, OnInit, OnDestroy } from \"@angular/core\";\nimport { Subscription, Observable } from \"rxjs\";\nimport { ContivGlobals } from \"../../components/models/contivglobals\";\nimport { BgpsModel } from \"../../components/models/bgpsmodel\";\nimport { CRUDHelperService } from \"../../components/utils/crudhelperservice\";\n\n@Component({\n selector: 'nodestats',\n templateUrl: './nodestats.html'\n})\nexport class NodeStatsComponent implements OnInit, OnDestroy {\n @Input('statkey') statkey:string;\n inspect:any;\n routes:any;\n filteredroutes:any;\n showLoader:boolean;\n private refresh:Subscription;\n\n constructor(private bgpsModel:BgpsModel,\n private crudHelperService:CRUDHelperService,\n private ngZone:NgZone) {\n this.statkey = '';\n this.inspect = {\n Config: {\n neighbor: ''\n },\n Oper: {\n adminStatus: '',\n neighborStatus: '',\n numRoutes: ''\n }\n };\n this.routes = [];\n this.filteredroutes = [];\n\n this.refresh = Observable.interval(5000).subscribe(() => {\n if (this.statkey != '')\n this.getBgpInspect(true);\n });\n }\n\n ngOnInit(){\n this.crudHelperService.startLoader(this);\n if(this.statkey != '')\n this.getBgpInspect(false);\n }\n\n ngOnDestroy() {\n this.refresh.unsubscribe();\n }\n\n getBgpInspect(reload:boolean) {\n var component = this;\n this.bgpsModel.getInspectByKey(this.statkey, ContivGlobals.BGPS_INSPECT_ENDPOINT, reload)\n .then(function successCallback(result) {\n component.inspect = result;\n component.routes = result['Oper'].routes;\n component.filteredroutes = result['Oper'].routes;\n\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n }, function errorCallback(result) {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n });\n }\n}\n" }, { "alpha_fraction": 0.6393442749977112, "alphanum_fraction": 0.6393442749977112, "avg_line_length": 22.600000381469727, "blob_id": "202f4aa8f4cd4e266d27707d59fd7883c246599b", "content_id": "e8d5462c9c0a8d7b305b57b0a599721c4127b4a7", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 122, "license_type": "permissive", "max_line_length": 43, "num_lines": 5, "path": "/app/components/graphobjects/module.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Defining the Graph Module.\n * See DESIGN.md for info on Graph Objects.\n */\nangular.module('contiv.graph', []);\n\n\n\n\n" }, { "alpha_fraction": 0.5147368311882019, "alphanum_fraction": 0.5582996010780334, "avg_line_length": 40.16666793823242, "blob_id": "a7ed78f94ba68baa2c0489bce7007fa2132ba07d", "content_id": "ffbc0b09ad78add7776e9a0add69f28b4a2832fc", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 12350, "license_type": "permissive", "max_line_length": 155, "num_lines": 300, "path": "/app/service_lbs/servicelbs_test.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 5/13/16.\n */\n'use strict';\n\ndescribe('contiv.servicelbs module', function () {\n\n beforeEach(module('ui.router'));\n\n beforeEach(module('contiv.servicelbs'));\n\n var servicelbListData = [\n {\n key: \"default:web\",\n serviceName: 'web',\n selectors: ['io.contiv1=web','io.contiv2=proxy','io.contiv3=front-end','io.contiv4=ui','io.contiv5=ux'],\n ports: ['80:8080:tcp'],\n networkName: 'contiv-net1',\n ipAddress: '20.1.1.24',\n tenantName: \"default\",\n \"link-sets\": {},\n links: {\n \"Network\": {},\n \"Tenant\": {\n \"type\": \"tenant\",\n \"key\": \"default\"\n }\n }\n },\n {\n key: \"default:app\",\n serviceName: 'app',\n selectors: ['io.contiv1=app','io.contiv2=middleware'],\n ports: ['80:8080:tcp'],\n networkName: 'contiv-net1',\n ipAddress: '20.1.1.24',\n tenantName: \"default\",\n \"link-sets\": {\n },\n links: {\n Network: {},\n Tenant: {\n type: \"tenant\",\n key: \"default\"\n }\n }\n }\n ];\n\n var networkListData = [\n {\n \"key\": \"default:contiv-net1\",\n \"encap\": \"vxlan\",\n \"gateway\": \"20.1.2.254\",\n \"networkName\": \"contiv-net1\",\n \"subnet\": \"20.1.2.0/24\",\n \"tenantName\": \"default\",\n \"link-sets\": {},\n \"links\": {\n \"Tenant\": {\n \"type\": \"tenant\",\n \"key\": \"default\"\n }\n }\n }\n ];\n\n var servicelbOperData = {\n \"Oper\":{\n \"numProviders\":3,\n \"providers\":[\n {\n \"containerID\":\"62e6dfd7b5de1b0faf8c8c1c12f87862b6f7f6daa4f55e3bfcc6a5171c67637c\",\n \"homingHost\":\"cluster-node1\",\n \"ipAddress\":[\n \"20.1.1.3\",\n \"\"\n ],\n \"labels\":\"map[app:web com.docker.swarm.id:359cfcc54ee996864ed1e31d4313297aa7b726e0f8244694d63282679dfcf6ba]\",\n \"macAddress\":\"02:02:14:01:01:03\",\n \"name\":\"182d045f309960e4e83d5f65cf7dbdb63aaa37e9c4642e2086e5989511ef9afa\",\n \"network\":\"contiv-net1.default\",\n \"serviceName\":\"serviceLb1\"\n },\n {\n \"containerID\":\"e1d8ae7112564b4029f218cb9fa239359937e77a3bfaf259a4be788b889b1369\",\n \"homingHost\":\"cluster-node1\",\n \"ipAddress\":[\n \"20.1.1.4\",\n \"\"\n ],\n \"labels\":\"map[app:web com.docker.swarm.id:5460ddf75d46c10f8a91b7f52ab2b4aa397c43c41c376773b98f44c7fc18d878]\",\n \"macAddress\":\"02:02:14:01:01:04\",\n \"name\":\"957c34540c5d9515698547d62263a080b0b8c0ca5d586cdd6c6d983f4a837231\",\n \"network\":\"contiv-net1.default\",\n \"serviceName\":\"serviceLb1\"\n },\n {\n \"containerID\":\"fbc5e16d9a2c1211d80c36e3e8c4bf7243f1478586941c6a50db2fe226174d4e\",\n \"homingHost\":\"cluster-node1\",\n \"ipAddress\":[\n \"20.1.1.5\",\n \"\"\n ],\n \"labels\":\"map[app:web com.docker.swarm.id:4555870c6d4af62b63ece84001271129cd437ee2abb72cf94c244f9a739e7827 env:prod]\",\n \"macAddress\":\"02:02:14:01:01:05\",\n \"name\":\"b31de2e1be08e6b741210f8028ed442393b49bd2bfbf81c7085cab10454cead0\",\n \"network\":\"contiv-net1.default\",\n \"serviceName\":\"serviceLb1\"\n }\n ],\n \"serviceVip\":\"20.1.1.2\"\n }\n }\n\n\n describe('servicelbslistctrl', function () {\n var $httpBackend;\n\n beforeEach(inject(function (_$httpBackend_) {\n $httpBackend = _$httpBackend_;\n $httpBackend.when('GET', ContivGlobals.SERVICELBS_ENDPOINT).respond(servicelbListData);\n }));\n\n afterEach(function () {\n $httpBackend.verifyNoOutstandingExpectation();\n $httpBackend.verifyNoOutstandingRequest();\n });\n\n var $controller, $interval, $rootScope;\n var servicelbListCtrl;\n beforeEach(inject(function (_$interval_, _$rootScope_, _$controller_) {\n $interval = _$interval_;\n $rootScope = _$rootScope_;\n $controller = _$controller_;\n servicelbListCtrl = $controller('ServicelbListCtrl', { $interval: $interval, $scope: $rootScope });\n }));\n it('should be defined', function () {\n //spec body\n expect(servicelbListCtrl).toBeDefined();\n $httpBackend.flush();\n });\n it('ServicelbListCtrl should do a GET on /api/serviceLBs/ REST API', function () {\n $httpBackend.expectGET(ContivGlobals.SERVICELBS_ENDPOINT);\n $httpBackend.flush();\n });\n it('ServicelbListCtrl should have servicelbs array assigned to servicelbs property', function () {\n $httpBackend.expectGET(ContivGlobals.SERVICELBS_ENDPOINT);\n $httpBackend.flush();\n expect(Array.isArray(servicelbListCtrl.servicelbs)).toBeTruthy();\n expect(servicelbListCtrl.servicelbs.length).toEqual(2);\n });\n it('ServicelbListCtrl should have showLoader property set to false after fetch', function () {\n $httpBackend.expectGET(ContivGlobals.SERVICELBS_ENDPOINT);\n $httpBackend.flush();\n expect(servicelbListCtrl.showLoader).toBeFalsy();\n });\n });\n\n describe('servicelbscreatectrl', function () {\n\n var $httpBackend;\n\n beforeEach(inject(\n function (_$httpBackend_) {\n $httpBackend = _$httpBackend_;\n $httpBackend.when('GET', ContivGlobals.NETWORKS_ENDPOINT).respond(networkListData);;\n }));\n\n afterEach(function () {\n $httpBackend.verifyNoOutstandingExpectation();\n $httpBackend.verifyNoOutstandingRequest();\n });\n\n var $controller;\n beforeEach(inject(function (_$controller_) {\n $controller = _$controller_;\n }));\n it('should be defined', function () {\n //spec body\n var servicelbCreateCtrl = $controller(\n 'ServicelbCreateCtrl');\n expect(servicelbCreateCtrl).toBeDefined();\n $httpBackend.flush();\n });\n it('ServicelbCreateCtrl should do a GET on /api/networks/ REST API', function () {\n $controller('ServicelbCreateCtrl');\n $httpBackend.expectGET(ContivGlobals.NETWORKS_ENDPOINT);\n $httpBackend.flush();\n });\n\n });\n\n describe('servicelbsdetailsctrl', function () {\n\n var $httpBackend, $state, $stateParams, $controller;\n var servicelbDetailsCtrl;\n\n beforeEach(inject(function (_$httpBackend_, _$state_, _$stateParams_, _$controller_) {\n $httpBackend = _$httpBackend_;\n $httpBackend.when('GET', ContivGlobals.SERVICELBS_ENDPOINT).respond(servicelbListData);\n $httpBackend.when('PUT', ContivGlobals.SERVICELBS_ENDPOINT + servicelbListData[0].key + '/').respond(servicelbListData[0]);\n $httpBackend.when('DELETE', ContivGlobals.SERVICELBS_ENDPOINT + servicelbListData[0].key + '/').respond(servicelbListData[0]);\n $state = _$state_;\n $state.go = function (stateName) {};\n $stateParams = _$stateParams_;\n $stateParams.key = servicelbListData[0].key;\n $controller = _$controller_;\n servicelbDetailsCtrl = $controller('ServicelbDetailsCtrl');\n }));\n\n afterEach(function () {\n $httpBackend.verifyNoOutstandingExpectation();\n $httpBackend.verifyNoOutstandingRequest();\n });\n\n\n it('should be defined', function () {\n //spec body\n expect(servicelbDetailsCtrl).toBeDefined();\n $httpBackend.flush();\n });\n it('ServicelbDetailsCtrl should do a GET on /api/serviceLBs/ REST API', function () {\n $httpBackend.expectGET(ContivGlobals.SERVICELBS_ENDPOINT);\n $httpBackend.flush();\n });\n it('ServicelbDetailsCtrl.saveServicelb() should do a PUT on /api/serviceLBs/ REST API', function () {\n $httpBackend.expectGET(ContivGlobals.SERVICELBS_ENDPOINT);\n $httpBackend.flush();\n servicelbDetailsCtrl.saveServicelb();\n $httpBackend.expectPUT(ContivGlobals.SERVICELBS_ENDPOINT+ servicelbListData[0].key + '/');\n $httpBackend.flush();\n expect(servicelbDetailsCtrl.showLoader).toBeFalsy();\n });\n it('ServicelbDetailsCtrl.deleteServicelb() should do a DELETE on /api/serviceLBs/ REST API', function () {\n $httpBackend.expectGET(ContivGlobals.SERVICELBS_ENDPOINT);\n $httpBackend.flush();\n servicelbDetailsCtrl.deleteServicelb();\n $httpBackend.expectDELETE(ContivGlobals.SERVICELBS_ENDPOINT + servicelbListData[0].key + '/');\n $httpBackend.flush();\n expect(servicelbDetailsCtrl.showLoader).toBeFalsy();\n });\n it('ServicelbDetailsCtrl should have servicelb object assigned to servicelb property', function () {\n $httpBackend.expectGET(ContivGlobals.SERVICELBS_ENDPOINT);\n $httpBackend.flush();\n expect(servicelbDetailsCtrl.servicelb).toEqual(servicelbListData[0]);\n });\n it('ServicelbDetailsCtrl should have showLoader property set to false after fetch', function () {\n $httpBackend.expectGET(ContivGlobals.SERVICELBS_ENDPOINT);\n $httpBackend.flush();\n expect(servicelbDetailsCtrl.showLoader).toBeFalsy();\n });\n });\n\n describe('ServicelbStatsCtrl', function () {\n\n var $controller, $state, $stateParams, $interval, $rootScope, $httpBackend;\n var servicelbStatsCtrl;\n \n \n beforeEach(inject(function (_$state_ ,_$stateParams_, _$rootScope_, _$interval_, _$controller_, _$httpBackend_) {\n $httpBackend = _$httpBackend_;\n $httpBackend.when('GET', ContivGlobals.SERVICELBS_INSPECT_ENDPOINT+servicelbListData[0].key+'/').respond(servicelbOperData);\n $state = _$state_;\n $interval = _$interval_;\n $rootScope = _$rootScope_;\n $stateParams = _$stateParams_;\n $stateParams.key = servicelbListData[0].key;\n $controller = _$controller_;\n servicelbStatsCtrl = $controller('ServicelbStatsCtrl',{ $state: $state, $stateParams: $stateParams, $scope: $rootScope, $interval: $interval});\n }));\n\n afterEach(function () {\n $httpBackend.verifyNoOutstandingExpectation();\n $httpBackend.verifyNoOutstandingRequest();\n });\n\n it('should be defined', function () {\n expect(servicelbStatsCtrl).toBeDefined();\n $httpBackend.flush();\n\n });\n it('servicelbStatsCtrl should do a GET on /api/v1/inspect/serviceLBs/default:serviceLb1/ REST API', function () {\n $httpBackend.expectGET(ContivGlobals.SERVICELBS_INSPECT_ENDPOINT+servicelbListData[0].key+'/');\n $httpBackend.flush();\n });\n it('servicelbStatsCtrl should construct providers object', function () {\n $httpBackend.flush();\n expect(servicelbStatsCtrl.providers).toBeDefined();\n expect(Array.isArray(servicelbStatsCtrl.providers)).toBeTruthy();\n expect(servicelbStatsCtrl.providers.length).toEqual(servicelbOperData.Oper.providers.length);\n });\n it('servicelbStatsCtrl should construct providerDetails object', function () {\n $httpBackend.flush();\n expect(servicelbStatsCtrl.providerDetails).toBeDefined();\n var len = Object.keys(servicelbStatsCtrl.providerDetails).length;\n expect(len).toEqual(3);\n });\n });\n});\n" }, { "alpha_fraction": 0.6305143237113953, "alphanum_fraction": 0.6335269808769226, "avg_line_length": 39.75438690185547, "blob_id": "6c63b5a18dde6db4492c1c3e0dc721ce360e058f", "content_id": "682246a2921f34f746ba10ea6d9d2cd35004dcb1", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4647, "license_type": "permissive", "max_line_length": 159, "num_lines": 114, "path": "/app/networks/networkdetailsctrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 10/14/16.\n */\n\nimport {Component, OnInit, OnDestroy, Inject} from \"@angular/core\";\nimport {CRUDHelperService} from \"../components/utils/crudhelperservice\";\nimport {Observable, Subscription} from \"rxjs\";\nimport {ApplicationGroupsModel} from \"../components/models/applicationgroupsmodel\";\nimport {NetworksModel} from \"../components/models/networksmodel\";\nimport {isUndefined} from \"util\";\nimport {ActivatedRoute, Router} from \"@angular/router\";\nimport {NotificationType} from \"../components/directives/notification\";\nvar _ = require('lodash');\ndeclare var jQuery:any;\n\n@Component({\n selector: 'networkdetails',\n templateUrl: \"./networkdetails.html\"\n})\n\nexport class NetworkdetailsComponent implements OnInit, OnDestroy{\n private applicationGroupsModel:ApplicationGroupsModel;\n private networksModel: NetworksModel;\n private crudHelperService: CRUDHelperService;\n public networkDetailsCtrl: any;\n private refresh: Subscription;\n public network: any;\n public infoselected: boolean;\n public statskey: string;\n\n constructor(private route: ActivatedRoute,\n private router: Router,\n applicationGroupsModel: ApplicationGroupsModel,\n networksModel: NetworksModel,\n crudHelperService: CRUDHelperService){\n\n this.applicationGroupsModel = applicationGroupsModel;\n this.networksModel = networksModel;\n this.crudHelperService = crudHelperService;\n this.infoselected = true;\n this.statskey='';\n this['showLoader'] = true;\n this.network = {networkName: '', encap: '', subnet: '', gateway: ''};\n this.refresh=Observable.interval(5000).subscribe(() => {\n if(this['showloader']!=true)\n this.getApplicationGroups(true);\n });\n this.networkDetailsCtrl = this;\n }\n\n ngOnInit(){\n this.crudHelperService.startLoader(this);\n this.statskey = this.route.snapshot.params['key'];\n this.getNetwork(false);\n }\n\n getApplicationGroups(reload: boolean){\n var networkDetailsCtrl = this;\n if(!isUndefined(networkDetailsCtrl['network'])){\n this.applicationGroupsModel.get(reload)\n .then(function successCallback(result){\n networkDetailsCtrl['applicationGroups'] = _.filter(result, {\n 'networkName': networkDetailsCtrl['network'].networkName,\n 'tenantName': networkDetailsCtrl['network'].tenantName\n });\n networkDetailsCtrl.crudHelperService.stopLoader(networkDetailsCtrl);\n },\n function errorCallback(result){\n networkDetailsCtrl.crudHelperService.stopLoader(networkDetailsCtrl);\n });\n }\n }\n\n getNetwork(reload: boolean){\n var networkDetailsCtrl = this;\n this.networksModel.getModelByKey(this.route.snapshot.params['key'], reload, 'key')\n .then((result) => {\n networkDetailsCtrl['network'] = result;\n networkDetailsCtrl.getApplicationGroups(false);\n }, (error) => {\n networkDetailsCtrl.crudHelperService.stopLoader(networkDetailsCtrl);\n })\n }\n\n deleteNetwork(){\n var networkDetailsCtrl = this;\n this.crudHelperService.startLoader(networkDetailsCtrl);\n if (!isUndefined(networkDetailsCtrl['network'])){\n this.networksModel.delete(networkDetailsCtrl['network'])\n .then((result) => {\n networkDetailsCtrl.crudHelperService.stopLoader(networkDetailsCtrl);\n networkDetailsCtrl.crudHelperService.showNotification(\"Network: Deleted\", result.toString());\n networkDetailsCtrl.returnToNetworks();\n }, (error) => {\n networkDetailsCtrl.crudHelperService.stopLoader(networkDetailsCtrl);\n networkDetailsCtrl.crudHelperService.showServerError(\"Network: Delete failed\", error);\n })\n }\n setTimeout(() => {\n if(networkDetailsCtrl['showLoader']==true){\n networkDetailsCtrl.crudHelperService.showNotification(\"Network: Delete task submitted\", networkDetailsCtrl.network.key, NotificationType.info);\n networkDetailsCtrl.crudHelperService.stopLoader(networkDetailsCtrl);\n }\n },2000);\n }\n\n returnToNetworks(){\n this.router.navigate(['../../list'], {relativeTo: this.route});\n }\n\n ngOnDestroy(){\n this.refresh.unsubscribe();\n }\n}\n\n" }, { "alpha_fraction": 0.4961715042591095, "alphanum_fraction": 0.509954035282135, "avg_line_length": 24.153846740722656, "blob_id": "3b835bd7783de8114deb96199ea3d744131ac2bf", "content_id": "63c4d09ccbb346f1386d58533a6db20d65c29bc1", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 653, "license_type": "permissive", "max_line_length": 53, "num_lines": 26, "path": "/app/components/pipes/filterpipe.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 10/21/16.\n */\nimport { Pipe, PipeTransform } from \"@angular/core\";\n@Pipe({\n name: 'filter',\n pure: false\n})\nexport class FilterPipe implements PipeTransform {\n transform(items:any[], searchText:string): any[]{\n var selectedItems = [];\n if(searchText.length === 0){\n return items;\n }\n for(var item of items){\n var str='';\n for(var key in item){\n str+=JSON.stringify(item[key]);\n }\n if (str.search(searchText) > -1){\n selectedItems.push(item);\n }\n }\n return selectedItems;\n }\n}" }, { "alpha_fraction": 0.5680190920829773, "alphanum_fraction": 0.6038185954093933, "avg_line_length": 20, "blob_id": "2007b4475ea2f2d14c43bce02ff734834c7c9add", "content_id": "f7f608278a3d7490eaaa0ee9cff885ce4ec3860e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 419, "license_type": "permissive", "max_line_length": 55, "num_lines": 20, "path": "/app/components/directives/tooltip.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 1/13/17.\n */\n\n\nimport {Component, Input, OnInit} from \"@angular/core\";\n@Component({\n selector: \"tooltip\",\n templateUrl: './tooltip.html',\n styleUrls: ['./tooltip.css']\n})\n\nexport class TooltipComponent implements OnInit{\n @Input('width') width: number = 400;\n public padding: number = 20;\n ngOnInit(){\n if (this.width <= 200)\n this.padding = 10;\n }\n}" }, { "alpha_fraction": 0.5680317282676697, "alphanum_fraction": 0.574636697769165, "avg_line_length": 22.671875, "blob_id": "6d907f2bfbfc5be053b905a85f66ce3e557f3ad5", "content_id": "9b4bd087105bec1f323849b8dc7f9545a6eeb4eb", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1514, "license_type": "permissive", "max_line_length": 77, "num_lines": 64, "path": "/app/components/directives/namevaluedirective.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 10/17/16.\n */\n\n\nimport {Component, Input, Output, EventEmitter, OnInit} from \"@angular/core\";\nvar _ = require('lodash');\n\nexport interface Item{\n name: string;\n value: string;\n}\n\n@Component({\n selector:'ctv-namevalue',\n templateUrl:'./namevalue.html'\n})\n\nexport class CtvNamevalueComponent{\n @Input('items') items: Item[];\n @Input('nameheader') nameheader: string;\n @Input('options') options:string[];\n @Input('valueheader') valueheader: string;\n @Output('itemsChange') itemsChange: EventEmitter<any>;\n @Input('type') type: string;\n public newItem:Item;\n constructor(){\n this.itemsChange = new EventEmitter<any>();\n this.items=[];\n this.nameheader = 'Name';\n this.valueheader = 'Value';\n this.type = 'text';\n this.newItem = {name: '', value: ''};\n this.options=[];\n }\n\n public resetItem(): void{\n this.newItem = {name:'',value:''};\n }\n\n\n public add(): void{\n function compare(val1, val2){\n return val1.name == val2.name;\n }\n\n if (this.newItem.name == '' && this.newItem.value == ''){\n return;\n }\n\n _.pullAllWith(this.items, [this.newItem], compare);\n\n this.items.push(this.newItem);\n this.itemsChange.emit(this.items);\n this.resetItem();\n }\n\n public remove(passedItem: Item): void{\n _.remove(this.items, function(item){\n return item.name == passedItem.name;\n });\n }\n\n}" }, { "alpha_fraction": 0.5987608432769775, "alphanum_fraction": 0.600247859954834, "avg_line_length": 34.377193450927734, "blob_id": "c35737ddb25bfe1c838d198186d4a0ecbc417c7c", "content_id": "e2da1769e733cf66a8b2fd920a448c1b2ee00901", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4035, "license_type": "permissive", "max_line_length": 128, "num_lines": 114, "path": "/app/service_lbs/servicelbcreatectrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 10/14/16.\n */\n\nimport { Component, OnInit, OnDestroy, Inject, NgZone } from \"@angular/core\";\nimport { CRUDHelperService } from \"../components/utils/crudhelperservice\";\nimport { ServicelbsModel } from \"../components/models/servicelbsmodel\";\nimport { NetworksModel } from \"../components/models/networksmodel\";\nimport { Router, ActivatedRoute } from \"@angular/router\";\nimport { OrganizationsModel } from \"../components/models/organizationsmodel\";\nvar _ = require('lodash');\n\n\n@Component({\n selector: 'servicelbCreate',\n templateUrl: './servicelbcreate.html'\n})\n\nexport class ServicelbCreateComponent implements OnInit {\n servicelbCreateCtrl:any;\n servicelb:any;\n networks:any[] = [];\n labelSelectors:any[] = [];\n tenants:any[] = [];\n\n constructor(private router:Router,\n private activatedRoute:ActivatedRoute,\n private ngZone:NgZone,\n private organizationsModel:OrganizationsModel,\n private servicelbsModel:ServicelbsModel,\n private crudHelperService:CRUDHelperService,\n private networksModel:NetworksModel) {\n this.servicelb = {\n serviceName: '',\n networkName: '',\n ipAddress: '',\n selectors: [],\n ports: [],\n tenantName: '',\n key: ''\n };\n this.servicelbCreateCtrl = this;\n }\n\n ngOnInit() {\n var component = this;\n component.crudHelperService.startLoader(this);\n\n function getTenants(reload:boolean) {\n component.organizationsModel.get(reload)\n .then((result) => {\n component.tenants = result;\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n }, (error) => {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n });\n }\n\n getTenants(false);\n }\n\n getNetworks(tenantName:string) {\n var servicelbCreateCtrl = this;\n this.networksModel.get(false)\n .then((result) => {\n servicelbCreateCtrl.networks = _.filter(result, {'tenantName': tenantName});\n servicelbCreateCtrl.crudHelperService.stopLoader(servicelbCreateCtrl);\n }, (error) => {\n servicelbCreateCtrl.crudHelperService.stopLoader(servicelbCreateCtrl);\n });\n }\n\n createServicelb(formvalid:boolean) {\n var servicelbCreateCtrl = this;\n this.createLabelSelectorStrings();\n if (formvalid) {\n this.crudHelperService.startLoader(this);\n this.servicelb.key = this.servicelb.tenantName + ':' + this.servicelb.serviceName;\n this.servicelbsModel.create(this.servicelb, undefined).then((result) => {\n servicelbCreateCtrl.crudHelperService.stopLoader(servicelbCreateCtrl);\n servicelbCreateCtrl.crudHelperService.showNotification(\"Service load balancer: Created\", result.key.toString());\n this.returnToServicelbs();\n }, (error) => {\n servicelbCreateCtrl.crudHelperService.stopLoader(servicelbCreateCtrl);\n servicelbCreateCtrl.crudHelperService.showServerError(\"Service load balancer: Create failed\", error);\n });\n }\n }\n\n cancelCreating() {\n this.returnToServicelbs();\n }\n\n returnToServicelbs() {\n this.router.navigate(['../list'], {relativeTo: this.activatedRoute});\n }\n\n createLabelSelectorStrings() {\n this.labelSelectors.forEach((labelSelector) => {\n var selectorString = labelSelector.name + '=' + labelSelector.value;\n this.servicelb.selectors.push(selectorString);\n })\n }\n\n updateTenant(tenantName:string) {\n this.servicelb.tenantName = tenantName;\n this.getNetworks(tenantName);\n\n }\n}\n\n\n" }, { "alpha_fraction": 0.6602671146392822, "alphanum_fraction": 0.6686143279075623, "avg_line_length": 25.64444351196289, "blob_id": "306ba0653e47a8b32b1db8a932a5416185df7a67", "content_id": "809d8094576c21e4e26af81bbcc20372f25edde8", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1198, "license_type": "permissive", "max_line_length": 62, "num_lines": 45, "path": "/app/firstrunwizard/firstrunnetworkcreate.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 2/12/17.\n */\n\n\n\nimport {Component, EventEmitter, Output} from \"@angular/core\";\nimport {FirstRunWizardService} from \"./firstrunwizardservice\";\n@Component({\n selector: 'firstrunnetworkcreate',\n templateUrl: './firstrunnetworkcreate.html'\n})\n\nexport class FirstrunNetworkCreateComponent{\n @Output('updatePage') updatePage:EventEmitter<any>;\n @Output('cancelPage') cancelPage:EventEmitter<any>;\n public clusterMode: string = '';\n public newNetwork: any;\n public networkPresent: boolean;\n constructor(private wizardService: FirstRunWizardService){\n this.updatePage = new EventEmitter<any>();\n this.cancelPage = new EventEmitter<any>();\n this.clusterMode = this.wizardService.clusterMode;\n this.newNetwork = this.wizardService.newNetwork\n }\n\n createNetwork(network: any){\n this.wizardService.skipArray[2] = false;\n this.wizardService.newNetwork = network;\n this.updatePage.emit(3);\n }\n\n goBack(){\n this.updatePage.emit(1);\n }\n\n skip(){\n this.wizardService.skipArray[2] = true;\n this.updatePage.emit(3)\n }\n\n cancel(){\n this.cancelPage.emit();\n }\n}" }, { "alpha_fraction": 0.5719649791717529, "alphanum_fraction": 0.5764706134796143, "avg_line_length": 31.754098892211914, "blob_id": "9242c125ae7bc1a21c366d17d3eb2ab39b944371", "content_id": "fb41e42e04fa4534bede4368c097784ff154629a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3995, "license_type": "permissive", "max_line_length": 91, "num_lines": 122, "path": "/app/components/utils/authservice.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 11/4/16.\n */\n\nimport { Injectable } from '@angular/core';\n\nimport { Observable } from 'rxjs/Observable';\nimport { Http, Headers, RequestOptions, Response } from \"@angular/http\";\nimport { AuthMatrix } from \"./authMatrix\";\nimport { isNull } from \"util\";\nimport { ContivGlobals } from \"../models/contivglobals\";\nimport { Subject } from \"rxjs\";\n\ninterface User{\n username: string;\n password: string;\n}\n\n@Injectable()\nexport class AuthService {\n isLoggedIn: boolean = false;\n\n // store the URL so we can redirect after logging in\n redirectUrl: string;\n headers: Headers;\n authTokenPayload: any;\n accessMatrix:any;\n authToken:string;\n username: string;\n public localUser: boolean = true;\n\n constructor(private http: Http){\n this.isLoggedIn = false;\n this.redirectUrl = '';\n this.accessMatrix = AuthMatrix;\n this.authTokenPayload = {};\n this.authToken='';\n }\n\n checkAccess(url: string): boolean{\n var searchUrl = url.replace('/m/', '');\n if(searchUrl.indexOf('details') > -1 || searchUrl.indexOf('edit') > -1)\n searchUrl = searchUrl.replace(/\\/[^\\/]*$/,'');\n if(searchUrl.indexOf('policyTab') > -1)\n searchUrl = searchUrl.replace(/;[^\\/]*$/,'');\n var role = this.authTokenPayload['role'];\n if (this.accessMatrix[searchUrl][role]=='y')\n return true;\n else\n return false;\n }\n\n login(user: User): Observable<any> {\n this.headers = new Headers();\n this.username = user.username;\n this.headers.append('Content-Type', 'application/json');\n var options = new RequestOptions({headers: this.headers});\n\n /* Use the below code if you are calling netmaster apis through CCN_Proxy */\n return this.http.post(ContivGlobals.LOGIN_ENDPOINT, user, options)\n .map((res) => {\n var s = this.extractToken(res);\n if (s){\n this.isLoggedIn = true;\n return true;\n }\n else{\n this.isLoggedIn = false;\n return false;\n }\n })\n .catch((error:any) => Observable.throw(error));\n }\n\n encodeUrlData(body: any) :string{\n var str = Object.keys(body).map(function(key){\n return encodeURIComponent(key) + '=' + encodeURIComponent(body[key]);\n }).join('&');\n return str;\n }\n\n extractToken(res: Response): boolean {\n /* auth_proxy is now sending the token as part of the body */\n\n var xAuthToken = res.json()['token'];\n if (xAuthToken.length > 0) {\n localStorage.setItem(\"authToken\", xAuthToken);\n localStorage.setItem(\"lastAccessTime\", new Date().getTime().toString());\n localStorage.setItem(\"username\", this.username);\n this.extractBody();\n return true;\n }\n else{\n return false;\n }\n }\n\n extractBody(): void{\n var token = localStorage.getItem(\"authToken\");\n this.authToken = token;\n var bodyEncoded = token.split('.')[1];\n var bodyString = atob(bodyEncoded);\n this.authTokenPayload = JSON.parse(bodyString);\n if(!isNull(this.authTokenPayload['username'].match(ContivGlobals.LDAPGROUP_REGEX)))\n this.localUser = false;\n this.username = localStorage.getItem(\"username\");\n }\n\n validateExpiry(): boolean{\n let currentDate: Date = new Date();\n let lastAccessTime: string = localStorage.getItem(\"lastAccessTime\");\n if(isNull(lastAccessTime)){\n return false;\n }\n let durationEloped = (currentDate.getTime() - parseInt(lastAccessTime)) / 60000;\n if((durationEloped >= 0) && (durationEloped < 60)){\n localStorage.setItem(\"lastAccessTime\", currentDate.getTime().toString());\n return true;\n }\n return false;\n }\n}" }, { "alpha_fraction": 0.6229977011680603, "alphanum_fraction": 0.6258581280708313, "avg_line_length": 31.33333396911621, "blob_id": "e333b9eb4295d481ef6da3ee6d77459d5eb3d71a", "content_id": "8ce6889866a66e53f85785c503a126c735a6e457", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1748, "license_type": "permissive", "max_line_length": 125, "num_lines": 54, "path": "/app/applicationgroups/bandwidthpolicydirective.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by hardik gandhi on 6/28/16.\n */\nimport { Component, Input, OnChanges } from '@angular/core';\nimport * as _ from 'lodash';\nimport { NetprofilesModel } from \"../components/models/netprofilesmodel\";\nimport { isUndefined } from \"util\";\n\n@Component({\n selector: 'ctv-bandwidthpolicy',\n templateUrl: './bandwidthpolicy.html'\n})\nexport class BandwidthPolicySelectionComponent implements OnChanges {\n @Input('mode') mode:string;\n @Input('applicationgroup') applicationgroup:any;\n\n netProfiles:any[] = [];\n selectedNetprofile:any = {};\n netProfileSearchText:string = '';\n\n constructor(private netprofilesModel:NetprofilesModel) {\n }\n\n ngOnChanges() {\n var component = this;\n component.getNetprofiles();\n }\n\n /**\n * Get profiles for the given tenant.\n */\n getNetprofiles() {\n var component = this;\n component.netprofilesModel.get(false).then(function (result) {\n component.netProfiles = _.filter(result, {\n 'tenantName': component.applicationgroup.tenantName\n });\n if ((component.applicationgroup.netProfile !== '') && (!isUndefined(component.applicationgroup['netProfile']))) {\n component.selectedNetprofile = _.find(component.netProfiles, function (policy) {\n return policy.profileName === component.applicationgroup.netProfile;\n });\n }\n });\n }\n\n updateApplicationgroup(netprofile) {\n this.selectedNetprofile = netprofile;\n if (this.selectedNetprofile === null) {\n this.applicationgroup.netProfile = '';\n } else {\n this.applicationgroup.netProfile = this.selectedNetprofile.profileName;\n }\n };\n}\n\n\n" }, { "alpha_fraction": 0.7122927308082581, "alphanum_fraction": 0.7138720750808716, "avg_line_length": 39.84946060180664, "blob_id": "b5321f2bf1f9999f205c362a296d6490ab96c9b0", "content_id": "309b7ec127b86ce09e65ced90d1d18d725577b88", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3799, "license_type": "permissive", "max_line_length": 88, "num_lines": 93, "path": "/app/app.module.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 10/6/16.\n */\nimport { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\nimport { HttpModule } from \"@angular/http\";\nimport { APP_BASE_HREF, HashLocationStrategy, LocationStrategy } from '@angular/common';\nimport { DashboardModule } from \"./dashboard/dashboard.module\";\nimport { NetworkPoliciesModule } from \"./network_policies/networkpolicies.module\";\nimport { SettingsModule } from \"./settings/settings.module\";\nimport { NetworkModule } from \"./networks/network.module\";\nimport { ServicelbModule } from \"./service_lbs/servicelb.module\";\nimport { AppProfilesModule } from \"./appprofiles/appprofile.module\";\nimport { UsersModule } from \"./settings/users/users.module\";\nimport { NetprofilesModel } from \"./components/models/netprofilesmodel\";\nimport { ApplicationGroupsModel } from \"./components/models/applicationgroupsmodel\";\nimport { NetworksModel } from \"./components/models/networksmodel\";\nimport { OrganizationsModel } from \"./components/models/organizationsmodel\";\nimport { PoliciesModel } from \"./components/models/policiesmodel\";\nimport { RulesModel } from \"./components/models/rulesmodel\";\nimport { ServicelbsModel } from \"./components/models/servicelbsmodel\";\nimport { UsersModel } from \"./components/models/usersmodel\";\nimport { AppProfilesModel } from \"./components/models/appprofilesmodel\";\nimport { BgpsModel } from \"./components/models/bgpsmodel\";\nimport { ContractGroupsModel } from \"./components/models/contractgroupsmodel\";\nimport { CRUDHelperService } from \"./components/utils/crudhelperservice\";\nimport { InspectService } from \"./components/utils/inspectservice\";\nimport { NetworkService } from \"./components/utils/networkservice\";\nimport { MenuModule } from \"./menu/menu.module\";\nimport { AppComponent } from \"./app.component\";\nimport { LoginModule } from \"./login/login.module\";\nimport { AuthService } from \"./components/utils/authservice\";\nimport { AuthGuard } from \"./components/utils/authguard\";\nimport { ApiService } from \"./components/utils/apiservice\";\nimport { FirstrunWizardModule } from \"./firstrunwizard/firstrunwizard.module\";\nimport { ChartService } from \"./components/utils/chartservice\";\nimport { AuthorizationModel } from \"./components/models/authorizationmodel\";\nimport { ApplicationGroupsModule } from \"./applicationgroups/applicationgroups.module\";\nimport appRoutes from \"./app.routes\";\nimport { AuthorizationModule } from \"./settings/authorization/authorization.module\";\nimport { OrganizationModule } from \"./settings/tenants/organization.module\";\nimport { FirstRunService } from \"./components/utils/firstrunservice\";\n\n\n@NgModule({\n imports: [\n BrowserModule,\n HttpModule,\n appRoutes,\n MenuModule,\n DashboardModule,\n NetworkPoliciesModule,\n ApplicationGroupsModule,\n SettingsModule,\n NetworkModule,\n ServicelbModule,\n AppProfilesModule,\n OrganizationModule,\n LoginModule,\n UsersModule,\n AuthorizationModule,\n FirstrunWizardModule\n ],\n declarations: [\n AppComponent\n ],\n providers: [\n ApplicationGroupsModel,\n NetprofilesModel,\n NetworksModel,\n OrganizationsModel,\n PoliciesModel,\n RulesModel,\n ServicelbsModel,\n UsersModel,\n AppProfilesModel,\n BgpsModel,\n ContractGroupsModel,\n AuthorizationModel,\n CRUDHelperService,\n InspectService,\n NetworkService,\n AuthService,\n AuthGuard,\n ApiService,\n ChartService,\n FirstRunService,\n { provide: APP_BASE_HREF, useValue: '' },\n { provide: LocationStrategy, useClass: HashLocationStrategy }\n ],\n bootstrap: [ AppComponent ]\n})\nexport class AppModule {}\n" }, { "alpha_fraction": 0.5256254076957703, "alphanum_fraction": 0.5436241626739502, "avg_line_length": 26.554622650146484, "blob_id": "d5d2f831abf2213926ac2e7217576ce34254dbcb", "content_id": "d2e9b91670a755f87a66b0ef84ec3daa833e828d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3278, "license_type": "permissive", "max_line_length": 112, "num_lines": 119, "path": "/e2e-tests/testConfiguration.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 8/17/16.\n */\n\nglobal.testConfig = {\n networks:{\n name:\"a-Test-Net\",\n encap:\"'vxlan'\",\n cidr:\"20.1.6.0/24\",\n gateway:\"20.1.6.254\"\n },\n\n storagePolicy:{\n name: \"a-Test-Volume-Policy\",\n pool: \"rbd\",\n size: \"10MB\",\n fileSystem: {\n name: \"string:ext4\",\n type: \"ext4\",\n command: \"mkfs.ext4 -m0 %\"\n },\n\n snapshot: {\n enabled: \"true\",\n frequency: \"30m\",\n noofsnaps: \"20\",\n },\n\n readWriteOp: {\n writeiops: \"\",\n readiops: \"\",\n writebps: \"10000000\",\n readbps: \"10000000\"\n },\n\n backend: {\n driver: \"ceph\",\n mount: \"ceph\",\n snap: \"ceph\"\n }\n \n },\n\n volumes: {\n name: \"a-Test-Volume27\",\n policy: \"a-Test-Volume-Policy\",\n newvolume: \"a-VTest-Volume-Copy27\"\n },\n\n getVerificationList: flattenObjects,\n verifyCreate: verifyCreate,\n clickLink: clickLink,\n removeObject: removeObject,\n waitForPageLoad: waitForPageLoad\n}\n\nfunction flattenObjects(pageObject){\n var fieldValues = [];\n function recurseObj(subObj){\n for(key in subObj){\n if(subObj[key] === null) continue;\n if(typeof subObj[key] === 'object')\n recurseObj(subObj[key]);\n else\n fieldValues.push(subObj[key]);\n }\n }\n recurseObj(pageObject);\n return fieldValues;\n}\n\nfunction verifyCreate(createElement, name){\n expect(createElement.getText()).toEqual(name);\n var linkRef = \"\"\n createElement.getAttribute(\"href\").then(function(href){\n linkRef = href.replace(\"%3A\", \":\");\n });\n createElement.click().then(function(){\n expect(browser.getCurrentUrl()).toEqual(linkRef);\n });\n}\n\nfunction clickLink(createButton){\n var createHref = createButton.getAttribute(\"href\");\n var createUrl = \"\";\n createHref.then(function(href){\n createUrl = href.replace(\"http://localhost:8080/\",\"\");\n });\n createButton.click().then(function(){\n expect(browser.getCurrentUrl()).toEqual(browser.params.globBaseUrl + createUrl);\n });\n}\n\nfunction removeObject(page, itemName){\n browser.get(page);\n element(by.cssContainingText(\"a\", itemName)).isPresent().then(function(present){\n if(present){\n element(by.cssContainingText(\"a\", itemName)).click().then(function(){\n element(by.cssContainingText(\"button\", \"Remove\")).isPresent().then(function(){\n element(by.cssContainingText(\"button\", \"Remove\")).click().then(function(){\n element(by.cssContainingText(\"div.positive.button\", \"Yes\")).isPresent().then(function(){\n element(by.cssContainingText(\"div.positive.button\", \"Yes\")).click();\n });\n });\n });\n });\n }\n });\n}\n\nfunction waitForPageLoad(sec){\n browser.driver.sleep(parseInt(sec));\n var el = element(by.css(\"div.inverted.dimmer\"));\n return browser.driver.wait(function() {\n return el.isDisplayed().then(function(present) {\n return !present;\n })\n });\n}" }, { "alpha_fraction": 0.7916666865348816, "alphanum_fraction": 0.7916666865348816, "avg_line_length": 31, "blob_id": "98f3f63a437146dea7b0311dee284cfade3f9b21", "content_id": "9aced93ff0ad60fa8a4e6f76d89304c5044e9a8c", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 96, "license_type": "permissive", "max_line_length": 53, "num_lines": 3, "path": "/Dockerfile", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "FROM nginx\nCOPY contiv-nginx.conf /etc/nginx/conf.d/default.conf\nCOPY app /usr/share/nginx/html\n" }, { "alpha_fraction": 0.6140089631080627, "alphanum_fraction": 0.6169895529747009, "avg_line_length": 39.43373489379883, "blob_id": "87ee16ff57c631f4c7d15295cdac02c93a282d94", "content_id": "e61b7d152f53c30c10a5d87c16edec20297c464b", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3355, "license_type": "permissive", "max_line_length": 141, "num_lines": 83, "path": "/app/applicationgroups/applicationgroupstats.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 11/18/16.\n */\n\nimport {Component, NgZone, Input, OnInit, OnDestroy} from \"@angular/core\";\nimport {ApplicationGroupsModel} from \"../components/models/applicationgroupsmodel\";\nimport {CRUDHelperService} from \"../components/utils/crudhelperservice\";\nimport {InspectService} from \"../components/utils/inspectservice\";\nimport {Subscription, Observable} from \"rxjs\";\nimport {ContivGlobals} from \"../components/models/contivglobals\";\nimport {isUndefined} from \"util\";\n@Component({\n selector: 'applicationgroupstats',\n templateUrl: './applicationgroupstats.html'\n})\n\nexport class ApplicationGroupStatsComponent implements OnInit, OnDestroy{\n @Input('statkey') statkey: string;\n public applicationInspectStats: any;\n private refresh: Subscription;\n public showLoader: boolean;\n config:any; endpoints:any; filteredendpoints: any; containerDetails: any;\n constructor(private applicationGroupsModel: ApplicationGroupsModel,\n private crudHelperService: CRUDHelperService,\n private inspectService: InspectService,\n private ngZone: NgZone){\n this.statkey = '';\n this.applicationInspectStats = {\n externalPktTag: '',\n numEndpoints: '',\n pktTag: ''\n };\n this.config = {networkName: '', groupName: ''}\n this.endpoints = [];\n this.filteredendpoints = [];\n this.containerDetails= {};\n this.refresh = Observable.interval(5000).subscribe(() => {\n if(this.statkey!='')\n this.getApplicationgroupInspect(true);\n });\n }\n\n ngOnInit(){\n this.crudHelperService.startLoader(this);\n if(this.statkey!='')\n this.getApplicationgroupInspect(false);\n }\n\n getApplicationgroupInspect(reload: boolean){\n var applicationStatsCtrl = this;\n this.applicationGroupsModel.getInspectByKey(this.statkey, ContivGlobals.APPLICATIONGROUPS_INSPECT_ENDPOINT, reload)\n .then((result) => {\n applicationStatsCtrl['applicationInspectStats'] = result['Oper'];\n applicationStatsCtrl['config'] = result['Config'];\n if(!isUndefined(result['Oper'].endpoints)){\n var containerDetails = applicationStatsCtrl.inspectService.buildEndPoints(result['Oper'].endpoints);\n if(applicationStatsCtrl.inspectService.checkContainerChanged(applicationStatsCtrl['containerDetails'],containerDetails)){\n applicationStatsCtrl['endpoints'] = result['Oper'].endpoints;\n applicationStatsCtrl['containerDetails'] = containerDetails;\n }\n }\n else{\n applicationStatsCtrl['endpoints'] = [];\n applicationStatsCtrl['containerDetails'] = {};\n }\n applicationStatsCtrl.ngZone.run(() => {\n applicationStatsCtrl.crudHelperService.stopLoader(applicationStatsCtrl);\n });\n },\n (error) => {\n applicationStatsCtrl.ngZone.run(() => {\n applicationStatsCtrl.crudHelperService.stopLoader(applicationStatsCtrl);\n });\n });\n\n\n }\n\n ngOnDestroy(){\n this.refresh.unsubscribe();\n }\n\n}" }, { "alpha_fraction": 0.5650929808616638, "alphanum_fraction": 0.6008583903312683, "avg_line_length": 17.421052932739258, "blob_id": "c6f714c71974a61eab371c4f07ded5ded203527b", "content_id": "f4cb92a41f9e89a62ff65a9423b9e51335912bcd", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 699, "license_type": "permissive", "max_line_length": 97, "num_lines": 38, "path": "/e2e-tests/protractor.conf.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "exports.config = {\n\n capabilities: {\n 'browserName': 'chrome'\n },\n\n seleniumServerJar: \"../node_modules/protractor/selenium/selenium-server-standalone-2.47.1.jar\",\n\n baseUrl: 'http://localhost:8080/',\n\n onPrepare: function() {\n browser.manage().window().setSize(1200, 1000);\n },\n\n specs: [\n './testConfiguration.js',\n './cleanup.js',\n './menu/*.js',\n './dashboard/*.js',\n './networks/*.js',\n './storage_policies/*.js',\n './volumes/*.js'\n ],\n\n framework: 'jasmine',\n\n\n params: {\n globBaseUrl: 'http://localhost:8080/'\n },\n\n jasmineNodeOpts: {\n showColors:true,\n defaultTimeoutInterval: 30000,\n isVerbose:true,\n includeStackTrace:true\n }\n};" }, { "alpha_fraction": 0.4602995216846466, "alphanum_fraction": 0.4617123603820801, "avg_line_length": 44.230770111083984, "blob_id": "d0fc073bc2cac7988b2280d814361bf993845a98", "content_id": "8afe18d1cfa59e639206f1f4c90a49a48dec544a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3539, "license_type": "permissive", "max_line_length": 111, "num_lines": 78, "path": "/app/visualization/visualizationlistctrl.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "angular.module('contiv.visualization')\n .config(['$stateProvider', function ($stateProvider) {\n $stateProvider\n .state('contiv.menu.visualization.list', {\n url: '/list',\n controller: 'VisualizationListCtrl as visualizationListCtrl',\n templateUrl: 'visualization/visualizationlist.html'\n })\n ;\n }])\n .controller('VisualizationListCtrl', [\"$scope\", \"$http\", 'VisualizationService', '$interval', \n function($scope, $http, VisualizationService, $interval) {\n //to see the expected format to be returned from these calls,\n //look at app/components/graphobjects/datasource/visualizerdatasource.js\n var successGraphDataCallback = function(result) {\n var nodes = [];\n var links = [];\n var nodeIds = [];\n _.forEach(result.results[0].series, function(series) {\n var endpoint = series.tags.EndpointIP;\n var provider = series.tags.ProviderIP;\n var node;\n //creating nodes\n if (_.includes(nodeIds, endpoint) == false) {\n node = {\n name: endpoint,\n id: endpoint,\n parent: null,\n ancestors: null\n };\n nodes.push(node);\n nodeIds.push(endpoint);\n }\n if (_.includes(nodeIds, provider) == false) {\n node = {\n name: provider,\n id: provider,\n parent: null,\n ancestors: null\n };\n nodes.push(node);\n nodeIds.push(provider);\n }\n //creating links\n var linkOut = {\n source: endpoint,\n target: provider,\n weight: series.values[0][2]\n };\n links.push(linkOut);\n var linkIn = {\n source: provider,\n target: endpoint,\n weight: series.values[0][1]\n };\n links.push(linkIn);\n });\n $scope.nodes = nodes;\n $scope.links = links;\n };\n //initial call\n VisualizationService.getGraphData().then(successGraphDataCallback, function errorCallback(result) {\n //will fail silently, graph won't be displayed\n });\n\n $scope.$on('$destroy', function () { $interval.cancel($scope.graphDataInterval); });\n\n VisualizationService.getStructureData().then(function successCallback(result) {\n //to see the expected form of ancestor_struct and children_struct, \n //look at app/components/graphobjects/datasource/visualizerdatasource.js\n $scope.ancestors_struct = result.ancestors_struct;\n $scope.children_struct = result.children_struct;\n $scope.labels = result.labels;\n $scope.serviceSelectors = result.serviceSelectors;\n }, function errorCallback(result) {\n //will fail silently, graph won't be displayed\n });\n }]);\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6331424713134766, "alphanum_fraction": 0.6367215514183044, "avg_line_length": 42.625, "blob_id": "0d764b1df186f15b74c8e9ba722a433a23070455", "content_id": "9ea64c748bdb85d8c39439cd80b0cf751158fb53", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2794, "license_type": "permissive", "max_line_length": 160, "num_lines": 64, "path": "/app/networks/networkcreatectrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 10/14/16.\n */\nimport { Component, Inject, Directive, OnInit, NgZone } from \"@angular/core\";\nimport { NetworksModel } from \"../components/models/networksmodel\";\nimport { CRUDHelperService } from \"../components/utils/crudhelperservice\";\nimport { Router, ActivatedRoute } from \"@angular/router\";\nimport { ContivGlobals } from \"../components/models/contivglobals\";\nimport { NotificationType } from \"../components/directives/notification\";\nimport { OrganizationsModel } from \"../components/models/organizationsmodel\";\n\n@Component({\n selector: 'networkcreate',\n templateUrl: './networkcreate.html'\n})\n\nexport class NetworkCreateComponent {\n networkCreateCtrl: any;\n newNetwork: any;\n tenants: any[] = [];\n\n constructor(private router: Router,\n private activatedRoute: ActivatedRoute,\n private networksModel: NetworksModel,\n private crudHelperService: CRUDHelperService){\n this['showLoader']=false;\n this['cidrPattern'] = ContivGlobals.CIDR_REGEX;\n this.newNetwork = {networkName: '', encap: 'vxlan', subnet:'', gateway:'', tenantName: '', key:'', nwType: '', pktTag: null, cfgdTag: ''};\n this.networkCreateCtrl = this;\n }\n\n returnToNetworks(){\n this.router.navigate(['../list'], {relativeTo: this.activatedRoute});\n }\n\n cancelCreating(){\n this.returnToNetworks();\n }\n\n createNetwork(network: any){\n var networkCreateCtrl = this;\n this.newNetwork = network;\n networkCreateCtrl.crudHelperService.startLoader(networkCreateCtrl);\n this.newNetwork.key = this.newNetwork.tenantName + ':' + this.newNetwork.networkName;\n this.networksModel.create(this.newNetwork,undefined)\n .then((result) => {\n networkCreateCtrl.crudHelperService.stopLoader(networkCreateCtrl);\n networkCreateCtrl.crudHelperService.showNotification(\"Network: Created\", result.key.toString());\n networkCreateCtrl.returnToNetworks();\n }, (error) => {\n networkCreateCtrl.crudHelperService.stopLoader(networkCreateCtrl);\n networkCreateCtrl.crudHelperService.showServerError(\"Network: Create failed\", error);\n });\n\n setTimeout(() => {\n if(networkCreateCtrl['showLoader']==true){\n networkCreateCtrl.crudHelperService.stopLoader(networkCreateCtrl);\n networkCreateCtrl.crudHelperService.showNotification(\"Network: Create task submitted\", networkCreateCtrl.newNetwork.key, NotificationType.info);\n networkCreateCtrl.returnToNetworks();\n }\n },2000)\n }\n\n}\n\n\n" }, { "alpha_fraction": 0.657912015914917, "alphanum_fraction": 0.665134608745575, "avg_line_length": 28.153846740722656, "blob_id": "b07225165cf3c19a189809677bccf5ff3a9e48c0", "content_id": "0b757be9c6ac6e2469ccc852db530b082ae07c53", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1523, "license_type": "permissive", "max_line_length": 96, "num_lines": 52, "path": "/app/firstrunwizard/firstrunacisettings.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": " /**\n * Created by cshampur on 10/30/16.\n */\nimport { Component, OnInit, EventEmitter, Output } from \"@angular/core\";\nimport { FirstRunWizardService } from \"./firstrunwizardservice\";\ndeclare var jQuery:any;\n\n@Component({\n selector: 'firstrunacisettings',\n templateUrl: './firstrunacisettings.html'\n})\nexport class FirstrunACISettingsComponent implements OnInit {\n private wizardService:FirstRunWizardService;\n public setting:any;\n public disabled: boolean = false;\n @Output('updatePage') updatePage:EventEmitter<any>;\n @Output('cancelPage') cancelPage:EventEmitter<any>;\n\n constructor(wizardService:FirstRunWizardService) {\n this.wizardService = wizardService;\n this.setting = this.wizardService.aciSetting;\n this.updatePage = new EventEmitter<any>();\n this.cancelPage = new EventEmitter<any>();\n if(this.wizardService.setting.networkInfraType !== 'aci')\n this.disabled = true;\n }\n\n ngOnInit() {\n this.setting = this.wizardService.aciSetting;\n }\n\n updateAciSettings(setting:any) {\n this.wizardService.skipArray[1] = false;\n this.wizardService.aciSetting = setting;\n this.updatePage.emit(2);\n }\n\n goBack() {\n this.updatePage.emit(0);\n }\n\n skip() {\n this.wizardService.skipArray[1] = true;\n Object.assign(this.wizardService.aciSetting, this.wizardService.defaults['aciSetting']);\n this.updatePage.emit(2);\n\n }\n\n cancel() {\n this.cancelPage.emit();\n }\n}" }, { "alpha_fraction": 0.6536343693733215, "alphanum_fraction": 0.659140944480896, "avg_line_length": 31.428571701049805, "blob_id": "e72c08802bb6b24b3ce0eedb3bdc9dec7bdb8d7d", "content_id": "ae8fa6206caeb6519ee79010154079b4e950a669", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1816, "license_type": "permissive", "max_line_length": 82, "num_lines": 56, "path": "/app/settings/authorization/authorizationlist.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 12/13/16.\n */\n\n\nimport {Component, OnInit} from \"@angular/core\";\nimport {Subscribable} from \"rxjs/Observable\";\nimport {Subscription, Observable} from \"rxjs\";\nimport {CRUDHelperService} from \"../../components/utils/crudhelperservice\";\nimport {AuthorizationModel} from \"../../components/models/authorizationmodel\";\nimport {Router, ActivatedRoute} from \"@angular/router\";\nimport {Authorization} from \"./authorizationcreate\";\n@Component({\n selector: 'authorizationlist',\n templateUrl: './authorizationlist.html'\n})\n\nexport class AuthorizationListComponent implements OnInit{\n public authorizations: Array<Authorization> = [];\n public filteredauth: any = [];\n public showLoader: boolean = false\n private refresh: Subscription;\n constructor(private crudHelperService: CRUDHelperService,\n private authorizationModel: AuthorizationModel,\n private router: Router,\n private activatedRoute: ActivatedRoute){\n\n this.refresh = Observable.interval(5000).subscribe(() => {\n this.getAuthorization(true);\n });\n }\n\n ngOnInit(){\n this.crudHelperService.startLoader(this);\n this.getAuthorization(false);\n }\n\n getAuthorization(reload){\n var authorizationComp = this;\n this.authorizationModel.get(reload)\n .then((result) => {\n authorizationComp.authorizations = result;\n authorizationComp.crudHelperService.stopLoader(authorizationComp);\n },(error) => {\n authorizationComp.crudHelperService.stopLoader(authorizationComp);\n });\n }\n\n ngOnDestroy(){\n this.refresh.unsubscribe();\n }\n\n create(){\n this.router.navigate(['../create'], {relativeTo: this.activatedRoute});\n }\n}\n" }, { "alpha_fraction": 0.6159929633140564, "alphanum_fraction": 0.6177504658699036, "avg_line_length": 28.973684310913086, "blob_id": "e98d2ec9d3176836b1e98c30619c9f8dc9a8d106", "content_id": "4adee921d1867322da7863dca37cbbdd0bd5ec73", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1138, "license_type": "permissive", "max_line_length": 84, "num_lines": 38, "path": "/app/components/directives/settings/acisettingcomponent.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "import {Component, Output, EventEmitter, Input, AfterViewInit} from \"@angular/core\";\ndeclare var jQuery:any;\n@Component({\n selector: 'acisettingcomp',\n templateUrl: './acisetting.html'\n})\nexport class AciSettingComponent implements AfterViewInit{\n\n @Input('firstRunWiz') firstRunWiz:boolean;\n @Output('updateAciDef') updateAciDef:EventEmitter<any>;\n @Input('setting') setting:any;\n @Output('cancel') cancel:EventEmitter<any>;\n @Output('skip') skip:EventEmitter<any>;\n @Output('goback') goback:EventEmitter<any>;\n @Input('disabled') disabled: boolean;\n\n constructor() {\n this.updateAciDef = new EventEmitter<any>();\n this.cancel = new EventEmitter<any>();\n this.skip = new EventEmitter<any>();\n this.goback = new EventEmitter<any>();\n }\n\n updateAciSetting(formvalid:boolean) {\n if (formvalid) {\n this.updateAciDef.emit(this.setting);\n }\n }\n\n ngAfterViewInit(){\n if(this.disabled){\n jQuery('.ui.dimmer.aci').dimmer({\n opacity: 0.8,\n closable: false\n }).dimmer('show');\n }\n }\n}" }, { "alpha_fraction": 0.5788079500198364, "alphanum_fraction": 0.5798675417900085, "avg_line_length": 40.4945068359375, "blob_id": "ffb16c0c33b79ba8cd0d74be856cf262b3404a5f", "content_id": "73a7f685b7cdea9506924cace3df782a5ecc8a39", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3775, "license_type": "permissive", "max_line_length": 138, "num_lines": 91, "path": "/app/networks/networkstatsctrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "import {Component, OnInit, OnDestroy, Input, NgZone} from \"@angular/core\";\nimport {CRUDHelperService} from \"../components/utils/crudhelperservice\";\nimport {Subscription, Observable} from \"rxjs\";\nimport {NetworksModel} from \"../components/models/networksmodel\";\nimport {InspectService} from \"../components/utils/inspectservice\";\nimport {isUndefined} from \"util\";\nimport {ContivGlobals} from \"../components/models/contivglobals\";\n\n@Component({\n selector: 'network-stat',\n templateUrl: './networkstats.html'\n})\nexport class NetworkStatComponent implements OnInit, OnDestroy{\n\n public networkStatsCtrl: any;\n @Input('statKey') statKey: string;\n private crudHelperService: CRUDHelperService;\n private refresh: Subscription;\n private networksModel: NetworksModel;\n private inspectSerrvice: InspectService;\n public showLoader: boolean\n networkInspectStats:any; config:any; endpoints:any; filteredendpoints:any; containerDetails:any;\n constructor(networksModel: NetworksModel,\n crudHelperService: CRUDHelperService,\n inspectSerrvice: InspectService,\n private ngZone: NgZone){\n this.crudHelperService = crudHelperService;\n this.networksModel = networksModel;\n this.inspectSerrvice = inspectSerrvice;\n this.statKey = '';\n this.showLoader = true;\n this.refresh = Observable.interval(5000).subscribe(() => {\n if(this.statKey!='')\n this.getNetworkInspect(true);\n });\n this.networkInspectStats= {\n allocatedAddressesCount: '',\n allocatedIPAddresses: '',\n availableIPAddresses: '',\n dnsServerIP: '',\n externalPktTag: '',\n numEndpoints: '',\n pktTag: '',\n networkTag: ''\n };\n this.config = {networkName: '',};\n this.endpoints = [];\n this.filteredendpoints = [];\n this.containerDetails= {};\n this.networkStatsCtrl = this;\n }\n\n ngOnInit(){\n this.crudHelperService.startLoader(this);\n if(this.statKey!='')\n this.getNetworkInspect(false);\n }\n\n getNetworkInspect(reload: boolean){\n var networkStatsCtrl = this;\n this.networksModel.getInspectByKey(this.statKey,\n ContivGlobals.NETWORKS_INSPECT_ENDPOINT, reload)\n .then((result) => {\n networkStatsCtrl['networkInspectStats'] = result['Oper'];\n networkStatsCtrl['config'] = result['Config'];\n if(!isUndefined(result['Oper'].endpoints)){\n var containerDetails = networkStatsCtrl.inspectSerrvice.buildEndPoints(result['Oper'].endpoints);\n if(networkStatsCtrl.inspectSerrvice.checkContainerChanged(networkStatsCtrl['containerDetails'],containerDetails)){\n networkStatsCtrl['endpoints'] = result['Oper'].endpoints;\n networkStatsCtrl['containerDetails'] = containerDetails;\n }\n }\n else{\n networkStatsCtrl['endpoints'] = []\n networkStatsCtrl['containerDetails'] = {};\n }\n networkStatsCtrl.ngZone.run(() => {\n networkStatsCtrl.crudHelperService.stopLoader(networkStatsCtrl);\n });\n },\n (error) => {\n networkStatsCtrl.ngZone.run(() => {\n networkStatsCtrl.crudHelperService.stopLoader(networkStatsCtrl);\n });\n });\n }\n\n ngOnDestroy(){\n this.refresh.unsubscribe();\n }\n}" }, { "alpha_fraction": 0.5418950915336609, "alphanum_fraction": 0.5493344068527222, "avg_line_length": 39.55555725097656, "blob_id": "13c35cd24c948aa42b39632899c4029e64e93921", "content_id": "5b0c9c113b4c84d2122de7a150256a2e6159b133", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2554, "license_type": "permissive", "max_line_length": 152, "num_lines": 63, "path": "/app/components/utils/inspectservice.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 7/17/16.\n */\nimport { Injectable } from '@angular/core';\nimport {isUndefined} from \"util\";\n\n@Injectable()\nexport class InspectService {\n /* This function would build the containerDetails object.\n eg :\n containerDetails={\n ContainerId1 : [{name: \"homingHost\", value: \"cluster-node1\", type: \"string\", format: \"none\"},\n {name: macAddress, value: \"02:02\", type:\"string\", format:\"none\"}\n ],\n ContainerId2 : [{name: \"homingHost\", value: \"cluster-node1\" type: \"string\", format: \"none\"},\n {name: macAddress, value: \"02:04\", type: \"string\", format: \"none\"}\n ]\n }\n --Used in displaying the container detail inside an accordion.\n */\n buildEndPoints(endpoints){\n var containerDetails = {};\n for(var i in endpoints ){\n var containerAttributes = [];\n for(var key in endpoints[i]){\n var endpointAttribute = {};\n endpointAttribute['name'] = key;\n endpointAttribute['format'] = 'none';\n endpointAttribute['type'] = 'string';\n switch (key){\n case \"ipAddress\" : endpointAttribute['value'] = endpoints[i][key].filter(function(ipAddress){return ipAddress.length > 0;}).join();\n break;\n case \"labels\" : endpointAttribute['value'] = endpoints[i][key].replace(/(map\\[|\\])/gi,'').replace(/(:)/gi, '=').split(' ')\n .filter(function(v){return v.length > 0});\n endpointAttribute['format'] = 'label';\n endpointAttribute['type'] = 'array';\n break;\n default : endpointAttribute['value'] = endpoints[i][key];\n }\n containerAttributes.push(endpointAttribute);\n }\n containerDetails[endpoints[i].containerID] = containerAttributes;\n }\n return containerDetails\n }\n\n /* This function checks whether any new containers were added or not\n View is updated only when there is a change in container configuration\n */\n checkContainerChanged(contDetailsA, contDetailsB){\n if(isUndefined(contDetailsA))\n return true;\n else{\n if(Object.keys(contDetailsA).length != Object.keys(contDetailsB).length)\n return true;\n for(var key in contDetailsB){\n if(!(key in contDetailsA))\n return true;\n }\n return false;\n }\n }\n}" }, { "alpha_fraction": 0.6918919086456299, "alphanum_fraction": 0.6972972750663757, "avg_line_length": 29, "blob_id": "a1f2549fba725e83d2e8bedecd7631c81f1907fd", "content_id": "a1767e098f0d4e47e4f9488d4e014cf58c7be20f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1110, "license_type": "permissive", "max_line_length": 78, "num_lines": 37, "path": "/app/networks/network.module.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 10/18/16.\n */\nimport { NgModule } from '@angular/core';\nimport { FormsModule } from \"@angular/forms\";\nimport { CommonModule } from \"@angular/common\";\nimport { DirectivesModule } from \"../components/directives/directives.module\";\nimport {NetworkListComponent} from \"./networklistctrl\";\nimport {NetworkStatComponent} from \"./networkstatsctrl\";\nimport {NetworkdetailsComponent} from \"./networkdetailsctrl\";\nimport {NetworkInfoComponent} from \"./networkinfoctrl\";\nimport {NetworkCreateComponent} from \"./networkcreatectrl\";\nimport {RouterModule} from \"@angular/router\";\n\n@NgModule({\n imports: [\n FormsModule,\n CommonModule,\n DirectivesModule,\n RouterModule\n ],\n declarations: [\n NetworkListComponent,\n NetworkStatComponent,\n NetworkInfoComponent,\n NetworkdetailsComponent,\n NetworkCreateComponent\n ],\n exports: [\n NetworkListComponent,\n NetworkStatComponent,\n NetworkInfoComponent,\n NetworkdetailsComponent,\n NetworkCreateComponent\n ]\n})\nexport class NetworkModule {}\n" }, { "alpha_fraction": 0.6280174255371094, "alphanum_fraction": 0.6280174255371094, "avg_line_length": 36.7164192199707, "blob_id": "1d6f531713c2e0223f5ecd4163da297818d8fde9", "content_id": "4547317c67e730f5fcfbac97efc2c376ab657dfa", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2527, "license_type": "permissive", "max_line_length": 106, "num_lines": 67, "path": "/app/settings/tenants/organizationdetailsctrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "import { Component, Inject, OnInit, NgZone } from \"@angular/core\";\nimport { ActivatedRoute, Router } from \"@angular/router\";\nimport { CRUDHelperService } from \"../../components/utils/crudhelperservice\";\nimport { OrganizationsModel } from \"../../components/models/organizationsmodel\";\n\n@Component({\n selector: 'organizationdetails',\n templateUrl: './organizationdetails.html'\n})\n\n\nexport class OrganizationDetailsComponent implements OnInit{\n public showLoader: boolean;\n public organizationDetailsCtrl: any;\n public organization: any;\n public showServerError: boolean;\n public serverErrorMessage: string;\n\n constructor(private activatedRoute: ActivatedRoute,\n private router: Router,\n private crudHelperService: CRUDHelperService,\n private organizationsModel: OrganizationsModel,\n private ngZone: NgZone){\n this.showServerError = false;\n this.serverErrorMessage = '';\n this.showLoader = false;\n this.organization = {tenantName: ''};\n this.organizationDetailsCtrl = this;\n\n }\n\n ngOnInit(){\n this.showLoader = true;\n var organizationDetailsCtrl = this;\n this.organizationsModel.getModelByKey(this.activatedRoute.snapshot.params['key'], false, 'key')\n .then((result) => {\n organizationDetailsCtrl.organization = result;\n organizationDetailsCtrl.ngZone.run(() => {\n organizationDetailsCtrl.showLoader = false;\n });\n }, (error) => {\n organizationDetailsCtrl.ngZone.run(() => {\n organizationDetailsCtrl.showLoader = false;\n });\n });\n }\n\n returnToOrganization(){\n this.router.navigate(['../../list'], { relativeTo: this.activatedRoute });\n }\n\n close() { this.returnToOrganization() }\n\n deleteOrganization(){\n var organizationDetailsCtrl = this;\n this.showLoader = true;\n this.organizationsModel.delete(this.organization)\n .then((result) => {\n organizationDetailsCtrl.showLoader = false;\n organizationDetailsCtrl.crudHelperService.showNotification(\"Tenant: Deleted\", result);\n organizationDetailsCtrl.returnToOrganization();\n }, (error) => {\n organizationDetailsCtrl.showLoader = false;\n organizationDetailsCtrl.crudHelperService.showServerError(\"Tenant: Delete failed\", error);\n });\n }\n}\n" }, { "alpha_fraction": 0.6551312804222107, "alphanum_fraction": 0.6610978245735168, "avg_line_length": 23.676469802856445, "blob_id": "b52901e5661aa6cb856ab6d66f2b108515efd15c", "content_id": "eefaaddd683c4c851af3bbb79ff5dfd4f3ca70a6", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 838, "license_type": "permissive", "max_line_length": 74, "num_lines": 34, "path": "/app/login/logoutctrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 11/6/16.\n */\n\n\nimport {Component, OnInit, OnDestroy} from \"@angular/core\";\nimport {Router, ActivatedRoute} from \"@angular/router\";\nimport { ContivGlobals } from \"../components/models/contivglobals\";\ndeclare var jQuery:any;\n@Component({\n selector: 'logout',\n templateUrl: './logout.html',\n styleUrls: ['./logout.css']\n})\n\nexport class LogoutComponent implements OnInit, OnDestroy{\n public product_name:string = ContivGlobals.PRODUCT_NAME;\n constructor(private router: Router,\n private activatedRoute: ActivatedRoute){\n\n }\n\n ngOnInit(){\n jQuery(\"body\").addClass(\"logoutbackground\");\n }\n\n ngOnDestroy(){\n jQuery(\"body\").removeClass(\"logoutbackground\");\n }\n\n login(){\n this.router.navigate(['/login'],{relativeTo:this.activatedRoute});\n }\n}" }, { "alpha_fraction": 0.7273315787315369, "alphanum_fraction": 0.7302461266517639, "avg_line_length": 62.04081726074219, "blob_id": "df0008d412449c3511516890f9efaa7a63abee31", "content_id": "13f0f6ac90265a471b6e9bac5692e7dad95b5e9f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3088, "license_type": "permissive", "max_line_length": 174, "num_lines": 49, "path": "/e2e-tests/storage_policies/storagepolicypageobject.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 8/17/16.\n */\n\nvar storagePolicyList = function(){\n this.createButton = element(by.css(\"button.button[ui-sref='contiv.menu.storagepolicies.create']\"));\n this.storagepolicyname = element(by.repeater(\"policy in storagePolicyListCtrl.filteredpolicies\").row(0)).element(by.cssContainingText(\"a\",testConfig.storagePolicy.name));\n}\n\nvar storagePolicyCreate = function(){\n this.policyName = element(by.css(\"#newStoragePolicyName\"));\n this.policyPool = element(by.css(\"#newStoragePolicyPool\"));\n this.policySize = element(by.css(\"#newStoragePolicySize\"));\n this.filesystem = {}\n this.filesystem.name = element(by.id(\"newStoragePolicyFilesystem\")).element(by.css(\"[value='\"+testConfig.storagePolicy.fileSystem.name+\"']\"));\n this.filesystem.type = element(by.model(\"newItem.name\")).element(by.css(\"[value='\"+testConfig.storagePolicy.fileSystem.type+\"']\"));\n this.filesystem.command = element(by.model(\"newItem.value\"));\n this.filesystem.addButton = element(by.css(\"table button.icon\"));\n this.runtime = {};\n if(testConfig.storagePolicy.snapshot.enabled==\"true\")\n this.runtime.snapshot = element.all(by.model(\"policy.runtime.snapshots\")).get(0);\n else\n this.runtime.snapshot = element.all(by.model(\"policy.runtime.snapshots\")).get(1);\n\n this.runtime.frequency = element(by.id(\"newStoragePolicySnapshotFrequency\"));\n this.runtime.keep = element(by.id(\"newStoragePolicySnapshotKeep\"));\n this.runtime.writeiops = element(by.id(\"newStoragePolicyWriteIops\"));\n this.runtime.readiops = element(by.id(\"newStoragePolicyReadIops\"));\n this.runtime.writebps = element(by.id(\"newStoragePolicyWriteBps\"));\n this.runtime.readbps = element(by.id(\"newStoragePolicyReadBps\"));\n this.backends = {};\n this.backends.driver = element(by.id(\"newStoragePolicyCRUDDriver\")).element(by.css(\"[value='\"+testConfig.storagePolicy.backend.driver+\"']\"));\n this.backends.mount = element(by.id(\"newStoragePolicyMountDriver\")).element(by.css(\"[value='\"+testConfig.storagePolicy.backend.mount+\"']\"));\n this.backends.snapshotdriver = element(by.id(\"newStoragePolicySnapshotDriver\")).element(by.css(\"[value='\"+testConfig.storagePolicy.backend.snap+\"']\"));\n this.policyCreate = element(by.cssContainingText(\"button\", \"Create\"));\n this.policyCancel = element(by.cssContainingText(\"button\", \"Cancel\"));\n this.collapsible = element.all(by.css(\"div[ng-click='collapsed = !collapsed'] h4\"));\n this.serverMessage = element(by.cssContainingText(\"ctv-error div div\", \"Error creating storage policy\"));\n}\n\nvar storagePolicyDetails = function(){\n this.tableData = element.all(by.css(\"table tbody tr\"));\n this.editButton = element(by.cssContainingText(\"button\", \"Edit\"));\n this.removeButton = element(by.cssContainingText(\"button\", \"Remove\"));\n this.editText = element(by.cssContainingText(\"span\",\"(Edit)\"));\n this.collapsible = element.all(by.css(\"i.plus.circle\"));\n}\n\nmodule.exports = {storagePolicyList:storagePolicyList,storagePolicyCreate:storagePolicyCreate, storagePolicyDetails: storagePolicyDetails};" }, { "alpha_fraction": 0.5717069506645203, "alphanum_fraction": 0.5744349360466003, "avg_line_length": 32.77631759643555, "blob_id": "1e6a4441962484f176f6067cef73b3fcd2f83c9a", "content_id": "8cb538ea0f3c1e9e30c86736a1154be0a6f81c65", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2566, "license_type": "permissive", "max_line_length": 76, "num_lines": 76, "path": "/app/components/utils/apiservice.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "import { Injectable } from \"@angular/core\";\nimport { Http, Headers, RequestOptions, Response } from \"@angular/http\";\nimport { Observable } from \"rxjs\";\nimport { AuthService } from \"./authservice\";\n@Injectable()\n\nexport class ApiService{\n private headers: Headers;\n public authServiceRef: AuthService;\n constructor(private http: Http,\n private authService: AuthService){\n this.authServiceRef = authService;\n }\n\n get(url: string): Observable<any>{\n var options = this.prepareHeader('get');\n return this.http.get(url,options)\n .catch((error: any) => {\n this.checkUnauthorized(error);\n return Observable.throw(error);\n });\n }\n\n put(url:string, body:any): Observable<any>{\n var options = this.prepareHeader('put');\n return this.http.put(url,body,options)\n .catch((error: any) => {\n this.checkUnauthorized(error);\n return Observable.throw(error);\n });\n }\n\n post(url:string, body:any): Observable<any>{\n var options = this.prepareHeader('post');\n return this.http.post(url,body,options)\n .catch((error: any) => {\n this.checkUnauthorized(error);\n return Observable.throw(error);\n });\n }\n\n delete(url:string): Observable<any>{\n var options = this.prepareHeader('delete');\n return this.http.delete(url,options)\n .catch((error: any) => {\n this.checkUnauthorized(error);\n return Observable.throw(error);\n });\n }\n\n patch(url:string, body:any): Observable<any>{\n var options = this.prepareHeader('patch')\n return this.http.patch(url, body, options)\n .catch((error: any) => {\n this.checkUnauthorized(error);\n return Observable.throw(error);\n });\n }\n\n prepareHeader(method: string): RequestOptions{\n this.headers = new Headers();\n if(method!='get' && method!='delete')\n this.headers.append('Content-Type', 'application/json');\n if (this.authService.authToken.length > 0)\n this.headers.append('X-Auth-Token', this.authService.authToken);\n var options = new RequestOptions({headers: this.headers});\n return options;\n }\n\n checkUnauthorized(error: any){\n if(this.authService.isLoggedIn){\n if((error.status===401) || (error.status===403))\n this.authService.isLoggedIn = false;\n }\n }\n}" }, { "alpha_fraction": 0.6822119355201721, "alphanum_fraction": 0.6914525032043457, "avg_line_length": 28.084033966064453, "blob_id": "c8ff7af0c313e4e6867f8e20889c61772387d6ec", "content_id": "509f591b5313cd5fa9eb26ddb70d4272033c8927", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6926, "license_type": "permissive", "max_line_length": 220, "num_lines": 238, "path": "/CONTRIBUTING.md", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "#Contributing to Contiv-ui\n\n\n\n##Developers - Table of contents\n=================\n\n * [Setup](#setting-up-contiv-ui-on-mac-and-windows)\n * [Windows](#for-windows)\n * [Mac](#for-mac)\n * [Adding icon](#adding-custom-icons-into-semantic-ui)\n * [Testing](#testing)\n * [Directives] (#writing-directive-tests)\n * [End to end testing] (#writing-end-to-end-tests)\n\n\n###Setting up Contiv-ui on Mac and Windows\n==========================================\n###For Windows:\n---------------\n####Fix long path issue and clone the repo:\n* install git, then run\n```\n$ git config --system core.longpaths true\n$ git clone https://github.com/contiv/contiv-ui.git\n```\n\n####Install app dependencies\n* install node.js\n* In the directory of the contiv-ui repo, run:\n```\n$ npm install -g bower \n$ npm install -g gulp\n$ npm install\n```\n* Build app with:\n```\nFor Dev\n$ npm run build:dev\n```\n```\nFor Production\n$ npm run build\n```\n\n####Install nginx\n* download nginx and unzip\n* add nginx to System Path\n * If you are having issues with nginx not being a recognized command, check that you added it to your path correctly\n* From contiv-nginx.conf(in the contiv-ui repo), copy from line 13 to line 50\n* Paste into nginx.conf (in nginx_location/conf) after line 47\n* In the section you just pasted, replace localhost with your server\n* Change the root to point to the absolute path of contiv-ui/app instead of html\n\n####Running nginx\n* In the directory of nginx, to start nginx:\n```\n$ start nginx\n```\nServer is now running on localhost:8080 \nIf you make changes in your app folder, rerun the gulp command and hard refresh page \n\n* If you modify nginx.conf, restart server with:\n```\n$ nginx -s reload\n```\n* To stop nginx:\n```\n$ nginx -s stop\n```\n\n###For Mac:\n-----------\n####Install git and clone repo\n```\n$ git\n$ git clone https://github.com/contiv/contiv-ui.git\n```\n####Install app dependencies\n* install node.js\n* In the directory of the contiv-ui repo, run:\n```\n$ sudo npm install npm -g\n$ sudo npm install -g bower \n$ sudo npm install -g gulp\n$ npm install\n```\n* Build app with:\n```\nFor Dev\n$ npm run build:dev\n```\n```\nFor Production\n$ npm run build\n```\n\n####Run AUTH Proxy\nContiv UI needs AUTH Proxy for user authentication and authorization. AUTH Proxy also acts as a web server for contiv UI.\nTo run contiv UI inside a docker container from contiv source.\n\n* Install Docker for Mac\n* Checkout 'contiv/auth_proxy'\n * Inside the 'auth_proxy' checkout:\n```\n\tgit pull <-- if you need to refresh the checkout\n\tmake\n\tmake generate-certificate <-- if this is a new checkout\n```\n* Also, set an env var pointing to the local UI src code:\n```\n\texport UI_DIR='/Users/john/Dev/gocode/src/github.com/contiv/contiv-ui/app'\n```\n\n* Load the cnn_proxy as a container. Note where in this CLI there is a reference to the data store and netmaster:\n```\ndocker run -it \\\n-v $PWD/local_certs:/local_certs:ro \\\n-v $UI_DIR:/ui:ro \\\n-p 10000:10000 auth_proxy:devbuild --listen-address=0.0.0.0:10000 \\\n--netmaster-address=<netmaster>:9999 \\\n--data-store-address=etcd://<etcd-server>:2379 \\\n--tls-certificate=/local_certs/cert.pem --tls-key-file=/local_certs/local.key\n```\n* From your browser:\n\thttps://localhost:10000/\n\n####Install nginx (This is no longer needed if you use AUTH Proxy)\n* install brew and nginx:\n```\n$ /usr/bin/ruby -e \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)\" \n$ brew install nginx\n```\n* From contiv-nginx.conf(in the contiv-ui repo), copy from line 13 to line 50\n* Paste into nginx.conf (location: /usr/local/etc/nginx) after line 47\n* In the section you just pasted, replace localhost with your backend server\n * This should point to the backend running contiv. It is fine to leave as localhost if you just want to view the UI.\n* Change the root to point to the absolute path of contiv-ui/app instead of html\n\n####Running nginx\n* In the directory of nginx, to start nginx:\n```\n$ nginx\n```\nServer is now running on localhost:8080 \nIf you make changes in your app folder, rerun the npm run build:dev command and hard refresh page to view changes in the browser\n\n* If you modify nginx.conf, restart server with:\n```\n$ nginx -s reload\n```\n* To stop nginx:\n```\n$ nginx -s stop\n```\n\n### Adding custom icons into semantic-ui\n----------------------------------------\n\n* Uncompress the folder containing the files related to the icons.\n* Copy and replace the following files contiv.eot, contiv.svg, contiv.tff, contiv.woff, contiv.woff2 from /font/ of the uncompressed folder into contiv-ui/app/bower_components/semantic-ui/src/themes/contiv/assets/fonts/.\n* Add the new icon to icon.overrides file present in contiv-ui/app/bower_components/semantic-ui/src/themes/contiv/elements/\n* eg for adding a snapshot icon - \n\n```\n.icon.snapshot:before {\n content: \"\\e959\";\n}\n\nHere content refers to the id of the icon present inside demo.html file.\n\n```\n* Do a gulp build inside the semantic installed folder\n\n```\n$ gulp build\n```\n\n* The icon can be used in the project as below :\n\n```\n<i class=\"snapshot icon\"></i>\n```\n\n\n###Testing (Tests not migrated to angular 2. They will not work currently.)\n==========\nTo run all tests:\n```\n$ npm test\n```\n\n####Writing Directive Tests\n---------------------------\nYou must configure karma to pre-process the linked template html file. To do so:\n* In the Karma.conf.js file:\n * add the location under preprocessors in the following format\n ```\n preprocessors: {\n 'app/example/**/*.html':['ng-html2js']\n },\n ```\n * Include the module.js file, all other js files, and the html file.\n ```\n files: [\n 'app/example/module.js',\n 'app/example/**/*.js,\n 'app/example/**/*.html\n ]\n ```\n* In the test file, add the following to load the html:\n ```\n beforeEach(module('contiv.test.directives'));\n ```\n \n#### Writing End to end tests\n----------------------------\nYour page interaction test must be organized into two files pageObject.js and pageSpec.js.\nInside pageObject you would create object references for every page element that the user can interact with. pageSpec.js would use the elements declared in pageObject.js to perform the actual test and verifications. \n\n######Running End to end tests -\nProtractor along with Standalone selenium web driver is used to execute these test scripts. By default, Contiv UI is expected to run on http://localhost:8080/ for these tests to run.\n\n```\n$ npm run protractor\n```\n\n######Debugging End to end tests using webstorm- \n\nFollow the below instructions to configure your webstorm for running/debugging end to end tests.\n\n* Click on Run/Edit\tConfigurations.\n* Add a new node.js module.\n* set the working directory path to contiv-ui/e2e-tests.\n* set the javascript file path to contiv-ui/node_modules/protractor/lib/cli.js.\n* set the Appliation parameters path to contiv-ui/e2e-tests/protractor.conf.js.\n\nYou can now set breakpoints and debug your test scripts through webstorm.\n\n\n\n\n" }, { "alpha_fraction": 0.4632018208503723, "alphanum_fraction": 0.4852048456668854, "avg_line_length": 31.158536911010742, "blob_id": "513178509e308f6c2bf4ce828afea724b0a15c3a", "content_id": "a9aa46e3bfe790e72e18c209496532bd8bb096e3", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2636, "license_type": "permissive", "max_line_length": 119, "num_lines": 82, "path": "/app/components/models/networksmodel_test.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 2/20/16.\n */\n'use strict';\n\ndescribe('contiv.models.networks module', function () {\n\n beforeEach(module('contiv.models'));\n\n describe('networks model', function () {\n\n var NetworksModel, $httpBackend;\n var networkListData = [\n {\n \"key\": \"default:contiv-net1\",\n \"encap\": \"vxlan\",\n \"gateway\": \"20.1.2.254\",\n \"networkName\": \"contiv-net1\",\n \"subnet\": \"20.1.2.0/24\",\n \"tenantName\": \"default\",\n \"link-sets\": {},\n \"links\": {\n \"Tenant\": {\n \"type\": \"tenant\",\n \"key\": \"default\"\n }\n }\n }\n ];\n\n var newNetworkData = {\n \"key\": \"default:contiv-net2\",\n \"encap\": \"vxlan\",\n \"gateway\": \"20.1.3.254\",\n \"networkName\": \"contiv-net2\",\n \"subnet\": \"20.1.3.0/24\",\n \"tenantName\": \"default\",\n \"link-sets\": {},\n \"links\": {\n \"Tenant\": {\n \"type\": \"tenant\",\n \"key\": \"default\"\n }\n }\n };\n\n beforeEach(inject(function (_NetworksModel_, _$httpBackend_) {\n NetworksModel = _NetworksModel_;\n $httpBackend = _$httpBackend_;\n $httpBackend.when('GET', ContivGlobals.NETWORKS_ENDPOINT).respond(networkListData);\n }));\n\n afterEach(function () {\n $httpBackend.verifyNoOutstandingExpectation();\n $httpBackend.verifyNoOutstandingRequest();\n });\n\n it('should be defined', function () {\n //spec body\n expect(NetworksModel).toBeDefined();\n });\n\n it('get() should do a GET on /api/networks/ REST API', function () {\n $httpBackend.expectGET(ContivGlobals.NETWORKS_ENDPOINT);\n NetworksModel.get();\n $httpBackend.flush();\n });\n\n it('create() should do a POST on /api/networks REST API', function () {\n $httpBackend.expectPOST(ContivGlobals.NETWORKS_ENDPOINT + newNetworkData.key + '/').respond(201, '');\n NetworksModel.create(newNetworkData);\n $httpBackend.flush();\n });\n\n it('delete() should do a DELETE on /api/networks REST API', function () {\n $httpBackend.expectDELETE(ContivGlobals.NETWORKS_ENDPOINT + networkListData[0].key + '/').respond(201, '');\n NetworksModel.delete(networkListData[0]);\n $httpBackend.flush();\n });\n\n });\n});" }, { "alpha_fraction": 0.5920471549034119, "alphanum_fraction": 0.5972017645835876, "avg_line_length": 34.76315689086914, "blob_id": "bd05934c17fcdd34cc346843d9c86c9f9bb2d3ab", "content_id": "58a79d8565e96da2aecd2ab1229a8df0a33fc115", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1358, "license_type": "permissive", "max_line_length": 94, "num_lines": 38, "path": "/app/components/models/usersmodel.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 11/7/16.\n */\nimport { Injectable } from '@angular/core';\nimport { Http, Response } from '@angular/http';\nimport { Collection } from \"./collection\";\nimport { ContivGlobals } from \"./contivglobals\";\nimport { ApiService } from \"../utils/apiservice\";\nimport * as _ from 'lodash';\nimport { isUndefined } from \"util\";\n\n@Injectable()\nexport class UsersModel extends Collection {\n constructor(http:Http, apiService:ApiService) {\n super(http, ContivGlobals.USERS_ENDPOINT, apiService);\n }\n\n save(model):Promise<any> {\n var collection = this;\n var url = ContivGlobals.USERS_ENDPOINT + model['username'] + '/';\n return this.apiService.patch(url, model).map((res:Response) => res.json()).toPromise()\n .then((result) => {\n _.remove(collection.models, function (n) {\n return n['username'] == model['username'];\n });\n collection.models.push(result);\n return result;\n });\n }\n\n getModelByKey(key, reload, keyname, url?): Promise<any>{\n var collection = this;\n if((!isUndefined(url)) && (collection.models.length==0))\n return this.apiService.get(url).map((res:Response) => res.json()).toPromise()\n else\n return super.getModelByKey(key, reload, keyname);\n }\n}" }, { "alpha_fraction": 0.5657004714012146, "alphanum_fraction": 0.5681159496307373, "avg_line_length": 29.8358211517334, "blob_id": "83b0ab0d0986c561ec5f45807f42980ccb0404b7", "content_id": "451d3ee958e6a686597a174723f7a0a27a5aaa63", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2070, "license_type": "permissive", "max_line_length": 60, "num_lines": 67, "path": "/app/components/graphobjects/link/link_test.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "'use strict';\n\ndescribe('link', function(){\n var linkFactory;\n var link;\n beforeEach(function(){\n module('contiv.graph');\n inject( function($injector){\n linkFactory = $injector.get('Link');\n link = new linkFactory.Link('source', 'target');\n });\n });\n \n it('Checking inital values', function(){\n expect(link.source).toBe('source');\n expect(link.target).toBe('target');\n expect(link.graph).toBe(null);\n expect(link.initialized).toBe(false);\n });\n\n it('Checking initializing', function() {\n link.initialize(\"testGraph\");\n expect(link.graph).toBe(\"testGraph\");\n expect(link.initialized).toBe(true);\n\n //calling initialize again shouldn't change anything\n link.initialize(\"newGraph\");\n expect(link.graph).toBe(\"testGraph\");\n expect(link.initialized).toBe(true);\n });\n\n\n it('testing policy related methods', function() {\n var policy = {\n policyName:'testPolicy',\n initialize: function(g){\n this.graph = g;\n },\n click:function(d3Obj, d) {\n expect(d.source).toBe('source');\n },\n destroy: function(){\n this.destroyed = true;\n }\n };\n link.initialize(\"testGraph\");\n link.installPathPolicy(policy);\n expect(link.hasPolicy).toBe(true);\n expect(link.pathPolicies.length).toBe(1);\n expect(policy.graph).toBe('testGraph');\n\n link.pathPolicyEvent('click', null, link);\n link.uninstallPathPolicy(policy);\n expect(policy.destroyed).toBe(true);\n expect(link.hasPolicy).toBe(false);\n expect(link.pathPolicies.length).toBe(0);\n\n link.installPathPolicy(policy);\n expect(link.hasPolicy).toBe(true);\n expect(link.pathPolicies.length).toBe(1);\n \n link.uninstallPathPolicy('testPolicy');\n expect(link.hasPolicy).toBe(false);\n expect(link.pathPolicies.length).toBe(0); \n })\n\n});\n\n\n\n\n" }, { "alpha_fraction": 0.6310223340988159, "alphanum_fraction": 0.6330787539482117, "avg_line_length": 37.258426666259766, "blob_id": "61d67ffc00a2eed2d9800b1c61cce7a453b5ada1", "content_id": "98e51127bf0b40a30ae997baa9847d2ea57333eb", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3404, "license_type": "permissive", "max_line_length": 128, "num_lines": 89, "path": "/app/appprofiles/appgroupselection.component.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 11/11/16.\n */\nimport { Component, Input, OnChanges } from '@angular/core';\nimport * as _ from 'lodash';\nimport { ApplicationGroupsModel } from \"../components/models/applicationgroupsmodel\";\n\n\n@Component({\n selector: 'ctv-appgroupselection',\n templateUrl: './appgroupselection.html'\n})\nexport class ApplicationGroupSelectionComponent implements OnChanges {\n @Input() mode:string;\n @Input() appProfile:any;\n\n applicationGroups:any[] = []; // To Get all application groups of tenant\n applicationGroupSearchText:string = '';\n\n selectedApplicationGroups:any[] = [];\n\n constructor(private applicationGroupsModel:ApplicationGroupsModel) {\n }\n\n ngOnChanges() {\n var component = this;\n\n component.getApplicationGroups();\n\n /**\n * To check 'details' or 'edit' mode (not create mode)\n */\n if (component.mode === 'details' || (component.mode === 'edit' && component.appProfile.appProfileName != \"\")) {\n //Application Profiles might not have any groups associated with them so define an empty array\n if (component.appProfile.endpointGroups === undefined) {\n component.appProfile.endpointGroups = [];\n }\n }\n }\n\n /**\n * Get application groups.\n */\n getApplicationGroups() {\n var component = this;\n //Refresh application groups as its links would be updated when a new application profile is created.\n component.applicationGroupsModel.get(true).then(function (result) {\n component.selectedApplicationGroups = _.filter(result, function (group) {\n return _.includes(component.appProfile.endpointGroups, group['groupName']);\n });\n //No two application profiles can share the same application groups\n component.applicationGroups = _.filter(result, function (group) {\n return (((_.isEmpty(group['links'].AppProfile)) || (group['links'].AppProfile.key === component.appProfile.key))\n && (group['tenantName'] === component.appProfile.tenantName));\n });\n });\n }\n\n /**\n * Add group to app profile\n */\n addApplicationGroup(groupName:string) {\n var component = this;\n var currentGroupName = groupName;\n\n if (currentGroupName !== undefined && !_.includes(component.appProfile.endpointGroups, currentGroupName)) {\n let key = component.appProfile.tenantName + ':' + currentGroupName;\n component.applicationGroupsModel.getModelByKey(key, false, undefined).then(function (group) {\n component.selectedApplicationGroups.push(group);\n component.selectedApplicationGroups = component.selectedApplicationGroups.slice();\n });\n //To be added to application group and saved to the server\n component.appProfile.endpointGroups.push(currentGroupName);\n }\n };\n\n /**\n * Remove group from app profile\n */\n removeApplicationGroup(groupName:string) {\n _.remove(this.selectedApplicationGroups, function (group) {\n return group['groupName'] === groupName;\n });\n this.selectedApplicationGroups = this.selectedApplicationGroups.slice();\n _.remove(this.appProfile.endpointGroups, function (group) {\n return group === groupName;\n });\n };\n}" }, { "alpha_fraction": 0.5930880904197693, "alphanum_fraction": 0.5953177213668823, "avg_line_length": 31.636363983154297, "blob_id": "0e0f53f285c1e719826a8a55d3f537a4769d3ce8", "content_id": "c6c43f3f8b130828a60a4366cd732fc94529ffa0", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1794, "license_type": "permissive", "max_line_length": 81, "num_lines": 55, "path": "/app/appprofiles/appprofilelist.component.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "import { Component, OnInit, OnDestroy, Inject, NgZone } from \"@angular/core\";\nimport { ActivatedRoute, Router } from \"@angular/router\";\nimport { CRUDHelperService } from \"../components/utils/crudhelperservice\";\nimport { Observable, Subscription } from \"rxjs\";\nimport { AppProfilesModel } from \"../components/models/appprofilesmodel\";\n\n\n@Component({\n selector: 'appprofilelist',\n templateUrl: './appprofilelist.html'\n})\n\nexport class AppProfileListComponent implements OnInit, OnDestroy{\n\n private refresh: Subscription;\n\n constructor(private activatedRoute: ActivatedRoute,\n private router: Router,\n private appProfilesModel: AppProfilesModel,\n private crudHelperService: CRUDHelperService,\n private ngZone: NgZone) {\n this.refresh = Observable.interval(5000).subscribe(() => {\n this.getAppProfiles(true);\n })\n }\n\n ngOnInit(){\n this.crudHelperService.startLoader(this);\n this.getAppProfiles(false);\n }\n\n getAppProfiles(reload: boolean){\n var component = this;\n this.appProfilesModel.get(reload)\n .then(function successCallback(result){\n component['appProfiles'] = result;\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n },\n function errorCallback(result){\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n });\n }\n\n create(){\n this.router.navigate(['../create'], { relativeTo: this.activatedRoute });\n }\n\n ngOnDestroy(){\n this.refresh.unsubscribe();\n }\n}" }, { "alpha_fraction": 0.6359469294548035, "alphanum_fraction": 0.636911928653717, "avg_line_length": 40.459999084472656, "blob_id": "477b445d6a6f25dc1502c25509beea060351d764", "content_id": "be3aa853aae98d2f7d0224f043fe14f1bcac33c7", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4145, "license_type": "permissive", "max_line_length": 118, "num_lines": 100, "path": "/app/settings/networksettingctrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "import { Component, OnInit, OnDestroy } from '@angular/core';\nimport { Subscription, Observable } from \"rxjs\";\nimport { CRUDHelperService } from \"../components/utils/crudhelperservice\";\nimport { NetworkService } from \"../components/utils/networkservice\";\nimport { ContivGlobals } from \"../components/models/contivglobals\";\n\n@Component({\n selector: 'networksetting',\n templateUrl: './networksettings.html'\n})\nexport class NetworkSettingsComponent implements OnDestroy {\n private refresh: Subscription;\n setting: any;\n aciSetting: any;\n globalInspectStats:any;\n\n constructor(private crudHelperService: CRUDHelperService,\n private networkService: NetworkService){\n this.setting = {};\n this.aciSetting = {};\n this.globalInspectStats = {};\n this['showLoader']=true;\n this['showServerError'] = false;\n this['serverErrorMessage'] = '';\n var networkSettingCtrl = this;\n\n function getNetworkSettings() {\n networkSettingCtrl.crudHelperService.startLoader(networkSettingCtrl);\n networkSettingCtrl.networkService.getSettings().then(function successCallback(result) {\n networkSettingCtrl.setting = result;\n getAciSettings();\n }, function errorCallback(result) {\n getAciSettings();\n });\n }\n\n getNetworkSettings();\n\n function getAciSettings(){\n networkService.getAciSettings()\n .then((result) => {\n networkSettingCtrl.aciSetting = result;\n networkSettingCtrl.getGlobalInspect(false);\n }, (error) => {\n networkSettingCtrl.getGlobalInspect(false);\n });\n }\n\n this.refresh = Observable.interval(5000).subscribe(() => {\n this.getGlobalInspect(true);\n });\n }\n\n updateNetworkSettings(settings:any) {\n var networkSettingCtrl = this;\n networkSettingCtrl.crudHelperService.startLoader(networkSettingCtrl);\n networkSettingCtrl.networkService.updateSettings(settings).then(function successCallback(result) {\n networkSettingCtrl.crudHelperService.stopLoader(networkSettingCtrl);\n if(result['networkInfraType'] === 'aci')\n networkSettingCtrl.networkService.setAciMode(true);\n else\n networkSettingCtrl.networkService.setAciMode(false);\n networkSettingCtrl.crudHelperService.showNotification(\"Network settings: Updated\", result.key.toString());\n }, function errorCallback(result) {\n networkSettingCtrl.crudHelperService.stopLoader(networkSettingCtrl);\n networkSettingCtrl.crudHelperService.showServerError(\"Network settings: Update failed\", result);\n });\n }\n\n updateAciSetting(settings:any){\n var networkSettingCtrl = this;\n networkSettingCtrl.crudHelperService.startLoader(networkSettingCtrl);\n networkSettingCtrl.networkService.updateAciSettings(settings)\n .then((result) => {\n networkSettingCtrl.crudHelperService.stopLoader(networkSettingCtrl);\n networkSettingCtrl.crudHelperService.showNotification(\"ACI settings: Updated\", result.key.toString());\n }, (error) => {\n networkSettingCtrl.crudHelperService.stopLoader(networkSettingCtrl);\n networkSettingCtrl.crudHelperService.showServerError(\"ACI settings: Update failed\", error);\n })\n\n }\n\n getGlobalInspect(reload: boolean){\n var networkSettingCtrl = this;\n networkSettingCtrl.networkService.getGlobalInspect()\n .then((result) => {\n networkSettingCtrl['globalInspectStats'] = result['Oper'];\n if(!reload)\n networkSettingCtrl.crudHelperService.stopLoader(networkSettingCtrl);\n }, (error) => {\n if(!reload)\n networkSettingCtrl.crudHelperService.stopLoader(networkSettingCtrl);\n });\n }\n\n ngOnDestroy(){\n this.refresh.unsubscribe();\n }\n}" }, { "alpha_fraction": 0.5176380276679993, "alphanum_fraction": 0.5345091819763184, "avg_line_length": 26.659574508666992, "blob_id": "4ef39b80b9b75457a53148fd18dbe175054b6578", "content_id": "a16021172d2039a72a4d02b50f8adbcf6bc05053", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1304, "license_type": "permissive", "max_line_length": 64, "num_lines": 47, "path": "/app/components/graphobjects/link/visualizerlink_test.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "'use strict';\n\ndescribe('link', function(){\n var linkFactory;\n var link;\n beforeEach(function(){\n module('contiv.graph');\n inject( function($injector){\n linkFactory = $injector.get('VisualizerLink');\n link = new linkFactory.Link('source', 'target', 10);\n });\n });\n \n it('Checking inital values', function(){\n expect(link.source).toBe('source');\n expect(link.target).toBe('target');\n expect(link.weight).toBe(10);\n expect(link.graph).toBe(null);\n expect(link.initialized).toBe(false);\n });\n\n it('testing weight related methods', function() {\n var graph = {\n links:[link],\n state:{\n VisualizerLink:{\n useAvgWeight:true\n }\n }\n }\n\n link.initialize(graph);\n link.setWeight(20);\n expect(link.weight).toBe(20);\n expect(link.getWeight()).toBe(20);\n link.increaseCount();\n expect(link.weight).toBe(20);\n expect(link.getWeight()).toBe(10);\n expect(link.getRawWeight()).toBe(20);\n link.setUseAvgWeight(false);\n expect(link.weight).toBe(20);\n expect(link.getWeight()).toBe(20);\n expect(link.getRawWeight()).toBe(20);\n\n })\n\n});\n\n\n\n\n" }, { "alpha_fraction": 0.6138995885848999, "alphanum_fraction": 0.6138995885848999, "avg_line_length": 34.74137878417969, "blob_id": "35c399a7a27ed6bca3a4be85588fab355138d522", "content_id": "c44c5424e97c6fd7e70d06e6294bc2d8628c525d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2072, "license_type": "permissive", "max_line_length": 91, "num_lines": 58, "path": "/app/components/directives/settings/tenantcreate.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "import {Component, EventEmitter, Input, Output} from \"@angular/core\";\nimport {FormBuilder, FormGroup, Validators} from \"@angular/forms\";\nimport {OrganizationsModel} from \"../../models/organizationsmodel\";\nimport {CRUDHelperService} from \"../../utils/crudhelperservice\";\n\nexport enum DisplayType {\n modal,\n component\n}\n\n@Component({\n selector: \"tenantcreate\",\n templateUrl: \"./tenantcreate.html\"\n})\n\nexport class TenantCreateComponent {\n public tenantCreateForm: FormGroup;\n public showLoader = false;\n public showServerError: boolean;\n public serverErrorMessage: string;\n @Input('displayType') displayType: DisplayType;\n @Output('created') created: EventEmitter<any>;\n @Output('canceled') canceled: EventEmitter<any>;\n public DisplayType = DisplayType;\n constructor(private formBuilder: FormBuilder,\n private organizationsModel: OrganizationsModel,\n private crudhelperService: CRUDHelperService) {\n this.created = new EventEmitter<any>();\n this.canceled = new EventEmitter<any>();\n this.tenantCreateForm = this.formBuilder.group({\n tenantName: ['', Validators.required]\n })\n }\n\n cancel() {\n this.canceled.emit(true);\n }\n\n create() {\n if (this.tenantCreateForm.valid) {\n this.showLoader = true;\n const tenantObj = {\n key: this.tenantCreateForm.get('tenantName').value,\n tenantName: this.tenantCreateForm.get('tenantName').value\n };\n this.organizationsModel.create(tenantObj, undefined)\n .then((result: any) => {\n this.showLoader = false;\n this.crudhelperService.showNotification(\"Tenant Created\", result.key);\n this.tenantCreateForm.reset();\n this.created.emit(true);\n }, (error) => {\n this.showLoader = false;\n this.crudhelperService.showServerError(\"Tenant: Create failed\", error);\n });\n }\n }\n}" }, { "alpha_fraction": 0.5350587964057922, "alphanum_fraction": 0.5374117493629456, "avg_line_length": 32.71428680419922, "blob_id": "c23f9db64cb989e7702d571f494d84d1364eb378", "content_id": "915b132ed52748dde713f3e666e2cfa55f5cb131", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2125, "license_type": "permissive", "max_line_length": 95, "num_lines": 63, "path": "/app/components/directives/verifydomdirective.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 11/7/16.\n */\n\nimport { Directive, Input, TemplateRef, ViewContainerRef } from \"@angular/core\";\nimport { AuthService } from \"../utils/authservice\";\nimport { NetworkService } from \"../utils/networkservice\";\n\n\n/* This Directive Hides and displays part of the dom based on the input verify string */\n@Directive({\n selector: '[verifydom]'\n})\n\nexport class VerifydomDirective{\n\n private display: boolean = false;\n constructor(private authService: AuthService,\n private templateRef: TemplateRef<any>,\n private viewContainer: ViewContainerRef,\n private networkService: NetworkService){\n\n }\n\n @Input() set verifydom(type: string){\n var directive = this;\n\n directive.display = false;\n switch (type){\n case 'admin': if(type === directive.authService.authTokenPayload['role'])\n directive.display = true;\n directive.render();\n break;\n case 'aci': if(directive.networkService.aciMode)\n directive.display = true;\n directive.render();\n directive.networkService.aciModeObservable.subscribe((res) => {\n directive.display = res;\n directive.render();\n });\n break;\n case 'docker': directive.verifyClusterMode(directive.networkService.clusterMode);\n directive.networkService.clusterModeObservable.subscribe((res) => {\n directive.verifyClusterMode(res);\n });\n }\n }\n\n verifyClusterMode(clusterMode: string){\n var directive = this;\n if(clusterMode === 'docker')\n directive.display = true;\n directive.render();\n }\n\n render(){\n this.viewContainer.clear();\n if(this.display){\n this.viewContainer.createEmbeddedView(this.templateRef);\n }\n }\n\n}\n\n" }, { "alpha_fraction": 0.620726466178894, "alphanum_fraction": 0.6260683536529541, "avg_line_length": 33.05454635620117, "blob_id": "573705940ac9e08d49eab7826f689255564576e4", "content_id": "ac93c3cdc23ceae4a1aebe633b7046f418cdb7f5", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1872, "license_type": "permissive", "max_line_length": 102, "num_lines": 55, "path": "/app/network_policies/isolationpolicylistctrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 10/19/16.\n */\nimport {Component, OnInit, OnDestroy, NgZone} from \"@angular/core\";\nimport {PoliciesModel} from \"../components/models/policiesmodel\";\nimport {CRUDHelperService} from \"../components/utils/crudhelperservice\";\nimport {Subscription, Observable} from \"rxjs\";\n@Component({\n selector: 'isolationpolicylist',\n templateUrl: './isolationpolicylist.html'\n})\n\nexport class IsolationListComponent implements OnInit, OnDestroy {\n private policiesModel:PoliciesModel;\n private crudHelperService:CRUDHelperService;\n public isolationPolicyListCtrl:any;\n private refresh:Subscription;\n\n constructor(policiesModel:PoliciesModel,\n crudHelperService:CRUDHelperService,\n private ngZone:NgZone) {\n this.crudHelperService = crudHelperService;\n this.policiesModel = policiesModel;\n this.isolationPolicyListCtrl = this;\n this.refresh = Observable.interval(5000).subscribe(() => {\n this.getPolicies(true);\n })\n }\n\n ngOnInit() {\n this.crudHelperService.startLoader(this);\n this.getPolicies(false);\n }\n\n getPolicies(reload:boolean) {\n var isolationPolicyListCtrl = this;\n this.policiesModel.get(reload)\n .then((result) => {\n isolationPolicyListCtrl['policies'] = result;\n isolationPolicyListCtrl.ngZone.run(() => {\n isolationPolicyListCtrl.crudHelperService.stopLoader(isolationPolicyListCtrl);\n });\n\n },\n (error) => {\n isolationPolicyListCtrl.ngZone.run(() => {\n isolationPolicyListCtrl.crudHelperService.stopLoader(isolationPolicyListCtrl);\n });\n });\n }\n\n ngOnDestroy() {\n this.refresh.unsubscribe();\n }\n}" }, { "alpha_fraction": 0.4909090995788574, "alphanum_fraction": 0.4950000047683716, "avg_line_length": 35.081966400146484, "blob_id": "5c5314ee1fa661dbe1fe2e0c5ebcd0ace4dcd3be", "content_id": "64512fa1bcde92d50dff23c025dd452dd9bb7423", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2200, "license_type": "permissive", "max_line_length": 110, "num_lines": 61, "path": "/app/components/models/applicationgroupsmodel.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 3/11/16.\n */\nimport { Injectable } from '@angular/core';\nimport { Http } from '@angular/http';\nimport { Collection } from \"./collection\";\nimport {Observable} from \"rxjs\";\nimport { ContivGlobals } from \"./contivglobals\";\nimport {ApiService} from \"../utils/apiservice\";\nimport {isUndefined} from \"util\";\n\n\n@Injectable()\nexport class ApplicationGroupsModel extends Collection {\n constructor(http: Http, apiService: ApiService) {\n super(http, ContivGlobals.APPLICATIONGROUPS_ENDPOINT,apiService);\n }\n\n /**\n * Generate key for application group\n * @param group\n */\n generateKey(group) {\n return group.tenantName + ':' + group.groupName;\n }\n\n getInspectByKey(key:string, url: string, reload: boolean): Promise<any>{\n return super.getInspectByKey(key,url,reload)\n .then((result) => {\n if(!isUndefined(result['Oper'].endpoints)){\n var processedEndpoints = [];\n var endpoints = result['Oper'].endpoints;\n for(var i=0; i<endpoints.length; i++){\n if(isUndefined(endpoints[i].containerID)){\n endpoints[i]['containerID'] = endpoints[i]['endpointID'];\n endpoints[i]['containerName'] = endpoints[i]['endpointID'].toString().substr(0,6);\n }\n }\n result['Oper'].endpoints = endpoints;\n }\n return result;\n });\n }\n\n public get(reload:boolean): Promise<any>{\n return super.get(reload)\n .then((result) => {\n //add logic for result processing\n var items = [];\n for (let item of result){\n if (typeof item.policies === 'undefined')\n item['policies']=[];\n if (typeof item.networkName === 'undefined')\n item['networkName']='';\n items.push(item);\n }\n return items;\n });\n }\n\n}" }, { "alpha_fraction": 0.5330865383148193, "alphanum_fraction": 0.5340120196342468, "avg_line_length": 30.794116973876953, "blob_id": "f59f96ebe9cab2bffffc5b20491ffc16ac9d7e05", "content_id": "afc38fd7a91cbd84705a95163c3452f095000bbb", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2161, "license_type": "permissive", "max_line_length": 109, "num_lines": 68, "path": "/app/settings/nodes/nodecreate.component.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "import { Component, Inject, OnInit, NgZone } from \"@angular/core\";\nimport { ActivatedRoute, Router } from \"@angular/router\";\nimport * as _ from 'lodash';\nimport { CRUDHelperService } from \"../../components/utils/crudhelperservice\";\nimport { BgpsModel } from \"../../components/models/bgpsmodel\";\n\n\n@Component({\n selector: 'nodecreate',\n templateUrl: './nodecreate.html'\n})\n\nexport class NodeCreateComponent {\n newNode:any = {};\n\n\n constructor(private activatedRoute:ActivatedRoute,\n private router:Router,\n private crudHelperService:CRUDHelperService,\n private bgpsModel:BgpsModel,\n private ngZone:NgZone) {\n var component = this;\n\n function resetForm() {\n crudHelperService.stopLoader(component);\n component.newNode = {\n \"key\": \"\",\n \"hostname\": \"\",\n \"routerip\": \"\",\n \"as\": \"0\",\n \"neighbor\": \"\",\n \"neighbor-as\": \"0\"\n };\n }\n\n resetForm();\n }\n\n returnToNodes() {\n this.router.navigate(['../list'], {relativeTo: this.activatedRoute});\n }\n\n cancelCreating() {\n this.returnToNodes();\n }\n\n createNode(formvalid:boolean) {\n var component = this;\n if (formvalid) {\n this.crudHelperService.startLoader(this);\n component.newNode.key = component.newNode.hostname;\n this.bgpsModel.create(component.newNode, undefined)\n .then((result) => {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n component.crudHelperService.showNotification(\"Node: Created\", result.key.toString());\n });\n component.returnToNodes();\n }, (error) => {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n component.crudHelperService.showServerError(\"Node: Create failed\", error);\n });\n }\n }\n\n}" }, { "alpha_fraction": 0.683351457118988, "alphanum_fraction": 0.7225244641304016, "avg_line_length": 21.975000381469727, "blob_id": "23d358e9e24f307eb637fc84ab950b9d8e200d19", "content_id": "83959c1e18f5afd6983ce9062621eb57d647275d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 919, "license_type": "permissive", "max_line_length": 92, "num_lines": 40, "path": "/backend/INSTALL.md", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "#Installing and setting up the backend\n\n##Step 1: Fowarding ports\nModify Vagrantfile to forward python server and Influx ports.\n```\nnode.vm.network \"forwarded_port\", guest: 4000, host: 4000\nnode.vm.network \"forwarded_port\", guest: 8086, host: 8086\n```\nIn the nginx.conf file, add the following location directives:\n```\nlocation /visualization/influx/{\n proxy_pass http://contiv215:8086/;\n}\nlocation /visualization/service {\n proxy_pass http://contiv215:4000;\n}\n```\n\n##Step 2: Setup containers and services\nIf you have no containers running, you can run serviceInit.sh to start some sample services.\nOn Node 1:\n```\n$ ./serviceInit.sh\n```\nAnd to add endpoint containers on other nodes:\n```\n./serviceInit.sh -c\n```\n\n##Step 3: Setting up the python servers\nOn all nodes, run:\n```\n$ python telegrafdatasource.py\n```\n\n##Step 4: Installing and Running telegraf and InfluxDB:\nOn Node 1:\n```\n$ sudo ./backendConfig.sh\n```\n" }, { "alpha_fraction": 0.6129213571548462, "alphanum_fraction": 0.6148876547813416, "avg_line_length": 35.336734771728516, "blob_id": "50cf76507ae2ce5ec10244a3a42f8239449e0b66", "content_id": "f1198df9a22cc0f4508cb890287d903daffab7ef", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3560, "license_type": "permissive", "max_line_length": 122, "num_lines": 98, "path": "/app/applicationgroups/contractgroup.component.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 12/14/16.\n */\nimport { Component, Input, OnChanges } from '@angular/core';\nimport * as _ from 'lodash';\nimport { ContractGroupsModel } from \"../components/models/contractgroupsmodel\";\n\n@Component({\n selector: 'ctv-contractgroup',\n templateUrl: './contractgroup.html'\n})\nexport class ContractGroupSelectionComponent implements OnChanges {\n @Input() mode:string;\n @Input() applicationgroup:any;\n\n selectedContractGroups:any[] = []; // To Store contract groups selected by user to display\n contractGroups:any[] = []; // To Get all contract groups of tenant\n contractGroupSearchText:string = '';\n\n constructor(private contractGroupsModel:ContractGroupsModel) {\n\n }\n\n ngOnChanges() {\n let component = this;\n\n /**\n * Get contract group objects for each contract group present in applicationgroup\n */\n function getSelectedContractGroups() {\n component.applicationgroup.extContractsGrps.forEach(function (contractGroup) {\n //To display details of selected contract groups\n let key = component.applicationgroup.tenantName + ':' + contractGroup;\n component.contractGroupsModel.getModelByKey(key, false, undefined)\n .then(function (group) {\n component.selectedContractGroups.push(group);\n });\n });\n }\n\n /**\n * To check 'details' or 'edit' mode (not create mode)\n */\n if (component.mode === 'details' || (component.mode === 'edit' && component.applicationgroup.groupName != \"\")) {\n component.getContractGroups();\n //Application Groups might not have any contract groups associated with them so define an empty array\n if (component.applicationgroup.extContractsGrps === undefined) {\n component.applicationgroup.extContractsGrps = [];\n }\n getSelectedContractGroups();\n }\n }\n\n /**\n * Get contract groups for the given tenant.\n */\n getContractGroups() {\n let component = this;\n component.contractGroupsModel.get(false).then(function (result) {\n component.contractGroups = _.filter(result, {\n 'tenantName': component.applicationgroup.tenantName\n });\n });\n }\n\n /**\n * Add contract group to application group\n */\n addContractGroup(contractGroupName) {\n let component = this;\n\n if (contractGroupName !== undefined && _.includes(component.selectedContractGroups, contractGroupName) == false) {\n //To display selected contract groups\n let key = component.applicationgroup.tenantName + ':' + contractGroupName;\n component.contractGroupsModel.getModelByKey(key, false, undefined)\n .then(function (group) {\n component.selectedContractGroups.push(group);\n });\n\n //To be added to application group and saved to the server\n component.applicationgroup.extContractsGrps\n .push(contractGroupName);\n }\n };\n\n /**\n * Remove contract group from application group\n */\n removeContractGroup(contractGroupName) {\n _.remove(this.selectedContractGroups, function (group) {\n return group.contractsGroupName === contractGroupName;\n });\n _.remove(this.applicationgroup.extContractsGrps, function (group) {\n return group === contractGroupName;\n });\n\n };\n}" }, { "alpha_fraction": 0.6118143200874329, "alphanum_fraction": 0.6118143200874329, "avg_line_length": 36.421051025390625, "blob_id": "cb82a5fc02ad3e92f466510e58378898c65b929c", "content_id": "af6f3566932369b042f7da29c042311a75e80ff2", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3555, "license_type": "permissive", "max_line_length": 94, "num_lines": 95, "path": "/app/settings/users/userdetails.component.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "import { Component, Inject, NgZone } from '@angular/core';\nimport { ActivatedRoute, Router } from \"@angular/router\";\nimport { UsersModel } from \"../../components/models/usersmodel\";\nimport { CRUDHelperService } from \"../../components/utils/crudhelperservice\";\nimport { OrganizationsModel } from \"../../components/models/organizationsmodel\";\nimport { User } from \"./usercreate.component\";\nimport { ContivGlobals } from \"../../components/models/contivglobals\";\nimport { AuthService } from \"../../components/utils/authservice\";\nimport { ProfileDisplayType } from \"../../components/directives/settings/userprofileedit\";\n\n@Component({\n selector: 'userdetails',\n templateUrl: './userdetails.html'\n})\nexport class UserDetailsComponent {\n user:User = {username: '', password: '', first_name: '', last_name: '', disable: false};\n organizations:any[] = [];\n mode:string = 'details';\n isRootAdmin: boolean = false;\n isLoggedInUser: boolean = false;\n public userDetailsCtrl:any = {}\n public username: string = ''\n public ProfileDisplayType = ProfileDisplayType;\n public showLoader: boolean = true;\n\n constructor(private activatedRoute: ActivatedRoute,\n private router: Router,\n private ngZone: NgZone,\n private usersModel:UsersModel,\n private crudHelperService:CRUDHelperService,\n private authService:AuthService) {\n var component = this;\n this.user = {username: '', first_name: '', last_name: '', disable: false};\n\n component.username = activatedRoute.snapshot.params['key'];\n\n if(component.mode == 'details'){\n component.getUserDetails();\n }\n }\n\n getUserDetails(){\n var component = this;\n component.usersModel.getModelByKey(component.username, false, 'username')\n .then(function (user) {\n component.user = user;\n component.isRootAdmin = (user.username === 'admin');\n component.isLoggedInUser = (component.authService.username === user.username);\n component.crudHelperService.stopLoader(component);\n }, function(error){\n component.crudHelperService.stopLoader(component);\n });\n }\n\n returnToUser() {\n this.router.navigate(['../../list'], { relativeTo: this.activatedRoute });\n }\n\n returnToUserDetails() {\n this.getUserDetails();\n this.mode = 'details';\n }\n\n editUser() {\n this.mode = 'edit';\n }\n\n cancelEditing() {\n this.returnToUserDetails();\n }\n\n cancelDetails() {\n this.returnToUser();\n }\n\n deleteUser() {\n var component = this;\n component.crudHelperService.startLoader(component);\n var username = component.user['username'];\n var url = ContivGlobals.USERS_ENDPOINT + username + '/';\n component.usersModel.deleteUsingKey(username, 'username', url).then(\n function successCallback(result) {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n component.crudHelperService.showNotification(\"User: Deleted\", result);\n component.returnToUser();\n }, function errorCallback(result) {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n component.crudHelperService.showServerError(\"User: Delete failed\", result);\n });\n }\n}\n" }, { "alpha_fraction": 0.5068762302398682, "alphanum_fraction": 0.5216865539550781, "avg_line_length": 34.39037322998047, "blob_id": "3102d33e8213a990fd92f2008525bca5de499783", "content_id": "a1918ef2d2102ffe0fe049855ff68b898cd1e025", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6617, "license_type": "permissive", "max_line_length": 103, "num_lines": 187, "path": "/app/components/directives/linegraphcomponent.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 11/16/16.\n */\n\nimport {Component, OnInit, DoCheck, Input, OnDestroy, NgZone} from \"@angular/core\";\nimport {ChartService, EndpointType} from \"../utils/chartservice\";\nimport {Subscription} from \"rxjs\";\nimport {isUndefined} from \"util\";\nimport {isNull} from \"util\";\n@Component({\n selector: 'linegraph',\n templateUrl: './linegraph.html',\n styleUrls: ['./linegraph.css']\n})\n\nexport class LineGraphComponent implements OnInit, DoCheck, OnDestroy{\n public EndpointType = EndpointType;\n private prevKey: string;\n @Input('key') key: string;\n @Input('endpointType') endpointType: EndpointType;\n private prevEndpointType: EndpointType;\n public inspectActivated: boolean;\n private subscription: Subscription;\n private start: number;\n private end: number;\n public lineChartData:Array<any>;\n public lineChartLabels:Array<any>;\n public lineChartOptions:any = {};\n public lineChartColors:Array<any> = [\n { // dark grey\n backgroundColor: 'rgba(0,117,180,0.1)',\n borderColor: 'rgba(4,159,217,1)',\n pointBackgroundColor: 'rgba(0,117,180,1)',\n pointBorderColor: 'rgba(0,117,180,1)',\n pointHoverBackgroundColor: '#fff',\n pointHoverBorderColor: 'rgba(77,83,96,1)'\n }\n ];\n public lineChartLegend:boolean = true;\n public lineChartType:string = 'line';\n public scaleEnd: number;\n constructor(private chartService: ChartService){\n this.lineChartData = [{\n label: '# of Endpoints',\n data: [0, 0, 0, 0],\n }];\n this.adjustScale(100);\n this.lineChartLabels = ['0T', '1T', '2T', '3T'];\n this.inspectActivated = false;\n this.prevKey = '';\n this.key = '';\n this.endpointType = EndpointType.Network;\n this.prevEndpointType = EndpointType.Network;\n }\n\n ngOnInit(){\n this.prevKey = this.key;\n this.prevEndpointType = this.endpointType;\n this.subscription = this.chartService.stream.subscribe((result) => {\n var resultKey = result['iKey'];\n var resultEndpointType = result['type'];\n var currKey = this.key;\n var currEndpointType = this.endpointType;\n if(resultKey===currKey && resultEndpointType === currEndpointType){\n this.scaleEnd++;\n if (!this.inspectActivated){\n this.start++;\n this.end++;\n this.loadGraphData();\n }\n }\n });\n }\n\n /* This function is needed to redraw the chart after every update. The drawing is done\n using last 15 array values from chartservice.graphdata.\n eg:\n chartservice.graphdata = { 0:\n { 'contiv-net': [1,2,3,4,5...],\n 'super-net': [1,2,3,4,5...]\n },\n 1:\n { 'app-group1': [1,2,3,4,5...],\n 'app-group2': [1,2,3,4,5...]\n }\n }\n In the above structure 0 represents enum EndpointType.Network;\n 1 represents enum EndpointType.ApplicationGroup;\n */\n private loadGraphData(){\n this.lineChartData[0]['data']=[];\n this.lineChartLabels = [];\n var max=0;\n for(var i= this.start; i<=this.end; i++){\n var endpointcount = this.chartService.graphData[this.endpointType][this.key][i];\n this.lineChartData[0]['data'].push(endpointcount);\n this.lineChartLabels.push(i + 'T');\n if(endpointcount > max){\n max = endpointcount;\n }\n }\n if(!isUndefined(this.lineChartOptions.scales)){\n var scaleMax = this.lineChartOptions.scales.yAxes[0].ticks.suggestedMax;\n if(max > scaleMax){\n this.adjustScale(max);\n }\n }\n else{\n this.adjustScale(max);\n }\n\n }\n\n /*\n This function is needed to update the Y-axes scale values so that the line\n is always within the boundry and there is significant change in offset of line\n when there is variation in the array values. This is needed since scale always begins at 0.\n */\n private adjustScale(max: number){\n this.lineChartOptions = {};\n this.lineChartOptions = {\n animation: false,\n responsive: true,\n }\n if(max < 7){\n this.lineChartOptions['scales'] = {\n yAxes: [{\n type: 'linear',\n ticks: {\n beginAtZero: true,\n suggestedMax: 8,\n }\n }]\n }\n }\n else{\n this.lineChartOptions['scales'] = {\n yAxes: [{\n type: 'linear',\n ticks: {\n beginAtZero: true,\n suggestedMax: Math.round(max * 3),\n callback: function(value, index, values){\n return Math.round(value);\n }\n }\n }]\n }\n }\n }\n\n ngDoCheck(){\n if((this.key != '') && (!isUndefined(this.key)) && (!isNull(this.key)))\n if((this.key!==this.prevKey) || (this.endpointType !== this.prevEndpointType)){\n if(!isUndefined(this.chartService.graphData[this.endpointType][this.key]))\n this.prepareChartData();\n }\n }\n\n // This function kind of resets the chart when different network or application group is selected.\n private prepareChartData(){\n this.inspectActivated = false;\n this.end = this.chartService.graphData[this.endpointType][this.key].length - 1;\n this.scaleEnd = this.end;\n this.start = this.end - 14 ;\n this.lineChartOptions = {};\n this.loadGraphData();\n this.prevKey = this.key;\n this.prevEndpointType = this.endpointType;\n }\n\n slide(slideVal: number){\n if(slideVal < this.scaleEnd){\n this.inspectActivated = true;\n }\n if(slideVal == this.scaleEnd){\n this.inspectActivated = false;\n }\n this.end = slideVal;\n this.start = slideVal - 14;\n this.loadGraphData();\n }\n\n ngOnDestroy(){\n this.subscription.unsubscribe();\n }\n}" }, { "alpha_fraction": 0.6745426654815674, "alphanum_fraction": 0.7080792784690857, "avg_line_length": 26.33333396911621, "blob_id": "e714a1cf9a0f37fda7fde7aaebd7637139eef1fe", "content_id": "a62160e70e240a49301308018709917caad1c7ec", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1312, "license_type": "permissive", "max_line_length": 115, "num_lines": 48, "path": "/README.md", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "# Setup contiv-ui with contiv netmaster\n\n#### Step 1: Clone the netplugin repository and bring up the VMs\n\n```sh\ngit clone https://github.com/contiv/netplugin.git\nexport GOPATH=\"<Your gopath>\"\ncd netplugin\n```\nModify Vagrantfile to forward etcd port:\n```\nnode.vm.network \"forwarded_port\", guest: 2379, host:2379\n```\n```sh\nmake demo\n```\n\n#### Step 2: Clone contiv-ui\n```sh\ngit clone https://github.com/contiv/contiv-ui.git\n```\n\n#### Step 3: Deploy Contiv UI as a Auth Proxy container.\n\n* Checkout 'contiv/auth_proxy'\n * Inside the 'auth_proxy' checkout:\n```sh\ngit pull # if you need to refresh the checkout\nmake\nmake generate-certificate # if this is a new checkout\n```\n* Also, set an env var pointing to the local UI src code:\n```sh\nexport UI_DIR='/Users/john/Dev/gocode/src/github.com/contiv/contiv-ui/app'\n```\n\n* Load the auth\\_proxy as a container. Note where in this CLI there is a reference to the data store and netmaster:\n```sh\ndocker run -it \\\n\t-v $PWD/local_certs:/local_certs:ro \\\n\t-v $UI_DIR:/ui:ro \\\n\t-p 10000:10000 contiv/auth_proxy:devbuild --listen-address=0.0.0.0:10000 \\\n\t--netmaster-address=localhost:9999 \\\n\t--data-store-address=etcd://localhost:2379 \\\n\t--tls-certificate=/local_certs/cert.pem --tls-key-file=/local_certs/local.key\n```\n\n#### Step 4: Access UI using https://localhost:10000/\n" }, { "alpha_fraction": 0.698924720287323, "alphanum_fraction": 0.7158218026161194, "avg_line_length": 25.040000915527344, "blob_id": "2c45ec9afdd1da717d68871aa5d9ed4abca1d79e", "content_id": "653b12df0d17febe258fb00e3f335d8de9c96f39", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 651, "license_type": "permissive", "max_line_length": 97, "num_lines": 25, "path": "/app/vendor.browser.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 10/6/16.\n */\n// Vendors\n\n// Angular 2\nimport '@angular/core';\nimport '@angular/common';\nimport '@angular/compiler';\nimport '@angular/platform-browser';\nimport '@angular/platform-browser-dynamic';\nimport '@angular/http';\nimport '@angular/router';\nimport '@angular/forms';\n\n// RxJS 5\nimport 'rxjs/Rx';\n// other libraries\nimport 'd3';\nimport '../app/bower_components/semantic-ui/dist/semantic.js';\nimport 'lodash';\n// For vendors for example jQuery, Lodash, angular2-jwt import them here\n// Also see src/typings.d.ts as you also need to run `typings install x` where `x` is your module\nimport 'chart.js';\nimport 'ng2-charts';\n" }, { "alpha_fraction": 0.5326112508773804, "alphanum_fraction": 0.5335531234741211, "avg_line_length": 37.61818313598633, "blob_id": "114ad08a283250d8339947e2fb82f735c8688487", "content_id": "b7edf748cd57ed91203a8dfa021c30bc1cdf78bd", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4247, "license_type": "permissive", "max_line_length": 93, "num_lines": 110, "path": "/app/components/utils/networkservice.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { Http, Response } from '@angular/http';\nimport 'rxjs/add/operator/map';\nimport { ContivGlobals } from \"../models/contivglobals\";\nimport { ApiService } from \"./apiservice\";\nimport { Subject, Observable } from \"rxjs\";\n\n@Injectable()\nexport class NetworkService {\n\n public aciMode: boolean = false;\n private aciModeSubject: Subject<any>;\n public aciModeObservable: Observable<any>;\n public clusterMode: string = '';\n private clusterModeSubject: Subject<any> = new Subject<any>();\n public clusterModeObservable: Observable<any> = this.clusterModeSubject.asObservable();\n constructor(private http: Http, private apiService: ApiService) {\n this.aciModeSubject = new Subject<any>();\n this.aciModeObservable = this.aciModeSubject.asObservable();\n var networkservice = this;\n this.getSettings().then((res)=>{},(err)=>{});\n this.getGlobalInspect().then((res) => {\n networkservice.clusterMode = res.Oper.clusterMode;\n networkservice.clusterModeSubject.next(networkservice.clusterMode);\n }, (error) => {});\n }\n\n getSettings(): Promise<any> {\n var networkservice = this;\n let promise = new Promise(function (resolve, reject) {\n let url = ContivGlobals.NETWORK_SETTINGS_ENDPOINT;\n networkservice.apiService.get(url).map((res: Response) => res.json()).toPromise()\n .then(function successCallback(result) {\n if (result[0].networkInfraType === 'aci') {\n networkservice.aciMode = true;\n } else {\n networkservice.aciMode = false;\n }\n networkservice.aciModeSubject.next(networkservice.aciMode);\n resolve(result[0]);\n }, function errorCallback(result) {\n reject(result);\n });\n });\n\n return promise;\n }\n\n updateSettings(setting) {\n setting.key = \"global\";\n setting.name = \"global\";\n return this.apiService.post(ContivGlobals.NETWORK_SETTINGS_ENDPOINT\n + 'global/', setting).map((res: Response) => res.json()).toPromise();\n }\n\n getAciSettings(): Promise<any> {\n var networkservice = this;\n let promise = new Promise(function (resolve, reject) {\n let url = ContivGlobals.ACI_SETTINGS_ENDPOINT;\n networkservice.apiService.get(url).map((res: Response) => res.json()).toPromise()\n .then(function successCallback(result) {\n if (result.length == 0) {\n result = [\n {\n key: '',\n enforcePolicies: 'yes',\n includeCommonTenant: 'no',\n name: '',\n nodeBindings: '',\n pathBindings: '',\n physicalDomain: ''\n }\n ]\n }\n resolve(result[0]);\n }, function errorCallback(result) {\n reject(result);\n });\n });\n\n return promise;\n }\n\n updateAciSettings(setting) {\n setting.key = \"aciGw\";\n setting.name = \"aciGw\";\n return this.apiService.post(ContivGlobals.ACI_SETTINGS_ENDPOINT\n + 'aciGw/', setting).map((res: Response) => res.json()).toPromise();\n }\n\n getGlobalInspect(): Promise<any> {\n var networkservice = this;\n let promise = new Promise(function (resolve, reject) {\n let url = ContivGlobals.GLOBAL_NETWORK_INSPECT_ENDPOINT + 'global/';\n networkservice.apiService.get(url).map((res: Response) => res.json()).toPromise()\n .then(function successCallback(result) {\n resolve(result);\n }, function errorCallback(result) {\n reject(result);\n });\n });\n\n return promise;\n }\n\n setAciMode(mode: boolean){\n this.aciMode = mode;\n this.aciModeSubject.next(this.aciMode);\n }\n}" }, { "alpha_fraction": 0.6478162407875061, "alphanum_fraction": 0.6488602757453918, "avg_line_length": 41.89552307128906, "blob_id": "39b77e455c79f53b7f0c032a4fc9c894fa3a34a1", "content_id": "db6b16a45d50e4a5b00d58b6608cec973d5ef38c", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5747, "license_type": "permissive", "max_line_length": 135, "num_lines": 134, "path": "/app/applicationgroups/applicationgroupcreatectrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 3/11/16.\n */\nimport { Component, Inject, ViewChild, NgZone } from '@angular/core';\nimport { ActivatedRoute, Router } from \"@angular/router\";\nimport { NetworksModel } from \"../components/models/networksmodel\";\nimport { ApplicationGroupsModel } from \"../components/models/applicationgroupsmodel\";\nimport { CRUDHelperService } from \"../components/utils/crudhelperservice\";\nimport { OrganizationsModel } from \"../components/models/organizationsmodel\";\nimport { NetworkService } from \"../components/utils/networkservice\";\nimport { ContractGroupSelectionComponent } from \"./contractgroup.component\";\nimport { IsolationPolicySelectionComponent } from \"./isolationpolicydirective\";\nimport { BandwidthPolicySelectionComponent } from \"./bandwidthpolicydirective\";\n\n@Component({\n selector: 'applicationgroupcreate',\n templateUrl: './applicationgroupcreate.html'\n})\nexport class ApplicationGroupCreateComponent {\n networks:any[] = [];\n tenants:any[] = [];\n applicationGroup:any = {};\n\n @ViewChild(BandwidthPolicySelectionComponent) bandwidthPolicyComponent: BandwidthPolicySelectionComponent;\n @ViewChild(IsolationPolicySelectionComponent) isolationPolicyComponent: IsolationPolicySelectionComponent;\n @ViewChild(ContractGroupSelectionComponent) contractGroupComponent: ContractGroupSelectionComponent;\n\n constructor(private activatedRoute:ActivatedRoute,\n private router:Router,\n private ngZone:NgZone,\n private organizationsModel:OrganizationsModel,\n private networksModel:NetworksModel,\n private applicationGroupsModel:ApplicationGroupsModel,\n private crudHelperService:CRUDHelperService,\n private networkService:NetworkService) {\n\n var applicationGroupCreateCtrl = this;\n\n\n function resetForm() {\n crudHelperService.stopLoader(applicationGroupCreateCtrl);\n applicationGroupCreateCtrl.applicationGroup = {\n groupName: '', // For Group Name\n networkName: '', // For Network Name\n policies: [], // For Isolation policies\n netProfile: '', // For Bandwidth policy Name\n extContractsGrps: [], // For External contract groups\n tenantName: '',\n cfgdTag: ''\n };\n }\n\n resetForm();\n }\n\n ngOnInit() {\n var component = this;\n component.crudHelperService.startLoader(component);\n\n function getTenants(reload:boolean) {\n component.organizationsModel.get(reload)\n .then((result) => {\n component.tenants = result;\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n }, (error) => {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n });\n }\n\n getTenants(false);\n }\n\n returnToApplicationGroup() {\n this.router.navigate(['../list'], {relativeTo: this.activatedRoute});\n }\n\n cancelCreating() {\n this.returnToApplicationGroup();\n }\n\n createApplicationGroup(validform:boolean) {\n var applicationGroupCreateCtrl = this;\n if (validform) {\n applicationGroupCreateCtrl.crudHelperService.startLoader(applicationGroupCreateCtrl);\n\n applicationGroupCreateCtrl.applicationGroup.key =\n applicationGroupCreateCtrl.applicationGroupsModel.generateKey(applicationGroupCreateCtrl.applicationGroup);\n if (applicationGroupCreateCtrl.applicationGroup.cfgdTag === '') {\n delete applicationGroupCreateCtrl.applicationGroup.cfgdTag;\n }\n /**\n * applicationGroup consist of Group Name, Network Name, Isolation Policies, Bandwidth Policy, cfgdtag\n */\n\n applicationGroupCreateCtrl.applicationGroupsModel.create(applicationGroupCreateCtrl.applicationGroup, undefined).then(\n function successCallback(result) {\n applicationGroupCreateCtrl.crudHelperService.stopLoader(applicationGroupCreateCtrl);\n applicationGroupCreateCtrl.crudHelperService.showNotification(\"Application group: Created\", result.key.toString());\n applicationGroupCreateCtrl.returnToApplicationGroup();\n }, function errorCallback(result) {\n applicationGroupCreateCtrl.crudHelperService.stopLoader(applicationGroupCreateCtrl);\n applicationGroupCreateCtrl.crudHelperService.showServerError(\"Application group: Create failed\", result);\n });\n }\n }\n\n /**\n * Get networks for the given tenant.\n */\n getNetworks(tenantName:string) {\n var component = this;\n component.networksModel.get(false).then(function (result) {\n component.networks = _.filter(result, {\n 'tenantName': tenantName\n });\n },(err) => {});\n }\n\n updateTenant(tenantName:string) {\n var component = this;\n component.applicationGroup.tenantName = tenantName;\n component.getNetworks(tenantName);\n component.isolationPolicyComponent.getIsolationPolicies();\n component.bandwidthPolicyComponent.getNetprofiles();\n //contractGroupComponent might be undefined if ACI is not configured\n if ((component.contractGroupComponent !== undefined) && (component.contractGroupComponent !== null)) {\n component.contractGroupComponent.getContractGroups();\n }\n }\n}" }, { "alpha_fraction": 0.6791132092475891, "alphanum_fraction": 0.6861143708229065, "avg_line_length": 49.411766052246094, "blob_id": "657af928d6e156c89eb5bd576bf444976f038c3e", "content_id": "476deff55e7d5f32cb10cfdb39170ec4688afb87", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 857, "license_type": "permissive", "max_line_length": 120, "num_lines": 17, "path": "/e2e-tests/dashboard/dashboardpageobject.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 7/27/16.\n */\n\n\nvar DashboardPage = function(){\n this.nodes = element(by.css(\"a.card[ui-sref='contiv.menu.nodes.list()']\"));\n this.networks = element(by.css(\"a.card[ui-sref='contiv.menu.networks.list()']\"));\n this.volumes = element(by.css(\"a.card[ui-sref='contiv.menu.volumes.list()']\"));\n this.applicationGroup = element(by.css(\"a.card[ui-sref='contiv.menu.applicationgroups.list()']\"));\n this.networkPolicies = element.all(by.css(\"a.card[ui-sref='contiv.menu.networkpolicies.list.isolation()']\")).get(0);\n this.storagePolicies = element(by.css(\"a.card[ui-sref='contiv.menu.storagepolicies.list()']\"));\n this.resourceContent = element.all(by.css(\"div.container > div.content\")).first();\n this.policyContent = element.all(by.css(\"div.container > div.content\")).last();\n}\n\nmodule.exports = DashboardPage;\n" }, { "alpha_fraction": 0.5476783514022827, "alphanum_fraction": 0.5594564080238342, "avg_line_length": 41.05714416503906, "blob_id": "2db4e68e5e29ec457f4014a05d9032a04786264f", "content_id": "daf4d127d9ed2943bf30abe9ce1800c9ad0d4609", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4415, "license_type": "permissive", "max_line_length": 120, "num_lines": 105, "path": "/e2e-tests/volumes/volumespagespec.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 8/17/16.\n */\n\nvar VolumesPage = require('./volumespageobject');\n\ndescribe(\"Volumes\", function(){\n var volList = new VolumesPage.volList();\n var volCreate = new VolumesPage.volCreate();\n var volDetails = new VolumesPage.volDetails();\n var volSnapshotCopy = new VolumesPage.volSnapshotCopy();\n\n beforeEach(function(){\n browser.get(\"#/m/volumes/list\");\n });\n\n it(\"Create volume\", function(){\n testConfig.clickLink(volList.createButton);\n volCreate.volumename.sendKeys(testConfig.volumes.name);\n volCreate.collapsible.each(function(element, index){\n browser.actions()\n .mouseMove(element, {x: 0, y: 0}) // 100px from left, 100 px from top of plot0\n .click()\n .perform();\n });\n volCreate.volumepolicy.click();\n volCreate.volumecreate.submit();\n expect(volCreate.serverMessage.isPresent()).toBeFalsy();\n });\n\n it(\"verify create\", function(){\n browser.refresh();\n testConfig.verifyCreate(volList.volumeName, testConfig.volumes.name);\n });\n\n it(\"verify storage policy details\", function(){\n volList.volumeName.click().then(function(){\n volDetails.collapsible.each(function(element, index){\n browser.actions()\n .mouseMove(element, {x: 0, y: 0}) // 100px from left, 100 px from top of plot0\n .click()\n .perform();\n });\n volDetails.detailsTable.then(function(elements){ \n expect(elements[0].all(by.css(\"td\")).get(1).getText()).toEqual(testConfig.volumes.name);\n });\n var storagePolicyData = testConfig.getVerificationList(testConfig.storagePolicy);\n volDetails.policyDetails.each(function(element, index){\n element.all(by.css(\"td\")).get(1).getText().then(function(text){\n expect(storagePolicyData).toContain(text);\n });\n });\n });\n });\n\n it(\"verify snapshot create\", function(){\n volList.volumeName.click().then(function(){\n volDetails.collapsible.each(function(element, index){\n browser.actions()\n .mouseMove(element, {x: 0, y: 0}) // 100px from left, 100 px from top of plot0\n .click()\n .perform();\n });\n expect(volDetails.snapshotSuccessMes.isPresent()).toBeFalsy();\n volDetails.snapshotButton.click().then(function(){\n testConfig.waitForPageLoad(5000);\n browser.waitForAngular();\n expect(volDetails.snapshotSuccessMes.isPresent()).toBeTruthy();\n expect(volDetails.snapshotDetails.all(by.css(\"td\")).get(0).isPresent()).toBeTruthy();\n testConfig.clickLink(volDetails.snapshotIcon);\n });\n });\n });\n \n it(\"verify snapshot copy\", function(){\n volList.volumeName.click().then(function(){\n volDetails.collapsible.each(function(element, index){\n browser.actions()\n .mouseMove(element, {x: 0, y: 0}) // 100px from left, 100 px from top of plot0\n .click()\n .perform();\n });\n var snapshot = \"\";\n volDetails.snapshotDetails.all(by.css(\"td\")).get(0).getText().then(function(text){\n snapshot=text;\n testConfig.clickLink(volDetails.snapshotIcon);\n expect(volSnapshotCopy.snapshot.getText()).toEqual(snapshot);\n });\n volSnapshotCopy.copyButton.click().then(function(){\n expect(volSnapshotCopy.errorMessage.isPresent()).toBeTruthy();\n });\n volSnapshotCopy.newVolume.sendKeys(testConfig.volumes.newvolume);\n volSnapshotCopy.copyButton.click().then(function(){\n expect(volSnapshotCopy.serverMessage.isPresent()).toBeFalsy();\n volSnapshotCopy.serverMessage.isPresent().then(function(present){\n if(!present){\n volDetails.detailsTable.then(function(elements){\n expect(elements[0].all(by.css(\"td\")).get(1).getText()).toEqual(testConfig.volumes.newvolume);\n });\n }\n });\n });\n });\n });\n});" }, { "alpha_fraction": 0.6153628826141357, "alphanum_fraction": 0.6170573234558105, "avg_line_length": 35.88541793823242, "blob_id": "692217ac664fdfc582ba098705f7495b15d3580d", "content_id": "cf2b1a71703a740d438a90242846a1f11eaac086", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3541, "license_type": "permissive", "max_line_length": 146, "num_lines": 96, "path": "/app/network_policies/isolationpolicycreatectrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 3/10/16.\n */\nimport { Component, Inject, OnInit, NgZone } from '@angular/core';\nimport { ActivatedRoute, Router } from \"@angular/router\";\nimport { PoliciesModel } from \"../components/models/policiesmodel\";\nimport { CRUDHelperService } from \"../components/utils/crudhelperservice\";\nimport { PolicyTab } from \"./networkpoliciestabsctrl\";\nimport { OrganizationsModel } from \"../components/models/organizationsmodel\";\n\n@Component({\n selector: 'isolationpolicycreate',\n templateUrl: './isolationpolicycreate.html'\n})\n\nexport class IsolationPolicyCreateComponent implements OnInit {\n newPolicy:any;\n tenants:any[] = [];\n policyMode:string = 'isolation'\n\n constructor(private activatedRoute: ActivatedRoute,\n private router: Router,\n private ngZone: NgZone,\n private organizationsModel: OrganizationsModel,\n private policiesModel: PoliciesModel,\n private crudHelperService: CRUDHelperService) {\n\n var component = this;\n\n function setMode() {\n if (activatedRoute.routeConfig.path.includes('isolation')) {\n component.policyMode = 'isolation';\n } else {\n component.policyMode = 'bandwidth';\n }\n }\n\n function resetForm() {\n crudHelperService.stopLoader(component);\n component.newPolicy = {\n policyName: '',\n tenantName: ''\n };\n }\n\n setMode();\n\n resetForm();\n }\n\n ngOnInit() {\n var component = this;\n component.crudHelperService.startLoader(component);\n\n function getTenants(reload: boolean) {\n component.organizationsModel.get(reload)\n .then((result) => {\n component.tenants = result;\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n }, (error) => {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n });\n }\n\n getTenants(false);\n }\n\n returnToPolicies() {\n this.router.navigate(['../../list', {policyTab: PolicyTab.isolation}], { relativeTo: this.activatedRoute });\n }\n\n cancelCreating() {\n this.returnToPolicies();\n }\n\n createPolicy(validform: boolean) {\n var isolationPolicyCreateCtrl = this;\n if (validform) {\n isolationPolicyCreateCtrl.crudHelperService.startLoader(isolationPolicyCreateCtrl);\n isolationPolicyCreateCtrl.newPolicy.key =\n isolationPolicyCreateCtrl.policiesModel.generateKey(isolationPolicyCreateCtrl.newPolicy);\n isolationPolicyCreateCtrl.policiesModel.create(isolationPolicyCreateCtrl.newPolicy, undefined).then(function successCallback(result) {\n isolationPolicyCreateCtrl.crudHelperService.stopLoader(isolationPolicyCreateCtrl);\n isolationPolicyCreateCtrl.crudHelperService.showNotification(\"Isolation policy: Created\", result.key);\n isolationPolicyCreateCtrl.returnToPolicies();\n }, function errorCallback(result) {\n isolationPolicyCreateCtrl.crudHelperService.stopLoader(isolationPolicyCreateCtrl);\n isolationPolicyCreateCtrl.crudHelperService.showServerError(\"Isolation policy: Create failed\", result);\n });\n }\n }\n}\n" }, { "alpha_fraction": 0.6716049313545227, "alphanum_fraction": 0.6777777671813965, "avg_line_length": 27.964284896850586, "blob_id": "e7f9840cf121f2fac4346c7b97953afd847a3bf8", "content_id": "47b5f7e3442ebc064e04b499c53399360c20228e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 810, "license_type": "permissive", "max_line_length": 56, "num_lines": 28, "path": "/e2e-tests/menu/menupagespec.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 7/27/16.\n */\n\nvar MenuPage = require('./menupageobject');\n\ndescribe(\"Testing Menu Page\",function(){\n\n var menuPage = new MenuPage();\n\n beforeEach(function(){\n browser.get(\"#/m\");\n });\n\n it(\"Clicking on various menu items\",function(){\n testConfig.clickLink(menuPage.dashboard);\n testConfig.clickLink(menuPage.applicationGroup);\n testConfig.clickLink(menuPage.networkPolicies);\n testConfig.clickLink(menuPage.storagePolicies);\n testConfig.clickLink(menuPage.serviceLb);\n testConfig.clickLink(menuPage.networks);\n testConfig.clickLink(menuPage.volumes);\n testConfig.clickLink(menuPage.nodes);\n testConfig.clickLink(menuPage.organizations);\n testConfig.clickLink(menuPage.settings);\n });\n\n});" }, { "alpha_fraction": 0.5646970868110657, "alphanum_fraction": 0.5759162306785583, "avg_line_length": 30.738094329833984, "blob_id": "1c3c4cd83df1b5a4c2049e4ae6c5e142f10ab916", "content_id": "7aa005cec4bb4520a5f0745653ea6757bff77e69", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1337, "license_type": "permissive", "max_line_length": 88, "num_lines": 42, "path": "/app/components/graphobjects/node/visualizernode_test.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "'use strict';\n\ndescribe('visualizer node', function(){\n var nodeFactory;\n var node;\n beforeEach(function(){\n module('contiv.graph');\n inject( function($injector){\n nodeFactory = $injector.get('VisualizerNode');\n node = new nodeFactory.Node(1, 2, 'testId', 'testText', 5, 'p', 'a', 0, -1);\n });\n });\n \n it('Checking inital values', function(){\n expect(node.x).toBe(1);\n expect(node.y).toBe(2);\n expect(node.id).toBe('testId');\n expect(node.text).toBe('testText');\n expect(node.radius).toBe(5);\n expect(node.parent).toBe('p');\n expect(node.ancestors).toBe('a');\n expect(node.xStart).toBe(0);\n expect(node.yStart).toBe(-1);\n expect(node.graph).toBe(null);\n expect(node.initialized).toBe(false);\n });\n\n it('Checking initializing and setRadius', function() {\n node.initialize(\"testGraph\");\n expect(node.graph).toBe(\"testGraph\");\n expect(node.initialized).toBe(true);\n\n //calling initialize again shouldn't change anything\n node.initialize(\"newGraph\");\n expect(node.graph).toBe(\"testGraph\");\n expect(node.initialized).toBe(true);\n\n expect(node.radius).toBe(5);\n node.setRadius(10);\n expect(node.radius).toBe(10);\n });\n});\n\n\n\n\n" }, { "alpha_fraction": 0.6134128570556641, "alphanum_fraction": 0.6145177483558655, "avg_line_length": 49.56983184814453, "blob_id": "af55d0491105c88b2cbd6f0a953cbcb8562cb13f", "content_id": "ffdbf36b7e1d8e04409171054a17cedd37af74fe", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 9051, "license_type": "permissive", "max_line_length": 103, "num_lines": 179, "path": "/gulpfile.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "var gulp = require('gulp');\nvar babel = require('gulp-babel');\nvar concat = require('gulp-concat');\nvar uglify = require('gulp-uglify');\nvar eventStream = require('event-stream');\nvar sourcemaps = require('gulp-sourcemaps');\n\n\ngulp.task('build', function () {\n var s1 = gulp.src(['app/components/**/module.js',//First include files that register shared modules\n 'app/**/module.js',//Include files that register modules for various tabs\n 'app/app.js',\n 'app/**/*.js',\n '!app/bundle.js',//Exclude generated bundle.js\n '!app/**/*test.js',//Exclude test files\n '!app/**/*.md', //Exclude .md files\n '!app/bower_components/**/*.js',\n '!app/components/graphobjects/**/*.js',\n '!app/main.browser.js',//Exclude files loaded by webpack\n '!app/app.module.js',//Exclude files loaded by webpack\n '!app/upgradeadapter.js',\n '!app/polyfills.browser.js',//Exclude files loaded by webpack\n '!app/vendor.browser.js',//Exclude files loaded by webpack\n '!app/polyfills.bundle.js',//Exclude bundle generated by webpack\n '!app/vendor.bundle.js',//Exclude bundle generated by webpack\n '!app/main.bundle.js',//Exclude bundle generated by webpack\n '!app/components/models/*model.js',\n '!app/components/models/basecollection.js',\n '!app/components/models/collection.js',\n '!app/components/utils/*service.js',\n '!app/components/directives/directives.module.js',\n '!app/components/directives/errormessagedirective.js',\n '!app/components/pipes/*.js',\n '!app/dashboard/dashboardctrl.js',\n '!app/network_policies/networkpolicies.module.js',\n '!app/network_policies/networkpoliciestabsctrl.js',\n '!app/network_policies/isolationpolicylistctrl.js',\n '!app/network_policies/bandwidthpolicylistctrl.js',\n '!app/network_policies/isolationpolicycreatectrl.js',\n '!app/network_policies/isolationpolicydetailsctrl.js',\n '!app/network_policies/bandwidthpolicycreatectrl.js',\n '!app/network_policies/bandwidthpolicydetailsctrl.js',\n '!app/applicationgroups/applicationgroups.module.js',\n '!app/applicationgroups/applicationgroupcreatectrl.js',\n '!app/applicationgroups/applicationgroupdetailsctrl.js',\n '!app/applicationgroups/isolationpolicydirective.js',\n '!app/applicationgroups/bandwidthpolicydirective.js',\n '!app/settings/settings.module.js',\n '!app/settings/networksettingctrl.js',\n '!app/components/directives/tabledirective.js',\n '!app/components/directives/accordiondirective.js',\n '!app/networks/networklistctrl.js',\n '!app/networks/network.module.js',\n '!app/applicationgroups/applicationgrouplistctrl.js',\n '!app/networks/networkstatsctrl.js',\n '!app/service_lbs/servicelb.module.js',\n '!app/service_lbs/servicelblistctrl.js',\n '!app/service_lbs/servicelbstatsctrl.js',\n '!app/organizations/organization.module.js',\n '!app/organizations/organizationlistctrl.js',\n '!app/networks/networkdetailsctrl.js',\n '!app/networks/networkinfoctrl.js',\n '!app/components/directives/collapsibledirective.js',\n '!app/components/directives/namevaluedirective.js',\n '!app/networks/networkcreatectrl.js',\n '!app/service_lbs/servicelbportsdirective.js',\n '!app/service_lbs/servicelbcreatectrl.js',\n '!app/service_lbs/servicelbdetailsctrl.js',\n '!app/service_lbs/servicelbinfoctrl.js',\n '!app/settings/clustersettingctrl.js',\n '!app/login/loginctrl.js',\n '!app/organizations/organizationcreatectrl.js',\n '!app/organizations/organizationdetailsctrl.js'\n ])//Exclude vendor libraries\n .pipe(sourcemaps.init());\n //ES6 code\n var s2 = gulp.src(['app/components/graphobjects/**/module.js',\n 'app/components/graphobjects/**/*.js',\n '!app/components/graphobjects/**/*test.js',\n '!app/components/graphobjects/**/*.md'\n ])//Exclude vendor libraries\n .pipe(sourcemaps.init())\n .pipe(babel());\n\n //merge the two streams\n eventStream.merge(s1, s2)\n .pipe(concat('app/bundle.js'))\n .pipe(uglify())\n .pipe(sourcemaps.write())\n .pipe(gulp.dest('.'))\n});\n\ngulp.task('dev-build', function () {\n var s1 = gulp.src(['app/components/**/module.js',//First include files that register shared modules\n 'app/**/module.js',//Include files that register modules for various tabs\n 'app/app.js',\n 'app/**/*.js',\n '!app/bundle.js',//Exclude generated bundle.js\n '!app/**/*test.js',//Exclude test files\n '!app/**/*.md', //Exclude .md files\n '!app/bower_components/**/*.js',\n '!app/components/graphobjects/**/*.js',\n '!app/main.browser.js',//Exclude files loaded by webpack\n '!app/app.module.js',//Exclude files loaded by webpack\n '!app/upgradeadapter.js',\n '!app/polyfills.browser.js',//Exclude files loaded by webpack\n '!app/vendor.browser.js',//Exclude files loaded by webpack\n '!app/polyfills.bundle.js',//Exclude bundle generated by webpack\n '!app/vendor.bundle.js',//Exclude bundle generated by webpack\n '!app/main.bundle.js',//Exclude bundle generated by webpack\n '!app/components/models/*model.js',\n '!app/components/models/basecollection.js',\n '!app/components/models/collection.js',\n '!app/components/utils/*service.js',\n '!app/components/directives/directives.module.js',\n '!app/components/directives/errormessagedirective.js',\n '!app/components/pipes/*.js',\n '!app/dashboard/dashboardctrl.js',\n '!app/network_policies/networkpolicies.module.js',\n '!app/network_policies/networkpoliciestabsctrl.js',\n '!app/network_policies/isolationpolicylistctrl.js',\n '!app/network_policies/bandwidthpolicylistctrl.js',\n '!app/network_policies/isolationpolicycreatectrl.js',\n '!app/network_policies/isolationpolicydetailsctrl.js',\n '!app/network_policies/bandwidthpolicycreatectrl.js',\n '!app/network_policies/bandwidthpolicydetailsctrl.js',\n '!app/applicationgroups/applicationgroups.module.js',\n '!app/applicationgroups/applicationgroupcreatectrl.js',\n '!app/applicationgroups/applicationgroupdetailsctrl.js',\n '!app/applicationgroups/isolationpolicydirective.js',\n '!app/applicationgroups/bandwidthpolicydirective.js',\n '!app/settings/settings.module.js',\n '!app/settings/networksettingctrl.js',\n '!app/components/directives/tabledirective.js',\n '!app/components/directives/accordiondirective.js',\n '!app/networks/networklistctrl.js',\n '!app/networks/network.module.js',\n '!app/applicationgroups/applicationgrouplistctrl.js',\n '!app/networks/networkstatsctrl.js',\n '!app/service_lbs/servicelb.module.js',\n '!app/service_lbs/servicelblistctrl.js',\n '!app/service_lbs/servicelbstatsctrl.js',\n '!app/organizations/organization.module.js',\n '!app/organizations/organizationlistctrl.js',\n '!app/networks/networkdetailsctrl.js',\n '!app/networks/networkinfoctrl.js',\n '!app/components/directives/collapsibledirective.js',\n '!app/components/directives/namevaluedirective.js',\n '!app/networks/networkcreatectrl.js',\n '!app/service_lbs/servicelbportsdirective.js',\n '!app/service_lbs/servicelbcreatectrl.js',\n '!app/service_lbs/servicelbdetailsctrl.js',\n '!app/service_lbs/servicelbinfoctrl.js',\n '!app/settings/clustersettingctrl.js',\n '!app/login/loginctrl.js',\n '!app/organizations/organizationcreatectrl.js',\n '!app/organizations/organizationdetailsctrl.js'\n ])//Exclude vendor libraries\n .pipe(sourcemaps.init());\n //ES6 code\n var s2 = gulp.src(['app/components/graphobjects/**/module.js',\n 'app/components/graphobjects/**/*.js',\n '!app/components/graphobjects/**/*test.js',\n '!app/components/graphobjects/**/*.md'\n ])//Exclude vendor libraries\n .pipe(sourcemaps.init())\n .pipe(babel());\n\n //merge the two streams\n eventStream.merge(s1, s2)\n .pipe(concat('app/bundle.js'))\n .pipe(sourcemaps.write())\n .pipe(gulp.dest('.'));\n});\n\n\ngulp.task('watch', ['build'], function () {\n gulp.watch('app/**/*.js', ['build'])\n});" }, { "alpha_fraction": 0.6514806151390076, "alphanum_fraction": 0.6628701686859131, "avg_line_length": 19, "blob_id": "b1a69e793181250bc3a014597e545b91f89883c4", "content_id": "24a4397556f6c4546e105710d3c9399e2ec8d029", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 439, "license_type": "permissive", "max_line_length": 64, "num_lines": 22, "path": "/app/login/unauthorized.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 11/6/16.\n */\n\n\nimport {Component, OnInit, OnDestroy} from \"@angular/core\";\ndeclare var jQuery:any;\n@Component({\n selector: 'unauthorized',\n templateUrl: './unauthorized.html'\n\n})\n\nexport class UnauthorizedComponent implements OnInit, OnDestroy{\n ngOnInit(){\n jQuery(\"body\").addClass(\"logoutbackground\");\n }\n\n ngOnDestroy(){\n jQuery(\"body\").removeClass(\"logoutbackground\");\n }\n}" }, { "alpha_fraction": 0.577434778213501, "alphanum_fraction": 0.5800957679748535, "avg_line_length": 31.39655113220215, "blob_id": "f8c1d7ffb18df423ae8429f09f2f9b1387fbbdd4", "content_id": "225427da94dfac90ca784b0b97b504ea8a45b366", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1879, "license_type": "permissive", "max_line_length": 81, "num_lines": 58, "path": "/app/settings/users/userlist.component.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "import { Component, OnInit, OnDestroy, Inject, NgZone } from \"@angular/core\";\nimport { ActivatedRoute, Router } from \"@angular/router\";\nimport { CRUDHelperService } from \"../../components/utils/crudhelperservice\";\nimport { Observable, Subscription } from \"rxjs\";\nimport { UsersModel } from \"../../components/models/usersmodel\";\nimport {User} from \"./usercreate.component\";\n\n\n@Component({\n selector: 'userlist',\n templateUrl: './userlist.html'\n})\n\nexport class UserListComponent implements OnInit, OnDestroy{\n\n private refresh: Subscription;\n public users: Array<User>;\n constructor(private activatedRoute: ActivatedRoute,\n private router: Router,\n private usersModel: UsersModel,\n private crudHelperService: CRUDHelperService,\n private ngZone: NgZone) {\n this.refresh = Observable.interval(5000).subscribe(() => {\n this.getUsers(true);\n })\n }\n\n ngOnInit(){\n this.crudHelperService.startLoader(this);\n this.getUsers(false);\n // update breadcrumbs\n $('.crumb2').html('User Management')\n }\n\n getUsers(reload: boolean){\n var component = this;\n this.usersModel.get(reload)\n .then(function successCallback(result){\n component['users'] = result;\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n },\n function errorCallback(result){\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n });\n }\n\n create(){\n this.router.navigate(['../create'], { relativeTo: this.activatedRoute });\n }\n\n ngOnDestroy(){\n this.refresh.unsubscribe();\n }\n}\n" }, { "alpha_fraction": 0.6364829540252686, "alphanum_fraction": 0.6482939720153809, "avg_line_length": 33.6363639831543, "blob_id": "99a64113ce894b5534b7b039d59c39f18c22d942", "content_id": "ed4db178be1c9d1706504de266559b2b59c6bbb1", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 762, "license_type": "permissive", "max_line_length": 91, "num_lines": 22, "path": "/e2e-tests/cleanup.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 8/19/16.\n */\n\ndescribe(\"Clean Up\", function(){\n it(\"Remove Network\", function(){\n testConfig.removeObject(\"#/m/networks/list\", testConfig.networks.name);\n testConfig.waitForPageLoad(0);\n });\n it(\"Remove Copied Volume\", function(){\n testConfig.removeObject(\"#/m/volumes/list\", testConfig.volumes.newvolume);\n testConfig.waitForPageLoad(0);\n });\n it(\"Remove Volume\", function(){\n testConfig.removeObject(\"#/m/volumes/list\", testConfig.volumes.name);\n testConfig.waitForPageLoad(0);\n });\n it(\"Remove Storage Policy\", function(){\n testConfig.removeObject(\"#/m/storagepolicies/list\", testConfig.storagePolicy.name);\n testConfig.waitForPageLoad(0);\n });\n});\n" }, { "alpha_fraction": 0.6171616911888123, "alphanum_fraction": 0.6278877854347229, "avg_line_length": 25.369565963745117, "blob_id": "4fe18e58326900e053a3020851ab4782691e6699", "content_id": "bdebaaf01b04d115459a2ebd4a338cbcd3ececdd", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1212, "license_type": "permissive", "max_line_length": 83, "num_lines": 46, "path": "/app/components/utils/crudhelperservice.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 4/29/16.\n */\nimport { Injectable } from '@angular/core';\nimport {NotificationType} from \"../directives/notification\";\ndeclare var jQuery:any;\n\n@Injectable()\nexport class CRUDHelperService {\n\n public message:string = '';\n public item:string = '';\n public displayNotify:boolean;\n public notificationType: NotificationType;\n\n constructor(){\n }\n\n startLoader(controller) {\n controller.showLoader = true;\n }\n\n stopLoader(controller) {\n controller.showLoader = false;\n }\n\n showNotification(message: string, item: string, notifyType?: NotificationType){\n this.message = message;\n this.item = item;\n this.notificationType = notifyType;\n this.displayNotify = true;\n }\n\n showServerError(message, error): void{\n var status = error.status;\n var operationstate = ''\n if (status=='401' || status=='402'){\n operationstate = 'Unauthorized Operation';\n }\n if(error.text().length > 0)\n operationstate = error.text();\n else\n operationstate = error.toString();\n this.showNotification(message, operationstate, NotificationType.alert);\n }\n}" }, { "alpha_fraction": 0.5412728190422058, "alphanum_fraction": 0.5431631803512573, "avg_line_length": 35.906978607177734, "blob_id": "19d6e37de8646cfea91457b7bb18975585a6d9b3", "content_id": "2d4b7d0d703573f6cf6e7b112598938db95a8f26", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1587, "license_type": "permissive", "max_line_length": 110, "num_lines": 43, "path": "/app/components/models/networksmodel.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { Http } from '@angular/http';\nimport { Collection } from \"./collection\";\nimport {isUndefined} from \"util\";\nimport { ContivGlobals } from \"./contivglobals\";\nimport {ApiService} from \"../utils/apiservice\";\n\n@Injectable()\nexport class NetworksModel extends Collection {\n constructor(http: Http, apiService: ApiService) {\n super(http, ContivGlobals.NETWORKS_ENDPOINT, apiService);\n }\n\n getInspectByKey(key:string, url: string, reload: boolean): Promise<any>{\n return super.getInspectByKey(key,url,reload)\n .then((result) => {\n if(!isUndefined(result['Oper'].endpoints)){\n var processedEndpoints = [];\n var endpoints = result['Oper'].endpoints;\n for(var i=0; i<endpoints.length; i++){\n if(isUndefined(endpoints[i].containerID)){\n endpoints[i]['containerID'] = endpoints[i]['endpointID'];\n endpoints[i]['containerName'] = endpoints[i]['endpointID'].toString().substr(0,6);\n }\n }\n result['Oper'].endpoints = endpoints;\n }\n return result;\n });\n }\n\n get(reload: boolean):Promise<any>{\n var collection = this;\n if(collection.cudOperationFlag){\n return new Promise(function(resolve, reject){\n resolve(collection.models)\n })\n }\n else{\n return super.get(reload);\n }\n }\n}\n" }, { "alpha_fraction": 0.614973247051239, "alphanum_fraction": 0.6283422708511353, "avg_line_length": 17.75, "blob_id": "c43e848099b109d108aa297a931e627bbf2a517f", "content_id": "31d860a26789f9da21db48d1764ee88da4f7afb5", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 374, "license_type": "permissive", "max_line_length": 47, "num_lines": 20, "path": "/app/components/directives/collapsibledirective.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 6/2/16.\n */\n\nimport {Component, Input} from \"@angular/core\";\n\n@Component({\n selector:'ctv-collapsible',\n templateUrl: './collapsible.html'\n})\n\nexport class CtvCollapsibleComponent{\n @Input('title') title: string;\n @Input('collapsed') collapsed: boolean;\n\n constructor() {\n this.title='';\n this.collapsed=true;\n }\n}" }, { "alpha_fraction": 0.6832535862922668, "alphanum_fraction": 0.6889952421188354, "avg_line_length": 28.05555534362793, "blob_id": "60aa6a4d1f9a65ddf126cda905488a305dfc83d6", "content_id": "686955a8781b7766f25ae069430ac8fba1f1e98a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1045, "license_type": "permissive", "max_line_length": 81, "num_lines": 36, "path": "/app/settings/authorization/authorization.module.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 12/13/16.\n */\nimport { NgModule } from '@angular/core';\nimport { FormsModule } from \"@angular/forms\";\nimport { CommonModule } from \"@angular/common\";\nimport { RouterModule } from \"@angular/router\";\nimport { DirectivesModule } from \"../../components/directives/directives.module\";\nimport { AuthorizationListComponent } from \"./authorizationlist\";\nimport { AuthorizationDetailsComponent } from \"./authorizationdetails\";\nimport { AuthorizationCreateComponent } from \"./authorizationcreate\";\n\n@NgModule({\n imports: [\n FormsModule,\n CommonModule,\n RouterModule,\n DirectivesModule\n ],\n declarations: [\n AuthorizationListComponent,\n AuthorizationDetailsComponent,\n AuthorizationCreateComponent\n ],\n exports: [\n AuthorizationListComponent,\n AuthorizationDetailsComponent,\n AuthorizationCreateComponent,\n DirectivesModule,\n FormsModule,\n CommonModule,\n RouterModule\n ]\n})\n\nexport class AuthorizationModule {}" }, { "alpha_fraction": 0.618043065071106, "alphanum_fraction": 0.6229802370071411, "avg_line_length": 31.735294342041016, "blob_id": "d740a6363935e9fba55519ca18d3c4e0186ff182", "content_id": "257b1ca04a0cc59d2b16551b5383c3d72e91b744", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2228, "license_type": "permissive", "max_line_length": 90, "num_lines": 68, "path": "/app/service_lbs/servicelblistctrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 10/14/16.\n */\n\nimport {Component, OnInit, OnDestroy, Inject, NgZone} from \"@angular/core\";\nimport {CRUDHelperService} from \"../components/utils/crudhelperservice\";\nimport {Observable, Subscription} from \"rxjs\";\nimport {ServicelbsModel} from \"../components/models/servicelbsmodel\";\nimport {Router, ActivatedRoute} from \"@angular/router\";\n\n\n@Component({\n selector: 'servicelbList',\n templateUrl: './servicelblist.html'\n})\n\nexport class ServicelbListComponent implements OnInit, OnDestroy{\n private servicelbsModel:ServicelbsModel;\n private crudHelperService: CRUDHelperService;\n public servicelbListCtrl: any;\n private refresh: Subscription;\n public searchResultCount:number;\n public count:number;\n\n constructor(private router: Router,\n private route: ActivatedRoute,\n servicelbsModel: ServicelbsModel,\n crudHelperService: CRUDHelperService,\n private ngZone: NgZone){\n this.servicelbsModel = servicelbsModel;\n this.crudHelperService = crudHelperService;\n this.servicelbListCtrl = this;\n this.count = 0;\n this['showLoader']=true;\n this.refresh=Observable.interval(5000).subscribe(() => {\n this.getServicelbs(true);\n })\n }\n\n ngOnInit(){\n this.crudHelperService.startLoader(this);\n this.getServicelbs(false);\n }\n\n getServicelbs(reload: boolean){\n var servicelbListCtrl = this;\n this.servicelbsModel.get(reload)\n .then(function successCallback(result){\n servicelbListCtrl['servicelbs'] = result;\n servicelbListCtrl.ngZone.run(() => {\n servicelbListCtrl.crudHelperService.stopLoader(servicelbListCtrl);\n })\n },\n function errorCallback(result){\n servicelbListCtrl.ngZone.run(() => {\n servicelbListCtrl.crudHelperService.stopLoader(servicelbListCtrl);\n })\n })\n }\n\n create(){\n this.router.navigate(['../create'],{relativeTo: this.route});\n }\n\n ngOnDestroy(){\n this.refresh.unsubscribe();\n }\n}\n\n\n" }, { "alpha_fraction": 0.7565482258796692, "alphanum_fraction": 0.7572250366210938, "avg_line_length": 55.7423095703125, "blob_id": "4de412214063d8af3f0acc3814422b35bfd53e84", "content_id": "4d8467c7e8392fd8326935fa6d87ed66f5e3d820", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 14775, "license_type": "permissive", "max_line_length": 834, "num_lines": 260, "path": "/DESIGN.md", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "#Graph Design\n\n##Developers - Table of contents\n=================\n\n * [Overview](#overview)\n * [Data Source Objects](#data-source-objects)\n * [Data Source](#data-source-datasourcejs)\n * [Visualizer Data Source](#visualizer-data-source-visualizerdatasourcejs)\n * [Node Objects](#node-objects)\n * [Node](#node-nodejs)\n * [Visualizer Node](#visualizer-node-visualizernodejs)\n * [Link Objects](#link-objects)\n * [Link](#link-linkjs)\n * [Visualizer Link](#visualizer-link-visualizerlinkjs)\n * [Graph Objects](#graph-objects)\n * [Graph](#graph-graphjs)\n * [Visualizer Graph](#visualizer-graph-visualizergraphjs)\n * [Policy Objects](#policy-objects)\n * [Policy](#policy-policyjs)\n * [Path Change View Policy](#path-change-view-policy-pathchangeviewpolicyjs)\n * [QTip Policy](#qtip-policy-qtippolicyjs)\n * [Save State Policy](#save-state-policy-savestatepolicyjs)\n * [Node Selection Policy](#node-selection-policy-nodeselectionpolicyjs)\n * [Split Join Node Policy](#split-join-node-policy-splitjoinnodepolicyjs)\n * [Split Join View Policy](#split-join-view-policy-splitjoinviewpolicyjs)\n\n \n###Overview:\n=============\nThe graph is composed of five components. Each of these components has a base class, and are meant to be extended to create tailored versions as needed.\n* Data source Object\n * Takes in node and link data from the server, and provides methods for converting and manipulating the data for the graph object.\n* Node Object\n * The object that holds data that is paired to the svg circles drawn.\n* Link Object:\n * The object that holds data for each connection, and is paired to the svg paths drawn.\n* Graph Object:\n * The graph object that controls the svg, nodes, links, and responds to user interactions.\n* Policy Object:\n * Determines how user interactions and events affect the graph. Used to isolate features from eachother.\n * Multiple policies can be installed at the same time.\n * Has a handler for all the standard mouse interactions, and these handlers will fire for the object it is installed on when the event occurs.\n\nTo use the graph object, include the contiv.graph module as a dependency for your module. Then you can inject which ever objects you need. Node objects, Link objects, and Graph objects all support policy installation and uninstallation. Graph objects support installing a policy for interaction with the graph, as well as default policies for nodes and links. When an event occurs, if the Node or Link in the event has its own policies installed, it will call the event handler for all the node or link's installed policies. If it doesn't have any of its own policies, it will call the event handler for the graph's default node policies or default path policies. This allows for certain nodes or links to have specialized policies if needed while still having a convenient way to install a policy on all nodes or on all links.\n\n###Data Source Objects\n=======================\nTakes in node and link data from the server, and provides methods for converting and manipulating the data for the graph object.\n\nTo write your own DataSource object, create a new factory that uses the DataSource you want to inherit as a dependency, and extend its DataSource class. Return the class object with DataSource as key. \n\n####Data Source (datasource.js)\nThis is the base class for the Data Source Object. The processNodeData and processLinkData methods convert the data into Node and Link Objects, which are expected by the Graph Object.\n\nIt's constructor has the following expectations:\n* Nodes:\n * Sample JSON - {id: node_id, text: node_text_to_display}\n* Links:\n * Sample JSON - {source: sourceNodeId, target: targetNodeId}\n\n####Visualizer Data Source (visualizerdatasource.js)\nThis is the Data Source Object used to handle data from the Contiv-UI backend, and to manipulate it specifically for the App Connectivity Graph tab. \n\nIt's constructor has the following expectations:\n* Nodes:\n * Sample JSON - {id: node_id, text: node_text_to_display}\n* Links:\n * Sample JSON - {source: sourceNodeId, target: targetNodeId, weight: linkWeight}\n* children_struct:\n * JSON object mapping node Id to an array of its children's Ids.\n * In the context of Contiv, a key would be a service id, and its corresponding value would be an array of container Ids for the containers that are part of the service.\n * Expected to have a topLevel attribute, that corresponds to an array of node Ids that have no parent.\n * If a Node is meant to be able to have children, but currently doesn't have any, it is expected that the children_struct still has the node id as key, and that its corresponding value is an empty list.\n \t* In the context of Contiv, this would be a service without any containers.\n* ancestors_struct:\n * JSON object mapping node Id to an array of its parent's Id, in increasing order of ancestry\n \t* Ex. ancestor_struct[node1] = ['parent_id', 'grandparent_id']\n* labels:\n * JSON mapping node Id to a JSON of its label pairings.\n * In the context of Contiv, it would map a container Id to its labels.\n* selectors:\n * JSON mapping node Id to a JSON of its service selectors.\n * In the context of Contiv, it would map a serviceId to its selectors.\n\nIt also contains method to aggregate flow between groups of containers, which allows for showing traffic between services, instead of containers.\n\n###Node Objects\n=======================\nBasic object that is used by the Graph Object. Each node will correspond to one of the svg circles. If any policies are installed on the node, the graph will call their event handlers instead of the graph's default node policies. The initialization method of the node will be called when it is added to the graph.\n\nTo write your own Node object, create a new factory that uses the node you want to inherit as a dependency, and extend its node class. Return the class object with Node as key.\n\n####Node (node.js)\nThis is the base class for the Node Object.\n\nIt's constructor has the following expectations:\n* x:\n * x coordinate of the center of the circle. Must have a value by the time it is drawn by D3.\n* y:\n * y coordinate of the center of the circle. Must have a value by the time it is drawn by D3.\n* id:\n * Unique Identifier for the node.\n* text:\n * text to be displayed on the node.\n* radius:\n * radius of the circle. Must have a value by the time it is drawn by D3.\n\n####Visualizer Node (visualizernode.js)\nThis is the Node Object that is designed for the App Connectivity Graph tab. Supports policies.\n\nIt's constructor has the following expectations:\n* x:\n * x coordinate of the center of the circle. Must have a value by the time it is drawn by D3.\n* y:\n * y coordinate of the center of the circle. Must have a value by the time it is drawn by D3.\n* id:\n * Unique Identifier for the node.\n* text:\n * text to be displayed on the node.\n* radius:\n * radius of the circle. Must have a value by the time it is drawn by D3.\n* parent:\n * Id of it's parent container, or null/undefined if there is none.\n* ancestors:\n * Array of its ancestors Ids, in order of ancestry.\n * Ex node.ancestors = ['parent_id', 'grandparent_id']\n* xStart:\n * Starting x position of the node. Will be animated to its x coordinate when it is drawn by the graph.\n* yStart:\n * Starting y position of the node. Will be animated to its y coordinate when it is drawn by the graph.\n\n###Link Objects\n=======================\nBasic object that is used by the Graph Object. Each link will correspond to one of the svg paths. If any policies are installed on the link, the graph will call their event handlers instead of the graph's default path policies. The initialization method of the link will be called when it is added to the graph.\n\nTo write your own Link object, create a new factory that uses the link you want to inherit as a dependency, and extend its link class. Return the class object with Link as key.\n\n####Link (link.js)\nThis is the base class for the Link Object.\n\nIt's constructor has the following expectations:\n* sourceNode:\n * Node that is the source of the link\n* targetNode:\n * Node that is the target of the link\n\n####Visualizer Link (visualizerlink.js)\nThis is the Link Object that is designed for the App Connectivity Graph tab. Supports policies.\n\nIt's constructor has the following expectations:\n* sourceNode:\n * Node that is the source of the link.\n* targetNode:\n * Node that is the target of the link.\n* weight:\n * Weight of the link.\n\n###Graph Objects\n=======================\nThe graph object controls drawing of the Nodes and Links, as well as user interaction with the graph. It is installed onto an svg element. Any nodes in its nodes attributes and any links in its links attribute will be drawn the next time the graph's updateGraph method is called. \n\nThe graph can only have one Svg policy, one D3 Drag policy, and one D3 zoom policy installed at a time. The graph has a default node policies and a default path policies, both which support installing multiple policies. When an event happens, if the node or link has no policies installed on it, it will trigger the event handler to the default node policies or to the default path policies.\n\nThe destroy function will remove any window bindings added by the graph, as well as call the destroy method of all policies installed.\n\n####Graph (graph.js)\nThe basic graph object.\n\nIt's constructor has the following expectations:\n* svg:\n * The svg that will contain the graph.\n* nodes:\n * Array of Node objects to draw.\n* links\n * Array of Link objects to draw.\n\n####Visualizer Graph (visualizergraph.js)\nThe graph object used by the App Connectivity Graph tab.\n\nIt's constructor has the following expectations:\n* svg:\n * The svg that will contain the graph.\n* nodes:\n * Array of Node objects to draw.\n* links\n * Array of Link objects to draw.\n* dataSource\n * Data Source object that is serving data to the graph.\n\n###Policy Objects\n=======================\nPolicies are used to isolate features for a graph. Policies can be installed on nodes, links, or the graph. Each policy has interaction handlers that will be called by the graph if installed. Policies can also modify graph functions (see QTipPolicy for an example). Multiple policies can be installed for a node or link. The destroy method will trigger when the graph is destroyed, or if the policy is uninstalled.\n\nFor using policies, you only need to inject PolicyService, which will contain all the policy objects.\n\nTo write your own policy, create a new factory that uses the policy you want to inherit as a dependency, and extend its policy. Return the class object with Policy as key, and add the policy to the PolicyService factory. \n\nFor saving state or consts for the policy, create a namespace in graph.state and graph.consts.\n```\ngraph.state.myPolicy = {};\ngraph.consts.myPolicy = {};\n```\n\n####Policy (policy.js)\nBase class for the Policy object. Has all the mouse handlers.\n\nIt's constructor has the following expectations:\n* policyName:\n * The name for the policy. Policy names should be unique.\n\n####Path Change View Policy (pathchangeviewpolicy.js)\nThis policy is used to change the angular state when paths are clicked. Generates the variables expected by visualizationEdgeCtrl, and then changes state.\n\nIt's constructor has the following expectations:\n* $state:\n * The angular state parameter. Used for changing states.\n\n\n####QTip Policy (qtippolicy.js)\nThis policy adds tooltip functionality to the nodes and paths. It utilizes the qTip library. \n\nIn order to install qTip onto the svg elements, theis policy must modify the updateNewNodes and updateNewPaths methods of the graph. By saving the original method of the graph, and replacing it with a method that contains both the original, and the function you want to call.\n```\nvar graphUpdateNewNodes = graph.updateNewNodes;\ngraph.updateNewNodes = function(newNodes) {\n graphUpdateNewNodes.call(graph, newNodes);\n thisPolicy.updateNewNodes(newNodes);\n}\n\nvar graphUpdateNewPaths = graph.updateNewPaths;\ngraph.updateNewPaths = function(newPaths) {\n graphUpdateNewPaths.call(graph, newPaths);\n thisPolicy.updateNewPaths(newPaths);\n}\n```\n\n####Save State Policy (savestatepolicy.js)\nThis policy allows for saving variables between angular states. Since angular services are only instantiated once, by passing in a variable of the service into this policy, any variables saved onto it will be saved even when the graph is destroyed. This policy modifies the graph's destroy function to pass the service variable as an argument for policies to save variables. When the graph is created again, if a load method is defined for a policy, it will call it with the service variable passed in.\n\nIt's constructor has the following expectations:\n* savedState:\n * An angular service's variable.\n\n####Node Selection Policy (nodeselectionpolicy.js)\nThis policy creates a selection method for selecting nodes. It also allows for selecting and moving multiple nodes when using the ctrl key.\n\n####Split Join Node Policy (splitjoinnodepolicy.js)\nThis policy allows for nodes to split into its children nodes, and for nodes to be joined together back into their parent node. Has minimal logic for placing the new nodes. Supports splitting and joining multiple nodes at once.\n\nInherits from Node Selection Policy.\n\n####Split Join View Policy (splitjoinviewpolicy.js)\nThis policy controls most of the view logic of the App Connectivity Graph tab. The logic is controlled by focus groups. When there is no focus groups, it will display the top level of children_struct. When a node is broken into its children, the Id of the node being split will be added to the focus group. Any nodes that have connections to the split node will remain in view on the bottom half of the screen, while the children will be placed on the top half. If any node is split on the top half, it will become the focus group. If a bottom half node is split, it will become a second focus group, and the bottom half view will be replaced with the newly split node's children. Joining a node will replace its respective focus group with the grandparent of the node being joined, or will remove it as a focus group if none exists. \n\nThis policy modifies the d3 force simulation methods of the graph to control the node placements, as well as to animate view changes between focus groups. Once a layout is generated, it is saved and will be reloaded if that specific focus group setup is revisited.\n\nThis policy also has a handle for installing an HTML element to function as a back button, as well as a handler for installing an HTML element for setting the title, which is determined by the focus groups.\n\nInherits from Split Join Node Policy.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.4843162000179291, "alphanum_fraction": 0.4889167845249176, "avg_line_length": 34.04411697387695, "blob_id": "629969389d9b5c5dc4e5081e5a3da9235b72e5a1", "content_id": "fd373c647eca288dd321781fc2daff083a93bf0a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2391, "license_type": "permissive", "max_line_length": 136, "num_lines": 68, "path": "/app/components/graphobjects/node/visualizernode.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * The node that is used specifically for the visualization tab.\n */\nangular.module('contiv.graph')\n .factory('VisualizerNode', ['Node', function (Node) {\n\t\tclass VisualizerNode extends Node.Node {\n\t\t\t/**\n\t\t\t * Constructs the object.\n\t\t\t *\n\t\t\t * @param {number} x \tx location\n\t\t\t * @param {number} y \ty location\n\t\t\t * @param {string} id \tThe identifier\n\t\t\t * @param {string} text \tThe text to display\n\t\t\t * @param {number} radius \tThe radius of the node\n\t\t\t * @param {string} parent The parent id\n\t\t\t * @param {Array} ancestors Array of ancestors Id\n\t\t\t * @param {number} xStart x loc to start animation\n\t\t\t * @param {number} yStart y loc to start animation\n\t\t\t */\n\t\t constructor(x, y, id, text, radius, parent, ancestors, \n\t\t \txStart, yStart) {\n\t\t super(x, y, id, text, radius);\n\t\t this.parent = parent;\n\t\t this.ancestors = ancestors;\n\t\t if (xStart == null) {\n\t\t \tthis.xStart = x;\n\t\t } else {\n\t\t \tthis.xStart = xStart;\n\t\t }\n\t\t if (yStart == null) {\n\t\t \tthis.yStart = y;\n\t\t } else {\n\t\t \tthis.yStart = yStart;\n\t\t }\n\t\t }\n\n\t\t\t/**\n\t\t\t * Called during the first update graph for a node\n\t\t\t *\n\t\t\t * @param {D3Object} d3node The d3 node\n\t\t\t * @param {Node} d The matching Node\n\t\t\t */\n\t\t\tnewNodeAttr(d3node, d) {\n\t\t\t\tvar thisGraph = this.graph;\n\t\t\t\tif (thisGraph.consts.containerClass != null &&\n\t\t\t\t\t\tthisGraph.dataSource.children_struct[d.id] == null) {\n\t\t\t\t\td3node.classed(thisGraph.consts.containerClass, true);\n\t\t\t\t}\n\t\t\t\td3node.transition(\"nodePositionTransition\")\n\t\t .duration(750)\n\t\t .attrTween(\"transform\", function(d) {\n\t\t if (d.xStart != null && d.yStart != null) {\n\t\t var xStart = d.xStart;\n\t\t var yStart = d.yStart;\n\t\t d.xStart = d.x;\n\t\t d.yStart = d.y;\n\t\t return d3.interpolateString(\"translate(\" + xStart + \",\" + yStart + \")\", \"translate(\" + d.x + \",\" + d.y + \")\");\n\t\t }\n\t\t return d3.interpolateString(\"translate(\" + d.x + \",\" + d.y + \")\", \"translate(\" + d.x + \",\" + d.y + \")\");\n\t\t });\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tNode: VisualizerNode\n\t\t}\n\n}]);\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5728380680084229, "alphanum_fraction": 0.5751596093177795, "avg_line_length": 30.345455169677734, "blob_id": "557b5f5efbff40417385fa2e8405689df9b68cee", "content_id": "a2070d3bf041d2436cf828bddc554946e5222adc", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1723, "license_type": "permissive", "max_line_length": 81, "num_lines": 55, "path": "/app/settings/nodes/nodelist.component.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "import { Component, OnInit, OnDestroy, Inject, NgZone } from \"@angular/core\";\nimport { ActivatedRoute, Router } from \"@angular/router\";\nimport { CRUDHelperService } from \"../../components/utils/crudhelperservice\";\nimport { Observable, Subscription } from \"rxjs\";\nimport { BgpsModel } from \"../../components/models/bgpsmodel\";\n\n\n@Component({\n selector: 'nodelist',\n templateUrl: './nodelist.html'\n})\n\nexport class NodeListComponent implements OnInit, OnDestroy{\n\n private refresh: Subscription;\n\n constructor(private activatedRoute: ActivatedRoute,\n private router: Router,\n private bgpsModel: BgpsModel,\n private crudHelperService: CRUDHelperService,\n private ngZone: NgZone) {\n this.refresh = Observable.interval(5000).subscribe(() => {\n this.getNodes(true);\n })\n }\n\n ngOnInit(){\n this.crudHelperService.startLoader(this);\n this.getNodes(false);\n }\n\n getNodes(reload: boolean){\n var component = this;\n this.bgpsModel.get(reload)\n .then(function successCallback(result){\n component['nodes'] = result;\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n },\n function errorCallback(result){\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n });\n }\n\n create(){\n this.router.navigate(['../create'], { relativeTo: this.activatedRoute });\n }\n\n ngOnDestroy(){\n this.refresh.unsubscribe();\n }\n}" }, { "alpha_fraction": 0.6061897277832031, "alphanum_fraction": 0.6153846383094788, "avg_line_length": 36.779659271240234, "blob_id": "fb86b4e4650362d641140c236a1b4f6efdb65fdc", "content_id": "2332bb7a66f7db8b88aac48065540dd28245e1dd", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4459, "license_type": "permissive", "max_line_length": 160, "num_lines": 118, "path": "/app/components/directives/notification.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 11/30/16.\n */\n\nimport {Component, DoCheck, OnInit} from \"@angular/core\";\nimport {CRUDHelperService} from \"../utils/crudhelperservice\";\nimport {isUndefined} from \"util\";\ndeclare var jQuery:any;\n\nexport enum NotificationType {\n confirm,\n alert,\n info\n}\n\n@Component({\n selector: 'notification',\n templateUrl: './notification.html',\n styleUrls: ['./notification.css']\n})\n\nexport class NotificationComponent implements DoCheck, OnInit{\n public NotificationType = NotificationType;\n public message: string = '';\n public item: string = '';\n private notifyId: number = 0;\n public notificationType: NotificationType;\n private notifyCounter: number = 0;\n constructor(private crudHelperService: CRUDHelperService){\n }\n\n ngOnInit(){\n jQuery('.notify').css(\n { right:30+'px',\n top: ((80/100)*window.innerHeight) + 'px'\n });\n jQuery('.notify').css({visibility: 'hidden'});\n window.onresize = function(){\n jQuery('.notify').css(\n { right:30+'px',\n top: ((80/100)*window.innerHeight) + 'px'\n });\n };\n this.notifyId = 0;\n }\n\n runAnimation(start: boolean){\n var self = this;\n var animation = {\n animation: 'fade up',\n duration: '600ms',\n onStart: function(){\n if(start)\n self.displayMessage();\n }\n };\n jQuery('.notify').transition(animation);\n }\n\n displayMessage(){\n this.message = this.crudHelperService.message;\n this.item = this.crudHelperService.item;\n this.notificationType = this.crudHelperService.notificationType;\n if(isUndefined(this.notificationType))\n this.notificationType = NotificationType.confirm;\n }\n\n /*\n Since notification is part of the Menu component. The ngDoCheck() block runs every time the angular\n checks for changes in the Document tree.\n CrudhelperService is the service using which all child components of menu communicate with the\n notification component.\n this.crudHelperService.displayNotify gets set to true when this.crudHelperService.showNotification is called.\n When its true : -\n a) if there is any earlier notification which is getting displayed then the notifyId would be positive integer.\n In this case I will be closing the current notification by running this.runAnimation(false), The flag is false\n so while closing the notification I dont change the message inside the Notification element.\n b) if there is no earlier notification I execute runAnimation() with flag true which swaps the message inside the notification element on\n start of the animation.\n c) The notification counter for the first time would be 1. This id is passed to notifyTimer which sets up a setTimeout.\n The setTimeout only hides the notification with matching timerId and notifyId. If there is a new notification\n before the previous setTimeout has closed the previous notification, Then we first close the previous notification and we increment the notifyId\n and create a new timer for closing notification with id 2. Meanwhile after 20 sec if the setTimeout from previous\n notification runs, we dont close the notification since the timer id of the previous notification is 1 but\n the current notifyId is 2.\n */\n ngDoCheck(){\n var self = this;\n if (this.crudHelperService.displayNotify){\n if (this.notifyId !== 0) {\n this.runAnimation(false);\n this.notifyId = 0;\n }\n\n this.crudHelperService.displayNotify = false;\n this.runAnimation(true);\n var currentnotifyId = ++this.notifyCounter;\n this.notifyId = currentnotifyId;\n var newTimer = new notifyTimer(currentnotifyId);\n\n }\n\n function notifyTimer(timerId){\n var timerId = timerId;\n setTimeout(function(){\n if(timerId == self.notifyId){\n self.runAnimation(false);\n self.notifyId = 0;\n }\n },15000)\n }\n }\n\n close() {\n this.runAnimation(false);\n this.notifyId = 0;\n }\n}\n\n" }, { "alpha_fraction": 0.692307710647583, "alphanum_fraction": 0.692307710647583, "avg_line_length": 23.700000762939453, "blob_id": "554292caed33a5b8bd2e5a77cd81a79210369bab", "content_id": "49141267f8ea40e8141d19676f7ce1fa8c3c44ca", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 247, "license_type": "permissive", "max_line_length": 146, "num_lines": 10, "path": "/RELEASE.md", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "# Automated releases\nNA\n\n# Manual releases\nUI is released in lock-step with auth_proxy. In order to release a ```version```, just create a tag with that ```version``` and push it to master.\n\n\t```\n\tgit tag <version>\n\tgit push origin <version>\n\t```\n" }, { "alpha_fraction": 0.5950453877449036, "alphanum_fraction": 0.5960264801979065, "avg_line_length": 35.38393020629883, "blob_id": "dc6cbed82d8fc52a96d9d981d9b5733ea80ab513", "content_id": "24c1794648c81d77705f174cd10154376a7f7edb", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4077, "license_type": "permissive", "max_line_length": 125, "num_lines": 112, "path": "/app/applicationgroups/isolationpolicydirective.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by hardik gandhi on 7/8/16.\n */\nimport { Component, Input, OnChanges } from '@angular/core';\nimport * as _ from 'lodash';\nimport { PoliciesModel } from \"../components/models/policiesmodel\";\nimport { RulesModel } from \"../components/models/rulesmodel\";\n\n@Component({\n selector: 'ctv-isolationpolicy',\n templateUrl: './isolationpolicy.html'\n})\nexport class IsolationPolicySelectionComponent implements OnChanges {\n @Input() mode:string;\n @Input() applicationgroup:any;\n\n incomingRules:any[] = [];\n outgoingRules:any[] = [];\n isolationPolicies:any[] = []; // To Get all isolation policies of tenant\n isolationPolicySearchText:string = '';\n\n constructor(private policiesModel:PoliciesModel,\n private rulesModel:RulesModel) {\n\n }\n\n ngOnChanges() {\n var component = this;\n\n /**\n * Get incoming and outgoing rules for each policy present in applicationgroup\n */\n function getRules() {\n component.applicationgroup.policies.forEach(function (policy) {\n //To display rules of selected policies\n component.rulesModel.getIncomingRules(policy, component.applicationgroup.tenantName)\n .then(function (rules) {\n Array.prototype.push.apply(component.incomingRules, rules);\n });\n component.rulesModel.getOutgoingRules(policy, component.applicationgroup.tenantName)\n .then(function (rules) {\n Array.prototype.push.apply(component.outgoingRules, rules);\n });\n });\n }\n\n /**\n * To check 'details' or 'edit' mode (not create mode)\n */\n if (component.mode === 'details' || (component.mode === 'edit' && component.applicationgroup.groupName != \"\")) {\n component.getIsolationPolicies();\n //Application Groups might not have any policies associated with them so define an empty array\n if (component.applicationgroup.policies === undefined) {\n component.applicationgroup.policies = [];\n }\n getRules();\n }\n }\n\n /**\n * Get policies for the given tenant.\n */\n getIsolationPolicies() {\n var component = this;\n component.policiesModel.get(false).then(function (result) {\n component.isolationPolicies = _.filter(result, {\n 'tenantName': component.applicationgroup.tenantName\n });\n });\n }\n\n /**\n * Add policy to application group\n */\n addIsolationPolicy(policyName) {\n var component = this;\n var currentPolicyName = policyName;\n\n if (currentPolicyName !== undefined && _.includes(component.applicationgroup.policies, currentPolicyName) == false) {\n //To display selected policies\n //To be added to application group and saved to the server\n component.applicationgroup.policies\n .push(currentPolicyName);\n\n //To display rules of selected policies\n component.rulesModel.getIncomingRules(currentPolicyName, component.applicationgroup.tenantName)\n .then(function (rules) {\n Array.prototype.push.apply(component.incomingRules, rules);\n });\n component.rulesModel.getOutgoingRules(currentPolicyName, component.applicationgroup.tenantName)\n .then(function (rules) {\n Array.prototype.push.apply(component.outgoingRules, rules);\n });\n\n }\n };\n\n /**\n * Remove policy from application group\n */\n removeIsolationPolicy(policyName) {\n _.remove(this.applicationgroup.policies, function (policy) {\n return policy === policyName;\n });\n _.remove(this.incomingRules, function (rule) {\n return rule.policyName === policyName;\n });\n _.remove(this.outgoingRules, function (rule) {\n return rule.policyName === policyName;\n });\n };\n}\n\n\n" }, { "alpha_fraction": 0.4297472834587097, "alphanum_fraction": 0.6001443862915039, "avg_line_length": 43.67741775512695, "blob_id": "c872350b205461ca3fd7a4180646c453f6370ec8", "content_id": "dd592f2e2b1f6bab1a28bc2146fbb8cc1bbb459d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 6925, "license_type": "permissive", "max_line_length": 131, "num_lines": 155, "path": "/app/components/utils/inspectservice_test.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 7/18/16.\n */\n'use strict';\n\ndescribe('contiv.utils module', function () {\n var endpoints = [\n {\n \"containerID\": \"62e6dfd7b5de1b0faf8c8c1c12f87862b6f7f6daa4f55e3bfcc6a5171c67637c\",\n \"homingHost\": \"cluster-node1\",\n \"ipAddress\": [\n \"20.1.1.3\",\n \"\"\n ],\n \"labels\": \"map[app:web com.docker.swarm.id:359cfcc54ee996864ed1e31d4313297aa7b726e0f8244694d63282679dfcf6ba]\",\n \"macAddress\": \"02:02:14:01:01:03\",\n \"name\": \"182d045f309960e4e83d5f65cf7dbdb63aaa37e9c4642e2086e5989511ef9afa\",\n \"network\": \"contiv-net1.default\",\n \"serviceName\": \"serviceLb1\"\n },\n {\n \"containerID\": \"e1d8ae7112564b4029f218cb9fa239359937e77a3bfaf259a4be788b889b1369\",\n \"homingHost\": \"cluster-node1\",\n \"ipAddress\": [\n \"20.1.1.4\",\n \"\"\n ],\n \"labels\": \"map[app:web com.docker.swarm.id:5460ddf75d46c10f8a91b7f52ab2b4aa397c43c41c376773b98f44c7fc18d878]\",\n \"macAddress\": \"02:02:14:01:01:04\",\n \"name\": \"957c34540c5d9515698547d62263a080b0b8c0ca5d586cdd6c6d983f4a837231\",\n \"network\": \"contiv-net1.default\",\n \"serviceName\": \"serviceLb1\"\n },\n {\n \"containerID\": \"fbc5e16d9a2c1211d80c36e3e8c4bf7243f1478586941c6a50db2fe226174d4e\",\n \"homingHost\": \"cluster-node1\",\n \"ipAddress\": [\n \"20.1.1.5\",\n \"\"\n ],\n \"labels\": \"map[app:web com.docker.swarm.id:4555870c6d4af62b63ece84001271129cd437ee2abb72cf94c244f9a739e7827 env:prod]\",\n \"macAddress\": \"02:02:14:01:01:05\",\n \"name\": \"b31de2e1be08e6b741210f8028ed442393b49bd2bfbf81c7085cab10454cead0\",\n \"network\": \"contiv-net1.default\",\n \"serviceName\": \"serviceLb1\"\n }\n ];\n\n var newEndpointA = [\n {\n \"containerID\": \"62e6dfd7b5de1b0faf8c8c1c12f87862b6f7f6daa4f55e3bfcc6a5171c67637c\",\n \"homingHost\": \"cluster-node1\",\n \"ipAddress\":[\n \"20.1.1.3\",\n \"\"\n ],\n \"labels\": \"map[app:web com.docker.swarm.id:359cfcc54ee996864ed1e31d4313297aa7b726e0f8244694d63282679dfcf6ba]\",\n \"macAddress\": \"02:02:14:01:01:03\",\n \"name\": \"182d045f309960e4e83d5f65cf7dbdb63aaa37e9c4642e2086e5989511ef9afa\",\n \"network\": \"contiv-net1.default\",\n \"serviceName\": \"serviceLb1\"\n },\n {\n \"containerID\": \"e1d8ae7112564b4029f218cb9fa239359937e77a3bfaf259a4be788b889b1369\",\n \"homingHost\": \"cluster-node1\",\n \"ipAddress\":[\n \"20.1.1.4\",\n \"\"\n ],\n \"labels\": \"map[app:web com.docker.swarm.id:5460ddf75d46c10f8a91b7f52ab2b4aa397c43c41c376773b98f44c7fc18d878]\",\n \"macAddress\": \"02:02:14:01:01:04\",\n \"name\": \"957c34540c5d9515698547d62263a080b0b8c0ca5d586cdd6c6d983f4a837231\",\n \"network\": \"contiv-net1.default\",\n \"serviceName\": \"serviceLb1\"\n }\n ];\n\n var newEndpointB = [\n {\n \"containerID\": \"61e6dfd7b5de1b0faf8c8c1c12f87862b6f7f6daa4f55e3bfcc6a5171c67637c\",\n \"homingHost\": \"cluster-node1\",\n \"ipAddress\": [\n \"20.1.1.3\",\n \"\"\n ],\n \"labels\": \"map[app:web com.docker.swarm.id:359cfcc54ee996864ed1e31d4313297aa7b726e0f8244694d63282679dfcf6ba]\",\n \"macAddress\": \"02:02:14:01:01:03\",\n \"name\": \"182d045f309960e4e83d5f65cf7dbdb63aaa37e9c4642e2086e5989511ef9afa\",\n \"network\": \"contiv-net1.default\",\n \"serviceName\": \"serviceLb1\"\n },\n {\n \"containerID\": \"e1d8ae7112564b4029f218cb9fa239359937e77a3bfaf259a4be788b889b1369\",\n \"homingHost\": \"cluster-node1\",\n \"ipAddress\": [\n \"20.1.1.4\",\n \"\"\n ],\n \"labels\": \"map[app:web com.docker.swarm.id:5460ddf75d46c10f8a91b7f52ab2b4aa397c43c41c376773b98f44c7fc18d878]\",\n \"macAddress\": \"02:02:14:01:01:04\",\n \"name\": \"957c34540c5d9515698547d62263a080b0b8c0ca5d586cdd6c6d983f4a837231\",\n \"network\": \"contiv-net1.default\",\n \"serviceName\": \"serviceLb1\"\n },\n {\n \"containerID\": \"fbc5e16d9a2c1211d80c36e3e8c4bf7243f1478586941c6a50db2fe226174d4e\",\n \"homingHost\": \"cluster-node1\",\n \"ipAddress\": [\n \"20.1.1.5\",\n \"\"\n ],\n \"labels\": \"map[app:web com.docker.swarm.id:4555870c6d4af62b63ece84001271129cd437ee2abb72cf94c244f9a739e7827 env:prod]\",\n \"macAddress\": \"02:02:14:01:01:05\",\n \"name\": \"b31de2e1be08e6b741210f8028ed442393b49bd2bfbf81c7085cab10454cead0\",\n \"network\": \"contiv-net1.default\",\n \"serviceName\": \"serviceLb1\"\n }\n ];\n\n beforeEach(module('ui.router'));\n beforeEach(module('contiv.utils'));\n\n var InspectService;\n\n describe(\"InspectService\", function () {\n beforeEach(inject(function ($injector) {\n InspectService = $injector.get('InspectService');\n }));\n it('should be defined', function () {\n expect(InspectService).toBeDefined();\n });\n it('buildEndPoints function should convert container details into an array of name value pairs', function () {\n var containerDetails = InspectService.buildEndPoints(endpoints);\n expect(Object.keys(containerDetails).length).toEqual(endpoints.length);\n });\n it('labels inside endpoints should be an array and IP Address should be a string',function(){\n var containerDetails = InspectService.buildEndPoints(endpoints);\n var endpointAttrArray = containerDetails[endpoints[0].name]\n for (var i in endpointAttrArray){\n if(endpointAttrArray[i].name == 'labels')\n expect(Array.isArray((endpointAttrArray[i].value))).toBeTruthy();\n if(endpointAttrArray[i].name == \"ipAddress\")\n expect(typeof endpointAttrArray[i].value == \"string\").toBeTruthy();\n }\n });\n it ('checkContainerChanged function correctly evaluates changes in container configurations', function(){\n var contDetailsA = InspectService.buildEndPoints(endpoints);\n var contDetailsB = InspectService.buildEndPoints(newEndpointA);\n var contDetailsC = InspectService.buildEndPoints(newEndpointB);\n expect(InspectService.checkContainerChanged(contDetailsA,contDetailsB)).toBeTruthy();\n expect(InspectService.checkContainerChanged(contDetailsA,contDetailsA)).toBeFalsy();\n expect(InspectService.checkContainerChanged(contDetailsA,contDetailsC)).toBeTruthy();\n });\n });\n});\n" }, { "alpha_fraction": 0.5975652933120728, "alphanum_fraction": 0.598976731300354, "avg_line_length": 37.828765869140625, "blob_id": "2dc869faa46fd8f599e80039f67a91b64d546ad1", "content_id": "f33d1399af4dfaf231b2236fb25b9225c946320b", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5668, "license_type": "permissive", "max_line_length": 132, "num_lines": 146, "path": "/app/service_lbs/servicelbinfoctrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 10/14/16.\n */\n\nimport {Component, OnInit, Input, Inject, EventEmitter, Output, AfterViewChecked, NgZone} from \"@angular/core\";\nimport {CRUDHelperService} from \"../components/utils/crudhelperservice\";\nimport {ServicelbsModel} from \"../components/models/servicelbsmodel\";\nimport {Router, ActivatedRoute} from \"@angular/router\";\nvar _ = require('lodash');\n\n\n@Component({\n selector: 'servicelb-info',\n templateUrl: \"./servicelbinfo.html\"\n})\n\nexport class ServicelbInfoComponent implements OnInit{\n @Input('mode') mode: string;\n @Output('modeChange') modeChange: EventEmitter<any>;\n @Output('serviceName') serviceName: EventEmitter<any>;\n private servicelbsModel: ServicelbsModel;\n private crudHelperService: CRUDHelperService;\n public servicelbInfoCtrl: any;\n public infoselected: boolean;\n public statskey: string;\n public servicelb: any;\n public labelSelectors: any;\n public showLoader: boolean;\n private ngZone: NgZone;\n\n constructor(private router: Router,\n private activatedRoute: ActivatedRoute,\n servicelbsModel: ServicelbsModel,\n crudHelperService: CRUDHelperService,\n ngZone: NgZone){\n this.servicelbsModel = servicelbsModel;\n this.crudHelperService = crudHelperService;\n this.infoselected = true;\n this.statskey='';\n this.showLoader = true;\n this.mode = 'details';\n this.servicelb = {serviceName: '', networkName: '', ipAddress: '', selectors: [], ports: [], tenantName: 'default', key:''};\n this.labelSelectors =[];\n this.modeChange = new EventEmitter<any>();\n this.serviceName = new EventEmitter<any>();\n this.ngZone = ngZone;\n this.servicelbInfoCtrl = this;\n }\n\n ngOnInit(){\n this.crudHelperService.startLoader(this);\n this.statskey = this.activatedRoute.snapshot.params['key'];\n this.getServicelbs(false);\n }\n\n returnToServicelbDetails() {\n this.mode = \"details\";\n this.modeChange.emit(this.mode);\n }\n\n returnToServicelbs(){\n this.router.navigate(['../../list'], {relativeTo: this.activatedRoute});\n }\n\n getServicelbs(reload: boolean){\n var servicelbInfoCtrl = this;\n this.servicelbsModel.getModelByKey(this.statskey, false, 'key')\n .then((result) => {\n servicelbInfoCtrl['servicelb'] = result;\n servicelbInfoCtrl.createEditViewLabels();\n servicelbInfoCtrl.serviceName.emit(servicelbInfoCtrl.servicelb.serviceName);\n servicelbInfoCtrl.ngZone.run(() => {\n servicelbInfoCtrl.crudHelperService.stopLoader(servicelbInfoCtrl);\n });\n },\n (error) => {\n servicelbInfoCtrl.ngZone.run(() => {\n servicelbInfoCtrl.crudHelperService.stopLoader(servicelbInfoCtrl);\n });\n })\n }\n\n createEditViewLabels(){\n this.servicelb.selectors.forEach((item) => {\n var selector = {\n name: item.split('=')[0],\n value: item.split('=')[1]\n }\n this.labelSelectors.push(selector);\n });\n }\n\n createLabelSelectorStrings(){\n var servicelbInfoCtrl = this;\n this.servicelb.selectors = [];\n this.labelSelectors.forEach((selector) => {\n var selectorString = selector.name+\"=\"+selector.value;\n this.servicelb.selectors.push(selectorString);\n });\n }\n\n saveServicelb(){\n this.crudHelperService.startLoader(this);\n var existingLabelsView = this.servicelb.selectors.slice();\n this.createLabelSelectorStrings();\n var servicelbInfoCtrl = this;\n this.servicelbsModel.save(this.servicelb)\n .then((result) => {\n servicelbInfoCtrl.ngZone.run(() => {\n servicelbInfoCtrl.crudHelperService.stopLoader(servicelbInfoCtrl);\n servicelbInfoCtrl.crudHelperService.showNotification(\"Service load balancer: Updated\", result.key.toString());\n });\n servicelbInfoCtrl.returnToServicelbDetails();\n },(error) => {\n servicelbInfoCtrl.servicelb.selectors = existingLabelsView;\n servicelbInfoCtrl.ngZone.run(() => {\n servicelbInfoCtrl.crudHelperService.stopLoader(servicelbInfoCtrl);\n servicelbInfoCtrl.crudHelperService.showServerError(\"Service load balancer: Update failed\", error);\n });\n });\n }\n\n deleteServicelb() {\n this.crudHelperService.startLoader(this);\n var servicelbInfoCtrl = this;\n this.servicelbsModel.delete(this.servicelb)\n .then((result) => {\n servicelbInfoCtrl.ngZone.run(() => {\n servicelbInfoCtrl.crudHelperService.stopLoader(servicelbInfoCtrl);\n servicelbInfoCtrl.crudHelperService.showNotification(\"Service load balancer: Deleted\", result.toString());\n });\n servicelbInfoCtrl.returnToServicelbs();\n },\n (error) => {\n servicelbInfoCtrl.ngZone.run(() => {\n servicelbInfoCtrl.crudHelperService.stopLoader(servicelbInfoCtrl);\n servicelbInfoCtrl.crudHelperService.showNotification(\"Service load balancer: Delete failed\", error);\n });\n }\n );\n }\n\n cancelEditing(){\n this.returnToServicelbDetails();\n }\n}" }, { "alpha_fraction": 0.6560402512550354, "alphanum_fraction": 0.6610738039016724, "avg_line_length": 29.58974266052246, "blob_id": "9164f31fdf165f88236225df65859c2e01c05987", "content_id": "ce7ce4a869878b99c64ed5df9742b073fc5429f5", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1192, "license_type": "permissive", "max_line_length": 110, "num_lines": 39, "path": "/app/components/directives/settings/networksettingcomponent.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 11/14/16.\n */\n\nimport {Component, Input, Output, EventEmitter} from \"@angular/core\";\nimport {ContivGlobals} from \"../../models/contivglobals\";\nimport any = jasmine.any;\n\n@Component({\n selector: 'networksettingcomp',\n templateUrl: './networksetting.html'\n})\n\nexport class NetworkSettingComponent {\n @Input('firstRunWiz') firstRunWiz:boolean;\n @Input('setting') setting:any;\n @Output('updateNetDef') updateNetDef: EventEmitter<any>;\n @Output('cancel') cancel: EventEmitter<any>;\n @Output('skip') skip: EventEmitter<any>;\n vlanPattern:string = ContivGlobals.VLAN_REGEX;\n vxlanPattern:string = ContivGlobals.VXLAN_REGEX;\n pvtSubnetPattern:string = ContivGlobals.PVTSUBNET_REGEX;\n\n constructor(){\n this.updateNetDef = new EventEmitter<any>();\n this.cancel = new EventEmitter<any>();\n this.skip = new EventEmitter<any>();\n this.firstRunWiz = false;\n this.setting = {networkInfraType: '', vlans: '', vxlans: '', fwdMode: '', arpMode: '', pvtSubnet: ''};\n }\n\n updateNetworkSettings(formvalid: boolean){\n if(formvalid){\n this.updateNetDef.emit(this.setting);\n }\n }\n\n\n}" }, { "alpha_fraction": 0.6656760573387146, "alphanum_fraction": 0.6706290245056152, "avg_line_length": 32.63333511352539, "blob_id": "0d8931ef9201d5823d200a1db6eb7583a91aed7b", "content_id": "ee0ab0ea985ed8d6929293fc4e295e0b2a5f1c0c", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2019, "license_type": "permissive", "max_line_length": 96, "num_lines": 60, "path": "/app/applicationgroups/applicationgrouplistctrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 3/11/16.\n */\nimport {Component, OnInit, OnDestroy, Inject} from \"@angular/core\";\nimport { ActivatedRoute, Router } from \"@angular/router\";\nimport {ApplicationGroupsModel} from \"../components/models/applicationgroupsmodel\";\nimport {CRUDHelperService} from \"../components/utils/crudhelperservice\";\nimport {Observable, Subscription} from \"rxjs\";\n\n@Component({\n selector:'app-group',\n template: require(\"./applicationgrouplist.html\")\n})\n\nexport class AppGrouplistComponent implements OnInit, OnDestroy{\n public applicationGroupListCtrl: any;\n private appGroupModel: ApplicationGroupsModel;\n private crudHelperService: CRUDHelperService;\n private refresh: Subscription;\n\n constructor(private activatedRoute: ActivatedRoute,\n private router: Router,\n appGroupModel: ApplicationGroupsModel,\n crudHelperService:CRUDHelperService){\n this.appGroupModel = appGroupModel;\n this.crudHelperService = crudHelperService;\n this.applicationGroupListCtrl = this;\n this['showLoader'] = true;\n\n this.refresh = Observable.interval(5000).subscribe(() => {\n this.getApplicationGroup(true);\n });\n this.crudHelperService.startLoader(this);\n }\n\n ngOnInit(){\n this.crudHelperService.startLoader(this);\n this.getApplicationGroup(false);\n }\n\n getApplicationGroup(reload: boolean){\n var applicationGroupListCtrl = this;\n this.appGroupModel.get(reload)\n .then((result) => {\n applicationGroupListCtrl['groups']=result;\n applicationGroupListCtrl.crudHelperService.stopLoader(applicationGroupListCtrl);\n }, (error) => {\n applicationGroupListCtrl.crudHelperService.stopLoader(applicationGroupListCtrl);\n });\n }\n\n create(){\n this.router.navigate(['../create'], { relativeTo: this.activatedRoute });\n }\n\n ngOnDestroy(){\n this.refresh.unsubscribe();\n }\n\n}\n\n" }, { "alpha_fraction": 0.6929057240486145, "alphanum_fraction": 0.6987366080284119, "avg_line_length": 27.58333396911621, "blob_id": "668f60f5001782b616683d2ca5def54da4d98385", "content_id": "067be3d37de3ed07a5c81e157f101c0ab757d26c", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1029, "license_type": "permissive", "max_line_length": 79, "num_lines": 36, "path": "/app/settings/tenants/organization.module.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "import {NgModule} from \"@angular/core\";\nimport {FormsModule} from \"@angular/forms\";\nimport {CommonModule} from \"@angular/common\";\nimport {RouterModule} from \"@angular/router\";\nimport {DirectivesModule} from \"../../components/directives/directives.module\";\nimport {OrganizationListComponent} from \"./organizationlistctrl\";\nimport {OrganizationCreateComponent} from \"./organizationcreatectrl\";\nimport {OrganizationDetailsComponent} from \"./organizationdetailsctrl\";\n/**\n * Created by cshampur on 10/18/16.\n */\n\n\n@NgModule({\n imports: [\n FormsModule,\n CommonModule,\n RouterModule,\n DirectivesModule\n ],\n declarations: [\n OrganizationListComponent,\n OrganizationCreateComponent,\n OrganizationDetailsComponent\n ],\n exports: [\n OrganizationListComponent,\n OrganizationCreateComponent,\n OrganizationDetailsComponent,\n DirectivesModule,\n FormsModule,\n CommonModule,\n RouterModule\n ]\n})\nexport class OrganizationModule {}\n" }, { "alpha_fraction": 0.7413162589073181, "alphanum_fraction": 0.7468007206916809, "avg_line_length": 51.14285659790039, "blob_id": "df4872062552a4948a4fb17048d4042515a38c1e", "content_id": "b6cb343140ded413e72ceef55b55732f2d4e7fff", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1094, "license_type": "permissive", "max_line_length": 159, "num_lines": 21, "path": "/e2e-tests/networks/networkspageobject.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 7/27/16.\n */\n\n\nvar netList = function(){\n this.createButton = element(by.css(\"button.button[ui-sref='contiv.menu.networks.create']\"));\n this.networkName = element(by.repeater(\"network in networksListCtrl.filterednetworks\").row(0)).element(by.cssContainingText(\"a\",testConfig.networks.name));\n}\n\nvar netCreate = function(){\n this.newNetworkName = element(by.model(\"networkCreateCtrl.newNetwork.networkName\"));\n this.newNetworkEncap = element(by.model(\"networkCreateCtrl.newNetwork.encap\")).element(by.css(\"[value=\"+testConfig.networks.encap+\"]\"));\n this.newNetworkCidr = element(by.model(\"networkCreateCtrl.newNetwork.subnet\"));\n this.newNetworkGateway = element(by.model(\"networkCreateCtrl.newNetwork.gateway\"));\n this.newNetworkCreateButton = element(by.cssContainingText(\"button\",\"Cancel\"));\n this.newNetworkCancelButton = element(by.cssContainingText(\"button\",\"Create\"));\n this.serverMessage = element(by.cssContainingText(\"ctv-error div div\", \"Error creating network\"));\n}\n\nmodule.exports = {\"netList\":netList,\"netCreate\":netCreate};" }, { "alpha_fraction": 0.6493405699729919, "alphanum_fraction": 0.6547711491584778, "avg_line_length": 24.799999237060547, "blob_id": "2b90ae57ae81206b5c842c88624d28bf92e8f99e", "content_id": "05e07d10d78d71a3e912ef7860a161374de26ad9", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1289, "license_type": "permissive", "max_line_length": 81, "num_lines": 50, "path": "/app/firstrunwizard/firstrunwizardctrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 10/29/16.\n */\n\nimport { Component, OnInit, OnDestroy } from \"@angular/core\";\nimport { ActivatedRoute, Router } from \"@angular/router\";\nimport { AuthService } from \"../components/utils/authservice\";\nimport { FirstRunWizardService } from \"./firstrunwizardservice\";\ndeclare var jQuery:any;\n\n@Component({\n selector: 'firstrunwizard',\n templateUrl: './firstrunwizard.html',\n styleUrls: ['./firstrunwizard.css']\n})\n\nexport class FirstrunWizardComponent implements OnInit{\n public pageNo: number;\n public welcomeActive: boolean;\n\n constructor(private wizardService: FirstRunWizardService,\n private activatedRoute: ActivatedRoute,\n private router: Router,\n private authService: AuthService){\n this.pageNo = 1;\n this.welcomeActive = true;\n wizardService.getNetworkSettings();\n wizardService.getAciSettings();\n wizardService.getGlobalInspect();\n }\n\n ngOnInit(){\n }\n\n public updatePage(pageno: number){\n this.pageNo = ++pageno;\n }\n\n logout() {\n this.authService.isLoggedIn = false;\n }\n\n skip() {\n this.router.navigate(['/m/dashboard'],{relativeTo: this.activatedRoute});\n }\n\n runwizard() {\n this.welcomeActive = false;\n }\n}" }, { "alpha_fraction": 0.6687306761741638, "alphanum_fraction": 0.6687306761741638, "avg_line_length": 37, "blob_id": "52c7e41b8f2551e5b442ab383281166c04242570", "content_id": "36ecfdf92341173682b4bce64f0712c023ec7fc0", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 646, "license_type": "permissive", "max_line_length": 103, "num_lines": 17, "path": "/Makefile", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "build:\n\t@docker run -it -u $$(id -u):$$(id -g) --rm -v ${PWD}:/contiv-ui contiv-ui-builder || \\\n \techo \"If you have not run the build task before, please run `make build-builder` first. \"\n\ndev-build:\n\t@docker run -it -u $$(id -u):$$(id -g) --rm -v ${PWD}:/contiv-ui contiv-ui-builder gulp dev-build || \\\n\t\techo \"If you have not run the build task before, please run `make build-builder` first. \"\n\nbuild-builder:\n\tdocker build -t contiv-ui-builder -f Dockerfile.build .\n\nbuild-nginx:\n\tdocker build -t contiv-ui-nginx .\n\nrun: build build-nginx\n\t@docker rm -f contiv-ui-nginx || :\n\tdocker run --name contiv-ui-nginx --net host -itd contiv-ui-nginx\n" }, { "alpha_fraction": 0.6749619245529175, "alphanum_fraction": 0.6841036081314087, "avg_line_length": 31.774999618530273, "blob_id": "cc1ab765bb7df2c87162aedb631c75dda4a8e605", "content_id": "18af3b84338ee521ebb6fc6a9c9a157a791b9c95", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3938, "license_type": "permissive", "max_line_length": 108, "num_lines": 120, "path": "/backend/telegrafdatasource.py", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer\nimport urllib2\nimport json\nimport sys\n\n\nPORT_NUMBER = 4000\n\n#This class will handles any incoming request from\n#the browser \nclass myHandler(BaseHTTPRequestHandler):\n\t\n\tdef labelParser(self, labels):\n\t\t#first 4 char are map[ and last is ]\n\t\tlabelMap = {}\n\t\tlabels = labels[4:-1]\n\t\tlabels = labels.split()\n\t\tfor l in labels:\n\t\t\tindex = l.find(':')\n\t\t\tkey = l[0:index]\n\t\t\tval = l[index+1:]\n\t\t\tlabelMap[key] = val\n\t\treturn labelMap\n\n\n\t#Handler for the GET requests\n\tdef do_GET(self):\n\t\tsvcstats = urllib2.urlopen(\"http://localhost:9090/svcstats\").read()\n\t\tsvcstatsjson = json.loads(str(svcstats))\n\t\tself.send_response(200)\n\t\tself.send_header('Content-type','application/json')\n\t\tself.end_headers()\n\t\tif ('/services' in self.path):\n\t\t\tserviceInspectNames = []\n\n\t\t\tservices = urllib2.urlopen(\"http://localhost:9999/api/v1/serviceLBs/\").read()\n\t\t\tfor s in json.loads(services):\n\t\t\t\tname = str(s[\"tenantName\"]) + ':' + str(s[\"serviceName\"])\n\t\t\t\tserviceInspectNames.append(name)\n\t\t\t# #inspect each service\n\t\t\tchildrenServiceDict = {}\n\t\t\tchildrenServiceDict[\"topLevel\"] = []\n\t\t\tancestorServiceDict = {}\n\t\t\tproviders = []\n\t\t\tlabelMap = {}\n\t\t\tselectorMap = {}\n\n\t\t\tfor serviceName in serviceInspectNames:\n\t\t\t\tservice = urllib2.urlopen(\"http://localhost:9999/api/v1/inspect/serviceLBs/\" + serviceName + '/').read()\n\t\t\t\tserviceJson = json.loads(service)\n\n\t\t\t\t#getting selectors\n\t\t\t\tselectorMapLocal = {}\n\t\t\t\tfor selector in serviceJson[\"Config\"][\"selectors\"]:\n\t\t\t\t\tindex = selector.find('=')\n\t\t\t\t\tkey = selector[0:index]\n\t\t\t\t\tval = selector[index+1:]\n\t\t\t\t\tselectorMapLocal[key] = val\n\t\t\t\tselectorMap[serviceName] = selectorMapLocal\n\n\t\t\t\toper = serviceJson[\"Oper\"]\n\t\t\t\tproviderList = oper.get(\"providers\", []);\n\t\t\t\tipAddrs = []\n\t\t\t\tfor provider in providerList:\n\t\t\t\t\tfor p in provider[\"ipAddress\"]:\n\t\t\t\t\t\tif p != \"\":\n\t\t\t\t\t\t\tif p not in providers:\n\t\t\t\t\t\t\t\tproviders.append(str(p))\n\t\t\t\t\t\t\t\tlabelMap[p] = self.labelParser(provider[\"labels\"])\n\t\t\t\t\t\t\tipAddrs.append(str(p))\n\t\t\t\t\t\t\tancestorServiceDict[str(p)] = [serviceName]\n\t\t\t\tchildrenServiceDict[serviceName] = ipAddrs\n\t\t\t\tchildrenServiceDict[\"topLevel\"].append(serviceName)\n\t\t\tret = {}\n\t\t\tret[\"ancestors_struct\"] = ancestorServiceDict\n\t\t\tret[\"children_struct\"] = childrenServiceDict\n\t\t\tret[\"labels\"] = labelMap\n\t\t\tret[\"serviceSelectors\"] = selectorMap\n\t\t\tself.wfile.write(json.dumps(ret))\n\t\telse:\n\t\t\tendpointKey = self.path[1:];\n\t\t\tendpointItem = None\n\t\t\tfor item in svcstatsjson:\n\t\t\t\tif item['EndpointIP'] == endpointKey:\n\t\t\t\t\tendpointItem = item\n\t\t\t\t\tbreak\n\t\t\tret = {}\n\t\t\tret[\"EndpointIP\"] = str(endpointItem[\"EndpointIP\"])\n\t\t\t#no point in checking for more services right now, as\n\t\t\t#telegraf http-json plugin can't handle multiple writes for a single \n\t\t\t#scrape\n\t\t\tret[\"ServiceIP\"] = str(endpointItem[\"SvcStats\"].keys()[0])\n\t\t\tservice = ret[\"ServiceIP\"];\n\t\t\tproviderStats = endpointItem[\"SvcStats\"][service][\"ProvStats\"]\n\t\t\t#finding which of the two keys is provider key\n\t\t\t#currently merging the stats to create bytes in and bytes out\n\t\t\t#for a pair, not individually\n\t\t\tproviderKeys = providerStats.keys()\n\t\t\tret['ProviderIP'] = str(providerKeys[0]);\n\t\t\tif ret['ProviderIP'] == ret['EndpointIP']:\n\t\t\t\tret['ProviderIP'] = str(providerKeys[1])\n\t\t\tret[\"BytesIn\"] = int(providerStats[ret['ProviderIP']]['BytesIn'])\n\t\t\tret[\"PacketsIn\"] = int(providerStats[ret['ProviderIP']]['PacketsIn'])\n\t\t\tret[\"BytesOut\"] = int(providerStats[ret['EndpointIP']]['BytesOut'])\n\t\t\tret[\"PacketsOut\"] = int(providerStats[ret['EndpointIP']]['PacketsOut'])\n\t\t\tself.wfile.write(json.dumps(ret))\n\t\treturn\n\ntry:\n\t#Create a web server and define the handler to manage the\n\t#incoming request\n\tserver = HTTPServer(('', PORT_NUMBER), myHandler)\n\tprint 'Started httpserver on port ' , PORT_NUMBER\n\t\n\t#Wait forever for incoming htto requests\n\tserver.serve_forever()\n\nexcept KeyboardInterrupt:\n\tprint '^C received, shutting down the web server'\n\tserver.socket.close()\n\n\n\n\n\n" }, { "alpha_fraction": 0.6781529784202576, "alphanum_fraction": 0.6850448250770569, "avg_line_length": 28.632652282714844, "blob_id": "d06926b6f376f9a206bdfb53ce78f609aa780fc2", "content_id": "b647cd02a148e2f378b1193188462e30e07edb35", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1451, "license_type": "permissive", "max_line_length": 90, "num_lines": 49, "path": "/app/firstrunwizard/firstrunnetworkdefaults.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 10/30/16.\n */\n\n\nimport {Component, OnInit, EventEmitter, Output, DoCheck} from \"@angular/core\";\nimport {FirstRunWizardService} from \"./firstrunwizardservice\";\n@Component({\n selector: 'firstrunnetworkdefault',\n templateUrl: './firstrunnetworkdefault.html'\n})\n\nexport class FirstrunNetworkDefaultComponent implements DoCheck{\n private wizardService: FirstRunWizardService;\n public setting: any;\n @Output('updatePage') updatePage: EventEmitter<any>;\n @Output('cancelPage') cancelPage: EventEmitter<any>;\n public showLoader: boolean;\n\n constructor(wizardService: FirstRunWizardService){\n this.wizardService = wizardService;\n this.setting = this.wizardService.setting;\n this.updatePage = new EventEmitter<any>();\n this.cancelPage = new EventEmitter<any>();\n this.showLoader = this.wizardService.showLoader;\n }\n\n ngDoCheck(){\n this.showLoader = this.wizardService.showLoader;\n this.setting = this.wizardService.setting;\n }\n\n updateNetworkSettings(setting: any){\n this.wizardService.skipArray[0] = false;\n this.wizardService.setting = setting;\n this.updatePage.emit(1);\n }\n\n cancel(){\n this.cancelPage.emit();\n }\n\n skip(){\n Object.assign(this.wizardService.setting, this.wizardService.defaults['setting']);\n this.wizardService.skipArray[0] = true;\n this.updatePage.emit(1);\n }\n\n}" }, { "alpha_fraction": 0.4225086569786072, "alphanum_fraction": 0.424080491065979, "avg_line_length": 65.29166412353516, "blob_id": "2768c6c4b75d069b5912d4d6e5b9365542ee267c", "content_id": "6d98dc4550a6bf490423aecae715815b1268f4ea", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3181, "license_type": "permissive", "max_line_length": 73, "num_lines": 48, "path": "/app/components/utils/authMatrix.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 11/4/16.\n */\n\nexport const AuthMatrix = {\n 'firstrun': {'ops':'n', 'admin':'y'},\n 'dashboard': {'ops':'y', 'admin':'y'},\n 'networkpolicies/list': {'ops':'y', 'admin':'y'},\n 'networkpolicies/isolation/create': {'ops':'y', 'admin':'y'},\n 'networkpolicies/isolation/details': {'ops':'y', 'admin':'y'},\n 'networkpolicies/isolation/edit': {'ops':'y', 'admin':'y'},\n 'networkpolicies/bandwidth/create': {'ops':'y', 'admin':'y'},\n 'networkpolicies/bandwidth/details': {'ops':'y', 'admin':'y'},\n 'networkpolicies/bandwidth/edit': {'ops':'y', 'admin':'y'},\n 'networkpolicies/contractgroup/create': {'ops':'y', 'admin':'y'},\n 'networkpolicies/contractgroup/details': {'ops':'y', 'admin':'y'},\n 'applicationgroups/list': {'ops':'y', 'admin':'y'},\n 'applicationgroups/create': {'ops':'y', 'admin':'y'},\n 'applicationgroups/details': {'ops':'y', 'admin':'y'},\n 'applicationgroups/edit': {'ops':'y', 'admin':'y'},\n 'settings/users/list': {'ops':'n', 'admin':'y'},\n 'settings/users/create': {'ops':'n', 'admin':'y'},\n 'settings/users/details': {'ops':'n', 'admin':'y'},\n 'settings/users/edit': {'ops':'n', 'admin':'y'},\n 'settings/nodes/list': {'ops':'n', 'admin':'y'},\n 'settings/nodes/create': {'ops':'n', 'admin':'y'},\n 'settings/nodes/details': {'ops':'n', 'admin':'y'},\n 'settings/nodes/edit': {'ops':'n', 'admin':'y'},\n 'settings/authorization/list': {'ops':'n', 'admin':'y'},\n 'settings/authorization/details': {'ops':'n', 'admin':'y'},\n 'settings/authorization/create': {'ops':'n', 'admin':'y'},\n 'settings/authorization/edit': {'ops':'n', 'admin':'y'},\n 'settings/networks': {'ops':'n', 'admin':'y'},\n 'settings/ldap': {'ops':'n', 'admin':'y'},\n 'settings/organizations/list': {'ops':'n', 'admin':'y'},\n 'settings/organizations/create': {'ops':'n', 'admin':'y'},\n 'settings/organizations/details': {'ops':'n', 'admin':'y'},\n 'networks/list': {'ops':'y', 'admin':'y'},\n 'networks/create': {'ops':'y', 'admin':'y'},\n 'networks/details': {'ops':'y', 'admin':'y'},\n 'servicelbs/list': {'ops':'y', 'admin':'y'},\n 'servicelbs/create': {'ops':'y', 'admin':'y'},\n 'servicelbs/details': {'ops':'y', 'admin':'y'},\n 'appprofiles/list': {'ops':'y', 'admin':'y'},\n 'appprofiles/create': {'ops':'y', 'admin':'y'},\n 'appprofiles/details': {'ops':'y', 'admin':'y'},\n 'appprofiles/edit': {'ops':'y', 'admin':'y'}\n};" }, { "alpha_fraction": 0.556151807308197, "alphanum_fraction": 0.5569183826446533, "avg_line_length": 31.524999618530273, "blob_id": "775b02d8d34ebd6cfbe153e1776ab462de2dbf14", "content_id": "101bb9b8c2262f3b5b6d3dd4a7afb91aa3a3dd8b", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2609, "license_type": "permissive", "max_line_length": 70, "num_lines": 80, "path": "/app/components/graphobjects/policy/qtippolicy_test.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "'use strict';\n\ndescribe('policy', function(){\n var policyFactory;\n var graph;\n beforeEach(function(){\n module('contiv.graph');\n inject( function($injector){\n policyFactory = $injector.get('QTipPolicy');\n });\n graph = {state:{\n testNodesOld:null,\n testPathsOld:null\n }, \n consts:{}, \n updateNewNodes:function(n){\n this.state.testNodesOld = 'oldNewNodes';\n },\n updateNewPaths:function(n) {\n this.state.testPathsOld = 'oldNewPaths';\n } \n };\n });\n\n it('Checking inital values', function(){\n //shouldn't take in passed in name\n var policy = new policyFactory.Policy(\"test\");\n expect(policy.policyName).toBe(\"QTipPolicy\");\n expect(policy.graph).toBe(null);\n expect(policy.initialized).toBe(false);\n });\n\n it('Checking initializing', function() {\n var policy = new policyFactory.Policy();\n policy.updateNewNodes = function(n){\n state.testNodesNew = 'qtip';\n };\n policy.updateNewPaths = function() {\n state.testPathsNew = 'qtip';\n };\n policy.initialize(graph);\n //checking policy is only modifying state and consts\n //and graph functions\n expect(graph.state != null).toBe(true);\n expect(graph.consts != null).toBe(true);\n expect(graph.updateNewPaths != null).toBe(true);\n expect(graph.updateNewNodes != null).toBe(true);\n var keys = 0;\n for (var k in graph) {\n keys++;\n }\n expect(keys).toBe(4);\n var state = graph.state.QTipPolicy;\n var graphState = graph.state;\n expect(state.mousedown).toBe(false);\n\n //checking overriding of update new nodes and update new paths\n \n graph.updateNewNodes();\n expect(graphState.testNodesOld != null).toBe(true);\n expect(state.testNodesNew != null).toBe(true);\n graph.updateNewPaths();\n expect(graphState.testPathsOld != null).toBe(true);\n expect(state.testPathsNew != null).toBe(true);\n\n });\n\n it('checking mouse up and down trigger', function() {\n var policy = new policyFactory.Policy();\n\n policy.initialize(graph);\n var state = graph.state.QTipPolicy;\n\n expect(state.mousedown).toBe(false);\n policy.mousedown();\n expect(state.mousedown).toBe(true);\n policy.mouseup();\n expect(state.mousedown).toBe(false);\n })\n});\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6328828930854797, "alphanum_fraction": 0.6342342495918274, "avg_line_length": 37.956138610839844, "blob_id": "b148f9b24138fe0032eb3640566078fdb2a4c9ea", "content_id": "6892742d6d5075f0215b0fb938d4503ba20b2d00", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4440, "license_type": "permissive", "max_line_length": 172, "num_lines": 114, "path": "/app/settings/authorization/authorizationdetails.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 12/13/16.\n */\n\n\nimport {Component, OnInit} from \"@angular/core\";\nimport {AuthorizationModel} from \"../../components/models/authorizationmodel\";\nimport {CRUDHelperService} from \"../../components/utils/crudhelperservice\";\nimport {Router, ActivatedRoute} from \"@angular/router\";\nimport {OrganizationsModel} from \"../../components/models/organizationsmodel\";\nimport {Authorization} from \"./authorizationcreate\";\n@Component({\n selector: 'authorizationdetails',\n templateUrl: './authorizationdetails.html'\n})\n\nexport class AuthorizationDetailsComponent implements OnInit{\n authorization: Authorization = {AuthzUUID: '', PrincipalName: '', Local: false, Role: '', TenantName: ''};\n mode: string = 'details';\n showLoader: boolean = false;\n tenants: any = [];\n isRootAdmin: boolean = false;\n constructor(private authorizationModel: AuthorizationModel,\n private crudHelperService: CRUDHelperService,\n private router: Router,\n private activatedRoute: ActivatedRoute,\n private organizationModel: OrganizationsModel){\n\n var authdetailsComp = this;\n\n function setMode(){\n if(activatedRoute.routeConfig.path.includes('edit')){\n authdetailsComp.mode = 'edit';\n }\n else{\n authdetailsComp.mode = 'details';\n }\n }\n\n setMode();\n }\n\n ngOnInit(){\n this.getAuthorizationDetail();\n }\n\n private getAuthorizationDetail(){\n var authdetailsComp = this;\n this.crudHelperService.startLoader(this);\n this.authorizationModel.getModelByKey(this.activatedRoute.snapshot.params['key'], false, 'AuthzUUID')\n .then((result) => {\n authdetailsComp.authorization = result;\n authdetailsComp.isRootAdmin = (result.PrincipalName === 'admin' && result.Role === 'admin');\n authdetailsComp.getOrganization();\n }, (error) => {\n authdetailsComp.crudHelperService.stopLoader(authdetailsComp);\n });\n }\n\n getOrganization(){\n var authdetailsComp = this;\n this.organizationModel.get(false)\n .then((result) => {\n authdetailsComp.tenants = result;\n authdetailsComp.crudHelperService.stopLoader(authdetailsComp);\n }, (error) => {\n authdetailsComp.crudHelperService.stopLoader(authdetailsComp);\n });\n }\n\n returnToList(){\n this.router.navigate(['../../list'], {relativeTo: this.activatedRoute});\n }\n\n editAuthorization() {\n this.router.navigate(['../../edit', this.authorization.AuthzUUID], { relativeTo: this.activatedRoute });\n }\n\n returntoAuthDetails() {\n this.router.navigate(['../../details', this.authorization.AuthzUUID], { relativeTo: this.activatedRoute });\n }\n\n cancelEditing() {\n this.returntoAuthDetails();\n }\n\n saveAuthorization(){\n var authdetailsComp = this;\n authdetailsComp.crudHelperService.startLoader(authdetailsComp);\n this.authorizationModel.save(this.authorization)\n .then((result) => {\n authdetailsComp.crudHelperService.stopLoader(authdetailsComp);\n authdetailsComp.crudHelperService.showNotification(\"Authorization: Updated\", result['PrincipalName'] + '::' + result['TenantName'] + '::' + result['Role']);\n authdetailsComp.returntoAuthDetails();\n });\n }\n\n deleteAuthorization(){\n var authdetailsComp = this;\n authdetailsComp.crudHelperService.startLoader(authdetailsComp);\n this.authorizationModel.delete(authdetailsComp.authorization['AuthzUUID'])\n .then((result) => {\n authdetailsComp.crudHelperService.stopLoader(authdetailsComp);\n authdetailsComp.crudHelperService.showNotification(\"Authorization: Deleted\", result);\n authdetailsComp.crudHelperService.stopLoader(authdetailsComp);\n authdetailsComp.returnToList();\n }, (error) => {\n authdetailsComp.crudHelperService.stopLoader(authdetailsComp);\n authdetailsComp.crudHelperService.showServerError(\"Authorization: Delete failed\", error);\n authdetailsComp.crudHelperService.stopLoader(authdetailsComp);\n authdetailsComp.returnToList();\n });\n }\n}" }, { "alpha_fraction": 0.7396034598350525, "alphanum_fraction": 0.7441973090171814, "avg_line_length": 58.89855194091797, "blob_id": "a8609866d37f87ac0cecc249d6266551b496e81b", "content_id": "5e98418c434319017481b72c3706cd8020961671", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4136, "license_type": "permissive", "max_line_length": 385, "num_lines": 69, "path": "/backend/DESIGN.md", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "#Backend Design\n\n##Developers - Table of contents\n=================\n\n * [Overview](#overview)\n * [InfluxDB](#influxdb)\n * [Telegraf](#telegraf)\n * [telegrafdatasource.py](#telegrafdatasourcepy)\n * [Limitations](#limitations)\n\n###Overview:\n============\nThe backend is made up of multiple components. \n* telegrafdatasource.py: \n * A python server that serves metadata to the front end, as well as acts as a middleware for converting data from Netplugin so that Telegraf can read it. \n * It is run on all the nodes.\n* Telegraf: \n * Datacollector that scrapes the python server for data, and writes to influx. Runs on one node.\n* InfluxDB: \n * Timeseries DB that is used for storing data. Runs in a docker container.\n* serviceInit.sh: \n * Starts up two services, one with 14 containers, and another with 3, as well as 4 endpoint containers. Generates traffic using netcat. Based on the service example here: http://contiv.github.io/documents/networking/services.html. \n * If run with \"-c\", creates another 3 endpoint containers. \n* backendConfig.sh: \n * Generates the config file for Telegraf, telegraf.conf. Uses Contiv Netplugin's API to specify endpoints for Telegraf to query the python server with.\n * Installs and starts telegraf, and starts up Influx DB in a docker container.\n* endpointExtract.py: \n * Helper file for backendConfig.sh\n * Extracts all the endpoint IP containers for a given node IP. \n* configBase.conf: \n * Basic telegraf config tempalte which backendConfig uses to generate telegraf.conf\n\n###InfluxDB\n============\n* Timeseries DB that is used for storing data. Runs in a docker container.\n* All recordings are stored with measurement as httpjson_svcstats.\n* Field Keys are Bytes In, Bytes Out, Packets In, Packets Out.\n* Tags are EndpointIP, ProviderIP, ServiceIP.\n* For info on querying the database, see https://docs.influxdata.com/influxdb/v0.13/guides/querying_data/\n\n###Telegraf\n============\n* Datacollector that writes to InfluxDB\n* Uses the httpjson plugin to read in JSON data\n * The plugin has some limitations. It cannot read tags that are nested, as well as cannot perform multiple rights for one read. Due to this, it cannot currently handle an endpoint talking to multiple services on the same node, as well as is unable to read from the Contiv Netplugin API directly.\n* The telegraf.conf configuration file has the python server with each endpoint as scraping points.\n\n\n###telegrafdatasource.py\n========================\n* Python server that handles two requests.\n * When queried with the url route, \"/services\", it calls the Contiv Netplugin API to gather metadata for the front end. Returns a JSON object with the following keys:\n * ancestors_struct: {JSON} Maps container ids to the service it belongs to.\n * children_struct: {JSON} Maps service name to the containers it holds.\n * labels: {JSON} Maps container Id to a JSON that has its label mappings.\n * serviceSelectors: {JSON} Maps service name to a JSON that has its label selector mappings.\n * All other routes are assumed to be an endpoint container(ex. \"/11.1.1.2\"). It will use Contiv Netplugin's API and will look up this endpoint to get its traffic. Note that the endpoint being looked up must also be running on the same node as this server. This will return a JSON object that Telegraf can read and then write to InfluxDB. The JSON object has the following keys:\n \t* EndpointIP: The endpoint IP\n \t* ServiceIP: The Service IP it's connecting to.\n \t* ProviderIP: The Provider IP it's connecting to.\n \t* BytesIn: Bytes In from the Endpoint IP to the Provider IP\n \t* BytesOut: Bytes Out from the Endpoint IP to the Provider IP\n \t* PacketsIn: Packets In from the Endpoint IP to the Provider IP\n \t* PacketsOut: Packets Out from the Endpoint IP to the Provider IP\n\n###Limitations\n===============\n* Due to the limitations of the telegraf httpjson plugin, the backend cannot currently handle an endpoint talking to multiple services on the same node. Future plan is to write our own plugin for telegraf, or to build our own data aggregator. This will also eliminate the need for the python server\n\n\n\n" }, { "alpha_fraction": 0.4577122628688812, "alphanum_fraction": 0.4634064733982086, "avg_line_length": 38.7599983215332, "blob_id": "4421e1b6b1115567986c46720fa755783c737b99", "content_id": "f3a742ed80c4c01f5ffecbd1ade7b18ae84591fc", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5971, "license_type": "permissive", "max_line_length": 89, "num_lines": 150, "path": "/app/components/graphobjects/policy/nodeselectionpolicy.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * This policy is used to add a select node feature.\n * Supports selecting multiple nodes by using the ctrl key.\n */\nangular.module('contiv.graph')\n .factory('NodeSelectionPolicy', ['Policy', function (Policy) {\n\n \tclass NodeSelectionPolicy extends Policy.Policy {\n /**\n * Constructs the object.\n */\n constructor() {\n super(\"NodeSelectionPolicy\");\n }\n\n /**\n * Called when policy is installed\n * Overwrites the on drag event of the graph\n * \n * @param {Graph} graph The graph it is \n \t\t * installed on\n \t\t */\n initialize(graph) {\n if (this.initialized) {\n return;\n }\n super.initialize(graph);\n var state = graph.state.NodeSelectionPolicy = {};\n state.selectedNodes = [];\n var consts = graph.consts.NodeSelectionPolicy = {};\n consts.selectedClass = \"selected\";\n //overwritting graph's node on drag event to support\n //moving multiple nodes at once\n var drag = graph.drag;\n drag.on('drag', function(args) {\n \tvar thisGraph = graph;\n \tif (thisGraph.consts.NodeSelectionPolicy != null) {\n \t\tvar selectedClass = thisGraph.consts.NodeSelectionPolicy.selectedClass;\n \t\tvar selection = d3.selectAll( '.' +selectedClass);\n\n if( selection[0].indexOf( this)==-1) {\n selection.classed(selectedClass, false);\n selection = d3.select( this);\n selection.classed(selectedClass, true);\n } \n\n selection.attr(\"transform\", function( d, i) {\n d.x += d3.event.dx;\n d.y += d3.event.dy;\n return \"translate(\" + [ d.x,d.y ] + \")\"\n });\n thisGraph.updateGraph();\n \t}\n\n })\n }\n\n /**\n * Adds the given node to the array of selected nodes\n *\n * @param {D3Object} d3Node The d3 node\n * @param {Node} nodeData Matching Node object\n */\n addSelectNode(d3Node, nodeData) {\n var thisGraph = this.graph,\n state = thisGraph.state.NodeSelectionPolicy,\n consts = thisGraph.consts.NodeSelectionPolicy;\n\n d3Node.classed(consts.selectedClass, true);\n state.selectedNodes.push(nodeData);\n }\n\n /**\n * Removes the given node from the array of selected nodes.\n *\n * @param {D3Object} d3Node The d3 node\n * @param {Node} nodeData Matching node object \n */\n removeSelectFromNode(d3Node, nodeData) {\n var thisGraph = this.graph,\n state = thisGraph.state.NodeSelectionPolicy,\n consts = thisGraph.consts.NodeSelectionPolicy;\n\n thisGraph.circles.filter(function(cd) {\n return cd.id === nodeData.id;\n }).classed(consts.selectedClass, false);\n var index = state.selectedNodes.indexOf(nodeData);\n state.selectedNodes.splice(index, 1);\n }\n\n /**\n * Removes all selected nodes.\n */\n removeAllSelectedNodes() {\n var thisGraph = this.graph,\n state = thisGraph.state.NodeSelectionPolicy,\n consts = thisGraph.consts.NodeSelectionPolicy;\n\n thisGraph.circles.classed(consts.selectedClass, false);\n state.selectedNodes = [];\n }\n\n /**\n * On Mousedown, determines whether to change the\n * selected status of the clicked node.\n *\n * @param {D3Object} d3node The d3 node\n * @param {Node} d Matching Node Object \n */\n mousedown(d3node, d) {\n var thisGraph = this.graph,\n state = thisGraph.state.NodeSelectionPolicy;\n d3.event.stopPropagation();\n if (d3.event.ctrlKey) {\n if (state.selectedNodes.indexOf(d) > -1) {\n this.removeSelectFromNode(d3node, d);\n } else {\n this.addSelectNode(d3node, d);\n }\n } else if (state.selectedNodes.indexOf(d) == -1) {\n //if no control key, and clicked not selected node,\n //remove all of current selection\n this.removeAllSelectedNodes();\n }\n }\n\n /**\n * On Mouseup, determines whether to change the\n * selected status of the clicked node.\n *\n * @param {D3Object} d3node The d3 node\n * @param {Node} d Matching Node Object\n */\n mouseup(d3node, d) {\n var thisGraph = this.graph,\n state = thisGraph.state.NodeSelectionPolicy;\n if (!d3.event.ctrlKey) {\n //if length is greater than 1, then we are moving multiple nodes\n //leave them all highlighted\n //otherwise we are just moving one node, so unhighlight\n if (state.selectedNodes.length <= 1) {\n this.removeSelectFromNode(d3node, d);\n }\n }\n }\n }\n return {\n Policy: NodeSelectionPolicy\n }\n}]);\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.571474552154541, "alphanum_fraction": 0.571474552154541, "avg_line_length": 31.69473648071289, "blob_id": "e2493737f57bf271eb84c10401579c1d1493acea", "content_id": "9a34e7e44ccb979865a6ae70464f7409844ce8db", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3106, "license_type": "permissive", "max_line_length": 104, "num_lines": 95, "path": "/app/settings/nodes/nodedetails.component.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "import { Component, Inject, OnInit, NgZone } from '@angular/core';\nimport { ActivatedRoute, Router } from \"@angular/router\";\nimport { CRUDHelperService } from \"../../components/utils/crudhelperservice\";\nimport { BgpsModel } from \"../../components/models/bgpsmodel\";\n\n@Component({\n selector: 'nodedetails',\n templateUrl: './nodedetails.html'\n})\nexport class NodeDetailsComponent implements OnInit {\n node:any = {};\n mode:string = 'details';\n\n infoselected: boolean;\n statskey: string;\n\n constructor(private activatedRoute:ActivatedRoute,\n private router:Router,\n private ngZone:NgZone,\n private bgpsModel:BgpsModel,\n private crudHelperService:CRUDHelperService) {\n var component = this;\n\n /**\n * To show edit or details screen based on the route\n */\n function setMode() {\n if (activatedRoute.routeConfig.path.includes('edit')) {\n component.mode = 'edit';\n } else {\n component.mode = 'details';\n }\n }\n\n setMode();\n this.statskey = this.activatedRoute.snapshot.params['key'];\n this.infoselected = true;\n }\n\n ngOnInit() {\n var component = this;\n component.crudHelperService.stopLoader(component);\n\n component.bgpsModel.getModelByKey(component.activatedRoute.snapshot.params['key'], false, 'key')\n .then(function successCallBack(node) {\n component.node = node;\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n }, (error) => {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n });\n }\n\n returnToNode() {\n this.router.navigate(['../../list'], {relativeTo: this.activatedRoute});\n }\n\n returnToNodeDetails() {\n this.router.navigate(['../../details', this.node.key], {relativeTo: this.activatedRoute});\n }\n\n cancelDetails() {\n this.returnToNode();\n }\n\n cancelEditing() {\n this.returnToNodeDetails();\n }\n\n editNode() {\n this.router.navigate(['../../edit', this.node.key], {relativeTo: this.activatedRoute});\n }\n\n\n deleteNode() {\n var component = this;\n component.crudHelperService.startLoader(component);\n component.bgpsModel.delete(component.node).then(\n function successCallback(result) {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n component.crudHelperService.showNotification(\"Node: Deleted\", result);\n component.returnToNode();\n }, function errorCallback(result) {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n component.crudHelperService.showServerError(\"Node: Delete failed\", result);\n });\n }\n}\n" }, { "alpha_fraction": 0.538269579410553, "alphanum_fraction": 0.5413200259208679, "avg_line_length": 30.365217208862305, "blob_id": "277b8b0d6f9168b548a06b1ff4653621cf72c4dd", "content_id": "8a71ccceb8d18bdd017e2cb5c42bd34514be2f1d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3606, "license_type": "permissive", "max_line_length": 128, "num_lines": 115, "path": "/app/firstrunwizard/firstrunwizardservice.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 10/29/16.\n */\n\n\nimport { Injectable } from \"@angular/core\";\nimport { NetworkService } from \"../components/utils/networkservice\";\nimport { NetworksModel } from \"../components/models/networksmodel\";\n\n@Injectable()\nexport class FirstRunWizardService {\n public setting:any;\n public aciSetting:any;\n public newNetwork: any;\n public globalInspect:any = {};\n public clusterMode:string = '';\n public skipArray: Array<boolean> = [false, false, false];\n public defaults: any = {};\n public showLoader: boolean = true;\n\n constructor(private networkService:NetworkService,\n private networksModel: NetworksModel) {\n this.initialize();\n }\n\n initialize(){\n this.setting = {\n networkInfraType: '',\n vlans: '',\n vxlans: '',\n fwdMode: '',\n arpMode: ''\n };\n this.aciSetting = {\n key: '',\n enforcePolicies: 'no',\n includeCommonTenant: 'no',\n name: '',\n nodeBindings: '',\n pathBindings: '',\n physicalDomain: ''\n };\n this.newNetwork = {\n networkName: '',\n encap: 'vxlan',\n subnet: '',\n gateway: '',\n tenantName: '',\n key: '',\n nwType: '',\n pktTag: null,\n cfgdTag: ''\n }\n }\n\n getNetworkSettings() {\n var wizardservice = this;\n this.showLoader = true;\n this.networkService.getSettings()\n .then((result) => {\n wizardservice.showLoader = false;\n wizardservice.setting = result;\n wizardservice.defaults['setting'] = Object.assign({}, wizardservice.setting);\n }, (error) => {}\n )\n }\n\n getAciSettings() {\n var wizardservice = this;\n this.networkService.getAciSettings()\n .then((result) => {\n wizardservice.aciSetting = result\n wizardservice.defaults['aciSetting'] = Object.assign({}, wizardservice.aciSetting);\n },(error) => {})\n }\n\n getGlobalInspect(){\n var wizardservice = this;\n this.networkService.getGlobalInspect()\n .then((result) => {\n wizardservice.globalInspect = result['Oper'];\n wizardservice.clusterMode = wizardservice.globalInspect['clusterMode'];\n }, (error) => {})\n }\n\n updateSettings():Promise<any> {\n var wizardservice = this;\n\n if(wizardservice.setting.networkInfraType === 'aci')\n wizardservice.networkService.setAciMode(true);\n else\n wizardservice.networkService.setAciMode(false);\n\n var p1 = new Promise((resolve, reject) => {\n if(wizardservice.skipArray[0] == true)\n resolve(\"skip\")\n else\n resolve(wizardservice.networkService.updateSettings(wizardservice.setting));\n });\n\n return p1.then((res) => {\n if(wizardservice.skipArray[1] == true)\n return \"skip\";\n else\n return wizardservice.networkService.updateAciSettings(wizardservice.aciSetting);\n }).then((res) => {\n if(wizardservice.skipArray[2] == true)\n return \"skip\";\n else{\n wizardservice.newNetwork.key = wizardservice.newNetwork.tenantName + ':' + wizardservice.newNetwork.networkName;\n return wizardservice.networksModel.create(wizardservice.newNetwork, undefined)\n }\n });\n }\n}" }, { "alpha_fraction": 0.5977388620376587, "alphanum_fraction": 0.5995623469352722, "avg_line_length": 36.5616455078125, "blob_id": "f366ce001a7eaa7aedc50d61f1e042a1f9451ec5", "content_id": "a56774727b01dfb37ed6937b47031c3899a32084", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2742, "license_type": "permissive", "max_line_length": 110, "num_lines": 73, "path": "/app/components/directives/settings/userprofileedit.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 1/19/17.\n */\nimport { Component, Inject, NgZone, Input, OnInit, EventEmitter, Output } from '@angular/core';\nimport { ActivatedRoute, Router } from \"@angular/router\";\nimport { User } from \"../../../settings/users/usercreate.component\";\nimport { UsersModel } from \"../../models/usersmodel\";\nimport { CRUDHelperService } from \"../../utils/crudhelperservice\";\nimport { ContivGlobals } from \"../../models/contivglobals\";\n\nexport enum ProfileDisplayType{\n modal,\n component\n}\n\n@Component({\n selector: 'userprofileedit',\n templateUrl: './userprofileedit.html'\n})\nexport class UserProfileEditComponent implements OnInit {\n public ProfileDisplayType = ProfileDisplayType;\n user:User = {username: '', password: '', first_name: '', last_name: '', disable: false};\n public showLoader: boolean = true;\n @Input('username') username: string = '';\n @Input('displayType') displayType: ProfileDisplayType = ProfileDisplayType.component;\n @Output('close') close: EventEmitter<any>;\n\n constructor(private ngZone: NgZone,\n private usersModel:UsersModel,\n private crudHelperService:CRUDHelperService) {\n\n var component = this;\n this.user = {username: '', first_name: '', last_name: '', disable: false};\n this.close = new EventEmitter<any>();\n }\n\n ngOnInit(){\n var component = this;\n var url = ContivGlobals.USERS_ENDPOINT + this.username + '/';\n this.usersModel.getModelByKey(this.username, false, 'username', url)\n .then((user) => {\n component.user = user;\n component.crudHelperService.stopLoader(component);\n }, (error) => {\n component.crudHelperService.stopLoader(component);\n });\n }\n\n closeEdit(){\n this.close.emit();\n }\n\n saveUser(formvalid: boolean) {\n var component = this;\n if (formvalid) {\n component.crudHelperService.startLoader(component);\n\n component.usersModel.save(component.user).then(\n function successCallback(result) {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n component.crudHelperService.showNotification(\"User: Updated\", result.username.toString());\n component.closeEdit();\n }, function errorCallback(result) {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n component.crudHelperService.showServerError(\"User: Update failed\", result);\n });\n }\n }\n}\n" }, { "alpha_fraction": 0.49471545219421387, "alphanum_fraction": 0.49837398529052734, "avg_line_length": 32.18918991088867, "blob_id": "f57516362209459aff94b7958d08e0482de17012", "content_id": "931f38cc5ce65dc6620e9807821957ffce6d1688", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2460, "license_type": "permissive", "max_line_length": 75, "num_lines": 74, "path": "/app/components/graphobjects/policy/policy.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Base policy class for the graph object\n * \n * Policies are used to isolate features for a graph.\n * Policies can be installed on nodes, links, or the graph.\n * Each policy has interaction handlers that will be called by the graph\n * if installed. Policies can also modify graph functions (see QTipPolicy).\n * Multiple policies can be installed for a node or link. \n * \n * To write your own policy, create a new factory that uses the policy\n * you want to inherit as a dependency, and extend its policy. \n * Return the class object with Policy as key, and \n * add the policy to the PolicyService factory.\n * \n * For saving state or consts for the policy, create a namespace\n * in graph.state and graph.consts.\n * Ex. \n * graph.state.myPolicy = {};\n * graph.consts.myPolicy = {};\n * \n */\nangular.module('contiv.graph')\n .factory('Policy', [function () {\n class Policy {\n /**\n * Constructs the object.\n *\n * @param {string} policyName The policy name\n */\n constructor(policyName) {\n this.policyName = policyName;\n this.graph = null;\n this.initialized = false;\n }\n\n /**\n * Called when the policy is installed.\n * \n * @param {Graph} graph The Graph that the policy is\n * being installed on\n */\n initialize(graph) {\n if (this.initialized) {\n return; \n }\n this.initialized = true;\n this.graph = graph;\n }\n\n /**\n * Handler, meant to be overridden in subclasses\n *\n * @param {d3 object} d3obj The d3object\n * @param {Node/Link/Graph} d The object it was\n * installed for. \n */\n mouseover (d3obj, d) {}\n dblclick(d3obj, d) {}\n contextmenu(d3obj, d) {}\n mouseout(d3obj, d) {}\n mousedown(d3obj, d) {}\n mouseup(d3obj, d) {}\n\n /**\n * Will be called when the graph is being destroyed.\n * Used to remove any elements or bindings the policy\n * has added.\n */\n destroy() {}\n }\n return {\n Policy: Policy\n }\n}]);\n\n\n\n\n" }, { "alpha_fraction": 0.5234042406082153, "alphanum_fraction": 0.5234042406082153, "avg_line_length": 32.130435943603516, "blob_id": "caaaa7dbf1a645c48bcd8706213cbed7339457ee", "content_id": "9961488ecf58202e2477f67abbafe252f575ecb8", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3055, "license_type": "permissive", "max_line_length": 76, "num_lines": 92, "path": "/app/components/graphobjects/policy/savestatepolicy.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * This policy provides a way for properties to be saved \n * between view changes\n * \n * It modifies the destroy function to also pass in an object that\n * will have all its properties saved and will be available \n * on graph load. When saving variables to the object, namespace with\n * the policy name.\n * \n * This policy must be loaded first in order for it saved variables \n * to be loaded when the view comes back to the graph\n */\nangular.module('contiv.graph')\n .factory('SaveStatePolicy', ['Policy', function (Policy) {\n \tclass SaveStatePolicy extends Policy.Policy {\n \t\t\n \t\t/**\n \t\t * Takes in the angular service to which it will\n \t\t * save it's properties to.\n \t\t *\n \t\t * @param {Object} savedState Object to save \n \t\t * properties to\n \t\t */\n \t\tconstructor(savedState) {\n \t\t\tsuper('SaveStatePolicy');\n \t\t\tthis.savedState = savedState;\n \t\t}\n\n \t\t/**\n \t\t * Called when the policy is installed\n \t\t * Modifies the destroy method \n \t\t * and adds a load method to the graph\n \t\t *\n \t\t * @param {Graph} graph The graph it is \n \t\t * installed on\n \t\t */\n \t\tinitialize(graph) {\n \t\t\tthis.graph = graph;\n \t\t\tvar thisPolicy = this;\n \t\t\tgraph.destroy = function() {\n \t\t\t\tthisPolicy.graphDestroy.call(graph, thisPolicy.savedState);\n \t\t\t};\n\n \t\t\tgraph.load = function(savedState) {\n \t\t\t\tthisPolicy.graphLoad.call(graph, savedState);\n \t\t\t}\n \t\t}\n\n \t\t/**\n \t\t * Will override the graph's default destroy, with \n \t\t * this policy's savedState passed in.\n \t\t * Called with this as the graph\n \t\t *\n \t\t * @param {Object} savedState The saved state\n \t\t */\n \t\tgraphDestroy(savedState) {\n var thisGraph = this;\n _(thisGraph.defaultNodePolicies).forEach(function(policy) {\n policy.destroy(savedState);\n });\n _(thisGraph.defaultPathPolicies).forEach(function(policy) {\n policy.destroy(savedState);\n });\n for (var key in thisGraph.bindings) {\n $(window).off(key, thisGraph.bindings[key]);\n }\n }\n\n /**\n * Will be called with the graph as this\n * Used to have all other policies use the load state\n *\n * @param {Object} savedState The saved state\n */\n graphLoad(savedState) {\n \tvar thisGraph = this;\n _(thisGraph.defaultNodePolicies).forEach(function(policy) {\n \tif (policy.load != null) {\n \tpolicy.load(savedState);\n \t}\n });\n _(thisGraph.defaultPathPolicies).forEach(function(policy) {\n \tif (policy.load != null) {\n \tpolicy.load(savedState);\n \t}\n });\n }\n \t}\n \treturn {\n \t\tPolicy: SaveStatePolicy\n \t}\n}]);\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6829880475997925, "alphanum_fraction": 0.6873822808265686, "avg_line_length": 30.254901885986328, "blob_id": "74031cb509bd3aa6d3230e02506cfd4ceab1c4a4", "content_id": "025260b320cb11a0a658c417caaf51ce80091025", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1593, "license_type": "permissive", "max_line_length": 78, "num_lines": 51, "path": "/app/settings/settings.module.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 10/25/16.\n */\nimport { NgModule } from '@angular/core';\nimport { FormsModule } from \"@angular/forms\";\nimport { CommonModule } from \"@angular/common\";\nimport { RouterModule } from \"@angular/router\";\nimport { DirectivesModule } from \"../components/directives/directives.module\";\nimport { NetworkSettingsComponent } from \"./networksettingctrl\";\nimport { SettingsMenuComponent } from \"./settingsmenu.component\";\nimport { NodeListComponent } from \"./nodes/nodelist.component\";\nimport { NodeCreateComponent } from \"./nodes/nodecreate.component\";\nimport { NodeDetailsComponent } from \"./nodes/nodedetails.component\";\nimport { NodeInfoComponent } from \"./nodes/nodeinfo.component\";\nimport { NodeStatsComponent } from \"./nodes/nodestats.component\";\nimport { LdapConfigComponent } from \"./ldapconfiguration\";\n\n@NgModule({\n imports: [\n FormsModule,\n CommonModule,\n RouterModule,\n DirectivesModule\n ],\n declarations: [\n SettingsMenuComponent,\n NetworkSettingsComponent,\n NodeListComponent,\n NodeCreateComponent,\n NodeDetailsComponent,\n NodeInfoComponent,\n NodeStatsComponent,\n LdapConfigComponent\n ],\n exports: [\n SettingsMenuComponent,\n NetworkSettingsComponent,\n NodeListComponent,\n NodeCreateComponent,\n NodeDetailsComponent,\n NodeInfoComponent,\n NodeStatsComponent,\n LdapConfigComponent,\n FormsModule,\n CommonModule,\n RouterModule,\n DirectivesModule\n ]\n})\nexport class SettingsModule {\n}" }, { "alpha_fraction": 0.6673930883407593, "alphanum_fraction": 0.6720239520072937, "avg_line_length": 46.07692337036133, "blob_id": "cfc6c110922c6e70683606e420d582fdc4e11e94", "content_id": "3b6cdde44830ff2ef77ee06a35d0630f631d51b4", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3671, "license_type": "permissive", "max_line_length": 105, "num_lines": 78, "path": "/e2e-tests/storage_policies/storagepolicypagespec.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 8/17/16.\n */\n\nvar StoragePolicyPage = require('./storagepolicypageobject');\n\ndescribe(\"Storage policy\", function(){\n var storagePolicyList = new StoragePolicyPage.storagePolicyList();\n var storagePolicyCreate = new StoragePolicyPage.storagePolicyCreate();\n var storagePolicyDetails = new StoragePolicyPage.storagePolicyDetails();\n\n beforeEach(function(){\n browser.get(\"#/m/storagepolicies/list\");\n });\n \n it(\"Create policy\", function(){\n testConfig.clickLink(storagePolicyList.createButton);\n storagePolicyCreate.policyName.sendKeys(testConfig.storagePolicy.name);\n storagePolicyCreate.policyPool.clear().then(function(){\n storagePolicyCreate.policyPool.sendKeys(testConfig.storagePolicy.pool);\n });\n storagePolicyCreate.policySize.clear().then(function(){\n storagePolicyCreate.policySize.sendKeys(testConfig.storagePolicy.size);\n });\n storagePolicyCreate.collapsible.each(function(element, index){\n browser.actions()\n .mouseMove(element, {x: 0, y: 0}) // 100px from left, 100 px from top of plot0\n .click()\n .perform();\n });\n storagePolicyCreate.filesystem.name.click();\n storagePolicyCreate.filesystem.type.click();\n storagePolicyCreate.filesystem.command.clear().then(function(){\n storagePolicyCreate.filesystem.command.sendKeys(testConfig.storagePolicy.fileSystem.command);\n });\n storagePolicyCreate.filesystem.addButton.click();\n storagePolicyCreate.runtime.snapshot.click();\n storagePolicyCreate.runtime.frequency.clear().then(function(){\n storagePolicyCreate.runtime.frequency.sendKeys(testConfig.storagePolicy.snapshot.frequency);\n });\n storagePolicyCreate.runtime.keep.clear().then(function(){\n storagePolicyCreate.runtime.keep.sendKeys(testConfig.storagePolicy.snapshot.noofsnaps);\n });\n storagePolicyCreate.runtime.writeiops.sendKeys(testConfig.storagePolicy.readWriteOp.writeiops);\n storagePolicyCreate.runtime.readiops.sendKeys(testConfig.storagePolicy.readWriteOp.readiops);\n storagePolicyCreate.runtime.writebps.sendKeys(testConfig.storagePolicy.readWriteOp.writebps);\n storagePolicyCreate.runtime.readbps.sendKeys(testConfig.storagePolicy.readWriteOp.readbps);\n storagePolicyCreate.backends.driver.click();\n storagePolicyCreate.backends.mount.click();\n storagePolicyCreate.backends.snapshotdriver.click();\n storagePolicyCreate.policyCreate.submit();\n expect(storagePolicyCreate.serverMessage.isPresent()).toBeFalsy();\n });\n \n it(\"Verify create\", function(){\n testConfig.verifyCreate(storagePolicyList.storagepolicyname, testConfig.storagePolicy.name);\n });\n\n it('verify details', function(){\n storagePolicyList.storagepolicyname.click().then(function(){\n tableFields = testConfig.getVerificationList(testConfig.storagePolicy);\n storagePolicyDetails.collapsible.each(function(element, index){\n element.click();\n });\n storagePolicyDetails.tableData.each(function(element,index){\n if(index < 16) {\n element.all(by.css(\"td\")).get(1).getText().then(function (text) {\n expect(tableFields).toContain(text);\n });\n }\n });\n storagePolicyDetails.editButton.click().then(function(){\n expect(storagePolicyDetails.editText.getText()).toEqual(\"(Edit)\");\n });\n });\n\n });\n});" }, { "alpha_fraction": 0.5705186724662781, "alphanum_fraction": 0.5705186724662781, "avg_line_length": 34.84782791137695, "blob_id": "a61946361f1c511640ddedf45d1242a92fe7d5ce", "content_id": "be3e2f6b67c018a54f2636240e9fb43bbdbe9b25", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3297, "license_type": "permissive", "max_line_length": 124, "num_lines": 92, "path": "/app/appprofiles/appprofilecreate.component.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "import { Component, Inject, OnInit, NgZone } from \"@angular/core\";\nimport { ActivatedRoute, Router } from \"@angular/router\";\nimport * as _ from 'lodash';\nimport { CRUDHelperService } from \"../components/utils/crudhelperservice\";\nimport { AppProfilesModel } from \"../components/models/appprofilesmodel\";\nimport { OrganizationsModel } from \"../components/models/organizationsmodel\";\n\n@Component({\n selector: 'appprofilecreate',\n templateUrl: './appprofilecreate.html'\n})\n\nexport class AppProfileCreateComponent implements OnInit {\n newAppProfile:any = {};\n tenants:any[] = [];\n\n constructor(private activatedRoute:ActivatedRoute,\n private router:Router,\n private ngZone:NgZone,\n private organizationsModel:OrganizationsModel,\n private crudHelperService:CRUDHelperService,\n private appProfilesModel:AppProfilesModel) {\n var component = this;\n\n function resetForm() {\n crudHelperService.stopLoader(component);\n component.newAppProfile = {\n key: '',\n appProfileName: '',\n endpointGroups: [],\n tenantName: ''\n };\n }\n\n resetForm();\n }\n\n ngOnInit() {\n var component = this;\n component.crudHelperService.startLoader(component);\n\n function getTenants(reload:boolean) {\n component.organizationsModel.get(reload)\n .then((result) => {\n component.tenants = result;\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n }, (error) => {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n });\n }\n\n getTenants(false);\n }\n\n returnToAppProfiles() {\n this.router.navigate(['../list'], {relativeTo: this.activatedRoute});\n }\n\n cancelCreating() {\n this.returnToAppProfiles();\n }\n\n createAppProfile(formvalid:boolean) {\n var component = this;\n if (formvalid) {\n this.crudHelperService.startLoader(this);\n component.newAppProfile.key = this.appProfilesModel.generateKey(this.newAppProfile);\n this.appProfilesModel.create(component.newAppProfile, undefined)\n .then((result) => {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n component.crudHelperService.showNotification(\"Application profile: Created\", result.key.toString());\n });\n component.returnToAppProfiles();\n }, (error) => {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n component.crudHelperService.showServerError(\"Application profile: Create failed\", error);\n });\n }\n }\n\n updateTenant(tenantName:string, appGroupSelComponent: any) {\n this.newAppProfile.tenantName = tenantName;\n appGroupSelComponent.getApplicationGroups();\n }\n}" }, { "alpha_fraction": 0.6255673170089722, "alphanum_fraction": 0.6278365850448608, "avg_line_length": 39.45918273925781, "blob_id": "2905deb03b89e7c889494de6e3b80a033221062e", "content_id": "be1acaf0a93dc82cfde17602e6988cf04bca679c", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3966, "license_type": "permissive", "max_line_length": 149, "num_lines": 98, "path": "/app/network_policies/bandwidthpolicycreatectrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/*\n/**\n * Created by hardik gandhi on 6/14/16.\n */\nimport { Component, Inject, OnInit, NgZone } from '@angular/core';\nimport { ActivatedRoute, Router } from \"@angular/router\";\nimport { NetprofilesModel } from \"../components/models/netprofilesmodel\";\nimport { CRUDHelperService } from \"../components/utils/crudhelperservice\";\nimport { PolicyTab } from \"./networkpoliciestabsctrl\";\nimport { OrganizationsModel } from \"../components/models/organizationsmodel\";\n\n@Component({\n selector: 'bandwidthpolicycreate',\n templateUrl: './bandwidthpolicycreate.html'\n})\nexport class BandwidthPolicyCreateComponent implements OnInit {\n newPolicy:any;\n tenants:any[] = [];\n\n constructor(private activatedRoute: ActivatedRoute,\n private router: Router,\n private ngZone: NgZone,\n private organizationsModel: OrganizationsModel,\n private netprofilesModel: NetprofilesModel,\n private crudHelperService: CRUDHelperService){\n var bandwidthPolicyCreateCtrl = this;\n\n function resetForm() {\n crudHelperService.stopLoader(bandwidthPolicyCreateCtrl);\n bandwidthPolicyCreateCtrl.newPolicy = {\n profileName: '',\n tenantName: '',\n bandwidth: '',\n bandwidthUnit: 'mbps',\n DSCP: 0,\n burst: 0\n };\n }\n resetForm();\n }\n\n ngOnInit() {\n var component = this;\n component.crudHelperService.startLoader(component);\n\n function getTenants(reload: boolean) {\n component.organizationsModel.get(reload)\n .then((result) => {\n component.tenants = result;\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n }, (error) => {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n });\n }\n\n getTenants(false);\n }\n\n returnToPolicies() {\n this.router.navigate(['../../list', {policyTab: PolicyTab.bandwidth}], { relativeTo: this.activatedRoute });\n }\n\n cancelCreating() {\n this.returnToPolicies();\n }\n\n createPolicy(validform: boolean) {\n var bandwidthPolicyCreateCtrl = this;\n if (validform) {\n bandwidthPolicyCreateCtrl.crudHelperService.startLoader(bandwidthPolicyCreateCtrl);\n\n bandwidthPolicyCreateCtrl.newPolicy.key =\n bandwidthPolicyCreateCtrl.netprofilesModel.generateKey(bandwidthPolicyCreateCtrl.newPolicy);\n\n bandwidthPolicyCreateCtrl.newPolicy.bandwidth = bandwidthPolicyCreateCtrl.newPolicy.bandwidthNumber\n + \" \"+ bandwidthPolicyCreateCtrl.newPolicy.bandwidthUnit;\n\n if (bandwidthPolicyCreateCtrl.newPolicy.DSCP == null) {//DSCP is null or undefined\n bandwidthPolicyCreateCtrl.newPolicy.DSCP = 0;\n }\n if (bandwidthPolicyCreateCtrl.newPolicy.burst == null) {//burst is null or undefined\n bandwidthPolicyCreateCtrl.newPolicy.burst = 0;\n }\n bandwidthPolicyCreateCtrl.netprofilesModel.create(bandwidthPolicyCreateCtrl.newPolicy, undefined).then(function successCallback(result) {\n bandwidthPolicyCreateCtrl.crudHelperService.stopLoader(bandwidthPolicyCreateCtrl);\n bandwidthPolicyCreateCtrl.crudHelperService.showNotification(\"Bandwidth policy: Created\", result.key.toString());\n bandwidthPolicyCreateCtrl.returnToPolicies();\n }, function errorCallback(result) {\n bandwidthPolicyCreateCtrl.crudHelperService.stopLoader(bandwidthPolicyCreateCtrl);\n bandwidthPolicyCreateCtrl.crudHelperService.showServerError(\"Bandwidth policy: Create failed\", result);\n });\n }\n }\n}\n\n" }, { "alpha_fraction": 0.47150570154190063, "alphanum_fraction": 0.4727054536342621, "avg_line_length": 32.72916793823242, "blob_id": "6e8fb45ec3c82906aef33942e66fe81bebd89889", "content_id": "04df8912d02b184ebdd0468f79f87d0ea6d72f1f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1667, "license_type": "permissive", "max_line_length": 91, "num_lines": 48, "path": "/app/settings/settingsmenu.html", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "<div class=\"ui sixteen column grid\">\r\n <div class=\"ui row pageHeader\">\r\n <div class=\"left aligned eight wide column\">\r\n <div class=\"content pageTitle\">Settings</div>\r\n </div>\r\n <div class=\"right aligned eight wide column\">&nbsp;</div>\r\n </div>\r\n <div class=\"ui row breadcrumbRow\">\r\n <div class=\"ui sixteen wide column\">\r\n <div class=\"breadcrumbs\"></div>\r\n </div>\r\n </div>\r\n\r\n <div class=\"ui row\" style=\"margin-bottom: 30px;\">\r\n <div class=\"ui sixteen wide column\">\r\n\r\n <div class=\"ui tabular menu\">\r\n <a class=\"item\" [routerLink]=\"['organizations']\" routerLinkActive=\"active\">\r\n Tenants\r\n </a>\r\n <a class=\"item\" [routerLink]=\"['users']\" routerLinkActive=\"active\">\r\n User Management\r\n </a>\r\n <a class=\"item\" [routerLink]=\"['authorization']\" routerLinkActive=\"active\">\r\n Authorizations\r\n </a>\r\n <a class=\"item\" [routerLink]=\"['nodes']\" routerLinkActive=\"active\">\r\n Nodes (BGP)\r\n </a>\r\n <a class=\"item\" [routerLink]=\"['networks']\" routerLinkActive=\"active\">\r\n Network Defaults\r\n </a>\r\n <a class=\"item\" [routerLink]=\"['ldap']\" routerLinkActive=\"active\">\r\n LDAP Settings\r\n </a>\r\n </div>\r\n\r\n </div>\r\n </div>\r\n\r\n <div class=\"ui row\">\r\n <div class=\"ui sixteen wide column\">\r\n\r\n <router-outlet></router-outlet>\r\n\r\n </div>\r\n </div>\r\n</div>\r\n" }, { "alpha_fraction": 0.7307302355766296, "alphanum_fraction": 0.7342799305915833, "avg_line_length": 36.22641372680664, "blob_id": "a6635fbf21e7d4508ffcb9ab1ba2ba751f8a7847", "content_id": "329b255196daf2f50a640970647d83c917c755f7", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1972, "license_type": "permissive", "max_line_length": 81, "num_lines": 53, "path": "/app/applicationgroups/applicationgroups.module.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 10/21/16.\n */\nimport { NgModule } from '@angular/core';\nimport { FormsModule } from \"@angular/forms\";\nimport { CommonModule } from \"@angular/common\";\nimport { RouterModule } from \"@angular/router\";\nimport { DirectivesModule } from \"../components/directives/directives.module\";\nimport { PipesModule } from \"../components/pipes/pipes.module\";\nimport { ApplicationGroupCreateComponent } from \"./applicationgroupcreatectrl\";\nimport { ApplicationGroupDetailsComponent } from \"./applicationgroupdetailsctrl\";\nimport { IsolationPolicySelectionComponent } from \"./isolationpolicydirective\";\nimport { BandwidthPolicySelectionComponent } from \"./bandwidthpolicydirective\";\nimport { ContractGroupSelectionComponent } from \"./contractgroup.component\";\nimport { AppGrouplistComponent } from \"./applicationgrouplistctrl\";\nimport { ApplicationGroupStatsComponent } from \"./applicationgroupstats\";\nimport { ApplicationGroupInfoComponent } from \"./applicationgroupinfoctrl\";\n\n@NgModule({\n imports: [\n FormsModule,\n CommonModule,\n RouterModule,\n DirectivesModule,\n PipesModule\n ],\n declarations: [\n ApplicationGroupCreateComponent,\n ApplicationGroupDetailsComponent,\n IsolationPolicySelectionComponent,\n BandwidthPolicySelectionComponent,\n ContractGroupSelectionComponent,\n AppGrouplistComponent,\n ApplicationGroupStatsComponent,\n ApplicationGroupInfoComponent\n ],\n exports: [\n AppGrouplistComponent,\n ApplicationGroupCreateComponent,\n ApplicationGroupDetailsComponent,\n IsolationPolicySelectionComponent,\n BandwidthPolicySelectionComponent,\n ContractGroupSelectionComponent,\n ApplicationGroupStatsComponent,\n ApplicationGroupInfoComponent,\n FormsModule,\n CommonModule,\n RouterModule,\n DirectivesModule,\n PipesModule\n ]\n})\nexport class ApplicationGroupsModule {}" }, { "alpha_fraction": 0.5517957806587219, "alphanum_fraction": 0.5577322840690613, "avg_line_length": 25.690475463867188, "blob_id": "127e3feaad08668ce9d9bfd110d46c09fbd7c27f", "content_id": "33bb49949b6e629a2ba3161330da794917359d92", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3369, "license_type": "permissive", "max_line_length": 119, "num_lines": 126, "path": "/app/components/graphobjects/link/link.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * The base class for link objects for the graph.\n * Supports policies.\n * \n * To write your own link object, create a new factory that uses the link\n * you want to inherit as a dependency, and extend its link class. \n * Return the class object with Link as key\n * \n */\nangular.module('contiv.graph')\n .factory('Link', [function () {\n \tclass Link {\n \t\t/**\n \t\t * Constructs the object.\n \t\t *\n \t\t * @param {Node} sourceNode The source node\n \t\t * @param {Node} targetNode The target node\n \t\t */\n\t\t\tconstructor(sourceNode, targetNode) {\n\t\t\t\tthis.source = sourceNode;\n\t\t\t\tthis.target = targetNode;\n\t\t\t\tthis.hasPolicy = false;\n\t\t\t\tthis.pathPolicies = [];\n\t\t\t\tthis.graph = null;\n\t\t\t\tthis.initialized = false;\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Called when a link is added to the graph\n\t\t\t *\n\t\t\t * @param {Graph} graph The graph it is added to\n\t\t\t */\n\t\t\tinitialize(graph) {\n\t\t\t\tif (this.initialized == false) {\n\t\t\t\t\tthis.initialized = true;\n\t\t\t\t\tthis.graph = graph;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Called during the update graph for existing links\n\t\t\t *\n\t\t\t * @param {D3Object} d3path The d3 path\n\t\t\t * @param {Link} \t d Matching Link Object \n\t\t\t */\n\t\t\tupdateAttr(d3path, d) {\n\t\t\t\td3path.style('marker-end', 'url(#end-arrow)')\n\t\t .attr(\"d\", arrowPath);\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Called during the first update graph for a link\n\t\t\t *\n\t\t\t * @param {D3Object} d3path The d3 path\n\t\t\t * @param {Link} \t d Matching Link Object \n\t\t\t */\n\t\t\tnewPathAttr(d3path, d) {\n\t\t\t\td3path.attr('d', arrowPath);\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Calculates the arrow path\n\t\t\t *\n\t\t\t * @return {string} The path to draw\n\t\t\t */\n\t\t arrowPath() {\n\t\t \tvar d = this;\n\t\t var dx = d.target.x - d.source.x,\n\t\t dy = d.target.y - d.source.y,\n\t\t dr = Math.sqrt(dx * dx + dy * dy);\n\t\t return \"M\" + d.source.x + \",\" + d.source.y + \"A\" + dr + \",\" + dr + \" 0 0,1 \" + d.target.x + \",\" + d.target.y;\n\t\t }\n\n\t\t /**\n\t\t * Used to install policies that are called when this\n\t\t * link has a mouse event\n\t\t *\n\t\t * @param {Policy} policy The policy to install\n\t\t */\n\t\t\tinstallPathPolicy(policy) {\n\t\t\t\tthis.hasPolicy = true;\n\t\t\t\tthis.pathPolicies.push(policy);\n\t\t\t\tpolicy.initialize(this.graph);\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Used to uninstall policy for this link\n\t\t\t *\n\t\t\t * @param {Policy} policyRemove The policy to remove\n\t\t\t */\n\t\t\tuninstallPathPolicy(policyRemove) {\n\t\t\t\tvar policyRemoveName;\n\t\t\t\tvar thisPath = this;\n\t\t\t\tif (typeof policyRemove === 'string') {\n\t\t\t\t\tpolicyRemoveName = policyRemove;\n\t\t\t\t} else {\n\t\t\t\t\tpolicyRemoveName = policyRemove.policyName;\n\t\t\t\t}\n\t\t\t\t_(thisPath.pathPolicies).forEach(function(policy, index) {\n\t\t\t\t\tif (policy.policyName === policyRemoveName) {\n\t\t\t\t\t\tpolicy.destroy();\n\t\t\t\t\t\tthisPath.pathPolicies.splice(index, 1);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tif (thisPath.pathPolicies.length === 0) {\n\t\t\t\t\tthisPath.hasPolicy = false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Called when there is a mouse event for this path\n\t\t\t *\n\t\t\t * @param {string} event The mouse event\n\t\t\t * @param {D3Object} d3path The d3 path\n\t\t\t * @param {Object} d The matching link object\n\t\t\t */\n\t\t\tpathPolicyEvent(event, d3path, d) {\n\t\t\t\t_(d.pathPolicies).forEach(function(policy) {\n\t\t\t\t\tpolicy[event](d3path, d);\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tLink: Link\n\t\t}\n}]);\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5572709441184998, "alphanum_fraction": 0.5612549781799316, "avg_line_length": 33.050846099853516, "blob_id": "3b13797113456a568452ccde328570fa4a452c5e", "content_id": "67d1417425b473386de15d3e67cf5847a2788e93", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2008, "license_type": "permissive", "max_line_length": 123, "num_lines": 59, "path": "/app/components/utils/firstrunservice.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 3/27/17.\n */\nimport { Injectable } from '@angular/core';\nimport { Subject } from \"rxjs\";\nimport { Observable } from 'rxjs/Observable';\nimport { NetworksModel } from \"../models/networksmodel\";\nimport { OrganizationsModel } from \"../models/organizationsmodel\";\n\n@Injectable()\nexport class FirstRunService {\n\n private firstrunSubject: Subject<any> =new Subject<any>();\n firstrunObservable: Observable<any> = this.firstrunSubject.asObservable();\n firstRun:boolean = false;\n public firstRunCompleted: boolean = false;\n\n constructor(private networksModel: NetworksModel,\n private organizationsModel: OrganizationsModel){\n }\n\n /**\n * Should only be called after the user has been logged in.\n */\n setFirstRun(check?: boolean): Promise<any> {\n if (!this.firstRunCompleted || check) {\n return this.checkFirstRun().then(isFirstRun => {\n this.firstRun = isFirstRun;\n this.firstrunSubject.next(this.firstRun);\n this.firstRunCompleted = true;\n return this.firstRun;\n });\n } else {\n return new Promise((resolve, reject) => {resolve(this.firstRun)});\n }\n\n }\n\n private checkFirstRun(): Promise<any> {\n //if there are any tenants other than default or if there are any networks, we should not run the first run wizard.\n return this.networksModel.get(true)\n .then(networks => {\n if (networks.length) {\n return false;\n }\n return this.organizationsModel.get(true)\n .then(orgs => {\n if ((!orgs.length) || (orgs.length === 1 && orgs[0].tenantName === 'default')) {\n return true;\n }\n return false;\n });\n }, (error) => {});\n }\n\n public resetCheck() {\n this.firstRunCompleted = false;\n }\n}" }, { "alpha_fraction": 0.5725039839744568, "alphanum_fraction": 0.5725039839744568, "avg_line_length": 32.6533317565918, "blob_id": "1e8e4545c5aeea215098f83c7d33710b8eb25dfe", "content_id": "a1d47896725edce779b142a5d37969c26af0e40c", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2524, "license_type": "permissive", "max_line_length": 103, "num_lines": 75, "path": "/app/settings/users/usercreate.component.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "import { Component, Inject, OnInit, NgZone } from \"@angular/core\";\nimport { ActivatedRoute, Router } from \"@angular/router\";\nimport { CRUDHelperService } from \"../../components/utils/crudhelperservice\";\nimport { UsersModel } from \"../../components/models/usersmodel\";\nimport { OrganizationsModel } from \"../../components/models/organizationsmodel\";\nimport {ContivGlobals} from \"../../components/models/contivglobals\";\n\nexport interface User{\n username: string;\n password?: string;\n first_name: string;\n last_name: string;\n disable: false;\n}\n\n@Component({\n selector: 'usercreate',\n templateUrl: './usercreate.html'\n})\n\nexport class UserCreateComponent{\n public newUser: User = {username: '', password: '', first_name: '', last_name: '', disable: false};\n public username_regex = ContivGlobals.USERNAME_REGEX;\n public organizations:any[] = [];\n\n constructor(private activatedRoute: ActivatedRoute,\n private router: Router,\n private crudHelperService: CRUDHelperService,\n private usersModel: UsersModel,\n private ngZone: NgZone){\n var component = this;\n\n function resetForm() {\n crudHelperService.stopLoader(component);\n component.newUser = {\n username: '',\n password: '',\n first_name: '',\n last_name: '',\n disable: false\n }\n }\n\n resetForm();\n }\n\n returnToUsers(){\n this.router.navigate(['../list'], { relativeTo: this.activatedRoute });\n }\n\n cancelCreating(){\n this.returnToUsers();\n }\n\n createUser(formvalid: boolean){\n var component = this;\n if(formvalid){\n this.crudHelperService.startLoader(this);\n this.usersModel.create(component.newUser,ContivGlobals.USERS_ENDPOINT, 'username')\n .then((result) => {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n component.crudHelperService.showNotification(\"User: Created\",result.username);\n component.returnToUsers();\n }, (error) => {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n component.crudHelperService.showServerError(\"User: Create failed\",error);\n });\n }\n }\n\n}\n" }, { "alpha_fraction": 0.595278263092041, "alphanum_fraction": 0.5973861813545227, "avg_line_length": 32.408451080322266, "blob_id": "3e675a7fc9101762a6e854b631f0d143411c8bd7", "content_id": "3b9b5c79f9f40682969f5c22a0472ffb47cdd4da", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2372, "license_type": "permissive", "max_line_length": 99, "num_lines": 71, "path": "/app/network_policies/networkpoliciestabsctrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 3/9/16.\n */\nimport { Component, Inject } from '@angular/core';\nimport { ActivatedRoute, Router } from \"@angular/router\";\n\nexport enum PolicyTab {\n isolation,\n bandwidth,\n contractGroup\n}\n\n@Component({\n selector: 'networkpoliciestabs',\n templateUrl: './networkpoliciestabs.html'\n})\nexport class NetworkPoliciesTabsComponent {\n isolationPolicySelected:boolean = true;\n bandwidthPolicySelected:boolean = false;\n contractGroupSelected:boolean = false;\n\n policyTab = PolicyTab;\n policyMode:string = 'isolation';\n\n\n constructor(private activatedRoute: ActivatedRoute,\n private router: Router) {\n this.selectPolicyTab(+activatedRoute.snapshot.params['policyTab']);\n }\n\n createNetworkPolicy() {\n if (this.isolationPolicySelected) {\n this.router.navigate(['../isolation/create'], { relativeTo: this.activatedRoute });\n }\n if (this.bandwidthPolicySelected) {\n this.router.navigate(['../bandwidth/create'], { relativeTo: this.activatedRoute });\n }\n if (this.contractGroupSelected) {\n this.router.navigate(['../contractgroup/create'], { relativeTo: this.activatedRoute });\n }\n }\n\n selectPolicyTab(tab:PolicyTab) {\n switch (tab) {\n case PolicyTab.isolation:\n this.isolationPolicySelected = true;\n this.bandwidthPolicySelected = false;\n this.contractGroupSelected = false;\n this.policyMode = 'isolation';\n break;\n case PolicyTab.bandwidth:\n this.isolationPolicySelected = false;\n this.bandwidthPolicySelected = true;\n this.contractGroupSelected = false;\n this.policyMode = 'bandwidth';\n break;\n case PolicyTab.contractGroup:\n this.isolationPolicySelected = false;\n this.bandwidthPolicySelected = false;\n this.contractGroupSelected = true;\n this.policyMode = 'contractgroup';\n break;\n default:\n this.isolationPolicySelected = true;\n this.bandwidthPolicySelected = false;\n this.contractGroupSelected = false;\n this.policyMode = 'isolation';\n break;\n }\n }\n}\n" }, { "alpha_fraction": 0.738002598285675, "alphanum_fraction": 0.7410289645195007, "avg_line_length": 37.54999923706055, "blob_id": "c2e9aa1464e2a404dcd37d1703714f74c7a2cdef", "content_id": "376b03a37380a7deee545462568273feca9d2070", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2313, "license_type": "permissive", "max_line_length": 81, "num_lines": 60, "path": "/app/network_policies/networkpolicies.module.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 10/14/16.\n */\nimport { NgModule } from '@angular/core';\nimport { FormsModule } from \"@angular/forms\";\nimport { CommonModule } from \"@angular/common\";\nimport { RouterModule } from \"@angular/router\";\nimport { DirectivesModule } from \"../components/directives/directives.module\";\nimport { NetworkPoliciesTabsComponent } from \"./networkpoliciestabsctrl\";\nimport { IsolationPolicyCreateComponent } from \"./isolationpolicycreatectrl\";\nimport { IsolationPolicyDetailsComponent } from \"./isolationpolicydetailsctrl\";\nimport { BandwidthPolicyCreateComponent } from \"./bandwidthpolicycreatectrl\";\nimport { BandwidthPolicyDetailsComponent } from \"./bandwidthpolicydetailsctrl\";\nimport { IsolationListComponent } from \"./isolationpolicylistctrl\";\nimport { BandwidthListComponent } from \"./bandwidthpolicylistctrl\";\nimport { IsolationPolicyStatComponent } from \"./isolationpolicystats\";\nimport { ContractGroupListComponent } from \"./contractgrouplist.component\";\nimport { ContractGroupCreateComponent } from \"./contractgroupcreate.component\";\nimport { ContractGroupDetailsComponent } from \"./contractgroupdetails.component\";\n\n@NgModule({\n imports: [\n FormsModule,\n CommonModule,\n RouterModule,\n DirectivesModule\n ],\n declarations: [\n NetworkPoliciesTabsComponent,\n IsolationPolicyCreateComponent,\n IsolationPolicyDetailsComponent,\n BandwidthPolicyCreateComponent,\n BandwidthPolicyDetailsComponent,\n BandwidthPolicyCreateComponent,\n IsolationListComponent,\n BandwidthListComponent,\n IsolationPolicyStatComponent,\n ContractGroupListComponent,\n ContractGroupCreateComponent,\n ContractGroupDetailsComponent\n ],\n exports: [\n NetworkPoliciesTabsComponent,\n IsolationPolicyCreateComponent,\n IsolationPolicyDetailsComponent,\n BandwidthPolicyCreateComponent,\n BandwidthPolicyDetailsComponent,\n IsolationListComponent,\n BandwidthListComponent,\n IsolationPolicyStatComponent,\n ContractGroupListComponent,\n ContractGroupCreateComponent,\n ContractGroupDetailsComponent,\n FormsModule,\n CommonModule,\n RouterModule,\n DirectivesModule\n ]\n})\nexport class NetworkPoliciesModule {}\n" }, { "alpha_fraction": 0.5090961456298828, "alphanum_fraction": 0.5116950869560242, "avg_line_length": 26.492063522338867, "blob_id": "b11e8e57a9f647248ab90565b3d756fbce184f1b", "content_id": "0951157dd5713952719dc9b5765f0eda30fe2c79", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3463, "license_type": "permissive", "max_line_length": 83, "num_lines": 126, "path": "/app/components/models/basecollection.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 10/7/16.\n */\nimport { Http, Response } from '@angular/http';\nimport { Observable } from 'rxjs/Rx';\n\nimport 'rxjs/add/operator/map';\nimport * as _ from 'lodash';\nimport { ApiService } from \"../utils/apiservice\";\nimport {isArray} from \"util\";\nimport {isString} from \"util\";\n\n/**\n * BaseCollection class that does just fetch of the objects.\n * @param $http\n * @param $q\n * @param url Used for doing HTTP GET and fetch objects from server\n * @constructor\n */\nexport class BaseCollection {\n models: any;\n\n constructor(protected http: Http, protected url: string,\n protected apiService: ApiService) {\n this.models = [];\n this.url = url;\n }\n\n /**\n *\n * @param reload Optional. Default is false\n * @returns {*}\n */\n get(reload):Promise<any> {\n var collection = this;\n if (reload === undefined) reload = false;\n return (!reload && collection.models.length > 0) ?\n new Promise(function (resolve) {\n resolve(collection.models);\n }) : collection.apiService.get(collection.url)\n .map((res: Response) => collection.filterAsyncReq(res)).toPromise()\n .then(function (result) {\n collection.models = result;\n return collection.models;\n });\n };\n\n /**\n * Returns a deep copy of the cached object\n * @param key\n * @param reload Optional. Default is false\n * @param keyname\n * @returns {*}\n */\n getModelByKey(key, reload, keyname):Promise<any> {\n var collection = this;\n if (reload === undefined) reload = false;\n if (keyname === undefined) keyname = 'key';\n\n var promise = new Promise(function (resolve) {\n if (!reload && collection.models.length > 0) {\n resolve(findModel());\n } else {\n collection.get(reload)\n .then(function () {\n resolve(findModel());\n });\n }\n });\n\n function findModel() {\n return _.cloneDeep(_.find(collection.models, function (c) {\n return c[keyname] == key;\n }));\n }\n\n return promise;\n };\n\n /**\n * Returns a deep copy of the cached object\n * @param model\n * @param reload Optional. Default is false\n * @returns {*}\n */\n getModel(model, reload):Promise<any> {\n var collection = this;\n if (reload === undefined) reload = false;\n\n var promise = new Promise(function (resolve) {\n if (!reload && collection.models.length > 0) {\n resolve(findModel());\n } else {\n collection.get(reload)\n .then(function () {\n resolve(findModel());\n });\n }\n });\n\n function findModel() {\n return _.cloneDeep(_.find(collection.models, model));\n }\n\n return promise;\n };\n\n clearModel(){\n var collection = this;\n collection.models = [];\n }\n\n filterAsyncReq(res: Response): any{\n var data = res.json();\n if(this.apiService.authServiceRef.isLoggedIn)\n return data;\n else\n if(isArray(data))\n return [];\n else if(isString(data))\n return '';\n else\n return {};\n }\n\n}" }, { "alpha_fraction": 0.4396766126155853, "alphanum_fraction": 0.4443407952785492, "avg_line_length": 40.19230651855469, "blob_id": "35f019c61378d06123fc4ede2900a26d6f886fdd", "content_id": "4a3c4fad32712e806276b11bdb1de1654d0ca545", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 6432, "license_type": "permissive", "max_line_length": 147, "num_lines": 156, "path": "/app/visualization/visualizationservice.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "angular.module('contiv.visualization')\n .factory('VisualizationService', ['$http', '$q', function ($http, $q) {\n /**\n * Makes a get request with the url and config.\n *\n * @param {string} url The url\n * @param {Object} config The configurations\n * @return {$Http Promise} Promise of the request\n */\n function makeGet(url, config) {\n var deferred = $q.defer();\n $http.get(url, config).then(function successCallback(result) {\n deferred.resolve(result.data);\n }, function errorCallback(result) {\n deferred.reject(result.data);\n });\n return deferred.promise;\n }\n\n /**\n * Makes a post request with the url and data\n *\n * @param {string} url The url\n * @param {JSON} data The data\n * @return {$Http Promise} Promise of the request\n */\n function makePost(url, data) {\n /**\n * converts the data into x-www-from-urlencoded\n *\n * @param {JSON} obj JSON data object\n * @return {string} x-www-form-urlencoded string\n */\n var param = function(obj) {\n var query = '', name, value, fullSubName, subName, subValue, innerObj, i;\n for (name in obj) {\n value = obj[name];\n\n if (value instanceof Array) {\n for (i=0; i<value.length; ++i) {\n subValue = value[i];\n fullSubName = name + '[' + i + ']';\n innerObj = {};\n innerObj[fullSubName] = subValue;\n query += param(innerObj) + '&';\n }\n } else if (value instanceof Object) {\n for (subName in value) {\n subValue = value[subName];\n fullSubName = name + '[' + subName + ']';\n innerObj = {};\n innerObj[fullSubName] = subValue;\n query += param(innerObj) + '&';\n }\n } else if(value !== undefined && value !== null) {\n query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';\n }\n }\n\n return query.length ? query.substr(0, query.length - 1) : query;\n };\n\n var deferred = $q.defer();\n $http({\n url:url,\n method:'POST',\n data: data,\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n transformRequest: [function(data) {\n return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;\n }]\n })\n .then(function successCallback(result) {\n deferred.resolve(result.data);\n }, function errorCallback(result) {\n deferred.reject(result.data);\n });\n return deferred.promise;\n }\n\n function getGraphData() {\n var url = ContivGlobals.VISUALIZATION_ENDPOINT;\n url += 'influx/query';\n var config = {\n params: {\n db:\"telegraf\",\n q:\"SELECT BytesIn, BytesOut, EndpointIP, ProviderIP FROM httpjson_svcstats WHERE time > now() - 1m GROUP BY * LIMIT 1\"\n }\n };\n return makeGet(url, config);\n }\n\n function getStructureData() {\n var url = ContivGlobals.VISUALIZATION_ENDPOINT;\n url += 'services';\n return makeGet(url);\n }\n\n function buildWhereQuery(points, type) {\n var query = \"(\";\n query += type + \"=\";\n query += \"'\" + points[0] + \"' \";\n //starts at 1, so will not run if length is 1\n for (var i = 1; i < points.length; i++) {\n query += 'OR ';\n query += type + \"=\";\n query += \"'\" + points[i] + \"' \";\n }\n query += \")\";\n return query;\n }\n\n function getEdgeData(sourceList, targetList, time) {\n var url = ContivGlobals.VISUALIZATION_ENDPOINT;\n url += 'influx/query';\n\n var data = {\n db : \"telegraf\",\n q: \"SELECT sum(\" + 'BytesOut' + \") from httpjson_svcstats WHERE time > now() - 15s AND \"\n + buildWhereQuery(sourceList, \"EndpointIP\") +\" AND \" \n + buildWhereQuery(targetList, 'ProviderIP') \n + \"GROUP BY time(20s) LIMIT 1; SELECT sum(\" + 'BytesIn' + \") from httpjson_svcstats WHERE time > now() - 15s AND \"\n + buildWhereQuery(sourceList, 'ProviderIP') +\" AND \" \n + buildWhereQuery(targetList, 'EndpointIP') \n + \"GROUP BY time(20s) fill(0) LIMIT 1\"\n };\n return makePost(url, data);\n }\n\n \n\n function getOldEdgeData(sourceList, targetList) {\n var url = ContivGlobals.VISUALIZATION_ENDPOINT;\n url += 'influx/query';\n var data = {\n db : \"telegraf\",\n q: \"SELECT sum(\" + 'BytesOut' + \") FROM httpjson_svcstats WHERE time > now() - 1m AND \"\n + buildWhereQuery(sourceList, \"EndpointIP\") +\" AND \" \n + buildWhereQuery(targetList, \"ProviderIP\") \n + \" GROUP BY time(10s) fill(0) LIMIT 6; SELECT sum(\" + 'BytesIn' + \") FROM httpjson_svcstats WHERE time > now() - 1m AND \"\n + buildWhereQuery(sourceList, \"ProviderIP\") +\" AND \" \n + buildWhereQuery(targetList, \"EndpointIP\") \n + \" GROUP BY time(10s) fill(0) LIMIT 6\"\n };\n return makePost(url, data);\n }\n\n return {\n getGraphData: getGraphData,\n getStructureData: getStructureData,\n getEdgeData: getEdgeData,\n getOldEdgeData: getOldEdgeData\n }\n }]);\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6540120840072632, "alphanum_fraction": 0.6583261489868164, "avg_line_length": 24.77777862548828, "blob_id": "7fc50b475381c355ffa23b034503339a11b410f7", "content_id": "ec8283af525c3641b1594f500e28d5f5cc860a0c", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1159, "license_type": "permissive", "max_line_length": 77, "num_lines": 45, "path": "/e2e-tests/dashboard/dashboardspec.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 7/27/16.\n */\n\n\nvar DashboardPage = require(\"./dashboardpageobject.js\");\n\ndescribe(\"Testing Dashboard Page\", function(){\n\n var dashboardPage = new DashboardPage();\n \n beforeEach(function(){\n browser.get(\"#/m/dashboard\");\n });\n\n it(\"Verify nodes link\",function(){\n testConfig.clickLink(dashboardPage.nodes);\n });\n\n it(\"Verify networks link\",function(){\n testConfig.clickLink(dashboardPage.networks);\n });\n\n it(\"Verify volumes link\",function(){\n testConfig.clickLink(dashboardPage.volumes);\n });\n\n it(\"Verify applicationGroup link\",function(){\n testConfig.clickLink(dashboardPage.applicationGroup);\n });\n\n it(\"Verify networkPolicies link\",function(){\n testConfig.clickLink(dashboardPage.networkPolicies);\n });\n\n it(\"Verify storagePolicies link\",function(){\n testConfig.clickLink(dashboardPage.storagePolicies);\n });\n\n it(\"Verifying Dashboard groups\", function(){\n expect(dashboardPage.resourceContent.getText()).toEqual(\"Resources\");\n expect(dashboardPage.policyContent.getText()).toEqual(\"Policies\");\n });\n \n});" }, { "alpha_fraction": 0.5018110871315002, "alphanum_fraction": 0.5026469826698303, "avg_line_length": 27.21259880065918, "blob_id": "a99ca00a4ce5c9a2defbb0ad2c70230f4f27c6e3", "content_id": "f494810084ea2662390d33afc333ce3303085ce5", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3589, "license_type": "permissive", "max_line_length": 80, "num_lines": 127, "path": "/app/components/graphobjects/datasource/datasource.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * The base class the DataSource object.\n * \n * The DataSource object takes in node and link data from the server, \n * and provides methods for converting and manipulating the data for\n * the graph object.\n * \n * To write your own DataSource object, create a new factory that uses the \n * DataSource you want to inherit as a dependency, and extend \n * its DataSource class. \n * Return the class object with DataSource as key.\n * \n * Node data is expected to be in the following format:\n * {id:node_id, text:node_text}\n * \n * Link data is expected to be in the following format:\n * {source: sourceNodeId, target: targetNodeId}\n * \n */\nangular.module('contiv.graph')\n .factory('DataSource', ['Node', 'Link', \n \tfunction (Node, Link) {\n\n \tclass DataSource {\n \t\t/**\n \t\t * Constructs the object.\n \t\t *\n \t\t * @param {Array} nodes The node data \n \t\t * @param {Array} links The link data\n \t\t */\n\t\t\tconstructor(nodes, links) {\n\t\t\t\tthis.nodes = nodes;\n\t\t\t\tthis.links = links;\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Replaces the node data\n\t\t\t *\n\t\t\t * @param {Node} nodes The nodes\n\t\t\t */\n\t\t\tupdateNodes(nodes) {\n\t\t\t\tthis.nodes = nodes;\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Replaces the link data\n\t\t\t *\n\t\t\t * @param {Link} links The links\n\t\t\t */\n\t\t\tupdateLinks(links) {\n\t\t\t\tthis.links = links;\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Returns the Name attribute of the Node with the \n\t\t\t * matching id\n\t\t\t *\n\t\t\t * @param {string} id The identifier\n\t\t\t * @return {string} name of the matching node\n\t\t\t */\n\t\t\tnodeIdToName(id) {\n\t\t var nodes = this.nodes;\n\t\t for (var i = 0; i < nodes.length; i++) {\n\t\t if (nodes[i].id == id) {\n\t\t return nodes[i].name;\n\t\t }\n\t\t }\n\t\t }\n\n\t\t /**\n\t\t * process the nodeData to create Node objects\n\t\t *\n\t\t * @param {Array} nodeData NodeData to convert \n\t\t * to node objects\n\t\t * @return {Array} Node objects\n\t\t */\n\t\t processNodeData(nodeData) {\n\t\t var nodes = [];\n\t\t _.forEach(nodeData, function(data) {\n\t\t var newNode = new Node.Node(null, null, data.id, data.text, null);\n\t\t nodes.push(newNode);\n\t\t });\n\t\t return nodes;\n\t\t }\n\n\t\t /**\n\t\t * process the linkData\n\t\t *\n\t\t * @param {Array} linkData The link data\n\t\t * @param {Array} nodes The nodes from processNodeData\n\t\t * @return {Array} Link objects\n\t\t */\n\t\t processLinkData(linkData, nodes) {\n\t\t \t/**\n\t\t\t * Returns the node that matches the id\n\t\t\t *\n\t\t\t * @param {string} id The identifier\n\t\t\t * @return {Node} The node with the matching id\n\t\t\t */\n\t\t\t function findNodeById(id, nodes) {\n\t\t\t for (var i = 0; i < nodes.length; i++) {\n\t\t\t if (id == nodes[i].id) {\n\t\t\t return nodes[i];\n\t\t\t }\n\t\t\t }\n\t\t\t }\n\n\t\t var links = [];\n\t\t //transforming link data\n\t\t for (var i = 0; i < linkData.length; i++) {\n\t\t if (linkData[i].source != linkData[i].target) {\n\t\t var source = findNodeById(linkData[i].source, nodes);\n\t\t var target = findNodeById(linkData[i].target, nodes);\n\t\t if (source == null || target == null) {\n\t\t \tcontinue;\n\t\t }\n\t var link = new Link.Link(source, target);\n\t links.push(link);\n\t\t } \n\t\t }\n\t\t return links;\n\t\t }\n\t\t}\n\t\treturn {\n\t\t\tDataSource:DataSource\n\t\t}\n}]);\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.4368831217288971, "alphanum_fraction": 0.4399999976158142, "avg_line_length": 44.761905670166016, "blob_id": "af73dd96247699764ae98ee0d4f12d775227e0e4", "content_id": "118ac4d0d30b7ef89484962a30cca585fdb5eb22", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3850, "license_type": "permissive", "max_line_length": 123, "num_lines": 84, "path": "/app/visualization/visualizationedgectrl.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "\n\nangular.module('contiv.visualization')\n .config(['$stateProvider', function ($stateProvider) {\n $stateProvider\n .state('contiv.menu.visualization.edge', {\n url: '/edge/{sourceName, targetName, sourceList, targetList}',\n params: {\n sourceName: null,\n targetName: null,\n sourceList: null,\n targetList: null\n },\n controller: 'VisualizationEdgeCtrl as visualizationedgeCtrl',\n templateUrl: 'visualization/visualizationedge.html'\n })\n ;\n }])\n .controller('VisualizationEdgeCtrl', [\"$scope\", \"$http\", '$state', '$stateParams', 'VisualizationService', '$interval',\n function($scope, $http, $state, $stateParams, VisualizationService, $interval) {\n var sourceName = $stateParams.sourceName;\n var targetName = $stateParams.targetName;\n var sourceList = $stateParams.sourceList;\n var targetList = $stateParams.targetList;\n\n //If the page is reloaded, these state params are all null,\n //so it will route them back to the visualization tab top view\n if (sourceList == null || targetList == null) {\n $state.go('contiv.menu.visualization.list');\n return;\n }\n\n var d = new Date();\n var t = d.getSeconds();\n $scope.edgeDataInterval = \n $interval(function() {\n VisualizationService.getEdgeData(sourceList, targetList, t.toString())\n .then(function successCallback(result) {\n var results = result.results;\n var data = 0;\n _.forEach(results, function(r) {\n if (_.isEmpty(r) === false) {\n data += r.series[0].values[0][1];\n }\n });\n $scope.sourceName = sourceName;\n $scope.targetName = targetName;\n $scope.edgeData = data;\n $scope.edgeDataTime = t;\n }, function errorCallback(result) {\n });\n }, 3000);\n\n //Destroying the interval function on route change\n $scope.$on('$destroy', function () { $interval.cancel($scope.edgeDataInterval); });\n\n\n VisualizationService.getOldEdgeData(sourceList, targetList)\n .then(function successCallback(result) {\n var results = result.results;\n var edgeData = [];\n //results, if not empty, are expected to have\n //6 data entries\n _.forEach(results, function(r) {\n if (_.isEmpty(r) === false) {\n var data = r.series[0].values;\n if (_.isEmpty(edgeData)) {\n _.forEach(data, function(d) {\n edgeData.push(d[1]);\n })\n } else {\n _.forEach(data, function(d, i) {\n edgeData[i] += d[1];\n })\n }\n }\n });\n\n $scope.sourceName = sourceName;\n $scope.targetName = targetName;\n $scope.sourceList = sourceList;\n $scope.targetList = targetList;\n $scope.oldEdgeData = edgeData;\n }, function errorCallback(result) {\n });\n }]);\n\n\n\n\n" }, { "alpha_fraction": 0.5386938452720642, "alphanum_fraction": 0.5426860451698303, "avg_line_length": 38.71341323852539, "blob_id": "1de7cff4f6d88444600230fb9ab191df7c9e61f9", "content_id": "aeaa09370b658c983ab382fdec03be633d83dce7", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 19538, "license_type": "permissive", "max_line_length": 149, "num_lines": 492, "path": "/app/applicationgroups/applicationgroups_test.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "'use strict';\n\ndescribe('contiv.applicationgroups module', function () {\n\n beforeEach(module('ui.router'));\n\n beforeEach(module('contiv.applicationgroups'));\n\n beforeEach(module('contiv.test.directives'));\n\n var groupListData = [\n {\n \"key\":\"default:grp1\",\n \"netProfile\":\"profile4\",\n \"groupName\":\"grp1\",\n \"networkName\":\"network1\",\n \"policies\":[\n \"proxy-net-policy\"\n ],\n \"tenantName\":\"default\",\n \"link-sets\":{\n \"Policies\":{\n \"default:proxy-net-policy\":{\n \"type\":\"policy\",\n \"key\":\"default:proxy-net-policy\"\n }\n }\n },\n \"links\":{\n \"Network\":{\n\n },\n \"Tenant\":{\n \"type\":\"tenant\",\n \"key\":\"default\"\n }\n }\n }\n ];\n\n var policyListData = [\n {\n \"key\": \"default:middleware_net_policy\",\n \"policyName\": \"middleware_net_policy\",\n \"tenantName\": \"default\",\n \"link-sets\": {},\n \"links\": {\n \"Tenant\": {\n \"type\": \"tenant\",\n \"key\": \"default\"\n }\n }\n },\n {\n \"key\": \"default:db_net_policy\",\n \"policyName\": \"db_net_policy\",\n \"tenantName\": \"default\",\n \"link-sets\": {},\n \"links\": {\n \"Tenant\": {\n \"type\": \"tenant\",\n \"key\": \"default\"\n }\n }\n }\n ];\n\n var ruleListData = [\n {\n \"key\": \"default:middleware-net-policy:1\",\n \"action\": \"allow\",\n \"direction\": \"out\",\n \"policyName\": \"middleware-net-policy\",\n \"priority\": 1,\n \"protocol\": \"tcp\",\n \"ruleId\": \"1\",\n \"tenantName\": \"default\",\n \"link-sets\": {\n \"Policies\": {\n \"default:middleware-net-policy\": {\n \"type\": \"policy\",\n \"key\": \"default:middleware-net-policy\"\n }\n }\n }\n },\n {\n \"key\": \"default:proxy-net-policy:1\",\n \"action\": \"allow\",\n \"direction\": \"in\",\n \"policyName\": \"proxy-net-policy\",\n \"port\": 443,\n \"priority\": 1,\n \"protocol\": \"tcp\",\n \"ruleId\": \"1\",\n \"tenantName\": \"default\",\n \"link-sets\": {\n \"Policies\": {\n \"default:proxy-net-policy\": {\n \"type\": \"policy\",\n \"key\": \"default:proxy-net-policy\"\n }\n }\n }\n },\n {\n \"key\": \"default:proxy-net-policy:2\",\n \"action\": \"allow\",\n \"direction\": \"in\",\n \"policyName\": \"proxy-net-policy\",\n \"port\": 80,\n \"priority\": 1,\n \"protocol\": \"tcp\",\n \"ruleId\": \"2\",\n \"tenantName\": \"default\",\n \"link-sets\": {\n \"Policies\": {\n \"default:proxy-net-policy\": {\n \"type\": \"policy\",\n \"key\": \"default:proxy-net-policy\"\n }\n }\n }\n }\n ];\n\n var networkListData = [\n {\n \"key\": \"default:contiv-net1\",\n \"encap\": \"vxlan\",\n \"gateway\": \"20.1.2.254\",\n \"networkName\": \"contiv-net1\",\n \"subnet\": \"20.1.2.0/24\",\n \"tenantName\": \"default\",\n \"link-sets\": {},\n \"links\": {\n \"Tenant\": {\n \"type\": \"tenant\",\n \"key\": \"default\"\n }\n }\n }\n ];\n\n var netprofileListData = [\n {\n \"DSCP\": 3,\n \"bandwidth\": \"20 mbps\",\n \"key\": \"default:p3\",\n \"link-sets\": {\n \"EndpointGroups\": {\n \"default:g4\": {\n \"key\": \"default:g4\",\n \"type\": \"endpointGroup\"\n }\n }\n },\n \"links\": {\n \"Tenant\": {\n \"key\": \"default\",\n \"type\": \"tenant\"\n }\n },\n \"profileName\": \"p3\",\n \"tenantName\": \"default\"\n }\n ];\n\n var appGroup = {\n \"key\": \"\",\n \"groupName\": \"\",\n \"netProfile\": \"\",\n \"networkName\": \"\",\n \"policies\": [\n \"proxy-net-policy\"\n ],\n \"tenantName\": \"default\",\n \"link-sets\": {\n \"Policies\": {\n \"default:proxy-net-policy\":{\n \"type\":\"policy\",\n \"key\":\"default:proxy-net-policy\"\n }\n }\n },\n \"links\": {\n \"AppProfile\": {},\n \"NetProfile\": {},\n \"Network\": {\n \"type\": \"network\",\n \"key\": \"default:net1\"\n },\n \"Tenant\": {\n \"type\": \"tenant\",\n \"key\": \"default\"\n }\n }\n };\n\n var appGroup_edit = {\n \"key\": \"default:grp1\",\n \"groupName\": \"grp1\",\n \"netProfile\": \"p3\",\n \"networkName\": \"net1\",\n \"policies\": [\n \"proxy-net-policy\"\n ],\n \"tenantName\": \"default\",\n \"link-sets\": {\n \"Policies\": {\n \"default:proxy-net-policy\":{\n \"type\":\"policy\",\n \"key\":\"default:proxy-net-policy\"\n }\n }\n },\n \"links\": {\n \"AppProfile\": {},\n \"NetProfile\": {},\n \"Network\": {\n \"type\": \"network\",\n \"key\": \"default:net1\"\n },\n \"Tenant\": {\n \"type\": \"tenant\",\n \"key\": \"default\"\n }\n }\n };\n\n describe('applicationgroupslistctrl', function () {\n var $httpBackend;\n\n beforeEach(inject(function (_$httpBackend_) {\n $httpBackend = _$httpBackend_;\n $httpBackend.when('GET', ContivGlobals.APPLICATIONGROUPS_ENDPOINT).respond(groupListData);\n }));\n\n afterEach(function () {\n $httpBackend.verifyNoOutstandingExpectation();\n $httpBackend.verifyNoOutstandingRequest();\n });\n\n var $controller, $interval, $rootScope;\n var groupListCtrl;\n beforeEach(inject(function (_$interval_, _$rootScope_, _$controller_) {\n $interval = _$interval_;\n $rootScope = _$rootScope_;\n $controller = _$controller_;\n groupListCtrl = $controller('ApplicationGroupListCtrl', { $interval: $interval, $scope: $rootScope });\n }));\n it('should be defined', function () {\n //spec body\n expect(groupListCtrl).toBeDefined();\n $httpBackend.flush();\n });\n it('ApplicationGroupListCtrl should do a GET on /api/endpointGroups/ REST API', function () {\n $httpBackend.expectGET(ContivGlobals.APPLICATIONGROUPS_ENDPOINT);\n $httpBackend.flush();\n });\n it('ApplicationGroupListCtrl should have groups array assigned to groups property', function () {\n $httpBackend.expectGET(ContivGlobals.APPLICATIONGROUPS_ENDPOINT);\n $httpBackend.flush();\n expect(Array.isArray(groupListCtrl.groups)).toBeTruthy();\n expect(groupListCtrl.groups.length).toEqual(1);\n });\n it('ApplicationGroupListCtrl should have showLoader property set to false after fetch', function () {\n $httpBackend.expectGET(ContivGlobals.APPLICATIONGROUPS_ENDPOINT);\n $httpBackend.flush();\n expect(groupListCtrl.showLoader).toBeFalsy();\n });\n });\n\n describe('applicationgroupscreatectrl', function () {\n\n var $httpBackend;\n\n beforeEach(inject(\n function (_$httpBackend_) {\n $httpBackend = _$httpBackend_;\n $httpBackend.when('GET', ContivGlobals.NETWORKS_ENDPOINT).respond(networkListData);\n $httpBackend.when('GET', ContivGlobals.POLICIES_ENDPOINT).respond(policyListData);\n $httpBackend.when('GET', ContivGlobals.RULES_ENDPOINT).respond(ruleListData);\n $httpBackend.when('GET', ContivGlobals.NETPROFILES_ENDPOINT).respond(netprofileListData);\n\n $httpBackend.when('POST', ContivGlobals.APPLICATIONGROUPS_ENDPOINT + groupListData[0].key + '/').respond(groupListData);\n }));\n\n afterEach(function () {\n $httpBackend.verifyNoOutstandingExpectation();\n $httpBackend.verifyNoOutstandingRequest();\n });\n\n var $controller,$state,applicationGroupCreateCtrl,$stateParams;\n beforeEach(inject(function (_$state_,_$stateParams_,_$controller_) {\n $controller = _$controller_;\n $state = _$state_;\n $stateParams = _$stateParams_;\n\n $state.go = function (stateName) {};\n applicationGroupCreateCtrl = $controller('ApplicationGroupCreateCtrl',\n { $state: $state});\n }));\n it('should be defined', function () {\n //spec body\n var groupCreateCtrl = $controller(\n 'ApplicationGroupCreateCtrl');\n expect(groupCreateCtrl).toBeDefined();\n $httpBackend.flush();\n });\n it('ApplicationGroupCreateCtrl should do a GET on /api/networks/ REST API', function () {\n $controller('ApplicationGroupCreateCtrl');\n $httpBackend.expectGET(ContivGlobals.NETWORKS_ENDPOINT);\n $httpBackend.flush();\n });\n it('ApplicationGroupCreateCtrl.createApplicationGroup should do a POST on /api/v1/endpointGroups/ REST API', function () {\n\n applicationGroupCreateCtrl.form = {'$valid' : true};\n applicationGroupCreateCtrl.applicationGroup.networkName = 'network1';\n applicationGroupCreateCtrl.applicationGroup.groupName = 'grp1';\n applicationGroupCreateCtrl.applicationGroup.profileName = 'profile4';\n applicationGroupCreateCtrl.applicationGroup.tenantName = 'default';\n applicationGroupCreateCtrl.createApplicationGroup();\n $httpBackend.expectPOST(ContivGlobals.APPLICATIONGROUPS_ENDPOINT + groupListData[0].key + '/');\n $httpBackend.flush();\n expect(applicationGroupCreateCtrl.showLoader).toBeFalsy();\n });\n });\n\n describe('applicationgroupsdetailsctrl', function () {\n\n var $httpBackend, $state, $stateParams, $controller;\n var groupDetailsCtrl;\n\n beforeEach(inject(function (_$httpBackend_, _$state_, _$stateParams_, _$controller_) {\n $httpBackend = _$httpBackend_;\n $httpBackend.when('GET', ContivGlobals.APPLICATIONGROUPS_ENDPOINT).respond(groupListData);\n $httpBackend.when('GET', ContivGlobals.POLICIES_ENDPOINT).respond(policyListData);\n $httpBackend.when('GET', ContivGlobals.RULES_ENDPOINT).respond(ruleListData);\n $httpBackend.when('GET', ContivGlobals.NETPROFILES_ENDPOINT).respond(netprofileListData);\n $httpBackend.when('PUT', ContivGlobals.APPLICATIONGROUPS_ENDPOINT + groupListData[0].key + '/').respond(groupListData[0]);\n $httpBackend.when('DELETE', ContivGlobals.APPLICATIONGROUPS_ENDPOINT + groupListData[0].key + '/').respond(groupListData[0]);\n $state = _$state_;\n $state.go = function (stateName) {};\n $stateParams = _$stateParams_;\n $stateParams.key = groupListData[0].key;\n $controller = _$controller_;\n groupDetailsCtrl = $controller('ApplicationGroupDetailsCtrl');\n }));\n\n afterEach(function () {\n $httpBackend.verifyNoOutstandingExpectation();\n $httpBackend.verifyNoOutstandingRequest();\n });\n\n it('should be defined', function () {\n //spec body\n expect(groupDetailsCtrl).toBeDefined();\n $httpBackend.flush();\n });\n it('ApplicationGroupDetailsCtrl should do a GET on /api/endpointGroups/ REST API', function () {\n $httpBackend.expectGET(ContivGlobals.APPLICATIONGROUPS_ENDPOINT);\n $httpBackend.flush();\n });\n it('ApplicationGroupDetailsCtrl.saveApplicationGroup() should do a PUT on /api/endpointGroups/ REST API', function () {\n $httpBackend.expectGET(ContivGlobals.APPLICATIONGROUPS_ENDPOINT);\n $httpBackend.flush();\n groupDetailsCtrl.saveApplicationGroup();\n $httpBackend.expectPUT(ContivGlobals.APPLICATIONGROUPS_ENDPOINT+ groupListData[0].key + '/');\n $httpBackend.flush();\n expect(groupDetailsCtrl.showLoader).toBeFalsy();\n });\n it('ApplicationGroupDetailsCtrl.deleteApplicationGroup() should do a DELETE on /api/endpointGroups/ REST API', function () {\n $httpBackend.expectGET(ContivGlobals.APPLICATIONGROUPS_ENDPOINT);\n $httpBackend.flush();\n groupDetailsCtrl.deleteApplicationGroup();\n $httpBackend.expectDELETE(ContivGlobals.APPLICATIONGROUPS_ENDPOINT + groupListData[0].key + '/');\n $httpBackend.flush();\n expect(groupDetailsCtrl.showLoader).toBeFalsy();\n });\n it('ApplicationGroupDetailsCtrl should have group object assigned to applicationGroup property', function () {\n $httpBackend.expectGET(ContivGlobals.APPLICATIONGROUPS_ENDPOINT);\n $httpBackend.flush();\n expect(groupDetailsCtrl.applicationGroup).toEqual(groupListData[0]);\n });\n it('ApplicationGroupDetailsCtrl should have showLoader property set to false after fetch', function () {\n $httpBackend.expectGET(ContivGlobals.APPLICATIONGROUPS_ENDPOINT);\n $httpBackend.flush();\n expect(groupDetailsCtrl.showLoader).toBeFalsy();\n });\n\n });\n\n describe('bandwidthpolicy directive', function () {\n var $httpBackend,rootScope,element,isolateScope;\n\n beforeEach(inject(\n function (_$httpBackend_,$rootScope,$compile) {\n $httpBackend = _$httpBackend_;\n $httpBackend.when('GET', ContivGlobals.NETPROFILES_ENDPOINT).respond(netprofileListData);\n element = $compile(\"<ctv-bandwidthpolicy mode = 'mode' applicationgroup='appGroup'></ctv-bandwidthpolicy>\")($rootScope);\n $rootScope.mode = 'edit';\n $rootScope.appGroup = appGroup;\n }));\n afterEach(function () {\n $httpBackend.verifyNoOutstandingExpectation();\n $httpBackend.verifyNoOutstandingRequest();\n });\n it('Bandwidthpolicy directive should do a GET on /api/v1/netprofiles/ REST API', function () {\n $httpBackend.expectGET(ContivGlobals.NETPROFILES_ENDPOINT);\n $httpBackend.flush();\n });\n it('Bandwidthpolicy directive should have netProfiles array assigned to netprofiles property', function() {\n $httpBackend.expectGET(ContivGlobals.NETPROFILES_ENDPOINT);\n $httpBackend.flush();\n isolateScope = element.isolateScope();\n expect(isolateScope.netProfiles.length).toEqual(1);\n });\n });\n\n describe('isolationpolicy directive', function(){\n var $httpBackend, $rootScope, $compile;\n var element,isolateScope;\n\n beforeEach(inject(function (_$httpBackend_, _$rootScope_, _$compile_) {\n $httpBackend = _$httpBackend_;\n $httpBackend.when('GET', ContivGlobals.POLICIES_ENDPOINT).respond(policyListData);\n $httpBackend.when('GET', ContivGlobals.RULES_ENDPOINT).respond(ruleListData);\n $httpBackend.when('GET', ContivGlobals.APPLICATIONGROUPS_ENDPOINT).respond(groupListData);\n\n $rootScope = _$rootScope_;\n $compile = _$compile_;\n }));\n afterEach(function () {\n $httpBackend.verifyNoOutstandingExpectation();\n $httpBackend.verifyNoOutstandingRequest();\n });\n\n it('Isolationpolicydirective should do a GET on /api/v1/policys/ REST API', function () {\n $rootScope.mode = 'details';\n $rootScope.appGroup = appGroup;\n element = $compile(\"<ctv-isolationpolicy mode='mode' applicationgroup='appGroup'></ctv-isolationpolicy>\")($rootScope);\n $httpBackend.expectGET(ContivGlobals.POLICIES_ENDPOINT);\n $httpBackend.flush();\n });\n\n it('addIsolationPolicy() should add policy to isolation directive scope object applicationgroup.policies', inject(function(){\n $rootScope.mode = 'edit';\n $rootScope.appGroup = appGroup_edit;\n element = $compile(\"<ctv-isolationpolicy mode='mode' applicationgroup='appGroup'></ctv-isolationpolicy>\")($rootScope);\n $httpBackend.flush();\n isolateScope = element.isolateScope();\n isolateScope.selectedPolicy.policy.policyName = policyListData[0].policyName;\n isolateScope.addIsolationPolicy();\n expect(isolateScope.applicationgroup.policies.length).toEqual(2);\n }));\n\n it('removeIsolationPolicy() should delete policy from isolation directive scope object applicationgroup.policies', inject(function(){\n $rootScope.mode = 'edit';\n $rootScope.appGroup = appGroup_edit;\n element = $compile(\"<ctv-isolationpolicy mode='mode' applicationgroup='appGroup'></ctv-isolationpolicy>\")($rootScope);\n $httpBackend.flush();\n isolateScope = element.isolateScope();\n isolateScope.selectedPolicy.policy.policyName = policyListData[0].policyName;\n isolateScope.removeIsolationPolicy(\"middleware_net_policy\");\n expect(isolateScope.applicationgroup.policies.length).toEqual(1);\n }));\n\n it('Isolationpolicydirective should have isolation policies array assigned to isolationPolicies property', function () {\n $rootScope.mode = 'details';\n $rootScope.appGroup = appGroup;\n element = $compile(\"<ctv-isolationpolicy mode='mode' applicationgroup='appGroup'></ctv-isolationpolicy>\")($rootScope);\n $httpBackend.expectGET(ContivGlobals.POLICIES_ENDPOINT);\n $httpBackend.flush();\n isolateScope = element.isolateScope();\n expect(isolateScope.isolationPolicies.length).toEqual(2);\n });\n\n it('Isolationpolicydirective should have incoming and outgoing rules array assigned to incomingRules & outgoingRules property', function () {\n $rootScope.mode = 'edit';\n $rootScope.appGroup = appGroup_edit;\n element = $compile(\"<ctv-isolationpolicy mode='mode' applicationgroup='appGroup'></ctv-isolationpolicy>\")($rootScope);\n $httpBackend.expectGET(ContivGlobals.RULES_ENDPOINT);\n $httpBackend.flush();\n isolateScope = element.isolateScope();\n expect(Array.isArray(isolateScope.incomingRules)).toBeTruthy();\n expect(Array.isArray(isolateScope.outgoingRules)).toBeTruthy();\n expect(isolateScope.incomingRules.length).toEqual(2);\n expect(isolateScope.outgoingRules.length).toEqual(0);\n });\n });\n});" }, { "alpha_fraction": 0.7080745100975037, "alphanum_fraction": 0.7127329111099243, "avg_line_length": 28.953489303588867, "blob_id": "fafbe7de79e4a39f883600718acebf7fca56d5d8", "content_id": "f30e49bf0ea1a1275838b73db3bde14358057db3", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1288, "license_type": "permissive", "max_line_length": 78, "num_lines": 43, "path": "/app/service_lbs/servicelb.module.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 10/18/16.\n */\n\nimport { NgModule } from '@angular/core';\nimport { FormsModule } from \"@angular/forms\";\nimport { CommonModule } from \"@angular/common\";\nimport { DirectivesModule } from \"../components/directives/directives.module\";\nimport {ServicelbListComponent} from \"./servicelblistctrl\";\nimport {ServicelbStatComponent} from \"./servicelbstatsctrl\";\nimport {ServicelbPortsComponent} from \"./servicelbportsdirective\";\nimport {ServicelbCreateComponent} from \"./servicelbcreatectrl\";\nimport {ServicelbInfoComponent} from \"./servicelbinfoctrl\";\nimport {ServicelbDetailsComponent} from \"./servicelbdetailsctrl\";\nimport {RouterModule} from \"@angular/router\";\n\n\n@NgModule({\n imports: [\n FormsModule,\n CommonModule,\n DirectivesModule,\n RouterModule\n ],\n declarations: [\n ServicelbListComponent,\n ServicelbStatComponent,\n ServicelbPortsComponent,\n ServicelbCreateComponent,\n ServicelbInfoComponent,\n ServicelbDetailsComponent\n ],\n exports: [\n ServicelbListComponent,\n ServicelbStatComponent,\n ServicelbPortsComponent,\n ServicelbCreateComponent,\n ServicelbInfoComponent,\n ServicelbDetailsComponent\n ]\n})\n\nexport class ServicelbModule {}\n" }, { "alpha_fraction": 0.690040647983551, "alphanum_fraction": 0.6907181739807129, "avg_line_length": 62.71223068237305, "blob_id": "53dd1384d0330bc8458b56a796bbb7e022359c9b", "content_id": "ffe883b5d57fb5ca8cf1d6f98a66c3433ca15259", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 8856, "license_type": "permissive", "max_line_length": 107, "num_lines": 139, "path": "/app/app.routes.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 11/1/16.\n */\nimport { RouterModule } from '@angular/router';\nimport { MenuComponent } from \"./menu/menuCtrl\";\nimport { NetworkPoliciesTabsComponent } from \"./network_policies/networkpoliciestabsctrl\";\nimport { IsolationPolicyCreateComponent } from \"./network_policies/isolationpolicycreatectrl\";\nimport { IsolationPolicyDetailsComponent } from \"./network_policies/isolationpolicydetailsctrl\";\nimport { BandwidthPolicyCreateComponent } from \"./network_policies/bandwidthpolicycreatectrl\";\nimport { BandwidthPolicyDetailsComponent } from \"./network_policies/bandwidthpolicydetailsctrl\";\nimport { DashboardComponent } from \"./dashboard/dashboardctrl\";\nimport { AppGrouplistComponent } from \"./applicationgroups/applicationgrouplistctrl\";\nimport { ApplicationGroupCreateComponent } from \"./applicationgroups/applicationgroupcreatectrl\";\nimport { ApplicationGroupDetailsComponent } from \"./applicationgroups/applicationgroupdetailsctrl\";\nimport { SettingsMenuComponent } from \"./settings/settingsmenu.component\";\nimport { NetworkSettingsComponent } from \"./settings/networksettingctrl\";\nimport { NetworkListComponent } from \"./networks/networklistctrl\";\nimport { NetworkdetailsComponent } from \"./networks/networkdetailsctrl\";\nimport { NetworkCreateComponent } from \"./networks/networkcreatectrl\";\nimport { ServicelbListComponent } from \"./service_lbs/servicelblistctrl\";\nimport { ServicelbCreateComponent } from \"./service_lbs/servicelbcreatectrl\";\nimport { ServicelbDetailsComponent } from \"./service_lbs/servicelbdetailsctrl\";\nimport { LoginComponent } from \"./login/loginctrl\";\nimport { AuthGuard } from \"./components/utils/authguard\";\nimport { UnauthorizedComponent } from \"./login/unauthorized\";\nimport { LogoutComponent } from \"./login/logoutctrl\";\nimport { UserListComponent } from \"./settings/users/userlist.component\";\nimport { UserCreateComponent } from \"./settings/users/usercreate.component\";\nimport { UserDetailsComponent } from \"./settings/users/userdetails.component\";\nimport { AppProfileListComponent } from \"./appprofiles/appprofilelist.component\";\nimport { AppProfileCreateComponent } from \"./appprofiles/appprofilecreate.component\";\nimport { AppProfileDetailsComponent } from \"./appprofiles/appprofiledetails.component\";\nimport { FirstrunWizardComponent } from \"./firstrunwizard/firstrunwizardctrl\";\nimport { NodeListComponent } from \"./settings/nodes/nodelist.component\";\nimport { NodeCreateComponent } from \"./settings/nodes/nodecreate.component\";\nimport { NodeDetailsComponent } from \"./settings/nodes/nodedetails.component\";\nimport { ContractGroupCreateComponent } from \"./network_policies/contractgroupcreate.component\";\nimport { ContractGroupDetailsComponent } from \"./network_policies/contractgroupdetails.component\";\nimport { AuthorizationListComponent } from \"./settings/authorization/authorizationlist\";\nimport { AuthorizationDetailsComponent } from \"./settings/authorization/authorizationdetails\";\nimport { AuthorizationCreateComponent } from \"./settings/authorization/authorizationcreate\";\nimport { OrganizationListComponent } from \"./settings/tenants/organizationlistctrl\";\nimport { OrganizationCreateComponent } from \"./settings/tenants/organizationcreatectrl\";\nimport { OrganizationDetailsComponent } from \"./settings/tenants/organizationdetailsctrl\";\nimport { LdapConfigComponent } from \"./settings/ldapconfiguration\";\n\nconst routes = [\n {path: 'login', component: LoginComponent},\n {path: 'logout', component: LogoutComponent},\n {path: 'unauthorized', component: UnauthorizedComponent},\n {path: '', redirectTo: 'login', pathMatch: 'full'},\n {\n path: 'm',\n component: MenuComponent,\n canActivateChild: [AuthGuard],\n children: [\n {path: '', redirectTo: 'dashboard', pathMatch: 'full'},\n {path: 'dashboard', component: DashboardComponent},\n {path: 'firstrun', component: FirstrunWizardComponent},\n\n //Network Policies\n {path: 'networkpolicies', redirectTo: 'networkpolicies/list', pathMatch: 'full'},\n {path: 'networkpolicies/list', component: NetworkPoliciesTabsComponent},\n {path: 'networkpolicies/isolation/create', component: IsolationPolicyCreateComponent},\n {path: 'networkpolicies/isolation/details/:key', component: IsolationPolicyDetailsComponent},\n {path: 'networkpolicies/isolation/edit/:key', component: IsolationPolicyDetailsComponent},\n {path: 'networkpolicies/bandwidth/create', component: BandwidthPolicyCreateComponent},\n {path: 'networkpolicies/bandwidth/details/:key', component: BandwidthPolicyDetailsComponent},\n {path: 'networkpolicies/bandwidth/edit/:key', component: BandwidthPolicyDetailsComponent},\n {path: 'networkpolicies/contractgroup/create', component: ContractGroupCreateComponent},\n {path: 'networkpolicies/contractgroup/details/:key', component: ContractGroupDetailsComponent},\n\n //Application Groups\n {path: 'applicationgroups', redirectTo: 'applicationgroups/list', pathMatch: 'full'},\n {path: 'applicationgroups/list', component: AppGrouplistComponent},\n {path: 'applicationgroups/create', component: ApplicationGroupCreateComponent},\n {path: 'applicationgroups/details/:key', component: ApplicationGroupDetailsComponent},\n {path: 'applicationgroups/edit/:key', component: ApplicationGroupDetailsComponent},\n\n //Settings\n {\n path: 'settings',\n component: SettingsMenuComponent,\n children: [\n {path: '', redirectTo: 'users/list', pathMatch: 'full'},\n {path: 'networks', component: NetworkSettingsComponent},\n {path: 'ldap', component: LdapConfigComponent},\n {path: 'nodes', redirectTo: 'nodes/list', pathMatch: 'full'},\n {path: 'nodes/list', component: NodeListComponent},\n {path: 'nodes/create', component: NodeCreateComponent},\n {path: 'nodes/details/:key', component: NodeDetailsComponent},\n {path: 'nodes/edit/:key', component: NodeDetailsComponent},\n //Users\n {path: 'users', redirectTo: 'users/list', pathMatch: 'full'},\n {path: 'users/list', component: UserListComponent},\n {path: 'users/create', component: UserCreateComponent},\n {path: 'users/details/:key', component: UserDetailsComponent},\n {path: 'users/edit/:key', component: UserDetailsComponent},\n //Authorizations\n {path: 'authorization', redirectTo: 'authorization/list', pathMatch: 'full'},\n {path: 'authorization/list', component: AuthorizationListComponent},\n {path: 'authorization/create', component: AuthorizationCreateComponent},\n {path: 'authorization/details/:key', component: AuthorizationDetailsComponent},\n {path: 'authorization/edit/:key', component: AuthorizationDetailsComponent},\n //Tenants\n {path: 'organizations', redirectTo: 'organizations/list', pathMatch: 'full'},\n {path: 'organizations/list', component: OrganizationListComponent},\n {path: 'organizations/create', component: OrganizationCreateComponent},\n {path: 'organizations/details/:key', component: OrganizationDetailsComponent},\n ]\n },\n\n\n\n //Networks\n {path: 'networks', redirectTo: 'networks/list', pathMatch: 'full'},\n {path: 'networks/list', component: NetworkListComponent},\n {path: 'networks/create', component: NetworkCreateComponent},\n {path: 'networks/details/:key', component: NetworkdetailsComponent},\n\n //Servicelbs\n {path: 'servicelbs', redirectTo: 'servicelbs/list', pathMatch: 'full'},\n {path: 'servicelbs/list', component: ServicelbListComponent},\n {path: 'servicelbs/create', component: ServicelbCreateComponent},\n {path: 'servicelbs/details/:key', component: ServicelbDetailsComponent},\n\n //Application profiles\n {path: 'appprofiles', redirectTo: 'appprofiles/list', pathMatch: 'full'},\n {path: 'appprofiles/list', component: AppProfileListComponent},\n {path: 'appprofiles/create', component: AppProfileCreateComponent},\n {path: 'appprofiles/details/:key', component: AppProfileDetailsComponent},\n {path: 'appprofiles/edit/:key', component: AppProfileDetailsComponent},\n\n ]\n },\n {path: '**', redirectTo: 'login', pathMatch: 'full'}\n];\n\nexport default RouterModule.forRoot(routes);\n" }, { "alpha_fraction": 0.5989304780960083, "alphanum_fraction": 0.5989304780960083, "avg_line_length": 40.33333206176758, "blob_id": "97916c8353e8c60e46c5db8f24cbd74f928e132e", "content_id": "9cb540afaf2a2a2c85b75695a006b19ce7e383b2", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 374, "license_type": "permissive", "max_line_length": 94, "num_lines": 9, "path": "/app/visualization/module.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "\n\nangular.module('contiv.visualization', ['contiv.models', 'contiv.directives', 'contiv.utils', \n\t'contiv.graph'])\n .config(['$stateProvider', function ($stateProvider) {\n $stateProvider.state('contiv.menu.visualization', {\n url: '/visualization',\n abstract: true,\n template: '<div ui-view class=\"ui container\"/>'\n })\n }]);\n" }, { "alpha_fraction": 0.5710914731025696, "alphanum_fraction": 0.5740413069725037, "avg_line_length": 26.80327796936035, "blob_id": "6d4f32f9d52de3877073cb469060e6b24bf3f60b", "content_id": "fe1381325f2839d73bd72118a19da83e4854f982", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1695, "license_type": "permissive", "max_line_length": 75, "num_lines": 61, "path": "/app/components/models/rulesmodel.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 3/8/16.\n */\nimport { Injectable } from '@angular/core';\nimport { Http } from '@angular/http';\nimport { Collection } from \"./collection\";\nimport * as _ from 'lodash';\nimport { ContivGlobals } from \"./contivglobals\";\nimport {ApiService} from \"../utils/apiservice\";\n\n@Injectable()\nexport class RulesModel extends Collection {\n constructor(http: Http, apiService: ApiService) {\n super(http, ContivGlobals.RULES_ENDPOINT, apiService);\n }\n\n /**\n * Get incoming rules for a given policy and a tenant\n * @param policyName\n * @param tenantName\n * @returns {*|webdriver.promise.Promise}\n */\n getIncomingRules(policyName, tenantName) {\n var rulesmodel = this;\n return rulesmodel.get(false).then(function (result) {\n return _.filter(result, {\n 'policyName': policyName,\n 'direction': 'in',\n 'tenantName': tenantName\n });\n\n });\n }\n\n /**\n * Get outgoing rules for a given policy and a tenant\n * @param policyName\n * @param tenantName\n * @returns {*|webdriver.promise.Promise}\n */\n getOutgoingRules(policyName, tenantName) {\n var rulesmodel = this;\n return rulesmodel.get(false).then(function (result) {\n return _.filter(result, {\n 'policyName': policyName,\n 'direction': 'out',\n 'tenantName': tenantName\n });\n\n });\n }\n\n /**\n * Generate rule key to save rule on server\n * @param rule\n * @returns {string}\n */\n generateKey(rule) {\n return rule.tenantName + ':' + rule.policyName + ':' + rule.ruleId;\n }\n}" }, { "alpha_fraction": 0.5043184161186218, "alphanum_fraction": 0.5043184161186218, "avg_line_length": 36.507041931152344, "blob_id": "ff91e78f18e0336bc0012e3c09d0f37654306223", "content_id": "01fbe7cac229425938c0c0023a2577912aaf407a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 2663, "license_type": "permissive", "max_line_length": 107, "num_lines": 71, "path": "/app/service_lbs/servicelbdetails.html", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "<div class=\"ui sixteen column grid\">\n <div [ngSwitch]=\"servicelbDetailsCtrl.mode\" class=\"ui row\">\n <div class=\"left aligned eight wide column\">\n <div class=\"content pageTitle\">{{servicelbDetailsCtrl.serviceName}}</div>\n </div>\n <div class=\"right aligned eight wide column\" *ngSwitchCase=\"'details'\">\n <button type=\"button\" class=\"ui basic button\"\n (click)=\"cancelDetails()\">\n Close\n </button>\n <button class=\"ui secondary button\"\n (click)=\"loadEdit()\">\n Edit\n </button>\n <button class=\"ui secondary button\" onclick=\"$('#delete-service-modal').modal('show')\">\n <i class=\"trash icon\"></i>\n Remove\n </button>\n\n </div>\n </div>\n\n <div id=\"delete-service-modal\" class=\"ui small modal\">\n <div class=\"header\">Delete</div>\n <div class=\"content\">\n <p>Are you sure you want to delete the service <q>{{servicelbDetailsCtrl.serviceName}}</q>?</p>\n </div>\n <div class=\"actions\">\n <div class=\"ui basic deny button modalBtn\">Cancel</div>\n <div class=\"ui primary approve button modalBtn\" (click)=\"deleteServicelb()\">\n Yes\n </div>\n </div>\n </div>\n\n <div class=\"ui row breadcrumbRow\">\n <div class=\"ui sixteen wide column\">\n <div class=\"breadcrumbs\">\n <span class=\"crumb\">\n <a href=\"/#/m/servicelbs/list\">\n Service Load Balancers\n </a>\n </span>\n <span class=\"crumb\">\n {{servicelbDetailsCtrl.serviceName}}\n </span>\n </div>\n </div>\n </div>\n\n <div class=\"ui row\">\n <div class=\"ui sixteen wide column\">\n\n <div class=\"ui tabular menu\" *ngIf=\"servicelbDetailsCtrl.mode=='details'\">\n <a class=\"item\" [ngClass]=\"{active: infoselected}\" (click)=\"infoselected=true\">\n Details\n </a>\n <a class=\"item\" [ngClass]=\"{active: !infoselected}\" (click)=\"infoselected=false\">\n Stats\n </a>\n </div>\n\n <servicelb-info [(mode)]=\"mode\" *ngIf=\"infoselected || servicelbDetailsCtrl.mode == 'edit'\"\n (serviceName)=\"serviceName=$event\"></servicelb-info>\n\n <servicelb-stat [statkey]=\"servicelbDetailsCtrl.statskey\"\n *ngIf=\"!infoselected && servicelbDetailsCtrl.mode != 'edit'\"></servicelb-stat>\n\n </div>\n </div>\n</div>\n" }, { "alpha_fraction": 0.4558490514755249, "alphanum_fraction": 0.5181131958961487, "avg_line_length": 49.96154022216797, "blob_id": "c771f67d8610bb6a9ee1ca76db3785aca36e996c", "content_id": "61daebfb7590d425c15ec71092075762e13ac167", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2650, "license_type": "permissive", "max_line_length": 156, "num_lines": 52, "path": "/app/components/models/contivglobals.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 11/2/16.\n * 12/21/16: updating API paths for ccn_proxy [catw]\n */\nexport const ContivGlobals = {\n //REST endpoints for NETMASTER\n 'NETWORKS_ENDPOINT': '/api/v1/networks/',\n 'NETWORKS_INSPECT_ENDPOINT': '/api/v1/inspect/networks/',\n 'SERVICELBS_INSPECT_ENDPOINT': '/api/v1/inspect/serviceLBs/',\n 'POLICIES_ENDPOINT': '/api/v1/policys/',\n 'POLICIES_INSPECT_ENDPOINT': '/api/v1/inspect/policys/',\n 'RULES_ENDPOINT': '/api/v1/rules/',\n 'APPLICATIONGROUPS_ENDPOINT': '/api/v1/endpointGroups/',\n 'APPLICATIONGROUPS_INSPECT_ENDPOINT': '/api/v1/inspect/endpointGroups/',\n 'SERVICELBS_ENDPOINT': '/api/v1/serviceLBs/',\n 'ORGANIZATIONS_ENDPOINT': '/api/v1/tenants/',\n 'NETWORK_SETTINGS_ENDPOINT': '/api/v1/globals/',\n 'GLOBAL_NETWORK_INSPECT_ENDPOINT': '/api/v1/inspect/globals/',\n 'ACI_SETTINGS_ENDPOINT': '/api/v1/aciGws/',\n 'NETPROFILES_ENDPOINT': '/api/v1/netprofiles/',\n 'BGPS_ENDPOINT': '/api/v1/Bgps/',\n 'BGPS_INSPECT_ENDPOINT': '/api/v1/inspect/Bgps/',\n 'APP_PROFILES_ENDPOINT': '/api/v1/appProfiles/',\n 'CONTRACTS_ENDPOINT': '/api/v1/extContractsGroups/',\n 'VISUALIZATION_ENDPOINT': '/visualization/',\n\n //REST endpoint for Login\n 'LOGIN_ENDPOINT': '/api/v1/auth_proxy/login/',\n\n //REST endpoints for USER\n 'USERS_ENDPOINT': '/api/v1/auth_proxy/local_users/',\n 'LDAP_ENDPOINT': '/api/v1/auth_proxy/ldap_configuration/',\n 'AUTHORIZATION_ENDPOINT': '/api/v1/auth_proxy/authorizations/',\n\n //Refresh interval in milliseconds\n 'REFRESH_INTERVAL': 5000,\n\n //RegEx for validation\n 'CIDR_REGEX' : '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\\/([0-9]|[1-2][0-9]|3[0-2]))$',\n 'PVTSUBNET_REGEX': '^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9]))\\.0\\.0)\\/16$',\n 'VLAN_REGEX' : '^([0-9]{1,4}?-[0-9]{1,4}?)$',\n\n 'VXLAN_REGEX' : '^([0-9]{1,8}?-[0-9]{1,8}?)$',\n 'NUMBER_REGEX' : '^[0-9]*$',\n 'USERNAME_REGEX': /^([a-zA-Z0-9\\_\\-\\.\\@])+$/,\n 'LDAPGROUP_REGEX': /([\\=])+/g,\n 'NETWORK_NAME_REGEX': /^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$/,\n\n // System strings\n 'PRODUCT_NAME': 'Contiv',\n 'PRODUCT_VERSION': 'TP_1.0.0',\n};\n" }, { "alpha_fraction": 0.6716758012771606, "alphanum_fraction": 0.6748633980751038, "avg_line_length": 38.23214340209961, "blob_id": "86ccb4d7daa8fd852370a04a54e68df8bf74ad4a", "content_id": "735a1f961cbbf70a46e3dd919520ab5b89090dc9", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2196, "license_type": "permissive", "max_line_length": 123, "num_lines": 56, "path": "/app/network_policies/contractgroupdetails.component.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 12/13/16.\n */\nimport { Component, Inject } from '@angular/core';\nimport { ActivatedRoute, Router } from \"@angular/router\";\nimport { ContractGroupsModel } from \"../components/models/contractgroupsmodel\";\nimport { CRUDHelperService } from \"../components/utils/crudhelperservice\";\nimport { PolicyTab } from \"./networkpoliciestabsctrl\";\n\n@Component({\n selector: 'contractgroupdetails',\n templateUrl: './contractgroupdetails.html'\n})\nexport class ContractGroupDetailsComponent {\n contractGroup:any = {};\n\n constructor(private activatedRoute: ActivatedRoute,\n private router: Router,\n private contractGroupsModel:ContractGroupsModel,\n private crudHelperService:CRUDHelperService) {\n var component = this;\n\n\n /* Get particular Profile for based on key*/\n component.contractGroupsModel.getModelByKey(activatedRoute.snapshot.params['key'],false,undefined)\n .then(function (contractGroup) {\n component.contractGroup = contractGroup;\n });\n component.crudHelperService.stopLoader(component);\n\n }\n\n deleteContractGroup() {\n var component = this;\n component.crudHelperService.startLoader(component);\n component.contractGroupsModel.deleteUsingKey(component.contractGroup.key, 'key', undefined).then(\n function successCallback(result) {\n component.crudHelperService.stopLoader(component);\n component.crudHelperService.showNotification(\"External contract group: Deleted\", result);\n component.returnToContractGroups();\n }, function errorCallback(result) {\n component.crudHelperService.stopLoader(component);\n component.crudHelperService.showServerError(\"External contract group: Delete failed\", result);\n });\n }\n\n\n returnToContractGroups() {\n this.router.navigate(['../../../list', {policyTab: PolicyTab.contractGroup}], { relativeTo: this.activatedRoute });\n }\n\n returnToContractDetails() {\n this.router.navigate(['../../details', this.contractGroup.key], { relativeTo: this.activatedRoute });\n }\n\n}" }, { "alpha_fraction": 0.6018396615982056, "alphanum_fraction": 0.6028909087181091, "avg_line_length": 40.369564056396484, "blob_id": "42f32684b2881c4efdbbdf2fd8e10027a8ec4916", "content_id": "253fedd46b7565645485c9dfc1bc1fa4ee5bf6ec", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3805, "license_type": "permissive", "max_line_length": 140, "num_lines": 92, "path": "/app/service_lbs/servicelbstatsctrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "import {Component, Inject, OnInit, OnDestroy, Input, AfterViewChecked, NgZone} from \"@angular/core\";\nimport {CRUDHelperService} from \"../components/utils/crudhelperservice\";\nimport {Subscription, Observable} from \"rxjs\";\ndeclare var jQuery:any;\nimport {InspectService} from \"../components/utils/inspectservice\";\nimport {isUndefined} from \"util\";\nimport {ServicelbsModel} from \"../components/models/servicelbsmodel\";\nimport {ContivGlobals} from \"../components/models/contivglobals\";\n\n@Component({\n selector: 'servicelb-stat',\n templateUrl: './servicelbstats.html'\n})\nexport class ServicelbStatComponent implements OnInit, OnDestroy{\n\n @Input('statkey') statkey: string;\n public servicelbStatsCtrl: any;\n private crudHelperService: CRUDHelperService;\n private refresh: Subscription;\n private servicelbsModel: ServicelbsModel;\n private inspectSerrvice: InspectService;\n public showLoader: boolean;\n private ngZone: NgZone;\n servicelbInspectStats:any; config:any; providers:any; filteredproviders:any; providerDetails:any;\n constructor(servicelbsModel: ServicelbsModel,\n crudHelperService: CRUDHelperService,\n inspectSerrvice: InspectService,\n ngZone: NgZone){\n this.crudHelperService = crudHelperService;\n this.servicelbsModel = servicelbsModel;\n this.inspectSerrvice = inspectSerrvice;\n this.showLoader = true;\n this.refresh = Observable.interval(5000).subscribe(() => {\n if(this.statkey!='')\n this.getServicelbInspect(true);\n })\n this.servicelbInspectStats= {\n allocatedAddressesCount: '',\n allocatedIPAddresses: '',\n dnsServerIP: '',\n externalPktTag: '',\n numEndpoints: '',\n pktTag: ''\n }\n this.config = {serviceName: '',}\n this.providers = []\n this.filteredproviders = []\n this.providerDetails= {}\n this.ngZone = ngZone\n this.servicelbStatsCtrl = this;\n this.statkey = '';\n }\n\n ngOnInit(){\n this.crudHelperService.startLoader(this);\n if(this.statkey!='')\n this.getServicelbInspect(false);\n }\n\n getServicelbInspect(reload: boolean){\n var servicelbStatsCtrl = this;\n this.servicelbsModel.getInspectByKey(this.statkey,\n ContivGlobals.SERVICELBS_INSPECT_ENDPOINT, reload)\n .then((result) => {\n servicelbStatsCtrl['servicelbInspectStats'] = result['Oper'];\n servicelbStatsCtrl['config'] = result['Config'];\n if(!isUndefined(result['Oper'].providers)){\n var providerDetails = servicelbStatsCtrl.inspectSerrvice.buildEndPoints(result['Oper'].providers);\n if(servicelbStatsCtrl.inspectSerrvice.checkContainerChanged(servicelbStatsCtrl['providerDetails'],providerDetails)){\n servicelbStatsCtrl['providers'] = result['Oper'].providers;\n servicelbStatsCtrl['providerDetails'] = providerDetails;\n }\n }\n else{\n servicelbStatsCtrl['providers'] = []\n servicelbStatsCtrl['providerDetails'] = {};\n }\n servicelbStatsCtrl.ngZone.run(() => {\n servicelbStatsCtrl.crudHelperService.stopLoader(servicelbStatsCtrl);\n });\n },\n (error) => {\n servicelbStatsCtrl.ngZone.run(() => {\n servicelbStatsCtrl.crudHelperService.stopLoader(servicelbStatsCtrl);\n });\n });\n }\n\n ngOnDestroy(){\n this.refresh.unsubscribe();\n }\n}" }, { "alpha_fraction": 0.5886766910552979, "alphanum_fraction": 0.5954979658126831, "avg_line_length": 25.196428298950195, "blob_id": "ab0c083026696d1abc5fee3390b476b398b2ffb5", "content_id": "9035f22b011551edd268a40beb47899423659a7b", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1466, "license_type": "permissive", "max_line_length": 114, "num_lines": 56, "path": "/app/service_lbs/servicelbportsdirective.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 10/17/16.\n */\n\n\nimport {Component, Input, Output, EventEmitter, OnInit} from \"@angular/core\";\nvar _ = require('lodash');\n\ninterface Item{\n servicePort: string;\n providerPort: string;\n protocol: string;\n}\n\n@Component({\n selector:'ctv-servicelbports',\n templateUrl:'./servicelbports.html'\n})\n\nexport class ServicelbPortsComponent{\n @Input('items') items: string[];\n @Output('itemsChange') itemsChange: EventEmitter<any>;\n public newItem:Item;\n constructor(){\n this.itemsChange = new EventEmitter<any>();\n this.items=[];\n this.newItem = {servicePort: '', providerPort: '', protocol: ''};\n }\n\n public resetItem(): void{\n this.newItem = {servicePort: '', providerPort: '', protocol: ''};\n }\n\n\n public add(): void{\n function compare(val1, val2){\n return val1 == val2;\n }\n\n if (this.newItem.servicePort == '' && this.newItem.providerPort == '' && this.newItem.protocol == ''){\n return;\n }\n var newItemStr = this.newItem.servicePort + ':' + this.newItem.providerPort + ':' + this.newItem.protocol;\n _.pullAllWith(this.items, [newItemStr], compare);\n this.items.push(newItemStr);\n this.itemsChange.emit(this.items);\n this.resetItem();\n }\n\n public remove(passedItem: Item): void{\n _.remove(this.items, function(item){\n return item == passedItem;\n });\n }\n\n}" }, { "alpha_fraction": 0.6118598580360413, "alphanum_fraction": 0.6154537200927734, "avg_line_length": 31.75, "blob_id": "31f451f68f10e622d3b0a38810392c48f3959773", "content_id": "9e20de736c06aa6defbca64cf2808497b5552505", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2226, "license_type": "permissive", "max_line_length": 90, "num_lines": 68, "path": "/app/firstrunwizard/firstrunwizardconfirmpage.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 10/30/16.\n */\n\n\nimport { Component, OnInit, Output, EventEmitter } from \"@angular/core\";\nimport { Router } from \"@angular/router\";\nimport { FirstRunWizardService } from \"./firstrunwizardservice\";\nimport { CRUDHelperService } from \"../components/utils/crudhelperservice\";\nimport { FirstRunService } from \"../components/utils/firstrunservice\";\n\n@Component({\n selector: 'firstrunwizardconfirmpage',\n templateUrl: './firstrunwizardconfirmpage.html'\n})\n\nexport class FirstrunConfirmComponent {\n public showLoader: boolean;\n public skipArray: Array<boolean>;\n @Output('updatePage') updatePage: EventEmitter<any>;\n @Output('cancelPage') cancelPage: EventEmitter<any>;\n constructor(private wizardService: FirstRunWizardService,\n private router: Router,\n private firstRunService: FirstRunService,\n private crudHelperService: CRUDHelperService){\n this.updatePage = new EventEmitter<any>();\n this.cancelPage = new EventEmitter<any>();\n this.showLoader = false;\n this.skipArray = Array.from(this.wizardService.skipArray);\n }\n\n process(){\n //this.updatePage.emit(4);\n // Will be calling the update settings funciton of wizard service,\n // A loader will be shown until all the updates are completed.\n var component = this;\n //this.crudHelperService.startLoader(this);\n this.showLoader = true;\n\n this.wizardService.updateSettings()\n .then((result) => {\n this.loadDashboard();\n }, (error) => {\n component.crudHelperService.stopLoader(component);\n component.crudHelperService.showServerError(\"Contiv setup failed\", error);\n });\n\n }\n\n loadDashboard(){\n this.firstRunService.setFirstRun(true)\n .then((firstrun: boolean) => {\n if (!firstrun) {\n this.wizardService.initialize();\n this.showLoader = false;\n this.router.navigate(['/m/dashboard']);\n }\n });\n }\n\n goBack(){\n this.updatePage.emit(2);\n }\n\n cancel(){\n this.cancelPage.emit();\n }\n}" }, { "alpha_fraction": 0.5120339393615723, "alphanum_fraction": 0.5429987907409668, "avg_line_length": 40.425594329833984, "blob_id": "25f9e3156bacafaff38498af60bcf2bd2f8e4534", "content_id": "72dbeafb35ea9823a8d00db65a2638a074c6c7b3", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 13919, "license_type": "permissive", "max_line_length": 127, "num_lines": 336, "path": "/app/networks/networks_test.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "'use strict';\n\ndescribe('contiv.networks module', function () {\n\n var networksData = [\n {\n \"key\": \"default:contiv-net1\",\n \"encap\": \"vxlan\",\n \"gateway\": \"20.1.2.254\",\n \"networkName\": \"contiv-net1\",\n \"subnet\": \"20.1.2.0/24\",\n \"tenantName\": \"default\",\n \"link-sets\": {},\n \"links\": {\n \"Tenant\": {\n \"type\": \"tenant\",\n \"key\": \"default\"\n }\n }\n }\n ];\n\n var groupsData = [\n {\n \"key\": \"default:contiv-net1:prod-web\",\n \"endpointGroupId\": 1,\n \"groupName\": \"prod-web\",\n \"networkName\": \"contiv-net1\",\n \"policies\": [\n \"proxy-net-policy\"\n ],\n \"tenantName\": \"default\",\n \"link-sets\": {\n \"Policies\": {\n \"default:proxy-net-policy\": {\n \"type\": \"policy\",\n \"key\": \"default:proxy-net-policy\"\n }\n }\n },\n \"links\": {\n \"AppProfile\": {},\n \"Network\": {},\n \"Tenant\": {\n \"type\": \"tenant\",\n \"key\": \"default\"\n }\n }\n },\n {\n \"key\": \"default:contiv-net2:prod-app\",\n \"endpointGroupId\": 2,\n \"groupName\": \"prod-app\",\n \"networkName\": \"contiv-net2\",\n \"policies\": [\n \"app-net-policy\"\n ],\n \"tenantName\": \"default\",\n \"link-sets\": {\n \"Policies\": {\n \"default:app-net-policy\": {\n \"type\": \"policy\",\n \"key\": \"default:app-net-policy\"\n }\n }\n },\n \"links\": {\n \"AppProfile\": {},\n \"Network\": {},\n \"Tenant\": {\n \"type\": \"tenant\",\n \"key\": \"default\"\n }\n }\n },\n {\n \"key\": \"default:contiv-net2:prod-stor\",\n \"endpointGroupId\": 5,\n \"groupName\": \"prod-stor\",\n \"networkName\": \"contiv-net2\",\n \"policies\": [\n \"db-net-policy\"\n ],\n \"tenantName\": \"default\",\n \"link-sets\": {\n \"Policies\": {\n \"default:db-net-policy\": {\n \"type\": \"policy\",\n \"key\": \"default:db-net-policy\"\n }\n }\n },\n \"links\": {\n \"AppProfile\": {},\n \"Network\": {},\n \"Tenant\": {\n \"type\": \"tenant\",\n \"key\": \"default\"\n }\n }\n }\n ];\n\n var networkOperData = {\n \"Oper\":{\n \"allocatedAddressesCount\":2,\n \"allocatedIPAddresses\":\"20.1.1.1-20.1.1.6, 20.1.1.254\",\n \"dnsServerIP\":\"20.1.1.1\",\n \"endpoints\":[\n {\n \"containerID\":\"c44e011692b36f3dc0c1b2d7f02f65446aa8c839725f2247eb160f902e662b3b\",\n \"homingHost\":\"cluster-node1\",\n \"ipAddress\":[\n \"20.1.1.2\",\n \"\"\n ],\n \"labels\":\"map[com.docker.swarm.id:f3d9025b52147907722e154d8d60963375dbe01fe2daf557902ac9eab37170c3]\",\n \"macAddress\":\"02:02:14:01:01:02\",\n \"name\":\"b437653f2b2009c1ebfb6f03546cf650dd6873a31b92326ad390b4a22af3c33c\",\n \"network\":\"contiv-net1.default\"\n },\n {\n \"containerID\":\"dd02a4ae156f3068ba0a66cd875c6b667e3b1aab6a005a61bccef4f186252b03\",\n \"homingHost\":\"cluster-node1\",\n \"ipAddress\":[\n \"20.1.1.3\",\n \"\"\n ],\n \"labels\":\"map[com.docker.swarm.id:f8cff2b516b2133ed8f6b6cc6fcbc989437b30744572e08dc874e737d0292410]\",\n \"macAddress\":\"02:02:14:01:01:03\",\n \"name\":\"ae20564a67bbb596f84d14d321ccc792b80755b035af56606bd0ccb25cb0c0b2\",\n \"network\":\"contiv-net1.default\"\n }],\n \"externalPktTag\":1,\n \"numEndpoints\":2,\n \"pktTag\":1\n }\n };\n\n beforeEach(module('ui.router'));\n\n beforeEach(module('contiv.networks'));\n\n var $httpBackend;\n\n beforeEach(inject(function (_$httpBackend_) {\n $httpBackend = _$httpBackend_;\n $httpBackend.when('GET', ContivGlobals.NETWORKS_INSPECT_ENDPOINT + networksData[0].key + '/').respond(networkOperData);\n $httpBackend.when('GET', ContivGlobals.NETWORKS_ENDPOINT).respond(networksData);\n $httpBackend.when('GET', ContivGlobals.APPLICATIONGROUPS_ENDPOINT).respond(groupsData);\n $httpBackend.when('DELETE', ContivGlobals.NETWORKS_ENDPOINT + networksData[0].key + '/').respond(networksData[0]);\n $httpBackend.when('POST', ContivGlobals.NETWORKS_ENDPOINT + networksData[0].key + '/').respond(networksData[0]);\n }));\n\n afterEach(function () {\n $httpBackend.verifyNoOutstandingExpectation();\n $httpBackend.verifyNoOutstandingRequest();\n });\n\n describe('networklist controller', function () {\n var $controller, $interval, $rootScope;\n var networkListCtrl;\n beforeEach(inject(function (_$interval_, _$rootScope_, _$controller_) {\n $interval = _$interval_;\n $rootScope = _$rootScope_;\n $controller = _$controller_;\n networkListCtrl = $controller('NetworksListCtrl', { $interval: $interval, $scope: $rootScope });\n }));\n it('should be defined', function () {\n expect(networkListCtrl).toBeDefined();\n $httpBackend.flush();\n });\n it('NetworksListCtrl should do a GET on /api/networks/ REST API', function () {\n $httpBackend.expectGET(ContivGlobals.NETWORKS_ENDPOINT);\n $httpBackend.flush();\n });\n it('NetworksListCtrl should have networks array assigned to networks property', function () {\n $httpBackend.expectGET(ContivGlobals.NETWORKS_ENDPOINT);\n $httpBackend.flush();\n expect(Array.isArray(networkListCtrl.networks)).toBeTruthy();\n expect(networkListCtrl.networks.length).toEqual(1);\n });\n it('NetworksListCtrl should do have showLoader property set to false after fetch', function () {\n $httpBackend.expectGET(ContivGlobals.NETWORKS_ENDPOINT);\n $httpBackend.flush();\n expect(networkListCtrl.showLoader).toBeFalsy();\n });\n });\n\n describe('networkdetails controller', function () {\n var $controller, $state, $stateParams, $interval, $rootScope;\n var networkDetailsCtrl;\n beforeEach(inject(function (_$state_ ,_$stateParams_, _$interval_, _$rootScope_, _$controller_) {\n $state = _$state_;\n $state.go = function (stateName) {};\n $stateParams = _$stateParams_;\n $stateParams.key = networksData[0].key;\n $interval = _$interval_;\n $rootScope = _$rootScope_;\n $controller = _$controller_;\n networkDetailsCtrl = $controller('NetworkDetailsCtrl',\n { $state: $state, $stateParams: $stateParams, $interval: $interval, $scope: $rootScope });\n }));\n\n it('should be defined', function () {\n expect(networkDetailsCtrl).toBeDefined();\n $httpBackend.flush();\n });\n\n it('NetworkDetailsCtrl should do a GET on /api/networks/ REST API', function () {\n $httpBackend.expectGET(ContivGlobals.NETWORKS_ENDPOINT);\n $httpBackend.flush();\n });\n\n it('NetworkDetailsCtrl should have network object assigned to network property', function () {\n $httpBackend.expectGET(ContivGlobals.NETWORKS_ENDPOINT);\n $httpBackend.flush();\n expect(networkDetailsCtrl.network).toEqual(networksData[0]);\n });\n\n it('NetworkDetailsCtrl should do a GET on /api/endpointGroups/ REST API', function () {\n $httpBackend.expectGET(ContivGlobals.APPLICATIONGROUPS_ENDPOINT);\n $httpBackend.flush();\n });\n\n it('NetworkDetailsCtrl should have application groups array assigned to applicationGroups property', function () {\n $httpBackend.expectGET(ContivGlobals.APPLICATIONGROUPS_ENDPOINT);\n $httpBackend.flush();\n expect(networkDetailsCtrl.applicationGroups.length).toEqual(1);\n expect(networkDetailsCtrl.applicationGroups[0]).toEqual(groupsData[0]);\n });\n\n it('NetworkDetailsCtrl.deleteNetwork() should do a DELETE on /api/networks/ REST API', function () {\n //Call flush to fulfill all the http requests to get network and application groups before calling deleteNetwork()\n $httpBackend.flush();\n networkDetailsCtrl.deleteNetwork();\n $httpBackend.expectDELETE(ContivGlobals.NETWORKS_ENDPOINT + networksData[0].key + '/');\n $httpBackend.flush();\n expect(networkDetailsCtrl.showLoader).toBeFalsy();\n });\n\n it('NetworksDetailsCtrl should do have showLoader property set to false after fetch', function () {\n $httpBackend.expectGET(ContivGlobals.NETWORKS_ENDPOINT);\n $httpBackend.flush();\n expect(networkDetailsCtrl.showLoader).toBeFalsy();\n });\n });\n\n describe('networkcreate controller', function () {\n\n var $controller, $state, $stateParams;\n var networkCreateCtrl;\n beforeEach(inject(function (_$state_ ,_$stateParams_, _$controller_) {\n $state = _$state_;\n $state.go = function (stateName) {};\n $stateParams = _$stateParams_;\n $stateParams.key = networksData[0].key;\n $controller = _$controller_;\n networkCreateCtrl = $controller('NetworkCreateCtrl');\n }));\n\n it('should be defined', function () {\n expect(networkCreateCtrl).toBeDefined();\n });\n\n it('NetworkCreateCtrl should have new network object initialized', function () {\n expect(networkCreateCtrl.newNetwork).toBeDefined();\n expect(networkCreateCtrl.newNetwork.encap).toEqual('vxlan');\n expect(networkCreateCtrl.newNetwork.tenantName).not.toEqual('');\n expect(networkCreateCtrl.newNetwork.networkName).toEqual('');\n expect(networkCreateCtrl.newNetwork.subnet).toEqual('');\n expect(networkCreateCtrl.newNetwork.gateway).toEqual('');\n });\n\n it('NetworkCreateCtrl.createNetwork() should do a POST on /api/networks/ REST API', function () {\n networkCreateCtrl.form = {'$valid' : true};\n networkCreateCtrl.newNetwork.networkName = 'contiv-net1';\n networkCreateCtrl.newNetwork.subnet = '20.1.2.0/24';\n networkCreateCtrl.newNetwork.gateway = '20.1.2.254';\n networkCreateCtrl.createNetwork();\n $httpBackend.expectPOST(ContivGlobals.NETWORKS_ENDPOINT + networksData[0].key + '/');\n $httpBackend.flush();\n expect(networkCreateCtrl.showLoader).toBeFalsy();\n });\n\n it('NetworkCreateCtrl.createNetwork() should not do a POST on /api/networks/ REST API for invalid form', function () {\n networkCreateCtrl.form = {'$valid' : false};\n networkCreateCtrl.newNetwork.networkName = 'contiv-net1';\n networkCreateCtrl.newNetwork.subnet = '20.1.2.0/24';\n networkCreateCtrl.newNetwork.gateway = '20.1.2.254';\n networkCreateCtrl.createNetwork();\n $httpBackend.verifyNoOutstandingRequest();\n expect(networkCreateCtrl.showLoader).toBeFalsy();\n });\n });\n\n describe('networkstats controller', function () {\n\n var $controller, $state, $stateParams, $interval, $rootScope;\n var networkStatsCtrl;\n beforeEach(inject(function (_$state_ ,_$stateParams_, _$interval_, _$rootScope_, _$controller_) {\n $state = _$state_;\n $state.go = function (stateName) {};\n $stateParams = _$stateParams_;\n $stateParams.key = networksData[0].key;\n $interval = _$interval_;\n $rootScope = _$rootScope_;\n $controller = _$controller_;\n networkStatsCtrl = $controller('NetworkStatsCtrl',\n { $state: $state, $stateParams: $stateParams, $interval: $interval, $scope: $rootScope });\n }));\n\n it('should be defined', function () {\n expect(networkStatsCtrl).toBeDefined();\n $httpBackend.flush();\n });\n\n it('NetworkStatsCtrl should do a GET on /netmaster/api/v1/inspect/networks/:key REST API', function () {\n $httpBackend.expectGET(ContivGlobals.NETWORKS_INSPECT_ENDPOINT + networksData[0].key + '/');\n $httpBackend.flush();\n });\n it('buildEndPoints function should construct container list with all the endpoints', function () {\n $httpBackend.flush();\n expect(networkStatsCtrl.endpoints).toBeDefined();\n expect(Array.isArray(networkStatsCtrl.endpoints)).toBeTruthy();\n expect(networkStatsCtrl.endpoints.length).toEqual(networkOperData.Oper.endpoints.length);\n });\n it('buildEndPoints function should construct endpoints object', function () {\n $httpBackend.flush();\n expect(networkStatsCtrl.containerDetails).toBeDefined();\n var len = Object.keys(networkStatsCtrl.containerDetails).length;\n expect(len).toEqual(2);\n });\n });\n \n});\n" }, { "alpha_fraction": 0.6321381330490112, "alphanum_fraction": 0.6365648508071899, "avg_line_length": 33.769229888916016, "blob_id": "f143814c9be3931e6f130fa2f1a0e0baaa4c502a", "content_id": "d884e9ddf200879a08c8b0586a4a70770cc4fe16", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2259, "license_type": "permissive", "max_line_length": 98, "num_lines": 65, "path": "/app/settings/tenants/organizationlistctrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 10/14/16.\n */\n\nimport {Component, OnInit, OnDestroy, Inject, NgZone} from \"@angular/core\";\nimport { ActivatedRoute, Router } from \"@angular/router\";\nimport {Observable, Subscription} from \"rxjs\";\nimport {CRUDHelperService} from \"../../components/utils/crudhelperservice\";\nimport {OrganizationsModel} from \"../../components/models/organizationsmodel\";\n\n\n@Component({\n selector: 'organizationlist',\n templateUrl: './organizationlist.html'\n})\n\nexport class OrganizationListComponent implements OnInit, OnDestroy{\n private organizationsModel:OrganizationsModel;\n private crudHelperService: CRUDHelperService;\n public organizationsListCtrl: any;\n private refresh: Subscription;\n\n constructor(private activatedRoute: ActivatedRoute,\n private router: Router,\n organizationsModel: OrganizationsModel,\n crudHelperService: CRUDHelperService,\n private ngZone: NgZone){\n this.organizationsModel = organizationsModel;\n this.crudHelperService = crudHelperService;\n this.organizationsListCtrl = this;\n this['showLoader']=true;\n this.refresh=Observable.interval(5000).subscribe(() => {\n this.getOrganizations(true);\n })\n }\n\n ngOnInit(){\n this.crudHelperService.startLoader(this);\n this.getOrganizations(false);\n }\n\n getOrganizations(reload: boolean){\n var organizationsListCtrl = this;\n this.organizationsModel.get(reload)\n .then(function successCallback(result){\n organizationsListCtrl['organizations'] = result;\n organizationsListCtrl.ngZone.run(() => {\n organizationsListCtrl.crudHelperService.stopLoader(organizationsListCtrl);\n });\n },\n function errorCallback(result){\n organizationsListCtrl.ngZone.run(() => {\n organizationsListCtrl.crudHelperService.stopLoader(organizationsListCtrl);\n });\n });\n }\n\n create(){\n this.router.navigate(['../create'], { relativeTo: this.activatedRoute });\n }\n\n ngOnDestroy(){\n this.refresh.unsubscribe();\n }\n}" }, { "alpha_fraction": 0.606589138507843, "alphanum_fraction": 0.606589138507843, "avg_line_length": 30.15151596069336, "blob_id": "6b4e9f24b706161564b1d319b9ae99339e7980f8", "content_id": "5007b67f395473c20082cd768802002a60f24cfb", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1032, "license_type": "permissive", "max_line_length": 60, "num_lines": 33, "path": "/app/components/graphobjects/policy/policy_test.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "'use strict';\n\ndescribe('policy', function(){\n var policyFactory;\n beforeEach(function(){\n module('contiv.graph');\n inject( function($injector){\n policyFactory = $injector.get('Policy');\n });\n });\n \n it('Checking inital values', function(){\n var policy = new policyFactory.Policy(\"test\");\n expect(policy.policyName).toBe(\"test\");\n expect(policy.graph).toBe(null);\n expect(policy.initialized).toBe(false);\n });\n\n it('Checking initializing', function() {\n var policy = new policyFactory.Policy(\"test\");\n\n policy.initialize(\"testGraph\");\n expect(policy.policyName).toBe(\"test\");\n expect(policy.graph).toBe(\"testGraph\");\n expect(policy.initialized).toBe(true);\n\n //calling initialize again shouldn't change anything\n policy.initialize(\"newGraph\");\n expect(policy.policyName).toBe(\"test\");\n expect(policy.graph).toBe(\"testGraph\");\n expect(policy.initialized).toBe(true);\n })\n});\n\n\n\n\n" }, { "alpha_fraction": 0.591269850730896, "alphanum_fraction": 0.60317462682724, "avg_line_length": 17.035715103149414, "blob_id": "e4107e1c892e1ec26cd5fb1657e35cd35cd8a72d", "content_id": "de78014bb098251536c32fa372943adcc9f4e14e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 504, "license_type": "permissive", "max_line_length": 60, "num_lines": 28, "path": "/app/components/directives/errormessagedirective.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 4/28/16.\n */\nimport { Component, Input, OnChanges } from \"@angular/core\";\n\n@Component({\n selector: 'ctv-error',\n templateUrl: './errormessage.html'\n})\nexport class ErrorMessageComponent implements OnChanges {\n\n @Input() header: string;\n @Input() error: string;\n\n private showError: boolean;\n\n constructor() {\n this.showError = true;\n }\n\n ngOnChanges() {\n this.showError = true;\n }\n\n close() {\n this.showError = false;\n }\n}" }, { "alpha_fraction": 0.6832946538925171, "alphanum_fraction": 0.6832946538925171, "avg_line_length": 27.766666412353516, "blob_id": "fdac88f9acce37a51e82716be96851562859f128", "content_id": "8bd61dd63e8509dd29b10713e0fb44041e13285a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 862, "license_type": "permissive", "max_line_length": 79, "num_lines": 30, "path": "/app/settings/tenants/organizationcreatectrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "import {Component} from \"@angular/core\";\nimport { ActivatedRoute, Router } from \"@angular/router\";\nimport {DisplayType} from \"../../components/directives/settings/tenantcreate\";\n\n@Component({\n selector: 'organizationcreate',\n templateUrl: './organizationcreate.html'\n})\n\nexport class OrganizationCreateComponent{\n public showLoader: boolean;\n public showServerError: boolean;\n public serverErrorMessage: string;\n public DisplayType = DisplayType;\n constructor(private activatedRoute: ActivatedRoute,\n private router: Router){\n this.showServerError = false;\n this.serverErrorMessage = '';\n this.showLoader = false;\n }\n\n returnToOrganizations(){\n this.router.navigate(['../list'], { relativeTo: this.activatedRoute });\n }\n\n cancelCreating(){\n this.returnToOrganizations();\n }\n\n}" }, { "alpha_fraction": 0.5396459102630615, "alphanum_fraction": 0.5473440885543823, "avg_line_length": 29.880952835083008, "blob_id": "8f78d7dcfc3e1bee2280d45b270e9c9964be502d", "content_id": "8e268c0932e6afab0dc56c3aac6a1c76f55aaeb3", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2598, "license_type": "permissive", "max_line_length": 71, "num_lines": 84, "path": "/app/components/graphobjects/node/node_test.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "'use strict';\n\ndescribe('node', function(){\n var nodeFactory;\n var node;\n beforeEach(function(){\n module('contiv.graph');\n inject( function($injector){\n nodeFactory = $injector.get('Node');\n node = new nodeFactory.Node(1, 2, 'testId', 'testText', 5);\n });\n });\n \n it('Checking inital values', function(){\n expect(node.x).toBe(1);\n expect(node.y).toBe(2);\n expect(node.id).toBe('testId');\n expect(node.text).toBe('testText');\n expect(node.radius).toBe(5);\n expect(node.graph).toBe(null);\n expect(node.initialized).toBe(false);\n });\n\n it('Checking initializing and setRadius', function() {\n node.initialize(\"testGraph\");\n expect(node.graph).toBe(\"testGraph\");\n expect(node.initialized).toBe(true);\n\n //calling initialize again shouldn't change anything\n node.initialize(\"newGraph\");\n expect(node.graph).toBe(\"testGraph\");\n expect(node.initialized).toBe(true);\n\n expect(node.radius).toBe(5);\n node.setRadius(10);\n expect(node.radius).toBe(10);\n });\n\n it('checking updateAttr', function() {\n var d3node = {\n attr : function(type, func) {\n if (type === \"transform\") {\n expect(func(node)).toBe(\"translate(1,2)\");\n }\n }\n };\n node.updateAttr(d3node, node);\n });\n\n it('testing policy related methods', function() {\n var policy = {\n policyName:'testPolicy',\n initialize: function(g){\n this.graph = g;\n },\n click:function(d3node, d) {\n expect(d.id).toBe('testId');\n },\n destroy: function(){\n this.destroyed = true;\n }\n };\n node.initialize(\"testGraph\");\n node.installNodePolicy(policy);\n expect(node.hasPolicy).toBe(true);\n expect(node.nodePolicies.length).toBe(1);\n expect(policy.graph).toBe('testGraph');\n\n node.nodePolicyEvent('click', null, node);\n node.uninstallNodePolicy(policy);\n expect(policy.destroyed).toBe(true);\n expect(node.hasPolicy).toBe(false);\n expect(node.nodePolicies.length).toBe(0);\n\n node.installNodePolicy(policy);\n expect(node.hasPolicy).toBe(true);\n expect(node.nodePolicies.length).toBe(1);\n \n node.uninstallNodePolicy('testPolicy');\n expect(node.hasPolicy).toBe(false);\n expect(node.nodePolicies.length).toBe(0); \n })\n\n});\n\n\n\n\n" }, { "alpha_fraction": 0.40003859996795654, "alphanum_fraction": 0.40592530369758606, "avg_line_length": 36.27218246459961, "blob_id": "1321886d52a9cc6746a4fec55b90cf2940b3a9f8", "content_id": "4ef736103322186172b16f5e0a6e27668d675245", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 31087, "license_type": "permissive", "max_line_length": 135, "num_lines": 834, "path": "/app/components/graphobjects/graph/graph.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * The base class the graph object. Any nodes or links that are contained in\n * its nodes or links property will be drawn on updateGraph.\n * Supports policies.\n * \n * To write your own graph object, create a new factory that uses the graph\n * you want to inherit as a dependency, and extend its graph class. \n * Return the class object with Graph as key.\n * \n */\nangular.module('contiv.graph')\n .factory('Graph', ['PolicyService', function (PolicyService) {\n class Graph {\n /**\n * constructor for the graph\n *\n * @param {HTML SVG} svg The svg that will \n * hold the graph\n * @param {Array} nodes List of nodes for the graph\n * @param {Array} links List of links for the graph\n */\n constructor(svg, nodes, links) {\n var thisGraph = this;\n\n thisGraph.nodes = nodes || [];\n thisGraph.links = links || [];\n\n thisGraph.defaultNodePolicies = [];\n thisGraph.defaultPathPolicies = [];\n\n thisGraph.svgPolicy = new PolicyService.Policy();\n\n thisGraph.state = {\n canZoom: true,\n canPan: true,\n initForce: false,\n disableUpdate: false\n };\n\n thisGraph.consts = {\n circleGClass: \"conceptG\",\n graphClass: \"graph\",\n pathClass: \"path\",\n nodeClass: \"circle\",\n nodeText: \"nodeText\",\n startRadius: 50,\n maxRadius: 60,\n padding: 5,\n displayOffset: 60\n };\n\n svg.on(\"mouseover\", function(d){\n thisGraph.svgPolicy[\"mouseover\"].call(this, d); \n })\n .on(\"dblclick\", function(d) {\n thisGraph.svgPolicy[\"dblclick\"].call(this, d); \n })\n .on(\"contextmenu\", function(d) {\n thisGraph.svgPolicy[\"contextmenu\"].call(this, d); \n })\n .on(\"mouseout\", function(d){\n thisGraph.svgPolicy[\"mouseout\"].call(this, d); \n })\n .on(\"mousedown\", function(d){\n thisGraph.svgPolicy[\"mousedown\"].call(this, d); \n })\n .on(\"mouseup\", function(d){\n thisGraph.svgPolicy[\"mouseup\"].call(this, d); \n });\n\n // define arrow markers for graph links\n var defs = svg.append('svg:defs');\n defs.append('svg:marker')\n .attr('id', 'end-arrow')\n .attr(\"viewBox\", \"0 -5 10 10\")\n .attr(\"refX\", 20)\n .attr(\"refY\", -1)\n .attr(\"markerWidth\", 6)\n .attr(\"markerHeight\", 6)\n .attr(\"orient\", \"auto\")\n .append(\"path\")\n .attr(\"d\", \"M0,-5L10,0L0,5\");\n\n // define arrow markers for leading arrow\n defs.append('svg:marker')\n .attr('id', 'mark-end-arrow')\n .attr('viewBox', '0 -5 10 10')\n .attr('refX', 7)\n .attr('markerWidth', 3.5)\n .attr('markerHeight', 3.5)\n .attr('orient', 'auto')\n .append('svg:path')\n .attr('d', 'M0,-5L10,0L0,5');\n\n thisGraph.svg = svg;\n thisGraph.svgG = svg.append(\"g\")\n .classed(thisGraph.consts.graphClass, true);\n var svgG = thisGraph.svgG;\n\n // svg nodes and links \n thisGraph.paths = svgG.append(\"g\").selectAll(\"g\");\n thisGraph.circles = svgG.append(\"g\").selectAll(\"g\");\n thisGraph.initNodes();\n thisGraph.initLinks();\n\n thisGraph.setPositions();\n var resizeFunc = function() {\n thisGraph.onWindowResize(svg);\n };\n\n thisGraph.bindings = {\n resize:resizeFunc\n };\n $(window).resize(resizeFunc);\n }\n\n /**\n * calls the destroy method for all policies\n */\n destroy() {\n var thisGraph = this;\n _(thisGraph.defaultNodePolicies).forEach(function(policy) {\n policy.destroy();\n });\n _(thisGraph.defaultPathPolicies).forEach(function(policy) {\n policy.destroy();\n });\n thisGraph.svgPolicy.destroy();\n for (var key in thisGraph.bindings) {\n $(window).off(key, thisGraph.bindings[key]);\n }\n }\n\n /**\n * Runs the init function for all the nodes\n */\n initNodes() {\n var thisGraph = this;\n _.forEach(thisGraph.nodes, function(node) {\n node.initialize(thisGraph);\n });\n }\n\n /**\n * Runs the init function for all the links\n */\n initLinks() {\n var thisGraph = this;\n _.forEach(thisGraph.links, function(link) {\n link.initialize(thisGraph);\n });\n }\n\n /**\n * returns the node matching the id, \n * or undefined if there is none\n *\n * @param {Object} id The identifier\n * @return {Node} { matching node }\n */\n findNodeById(id){\n var thisGraph = this;\n for (var i = 0; i < thisGraph.nodes.length; i++) {\n if (id === thisGraph.nodes[i].id) {\n return thisGraph.nodes[i];\n }\n }\n };\n\n /**\n * Returns the d3Node object that matches the id,\n * or undefined if there is none\n *\n * @param {string} id The identifier\n * @return {D3Node} The d3 node\n */\n findD3Node(id) {\n var thisGraph = this;\n var d3Node;\n thisGraph.circles.each(function(d) {\n if (d.id === id) {\n d3Node = d3.select(this);\n }\n });\n return d3Node;\n }\n\n /**\n * Used to install a drag policy that will be called\n * when nodes are dragged\n *\n * @param {d3.behavior.drag} d3drag D3 drag object\n */\n installDragPolicy(d3drag) {\n this.drag = d3drag;\n }\n\n /**\n * Used to install a policy that will be called \n * when there is mouse interactions with the graph's svg\n *\n * @param {Policy} policy The policy to install\n */\n installSvgPolicy(policy) {\n this.svgPolicy = policy;\n }\n\n /**\n * Used to install policies that are called when there is\n * mouse interaction with a node\n *\n * @param {Policy} policy The policy to install\n */\n installDefaultNodePolicy(policy) {\n var thisGraph = this;\n thisGraph.defaultNodePolicies.push(policy);\n policy.initialize(thisGraph);\n }\n\n\n /**\n * Used to remove an installed policy for nodes\n *\n * @param {Node} policyRemove The policy to remove\n */\n uninstallDefaultNodePolicy(policyRemove) {\n var policyRemoveName;\n if (typeof policyRemove === 'string') {\n policyRemoveName = policyRemove;\n } else {\n policyRemoveName = policyRemove.policyName;\n }\n _(thisGraph.defaultNodePolicies).forEach(function(policy, index) {\n if (policy.policyName === policyRemoveName) {\n policy.destroy();\n thisGraph.defaultNodePolicies.splice(index, 1);\n }\n });\n }\n\n /**\n * Returns the node policy object with the given name\n *\n * @param {string} policyName The policy name\n * @return {Policy} policy The matching policy\n */\n getNodePolicy(policyName) {\n \tvar thisGraph = this;\n\n _(thisGraph.defaultNodePolicies).forEach(function(policy, index) {\n if (policy.policyName === policyName) {\n return policy;\n }\n });\n }\n\n /**\n * Used to install policies that are called when there is a\n * mouse interaction with a path\n *\n * @param {Policy} policy The policy to install\n */\n installDefaultPathPolicy(policy) {\n var thisGraph = this;\n thisGraph.defaultPathPolicies.push(policy);\n policy.initialize(thisGraph);\n }\n\n /**\n * Used to remove an installed policy for links\n *\n * @param {Policy} policyRemove The policy to remove\n */\n uninstallDefaultPathPolicy(policyRemove) {\n var policyRemoveName;\n var thisGraph = this;\n if (typeof policyRemove === 'string') {\n policyRemoveName = policyRemove;\n } else {\n policyRemoveName = policyRemove.policyName;\n }\n _(thisGraph.defaultPathPolicies).forEach(function(policy, index) {\n if (policy.policyName === policyRemoveName) {\n policy.destroy();\n thisGraph.defaultPathPolicies.splice(index, 1);\n }\n });\n }\n \n /**\n * Called when there is a mouse interaction with a path\n * Propogates the event to all installed path policies\n *\n * @param {string} event The event type\n * @param {d3object} d3path The d3 path\n * @param {Path} d The matching Link object\n */\n pathPolicyEvent(event, d3path, d) {\n var thisGraph = this;\n _(thisGraph.defaultPathPolicies).forEach(function(policy) {\n policy[event](d3path, d);\n })\n }\n\n /**\n * Called when there is a mouse interaction with a node\n * Propogates the event to all installed node policies\n * \n * @param {string} event The event type\n * @param {d3object} d3node The d3 node\n * @param {Path} d The matching Node object\n */\n nodePolicyEvent(event, d3node, d) {\n var thisGraph = this;\n _.forEach(thisGraph.defaultNodePolicies, function(policy) {\n policy[event](d3node, d);\n })\n }\n\n /**\n * Sets pan and zoom rules for the graph\n *\n * @param {d3.behavior.zoom} d3zoom D3 zoom obj\n */\n installZoomPolicy(d3zoom) {\n this.dragSvg = d3zoom;\n this.svg.call(this.dragSvg);\n }\n\n /**\n * Called when the window is resized\n * Hook for overriding in subclasses\n *\n * @param {HTML SVG} svg The svg that the handler\n * is attached to\n */\n onWindowResize(svg) {}\n\n /**\n * Inserts line breaks in node text\n *\n * @param {HTML Elem} gEl The elem to add text to\n * @param {string} title The title\n */\n insertTitleLinebreaks (gEl, title) {\n var thisGraph = this;\n var words = title.split(/\\s+/g),\n nwords = words.length;\n var el = gEl.append(\"text\")\n .attr('class', thisGraph.consts.nodeText)\n .attr(\"text-anchor\",\"middle\")\n .attr(\"dy\", \"-\" + (nwords-1)*7.5);\n\n for (var i = 0; i < words.length; i++) {\n var tspan = el.append('tspan').text(words[i]);\n if (i > 0)\n tspan.attr('x', 0).attr('dy', '15');\n }\n }\n\n /**\n * Removes all links from the given node\n *\n * @param {Node} node The node\n */\n spliceLinksForNode(node) {\n var thisGraph = this,\n toSplice = thisGraph.links.filter(function(l) {\n return (l.source === node || l.target === node);\n });\n toSplice.map(function(l) {\n thisGraph.links.splice(thisGraph.links.indexOf(l), 1);\n });\n }\n\n /**\n * Adds the node to the graph and updates\n *\n * @param {Node} node The node\n */\n addNode(node) {\n var thisGraph = this;\n thisGraph.nodes.push(node);\n node.initialize(thisGraph);\n thisGraph.updateGraph();\n };\n\n /**\n * Removes the node to the graph and updates\n *\n * @param {Node} node The node\n */\n removeNode(node) {\n var thisGraph = this;\n thisGraph.nodes.splice(thisGraph.nodes.indexOf(node), 1);\n thisGraph.spliceLinksForNode(node);\n\n thisGraph.updateGraph();\n };\n\n /**\n * Adds the link to the graph and updates\n *\n * @param {link} link The link\n */\n addLink(link) {\n var thisGraph = this;\n thisGraph.links.push(link);\n link.initialize(thisGraph);\n thisGraph.updateGraph();\n };\n\n /**\n * Removes the link to the graph and updates\n *\n * @param {link} link The link\n */\n removeLink(link) {\n var thisGraph = this;\n thisGraph.links.splice(thisGraph.links.indexOf(link), 1);\n link.initialize(thisGraph);\n thisGraph.updateGraph();\n }\n\n /**\n * Called when the graph is updating existing paths\n *\n * @param {Path} paths List of paths\n */\n updateExistingPaths(paths) {\n paths.each(function(d) {\n d.updateAttr(d3.select(this), d);\n });\n }\n\n /**\n * Called when the graph is adding new paths\n *\n * @param {Path} newPaths List of new paths\n */\n updateNewPaths(newPaths) {\n var thisGraph = this;\n\n thisGraph.initLinks();\n\n newPaths.each(function(d) {\n d.newPathAttr(d3.select(this), d);\n });\n\n //if node doesn't have its own policy, use default for the graph\n newPaths.on(\"mouseover\", function(d){\n if (d.hasPolicy) {\n d.pathPolicyEvent(\"mouseover\", d3.select(this), d); \n } else {\n thisGraph.pathPolicyEvent(\"mouseover\", d3.select(this), d); \n }\n })\n .on(\"dblclick\", function(d) {\n if (d.hasPolicy) {\n d.pathPolicyEvent(\"dblclick\", d3.select(this), d); \n } else {\n thisGraph.pathPolicyEvent(\"dblclick\", d3.select(this), d); \n }\n })\n .on(\"contextmenu\", function(d) {\n if (d.hasPolicy) {\n d.pathPolicyEvent(\"contextmenu\", d3.select(this), d); \n } else {\n thisGraph.pathPolicyEvent(\"contextmenu\", d3.select(this), d); \n }\n })\n .on(\"mouseout\", function(d){\n if (d.hasPolicy) {\n d.pathPolicyEvent(\"mouseout\", d3.select(this), d); \n } else {\n thisGraph.pathPolicyEvent(\"mouseout\", d3.select(this), d); \n }\n })\n .on(\"mousedown\", function(d){\n if (d.hasPolicy) {\n d.pathPolicyEvent(\"mousedown\", d3.select(this), d); \n } else {\n thisGraph.pathPolicyEvent(\"mousedown\", d3.select(this), d); \n }\n })\n .on(\"mouseup\", function(d){\n if (d.hasPolicy) {\n d.pathPolicyEvent(\"mouseup\", d3.select(this), d); \n } else {\n thisGraph.pathPolicyEvent(\"mouseup\", d3.select(this), d); \n }\n })\n .call(thisGraph.drag);\n }\n\n\n /**\n * Called when the graph is updating existing nodes\n */\n updateExistingNodes() {\n var thisGraph = this;\n thisGraph.circles = this.circles.data(thisGraph.nodes, function(d){ return d.id;})\n .each(function(d) {\n d.updateAttr(d3.select(this), d);\n });\n\n }\n\n /**\n * Called when the graph is adding new nodes\n *\n * @param {Node} newNodes List of new nodes\n */\n updateNewNodes(newNodes) {\n var thisGraph = this;\n\n newNodes.each(function(d) {\n if (d.graph == null) {\n d.initialize(thisGraph);\n }\n d.newNodeAttr(d3.select(this), d);\n });\n\n \n //if node doesn't have its own policy, use default for the graph\n newNodes.on(\"mouseover\", function(d){\n if (d.hasPolicy) {\n d.nodePolicyEvent(\"mouseover\", d3.select(this), d); \n } else {\n thisGraph.nodePolicyEvent(\"mouseover\", d3.select(this), d); \n }\n })\n .on(\"dblclick\", function(d) {\n if (d.hasPolicy) {\n d.nodePolicyEvent(\"dblclick\", d3.select(this), d); \n } else {\n thisGraph.nodePolicyEvent(\"dblclick\", d3.select(this), d); \n }\n })\n .on(\"contextmenu\", function(d) {\n if (d.hasPolicy) {\n d.nodePolicyEvent(\"contextmenu\", d3.select(this), d); \n } else {\n thisGraph.nodePolicyEvent(\"contextmenu\", d3.select(this), d); \n }\n })\n .on(\"mouseout\", function(d){\n if (d.hasPolicy) {\n d.nodePolicyEvent(\"mouseout\", d3.select(this), d); \n } else {\n thisGraph.nodePolicyEvent(\"mouseout\", d3.select(this), d); \n }\n })\n .on(\"mousedown\", function(d){\n if (d.hasPolicy) {\n d.nodePolicyEvent(\"mousedown\", d3.select(this), d); \n } else {\n thisGraph.nodePolicyEvent(\"mousedown\", d3.select(this), d); \n }\n })\n .on(\"mouseup\", function(d){\n if (d.hasPolicy) {\n d.nodePolicyEvent(\"mouseup\", d3.select(this), d); \n } else {\n thisGraph.nodePolicyEvent(\"mouseup\", d3.select(this), d); \n }\n })\n .call(thisGraph.drag);\n\n newNodes.append(\"circle\")\n .attr(\"r\", function(d) {return String(d.radius)});\n\n\n newNodes.each(function(d){\n thisGraph.insertTitleLinebreaks(d3.select(this), d.text);\n });\n }\n\n /**\n * Prevents nodes from colliding\n *\n * @param {number} alpha Affects how much change\n * the collision causes\n * @return {boolean} {Whether nodes are collided}\n */\n d3ForceCollide(alpha) {\n \tvar thisGraph = this,\n \t\tconsts = thisGraph.consts;\n \tvar nodes = thisGraph.nodes;\n \tvar quadtree = d3.geom.quadtree(nodes);\n return function(d) {\n var r = d.radius + consts.maxRadius + consts.padding,\n nx1 = d.x - r,\n nx2 = d.x + r,\n ny1 = d.y - r,\n ny2 = d.y + r;\n quadtree.visit(function(quad, x1, y1, x2, y2) {\n if (quad.point && (quad.point !== d)) {\n var x = d.x - quad.point.x,\n y = d.y - quad.point.y,\n l = Math.sqrt(x * x + y * y),\n r = d.radius + quad.point.radius + consts.padding;\n if (l < r) {\n l = (l - r) / l * alpha;\n d.x -= x *= l;\n d.y -= y *= l;\n quad.point.x += x;\n quad.point.y += y;\n }\n }\n return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1;\n });\n };\n }\n\n /**\n * Tick of the d3 force simulation\n *\n * @param {D3tick event} e D3tick event\n * @param {number} width The width of the simulation\n * @param {number} height The height of the simulation\n */\n d3ForceTick(e, width, height) {\n \tvar thisGraph = this,\n \t\tconsts = thisGraph.consts;\n\n \tvar offset = consts.displayOffset;\t\n \tvar nodes = thisGraph.nodes;\n \tvar q = d3.geom.quadtree(thisGraph.nodes),\n i = 0,\n n = nodes.length;\n\n while (++i < n) {\n q.visit(this.d3ForceCollide(nodes[i]));\n }\n\n thisGraph.circles.each(this.d3ForceCollide(.5))\n .attr(\"cx\", function(d) { return d.x = Math.max(d.radius + offset, Math.min(width - offset - d.radius, d.x)); })\n .attr(\"cy\", function(d) { return d.y = Math.max(d.radius + offset, Math.min(height - offset - d.radius, d.y)); });\n\n thisGraph.paths\n .attr('x1', function(d) { return d.source.x; })\n .attr('y1', function(d) { return d.source.y; })\n .attr('x2', function(d) { return d.target.x; })\n .attr('y2', function(d) { return d.target.y; });\n }\n\n /**\n * Starts on start of the force simulation\n */\n d3ForceStart() {\n \tvar thisGraph = this;\n thisGraph.paths\n .attr('x1', function(d) { return d.source.x; })\n .attr('y1', function(d) { return d.source.y; })\n .attr('x2', function(d) { return d.target.x; })\n .attr('y2', function(d) { return d.target.y; });\n }\n\n /**\n * Called on the end of the force simulation\n */\n d3ForceEnd() {\n \tvar thisGraph = this;\n \tthisGraph.circles\n .attr('cx', function(d) { return d.x; })\n .attr('cy', function(d) { return d.y; });\n\n thisGraph.paths.attr('x1', function(d) { return d.source.x; })\n .attr('y1', function(d) { return d.source.y; })\n .attr('x2', function(d) { return d.target.x; })\n .attr('y2', function(d) { return d.target.y; });\n }\n\n /**\n * Calculates the width and height bounds for the \n * force simulation\n *\n * @return {Object} width and height as properties \n */\n d3ForceBounds() {\n var svgWidth = $('#visualization-graph').width();\n var svgHeight = $('#visualization-graph').height();\n\n var width = svgWidth;\n var height = svgHeight;\n return {width:width, height:height};\n }\n\n /**\n * Does a d3 force simulation\n *\n * @param {Function} callback The callback\n */\n setForce(callback) {\n var thisGraph = this;\n\n var nodes = thisGraph.nodes;\n var links = thisGraph.links;\n if (_.isEmpty(nodes)) {\n return;\n }\n\n var bounds = thisGraph.d3ForceBounds();\n\n var force = d3.layout.force()\n .size([bounds.width, bounds.height])\n .nodes(nodes)\n .charge(function(d) {\n return -6000;\n })\n .links(links);\n\n force.linkDistance(bounds.width/3);\n force.linkStrength(.2);\n force.gravity(.2);\n\n force.on('tick', function(e) {\n \tthisGraph.d3ForceTick.call(thisGraph, \n \t\t\te, bounds.width, bounds.height);\n });\n\n force.on('start', function() {\n \tthisGraph.d3ForceStart.call(thisGraph)\n });\n\n force.on('end', function() {\n \tthisGraph.d3ForceEnd.call(thisGraph)\n }); \n\n\n force.start();\n var k = 0;\n while ((force.alpha() > 1e-2) && (k < 150)) {\n force.tick();\n k = k + 1;\n }\n force.stop();\n\n if (callback != null) {\n \tcallback();\n }\n }\n\n /**\n * Sets the positions to be the center of the screen if \n * not provided\n * also sets the radius of the nodes\n */\n setPositions() {\n var thisGraph = this;\n\n var offset = thisGraph.consts.displayOffset;\n var svgWidth = $('#visualization-graph').width();\n var svgHeight = $('#visualization-graph').height();\n\n var width = svgWidth - (2*offset);\n var height = svgHeight - (2*offset);\n\n var nodes = thisGraph.nodes;\n\n for (var i = 0; i < nodes.length; i++) {\n nodes[i].radius = nodes[i].radius || thisGraph.consts.startRadius;\n if (nodes[i].x == null || nodes[i].y == null) {\n // nodes[i].xStart = width/2 + nodes[i].radius + offset\n nodes[i].x = width/2 + nodes[i].radius + offset;\n // nodes[i].yStart = height/2 + nodes[i].radius + offset\n nodes[i].y = height/2 + nodes[i].radius + offset\n }\n }\n }\n\n /**\n * Called to update the view of the graph when\n * data changes\n *\n * @param {Function} callback The callback\n */\n updateGraph(callback) {\n var thisGraph = this,\n consts = thisGraph.consts,\n state = thisGraph.state;\n\n \tif (thisGraph.state.disableUpdate) {\n \t\treturn;\n \t}\n\n this.updateExistingNodes();\n var newGs= thisGraph.circles.enter()\n .append(\"g\");\n\n \t// console.log('update', newGs);\n newGs.classed(consts.circleGClass, true);\n \n // this.updateNewNodes(newGs);\n\n // remove old nodes\n thisGraph.circles.exit().remove();\n\n if (state.initForce == false) {\n thisGraph.setForce(function() {\n \t thisGraph.updateNewNodes.call(thisGraph, newGs);\n });\n state.initForce = true;\n } else {\n\t this.updateNewNodes(newGs);\n\t }\n\n thisGraph.paths = thisGraph.paths.data(thisGraph.links, function(d){\n return String(d.source.id) + \"+\" + String(d.target.id);\n });\n var paths = thisGraph.paths;\n this.updateExistingPaths(paths);\n\n var newpaths = paths.enter()\n .append(\"path\")\n .style('marker-end','url(#end-arrow)')\n .classed(\"link\", true);\n this.updateNewPaths(newpaths);\n\n // remove old links\n paths.exit().remove();\n\n if (callback != null) {\n \tcallback();\n }\n\n }\n }\n\n return {\n Graph: Graph\n }\n}]);\n\n\n" }, { "alpha_fraction": 0.5514458417892456, "alphanum_fraction": 0.553463339805603, "avg_line_length": 36.20000076293945, "blob_id": "e0d5864fe7804d7b4b57c269d1e90da4679881f5", "content_id": "241378559127bb09a353b65af2c7323aeba8269d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1487, "license_type": "permissive", "max_line_length": 110, "num_lines": 40, "path": "/app/components/models/policiesmodel.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { Http } from '@angular/http';\nimport { Collection } from \"./collection\";\nimport { ContivGlobals } from \"./contivglobals\";\nimport {ApiService} from \"../utils/apiservice\";\nimport {isUndefined} from \"util\";\n\n@Injectable()\nexport class PoliciesModel extends Collection {\n constructor(http: Http, apiService: ApiService) {\n super(http, ContivGlobals.POLICIES_ENDPOINT, apiService);\n }\n\n /**\n * Generate policy key to save policy on server\n * @param policy\n * @returns {string}\n */\n generateKey(policy) {\n return policy.tenantName + ':' + policy.policyName;\n }\n\n getInspectByKey(key:string, url: string, reload: boolean): Promise<any>{\n return super.getInspectByKey(key,url,reload)\n .then((result) => {\n if(!isUndefined(result['Oper'].endpoints)){\n var processedEndpoints = [];\n var endpoints = result['Oper'].endpoints;\n for(var i=0; i<endpoints.length; i++){\n if(isUndefined(endpoints[i].containerID)){\n endpoints[i]['containerID'] = endpoints[i]['endpointID'];\n endpoints[i]['containerName'] = endpoints[i]['endpointID'].toString().substr(0,6);\n }\n }\n result['Oper'].endpoints = endpoints;\n }\n return result;\n });\n }\n}" }, { "alpha_fraction": 0.6582106947898865, "alphanum_fraction": 0.6587992906570435, "avg_line_length": 41.477500915527344, "blob_id": "84ed243bd23b39ede633f0e034a5bd87fc0f1fdb", "content_id": "42403ebf47a738c1e74ad814c51c695b8384632b", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 16990, "license_type": "permissive", "max_line_length": 155, "num_lines": 400, "path": "/app/network_policies/isolationpolicydetailsctrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 3/8/16.\n */\nimport { Component, Inject } from '@angular/core';\nimport { ActivatedRoute, Router } from \"@angular/router\";\nimport { PoliciesModel } from \"../components/models/policiesmodel\";\nimport { RulesModel } from \"../components/models/rulesmodel\";\nimport { NetworksModel } from \"../components/models/networksmodel\";\nimport { ApplicationGroupsModel } from \"../components/models/applicationgroupsmodel\";\nimport { CRUDHelperService } from \"../components/utils/crudhelperservice\";\nimport { PolicyTab } from \"./networkpoliciestabsctrl\";\nimport { ContivGlobals } from \"../components/models/contivglobals\";\n\n@Component({\n selector: 'isolationpolicydetails',\n templateUrl: './isolationpolicydetails.html'\n})\nexport class IsolationPolicyDetailsComponent {\n policy:any = {};\n incomingRules:any[] = [];\n outgoingRules:any[] = [];\n mode:string = 'details';\n newIncomingRule:any = {};\n newOutgoingRule:any = {};\n networks:any[] = [];\n applicationGroups:any[] = [];\n disableOutgoingNetworkSelection:boolean = false;\n disableIncomingNetworkSelection:boolean = false;\n disableOutgoingApplicationGroupSelection:boolean = false;\n disableIncomingApplicationGroupSelection:boolean = false;\n disableIncomingIPAddressSelection:boolean = false;\n disableOutgoingIPAddressSelection:boolean = false;\n newIncomingSelectedApplicationGroup:string = '';\n newOutgoingSelectedApplicationGroup:string = '';\n newIncomingSelectedNetwork:string = '';\n newOutgoingSelectedNetwork:string = '';\n incorrectCIDR:boolean = false;\n validateCIDRFlag:boolean = false;\n infoselected: boolean = true;\n statskey: string = ''\n\n constructor(private activatedRoute: ActivatedRoute,\n private router: Router,\n private policiesModel:PoliciesModel,\n private rulesModel:RulesModel,\n private networksModel:NetworksModel,\n private applicationGroupsModel:ApplicationGroupsModel,\n private crudHelperService:CRUDHelperService) {\n var isolationPolicyDetailsCtrl = this;\n this.statskey = activatedRoute.snapshot.params['key'];\n\n /**\n * To show edit or details screen based on the route\n */\n function setMode() {\n if (activatedRoute.routeConfig.path.includes('edit')) {\n isolationPolicyDetailsCtrl.mode = 'edit';\n } else {\n isolationPolicyDetailsCtrl.mode = 'details';\n }\n }\n\n\n /**\n * Get network names for the given tenant.\n */\n function getNetworks() {\n isolationPolicyDetailsCtrl.networksModel.get(false).then(function (result) {\n //_.filter() returns a new array\n isolationPolicyDetailsCtrl.networks = _.filter(result, {\n 'tenantName': isolationPolicyDetailsCtrl['policy'].tenantName\n });\n },(err)=>{});\n }\n\n /**\n * Get application group names for the given tenant.\n */\n function getApplicationGroups() {\n isolationPolicyDetailsCtrl.applicationGroupsModel.get(false)\n .then(function (result) {\n //_.filter() returns a new array\n isolationPolicyDetailsCtrl.applicationGroups = _.filter(result, {\n 'tenantName': isolationPolicyDetailsCtrl['policy'].tenantName\n });\n });\n }\n\n isolationPolicyDetailsCtrl.crudHelperService.stopLoader(isolationPolicyDetailsCtrl);\n\n isolationPolicyDetailsCtrl.policiesModel.getModelByKey(activatedRoute.snapshot.params['key'], false, 'key')\n .then(function (policy) {\n isolationPolicyDetailsCtrl.policy = policy;\n isolationPolicyDetailsCtrl.rulesModel.getIncomingRules(policy.policyName, policy.tenantName).then(function (result) {\n isolationPolicyDetailsCtrl.incomingRules = result;\n isolationPolicyDetailsCtrl.resetNewIncomingRule();\n });\n isolationPolicyDetailsCtrl.rulesModel.getOutgoingRules(policy.policyName, policy.tenantName).then(function (result) {\n isolationPolicyDetailsCtrl.outgoingRules = result;\n isolationPolicyDetailsCtrl.resetNewOutgoingRule();\n });\n });\n\n getNetworks();\n getApplicationGroups();\n setMode();\n }\n\n returnToPolicies() {\n this.router.navigate(['../../../list', {policyTab: PolicyTab.isolation}], { relativeTo: this.activatedRoute });\n }\n\n returnToPolicyDetails() {\n this.router.navigate(['../../details', this.policy.key], { relativeTo: this.activatedRoute });\n }\n\n editPolicy() {\n this.router.navigate(['../../edit', this.policy.key], { relativeTo: this.activatedRoute });\n }\n\n cancelDetails() {\n this.returnToPolicies();\n }\n\n cancelEditing() {\n this.returnToPolicyDetails();\n }\n\n /**\n * Go back to policy details after done editing\n */\n doneEditing() {\n this.returnToPolicyDetails();\n }\n\n deletePolicy() {\n var isolationPolicyDetailsCtrl = this;\n isolationPolicyDetailsCtrl.crudHelperService.startLoader(isolationPolicyDetailsCtrl);\n isolationPolicyDetailsCtrl.policiesModel.delete(isolationPolicyDetailsCtrl.policy).then(function successCallback(result) {\n isolationPolicyDetailsCtrl.crudHelperService.stopLoader(isolationPolicyDetailsCtrl);\n isolationPolicyDetailsCtrl.crudHelperService.showNotification(\"Isolation policy: Deleted\", result);\n isolationPolicyDetailsCtrl.returnToPolicies();\n }, function errorCallback(result) {\n isolationPolicyDetailsCtrl.crudHelperService.stopLoader(isolationPolicyDetailsCtrl);\n isolationPolicyDetailsCtrl.crudHelperService.showServerError(\"Isolation policy: Delete failed\", result);\n });\n }\n\n validateCIDR(ipaddress) {\n var cidrPattern = new RegExp(ContivGlobals.CIDR_REGEX);\n\n if (ipaddress == '') {\n return true;\n }\n\n if (cidrPattern.test(ipaddress)) {\n this.incorrectCIDR = false;\n return true;\n }\n this.incorrectCIDR = true;\n this.validateCIDRFlag = true;\n return false;\n }\n\n resetNewIncomingRule() {\n //Rule object to be created on server\n this.newIncomingRule = {\n ruleId: '',\n priority: 1,\n action: 'allow',//to make it default selected option in UI\n fromEndpointGroup: '',\n fromNetwork: '',\n fromIpAddress: '',\n protocol: 'tcp',//to make it default selected option in UI\n port: 0,\n direction: 'in',\n tenantName: this.policy.tenantName,\n policyName: this.policy.policyName\n };\n this.newIncomingSelectedApplicationGroup = '';\n this.newIncomingSelectedNetwork = '';\n this.disableIncomingNetworkSelection = false;\n this.disableIncomingApplicationGroupSelection = false;\n this.disableIncomingIPAddressSelection = false;\n this.incorrectCIDR = false;\n this.validateCIDRFlag = false;\n }\n\n resetNewOutgoingRule() {\n //Rule object to be created on server\n this.newOutgoingRule = {\n ruleId: '',\n priority: 1,\n action: 'allow',//to make it default selected option in UI\n toEndpointGroup: '',\n toNetwork: '',\n toIpAddress: '',\n protocol: 'tcp',//to make it default selected option in UI\n port: 0,\n direction: 'out',\n tenantName: this.policy.tenantName,\n policyName: this.policy.policyName\n };\n this.newOutgoingSelectedApplicationGroup = '';\n this.newOutgoingSelectedNetwork = '';\n this.disableOutgoingNetworkSelection = false;\n this.disableOutgoingApplicationGroupSelection = false;\n this.disableOutgoingIPAddressSelection = false;\n this.incorrectCIDR = false;\n this.validateCIDRFlag = false;\n }\n\n /**\n * Event handler to disable network selection box once application group is selected while creating a new\n * rule.\n */\n onChangeOutgoingApplicationGroupSelection(group: string) {\n if (group) {\n //If application group has been selected\n this.newOutgoingRule.toEndpointGroup = group;\n this.newOutgoingRule.toNetwork = '';\n this.disableOutgoingNetworkSelection = true;\n } else {\n //When 'none' is selected\n this.newOutgoingRule.toEndpointGroup = '';\n this.disableOutgoingNetworkSelection = false;\n }\n }\n\n /**\n * Event handler to disable network selection box once application group is selected while creating a new\n * rule.\n */\n onChangeIncomingApplicationGroupSelection(group: string) {\n if (group) {\n //If application group has been selected\n this.newIncomingRule.fromEndpointGroup = group;\n this.newIncomingRule.fromNetwork = '';\n this.disableIncomingNetworkSelection = true;\n } else {\n //When 'none' is selected\n this.newIncomingRule.fromEndpointGroup = '';\n this.disableOutgoingApplicationGroupSelection = false;\n this.disableIncomingNetworkSelection = false;\n }\n\n }\n\n /**\n * Event handler to disable application group selection box once network is selected while creating a new\n * rule.\n */\n onChangeOutgoingNetworkSelection(network: string) {\n if (network) {\n //If network has been selected\n this.newOutgoingRule.toNetwork = network;\n this.newOutgoingRule.ToEndpointGroup = '';\n this.disableOutgoingApplicationGroupSelection = true;\n this.disableOutgoingIPAddressSelection = true;\n } else {\n this.newOutgoingRule.toIpAddress = '';\n this.disableOutgoingApplicationGroupSelection = false;\n this.disableOutgoingIPAddressSelection = false;\n }\n }\n\n /**\n * Event handler to disable application group selection box once network is selected while creating a new\n * rule.\n */\n onChangeIncomingNetworkSelection(network: string) {\n if (network) {\n //If network has been selected\n this.newIncomingRule.fromNetwork = network;\n this.newIncomingRule.fromEndpointGroup = '';\n this.disableIncomingApplicationGroupSelection = true;\n this.disableIncomingIPAddressSelection = true;\n } else {\n this.newIncomingRule.fromNetwork = '';\n this.disableIncomingApplicationGroupSelection = false;\n this.disableIncomingIPAddressSelection = false;\n }\n }\n\n onChangeIncomingIPAddress() {\n if (this.newIncomingRule.fromIpAddress == '') {\n this.incorrectCIDR = false;\n this.disableIncomingNetworkSelection = false;\n } else {\n this.disableIncomingNetworkSelection = true;\n }\n\n if (this.validateCIDRFlag &&\n this.incorrectCIDR) {\n this.validateCIDR(this.newIncomingRule.fromIpAddress);\n }\n }\n\n onChangeOutgoingIPAddress() {\n if (this.newOutgoingRule.toIpAddress == '') {\n this.incorrectCIDR = false;\n this.disableOutgoingNetworkSelection = false;\n } else {\n this.disableOutgoingNetworkSelection = true;\n }\n\n if (this.validateCIDRFlag &&\n this.incorrectCIDR) {\n this.validateCIDR(this.newOutgoingRule.toIpAddress);\n }\n }\n\n /**\n * Generates rule id\n * TODO Make it cryptographically stronger once we have multiple users updating same policy\n */\n generateRuleId(rule) {\n rule.ruleId =\n (this.incomingRules.length + this.outgoingRules.length + 1).toString() + '-' +\n Date.now().toString();\n }\n\n /**\n * Rule is saved to server\n */\n addIncomingRule() {\n var isolationPolicyDetailsCtrl = this;\n if (isolationPolicyDetailsCtrl.validateCIDR(isolationPolicyDetailsCtrl.newIncomingRule.fromIpAddress)) {\n isolationPolicyDetailsCtrl.crudHelperService.startLoader(isolationPolicyDetailsCtrl);\n isolationPolicyDetailsCtrl.generateRuleId(isolationPolicyDetailsCtrl.newIncomingRule);\n isolationPolicyDetailsCtrl.newIncomingRule.key = isolationPolicyDetailsCtrl.rulesModel.generateKey(isolationPolicyDetailsCtrl.newIncomingRule);\n isolationPolicyDetailsCtrl.rulesModel.create(isolationPolicyDetailsCtrl.newIncomingRule, undefined).then(function successCallback(result) {\n isolationPolicyDetailsCtrl.crudHelperService.stopLoader(isolationPolicyDetailsCtrl);\n isolationPolicyDetailsCtrl.incomingRules.push(result);\n isolationPolicyDetailsCtrl.resetNewIncomingRule();\n isolationPolicyDetailsCtrl.crudHelperService.showNotification(\"Isolation policy: Incoming rules added\", result.key.toString());\n }, function errorCallback(result) {\n isolationPolicyDetailsCtrl.crudHelperService.stopLoader(isolationPolicyDetailsCtrl);\n isolationPolicyDetailsCtrl.crudHelperService.showServerError(\"Isolation policy: Adding incoming rules failed\", result);\n });\n }\n }\n\n /**\n * Rule is saved to server\n */\n addOutgoingRule() {\n var isolationPolicyDetailsCtrl = this;\n if (isolationPolicyDetailsCtrl.validateCIDR(isolationPolicyDetailsCtrl.newOutgoingRule.toIpAddress)) {\n isolationPolicyDetailsCtrl.crudHelperService.startLoader(isolationPolicyDetailsCtrl);\n isolationPolicyDetailsCtrl.generateRuleId(isolationPolicyDetailsCtrl.newOutgoingRule);\n isolationPolicyDetailsCtrl.newOutgoingRule.key = isolationPolicyDetailsCtrl.rulesModel.generateKey(isolationPolicyDetailsCtrl.newOutgoingRule);\n isolationPolicyDetailsCtrl.rulesModel.create(isolationPolicyDetailsCtrl.newOutgoingRule, undefined).then(function successCallback(result) {\n isolationPolicyDetailsCtrl.crudHelperService.stopLoader(isolationPolicyDetailsCtrl);\n isolationPolicyDetailsCtrl.outgoingRules.push(result);\n isolationPolicyDetailsCtrl.resetNewOutgoingRule();\n isolationPolicyDetailsCtrl.crudHelperService.showNotification(\"Isolation policy: Outgoing rules added\", result.key.toString());\n }, function errorCallback(result) {\n isolationPolicyDetailsCtrl.crudHelperService.stopLoader(isolationPolicyDetailsCtrl);\n isolationPolicyDetailsCtrl.crudHelperService.showServerError(\"Isolation policy: Adding outgoing rules failed\", result);\n });\n }\n }\n\n /**\n * Delete incoming rule from server\n */\n deleteIncomingRule(key) {\n var isolationPolicyDetailsCtrl = this;\n isolationPolicyDetailsCtrl.crudHelperService.startLoader(isolationPolicyDetailsCtrl);\n isolationPolicyDetailsCtrl.rulesModel.deleteUsingKey(key,'key', undefined).then(function successCallback(result) {\n isolationPolicyDetailsCtrl.crudHelperService.stopLoader(isolationPolicyDetailsCtrl);\n _.remove(isolationPolicyDetailsCtrl.incomingRules, function (n) {\n return n.key == key;\n });\n isolationPolicyDetailsCtrl.crudHelperService.showNotification(\"Isolation policy: Incoming rules deleted\", result)\n }, function errorCallback(result) {\n isolationPolicyDetailsCtrl.crudHelperService.stopLoader(isolationPolicyDetailsCtrl);\n isolationPolicyDetailsCtrl.crudHelperService.showServerError(\"Isolation policy: Deleting incoming rules failed\", result);\n });\n }\n\n /**\n * Delete outgoing rule from server\n */\n deleteOutgoingRule(key) {\n var isolationPolicyDetailsCtrl = this;\n isolationPolicyDetailsCtrl.crudHelperService.startLoader(isolationPolicyDetailsCtrl);\n isolationPolicyDetailsCtrl.rulesModel.deleteUsingKey(key, 'key', undefined).then(function successCallback(result) {\n isolationPolicyDetailsCtrl.crudHelperService.stopLoader(isolationPolicyDetailsCtrl);\n _.remove(isolationPolicyDetailsCtrl.outgoingRules, function (n) {\n return n.key == key;\n });\n isolationPolicyDetailsCtrl.crudHelperService.showNotification(\"Isolation policy: Outgoing rules deleted\", result)\n }, function errorCallback(result) {\n isolationPolicyDetailsCtrl.crudHelperService.stopLoader(isolationPolicyDetailsCtrl);\n isolationPolicyDetailsCtrl.crudHelperService.showServerError(\"Isolation policy: Deleting outgoing rules failed\", result);\n });\n }\n}" }, { "alpha_fraction": 0.5957446694374084, "alphanum_fraction": 0.6382978558540344, "avg_line_length": 18, "blob_id": "df6c438948c0d6b33e03a1a2c6580fa9926b0a63", "content_id": "b6e55fb8d44d1a69b0e58da0b90c6a52912e3975", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 94, "license_type": "permissive", "max_line_length": 51, "num_lines": 5, "path": "/karma.webpack.conf.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 4/6/17.\n */\n\nmodule.exports = require('./config/karma.conf.js');" }, { "alpha_fraction": 0.589211642742157, "alphanum_fraction": 0.6016597747802734, "avg_line_length": 23.149999618530273, "blob_id": "0679979a60f9cf89bd1b2042f9c9d2fdbe1dc8aa", "content_id": "d9468125afb1d74a73e03de43bbe909a2308785e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 482, "license_type": "permissive", "max_line_length": 62, "num_lines": 20, "path": "/app/networks/networkinfoctrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 10/25/16.\n */\n\nimport {Component, Input} from \"@angular/core\";\n@Component({\n selector: 'network-info',\n templateUrl: './networkinfo.html'\n})\n\nexport class NetworkInfoComponent {\n @Input('networkDetailsCtrl') networkDetailsCtrl: any;\n constructor(){\n this.networkDetailsCtrl = { network:\n {networkName: '', encap: '', subnet: '', gateway: ''},\n showLoader: false,\n applicationGroups: []\n };\n }\n}" }, { "alpha_fraction": 0.5250325202941895, "alphanum_fraction": 0.5253576040267944, "avg_line_length": 36.98765563964844, "blob_id": "86faa2ead39d4562d84ad712783e1c16508ba35c", "content_id": "a2a5cb7ed447338b54a2b33f3e4c695d0fb4bbed", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3076, "license_type": "permissive", "max_line_length": 83, "num_lines": 81, "path": "/app/login/loginctrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "import { Component, Inject, OnInit, ViewEncapsulation } from \"@angular/core\";\nimport { CRUDHelperService } from \"../components/utils/crudhelperservice\";\nimport { Router } from \"@angular/router\";\nimport { AuthService } from \"../components/utils/authservice\";\nimport { ContivGlobals } from \"../components/models/contivglobals\";\nimport { ChartService } from \"../components/utils/chartservice\";\nimport { FirstRunService } from \"../components/utils/firstrunservice\";\n\ndeclare var jQuery:any;\n\n@Component({\n selector: 'login',\n templateUrl: './login.html',\n styles: [require('./login.css')]\n})\n\nexport class LoginComponent implements OnInit{\n public showLoader: boolean;\n public showServerError: boolean;\n public serverErrorMessage: string;\n public loginCtrl: any;\n public username: string;\n public password: string;\n public product_name:string = ContivGlobals.PRODUCT_NAME;\n \n constructor(private router: Router,\n private crudHelperService: CRUDHelperService,\n private authService: AuthService,\n private firstRunService: FirstRunService,\n private chartService: ChartService){\n this.showLoader = true;\n this.showServerError = false;\n this.username = '';\n this.password = '';\n this.loginCtrl = this;\n }\n\n ngOnInit(){\n this.crudHelperService.stopLoader(this);\n jQuery(\"body\").addClass(\"loginbackground\");\n }\n\n ngOnDestroy(){\n jQuery(\"body\").removeClass(\"loginbackground\");\n }\n\n login(){\n this.crudHelperService.startLoader(this);\n this.authService.login({username: this.username, password: this.password})\n .subscribe((result) => {\n if(result){\n this.showServerError = false;\n this.firstRunService.setFirstRun()\n .then(isFirstRun => {\n this.crudHelperService.stopLoader(this);\n if (isFirstRun) {\n this.router.navigate(['/m/firstrun']);\n }\n else {\n if (this.authService.redirectUrl.length > 0) {\n var redirectUrl = this.authService.redirectUrl;\n this.authService.redirectUrl = '';\n this.router.navigate([redirectUrl]);\n }\n else{\n this.router.navigate(['/m/dashboard']);\n }\n }\n });\n }\n else{\n this.crudHelperService.stopLoader(this);\n this.showServerError = true;\n jQuery('#login-failed').modal('show');\n }\n }, (error) => {\n this.crudHelperService.stopLoader(this);\n this.showServerError = true;\n });\n }\n}" }, { "alpha_fraction": 0.558282196521759, "alphanum_fraction": 0.5603271722793579, "avg_line_length": 33.92856979370117, "blob_id": "34bf5bf9b27a848cd971f9ec1ea7d15a65da5fa5", "content_id": "8359fd9c911f431fb0b4f0281f6a5f1998583e88", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2934, "license_type": "permissive", "max_line_length": 116, "num_lines": 84, "path": "/app/settings/nodes/nodeinfo.component.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 12/7/16.\n */\nimport { Component, Input, OnInit, NgZone } from \"@angular/core\";\nimport { ActivatedRoute, Router } from \"@angular/router\";\nimport { CRUDHelperService } from \"../../components/utils/crudhelperservice\";\nimport { BgpsModel } from \"../../components/models/bgpsmodel\";\n\n@Component({\n selector: 'nodeinfo',\n templateUrl: './nodeinfo.html'\n})\nexport class NodeInfoComponent implements OnInit {\n @Input('mode') mode: string;\n node:any = {};\n\n constructor(private activatedRoute:ActivatedRoute,\n private router:Router,\n private ngZone:NgZone,\n private bgpsModel:BgpsModel,\n private crudHelperService:CRUDHelperService) {\n var component = this;\n\n /**\n * To show edit or details screen based on the route\n */\n function setMode() {\n if (activatedRoute.routeConfig.path.includes('edit')) {\n component.mode = 'edit';\n } else {\n component.mode = 'details';\n }\n }\n\n setMode();\n }\n\n ngOnInit() {\n var component = this;\n component.crudHelperService.stopLoader(component);\n\n component.bgpsModel.getModelByKey(component.activatedRoute.snapshot.params['key'], false, 'key')\n .then(function successCallBack(node) {\n component.node = node;\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n }, (error) => {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n });\n }\n\n returnToNodeDetails() {\n this.router.navigate(['../../details', this.node.key], {relativeTo: this.activatedRoute});\n }\n\n cancelEditing() {\n this.returnToNodeDetails();\n }\n\n saveNode(formvalid:boolean) {\n var component = this;\n if (formvalid) {\n component.crudHelperService.startLoader(component);\n\n component.bgpsModel.save(component.node).then(\n function successCallback(result) {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n component.crudHelperService.showNotification(\"Node: Bgp config updated\", result.key.toString());\n component.returnToNodeDetails();\n }, function errorCallback(result) {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n });\n component.crudHelperService.showServerError(\"Node: Bgp config update failed\", result);\n component.crudHelperService.showServerError(component, result);\n });\n }\n }\n}\n" }, { "alpha_fraction": 0.38596367835998535, "alphanum_fraction": 0.38999223709106445, "avg_line_length": 38.280555725097656, "blob_id": "fc10c3d53e4236dbc255fc67e45666eed4a6f421", "content_id": "fdd4c5764dad4fdb4aef93141592bcd67d1fe183", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 14149, "license_type": "permissive", "max_line_length": 85, "num_lines": 360, "path": "/app/components/graphobjects/policy/splitjoinnodepolicy_test.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "'use strict';\n\ndescribe('SplitJoinNodePolicy', function(){\n var policyFactory;\n var graph;\n var VisualizerNode;\n var envVariables;\n var children_struct;\n var ancestors_struct;\n beforeEach(function(){\n envVariables = {\n \"nodes\": [\n {\n \"name\":\"Web\",\n \"id\": 0,\n \"ancestors\": null\n },\n {\n \"name\":\"Passenger App Container\",\n \"id\": 1,\n \"parent\": \"Passenger App\",\n \"ancestors\":\"Passenger App, Passenger\"\n },\n {\n \"name\":\"Passenger App Container\",\n \"id\": 2,\n \"parent\": \"Passenger App\",\n \"ancestors\":\"Passenger App, Passenger\"\n },\n {\n \"name\":\"Passenger Db Container\",\n \"id\": 3,\n \"parent\": \"Passenger Db\",\n \"ancestors\":\"Passenger Db, Passenger\"\n },\n {\n \"name\":\"Driver App Container\",\n \"id\": 4,\n \"parent\": \"Driver App\",\n \"ancestors\":\"Driver App, Driver\"\n },\n {\n \"name\":\"Driver Db Container\",\n \"id\": 5,\n \"parent\": \"Driver Db\",\n \"ancestors\":\"Driver Db, Driver\"\n }\n ],\n \"links\": [\n {\n \"source\": 0,\n \"target\": 1,\n \"weight\": 5\n },\n {\n \"source\": 1,\n \"target\": 0,\n \"weight\": 5\n },\n {\n \"source\": 0,\n \"target\": 2,\n \"weight\": 3\n },\n {\n \"source\": 1,\n \"target\": 3,\n \"weight\": 2\n },\n {\n \"source\": 2,\n \"target\": 3,\n \"weight\": 3\n },\n {\n \"source\": 0,\n \"target\": 4,\n \"weight\": 6\n },\n {\n \"source\": 4,\n \"target\": 5,\n \"weight\": 10\n }\n ]\n };\n children_struct = {};\n children_struct.topLevel = [\"Web\", \"Passenger\", \"Driver\"];\n children_struct[\"Passenger\"] = [\"Passenger App\", \"Passenger Db\"];\n children_struct[\"Driver\"] = [\"Driver App\", \"Driver Db\"];\n children_struct[\"Passenger App\"] = [1, 2];\n children_struct[\"Passenger Db\"] = [3];\n children_struct[\"Driver App\"] = [4];\n children_struct[\"Driver Db\"] = [5];\n\n ancestors_struct = {};\n ancestors_struct[\"Passenger App Container\"] = [\"Passenger App\", \"Passenger\"];\n ancestors_struct[\"Passenger Db Container\"] = [\"Passenger Db\", \"Passenger\"];\n ancestors_struct[\"Driver App Container\"] = [\"Driver App\", \"Driver\"];\n ancestors_struct[\"Driver Db Container\"] = [\"Driver Db\", \"Driver\"];\n ancestors_struct[\"Passenger App\"] = [\"Passenger\"];\n ancestors_struct[\"Passenger Db\"] = [\"Passenger\"];\n ancestors_struct[\"Driver App\"] = [\"Driver\"];\n ancestors_struct[\"Driver Db\"] = [\"Driver\"];\n ancestors_struct[\"Passenger\"] = [null];\n ancestors_struct[\"Driver\"] = [null];\n ancestors_struct[\"Web\"] = [null];\n module('contiv.graph');\n // module('NodeModule');\n inject( function($injector){\n // VisualizerNode = $injector.get('VisualizerNode');\n policyFactory = $injector.get('SplitJoinNodePolicy');\n });\n //creating mock for testing\n graph = {\n state:{},\n findNodeById: function(id) {\n var thisGraph = this;\n for (var i = 0; i < thisGraph.nodes.length; i++) {\n if (id === thisGraph.nodes[i].id) {\n return thisGraph.nodes[i];\n }\n } \n },\n consts:{radiusDecay: .9},\n nodes: [],\n links: [],\n spliceLinksForNode: function(){},\n dataSource: {\n children_struct: children_struct,\n ancestors_struct: ancestors_struct,\n getFlowBetweenSet: function(nameset) {\n if (_.includes(nameset, \"Web\") && \n _.includes(nameset, \"Passenger App\") && \n _.includes(nameset, \"Passenger Db\") &&\n _.includes(nameset, \"Driver\")) {\n return {nodeData: [\n {id:'Web'}, \n {id:'Passenger App'},\n {id:'Passenger Db'},\n {id:'Driver'}]\n };\n } else if (_.includes(nameset, \"Web\") && \n _.includes(nameset, \"Passenger\") && \n _.includes(nameset, \"Driver Db\") &&\n _.includes(nameset, \"Driver App\")) {\n return {nodeData: [\n {id:'Web'}, \n {id:'Passenger'},\n {id:'Driver Db'},\n {id:'Driver App'}]\n };\n } else if (_.includes(nameset, \"Web\") && \n _.includes(nameset, \"Passenger App\") && \n _.includes(nameset, \"Passenger Db\") &&\n _.includes(nameset, \"Driver Db\") &&\n _.includes(nameset, \"Driver App\")) {\n return {nodeData: [\n {id:'Web'}, \n {id:'Passenger App'},\n {id:'Passenger Db'},\n {id:'Driver Db'},\n {id:'Driver App'}]\n };\n } else if (_.includes(nameset, \"Web\") && \n _.includes(nameset, 1) && \n _.includes(nameset, 2) && \n _.includes(nameset, \"Passenger Db\") &&\n _.includes(nameset, \"Driver\")) {\n return {nodeData: [\n {id:'Web'}, \n {id:1},\n {id:2},\n {id:'Passenger Db'},\n {id:'Driver'}]\n };\n } else if (_.includes(nameset, \"Web\") &&\n _.includes(nameset, \"Passenger\") &&\n _.includes(nameset, \"Driver\")) {\n return {nodeData: [\n {id:'Web'},\n {id:'Passenger'},\n {id:'Driver'}]\n };\n }\n },\n processLinkData:function(){} },\n initNodes: function(){},\n initLinks: function(){},\n drag: {\n on: function(){}\n },\n \n circles:{\n nodes : [],\n filter:function(f){\n var nodematch = _.filter(this.nodes, f);\n return {\n classed: function(className, set) {\n _.forEach(nodematch, function(n){\n n.classed(className, set); \n });\n }\n }\n },\n classed: function(className, set) {\n _.forEach(this.nodes, function(n){\n n.classed(className, set); \n })\n }\n }\n \n };\n });\n\n function checkSplitNode(policy, graph, node, expectation) {\n policy.splitNode(node); \n for (var i = 0; i < graph.nodes.length; i++) {\n if (expectation[graph.nodes[i].id] === undefined) {\n console.log(graph.nodes[i].id, expectation);\n }\n expect(expectation[graph.nodes[i].id]).toBe(true);\n }\n var count = 0;\n for (var k in expectation) {\n count++;\n }\n expect(graph.nodes.length).toBe(count)\n }\n\n function checkMultiSplit(policy, graph, nodes, expectation) {\n policy.splitMultipleNodes(nodes); \n for (var i = 0; i < graph.nodes.length; i++) {\n if (expectation[graph.nodes[i].id] === undefined) {\n console.log(graph.nodes[i].id, expectation);\n }\n expect(expectation[graph.nodes[i].id]).toBe(true);\n }\n var count = 0;\n for (var k in expectation) {\n count++;\n }\n expect(graph.nodes.length).toBe(count)\n }\n\n function checkJoinNode(policy, graph, node, expectation) {\n policy.joinNode(node); \n for (var i = 0; i < graph.nodes.length; i++) {\n if (expectation[graph.nodes[i].id] === undefined) {\n console.log(graph.nodes[i].id, expectation);\n }\n expect(expectation[graph.nodes[i].id]).toBe(true);\n }\n var count = 0;\n for (var k in expectation) {\n count++;\n }\n expect(graph.nodes.length).toBe(count)\n }\n\n function checkMultiJoin(policy, graph, nodes, expectation) {\n policy.joinMultipleNode(nodes); \n for (var i = 0; i < graph.nodes.length; i++) {\n if (expectation[graph.nodes[i].id] === undefined) {\n console.log(graph.nodes[i].id, expectation);\n }\n expect(expectation[graph.nodes[i].id]).toBe(true);\n }\n var count = 0;\n for (var k in expectation) {\n count++;\n }\n expect(graph.nodes.length).toBe(count)\n }\n\n \n it('Checking inital values', function(){\n var policy = new policyFactory.Policy(\"test\");\n expect(policy.policyName).toBe(\"SplitJoinNodePolicy\");\n expect(policy.graph).toBe(null);\n expect(policy.initialized).toBe(false);\n });\n\n\n it('splitting and joining nodes', function() {\n var expectation, node;\n var policy = new policyFactory.Policy();\n policy.initialize(graph);\n //catching post event so updategraph isn't run\n policy.splitNodeEvent = function(){};\n policy.joinNodeEvent = function(){};\n policy.splitMultipleNodesEvent = function(){};\n policy.joinMultipleNodesEvent = function(){};\n graph.nodes = [{id:'Web', ancestors:[]}, \n {id:'Passenger', ancestors:[]},\n {id:'Driver', ancestors:[]}];\n\n // basic splitting\n node = graph.findNodeById(\"Passenger\");\n expectation = {\"Web\":true,\n \"Passenger App\": true,\n \"Passenger Db\": true,\n \"Driver\": true};\n // spyOn(graph.dataSource, ['getFlowBetweenSet'])\n // .and.returnValue({nodeData: [{id:'Web'}, \n // {id:'Passenger App'},\n // {id:'Passenger Db'},\n // {id:'Driver'}]\n // });\n \n checkSplitNode(policy, graph, node, expectation);\n\n // can't split a node that has no children\n node = graph.findNodeById(\"Web\");\n checkSplitNode(policy, graph, node, expectation);\n\n //checking second level split\n node = graph.findNodeById(\"Passenger App\");\n expectation = {\"Web\":true,\n \"1\": true,\n \"2\": true,\n \"Passenger Db\": true,\n \"Driver\": true};\n\n checkSplitNode(policy, graph, node, expectation); \n //joining passenger db -- will join the passenger\n //app container as well\n node = graph.findNodeById(\"Passenger Db\");\n expectation = {\"Web\":true,\n \"Passenger\": true,\n \"Driver\": true};\n checkJoinNode(policy, graph, node, expectation);\n\n // can't join a node that has no parent\n node = graph.findNodeById(\"Passenger\");\n checkJoinNode(policy, graph, node, expectation);\n\n\n // multiple splitting\n var n1 = graph.findNodeById(\"Passenger\");\n var n2 = graph.findNodeById(\"Driver\");\n var nodeList = [n1, n2];\n expectation = {\"Web\":true,\n \"Passenger App\": true,\n \"Passenger Db\": true,\n \"Driver Db\": true,\n \"Driver App\": true};\n checkMultiSplit(policy, graph, nodeList, expectation);\n\n // multiple joining\n n1 = graph.findNodeById(\"Passenger App\");\n n2 = graph.findNodeById(\"Driver Db\");\n nodeList = [n1, n2];\n expectation = {\"Web\":true,\n \"Passenger\": true,\n \"Driver\": true};\n checkMultiJoin(policy, graph, nodeList, expectation);\n\n })\n});\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6409043073654175, "alphanum_fraction": 0.6461619138717651, "avg_line_length": 29.645160675048828, "blob_id": "e1bbd2ea53bfda6c4a95cde9f622cdcaaa99dd2b", "content_id": "b57e55574c60f6e9f776e3d5321309c9e2daffac", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1902, "license_type": "permissive", "max_line_length": 82, "num_lines": 62, "path": "/app/networks/networklistctrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 10/14/16.\n */\n\nimport {Component, OnInit, OnDestroy, Inject} from \"@angular/core\";\nimport {NetworksModel} from \"../components/models/networksmodel\";\nimport {CRUDHelperService} from \"../components/utils/crudhelperservice\";\nimport {Observable, Subscription} from \"rxjs\";\nimport {Router, ActivatedRoute} from \"@angular/router\";\n\n\n@Component({\n selector: 'networkList',\n template: require(\"./networklist.html\")\n})\n\n\n\nexport class NetworkListComponent implements OnInit, OnDestroy{\n private networksModel:NetworksModel;\n private crudHelperService: CRUDHelperService;\n public networkListComp: any;\n private refresh: Subscription;\n\n constructor(private router: Router,\n private activatedRoute: ActivatedRoute,\n networksModel: NetworksModel,\n crudHelperService: CRUDHelperService){\n this.networksModel = networksModel;\n this.crudHelperService = crudHelperService;\n this.networkListComp = this;\n this['showLoader']=true;\n this.refresh=Observable.interval(5000).subscribe(() => {\n this.getNetworks(true);\n })\n }\n\n ngOnInit(){\n this.crudHelperService.startLoader(this);\n this.getNetworks(false);\n }\n\n getNetworks(reload: boolean){\n var networkListComp = this;\n this.networksModel.get(reload)\n .then(function successCallback(result){\n networkListComp['networks'] = result;\n networkListComp.crudHelperService.stopLoader(networkListComp);\n },\n function errorCallback(result){\n networkListComp.crudHelperService.stopLoader(networkListComp);\n })\n }\n\n create(){\n this.router.navigate(['../create'], {relativeTo: this.activatedRoute});\n }\n\n ngOnDestroy(){\n this.refresh.unsubscribe();\n }\n}\n\n\n" }, { "alpha_fraction": 0.6252452731132507, "alphanum_fraction": 0.6275343298912048, "avg_line_length": 35.41666793823242, "blob_id": "e41e9ded12c95a6229c4a3ca144351554503e08c", "content_id": "20fe4a520a7afaf06668779fbd6b56a64faae182", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3058, "license_type": "permissive", "max_line_length": 195, "num_lines": 84, "path": "/app/components/directives/settings/ldapsettingcomponent.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 12/18/16.\n */\nimport { Component } from \"@angular/core\";\nimport { ApiService } from \"../../utils/apiservice\";\nimport { ContivGlobals } from \"../../models/contivglobals\";\nimport { CRUDHelperService } from \"../../utils/crudhelperservice\";\nimport { Observable } from \"rxjs\";\nimport isEmpty = require(\"lodash/isEmpty\");\n\nexport interface LdapConfig{\n server: string;\n port: number;\n base_dn: string;\n service_account_dn: string;\n service_account_password: string;\n start_tls: boolean;\n insecure_skip_verify: boolean;\n tls_cert_issued_to: string;\n}\n\n@Component({\n selector: 'ldapsettings',\n templateUrl: './ldapsetting.html'\n})\n\nexport class LdapSettingsComponent{\n public ldapConfig: LdapConfig = {server: '', port: 0, base_dn: '', service_account_dn: '', service_account_password: '',start_tls: false, insecure_skip_verify: false, tls_cert_issued_to: ''};\n public startLoader: boolean;\n private ldapConfigExists: boolean = true;\n constructor(private apiService: ApiService,\n private crudHelperService: CRUDHelperService){\n\n }\n\n ngOnInit(){\n this.getLdapConfig();\n }\n\n getLdapConfig(){\n var ldapComponent = this;\n this.crudHelperService.startLoader(this);\n this.apiService.get(ContivGlobals.LDAP_ENDPOINT)\n .map(res => res.json())\n .subscribe((result) => {\n if(!isEmpty(result))\n ldapComponent.ldapConfig = result;\n else\n ldapComponent.ldapConfigExists = false;\n ldapComponent.crudHelperService.stopLoader(ldapComponent);\n }, (error) => {\n ldapComponent.ldapConfigExists = false;\n ldapComponent.crudHelperService.stopLoader(ldapComponent);\n });\n }\n\n updateLdapConfig(formValid: boolean){\n var ldapComponent = this;\n if(formValid){\n if(ldapComponent.ldapConfig.insecure_skip_verify)\n ldapComponent.ldapConfig.tls_cert_issued_to = '';\n if(!ldapComponent.ldapConfig.start_tls)\n ldapComponent.ldapConfig.insecure_skip_verify = false;\n this.crudHelperService.startLoader(this);\n this.update().subscribe((result) => {\n ldapComponent.ldapConfigExists = true;\n ldapComponent.crudHelperService.stopLoader(ldapComponent);\n ldapComponent.crudHelperService.showNotification(\"LDAP: Configuration Updated\", ldapComponent.ldapConfig.server);\n }, (error) => {\n ldapComponent.crudHelperService.stopLoader(ldapComponent);\n ldapComponent.crudHelperService.showServerError(\"LDAP: Update Failed\", error);\n });\n }\n }\n\n update(): Observable<any>{\n if(this.ldapConfigExists){\n return this.apiService.patch(ContivGlobals.LDAP_ENDPOINT, this.ldapConfig);\n }\n else{\n return this.apiService.put(ContivGlobals.LDAP_ENDPOINT, this.ldapConfig);\n }\n }\n}" }, { "alpha_fraction": 0.5692076086997986, "alphanum_fraction": 0.6695085167884827, "avg_line_length": 45.348838806152344, "blob_id": "f935866f120f2c876e7c3b40ba8f00b698c58306", "content_id": "d77773496ebcaeefc2d7ed6c0df28f86cd1fc315", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1994, "license_type": "permissive", "max_line_length": 185, "num_lines": 43, "path": "/backend/serviceInit.sh", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "#service script\nunset opt\nwhile getopts c opt; do\n\tcase $opt in\n\t\tc)\n\t docker exec -it $(docker run -itd --net=client-net contiv/alpine sh) sh -c \"nc -znvw 1 100.1.1.3 8080\"\n\t docker exec -it $(docker run -itd --net=client-net contiv/alpine sh) sh -c \"nc -znvw 1 100.1.1.3 8080\"\n\t docker exec -it $(docker run -itd --net=client-net contiv/alpine sh) sh -c \"nc -znvw 1 100.1.1.3 8080\"\n\t ;;\n esac\ndone\n\nif [ $# -eq 0 ];\nthen\n \tnetctl net create contiv-srv-net -s 100.1.1.0/24\n\n\t#app-svc service\n\tnetctl service create app-svc --ip 100.1.1.3 --network contiv-srv-net --tenant default --selector=tier=web --selector=release=stable --selector=environment=prod --port 8080:80:TCP\n\tnetctl net create contiv-net -s 10.1.1.0/24 -g 10.1.1.254\n\tfor i in `seq 1 14`;\n do\n \tdocker exec -it $(docker run -itd --net=contiv-net --label=tier=web --label=release=stable --label=environment=prod --label=version=1.0 contiv/alpine sh) sh -c \"nc -l -p 80 &\"\n done \n\n\n #app-db service\n\tnetctl service create app-db --ip 100.1.1.4 --network contiv-srv-net --tenant default --selector=tier=db --selector=release=stable --selector=environment=prod --port 8080:80:TCP\n for i in `seq 1 3`;\n \tdo\n\t\t\tdocker exec -it $(docker run -itd --net=contiv-net --label=tier=db --label=release=stable --label=environment=prod --label=version=1.0 contiv/alpine sh) sh -c \"nc -l -p 80 &\"\n\t\tdone\n\n\tnetctl net create client-net -s 11.1.1.0/24 -g 11.1.1.254\n\n\t#endpoint to app-svc\n\tdocker exec -it $(docker run -itd --net=client-net contiv/alpine sh) sh -c \"nc -znvw 1 100.1.1.3 8080\"\n\tdocker exec -it $(docker run -itd --net=client-net contiv/alpine sh) sh -c \"nc -znvw 1 100.1.1.3 8080\"\n\tdocker exec -it $(docker run -itd --net=client-net contiv/alpine sh) sh -c \"nc -znvw 1 100.1.1.3 8080\"\n\n\t#endpoint to app-db\n\tdocker exec -it $(docker run -itd --net=client-net contiv/alpine sh) sh -c \"nc -znvw 1 100.1.1.4 8080\"\nfi\nexit\n\n" }, { "alpha_fraction": 0.5997183322906494, "alphanum_fraction": 0.6014084219932556, "avg_line_length": 31.272727966308594, "blob_id": "96b94f2cceb90fb7c55f1767e7f55f911f503d7b", "content_id": "164bda0e82a3fe187801e20eacd62d03788cd3b9", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3550, "license_type": "permissive", "max_line_length": 108, "num_lines": 110, "path": "/app/settings/authorization/authorizationcreate.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 12/13/16.\n */\nimport { Component, Inject, OnInit, NgZone } from \"@angular/core\";\nimport { ActivatedRoute, Router } from \"@angular/router\";\nimport { CRUDHelperService } from \"../../components/utils/crudhelperservice\";\nimport { UsersModel } from \"../../components/models/usersmodel\";\nimport { OrganizationsModel } from \"../../components/models/organizationsmodel\";\nimport { AuthorizationModel } from \"../../components/models/authorizationmodel\";\n\n\nexport interface Authorization{\n AuthzUUID?: string\n PrincipalName: string;\n Local: boolean;\n Role: string;\n TenantName: string;\n}\n\n@Component({\n selector: 'authorizationcreate',\n templateUrl: './authorizationcreate.html'\n})\n\nexport class AuthorizationCreateComponent implements OnInit{\n authorization: Authorization = { PrincipalName: '', Local: false , Role: '', TenantName: '' };\n tenants: any = [];\n users: any = [];\n usertype: string = ''\n showLoader: boolean = false;\n\n constructor(private activatedRoute: ActivatedRoute,\n private router: Router,\n private crudHelperService: CRUDHelperService,\n private authorizationModel: AuthorizationModel,\n private organizationsModel: OrganizationsModel,\n private usersModel: UsersModel){\n this.usertype = 'local'\n\n }\n\n ngOnInit(){\n this.getOrganization();\n }\n\n getOrganization(){\n var authCreateComp = this;\n this.crudHelperService.startLoader(this);\n this.organizationsModel.get(false)\n .then((result) => {\n authCreateComp.tenants = result;\n authCreateComp.getUsers();\n }, (error) => {\n authCreateComp.crudHelperService.stopLoader(authCreateComp);\n })\n }\n\n getUsers(){\n var authCreateComp = this;\n this.usersModel.get(false)\n .then((result) => {\n authCreateComp.users = result;\n authCreateComp.crudHelperService.stopLoader(authCreateComp)\n }, (error) => {\n authCreateComp.crudHelperService.stopLoader(authCreateComp)\n });\n }\n\n\n\n returnToAuthList(){\n this.router.navigate(['../list'], { relativeTo: this.activatedRoute });\n }\n\n cancelCreating(){\n this.returnToAuthList();\n }\n\n changeAuthType() {\n if (this.usertype==='local') {\n this.authorization.Local = true\n } else {\n this.authorization.Local = false\n }\n }\n\n checkRole(){\n if(this.authorization.Role === 'admin')\n this.authorization.TenantName = '';\n }\n\n createAuthorization(formvalid: boolean){\n var authCreateComp = this;\n if(formvalid){\n this.crudHelperService.startLoader(this);\n this.changeAuthType();\n this.authorizationModel.create(this.authorization)\n .then((result) => {\n authCreateComp.crudHelperService.stopLoader(authCreateComp);\n authCreateComp.crudHelperService.showNotification(\"Authorization: Created\",\n result['PrincipalName'] + '::' + result['TenantName'] + '::' + result['Role']);\n authCreateComp.returnToAuthList();\n }, (error) => {\n authCreateComp.crudHelperService.stopLoader(authCreateComp);\n authCreateComp.crudHelperService.showServerError(\"Authorization: Create failed\", error);\n })\n }\n }\n\n}\n" }, { "alpha_fraction": 0.5425971150398254, "alphanum_fraction": 0.5593007206916809, "avg_line_length": 46.85960006713867, "blob_id": "a95203c9aa490e4df6f00c0fefd70735c3fcd817", "content_id": "15f3f395743dec03de639cbb0c455c5ab9643ba0", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 16703, "license_type": "permissive", "max_line_length": 153, "num_lines": 349, "path": "/app/components/directives/directives_test.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 5/25/16.\n */\ndescribe('contiv.directives', function() {\n var envVariables = [\n {name: 'fooEnv1', value: 'barEnv1'},\n {name: 'fooEnv2', value: 'barEnv2'},\n {name: 'fooEnv3', value: 'barEnv3'}\n ];\n\n /* Accordion directive inputs */\n var accordionItems = [\n {name: \"name1\", value: \"value1\"},\n {name: \"name2\", value: \"value2\"},\n {name: \"name3\", value: \"value3\"},\n {name: \"labels\", value: [\"label1=val1\", \"label2=val2\", \"label3=val3\"]}\n ];\n\n /* Table directive inputs */\n var tableItems = [\n {name: \"name11\", ipAddress: \"20.1.2.4\", homingHost: \"cluster-1\"},\n {name: \"name12\", ipAddress: \"20.1.2.3\", homingHost: \"cluster-1\"},\n {name: \"name13\", ipAddress: \"20.1.2.2\", homingHost: \"cluster-1\"},\n {name: \"name14\", ipAddress: \"20.1.2.1\", homingHost: \"cluster-1\"},\n {name: \"name17\", ipAddress: \"20.1.2.0\", homingHost: \"cluster-2\"},\n {name: \"name16\", ipAddress: \"20.1.1.9\", homingHost: \"cluster-2\"},\n {name: \"name15\", ipAddress: \"20.1.1.8\", homingHost: \"cluster-2\"},\n {name: \"name25\", ipAddress: \"20.1.1.7\", homingHost: \"cluster-3\"},\n {name: \"name24\", ipAddress: \"20.1.1.6\", homingHost: \"cluster-3\"},\n {name: \"name26\", ipAddress: \"20.1.1.5\", homingHost: \"cluster-6\"},\n {name: \"name20\", ipAddress: \"20.1.1.4\", homingHost: \"cluster-6\"},\n {name: \"name23\", ipAddress: \"20.1.1.3\", homingHost: \"cluster-6\"},\n {name: \"name22\", ipAddress: \"20.1.1.2\", homingHost: \"cluster-6\"},\n {name: \"name21\", ipAddress: \"20.1.1.1\", homingHost: \"cluster-1\"}\n ];\n\n // End of table directive inputs\n\n var $compile, $rootScope;\n\n //Load the utils module\n beforeEach(module('contiv.utils'));\n // Load the module which contains the directive\n beforeEach(module('contiv.directives'));\n //Module that contains html template of the directive\n beforeEach(module('contiv.test.directives'));\n\n // Store references to $rootScope and $compile\n // so they are available to all tests in this describe block\n beforeEach(inject(function(_$compile_, _$rootScope_){\n // The injector unwraps the underscores (_) from around the parameter names when matching\n $compile = _$compile_;\n $rootScope = _$rootScope_;\n\n }));\n\n describe('namevalue directive', function () {\n var isolateScope, element;\n beforeEach(inject(function() {\n // Compile a piece of HTML containing the directive\n element = $compile(\"<ctv-namevalue items='envVariables'></ctv-namevalue>\")($rootScope);\n $rootScope.envVariables = envVariables;\n // fire all the watches, so the scope expression will be evaluated\n $rootScope.$digest();\n isolateScope = element.isolateScope();\n }));\n it('Replaces the element with the appropriate content', function () {\n\n // Check that the compiled element contains the templated content\n expect(element.html()).toContain(\"<td class=\\\"ng-binding\\\">fooEnv1</td>\");\n expect(element.html()).toContain(\"<td class=\\\"ng-binding\\\">barEnv1</td>\");\n expect(element.html()).toContain(\"<td class=\\\"ng-binding\\\">fooEnv2</td>\");\n expect(element.html()).toContain(\"<td class=\\\"ng-binding\\\">barEnv2</td>\");\n expect(element.html()).toContain(\"<td class=\\\"ng-binding\\\">fooEnv3</td>\");\n expect(element.html()).toContain(\"<td class=\\\"ng-binding\\\">barEnv3</td>\");\n });\n it('add() should cache variable', function () {\n isolateScope.newItem = {name: 'fooEnv4', value: 'barEnv4'};\n isolateScope.add();\n expect(isolateScope.items.length).toEqual(4);\n expect(isolateScope.items[3].name).toEqual('fooEnv4');\n expect(isolateScope.items[3].value).toEqual('barEnv4');\n //newItem should be reset\n expect(isolateScope.newItem.name).toEqual('');\n expect(isolateScope.newItem.value).toEqual('');\n });\n it('add() called twice with same variable name should only have the latest addition', function () {\n var isolateScope = element.isolateScope();\n isolateScope.newItem = {name: 'fooEnv4', value: 'barEnv4'};\n isolateScope.add();\n isolateScope.newItem = {name: 'fooEnv4', value: 'barEnv5'};\n isolateScope.add();\n expect(isolateScope.items.length).toEqual(4);\n expect(isolateScope.items[3].name).toEqual('fooEnv4');\n expect(isolateScope.items[3].value).toEqual('barEnv5');\n });\n it('remove() should remove the variable from cache', function () {\n var isolateScope = element.isolateScope();\n isolateScope.newItem = {name: 'fooEnv4', value: 'barEnv4'};\n isolateScope.add();\n isolateScope.newItem = {name: 'fooEnv5', value: 'barEnv5'};\n isolateScope.add();\n expect(isolateScope.items.length).toEqual(5);\n isolateScope.remove({name: 'fooEnv4', value: 'barEnv4'});\n expect(isolateScope.items.length).toEqual(4);\n expect(isolateScope.items[3].name).toEqual('fooEnv5');\n expect(isolateScope.items[3].value).toEqual('barEnv5');\n isolateScope.remove({name: 'fooEnv1', value: 'barEnv1'});\n expect(isolateScope.items.length).toEqual(3);\n isolateScope.remove({name: 'fooEnv2', value: 'barEnv2'});\n expect(isolateScope.items.length).toEqual(2);\n isolateScope.remove({name: 'fooEnv3', value: 'barEnv3'});\n expect(isolateScope.items.length).toEqual(1);\n isolateScope.remove({name: 'fooEnv5', value: 'barEnv5'});\n expect(isolateScope.items.length).toEqual(0);\n isolateScope.remove({name: 'fooEnv5', value: 'barEnv5'});\n expect(isolateScope.items.length).toEqual(0);\n });\n });\n\n describe('accordion directive', function(){\n var element;\n beforeEach(inject(function(){\n // Compile a piece of HTML containing the directive\n $rootScope.accordionItems = accordionItems;\n $rootScope.accordion = function(){};\n // fire all the watches, so the scope expression will be evaluated\n element = $compile(\"<ctv-accordion items = 'accordionItems'><span>Accordion Title</span></ctv-accordion>\")($rootScope);\n $rootScope.$digest();\n isolateScope = element.isolateScope();\n }));\n\n it('Element with accordion class must be present', function(){\n expect(element.find(\"div:first-child\").hasClass(\"accordion\")).toBeTruthy();\n });\n\n it('Title must be present for an accordion', function(){\n expect(element.find(\"div.title span\").text()).toEqual(\"Accordion Title\");\n });\n\n it('Number of table rows should be equal to the number of name value pairs in accordiondata', function(){\n expect(element.find(\"tr\").length).toBe(accordionItems.length);\n });\n\n it('Accordion contents must be valid', function(){\n var i = 0;\n var dataRows = element.find(\"tr\");\n dataRows.each(function (index, elem){\n var tableData = angular.element(elem).children();\n expect(tableData[0].textContent.replace(/\\s/g, '')).toEqual(accordionItems[i].name);\n if(accordionItems[i].name == \"labels\"){\n var labelNodes = tableData[1].childNodes;\n for(var j in labelNodes) {\n if(labelNodes[j].nodeType == 1){\n expect(accordionItems[i].value).toContain(labelNodes[j].textContent.replace(/\\s/g, ''));\n }\n }\n }\n else{\n expect(tableData[1].textContent.replace(/\\s/g, '')).toEqual(accordionItems[i].value);\n }\n i++;\n });\n })\n });\n\n describe(\"table directive\",function(){\n var element,tableCtrl,scope,$filter;\n beforeEach(inject(function(_$filter_){\n $filter = _$filter_;\n scope = $rootScope.$new();\n scope.tableItems = tableItems;\n scope.size = 12;\n scope.name = \"name\";\n scope.ipAddress = \"ipAddress\";\n scope.homingHost = \"homingHost\";\n var elem = \"<ctv-table defaultsortcolumn='name' items='tableItems' filtereditems='filtItems' size='size'>\" +\n \" <ctv-thead>\" +\n \" <ctv-tr>\" +\n \" <ctv-th sortfield='name'>name</ctv-th>\" +\n \" <ctv-th sortfield='ipAddress'>ipAddress</ctv-th>\" +\n \" <ctv-th sortfield='homingHost'>homingHost</ctv-th>\" +\n \" <ctv-th><ctv-tsearch placeholder='Search' size='30'></ctv-tsearch></ctv-th>\" +\n \" </ctv-tr>\" +\n \" </ctv-thead>\" +\n \" <ctv-tbody>\" +\n \" <ctv-tr ng-repeat='item in filtItems'>\" +\n \" <ctv-td>{{item.name}}</ctv-td>\" +\n \" <ctv-td>{{item.ipAddress}}</ctv-td>\" +\n \" <ctv-td>{{item.homingHost}}</ctv-td>\" +\n \" </ctv-tr>\" +\n \" </ctv-tbody>\" +\n \" <ctv-tfoot>\" +\n \" <ctv-tr>\" +\n \" <ctv-th>\" +\n \" <ctv-tpagination></ctv-tpagination>\" +\n \" </ctv-th>\" +\n \" </ctv-tr>\" +\n \" </ctv-tfoot>\" +\n \"</ctv-table>\";\n element = $compile(elem)(scope);\n scope.$digest();\n tableCtrl = element.controller(\"ctvTable\");\n }));\n\n //Function for verifying contents of generated table data\n function verifyTableData(pageNo,field,direction){\n var sortedTabItem = sortTestTabData(field,direction);\n var domTableData = element.find(\"tbody tr\");\n var i=(pageNo-1) * 12;\n domTableData.each(function(index,elem){\n var textContent = elem.innerText;\n expect(textContent).toContain(sortedTabItem[i].name);\n expect(textContent).toContain(sortedTabItem[i].ipAddress);\n expect(textContent).toContain(sortedTabItem[i].homingHost);\n i++;\n });\n }\n\n //function for sorting input table data array based on key\n function sortTestTabData(field, direction){\n return $filter('orderBy')(tableItems, field, direction);\n }\n\n it(\"The number of items displayed should be equal to the size attribute\",function() {\n expect(scope.filtItems.length).toEqual(scope.size);\n });\n\n it(\"Showchunk function should display items according to the input page No\", function(){\n tableCtrl.showChunk(1);\n scope.$apply();\n expect(scope.filtItems.length).toEqual(tableItems.length-scope.size);\n });\n\n it(\"Showchunk function should select only items matching the input text\",function(){\n tableCtrl.showChunk(0, \"cluster-1\");\n scope.$apply();\n var testFilterTab = tableItems.filter(function(item){\n return (item.homingHost == \"cluster-1\");\n });\n expect(scope.filtItems.length).toEqual(testFilterTab.length);\n for(var i in scope.filtItems.length){\n expect(scope.filtItems[i].name).toEqual(testFilterTab[i].name);\n }\n });\n\n it(\"By default the items in the table must be sorted based on defaultsortcolumn\",function() {\n var sortedTabItem = sortTestTabData(scope.name,false);\n for (var i in scope.filtItems) {\n expect(scope.filtItems[i].name).toEqual(sortedTabItem[i].name);\n }\n });\n\n it(\"sort funciton should sort all items in the table based on the input sort field\", function(){\n tableCtrl.sort(\"ipAddress\");\n scope.$apply();\n var sortedTabItem = sortTestTabData(\"ipAddress\",false);\n for(var i in scope.filtItems){\n expect(scope.filtItems[i].name).toEqual(sortedTabItem[i].name);\n }\n //All pages must be sorted based on the input sortfield\n tableCtrl.showNextChunk();\n scope.$apply();\n for(var i in scope.filtItems){\n expect(scope.filtItems[i][\"ipAddress\"]).toEqual(sortedTabItem[sortedTabItem.length - scope.filtItems.length + parseInt(i)][\"ipAddress\"]);\n }\n });\n\n it(\"showNextChunk function should load items present in the second chunk\", function(){\n tableCtrl.showNextChunk();\n scope.$apply();\n expect(scope.filtItems.length).toEqual(tableItems.length-scope.size);\n });\n\n it(\"showPrevChunk should load items present in the previous chunk\", function(){\n tableCtrl.showChunk(1);\n scope.$apply();\n tableCtrl.showPrevChunk();\n scope.$apply();\n var sortedTabItem = sortTestTabData(scope.name,false);\n for (var i in scope.filtItems) {\n expect(scope.filtItems[i].name).toEqual(sortedTabItem[i].name);\n }\n });\n\n it(\"The directive must create a table element and update the dom with the input items\",function(){\n expect(element.find(\"table\").hasClass(\"ui very basic unstackable table\")).toBeTruthy();\n verifyTableData(1,scope.name,false);\n });\n\n\n it(\"verify whether sorting icon is displayed pointing in the right direction\", function(){\n var iconTag = element.find(\"th[sortfield=\"+tableCtrl.sortObj.field+\"]\").children()[0];\n expect(iconTag.tagName).toEqual(\"I\");\n expect(iconTag.className).toContain(\"angle down icon\");\n var firstColumn = element.find(\"th[sortfield]\")[0];\n firstColumn.click();\n scope.$apply();\n expect(iconTag.className).toContain(\"angle icon up\");\n });\n\n it(\"Clicking on table header should call the sort function passing the sortfield \",function(){\n spyOn(tableCtrl,\"sort\").and.callThrough();\n var secondColumn = element.find(\"th[sortfield]\")[1];\n secondColumn.click();\n expect(tableCtrl.sort).toHaveBeenCalledWith(scope.ipAddress);\n });\n\n it(\"Clicking on previous and next in the pagination footer should update the dom with the corresponding items\",\n function(){\n var pageNext = element.find(\"tfoot a.icon\")[1];\n var pagePrev = element.find(\"tfoot a.icon\")[0];\n pageNext.click();\n scope.$apply();\n verifyTableData(2,scope.name,false);\n pagePrev.click();\n scope.$apply();\n verifyTableData(1,scope.name,false);\n });\n\n it(\"Number of page links displayed should be equal to chunks created\", function(){\n expect(element.find(\"tfoot a\").not(\".icon\").length).toEqual(tableCtrl.chunks.length);\n });\n\n it(\"Clicking on the page numbers in the pagination menu should call the showChunk with corresponding page no\",\n function(){\n spyOn(tableCtrl, \"showChunk\").and.callThrough();;\n var secondPage = element.find(\"tfoot a\").not(\".icon\")[1];\n secondPage.click();\n var secondPageNo = secondPage.innerText.trim();\n expect(tableCtrl.showChunk).toHaveBeenCalledWith(secondPageNo - 1,undefined);\n });\n\n it(\"Entering text in search box should call showChunk passing entered text as parameter\",function(){\n spyOn(tableCtrl, \"showChunk\").and.callThrough();\n var searchField = element.find(\"input[type='text']\");\n searchField.val(\"cluster-1\").trigger('input');\n expect(tableCtrl.showChunk).toHaveBeenCalledWith(tableCtrl.pageNo,\"cluster-1\");\n });\n\n it(\"sorting direction must change on click\", function(){\n var firstColumn = element.find(\"th[sortfield]\")[0];\n firstColumn.click();\n scope.$apply();\n verifyTableData(1,scope.name,true);\n });\n\n });\n});\n" }, { "alpha_fraction": 0.7182080745697021, "alphanum_fraction": 0.7268785834312439, "avg_line_length": 30.454545974731445, "blob_id": "295222a909e1545a52de960873a46b4d9b371610", "content_id": "8f17e1bce82c89845eb4fd186356fe6af9a88638", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1384, "license_type": "permissive", "max_line_length": 78, "num_lines": 44, "path": "/app/firstrunwizard/firstrunwizard.module.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 10/29/16.\n */\n\n/**\n * Created by cshampur on 10/18/16.\n */\nimport { NgModule } from '@angular/core';\nimport { FormsModule } from \"@angular/forms\";\nimport { CommonModule } from \"@angular/common\";\nimport { DirectivesModule } from \"../components/directives/directives.module\";\nimport {RouterModule} from \"@angular/router\";\nimport {FirstRunWizardService} from \"./firstrunwizardservice\";\nimport {FirstrunWizardComponent} from \"./firstrunwizardctrl\";\nimport {FirstrunNetworkDefaultComponent} from \"./firstrunnetworkdefaults\";\nimport {FirstrunACISettingsComponent} from \"./firstrunacisettings\";\nimport {FirstrunConfirmComponent} from \"./firstrunwizardconfirmpage\";\nimport {FirstrunNetworkCreateComponent} from \"./firstrunnetworkcreate\";\n\n\n@NgModule({\n imports: [\n FormsModule,\n CommonModule,\n DirectivesModule,\n RouterModule\n ],\n declarations: [\n FirstrunWizardComponent,\n FirstrunNetworkDefaultComponent,\n FirstrunACISettingsComponent,\n FirstrunConfirmComponent,\n FirstrunNetworkCreateComponent\n ],\n exports: [\n FirstrunWizardComponent,\n FirstrunNetworkDefaultComponent,\n FirstrunACISettingsComponent,\n FirstrunConfirmComponent,\n FirstrunNetworkCreateComponent\n ],\n providers: [FirstRunWizardService]\n})\nexport class FirstrunWizardModule {}\n" }, { "alpha_fraction": 0.6589887738227844, "alphanum_fraction": 0.6623595356941223, "avg_line_length": 24.056337356567383, "blob_id": "b01a6c807a78b86b6ca336edf6e5015b3abe7b6c", "content_id": "61159dc6ecc791deaa274dbd7cbf466b277c3010", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1780, "license_type": "permissive", "max_line_length": 93, "num_lines": 71, "path": "/app/service_lbs/servicelbdetailsctrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 10/14/16.\n */\n\nimport {Component, OnInit, OnDestroy, Inject, ViewChild, AfterViewInit} from \"@angular/core\";\nimport {CRUDHelperService} from \"../components/utils/crudhelperservice\";\nimport {ServicelbsModel} from \"../components/models/servicelbsmodel\";\nimport {ServicelbInfoComponent} from \"./servicelbinfoctrl\";\nimport {ServicelbStatComponent} from \"./servicelbstatsctrl\";\nimport {Router, ActivatedRoute} from \"@angular/router\";\nvar _ = require('lodash');\n\n\n@Component({\n selector: 'servicelbDetails',\n templateUrl: \"./servicelbdetails.html\"\n})\n\nexport class ServicelbDetailsComponent implements OnInit{\n public infoselected: boolean\n public statskey: string;\n public mode: string;\n public servicelbDetailsCtrl: any;\n public serviceName:any;\n\n @ViewChild(ServicelbInfoComponent)\n public servielbInfo: ServicelbInfoComponent;\n\n @ViewChild(ServicelbStatComponent)\n public servielbStat: ServicelbInfoComponent;\n\n\n constructor(private router: Router,\n private activatedRoute: ActivatedRoute\n ){\n this.infoselected = true;\n this.statskey='';\n this.mode = 'details';\n this.serviceName='';\n this.servicelbDetailsCtrl = this;\n }\n\n ngOnInit(){\n this.statskey = this.activatedRoute.snapshot.params['key'];\n\n }\n\n returnToServicelbs() {\n this.router.navigate(['../../list'], {relativeTo: this.activatedRoute});\n }\n \n cancelDetails() {\n this.returnToServicelbs()\n }\n\n cancelEditing() {\n this.returnToServicelbs()\n }\n\n loadDetails() {\n this.mode = \"details\";\n }\n\n loadEdit() {\n this.mode = \"edit\";\n }\n\n deleteServicelb(){\n this.servielbInfo.deleteServicelb();\n }\n}\n\n" }, { "alpha_fraction": 0.6527777910232544, "alphanum_fraction": 0.6635802388191223, "avg_line_length": 24.920000076293945, "blob_id": "c1062864dc1ac350d93b6f15760402d549f718d3", "content_id": "b97c8ba1926e87672a74542282ccbfcb5cfc7148", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 648, "license_type": "permissive", "max_line_length": 69, "num_lines": 25, "path": "/app/components/models/appprofilesmodel.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 11/11/16.\n */\nimport { Injectable } from '@angular/core';\nimport { Http } from '@angular/http';\nimport { Collection } from \"./collection\";\nimport { ContivGlobals } from \"./contivglobals\";\nimport { ApiService } from \"../utils/apiservice\";\n\n\n@Injectable()\nexport class AppProfilesModel extends Collection {\n constructor(http: Http, apiService: ApiService) {\n super(http, ContivGlobals.APP_PROFILES_ENDPOINT, apiService);\n }\n\n /**\n * Generate key for application profile\n * @param profile\n */\n generateKey(profile) {\n return profile.tenantName + ':' + profile.appProfileName;\n }\n\n}\n" }, { "alpha_fraction": 0.635477602481842, "alphanum_fraction": 0.6432748436927795, "avg_line_length": 18.769229888916016, "blob_id": "79785b088407148117a838b4a5f35a18fbc7766e", "content_id": "6d9b97ff2146820994e5d0d41646a206816214fc", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 513, "license_type": "permissive", "max_line_length": 67, "num_lines": 26, "path": "/app/components/directives/accordiondirective.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 7/1/16.\n */\nimport {Component, Input, ElementRef, OnInit} from \"@angular/core\";\ndeclare var jQuery:any;\n\ninterface Items {\n name: string;\n value: string;\n format: string;\n type: string;\n}\n\n@Component({\n selector: 'ctv-accordion',\n templateUrl: './accordion.html'\n})\nexport class CtvAccordionComponent implements OnInit{\n @Input('items') items:Items[];\n\n constructor(elem: ElementRef){\n }\n ngOnInit(){\n jQuery(\".ui.accordion\").accordion();\n }\n}" }, { "alpha_fraction": 0.6109358668327332, "alphanum_fraction": 0.6161934733390808, "avg_line_length": 26.200000762939453, "blob_id": "226edf1785e952d26049200d7759806388e2e1d6", "content_id": "8dca8e1ea1216c680a39b84ea4b77c9d62865d4c", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 951, "license_type": "permissive", "max_line_length": 68, "num_lines": 35, "path": "/app/components/models/netprofilesmodel.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by hardik gandhi on 6/15/16.\n */\nimport { Injectable } from '@angular/core';\nimport { Http } from '@angular/http';\nimport { Collection } from \"./collection\";\nimport { ContivGlobals } from \"./contivglobals\";\nimport {ApiService} from \"../utils/apiservice\";\nimport {isUndefined} from \"util\";\n\n@Injectable()\nexport class NetprofilesModel extends Collection {\n constructor(http: Http, apiService: ApiService) {\n super(http, ContivGlobals.NETPROFILES_ENDPOINT, apiService);\n }\n\n /**\n * Generate policy key to save policy on server\n * @param policy\n * @returns {string}\n */\n generateKey(policy) {\n return policy.tenantName + ':' + policy.profileName;\n }\n\n get(reload: boolean):Promise<any>{\n return super.get(reload).then((result) => {\n var items = result.filter((item) => {\n return !isUndefined(item['profileName']);\n });\n return items;\n });\n }\n\n}" }, { "alpha_fraction": 0.48804205656051636, "alphanum_fraction": 0.49724048376083374, "avg_line_length": 36.22549057006836, "blob_id": "98e3f773e6d53ef05316edcba91985ae2a7c0f20", "content_id": "637ca8c0f0984b2f85b4f8a85b226ec7bfafcfd0", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3805, "license_type": "permissive", "max_line_length": 75, "num_lines": 102, "path": "/app/components/graphobjects/policy/nodeselectionpolicy_test.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "'use strict';\n\ndescribe('NodeSelectionPolicy', function(){\n var policyFactory;\n var graph;\n beforeEach(function(){\n module('contiv.graph');\n inject( function($injector){\n policyFactory = $injector.get('NodeSelectionPolicy');\n });\n //creating mock for testing\n graph = {\n state:{}, \n consts:{},\n nodes: [],\n drag: {\n on: function(){}\n },\n \n circles:{\n nodes : [],\n filter:function(f){\n var nodematch = _.filter(this.nodes, f);\n return {\n classed: function(className, set) {\n _.forEach(nodematch, function(n){\n n.classed(className, set); \n });\n }\n }\n },\n classed: function(className, set) {\n _.forEach(this.nodes, function(n){\n n.classed(className, set); \n })\n }\n }\n };\n });\n\n it('Checking inital values', function(){\n var policy = new policyFactory.Policy(\"test\");\n expect(policy.policyName).toBe(\"NodeSelectionPolicy\");\n expect(policy.graph).toBe(null);\n expect(policy.initialized).toBe(false);\n });\n\n it('add and removing nodes', function() {\n var policy = new policyFactory.Policy();\n policy.initialize(graph);\n var selectedClass = graph.consts.NodeSelectionPolicy.selectedClass;\n\n //creates a mock that can be used both as a\n //d3node and as nodeData\n function dummyNode(id) {\n return {\n id: id,\n className: null,\n classed: function(className, set) {\n if (set) {\n this.className = className;\n } else {\n this.className = null;\n }\n }\n }\n }\n var state = graph.state.NodeSelectionPolicy;\n\n var node1 = dummyNode(1);\n var node2 = dummyNode(2);\n var node3 = dummyNode(3);\n\n graph.circles.nodes = [node1, node2, node3];\n\n //testing adding and removing a node\n policy.addSelectNode(node1, node1);//node should be added\n expect(state.selectedNodes.length).toBe(1);\n expect(node1.className).toBe(selectedClass);\n policy.addSelectNode(node2, node2);//node should be added\n expect(state.selectedNodes.length).toBe(2);\n expect(node2.className).toBe(selectedClass);\n expect(_.includes(state.selectedNodes, node1)).toBe(true);\n policy.removeSelectFromNode(node1, node1);//node should be removed\n expect(node1.className).toBe(null);\n expect(node2.className).toBe(selectedClass);\n expect(_.includes(state.selectedNodes, node2)).toBe(true);\n policy.removeSelectFromNode(node2, node2);//node should be removed\n expect(node2.className).toBe(null);\n expect(_.isEmpty(state.selectedNodes)).toBe(true);\n\n //testing removing all selected nodes\n policy.addSelectNode(node1, node1);//node should be added\n policy.addSelectNode(node2, node2);//node should be added\n policy.addSelectNode(node3, node3);//node should be added\n expect(state.selectedNodes.length).toBe(3);\n policy.removeAllSelectedNodes();\n expect(state.selectedNodes.length).toBe(0);\n\n\n })\n});\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.702301025390625, "alphanum_fraction": 0.7066155076026917, "avg_line_length": 52.512821197509766, "blob_id": "3a0368be26a0c4ff8f876ea359c05c46ca04abb7", "content_id": "b1a4f49a9c856e53f6cd75ab166f0fe188f2b97d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2086, "license_type": "permissive", "max_line_length": 117, "num_lines": 39, "path": "/e2e-tests/volumes/volumespageobject.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 8/17/16.\n */\n\n\nvar volList = function(){\n this.createButton = element(by.css(\"button.button[ui-sref='contiv.menu.volumes.create']\"));\n this.volumeName = element(by.cssContainingText(\"a\",testConfig.volumes.name));\n}\n\nvar volCreate = function(){\n this.volumename = element(by.id(\"newVolumeName\"));\n this.volumepolicy = element(by.id(\"newVolumePolicy\")).element(by.css(\"[label='\"+testConfig.volumes.policy+\"']\"));\n this.volumecreate = element(by.cssContainingText(\"button\", \"Create\"));\n this.volumecancel = element(by.cssContainingText(\"button\", \"Cancel\"));\n this.collapsible = element.all(by.css(\"div[ng-click='collapsed = !collapsed'] h4\"));\n this.serverMessage = element(by.cssContainingText(\"ctv-error div div\", \"Error creating volume\"));\n}\n\nvar volDetails = function(){\n this.detailsTable = element.all(by.css(\"table tbody tr\"));\n this.policyDetails = element(by.css(\"ctv-collapsible[title='Policy Settings']\")).all(by.css(\"table tbody tr\"));\n this.snapshotDetails = element(by.css(\"ctv-collapsible[title='Snapshots']\")).all(by.css(\"table tbody tr\"));\n this.snapshotButton = element(by.cssContainingText(\"button\", \"Snapshot\"));\n this.collapsible = element.all(by.css(\"div[ng-click='collapsed = !collapsed'] h4\"));\n this.snapshotSuccessMes = element(by.css(\"div[class='ui positive message']\"));\n this.snapshotIcon = element(by.css(\"ctv-collapsible[title='Snapshots']\")).all(by.css(\"td a\")).get(0);\n}\n\nvar volSnapshotCopy = function(){\n this.snapshot = element.all(by.css(\"table tbody td\")).get(1);\n this.newVolume = element.all(by.id(\"newvolume\"));\n this.copyButton = element(by.cssContainingText(\"button\", \"Copy\"));\n this.cancelButton = element(by.cssContainingText(\"button\", \"Cancel\"));\n this.errorMessage = element(by.cssContainingText(\"li\", \"Please enter volume name\"));\n this.serverMessage = element(by.cssContainingText(\"ctv-error div div\", \"Error copying volume\"));\n}\n\nmodule.exports = {volList: volList, volCreate: volCreate, volDetails: volDetails, volSnapshotCopy: volSnapshotCopy};" }, { "alpha_fraction": 0.491418719291687, "alphanum_fraction": 0.49728304147720337, "avg_line_length": 34.67562484741211, "blob_id": "20d24d63ee03af7c2574c7abcd1d46b1df219930", "content_id": "49e9c25a354da4b2fc9467b7d067d921e5c8a647", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 18587, "license_type": "permissive", "max_line_length": 129, "num_lines": 521, "path": "/app/network_policies/networkpolicies_test.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 3/10/16.\n */\n'use strict';\n\ndescribe('contiv.networkpolicies module', function () {\n\n var policiesData = [\n {\n \"key\": \"default:middleware_net_policy\",\n \"policyName\": \"middleware_net_policy\",\n \"tenantName\": \"default\",\n \"link-sets\": {},\n \"links\": {\n \"Tenant\": {\n \"type\": \"tenant\",\n \"key\": \"default\"\n }\n }\n },\n {\n \"key\": \"default:db_net_policy\",\n \"policyName\": \"db_net_policy\",\n \"tenantName\": \"default\",\n \"link-sets\": {},\n \"links\": {\n \"Tenant\": {\n \"type\": \"tenant\",\n \"key\": \"default\"\n }\n }\n }\n ];\n\n var networksData = [\n {\n \"key\": \"default:contiv-net1\",\n \"encap\": \"vxlan\",\n \"gateway\": \"20.1.2.254\",\n \"networkName\": \"contiv-net1\",\n \"subnet\": \"20.1.2.0/24\",\n \"tenantName\": \"default\",\n \"link-sets\": {},\n \"links\": {\n \"Tenant\": {\n \"type\": \"tenant\",\n \"key\": \"default\"\n }\n }\n }\n ];\n\n var groupsData = [\n {\n \"key\": \"default:contiv-net1:prod-web\",\n \"endpointGroupId\": 1,\n \"groupName\": \"prod-web\",\n \"networkName\": \"contiv-net1\",\n \"policies\": [\n \"proxy-net-policy\"\n ],\n \"tenantName\": \"default\",\n \"link-sets\": {\n \"Policies\": {\n \"default:proxy-net-policy\": {\n \"type\": \"policy\",\n \"key\": \"default:proxy-net-policy\"\n }\n }\n },\n \"links\": {\n \"AppProfile\": {},\n \"Network\": {},\n \"Tenant\": {\n \"type\": \"tenant\",\n \"key\": \"default\"\n }\n }\n },\n {\n \"key\": \"default:contiv-net2:prod-app\",\n \"endpointGroupId\": 2,\n \"groupName\": \"prod-app\",\n \"networkName\": \"contiv-net2\",\n \"policies\": [\n \"app-net-policy\"\n ],\n \"tenantName\": \"default\",\n \"link-sets\": {\n \"Policies\": {\n \"default:app-net-policy\": {\n \"type\": \"policy\",\n \"key\": \"default:app-net-policy\"\n }\n }\n },\n \"links\": {\n \"AppProfile\": {},\n \"Network\": {},\n \"Tenant\": {\n \"type\": \"tenant\",\n \"key\": \"default\"\n }\n }\n },\n {\n \"key\": \"default:contiv-net2:prod-stor\",\n \"endpointGroupId\": 5,\n \"groupName\": \"prod-stor\",\n \"networkName\": \"contiv-net2\",\n \"policies\": [\n \"db-net-policy\"\n ],\n \"tenantName\": \"default\",\n \"link-sets\": {\n \"Policies\": {\n \"default:db-net-policy\": {\n \"type\": \"policy\",\n \"key\": \"default:db-net-policy\"\n }\n }\n },\n \"links\": {\n \"AppProfile\": {},\n \"Network\": {},\n \"Tenant\": {\n \"type\": \"tenant\",\n \"key\": \"default\"\n }\n }\n }\n ];\n\n var rulesData = [\n {\n \"key\": \"default:middleware-net-policy:1\",\n \"action\": \"allow\",\n \"direction\": \"out\",\n \"policyName\": \"middleware-net-policy\",\n \"priority\": 1,\n \"protocol\": \"tcp\",\n \"ruleId\": \"1\",\n \"tenantName\": \"default\",\n \"link-sets\": {\n \"Policies\": {\n \"default:middleware-net-policy\": {\n \"type\": \"policy\",\n \"key\": \"default:middleware-net-policy\"\n }\n }\n }\n },\n {\n \"key\": \"default:proxy-net-policy:1\",\n \"action\": \"allow\",\n \"direction\": \"in\",\n \"policyName\": \"proxy-net-policy\",\n \"port\": 443,\n \"priority\": 1,\n \"protocol\": \"tcp\",\n \"ruleId\": \"1\",\n \"tenantName\": \"default\",\n \"link-sets\": {\n \"Policies\": {\n \"default:proxy-net-policy\": {\n \"type\": \"policy\",\n \"key\": \"default:proxy-net-policy\"\n }\n }\n }\n },\n {\n \"key\": \"default:proxy-net-policy:2\",\n \"action\": \"allow\",\n \"direction\": \"in\",\n \"policyName\": \"proxy-net-policy\",\n \"port\": 80,\n \"priority\": 1,\n \"protocol\": \"tcp\",\n \"ruleId\": \"2\",\n \"tenantName\": \"default\",\n \"link-sets\": {\n \"Policies\": {\n \"default:proxy-net-policy\": {\n \"type\": \"policy\",\n \"key\": \"default:proxy-net-policy\"\n }\n }\n }\n }\n ];\n\n var netprofileData = [\n {\n \"DSCP\": 10,\n \"bandwidth\": \"10 gbps\",\n \"key\": \"default:pr1\",\n \"link-sets\": {\n \"EndpointGroups\": {\n \"default:g1\": {\n \"key\": \"default:g1\",\n \"type\": \"endpointGroup\"\n }\n }\n },\n \"links\": {\n \"Tenant\": {\n \"key\": \"default\",\n \"type\": \"tenant\"\n }\n },\n \"profileName\": \"pr1\",\n \"tenantName\": \"default\"\n },\n {\n \"DSCP\": 34,\n \"bandwidth\": \"34 gbps\",\n \"key\": \"default:pr2\",\n \"link-sets\": {\n \"EndpointGroups\": {\n \"default:g2\": {\n \"key\": \"default:g2\",\n \"type\": \"endpointGroup\"\n },\n \"default:g3\": {\n \"key\": \"default:g3\",\n \"type\": \"endpointGroup\"\n }\n }\n },\n \"links\": {\n \"Tenant\": {\n \"key\": \"default\",\n \"type\": \"tenant\"\n }\n },\n \"profileName\": \"pr2\",\n \"tenantName\": \"default\"\n },\n {\n \"DSCP\": 3,\n \"bandwidth\": \"20 mbps\",\n \"key\": \"default:p3\",\n \"link-sets\": {\n \"EndpointGroups\": {\n \"default:g4\": {\n \"key\": \"default:g4\",\n \"type\": \"endpointGroup\"\n }\n }\n },\n \"links\": {\n \"Tenant\": {\n \"key\": \"default\",\n \"type\": \"tenant\"\n }\n },\n \"profileName\": \"p3\",\n \"tenantName\": \"default\"\n }\n ];\n\n beforeEach(module('ui.router'));\n\n beforeEach(module('contiv.networkpolicies'));\n\n beforeEach(module('contiv.test.directives'));\n\n var $httpBackend;\n\n beforeEach(inject(function (_$httpBackend_) {\n $httpBackend = _$httpBackend_;\n $httpBackend.when('GET', ContivGlobals.POLICIES_ENDPOINT).respond(policiesData);\n $httpBackend.when('GET', ContivGlobals.NETWORKS_ENDPOINT).respond(networksData);\n $httpBackend.when('GET', ContivGlobals.APPLICATIONGROUPS_ENDPOINT).respond(groupsData);\n $httpBackend.when('GET', ContivGlobals.RULES_ENDPOINT).respond(rulesData);\n\n $httpBackend.when('GET', ContivGlobals.NETPROFILES_ENDPOINT).respond(netprofileData);\n $httpBackend.when('DELETE', ContivGlobals.NETPROFILES_ENDPOINT + netprofileData[0].key + '/').respond(netprofileData[0]);\n $httpBackend.when('POST', ContivGlobals.NETPROFILES_ENDPOINT + netprofileData[0].key + '/').respond(netprofileData[0]);\n $httpBackend.when('PUT', ContivGlobals.NETPROFILES_ENDPOINT + netprofileData[0].key + '/').respond(netprofileData[0]);\n }));\n\n\n afterEach(function () {\n $httpBackend.verifyNoOutstandingExpectation();\n $httpBackend.verifyNoOutstandingRequest();\n });\n\n describe('bandwidthpolicylistctrl', function () {\n\n var $controller, $interval, $rootScope;\n var policyListCtrl;\n beforeEach(inject(function (_$interval_, _$rootScope_, _$controller_) {\n $interval = _$interval_;\n $rootScope = _$rootScope_;\n $controller = _$controller_;\n policyListCtrl = $controller('BandwidthPolicyListCtrl', { $interval: $interval, $scope: $rootScope });\n }));\n it('should be defined', function () {\n //spec body\n expect(policyListCtrl).toBeDefined();\n $httpBackend.flush();\n });\n it('BandwidthPolicyListCtrl should do a GET on /api/v1/netprofiles/ REST API', function () {\n $httpBackend.expectGET(ContivGlobals.NETPROFILES_ENDPOINT);\n $httpBackend.flush();\n });\n it('BandwidthPolicyListCtrl should have policy array assigned to policies property', function () {\n $httpBackend.expectGET(ContivGlobals.NETPROFILES_ENDPOINT);\n $httpBackend.flush();\n expect(Array.isArray(policyListCtrl.policies)).toBeTruthy();\n expect(policyListCtrl.policies.length).toEqual(3);\n });\n it('BandwidthPolicyListCtrl should have showLoader property set to false after fetch', function () {\n $httpBackend.expectGET(ContivGlobals.NETPROFILES_ENDPOINT);\n $httpBackend.flush();\n expect(policyListCtrl.showLoader).toBeFalsy();\n });\n\n });\n\n\n describe('bandwidthpolicydetailsctrl', function () {\n\n var $controller, $state, $stateParams;\n var bandwidthPolicyDetailsCtrl;\n beforeEach(inject(function (_$state_ ,_$stateParams_, _$controller_) {\n $state = _$state_;\n $state.go = function (stateName) {};\n $stateParams = _$stateParams_;\n $stateParams.key = netprofileData[0].key;\n $controller = _$controller_;\n bandwidthPolicyDetailsCtrl = $controller('BandwidthPolicyDetailsCtrl',\n { $state: $state, $stateParams: $stateParams });\n }));\n\n it('should be defined', function () {\n expect(bandwidthPolicyDetailsCtrl).toBeDefined();\n $httpBackend.flush();\n });\n\n it('BandwidthPolicyDetailsCtrl should have showLoader property set to false after fetch', function () {\n $httpBackend.expectGET(ContivGlobals.NETPROFILES_ENDPOINT);\n $httpBackend.flush();\n expect(bandwidthPolicyDetailsCtrl.showLoader).toBeFalsy();\n });\n\n it('BandwidthPolicyDetailsCtrl.deletePolicy() should do a DELETE on /api/v1/netprofiles/ REST API', function () {\n //Call flush to fulfill all the http requests to get netprofile policys before calling deleteNetwork()\n $httpBackend.flush();\n bandwidthPolicyDetailsCtrl.deletePolicy();\n $httpBackend.expectDELETE(ContivGlobals.NETPROFILES_ENDPOINT + netprofileData[0].key + '/');\n $httpBackend.flush();\n expect(bandwidthPolicyDetailsCtrl.showLoader).toBeFalsy();\n });\n\n it('BandwidthPolicyDetailsCtrl.savePolicy() should do a PUT on /api/v1/netprofiles/ REST API', function() {\n $httpBackend.flush();\n bandwidthPolicyDetailsCtrl.form = {'$valid' : true};\n bandwidthPolicyDetailsCtrl.policy.bandwidthNumber = '10';\n bandwidthPolicyDetailsCtrl.policy.bandwidthUnit = 'gbps';\n bandwidthPolicyDetailsCtrl.policy.DSCP = 10;\n bandwidthPolicyDetailsCtrl.savePolicy();\n $httpBackend.expectPUT(ContivGlobals.NETPROFILES_ENDPOINT + netprofileData[0].key + '/');\n $httpBackend.flush();\n expect(bandwidthPolicyDetailsCtrl.showLoader).toBeFalsy();\n });\n\n });\n\n describe('bandwidthpolicycreatectrl', function () {\n\n var $controller,$state,$stateParams;\n var bandwidthPolicyCreateCtrl;\n beforeEach(inject(function (_$state_,_$stateParams_, _$controller_) {\n $controller = _$controller_;\n $state = _$state_;\n $stateParams = _$stateParams_;\n \n $state.go = function (stateName) {};\n $stateParams.key = netprofileData[0].key;\n bandwidthPolicyCreateCtrl = $controller('BandwidthPolicyCreateCtrl',\n { $state: $state});\n }));\n\n it('should be defined', function () {\n var bandwidthPolicyCreateCtrl = $controller('BandwidthPolicyCreateCtrl');\n expect(bandwidthPolicyCreateCtrl).toBeDefined();\n });\n\n\n it('BandwidthPolicyCreateCtrl.createPolicy should do a POST on /api/v1/netprofiles/ REST API', function () {\n bandwidthPolicyCreateCtrl.form = {'$valid' : true};\n bandwidthPolicyCreateCtrl.newPolicy.profileName = 'pr1';\n bandwidthPolicyCreateCtrl.bandwidthNumber = '10';\n bandwidthPolicyCreateCtrl.bandwidthUnit = 'gbps'\n bandwidthPolicyCreateCtrl.newPolicy.DSCP = 10;\n bandwidthPolicyCreateCtrl.createPolicy();\n $httpBackend.expectPOST(ContivGlobals.NETPROFILES_ENDPOINT + netprofileData[0].key + '/');\n $httpBackend.flush();\n expect(bandwidthPolicyCreateCtrl.showLoader).toBeFalsy();\n });\n\n it('BandwidthPolicyCreateCtrl.createPolicy should not do a POST on /api/v1/netprofiles/ REST API', function () {\n bandwidthPolicyCreateCtrl.form = {'$valid' : false};\n bandwidthPolicyCreateCtrl.newPolicy.profileName = 'pr1';\n bandwidthPolicyCreateCtrl.bandwidthNumber = '10';\n bandwidthPolicyCreateCtrl.bandwidthUnit = 'gbps'\n bandwidthPolicyCreateCtrl.newPolicy.DSCP = 10;\n bandwidthPolicyCreateCtrl.createPolicy();\n $httpBackend.verifyNoOutstandingRequest();\n expect(bandwidthPolicyCreateCtrl.showLoader).toBeFalsy();\n });\n });\n\n\n\n describe('isolationpolicylistctrl', function () {\n\n var $controller, $interval, $rootScope;\n var policyListCtrl;\n beforeEach(inject(function (_$interval_, _$rootScope_, _$controller_) {\n $interval = _$interval_;\n $rootScope = _$rootScope_;\n $controller = _$controller_;\n policyListCtrl = $controller('IsolationPolicyListCtrl', { $interval: $interval, $scope: $rootScope });\n }));\n it('should be defined', function () {\n //spec body\n expect(policyListCtrl).toBeDefined();\n $httpBackend.flush();\n });\n it('IsolationPolicyListCtrl should do a GET on /api/policys/ REST API', function () {\n $httpBackend.expectGET(ContivGlobals.POLICIES_ENDPOINT);\n $httpBackend.flush();\n });\n it('IsolationPolicyListCtrl should have policy array assigned to policies property', function () {\n $httpBackend.expectGET(ContivGlobals.POLICIES_ENDPOINT);\n $httpBackend.flush();\n expect(Array.isArray(policyListCtrl.policies)).toBeTruthy();\n expect(policyListCtrl.policies.length).toEqual(2);\n });\n it('IsolationPolicyListCtrl should have showLoader property set to false after fetch', function () {\n $httpBackend.expectGET(ContivGlobals.POLICIES_ENDPOINT);\n $httpBackend.flush();\n expect(policyListCtrl.showLoader).toBeFalsy();\n });\n });\n\n\n describe('isolationpolicydetailsctrl', function () {\n\n var $controller, $state, $stateParams;\n var isolationPolicyDetailsCtrl;\n\n beforeEach(inject(function (_$state_ ,_$stateParams_, _$controller_) {\n $state = _$state_;\n $state.go = function (stateName) {};\n $stateParams = _$stateParams_;\n $stateParams.key = policiesData[0].key;\n $controller = _$controller_;\n isolationPolicyDetailsCtrl = $controller('IsolationPolicyDetailsCtrl',\n { $state: $state, $stateParams: $stateParams });\n }));\n\n it('should be defined', function () {\n expect(isolationPolicyDetailsCtrl).toBeDefined();\n $httpBackend.flush();\n });\n\n it('IsolationPolicyDetailsCtrl should have showLoader property set to false after fetch', function () {\n $httpBackend.expectGET(ContivGlobals.POLICIES_ENDPOINT);\n $httpBackend.flush();\n expect(isolationPolicyDetailsCtrl.showLoader).toBeFalsy();\n });\n });\n\n describe('isolationpolicycreatectrl', function () {\n\n var $controller;\n beforeEach(inject(function (_$controller_) {\n $controller = _$controller_;\n }));\n\n it('should be defined', function () {\n var isolationPolicyCreateCtrl = $controller('IsolationPolicyCreateCtrl');\n expect(isolationPolicyCreateCtrl).toBeDefined();\n });\n\n });\n \n\n describe('bandwidth directive', function () {\n var element;\n var $rootScope,$compile;\n\n var policy = netprofileData[0];\n var mode_var = \"create\";\n \n beforeEach(inject(function(_$compile_,_$rootScope_){\n // The injector unwraps the underscores (_) from around the parameter names when matching\n $rootScope = _$rootScope_;\n $compile = _$compile_;\n\n }));\n beforeEach(inject(function() {\n // Compile a piece of HTML containing the directive\n\n element = $compile(\"<ctv-bandwidth mode=mode_var bandwidth-policy=policy></ctv-bandwidth>\")($rootScope);\n $rootScope.policy=policy;\n $rootScope.mode = mode_var;\n // fire all the watches, so the scope expression will be evaluated\n $rootScope.$digest();\n }));\n it('Replaces the element with the appropriate content', function () {\n expect(element.html()).toContain(\"<div ng-switch=\\\"mode\\\">\");\n \n });\n });\n});\n" }, { "alpha_fraction": 0.553101122379303, "alphanum_fraction": 0.5556499361991882, "avg_line_length": 33.130435943603516, "blob_id": "0a85d0cb7bdd78d7fe88acd21224ba67916fa703", "content_id": "12b742875cba540c1a8ecc90464421b791a49f2a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2354, "license_type": "permissive", "max_line_length": 94, "num_lines": 69, "path": "/app/components/models/authorizationmodel.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 12/13/16.\n */\n\n\nimport {Injectable} from \"@angular/core\";\nimport {ContivGlobals} from \"./contivglobals\";\nimport {Http, Response} from \"@angular/http\";\nimport {ApiService} from \"../utils/apiservice\";\nimport {Collection} from \"./collection\";\nimport {Authorization} from \"../../settings/authorization/authorizationcreate\";\n@Injectable()\n\nexport class AuthorizationModel extends Collection{\n constructor(http: Http, apiService: ApiService) {\n super(http, ContivGlobals.AUTHORIZATION_ENDPOINT, apiService);\n }\n\n delete(authId): Promise<any>{\n var collection = this;\n var url = collection.url + authId + '/';\n return super.deleteUsingKey(authId, 'AuthzUUID', url);\n }\n\n save(model):Promise<any> {\n var collection = this;\n var url = ContivGlobals.AUTHORIZATION_ENDPOINT + model['AuthzUUID'] + '/';\n return this.apiService.patch(url, model).map((res:Response) => res.json()).toPromise()\n .then((result) => {\n _.remove(collection.models, function (n) {\n return n['AuthzUUID'] == model['AuthzUUID'];\n });\n collection.models.push(result);\n return result;\n });\n }\n\n create(model): Promise<any> {\n var collection = this;\n return this.apiService.post(ContivGlobals.AUTHORIZATION_ENDPOINT, model)\n .map((res:Response) => res.json()).toPromise()\n .then((result) => {\n _.remove(collection.models, function(n){\n return (n['PrincipalName'] == model['PrincipalName'] &&\n n['TenantName'] == model['TenantName'] &&\n n['Role'] == model['Role'])\n });\n collection.models.push(result);\n return result;\n });\n }\n\n get(reload: boolean): Promise<any>{\n var collection = this;\n return super.get(reload).then((res) => {\n return collection.filterResult(res);\n });\n }\n\n filterResult(result): Array<Authorization>{\n var filterItems: Array<Authorization> = [];\n for(var item of result){\n if((item.Role!=='ops') || (item.TenantName !=='')) {\n filterItems.push(item);\n }\n }\n return filterItems;\n }\n}" }, { "alpha_fraction": 0.6042483448982239, "alphanum_fraction": 0.6058823466300964, "avg_line_length": 33.39325714111328, "blob_id": "a0f222698b3be92d17b40a486a34a27a604296aa", "content_id": "f68e98bbb1e403cff6e07c9b8b95dfbd330a982b", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3060, "license_type": "permissive", "max_line_length": 85, "num_lines": 89, "path": "/app/components/directives/settings/networkcreateform.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by cshampur on 2/10/17.\n */\n\nimport {Component, Input, Output, EventEmitter, OnInit, NgZone} from \"@angular/core\";\nimport {OrganizationsModel} from \"../../models/organizationsmodel\";\nimport {CRUDHelperService} from \"../../utils/crudhelperservice\";\nimport {NetworksModel} from \"../../models/networksmodel\";\nimport {isNull} from \"util\";\nimport {ContivGlobals} from \"../../models/contivglobals\";\nimport {DisplayType} from \"./tenantcreate\";\ndeclare var $:any;\n\n@Component({\n selector: 'networkcreateform',\n templateUrl: './networkcreateform.html'\n})\n\nexport class NetworkCreateformComponent implements OnInit{\n @Input('firstRunWiz') firstRunWiz:boolean;\n @Input('newNetwork') newNetwork: any;\n @Input('clusterMode') clusterMode: string = '';\n @Output('createnetwork') createnetwork: EventEmitter<any>;\n @Output('cancel') cancel:EventEmitter<any>;\n @Output('goback') goback:EventEmitter<any>;\n @Output('skip') skip:EventEmitter<any>;\n public networkCreateCtrl: any;\n public showLoader: boolean = true;\n public tenants: any = [];\n public networkPresent: boolean = false;\n public networkNamePattern = ContivGlobals.NETWORK_NAME_REGEX;\n public DisplayType = DisplayType;\n constructor(private organizationsModel: OrganizationsModel,\n private crudHelperService: CRUDHelperService,\n private ngZone: NgZone){\n this.createnetwork = new EventEmitter<any>();\n this.cancel = new EventEmitter<any>();\n this.goback = new EventEmitter<any>();\n this.skip = new EventEmitter<any>();\n this.networkCreateCtrl = this;\n }\n\n getTenants(reload: boolean) {\n var component = this;\n component.organizationsModel.get(reload)\n .then((result) => {\n component.tenants = result;\n if(component.clusterMode === 'kubernetes' && component.firstRunWiz)\n component.newNetwork['networkName'] = 'default-net';\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n })\n }, (error) => {\n component.ngZone.run(() => {\n component.crudHelperService.stopLoader(component);\n })\n });\n }\n\n ngOnInit(){\n var component = this;\n this.crudHelperService.startLoader(this);\n this.getTenants(false);\n }\n\n closeTenantCreate() {\n $('#tenant-create-modal').modal('hide');\n }\n\n showTenantModal() {\n $('#tenant-create-modal').modal('show');\n }\n\n createNetwork(formvalid: boolean){\n if(formvalid){\n if (isNull(this.newNetwork.pktTag)) {\n delete this.newNetwork.pktTag;\n }\n if (this.newNetwork.cfgdTag === '') {\n delete this.newNetwork.cfgdTag;\n }\n if (this.newNetwork.nwType === '') {\n delete this.newNetwork.nwType;\n }\n this.createnetwork.emit(this.newNetwork);\n }\n }\n\n}" }, { "alpha_fraction": 0.3428625762462616, "alphanum_fraction": 0.35353535413742065, "avg_line_length": 36.73381423950195, "blob_id": "f9718a1fc0e60561181f53fcb382d2559adf3798", "content_id": "7442a93d1530189e563e0e2b090605260571973d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5247, "license_type": "permissive", "max_line_length": 96, "num_lines": 139, "path": "/app/visualization/visualizationedgedirective.js", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "\n\nangular.module('contiv.visualization')\n .directive(\"visualizationEdge\", ['$window',\n function($window) {\n function visualizationEdgeD3(scope, d3) {\n var bodyEl = document.getElementsByTagName('body')[0];\n \n var width = bodyEl.clientWidth - 400,\n height = bodyEl.clientHeight - 400;\n\n\n //taken from http://bl.ocks.org/simenbrekken/6634070\n // /** MAIN SVG **/\n var limit = 59,\n duration = 750,\n now = new Date(Date.now() - duration);\n\n var groups = {\n current: {\n value: 0,\n color: 'orange',\n data: d3.range(limit).map(function(d) {\n return scope.oldEdgeData[Math.floor(d/10)] || 0;\n })\n }\n };\n var x = d3.time.scale()\n .domain([now - (limit - 2), now - duration])\n .range([0, width]);\n\n var y = d3.scale.linear()\n .domain([0, d3.max(groups.current.data, function (d) { return d + 10; })])\n .range([height, 0]);\n\n var line = d3.svg.line()\n .interpolate('basis')\n .x(function(d, i) {\n return x(now - (limit - 1 - i) * duration)\n })\n .y(function(d) {\n return y(d)\n });\n\n var xSvg = d3.select('.graph').append('svg')\n .attr('width', 25)\n .style('overflow', 'visible')\n .style('position', 'fixed');\n\n \n\n var yAxis = xSvg.append('g')\n .attr('class', 'y axis')\n // .attr('transform', 'translate(0,' + width + ')')\n .call(y.axis = d3.svg.axis().scale(y).orient('left'));\n \n var svg= d3.select('.graph').append('svg')\n .attr('class', 'chart')\n .attr('width', width - 50)\n .attr('height', height + 50);\n // .style('overflow', \"visible\");\n\n var axis = svg.append('g')\n .attr('class', 'x axis')\n .attr('transform', 'translate(0,' + height + ')')\n .call(x.axis = d3.svg.axis().scale(x).orient('bottom'));\n\n var paths = svg.append('g');\n\n for (var name in groups) {\n var group = groups[name];\n group.path = paths.append('path')\n .data([group.data])\n .attr('class', name + ' group')\n .style('stroke', group.color)\n }\n\n function tick() {\n now = new Date();\n\n // Add new values\n for (var name in groups) {\n var group = groups[name];\n group.data.push(scope.edgeData || 0);\n group.path.attr('d', line)\n }\n\n // Shift domain\n x.domain([now - (limit - 2) * duration, now - duration]);\n\n // Slide x-axis left\n axis.transition()\n .duration(duration)\n .ease('linear')\n .call(x.axis);\n\n yAxis.transition()\n .duration(duration)\n .ease('linear')\n .call(y.axis);\n\n // Slide paths left\n paths.attr('transform', null)\n .transition()\n .duration(duration)\n .ease('linear')\n .attr('transform', 'translate(' + x(now - (limit - 1) * duration) + ')')\n .each('end', function() {\n tick()\n });\n\n // Remove oldest data point from each group\n for (var name in groups) {\n var group = groups[name];\n group.data.shift()\n }\n }\n tick()\n }\n\n return{\n restrict:'EA',\n replace: false,\n templateUrl: 'visualization/visualizationedgetemplate.html',\n link: function(scope){\n scope.$watchGroup(['edgeData', 'oldEdgeData'],\n function() {\n if (scope.edgeData != null &&\n scope.oldEdgeData != null ) {\n if (!scope.initialize) {\n scope.initialize = true;\n var d3 = $window.d3; \n visualizationEdgeD3(scope, d3);\n }\n } \n });\n }\n };\n }\n ]\n);\n" }, { "alpha_fraction": 0.66434645652771, "alphanum_fraction": 0.6658932566642761, "avg_line_length": 39, "blob_id": "6ef4a494113e1b3b731a3628e23e845108e574f2", "content_id": "92b4f002e6c3ca500bee1f789560ef7790887f38", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3879, "license_type": "permissive", "max_line_length": 128, "num_lines": 97, "path": "/app/applicationgroups/applicationgroupdetailsctrl.ts", "repo_name": "contiv/contiv-ui", "src_encoding": "UTF-8", "text": "/**\n * Created by vjain3 on 3/15/16.\n */\nimport {Component, Inject, OnInit, NgZone} from '@angular/core';\nimport { ActivatedRoute, Router } from \"@angular/router\";\nimport { ApplicationGroupsModel } from \"../components/models/applicationgroupsmodel\";\nimport { CRUDHelperService } from \"../components/utils/crudhelperservice\";\n\n@Component({\n selector: 'applicationgroupdetails',\n templateUrl: './applicationgroupdetails.html'\n})\nexport class ApplicationGroupDetailsComponent implements OnInit{\n applicationGroup:any = {};\n mode:string = 'details';\n public infoselected: boolean;\n public statskey: string;\n public showLoader: boolean;\n public showServerError: boolean;\n public serverErrorMessage: string;\n\n constructor(private activatedRoute: ActivatedRoute,\n private router: Router,\n private ngZone: NgZone,\n private applicationGroupsModel:ApplicationGroupsModel,\n private crudHelperService:CRUDHelperService) {\n var applicationGroupDetailsCtrl = this;\n\n /**\n * To show edit or details screen based on the route\n */\n function setMode() {\n if (activatedRoute.routeConfig.path.includes('edit')) {\n applicationGroupDetailsCtrl.mode = 'edit';\n } else {\n applicationGroupDetailsCtrl.mode = 'details';\n }\n }\n\n applicationGroupDetailsCtrl.crudHelperService.startLoader(applicationGroupDetailsCtrl);\n\n applicationGroupDetailsCtrl.applicationGroupsModel.getModelByKey(activatedRoute.snapshot.params['key'], false, 'key')\n .then(function (group) {\n applicationGroupDetailsCtrl.applicationGroup = group;\n applicationGroupDetailsCtrl.ngZone.run(() => {\n applicationGroupDetailsCtrl.crudHelperService.stopLoader(applicationGroupDetailsCtrl);\n });\n\n }, (error) => {\n applicationGroupDetailsCtrl.ngZone.run(() => {\n applicationGroupDetailsCtrl.crudHelperService.stopLoader(applicationGroupDetailsCtrl);\n });\n });\n\n setMode();\n this.applicationGroup = {groupName: '', networkName: ''};\n this.serverErrorMessage = '';\n this.statskey = '';\n this.infoselected = true;\n }\n\n ngOnInit(){\n this.statskey = this.activatedRoute.snapshot.params['key'];\n }\n\n returnToApplicationGroup() {\n this.router.navigate(['../../list'], { relativeTo: this.activatedRoute });\n }\n\n returnToApplicationGroupDetails() {\n this.router.navigate(['../../details', this.applicationGroup.key], { relativeTo: this.activatedRoute });\n }\n\n editApplicationGroup() {\n this.router.navigate(['../../edit', this.applicationGroup.key], { relativeTo: this.activatedRoute });\n }\n\n cancelDetails() {\n this.returnToApplicationGroup();\n }\n\n deleteApplicationGroup() {\n var applicationGroupDetailsCtrl = this;\n applicationGroupDetailsCtrl.crudHelperService.startLoader(applicationGroupDetailsCtrl);\n applicationGroupDetailsCtrl.applicationGroupsModel.delete(applicationGroupDetailsCtrl.applicationGroup).then(\n function successCallback(result) {\n applicationGroupDetailsCtrl.crudHelperService.stopLoader(applicationGroupDetailsCtrl);\n applicationGroupDetailsCtrl.crudHelperService.showNotification(\"Application group: Deleted\", result.toString());\n applicationGroupDetailsCtrl.returnToApplicationGroup();\n }, function errorCallback(result) {\n applicationGroupDetailsCtrl.crudHelperService.stopLoader(applicationGroupDetailsCtrl);\n applicationGroupDetailsCtrl.crudHelperService.showServerError(\"Application group: Delete failed\", result);\n });\n }\n\n\n}" } ]
172
aojiang996/one-piece-comic-crawler
https://github.com/aojiang996/one-piece-comic-crawler
ea584313d863fbf1627903359bd3dd5cd475b082
9f0cde8f838b54d1d28a0c045b0f99404aaa17c4
dc7dd93673dc40eba7617fea35be617cee11eead
refs/heads/master
2022-12-12T03:08:39.513833
2020-08-12T15:02:21
2020-08-12T15:02:21
287,041,769
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5721630454063416, "alphanum_fraction": 0.5930958390235901, "avg_line_length": 24.715686798095703, "blob_id": "c05935f0650eae01933d4a83b09bf980ab4dc077", "content_id": "973c157418e8cb1d84bcb704103ce7e9312c6038", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2835, "license_type": "no_license", "max_line_length": 107, "num_lines": 102, "path": "/one_piece.py", "repo_name": "aojiang996/one-piece-comic-crawler", "src_encoding": "UTF-8", "text": "# coding=utf-8\r\n'''\r\nCreated on 2020-4-2\r\n@author: jiangao\r\nProject: one piece 漫画爬取\r\n'''\r\nimport requests\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.chrome.options import Options\r\nfrom requests.exceptions import RequestException\r\nfrom bs4 import BeautifulSoup\r\nimport re\r\nimport csv\r\nimport sys\r\nimport io\r\nimport time\r\n \r\n\r\nheaders = {\r\n 'Content-Type': 'text/plain; charset=UTF-8',\r\n 'Origin':'https://maoyan.com',\r\n 'Referer':'https://maoyan.com/board/4',\r\n 'User-Agent':'Chrome/80.0.3396.99 Safari/537.36'\r\n }\r\n \r\n#爬取网页源代码\r\ndef get_one_page(url,headers):\r\n try:\r\n response =requests.get(url,headers=headers)\r\n if response.status_code == 200:\r\n response.encoding = \"utf-8\"\r\n print(\"worked\")\r\n return response.text\r\n else:\r\n print(\"none\")\r\n print(response.status_code)\r\n return None\r\n except RequestException:\r\n print(\"none2\")\r\n print(response.status_code)\r\n return None\r\n\r\n#提取正则表达式\r\ndef parse_one_page(html):\r\n pattern = re.compile('<img class=\"\" src=\"(.*?)\" alt=\"')\r\n p = re.findall(pattern,html)\r\n return p\r\n\r\ndef parse_image_page(html):\r\n pattern = re.compile('http://mhua.zerobyw4.com/manhua/.*?/.*?/(.*)')\r\n p = re.findall(pattern,html)\r\n return p\r\n\r\n#下载海报\r\ndef save_image_file(url,path):\r\n jd = requests.get(url)\r\n if jd.status_code == 200:\r\n with open(path,'wb') as e:\r\n e.write(jd.content)\r\n e.close()\r\n\r\ndef main(k):\r\n sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf8') #改变标准输出的默认编码\r\n chrome_driver = 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe' #chromedriver的文件位置\r\n b = webdriver.Chrome(executable_path = chrome_driver)\r\n f = open('C:/Users/Desktop/all.txt','r')\r\n html = f.readlines()\r\n f.close()\r\n files = 'D:/one/'\r\n\r\n b.get(html[k-1])\r\n time.sleep(2)\r\n #输入账号\r\n username = b.find_element_by_name('username')\r\n username.send_keys('username')\r\n #输入密码\r\n password = b.find_element_by_name('password')\r\n password.send_keys('password')\r\n #点击登录\r\n login_button = b.find_element_by_class_name('vm')\r\n login_button.submit()\r\n\r\n p = parse_one_page(b.page_source.encode('utf-8').decode())\r\n\r\n one = p[0]\r\n strinfo = re.compile('002')\r\n one = strinfo.sub('001',one)\r\n p.reverse()#反向列表元素\r\n p.append(one)\r\n p.reverse()\r\n for j in p:\r\n num = parse_image_page(j)\r\n path = files+str(k)+'/'+ num[0]\r\n save_image_file(j,path)\r\n k += 1\r\n b.quit()\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n url = 'http://mhua.zerobyw4.com/manhua/O9NI9EC6E/94/001.jpg'\r\n print(get_one_page(url,headers))" }, { "alpha_fraction": 0.3992413580417633, "alphanum_fraction": 0.4357515275478363, "avg_line_length": 25.697368621826172, "blob_id": "c82ec1275ba72bdca7c811b2530f001fc2587255", "content_id": "2bfb037cd9a468fc67171937fa1fa5bc17254634", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2149, "license_type": "no_license", "max_line_length": 66, "num_lines": 76, "path": "/one_piece_regular_expression.py", "repo_name": "aojiang996/one-piece-comic-crawler", "src_encoding": "UTF-8", "text": "# coding=utf-8\r\n'''\r\nCreated on 2020-4-2\r\n@author: jiangao\r\nProject: one piece 漫画爬取\r\n'''\r\nimport requests\r\nimport threading\r\nimport sys\r\nimport io\r\nimport time\r\nimport os\r\nimport re\r\nimport socket\r\n\r\n\r\nheader = {\r\n 'Content-Type': 'text/plain; charset=UTF-8',\r\n 'User-Agent':'Chrome/80.0.3396.99 Safari/537.36'\r\n }\r\n#下载海报\r\ndef save_image_file(url,path):\r\n jd = requests.get(url,headers = header)\r\n time.sleep(2)\r\n socket.setdefaulttimeout(20)\r\n if jd.status_code == 200:\r\n print('work')\r\n time.sleep(1)\r\n with open(path,'wb') as e:\r\n e.write(jd.content)\r\n e.close()\r\n return 0\r\n else:\r\n return 1\r\n\r\ndef save(op,ed):\r\n a = 'http://mhua.zerobyw4.com/manhua/ON9EP9IE6CE/'\r\n c = '.jpg'\r\n for j in range(op,op+1):\r\n path = 'D:/one/' + str(j) +'/'\r\n for i in range(ed+1,250):\r\n if i<10:\r\n print(\"第\"+str(i)+\"张\"+\" \"+\"(\"+\"第\"+str(j)+\"卷\"+\")\")\r\n h = a + str(j) + '/' + '00' + str(i) +c\r\n b = save_image_file(h,path + '00' + str(i) +c)\r\n if b == 1:\r\n break\r\n elif i>=10 and i<100:\r\n print(\"第\"+str(i)+\"张\"+\" \"+\"(\"+\"第\"+str(j)+\"卷\"+\")\")\r\n h = a + str(j) + '/' + '0' + str(i) +c\r\n b = save_image_file(h,path + '0' + str(i) +c)\r\n if b == 1:\r\n break\r\n else:\r\n print(\"第\"+str(i)+\"张\"+\" \"+\"(\"+\"第\"+str(j)+\"卷\"+\")\")\r\n h = a + str(j) + '/' + str(i) +c\r\n b = save_image_file(h,path + str(i) +c)\r\n if b == 1:\r\n break\r\n\r\n \r\ndef save1():\r\n listos = os.listdir('D:\\\\one')\r\n for i in range(94,95):\r\n listoss = os.listdir('D:\\\\one\\\\'+str(i))\r\n j = listoss[-1:]\r\n strinfo = re.compile('.jpg')\r\n one = strinfo.sub('',j[0])\r\n save(int(i),int(one))\r\n\r\n\r\n \r\nif __name__ == '__main__':\r\n url = 'http://mhua.zerobyw4.com/manhua/O9NI9EC6E/94/001.jpg'\r\n path = 'D:\\\\one\\\\94\\\\001.jpg'\r\n save_image_file(url,path)\r\n " } ]
2
larisala/ime-runestone-server
https://github.com/larisala/ime-runestone-server
fdd0d4f8ef3809f446b4ccec1bad7fd6ccab159f
0722c1d2145b4c1e7b56547020d5eb1f55f96ec1
527356ec1327729b8e4dd1891b9c11715cc8df06
refs/heads/main
2023-02-20T02:10:49.526608
2021-01-24T23:33:56
2021-01-24T23:33:56
332,578,062
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7739403247833252, "alphanum_fraction": 0.795918345451355, "avg_line_length": 56.90909194946289, "blob_id": "6d948d42337943d525b64f614f11e3af0503cd26", "content_id": "11aadab79e37ca46d47403875d686c7454cc4161", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 639, "license_type": "no_license", "max_line_length": 150, "num_lines": 11, "path": "/README.md", "repo_name": "larisala/ime-runestone-server", "src_encoding": "UTF-8", "text": "# Runestone Server for IME-USP\n\nThis code contains the modified parts of Runestone Server (version 5.1.2) to use at University of São Paulo's Institute of Mathematics and Statistics.\n\nThe views were modified to create a custom layout for the University and translate some strings to portuguese. \n\n### How to use\n1. Follow these steps to install Runestone: https://runestoneserver.readthedocs.io/en/stable/docs/installation.html\n2. Clone this repository to your machine and place the folders inside `web2py/applications/runestone` directory.\n\nThis was a project for 2020's subject MAC0499 in Universidade de São Paulo. Larissa Goto and Jiang Zhi.\n" }, { "alpha_fraction": 0.7020046710968018, "alphanum_fraction": 0.7058725953102112, "avg_line_length": 49.61894607543945, "blob_id": "04b7fd8b94816c7198d1a99f4f983c2feb9161ad", "content_id": "0c5670edb03db715d6b26239d02a7426c0a6958a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 24333, "license_type": "no_license", "max_line_length": 283, "num_lines": 475, "path": "/languages/pt-br.py", "repo_name": "larisala/ime-runestone-server", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n{\n'': '',\n'!langcode!': 'pt-br',\n'!langname!': 'pt-br',\n'\"update\" is an optional expression like \"field1=\\'newvalue\\'\". You cannot update or delete the results of a JOIN': '\"update\" is an optional expression like \"field1=\\'newvalue\\'\". You cannot update or delete the results of a JOIN',\n'# required': '# necessário',\n'%s %%{row} deleted': '%s %%{row} deleted',\n'%s %%{row} updated': '%s %%{row} updated',\n'%s selected': '%s selected',\n'%Y-%m-%d': '%Y-%m-%d',\n'%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S',\n'(normally leave checked)': '(normally leave checked)',\n'<html>Click on <a href=\"%(link)s\">this link</a> to reset your password.</html>': '<html>Click on <a href=\"%(link)s\">this link</a> to reset your password.</html>',\n'?': '?',\n'@markmin\\x01(**%.0d MB**)': '(**%.0d MB**)',\n'@markmin\\x01**%(items)s** %%{item(items)}, **%(bytes)s** %%{byte(bytes)}': '**%(items)s** %%{item(items)}, **%(bytes)s** %%{byte(bytes)}',\n'@markmin\\x01**%(items)s** items, **%(bytes)s** %%{byte(bytes)}': '**%(items)s** items, **%(bytes)s** %%{byte(bytes)}',\n'@markmin\\x01**not available** (requires the Python [[Pympler https://pypi.python.org/pypi/Pympler popup]] library)': '**not available** (requires the Python [[Pympler https://pypi.python.org/pypi/Pympler popup]] library)',\n'@markmin\\x01``**not available**``:red (requires the Python [[Pympler https://pypi.python.org/pypi/Pympler popup]] library)': '``**not available**``:red (requires the Python [[Pympler https://pypi.python.org/pypi/Pympler popup]] library)',\n'@markmin\\x01Cache contains items up to **%(hours)02d** %%{hour(hours)} **%(min)02d** %%{minute(min)} **%(sec)02d** %%{second(sec)} old.': 'Cache contains items up to **%(hours)02d** %%{hour(hours)} **%(min)02d** %%{minute(min)} **%(sec)02d** %%{second(sec)} old.',\n'@markmin\\x01DISK contains items up to **%(hours)02d** %%{hour(hours)} **%(min)02d** %%{minute(min)} **%(sec)02d** %%{second(sec)} old.': 'DISK contains items up to **%(hours)02d** %%{hour(hours)} **%(min)02d** %%{minute(min)} **%(sec)02d** %%{second(sec)} old.',\n'@markmin\\x01Hit Ratio: **%(ratio)s%%** (**%(hits)s** %%{hit(hits)} and **%(misses)s** %%{miss(misses)})': 'Hit Ratio: **%(ratio)s%%** (**%(hits)s** %%{hit(hits)} and **%(misses)s** %%{miss(misses)})',\n'@markmin\\x01Number of entries: **%s**': 'Number of entries: **%s**',\n'@markmin\\x01RAM contains items up to **%(hours)02d** %%{hour(hours)} **%(min)02d** %%{minute(min)} **%(sec)02d** %%{second(sec)} old.': 'RAM contains items up to **%(hours)02d** %%{hour(hours)} **%(min)02d** %%{minute(min)} **%(sec)02d** %%{second(sec)} old.',\n'A new password was emailed to you': 'Uma nova senha foi enviada para seu e-mail',\n'About Runestone': 'Sobre o Runestone',\n'Active Code Runs': 'Execuções em ActiveCode',\n'Active Students': 'Estudantes Ativos',\n'Activity count': 'Contagem de atividade',\n'Add': 'Adicionar',\n'Add a New Instructor': 'Adicionar Novo Instrutor',\n'Add TA': 'Adicionar TA',\n'Add Tags': 'Add Tags',\n'Admin': 'Admin',\n'Admin Panel': 'Painel Admin',\n'All logs, records, and assignments from dates before the start date will not be visible to you or to your students.': 'All logs, records, and assignments from dates before the start date will not be visible to you or to your students.',\n'All Sections': 'Todas as Seções',\n'All Time': 'Tudo',\n'Allow Pairs': 'Permitir Pares',\n'appadmin is disabled because insecure channel': 'appadmin is disabled because insecure channel',\n'Apply changes': 'Aplicar alterações',\n'Are you sure you want to delete this object?': 'Are you sure you want to delete this object?',\n'Assignment': 'Lição',\n'assignment': 'lição',\n'Assignment Name': 'Nome da Lição',\n'Assignment properties': 'Propriedades da lição',\n'Assignment table': 'Assignment table',\n'Assignments': 'Lições',\n'Authentication code': 'Código de autenticação',\n'Author (First Last)': 'Autor (Primeiro Último)',\n'Auto-grade': 'Auto-correção',\n'Autograde and Display Totals': 'Autograde and Display Totals',\n'Autograde does not support multiple selections yet.': 'Autograde does not support multiple selections yet.',\n'Available Databases and Tables': 'Bases de Dados e Tabelas Disponíveis',\n'Average # of attempts': '# Médio de Tentativas',\n'Average grade': 'Nota média',\n'Avg Score': 'Pontuação Média',\n'Back to': 'Voltar para',\n'Back to top': 'Voltar para início',\n'Book Completion': 'Completude do Livro',\n'Book Index': 'Índice',\n'Browse': 'Navegar',\n'Build a Custom Course': 'Criar um Curso Custom',\n'cache': 'cache',\n'Cache': 'Cache',\n'Cache Cleared': 'Cache limpo',\n'Cache Keys': 'Cache Keys',\n'Cancel': 'Cancelar',\n'Cannot be empty': 'Não pode ser vazio',\n'Change Course': 'Alterar Curso',\n'Change Difficulty': 'Alterar Dificuldade',\n'Change Log': 'Change Log',\n'Change Password': 'Alterar Senha',\n'Change password': 'Alterar senha',\n'Chapter': 'Capítulo',\n'chapter': 'capítulo',\n'Chapter Activity': 'Atividade do Capítulo',\n'Chapter Progress': 'Progresso do Capítulo',\n'Check to delete': 'Marque para deletar',\n'Choose a CSV file with student information': 'Escolha um arquivo CSV com as informações dos estudantes',\n'Class Activity': 'Atividade da Classe',\n'Class Average': 'Média da Classe',\n'Clear CACHE?': 'Clear CACHE?',\n'Clear DISK': 'Clear DISK',\n'Clear Flag': 'Clear Flag',\n'Clear RAM': 'Clear RAM',\n'Click on the link %(link)s to reset your password': 'Clique no link %(link)s para redefinir sua senha',\n'Click on the question name to display or update the grade for any question.': 'Click on the question name to display or update the grade for any question.',\n'Click your course to remove it': 'Clique no curso para removê-lo',\n'Client IP': 'Client IP',\n'Close': 'Fechar',\n'Community Contributed question': 'Questão da Comunidade',\n'Competency': 'Competência',\n'Completed Section': 'Completaram a Seção',\n'computed score': 'pontuação computada',\n'Confirm Password': 'Confirmar Senha',\n'Constrain search to this course': 'Limitar busca para este curso',\n'Copy': 'Copiar',\n'Copy Assignments': 'Copiar Lições',\n'Correct': 'Estavam corretos',\n'Correct after first attempt': 'Estavam corretos após primeira tentativa',\n'Correct after multiple attempts': 'Estavam corretos após múltiplas tentativas',\n'Count of Subchapter Activities': 'Contagem de Atividades do Subcapítulo',\n'Course Name': 'Nome do Curso',\n'Course Selection': 'Seleção de Curso',\n'Course Settings': 'Configurações do Curso',\n'Course start date': 'Data de início do curso',\n'Create': 'Criar',\n'Create a Course': 'Criar um Curso',\n'Create Assignment': 'Criar Lição',\n'Create LTI Key and Secret': 'Criar Chave LTI e Secret',\n'Create New Section': 'Criar Nova Seção',\n'Created On': 'Criado Em',\n'Current request': 'Request atual',\n'Current response': 'Resposta atual',\n'Current session': 'Sessão atual',\n'data uploaded': 'data uploaded',\n'Database': 'Database',\n'Database %s select': 'Database %s select',\n'Database Administration (appadmin)': 'Database Administration (appadmin)',\n'db': 'db',\n'Define the readings students must complete by selecting chapters and subchapters of the textbook.': 'Define the readings students must complete by selecting chapters and subchapters of the textbook.',\n'Delete': 'Deletar',\n'Delete a Course': 'Deletar um Curso',\n'Delete:': 'Deletar:',\n'Description': 'Descrição',\n'Description:': 'Descrição:',\n'design': 'design',\n'Difficulty ': 'Dificuldade',\n'Difficulty:': 'Dificuldade:',\n'DISK': 'DISK',\n'Disk Cache Keys': 'Disk Cache Keys',\n'Disk Cleared': 'Disk Cleared',\n'done!': 'Feito!',\n'Download CSV': 'Download CSV',\n'Download Gradebook': 'Download Notas',\n'Download Log': 'Download Log',\n'Drop a Course': 'Sair de um Curso',\n'Due': 'Para',\n'Due Date': 'Prazo',\n'Due Date:': 'Prazo:',\n'E-mail': 'E-mail',\n'E-mail address': 'Endereço de e-mail',\n'Each row must have six elements in the order shown below.': 'Cada linha precisa ter seis elementos na seguinte ordem.',\n'Edit': 'Editar',\n'Edit current record': 'Edit current record',\n'Edit Profile': 'Editar Perfil',\n'Edit Question': 'Editar Questão',\n'Editorial Page': 'Página Editorial',\n'Email': 'E-mail',\n'Email sent': 'E-mail enviiado',\n'Email verification': 'Verificação de e-mail',\n'Email verified': 'E-mail verificado',\n'Enable ActiveCode Downloads': 'Enable ActiveCode Downloads',\n'Enable experimental pair programming features.': 'Enable experimental pair programming features.',\n'Enroll in a Course': 'Registrar-se em um Curso',\n'Enter assignment name': 'Insira nome da lição',\n'Enter date as %(format)s': 'Enter date as %(format)s',\n'Enter password': 'Insira senha',\n'Enter the new name for assignment': '',\n'Enter the new name for assignment ': 'Insira novo nome para a lição ',\n'Enter username': 'Insira usuário',\n'Errors in CSV No students registered': 'Erros no CSV - Nenhum estudante registrado',\n'Exercise Analytics': 'Análise dos Exercícios',\n'export as csv file': 'Exportar como arquivo csv',\n'Family name': 'Nome da Família',\n'FAQ': 'FAQ',\n'Filter by Assignment': 'Filtrar por Lição',\n'Filter by Student': 'Filtrar por Estudante',\n'First Interaction with all Activities': 'Primeira interação com todas as Atividades',\n'First Name': 'Primeiro Nome',\n'First name': 'Primeiro Nome',\n'first try': 'Primeira tentativa',\n'FName': 'Primeiro nome',\n'Forgot Username': 'Esqueci meu Usuário',\n'Free Text Search of question': 'Busca por texto livre',\n'Frequency': 'Frequência',\n'Function disabled': 'Função desabillitada',\n'Given name': 'Dado nome',\n'Go Back': 'Voltar',\n'Grade Book': 'Livro de Notas',\n'Gradebook': 'Livro de Notas',\n'Grades': 'Notas',\n'Grading': 'Avaliação',\n'Grading Instructions': 'Instruções de Avaliação',\n'Graph Model': 'Graph Model',\n'Group %(group_id)s created': 'Group %(group_id)s created',\n'Group %(group_id)s deleted': 'Group %(group_id)s deleted',\n'Group ID': 'Group ID',\n'Group uniquely assigned to user %(id)s': 'Group uniquely assigned to user %(id)s',\n'Help support us:': 'Ajude-nos:',\n'Help/Documentation': 'Ajuda/Documentação',\n'Hide/Show': 'Esconder/Mostrar',\n'I Accept': 'Eu Aceito',\n'If anything fails then none of the students will be added. Fix your file and try again.': 'Se algo der errado nenhum dos estudantes será adicionado. Conserte seu arquivo e tente de novo.',\n'import': 'importar',\n'Import/Export': 'Importar/Exportar',\n'Incorrect code. {0} more attempt(s) remaining.': 'Código incorreto. {0} tentativas restantes.',\n'Index': 'Índice',\n'Instructor Dashboard': 'Painel do Instrutor',\n'Instructor Name': 'Nome do Instrutor',\n\"Instructor's Page\": 'Página do Instrutor',\n'Instructors Guide': 'Guia do Instrutor',\n'Insufficient privileges': 'Privilégios insuficientes',\n'Internal State': 'Estado interno',\n'Invalid email': 'E-mail inválido',\n'Invalid key': 'Chave inválilda',\n'Invalid login': 'Login inválido',\n'Invalid password': 'Senha inválida',\n'Invalid Query': 'Query inválida',\n'invalid request': 'Request inválida',\n'Invalid reset password': 'Redefinição de senha inválida',\n'Invalid user': 'Usuário inválido',\n'Invalid username': 'Nome de usuário inválido',\n'Invitation to join %(site)s': 'Convite para se juntar à %(site)s',\n'Is Primary': 'Is Primary',\n'Key': 'Chave',\n'Key verified': 'Chave verificada',\n'Last 24 Hours': 'Últimas 24 Horas',\n'Last 7 Days': 'Últimos 7 Dias',\n'Last Interaction with all Activities': 'Última interação com todas as Atividades',\n'Last Name': 'Sobrenome',\n'Last name': 'Sobrenome',\n'Last Page Loaded': 'Última Página Carregada',\n'last try': 'última tentativa',\n'Leave blank for no limit': 'Deixe em branco para não limitar',\n'Legend:': 'Legenda:',\n'LName': 'Sorenome',\n'Location:': 'Localização:',\n'Log In': 'Entrar',\n'Log Out': 'Sair',\n'Logged in': 'Logado',\n'Logged out': 'Deslogado',\n'Login': 'Entrar',\n'Login disabled by administrator': 'Login desabilitado pelo administrador',\n'Lost Password': 'Perdi Minha Senha',\n'LTI Configuration': 'Configuração LTI',\n'LTI Integration': 'Integração LTI',\n'Make Private': 'Tornar Privado',\n'Manage %(action)s': 'Gerenciar %(action)s',\n'Manage Access Control': 'Gerenciar Controle de Acesso',\n'Manage Cache': 'Gerenciar Cache',\n'Manage Students': 'Gerenciar Estudantes',\n'manual override score': 'sobrescrever pontuação manualmente',\n'Max points': 'Pontos máximos',\n'Maximum': 'Máximo',\n'Memberships': 'Membros',\n'Minimum': 'Mínimo',\n'Modified On': 'Modificado Em',\n'Name': 'Nome',\n'Name of assignment': 'Nome da lição',\n'Name of student': 'Nome do estudante',\n'Never attempted': 'Nunca tentaram',\n'Never correct': 'Nunca acertaram',\n'New password': 'Nova senha',\n'New Record': 'New Record',\n'new record inserted': 'new record inserted',\n'next %s rows': 'next %s rows',\n'No databases in this application': 'No databases in this application',\n'No Feedback': 'Sem Feedback',\n'No Pause': 'Sem Pausa',\n'No valid students were selected': 'Nenhum estudante válido foi selecionado',\n'Not logged in': 'Não logado',\n'Not Started': 'Não iniciaram',\n'Not yet graded': 'Não avaliado',\n'Note': 'Nota',\n'Number of clicks': 'Número de cliques',\n'Number of Interactions with each Activity': 'Número de Interações com cada Atividade',\n'Object or table name': 'Object or table name',\n'Old password': 'Senha antiga',\n'Only check work submitted before': 'Ver apenas trabalhos submetidos antes de',\n'or import from csv file': 'ou importe de um arquivo csv',\n'Origin': 'Origem',\n'Other Activities': 'Outras Atividades',\n'Our Library': 'Nossa Biblioteca',\n'Overall Progression': 'Progresso Geral',\n'Override student score for whole assignment.': 'Sobrescrever pontuação de toda a lição.',\n'Overview': 'Resumo',\n'Page Views': 'Visualizações de Páginas',\n'Password': 'Senha',\n'Password changed': 'Senha alterada',\n\"Password fields don't match\": 'Campos de senha devem ser iguais',\n'Password reset': 'Redefinição de senha',\n'Password retrieve': 'Recuperação de senha',\n'Percent': 'Porcentagem',\n'Percent of students who have': 'Porcentagem de estudantes que',\n'Permission': 'Permissão',\n'Permissions': 'Permissões',\n'Please edit your csv file in a text editor and correct the errors.': 'Por favor edite seu arquivo csv em um editor de texto e corrija os erros.',\n'please input your password again': 'Por favor, insira sua senha novamente',\n'Points': 'Pontos',\n'Points Possible': 'Pontos Possíveis',\n'Practice': 'Prática',\n'Preview': 'Prévia',\n'previous %s rows': 'previous %s rows',\n'Privacy Policy': 'Política de Privacidade',\n'Private': 'Privado',\n'Problems': 'Problemas',\n'Profile': 'Perfil',\n'Profile updated': 'Perfil atualizado',\n'Progress Page': 'Página de Progresso',\n'Query:': 'Query:',\n'Question': 'Questão',\n'Question id': 'id da Questão',\n'Question in Context': 'Questão no Contexto',\n'Question is autograded': 'Questão é auto-avaliada',\n'Question location': 'Localização da questão',\n'Question type': 'Tipo da questão',\n'Question Type': 'Tipo de Questão',\n'Question written by author': 'Questão escrita pelo autor',\n'Questions': 'Questões',\n'Questions for Review': 'Questões para revisão',\n'RAM': 'RAM',\n'RAM Cache Keys': 'RAM Cache Keys',\n'Ram Cleared': 'Ram Cleared',\n'Readings': 'Leituras',\n'Really Delete': 'Realmente deletar',\n'Recent Activity': 'Atividade Recente',\n'Record': 'Record',\n'Record %(id)s created': 'Record %(id)s created',\n'Record %(id)s deleted': 'Record %(id)s deleted',\n'Record %(id)s read': 'Record %(id)s read',\n'Record %(id)s updated': 'Record %(id)s updated',\n'Record Created': 'Record Created',\n'Record Deleted': 'Record Deleted',\n'record does not exist': 'record does not exist',\n'Record id': 'Record id',\n'Record ID': 'Record ID',\n'Record Updated': 'Record Updated',\n'Refresh table': 'Refresh table',\n'Register': 'Cadastre-se',\n'Register Students': 'Cadastrar Estudantes',\n'Registration identifier': 'Identificador de cadastro',\n'Registration is pending approval': 'Cadastro está aguardando aprovação',\n'Registration key': 'Chave de cadastro',\n'Registration needs verification': 'Cadastro precisa de verificação',\n'Registration successful': 'Cadastro bem sucedido',\n'Release Grade to LMS': 'Lançar Nota para LMS',\n'Release Grades': 'Lançar Notas',\n'Remember me': 'Lembre-me',\n'Remember me (for 30 days)': 'Lembre-me (por 30 dias)',\n'Remove a Course': 'Remover um Curso',\n'Remove a Current Instructor': 'Remover Instrutor Atual',\n'Remove Student(s)': 'Remover Estudante(s)',\n'Removing a student drops them from your course and transfers them to the \"open\" course for the same book.': 'Remover um estudante o retira do seu curso e transfere ele para o curso \"aberto\" do mesmo livro.',\n'Rename': 'Renomear',\n'Rename Assignment': 'Renomear Lição',\n'Report A Problem': 'Reportar um Problema',\n'Request reset password': 'Pedir redefinição de senha',\n'Require a username to access this course': 'É necessário um usuário para acessar este curso',\n'Reset': 'Redefinir',\n'Reset an Exam': 'Redefinir um Exame',\n'Reset Password': 'Redefinir Senha',\n'Reset Password key': 'Redefinir chave de senha',\n'Reset Student Exam': 'Redefinir Exame de Estudante',\n'Response': 'Resposta',\n'Responses': 'Respostas',\n'Responses by Student': 'Respostas por Estudante',\n'Role': 'Papel',\n'Roles': 'Papéis',\n'Rows in Table': 'Rows in Table',\n'Rows selected': 'Rows selected',\n'Runestone in social media:': 'Runestone nas redes sociais:',\n'Runestone News': 'Novidades Runestone',\n'Save': 'Salvar',\n'Save and Add': 'Salvar e Adicionar',\n'Score': 'Pontuação',\n'Score Me': 'Avalie-me',\n'Scratch Activecode': 'Escrever em Activecode',\n'Search': 'Busca',\n'Search Question Bank': 'Procurar em Banco de Questões',\n'Select a Course': 'Selecionar Curso',\n'Select All': 'Selecionar Todos',\n'Select Assessment to Reset': 'Selecione Avaliação para Redefinir',\n'Select Chapter': 'Selecione o Capítulo',\n'Select Question': 'Selecionar Questão',\n'Select Student to Reset': 'Selecione Estudante para Redefinir',\n'Select Student(s) for Action': 'Selecione Estudante(s) para Ação',\n'Select the course you want to copy assignments from.': 'Selecione o curso de qual você quer copiar lições.',\n'Select the problems which compose this assignment.': 'Selecione os problemas que vão compor esta lição.',\n'Select: Chapter or Assignment': 'Selecione: Capítulo ou Lição',\n'Set the course start date': 'Defina a data de início do curso',\n'Show as Timed Assessment': 'Mostrar como Avaliação Temporizada',\n'Show Secret': 'Mostrar Secret',\n'Sign Up': 'Cadastre-se',\n'Simulation Results': 'Resultados da Simulação',\n'Size of cache:': 'Tamanho do cache:',\n'Started Section': 'Iniciaram a Seção',\n'state': 'estado',\n'Statistics': 'Estatísticas',\n'Student': 'Estudante',\n'Student Activity Summary': 'Resumo da Atividade dos Estudantes',\n'Student Progress': 'Progresso dos Estudantes',\n'Student Progress for': 'Progresso do Estudante para',\n'Student Report': 'Relatório do Estudante',\n\"Student's Score\": 'Pontuação do Estudante',\n'Students': 'Estudantes',\n'Students Online': 'Estudantes Online',\n'Students who were': 'Estudantes que',\n'Subchapter': 'Subcapítulo',\n'submit': 'Enviar',\n'Submit': 'Enviar',\n'Table': 'Tabela',\n'Table of Contents': 'Sumário',\n'Term Start Date': 'Data de Início do Termo',\n'Term start date': 'Data de início do Termo',\n'Terms of Service': 'Termos de Serviço',\n'The \"query\" is a condition like \"db.table1.field1==\\'value\\'\". Something like \"db.table1.field1==db.table2.field2\" results in a SQL JOIN.': 'The \"query\" is a condition like \"db.table1.field1==\\'value\\'\". Something like \"db.table1.field1==db.table2.field2\" results in a SQL JOIN.',\n'This action CANNOT BE UNDONE': 'Esta ação NÃO PODE SER DESFEITA',\n'This action cannot be undone': 'Esta ação não pode ser desfeita',\n'This allows you set the start date for the current term of your course.': 'Isso permite que você configure a data de início do termo atual de seu curso.',\n'This code was emailed to you and is required for login.': 'Este código foi enviado para você por e-mail e é necessário para login.',\n'This email already has an account': 'Este e-mail já está registrado',\n'This page shows students who have loaded a page in the last 15 minutes. Refresh the page to update.': 'Esta página mostra estudantes que carregaram uma página nos últimos 15 minutos. Refresque a página para atualizar.',\n'This will delete all sections under this course. Students will not be able to access course materials.': 'Isso deletará todas as seções sob este curso. Estudantes não poderão acessar os materiais do curso.',\n'Time': 'Tempo',\n'Time in Cache (h:m:s)': 'Tempo no Cache (h:m:s)',\n'Time Limit': 'Tempo Limite',\n'Timed': 'Temporizado',\n'Timed Exam Analysis': 'Análise de Exames Temporizados',\n'Timestamp': 'Timestamp',\n'To launch lti on Runestone use': 'Para acionar o lti no Runestone use',\n'Total': 'Total',\n'Traceback': 'Traceback',\n'Two-step Login Authentication Code': 'Código de Autenticação de duas etapas',\n'unable to parse csv file': 'não foi possível processar o arquivo csv',\n'Unable to send email': 'Não foi possível enviar o e-mail',\n'UName': 'Usuário',\n'Update:': 'Atualizar:',\n'Upload a csv file with the following format to automatically register your students.': 'Faça o upload de um arquivo csv com o seguinte formato para registrar automaticamente seus estudantes.',\n'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.',\n'Use Python3 print function and true division': 'Use Python3 print function and true division',\n'Use this to make quizzes or exams': 'Use para fazer quizzes ou provas',\n'User': 'Usuário',\n'User %(id)s is impersonating %(other_id)s': 'User %(id)s is impersonating %(other_id)s',\n'User %(id)s Logged-in': 'User %(id)s Logged-in',\n'User %(id)s Logged-out': 'User %(id)s Logged-out',\n'User %(id)s Password changed': 'User %(id)s Password changed',\n'User %(id)s Password reset': 'User %(id)s Password reset',\n'User %(id)s Password retrieved': 'User %(id)s Password retrieved',\n'User %(id)s Profile updated': 'User %(id)s Profile updated',\n'User %(id)s Registered': 'User %(id)s Registered',\n'User %(id)s Username retrieved': 'User %(id)s Username retrieved',\n'User %(id)s Verification email sent': 'User %(id)s Verification email sent',\n'User %(id)s verified registration key': 'User %(id)s verified registration key',\n'User ID': 'User ID',\n'User id': 'User id',\n'Username': 'Usuário',\n'Username already taken': 'Usuário já foi registrado',\n'Username retrieve': 'Recuperar usuário',\n'Username:': 'Usuário:',\n'Users': 'Usuários',\n'Verify Password': 'Verificar Senha',\n'View': 'Ver',\n'View Individual Student Progression': 'Ver Progresso Individual',\n'Visible to Students': 'Visível para Estudantes',\n'Warning': 'Aviso',\n'Welcome %(username)s! Click on the link %(link)s to verify your email': 'Bem-vindo %(username)s! Clique no link %(link)s para verificar seu e-mail',\n'Welcome to CourseWare Manager': 'Welcome to CourseWare Manager',\n'Which to grade': 'Qual avaliar',\n'Write': 'Escrever',\n'You are writing in ': 'Você está escrevendo em',\n'You can make the file in your favorite Spreadsheet app and then export it to a CSV file to upload here. Please export without headers.': 'Você pode criar o arquivo na sua aplicação de planilhas favorita e exportar em CSV para fazer upload aqui. Por favor, exporte sem o cabeçalho',\n'You can resubmit the file after your corrections.': 'Você pode enviar novamente após as correções.',\n'You cannot remove yourself as an instructor.': 'Você não pode se remover como instrutor.',\n'You have been invited to join %(site)s, click %(link)s to complete the process': 'You have been invited to join %(site)s, click %(link)s to complete the process',\n'You have successfully removed students': 'Você removeu estudantes com sucesso',\n'You will not see them in the grading interface or gradebook anymore, but no data is lost.': 'Você não os verá mais na interface de avaliação, mas nenhum dado foi perdido.',\n'Your CSV file has the following problems:': 'Seu arquivo CSV possui os seguintes problemas:',\n'Your password is: %(password)s': 'Sua senha é: %(password)s',\n'Your temporary login code is {0}': 'Seu código de login temporário é {0}',\n'Your username is: %(username)s': 'Seu usuário é: %(username)s',\n'Your username was emailed to you': 'Seu usuário foi enviado por e-mail',\n}\n" } ]
2
veekaybee/wired
https://github.com/veekaybee/wired
f0de8dda88cb12c7301cee2c8b05c5e583a4ab23
e4b332403f98728c59acbb46536bdc5e972e967b
0f7b81ed6660d7444a752ecef3b6fe80ffb6557c
refs/heads/master
2021-01-10T02:01:15.162511
2016-04-07T01:11:35
2016-04-07T01:11:35
55,652,753
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6864607930183411, "alphanum_fraction": 0.7102137804031372, "avg_line_length": 22.38888931274414, "blob_id": "7a9114aab8737041db4323959b492568d1097b06", "content_id": "39655baacf6ef922c3098930db48d9533993c252", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 421, "license_type": "no_license", "max_line_length": 67, "num_lines": 18, "path": "/wired.py", "repo_name": "veekaybee/wired", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport urllib2\nfrom bs4 import BeautifulSoup\nimport re\n\naddress = \"http://www.wired.com/2015/10/how-to-switch-android-ios/\"\n\nresponse = urllib2.urlopen(address)\nsoup = BeautifulSoup(response,\"lxml\")\nparagraphs = soup.find('article').find_all('p')\n\nfor paragraph in paragraphs:\n\tprint paragraph.text\n\n# with open('article.txt', 'w') as article:\n# \tfor line in text:\n# \t\tarticle.write(str(line))\n" } ]
1
almasakchabayev/_project_coupon
https://github.com/almasakchabayev/_project_coupon
e20694e5c0c2949d5c1fe2deb4aeace4d431f985
3b6e16528ba686359318721e2435a5044d979b1a
8dc59154e84c75ced019f23cca148649fbcc0916
refs/heads/master
2016-09-06T19:47:50.070227
2014-12-25T17:47:03
2014-12-25T17:47:03
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5963855385780334, "alphanum_fraction": 0.5963855385780334, "avg_line_length": 30.461538314819336, "blob_id": "23553ab5ff4b9652369ae74b7bb6190a24b79620", "content_id": "f22dacf85f7cfaecbee8e1535090ec497c0574d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 830, "license_type": "no_license", "max_line_length": 135, "num_lines": 26, "path": "/spiders/coupon_spider.py", "repo_name": "almasakchabayev/_project_coupon", "src_encoding": "UTF-8", "text": "import scrapy\nfrom scrapy.selector import Selector\nfrom scrapy.http import Request\n\n\nclass MySpider(scrapy.Spider):\n name = \"coupon\"\n allowed_domains = [\n 'chocolife.me',\n ]\n start_urls = [\n 'http://www.chocolife.me/',\n ]\n\n def parse(self, response):\n selector = Selector(response)\n category_urls = selector.xpath('//div[@id=\"b-deals__menunav__nav\"]/ul[@class=\"b-deals__menunav__select\"]/li/a/@href').extract()\n for url in category_urls:\n if 'chocolife' in url:\n yield Request(url, callback=self.parse_deal)\n else:\n yield Request('http://www.chocolife.me' + url, callback=self.parse_deal)\n\n def parse_deal(self, response):\n selector = Selector(response)\n print selector.xpath('//html').extract()\n\n\n\n \n" } ]
1
microsoft/MLOS
https://github.com/microsoft/MLOS
66968fd0e00df9a3d819ce5287dc057585b2bd8c
0db80043dad256d77dc4c2b4fc54aa0b0aa2597f
0aaba744749d86e0ed7b0cb088707857de0e6d82
refs/heads/main
2023-08-19T02:10:54.290106
2023-08-18T20:29:48
2023-08-18T20:29:48
253,620,591
109
50
MIT
2020-04-06T21:33:40
2023-09-11T22:54:34
2023-09-14T18:52:13
Python
[ { "alpha_fraction": 0.6180052161216736, "alphanum_fraction": 0.6180052161216736, "avg_line_length": 39.816566467285156, "blob_id": "e09783377a2806f057ab5485b0b983144ff85b79", "content_id": "68a1d444b8877d12bc716b3ef2595eaa2354aa4e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6898, "license_type": "permissive", "max_line_length": 115, "num_lines": 169, "path": "/mlos_bench/mlos_bench/environments/local/local_fileshare_env.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nScheduler-side Environment to run scripts locally\nand upload/download data to the shared storage.\n\"\"\"\n\nimport logging\n\nfrom datetime import datetime\nfrom string import Template\nfrom typing import Any, Dict, List, Generator, Iterable, Mapping, Optional, Tuple\n\nfrom mlos_bench.services.base_service import Service\nfrom mlos_bench.services.types.local_exec_type import SupportsLocalExec\nfrom mlos_bench.services.types.fileshare_type import SupportsFileShareOps\nfrom mlos_bench.environments.status import Status\nfrom mlos_bench.environments.local.local_env import LocalEnv\nfrom mlos_bench.tunables.tunable import TunableValue\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\n\n_LOG = logging.getLogger(__name__)\n\n\nclass LocalFileShareEnv(LocalEnv):\n \"\"\"\n Scheduler-side Environment that runs scripts locally\n and uploads/downloads data to the shared file storage.\n \"\"\"\n\n def __init__(self,\n *,\n name: str,\n config: dict,\n global_config: Optional[dict] = None,\n tunables: Optional[TunableGroups] = None,\n service: Optional[Service] = None):\n \"\"\"\n Create a new application environment with a given config.\n\n Parameters\n ----------\n name: str\n Human-readable name of the environment.\n config : dict\n Free-format dictionary that contains the benchmark environment\n configuration. Each config must have at least the \"tunable_params\"\n and the \"const_args\" sections.\n `LocalFileShareEnv` must also have at least some of the following\n parameters: {setup, upload, run, download, teardown,\n dump_params_file, read_results_file}\n global_config : dict\n Free-format dictionary of global parameters (e.g., security credentials)\n to be mixed in into the \"const_args\" section of the local config.\n tunables : TunableGroups\n A collection of tunable parameters for *all* environments.\n service: Service\n An optional service object (e.g., providing methods to\n deploy or reboot a VM, etc.).\n \"\"\"\n super().__init__(name=name, config=config, global_config=global_config, tunables=tunables, service=service)\n\n assert self._service is not None and isinstance(self._service, SupportsLocalExec), \\\n \"LocalEnv requires a service that supports local execution\"\n self._local_exec_service: SupportsLocalExec = self._service\n\n assert self._service is not None and isinstance(self._service, SupportsFileShareOps), \\\n \"LocalEnv requires a service that supports file upload/download operations\"\n self._file_share_service: SupportsFileShareOps = self._service\n\n self._upload = self._template_from_to(\"upload\")\n self._download = self._template_from_to(\"download\")\n\n def _template_from_to(self, config_key: str) -> List[Tuple[Template, Template]]:\n \"\"\"\n Convert a list of {\"from\": \"...\", \"to\": \"...\"} to a list of pairs\n of string.Template objects so that we can plug in self._params into it later.\n \"\"\"\n return [\n (Template(d['from']), Template(d['to']))\n for d in self.config.get(config_key, [])\n ]\n\n @staticmethod\n def _expand(from_to: Iterable[Tuple[Template, Template]],\n params: Mapping[str, TunableValue]) -> Generator[Tuple[str, str], None, None]:\n \"\"\"\n Substitute $var parameters in from/to path templates.\n Return a generator of (str, str) pairs of paths.\n \"\"\"\n return (\n (path_from.safe_substitute(params), path_to.safe_substitute(params))\n for (path_from, path_to) in from_to\n )\n\n def setup(self, tunables: TunableGroups, global_config: Optional[dict] = None) -> bool:\n \"\"\"\n Run setup scripts locally and upload the scripts and data to the shared storage.\n\n Parameters\n ----------\n tunables : TunableGroups\n A collection of tunable OS and application parameters along with their\n values. In a local environment these could be used to prepare a config\n file on the scheduler prior to transferring it to the remote environment,\n for instance.\n global_config : dict\n Free-format dictionary of global parameters of the environment\n that are not used in the optimization process.\n\n Returns\n -------\n is_success : bool\n True if operation is successful, false otherwise.\n \"\"\"\n self._is_ready = super().setup(tunables, global_config)\n if self._is_ready:\n assert self._temp_dir is not None\n params = self._get_env_params()\n params[\"PWD\"] = self._temp_dir\n for (path_from, path_to) in self._expand(self._upload, params):\n self._file_share_service.upload(self._config_loader_service.resolve_path(\n path_from, extra_paths=[self._temp_dir]), path_to)\n return self._is_ready\n\n def _download_files(self, ignore_missing: bool = False) -> None:\n \"\"\"\n Download files from the shared storage.\n\n Parameters\n ----------\n ignore_missing : bool\n If True, raise an exception when some file cannot be downloaded.\n If False, proceed with downloading other files and log a warning.\n \"\"\"\n assert self._temp_dir is not None\n params = self._get_env_params()\n params[\"PWD\"] = self._temp_dir\n for (path_from, path_to) in self._expand(self._download, params):\n try:\n self._file_share_service.download(\n path_from, self._config_loader_service.resolve_path(\n path_to, extra_paths=[self._temp_dir]))\n except FileNotFoundError as ex:\n _LOG.warning(\"Cannot download: %s\", path_from)\n if not ignore_missing:\n raise ex\n\n def run(self) -> Tuple[Status, Optional[Dict[str, float]]]:\n \"\"\"\n Download benchmark results from the shared storage\n and run post-processing scripts locally.\n\n Returns\n -------\n (status, output) : (Status, dict)\n A pair of (Status, output) values, where `output` is a dict\n with the results or None if the status is not COMPLETED.\n If run script is a benchmark, then the score is usually expected to\n be in the `score` field.\n \"\"\"\n self._download_files()\n return super().run()\n\n def status(self) -> Tuple[Status, List[Tuple[datetime, str, Any]]]:\n self._download_files(ignore_missing=True)\n return super().status()\n" }, { "alpha_fraction": 0.7639424800872803, "alphanum_fraction": 0.7646439671516418, "avg_line_length": 48.155174255371094, "blob_id": "190e8f11e0edc50b3887ea7a28dde0dc67cb9067", "content_id": "c6fb5670f0f2968eff9d5bbfedade424a1df9db0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2851, "license_type": "permissive", "max_line_length": 101, "num_lines": 58, "path": "/mlos_bench/mlos_bench/tests/tunables/tunable_group_indexing_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTests for checking the indexing rules for tunable groups.\n\"\"\"\n\nfrom mlos_bench.tunables.tunable import Tunable\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\n\n\ndef test_tunable_group_indexing(tunable_groups: TunableGroups, tunable_categorical: Tunable) -> None:\n \"\"\"\n Check that various types of indexing work for the tunable group.\n \"\"\"\n # Check that the \"in\" operator works.\n assert tunable_categorical in tunable_groups\n assert tunable_categorical.name in tunable_groups\n\n # NOTE: we reassign the tunable_categorical here since they come from\n # different fixtures so are technically different objects.\n (tunable_categorical, covariant_group) = tunable_groups.get_tunable(tunable_categorical.name)\n assert tunable_groups.get_tunable(tunable_categorical)[0] == tunable_categorical\n\n assert tunable_categorical in covariant_group\n assert tunable_categorical.name in covariant_group\n\n # Check that we can lookup that tunable by name or tunable object in the covariant group.\n assert covariant_group.get_tunable(tunable_categorical) == tunable_categorical\n assert covariant_group.get_tunable(tunable_categorical.name) == tunable_categorical\n\n # Reset the value on the tunable using the tunable.\n tunable_categorical.value = tunable_categorical.default\n\n # Check that we can index by name or tunable object.\n assert tunable_groups[tunable_categorical] == tunable_categorical.value\n assert tunable_groups[tunable_categorical.name] == tunable_categorical.value\n assert covariant_group[tunable_categorical] == tunable_categorical.value\n assert covariant_group[tunable_categorical.name] == tunable_categorical.value\n\n # Check that we can assign a new value by index.\n new_value = [x for x in tunable_categorical.categories if x != tunable_categorical.value][0]\n tunable_groups[tunable_categorical] = new_value\n assert tunable_groups[tunable_categorical] == new_value\n assert tunable_groups[tunable_categorical.name] == new_value\n assert covariant_group[tunable_categorical] == new_value\n assert covariant_group[tunable_categorical.name] == new_value\n assert tunable_categorical.value == new_value\n assert tunable_categorical.value != tunable_categorical.default\n\n # Check that we can assign a new value by name.\n tunable_groups[tunable_categorical] = tunable_categorical.default\n assert tunable_categorical.value == tunable_categorical.default\n assert tunable_groups[tunable_categorical] == tunable_categorical.value\n assert tunable_groups[tunable_categorical.name] == tunable_categorical.value\n assert covariant_group[tunable_categorical] == tunable_categorical.value\n assert covariant_group[tunable_categorical.name] == tunable_categorical.value\n" }, { "alpha_fraction": 0.6721274852752686, "alphanum_fraction": 0.6721274852752686, "avg_line_length": 18.373912811279297, "blob_id": "3181057d547c07b692db4eb5db42da2b0f1c4e39", "content_id": "7526eb9ffb93ae3a440221480cad949fac7db33d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 4456, "license_type": "permissive", "max_line_length": 295, "num_lines": 230, "path": "/doc/source/overview.rst", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#############################\nmlos-core API\n#############################\n\nThis is a list of major functions and classes provided by `mlos_core`.\n\n.. currentmodule:: mlos_core\n\nOptimizers\n==========\n.. currentmodule:: mlos_core.optimizers\n.. autosummary::\n :toctree: generated/\n\n :template: class.rst\n\n OptimizerType\n OptimizerFactory\n\n :template: function.rst\n\n OptimizerFactory.create\n\n.. currentmodule:: mlos_core.optimizers.optimizer\n.. autosummary::\n :toctree: generated/\n :template: class.rst\n\n BaseOptimizer\n\n.. currentmodule:: mlos_core.optimizers.random_optimizer\n.. autosummary::\n :toctree: generated/\n :template: class.rst\n\n RandomOptimizer\n\n.. currentmodule:: mlos_core.optimizers.flaml_optimizer\n.. autosummary::\n :toctree: generated/\n :template: class.rst\n\n FlamlOptimizer\n\n.. currentmodule:: mlos_core.optimizers.bayesian_optimizers\n.. autosummary::\n :toctree: generated/\n :template: class.rst\n\n BaseBayesianOptimizer\n SmacOptimizer\n\nSpaces\n======\n\nConverters\n----------\n.. currentmodule:: mlos_core.spaces.converters.flaml\n.. autosummary::\n :toctree: generated/\n :template: function.rst\n\n configspace_to_flaml_space\n\nSpace Adapters\n--------------\n.. currentmodule:: mlos_core.spaces.adapters\n.. autosummary::\n :toctree: generated/\n\n :template: class.rst\n\n SpaceAdapterType\n SpaceAdapterFactory\n\n :template: function.rst\n\n SpaceAdapterFactory.create\n\n.. currentmodule:: mlos_core.spaces.adapters.adapter\n.. autosummary::\n :toctree: generated/\n :template: class.rst\n\n BaseSpaceAdapter\n\n.. currentmodule:: mlos_core.spaces.adapters.identity_adapter\n.. autosummary::\n :toctree: generated/\n :template: class.rst\n\n IdentityAdapter\n\n.. currentmodule:: mlos_core.spaces.adapters.llamatune\n.. autosummary::\n :toctree: generated/\n :template: class.rst\n\n LlamaTuneAdapter\n\n#############################\nmlos-bench API\n#############################\n\nThis is a list of major functions and classes provided by `mlos_bench`.\n\n.. currentmodule:: mlos_bench\n\nMain\n====\n\n:doc:`run.py </api/mlos_bench/mlos_bench.run>`\n\n The script to run the benchmarks or the optimization loop.\n\n Also available as `mlos_bench` command line tool.\n\n.. note::\n The are `json config examples <https://github.com/microsoft/MLOS/tree/main/mlos_bench/mlos_bench/config/>`_ and `json schemas <https://github.com/microsoft/MLOS/tree/main/mlos_bench/mlos_bench/config/schemas/>`_ on the main `source code <https://github.com/microsoft/MLOS>`_ repository site.\n\nBenchmark Environments\n======================\n.. currentmodule:: mlos_bench.environments\n.. autosummary::\n :toctree: generated/\n :template: class.rst\n\n Status\n Environment\n CompositeEnv\n MockEnv\n\nLocal Environments\n-------------------\n\n.. currentmodule:: mlos_bench.environments.local\n.. autosummary::\n :toctree: generated/\n :template: class.rst\n\n LocalEnv\n LocalFileShareEnv\n\nRemote Environments\n-------------------\n\n.. currentmodule:: mlos_bench.environments.remote\n.. autosummary::\n :toctree: generated/\n :template: class.rst\n\n RemoteEnv\n OSEnv\n VMEnv\n\nTunable Parameters\n==================\n.. currentmodule:: mlos_bench.tunables\n.. autosummary::\n :toctree: generated/\n :template: class.rst\n\n Tunable\n TunableGroups\n\nService Mix-ins\n===============\n.. currentmodule:: mlos_bench.services\n.. autosummary::\n :toctree: generated/\n :template: class.rst\n\n Service\n FileShareService\n\n.. currentmodule:: mlos_bench.services.config_persistence\n.. autosummary::\n :toctree: generated/\n :template: class.rst\n\n ConfigPersistenceService\n\nLocal Services\n---------------\n.. currentmodule:: mlos_bench.services.local\n.. autosummary::\n :toctree: generated/\n :template: class.rst\n\n LocalExecService\n\nRemote Azure Services\n---------------------\n\n.. currentmodule:: mlos_bench.services.remote.azure\n.. autosummary::\n :toctree: generated/\n :template: class.rst\n\n AzureVMService\n AzureFileShareService\n\nOptimizer Adapters\n==================\n.. currentmodule:: mlos_bench.optimizers\n.. autosummary::\n :toctree: generated/\n :template: class.rst\n\n Optimizer\n MockOptimizer\n MlosCoreOptimizer\n\nStorage\n=======\n.. currentmodule:: mlos_bench.storage\n.. autosummary::\n :toctree: generated/\n :template: class.rst\n\n Storage\n\nSQL DB Storage\n--------------\n.. currentmodule:: mlos_bench.storage.sql.storage\n.. autosummary::\n :toctree: generated/\n :template: class.rst\n\n SqlStorage\n" }, { "alpha_fraction": 0.6674225330352783, "alphanum_fraction": 0.67044597864151, "avg_line_length": 30.5, "blob_id": "41e9d8167de094afb9a2a3794a511d2d69c0d528", "content_id": "9929d5d18137c2aa932ce2832cfbb24d243fcdac", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1323, "license_type": "permissive", "max_line_length": 96, "num_lines": 42, "path": "/mlos_bench/mlos_bench/optimizers/one_shot_optimizer.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nNo-op optimizer for mlos_bench that proposes a single configuration.\n\"\"\"\n\nimport logging\nfrom typing import Optional\n\nfrom mlos_bench.services.base_service import Service\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\nfrom mlos_bench.optimizers.mock_optimizer import MockOptimizer\n\n_LOG = logging.getLogger(__name__)\n\n\nclass OneShotOptimizer(MockOptimizer):\n \"\"\"\n Mock optimizer that proposes a single configuration and returns.\n Explicit configs (partial or full) are possible using configuration files.\n \"\"\"\n\n # TODO: Add support for multiple explicit configs (i.e., FewShot or Manual Optimizer) - #344\n\n def __init__(self,\n tunables: TunableGroups,\n config: dict,\n global_config: Optional[dict] = None,\n service: Optional[Service] = None):\n super().__init__(tunables, config, global_config, service)\n _LOG.info(\"Run a single iteration for: %s\", self._tunables)\n self._max_iter = 1 # Always run for just one iteration.\n\n @property\n def supports_preload(self) -> bool:\n return False\n\n def suggest(self) -> TunableGroups:\n _LOG.info(\"Suggest: %s\", self._tunables)\n return self._tunables.copy()\n" }, { "alpha_fraction": 0.6066498160362244, "alphanum_fraction": 0.6066498160362244, "avg_line_length": 38.86390686035156, "blob_id": "5441f6773edb9580db2444ec6b23e32f83810968", "content_id": "73c4ad3bb8817f24301aca475e6d6629f508a779", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6737, "license_type": "permissive", "max_line_length": 93, "num_lines": 169, "path": "/mlos_bench/mlos_bench/environments/remote/remote_env.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nRemotely executed benchmark/script environment.\n\"\"\"\n\nimport logging\nfrom typing import Dict, Iterable, Optional, Tuple\n\nfrom mlos_bench.environments.status import Status\nfrom mlos_bench.environments.script_env import ScriptEnv\nfrom mlos_bench.services.base_service import Service\nfrom mlos_bench.services.types.remote_exec_type import SupportsRemoteExec\nfrom mlos_bench.services.types.vm_provisioner_type import SupportsVMOps\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\n\n_LOG = logging.getLogger(__name__)\n\n\nclass RemoteEnv(ScriptEnv):\n \"\"\"\n Environment to run benchmarks and scripts on a remote host.\n \"\"\"\n\n def __init__(self,\n *,\n name: str,\n config: dict,\n global_config: Optional[dict] = None,\n tunables: Optional[TunableGroups] = None,\n service: Optional[Service] = None):\n \"\"\"\n Create a new environment for remote execution.\n\n Parameters\n ----------\n name: str\n Human-readable name of the environment.\n config : dict\n Free-format dictionary that contains the benchmark environment\n configuration. Each config must have at least the \"tunable_params\"\n and the \"const_args\" sections.\n `RemoteEnv` must also have at least some of the following parameters:\n {setup, run, teardown, wait_boot}\n global_config : dict\n Free-format dictionary of global parameters (e.g., security credentials)\n to be mixed in into the \"const_args\" section of the local config.\n tunables : TunableGroups\n A collection of tunable parameters for *all* environments.\n service: Service\n An optional service object (e.g., providing methods to\n deploy or reboot a VM, etc.).\n \"\"\"\n super().__init__(name=name, config=config, global_config=global_config,\n tunables=tunables, service=service)\n\n self._wait_boot = self.config.get(\"wait_boot\", False)\n\n assert self._service is not None and isinstance(self._service, SupportsRemoteExec), \\\n \"RemoteEnv requires a service that supports remote execution operations\"\n self._remote_exec_service: SupportsRemoteExec = self._service\n\n # TODO: Refactor this as \"host\" and \"os\" operations to accommodate SSH service.\n assert self._service is not None and isinstance(self._service, SupportsVMOps), \\\n \"RemoteEnv requires a service that supports host operations\"\n self._host_service: SupportsVMOps = self._service\n\n def setup(self, tunables: TunableGroups, global_config: Optional[dict] = None) -> bool:\n \"\"\"\n Check if the environment is ready and set up the application\n and benchmarks on a remote host.\n\n Parameters\n ----------\n tunables : TunableGroups\n A collection of tunable OS and application parameters along with their\n values. Setting these parameters should not require an OS reboot.\n global_config : dict\n Free-format dictionary of global parameters of the environment\n that are not used in the optimization process.\n\n Returns\n -------\n is_success : bool\n True if operation is successful, false otherwise.\n \"\"\"\n if not super().setup(tunables, global_config):\n return False\n\n if self._wait_boot:\n _LOG.info(\"Wait for the remote environment to start: %s\", self)\n (status, params) = self._host_service.vm_start(self._params)\n if status.is_pending():\n (status, _) = self._host_service.wait_vm_operation(params)\n if not status.is_succeeded():\n return False\n\n if self._script_setup:\n _LOG.info(\"Set up the remote environment: %s\", self)\n (status, _) = self._remote_exec(self._script_setup)\n _LOG.info(\"Remote set up complete: %s :: %s\", self, status)\n self._is_ready = status.is_succeeded()\n else:\n self._is_ready = True\n\n return self._is_ready\n\n def run(self) -> Tuple[Status, Optional[Dict[str, float]]]:\n \"\"\"\n Runs the run script on the remote environment.\n\n This can be used to, for instance, submit a new experiment to the\n remote application environment by (re)configuring an application and\n launching the benchmark, or run a script that collects the results.\n\n Returns\n -------\n (status, output) : (Status, dict)\n A pair of (Status, output) values, where `output` is a dict\n with the results or None if the status is not COMPLETED.\n If run script is a benchmark, then the score is usually expected to\n be in the `score` field.\n \"\"\"\n _LOG.info(\"Run script remotely on: %s\", self)\n (status, _) = result = super().run()\n if not (status.is_ready() and self._script_run):\n return result\n\n result = self._remote_exec(self._script_run)\n _LOG.info(\"Remote run complete: %s :: %s\", self, result)\n return result\n\n def teardown(self) -> None:\n \"\"\"\n Clean up and shut down the remote environment.\n \"\"\"\n if self._script_teardown:\n _LOG.info(\"Remote teardown: %s\", self)\n (status, _) = self._remote_exec(self._script_teardown)\n _LOG.info(\"Remote teardown complete: %s :: %s\", self, status)\n super().teardown()\n\n def _remote_exec(self, script: Iterable[str]) -> Tuple[Status, Optional[dict]]:\n \"\"\"\n Run a script on the remote host.\n\n Parameters\n ----------\n script : [str]\n List of commands to be executed on the remote host.\n\n Returns\n -------\n result : (Status, dict)\n A pair of Status and dict with the benchmark/script results.\n Status is one of {PENDING, SUCCEEDED, FAILED, TIMED_OUT}\n \"\"\"\n env_params = self._get_env_params()\n _LOG.debug(\"Submit script: %s with %s\", self, env_params)\n (status, output) = self._remote_exec_service.remote_exec(\n script, config=self._params, env_params=env_params)\n _LOG.debug(\"Script submitted: %s %s :: %s\", self, status, output)\n if status in {Status.PENDING, Status.SUCCEEDED}:\n (status, output) = self._remote_exec_service.get_remote_exec_results(output)\n # TODO: extract the results from `output`.\n _LOG.debug(\"Status: %s :: %s\", status, output)\n return (status, output)\n" }, { "alpha_fraction": 0.6636155843734741, "alphanum_fraction": 0.6676201224327087, "avg_line_length": 30.781818389892578, "blob_id": "78aa0fc07830e9486ec64fdf4f970781874d80c0", "content_id": "60bd1ce33370890e96d385f069892ef0c55b6c97", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1748, "license_type": "permissive", "max_line_length": 117, "num_lines": 55, "path": "/.devcontainer/build/build-devcontainer-cli.sh", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#!/bin/bash\n##\n## Copyright (c) Microsoft Corporation.\n## Licensed under the MIT License.\n##\n\nset -x\n\nset -eu\nscriptdir=$(dirname \"$(readlink -f \"$0\")\")\ncd \"$scriptdir/\"\n\n# Build the helper container that has the devcontainer CLI for building the devcontainer.\n\nif [ ! -w /var/run/docker.sock ]; then\n echo \"ERROR: $USER does not have write access to /var/run/docker.sock. Please add $USER to the docker group.\" >&2\n exit 1\nfi\nDOCKER_GID=$(stat -c'%g' /var/run/docker.sock)\n# Make this work inside a devcontainer as well.\nif [ -w /var/run/docker-host.sock ]; then\n DOCKER_GID=$(stat -c'%g' /var/run/docker-host.sock)\nfi\n\nexport DOCKER_BUILDKIT=${DOCKER_BUILDKIT:-1}\ndevcontainer_cli_build_args=''\nif docker buildx version 2>/dev/null; then\n devcontainer_cli_build_args+=' --progress=plain'\nelse\n echo 'NOTE: docker buildkit unavailable.' >&2\nfi\n\nif [ \"${NO_CACHE:-}\" == 'true' ]; then\n devcontainer_cli_build_args+=' --no-cache --pull'\nelse\n cacheFrom='mloscore.azurecr.io/devcontainer-cli:latest'\n tmpdir=$(mktemp -d)\n devcontainer_cli_build_args+=\" --cache-from $cacheFrom\"\n docker --config=\"$tmpdir\" pull \"$cacheFrom\" || true\n rmdir \"$tmpdir\"\nfi\n\ndocker build -t devcontainer-cli:latest -t cspell:latest -t markdown-link-check:latest \\\n $devcontainer_cli_build_args \\\n --build-arg BUILDKIT_INLINE_CACHE=1 \\\n --build-arg NODE_UID=$(id -u) \\\n --build-arg NODE_GID=$(id -g) \\\n --build-arg DOCKER_GID=$DOCKER_GID \\\n --build-arg http_proxy=${http_proxy:-} \\\n --build-arg https_proxy=${https_proxy:-} \\\n --build-arg no_proxy=${no_proxy:-} \\\n -f Dockerfile .\nif [ \"${CONTAINER_REGISTRY:-}\" != '' ]; then\n docker tag devcontainer-cli:latest \"$CONTAINER_REGISTRY/devcontainer-cli:latest\"\nfi\n" }, { "alpha_fraction": 0.6832225322723389, "alphanum_fraction": 0.6851779222488403, "avg_line_length": 30.182926177978516, "blob_id": "64a1ba6247bf571f0b73f563d69ce4c4ec177f1e", "content_id": "760503eb2e451d19bd51d149fcccbb9fcdb37431", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2557, "license_type": "permissive", "max_line_length": 104, "num_lines": 82, "path": "/mlos_core/mlos_core/spaces/adapters/__init__.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nBasic initializer module for the mlos_core space adapters.\n\"\"\"\n\nfrom enum import Enum\nfrom typing import Optional, TypeVar\n\nimport ConfigSpace\n\nfrom mlos_core.spaces.adapters.identity_adapter import IdentityAdapter\nfrom mlos_core.spaces.adapters.llamatune import LlamaTuneAdapter\n\n__all__ = [\n 'IdentityAdapter',\n 'LlamaTuneAdapter',\n]\n\n\nclass SpaceAdapterType(Enum):\n \"\"\"Enumerate supported MlosCore space adapters.\"\"\"\n\n IDENTITY = IdentityAdapter\n \"\"\"A no-op adapter will be used\"\"\"\n\n LLAMATUNE = LlamaTuneAdapter\n \"\"\"An instance of LlamaTuneAdapter class will be used\"\"\"\n\n\n# To make mypy happy, we need to define a type variable for each optimizer type.\n# https://github.com/python/mypy/issues/12952\n# ConcreteSpaceAdapter = TypeVar('ConcreteSpaceAdapter', *[member.value for member in SpaceAdapterType])\n# To address this, we add a test for complete coverage of the enum.\nConcreteSpaceAdapter = TypeVar(\n 'ConcreteSpaceAdapter',\n IdentityAdapter,\n LlamaTuneAdapter,\n)\n\n\nclass SpaceAdapterFactory:\n \"\"\"Simple factory class for creating BaseSpaceAdapter-derived objects\"\"\"\n\n # pylint: disable=too-few-public-methods\n\n @staticmethod\n def create(*,\n parameter_space: ConfigSpace.ConfigurationSpace,\n space_adapter_type: SpaceAdapterType = SpaceAdapterType.IDENTITY,\n space_adapter_kwargs: Optional[dict] = None) -> ConcreteSpaceAdapter:\n \"\"\"\n Create a new space adapter instance, given the parameter space and potential\n space adapter options.\n\n Parameters\n ----------\n parameter_space : ConfigSpace.ConfigurationSpace\n Input configuration space.\n space_adapter_type : Optional[SpaceAdapterType]\n Space adapter class to be used alongside the optimizer.\n space_adapter_kwargs : Optional[dict]\n Optional arguments passed in SpaceAdapter class constructor.\n\n Returns\n -------\n space_adapter : ConcreteSpaceAdapter\n Instance of concrete space adapter (e.g., None, LlamaTuneAdapter, etc.)\n \"\"\"\n if space_adapter_type is None:\n space_adapter_type = SpaceAdapterType.IDENTITY\n if space_adapter_kwargs is None:\n space_adapter_kwargs = {}\n\n space_adapter: ConcreteSpaceAdapter = space_adapter_type.value(\n orig_parameter_space=parameter_space,\n **space_adapter_kwargs\n )\n\n return space_adapter\n" }, { "alpha_fraction": 0.7482014298439026, "alphanum_fraction": 0.7482014298439026, "avg_line_length": 22.16666603088379, "blob_id": "af47c16e3f12c5798855d61a2f51360d286ff582", "content_id": "1971c0179968d121d1426eb2285a950238b05f98", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 417, "license_type": "permissive", "max_line_length": 78, "num_lines": 18, "path": "/mlos_bench/mlos_bench/tests/services/__init__.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTests for mlos_bench.services.\nUsed to make mypy happy about multiple conftest.py modules.\n\"\"\"\n\nfrom .local import MockLocalExecService\nfrom .remote import MockFileShareService, MockRemoteExecService, MockVMService\n\n__all__ = [\n 'MockLocalExecService',\n 'MockFileShareService',\n 'MockRemoteExecService',\n 'MockVMService',\n]\n" }, { "alpha_fraction": 0.5971602201461792, "alphanum_fraction": 0.5973387956619263, "avg_line_length": 35.59477233886719, "blob_id": "98cfbd1a53a8e473d9d70463be28d99bd6acac09", "content_id": "247d76fd508a2d6aa8a5e863b064ecded5bd7974", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11198, "license_type": "permissive", "max_line_length": 119, "num_lines": 306, "path": "/mlos_bench/mlos_bench/tunables/tunable_groups.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTunableGroups definition.\n\"\"\"\nimport copy\n\nfrom typing import Dict, Generator, Iterable, Mapping, Optional, Tuple, Union\n\nfrom mlos_bench.tunables.tunable import Tunable, TunableValue\nfrom mlos_bench.tunables.covariant_group import CovariantTunableGroup\n\n\nclass TunableGroups:\n \"\"\"\n A collection of covariant groups of tunable parameters.\n \"\"\"\n\n def __init__(self, config: Optional[dict] = None):\n \"\"\"\n Create a new group of tunable parameters.\n\n Parameters\n ----------\n config : dict\n Python dict of serialized representation of the covariant tunable groups.\n \"\"\"\n if config is None:\n config = {}\n self._index: Dict[str, CovariantTunableGroup] = {} # Index (Tunable id -> CovariantTunableGroup)\n self._tunable_groups: Dict[str, CovariantTunableGroup] = {}\n for (name, group_config) in config.items():\n self._add_group(CovariantTunableGroup(name, group_config))\n\n def __eq__(self, other: object) -> bool:\n \"\"\"\n Check if two TunableGroups are equal.\n\n Parameters\n ----------\n other : TunableGroups\n A tunable groups object to compare to.\n\n Returns\n -------\n is_equal : bool\n True if two TunableGroups are equal.\n \"\"\"\n if not isinstance(other, TunableGroups):\n return False\n return bool(self._tunable_groups == other._tunable_groups)\n\n def copy(self) -> \"TunableGroups\":\n \"\"\"\n Deep copy of the TunableGroups object.\n\n Returns\n -------\n tunables : TunableGroups\n A new instance of the TunableGroups object\n that is a deep copy of the original one.\n \"\"\"\n return copy.deepcopy(self)\n\n def _add_group(self, group: CovariantTunableGroup) -> None:\n \"\"\"\n Add a CovariantTunableGroup to the current collection.\n\n Note: non-overlapping groups are expected to be added to the collection.\n\n Parameters\n ----------\n group : CovariantTunableGroup\n \"\"\"\n assert group.name not in self._tunable_groups, f\"Duplicate covariant tunable group name {group.name} in {self}\"\n self._tunable_groups[group.name] = group\n for tunable in group.get_tunables():\n if tunable.name in self._index:\n raise ValueError(f\"Duplicate Tunable {tunable.name} from group {group.name} in {self}\")\n self._index[tunable.name] = group\n\n def merge(self, tunables: \"TunableGroups\") -> \"TunableGroups\":\n \"\"\"\n Merge the two collections of covariant tunable groups.\n\n Unlike the dict `update` method, this method does not modify the\n original when overlapping keys are found.\n It is expected be used to merge the tunable groups referenced by a\n standalone Environment config into a parent CompositeEnvironment,\n for instance.\n This allows self contained, potentially overlapping, but also\n overridable configs to be composed together.\n\n Parameters\n ----------\n tunables : TunableGroups\n A collection of covariant tunable groups.\n\n Returns\n -------\n self : TunableGroups\n Self-reference for chaining.\n \"\"\"\n # pylint: disable=protected-access\n # Check that covariant groups are unique, else throw an error.\n for group in tunables._tunable_groups.values():\n if group.name not in self._tunable_groups:\n self._add_group(group)\n else:\n # Check that there's no overlap in the tunables.\n # But allow for differing current values.\n if not self._tunable_groups[group.name].equals_defaults(group):\n raise ValueError(f\"Overlapping covariant tunable group name {group.name} \" +\n \"in {self._tunable_groups[group.name]} and {tunables}\")\n return self\n\n def __repr__(self) -> str:\n \"\"\"\n Produce a human-readable version of the TunableGroups (mostly for logging).\n\n Returns\n -------\n string : str\n A human-readable version of the TunableGroups.\n \"\"\"\n return \"{ \" + \", \".join(\n f\"{group.name}::{tunable}\"\n for group in sorted(self._tunable_groups.values(), key=lambda g: (-g.cost, g.name))\n for tunable in sorted(group._tunables.values())) + \" }\"\n\n def __contains__(self, tunable: Union[str, Tunable]) -> bool:\n \"\"\"\n Checks if the given name/tunable is in this tunable group.\n \"\"\"\n name: str = tunable.name if isinstance(tunable, Tunable) else tunable\n return name in self._index\n\n def __getitem__(self, tunable: Union[str, Tunable]) -> TunableValue:\n \"\"\"\n Get the current value of a single tunable parameter.\n \"\"\"\n name: str = tunable.name if isinstance(tunable, Tunable) else tunable\n return self._index[name][name]\n\n def __setitem__(self, tunable: Union[str, Tunable], tunable_value: Union[TunableValue, Tunable]) -> TunableValue:\n \"\"\"\n Update the current value of a single tunable parameter.\n \"\"\"\n # Use double index to make sure we set the is_updated flag of the group\n name: str = tunable.name if isinstance(tunable, Tunable) else tunable\n value: TunableValue = tunable_value.value if isinstance(tunable_value, Tunable) else tunable_value\n self._index[name][name] = value\n return self._index[name][name]\n\n def __iter__(self) -> Generator[Tuple[Tunable, CovariantTunableGroup], None, None]:\n \"\"\"\n An iterator over all tunables in the group.\n\n Returns\n -------\n [(tunable, group), ...] : iter(Tunable, CovariantTunableGroup)\n An iterator over all tunables in all groups. Each element is a 2-tuple\n of an instance of the Tunable parameter and covariant group it belongs to.\n \"\"\"\n return ((group.get_tunable(name), group) for (name, group) in self._index.items())\n\n def get_tunable(self, tunable: Union[str, Tunable]) -> Tuple[Tunable, CovariantTunableGroup]:\n \"\"\"\n Access the entire Tunable (not just its value) and its covariant group.\n Throw KeyError if the tunable is not found.\n\n Parameters\n ----------\n tunable : Union[str, Tunable]\n Name of the tunable parameter.\n\n Returns\n -------\n (tunable, group) : (Tunable, CovariantTunableGroup)\n A 2-tuple of an instance of the Tunable parameter and covariant group it belongs to.\n \"\"\"\n name: str = tunable.name if isinstance(tunable, Tunable) else tunable\n group = self._index[name]\n return (group.get_tunable(name), group)\n\n def get_covariant_group_names(self) -> Iterable[str]:\n \"\"\"\n Get the names of all covariance groups in the collection.\n\n Returns\n -------\n group_names : [str]\n IDs of the covariant tunable groups.\n \"\"\"\n return self._tunable_groups.keys()\n\n def subgroup(self, group_names: Iterable[str]) -> \"TunableGroups\":\n \"\"\"\n Select the covariance groups from the current set and create a new\n TunableGroups object that consists of those covariance groups.\n\n Note: The new TunableGroup will include *references* (not copies) to\n original ones, so each will get updated together.\n This is often desirable to support the use case of multiple related\n Environments (e.g. Local vs Remote) using the same set of tunables\n within a CompositeEnvironment.\n\n Parameters\n ----------\n group_names : list of str\n IDs of the covariant tunable groups.\n\n Returns\n -------\n tunables : TunableGroups\n A collection of covariant tunable groups.\n \"\"\"\n # pylint: disable=protected-access\n tunables = TunableGroups()\n for name in group_names:\n if name not in self._tunable_groups:\n raise KeyError(f\"Unknown covariant group name '{name}' in tunable group {self}\")\n tunables._add_group(self._tunable_groups[name])\n return tunables\n\n def get_param_values(self, group_names: Optional[Iterable[str]] = None,\n into_params: Optional[Dict[str, TunableValue]] = None) -> Dict[str, TunableValue]:\n \"\"\"\n Get the current values of the tunables that belong to the specified covariance groups.\n\n Parameters\n ----------\n group_names : list of str or None\n IDs of the covariant tunable groups.\n Select parameters from all groups if omitted.\n into_params : dict\n An optional dict to copy the parameters and their values into.\n\n Returns\n -------\n into_params : dict\n Flat dict of all parameters and their values from given covariance groups.\n \"\"\"\n if group_names is None:\n group_names = self.get_covariant_group_names()\n if into_params is None:\n into_params = {}\n for name in group_names:\n into_params.update(self._tunable_groups[name].get_tunable_values_dict())\n return into_params\n\n def is_updated(self, group_names: Optional[Iterable[str]] = None) -> bool:\n \"\"\"\n Check if any of the given covariant tunable groups has been updated.\n\n Parameters\n ----------\n group_names : list of str or None\n IDs of the (covariant) tunable groups. Check all groups if omitted.\n\n Returns\n -------\n is_updated : bool\n True if any of the specified tunable groups has been updated, False otherwise.\n \"\"\"\n return any(self._tunable_groups[name].is_updated()\n for name in (group_names or self.get_covariant_group_names()))\n\n def reset(self, group_names: Optional[Iterable[str]] = None) -> \"TunableGroups\":\n \"\"\"\n Clear the update flag of given covariant groups.\n\n Parameters\n ----------\n group_names : list of str or None\n IDs of the (covariant) tunable groups. Reset all groups if omitted.\n\n Returns\n -------\n self : TunableGroups\n Self-reference for chaining.\n \"\"\"\n for name in (group_names or self.get_covariant_group_names()):\n self._tunable_groups[name].reset_is_updated()\n return self\n\n def assign(self, param_values: Mapping[str, TunableValue]) -> \"TunableGroups\":\n \"\"\"\n In-place update the values of the tunables from the dictionary\n of (key, value) pairs.\n\n Parameters\n ----------\n param_values : Mapping[str, TunableValue]\n Dictionary mapping Tunable parameter names to new values.\n\n Returns\n -------\n self : TunableGroups\n Self-reference for chaining.\n \"\"\"\n for key, value in param_values.items():\n self[key] = value\n return self\n" }, { "alpha_fraction": 0.699138879776001, "alphanum_fraction": 0.7034445405006409, "avg_line_length": 29.459016799926758, "blob_id": "7b00947c47799e43a2451d8889af8d649bea0d46", "content_id": "8a9fba6d86ecb79d23874aa420514b31720fc4e8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1858, "license_type": "permissive", "max_line_length": 96, "num_lines": 61, "path": "/mlos_bench/mlos_bench/tests/tunables/tunable_group_update_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTests for checking the is_updated flag for tunable groups.\n\"\"\"\n\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\n\n_TUNABLE_VALUES = {\n \"kernel_sched_migration_cost_ns\": 8888,\n \"kernel_sched_latency_ns\": 9999,\n}\n\n\ndef test_tunable_group_update(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Test that updating a tunable group raises the is_updated flag.\n \"\"\"\n tunable_groups.assign(_TUNABLE_VALUES)\n assert tunable_groups.is_updated()\n\n\ndef test_tunable_group_update_twice(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Test that updating a tunable group with the same values do *NOT* raises the is_updated flag.\n \"\"\"\n tunable_groups.assign(_TUNABLE_VALUES)\n assert tunable_groups.is_updated()\n\n tunable_groups.reset()\n assert not tunable_groups.is_updated()\n\n tunable_groups.assign(_TUNABLE_VALUES)\n assert not tunable_groups.is_updated()\n\n\ndef test_tunable_group_update_kernel(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Test that the is_updated flag is set only for the affected covariant group.\n \"\"\"\n tunable_groups.assign(_TUNABLE_VALUES)\n assert tunable_groups.is_updated()\n assert tunable_groups.is_updated([\"kernel\"])\n assert not tunable_groups.is_updated([\"boot\", \"provision\"])\n\n\ndef test_tunable_group_update_boot(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Test that the is_updated flag is set only for the affected covariant group.\n \"\"\"\n tunable_groups.assign(_TUNABLE_VALUES)\n assert tunable_groups.is_updated()\n assert not tunable_groups.is_updated([\"boot\"])\n\n tunable_groups.reset()\n tunable_groups[\"idle\"] = \"mwait\"\n assert tunable_groups.is_updated()\n assert tunable_groups.is_updated([\"boot\"])\n assert not tunable_groups.is_updated([\"kernel\"])\n" }, { "alpha_fraction": 0.6713157296180725, "alphanum_fraction": 0.6765249371528625, "avg_line_length": 38.67333221435547, "blob_id": "d7c67bdc3e0714a79b34e5319181d5515f2d839d", "content_id": "275a850333cb4b428506d33af1c6655794e3b76b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11902, "license_type": "permissive", "max_line_length": 132, "num_lines": 300, "path": "/mlos_core/mlos_core/tests/optimizers/optimizer_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTests for Bayesian Optimizers.\n\"\"\"\n\nfrom copy import deepcopy\nfrom typing import List, Optional, Type\n\nimport logging\nimport pytest\n\nimport pandas as pd\nimport numpy as np\nimport numpy.typing as npt\nimport ConfigSpace as CS\n\nfrom mlos_core.optimizers import (\n OptimizerType, ConcreteOptimizer, OptimizerFactory, BaseOptimizer)\n\nfrom mlos_core.optimizers.bayesian_optimizers import BaseBayesianOptimizer, SmacOptimizer\nfrom mlos_core.spaces.adapters import SpaceAdapterType\n\nfrom mlos_core.tests import get_all_concrete_subclasses\n\n\n_LOG = logging.getLogger(__name__)\n_LOG.setLevel(logging.DEBUG)\n\n\[email protected](('optimizer_class', 'kwargs'), [\n *[(member.value, {}) for member in OptimizerType],\n])\ndef test_create_optimizer_and_suggest(configuration_space: CS.ConfigurationSpace,\n optimizer_class: Type[BaseOptimizer], kwargs: Optional[dict]) -> None:\n \"\"\"\n Test that we can create an optimizer and get a suggestion from it.\n \"\"\"\n if kwargs is None:\n kwargs = {}\n optimizer = optimizer_class(parameter_space=configuration_space, **kwargs)\n assert optimizer is not None\n\n assert optimizer.parameter_space is not None\n\n suggestion = optimizer.suggest()\n assert suggestion is not None\n\n myrepr = repr(optimizer)\n assert myrepr.startswith(optimizer_class.__name__)\n\n # pending not implemented\n with pytest.raises(NotImplementedError):\n optimizer.register_pending(suggestion)\n\n\[email protected](('optimizer_class', 'kwargs'), [\n *[(member.value, {}) for member in OptimizerType],\n])\ndef test_basic_interface_toy_problem(configuration_space: CS.ConfigurationSpace,\n optimizer_class: Type[BaseOptimizer], kwargs: Optional[dict]) -> None:\n \"\"\"\n Toy problem to test the optimizers.\n \"\"\"\n max_iterations = 20\n if kwargs is None:\n kwargs = {}\n if optimizer_class == OptimizerType.SMAC.value:\n # SMAC sets the initial random samples as a percentage of the max iterations, which defaults to 100.\n # To avoid having to train more than 25 model iterations, we set a lower number of max iterations.\n kwargs['max_trials'] = max_iterations * 2\n\n def objective(x: pd.Series) -> npt.ArrayLike: # pylint: disable=invalid-name\n ret: npt.ArrayLike = (6 * x - 2)**2 * np.sin(12 * x - 4)\n return ret\n # Emukit doesn't allow specifying a random state, so we set the global seed.\n np.random.seed(42)\n optimizer = optimizer_class(parameter_space=configuration_space, **kwargs)\n\n with pytest.raises(ValueError, match=\"No observations\"):\n optimizer.get_best_observation()\n\n with pytest.raises(ValueError, match=\"No observations\"):\n optimizer.get_observations()\n\n for _ in range(max_iterations):\n suggestion = optimizer.suggest()\n assert isinstance(suggestion, pd.DataFrame)\n assert (suggestion.columns == ['x', 'y', 'z']).all()\n # check that suggestion is in the space\n configuration = CS.Configuration(optimizer.parameter_space, suggestion.iloc[0].to_dict())\n # Raises an error if outside of configuration space\n configuration.is_valid_configuration()\n observation = objective(suggestion['x'])\n assert isinstance(observation, pd.Series)\n optimizer.register(suggestion, observation)\n\n best_observation = optimizer.get_best_observation()\n assert isinstance(best_observation, pd.DataFrame)\n assert (best_observation.columns == ['x', 'y', 'z', 'score']).all()\n assert best_observation['score'].iloc[0] < -5\n\n all_observations = optimizer.get_observations()\n assert isinstance(all_observations, pd.DataFrame)\n assert all_observations.shape == (20, 4)\n assert (all_observations.columns == ['x', 'y', 'z', 'score']).all()\n\n # It would be better to put this into bayesian_optimizer_test but then we'd have to refit the model\n if isinstance(optimizer, BaseBayesianOptimizer):\n pred_best = optimizer.surrogate_predict(best_observation[['x', 'y', 'z']])\n assert pred_best.shape == (1,)\n\n pred_all = optimizer.surrogate_predict(all_observations[['x', 'y', 'z']])\n assert pred_all.shape == (20,)\n\n\[email protected](('optimizer_type'), [\n # Enumerate all supported Optimizers\n # *[member for member in OptimizerType],\n *list(OptimizerType),\n])\ndef test_concrete_optimizer_type(optimizer_type: OptimizerType) -> None:\n \"\"\"\n Test that all optimizer types are listed in the ConcreteOptimizer constraints.\n \"\"\"\n assert optimizer_type.value in ConcreteOptimizer.__constraints__ # type: ignore[attr-defined] # pylint: disable=no-member\n\n\[email protected](('optimizer_type', 'kwargs'), [\n # Default optimizer\n (None, {}),\n # Enumerate all supported Optimizers\n *[(member, {}) for member in OptimizerType],\n # Optimizer with non-empty kwargs argument\n])\ndef test_create_optimizer_with_factory_method(configuration_space: CS.ConfigurationSpace,\n optimizer_type: Optional[OptimizerType], kwargs: Optional[dict]) -> None:\n \"\"\"\n Test that we can create an optimizer via a factory.\n \"\"\"\n if kwargs is None:\n kwargs = {}\n if optimizer_type is None:\n optimizer = OptimizerFactory.create(\n parameter_space=configuration_space,\n optimizer_kwargs=kwargs,\n )\n else:\n optimizer = OptimizerFactory.create(\n parameter_space=configuration_space,\n optimizer_type=optimizer_type,\n optimizer_kwargs=kwargs,\n )\n assert optimizer is not None\n\n assert optimizer.parameter_space is not None\n\n suggestion = optimizer.suggest()\n assert suggestion is not None\n\n if optimizer_type is not None:\n myrepr = repr(optimizer)\n assert myrepr.startswith(optimizer_type.value.__name__)\n\n\[email protected](('optimizer_type', 'kwargs'), [\n # Enumerate all supported Optimizers\n *[(member, {}) for member in OptimizerType],\n # Optimizer with non-empty kwargs argument\n (OptimizerType.SMAC, {\n # Test with default config.\n 'use_default_config': True,\n # 'n_random_init': 10,\n }),\n])\ndef test_optimizer_with_llamatune(optimizer_type: OptimizerType, kwargs: Optional[dict]) -> None:\n \"\"\"\n Toy problem to test the optimizers with llamatune space adapter.\n \"\"\"\n # pylint: disable=too-complex\n # pylint: disable=too-many-statements\n # pylint: disable=too-many-locals\n num_iters = 50\n if kwargs is None:\n kwargs = {}\n\n def objective(point: pd.DataFrame) -> pd.Series:\n # Best value can be reached by tuning an 1-dimensional search space\n ret: pd.Series = np.sin(point['x'] * point['y'])\n assert ret.hasnans is False\n return ret\n\n input_space = CS.ConfigurationSpace(seed=1234)\n # Add two continuous inputs\n input_space.add_hyperparameter(CS.UniformFloatHyperparameter(name='x', lower=0, upper=3))\n input_space.add_hyperparameter(CS.UniformFloatHyperparameter(name='y', lower=0, upper=3))\n\n # Initialize an optimizer that uses LlamaTune space adapter\n space_adapter_kwargs = {\n \"num_low_dims\": 1,\n \"special_param_values\": None,\n \"max_unique_values_per_param\": None,\n }\n\n # Make some adjustments to the kwargs for the optimizer and LlamaTuned\n # optimizer for debug/testing.\n\n # if optimizer_type == OptimizerType.SMAC:\n # # Allow us to override the number of random init samples.\n # kwargs['max_ratio'] = 1.0\n optimizer_kwargs = deepcopy(kwargs)\n llamatune_optimizer_kwargs = deepcopy(kwargs)\n # if optimizer_type == OptimizerType.SMAC:\n # optimizer_kwargs['n_random_init'] = 20\n # llamatune_optimizer_kwargs['n_random_init'] = 10\n\n llamatune_optimizer: BaseOptimizer = OptimizerFactory.create(\n parameter_space=input_space,\n optimizer_type=optimizer_type,\n optimizer_kwargs=llamatune_optimizer_kwargs,\n space_adapter_type=SpaceAdapterType.LLAMATUNE,\n space_adapter_kwargs=space_adapter_kwargs,\n )\n # Initialize an optimizer that uses the original space\n optimizer: BaseOptimizer = OptimizerFactory.create(\n parameter_space=input_space,\n optimizer_type=optimizer_type,\n optimizer_kwargs=optimizer_kwargs,\n )\n assert optimizer is not None\n assert llamatune_optimizer is not None\n assert optimizer.optimizer_parameter_space != llamatune_optimizer.optimizer_parameter_space\n\n llamatune_n_random_init = 0\n opt_n_random_init = int(kwargs.get('n_random_init', 0))\n if optimizer_type == OptimizerType.SMAC:\n assert isinstance(optimizer, SmacOptimizer)\n assert isinstance(llamatune_optimizer, SmacOptimizer)\n opt_n_random_init = optimizer.n_random_init\n llamatune_n_random_init = llamatune_optimizer.n_random_init\n\n for i in range(num_iters):\n # Place to set a breakpoint for when the optimizer is done with random init.\n if llamatune_n_random_init and i > llamatune_n_random_init:\n _LOG.debug(\"LlamaTuned Optimizer is done with random init.\")\n if opt_n_random_init and i >= opt_n_random_init:\n _LOG.debug(\"Optimizer is done with random init.\")\n\n # loop for optimizer\n suggestion = optimizer.suggest()\n observation = objective(suggestion)\n optimizer.register(suggestion, observation)\n\n # loop for llamatune-optimizer\n suggestion = llamatune_optimizer.suggest()\n _x, _y = suggestion['x'].iloc[0], suggestion['y'].iloc[0]\n assert _x == pytest.approx(_y, rel=1e-3) or _x + _y == pytest.approx(3., rel=1e-3) # optimizer explores 1-dimensional space\n observation = objective(suggestion)\n llamatune_optimizer.register(suggestion, observation)\n\n # Retrieve best observations\n best_observation = optimizer.get_best_observation()\n llamatune_best_observation = llamatune_optimizer.get_best_observation()\n\n for best_obv in (best_observation, llamatune_best_observation):\n assert isinstance(best_obv, pd.DataFrame)\n assert (best_obv.columns == ['x', 'y', 'score']).all()\n\n # LlamaTune's optimizer score should better (i.e., lower) than plain optimizer's one, or close to that\n assert best_observation['score'].iloc[0] > llamatune_best_observation['score'].iloc[0] or \\\n best_observation['score'].iloc[0] + 1e-3 > llamatune_best_observation['score'].iloc[0]\n\n # Retrieve and check all observations\n for all_obvs in (optimizer.get_observations(), llamatune_optimizer.get_observations()):\n assert isinstance(all_obvs, pd.DataFrame)\n assert all_obvs.shape == (num_iters, 3)\n assert (all_obvs.columns == ['x', 'y', 'score']).all()\n\n # .surrogate_predict method not currently implemented if space adapter is employed\n if isinstance(llamatune_optimizer, BaseBayesianOptimizer):\n with pytest.raises(NotImplementedError):\n llamatune_optimizer.surrogate_predict(llamatune_best_observation[['x', 'y']])\n\n\n# Dynamically determine all of the optimizers we have implemented.\n# Note: these must be sorted.\noptimizer_subclasses: List[Type[BaseOptimizer]] = get_all_concrete_subclasses(BaseOptimizer, # type: ignore[type-abstract]\n pkg_name='mlos_core')\nassert optimizer_subclasses\n\n\[email protected](('optimizer_class'), optimizer_subclasses)\ndef test_optimizer_type_defs(optimizer_class: Type[BaseOptimizer]) -> None:\n \"\"\"\n Test that all optimizer classes are listed in the OptimizerType enum.\n \"\"\"\n optimizer_type_classes = {member.value for member in OptimizerType}\n assert optimizer_class in optimizer_type_classes\n" }, { "alpha_fraction": 0.46938255429267883, "alphanum_fraction": 0.47644156217575073, "avg_line_length": 42.22793960571289, "blob_id": "779de88f538cc354ff1d750152ef1a6c60dad3ae", "content_id": "fdf689d1aabe38e40a71bb77c06a4d40930e5f33", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11758, "license_type": "permissive", "max_line_length": 111, "num_lines": 272, "path": "/mlos_bench/mlos_bench/tests/environments/composite_env_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nUnit tests for composite environment.\n\"\"\"\n\nimport pytest\n\nfrom mlos_bench.environments.composite_env import CompositeEnv\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\nfrom mlos_bench.services.config_persistence import ConfigPersistenceService\n\n# pylint: disable=redefined-outer-name\n\n\[email protected]\ndef composite_env(tunable_groups: TunableGroups) -> CompositeEnv:\n \"\"\"\n Test fixture for CompositeEnv.\n \"\"\"\n return CompositeEnv(\n name=\"Composite Test Environment\",\n config={\n \"tunable_params\": [\"provision\", \"boot\"],\n \"const_args\": {\n \"vm_server_name\": \"Mock Server VM\",\n \"vm_client_name\": \"Mock Client VM\",\n \"someConst\": \"root\"\n },\n \"children\": [\n {\n \"name\": \"Mock Client Environment 1\",\n \"class\": \"mlos_bench.environments.mock_env.MockEnv\",\n \"config\": {\n \"tunable_params\": [\"provision\"],\n \"const_args\": {\n \"vmName\": \"$vm_client_name\",\n \"EnvId\": 1,\n },\n \"required_args\": [\"vmName\", \"someConst\"],\n \"range\": [60, 120],\n \"metrics\": [\"score\"],\n }\n },\n {\n \"name\": \"Mock Server Environment 2\",\n \"class\": \"mlos_bench.environments.mock_env.MockEnv\",\n \"config\": {\n \"tunable_params\": [\"boot\"],\n \"const_args\": {\n \"vmName\": \"$vm_server_name\",\n \"EnvId\": 2,\n },\n \"required_args\": [\"vmName\"],\n \"range\": [60, 120],\n \"metrics\": [\"score\"],\n }\n },\n {\n \"name\": \"Mock Control Environment 3\",\n \"class\": \"mlos_bench.environments.mock_env.MockEnv\",\n \"config\": {\n \"tunable_params\": [\"boot\"],\n \"const_args\": {\n \"vmName\": \"Mock Control VM\",\n \"EnvId\": 3,\n },\n \"required_args\": [\"vmName\", \"vm_server_name\", \"vm_client_name\"],\n \"range\": [60, 120],\n \"metrics\": [\"score\"],\n }\n }\n ]\n },\n tunables=tunable_groups,\n service=ConfigPersistenceService({}),\n )\n\n\ndef test_composite_env_params(composite_env: CompositeEnv) -> None:\n \"\"\"\n Check that the const_args from the parent environment get propagated to the children.\n NOTE: The current logic is that variables flow down via required_args and const_args, parent\n \"\"\"\n assert composite_env.children[0].parameters == {\n \"vmName\": \"Mock Client VM\", # const_args from the parent thru variable substitution\n \"EnvId\": 1, # const_args from the child\n \"vmSize\": \"Standard_B4ms\", # tunable_params from the parent\n \"someConst\": \"root\", # pulled in from parent via required_args\n }\n assert composite_env.children[1].parameters == {\n \"vmName\": \"Mock Server VM\", # const_args from the parent\n \"EnvId\": 2, # const_args from the child\n \"idle\": \"halt\", # tunable_params from the parent\n # \"someConst\": \"root\" # not required, so not passed from the parent\n }\n assert composite_env.children[2].parameters == {\n \"vmName\": \"Mock Control VM\", # const_args from the parent\n \"EnvId\": 3, # const_args from the child\n \"idle\": \"halt\", # tunable_params from the parent\n # \"someConst\": \"root\" # not required, so not passed from the parent\n \"vm_client_name\": \"Mock Client VM\",\n \"vm_server_name\": \"Mock Server VM\"\n }\n\n\ndef test_composite_env_setup(composite_env: CompositeEnv, tunable_groups: TunableGroups) -> None:\n \"\"\"\n Check that the child environments update their tunable parameters.\n \"\"\"\n tunable_groups.assign({\n \"vmSize\": \"Standard_B2s\",\n \"idle\": \"mwait\",\n \"kernel_sched_migration_cost_ns\": 100000,\n })\n\n with composite_env as env_context:\n assert env_context.setup(tunable_groups)\n\n assert composite_env.children[0].parameters == {\n \"vmName\": \"Mock Client VM\", # const_args from the parent\n \"EnvId\": 1, # const_args from the child\n \"vmSize\": \"Standard_B2s\", # tunable_params from the parent\n \"someConst\": \"root\", # pulled in from parent via required_args\n }\n assert composite_env.children[1].parameters == {\n \"vmName\": \"Mock Server VM\", # const_args from the parent\n \"EnvId\": 2, # const_args from the child\n \"idle\": \"mwait\", # tunable_params from the parent\n # \"someConst\": \"root\" # not required, so not passed from the parent\n }\n assert composite_env.children[2].parameters == {\n \"vmName\": \"Mock Control VM\", # const_args from the parent\n \"EnvId\": 3, # const_args from the child\n \"idle\": \"mwait\", # tunable_params from the parent\n \"vm_client_name\": \"Mock Client VM\",\n \"vm_server_name\": \"Mock Server VM\",\n }\n\n\[email protected]\ndef nested_composite_env(tunable_groups: TunableGroups) -> CompositeEnv:\n \"\"\"\n Test fixture for CompositeEnv.\n \"\"\"\n return CompositeEnv(\n name=\"Composite Test Environment\",\n config={\n \"tunable_params\": [\"provision\", \"boot\"],\n \"const_args\": {\n \"vm_server_name\": \"Mock Server VM\",\n \"vm_client_name\": \"Mock Client VM\",\n \"someConst\": \"root\"\n },\n \"children\": [\n {\n \"name\": \"Nested Composite Client Environment 1\",\n \"class\": \"mlos_bench.environments.composite_env.CompositeEnv\",\n \"config\": {\n \"tunable_params\": [\"provision\"],\n \"const_args\": {\n \"vmName\": \"$vm_client_name\",\n \"EnvId\": 1,\n },\n \"required_args\": [\"vmName\", \"EnvId\", \"someConst\", \"vm_server_name\"],\n \"children\": [\n {\n \"name\": \"Mock Client Environment 1\",\n \"class\": \"mlos_bench.environments.mock_env.MockEnv\",\n \"config\": {\n \"tunable_params\": [\"provision\"],\n # TODO: Might be nice to include a \"^\" or \"*\" option\n # here to indicate that all required_args from\n # the parent should be included here too in\n # order to reduce duplication.\n \"required_args\": [\"vmName\", \"EnvId\", \"someConst\", \"vm_server_name\"],\n \"range\": [60, 120],\n \"metrics\": [\"score\"],\n }\n },\n # ...\n ],\n },\n },\n {\n \"name\": \"Nested Composite Server Environment 2\",\n \"class\": \"mlos_bench.environments.composite_env.CompositeEnv\",\n \"config\": {\n \"tunable_params\": [\"boot\"],\n \"const_args\": {\n \"vmName\": \"$vm_server_name\",\n \"EnvId\": 2,\n },\n \"required_args\": [\"vmName\", \"EnvId\", \"vm_client_name\"],\n \"children\": [\n {\n \"name\": \"Mock Server Environment 2\",\n \"class\": \"mlos_bench.environments.mock_env.MockEnv\",\n \"config\": {\n \"tunable_params\": [\"boot\"],\n \"required_args\": [\"vmName\", \"EnvId\", \"vm_client_name\"],\n \"range\": [60, 120],\n \"metrics\": [\"score\"],\n }\n },\n # ...\n ],\n },\n },\n\n ]\n },\n tunables=tunable_groups,\n service=ConfigPersistenceService({}),\n )\n\n\ndef test_nested_composite_env_params(nested_composite_env: CompositeEnv) -> None:\n \"\"\"\n Check that the const_args from the parent environment get propagated to the children.\n NOTE: The current logic is that variables flow down via required_args and const_args, parent\n \"\"\"\n assert isinstance(nested_composite_env.children[0], CompositeEnv)\n assert nested_composite_env.children[0].children[0].parameters == {\n \"vmName\": \"Mock Client VM\", # const_args from the parent thru variable substitution\n \"EnvId\": 1, # const_args from the child\n \"vmSize\": \"Standard_B4ms\", # tunable_params from the parent\n \"someConst\": \"root\", # pulled in from parent via required_args\n \"vm_server_name\": \"Mock Server VM\",\n }\n assert isinstance(nested_composite_env.children[1], CompositeEnv)\n assert nested_composite_env.children[1].children[0].parameters == {\n \"vmName\": \"Mock Server VM\", # const_args from the parent\n \"EnvId\": 2, # const_args from the child\n \"idle\": \"halt\", # tunable_params from the parent\n # \"someConst\": \"root\" # not required, so not passed from the parent\n \"vm_client_name\": \"Mock Client VM\",\n }\n\n\ndef test_nested_composite_env_setup(nested_composite_env: CompositeEnv, tunable_groups: TunableGroups) -> None:\n \"\"\"\n Check that the child environments update their tunable parameters.\n \"\"\"\n tunable_groups.assign({\n \"vmSize\": \"Standard_B2s\",\n \"idle\": \"mwait\",\n \"kernel_sched_migration_cost_ns\": 100000,\n })\n\n with nested_composite_env as env_context:\n assert env_context.setup(tunable_groups)\n\n assert isinstance(nested_composite_env.children[0], CompositeEnv)\n assert nested_composite_env.children[0].children[0].parameters == {\n \"vmName\": \"Mock Client VM\", # const_args from the parent\n \"EnvId\": 1, # const_args from the child\n \"vmSize\": \"Standard_B2s\", # tunable_params from the parent\n \"someConst\": \"root\", # pulled in from parent via required_args\n \"vm_server_name\": \"Mock Server VM\",\n }\n\n assert isinstance(nested_composite_env.children[1], CompositeEnv)\n assert nested_composite_env.children[1].children[0].parameters == {\n \"vmName\": \"Mock Server VM\", # const_args from the parent\n \"EnvId\": 2, # const_args from the child\n \"idle\": \"mwait\", # tunable_params from the parent\n # \"someConst\": \"root\" # not required, so not passed from the parent\n \"vm_client_name\": \"Mock Client VM\",\n }\n" }, { "alpha_fraction": 0.6260977983474731, "alphanum_fraction": 0.6429494619369507, "avg_line_length": 44.04216766357422, "blob_id": "49939c6fe728a40d1440751cdfdf2f9eae29799c", "content_id": "661decc288a30378c1b5c7c3e40081360611e0d9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22431, "license_type": "permissive", "max_line_length": 129, "num_lines": 498, "path": "/mlos_core/mlos_core/tests/spaces/adapters/llamatune_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTests for LlamaTune space adapter.\n\"\"\"\n\n# pylint: disable=missing-function-docstring\n\nfrom typing import Any, Dict, Iterator, List, Set\n\nimport pytest\n\nimport ConfigSpace as CS\nimport pandas as pd\n\nfrom mlos_core.spaces.adapters import LlamaTuneAdapter\n\n\ndef construct_parameter_space(\n n_continuous_params: int = 0,\n n_integer_params: int = 0,\n n_categorical_params: int = 0,\n seed: int = 1234,\n) -> CS.ConfigurationSpace:\n \"\"\"\n Helper function for construct an instance of `ConfigSpace.ConfigurationSpace`.\n \"\"\"\n input_space = CS.ConfigurationSpace(seed=seed)\n\n for idx in range(n_continuous_params):\n input_space.add_hyperparameter(\n CS.UniformFloatHyperparameter(name=f'cont_{idx}', lower=0, upper=64))\n for idx in range(n_integer_params):\n input_space.add_hyperparameter(\n CS.UniformIntegerHyperparameter(name=f'int_{idx}', lower=-1, upper=256))\n for idx in range(n_categorical_params):\n input_space.add_hyperparameter(\n CS.CategoricalHyperparameter(name=f'str_{idx}', choices=[f'option_{idx}' for idx in range(5)]))\n\n return input_space\n\n\[email protected](('num_target_space_dims', 'param_space_kwargs'), ([\n (num_target_space_dims, param_space_kwargs)\n for num_target_space_dims in (2, 4)\n for num_orig_space_factor in (1.5, 4)\n for param_space_kwargs in (\n {'n_continuous_params': int(num_target_space_dims * num_orig_space_factor)},\n {'n_integer_params': int(num_target_space_dims * num_orig_space_factor)},\n {'n_categorical_params': int(num_target_space_dims * num_orig_space_factor)},\n # Mix of all three types\n {\n 'n_continuous_params': int(num_target_space_dims * num_orig_space_factor / 3),\n 'n_integer_params': int(num_target_space_dims * num_orig_space_factor / 3),\n 'n_categorical_params': int(num_target_space_dims * num_orig_space_factor / 3),\n },\n )\n]))\ndef test_num_low_dims(num_target_space_dims: int, param_space_kwargs: dict) -> None: # pylint: disable=too-many-locals\n \"\"\"\n Tests LlamaTune's low-to-high space projection method.\n \"\"\"\n input_space = construct_parameter_space(**param_space_kwargs)\n\n # Number of target parameter space dimensions should be fewer than those of the original space\n with pytest.raises(ValueError):\n LlamaTuneAdapter(\n orig_parameter_space=input_space,\n num_low_dims=len(list(input_space.keys()))\n )\n\n # Enable only low-dimensional space projections\n adapter = LlamaTuneAdapter(\n orig_parameter_space=input_space,\n num_low_dims=num_target_space_dims,\n special_param_values=None,\n max_unique_values_per_param=None\n )\n\n sampled_configs = adapter.target_parameter_space.sample_configuration(size=100)\n for sampled_config in sampled_configs: # pylint: disable=not-an-iterable # (false positive)\n # Transform low-dim config to high-dim point/config\n sampled_config_df = pd.DataFrame([sampled_config.values()], columns=list(sampled_config.keys()))\n orig_config_df = adapter.transform(sampled_config_df)\n\n # High-dim (i.e., original) config should be valid\n orig_config = CS.Configuration(input_space, values=orig_config_df.iloc[0].to_dict())\n input_space.check_configuration(orig_config)\n\n # Transform high-dim config back to low-dim\n target_config_df = adapter.inverse_transform(orig_config_df)\n\n # Sampled config and this should be the same\n target_config = CS.Configuration(adapter.target_parameter_space, values=target_config_df.iloc[0].to_dict())\n assert target_config == sampled_config\n\n # Try inverse projection (i.e., high-to-low) for previously unseen configs\n unseen_sampled_configs = adapter.target_parameter_space.sample_configuration(size=25)\n for unseen_sampled_config in unseen_sampled_configs: # pylint: disable=not-an-iterable # (false positive)\n if unseen_sampled_config in sampled_configs: # pylint: disable=unsupported-membership-test # (false positive)\n continue\n\n unseen_sampled_config_df = pd.DataFrame([unseen_sampled_config.values()], columns=list(unseen_sampled_config.keys()))\n with pytest.raises(ValueError):\n _ = adapter.inverse_transform(unseen_sampled_config_df) # pylint: disable=redefined-variable-type\n\n\ndef test_special_parameter_values_validation() -> None:\n \"\"\"\n Tests LlamaTune's validation process of user-provided special parameter values dictionary.\n \"\"\"\n input_space = CS.ConfigurationSpace(seed=1234)\n input_space.add_hyperparameter(\n CS.CategoricalHyperparameter(name='str', choices=[f'choice_{idx}' for idx in range(5)]))\n input_space.add_hyperparameter(\n CS.UniformFloatHyperparameter(name='cont', lower=-1, upper=100))\n input_space.add_hyperparameter(\n CS.UniformIntegerHyperparameter(name='int', lower=0, upper=100))\n\n # Only UniformIntegerHyperparameters are currently supported\n with pytest.raises(NotImplementedError):\n special_param_values_dict_1 = {'str': 'choice_1'}\n LlamaTuneAdapter(\n orig_parameter_space=input_space,\n num_low_dims=2,\n special_param_values=special_param_values_dict_1,\n max_unique_values_per_param=None,\n )\n\n with pytest.raises(NotImplementedError):\n special_param_values_dict_2 = {'cont': -1}\n LlamaTuneAdapter(\n orig_parameter_space=input_space,\n num_low_dims=2,\n special_param_values=special_param_values_dict_2,\n max_unique_values_per_param=None,\n )\n\n # Special value should belong to parameter value domain\n with pytest.raises(ValueError, match='value domain'):\n special_param_values_dict = {'int': -1}\n LlamaTuneAdapter(\n orig_parameter_space=input_space,\n num_low_dims=2,\n special_param_values=special_param_values_dict,\n max_unique_values_per_param=None,\n )\n\n # Invalid dicts; ValueError should be thrown\n invalid_special_param_values_dicts: List[Dict[str, Any]] = [\n {'int-Q': 0}, # parameter does not exist\n {'int': {0: 0.2}}, # invalid definition\n {'int': 0.2}, # invalid parameter value\n {'int': (0.4, 0)}, # (biasing %, special value) instead of (special value, biasing %)\n {'int': [0, 0]}, # duplicate special values\n {'int': []}, # empty list\n {'int': [{0: 0.2}]},\n {'int': [(0.4, 0), (1, 0.7)]}, # first tuple is inverted; second is correct\n {'int': [(0, 0.1), (0, 0.2)]}, # duplicate special values\n ]\n for spv_dict in invalid_special_param_values_dicts:\n with pytest.raises(ValueError):\n LlamaTuneAdapter(\n orig_parameter_space=input_space,\n num_low_dims=2,\n special_param_values=spv_dict,\n max_unique_values_per_param=None,\n )\n\n # Biasing percentage of special value(s) are invalid\n invalid_special_param_values_dicts = [\n {'int': (0, 1.1)}, # >1 probability\n {'int': (0, 0)}, # Zero probability\n {'int': (0, -0.1)}, # Negative probability\n {'int': (0, 20)}, # 2,000% instead of 20%\n {'int': [0, 1, 2, 3, 4, 5]}, # default biasing is 20%; 6 values * 20% > 100%\n {'int': [(0, 0.4), (1, 0.7)]}, # combined probability >100%\n {'int': [(0, -0.4), (1, 0.7)]}, # probability for value 0 is invalid.\n ]\n\n for spv_dict in invalid_special_param_values_dicts:\n with pytest.raises(ValueError):\n LlamaTuneAdapter(\n orig_parameter_space=input_space,\n num_low_dims=2,\n special_param_values=spv_dict,\n max_unique_values_per_param=None,\n )\n\n\ndef gen_random_configs(adapter: LlamaTuneAdapter, num_configs: int) -> Iterator[CS.Configuration]:\n for sampled_config in adapter.target_parameter_space.sample_configuration(size=num_configs):\n # Transform low-dim config to high-dim config\n sampled_config_df = pd.DataFrame([sampled_config.values()], columns=list(sampled_config.keys()))\n orig_config_df = adapter.transform(sampled_config_df)\n orig_config = CS.Configuration(adapter.orig_parameter_space, values=orig_config_df.iloc[0].to_dict())\n yield orig_config\n\n\ndef test_special_parameter_values_biasing() -> None: # pylint: disable=too-complex\n \"\"\"\n Tests LlamaTune's special parameter values biasing methodology\n \"\"\"\n input_space = CS.ConfigurationSpace(seed=1234)\n input_space.add_hyperparameter(\n CS.UniformIntegerHyperparameter(name='int_1', lower=0, upper=100))\n input_space.add_hyperparameter(\n CS.UniformIntegerHyperparameter(name='int_2', lower=0, upper=100))\n\n num_configs = 400\n bias_percentage = LlamaTuneAdapter.DEFAULT_SPECIAL_PARAM_VALUE_BIASING_PERCENTAGE\n eps = 0.2\n\n # Single parameter; single special value\n special_param_value_dicts: List[Dict[str, Any]] = [\n {'int_1': 0},\n {'int_1': (0, bias_percentage)},\n {'int_1': [0]},\n {'int_1': [(0, bias_percentage)]}\n ]\n\n for spv_dict in special_param_value_dicts:\n adapter = LlamaTuneAdapter(\n orig_parameter_space=input_space,\n num_low_dims=1,\n special_param_values=spv_dict,\n max_unique_values_per_param=None,\n )\n\n special_value_occurrences = sum(\n 1 for config in gen_random_configs(adapter, num_configs) if config['int_1'] == 0)\n assert (1 - eps) * int(num_configs * bias_percentage) <= special_value_occurrences\n\n # Single parameter; multiple special values\n special_param_value_dicts = [\n {'int_1': [0, 1]},\n {'int_1': [(0, bias_percentage), (1, bias_percentage)]}\n ]\n\n for spv_dict in special_param_value_dicts:\n adapter = LlamaTuneAdapter(\n orig_parameter_space=input_space,\n num_low_dims=1,\n special_param_values=spv_dict,\n max_unique_values_per_param=None,\n )\n\n special_values_occurrences = {0: 0, 1: 0}\n for config in gen_random_configs(adapter, num_configs):\n if config['int_1'] == 0:\n special_values_occurrences[0] += 1\n elif config['int_1'] == 1:\n special_values_occurrences[1] += 1\n\n assert (1 - eps) * int(num_configs * bias_percentage) <= special_values_occurrences[0]\n assert (1 - eps) * int(num_configs * bias_percentage) <= special_values_occurrences[1]\n\n # Multiple parameters; multiple special values; different biasing percentage\n spv_dict = {\n 'int_1': [(0, bias_percentage), (1, bias_percentage / 2)],\n 'int_2': [(2, bias_percentage / 2), (100, bias_percentage * 1.5)]\n }\n adapter = LlamaTuneAdapter(\n orig_parameter_space=input_space,\n num_low_dims=1,\n special_param_values=spv_dict,\n max_unique_values_per_param=None,\n )\n\n special_values_instances: Dict[str, Dict[int, int]] = {\n 'int_1': {0: 0, 1: 0},\n 'int_2': {2: 0, 100: 0},\n }\n for config in gen_random_configs(adapter, num_configs):\n if config['int_1'] == 0:\n special_values_instances['int_1'][0] += 1\n elif config['int_1'] == 1:\n special_values_instances['int_1'][1] += 1\n\n if config['int_2'] == 2:\n special_values_instances['int_2'][2] += 1\n elif config['int_2'] == 100:\n special_values_instances['int_2'][100] += 1\n\n assert (1 - eps) * int(num_configs * bias_percentage) <= special_values_instances['int_1'][0]\n assert (1 - eps) * int(num_configs * bias_percentage / 2) <= special_values_instances['int_1'][1]\n assert (1 - eps) * int(num_configs * bias_percentage / 2) <= special_values_instances['int_2'][2]\n assert (1 - eps) * int(num_configs * bias_percentage * 1.5) <= special_values_instances['int_2'][100]\n\n\ndef test_max_unique_values_per_param() -> None:\n \"\"\"\n Tests LlamaTune's parameter values discretization implementation.\n \"\"\"\n # Define config space with a mix of different parameter types\n input_space = CS.ConfigurationSpace(seed=1234)\n input_space.add_hyperparameter(\n CS.UniformFloatHyperparameter(name='cont_1', lower=0, upper=5))\n input_space.add_hyperparameter(\n CS.UniformFloatHyperparameter(name='cont_2', lower=1, upper=100))\n input_space.add_hyperparameter(\n CS.UniformIntegerHyperparameter(name='int_1', lower=1, upper=10))\n input_space.add_hyperparameter(\n CS.UniformIntegerHyperparameter(name='int_2', lower=0, upper=2048))\n input_space.add_hyperparameter(\n CS.CategoricalHyperparameter(name='str_1', choices=['on', 'off']))\n input_space.add_hyperparameter(\n CS.CategoricalHyperparameter(name='str_2', choices=[f'choice_{idx}' for idx in range(10)]))\n\n # Restrict the number of unique parameter values\n num_configs = 200\n for max_unique_values_per_param in (5, 25, 100):\n adapter = LlamaTuneAdapter(\n orig_parameter_space=input_space,\n num_low_dims=3,\n special_param_values=None,\n max_unique_values_per_param=max_unique_values_per_param,\n )\n\n # Keep track of unique values generated for each parameter\n unique_values_dict: Dict[str, set] = {param: set() for param in list(input_space.keys())}\n for config in gen_random_configs(adapter, num_configs):\n for param, value in config.items():\n unique_values_dict[param].add(value)\n\n # Ensure that their number is less than the maximum number allowed\n for _, unique_values in unique_values_dict.items():\n assert len(unique_values) <= max_unique_values_per_param\n\n\[email protected](('num_target_space_dims', 'param_space_kwargs'), ([\n (num_target_space_dims, param_space_kwargs)\n for num_target_space_dims in (2, 4)\n for num_orig_space_factor in (1.5, 4)\n for param_space_kwargs in (\n {'n_continuous_params': int(num_target_space_dims * num_orig_space_factor)},\n {'n_integer_params': int(num_target_space_dims * num_orig_space_factor)},\n {'n_categorical_params': int(num_target_space_dims * num_orig_space_factor)},\n # Mix of all three types\n {\n 'n_continuous_params': int(num_target_space_dims * num_orig_space_factor / 3),\n 'n_integer_params': int(num_target_space_dims * num_orig_space_factor / 3),\n 'n_categorical_params': int(num_target_space_dims * num_orig_space_factor / 3),\n },\n )\n]))\ndef test_approx_inverse_mapping(num_target_space_dims: int, param_space_kwargs: dict) -> None: # pylint: disable=too-many-locals\n \"\"\"\n Tests LlamaTune's approximate high-to-low space projection method, using pseudo-inverse.\n \"\"\"\n input_space = construct_parameter_space(**param_space_kwargs)\n\n # Enable low-dimensional space projection, but disable reverse mapping\n adapter = LlamaTuneAdapter(\n orig_parameter_space=input_space,\n num_low_dims=num_target_space_dims,\n special_param_values=None,\n max_unique_values_per_param=None,\n use_approximate_reverse_mapping=False,\n )\n\n sampled_config = input_space.sample_configuration() # size=1)\n with pytest.raises(ValueError):\n sampled_config_df = pd.DataFrame([sampled_config.values()], columns=list(sampled_config.keys()))\n _ = adapter.inverse_transform(sampled_config_df)\n\n # Enable low-dimensional space projection *and* reverse mapping\n adapter = LlamaTuneAdapter(\n orig_parameter_space=input_space,\n num_low_dims=num_target_space_dims,\n special_param_values=None,\n max_unique_values_per_param=None,\n use_approximate_reverse_mapping=True,\n )\n\n # Warning should be printed the first time\n sampled_config = input_space.sample_configuration() # size=1)\n with pytest.warns(UserWarning):\n sampled_config_df = pd.DataFrame([sampled_config.values()], columns=list(sampled_config.keys()))\n target_config_df = adapter.inverse_transform(sampled_config_df)\n # Low-dim (i.e., target) config should be valid\n target_config = CS.Configuration(adapter.target_parameter_space, values=target_config_df.iloc[0].to_dict())\n adapter.target_parameter_space.check_configuration(target_config)\n\n # Test inverse transform with 100 random configs\n for _ in range(100):\n sampled_config = input_space.sample_configuration() # size=1)\n sampled_config_df = pd.DataFrame([sampled_config.values()], columns=list(sampled_config.keys()))\n target_config_df = adapter.inverse_transform(sampled_config_df)\n # Low-dim (i.e., target) config should be valid\n target_config = CS.Configuration(adapter.target_parameter_space, values=target_config_df.iloc[0].to_dict())\n adapter.target_parameter_space.check_configuration(target_config)\n\n\[email protected](('num_low_dims', 'special_param_values', 'max_unique_values_per_param'), ([\n (num_low_dims, special_param_values, max_unique_values_per_param)\n for num_low_dims in (8, 16)\n for special_param_values in (\n {'int_1': -1, 'int_2': -1, 'int_3': -1, 'int_4': [-1, 0]},\n {'int_1': (-1, 0.1), 'int_2': -1, 'int_3': (-1, 0.3), 'int_4': [(-1, 0.1), (0, 0.2)]},\n )\n for max_unique_values_per_param in (50, 250)\n]))\ndef test_llamatune_pipeline(num_low_dims: int, special_param_values: dict, max_unique_values_per_param: int) -> None:\n \"\"\"\n Tests LlamaTune space adapter when all components are active.\n \"\"\"\n # pylint: disable=too-many-locals\n\n # Define config space with a mix of different parameter types\n input_space = construct_parameter_space(n_continuous_params=10, n_integer_params=10, n_categorical_params=5)\n adapter = LlamaTuneAdapter(\n orig_parameter_space=input_space,\n num_low_dims=num_low_dims,\n special_param_values=special_param_values,\n max_unique_values_per_param=max_unique_values_per_param,\n )\n\n special_value_occurrences = {\n param: {special_value: 0 for special_value, _ in tuples_list}\n for param, tuples_list in adapter._special_param_values_dict.items() # pylint: disable=protected-access\n }\n unique_values_dict: Dict[str, Set] = {param: set() for param in input_space.keys()}\n\n num_configs = 1000\n for config in adapter.target_parameter_space.sample_configuration(size=num_configs): # pylint: disable=not-an-iterable\n # Transform low-dim config to high-dim point/config\n sampled_config_df = pd.DataFrame([config.values()], columns=list(config.keys()))\n orig_config_df = adapter.transform(sampled_config_df)\n # High-dim (i.e., original) config should be valid\n orig_config = CS.Configuration(input_space, values=orig_config_df.iloc[0].to_dict())\n input_space.check_configuration(orig_config)\n\n # Transform high-dim config back to low-dim\n target_config_df = adapter.inverse_transform(orig_config_df)\n # Sampled config and this should be the same\n target_config = CS.Configuration(adapter.target_parameter_space, values=target_config_df.iloc[0].to_dict())\n assert target_config == config\n\n for param, value in orig_config.items():\n # Keep track of special value occurrences\n if param in special_value_occurrences:\n if value in special_value_occurrences[param]:\n special_value_occurrences[param][value] += 1\n\n # Keep track of unique values generated for each parameter\n unique_values_dict[param].add(value)\n\n # Ensure that occurrences of special values do not significantly deviate from expected\n eps = 0.2\n for param, tuples_list in adapter._special_param_values_dict.items(): # pylint: disable=protected-access\n for value, bias_percentage in tuples_list:\n assert (1 - eps) * int(num_configs * bias_percentage) <= special_value_occurrences[param][value]\n\n # Ensure that number of unique values is less than the maximum number allowed\n for _, unique_values in unique_values_dict.items():\n assert len(unique_values) <= max_unique_values_per_param\n\n\[email protected](('num_target_space_dims', 'param_space_kwargs'), ([\n (num_target_space_dims, param_space_kwargs)\n for num_target_space_dims in (2, 4)\n for num_orig_space_factor in (1.5, 4)\n for param_space_kwargs in (\n {'n_continuous_params': int(num_target_space_dims * num_orig_space_factor)},\n {'n_integer_params': int(num_target_space_dims * num_orig_space_factor)},\n {'n_categorical_params': int(num_target_space_dims * num_orig_space_factor)},\n # Mix of all three types\n {\n 'n_continuous_params': int(num_target_space_dims * num_orig_space_factor / 3),\n 'n_integer_params': int(num_target_space_dims * num_orig_space_factor / 3),\n 'n_categorical_params': int(num_target_space_dims * num_orig_space_factor / 3),\n },\n )\n]))\ndef test_deterministic_behavior_for_same_seed(num_target_space_dims: int, param_space_kwargs: dict) -> None:\n \"\"\"\n Tests LlamaTune's space adapter deterministic behavior when given same seed in the input parameter space.\n \"\"\"\n def generate_target_param_space_configs(seed: int) -> List[CS.Configuration]:\n input_space = construct_parameter_space(**param_space_kwargs, seed=seed)\n\n # Init adapter and sample points in the low-dim space\n adapter = LlamaTuneAdapter(\n orig_parameter_space=input_space,\n num_low_dims=num_target_space_dims,\n special_param_values=None,\n max_unique_values_per_param=None,\n use_approximate_reverse_mapping=False,\n )\n\n sample_configs: List[CS.Configuration] = adapter.target_parameter_space.sample_configuration(size=100)\n return sample_configs\n\n assert generate_target_param_space_configs(42) == generate_target_param_space_configs(42)\n assert generate_target_param_space_configs(1234) != generate_target_param_space_configs(42)\n" }, { "alpha_fraction": 0.7080957889556885, "alphanum_fraction": 0.7098061442375183, "avg_line_length": 32.09434127807617, "blob_id": "ffc66db69b2af6f08a5966cf4902daee9cfa1c94", "content_id": "19e3f48ef98b3395e0672b7df7958824919b6de6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 1754, "license_type": "permissive", "max_line_length": 218, "num_lines": 53, "path": "/doc/source/index.rst", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "Welcome to MlosCore's documentation!\n====================================\n\n.. image:: badges/tests.svg\n\n.. image:: badges/coverage.svg\n :target: htmlcov/index.html\n\n``mlos_core``\n-------------\n\nThis repository contains a stripped down implementation of essentially just the core optimizer and config space description APIs from the original `MLOS <https://github.com/microsoft/MLOS>`_.\n\nIt is intended to provide a simplified, easier to consume (e.g. via ``pip``), with lower dependencies abstraction to\n\n- describe a space of context, parameters, their ranges, constraints, etc. and result objectives\n- an \"optimizer\" service `abstraction <./overview.html#mlos-core-api>`_ (e.g. ``register()`` and ``suggest()``) so we can easily swap out different implementations methods of searching (e.g. random, BO, etc.)\n- provide some helpers for `automating optimization experiment <./overview.html#mlos-bench-api>`_ runner loops and data collection\n\nFor these design requirements we intend to reuse as much from existing OSS libraries as possible and layer policies and optimizations specifically geared towards autotuning over top.\n\n``mlos_bench``\n--------------\n\nThis repository also contains the `mlos_bench <./overview.html#mlos-bench-api>`_ module intended to help automate and manage running experiments for autotuning systems with `mlos_core <./overview.html#mlos-core-api>`_.\n\nSee Also\n--------\n\n- `Source Code <https://aka.ms/mlos-core/src>`_\n\n.. toctree::\n :hidden:\n :maxdepth: 3\n :caption: Documentation\n\n installation\n overview\n\n.. toctree::\n :hidden:\n :maxdepth: 4\n :caption: API Reference\n\n api/mlos_core/modules\n api/mlos_bench/modules\n\n.. toctree::\n :maxdepth: 2\n :hidden:\n :caption: Examples\n\n auto_examples/index\n" }, { "alpha_fraction": 0.6997534036636353, "alphanum_fraction": 0.7114673256874084, "avg_line_length": 38.56097412109375, "blob_id": "1dd7b6902981946bbafc54d8e83aa641e8075682", "content_id": "37b8aa3a6980cf4763adb6486ab3bb6e7464750c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1622, "license_type": "permissive", "max_line_length": 132, "num_lines": 41, "path": "/mlos_core/mlos_core/tests/spaces/adapters/identity_adapter_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTests for Identity space adapter.\n\"\"\"\n\n# pylint: disable=missing-function-docstring\n\nimport ConfigSpace as CS\nimport pandas as pd\n\nfrom mlos_core.spaces.adapters import IdentityAdapter\n\n\ndef test_identity_adapter() -> None:\n \"\"\"\n Tests identity adapter\n \"\"\"\n input_space = CS.ConfigurationSpace(seed=1234)\n input_space.add_hyperparameter(\n CS.UniformIntegerHyperparameter(name='int_1', lower=0, upper=100))\n input_space.add_hyperparameter(\n CS.UniformFloatHyperparameter(name='float_1', lower=0, upper=100))\n input_space.add_hyperparameter(\n CS.CategoricalHyperparameter(name='str_1', choices=['on', 'off']))\n\n adapter = IdentityAdapter(orig_parameter_space=input_space)\n\n num_configs = 10\n for sampled_config in input_space.sample_configuration(size=num_configs): # pylint: disable=not-an-iterable # (false positive)\n sampled_config_df = pd.DataFrame([sampled_config.values()], columns=list(sampled_config.keys()))\n target_config_df = adapter.inverse_transform(sampled_config_df)\n assert target_config_df.equals(sampled_config_df)\n target_config = CS.Configuration(adapter.target_parameter_space, values=target_config_df.iloc[0].to_dict())\n assert target_config == sampled_config\n orig_config_df = adapter.transform(target_config_df)\n assert orig_config_df.equals(sampled_config_df)\n orig_config = CS.Configuration(adapter.orig_parameter_space, values=orig_config_df.iloc[0].to_dict())\n assert orig_config == sampled_config\n" }, { "alpha_fraction": 0.660937488079071, "alphanum_fraction": 0.6625000238418579, "avg_line_length": 32.68421173095703, "blob_id": "987e5b6ec74d71fda3172ff0cd4a03c66037ce17", "content_id": "d30a4bd9a56c8108f59c843e87fdb19a62fd2fa3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 640, "license_type": "permissive", "max_line_length": 119, "num_lines": 19, "path": "/scripts/generate-azure-credentials-config.sh", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#!/bin/bash\n##\n## Copyright (c) Microsoft Corporation.\n## Licensed under the MIT License.\n##\n\nset -eu\nset -x\n\nAZURE_DEFAULTS_GROUP=${AZURE_DEFAULTS_GROUP:-$(az config get --local defaults.group --query value -o tsv)}\nAZURE_STORAGE_ACCOUNT_NAME=${AZURE_STORAGE_ACCOUNT_NAME:-$(az config get --local storage.account --query value -o tsv)}\n\naz account get-access-token \\\n --query \"{tenant:tenant,subscription:subscription}\" |\n jq \".storageAccountKey = `\n az storage account keys list \\\n --resource-group $AZURE_DEFAULTS_GROUP \\\n --account-name $AZURE_STORAGE_ACCOUNT_NAME \\\n --query '[0].value'`\"\n" }, { "alpha_fraction": 0.656521737575531, "alphanum_fraction": 0.6739130616188049, "avg_line_length": 14.333333015441895, "blob_id": "9db524412a756f89fddeb7ef1a9973a9f1a74b30", "content_id": "eea9dd955c4a48947d7bb8cc3c12783517eac717", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 230, "license_type": "permissive", "max_line_length": 73, "num_lines": 15, "path": "/doc/README.md", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "# Documentation Generation\n\nDocumentation is generated using [`sphinx`](https://www.sphinx-doc.org/).\n\n```sh\nmake -C .. doc\n```\n\n## Testing with Docker\n\n```sh\n./nginx-docker.sh restart\n```\n\n> Now browse to `http://localhost:8080`\n" }, { "alpha_fraction": 0.7135016322135925, "alphanum_fraction": 0.7299670577049255, "avg_line_length": 32.74074172973633, "blob_id": "36777c13ade4c79f323beb0564ebdd7c369c4fa5", "content_id": "be1b65838781bdcfebfc23aa18265d697f75728c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 911, "license_type": "permissive", "max_line_length": 93, "num_lines": 27, "path": "/mlos_core/mlos_core/tests/optimizers/conftest.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTest fixtures for mlos_bench optimizers.\n\"\"\"\n\nimport pytest\n\nimport ConfigSpace as CS\n\n\[email protected]\ndef configuration_space() -> CS.ConfigurationSpace:\n \"\"\"\n Test fixture to produce a config space with all types of hyperparameters.\n \"\"\"\n # Start defining a ConfigurationSpace for the Optimizer to search.\n space = CS.ConfigurationSpace(seed=1234)\n # Add a continuous input dimension between 0 and 1.\n space.add_hyperparameter(CS.UniformFloatHyperparameter(name='x', lower=0, upper=1))\n # Add a categorical hyperparameter with 3 possible values.\n space.add_hyperparameter(CS.CategoricalHyperparameter(name='y', choices=[\"a\", \"b\", \"c\"]))\n # Add a discrete input dimension between 0 and 10.\n space.add_hyperparameter(CS.UniformIntegerHyperparameter(name='z', lower=0, upper=10))\n return space\n" }, { "alpha_fraction": 0.6878402829170227, "alphanum_fraction": 0.6896551847457886, "avg_line_length": 25.238094329833984, "blob_id": "d79bcdd2793028129f6ce88ac457ef2076fedbf1", "content_id": "5809b3797b01a03b3ce003b891b431a947421ceb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 551, "license_type": "permissive", "max_line_length": 110, "num_lines": 21, "path": "/mlos_bench/mlos_bench/config/environments/apps/redis/scripts/remote/run-workload.sh", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#!/bin/bash\n##\n## Copyright (c) Microsoft Corporation.\n## Licensed under the MIT License.\n##\n\nset -eu\n\nscriptdir=$(dirname \"$(readlink -f \"$0\")\")\ncd \"$scriptdir\"\nsource ./common.sh\n\ncheck_docker\n\n# Run the client workload.\n# Here we reuse the redis server container image, but replace its entrypoint with the redis-benchmark utility.\ndocker run --rm --name $REDIS_CLIENT_NAME --entrypoint /usr/local/bin/redis-benchmark $REDIS_IMAGE \\\n -h $REDIS_SERVER_HOST -p $REDIS_PORT \\\n -t set \\\n -q --csv \\\n | tee /tmp/mlos_bench/output/results.csv\n" }, { "alpha_fraction": 0.7729591727256775, "alphanum_fraction": 0.7729591727256775, "avg_line_length": 23.5, "blob_id": "f477a7339139cf65a382b67fe831e262fe915743", "content_id": "55f0aa09eb8ce3b68e31d699b3b9ffdfb590de7d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 392, "license_type": "permissive", "max_line_length": 93, "num_lines": 16, "path": "/mlos_core/mlos_core/optimizers/bayesian_optimizers/__init__.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nBasic initializer module for the mlos_core Bayesian optimizers.\n\"\"\"\n\nfrom mlos_core.optimizers.bayesian_optimizers.bayesian_optimizer import BaseBayesianOptimizer\nfrom mlos_core.optimizers.bayesian_optimizers.smac_optimizer import SmacOptimizer\n\n\n__all__ = [\n 'BaseBayesianOptimizer',\n 'SmacOptimizer',\n]\n" }, { "alpha_fraction": 0.7252747416496277, "alphanum_fraction": 0.7252747416496277, "avg_line_length": 20.41176414489746, "blob_id": "bf1fd18d2adf76f7961c2b4d154dd20c313c11fc", "content_id": "d1feae054c4b1c9f2f4eacff18a846972711a3e5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 364, "license_type": "permissive", "max_line_length": 63, "num_lines": 17, "path": "/mlos_bench/mlos_bench/environments/remote/__init__.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nRemote Tunable Environments for mlos_bench.\n\"\"\"\n\nfrom mlos_bench.environments.remote.remote_env import RemoteEnv\nfrom mlos_bench.environments.remote.os_env import OSEnv\nfrom mlos_bench.environments.remote.vm_env import VMEnv\n\n__all__ = [\n 'RemoteEnv',\n 'OSEnv',\n 'VMEnv',\n]\n" }, { "alpha_fraction": 0.8138771653175354, "alphanum_fraction": 0.8152836561203003, "avg_line_length": 100.57142639160156, "blob_id": "d1bfd3128355881bfcb49a27604b78528a09ba47", "content_id": "81fcf8702ce975028919844be92301a997d6a186", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2133, "license_type": "permissive", "max_line_length": 324, "num_lines": 21, "path": "/mlos_core/README.md", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "# mlos-core\n\nThis directory contains the code for the `mlos-core` optimizer package.\n\n## Description\n\n`mlos-core` is an optimizer package, using Bayesian optimization to identify & sample tunable configuration parameters and propose optimal parameter values.\nThese are evaluated by `mlos-bench`, generating and tracking experiment results (proposed parameters, benchmark results & telemetry) to update the optimization loop.\n\n## Features\n\nSince the tunable OS kernel parameter search space is extremely large, `mlos-core` automates the following steps to efficiently generate optimal task-specific kernel configurations.\n\n1. Reduce the search space by identifying a promising set of tunable parameters\n - Map out the configuration search space: Automatically track and manage the discovery of new Linux kernel parameters and their default values across versions. Filter out non-tunable parameters (e.g., not writable) and track which kernel parameters exist for a given kernel version.\n - Leverage parameter knowledge for optimization: Information on ranges, sampling intervals, parameter correlations, workload type sensitivities for tunable parameters are tracked and currently manually curated. In the future, this can be automatically maintained by scraping documentation pages on kernel parameters.\n - Tailored to application: Consider prior knowledge of the parameter's impact & an application's workload profile (e.g. network heavy, disk heavy, CPU bound, multi-threaded, latency sensitive, throughput oriented, etc.) to identify likely impactful candidates of tunable parameters, specific to a particular application.\n2. Sampling to warm-start optimization in a high dimensional search space\n3. Produce optimal configurations through Bayesian optimization\n - Support for various optimizer algorithms (default Bayesian optimizer, Flaml, SMAC, and random for baseline comparison), that handle multiple types of constraints. This includes cost-aware optimization, that considers experiment costs given current tunable parameters.\n - Integrated with `mlos-bench`, proposed configurations are logged and evaluated.\n" }, { "alpha_fraction": 0.6014834642410278, "alphanum_fraction": 0.6095752120018005, "avg_line_length": 25.96363639831543, "blob_id": "ec662c21d1ad4dcde34f73141a2e90b63fad2739", "content_id": "45161dc1591be02a7209ec0591e7047907ee855b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1483, "license_type": "permissive", "max_line_length": 91, "num_lines": 55, "path": "/doc/nginx-docker.sh", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#!/bin/bash\n##\n## Copyright (c) Microsoft Corporation.\n## Licensed under the MIT License.\n##\n\n# A quick script to start a local webserver for testing the sphinx documentation.\n\nset -eu\n\nscriptpath=$(readlink -f \"$0\")\nscriptdir=$(dirname \"$scriptpath\")\ncd \"$scriptdir\"\n\nif [ -f ../.devcontainer/.env ]; then\n source ../.devcontainer/.env\nfi\nNGINX_PORT=\"${NGINX_PORT:-81}\"\n\n# Make it work inside a devcontainer too.\nrepo_root=$(readlink -f \"$scriptdir/..\")\nif [ -n \"${LOCAL_WORKSPACE_FOLDER:-}\" ]; then\n repo_root=\"$LOCAL_WORKSPACE_FOLDER\"\nfi\n\ncmd=\"${1:-}\"\n\nif [ \"$cmd\" == 'start' ]; then\n set -x\n tmpdir=$(mktemp -d)\n docker build --progress=plain -t mlos-doc-nginx \\\n --build-arg http_proxy=$http_proxy \\\n --build-arg https_proxy=$https_proxy \\\n --build-arg no_proxy=$no_proxy \\\n --build-arg NGINX_PORT=$NGINX_PORT \\\n -f Dockerfile \"$tmpdir\"\n rmdir \"$tmpdir\"\n docker run -d --name mlos-doc-nginx \\\n -v \"$repo_root/doc/nginx-default.conf\":/etc/nginx/templates/default.conf.template \\\n -v \"$repo_root/doc\":/doc \\\n --env NGINX_PORT=$NGINX_PORT \\\n -p 8080:$NGINX_PORT \\\n mlos-doc-nginx\n set +x\nelif [ \"$cmd\" == 'stop' ]; then\n docker stop mlos-doc-nginx || true\n docker rm mlos-doc-nginx || true\nelif [ \"$cmd\" == 'restart' ]; then\n \"$scriptpath\" 'stop'\n \"$scriptpath\" 'start'\nelse\n echo \"ERROR: Invalid argument: $0.\" >&2\n echo \"Usage: $0 [start|stop|restart]\"\n exit 1\nfi\n" }, { "alpha_fraction": 0.6315581798553467, "alphanum_fraction": 0.6335305571556091, "avg_line_length": 35.21428680419922, "blob_id": "6c4025aaed4e2b1577e09249ef0ddf853f1f2f93", "content_id": "4b02cbc2eab039d317d938dd68de99ca4c22f22d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2535, "license_type": "permissive", "max_line_length": 96, "num_lines": 70, "path": "/mlos_bench/mlos_bench/services/remote/azure/azure_auth.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nA collection Service functions for managing VMs on Azure.\n\"\"\"\n\nimport datetime\nimport json\nimport logging\nimport subprocess\nfrom typing import Any, Dict, Optional\n\nfrom mlos_bench.services.base_service import Service\nfrom mlos_bench.services.types.authenticator_type import SupportsAuth\n\n_LOG = logging.getLogger(__name__)\n\n\nclass AzureAuthService(Service, SupportsAuth):\n \"\"\"\n Helper methods to get access to Azure services.\n \"\"\"\n\n _REQ_INTERVAL = 300 # = 5 min\n\n def __init__(self,\n config: Optional[Dict[str, Any]] = None,\n global_config: Optional[Dict[str, Any]] = None,\n parent: Optional[Service] = None):\n \"\"\"\n Create a new instance of Azure authentication services proxy.\n\n Parameters\n ----------\n config : dict\n Free-format dictionary that contains the benchmark environment\n configuration.\n global_config : dict\n Free-format dictionary of global parameters.\n parent : Service\n Parent service that can provide mixin functions.\n \"\"\"\n super().__init__(config, global_config, parent)\n\n # Register methods that we want to expose to the Environment objects.\n self.register([self.get_access_token])\n\n # This parameter can come from command line as strings, so conversion is needed.\n self._req_interval = float(self.config.get(\"tokenRequestInterval\", self._REQ_INTERVAL))\n\n self._access_token = \"RENEW *NOW*\"\n self._token_expiration_ts = datetime.datetime.now() # Typically, some future timestamp.\n\n def get_access_token(self) -> str:\n \"\"\"\n Get the access token from Azure CLI, if expired.\n \"\"\"\n ts_diff = (self._token_expiration_ts - datetime.datetime.now()).total_seconds()\n _LOG.debug(\"Time to renew the token: %.2f sec.\", ts_diff)\n if ts_diff < self._req_interval:\n _LOG.debug(\"Request new accessToken\")\n # TODO: Use azure-identity SDK and a key valut instead of `az` CLI.\n res = json.loads(subprocess.check_output(\n 'az account get-access-token', shell=True, text=True))\n self._token_expiration_ts = datetime.datetime.fromisoformat(res[\"expiresOn\"])\n self._access_token = res[\"accessToken\"]\n _LOG.info(\"Got new accessToken. Expiration time: %s\", self._token_expiration_ts)\n return self._access_token\n" }, { "alpha_fraction": 0.7788309454917908, "alphanum_fraction": 0.7851500511169434, "avg_line_length": 89.42857360839844, "blob_id": "c295b6d313a9462c095ed919bcbc8e0d046cc970", "content_id": "d5e992ef77bf837ce050c0ad6686437870c8b986", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 633, "license_type": "permissive", "max_line_length": 254, "num_lines": 7, "path": "/mlos_bench/mlos_bench/services/types/README.md", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "# Service Type Interfaces\n\nService loading in `mlos_bench` uses a [mix-in](https://en.wikipedia.org/wiki/Mixin#In_Python) approach to combine the functionality of multiple classes specified at runtime through config files into a single class.\n\nThis can make type checking in the `Environments` that use those `Services` a little tricky, both for developers and checking tools.\n\nTo address this we define `@runtime_checkable` decorated [`Protocols`](https://peps.python.org/pep-0544/) (\"interfaces\" in other languages) to declare the expected behavior of the `Services` that are loaded at runtime in the `Environments` that use them.\n" }, { "alpha_fraction": 0.7665121555328369, "alphanum_fraction": 0.7665121555328369, "avg_line_length": 74.0434799194336, "blob_id": "ecfb23a4f772b09634f93bf62a026c4de2e13dfd", "content_id": "9bded1ed4eceb50ada87bfff1a4719beb20ae0e5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3452, "license_type": "permissive", "max_line_length": 369, "num_lines": 46, "path": "/mlos_bench/mlos_bench/config/README.md", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "# `config` Examples Overview\n\nThe [`config`](./) directory contains a collection of scripts and config snippets that are used to configure the `mlos_bench` components.\n\nThese are meant to be used as examples and starting points for your own configuration, though some can be included as-is in your configuration (e.g. linux kernel configs).\n\nIn general the `config` directory layout follows that of the `mlos_bench` module/directory layout (e.g. `remote` and `local` `Environments` making using of `Services`, etc., each with their own `json` configs and shell scripts.).\n\nFull end-to-end examples are provided in the [`cli`](./cli/) directory, and typically and make use of the root [`CompositeEnvironments`](./environments/root/) to combine multiple [`Environments`](./environments/), also referencing [`Services`](./services/), [`Storage`](./storage/), and [`Optimizer`](./optimizers/) configs, into a single [`mlos_bench`](../run.py) run.\n\n## Globals\n\nAs mentioned in the [mlos_bench/README.md](../../README.md), a general rule is that the parameters from the global configs like `global_config_azure.json` and/or `experiment_MyAppBench.jsonc` override the corresponding parameters in other configurations.\nThat allows us to propagate the values of the parameters that are specific to the experiment into other components of the framework and keep the majority of the config files in our library immutable and reusable.\n\n### Sensitive parameters\n\nWe recommend storing sensitive parameters like DB hostname and password or Azure credentials in a separate file that is not checked into the source control.\nOne can create several such files, e.g., `global_config_storage.json` for DB password and `global_config_azure.json` (usually generated by [`scripts/generate-azure-credentials-config.sh`](../../../scripts/generate-azure-credentials-config.sh)) and include them in the `\"globals\"` section of the CLI config.\n\n### Experiment-specific parameters\n\nSome global parameters vary from experiment to experiment.\nIt makes sense to store them in a separate file and include it in the `\"globals\"` section of the CLI config - or, better yet, specify it in the `--globals` option in the command line.\nJust like with other global configs, the values from the experiment configuration will override the corresponding values in the Environment, Service, and Optimizer configs down the configuration tree.\nThis way we can keep our Environment configs immutable and reusable.\n\nOne example of the experiment-specific config is the [`experiment_RedisBench.jsonc`](experiments/experiment_RedisBench.jsonc) file that contains the name of the experiment and parameters like VM size and location that may be different for different experiments but remain constant for all trials of that particular experiment.\n\n## Schemas\n\nThe [`schemas`](./schemas/) directory contains the [`jsonschema`](https://json-schema.org/) schemas for the `mlos_bench` config files and may also be helpful when writing your own configs.\n\nFor instance including a `\"$schema\"` attribute at the top of your `json` config file will enable `json` validation and auto-complete in many editors (e.g. [VSCode](https://code.visualstudio.com/)):\n\n```jsonc\n{\n \"$schema\": \"https://raw.githubusercontent.com/microsoft/MLOS/main/mlos_bench/mlos_bench/config/schemas/environments/environment-schema.json\",\n\n\n \"class\": \"mlos_bench.environments.SomeEnviroment\",\n \"config\": {\n // ...\n }\n}\n```\n" }, { "alpha_fraction": 0.5752437710762024, "alphanum_fraction": 0.575667679309845, "avg_line_length": 29.636363983154297, "blob_id": "466c8b777e1e848a9dc020a9de176cf25b3102c5", "content_id": "930a3355d046eedbd0e8ae4070c10e8586c0ee09", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7077, "license_type": "permissive", "max_line_length": 117, "num_lines": 231, "path": "/mlos_bench/mlos_bench/tunables/covariant_group.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTunable parameter definition.\n\"\"\"\nimport copy\n\nfrom typing import Dict, Iterable, Union\n\nfrom mlos_bench.tunables.tunable import Tunable, TunableValue\n\n\nclass CovariantTunableGroup:\n \"\"\"\n A collection of tunable parameters.\n Changing any of the parameters in the group incurs the same cost of the experiment.\n \"\"\"\n\n def __init__(self, name: str, config: dict):\n \"\"\"\n Create a new group of tunable parameters.\n\n Parameters\n ----------\n name : str\n Human-readable identifier of the tunable parameters group.\n config : dict\n Python dict that represents a CovariantTunableGroup\n (e.g., deserialized from JSON).\n \"\"\"\n self._is_updated = True\n self._name = name\n self._cost = int(config.get(\"cost\", 0))\n self._tunables: Dict[str, Tunable] = {\n name: Tunable(name, tunable_config)\n for (name, tunable_config) in config.get(\"params\", {}).items()\n }\n\n @property\n def name(self) -> str:\n \"\"\"\n Get the name of the covariant group.\n\n Returns\n -------\n name : str\n Name (i.e., a string id) of the covariant group.\n \"\"\"\n return self._name\n\n @property\n def cost(self) -> int:\n \"\"\"\n Get the cost of changing the values in the covariant group.\n This value is a constant. Use `get_current_cost()` to get\n the cost given the group update status.\n\n Returns\n -------\n cost : int\n Cost of changing the values in the covariant group.\n \"\"\"\n return self._cost\n\n def copy(self) -> \"CovariantTunableGroup\":\n \"\"\"\n Deep copy of the CovariantTunableGroup object.\n\n Returns\n -------\n group : CovariantTunableGroup\n A new instance of the CovariantTunableGroup object\n that is a deep copy of the original one.\n \"\"\"\n return copy.deepcopy(self)\n\n def __eq__(self, other: object) -> bool:\n \"\"\"\n Check if two CovariantTunableGroup objects are equal.\n\n Parameters\n ----------\n other : CovariantTunableGroup\n A covariant tunable group object to compare to.\n\n Returns\n -------\n is_equal : bool\n True if two CovariantTunableGroup objects are equal.\n \"\"\"\n if not isinstance(other, CovariantTunableGroup):\n return False\n # TODO: May need to provide logic to relax the equality check on the\n # tunables (e.g. \"compatible\" vs. \"equal\").\n return (self._name == other._name and\n self._cost == other._cost and\n self._is_updated == other._is_updated and\n self._tunables == other._tunables)\n\n def equals_defaults(self, other: \"CovariantTunableGroup\") -> bool:\n \"\"\"\n Checks to see if the other CovariantTunableGroup is the same, ignoring\n the current values of the two groups' Tunables.\n\n Parameters\n ----------\n other : CovariantTunableGroup\n A covariant tunable group object to compare to.\n\n Returns\n -------\n are_equal : bool\n True if the two CovariantTunableGroup objects' *metadata* are the same,\n False otherwise.\n \"\"\"\n # NOTE: May be worth considering to implement this check without copies.\n cpy = self.copy()\n cpy.restore_defaults()\n cpy.reset_is_updated()\n\n other = other.copy()\n other.restore_defaults()\n other.reset_is_updated()\n return cpy == other\n\n def restore_defaults(self) -> None:\n \"\"\"\n Restore all tunable parameters to their default values.\n \"\"\"\n for tunable in self._tunables.values():\n if tunable.value != tunable.default:\n self._is_updated = True\n tunable.value = tunable.default\n\n def reset_is_updated(self) -> None:\n \"\"\"\n Clear the update flag. That is, state that running an experiment with the\n current values of the tunables in this group has no extra cost.\n \"\"\"\n self._is_updated = False\n\n def is_updated(self) -> bool:\n \"\"\"\n Check if any of the tunable values in the group has been updated.\n\n Returns\n -------\n is_updated : bool\n True if any of the tunable values in the group has been updated, False otherwise.\n \"\"\"\n return self._is_updated\n\n def get_current_cost(self) -> int:\n \"\"\"\n Get the cost of the experiment given current tunable values.\n\n Returns\n -------\n cost : int\n Cost of the experiment or 0 if parameters have not been updated.\n \"\"\"\n return self._cost if self._is_updated else 0\n\n def get_names(self) -> Iterable[str]:\n \"\"\"\n Get the names of all tunables in the group.\n \"\"\"\n return self._tunables.keys()\n\n def get_tunable_values_dict(self) -> Dict[str, TunableValue]:\n \"\"\"\n Get current values of all tunables in the group as a dict.\n\n Returns\n -------\n tunables : Dict[str, TunableValue]\n \"\"\"\n return {name: tunable.value for (name, tunable) in self._tunables.items()}\n\n def __repr__(self) -> str:\n \"\"\"\n Produce a human-readable version of the CovariantTunableGroup\n (mostly for logging).\n\n Returns\n -------\n string : str\n A human-readable version of the CovariantTunableGroup.\n \"\"\"\n return f\"{self._name}: {self._tunables}\"\n\n def get_tunable(self, tunable: Union[str, Tunable]) -> Tunable:\n \"\"\"\n Access the entire Tunable in a group (not just its value).\n Throw KeyError if the tunable is not in the group.\n\n Parameters\n ----------\n tunable : str\n Name of the tunable parameter.\n\n Returns\n -------\n Tunable\n An instance of the Tunable parameter.\n \"\"\"\n name: str = tunable.name if isinstance(tunable, Tunable) else tunable\n return self._tunables[name]\n\n def get_tunables(self) -> Iterable[Tunable]:\n \"\"\"Gets the set of tunables for this CovariantTunableGroup.\n\n Returns\n -------\n Iterable[Tunable]\n \"\"\"\n return self._tunables.values()\n\n def __contains__(self, tunable: Union[str, Tunable]) -> bool:\n name: str = tunable.name if isinstance(tunable, Tunable) else tunable\n return name in self._tunables\n\n def __getitem__(self, tunable: Union[str, Tunable]) -> TunableValue:\n return self.get_tunable(tunable).value\n\n def __setitem__(self, tunable: Union[str, Tunable], tunable_value: Union[TunableValue, Tunable]) -> TunableValue:\n value: TunableValue = tunable_value.value if isinstance(tunable_value, Tunable) else tunable_value\n self._is_updated |= self.get_tunable(tunable).update(value)\n return value\n" }, { "alpha_fraction": 0.5813953280448914, "alphanum_fraction": 0.5926481485366821, "avg_line_length": 36.54929733276367, "blob_id": "4d6699a5b07ad1441eea064d8b8c624dec8180f6", "content_id": "9e9778277590197c806ce9c41205adfb8263b6de", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2666, "license_type": "permissive", "max_line_length": 93, "num_lines": 71, "path": "/mlos_bench/mlos_bench/tests/environments/local/local_env_vars_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nUnit tests for passing shell environment variables into LocalEnv scripts.\n\"\"\"\nimport sys\n\nimport pytest\n\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\nfrom mlos_bench.tests.environments.local import create_local_env, check_local_env_success\n\n\ndef _run_local_env(tunable_groups: TunableGroups, shell_subcmd: str, expected: dict) -> None:\n \"\"\"\n Check that LocalEnv can set shell environment variables.\n \"\"\"\n local_env = create_local_env(tunable_groups, {\n \"const_args\": {\n \"const_arg\": 111, # Passed into \"shell_env_params\"\n \"other_arg\": 222, # NOT passed into \"shell_env_params\"\n },\n \"tunable_params\": [\"kernel\"],\n \"shell_env_params\": [\n \"const_arg\", # From \"const_arg\"\n \"kernel_sched_latency_ns\", # From \"tunable_params\"\n ],\n \"run\": [\n \"echo const_arg,other_arg,unknown_arg,kernel_sched_latency_ns > output.csv\",\n f\"echo {shell_subcmd} >> output.csv\",\n ],\n \"read_results_file\": \"output.csv\",\n })\n\n check_local_env_success(local_env, tunable_groups, expected, [])\n\n\[email protected](sys.platform == 'win32', reason=\"sh-like shell only\")\ndef test_local_env_vars_shell(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Check that LocalEnv can set shell environment variables in sh-like shell.\n \"\"\"\n _run_local_env(\n tunable_groups,\n shell_subcmd=\"$const_arg,$other_arg,$unknown_arg,$kernel_sched_latency_ns\",\n expected={\n \"const_arg\": 111, # From \"const_args\"\n \"other_arg\": float(\"NaN\"), # Not included in \"shell_env_params\"\n \"unknown_arg\": float(\"NaN\"), # Unknown/undefined variable\n \"kernel_sched_latency_ns\": 2000000, # From \"tunable_params\"\n }\n )\n\n\[email protected](sys.platform != 'win32', reason=\"Windows only\")\ndef test_local_env_vars_windows(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Check that LocalEnv can set shell environment variables on Windows / cmd shell.\n \"\"\"\n _run_local_env(\n tunable_groups,\n shell_subcmd=r\"%const_arg%,%other_arg%,%unknown_arg%,%kernel_sched_latency_ns%\",\n expected={\n \"const_arg\": 111, # From \"const_args\"\n \"other_arg\": r\"%other_arg%\", # Not included in \"shell_env_params\"\n \"unknown_arg\": r\"%unknown_arg%\", # Unknown/undefined variable\n \"kernel_sched_latency_ns\": 2000000, # From \"tunable_params\"\n }\n )\n" }, { "alpha_fraction": 0.5465356707572937, "alphanum_fraction": 0.550672173500061, "avg_line_length": 22.585365295410156, "blob_id": "e9bc447238eafae46d6a537b6e5af9a586014043", "content_id": "91cfd3a09b9efc5e2ad916ad6f30a32fdf49d25f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1934, "license_type": "permissive", "max_line_length": 70, "num_lines": 82, "path": "/mlos_bench/mlos_bench/environments/status.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nEnum for the status of the benchmark/environment.\n\"\"\"\n\nimport enum\n\n\nclass Status(enum.Enum):\n \"\"\"\n Enum for the status of the benchmark/environment.\n \"\"\"\n\n UNKNOWN = 0\n PENDING = 1\n READY = 2\n RUNNING = 3\n SUCCEEDED = 4\n CANCELED = 5\n FAILED = 6\n TIMED_OUT = 7\n\n def is_good(self) -> bool:\n \"\"\"\n Check if the status of the benchmark/environment is good.\n \"\"\"\n return self in {\n Status.PENDING,\n Status.READY,\n Status.RUNNING,\n Status.SUCCEEDED,\n }\n\n def is_completed(self) -> bool:\n \"\"\"\n Check if the status of the benchmark/environment is\n one of {SUCCEEDED, FAILED, TIMED_OUT}.\n \"\"\"\n return self in {\n Status.SUCCEEDED,\n Status.FAILED,\n Status.TIMED_OUT,\n }\n\n def is_pending(self) -> bool:\n \"\"\"\n Check if the status of the benchmark/environment is PENDING.\n \"\"\"\n return self == Status.PENDING\n\n def is_ready(self) -> bool:\n \"\"\"\n Check if the status of the benchmark/environment is READY.\n \"\"\"\n return self == Status.READY\n\n def is_succeeded(self) -> bool:\n \"\"\"\n Check if the status of the benchmark/environment is SUCCEEDED.\n \"\"\"\n return self == Status.SUCCEEDED\n\n def is_failed(self) -> bool:\n \"\"\"\n Check if the status of the benchmark/environment is FAILED.\n \"\"\"\n return self == Status.FAILED\n\n def is_canceled(self) -> bool:\n \"\"\"\n Check if the status of the benchmark/environment is CANCELED.\n \"\"\"\n return self == Status.CANCELED\n\n def is_timed_out(self) -> bool:\n \"\"\"\n Check if the status of the benchmark/environment is TIMED_OUT.\n \"\"\"\n return self == Status.FAILED\n" }, { "alpha_fraction": 0.6041542887687683, "alphanum_fraction": 0.6172106862068176, "avg_line_length": 23.071428298950195, "blob_id": "411763e27e591bfcf1e951cb80fcf44d372545a4", "content_id": "9dc22fd0f70539ece4a876f2136f790d9f8dec59", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1685, "license_type": "permissive", "max_line_length": 79, "num_lines": 70, "path": "/mlos_bench/mlos_bench/tests/tunables/conftest.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTest fixtures for individual Tunable objects.\n\"\"\"\n\nimport pytest\n\nfrom mlos_bench.tunables.tunable import Tunable\n\n# pylint: disable=redefined-outer-name\n# -- Ignore pylint complaints about pytest references to\n# `tunable_groups` fixture as both a function and a parameter.\n\n\[email protected]\ndef tunable_categorical() -> Tunable:\n \"\"\"\n A test fixture that produces a categorical Tunable object.\n\n Returns\n -------\n tunable : Tunable\n An instance of a categorical Tunable.\n \"\"\"\n return Tunable(\"vmSize\", {\n \"description\": \"Azure VM size\",\n \"type\": \"categorical\",\n \"default\": \"Standard_B4ms\",\n \"values\": [\"Standard_B2s\", \"Standard_B2ms\", \"Standard_B4ms\"]\n })\n\n\[email protected]\ndef tunable_int() -> Tunable:\n \"\"\"\n A test fixture that produces an interger Tunable object with limited range.\n\n Returns\n -------\n tunable : Tunable\n An instance of an integer Tunable.\n \"\"\"\n return Tunable(\"kernel_sched_migration_cost_ns\", {\n \"description\": \"Cost of migrating the thread to another core\",\n \"type\": \"int\",\n \"default\": 40000,\n \"range\": [-1, 500000],\n \"special\": [-1]\n })\n\n\[email protected]\ndef tunable_float() -> Tunable:\n \"\"\"\n A test fixture that produces a float Tunable object with limited range.\n\n Returns\n -------\n tunable : Tunable\n An instance of a float Tunable.\n \"\"\"\n return Tunable(\"chaos_monkey_prob\", {\n \"description\": \"Probability of spontaneous VM shutdown\",\n \"type\": \"float\",\n \"default\": 0.01,\n \"range\": [0, 1]\n })\n" }, { "alpha_fraction": 0.6931589245796204, "alphanum_fraction": 0.6941649913787842, "avg_line_length": 33.67441940307617, "blob_id": "df11f94e4204d3f09dab63eafd5f433e96d21d75", "content_id": "d3d70b25d28ee080429448bcaa82543c7e5ac3a2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2982, "license_type": "permissive", "max_line_length": 113, "num_lines": 86, "path": "/mlos_bench/mlos_bench/tests/services/config_persistence_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nUnit tests for configuration persistence service.\n\"\"\"\n\nimport os\nimport sys\nimport pytest\n\nfrom mlos_bench.config.schemas import ConfigSchema\nfrom mlos_bench.services.config_persistence import ConfigPersistenceService\n\n\nif sys.version_info < (3, 9):\n from importlib_resources import files\nelse:\n from importlib.resources import files\n\n\n# pylint: disable=redefined-outer-name\n\n\[email protected]\ndef config_persistence_service() -> ConfigPersistenceService:\n \"\"\"\n Test fixture for ConfigPersistenceService.\n \"\"\"\n return ConfigPersistenceService({\n \"config_path\": [\n \"./non-existent-dir/test/foo/bar\", # Non-existent config path\n str(files(\"mlos_bench.tests.config\").joinpath(\"\")), # Test configs (relative to mlos_bench/tests)\n # Shouldn't be necessary since we automatically add this.\n # str(files(\"mlos_bench.config\").joinpath(\"\")), # Stock configs\n ]\n })\n\n\ndef test_resolve_stock_path(config_persistence_service: ConfigPersistenceService) -> None:\n \"\"\"\n Check if we can actually find a file somewhere in `config_path`.\n \"\"\"\n # pylint: disable=protected-access\n assert config_persistence_service._config_path is not None\n assert ConfigPersistenceService.BUILTIN_CONFIG_PATH in config_persistence_service._config_path\n file_path = \"storage/in-memory.jsonc\"\n path = config_persistence_service.resolve_path(file_path)\n assert path.endswith(file_path)\n assert os.path.exists(path)\n assert os.path.samefile(\n ConfigPersistenceService.BUILTIN_CONFIG_PATH,\n os.path.commonpath([ConfigPersistenceService.BUILTIN_CONFIG_PATH, path])\n )\n\n\ndef test_resolve_path(config_persistence_service: ConfigPersistenceService) -> None:\n \"\"\"\n Check if we can actually find a file somewhere in `config_path`.\n \"\"\"\n file_path = \"tunable-values/tunable-values-example.jsonc\"\n path = config_persistence_service.resolve_path(file_path)\n assert path.endswith(file_path)\n assert os.path.exists(path)\n\n\ndef test_resolve_path_fail(config_persistence_service: ConfigPersistenceService) -> None:\n \"\"\"\n Check if non-existent file resolves without using `config_path`.\n \"\"\"\n file_path = \"foo/non-existent-config.json\"\n path = config_persistence_service.resolve_path(file_path)\n assert not os.path.exists(path)\n assert path == file_path\n\n\ndef test_load_config(config_persistence_service: ConfigPersistenceService) -> None:\n \"\"\"\n Check if we can successfully load a config file located relative to `config_path`.\n \"\"\"\n tunables_data = config_persistence_service.load_config(\"tunable-values/tunable-values-example.jsonc\",\n ConfigSchema.TUNABLE_VALUES)\n assert tunables_data is not None\n assert isinstance(tunables_data, dict)\n assert len(tunables_data) >= 1\n" }, { "alpha_fraction": 0.7254237532615662, "alphanum_fraction": 0.7254237532615662, "avg_line_length": 18.66666603088379, "blob_id": "34cfa9af5d0a4b72edd9ad8a7b401f9cc14b9483", "content_id": "656d8c0a7a56a6f446745c62179d78844d477ba0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 295, "license_type": "permissive", "max_line_length": 60, "num_lines": 15, "path": "/mlos_bench/mlos_bench/tunables/__init__.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTunables classes for Environments in mlos_bench.\n\"\"\"\n\nfrom mlos_bench.tunables.tunable import Tunable\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\n\n__all__ = [\n 'Tunable',\n 'TunableGroups',\n]\n" }, { "alpha_fraction": 0.7245283126831055, "alphanum_fraction": 0.7245283126831055, "avg_line_length": 17.928571701049805, "blob_id": "4fb6a6dfff2ad9e20512d31065d2d7486773a2a6", "content_id": "c6dbf7c0211bfabfc8064be21862ff277f1226f8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 265, "license_type": "permissive", "max_line_length": 59, "num_lines": 14, "path": "/mlos_bench/mlos_bench/tests/services/local/__init__.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTests for mlos_bench.services.local.\nUsed to make mypy happy about multiple conftest.py modules.\n\"\"\"\n\nfrom .mock import MockLocalExecService\n\n__all__ = [\n 'MockLocalExecService',\n]\n" }, { "alpha_fraction": 0.6902146935462952, "alphanum_fraction": 0.6902146935462952, "avg_line_length": 47.80799865722656, "blob_id": "1826c816f5193461e2d7aaa8e77ec344b6c4813a", "content_id": "196efa060fba5ca2bd6f640b10a1b676337b944f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6101, "license_type": "permissive", "max_line_length": 130, "num_lines": 125, "path": "/mlos_bench/mlos_bench/tests/config/schemas/optimizers/test_optimizer_schemas.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTests for optimizer schema validation.\n\"\"\"\n\nfrom os import path\nfrom typing import Optional\n\nimport pytest\n\nfrom mlos_core.optimizers import OptimizerType\nfrom mlos_core.spaces.adapters import SpaceAdapterType\nfrom mlos_core.tests import get_all_concrete_subclasses\n\nfrom mlos_bench.config.schemas import ConfigSchema\nfrom mlos_bench.optimizers.base_optimizer import Optimizer\n\nfrom mlos_bench.tests import try_resolve_class_name\nfrom mlos_bench.tests.config.schemas import (get_schema_test_cases,\n check_test_case_against_schema,\n check_test_case_config_with_extra_param)\n\n\n# General testing strategy:\n# - hand code a set of good/bad configs (useful to test editor schema checking)\n# - enumerate and try to check that we've covered all the cases\n# - for each config, load and validate against expected schema\n\nTEST_CASES = get_schema_test_cases(path.join(path.dirname(__file__), \"test-cases\"))\n\n\n# Dynamically enumerate some of the cases we want to make sure we cover.\n\nexpected_mlos_bench_optimizer_class_names = [subclass.__module__ + \".\" + subclass.__name__\n for subclass in get_all_concrete_subclasses(Optimizer, # type: ignore[type-abstract]\n pkg_name='mlos_bench')]\nassert expected_mlos_bench_optimizer_class_names\n\n# Also make sure that we check for configs where the optimizer_type or space_adapter_type are left unspecified (None).\n\nexpected_mlos_core_optimizer_types = list(OptimizerType) + [None]\nassert expected_mlos_core_optimizer_types\n\nexpected_mlos_core_space_adapter_types = list(SpaceAdapterType) + [None]\nassert expected_mlos_core_space_adapter_types\n\n\n# Do the full cross product of all the test cases and all the optimizer types.\[email protected](\"test_case_subtype\", sorted(TEST_CASES.by_subtype))\[email protected](\"mlos_bench_optimizer_type\", expected_mlos_bench_optimizer_class_names)\ndef test_case_coverage_mlos_bench_optimizer_type(test_case_subtype: str, mlos_bench_optimizer_type: str) -> None:\n \"\"\"\n Checks to see if there is a given type of test case for the given mlos_bench optimizer type.\n \"\"\"\n for test_case in TEST_CASES.by_subtype[test_case_subtype].values():\n if try_resolve_class_name(test_case.config.get(\"class\")) == mlos_bench_optimizer_type:\n return\n raise NotImplementedError(\n f\"Missing test case for subtype {test_case_subtype} for Optimizer class {mlos_bench_optimizer_type}\")\n\n# Being a little lazy for the moment and relaxing the requirement that we have\n# a subtype test case for each optimizer and space adapter combo.\n\n\[email protected](\"test_case_type\", sorted(TEST_CASES.by_type))\n# @pytest.mark.parametrize(\"test_case_subtype\", sorted(TEST_CASES.by_subtype))\[email protected](\"mlos_core_optimizer_type\", expected_mlos_core_optimizer_types)\ndef test_case_coverage_mlos_core_optimizer_type(test_case_type: str,\n mlos_core_optimizer_type: Optional[OptimizerType]) -> None:\n \"\"\"\n Checks to see if there is a given type of test case for the given mlos_core optimizer type.\n \"\"\"\n optimizer_name = None if mlos_core_optimizer_type is None else mlos_core_optimizer_type.name\n for test_case in TEST_CASES.by_type[test_case_type].values():\n if try_resolve_class_name(test_case.config.get(\"class\")) \\\n == \"mlos_bench.optimizers.mlos_core_optimizer.MlosCoreOptimizer\":\n optimizer_type = None\n if test_case.config.get(\"config\"):\n optimizer_type = test_case.config[\"config\"].get(\"optimizer_type\", None)\n if optimizer_type == optimizer_name:\n return\n raise NotImplementedError(\n f\"Missing test case for type {test_case_type} for MlosCore Optimizer type {mlos_core_optimizer_type}\")\n\n\[email protected](\"test_case_type\", sorted(TEST_CASES.by_type))\n# @pytest.mark.parametrize(\"test_case_subtype\", sorted(TEST_CASES.by_subtype))\[email protected](\"mlos_core_space_adapter_type\", expected_mlos_core_space_adapter_types)\ndef test_case_coverage_mlos_core_space_adapter_type(test_case_type: str,\n mlos_core_space_adapter_type: Optional[SpaceAdapterType]) -> None:\n \"\"\"\n Checks to see if there is a given type of test case for the given mlos_core space adapter type.\n \"\"\"\n space_adapter_name = None if mlos_core_space_adapter_type is None else mlos_core_space_adapter_type.name\n for test_case in TEST_CASES.by_type[test_case_type].values():\n if try_resolve_class_name(test_case.config.get(\"class\")) \\\n == \"mlos_bench.optimizers.mlos_core_optimizer.MlosCoreOptimizer\":\n space_adapter_type = None\n if test_case.config.get(\"config\"):\n space_adapter_type = test_case.config[\"config\"].get(\"space_adapter_type\", None)\n if space_adapter_type == space_adapter_name:\n return\n raise NotImplementedError(\n f\"Missing test case for type {test_case_type} for SpaceAdapter type {mlos_core_space_adapter_type}\")\n\n\n# Now we actually perform all of those validation tests.\n\[email protected](\"test_case_name\", sorted(TEST_CASES.by_path))\ndef test_optimizer_configs_against_schema(test_case_name: str) -> None:\n \"\"\"\n Checks that the optimizer config validates against the schema.\n \"\"\"\n check_test_case_against_schema(TEST_CASES.by_path[test_case_name], ConfigSchema.OPTIMIZER)\n\n\[email protected](\"test_case_name\", sorted(TEST_CASES.by_type[\"good\"]))\ndef test_optimizer_configs_with_extra_param(test_case_name: str) -> None:\n \"\"\"\n Checks that the optimizer config fails to validate if extra params are present in certain places.\n \"\"\"\n check_test_case_config_with_extra_param(TEST_CASES.by_type[\"good\"][test_case_name], ConfigSchema.OPTIMIZER)\n" }, { "alpha_fraction": 0.6055349111557007, "alphanum_fraction": 0.6055349111557007, "avg_line_length": 36.53488540649414, "blob_id": "e6c1da069fb5083d60e45b0825e29a52449daaf8", "content_id": "693cf71818106f318af48e63fa209b6363e1468b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4842, "license_type": "permissive", "max_line_length": 111, "num_lines": 129, "path": "/mlos_bench/mlos_bench/services/types/config_loader_type.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nProtocol interface for helper functions to lookup and load configs.\n\"\"\"\n\nfrom typing import Dict, List, Iterable, Optional, Union, Protocol, runtime_checkable, TYPE_CHECKING\n\nfrom mlos_bench.config.schemas import ConfigSchema\nfrom mlos_bench.tunables.tunable import TunableValue\n\n\n# Avoid's circular import issues.\nif TYPE_CHECKING:\n from mlos_bench.tunables.tunable_groups import TunableGroups\n from mlos_bench.services.base_service import Service\n from mlos_bench.environments.base_environment import Environment\n\n\n@runtime_checkable\nclass SupportsConfigLoading(Protocol):\n \"\"\"\n Protocol interface for helper functions to lookup and load configs.\n \"\"\"\n\n def resolve_path(self, file_path: str,\n extra_paths: Optional[Iterable[str]] = None) -> str:\n \"\"\"\n Prepend the suitable `_config_path` to `path` if the latter is not absolute.\n If `_config_path` is `None` or `path` is absolute, return `path` as is.\n\n Parameters\n ----------\n file_path : str\n Path to the input config file.\n extra_paths : Iterable[str]\n Additional directories to prepend to the list of search paths.\n\n Returns\n -------\n path : str\n An actual path to the config or script.\n \"\"\"\n\n def load_config(self, json_file_name: str, schema_type: Optional[ConfigSchema]) -> Union[dict, List[dict]]:\n \"\"\"\n Load JSON config file. Search for a file relative to `_config_path`\n if the input path is not absolute.\n This method is exported to be used as a service.\n\n Parameters\n ----------\n json_file_name : str\n Path to the input config file.\n schema_type : Optional[ConfigSchema]\n The schema type to validate the config against.\n\n Returns\n -------\n config : Union[dict, List[dict]]\n Free-format dictionary that contains the configuration.\n \"\"\"\n\n def build_environment(self, # pylint: disable=too-many-arguments\n config: dict,\n tunables: \"TunableGroups\",\n global_config: Optional[dict] = None,\n parent_args: Optional[Dict[str, TunableValue]] = None,\n service: Optional[\"Service\"] = None) -> \"Environment\":\n \"\"\"\n Factory method for a new environment with a given config.\n\n Parameters\n ----------\n config : dict\n A dictionary with three mandatory fields:\n \"name\": Human-readable string describing the environment;\n \"class\": FQN of a Python class to instantiate;\n \"config\": Free-format dictionary to pass to the constructor.\n tunables : TunableGroups\n A (possibly empty) collection of groups of tunable parameters for\n all environments.\n global_config : Optional[dict]\n Global parameters to add to the environment config.\n parent_args : Optional[Dict[str, TunableValue]]\n An optional reference of the parent CompositeEnv's const_args used to\n expand dynamic config parameters from.\n service: Optional[Service]\n An optional service object (e.g., providing methods to\n deploy or reboot a VM, etc.).\n\n Returns\n -------\n env : Environment\n An instance of the `Environment` class initialized with `config`.\n \"\"\"\n\n def load_environment_list( # pylint: disable=too-many-arguments\n self,\n json_file_name: str,\n tunables: \"TunableGroups\",\n global_config: Optional[dict] = None,\n parent_args: Optional[Dict[str, TunableValue]] = None,\n service: Optional[\"Service\"] = None) -> List[\"Environment\"]:\n \"\"\"\n Load and build a list of environments from the config file.\n\n Parameters\n ----------\n json_file_name : str\n The environment JSON configuration file.\n Can contain either one environment or a list of environments.\n tunables : TunableGroups\n A (possibly empty) collection of tunables to add to the environment.\n global_config : Optional[dict]\n Global parameters to add to the environment config.\n parent_args : Optional[Dict[str, TunableValue]]\n An optional reference of the parent CompositeEnv's const_args used to\n expand dynamic config parameters from.\n service : Optional[Service]\n An optional reference of the parent service to mix in.\n\n Returns\n -------\n env : List[Environment]\n A list of new benchmarking environments.\n \"\"\"\n" }, { "alpha_fraction": 0.7122448682785034, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 27.823530197143555, "blob_id": "b6c43fe5674ecc1e9ece3bb85b156f74266df04a", "content_id": "55a485e951f04bc2cc4fb779935fe18124b105c7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 490, "license_type": "permissive", "max_line_length": 84, "num_lines": 17, "path": "/mlos_bench/mlos_bench/tests/tunables/tunable_group_subgroup_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTests for `TunableGroup.subgroup()` method.\n\"\"\"\n\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\n\n\ndef test_tunable_group_subgroup(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Check that the subgroup() method returns only a selection of tunable parameters.\n \"\"\"\n tunables = tunable_groups.subgroup([\"provision\"])\n assert tunables.get_param_values() == {'vmSize': 'Standard_B4ms'}\n" }, { "alpha_fraction": 0.6008878350257874, "alphanum_fraction": 0.6008878350257874, "avg_line_length": 32.94520568847656, "blob_id": "a6240edd218fc3c45a8a6a8eabb4c1314952a330", "content_id": "0f3b27bdc020973a36f1f91fb689a4858c9df2f2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2478, "license_type": "permissive", "max_line_length": 75, "num_lines": 73, "path": "/mlos_bench/mlos_bench/storage/sql/storage.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nSaving and restoring the benchmark data in SQL database.\n\"\"\"\n\nimport logging\nfrom typing import Optional\n\nfrom sqlalchemy import URL, create_engine\n\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\nfrom mlos_bench.services.base_service import Service\nfrom mlos_bench.storage.base_storage import Storage\nfrom mlos_bench.storage.sql.schema import DbSchema\nfrom mlos_bench.storage.sql.experiment import Experiment\n\n_LOG = logging.getLogger(__name__)\n\n\nclass SqlStorage(Storage):\n \"\"\"\n An implementation of the Storage interface using SQLAlchemy backend.\n \"\"\"\n\n def __init__(self,\n tunables: TunableGroups,\n config: dict,\n global_config: Optional[dict] = None,\n service: Optional[Service] = None):\n super().__init__(tunables, config, global_config, service)\n lazy_schema_create = self._config.pop(\"lazy_schema_create\", False)\n self._log_sql = self._config.pop(\"log_sql\", False)\n self._url = URL.create(**self._config)\n self._repr = f\"{self._url.get_backend_name()}:{self._url.database}\"\n _LOG.info(\"Connect to the database: %s\", self)\n self._engine = create_engine(self._url, echo=self._log_sql)\n self._db_schema: DbSchema\n if not lazy_schema_create:\n assert self._schema\n else:\n _LOG.info(\"Using lazy schema create for database: %s\", self)\n\n @property\n def _schema(self) -> DbSchema:\n \"\"\"Lazily create schema upon first access.\"\"\"\n if not hasattr(self, '_db_schema'):\n self._db_schema = DbSchema(self._engine).create()\n if _LOG.isEnabledFor(logging.DEBUG):\n _LOG.debug(\"DDL statements:\\n%s\", self._schema)\n return self._db_schema\n\n def __repr__(self) -> str:\n return self._repr\n\n def experiment(self, *,\n experiment_id: str,\n trial_id: int,\n root_env_config: str,\n description: str,\n opt_target: str) -> Storage.Experiment:\n return Experiment(\n engine=self._engine,\n schema=self._schema,\n tunables=self._tunables,\n experiment_id=experiment_id,\n trial_id=trial_id,\n root_env_config=root_env_config,\n description=description,\n opt_target=opt_target,\n )\n" }, { "alpha_fraction": 0.6661016941070557, "alphanum_fraction": 0.6661016941070557, "avg_line_length": 31.77777862548828, "blob_id": "d4b0bbd56aed7024488b77da77d4beb305f2a48f", "content_id": "a7a2d9dbd00f964efba54b881565e25400f518e9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2950, "license_type": "permissive", "max_line_length": 95, "num_lines": 90, "path": "/mlos_bench/mlos_bench/tests/environments/local/__init__.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTests for mlos_bench.environments.local.\nUsed to make mypy happy about multiple conftest.py modules.\n\"\"\"\nfrom datetime import datetime\nfrom typing import Any, Dict, List, Tuple\n\nimport pytest\n\nfrom mlos_bench.environments.local.local_env import LocalEnv\nfrom mlos_bench.services.config_persistence import ConfigPersistenceService\nfrom mlos_bench.services.local.local_exec import LocalExecService\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\n\n\ndef create_local_env(tunable_groups: TunableGroups, config: Dict[str, Any]) -> LocalEnv:\n \"\"\"\n Create a LocalEnv with the given configuration.\n\n Parameters\n ----------\n tunable_groups : TunableGroups\n Tunable parameters (usually come from a fixture).\n config : Dict[str, Any]\n Environment configuration.\n\n Returns\n -------\n local_env : LocalEnv\n A new instance of the local environment.\n \"\"\"\n return LocalEnv(name=\"TestLocalEnv\", config=config, tunables=tunable_groups,\n service=LocalExecService(parent=ConfigPersistenceService()))\n\n\ndef check_local_env_success(local_env: LocalEnv,\n tunable_groups: TunableGroups,\n expected_results: Dict[str, float],\n expected_telemetry: List[Tuple[datetime, str, Any]]) -> None:\n \"\"\"\n Set up a local environment and run a test experiment there.\n\n Parameters\n ----------\n tunable_groups : TunableGroups\n Tunable parameters (usually come from a fixture).\n local_env : LocalEnv\n A local environment to query for the results.\n expected_results : Dict[str, float]\n Expected results of the benchmark.\n expected_telemetry : List[Tuple[datetime, str, Any]]\n Expected telemetry data of the benchmark.\n \"\"\"\n with local_env as env_context:\n\n assert env_context.setup(tunable_groups)\n\n (status, data) = env_context.run()\n assert status.is_succeeded()\n assert data == pytest.approx(expected_results, nan_ok=True)\n\n (status, telemetry) = env_context.status()\n assert status.is_good()\n assert telemetry == pytest.approx(expected_telemetry, nan_ok=True)\n\n\ndef check_local_env_fail_telemetry(local_env: LocalEnv, tunable_groups: TunableGroups) -> None:\n \"\"\"\n Set up a local environment and run a test experiment there;\n Make sure the environment `.status()` call fails.\n\n Parameters\n ----------\n tunable_groups : TunableGroups\n Tunable parameters (usually come from a fixture).\n local_env : LocalEnv\n A local environment to query for the results.\n \"\"\"\n with local_env as env_context:\n\n assert env_context.setup(tunable_groups)\n (status, _data) = env_context.run()\n assert status.is_succeeded()\n\n with pytest.raises(ValueError):\n env_context.status()\n" }, { "alpha_fraction": 0.6190913319587708, "alphanum_fraction": 0.6259751915931702, "avg_line_length": 34.14516067504883, "blob_id": "c65dffb77beef264e01cf39f489bdd749487cfed", "content_id": "b636cd41cc80a501c1e23c97be167fb6de2b382e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2179, "license_type": "permissive", "max_line_length": 135, "num_lines": 62, "path": "/mlos_bench/mlos_bench/config/environments/apps/redis/scripts/remote/common.sh", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "##\n## Copyright (c) Microsoft Corporation.\n## Licensed under the MIT License.\n##\n\nREDIS_IMAGE='redis:7.0'\nREDIS_PORT='6379'\nREDIS_SERVER_NAME='redis-server'\nREDIS_CLIENT_NAME='redis-client'\n\nif [ -z \"${REDIS_SERVER_HOST:-}\" ]; then\n # If not provided, assume that the client and server containers are run on the same host.\n # NOTE: In setup-app.sh we expose the server port on the host so we can connect to the host from the client.\n if grep WSL2 /proc/version 2>/dev/null; then\n # In the case of WSL2, the docker containers run in a different VM than the typical CLI,\n # so we have to connect to the host machine instead\n # (which we infer from the WSL2 VM's gateway address).\n REDIS_SERVER_HOST=$(ip route show | grep '^default via ' | awk '{ print $3 }')\n else\n REDIS_SERVER_HOST=$(hostname -f)\n fi\nfi\n\ncheck_root() {\n if [ $EUID != 0 ]; then\n echo \"ERROR: This script expects to be executed with root privileges.\" >&2\n exit 1\n fi\n}\n\ncheck_docker() {\n if ! hash docker 2>/dev/null; then\n check_root\n\n # Taken from https://docs.docker.com/engine/install/ubuntu/#install-using-the-repository\n distro=$(lsb_release -is | tr '[:upper:]' '[:lower:]')\n\n # Remove any older versions\n apt-get remove docker docker-engine docker.io containerd runc || true\n\n # Allow apt to use a repo over HTTPS\n apt-get update\n apt-get -y install \\\n ca-certificates \\\n curl \\\n gnupg \\\n lsb-release\n\n # Add Docker's official GPG key\n mkdir -p /etc/apt/keyrings\n curl -fsSL https://download.docker.com/linux/$distro/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg\n\n # Set up the repo\n echo \\\n \"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/$distro \\\n $(lsb_release -cs) stable\" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null\n\n # Install latest version of Docker Engine and related\n apt-get update\n apt-get -y install docker-ce docker-ce-cli containerd.io\n fi\n}\n" }, { "alpha_fraction": 0.7614002823829651, "alphanum_fraction": 0.7614002823829651, "avg_line_length": 62.85293960571289, "blob_id": "0212366c58bd0bd126049e19aa3a449b3c1233b8", "content_id": "3a3cfdb6a52d44aea935c2dbe91129e38291cb27", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2171, "license_type": "permissive", "max_line_length": 171, "num_lines": 34, "path": "/mlos_bench/mlos_bench/environments/README.md", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "# Environments\n\n## Overview\n\nThis directory contains the code for the [`Environment`](./base_environment.py) classes used in the [`mlos_bench`](../../../mlos_bench/) benchmarking automation framework.\nAn [`Environment`](./base_environment.py) is a class that represents a system that can be benchmarked.\nIt is responsible for setting up a portion of the system, running the benchmark (or some other command), and tearing down that portion of the system.\nA `CompositeEnvironment` can be used to stack these together to represent the entire system under evaluation (e.g., VM, OS, App, etc.)\nEach `Environment` object also keeps track of the current state of the system, and can be used to query the system for metrics.\n\nEnvironments can have [`Tunable`](../tunables/tunable.py) parameters and [`TunableGroups`](../tunables/tunable_groups.py) for controlling their configuration.\nIt is generally expected that all [`Tunable`](../tunables/tunable.py) parameters within an `Environment` will have the same cost to change.\n> It may therefore make sense to split a portion of the system logically across `Environments` (e.g., boot-time vs. runtime settings).\n\nCommon and platform-specific functionality of the environments is implemented in [`Service`](../services/) classes.\n\n## Lifecycle\n\nEach Environment has several stages that it goes through:\n\n- `setup`\n- `run`\n- `teardown`\n\nOne can also query the current state of the system via the `.status()` method.\nOur current implementation of the `Environment` classes is synchronous; that means, a `.status()` method can only be used *after* `.run()` method has been called.\n\nOnce we implement an asynchronous mode of operation, the `.status()` method will be usable at any time during the `Environment` object lifecycle.\n\n## Composite Environments\n\nEnvironments can be stacked via the [`CompositeEnv`](./composite_env.py) class.\nFor instance, a VM, OS, and Application Environment can be stacked together to form a full benchmarking environment, each with their own tunables.\nThus one may represent a system by multiple `Environment` objects, e.g., [`VMEnv`](./remote/vm_env.py), [`RemoteEnv`](remote/remote_env.py), and so on.\n" }, { "alpha_fraction": 0.5903367400169373, "alphanum_fraction": 0.6105417013168335, "avg_line_length": 34.20618438720703, "blob_id": "aa768fa8bd7bc88ed0a53de646630765b9420131", "content_id": "4551372f708e9d14e6cccca6a83b750f519bfe01", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3415, "license_type": "permissive", "max_line_length": 94, "num_lines": 97, "path": "/mlos_bench/mlos_bench/tests/environments/mock_env_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nUnit tests for mock benchmark environment.\n\"\"\"\nimport pytest\n\nfrom mlos_bench.environments.mock_env import MockEnv\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\n\n\ndef test_mock_env_default(mock_env: MockEnv, tunable_groups: TunableGroups) -> None:\n \"\"\"\n Check the default values of the mock environment.\n \"\"\"\n with mock_env as env_context:\n assert env_context.setup(tunable_groups)\n (status, data) = env_context.run()\n assert status.is_succeeded()\n assert data is not None\n assert data[\"score\"] == pytest.approx(73.97, 0.01)\n # Second time, results should differ because of the noise.\n (status, data) = env_context.run()\n assert status.is_succeeded()\n assert data is not None\n assert data[\"score\"] == pytest.approx(72.92, 0.01)\n\n\ndef test_mock_env_no_noise(mock_env_no_noise: MockEnv, tunable_groups: TunableGroups) -> None:\n \"\"\"\n Check the default values of the mock environment.\n \"\"\"\n with mock_env_no_noise as env_context:\n assert env_context.setup(tunable_groups)\n for _ in range(10):\n # Noise-free results should be the same every time.\n (status, data) = env_context.run()\n assert status.is_succeeded()\n assert data is not None\n assert data[\"score\"] == pytest.approx(75.0, 0.01)\n\n\[email protected](('tunable_values', 'expected_score'), [\n ({\n \"vmSize\": \"Standard_B2ms\",\n \"idle\": \"halt\",\n \"kernel_sched_migration_cost_ns\": 250000\n }, 66.4),\n ({\n \"vmSize\": \"Standard_B4ms\",\n \"idle\": \"halt\",\n \"kernel_sched_migration_cost_ns\": 40000\n }, 74.06),\n])\ndef test_mock_env_assign(mock_env: MockEnv, tunable_groups: TunableGroups,\n tunable_values: dict, expected_score: float) -> None:\n \"\"\"\n Check the benchmark values of the mock environment after the assignment.\n \"\"\"\n with mock_env as env_context:\n tunable_groups.assign(tunable_values)\n assert env_context.setup(tunable_groups)\n (status, data) = env_context.run()\n assert status.is_succeeded()\n assert data is not None\n assert data[\"score\"] == pytest.approx(expected_score, 0.01)\n\n\[email protected](('tunable_values', 'expected_score'), [\n ({\n \"vmSize\": \"Standard_B2ms\",\n \"idle\": \"halt\",\n \"kernel_sched_migration_cost_ns\": 250000\n }, 67.5),\n ({\n \"vmSize\": \"Standard_B4ms\",\n \"idle\": \"halt\",\n \"kernel_sched_migration_cost_ns\": 40000\n }, 75.1),\n])\ndef test_mock_env_no_noise_assign(mock_env_no_noise: MockEnv,\n tunable_groups: TunableGroups,\n tunable_values: dict, expected_score: float) -> None:\n \"\"\"\n Check the benchmark values of the noiseless mock environment after the assignment.\n \"\"\"\n with mock_env_no_noise as env_context:\n tunable_groups.assign(tunable_values)\n assert env_context.setup(tunable_groups)\n for _ in range(10):\n # Noise-free environment should produce the same results every time.\n (status, data) = env_context.run()\n assert status.is_succeeded()\n assert data is not None\n assert data[\"score\"] == pytest.approx(expected_score, 0.01)\n" }, { "alpha_fraction": 0.6352530717849731, "alphanum_fraction": 0.6352530717849731, "avg_line_length": 19.464284896850586, "blob_id": "28e6cc360fed6045060fff54117e2b6c40386ea6", "content_id": "3e3faea742cbf4dcc68536d3928fea25a9562afc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 573, "license_type": "permissive", "max_line_length": 65, "num_lines": 28, "path": "/mlos_bench/mlos_bench/services/types/authenticator_type.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nProtocol interface for authentication for the cloud services.\n\"\"\"\n\nfrom typing import Protocol, runtime_checkable\n\n\n@runtime_checkable\nclass SupportsAuth(Protocol):\n \"\"\"\n Protocol interface for authentication for the cloud services.\n \"\"\"\n\n # pylint: disable=too-few-public-methods\n\n def get_access_token(self) -> str:\n \"\"\"\n Get the access token for cloud services.\n\n Returns\n -------\n access_token : str\n Access token.\n \"\"\"\n" }, { "alpha_fraction": 0.7514451146125793, "alphanum_fraction": 0.7514451146125793, "avg_line_length": 52.230770111083984, "blob_id": "c45452b54bdeabcdd2629f4f8c09343675c7b65b", "content_id": "125b71be46be8b2dc1150d1454606d5e91381e16", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 692, "license_type": "permissive", "max_line_length": 212, "num_lines": 13, "path": "/mlos_bench/mlos_bench/services/README.md", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "# Services\n\nServices are essentially a collection of helper functions used to `setup`, `run`, and `teardown` an [`Environment`](../environments/) in the [`mlos_bench`](../../../mlos_bench/) benchmarking automation framework.\n\nThey are (roughly) divided into two categories:\n\n- `LocalService` - A service that runs on the same machine as the scheduler component.\n\n This may be things like executing a script for parsing the results of a benchmark run using local tools that aren't necessarily available on the target system.\n\n- `RemoteService` - A service that runs on a remote (target) machine.\n\n This may be things like executing a script on a remote machine to start a benchmark run.\n" }, { "alpha_fraction": 0.6010638475418091, "alphanum_fraction": 0.7393617033958435, "avg_line_length": 17.799999237060547, "blob_id": "a7b99c0babe270cf533aa7e1420ad2d79ef2e200", "content_id": "185c9d5135fe669777a74e36a9c6eace67403913", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 188, "license_type": "permissive", "max_line_length": 71, "num_lines": 10, "path": "/doc/requirements.txt", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "sphinx\nnbsphinx\njupyter_core>=4.11.2 # nbsphix dependency - addresses CVE-2022-39286\nnbconvert\nmistune>=2.0.3 # Address CVE-2022-34749\nnumpydoc\nsphinx-rtd-theme\n\ndoc8\nrstcheck\n" }, { "alpha_fraction": 0.7067307829856873, "alphanum_fraction": 0.7074176073074341, "avg_line_length": 33.66666793823242, "blob_id": "e2bb8ca450d509f80eddf09c1bd2e6aa81f846b1", "content_id": "ef7aaf2fa11159598cf9af26efbab2bd4bf1a2a9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1456, "license_type": "permissive", "max_line_length": 109, "num_lines": 42, "path": "/mlos_core/mlos_core/tests/optimizers/bayesian_optimizers_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTests for Bayesian Optimizers.\n\"\"\"\n\nfrom typing import Optional, Type\n\nimport pytest\n\nimport pandas as pd\nimport ConfigSpace as CS\n\nfrom mlos_core.optimizers import BaseOptimizer, OptimizerType\nfrom mlos_core.optimizers.bayesian_optimizers import BaseBayesianOptimizer\n\n\[email protected](('optimizer_class', 'kwargs'), [\n *[(member.value, {}) for member in OptimizerType],\n])\ndef test_context_not_implemented_error(configuration_space: CS.ConfigurationSpace,\n optimizer_class: Type[BaseOptimizer], kwargs: Optional[dict]) -> None:\n \"\"\"\n Make sure we raise exceptions for the functionality that has not been implemented yet.\n \"\"\"\n if kwargs is None:\n kwargs = {}\n optimizer = optimizer_class(parameter_space=configuration_space, **kwargs)\n suggestion = optimizer.suggest()\n scores = pd.DataFrame({'score': [1]})\n # test context not implemented errors\n with pytest.raises(NotImplementedError):\n optimizer.register(suggestion, scores['score'], context=pd.DataFrame([[\"something\"]]))\n\n with pytest.raises(NotImplementedError):\n optimizer.suggest(context=pd.DataFrame([[\"something\"]]))\n\n if isinstance(optimizer, BaseBayesianOptimizer):\n with pytest.raises(NotImplementedError):\n optimizer.surrogate_predict(suggestion, context=pd.DataFrame([[\"something\"]]))\n" }, { "alpha_fraction": 0.6481481194496155, "alphanum_fraction": 0.6535947918891907, "avg_line_length": 24.5, "blob_id": "d071ddfafaa28c3664e21337ebb8fc3ae5c8ab45", "content_id": "d3de677142a70b730c7cfe25c0da5fd246581cfc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 918, "license_type": "permissive", "max_line_length": 80, "num_lines": 36, "path": "/mlos_bench/mlos_bench/tests/storage/conftest.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTest fixtures for mlos_bench storage.\n\"\"\"\n\nimport pytest\n\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\nfrom mlos_bench.storage.base_storage import Storage\nfrom mlos_bench.storage.sql.storage import SqlStorage\n\n\[email protected]\ndef exp_storage_memory_sql(tunable_groups: TunableGroups) -> Storage.Experiment:\n \"\"\"\n Test fixture for in-memory SQLite3 storage.\n \"\"\"\n storage = SqlStorage(\n tunables=tunable_groups,\n service=None,\n config={\n \"drivername\": \"sqlite\",\n \"database\": \":memory:\",\n }\n )\n # pylint: disable=unnecessary-dunder-call\n return storage.experiment(\n experiment_id=\"Test-001\",\n trial_id=1,\n root_env_config=\"environment.jsonc\",\n description=\"pytest experiment\",\n opt_target=\"score\",\n ).__enter__()\n" }, { "alpha_fraction": 0.7080564498901367, "alphanum_fraction": 0.7167773842811584, "avg_line_length": 27.32941246032715, "blob_id": "88008add50daa44e888a683413403b20f1d378dd", "content_id": "a890f238f74f6d0f66b684412dc291e712dd56fc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 2408, "license_type": "permissive", "max_line_length": 192, "num_lines": 85, "path": "/doc/source/installation.rst", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "Installation\n============\n\nDevelopment\n-----------\n\nThe development environment for MLOS uses ``conda`` to ease dependency management.\n\nDevcontainer\n------------\n\nFor a quick start, you can use the provided `VSCode devcontainer <https://code.visualstudio.com/docs/remote/containers>`_ configuration.\n\nSimply open the project in VSCode and follow the prompts to build and open the devcontainer and the conda environment and additional tools will be installed automatically inside the container.\n\nManually\n--------\n\n .. note::\n See Also: `conda install instructions <https://docs.conda.io/projects/conda/en/latest/user-guide/install/index.html>`_\n\n Note: to support Windows we rely on some pre-compiled packages from `conda-forge` channels, which increases the `conda` solver time during environment create/update.\n\n To work around this the (currently) experimental `libmamba` solver can be used.\n\n See `<https://github.com/conda-incubator/conda-libmamba-solver#getting-started>`_ for more details.\n\n\n0. Create the `mlos` Conda environment.\n\n .. code-block:: shell\n\n conda env create -f conda-envs/mlos.yml\n\n\n .. note::\n See the `conda-envs/` directory for additional conda environment files, including those used for Windows (e.g. `conda-envs/mlos-windows.yml`).\n\n\n or\n\n .. code-block:: shell\n\n # This will also ensure the environment is update to date using \"conda env update -f conda-envs/mlos.yml\"\n make conda-env\n\n\n1. Initialize the shell environment.\n\n .. code-block:: shell\n\n conda activate mlos\n\n2. Run the BayesianOptimization.ipynb notebook.\n\nDistributing\n------------\n\n1. Build the *wheel* file(s).\n\n .. code-block:: shell\n\n make dist\n\n2. Install it (e.g. after copying it somewhere else).\n\n .. code-block:: shell\n\n # this will install just the optimizer component with SMAC support:\n pip install dist/mlos_core-0.1.0-py3-none-any.whl[smac]\n\n # this will install just the optimizer component with flaml support:\n pip install dist/mlos_core-0.1.0-py3-none-any.whl[flaml]\n\n # this will install just the optimizer component with smac and flaml support:\n pip install dist/mlos_core-0.1.0-py3-none-any.whl[smac,flaml]\n\n .. code-block:: shell\n\n # this will install both the optimizer and the experiment runner:\n pip install dist/mlos_bench-0.1.0-py3-none-any.whl\n\n .. note::\n\n Note: exact versions may differ due to automatic versioning.\n" }, { "alpha_fraction": 0.7057142853736877, "alphanum_fraction": 0.7057142853736877, "avg_line_length": 69, "blob_id": "e2dd24f14768579720c6bc6acfaa3e686fa99ee4", "content_id": "7a1c2f4289e5bd36a3c8f319117d9b2279071ac5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 350, "license_type": "permissive", "max_line_length": 207, "num_lines": 5, "path": "/mlos_bench/mlos_bench/optimizers/README.md", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "# Optimizers\n\nThis directory contains a small collection of optimizer shims that can be used in [`mlos_bench`](../../../mlos_bench/) to help optimize the [`Tunables`](../tunables/) in an [`Environment`](../environments/).\n\nIn general, we expect that the optimizer will be one provided by the [`mlos_core`](../../../mlos_core/) optimizer abstraction.\n" }, { "alpha_fraction": 0.6076579093933105, "alphanum_fraction": 0.6076579093933105, "avg_line_length": 30.920635223388672, "blob_id": "9d8a5adeaa97f68d96b684aee054eb4633e4a1b8", "content_id": "8dd41e51a817029e5ebf4c8cd1ab2d5be9ff3adc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2011, "license_type": "permissive", "max_line_length": 80, "num_lines": 63, "path": "/mlos_bench/mlos_bench/services/types/remote_exec_type.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nProtocol interface for Service types that provide helper functions to run\nscripts on a remote host OS.\n\"\"\"\n\nfrom typing import Iterable, Tuple, Protocol, runtime_checkable, TYPE_CHECKING\n\nif TYPE_CHECKING:\n from mlos_bench.environments.status import Status\n\n\n@runtime_checkable\nclass SupportsRemoteExec(Protocol):\n \"\"\"\n Protocol interface for Service types that provide helper functions to run\n scripts on a remote host OS.\n \"\"\"\n\n def remote_exec(self, script: Iterable[str], config: dict,\n env_params: dict) -> Tuple[\"Status\", dict]:\n \"\"\"\n Run a command on remote host OS.\n\n Parameters\n ----------\n script : Iterable[str]\n A list of lines to execute as a script on a remote VM.\n config : dict\n Flat dictionary of (key, value) pairs of parameters.\n They usually come from `const_args` and `tunable_params`\n properties of the Environment.\n env_params : dict\n Parameters to pass as *shell* environment variables into the script.\n This is usually a subset of `config` with some possible conversions.\n\n Returns\n -------\n result : (Status, dict)\n A pair of Status and result.\n Status is one of {PENDING, SUCCEEDED, FAILED}\n \"\"\"\n\n def get_remote_exec_results(self, config: dict) -> Tuple[\"Status\", dict]:\n \"\"\"\n Get the results of the asynchronously running command.\n\n Parameters\n ----------\n config : dict\n Flat dictionary of (key, value) pairs of tunable parameters.\n Must have the \"asyncResultsUrl\" key to get the results.\n If the key is not present, return Status.PENDING.\n\n Returns\n -------\n result : (Status, dict)\n A pair of Status and result.\n Status is one of {PENDING, SUCCEEDED, FAILED, TIMED_OUT}\n \"\"\"\n" }, { "alpha_fraction": 0.6693462133407593, "alphanum_fraction": 0.673097550868988, "avg_line_length": 30.627119064331055, "blob_id": "1e4a57f7bc668fb82fd1df770a001e37366cf78f", "content_id": "7283e48f1ca73389fdfcb240e9cd66842406d1ae", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1866, "license_type": "permissive", "max_line_length": 124, "num_lines": 59, "path": "/mlos_core/mlos_core/tests/__init__.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nCommon functions for mlos_core Optimizer tests.\n\"\"\"\n\nimport sys\n\nfrom importlib import import_module\nfrom pkgutil import walk_packages\nfrom typing import List, Optional, Set, Type, TypeVar\n\n\nif sys.version_info >= (3, 10):\n from typing import TypeAlias\nelse:\n from typing_extensions import TypeAlias\n\n\nT = TypeVar('T')\n\n\ndef get_all_submodules(pkg: TypeAlias) -> List[str]:\n \"\"\"\n Imports all submodules for a package and returns their names.\n Useful for dynamically enumerating subclasses.\n \"\"\"\n submodules = []\n for _, submodule_name, _ in walk_packages(pkg.__path__, prefix=f\"{pkg.__name__}.\", onerror=lambda x: None):\n submodules.append(submodule_name)\n return submodules\n\n\ndef _get_all_subclasses(cls: Type[T]) -> Set[Type[T]]:\n \"\"\"\n Gets the set of all of the subclasses of the given class.\n Useful for dynamically enumerating expected test cases.\n \"\"\"\n return set(cls.__subclasses__()).union(\n s for c in cls.__subclasses__() for s in _get_all_subclasses(c))\n\n\ndef get_all_concrete_subclasses(cls: Type[T], pkg_name: Optional[str] = None) -> List[Type[T]]:\n \"\"\"\n Gets a sorted list of all of the concrete subclasses of the given class.\n Useful for dynamically enumerating expected test cases.\n\n Note: For abstract types, mypy will complain at the call site.\n Use \"# type: ignore[type-abstract]\" to suppress the warning.\n See Also: https://github.com/python/mypy/issues/4717\n \"\"\"\n if pkg_name is not None:\n pkg = import_module(pkg_name)\n submodules = get_all_submodules(pkg)\n assert submodules\n return sorted([subclass for subclass in _get_all_subclasses(cls) if not getattr(subclass, \"__abstractmethods__\", None)],\n key=lambda c: (c.__module__, c.__name__))\n" }, { "alpha_fraction": 0.5839603543281555, "alphanum_fraction": 0.5925858020782471, "avg_line_length": 28.775957107543945, "blob_id": "772958d7b1a08fb67e2ced6c7119fea2ce1fc89c", "content_id": "7395aa3e15c2ef5fd3be6cd7708732b1e5cbfdaa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5449, "license_type": "permissive", "max_line_length": 81, "num_lines": 183, "path": "/mlos_bench/mlos_bench/tests/environments/include_tunables_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTest the selection of tunables / tunable groups for the environment.\n\"\"\"\n\nfrom mlos_bench.environments.mock_env import MockEnv\nfrom mlos_bench.services.config_persistence import ConfigPersistenceService\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\n\n\ndef test_one_group(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Make sure only one tunable group is available to the environment.\n \"\"\"\n env = MockEnv(\n name=\"Test Env\",\n config={\"tunable_params\": [\"provision\"]},\n tunables=tunable_groups\n )\n assert env.tunable_params.get_param_values() == {\n \"vmSize\": \"Standard_B4ms\",\n }\n\n\ndef test_two_groups(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Make sure only the selected tunable groups are available to the environment.\n \"\"\"\n env = MockEnv(\n name=\"Test Env\",\n config={\"tunable_params\": [\"provision\", \"kernel\"]},\n tunables=tunable_groups\n )\n assert env.tunable_params.get_param_values() == {\n \"vmSize\": \"Standard_B4ms\",\n \"kernel_sched_migration_cost_ns\": -1,\n \"kernel_sched_latency_ns\": 2000000,\n }\n\n\ndef test_two_groups_setup(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Make sure only the selected tunable groups are available to the environment,\n the set is not changed after calling the `.setup()` method.\n \"\"\"\n env = MockEnv(\n name=\"Test Env\",\n config={\n \"tunable_params\": [\"provision\", \"kernel\"],\n \"const_args\": {\n \"const_param1\": 10,\n \"const_param2\": \"foo\",\n },\n },\n tunables=tunable_groups\n )\n expected_params = {\n \"vmSize\": \"Standard_B4ms\",\n \"kernel_sched_migration_cost_ns\": -1,\n \"kernel_sched_latency_ns\": 2000000,\n }\n assert env.tunable_params.get_param_values() == expected_params\n\n with env as env_context:\n assert env_context.setup(tunable_groups)\n\n # Make sure the set of tunables does not change after the setup:\n assert env.tunable_params.get_param_values() == expected_params\n assert env.parameters == {\n **expected_params,\n \"const_param1\": 10,\n \"const_param2\": \"foo\",\n }\n\n\ndef test_zero_groups_implicit(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Make sure that no tunable groups are available to the environment by default.\n \"\"\"\n env = MockEnv(\n name=\"Test Env\",\n config={},\n tunables=tunable_groups\n )\n assert env.tunable_params.get_param_values() == {}\n\n\ndef test_zero_groups_explicit(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Make sure that no tunable groups are available to the environment\n when explicitly specifying an empty list of tunable_params.\n \"\"\"\n env = MockEnv(\n name=\"Test Env\",\n config={\"tunable_params\": []},\n tunables=tunable_groups\n )\n assert env.tunable_params.get_param_values() == {}\n\n\ndef test_zero_groups_implicit_setup(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Make sure that no tunable groups are available to the environment by default\n and it does not change after the setup.\n \"\"\"\n env = MockEnv(\n name=\"Test Env\",\n config={\n \"const_args\": {\n \"const_param1\": 10,\n \"const_param2\": \"foo\",\n },\n },\n tunables=tunable_groups\n )\n assert env.tunable_params.get_param_values() == {}\n\n with env as env_context:\n assert env_context.setup(tunable_groups)\n\n # Make sure the set of tunables does not change after the setup:\n assert env.tunable_params.get_param_values() == {}\n assert env.parameters == {\n \"const_param1\": 10,\n \"const_param2\": \"foo\",\n }\n\n\ndef test_loader_level_include() -> None:\n \"\"\"\n Make sure only the selected tunable groups are available to the environment,\n the set is not changed after calling the `.setup()` method.\n \"\"\"\n env_json = {\n \"class\": \"mlos_bench.environments.mock_env.MockEnv\",\n \"name\": \"Test Env\",\n \"include_tunables\": [\n \"environments/os/linux/boot/linux-boot-tunables.jsonc\"\n ],\n \"config\": {\n \"tunable_params\": [\"linux-kernel-boot\"],\n \"const_args\": {\n \"const_param1\": 10,\n \"const_param2\": \"foo\",\n },\n },\n }\n loader = ConfigPersistenceService({\n \"config_path\": [\n \"mlos_bench/config\",\n \"mlos_bench/examples\",\n ]\n })\n env = loader.build_environment(config=env_json, tunables=TunableGroups())\n expected_params = {\n \"align_va_addr\": \"on\",\n \"idle\": \"halt\",\n \"ima.ahash_bufsize\": 4096,\n \"noautogroup\": \"\",\n \"nohugevmalloc\": \"\",\n \"nohalt\": \"\",\n \"nohz\": \"\",\n \"no-kvmapf\": \"\",\n \"nopvspin\": \"\",\n }\n assert env.tunable_params.get_param_values() == expected_params\n\n expected_params[\"align_va_addr\"] = \"off\"\n tunables = env.tunable_params.copy().assign({\"align_va_addr\": \"off\"})\n\n with env as env_context:\n assert env_context.setup(tunables)\n\n # Make sure the set of tunables does not change after the setup:\n assert env.parameters == {\n **expected_params,\n \"const_param1\": 10,\n \"const_param2\": \"foo\",\n }\n assert env.tunable_params.get_param_values() == expected_params\n" }, { "alpha_fraction": 0.6771378517150879, "alphanum_fraction": 0.6771378517150879, "avg_line_length": 21.038461685180664, "blob_id": "1f7fc741dfb2c6f9d9ae587ff18806c93907a025", "content_id": "ba10a11d85fc752a02dc2e01447149af65c6d49b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 573, "license_type": "permissive", "max_line_length": 75, "num_lines": 26, "path": "/mlos_core/mlos_core/__init__.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nBasic initializer module for the mlos_core package.\n\"\"\"\n\nimport ConfigSpace\nimport pandas as pd\n\n\ndef config_to_dataframe(config: ConfigSpace.Configuration) -> pd.DataFrame:\n \"\"\"Converts a ConfigSpace config to a DataFrame\n\n Parameters\n ----------\n config : ConfigSpace.Configuration\n The config to convert.\n\n Returns\n -------\n pd.DataFrame\n A DataFrame with a single row, containing the config's parameters.\n \"\"\"\n return pd.DataFrame([dict(config)])\n" }, { "alpha_fraction": 0.8013244867324829, "alphanum_fraction": 0.8013244867324829, "avg_line_length": 29.200000762939453, "blob_id": "8ab095e99a36750fbad17e0401da25fa8554aa61", "content_id": "d21545354a4184a93600b6514ba0ec31b9fd1ab7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 151, "license_type": "permissive", "max_line_length": 67, "num_lines": 5, "path": "/mlos_bench/mlos_bench/tests/config/schemas/optimizers/test-cases/README.md", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "# Optimizer Config Schema Test Cases\n\nThis directory contains test cases for the optimizer config schema.\n\n> Be cautious when using these as examples.\n" }, { "alpha_fraction": 0.7211678624153137, "alphanum_fraction": 0.7226277589797974, "avg_line_length": 23.464284896850586, "blob_id": "149920642a4d5d4305eed05cfb274be5b3ef61f0", "content_id": "7428d4b34d917b2c44b70046ffcf02b68a468d4c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 685, "license_type": "permissive", "max_line_length": 63, "num_lines": 28, "path": "/mlos_bench/mlos_bench/config/environments/os/linux/boot/scripts/remote/prepare-os-boot-time.sh", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#!/bin/bash\n##\n## Copyright (c) Microsoft Corporation.\n## Licensed under the MIT License.\n##\n\n# Script to store old grub config and reboot VM (if necessary).\n# Config file created in scheduler should have been moved to\n# VM BEFORE this script is run.\n# This script should be run in the VM.\n\nset -eu\n\nscriptdir=$(dirname \"$(readlink -f \"$0\")\")\ncd \"$scriptdir\"\nsource ./common-boot-time.sh\n\n# remove original boot time parameters file if it exists\nrm -f \"$ORIG_BOOT_TIME\"\n\n# create copy of original boot-time parameters\ncp /etc/default/grub.cfg \"$ORIG_BOOT_TIME\"\nupdate-grub\n\n# check if the real config file has changed\nif diff -u /boot/grub/grub.cfg \"$ORIG_BOOT_TIME\"; then\n reboot\nfi\n" }, { "alpha_fraction": 0.7113401889801025, "alphanum_fraction": 0.7113401889801025, "avg_line_length": 18.399999618530273, "blob_id": "4d7f9c6976108e4a76b307ec4d715c2f89910fa7", "content_id": "73daf81c3b3aad2c762c6a7d6303a74840e325bc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 291, "license_type": "permissive", "max_line_length": 84, "num_lines": 15, "path": "/mlos_bench/mlos_bench/config/schemas/__init__.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nA module for managing config schemas and their validation.\n\"\"\"\n\nfrom mlos_bench.config.schemas.config_schemas import ConfigSchema, CONFIG_SCHEMA_DIR\n\n\n__all__ = [\n 'ConfigSchema',\n 'CONFIG_SCHEMA_DIR',\n]\n" }, { "alpha_fraction": 0.72492915391922, "alphanum_fraction": 0.7286118865013123, "avg_line_length": 37.79121017456055, "blob_id": "26ebfe8aa3705a738f2af7f36b2b37d0bee53f75", "content_id": "4f0c31538f3cd52cf0b7897e3650f0ebb1d923fc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3530, "license_type": "permissive", "max_line_length": 130, "num_lines": 91, "path": "/mlos_core/mlos_core/tests/spaces/adapters/space_adapter_factory_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTests for space adapter factory.\n\"\"\"\n\n# pylint: disable=missing-function-docstring\n\nfrom typing import List, Optional, Type\n\nimport pytest\n\nimport ConfigSpace as CS\n\nfrom mlos_core.spaces.adapters import SpaceAdapterFactory, SpaceAdapterType, ConcreteSpaceAdapter\nfrom mlos_core.spaces.adapters.adapter import BaseSpaceAdapter\nfrom mlos_core.spaces.adapters.identity_adapter import IdentityAdapter\n\nfrom mlos_core.tests import get_all_concrete_subclasses\n\n\[email protected](('space_adapter_type'), [\n # Enumerate all supported SpaceAdapters\n # *[member for member in SpaceAdapterType],\n *list(SpaceAdapterType),\n])\ndef test_concrete_optimizer_type(space_adapter_type: SpaceAdapterType) -> None:\n \"\"\"\n Test that all optimizer types are listed in the ConcreteOptimizer constraints.\n \"\"\"\n # pylint: disable=no-member\n assert space_adapter_type.value in ConcreteSpaceAdapter.__constraints__ # type: ignore[attr-defined]\n\n\[email protected](('space_adapter_type', 'kwargs'), [\n # Default space adapter\n (None, {}),\n # Enumerate all supported Optimizers\n *[(member, {}) for member in SpaceAdapterType],\n])\ndef test_create_space_adapter_with_factory_method(space_adapter_type: Optional[SpaceAdapterType], kwargs: Optional[dict]) -> None:\n # Start defining a ConfigurationSpace for the Optimizer to search.\n input_space = CS.ConfigurationSpace(seed=1234)\n\n # Add a single continuous input dimension between 0 and 1.\n input_space.add_hyperparameter(CS.UniformFloatHyperparameter(name='x', lower=0, upper=1))\n # Add a single continuous input dimension between 0 and 1.\n input_space.add_hyperparameter(CS.UniformFloatHyperparameter(name='y', lower=0, upper=1))\n\n # Adjust some kwargs for specific space adapters\n if space_adapter_type is SpaceAdapterType.LLAMATUNE:\n if kwargs is None:\n kwargs = {}\n kwargs.setdefault('num_low_dims', 1)\n\n space_adapter: BaseSpaceAdapter\n if space_adapter_type is None:\n space_adapter = SpaceAdapterFactory.create(parameter_space=input_space)\n else:\n space_adapter = SpaceAdapterFactory.create(\n parameter_space=input_space,\n space_adapter_type=space_adapter_type,\n space_adapter_kwargs=kwargs,\n )\n\n if space_adapter_type is None or space_adapter_type is SpaceAdapterType.IDENTITY:\n assert isinstance(space_adapter, IdentityAdapter)\n else:\n assert space_adapter is not None\n assert space_adapter.orig_parameter_space is not None\n myrepr = repr(space_adapter)\n assert myrepr.startswith(space_adapter_type.value.__name__), \\\n f\"Expected {space_adapter_type.value.__name__} but got {myrepr}\"\n\n\n# Dynamically determine all of the optimizers we have implemented.\n# Note: these must be sorted.\nspace_adapter_subclasses: List[Type[BaseSpaceAdapter]] = \\\n get_all_concrete_subclasses(BaseSpaceAdapter, pkg_name='mlos_core') # type: ignore[type-abstract]\nassert space_adapter_subclasses\n\n\[email protected](('space_adapter_class'), space_adapter_subclasses)\ndef test_space_adapter_type_defs(space_adapter_class: Type[BaseSpaceAdapter]) -> None:\n \"\"\"\n Test that all space adapter classes are listed in the SpaceAdapterType enum.\n \"\"\"\n space_adapter_type_classes = {space_adapter_type.value for space_adapter_type in SpaceAdapterType}\n assert space_adapter_class in space_adapter_type_classes\n" }, { "alpha_fraction": 0.5422777533531189, "alphanum_fraction": 0.5775846242904663, "avg_line_length": 33.73584747314453, "blob_id": "6ac8ffe5fbe767e6805d74bc223d9eb41544b7ca", "content_id": "0aa4694be878d129114cd421c8b9ac1feaf15ba6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5523, "license_type": "permissive", "max_line_length": 84, "num_lines": 159, "path": "/mlos_bench/mlos_bench/tests/environments/local/local_env_telemetry_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nUnit tests for telemetry and status of LocalEnv benchmark environment.\n\"\"\"\nfrom datetime import datetime, timedelta\n\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\nfrom mlos_bench.tests.environments.local import (\n create_local_env, check_local_env_success, check_local_env_fail_telemetry\n)\n\n\ndef test_local_env_telemetry(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Produce benchmark and telemetry data in a local script and read it.\n \"\"\"\n ts1 = datetime.utcnow()\n ts1 -= timedelta(microseconds=ts1.microsecond) # Round to a second\n ts2 = ts1 + timedelta(minutes=1)\n\n time_str1 = ts1.strftime(\"%Y-%m-%d %H:%M:%S\")\n time_str2 = ts2.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n local_env = create_local_env(tunable_groups, {\n \"run\": [\n \"echo 'metric,value' > output.csv\",\n \"echo 'latency,4.1' >> output.csv\",\n \"echo 'throughput,512' >> output.csv\",\n \"echo 'score,0.95' >> output.csv\",\n \"echo '-------------------'\", # This output does not go anywhere\n \"echo 'timestamp,metric,value' > telemetry.csv\",\n f\"echo {time_str1},cpu_load,0.65 >> telemetry.csv\",\n f\"echo {time_str1},mem_usage,10240 >> telemetry.csv\",\n f\"echo {time_str2},cpu_load,0.8 >> telemetry.csv\",\n f\"echo {time_str2},mem_usage,20480 >> telemetry.csv\",\n ],\n \"read_results_file\": \"output.csv\",\n \"read_telemetry_file\": \"telemetry.csv\",\n })\n\n check_local_env_success(\n local_env, tunable_groups,\n expected_results={\n \"latency\": 4.1,\n \"throughput\": 512.0,\n \"score\": 0.95,\n },\n expected_telemetry=[\n (ts1, \"cpu_load\", 0.65),\n (ts1, \"mem_usage\", 10240.0),\n (ts2, \"cpu_load\", 0.8),\n (ts2, \"mem_usage\", 20480.0),\n ],\n )\n\n\ndef test_local_env_telemetry_no_header(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Read the telemetry data with no header.\n \"\"\"\n ts1 = datetime.utcnow()\n ts1 -= timedelta(microseconds=ts1.microsecond) # Round to a second\n ts2 = ts1 + timedelta(minutes=1)\n\n time_str1 = ts1.strftime(\"%Y-%m-%d %H:%M:%S\")\n time_str2 = ts2.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n local_env = create_local_env(tunable_groups, {\n \"run\": [\n f\"echo {time_str1},cpu_load,0.65 > telemetry.csv\",\n f\"echo {time_str1},mem_usage,10240 >> telemetry.csv\",\n f\"echo {time_str2},cpu_load,0.8 >> telemetry.csv\",\n f\"echo {time_str2},mem_usage,20480 >> telemetry.csv\",\n ],\n \"read_telemetry_file\": \"telemetry.csv\",\n })\n\n check_local_env_success(\n local_env, tunable_groups,\n expected_results={},\n expected_telemetry=[\n (ts1, \"cpu_load\", 0.65),\n (ts1, \"mem_usage\", 10240.0),\n (ts2, \"cpu_load\", 0.8),\n (ts2, \"mem_usage\", 20480.0),\n ],\n )\n\n\ndef test_local_env_telemetry_wrong_header(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Read the telemetry data with incorrect header.\n \"\"\"\n ts1 = datetime.utcnow()\n ts1 -= timedelta(microseconds=ts1.microsecond) # Round to a second\n ts2 = ts1 + timedelta(minutes=1)\n\n time_str1 = ts1.strftime(\"%Y-%m-%d %H:%M:%S\")\n time_str2 = ts2.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n local_env = create_local_env(tunable_groups, {\n \"run\": [\n # Error: the data is correct, but the header has unexpected column names\n \"echo 'ts,metric_name,metric_value' > telemetry.csv\",\n f\"echo {time_str1},cpu_load,0.65 >> telemetry.csv\",\n f\"echo {time_str1},mem_usage,10240 >> telemetry.csv\",\n f\"echo {time_str2},cpu_load,0.8 >> telemetry.csv\",\n f\"echo {time_str2},mem_usage,20480 >> telemetry.csv\",\n ],\n \"read_telemetry_file\": \"telemetry.csv\",\n })\n\n check_local_env_fail_telemetry(local_env, tunable_groups)\n\n\ndef test_local_env_telemetry_invalid(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Fail when the telemetry data has wrong format.\n \"\"\"\n ts1 = datetime.utcnow()\n ts1 -= timedelta(microseconds=ts1.microsecond) # Round to a second\n ts2 = ts1 + timedelta(minutes=1)\n\n time_str1 = ts1.strftime(\"%Y-%m-%d %H:%M:%S\")\n time_str2 = ts2.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n local_env = create_local_env(tunable_groups, {\n \"run\": [\n # Error: too many columns\n f\"echo {time_str1},EXTRA,cpu_load,0.65 > telemetry.csv\",\n f\"echo {time_str1},EXTRA,mem_usage,10240 >> telemetry.csv\",\n f\"echo {time_str2},EXTRA,cpu_load,0.8 >> telemetry.csv\",\n f\"echo {time_str2},EXTRA,mem_usage,20480 >> telemetry.csv\",\n ],\n \"read_telemetry_file\": \"telemetry.csv\",\n })\n\n check_local_env_fail_telemetry(local_env, tunable_groups)\n\n\ndef test_local_env_telemetry_invalid_ts(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Fail when the telemetry data has wrong format.\n \"\"\"\n local_env = create_local_env(tunable_groups, {\n \"run\": [\n # Error: field 1 must be a timestamp\n \"echo 1,cpu_load,0.65 > telemetry.csv\",\n \"echo 2,mem_usage,10240 >> telemetry.csv\",\n \"echo 3,cpu_load,0.8 >> telemetry.csv\",\n \"echo 4,mem_usage,20480 >> telemetry.csv\",\n ],\n \"read_telemetry_file\": \"telemetry.csv\",\n })\n\n check_local_env_fail_telemetry(local_env, tunable_groups)\n" }, { "alpha_fraction": 0.6349557638168335, "alphanum_fraction": 0.6356931924819946, "avg_line_length": 33.769229888916016, "blob_id": "dcae1e96f7ff8655a77161e68e88c9bd5bc63015", "content_id": "af97481976e98a6bca5a87ee0b82f0ac9d58be38", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1356, "license_type": "permissive", "max_line_length": 176, "num_lines": 39, "path": "/.devcontainer/scripts/run-markdown-link-check.sh", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#!/bin/bash\n##\n## Copyright (c) Microsoft Corporation.\n## Licensed under the MIT License.\n##\n\nset -x\n\nset -eu\nscriptdir=$(dirname \"$(readlink -f \"$0\")\")\ncd \"$scriptdir/\"\n\n# Build the helper container that has the cspell CLI.\n#../build/build-devcontainer-cli.sh\n\n# Make this work inside a devcontainer as well.\nreporoot=$(readlink -f \"$scriptdir/../../\")\nif [ -n \"${LOCAL_WORKSPACE_FOLDER:-}\" ]; then\n reporoot=\"$LOCAL_WORKSPACE_FOLDER\"\nfi\n\n# Basically does what the markdown-link-check github action would do, but locally too.\n# See Also: ~/.github/workflows/markdown-link-check.yml\n\ndocker run -i --rm \\\n --user $(id -u):$(id -g) \\\n -v \"$reporoot\":/src:ro \\\n --workdir /src \\\n markdown-link-check:latest \\\n find ./doc ./mlos_core ./mlos_bench ./.devcontainer -name '*.md' -not -path './node_modules/*' \\\n -exec markdown-link-check '{}' --config ./.github/workflows/markdown-link-check-config.json -q -v ';'\n\ndocker run -i --rm \\\n --user $(id -u):$(id -g) \\\n -v \"$reporoot\":/src:ro \\\n --workdir /src \\\n markdown-link-check:latest \\\n find . -type f '(' -wholename ./CODE_OF_CONDUCT.md -o -wholename ./CONTRIBUTING.md -o -wholename ./README.md -o -wholename ./SECURITY.md ')' -not -path './node_modules/*' \\\n -exec markdown-link-check '{}' --config ./.github/workflows/markdown-link-check-config.json -q -v ';'\n" }, { "alpha_fraction": 0.6005958914756775, "alphanum_fraction": 0.6018226146697998, "avg_line_length": 39.612098693847656, "blob_id": "ade327fe84accdd0b3e4e846ba011381dff4b70e", "content_id": "feac3a70292702e07931ee2be76a64dd10812395", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11412, "license_type": "permissive", "max_line_length": 108, "num_lines": 281, "path": "/mlos_bench/mlos_bench/environments/local/local_env.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nScheduler-side benchmark environment to run scripts locally.\n\"\"\"\n\nimport json\nimport logging\nimport sys\n\nfrom datetime import datetime\nfrom tempfile import TemporaryDirectory\nfrom contextlib import nullcontext\n\nfrom types import TracebackType\nfrom typing import Any, Dict, Iterable, List, Mapping, Optional, Tuple, Type, Union\nfrom typing_extensions import Literal\n\nimport pandas\n\nfrom mlos_bench.environments.status import Status\nfrom mlos_bench.environments.base_environment import Environment\nfrom mlos_bench.environments.script_env import ScriptEnv\nfrom mlos_bench.services.base_service import Service\nfrom mlos_bench.services.types.local_exec_type import SupportsLocalExec\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\nfrom mlos_bench.util import path_join\n\n_LOG = logging.getLogger(__name__)\n\n\nclass LocalEnv(ScriptEnv):\n # pylint: disable=too-many-instance-attributes\n \"\"\"\n Scheduler-side Environment that runs scripts locally.\n \"\"\"\n\n def __init__(self,\n *,\n name: str,\n config: dict,\n global_config: Optional[dict] = None,\n tunables: Optional[TunableGroups] = None,\n service: Optional[Service] = None):\n \"\"\"\n Create a new environment for local execution.\n\n Parameters\n ----------\n name: str\n Human-readable name of the environment.\n config : dict\n Free-format dictionary that contains the benchmark environment\n configuration. Each config must have at least the \"tunable_params\"\n and the \"const_args\" sections.\n `LocalEnv` must also have at least some of the following parameters:\n {setup, run, teardown, dump_params_file, read_results_file}\n global_config : dict\n Free-format dictionary of global parameters (e.g., security credentials)\n to be mixed in into the \"const_args\" section of the local config.\n tunables : TunableGroups\n A collection of tunable parameters for *all* environments.\n service: Service\n An optional service object (e.g., providing methods to\n deploy or reboot a VM, etc.).\n \"\"\"\n super().__init__(name=name, config=config, global_config=global_config,\n tunables=tunables, service=service)\n\n assert self._service is not None and isinstance(self._service, SupportsLocalExec), \\\n \"LocalEnv requires a service that supports local execution\"\n self._local_exec_service: SupportsLocalExec = self._service\n\n self._temp_dir: Optional[str] = None\n self._temp_dir_context: Union[TemporaryDirectory, nullcontext, None] = None\n\n self._dump_params_file: Optional[str] = self.config.get(\"dump_params_file\")\n self._dump_meta_file: Optional[str] = self.config.get(\"dump_meta_file\")\n\n self._read_results_file: Optional[str] = self.config.get(\"read_results_file\")\n self._read_telemetry_file: Optional[str] = self.config.get(\"read_telemetry_file\")\n\n def __enter__(self) -> Environment:\n assert self._temp_dir is None and self._temp_dir_context is None\n self._temp_dir_context = self._local_exec_service.temp_dir_context(self.config.get(\"temp_dir\"))\n self._temp_dir = self._temp_dir_context.__enter__()\n return super().__enter__()\n\n def __exit__(self, ex_type: Optional[Type[BaseException]],\n ex_val: Optional[BaseException],\n ex_tb: Optional[TracebackType]) -> Literal[False]:\n \"\"\"\n Exit the context of the benchmarking environment.\n \"\"\"\n assert not (self._temp_dir is None or self._temp_dir_context is None)\n self._temp_dir_context.__exit__(ex_type, ex_val, ex_tb)\n self._temp_dir = None\n self._temp_dir_context = None\n return super().__exit__(ex_type, ex_val, ex_tb)\n\n def setup(self, tunables: TunableGroups, global_config: Optional[dict] = None) -> bool:\n \"\"\"\n Check if the environment is ready and set up the application\n and benchmarks, if necessary.\n\n Parameters\n ----------\n tunables : TunableGroups\n A collection of tunable OS and application parameters along with their\n values. In a local environment these could be used to prepare a config\n file on the scheduler prior to transferring it to the remote environment,\n for instance.\n global_config : dict\n Free-format dictionary of global parameters of the environment\n that are not used in the optimization process.\n\n Returns\n -------\n is_success : bool\n True if operation is successful, false otherwise.\n \"\"\"\n if not super().setup(tunables, global_config):\n return False\n\n _LOG.info(\"Set up the environment locally: '%s' at %s\", self, self._temp_dir)\n assert self._temp_dir is not None\n\n if self._dump_params_file:\n fname = path_join(self._temp_dir, self._dump_params_file)\n _LOG.debug(\"Dump tunables to file: %s\", fname)\n with open(fname, \"wt\", encoding=\"utf-8\") as fh_tunables:\n # json.dump(self._params, fh_tunables) # Tunables *and* const_args\n json.dump(self._tunable_params.get_param_values(), fh_tunables)\n\n if self._dump_meta_file:\n fname = path_join(self._temp_dir, self._dump_meta_file)\n _LOG.debug(\"Dump tunables metadata to file: %s\", fname)\n with open(fname, \"wt\", encoding=\"utf-8\") as fh_meta:\n json.dump({\n tunable.name: tunable.meta\n for (tunable, _group) in self._tunable_params if tunable.meta\n }, fh_meta)\n\n if self._script_setup:\n return_code = self._local_exec(self._script_setup, self._temp_dir)\n self._is_ready = bool(return_code == 0)\n else:\n self._is_ready = True\n\n return self._is_ready\n\n def run(self) -> Tuple[Status, Optional[Dict[str, float]]]:\n \"\"\"\n Run a script in the local scheduler environment.\n\n Returns\n -------\n (status, output) : (Status, dict)\n A pair of (Status, output) values, where `output` is a dict\n with the results or None if the status is not COMPLETED.\n If run script is a benchmark, then the score is usually expected to\n be in the `score` field.\n \"\"\"\n (status, _) = result = super().run()\n if not status.is_ready():\n return result\n\n assert self._temp_dir is not None\n\n if self._script_run:\n return_code = self._local_exec(self._script_run, self._temp_dir)\n if return_code != 0:\n return (Status.FAILED, None)\n\n # FIXME: We should not be assuming that the only output file type is a CSV.\n if not self._read_results_file:\n _LOG.debug(\"Not reading the data at: %s\", self)\n return (Status.SUCCEEDED, {})\n\n data = self._normalize_columns(pandas.read_csv(\n self._config_loader_service.resolve_path(\n self._read_results_file, extra_paths=[self._temp_dir]),\n index_col=False,\n ))\n\n _LOG.debug(\"Read data:\\n%s\", data)\n if list(data.columns) == [\"metric\", \"value\"]:\n _LOG.info(\"Local results have (metric,value) header and %d rows: assume long format\", len(data))\n data = pandas.DataFrame([data.value.to_list()], columns=data.metric.to_list())\n elif len(data) == 1:\n _LOG.info(\"Local results have 1 row: assume wide format\")\n else:\n raise ValueError(f\"Invalid data format: {data}\")\n\n data_dict = data.iloc[-1].to_dict()\n _LOG.info(\"Local run complete: %s ::\\n%s\", self, data_dict)\n return (Status.SUCCEEDED, data_dict)\n\n @staticmethod\n def _normalize_columns(data: pandas.DataFrame) -> pandas.DataFrame:\n \"\"\"\n Strip trailing spaces from column names (Windows only).\n \"\"\"\n # Windows cmd interpretation of > redirect symbols can leave trailing spaces in\n # the final column, which leads to misnamed columns.\n # For now, we simply strip trailing spaces from column names to account for that.\n if sys.platform == 'win32':\n data.rename(str.rstrip, axis='columns', inplace=True)\n return data\n\n def status(self) -> Tuple[Status, List[Tuple[datetime, str, Any]]]:\n\n (status, _) = super().status()\n if not (self._is_ready and self._read_telemetry_file):\n return (status, [])\n\n assert self._temp_dir is not None\n try:\n fname = self._config_loader_service.resolve_path(\n self._read_telemetry_file, extra_paths=[self._temp_dir])\n\n # FIXME: We should not be assuming that the only output file type is a CSV.\n data = self._normalize_columns(\n pandas.read_csv(fname, index_col=False, parse_dates=[0]))\n\n expected_col_names = [\"timestamp\", \"metric\", \"value\"]\n if len(data.columns) != len(expected_col_names):\n raise ValueError(f'Telemetry data must have columns {expected_col_names}')\n\n if list(data.columns) != expected_col_names:\n # Assume no header - this is ok for telemetry data.\n data = pandas.read_csv(\n fname, index_col=False, parse_dates=[0], names=expected_col_names)\n\n except FileNotFoundError as ex:\n _LOG.warning(\"Telemetry CSV file not found: %s :: %s\", self._read_telemetry_file, ex)\n return (status, [])\n\n _LOG.debug(\"Read telemetry data:\\n%s\", data)\n col_dtypes: Mapping[int, Type] = {0: datetime}\n return (status, [\n (pandas.Timestamp(ts).to_pydatetime(), metric, value)\n for (ts, metric, value) in data.to_records(index=False, column_dtypes=col_dtypes)\n ])\n\n def teardown(self) -> None:\n \"\"\"\n Clean up the local environment.\n \"\"\"\n if self._script_teardown:\n _LOG.info(\"Local teardown: %s\", self)\n return_code = self._local_exec(self._script_teardown)\n _LOG.info(\"Local teardown complete: %s :: %s\", self, return_code)\n super().teardown()\n\n def _local_exec(self, script: Iterable[str], cwd: Optional[str] = None) -> int:\n \"\"\"\n Execute a script locally in the scheduler environment.\n\n Parameters\n ----------\n script : Iterable[str]\n Lines of the script to run locally.\n Treat every line as a separate command to run.\n cwd : Optional[str]\n Work directory to run the script at.\n\n Returns\n -------\n return_code : int\n Return code of the script. 0 if successful.\n \"\"\"\n env_params = self._get_env_params()\n _LOG.info(\"Run script locally on: %s at %s with env %s\", self, cwd, env_params)\n (return_code, _stdout, stderr) = self._local_exec_service.local_exec(\n script, env=env_params, cwd=cwd)\n if return_code != 0:\n _LOG.warning(\"ERROR: Local script returns code %d stderr:\\n%s\", return_code, stderr)\n return return_code\n" }, { "alpha_fraction": 0.7727272510528564, "alphanum_fraction": 0.7727272510528564, "avg_line_length": 24.66666603088379, "blob_id": "3126aea908d86df694042534f7691a4750e6010f", "content_id": "e5756299f8cd0f023dcdaf8bafda39519308a7e1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 462, "license_type": "permissive", "max_line_length": 82, "num_lines": 18, "path": "/mlos_bench/mlos_bench/services/remote/azure/__init__.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nAzure-specific benchmark environments for mlos_bench.\n\"\"\"\n\nfrom mlos_bench.services.remote.azure.azure_auth import AzureAuthService\nfrom mlos_bench.services.remote.azure.azure_services import AzureVMService\nfrom mlos_bench.services.remote.azure.azure_fileshare import AzureFileShareService\n\n\n__all__ = [\n 'AzureAuthService',\n 'AzureVMService',\n 'AzureFileShareService',\n]\n" }, { "alpha_fraction": 0.6809470057487488, "alphanum_fraction": 0.6823562383651733, "avg_line_length": 31.550458908081055, "blob_id": "c43af230197d235c938e3591dcbbf30dc8f91358", "content_id": "46b66425b45e4c9f2605bcd6046beabd79f0f225", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3548, "license_type": "permissive", "max_line_length": 95, "num_lines": 109, "path": "/mlos_core/mlos_core/optimizers/__init__.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nBasic initializer module for the mlos_core optimizers.\n\"\"\"\n\nfrom enum import Enum\nfrom typing import Optional, TypeVar\n\nimport ConfigSpace\n\nfrom mlos_core.optimizers.optimizer import BaseOptimizer\nfrom mlos_core.optimizers.random_optimizer import RandomOptimizer\nfrom mlos_core.optimizers.bayesian_optimizers.smac_optimizer import SmacOptimizer\nfrom mlos_core.optimizers.flaml_optimizer import FlamlOptimizer\nfrom mlos_core.spaces.adapters import SpaceAdapterType, SpaceAdapterFactory\n\n__all__ = [\n 'SpaceAdapterType',\n 'OptimizerFactory',\n 'BaseOptimizer',\n 'RandomOptimizer',\n 'FlamlOptimizer',\n 'SmacOptimizer',\n]\n\n\nclass OptimizerType(Enum):\n \"\"\"Enumerate supported MlosCore optimizers.\"\"\"\n\n RANDOM = RandomOptimizer\n \"\"\"An instance of RandomOptimizer class will be used\"\"\"\n\n FLAML = FlamlOptimizer\n \"\"\"An instance of FlamlOptimizer class will be used\"\"\"\n\n SMAC = SmacOptimizer\n \"\"\"An instance of SmacOptimizer class will be used\"\"\"\n\n\n# To make mypy happy, we need to define a type variable for each optimizer type.\n# https://github.com/python/mypy/issues/12952\n# ConcreteOptimizer = TypeVar('ConcreteOptimizer', *[member.value for member in OptimizerType])\n# To address this, we add a test for complete coverage of the enum.\nConcreteOptimizer = TypeVar(\n 'ConcreteOptimizer',\n RandomOptimizer,\n FlamlOptimizer,\n SmacOptimizer,\n)\n\nDEFAULT_OPTIMIZER_TYPE = OptimizerType.FLAML\n\n\nclass OptimizerFactory:\n \"\"\"Simple factory class for creating BaseOptimizer-derived objects\"\"\"\n\n # pylint: disable=too-few-public-methods\n\n @staticmethod\n def create(*,\n parameter_space: ConfigSpace.ConfigurationSpace,\n optimizer_type: OptimizerType = DEFAULT_OPTIMIZER_TYPE,\n optimizer_kwargs: Optional[dict] = None,\n space_adapter_type: SpaceAdapterType = SpaceAdapterType.IDENTITY,\n space_adapter_kwargs: Optional[dict] = None) -> ConcreteOptimizer:\n \"\"\"\n Create a new optimizer instance, given the parameter space, optimizer type,\n and potential optimizer options.\n\n Parameters\n ----------\n parameter_space : ConfigSpace.ConfigurationSpace\n Input configuration space.\n optimizer_type : OptimizerType\n Optimizer class as defined by Enum.\n optimizer_kwargs : Optional[dict]\n Optional arguments passed in Optimizer class constructor.\n space_adapter_type : Optional[SpaceAdapterType]\n Space adapter class to be used alongside the optimizer.\n space_adapter_kwargs : Optional[dict]\n Optional arguments passed in SpaceAdapter class constructor.\n\n Returns\n -------\n optimizer : ConcreteOptimizer\n Instance of concrete optimizer class\n (e.g., RandomOptimizer, FlamlOptimizer, SmacOptimizer, etc.).\n \"\"\"\n if space_adapter_kwargs is None:\n space_adapter_kwargs = {}\n if optimizer_kwargs is None:\n optimizer_kwargs = {}\n\n space_adapter = SpaceAdapterFactory.create(\n parameter_space=parameter_space,\n space_adapter_type=space_adapter_type,\n space_adapter_kwargs=space_adapter_kwargs,\n )\n\n optimizer: ConcreteOptimizer = optimizer_type.value(\n parameter_space=parameter_space,\n space_adapter=space_adapter,\n **optimizer_kwargs\n )\n\n return optimizer\n" }, { "alpha_fraction": 0.6675675511360168, "alphanum_fraction": 0.6675675511360168, "avg_line_length": 28.210525512695312, "blob_id": "51ef559c2fb38faf481f836562a1b46522713823", "content_id": "d50fcf19c3cc679bd2a6a83e36bd25eb3d42c0be", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1110, "license_type": "permissive", "max_line_length": 90, "num_lines": 38, "path": "/mlos_bench/mlos_bench/tests/services/remote/mock/mock_fileshare_service.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nA collection Service functions for mocking file share ops.\n\"\"\"\n\nimport logging\nfrom typing import Any, Dict, Optional\n\nfrom mlos_bench.services.base_service import Service\nfrom mlos_bench.services.base_fileshare import FileShareService\nfrom mlos_bench.services.types.fileshare_type import SupportsFileShareOps\n\n_LOG = logging.getLogger(__name__)\n\n\nclass MockFileShareService(FileShareService, SupportsFileShareOps):\n \"\"\"\n A collection Service functions for mocking file share ops.\n \"\"\"\n\n def __init__(self, config: Optional[Dict[str, Any]] = None,\n global_config: Optional[Dict[str, Any]] = None,\n parent: Optional[Service] = None):\n super().__init__(config, global_config, parent)\n\n self.register([\n self.download,\n self.upload,\n ])\n\n def download(self, remote_path: str, local_path: str, recursive: bool = True) -> None:\n pass\n\n def upload(self, local_path: str, remote_path: str, recursive: bool = True) -> None:\n pass\n" }, { "alpha_fraction": 0.7217676043510437, "alphanum_fraction": 0.7250409126281738, "avg_line_length": 28.095237731933594, "blob_id": "1796daf07958abe3076b5a98486b12250e94529e", "content_id": "543bd9d9d3df5f3331c50fb5be7415091c372927", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 611, "license_type": "permissive", "max_line_length": 94, "num_lines": 21, "path": "/mlos_bench/mlos_bench/config/environments/apps/redis/scripts/remote/setup-app.sh", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#!/bin/bash\n##\n## Copyright (c) Microsoft Corporation.\n## Licensed under the MIT License.\n##\n\nset -eu\n\nscriptdir=$(dirname \"$(readlink -f \"$0\")\")\ncd \"$scriptdir\"\nsource ./common.sh\n\ncheck_docker\n\n# Remove any previously running/failed instances.\ndocker rm --force $REDIS_SERVER_NAME 2>/dev/null || true\n\n# Start the redis server container in the background and expose it's port on the host machine.\n# TODO: Explore use of -v /data volume mount for persisting snapshots.\n# TODO: Explore how to map different server configs in.\ndocker run -d --rm --name $REDIS_SERVER_NAME -p $REDIS_PORT:$REDIS_PORT $REDIS_IMAGE\n" }, { "alpha_fraction": 0.5938989520072937, "alphanum_fraction": 0.5977120995521545, "avg_line_length": 20.85416603088379, "blob_id": "0e2ef6d92c69df44b024c84083788882504bab94", "content_id": "96ea7270594b57525247d733728d846872fb9c46", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1049, "license_type": "permissive", "max_line_length": 97, "num_lines": 48, "path": "/scripts/dmypy-wrapper.sh", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#!/bin/bash\n##\n## Copyright (c) Microsoft Corporation.\n## Licensed under the MIT License.\n##\n\nset -eu\n\n#set -x\n\n# Start in the root dir.\nscriptdir=$(dirname \"$(readlink -f \"$0\")\")\ncd \"$scriptdir/..\"\n\nDMYPY_STATUS_FILE='.dmypy.json'\nDMYPY_STATUS_ARGS=\"--status-file $DMYPY_STATUS_FILE\"\nDMYPY_START_ARGS=''\n\nwhile [ -z \"${1:-}\" ]; do\n opt=\"${1:-}\"\n case $opt in\n --*)\n DMYPY_START_ARGS+=\" $opt\"\n shift\n ;;\n *)\n break\n ;;\n esac\ndone\nif [ -z \"$DMYPY_START_ARGS\" ]; then\n DMYPY_START_ARGS='--pretty --cache-fine-grained --install-types --non-interactive'\nfi\n\ndmypy $DMYPY_STATUS_ARGS status >/dev/null || dmypy $DMYPY_STATUS_ARGS start -- $DMYPY_START_ARGS\n\n# Restart the daemon if the config file has changed.\nif [ setup.cfg -nt /proc/$(cat $DMYPY_STATUS_FILE | jq -e -r .pid) ]; then\n dmypy $DMYPY_STATUS_ARGS restart -- $DMYPY_START_ARGS\nfi\n\nif [ -z \"${1:-}\" ]; then\n\tdmypy status\n\texit $?\nfi\n\n# Check the files passed as arguments.\ndmypy $DMYPY_STATUS_ARGS check $*\n" }, { "alpha_fraction": 0.5929113626480103, "alphanum_fraction": 0.5934900641441345, "avg_line_length": 36.26415252685547, "blob_id": "d2b86b2bca2545815cdcbefa779f4a9bdda09395", "content_id": "21c36a0764798b41ff8f08c6f9a24e87bd0c2cf0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13825, "license_type": "permissive", "max_line_length": 127, "num_lines": 371, "path": "/mlos_bench/mlos_bench/environments/base_environment.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nA hierarchy of benchmark environments.\n\"\"\"\n\nimport abc\nimport json\nimport logging\nfrom datetime import datetime\nfrom types import TracebackType\nfrom typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple, Type, TYPE_CHECKING, Union\nfrom typing_extensions import Literal\n\nfrom mlos_bench.environments.status import Status\nfrom mlos_bench.services.base_service import Service\nfrom mlos_bench.tunables.tunable import TunableValue\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\nfrom mlos_bench.util import instantiate_from_config, merge_parameters\n\nif TYPE_CHECKING:\n from mlos_bench.services.types.config_loader_type import SupportsConfigLoading\n\n_LOG = logging.getLogger(__name__)\n\n\nclass Environment(metaclass=abc.ABCMeta):\n # pylint: disable=too-many-instance-attributes\n \"\"\"\n An abstract base of all benchmark environments.\n \"\"\"\n\n @classmethod\n def new(cls,\n *,\n env_name: str,\n class_name: str,\n config: dict,\n global_config: Optional[dict] = None,\n tunables: Optional[TunableGroups] = None,\n service: Optional[Service] = None,\n ) -> \"Environment\":\n \"\"\"\n Factory method for a new environment with a given config.\n\n Parameters\n ----------\n env_name: str\n Human-readable name of the environment.\n class_name: str\n FQN of a Python class to instantiate, e.g.,\n \"mlos_bench.environments.remote.VMEnv\".\n Must be derived from the `Environment` class.\n config : dict\n Free-format dictionary that contains the benchmark environment\n configuration. It will be passed as a constructor parameter of\n the class specified by `name`.\n global_config : dict\n Free-format dictionary of global parameters (e.g., security credentials)\n to be mixed in into the \"const_args\" section of the local config.\n tunables : TunableGroups\n A collection of groups of tunable parameters for all environments.\n service: Service\n An optional service object (e.g., providing methods to\n deploy or reboot a VM, etc.).\n\n Returns\n -------\n env : Environment\n An instance of the `Environment` class initialized with `config`.\n \"\"\"\n assert issubclass(cls, Environment)\n return instantiate_from_config(\n cls,\n class_name,\n name=env_name,\n config=config,\n global_config=global_config,\n tunables=tunables,\n service=service\n )\n\n def __init__(self,\n *,\n name: str,\n config: dict,\n global_config: Optional[dict] = None,\n tunables: Optional[TunableGroups] = None,\n service: Optional[Service] = None):\n \"\"\"\n Create a new environment with a given config.\n\n Parameters\n ----------\n name: str\n Human-readable name of the environment.\n config : dict\n Free-format dictionary that contains the benchmark environment\n configuration. Each config must have at least the \"tunable_params\"\n and the \"const_args\" sections.\n global_config : dict\n Free-format dictionary of global parameters (e.g., security credentials)\n to be mixed in into the \"const_args\" section of the local config.\n tunables : TunableGroups\n A collection of groups of tunable parameters for all environments.\n service: Service\n An optional service object (e.g., providing methods to\n deploy or reboot a VM, etc.).\n \"\"\"\n self.name = name\n self.config = config\n self._service = service\n self._is_ready = False\n self._in_context = False\n self._const_args = config.get(\"const_args\", {})\n\n if tunables is None:\n _LOG.warning(\"No tunables provided for %s. Tunable inheritance across composite environments may be broken.\", name)\n tunables = TunableGroups()\n\n groups = self._expand_groups(\n config.get(\"tunable_params\", []),\n (global_config or {}).get(\"tunable_params_map\", {}))\n _LOG.debug(\"Tunable groups for: '%s' :: %s\", name, groups)\n\n self._tunable_params = tunables.subgroup(groups)\n\n # If a parameter comes from the tunables, do not require it in the const_args or globals\n req_args = (\n set(config.get(\"required_args\", [])) -\n set(self._tunable_params.get_param_values().keys())\n )\n merge_parameters(dest=self._const_args, source=global_config, required_keys=req_args)\n\n self._params = self._combine_tunables(self._tunable_params)\n _LOG.debug(\"Parameters for '%s' :: %s\", name, self._params)\n\n if _LOG.isEnabledFor(logging.DEBUG):\n _LOG.debug(\"Config for: '%s'\\n%s\",\n name, json.dumps(self.config, indent=2))\n\n @staticmethod\n def _expand_groups(groups: Iterable[str],\n groups_exp: Dict[str, Union[str, Sequence[str]]]) -> List[str]:\n \"\"\"\n Expand `$tunable_group` into actual names of the tunable groups.\n\n Parameters\n ----------\n groups : List[str]\n Names of the groups of tunables, maybe with `$` prefix (subject to expansion).\n groups_exp : dict\n A dictionary that maps dollar variables for tunable groups to the lists\n of actual tunable groups IDs.\n\n Returns\n -------\n groups : List[str]\n A flat list of tunable groups IDs for the environment.\n \"\"\"\n res: List[str] = []\n for grp in groups:\n if grp[:1] == \"$\":\n tunable_group_name = grp[1:]\n if tunable_group_name not in groups_exp:\n raise KeyError(f\"Expected tunable group name ${tunable_group_name} undefined in {groups_exp}\")\n add_groups = groups_exp[tunable_group_name]\n res += [add_groups] if isinstance(add_groups, str) else add_groups\n else:\n res.append(grp)\n return res\n\n @property\n def _config_loader_service(self) -> \"SupportsConfigLoading\":\n assert self._service is not None\n return self._service.config_loader_service\n\n def __enter__(self) -> 'Environment':\n \"\"\"\n Enter the environment's benchmarking context.\n \"\"\"\n _LOG.debug(\"Environment START :: %s\", self)\n assert not self._in_context\n self._in_context = True\n return self\n\n def __exit__(self, ex_type: Optional[Type[BaseException]],\n ex_val: Optional[BaseException],\n ex_tb: Optional[TracebackType]) -> Literal[False]:\n \"\"\"\n Exit the context of the benchmarking environment.\n \"\"\"\n if ex_val is None:\n _LOG.debug(\"Environment END :: %s\", self)\n else:\n assert ex_type and ex_val\n _LOG.warning(\"Environment END :: %s\", self, exc_info=(ex_type, ex_val, ex_tb))\n assert self._in_context\n self._in_context = False\n return False # Do not suppress exceptions\n\n def __str__(self) -> str:\n return self.name\n\n def __repr__(self) -> str:\n return f\"{self.__class__.__name__} :: '{self.name}'\"\n\n def pprint(self, indent: int = 4, level: int = 0) -> str:\n \"\"\"\n Pretty-print the environment configuration.\n For composite environments, print all children environments as well.\n\n Parameters\n ----------\n indent : int\n Number of spaces to indent the output. Default is 4.\n level : int\n Current level of indentation. Default is 0.\n\n Returns\n -------\n pretty : str\n Pretty-printed environment configuration.\n Default output is the same as `__repr__`.\n \"\"\"\n return f'{\" \" * indent * level}{repr(self)}'\n\n def _combine_tunables(self, tunables: TunableGroups) -> Dict[str, TunableValue]:\n \"\"\"\n Plug tunable values into the base config. If the tunable group is unknown,\n ignore it (it might belong to another environment). This method should\n never mutate the original config or the tunables.\n\n Parameters\n ----------\n tunables : TunableGroups\n A collection of groups of tunable parameters\n along with the parameters' values.\n\n Returns\n -------\n params : Dict[str, Union[int, float, str]]\n Free-format dictionary that contains the new environment configuration.\n \"\"\"\n return tunables.get_param_values(\n group_names=list(self._tunable_params.get_covariant_group_names()),\n into_params=self._const_args.copy())\n\n @property\n def tunable_params(self) -> TunableGroups:\n \"\"\"\n Get the configuration space of the given environment.\n\n Returns\n -------\n tunables : TunableGroups\n A collection of covariant groups of tunable parameters.\n \"\"\"\n return self._tunable_params\n\n @property\n def parameters(self) -> Dict[str, TunableValue]:\n \"\"\"\n Key/value pairs of all environment parameters (i.e., `const_args` and `tunable_params`).\n Note that before `.setup()` is called, all tunables will be set to None.\n\n Returns\n -------\n parameters : Dict[str, TunableValue]\n Key/value pairs of all environment parameters (i.e., `const_args` and `tunable_params`).\n \"\"\"\n return self._params\n\n def setup(self, tunables: TunableGroups, global_config: Optional[dict] = None) -> bool:\n \"\"\"\n Set up a new benchmark environment, if necessary. This method must be\n idempotent, i.e., calling it several times in a row should be\n equivalent to a single call.\n\n Parameters\n ----------\n tunables : TunableGroups\n A collection of tunable parameters along with their values.\n global_config : dict\n Free-format dictionary of global parameters of the environment\n that are not used in the optimization process.\n\n Returns\n -------\n is_success : bool\n True if operation is successful, false otherwise.\n \"\"\"\n _LOG.info(\"Setup %s :: %s\", self, tunables)\n assert isinstance(tunables, TunableGroups)\n\n # Make sure we create a context before invoking setup/run/status/teardown\n assert self._in_context\n\n # Assign new values to the environment's tunable parameters:\n groups = list(self._tunable_params.get_covariant_group_names())\n self._tunable_params.assign(tunables.get_param_values(groups))\n\n # Write to the log whether the environment needs to be reset.\n # (Derived classes still have to check `self._tunable_params.is_updated()`).\n is_updated = self._tunable_params.is_updated()\n if _LOG.isEnabledFor(logging.DEBUG):\n _LOG.debug(\"Env '%s': Tunable groups reset = %s :: %s\", self, is_updated, {\n name: self._tunable_params.is_updated([name])\n for name in self._tunable_params.get_covariant_group_names()\n })\n else:\n _LOG.info(\"Env '%s': Tunable groups reset = %s\", self, is_updated)\n\n # Combine tunables, const_args, and global config into `self._params`:\n self._params = self._combine_tunables(tunables)\n merge_parameters(dest=self._params, source=global_config)\n\n if _LOG.isEnabledFor(logging.DEBUG):\n _LOG.debug(\"Combined parameters:\\n%s\", json.dumps(self._params, indent=2))\n\n return True\n\n def teardown(self) -> None:\n \"\"\"\n Tear down the benchmark environment. This method must be idempotent,\n i.e., calling it several times in a row should be equivalent to a\n single call.\n \"\"\"\n _LOG.info(\"Teardown %s\", self)\n # Make sure we create a context before invoking setup/run/status/teardown\n assert self._in_context\n self._is_ready = False\n\n def run(self) -> Tuple[Status, Optional[Dict[str, float]]]:\n \"\"\"\n Execute the run script for this environment.\n\n For instance, this may start a new experiment, download results, reconfigure\n the environment, etc. Details are configurable via the environment config.\n\n Returns\n -------\n (status, output) : (Status, dict)\n A pair of (Status, output) values, where `output` is a dict\n with the results or None if the status is not COMPLETED.\n If run script is a benchmark, then the score is usually expected to\n be in the `score` field.\n \"\"\"\n # Make sure we create a context before invoking setup/run/status/teardown\n assert self._in_context\n (status, _) = self.status()\n return (status, None)\n\n def status(self) -> Tuple[Status, List[Tuple[datetime, str, Any]]]:\n \"\"\"\n Check the status of the benchmark environment.\n\n Returns\n -------\n (benchmark_status, telemetry) : (Status, list)\n A pair of (benchmark status, telemetry) values.\n `telemetry` is a list (maybe empty) of (timestamp, metric, value) triplets.\n \"\"\"\n # Make sure we create a context before invoking setup/run/status/teardown\n assert self._in_context\n if self._is_ready:\n return (Status.READY, [])\n _LOG.warning(\"Environment not ready: %s\", self)\n return (Status.PENDING, [])\n" }, { "alpha_fraction": 0.6960955858230591, "alphanum_fraction": 0.7016317248344421, "avg_line_length": 42.44303894042969, "blob_id": "67ea64fd818559baa17562438879ae4e11db5037", "content_id": "5897e5799db9626d8d10755f3a290cd4dbd7daff", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 3432, "license_type": "permissive", "max_line_length": 128, "num_lines": 79, "path": "/.devcontainer/Dockerfile", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nFROM mcr.microsoft.com/devcontainers/miniconda:3 AS base\n\n# Add some additional packages for the devcontainer terminal environment.\nUSER root\nRUN apt-get update && export DEBIAN_FRONTEND=noninteractive \\\n && apt-get -y install --no-install-recommends \\\n bash bash-completion \\\n less colordiff \\\n curl jq \\\n ripgrep \\\n vim-nox neovim python3-pynvim \\\n make \\\n rename \\\n && apt-get clean && rm -rf /var/lib/apt/lists/* \\\n && echo \"C-w: unix-filename-rubout\" >> /etc/inputrc\n # Also tweak C-w to stop at slashes as well instead of just spaces\n\n# Set some cache dirs to be owned by the vscode user even as we're currently\n# executing as root to build the container image.\n# NOTE: We do *not* mark these as volumes - it doesn't help rebuilding at all.\n\nARG PIP_CACHE_DIR=/var/cache/pip\nENV PIP_CACHE_DIR=/var/cache/pip\nRUN mkdir -p ${PIP_CACHE_DIR} \\\n && chown -R vscode:conda ${PIP_CACHE_DIR} \\\n && chmod -R u=rwX,g=rwXs,o=rX ${PIP_CACHE_DIR}\n\nARG CONDA_PKGS_DIRS=/opt/conda/pkgs\nENV CONDA_PKGS_DIRS=/opt/conda/pkgs\nRUN mkdir -p ${CONDA_PKGS_DIRS} \\\n && chown -R vscode:conda ${CONDA_PKGS_DIRS} \\\n && chmod -R u=rwX,g=rwXs,o=rX ${CONDA_PKGS_DIRS}\n\nUSER vscode\n\n# Use the mamba solver (necessary for some quality of life speedups due to\n# required packages to support Windows)\nRUN umask 0002 \\\n && /opt/conda/bin/conda install -v -y -n base conda-libmamba-solver \\\n && /opt/conda/bin/conda config --set solver libmamba\n\n# Update the base. This helps save space by making sure the same version\n# python is used for both the base env and mlos env.\nRUN umask 0002 \\\n && /opt/conda/bin/conda update -v -y -n base -c defaults --all \\\n && /opt/conda/bin/conda clean -v -y -a\n\n# Install some additional editor packages for the base environment.\nRUN umask 0002 \\\n && /opt/conda/bin/conda run -n base pip install --no-cache-dir -U pynvim\n\n# Setup (part of) the mlos environment in the devcontainer.\n# NOTEs:\n# - The mlos_deps.yml file is prepared by the prep-container-build script(s).\n# - The rest happens during first container start once the source is available.\n# See Also: updateContentCommand in .devcontainer/devcontainer.json\nRUN mkdir -p /opt/conda/pkgs/cache/ && chown -R vscode:conda /opt/conda/pkgs/cache/\nRUN /opt/conda/bin/conda init bash \\\n && /opt/conda/bin/conda config --set solver libmamba\n\n# Prepare the mlos_deps.yml file in a cross platform way.\nFROM mcr.microsoft.com/devcontainers/miniconda:3 AS deps-prep\nCOPY --chown=vscode:conda . /tmp/conda-tmp/\nRUN /tmp/conda-tmp/prep-deps-files.sh \\\n && ls -l /tmp/conda-tmp/ # && cat /tmp/conda-tmp/combined.requirements.txt /tmp/conda-tmp/mlos_deps.yml\n\n# Install some additional dependencies for the mlos environment.\nFROM base AS devcontainer\nCOPY --from=deps-prep --chown=vscode:conda /tmp/conda-tmp/mlos_deps.yml /tmp/conda-tmp/combined.requirements.txt /tmp/conda-tmp/\nRUN umask 0002 \\\n && /opt/conda/bin/conda env create -n mlos -v -f /tmp/conda-tmp/mlos_deps.yml \\\n && /opt/conda/bin/conda run -n mlos pip install -U -r /tmp/conda-tmp/combined.requirements.txt \\\n && /opt/conda/bin/conda clean -v -y -a \\\n && mkdir -p /opt/conda/pkgs/cache/ && chown -R vscode:conda /opt/conda/pkgs/cache/\nRUN mkdir -p /home/vscode/.conda/envs \\\n && ln -s /opt/conda/envs/mlos /home/vscode/.conda/envs/mlos\n" }, { "alpha_fraction": 0.622980535030365, "alphanum_fraction": 0.6239696741104126, "avg_line_length": 35.10714340209961, "blob_id": "b4d6b201989e43c5ba9838f32d0c3cd39a483fb5", "content_id": "045aff246f0dd9c1691d79dffdef3d2171e4673b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6066, "license_type": "permissive", "max_line_length": 86, "num_lines": 168, "path": "/mlos_bench/mlos_bench/run.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nOS Autotune main optimization loop.\n\nNote: this script is also available as a CLI tool via pip under the name \"mlos_bench\".\n\nSee `--help` output for details.\n\"\"\"\n\nimport json\nimport logging\nfrom datetime import datetime\nfrom typing import Optional, Tuple, Dict, Any\n\nfrom mlos_bench.launcher import Launcher\nfrom mlos_bench.optimizers.base_optimizer import Optimizer\nfrom mlos_bench.environments.base_environment import Environment\nfrom mlos_bench.storage.base_storage import Storage\nfrom mlos_bench.environments.status import Status\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\n\n_LOG = logging.getLogger(__name__)\n\n\ndef _main() -> None:\n\n launcher = Launcher(\"mlos_bench\", \"Systems autotuning and benchmarking tool\")\n\n result = _optimize(\n env=launcher.environment,\n opt=launcher.optimizer,\n storage=launcher.storage,\n root_env_config=launcher.root_env_config,\n global_config=launcher.global_config,\n do_teardown=launcher.teardown\n )\n\n _LOG.info(\"Final result: %s\", result)\n\n\ndef _optimize(*,\n env: Environment,\n opt: Optimizer,\n storage: Storage,\n root_env_config: str,\n global_config: Dict[str, Any],\n do_teardown: bool) -> Tuple[Optional[float], Optional[TunableGroups]]:\n \"\"\"\n Main optimization loop.\n\n Parameters\n ----------\n env : Environment\n benchmarking environment to run the optimization on.\n opt : Optimizer\n An interface to mlos_core optimizers.\n storage : Storage\n A storage system to persist the experiment data.\n root_env_config : str\n A path to the root JSON configuration file of the benchmarking environment.\n global_config : dict\n Global configuration parameters.\n do_teardown : bool\n If True, teardown the environment at the end of the experiment\n \"\"\"\n # pylint: disable=too-many-locals\n if _LOG.isEnabledFor(logging.INFO):\n _LOG.info(\"Root Environment:\\n%s\", env.pprint())\n\n experiment_id = global_config[\"experiment_id\"].strip()\n trial_id = int(global_config.get(\"trial_id\", 1))\n config_id = int(global_config.get(\"config_id\", -1))\n\n # Start new or resume the existing experiment. Verify that the\n # experiment configuration is compatible with the previous runs.\n # If the `merge` config parameter is present, merge in the data\n # from other experiments and check for compatibility.\n with env as env_context, storage.experiment(experiment_id=experiment_id,\n trial_id=trial_id,\n root_env_config=root_env_config,\n description=env.name,\n opt_target=opt.target) as exp:\n\n _LOG.info(\"Experiment: %s Env: %s Optimizer: %s\", exp, env, opt)\n\n if opt.supports_preload:\n # Load (tunable values, benchmark scores) to warm-up the optimizer.\n # `.load()` returns data from ALL merged-in experiments and attempts\n # to impute the missing tunable values.\n (configs, scores, status) = exp.load()\n opt.bulk_register(configs, scores, status)\n # Complete any pending trials.\n for trial in exp.pending_trials():\n _run(env_context, opt, trial, global_config)\n else:\n _LOG.warning(\"Skip pending trials and warm-up: %s\", opt)\n\n # Now run new trials until the optimizer is done.\n while opt.not_converged():\n\n tunables = opt.suggest()\n\n if config_id > 0:\n tunable_values = exp.load_config(config_id)\n tunables.assign(tunable_values)\n _LOG.info(\"Load config from storage: %d\", config_id)\n if _LOG.isEnabledFor(logging.DEBUG):\n _LOG.debug(\"Config %d ::\\n%s\",\n config_id, json.dumps(tunable_values, indent=2))\n config_id = -1\n\n trial = exp.new_trial(tunables)\n _run(env_context, opt, trial, global_config)\n\n if do_teardown:\n env_context.teardown()\n\n (best_score, best_config) = opt.get_best_observation()\n _LOG.info(\"Env: %s best score: %s\", env, best_score)\n return (best_score, best_config)\n\n\ndef _run(env_context: Environment, opt: Optimizer,\n trial: Storage.Trial, global_config: Dict[str, Any]) -> None:\n \"\"\"\n Run a single trial.\n\n Parameters\n ----------\n env_context : Environment\n Benchmarking environment context to run the optimization on.\n opt : Optimizer\n An interface to mlos_core optimizers.\n storage : Storage\n A storage system to persist the experiment data.\n global_config : dict\n Global configuration parameters.\n \"\"\"\n _LOG.info(\"Trial: %s\", trial)\n\n if not env_context.setup(trial.tunables, trial.config(global_config)):\n _LOG.warning(\"Setup failed: %s :: %s\", env_context, trial.tunables)\n # FIXME: Use the actual timestamp from the environment.\n trial.update(Status.FAILED, datetime.utcnow())\n opt.register(trial.tunables, Status.FAILED)\n return\n\n (status, results) = env_context.run() # Block and wait for the final result.\n _LOG.info(\"Results: %s :: %s\\n%s\", trial.tunables, status, results)\n\n # In async mode (TODO), poll the environment for status and telemetry\n # and update the storage with the intermediate results.\n (_, telemetry) = env_context.status()\n # Use the status from `.run()` as it is the final status of the experiment.\n # TODO: Use the `.status()` output in async mode.\n trial.update_telemetry(status, telemetry)\n\n # FIXME: Use the actual timestamp from the benchmark.\n trial.update(status, datetime.utcnow(), results)\n opt.register(trial.tunables, status, results)\n\n\nif __name__ == \"__main__\":\n _main()\n" }, { "alpha_fraction": 0.6421940922737122, "alphanum_fraction": 0.6447257399559021, "avg_line_length": 27.90243911743164, "blob_id": "8fcbb4f041e64ecfbe2a835cd1b66b30a531df83", "content_id": "ae2aba9f21f3f530a67bce74bc19cd4c49db3748", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1185, "license_type": "permissive", "max_line_length": 90, "num_lines": 41, "path": "/.devcontainer/scripts/common/prep-deps-files.sh", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#!/bin/bash\n##\n## Copyright (c) Microsoft Corporation.\n## Licensed under the MIT License.\n##\n\n# Prep some files for the devcontainer build in a way that's cross platform.\n# We do this by running this script from a container that has the tools we need\n# and generates files with the right encodings so that it's more cacheable\n# across platforms.\n\nset -eu\nset -o pipefail\n\nset -x\n\nscriptdir=$(dirname \"$(readlink -f \"$0\")\")\ncd \"$scriptdir\"\n\ncat /tmp/conda-tmp/mlos.yml \\\n | sed 's|#.*||' \\\n | egrep -v -e '--editable' -e '^\\s*$' \\\n | tee /tmp/conda-tmp/mlos_deps.yml\n\n# Try to grab the requirements.txt files for the python packages.\ntmpdir=$(mktemp -d)\nget_python_deps() {\n local pkg=\"$1\"\n touch /tmp/conda-tmp/$pkg.requirements.txt\n python3 /tmp/conda-tmp/$pkg/setup.py egg_info --egg-base \"$tmpdir/\"\n cat \"$tmpdir/$pkg.egg-info/requires.txt\" \\\n | grep -v -e '^\\[' -e '^\\s*$' \\\n | grep -v '^mlos-core' \\\n | sort -u \\\n > /tmp/conda-tmp/$pkg.requirements.txt\n}\nfor pkg in mlos_core mlos_bench; do\n get_python_deps \"$pkg\"\ndone\nrm -rf \"$tmpdir\"\ncat /tmp/conda-tmp/*.requirements.txt | sort -u > /tmp/conda-tmp/combined.requirements.txt\n" }, { "alpha_fraction": 0.6395511627197266, "alphanum_fraction": 0.658719003200531, "avg_line_length": 29.55714225769043, "blob_id": "f1e4a01838d5e17f924a37acc81e9542f6ca5953", "content_id": "efab570d17ec4e943526acbe12a34a6cf7c84016", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2139, "license_type": "permissive", "max_line_length": 129, "num_lines": 70, "path": "/mlos_core/setup.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nSetup instructions for the mlos_core package.\n\"\"\"\n\nfrom itertools import chain\nfrom logging import warning\nfrom typing import Dict, List\n\nfrom setuptools import setup, find_packages\n\nfrom _version import _VERSION # pylint: disable=import-private-name\n\ntry:\n from setuptools_scm import get_version\n version = get_version(root='..', relative_to=__file__)\n if version is not None:\n _VERSION = version # noqa: F811\nexcept ImportError:\n warning(\"setuptools_scm not found, using version from _version.py\")\nexcept LookupError as e:\n warning(f\"setuptools_scm failed to find git version, using version from _version.py: {e}\")\n\n\nextra_requires: Dict[str, List[str]] = { # pylint: disable=consider-using-namedtuple-or-dataclass\n 'flaml': ['flaml[blendsearch]'],\n 'smac': ['smac>=2.0.0'], # NOTE: Major refactoring on SMAC starting from v2.0.0\n}\n\n# construct special 'full' extra that adds requirements for all built-in\n# backend integrations and additional extra features.\nextra_requires['full'] = list(set(chain(*extra_requires.values())))\n\nextra_requires['full-tests'] = extra_requires['full'] + [\n 'pytest',\n 'pytest-forked',\n 'pytest-xdist',\n 'pytest-cov',\n 'pytest-local-badge',\n]\n\n# pylint: disable=duplicate-code\nMODULE_BASE_NAME = 'mlos_core'\nsetup(\n name='mlos-core',\n version=_VERSION,\n packages=find_packages(exclude=[f\"{MODULE_BASE_NAME}.tests\", f\"{MODULE_BASE_NAME}.tests.*\"]),\n package_data={\n '': ['py.typed', '**/*.pyi'],\n },\n install_requires=[\n 'scikit-learn>=1.2',\n 'joblib>=1.1.1', # CVE-2022-21797: scikit-learn dependency, addressed in 1.2.0dev0, which isn't currently released\n 'scipy>=1.3.2',\n 'numpy>=1.24',\n 'pandas>=1.0.3',\n 'ConfigSpace>=0.7.1',\n ],\n extras_require=extra_requires,\n author='Microsoft',\n author_email='[email protected]',\n description=('MLOS Core Python interface for parameter optimization.'),\n license='MIT',\n keywords='',\n url='https://aka.ms/mlos-core',\n python_requires='>=3.8',\n)\n" }, { "alpha_fraction": 0.7112756371498108, "alphanum_fraction": 0.7146924734115601, "avg_line_length": 33.431373596191406, "blob_id": "b796cbabae3c4dc662f976fe30d072636a1454a8", "content_id": "16bb42500c983a76bb1a721070da4f73dfc5d7d6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1756, "license_type": "permissive", "max_line_length": 79, "num_lines": 51, "path": "/mlos_bench/mlos_bench/tests/tunables/tunables_copy_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nUnit tests for deep copy of tunable objects and groups.\n\"\"\"\n\nfrom mlos_bench.tunables.covariant_group import CovariantTunableGroup\nfrom mlos_bench.tunables.tunable import Tunable, TunableValue\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\n\n\ndef test_copy_tunable_int(tunable_int: Tunable) -> None:\n \"\"\"\n Check if deep copy works for Tunable object.\n \"\"\"\n tunable_copy = tunable_int.copy()\n assert tunable_int == tunable_copy\n tunable_copy.numerical_value += 200\n assert tunable_int != tunable_copy\n\n\ndef test_copy_tunable_groups(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Check if deep copy works for TunableGroups object.\n \"\"\"\n tunable_groups_copy = tunable_groups.copy()\n assert tunable_groups == tunable_groups_copy\n tunable_groups_copy[\"vmSize\"] = \"Standard_B2ms\"\n assert tunable_groups_copy.is_updated()\n assert not tunable_groups.is_updated()\n assert tunable_groups != tunable_groups_copy\n\n\ndef test_copy_covariant_group(covariant_group: CovariantTunableGroup) -> None:\n \"\"\"\n Check if deep copy works for TunableGroups object.\n \"\"\"\n covariant_group_copy = covariant_group.copy()\n assert covariant_group == covariant_group_copy\n tunable = next(iter(covariant_group.get_tunables()))\n new_value: TunableValue\n if tunable.is_categorical:\n new_value = [x for x in tunable.categories if x != tunable.category][0]\n elif tunable.is_numerical:\n new_value = tunable.numerical_value + 1\n covariant_group_copy[tunable] = new_value\n assert covariant_group_copy.is_updated()\n assert not covariant_group.is_updated()\n assert covariant_group != covariant_group_copy\n" }, { "alpha_fraction": 0.7155172228813171, "alphanum_fraction": 0.7155172228813171, "avg_line_length": 24.375, "blob_id": "2921e9c3daeb8fd24eec61e3fd42b8ac45b06ac8", "content_id": "ad79fa21c9e295d024736fd38be9f1d077af4426", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 812, "license_type": "permissive", "max_line_length": 78, "num_lines": 32, "path": "/mlos_core/mlos_core/spaces/adapters/identity_adapter.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nContains the Identity (no-op) Space Adapter class.\n\"\"\"\n\nimport ConfigSpace\nimport pandas as pd\n\nfrom mlos_core.spaces.adapters.adapter import BaseSpaceAdapter\n\n\nclass IdentityAdapter(BaseSpaceAdapter):\n \"\"\"Identity (no-op) SpaceAdapter class.\n\n Parameters\n ----------\n orig_parameter_space : ConfigSpace.ConfigurationSpace\n The original parameter space to explore.\n \"\"\"\n\n @property\n def target_parameter_space(self) -> ConfigSpace.ConfigurationSpace:\n return self._orig_parameter_space\n\n def transform(self, configuration: pd.DataFrame) -> pd.DataFrame:\n return configuration\n\n def inverse_transform(self, configurations: pd.DataFrame) -> pd.DataFrame:\n return configurations\n" }, { "alpha_fraction": 0.7469879388809204, "alphanum_fraction": 0.7469879388809204, "avg_line_length": 49.23684310913086, "blob_id": "7b2e68bf8fd33bbad937aaecf819d0fc1a2016dc", "content_id": "58f6f945a8c70b2114df08081a43bd5cd9038a12", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1909, "license_type": "permissive", "max_line_length": 269, "num_lines": 38, "path": "/mlos_bench/mlos_bench/config/schemas/environments/README.md", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "# Environment Config Schema\n\nThis directory contains json schema files for the `mlos_bench` [`Environment`](../../../environments/) [configs](../../environments/).\n\n## Organization\n\nThe environment config schema is organized as follows:\n\n- [`environment-schema.json`](./environment-schema.json)\n\n is the root schema.\n This is the only one that should be referenced in the `\"$schema\"` field, and only in the top-level.\n\n This schema references the following subschemas:\n\n - [`composite-env-subschema.json`](./composite-env-subschema.json)\n\n This is a subschema that recognizes a `CompositeEnv` environment.\n\n Since it can include config elements for other leaf elements directly, it also references `leaf-environment-subschema.json`.\n\n - [`leaf-environment-subschemas.json`](./leaf-environment-subschemas.json)\n\n This is a simple subschema that simple recognizes one of any of the other concrete `Environment` subschema files, *except* `CompositeEnv`.\n\n Both leaf and composite environments have common elements, which are defined in the [`base-environment-subschema.json`](./base-environment-subschema.json).\n\n All other leaf environments are concrete subschemas that extend the base environment subschema.\n\n For instance:\n\n - [`local/local-env-subschema.json`](./local/local-env-subschema.json)\n - [`local/local-fileshare-env-subschema.json`](./local/local-fileshare-env-subschema.json)\n - [`remote/os-env-subschema.json`](./remote/os-env-subschema.json)\n - [`remote/remote-env-subschema.json`](./remote/remote-env-subschema.json)\n - [`remote/vm-env-subschema.json`](./remote/vm-env-subschema.json)\n\n Since nested `\"config\"` property objects need to specify their own `\"unevaluatedProperties\": false` setting locally, we also extract common reusable schema elements out to [`common-environment-subschemas.json`.](./common-environment-subschemas.json) for `$ref`-ing.\n" }, { "alpha_fraction": 0.7504322528839111, "alphanum_fraction": 0.7550432085990906, "avg_line_length": 41.317073822021484, "blob_id": "255b4d3633f143cde49976d4f065ec9bbb171548", "content_id": "78df5484b661bf117365b0085982d058cfe17db6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1735, "license_type": "permissive", "max_line_length": 255, "num_lines": 41, "path": "/.devcontainer/scripts/README.md", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "# Devcontainer setup scripts\n\nThis directory contains some script variants to preparing the devcontainer environment.\n\n## `.env` file hack\n\nAllow touching (creating but not altering) a `.env` file prior to devcontainer start so those variables can be populated into the devcontainer environment.\n\nSee Also: <https://github.com/microsoft/vscode-remote-release/issues/4568>\n\n## `mlos_deps.yml` file hack\n\nWhen building the devcontainer image, we don't want to include the MLOS source code initially, just its dependencies, so we filter out the MLOS source code from the `mlos.yml` file when building the image and keep the context to that smaller set of files.\n\nWhen the devcontainer starts, we map the source code (and hence the `mlos.yml` file) into the devcontainer and then run `conda env update` to install the rest of the MLOS dependencies.\n\nThis makes the devcontainer base more cacheable.\n\n## Publishing the devcontainer image for cache reuse\n\nThe build pipeline publishes the devcontainer image to the Azure Container Registry (ACR) so that it can be reused by other builds.\n\nThe secrets for this are stored in the pipeline, but also available in a Key Vault in the MlosCore RG.\n\nOne can also use `az acr login` to push an image manually if need be.\n\n### Image cleanup\n\nTo save space in the ACR, we purge images older than 7 days.\n\n```sh\n#DRY_RUN_ARGS='--dry-run'\n\nPURGE_CMD=\"acr purge --filter 'devcontainer-cli:.*' --filter 'mlos-devcontainer:.*' --untagged --ago 7d $DRY_RUN_ARGS\"\n\n# Setup a daily task:\naz acr task create --name dailyPurgeTask --cmd \"$PURGE_CMD\" --registry mloscore --schedule \"0 1 * * *\" --context /dev/null\n\n# Or, run it manually.\naz acr run --cmd \"$PURGE_CMD\" --registry mloscore --context /dev/null\n```\n" }, { "alpha_fraction": 0.6403712034225464, "alphanum_fraction": 0.6403712034225464, "avg_line_length": 30.536584854125977, "blob_id": "7207811fef282d4f9d5444900c5f4ffc8e1e3742", "content_id": "c7005471171c9639679681fd676090a05fc01fcc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1293, "license_type": "permissive", "max_line_length": 74, "num_lines": 41, "path": "/mlos_bench/mlos_bench/tests/services/remote/mock/mock_remote_exec_service.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nA collection Service functions for mocking remote script execution.\n\"\"\"\n\nfrom typing import Any, Dict, Optional\n\nfrom mlos_bench.services.base_service import Service\nfrom mlos_bench.services.types.remote_exec_type import SupportsRemoteExec\nfrom mlos_bench.tests.services.remote.mock import mock_operation\n\n\nclass MockRemoteExecService(Service, SupportsRemoteExec):\n \"\"\"\n Mock remote script execution service.\n \"\"\"\n\n def __init__(self, config: Optional[Dict[str, Any]] = None,\n global_config: Optional[Dict[str, Any]] = None,\n parent: Optional[Service] = None):\n \"\"\"\n Create a new instance of mock remote exec service.\n\n Parameters\n ----------\n config : dict\n Free-format dictionary that contains the benchmark environment\n configuration.\n global_config : dict\n Free-format dictionary of global parameters.\n parent : Service\n Parent service that can provide mixin functions.\n \"\"\"\n super().__init__(config, global_config, parent)\n self.register({\n \"remote_exec\": mock_operation,\n \"get_remote_exec_results\": mock_operation,\n })\n" }, { "alpha_fraction": 0.6438087821006775, "alphanum_fraction": 0.6622257232666016, "avg_line_length": 30.121952056884766, "blob_id": "45e19278e756e579a9bcda8b00382990ef468aed", "content_id": "748940fb40c371bb80da4f43a415a9f700a7028c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2552, "license_type": "permissive", "max_line_length": 102, "num_lines": 82, "path": "/mlos_core/mlos_core/tests/optimizers/one_hot_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTests for one-hot encoding for certain optimizers.\n\"\"\"\n\nimport pytest\n\nimport pandas as pd\nimport numpy as np\nimport numpy.typing as npt\nimport ConfigSpace as CS\n\nfrom mlos_core.optimizers import SmacOptimizer\n\n# pylint: disable=protected-access,redefined-outer-name\n\n\[email protected]\ndef data_frame() -> pd.DataFrame:\n \"\"\"\n Toy data frame corresponding to the `configuration_space` hyperparameters.\n The columns are deliberately *not* in alphabetic order.\n \"\"\"\n return pd.DataFrame({\n 'y': ['a', 'b', 'c'],\n 'x': [0.1, 0.2, 0.3],\n 'z': [1, 5, 8],\n })\n\n\[email protected]\ndef one_hot() -> npt.NDArray:\n \"\"\"\n One-hot encoding of the `data_frame` above.\n The columns follow the order of the hyperparameters in `configuration_space`.\n \"\"\"\n return np.array([\n [0.1, 1.0, 0.0, 0.0, 1.0],\n [0.2, 0.0, 1.0, 0.0, 5.0],\n [0.3, 0.0, 0.0, 1.0, 8.0],\n ])\n\n\ndef test_to_1hot(configuration_space: CS.ConfigurationSpace,\n data_frame: pd.DataFrame, one_hot: npt.NDArray) -> None:\n \"\"\"\n Toy problem to test one-hot encoding.\n \"\"\"\n optimizer = SmacOptimizer(parameter_space=configuration_space)\n assert optimizer._to_1hot(data_frame) == pytest.approx(one_hot)\n\n\ndef test_from_1hot(configuration_space: CS.ConfigurationSpace,\n data_frame: pd.DataFrame, one_hot: npt.NDArray) -> None:\n \"\"\"\n Toy problem to test one-hot decoding.\n \"\"\"\n optimizer = SmacOptimizer(parameter_space=configuration_space)\n assert optimizer._from_1hot(one_hot).to_dict() == data_frame.to_dict()\n\n\ndef test_round_trip(configuration_space: CS.ConfigurationSpace, data_frame: pd.DataFrame) -> None:\n \"\"\"\n Round-trip test for one-hot-encoding and then decoding a data frame.\n \"\"\"\n optimizer = SmacOptimizer(parameter_space=configuration_space)\n df_round_trip = optimizer._from_1hot(optimizer._to_1hot(data_frame))\n assert df_round_trip.x.to_numpy() == pytest.approx(data_frame.x)\n assert (df_round_trip.y == data_frame.y).all()\n assert (df_round_trip.z == data_frame.z).all()\n\n\ndef test_round_trip_reverse(configuration_space: CS.ConfigurationSpace, one_hot: npt.NDArray) -> None:\n \"\"\"\n Round-trip test for one-hot-decoding and then encoding of a numpy array.\n \"\"\"\n optimizer = SmacOptimizer(parameter_space=configuration_space)\n round_trip = optimizer._to_1hot(optimizer._from_1hot(one_hot))\n assert round_trip == pytest.approx(one_hot)\n" }, { "alpha_fraction": 0.701265811920166, "alphanum_fraction": 0.7063291072845459, "avg_line_length": 19.789474487304688, "blob_id": "6ef41569001b528fbc61eec62e3dc0b890c7b27b", "content_id": "3aeb52f66b93c7775be1a0ac33486750af596870", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 395, "license_type": "permissive", "max_line_length": 65, "num_lines": 19, "path": "/mlos_bench/mlos_bench/config/environments/apps/redis/scripts/remote/setup-workload.sh", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#!/bin/bash\n##\n## Copyright (c) Microsoft Corporation.\n## Licensed under the MIT License.\n##\n\nset -eu\n\nscriptdir=$(dirname \"$(readlink -f \"$0\")\")\ncd \"$scriptdir\"\nsource ./common.sh\n\ncheck_docker\n\n# Remove any previously running/failed instances.\ndocker rm --force $REDIS_CLIENT_NAME 2>/dev/null || true\n\n# To setup the workload, for now, we only need to pull the image.\ndocker pull $REDIS_IMAGE\n" }, { "alpha_fraction": 0.672798216342926, "alphanum_fraction": 0.678093671798706, "avg_line_length": 32.532711029052734, "blob_id": "c6154a859d633088468b445c0dadcd8462dce629", "content_id": "ef2b83864e7c2ce726fc50f0f17e6e556e19c269", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3588, "license_type": "permissive", "max_line_length": 114, "num_lines": 107, "path": "/doc/source/conf.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\n# 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#\n\nimport os\nimport sys\n\nfrom logging import warning\n\nimport sphinx_rtd_theme\n\n#sys.path.insert(0, os.path.abspath('../..'))\nsys.path.insert(0, os.path.abspath('../../mlos_core/mlos_core'))\nsys.path.insert(1, os.path.abspath('../../mlos_bench/mlos_bench'))\n\n\n# -- Project information -----------------------------------------------------\n\nproject = 'MlosCore'\ncopyright = '2022, GSL'\nauthor = 'GSL'\n\n# The full version, including alpha/beta/rc tags\nrelease = '0.1.0'\n\ntry:\n from setuptools_scm import get_version\n version = get_version(root='../..', relative_to=__file__)\n if version is not None:\n release = version\nexcept ImportError:\n warning(\"setuptools_scm not found, using version from _version.py\")\nexcept LookupError as e:\n warning(f\"setuptools_scm failed to find git version, using version from _version.py: {e}\")\n\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 'nbsphinx',\n 'sphinx.ext.autodoc',\n 'sphinx.ext.autosummary',\n 'sphinx.ext.doctest',\n 'numpydoc',\n 'matplotlib.sphinxext.plot_directive',\n]\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# generate autosummary even if no references\nautosummary_generate = True\n# but don't complain about missing stub files\n# See Also: <https://stackoverflow.com/a/73294408>\nnumpydoc_class_members_toctree = False\n\nautodoc_default_options = {\n 'members': True,\n 'undoc-members': True,\n # Don't generate documentation for some (non-private) functions that are more for internal implementation use.\n 'exclude-members': 'mlos_bench.util.check_required_params'\n}\n\n# Generate the plots for the gallery\n# plot_gallery = True\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 = ['_build', '_templates']\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# -- nbsphinx options for rendering notebooks -------------------------------\n# nbsphinx_execute = 'never' # enable to stop nbsphinx from executing notebooks\nnbsphinx_kernel_name = 'python3'\n# Exclude build directory and Jupyter backup files:\nexclude_patterns = ['_build', '**.ipynb_checkpoints']\n" }, { "alpha_fraction": 0.626057505607605, "alphanum_fraction": 0.6277495622634888, "avg_line_length": 20.88888931274414, "blob_id": "3762b64dc89191c853511ca5247496c14009020c", "content_id": "994e512673f2613974e17bb60980ecc47b19a115", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 591, "license_type": "permissive", "max_line_length": 53, "num_lines": 27, "path": "/.devcontainer/scripts/run-cspell.sh", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#!/bin/bash\n##\n## Copyright (c) Microsoft Corporation.\n## Licensed under the MIT License.\n##\n\nset -x\n\nset -eu\nscriptdir=$(dirname \"$(readlink -f \"$0\")\")\ncd \"$scriptdir/\"\n\n# Build the helper container that has the cspell CLI.\n#../build/build-devcontainer-cli.sh\n\n# Make this work inside a devcontainer as well.\nreporoot=$(readlink -f \"$scriptdir/../../\")\nif [ -n \"${LOCAL_WORKSPACE_FOLDER:-}\" ]; then\n reporoot=\"$LOCAL_WORKSPACE_FOLDER\"\nfi\n\ndocker run -i --rm \\\n --user $(id -u):$(id -g) \\\n -v \"$reporoot\":/src \\\n --workdir /src \\\n cspell \\\n cspell lint --no-progress /src/\n" }, { "alpha_fraction": 0.6892454028129578, "alphanum_fraction": 0.7017230987548828, "avg_line_length": 35.58695602416992, "blob_id": "f131dd8ef2a70936633bb790b251b34e5dc99d28", "content_id": "84cef4f5eaab71c112cc1284cffcbf3161d97dcc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 1683, "license_type": "permissive", "max_line_length": 136, "num_lines": 46, "path": "/.devcontainer/build/Dockerfile", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\n# Start with npm\nFROM node:lts-slim\n\n# Install some basic dependencies\nRUN apt-get update \\\n && apt-get install -y --no-install-recommends \\\n apt-transport-https ca-certificates curl gnupg2 software-properties-common \\\n less jq \\\n build-essential g++ libx11-dev libxkbfile-dev libsecret-1-dev python-is-python3 python3-minimal\n\n# Install docker CLI\n# https://docs.docker.com/engine/install/debian/\nRUN install -m 0755 -d /etc/apt/keyrings \\\n && curl -fsSL https://download.docker.com/linux/debian/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg \\\n && chmod a+r /etc/apt/keyrings/docker.gpg \\\n && echo \"deb [arch=\"$(dpkg --print-architecture)\" signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/debian \\\n \"$(. /etc/os-release && echo \"$VERSION_CODENAME\")\" stable\" | tee /etc/apt/sources.list.d/docker.list \\\n && apt-get update \\\n && apt-get install -y --no-install-recommends docker-ce-cli docker-buildx-plugin docker-compose-plugin\n\n# Install the devcontainer CLI\nRUN npm install -g @devcontainers/cli\n\n# Also add the cspell tool to image.\nRUN npm install -g cspell\n\n# Also add the markdown-link-check tool to image.\nRUN npm install -g markdown-link-check\n\n# Adjust the uid/gid of the node user to match the host user\nARG NODE_UID=1000\nARG NODE_GID=1000\nARG DOCKER_GID=999\nRUN groupmod --gid $NODE_GID node \\\n && usermod --uid $NODE_UID --gid $NODE_GID node \\\n && chown -R $NODE_UID:$NODE_GID /home/node \\\n && groupadd --non-unique --gid $DOCKER_GID docker \\\n && adduser node docker\n\nUSER node\nWORKDIR /src\n\nCMD \"/bin/bash\"\n" }, { "alpha_fraction": 0.7346368432044983, "alphanum_fraction": 0.7346368432044983, "avg_line_length": 64.09091186523438, "blob_id": "3783a597c3f76dcff439c1b67ee62c643eebacac", "content_id": "5a7c15e0a7f91f68d303e4c55933a9273e2fc190", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 716, "license_type": "permissive", "max_line_length": 222, "num_lines": 11, "path": "/mlos_bench/mlos_bench/tunables/README.md", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "# Tunables\n\nThis directory contains the code for the *Tunables* used in the [`mlos_bench`](../../../mlos_bench/) benchmarking optimization framework.\n\nA `TunableGroup` is a collection of `Tunables` that are related to each other in some way.\nFor example, they may all be part of the same [`Environment`](../environments/) and hence have the same cost to change together.\nA good example are \"boot time\" kernel parameters vs. \"runtime\" kernel parameters vs. \"application\" parameters.\n\n## TODOs\n\n- Evaluate replacing these entirely with [`ConfigSpace`](https://automl.github.io/ConfigSpace/main/), since that is currently what we use to configure the ([`mlos_core`](../../../mlos_core/)) [`Optimizer`](../optimizers/).\n" }, { "alpha_fraction": 0.751861035823822, "alphanum_fraction": 0.751861035823822, "avg_line_length": 21.38888931274414, "blob_id": "f496a5b7008c22e895d4600d627b4adcc5195b9d", "content_id": "89e71be8154174098367679de874fd6101ccb335", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 403, "license_type": "permissive", "max_line_length": 65, "num_lines": 18, "path": "/mlos_bench/mlos_bench/services/__init__.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nServices for implementing Environments for mlos_bench.\n\"\"\"\n\nfrom mlos_bench.services.base_service import Service\nfrom mlos_bench.services.base_fileshare import FileShareService\nfrom mlos_bench.services.local.local_exec import LocalExecService\n\n\n__all__ = [\n 'Service',\n 'FileShareService',\n 'LocalExecService',\n]\n" }, { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 16, "blob_id": "4e6d6a691032fc47e12525d9d323c94aaaed88f9", "content_id": "f35ea4c7e86039c2bf516c5de1752477f188ce5e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 238, "license_type": "permissive", "max_line_length": 65, "num_lines": 14, "path": "/mlos_bench/mlos_bench/services/local/__init__.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nLocal scheduler side Services for mlos_bench.\n\"\"\"\n\nfrom mlos_bench.services.local.local_exec import LocalExecService\n\n\n__all__ = [\n 'LocalExecService',\n]\n" }, { "alpha_fraction": 0.6816720366477966, "alphanum_fraction": 0.6897106170654297, "avg_line_length": 27.272727966308594, "blob_id": "de4bd83001690d0846b4e46968d482a47141cc00", "content_id": "bbae3b95f035ee72f4ad329d2573a5cef0f44b70", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 622, "license_type": "permissive", "max_line_length": 82, "num_lines": 22, "path": "/mlos_bench/mlos_bench/config/environments/os/linux/boot/scripts/remote/common-boot-time.sh", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "##\n## Copyright (c) Microsoft Corporation.\n## Licensed under the MIT License.\n##\n\n# Environment variables, distribution check, root access for boot-time parameters.\n# This file should be in the VM.\n\n# check for supported distribution\nif ! lsb_release -i -s | grep -q -i -x -e ubuntu -e debian; then\n echo \"ERROR: Unsupported distribution: $(lsb_release -i -s)\" >&2;\n exit 1;\nfi\n\n# check for root access\nif [ $EUID != 0 ]; then\n echo \"ERROR: This script expects to be executed with root privileges.\" >&2\n exit 1\nfi\n\n# file of old boot-time parameters\nORIG_BOOT_TIME=\"${ORIG_BOOT_TIME:-/boot/grub/grub.cfg.bak}\"\n" }, { "alpha_fraction": 0.6201848983764648, "alphanum_fraction": 0.6201848983764648, "avg_line_length": 36.44230651855469, "blob_id": "9d4194aea55f1d84e2e7049649595b59e07cba2e", "content_id": "1ea84daa46901b143fb70ce9be6a88e281df9aa9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3894, "license_type": "permissive", "max_line_length": 115, "num_lines": 104, "path": "/mlos_bench/mlos_bench/environments/remote/os_env.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nOS-level remote Environment on Azure.\n\"\"\"\n\nfrom typing import Optional\n\nimport logging\n\nfrom mlos_bench.environments.base_environment import Environment\nfrom mlos_bench.environments.status import Status\nfrom mlos_bench.services.base_service import Service\nfrom mlos_bench.services.types.vm_provisioner_type import SupportsVMOps\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\n\n_LOG = logging.getLogger(__name__)\n\n\nclass OSEnv(Environment):\n \"\"\"\n OS Level Environment for a host.\n \"\"\"\n\n def __init__(self,\n *,\n name: str,\n config: dict,\n global_config: Optional[dict] = None,\n tunables: Optional[TunableGroups] = None,\n service: Optional[Service] = None):\n \"\"\"\n Create a new environment for remote execution.\n\n Parameters\n ----------\n name: str\n Human-readable name of the environment.\n config : dict\n Free-format dictionary that contains the benchmark environment\n configuration. Each config must have at least the \"tunable_params\"\n and the \"const_args\" sections.\n `RemoteEnv` must also have at least some of the following parameters:\n {setup, run, teardown, wait_boot}\n global_config : dict\n Free-format dictionary of global parameters (e.g., security credentials)\n to be mixed in into the \"const_args\" section of the local config.\n tunables : TunableGroups\n A collection of tunable parameters for *all* environments.\n service: Service\n An optional service object (e.g., providing methods to\n deploy or reboot a VM, etc.).\n \"\"\"\n super().__init__(name=name, config=config, global_config=global_config, tunables=tunables, service=service)\n\n # TODO: Refactor this as \"host\" and \"os\" operations to accommodate SSH service.\n assert self._service is not None and isinstance(self._service, SupportsVMOps), \\\n \"RemoteEnv requires a service that supports host operations\"\n self._host_service: SupportsVMOps = self._service\n\n def setup(self, tunables: TunableGroups, global_config: Optional[dict] = None) -> bool:\n \"\"\"\n Check if the host is up and running; boot it, if necessary.\n\n Parameters\n ----------\n tunables : TunableGroups\n A collection of groups of tunable parameters along with the\n parameters' values. VMEnv tunables are variable parameters that,\n together with the VMEnv configuration, are sufficient to provision\n and start a VM.\n global_config : dict\n Free-format dictionary of global parameters of the environment\n that are not used in the optimization process.\n\n Returns\n -------\n is_success : bool\n True if operation is successful, false otherwise.\n \"\"\"\n _LOG.info(\"OS set up: %s :: %s\", self, tunables)\n if not super().setup(tunables, global_config):\n return False\n\n (status, params) = self._host_service.vm_start(self._params)\n if status.is_pending():\n (status, _) = self._host_service.wait_vm_operation(params)\n\n self._is_ready = status in {Status.SUCCEEDED, Status.READY}\n return self._is_ready\n\n def teardown(self) -> None:\n \"\"\"\n Clean up and shut down the host without deprovisioning it.\n \"\"\"\n _LOG.info(\"OS tear down: %s\", self)\n (status, params) = self._host_service.vm_stop(self._params)\n if status.is_pending():\n (status, _) = self._host_service.wait_vm_operation(params)\n\n super().teardown()\n _LOG.debug(\"Final status of OS stopping: %s :: %s\", self, status)\n" }, { "alpha_fraction": 0.78125, "alphanum_fraction": 0.7832278609275818, "avg_line_length": 67.32432556152344, "blob_id": "3cc825a8b2393ba5312175d16dae74e4e7d87eda", "content_id": "990f73f446e1fac5a2843ef6267dcc12b014a677", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2528, "license_type": "permissive", "max_line_length": 275, "num_lines": 37, "path": "/CONTRIBUTING.md", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "# Contributing to MLOS\n\nThis project welcomes contributions and suggestions.\nMost contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution.\nFor details, visit https://cla.opensource.microsoft.com.\n\nWhen you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment).\nSimply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.\n\nThis project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).\nFor more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [[email protected]](mailto:[email protected]) with any additional questions or comments.\n\n## Details\n\n[`main`](https://github.com/microsoft/MLOS/tree/main) is considered the primary development branch.\n\nWe expect development to follow a typical \"gitflow\" style workflow:\n\n1. Fork a copy of the [MLOS repo in Github](https://github.com/microsoft/MLOS).\n2. Create a development (a.k.a. topic) branch off of `main` to work on changes.\n\n ```shell\n git checkout -b YourDevName/some-topic-description main\n ```\n\n3. Submit changes for inclusion as a [Pull Request on Github](https://github.com/microsoft/MLOS/pulls).\n4. PRs are associated with [Github Issues](https://github.com/microsoft/MLOS/issues) and need [MLOS-committers](https://github.com/orgs/microsoft/teams/MLOS-committers) to sign-off (in addition to other CI pipeline checks like tests and lint checks to pass).\n5. Once approved, the PR can be completed using a squash merge in order to keep a nice linear history.\n\n### Caveats\n\nThere are consumers of MLOS internal to Microsoft that use an internal copy of the Github repo targetting code that is not open-sourced.\nThis arrangement sometimes means porting changes from the internal repo to Github (and vise-versa).\nWhen that happens, the changes are submitted as a PR as described above, with the slight modification of (once approved and passing tests) using a rebase based merge instead of a squash merge in order to allow detecting duplicate patches between the public and private repos.\n\nAdditionally, to try and catch breaking changes we run some extra internal integration tests as well.\nIf they do find issues, we encourage a conversation to occur on how to resolve them in the PRs.\n" }, { "alpha_fraction": 0.665553867816925, "alphanum_fraction": 0.665553867816925, "avg_line_length": 36.87356185913086, "blob_id": "140480ad9cde033fd1f383b2276b7462b0911992", "content_id": "6c3a86fc8a1e95eca4ff138e21ba6fd2d4576d99", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3295, "license_type": "permissive", "max_line_length": 119, "num_lines": 87, "path": "/mlos_core/mlos_core/spaces/adapters/adapter.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nContains the BaseSpaceAdapter abstract class.\n\"\"\"\n\nfrom abc import ABCMeta, abstractmethod\n\nimport ConfigSpace\nimport pandas as pd\n\n\nclass BaseSpaceAdapter(metaclass=ABCMeta):\n \"\"\"SpaceAdapter abstract class defining the basic interface.\n\n Parameters\n ----------\n orig_parameter_space : ConfigSpace.ConfigurationSpace\n The original parameter space to explore.\n \"\"\"\n\n def __init__(self, *, orig_parameter_space: ConfigSpace.ConfigurationSpace):\n self._orig_parameter_space: ConfigSpace.ConfigurationSpace = orig_parameter_space\n self._random_state = orig_parameter_space.random\n\n def __repr__(self) -> str:\n # pylint: disable=consider-using-f-string\n return \"{}(original_parameter_space={}, target_parameter_space={})\".format(\n self.__class__.__name__,\n self.orig_parameter_space,\n self.target_parameter_space,\n )\n\n @property\n def orig_parameter_space(self) -> ConfigSpace.ConfigurationSpace:\n \"\"\"\n Original (user-provided) parameter space to explore.\n \"\"\"\n return self._orig_parameter_space\n\n @property\n @abstractmethod\n def target_parameter_space(self) -> ConfigSpace.ConfigurationSpace:\n \"\"\"\n Target parameter space that is fed to the underlying optimizer.\n \"\"\"\n pass # pylint: disable=unnecessary-pass # pragma: no cover\n\n @abstractmethod\n def transform(self, configuration: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Translates a configuration, which belongs to the target parameter space, to the original parameter space.\n This method is called by the `suggest` method of the `BaseOptimizer` class.\n\n Parameters\n ----------\n configuration : pd.DataFrame\n Pandas dataframe with a single row. Column names are the parameter names of the target parameter space.\n\n Returns\n -------\n configuration : pd.DataFrame\n Pandas dataframe with a single row, containing the translated configuration.\n Column names are the parameter names of the original parameter space.\n \"\"\"\n pass # pylint: disable=unnecessary-pass # pragma: no cover\n\n @abstractmethod\n def inverse_transform(self, configurations: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Translates a configuration, which belongs to the original parameter space, to the target parameter space.\n This method is called by the `register` method of the `BaseOptimizer` class, and performs the inverse operation\n of `BaseSpaceAdapter.transform` method.\n\n Parameters\n ----------\n configurations : pd.DataFrame\n Dataframe of configurations / parameters, which belong to the original parameter space.\n The columns are the parameter names the original parameter space and the rows are the configurations.\n\n Returns\n -------\n configurations : pd.DataFrame\n Dataframe of the translated configurations / parameters.\n The columns are the parameter names of the target parameter space and the rows are the configurations.\n \"\"\"\n pass # pylint: disable=unnecessary-pass # pragma: no cover\n" }, { "alpha_fraction": 0.6114460229873657, "alphanum_fraction": 0.6121902465820312, "avg_line_length": 41.657142639160156, "blob_id": "009fabcbbd816da28107dbde4a47a992a618754b", "content_id": "2c5580faab5e134e1cbfeccdb75282d7ceebd072", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13437, "license_type": "permissive", "max_line_length": 117, "num_lines": 315, "path": "/mlos_bench/mlos_bench/launcher.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nA helper class to load the configuration files, parse the command line parameters,\nand instantiate the main components of mlos_bench system.\n\nIt is used in `mlos_bench.run` module to run the benchmark/optimizer from the\ncommand line.\n\"\"\"\n\nimport logging\nimport argparse\n\nfrom string import Template\nfrom typing import Any, Dict, Iterable, List, Optional, Tuple, Type\n\nfrom mlos_bench.config.schemas import ConfigSchema\nfrom mlos_bench.util import BaseTypeVar\n\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\nfrom mlos_bench.environments.base_environment import Environment\n\nfrom mlos_bench.optimizers.base_optimizer import Optimizer\nfrom mlos_bench.optimizers.mock_optimizer import MockOptimizer\nfrom mlos_bench.optimizers.one_shot_optimizer import OneShotOptimizer\n\nfrom mlos_bench.storage.base_storage import Storage\n\nfrom mlos_bench.services.local.local_exec import LocalExecService\nfrom mlos_bench.services.config_persistence import ConfigPersistenceService\n\n\n_LOG_LEVEL = logging.INFO\n_LOG_FORMAT = '%(asctime)s %(filename)s:%(lineno)d %(funcName)s %(levelname)s %(message)s'\nlogging.basicConfig(level=_LOG_LEVEL, format=_LOG_FORMAT)\n\n_LOG = logging.getLogger(__name__)\n\n\nclass Launcher:\n # pylint: disable=too-few-public-methods,too-many-instance-attributes\n \"\"\"\n Command line launcher for mlos_bench and mlos_core.\n \"\"\"\n\n def __init__(self, description: str, long_text: str = \"\"):\n\n _LOG.info(\"Launch: %s\", description)\n parser = argparse.ArgumentParser(description=f\"{description} : {long_text}\")\n (args, args_rest) = self._parse_args(parser)\n\n # Bootstrap config loader: command line takes priority.\n self._config_loader = ConfigPersistenceService({\"config_path\": args.config_path or []})\n if args.config:\n config = self._config_loader.load_config(args.config, ConfigSchema.CLI)\n assert isinstance(config, Dict)\n config_path = config.get(\"config_path\", [])\n if config_path and not args.config_path:\n # Reset the config loader with the paths from JSON file.\n self._config_loader = ConfigPersistenceService({\"config_path\": config_path})\n else:\n config = {}\n\n log_level = args.log_level or config.get(\"log_level\", _LOG_LEVEL)\n try:\n log_level = int(log_level)\n except ValueError:\n # failed to parse as an int - leave it as a string and let logging\n # module handle whether it's an appropriate log name or not\n log_level = logging.getLevelName(log_level)\n logging.root.setLevel(log_level)\n log_file = args.log_file or config.get(\"log_file\")\n if log_file:\n log_handler = logging.FileHandler(log_file)\n log_handler.setLevel(log_level)\n log_handler.setFormatter(logging.Formatter(_LOG_FORMAT))\n logging.root.addHandler(log_handler)\n\n self._parent_service = LocalExecService(parent=self._config_loader)\n\n self.global_config = self._load_config(\n config.get(\"globals\", []) + (args.globals or []),\n (args.config_path or []) + config.get(\"config_path\", []),\n args_rest,\n {key: val for (key, val) in config.items() if key not in vars(args)},\n )\n self.global_config = self._expand_vars(self.global_config)\n\n env_path = args.environment or config.get(\"environment\")\n if not env_path:\n _LOG.error(\"No environment config specified.\")\n parser.error(\"At least the Environment config must be specified.\" +\n \" Run `mlos_bench --help` and consult `README.md` for more info.\")\n self.root_env_config = self._config_loader.resolve_path(env_path)\n\n self.environment: Environment = self._config_loader.load_environment(\n self.root_env_config, TunableGroups(), self.global_config, service=self._parent_service)\n _LOG.info(\"Init environment: %s\", self.environment)\n\n # NOTE: Init tunable values *after* the Environment, but *before* the Optimizer\n self.tunables = self._init_tunable_values(\n args.random_init or config.get(\"random_init\", False),\n config.get(\"random_seed\") if args.random_seed is None else args.random_seed,\n config.get(\"tunable_values\", []) + (args.tunable_values or [])\n )\n _LOG.info(\"Init tunables: %s\", self.tunables)\n\n self.optimizer = self._load_optimizer(args.optimizer or config.get(\"optimizer\"))\n _LOG.info(\"Init optimizer: %s\", self.optimizer)\n\n self.storage = self._load_storage(args.storage or config.get(\"storage\"))\n _LOG.info(\"Init storage: %s\", self.storage)\n\n self.teardown = args.teardown or config.get(\"teardown\", True)\n\n @staticmethod\n def _parse_args(parser: argparse.ArgumentParser) -> Tuple[argparse.Namespace, List[str]]:\n \"\"\"\n Parse the command line arguments.\n \"\"\"\n parser.add_argument(\n '--config', required=False,\n help='Main JSON5 configuration file. Its keys are the same as the' +\n ' command line options and can be overridden by the latter.\\n' +\n '\\n' +\n ' See the `mlos_bench/config/` tree at https://github.com/microsoft/MLOS/ ' +\n ' for additional config examples for this and other arguments.')\n\n parser.add_argument(\n '--log_file', required=False,\n help='Path to the log file. Use stdout if omitted.')\n\n parser.add_argument(\n '--log_level', required=False, type=str,\n help=f'Logging level. Default is {logging.getLevelName(_LOG_LEVEL)}.' +\n ' Set to DEBUG for debug, WARNING for warnings only.')\n\n parser.add_argument(\n '--config_path', nargs=\"+\", required=False,\n help='One or more locations of JSON config files.')\n\n parser.add_argument(\n '--environment', required=False,\n help='Path to JSON file with the configuration of the benchmarking environment.')\n\n parser.add_argument(\n '--optimizer', required=False,\n help='Path to the optimizer configuration file. If omitted, run' +\n ' a single trial with default (or specified in --tunable_values).')\n\n parser.add_argument(\n '--storage', required=False,\n help='Path to the storage configuration file.' +\n ' If omitted, use the ephemeral in-memory SQL storage.')\n\n parser.add_argument(\n '--random_init', required=False, default=False,\n dest='random_init', action='store_true',\n help='Initialize tunables with random values. (Before applying --tunable_values).')\n\n parser.add_argument(\n '--random_seed', required=False, type=int,\n help='Seed to use with --random_init')\n\n parser.add_argument(\n '--tunable_values', nargs=\"+\", required=False,\n help='Path to one or more JSON files that contain values of the tunable' +\n ' parameters. This can be used for a single trial (when no --optimizer' +\n ' is specified) or as default values for the first run in optimization.')\n\n parser.add_argument(\n '--globals', nargs=\"+\", required=False,\n help='Path to one or more JSON files that contain additional' +\n ' [private] parameters of the benchmarking environment.')\n\n parser.add_argument(\n '--no_teardown', required=False, default=None,\n dest='teardown', action='store_false',\n help='Disable teardown of the environment after the benchmark.')\n\n return parser.parse_known_args()\n\n @staticmethod\n def _try_parse_extra_args(cmdline: Iterable[str]) -> Dict[str, str]:\n \"\"\"\n Helper function to parse global key/value pairs from the command line.\n \"\"\"\n _LOG.debug(\"Extra args: %s\", cmdline)\n\n config = {}\n key = None\n for elem in cmdline:\n if elem.startswith(\"--\"):\n if key is not None:\n raise ValueError(\"Command line argument has no value: \" + key)\n key = elem[2:]\n kv_split = key.split(\"=\", 1)\n if len(kv_split) == 2:\n config[kv_split[0].strip()] = kv_split[1]\n key = None\n else:\n if key is None:\n raise ValueError(\"Command line argument has no key: \" + elem)\n config[key.strip()] = elem\n key = None\n\n if key is not None:\n raise ValueError(\"Command line argument has no value: \" + key)\n\n _LOG.debug(\"Parsed config: %s\", config)\n return config\n\n def _load_config(self,\n args_globals: Iterable[str],\n config_path: Iterable[str],\n args_rest: Iterable[str],\n global_config: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"\n Get key/value pairs of the global configuration parameters\n from the specified config files (if any) and command line arguments.\n \"\"\"\n for config_file in (args_globals or []):\n conf = self._config_loader.load_config(config_file, ConfigSchema.GLOBALS)\n assert isinstance(conf, dict)\n global_config.update(conf)\n global_config.update(Launcher._try_parse_extra_args(args_rest))\n if config_path:\n global_config[\"config_path\"] = config_path\n return global_config\n\n def _expand_vars(self, value: Any) -> Any:\n \"\"\"\n Expand dollar variables in the globals.\n\n NOTE: `self.global_config` must be set.\n \"\"\"\n if isinstance(value, str):\n return Template(value).safe_substitute(self.global_config)\n if isinstance(value, dict):\n return {key: self._expand_vars(val) for (key, val) in value.items()}\n if isinstance(value, list):\n return [self._expand_vars(val) for val in value]\n return value\n\n def _init_tunable_values(self, random_init: bool, seed: Optional[int],\n args_tunables: Optional[str]) -> TunableGroups:\n \"\"\"\n Initialize the tunables and load key/value pairs of the tunable values\n from given JSON files, if specified.\n \"\"\"\n tunables = self.environment.tunable_params\n _LOG.debug(\"Init tunables: default = %s\", tunables)\n\n if random_init:\n tunables = MockOptimizer(\n tunables=tunables, service=None,\n config={\"start_with_defaults\": False, \"seed\": seed}).suggest()\n _LOG.debug(\"Init tunables: random = %s\", tunables)\n\n if args_tunables is not None:\n for data_file in args_tunables:\n values = self._config_loader.load_config(data_file, ConfigSchema.TUNABLE_VALUES)\n assert isinstance(values, Dict)\n tunables.assign(values)\n _LOG.debug(\"Init tunables: load %s = %s\", data_file, tunables)\n\n return tunables\n\n def _load_optimizer(self, args_optimizer: Optional[str]) -> Optimizer:\n \"\"\"\n Instantiate the Optimizer object from JSON config file, if specified\n in the --optimizer command line option. If config file not specified,\n create a one-shot optimizer to run a single benchmark trial.\n \"\"\"\n if args_optimizer is None:\n return OneShotOptimizer(\n self.tunables, config=self.global_config, service=self._parent_service)\n optimizer = self._load(Optimizer, args_optimizer, ConfigSchema.OPTIMIZER) # type: ignore[type-abstract]\n return optimizer\n\n def _load_storage(self, args_storage: Optional[str]) -> Storage:\n \"\"\"\n Instantiate the Storage object from JSON file provided in the --storage\n command line parameter. If omitted, create an ephemeral in-memory SQL\n storage instead.\n \"\"\"\n if args_storage is None:\n # pylint: disable=import-outside-toplevel\n from mlos_bench.storage.sql.storage import SqlStorage\n return SqlStorage(self.tunables, service=self._parent_service,\n config={\"drivername\": \"sqlite\", \"database\": \":memory:\"})\n storage = self._load(Storage, args_storage, ConfigSchema.STORAGE) # type: ignore[type-abstract]\n return storage\n\n def _load(self, cls: Type[BaseTypeVar], json_file_name: str, schema_type: Optional[ConfigSchema]) -> BaseTypeVar:\n \"\"\"\n Create a new instance of class `cls` from JSON configuration.\n\n Note: For abstract types, mypy will complain at the call site.\n Use \"# type: ignore[type-abstract]\" to suppress the warning.\n See Also: https://github.com/python/mypy/issues/4717\n \"\"\"\n class_config = self._config_loader.load_config(json_file_name, schema_type)\n assert isinstance(class_config, Dict)\n ret = self._config_loader.build_generic(\n base_cls=cls,\n tunables=self.tunables,\n service=self._parent_service,\n config=class_config,\n global_config=self.global_config\n )\n assert isinstance(ret, cls)\n return ret\n" }, { "alpha_fraction": 0.6854414343833923, "alphanum_fraction": 0.6871954798698425, "avg_line_length": 35.13380432128906, "blob_id": "4f49329180565981704ae739480e8d0dbcf44f56", "content_id": "e051651adade095c62b3a6e916624f77756370aa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5131, "license_type": "permissive", "max_line_length": 113, "num_lines": 142, "path": "/mlos_bench/mlos_bench/tests/optimizers/mlos_core_opt_smac_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nUnit tests for mock mlos_bench optimizer.\n\"\"\"\n\nimport os\nimport sys\n\nimport pytest\n\nfrom mlos_bench.util import path_join\nfrom mlos_bench.optimizers.mlos_core_optimizer import MlosCoreOptimizer\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\n\nfrom mlos_bench.tests import SEED\n\nfrom mlos_core.optimizers.bayesian_optimizers.smac_optimizer import SmacOptimizer\n\n\nOUTPUT_DIR_PATH_BASE = r'c:/temp' if sys.platform == 'win32' else '/tmp/'\n\n\ndef test_init_mlos_core_smac_opt_bad_trial_count(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Test invalid max_trials initialization of mlos_core SMAC optimizer.\n \"\"\"\n test_opt_config = {\n 'optimizer_type': 'SMAC',\n 'max_trials': 10,\n 'max_iterations': 11,\n 'seed': SEED,\n }\n with pytest.raises(AssertionError):\n opt = MlosCoreOptimizer(tunable_groups, test_opt_config)\n assert opt is None\n\n\ndef test_init_mlos_core_smac_opt_max_trials(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Test max_trials initialization of mlos_core SMAC optimizer.\n \"\"\"\n test_opt_config = {\n 'optimizer_type': 'SMAC',\n 'max_iterations': 123,\n 'seed': SEED,\n }\n opt = MlosCoreOptimizer(tunable_groups, test_opt_config)\n # pylint: disable=protected-access\n assert isinstance(opt._opt, SmacOptimizer)\n assert opt._opt.base_optimizer.scenario.n_trials == test_opt_config['max_iterations']\n\n\ndef test_init_mlos_core_smac_absolute_output_directory(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Test absolute path output directory initialization of mlos_core SMAC optimizer.\n \"\"\"\n test_opt_config = {\n 'optimizer_type': 'SMAC',\n 'output_directory': path_join(OUTPUT_DIR_PATH_BASE, 'test_output_dir'),\n 'seed': SEED,\n }\n opt = MlosCoreOptimizer(tunable_groups, test_opt_config)\n assert isinstance(opt, MlosCoreOptimizer)\n # pylint: disable=protected-access\n assert isinstance(opt._opt, SmacOptimizer)\n # Final portions of the path are generated by SMAC when run_name is not specified.\n assert path_join(str(opt._opt.base_optimizer.scenario.output_directory)).startswith(\n str(test_opt_config['output_directory']))\n\n\ndef test_init_mlos_core_smac_relative_output_directory(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Test relative path output directory initialization of mlos_core SMAC optimizer.\n \"\"\"\n test_opt_config = {\n 'optimizer_type': 'SMAC',\n 'output_directory': 'test_output_dir',\n 'seed': SEED,\n }\n opt = MlosCoreOptimizer(tunable_groups, test_opt_config)\n assert isinstance(opt, MlosCoreOptimizer)\n # pylint: disable=protected-access\n assert isinstance(opt._opt, SmacOptimizer)\n assert path_join(str(opt._opt.base_optimizer.scenario.output_directory)).startswith(\n path_join(os.getcwd(), str(test_opt_config['output_directory'])))\n\n\ndef test_init_mlos_core_smac_relative_output_directory_with_run_name(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Test relative path output directory initialization of mlos_core SMAC optimizer.\n \"\"\"\n test_opt_config = {\n 'optimizer_type': 'SMAC',\n 'output_directory': 'test_output_dir',\n 'run_name': 'test_run',\n 'seed': SEED,\n }\n opt = MlosCoreOptimizer(tunable_groups, test_opt_config)\n assert isinstance(opt, MlosCoreOptimizer)\n # pylint: disable=protected-access\n assert isinstance(opt._opt, SmacOptimizer)\n assert path_join(str(opt._opt.base_optimizer.scenario.output_directory)).startswith(\n path_join(os.getcwd(), str(test_opt_config['output_directory']), str(test_opt_config['run_name'])))\n\n\ndef test_init_mlos_core_smac_relative_output_directory_with_experiment_id(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Test relative path output directory initialization of mlos_core SMAC optimizer.\n \"\"\"\n test_opt_config = {\n 'optimizer_type': 'SMAC',\n 'output_directory': 'test_output_dir',\n 'seed': SEED,\n }\n global_config = {\n 'experiment_id': 'experiment_id',\n }\n opt = MlosCoreOptimizer(tunable_groups, test_opt_config, global_config)\n assert isinstance(opt, MlosCoreOptimizer)\n # pylint: disable=protected-access\n assert isinstance(opt._opt, SmacOptimizer)\n assert path_join(str(opt._opt.base_optimizer.scenario.output_directory)).startswith(\n path_join(os.getcwd(), str(test_opt_config['output_directory']), global_config['experiment_id']))\n\n\ndef test_init_mlos_core_smac_temp_output_directory(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Test random output directory initialization of mlos_core SMAC optimizer.\n \"\"\"\n test_opt_config = {\n 'optimizer_type': 'SMAC',\n 'output_directory': None,\n 'seed': SEED,\n }\n opt = MlosCoreOptimizer(tunable_groups, test_opt_config)\n assert isinstance(opt, MlosCoreOptimizer)\n # pylint: disable=protected-access\n assert isinstance(opt._opt, SmacOptimizer)\n assert opt._opt.base_optimizer.scenario.output_directory is not None\n" }, { "alpha_fraction": 0.7086662650108337, "alphanum_fraction": 0.7133784294128418, "avg_line_length": 39.00819778442383, "blob_id": "cd9a5a27f437d9948a23ea310e7d61ad509d1610", "content_id": "09fb8a6abdc7cac42594b43f830cc425a20593e1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4881, "license_type": "permissive", "max_line_length": 289, "num_lines": 122, "path": "/mlos_bench/mlos_bench/config/experiments/README.md", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "# Experiment-specific parameters\n\nSome global parameters vary from experiment to experiment.\nIt makes sense to store them in a separate file and include it in the `\"globals\"` section of the CLI config - or, better yet, specify it in the `--globals` option in the command line.\nJust like with other global configs, the values from the experiment configuration will override the corresponding values in the Environment, Service, Optimizer, and Storage configs down the configuration tree.\nThis way we can keep most of our configs immutable and reusable across different experiments and system configurations.\n\n## Working example\n\nLet's take a look at the [`experiment_RedisBench.jsonc`](experiment_RedisBench.jsonc) file.\nit looks like this:\n\n```jsonc\n{\n \"experiment_id\": \"RedisBench\",\n \"trial_id\": 1,\n\n \"deploymentName\": \"RedisBench\",\n \"vmName\": \"os-autotune-linux-vm\",\n\n \"resourceGroup\": \"os-autotune\",\n \"location\": \"westus2\",\n\n \"virtualNetworkName\": \"mlos-2vms-vnet\",\n \"subnetName\": \"mlos-2vms-subnet\",\n\n \"storageAccountName\": \"osatsharedstorage\",\n \"storageFileShareName\": \"os-autotune-file-share\",\n\n \"vmSize\": \"Standard_B2s\",\n \"ubuntuOSVersion\": \"18.04-LTS\",\n\n \"tunable_params_map\": {\n\n // VM provisioning parameter groups (see `azure-vm-tunables.jsonc`):\n // [\"azure-vm\"] (not used at the moment)\n \"provision\": [],\n\n // Boot-time Linux parameter groups (see `linux-boot-tunables.jsonc`):\n // [\"linux-kernel-boot\"]\n \"linux-boot\": [\"linux-kernel-boot\"],\n\n // Runtime Linux parameter groups (see `linux-runtime-tunables.jsonc`):\n // [\"linux-swap\", \"linux-hugepages-2048kB\", \"linux-scheduler\"]\n \"linux-runtime\": [\"linux-swap\", \"linux-scheduler\"],\n\n // Redis config parameter groups (see `redis-tunables.jsonc`):\n // [\"redis\"]\n \"redis\": []\n },\n\n \"optimization_target\": \"score\",\n \"optimization_direction\": \"min\"\n}\n```\n\nIt has a mixture of parameters from different components of the framework. for example, the following section contains the parameters that are specific to the Azure VM provisioning:\n\n```jsonc\n{\n \"resourceGroup\": \"os-autotune\",\n \"location\": \"westus2\",\n\n \"virtualNetworkName\": \"mlos-2vms-vnet\",\n \"subnetName\": \"mlos-2vms-subnet\",\n\n \"storageAccountName\": \"osatsharedstorage\",\n \"storageFileShareName\": \"os-autotune-file-share\",\n\n \"vmSize\": \"Standard_B2s\",\n \"ubuntuOSVersion\": \"18.04-LTS\"\n}\n```\n\nAt runtime, these values will be pushed down to the `AzureVMService` configuration, e.g., [`service-linux-vm-ops.jsonc`](../services/remote/azure/service-linux-vm-ops.jsonc).\n\nLikewise, parameters\n\n```jsonc\n{\n \"optimization_target\": \"score\",\n \"optimization_direction\": \"min\"\n}\n```\n\nwill be pushed down to the `Optimizer` configuration, e.g., [`mlos_core_flaml.jsonc`](../optimizers/mlos_core_flaml.jsonc), and so on.\n\n> NOTE: it is perfectly ok to have several files with the experiment-specific parameters (say, one for Azure, another one for Storage, and so on) and either include them in the `\"globals\"` section of the CLI config, and/or specify them in the command line when running the experiment, e.g.\n>\n> ```bash\n> mlos_bench --config mlos_bench/mlos_bench/config/cli/azure-redis-opt.jsonc --globals experiment_Redis_Azure.jsonc experiment_Redis_Tunables.jsonc --max_iterations 10\n> ```\n>\n> (Note several files after the `--globals` option).\n\n### Tunable Parameters Map\n\nThe `\"tunable_params_map\"` section is a bit more interesting.\nIt allows us to specify which tunable parameters we want to optimize for.\nValues on the right side of the mapping correspond to the names of the covariant tunable groups, e.g., `\"linux-swap\"` or `\"linux-scheduler\"` in [`linux-runtime-tunables.jsonc`](../environments/os/linux/runtime/linux-runtime-tunables.jsonc).\nIdentifiers on the left side, e.g., `\"linux-runtime\"`, are arbitrary and are used as a reference to the corresponding covariant tunable groups.\nWe can use those identifiers inside the `\"tunable_params\"` section of the Environment configs to specify which tunable parameters we want to optimize for.\nWe use a `$` prefix to distinguish such identifiers from the actual names of the covariant groups.\nIn the Environment config, it will look like the following:\n\n```jsonc\n{\n \"name\": \"Generate Linux kernel parameters for Ubuntu\",\n \"class\": \"mlos_bench.environments.LocalFileShareEnv\",\n\n \"config\": {\n\n \"tunable_params\": [\"$linux-runtime\"],\n\n // ...\n }\n}\n```\n\nIf there are several dollar variables in the `\"tunable_params\"` section, they will get concatenated into a single list of covariant groups identifiers.\n\nThis way, we can enable and disable optimization for certain parameters in the top-level experiment config and keep the leaf Environment configs immutable and reusable across different experiments and system configurations.\n" }, { "alpha_fraction": 0.7010127902030945, "alphanum_fraction": 0.7023337483406067, "avg_line_length": 32.89552307128906, "blob_id": "3c71944b12ff34b4bd7bf5f2311b498ce63aca95", "content_id": "1b161174fbc389988deae4a7679ecae2da7faa21", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2271, "license_type": "permissive", "max_line_length": 100, "num_lines": 67, "path": "/mlos_bench/mlos_bench/tests/services/remote/azure/conftest.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nConfiguration test fixtures for azure_services in mlos_bench.\n\"\"\"\n\nfrom unittest.mock import patch\n\nimport pytest\n\nfrom mlos_bench.services.config_persistence import ConfigPersistenceService\nfrom mlos_bench.services.remote.azure import AzureAuthService, AzureVMService, AzureFileShareService\n\n# pylint: disable=redefined-outer-name\n\n\[email protected]\ndef config_persistence_service() -> ConfigPersistenceService:\n \"\"\"\n Test fixture for ConfigPersistenceService.\n \"\"\"\n return ConfigPersistenceService()\n\n\[email protected]\ndef azure_auth_service(config_persistence_service: ConfigPersistenceService,\n monkeypatch: pytest.MonkeyPatch) -> AzureAuthService:\n \"\"\"\n Creates a dummy AzureAuthService for tests that require it.\n \"\"\"\n auth = AzureAuthService(config={}, global_config={}, parent=config_persistence_service)\n monkeypatch.setattr(auth, \"get_access_token\", lambda: \"TEST_TOKEN\")\n return auth\n\n\[email protected]\ndef azure_vm_service(azure_auth_service: AzureAuthService) -> AzureVMService:\n \"\"\"\n Creates a dummy Azure VM service for tests that require it.\n \"\"\"\n return AzureVMService(config={\n \"deploymentTemplatePath\": \"services/remote/azure/arm-templates/azuredeploy-ubuntu-vm.jsonc\",\n \"deploymentName\": \"TEST_DEPLOYMENT\",\n \"subscription\": \"TEST_SUB\",\n \"resourceGroup\": \"TEST_RG\",\n \"deploymentTemplateParameters\": {\n \"location\": \"westus2\",\n },\n \"vmName\": \"test-vm\", # Should come from the upper-level config\n \"pollInterval\": 1,\n \"pollTimeout\": 2\n }, global_config={}, parent=azure_auth_service)\n\n\[email protected]\ndef azure_fileshare(config_persistence_service: ConfigPersistenceService) -> AzureFileShareService:\n \"\"\"\n Creates a dummy AzureFileShareService for tests that require it.\n \"\"\"\n with patch(\"mlos_bench.services.remote.azure.azure_fileshare.ShareClient\"):\n return AzureFileShareService(config={\n \"storageAccountName\": \"TEST_ACCOUNT_NAME\",\n \"storageFileShareName\": \"TEST_FS_NAME\",\n \"storageAccountKey\": \"TEST_ACCOUNT_KEY\"\n }, global_config={}, parent=config_persistence_service)\n" }, { "alpha_fraction": 0.621810257434845, "alphanum_fraction": 0.6420937776565552, "avg_line_length": 33.47368240356445, "blob_id": "e5358e4f11550d2f448c644d3c3261109c126473", "content_id": "f4597d8ea15f97a523589a3923b9c072c1789008", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4585, "license_type": "permissive", "max_line_length": 90, "num_lines": 133, "path": "/mlos_bench/mlos_bench/tests/optimizers/toy_optimization_loop_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nToy optimization loop to test the optimizers on mock benchmark environment.\n\"\"\"\n\nfrom typing import Tuple\n\nimport logging\n\nimport pytest\n\nfrom mlos_core import config_to_dataframe\nfrom mlos_core.optimizers.bayesian_optimizers.smac_optimizer import SmacOptimizer\nfrom mlos_bench.optimizers.convert_configspace import tunable_values_to_configuration\n\nfrom mlos_bench.environments.base_environment import Environment\nfrom mlos_bench.environments.mock_env import MockEnv\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\nfrom mlos_bench.optimizers.base_optimizer import Optimizer\nfrom mlos_bench.optimizers.mock_optimizer import MockOptimizer\nfrom mlos_bench.optimizers.mlos_core_optimizer import MlosCoreOptimizer\n\n\n# For debugging purposes output some warnings which are captured with failed tests.\nDEBUG = True\nlogger = logging.debug\nif DEBUG:\n logger = logging.warning\n\n\ndef _optimize(env: Environment, opt: Optimizer) -> Tuple[float, TunableGroups]:\n \"\"\"\n Toy optimization loop.\n \"\"\"\n assert opt.not_converged()\n\n while opt.not_converged():\n\n with env as env_context:\n\n tunables = opt.suggest()\n\n logger(\"tunables: %s\", str(tunables))\n # pylint: disable=protected-access\n if isinstance(opt, MlosCoreOptimizer) and isinstance(opt._opt, SmacOptimizer):\n config = tunable_values_to_configuration(tunables)\n config_df = config_to_dataframe(config)\n logger(\"config: %s\", str(config))\n try:\n logger(\"prediction: %s\", opt._opt.surrogate_predict(config_df))\n except RuntimeError:\n pass\n\n assert env_context.setup(tunables)\n\n (status, output) = env_context.run()\n assert status.is_succeeded()\n assert output is not None\n score = output['score']\n assert 60 <= score <= 120\n logger(\"score: %s\", str(score))\n\n opt.register(tunables, status, score)\n\n (best_score, best_tunables) = opt.get_best_observation()\n assert isinstance(best_score, float) and isinstance(best_tunables, TunableGroups)\n return (best_score, best_tunables)\n\n\ndef test_mock_optimization_loop(mock_env_no_noise: MockEnv,\n mock_opt: MockOptimizer) -> None:\n \"\"\"\n Toy optimization loop with mock environment and optimizer.\n \"\"\"\n (score, tunables) = _optimize(mock_env_no_noise, mock_opt)\n assert score == pytest.approx(64.9, 0.01)\n assert tunables.get_param_values() == {\n \"vmSize\": \"Standard_B2ms\",\n \"idle\": \"halt\",\n \"kernel_sched_migration_cost_ns\": 117025,\n \"kernel_sched_latency_ns\": 149827706,\n }\n\n\ndef test_mock_optimization_loop_no_defaults(mock_env_no_noise: MockEnv,\n mock_opt_no_defaults: MockOptimizer) -> None:\n \"\"\"\n Toy optimization loop with mock environment and optimizer.\n \"\"\"\n (score, tunables) = _optimize(mock_env_no_noise, mock_opt_no_defaults)\n assert score == pytest.approx(60.97, 0.01)\n assert tunables.get_param_values() == {\n \"vmSize\": \"Standard_B2s\",\n \"idle\": \"halt\",\n \"kernel_sched_migration_cost_ns\": 49122,\n \"kernel_sched_latency_ns\": 234760738,\n }\n\n\ndef test_flaml_optimization_loop(mock_env_no_noise: MockEnv,\n flaml_opt: MlosCoreOptimizer) -> None:\n \"\"\"\n Toy optimization loop with mock environment and FLAML optimizer.\n \"\"\"\n (score, tunables) = _optimize(mock_env_no_noise, flaml_opt)\n assert score == pytest.approx(60.15, 0.01)\n assert tunables.get_param_values() == {\n \"vmSize\": \"Standard_B2s\",\n \"idle\": \"halt\",\n \"kernel_sched_migration_cost_ns\": 50132,\n \"kernel_sched_latency_ns\": 22674895,\n }\n\n\n# @pytest.mark.skip(reason=\"SMAC is not deterministic\")\ndef test_smac_optimization_loop(mock_env_no_noise: MockEnv,\n smac_opt: MlosCoreOptimizer) -> None:\n \"\"\"\n Toy optimization loop with mock environment and SMAC optimizer.\n \"\"\"\n (score, tunables) = _optimize(mock_env_no_noise, smac_opt)\n expected_score = 73.59\n expected_tunable_values = {\n \"vmSize\": \"Standard_B2s\",\n \"idle\": \"mwait\",\n \"kernel_sched_migration_cost_ns\": 319025,\n \"kernel_sched_latency_ns\": 499339615,\n }\n assert score == pytest.approx(expected_score, 0.01)\n assert tunables.get_param_values() == expected_tunable_values\n" }, { "alpha_fraction": 0.6103973984718323, "alphanum_fraction": 0.6151777505874634, "avg_line_length": 27.36440658569336, "blob_id": "40dff5842178797a83484e3c08a20bbaf7ca6efe", "content_id": "6a91b14016b0642a2ca938ad4df526d64e15c424", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3347, "license_type": "permissive", "max_line_length": 83, "num_lines": 118, "path": "/mlos_bench/mlos_bench/tests/tunables/tunable_comparison_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nUnit tests for checking tunable comparisons.\n\"\"\"\n\nimport pytest\n\nfrom mlos_bench.tunables.covariant_group import CovariantTunableGroup\nfrom mlos_bench.tunables.tunable import Tunable\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\n\n\ndef test_tunable_int_value_lt(tunable_int: Tunable) -> None:\n \"\"\"\n Tests that the __lt__ operator works as expected.\n \"\"\"\n tunable_int_2 = tunable_int.copy()\n tunable_int_2.numerical_value += 1\n assert tunable_int.numerical_value < tunable_int_2.numerical_value\n assert tunable_int < tunable_int_2\n\n\ndef test_tunable_int_name_lt(tunable_int: Tunable) -> None:\n \"\"\"\n Tests that the __lt__ operator works as expected.\n \"\"\"\n tunable_int_2 = tunable_int.copy()\n tunable_int_2._name = \"aaa\" # pylint: disable=protected-access\n assert tunable_int_2 < tunable_int\n\n\ndef test_tunable_categorical_value_lt(tunable_categorical: Tunable) -> None:\n \"\"\"\n Tests that the __lt__ operator works as expected.\n \"\"\"\n tunable_categorical_2 = tunable_categorical.copy()\n new_value = [\n x for x in tunable_categorical.categories\n if x != tunable_categorical.category and x is not None\n ][0]\n assert tunable_categorical.category is not None\n tunable_categorical_2.category = new_value\n if tunable_categorical.category < new_value:\n assert tunable_categorical < tunable_categorical_2\n elif tunable_categorical.category > new_value:\n assert tunable_categorical > tunable_categorical_2\n\n\ndef test_tunable_categorical_lt_null() -> None:\n \"\"\"\n Tests that the __lt__ operator works as expected.\n \"\"\"\n tunable_cat = Tunable(\n name=\"same-name\",\n config={\n \"type\": \"categorical\",\n \"values\": [\"floof\", \"fuzz\"],\n \"default\": \"floof\",\n }\n )\n tunable_dog = Tunable(\n name=\"same-name\",\n config={\n \"type\": \"categorical\",\n \"values\": [None, \"doggo\"],\n \"default\": None,\n }\n )\n assert tunable_dog < tunable_cat\n\n\ndef test_tunable_lt_same_name_different_type() -> None:\n \"\"\"\n Tests that the __lt__ operator works as expected.\n \"\"\"\n tunable_cat = Tunable(\n name=\"same-name\",\n config={\n \"type\": \"categorical\",\n \"values\": [\"floof\", \"fuzz\"],\n \"default\": \"floof\",\n }\n )\n tunable_int = Tunable(\n name=\"same-name\",\n config={\n \"type\": \"int\",\n \"range\": [1, 3],\n \"default\": 2,\n }\n )\n assert tunable_cat < tunable_int\n\n\ndef test_tunable_lt_different_object(tunable_int: Tunable) -> None:\n \"\"\"\n Tests that the __lt__ operator works as expected.\n \"\"\"\n assert (tunable_int < \"foo\") is False\n with pytest.raises(TypeError):\n assert \"foo\" < tunable_int # type: ignore[operator]\n\n\ndef test_tunable_group_ne_object(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Tests that the __eq__ operator works as expected with other objects.\n \"\"\"\n assert tunable_groups != \"foo\"\n\n\ndef test_covariant_group_ne_object(covariant_group: CovariantTunableGroup) -> None:\n \"\"\"\n Tests that the __eq__ operator works as expected with other objects.\n \"\"\"\n assert covariant_group != \"foo\"\n" }, { "alpha_fraction": 0.5825176239013672, "alphanum_fraction": 0.5830207467079163, "avg_line_length": 40.405303955078125, "blob_id": "ebbd15fda8c50da8bd44e12fe91c89aeec95a05d", "content_id": "bbef753b77773118c9ce180041c6da5189c61242", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21862, "license_type": "permissive", "max_line_length": 121, "num_lines": 528, "path": "/mlos_bench/mlos_bench/services/config_persistence.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nHelper functions to load, instantiate, and serialize Python objects\nthat encapsulate benchmark environments, tunable parameters, and\nservice functions.\n\"\"\"\n\nimport os\nimport sys\n\nimport json # For logging only\nimport logging\n\nfrom typing import Any, Dict, Iterable, List, Optional, Tuple, Type\n\nimport json5 # To read configs with comments and other JSON5 syntax features\nfrom jsonschema import ValidationError, SchemaError\n\nfrom mlos_bench.config.schemas import ConfigSchema\nfrom mlos_bench.environments.base_environment import Environment\nfrom mlos_bench.services.base_service import Service\nfrom mlos_bench.services.types.config_loader_type import SupportsConfigLoading\nfrom mlos_bench.tunables.tunable import TunableValue\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\nfrom mlos_bench.util import instantiate_from_config, merge_parameters, path_join, preprocess_dynamic_configs, BaseTypeVar\n\nif sys.version_info < (3, 10):\n from importlib_resources import files\nelse:\n from importlib.resources import files\n\n\n_LOG = logging.getLogger(__name__)\n\n\nclass ConfigPersistenceService(Service, SupportsConfigLoading):\n \"\"\"\n Collection of methods to deserialize the Environment, Service, and TunableGroups objects.\n \"\"\"\n\n BUILTIN_CONFIG_PATH = str(files(\"mlos_bench.config\").joinpath(\"\")).replace(\"\\\\\", \"/\")\n\n def __init__(self,\n config: Optional[Dict[str, Any]] = None,\n global_config: Optional[Dict[str, Any]] = None,\n parent: Optional[Service] = None):\n \"\"\"\n Create a new instance of config persistence service.\n\n Parameters\n ----------\n config : dict\n Free-format dictionary that contains parameters for the service.\n (E.g., root path for config files, etc.)\n global_config : dict\n Free-format dictionary of global parameters.\n parent : Service\n An optional parent service that can provide mixin functions.\n \"\"\"\n super().__init__(config, global_config, parent)\n self._config_path: List[str] = self.config.get(\"config_path\", [])\n self._config_loader_service = self\n\n if self.BUILTIN_CONFIG_PATH not in self._config_path:\n self._config_path.append(self.BUILTIN_CONFIG_PATH)\n\n # Register methods that we want to expose to the Environment objects.\n self.register([\n self.resolve_path,\n self.load_config,\n self.prepare_class_load,\n self.build_service,\n self.build_environment,\n self.load_services,\n self.load_environment,\n self.load_environment_list,\n ])\n\n def resolve_path(self, file_path: str,\n extra_paths: Optional[Iterable[str]] = None) -> str:\n \"\"\"\n Prepend the suitable `_config_path` to `path` if the latter is not absolute.\n If `_config_path` is `None` or `path` is absolute, return `path` as is.\n\n Parameters\n ----------\n file_path : str\n Path to the input config file.\n extra_paths : Iterable[str]\n Additional directories to prepend to the list of search paths.\n\n Returns\n -------\n path : str\n An actual path to the config or script.\n \"\"\"\n path_list = list(extra_paths or []) + self._config_path\n _LOG.debug(\"Resolve path: %s in: %s\", file_path, path_list)\n if not os.path.isabs(file_path):\n for path in path_list:\n full_path = path_join(path, file_path, abs_path=True)\n if os.path.exists(full_path):\n _LOG.debug(\"Path resolved: %s\", full_path)\n return full_path\n _LOG.debug(\"Path not resolved: %s\", file_path)\n return file_path\n\n def load_config(self,\n json_file_name: str,\n schema_type: Optional[ConfigSchema],\n ) -> Dict[str, Any]:\n \"\"\"\n Load JSON config file. Search for a file relative to `_config_path`\n if the input path is not absolute.\n This method is exported to be used as a service.\n\n Parameters\n ----------\n json_file_name : str\n Path to the input config file.\n schema_type : Optional[ConfigSchema]\n The schema type to validate the config against.\n\n Returns\n -------\n config : Union[dict, List[dict]]\n Free-format dictionary that contains the configuration.\n \"\"\"\n json_file_name = self.resolve_path(json_file_name)\n _LOG.info(\"Load config: %s\", json_file_name)\n with open(json_file_name, mode='r', encoding='utf-8') as fh_json:\n config = json5.load(fh_json)\n if schema_type is not None:\n try:\n schema_type.validate(config)\n except (ValidationError, SchemaError) as ex:\n _LOG.error(\"Failed to validate config %s against schema type %s at %s\",\n json_file_name, schema_type.name, schema_type.value)\n raise ValueError(f\"Failed to validate config {json_file_name} against \" +\n f\"schema type {schema_type.name} at {schema_type.value}\") from ex\n if isinstance(config, dict) and config.get(\"$schema\"):\n # Remove $schema attributes from the config after we've validated\n # them to avoid passing them on to other objects\n # (e.g. SqlAlchemy based storage initializers).\n # NOTE: we only do this for internal schemas.\n # Other configs that get loaded may need the schema field\n # (e.g. Azure ARM templates).\n del config[\"$schema\"]\n return config # type: ignore[no-any-return]\n\n def prepare_class_load(self, config: Dict[str, Any],\n global_config: Optional[Dict[str, Any]] = None,\n parent_args: Optional[Dict[str, TunableValue]] = None) -> Tuple[str, Dict[str, Any]]:\n \"\"\"\n Extract the class instantiation parameters from the configuration.\n Mix-in the global parameters and resolve the local file system paths,\n where it is required.\n\n Parameters\n ----------\n config : dict\n Configuration of the optimizer.\n global_config : dict\n Global configuration parameters (optional).\n parent_args : Dict[str, TunableValue]\n An optional reference of the parent CompositeEnv's const_args used to\n expand dynamic config parameters from.\n\n Returns\n -------\n (class_name, class_config) : (str, dict)\n Name of the class to instantiate and its configuration.\n \"\"\"\n class_name = config[\"class\"]\n class_config = config.setdefault(\"config\", {})\n\n # Replace any appearance of \"$param_name\" in the const_arg values with\n # the value from the parent CompositeEnv.\n # Note: we could consider expanding this feature to additional config\n # sections in the future, but for now only use it in const_args.\n if class_name.startswith(\"mlos_bench.environments.\"):\n const_args = class_config.get(\"const_args\", {})\n preprocess_dynamic_configs(dest=const_args, source=parent_args)\n\n merge_parameters(dest=class_config, source=global_config)\n\n for key in set(class_config).intersection(config.get(\"resolve_config_property_paths\", [])):\n if isinstance(class_config[key], str):\n class_config[key] = self.resolve_path(class_config[key])\n elif isinstance(class_config[key], (list, tuple)):\n class_config[key] = [self.resolve_path(path) for path in class_config[key]]\n else:\n raise ValueError(f\"Parameter {key} must be a string or a list\")\n\n if _LOG.isEnabledFor(logging.DEBUG):\n _LOG.debug(\"Instantiating: %s with config:\\n%s\",\n class_name, json.dumps(class_config, indent=2))\n\n return (class_name, class_config)\n\n def build_generic(self, *,\n base_cls: Type[BaseTypeVar],\n tunables: TunableGroups,\n service: Service,\n config: Dict[str, Any],\n global_config: Optional[Dict[str, Any]] = None) -> BaseTypeVar:\n \"\"\"\n Generic instantiation of mlos_bench objects like Storage and Optimizer\n that depend on Service and TunableGroups.\n\n A class *MUST* have a constructor that takes four named arguments:\n (tunables, config, global_config, service)\n\n Parameters\n ----------\n base_cls : ClassType\n A base class of the object to instantiate.\n tunables : TunableGroups\n Tunable parameters of the environment. We need them to validate the\n configurations of merged-in experiments and restored/pending trials.\n service: Service\n An optional service object (e.g., providing methods to load config files, etc.)\n config : dict\n Configuration of the class to instantiate, as loaded from JSON.\n global_config : dict\n Global configuration parameters (optional).\n\n Returns\n -------\n inst : Any\n A new instance of the `cls` class.\n \"\"\"\n tunables_path = config.get(\"include_tunables\")\n if tunables_path is not None:\n tunables = self._load_tunables(tunables_path, tunables)\n (class_name, class_config) = self.prepare_class_load(config, global_config)\n inst = instantiate_from_config(base_cls, class_name,\n tunables=tunables,\n config=class_config,\n global_config=global_config,\n service=service)\n _LOG.info(\"Created: %s %s\", base_cls.__name__, inst)\n return inst\n\n def build_environment(self, # pylint: disable=too-many-arguments\n config: Dict[str, Any],\n tunables: TunableGroups,\n global_config: Optional[Dict[str, Any]] = None,\n parent_args: Optional[Dict[str, TunableValue]] = None,\n service: Optional[Service] = None) -> Environment:\n \"\"\"\n Factory method for a new environment with a given config.\n\n Parameters\n ----------\n config : dict\n A dictionary with three mandatory fields:\n \"name\": Human-readable string describing the environment;\n \"class\": FQN of a Python class to instantiate;\n \"config\": Free-format dictionary to pass to the constructor.\n tunables : TunableGroups\n A (possibly empty) collection of groups of tunable parameters for\n all environments.\n global_config : dict\n Global parameters to add to the environment config.\n parent_args : Dict[str, TunableValue]\n An optional reference of the parent CompositeEnv's const_args used to\n expand dynamic config parameters from.\n service: Service\n An optional service object (e.g., providing methods to\n deploy or reboot a VM, etc.).\n\n Returns\n -------\n env : Environment\n An instance of the `Environment` class initialized with `config`.\n \"\"\"\n env_name = config[\"name\"]\n (env_class, env_config) = self.prepare_class_load(config, global_config, parent_args)\n\n env_services_path = config.get(\"include_services\")\n if env_services_path is not None:\n service = self.load_services(env_services_path, global_config, service)\n\n env_tunables_path = config.get(\"include_tunables\")\n if env_tunables_path is not None:\n tunables = self._load_tunables(env_tunables_path, tunables)\n\n _LOG.debug(\"Creating env: %s :: %s\", env_name, env_class)\n env = Environment.new(env_name=env_name, class_name=env_class,\n config=env_config, global_config=global_config,\n tunables=tunables, service=service)\n\n _LOG.info(\"Created env: %s :: %s\", env_name, env)\n return env\n\n def _build_standalone_service(self, config: Dict[str, Any],\n global_config: Optional[Dict[str, Any]] = None,\n parent: Optional[Service] = None) -> Service:\n \"\"\"\n Factory method for a new service with a given config.\n\n Parameters\n ----------\n config : dict\n A dictionary with two mandatory fields:\n \"class\": FQN of a Python class to instantiate;\n \"config\": Free-format dictionary to pass to the constructor.\n global_config : dict\n Global parameters to add to the service config.\n parent: Service\n An optional reference of the parent service to mix in.\n\n Returns\n -------\n svc : Service\n An instance of the `Service` class initialized with `config`.\n \"\"\"\n (svc_class, svc_config) = self.prepare_class_load(config, global_config)\n service = Service.new(svc_class, svc_config, global_config, parent)\n _LOG.info(\"Created service: %s\", service)\n return service\n\n def _build_composite_service(self, config_list: Iterable[Dict[str, Any]],\n global_config: Optional[Dict[str, Any]] = None,\n parent: Optional[Service] = None) -> Service:\n \"\"\"\n Factory method for a new service with a given config.\n\n Parameters\n ----------\n config_list : a list of dict\n A list where each element is a dictionary with 2 mandatory fields:\n \"class\": FQN of a Python class to instantiate;\n \"config\": Free-format dictionary to pass to the constructor.\n global_config : dict\n Global parameters to add to the service config.\n parent: Service\n An optional reference of the parent service to mix in.\n\n Returns\n -------\n svc : Service\n An instance of the `Service` class that is a combination of all\n services from the list plus the parent mix-in.\n \"\"\"\n service = Service()\n if parent:\n service.register(parent.export())\n\n for config in config_list:\n service.register(self._build_standalone_service(\n config, global_config, service).export())\n\n if _LOG.isEnabledFor(logging.DEBUG):\n _LOG.debug(\"Created mix-in service:\\n%s\", \"\\n\".join(\n f' \"{key}\": {val}' for (key, val) in service.export().items()))\n\n return service\n\n def build_service(self,\n config: Dict[str, Any],\n global_config: Optional[Dict[str, Any]] = None,\n parent: Optional[Service] = None) -> Service:\n \"\"\"\n Factory method for a new service with a given config.\n\n Parameters\n ----------\n config : dict\n A dictionary with 2 mandatory fields:\n \"class\": FQN of a Python class to instantiate;\n \"config\": Free-format dictionary to pass to the constructor.\n global_config : dict\n Global parameters to add to the service config.\n parent: Service\n An optional reference of the parent service to mix in.\n\n Returns\n -------\n svc : Service\n An instance of the `Service` class that is a combination of all\n services from the list plus the parent mix-in.\n \"\"\"\n if _LOG.isEnabledFor(logging.DEBUG):\n _LOG.debug(\"Build service from config:\\n%s\",\n json.dumps(config, indent=2))\n\n assert isinstance(config, dict)\n config_list: List[Dict[str, Any]]\n if \"class\" not in config:\n # Top level config is a simple object with a list of services\n config_list = config[\"services\"]\n else:\n # Top level config is a single service\n if parent is None:\n return self._build_standalone_service(config, global_config)\n config_list = [config]\n\n return self._build_composite_service(config_list, global_config, parent)\n\n def load_environment(self, # pylint: disable=too-many-arguments\n json_file_name: str,\n tunables: TunableGroups,\n global_config: Optional[Dict[str, Any]] = None,\n parent_args: Optional[Dict[str, TunableValue]] = None,\n service: Optional[Service] = None) -> Environment:\n \"\"\"\n Load and build new environment from the config file.\n\n Parameters\n ----------\n json_file_name : str\n The environment JSON configuration file.\n tunables : TunableGroups\n A (possibly empty) collection of tunables to add to the environment.\n global_config : dict\n Global parameters to add to the environment config.\n parent_args : Dict[str, TunableValue]\n An optional reference of the parent CompositeEnv's const_args used to\n expand dynamic config parameters from.\n service : Service\n An optional reference of the parent service to mix in.\n\n Returns\n -------\n env : Environment\n A new benchmarking environment.\n \"\"\"\n config = self.load_config(json_file_name, ConfigSchema.ENVIRONMENT)\n assert isinstance(config, dict)\n return self.build_environment(config, tunables, global_config, parent_args, service)\n\n def load_environment_list(self, # pylint: disable=too-many-arguments\n json_file_name: str,\n tunables: TunableGroups,\n global_config: Optional[Dict[str, Any]] = None,\n parent_args: Optional[Dict[str, TunableValue]] = None,\n service: Optional[Service] = None) -> List[Environment]:\n \"\"\"\n Load and build a list of environments from the config file.\n\n Parameters\n ----------\n json_file_name : str\n The environment JSON configuration file.\n Can contain either one environment or a list of environments.\n tunables : TunableGroups\n An (possibly empty) collection of tunables to add to the environment.\n global_config : dict\n Global parameters to add to the environment config.\n service : Service\n An optional reference of the parent service to mix in.\n parent_args : Dict[str, TunableValue]\n An optional reference of the parent CompositeEnv's const_args used to\n expand dynamic config parameters from.\n\n Returns\n -------\n env : List[Environment]\n A list of new benchmarking environments.\n \"\"\"\n config = self.load_config(json_file_name, ConfigSchema.ENVIRONMENT)\n return [\n self.build_environment(config, tunables, global_config, parent_args, service)\n ]\n\n def load_services(self, json_file_names: Iterable[str],\n global_config: Optional[Dict[str, Any]] = None,\n parent: Optional[Service] = None) -> Service:\n \"\"\"\n Read the configuration files and bundle all service methods\n from those configs into a single Service object.\n\n Parameters\n ----------\n json_file_names : list of str\n A list of service JSON configuration files.\n global_config : dict\n Global parameters to add to the service config.\n parent : Service\n An optional reference of the parent service to mix in.\n\n Returns\n -------\n service : Service\n A collection of service methods.\n \"\"\"\n _LOG.info(\"Load services: %s parent: %s\",\n json_file_names, parent.__class__.__name__)\n service = Service({}, global_config, parent)\n for fname in json_file_names:\n config = self.load_config(fname, ConfigSchema.SERVICE)\n service.register(self.build_service(config, global_config, service).export())\n return service\n\n def _load_tunables(self, json_file_names: Iterable[str],\n parent: TunableGroups) -> TunableGroups:\n \"\"\"\n Load a collection of tunable parameters from JSON files into the parent\n TunableGroup.\n\n This helps allow standalone environment configs to reference\n overlapping tunable groups configs but still allow combining them into\n a single instance that each environment can reference.\n\n Parameters\n ----------\n json_file_names : list of str\n A list of JSON files to load.\n parent : TunableGroups\n A (possibly empty) collection of tunables to add to the new collection.\n\n Returns\n -------\n tunables : TunableGroup\n The larger collection of tunable parameters.\n \"\"\"\n _LOG.info(\"Load tunables: '%s'\", json_file_names)\n tunables = parent.copy()\n for fname in json_file_names:\n config = self.load_config(fname, ConfigSchema.TUNABLE_PARAMS)\n assert isinstance(config, dict)\n tunables.merge(TunableGroups(config))\n return tunables\n" }, { "alpha_fraction": 0.6212984323501587, "alphanum_fraction": 0.6224373579025269, "avg_line_length": 38.90909194946289, "blob_id": "c7a71126fee4c1c67f5505e30543e74ea1168e63", "content_id": "ed9b507517c08d7940c7250769d82f72d6e930f5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3512, "license_type": "permissive", "max_line_length": 110, "num_lines": 88, "path": "/mlos_bench/mlos_bench/optimizers/mock_optimizer.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nMock optimizer for mlos_bench.\n\"\"\"\n\nimport random\nimport logging\n\nfrom typing import Callable, Dict, Optional, Sequence, Tuple, Union\n\nfrom mlos_bench.environments.status import Status\nfrom mlos_bench.tunables.tunable import Tunable, TunableValue\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\n\nfrom mlos_bench.optimizers.base_optimizer import Optimizer\nfrom mlos_bench.services.base_service import Service\n\n_LOG = logging.getLogger(__name__)\n\n\nclass MockOptimizer(Optimizer):\n \"\"\"\n Mock optimizer to test the Environment API.\n \"\"\"\n\n def __init__(self,\n tunables: TunableGroups,\n config: dict,\n global_config: Optional[dict] = None,\n service: Optional[Service] = None):\n super().__init__(tunables, config, global_config, service)\n rnd = random.Random(config.get(\"seed\", 42))\n self._random: Dict[str, Callable[[Tunable], TunableValue]] = {\n \"categorical\": lambda tunable: rnd.choice(tunable.categories),\n \"float\": lambda tunable: rnd.uniform(*tunable.range),\n \"int\": lambda tunable: rnd.randint(*tunable.range),\n }\n self._best_config: Optional[TunableGroups] = None\n self._best_score: Optional[float] = None\n\n def bulk_register(self, configs: Sequence[dict], scores: Sequence[Optional[float]],\n status: Optional[Sequence[Status]] = None) -> bool:\n if not super().bulk_register(configs, scores, status):\n return False\n if status is None:\n status = [Status.SUCCEEDED] * len(configs)\n for (params, score, trial_status) in zip(configs, scores, status):\n tunables = self._tunables.copy().assign(params)\n self.register(tunables, trial_status, None if score is None else float(score))\n self._iter -= 1 # Do not advance the iteration counter during warm-up.\n if _LOG.isEnabledFor(logging.DEBUG):\n (score, _) = self.get_best_observation()\n _LOG.debug(\"Warm-up end: %s = %s\", self.target, score)\n return True\n\n def suggest(self) -> TunableGroups:\n \"\"\"\n Generate the next (random) suggestion.\n \"\"\"\n tunables = self._tunables.copy()\n if self._start_with_defaults:\n _LOG.info(\"Use default values for the first trial\")\n self._start_with_defaults = False\n else:\n for (tunable, _group) in tunables:\n tunable.value = self._random[tunable.type](tunable)\n _LOG.info(\"Iteration %d :: Suggest: %s\", self._iter, tunables)\n return tunables\n\n def register(self, tunables: TunableGroups, status: Status,\n score: Optional[Union[float, dict]] = None) -> Optional[float]:\n registered_score = super().register(tunables, status, score)\n if status.is_succeeded() and (\n self._best_score is None or (registered_score is not None and registered_score < self._best_score)\n ):\n self._best_score = registered_score\n self._best_config = tunables.copy()\n self._iter += 1\n return registered_score\n\n def get_best_observation(self) -> Union[Tuple[float, TunableGroups], Tuple[None, None]]:\n if self._best_score is None:\n return (None, None)\n assert self._best_config is not None\n return (self._best_score * self._opt_sign, self._best_config)\n" }, { "alpha_fraction": 0.6488730907440186, "alphanum_fraction": 0.6567813158035278, "avg_line_length": 33.643836975097656, "blob_id": "0176dfa648ae70bd01962bc90413d595854c833e", "content_id": "ecb29029032d61ddc75ef4794e7f3399b137b3ef", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2529, "license_type": "permissive", "max_line_length": 98, "num_lines": 73, "path": "/mlos_bench/mlos_bench/tests/storage/trial_telemetry_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nUnit tests for saving and restoring the telemetry data.\n\"\"\"\nfrom datetime import datetime, timedelta\nfrom typing import Any, List, Optional, Tuple\n\nimport pytest\n\nfrom mlos_bench.environments.status import Status\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\nfrom mlos_bench.storage.base_storage import Storage\n\n# pylint: disable=redefined-outer-name\n\n\[email protected]\ndef telemetry_data() -> List[Tuple[datetime, str, Any]]:\n \"\"\"\n Mock telemetry data for the trial.\n\n Returns\n -------\n List[Tuple[datetime, str, str]]\n A list of (timestamp, metric_id, metric_value)\n \"\"\"\n timestamp1 = datetime.utcnow()\n timestamp2 = timestamp1 + timedelta(seconds=1)\n return sorted([\n (timestamp1, \"cpu_load\", 10.1),\n (timestamp1, \"memory\", 20),\n (timestamp1, \"setup\", \"prod\"),\n (timestamp2, \"cpu_load\", 30.1),\n (timestamp2, \"memory\", 40),\n (timestamp2, \"setup\", \"prod\"),\n ])\n\n\ndef _telemetry_str(data: List[Tuple[datetime, str, Any]]\n ) -> List[Tuple[datetime, str, Optional[str]]]:\n \"\"\"\n Convert telemetry values to strings.\n \"\"\"\n return [(ts, key, None if val is None else str(val)) for (ts, key, val) in data]\n\n\ndef test_update_telemetry(exp_storage_memory_sql: Storage.Experiment,\n tunable_groups: TunableGroups,\n telemetry_data: List[Tuple[datetime, str, Any]]) -> None:\n \"\"\"\n Make sure update_telemetry() and load_telemetry() methods work.\n \"\"\"\n trial = exp_storage_memory_sql.new_trial(tunable_groups)\n assert exp_storage_memory_sql.load_telemetry(trial.trial_id) == []\n\n trial.update_telemetry(Status.RUNNING, telemetry_data)\n assert exp_storage_memory_sql.load_telemetry(trial.trial_id) == _telemetry_str(telemetry_data)\n\n\ndef test_update_telemetry_twice(exp_storage_memory_sql: Storage.Experiment,\n tunable_groups: TunableGroups,\n telemetry_data: List[Tuple[datetime, str, Any]]) -> None:\n \"\"\"\n Make sure update_telemetry() call is idempotent.\n \"\"\"\n trial = exp_storage_memory_sql.new_trial(tunable_groups)\n trial.update_telemetry(Status.RUNNING, telemetry_data)\n trial.update_telemetry(Status.RUNNING, telemetry_data)\n trial.update_telemetry(Status.RUNNING, telemetry_data)\n assert exp_storage_memory_sql.load_telemetry(trial.trial_id) == _telemetry_str(telemetry_data)\n" }, { "alpha_fraction": 0.5472174882888794, "alphanum_fraction": 0.5472174882888794, "avg_line_length": 34.8802604675293, "blob_id": "751aa6df871e269e06f74e0111090740112c1b10", "content_id": "5354cf8152c767ef295c2b3985f09b14106eedfc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11087, "license_type": "permissive", "max_line_length": 115, "num_lines": 309, "path": "/mlos_bench/mlos_bench/storage/base_storage.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nBase interface for saving and restoring the benchmark data.\n\"\"\"\n\nimport logging\nfrom abc import ABCMeta, abstractmethod\nfrom datetime import datetime\nfrom types import TracebackType\nfrom typing import Optional, Union, List, Tuple, Dict, Iterator, Type, Any\nfrom typing_extensions import Literal\n\nfrom mlos_bench.environments.status import Status\nfrom mlos_bench.services.base_service import Service\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\nfrom mlos_bench.util import get_git_info\n\n_LOG = logging.getLogger(__name__)\n\n\nclass Storage(metaclass=ABCMeta):\n # pylint: disable=too-few-public-methods,too-many-instance-attributes\n \"\"\"\n An abstract interface between the benchmarking framework\n and storage systems (e.g., SQLite or MLFLow).\n \"\"\"\n\n def __init__(self,\n tunables: TunableGroups,\n config: Dict[str, Any],\n global_config: Optional[dict] = None,\n service: Optional[Service] = None):\n \"\"\"\n Create a new storage object.\n\n Parameters\n ----------\n tunables : TunableGroups\n Tunable parameters of the environment. We need them to validate the\n configurations of merged-in experiments and restored/pending trials.\n config : dict\n Free-format key/value pairs of configuration parameters.\n \"\"\"\n _LOG.debug(\"Storage config: %s\", config)\n self._tunables = tunables.copy()\n self._service = service\n self._config = config.copy()\n self._global_config = global_config or {}\n\n @abstractmethod\n def experiment(self, *,\n experiment_id: str,\n trial_id: int,\n root_env_config: str,\n description: str,\n opt_target: str) -> 'Storage.Experiment':\n \"\"\"\n Create a new experiment in the storage.\n\n We need the `opt_target` parameter here to know what metric to retrieve\n when we load the data from previous trials. Later we will replace it with\n full metadata about the optimization direction, multiple objectives, etc.\n\n Parameters\n ----------\n experiment_id : str\n Unique identifier of the experiment.\n trial_id : int\n Starting number of the trial.\n root_env_config : str\n A path to the root JSON configuration file of the benchmarking environment.\n description : str\n Human-readable description of the experiment.\n opt_target : str\n Name of metric we're optimizing for.\n\n Returns\n -------\n experiment : Storage.Experiment\n An object that allows to update the storage with\n the results of the experiment and related data.\n \"\"\"\n\n class Experiment(metaclass=ABCMeta):\n \"\"\"\n Base interface for storing the results of the experiment.\n This class is instantiated in the `Storage.experiment()` method.\n \"\"\"\n\n def __init__(self, tunables: TunableGroups, experiment_id: str, root_env_config: str):\n self._tunables = tunables.copy()\n self._experiment_id = experiment_id\n (self._git_repo, self._git_commit, self._root_env_config) = get_git_info(root_env_config)\n\n def __enter__(self) -> 'Storage.Experiment':\n \"\"\"\n Enter the context of the experiment.\n\n Override the `_setup` method to add custom context initialization.\n \"\"\"\n _LOG.debug(\"Starting experiment: %s\", self)\n self._setup()\n return self\n\n def __exit__(self, exc_type: Optional[Type[BaseException]],\n exc_val: Optional[BaseException],\n exc_tb: Optional[TracebackType]) -> Literal[False]:\n \"\"\"\n End the context of the experiment.\n\n Override the `_teardown` method to add custom context teardown logic.\n \"\"\"\n is_ok = exc_val is None\n if is_ok:\n _LOG.debug(\"Finishing experiment: %s\", self)\n else:\n assert exc_type and exc_val\n _LOG.warning(\"Finishing experiment: %s\", self,\n exc_info=(exc_type, exc_val, exc_tb))\n self._teardown(is_ok)\n return False # Do not suppress exceptions\n\n def __repr__(self) -> str:\n return self._experiment_id\n\n def _setup(self) -> None:\n \"\"\"\n Create a record of the new experiment or find an existing one in the storage.\n\n This method is called by `Storage.Experiment.__enter__()`.\n \"\"\"\n\n def _teardown(self, is_ok: bool) -> None:\n \"\"\"\n Finalize the experiment in the storage.\n\n This method is called by `Storage.Experiment.__exit__()`.\n\n Parameters\n ----------\n is_ok : bool\n True if there were no exceptions during the experiment, False otherwise.\n \"\"\"\n\n @abstractmethod\n def merge(self, experiment_ids: List[str]) -> None:\n \"\"\"\n Merge in the results of other (compatible) experiments trials.\n Used to help warm up the optimizer for this experiment.\n\n Parameters\n ----------\n experiment_ids : List[str]\n List of IDs of the experiments to merge in.\n \"\"\"\n\n @abstractmethod\n def load_config(self, config_id: int) -> Dict[str, Any]:\n \"\"\"\n Load tunable values for a given config ID.\n \"\"\"\n\n @abstractmethod\n def load_telemetry(self, trial_id: int) -> List[Tuple[datetime, str, Any]]:\n \"\"\"\n Retrieve the telemetry data for a given trial.\n\n Parameters\n ----------\n trial_id : int\n Trial ID.\n\n Returns\n -------\n metrics : List[Tuple[datetime, str, Any]]\n Telemetry data.\n \"\"\"\n\n @abstractmethod\n def load(self, opt_target: Optional[str] = None) -> Tuple[List[dict], List[Optional[float]], List[Status]]:\n \"\"\"\n Load (tunable values, benchmark scores, status) to warm-up the optimizer.\n This call returns data from ALL merged-in experiments and attempts\n to impute the missing tunable values.\n \"\"\"\n\n @abstractmethod\n def pending_trials(self) -> Iterator['Storage.Trial']:\n \"\"\"\n Return an iterator over the pending trial runs for this experiment.\n \"\"\"\n\n @abstractmethod\n def new_trial(self, tunables: TunableGroups,\n config: Optional[Dict[str, Any]] = None) -> 'Storage.Trial':\n \"\"\"\n Create a new experiment run in the storage.\n\n Parameters\n ----------\n tunables : TunableGroups\n Tunable parameters of the experiment.\n config : dict\n Key/value pairs of additional non-tunable parameters of the trial.\n\n Returns\n -------\n trial : Storage.Trial\n An object that allows to update the storage with\n the results of the experiment trial run.\n \"\"\"\n\n class Trial(metaclass=ABCMeta):\n \"\"\"\n Base interface for storing the results of a single run of the experiment.\n This class is instantiated in the `Storage.Experiment.trial()` method.\n \"\"\"\n\n def __init__(self, *,\n tunables: TunableGroups, experiment_id: str, trial_id: int,\n config_id: int, opt_target: str, config: Optional[Dict[str, Any]] = None):\n self._tunables = tunables\n self._experiment_id = experiment_id\n self._trial_id = trial_id\n self._config_id = config_id\n self._opt_target = opt_target\n self._config = config or {}\n\n def __repr__(self) -> str:\n return f\"{self._experiment_id}:{self._trial_id}\"\n\n @property\n def trial_id(self) -> int:\n \"\"\"\n ID of the current trial.\n \"\"\"\n return self._trial_id\n\n @property\n def config_id(self) -> int:\n \"\"\"\n ID of the current trial configuration.\n \"\"\"\n return self._config_id\n\n @property\n def tunables(self) -> TunableGroups:\n \"\"\"\n Tunable parameters of the current trial.\n \"\"\"\n return self._tunables\n\n def config(self, global_config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:\n \"\"\"\n Produce a copy of the global configuration updated\n with the parameters of the current trial.\n \"\"\"\n config = self._config.copy()\n config.update(global_config or {})\n config[\"experiment_id\"] = self._experiment_id\n config[\"trial_id\"] = self._trial_id\n return config\n\n @abstractmethod\n def update(self, status: Status, timestamp: datetime,\n metrics: Optional[Union[Dict[str, float], float]] = None\n ) -> Optional[Dict[str, float]]:\n \"\"\"\n Update the storage with the results of the experiment.\n\n Parameters\n ----------\n status : Status\n Status of the experiment run.\n timestamp: datetime\n Timestamp of the status and metrics.\n metrics : Optional[Union[Dict[str, float], float]]\n One or several metrics of the experiment run.\n Must contain the optimization target if the status is SUCCEEDED.\n\n Returns\n -------\n metrics : Optional[Dict[str, float]]\n Same as `metrics`, but always in the dict format.\n \"\"\"\n _LOG.info(\"Store trial: %s :: %s %s\", self, status, metrics)\n if isinstance(metrics, dict) and self._opt_target not in metrics:\n _LOG.warning(\"Trial %s :: opt.target missing: %s\", self, self._opt_target)\n # raise ValueError(\n # f\"Optimization target '{self._opt_target}' is missing from {metrics}\")\n return {self._opt_target: metrics} if isinstance(metrics, (float, int)) else metrics\n\n @abstractmethod\n def update_telemetry(self, status: Status,\n metrics: List[Tuple[datetime, str, Any]]) -> None:\n \"\"\"\n Save the experiment's telemetry data and intermediate status.\n\n Parameters\n ----------\n status : Status\n Current status of the trial.\n metrics : List[Tuple[datetime, str, Any]]\n Telemetry data.\n \"\"\"\n _LOG.info(\"Store telemetry: %s :: %s %d records\", self, status, len(metrics))\n" }, { "alpha_fraction": 0.6315222978591919, "alphanum_fraction": 0.6438945531845093, "avg_line_length": 27.600000381469727, "blob_id": "aa0b743b5124fcc96a60a4100714061d29338fc1", "content_id": "1c22e79996e8f9e054626daf4d1dfc40123c63fd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1859, "license_type": "permissive", "max_line_length": 92, "num_lines": 65, "path": "/mlos_bench/mlos_bench/tests/optimizers/llamatune_opt_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nUnit tests for mock mlos_bench optimizer.\n\"\"\"\n\nimport pytest\n\nfrom mlos_bench.environments.status import Status\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\nfrom mlos_bench.optimizers.mlos_core_optimizer import MlosCoreOptimizer\n\nfrom mlos_bench.tests import SEED\n\n# pylint: disable=redefined-outer-name\n\n\[email protected]\ndef llamatune_opt(tunable_groups: TunableGroups) -> MlosCoreOptimizer:\n \"\"\"\n Test fixture for mlos_core SMAC optimizer.\n \"\"\"\n return MlosCoreOptimizer(\n tunables=tunable_groups,\n service=None,\n config={\n \"space_adapter_type\": \"LLAMATUNE\",\n \"space_adapter_config\": {\n \"num_low_dims\": 1,\n },\n \"optimization_target\": \"score\",\n \"max_iterations\": 10,\n \"optimizer_type\": \"SMAC\",\n \"seed\": SEED,\n # \"start_with_defaults\": False,\n })\n\n\[email protected]\ndef mock_scores() -> list:\n \"\"\"\n A list of fake benchmark scores to test the optimizers.\n \"\"\"\n return [88.88, 66.66, 99.99]\n\n\ndef test_llamatune_optimizer(llamatune_opt: MlosCoreOptimizer, mock_scores: list) -> None:\n \"\"\"\n Make sure that llamatune+smac optimizer initializes and works correctly.\n \"\"\"\n for score in mock_scores:\n assert llamatune_opt.not_converged()\n tunables = llamatune_opt.suggest()\n # FIXME: Emukit optimizer is not deterministic, so we can't check the tunables here.\n llamatune_opt.register(tunables, Status.SUCCEEDED, score)\n\n (score, _tunables) = llamatune_opt.get_best_observation()\n assert score == pytest.approx(66.66, 0.01)\n\n\nif __name__ == '__main__':\n # For attaching debugger debugging:\n pytest.main([\"-vv\", \"-n1\", \"-k\", \"test_llamatune_optimizer\", __file__])\n" }, { "alpha_fraction": 0.639072835445404, "alphanum_fraction": 0.6498344540596008, "avg_line_length": 31.648649215698242, "blob_id": "0f70282d1cf520754d37adcf5150d02a2d4480a1", "content_id": "6f8549aee7626bfae89503d4e420e8d8dabc2dbf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2416, "license_type": "permissive", "max_line_length": 91, "num_lines": 74, "path": "/mlos_bench/mlos_bench/tests/services/local/local_exec_python_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nUnit tests for LocalExecService to run Python scripts locally.\n\"\"\"\n\nfrom typing import Any, Dict\n\nimport json\n\nimport pytest\n\nfrom mlos_bench.tunables.tunable import TunableValue\nfrom mlos_bench.services.local.local_exec import LocalExecService\nfrom mlos_bench.services.config_persistence import ConfigPersistenceService\nfrom mlos_bench.util import path_join\n\n# pylint: disable=redefined-outer-name\n\n\[email protected]\ndef local_exec_service() -> LocalExecService:\n \"\"\"\n Test fixture for LocalExecService.\n \"\"\"\n return LocalExecService(parent=ConfigPersistenceService())\n\n\ndef test_run_python_script(local_exec_service: LocalExecService) -> None:\n \"\"\"\n Run a Python script using a local_exec service.\n \"\"\"\n input_file = \"./input-params.json\"\n meta_file = \"./input-params-meta.json\"\n output_file = \"./config-kernel.sh\"\n\n # Tunable parameters to save in JSON\n params: Dict[str, TunableValue] = {\n \"sched_migration_cost_ns\": 40000,\n \"sched_granularity_ns\": 800000,\n }\n\n # Tunable parameters metadata\n params_meta: Dict[str, Any] = {\n \"sched_migration_cost_ns\": {\"name_prefix\": \"/proc/sys/kernel/\"},\n \"sched_granularity_ns\": {\"name_prefix\": \"/proc/sys/kernel/\"},\n }\n\n with local_exec_service.temp_dir_context() as temp_dir:\n\n with open(path_join(temp_dir, input_file), \"wt\", encoding=\"utf-8\") as fh_input:\n json.dump(params, fh_input)\n\n with open(path_join(temp_dir, meta_file), \"wt\", encoding=\"utf-8\") as fh_meta:\n json.dump(params_meta, fh_meta)\n\n script_path = local_exec_service.config_loader_service.resolve_path(\n \"environments/os/linux/runtime/scripts/local/generate_kernel_config_script.py\")\n\n (return_code, _stdout, stderr) = local_exec_service.local_exec([\n f\"{script_path} {input_file} {meta_file} {output_file}\"\n ], cwd=temp_dir, env=params)\n\n assert stderr.strip() == \"\"\n assert return_code == 0\n # assert stdout.strip() == \"\"\n\n with open(path_join(temp_dir, output_file), \"rt\", encoding=\"utf-8\") as fh_output:\n assert [ln.strip() for ln in fh_output.readlines()] == [\n 'echo \"40000\" > /proc/sys/kernel/sched_migration_cost_ns',\n 'echo \"800000\" > /proc/sys/kernel/sched_granularity_ns',\n ]\n" }, { "alpha_fraction": 0.6538821458816528, "alphanum_fraction": 0.6566885113716125, "avg_line_length": 33.48387145996094, "blob_id": "cd5d605e87625e4ae34971d538a4ac8c5d60c9bb", "content_id": "d03e4f57713b6e74d690c3d934b613f9c41f27d9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1069, "license_type": "permissive", "max_line_length": 94, "num_lines": 31, "path": "/mlos_bench/mlos_bench/config/environments/os/linux/boot/scripts/local/generate_grub_config.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nHelper script to generate GRUB config from tunable parameters JSON.\n\nRun: `./generate_grub_config.py ./input-boot-params.json ./output-grub.cfg`\n\"\"\"\n\nimport json\nimport argparse\n\n\ndef _main(fname_input: str, fname_output: str) -> None:\n with open(fname_input, \"rt\", encoding=\"utf-8\") as fh_tunables, \\\n open(fname_output, \"wt\", encoding=\"utf-8\", newline=\"\") as fh_config:\n for (key, val) in json.load(fh_tunables).items():\n line = f'GRUB_CMDLINE_LINUX_DEFAULT=\"${{GRUB_CMDLINE_LINUX_DEFAULT}} {key}={val}\"'\n fh_config.write(line + \"\\n\")\n print(line)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"Generate GRUB config from tunable parameters JSON.\")\n parser.add_argument(\"input\", help=\"JSON file with tunable parameters.\")\n parser.add_argument(\"output\", help=\"Output shell script to configure GRUB.\")\n args = parser.parse_args()\n _main(args.input, args.output)\n" }, { "alpha_fraction": 0.8314606547355652, "alphanum_fraction": 0.8314606547355652, "avg_line_length": 28.66666603088379, "blob_id": "0d647cab1e14e880446589f9050be10e6d6882cb", "content_id": "cc19f618af1ae8e7050a72ae9a6a35c2881ac641", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 89, "license_type": "permissive", "max_line_length": 79, "num_lines": 3, "path": "/NOTICE", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "NOTICES\n\nThis repository incorporates material as listed below or described in the code.\n" }, { "alpha_fraction": 0.6303601861000061, "alphanum_fraction": 0.630789041519165, "avg_line_length": 33.29411697387695, "blob_id": "0bb02611a042e8ad8cb3a76c19961b16605d84f0", "content_id": "5dbd47d52db7935f3675b1dc1912ae9362b76ac9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2332, "license_type": "permissive", "max_line_length": 121, "num_lines": 68, "path": "/mlos_bench/mlos_bench/services/types/local_exec_type.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nProtocol interface for Service types that provide helper functions to run\nscripts and commands locally on the scheduler side.\n\"\"\"\n\nfrom typing import Iterable, Mapping, Optional, Tuple, Union, Protocol, runtime_checkable\n\nimport tempfile\nimport contextlib\n\nfrom mlos_bench.tunables.tunable import TunableValue\n\n\n@runtime_checkable\nclass SupportsLocalExec(Protocol):\n \"\"\"\n Protocol interface for a collection of methods to run scripts and commands\n in an external process on the node acting as the scheduler. Can be useful\n for data processing due to reduced dependency management complications vs\n the target environment.\n Used in LocalEnv and provided by LocalExecService.\n \"\"\"\n\n def local_exec(self, script_lines: Iterable[str],\n env: Optional[Mapping[str, TunableValue]] = None,\n cwd: Optional[str] = None,\n return_on_error: bool = False) -> Tuple[int, str, str]:\n \"\"\"\n Execute the script lines from `script_lines` in a local process.\n\n Parameters\n ----------\n script_lines : Iterable[str]\n Lines of the script to run locally.\n Treat every line as a separate command to run.\n env : Mapping[str, Union[int, float, str]]\n Environment variables (optional).\n cwd : str\n Work directory to run the script at.\n If omitted, use `temp_dir` or create a temporary dir.\n return_on_error : bool\n If True, stop running script lines on first non-zero return code.\n The default is False.\n\n Returns\n -------\n (return_code, stdout, stderr) : (int, str, str)\n A 3-tuple of return code, stdout, and stderr of the script process.\n \"\"\"\n\n def temp_dir_context(self, path: Optional[str] = None) -> Union[tempfile.TemporaryDirectory, contextlib.nullcontext]:\n \"\"\"\n Create a temp directory or use the provided path.\n\n Parameters\n ----------\n path : str\n A path to the temporary directory. Create a new one if None.\n\n Returns\n -------\n temp_dir_context : TemporaryDirectory\n Temporary directory context to use in the `with` clause.\n \"\"\"\n" }, { "alpha_fraction": 0.7160751819610596, "alphanum_fraction": 0.7160751819610596, "avg_line_length": 34.48147964477539, "blob_id": "35b9d5c8432e4d106b2ff0c187f48539a5e414de", "content_id": "ca01039e444e7cdf7a5a2e84851485d29e87a5f8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 958, "license_type": "permissive", "max_line_length": 116, "num_lines": 27, "path": "/conftest.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nProvides some pytest configuration overrides for both modules.\n\"\"\"\n\n# Note: This file is named conftest.py so that pytest picks it up automatically\n# without the need to adjust PYTHONPATH or sys.path as much.\n\nimport os\nfrom warnings import warn\n\nimport pytest\n\n\ndef pytest_configure(config: pytest.Config) -> None: # pylint: disable=unused-argument\n \"\"\"\n Add some additional (global) configuration steps for pytest.\n \"\"\"\n # Workaround some issues loading emukit in certain environments.\n if os.environ.get('DISPLAY', None):\n import matplotlib # pylint: disable=import-outside-toplevel\n matplotlib.rcParams['backend'] = 'agg'\n warn(UserWarning('DISPLAY environment variable is set, which can cause problems in some setups (e.g. WSL). '\n + f'Adjusting matplotlib backend to \"{matplotlib.rcParams[\"backend\"]}\" to compensate.'))\n" }, { "alpha_fraction": 0.758849561214447, "alphanum_fraction": 0.758849561214447, "avg_line_length": 24.11111068725586, "blob_id": "d43a103a8339351e87215fb7c4db2c245f9fd2d9", "content_id": "e8a87ab684670c8f85c2be36d064df0c97bd4c76", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 452, "license_type": "permissive", "max_line_length": 64, "num_lines": 18, "path": "/mlos_bench/mlos_bench/tests/services/remote/__init__.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTests for mlos_bench.services.remote.\nUsed to make mypy happy about multiple conftest.py modules.\n\"\"\"\n\nfrom .mock.mock_fileshare_service import MockFileShareService\nfrom .mock.mock_remote_exec_service import MockRemoteExecService\nfrom .mock.mock_vm_service import MockVMService\n\n__all__ = [\n 'MockFileShareService',\n 'MockRemoteExecService',\n 'MockVMService',\n]\n" }, { "alpha_fraction": 0.599659264087677, "alphanum_fraction": 0.6206132769584656, "avg_line_length": 32.352272033691406, "blob_id": "5b8028314f7025ed560c90d498b52f34324d8bce", "content_id": "e99677769554b6b549fd345922fbb3e7d2aafad8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5870, "license_type": "permissive", "max_line_length": 93, "num_lines": 176, "path": "/mlos_bench/mlos_bench/tests/optimizers/opt_bulk_register_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nUnit tests for mock mlos_bench optimizer.\n\"\"\"\n\nfrom typing import Optional, List\n\nimport pytest\n\nfrom mlos_bench.environments.status import Status\nfrom mlos_bench.optimizers.base_optimizer import Optimizer\nfrom mlos_bench.optimizers.mock_optimizer import MockOptimizer\nfrom mlos_bench.optimizers.mlos_core_optimizer import MlosCoreOptimizer\n\n# pylint: disable=redefined-outer-name\n\n\[email protected]\ndef mock_configs() -> List[dict]:\n \"\"\"\n Mock configurations of earlier experiments.\n \"\"\"\n return [\n {\n 'vmSize': 'Standard_B4ms',\n 'idle': 'halt',\n 'kernel_sched_migration_cost_ns': 50000,\n 'kernel_sched_latency_ns': 1000000,\n },\n {\n 'vmSize': 'Standard_B4ms',\n 'idle': 'halt',\n 'kernel_sched_migration_cost_ns': 40000,\n 'kernel_sched_latency_ns': 2000000,\n },\n {\n 'vmSize': 'Standard_B4ms',\n 'idle': 'mwait',\n 'kernel_sched_migration_cost_ns': 100000,\n 'kernel_sched_latency_ns': 3000000,\n },\n {\n 'vmSize': 'Standard_B2s',\n 'idle': 'mwait',\n 'kernel_sched_migration_cost_ns': 200000,\n 'kernel_sched_latency_ns': 4000000,\n }\n ]\n\n\[email protected]\ndef mock_configs_str(mock_configs: List[dict]) -> List[dict]:\n \"\"\"\n Same as `mock_config` above, but with all values converted to strings.\n (This can happen when we retrieve the data from storage).\n \"\"\"\n return [\n {key: str(val) for (key, val) in config.items()}\n for config in mock_configs\n ]\n\n\[email protected]\ndef mock_scores() -> List[Optional[float]]:\n \"\"\"\n Mock benchmark results from earlier experiments.\n \"\"\"\n return [None, 88.88, 66.66, 99.99]\n\n\[email protected]\ndef mock_status() -> List[Status]:\n \"\"\"\n Mock status values for earlier experiments.\n \"\"\"\n return [Status.FAILED, Status.SUCCEEDED, Status.SUCCEEDED, Status.SUCCEEDED]\n\n\ndef _test_opt_update_min(opt: Optimizer, configs: List[dict],\n scores: List[float], status: Optional[List[Status]] = None) -> None:\n \"\"\"\n Test the bulk update of the optimizer on the minimization problem.\n \"\"\"\n opt.bulk_register(configs, scores, status)\n (score, tunables) = opt.get_best_observation()\n assert score == pytest.approx(66.66, 0.01)\n assert tunables is not None\n assert tunables.get_param_values() == {\n \"vmSize\": \"Standard_B4ms\",\n \"idle\": \"mwait\",\n \"kernel_sched_migration_cost_ns\": 100000,\n 'kernel_sched_latency_ns': 3000000,\n }\n\n\ndef _test_opt_update_max(opt: Optimizer, configs: List[dict],\n scores: List[float], status: Optional[List[Status]] = None) -> None:\n \"\"\"\n Test the bulk update of the optimizer on the maximization problem.\n \"\"\"\n opt.bulk_register(configs, scores, status)\n (score, tunables) = opt.get_best_observation()\n assert score == pytest.approx(99.99, 0.01)\n assert tunables is not None\n assert tunables.get_param_values() == {\n \"vmSize\": \"Standard_B2s\",\n \"idle\": \"mwait\",\n \"kernel_sched_migration_cost_ns\": 200000,\n 'kernel_sched_latency_ns': 4000000,\n }\n\n\ndef test_update_mock_min(mock_opt: MockOptimizer, mock_configs: List[dict],\n mock_scores: List[float], mock_status: List[Status]) -> None:\n \"\"\"\n Test the bulk update of the mock optimizer on the minimization problem.\n \"\"\"\n _test_opt_update_min(mock_opt, mock_configs, mock_scores, mock_status)\n # make sure the first suggestion after bulk load is *NOT* the default config:\n assert mock_opt.suggest().get_param_values() == {\n \"vmSize\": \"Standard_B4ms\",\n \"idle\": \"halt\",\n \"kernel_sched_migration_cost_ns\": 13111,\n 'kernel_sched_latency_ns': 796233790,\n }\n\n\ndef test_update_mock_min_str(mock_opt: MockOptimizer, mock_configs_str: List[dict],\n mock_scores: List[float], mock_status: List[Status]) -> None:\n \"\"\"\n Test the bulk update of the mock optimizer with all-strings data.\n \"\"\"\n _test_opt_update_min(mock_opt, mock_configs_str, mock_scores, mock_status)\n\n\ndef test_update_mock_max(mock_opt_max: MockOptimizer, mock_configs: List[dict],\n mock_scores: List[float], mock_status: List[Status]) -> None:\n \"\"\"\n Test the bulk update of the mock optimizer on the maximization problem.\n \"\"\"\n _test_opt_update_max(mock_opt_max, mock_configs, mock_scores, mock_status)\n\n\ndef test_update_flaml(flaml_opt: MlosCoreOptimizer, mock_configs: List[dict],\n mock_scores: List[float], mock_status: List[Status]) -> None:\n \"\"\"\n Test the bulk update of the FLAML optimizer.\n \"\"\"\n _test_opt_update_min(flaml_opt, mock_configs, mock_scores, mock_status)\n\n\ndef test_update_flaml_max(flaml_opt_max: MlosCoreOptimizer, mock_configs: List[dict],\n mock_scores: List[float], mock_status: List[Status]) -> None:\n \"\"\"\n Test the bulk update of the FLAML optimizer.\n \"\"\"\n _test_opt_update_max(flaml_opt_max, mock_configs, mock_scores, mock_status)\n\n\ndef test_update_smac(smac_opt: MlosCoreOptimizer, mock_configs: List[dict],\n mock_scores: List[float], mock_status: List[Status]) -> None:\n \"\"\"\n Test the bulk update of the SMAC optimizer.\n \"\"\"\n _test_opt_update_min(smac_opt, mock_configs, mock_scores, mock_status)\n\n\ndef test_update_smac_max(smac_opt_max: MlosCoreOptimizer, mock_configs: List[dict],\n mock_scores: List[float], mock_status: List[Status]) -> None:\n \"\"\"\n Test the bulk update of the SMAC optimizer.\n \"\"\"\n _test_opt_update_max(smac_opt_max, mock_configs, mock_scores, mock_status)\n" }, { "alpha_fraction": 0.6788321137428284, "alphanum_fraction": 0.6916058659553528, "avg_line_length": 31.235294342041016, "blob_id": "3f7852b6160178a35339d39d996a09ae454922ec", "content_id": "b34f84158caa0d865e905857804b2d9d6d0f025d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 548, "license_type": "permissive", "max_line_length": 126, "num_lines": 17, "path": "/scripts/update-version.sh", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#!/bin/bash\n##\n## Copyright (c) Microsoft Corporation.\n## Licensed under the MIT License.\n##\n\n# This script is used to update the git tags, version numbers, etc. in a number of files.\n# See Also: .bumpversion.cfg (which gets rewritten by the tool, and strips comments, so we keep a separate config file for it)\n\nset -eu\n\nscriptdir=$(dirname \"$(readlink -f \"$0\")\")\ncd \"$scriptdir/..\"\n\nset -x\n# Example usage: \"./update-version.sh --dry-run patch\" to bump v0.0.4 -> v0.0.5, for instance.\nconda run -n ${CONDA_ENV_NAME:-mlos} bumpversion --verbose $*\n" }, { "alpha_fraction": 0.5488584637641907, "alphanum_fraction": 0.5634703040122986, "avg_line_length": 26.721519470214844, "blob_id": "10ad26a29cddd648ab280c290cd18b2fbdfcf415", "content_id": "8910ee6fbf5ca7d317fe308426c188bb7425f03f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2190, "license_type": "permissive", "max_line_length": 89, "num_lines": 79, "path": "/mlos_bench/mlos_bench/tests/environments/local/local_env_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nUnit tests for LocalEnv benchmark environment.\n\"\"\"\nimport pytest\n\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\nfrom mlos_bench.tests.environments.local import create_local_env, check_local_env_success\n\n\ndef test_local_env(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Produce benchmark and telemetry data in a local script and read it.\n \"\"\"\n local_env = create_local_env(tunable_groups, {\n \"run\": [\n \"echo 'metric,value' > output.csv\",\n \"echo 'latency,10' >> output.csv\",\n \"echo 'throughput,66' >> output.csv\",\n \"echo 'score,0.9' >> output.csv\",\n ],\n \"read_results_file\": \"output.csv\",\n })\n\n check_local_env_success(\n local_env, tunable_groups,\n expected_results={\n \"latency\": 10.0,\n \"throughput\": 66.0,\n \"score\": 0.9,\n },\n expected_telemetry=[],\n )\n\n\ndef test_local_env_results_no_header(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Fail if the results are not in the expected format.\n \"\"\"\n local_env = create_local_env(tunable_groups, {\n \"run\": [\n # No header\n \"echo 'latency,10' > output.csv\",\n \"echo 'throughput,66' >> output.csv\",\n \"echo 'score,0.9' >> output.csv\",\n ],\n \"read_results_file\": \"output.csv\",\n })\n\n with local_env as env_context:\n assert env_context.setup(tunable_groups)\n with pytest.raises(ValueError):\n env_context.run()\n\n\ndef test_local_env_wide(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Produce benchmark data in wide format and read it.\n \"\"\"\n local_env = create_local_env(tunable_groups, {\n \"run\": [\n \"echo 'latency,throughput,score' > output.csv\",\n \"echo '10,66,0.9' >> output.csv\",\n ],\n \"read_results_file\": \"output.csv\",\n })\n\n check_local_env_success(\n local_env, tunable_groups,\n expected_results={\n \"latency\": 10,\n \"throughput\": 66,\n \"score\": 0.9,\n },\n expected_telemetry=[],\n )\n" }, { "alpha_fraction": 0.7415730357170105, "alphanum_fraction": 0.7415730357170105, "avg_line_length": 21.25, "blob_id": "e937c992b7b81c5ade130b8d3e0ea46ce08a3e7c", "content_id": "509ecbd842b0f0ec31123c8c1efbca8bd784fd78", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 178, "license_type": "permissive", "max_line_length": 59, "num_lines": 8, "path": "/mlos_bench/mlos_bench/tests/optimizers/__init__.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTests for mlos_bench.optimizers.\nUsed to make mypy happy about multiple conftest.py modules.\n\"\"\"\n" }, { "alpha_fraction": 0.6108470559120178, "alphanum_fraction": 0.6108470559120178, "avg_line_length": 34.77000045776367, "blob_id": "c49ba905bee6a8c2ae35116ad821df29d836270c", "content_id": "3d2d0dcd5b8ef7bcd9bb563574715083b2f1fa5b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3577, "license_type": "permissive", "max_line_length": 115, "num_lines": 100, "path": "/mlos_bench/mlos_bench/environments/remote/vm_env.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\n\"Remote\" VM Environment.\n\"\"\"\n\nfrom typing import Optional\n\nimport logging\n\nfrom mlos_bench.environments.base_environment import Environment\nfrom mlos_bench.services.base_service import Service\nfrom mlos_bench.services.types.vm_provisioner_type import SupportsVMOps\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\n\n_LOG = logging.getLogger(__name__)\n\n\nclass VMEnv(Environment):\n \"\"\"\n \"Remote\" VM environment.\n \"\"\"\n\n def __init__(self,\n *,\n name: str,\n config: dict,\n global_config: Optional[dict] = None,\n tunables: Optional[TunableGroups] = None,\n service: Optional[Service] = None):\n \"\"\"\n Create a new environment for VM operations.\n\n Parameters\n ----------\n name: str\n Human-readable name of the environment.\n config : dict\n Free-format dictionary that contains the benchmark environment\n configuration. Each config must have at least the \"tunable_params\"\n and the \"const_args\" sections.\n global_config : dict\n Free-format dictionary of global parameters (e.g., security credentials)\n to be mixed in into the \"const_args\" section of the local config.\n tunables : TunableGroups\n A collection of tunable parameters for *all* environments.\n service: Service\n An optional service object (e.g., providing methods to\n deploy or reboot a VM, etc.).\n \"\"\"\n super().__init__(name=name, config=config, global_config=global_config, tunables=tunables, service=service)\n\n assert self._service is not None and isinstance(self._service, SupportsVMOps), \\\n \"VMEnv requires a service that supports VM operations\"\n self._vm_service: SupportsVMOps = self._service\n\n def setup(self, tunables: TunableGroups, global_config: Optional[dict] = None) -> bool:\n \"\"\"\n Check if VM is ready. (Re)provision and start it, if necessary.\n\n Parameters\n ----------\n tunables : TunableGroups\n A collection of groups of tunable parameters along with the\n parameters' values. VMEnv tunables are variable parameters that,\n together with the VMEnv configuration, are sufficient to provision\n and start a VM.\n global_config : dict\n Free-format dictionary of global parameters of the environment\n that are not used in the optimization process.\n\n Returns\n -------\n is_success : bool\n True if operation is successful, false otherwise.\n \"\"\"\n _LOG.info(\"VM set up: %s :: %s\", self, tunables)\n if not super().setup(tunables, global_config):\n return False\n\n (status, params) = self._vm_service.vm_provision(self._params)\n if status.is_pending():\n (status, _) = self._vm_service.wait_vm_deployment(True, params)\n\n self._is_ready = status.is_succeeded()\n return self._is_ready\n\n def teardown(self) -> None:\n \"\"\"\n Shut down the VM and release it.\n \"\"\"\n _LOG.info(\"VM tear down: %s\", self)\n (status, params) = self._vm_service.vm_deprovision(self._params)\n if status.is_pending():\n (status, _) = self._vm_service.wait_vm_deployment(False, params)\n\n super().teardown()\n _LOG.debug(\"Final status of VM deprovisioning: %s :: %s\", self, status)\n" }, { "alpha_fraction": 0.6954545378684998, "alphanum_fraction": 0.6954545378684998, "avg_line_length": 15.923076629638672, "blob_id": "6eeeb79d6a106b89ec8456e8e885463caa0f2022", "content_id": "305b3d94a0375d4a6e7d697fc8cab7d377a5b971", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 220, "license_type": "permissive", "max_line_length": 51, "num_lines": 13, "path": "/mlos_bench/mlos_bench/storage/__init__.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nInterfaces to the storage backends for OS Autotune.\n\"\"\"\n\nfrom mlos_bench.storage.base_storage import Storage\n\n__all__ = [\n 'Storage',\n]\n" }, { "alpha_fraction": 0.7612612843513489, "alphanum_fraction": 0.7702702879905701, "avg_line_length": 36, "blob_id": "661778c616052f000eeaefb6e8e1bf2902853810", "content_id": "2cfb621c112fe9ecc5c2903c1e04789904a4c833", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 222, "license_type": "permissive", "max_line_length": 78, "num_lines": 6, "path": "/doc/Dockerfile", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "FROM nginx:latest\nRUN apt-get update && apt-get install -y --no-install-recommends linklint curl\n# Our nginx config overrides the default listening port.\nARG NGINX_PORT=81\nENV NGINX_PORT=${NGINX_PORT}\nEXPOSE ${NGINX_PORT}\n" }, { "alpha_fraction": 0.6410256624221802, "alphanum_fraction": 0.6419098377227783, "avg_line_length": 30.41666603088379, "blob_id": "892763d07736c9a2b12dc912e06f5b71ed10680a", "content_id": "e39963fe7b461b309965ee930789fc38d7077c42", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1131, "license_type": "permissive", "max_line_length": 79, "num_lines": 36, "path": "/.devcontainer/scripts/run-devcontainer.sh", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#!/bin/bash\n##\n## Copyright (c) Microsoft Corporation.\n## Licensed under the MIT License.\n##\n\n# Quick hacky script to start a devcontainer in a non-vscode shell for testing.\n# See Also:\n# - ../build/build-devcontainer\n# - \"devcontainer open\" subcommand from <https://github.com/devcontainers/cli>\n\nset -eu\n\n# Move to repo root.\nscriptdir=$(dirname \"$(readlink -f \"$0\")\")\nrepo_root=$(readlink -f \"$scriptdir/../..\")\nrepo_name=$(basename \"$repo_root\")\ncd \"$repo_root\"\n\ncontainer_name=\"$repo_name.$(stat -c%i \"$repo_root/\")\"\n\nmkdir -p \"/tmp/$container_name/dc/shellhistory\"\ndocker run -it --rm \\\n --name \"$container_name\" \\\n --user vscode \\\n -v \"$HOME/.azure\":/dc/azure \\\n -v \"/tmp/$container_name/dc/shellhistory:/dc/shellhistory\" \\\n -v /var/run/docker.sock:/var/run/docker.sock \\\n -v \"$PWD\":\"/workspaces/$repo_name\" \\\n --workdir \"/workspaces/$repo_name\" \\\n --env CONTAINER_WORKSPACE_FOLDER=\"/workspaces/$repo_name\" \\\n --env LOCAL_WORKSPACE_FOLDER=\"$repo_root\" \\\n --env http_proxy=\"${http_proxy:-}\" \\\n --env https_proxy=\"${https_proxy:-}\" \\\n --env no_proxy=\"${no_proxy:-}\" \\\n mlos-devcontainer\n" }, { "alpha_fraction": 0.7209302186965942, "alphanum_fraction": 0.7275747656822205, "avg_line_length": 33.46564865112305, "blob_id": "ce22c8b5ec82284957384a72af4c03b1a3c74155", "content_id": "3b7085f5ff9d88c33764499685bcc0f1cc7c4b8e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4515, "license_type": "permissive", "max_line_length": 88, "num_lines": 131, "path": "/mlos_bench/mlos_bench/tests/tunables/tunable_to_configspace_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nUnit tests for Tunable to ConfigSpace conversion.\n\"\"\"\n\nimport pytest\n\nfrom ConfigSpace import UniformIntegerHyperparameter\nfrom ConfigSpace import UniformFloatHyperparameter\nfrom ConfigSpace import CategoricalHyperparameter\nfrom ConfigSpace import ConfigurationSpace\n\nfrom mlos_bench.tunables.tunable import Tunable\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\n\nfrom mlos_bench.optimizers.convert_configspace import _tunable_to_hyperparameter\nfrom mlos_bench.optimizers.convert_configspace import tunable_groups_to_configspace\n\n# pylint: disable=redefined-outer-name\n\n\[email protected]\ndef configuration_space() -> ConfigurationSpace:\n \"\"\"\n A test fixture that produces a mock ConfigurationSpace object\n matching the tunable_groups fixture.\n\n Returns\n -------\n configuration_space : ConfigurationSpace\n A new ConfigurationSpace object for testing.\n \"\"\"\n spaces = ConfigurationSpace(space={\n \"vmSize\": [\"Standard_B2s\", \"Standard_B2ms\", \"Standard_B4ms\"],\n \"idle\": [\"halt\", \"mwait\", \"noidle\"],\n \"kernel_sched_migration_cost_ns\": (-1, 500000),\n \"kernel_sched_latency_ns\": (0, 1000000000),\n })\n\n spaces[\"vmSize\"].default_value = \"Standard_B4ms\"\n spaces[\"idle\"].default_value = \"halt\"\n spaces[\"kernel_sched_migration_cost_ns\"].default_value = -1\n spaces[\"kernel_sched_latency_ns\"].default_value = 2000000\n\n return spaces\n\n\ndef _cmp_tunable_hyperparameter_categorical(\n tunable: Tunable, cs_param: CategoricalHyperparameter) -> None:\n \"\"\"\n Check if categorical Tunable and ConfigSpace Hyperparameter actually match.\n \"\"\"\n assert isinstance(cs_param, CategoricalHyperparameter)\n assert set(cs_param.choices) == set(tunable.categories)\n assert cs_param.default_value == tunable.value\n\n\ndef _cmp_tunable_hyperparameter_int(\n tunable: Tunable, cs_param: UniformIntegerHyperparameter) -> None:\n \"\"\"\n Check if integer Tunable and ConfigSpace Hyperparameter actually match.\n \"\"\"\n assert isinstance(cs_param, UniformIntegerHyperparameter)\n assert (cs_param.lower, cs_param.upper) == tuple(tunable.range)\n assert cs_param.default_value == tunable.value\n\n\ndef _cmp_tunable_hyperparameter_float(\n tunable: Tunable, cs_param: UniformFloatHyperparameter) -> None:\n \"\"\"\n Check if float Tunable and ConfigSpace Hyperparameter actually match.\n \"\"\"\n assert isinstance(cs_param, UniformFloatHyperparameter)\n assert (cs_param.lower, cs_param.upper) == tuple(tunable.range)\n assert cs_param.default_value == tunable.value\n\n\ndef test_tunable_to_hyperparameter_categorical(tunable_categorical: Tunable) -> None:\n \"\"\"\n Check the conversion of Tunable to CategoricalHyperparameter.\n \"\"\"\n cs_param = _tunable_to_hyperparameter(tunable_categorical)\n _cmp_tunable_hyperparameter_categorical(tunable_categorical, cs_param)\n\n\ndef test_tunable_to_hyperparameter_int(tunable_int: Tunable) -> None:\n \"\"\"\n Check the conversion of Tunable to UniformIntegerHyperparameter.\n \"\"\"\n cs_param = _tunable_to_hyperparameter(tunable_int)\n _cmp_tunable_hyperparameter_int(tunable_int, cs_param)\n\n\ndef test_tunable_to_hyperparameter_float(tunable_float: Tunable) -> None:\n \"\"\"\n Check the conversion of Tunable to UniformFloatHyperparameter.\n \"\"\"\n cs_param = _tunable_to_hyperparameter(tunable_float)\n _cmp_tunable_hyperparameter_float(tunable_float, cs_param)\n\n\n_CMP_FUNC = {\n \"int\": _cmp_tunable_hyperparameter_int,\n \"float\": _cmp_tunable_hyperparameter_float,\n \"categorical\": _cmp_tunable_hyperparameter_categorical\n}\n\n\ndef test_tunable_groups_to_hyperparameters(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Check the conversion of TunableGroups to ConfigurationSpace.\n Make sure that the corresponding Tunable and Hyperparameter objects match.\n \"\"\"\n space = tunable_groups_to_configspace(tunable_groups)\n for (tunable, _group) in tunable_groups:\n cs_param = space[tunable.name]\n assert cs_param.default_value == tunable.value\n _CMP_FUNC[tunable.type](tunable, cs_param)\n\n\ndef test_tunable_groups_to_configspace(\n tunable_groups: TunableGroups, configuration_space: ConfigurationSpace) -> None:\n \"\"\"\n Check the conversion of the entire TunableGroups collection\n to a single ConfigurationSpace object.\n \"\"\"\n space = tunable_groups_to_configspace(tunable_groups)\n assert space == configuration_space\n" }, { "alpha_fraction": 0.5864092111587524, "alphanum_fraction": 0.5898313522338867, "avg_line_length": 25.3935489654541, "blob_id": "c519f4c23a91f88fca9fff242929d245ba36b7e6", "content_id": "b8388c939b7b36c975de85a5f9f57d2e86e74a7f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4091, "license_type": "permissive", "max_line_length": 79, "num_lines": 155, "path": "/mlos_bench/mlos_bench/tests/optimizers/conftest.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTest fixtures for mlos_bench optimizers.\n\"\"\"\n\nimport pytest\n\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\nfrom mlos_bench.optimizers.mock_optimizer import MockOptimizer\nfrom mlos_bench.optimizers.mlos_core_optimizer import MlosCoreOptimizer\n\nfrom mlos_bench.tests import SEED\n\n\[email protected]\ndef mock_opt_no_defaults(tunable_groups: TunableGroups) -> MockOptimizer:\n \"\"\"\n Test fixture for MockOptimizer that ignores the initial configuration.\n \"\"\"\n return MockOptimizer(\n tunables=tunable_groups,\n service=None,\n config={\n \"optimization_target\": \"score\",\n \"optimization_direction\": \"min\",\n \"max_iterations\": 5,\n \"start_with_defaults\": False,\n \"seed\": SEED\n },\n )\n\n\[email protected]\ndef mock_opt(tunable_groups: TunableGroups) -> MockOptimizer:\n \"\"\"\n Test fixture for MockOptimizer.\n \"\"\"\n return MockOptimizer(\n tunables=tunable_groups,\n service=None,\n config={\n \"optimization_target\": \"score\",\n \"optimization_direction\": \"min\",\n \"max_iterations\": 5,\n \"seed\": SEED\n },\n )\n\n\[email protected]\ndef mock_opt_max(tunable_groups: TunableGroups) -> MockOptimizer:\n \"\"\"\n Test fixture for MockOptimizer.\n \"\"\"\n return MockOptimizer(\n tunables=tunable_groups,\n service=None,\n config={\n \"optimization_target\": \"score\",\n \"optimization_direction\": \"max\",\n \"max_iterations\": 10,\n \"seed\": SEED\n },\n )\n\n\[email protected]\ndef flaml_opt(tunable_groups: TunableGroups) -> MlosCoreOptimizer:\n \"\"\"\n Test fixture for mlos_core FLAML optimizer.\n \"\"\"\n return MlosCoreOptimizer(\n tunables=tunable_groups,\n service=None,\n config={\n \"optimization_target\": \"score\",\n \"optimization_direction\": \"min\",\n \"max_iterations\": 15,\n \"optimizer_type\": \"FLAML\",\n \"seed\": SEED,\n },\n )\n\n\[email protected]\ndef flaml_opt_max(tunable_groups: TunableGroups) -> MlosCoreOptimizer:\n \"\"\"\n Test fixture for mlos_core FLAML optimizer.\n \"\"\"\n return MlosCoreOptimizer(\n tunables=tunable_groups,\n service=None,\n config={\n \"optimization_target\": \"score\",\n \"optimization_direction\": \"max\",\n \"max_iterations\": 15,\n \"optimizer_type\": \"FLAML\",\n \"seed\": SEED,\n },\n )\n\n# FIXME: SMAC's RF model can be non-deterministic at low iterations, which are\n# normally calculated as a percentage of the max_iterations and number of\n# tunable dimensions, so for now we set the initial random samples equal to the\n# number of iterations and control them with a seed.\n\n\nSMAC_ITERATIONS = 10\n\n\[email protected]\ndef smac_opt(tunable_groups: TunableGroups) -> MlosCoreOptimizer:\n \"\"\"\n Test fixture for mlos_core SMAC optimizer.\n \"\"\"\n return MlosCoreOptimizer(\n tunables=tunable_groups,\n service=None,\n config={\n \"optimization_target\": \"score\",\n \"optimization_direction\": \"min\",\n \"max_iterations\": SMAC_ITERATIONS,\n \"optimizer_type\": \"SMAC\",\n \"seed\": SEED,\n \"output_directory\": None,\n # See Above\n \"n_random_init\": SMAC_ITERATIONS,\n \"max_ratio\": 1.0,\n },\n )\n\n\[email protected]\ndef smac_opt_max(tunable_groups: TunableGroups) -> MlosCoreOptimizer:\n \"\"\"\n Test fixture for mlos_core SMAC optimizer.\n \"\"\"\n return MlosCoreOptimizer(\n tunables=tunable_groups,\n service=None,\n config={\n \"optimization_target\": \"score\",\n \"optimization_direction\": \"max\",\n \"max_iterations\": SMAC_ITERATIONS,\n \"optimizer_type\": \"SMAC\",\n \"seed\": SEED,\n \"output_directory\": None,\n # See Above\n \"n_random_init\": SMAC_ITERATIONS,\n \"max_ratio\": 1.0,\n },\n )\n" }, { "alpha_fraction": 0.6953125, "alphanum_fraction": 0.6968148946762085, "avg_line_length": 31.95049476623535, "blob_id": "9c30944df8d62ec21ec88a5e2dab04d85fe9b6cb", "content_id": "03bb2c307272d37399d35eaf97ae02acfe0109e2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3328, "license_type": "permissive", "max_line_length": 109, "num_lines": 101, "path": "/mlos_bench/mlos_bench/optimizers/convert_configspace.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nFunctions to convert TunableGroups to ConfigSpace for use with the mlos_core optimizers.\n\"\"\"\n\nimport logging\n\nfrom typing import Optional\n\nfrom ConfigSpace.hyperparameters import Hyperparameter\nfrom ConfigSpace import UniformIntegerHyperparameter\nfrom ConfigSpace import UniformFloatHyperparameter\nfrom ConfigSpace import CategoricalHyperparameter\nfrom ConfigSpace import ConfigurationSpace, Configuration\n\nfrom mlos_bench.tunables.tunable import Tunable\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\n\n_LOG = logging.getLogger(__name__)\n\n\ndef _tunable_to_hyperparameter(\n tunable: Tunable, group_name: Optional[str] = None, cost: int = 0) -> Hyperparameter:\n \"\"\"\n Convert a single Tunable to an equivalent ConfigSpace Hyperparameter object.\n\n Parameters\n ----------\n tunable : Tunable\n An mlos_bench Tunable object.\n group_name : str\n Human-readable id of the CovariantTunableGroup this Tunable belongs to.\n cost : int\n Cost to change this parameter (comes from the corresponding CovariantTunableGroup).\n\n Returns\n -------\n hyperparameter : Hyperparameter\n A ConfigSpace Hyperparameter object that corresponds to the Tunable.\n \"\"\"\n meta = {\"group\": group_name, \"cost\": cost} # {\"lower\": \"\", \"upper\": \"\", \"scaling\": \"\"}\n if tunable.type == \"categorical\":\n return CategoricalHyperparameter(\n tunable.name, choices=tunable.categories,\n default_value=tunable.default, meta=meta)\n elif tunable.type == \"int\":\n return UniformIntegerHyperparameter(\n tunable.name, lower=tunable.range[0], upper=tunable.range[1],\n default_value=tunable.default, meta=meta)\n elif tunable.type == \"float\":\n return UniformFloatHyperparameter(\n tunable.name, lower=tunable.range[0], upper=tunable.range[1],\n default_value=tunable.default, meta=meta)\n else:\n raise TypeError(f\"Undefined Parameter Type: {tunable.type}\")\n\n\ndef tunable_groups_to_configspace(tunables: TunableGroups, seed: Optional[int] = None) -> ConfigurationSpace:\n \"\"\"\n Convert TunableGroups to hyperparameters in ConfigurationSpace.\n\n Parameters\n ----------\n tunables : TunableGroups\n A collection of tunable parameters.\n\n seed : Optional[int]\n Random seed to use.\n\n Returns\n -------\n configspace : ConfigurationSpace\n A new ConfigurationSpace instance that corresponds to the input TunableGroups.\n \"\"\"\n space = ConfigurationSpace(seed=seed)\n space.add_hyperparameters([\n _tunable_to_hyperparameter(tunable, group.name, group.get_current_cost())\n for (tunable, group) in tunables\n ])\n return space\n\n\ndef tunable_values_to_configuration(tunables: TunableGroups) -> Configuration:\n \"\"\"\n Converts a TunableGroups current values to a ConfigSpace Configuration.\n\n Parameters\n ----------\n tunables : TunableGroups\n The TunableGroups to take the current value from.\n\n Returns\n -------\n Configuration\n A ConfigSpace Configuration.\n \"\"\"\n configspace = tunable_groups_to_configspace(tunables)\n return Configuration(configspace, values={tunable.name: tunable.value for (tunable, _group) in tunables})\n" }, { "alpha_fraction": 0.7283702492713928, "alphanum_fraction": 0.7283702492713928, "avg_line_length": 30.723403930664062, "blob_id": "853fdbb9b2c76aefb6f3c242c9e801943d17450a", "content_id": "fcf0d5b9e58fb4ef317e1444e2e810f0b9f97647", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1491, "license_type": "permissive", "max_line_length": 87, "num_lines": 47, "path": "/mlos_bench/mlos_bench/tests/tunables/tunable_accessors_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nUnit tests for accessing values to the individual parameters within tunable groups.\n\"\"\"\n\nimport pytest\n\nfrom mlos_bench.tunables.covariant_group import CovariantTunableGroup\nfrom mlos_bench.tunables.tunable import Tunable\n\n\ndef test_categorical_access_to_numerical_tunable(tunable_int: Tunable) -> None:\n \"\"\"\n Make sure we throw an error on accessing a numerical tunable as a categorical.\n \"\"\"\n with pytest.raises(ValueError):\n print(tunable_int.category)\n with pytest.raises(AssertionError):\n print(tunable_int.categories)\n\n\ndef test_numerical_access_to_categorical_tunable(tunable_categorical: Tunable) -> None:\n \"\"\"\n Make sure we throw an error on accessing a numerical tunable as a categorical.\n \"\"\"\n with pytest.raises(ValueError):\n print(tunable_categorical.numerical_value)\n with pytest.raises(AssertionError):\n print(tunable_categorical.range)\n\n\ndef test_covariant_group_repr(covariant_group: CovariantTunableGroup) -> None:\n \"\"\"\n Tests that the covariant group representation works as expected.\n \"\"\"\n assert repr(covariant_group).startswith(f\"{covariant_group.name}:\")\n\n\ndef test_covariant_group_tunables(covariant_group: CovariantTunableGroup) -> None:\n \"\"\"\n Tests that we can access the tunables in the covariant group.\n \"\"\"\n for tunable in covariant_group.get_tunables():\n assert isinstance(tunable, Tunable)\n" }, { "alpha_fraction": 0.6293548941612244, "alphanum_fraction": 0.6300172209739685, "avg_line_length": 29.31726837158203, "blob_id": "f6590b096cad52d4bc401b98efd30da757defdf4", "content_id": "42a3d86761052d5554f8c852a33467f3b27e69f4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7549, "license_type": "permissive", "max_line_length": 101, "num_lines": 249, "path": "/mlos_bench/mlos_bench/util.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nVarious helper functions for mlos_bench.\n\"\"\"\n\n# NOTE: This has to be placed in the top-level mlos_bench package to avoid circular imports.\n\nimport os\nimport json\nimport logging\nimport importlib\nimport subprocess\nfrom typing import Any, Dict, Iterable, Mapping, Optional, Tuple, Type, TypeVar, TYPE_CHECKING, Union\n\n_LOG = logging.getLogger(__name__)\n\nif TYPE_CHECKING:\n from mlos_bench.environments.base_environment import Environment\n from mlos_bench.optimizers.base_optimizer import Optimizer\n from mlos_bench.services.base_service import Service\n from mlos_bench.storage.base_storage import Storage\n\n# BaseTypeVar is a generic with a constraint of the three base classes.\nBaseTypeVar = TypeVar(\"BaseTypeVar\", \"Environment\", \"Optimizer\", \"Service\", \"Storage\")\nBaseTypes = Union[\"Environment\", \"Optimizer\", \"Service\", \"Storage\"]\n\n\ndef preprocess_dynamic_configs(*, dest: dict, source: Optional[dict] = None) -> dict:\n \"\"\"\n Replaces all $name values in the destination config with the corresponding\n value from the source config.\n\n Parameters\n ----------\n dest : dict\n Destination config.\n source : Optional[dict]\n Source config.\n\n Returns\n -------\n dest : dict\n A reference to the destination config after the preprocessing.\n \"\"\"\n if source is None:\n source = {}\n for key, val in dest.items():\n if isinstance(val, str) and val.startswith(\"$\") and val[1:] in source:\n dest[key] = source[val[1:]]\n return dest\n\n\ndef merge_parameters(*, dest: dict, source: Optional[dict] = None,\n required_keys: Optional[Iterable[str]] = None) -> dict:\n \"\"\"\n Merge the source config dict into the destination config.\n Pick from the source configs *ONLY* the keys that are already present\n in the destination config.\n\n Parameters\n ----------\n dest : dict\n Destination config.\n source : Optional[dict]\n Source config.\n required_keys : Optional[Iterable[str]]\n An optional list of keys that must be present in the destination config.\n\n Returns\n -------\n dest : dict\n A reference to the destination config after the merge.\n \"\"\"\n if source is None:\n source = {}\n\n for key in set(dest).intersection(source):\n dest[key] = source[key]\n\n for key in required_keys or []:\n if key in dest:\n continue\n if key in source:\n dest[key] = source[key]\n else:\n raise ValueError(\"Missing required parameter: \" + key)\n\n return dest\n\n\ndef path_join(*args: str, abs_path: bool = False) -> str:\n \"\"\"\n Joins the path components and normalizes the path.\n\n Parameters\n ----------\n args : str\n Path components.\n\n abs_path : bool\n If True, the path is converted to be absolute.\n\n Returns\n -------\n str\n Joined path.\n \"\"\"\n path = os.path.join(*args)\n if abs_path:\n path = os.path.abspath(path)\n return os.path.normpath(path).replace(\"\\\\\", \"/\")\n\n\ndef prepare_class_load(config: dict,\n global_config: Optional[Dict[str, Any]] = None) -> Tuple[str, Dict[str, Any]]:\n \"\"\"\n Extract the class instantiation parameters from the configuration.\n\n Parameters\n ----------\n config : dict\n Configuration of the optimizer.\n global_config : dict\n Global configuration parameters (optional).\n\n Returns\n -------\n (class_name, class_config) : (str, dict)\n Name of the class to instantiate and its configuration.\n \"\"\"\n class_name = config[\"class\"]\n class_config = config.setdefault(\"config\", {})\n\n merge_parameters(dest=class_config, source=global_config)\n\n if _LOG.isEnabledFor(logging.DEBUG):\n _LOG.debug(\"Instantiating: %s with config:\\n%s\",\n class_name, json.dumps(class_config, indent=2))\n\n return (class_name, class_config)\n\n\ndef get_class_from_name(class_name: str) -> type:\n \"\"\"\n Gets the class from the fully qualified name.\n\n Parameters\n ----------\n class_name : str\n Fully qualified class name.\n\n Returns\n -------\n type\n Class object.\n \"\"\"\n # We need to import mlos_bench to make the factory methods work.\n class_name_split = class_name.split(\".\")\n module_name = \".\".join(class_name_split[:-1])\n class_id = class_name_split[-1]\n\n module = importlib.import_module(module_name)\n cls = getattr(module, class_id)\n assert isinstance(cls, type)\n return cls\n\n\n# FIXME: Technically, this should return a type \"class_name\" derived from \"base_class\".\ndef instantiate_from_config(base_class: Type[BaseTypeVar], class_name: str,\n *args: Any, **kwargs: Any) -> BaseTypeVar:\n \"\"\"\n Factory method for a new class instantiated from config.\n\n Parameters\n ----------\n base_class : type\n Base type of the class to instantiate.\n Currently it's one of {Environment, Service, Optimizer}.\n class_name : str\n FQN of a Python class to instantiate, e.g.,\n \"mlos_bench.environments.remote.VMEnv\".\n Must be derived from the `base_class`.\n args : list\n Positional arguments to pass to the constructor.\n kwargs : dict\n Keyword arguments to pass to the constructor.\n\n Returns\n -------\n inst : Union[Environment, Service, Optimizer, Storage]\n An instance of the `class_name` class.\n \"\"\"\n impl = get_class_from_name(class_name)\n _LOG.info(\"Instantiating: %s :: %s\", class_name, impl)\n\n assert issubclass(impl, base_class)\n ret: BaseTypeVar = impl(*args, **kwargs)\n assert isinstance(ret, base_class)\n return ret\n\n\ndef check_required_params(config: Mapping[str, Any], required_params: Iterable[str]) -> None:\n \"\"\"\n Check if all required parameters are present in the configuration.\n Raise ValueError if any of the parameters are missing.\n\n Parameters\n ----------\n config : dict\n Free-format dictionary with the configuration\n of the service or benchmarking environment.\n required_params : Iterable[str]\n A collection of identifiers of the parameters that must be present\n in the configuration.\n \"\"\"\n missing_params = set(required_params).difference(config)\n if missing_params:\n raise ValueError(\n \"The following parameters must be provided in the configuration\"\n + f\" or as command line arguments: {missing_params}\")\n\n\ndef get_git_info(path: str = __file__) -> Tuple[str, str, str]:\n \"\"\"\n Get the git repository, commit hash, and local path of the given file.\n\n Parameters\n ----------\n path : str\n Path to the file in git repository.\n\n Returns\n -------\n (git_repo, git_commit, git_path) : Tuple[str, str, str]\n Git repository URL, last commit hash, and relative file path.\n \"\"\"\n dirname = os.path.dirname(path)\n git_repo = subprocess.check_output(\n [\"git\", \"-C\", dirname, \"remote\", \"get-url\", \"origin\"], text=True).strip()\n git_commit = subprocess.check_output(\n [\"git\", \"-C\", dirname, \"rev-parse\", \"HEAD\"], text=True).strip()\n git_root = subprocess.check_output(\n [\"git\", \"-C\", dirname, \"rev-parse\", \"--show-toplevel\"], text=True).strip()\n _LOG.debug(\"Current git branch: %s %s\", git_repo, git_commit)\n rel_path = os.path.relpath(os.path.abspath(path), os.path.abspath(git_root))\n return (git_repo, git_commit, rel_path.replace(\"\\\\\", \"/\"))\n" }, { "alpha_fraction": 0.6284467577934265, "alphanum_fraction": 0.6382198929786682, "avg_line_length": 31.191011428833008, "blob_id": "d742b3bd257ef6ac74a408932b6bc14e8cd3b0f6", "content_id": "b9604ee4bbe8a1094b1061eabf04b83e31e60ba5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5730, "license_type": "permissive", "max_line_length": 124, "num_lines": 178, "path": "/mlos_bench/mlos_bench/tests/services/remote/azure/azure_services_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTests for mlos_bench.services.remote.azure.azure_services\n\"\"\"\n\nfrom unittest.mock import MagicMock, patch\n\nimport pytest\n\nfrom mlos_bench.environments.status import Status\n\nfrom mlos_bench.services.remote.azure.azure_services import AzureVMService\n\n# pylint: disable=missing-function-docstring\n# pylint: disable=too-many-arguments\n\n\[email protected](\n (\"operation_name\", \"accepts_params\"), [\n (\"vm_start\", True),\n (\"vm_stop\", True),\n (\"vm_deprovision\", True),\n (\"vm_restart\", True),\n ])\[email protected](\n (\"http_status_code\", \"operation_status\"), [\n (200, Status.SUCCEEDED),\n (202, Status.PENDING),\n (401, Status.FAILED),\n (404, Status.FAILED),\n ])\n@patch(\"mlos_bench.services.remote.azure.azure_services.requests\")\ndef test_vm_operation_status(mock_requests: MagicMock, azure_vm_service: AzureVMService, operation_name: str,\n accepts_params: bool, http_status_code: int, operation_status: Status) -> None:\n\n mock_response = MagicMock()\n mock_response.status_code = http_status_code\n mock_requests.post.return_value = mock_response\n\n operation = getattr(azure_vm_service, operation_name)\n if accepts_params:\n status, _ = operation({\"vmName\": \"test-vm\"})\n else:\n status, _ = operation()\n\n assert status == operation_status\n\n\n@patch(\"mlos_bench.services.remote.azure.azure_services.time.sleep\")\n@patch(\"mlos_bench.services.remote.azure.azure_services.requests\")\ndef test_wait_vm_operation_ready(mock_requests: MagicMock, mock_sleep: MagicMock, azure_vm_service: AzureVMService) -> None:\n\n # Mock response header\n async_url = \"DUMMY_ASYNC_URL\"\n retry_after = 12345\n params = {\n \"asyncResultsUrl\": async_url,\n \"vmName\": \"test-vm\",\n \"pollInterval\": retry_after,\n }\n\n mock_status_response = MagicMock(status_code=200)\n mock_status_response.json.return_value = {\n \"status\": \"Succeeded\",\n }\n mock_requests.get.return_value = mock_status_response\n\n status, _ = azure_vm_service.wait_vm_operation(params)\n\n assert (async_url, ) == mock_requests.get.call_args[0]\n assert (retry_after, ) == mock_sleep.call_args[0]\n assert status.is_succeeded()\n\n\n@patch(\"mlos_bench.services.remote.azure.azure_services.requests\")\ndef test_wait_vm_operation_timeout(mock_requests: MagicMock, azure_vm_service: AzureVMService) -> None:\n\n # Mock response header\n params = {\n \"asyncResultsUrl\": \"DUMMY_ASYNC_URL\",\n \"vmName\": \"test-vm\",\n \"pollInterval\": 1\n }\n\n mock_status_response = MagicMock(status_code=200)\n mock_status_response.json.return_value = {\n \"status\": \"InProgress\",\n }\n mock_requests.get.return_value = mock_status_response\n\n (status, _) = azure_vm_service.wait_vm_operation(params)\n assert status == Status.TIMED_OUT\n\n\[email protected](\n (\"http_status_code\", \"operation_status\"), [\n (200, Status.SUCCEEDED),\n (202, Status.PENDING),\n (401, Status.FAILED),\n (404, Status.FAILED),\n ])\n@patch(\"mlos_bench.services.remote.azure.azure_services.requests\")\ndef test_remote_exec_status(mock_requests: MagicMock, azure_vm_service: AzureVMService,\n http_status_code: int, operation_status: Status) -> None:\n script = [\"command_1\", \"command_2\"]\n\n mock_response = MagicMock()\n mock_response.status_code = http_status_code\n mock_requests.post.return_value = mock_response\n\n status, _ = azure_vm_service.remote_exec(script, config={}, env_params={})\n\n assert status == operation_status\n\n\n@patch(\"mlos_bench.services.remote.azure.azure_services.requests\")\ndef test_remote_exec_headers_output(mock_requests: MagicMock, azure_vm_service: AzureVMService) -> None:\n\n async_url_key = \"asyncResultsUrl\"\n async_url_value = \"DUMMY_ASYNC_URL\"\n script = [\"command_1\", \"command_2\"]\n\n mock_response = MagicMock()\n mock_response.status_code = 202\n mock_response.headers = {\n \"Azure-AsyncOperation\": async_url_value\n }\n mock_requests.post.return_value = mock_response\n\n _, cmd_output = azure_vm_service.remote_exec(script, config={}, env_params={\n \"param_1\": 123,\n \"param_2\": \"abc\",\n })\n\n assert async_url_key in cmd_output\n assert cmd_output[async_url_key] == async_url_value\n\n assert mock_requests.post.call_args[1][\"json\"] == {\n \"commandId\": \"RunShellScript\",\n \"script\": script,\n \"parameters\": [\n {\"name\": \"param_1\", \"value\": 123},\n {\"name\": \"param_2\", \"value\": \"abc\"}\n ]\n }\n\n\[email protected](\n (\"operation_status\", \"wait_output\", \"results_output\"), [\n (Status.SUCCEEDED, {\n \"properties\": {\n \"output\": [\n {\"message\": \"DUMMY_STDOUT_STDERR\"},\n ]\n }\n }, [\n {\"message\": \"DUMMY_STDOUT_STDERR\"},\n ]),\n (Status.PENDING, {}, {}),\n (Status.FAILED, {}, {}),\n ])\ndef test_get_remote_exec_results(azure_vm_service: AzureVMService, operation_status: Status,\n wait_output: dict, results_output: dict) -> None:\n\n params = {\"asyncResultsUrl\": \"DUMMY_ASYNC_URL\"}\n\n mock_wait_vm_operation = MagicMock()\n mock_wait_vm_operation.return_value = (operation_status, wait_output)\n # azure_vm_service.wait_vm_operation = mock_wait_vm_operation\n setattr(azure_vm_service, \"wait_vm_operation\", mock_wait_vm_operation)\n\n status, cmd_output = azure_vm_service.get_remote_exec_results(params)\n\n assert status == operation_status\n assert cmd_output == results_output\n" }, { "alpha_fraction": 0.7091633677482605, "alphanum_fraction": 0.711155354976654, "avg_line_length": 20.826086044311523, "blob_id": "9933e100467bc8d2e2554024e165739da59bff0c", "content_id": "fa5542eb5d63e177114f104130d722d46411eda5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 502, "license_type": "permissive", "max_line_length": 65, "num_lines": 23, "path": "/mlos_bench/mlos_bench/config/environments/os/linux/boot/scripts/remote/cleanup-os-boot-time.sh", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#!/bin/bash\n##\n## Copyright (c) Microsoft Corporation.\n## Licensed under the MIT License.\n##\n\n# Script to restore boot-time parameters of VM to original state.\n# This script should be run in the VM.\n\nset -eu\n\nscriptdir=$(dirname \"$(readlink -f \"$0\")\")\ncd \"$scriptdir\"\nsource ./common-boot-time.sh\n\n# remove our addins file and regenerate the config file\nrm -f \"$ORIG_BOOT_TIME\"\nupdate-grub\n\n# check if the real config file has changed\nif diff -u /boot/grub/grub.cfg \"$ORIG_BOOT_TIME\"; then\n reboot\nfi\n" }, { "alpha_fraction": 0.6055756211280823, "alphanum_fraction": 0.6133195757865906, "avg_line_length": 33.18235397338867, "blob_id": "721982d3c2b28653cf4ef4e3c92045ae822849c2", "content_id": "b637cf8f8199dc208df7a6a7fb504e5ab5010926", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5811, "license_type": "permissive", "max_line_length": 121, "num_lines": 170, "path": "/mlos_bench/mlos_bench/tests/services/local/local_exec_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nUnit tests for the service to run the scripts locally.\n\"\"\"\nimport sys\n\nimport pytest\nimport pandas\n\nfrom mlos_bench.services.local.local_exec import LocalExecService, split_cmdline\nfrom mlos_bench.services.config_persistence import ConfigPersistenceService\nfrom mlos_bench.util import path_join\n\n# pylint: disable=redefined-outer-name\n# -- Ignore pylint complaints about pytest references to\n# `local_exec_service` fixture as both a function and a parameter.\n\n\ndef test_split_cmdline() -> None:\n \"\"\"\n Test splitting a commandline into subcommands.\n \"\"\"\n cmdline = \". env.sh && (echo hello && echo world | tee > /tmp/test || echo foo && echo $var; true)\"\n assert list(split_cmdline(cmdline)) == [\n ['.', 'env.sh'],\n ['&&'],\n ['('],\n ['echo', 'hello'],\n ['&&'],\n ['echo', 'world'],\n ['|'],\n ['tee'],\n ['>'],\n ['/tmp/test'],\n ['||'],\n ['echo', 'foo'],\n ['&&'],\n ['echo', '$var'],\n [';'],\n ['true'],\n [')'],\n ]\n\n\[email protected]\ndef local_exec_service() -> LocalExecService:\n \"\"\"\n Test fixture for LocalExecService.\n \"\"\"\n return LocalExecService(parent=ConfigPersistenceService())\n\n\ndef test_resolve_script(local_exec_service: LocalExecService) -> None:\n \"\"\"\n Test local script resolution logic with complex subcommand names.\n \"\"\"\n script = \"os/linux/runtime/scripts/local/generate_kernel_config_script.py\"\n script_abspath = local_exec_service.config_loader_service.resolve_path(script)\n orig_cmdline = f\". env.sh && {script}\"\n expected_cmdline = f\". env.sh && {script_abspath}\"\n subcmds_tokens = split_cmdline(orig_cmdline)\n # pylint: disable=protected-access\n subcmds_tokens = [local_exec_service._resolve_cmdline_script_path(subcmd_tokens) for subcmd_tokens in subcmds_tokens]\n cmdline_tokens = [token for subcmd_tokens in subcmds_tokens for token in subcmd_tokens]\n expanded_cmdline = \" \".join(cmdline_tokens)\n assert expanded_cmdline == expected_cmdline\n\n\ndef test_run_script(local_exec_service: LocalExecService) -> None:\n \"\"\"\n Run a script locally and check the results.\n \"\"\"\n # `echo` should work on all platforms\n (return_code, stdout, stderr) = local_exec_service.local_exec([\"echo hello\"])\n assert return_code == 0\n assert stdout.strip() == \"hello\"\n assert stderr.strip() == \"\"\n\n\ndef test_run_script_multiline(local_exec_service: LocalExecService) -> None:\n \"\"\"\n Run a multiline script locally and check the results.\n \"\"\"\n # `echo` should work on all platforms\n (return_code, stdout, stderr) = local_exec_service.local_exec([\n \"echo hello\",\n \"echo world\"\n ])\n assert return_code == 0\n assert stdout.strip().split() == [\"hello\", \"world\"]\n assert stderr.strip() == \"\"\n\n\ndef test_run_script_multiline_env(local_exec_service: LocalExecService) -> None:\n \"\"\"\n Run a multiline script locally and pass the environment variables to it.\n \"\"\"\n # `echo` should work on all platforms\n (return_code, stdout, stderr) = local_exec_service.local_exec([\n r\"echo $var\", # Unix shell\n r\"echo %var%\" # Windows cmd\n ], env={\"var\": \"VALUE\", \"int_var\": 10})\n assert return_code == 0\n if sys.platform == 'win32':\n assert stdout.strip().split() == [\"$var\", \"VALUE\"]\n else:\n assert stdout.strip().split() == [\"VALUE\", \"%var%\"]\n assert stderr.strip() == \"\"\n\n\ndef test_run_script_read_csv(local_exec_service: LocalExecService) -> None:\n \"\"\"\n Run a script locally and read the resulting CSV file.\n \"\"\"\n with local_exec_service.temp_dir_context() as temp_dir:\n\n (return_code, stdout, stderr) = local_exec_service.local_exec([\n \"echo 'col1,col2'> output.csv\", # No space before '>' to make it work on Windows\n \"echo '111,222' >> output.csv\",\n \"echo '333,444' >> output.csv\",\n ], cwd=temp_dir)\n\n assert return_code == 0\n assert stdout.strip() == \"\"\n assert stderr.strip() == \"\"\n\n data = pandas.read_csv(path_join(temp_dir, \"output.csv\"))\n if sys.platform == 'win32':\n # Workaround for Python's subprocess module on Windows adding a\n # space inbetween the col1,col2 arg and the redirect symbol which\n # cmd poorly interprets as being part of the original string arg.\n # Without this, we get \"col2 \" as the second column name.\n data.rename(str.rstrip, axis='columns', inplace=True)\n assert all(data.col1 == [111, 333])\n assert all(data.col2 == [222, 444])\n\n\ndef test_run_script_write_read_txt(local_exec_service: LocalExecService) -> None:\n \"\"\"\n Write data a temp location and run a script that updates it there.\n \"\"\"\n with local_exec_service.temp_dir_context() as temp_dir:\n\n input_file = \"input.txt\"\n with open(path_join(temp_dir, input_file), \"wt\", encoding=\"utf-8\") as fh_input:\n fh_input.write(\"hello\\n\")\n\n (return_code, stdout, stderr) = local_exec_service.local_exec([\n f\"echo 'world' >> {input_file}\",\n f\"echo 'test' >> {input_file}\",\n ], cwd=temp_dir)\n\n assert return_code == 0\n assert stdout.strip() == \"\"\n assert stderr.strip() == \"\"\n\n with open(path_join(temp_dir, input_file), \"rt\", encoding=\"utf-8\") as fh_input:\n assert fh_input.read().split() == [\"hello\", \"world\", \"test\"]\n\n\ndef test_run_script_fail(local_exec_service: LocalExecService) -> None:\n \"\"\"\n Try to run a non-existent command.\n \"\"\"\n (return_code, stdout, _stderr) = local_exec_service.local_exec([\"foo_bar_baz hello\"])\n assert return_code != 0\n assert stdout.strip() == \"\"\n" }, { "alpha_fraction": 0.7701149582862854, "alphanum_fraction": 0.7701149582862854, "avg_line_length": 26.473684310913086, "blob_id": "416c51d1be8db7179622b44cbf88ae808261367e", "content_id": "f8759172514dd1fbb406bd32bb0e0792aa253438", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 522, "license_type": "permissive", "max_line_length": 71, "num_lines": 19, "path": "/mlos_bench/mlos_bench/optimizers/__init__.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nInterfaces and wrapper classes for optimizers to be used in Autotune.\n\"\"\"\n\nfrom mlos_bench.optimizers.base_optimizer import Optimizer\nfrom mlos_bench.optimizers.mock_optimizer import MockOptimizer\nfrom mlos_bench.optimizers.one_shot_optimizer import OneShotOptimizer\nfrom mlos_bench.optimizers.mlos_core_optimizer import MlosCoreOptimizer\n\n__all__ = [\n 'Optimizer',\n 'MockOptimizer',\n 'OneShotOptimizer',\n 'MlosCoreOptimizer',\n]\n" }, { "alpha_fraction": 0.6917904019355774, "alphanum_fraction": 0.6917904019355774, "avg_line_length": 40.5, "blob_id": "99c3ef40b043c347541660ffcee65cdefc7e5c57", "content_id": "67fdcbdfbd6233dc251537f5a801fd5b2998ef4f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3569, "license_type": "permissive", "max_line_length": 109, "num_lines": 86, "path": "/mlos_bench/mlos_bench/tests/config/schemas/services/test_services_schemas.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTests for service schema validation.\n\"\"\"\n\nfrom os import path\nfrom typing import Any, Dict, List\n\nimport pytest\n\nfrom mlos_core.tests import get_all_concrete_subclasses\n\nfrom mlos_bench.config.schemas import ConfigSchema\nfrom mlos_bench.services.base_service import Service\nfrom mlos_bench.services.config_persistence import ConfigPersistenceService\nfrom mlos_bench.services.local.temp_dir_context import TempDirContextService\n\nfrom mlos_bench.tests import try_resolve_class_name\nfrom mlos_bench.tests.config.schemas import (get_schema_test_cases,\n check_test_case_against_schema,\n check_test_case_config_with_extra_param)\n\n\n# General testing strategy:\n# - hand code a set of good/bad configs (useful to test editor schema checking)\n# - enumerate and try to check that we've covered all the cases\n# - for each config, load and validate against expected schema\n\nTEST_CASES = get_schema_test_cases(path.join(path.dirname(__file__), \"test-cases\"))\n\n\n# Dynamically enumerate some of the cases we want to make sure we cover.\n\nNON_CONFIG_SERVICE_CLASSES = {\n ConfigPersistenceService, # configured thru the launcher cli args\n TempDirContextService, # ABCMeta abstract class, but no good way to test that dynamically in Python.\n}\n\nexpected_service_class_names = [subclass.__module__ + \".\" + subclass.__name__\n for subclass\n in get_all_concrete_subclasses(Service, pkg_name='mlos_bench')\n if subclass not in NON_CONFIG_SERVICE_CLASSES]\nassert expected_service_class_names\n\n\n# Do the full cross product of all the test cases and all the Service types.\[email protected](\"test_case_subtype\", sorted(TEST_CASES.by_subtype))\[email protected](\"service_class\", expected_service_class_names)\ndef test_case_coverage_mlos_bench_service_type(test_case_subtype: str, service_class: str) -> None:\n \"\"\"\n Checks to see if there is a given type of test case for the given mlos_bench Service type.\n \"\"\"\n for test_case in TEST_CASES.by_subtype[test_case_subtype].values():\n config_list: List[Dict[str, Any]]\n if not isinstance(test_case.config, dict):\n continue # type: ignore[unreachable]\n if \"class\" not in test_case.config:\n config_list = test_case.config[\"services\"]\n else:\n config_list = [test_case.config]\n for config in config_list:\n if try_resolve_class_name(config.get(\"class\")) == service_class:\n return\n raise NotImplementedError(\n f\"Missing test case for subtype {test_case_subtype} for service class {service_class}\")\n\n\n# Now we actually perform all of those validation tests.\n\[email protected](\"test_case_name\", sorted(TEST_CASES.by_path))\ndef test_service_configs_against_schema(test_case_name: str) -> None:\n \"\"\"\n Checks that the service config validates against the schema.\n \"\"\"\n check_test_case_against_schema(TEST_CASES.by_path[test_case_name], ConfigSchema.SERVICE)\n\n\[email protected](\"test_case_name\", sorted(TEST_CASES.by_type[\"good\"]))\ndef test_service_configs_with_extra_param(test_case_name: str) -> None:\n \"\"\"\n Checks that the service config fails to validate if extra params are present in certain places.\n \"\"\"\n check_test_case_config_with_extra_param(TEST_CASES.by_type[\"good\"][test_case_name], ConfigSchema.SERVICE)\n" }, { "alpha_fraction": 0.5996718406677246, "alphanum_fraction": 0.5996718406677246, "avg_line_length": 22.44230842590332, "blob_id": "98e5df5ba2e606d6d7122fb8979ea6f191a7126c", "content_id": "67f9e63e48b3d8d18108500b9c62378ef4532014", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1219, "license_type": "permissive", "max_line_length": 81, "num_lines": 52, "path": "/mlos_bench/mlos_bench/tests/environments/base_env_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nUnit tests for base environment class functionality.\n\"\"\"\n\nimport pytest\n\nfrom mlos_bench.environments.base_environment import Environment\n\n_GROUPS = {\n \"group\": [\"a\", \"b\"],\n \"list\": [\"c\", \"d\"],\n \"str\": \"efg\",\n \"empty\": [],\n \"other\": [\"h\", \"i\", \"j\"],\n}\n\n# pylint: disable=protected-access\n\n\ndef test_expand_groups() -> None:\n \"\"\"\n Check the dollar variable expansion for tunable groups.\n \"\"\"\n assert Environment._expand_groups(\n [\"begin\", \"$list\", \"$empty\", \"$str\", \"end\"],\n _GROUPS) == [\"begin\", \"c\", \"d\", \"efg\", \"end\"]\n\n\ndef test_expand_groups_empty_input() -> None:\n \"\"\"\n Make sure an empty group stays empty.\n \"\"\"\n assert Environment._expand_groups([], _GROUPS) == []\n\n\ndef test_expand_groups_empty_list() -> None:\n \"\"\"\n Make sure an empty group expansion works properly.\n \"\"\"\n assert not Environment._expand_groups([\"$empty\"], _GROUPS)\n\n\ndef test_expand_groups_unknown() -> None:\n \"\"\"\n Make sure we fail on unknown $GROUP names expansion.\n \"\"\"\n with pytest.raises(KeyError):\n Environment._expand_groups([\"$list\", \"$UNKNOWN\", \"$str\", \"end\"], _GROUPS)\n" }, { "alpha_fraction": 0.6568047404289246, "alphanum_fraction": 0.6612426042556763, "avg_line_length": 31.190475463867188, "blob_id": "e4e1da594773192f533eacddccfe629361bcee3c", "content_id": "41bd1624599592bfc3378de35071b771c48739da", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 676, "license_type": "permissive", "max_line_length": 73, "num_lines": 21, "path": "/mlos_bench/mlos_bench/config/environments/os/linux/boot/scripts/local/create_new_grub_cfg.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nPython script to parse through JSON and create new config file.\n\nThis script will be run in the SCHEDULER.\nNEW_CFG will need to be copied over to the VM (/etc/default/grub.d).\n\"\"\"\nimport json\n\nJSON_CONFIG_FILE = \"config-boot-time.json\"\nNEW_CFG = \"zz-mlos-boot-params.cfg\"\n\nwith open(JSON_CONFIG_FILE, 'r', encoding='UTF-8') as fh_json, \\\n open(NEW_CFG, 'w', encoding='UTF-8') as fh_config:\n for key, val in json.load(fh_json).items():\n fh_config.write('GRUB_CMDLINE_LINUX_DEFAULT=\"$'\n f'{{GRUB_CMDLINE_LINUX_DEFAULT}} {key}={val}\"\\n')\n" }, { "alpha_fraction": 0.4392678737640381, "alphanum_fraction": 0.4608984887599945, "avg_line_length": 30.086206436157227, "blob_id": "c80e06d31a4733bd30dda14952176c4272b444bc", "content_id": "3482532629c017f4f26700e6a8974d3c6210759f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1803, "license_type": "permissive", "max_line_length": 91, "num_lines": 58, "path": "/mlos_bench/mlos_bench/tests/tunables/tunables_str_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nUnit tests to make sure we always produce a string representation\nof a TunableGroup in canonical form.\n\"\"\"\n\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\n\n\ndef test_tunable_groups_str(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Check that we produce the same string representation of TunableGroups,\n regardless of the order in which we declare the covariant groups and\n tunables within each covariant group.\n \"\"\"\n # Same as `tunable_groups` (defined in the `conftest.py` file), but in different order:\n tunables_other = TunableGroups({\n \"kernel\": {\n \"cost\": 1,\n \"params\": {\n \"kernel_sched_latency_ns\": {\n \"type\": \"int\",\n \"default\": 2000000,\n \"range\": [0, 1000000000]\n },\n \"kernel_sched_migration_cost_ns\": {\n \"type\": \"int\",\n \"default\": -1,\n \"range\": [-1, 500000],\n \"special\": [-1]\n }\n }\n },\n \"boot\": {\n \"cost\": 300,\n \"params\": {\n \"idle\": {\n \"type\": \"categorical\",\n \"default\": \"halt\",\n \"values\": [\"halt\", \"mwait\", \"noidle\"]\n }\n }\n },\n \"provision\": {\n \"cost\": 1000,\n \"params\": {\n \"vmSize\": {\n \"type\": \"categorical\",\n \"default\": \"Standard_B4ms\",\n \"values\": [\"Standard_B2s\", \"Standard_B2ms\", \"Standard_B4ms\"]\n }\n }\n },\n })\n assert str(tunable_groups) == str(tunables_other)\n" }, { "alpha_fraction": 0.6421673893928528, "alphanum_fraction": 0.6421673893928528, "avg_line_length": 34.846153259277344, "blob_id": "3618efe1f305bfb555f60a7f7dea0f69462bcf23", "content_id": "32cef77f25d7a949bf1b76e5cbd4e1f50bd11c74", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1864, "license_type": "permissive", "max_line_length": 254, "num_lines": 52, "path": "/mlos_bench/mlos_bench/tests/config/schemas/README.md", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "# Config Schema Tests\n\nThis directory contains tests for the config schemas.\n\n## Goals\n\nThe intention is to provide test cases for\n\n- good examples, both minimal and complete\n- bad examples (things that should be rejected by the schema)\n- catch places where we have not defined a schema for a new class\n\n## Layout\n\nTo accomplish this, each config schema type has it's own directory containing the following directory layout:\n\n```txt\ntest_{config_type}_schemas.py\ntest-cases/\n good/\n partial/\n test-case-a.jsonc\n ...\n full/\n test-case-b.jsonc\n ...\n bad/\n invalid/\n test-case-c.jsonc\n ...\n unhandled/\n test-case-d.jsonc\n ...\n```\n\nEach test case is a jsonc file that contains a single config object.\n\n## Test Code\n\nEach `test_{config_type}_schemas.py` file contains a short bit of code that enumerates the test cases in the `test-cases` directory and runs them through the schema validator and checks that the result is as expected according to the directory structure.\n\nSince there is much boilerplate in that logic repeated across config type, most of that code actually lives in [`__init__.py`](./__init__.py) in this directory.\n\n### Coverage Checks\n\nThere are additionally basic tests to ensure that there appear to be reasonable test coverage for each class implemented in `mlos_bench` and `mlos_core` so that when we add new features they are handled by the schema.\n\n> NOTE: This is by no means a complete check - only a best effort attempt to remind us to take a look at schema test coverage when we add new features.\n\n## See Also\n\n- [config/schemas/README.md](../../../config/schemas/README.md)\n" }, { "alpha_fraction": 0.6391887068748474, "alphanum_fraction": 0.6421607136726379, "avg_line_length": 51.40163803100586, "blob_id": "1898c48d7f71e57f8d1b573ac8a4cc01071d26e2", "content_id": "f4e6b1a3fd1e88702ff5a4b8fa3912572f5c6f17", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19179, "license_type": "permissive", "max_line_length": 132, "num_lines": 366, "path": "/mlos_core/mlos_core/spaces/adapters/llamatune.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nImplementation of LlamaTune space adapter.\n\"\"\"\nfrom typing import Dict, Optional\nfrom warnings import warn\n\nimport ConfigSpace\nimport numpy as np\nimport numpy.typing as npt\nimport pandas as pd\nfrom sklearn.preprocessing import MinMaxScaler\nfrom mlos_core.spaces.adapters.adapter import BaseSpaceAdapter\n\n\nclass LlamaTuneAdapter(BaseSpaceAdapter): # pylint: disable=too-many-instance-attributes\n \"\"\"\n Implementation of LlamaTune, a set of parameter space transformation techniques,\n aimed at improving the sample-efficiency of the underlying optimizer.\n \"\"\"\n\n DEFAULT_NUM_LOW_DIMS = 16\n \"\"\"Default number of dimensions in the low-dimensional search space, generated by HeSBO projection\"\"\"\n\n DEFAULT_SPECIAL_PARAM_VALUE_BIASING_PERCENTAGE = .2\n \"\"\"Default percentage of bias for each special parameter value\"\"\"\n\n DEFAULT_MAX_UNIQUE_VALUES_PER_PARAM = 10000\n \"\"\"Default number of (max) unique values of each parameter, when space discretization is used\"\"\"\n\n def __init__(self, *,\n orig_parameter_space: ConfigSpace.ConfigurationSpace,\n num_low_dims: int = DEFAULT_NUM_LOW_DIMS,\n special_param_values: Optional[dict] = None,\n max_unique_values_per_param: Optional[int] = DEFAULT_MAX_UNIQUE_VALUES_PER_PARAM,\n use_approximate_reverse_mapping: bool = False):\n \"\"\"\n Create a space adapter that employs LlamaTune's techniques.\n\n Parameters\n ----------\n orig_parameter_space : ConfigSpace.ConfigurationSpace\n The original (user-provided) parameter space to optimize.\n num_low_dims: int\n Number of dimensions used in the low-dimensional parameter search space.\n special_param_values_dict: Optional[dict]\n Dictionary of special\n max_unique_values_per_param: Optional[int]:\n Number of unique values per parameter. Used to discretize the parameter space.\n If `None` space discretization is disabled.\n \"\"\"\n super().__init__(orig_parameter_space=orig_parameter_space)\n\n if num_low_dims >= len(orig_parameter_space):\n raise ValueError(\"Number of target config space dimensions should be less than those of original config space.\")\n\n # Validate input special param values dict\n special_param_values = special_param_values or {}\n self._validate_special_param_values(special_param_values)\n\n # Create low-dimensional parameter search space\n self._construct_low_dim_space(num_low_dims, max_unique_values_per_param)\n\n # Initialize config values scaler: from (-1, 1) to (0, 1) range\n config_scaler = MinMaxScaler(feature_range=(0, 1))\n ones_vector = np.ones(len(list(self.orig_parameter_space.values())))\n config_scaler.fit([-ones_vector, ones_vector])\n self._config_scaler = config_scaler\n\n # Generate random mapping from low-dimensional space to original config space\n num_orig_dims = len(list(self.orig_parameter_space.values()))\n self._h_matrix = self._random_state.choice(range(num_low_dims), num_orig_dims)\n self._sigma_vector = self._random_state.choice([-1, 1], num_orig_dims)\n\n # Used to retrieve the low-dim point, given the high-dim one\n self._suggested_configs: Dict[ConfigSpace.Configuration, ConfigSpace.Configuration] = {}\n self._pinv_matrix: npt.NDArray\n self._use_approximate_reverse_mapping = use_approximate_reverse_mapping\n\n @property\n def target_parameter_space(self) -> ConfigSpace.ConfigurationSpace:\n \"\"\"Get the parameter space, which is explored by the underlying optimizer.\"\"\"\n return self._target_config_space\n\n def inverse_transform(self, configurations: pd.DataFrame) -> pd.DataFrame:\n target_configurations = []\n for (_, config) in configurations.iterrows():\n configuration = ConfigSpace.Configuration(self.orig_parameter_space, values=config.to_dict())\n\n target_config = self._suggested_configs.get(configuration, None)\n # NOTE: HeSBO is a non-linear projection method, and does not inherently support inverse projection\n # To (partly) support this operation, we keep track of the suggested low-dim point(s) along with the\n # respective high-dim point; this way we can retrieve the low-dim point, from its high-dim counterpart.\n if target_config is None:\n # Inherently it is not supported to register points, which were not suggested by the optimizer.\n if configuration == self.orig_parameter_space.get_default_configuration():\n # Default configuration should always be registerable.\n pass\n elif not self._use_approximate_reverse_mapping:\n raise ValueError(f\"{repr(configuration)}\\n\" \"The above configuration was not suggested by the optimizer. \"\n \"Approximate reverse mapping is currently disabled; thus *only* configurations suggested \"\n \"previously by the optimizer can be registered.\")\n\n # ...yet, we try to support that by implementing an approximate reverse mapping using pseudo-inverse matrix.\n if getattr(self, '_pinv_matrix', None) is None:\n self._try_generate_approx_inverse_mapping()\n\n # Perform approximate reverse mapping\n # NOTE: applying special value biasing is not possible\n vector = self._config_scaler.inverse_transform([configuration.get_array()])[0]\n target_config_vector = self._pinv_matrix.dot(vector)\n target_config = ConfigSpace.Configuration(self.target_parameter_space, vector=target_config_vector)\n\n target_configurations.append(target_config)\n\n return pd.DataFrame(target_configurations, columns=list(self.target_parameter_space.keys()))\n\n def transform(self, configuration: pd.DataFrame) -> pd.DataFrame:\n if len(configuration) != 1:\n raise ValueError(\"Configuration dataframe must contain exactly 1 row. \"\n f\"Found {len(configuration)} rows.\")\n\n target_values_dict = configuration.iloc[0].to_dict()\n target_configuration = ConfigSpace.Configuration(self.target_parameter_space, values=target_values_dict)\n\n orig_values_dict = self._transform(target_values_dict)\n orig_configuration = ConfigSpace.Configuration(self.orig_parameter_space, values=orig_values_dict)\n\n # Add to inverse dictionary -- needed for registering the performance later\n self._suggested_configs[orig_configuration] = target_configuration\n\n return pd.DataFrame([orig_values_dict.values()], columns=list(self.orig_parameter_space.keys()))\n\n def _construct_low_dim_space(self, num_low_dims: int, max_unique_values_per_param: Optional[int]) -> None:\n \"\"\"Constructs the low-dimensional parameter (potentially discretized) search space.\n\n Parameters\n ----------\n num_low_dims : int\n Number of dimensions used in the low-dimensional parameter search space.\n\n max_unique_values_per_param: Optional[int]:\n Number of unique values per parameter. Used to discretize the parameter space.\n If `None` space discretization is disabled.\n \"\"\"\n # Define target space parameters\n q_scaler = None\n if max_unique_values_per_param is None:\n hyperparameters = [\n ConfigSpace.UniformFloatHyperparameter(name=f'dim_{idx}', lower=-1, upper=1)\n for idx in range(num_low_dims)\n ]\n else:\n # Currently supported optimizers do not support defining a discretized space (like ConfigSpace does using `q` kwarg).\n # Thus, to support space discretization, we define the low-dimensional space using integer hyperparameters.\n # We also employ a scaler, which scales suggested values to [-1, 1] range, used by HeSBO projection.\n hyperparameters = [\n ConfigSpace.UniformIntegerHyperparameter(name=f'dim_{idx}', lower=1, upper=max_unique_values_per_param)\n for idx in range(num_low_dims)\n ]\n\n # Initialize quantized values scaler: from [0, max_unique_values_per_param] to (-1, 1) range\n q_scaler = MinMaxScaler(feature_range=(-1, 1))\n ones_vector = np.ones(num_low_dims)\n max_value_vector = ones_vector * max_unique_values_per_param\n q_scaler.fit([ones_vector, max_value_vector])\n\n self._q_scaler = q_scaler\n\n # Construct low-dimensional parameter search space\n config_space = ConfigSpace.ConfigurationSpace(name=self.orig_parameter_space.name)\n config_space.random = self._random_state # use same random state as in original parameter space\n config_space.add_hyperparameters(hyperparameters)\n self._target_config_space = config_space\n\n def _transform(self, configuration: dict) -> dict:\n \"\"\"Projects a low-dimensional point (configuration) to the high-dimensional original parameter space,\n and then biases the resulting parameter values towards their special value(s) (if any).\n\n Parameters\n ----------\n configuration : dict\n Configuration in the low-dimensional space.\n\n Returns\n -------\n configuration : dict\n Projected configuration in the high-dimensional original search space.\n \"\"\"\n original_parameters = list(self.orig_parameter_space.values())\n low_dim_config_values = list(configuration.values())\n\n if self._q_scaler is not None:\n # Scale parameter values from [1, max_value] to [-1, 1]\n low_dim_config_values = self._q_scaler.transform([low_dim_config_values])[0]\n\n # Project low-dim point to original parameter space\n original_config_values = [\n self._sigma_vector[idx] * low_dim_config_values[self._h_matrix[idx]]\n for idx in range(len(original_parameters))\n ]\n # Scale parameter values to [0, 1]\n original_config_values = self._config_scaler.transform([original_config_values])[0]\n\n original_config = {}\n for param, norm_value in zip(original_parameters, original_config_values):\n # Clip value to force it to fall in [0, 1]\n # NOTE: HeSBO projection ensures that theoretically but due to\n # floating point ops nuances this is not always guaranteed\n value = max(0., min(1., norm_value)) # pylint: disable=redefined-loop-name\n\n if isinstance(param, ConfigSpace.CategoricalHyperparameter):\n index = int(value * len(param.choices)) # truncate integer part\n index = max(0, min(len(param.choices) - 1, index))\n # NOTE: potential rounding here would be unfair to first & last values\n orig_value = param.choices[index]\n elif isinstance(param, ConfigSpace.hyperparameters.NumericalHyperparameter):\n if param.name in self._special_param_values_dict:\n value = self._special_param_value_scaler(param, value)\n\n orig_value = param._transform(value) # pylint: disable=protected-access\n orig_value = max(param.lower, min(param.upper, orig_value))\n else:\n raise NotImplementedError(\"Only Categorical, Integer, and Float hyperparameters are currently supported.\")\n\n original_config[param.name] = orig_value\n\n return original_config\n\n def _special_param_value_scaler(self, param: ConfigSpace.UniformIntegerHyperparameter, input_value: float) -> float:\n \"\"\"Biases the special value(s) of this parameter, by shifting the normalized `input_value` towards those.\n\n Parameters\n ----------\n param: ConfigSpace.UniformIntegerHyperparameter\n Parameter of the original parameter space.\n\n input_value: float\n Normalized value for this parameter, as suggested by the underlying optimizer.\n\n Returns\n -------\n biased_value: float\n Normalized value after special value(s) biasing is applied.\n \"\"\"\n special_values_list = self._special_param_values_dict[param.name]\n\n # Check if input value corresponds to some special value\n perc_sum = 0.\n ret: float\n for special_value, biasing_perc in special_values_list:\n perc_sum += biasing_perc\n if input_value < perc_sum:\n ret = param._inverse_transform(special_value) # pylint: disable=protected-access\n return ret\n\n # Scale input value uniformly to non-special values\n ret = param._inverse_transform( # pylint: disable=protected-access\n param._transform_scalar((input_value - perc_sum) / (1 - perc_sum))) # pylint: disable=protected-access\n return ret\n\n # pylint: disable=too-complex,too-many-branches\n def _validate_special_param_values(self, special_param_values_dict: dict) -> None:\n \"\"\"Checks that the user-provided dict of special parameter values is valid.\n And assigns it to the corresponding attribute.\n\n Parameters\n ----------\n special_param_values_dict: dict\n User-provided dict of special parameter values.\n\n Raises\n ------\n ValueError: if dictionary key, valid, or structure is invalid.\n NotImplementedError: if special value is defined for a non-integer parameter\n \"\"\"\n error_prefix = \"Validation of special parameter values dict failed.\"\n\n all_parameters = list(self.orig_parameter_space.keys())\n sanitized_dict = {}\n\n for param, value in special_param_values_dict.items():\n if param not in all_parameters:\n raise ValueError(error_prefix + f\"Parameter '{param}' does not exist.\")\n\n hyperparameter = self.orig_parameter_space[param]\n if not isinstance(hyperparameter, ConfigSpace.UniformIntegerHyperparameter):\n raise NotImplementedError(error_prefix + f\"Parameter '{param}' is not supported. \"\n \"Only Integer Hyperparameters are currently supported.\")\n\n if isinstance(value, int):\n # User specifies a single special value -- default biasing percentage is used\n tuple_list = [(value, self.DEFAULT_SPECIAL_PARAM_VALUE_BIASING_PERCENTAGE)]\n elif isinstance(value, tuple) and [type(v) for v in value] == [int, float]:\n # User specifies both special value and biasing percentage\n tuple_list = [value] # type: ignore[list-item]\n elif isinstance(value, list) and value:\n if all(isinstance(t, int) for t in value):\n # User specifies list of special values\n tuple_list = [(v, self.DEFAULT_SPECIAL_PARAM_VALUE_BIASING_PERCENTAGE) for v in value]\n elif all(isinstance(t, tuple) and [type(v) for v in t] == [int, float] for t in value):\n # User specifies list of tuples; each tuple defines the special value and the biasing percentage\n tuple_list = value\n else:\n raise ValueError(error_prefix + f\"Invalid format in value list for parameter '{param}'. \"\n f\"Special value list should contain either integers, or (special value, biasing %) tuples.\")\n else:\n raise ValueError(error_prefix + f\"Invalid format for parameter '{param}'. Dict value should be \"\n \"an int, a (int, float) tuple, a list of integers, or a list of (int, float) tuples.\")\n\n # Are user-specified special values valid?\n if not all(hyperparameter.lower <= v <= hyperparameter.upper for v, _ in tuple_list):\n raise ValueError(error_prefix + f\"One (or more) special values are outside of parameter '{param}' value domain.\")\n # Are user-provided special values unique?\n if len(set(v for v, _ in tuple_list)) != len(tuple_list):\n raise ValueError(error_prefix + f\"One (or more) special values are defined more than once for parameter '{param}'.\")\n # Are biasing percentages valid?\n if not all(0 < perc < 1 for _, perc in tuple_list):\n raise ValueError(error_prefix + f\"One (or more) biasing percentages for parameter '{param}' are invalid: \"\n \"i.e., fall outside (0, 1) range.\")\n\n total_percentage = sum(perc for _, perc in tuple_list)\n if total_percentage >= 1.:\n raise ValueError(error_prefix + f\"Total special values percentage for parameter '{param}' surpass 100%.\")\n # ... and reasonable?\n if total_percentage >= 0.5:\n warn(f\"Total special values percentage for parameter '{param}' exceeds 50%.\", UserWarning)\n\n sanitized_dict[param] = tuple_list\n\n self._special_param_values_dict = sanitized_dict\n\n def _try_generate_approx_inverse_mapping(self) -> None:\n \"\"\"Tries to generate an approximate reverse mapping: i.e., from high-dimensional space to the low-dimensional one.\n Reverse mapping is generated using the pseudo-inverse matrix, of original HeSBO projection matrix.\n This mapping can be potentially used to register configurations that were *not* previously suggested by the optimizer.\n\n NOTE: This method is experimental, and there is currently no guarantee that it works as expected.\n\n Raises\n ------\n RuntimeError: if reverse mapping computation fails.\n \"\"\"\n from scipy.linalg import pinv, LinAlgError # pylint: disable=import-outside-toplevel\n\n warn(\"Trying to register a configuration that was not previously suggested by the optimizer. \" +\n \"This inverse configuration transformation is typically not supported. \" +\n \"However, we will try to register this configuration using an *experimental* method.\", UserWarning)\n\n orig_space_num_dims = len(list(self.orig_parameter_space.values()))\n target_space_num_dims = len(list(self.target_parameter_space.values()))\n\n # Construct dense projection matrix from sparse repr\n proj_matrix = np.zeros(shape=(orig_space_num_dims, target_space_num_dims))\n for row, col in enumerate(self._h_matrix):\n proj_matrix[row][col] = self._sigma_vector[row]\n\n # Compute pseudo-inverse matrix\n try:\n self._pinv_matrix = pinv(proj_matrix)\n except LinAlgError as err:\n raise RuntimeError(f\"Unable to generate reverse mapping using pseudo-inverse matrix: {repr(err)}\") from err\n assert self._pinv_matrix.shape == (target_space_num_dims, orig_space_num_dims)\n" }, { "alpha_fraction": 0.5651804804801941, "alphanum_fraction": 0.571974515914917, "avg_line_length": 25.022098541259766, "blob_id": "c481751a9ad36a745c176e4831e706e8f2868076", "content_id": "4b971a1db10df85114d30df48a1e865f94a9a7d2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4710, "license_type": "permissive", "max_line_length": 76, "num_lines": 181, "path": "/mlos_bench/mlos_bench/tests/tunables/tunable_definition_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nUnit tests for checking tunable definition rules.\n\"\"\"\n\nimport json5 as json\nimport pytest\n\nfrom mlos_bench.tunables.tunable import Tunable\n\n\ndef test_categorical_required_params() -> None:\n \"\"\"\n Check that required parameters are present for categorical tunables.\n \"\"\"\n json_config = \"\"\"\n {\n \"type\": \"categorical\",\n \"values_missing\": [\"foo\", \"bar\", \"foo\"],\n \"default\": \"foo\"\n }\n \"\"\"\n config = json.loads(json_config)\n with pytest.raises(ValueError):\n Tunable(name='test', config=config)\n\n\ndef test_categorical_wrong_params() -> None:\n \"\"\"\n Disallow range param for categorical tunables.\n \"\"\"\n json_config = \"\"\"\n {\n \"type\": \"categorical\",\n \"values\": [\"foo\", \"bar\", \"foo\"],\n \"range\": [0, 1],\n \"default\": \"foo\"\n }\n \"\"\"\n config = json.loads(json_config)\n with pytest.raises(ValueError):\n Tunable(name='test', config=config)\n\n\ndef test_categorical_disallow_special_values() -> None:\n \"\"\"\n Disallow special values for categorical values.\n \"\"\"\n json_config = \"\"\"\n {\n \"type\": \"categorical\",\n \"values\": [\"foo\", \"bar\", \"foo\"],\n \"special\": [\"baz\"],\n \"default\": \"foo\"\n }\n \"\"\"\n config = json.loads(json_config)\n with pytest.raises(ValueError):\n Tunable(name='test', config=config)\n\n\ndef test_categorical_tunable_disallow_repeats() -> None:\n \"\"\"\n Disallow duplicate values in categorical tunables.\n \"\"\"\n with pytest.raises(ValueError):\n Tunable(name='test', config={\n \"type\": \"categorical\",\n \"values\": [\"foo\", \"bar\", \"foo\"],\n \"default\": \"foo\",\n })\n\n\[email protected](\"tunable_type\", [\"int\", \"float\"])\ndef test_numerical_tunable_disallow_null_default(tunable_type: str) -> None:\n \"\"\"\n Disallow null values as default for numerical tunables.\n \"\"\"\n with pytest.raises(ValueError):\n Tunable(name=f'test_{tunable_type}', config={\n \"type\": tunable_type,\n \"range\": [0, 10],\n \"default\": None,\n })\n\n\[email protected](\"tunable_type\", [\"int\", \"float\"])\ndef test_numerical_tunable_disallow_out_of_range(tunable_type: str) -> None:\n \"\"\"\n Disallow out of range values as default for numerical tunables.\n \"\"\"\n with pytest.raises(ValueError):\n Tunable(name=f'test_{tunable_type}', config={\n \"type\": tunable_type,\n \"range\": [0, 10],\n \"default\": 11,\n })\n\n\[email protected](\"tunable_type\", [\"int\", \"float\"])\ndef test_numerical_tunable_wrong_params(tunable_type: str) -> None:\n \"\"\"\n Disallow values param for numerical tunables.\n \"\"\"\n with pytest.raises(ValueError):\n Tunable(name=f'test_{tunable_type}', config={\n \"type\": tunable_type,\n \"range\": [0, 10],\n \"values\": [\"foo\", \"bar\"],\n \"default\": 0,\n })\n\n\[email protected](\"tunable_type\", [\"int\", \"float\"])\ndef test_numerical_tunable_required_params(tunable_type: str) -> None:\n \"\"\"\n Disallow null values param for numerical tunables.\n \"\"\"\n json_config = f\"\"\"\n {{\n \"type\": \"{tunable_type}\",\n \"range_missing\": [0, 10],\n \"default\": 0\n }}\n \"\"\"\n config = json.loads(json_config)\n with pytest.raises(ValueError):\n Tunable(name=f'test_{tunable_type}', config=config)\n\n\[email protected](\"tunable_type\", [\"int\", \"float\"])\ndef test_numerical_tunable_invalid_range(tunable_type: str) -> None:\n \"\"\"\n Disallow invalid range param for numerical tunables.\n \"\"\"\n json_config = f\"\"\"\n {{\n \"type\": \"{tunable_type}\",\n \"range\": [0, 10, 7],\n \"default\": 0\n }}\n \"\"\"\n config = json.loads(json_config)\n with pytest.raises(AssertionError):\n Tunable(name=f'test_{tunable_type}', config=config)\n\n\[email protected](\"tunable_type\", [\"int\", \"float\"])\ndef test_numerical_tunable_reversed_range(tunable_type: str) -> None:\n \"\"\"\n Disallow reverse range param for numerical tunables.\n \"\"\"\n json_config = f\"\"\"\n {{\n \"type\": \"{tunable_type}\",\n \"range\": [10, 0],\n \"default\": 0\n }}\n \"\"\"\n config = json.loads(json_config)\n with pytest.raises(ValueError):\n Tunable(name=f'test_{tunable_type}', config=config)\n\n\ndef test_bad_type() -> None:\n \"\"\"\n Disallow bad types.\n \"\"\"\n json_config = \"\"\"\n {\n \"type\": \"foo\",\n \"range\": [0, 10],\n \"default\": 0\n }\n \"\"\"\n config = json.loads(json_config)\n with pytest.raises(ValueError):\n Tunable(name='test_bad_type', config=config)\n" }, { "alpha_fraction": 0.7501523494720459, "alphanum_fraction": 0.7501523494720459, "avg_line_length": 31.176469802856445, "blob_id": "ec5565afb99414bda66fe615cbd6a922f378f58b", "content_id": "36a85a10bfc84e6af9453e866f8eff38273b4e11", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1641, "license_type": "permissive", "max_line_length": 118, "num_lines": 51, "path": "/mlos_bench/mlos_bench/tests/config/services/test_load_service_config_examples.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTests for loading service config examples.\n\"\"\"\nimport logging\nfrom typing import List\n\nimport pytest\n\nfrom mlos_bench.tests.config import locate_config_examples\n\nfrom mlos_bench.config.schemas.config_schemas import ConfigSchema\nfrom mlos_bench.services.base_service import Service\nfrom mlos_bench.services.config_persistence import ConfigPersistenceService\nfrom mlos_bench.util import path_join\n\n\n_LOG = logging.getLogger(__name__)\n_LOG.setLevel(logging.DEBUG)\n\n\n# Get the set of configs to test.\nCONFIG_TYPE = \"services\"\n\n\ndef filter_configs(configs_to_filter: List[str]) -> List[str]:\n \"\"\"If necessary, filter out json files that aren't for the module we're testing.\"\"\"\n for config_path in configs_to_filter:\n if config_path.endswith(\"arm-templates/azuredeploy-ubuntu-vm.jsonc\"):\n configs_to_filter.remove(config_path)\n return configs_to_filter\n\n\nconfigs = filter_configs(locate_config_examples(path_join(ConfigPersistenceService.BUILTIN_CONFIG_PATH, CONFIG_TYPE)))\nassert configs\n\n\[email protected](\"config_path\", configs)\ndef test_load_service_config_examples(config_loader_service: ConfigPersistenceService, config_path: str) -> None:\n \"\"\"Tests loading a config example.\"\"\"\n config = config_loader_service.load_config(config_path, ConfigSchema.SERVICE)\n # Make an instance of the class based on the config.\n service_inst = config_loader_service.build_service(\n config=config,\n parent=config_loader_service,\n )\n assert service_inst is not None\n assert isinstance(service_inst, Service)\n" }, { "alpha_fraction": 0.7016393542289734, "alphanum_fraction": 0.7065573930740356, "avg_line_length": 20.785715103149414, "blob_id": "6779392f03c46656fbaf15888834062ae7f55fc9", "content_id": "8e18ada9dc530d4f7f3c74ca963886424af03ce0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 610, "license_type": "permissive", "max_line_length": 75, "num_lines": 28, "path": "/mlos_bench/mlos_bench/tests/config/conftest.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTest fixtures for mlos_bench config loader tests.\n\"\"\"\n\nimport sys\n\nimport pytest\n\nfrom mlos_bench.services.config_persistence import ConfigPersistenceService\n\nif sys.version_info < (3, 10):\n from importlib_resources import files\nelse:\n from importlib.resources import files\n\n\[email protected]\ndef config_loader_service() -> ConfigPersistenceService:\n \"\"\"Config loader service fixture.\"\"\"\n return ConfigPersistenceService(config={\n \"config_path\": [\n files(\"mlos_bench.tests.config\"),\n ]\n })\n" }, { "alpha_fraction": 0.6024181842803955, "alphanum_fraction": 0.6024181842803955, "avg_line_length": 32.47618865966797, "blob_id": "6ab2eb52b2b7ff53b55965409c886ce7c30a2311", "content_id": "83595aad1fdfdee82bb052c6f5245c1bcc0f3ef6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2812, "license_type": "permissive", "max_line_length": 90, "num_lines": 84, "path": "/mlos_bench/mlos_bench/services/base_fileshare.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nBase class for remote file shares.\n\"\"\"\n\nimport logging\n\nfrom abc import ABCMeta, abstractmethod\nfrom typing import Any, Dict, Optional\n\nfrom mlos_bench.services.base_service import Service\nfrom mlos_bench.services.types.fileshare_type import SupportsFileShareOps\n\n_LOG = logging.getLogger(__name__)\n\n\nclass FileShareService(Service, SupportsFileShareOps, metaclass=ABCMeta):\n \"\"\"\n An abstract base of all file shares.\n \"\"\"\n\n def __init__(self, config: Optional[Dict[str, Any]] = None,\n global_config: Optional[Dict[str, Any]] = None,\n parent: Optional[Service] = None):\n \"\"\"\n Create a new file share with a given config.\n\n Parameters\n ----------\n config : dict\n Free-format dictionary that contains the file share configuration.\n It will be passed as a constructor parameter of the class\n specified by `class_name`.\n global_config : dict\n Free-format dictionary of global parameters.\n parent : Service\n Parent service that can provide mixin functions.\n \"\"\"\n super().__init__(config, global_config, parent)\n\n self.register([\n self.download,\n self.upload,\n ])\n\n @abstractmethod\n def download(self, remote_path: str, local_path: str, recursive: bool = True) -> None:\n \"\"\"\n Downloads contents from a remote share path to a local path.\n\n Parameters\n ----------\n remote_path : str\n Path to download from the remote file share, a file if recursive=False\n or a directory if recursive=True.\n local_path : str\n Path to store the downloaded content to.\n recursive : bool\n If False, ignore the subdirectories;\n if True (the default), download the entire directory tree.\n \"\"\"\n _LOG.info(\"Download from File Share %s recursively: %s -> %s\",\n \"\" if recursive else \"non\", remote_path, local_path)\n\n @abstractmethod\n def upload(self, local_path: str, remote_path: str, recursive: bool = True) -> None:\n \"\"\"\n Uploads contents from a local path to remote share path.\n\n Parameters\n ----------\n local_path : str\n Path to the local directory to upload contents from.\n remote_path : str\n Path in the remote file share to store the uploaded content to.\n recursive : bool\n If False, ignore the subdirectories;\n if True (the default), upload the entire directory tree.\n \"\"\"\n _LOG.info(\"Upload to File Share %s recursively: %s -> %s\",\n \"\" if recursive else \"non\", local_path, remote_path)\n" }, { "alpha_fraction": 0.6457498669624329, "alphanum_fraction": 0.6461949348449707, "avg_line_length": 31.100000381469727, "blob_id": "fd52c0d05da6b338877a3a78df7d917f9eb50bf6", "content_id": "27421f687dae746a8144f58f2b52565e7f5c065d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2247, "license_type": "permissive", "max_line_length": 122, "num_lines": 70, "path": "/mlos_core/mlos_core/optimizers/random_optimizer.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nContains the RandomOptimizer class.\n\"\"\"\n\nfrom typing import Optional\n\nimport pandas as pd\n\nfrom mlos_core.optimizers.optimizer import BaseOptimizer\n\n\nclass RandomOptimizer(BaseOptimizer):\n \"\"\"Optimizer class that produces random suggestions.\n Useful for baseline comparison against Bayesian optimizers.\n\n Parameters\n ----------\n parameter_space : ConfigSpace.ConfigurationSpace\n The parameter space to optimize.\n \"\"\"\n\n def _register(self, configurations: pd.DataFrame, scores: pd.Series,\n context: Optional[pd.DataFrame] = None) -> None:\n \"\"\"Registers the given configurations and scores.\n\n Doesn't do anything on the RandomOptimizer except storing configurations for logging.\n\n Parameters\n ----------\n configurations : pd.DataFrame\n Dataframe of configurations / parameters. The columns are parameter names and the rows are the configurations.\n\n scores : pd.Series\n Scores from running the configurations. The index is the same as the index of the configurations.\n\n context : None\n Not Yet Implemented.\n \"\"\"\n if context is not None:\n raise NotImplementedError()\n # should we pop them from self.pending_observations?\n\n def _suggest(self, context: Optional[pd.DataFrame] = None) -> pd.DataFrame:\n \"\"\"Suggests a new configuration.\n\n Sampled at random using ConfigSpace.\n\n Parameters\n ----------\n context : None\n Not Yet Implemented.\n\n Returns\n -------\n configuration : pd.DataFrame\n Pandas dataframe with a single row. Column names are the parameter names.\n \"\"\"\n if context is not None:\n # not sure how that works here?\n raise NotImplementedError()\n return pd.DataFrame(dict(self.optimizer_parameter_space.sample_configuration()), index=[0])\n\n def register_pending(self, configurations: pd.DataFrame,\n context: Optional[pd.DataFrame] = None) -> None:\n raise NotImplementedError()\n # self._pending_observations.append((configurations, context))\n" }, { "alpha_fraction": 0.7161571979522705, "alphanum_fraction": 0.7161571979522705, "avg_line_length": 16.615385055541992, "blob_id": "f0cad73fdd6ac82dfd353ffd79d2d49ddd52a24e", "content_id": "eede9383bc6e73dcd28fb8145d6730223a1ac74a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 229, "license_type": "permissive", "max_line_length": 57, "num_lines": 13, "path": "/mlos_bench/mlos_bench/tests/services/local/mock/__init__.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nMock local services for testing purposes.\n\"\"\"\n\nfrom .mock_local_exec_service import MockLocalExecService\n\n__all__ = [\n 'MockLocalExecService',\n]\n" }, { "alpha_fraction": 0.6530163884162903, "alphanum_fraction": 0.6562459468841553, "avg_line_length": 44.53529357910156, "blob_id": "60f75469320fca6cb5d895ec841392ce44097ab9", "content_id": "78d661be730130847658ef422cf601d4a7271a85", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15482, "license_type": "permissive", "max_line_length": 127, "num_lines": 340, "path": "/mlos_core/mlos_core/optimizers/bayesian_optimizers/smac_optimizer.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nContains the wrapper class for SMAC Bayesian optimizers.\nSee Also: <https://automl.github.io/SMAC3/main/index.html>\n\"\"\"\n\nfrom logging import warning\nfrom pathlib import Path\nfrom typing import Dict, List, Optional, Union, TYPE_CHECKING\nfrom tempfile import TemporaryDirectory\n\nimport ConfigSpace\nimport numpy.typing as npt\nimport pandas as pd\n\nfrom mlos_core.optimizers.bayesian_optimizers.bayesian_optimizer import BaseBayesianOptimizer\nfrom mlos_core.spaces.adapters.adapter import BaseSpaceAdapter\nfrom mlos_core.spaces.adapters.identity_adapter import IdentityAdapter\n\n\nclass SmacOptimizer(BaseBayesianOptimizer):\n \"\"\"Wrapper class for SMAC based Bayesian optimization.\n\n Parameters\n ----------\n parameter_space : ConfigSpace.ConfigurationSpace\n The parameter space to optimize.\n\n space_adapter : BaseSpaceAdapter\n The space adapter class to employ for parameter space transformations.\n\n seed : Optional[int]\n By default SMAC uses a known seed (0) to keep results reproducible.\n However, if a `None` seed is explicitly provided, we let a random seed be produced by SMAC.\n\n run_name : Optional[str]\n Name of this run. This is used to easily distinguish across different runs.\n If set to `None` (default), SMAC will generate a hash from metadata.\n\n output_directory : Optional[str]\n The directory where SMAC output will saved. If set to `None` (default), a temporary dir will be used.\n\n max_trials : int\n Maximum number of trials (i.e., function evaluations) to be run. Defaults to 100.\n Note that modifying this value directly affects the value of `n_random_init`, if latter is set to `None`.\n\n n_random_init : Optional[int]\n Number of points evaluated at start to bootstrap the optimizer.\n Default depends on max_trials and number of parameters and max_ratio.\n Note: it can sometimes be useful to set this to 1 when pre-warming the\n optimizer from historical data.\n See Also: mlos_bench.optimizer.bulk_register\n\n max_ratio : Optional[int]\n Maximum ratio of max_trials to be random configurations to be evaluated\n at start to bootstrap the optimizer.\n Useful if you want to explicitly control the number of random\n configurations evaluated at start.\n\n use_default_config: bool\n Whether to use the default config for the first trial after random initialization.\n\n n_random_probability: float\n Probability of choosing to evaluate a random configuration during optimization.\n Defaults to `0.1`. Setting this to a higher value favors exploration over exploitation.\n \"\"\"\n\n def __init__(self, *, # pylint: disable=too-many-locals\n parameter_space: ConfigSpace.ConfigurationSpace,\n space_adapter: Optional[BaseSpaceAdapter] = None,\n seed: Optional[int] = 0,\n run_name: Optional[str] = None,\n output_directory: Optional[str] = None,\n max_trials: int = 100,\n n_random_init: Optional[int] = None,\n max_ratio: Optional[float] = None,\n use_default_config: bool = False,\n n_random_probability: float = 0.1):\n\n super().__init__(\n parameter_space=parameter_space,\n space_adapter=space_adapter,\n )\n\n # Declare at the top because we need it in __del__/cleanup()\n self._temp_output_directory: Optional[TemporaryDirectory] = None\n\n # pylint: disable=import-outside-toplevel\n from smac import HyperparameterOptimizationFacade as Optimizer_Smac\n from smac import Scenario\n from smac.intensifier.abstract_intensifier import AbstractIntensifier\n from smac.main.config_selector import ConfigSelector\n from smac.random_design.probability_design import ProbabilityRandomDesign\n from smac.runhistory import TrialInfo\n\n # Store for TrialInfo instances returned by .ask()\n self.trial_info_map: Dict[ConfigSpace.Configuration, TrialInfo] = {}\n\n # The default when not specified is to use a known seed (0) to keep results reproducible.\n # However, if a `None` seed is explicitly provided, we let a random seed be produced by SMAC.\n # https://automl.github.io/SMAC3/main/api/smac.scenario.html#smac.scenario.Scenario\n seed = -1 if seed is None else seed\n\n # Create temporary directory for SMAC output (if none provided)\n if output_directory is None:\n # pylint: disable=consider-using-with\n try:\n self._temp_output_directory = TemporaryDirectory(ignore_cleanup_errors=True) # Argument added in Python 3.10\n except TypeError:\n self._temp_output_directory = TemporaryDirectory()\n output_directory = self._temp_output_directory.name\n\n if n_random_init is not None:\n assert isinstance(n_random_init, int) and n_random_init >= 0\n if n_random_init == max_trials and use_default_config:\n # Increase max budgeted trials to account for use_default_config.\n max_trials += 1\n\n scenario: Scenario = Scenario(\n self.optimizer_parameter_space,\n name=run_name,\n output_directory=Path(output_directory),\n deterministic=True,\n use_default_config=use_default_config,\n n_trials=max_trials,\n seed=seed or -1, # if -1, SMAC will generate a random seed internally\n n_workers=1, # Use a single thread for evaluating trials\n )\n intensifier: AbstractIntensifier = Optimizer_Smac.get_intensifier(scenario, max_config_calls=1)\n config_selector: ConfigSelector = Optimizer_Smac.get_config_selector(scenario, retrain_after=1)\n\n # TODO: When bulk registering prior configs to rewarm the optimizer,\n # there is a way to inform SMAC's initial design that we have\n # additional_configs and can set n_configs == 0.\n # Additionally, we may want to consider encoding those values into the\n # runhistory when prewarming the optimizer so that the initial design\n # doesn't reperform random init.\n # See Also: #488\n\n initial_design_args: Dict[str, Union[list, int, float, Scenario]] = {\n 'scenario': scenario,\n # Workaround a bug in SMAC that sets a default arg to a mutable\n # value that can cause issues when multiple optimizers are\n # instantiated with the use_default_config option within the same\n # process that use different ConfigSpaces so that the second\n # receives the default config from both as an additional config.\n 'additional_configs': []\n }\n if n_random_init is not None:\n initial_design_args['n_configs'] = n_random_init\n if n_random_init > 0.25 * max_trials and max_ratio is None:\n warning(\n 'Number of random initial configurations (%d) is ' +\n 'greater than 25%% of max_trials (%d). ' +\n 'Consider setting max_ratio to avoid SMAC overriding n_random_init.',\n n_random_init,\n max_trials,\n )\n if max_ratio is not None:\n assert isinstance(max_ratio, float) and 0.0 <= max_ratio <= 1.0\n initial_design_args['max_ratio'] = max_ratio\n\n # Use the default InitialDesign from SMAC.\n # (currently SBOL instead of LatinHypercube due to better uniformity\n # for initial sampling which results in lower overall samples required)\n initial_design = Optimizer_Smac.get_initial_design(**initial_design_args) # type: ignore[arg-type]\n # initial_design = LatinHypercubeInitialDesign(**initial_design_args) # type: ignore[arg-type]\n\n # Workaround a bug in SMAC that doesn't pass the seed to the random\n # design when generated a random_design for itself via the\n # get_random_design static method when random_design is None.\n assert isinstance(n_random_probability, float) and n_random_probability >= 0\n random_design = ProbabilityRandomDesign(probability=n_random_probability, seed=scenario.seed)\n\n self.base_optimizer = Optimizer_Smac(\n scenario,\n SmacOptimizer._dummy_target_func,\n initial_design=initial_design,\n intensifier=intensifier,\n random_design=random_design,\n config_selector=config_selector,\n overwrite=True,\n logging_level=False, # Use the existing logger\n )\n\n def __del__(self) -> None:\n # Best-effort attempt to clean up, in case the user forgets to call .cleanup()\n self.cleanup()\n\n @property\n def n_random_init(self) -> int:\n \"\"\"\n Gets the number of random samples to use to initialize the optimizer's search space sampling.\n\n Note: This may not be equal to the value passed to the initializer, due to logic present in the SMAC.\n See Also: max_ratio\n\n Returns\n -------\n int\n The number of random samples used to initialize the optimizer's search space sampling.\n \"\"\"\n # pylint: disable=protected-access\n return self.base_optimizer._initial_design._n_configs\n\n @staticmethod\n def _dummy_target_func(config: ConfigSpace.Configuration, seed: int = 0) -> None:\n \"\"\"Dummy target function for SMAC optimizer.\n\n Since we only use the ask-and-tell interface, this is never called.\n\n Parameters\n ----------\n config : ConfigSpace.Configuration\n Configuration to evaluate.\n\n seed : int\n Random seed to use for the target function. Not actually used.\n \"\"\"\n # NOTE: Providing a target function when using the ask-and-tell interface is an imperfection of the API\n # -- this planned to be fixed in some future release: https://github.com/automl/SMAC3/issues/946\n raise RuntimeError('This function should never be called.')\n\n def _register(self, configurations: pd.DataFrame, scores: pd.Series, context: Optional[pd.DataFrame] = None) -> None:\n \"\"\"Registers the given configurations and scores.\n\n Parameters\n ----------\n configurations : pd.DataFrame\n Dataframe of configurations / parameters. The columns are parameter names and the rows are the configurations.\n\n scores : pd.Series\n Scores from running the configurations. The index is the same as the index of the configurations.\n\n context : pd.DataFrame\n Not Yet Implemented.\n \"\"\"\n from smac.runhistory import StatusType, TrialInfo, TrialValue # pylint: disable=import-outside-toplevel\n\n if context is not None:\n raise NotImplementedError()\n\n # Register each trial (one-by-one)\n for config, score in zip(self._to_configspace_configs(configurations), scores.tolist()):\n # Retrieve previously generated TrialInfo (returned by .ask()) or create new TrialInfo instance\n info: TrialInfo = self.trial_info_map.get(config, TrialInfo(config=config, seed=self.base_optimizer.scenario.seed))\n value: TrialValue = TrialValue(cost=score, time=0.0, status=StatusType.SUCCESS)\n self.base_optimizer.tell(info, value, save=False)\n\n # Save optimizer once we register all configs\n self.base_optimizer.optimizer.save()\n\n def _suggest(self, context: Optional[pd.DataFrame] = None) -> pd.DataFrame:\n \"\"\"Suggests a new configuration.\n\n Parameters\n ----------\n context : pd.DataFrame\n Not Yet Implemented.\n\n Returns\n -------\n configuration : pd.DataFrame\n Pandas dataframe with a single row. Column names are the parameter names.\n \"\"\"\n if TYPE_CHECKING:\n from smac.runhistory import TrialInfo # pylint: disable=import-outside-toplevel\n\n if context is not None:\n raise NotImplementedError()\n\n trial: TrialInfo = self.base_optimizer.ask()\n trial.config.is_valid_configuration()\n self.optimizer_parameter_space.check_configuration(trial.config)\n assert trial.config.config_space == self.optimizer_parameter_space\n self.trial_info_map[trial.config] = trial\n config_df = pd.DataFrame([trial.config], columns=list(self.optimizer_parameter_space.keys()))\n return config_df\n\n def register_pending(self, configurations: pd.DataFrame, context: Optional[pd.DataFrame] = None) -> None:\n raise NotImplementedError()\n\n def surrogate_predict(self, configurations: pd.DataFrame, context: Optional[pd.DataFrame] = None) -> npt.NDArray:\n from smac.utils.configspace import convert_configurations_to_array # pylint: disable=import-outside-toplevel\n\n if context is not None:\n raise NotImplementedError()\n if self._space_adapter and not isinstance(self._space_adapter, IdentityAdapter):\n raise NotImplementedError()\n\n # pylint: disable=protected-access\n if len(self._observations) <= self.base_optimizer._initial_design._n_configs:\n raise RuntimeError(\n 'Surrogate model can make predictions *only* after all initial points have been evaluated ' +\n f'{len(self._observations)} <= {self.base_optimizer._initial_design._n_configs}')\n if self.base_optimizer._config_selector._model is None:\n raise RuntimeError('Surrogate model is not yet trained')\n\n configs: npt.NDArray = convert_configurations_to_array(self._to_configspace_configs(configurations))\n mean_predictions, _ = self.base_optimizer._config_selector._model.predict(configs)\n return mean_predictions.reshape(-1,)\n\n def acquisition_function(self, configurations: pd.DataFrame, context: Optional[pd.DataFrame] = None) -> npt.NDArray:\n if context is not None:\n raise NotImplementedError()\n if self._space_adapter:\n raise NotImplementedError()\n\n # pylint: disable=protected-access\n if self.base_optimizer._config_selector._acquisition_function is None:\n raise RuntimeError('Acquisition function is not yet initialized')\n\n configs: list = self._to_configspace_configs(configurations)\n return self.base_optimizer._config_selector._acquisition_function(configs).reshape(-1,)\n\n def cleanup(self) -> None:\n if self._temp_output_directory is not None:\n self._temp_output_directory.cleanup()\n self._temp_output_directory = None\n\n def _to_configspace_configs(self, configurations: pd.DataFrame) -> List[ConfigSpace.Configuration]:\n \"\"\"Convert a dataframe of configurations to a list of ConfigSpace configurations.\n\n Parameters\n ----------\n configurations : pd.DataFrame\n Dataframe of configurations / parameters. The columns are parameter names and the rows are the configurations.\n\n Returns\n -------\n configurations : list\n List of ConfigSpace configurations.\n \"\"\"\n return [\n ConfigSpace.Configuration(self.optimizer_parameter_space, values=config.to_dict())\n for (_, config) in configurations.iterrows()\n ]\n" }, { "alpha_fraction": 0.6358157396316528, "alphanum_fraction": 0.6564787030220032, "avg_line_length": 36.467742919921875, "blob_id": "c99416f3507c7b9b3f7672be566187e3103ea558", "content_id": "cfdecbb67b0510f3ef466f7f2033de123f73c69f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2323, "license_type": "permissive", "max_line_length": 92, "num_lines": 62, "path": "/mlos_bench/mlos_bench/tests/storage/trial_config_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nUnit tests for saving and retrieving additional parameters of pending trials.\n\"\"\"\n\nfrom mlos_bench.storage.base_storage import Storage\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\n\n\ndef test_exp_trial_pending(exp_storage_memory_sql: Storage.Experiment,\n tunable_groups: TunableGroups) -> None:\n \"\"\"\n Schedule a trial and check that it is pending and has the right configuration.\n \"\"\"\n config = {\"location\": \"westus2\", \"num_repeats\": 100}\n trial = exp_storage_memory_sql.new_trial(tunable_groups, config)\n (pending,) = list(exp_storage_memory_sql.pending_trials())\n assert pending.trial_id == trial.trial_id\n assert pending.tunables == tunable_groups\n assert pending.config() == {\n \"location\": \"westus2\",\n \"num_repeats\": \"100\",\n \"experiment_id\": \"Test-001\",\n \"trial_id\": 1,\n }\n\n\ndef test_exp_trial_configs(exp_storage_memory_sql: Storage.Experiment,\n tunable_groups: TunableGroups) -> None:\n \"\"\"\n Start multiple trials with two different configs and check that\n we store only two config objects in the DB.\n \"\"\"\n config1 = tunable_groups.copy().assign({'idle': 'mwait'})\n trials1 = [\n exp_storage_memory_sql.new_trial(config1),\n exp_storage_memory_sql.new_trial(config1),\n exp_storage_memory_sql.new_trial(config1.copy()), # Same values, different instance\n ]\n assert trials1[0].config_id == trials1[1].config_id\n assert trials1[0].config_id == trials1[2].config_id\n\n config2 = tunable_groups.copy().assign({'idle': 'halt'})\n trials2 = [\n exp_storage_memory_sql.new_trial(config2),\n exp_storage_memory_sql.new_trial(config2),\n exp_storage_memory_sql.new_trial(config2.copy()), # Same values, different instance\n ]\n assert trials2[0].config_id == trials2[1].config_id\n assert trials2[0].config_id == trials2[2].config_id\n\n assert trials1[0].config_id != trials2[0].config_id\n\n pending_ids = [\n pending.config_id for pending in exp_storage_memory_sql.pending_trials()\n ]\n assert len(pending_ids) == 6\n assert len(set(pending_ids)) == 2\n assert set(pending_ids) == {trials1[0].config_id, trials2[0].config_id}\n" }, { "alpha_fraction": 0.7524777054786682, "alphanum_fraction": 0.7576808929443359, "avg_line_length": 54.28767013549805, "blob_id": "2f1f235e51fe242ee7ebb91953055e10308b85cd", "content_id": "ce61cee63fa0f3ee87a8b137f30c0b2ae67c9c9b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4036, "license_type": "permissive", "max_line_length": 305, "num_lines": 73, "path": "/mlos_bench/mlos_bench/config/schemas/README.md", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "# Config Schemas\n\nThis directory contains [json schemas](https://json-schema.org/) for describing the configuration of the MLOS benchmarking framework.\n\n## Usage\n\n`mlos_bench` `.jsonc` config files can reference these schema files in a couple of ways:\n\n### Internally\n\nIf the config file is in the same directory as the schema (e.g. when editing within this repository), it can reference the schema by filename:\n\n```jsonc\n{\n \"$schema\": \"../schemas/optimizer-schema.jsonc\",\n ...\n}\n```\n\n> Note: we usually avoid this approach since it makes it harder to move the schema files around and just doesn't look very nice.\n>\n> Instead, we try to use on `.vscode/settings.json` to map local repo file globs to their schema files and simply omit the `$schema` field from the config files.\n\n### Externally\n\n```jsonc\n{\n \"$schema\": \"https://raw.githubusercontent.com/microsoft/MLOS/main/mlos_bench/mlos_bench/config/schemas/optimizer-schema.jsonc\",\n ...\n}\n```\n\n> Note: the above URL is not guaranteed to be stable. It is often recommended to use a specific commit hash or tag in the URL rather than `main` if you depend on that.\n\n<!-- intentionally blank line to avoid markdown lint complaints -->\n\n> Note: when doing schema development within the `MLOS` repo, this approach may cause false errors to be reported if the remote schema file is different than the local one (and hence config files don't validate quite right).\n>\n> There is a [deficiency](https://github.com/microsoft/vscode/issues/2809#issuecomment-1544387883) in the `json.schemas` handling in `.vscode/settings.json` that currently prevents remote URLs from being mapping to local files.\n>\n> A simple workaround for now is to comment out the `$schema` field in the config file while editing, and then uncomment it when you're ready to commit.\n\n## Validation\n\nWithin the codebase we use [`jsonschema`](https://pypi.org/project/jsonschema/) to validate config files against the schemas upon loading.\n\nFor manual testing, you can use the [`check-jsonschema`](https://pypi.org/project/check-jsonschema/).\n\nFor instance:\n\n```shell\ncheck-jsonschema --verbose --default-filetype json5 \\\n --schemafile mlos_bench/mlos_bench/config/schemas/optimizers/optimizer-schema.json \\\n mlos_bench/mlos_bench/config/optimizers/mlos_core_opt.jsonc\n```\n\n## Development\n\n### Editing\n\nUnlike the config files, the schemas are written in plain `json` instead of `jsonc` since some tooling for schema validation doesn't support parsing json files with comments.\nYou can add comments within an object using the `\"$comment\"` property to work around this a little.\n\nWhen referencing a schema in a config file (see above), the `$schema` property will allow for autocomplete in some editors such as [VSCode](https://code.visualstudio.com/).\n\n### Conventions\n\n- We do not typically specify `\"default\"` values in the schema files, since for most validators those aren't enforced, and it would require additional maintenance effort to keep the defaults in sync with the code.\n- We typically specify `\"unevaluatedProperties\": false` in order to prevent typos in the config files from going unnoticed, however this can be overridden for portions of the schema if necessary.\n > Note: It's important to use `\"unevaluatedProperties\": false` from the [2020-09 draft](https://json-schema.org/understanding-json-schema/reference/object.html?highlight=unevaluated#unevaluated-properties), and not `\"additionalProperties\": false` due to the order in which those two rules get processed.\n- When specifying \"conditions\" always pair the property clause `\"properties\": { \"property-name\": { \"const\": \"value\" } }` to match it with the `\"required\": [\"property-name\"]` clause to ensure that it is a strict match.\n- Close all `if-then-else` statements inside a `\"oneOf\"` block with an `\"else\": false`, else the clause will implicitly default to `true`.\n > As a nice corollary, this should force a full set of matching descriptions in the `\"oneOf\"` block so we don't accidentally leave off a supported matching value.\n" }, { "alpha_fraction": 0.604645311832428, "alphanum_fraction": 0.6051502227783203, "avg_line_length": 41.13829803466797, "blob_id": "b787e82cb032d7364520fd9abb7f7fd6d41069b4", "content_id": "7f0f6c38412da42609ed718bd7cb89c2da127d97", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3961, "license_type": "permissive", "max_line_length": 102, "num_lines": 94, "path": "/mlos_bench/mlos_bench/environments/script_env.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nBase scriptable benchmark environment.\n\"\"\"\n\nimport abc\nimport re\nfrom typing import Dict, Iterable, Optional\n\nfrom mlos_bench.environments.base_environment import Environment\nfrom mlos_bench.services.base_service import Service\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\n\n\nclass ScriptEnv(Environment, metaclass=abc.ABCMeta):\n \"\"\"\n Base Environment that runs scripts for setup/run/teardown.\n \"\"\"\n\n _RE_INVALID = re.compile(r\"[^a-zA-Z0-9_]\")\n\n def __init__(self,\n *,\n name: str,\n config: dict,\n global_config: Optional[dict] = None,\n tunables: Optional[TunableGroups] = None,\n service: Optional[Service] = None):\n \"\"\"\n Create a new environment for script execution.\n\n Parameters\n ----------\n name: str\n Human-readable name of the environment.\n config : dict\n Free-format dictionary that contains the benchmark environment\n configuration. Each config must have at least the `tunable_params`\n and the `const_args` sections. It must also have at least one of\n the following parameters: {`setup`, `run`, `teardown`}.\n Additional parameters:\n * `shell_env_params` - an array of parameters to pass to the script\n as shell environment variables, and\n * `shell_env_params_rename` - a dictionary of {to: from} mappings\n of the script parameters. If not specified, replace all\n non-alphanumeric characters with underscores.\n If neither `shell_env_params` nor `shell_env_params_rename` are specified,\n pass *all* parameters to the script.\n global_config : dict\n Free-format dictionary of global parameters (e.g., security credentials)\n to be mixed in into the \"const_args\" section of the local config.\n tunables : TunableGroups\n A collection of tunable parameters for *all* environments.\n service: Service\n An optional service object (e.g., providing methods to\n deploy or reboot a VM, etc.).\n \"\"\"\n super().__init__(name=name, config=config, global_config=global_config,\n tunables=tunables, service=service)\n\n self._script_setup = self.config.get(\"setup\")\n self._script_run = self.config.get(\"run\")\n self._script_teardown = self.config.get(\"teardown\")\n\n self._shell_env_params: Optional[Iterable[str]] = self.config.get(\"shell_env_params\")\n self._shell_env_params_rename: Dict[str, str] = self.config.get(\"shell_env_params_rename\", {})\n\n def _get_env_params(self) -> Dict[str, str]:\n \"\"\"\n Get the *shell* environment parameters to be passed to the script.\n\n Returns\n -------\n env_params : Dict[str, str]\n Parameters to pass as *shell* environment variables into the script.\n This is usually a subset of `_params` with some possible conversions.\n \"\"\"\n rename: Dict[str, str] # {to: from} mapping of the script parameters.\n if self._shell_env_params is None:\n if self._shell_env_params_rename:\n # Only rename specified - use it.\n rename = self._shell_env_params_rename.copy()\n else:\n # Neither `shell_env_params` nor rename are specified - use all params.\n rename = {self._RE_INVALID.sub(\"_\", key): key for key in self._params}\n else:\n # Use `shell_env_params` and rename if specified.\n rename = {self._RE_INVALID.sub(\"_\", key): key for key in self._shell_env_params}\n rename.update(self._shell_env_params_rename)\n\n return {key_sub: str(self._params[key]) for (key_sub, key) in rename.items()}\n" }, { "alpha_fraction": 0.6971480250358582, "alphanum_fraction": 0.7043911218643188, "avg_line_length": 36.440677642822266, "blob_id": "1ddf939646d8abcbafbffabac52e18cc4844d531", "content_id": "44801102807e927fe94cd3ce2245b37ad9f80245", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2209, "license_type": "permissive", "max_line_length": 91, "num_lines": 59, "path": "/.devcontainer/scripts/prep-container-build", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#!/bin/sh\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nset -eu\n\nset -x\n\nscriptdir=$(dirname \"$(readlink -f \"$0\")\")\n# Start in the script directory.\ncd \"$scriptdir\"\n\n# Move up to the repo root.\ncd ../../\n\n# Make sure the .env file exists for the devcontainer to load.\nif [ ! -f .env ]; then\n echo \"Creating empty .env file for devcontainer.\"\n touch .env\nfi\n# Also prep the random NGINX_PORT for the docker-compose command.\nif ! [ -e .devcontainer/.env ] || ! egrep -q \"^NGINX_PORT=[0-9]+$\" .devcontainer/.env; then\n NGINX_PORT=$(($(shuf -i 0-30000 -n 1) + 80))\n echo \"NGINX_PORT=$NGINX_PORT\" > .devcontainer/.env\nfi\n\n# Prep some files to use as context for the devcontainer to build from.\nif [ -d .devcontainer/tmp ]; then\n rm -rf .devcontainer/tmp\nfi\nmkdir -p .devcontainer/tmp/\ncp -v conda-envs/mlos.yml .devcontainer/tmp/mlos.yml\nfor pkg in mlos_core mlos_bench; do\n mkdir -p .devcontainer/tmp/$pkg\n cp -v $pkg/setup.py .devcontainer/tmp/$pkg/setup.py\n cp -v $pkg/_version.py .devcontainer/tmp/$pkg/_version.py\ndone\ncp -v doc/requirements.txt .devcontainer/tmp/doc.requirements.txt\n\n# Copy the script that will be run in the devcontainer to prep the files from\n# those in a cross platform way (e.g. proper line endings and whatnot so that\n# it's cacheable and reusable across platforms).\ncp -v .devcontainer/scripts/common/prep-deps-files.sh .devcontainer/tmp/prep-deps-files.sh\n\n# Prior to building the container locally, try to pull the latest version from\n# upstream to see if we can use it as a cache.\n# TODO: Ideally we'd only do this when rebuilding the image, but not sure how\n# to detect that form of startup yet.\n# See Also: https://github.com/microsoft/vscode-remote-release/issues/8179\nif [ \"${NO_CACHE:-}\" != 'true' ]; then\n cacheFrom='mloscore.azurecr.io/mlos-devcontainer'\n # Skip pulling for now (see TODO note above)\n echo \"Consider pulling image $cacheFrom for build caching.\"\n ## Make sure we use an empty config to avoid auth issues for devs with the\n ## registry, which should allow anonymous pulls\n #tmpdir=$(mktemp -d)\n #docker --config=\"$tmpdir\" pull -q \"$cacheFrom\" >/dev/null || true\n #rmdir \"$tmpdir\"\nfi\n" }, { "alpha_fraction": 0.5545303225517273, "alphanum_fraction": 0.5631523132324219, "avg_line_length": 34.92934799194336, "blob_id": "d18644e26c23e697de22a4815419a5e4dae53723", "content_id": "7b198e838be74191f4e01a733f7942da7f15788b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6611, "license_type": "permissive", "max_line_length": 89, "num_lines": 184, "path": "/mlos_bench/mlos_bench/storage/sql/schema.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nDB schema definition.\n\"\"\"\n\nimport logging\nfrom typing import List, Any\n\nfrom sqlalchemy import (\n Engine, MetaData, Dialect, create_mock_engine,\n Table, Column, Sequence, Integer, String, DateTime,\n PrimaryKeyConstraint, ForeignKeyConstraint, UniqueConstraint,\n)\n\n_LOG = logging.getLogger(__name__)\n\n# This class is internal to SqlStorage and is mostly a struct\n# for all DB tables, so it's ok to disable the warnings.\n# pylint: disable=too-many-instance-attributes\n\n\nclass _DDL:\n \"\"\"\n A helper class to capture the DDL statements from SQLAlchemy.\n\n It is used in `DbSchema.__str__()` method below.\n \"\"\"\n\n def __init__(self, dialect: Dialect):\n self._dialect = dialect\n self.statements: List[str] = []\n\n def __call__(self, sql: Any, *_args: Any, **_kwargs: Any) -> None:\n self.statements.append(str(sql.compile(dialect=self._dialect)))\n\n def __repr__(self) -> str:\n res = \";\\n\".join(self.statements)\n return res + \";\" if res else \"\"\n\n\nclass DbSchema:\n \"\"\"\n A class to define and create the DB schema.\n \"\"\"\n\n def __init__(self, engine: Engine):\n \"\"\"\n Declare the SQLAlchemy schema for the database.\n \"\"\"\n _LOG.info(\"Create the DB schema for: %s\", engine)\n self._engine = engine\n self._meta = MetaData()\n\n self.experiment = Table(\n \"experiment\",\n self._meta,\n Column(\"exp_id\", String(255), nullable=False),\n Column(\"description\", String(1024)),\n Column(\"root_env_config\", String(1024), nullable=False),\n Column(\"git_repo\", String(1024), nullable=False),\n Column(\"git_commit\", String(40), nullable=False),\n\n PrimaryKeyConstraint(\"exp_id\"),\n )\n\n # A workaround for SQLAlchemy issue with autoincrement in DuckDB:\n if engine.dialect.name == \"duckdb\":\n seq_config_id = Sequence('seq_config_id')\n col_config_id = Column(\"config_id\", Integer, seq_config_id,\n server_default=seq_config_id.next_value(),\n nullable=False, primary_key=True)\n else:\n col_config_id = Column(\"config_id\", Integer, nullable=False,\n primary_key=True, autoincrement=True)\n\n self.config = Table(\n \"config\",\n self._meta,\n col_config_id,\n Column(\"config_hash\", String(64), nullable=False, unique=True),\n )\n\n self.trial = Table(\n \"trial\",\n self._meta,\n Column(\"exp_id\", String(255), nullable=False),\n Column(\"trial_id\", Integer, nullable=False),\n Column(\"config_id\", Integer, nullable=False),\n Column(\"ts_start\", DateTime, nullable=False, default=\"now\"),\n Column(\"ts_end\", DateTime),\n # Should match the text IDs of `mlos_bench.environments.Status` enum:\n Column(\"status\", String(16), nullable=False),\n\n PrimaryKeyConstraint(\"exp_id\", \"trial_id\"),\n ForeignKeyConstraint([\"exp_id\"], [self.experiment.c.exp_id]),\n ForeignKeyConstraint([\"config_id\"], [self.config.c.config_id]),\n )\n\n # Values of the tunable parameters of the experiment,\n # fixed for a particular trial config.\n self.config_param = Table(\n \"config_param\",\n self._meta,\n Column(\"config_id\", Integer, nullable=False),\n Column(\"param_id\", String(255), nullable=False),\n Column(\"param_value\", String(255)),\n\n PrimaryKeyConstraint(\"config_id\", \"param_id\"),\n ForeignKeyConstraint([\"config_id\"], [self.config.c.config_id]),\n )\n\n # Values of additional non-tunable parameters of the trial,\n # e.g., scheduled execution time, VM name / location, number of repeats, etc.\n self.trial_param = Table(\n \"trial_param\",\n self._meta,\n Column(\"exp_id\", String(255), nullable=False),\n Column(\"trial_id\", Integer, nullable=False),\n Column(\"param_id\", String(255), nullable=False),\n Column(\"param_value\", String(255)),\n\n PrimaryKeyConstraint(\"exp_id\", \"trial_id\", \"param_id\"),\n ForeignKeyConstraint([\"exp_id\", \"trial_id\"],\n [self.trial.c.exp_id, self.trial.c.trial_id]),\n )\n\n self.trial_result = Table(\n \"trial_result\",\n self._meta,\n Column(\"exp_id\", String(255), nullable=False),\n Column(\"trial_id\", Integer, nullable=False),\n Column(\"metric_id\", String(255), nullable=False),\n Column(\"metric_value\", String(255)),\n\n PrimaryKeyConstraint(\"exp_id\", \"trial_id\", \"metric_id\"),\n ForeignKeyConstraint([\"exp_id\", \"trial_id\"],\n [self.trial.c.exp_id, self.trial.c.trial_id]),\n )\n\n self.trial_telemetry = Table(\n \"trial_telemetry\",\n self._meta,\n Column(\"exp_id\", String(255), nullable=False),\n Column(\"trial_id\", Integer, nullable=False),\n Column(\"ts\", DateTime, nullable=False, default=\"now\"),\n Column(\"metric_id\", String(255), nullable=False),\n Column(\"metric_value\", String(255)),\n\n UniqueConstraint(\"exp_id\", \"trial_id\", \"ts\", \"metric_id\"),\n ForeignKeyConstraint([\"exp_id\", \"trial_id\"],\n [self.trial.c.exp_id, self.trial.c.trial_id]),\n )\n\n _LOG.debug(\"Schema: %s\", self._meta)\n\n def create(self) -> 'DbSchema':\n \"\"\"\n Create the DB schema.\n \"\"\"\n _LOG.info(\"Create the DB schema\")\n self._meta.create_all(self._engine)\n return self\n\n def __repr__(self) -> str:\n \"\"\"\n Produce a string with all SQL statements required to create the schema\n from scratch in current SQL dialect.\n\n That is, return a collection of CREATE TABLE statements and such.\n NOTE: this method is quite heavy! We use it only once at startup\n to log the schema, and if the logging level is set to DEBUG.\n\n Returns\n -------\n sql : str\n A multi-line string with SQL statements to create the DB schema from scratch.\n \"\"\"\n ddl = _DDL(self._engine.dialect)\n mock_engine = create_mock_engine(self._engine.url, executor=ddl)\n self._meta.create_all(mock_engine, checkfirst=False)\n return str(ddl)\n" }, { "alpha_fraction": 0.5228855609893799, "alphanum_fraction": 0.524129331111908, "avg_line_length": 39.60606002807617, "blob_id": "e144fb59f0b3838fb4ae0d8da375fb6c2d5dd8e9", "content_id": "5caa9649cec81f09288565f9a38187c319348201", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4020, "license_type": "permissive", "max_line_length": 97, "num_lines": 99, "path": "/mlos_bench/mlos_bench/storage/sql/trial.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nSaving and updating benchmark data using SQLAlchemy backend.\n\"\"\"\n\nimport logging\nfrom datetime import datetime\nfrom typing import List, Optional, Tuple, Union, Dict, Any\n\nfrom sqlalchemy import Engine\nfrom sqlalchemy.exc import IntegrityError\n\nfrom mlos_bench.environments.status import Status\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\nfrom mlos_bench.storage.base_storage import Storage\nfrom mlos_bench.storage.sql.schema import DbSchema\n\n_LOG = logging.getLogger(__name__)\n\n\nclass Trial(Storage.Trial):\n \"\"\"\n Store the results of a single run of the experiment in SQL database.\n \"\"\"\n\n def __init__(self, *,\n engine: Engine, schema: DbSchema, tunables: TunableGroups,\n experiment_id: str, trial_id: int, config_id: int,\n opt_target: str, config: Optional[Dict[str, Any]] = None):\n super().__init__(\n tunables=tunables,\n experiment_id=experiment_id,\n trial_id=trial_id,\n config_id=config_id,\n opt_target=opt_target,\n config=config,\n )\n self._engine = engine\n self._schema = schema\n\n def update(self, status: Status, timestamp: datetime,\n metrics: Optional[Union[Dict[str, float], float]] = None\n ) -> Optional[Dict[str, float]]:\n metrics = super().update(status, timestamp, metrics)\n with self._engine.begin() as conn:\n try:\n cur_status = conn.execute(\n self._schema.trial.update().where(\n self._schema.trial.c.exp_id == self._experiment_id,\n self._schema.trial.c.trial_id == self._trial_id,\n self._schema.trial.c.status.notin_(\n ['SUCCEEDED', 'CANCELED', 'FAILED', 'TIMED_OUT']),\n ).values(\n status=status.name,\n ts_end=timestamp,\n )\n )\n if cur_status.rowcount not in {1, -1}:\n _LOG.warning(\"Trial %s :: update failed: %s\", self, status)\n raise RuntimeError(\n f\"Failed to update the status of the trial {self} to {status}.\" +\n f\" ({cur_status.rowcount} rows)\")\n if metrics:\n conn.execute(self._schema.trial_result.insert().values([\n {\n \"exp_id\": self._experiment_id,\n \"trial_id\": self._trial_id,\n \"metric_id\": key,\n \"metric_value\": None if val is None else str(val),\n }\n for (key, val) in metrics.items()\n ]))\n except Exception:\n conn.rollback()\n raise\n\n return metrics\n\n def update_telemetry(self, status: Status, metrics: List[Tuple[datetime, str, Any]]) -> None:\n super().update_telemetry(status, metrics)\n # NOTE: Not every SQLAlchemy dialect supports `Insert.on_conflict_do_nothing()`\n # and we need to keep `.update_telemetry()` idempotent; hence a loop instead of\n # a bulk upsert.\n # See Also: comments in <https://github.com/microsoft/MLOS/pull/466>\n for (timestamp, key, val) in metrics:\n with self._engine.begin() as conn:\n try:\n conn.execute(self._schema.trial_telemetry.insert().values(\n exp_id=self._experiment_id,\n trial_id=self._trial_id,\n ts=timestamp,\n metric_id=key,\n metric_value=None if val is None else str(val),\n ))\n except IntegrityError as ex:\n _LOG.warning(\"Record already exists: %s :: %s\", (timestamp, key, val), ex)\n" }, { "alpha_fraction": 0.5987384915351868, "alphanum_fraction": 0.603347897529602, "avg_line_length": 36.135135650634766, "blob_id": "421d825a512b353297478dc1db8ca0c3e0531d09", "content_id": "a730e4d0fcf62497a21119b0cfc6a86cbbeb8afa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4122, "license_type": "permissive", "max_line_length": 89, "num_lines": 111, "path": "/mlos_bench/mlos_bench/environments/mock_env.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nScheduler-side environment to mock the benchmark results.\n\"\"\"\n\nimport random\nimport logging\nfrom typing import Dict, Optional, Tuple\n\nimport numpy\n\nfrom mlos_bench.services.base_service import Service\nfrom mlos_bench.environments.status import Status\nfrom mlos_bench.environments.base_environment import Environment\nfrom mlos_bench.tunables import Tunable, TunableGroups\n\n_LOG = logging.getLogger(__name__)\n\n\nclass MockEnv(Environment):\n \"\"\"\n Scheduler-side environment to mock the benchmark results.\n \"\"\"\n\n _NOISE_VAR = 0.2\n \"\"\"Variance of the Gaussian noise added to the benchmark value.\"\"\"\n\n def __init__(self,\n *,\n name: str,\n config: dict,\n global_config: Optional[dict] = None,\n tunables: Optional[TunableGroups] = None,\n service: Optional[Service] = None):\n \"\"\"\n Create a new environment that produces mock benchmark data.\n\n Parameters\n ----------\n name: str\n Human-readable name of the environment.\n config : dict\n Free-format dictionary that contains the benchmark environment configuration.\n global_config : dict\n Free-format dictionary of global parameters (e.g., security credentials)\n to be mixed in into the \"const_args\" section of the local config.\n Optional arguments are `seed`, `range`, and `metrics`.\n tunables : TunableGroups\n A collection of tunable parameters for *all* environments.\n service: Service\n An optional service object. Not used by this class.\n \"\"\"\n super().__init__(name=name, config=config, global_config=global_config,\n tunables=tunables, service=service)\n seed = self.config.get(\"seed\")\n self._random = random.Random(seed) if seed is not None else None\n self._range = self.config.get(\"range\")\n self._metrics = self.config.get(\"metrics\", [\"score\"])\n self._is_ready = True\n\n def run(self) -> Tuple[Status, Optional[Dict[str, float]]]:\n \"\"\"\n Produce mock benchmark data for one experiment.\n\n Returns\n -------\n (status, output) : (Status, dict)\n A pair of (Status, output) values, where `output` is a dict\n with the results or None if the status is not COMPLETED.\n The keys of the `output` dict are the names of the metrics\n specified in the config; by default it's just one metric\n named \"score\". All output metrics have the same value.\n \"\"\"\n (status, _) = result = super().run()\n if not status.is_ready():\n return result\n\n # Simple convex function of all tunable parameters.\n score = numpy.mean(numpy.square([\n self._normalized(tunable) for (tunable, _group) in self._tunable_params\n ]))\n\n # Add noise and shift the benchmark value from [0, 1] to a given range.\n noise = self._random.gauss(0, self._NOISE_VAR) if self._random else 0\n score = numpy.clip(score + noise, 0, 1)\n if self._range:\n score = self._range[0] + score * (self._range[1] - self._range[0])\n\n return (Status.SUCCEEDED, {metric: score for metric in self._metrics})\n\n @staticmethod\n def _normalized(tunable: Tunable) -> float:\n \"\"\"\n Get the NORMALIZED value of a tunable.\n That is, map current value to the [0, 1] range.\n \"\"\"\n val = None\n if tunable.is_categorical:\n val = (tunable.categories.index(tunable.category) /\n float(len(tunable.categories) - 1))\n elif tunable.is_numerical:\n val = ((tunable.numerical_value - tunable.range[0]) /\n float(tunable.range[1] - tunable.range[0]))\n else:\n raise ValueError(\"Invalid parameter type: \" + tunable.type)\n # Explicitly clip the value in case of numerical errors.\n ret: float = numpy.clip(val, 0, 1)\n return ret\n" }, { "alpha_fraction": 0.7164835333824158, "alphanum_fraction": 0.7186813354492188, "avg_line_length": 36.295082092285156, "blob_id": "8ebfc255c018765ed3af3e2f28931aba0987d339", "content_id": "dc6b10703b0a0f1aa30bcafbdf153e86cb12010f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2275, "license_type": "permissive", "max_line_length": 112, "num_lines": 61, "path": "/mlos_core/mlos_core/spaces/converters/flaml.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nContains space converters for FLAML.\n\"\"\"\n\nfrom typing import Dict\n\nimport sys\n\nimport ConfigSpace\nimport numpy as np\n\nimport flaml.tune\nimport flaml.tune.sample\n\nif sys.version_info >= (3, 10):\n from typing import TypeAlias\nelse:\n from typing_extensions import TypeAlias\n\n\nFlamlDomain: TypeAlias = flaml.tune.sample.Domain\nFlamlSpace: TypeAlias = Dict[str, flaml.tune.sample.Domain]\n\n\ndef configspace_to_flaml_space(config_space: ConfigSpace.ConfigurationSpace) -> Dict[str, FlamlDomain]:\n \"\"\"Converts a ConfigSpace.ConfigurationSpace to dict.\n\n Parameters\n ----------\n config_space : ConfigSpace.ConfigurationSpace\n Input configuration space.\n\n Returns\n -------\n flaml_space : dict\n A dictionary of flaml.tune.sample.Domain objects keyed by parameter name.\n \"\"\"\n flaml_numeric_type = {\n (ConfigSpace.UniformIntegerHyperparameter, False): flaml.tune.randint,\n (ConfigSpace.UniformIntegerHyperparameter, True): flaml.tune.lograndint,\n (ConfigSpace.UniformFloatHyperparameter, False): flaml.tune.uniform,\n (ConfigSpace.UniformFloatHyperparameter, True): flaml.tune.loguniform,\n }\n\n def _one_parameter_convert(parameter: ConfigSpace.hyperparameters.Hyperparameter) -> FlamlDomain:\n if isinstance(parameter, ConfigSpace.UniformFloatHyperparameter):\n # FIXME: upper isn't included in the range\n return flaml_numeric_type[(type(parameter), parameter.log)](parameter.lower, parameter.upper)\n elif isinstance(parameter, ConfigSpace.UniformIntegerHyperparameter):\n return flaml_numeric_type[(type(parameter), parameter.log)](parameter.lower, parameter.upper + 1)\n elif isinstance(parameter, ConfigSpace.CategoricalHyperparameter):\n if len(np.unique(parameter.probabilities)) > 1:\n raise ValueError(\"FLAML doesn't support categorical parameters with non-uniform probabilities.\")\n return flaml.tune.choice(parameter.choices) # TODO: set order?\n raise ValueError(f\"Type of parameter {parameter} ({type(parameter)}) not supported.\")\n\n return {param.name: _one_parameter_convert(param) for param in config_space.values()}\n" }, { "alpha_fraction": 0.7462526559829712, "alphanum_fraction": 0.7462526559829712, "avg_line_length": 28.1875, "blob_id": "69a2d9e1373e89be35375bdd54e1f02f7f015e66", "content_id": "7678796be90c3d4da241b28cf890a95943bd75b1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 934, "license_type": "permissive", "max_line_length": 97, "num_lines": 32, "path": "/mlos_bench/mlos_bench/tests/config/schemas/globals/test_globals_schemas.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTests for CLI schema validation.\n\"\"\"\n\nfrom os import path\n\nimport pytest\n\nfrom mlos_bench.config.schemas import ConfigSchema\n\nfrom mlos_bench.tests.config.schemas import get_schema_test_cases, check_test_case_against_schema\n\n\n# General testing strategy:\n# - hand code a set of good/bad configs (useful to test editor schema checking)\n# - for each config, load and validate against expected schema\n\nTEST_CASES = get_schema_test_cases(path.join(path.dirname(__file__), \"test-cases\"))\n\n\n# Now we actually perform all of those validation tests.\n\[email protected](\"test_case_name\", sorted(TEST_CASES.by_path))\ndef test_globals_configs_against_schema(test_case_name: str) -> None:\n \"\"\"\n Checks that the CLI config validates against the schema.\n \"\"\"\n check_test_case_against_schema(TEST_CASES.by_path[test_case_name], ConfigSchema.GLOBALS)\n" }, { "alpha_fraction": 0.5585390329360962, "alphanum_fraction": 0.5620598793029785, "avg_line_length": 35.55728530883789, "blob_id": "7f9539c7e08f6e2600c82cc59433c21105eed35b", "content_id": "5dd5349ecc3faab9b069b6c91e1684c0e6707d27", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 25846, "license_type": "permissive", "max_line_length": 100, "num_lines": 707, "path": "/mlos_bench/mlos_bench/services/remote/azure/azure_services.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nA collection Service functions for managing VMs on Azure.\n\"\"\"\n\nimport json\nimport time\nimport logging\n\nfrom typing import Any, Callable, Dict, Iterable, Optional, Tuple\n\nimport requests\n\nfrom mlos_bench.environments.status import Status\nfrom mlos_bench.services.base_service import Service\nfrom mlos_bench.services.types.authenticator_type import SupportsAuth\nfrom mlos_bench.services.types.remote_exec_type import SupportsRemoteExec\nfrom mlos_bench.services.types.vm_provisioner_type import SupportsVMOps\nfrom mlos_bench.util import check_required_params, merge_parameters\n\n_LOG = logging.getLogger(__name__)\n\n\nclass AzureVMService(Service, SupportsVMOps, SupportsRemoteExec):\n \"\"\"\n Helper methods to manage VMs on Azure.\n \"\"\"\n\n _POLL_INTERVAL = 4 # seconds\n _POLL_TIMEOUT = 300 # seconds\n _REQUEST_TIMEOUT = 5 # seconds\n\n # Azure Resources Deployment REST API as described in\n # https://docs.microsoft.com/en-us/rest/api/resources/deployments\n\n _URL_DEPLOY = (\n \"https://management.azure.com\" +\n \"/subscriptions/{subscription}\" +\n \"/resourceGroups/{resource_group}\" +\n \"/providers/Microsoft.Resources\" +\n \"/deployments/{deployment_name}\" +\n \"?api-version=2022-05-01\"\n )\n\n # Azure Compute REST API calls as described in\n # https://docs.microsoft.com/en-us/rest/api/compute/virtual-machines\n\n # From: https://docs.microsoft.com/en-us/rest/api/compute/virtual-machines/start\n _URL_START = (\n \"https://management.azure.com\" +\n \"/subscriptions/{subscription}\" +\n \"/resourceGroups/{resource_group}\" +\n \"/providers/Microsoft.Compute\" +\n \"/virtualMachines/{vm_name}\" +\n \"/start\" +\n \"?api-version=2022-03-01\"\n )\n\n # From: https://docs.microsoft.com/en-us/rest/api/compute/virtual-machines/power-off\n _URL_STOP = (\n \"https://management.azure.com\" +\n \"/subscriptions/{subscription}\" +\n \"/resourceGroups/{resource_group}\" +\n \"/providers/Microsoft.Compute\" +\n \"/virtualMachines/{vm_name}\" +\n \"/powerOff\" +\n \"?api-version=2022-03-01\"\n )\n\n # From: https://docs.microsoft.com/en-us/rest/api/compute/virtual-machines/deallocate\n _URL_DEPROVISION = (\n \"https://management.azure.com\" +\n \"/subscriptions/{subscription}\" +\n \"/resourceGroups/{resource_group}\" +\n \"/providers/Microsoft.Compute\" +\n \"/virtualMachines/{vm_name}\" +\n \"/deallocate\" +\n \"?api-version=2022-03-01\"\n )\n\n # From: https://docs.microsoft.com/en-us/rest/api/compute/virtual-machines/restart\n _URL_REBOOT = (\n \"https://management.azure.com\" +\n \"/subscriptions/{subscription}\" +\n \"/resourceGroups/{resource_group}\" +\n \"/providers/Microsoft.Compute\" +\n \"/virtualMachines/{vm_name}\" +\n \"/restart\" +\n \"?api-version=2022-03-01\"\n )\n\n # From: https://docs.microsoft.com/en-us/rest/api/compute/virtual-machines/run-command\n _URL_REXEC_RUN = (\n \"https://management.azure.com\" +\n \"/subscriptions/{subscription}\" +\n \"/resourceGroups/{resource_group}\" +\n \"/providers/Microsoft.Compute\" +\n \"/virtualMachines/{vm_name}\" +\n \"/runCommand\" +\n \"?api-version=2022-03-01\"\n )\n\n def __init__(self,\n config: Optional[Dict[str, Any]] = None,\n global_config: Optional[Dict[str, Any]] = None,\n parent: Optional[Service] = None):\n \"\"\"\n Create a new instance of Azure services proxy.\n\n Parameters\n ----------\n config : dict\n Free-format dictionary that contains the benchmark environment\n configuration.\n global_config : dict\n Free-format dictionary of global parameters.\n parent : Service\n Parent service that can provide mixin functions.\n \"\"\"\n super().__init__(config, global_config, parent)\n\n check_required_params(\n self.config, {\n \"subscription\",\n \"resourceGroup\",\n \"deploymentName\",\n \"deploymentTemplatePath\",\n \"deploymentTemplateParameters\",\n }\n )\n\n # Register methods that we want to expose to the Environment objects.\n self.register([\n self.wait_vm_deployment,\n self.wait_vm_operation,\n self.vm_provision,\n self.vm_start,\n self.vm_stop,\n self.vm_deprovision,\n self.vm_restart,\n self.remote_exec,\n self.get_remote_exec_results,\n ])\n\n # These parameters can come from command line as strings, so conversion is needed.\n self._poll_interval = float(self.config.get(\"pollInterval\", self._POLL_INTERVAL))\n self._poll_timeout = float(self.config.get(\"pollTimeout\", self._POLL_TIMEOUT))\n self._request_timeout = float(self.config.get(\"requestTimeout\", self._REQUEST_TIMEOUT))\n\n # TODO: Provide external schema validation?\n template = self.config_loader_service.load_config(\n self.config['deploymentTemplatePath'], schema_type=None)\n assert template is not None and isinstance(template, dict)\n self._deploy_template = template\n\n self._deploy_params = merge_parameters(\n dest=self.config['deploymentTemplateParameters'].copy(), source=global_config)\n\n def _get_headers(self) -> dict:\n \"\"\"\n Get the headers for the REST API calls.\n \"\"\"\n assert self._parent is not None and isinstance(self._parent, SupportsAuth), \\\n \"Authorization service not provided. Include service-auth.jsonc?\"\n return {\"Authorization\": \"Bearer \" + self._parent.get_access_token()}\n\n @staticmethod\n def _extract_arm_parameters(json_data: dict) -> dict:\n \"\"\"\n Extract parameters from the ARM Template REST response JSON.\n\n Returns\n -------\n parameters : dict\n Flat dictionary of parameters and their values.\n \"\"\"\n return {\n key: val.get(\"value\")\n for (key, val) in json_data.get(\"properties\", {}).get(\"parameters\", {}).items()\n if val.get(\"value\") is not None\n }\n\n def _azure_vm_post_helper(self, params: dict, url: str) -> Tuple[Status, dict]:\n \"\"\"\n General pattern for performing an action on an Azure VM via its REST API.\n\n Parameters\n ----------\n params: dict\n Flat dictionary of (key, value) pairs of tunable parameters.\n url: str\n REST API url for the target to perform on the Azure VM.\n Should be a url that we intend to POST to.\n\n Returns\n -------\n result : (Status, dict={})\n A pair of Status and result.\n Status is one of {PENDING, SUCCEEDED, FAILED}\n Result will have a value for 'asyncResultsUrl' if status is PENDING,\n and 'pollInterval' if suggested by the API.\n \"\"\"\n _LOG.debug(\"Request: POST %s\", url)\n\n response = requests.post(url, headers=self._get_headers(), timeout=self._request_timeout)\n _LOG.debug(\"Response: %s\", response)\n\n # Logical flow for async operations based on:\n # https://docs.microsoft.com/en-us/azure/azure-resource-manager/management/async-operations\n if response.status_code == 200:\n return (Status.SUCCEEDED, params.copy())\n elif response.status_code == 202:\n result = params.copy()\n if \"Azure-AsyncOperation\" in response.headers:\n result[\"asyncResultsUrl\"] = response.headers.get(\"Azure-AsyncOperation\")\n elif \"Location\" in response.headers:\n result[\"asyncResultsUrl\"] = response.headers.get(\"Location\")\n if \"Retry-After\" in response.headers:\n result[\"pollInterval\"] = float(response.headers[\"Retry-After\"])\n\n return (Status.PENDING, result)\n else:\n _LOG.error(\"Response: %s :: %s\", response, response.text)\n # _LOG.error(\"Bad Request:\\n%s\", response.request.body)\n return (Status.FAILED, {})\n\n def _check_vm_operation_status(self, params: dict) -> Tuple[Status, dict]:\n \"\"\"\n Checks the status of a pending operation on an Azure VM.\n\n Parameters\n ----------\n params: dict\n Flat dictionary of (key, value) pairs of tunable parameters.\n Must have the \"asyncResultsUrl\" key to get the results.\n If the key is not present, return Status.PENDING.\n\n Returns\n -------\n result : (Status, dict)\n A pair of Status and result.\n Status is one of {PENDING, RUNNING, SUCCEEDED, FAILED}\n Result is info on the operation runtime if SUCCEEDED, otherwise {}.\n \"\"\"\n url = params.get(\"asyncResultsUrl\")\n if url is None:\n return Status.PENDING, {}\n\n try:\n response = requests.get(url, headers=self._get_headers(), timeout=self._request_timeout)\n except requests.exceptions.ReadTimeout:\n _LOG.warning(\"Request timed out: %s\", url)\n # return Status.TIMED_OUT, {}\n return Status.RUNNING, {}\n\n if _LOG.isEnabledFor(logging.DEBUG):\n _LOG.debug(\"Response: %s\\n%s\", response,\n json.dumps(response.json(), indent=2)\n if response.content else \"\")\n\n if response.status_code == 200:\n output = response.json()\n status = output.get(\"status\")\n if status == \"InProgress\":\n return Status.RUNNING, {}\n elif status == \"Succeeded\":\n return Status.SUCCEEDED, output\n\n _LOG.error(\"Response: %s :: %s\", response, response.text)\n return Status.FAILED, {}\n\n def wait_vm_deployment(self, is_setup: bool, params: dict) -> Tuple[Status, dict]:\n \"\"\"\n Waits for a pending operation on an Azure VM to resolve to SUCCEEDED or FAILED.\n Return TIMED_OUT when timing out.\n\n Parameters\n ----------\n is_setup : bool\n If True, wait for VM being deployed; otherwise, wait for successful deprovisioning.\n params : dict\n Flat dictionary of (key, value) pairs of tunable parameters.\n\n Returns\n -------\n result : (Status, dict)\n A pair of Status and result.\n Status is one of {PENDING, SUCCEEDED, FAILED, TIMED_OUT}\n Result is info on the operation runtime if SUCCEEDED, otherwise {}.\n \"\"\"\n _LOG.info(\"Wait for %s to %s\", params[\"deploymentName\"],\n \"provision\" if is_setup else \"deprovision\")\n return self._wait_while(self._check_deployment, Status.PENDING, params)\n\n def wait_vm_operation(self, params: dict) -> Tuple[Status, dict]:\n \"\"\"\n Waits for a pending operation on an Azure VM to resolve to SUCCEEDED or FAILED.\n Return TIMED_OUT when timing out.\n\n Parameters\n ----------\n params: dict\n Flat dictionary of (key, value) pairs of tunable parameters.\n Must have the \"asyncResultsUrl\" key to get the results.\n If the key is not present, return Status.PENDING.\n\n Returns\n -------\n result : (Status, dict)\n A pair of Status and result.\n Status is one of {PENDING, SUCCEEDED, FAILED, TIMED_OUT}\n Result is info on the operation runtime if SUCCEEDED, otherwise {}.\n \"\"\"\n _LOG.info(\"Wait for operation on VM %s\", params[\"vmName\"])\n return self._wait_while(self._check_vm_operation_status, Status.RUNNING, params)\n\n def _wait_while(self, func: Callable[[dict], Tuple[Status, dict]],\n loop_status: Status, params: dict) -> Tuple[Status, dict]:\n \"\"\"\n Invoke `func` periodically while the status is equal to `loop_status`.\n Return TIMED_OUT when timing out.\n\n Parameters\n ----------\n func : a function\n A function that takes `params` and returns a pair of (Status, {})\n loop_status: Status\n Steady state status - keep polling `func` while it returns `loop_status`.\n params : dict\n Flat dictionary of (key, value) pairs of tunable parameters.\n\n Returns\n -------\n result : (Status, dict)\n A pair of Status and result.\n \"\"\"\n config = merge_parameters(\n dest=self.config.copy(), source=params, required_keys=[\"deploymentName\"])\n\n poll_period = params.get(\"pollInterval\", self._poll_interval)\n\n _LOG.debug(\"Wait for %s status %s :: poll %.2f timeout %d s\",\n config[\"deploymentName\"], loop_status, poll_period, self._poll_timeout)\n\n ts_timeout = time.time() + self._poll_timeout\n poll_delay = poll_period\n while True:\n # Wait for the suggested time first then check status\n ts_start = time.time()\n if ts_start >= ts_timeout:\n break\n\n if poll_delay > 0:\n _LOG.debug(\"Sleep for: %.2f of %.2f s\", poll_delay, poll_period)\n time.sleep(poll_delay)\n\n (status, output) = func(params)\n if status != loop_status:\n return status, output\n\n ts_end = time.time()\n poll_delay = poll_period - ts_end + ts_start\n\n _LOG.warning(\"Request timed out: %s\", params)\n return (Status.TIMED_OUT, {})\n\n def _check_deployment(self, params: dict) -> Tuple[Status, dict]:\n \"\"\"\n Check if Azure deployment exists.\n Return SUCCEEDED if true, PENDING otherwise.\n\n Parameters\n ----------\n _params : dict\n Flat dictionary of (key, value) pairs of tunable parameters.\n This parameter is not used; we need it for compatibility with\n other polling functions used in `_wait_while()`.\n\n Returns\n -------\n result : (Status, dict={})\n A pair of Status and result. The result is always {}.\n Status is one of {SUCCEEDED, PENDING, FAILED}\n \"\"\"\n config = merge_parameters(\n dest=self.config.copy(),\n source=params,\n required_keys=[\n \"subscription\",\n \"resourceGroup\",\n \"deploymentName\",\n ]\n )\n\n _LOG.info(\"Check deployment: %s\", config[\"deploymentName\"])\n\n url = self._URL_DEPLOY.format(\n subscription=config[\"subscription\"],\n resource_group=config[\"resourceGroup\"],\n deployment_name=config[\"deploymentName\"],\n )\n\n response = requests.head(url, headers=self._get_headers(), timeout=self._request_timeout)\n _LOG.debug(\"Response: %s\", response)\n\n if response.status_code == 204:\n return (Status.SUCCEEDED, {})\n elif response.status_code == 404:\n return (Status.PENDING, {})\n\n _LOG.error(\"Response: %s :: %s\", response, response.text)\n return (Status.FAILED, {})\n\n def vm_provision(self, params: dict) -> Tuple[Status, dict]:\n \"\"\"\n Check if Azure VM is ready. Deploy a new VM, if necessary.\n\n Parameters\n ----------\n params : dict\n Flat dictionary of (key, value) pairs of tunable parameters.\n VMEnv tunables are variable parameters that, together with the\n VMEnv configuration, are sufficient to provision a VM.\n\n Returns\n -------\n result : (Status, dict={})\n A pair of Status and result. The result is the input `params` plus the\n parameters extracted from the response JSON, or {} if the status is FAILED.\n Status is one of {PENDING, SUCCEEDED, FAILED}\n \"\"\"\n config = merge_parameters(dest=self.config.copy(), source=params)\n _LOG.info(\"Deploy: %s :: %s\", config[\"deploymentName\"], params)\n\n params = merge_parameters(dest=self._deploy_params.copy(), source=params)\n if _LOG.isEnabledFor(logging.DEBUG):\n _LOG.debug(\"Deploy: %s merged params ::\\n%s\",\n config[\"deploymentName\"], json.dumps(params, indent=2))\n\n url = self._URL_DEPLOY.format(\n subscription=config[\"subscription\"],\n resource_group=config[\"resourceGroup\"],\n deployment_name=config[\"deploymentName\"],\n )\n\n json_req = {\n \"properties\": {\n \"mode\": \"Incremental\",\n \"template\": self._deploy_template,\n \"parameters\": {\n key: {\"value\": val} for (key, val) in params.items()\n if key in self._deploy_template.get(\"parameters\", {})\n }\n }\n }\n\n if _LOG.isEnabledFor(logging.DEBUG):\n _LOG.debug(\"Request: PUT %s\\n%s\", url, json.dumps(json_req, indent=2))\n\n response = requests.put(url, json=json_req,\n headers=self._get_headers(), timeout=self._request_timeout)\n\n if _LOG.isEnabledFor(logging.DEBUG):\n _LOG.debug(\"Response: %s\\n%s\", response,\n json.dumps(response.json(), indent=2)\n if response.content else \"\")\n else:\n _LOG.info(\"Response: %s\", response)\n\n if response.status_code == 200:\n return (Status.PENDING, config)\n elif response.status_code == 201:\n output = self._extract_arm_parameters(response.json())\n if _LOG.isEnabledFor(logging.DEBUG):\n _LOG.debug(\"Extracted parameters:\\n%s\", json.dumps(output, indent=2))\n params.update(output)\n params.setdefault(\"asyncResultsUrl\", url)\n params.setdefault(\"deploymentName\", config[\"deploymentName\"])\n return (Status.PENDING, params)\n else:\n _LOG.error(\"Response: %s :: %s\", response, response.text)\n # _LOG.error(\"Bad Request:\\n%s\", response.request.body)\n return (Status.FAILED, {})\n\n def vm_start(self, params: dict) -> Tuple[Status, dict]:\n \"\"\"\n Start the VM on Azure.\n\n Parameters\n ----------\n params : dict\n Flat dictionary of (key, value) pairs of tunable parameters.\n\n Returns\n -------\n result : (Status, dict={})\n A pair of Status and result. The result is always {}.\n Status is one of {PENDING, SUCCEEDED, FAILED}\n \"\"\"\n config = merge_parameters(\n dest=self.config.copy(),\n source=params,\n required_keys=[\n \"subscription\",\n \"resourceGroup\",\n \"vmName\",\n ]\n )\n _LOG.info(\"Start VM: %s :: %s\", config[\"vmName\"], params)\n return self._azure_vm_post_helper(config, self._URL_START.format(\n subscription=config[\"subscription\"],\n resource_group=config[\"resourceGroup\"],\n vm_name=config[\"vmName\"],\n ))\n\n def vm_stop(self, params: dict) -> Tuple[Status, dict]:\n \"\"\"\n Stops the VM on Azure by initiating a graceful shutdown.\n\n Parameters\n ----------\n params : dict\n Flat dictionary of (key, value) pairs of tunable parameters.\n\n Returns\n -------\n result : (Status, dict={})\n A pair of Status and result. The result is always {}.\n Status is one of {PENDING, SUCCEEDED, FAILED}\n \"\"\"\n config = merge_parameters(\n dest=self.config.copy(),\n source=params,\n required_keys=[\n \"subscription\",\n \"resourceGroup\",\n \"vmName\",\n ]\n )\n _LOG.info(\"Stop VM: %s\", config[\"vmName\"])\n return self._azure_vm_post_helper(config, self._URL_STOP.format(\n subscription=config[\"subscription\"],\n resource_group=config[\"resourceGroup\"],\n vm_name=config[\"vmName\"],\n ))\n\n def vm_deprovision(self, params: dict) -> Tuple[Status, dict]:\n \"\"\"\n Deallocates the VM on Azure by shutting it down then releasing the compute resources.\n\n Parameters\n ----------\n params : dict\n Flat dictionary of (key, value) pairs of tunable parameters.\n\n Returns\n -------\n result : (Status, dict={})\n A pair of Status and result. The result is always the same as input `params`.\n Status is one of {PENDING, SUCCEEDED, FAILED}\n \"\"\"\n config = merge_parameters(\n dest=self.config.copy(),\n source=params,\n required_keys=[\n \"subscription\",\n \"resourceGroup\",\n \"deploymentName\",\n ]\n )\n _LOG.info(\"Deprovision: %s\", config[\"deploymentName\"])\n # TODO: Properly deprovision all resources specified in the ARM template.\n if \"vmName\" in config:\n return self.vm_stop(params)\n return (Status.SUCCEEDED, config)\n\n def vm_restart(self, params: dict) -> Tuple[Status, dict]:\n \"\"\"\n Reboot the VM on Azure by initiating a graceful shutdown.\n\n Parameters\n ----------\n params : dict\n Flat dictionary of (key, value) pairs of tunable parameters.\n\n Returns\n -------\n result : (Status, dict={})\n A pair of Status and result. The result is always {}.\n Status is one of {PENDING, SUCCEEDED, FAILED}\n \"\"\"\n config = merge_parameters(\n dest=self.config.copy(),\n source=params,\n required_keys=[\n \"subscription\",\n \"resourceGroup\",\n \"vmName\",\n ]\n )\n _LOG.info(\"Reboot VM: %s\", config[\"vmName\"])\n return self._azure_vm_post_helper(config, self._URL_REBOOT.format(\n subscription=config[\"subscription\"],\n resource_group=config[\"resourceGroup\"],\n vm_name=config[\"vmName\"],\n ))\n\n def remote_exec(self, script: Iterable[str], config: dict,\n env_params: dict) -> Tuple[Status, dict]:\n \"\"\"\n Run a command on Azure VM.\n\n Parameters\n ----------\n script : Iterable[str]\n A list of lines to execute as a script on a remote VM.\n config : dict\n Flat dictionary of (key, value) pairs of the Environment parameters.\n They usually come from `const_args` and `tunable_params`\n properties of the Environment.\n env_params : dict\n Parameters to pass as *shell* environment variables into the script.\n This is usually a subset of `config` with some possible conversions.\n\n Returns\n -------\n result : (Status, dict)\n A pair of Status and result.\n Status is one of {PENDING, SUCCEEDED, FAILED}\n \"\"\"\n config = merge_parameters(\n dest=self.config.copy(),\n source=config,\n required_keys=[\n \"subscription\",\n \"resourceGroup\",\n \"vmName\",\n ]\n )\n\n if _LOG.isEnabledFor(logging.INFO):\n _LOG.info(\"Run a script on VM: %s\\n %s\", config[\"vmName\"], \"\\n \".join(script))\n\n json_req = {\n \"commandId\": \"RunShellScript\",\n \"script\": list(script),\n \"parameters\": [{\"name\": key, \"value\": val} for (key, val) in env_params.items()]\n }\n\n url = self._URL_REXEC_RUN.format(\n subscription=config[\"subscription\"],\n resource_group=config[\"resourceGroup\"],\n vm_name=config[\"vmName\"],\n )\n\n if _LOG.isEnabledFor(logging.DEBUG):\n _LOG.debug(\"Request: POST %s\\n%s\", url, json.dumps(json_req, indent=2))\n\n response = requests.post(\n url, json=json_req, headers=self._get_headers(), timeout=self._request_timeout)\n\n if _LOG.isEnabledFor(logging.DEBUG):\n _LOG.debug(\"Response: %s\\n%s\", response,\n json.dumps(response.json(), indent=2)\n if response.content else \"\")\n else:\n _LOG.info(\"Response: %s\", response)\n\n if response.status_code == 200:\n # TODO: extract the results from JSON response\n return (Status.SUCCEEDED, config)\n elif response.status_code == 202:\n return (Status.PENDING, {\n **config,\n \"asyncResultsUrl\": response.headers.get(\"Azure-AsyncOperation\")\n })\n else:\n _LOG.error(\"Response: %s :: %s\", response, response.text)\n # _LOG.error(\"Bad Request:\\n%s\", response.request.body)\n return (Status.FAILED, {})\n\n def get_remote_exec_results(self, config: dict) -> Tuple[Status, dict]:\n \"\"\"\n Get the results of the asynchronously running command.\n\n Parameters\n ----------\n config : dict\n Flat dictionary of (key, value) pairs of tunable parameters.\n Must have the \"asyncResultsUrl\" key to get the results.\n If the key is not present, return Status.PENDING.\n\n Returns\n -------\n result : (Status, dict)\n A pair of Status and result.\n Status is one of {PENDING, SUCCEEDED, FAILED, TIMED_OUT}\n \"\"\"\n _LOG.info(\"Check the results on VM: %s\", config.get(\"vmName\"))\n (status, result) = self.wait_vm_operation(config)\n if status.is_succeeded():\n return (status, result.get(\"properties\", {}).get(\"output\", {}))\n else:\n return (status, result)\n" }, { "alpha_fraction": 0.6426116824150085, "alphanum_fraction": 0.6426116824150085, "avg_line_length": 13.550000190734863, "blob_id": "4f3ba742fd993968ef94ea8ddc5907fdb2fb5345", "content_id": "71acc5df9f0435ec88f7434ba94926f23a0fd9b8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 291, "license_type": "permissive", "max_line_length": 38, "num_lines": 20, "path": "/doc/source/_templates/numpydoc_docstring.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n{{index}}\n{{summary}}\n{{extended_summary}}\n{{parameters}}\n{{returns}}\n{{yields}}\n{{other_parameters}}\n{{attributes}}\n{{raises}}\n{{warns}}\n{{warnings}}\n{{see_also}}\n{{notes}}\n{{references}}\n{{examples}}\n{{methods}}\n" }, { "alpha_fraction": 0.5272002220153809, "alphanum_fraction": 0.5278648138046265, "avg_line_length": 43.44303894042969, "blob_id": "0c891d6f5005db8d0055e9ff179569ef0504a804", "content_id": "8a271a955626beed09eab7b8adbc941608a55831", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10533, "license_type": "permissive", "max_line_length": 111, "num_lines": 237, "path": "/mlos_bench/mlos_bench/storage/sql/experiment.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nSaving and restoring the benchmark data using SQLAlchemy.\n\"\"\"\n\nimport logging\nimport hashlib\nfrom datetime import datetime\nfrom typing import Optional, Tuple, List, Dict, Iterator, Any\n\nfrom sqlalchemy import Engine, Connection, Table, column, func\n\nfrom mlos_bench.environments.status import Status\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\nfrom mlos_bench.storage.base_storage import Storage\nfrom mlos_bench.storage.sql.schema import DbSchema\nfrom mlos_bench.storage.sql.trial import Trial\n\n_LOG = logging.getLogger(__name__)\n\n\nclass Experiment(Storage.Experiment):\n \"\"\"\n Logic for retrieving and storing the results of a single experiment.\n \"\"\"\n\n def __init__(self, *,\n engine: Engine,\n schema: DbSchema,\n tunables: TunableGroups,\n experiment_id: str,\n trial_id: int,\n root_env_config: str,\n description: str,\n opt_target: str):\n super().__init__(tunables, experiment_id, root_env_config)\n self._engine = engine\n self._schema = schema\n self._trial_id = trial_id\n self._description = description\n self._opt_target = opt_target\n\n def _setup(self) -> None:\n super()._setup()\n with self._engine.begin() as conn:\n # Get git info and the last trial ID for the experiment.\n # pylint: disable=not-callable\n exp_info = conn.execute(\n self._schema.experiment.select().with_only_columns(\n self._schema.experiment.c.git_repo,\n self._schema.experiment.c.git_commit,\n self._schema.experiment.c.root_env_config,\n func.max(self._schema.trial.c.trial_id).label(\"trial_id\"),\n ).join(\n self._schema.trial,\n self._schema.trial.c.exp_id == self._schema.experiment.c.exp_id,\n isouter=True\n ).where(\n self._schema.experiment.c.exp_id == self._experiment_id,\n ).group_by(\n self._schema.experiment.c.git_repo,\n self._schema.experiment.c.git_commit,\n self._schema.experiment.c.root_env_config,\n )\n ).fetchone()\n if exp_info is None:\n _LOG.info(\"Start new experiment: %s\", self._experiment_id)\n # It's a new experiment: create a record for it in the database.\n conn.execute(self._schema.experiment.insert().values(\n exp_id=self._experiment_id,\n description=self._description,\n git_repo=self._git_repo,\n git_commit=self._git_commit,\n root_env_config=self._root_env_config,\n ))\n else:\n if exp_info.trial_id is not None:\n self._trial_id = exp_info.trial_id + 1\n _LOG.info(\"Continue experiment: %s last trial: %s resume from: %d\",\n self._experiment_id, exp_info.trial_id, self._trial_id)\n if exp_info.git_commit != self._git_commit:\n _LOG.warning(\"Experiment %s git expected: %s %s\",\n self, exp_info.git_repo, exp_info.git_commit)\n\n def merge(self, experiment_ids: List[str]) -> None:\n _LOG.info(\"Merge: %s <- %s\", self._experiment_id, experiment_ids)\n raise NotImplementedError()\n\n def load_config(self, config_id: int) -> Dict[str, Any]:\n with self._engine.connect() as conn:\n return self._get_params(conn, self._schema.config_param, config_id=config_id)\n\n def load_telemetry(self, trial_id: int) -> List[Tuple[datetime, str, Any]]:\n with self._engine.connect() as conn:\n cur_telemetry = conn.execute(\n self._schema.trial_telemetry.select().where(\n self._schema.trial_telemetry.c.exp_id == self._experiment_id,\n self._schema.trial_telemetry.c.trial_id == trial_id\n ).order_by(\n self._schema.trial_telemetry.c.ts,\n self._schema.trial_telemetry.c.metric_id,\n )\n )\n return [(row.ts, row.metric_id, row.metric_value)\n for row in cur_telemetry.fetchall()]\n\n def load(self, opt_target: Optional[str] = None) -> Tuple[List[dict], List[Optional[float]], List[Status]]:\n opt_target = opt_target or self._opt_target\n (configs, scores, status) = ([], [], [])\n with self._engine.connect() as conn:\n cur_trials = conn.execute(\n self._schema.trial.select().with_only_columns(\n self._schema.trial.c.trial_id,\n self._schema.trial.c.config_id,\n self._schema.trial.c.status,\n self._schema.trial_result.c.metric_value,\n ).join(\n self._schema.trial_result, (\n (self._schema.trial.c.exp_id == self._schema.trial_result.c.exp_id) &\n (self._schema.trial.c.trial_id == self._schema.trial_result.c.trial_id)\n ), isouter=True\n ).where(\n self._schema.trial.c.exp_id == self._experiment_id,\n self._schema.trial.c.status.in_(['SUCCEEDED', 'FAILED', 'TIMED_OUT']),\n (self._schema.trial_result.c.metric_id.is_(None) |\n (self._schema.trial_result.c.metric_id == opt_target)),\n ).order_by(\n self._schema.trial.c.trial_id.asc(),\n )\n )\n for trial in cur_trials.fetchall():\n tunables = self._get_params(\n conn, self._schema.config_param, config_id=trial.config_id)\n configs.append(tunables)\n scores.append(None if trial.metric_value is None else float(trial.metric_value))\n status.append(Status[trial.status])\n return (configs, scores, status)\n\n @staticmethod\n def _get_params(conn: Connection, table: Table, **kwargs: Any) -> Dict[str, Any]:\n cur_params = conn.execute(table.select().where(*[\n column(key) == val for (key, val) in kwargs.items()]))\n return {row.param_id: row.param_value for row in cur_params.fetchall()}\n\n @staticmethod\n def _save_params(conn: Connection, table: Table,\n params: Dict[str, Any], **kwargs: Any) -> None:\n conn.execute(table.insert(), [\n {\n **kwargs,\n \"param_id\": key,\n \"param_value\": None if val is None else str(val)\n }\n for (key, val) in params.items()\n ])\n\n def pending_trials(self) -> Iterator[Storage.Trial]:\n _LOG.info(\"Retrieve pending trials for: %s\", self._experiment_id)\n with self._engine.connect() as conn:\n cur_trials = conn.execute(self._schema.trial.select().where(\n self._schema.trial.c.exp_id == self._experiment_id,\n self._schema.trial.c.ts_end.is_(None)\n ))\n for trial in cur_trials.fetchall():\n tunables = self._get_params(\n conn, self._schema.config_param,\n config_id=trial.config_id)\n config = self._get_params(\n conn, self._schema.trial_param,\n exp_id=self._experiment_id, trial_id=trial.trial_id)\n yield Trial(\n engine=self._engine,\n schema=self._schema,\n # Reset .is_updated flag after the assignment:\n tunables=self._tunables.copy().assign(tunables).reset(),\n experiment_id=self._experiment_id,\n trial_id=trial.trial_id,\n config_id=trial.config_id,\n opt_target=self._opt_target,\n config=config,\n )\n\n def _get_config_id(self, conn: Connection, tunables: TunableGroups) -> int:\n \"\"\"\n Get the config ID for the given tunables. If the config does not exist,\n create a new record for it.\n \"\"\"\n config_hash = hashlib.sha256(str(tunables).encode('utf-8')).hexdigest()\n cur_config = conn.execute(self._schema.config.select().where(\n self._schema.config.c.config_hash == config_hash\n )).fetchone()\n if cur_config is not None:\n return int(cur_config.config_id) # mypy doesn't know it's always int\n # Config not found, create a new one:\n config_id: int = conn.execute(self._schema.config.insert().values(\n config_hash=config_hash)).inserted_primary_key[0]\n self._save_params(\n conn, self._schema.config_param,\n {tunable.name: tunable.value for (tunable, _group) in tunables},\n config_id=config_id)\n return config_id\n\n def new_trial(self, tunables: TunableGroups,\n config: Optional[Dict[str, Any]] = None) -> Storage.Trial:\n _LOG.debug(\"Create trial: %s:%d\", self._experiment_id, self._trial_id)\n with self._engine.begin() as conn:\n try:\n config_id = self._get_config_id(conn, tunables)\n conn.execute(self._schema.trial.insert().values(\n exp_id=self._experiment_id,\n trial_id=self._trial_id,\n config_id=config_id,\n ts_start=datetime.utcnow(),\n status='PENDING',\n ))\n if config is not None:\n self._save_params(\n conn, self._schema.trial_param, config,\n exp_id=self._experiment_id, trial_id=self._trial_id)\n trial = Trial(\n engine=self._engine,\n schema=self._schema,\n tunables=tunables,\n experiment_id=self._experiment_id,\n trial_id=self._trial_id,\n config_id=config_id,\n opt_target=self._opt_target,\n config=config,\n )\n self._trial_id += 1\n return trial\n except Exception:\n conn.rollback()\n raise\n" }, { "alpha_fraction": 0.6486301422119141, "alphanum_fraction": 0.6513698697090149, "avg_line_length": 32.181819915771484, "blob_id": "6dd42ba78381607555405ebf56fa878d597af4fb", "content_id": "e6d80397299a8809f3c13bc573c950cc31518976", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1460, "license_type": "permissive", "max_line_length": 107, "num_lines": 44, "path": "/mlos_bench/mlos_bench/config/environments/os/linux/runtime/scripts/local/generate_kernel_config_script.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nHelper script to generate a script to update kernel parameters from tunables JSON.\n\nRun: `./generate_kernel_config_script.py ./kernel-params.json ./kernel-params-meta.json ./config-kernel.sh`\n\"\"\"\n\nimport json\nimport argparse\n\n\ndef _main(fname_input: str, fname_meta: str, fname_output: str) -> None:\n\n with open(fname_input, \"rt\", encoding=\"utf-8\") as fh_tunables:\n tunables_data = json.load(fh_tunables)\n\n with open(fname_meta, \"rt\", encoding=\"utf-8\") as fh_meta:\n tunables_meta = json.load(fh_meta)\n\n with open(fname_output, \"wt\", encoding=\"utf-8\", newline=\"\") as fh_config:\n for (key, val) in tunables_data.items():\n meta = tunables_meta.get(key, {})\n name_prefix = meta.get(\"name_prefix\", \"\")\n line = f'echo \"{val}\" > {name_prefix}{key}'\n fh_config.write(line + \"\\n\")\n print(line)\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(\n description=\"generate a script to update kernel parameters from tunables JSON.\")\n\n parser.add_argument(\"input\", help=\"JSON file with tunable parameters.\")\n parser.add_argument(\"meta\", help=\"JSON file with tunable parameters metadata.\")\n parser.add_argument(\"output\", help=\"Output shell script to configure Linux kernel.\")\n\n args = parser.parse_args()\n\n _main(args.input, args.meta, args.output)\n" }, { "alpha_fraction": 0.7450000047683716, "alphanum_fraction": 0.7450000047683716, "avg_line_length": 21.22222137451172, "blob_id": "6593ecc75445e4a7a2b7248069cfcbc30d709494", "content_id": "83b1b7d391ebc7b2684223d2f49133a1aabdedc5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 200, "license_type": "permissive", "max_line_length": 96, "num_lines": 9, "path": "/mlos_core/mlos_core/tests/optimizers/__init__.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nOptimizer tests.\n\nNote: this file is required so that mypy doesn't complain about overlapping conftest.py modules.\n\"\"\"\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6674737930297852, "avg_line_length": 32.486488342285156, "blob_id": "1b2a243658741057ab54e8794031fdfa9c85fde4", "content_id": "503c5e1956d86d7fc6c3b7c892ed4e21ce3ed9f9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1239, "license_type": "permissive", "max_line_length": 79, "num_lines": 37, "path": "/mlos_bench/mlos_bench/tests/services/local/mock/mock_local_exec_service.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nA collection Service functions for mocking local exec.\n\"\"\"\n\nimport logging\nfrom typing import Any, Dict, Iterable, Mapping, Optional, Tuple, TYPE_CHECKING\n\nfrom mlos_bench.services.base_service import Service\nfrom mlos_bench.services.local.temp_dir_context import TempDirContextService\nfrom mlos_bench.services.types.local_exec_type import SupportsLocalExec\n\nif TYPE_CHECKING:\n from mlos_bench.tunables.tunable import TunableValue\n\n_LOG = logging.getLogger(__name__)\n\n\nclass MockLocalExecService(TempDirContextService, SupportsLocalExec):\n \"\"\"\n Mock methods for LocalExecService testing.\n \"\"\"\n\n def __init__(self, config: Optional[Dict[str, Any]] = None,\n global_config: Optional[Dict[str, Any]] = None,\n parent: Optional[Service] = None):\n super().__init__(config, global_config, parent)\n self.register([self.local_exec])\n\n def local_exec(self, script_lines: Iterable[str],\n env: Optional[Mapping[str, \"TunableValue\"]] = None,\n cwd: Optional[str] = None,\n return_on_error: bool = False) -> Tuple[int, str, str]:\n return (0, \"\", \"\")\n" }, { "alpha_fraction": 0.6725248694419861, "alphanum_fraction": 0.6725248694419861, "avg_line_length": 33.13999938964844, "blob_id": "9bd18742bfeda955b1120b70984b7ec33d43f3ea", "content_id": "f066be1fb91b3c0a09dd6e2daa51a4fbd51d3931", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1707, "license_type": "permissive", "max_line_length": 122, "num_lines": 50, "path": "/mlos_core/mlos_core/optimizers/bayesian_optimizers/bayesian_optimizer.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nContains the wrapper classes for base Bayesian optimizers.\n\"\"\"\n\nfrom abc import ABCMeta, abstractmethod\n\nfrom typing import Optional\n\nimport pandas as pd\nimport numpy.typing as npt\n\nfrom mlos_core.optimizers.optimizer import BaseOptimizer\n\n\nclass BaseBayesianOptimizer(BaseOptimizer, metaclass=ABCMeta):\n \"\"\"Abstract base class defining the interface for Bayesian optimization.\"\"\"\n\n @abstractmethod\n def surrogate_predict(self, configurations: pd.DataFrame,\n context: Optional[pd.DataFrame] = None) -> npt.NDArray:\n \"\"\"Obtain a prediction from this Bayesian optimizer's surrogate model for the given configuration(s).\n\n Parameters\n ----------\n configurations : pd.DataFrame\n Dataframe of configurations / parameters. The columns are parameter names and the rows are the configurations.\n\n context : pd.DataFrame\n Not Yet Implemented.\n \"\"\"\n pass # pylint: disable=unnecessary-pass # pragma: no cover\n\n @abstractmethod\n def acquisition_function(self, configurations: pd.DataFrame,\n context: Optional[pd.DataFrame] = None) -> npt.NDArray:\n \"\"\"Invokes the acquisition function from this Bayesian optimizer for the given configuration.\n\n Parameters\n ----------\n configurations : pd.DataFrame\n Dataframe of configurations / parameters. The columns are parameter names and the rows are the configurations.\n\n context : pd.DataFrame\n Not Yet Implemented.\n \"\"\"\n pass # pylint: disable=unnecessary-pass # pragma: no cover\n" }, { "alpha_fraction": 0.5647032260894775, "alphanum_fraction": 0.5647032260894775, "avg_line_length": 30.184396743774414, "blob_id": "3694f5b39f893220ba2884166b274dd6c090f4f1", "content_id": "0574d25c61e5061af6afa5343f34bf94bd2ac14c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4397, "license_type": "permissive", "max_line_length": 95, "num_lines": 141, "path": "/mlos_bench/mlos_bench/services/types/vm_provisioner_type.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nProtocol interface for VM provisioning operations.\n\"\"\"\n\nfrom typing import Tuple, Protocol, runtime_checkable, TYPE_CHECKING\n\nif TYPE_CHECKING:\n from mlos_bench.environments.status import Status\n\n\n@runtime_checkable\nclass SupportsVMOps(Protocol):\n \"\"\"\n Protocol interface for VM provisioning operations.\n \"\"\"\n\n def vm_provision(self, params: dict) -> Tuple[\"Status\", dict]:\n \"\"\"\n Check if VM is ready. Deploy a new VM, if necessary.\n\n Parameters\n ----------\n params : dict\n Flat dictionary of (key, value) pairs of tunable parameters.\n VMEnv tunables are variable parameters that, together with the\n VMEnv configuration, are sufficient to provision a VM.\n\n Returns\n -------\n result : (Status, dict={})\n A pair of Status and result. The result is always {}.\n Status is one of {PENDING, SUCCEEDED, FAILED}\n \"\"\"\n\n def wait_vm_deployment(self, is_setup: bool, params: dict) -> Tuple[\"Status\", dict]:\n \"\"\"\n Waits for a pending operation on an Azure VM to resolve to SUCCEEDED or FAILED.\n Return TIMED_OUT when timing out.\n\n Parameters\n ----------\n is_setup : bool\n If True, wait for VM being deployed; otherwise, wait for successful deprovisioning.\n params : dict\n Flat dictionary of (key, value) pairs of tunable parameters.\n\n Returns\n -------\n result : (Status, dict)\n A pair of Status and result.\n Status is one of {PENDING, SUCCEEDED, FAILED, TIMED_OUT}\n Result is info on the operation runtime if SUCCEEDED, otherwise {}.\n \"\"\"\n\n def vm_start(self, params: dict) -> Tuple[\"Status\", dict]:\n \"\"\"\n Start a VM.\n\n Parameters\n ----------\n params : dict\n Flat dictionary of (key, value) pairs of tunable parameters.\n\n Returns\n -------\n result : (Status, dict={})\n A pair of Status and result. The result is always {}.\n Status is one of {PENDING, SUCCEEDED, FAILED}\n \"\"\"\n\n def vm_stop(self, params: dict) -> Tuple[\"Status\", dict]:\n \"\"\"\n Stops the VM by initiating a graceful shutdown.\n\n Parameters\n ----------\n params : dict\n Flat dictionary of (key, value) pairs of tunable parameters.\n\n Returns\n -------\n result : (Status, dict={})\n A pair of Status and result. The result is always {}.\n Status is one of {PENDING, SUCCEEDED, FAILED}\n \"\"\"\n\n def vm_restart(self, params: dict) -> Tuple[\"Status\", dict]:\n \"\"\"\n Restarts the VM by initiating a graceful shutdown.\n\n Parameters\n ----------\n params : dict\n Flat dictionary of (key, value) pairs of tunable parameters.\n\n Returns\n -------\n result : (Status, dict={})\n A pair of Status and result. The result is always {}.\n Status is one of {PENDING, SUCCEEDED, FAILED}\n \"\"\"\n\n def vm_deprovision(self, params: dict) -> Tuple[\"Status\", dict]:\n \"\"\"\n Deallocates the VM by shutting it down then releasing the compute resources.\n\n Parameters\n ----------\n params : dict\n Flat dictionary of (key, value) pairs of tunable parameters.\n\n Returns\n -------\n result : (Status, dict={})\n A pair of Status and result. The result is always {}.\n Status is one of {PENDING, SUCCEEDED, FAILED}\n \"\"\"\n\n def wait_vm_operation(self, params: dict) -> Tuple[\"Status\", dict]:\n \"\"\"\n Waits for a pending operation on a VM to resolve to SUCCEEDED or FAILED.\n Return TIMED_OUT when timing out.\n\n Parameters\n ----------\n params: dict\n Flat dictionary of (key, value) pairs of tunable parameters.\n Must have the \"asyncResultsUrl\" key to get the results.\n If the key is not present, return Status.PENDING.\n\n Returns\n -------\n result : (Status, dict)\n A pair of Status and result.\n Status is one of {PENDING, SUCCEEDED, FAILED, TIMED_OUT}\n Result is info on the operation runtime if SUCCEEDED, otherwise {}.\n \"\"\"\n" }, { "alpha_fraction": 0.623577892780304, "alphanum_fraction": 0.6267163753509521, "avg_line_length": 30.664596557617188, "blob_id": "e605fc38d8e10a5c1bf52dac141f5f6333e3d463", "content_id": "8d195dd5cfc7763b62016ab841fe68eb140a6b9b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5098, "license_type": "permissive", "max_line_length": 86, "num_lines": 161, "path": "/mlos_bench/mlos_bench/tests/tunables/tunable_slice_references_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nUnit tests for unique references to tunables when they're loaded multiple times.\n\"\"\"\n\nimport json5 as json\nimport pytest\n\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\n\n\ndef test_duplicate_merging_tunable_groups(tunable_groups_config: dict) -> None:\n \"\"\"\n Check that the merging logic of tunable groups works as expected.\n \"\"\"\n parent_tunables = TunableGroups(tunable_groups_config)\n\n # Pretend we loaded this one from disk another time.\n tunables_dup = TunableGroups(tunable_groups_config)\n\n (tunable, covariant_group) = next(iter(parent_tunables))\n (tunable_dup, covariant_group_dup) = next(iter(tunables_dup))\n\n assert tunable == tunable_dup\n assert covariant_group == covariant_group_dup\n\n # Test merging prior to making any changes.\n parent_tunable_copy = parent_tunables.copy()\n parent_tunables = parent_tunables.merge(tunables_dup)\n\n # Check that they're the same.\n assert covariant_group == covariant_group_dup\n assert parent_tunables == tunables_dup\n assert parent_tunables == parent_tunable_copy\n\n (tunable_retry, covariant_group_retry) = next(iter(parent_tunables))\n assert tunable == tunable_retry\n assert covariant_group == covariant_group_retry\n\n # Update a value to indicate that they're separate copies.\n if tunable.is_categorical:\n tunable.category = [x for x in tunable.categories if x != tunable.category][0]\n elif tunable.is_numerical:\n tunable.numerical_value += 1\n\n # Check that they're separate.\n assert tunable != tunable_dup\n assert covariant_group != covariant_group_dup\n assert parent_tunables != tunables_dup\n\n # Should be ok since we only changed the value.\n parent_tunable_copy = parent_tunables.copy()\n parent_tunables = parent_tunables.merge(tunables_dup)\n\n # Make sure nothing changed in the parent.\n assert tunable != tunable_dup\n assert covariant_group != covariant_group_dup\n assert parent_tunables != tunables_dup\n assert parent_tunables == parent_tunable_copy\n\n\ndef test_overlapping_group_merge_tunable_groups(tunable_groups_config: dict) -> None:\n \"\"\"\n Check that the merging logic of tunable groups works as expected.\n \"\"\"\n parent_tunables = TunableGroups(tunable_groups_config)\n\n # This config should overlap with the parent config.\n # (same group name, different param name, different values)\n other_tunables_json = \"\"\"\n {\n \"boot\": {\n \"cost\": 300,\n \"params\": {\n \"noidle\": {\n \"description\": \"(different) idling method\",\n \"type\": \"categorical\",\n \"default\": \"nomwait\",\n \"values\": [\"nohalt\", \"nomwait\", \"idle\"]\n }\n }\n }\n }\n \"\"\"\n\n other_tunables_config = json.loads(other_tunables_json)\n other_tunables = TunableGroups(other_tunables_config)\n\n with pytest.raises(ValueError):\n parent_tunables.merge(other_tunables)\n\n\ndef test_bad_extended_merge_tunable_group(tunable_groups_config: dict) -> None:\n \"\"\"\n Check that the merging logic of tunable groups works as expected.\n \"\"\"\n parent_tunables = TunableGroups(tunable_groups_config)\n\n # This config should overlap with the parent config.\n # (different group name, same param name)\n other_tunables_json = \"\"\"\n {\n \"new-group\": {\n \"cost\": 300,\n \"params\": {\n \"idle\": {\n \"type\": \"categorical\",\n \"description\": \"Idling method\",\n \"default\": \"mwait\",\n \"values\": [\"halt\", \"mwait\", \"noidle\"]\n }\n }\n }\n }\n \"\"\"\n\n other_tunables_config = json.loads(other_tunables_json)\n other_tunables = TunableGroups(other_tunables_config)\n\n with pytest.raises(ValueError):\n parent_tunables.merge(other_tunables)\n\n\ndef test_good_extended_merge_tunable_group(tunable_groups_config: dict) -> None:\n \"\"\"\n Check that the merging logic of tunable groups works as expected.\n \"\"\"\n parent_tunables = TunableGroups(tunable_groups_config)\n\n # This config should overlap with the parent config.\n # (different group name, same param name)\n other_tunables_json = \"\"\"\n {\n \"new-group\": {\n \"cost\": 300,\n \"params\": {\n \"new-param\": {\n \"type\": \"int\",\n \"default\": 0,\n \"range\": [0, 10]\n }\n }\n }\n }\n \"\"\"\n\n other_tunables_config = json.loads(other_tunables_json)\n other_tunables = TunableGroups(other_tunables_config)\n\n assert \"new-param\" not in parent_tunables\n assert \"new-param\" in other_tunables\n\n parent_tunables = parent_tunables.merge(other_tunables)\n\n assert \"new-param\" in parent_tunables\n (tunable_param, covariant_group) = parent_tunables.get_tunable(\"new-param\")\n assert tunable_param.name == \"new-param\"\n assert covariant_group.name == \"new-group\"\n" }, { "alpha_fraction": 0.6572299599647522, "alphanum_fraction": 0.6689895391464233, "avg_line_length": 35.736000061035156, "blob_id": "b7e5e91ff5adffc3907541e98ce71966c70405de", "content_id": "9e15ee0d4bfe6cfb8c51b23f21bc56cbc25fc59e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9184, "license_type": "permissive", "max_line_length": 117, "num_lines": 250, "path": "/mlos_core/mlos_core/tests/spaces/spaces_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTests for mlos_core.spaces\n\"\"\"\n\n# pylint: disable=missing-function-docstring\n\nfrom abc import ABCMeta, abstractmethod\nfrom typing import Any, Callable, List, NoReturn, Union\n\nimport numpy as np\nimport numpy.typing as npt\nimport pytest\n\nimport scipy\n\nimport ConfigSpace as CS\nfrom ConfigSpace.hyperparameters import NormalIntegerHyperparameter\n\nimport flaml.tune.sample\n\nfrom mlos_core.spaces.converters.flaml import configspace_to_flaml_space, FlamlDomain, FlamlSpace\n\n\nOptimizerSpace = Union[FlamlSpace, CS.ConfigurationSpace]\nOptimizerParam = Union[FlamlDomain, CS.hyperparameters.Hyperparameter]\n\n\ndef assert_is_uniform(arr: npt.NDArray) -> None:\n \"\"\"Implements a few tests for uniformity.\"\"\"\n _values, counts = np.unique(arr, return_counts=True)\n\n kurtosis = scipy.stats.kurtosis(arr)\n\n _chi_sq, p_value = scipy.stats.chisquare(counts)\n\n frequencies = counts / len(arr)\n assert np.isclose(frequencies.sum(), 1)\n _f_chi_sq, f_p_value = scipy.stats.chisquare(frequencies)\n\n assert np.isclose(kurtosis, -1.2, atol=.1)\n assert p_value > .3\n assert f_p_value > .5\n\n\ndef assert_is_log_uniform(arr: npt.NDArray, base: float = np.e) -> None:\n \"\"\"Checks whether an array is log uniformly distributed.\"\"\"\n logs = np.log(arr) / np.log(base)\n assert_is_uniform(logs)\n\n\ndef test_is_uniform() -> None:\n \"\"\"Test our uniform distribution check function.\"\"\"\n np.random.seed(42)\n uniform = np.random.uniform(1, 20, 1000)\n assert_is_uniform(uniform)\n\n\ndef test_is_log_uniform() -> None:\n \"\"\"Test our log uniform distribution check function.\"\"\"\n np.random.seed(42)\n log_uniform = np.exp(np.random.uniform(np.log(1), np.log(20), 1000))\n assert_is_log_uniform(log_uniform)\n\n\ndef invalid_conversion_function(*args: Any) -> NoReturn:\n \"\"\"\n A quick dummy function for the base class to make pylint happy.\n \"\"\"\n raise NotImplementedError('subclass must override conversion_function')\n\n\nclass BaseConversion(metaclass=ABCMeta):\n \"\"\"\n Base class for testing optimizer space conversions.\n \"\"\"\n conversion_function: Callable[..., OptimizerSpace] = invalid_conversion_function\n\n @abstractmethod\n def sample(self, config_space: OptimizerSpace, n_samples: int = 1) -> OptimizerParam:\n \"\"\"\n Sample from the given configuration space.\n\n Parameters\n ----------\n config_space : CS.ConfigurationSpace\n Configuration space to sample from.\n n_samples : int, optional\n Number of samples to use, by default 1.\n \"\"\"\n\n @abstractmethod\n def get_parameter_names(self, config_space: OptimizerSpace) -> List[str]:\n \"\"\"\n Get the parameter names from the given configuration space.\n\n Parameters\n ----------\n config_space : CS.ConfigurationSpace\n Configuration space.\n \"\"\"\n\n @abstractmethod\n def categorical_counts(self, points: npt.NDArray) -> npt.NDArray:\n \"\"\"\n Get the counts of each categorical value in the given points.\n\n Parameters\n ----------\n points : np.array\n Counts of each categorical value.\n \"\"\"\n\n @abstractmethod\n def test_dimensionality(self) -> None:\n \"\"\"\n Check that the dimensionality of the converted space is correct.\n \"\"\"\n\n def test_unsupported_hyperparameter(self) -> None:\n input_space = CS.ConfigurationSpace()\n input_space.add_hyperparameter(NormalIntegerHyperparameter(\"a\", 2, 1))\n with pytest.raises(ValueError, match=\"NormalIntegerHyperparameter\"):\n self.conversion_function(input_space)\n\n def test_continuous_bounds(self) -> None:\n input_space = CS.ConfigurationSpace()\n input_space.add_hyperparameter(CS.UniformFloatHyperparameter(\"a\", lower=100, upper=200))\n input_space.add_hyperparameter(CS.UniformIntegerHyperparameter(\"b\", lower=-10, upper=-5))\n\n converted_space = self.conversion_function(input_space)\n assert self.get_parameter_names(converted_space) == [\"a\", \"b\"]\n point = self.sample(converted_space)\n assert 100 <= point[0] <= 200\n assert -10 <= point[1] <= -5\n\n def test_uniform_samples(self) -> None:\n input_space = CS.ConfigurationSpace()\n input_space.add_hyperparameter(CS.UniformFloatHyperparameter(\"a\", lower=1, upper=5))\n input_space.add_hyperparameter(CS.UniformIntegerHyperparameter(\"c\", lower=1, upper=20))\n converted_space = self.conversion_function(input_space)\n\n np.random.seed(42)\n uniform, integer_uniform = self.sample(converted_space, n_samples=1000).T\n\n # uniform float\n assert_is_uniform(uniform)\n\n # Check that we get both ends of the sampled range returned to us.\n assert input_space['c'].lower in integer_uniform\n assert input_space['c'].upper in integer_uniform\n # integer uniform\n assert_is_uniform(integer_uniform)\n\n def test_uniform_categorical(self) -> None:\n input_space = CS.ConfigurationSpace()\n input_space.add_hyperparameter(CS.CategoricalHyperparameter(\"c\", choices=[\"foo\", \"bar\"]))\n converted_space = self.conversion_function(input_space)\n points = self.sample(converted_space, n_samples=100)\n counts = self.categorical_counts(points)\n assert 35 < counts[0] < 65\n assert 35 < counts[1] < 65\n\n def test_weighted_categorical(self) -> None:\n raise NotImplementedError('subclass must override')\n\n def test_log_int_spaces(self) -> None:\n raise NotImplementedError('subclass must override')\n\n def test_log_float_spaces(self) -> None:\n raise NotImplementedError('subclass must override')\n\n\nclass TestFlamlConversion(BaseConversion):\n \"\"\"\n Tests for ConfigSpace to Flaml parameter conversions.\n \"\"\"\n\n conversion_function = staticmethod(configspace_to_flaml_space)\n\n def sample(self, config_space: FlamlSpace, n_samples: int = 1) -> npt.NDArray: # type: ignore[override]\n assert isinstance(config_space, dict)\n assert isinstance(next(iter(config_space.values())), flaml.tune.sample.Domain)\n ret: npt.NDArray = np.array([domain.sample(size=n_samples) for domain in config_space.values()]).T\n return ret\n\n def get_parameter_names(self, config_space: FlamlSpace) -> List[str]: # type: ignore[override]\n assert isinstance(config_space, dict)\n ret: List[str] = list(config_space.keys())\n return ret\n\n def categorical_counts(self, points: npt.NDArray) -> npt.NDArray:\n _vals, counts = np.unique(points, return_counts=True)\n assert isinstance(counts, np.ndarray)\n return counts\n\n def test_dimensionality(self) -> None:\n input_space = CS.ConfigurationSpace()\n input_space.add_hyperparameter(CS.UniformIntegerHyperparameter(\"a\", lower=1, upper=10))\n input_space.add_hyperparameter(CS.CategoricalHyperparameter(\"b\", choices=[\"bof\", \"bum\"]))\n input_space.add_hyperparameter(CS.CategoricalHyperparameter(\"c\", choices=[\"foo\", \"bar\"]))\n output_space = configspace_to_flaml_space(input_space)\n assert len(output_space) == 3\n\n def test_weighted_categorical(self) -> None:\n np.random.seed(42)\n input_space = CS.ConfigurationSpace()\n input_space.add_hyperparameter(CS.CategoricalHyperparameter(\"c\", choices=[\"foo\", \"bar\"], weights=[0.9, 0.1]))\n with pytest.raises(ValueError, match=\"non-uniform\"):\n configspace_to_flaml_space(input_space)\n\n @pytest.mark.skip(reason=\"FIXME: flaml sampling is non-log-uniform\")\n def test_log_int_spaces(self) -> None:\n np.random.seed(42)\n # integer is supported\n input_space = CS.ConfigurationSpace()\n input_space.add_hyperparameter(CS.UniformIntegerHyperparameter(\"d\", lower=1, upper=20, log=True))\n converted_space = configspace_to_flaml_space(input_space)\n\n # test log integer sampling\n integer_log_uniform = self.sample(converted_space, n_samples=1000)\n integer_log_uniform = np.array(integer_log_uniform).ravel()\n\n # FIXME: this fails - flaml is calling np.random.uniform() on base 10\n # logs of the bounds as expected but for some reason the resulting\n # samples are more skewed towards the lower end of the range\n # See Also: https://github.com/microsoft/FLAML/issues/1104\n assert_is_log_uniform(integer_log_uniform, base=10)\n\n def test_log_float_spaces(self) -> None:\n np.random.seed(42)\n\n # continuous is supported\n input_space = CS.ConfigurationSpace()\n input_space.add_hyperparameter(CS.UniformFloatHyperparameter(\"b\", lower=1, upper=5, log=True))\n converted_space = configspace_to_flaml_space(input_space)\n\n # test log integer sampling\n float_log_uniform = self.sample(converted_space, n_samples=1000)\n float_log_uniform = np.array(float_log_uniform).ravel()\n\n assert_is_log_uniform(float_log_uniform)\n\n\nif __name__ == '__main__':\n # For attaching debugger debugging:\n pytest.main([\"-vv\", \"-k\", \"test_log_int_spaces\", __file__])\n" }, { "alpha_fraction": 0.6190639138221741, "alphanum_fraction": 0.6258968114852905, "avg_line_length": 31.5222225189209, "blob_id": "b25dcd1f5b2f941396a9b55d9f14591a31fae50c", "content_id": "9100dcff76f92e015138ebc0ca17e8c86ad303f2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2927, "license_type": "permissive", "max_line_length": 126, "num_lines": 90, "path": "/mlos_bench/setup.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nSetup instructions for the mlos_bench package.\n\"\"\"\n\nfrom logging import warning\nfrom itertools import chain\nfrom typing import Dict, List\n\nfrom setuptools import setup, find_packages\n\nfrom _version import _VERSION # pylint: disable=import-private-name\n\ntry:\n from setuptools_scm import get_version\n version = get_version(root='..', relative_to=__file__)\n if version is not None:\n _VERSION = version # noqa: F811\nexcept ImportError:\n warning(\"setuptools_scm not found, using version from _version.py\")\nexcept LookupError as e:\n warning(f\"setuptools_scm failed to find git version, using version from _version.py: {e}\")\n\n\nextra_requires: Dict[str, List[str]] = { # pylint: disable=consider-using-namedtuple-or-dataclass\n # Additional tools for extra functionality.\n 'azure': ['azure-storage-file-share'],\n 'storage-sql-duckdb': ['sqlalchemy', 'duckdb_engine'],\n 'storage-sql-mysql': ['sqlalchemy', 'mysql-connector-python'],\n 'storage-sql-postgres': ['sqlalchemy', 'psycopg2'],\n 'storage-sql-sqlite': ['sqlalchemy'], # sqlite3 comes with python, so we don't need to install it.\n # Transitive extra_requires from mlos-core.\n 'flaml': ['flaml[blendsearch]'],\n 'smac': ['smac'],\n}\n\n# construct special 'full' extra that adds requirements for all built-in\n# backend integrations and additional extra features.\nextra_requires['full'] = list(set(chain(*extra_requires.values())))\n\nextra_requires['full-tests'] = extra_requires['full'] + [\n 'pytest',\n 'pytest-forked',\n 'pytest-xdist',\n 'pytest-cov',\n 'pytest-local-badge',\n]\n\n# pylint: disable=duplicate-code\nMODULE_BASE_NAME = 'mlos_bench'\nsetup(\n name='mlos-bench',\n version=_VERSION,\n packages=find_packages(exclude=[f\"{MODULE_BASE_NAME}.tests\", f\"{MODULE_BASE_NAME}.tests.*\"]),\n package_data={\n '': ['py.typed', '**/*.pyi'],\n 'mlos_bench': [\n 'config/**/*.md',\n 'config/**/*.jsonc',\n 'config/**/*.json',\n 'config/**/*.py',\n 'config/**/*.sh',\n 'config/**/*.cmd',\n 'config/**/*.ps1',\n ],\n },\n entry_points={\n 'console_scripts': [\n 'mlos_bench = mlos_bench.run:_main',\n ],\n },\n install_requires=[\n 'mlos-core==' + _VERSION,\n 'requests',\n 'json5',\n 'jsonschema>=4.18.0', 'referencing>=0.29.1',\n 'importlib_resources;python_version<\"3.10\"',\n ] + extra_requires['storage-sql-sqlite'], # NOTE: For now sqlite is a fallback storage backend, so we always install it.\n extras_require=extra_requires,\n author='Microsoft',\n author_email='[email protected]',\n description=('MLOS Bench Python interface for benchmark automation and optimization.'),\n license='MIT',\n keywords='',\n url='https://aka.ms/mlos-core',\n python_requires='>=3.8',\n)\n" }, { "alpha_fraction": 0.7907816767692566, "alphanum_fraction": 0.7963041663169861, "avg_line_length": 91.31372833251953, "blob_id": "f7b924b9272452632868b5e6961906272d842fe2", "content_id": "6d1ac979783ad85d90803a6b6c6a28512409e75f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4710, "license_type": "permissive", "max_line_length": 700, "num_lines": 51, "path": "/mlos_core/mlos_core/spaces/adapters/README.md", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "# Space Adapters\n\nIt is often the case in black-box optimization that we need to perform some kind of *transformation* between the original parameter space (i.e., input space), and the space considered by the underlying optimizer (i.e., target parameters space).\nTwo examples of such transformations include (1) applying log space on the values of one (or more) parameters, or (2) employing parameter value discretization to reduce the number of unique considered values.\nWhile trivial transformations, like the two above, might be provided by `ConfigSpace`, more complicated ones are not.\n\nA *space adapter* provides the user the ability to define such an arbitrary transformation.\nThis is achieved using an implementation of the abstract `BaseSpaceAdapter` class.\nTo facilitate the custom transformation functionality, the user should provide implementation for the following three methods:\n\n- `transform`, which provides the logic for translating a given configuration *from* the target parameter space to the original one.\n- `inverse_transform`, which translates a configuration *from* the original parameter space to the target one.\n- `target_parameter_space`, which returns the `ConfigSpace` definition of the target parameter space, which is typically based upon the input original space.\n\nMore technical details can be found in `adapter.py`.\n\nPlease note that currently space adapters cannot be used in conjunction with user-provided context. We plan to investigate whether it is possible to support such a functionality in the future.\n\n## LlamaTune Space Adapter\n\nCurrently, `mlos_core` supports a single space adapter, `LlamaTuneSpaceAdapter`, which implements the LlamaTune methodology described in this [VLDB'22 research paper](https://www.vldb.org/pvldb/vol15/p2953-kanellis.pdf).\nIt has been shown experimentally that optimizers (like SMAC) that leverage LlamaTune can identify good-performing parameter configurations in a more *sample-efficient* manner, using on average 5.6x fewer samples.\n\nIn summary, LlamaTune leverages expert domain knowledge for DBMSs to construct an *artificial low-dimensional* search space that is more effectively explored by the optimizer.\nThis low-dimensional space is constructed using a random linear projection of the original parameter space, i.e., the parameters of the target parameter space are *linear combinations* of the parameters of the original one.\nFurther, LlamaTune allows the user to provide a list of *special values* for a subset of the original parameters; these special values will then be prioritized during the optimization process.\nFinally, the user can optionally specify the maximum number of unique values for each parameter.\n\n### Usage Example\n\n`LlamaTuneSpaceAdapter` receives up to three hyperparameters:\n\n- `num_low_dims`, the dimensionality of the target parameter space (defaults to 16). Needs to be smaller than the original space.\n- `special_param_values`, one (or more) special values for each parameter. The user can also define the degree of prioritization (defaults to 20%).\n- `max_unique_values`, the maximum number of unique values per parameter (defaults to 10,000).\n\nThe user can employ `LlamaTuneSpaceAdapter` when initializing the `mlos_core` optimizer, using `OptimizerFactory`, as follows:\n\n```python\nllamatune_optimizer = OptimizerFactory.create(\n ...\n space_adapter_type=SpaceAdapterType.LLAMATUNE,\n space_adapter_kwargs=<llamatune_kwargs>,\n)\n```\n\n### Known Limitations\n\nThe random projection method employed by LlamaTune is inherently one-directional, i.e., from the target parameter space to the original one. This poses no issues in the typical use case, where each `.suggest()` call to the `mlos_core` optimizer is strictly followed by the corresponding `.register()` call. Yet, if the user wishes to register points (i.e., configurations) that were **not** previously suggested by the optimizer (e.g., bootstraping the optimizer using samples from some other run), it would normally be impossible.\n\nIn an effort to accommodate this use-case, we have devise a method, which tries to approximate the reverse projection of those user-provided points. Given that the original random projection utilizes a projection matrix *P*, our method computes its [Moore–Penrose pseudo-inverse](https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_inverse) matrix *P'*. Then, using *P'* we (approximately) project the points from the original parameter space to the target one. Please note that this method is *highly experimental*, and thus we provide no guarantees on how well (or not) it performs. More technical information can be found in the `_try_generate_approx_inverse_mapping` method inside `llamatune.py`.\n" }, { "alpha_fraction": 0.5659176111221313, "alphanum_fraction": 0.566591739654541, "avg_line_length": 31.881772994995117, "blob_id": "e036fe7ee1cc19de63609afb5b59cf58f1580200", "content_id": "61bd43aa24441110754b9870847d679e1892f69c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13350, "license_type": "permissive", "max_line_length": 99, "num_lines": 406, "path": "/mlos_bench/mlos_bench/tunables/tunable.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTunable parameter definition.\n\"\"\"\nimport copy\nimport collections\nimport logging\n\nfrom typing import Any, Dict, List, Optional, Sequence, Tuple, Type, TypedDict, Union\n\n_LOG = logging.getLogger(__name__)\n\n\n\"\"\"A tunable parameter value type alias.\"\"\"\nTunableValue = Union[int, float, Optional[str]]\n\n\nclass TunableDict(TypedDict, total=False):\n \"\"\"\n A typed dict for tunable parameters.\n\n Mostly used for mypy type checking.\n\n These are the types expected to be received from the json config.\n \"\"\"\n\n type: str\n description: Optional[str]\n default: TunableValue\n values: Optional[List[Optional[str]]]\n range: Optional[Union[Sequence[int], Sequence[float]]]\n special: Optional[Union[List[int], List[str]]]\n meta: Dict[str, Any]\n\n\nclass Tunable: # pylint: disable=too-many-instance-attributes\n \"\"\"\n A tunable parameter definition and its current value.\n \"\"\"\n\n # Maps tunable types to their corresponding Python types by name.\n _DTYPE: Dict[str, Type] = {\n \"int\": int,\n \"float\": float,\n \"categorical\": str,\n }\n\n def __init__(self, name: str, config: TunableDict):\n \"\"\"\n Create an instance of a new tunable parameter.\n\n Parameters\n ----------\n name : str\n Human-readable identifier of the tunable parameter.\n config : dict\n Python dict that represents a Tunable (e.g., deserialized from JSON)\n \"\"\"\n self._name = name\n self._type = config[\"type\"] # required\n self._description = config.get(\"description\")\n self._default = config[\"default\"]\n self._values = config.get(\"values\")\n self._meta: Dict[str, Any] = config.get(\"meta\", {})\n self._range: Optional[Union[Tuple[int, int], Tuple[float, float]]] = None\n config_range = config.get(\"range\")\n if config_range is not None:\n assert len(config_range) == 2, f\"Invalid range: {config_range}\"\n config_range = (config_range[0], config_range[1])\n self._range = config_range\n self._special = config.get(\"special\")\n self._current_value = self._default\n self._sanity_check()\n\n def _sanity_check(self) -> None:\n \"\"\"\n Check if the status of the Tunable is valid, and throw ValueError if it is not.\n \"\"\"\n if self.is_categorical:\n if not (self._values and isinstance(self._values, collections.abc.Iterable)):\n raise ValueError(\"Must specify values for the categorical type\")\n if self._range is not None:\n raise ValueError(\"Range must be None for the categorical type\")\n if len(set(self._values)) != len(self._values):\n raise ValueError(\"Values must be unique for the categorical type\")\n if self._special is not None:\n raise ValueError(\"Special values must be None for the categorical type\")\n elif self.is_numerical:\n if self._values is not None:\n raise ValueError(\"Values must be None for the numerical type\")\n if not self._range or len(self._range) != 2 or self._range[0] >= self._range[1]:\n raise ValueError(f\"Invalid range: {self._range}\")\n else:\n raise ValueError(f\"Invalid parameter type: {self._type}\")\n if not self.is_valid(self.default):\n raise ValueError(f\"Invalid default value: {self.default}\")\n\n def __repr__(self) -> str:\n \"\"\"\n Produce a human-readable version of the Tunable (mostly for logging).\n\n Returns\n -------\n string : str\n A human-readable version of the Tunable.\n \"\"\"\n return f\"{self._name}={self._current_value}\"\n\n def __eq__(self, other: object) -> bool:\n \"\"\"\n Check if two Tunable objects are equal.\n\n Parameters\n ----------\n other : Tunable\n A tunable object to compare to.\n\n Returns\n -------\n is_equal : bool\n True if the Tunables correspond to the same parameter and have the same value and type.\n NOTE: ranges and special values are not currently considered in the comparison.\n \"\"\"\n if not isinstance(other, Tunable):\n return False\n return bool(\n self._name == other._name and\n self._type == other._type and\n self._current_value == other._current_value\n )\n\n def __lt__(self, other: object) -> bool: # pylint: disable=too-many-return-statements\n \"\"\"\n Compare the two Tunable objects. We mostly need this to create a canonical list\n of tunable objects when hashing a TunableGroup.\n\n Parameters\n ----------\n other : Tunable\n A tunable object to compare to.\n\n Returns\n -------\n is_less : bool\n True if the current Tunable is less then the other one, False otherwise.\n \"\"\"\n if not isinstance(other, Tunable):\n return False\n if self._name < other._name:\n return True\n if self._name == other._name and self._type < other._type:\n return True\n if self._name == other._name and self._type == other._type:\n if self.is_numerical:\n assert self._current_value is not None\n assert other._current_value is not None\n return bool(float(self._current_value) < float(other._current_value))\n # else: categorical\n if self._current_value is None:\n return True\n if other._current_value is None:\n return False\n return bool(str(self._current_value) < str(other._current_value))\n return False\n\n def copy(self) -> \"Tunable\":\n \"\"\"\n Deep copy of the Tunable object.\n\n Returns\n -------\n tunable : Tunable\n A new Tunable object that is a deep copy of the original one.\n \"\"\"\n return copy.deepcopy(self)\n\n @property\n def default(self) -> TunableValue:\n \"\"\"\n Get the default value of the tunable.\n \"\"\"\n return self._default\n\n @property\n def value(self) -> TunableValue:\n \"\"\"\n Get the current value of the tunable.\n \"\"\"\n return self._current_value\n\n @value.setter\n def value(self, value: TunableValue) -> TunableValue:\n \"\"\"\n Set the current value of the tunable.\n \"\"\"\n # We need this coercion for the values produced by some optimizers\n # (e.g., scikit-optimize) and for data restored from certain storage\n # systems (where values can be strings).\n try:\n if self.is_categorical and value is None:\n coerced_value = None\n else:\n coerced_value = self._DTYPE[self._type](value)\n except Exception:\n _LOG.error(\"Impossible conversion: %s %s <- %s %s\",\n self._type, self._name, type(value), value)\n raise\n\n if self._type == \"int\" and isinstance(value, float) and value != coerced_value:\n _LOG.error(\"Loss of precision: %s %s <- %s %s\",\n self._type, self._name, type(value), value)\n raise ValueError(f\"Loss of precision: {self._name}={value}\")\n\n if not self.is_valid(coerced_value):\n _LOG.error(\"Invalid assignment: %s %s <- %s %s\",\n self._type, self._name, type(value), value)\n raise ValueError(f\"Invalid value for the tunable: {self._name}={value}\")\n\n self._current_value = coerced_value\n return self._current_value\n\n def update(self, value: TunableValue) -> bool:\n \"\"\"\n Assign the value to the tunable. Return True if it is a new value, False otherwise.\n\n Parameters\n ----------\n value : Union[int, float, str]\n Value to assign.\n\n Returns\n -------\n is_updated : bool\n True if the new value is different from the previous one, False otherwise.\n \"\"\"\n prev_value = self._current_value\n self.value = value\n return prev_value != self._current_value\n\n def is_valid(self, value: TunableValue) -> bool:\n \"\"\"\n Check if the value can be assigned to the tunable.\n\n Parameters\n ----------\n value : Union[int, float, str]\n Value to validate.\n\n Returns\n -------\n is_valid : bool\n True if the value is valid, False otherwise.\n \"\"\"\n if self.is_categorical and self._values:\n return value in self._values\n elif self.is_numerical and self._range:\n if isinstance(value, (int, float)):\n # TODO: allow special values outside of range?\n return bool(self._range[0] <= value <= self._range[1]) # or value == self._default\n else:\n raise ValueError(f\"Invalid value type for tunable {self}: {value}={type(value)}\")\n else:\n raise ValueError(f\"Invalid parameter type: {self._type}\")\n\n @property\n def category(self) -> Optional[str]:\n \"\"\"\n Get the current value of the tunable as a number.\n \"\"\"\n if self.is_categorical:\n return None if self._current_value is None else str(self._current_value)\n else:\n raise ValueError(\"Cannot get categorical values for a numerical tunable.\")\n\n @category.setter\n def category(self, new_value: Optional[str]) -> Optional[str]:\n \"\"\"\n Set the current value of the tunable.\n \"\"\"\n assert self.is_categorical\n assert isinstance(new_value, (str, type(None)))\n self.value = new_value\n return self.value\n\n @property\n def numerical_value(self) -> Union[int, float]:\n \"\"\"\n Get the current value of the tunable as a number.\n \"\"\"\n assert self._current_value is not None\n if self._type == \"int\":\n return int(self._current_value)\n elif self._type == \"float\":\n return float(self._current_value)\n else:\n raise ValueError(\"Cannot get numerical value for a categorical tunable.\")\n\n @numerical_value.setter\n def numerical_value(self, new_value: Union[int, float]) -> Union[int, float]:\n \"\"\"\n Set the current numerical value of the tunable.\n \"\"\"\n # We need this coercion for the values produced by some optimizers\n # (e.g., scikit-optimize) and for data restored from certain storage\n # systems (where values can be strings).\n assert self.is_numerical\n self.value = new_value\n return self.value\n\n @property\n def name(self) -> str:\n \"\"\"\n Get the name / string ID of the tunable.\n \"\"\"\n return self._name\n\n @property\n def type(self) -> str:\n \"\"\"\n Get the data type of the tunable.\n\n Returns\n -------\n type : str\n Data type of the tunable - one of {'int', 'float', 'categorical'}.\n \"\"\"\n return self._type\n\n @property\n def dtype(self) -> Type:\n \"\"\"\n Get the actual Python data type of the tunable.\n\n This is useful for bulk conversions of the input data.\n\n Returns\n -------\n dtype : type\n Data type of the tunable - one of {int, float, str}.\n \"\"\"\n return self._DTYPE[self._type]\n\n @property\n def is_categorical(self) -> bool:\n \"\"\"\n Check if the tunable is categorical.\n\n Returns\n -------\n is_categorical : bool\n True if the tunable is categorical, False otherwise.\n \"\"\"\n return self._type == \"categorical\"\n\n @property\n def is_numerical(self) -> bool:\n \"\"\"\n Check if the tunable is an integer or float.\n\n Returns\n -------\n is_int : bool\n True if the tunable is an integer or float, False otherwise.\n \"\"\"\n return self._type in {\"int\", \"float\"}\n\n @property\n def range(self) -> Union[Tuple[int, int], Tuple[float, float]]:\n \"\"\"\n Get the range of the tunable if it is numerical, None otherwise.\n\n Returns\n -------\n range : (number, number)\n A 2-tuple of numbers that represents the range of the tunable.\n Numbers can be int or float, depending on the type of the tunable.\n \"\"\"\n assert self.is_numerical\n assert self._range is not None\n return self._range\n\n @property\n def categories(self) -> List[Optional[str]]:\n \"\"\"\n Get the list of all possible values of a categorical tunable.\n Return None if the tunable is not categorical.\n\n Returns\n -------\n values : List[str]\n List of all possible values of a categorical tunable.\n \"\"\"\n assert self.is_categorical\n assert self._values is not None\n return self._values\n\n @property\n def meta(self) -> Dict[str, Any]:\n \"\"\"\n Get the tunable's metadata. This is a free-form dictionary that can be used to\n store any additional information about the tunable (e.g., the unit information).\n \"\"\"\n return self._meta\n" }, { "alpha_fraction": 0.7649572491645813, "alphanum_fraction": 0.7649572491645813, "avg_line_length": 25, "blob_id": "4db0ffda9069099ea25bb0e731fd37ab8d5d0018", "content_id": "9ed54809084a8ebad37503d5578bfc2a542a505f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 702, "license_type": "permissive", "max_line_length": 79, "num_lines": 27, "path": "/mlos_bench/mlos_bench/environments/__init__.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTunable Environments for mlos_bench.\n\"\"\"\n\nfrom mlos_bench.environments.status import Status\nfrom mlos_bench.environments.base_environment import Environment\n\nfrom mlos_bench.environments.mock_env import MockEnv\nfrom mlos_bench.environments.remote.remote_env import RemoteEnv\nfrom mlos_bench.environments.local.local_env import LocalEnv\nfrom mlos_bench.environments.local.local_fileshare_env import LocalFileShareEnv\nfrom mlos_bench.environments.composite_env import CompositeEnv\n\n__all__ = [\n 'Status',\n\n 'Environment',\n 'MockEnv',\n 'RemoteEnv',\n 'LocalEnv',\n 'LocalFileShareEnv',\n 'CompositeEnv',\n]\n" }, { "alpha_fraction": 0.6241862177848816, "alphanum_fraction": 0.6283290386199951, "avg_line_length": 34.950355529785156, "blob_id": "600f6e744b1d2e0d8a304c3933a750a2d2893085", "content_id": "03fcdb564e2d470baa0a818a82557effcf795270", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5069, "license_type": "permissive", "max_line_length": 105, "num_lines": 141, "path": "/mlos_bench/mlos_bench/config/schemas/config_schemas.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nA simple class for describing where to find different config schemas and validating configs against them.\n\"\"\"\n\nimport logging\nfrom enum import Enum\nfrom os import path, walk, environ\nfrom typing import Dict, Iterator, Mapping\n\nimport json # schema files are pure json - no comments\nimport jsonschema\n\nfrom referencing import Registry, Resource\nfrom referencing.jsonschema import DRAFT202012\n\nfrom mlos_bench.util import path_join\n\n_LOG = logging.getLogger(__name__)\n\n# The path to find all config schemas.\nCONFIG_SCHEMA_DIR = path_join(path.dirname(__file__), abs_path=True)\n\n# Allow skipping schema validation for tight dev cycle changes.\n# It is used in `ConfigSchema.validate()` method below.\n# NOTE: this may cause pytest to fail if it's expecting exceptions\n# to be raised for invalid configs.\n_VALIDATION_ENV_FLAG = 'MLOS_BENCH_SKIP_SCHEMA_VALIDATION'\n_SKIP_VALIDATION = (environ.get(_VALIDATION_ENV_FLAG, 'false').lower()\n in {'true', 'y', 'yes', 'on', '1'})\n\n\n# Note: we separate out the SchemaStore from a class method on ConfigSchema\n# because of issues with mypy/pylint and non-Enum-member class members.\nclass SchemaStore(Mapping):\n \"\"\"\n A simple class for storing schemas and subschemas for the validator to reference.\n \"\"\"\n\n # A class member mapping of schema id to schema object.\n _SCHEMA_STORE: Dict[str, dict] = {}\n _REGISTRY: Registry = Registry()\n\n def __len__(self) -> int:\n return self._SCHEMA_STORE.__len__()\n\n def __iter__(self) -> Iterator:\n return self._SCHEMA_STORE.__iter__()\n\n def __getitem__(self, key: str) -> dict:\n \"\"\"Gets the schema object for the given key.\"\"\"\n if not self._SCHEMA_STORE:\n self._load_schemas()\n return self._SCHEMA_STORE[key]\n\n @classmethod\n def _load_schemas(cls) -> None:\n \"\"\"Loads all schemas and subschemas into the schema store for the validator to reference.\"\"\"\n if cls._SCHEMA_STORE:\n return\n for root, _, files in walk(CONFIG_SCHEMA_DIR):\n for file_name in files:\n if not file_name.endswith(\".json\"):\n continue\n file_path = path_join(root, file_name)\n if path.getsize(file_path) == 0:\n continue\n with open(file_path, mode=\"r\", encoding=\"utf-8\") as schema_file:\n schema = json.load(schema_file)\n cls._SCHEMA_STORE[file_path] = schema\n # Let the schema be referenced by its id as well.\n assert \"$id\" in schema\n assert schema[\"$id\"] not in cls._SCHEMA_STORE\n cls._SCHEMA_STORE[schema[\"$id\"]] = schema\n\n @classmethod\n def _load_registry(cls) -> None:\n \"\"\"Also store them in a Registry object for referencing by recent versions of jsonschema.\"\"\"\n if not cls._SCHEMA_STORE:\n cls._load_schemas()\n cls._REGISTRY = Registry().with_resources([\n (url, Resource.from_contents(schema, default_specification=DRAFT202012))\n for url, schema in cls._SCHEMA_STORE.items()\n ])\n\n @property\n def registry(self) -> Registry:\n \"\"\"Returns a Registry object with all the schemas loaded.\"\"\"\n if not self._REGISTRY:\n self._load_registry()\n return self._REGISTRY\n\n\nSCHEMA_STORE = SchemaStore()\n\n\nclass ConfigSchema(Enum):\n \"\"\"\n An enum to help describe schema types and help validate configs against them.\n \"\"\"\n\n CLI = path_join(CONFIG_SCHEMA_DIR, \"cli/cli-schema.json\")\n GLOBALS = path_join(CONFIG_SCHEMA_DIR, \"cli/globals-schema.json\")\n ENVIRONMENT = path_join(CONFIG_SCHEMA_DIR, \"environments/environment-schema.json\")\n OPTIMIZER = path_join(CONFIG_SCHEMA_DIR, \"optimizers/optimizer-schema.json\")\n SERVICE = path_join(CONFIG_SCHEMA_DIR, \"services/service-schema.json\")\n STORAGE = path_join(CONFIG_SCHEMA_DIR, \"storage/storage-schema.json\")\n TUNABLE_PARAMS = path_join(CONFIG_SCHEMA_DIR, \"tunables/tunable-params-schema.json\")\n TUNABLE_VALUES = path_join(CONFIG_SCHEMA_DIR, \"tunables/tunable-values-schema.json\")\n\n @property\n def schema(self) -> dict:\n \"\"\"Gets the schema object for this type.\"\"\"\n schema = SCHEMA_STORE[self.value]\n assert schema\n return schema\n\n def validate(self, config: dict) -> None:\n \"\"\"\n Validates the given config against this schema.\n\n Parameters\n ----------\n config : dict\n The config to validate.\n\n Raises\n ------\n jsonschema.exceptions.ValidationError\n jsonschema.exceptions.SchemaError\n \"\"\"\n if _SKIP_VALIDATION:\n _LOG.warning(\"%s is set - skip schema validation\", _VALIDATION_ENV_FLAG)\n else:\n jsonschema.Draft202012Validator(\n schema=self.schema,\n registry=SCHEMA_STORE.registry, # type: ignore[call-arg]\n ).validate(config)\n" }, { "alpha_fraction": 0.5805055499076843, "alphanum_fraction": 0.5809610486030579, "avg_line_length": 31.52592658996582, "blob_id": "c575e00fa386e347d65132c363e71739bfba7f41", "content_id": "3583e6aaf06e04733fa6f067ded544fbfcd39650", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4391, "license_type": "permissive", "max_line_length": 99, "num_lines": 135, "path": "/mlos_bench/mlos_bench/services/base_service.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nBase class for the service mix-ins.\n\"\"\"\n\nimport json\nimport logging\n\nfrom typing import Any, Callable, Dict, List, Optional, Union\n\nfrom mlos_bench.services.types.config_loader_type import SupportsConfigLoading\nfrom mlos_bench.util import instantiate_from_config\n\n_LOG = logging.getLogger(__name__)\n\n\nclass Service:\n \"\"\"\n An abstract base of all environment services.\n \"\"\"\n\n @classmethod\n def new(cls,\n class_name: str,\n config: Optional[Dict[str, Any]] = None,\n global_config: Optional[Dict[str, Any]] = None,\n parent: Optional[\"Service\"] = None) -> \"Service\":\n \"\"\"\n Factory method for a new service with a given config.\n\n Parameters\n ----------\n class_name: str\n FQN of a Python class to instantiate, e.g.,\n \"mlos_bench.services.remote.azure.AzureVMService\".\n Must be derived from the `Service` class.\n config : dict\n Free-format dictionary that contains the service configuration.\n It will be passed as a constructor parameter of the class\n specified by `class_name`.\n global_config : dict\n Free-format dictionary of global parameters.\n parent : Service\n A parent service that can provide mixin functions.\n\n Returns\n -------\n svc : Service\n An instance of the `Service` class initialized with `config`.\n \"\"\"\n assert issubclass(cls, Service)\n return instantiate_from_config(cls, class_name, config, global_config, parent)\n\n def __init__(self,\n config: Optional[Dict[str, Any]] = None,\n global_config: Optional[Dict[str, Any]] = None,\n parent: Optional[\"Service\"] = None):\n \"\"\"\n Create a new service with a given config.\n\n Parameters\n ----------\n config : dict\n Free-format dictionary that contains the service configuration.\n It will be passed as a constructor parameter of the class\n specified by `class_name`.\n global_config : dict\n Free-format dictionary of global parameters.\n parent : Service\n An optional parent service that can provide mixin functions.\n \"\"\"\n self.config = config or {}\n self._parent = parent\n self._services: Dict[str, Callable] = {}\n\n if parent:\n self.register(parent.export())\n\n self._config_loader_service: SupportsConfigLoading\n if parent and isinstance(parent, SupportsConfigLoading):\n self._config_loader_service = parent\n\n if _LOG.isEnabledFor(logging.DEBUG):\n _LOG.debug(\"Service: %s Config:\\n%s\", self, json.dumps(self.config, indent=2))\n _LOG.debug(\"Service: %s Globals:\\n%s\", self, json.dumps(global_config or {}, indent=2))\n _LOG.debug(\"Service: %s Parent mixins: %s\", self,\n [] if parent is None else list(parent._services.keys()))\n\n def __repr__(self) -> str:\n return self.__class__.__name__\n\n @property\n def config_loader_service(self) -> SupportsConfigLoading:\n \"\"\"\n Return a config loader service.\n\n Returns\n -------\n config_loader_service : SupportsConfigLoading\n A config loader service.\n \"\"\"\n return self._config_loader_service\n\n def register(self, services: Union[Dict[str, Callable], List[Callable]]) -> None:\n \"\"\"\n Register new mix-in services.\n\n Parameters\n ----------\n services : dict or list\n A dictionary of string -> function pairs.\n \"\"\"\n if not isinstance(services, dict):\n services = {svc.__name__: svc for svc in services}\n\n if _LOG.isEnabledFor(logging.DEBUG):\n _LOG.debug(\"Service: %s Add methods: %s\",\n self.__class__.__name__, list(services.keys()))\n\n self._services.update(services)\n self.__dict__.update(self._services)\n\n def export(self) -> Dict[str, Callable]:\n \"\"\"\n Return a dictionary of functions available in this service.\n\n Returns\n -------\n services : dict\n A dictionary of string -> function pairs.\n \"\"\"\n return self._services\n" }, { "alpha_fraction": 0.6536697149276733, "alphanum_fraction": 0.6536697149276733, "avg_line_length": 23.91428565979004, "blob_id": "662e33dc41b7419cdcb68b36815846dccac6f9b0", "content_id": "708f0ee00ebc8a6c925d44d923e0f38df1697876", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 872, "license_type": "permissive", "max_line_length": 66, "num_lines": 35, "path": "/mlos_bench/mlos_bench/tests/config/__init__.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nHelper functions for config example loading tests.\n\"\"\"\n\nfrom typing import List\n\nimport os\n\nfrom mlos_bench.util import path_join\n\n\ndef locate_config_examples(config_examples_dir: str) -> List[str]:\n \"\"\"Locates all config examples in the given directory.\n\n Parameters\n ----------\n config_examples_dir: str\n Path to the directory containing config examples.\n\n Returns\n -------\n config_examples: List[str]\n List of paths to config examples.\n \"\"\"\n assert os.path.isdir(config_examples_dir)\n config_examples = []\n for root, _, files in os.walk(config_examples_dir):\n for file in files:\n if file.endswith(\".json\") or file.endswith(\".jsonc\"):\n config_examples.append(path_join(root, file))\n return config_examples\n" }, { "alpha_fraction": 0.6189948916435242, "alphanum_fraction": 0.6196871399879456, "avg_line_length": 42.251495361328125, "blob_id": "58e027519f3e987cfe4f9c49c0615e477ae0047e", "content_id": "48d5d319546ca9242fcb25eb12e53d982a584ee4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7223, "license_type": "permissive", "max_line_length": 121, "num_lines": 167, "path": "/mlos_bench/mlos_bench/optimizers/mlos_core_optimizer.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nA wrapper for mlos_core optimizers for mlos_bench.\n\"\"\"\n\nimport logging\nimport os\n\nfrom typing import Optional, Sequence, Tuple, Union\n\nimport pandas as pd\n\nfrom mlos_core.optimizers import BaseOptimizer, OptimizerType, OptimizerFactory, SpaceAdapterType, DEFAULT_OPTIMIZER_TYPE\n\nfrom mlos_bench.environments.status import Status\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\n\nfrom mlos_bench.optimizers.base_optimizer import Optimizer\nfrom mlos_bench.optimizers.convert_configspace import tunable_groups_to_configspace\n\nfrom mlos_bench.services.base_service import Service\n\nfrom mlos_bench.util import path_join\n\n_LOG = logging.getLogger(__name__)\n\n\nclass MlosCoreOptimizer(Optimizer):\n \"\"\"\n A wrapper class for the mlos_core optimizers.\n \"\"\"\n\n def __init__(self,\n tunables: TunableGroups,\n config: dict,\n global_config: Optional[dict] = None,\n service: Optional[Service] = None):\n super().__init__(tunables, config, global_config, service)\n\n seed = config.get(\"seed\")\n seed = None if seed is None else int(seed)\n\n space = tunable_groups_to_configspace(tunables, seed)\n _LOG.debug(\"ConfigSpace: %s\", space)\n\n opt_type = getattr(OptimizerType, self._config.pop(\n 'optimizer_type', DEFAULT_OPTIMIZER_TYPE.name))\n\n if opt_type == OptimizerType.SMAC:\n # If output_directory is specified, turn it into an absolute path.\n if 'output_directory' not in self._config:\n self._config['output_directory'] = 'smac_output'\n _LOG.info(\n \"No output_directory was specified for SMAC optimizer. Defaulting to '%s'.\",\n self._config['output_directory'])\n output_directory = self._config.get('output_directory')\n if output_directory is not None:\n if not os.path.isabs(output_directory):\n self._config['output_directory'] = path_join(os.getcwd(), output_directory)\n else:\n _LOG.warning(\"SMAC optimizer output_directory was null. SMAC will use a temporary directory.\")\n\n # Make sure max_trials >= max_iterations.\n if 'max_trials' not in self._config:\n self._config['max_trials'] = self._max_iter\n assert int(self._config['max_trials']) >= self._max_iter, \\\n f\"max_trials {self._config.get('max_trials')} <= max_iterations {self._max_iter}\"\n\n if 'run_name' not in self._config and self.experiment_id:\n self._config['run_name'] = self.experiment_id\n\n space_adapter_type = self._config.pop('space_adapter_type', None)\n space_adapter_config = self._config.pop('space_adapter_config', {})\n\n if space_adapter_type is not None:\n space_adapter_type = getattr(SpaceAdapterType, space_adapter_type)\n\n self._opt: BaseOptimizer = OptimizerFactory.create(\n parameter_space=space,\n optimizer_type=opt_type,\n optimizer_kwargs=self._config,\n space_adapter_type=space_adapter_type,\n space_adapter_kwargs=space_adapter_config,\n )\n\n def __repr__(self) -> str:\n return f\"{super().__repr__()}({self._opt.__class__.__name__})\"\n\n def bulk_register(self, configs: Sequence[dict], scores: Sequence[Optional[float]],\n status: Optional[Sequence[Status]] = None) -> bool:\n if not super().bulk_register(configs, scores, status):\n return False\n df_configs = self._to_df(configs) # Impute missing values, if necessary\n df_scores = pd.Series(scores, dtype=float) * self._opt_sign\n if status is not None:\n df_status = pd.Series(status)\n df_scores[df_status != Status.SUCCEEDED] = float(\"inf\")\n df_status_completed = df_status.apply(Status.is_completed)\n df_configs = df_configs[df_status_completed]\n df_scores = df_scores[df_status_completed]\n # External data can have incorrect types (e.g., all strings).\n for (tunable, _group) in self._tunables:\n df_configs[tunable.name] = df_configs[tunable.name].astype(tunable.dtype)\n self._opt.register(df_configs, df_scores)\n if _LOG.isEnabledFor(logging.DEBUG):\n (score, _) = self.get_best_observation()\n _LOG.debug(\"Warm-up end: %s = %s\", self.target, score)\n return True\n\n def _to_df(self, configs: Sequence[dict]) -> pd.DataFrame:\n \"\"\"\n Select from past trials only the columns required in this experiment and\n impute default values for the tunables that are missing in the dataframe.\n\n Parameters\n ----------\n configs : Sequence[dict]\n Sequence of dicts with past trials data.\n\n Returns\n -------\n df_configs : pd.DataFrame\n A dataframe with past trials data, with missing values imputed.\n \"\"\"\n df_configs = pd.DataFrame(configs)\n tunables_names = self._tunables.get_param_values().keys()\n missing_cols = set(tunables_names).difference(df_configs.columns)\n for (tunable, _group) in self._tunables:\n if tunable.name in missing_cols:\n df_configs[tunable.name] = tunable.default\n else:\n df_configs[tunable.name].fillna(tunable.default, inplace=True)\n # By default, hyperparameters in ConfigurationSpace are sorted by name:\n df_configs = df_configs[sorted(tunables_names)]\n _LOG.debug(\"Loaded configs:\\n%s\", df_configs)\n return df_configs\n\n def suggest(self) -> TunableGroups:\n if self._start_with_defaults:\n _LOG.info(\"Use default values for the first trial\")\n df_config = self._opt.suggest(defaults=self._start_with_defaults)\n self._start_with_defaults = False\n _LOG.info(\"Iteration %d :: Suggest:\\n%s\", self._iter, df_config)\n return self._tunables.copy().assign(df_config.loc[0].to_dict())\n\n def register(self, tunables: TunableGroups, status: Status,\n score: Optional[Union[float, dict]] = None) -> Optional[float]:\n score = super().register(tunables, status, score) # With _opt_sign applied\n if status.is_completed():\n # By default, hyperparameters in ConfigurationSpace are sorted by name:\n df_config = pd.DataFrame(dict(sorted(tunables.get_param_values().items())), index=[0])\n _LOG.debug(\"Score: %s Dataframe:\\n%s\", score, df_config)\n self._opt.register(df_config, pd.Series([score], dtype=float))\n self._iter += 1\n return score\n\n def get_best_observation(self) -> Union[Tuple[float, TunableGroups], Tuple[None, None]]:\n df_config = self._opt.get_best_observation()\n if len(df_config) == 0:\n return (None, None)\n params = df_config.iloc[0].to_dict()\n _LOG.debug(\"Best observation: %s\", params)\n score = params.pop(\"score\") * self._opt_sign # mlos_core always uses the `score` column\n return (score, self._tunables.copy().assign(params))\n" }, { "alpha_fraction": 0.6964892148971558, "alphanum_fraction": 0.6987542510032654, "avg_line_length": 25.75757598876953, "blob_id": "fa3a8ffbfbc30d0f2b9ee6b4d011d76c815e97e8", "content_id": "36d864d27522b92c0d45de97e14c73709cbd0c36", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 883, "license_type": "permissive", "max_line_length": 79, "num_lines": 33, "path": "/mlos_bench/mlos_bench/tests/__init__.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTests for mlos_bench.\nUsed to make mypy happy about multiple conftest.py modules.\n\"\"\"\n\nfrom typing import Optional\n\nfrom mlos_bench.util import get_class_from_name\n\n\n# A common seed to use to avoid tracking down race conditions and intermingling\n# issues of seeds across tests that run in non-deterministic parallel orders.\nSEED = 42\n\n# import numpy as np\n# np.random.seed(SEED)\n\n\ndef try_resolve_class_name(class_name: Optional[str]) -> Optional[str]:\n \"\"\"\n Gets the full class name from the given name or None on error.\n \"\"\"\n if class_name is None:\n return None\n try:\n the_class = get_class_from_name(class_name)\n return the_class.__module__ + \".\" + the_class.__name__\n except (ValueError, AttributeError, ModuleNotFoundError, ImportError):\n return None\n" }, { "alpha_fraction": 0.7466948628425598, "alphanum_fraction": 0.7466948628425598, "avg_line_length": 32.76785659790039, "blob_id": "8d2cec385b77ed866a15c67770028fa6e59117b9", "content_id": "0e312e4eb93a896b96b249b1c01fa678b77fa9b7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1891, "license_type": "permissive", "max_line_length": 118, "num_lines": 56, "path": "/mlos_bench/mlos_bench/tests/config/storage/test_load_storage_config_examples.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTests for loading storage config examples.\n\"\"\"\nimport logging\nfrom typing import List\n\nimport pytest\n\nfrom mlos_bench.tests.config import locate_config_examples\n\nfrom mlos_bench.config.schemas.config_schemas import ConfigSchema\nfrom mlos_bench.services.config_persistence import ConfigPersistenceService\nfrom mlos_bench.storage.base_storage import Storage\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\nfrom mlos_bench.util import get_class_from_name, path_join\n\n\n_LOG = logging.getLogger(__name__)\n_LOG.setLevel(logging.DEBUG)\n\n\n# Get the set of configs to test.\nCONFIG_TYPE = \"storage\"\n\n\ndef filter_configs(configs_to_filter: List[str]) -> List[str]:\n \"\"\"If necessary, filter out json files that aren't for the module we're testing.\"\"\"\n return configs_to_filter\n\n\nconfigs = filter_configs(locate_config_examples(path_join(ConfigPersistenceService.BUILTIN_CONFIG_PATH, CONFIG_TYPE)))\nassert configs\n\n\[email protected](\"config_path\", configs)\ndef test_load_storage_config_examples(config_loader_service: ConfigPersistenceService, config_path: str) -> None:\n \"\"\"Tests loading a config example.\"\"\"\n config = config_loader_service.load_config(config_path, ConfigSchema.STORAGE)\n assert isinstance(config, dict)\n # Skip schema loading that would require a database connection for this test.\n config[\"config\"][\"lazy_schema_create\"] = True\n cls = get_class_from_name(config[\"class\"])\n assert issubclass(cls, Storage)\n # Make an instance of the class based on the config.\n storage_inst = config_loader_service.build_generic(\n base_cls=Storage, # type: ignore[type-abstract]\n tunables=TunableGroups(),\n config=config,\n service=config_loader_service,\n )\n assert storage_inst is not None\n assert isinstance(storage_inst, cls)\n" }, { "alpha_fraction": 0.7230685949325562, "alphanum_fraction": 0.7265042066574097, "avg_line_length": 47.08913040161133, "blob_id": "85afa9401e8cf4e30c04ee1ba137f553f083f2dd", "content_id": "176dd41953f5bc9f458ed2ab30353edcf41f615c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 22121, "license_type": "permissive", "max_line_length": 189, "num_lines": 460, "path": "/Makefile", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nCONDA_ENV_NAME ?= mlos\nPYTHON_VERSION := $(shell echo \"${CONDA_ENV_NAME}\" | sed -r -e 's/^mlos[-]?//')\nENV_YML := conda-envs/${CONDA_ENV_NAME}.yml\n\n# Find the non-build python files we should consider as rule dependencies.\nPYTHON_FILES := $(shell find ./ -type f -name '*.py' 2>/dev/null | egrep -v -e '^./((mlos_core|mlos_bench)/)?build/' -e '^./doc/source/')\nMLOS_CORE_PYTHON_FILES := $(shell find ./mlos_core/ -type f -name '*.py' 2>/dev/null | egrep -v -e '^./mlos_core/build/')\nMLOS_BENCH_PYTHON_FILES := $(shell find ./mlos_bench/ -type f -name '*.py' 2>/dev/null | egrep -v -e '^./mlos_bench/build/')\n\nDOCKER := $(shell which docker)\n# Make sure the build directory exists.\nMKDIR_BUILD := $(shell test -d build || mkdir build)\n\n# Allow overriding the default verbosity of conda for CI jobs.\n#CONDA_INFO_LEVEL ?= -q\n\n# Run make in parallel by default.\nMAKEFLAGS += -j$(shell nproc)\n#MAKEFLAGS += -Oline\n\n.PHONY: all\nall: check test dist dist-test doc licenseheaders\n\n.PHONY: conda-env\nconda-env: build/conda-env.${CONDA_ENV_NAME}.build-stamp\n\nbuild/conda-env.${CONDA_ENV_NAME}.build-stamp: ${ENV_YML} mlos_core/setup.py mlos_bench/setup.py\n\t@echo \"CONDA_SOLVER: ${CONDA_SOLVER}\"\n\t@echo \"CONDA_EXPERIMENTAL_SOLVER: ${CONDA_EXPERIMENTAL_SOLVER}\"\n\t@echo \"CONDA_INFO_LEVEL: ${CONDA_INFO_LEVEL}\"\n\tconda env list -q | grep -q \"^${CONDA_ENV_NAME} \" || conda env create ${CONDA_INFO_LEVEL} -n ${CONDA_ENV_NAME} -f ${ENV_YML}\n\tconda env update ${CONDA_INFO_LEVEL} -n ${CONDA_ENV_NAME} --prune -f ${ENV_YML}\n\t$(MAKE) clean-check clean-test clean-doc\n\ttouch $@\n\n.PHONY: clean-conda-env\nclean-conda-env:\n\tconda env remove -y ${CONDA_INFO_LEVEL} -n ${CONDA_ENV_NAME}\n\trm -f build/conda-env.${CONDA_ENV_NAME}.build-stamp\n\n.PHONY: check\ncheck: pycodestyle pydocstyle pylint mypy # cspell licenseheaders markdown-link-check\n\n.PHONY: pycodestyle\npycodestyle: conda-env build/pycodestyle.mlos_core.${CONDA_ENV_NAME}.build-stamp build/pycodestyle.mlos_bench.${CONDA_ENV_NAME}.build-stamp\n\nbuild/pycodestyle.mlos_core.${CONDA_ENV_NAME}.build-stamp: $(MLOS_CORE_PYTHON_FILES)\nbuild/pycodestyle.mlos_bench.${CONDA_ENV_NAME}.build-stamp: $(MLOS_BENCH_PYTHON_FILES)\n\nbuild/pycodestyle.%.${CONDA_ENV_NAME}.build-stamp: build/conda-env.${CONDA_ENV_NAME}.build-stamp setup.cfg\n\t# Check for decent pep8 code style with pycodestyle.\n\t# Note: if this fails, try using autopep8 to fix it.\n\tconda run -n ${CONDA_ENV_NAME} pycodestyle $(filter-out setup.cfg,$+)\n\ttouch $@\n\n.PHONY: pydocstyle\npydocstyle: conda-env build/pydocstyle.mlos_core.${CONDA_ENV_NAME}.build-stamp build/pydocstyle.mlos_bench.${CONDA_ENV_NAME}.build-stamp\n\nbuild/pydocstyle.mlos_core.${CONDA_ENV_NAME}.build-stamp: $(MLOS_CORE_PYTHON_FILES)\nbuild/pydocstyle.mlos_bench.${CONDA_ENV_NAME}.build-stamp: $(MLOS_BENCH_PYTHON_FILES)\n\nbuild/pydocstyle.%.${CONDA_ENV_NAME}.build-stamp: build/conda-env.${CONDA_ENV_NAME}.build-stamp setup.cfg\n\t# Check for decent pep8 doc style with pydocstyle.\n\tconda run -n ${CONDA_ENV_NAME} pydocstyle $(filter-out setup.cfg,$+)\n\ttouch $@\n\n.PHONY: licenseheaders\nlicenseheaders: build/licenseheaders.${CONDA_ENV_NAME}.build-stamp\n\nbuild/licenseheaders.${CONDA_ENV_NAME}.build-stamp: $(PYTHON_FILES) doc/mit-license.tmpl\n\t# Note: to avoid makefile dependency loops, we don't touch the setup.py files as that would force the conda-env to be rebuilt.\n\tconda run -n ${CONDA_ENV_NAME} licenseheaders -t doc/mit-license.tmpl -E .py .sh .ps1 -x mlos_bench/setup.py mlos_core/setup.py\n\ttouch $@\n\n.PHONY: cspell\nifeq ($(DOCKER),)\ncspell:\n\t@echo \"NOTE: docker is not available. Skipping cspell check.\"\nelse\ncspell: build/cspell-container.build-stamp\n\t./.devcontainer/scripts/run-cspell.sh\nendif\n\nbuild/cspell-container.build-stamp:\n\t# Build the docker image with cspell in it.\n\t$(MAKE) -C .devcontainer/build cspell\n\ttouch $@\n\n.PHONY: markdown-link-check\nifeq ($(DOCKER),)\nmarkdown-link-check:\n\t@echo \"NOTE: docker is not available. Skipping markdown-link-check check.\"\nelse\nmarkdown-link-check: build/markdown-link-check-container.build-stamp\n\t./.devcontainer/scripts/run-markdown-link-check.sh\nendif\n\nbuild/markdown-link-check-container.build-stamp:\n\t# Build the docker image with markdown-link-check in it.\n\t$(MAKE) -C .devcontainer/build markdown-link-check\n\ttouch $@\n\n.PHONY: pylint\npylint: conda-env build/pylint.mlos_core.${CONDA_ENV_NAME}.build-stamp build/pylint.mlos_bench.${CONDA_ENV_NAME}.build-stamp\n\nbuild/pylint.mlos_core.${CONDA_ENV_NAME}.build-stamp: $(MLOS_CORE_PYTHON_FILES)\nbuild/pylint.mlos_bench.${CONDA_ENV_NAME}.build-stamp: $(MLOS_BENCH_PYTHON_FILES)\n\nbuild/pylint.%.${CONDA_ENV_NAME}.build-stamp: build/conda-env.${CONDA_ENV_NAME}.build-stamp .pylintrc\n\tconda run -n ${CONDA_ENV_NAME} pylint -j0 $(filter-out .pylintrc,$+)\n\ttouch $@\n\n.PHONY: flake8\nflake8: conda-env build/flake8.mlos_core.${CONDA_ENV_NAME}.build-stamp build/flake8.mlos_bench.${CONDA_ENV_NAME}.build-stamp\n\nbuild/flake8.mlos_core.${CONDA_ENV_NAME}.build-stamp: $(MLOS_CORE_PYTHON_FILES)\nbuild/flake8.mlos_bench.${CONDA_ENV_NAME}.build-stamp: $(MLOS_BENCH_PYTHON_FILES)\n\nbuild/flake8.%.${CONDA_ENV_NAME}.build-stamp: build/conda-env.${CONDA_ENV_NAME}.build-stamp setup.cfg\n\tconda run -n ${CONDA_ENV_NAME} flake8 -j0 $(filter-out setup.cfg,$+)\n\ttouch $@\n\n.PHONY: mypy\nmypy: conda-env build/mypy.mlos_core.${CONDA_ENV_NAME}.build-stamp build/mypy.mlos_bench.${CONDA_ENV_NAME}.build-stamp\n\nbuild/mypy.mlos_core.${CONDA_ENV_NAME}.build-stamp: $(MLOS_CORE_PYTHON_FILES)\nbuild/mypy.mlos_bench.${CONDA_ENV_NAME}.build-stamp: $(MLOS_BENCH_PYTHON_FILES) build/mypy.mlos_core.${CONDA_ENV_NAME}.build-stamp\n\nNON_MYPY_FILES := scripts/dmypy-wrapper.sh build/conda-env.${CONDA_ENV_NAME}.build-stamp build/mypy.mlos_core.${CONDA_ENV_NAME}.build-stamp setup.cfg\nbuild/mypy.%.${CONDA_ENV_NAME}.build-stamp: scripts/dmypy-wrapper.sh build/conda-env.${CONDA_ENV_NAME}.build-stamp setup.cfg\n\tconda run -n ${CONDA_ENV_NAME} scripts/dmypy-wrapper.sh \\\n\t\t$(filter-out $(NON_MYPY_FILES),$+)\n\ttouch $@\n\n\n.PHONY: test\ntest: pytest\n\nPYTEST_MODULES :=\n\n.PHONY: pytest\npytest: conda-env build/pytest.${CONDA_ENV_NAME}.build-stamp\n\nbuild/pytest.mlos_core.${CONDA_ENV_NAME}.needs-build-stamp: build/conda-env.${CONDA_ENV_NAME}.build-stamp\nbuild/pytest.mlos_core.${CONDA_ENV_NAME}.needs-build-stamp: $(MLOS_CORE_PYTHON_FILES) conftest.py setup.cfg\nbuild/pytest.mlos_core.${CONDA_ENV_NAME}.needs-build-stamp:\n\t# Update the PYTEST_MODULES list to include mlos_core.\n\t$(eval PYTEST_MODULES += mlos_core)\n\techo \"PYTEST_MODULES: $(PYTEST_MODULES)\"\n\ttouch $@\n\n# Run the mlos_bench target update after mlos_core target update.\nbuild/pytest.mlos_bench.${CONDA_ENV_NAME}.needs-build-stamp: build/pytest.mlos_core.${CONDA_ENV_NAME}.needs-build-stamp\nbuild/pytest.mlos_bench.${CONDA_ENV_NAME}.needs-build-stamp: build/conda-env.${CONDA_ENV_NAME}.build-stamp\nbuild/pytest.mlos_bench.${CONDA_ENV_NAME}.needs-build-stamp: $(MLOS_BENCH_PYTHON_FILES) conftest.py setup.cfg\nbuild/pytest.mlos_bench.${CONDA_ENV_NAME}.needs-build-stamp:\n\t# Update the PYTEST_MODULES list to include mlos_bench.\n\t$(eval PYTEST_MODULES += mlos_bench)\n\techo \"PYTEST_MODULES: $(PYTEST_MODULES)\"\n\ttouch $@\n\nPYTEST_OPTIONS :=\n\n# Allow optionally skipping coverage calculations during local testing to skip up inner dev loop.\nSKIP_COVERAGE := $(shell echo $${SKIP_COVERAGE:-} | grep -i -x -e 1 -e true)\n\nifeq ($(SKIP_COVERAGE),)\n PYTEST_OPTIONS += --cov=. --cov-append --cov-fail-under=0.8 --cov-report=xml --cov-report=html --junitxml=junit/test-results.xml --local-badge-output-dir=doc/source/badges/\nendif\n\n# Run the pytest target on only the modules that have changed recently, but\n# make sure the coverage report is for both of them when used in the pipeline.\n# NOTE: When run locally, the junit/test-results.xml will only include the\n# tests from the latest run, but this file is only used for upstream reporting,\n# so probably shouldn't matter.\nbuild/pytest.${CONDA_ENV_NAME}.build-stamp: build/pytest.mlos_core.${CONDA_ENV_NAME}.needs-build-stamp build/pytest.mlos_bench.${CONDA_ENV_NAME}.needs-build-stamp\n\t# Make sure to update the list of modules needed everytime in case the test fails and we need to rerun it.\n\tfor pytest_module in $(PYTEST_MODULES); do rm -f build/pytest.$${pytest_module}.${CONDA_ENV_NAME}.needs-build-stamp; done\n\t# Run pytest for the modules: $(PYTEST_MODULES)\n\tmkdir -p doc/source/badges/\n\tconda run -n ${CONDA_ENV_NAME} pytest $(PYTEST_OPTIONS) $(PYTEST_MODULES)\n\t# Mark those as done again.\n\tfor pytest_module in $(PYTEST_MODULES); do touch build/pytest.$${pytest_module}.${CONDA_ENV_NAME}.needs-build-stamp; done\n\ttouch $@\n\n\n.PHONY: dist\ndist: bdist_wheel\n\n.PHONY: bdist_wheel\nbdist_wheel: conda-env mlos_core/dist/tmp/mlos_core-latest-py3-none-any.whl mlos_bench/dist/tmp/mlos_bench-latest-py3-none-any.whl\n\nmlos_core/dist/tmp/mlos_core-latest-py3-none-any.whl: mlos_core/dist/tmp/mlos-core-latest.tar\nmlos_core/dist/tmp/mlos_core-latest-py3-none-any.whl: MODULE_NAME := mlos_core\nmlos_core/dist/tmp/mlos_core-latest-py3-none-any.whl: PACKAGE_NAME := mlos-core\nmlos_core/dist/tmp/mlos-core-latest.tar: mlos_core/setup.py mlos_core/MANIFEST.in $(MLOS_CORE_PYTHON_FILES)\nmlos_core/dist/tmp/mlos-core-latest.tar: MODULE_NAME := mlos_core\nmlos_core/dist/tmp/mlos-core-latest.tar: PACKAGE_NAME := mlos-core\n\nmlos_bench/dist/tmp/mlos_bench-latest-py3-none-any.whl: mlos_bench/dist/tmp/mlos-bench-latest.tar\nmlos_bench/dist/tmp/mlos_bench-latest-py3-none-any.whl: MODULE_NAME := mlos_bench\nmlos_bench/dist/tmp/mlos_bench-latest-py3-none-any.whl: PACKAGE_NAME := mlos-bench\nmlos_bench/dist/tmp/mlos-bench-latest.tar: mlos_bench/setup.py mlos_bench/MANIFEST.in $(MLOS_BENCH_PYTHON_FILES)\nmlos_bench/dist/tmp/mlos-bench-latest.tar: MODULE_NAME := mlos_bench\nmlos_bench/dist/tmp/mlos-bench-latest.tar: PACKAGE_NAME := mlos-bench\n\n%-latest.tar: build/conda-env.${CONDA_ENV_NAME}.build-stamp\n%-latest.tar:\n\tmkdir -p $(MODULE_NAME)/dist/tmp\n\trm -f $(MODULE_NAME)/dist/$(PACKAGE_NAME)-*.tar\n\trm -f $(MODULE_NAME)/dist/tmp/$(PACKAGE_NAME)-latest.tar\n\tcd $(MODULE_NAME)/ && conda run -n ${CONDA_ENV_NAME} python3 setup.py sdist --formats tar\n\tls $(MODULE_NAME)/dist/$(PACKAGE_NAME)-*.tar\n\t! ( tar tf $(MODULE_NAME)/dist/$(PACKAGE_NAME)-*.tar | grep -m1 tests/ )\n\t[ \"$(MODULE_NAME)\" != \"mlos_bench\" ] || tar tf $(MODULE_NAME)/dist/$(PACKAGE_NAME)-*.tar | grep -m1 mlos_bench/config/\n\tcd $(MODULE_NAME)/dist/tmp && ln -s ../$(PACKAGE_NAME)-*.tar $(PACKAGE_NAME)-latest.tar\n\n%-latest-py3-none-any.whl: build/conda-env.${CONDA_ENV_NAME}.build-stamp\n%-latest-py3-none-any.whl:\n\trm -f $(MODULE_NAME)/dist/$(MODULE_NAME)-*-py3-none-any.whl\n\trm -f $(MODULE_NAME)/dist/tmp/$(MODULE_NAME)-latest-py3-none-any.whl\n\tcd $(MODULE_NAME)/ && conda run -n ${CONDA_ENV_NAME} pip wheel --no-index --no-deps --wheel-dir dist dist/tmp/$(PACKAGE_NAME)-latest.tar\n\tls $(MODULE_NAME)/dist/$(MODULE_NAME)-*-py3-none-any.whl\n\t# Check to make sure the tests were excluded from the wheel.\n\t! ( unzip -t $(MODULE_NAME)/dist/$(MODULE_NAME)-*-py3-none-any.whl | grep -m1 tests/ )\n\t# Check to make sure the mlos_bench module has the config directory.\n\t[ \"$(MODULE_NAME)\" != \"mlos_bench\" ] || unzip -t $(MODULE_NAME)/dist/$(MODULE_NAME)-*-py3-none-any.whl | grep -m1 mlos_bench/config/\n\tcd $(MODULE_NAME)/dist/tmp && ln -s ../$(MODULE_NAME)-*-py3-none-any.whl $(MODULE_NAME)-latest-py3-none-any.whl\n\n.PHONY: dist-test-env-clean\ndist-test-env-clean:\n\t# Remove any existing mlos-dist-test environment so we can start clean.\n\tconda env remove -y ${CONDA_INFO_LEVEL} -n mlos-dist-test-$(PYTHON_VERSION) 2>/dev/null || true\n\trm -f build/dist-test-env.$(PYTHON_VERSION).build-stamp\n\n.PHONY: dist-test-env\ndist-test-env: dist build/dist-test-env.$(PYTHON_VERSION).build-stamp\n\nbuild/dist-test-env.$(PYTHON_VERSION).build-stamp: build/conda-env.${CONDA_ENV_NAME}.build-stamp\n# Use the same version of python as the one we used to build the wheels.\nbuild/dist-test-env.$(PYTHON_VERSION).build-stamp: PYTHON_VERS_REQ=$(shell conda list -n ${CONDA_ENV_NAME} | egrep '^python\\s+' | sed -r -e 's/^python\\s+//' | cut -d' ' -f1 | cut -d. -f1-2)\nbuild/dist-test-env.$(PYTHON_VERSION).build-stamp: mlos_core/dist/tmp/mlos_core-latest-py3-none-any.whl mlos_bench/dist/tmp/mlos_bench-latest-py3-none-any.whl\n\t# Create a clean test environment for checking the wheel files.\n\t$(MAKE) dist-test-env-clean\n\tconda create -y ${CONDA_INFO_LEVEL} -n mlos-dist-test-$(PYTHON_VERSION) python=$(PYTHON_VERS_REQ)\n\t# Test a clean install of the mlos_core wheel.\n\tconda run -n mlos-dist-test-$(PYTHON_VERSION) pip install \"mlos_core/dist/tmp/mlos_core-latest-py3-none-any.whl[full-tests]\"\n\t# Test a clean install of the mlos_bench wheel.\n\tconda run -n mlos-dist-test-$(PYTHON_VERSION) pip install \"mlos_bench/dist/tmp/mlos_bench-latest-py3-none-any.whl[full-tests]\"\n\t# Test that the config dir for mlos_bench got distributed.\n\ttest -e `conda env list | grep \"mlos-dist-test-$(PYTHON_VERSION) \" | awk '{ print $$2 }'`/lib/python$(PYTHON_VERS_REQ)/site-packages/mlos_bench/config/README.md\n\ttouch $@\n\n.PHONY: dist-test\n#dist-test: dist-clean\ndist-test: dist-test-env build/dist-test.$(PYTHON_VERSION).build-stamp\n\n# Unnecessary if we invoke it as \"python3 -m pytest ...\"\nbuild/dist-test.$(PYTHON_VERSION).build-stamp: $(PYTHON_FILES) build/dist-test-env.$(PYTHON_VERSION).build-stamp\n\t# Make sure we're using the packages from the wheel.\n\t# Note: this will pick up the local directory and change the output if we're using PYTHONPATH=.\n\tconda run -n mlos-dist-test-$(PYTHON_VERSION) pip list --verbose | grep mlos-core | grep ' pip'\n\tconda run -n mlos-dist-test-$(PYTHON_VERSION) pip list --verbose | grep mlos-bench | grep ' pip'\n\t# Run a simple test that uses the mlos_core wheel (full tests can be checked with `make test`).\n\tconda run -n mlos-dist-test-$(PYTHON_VERSION) python3 -m pytest mlos_core/mlos_core/tests/spaces/spaces_test.py\n\t# Run a simple test that uses the mlos_bench wheel (full tests can be checked with `make test`).\n\tconda run -n mlos-dist-test-$(PYTHON_VERSION) python3 -m pytest mlos_bench/mlos_bench/tests/environments/mock_env_test.py\n\ttouch $@\n\ndist-test-clean: dist-test-env-clean\n\trm -f build/dist-test-env.$(PYTHON_VERSION).build-stamp\n\n\nbuild/doc-prereqs.${CONDA_ENV_NAME}.build-stamp: build/conda-env.${CONDA_ENV_NAME}.build-stamp\nbuild/doc-prereqs.${CONDA_ENV_NAME}.build-stamp: doc/requirements.txt\n\tconda run -n ${CONDA_ENV_NAME} pip install -U -r doc/requirements.txt\n\ttouch $@\n\n.PHONY: doc-prereqs\ndoc-prereqs: build/doc-prereqs.${CONDA_ENV_NAME}.build-stamp\n\n.PHONY: clean-doc-env\nclean-doc-env:\n\trm -f build/doc-prereqs.build-stamp\n\trm -f build/doc-prereqs.${CONDA_ENV_NAME}.build-stamp\n\nCOMMON_DOC_FILES := build/doc-prereqs.${CONDA_ENV_NAME}.build-stamp doc/source/*.rst doc/source/_templates/*.rst doc/source/conf.py\n\ndoc/source/api/mlos_core/modules.rst: $(MLOS_CORE_PYTHON_FILES) $(COMMON_DOC_FILES)\n\trm -rf doc/source/api/mlos_core\n\tcd doc/ && conda run -n ${CONDA_ENV_NAME} sphinx-apidoc -f -e -M -o source/api/mlos_core/ ../mlos_core/ ../mlos_*/setup.py\n\ndoc/source/api/mlos_bench/modules.rst: $(MLOS_BENCH_PYTHON_FILES) $(COMMON_DOC_FILES)\n\trm -rf doc/source/api/mlos_bench\n\tcd doc/ && conda run -n ${CONDA_ENV_NAME} sphinx-apidoc -f -e -M -o source/api/mlos_bench/ ../mlos_bench/ ../mlos_*/setup.py\n\t# Save the help output of the mlos_bench scripts to include in the documentation.\n\t# First make sure that the latest version of mlos_bench is installed (since it uses git based tagging).\n\tconda run -n ${CONDA_ENV_NAME} pip install -e mlos_core -e mlos_bench\n\tconda run -n ${CONDA_ENV_NAME} mlos_bench --help > doc/source/api/mlos_bench/mlos_bench.run.usage.txt\n\techo \".. literalinclude:: mlos_bench.run.usage.txt\" >> doc/source/api/mlos_bench/mlos_bench.run.rst\n\techo \" :language: none\" >> doc/source/api/mlos_bench/mlos_bench.run.rst\n\nSPHINX_API_RST_FILES := doc/source/api/mlos_core/modules.rst doc/source/api/mlos_bench/modules.rst\n\n.PHONY: sphinx-apidoc\nsphinx-apidoc: $(SPHINX_API_RST_FILES)\n\nifeq ($(SKIP_COVERAGE),)\ndoc/build/html/index.html: build/pytest.${CONDA_ENV_NAME}.build-stamp\ndoc/build/html/htmlcov/index.html: build/pytest.${CONDA_ENV_NAME}.build-stamp\nendif\n\ndoc/build/html/index.html: $(SPHINX_API_RST_FILES) doc/Makefile\n\t@rm -rf doc/build\n\t@mkdir -p doc/build\n\t@rm -f doc/build/log.txt\n\n\t# Make sure that at least placeholder doc badges are there.\n\tmkdir -p doc/source/badges/\n\ttouch doc/source/badges/coverage.svg\n\ttouch doc/source/badges/tests.svg\n\n\t# Build the rst files into html.\n\tconda run -n ${CONDA_ENV_NAME} $(MAKE) -C doc/ $(MAKEFLAGS) html \\\n\t\t>> doc/build/log.txt 2>&1 \\\n\t\t|| { cat doc/build/log.txt; exit 1; }\n\t# DONE: Add some output filtering for this so we can more easily see what went wrong.\n\t# (e.g. skip complaints about missing .examples files)\n\t# See check-doc\n\n.PHONY: doc\ndoc: doc/build/html/.nojekyll build/check-doc.build-stamp build/linklint-doc.build-stamp\n\ndoc/build/html/htmlcov/index.html: doc/build/html/index.html\n\t# Make the codecov html report available for the site.\n\ttest -d htmlcov && cp -a htmlcov doc/build/html/ || true\n\tmkdir -p doc/build/html/htmlcov\n\ttouch doc/build/html/htmlcov/index.html\n\ndoc/build/html/.nojekyll: doc/build/html/index.html doc/build/html/htmlcov/index.html\n\t# Make sure that github pages doesn't try to run jekyll on the docs.\n\ttouch doc/build/html/.nojekyll\n\n.PHONY: check-doc\ncheck-doc: build/check-doc.build-stamp\n\nbuild/check-doc.build-stamp: doc/build/html/index.html doc/build/html/htmlcov/index.html\n\t# Check for a few files to make sure the docs got generated in a way we want.\n\ttest -s doc/build/html/index.html\n\ttest -s doc/build/html/generated/mlos_core.optimizers.optimizer.BaseOptimizer.html\n\ttest -s doc/build/html/generated/mlos_bench.environments.Environment.html\n\ttest -s doc/build/html/api/mlos_core/mlos_core.html\n\ttest -s doc/build/html/api/mlos_bench/mlos_bench.html\n\tgrep -q -e '--config CONFIG' doc/build/html/api/mlos_bench/mlos_bench.run.html\n\t# Check doc logs for errors (but skip over some known ones) ...\n\t@cat doc/build/log.txt \\\n\t\t| egrep -C1 -e WARNING -e CRITICAL -e ERROR \\\n\t\t| egrep -v \\\n\t\t\t-e \"warnings.warn\\(f'\\\"{wd.path}\\\" is shallow and may cause errors'\\)\" \\\n\t\t\t-e \"No such file or directory: '.*.examples'.$$\" \\\n\t\t\t-e 'Problems with \"include\" directive path:' \\\n\t\t\t-e 'duplicate object description' \\\n\t\t\t-e \"document isn't included in any toctree\" \\\n\t\t\t-e \"more than one target found for cross-reference\" \\\n\t\t\t-e \"toctree contains reference to nonexisting document 'auto_examples/index'\" \\\n\t\t\t-e \"failed to import function 'create' from module '(SpaceAdapter|Optimizer)Factory'\" \\\n\t\t\t-e \"No module named '(SpaceAdapter|Optimizer)Factory'\" \\\n\t\t\t-e '^make.*resetting jobserver mode' \\\n\t\t| grep -v '^\\s*$$' \\\n\t\t| if grep .; then echo \"Errors found in doc build. Check doc/build/log.txt for details.\"; exit 1; else exit 0; fi\n\ttouch $@\n\n.PHONY: linklint-doc\nifeq ($(DOCKER),)\nlinklint-doc:\n\t@echo \"NOTE: linklint-doc target requires docker.\"\nelse\nlinklint-doc: build/linklint-doc.build-stamp\nendif\n\nbuild/linklint-doc.build-stamp: doc/build/html/index.html doc/build/html/htmlcov/index.html build/check-doc.build-stamp\n\t@echo \"Starting nginx docker container for serving docs.\"\n\t./doc/nginx-docker.sh restart\n\tdocker port mlos-doc-nginx\n\tnginx_port=`docker port mlos-doc-nginx | grep 0.0.0.0:8080 | cut -d/ -f1` \\\n\t\t&& echo nginx_port=$${nginx_port} \\\n\t\t&& set -x \\\n\t\t&& docker exec mlos-doc-nginx curl -sSf http://localhost:$${nginx_port}/index.html >/dev/null\n\t@echo \"Running linklint on the docs.\"\n\tdocker exec mlos-doc-nginx linklint -net -redirect -root /doc/build/html/ /@ -error -warn > doc/build/linklint.out 2>&1\n\t@if cat doc/build/linklint.out | grep -e ^ERROR -e ^WARN | grep -v 'missing named anchors' | grep -q .; then \\\n\t\techo \"Found errors in the documentation:\"; cat doc/build/linklint.out; exit 1; \\\n\tfi\n\t@echo \"OK\"\n\ttouch $@\n\n.PHONY: clean-doc\nclean-doc:\n\trm -rf doc/build/ doc/global/ doc/source/api/ doc/source/generated\n\n\n.PHONY: clean-check\nclean-check:\n\trm -f build/pylint.build-stamp\n\trm -f build/pylint.${CONDA_ENV_NAME}.build-stamp\n\trm -f build/pylint.mlos_core.${CONDA_ENV_NAME}.build-stamp\n\trm -f build/pylint.mlos_bench.${CONDA_ENV_NAME}.build-stamp\n\trm -f build/mypy.mlos_core.${CONDA_ENV_NAME}.build-stamp\n\trm -f build/mypy.mlos_bench.${CONDA_ENV_NAME}.build-stamp\n\trm -f build/pycodestyle.build-stamp\n\trm -f build/pycodestyle.${CONDA_ENV_NAME}.build-stamp\n\trm -f build/pycodestyle.mlos_core.${CONDA_ENV_NAME}.build-stamp\n\trm -f build/pycodestyle.mlos_bench.${CONDA_ENV_NAME}.build-stamp\n\trm -f build/pydocstyle.build-stamp\n\trm -f build/pydocstyle.${CONDA_ENV_NAME}.build-stamp\n\trm -f build/pydocstyle.mlos_core.${CONDA_ENV_NAME}.build-stamp\n\trm -f build/pydocstyle.mlos_bench.${CONDA_ENV_NAME}.build-stamp\n\trm -f build/licenseheaders.${CONDA_ENV_NAME}.build-stamp\n\trm -f build/licenseheaders-prereqs.${CONDA_ENV_NAME}.build-stamp\n\n.PHONY: clean-test\nclean-test:\n\trm -f build/pytest.build-stamp\n\trm -f build/pytest.${CONDA_ENV_NAME}.build-stamp\n\trm -f build/pytest.mlos_core.${CONDA_ENV_NAME}.build-stamp\n\trm -f build/pytest.mlos_bench.${CONDA_ENV_NAME}.build-stamp\n\trm -f build/pytest.mlos_core.${CONDA_ENV_NAME}.needs-build-stamp\n\trm -f build/pytest.mlos_bench.${CONDA_ENV_NAME}.needs-build-stamp\n\trm -rf .pytest_cache/\n\trm -f coverage.xml .coverage* build/.converage*\n\trm -rf htmlcov/\n\trm -rf junit/\n\trm -rf test-output.xml\n\n.PHONY: dist-clean\ndist-clean:\n\trm -rf build dist\n\trm -rf mlos_core/build mlos_core/dist\n\trm -rf mlos_bench/build mlos_bench/dist\n\n.PHONY: clean\nclean: clean-check clean-test dist-clean clean-doc clean-doc-env dist-test-clean\n\trm -f .*.build-stamp\n\trm -f build/conda-env.build-stamp build/conda-env.*.build-stamp\n\trm -rf mlos_core.egg-info\n\trm -rf mlos_core/mlos_core.egg-info\n\trm -rf mlos_bench.egg-info\n\trm -rf mlos_bench/mlos_bench.egg-info\n\trm -rf __pycache__\n\tfind . -type d -name __pycache__ -print0 | xargs -t -r -0 rm -rf\n\tfind . -type f -name '*.pyc' -print0 | xargs -t -r -0 rm -f\n\n.PHONY: devcontainer\ndevcontainer:\n\t./.devcontainer/build/build-devcontainer.sh\n\t@echo\n\t@echo \"Run ./.devcontainer/scripts/run-devcontainer.sh to start the newly built devcontainer.\"\n" }, { "alpha_fraction": 0.7580645084381104, "alphanum_fraction": 0.7580645084381104, "avg_line_length": 22.25, "blob_id": "d766a179d011a20f3916d82e09d56047cf2306bd", "content_id": "1fed310b78e9dc477d660bbb1eb55780ab9f0129", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 186, "license_type": "permissive", "max_line_length": 63, "num_lines": 8, "path": "/mlos_bench/mlos_bench/__init__.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nmlos_bench is a framework to help automate benchmarking and and\nOS/application parameter autotuning.\n\"\"\"\n" }, { "alpha_fraction": 0.6530612111091614, "alphanum_fraction": 0.6530612111091614, "avg_line_length": 20.30434799194336, "blob_id": "b784ab1d4432b8f999de11e50c0025f194b482a4", "content_id": "d86cbdf2a3457f7edf95040be81636494717a817", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 490, "license_type": "permissive", "max_line_length": 71, "num_lines": 23, "path": "/mlos_bench/mlos_bench/tests/services/remote/mock/__init__.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nMock remote services for testing purposes.\n\"\"\"\n\nfrom typing import Any, Tuple\n\nfrom mlos_bench.environments.status import Status\n\n\ndef mock_operation(*_args: Any, **_kwargs: Any) -> Tuple[Status, dict]:\n \"\"\"\n Mock VM operation that always succeeds.\n\n Returns\n -------\n result : (Status, dict)\n A pair of Status and result, always (SUCCEEDED, {}).\n \"\"\"\n return Status.SUCCEEDED, {}\n" }, { "alpha_fraction": 0.6034232378005981, "alphanum_fraction": 0.6321439146995544, "avg_line_length": 30.336362838745117, "blob_id": "52eb0489b9c7b73cfbabeb213bbd5983708a67ef", "content_id": "5f186d4596f64da0f50849ad3fd05d3c2164910a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3447, "license_type": "permissive", "max_line_length": 92, "num_lines": 110, "path": "/mlos_bench/mlos_bench/tests/optimizers/mock_opt_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nUnit tests for mock mlos_bench optimizer.\n\"\"\"\n\nimport pytest\n\nfrom mlos_bench.environments.status import Status\nfrom mlos_bench.optimizers.mock_optimizer import MockOptimizer\n\n# pylint: disable=redefined-outer-name\n\n\[email protected]\ndef mock_configurations_no_defaults() -> list:\n \"\"\"\n A list of 2-tuples of (tunable_values, score) to test the optimizers.\n \"\"\"\n return [\n ({\n \"vmSize\": \"Standard_B4ms\",\n \"idle\": \"halt\",\n \"kernel_sched_migration_cost_ns\": 13111,\n \"kernel_sched_latency_ns\": 796233790,\n }, 88.88),\n ({\n \"vmSize\": \"Standard_B2ms\",\n \"idle\": \"halt\",\n \"kernel_sched_migration_cost_ns\": 117025,\n \"kernel_sched_latency_ns\": 149827706,\n }, 66.66),\n ({\n \"vmSize\": \"Standard_B4ms\",\n \"idle\": \"halt\",\n \"kernel_sched_migration_cost_ns\": 354784,\n \"kernel_sched_latency_ns\": 795285932,\n }, 99.99),\n ]\n\n\[email protected]\ndef mock_configurations(mock_configurations_no_defaults: list) -> list:\n \"\"\"\n A list of 2-tuples of (tunable_values, score) to test the optimizers.\n \"\"\"\n return [\n ({\n \"vmSize\": \"Standard_B4ms\",\n \"idle\": \"halt\",\n \"kernel_sched_migration_cost_ns\": -1,\n \"kernel_sched_latency_ns\": 2000000,\n }, 88.88),\n ] + mock_configurations_no_defaults\n\n\ndef _optimize(mock_opt: MockOptimizer, mock_configurations: list) -> float:\n \"\"\"\n Run several iterations of the optimizer and return the best score.\n \"\"\"\n for (tunable_values, score) in mock_configurations:\n assert mock_opt.not_converged()\n tunables = mock_opt.suggest()\n assert tunables.get_param_values() == tunable_values\n mock_opt.register(tunables, Status.SUCCEEDED, score)\n\n (score, _tunables) = mock_opt.get_best_observation()\n assert score is not None\n assert isinstance(score, float)\n return score\n\n\ndef test_mock_optimizer(mock_opt: MockOptimizer, mock_configurations: list) -> None:\n \"\"\"\n Make sure that mock optimizer produces consistent suggestions.\n \"\"\"\n score = _optimize(mock_opt, mock_configurations)\n assert score == pytest.approx(66.66, 0.01)\n\n\ndef test_mock_optimizer_no_defaults(mock_opt_no_defaults: MockOptimizer,\n mock_configurations_no_defaults: list) -> None:\n \"\"\"\n Make sure that mock optimizer produces consistent suggestions.\n \"\"\"\n score = _optimize(mock_opt_no_defaults, mock_configurations_no_defaults)\n assert score == pytest.approx(66.66, 0.01)\n\n\ndef test_mock_optimizer_max(mock_opt_max: MockOptimizer, mock_configurations: list) -> None:\n \"\"\"\n Check the maximization mode of the mock optimizer.\n \"\"\"\n score = _optimize(mock_opt_max, mock_configurations)\n assert score == pytest.approx(99.99, 0.01)\n\n\ndef test_mock_optimizer_register_fail(mock_opt: MockOptimizer) -> None:\n \"\"\"\n Check the input acceptance conditions for Optimizer.register().\n \"\"\"\n tunables = mock_opt.suggest()\n mock_opt.register(tunables, Status.SUCCEEDED, 10)\n mock_opt.register(tunables, Status.FAILED)\n with pytest.raises(ValueError):\n mock_opt.register(tunables, Status.SUCCEEDED, None)\n with pytest.raises(ValueError):\n mock_opt.register(tunables, Status.FAILED, 10)\n" }, { "alpha_fraction": 0.6642201542854309, "alphanum_fraction": 0.6715596318244934, "avg_line_length": 26.25, "blob_id": "a004b9aeb8ba25e62e05858378708beed3e1e105", "content_id": "54946fca6eb49d0d78a23543c406ac8ab34d73dc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 545, "license_type": "permissive", "max_line_length": 79, "num_lines": 20, "path": "/mlos_bench/mlos_bench/tests/util_git_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nUnit tests for get_git_info utility function.\n\"\"\"\nimport re\n\nfrom mlos_bench.util import get_git_info\n\n\ndef test_get_git_info() -> None:\n \"\"\"\n Check that we can retrieve git info about the current repository correctly.\n \"\"\"\n (git_repo, git_commit, rel_path) = get_git_info(__file__)\n assert \"mlos\" in git_repo.lower()\n assert re.match(r\"[0-9a-f]{40}\", git_commit) is not None\n assert rel_path == \"mlos_bench/mlos_bench/tests/util_git_test.py\"\n" }, { "alpha_fraction": 0.6466611623764038, "alphanum_fraction": 0.6472130417823792, "avg_line_length": 37.967742919921875, "blob_id": "41e91d68405f1cc32580055d3803a12d64e9da5e", "content_id": "c7ca4fd06a5d798d2736f7447f58ec87ee1fb712", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7248, "license_type": "permissive", "max_line_length": 122, "num_lines": 186, "path": "/mlos_core/mlos_core/optimizers/flaml_optimizer.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nContains the FlamlOptimizer class.\n\"\"\"\n\nfrom typing import Dict, NamedTuple, Optional, Union\nfrom warnings import warn\n\nimport ConfigSpace\nimport numpy as np\nimport pandas as pd\n\nfrom mlos_core.optimizers.optimizer import BaseOptimizer\nfrom mlos_core.spaces.adapters.adapter import BaseSpaceAdapter\n\n\nclass EvaluatedSample(NamedTuple):\n \"\"\"A named tuple representing a sample that has been evaluated.\"\"\"\n\n config: dict\n score: float\n\n\nclass FlamlOptimizer(BaseOptimizer):\n \"\"\"Wrapper class for FLAML Optimizer: A fast library for AutoML and tuning.\n\n Parameters\n ----------\n parameter_space : ConfigSpace.ConfigurationSpace\n The parameter space to optimize.\n\n space_adapter : BaseSpaceAdapter\n The space adapter class to employ for parameter space transformations.\n\n low_cost_partial_config : dict\n A dictionary from a subset of controlled dimensions to the initial low-cost values.\n More info: https://microsoft.github.io/FLAML/docs/FAQ#about-low_cost_partial_config-in-tune\n\n seed : Optional[int]\n If provided, calls np.random.seed() with the provided value to set the seed globally at init.\n \"\"\"\n\n def __init__(self, *,\n parameter_space: ConfigSpace.ConfigurationSpace,\n space_adapter: Optional[BaseSpaceAdapter] = None,\n low_cost_partial_config: Optional[dict] = None,\n seed: Optional[int] = None):\n\n super().__init__(\n parameter_space=parameter_space,\n space_adapter=space_adapter,\n )\n\n # Per upstream documentation, it is recommended to set the seed for\n # flaml at the start of its operation globally.\n if seed is not None:\n np.random.seed(seed)\n\n # pylint: disable=import-outside-toplevel\n from mlos_core.spaces.converters.flaml import configspace_to_flaml_space, FlamlDomain\n\n self.flaml_parameter_space: Dict[str, FlamlDomain] = configspace_to_flaml_space(self.optimizer_parameter_space)\n self.low_cost_partial_config = low_cost_partial_config\n\n self.evaluated_samples: Dict[ConfigSpace.Configuration, EvaluatedSample] = {}\n self._suggested_config: Optional[dict]\n\n def _register(self, configurations: pd.DataFrame, scores: pd.Series,\n context: Optional[pd.DataFrame] = None) -> None:\n \"\"\"Registers the given configurations and scores.\n\n Parameters\n ----------\n configurations : pd.DataFrame\n Dataframe of configurations / parameters. The columns are parameter names and the rows are the configurations.\n\n scores : pd.Series\n Scores from running the configurations. The index is the same as the index of the configurations.\n\n context : None\n Not Yet Implemented.\n \"\"\"\n if context is not None:\n raise NotImplementedError()\n for (_, config), score in zip(configurations.iterrows(), scores):\n cs_config: ConfigSpace.Configuration = ConfigSpace.Configuration(\n self.optimizer_parameter_space, values=config.to_dict())\n if cs_config in self.evaluated_samples:\n warn(f\"Configuration {config} was already registered\", UserWarning)\n\n self.evaluated_samples[cs_config] = EvaluatedSample(config=config.to_dict(), score=score)\n\n def _suggest(self, context: Optional[pd.DataFrame] = None) -> pd.DataFrame:\n \"\"\"Suggests a new configuration.\n\n Sampled at random using ConfigSpace.\n\n Parameters\n ----------\n context : None\n Not Yet Implemented.\n\n Returns\n -------\n configuration : pd.DataFrame\n Pandas dataframe with a single row. Column names are the parameter names.\n \"\"\"\n if context is not None:\n raise NotImplementedError()\n config: dict = self._get_next_config()\n return pd.DataFrame(config, index=[0])\n\n def register_pending(self, configurations: pd.DataFrame,\n context: Optional[pd.DataFrame] = None) -> None:\n raise NotImplementedError()\n\n def _target_function(self, config: dict) -> Union[dict, None]:\n \"\"\"Configuration evaluation function called by FLAML optimizer.\n\n FLAML may suggest the same configuration multiple times (due to its warm-start mechanism).\n Once FLAML suggests an unseen configuration, we store it, and stop the optimization process.\n\n Parameters\n ----------\n config: dict\n Next configuration to be evaluated, as suggested by FLAML.\n This config is stored internally and is returned to user, via `.suggest()` method.\n\n Returns\n -------\n result: Union[dict, None]\n Dictionary with a single key, `score`, if config already evaluated; `None` otherwise.\n \"\"\"\n cs_config: ConfigSpace.Configuration = ConfigSpace.Configuration(self.optimizer_parameter_space, values=config)\n if cs_config in self.evaluated_samples:\n return {'score': self.evaluated_samples[cs_config].score}\n\n self._suggested_config = config\n return None # Returning None stops the process\n\n def _get_next_config(self) -> dict:\n \"\"\"Warm-starts a new instance of FLAML, and returns a recommended, unseen new configuration.\n\n Since FLAML does not provide an ask-and-tell interface, we need to create a new instance of FLAML\n each time we get asked for a new suggestion. This is suboptimal performance-wise, but works.\n To do so, we use any previously evaluated configurations to bootstrap FLAML (i.e., warm-start).\n For more info: https://microsoft.github.io/FLAML/docs/Use-Cases/Tune-User-Defined-Function#warm-start\n\n Returns\n -------\n result: dict\n Dictionary with a single key, `score`, if config already evaluated; `None` otherwise.\n\n Raises\n ------\n RuntimeError: if FLAML did not suggest a previously unseen configuration.\n \"\"\"\n from flaml import tune # pylint: disable=import-outside-toplevel\n\n # Parse evaluated configs to format used by FLAML\n points_to_evaluate: list = []\n evaluated_rewards: list = []\n if len(self.evaluated_samples) > 0:\n evaluated_samples_list: list = [(s.config, s.score) for s in self.evaluated_samples.values()]\n points_to_evaluate, evaluated_rewards = list(zip(*evaluated_samples_list))\n\n # Warm start FLAML optimizer\n self._suggested_config = None\n tune.run(\n self._target_function,\n config=self.flaml_parameter_space,\n mode='min',\n metric='score',\n points_to_evaluate=list(points_to_evaluate),\n evaluated_rewards=list(evaluated_rewards),\n num_samples=len(points_to_evaluate) + 1,\n low_cost_partial_config=self.low_cost_partial_config,\n verbose=0,\n )\n if self._suggested_config is None:\n raise RuntimeError('FLAML did not produce a suggestion')\n\n return self._suggested_config # type: ignore[unreachable]\n" }, { "alpha_fraction": 0.58971107006073, "alphanum_fraction": 0.591231644153595, "avg_line_length": 35.3686637878418, "blob_id": "acaa17f0a4d77aa1ab216465d34722bc751dd848", "content_id": "b2b48ce6f01e0ca66e489f8541ab55d0dd717af0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7892, "license_type": "permissive", "max_line_length": 92, "num_lines": 217, "path": "/mlos_bench/mlos_bench/services/local/local_exec.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nHelper functions to run scripts and commands locally on the scheduler side.\n\"\"\"\n\nimport errno\nimport logging\nimport os\nimport shlex\nimport subprocess\nimport sys\n\nfrom typing import Any, Dict, Iterable, List, Mapping, Optional, Tuple, TYPE_CHECKING\n\nfrom mlos_bench.services.base_service import Service\nfrom mlos_bench.services.local.temp_dir_context import TempDirContextService\nfrom mlos_bench.services.types.local_exec_type import SupportsLocalExec\n\nif TYPE_CHECKING:\n from mlos_bench.tunables.tunable import TunableValue\n\n_LOG = logging.getLogger(__name__)\n\n\ndef split_cmdline(cmdline: str) -> Iterable[List[str]]:\n \"\"\"\n A single command line may contain multiple commands separated by\n special characters (e.g., &&, ||, etc.) so further split the\n commandline into an array of subcommand arrays.\n\n Parameters\n ----------\n cmdline: str\n The commandline to split.\n\n Yields\n ------\n Iterable[List[str]]\n A list of subcommands or separators, each one a list of tokens.\n Can be rejoined as a flattened array.\n \"\"\"\n cmdline_tokens = shlex.shlex(cmdline, posix=True, punctuation_chars=True)\n cmdline_tokens.whitespace_split = True\n subcmd = []\n for token in cmdline_tokens:\n if token[0] not in cmdline_tokens.punctuation_chars:\n subcmd.append(token)\n else:\n # Separator encountered. Yield any non-empty previous subcmd we accumulated.\n if subcmd:\n yield subcmd\n # Also return the separators.\n yield [token]\n subcmd = []\n # Return the trailing subcommand.\n if subcmd:\n yield subcmd\n\n\nclass LocalExecService(TempDirContextService, SupportsLocalExec):\n \"\"\"\n Collection of methods to run scripts and commands in an external process\n on the node acting as the scheduler. Can be useful for data processing\n due to reduced dependency management complications vs the target environment.\n \"\"\"\n\n def __init__(self,\n config: Optional[Dict[str, Any]] = None,\n global_config: Optional[Dict[str, Any]] = None,\n parent: Optional[Service] = None):\n \"\"\"\n Create a new instance of a service to run scripts locally.\n\n Parameters\n ----------\n config : dict\n Free-format dictionary that contains parameters for the service.\n (E.g., root path for config files, etc.)\n global_config : dict\n Free-format dictionary of global parameters.\n parent : Service\n An optional parent service that can provide mixin functions.\n \"\"\"\n super().__init__(config, global_config, parent)\n self.register([self.local_exec])\n\n def local_exec(self, script_lines: Iterable[str],\n env: Optional[Mapping[str, \"TunableValue\"]] = None,\n cwd: Optional[str] = None,\n return_on_error: bool = False) -> Tuple[int, str, str]:\n \"\"\"\n Execute the script lines from `script_lines` in a local process.\n\n Parameters\n ----------\n script_lines : Iterable[str]\n Lines of the script to run locally.\n Treat every line as a separate command to run.\n env : Mapping[str, Union[int, float, str]]\n Environment variables (optional).\n cwd : str\n Work directory to run the script at.\n If omitted, use `temp_dir` or create a temporary dir.\n return_on_error : bool\n If True, stop running script lines on first non-zero return code.\n The default is False.\n\n Returns\n -------\n (return_code, stdout, stderr) : (int, str, str)\n A 3-tuple of return code, stdout, and stderr of the script process.\n \"\"\"\n (return_code, stdout_list, stderr_list) = (0, [], [])\n with self.temp_dir_context(cwd) as temp_dir:\n\n _LOG.debug(\"Run in directory: %s\", temp_dir)\n\n for line in script_lines:\n (return_code, stdout, stderr) = self._local_exec_script(line, env, temp_dir)\n stdout_list.append(stdout)\n stderr_list.append(stderr)\n if return_code != 0 and return_on_error:\n break\n\n stdout = \"\".join(stdout_list)\n stderr = \"\".join(stderr_list)\n\n _LOG.debug(\"Run: stdout:\\n%s\", stdout)\n _LOG.debug(\"Run: stderr:\\n%s\", stderr)\n\n return (return_code, stdout, stderr)\n\n def _resolve_cmdline_script_path(self, subcmd_tokens: List[str]) -> List[str]:\n \"\"\"\n Resolves local script path (first token) in the (sub)command line\n tokens to its full path.\n\n Parameters\n ----------\n subcmd_tokens : List[str]\n The previously split tokens of the subcmd.\n\n Returns\n -------\n List[str]\n A modified sub command line with the script paths resolved.\n \"\"\"\n script_path = self.config_loader_service.resolve_path(subcmd_tokens[0])\n # Special case check for lone `.` which means both `source` and\n # \"current directory\" (which isn't executable) in posix shells.\n if os.path.exists(script_path) and os.path.isfile(script_path):\n # If the script exists, use it.\n subcmd_tokens[0] = os.path.abspath(script_path)\n # Also check if it is a python script and prepend the currently\n # executing python executable path to avoid requiring\n # executable mode bits or a shebang.\n if script_path.strip().lower().endswith(\".py\"):\n subcmd_tokens.insert(0, sys.executable)\n return subcmd_tokens\n\n def _local_exec_script(self, script_line: str,\n env_params: Optional[Mapping[str, \"TunableValue\"]],\n cwd: str) -> Tuple[int, str, str]:\n \"\"\"\n Execute the script from `script_path` in a local process.\n\n Parameters\n ----------\n script_line : str\n Line of the script to run in the local process.\n env_params : Mapping[str, Union[int, float, str]]\n Environment variables.\n cwd : str\n Work directory to run the script at.\n\n Returns\n -------\n (return_code, stdout, stderr) : (int, str, str)\n A 3-tuple of return code, stdout, and stderr of the script process.\n \"\"\"\n # Split the command line into set of subcmd tokens.\n # For each subcmd, perform path resolution fixups for any scripts being executed.\n subcmds = split_cmdline(script_line)\n subcmds = [self._resolve_cmdline_script_path(subcmd) for subcmd in subcmds]\n # Finally recombine all of the fixed up subcmd tokens into the original.\n cmd = [token for subcmd in subcmds for token in subcmd]\n\n env: Dict[str, str] = {}\n if env_params:\n env = {key: str(val) for (key, val) in env_params.items()}\n\n if sys.platform == 'win32':\n # A hack to run Python on Windows with env variables set:\n env_copy = os.environ.copy()\n env_copy[\"PYTHONPATH\"] = \"\"\n env_copy.update(env)\n env = env_copy\n\n try:\n if sys.platform != 'win32':\n cmd = [\" \".join(cmd)]\n\n _LOG.info(\"Run: %s\", cmd)\n\n proc = subprocess.run(cmd, env=env or None, cwd=cwd, shell=True,\n text=True, check=False, capture_output=True)\n\n _LOG.debug(\"Run: return code = %d\", proc.returncode)\n return (proc.returncode, proc.stdout, proc.stderr)\n\n except FileNotFoundError as ex:\n _LOG.warning(\"File not found: %s\", cmd, exc_info=ex)\n\n return (errno.ENOENT, \"\", \"File not found\")\n" }, { "alpha_fraction": 0.8136363625526428, "alphanum_fraction": 0.8136363625526428, "avg_line_length": 23.44444465637207, "blob_id": "a25b4ebeda996a7bc5401b8b7bf6e8cfa0a3b622", "content_id": "e84484e224edfcafe269dad811b527cb71d5505d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 220, "license_type": "permissive", "max_line_length": 68, "num_lines": 9, "path": "/.devcontainer/build/Makefile", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": ".PHONY: all devcontainer-cli devcontainer cspell markdown-link-check\n\nall: devcontainer-cli devcontainer\n\ndevcontainer-cli cspell markdown-link-check:\n\t./build-devcontainer-cli.sh\n\ndevcontainer:\n\t./build-devcontainer.sh\n" }, { "alpha_fraction": 0.5930837392807007, "alphanum_fraction": 0.5995839834213257, "avg_line_length": 33.64864730834961, "blob_id": "80886cf8e84d96d4581ef26d62d553b2fa3d32ca", "content_id": "cdea175bdef61518eae34a08551fdeaf2ae25cdd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3846, "license_type": "permissive", "max_line_length": 93, "num_lines": 111, "path": "/mlos_bench/mlos_bench/tests/launcher_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nUnit tests to check the main CLI launcher.\n\"\"\"\nimport os\nimport re\nfrom typing import List\n\nimport pytest\n\nfrom mlos_bench.services.local.local_exec import LocalExecService\nfrom mlos_bench.services.config_persistence import ConfigPersistenceService\nfrom mlos_bench.util import path_join\n\n# pylint: disable=redefined-outer-name\n\n\[email protected]\ndef root_path() -> str:\n \"\"\"\n Root path of mlos_bench project.\n \"\"\"\n return path_join(os.path.dirname(__file__), \"../../..\", abs_path=True)\n\n\[email protected]\ndef local_exec_service() -> LocalExecService:\n \"\"\"\n Test fixture for LocalExecService.\n \"\"\"\n return LocalExecService(parent=ConfigPersistenceService({\n \"config_path\": [\n \"mlos_bench/config\",\n \"mlos_bench/examples\",\n ]\n }))\n\n\ndef _launch_main_app(root_path: str, local_exec_service: LocalExecService,\n cli_config: str, re_expected: List[str]) -> None:\n \"\"\"\n Run mlos_bench command-line application with given config\n and check the results in the log.\n \"\"\"\n with local_exec_service.temp_dir_context() as temp_dir:\n\n # Test developers note: for local debugging,\n # uncomment the following line to use a known file path that can be examined:\n # temp_dir = '/tmp'\n log_path = path_join(temp_dir, \"mock-test.log\")\n (return_code, _stdout, _stderr) = local_exec_service.local_exec(\n [f\"./mlos_bench/mlos_bench/run.py {cli_config} --log_file '{log_path}'\"],\n cwd=root_path)\n assert return_code == 0\n\n try:\n iter_expected = iter(re_expected)\n re_log = re.compile(next(iter_expected))\n with open(log_path, \"rt\", encoding=\"utf-8\") as fh_out:\n for line in fh_out:\n if re_log.match(line):\n re_log = re.compile(next(iter_expected))\n assert False, f\"Pattern not found: '{re_log.pattern}'\"\n except StopIteration:\n pass # Success: all patterns found\n\n\n_RE_DATE = r\"\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3}\"\n\n\ndef test_launch_main_app_bench(root_path: str, local_exec_service: LocalExecService) -> None:\n \"\"\"\n Run mlos_bench command-line application with mock benchmark config\n and check the results in the log.\n \"\"\"\n _launch_main_app(\n root_path, local_exec_service,\n \"--config mlos_bench/mlos_bench/tests/config/cli/mock-bench.jsonc\",\n [\n f\"^{_RE_DATE} run\\\\.py:\\\\d+ \" +\n r\"_optimize INFO Env: Mock environment best score: 65\\.67\\d+\\s*$\",\n ]\n )\n\n\ndef test_launch_main_app_opt(root_path: str, local_exec_service: LocalExecService) -> None:\n \"\"\"\n Run mlos_bench command-line application with mock optimization config\n and check the results in the log.\n \"\"\"\n _launch_main_app(\n root_path, local_exec_service,\n \"--config mlos_bench/mlos_bench/tests/config/cli/mock-opt.jsonc --max_iterations 3\",\n [\n # Iteration 1: Expect first value to be the baseline\n f\"^{_RE_DATE} mlos_core_optimizer\\\\.py:\\\\d+ \" +\n r\"register DEBUG Score: 65\\.67\\d+ Dataframe:\\s*$\",\n # Iteration 2: The result may not always be deterministic\n f\"^{_RE_DATE} mlos_core_optimizer\\\\.py:\\\\d+ \" +\n r\"register DEBUG Score: \\d+\\.\\d+ Dataframe:\\s*$\",\n # Iteration 3: non-deterministic (depends on the optimizer)\n f\"^{_RE_DATE} mlos_core_optimizer\\\\.py:\\\\d+ \" +\n r\"register DEBUG Score: \\d+\\.\\d+ Dataframe:\\s*$\",\n # Final result: baseline is the optimum for the mock environment\n f\"^{_RE_DATE} run\\\\.py:\\\\d+ \" +\n r\"_optimize INFO Env: Mock environment best score: 65\\.67\\d+\\s*$\",\n ]\n )\n" }, { "alpha_fraction": 0.6059069633483887, "alphanum_fraction": 0.6080420017242432, "avg_line_length": 41.2593994140625, "blob_id": "5b1d78c7bff7d2cf8d55be1656cf2483465d31a8", "content_id": "d1c62778b8adaf78ed0d2f7063d0aeb1981c4b1d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11241, "license_type": "permissive", "max_line_length": 131, "num_lines": 266, "path": "/mlos_core/mlos_core/optimizers/optimizer.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nContains the BaseOptimizer abstract class.\n\"\"\"\n\nimport collections\nfrom abc import ABCMeta, abstractmethod\nfrom typing import List, Optional, Tuple\n\nimport ConfigSpace\nimport numpy as np\nimport numpy.typing as npt\nimport pandas as pd\n\nfrom mlos_core import config_to_dataframe\nfrom mlos_core.spaces.adapters.adapter import BaseSpaceAdapter\n\n\nclass BaseOptimizer(metaclass=ABCMeta):\n \"\"\"\n Optimizer abstract base class defining the basic interface.\n \"\"\"\n\n def __init__(self, *,\n parameter_space: ConfigSpace.ConfigurationSpace,\n space_adapter: Optional[BaseSpaceAdapter] = None):\n \"\"\"\n Create a new instance of the base optimizer.\n\n Parameters\n ----------\n parameter_space : ConfigSpace.ConfigurationSpace\n The parameter space to optimize.\n space_adapter : BaseSpaceAdapter\n The space adapter class to employ for parameter space transformations.\n \"\"\"\n self.parameter_space: ConfigSpace.ConfigurationSpace = parameter_space\n self.optimizer_parameter_space: ConfigSpace.ConfigurationSpace = \\\n parameter_space if space_adapter is None else space_adapter.target_parameter_space\n\n if space_adapter is not None and space_adapter.orig_parameter_space != parameter_space:\n raise ValueError(\"Given parameter space differs from the one given to space adapter\")\n\n self._space_adapter: Optional[BaseSpaceAdapter] = space_adapter\n self._observations: List[Tuple[pd.DataFrame, pd.Series, Optional[pd.DataFrame]]] = []\n self._has_context: Optional[bool] = None\n self._pending_observations: List[Tuple[pd.DataFrame, Optional[pd.DataFrame]]] = []\n\n def __repr__(self) -> str:\n return f\"{self.__class__.__name__}(space_adapter={self.space_adapter})\"\n\n @property\n def space_adapter(self) -> Optional[BaseSpaceAdapter]:\n \"\"\"Get the space adapter instance (if any).\"\"\"\n return self._space_adapter\n\n def register(self, configurations: pd.DataFrame, scores: pd.Series,\n context: Optional[pd.DataFrame] = None) -> None:\n \"\"\"Wrapper method, which employs the space adapter (if any), before registering the configurations and scores.\n\n Parameters\n ----------\n configurations : pd.DataFrame\n Dataframe of configurations / parameters. The columns are parameter names and the rows are the configurations.\n scores : pd.Series\n Scores from running the configurations. The index is the same as the index of the configurations.\n\n context : pd.DataFrame\n Not Yet Implemented.\n \"\"\"\n # Do some input validation.\n assert self._has_context is None or self._has_context ^ (context is None), \\\n \"Context must always be added or never be added.\"\n assert len(configurations) == len(scores), \\\n \"Mismatched number of configurations and scores.\"\n if context is not None:\n assert len(configurations) == len(context), \\\n \"Mismatched number of configurations and context.\"\n assert configurations.shape[1] == len(self.parameter_space.values()), \\\n \"Mismatched configuration shape.\"\n self._observations.append((configurations, scores, context))\n self._has_context = context is not None\n\n if self._space_adapter:\n configurations = self._space_adapter.inverse_transform(configurations)\n assert configurations.shape[1] == len(self.optimizer_parameter_space.values()), \\\n \"Mismatched configuration shape after inverse transform.\"\n return self._register(configurations, scores, context)\n\n @abstractmethod\n def _register(self, configurations: pd.DataFrame, scores: pd.Series,\n context: Optional[pd.DataFrame] = None) -> None:\n \"\"\"Registers the given configurations and scores.\n\n Parameters\n ----------\n configurations : pd.DataFrame\n Dataframe of configurations / parameters. The columns are parameter names and the rows are the configurations.\n scores : pd.Series\n Scores from running the configurations. The index is the same as the index of the configurations.\n\n context : pd.DataFrame\n Not Yet Implemented.\n \"\"\"\n pass # pylint: disable=unnecessary-pass # pragma: no cover\n\n def suggest(self, context: Optional[pd.DataFrame] = None, defaults: bool = False) -> pd.DataFrame:\n \"\"\"\n Wrapper method, which employs the space adapter (if any), after suggesting a new configuration.\n\n Parameters\n ----------\n context : pd.DataFrame\n Not Yet Implemented.\n defaults : bool\n Whether or not to return the default config instead of an optimizer guided one.\n By default, use the one from the optimizer.\n\n Returns\n -------\n configuration : pd.DataFrame\n Pandas dataframe with a single row. Column names are the parameter names.\n \"\"\"\n if defaults:\n configuration = config_to_dataframe(self.parameter_space.get_default_configuration())\n if self.space_adapter is not None:\n configuration = self.space_adapter.inverse_transform(configuration)\n else:\n configuration = self._suggest(context)\n assert len(configuration) == 1, \\\n \"Suggest must return a single configuration.\"\n assert len(configuration.columns) == len(self.optimizer_parameter_space.values()), \\\n \"Suggest returned a configuration with the wrong number of parameters.\"\n if self._space_adapter:\n configuration = self._space_adapter.transform(configuration)\n assert len(configuration.columns) == len(self.parameter_space.values()), \\\n \"Space adapter transformed configuration with the wrong number of parameters.\"\n return configuration\n\n @abstractmethod\n def _suggest(self, context: Optional[pd.DataFrame] = None) -> pd.DataFrame:\n \"\"\"Suggests a new configuration.\n\n Parameters\n ----------\n context : pd.DataFrame\n Not Yet Implemented.\n\n Returns\n -------\n configuration : pd.DataFrame\n Pandas dataframe with a single row. Column names are the parameter names.\n \"\"\"\n pass # pylint: disable=unnecessary-pass # pragma: no cover\n\n @abstractmethod\n def register_pending(self, configurations: pd.DataFrame,\n context: Optional[pd.DataFrame] = None) -> None:\n \"\"\"Registers the given configurations as \"pending\".\n That is it say, it has been suggested by the optimizer, and an experiment trial has been started.\n This can be useful for executing multiple trials in parallel, retry logic, etc.\n\n Parameters\n ----------\n configurations : pd.DataFrame\n Dataframe of configurations / parameters. The columns are parameter names and the rows are the configurations.\n context : pd.DataFrame\n Not Yet Implemented.\n \"\"\"\n pass # pylint: disable=unnecessary-pass # pragma: no cover\n\n def get_observations(self) -> pd.DataFrame:\n \"\"\"Returns the observations as a dataframe.\n\n Returns\n -------\n observations : pd.DataFrame\n Dataframe of observations. The columns are parameter names and \"score\" for the score, each row is an observation.\n \"\"\"\n if len(self._observations) == 0:\n raise ValueError(\"No observations registered yet.\")\n configs = pd.concat([config for config, _, _ in self._observations])\n scores = pd.concat([score for _, score, _ in self._observations])\n try:\n contexts = pd.concat([context for _, _, context in self._observations if context is not None])\n except ValueError:\n contexts = None\n configs[\"score\"] = scores\n if contexts is not None:\n # configs = pd.concat([configs, contexts], axis=1)\n # Not reachable for now\n raise NotImplementedError() # pragma: no cover\n return configs\n\n def get_best_observation(self) -> pd.DataFrame:\n \"\"\"Returns the best observation so far as a dataframe.\n\n Returns\n -------\n best_observation : pd.DataFrame\n Dataframe with a single row containing the best observation. The columns are parameter names and \"score\" for the score.\n \"\"\"\n if len(self._observations) == 0:\n raise ValueError(\"No observations registered yet.\")\n observations = self.get_observations()\n return observations.nsmallest(1, columns='score')\n\n def cleanup(self) -> None:\n \"\"\"Cleanup the optimizer.\"\"\"\n pass # pylint: disable=unnecessary-pass # pragma: no cover\n\n def _from_1hot(self, config: npt.NDArray) -> pd.DataFrame:\n \"\"\"\n Convert numpy array from one-hot encoding to a DataFrame\n with categoricals and ints in proper columns.\n \"\"\"\n df_dict = collections.defaultdict(list)\n for i in range(config.shape[0]):\n j = 0\n for param in self.optimizer_parameter_space.values():\n if isinstance(param, ConfigSpace.CategoricalHyperparameter):\n for (offset, val) in enumerate(param.choices):\n if config[i][j + offset] == 1:\n df_dict[param.name].append(val)\n break\n j += len(param.choices)\n else:\n val = config[i][j]\n if isinstance(param, ConfigSpace.UniformIntegerHyperparameter):\n val = int(val)\n df_dict[param.name].append(val)\n j += 1\n return pd.DataFrame(df_dict)\n\n def _to_1hot(self, config: pd.DataFrame) -> npt.NDArray:\n \"\"\"\n Convert pandas DataFrame to one-hot-encoded numpy array.\n \"\"\"\n n_cols = 0\n n_rows = config.shape[0] if config.ndim > 1 else 1\n for param in self.optimizer_parameter_space.values():\n if isinstance(param, ConfigSpace.CategoricalHyperparameter):\n n_cols += len(param.choices)\n else:\n n_cols += 1\n one_hot = np.zeros((n_rows, n_cols), dtype=np.float32)\n for i in range(n_rows):\n j = 0\n for param in self.optimizer_parameter_space.values():\n if config.ndim > 1:\n col = config.columns.get_loc(param.name)\n val = config.iloc[i, col]\n else:\n col = config.index.get_loc(param.name)\n val = config.iloc[col]\n if isinstance(param, ConfigSpace.CategoricalHyperparameter):\n offset = param.choices.index(val)\n one_hot[i][j + offset] = 1\n j += len(param.choices)\n else:\n one_hot[i][j] = val\n j += 1\n return one_hot\n" }, { "alpha_fraction": 0.6352887749671936, "alphanum_fraction": 0.6352887749671936, "avg_line_length": 31.82089614868164, "blob_id": "347742d07c623bc4c91b6d8fa90d2bb14ae0ee3b", "content_id": "cbfdb70e902b3ef42d479f733844f9e50c7d941f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2199, "license_type": "permissive", "max_line_length": 101, "num_lines": 67, "path": "/mlos_bench/mlos_bench/services/local/temp_dir_context.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nHelper functions to work with temp files locally on the scheduler side.\n\"\"\"\n\nimport abc\nimport logging\nfrom contextlib import nullcontext\nfrom tempfile import TemporaryDirectory\nfrom typing import Any, Dict, Optional, Union\n\nfrom mlos_bench.services.base_service import Service\n\n_LOG = logging.getLogger(__name__)\n\n\nclass TempDirContextService(Service, metaclass=abc.ABCMeta):\n \"\"\"\n A *base* service class that provides a method to create a temporary\n directory context for local scripts.\n\n It is inherited by LocalExecService and MockLocalExecService.\n This class is not supposed to be used as a standalone service.\n \"\"\"\n\n def __init__(self,\n config: Optional[Dict[str, Any]] = None,\n global_config: Optional[Dict[str, Any]] = None,\n parent: Optional[Service] = None):\n \"\"\"\n Create a new instance of a service that provides temporary directory context\n for local exec service.\n\n Parameters\n ----------\n config : dict\n Free-format dictionary that contains parameters for the service.\n (E.g., root path for config files, etc.)\n global_config : dict\n Free-format dictionary of global parameters.\n parent : Service\n An optional parent service that can provide mixin functions.\n \"\"\"\n super().__init__(config, global_config, parent)\n self._temp_dir = self.config.get(\"temp_dir\")\n self.register([self.temp_dir_context])\n\n def temp_dir_context(self, path: Optional[str] = None) -> Union[TemporaryDirectory, nullcontext]:\n \"\"\"\n Create a temp directory or use the provided path.\n\n Parameters\n ----------\n path : str\n A path to the temporary directory. Create a new one if None.\n\n Returns\n -------\n temp_dir_context : TemporaryDirectory\n Temporary directory context to use in the `with` clause.\n \"\"\"\n if path is None and self._temp_dir is None:\n return TemporaryDirectory()\n return nullcontext(path or self._temp_dir)\n" }, { "alpha_fraction": 0.613433837890625, "alphanum_fraction": 0.613433837890625, "avg_line_length": 30.042552947998047, "blob_id": "860cb2ac5c5706e869e379ecc265882d9ec834c0", "content_id": "1a5aa9c00f286a42f8bed247f28c5021019756ac", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1459, "license_type": "permissive", "max_line_length": 90, "num_lines": 47, "path": "/mlos_bench/mlos_bench/services/types/fileshare_type.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nProtocol interface for file share operations.\n\"\"\"\n\nfrom typing import Protocol, runtime_checkable\n\n\n@runtime_checkable\nclass SupportsFileShareOps(Protocol):\n \"\"\"\n Protocol interface for file share operations.\n \"\"\"\n\n def download(self, remote_path: str, local_path: str, recursive: bool = True) -> None:\n \"\"\"\n Downloads contents from a remote share path to a local path.\n\n Parameters\n ----------\n remote_path : str\n Path to download from the remote file share, a file if recursive=False\n or a directory if recursive=True.\n local_path : str\n Path to store the downloaded content to.\n recursive : bool\n If False, ignore the subdirectories;\n if True (the default), download the entire directory tree.\n \"\"\"\n\n def upload(self, local_path: str, remote_path: str, recursive: bool = True) -> None:\n \"\"\"\n Uploads contents from a local path to remote share path.\n\n Parameters\n ----------\n local_path : str\n Path to the local directory to upload contents from.\n remote_path : str\n Path in the remote file share to store the uploaded content to.\n recursive : bool\n If False, ignore the subdirectories;\n if True (the default), upload the entire directory tree.\n \"\"\"\n" }, { "alpha_fraction": 0.6584370732307434, "alphanum_fraction": 0.6676188707351685, "avg_line_length": 28.884145736694336, "blob_id": "ccc4659a45feef227fff1c4256853105308c4bcf", "content_id": "9ceae74df62f412d53d27d0d4c8eb4ee01623f12", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4901, "license_type": "permissive", "max_line_length": 87, "num_lines": 164, "path": "/mlos_bench/mlos_bench/tests/tunables/tunables_assign_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nUnit tests for assigning values to the individual parameters within tunable groups.\n\"\"\"\n\nimport json5 as json\nimport pytest\n\nfrom mlos_bench.tunables.tunable import Tunable\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\n\n\ndef test_tunables_assign_unknown_param(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Make sure that bulk assignment fails for parameters\n that don't exist in the TunableGroups object.\n \"\"\"\n with pytest.raises(KeyError):\n tunable_groups.assign({\n \"vmSize\": \"Standard_B2ms\",\n \"idle\": \"mwait\",\n \"UnknownParam_1\": 1,\n \"UnknownParam_2\": \"invalid-value\"\n })\n\n\ndef test_tunables_assign_invalid_categorical(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Check parameter validation for categorical tunables.\n \"\"\"\n with pytest.raises(ValueError):\n tunable_groups.assign({\"vmSize\": \"InvalidSize\"})\n\n\ndef test_tunables_assign_invalid_range(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Check parameter out-of-range validation for numerical tunables.\n \"\"\"\n with pytest.raises(ValueError):\n tunable_groups.assign({\"kernel_sched_migration_cost_ns\": -2})\n\n\ndef test_tunables_assign_coerce_str(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Check the conversion from strings when assigning to an integer parameter.\n \"\"\"\n tunable_groups.assign({\"kernel_sched_migration_cost_ns\": \"10000\"})\n\n\ndef test_tunables_assign_coerce_str_range_check(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Check the range when assigning to an integer tunable.\n \"\"\"\n with pytest.raises(ValueError):\n tunable_groups.assign({\"kernel_sched_migration_cost_ns\": \"5500000\"})\n\n\ndef test_tunables_assign_coerce_str_invalid(tunable_groups: TunableGroups) -> None:\n \"\"\"\n Make sure we fail when assigning an invalid string to an integer tunable.\n \"\"\"\n with pytest.raises(ValueError):\n tunable_groups.assign({\"kernel_sched_migration_cost_ns\": \"1.1\"})\n\n\ndef test_tunable_assign_str_to_numerical(tunable_int: Tunable) -> None:\n \"\"\"\n Check str to int coercion.\n \"\"\"\n with pytest.raises(ValueError):\n tunable_int.numerical_value = \"foo\" # type: ignore[assignment]\n\n\ndef test_tunable_assign_int_to_numerical_value(tunable_int: Tunable) -> None:\n \"\"\"\n Check numerical value assignment.\n \"\"\"\n tunable_int.numerical_value = 10.0\n assert tunable_int.numerical_value == 10\n\n\ndef test_tunable_assign_float_to_numerical_value(tunable_float: Tunable) -> None:\n \"\"\"\n Check numerical value assignment.\n \"\"\"\n tunable_float.numerical_value = 0.1\n assert tunable_float.numerical_value == 0.1\n\n\ndef test_tunable_assign_str_to_int(tunable_int: Tunable) -> None:\n \"\"\"\n Check str to int coercion.\n \"\"\"\n tunable_int.value = \"10\"\n assert tunable_int.value == 10 # type: ignore[comparison-overlap]\n\n\ndef test_tunable_assign_str_to_float(tunable_float: Tunable) -> None:\n \"\"\"\n Check str to float coercion.\n \"\"\"\n tunable_float.value = \"0.5\"\n assert tunable_float.value == 0.5 # type: ignore[comparison-overlap]\n\n\ndef test_tunable_assign_float_to_int(tunable_int: Tunable) -> None:\n \"\"\"\n Check float to int coercion.\n \"\"\"\n tunable_int.value = 10.0\n assert tunable_int.value == 10\n\n\ndef test_tunable_assign_float_to_int_fail(tunable_int: Tunable) -> None:\n \"\"\"\n Check the invalid float to int coercion.\n \"\"\"\n with pytest.raises(ValueError):\n tunable_int.value = 10.1\n\n\ndef test_tunable_assign_null_to_categorical() -> None:\n \"\"\"\n Checks that we can use null/None in categorical tunables.\n \"\"\"\n json_config = \"\"\"\n {\n \"name\": \"categorical_test\",\n \"type\": \"categorical\",\n \"values\": [\"foo\", null],\n \"default\": \"foo\"\n }\n \"\"\"\n config = json.loads(json_config)\n categorical_tunable = Tunable(name='categorical_test', config=config)\n assert categorical_tunable\n assert categorical_tunable.category == \"foo\"\n categorical_tunable.value = None\n assert categorical_tunable.value is None\n assert categorical_tunable.value != 'None'\n assert categorical_tunable.category is None\n\n\ndef test_tunable_assign_null_to_int(tunable_int: Tunable) -> None:\n \"\"\"\n Checks that we can't use null/None in integer tunables.\n \"\"\"\n with pytest.raises(TypeError):\n tunable_int.value = None\n with pytest.raises(TypeError):\n tunable_int.numerical_value = None # type: ignore[assignment]\n\n\ndef test_tunable_assign_null_to_float(tunable_float: Tunable) -> None:\n \"\"\"\n Checks that we can't use null/None in float tunables.\n \"\"\"\n with pytest.raises(TypeError):\n tunable_float.value = None\n with pytest.raises(TypeError):\n tunable_float.numerical_value = None # type: ignore[assignment]\n" }, { "alpha_fraction": 0.6032228469848633, "alphanum_fraction": 0.6041474342346191, "avg_line_length": 37.04522705078125, "blob_id": "128a8fa2ef1e246bf3a7a18fbe01e66e0ea05fea", "content_id": "a0d8eea6ccd48836f223a1ea9b44cdd96c150632", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7571, "license_type": "permissive", "max_line_length": 118, "num_lines": 199, "path": "/mlos_bench/mlos_bench/optimizers/base_optimizer.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nBase class for an interface between the benchmarking framework\nand mlos_core optimizers.\n\"\"\"\n\nimport logging\nfrom typing import Dict, Optional, Sequence, Tuple, Union\nfrom abc import ABCMeta, abstractmethod\nfrom distutils.util import strtobool # pylint: disable=deprecated-module\n\nfrom mlos_bench.services.base_service import Service\nfrom mlos_bench.environments.status import Status\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\n\n_LOG = logging.getLogger(__name__)\n\n\nclass Optimizer(metaclass=ABCMeta): # pylint: disable=too-many-instance-attributes\n \"\"\"\n An abstract interface between the benchmarking framework and mlos_core optimizers.\n \"\"\"\n\n def __init__(self,\n tunables: TunableGroups,\n config: dict,\n global_config: Optional[dict] = None,\n service: Optional[Service] = None):\n \"\"\"\n Create a new optimizer for the given configuration space defined by the tunables.\n\n Parameters\n ----------\n tunables : TunableGroups\n The tunables to optimize.\n config : dict\n Free-format key/value pairs of configuration parameters to pass to the optimizer.\n global_config : Optional[dict]\n service : Optional[Service]\n \"\"\"\n _LOG.info(\"Create optimizer for: %s\", tunables)\n _LOG.debug(\"Optimizer config: %s\", config)\n self._config = config.copy()\n self._global_config = global_config or {}\n self._tunables = tunables\n self._service = service\n\n experiment_id = self._global_config.get('experiment_id')\n self.experiment_id = str(experiment_id).strip() if experiment_id else None\n\n self._iter = 1\n # If False, use the optimizer to suggest the initial configuration;\n # if True (default), use the already initialized values for the first iteration.\n self._start_with_defaults: bool = bool(\n strtobool(str(self._config.pop('start_with_defaults', True))))\n self._max_iter = int(self._config.pop('max_iterations', 100))\n self._opt_target = str(self._config.pop('optimization_target', 'score'))\n self._opt_sign = {\"min\": 1, \"max\": -1}[self._config.pop('optimization_direction', 'min')]\n\n def __repr__(self) -> str:\n opt_direction = 'min' if self._opt_sign > 0 else 'max'\n return f\"{self.__class__.__name__}:{opt_direction}({self._opt_target})(config={self._config})\"\n\n @property\n def target(self) -> str:\n \"\"\"\n The name of the target metric to optimize.\n \"\"\"\n return self._opt_target\n\n @property\n def supports_preload(self) -> bool:\n \"\"\"\n Return True if the optimizer supports pre-loading the data from previous experiments.\n \"\"\"\n return True\n\n @abstractmethod\n def bulk_register(self, configs: Sequence[dict], scores: Sequence[Optional[float]],\n status: Optional[Sequence[Status]] = None) -> bool:\n \"\"\"\n Pre-load the optimizer with the bulk data from previous experiments.\n\n Parameters\n ----------\n configs : Sequence[dict]\n Records of tunable values from other experiments.\n scores : Sequence[float]\n Benchmark results from experiments that correspond to `configs`.\n status : Optional[Sequence[float]]\n Status of the experiments that correspond to `configs`.\n\n Returns\n -------\n is_not_empty : bool\n True if there is data to register, false otherwise.\n \"\"\"\n _LOG.info(\"Warm-up the optimizer with: %d configs, %d scores, %d status values\",\n len(configs or []), len(scores or []), len(status or []))\n if len(configs or []) != len(scores or []):\n raise ValueError(\"Numbers of configs and scores do not match.\")\n if status is not None and len(configs or []) != len(status or []):\n raise ValueError(\"Numbers of configs and status values do not match.\")\n has_data = bool(configs and scores)\n if has_data and self._start_with_defaults:\n _LOG.info(\"Prior data exists - do *NOT* use the default initialization.\")\n self._start_with_defaults = False\n return has_data\n\n @abstractmethod\n def suggest(self) -> TunableGroups:\n \"\"\"\n Generate the next suggestion.\n\n Returns\n -------\n tunables : TunableGroups\n The next configuration to benchmark.\n These are the same tunables we pass to the constructor,\n but with the values set to the next suggestion.\n \"\"\"\n\n @abstractmethod\n def register(self, tunables: TunableGroups, status: Status,\n score: Optional[Union[float, Dict[str, float]]] = None) -> Optional[float]:\n \"\"\"\n Register the observation for the given configuration.\n\n Parameters\n ----------\n tunables : TunableGroups\n The configuration that has been benchmarked.\n Usually it's the same config that the `.suggest()` method returned.\n status : Status\n Final status of the experiment (e.g., SUCCEEDED or FAILED).\n score : Union[float, Dict[str, float]]\n A scalar or a dict with the final benchmark results.\n None if the experiment was not successful.\n\n Returns\n -------\n value : float\n The scalar benchmark score extracted (and possibly transformed) from the dataframe that's being minimized.\n \"\"\"\n _LOG.info(\"Iteration %d :: Register: %s = %s score: %s\",\n self._iter, tunables, status, score)\n if status.is_succeeded() == (score is None): # XOR\n raise ValueError(\"Status and score must be consistent.\")\n return self._get_score(status, score)\n\n def _get_score(self, status: Status, score: Optional[Union[float, Dict[str, float]]]) -> Optional[float]:\n \"\"\"\n Extract a scalar benchmark score from the dataframe.\n Change the sign if we are maximizing.\n\n Parameters\n ----------\n status : Status\n Final status of the experiment (e.g., SUCCEEDED or FAILED).\n score : Union[float, Dict[str, float]]\n A scalar or a dict with the final benchmark results.\n None if the experiment was not successful.\n\n Returns\n -------\n score : float\n A scalar benchmark score to be used as a primary target for MINIMIZATION.\n \"\"\"\n if not status.is_completed():\n return None\n if status.is_succeeded():\n assert score is not None\n if isinstance(score, dict):\n score = score[self._opt_target]\n return float(score) * self._opt_sign\n assert score is None\n return float(\"inf\")\n\n def not_converged(self) -> bool:\n \"\"\"\n Return True if not converged, False otherwise.\n Base implementation just checks the iteration count.\n \"\"\"\n return self._iter <= self._max_iter\n\n @abstractmethod\n def get_best_observation(self) -> Union[Tuple[float, TunableGroups], Tuple[None, None]]:\n \"\"\"\n Get the best observation so far.\n\n Returns\n -------\n (value, tunables) : Tuple[float, TunableGroups]\n The best value and the corresponding configuration.\n (None, None) if no successful observation has been registered yet.\n \"\"\"\n" }, { "alpha_fraction": 0.6895306706428528, "alphanum_fraction": 0.6906294226646423, "avg_line_length": 44.18439865112305, "blob_id": "21514cf10f1fc190097c775e3d85ee197f13c5d6", "content_id": "6ecace72c8a6f31a491d83f4b13020aa2dbd8044", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6371, "license_type": "permissive", "max_line_length": 125, "num_lines": 141, "path": "/mlos_bench/mlos_bench/tests/config/environments/test_load_environment_config_examples.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTests for loading environment config examples.\n\"\"\"\nimport logging\nfrom typing import List\n\nimport pytest\n\nfrom mlos_bench.tests.config import locate_config_examples\n\nfrom mlos_bench.config.schemas.config_schemas import ConfigSchema\nfrom mlos_bench.environments.base_environment import Environment\nfrom mlos_bench.environments.composite_env import CompositeEnv\nfrom mlos_bench.services.config_persistence import ConfigPersistenceService\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\nfrom mlos_bench.util import path_join\n\n\n_LOG = logging.getLogger(__name__)\n_LOG.setLevel(logging.DEBUG)\n\n\n# Get the set of configs to test.\nCONFIG_TYPE = \"environments\"\n\n\ndef filter_configs(configs_to_filter: List[str]) -> List[str]:\n \"\"\"If necessary, filter out json files that aren't for the module we're testing.\"\"\"\n configs_to_filter = [config_path for config_path in configs_to_filter if not config_path.endswith(\"-tunables.jsonc\")]\n return configs_to_filter\n\n\nconfigs = filter_configs(locate_config_examples(path_join(ConfigPersistenceService.BUILTIN_CONFIG_PATH, CONFIG_TYPE)))\nassert configs\n\n\[email protected](\"config_path\", configs)\ndef test_load_environment_config_examples(config_loader_service: ConfigPersistenceService, config_path: str) -> None:\n \"\"\"Tests loading an environment config example.\"\"\"\n envs = load_environment_config_examples(config_loader_service, config_path)\n for env in envs:\n assert env is not None\n assert isinstance(env, Environment)\n\n\ndef load_environment_config_examples(config_loader_service: ConfigPersistenceService, config_path: str) -> List[Environment]:\n \"\"\"Loads an environment config example.\"\"\"\n # Make sure that any \"required_args\" are provided.\n global_config = {\n \"experiment_id\": \"test\",\n \"trial_id\": 1,\n\n \"mountPoint\": \"/mnt/tmp\",\n\n # FIXME: The setup ubuntu configs currently use these values in their mounting scripts.\n # We should abstract that out so those details are only needed when a service that uses those is used.\n \"storageAccountName\": \"foo\",\n \"storageAccountKey\": \"bar\",\n \"storageFileShareName\": \"baz\",\n\n # Assign some values to variadic tunables and required parameters present in the config examples.\n \"vmName\": \"vmTestName\",\n \"tunable_params_map\": {\n \"linux-runtime\": [\"linux-scheduler\", \"linux-swap\"],\n \"linux-boot\": [\"linux-kernel-boot\"],\n \"provision\": [\"azure-vm\"],\n \"redis\": [\"redis\"],\n }\n }\n\n # Make sure we have the required services for the envs being used.\n mock_service_configs = [\n \"services/local/mock/mock_local_exec_service.jsonc\",\n \"services/remote/mock/mock_fileshare_service.jsonc\",\n \"services/remote/mock/mock_vm_service.jsonc\",\n \"services/remote/mock/mock_remote_exec_service.jsonc\",\n ]\n\n tunable_groups = TunableGroups() # base tunable groups that all others get built on\n\n for mock_service_config_path in mock_service_configs:\n mock_service_config = config_loader_service.load_config(mock_service_config_path, ConfigSchema.SERVICE)\n config_loader_service.register(config_loader_service.build_service(\n config=mock_service_config, parent=config_loader_service).export())\n\n envs = config_loader_service.load_environment_list(\n config_path, tunable_groups, global_config, service=config_loader_service)\n return envs\n\n\ncomposite_configs = filter_configs(locate_config_examples(path_join(\n ConfigPersistenceService.BUILTIN_CONFIG_PATH, \"environments/root/\")))\nassert composite_configs\n\n\[email protected](\"config_path\", composite_configs)\ndef test_load_composite_env_config_examples(config_loader_service: ConfigPersistenceService, config_path: str) -> None:\n \"\"\"Tests loading a composite env config example.\"\"\"\n envs = load_environment_config_examples(config_loader_service, config_path)\n assert len(envs) == 1\n assert isinstance(envs[0], CompositeEnv)\n composite_env: CompositeEnv = envs[0]\n\n for child_env in composite_env.children:\n assert child_env is not None\n assert isinstance(child_env, Environment)\n assert child_env.tunable_params is not None\n\n checked_child_env_groups = set()\n for (child_tunable, child_group) in child_env.tunable_params:\n # Lookup that tunable in the composite env.\n assert child_tunable in composite_env.tunable_params\n (composite_tunable, composite_group) = composite_env.tunable_params.get_tunable(child_tunable)\n assert child_tunable is composite_tunable # Check that the tunables are the same object.\n if child_group.name not in checked_child_env_groups:\n assert child_group is composite_group\n checked_child_env_groups.add(child_group.name)\n\n # Check that when we change a child env, it's value is reflected in the composite env as well.\n # That is to say, they refer to the same objects, despite having potentially been loaded from separate configs.\n if child_tunable.is_categorical:\n old_cat_value = child_tunable.category\n assert child_tunable.value == old_cat_value\n assert child_group[child_tunable] == old_cat_value\n assert composite_env.tunable_params[child_tunable] == old_cat_value\n new_cat_value = [x for x in child_tunable.categories if x != old_cat_value][0]\n child_tunable.category = new_cat_value\n assert child_env.tunable_params[child_tunable] == new_cat_value\n assert composite_env.tunable_params[child_tunable] == child_tunable.category\n elif child_tunable.is_numerical:\n old_num_value = child_tunable.numerical_value\n assert child_tunable.value == old_num_value\n assert child_group[child_tunable] == old_num_value\n assert composite_env.tunable_params[child_tunable] == old_num_value\n child_tunable.numerical_value += 1\n assert child_env.tunable_params[child_tunable] == old_num_value + 1\n assert composite_env.tunable_params[child_tunable] == child_tunable.numerical_value\n" }, { "alpha_fraction": 0.7461898922920227, "alphanum_fraction": 0.7579132318496704, "avg_line_length": 32.45098114013672, "blob_id": "a47f5f79f8b08bf94fc203d15b926cc5d695700b", "content_id": "d373c159b587ee3cd8d2930895024cc4f1d50e9e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 1706, "license_type": "permissive", "max_line_length": 167, "num_lines": 51, "path": "/.pylintrc", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "# vim: set ft=dosini:\n\n[MAIN]\n# Specify a score threshold to be exceeded before program exits with error.\nfail-under=9.8\n\n# Make sure public methods are documented.\n# See Also: https://github.com/PyCQA/pydocstyle/issues/309#issuecomment-1426642147\n# Also fail on unused imports.\nfail-on=\n missing-function-docstring,\n unused-import\n\n# Ignore pylint complaints about an upstream dependency.\nignored-modules=ConfigSpace.hyperparameters\n\n# Help inform pylint where to find the project's source code without needing to relyon PYTHONPATH.\n#init-hook=\"from pylint.config import find_pylintrc; import os, sys; sys.path.append(os.path.dirname(find_pylintrc())); from logging import warning; warning(sys.path)\"\ninit-hook=\"from logging import warning; warning(sys.path)\"\n\n# Load some extra checkers.\nload-plugins=\n pylint.extensions.bad_builtin,\n pylint.extensions.code_style,\n pylint.extensions.docparams,\n pylint.extensions.docstyle,\n pylint.extensions.for_any_all,\n pylint.extensions.mccabe,\n pylint.extensions.no_self_use,\n pylint.extensions.private_import,\n pylint.extensions.redefined_loop_name,\n pylint.extensions.redefined_variable_type,\n pylint.extensions.set_membership,\n pylint.extensions.typing\n\n[FORMAT]\n# Maximum number of characters on a single line.\nmax-line-length=132\n\n[MESSAGE CONTROL]\ndisable=\n no-else-return,\n consider-using-assignment-expr,\n deprecated-typing-alias, # disable for now - only deprecated recently\n docstring-first-line-empty,\n consider-alternative-union-syntax, # disable for now - still supporting python 3.8\n missing-raises-doc\n\n[STRING]\n#check-quote-consistency=yes\ncheck-str-concat-over-line-jumps=yes\n" }, { "alpha_fraction": 0.6633663177490234, "alphanum_fraction": 0.6633663177490234, "avg_line_length": 13.428571701049805, "blob_id": "660d196a11de52584f3a5d0bbf71b80cc77d8a9e", "content_id": "8230accbfc784e979d3c7714ce8e098de68532c1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 101, "license_type": "permissive", "max_line_length": 39, "num_lines": 7, "path": "/mlos_bench/mlos_bench/config/environments/apps/redis/scripts/remote/cleanup-workload.sh", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#!/bin/bash\n##\n## Copyright (c) Microsoft Corporation.\n## Licensed under the MIT License.\n##\n\n# TODO\n" }, { "alpha_fraction": 0.6734785437583923, "alphanum_fraction": 0.6777453422546387, "avg_line_length": 36.420169830322266, "blob_id": "f141a4c66e9e462361752cf8da43b4dd1ae05061", "content_id": "1750316912704e73bfd3b89d224060e36f16b1dd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4453, "license_type": "permissive", "max_line_length": 91, "num_lines": 119, "path": "/mlos_bench/mlos_bench/tests/storage/exp_load_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nUnit tests for the storage subsystem.\n\"\"\"\nfrom datetime import datetime\n\nimport pytest\n\nfrom mlos_bench.environments.status import Status\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\nfrom mlos_bench.storage.base_storage import Storage\n\n\ndef test_exp_load_empty(exp_storage_memory_sql: Storage.Experiment) -> None:\n \"\"\"\n Try to retrieve old experimental data from the empty storage.\n \"\"\"\n (configs, scores, status) = exp_storage_memory_sql.load()\n assert not configs\n assert not scores\n assert not status\n\n\ndef test_exp_pending_empty(exp_storage_memory_sql: Storage.Experiment) -> None:\n \"\"\"\n Try to retrieve pending experiments from the empty storage.\n \"\"\"\n trials = list(exp_storage_memory_sql.pending_trials())\n assert not trials\n\n\ndef test_exp_trial_pending(exp_storage_memory_sql: Storage.Experiment,\n tunable_groups: TunableGroups) -> None:\n \"\"\"\n Start a trial and check that it is pending.\n \"\"\"\n trial = exp_storage_memory_sql.new_trial(tunable_groups)\n (pending,) = list(exp_storage_memory_sql.pending_trials())\n assert pending.trial_id == trial.trial_id\n assert pending.tunables == tunable_groups\n\n\ndef test_exp_trial_pending_many(exp_storage_memory_sql: Storage.Experiment,\n tunable_groups: TunableGroups) -> None:\n \"\"\"\n Start THREE trials and check that both are pending.\n \"\"\"\n config1 = tunable_groups.copy().assign({'idle': 'mwait'})\n config2 = tunable_groups.copy().assign({'idle': 'noidle'})\n trial_ids = {\n exp_storage_memory_sql.new_trial(config1).trial_id,\n exp_storage_memory_sql.new_trial(config2).trial_id,\n exp_storage_memory_sql.new_trial(config2).trial_id, # Submit same config twice\n }\n pending_ids = {pending.trial_id for pending in exp_storage_memory_sql.pending_trials()}\n assert len(pending_ids) == 3\n assert trial_ids == pending_ids\n\n\ndef test_exp_trial_pending_fail(exp_storage_memory_sql: Storage.Experiment,\n tunable_groups: TunableGroups) -> None:\n \"\"\"\n Start a trial, fail it, and and check that it is NOT pending.\n \"\"\"\n trial = exp_storage_memory_sql.new_trial(tunable_groups)\n trial.update(Status.FAILED, datetime.utcnow())\n trials = list(exp_storage_memory_sql.pending_trials())\n assert not trials\n\n\ndef test_exp_trial_success(exp_storage_memory_sql: Storage.Experiment,\n tunable_groups: TunableGroups) -> None:\n \"\"\"\n Start a trial, finish it successfully, and and check that it is NOT pending.\n \"\"\"\n trial = exp_storage_memory_sql.new_trial(tunable_groups)\n trial.update(Status.SUCCEEDED, datetime.utcnow(), 99.9)\n trials = list(exp_storage_memory_sql.pending_trials())\n assert not trials\n\n\ndef test_exp_trial_update_twice(exp_storage_memory_sql: Storage.Experiment,\n tunable_groups: TunableGroups) -> None:\n \"\"\"\n Update the trial status twice and receive an error.\n \"\"\"\n trial = exp_storage_memory_sql.new_trial(tunable_groups)\n trial.update(Status.FAILED, datetime.utcnow())\n with pytest.raises(RuntimeError):\n trial.update(Status.SUCCEEDED, datetime.utcnow(), 99.9)\n\n\ndef test_exp_trial_pending_3(exp_storage_memory_sql: Storage.Experiment,\n tunable_groups: TunableGroups) -> None:\n \"\"\"\n Start THREE trials, let one succeed, another one fail and keep one not updated.\n Check that one is still pending another one can be loaded into the optimizer.\n \"\"\"\n score = 99.9\n\n trial_fail = exp_storage_memory_sql.new_trial(tunable_groups)\n trial_succ = exp_storage_memory_sql.new_trial(tunable_groups)\n trial_pend = exp_storage_memory_sql.new_trial(tunable_groups)\n\n trial_fail.update(Status.FAILED, datetime.utcnow())\n trial_succ.update(Status.SUCCEEDED, datetime.utcnow(), score)\n\n (pending,) = list(exp_storage_memory_sql.pending_trials())\n assert pending.trial_id == trial_pend.trial_id\n\n (configs, scores, status) = exp_storage_memory_sql.load()\n assert len(configs) == 2\n assert scores == [None, score]\n assert status == [Status.FAILED, Status.SUCCEEDED]\n assert tunable_groups.copy().assign(configs[0]).reset() == trial_fail.tunables\n assert tunable_groups.copy().assign(configs[1]).reset() == trial_succ.tunables\n" }, { "alpha_fraction": 0.5400000214576721, "alphanum_fraction": 0.5542857050895691, "avg_line_length": 24.36231803894043, "blob_id": "f9a44439719b1711fd51dfc0c59335c65f51018f", "content_id": "de0bc796227df2e5975d5e6ca573ab5558b81990", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3500, "license_type": "permissive", "max_line_length": 78, "num_lines": 138, "path": "/mlos_bench/mlos_bench/tests/conftest.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nCommon fixtures for mock TunableGroups and Environment objects.\n\"\"\"\n\nfrom typing import Any, Dict\n\nimport json5 as json\nimport pytest\n\nfrom mlos_bench.tests import SEED\nfrom mlos_bench.environments.mock_env import MockEnv\nfrom mlos_bench.tunables.covariant_group import CovariantTunableGroup\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\n\n# pylint: disable=redefined-outer-name\n# -- Ignore pylint complaints about pytest references to\n# `tunable_groups` fixture as both a function and a parameter.\n\n\nTUNABLE_GROUPS_JSON = \"\"\"\n{\n \"provision\": {\n \"cost\": 1000,\n \"params\": {\n \"vmSize\": {\n \"description\": \"Azure VM size\",\n \"type\": \"categorical\",\n \"default\": \"Standard_B4ms\",\n \"values\": [\"Standard_B2s\", \"Standard_B2ms\", \"Standard_B4ms\"]\n }\n }\n },\n \"boot\": {\n \"cost\": 300,\n \"params\": {\n \"idle\": {\n \"description\": \"Idling method\",\n \"type\": \"categorical\",\n \"default\": \"halt\",\n \"values\": [\"halt\", \"mwait\", \"noidle\"]\n }\n }\n },\n \"kernel\": {\n \"cost\": 1,\n \"params\": {\n \"kernel_sched_migration_cost_ns\": {\n \"description\": \"Cost of migrating the thread to another core\",\n \"type\": \"int\",\n \"default\": -1,\n \"range\": [-1, 500000],\n \"special\": [-1]\n },\n \"kernel_sched_latency_ns\": {\n \"description\": \"Initial value for the scheduler period\",\n \"type\": \"int\",\n \"default\": 2000000,\n \"range\": [0, 1000000000]\n }\n }\n }\n}\n\"\"\"\n\n\[email protected]\ndef tunable_groups_config() -> Dict[str, Any]:\n \"\"\"\n Fixture to get the JSON string for the tunable groups.\n \"\"\"\n conf = json.loads(TUNABLE_GROUPS_JSON)\n assert isinstance(conf, dict)\n return conf\n\n\[email protected]\ndef tunable_groups(tunable_groups_config: dict) -> TunableGroups:\n \"\"\"\n A test fixture that produces a mock TunableGroups.\n\n Returns\n -------\n tunable_groups : TunableGroups\n A new TunableGroups object for testing.\n \"\"\"\n tunables = TunableGroups(tunable_groups_config)\n tunables.reset()\n return tunables\n\n\[email protected]\ndef covariant_group(tunable_groups: TunableGroups) -> CovariantTunableGroup:\n \"\"\"\n Text fixture to get a CovariantTunableGroup from tunable_groups.\n\n Returns\n -------\n CovariantTunableGroup\n \"\"\"\n (_, covariant_group) = next(iter(tunable_groups))\n return covariant_group\n\n\[email protected]\ndef mock_env(tunable_groups: TunableGroups) -> MockEnv:\n \"\"\"\n Test fixture for MockEnv.\n \"\"\"\n return MockEnv(\n name=\"Test Env\",\n config={\n \"tunable_params\": [\"provision\", \"boot\", \"kernel\"],\n \"seed\": SEED,\n \"range\": [60, 120],\n \"metrics\": [\"score\"],\n },\n tunables=tunable_groups\n )\n\n\[email protected]\ndef mock_env_no_noise(tunable_groups: TunableGroups) -> MockEnv:\n \"\"\"\n Test fixture for MockEnv.\n \"\"\"\n return MockEnv(\n name=\"Test Env No Noise\",\n config={\n \"tunable_params\": [\"provision\", \"boot\", \"kernel\"],\n \"range\": [60, 120],\n \"metrics\": [\"score\", \"other_score\"],\n },\n tunables=tunable_groups\n )\n" }, { "alpha_fraction": 0.5932276844978333, "alphanum_fraction": 0.5937703251838684, "avg_line_length": 37.71428680419922, "blob_id": "f683a5620166d759b782c92891073e7643bcf221", "content_id": "9e8b4f487e17e3d3e9bf990bbc825b6a7e90d452", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9214, "license_type": "permissive", "max_line_length": 97, "num_lines": 238, "path": "/mlos_bench/mlos_bench/environments/composite_env.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nComposite benchmark environment.\n\"\"\"\n\nimport logging\nfrom datetime import datetime\n\nfrom types import TracebackType\nfrom typing import Any, Dict, List, Optional, Tuple, Type\nfrom typing_extensions import Literal\n\nfrom mlos_bench.services.base_service import Service\nfrom mlos_bench.environments.status import Status\nfrom mlos_bench.environments.base_environment import Environment\nfrom mlos_bench.tunables.tunable_groups import TunableGroups\n\n_LOG = logging.getLogger(__name__)\n\n\nclass CompositeEnv(Environment):\n \"\"\"\n Composite benchmark environment.\n \"\"\"\n\n def __init__(self,\n *,\n name: str,\n config: dict,\n global_config: Optional[dict] = None,\n tunables: Optional[TunableGroups] = None,\n service: Optional[Service] = None):\n \"\"\"\n Create a new environment with a given config.\n\n Parameters\n ----------\n name: str\n Human-readable name of the environment.\n config : dict\n Free-format dictionary that contains the environment\n configuration. Must have a \"children\" section.\n global_config : dict\n Free-format dictionary of global parameters (e.g., security credentials)\n to be mixed in into the \"const_args\" section of the local config.\n tunables : TunableGroups\n A collection of groups of tunable parameters for *all* environments.\n service: Service\n An optional service object (e.g., providing methods to\n deploy or reboot a VM, etc.).\n \"\"\"\n super().__init__(name=name, config=config, global_config=global_config,\n tunables=tunables, service=service)\n\n # By default, the Environment includes only the tunables explicitly specified\n # in the \"tunable_params\" section of the config. `CompositeEnv`, however, must\n # retain all tunables from its children environments plus the ones that come\n # from the \"include_tunables\".\n tunables = tunables.copy() if tunables else TunableGroups()\n\n _LOG.debug(\"Build composite environment '%s' START: %s\", self, tunables)\n self._children: List[Environment] = []\n self._child_contexts: List[Environment] = []\n\n # To support trees of composite environments (e.g. for multiple VM experiments),\n # each CompositeEnv gets a copy of the original global config and adjusts it with\n # the `const_args` specific to it.\n global_config = (global_config or {}).copy()\n for (key, val) in self._const_args.items():\n global_config.setdefault(key, val)\n\n for child_config_file in config.get(\"include_children\", []):\n for env in self._config_loader_service.load_environment_list(\n child_config_file, tunables, global_config, self._const_args, self._service):\n self._add_child(env, tunables)\n\n for child_config in config.get(\"children\", []):\n env = self._config_loader_service.build_environment(\n child_config, tunables, global_config, self._const_args, self._service)\n self._add_child(env, tunables)\n\n _LOG.debug(\"Build composite environment '%s' END: %s\", self, self._tunable_params)\n\n if not self._children:\n raise ValueError(\"At least one child environment must be present\")\n\n def __enter__(self) -> Environment:\n self._child_contexts = [env.__enter__() for env in self._children]\n return super().__enter__()\n\n def __exit__(self, ex_type: Optional[Type[BaseException]],\n ex_val: Optional[BaseException],\n ex_tb: Optional[TracebackType]) -> Literal[False]:\n ex_throw = None\n for env in reversed(self._children):\n try:\n env.__exit__(ex_type, ex_val, ex_tb)\n # pylint: disable=broad-exception-caught\n except Exception as ex:\n _LOG.error(\"Exception while exiting child environment '%s': %s\", env, ex)\n ex_throw = ex\n self._child_contexts = []\n super().__exit__(ex_type, ex_val, ex_tb)\n if ex_throw:\n raise ex_throw\n return False\n\n @property\n def children(self) -> List[Environment]:\n \"\"\"\n Return the list of child environments.\n \"\"\"\n return self._children\n\n def pprint(self, indent: int = 4, level: int = 0) -> str:\n \"\"\"\n Pretty-print the environment and its children.\n\n Parameters\n ----------\n indent : int\n Number of spaces to indent the output at each level. Default is 4.\n level : int\n Current level of indentation. Default is 0.\n\n Returns\n -------\n pretty : str\n Pretty-printed environment configuration.\n \"\"\"\n return super().pprint(indent, level) + '\\n' + '\\n'.join(\n child.pprint(indent, level + 1) for child in self._children)\n\n def _add_child(self, env: Environment, tunables: TunableGroups) -> None:\n \"\"\"\n Add a new child environment to the composite environment.\n This method is called from the constructor only.\n \"\"\"\n _LOG.debug(\"Merge tunables: '%s' <- '%s' :: %s\", self, env, env.tunable_params)\n self._children.append(env)\n self._tunable_params.merge(env.tunable_params)\n tunables.merge(env.tunable_params)\n\n def setup(self, tunables: TunableGroups, global_config: Optional[dict] = None) -> bool:\n \"\"\"\n Set up the children environments.\n\n Parameters\n ----------\n tunables : TunableGroups\n A collection of tunable parameters along with their values.\n global_config : dict\n Free-format dictionary of global parameters of the environment\n that are not used in the optimization process.\n\n Returns\n -------\n is_success : bool\n True if all children setup() operations are successful,\n false otherwise.\n \"\"\"\n assert self._in_context\n self._is_ready = super().setup(tunables, global_config) and all(\n env_context.setup(tunables, global_config) for env_context in self._child_contexts)\n return self._is_ready\n\n def teardown(self) -> None:\n \"\"\"\n Tear down the children environments. This method is idempotent,\n i.e., calling it several times is equivalent to a single call.\n The environments are being torn down in the reverse order.\n \"\"\"\n assert self._in_context\n for env_context in reversed(self._child_contexts):\n env_context.teardown()\n super().teardown()\n\n def run(self) -> Tuple[Status, Optional[Dict[str, float]]]:\n \"\"\"\n Submit a new experiment to the environment.\n Return the result of the *last* child environment if successful,\n or the status of the last failed environment otherwise.\n\n Returns\n -------\n (status, output) : (Status, dict)\n A pair of (Status, output) values, where `output` is a dict\n with the results or None if the status is not COMPLETED.\n If run script is a benchmark, then the score is usually expected to\n be in the `score` field.\n \"\"\"\n _LOG.info(\"Run: %s\", self._children)\n (status, metrics) = super().run()\n if not status.is_ready():\n return (status, metrics)\n\n joint_metrics = {}\n for env_context in self._child_contexts:\n _LOG.debug(\"Child env. run: %s\", env_context)\n (status, metrics) = env_context.run()\n _LOG.debug(\"Child env. run results: %s :: %s %s\", env_context, status, metrics)\n if not status.is_good():\n _LOG.info(\"Run failed: %s :: %s\", self, status)\n return (status, None)\n joint_metrics.update(metrics or {})\n\n _LOG.info(\"Run completed: %s :: %s %s\", self, status, joint_metrics)\n return (status, joint_metrics)\n\n def status(self) -> Tuple[Status, List[Tuple[datetime, str, Any]]]:\n \"\"\"\n Check the status of the benchmark environment.\n\n Returns\n -------\n (benchmark_status, telemetry) : (Status, list)\n A pair of (benchmark status, telemetry) values.\n `telemetry` is a list (maybe empty) of (timestamp, metric, value) triplets.\n \"\"\"\n (status, telemetry) = super().status()\n if not status.is_ready():\n return (status, telemetry)\n\n joint_telemetry = []\n final_status = None\n for env_context in self._child_contexts:\n (status, telemetry) = env_context.status()\n _LOG.debug(\"Child env. status: %s :: %s\", env_context, status)\n joint_telemetry.extend(telemetry)\n if not status.is_good() and final_status is None:\n final_status = status\n\n final_status = final_status or status\n _LOG.info(\"Final status: %s :: %s\", self, final_status)\n return (final_status, joint_telemetry)\n" }, { "alpha_fraction": 0.7389937043190002, "alphanum_fraction": 0.7389937043190002, "avg_line_length": 20.200000762939453, "blob_id": "fede072f1f6ecfd5857c9021686a35f53aba0bf7", "content_id": "0cdd8349b433c237b46bd3b8720f0ae71a235241", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 318, "license_type": "permissive", "max_line_length": 79, "num_lines": 15, "path": "/mlos_bench/mlos_bench/environments/local/__init__.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nLocal Environments for mlos_bench.\n\"\"\"\n\nfrom mlos_bench.environments.local.local_env import LocalEnv\nfrom mlos_bench.environments.local.local_fileshare_env import LocalFileShareEnv\n\n__all__ = [\n 'LocalEnv',\n 'LocalFileShareEnv',\n]\n" }, { "alpha_fraction": 0.6394827365875244, "alphanum_fraction": 0.6405172348022461, "avg_line_length": 34.802467346191406, "blob_id": "49ba48e7abfa36c50b75146d806bd3f248e16f9f", "content_id": "473a67c2f45cf13bc282a0304e15896b9edc2054", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5800, "license_type": "permissive", "max_line_length": 127, "num_lines": 162, "path": "/mlos_bench/mlos_bench/tests/config/schemas/__init__.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nCommon tests for config schemas and their validation and test cases.\n\"\"\"\n\nfrom copy import deepcopy\nfrom dataclasses import dataclass\nfrom typing import Any, Dict, Set\n\nimport os\n\nimport json5\nimport jsonschema\nimport pytest\n\nfrom mlos_bench.config.schemas.config_schemas import ConfigSchema\nfrom mlos_bench.tests.config import locate_config_examples\n\n\n# A dataclass to make pylint happy.\n@dataclass\nclass SchemaTestType:\n \"\"\"\n The different type of schema test cases we expect to have.\n \"\"\"\n\n test_case_type: str\n test_case_subtypes: Set[str]\n\n def __hash__(self) -> int:\n return hash(self.test_case_type)\n\n\n# The different type of schema test cases we expect to have.\n_SCHEMA_TEST_TYPES = {x.test_case_type: x for x in (\n SchemaTestType(test_case_type='good', test_case_subtypes={'full', 'partial'}),\n SchemaTestType(test_case_type='bad', test_case_subtypes={'invalid', 'unhandled'}),\n)}\n\n\n@dataclass\nclass SchemaTestCaseInfo():\n \"\"\"\n Some basic info about a schema test case.\n \"\"\"\n\n config: Dict[str, Any]\n test_case_file: str\n test_case_type: str\n test_case_subtype: str\n\n def __hash__(self) -> int:\n return hash(self.test_case_file)\n\n\ndef check_schema_dir_layout(test_cases_root: str) -> None:\n \"\"\"\n Makes sure the directory layout matches what we expect so we aren't missing\n any extra configs or test cases.\n \"\"\"\n for test_case_dir in os.listdir(test_cases_root):\n if test_case_dir == 'README.md':\n continue\n if test_case_dir not in _SCHEMA_TEST_TYPES:\n raise NotImplementedError(f\"Unhandled test case type: {test_case_dir}\")\n for test_case_subdir in os.listdir(os.path.join(test_cases_root, test_case_dir)):\n if test_case_subdir == 'README.md':\n continue\n if test_case_subdir not in _SCHEMA_TEST_TYPES[test_case_dir].test_case_subtypes:\n raise NotImplementedError(f\"Unhandled test case subtype {test_case_subdir} for test case type {test_case_dir}\")\n\n\n@dataclass\nclass TestCases:\n \"\"\"\n A container for test cases by type.\n \"\"\"\n\n by_path: Dict[str, SchemaTestCaseInfo]\n by_type: Dict[str, Dict[str, SchemaTestCaseInfo]]\n by_subtype: Dict[str, Dict[str, SchemaTestCaseInfo]]\n\n\ndef get_schema_test_cases(test_cases_root: str) -> TestCases:\n \"\"\"\n Gets a dict of schema test cases from the given root.\n \"\"\"\n test_cases = TestCases(by_path={},\n by_type={x: {} for x in _SCHEMA_TEST_TYPES},\n by_subtype={y: {} for x in _SCHEMA_TEST_TYPES for y in _SCHEMA_TEST_TYPES[x].test_case_subtypes})\n check_schema_dir_layout(test_cases_root)\n # Note: we sort the test cases so that we can deterministically test them in parallel.\n for (test_case_type, schema_test_type) in _SCHEMA_TEST_TYPES.items():\n for test_case_subtype in schema_test_type.test_case_subtypes:\n for test_case_file in locate_config_examples(os.path.join(test_cases_root, test_case_type, test_case_subtype)):\n with open(test_case_file, mode='r', encoding='utf-8') as test_case_fh:\n try:\n test_case_info = SchemaTestCaseInfo(\n config=json5.load(test_case_fh),\n test_case_file=test_case_file,\n test_case_type=test_case_type,\n test_case_subtype=test_case_subtype,\n )\n test_cases.by_path[test_case_info.test_case_file] = test_case_info\n test_cases.by_type[test_case_info.test_case_type][test_case_info.test_case_file] = test_case_info\n test_cases.by_subtype[test_case_info.test_case_subtype][test_case_info.test_case_file] = test_case_info\n except Exception as ex:\n raise RuntimeError(\"Failed to load test case: \" + test_case_file) from ex\n assert test_cases\n\n assert len(test_cases.by_type[\"good\"]) > 0\n assert len(test_cases.by_type[\"bad\"]) > 0\n assert len(test_cases.by_subtype) > 2\n\n return test_cases\n\n\ndef check_test_case_against_schema(test_case: SchemaTestCaseInfo, schema_type: ConfigSchema) -> None:\n \"\"\"\n Checks the given test case against the given schema.\n\n Parameters\n ----------\n test_case : SchemaTestCaseInfo\n Schema test case to check.\n schema_type : ConfigSchema\n Schema to check against, e.g., ENVIRONMENT or SERVICE.\n\n Raises\n ------\n NotImplementedError\n If test case is not known.\n \"\"\"\n if test_case.test_case_type == \"good\":\n schema_type.validate(test_case.config)\n elif test_case.test_case_type == \"bad\":\n with pytest.raises(jsonschema.ValidationError):\n schema_type.validate(test_case.config)\n else:\n raise NotImplementedError(f\"Unknown test case type: {test_case.test_case_type}\")\n\n\ndef check_test_case_config_with_extra_param(test_case: SchemaTestCaseInfo, schema_type: ConfigSchema) -> None:\n \"\"\"\n Checks that the config fails to validate if extra params are present in certain places.\n \"\"\"\n config = deepcopy(test_case.config)\n schema_type.validate(config)\n extra_outer_attr = \"extra_outer_attr\"\n config[extra_outer_attr] = \"should not be here\"\n with pytest.raises(jsonschema.ValidationError):\n schema_type.validate(config)\n del config[extra_outer_attr]\n if not config.get(\"config\"):\n config[\"config\"] = {}\n extra_config_attr = \"extra_config_attr\"\n config[\"config\"][extra_config_attr] = \"should not be here\"\n with pytest.raises(jsonschema.ValidationError):\n schema_type.validate(config)\n" }, { "alpha_fraction": 0.7896995544433594, "alphanum_fraction": 0.7896995544433594, "avg_line_length": 30.772727966308594, "blob_id": "fe2d3bca948756698a7d4f3e5d51b3bf8f29ffb5", "content_id": "ebc8bee2e0a37faafcdae30bc9c9bc6b0f376a6c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 699, "license_type": "permissive", "max_line_length": 96, "num_lines": 22, "path": "/mlos_bench/mlos_bench/services/types/__init__.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nService types for implementing declaring Service behavior for Environments to use in mlos_bench.\n\"\"\"\n\nfrom mlos_bench.services.types.config_loader_type import SupportsConfigLoading\nfrom mlos_bench.services.types.fileshare_type import SupportsFileShareOps\nfrom mlos_bench.services.types.vm_provisioner_type import SupportsVMOps\nfrom mlos_bench.services.types.local_exec_type import SupportsLocalExec\nfrom mlos_bench.services.types.remote_exec_type import SupportsRemoteExec\n\n\n__all__ = [\n 'SupportsConfigLoading',\n 'SupportsFileShareOps',\n 'SupportsVMOps',\n 'SupportsLocalExec',\n 'SupportsRemoteExec',\n]\n" }, { "alpha_fraction": 0.6493070125579834, "alphanum_fraction": 0.6518269777297974, "avg_line_length": 33.014286041259766, "blob_id": "b8c2581231afa4c05340eb28c364cea633643267", "content_id": "29f2583b4ab502384417fb1cab5f7d0ac3b6e434", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2381, "license_type": "permissive", "max_line_length": 140, "num_lines": 70, "path": "/.devcontainer/build/build-devcontainer.sh", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#!/bin/bash\n##\n## Copyright (c) Microsoft Corporation.\n## Licensed under the MIT License.\n##\n\nset -x\n\nset -eu\nscriptdir=$(dirname \"$(readlink -f \"$0\")\")\ncd \"$scriptdir/\"\n\n# Build the helper container that has the devcontainer CLI for building the devcontainer.\nNO_CACHE=${NO_CACHE:-} ./build-devcontainer-cli.sh\n\nDOCKER_GID=$(stat -c'%g' /var/run/docker.sock)\n# Make this work inside a devcontainer as well.\nif [ -w /var/run/docker-host.sock ]; then\n DOCKER_GID=$(stat -c'%g' /var/run/docker-host.sock)\nfi\n\n# Build the devcontainer image.\nrootdir=$(readlink -f \"$scriptdir/../..\")\n\n# Run the initialize command on the host first.\n# Note: command should already pull the cached image if possible.\npwd\ndevcontainer_json=$(cat \"$rootdir/.devcontainer/devcontainer.json\" | sed -e 's|//.*||' -e 's|/\\*|\\n&|g;s|*/|&\\n|g' | sed -e '/\\/\\*/,/*\\//d')\ninitializeCommand=$(echo \"$devcontainer_json\" | docker run -i --rm devcontainer-cli jq -e -r '.initializeCommand[]')\nif [ -z \"$initializeCommand\" ]; then\n echo \"No initializeCommand found in devcontainer.json\" >&2\n exit 1\nelse\n eval \"pushd \"$rootdir/\"; $initializeCommand; popd\"\nfi\n\ndevcontainer_build_args=''\nif [ \"${NO_CACHE:-}\" == 'true' ]; then\n base_image=$(grep '^FROM ' \"$rootdir/.devcontainer/Dockerfile\" | sed -e 's/^FROM //' -e 's/ AS .*//' | head -n1)\n docker pull \"$base_image\" || true\n devcontainer_build_args='--no-cache'\nelse\n cache_from='mloscore.azurecr.io/mlos-devcontainer:latest'\n devcontainer_build_args=\"--cache-from $cache_from\"\n tmpdir=$(mktemp -d)\n docker --config=\"$tmpdir\" pull \"$cache_from\" || true\n rmdir \"$tmpdir\"\nfi\n\n# Make this work inside a devcontainer as well.\nif [ -n \"${LOCAL_WORKSPACE_FOLDER:-}\" ]; then\n rootdir=\"$LOCAL_WORKSPACE_FOLDER\"\nfi\n\ndocker run -i --rm \\\n --user $(id -u):$DOCKER_GID \\\n -v \"$rootdir\":/src \\\n -v /var/run/docker.sock:/var/run/docker.sock \\\n --env DOCKER_BUILDKIT=${DOCKER_BUILDKIT:-1} \\\n --env BUILDKIT_INLINE_CACHE=1 \\\n --env http_proxy=${http_proxy:-} \\\n --env https_proxy=${https_proxy:-} \\\n --env no_proxy=${no_proxy:-} \\\n devcontainer-cli \\\n devcontainer build --workspace-folder /src \\\n $devcontainer_build_args \\\n --image-name mlos-devcontainer:latest\nif [ \"${CONTAINER_REGISTRY:-}\" != '' ]; then\n docker tag mlos-devcontainer:latest \"$CONTAINER_REGISTRY/mlos-devcontainer:latest\"\nfi\n" }, { "alpha_fraction": 0.6131436228752136, "alphanum_fraction": 0.6138211488723755, "avg_line_length": 29.75, "blob_id": "e27ed66b3f529b1ed3750686cd57ab7716f89a0a", "content_id": "e33c717953e70cff8b222a497bc2a79a271c1373", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1476, "license_type": "permissive", "max_line_length": 95, "num_lines": 48, "path": "/mlos_bench/mlos_bench/config/environments/apps/redis/scripts/local/process_redis_results.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nScript for post-processing redis-benchmark results.\n\"\"\"\n\nimport argparse\n\nimport pandas as pd\n\n\ndef _main(input_file: str, output_file: str) -> None:\n \"\"\"\n Re-shape Redis benchmark CSV results from wide to long.\n \"\"\"\n df_wide = pd.read_csv(input_file)\n\n # Format the results from wide to long\n # The target is columns of metric and value to act as key-value pairs.\n df_long = (\n df_wide\n .melt(id_vars=[\"test\"])\n .assign(metric=lambda df: df[\"test\"] + \"_\" + df[\"variable\"])\n .drop(columns=[\"test\", \"variable\"])\n .loc[:, [\"metric\", \"value\"]]\n )\n\n # Add a default `score` metric to the end of the dataframe.\n df_long = pd.concat([\n df_long,\n pd.DataFrame({\"metric\": [\"score\"], \"value\": [df_long.value[df_long.index.max()]]})\n ])\n\n df_long.to_csv(output_file, index=False)\n print(f\"Converted: {input_file} -> {output_file}\")\n # print(df_long)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Post-process Redis benchmark results.\")\n parser.add_argument(\"input\", help=\"Redis benchmark results (downloaded from a remote VM).\")\n parser.add_argument(\"output\", help=\"Converted Redis benchmark data\" +\n \" (to be consumed by OS Autotune framework).\")\n args = parser.parse_args()\n _main(args.input, args.output)\n" }, { "alpha_fraction": 0.6765957474708557, "alphanum_fraction": 0.6808510422706604, "avg_line_length": 15.785714149475098, "blob_id": "5db8b331a3b127648586135c63ea12a44b1a5931", "content_id": "48fbc3c0ec518743ded51029c508e9a02624e84b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 235, "license_type": "permissive", "max_line_length": 42, "num_lines": 14, "path": "/mlos_bench/mlos_bench/config/environments/apps/redis/scripts/remote/cleanup-app.sh", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#!/bin/bash\n##\n## Copyright (c) Microsoft Corporation.\n## Licensed under the MIT License.\n##\n\nset -eu\n\nscriptdir=$(dirname \"$(readlink -f \"$0\")\")\ncd \"$scriptdir\"\nsource ./common.sh\n\n# Stop the container.\ndocker stop $REDIS_SERVER_NAME\n" }, { "alpha_fraction": 0.6735445857048035, "alphanum_fraction": 0.6739130616188049, "avg_line_length": 33.35443115234375, "blob_id": "0014e1e70d81a2fa63a33c2533df197985279e7a", "content_id": "f8ef1ff5a9cf5e2d74a27784aaa1fd708048bf52", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2714, "license_type": "permissive", "max_line_length": 118, "num_lines": 79, "path": "/mlos_bench/mlos_bench/tests/config/cli/test_load_cli_config_examples.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTests for loading storage config examples.\n\"\"\"\n\nfrom typing import List\n\nimport logging\n\nimport pytest\n\nfrom mlos_bench.tests.config import locate_config_examples\n\nfrom mlos_bench.config.schemas import ConfigSchema\nfrom mlos_bench.services.config_persistence import ConfigPersistenceService\nfrom mlos_bench.util import path_join\n\n\n_LOG = logging.getLogger(__name__)\n_LOG.setLevel(logging.DEBUG)\n\n\n# Get the set of configs to test.\nCONFIG_TYPE = \"cli\"\n\n\ndef filter_configs(configs_to_filter: List[str]) -> List[str]:\n \"\"\"If necessary, filter out json files that aren't for the module we're testing.\"\"\"\n return configs_to_filter\n\n\nconfigs = filter_configs(locate_config_examples(path_join(ConfigPersistenceService.BUILTIN_CONFIG_PATH, CONFIG_TYPE)))\nassert configs\n\n\[email protected](\"config_path\", configs)\ndef test_load_cli_config_examples(config_loader_service: ConfigPersistenceService, config_path: str) -> None:\n \"\"\"Tests loading a config example.\"\"\"\n config = config_loader_service.load_config(config_path, ConfigSchema.CLI)\n assert isinstance(config, dict)\n\n if config_paths := config.get(\"config_path\"):\n assert isinstance(config_paths, list)\n config_paths.reverse()\n for path in config_paths:\n config_loader_service._config_path.insert(0, path) # pylint: disable=protected-access\n\n # Foreach arg that references another file, see if we can at least load that too.\n args_to_skip = {\n \"config_path\", # handled above\n \"globals\", # we don't commit globals to the repo generally, so skip testing them\n \"log_file\",\n \"log_level\",\n \"experiment_id\",\n \"trial_id\",\n \"teardown\",\n }\n for arg in config:\n if arg in args_to_skip:\n continue\n\n if arg == \"environment\":\n sub_config = config_loader_service.load_config(config[arg], ConfigSchema.ENVIRONMENT)\n assert isinstance(sub_config, dict)\n elif arg == \"optimizer\":\n sub_config = config_loader_service.load_config(config[arg], ConfigSchema.OPTIMIZER)\n assert isinstance(sub_config, dict)\n elif arg == \"storage\":\n sub_config = config_loader_service.load_config(config[arg], ConfigSchema.STORAGE)\n assert isinstance(sub_config, dict)\n elif arg == \"tunable_values\":\n for path in config[arg]:\n sub_config = config_loader_service.load_config(path, ConfigSchema.TUNABLE_VALUES)\n assert isinstance(sub_config, dict)\n else:\n raise NotImplementedError(f\"Unhandled arg {arg} in config {config_path}\")\n" }, { "alpha_fraction": 0.7640430927276611, "alphanum_fraction": 0.7658793330192566, "avg_line_length": 62.39153289794922, "blob_id": "1f82012df90822d34dca1fda6d01540e8bd7600b", "content_id": "095ac2d26b2e92cf46f4e543669abd228ed2dcda", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 11981, "license_type": "permissive", "max_line_length": 324, "num_lines": 189, "path": "/mlos_bench/README.md", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "# mlos-bench\n\nThis directory contains the code for the `mlos-bench` experiment runner package.\n\nIt makes use of the `mlos-core` package for its optimizer.\n\n## Table of Contents\n\n<!-- markdownlint-disable MD007 -->\n\n<!-- TOC -->\n\n- [mlos-bench](#mlos-bench)\n - [Table of Contents](#table-of-contents)\n - [Description](#description)\n - [Features](#features)\n - [Quickstart](#quickstart)\n - [Install and activate the conda environment](#install-and-activate-the-conda-environment)\n - [Make sure that you have Azure CLI tool installed and working](#make-sure-that-you-have-azure-cli-tool-installed-and-working)\n - [Generate access tokens to interact with Azure resources](#generate-access-tokens-to-interact-with-azure-resources)\n - [Create a JSON config with DB credentials Optional](#create-a-json-config-with-db-credentials-optional)\n - [Create a top-level configuration file for your MLOS setup](#create-a-top-level-configuration-file-for-your-mlos-setup)\n - [Create another config file for the parameters specific to your experiment](#create-another-config-file-for-the-parameters-specific-to-your-experiment)\n - [Run the benchmark](#run-the-benchmark)\n - [Optimization](#optimization)\n\n<!-- /TOC -->\n\n<!-- markdownlint-enable MD007 -->\n\n## Description\n\n`mlos-bench` is an end-to-end benchmarking service that can be independently launched for experimentation but is also integrated with `mlos-core` as its optimizer for OS tuning.\n Given a user-provided VM configuration, `mlos-bench` provisions a configured environment and remotely executes benchmarks on the cloud.\n Experiment results (benchmark results & telemetry) are stored as input to the `mlos-core` optimization engine loop to evaluate proposed configuration parameters and produce new results.\n\n## Features\n\nWith a [JSON5](https://spec.json5.org) [config file](./mlos_bench/config/) and command line parameters as input, `mlos-bench` streamlines workload performance measurement by automating the following benchmarking steps:\n\n1. Set up & clean up benchmark and application configuration\n - **Ease of use:** Mlos-bench abstracts away controls for managing VMs in Azure, e.g., setup, teardown, stop, deprovision, and reboot. Get visibility into VM status through Azure Portal, ensuring that a VM is provisioned & running before issuing commands to it.\n - **Versatility:** Mlos-bench provides a common interface to control a collection of environments (application, OS, VM), regardless of where or which cloud they come from. This allows changes to easily propagate to all environment layers when a new set of kernel parameters are applied.\n - **Efficiency:** In adapting an environment to new parameters, mlos-bench optimizes for low re-configuration costs during optimization. For example, considering that not all OS kernel parameter adjustments require a full reboot, as some can be changed during run-time.\n2. Run benchmarks in the provisioned environment & standardize results for the optimizer\n - Through Azure File Share, access docker scripts to run benchmarks & store results as input for optimization. For example, execute Redis benchmark uploaded to the file share, running a benchmark docker container with specified parameters. The file share is mounted to VMs via remote execution, instead of ARM templates.\n - **Configurable:** Specify a python script in the initial config to post-process & standardize benchmark results. An example post-processing script for Redis benchmarks is included.\n - **Local & remote benchmark execution:** Benchmarks can be run both locally in Hyper-V and remotely on Azure. Local execution allows better accuracy, while Azure runs are required to estimate the benchmark noise and understand the VM behavior when using cloud storage.\n - **Cloud agnostic:** Mlos-bench can remotely execute benchmarks on other clouds, outside of Azure - e.g., controls for EC2 instances and ability to provision environments on AWS with Terraform.\n - **Persistence:** Storage integration is available to persist experiment parameters and track results for re-use, either for analysis during & after trials, or warm-starting future experiments.\n\n## Quickstart\n\nTo get started, we can adapt an example configuration to test out running `mlos-bench`.\nFor these instructions, we will be using Azure for our resources.\n\n### 1. Install and activate the conda environment\n\nFrom here onwards we assume we are in the project root directory.\nEnsure you have a conda environment (`mlos`) set up for executing `mlos_bench`.\nCreate and activate the environment with:\n\n```sh\nconda env create -f conda-envs/mlos.yml\nconda activate mlos\n```\n\n> Note: if you are running inside the devcontainer, this should be done automatically.\n\n### 2. Make sure that you have Azure CLI tool installed and working\n\n> Installation instructions for `az` (Azure CLI) [can be found here](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli).\n>\n> Note: `az` comes preinstalled inside the devcontainer.\n\nIf necessary, login to Azure and set your default subscription:\n\n```shell\n# If using az cli for the first time, a login will be required:\naz login\n# Make sure to set your default subscription, RG, and Storage Account for these experiments.\n# For instance:\naz account set --subscription \"My Subscription Name\"\naz config set defaults.group=MyRG --local\naz config set storage.account=MyStorageAccount --local\naz account set --subscription \"...\"\n```\n\n### 3. Generate access tokens to interact with Azure resources\n\nA script at `./scripts/generate-azure-credentials-config` produces a JSON config snippet with necessary Azure credentials.\n\n```shell\n./scripts/generate-azure-credentials-config > ./global_config_azure.json\n```\n\nThis data produced in the `global_config_azure.json` file is in the format that can be used by our framework.\n\n```jsonc\n{\n \"subscription\": \"some-guid\",\n \"tenant\": \"some-other-guid\",\n \"storageAccountKey\": \"some-base-64-encoded-key\",\n}\n```\n\n> Note: On Linux, this script also requires `jq` to also be installed (comes preinstalled in the devcontainer).\n\n### 4. Create a JSON config with DB credentials (Optional)\n\nIf you plan to store the information about experiments and benchmarks in a (remote) database like PostgreSQL or MySQL, create a JSON/JSONC file with the DB hostname and password.\nSee [`mysql.jsonc`](./mlos_bench/config/storage/mysql.jsonc) or [`postgresql.jsonc`](./mlos_bench/config/storage/postgresql.jsonc) configuration files for examples with a more complete list of DB parameters supported by underlying the [SqlAlchemy](https://www.sqlalchemy.org/library.html#reference) library.\nSave your config in `./global_config_storage.jsonc` file.\nIt should look like this:\n\n```jsonc\n{\n \"host\": \"mysql-db.mysql.database.azure.com\",\n \"password\": \"database_password\"\n}\n```\n\nAny parameter that is not specified in `./global_config_storage.json` will be taken from the corresponding DB's config file, e.g., [`postgresql.jsonc`](./mlos_bench/config/storage/postgresql.jsonc).\n\nFor database like SQLite or DuckDB, there is no need for an additional config file.\nThe data will be stored locally in a file, e.g., `./mlos_bench.duckdb`.\nSee [`sqlite.jsonc`](./mlos_bench/config/storage/sqlite.jsonc) or [`duckdb.jsonc`](./mlos_bench/config/storage/duckdb.jsonc) for more details.\n\n> Note: if no storage is specified, a basic sqlite config will be used by default.\n\n### 5. Create a top-level configuration file for your MLOS setup\n\nWe provide a few examples of such files in [`./mlos_bench/config/cli/`](./mlos_bench/config/cli).\nFor example, [`azure-redis-opt.jsonc`](./mlos_bench/config/cli/azure-redis-opt.jsonc) is a configuration for optimizing Redis VM on Azure and saving the results in a local SQLite database.\nLikewise, [`azure-redis-bench.jsonc`](./mlos_bench/config/cli/azure-redis-bench.jsonc) is a setup to run a single Redis benchmark (and, again, save the results in SQLite).\n\nCLI configs like those are meant to connect several MLOS components together, namely:\n\n- Benchmarking environment (configured in [`environments/root/root-azure-redis.jsonc`](./mlos_bench/config/environments/root/root-azure-redis.jsonc));\n- Optimization engine ([`optimizers/mlos_core_flaml.jsonc`](./mlos_bench/config/optimizers/mlos_core_flaml.jsonc));\n- Storage for experimental data ([`storage/sqlite.jsonc`](./mlos_bench/config/storage/sqlite.jsonc));\n\nThey also refer to other configs, e.g.\n\n- Reusable config snippets in `\"config_path\"` section, and\n- Additional config files containing sensitive data like DB passwords and Azure credentials.\n\n> Make sure that the files `./global_config_azure.json` and `./global_config_storage.json` you created in the previous steps are included in the `\"globals\"` section of your CLI config.\n\nFor the purpose of this tutorial, we will assume that we reuse the existing [`azure-redis-bench.jsonc`](./mlos_bench/config/cli/azure-redis-bench.jsonc) and [`azure-redis-opt.jsonc`](./mlos_bench/config/cli/azure-redis-opt.jsonc) configurations without any changes.\nIn a more realistic scenario, however, you might need to change and/or create new config files for some parts of your benchmarking environment.\nWe'll give more details on that below.\n\n### 5. Create another config file for the parameters specific to your experiment\n\nCopy one of our examples, e.g., [`experiment_RedisBench.jsonc`](./mlos_bench/config/experiments/experiment_RedisBench.jsonc) and name it after your experiment, e.g. `experiment_MyBenchmark.jsonc`.\n\nIn that file, you can specify any parameters that occur in your other configs, namely in `\"const_args\"` section of the Environment configs, or in `\"config\"` sections of your Service, Storage, or Optimizer configurations.\n\n> A general rule is that the parameters from the global configs like `./global_config_azure.json` or `experiment_MyAppBench.jsonc` override the corresponding parameters in other configurations.\n> That allows us to propagate the values of the parameters that are specific to the experiment into other components of the framework and keep the majority of the config files in our library immutable and reusable.\n\n### 6. Run the benchmark\n\nNow we can run our configuration with `mlos_bench`:\n\n```shell\nmlos_bench --config \"./mlos_bench/mlos_bench/config/cli/azure-redis-bench.jsonc\" --globals \"experiment_MyBenchmark.jsonc\"\n```\n\nThis should run a single trial with the given tunable values (loaded from one or more files in the `\"tunable_values\"`), write the results to the log and keep the environment running (as directed by the `\"teardown\": false` configuration parameter in the CLI config).\n\nNote that using the `--globals` command line option is the same as adding `experiment_MyBenchmark.jsonc` to the `\"globals\"` section of the CLI config.\nSame applies to all other CLI parameters - e.g., you can change the log level by adding `--log_level INFO` to the command line.\n\nAlso, note that you don't have to provide full path to the `experiment_MyBenchmark.jsonc` file - the application will look for it in the paths specified in the `\"config_path\"` section of the CLI config.\n\n## Optimization\n\nSearching for an optimal set of tunable parameters is very similar to running a single benchmark.\nAll we have to do is specifying the [`Optimizer`](./mlos_bench/optimizers/) in the top-level configuration, like in our [`azure-redis-opt.jsonc`](./mlos_bench/config/cli/azure-redis-opt.jsonc) example.\n\n```sh\nmlos_bench --config \"./mlos_bench/mlos_bench/config/cli/azure-redis-opt.jsonc\" --globals \"experiment_MyBenchmark.jsonc --max_iterations 10\"\n```\n\nNote that again we use the command line option `--max_iterations` to override the default value from [`mlos_core_flaml.jsonc`](./mlos_bench/config/optimizers/mlos_core_flaml.jsonc).\n\nWe don't have to specify the `\"tunable_values\"` for the optimization: the optimizer will suggest new values on each iteration and the framework will feed this data into the benchmarking environment.\n" }, { "alpha_fraction": 0.6996209025382996, "alphanum_fraction": 0.6996209025382996, "avg_line_length": 42.40506362915039, "blob_id": "14ebe73bf6d72435daa39b1a5ae5d42ec57e46e3", "content_id": "a57cb6d09a9281eba83deabba152690eff630072", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3429, "license_type": "permissive", "max_line_length": 113, "num_lines": 79, "path": "/mlos_bench/mlos_bench/tests/config/schemas/environments/test_environment_schemas.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTests for environment schema validation.\n\"\"\"\n\nfrom os import path\n\nimport pytest\n\nfrom mlos_core.tests import get_all_concrete_subclasses\n\nfrom mlos_bench.config.schemas import ConfigSchema\nfrom mlos_bench.environments.base_environment import Environment\nfrom mlos_bench.environments.composite_env import CompositeEnv\nfrom mlos_bench.environments.script_env import ScriptEnv\n\nfrom mlos_bench.tests import try_resolve_class_name\nfrom mlos_bench.tests.config.schemas import (get_schema_test_cases,\n check_test_case_against_schema,\n check_test_case_config_with_extra_param)\n\n\n# General testing strategy:\n# - hand code a set of good/bad configs (useful to test editor schema checking)\n# - enumerate and try to check that we've covered all the cases\n# - for each config, load and validate against expected schema\n\nTEST_CASES = get_schema_test_cases(path.join(path.dirname(__file__), \"test-cases\"))\n\n\n# Dynamically enumerate some of the cases we want to make sure we cover.\n\nNON_CONFIG_ENV_CLASSES = {\n ScriptEnv # ScriptEnv is ABCMeta abstract, but there's no good way to test that dynamically in Python.\n}\nexpected_environment_class_names = [subclass.__module__ + \".\" + subclass.__name__\n for subclass\n in get_all_concrete_subclasses(Environment, pkg_name='mlos_bench')\n if subclass not in NON_CONFIG_ENV_CLASSES]\nassert expected_environment_class_names\n\nCOMPOSITE_ENV_CLASS_NAME = CompositeEnv.__module__ + \".\" + CompositeEnv.__name__\nexpected_leaf_environment_class_names = [subclass_name for subclass_name in expected_environment_class_names\n if subclass_name != COMPOSITE_ENV_CLASS_NAME]\n\n\n# Do the full cross product of all the test cases and all the Environment types.\[email protected](\"test_case_subtype\", sorted(TEST_CASES.by_subtype))\[email protected](\"env_class\", expected_environment_class_names)\ndef test_case_coverage_mlos_bench_environment_type(test_case_subtype: str, env_class: str) -> None:\n \"\"\"\n Checks to see if there is a given type of test case for the given mlos_bench Environment type.\n \"\"\"\n for test_case in TEST_CASES.by_subtype[test_case_subtype].values():\n if try_resolve_class_name(test_case.config.get(\"class\")) == env_class:\n return\n raise NotImplementedError(\n f\"Missing test case for subtype {test_case_subtype} for Environment class {env_class}\")\n\n\n# Now we actually perform all of those validation tests.\n\[email protected](\"test_case_name\", sorted(TEST_CASES.by_path))\ndef test_environment_configs_against_schema(test_case_name: str) -> None:\n \"\"\"\n Checks that the environment config validates against the schema.\n \"\"\"\n check_test_case_against_schema(TEST_CASES.by_path[test_case_name], ConfigSchema.ENVIRONMENT)\n\n\[email protected](\"test_case_name\", sorted(TEST_CASES.by_type[\"good\"]))\ndef test_environment_configs_with_extra_param(test_case_name: str) -> None:\n \"\"\"\n Checks that the environment config fails to validate if extra params are present in certain places.\n \"\"\"\n check_test_case_config_with_extra_param(TEST_CASES.by_type[\"good\"][test_case_name], ConfigSchema.ENVIRONMENT)\n" }, { "alpha_fraction": 0.6855670213699341, "alphanum_fraction": 0.7010309100151062, "avg_line_length": 18.399999618530273, "blob_id": "24210c9e9002a6df336deab8a5ef44081ed6c138", "content_id": "c89ae10815f2e2491051c6070d27461d1b3cd665", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 194, "license_type": "permissive", "max_line_length": 46, "num_lines": 10, "path": "/mlos_bench/_version.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nVersion number for the mlos_core package.\n\"\"\"\n\n# NOTE: This should be managed by bumpversion.\n_VERSION = '0.1.0'\n" }, { "alpha_fraction": 0.6548871994018555, "alphanum_fraction": 0.6568205952644348, "avg_line_length": 40.5625, "blob_id": "1aa6a4319cda14a1d56bdb32fb990d9c70930588", "content_id": "bac8efaa20f6bab6fa21f4a8afeeacb9d5bd5d7d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9310, "license_type": "permissive", "max_line_length": 131, "num_lines": 224, "path": "/mlos_bench/mlos_bench/tests/services/remote/azure/azure_fileshare_test.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nTests for mlos_bench.services.remote.azure.azure_fileshare\n\"\"\"\n\nimport os\nfrom unittest.mock import MagicMock, Mock, patch, call\n\nfrom mlos_bench.services.remote.azure.azure_fileshare import AzureFileShareService\n\n# pylint: disable=missing-function-docstring\n# pylint: disable=too-many-arguments\n# pylint: disable=unused-argument\n\n\n@patch(\"mlos_bench.services.remote.azure.azure_fileshare.open\")\n@patch(\"mlos_bench.services.remote.azure.azure_fileshare.os.makedirs\")\ndef test_download_file(mock_makedirs: MagicMock, mock_open: MagicMock, azure_fileshare: AzureFileShareService) -> None:\n filename = \"test.csv\"\n remote_folder = \"a/remote/folder\"\n local_folder = \"some/local/folder\"\n remote_path = f\"{remote_folder}/{filename}\"\n local_path = f\"{local_folder}/{filename}\"\n mock_share_client = azure_fileshare._share_client # pylint: disable=protected-access\n with patch.object(mock_share_client, \"get_file_client\") as mock_get_file_client, \\\n patch.object(mock_share_client, \"get_directory_client\") as mock_get_directory_client:\n mock_get_directory_client.return_value = Mock(exists=Mock(return_value=False))\n\n azure_fileshare.download(remote_path, local_path)\n\n mock_get_file_client.assert_called_with(remote_path)\n\n mock_makedirs.assert_called_with(\n local_folder,\n exist_ok=True,\n )\n open_path, open_mode = mock_open.call_args.args\n assert os.path.abspath(local_path) == os.path.abspath(open_path)\n assert open_mode == \"wb\"\n\n\ndef make_dir_client_returns(remote_folder: str) -> dict:\n return {\n remote_folder: Mock(\n exists=Mock(return_value=True),\n list_directories_and_files=Mock(return_value=[\n {\"name\": \"a_folder\", \"is_directory\": True},\n {\"name\": \"a_file_1.csv\", \"is_directory\": False},\n ])\n ),\n f\"{remote_folder}/a_folder\": Mock(\n exists=Mock(return_value=True),\n list_directories_and_files=Mock(return_value=[\n {\"name\": \"a_file_2.csv\", \"is_directory\": False},\n ])\n ),\n f\"{remote_folder}/a_file_1.csv\": Mock(\n exists=Mock(return_value=False)\n ),\n f\"{remote_folder}/a_folder/a_file_2.csv\": Mock(\n exists=Mock(return_value=False)\n ),\n }\n\n\n@patch(\"mlos_bench.services.remote.azure.azure_fileshare.open\")\n@patch(\"mlos_bench.services.remote.azure.azure_fileshare.os.makedirs\")\ndef test_download_folder_non_recursive(mock_makedirs: MagicMock,\n mock_open: MagicMock,\n azure_fileshare: AzureFileShareService) -> None:\n remote_folder = \"a/remote/folder\"\n local_folder = \"some/local/folder\"\n dir_client_returns = make_dir_client_returns(remote_folder)\n mock_share_client = azure_fileshare._share_client # pylint: disable=protected-access\n with patch.object(mock_share_client, \"get_directory_client\") as mock_get_directory_client, \\\n patch.object(mock_share_client, \"get_file_client\") as mock_get_file_client:\n\n mock_get_directory_client.side_effect = lambda x: dir_client_returns[x]\n\n azure_fileshare.download(remote_folder, local_folder, recursive=False)\n\n mock_get_file_client.assert_called_with(\n f\"{remote_folder}/a_file_1.csv\",\n )\n mock_get_directory_client.assert_has_calls([\n call(remote_folder),\n call(f\"{remote_folder}/a_file_1.csv\"),\n ], any_order=True)\n\n\n@patch(\"mlos_bench.services.remote.azure.azure_fileshare.open\")\n@patch(\"mlos_bench.services.remote.azure.azure_fileshare.os.makedirs\")\ndef test_download_folder_recursive(mock_makedirs: MagicMock, mock_open: MagicMock, azure_fileshare: AzureFileShareService) -> None:\n remote_folder = \"a/remote/folder\"\n local_folder = \"some/local/folder\"\n dir_client_returns = make_dir_client_returns(remote_folder)\n mock_share_client = azure_fileshare._share_client # pylint: disable=protected-access\n with patch.object(mock_share_client, \"get_directory_client\") as mock_get_directory_client, \\\n patch.object(mock_share_client, \"get_file_client\") as mock_get_file_client:\n mock_get_directory_client.side_effect = lambda x: dir_client_returns[x]\n\n azure_fileshare.download(remote_folder, local_folder, recursive=True)\n\n mock_get_file_client.assert_has_calls([\n call(f\"{remote_folder}/a_file_1.csv\"),\n call(f\"{remote_folder}/a_folder/a_file_2.csv\"),\n ], any_order=True)\n mock_get_directory_client.assert_has_calls([\n call(remote_folder),\n call(f\"{remote_folder}/a_file_1.csv\"),\n call(f\"{remote_folder}/a_folder\"),\n call(f\"{remote_folder}/a_folder/a_file_2.csv\"),\n ], any_order=True)\n\n\n@patch(\"mlos_bench.services.remote.azure.azure_fileshare.open\")\n@patch(\"mlos_bench.services.remote.azure.azure_fileshare.os.path.isdir\")\ndef test_upload_file(mock_isdir: MagicMock, mock_open: MagicMock, azure_fileshare: AzureFileShareService) -> None:\n filename = \"test.csv\"\n remote_folder = \"a/remote/folder\"\n local_folder = \"some/local/folder\"\n remote_path = f\"{remote_folder}/{filename}\"\n local_path = f\"{local_folder}/{filename}\"\n mock_share_client = azure_fileshare._share_client # pylint: disable=protected-access\n mock_isdir.return_value = False\n\n with patch.object(mock_share_client, \"get_file_client\") as mock_get_file_client:\n azure_fileshare.upload(local_path, remote_path)\n\n mock_get_file_client.assert_called_with(remote_path)\n open_path, open_mode = mock_open.call_args.args\n assert os.path.abspath(local_path) == os.path.abspath(open_path)\n assert open_mode == \"rb\"\n\n\nclass MyDirEntry:\n # pylint: disable=too-few-public-methods\n \"\"\"Dummy class for os.DirEntry\"\"\"\n def __init__(self, name: str, is_a_dir: bool):\n self.name = name\n self.is_a_dir = is_a_dir\n\n def is_dir(self) -> bool:\n return self.is_a_dir\n\n\ndef make_scandir_returns(local_folder: str) -> dict:\n return {\n local_folder: [\n MyDirEntry(\"a_folder\", True),\n MyDirEntry(\"a_file_1.csv\", False),\n ],\n f\"{local_folder}/a_folder\": [\n MyDirEntry(\"a_file_2.csv\", False),\n ],\n }\n\n\ndef make_isdir_returns(local_folder: str) -> dict:\n return {\n local_folder: True,\n f\"{local_folder}/a_file_1.csv\": False,\n f\"{local_folder}/a_folder\": True,\n f\"{local_folder}/a_folder/a_file_2.csv\": False,\n }\n\n\ndef process_paths(input_path: str) -> str:\n skip_prefix = os.getcwd()\n # Remove prefix from os.path.abspath if there\n if input_path == os.path.abspath(input_path):\n result = input_path[len(skip_prefix) + 1:]\n else:\n result = input_path\n # Change file seps to unix-style\n return result.replace(\"\\\\\", \"/\")\n\n\n@patch(\"mlos_bench.services.remote.azure.azure_fileshare.open\")\n@patch(\"mlos_bench.services.remote.azure.azure_fileshare.os.path.isdir\")\n@patch(\"mlos_bench.services.remote.azure.azure_fileshare.os.scandir\")\ndef test_upload_directory_non_recursive(mock_scandir: MagicMock,\n mock_isdir: MagicMock,\n mock_open: MagicMock,\n azure_fileshare: AzureFileShareService) -> None:\n remote_folder = \"a/remote/folder\"\n local_folder = \"some/local/folder\"\n scandir_returns = make_scandir_returns(local_folder)\n isdir_returns = make_isdir_returns(local_folder)\n mock_scandir.side_effect = lambda x: scandir_returns[process_paths(x)]\n mock_isdir.side_effect = lambda x: isdir_returns[process_paths(x)]\n mock_share_client = azure_fileshare._share_client # pylint: disable=protected-access\n\n with patch.object(mock_share_client, \"get_file_client\") as mock_get_file_client:\n azure_fileshare.upload(local_folder, remote_folder, recursive=False)\n\n mock_get_file_client.assert_called_with(f\"{remote_folder}/a_file_1.csv\")\n\n\n@patch(\"mlos_bench.services.remote.azure.azure_fileshare.open\")\n@patch(\"mlos_bench.services.remote.azure.azure_fileshare.os.path.isdir\")\n@patch(\"mlos_bench.services.remote.azure.azure_fileshare.os.scandir\")\ndef test_upload_directory_recursive(mock_scandir: MagicMock,\n mock_isdir: MagicMock,\n mock_open: MagicMock,\n azure_fileshare: AzureFileShareService) -> None:\n remote_folder = \"a/remote/folder\"\n local_folder = \"some/local/folder\"\n scandir_returns = make_scandir_returns(local_folder)\n isdir_returns = make_isdir_returns(local_folder)\n mock_scandir.side_effect = lambda x: scandir_returns[process_paths(x)]\n mock_isdir.side_effect = lambda x: isdir_returns[process_paths(x)]\n mock_share_client = azure_fileshare._share_client # pylint: disable=protected-access\n\n with patch.object(mock_share_client, \"get_file_client\") as mock_get_file_client:\n azure_fileshare.upload(local_folder, remote_folder, recursive=True)\n\n mock_get_file_client.assert_has_calls([\n call(f\"{remote_folder}/a_file_1.csv\"),\n call(f\"{remote_folder}/a_folder/a_file_2.csv\"),\n ], any_order=True)\n" }, { "alpha_fraction": 0.5886176228523254, "alphanum_fraction": 0.5886176228523254, "avg_line_length": 39.1783447265625, "blob_id": "fe15bdcbc27e00a2a098508f424ec8f9b594db03", "content_id": "ae48d66db4535d22220c87f309624a8fb3b65163", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6308, "license_type": "permissive", "max_line_length": 98, "num_lines": 157, "path": "/mlos_bench/mlos_bench/services/remote/azure/azure_fileshare.py", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n#\n\"\"\"\nA collection FileShare functions for interacting with Azure File Shares.\n\"\"\"\n\nimport os\nimport logging\n\nfrom typing import Any, Dict, Optional, Set\n\nfrom azure.storage.fileshare import ShareClient\nfrom azure.core.exceptions import ResourceNotFoundError\n\nfrom mlos_bench.services.base_service import Service\nfrom mlos_bench.services.base_fileshare import FileShareService\nfrom mlos_bench.util import check_required_params\n\n_LOG = logging.getLogger(__name__)\n\n\nclass AzureFileShareService(FileShareService):\n \"\"\"\n Helper methods for interacting with Azure File Share\n \"\"\"\n\n _SHARE_URL = \"https://{account_name}.file.core.windows.net/{fs_name}\"\n\n def __init__(self,\n config: Optional[Dict[str, Any]] = None,\n global_config: Optional[Dict[str, Any]] = None,\n parent: Optional[Service] = None):\n \"\"\"\n Create a new file share Service for Azure environments with a given config.\n\n Parameters\n ----------\n config : dict\n Free-format dictionary that contains the file share configuration.\n It will be passed as a constructor parameter of the class\n specified by `class_name`.\n global_config : dict\n Free-format dictionary of global parameters.\n parent : Service\n Parent service that can provide mixin functions.\n \"\"\"\n super().__init__(config, global_config, parent)\n\n check_required_params(\n self.config, {\n \"storageAccountName\",\n \"storageFileShareName\",\n \"storageAccountKey\",\n }\n )\n\n self._share_client = ShareClient.from_share_url(\n AzureFileShareService._SHARE_URL.format(\n account_name=self.config[\"storageAccountName\"],\n fs_name=self.config[\"storageFileShareName\"],\n ),\n credential=self.config[\"storageAccountKey\"],\n )\n\n def download(self, remote_path: str, local_path: str, recursive: bool = True) -> None:\n super().download(remote_path, local_path, recursive)\n dir_client = self._share_client.get_directory_client(remote_path)\n if dir_client.exists():\n os.makedirs(local_path, exist_ok=True)\n for content in dir_client.list_directories_and_files():\n name = content[\"name\"]\n local_target = f\"{local_path}/{name}\"\n remote_target = f\"{remote_path}/{name}\"\n if recursive or not content[\"is_directory\"]:\n self.download(remote_target, local_target, recursive)\n else: # Must be a file\n # Ensure parent folders exist\n folder, _ = os.path.split(local_path)\n os.makedirs(folder, exist_ok=True)\n file_client = self._share_client.get_file_client(remote_path)\n try:\n data = file_client.download_file()\n with open(local_path, \"wb\") as output_file:\n _LOG.debug(\"Download file: %s -> %s\", remote_path, local_path)\n data.readinto(output_file) # type: ignore[no-untyped-call]\n except ResourceNotFoundError as ex:\n # Translate into non-Azure exception:\n raise FileNotFoundError(\"Cannot download: {remote_path}\") from ex\n\n def upload(self, local_path: str, remote_path: str, recursive: bool = True) -> None:\n super().upload(local_path, remote_path, recursive)\n self._upload(local_path, remote_path, recursive, set())\n\n def _upload(self, local_path: str, remote_path: str, recursive: bool, seen: Set[str]) -> None:\n \"\"\"\n Upload contents from a local path to an Azure file share.\n This method is called from `.upload()` above. We need it to avoid exposing\n the `seen` parameter and to make `.upload()` match the base class' virtual\n method.\n\n Parameters\n ----------\n local_path : str\n Path to the local directory to upload contents from, either a file or directory.\n remote_path : str\n Path in the remote file share to store the uploaded content to.\n recursive : bool\n If False, ignore the subdirectories;\n if True (the default), upload the entire directory tree.\n seen: Set[str]\n Helper set for keeping track of visited directories to break circular paths.\n \"\"\"\n local_path = os.path.abspath(local_path)\n if local_path in seen:\n _LOG.warning(\"Loop in directories, skipping '%s'\", local_path)\n return\n seen.add(local_path)\n\n if os.path.isdir(local_path):\n dir_client = self._share_client.get_directory_client(remote_path)\n if not dir_client.exists():\n dir_client.create_directory()\n for entry in os.scandir(local_path):\n name = entry.name\n local_target = f\"{local_path}/{name}\"\n remote_target = f\"{remote_path}/{name}\"\n if recursive or not entry.is_dir():\n self._upload(local_target, remote_target, recursive, seen)\n else:\n # Ensure parent folders exist\n folder, _ = os.path.split(remote_path)\n self._remote_makedirs(folder)\n file_client = self._share_client.get_file_client(remote_path)\n with open(local_path, \"rb\") as file_data:\n _LOG.debug(\"Upload file: %s -> %s\", local_path, remote_path)\n file_client.upload_file(file_data)\n\n def _remote_makedirs(self, remote_path: str) -> None:\n \"\"\"\n Create remote directories for the entire path.\n Succeeds even some or all directories along the path already exist.\n\n Parameters\n ----------\n remote_path : str\n Path in the remote file share to create.\n \"\"\"\n path = \"\"\n for folder in remote_path.replace(\"\\\\\", \"/\").split(\"/\"):\n if not folder:\n continue\n path += folder + \"/\"\n dir_client = self._share_client.get_directory_client(path)\n if not dir_client.exists():\n dir_client.create_directory()\n" }, { "alpha_fraction": 0.7418806552886963, "alphanum_fraction": 0.7462235689163208, "avg_line_length": 47.14545440673828, "blob_id": "06d8a06256c7aa8e22e695a2c450c4877dfd815c", "content_id": "ef180fcbdc7d33b9204d43d599f825c692a908e5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5296, "license_type": "permissive", "max_line_length": 532, "num_lines": 110, "path": "/README.md", "repo_name": "microsoft/MLOS", "src_encoding": "UTF-8", "text": "# MLOS\n\n[![MLOS DevContainer](https://github.com/microsoft/MLOS/actions/workflows/devcontainer.yml/badge.svg)](https://github.com/microsoft/MLOS/actions/workflows/devcontainer.yml)\n[![MLOS Linux](https://github.com/microsoft/MLOS/actions/workflows/linux.yml/badge.svg)](https://github.com/microsoft/MLOS/actions/workflows/linux.yml)\n[![MLOS Windows](https://github.com/microsoft/MLOS/actions/workflows/windows.yml/badge.svg)](https://github.com/microsoft/MLOS/actions/workflows/windows.yml)\n[![Code Coverage Status](https://microsoft.github.io/MLOS/_images/coverage.svg)](https://microsoft.github.io/MLOS/htmlcov/index.html)\n\nThis repository contains a stripped down implementation of essentially just the core optimizer and config space description APIs from the original [MLOS](https://github.com/microsoft/MLOS)<!-- /tree/deprecated --> as well as the [`mlos-bench`](./mlos_bench/) module intended to help automate and manage running experiments for autotuning systems with [`mlos-core`](./mlos_core/).\n\nIt is intended to provide a simplified, easier to consume (e.g. via `pip`), with lower dependencies abstraction to\n\n- describe a space of context, parameters, their ranges, constraints, etc. and result objectives\n- an \"optimizer\" service [abstraction](https://microsoft.github.io/MLOS/overview.html#mlos-core-api) (e.g. [`register()`](https://microsoft.github.io/MLOS/generated/mlos_core.optimizers.optimizer.BaseOptimizer.html#mlos_core.optimizers.optimizer.BaseOptimizer.register) and [`suggest()`](https://microsoft.github.io/MLOS/generated/mlos_core.optimizers.optimizer.BaseOptimizer.html#mlos_core.optimizers.optimizer.BaseOptimizer.suggest)) so we can easily swap out different implementations methods of searching (e.g. random, BO, etc.)\n- provide some helpers for [automating optimization experiment](https://microsoft.github.io/MLOS/overview.html#mlos-bench-api) runner loops and data collection\n\nFor these design requirements we intend to reuse as much from existing OSS libraries as possible and layer policies and optimizations specifically geared towards autotuning over top.\n\n## Getting Started\n\nThe development environment for MLOS uses `conda` to ease dependency management.\n\n### Devcontainer\n\nFor a quick start, you can use the provided [VSCode devcontainer](https://code.visualstudio.com/docs/remote/containers) configuration.\n\nSimply open the project in VSCode and follow the prompts to build and open the devcontainer and the conda environment and additional tools will be installed automatically inside the container.\n\n### Manually\n\n> See Also: [`conda` install instructions](https://docs.conda.io/projects/conda/en/latest/user-guide/install/index.html)\n>\n> Note: to support Windows we currently rely on some pre-compiled packages from `conda-forge` channels, which increases the `conda` solver time during environment create/update.\n>\n> To work around this the (currently) experimental `libmamba` solver can be used.\n>\n> See <https://github.com/conda-incubator/conda-libmamba-solver#getting-started> for more details.\n\n0. Create the `mlos` Conda environment.\n\n ```sh\n conda env create -f conda-envs/mlos.yml\n ```\n\n > See the [`conda-envs/`](./conda-envs/) directory for additional conda environment files, including those used for Windows (e.g. [`mlos-windows.yml`](./conda-envs/mlos-windows.yml)).\n\n or\n\n ```sh\n # This will also ensure the environment is update to date using \"conda env update -f conda-envs/mlos.yml\"\n make conda-env\n ```\n\n > Note: the latter expects a *nix environment.\n\n1. Initialize the shell environment.\n\n ```sh\n conda activate mlos\n ```\n\n2. For an example of using the `mlos_core` optimizer APIs run the [`BayesianOptimization.ipynb`](./mlos_core/notebooks/BayesianOptimization.ipynb) notebook.\n\n3. For an example of using the `mlos_bench` tool to run an experiment, see the [`mlos_bench` Quickstart README](./mlos_bench/README.md#quickstart).\n\n Here's a quick summary:\n\n ```shell\n ./scripts/generate-azure-credentials-config > global_config_azure.json\n\n # run a simple experiment\n mlos_bench --config ./mlos_bench/mlos_bench/config/cli/azure-redis-1shot.jsonc\n ```\n\n > See Also:\n >\n > - [mlos_bench/README.md](./mlos_bench/README.md) for a complete example.\n > - [mlos_bench/config](./mlos_bench/mlos_bench/config/) for additional configuration details\n\n## Distributing\n\n1. Build the *wheel* file(s)\n\n ```sh\n make dist\n ```\n\n2. Install it (e.g. after copying it somewhere else).\n\n ```sh\n # this will install just the optimizer component with SMAC support:\n pip install dist/mlos_core-0.1.0-py3-none-any.whl[smac]\n\n # this will install just the optimizer component with flaml support:\n pip install dist/mlos_core-0.1.0-py3-none-any.whl[flaml]\n\n # this will install just the optimizer component with smac and flaml support:\n pip install dist/mlos_core-0.1.0-py3-none-any.whl[smac,flaml]\n ```\n\n ```sh\n # this will install both the optimizer and the experiment runner:\n pip install dist/mlos_bench-0.1.0-py3-none-any.whl\n ```\n\n > Note: exact versions may differ due to automatic versioning.\n\n## See Also\n\n- API and Examples Documentation: <https://aka.ms/mlos-core/docs>\n- Source Code Repository: <https://aka.ms/mlos-core/src>\n" } ]
195
llq20133100095/lightgbm_scipy
https://github.com/llq20133100095/lightgbm_scipy
31b383d35020c5946e6d9d48984ba280e8dd0e19
53ee1dd481494b9f4ec346f506882d2a7274860b
c3a68142fcfc8fabcb205acef47de93f048cb7e2
refs/heads/master
2020-04-29T16:07:13.724832
2019-03-18T11:51:10
2019-03-18T11:51:10
176,248,599
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5579360127449036, "alphanum_fraction": 0.5790585279464722, "avg_line_length": 27.06779670715332, "blob_id": "5a20aaf4c9e3e08867db22215eb0aaf69b53a711", "content_id": "f9d3259f619feb05f7131c87effe0de3c74abb00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3316, "license_type": "no_license", "max_line_length": 109, "num_lines": 118, "path": "/u.py", "repo_name": "llq20133100095/lightgbm_scipy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 25 20:51:04 2018\n\n@author: llq\n\"\"\"\nimport pandas as pd\nimport lightgbm as lgb\nfrom sklearn.feature_extraction.text import CountVectorizer,TfidfVectorizer\nfrom sklearn.preprocessing import OneHotEncoder,LabelEncoder\nfrom scipy import sparse\nimport os\nimport gc\nimport math\nimport numpy as np\nfrom sklearn.neighbors import NearestNeighbors\n\n'''\ntexts=[\"dog cat fish\",\"dog cat cat\",\"fish bird\", 'bird']\n\n#TF\ncv = CountVectorizer()\n#cv_fit=cv.fit_transform(texts)\n#print(cv.get_feature_names())\n#print(cv_fit.toarray())\ncv.fit(texts)\na=cv.transform(texts).toarray()\n\n#tf-idf\ntfidf=TfidfVectorizer()\ntfidf.fit(texts)\nb=tfidf.transform(texts).toarray()\n\n\ntxt=pd.read_csv('./data/train.csv')\nnum=0\nnum1=0\na=np.array(txt[\"label\"])\nfor i in range(len(a)):\n if(a[i]==1):\n num+=1\n if(a[i]==-1):\n num1+=1\n'''\n#csr = sparse.coo_matrix([[1, 5, -3], [4, 0, 1], [1, 3, 0]])\n#csr=csr.tocsr()\n#csr[0,0]=5\n\n\ndef llq_smote(more_data,less_data, tag_index=None, max_amount=0, std_rate=5, kneighbor=5):\n\n #connect two sparse matrix\n data=np.vstack((more_data,less_data))\n \n case_state=pd.Series([more_data.shape[0],less_data.shape[0]])\n case_rate = max(case_state) / min(case_state)\n location = []\n if case_rate < 5:\n print('do not need smote')\n data=data.tocsr()\n #train_y\n train_y=data[0]\n #train_x\n data=data[:,1:]\n\n return data,train_y\n \n else:\n neighbors = NearestNeighbors(n_neighbors=kneighbor).fit(less_data)\n for i in range(less_data.shape[0]):\n location_set = neighbors.kneighbors([less_data.getrow(i).toarray()[0]], return_distance=False)[0]\n #store the 5 neighobors in each less data.\n location.append(location_set)\n print('it processes %s in %s less_data' % (i+1,less_data.shape[0]))\n \n if max_amount > 0:\n amount = max_amount\n else:\n amount = int(max(case_state) / std_rate)\n \n times=0\n update_case = []\n while times<amount:\n #shuffle:choose a neighbor data\n ran=np.random.randint(1,kneighbor)\n np.random.shuffle(location)\n less_data_index=location[0][ran]\n center_index=location[0][0]\n \n #create new data. And label set to 1.\n gap=np.random.random()\n dif=less_data.getrow(center_index)-less_data.getrow(less_data_index)\n new_case=less_data.getrow(center_index)+gap*abs(dif)\n \n #transform coo to csr matrix\n new_case=new_case.tocsr()\n #set label to 1\n new_case[0,0]=1\n if times==0:\n update_case=new_case\n elif times!=0:\n update_case=sparse.vstack((update_case,new_case))\n\n print('it cretes %s new data,completeing %.2f' % (times+1, times * 100 / amount))\n times = times + 1 \n \n #concate\n data=sparse.vstack((data.tocsr(),update_case))\n \n #train_y\n train_y=data[0]\n #train_x\n data=data[:,1:]\n\n return data,train_y\n \ndata,train_y=llq_smote(train_more_data,train_less_data,tag_index=0)\n\n\n" }, { "alpha_fraction": 0.5858567357063293, "alphanum_fraction": 0.6001280546188354, "avg_line_length": 38.46570587158203, "blob_id": "efddc9ffe6c1b5969f78500d8dc2ca88ed8ab5ec", "content_id": "956f6bb04a8480071570e12c16a39453d7a7636f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11575, "license_type": "no_license", "max_line_length": 162, "num_lines": 277, "path": "/smote", "repo_name": "llq20133100095/lightgbm_scipy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 14 10:55:14 2018\n\n@author: llq\n\"\"\"\n\n# smote unbalance dataset\nfrom __future__ import division\nimport pandas as pd\nimport numpy as np\nimport lightgbm as lgb\nfrom sklearn.neighbors import NearestNeighbors\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.preprocessing import OneHotEncoder,LabelEncoder\nfrom scipy import sparse\nimport os\nimport gc\nimport math\n\n\n#\"\"\"\n# Parameters\n# ----------\n# data : 原始数据\n# tag_index : 因变量所在的列数,以0开始\n# max_amount : 少类别类想要达到的数据量\n# std_rate : 多类:少类想要达到的比例\n# #如果max_amount和std_rate同时定义优先考虑max_amount的定义\n# kneighbor : 生成数据依赖kneighbor个附近的同类点,建议不超过5个\n# kdistinctvalue : 认为每列不同元素大于kdistinctvalue及为连续变量,否则为class变量\n# method : 生成方法\n#\"\"\"\n#\n## smote unbalance dataset\n#def smote(data, tag_index=None, max_amount=0, std_rate=5, kneighbor=5, kdistinctvalue=10, method='mean'):\n# try:\n# data = pd.DataFrame(data)\n# except:\n# raise ValueError\n# case_state = data.iloc[:, tag_index].groupby(data.iloc[:, tag_index]).count()\n# case_rate = max(case_state) / min(case_state)\n# location = []\n# if case_rate < 5:\n# print('不需要smote过程')\n# return data\n# else:\n# # 拆分不同大小的数据集合\n# less_data = np.array(\n# data[data.iloc[:, tag_index] == np.array(case_state[case_state == min(case_state)].index)[0]])\n# more_data = np.array(\n# data[data.iloc[:, tag_index] == np.array(case_state[case_state == max(case_state)].index)[0]])\n# # 找出每个少量数据中每条数据k个邻居\n# neighbors = NearestNeighbors(n_neighbors=kneighbor).fit(less_data)\n# for i in range(len(less_data)):\n# point = less_data[i, :]\n# location_set = neighbors.kneighbors([less_data[i]], return_distance=False)[0]\n# location.append(location_set)\n# # 确定需要将少量数据补充到上限额度\n# # 判断有没有设定生成数据个数,如果没有按照std_rate(预期正负样本比)比例生成\n# if max_amount > 0:\n# amount = max_amount\n# else:\n# amount = int(max(case_state) / std_rate)\n# # 初始化,判断连续还是分类变量采取不同的生成逻辑\n# times = 0\n# continue_index = [] # 连续变量\n# class_index = [] # 分类变量[离散变量]\n# for i in range(less_data.shape[1]):\n# if len(pd.DataFrame(less_data[:, i]).drop_duplicates()) > kdistinctvalue:\n# continue_index.append(i)\n# else:\n# class_index.append(i)\n# case_update = list()\n# location_transform = np.array(location)\n# while times < amount:\n# # 连续变量取附近k个点的重心,认为少数样本的附近也是少数样本\n# new_case = []\n# pool = np.random.permutation(len(location))[1]\n# neighbor_group = location_transform[pool]\n# if method == 'mean':\n# new_case1 = less_data[list(neighbor_group), :][:, continue_index].mean(axis=0)\n# # 连续样本的附近点向量上的点也是异常点\n# if method == 'random':\n# away_index = np.random.permutation(len(neighbor_group) - 1)[1]\n# neighbor_group_removeorigin = neighbor_group[1:][away_index]\n# new_case1 = less_data[pool][continue_index] + np.random.rand() * (\n# less_data[pool][continue_index] - less_data[neighbor_group_removeorigin][continue_index])\n# # 分类变量取mode(众数,就是频数最高的那个)\n# new_case2 = np.array(pd.DataFrame(less_data[neighbor_group, :][:, class_index]).mode().iloc[0, :])\n# new_case = list(new_case1) + list(new_case2)\n# if times == 0:\n# case_update = new_case\n# else:\n# case_update = np.c_[case_update, new_case]\n# print('已经生成了%s条新数据,完成百分之%.2f' % (times, times * 100 / amount))\n# times = times + 1\n# less_origin_data = np.hstack((less_data[:, continue_index], less_data[:, class_index]))\n# more_origin_data = np.hstack((more_data[:, continue_index], more_data[:, class_index]))\n# data_res = np.vstack((more_origin_data, less_origin_data, np.array(case_update.T)))\n# label_columns = [0] * more_origin_data.shape[0] + [1] * (\n# less_origin_data.shape[0] + np.array(case_update.T).shape[0])\n# data_res = pd.DataFrame(data_res)\n# return data_res\n\ndef llq_smote(more_data, less_data, tag_index=None, max_amount=0, std_rate=5, kneighbor=5):\n #connect two sparse matrix\n data=sparse.vstack((more_data,less_data))\n \n case_state=pd.Series([more_data.shape[0],less_data.shape[0]])\n case_rate = max(case_state) / min(case_state)\n location = []\n if case_rate < 5:\n print('do not need smote')\n data=data.tocsr()\n #train_y\n train_y=data[0]\n #train_x\n data=data[:,1:]\n\n return data,train_y\n \n else:\n #find k neighbors in less_data\n neighbors = NearestNeighbors(n_neighbors=kneighbor).fit(less_data)\n for i in range(less_data.shape[0]):\n location_set = neighbors.kneighbors([less_data.getrow(i).toarray()[0]], return_distance=False)[0]\n #store the 5 neighobors in each less data.\n location.append(location_set)\n print('it processes %s in %s less_data' % (i+1,less_data.shape[0]))\n \n # if don't have max_amount,it will decide in std_rate\n if max_amount > 0:\n amount = max_amount\n else:\n amount = int(max(case_state) / std_rate)\n \n times=0\n update_case = []\n while times<amount:\n #shuffle:choose a neighbor data\n ran=np.random.randint(1,kneighbor)\n np.random.shuffle(location)\n less_data_index=location[0][ran]\n center_index=location[0][0]\n \n #create new data. And label set to 1.\n gap=np.random.random()\n dif=less_data.getrow(center_index)-less_data.getrow(less_data_index)\n new_case=less_data.getrow(center_index)+gap*abs(dif)\n \n #transform coo to csr matrix\n new_case=new_case.tocsr()\n #set label to 1\n new_case[0,0]=1\n if times==0:\n update_case=new_case\n elif times!=0:\n update_case=sparse.vstack((update_case,new_case))\n\n print('it cretes %s new data,completeing %.2f' % (times+1, times * 100 / amount))\n times = times + 1 \n \n #concate\n data=sparse.vstack((data.tocsr(),update_case))\n \n #train_y\n train_y=data.getcol(0).toarray().reshape((-1,))\n #train_x\n data=data[:,1:]\n\n return data,train_y\n \ndef batch_predict(data,index):\n one_hot_feature=['LBS','age','carrier','consumptionAbility','education','gender','house','os','ct','marriageStatus','advertiserId','campaignId', 'creativeId',\n 'adCategoryId', 'productId', 'productType']\n vector_feature=['appIdAction','appIdInstall','interest1','interest2','interest3','interest4','interest5','kw1','kw2','kw3','topic1','topic2','topic3']\n\n for feature in one_hot_feature:\n try:\n #简单来说 LabelEncoder 是对不连续的数字或者文本进行编号\n data[feature] = LabelEncoder().fit_transform(data[feature].apply(int))\n except:\n data[feature] = LabelEncoder().fit_transform(data[feature])\n \n #get the data an label\n more_data=data[data.label==0]\n less_data=data[data.label==1]\n test=data[data.label==-1]\n res=test[['aid','uid']]\n test=test.drop('label',axis=1)\n enc = OneHotEncoder()\n train_more_data=more_data[['creativeSize']]\n train_less_data=less_data[['creativeSize']]\n test_x=test[['creativeSize']]\n \n train_more_y=sparse.coo_matrix(more_data[['label']])\n train_less_y=sparse.coo_matrix(less_data[['label']])\n train_more_data=sparse.hstack((train_more_y,train_more_data))\n train_less_data=sparse.hstack((train_less_y,train_less_data))\n\n #concate the one-hot encode\n for feature in one_hot_feature:\n enc.fit(data[feature].values.reshape(-1, 1))\n train_more_a=enc.transform(more_data[feature].values.reshape(-1, 1))\n train_less_a=enc.transform(less_data[feature].values.reshape(-1, 1))\n test_a = enc.transform(test[feature].values.reshape(-1, 1))\n train_more_data= sparse.hstack((train_more_data, train_more_a))\n train_less_data= sparse.hstack((train_less_data, train_less_a))\n test_x = sparse.hstack((test_x, test_a))\n print(feature+' finish')\n print('one-hot prepared !')\n \n #concate the cv\n cv=CountVectorizer()\n for feature in vector_feature:\n cv.fit(data[feature])\n train_more_a = cv.transform(more_data[feature])\n train_less_a = cv.transform(less_data[feature])\n test_a = cv.transform(test[feature])\n train_more_data = sparse.hstack((train_more_data, train_more_a))\n train_less_data = sparse.hstack((train_less_data, train_less_a))\n test_x = sparse.hstack((test_x, test_a))\n print(feature + ' finish')\n print('cv prepared !')\n \n \n #Smote\n train_data, train_y = llq_smote(train_more_data,train_less_data,tag_index=0,std_rate=10, kneighbor=10)\n# return train_data,train_y,test_x\n \n del data\n return LGB_predict(train_data, train_y, test_x, res, index)\n\ndef LGB_predict(train_x,train_y,test_x,res,index):\n print(\"LGB test\")\n clf = lgb.LGBMClassifier(\n boosting_type='gbdt', num_leaves=31, reg_alpha=0.0, reg_lambda=1,\n max_depth=-1, n_estimators=10000, objective='binary',\n subsample=0.7, colsample_bytree=0.7, subsample_freq=1,\n learning_rate=0.05, min_child_weight=50, random_state=2018, n_jobs=-1\n )\n clf.fit(train_x, train_y, eval_set=[(train_x, train_y)], eval_metric='auc',early_stopping_rounds=2000)\n res['score'+str(index)] = clf.predict_proba(test_x)[:,1]\n res['score'+str(index)] = res['score'+str(index)].apply(lambda x: float('%.6f' % x))\n print(str(index)+' predict finish!')\n gc.collect()\n res=res.reset_index(drop=True)\n return res['score'+str(index)]\n \ndata=pd.read_csv('./data/data.csv')\n\n#get the train data and test data\ntrain=data[data['label']!=-1]\ntest=data[data['label']==-1]\ndel data\npredict=pd.read_csv('./data/test1.csv')\ncnt=1\n#返回数字的上入整数\nsize = math.ceil(len(train) / cnt)\nresult=[]\nfor i in range(cnt):\n start = size * i\n end = (i + 1) * size if (i + 1) * size < len(train) else len(train)\n slice = train[int(start):int(end)]\n result.append(batch_predict(pd.concat([slice,test]),i))\n gc.collect()\n#train_data,train_y,test_x=batch_predict(data,0)\n \n \nresult=pd.concat(result,axis=1)\nresult['score']=np.mean(result,axis=1)\nresult=result.reset_index(drop=True)\nresult=pd.concat([predict[['aid','uid']].reset_index(drop=True),result['score']],axis=1)\nresult[['aid','uid','score']].to_csv('./data/submission.csv', index=False)\nos.system('zip ./data/baseline.zip ./data/submission.csv')" } ]
2
hobler/miniTopSim20
https://github.com/hobler/miniTopSim20
6daf8431c102119d9daa8194c7a58025cbb6e701
6ead4c5ed9cc1459f019af4bfa899c46c0d2fb22
76c67cac1068bb75412ccc412282e8e2accf77d7
refs/heads/master
2023-03-12T15:39:26.705819
2021-01-27T18:19:47
2021-01-27T18:19:47
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.737500011920929, "alphanum_fraction": 0.737500011920929, "avg_line_length": 16.77777862548828, "blob_id": "d91e119adcf3b7b1662a54eb621e29183ac44801", "content_id": "5c94f3381b9e08d3799d342927d60c0e63e15dd3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 160, "license_type": "permissive", "max_line_length": 50, "num_lines": 9, "path": "/work/Aufgabe10_moc/run.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "\"\"\"\nTemplate for calling miniTopSim.\n\nFeel free to copy, but do not modify the original!\n\"\"\"\n\nfrom mini_topsim.main import mini_topsim\n\nsuccess = mini_topsim()\n" }, { "alpha_fraction": 0.4945789575576782, "alphanum_fraction": 0.548247218132019, "avg_line_length": 30.44318199157715, "blob_id": "83a29927920e1a18834ef07a1e3366b342f1d4fe", "content_id": "af19b9e9deb5c2019a9921ae3cd8ed33650463b4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5534, "license_type": "permissive", "max_line_length": 79, "num_lines": 176, "path": "/work/Aufgabe5_delooping/Testingstuff.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom scipy import linalg\nfrom time import time as t\nimport TestingSurfaces\n\ndef intersection(solution, further_information):\n zeroes = np.zeros(solution.shape)\n ones = np.ones(solution.shape)\n first_row = zeroes < solution\n print(first_row)\n second_row = solution < ones\n print(second_row)\n intersection = first_row == second_row\n result = np.logical_and(intersection[:, 0], intersection[:, 1])\n print(result)\nclass Segment_a:\n def __init__(self, p11, p12, p21, p22):\n self.x11 = p11[0]\n self.y11 = p11[1]\n self.x12 = p12[0]\n self.y12 = p12[1]\n self.x21 = p21[0]\n self.y21 = p21[1]\n self.x22 = p22[0]\n self.y22 = p22[1]\n self.a = np.array([[self.x12 - self.x11,\n -self.x22 + self.x21],\n [self.y12 - self.y11,\n -self.y22 + self.y21]])\n\n def __call__(self):\n return self.a\n\n\nclass Segment_b:\n def __init__(self, p11, p21):\n self.x11 = p11[0]\n self.y11 = p11[1]\n self.x21 = p21[0]\n self.y21 = p21[1]\n self.b = np.array([[self.x21 - self.x11],\n [self.y21 - self.y11]])\n\n def __call__(self):\n return self.b\n\n\nStart_Time = t()\nx = np.array((0.0, 1.0, 2.0, 1.0, 2.3, 5.0, 6.0))\ny = np.array((5.0, 5.5, 5.3, 4.0, 6.5, 5.0, 6.0))\n\np = np.transpose(np.concatenate((x, y)).reshape((2, 7)))\nprint(p)\nprint(np.size(p))\nintervall = np.arange(2, 4)\nprint('Intervall = {}'.format(intervall))\nprint(np.delete(p, intervall, 0))\ni = 0\nprint(np.array((3, 4)))\ntest = np.array((3, 4))\ntest = np.reshape(test, (1, 2))\nprint(test.shape)\nwhile i < 10000:\n i += 1\n\nnewpoint = np.array([99, 99])\nprint(newpoint)\n\np = np.insert(p, 2, newpoint, axis=0)\nprint(p)\n\n# intervall = np.arange(3, 5)\n# for point in intervall:\n# print(point)\n# deloopedsurface = np.delete(p, point)\n# print(deloopedsurface)\n# print('XXXXXXXXXXXXXXXXXXXXXX')\nprint('Size of p = {}'.format(np.size(p) / 2))\n\ntestbool = True\nprint(testbool)\ntestbool = False\nprint(testbool)\n\nStop_Time = t()\nprint('++++++++++++++++')\nprint(Stop_Time - Start_Time)\nprint('//////////////////////')\nprint(x)\nx = np.delete(x, (1, 3, 5), axis=0)\nprint(x)\n\npoint1 = np.array([2, 3]).reshape((1, 2))\npoint2 = np.array([3, 4]).reshape((1, 2))\npoint3 = np.array([6, 3]).reshape((1, 2))\npoint4 = np.array([3, 5]).reshape((1, 2))\npoint5 = np.array([6, 7]).reshape((1, 2))\npoints = np.concatenate((point1, point2, point3, point4, point5), axis=0)\nrestult = np.concatenate((point2 - point1, -point4 + point3), axis=0)\n\nprint(restult)\n\na1 = np.array([[1.0, 2.0], [3.0, 4.0]])\na2 = np.array([[2, 3], [5, 7]])\na3 = np.array([[1, 2], [3, 4]])\na4 = np.array([[1, 2], [3, 4]])\nb1 = np.array([[1.0], [2.0]])\nb2 = np.array([[5], [8]])\nb3 = np.array([[5], [8]])\nb4 = np.array([[5], [8]])\n# a_versuch = np.array([a1, a2], [a3, a4])\n# solution = np.linalg.solve(a_versuch, [[b1, b2], [b3, b4]])\n# print('Solution:{}'.format(solution))\n# print('shape:{}'.format(a_versuch.shape))\na_test = np.zeros((int(points.size / 2) - 1, int(points.size / 2) - 1),\n Segment_a)\nb_test = np.zeros((int(points.size / 2) - 1, int(points.size / 2) - 1),\n Segment_b)\n\nfor i, pointi in enumerate(points):\n if i < int(points.size / 2) - 1:\n pointiplusone = points[i + 1, :]\n for j, pointj in enumerate(points):\n if i + 1 < j and j < int(points.size / 2) - 1:\n pointjplusone = points[j + 1, :]\n # element = (pointiplusone - pointi, -pointjplusone + pointj)\n print('shape/type = {}'.format(pointi.shape))\n element_a = Segment_a(pointi, pointiplusone, pointj,\n pointjplusone)\n print(element_a.a)\n if np.linalg.det(element_a()) != 0:\n a_test[i, j] = element_a\n print(\n 'b element:{}'.format((pointj - pointi).reshape(2, 1)))\n element_b = Segment_b(pointi, pointj)\n b_test[i, j] = element_b\n\nprint(a_test)\n#erg = np.linalg.solve(a_test, b_test)\nprint('TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT')\npoints1 = TestingSurfaces.p\nnumber_of_segments = (int(points1.size / 2) - 1)\nnumber_of_pairs = int(number_of_segments**2/2+number_of_segments/2)\nprint('number of points in the test = {}'.format(points1.shape))\na = np.zeros((number_of_pairs, 2, 2))\nb = np.zeros((number_of_pairs, 2, 1))\nfurther_information = np.zeros(((int(points1.size / 2) - 1) ** 2, 2))\nprint(a.shape)\nprint('datatype of a1 = {}'.format(a1.dtype))\nprint(b.shape)\n\nk = 0\nfor i, pointi in enumerate(points1):\n if i < int(points1.size / 2) - 1:\n pointiplusone = points1[i + 1, :]\n for j, pointj in enumerate(points1):\n if i + 1 < j and j < int(points1.size / 2) - 1:\n print('k = {}'.format(k))\n pointjplusone = points1[j + 1, :]\n element = (pointiplusone - pointi, -pointjplusone + pointj)\n if np.linalg.det(element) != 0:\n a[k, :, :] = element\n b[k, :, :] = (pointj - pointi).reshape(2, 1)\n further_information[k, :] = (i, j)\n k = k + 1\n\n# print('matrix a = {}'.format(a))\n# print(a.shape)\n\n# print('matrix b = {}'.format(b))\n# print(b)\nsolution = np.linalg.solve(a[:k], b[:k])\nprint('Solution 3d = {}'.format(solution))\nintersection(solution, further_information)\n# print(a1)\n# print(b1)\n" }, { "alpha_fraction": 0.5259953737258911, "alphanum_fraction": 0.5348120927810669, "avg_line_length": 38.04644775390625, "blob_id": "9ed1ee575deb7836a17641326e95a97ab139f93b", "content_id": "f85d02779a1d9183adb9e213440f8185be53c2f8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14293, "license_type": "permissive", "max_line_length": 80, "num_lines": 366, "path": "/mini_topsim/surface.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "\"\"\"\nDefines the class Surface\n\nincludes function \n\"normal_vector\" calculates the normal vectors in every point of the surface\n\"plot\" which plots the surface\n\"write\" which writes the surface points into a .srf file\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nimport time\nimport mini_topsim.init_surface as init\nfrom numpy import arccos, dot, pi, cross\nfrom numpy.linalg import norm\n\nimport mini_topsim.parameters as par\n\n\nclass Surface:\n\n def __init__(self):\n \"\"\"\n Initializes the x and y-Values with the init_surface module\n \"\"\"\n if par.INITIAL_SURFACE_TYPE == 'File':\n srf_file = par.INITIAL_SURFACE_FILE\n self.xvals, self.yvals = init.read_srf_file(srf_file,\n par.TOTAL_TIME)\n\n else:\n self.xvals = np.arange(par.XMIN, par.XMAX + 1, par.DELTA_X)\n self.yvals = init.init_surface(self.xvals)\n\n def normal_vector(self):\n \"\"\"\n calculates the normal vectors in every point of the surface\n\n calculates the vector between the nearest neighbours of the point\n and returns the normal vector of it\n\n :returns: x Values, y Values of the normal vectors\n \"\"\"\n dx = np.zeros_like(self.xvals)\n dy = np.zeros_like(self.yvals)\n\n # start and endpoint only have one neighbor\n dx[0] = self.xvals[1] - self.xvals[0]\n dy[0] = self.yvals[1] - self.yvals[0]\n dx[-1] = self.xvals[-1] - self.xvals[-2]\n dy[-1] = self.yvals[-1] - self.yvals[-2]\n\n # right neighbour - left neighbour\n dy[1:-1] = self.yvals[2:] - self.yvals[:-2]\n dx[1:-1] = self.xvals[2:] - self.xvals[:-2]\n\n magnitude = np.linalg.norm([dx, dy], axis=0)\n\n nx = dy / magnitude\n ny = -dx / magnitude\n return nx, ny\n\n def plot(self, time):\n \"\"\"\n plots the surface\n\n :param time: current simulation time\n \"\"\"\n plt.plot(self.xvals, self.yvals, \"x-\", label=f\"t = {time}\")\n plt.title('Surface')\n plt.xlabel('x[nm]')\n plt.ylabel('y[nm]')\n\n def write(self, time, filename):\n \"\"\"\n writes the surface values into an srf file\n\n format: surface: <time> <npoints> x-positions y-positions\n x[0] y[0]\n\n :param time: current simulation time\n :param filename: name of the file\n \"\"\"\n with open(filename, 'a') as f:\n f.write(\n f\"surface: {time} {len(self.xvals)} x-positions y-positions\\n\")\n for x, y in zip(self.xvals, self.yvals):\n f.write(f\"{x} {y}\\n\")\n\n def eliminate_overhangs(self):\n \"\"\"\n Eliminates overhanging structures iteratively\n \"\"\"\n # from left to right\n for index in range(0, len(self.xvals) - 1):\n if (self.xvals[index] > self.xvals[index + 1] and\n self.yvals[index] < self.yvals[index + 1]):\n self.xvals[index + 1] = self.xvals[index]\n\n # from right to left\n for index in range(len(self.xvals) - 1, 0, -1):\n if (self.xvals[index] < self.xvals[index - 1] and\n self.yvals[index - 1] > self.yvals[index]):\n self.xvals[index - 1] = self.xvals[index]\n\n def _update_points(self):\n \"\"\"updates the points of the Object for further calculations\"\"\"\n\n self.points = np.concatenate((self.xvals.reshape((self.xvals.size, 1)),\n self.yvals.reshape(\n (self.xvals.size, 1))),\n axis=1)\n\n def _intersections(self, _results):\n \"\"\"determines if an intersection has occured and returns a bool array\n\n :param _results: numpy array of all the results for the intersections\n :returns _result_bool: numpy array where TRUE indicates an intersection\n and FALSE indicates no intersection in the interested part\n \"\"\"\n zeroes = np.zeros(_results.shape)\n ones = np.ones(_results.shape)\n first_column = zeroes < _results\n # print(first_column)\n second_column = _results < ones\n # print(second_column)\n intersection = first_column == second_column\n # print(intersection)\n _result_bool = np.logical_and(intersection[:, 0], intersection[:, 1])\n return _result_bool\n\n def _calculate_new_points(self, _results, _result_bool):\n \"\"\"calculates the points of intersection\n\n :param _results: contains the results of all compared segments as numpy\n array\n :param _result_bool: contains the information if there was an\n intersection or not as bool value\n \"\"\"\n self._newpoints = np.zeros(self._further_information.shape)\n self._newpoints[:] = np.NaN\n for k, result in enumerate(_results):\n if _result_bool[k]:\n i = self._further_information[k, 0]\n # print('i= {}'.format(i))\n # print('point = {}'.format(self.points[i]))\n self._newpoints[k] = self.points[i] + (self.points[i + 1] -\n self.points[i]) * \\\n result[\n 0]\n # print('new points = {}'.format(self._newpoints))\n\n def _setvals(self):\n \"\"\"writes the x and y yalues back\"\"\"\n self.xvals = self.points[:, 0]\n self.yvals = self.points[:, 1]\n\n def _create_matrices(self):\n \"\"\"creates the two matrices a and b so that a*x=b can be solved\n\n For each Segment Pair that has to be compared there is an entry in a and\n b to solve the linear equation system a*x=b.\n \"\"\"\n number_of_segments = (int(self.points.size / 2) - 1)\n number_of_pairs = int(\n (number_of_segments ** 2) / 2 + number_of_segments / 2)\n self._a = np.zeros((number_of_pairs, 2, 2))\n self._b = np.zeros((number_of_pairs, 2, 1))\n self._further_information = np.zeros(\n ((int(self.points.size / 2) - 1) ** 2, 2), dtype=int)\n self._k = 0\n\n for i, pointi in enumerate(self.points):\n if i < number_of_segments:\n pointiplusone = self.points[i + 1]\n for j, pointj in enumerate(self.points):\n if i + 1 < j and j < number_of_segments:\n # print('k = {}'.format(self._k))\n pointjplusone = self.points[j + 1]\n element = np.transpose((\n pointiplusone - pointi, -pointjplusone + pointj))\n if np.linalg.det(element) != 0:\n self._a[self._k] = element\n self._b[self._k] = (pointj - pointi).reshape(2, 1)\n self._further_information[self._k] = (i, j)\n self._k = self._k + 1\n\n def _flaglooppoints(self, _result_bool):\n \"\"\"Flags entries in self.points with None if they should be removed\n\n If there is an intersection of two segments there is an interval of\n points witch should be removed. Flagging them makes it possible to\n enter the new points in the right position.\n\n :param _result_bool: contains the information if there was an\n intersection or not as bool value\n \"\"\"\n\n for k, intersection in enumerate(_result_bool):\n if intersection:\n i = self._further_information[k, 0]\n j = self._further_information[k, 1]\n interval = np.arange(i + 1, j + 1)\n for point_index in interval:\n self.points[point_index] = np.array((None, None))\n\n def _insertintersectionpoints(self):\n \"\"\"inserts the new points in the corresponding place\"\"\"\n\n for k, newpoint in enumerate(self._newpoints):\n if not np.isnan(newpoint[0]):\n i = self._further_information[k, 0]\n # print('k = {}'.format(k))\n # print('i= {}'.format(i))\n # print('newpoint = {}'.format(newpoint))\n self.points[i + 1] = newpoint\n\n def _removeflaged(self):\n \"\"\"removes the remaining Flaged points\"\"\"\n\n interval = np.zeros((1, 0), dtype=int)\n for i, point in enumerate(self.points):\n if np.isnan(point[0]):\n interval = np.append(interval, i)\n self.points = np.delete(self.points, interval, axis=0)\n\n def deloop(self):\n \"\"\"This method removes the loopes created by advancing the simulation.\n\n When the surface is changed there is a chance that loops are created.\n Those are detected and removed by calculating the intersection point\n and adding it and removing the loop points. So the total number of\n points can change.\n \"\"\"\n self._update_points()\n self._create_matrices()\n _results = np.linalg.solve(self._a[:self._k], self._b[:self._k])\n _result_bool = self._intersections(_results)\n self._calculate_new_points(_results, _result_bool)\n self._flaglooppoints(_result_bool)\n self._insertintersectionpoints()\n self._removeflaged()\n self._setvals()\n\n def distance(self, refsrf):\n \"\"\"\n calculates the distance to a reference surface \n \n :param refsrf: reference surface object\n \"\"\"\n distances12 = np.zeros_like(self.xvals)\n distances21 = np.zeros_like(refsrf.xvals)\n\n tmp = np.zeros(len(refsrf.xvals) - 1)\n for i in range(len(self.xvals)):\n p = [self.xvals[i], self.yvals[i]]\n for j in range(len(refsrf.xvals) - 1):\n seg = np.asarray([[refsrf.xvals[j], refsrf.yvals[j]],\n [refsrf.xvals[j + 1], refsrf.yvals[j + 1]]])\n tmp[j] = point2segment_dist(p, seg)\n distances12[i] = min((np.abs(tmp)))\n\n del tmp\n tmp = np.zeros(len(self.xvals) - 1)\n for i in range(len(refsrf.xvals)):\n p = [refsrf.xvals[i], refsrf.yvals[i]]\n for j in range(len(self.xvals) - 1):\n seg = np.asarray([[self.xvals[j], self.yvals[j]],\n [self.xvals[j + 1], self.yvals[j + 1]]])\n tmp[j] = point2segment_dist(p, seg)\n distances21[i] = min((np.abs(tmp)))\n\n return (np.mean(distances12) + np.mean(distances21)) / 2\n\n def view_factor(self):\n \"\"\"\n calculates the view factor of a surface.\n\n point-to-point visibility considered according to assignment\n\n :returns: view factor and its derivative for each surface point\n in a tuple\n \"\"\"\n # meshgrid anschauen\n x_strech = np.broadcast_to(self.xvals,\n shape=(self.xvals.size, self.xvals.size))\n x_strech_transpose = x_strech.T\n x_distances = x_strech_transpose - x_strech\n\n y_strech = np.broadcast_to(self.yvals,\n shape=(self.yvals.size, self.yvals.size))\n y_strech_transpose = y_strech.T\n y_distances = y_strech_transpose - y_strech\n\n distance = np.sqrt(x_distances*x_distances+y_distances*y_distances)\n nx, ny = self.normal_vector()\n\n cosines = -np.divide(nx * x_distances + ny * y_distances, distance,\n out=np.zeros_like(x_distances),\n where=distance != 0).T\n\n # roll -> shift des Arrays \"nach rechts/links\" (C like gespeichert),\n # siehe Doc\n # delta_l -> Mittelwert der Abstände zu den Nachbarknoten\n # Frage, geht das schneller?\n delta_l = np.diag(np.roll(distance, 1) + np.roll(distance, -1)) / 2\n\n # cos_beta_ij == cosines, cos_alpha_ij == cosines.T (== cos_beta_ji)\n cos_b = cosines\n cos_a = cosines.T\n\n # Mit Maske möglich\n v_factor = np.divide(\n np.multiply(cos_a, cos_b,\n out=np.zeros_like(cosines),\n where=np.logical_and(cos_b > 0,\n cos_a > 0)),\n 2 * distance,\n out=np.zeros_like(cos_a * cos_b),\n where=distance != 0) * delta_l\n\n # cross product (nx, ny) x (x, y)\n sines = -np.divide(nx * y_distances - ny * x_distances, distance,\n out=np.zeros_like(x_distances),\n where=distance != 0).T\n\n sin_b = sines\n\n # calculate as cos_alpha * sin_beta * delta_l / (2*distance)\n v_factor_deriv = np.divide(\n np.multiply(cos_a, sin_b,\n out=np.zeros_like(cosines),\n where=np.logical_and(cos_b > 0,\n cos_a > 0)),\n 2 * distance,\n out=np.zeros_like(cos_a * sin_b),\n where=distance != 0) * delta_l\n\n return v_factor, v_factor_deriv\n\n\ndef point2segment_dist(p, seg):\n \"\"\"\n calculates the distance between a point and a surface segment.\n\n If point projects onto the line segment, the orthogonal distance\n from the point to the line is returned.\n If the point does not project to the line segment, the distances\n to both segment endpoints is calculated and take the shortest\n distance is returned.\n\n :param p: Numpy array p=[x,y]\n :param seg: list of segment endpoints [pstart, pend]=[[x1,y1],[x2,y2]]\n :return: The minimum distance between point and surface segment.\n \"\"\"\n start = seg[0]\n end = seg[1]\n if all(start == p) or all(end == p):\n return 0\n if arccos(round(dot((p - start) / norm(p - start),\n (end - start) / norm(end - start)), 8)) > pi / 2:\n return norm(p - start)\n if arccos(round(dot((p - end) / norm(p - end),\n (start - end) / norm(start - end)), 8)) > pi / 2:\n return norm(p - end)\n return norm(cross(start - end, start - p)) / norm(end - start)\n" }, { "alpha_fraction": 0.672535240650177, "alphanum_fraction": 0.6760563254356384, "avg_line_length": 22.66666603088379, "blob_id": "09d52665e1843d136ace7a92f575267dc6263ff0", "content_id": "e4e7f2a664c9851ce5b437af170643286fba4070", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 284, "license_type": "permissive", "max_line_length": 62, "num_lines": 12, "path": "/work/Aufgabe13_gui/run.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "import os, sys\n\ncurrent_dir = os.path.dirname(__file__)\ncodedir = os.path.join(current_dir, '..', '..', 'mini_topsim')\nsys.path.insert(0, codedir)\n\nfrom gui import main\n\ncommand_line = [codedir, 'Initial', 'Conditions']\n#command_line = [codedir, 'Setup']\n\nwindow = main(command_line)\n" }, { "alpha_fraction": 0.6369668245315552, "alphanum_fraction": 0.686255931854248, "avg_line_length": 24.731706619262695, "blob_id": "ec86ba4eeb0b1e7883f153a3884cc4786b70a2e3", "content_id": "e73d2a7e4154c5b81b92f71e1571222c143fae9d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1055, "license_type": "permissive", "max_line_length": 80, "num_lines": 41, "path": "/work/Aufgabe4_sputter/test_overhangs.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "import os, sys\nfiledir = os.path.dirname(__file__)\ncodedir = os.path.join(filedir, '..', '..', 'mini_topsim')\nsys.path.insert(0, codedir)\n\n\nfrom surface import Surface\nimport parameters as par\n\nimport matplotlib.pyplot as plt\n\n\nconfig_filename=\"test_overhangs.cfg\"\nconfig_file = os.path.join(os.path.dirname(__file__), config_filename)\n\nif not config_file.endswith('.cfg'):\n print('Error: Incorrect config.')\n sys.exit()\n\nfilename = os.path.splitext(config_file)[0] + '.srf'\n\nif os.path.exists(filename):\n os.remove(filename)\n\npar.load_parameters(config_file)\n\n#Example Surface\nsurface = Surface()\nsurface.xvals=[0.,1.,2.,1.,1.5,3.,4.,5.,4.,5.,6.,7.,8.,7.,7.5,8.,9.]\nsurface.yvals=[10.,10.,10.,15.,17.,18.,18.,18.,12.,13.,13.,12.,11.,10.,9.,8.,8.]\n\nplt.title('Eliminate Overhangs Test')\nplt.ylabel('Surface Y values')\nplt.xlabel('Surface X values')\nplt.plot(surface.xvals, surface.yvals, 'b-', label='With Overhangs')\n\nsurface.eliminate_overhangs()\n\nplt.plot(surface.xvals, surface.yvals, 'r-', label='Without Overhangs')\nplt.legend()\nplt.show()\n" }, { "alpha_fraction": 0.5215471982955933, "alphanum_fraction": 0.5389951467514038, "avg_line_length": 36.01556396484375, "blob_id": "a82e8f832e3a8f6cc274346b31a21fc0d6372566", "content_id": "3b5d9e36a6fc3cff94b2d038a2308256a0695613", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9514, "license_type": "permissive", "max_line_length": 89, "num_lines": 257, "path": "/work/Aufgabe5_delooping/Testingcoreconcept.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "\"\"\"\nDefines the class Surface\n\nincludes function\n\"normal_vector\" calculates the normal vectors in every point of the surface\n\"plot\" which plots the surface\n\"write\" which writes the surface points into a .srf file\n\"\"\"\nimport numpy as np\n#import init_surface as init\nimport matplotlib.pyplot as plt\nimport TestingSurfaces\n\n#import parameters as par\n\n\nclass Segment_pair:\n def __init__(self, p11, p12, p21, p22):\n self.x11 = p11[0]\n self.y11 = p11[1]\n self.x12 = p12[0]\n self.y12 = p12[1]\n self.x21 = p21[0]\n self.y21 = p21[1]\n self.x22 = p22[0]\n self.y22 = p22[1]\n\n\nclass Surface:\n\n def __init__(self, x, y):\n \"\"\"\n Initializes the x and y-Values with the init_surface module\n \"\"\"\n self.xvals = x\n self.yvals = y\n\n def normal_vector(self):\n \"\"\"\n calculates the normal vectors in every point of the surface\n\n calculates the vector between the nearest neigbours of the point\n and returns the normal vector of it\n\n :returns: x Values, y Values of the normal vectors\n \"\"\"\n dx = np.zeros_like(self.xvals)\n dy = np.zeros_like(self.yvals)\n\n # start and endpoint only have one neighbor\n dx[0] = self.xvals[1] - self.xvals[0]\n dy[0] = self.yvals[1] - self.yvals[0]\n dx[-1] = self.xvals[-1] - self.xvals[-2]\n dy[-1] = self.yvals[-1] - self.yvals[-2]\n\n # right neigbour - left neigbour\n dy[1:-1] = self.yvals[2:] - self.yvals[:-2]\n dx[1:-1] = self.xvals[2:] - self.xvals[:-2]\n\n magnitude = np.linalg.norm([dx, dy], axis=0)\n\n nx = dy / magnitude\n ny = -dx / magnitude\n return nx, ny\n\n def plot(self, time):\n \"\"\"\n plots the surface\n\n :param time: current simulation time\n \"\"\"\n plt.plot(self.xvals, self.yvals, \"x-\", label=f\"t = {time}\")\n plt.title('Surface')\n plt.xlabel('x[nm]')\n plt.ylabel('y[nm]')\n plt.show()\n\n def write(self, time, filename):\n \"\"\"\n writes the surface values into an srf file\n\n format: surface: <time> <npoints> x-positions y-positions\n x[0] y[0]\n\n :param time: current simulation time\n :param filename: name of the file\n \"\"\"\n with open(filename, 'a') as f:\n f.write(\n f\"surface: {time} {len(self.xvals)} x-positions y-positions\\n\")\n for x, y in zip(self.xvals, self.yvals):\n f.write(f\"{x} {y}\\n\")\n\n def _update_points(self):\n self.points = np.concatenate((self.xvals.reshape((self.xvals.size, 1)),\n self.yvals.reshape((self.xvals.size, 1))),\n axis=1)\n\n def _intersections(self, result):\n\n zeroes = np.zeros(result.shape)\n ones = np.ones(result.shape)\n first_row = zeroes < result\n #print(first_row)\n second_row = result < ones\n #print(second_row)\n intersection = first_row == second_row\n result_bool = np.logical_and(intersection[:, 0], intersection[:, 1])\n return result_bool\n\n def _calculate_new_points(self, results, result_bool):\n self.newpoints = np.zeros((self.further_information.shape))\n self.newpoints[:] = np.NaN\n for k, result in enumerate(results):\n if result_bool[k]:\n i = int(self.further_information[k, 0])\n j = int(self.further_information[k, 1])\n #print('i= {}'.format(i))\n #print('j = {}'.format(j))\n #print('point = {}'.format(self.points[i]))\n self.newpoints[k] = self.points[i] + (self.points[i + 1] -\n self.points[i]) * result[0]\n #print('new points = {}'.format(self.newpoints))\n\n\n def _setvals(self):\n self.xvals = self.points[:, 0]\n self.yvals = self.points[:, 1]\n\n def _create_matrix(self):\n\n self.number_of_segments = (int(self.points.size / 2) - 1)\n self.number_of_pairs = int(\n self.number_of_segments ** 2 / 2 + self.number_of_segments / 2)\n self.a = np.zeros((self.number_of_pairs, 2, 2))\n self.b = np.zeros((self.number_of_pairs, 2, 1))\n self.further_information = np.zeros(\n ((int(self.points.size / 2) - 1) ** 2, 2))\n\n self.k = 0\n for i, pointi in enumerate(self.points):\n if i < int(self.points.size / 2) - 1:\n pointiplusone = self.points[i + 1, :]\n for j, pointj in enumerate(self.points):\n if i + 1 < j and j < int(self.points.size / 2) - 1:\n #print('k = {}'.format(self.k))\n pointjplusone = self.points[j + 1, :]\n element = (\n pointiplusone - pointi, -pointjplusone + pointj)\n if np.linalg.det(np.transpose(element)) != 0:\n self.a[self.k] = np.transpose(element)\n self.b[self.k] = (pointj - pointi).reshape(2, 1)\n self.further_information[self.k] = (i, j)\n self.k = self.k + 1\n\n def _compare_segments(self, segment_pair):\n a = [[segment_pair.x12 - segment_pair.x11,\n -segment_pair.x22 + segment_pair.x21],\n [segment_pair.y12 - segment_pair.y11,\n -segment_pair.y22 + segment_pair.y21]]\n\n b = [[segment_pair.x21 - segment_pair.x11],\n [segment_pair.y21 - segment_pair.y11]]\n # print('Checking for intersection!')\n # print('a is: {}'.format(a))\n # print('Determinat is: {}'.format(np.linalg.det(a)))\n if np.linalg.det(a) != 0:\n # print('Determinat is non Zero')\n erg = np.linalg.solve(a, b)\n if 0 < erg[0] < 1 and 0 < erg[1] < 1:\n # print('Intersection found!')\n return np.transpose(erg)\n\n def _intersectionpoint(self, result, i, j):\n newpoint = self.points[i, :] + (\n self.points[i + 1, :] - self.points[i, :]\n ) * result[0, 0]\n # print('new Point: {}'.format(newpoint))\n return np.reshape(newpoint, (1, 2))\n\n def _flaglooppoints(self, result_bool):\n\n for k, intersection in enumerate(result_bool):\n if intersection:\n i = int(self.further_information[k, 0])\n j = int(self.further_information[k, 1])\n intervall = np.arange(i+1, j+1)\n for element in intervall:\n self.points[element, :] = np.array((None, None))\n\n def _insertintersectionpoint(self, result_bool):\n for k, newpoint in enumerate(self.newpoints):\n if not np.isnan(newpoint[0]):\n i = int(self.further_information[k, 0])\n j = int(self.further_information[k, 1])\n #print('k = {}'.format(k))\n #print('i= {}'.format(i))\n #print('j = {}'.format(j))\n #print('newpoint = {}'.format(newpoint))\n self.points[i+1] = newpoint\n\n def _removeflaged(self):\n intervall = np.zeros((1, 0), dtype=int)\n for i, point in enumerate(self.points):\n if np.isnan(point[0]):\n intervall = np.append(intervall, i)\n self.points = np.delete(self.points, intervall, axis=0)\n\n def deloop(self):\n \"\"\"This method removes the loopes created by advancing the simulation\n\n format:\n\n :param <>:\n \"\"\"\n # print('Entering deloop!')\n # print('in deloop yvals : {}'.format(self.yvals))\n # print(self.xvals.reshape((self.xvals.size, 1)).shape)\n # (self.points)\n self._update_points()\n print('Before deloop = {}'.format(self.points))\n self._create_matrix()\n # print('Compare Matrix shape: {}'.format(compare_matrix.shape))\n # print(compare_matrix[0,0].x11)\n # print(compare_matrix[0, 0].y11)\n print('a = {}'.format(self.a[:self.k]))\n print('b = {}'.format(self.b[:self.k]))\n result = np.linalg.solve(self.a[:self.k], self.b[:self.k])\n print('result = {}'.format(result))\n print('further_information = {}'.format(self.further_information))\n print('result shape = {}'.format(result.shape))\n print('further_information shape = {}'.format(self.further_information.shape))\n print('k = {}'.format(self.k))\n result_bool = self._intersections(result)\n print('The result_bool is: {}'.format(result_bool))\n self._calculate_new_points(result, result_bool)\n print('new calculated points = {}'.format(self.newpoints))\n self._flaglooppoints(result_bool)\n print('show flaged points = {}'.format(self.points))\n\n # print('points after inserting none outside the method: {}'.format(self.points))\n self._insertintersectionpoint(result_bool)\n #print('number of points = {}'.format(self.points.shape))\n #print('number of xvals = {}'.format(self.xvals.shape))\n self._removeflaged()\n self._setvals()\n print('After deloop = {}'.format(self.points))\n\nsurface = Surface(TestingSurfaces.x, TestingSurfaces.y)\nplt.plot(surface.xvals, surface.yvals, \"x-\", label=f\"t = {1}\")\nplt.title('Surface')\nplt.xlabel('x[nm]')\nplt.ylabel('y[nm]')\n\nsurface.deloop()\nplt.plot(surface.xvals, surface.yvals, \"x-\", label=f\"t = {1}\")\nplt.show()\n\n" }, { "alpha_fraction": 0.5206159353256226, "alphanum_fraction": 0.5423771739006042, "avg_line_length": 35.719627380371094, "blob_id": "14bf670115ca5f7d2ddf50318ef7706dce80c79d", "content_id": "344e812c57a6048a0410d6b91b8174d1ad0e5720", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7859, "license_type": "permissive", "max_line_length": 191, "num_lines": 214, "path": "/work/Aufgabe5_delooping/delooping.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "\"\"\"\nScript to test basic delooping to be implemented in the project.\nThis should be a standalone file\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\nimport TestingSurfaces\n\n\nclass Segment_pair:\n def __init__(self, p11, p12, p21, p22):\n self.x11 = p11[0]\n self.y11 = p11[1]\n self.x12 = p12[0]\n self.y12 = p12[1]\n self.x21 = p21[0]\n self.y21 = p21[1]\n self.x22 = p22[0]\n self.y22 = p22[1]\n\n\ndef create_matrix(points):\n compare_matrix = np.zeros(\n (int((np.size(points) / 2) - 2), int((np.size(points) / 2) - 2)),\n Segment_pair)\n for i, pointi in enumerate(points):\n if i < int((np.size(points) / 2) - 1):\n pointiplusone = points[i + 1, :]\n for j, pointj in enumerate(points):\n if j > i and j < int((np.size(points) / 2) - 1):\n pointjplusone = points[j + 1, :]\n compare_matrix[i, j - 1] = Segment_pair(pointi,\n pointiplusone,\n pointj,\n pointjplusone)\n return compare_matrix\n\n\ndef intersectionPoint2(points, result, i, j):\n newpoint = points[i, :] + (points[i + 1, :] - points[i, :]) * result[0, 0]\n return np.reshape(newpoint, (1, 2))\n\n\ndef compare_segments(segment_pair):\n a = [[segment_pair.x12 - segment_pair.x11,\n -segment_pair.x22 + segment_pair.x21],\n [segment_pair.y12 - segment_pair.y11,\n -segment_pair.y22 + segment_pair.y21]]\n\n b = [[segment_pair.x21 - segment_pair.x11],\n [segment_pair.y21 - segment_pair.y11]]\n\n if np.linalg.det(a) != 0:\n erg = np.linalg.solve(a, b)\n if 0 < erg[0] < 1 and 0 < erg[1] < 1:\n return np.transpose(erg)\n\n\ndef removelooppoints2(restult_list, points):\n for intersection in restult_list:\n intervall = np.arange(int(intersection[2]), int(intersection[3]))\n for element in intervall:\n points[element, :] = np.array((None, None))\n return points\n\n\ndef insertintersectionpoint2(result_list, points_noloop):\n for intersection in result_list:\n points_noloop[int(intersection[2]), :] = intersection[:2]\n return points_noloop\n\n\ndef removeflaged(points):\n intervall = np.zeros((1, 0), dtype=int)\n for i, point in enumerate(points):\n if np.isnan(point[0]):\n intervall = np.append(intervall, i)\n points = np.delete(points, (intervall), axis=0)\n return points\n\n\ndef deloop2(points):\n \"\"\"Hier wird versucht das ganze als whole array operationen zu machen\"\"\"\n print('Strart deloop2')\n # Die Matrix der Vergleichspunkte füllen\n compare_matrix = create_matrix(points)\n result_list = np.zeros((0, 4), dtype=float)\n for i, j in np.ndindex(compare_matrix.shape):\n if compare_matrix[i, j] != 0:\n print(compare_matrix[i, j])\n result = compare_segments(compare_matrix[i, j])\n if result is not None:\n newpoint = intersectionPoint2(points, result, i, j)\n indexarray = np.array((i + 1, j + 2)).reshape((1, 2))\n resultij = np.concatenate((newpoint, indexarray), axis=1)\n result_list = np.concatenate((result_list, resultij))\n result_list = np.flip(result_list, axis=0)\n points_noloop = removelooppoints2(result_list, points)\n points = insertintersectionpoint2(result_list, points_noloop)\n points = removeflaged((points))\n return points\n\n\ndef intersectionPoint(workingpoint, workingpointplusone, erg):\n newpoint = workingpoint + (workingpointplusone - workingpoint) * erg[0]\n print('This is the new Point inserted: {}'.format(newpoint))\n return newpoint\n\n\ndef removelooppoints(p, start, end):\n print('i = {}, j = {}'.format(start, end))\n intervall = np.arange(start + 1, end + 1)\n p = np.delete(p, intervall, axis=0)\n return p\n\n\ndef insertIntersectionPoint(deloopedsurface, newpoint, place):\n print('This is the new delooped surface:')\n print(deloopedsurface)\n print(place)\n newsurface = np.insert(deloopedsurface, place, newpoint, axis=0)\n print(newsurface)\n return newsurface\n\n\ndef deloop(p):\n \"\"\"Nimm zuerst die ersten beiden Punkte und dieser Streckenabschnitt wird mit den anderen auf einen Schnittpunkt\n verglichen\"\"\"\n\n for i, workingpoint in enumerate(p):\n if i < np.size(p) / 2 - 1:\n workingpointplusone = p[i + 1, :]\n for j, movingpoint in enumerate(p):\n if i == j:\n continue\n if j < np.size(p) / 2 - 1:\n movingpointplusone = p[j + 1]\n a = np.transpose(np.array(\n [workingpointplusone - workingpoint,\n -movingpointplusone + movingpoint]))\n b = (np.array(movingpoint - workingpoint))\n # print('a = {}'.format(a))\n # print('b = {}'.format(b))\n erg = np.linalg.solve(a, np.transpose(b))\n if 0 < erg[0] < 1 and 0 < erg[1] < 1:\n \"\"\"Du hast eine Intersection gefunden! Entferne Sie doch bitte\"\"\"\n newpoint = intersectionPoint(workingpoint,\n workingpointplusone, erg)\n print('These are the 2 sections:')\n print(p[i, :])\n print(p[j, :])\n print('This is the old surface:')\n print(p)\n deloopedsurface = removelooppoints(p, i, j)\n\n p = insertIntersectionPoint(deloopedsurface, newpoint,\n i + 1)\n print('This is the new surface!!')\n print(p)\n print('Kreuzung')\n print('Ergebnis = {}'.format(erg))\n # plt.plot(p[:, 0], p[:, 1], 'b+-', label='Surfacepoints')\n # plt.show()\n print('This is before the continue:')\n print(p)\n print('i = {}'.format(i))\n print('j = {}'.format(j))\n\n return p\n # removeIntersection(workingpoint, workingpointplusone, movingpoint, movingpointplusone, erg)\n\n # print(erg[0])\n # print(erg[1])\n # print('Ergebnis = {}'.format(erg))\n # ergebnis = np.linalg.solve(np.transpose(np.array(workingpointplusone - workingpoint), np.array(-movingpointplusone + movingpoint)), np.array(movingpoint - workingpoint))\n # print(ergebnis)\n # if ergebnis[0] <= 1:\n # print(ergebnis)\n\n # np.linalg.solve(np.transpose(np.array(workingpointplusone - workingpoint, - )))\n # np.linalg.solve(np.transpose(np.array([p[1, :] - p[0, :], -p[2, :] + p[1, :]])), (np.array(p[1, :] - p[0, :])))\n\n print('xxxxxxxxxxxxxx')\n global deloopagain\n deloopagain = False\n return p\n\n\n\"\"\" In zweidimensionalen Numpy Arrays werden die Punkte gespeichert\nx0 y0\nx1 y1\nx2 y2\nx3 y3\n\"\"\"\n\nsurface = TestingSurfaces.p3\nsurfaceold = np.copy(TestingSurfaces.p3)\n\nplt.plot(surface[:, 0], surface[:, 1], 'b+-', label='Surfacepoints')\nplt.show()\ndeloopagain = True\n\nstart_time = time.time()\ndeloopedsurface2 = deloop2(surface)\nstop_time = time.time()\nprint(float(stop_time - start_time))\n\nplt.plot(surfaceold[:, 0], surfaceold[:, 1], 'b+-', label='Surfacepoints')\nplt.plot(deloopedsurface2[:, 0], deloopedsurface2[:, 1], 'k*-',\n label='Delooped Surface')\nplt.grid()\nplt.show()\n" }, { "alpha_fraction": 0.6491862535476685, "alphanum_fraction": 0.6576250791549683, "avg_line_length": 24.136363983154297, "blob_id": "e73dbac4be861e74290f3369cfc531914ba97e19", "content_id": "7f28989e92fa1978680419a34db2a4aecf9d0c3e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1659, "license_type": "permissive", "max_line_length": 87, "num_lines": 66, "path": "/work/Aufgabe1_basic/main.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "\"\"\"\nUsage: $ python3 main.py <simulation time> <timestep>\n\nincludes to functions:\n\"mini_topsim\": reads the Simulation parameters and starts the Simulation\n\"simulation\": simulates the surface movement with the given parameters \n\"\"\"\n\nimport sys\nimport matplotlib.pyplot as plt\n\nfrom surface import Surface\nfrom advance import advance\nfrom advance import timestep\n\n\ndef mini_topsim():\n \"\"\"\n Reads the Simulation parameter from the system arguments ands starts the simulation\n\n the first sys.argv[1] is the simulation time \n the second sys.argv[2] is the timestep\n if no sys arguments are passed the simulation starts with tend = 10 and dt = 1\n \"\"\"\n\n if len(sys.argv) > 1:\n tend = float(sys.argv[1])\n dt = float(sys.argv[2])\n else:\n tend = 10\n dt = 1\n simulation(tend, dt)\n\n\ndef simulation(tend, dt):\n \"\"\"\n starts the simulation, plots and writes the data\n\n creates a Surface Object and starts the simulation. \n the correct timestep is calculated with the timestep function \n from the advance module. \n Writes all calculated datapoints to a file with the \n filenname: basic_<tend>_<dt>.srf\n plots the simulation fpr t = 0 and t = tend\n\n :param tend: endtime of the simulation\n :param dt: timestep of the simulation\n \"\"\"\n s = Surface()\n time = 0\n filename = f\"basic_{tend}_{dt}.srf\"\n s.plot(time)\n\n while time < tend:\n s.write(time, filename)\n advance(s, timestep(dt, time, tend))\n time += timestep(dt, time, tend)\n\n s.write(time, filename)\n s.plot(time)\n plt.legend()\n plt.show()\n\n\nif __name__ == '__main__':\n mini_topsim()\n" }, { "alpha_fraction": 0.6748251914978027, "alphanum_fraction": 0.6940559148788452, "avg_line_length": 26.878047943115234, "blob_id": "d0186d750839d405dbfcaaa2ffd0dc379d6d77d1", "content_id": "0d8e8ab73d139c3ee3dee2ab9a3059ef5ceb13c9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1144, "license_type": "permissive", "max_line_length": 73, "num_lines": 41, "path": "/work/Aufgabe15_AB/test_cosine_2.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "#import pytest\nimport os, sys\nfiledir = os.path.dirname(__file__)\ncodedir = os.path.join(filedir, '..', '..', 'mini_topsim')\nsys.path.insert(0, codedir)\n\nimport mini_topsim.plot as srfplt\nfrom mini_topsim.surface import Surface\nfrom mini_topsim.main import mini_topsim\nimport mini_topsim.parameters as par\n\nconfig_file = os.path.join(filedir,'cosine_2.cfg')\nmini_topsim(config_file)\n\n\n\ndef test_calc_distance():\n \"\"\"q\n calculates distance between surfaces and tests it with treshold value\n \n calculates distance between cosine_2.srf andcosine.srf_save and\n tests it with treshold value calculated in calc_distance\n \n \"\"\"\n \n srf_filename1 = os.path.join(filedir,'cosine_2.srf')\n srf_filename2 = os.path.join(filedir,'cosine.srf_save')\n srfplotter = srfplt._SurfacePlotter(srf_filename1, srf_filename2)\n \n srf1 = Surface()\n srf1.xvals = srfplotter.xpoints_list[-1]\n srf1.yvals = srfplotter.ypoints_list[-1]\n \n srf2 = Surface()\n srf2.xvals = srfplotter.refsrf.xpoints_list[-1]\n srf2.yvals = srfplotter.refsrf.ypoints_list[-1]\n\n dist = srf1.distance(srf2)\n \n \n assert dist <= 1e-9\n\n" }, { "alpha_fraction": 0.6800989508628845, "alphanum_fraction": 0.6868151426315308, "avg_line_length": 27.867347717285156, "blob_id": "b8c0eb96c008064c918671bdb3954f2b6460de98", "content_id": "38c4229c514f8df7a2ef156432aefc40af3b79a0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2829, "license_type": "permissive", "max_line_length": 77, "num_lines": 98, "path": "/mini_topsim/parameters.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n#Georg Mikula\n#e11902119\n\nimport sys\nimport os\nimport configparser\n\n\ndef _parse_file(filename):\n\t\"\"\"This function opens a file with the given filename and creates a\n\tdictonary of all parameters in the file. \n\tThe keys of the dictionary are the parameter names. Sections are \n\tcompletely ignored and have no effect on the returned dict.\"\"\"\n\tif not os.path.isfile(filename):\n\t\traise FileNotFoundError(filename + ' not found.')\n\tcp = configparser.ConfigParser()\n\tcp.read(filename)\n\tconfig = {}\n\tfor section in cp.sections():\n\t\tfor option in cp[section]:\n\t\t\tconfig[option.upper()] = eval(cp[section][option])\n\treturn config\n\n\ndef _check_conditions(conditions_dict):\n\t\"\"\"Checks all parameter conditions. Raises a CondtionIncorrectException\n\tif at least one condition failed.\"\"\"\n\tincorrect_conditions = 0\n\tfor key, condition in conditions_dict.items():\n\t\tif(not eval(condition)):\n\t\t\tincorrect_conditions = incorrect_conditions + 1\n\t\t\tprint(\"Error: The condition \" + str(condition) + \" of parameter \"\n\t\t\t\t+ str(key) + \" is not true!\")\n\n\tif incorrect_conditions != 0:\n\t\tprint(str(incorrect_conditions) + \" conditions are false\")\n\t\tsys.exit()\n\n\ndef load_parameters(config_file_path, params_db_filename = 'parameters.db'):\n\t\"\"\"Loads all parameters from parameters.db (or argument 2) file.\n\tReads configuration for argument1 file and if the type of the config \n\tmatches with the parameter it's stored.\tAlso all Help Strings are stored \n\tin the module variable HELP_STRINGS and can be accessed with the parameter \n\tname as key.\"\"\"\n\n\tparams_db_path = os.path.join(os.path.dirname(__file__), params_db_filename)\n\tparams = _parse_file(params_db_path)\n\tconfig = _parse_file(config_file_path)\n\n\tparam_dict = {}\n\tconditions_dict = {}\n\tincorrect_params = 0\n\n\tfor key, (default, condition, description) in params.items():\n\t\tglobals()[key] = default\n\t\tif key in config:\n\n\t\t\tfloat_as_int = False\n\t\t\tc = config[key]\n\t\t\ttype_c = type(c)\n\t\t\tif((type(default) == float) and (type_c == int)) or \\\n\t\t\t\t((type(default) == type) and (default == float)):\n\n\t\t\t\ttype_c = float\n\t\t\t\tfloat_as_int = True\n\n\t\t\tif(type_c == type(default)) or \\\n\t\t\t\t((type(default) is type) and (type_c == default)):\n\t\t\t\tif float_as_int:\n\t\t\t\t\tglobals()[key] = float(config[key])\n\t\t\t\telse:\n\t\t\t\t\tglobals()[key] = config[key]\n\t\t\telse:\n\t\t\t\tprint(\"Error: Wrong type of \" + str(key) + \"!\")\n\t\t\t\tincorrect_params = incorrect_params + 1\n\t\t\t\tbreak\n\n\t\telif type(default) is type:\n\t\t\tprint(\"Error: Mandatory parameter \" + str(key) + \" missing!\")\n\t\t\tincorrect_params = incorrect_params + 1\n\t\t\tbreak\n\n\t\tparam_dict[key] = globals()[key]\n\n\t\tif condition is not None:\n\t\t\tconditions_dict[key] = condition\n\n\tif incorrect_params != 0:\n\t\tprint(str(incorrect_params) + \" Errors were detected.\")\n\t\tsys.exit()\n\n\t_check_conditions(conditions_dict)\n\n\treturn param_dict\n" }, { "alpha_fraction": 0.6798287630081177, "alphanum_fraction": 0.6912464499473572, "avg_line_length": 28.605634689331055, "blob_id": "7405fd4f4c00c1d466a3824d422d68216d01d170", "content_id": "ab1af8738338de1759785365f9a685e28235c9e6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2102, "license_type": "permissive", "max_line_length": 80, "num_lines": 71, "path": "/work/Aufgabe8_beam/plot_beam.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "\"\"\"\nScript to compare the three beam flux densities graphically\n\nThe function plot_beam_comparison allows user to graphically compare the three\ndifferent beam flux densities from the associated beam classes BeamConstant with\na broad beam, BeamGaussian with a Gaussian beam and BeamError with an error\nfunction beam. Additionally, user can set the parameters J, I, fwhm, Wx, Wz and\nxc according to their needs.\nThe output is an image stored in the working directory.\n\nThis file contains the following functions:\n * plot_beam_comparison - calculates the three different beam flux densities\n\"\"\"\n\nimport os\nimport sys\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Adding the code directory to sys.path\nfiledir = os.path.dirname(__file__)\ncodedir = os.path.join(filedir, '..', '..', 'mini_topsim')\nsys.path.insert(0, codedir)\n\nimport mini_topsim.parameters as par\nfrom mini_topsim.beam import BeamConstant, BeamError, BeamGaussian\n\n\ndef plot_beam_comparison():\n \"\"\"\n Calculating and plotting the different beam flux densities\n\n :return:\n \"\"\"\n xmin = -1000\n xmax = 1000\n step = 1\n xvals = np.arange(xmin, xmax + 1, step)\n\n # Initialize parameters\n par.load_parameters('const.cfg')\n\n # Broad beam\n beam_profile = BeamConstant(J=0.001)\n fbeam_constant = beam_profile(xvals)\n\n # Gaussian beam\n beam_profile = BeamGaussian(I=0.92e-13)\n fbeam_Gaussian = beam_profile(xvals)\n\n # Error function beam\n beam_profile = BeamError(I=1e-11)\n fbeam_error = beam_profile(xvals)\n\n # Plotting the three different diagrams\n fig, ax = plt.subplots()\n ax.plot(xvals, fbeam_constant, 'b-', label=r'$Broad\\ beam$')\n ax.plot(xvals, fbeam_Gaussian, 'r--', label=r'$Gaussian\\ beam$')\n ax.plot(xvals, fbeam_error, 'g:', label=r'$Error\\ function\\ beam$')\n ax.set_title('Beam flux density')\n ax.set_xlabel(r'$x\\ in\\ nm$')\n ax.set_ylabel(r'$F_{beam}(x)\\ in\\ \\frac{atoms}{cm^2s}$')\n ax.legend(loc='lower right')\n ax.grid(which='both')\n\n plt.show()\n fig.savefig('plot_beam.png')\n\n\nif __name__ == '__main__':\n plot_beam_comparison()\n" }, { "alpha_fraction": 0.6768507361412048, "alphanum_fraction": 0.7003525495529175, "avg_line_length": 22.58333396911621, "blob_id": "0d718aa91f06aa14c2ea732a240d50d74c0408e3", "content_id": "b04d41aa71c9e615b1fd04fb7977eac7551ef89a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 851, "license_type": "permissive", "max_line_length": 70, "num_lines": 36, "path": "/work/Aufgabe9_redep/main.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "import os, sys\nfiledir = os.path.dirname(__file__)\ncodedir = os.path.join(filedir, '..', '..', 'mini_topsim')\nsys.path.insert(0, codedir)\n\nfrom surface import Surface\nimport parameters as par\nimport time\n\nimport matplotlib.pyplot as plt\n\nconfig_filename=\"yamamura.cfg\"\nconfig_file = os.path.join(os.path.dirname(__file__), config_filename)\n\nif not config_file.endswith('.cfg'):\n print('Error: Incorrect config.')\n sys.exit()\n\nfilename = os.path.splitext(config_file)[0] + '.srf'\n\nif os.path.exists(filename):\n os.remove(filename)\n\npar.load_parameters(config_file)\n\n# my stuff (Claus Spitzer 11816266)\n\nmy_surface = Surface()\n\nmy_surface.plot(10) # 10 ist nur ein Dummy\nmy_surface.write(10, filename)\nstart = time.time()\nmy_surface.view_factor()\nstop = time.time()\nprint('Computation time for view_factor: ', (stop-start)*1000, 'ms')\n# plt.show()\n\n\n" }, { "alpha_fraction": 0.7094972133636475, "alphanum_fraction": 0.7104282975196838, "avg_line_length": 25.19512176513672, "blob_id": "dc52a9ee0bf24541393b5a9e6019fad5608e3f6e", "content_id": "212b982db8c4a8a5486622c9783da7575215d79f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1074, "license_type": "permissive", "max_line_length": 75, "num_lines": 41, "path": "/work/Aufgabe1_basic/advance.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "\"\"\"\nImplements the functions to calculate the surface movement\n\nfunction advance: calculates the movement of the surface\nfunction timestep: calculates the timestep for a given time \n\n\"\"\"\n\n\nimport numpy as np\nfrom surface import Surface\n\n\ndef advance(surface: Surface, dtime):\n \"\"\"\n calculates the movement of the surface fpr a timestep dtime\n\n :param surface: surface that is being calculated\n :param dtime: timstep of the calculation\n \"\"\"\n v = 1.\n nX, nY = surface.normal_vector()\n\n surface.xVals += nX*dtime*v\n surface.yVals += nY*dtime*v\n\n\ndef timestep(dtime, time, end_time):\n \"\"\"\n calculates the timestep for a given time\n\n returns the timestep if the calculation isnt overstepping the endtime\n if it would overstep it returns the resttime to calculte to the endtime\n\n :param dtime: timestep\n :param time: current time in simulation\n :param end_time: endtime of the simulation\n\n :returns: correct timestep to reach the calculation endtime\n \"\"\"\n return dtime if (time + dtime) <= end_time else (end_time - time)\n" }, { "alpha_fraction": 0.7015306353569031, "alphanum_fraction": 0.7321428656578064, "avg_line_length": 31.75, "blob_id": "ac01922fdb3a9bc85a825f7c43dd33871f66b14f", "content_id": "65ad0b2948166bcb75afb6beaeea5665aa5cf206", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 392, "license_type": "permissive", "max_line_length": 65, "num_lines": 12, "path": "/work/Aufgabe6_testing/etch_diff_1_0_125.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "import os, sys\nfiledir = os.path.dirname(__file__)\ncodedir = os.path.join(filedir, '..', '..', 'mini_topsim')\nsys.path.insert(0, codedir)\n\nimport mini_topsim.plot as srfplt\n\nsrf_filename1 = os.path.join(filedir,'etch_dx0_125.srf')\nsrf_filename2 = os.path.join(filedir,'etch_dx1.srf')\n\nsrfplt.plot(srf_filename1, srf_filename2)\nsrfplotter = srfplt._SurfacePlotter(srf_filename1, srf_filename2)" }, { "alpha_fraction": 0.5275904536247253, "alphanum_fraction": 0.5328632593154907, "avg_line_length": 35.65168380737305, "blob_id": "3da3aae4eebba0c1f467175f0803c44362bd08e7", "content_id": "daddbb2f31a2ccf43672c4347bb5b6646188dab3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16310, "license_type": "permissive", "max_line_length": 91, "num_lines": 445, "path": "/mini_topsim/gui_13.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "import sys\nimport os\nimport configparser\nimport tkinter as tk\nimport tkinter.ttk as ttk\n\nfrom tkinter import messagebox\nfrom functools import partial\nfrom PIL import ImageTk, Image\nfrom tkinter import filedialog\n\nclass Gui:\n \"\"\"\n This class represents a GUI for reading, changing and writing purposes.\n \n The input is read from the parameters.db file.\n In the GUI the values can be edited and finally saved in beispiel.cfg\n The GUI is configured by a grid layout using themed widgets (tkinter.ttk).\n The section must be set as the parameter on the command line.\n command line: python3<path-to-mini_topsim>gui.py <section-name>\n At the beginning the default parameters of the section are shown.\n \n Use the OK-Button for saving the config and the Cancel-Button for closing\n the session.\n If you try to close the window, you will be asked how to close the session\n if you have still unsaved parameters in comparison to beispiel.cfg \n \"\"\"\n \n def __init__(self, section, parameter_file, button_file, cfg_file):\n \"\"\" \n This function sets all needed configurations of the Tkinter Window.\n At the beginning the GUI is set in the middle of the screen.\n \n Attributes\n ----------\n section : input from user in the command line\n parameter_file : path to the parameter file\n button_file : path to the button file\n cfg_file : path to the config file\n \"\"\"\n print(section)\n self.section = section\n self.parameter_file = parameter_file\n self.button_file = button_file\n self.cfg_file = cfg_file\n self.data = self.get_data()\n \n self.root = tk.Tk() \n screen_width = self.root.winfo_screenwidth()\n screen_height = self.root.winfo_screenheight()\n gui_width = 500\n gui_height = 100 + 30 * len(self.data)\n if gui_width > screen_width:\n gui_width = screen_width\n if gui_height > screen_height:\n gui_height = screen_height\n \n self.root.geometry('{}x{}'.format(gui_width, gui_height))\n x_position = int(screen_width/2 - gui_width/2)\n y_position = int(screen_height/2 - gui_height/2)\n self.root.geometry('+{}+{}'.format(x_position, y_position))\n\n self.root.columnconfigure(0, weight=0)\n self.root.columnconfigure(1, weight=1)\n self.root.columnconfigure(2, weight=0)\n \n self.display()\n\n def start(self):\n \"\"\"\n This function starts the GUI.\n \"\"\"\n \n self.root.title('MiniTopSim-Project')\n self.root.mainloop() \n\n def get_data(self):\n \"\"\"\n This function reads parameters.db and copies all data in a dictionary.\n \n Returns\n -------\n data_from_file : dict\n \"\"\"\n \n data_from_file = {}\n possible_sections = []\n\n cp = configparser.ConfigParser()\n cp.optionxform = str\n cp.read(self.parameter_file)\n\n ###################################################################################\n # Aufgabe 14 Bugfix\n if 'Beam' in cp:\n cp['Beam']['TOTAL_TIME'] = cp['Beam']['TOTAL_TIME'].replace(\"float\", \"0.0\")\n ###################################################################################\n for possible_section in cp.sections():\n possible_sections.append(possible_section)\n \n if self.section not in possible_sections:\n print('The given section \\\"{}\\\" is not available!'.format(\n self.section))\n print('Try to use one of these next time and type in without ' \n 'quotes:')\n print(possible_sections)\n sys.exit()\n \n for option in cp[self.section]:\n value = list(eval(cp[self.section][option]))\n data_from_file[option] = value\n globals()[option] = value[0]\n if len(data_from_file) == 0:\n print('The given section \\\"{}\\\" doesn\\'t contain any data!'.format(\n self.section))\n sys.exit()\n return data_from_file\n \n def display(self):\n \"\"\"\n This function sets the grid layout and the basic visualisation.\n \n If the value is type int or double -> spinbox\n Else if the value is type bool -> checkbutton\n else -> entry\n \n If the user hits a new content in the GUI, it will be automatically\n verified if the data is valid too.\n \n On the right handside every parameter has got a help button, if the\n user wants to get further information on the parameter and its \n condition.\n At the Bottom there are the two buttons called 'OK' and 'Cancel'\n situated.\n If you press 'OK' and the data isn't already set in beispiel.config\n a filedialog will appear to get the right directory.\n If you press 'Cancel' the GUI will just close.\n If you press the 'X' button on the right hand corner then it depends\n on the current state. If the current config is already saved in \n beispiel.cfg then it close like the 'Cancel' Button. But if there are\n unsaved parameters you will be asked if you want to save the current\n state or discard it.\n \"\"\"\n \n self.entries = {}\n self.root.protocol('WM_DELETE_WINDOW', self.exit_window)\n info_image = Image.open(self.button_file)\n self.button_image = ImageTk.PhotoImage(info_image)\n\n label = ttk.Label(self.root, relief='sunken', text='PARAMETER')\n label.grid(row=0, column=0, padx='5', pady='5', sticky='ew')\n label = ttk.Label(self.root, relief='sunken', text='VALUE')\n label.grid(row=0, column=1, padx='5', pady='5', sticky='ew')\n label = ttk.Label(self.root, relief='sunken', text='HELP')\n label.grid(row=0, column=2, padx='5', pady='5', sticky='ew')\n \n current_row = 0 \n for key, value in self.data.items():\n current_row = current_row + 1\n label = ttk.Label(self.root, text=key)\n label.grid(row=current_row, column=0, padx='5', sticky='ew')\n\n self.defaultvalue = value[0] \n defaulttype = type(self.defaultvalue)\n \n if defaulttype is int or defaulttype is float:\n content = tk.DoubleVar()\n entry = ttk.Spinbox(self.root, textvariable=content,\n validate='focusout', from_=-1000.0, to=1000.0,\n validatecommand=partial(self.change_update, key))\n \n elif defaulttype is bool:\n content = tk.BooleanVar()\n entry = ttk.Checkbutton(self.root, variable=content,\n command=partial(self.change_update, key))\n \n else:\n content = tk.StringVar()\n entry = ttk.Entry(self.root, textvariable=content, \n validate='focusout', validatecommand=partial(\n self.change_update, key))\n\n content.set(self.defaultvalue)\n entry.grid(row=current_row, column=1, padx='5', sticky='ew')\n \n help_button = ttk.Button(self.root, image=self.button_image, \n command=partial(self.info, key))\n help_button.grid(row=current_row, column=2, padx='5', sticky='ew')\n\n self.entries[key] = {'content': content, 'entry': entry, \n 'default': self.defaultvalue}\n \n save_button = ttk.Button(self.root, text='OK',\n command=self.save)\n save_button.grid(column=1, row=current_row+1, padx='5', pady='5',\n sticky='nsw')\n cancel_button = ttk.Button(self.root, text='Cancel',\n command=self.close)\n cancel_button.grid(column=1, row=current_row+1, padx='5', pady='5',\n sticky='nse') \n\n def info(self, key):\n \"\"\"\n This function shows the information on user defined parameter.\n \"\"\"\n \n help_text = str(self.data[key][2])\n if self.data[key][1] is None:\n value_text = 'None'\n else:\n value_text = str(self.data[key][1])\n info_text = 'Info:\\n' + help_text + '\\n' + 'Condition:\\n' + value_text\n messagebox.showinfo(key, info_text)\n\n def change_update(self, key):\n \"\"\"\n This function processes the user input of the GUI.\n \n If the new value doesn't match with the belonging condition, then the\n old one is set again and the user gets an error message.\n \n Returns\n -------\n Bool : error occured or not\n \"\"\"\n \n old_value = globals()[key]\n globals()[key] = self.entries[key]['content'].get()\n if self.data[key][1] is not None and not eval(self.data[key][1]):\n error = True\n else:\n error = False\n\n if error:\n self.entries[key]['content'].set(old_value)\n globals()[key] = old_value\n messagebox.showerror(key, 'The new value isn\\'t compatible with '\\\n 'the existing condition!')\n self.info(key)\n return False\n else:\n self.defaultvalue = self.data[key][0]\n self.data[key][0] = self.entries[key]['content'].get()\n return True\n \n def check_data(self):\n \"\"\"\n This function checks the data if all values correspond with their \n conditions.\n This function will be called before saving the data.\n \n Returns\n -------\n Bool : warnings occured or not\n \"\"\"\n \n warnings = 0\n \n for key, condition in self.data.items():\n if condition[1] is not None:\n if not eval(condition[1]):\n warnings = warnings + 1\n messagebox.showwarning(key, key + ' doesn\\'t '\\\n 'match the requirements!\\n\\n' + 'Value: ' + \n str(self.data[key][0]) + '\\nCondition: ' + \n str(self.data[key][1]))\n \n if warnings > 0:\n return False\n else:\n return True\n \n def save(self):\n \"\"\"\n This function will call CreateConfigFile class if everything is valid.\n \n This function will be called by pressing the 'OK' button or the 'X'.\n If the data exists already in beispiel.cfg then an information will be\n printed on the screen.\n \n Returns\n -------\n Bool : saving procedure successfully or not\n \"\"\"\n \n result = self.data_already_in_file()\n if result:\n messagebox.showinfo('Save', 'Data exists already in beispiel.cfg')\n else:\n valid_data = self.check_data()\n if valid_data:\n config = CreateConfigFile(self.data)\n success = config.save_file(self.section, self.cfg_file)\n if success:\n messagebox.showinfo('Save', 'Save of config successfully!')\n return True\n else:\n messagebox.showerror('Save', 'Please correct the error(s) as '\\\n 'displayed!')\n return False\n\n def exit_window(self):\n \"\"\"\n This function will be called when you try to leave the GUI by the 'X'.\n \n If there is no unsaved work, it just will close like the 'Cancel' \n button. If there is something new you will be asked for saving it.\n \"\"\"\n \n equal = self.data_already_in_file()\n answer = False \n success = True\n if not equal:\n messagebox.showwarning('Unsaved Data', 'The data isn\\'t equal to '\\\n 'the file beispiel.cfg')\n answer = messagebox.askyesno('Create Config file?', 'Do you want '\\\n 'to save the parameters?')\n \n if answer:\n success = self.save()\n if success:\n self.close()\n \n def data_already_in_file(self):\n \"\"\"\n This function evaluates if the data of current state already exists.\n\n Returns\n -------\n Bool : savind successfully or not\n \"\"\"\n \n path_to_file = os.path.join(self.cfg_file, 'beispiel.cfg')\n if os.path.exists(path_to_file):\n data_file = {}\n cp = configparser.ConfigParser()\n cp.optionxform = str\n cp.read(path_to_file)\n \n if self.section in cp.sections():\n for option in cp[self.section]:\n value = list(eval(cp[self.section][option]))\n data_file[option] = value\n \n if self.data == data_file:\n return True\n \n return False\n \n def close(self):\n \"\"\"\n This function closes the GUI.\n \"\"\"\n \n self.root.destroy() \n \nclass CreateConfigFile:\n \"\"\"\n This class represents the procedure of saving your config.\n \n The data is given to the class in the __init__ function, which will be \n used to create a config file.\n Default is beispiel.cfg in the directory .../work/Aufgabe13_gui/\n \"\"\"\n \n def __init__(self, data):\n \"\"\"\n This function enables the usage of the config data.\n \n Attributes\n ----------\n data : dict of the given section\n \"\"\"\n \n self.data = data\n\n def save_file(self, section, cfg_file):\n \"\"\"\n This function saves the data in a config file.\n \n Therefore a filedioalog is opened to help you to get the right \n directory. \n \n Attributes\n ----------\n section : input from user in the command line\n cfg_file : path to the config file\n \n Returns\n -------\n Bool : success in saving the data or not\n \"\"\"\n \n cp = configparser.ConfigParser()\n cp.optionxform = str\n file_name = filedialog.asksaveasfilename(initialdir=cfg_file,\n title='Save config', filetypes=(('cfg-files', '*.cfg'),\n ('all files', '*.*')), defaultextension='.cfg', \n initialfile='beispiel.cfg')\n\n if file_name:\n cp.add_section(section)\n for key, value in self.data.items():\n cp.set(section, key, str(tuple(value)))\n \n with open(file_name, 'w') as file:\n cp.write(file)\n return True\n \n return False\n\ndef main(command_line_input):\n \"\"\"\n This function calls and starts the GUI.\n\n The function proves the existence of parameters.db and if the command line\n is valid.\n If this is the case then the GUI is called.\n \"\"\"\n\n current_dir = os.path.dirname(os.path.abspath(__file__))\n path_to_parameter_file = os.path.join(current_dir, 'parameters.db')\n if not os.path.exists(path_to_parameter_file):\n print('File parameters.db cannot be found in directory {}'.format(\n path_to_parameter_file))\n sys.exit()\n\n parent_dir = os.path.dirname(current_dir)\n path_to_button_file = os.path.join(current_dir, 'info.png')\n path_to_cfg_file = os.path.join(parent_dir, 'work', 'Aufgabe13_gui')\n\n if len(command_line_input) == 2:\n section_name = command_line_input[1]\n elif len(command_line_input) > 2:\n section_name = ' '.join(command_line_input[1:])\n else:\n print('Syntax from command line is not valid!')\n sys.exit()\n\n gui = Gui(section_name, path_to_parameter_file, path_to_button_file,\n path_to_cfg_file)\n gui.start()\n\nif __name__ == \"__main__\":\n main(sys.argv)\n" }, { "alpha_fraction": 0.5943098068237305, "alphanum_fraction": 0.6364594101905823, "avg_line_length": 26.114286422729492, "blob_id": "4b789c445c0e10537cedb3d3c53e399fa3b01144", "content_id": "96257e6d994ed96ad22c5a0cd126f1cfca48733c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 949, "license_type": "permissive", "max_line_length": 69, "num_lines": 35, "path": "/work/Aufgabe5_delooping/Task5_test_run.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "\"\"\"\nTesting the functionality of the deloog method\n\"\"\"\nimport sys\nimport os\nimport pytest\nimport numpy as np\nfiledir = os.path.dirname(__file__)\ncodedir = os.path.join(filedir, '..', '..', 'mini_topsim')\nsys.path.insert(0, codedir)\nfrom mini_topsim.main import mini_topsim\nimport mini_topsim.surface as surface\nimport mini_topsim.parameters as par\n\n#def test_run():\n# \"\"\"Test running miniTopSim.\"\"\"\n# success = mini_topsim()\n# assert success, 'Error during executing miniTopSim.'\n\n#@pytest.fixture()\n#def set_param():\n# \"\"\"Set parameter value.\"\"\"\n# par.XMIN = -50.\n# par.XMAX = 50\n# par.DELTA_X = 1.\n# par.INITIAL_SURFACE_TYPE = 'Cosine'\n# par.FUN_XMIN = -25.\n# par.FUN_XMAX = 25.\n\n#def test_surface(set_param):\n#\n# assert par.XMIN == -50.\n# newsurface = surface.Surface()\n# newsurface.xvals = np.array((0.0, 1.0, 2.0, 1.0, 1.3, 2.0, 6.0))\n# newsurface.yvals = np.array((5.0, 5.5, 5.3, 4.0, 5.0, 5.5, 6.0))\n" }, { "alpha_fraction": 0.6545850038528442, "alphanum_fraction": 0.6563972234725952, "avg_line_length": 26.59000015258789, "blob_id": "b661b3665dfa29e369a314d2610f6e6465b44c1a", "content_id": "8a600c90101d96ba4b4d4fe1652466e3a582d110", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2759, "license_type": "permissive", "max_line_length": 79, "num_lines": 100, "path": "/mini_topsim/main.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "\"\"\"\nUsage: $ python3 main.py <simulation time> <timestep>\n\nincludes to functions:\n\"mini_topsim\": reads the Simulation parameters and starts the Simulation \n\"\"\"\n\nimport sys\nimport os\nfrom time import time as currenttime\n\nimport matplotlib.pyplot as plt\n\nfrom mini_topsim.surface import Surface\nfrom mini_topsim.advance import advance\nfrom mini_topsim.advance import timestep\nimport mini_topsim.sputtering as sputter\nimport mini_topsim.parameters as par\nfrom mini_topsim.beam import init_beam_profile\nimport mini_topsim.plot as plot\n\n\ndef mini_topsim(config_file=None):\n \"\"\"\n Loads parameters from config_file, starts the sim, plots and writes to file\n\n :param config_file: config_file with simulation parameters\n\n\n Loads parameters from config_file. \n If no config_file is passed passed, None is returned.\n Creates a Surface Object and starts the simulation. \n The correct timestep is calculated with the timestep function \n from the advance module. \n \n If a *.srf_save file with the same filename exists, the plot function with\n both surfaces is called.\n\n \"\"\"\n print('Running miniTopSim ...')\n\n if config_file is None:\n if len(sys.argv) > 1:\n config_filename = sys.argv[1]\n else:\n sys.exit('No Config file passed')\n # config_filename = 'cosine.cfg'\n\n config_file = config_filename\n\n if not config_file.endswith('.cfg'):\n print('Error: Incorrect config.')\n sys.exit()\n\n filename = os.path.splitext(config_file)[0] + '.srf'\n\n if os.path.exists(filename):\n os.remove(filename)\n\n par.load_parameters(config_file)\n dir_path = os.path.dirname(os.path.realpath(config_file))\n par.INITIAL_SURFACE_FILE = os.path.join(dir_path,\n par.INITIAL_SURFACE_FILE)\n\n tend = par.TOTAL_TIME\n dt = par.TIME_STEP\n\n surface = Surface()\n\n # Initialize beam profile\n init_beam_profile()\n\n sputter.init_sputtering()\n time = 0\n start_simulation_time = currenttime()\n\n while time < tend:\n surface.write(time, filename)\n dtime = timestep(dt, time, tend)\n advance(surface, dtime)\n surface.eliminate_overhangs()\n time += dtime\n\n stop_simulation_time = currenttime()\n simulation_time = stop_simulation_time - start_simulation_time\n print('The Simulation took: {}s'.format(float(simulation_time)))\n surface.write(time, filename)\n\n filename_save = filename + '_save'\n\n if par.PLOT_SURFACE:\n if os.path.exists(filename_save):\n print('*.srf_save file exists... plotting both!')\n plot.plot(filename, filename_save)\n else:\n plot.plot(filename)\n\n\nif __name__ == '__main__':\n mini_topsim()\n" }, { "alpha_fraction": 0.6656453609466553, "alphanum_fraction": 0.6759862303733826, "avg_line_length": 32.063289642333984, "blob_id": "2e3dd05819952068e1ba5f90d054d6aa51b6f46f", "content_id": "f09df75e44c935c45af48da48399c3b85227ad50", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2611, "license_type": "permissive", "max_line_length": 123, "num_lines": 79, "path": "/mini_topsim/implant.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "'''\nDescription: Initialization of the corresponding surface. There is defined a class Gauss, \nwhich provides a callable object for calculating the Gaussian function.\n\nClasses:\n\t\tGauss: provides a callable object for calculating the Gaussian function.\n\nFunctions:\n\t\t__call__(self): Calculates the Gaussian function.\n\nAdditionally this module can be used as a script:\n\tUSAGE: $ python3 implant.py [name of .cfg file]\n\twhere: .cfg file defines the implantation for the corresponding surface\n\nAuthor: Omerasevic Armin (01325962)\nPart of the miniTopSim Project: https://github.com/hobler/miniTopSim \n'''\nfrom init_surface import init_surface\nfrom bulk import Bulk\nfrom surface import Surface\n\nimport sys\nimport numpy as np\nimport mini_topsim.parameters as par\nfrom scipy.interpolate import interp1d\n\n\nclass Gauss:\n\t'''\n\tProvides a callable object for calculating the Gaussian function.\n\t'''\t\t\t\n\t\t\n\tdef __call__(self, bulk):\t\n\t\t'''\n\t\tCalculates the Gaussian function.\n\t\tWe use it since the probability distribution for the end point of the ion trajectories \n\t\tcan be approximately described by a Gaussian function.\t\t\t\n\t\t'''\n\t\tf_interp = interp1d(bulk.xvals, bulk.yvals, kind = 'cubic',bounds_error=False) \n\t\t\n\t\tprefactor = par.DOSE*(1e-14)/(2*np.pi*par.DRP*par.DRLAT)\n\t\tDelta_R_p_pow = 2*par.DRP**2\n\t\tDelta_R_lat_pow = 2*par.DRLAT**2\t\t\t\t\n\t\t\t\n\t\tconc = np.zeros(shape=(len(bulk.x_grid),len(bulk.y_grid)))\n\t\tfor i, x_koor in enumerate(bulk.x_grid): \n\t\t\tfor j, y_koor in enumerate(bulk.y_grid):\n\t\t\t\tconc[i][j]=0.0\t\t\t\n\t\t\t\tif y_koor <= f_interp(x_koor): #inside material\n\t\t\t\t\tfor psi_i in np.arange(x_koor - 3*par.DRLAT, x_koor + 3*par.DRLAT , par.BULK_DX): \n\t\t\t\t\t\tif psi_i >= par.XMIN and psi_i <= par.XMAX: \n\t\t\t\t\t\t\tconc[i][j]+=np.exp(-(((np.absolute(np.absolute(y_koor)-np.absolute(f_interp(psi_i))-par.RP)) ** 2)/Delta_R_p_pow)- \\\n\t\t\t\t\t\t\t((np.absolute(x_koor-psi_i) ** 2)/Delta_R_lat_pow))*par.BULK_DX\n\t\t\t\t\tconc[i][j]*=prefactor\n\t\t\t\t#print(x_koor , y_koor, conc[i][j])\t\n\t\tbulk.conc = conc\t\n\n\t\t\nif __name__ == '__main__':\n\t'''\n\tThis module can be used as a script to plot dopant concentration on the nodes of a regular lattice,\n\tto write the dopant distribution of the nodes to a file or to save the plot as .png file if needed.\n\n\tUSAGE: $ python implant.py [name of .cfg file]\n\t'''\n\tif(len(sys.argv) == 2):\n\t\tconfig_file = sys.argv[1]\n\t\tif config_file.endswith(\".cfg\"):\n\t\t\tpar.load_parameters(config_file)\n\t\t\ts = Surface()\n\t\t\tb = Bulk(s.xvals,s.yvals)\n\t\t\tg = Gauss()\n\t\t\tg(b)\n\t\t\tb.write_bulk()\n\t\t\tb.plot_bulk()\n\t\telse:\n\t\t\tsys.exit(\"Wrong config file format .cfg!\")\n\telse:\n\t\tsys.exit(\"No Config file passed!\")" }, { "alpha_fraction": 0.6716417670249939, "alphanum_fraction": 0.6809701323509216, "avg_line_length": 23.272727966308594, "blob_id": "91249ec9e479ce1b16129a6bcde07b495fa6e197", "content_id": "74e5ea4e3cef63bccf713e66f4c9b0bef3c4cbc3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 536, "license_type": "permissive", "max_line_length": 58, "num_lines": 22, "path": "/work/Aufgabe6_testing/run.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "import os, sys\nfiledir = os.path.dirname(__file__)\ncodedir = os.path.join(filedir, '..', '..', 'mini_topsim')\nsys.path.insert(0, codedir)\n\nfrom mini_topsim.main import mini_topsim\nimport mini_topsim.plot as srfplt\n\nconfig_filename = None\n\nif len(sys.argv) == 2:\n config_filename = sys.argv[1]\nelse:\n config_filename = 'config1.cfg'\n\nconfig_file = os.path.join(filedir, config_filename)\n\nif not config_file.endswith('.cfg'):\n print('Error: Config-file 1 does not end with .cfg')\n sys.exit() \n \nmini_topsim(config_file)\n\n\n" }, { "alpha_fraction": 0.692307710647583, "alphanum_fraction": 0.695652186870575, "avg_line_length": 21.923076629638672, "blob_id": "b5fbdede8af293b6d48083ba649952da64e9a2b6", "content_id": "db27ee998d3c8765dab213911f640af47399fa51", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 299, "license_type": "permissive", "max_line_length": 58, "num_lines": 13, "path": "/work/Aufgabe7_time_integration/run.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "\"\"\"\nTemplate for calling miniTopSim.\n\nFeel free to copy, but do not modify the original!\n\"\"\"\nimport os, sys\nfiledir = os.path.dirname(__file__)\ncodedir = os.path.join(filedir, '..', '..', 'mini_topsim')\nsys.path.insert(0, codedir)\n\nfrom mini_topsim.main import mini_topsim\n\nsuccess = mini_topsim()\n\n" }, { "alpha_fraction": 0.5333333611488342, "alphanum_fraction": 0.572549045085907, "avg_line_length": 22.18181800842285, "blob_id": "91ce82f0b5ed98a136b02ac152d1ca112a35cbf4", "content_id": "b2cb303c0c47e04532e6aea005a572414316ebd1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 510, "license_type": "permissive", "max_line_length": 68, "num_lines": 22, "path": "/work/Aufgabe1_basic/init_surface.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "\"\"\"\nImplements a function \"init_surface\" to initialize the Surface\n\"\"\"\n\nimport numpy as np\nimport math\n\n\ndef init_surface(xVals):\n \"\"\"\n initializes the starting values of the Surface \n\n funct ion: y = 0 if |x| < 25 else -50*(1+cos((2*Pi*x)/50))\n\n :param xVals: x-values of the surface\n\n :returns: y-Values of the initialized surface\n \"\"\"\n\n return np.array([0 if (x < -24 or x > 24)\n else ((-50) * (1 + math.cos((2*math.pi*x)/50)))\n for x in xVals])\n" }, { "alpha_fraction": 0.6609865427017212, "alphanum_fraction": 0.664872944355011, "avg_line_length": 29.409090042114258, "blob_id": "ec7cd6efe9180eeedd01e69a14b75a07e3972e84", "content_id": "fe4f07716746eb1576a9e418d7f3252bc86c750c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3345, "license_type": "permissive", "max_line_length": 77, "num_lines": 110, "path": "/mini_topsim/advance.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "\"\"\"\nImplements the functions to calculate the surface movement\n\nfunction advance: calculates the movement of the surface\nfunction timestep: calculates the timestep for a given time\nfunction get_velocities: calculates the the surface velocities\n\n\"\"\"\n\n\nimport numpy as np\nimport mini_topsim.sputtering as sputter\nimport mini_topsim.beam as beam\nimport scipy.constants as sciconst\nimport mini_topsim.parameters as par\n\n\ndef advance(surface, dtime):\n \"\"\"\n calculates the movement of the surface for a timestep dtime\n\n Depending on the selected type of time integration method, the surface\n points are calculated accordingly\n\n :param surface: surface that is being calculated\n :param dtime: timestep of the calculation\n \"\"\"\n\n nx, ny = surface.normal_vector()\n v, v_deriv = get_velocities(surface)\n\n if par.TIME_INTEGRATION == 'normal':\n surface.xvals += nx * v * dtime\n surface.yvals += ny * v * dtime\n elif par.TIME_INTEGRATION == 'vertical':\n surface.yvals += v / ny * dtime\n elif par.TIME_INTEGRATION == 'characteristics':\n costheta = -ny\n costheta = np.where(costheta < 0, 0, costheta) # eliminate overhangs\n sintheta = nx\n surface.xvals += (v * sintheta + v_deriv * costheta) * dtime\n surface.yvals += (-v * costheta + v_deriv * sintheta) * dtime\n\n surface.deloop()\n surface.eliminate_overhangs()\n\n\ndef timestep(dtime, time, end_time):\n \"\"\"\n calculates the timestep for a given time\n\n Returns the timestep if the calculation isnt overstepping the endtime\n if it would overstep it returns the resttime to calculte to the endtime.\n\n :param dtime: timestep\n :param time: current time in simulation\n :param end_time: endtime of the simulation\n\n :returns: correct timestep to reach the calculation endtime\n \"\"\"\n return dtime if (time + dtime) <= end_time else (end_time - time)\n\n\ndef get_velocities(surface):\n \"\"\"\n returns the surface velocities for each point\n\n Depending on the ETCHING parameter this function either returns the value\n of the ETCH_RATE parameter for etching, or calculates the surface\n velocity depending on the sputter flux density.\n REDEP allows: accounting for redeposition\n\n :param surface: surface object of class Surface\n\n :returns: surface velocity and its derivative for each surface point\n in a tuple\n \"\"\"\n\n nx, ny = surface.normal_vector()\n\n if par.ETCHING is True:\n v = np.full_like(ny, par.ETCH_RATE)\n v_deriv = np.zeros_like(v)\n return v, v_deriv\n\n costheta = -ny\n costheta = np.where(costheta < 0, 0, costheta)\n sintheta = nx\n\n y, y_deriv = sputter.get_sputter_yield(costheta, sintheta)\n\n n = par.DENSITY\n\n f_beam = beam.beam_profile(surface.xvals)\n f_sput = f_beam * costheta * y\n f_sput_deriv = f_beam * (-sintheta * y + costheta * y_deriv)\n\n if par.REDEP is True:\n v_factor, v_factor_deriv = surface.view_factor()\n f_redep = v_factor @ f_sput # matrix multiplication '@'\n # assert f_redep.ndim == 1\n f_redep_deriv = v_factor_deriv @ f_sput + v_factor @ f_sput_deriv\n v = 1e7 * (f_sput - f_redep) / n\n v_deriv = 1e7 * (f_sput_deriv - f_redep_deriv) / n\n\n else:\n v = 1e7 * f_sput / n\n v_deriv = 1e7 * f_sput_deriv / n\n\n return v, v_deriv\n" }, { "alpha_fraction": 0.678804874420166, "alphanum_fraction": 0.6965453028678894, "avg_line_length": 29.600000381469727, "blob_id": "fc7e4f14e56930f86e8581586e25dedca70d632c", "content_id": "fb39e154bf179be09664333f41cf4a7bc1fc20b3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1071, "license_type": "permissive", "max_line_length": 73, "num_lines": 35, "path": "/work/Aufgabe4_sputter/test_table.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "import pytest\nimport os, sys\nfiledir = os.path.dirname(__file__)\ncodedir = os.path.join(filedir, '..', '..', 'mini_topsim')\nsys.path.insert(0, codedir)\n\nimport mini_topsim.plot as srfplt\nfrom mini_topsim.surface import Surface\nfrom mini_topsim.main import mini_topsim\n\nconfig_file = os.path.join(filedir,'table.cfg')\nmini_topsim(config_file)\n\ndef test_calc_distance():\n \"\"\"\n calculates distance between surfaces and tests it with treshold value\n \n calculates distance between table.srf and table.srf_save and\n tests it with treshold value calculated in calc_distance\n \n \"\"\"\n \n srf_filename1 = os.path.join(filedir,'table.srf')\n srf_filename2 = os.path.join(filedir,'table.srf_save')\n srfplotter = srfplt._SurfacePlotter(srf_filename1, srf_filename2)\n \n srf1 = Surface()\n srf1.xvals = srfplotter.xpoints_list[-1]\n srf1.yvals = srfplotter.ypoints_list[-1]\n \n srf2 = Surface()\n srf2.xvals = srfplotter.refsrf.xpoints_list[-1]\n srf2.yvals = srfplotter.refsrf.ypoints_list[-1]\n \n assert srf1.distance(srf2) <= 1e-9\n" }, { "alpha_fraction": 0.6160230040550232, "alphanum_fraction": 0.6233642101287842, "avg_line_length": 32.68817138671875, "blob_id": "e828a0598100ae1b470aedd046942dd9112c1781", "content_id": "8a82d215769294dc3d18920972b1c88d3bdd44fc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3133, "license_type": "permissive", "max_line_length": 82, "num_lines": 93, "path": "/mini_topsim/sputtering.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "import os\n\nimport mini_topsim.parameters as par\n\nimport numpy as np\nfrom scipy.interpolate import interp1d\n\n\ndef init_sputtering():\n \"\"\"\n initializes the get_sputter_yield module variable\n\n Depending on the set parameters this function either attaches a callable\n object that implements the yamamura function to the get_sputter_yield\n variable, or one that reads the sputter yields from a given table.\n \"\"\"\n global get_sputter_yield\n if par.SPUTTER_YIELD_FILE == '':\n get_sputter_yield = Sputter_yield_Yamamura(par.SPUTTER_YIELD_0,\n par.SPUTTER_YIELD_F, par.SPUTTER_YIELD_B)\n else:\n get_sputter_yield = Sputter_yield_table(par.SPUTTER_YIELD_FILE)\n\n\nclass Sputter_yield_Yamamura():\n \"\"\"\n describes a callable object that implements the yamamura function\n \"\"\"\n def __init__(self, y0, f, b):\n self.y0 = y0\n self.f = f\n self.b = b\n \n def __call__(self, costheta, sintheta=None):\n \"\"\"\n calculates the sputter yield and its derivative\n\n Calculates the sputter yield according to the yamamura function\n and its derivative with respect to theta.\n\n :param costheta: the cosine of the angle between the surface normal \n and the sputter beam direction.\n :param sintheta: the sine of the angle between the surface normal\n and the sputter beam direction (default value None).\n \n :returns: Sputter yield Y and its derivative\n \"\"\"\n y = self.y0 * costheta**(-self.f) * np.exp(self.b * (1 - 1/costheta))\n\n if sintheta is None:\n theta = np.arccos(costheta)\n sintheta = np.sin(theta)\n\n y_deriv = self.y0 * sintheta * np.exp(self.b * (1 - 1/costheta)) * \\\n costheta**(-self.f - 2) * (self.f * costheta - self.b)\n\n # removes division by 0 errors. If costheta = 0 -> Y should be 0\n y[np.isnan(y)] = 0\n y_deriv[np.isnan(y_deriv)] = 0\n\n return y, y_deriv\n\n\nclass Sputter_yield_table():\n \"\"\"\n describes a callable object that interpolates sputter yields from a given file\n \"\"\"\n def __init__(self, filename):\n filepath = os.path.join(os.path.dirname(__file__), 'tables/', filename)\n print(filepath)\n data = np.genfromtxt(filepath, skip_header=1)\n tiltvals = data[:, 0]\n yieldvals = data[:, 1]\n self.yfunc = interp1d(tiltvals, yieldvals)\n\n def __call__(self, costheta, sintheta=None):\n \"\"\"\n interpolates sputter yields from given data in a file\n\n :param costheta: the cosine of the angle between the surface normal \n and the sputter beam direction\n :param sintheta: the sine of the angle between the surface normal\n and the sputter beam direction (default value None).\n\n :returns: Sputter yield Y\n \"\"\"\n if sintheta is not None:\n # if sintheta available, calculate with it because\n # sine is injective in the relevant interval [-pi/2,pi/2]\n theta = np.arcsin(sintheta)\n else:\n theta = np.arccos(costheta)\n return self.yfunc(theta)\n" }, { "alpha_fraction": 0.536370038986206, "alphanum_fraction": 0.5439618825912476, "avg_line_length": 21.383399963378906, "blob_id": "07069fb3c4e75ba40b76ac7f16070025ebc8111f", "content_id": "b87625c5a5a985c0ef406963d0ed913f9b6205c0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5664, "license_type": "permissive", "max_line_length": 95, "num_lines": 253, "path": "/mini_topsim/init_surface.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "\"\"\"\nImplements a function \"init_surface\" to initialize the Surface\n\"\"\"\n\nimport numpy as np\nimport mini_topsim.parameters as par\n\n\ndef init_surface(xvals):\n \"\"\"\n initializes the starting values of the Surface \n\n INITIAL_SURFACE_TYPE can be: \n \"Flat\",\"Cosine\",\"DoubleCosine\",\"Step\",\"V-Shape\",\"File\"\n \n In case of \"File\":\n A srf-File from INTITIAL_SURFACE_FILE will be read and used as input.\n \n Parameters\n ----------\n xvals : np.array\n x-values of the surface.\n\n Returns\n -------\n yvals : np.array\n y-Values of the initialized surface.\n \"\"\"\n \n if par.INITIAL_SURFACE_TYPE == 'Flat':\n yvals=_flat(xvals)\n \n elif par.INITIAL_SURFACE_TYPE == 'DoubleCosine':\n yvals=_double_cosine(xvals)\n \n elif par.INITIAL_SURFACE_TYPE == 'Step':\n yvals=_step(xvals)\n \n elif par.INITIAL_SURFACE_TYPE == 'V-Shape':\n yvals=_vshape(xvals)\n\n else:\n yvals=_cosine(xvals)\n \n \n return yvals\n\ndef _flat(xvals):\n \"\"\"\n Function for flat surface y=0, with boundary conditions\n\n Parameters\n ----------\n xvals : np.array\n x-values of the surface.\n\n Returns\n -------\n yvals : np.array\n y-Values of the initialized surface.\n\n \"\"\"\n yvals = np.zeros_like(xvals)\n return yvals\n\n\ndef _cosine(xvals):\n \"\"\"\n Function for cosine surface with boundary conditions\n\n Parameters\n ----------\n xvals : np.array\n x-values of the surface.\n\n Returns\n -------\n yvals : np.array\n y-Values of the initialized surface.\n\n \"\"\"\n mask = ((xvals >= par.FUN_XMIN) & (xvals <= par.FUN_XMAX))\n yvals = np.zeros_like(xvals)\n \n yvals[mask] = (-(par.FUN_PEAK_TO_PEAK / 2) * (1 +\n np.cos((2*np.pi*xvals[mask])/50))) \n \n return yvals\n\ndef _double_cosine(xvals):\n \"\"\"\n Function for double cosine surface with boundary conditions\n\n Parameters\n ----------\n xvals : np.array\n x-values of the surface.\n\n Returns\n -------\n yvals : np.array\n y-Values of the initialized surface.\n\n \"\"\"\n mask = ((xvals >= par.FUN_XMIN) & (xvals <= par.FUN_XMAX))\n yvals = np.zeros_like(xvals)\n \n yvals[mask] = (-(par.FUN_PEAK_TO_PEAK / 2) * (1 +\n np.cos(((4*np.pi*xvals[mask])+50*np.pi)/50))) \n \n return yvals\n\ndef _step(xvals):\n \"\"\"\n Function for step surface with boundary conditions\n \n Step function with or without angle of inclination (depending on:\n FUN_XMIN=FUN_XMAX or FUN_XMIN<FUN_XMAX). \n\n Parameters\n ----------\n xvals : np.array\n x-values of the surface.\n\n Returns\n -------\n yvals : np.array\n y-Values of the initialized surface.\n\n \"\"\"\n mask = ((xvals >= par.FUN_XMIN) & (xvals <= par.FUN_XMAX))\n mask_min = (xvals<par.FUN_XMIN)\n \n yvals = np.zeros_like(xvals)\n yvals[mask_min] = -par.FUN_PEAK_TO_PEAK\n \n\n k,d = _find_linar_poly(par.FUN_XMIN, -par.FUN_PEAK_TO_PEAK, par.FUN_XMAX, 0)\n\n\n yvals[mask] = k*xvals[mask] + d\n\n return yvals\n\ndef _vshape(xvals):\n '''\n Function for v-shape surface with boundary conditions\n\n Parameters\n ----------\n xvals : np.array\n x-values of the surface.\n\n Returns\n -------\n yvals : np.array\n y-Values of the initialized surface.\n\n '''\n\n center = par.FUN_XMIN + (par.FUN_XMAX-par.FUN_XMIN)/2\n\n mask_left = ((xvals >= par.FUN_XMIN) & (xvals <= center))\n mask_right = ((xvals >= center) & (xvals <= par.FUN_XMAX))\n\n yvals = np.zeros_like(xvals)\n \n\n k1,d1 = _find_linar_poly(par.FUN_XMIN, 0, center, -par.FUN_PEAK_TO_PEAK)\n k2,d2 = _find_linar_poly(center, -par.FUN_PEAK_TO_PEAK, par.FUN_XMAX, 0)\n\n\n yvals[mask_left] = k1*xvals[mask_left] + d1\n yvals[mask_right] = k2*xvals[mask_right] + d2\n \n return yvals\n\n\n\n#def _file()\n\ndef _find_linar_poly(p1_x, p1_y, p2_x, p2_y):\n \"\"\"\n Finding the linear polynomial y=kx+d from two points\n\n Parameters\n ----------\n p1_x : float\n X value of first point.\n p1_y : float\n Y value of first point.\n p2_x : float\n X value of second point.\n p2_y : float\n Y value of second point.\n\n Returns\n -------\n k : float\n Slope of the linear polynomial.\n d : float\n Intersection with y-axis.\n\n \"\"\"\n k = (p2_y-p1_y)/(p2_x - p1_x)\n d = p1_y - k * p1_x\n return k,d\n\ndef read_srf_file(filename,time):\n '''\n Reads x/y Values from srf-file at given time_stamp\n\n Parameters\n ----------\n filename : str\n Absolut path of given srf-file.\n time : float\n The time stamp where data will be taken.\n \n Returns\n -------\n xvalues : np.array\n x-Values of the initialized surface.\n yvalues : np.array\n y-Values of the initialized surface.\n\n '''\n xvalues_list = list()\n yvalues_list = list()\n\n n_values = 0\n\n print(filename)\n \n with open(filename) as file:\n\n for line_index, line in enumerate(file):\n if 'surface:' +' '+ str(time) in line:\n string_array = line.split(' ')\n\n n_values=(int(string_array[2]))\n \n for n, line in enumerate(file):\n if n<n_values:\n value_array = line.split(' ')\n xvalues_list.append(float(value_array[0]))\n yvalues_list.append(float(value_array[1]))\n \n xvalues = np.array(xvalues_list)\n yvalues = np.array(yvalues_list)\n \n \n return xvalues, yvalues\n\n" }, { "alpha_fraction": 0.6175869107246399, "alphanum_fraction": 0.6421267986297607, "avg_line_length": 22.14285659790039, "blob_id": "e27bda327375267586146fdf71d942b8ac09a17e", "content_id": "81b987c34b17d7c9ad3b6bc5d3eb324f43c39743", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 489, "license_type": "permissive", "max_line_length": 54, "num_lines": 21, "path": "/work/Aufgabe2_param/process_parameters.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "\n#Georg Mikula\n#e11902119\n\nimport mini_topsim.parameters as par\nimport sys\n\nparams = par.load_parameters(sys.argv[1]);\n\ncounter = 0\nfor item in dir(par):\n\tif item in params.keys():\n\t\tcounter = counter + 1\n\nif(len(params) != counter):\n\tprint(\"Error not all params are available\")\n\nwith open(sys.argv[1] + \".out\", \"w\") as out_file:\n\tout_file.write(\"[Parameters]\\n\")\n\tfor key, param in params.items():\n\t\tout_file.write(str(key) + \" = \" + str(param) + \"\\n\")\n\t\tprint(str(key) + \" = \" + str(param))\n\n\n" }, { "alpha_fraction": 0.6887173652648926, "alphanum_fraction": 0.6997427344322205, "avg_line_length": 36.21917724609375, "blob_id": "a9e1702649b55881e5e7a8b013bff52f36bb9a34", "content_id": "0e87071eb739c349d457294eb34c956a33b6129f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2721, "license_type": "permissive", "max_line_length": 108, "num_lines": 73, "path": "/mini_topsim/bulk.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "'''\nDescription: Implementation of the Bulk class with methods for writing and plotting the dopant distribution.\n\nClasses:\n\t\tBulk: provides plotting and writing functions for the object of this class\n\t\t\nFunctions:\n\twrite_bulk(): Writes the dopant distribution for the corresponding node coordinates to an .out file.\n\tplot_bulk(): Plots dopant concentration on the nodes of a regular lattice\n\nAuthor: Omerasevic Armin (01325962)\nPart of the miniTopSim Project: https://github.com/hobler/miniTopSim \n'''\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport mini_topsim.parameters as par\n\n\nfiledir = os.path.dirname(__file__)\ncodedir = os.path.join(filedir, '..', 'work', 'Aufgabe16_implant/')\n\n\nclass Bulk:\n\t'''\n\tProvides the functions for plotting a dopant distribution of a corresponding surface\n\tas well as saving a class Bulk data to an .out file.\n\t'''\n\tdef __init__(self, xvals, yvals, conc=False):\n\t\t'''\n\t\tInitializes all class parameters.\n\t\t'''\n\t\tself.xvals = xvals\n\t\tself.yvals = yvals\n\t\tself.x_grid = np.arange(par.XMIN, par.XMAX , par.BULK_DX)\n\t\tself.y_grid = np.arange(np.amin(self.yvals) - par.RP - 3*par.DRP, 0+5 , par.BULK_DY)\t\n\t\tself.conc = conc \n\t\tself.save_data_form = codedir + f\"{par.INITIAL_SURFACE_TYPE.lower()}\"\t\t\t\n\t\n\tdef write_bulk(self):\n\t\t'''\n\t\tWrites the dopant distribution for the corresponding node coordinates to an .out file.\n\t\t'''\n\t\twith open(codedir + f\"/Bulk_{par.INITIAL_SURFACE_TYPE}.out\", 'w') as bulk_out_file:\n\t\t\tbulk_out_file.write(\"Dopant distribution\\n\\tX\\t\\tY\\t\\tconc\\n\")\n\t\t\tfor i, x_koor in enumerate(self.x_grid): \n\t\t\t\tfor j, y_koor in enumerate(self.y_grid):\n\t\t\t\t\tbulk_out_file.write(f\"{x_koor:7.2f}\\t{y_koor:7.2f}\\t\\t{self.conc[i][j]:.3E}\\n\")\n\t\t\t\t\t\n\n\tdef plot_bulk(self, save_fig=False):\n\t\t'''\n\t\tPlots dopant concentration on the nodes of a regular lattice with contour lines at concentrations \n\t\t0.1, 0.2, ... 1.0 of the maximum occurring concentration.\n\t\n\t\tArg: \n\t\t\tsave_fig: Decides between plotting the concentration of the nodes and saving of the plot as .jpg image\n\t\t'''\t\n\t\tnorm_conc = np.transpose(self.conc)/np.amax(self.conc)\n\t\tprint(\"Max concentration: \" ,np.amax(self.conc)) \n\t\tdoping_conc = np.arange(0.1, 1.1, 0.1)\n\t\tplt.contourf(self.x_grid, self.y_grid, norm_conc, doping_conc, cmap='jet')\n\t\tplt.colorbar()\n\t\tplt.title('Dopant distribution for \"{}\" function'.format(par.INITIAL_SURFACE_TYPE))\n\t\tplt.xlabel(\"x coordinate of a lattice node\")\n\t\tplt.ylabel(\"y coordinate of a lattice node\")\n\t\tplt.plot(self.xvals, self.yvals, \"-r\") #Showing the surface itself\n\t\tplt.xlim([np.amin(self.x_grid),np.amax(self.x_grid)])\n\t\tplt.ylim([np.amin(self.y_grid),np.amax(self.y_grid)])\n\t\tif save_fig:\n\t\t\tplt.savefig(f\"{self.save_data_form}.png\")\n\t\telse:\n\t\t\tplt.show()\t\t\n\t\t" }, { "alpha_fraction": 0.6707616448402405, "alphanum_fraction": 0.6914004683494568, "avg_line_length": 30.796875, "blob_id": "ab0bc144b1b0550cde0088a9ae1863e53730bd77", "content_id": "593c18a93ac44744457e2bce1b6c7e0c28954ab1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2035, "license_type": "permissive", "max_line_length": 79, "num_lines": 64, "path": "/work/Aufgabe8_beam/test_gauss_1.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "\"\"\"\nTest to compare the gauss_1 simulation values to a saved gauss_1.srf_save file\n\nThis script allows user to compare the current simulation of the gauss_1.cfg\nwith saved values from gauss_1.srf_save and utilizes the Gaussian beam profile.\nIf the tests fail, an assert statement will be printed out.\n\nThis file contains the following functions:\n *test_run - test the execution of the miniTopSim simulation\n *test_gauss_1 - tests the values from gauss_1.cfg and gauss_1.srf_save\n\"\"\"\n\nimport pytest\nimport os\nimport sys\n\n# Adding the code directory to sys.path\nfiledir = os.path.dirname(__file__)\ncodedir = os.path.join(filedir, '..', '..', 'mini_topsim')\nsys.path.insert(0, codedir)\n\nimport mini_topsim.plot as srfplot\nfrom mini_topsim.surface import Surface\nfrom mini_topsim.main import mini_topsim\n\n\ndef test_run():\n \"\"\"\n Test running miniTopSim\n\n :return:\n \"\"\"\n config_file = os.path.join(filedir, 'gauss_1.cfg')\n success = mini_topsim(config_file)\n assert success is None, 'Error during executing miniTopSim'\n\n\ndef test_gauss_1():\n \"\"\"\n Compares the the values from erf_1.cfg and erf_1.srf_save through distance\n\n :return:\n \"\"\"\n srf_filename_1 = os.path.join(filedir, 'gauss_1.srf')\n srf_filename_2 = os.path.join(filedir, 'gauss_1.srf_save')\n srfplotter = srfplot._SurfacePlotter(srf_filename_1, srf_filename_2)\n\n srf1 = Surface()\n srf1.xvals = srfplotter.xpoints_list[-1]\n srf1.yvals = srfplotter.ypoints_list[-1]\n\n srf2 = Surface()\n srf2.xvals = srfplotter.refsrf.xpoints_list[-1]\n srf2.yvals = srfplotter.refsrf.ypoints_list[-1]\n\n dist = srf1.distance(srf2)\n\n assert len(srf1.xvals) == len(srf2.xvals), \\\n 'number of x-values from simulation and gauss_1.srf_save do not match'\n assert len(srf1.yvals) == len(srf2.yvals), \\\n 'number of y-values from simulation and gauss_1.srf_save do not match'\n assert dist <= 0.005, \\\n 'values from simulation and gauss_1.srf_save do not match'\\\n + ' distance %.3f is too great' % dist\n" }, { "alpha_fraction": 0.7236841917037964, "alphanum_fraction": 0.7317527532577515, "avg_line_length": 62.42519760131836, "blob_id": "897bbbbd4fb8c5645775f6ff3609b056d516ade7", "content_id": "2023fb61befd2e8fb39a4eecbd3f9e6d65b19a0a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 8144, "license_type": "permissive", "max_line_length": 721, "num_lines": 127, "path": "/README.md", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "# miniTopSim\nProject of the Seminar \"Scientific Programming in Python\" at TU Wien, WS 2020/21.\n\n--------------------\n1. Code-Organisation\n--------------------\n\nDie Verzeichnisstruktur des Projekts:\n\n```\nminiTopSim/\n mini_topsim/ # Das Code-Verzeichnis\n __init__.py # macht aus mini_topsim ein Package\n main.py # Main Script und Top-Level-Funktion\n parameters.py # Modul, das die Parameter als Attribute hat\n ... # weitere Module\n parameters.db # Parameterdatenbank\n tables/ # Verzeichnis für Tabellen\n ... # Tabellen\n work/ # Verzeichnis für Arbeitsverzeichnisse\n Aufgabe1_basic # Arbeitsverzeichnis für Aufgabe 1\n Aufgabe2_param # Arbeitsverzeichnis für Aufgabe 2\n ... # Arbeitsverzeichnisse für die weiteren Aufgaben\n templates/ # Verzeichnis für Templates (nicht ändern!)\n run.py # Skript zum Laufenlassen von miniTopSim\n test_run.py # Testmodul\n```\n\nDamit die Imports funktionieren, müssen Sie das Package lokal installieren. Wechseln Sie in das Überverzeichnis des Projektverzeichnisses (`miniTopSim`) und geben Sie ein:\n\n```bash\npip install -e ./miniTopSim/\n```\n\nEs kann auch sein, dass Sie `pip3` statt `pip` sagen müssen, oder dass Sie `pip` erst installieren müssen. Falls Sie mit `pip` nicht erfolgreich sind, ist ein Workaround, das Code-Verzeichnis in `sys.path` aufzunehmen:\n\n```\n import os, sys\n filedir = os.path.dirname(__file__)\n codedir = os.path.join(filedir, '..', ’..’, ’mini_topsim’)\n sys.path.insert(0, codedir)\n```\n\n------------------------\n2. Aufruf von miniTopSim\n------------------------\n\nRufen Sie miniTopSim immer aus \"Ihrem\" Arbeitsverzeichnis aus auf (`Aufgabe<nn>_<name>`). Ab der zweiten Stunde soll der Aufruf mit\n\n```bash\npython3 run.py beispiel.cfg\n```\n\nerfolgen. In `run.py` erfolgen die Imports nach dem Muster von `work/templates/run.py`. Da für alle Aufgaben ein `run.py`-File geschrieben werden muss, wird dieses in den einzelnen Aufgabestellungen nicht extra erwähnt. **Achten Sie darauf, dass keine Files vom Programm in das Code-Directory (`mini_topsim`) geschrieben werden.**\n\n`beispiel.cfg` (kann auch anders heißen, siehe Aufgabenstellung, jedenfalls aber mit Endung `.cfg`) ist das Konfigurationsfile (cfg-File), das wie folgt aussieht:\n\n```\n[SectionName1]\nParameterName1 = Wert1\nParameterName2 = Wert2\n...\n[SectionName2]\nParameterNameN+1 = WertN+1\nParameterNameN+2 = WertN+2\n...\n```\n\n`ParameterName*` sind durch die Namen der Parameter zu ersetzen, `Wert*` durch die Parameterwerte. Die Parameter sind in Gruppen („Sections”) eingeteilt. \n\nWelche Parameter in welchen Sections einzuführen sind, ist in den einzelnen Aufgaben angegeben. \"Einführen\" heißt für Sie, dass Sie einen Eintrag in der Parameter-Datenbank (`parameters.db` Datei im Code-Verzeichnis) vornehmen. Die Parameter-Datenbank ist ein Textfile in folgendem Format:\n\n```\n[SectionName1]\nParameterName1 = (DefaultWert1, 'Bedingung1', '''Erklärung1''')\nParameterName2 = (DefaultWert2, 'Bedingung2', '''Erklärung2''')\n...\n[SectionName2]\nParameterNameN+1 = (DefaultWertN+1, 'BedingungN+1', '''ErklärungN+1''')\nParameterNameN+2 = (DefaultWertN+2, 'BedingungN+2', '''ErklärungN+2''')\n...\n```\n\nFür jeden Parameter sind in einem Tupel der Defaultwert, eine Bedingung und eine Erklärung angegeben. Statt des Defaultwerts kann auch ein Datentyp angegeben sein, dann ist der Parameter obligatorisch mit diesem Datentyp im cfg-File anzugeben. Die Bedingung kann auch None sein, dann wird keine Bedingung überprüft. Ansonsten ist die Bedingung ein gültiger boolscher Python-Ausdruck, in einem String gespeichert. Er kann denselben oder andere Parameternamen (in Großbuchstaben) als Variablen enthalten. Die Erklärung ist ein String, der (bei Verwendung von Triple-Quotes) auch über mehrere Zeilen laufen kann. Wann immer ein neuer Parameter eingeführt wird, muss also auch ein Eintrag in der Parameter-Datenbank erfolgen.\n\nIm Programm werden die Parameter über das `parameters` Modul (Datei `parameters.py`) zur Verfügung gestellt. Dieses wird von den anderen `mini_topsim`-Modulen aus mit\n\n```\nfrom . import parameters as par\n```\n\nimportiert. Die Parameter stehen dann als Modulvariablen des `parameters` Moduls zur Verfügung, d.h. sie können unter den Namen `par.ParameterName*` (`ParameterName*` entsprechend dem Parameternamen ersetzen) referenziert werden. Von außerhalb des Code-Verzeichnisses, also insbesondere von Ihrem Arbeitsverzeichnis aus, lautet der Import\n\n```\nimport mini_topsim.parameters as par\n```\n\n---------\n3. Testen\n---------\n\nAb der zweiten Stunde sind in den Aufgaben automatisierte Tests durchzuführen. Hierfür verwenden wir Pytest. Nachdem Sie Test-Code geschrieben haben, rufen Sie `pytest` (manchmal auch `pytest3` oder `pytest-3`) in Ihrem Arbeitsverzeichnis auf, dann werden Ihre Tests ausgeführt. Wollen Sie die Tests der anderen Aufgaben auch ausführen (das sollten Sie zumindest tun, bevor Sie mit Ihrer Aufgabe beginnen und bevor Sie diese abgeben), dann starten Sie `pytest` aus `miniTopSim/work/`. Für das Importieren von Modulen gilt dasselbe wie für das `run.py` Skript.\n\nTests müssen ein assert Statement enthalten (siehe Vortragsfolien)!\n\nAb Aufgabe 6 und wenn nichts anderes angegeben ist, besteht ein Test aus einer Simulation, die ein `srf`-File erzeugt. Die letzte Oberfläche soll auf \"geringen Abstand\" von der letzten Oberfläche des entsprechenden `srf_save`-Files überprüft werden. Letzteres wird durch Kopieren des `srf`-Files einer vorangegangenen Simulation auf ein File mit Endung `.srf_save` erzeugt. Die in den Angaben verlangten Tests stellen ein Minimum dar. Es ist meist sinnvoll, weitere Tests zu definieren. Achten Sie aber darauf, dass diese möglichst nicht zu lange laufen.\n\n-------------------\n4. Arbeiten mit git\n-------------------\n\n- Sie können den Code jederzeit herunterladen (fetch bzw. pull). Erzeugen Sie einen Branch, auf dem Sie arbeiten. Wählen Sie den Branchnamen ident mit Ihrem Arbeitsverzeichnis (`Aufgabe1_basic` etc.). **Uploaden (pushen) Sie Ihren Branch spätestens um 8:00 am Tag Ihrer Präsentation. Laden Sie zusätzlich die \"Abzugebenden Files\" bis zu dieser Deadline auf TUWEL hoch.** Führen Sie nach der Präsentation und nach eventuellen Nachbesserungen Ihren Branch mit dem `master` Branch zusammen (merge) und **pushen Sie beide Branches bis spätestens eine Woche nach Ihrer Präsentation**.\n\n- Grundsätzlich nur getesteten, voll funktionsfähigen Code uploaden, insbesondere am `master` Branch. Lokal in Ihrem Branch ist es hingegen ratsam, viele Commits zu machen.\n\n- `png`- und `srf`-Files werden nicht versioniert, d.h. sie werden nicht ins Repository übertragen. Damit von Ihnen generierte `srf`-Files für Vergleichszwecke erhalten bleiben, kopieren Sie sie auf Files mit gleichem Namen aber Endung `.srf_save`, wenn Sie sicher sind, dass sich nichts mehr ändert.\n\n**Lesen Sie sorgfältig die Folien \"Working with GitHub\" aus dem einleitenden Vortrag.**\n\n\n----------------------------\n5. Hinweise zur Präsentation\n----------------------------\n\nSie sollen Ihre Arbeit in einem ca. 10-15-minütigen Vortrag präsentieren. Halten Sie den Vortrag in erster Linie für Ihre Kollegen und berücksichtigen Sie deren Wissensstand. Ihr Vortrag soll die Aufgabenstellung darlegen, den Code präsentieren und die Ergebnisse der Tests und/oder Simulationen beschreiben. Sie können dazu mehrere Hilfsmittel verwenden, in der Regel Powerpoint-Präsentation und/oder Spyder/PyCharm/Editor. Kurze Rechnungen können Sie online laufen lassen, bei längeren wird es angebracht sein, die Ergebnisse vorzubereiten.\n\nDamit Ihr Code \"präsentierbar\" ist, schreiben Sie möglichst übersichtlichen Code und beachten Sie den \"Style Guide for Python Code\" (http://www.python.org/dev/peps/pep-0008/) und die \"Docstring Conventions\" (http://www.python.org/dev/peps/pep-0257/).\n\n" }, { "alpha_fraction": 0.5909292101860046, "alphanum_fraction": 0.5969862341880798, "avg_line_length": 34.072540283203125, "blob_id": "42c799fd0804000a977c8cf209651ca5d59e76e4", "content_id": "06dd0b281b34e8c0a048e4efceae860c275cd539", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13538, "license_type": "permissive", "max_line_length": 86, "num_lines": 386, "path": "/mini_topsim/plot.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n'''\nFunctions to interactively plot 2D-surfaces with data read from a .srf file.\n\nThis module offers functionality to create an interactive matplotlib-plot of \n2D-surfaces with the data read from a .srf file. To create a plot you have to \ninvoke the \\'plot(filename)\\' function. Internally a private class is used to \nhandle the plotting.\n\nKeybindings:\n [Space]: shows next/previous surface\n [0-9]: only show each 2^n-th surface when pressing [Space]\n [f]: show first surface\n [l]: show last surface\n [r]: reverse direction of movement \n [a]: toggle between automatic and 1:1 aspect ratio\n [d]: toggle between showing multiple surfaces or only the current surface\n [s]: saves plot as .png in cwd with the same filename as the .srf file\n [b]: switch between automatic and fixed y-boundaries\n [q]: quit the plot\n\nThe .srf file is expected to have the following format and can also include \nmultiple surfaces:\n\n surface: (time) (npoints) x-positions y-positions\n x[0] y[0]\n x[1] y[1]\n ...\n x[npoints-1] y[npoints-1]\n surface: (time2) (npoints2) x-positions y-positions\n ...\n\nx[n]: x-position in nm\ny[n]: y-position in nm\ntime: time in s\nnpoints: number of points\n\n\nAdditionally this module can be used as a script:\n USAGE: $ python3 plot.py [Name of .srf file]\n\n\nClasses:\n WrongFileExtensionError: Exception that gets raised if the passed file \n doesn't have the correct FileExtension\n\nFunctions:\n plot(filename): extracts surface data from the .srf file and creates an \n interactive plot with the data\n\n\nAuthor: Haberl Alexander\nPart of the miniTopSim Project: https://github.com/hobler/miniTopSim\n'''\nimport os\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\n# The _SurfacePlotter class overwrites the default plt keybindings.\n# When overwriting some of these keybindings, matplotlib prints a warning \n# message, because they are bound to functions that will be removed in later \n# matplotlib versions.\n# The following lines stop these warnings from being printed and cluttering \n# the terminal.\n#\n# Note: for later matplotlib releases we might have to remove the following \n# line from the _SurfacePlotter class:\n# 'plt.rcParams['keymap.all_axes'] =''\nimport warnings\nimport matplotlib.cbook\nwarnings.filterwarnings(\"ignore\",category=matplotlib.cbook.mplDeprecation)\n#\n\n\nclass _SurfacePlotter:\n '''\n Private class that handles the plotting. \n \n This class should not be used outside of this module. If you want to plot \n a .srf file use the function \\'plot(filename)\\' instead! Lists where used to\n save the information of multiple surfaces. Each list element represents a \n surface at a specific point in time.\n\n Args:\n filename(string, string2 = None): \n string ... name of the *.srf file\n string2 ... name of the reference *.srf file to plot dashed \n\n Attributes:\n filename(string): Name of the .srf file\n xpoints_list(list): List of np-arrays. Each np-array holds all x-values \n of one surface\n ypoints_list(list): List of np-arrays. Each np-array holds all y-values \n of one surface\n time_list(list): Contains the timepoints from all surfaces.\n n_point_list(list): Contains the number of points from all surfaces.\n alreadyplotted_list(list): Contains information if a specific surface \n has already been plotted\n surface_index(int): Used for indexing the lists mentioned above. Points \n to the current surface\n forward_movement(bool): Toggling between moving forward/backwards.\n length(int): Length of the lists mentioned above.\n aspectratio_auto(bool): Toggling between automatic and 1:1 aspect-ratio\n deleteplot_mode(bool): Toggling between showing multiple surfaces \n or only the current one\n stepsize(int): Size of step when switching between surfaces\n boundarymode_auto(bool): Toggling between fixed and automatic \n x/y-boundaries\n ylim(Tuple of two floats): Bottom and Top y-limit of the plot.\n xlim(Tuple of two floats): Left and right x-limit of the plot.\n\n Raises:\n FileNotFoundError: if file is not found\n WrongFileExtensionError: if file doesn't have the correct file extension\n IndexError: if file is not formatted correctly\n ValueError: if file is not formatted correctly\n '''\n\n def __init__(self, filename, reffilename = None):\n '''\n Initializes all class parameters and changes default plt keybindings.\n '''\n self.filename = filename\n self.xpoints_list = list()\n self.ypoints_list = list()\n self.time_list = list()\n self.n_point_list = list()\n self.alreadyplotted_list = None\n self.surface_index = 0\n self.forward_movement = True\n self.length = 0\n self.aspectratio_auto = True\n self.deleteplot_mode = True\n self.stepsize = 1\n self.boundarymode_auto = True\n self.ylim = None\n self.xlim = None\n plt.rcParams['keymap.fullscreen'] = ['ctrl+f']\n plt.rcParams['keymap.yscale'] = ['ctrl+l']\n plt.rcParams['keymap.home'] = ['h', 'home']\n plt.rcParams['keymap.all_axes'] = ''\n plt.rcParams['keymap.save'] = ['ctrl+s']\n plt.rcParams['keymap.quit'] = ['ctrl+w', 'cmd+w']\n self._read_srf_file()\n if reffilename != None:\n self.refsrf = _SurfacePlotter(reffilename)\n else:\n self.refsrf = None\n \n def _read_srf_file(self):\n '''\n Extracts x/y-values, time and number of points from the .srf file\n '''\n with open(self.filename) as file:\n\n if (self.filename.endswith(('.srf_save', '.srf')) == False):\n raise WrongFileExtensionError(\n 'plot.py: Expected \\'.srf\\' or \\'.srf_save\\' file')\n\n xpoints = None\n ypoints = None\n i = 0\n j = 0\n\n for line in file:\n if 'surface:' in line:\n string_array = line.split(' ')\n self.time_list.append(float(string_array[1]))\n self.n_point_list.append(int(string_array[2]))\n\n xpoints = np.empty(self.n_point_list[i], dtype=np.float64)\n ypoints = np.empty(self.n_point_list[i], dtype=np.float64)\n self.xpoints_list.append(xpoints)\n self.ypoints_list.append(ypoints)\n\n i = i+1\n j = 0\n else:\n string_array = line.split(' ')\n xpoints[j] = float(string_array[0])\n ypoints[j] = float(string_array[1])\n j = j + 1\n\n self.length = i\n self.alreadyplotted_list = [False] * self.length\n\n def on_key_press(self, event):\n '''\n Changes attributes of the class depending on the pressed key.\n\n Gets called by plt when a key is pressed. \n\n Attributes:\n event: the key press event that causes this function to be called\n '''\n\n if(event.key == 'l'):\n lastelement = self.length - 1\n self.surface_index = lastelement\n\n elif(event.key == 'f'):\n self.surface_index = 0\n\n elif(event.key == ' '):\n if(self.forward_movement == True):\n self.surface_index = self.surface_index + self.stepsize\n if(self.surface_index >= self.length):\n self.surface_index = 0\n\n else:\n self.surface_index = self.surface_index - self.stepsize\n if(self.surface_index <= -1):\n self.surface_index = self.length - 1\n\n elif(event.key == 'r'):\n self.forward_movement = not self.forward_movement\n return\n\n elif(event.key == 'a'):\n self.aspectratio_auto = not self.aspectratio_auto\n\n elif(event.key == 'd'):\n self.deleteplot_mode = not self.deleteplot_mode\n return\n\n elif(event.key == 's'):\n fname = os.path.splitext(self.filename)[0] + '.png'\n plt.savefig(fname, dpi = 420)\n return\n\n elif(event.key == 'b'):\n self.boundarymode_auto = not self.boundarymode_auto\n if(self.boundarymode_auto == False):\n ax = plt.gca()\n self.ylim = ax.get_ylim()\n self.xlim = ax.get_xlim() \n\n elif(event.key == 'q'):\n plt.close('all')\n return\n\n elif(event.key.isnumeric() == True):\n self.stepsize = 2 ** int(event.key)\n return\n\n self.update_plot()\n\n return None\n\n def update_plot(self):\n '''\n Updates the plot depending on the saved parameters\n \n If srf-object includes a reference surface with different time-steps,\n the reference surface with the simulation time closest to the actual\n time is plotted in dashed\n '''\n if(self.deleteplot_mode == True):\n plt.clf()\n self.alreadyplotted_list = [False for i in range(self.length)]\n ax = plt.gca()\n box = ax.get_position()\n ax.set_position([box.x0, box.y0, box.width * 0.9, box.height])\n\n if(self.alreadyplotted_list[self.surface_index] == False):\n plt.plot(self.xpoints_list[self.surface_index], \n self.ypoints_list[self.surface_index], \n label='srf1:\\nt = ' + str(self.time_list[self.surface_index]) + 's')\n \n if self.refsrf != None:\n # plot surface with nearest time in reference file\n time = self.time_list[self.surface_index]\n refsrf_idx = self.refsrf.find_nearest(time)\n plt.plot(self.refsrf.xpoints_list[refsrf_idx], \n self.refsrf.ypoints_list[refsrf_idx], linestyle='dashed',\n label='srf2:\\nt = ' + str(self.refsrf.time_list[refsrf_idx]) + 's')\n\n self.alreadyplotted_list[self.surface_index] = True\n if(self.boundarymode_auto != True):\n plt.ylim(self.ylim)\n plt.xlim(self.xlim)\n else:\n ax = plt.gca()\n ax.relim()\n ax.autoscale(True, 'both', False)\n\n ax = plt.gca()\n if(self.aspectratio_auto != True):\n ax.set_aspect(aspect=1)\n else:\n ax.set_aspect(aspect = 'auto')\n\n plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n plt.xlabel('x in nm')\n plt.ylabel('y in nm')\n plt.title(\"Surfaces: 2D-Plot\")\n plt.grid(True, 'both', 'both')\n plt.draw()\n \n def find_nearest(self, time):\n '''\n returns surface index of srf-object at simulation time closest to time\n \n :param time: simulation time value\n \n :return: surface index with simulation time closest to time\n '''\n return (np.abs(np.asarray(self.time_list) - time)).argmin()\n \n def plot_interactive(self):\n '''\n Starts the interactive plot\n '''\n fig = plt.figure()\n fig.canvas.mpl_connect('key_press_event', self.on_key_press)\n self.update_plot()\n plt.show()\n\nclass WrongFileExtensionError(Exception):\n '''\n Gets raised if the FileExtension is not correct\n '''\n pass\n\n\ndef plot(filename, reffilename = None):\n '''\n Plots the 2D-surfaces from a \\'.srf\\' file in an interactive plt-plot.\n\n Keybindings: \n [Space]: shows next/previous surface\n [0-9]: only show each 2^n-th surface when pressing [Space]\n [f]: show first surface\n [l]: show last surface\n [r]: reverse direction of movement \n [a]: toggle between automatic and 1:1 aspect ratio\n [d]: toggle between showing multiple surfaces or only the current surface\n [s]: saves plot as .png in cwd with the same filename as the .srf file\n [b]: switch between automatic and fixed y-boundaries\n [q]: quit the plot\n\n The .srf file is expected to have the following format and can also include \n multiple surfaces:\n\n surface: (time) (npoints) x-positions y-positions\n x[0] y[0]\n x[1] y[1]\n ...\n x[npoints-1] y[npoints-1]\n surface: (time2) (npoints2) x-positions y-positions\n ...\n\n x[n]: x-position in nm\n y[n]: y-position in nm\n time: time in s\n npoints: number of points\n\n Args:\n filename(str): Name of the \\'.srf\\' file.\n reffilename(str): Optional. Name of the reference \\'.srf\\' file.\n\n Raises:\n FileNotFoundError: if file is not found\n WrongFileExtensionError: if file doesn't have the correct file extension\n IndexError: if file is not formatted correctly\n ValueError: if file is not formatted correctly\n '''\n plotter = _SurfacePlotter(filename, reffilename)\n plotter.plot_interactive()\n\n\nif __name__ == '__main__':\n '''\n This module can be used as a script to plot 2D-surfaces from a \\'.srf\\' file\n\n USAGE: $ python3 plot.py 1st.srf file 2nd.srf file\n\n If no filename is specified the default name 'trench.srf_save' will be used.\n '''\n if(len(sys.argv) == 2):\n plot(sys.argv[1])\n elif(len(sys.argv) == 3):\n plot(sys.argv[1], sys.argv[2]) \n else:\n print('plot.py: no file specified! Using default file.')\n plot('config1.srf')\n" }, { "alpha_fraction": 0.6494845151901245, "alphanum_fraction": 0.6546391844749451, "avg_line_length": 14.916666984558105, "blob_id": "e4a4afe75a3eec58dff4efcc39978ed841f706b4", "content_id": "97d84194a867d110c76434b4d1e07318e8428cc0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 194, "license_type": "permissive", "max_line_length": 69, "num_lines": 12, "path": "/work/Aufgabe5_delooping/run.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "\"\"\"\nUsage: $ python3 run.py \"etch.cfg\"\n\nRuns the simulation for testing the timing of the delooping algorithm\n\"\"\"\n\n\nimport timing\n\nif __name__ == '__main__':\n\n timing.mini_topsim_timing()\n\n\n\n" }, { "alpha_fraction": 0.6553672552108765, "alphanum_fraction": 0.6610169410705566, "avg_line_length": 18.66666603088379, "blob_id": "aab0e2c804296a1e6705bb9dbe5216067eb62c8c", "content_id": "7434068b5eba2a688036b68439e90f6400f89121", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 177, "license_type": "permissive", "max_line_length": 62, "num_lines": 9, "path": "/work/Aufgabe14_gui/run.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "import os, sys\n\ncurrent_dir = os.path.dirname(__file__)\ncodedir = os.path.join(current_dir, '..', '..', 'mini_topsim')\nsys.path.insert(0, codedir)\n\nfrom gui import main\n\nmain()\n" }, { "alpha_fraction": 0.6896551847457886, "alphanum_fraction": 0.6945812702178955, "avg_line_length": 24.5, "blob_id": "22de9bdf2c7349a5eca6bd5440b1fb5c3febffb0", "content_id": "65a0fa5e1c95c7c656be3d2d1146c40e12429be2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 203, "license_type": "permissive", "max_line_length": 58, "num_lines": 8, "path": "/work/Aufgabe4_sputter/run.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "import os, sys\nfiledir = os.path.dirname(__file__)\ncodedir = os.path.join(filedir, '..', '..', 'mini_topsim')\nsys.path.insert(0, codedir)\nimport mini_topsim.main as mtp\n\n#Run minitopsim\nmtp.mini_topsim()" }, { "alpha_fraction": 0.7605984807014465, "alphanum_fraction": 0.7605984807014465, "avg_line_length": 25.799999237060547, "blob_id": "85a66320028c061bd148cf5a89d00c58028f7837", "content_id": "33f4e44f2ba5f4498348527cfad8e0562526616d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 401, "license_type": "permissive", "max_line_length": 53, "num_lines": 15, "path": "/work/Aufgabe10_moc/run_all.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "\"\"\"\nScript to run all necessary simulations consecutively\n\"\"\"\n\nfrom mini_topsim.main import mini_topsim\n\nmini_topsim('cosine_norm_noredep.cfg')\nmini_topsim('cosine_moc_noredep.cfg')\nmini_topsim('cosine_norm_redep.cfg')\nmini_topsim('cosine_moc_redep.cfg')\n\nmini_topsim('gauss_norm_noredep.cfg')\nmini_topsim('gauss_moc_noredep.cfg')\nmini_topsim('gauss_norm_redep.cfg')\nmini_topsim('gauss_moc_redep.cfg')" }, { "alpha_fraction": 0.6938775777816772, "alphanum_fraction": 0.701298713684082, "avg_line_length": 23.454545974731445, "blob_id": "474b841448781277e9203b5db0ffde68b5575dfd", "content_id": "b652a0dbca653d4d6511aebc6d1a016a805859f4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 539, "license_type": "permissive", "max_line_length": 56, "num_lines": 22, "path": "/work/templates/test_run.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "\"\"\"\nTemplate for testing miniTopSim using pytest.\n\nFeel free to copy, but do not modify the original!\n\"\"\"\nimport pytest\nfrom mini_topsim.main import mini_topsim\nimport mini_topsim.parameters as par\n\ndef test_run():\n \"\"\"Test running miniTopSim.\"\"\"\n success = mini_topsim()\n assert success, 'Error during executing miniTopSim.'\n\[email protected]()\ndef set_param():\n \"\"\"Set parameter value.\"\"\"\n par.TestParameter = 56\n\ndef test_set_param(set_param):\n \"\"\"Test setting a parameter value.\"\"\"\n assert par.TestParameter == 56\n\n" }, { "alpha_fraction": 0.6266798973083496, "alphanum_fraction": 0.631631076335907, "avg_line_length": 32.18779373168945, "blob_id": "cf811d758ba05006374cc629912231f79c2970f9", "content_id": "dcb333157cc5d32ec8fd30a0f6d5f0402df58814", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7069, "license_type": "permissive", "max_line_length": 78, "num_lines": 213, "path": "/mini_topsim/beam.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "\"\"\"\nImplementation of three beam classes to calculate the beam flux density\n\nThis script is used to implement three different types of beams - broad beam,\nGaussian beam and error function beam through classes and calculates the beam\nflux density in atoms/cm^2s according to the corresponding formula and\nparameters.\n\nThe BeamConstant class is dependent on the beam current density J.\nThe BeamGaussian class is dependent on the beam current I, scan width Wz, beam\ncenter xc and the Full Width at half maximum FWHM.\nThe BeamError class is dependent on the beam current I, scan width Wz, beam\nwidth Wx, beam center xc and the Full Width at half maximum FWHM.\n\nThe initialisation function selects the beam profile based on the loaded\nparameters.\nOther functions include the get_sigma to calculate the required standard\ndeviation.\n\nThis file contains the following functions:\n * init_beam_profile - initializes the beam profile\n * get_sigma - calculates the standard deviation\n\nIt also includes these classes and methods:\n * BeamConstant - class used to represent the broad beam\n * __call__ - returns the calculated beam flux density for the broad\n beam\n * BeamGaussian - class used to represent the Gaussian beam\n * __call__ - returns the calculated beam flux density for the Gaussian\n beam\n * BeamError - class used to represent the error function beam\n * __call__ - returns the calculated beam flux density for the error\n function beam\n\"\"\"\n\nimport numpy as np\nfrom scipy import constants as const\nfrom scipy import special as sp\nimport mini_topsim.parameters as par\n\n\ndef init_beam_profile():\n \"\"\"\n Initialising the beam profile according to the config parameters\n\n :return:\n \"\"\"\n global beam_profile\n\n if par.BEAM_TYPE == 'constant':\n beam_profile = BeamConstant()\n elif par.BEAM_TYPE == 'Gaussian':\n beam_profile = BeamGaussian()\n elif par.BEAM_TYPE == 'error function':\n beam_profile = BeamError()\n else:\n exit('Error: BEAM_TYPE invalid\\n')\n\n\ndef get_sigma(fwhm):\n \"\"\"\n Calculating the standard deviation from the Full Width at half maximum\n\n Keyword arguments:\n :param fwhm: Full Width at half maximum\n :return: standard deviation\n \"\"\"\n return fwhm / (np.sqrt(8 * np.log(2)))\n\n\nclass BeamConstant:\n \"\"\"\n Class to describe the broad beam with associated callable object\n\n Attributes:\n J: beam current density in A/cm^2\n const_f: constant factor J / e\n\n Methods:\n __call__(self, x): Callable object for calculating the beam flux density\n \"\"\"\n\n def __init__(self, J=None):\n \"\"\"\n The constructor for the BeamConstant class\n\n If the arguments are not passed in, the loaded parameters from the\n config file will be used instead.\n\n Keyword arguments:\n :param J: beam current density in A/cm^2 (default None)\n \"\"\"\n self.J = par.BEAM_CURRENT_DENSITY if J is None else J\n self.const_f = self.J / const.e\n\n def __call__(self, x):\n \"\"\"\n Callable object for calculating the beam flux density\n\n Keyword arguments:\n :param x: x-values in nm\n :return: beam flux density in atoms/cm^2s\n \"\"\"\n fbeam = np.ones_like(x) * self.const_f\n\n return fbeam\n\n\nclass BeamGaussian:\n \"\"\"\n Class to describe the Gaussian beam with associated callable object\n\n Attributes:\n I: beam current in A\n Wz: scan width in nm\n xc: beam center in nm\n fwhm: Full Width at half maximum in nm\n sigma: calculated standard deviation in nm\n const_f : constant factor I / (e * sqrt(2 * sigma) * Wz)\n\n Methods:\n __call__(self, x): Callable object for calculating the beam flux density\n \"\"\"\n\n def __init__(self, I=None, fwhm=None, Wz=None, xc=None):\n \"\"\"\n The constructor for the BeamGaussian class\n\n If the arguments are not passed in, the loaded parameters from the\n config file will be used instead.\n\n Keyword arguments:\n :param I: beam current in A (default None)\n :param fwhm: Full Width at half maximum in nm (default None)\n :param Wz: scan width in nm (default None)\n :param xc: beam center in nm (default None)\n \"\"\"\n self.I = par.BEAM_CURRENT if I is None else I\n self.fwhm = par.FWHM if fwhm is None else fwhm\n self.Wz = par.SCAN_WIDTH if Wz is None else Wz\n self.xc = par.BEAM_CENTER if xc is None else xc\n self.sigma = get_sigma(self.fwhm)\n self.const_f = self.I / (const.e * np.sqrt(2 * self.sigma) * self.Wz)\n\n def __call__(self, x):\n \"\"\"\n Callable object for calculating the beam flux density\n\n Keyword arguments:\n :param x: x-values in nm\n :return: beam flux density in atoms/cm^2s\n \"\"\"\n fbeam = self.const_f * np.exp(-(x - self.xc) ** 2\n / (2 * self.sigma ** 2))\n\n # Converting beam flux density to atoms/cm^2s\n return fbeam * 1e14\n\n\nclass BeamError:\n \"\"\"\n Class to describe the error function beam with associated callable object\n\n Attributes:\n I: beam current in A\n Wx: beam width in nm\n Wz: scan width in nm\n xc: beam center in nm\n fwhm: Full Width at half maximum in nm\n sigma: calculated standard deviation in nm\n const_f : constant prefactor I / (2 * e * Wx * Wz)\n x1: lower limit of the scan interval xc - Wx / 2\n x2: upper limit of the scan interval xc + Wx / 2\n \"\"\"\n\n def __init__(self, I=None, fwhm=None, Wx=None, Wz=None, xc=None):\n \"\"\"\n The constructor for the BeamError class\n\n If the arguments are not passed in, the loaded parameters from the\n config file will be used instead.\n\n Keyword arguments:\n :param I: beam current in A (default None)\n :param fwhm: Full Width at half maximum in nm (default None)\n :param Wx: beam width in nm (default None)\n :param Wz: scan width in nm (default None)\n :param xc: beam center in nm (default None)\n \"\"\"\n self.I = par.BEAM_CURRENT if I is None else I\n self.fwhm = par.FWHM if fwhm is None else fwhm\n self.Wx = par.ERF_BEAM_WIDTH if Wx is None else Wx\n self.Wz = par.SCAN_WIDTH if Wz is None else Wz\n self.xc = par.BEAM_CENTER if xc is None else xc\n self.sigma = get_sigma(self.fwhm)\n self.const_f = self.I / (2 * const.e * self.Wx * self.Wz)\n self.x1 = self.xc - self.Wx / 2\n self.x2 = self.xc + self.Wx / 2\n\n def __call__(self, x):\n \"\"\"\n Callable object for calculating the beam flux density\n\n Keyword arguments:\n :param x: x-values in nm\n :return: beam flux density in atoms/cm^2s\n \"\"\"\n fbeam = self.const_f * \\\n (sp.erf(-(x - self.x2) / (np.sqrt(2) * self.sigma))\n - sp.erf(- (x - self.x1) / (np.sqrt(2) * self.sigma)))\n\n # Converting beam flux density to atoms/cm^2s\n return fbeam * 1e14\n" }, { "alpha_fraction": 0.561482846736908, "alphanum_fraction": 0.5741410255432129, "avg_line_length": 28.87837791442871, "blob_id": "2b12bda044015b2d4dda57fe7584fa6008ce346b", "content_id": "bb1e740d6644772d394bf50e93367d499c348b0c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2212, "license_type": "permissive", "max_line_length": 83, "num_lines": 74, "path": "/work/Aufgabe1_basic/surface.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "\"\"\"\nDefines the class Surface\n\nincludes function \n\"normal_vector\" which calculates the normal vectors in every point of the surface\n\"plot\" which plots the surface\n\"write\" which writes the surface points into a .srf file\n\"\"\"\nimport numpy as np\nimport init_surface\nimport matplotlib.pyplot as plt\n\n\nclass Surface:\n\n def __init__(self):\n \"\"\"\n Initializes the x and y-Values with the init_surface module\n \"\"\"\n self.xVals = np.arange(-50., 51., 1.)\n self.yVals = init_surface.init_surface(self.xVals)\n\n def normal_vector(self):\n \"\"\"\n calculates the normal vectors in every point of the surface\n\n calculates the vector between the nearest neigbours of the point\n and returns the normal vector of it\n\n :returns: x Values, y Values of the normal vectors\n \"\"\"\n x = np.zeros_like(self.xVals)\n y = np.zeros_like(self.yVals)\n\n #start and endpoint only have one neighbor \n x[0] = self.xVals[1] - self.xVals[0]\n y[0] = self.yVals[1] - self.yVals[0]\n x[-1] = self.xVals[-1] - self.xVals[-2]\n y[-1] = self.yVals[-1] - self.yVals[-2]\n\n\n #right neigbour - left neigbour\n y[1:-1] = np.array(self.yVals[2::] - self.yVals[:-2:])\n x[1:-1] = np.array(self.xVals[2::] - self.xVals[:-2:])\n\n magnitude = np.linalg.norm([x, y], axis=0)\n\n return (y / magnitude), (-x / magnitude)\n\n def plot(self, time):\n \"\"\"\n plots the surface\n\n :param time: current simulation time\n \"\"\"\n plt.plot(self.xVals, self.yVals, \"x-\", label=f\"t = {time}\")\n plt.title('Surface')\n plt.xlabel('x[nm]')\n plt.ylabel('y[nm]')\n\n def write(self, time, filename):\n \"\"\"\n writes the surface values into an srf file\n\n format: surface: <time> <npoints> x-positions y-positions\n x[0] y[0]\n \n :param time: current simulation time\n :param filename: name of the file\n \"\"\"\n with open(filename, 'a') as f:\n f.write(f\"surface: {time} {len(self.xVals)} x-positions y-positions\\n\")\n for x, y in zip(self.xVals, self.yVals):\n f.write(f\"{x} {y}\\n\")\n\n" }, { "alpha_fraction": 0.5773022174835205, "alphanum_fraction": 0.583398163318634, "avg_line_length": 33.73423385620117, "blob_id": "77eed6f7a0fc390079d4fa2c832f8d62bc48f1ca", "content_id": "cc924a125dbe80d99d1781d412c4e6d82a26512a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7710, "license_type": "permissive", "max_line_length": 146, "num_lines": 222, "path": "/mini_topsim/gui.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "import tkinter.tix as tix\n\n\n\nimport sys\nimport os\nimport configparser\nimport tkinter as tk\nimport tkinter.ttk as ttk\n\nfrom tkinter import messagebox\nfrom functools import partial\nfrom PIL import ImageTk, Image\nfrom tkinter import filedialog\n\nfrom mini_topsim.gui_13 import Gui\n\ntk_root = None\ntk_notebook = None\ntabnames = []\ntabs = []\ngui_classes = []\n\n\nclass GuiNew(Gui):\n \"\"\"\n This class represents one Page of the GUI for reading, changing and writing purposes.\n\n It extends the Gui class from Aufgabe 13 (gui_13.py) and overwrites the init to modify it for use in the notebook.\n The input is read from the parameters.db file.\n \"\"\"\n def __init__(self,maintk,frame,section,parameter_file,button_file,cfg_file,initial_file):\n \"\"\"\n This function sets all needed configurations of one Page of the Notebook.\n\n Attributes\n ----------\n maintk : the main tkinter link\n frame : the tkinter frame of the page which is reserved for this section\n section : the section of this notebook page\n parameter_file : path to the parameter file\n button_file : path to the button file\n cfg_file : path to the config file\n initial_file : path to the initial values file\n \"\"\"\n self.root = frame\n self.maintk = maintk\n\n self.root.protocol = maintk.protocol\n self.root.title = maintk.title\n self.root.geometry = maintk.geometry\n self.maintk.protocol('WM_DELETE_WINDOW', self.exit_window)\n\n self.section = section\n self.parameter_file = parameter_file\n self.button_file = button_file\n self.cfg_file = cfg_file\n self.data = self.get_data()\n if initial_file is not None:\n cp = configparser.ConfigParser()\n cp.optionxform = str\n cp.read(initial_file)\n for key in cp[self.section]:\n val = eval(cp[self.section][key])\n self.data[key][0] = val\n\n self.root.columnconfigure(0, weight=0)\n self.root.columnconfigure(1, weight=1)\n self.root.columnconfigure(2, weight=0)\n\n screen_width = self.root.winfo_screenwidth()\n screen_height = self.root.winfo_screenheight()\n gui_width = 500\n gui_height = 100 + 30 * len(self.data)\n if gui_width > screen_width:\n gui_width = screen_width\n if gui_height > screen_height:\n gui_height = screen_height\n\n self.maintk.geometry('{}x{}'.format(gui_width, gui_height))\n x_position = int(screen_width/2 - gui_width/2)\n y_position = int(screen_height/2 - gui_height/2)\n self.maintk.geometry('+{}+{}'.format(x_position, y_position))\n\n self.display()\n tooltip = tix.Balloon(self.root)\n tooltip.subwidget('label').forget()\n tooltip.message.config(bg=\"gray95\",fg=\"black\")\n for subwidgets in tooltip.subwidgets_all():\n subwidgets.configure(bg='gray95')\n for entry in self.entries:\n tooltip.bind_widget(self.entries[entry]['entry'],balloonmsg=self.data[entry][2])\n\n self.root.bind(\"<<NotebookTabChanged>>\",self.on_tab_switch)\n\n def exit_window(self):\n \"\"\"\n This function will be called when you try to leave the GUI by the 'X'.\n \n You will be asked for saving it.\n \"\"\"\n answer = False\n success = True\n answer = messagebox.askyesno('Create Config file?', 'Do you want '\\\n 'to save the parameters?')\n if answer:\n success = self.save()\n if success:\n self.close()\n\n def close(self):\n \"\"\"\n This function closes the GUI.\n \"\"\"\n self.maintk.destroy()\n\n def on_tab_switch(self):\n \"\"\"\n This function resizes the gui to the size of the new tab.\n \"\"\"\n screen_width = self.maintk.winfo_screenwidth()\n screen_height = self.maintk.winfo_screenheight()\n window_width = self.maintk.winfo_width()\n gui_width = 500\n if window_width < gui_width:\n window_width = gui_width\n gui_height = 100 + 30 * len(self.data)\n if gui_width > screen_width:\n gui_width = screen_width\n if gui_height > screen_height:\n gui_height = screen_height\n self.maintk.geometry('{}x{}'.format(window_width, gui_height))\n\n def save(self):\n \"\"\"\n This function saves the data in a config file.\n\n Therefore a filedialog is opened to help you to get the right\n directory.\n \"\"\"\n is_invalid = False\n for c in gui_classes:\n is_invalid |= (not c.check_data())\n if not is_invalid:\n cp = configparser.ConfigParser()\n cp.optionxform = str\n file_name = filedialog.asksaveasfilename(\n initialdir=self.cfg_file,\n title='Save config', filetypes=(('cfg-files', '*.cfg'),\n ('all files', '*.*')),\n defaultextension='.cfg',\n initialfile='beispiel2.cfg')\n for guis in gui_classes:\n cp.add_section(guis.section)\n for key, value in guis.data.items():\n if type(value[0]) is str:\n cp.set(guis.section, key, \"'\"+str(value[0]) +\"'\")\n else:\n cp.set(guis.section, key, str(value[0]))\n if file_name:\n with open(file_name, 'w') as file:\n cp.write(file)\n messagebox.showinfo('Save', 'Save of config successfully!')\n return True\n else:\n return False\n\n\ndef notebook_tab_changed(event):\n '''\n Determines which Tab was switched to and triggers the event there.\n '''\n i = tk_notebook.index(tk_notebook.select())\n gui_classes[i].on_tab_switch()\n\n\ndef main():\n global tk_root\n global tk_notebook\n tk_root = tix.Tk()\n tk_notebook = ttk.Notebook(tk_root)\n\n current_dir = os.path.dirname(os.path.abspath(__file__))\n path_to_parameter_file = os.path.join(current_dir, 'parameters.db')\n path_to_button_file = os.path.join(current_dir, 'info.png')\n parent_dir = os.path.dirname(current_dir)\n path_to_cfg_file = os.path.join(parent_dir, 'work', 'Aufgabe14_gui')\n path_to_init_file = None\n if not os.path.exists(path_to_parameter_file):\n print('File parameters.db cannot be found in directory {}'.format(\n path_to_parameter_file))\n sys.exit()\n if not os.path.exists(path_to_button_file):\n print('File info.png cannot be found in directory {}'.format(\n path_to_button_file))\n sys.exit()\n\n if len(sys.argv) == 2:\n path_to_init_file = os.path.join(parent_dir,sys.argv[1])\n if not os.path.exists(path_to_init_file):\n print('File *.cfg cannot be found in directory {}'.format(\n path_to_init_file))\n sys.exit()\n\n cp = configparser.ConfigParser()\n cp.optionxform = str\n cp.read(path_to_parameter_file)\n tabnames.extend(cp.sections())\n print(tabnames)\n\n for i in range(len(tabnames)):\n tabs.append(ttk.Frame(tk_notebook))\n tk_notebook.add(tabs[i], text=tabnames[i])\n gui_classes.append(GuiNew(tk_root, tabs[i], tabnames[i], path_to_parameter_file, path_to_button_file, path_to_cfg_file,path_to_init_file))\n\n tk_notebook.bind(\"<<NotebookTabChanged>>\",notebook_tab_changed)\n tk_notebook.pack(expand=1, fill=\"both\")\n tk_root.title('MiniTopSim-Project')\n tk_root.mainloop()\n\nif __name__ == \"__main__\":\n main()" }, { "alpha_fraction": 0.623311460018158, "alphanum_fraction": 0.6329602599143982, "avg_line_length": 28.44318199157715, "blob_id": "715e1bc950e6905395d239cd7b849aef54787859", "content_id": "1dbddc98830bf170107996ae26bc1c595e94eda8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2591, "license_type": "permissive", "max_line_length": 77, "num_lines": 88, "path": "/work/Aufgabe5_delooping/timing.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "\"\"\"\nRunning the main simulation with the added timing tests\n\"\"\"\nimport sys\nimport os\nimport numpy as np\n\nfiledir = os.path.dirname(__file__)\ncodedir = os.path.join(filedir, '..', '..', 'mini_topsim')\nsys.path.insert(0, codedir)\nfrom time import time as currenttime\nimport matplotlib.pyplot as plt\nfrom mini_topsim.surface import Surface\nfrom advance import advance\nfrom advance import timestep\nimport parameters as par\nimport plot\n\n\ndef mini_topsim_timing():\n \"\"\"\n Reads the Simulation parameters, starts the sim, plots and writes to file\n\n the first sys.argv[1] is the config file name.\n\n if no sys argument is passed the programm will stop.\n Writes all calculated datapoints to a file with the\n filenname: <config_file_name>.srf\n\n \"\"\"\n print('Running miniTopSim ...')\n\n if len(sys.argv) > 1:\n config_filename = sys.argv[1]\n else:\n print(\"Error: No config passed.\")\n sys.exit()\n\n config_file = os.path.join(os.path.dirname(__file__), config_filename)\n\n if not config_file.endswith('.cfg'):\n print('Error: Incorrect config.')\n sys.exit()\n\n filename = os.path.splitext(config_file)[0] + '.srf'\n\n if os.path.exists(filename):\n os.remove(filename)\n\n par.load_parameters(config_file)\n\n tend = par.TOTAL_TIME\n dt = par.TIME_STEP\n par.DELTA_X = 10\n simulation_time_array = np.empty((2, 0))\n\n while par.DELTA_X > 0.2:\n # print(par.DELTA_X)\n surface = Surface()\n time = 0\n start_simulation_time = currenttime()\n while time < tend:\n surface.write(time, filename)\n dtime = timestep(dt, time, tend)\n advance(surface, dtime)\n time += dtime\n\n stop_simulation_time = currenttime()\n simulation_time = stop_simulation_time - start_simulation_time\n simulation_time_array = np.append(simulation_time_array, np.array(\n (int(100 / par.DELTA_X), simulation_time)).reshape(2, 1), axis=1)\n # print('The Simulation took: {}s'.format(float(simulation_time)))\n # print(np.array((int(100/par.DELTA_X))))\n # print(par.DELTA_X)\n surface.write(time, filename)\n par.DELTA_X = par.DELTA_X - 0.6\n # print(par.DELTA_X)\n\n plt.title('Simulationtime in dependence of the number of points')\n plt.plot(simulation_time_array[0], simulation_time_array[1], 'b+-')\n plt.xscale('log')\n plt.yscale('log')\n plt.xlabel('Number of points')\n plt.ylabel('Time in Seconds')\n plt.grid(which='both')\n plt.show()\n if par.PLOT_SURFACE:\n plot.plot(filename)\n" }, { "alpha_fraction": 0.6896551847457886, "alphanum_fraction": 0.7352613806724548, "avg_line_length": 33.57692337036133, "blob_id": "aa78e5c0abffd435275d5603bf3a7b4ebbdaaf93", "content_id": "24c22257d4c86d7ff2b4f06f51eb415af87ac0da", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 899, "license_type": "permissive", "max_line_length": 69, "num_lines": 26, "path": "/work/Aufgabe6_testing/etch_dist_1_0_125.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "import os, sys\nfiledir = os.path.dirname(__file__)\ncodedir = os.path.join(filedir, '..', '..', 'mini_topsim')\nsys.path.insert(0, codedir)\n\nimport mini_topsim.plot as srfplt\nfrom mini_topsim.surface import Surface\nfrom mini_topsim.main import par\n\nsrf_filename1 = os.path.join(filedir,'etch_dx0_125.srf')\nsrf_filename2 = os.path.join(filedir,'etch_dx1.srf')\n\nsrfplotter = srfplt._SurfacePlotter(srf_filename1, srf_filename2)\n\npar.load_parameters(os.path.join(filedir,'etch_dx0_125.cfg'))\nsrf1 = Surface()\nsrf1.xvals = srfplotter.xpoints_list[-1]\nsrf1.yvals = srfplotter.ypoints_list[-1]\n\npar.load_parameters(os.path.join(filedir,'etch_dx1.cfg'))\nsrf2 = Surface()\nsrf2.xvals = srfplotter.refsrf.xpoints_list[-1]\nsrf2.yvals = srfplotter.refsrf.ypoints_list[-1]\n\nprint('Surface distance dx0_125 to dx1 = %.5f' % srf1.distance(srf2))\nprint('Surface distance dx1 to dx0_125 = %.5f' % srf2.distance(srf1))\n" }, { "alpha_fraction": 0.7287581562995911, "alphanum_fraction": 0.7287581562995911, "avg_line_length": 26.81818199157715, "blob_id": "825a6767cbd8bc4cca3baa336d6a746c84d1e21d", "content_id": "3d1c65f44ad5964e81b40fb332071a65acea14d8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 306, "license_type": "permissive", "max_line_length": 57, "num_lines": 11, "path": "/work/Aufgabe10_moc/plot_all.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "\"\"\"\nScript to plot all necessary simulations\n\"\"\"\n\nfrom mini_topsim.plot import plot\n\nplot('cosine_norm_noredep.srf', 'cosine_moc_noredep.srf')\nplot('cosine_norm_redep.srf', 'cosine_moc_redep.srf')\n\nplot('gauss_norm_noredep.srf', 'gauss_moc_noredep.srf')\nplot('gauss_norm_redep.srf', 'gauss_moc_redep.srf')\n" }, { "alpha_fraction": 0.7527173757553101, "alphanum_fraction": 0.7554348111152649, "avg_line_length": 27.30769157409668, "blob_id": "377e4a1d3cac21e49ec36867cf2e688d2eea594b", "content_id": "3ddc9d6cd4fa92df102de397771e8abc9c6174ef", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 368, "license_type": "permissive", "max_line_length": 58, "num_lines": 13, "path": "/work/Aufgabe9_redep/run.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "import os, sys\nfiledir = os.path.dirname(__file__)\ncodedir = os.path.join(filedir, '..', '..', 'mini_topsim')\nsys.path.insert(0, codedir)\nimport mini_topsim.main as mtp\nimport numpy as np\nimport mini_topsim.sputtering as sputter\nimport mini_topsim.beam as beam\nimport scipy.constants as sciconst\nimport mini_topsim.parameters as par\n\n#Run minitopsim\nmtp.mini_topsim()\n" }, { "alpha_fraction": 0.7008547186851501, "alphanum_fraction": 0.7094017267227173, "avg_line_length": 19.647058486938477, "blob_id": "79da7ec2803a5df93340a240ff3c883bb0c2d03a", "content_id": "5b5dc97cb9575260f1c4a4ad2bdfb3271c1ddd97", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 351, "license_type": "permissive", "max_line_length": 63, "num_lines": 17, "path": "/work/Aufgabe8_beam/run.py", "repo_name": "hobler/miniTopSim20", "src_encoding": "UTF-8", "text": "\"\"\"\nScript to run miniTopSim code from work directory Aufgabe8_beam\n\nUsage: $python3 run.py <.cfg file>\n\"\"\"\n\nimport os\nimport sys\n\n# Adding the code directory to sys.path\nfiledir = os.path.dirname(__file__)\ncodedir = os.path.join(filedir, '..', '..', 'mini_topsim')\nsys.path.insert(0, codedir)\n\nfrom mini_topsim.main import mini_topsim\n\nmini_topsim()\n" } ]
43
nightman413/e-commerce
https://github.com/nightman413/e-commerce
6fff6593f04f51011cda00574f54f19308bd1296
9da08a897f8ef587ceb6b31366dd8c3ef1e512e6
daae9ef4f76613cb1cd590fc3396c988e2cbcaa6
refs/heads/master
2022-11-27T13:48:25.858649
2020-08-11T11:42:06
2020-08-11T11:42:06
286,728,315
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.7108886241912842, "alphanum_fraction": 0.7121402025222778, "avg_line_length": 29.769229888916016, "blob_id": "ab2579658f221ae345c0161f7fdced1e2655a69f", "content_id": "3205ef46e13950a242b558287d8bfc3873b2e3c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 799, "license_type": "no_license", "max_line_length": 84, "num_lines": 26, "path": "/product/admin.py", "repo_name": "nightman413/e-commerce", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom product.models import Category, Product , Images\n\n# Register your models here.\n\nclass ProductImagesInline(admin.TabularInline):\n model = Images\n extra = 5\n\nclass CategoryAdmin(admin.ModelAdmin):\n list_display = ['title', 'status']\n list_filter = ['status']\n\nclass ProductAdmin(admin.ModelAdmin):\n list_display = ['title', 'category' , 'price', 'amount', 'image_tag' , 'status']\n readonly_fields = ['image_tag']\n list_filter = ['status','category']\n inlines = [ProductImagesInline]\n\nclass ImagesAdmin(admin.ModelAdmin):\n list_display = ['title', 'product', 'image_tag']\n readonly_fields = ['image_tag']\n\nadmin.site.register(Category, CategoryAdmin)\nadmin.site.register(Product, ProductAdmin)\nadmin.site.register(Images, ImagesAdmin)" }, { "alpha_fraction": 0.6622562408447266, "alphanum_fraction": 0.6650418043136597, "avg_line_length": 26.634614944458008, "blob_id": "96f4bc62a31226542e2865ca2f09b7dad72ed1a9", "content_id": "0c14f1eb40efc9408610095ba2e88d1689cda72c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1453, "license_type": "no_license", "max_line_length": 87, "num_lines": 52, "path": "/home/views.py", "repo_name": "nightman413/e-commerce", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom home.models import Setting\n\n# Create your views here.\n\nfrom home.models import ContactFormu, ContactFormMessage\n\n\n\ndef index(request):\n setting = Setting.objects.get(pk=1)\n context = {'setting':setting, 'page':'home'}\n return render(request, 'index.html',context)\n\n\n\n\n\ndef hakkımızda(request):\n setting = Setting.objects.get(pk=1)\n context = {'setting':setting}\n return render(request, 'hakkımızda.html',context)\n\n\n\n\n\ndef referanslar(request):\n setting = Setting.objects.get(pk=1)\n context = {'setting':setting}\n return render(request, 'referanslarımız.html',context)\n\n\n\ndef iletisim(request):\n\n if request.method == 'POST' : # form post edildiyse\n form = ContactFormu(request.POST)\n if form.is_valid():\n data = ContactFormu() # model ile bağlantı kur\n data.name = form.cleaned_data['name'] # formdan bilgiyi al\n data.email = form.cleaned_data['email']\n data.subject = form.cleaned_data['subject']\n data.message = form.cleaned_data['message']\n data.save() # Veritabanına kaydet\n messages.success(request, \"mesajınız başarılı bir şekilde gönderilmiştir \")\n return HttpResponseRedirect ('/iletisim')\n\n setting = Setting.objects.get(pk=1)\n form = ContactFormu()\n context = {'setting':setting, 'form':form}\n return render(request, 'iletisim.html',context)" }, { "alpha_fraction": 0.5587392449378967, "alphanum_fraction": 0.610315203666687, "avg_line_length": 19.52941131591797, "blob_id": "979bb584d0035eb01c805b27c61dc2635a197bd9", "content_id": "f68b29303f61ddd57be21eb4346fa13bccf85893", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 349, "license_type": "no_license", "max_line_length": 45, "num_lines": 17, "path": "/home/migrations/0005_auto_20200809_1035.py", "repo_name": "nightman413/e-commerce", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1 on 2020-08-09 10:35\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('home', '0004_contactforwmessage'),\n ]\n\n operations = [\n migrations.RenameModel(\n old_name='ContactForwMessage',\n new_name='ContactFormMessage',\n ),\n ]\n" }, { "alpha_fraction": 0.6583101153373718, "alphanum_fraction": 0.6713091731071472, "avg_line_length": 35.423728942871094, "blob_id": "27878c6fc6002683fff886765b7405b3aeb54369", "content_id": "37a61dbe69c356c71420fd60511131eb6eda8eb1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2156, "license_type": "no_license", "max_line_length": 112, "num_lines": 59, "path": "/product/models.py", "repo_name": "nightman413/e-commerce", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.utils import safestring\n\n# Create your models here.\nfrom ckeditor_uploader.fields import RichTextUploadingField\n\n\nclass Category(models.Model):\n STATUS = (\n ('True', 'Evet'),\n ('False', 'Hayır'),\n )\n title = models.CharField(max_length=200)\n keywords = models.CharField(max_length=200)\n description = models.CharField(max_length=200)\n image = models.ImageField(blank=True, upload_to='images/')\n status = models.CharField(max_length=10, choices=STATUS)\n slug = models.SlugField()\n parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE)\n create_at = models.DateTimeField(auto_now_add=True)\n update_at = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return self.title\n\nclass Product(models.Model):\n STATUS = (\n ('True', 'Evet'),\n ('False', 'Hayır'),\n )\n category = models.ForeignKey(Category, on_delete=models.CASCADE) # relation with category table \n title = models.CharField(max_length=100)\n keywords = models.CharField(max_length=255)\n description = models.CharField(max_length=255)\n image = models.ImageField(blank=True, upload_to='images/')\n price = models.FloatField()\n amount = models.IntegerField()\n detail = RichTextUploadingField()\n status = models.CharField(max_length=10, choices=STATUS)\n create_at = models.DateTimeField(auto_now_add=True)\n update_at = models.DateTimeField(auto_now=True) \n \n def image_tag(self):\n return safestring.mark_safe('<img src=\"{}\" height=\"50\"/> '.format(self.image.url))\n image_tag.short_description = 'Image'\n \n def __str__(self):\n return self.title\n\nclass Images(models.Model):\n product = models.ForeignKey(Product, on_delete=models.CASCADE)\n title = models.CharField(max_length=50)\n image = models.ImageField(blank=True, upload_to='images/')\n def __str__(self):\n return self.title\n \n def image_tag(self):\n return safestring.mark_safe('<img src=\"{}\" height=\"50\"/> '.format(self.image.url))\n image_tag.short_description = 'Image'\n \n" }, { "alpha_fraction": 0.7752161622047424, "alphanum_fraction": 0.7752161622047424, "avg_line_length": 23.85714340209961, "blob_id": "5780e89dca05ebbb1efaf1f49c2ce260eedc0ded", "content_id": "2ac583305f8bf03bb25764325bc07f7c196f2b15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 347, "license_type": "no_license", "max_line_length": 63, "num_lines": 14, "path": "/home/admin.py", "repo_name": "nightman413/e-commerce", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\n \n# Register your models here.\nfrom home.models import ContactFormMessage, Setting\n\n\n\nclass ContactFormMessageAdmin(admin.ModelAdmin):\n list_display= ['name', 'email', 'subject', 'status']\n list_filter= ['status']\n\nadmin.site.register(ContactFormMessage,ContactFormMessageAdmin)\nadmin.site.register(Setting)" } ]
5
docopeland/python-coursera
https://github.com/docopeland/python-coursera
193a04a378e0f7cdbd1ede92242d9b1c24183722
c791505f20acc605e4284200f716cc18fbfd729c
86e69ced64d8f3566b55ae4e3218dbf5fd85fe0c
refs/heads/docopeland
2023-02-26T10:57:09.573059
2021-02-04T16:56:42
2021-02-04T16:56:42
323,247,529
0
0
null
2020-12-21T06:14:00
2020-12-24T17:44:48
2020-12-25T04:31:29
Python
[ { "alpha_fraction": 0.6954813599586487, "alphanum_fraction": 0.7072691321372986, "avg_line_length": 36.703704833984375, "blob_id": "633636630743f096afb6b37e08eacd241f8d5b8b", "content_id": "ddecd422e3936f30b48b3aa9be0d1704b16d69e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1018, "license_type": "no_license", "max_line_length": 118, "num_lines": 27, "path": "/PythonForEverybody/course2/CH7.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# assignment 7.1\n# Write a program that prompts for a file name, then opens that file and reads through the file, and print the\n# contents of the file in upper case.\n\n# Use words.txt as the file name\nfname = input(\"Enter file name: \")\nfh = open(fname)\nfor line in fh:\n print(line.upper().rstrip())\n\n# assignment 7.2\n# Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of\n# the form: X-DSPAM-Confidence: 0.8475\n# Count these lines and extract the floating point values from each of the lines and compute the average of those\n# values and produce an output as shown below. Do not use the sum() function or a variable named sum in your solution.\n\nfname = input(\"Enter file name: \")\nfOpen = open(fname)\ncount = 0\nvalues = 0\nfor line in fOpen:\n if line.startswith(\"X-DSPAM-Confidence\"):\n count = count + 1\n values = values + float(line[line.find(\" \"):].strip())\n else:\n continue\nprint(\"Average spam confidence:\", values/count)\n" }, { "alpha_fraction": 0.7154695987701416, "alphanum_fraction": 0.7237569093704224, "avg_line_length": 44.25, "blob_id": "e79382852fa8a31bb1a3ac772a22b285ea4eebb3", "content_id": "ed266670231db9f33922590d4f185c1fb97c568e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 724, "license_type": "no_license", "max_line_length": 115, "num_lines": 16, "path": "/PythonForEverybody/course3/CH11.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# Finding Numbers in a Haystack\n# In this assignment you will read through and parse a file with text and numbers. You will extract all the numbers\n# in the file and compute the sum of the numbers.\n# Handling The Data\n# The basic outline of this problem is to read the file, look for integers using the re.findall(), looking for a\n# regular expression of '[0-9]+' and then converting the extracted strings to integers and summing up the integers.\n\nimport re\nfName = input(\"Enter file name: \")\nfHandle = open(fName)\nnums = list()\nfor line in fHandle:\n if re.search('[0-9]+',line.rstrip()):\n nums.append(re.findall('[0-9]+',line.rstrip()))\nfinal = [int(val) for sublist in nums for val in sublist]\nprint(sum(final))\n" }, { "alpha_fraction": 0.6613546013832092, "alphanum_fraction": 0.7250996232032776, "avg_line_length": 30.5, "blob_id": "33992dbcb1a48fe06f8675a2636c4fe8133ef570", "content_id": "720a731d8a79b23754adf15f1167a8b1bbed7eea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 251, "license_type": "no_license", "max_line_length": 84, "num_lines": 8, "path": "/Python3Programming/course1/CH04.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# Use a for statement to print 10 random numbers.\nimport random\nfor _ in range(10):\n print(random.random())\n\n# Repeat the above exercise but this time print 10 random numbers between 25 and 35.\nfor _ in range(10):\n print(random.randrange(25,35))" }, { "alpha_fraction": 0.658349335193634, "alphanum_fraction": 0.6802303194999695, "avg_line_length": 45.53571319580078, "blob_id": "709ed664fa4193cdcda0d33998ea3c418868574e", "content_id": "446c3a17e10440101c2749f637c0208ae51d6463", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2605, "license_type": "no_license", "max_line_length": 120, "num_lines": 56, "path": "/Python3Programming/course5/project.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# The Assignment\n# Take a ZIP file of images and process them, using a library built into python that you need to learn how to use. A ZIP\n# file takes several different files and compresses them, thus saving space, into one single file. The files in the ZIP\n# file we provide are newspaper images (like you saw in week 3). Your task is to write python code which allows one to\n# search through the images looking for the occurrences of keywords and faces. E.g. if you search for \"pizza\" it will\n# return a contact sheet of all of the faces which were located on the newspaper page which mentions \"pizza\". This will\n# test your ability to learn a new (library), your ability to use OpenCV to detect faces, your ability to use tesseract\n# to do optical character recognition, and your ability to use PIL to composite images together into contact sheets.\n#\n# Each page of the newspapers is saved as a single PNG image in a file called images.zip. These newspapers are in\n# english, and contain a variety of stories, advertisements and images. Note: This file is fairly large (~200 MB) and\n# may take some time to work with, I would encourage you to use small_img.zip for testing.\n\nimport zipfile\n\nfrom PIL import Image\nimport pytesseract\nimport cv2 as cv\n\n# loading the face detection classifier\nface_cascade = cv.CascadeClassifier('readonly/haarcascade_frontalface_default.xml')\n\n# the rest is up to you!\ndef faceCrop(image):\n gray = cv.cvtColor(image,cv.COLOR_RGB2GRAY)\n faces = face_cascade.detectMultiScale(gray,1.35)\n pilImg = Image.fromarray(gray)\n return [pilImg.crop((face[0],face[1],face[0]+face[2],face[1]+face[3])) for face in faces]\n\ndef showFace(faces):\n if len(faces) < 1:\n print(\"But there were no faces in that file!\")\n elif len(faces) > 5:\n facepage = Image.new(\"L\",(500,200))\n for i in range(len(faces)):\n faces[i] = faces[i].resize((100,100),Image.NEAREST)\n if i < 5:\n facepage.paste(faces[i],(i*100,0))\n else:\n facepage.paste(faces[i],((i-5)*100,100))\n else:\n facepage = Image.new(\"L\",(500,100))\n for i in range(len(faces)):\n faces[i] = faces[i].resize((100,100),Image.NEAREST)\n facepage.paste(faces[i],(i*100,0))\n facepage.show()\n\ndef search(word,zipf):\n zip = zipfile.ZipFile(zipf,\"r\")\n for name in zip.namelist():\n if word in pytesseract.image_to_string(name):\n print(\"Results found in file {}\".format(name))\n image = cv.imread(name)\n showFace(faceCrop(image))\n else:\n continue" }, { "alpha_fraction": 0.6638951301574707, "alphanum_fraction": 0.6961944103240967, "avg_line_length": 50.278690338134766, "blob_id": "03aec2f6b2fa2379e8566e7727b17c0308ec7dcd", "content_id": "528720a2989f1631c76c208c761c8684209c557a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3149, "license_type": "no_license", "max_line_length": 120, "num_lines": 61, "path": "/Python3Programming/course1/overall.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# Below are a set of scores that students have received in the past semester. Write code to determine how many are 90\n# or above and assign that result to the value a_scores.\nscores = \"67 80 90 78 93 20 79 89 96 97 92 88 79 68 58 90 98 100 79 74 83 88 80 86 85 70 90 100\"\nscores = scores.split()\na_scores = 0\nfor score in scores:\n if int(score) >= 90:\n a_scores += 1\nprint(a_scores)\n\n# Write code that uses the string stored in org and creates an acronym which is assigned to the variable acro. Only\n# the first letter of each word should be used, each letter in the acronym should be a capital letter, and there\n# should be nothing to separate the letters of the acronym. Words that should not be included in the acronym are\n# stored in the list stopwords. For example, if org was assigned the string “hello to world” then the resulting\n# acronym should be “HW”.\nstopwords = ['to', 'a', 'for', 'by', 'an', 'am', 'the', 'so', 'it', 'and', \"The\"]\norg = \"The organization for health, safety, and education\"\norg = org.split()\nacro = \"\"\nfor word in org:\n if word.lower() not in stopwords:\n acro = acro + word[0].upper()\nprint(acro)\n\n# Write code that uses the string stored in sent and creates an acronym which is assigned to the variable acro. The\n# first two letters of each word should be used, each letter in the acronym should be a capital letter, and each\n# element of the acronym should be separated by a “. ” (dot and space). Words that should not be included in the\n# acronym are stored in the list stopwords. For example, if sent was assigned the string “height and ewok wonder” then\n# the resulting acronym should be “HE. EW. WO”.\nstopwords = ['to', 'a', 'for', 'by', 'an', 'am', 'the', 'so', 'it', 'and', 'The']\nsent = \"The water earth and air are vital\"\nsent = sent.split()\nacro = []\nfor word in sent:\n if word.lower() not in stopwords:\n acro.append(word[0:2].upper())\nacro = \". \".join(acro)\nprint(acro)\n\n# A palindrome is a phrase that, if reversed, would read the exact same. Write code that checks if p_phrase is a\n# palindrome by reversing it and then checking if the reversed version is equal to the original. Assign the reversed\n# version of p_phrase to the variable r_phrase so that we can check your work.\np_phrase = \"was it a car or a cat I saw\"\np_phrase = list(p_phrase.replace(\" \",\"\").lower())\nr_phrase = []\nfor i in range(len(p_phrase),0,-1):\n r_phrase.append(p_phrase[i-1])\nif p_phrase == r_phrase:\n print(True)\n\n# Provided is a list of data about a store’s inventory where each item in the list represents the name of an item, how\n# much is in stock, and how much it costs. Print out each item in the list with the same formatting, using the .format\n# method (not string concatenation). For example, the first print statement should read The store has 12 shoes, each for\n# 29.99 USD.\ninventory = [\"shoes, 12, 29.99\", \"shirts, 20, 9.99\", \"sweatpants, 25, 15.00\", \"scarves, 13, 7.75\"]\nfor item in inventory:\n item = item.split(\", \")\n name = item[0]\n stock = item[1]\n cost = item[2]\n print(\"The store has {} {}, each for {} USD.\".format(stock, name, cost))" }, { "alpha_fraction": 0.7115710973739624, "alphanum_fraction": 0.733627438545227, "avg_line_length": 49.82758712768555, "blob_id": "69512d0df3c1046c8301bdec2103c5cc2e81def6", "content_id": "32e1ac4df5f0a128bbcdf21e9c21dfb80d2b6153", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2947, "license_type": "no_license", "max_line_length": 119, "num_lines": 58, "path": "/Python3Programming/course1/CH02.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# Challenge: Many people keep time using a 24 hour clock (11 is 11am and 23 is 11pm, 0 is midnight). If it is currently\n# 13 and you set your alarm to go off in 50 hours, it will be 15 (3pm). Write a Python program to solve the general\n# version of the above problem. Ask the user for the time now (in hours), and then ask for the number of hours to wait\n# for the alarm. Your program should output what the time will be on the clock when the alarm goes off.\ntimeNow = input(\"What time is it now?\")\ntimeThen = (int(timeNow) + 50) % 24\nprint(timeThen)\n\n# It is possible to name the days 0 thru 6 where day 0 is Sunday and day 6 is Saturday. If you go on a wonderful\n# holiday leaving on day number 3 (a Wednesday) and you return home after 10 nights you would return home on a\n# Saturday (day 6). Write a general version of the program which asks for the starting day number, and the length of\n# your stay, and it will tell you the number of day of the week you will return on.\ndayLeave = input(\"What day did you leave?\")\nlenofStay = input(\"How long was your stay?\")\ndayReturn = (int(dayLeave) + int(lenofStay)) % 7\nprint(dayReturn)\n\n# Write a Python program that assigns the principal amount of 10000 to variable P, assign to n the value 12, and assign\n# to r the interest rate of 8% (0.08). Then have the program prompt the user for the number of years, t, that the money\n# will be compounded for. Calculate and print the final amount after t years.\nP = 10000\nn = 12\nr = 0.08\nt = input(\"Number of years?\")\nA = P*(1 + (r/n))**(n*int(t))\nprint(A)\n\n# Write a program that will compute the area of a circle. Prompt the user to enter the radius and save it to a variable\n# called radius. Print a nice message back to the user with the answer.\npi = 3.14\nradius = input(\"Radius of circle?\")\narea = pi * int(radius)**2\nprint(area)\n\n# Challenge: Write a program that will compute the area of a rectangle. Prompt the user to enter the width and height\n# of the rectangle and store the values in variables called width and height. Print a nice message with the answer..\nwidth = input(\"width of rectangle \")\nheight = input(\"height of rectangle \")\narea = int(height) * int(width)\nprint(area)\n\n# Write a program that will compute MPG for a car. Prompt the user to enter the number of miles driven and the number\n# of gallons used. Print a nice message with the answer.\nmiles = input(\"miles driven\")\ngallons = input(\"gallons used\")\nmpg = int(miles) / int(gallons)\nprint(mpg)\n\n# Challenge: Write a program that will convert degrees celsius to degrees fahrenheit.\ndegC = input(\"degrees in Celsius\")\ndegF = int(degC) * (9 / 5) + 32\nprint(degF)\n\n# Ask the user for the temperature in Fahrenheit and store it in a variable call deg_f. Calculate the equivalent\n# temperature in degrees Celsius and store it in def_c. Output a message to the user giving the temperature in Celsius.\ndeg_f = input(\"degrees in Farenheit\")\ndeg_c = (int(deg_f) - 32) * (5 / 9)\nprint(deg_c)" }, { "alpha_fraction": 0.6776447296142578, "alphanum_fraction": 0.7025948166847229, "avg_line_length": 49.099998474121094, "blob_id": "56d5d85391b6fa1fc66d75d1f11d8fc4b2a7254b", "content_id": "f6b75b706ce11febf4783010936fd0e15518abec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1002, "license_type": "no_license", "max_line_length": 118, "num_lines": 20, "path": "/PythonForEverybody/course1/CH4.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# assignment 4.6\n# Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay should be the\n# normal rate for hours up to 40 and time-and-a-half for the hourly rate for all hours worked above 40 hours. Put the\n# logic to do the computation of pay in a function called computepay() and use the function to do the computation.\n# The function should return a value. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be\n# 498.75). You should use input to read a string and float() to convert the string to a number. Do not worry about\n# error checking the user input unless you want to - you can assume the user types numbers properly. Do not name your\n# variable sum or use the sum() function.\ndef computepay(h, r):\n h = float(h)\n r = float(r)\n if h <= 40:\n return h*r\n else:\n return 40*r + (h - 40)*(1.5*r)\n\nhrs = input(\"Enter Hours: \")\nrate = input(\"Enter Rate: \")\np = computepay(hrs, rate)\nprint(\"Pay\", p)\n" }, { "alpha_fraction": 0.7528089880943298, "alphanum_fraction": 0.7574906349182129, "avg_line_length": 53.769229888916016, "blob_id": "8dc6cdf7d0cffecb9a2c94e06b3fba0cd4e8a952", "content_id": "94d4c69b9454526c7fd43085ffc1b89d37c04af4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2136, "license_type": "no_license", "max_line_length": 118, "num_lines": 39, "path": "/PythonForEverybody/course3/CH13-03.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# Calling a JSON API\n# The program will prompt for a location, contact a web service and retrieve JSON for the web service and parse that\n# data, and retrieve the first place_id from the JSON. A place ID is a textual identifier that uniquely identifies a\n# place as within Google Maps.\n#\n# API End Points\n# To complete this assignment, you should use this API endpoint that has a static subset of the Google Data:\n# http://py4e-data.dr-chuck.net/json?\n# This API uses the same parameter (address) as the Google API. This API also has no rate limit so you can test as\n# often as you like. If you visit the URL with no parameters, you get \"No address...\" response.\n# To call the API, you need to include a key= parameter and provide the address that you are requesting as the\n# address= parameter that is properly URL encoded using the urllib.parse.urlencode() function\n#\n# Make sure to check that your code is using the API endpoint is as shown above. You will get different results from\n# the geojson and json endpoints so make sure you are using the same end point as this autograder is using.\n#\n# Test Data / Sample Execution\n# You can test to see if your program is working with a location of \"South Federal University\" which will have a place\n# id of \"ChIJJ2MNmPl_bIcRt8t5x-X5ZhQ\".\n#\n# Please run your program to find the place_id for this location:\n# Indian Institute of Technology Kharagpur India\n# Make sure to enter the name and case exactly as above and enter the place_id and your Python code below.\n# Hint: The first seven characters of the place_id are \"ChIJR1V ...\"\n# Make sure to retrieve the data from the URL specified above and not the normal Google API. Your program should work\n# with the Google API - but the place_id may not match for this assignment.\n\nimport urllib.request, urllib.parse, urllib.error\nimport json\n\naddress = input(\"Enter location: \")\nparam = dict()\nparam[\"address\"] = address\nparam[\"key\"] = 42\nservice = \"http://py4e-data.dr-chuck.net/json?\"\nurl = service + urllib.parse.urlencode(param)\ndata = urllib.request.urlopen(url).read().decode()\njs = json.loads(data)\nprint(js[\"results\"][0][\"place_id\"])\n" }, { "alpha_fraction": 0.7980769276618958, "alphanum_fraction": 0.7980769276618958, "avg_line_length": 103, "blob_id": "cfca28bcdd9f1890d5b04f7fc0e641c411b0164c", "content_id": "ca78c153ee7013ee1cf7b48ad9153a4be2db6c72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 104, "license_type": "no_license", "max_line_length": 103, "num_lines": 1, "path": "/PythonForEverybody/course3/README.md", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "this is the work that I did for the third course of the specialization: Using Python to Access Web Data\n" }, { "alpha_fraction": 0.6222062110900879, "alphanum_fraction": 0.666907012462616, "avg_line_length": 36.486488342285156, "blob_id": "773d55898ef36fa9b9ee561fbdd4325c4afe4679", "content_id": "0eea545675188f8d28c9f1bb6f0fed7637d99822", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1387, "license_type": "no_license", "max_line_length": 120, "num_lines": 37, "path": "/PythonForEverybody/course1/CH3.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# assignment 3.1\n# Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay the hourly\n# rate for the hours up to 40 and 1.5 times the hourly rate for all hours worked above 40 hours. Use 45 hours and a\n# rate of 10.50 per hour to test the program (the pay should be 498.75). You should use input to read a string and\n# float() to convert the string to a number. Do not worry about error checking the user input - assume the user types\n# numbers properly\nhrs = input(\"Enter Hours: \")\nrate = input(\"Enter Rate: \")\nif float(hrs) <= 40:\n print(float(hrs) * float(rate))\nelse:\n print((40 * float(rate)) + (float(hrs) - 40)*float(rate)*1.5)\n\n# assignment 3.3\n# Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error.\n# If the score is between 0.0 and 1.0, print a grade using the following table:\n# Score Grade\n# >= 0.9 A\n# >= 0.8 B\n# >= 0.7 C\n# >= 0.6 D\n# < 0.6 F\n# If the user enters a value out of range, print a suitable error message and exit. For the test, enter a score of 0.85.\nscore = input(\"Enter Score: \")\nif float(score) < 0.0 or float(score) > 1.0:\n print(\"score is out of range\")\n quit()\nelif float(score) >= 0.9:\n print(\"A\")\nelif float(score) >= 0.8:\n print(\"B\")\nelif float(score) >= 0.7:\n print(\"C\")\nelif float(score) >= 0.6:\n print(\"D\")\nelse:\n print(\"F\")\n" }, { "alpha_fraction": 0.7284041047096252, "alphanum_fraction": 0.7423133254051208, "avg_line_length": 49.62963104248047, "blob_id": "1d5671f37776e6e40539656732d9da1426c8c09b", "content_id": "1d89dcacaff2d33507f4435edca1fbedaafefa9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1366, "license_type": "no_license", "max_line_length": 117, "num_lines": 27, "path": "/PythonForEverybody/course3/CH13-01.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# Extracting Data from XML\n# The program will prompt for a URL, read the XML data from that URL using urllib and then parse and extract the\n# comment counts from the XML data, compute the sum of the numbers in the file.\n#\n# Data Format and Approach\n# The data consists of a number of names and comment counts in XML as follows:\n# <comment>\n# <name>Matthias</name>\n# <count>97</count>\n# </comment>\n# You are to look through all the <comment> tags and find the <count> values sum the numbers. The closest sample code\n# that shows how to parse XML is geoxml.py. But since the nesting of the elements in our data is different than the\n# data we are parsing in that sample code you will have to make real changes to the code.\n# To make the code a little simpler, you can use an XPath selector string to look through the entire tree of XML for\n# any tag named 'count' with the following line of code: counts = tree.findall('.//count')\n# Sample data: http://py4e-data.dr-chuck.net/comments_42.xml (Sum=2553)\n# Actual data: http://py4e-data.dr-chuck.net/comments_1109155.xml (Sum ends with 62)\n\nimport xml.etree.ElementTree as ET\nimport urllib.request, urllib.parse, urllib.error\n\nurl = input(\"Enter URL: \")\nhtml = urllib.request.urlopen(url).read()\ntree = ET.fromstring(html)\ncounts = tree.findall('.//count')\nval = [int(count.text) for count in counts]\nprint(sum(val))" }, { "alpha_fraction": 0.6508795619010925, "alphanum_fraction": 0.6792963743209839, "avg_line_length": 37.894737243652344, "blob_id": "0f5f6b68bf8a65c0db8bd8fea04bc8d7dd16f070", "content_id": "d409fb85a36a6c193d00e02ddd67fa36fc9c516e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 739, "license_type": "no_license", "max_line_length": 115, "num_lines": 19, "path": "/PythonForEverybody/course2/CH10.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# assignment 10.2\n# Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of\n# the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a\n# second time using a colon.\n# From [email protected] Sat Jan 5 09:14:16 2008\n# Once you have accumulated the counts for each hour, print out the counts, sorted by hour.\n\nfName = input(\"Enter file: \")\nif len(fName) < 1:\n fName = \"mbox-short.txt\"\nfHandle = open(fName)\nhours = dict()\nfor line in fHandle:\n if line.strip().startswith(\"From \"):\n hours[line.split()[5][:2]] = hours.get(line.split()[5][:2],0) + 1\n else:\n continue\nfor k,v in sorted(hours.items()):\n print(k,v)\n" }, { "alpha_fraction": 0.607594907283783, "alphanum_fraction": 0.6398158669471741, "avg_line_length": 28, "blob_id": "127ff94bc61cbfe6e194331fa62348a2ce8235cb", "content_id": "3b99410e03252ac1bf0b657333e8f79fa73b6ec2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 869, "license_type": "no_license", "max_line_length": 118, "num_lines": 30, "path": "/Python3Programming/course1/CH05.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# Write a program that prints We like Python's turtles! 10 times.\nfor _ in range(10):\n print(\"We like Python's turtles!\")\n\n# Use for loops to make a turtle draw regular polygons (regular means all sides the same lengths, all angles the same)\nimport turtle\nback = turtle.Screen()\nlil = turtle.Turtle()\nshape = input(\"What shape should lil turtle draw?\")\n# triangle\nif shape == \"triangle\":\n for _ in range(3):\n lil.forward(100)\n lil.right(120)\nif shape == \"square\":\n for _ in range(4):\n lil.forward(100)\n lil.right(90)\nif shape == \"hexagon\":\n for _ in range(6):\n lil.forward(100)\n lil.right(60)\nif shape == \"octagon\":\n for _ in range(8):\n lil.forward(50)\n lil.right(45)\n\n# Create a turtle and assign it to a variable. When you print its type, what do you get?\nturt = turtle.Turtle()\nprint(type(turt))" }, { "alpha_fraction": 0.686693012714386, "alphanum_fraction": 0.6985507011413574, "avg_line_length": 55.656715393066406, "blob_id": "9bf54087666ac6011f1231efaeb8c16dfe5a3422", "content_id": "c7df5e483cfbd09b1bba8243a58c15be56d40430", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3801, "license_type": "no_license", "max_line_length": 120, "num_lines": 67, "path": "/Python3Programming/course2/CH15.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# Create a function called mult that has two parameters, the first is required and should be an integer, the second is\n# an optional parameter that can either be a number or a string but whose default is 6. The function should return the\n# first parameter multiplied by the second.\ndef mult(num, opt=6):\n return num*opt\n\n# The following function, greeting, does not work. Please fix the code so that it runs without error. This only requires\n# one change in the definition of the function.\ndef greeting(name, greeting=\"Hello \", excl=\"!\"):\n return greeting + name + excl\n\nprint(greeting(\"Bob\"))\nprint(greeting(\"\"))\nprint(greeting(\"Bob\", excl=\"!!!\"))\n\n# Below is a function, sum, that does not work. Change the function definition so the code works. The function should\n# still have a required parameter, intx, and an optional parameter, intz with a defualt value of 5.\ndef sum(intx, intz=5):\n return intz + intx\n\n# Write a function, test, that takes in three parameters: a required integer, an optional boolean whose default value is\n# True, and an optional dictionary, called dict1, whose default value is {2:3, 4:5, 6:8}. If the boolean parameter is\n# True, the function should test to see if the integer is a key in the dictionary. The value of that key should then be\n# returned. If the boolean parameter is False, return the boolean value “False”.\ndef test(num, booly=True, dict1={2:3, 4:5, 6:8}):\n if booly is True:\n return dict1.get(num)\n else:\n return False\n\n# Write a function called checkingIfIn that takes three parameters. The first is a required parameter, which should be\n# a string. The second is an optional parameter called direction with a default value of True. The third is an optional\n# parameter called d that has a default value of {'apple': 2, 'pear': 1, 'fruit': 19, 'orange': 5, 'banana': 3,\n# 'grapes': 2, 'watermelon': 7}. Write the function checkingIfIn so that when the second parameter is True, it checks to\n# see if the first parameter is a key in the third parameter; if it is, return True, otherwise return False.\n# But if the second parameter is False, then the function should check to see if the first parameter is not a key of the\n# third. If it’s not, the function should return True in this case, and if it is, it should return False.\ndef checkingIfIn(string, direction=True, d={'apple': 2, 'pear': 1, 'fruit': 19, 'orange': 5, 'banana': 3, 'grapes': 2,\n 'watermelon': 7}):\n if direction is True:\n return string in d\n else:\n return string not in d\n\n# We have provided the function checkingIfIn such that if the first input parameter is in the third, dictionary, input\n# parameter, then the function returns that value, and otherwise, it returns False. Follow the instructions in the\n# active code window for specific variable assignmemts.\ndef checkingIfIn(a, direction = True, d = {'apple': 2, 'pear': 1, 'fruit': 19, 'orange': 5, 'banana': 3, 'grapes': 2,\n 'watermelon': 7}):\n if direction == True:\n if a in d:\n return d[a]\n else:\n return False\n else:\n if a not in d:\n return True\n else:\n return d[a]\n# Call the function so that it returns False and assign that function call to the variable c_false\nc_false = checkingIfIn(\"mango\")\n# Call the fucntion so that it returns True and assign it to the variable c_true\nc_true = checkingIfIn(\"mango\",False)\n# Call the function so that the value of fruit is assigned to the variable fruit_ans\nfruit_ans = checkingIfIn(\"fruit\")\n# Call the function using the first and third parameter so that the value 8 is assigned to the variable param_check\nparam_check = checkingIfIn(\"pineapple\", d={\"pineapple\":8})" }, { "alpha_fraction": 0.6559703350067139, "alphanum_fraction": 0.6925338506698608, "avg_line_length": 52.951725006103516, "blob_id": "e7a7dd00f0377a30098201779e43d5c034537838", "content_id": "ccfdcc8cf00f64349db2bd7a9eaaa212529631b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7840, "license_type": "no_license", "max_line_length": 120, "num_lines": 145, "path": "/Python3Programming/course2/CH11.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# At the halfway point during the Rio Olympics, the United States had 70 medals, Great Britain had 38 medals, China had\n# 45 medals, Russia had 30 medals, and Germany had 17 medals. Create a dictionary assigned to the variable medal_count\n# with the country names as the keys and the number of medals the country had as each key’s value.\nmedal_count = {'United States':70, 'Great Britan':38, 'China':45, 'Russia':30,'Germany':17}\nprint(medal_count)\n\n# Given the dictionary swimmers, add an additional key-value pair to the dictionary with \"Phelps\" as the key and the\n# integer 23 as the value. Do not rewrite the entire dictionary.\nswimmers = {'Manuel':4, 'Lochte':12, 'Adrian':7, 'Ledecky':5, 'Dirado':4}\nswimmers[\"Phelps\"]=23\nprint(swimmers)\n\n# Add the string “hockey” as a key to the dictionary sports_periods and assign it the value of 3. Do not rewrite the\n# entire dictionary.\nsports_periods = {'baseball': 9, 'basketball': 4, 'soccer': 4, 'cricket': 2}\nsports_periods[\"hockey\"]=3\nprint(sports_periods)\n\n# The dictionary golds contains information about how many gold medals each country won in the 2016 Olympics. But today,\n# Spain won 2 more gold medals. Update golds to reflect this information.\ngolds = {\"Italy\": 12, \"USA\": 33, \"Brazil\": 15, \"China\": 27, \"Spain\": 19, \"Canada\": 22, \"Argentina\": 8, \"England\": 29}\ngolds[\"Spain\"] = golds[\"Spain\"] + 2\nprint(golds)\n\n# Create a list of the countries that are in the dictionary golds, and assign that list to the variable name countries.\n# Do not hard code this.\ngolds = {\"Italy\": 12, \"USA\": 33, \"Brazil\": 15, \"China\": 27, \"Spain\": 19, \"Canada\": 22, \"Argentina\": 8, \"England\": 29}\ncountries = golds.keys()\nprint(countries)\n\n# Provided is the dictionary, medal_count, which lists countries and their respective medal count at the halfway point\n# in the 2016 Rio Olympics. Using dictionary mechanics, assign the medal count value for \"Belarus\" to the variable\n# belarus. Do not hardcode this.\nmedal_count = {'United States': 70, 'Great Britain':38, 'China':45, 'Russia':30, 'Germany':17, 'Italy':22, 'France': 22,\n 'Japan':26, 'Australia':22, 'South Korea':14, 'Hungary':12, 'Netherlands':10, 'Spain':5, 'New Zealand':8,\n 'Canada':13, 'Kazakhstan':8, 'Colombia':4, 'Switzerland':5, 'Belgium':4, 'Thailand':4, 'Croatia':3,\n 'Iran':3, 'Jamaica':3, 'South Africa':7, 'Sweden':6, 'Denmark':7, 'North Korea':6, 'Kenya':4, 'Brazil':7,\n 'Belarus':4, 'Cuba':5, 'Poland':4, 'Romania':4, 'Slovenia':3, 'Argentina':2, 'Bahrain':2, 'Slovakia':2,\n 'Vietnam':2, 'Czech Republic':6, 'Uzbekistan':5}\nbelarus = medal_count[\"Belarus\"]\nprint(belarus)\n\n# The dictionary total_golds contains the total number of gold medals that countries have won over the course of\n# history. Use dictionary mechanics to find the number of golds Chile has won, and assign that number to the variable\n# name chile_golds. Do not hard code this!\ntotal_golds = {\"Italy\": 114, \"Germany\": 782, \"Pakistan\": 10, \"Sweden\": 627, \"USA\": 2681, \"Zimbabwe\": 8, \"Greece\": 111,\n \"Mongolia\": 24, \"Brazil\": 108, \"Croatia\": 34, \"Algeria\": 15, \"Switzerland\": 323, \"Yugoslavia\": 87,\n \"China\": 526, \"Egypt\": 26, \"Norway\": 477, \"Spain\": 133, \"Australia\": 480, \"Slovakia\": 29, \"Canada\": 22,\n \"New Zealand\": 100, \"Denmark\": 180, \"Chile\": 13, \"Argentina\": 70, \"Thailand\": 24, \"Cuba\": 209,\n \"Uganda\": 7, \"England\": 806, \"Denmark\": 180, \"Ukraine\": 122, \"Bahamas\": 12}\nchile_golds = total_golds[\"Chile\"]\nprint(chile_golds)\n\n# Provided is a dictionary called US_medals which has the first 70 metals that the United States has won in 2016, and\n# in which category they have won it in. Using dictionary mechanics, assign the value of the key \"Fencing\" to a\n# variable fencing_value. Remember, do not hard code this.\nUS_medals = {\"Swimming\": 33, \"Gymnastics\": 6, \"Track & Field\": 6, \"Tennis\": 3, \"Judo\": 2, \"Rowing\": 2, \"Shooting\": 3,\n \"Cycling - Road\": 1, \"Fencing\": 4, \"Diving\": 2, \"Archery\": 2, \"Cycling - Track\": 1, \"Equestrian\": 2,\n \"Golf\": 1, \"Weightlifting\": 1}\nfencing_value = US_medals[\"Fencing\"]\nprint(fencing_value)\n\n# The dictionary Junior shows a schedule for a junior year semester. The key is the course name and the value is the\n# number of credits. Find the total number of credits taken this semester and assign it to the variable credits.\nJunior = {'SI 206':4, 'SI 310':4, 'BL 300':3, 'TO 313':3, 'BCOM 350':1, 'MO 300':3}\ncredits = 0\nfor v in Junior.values():\n credits = credits + v\nprint(credits)\n\n# Create a dictionary, freq, that displays each character in string str1 as the key and its frequency as the value.\nstr1 = \"peter piper picked a peck of pickled peppers\"\nfreq = {}\nfor char in str1:\n freq[char] = freq.get(char,0) + 1\nprint(freq)\n\n# Provided is a string saved to the variable name s1. Create a dictionary named counts that contains each letter in s1\n# and the number of times it occurs.\ns1 = \"hello\"\ncounts = {}\nfor char in s1:\n counts[char] = counts.get(char,0) + 1\nprint(counts)\n\n# Create a dictionary, freq_words, that contains each word in string str1 as the key and its frequency as the value.\nstr1 = \"I wish I wish with all my heart to fly with dragons in a land apart\"\nfreq_words = {}\nfor word in str1.split():\n freq_words[word] = freq_words.get(word,0) + 1\nprint(freq_words)\n\n# Create a dictionary called wrd_d from the string sent, so that the key is a word and the value is how many times you\n# have seen that word.\nsent = \"Singing in the rain and playing in the rain are two entirely different situations but both can be good\"\nwrd_d = {}\nfor word in sent.split():\n wrd_d[word] = wrd_d.get(word,0) + 1\nprint(wrd_d)\n\n# Create the dictionary characters that shows each character from the string sally and its frequency. Then, find the\n# most frequent letter based on the dictionary. Assign this letter to the variable best_char.\nsally = \"sally sells sea shells by the sea shore\"\ncharacters = {}\nfor char in sally:\n characters[char] = characters.get(char,0) + 1\nbest_char = \"\"\nmaxval = 0\nfor k,v in characters.items():\n if v > maxval:\n maxval = v\n best_char = k\nprint(best_char)\n\n# Find the least frequent letter. Create the dictionary characters that shows each character from string sally and its\n# frequency. Then, find the least frequent letter in the string and assign the letter to the variable worst_char.\nsally = \"sally sells sea shells by the sea shore and by the road\"\ncharacters = {}\nfor char in sally:\n characters[char] = characters.get(char,0) + 1\nworst_char = \"\"\nminval = 10\nfor k,v in characters.items():\n if v < minval:\n minval = v\n worst_char = k\nprint(worst_char)\n\n# Create a dictionary named letter_counts that contains each letter and the number of times it occurs in string1.\n# Challenge: Letters should not be counted separately as upper-case and lower-case. Instead, all of them should be\n# counted as lower-case.\nstring1 = \"There is a tide in the affairs of men, Which taken at the flood, leads on to fortune. Omitted, all the \" \\\n \"voyage of their life is bound in shallows and in miseries. On such a full sea are we now afloat. And we \" \\\n \"must take the current when it serves, or lose our ventures.\"\nletter_counts = {}\nfor char in string1.lower():\n letter_counts[char] = letter_counts.get(char,0) + 1\n\n# Create a dictionary called low_d that keeps track of all the characters in the string p and notes how many times each\n# character was seen. Make sure that there are no repeats of characters as keys, such that “T” and “t” are both seen as\n# a “t” for example.\np = \"Summer is a great time to go outside. You have to be careful of the sun though because of the heat.\"\nlow_d = {}\nfor char in p.lower():\n low_d[char] = low_d.get(char,0) + 1" }, { "alpha_fraction": 0.7134503126144409, "alphanum_fraction": 0.7407407164573669, "avg_line_length": 38.46154022216797, "blob_id": "b7f9032c84b69a41cb9a1f7d23eb20b5a6354479", "content_id": "ed365d02f5ddd0c0c3cef5d21923ccc841edee9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 513, "license_type": "no_license", "max_line_length": 115, "num_lines": 13, "path": "/PythonForEverybody/course2/CH6.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# assignment 6.5\n# Write code using find() and string slicing (see section 6.10) to extract the number at the end of the line below.\n# Convert the extracted value to a floating point number and print it out.\ntext = \"X-DSPAM-Confidence: 0.8475\"\n# finding the first string occuran e of a space\nspaceNo = text.find(\" \")\n# getting the substring from space to end of string\nnew1 = text[spaceNo:]\n# stripping the string of all whitespaces\nnew2 = new1.strip()\n# making it a float\nnewText = float(new2)\nprint(newText)\n" }, { "alpha_fraction": 0.5689194202423096, "alphanum_fraction": 0.6036655306816101, "avg_line_length": 26.578947067260742, "blob_id": "5684b384ff79749286867c486944e2fc900b616f", "content_id": "0d16c1bf85f80224fbe807a327eb0c2fbbb9b5a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2619, "license_type": "no_license", "max_line_length": 97, "num_lines": 95, "path": "/Python3Programming/course4/CH20-2.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "import unittest\n\n# code provided that i need to write tests for\ndef lr(n): return list(range(n))\n\ndef mySum(a):\n if type(a) is type(''.join([][:])): return a[lr(1)[0]] + mySum(a[1:])\n elif len(a)==len(lr(1)+[]): return a[lr(1)[0]]\n else: return None and a[lr(1)[0]] + mySum(a[1:])\n\nclass Student():\n def __init__(s,a,b=1): s.name,s.years_UM,s.knowledge = ''*200+a+''*100,1,len(lr(0)) + len([])\n def study(s):\n for _ in lr(s.knowledge): s.knowledge = s.knowledge + 1\n def getKnowledge(s):\n for i in lr(s.knowledge): return s.knowledge\n def year_at_umich(s): return s.years_UM\n\n\n# tests for function mySum\nclass TestingmySum(unittest.TestCase):\n def testEmptyList(self):\n self.assertEqual(mySum([]), 0)\n\n def testOneValList(self):\n self.assertEqual(mySum([1]), 1)\n\n def testPosList(self):\n self.assertEqual(mySum([1, 2, 3]), 6)\n\n def testNegList(self):\n self.assertEqual(mySum([-1, -2, -3]), -6)\n\n# tests for class Student\nclass TestingStudent(unittest.TestCase):\n def testS1name(self):\n s1 = Student(\"danielle\")\n self.assertEqual(s1.name,\"danielle\")\n\n def testS1years(self):\n s1 = Student(\"danielle\")\n self.assertEqual(s1.years_UM,1)\n\n def testS1Knowledge(self):\n s1 = Student(\"danielle\")\n self.assertEqual(s1.knowledge,0)\n\n def testS1Study(self):\n s1 = Student(\"danielle\")\n self.assertEqual(s1.study(),None)\n\n def testS1StudyKnowledge(self):\n s1 = Student(\"danielle\")\n s1.study()\n self.assertEqual(s1.knowledge,1)\n\n def testS1GetKnowledge(self):\n s1 = Student(\"danielle\")\n self.assertEqual(s1.getKnowledge(),1)\n\n def testS1YearAtUmich(self):\n s1 = Student(\"danielle\")\n self.assertEqual(s1.year_at_umich(),1)\n\n def testS2name(self):\n s2 = Student(\"emily\",3)\n self.assertEqual(s2.name,\"emily\")\n\n def testS2years(self):\n s2 = Student(\"emily\",3)\n self.assertEqual(s2.years_UM,3)\n\n def testS2Knowledge(self):\n s2 = Student(\"emily\",3)\n self.assertEqual(s2.knowledge,0)\n\n def testS2Study(self):\n s2 = Student(\"emily\",3)\n self.assertEqual(s2.study(),None)\n\n def testS2StudyKnowledge(self):\n s2 = Student(\"emily\",3)\n s2.study()\n self.assertEqual(s2.knowledge,1)\n\n def testS2GetKnowledge(self):\n s2 = Student(\"emily\",3)\n self.assertEqual(s2.getKnowledge(),1)\n\n def testS2YearAtUmich(self):\n s2 = Student(\"emily\",3)\n self.assertEqual(s2.year_at_umich(),3)\n\nif __name__ == \"__main__\":\n unittest.main()" }, { "alpha_fraction": 0.6989189386367798, "alphanum_fraction": 0.7021621465682983, "avg_line_length": 38.36170196533203, "blob_id": "e0fe94fcfeab66966efd5b0ce31e1f487dec6274", "content_id": "78aa41183d2a87efc940121333aaac4f365c2277", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1866, "license_type": "no_license", "max_line_length": 123, "num_lines": 47, "path": "/Python3Programming/course1/CH09.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# Write code to add ‘horseback riding’ to the third position (i.e., right before volleyball) in the list sports.\nsports = ['cricket', 'football', 'volleyball', 'baseball', 'softball', 'track and field', 'curling', 'ping pong', 'hockey']\nsports.insert(2,\"horseback riding\")\nprint(sports)\n\n# Write code to take ‘London’ out of the list trav_dest.\ntrav_dest = ['Beirut', 'Milan', 'Pittsburgh', 'Buenos Aires', 'Nairobi', 'Kathmandu', 'Osaka', 'London', 'Melbourne']\ntrav_dest.remove(\"London\")\nprint(trav_dest)\n\n# Write code to add ‘Guadalajara’ to the end of the list trav_dest using a list method.\ntrav_dest.append(\"Guadalajara\")\nprint(trav_dest)\n\n# Write code to rearrange the strings in the list winners so that they are in alphabetical order from A to Z.\nwinners = ['Kazuo Ishiguro', 'Rainer Weiss', 'Youyou Tu', 'Malala Yousafzai', 'Alice Munro', 'Alvin E. Roth']\nwinners.sort()\nprint(winners)\n\n# Write code to switch the order of the winners list so that it is now Z to A. Assign this list to the variable\n# z_winners.\nwinners.sort(reverse=True)\nz_winners = winners[:]\nprint(z_winners)\n\n# Currently there is a string called str1. Write code to create a list called chars which should contain the characters\n# from str1. Each character in str1 should be its own element in the list chars.\nstr1 = \"I love python\"\nchars = []\nfor cha in str1:\n chars.append(cha)\nprint(chars)\n\n# For each character in the string saved in ael, append that character to a list that should be saved in a variable app.\nael = \"python!\"\napp = []\nfor cha in ael:\n app.append(cha)\nprint(app)\n\n#For each string in wrds, add ‘ed’ to the end of the word (to make the word past tense). Save these past tense words to\n# a list called past_wrds.\nwrds = [\"end\", 'work', \"play\", \"start\", \"walk\", \"look\", \"open\", \"rain\", \"learn\", \"clean\"]\npast_wrds = []\nfor wrd in wrds:\n past_wrds.append(wrd+\"ed\")\nprint(past_wrds)\n" }, { "alpha_fraction": 0.6817108392715454, "alphanum_fraction": 0.6835476160049438, "avg_line_length": 35.653846740722656, "blob_id": "b603bbb1b901f9e2c8a35a456add2b91e164362c", "content_id": "d06b164c5ecb4803d57558cddfcee7832406c143", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3811, "license_type": "no_license", "max_line_length": 117, "num_lines": 104, "path": "/PythonForEverybody/course4/CH15-03.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# Musical Track Database\n# This application will read an iTunes export file in XML and produce a properly normalized database with this\n# structure:\n# CREATE TABLE Artist (\n# id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,\n# name TEXT UNIQUE\n# );\n#\n# CREATE TABLE Genre (\n# id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,\n# name TEXT UNIQUE\n# );\n#\n# CREATE TABLE Album (\n# id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,\n# artist_id INTEGER,\n# title TEXT UNIQUE\n# );\n#\n# CREATE TABLE Track (\n# id INTEGER NOT NULL PRIMARY KEY\n# AUTOINCREMENT UNIQUE,\n# title TEXT UNIQUE,\n# album_id INTEGER,\n# genre_id INTEGER,\n# len INTEGER, rating INTEGER, count INTEGER\n# );\n#\n# For the database that you turn in for this assignment, only use the Library.xml data that is provided.\n#\n# To grade this assignment, the program will run a query like this on your uploaded database and look for the data it\n# expects to see:\n# SELECT Track.title, Artist.name, Album.title, Genre.name\n# FROM Track JOIN Genre JOIN Album JOIN Artist\n# ON Track.genre_id = Genre.ID and Track.album_id = Album.id\n# AND Album.artist_id = Artist.id\n# ORDER BY Artist.name LIMIT 3\n\nimport sqlite3\nimport xml.etree.ElementTree as ET\n\nconn = sqlite3.connect(\"tracks.sqlite\")\ncurr = conn.cursor()\n\n# drop and create tables\ncurr.executescript(\"\"\"\nDROP TABLE IF EXISTS Artist;\nDROP TABLE IF EXISTS Genre;\nDROP TABLE IF EXISTS Album;\nDROP TABLE IF EXISTS Track;\nCREATE TABLE Artist (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, name TEXT UNIQUE);\nCREATE TABLE Genre (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, name TEXT UNIQUE);\nCREATE TABLE Album (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, artist_id INTEGER, title TEXT UNIQUE);\nCREATE TABLE Track (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, title TEXT UNIQUE, album_id INTEGER,\n genre_id INTEGER, len INTEGER, rating INTEGER, count INTEGER)\"\"\")\n\n# get the info out of the file\nxmlName = input(\"Enter XML: \")\nif len(xmlName) < 1: xmlName = \"files/Library.xml\"\ndata = ET.parse(xmlName)\ninfo = data.findall(\"dict/dict/dict\")\n\n# find the correct value from the xml\ndef lookup(d, keyword):\n found = False\n for child in d:\n if found: return child.text\n if child.tag == 'key' and child.text == keyword:\n found = True\n return None\n\n#looping through the entries of the xml\nprint(\"There are\",len(info),\"tracks\")\nfor entry in info:\n if lookup(entry,\"Track ID\") is None: continue\n name = lookup(entry,\"Name\")\n artist = lookup(entry,\"Artist\")\n album = lookup(entry,\"Album\")\n genre = lookup(entry,\"Genre\")\n time = lookup(entry,\"Total Time\")\n count = lookup(entry,\"Play Count\")\n rating = lookup(entry,\"Rating\")\n if name is None or artist is None or album is None or genre is None: continue\n print(name, artist, album, genre, time, count, rating)\n\n # getting artist_id\n curr.execute(\"INSERT OR IGNORE INTO Artist (name) VALUES ( ? )\", (artist,))\n curr.execute(\"SELECT id FROM Artist where name = ?\", (artist,))\n artist_id = curr.fetchone()[0]\n\n # getting genre_id\n curr.execute(\"INSERT OR IGNORE INTO Genre (name) VALUES ( ? )\", (genre,))\n curr.execute(\"SELECT id FROM Genre where name = ?\", (genre,))\n genre_id = curr.fetchone()[0]\n\n # getting album_id\n curr.execute(\"INSERT OR IGNORE INTO Album (title, artist_id) VALUES ( ?, ? )\", (album,artist_id,))\n curr.execute(\"SELECT id FROM Album where title = ?\", (album,))\n album_id = curr.fetchone()[0]\n\n # doing the track\n curr.execute(\"\"\"INSERT OR REPLACE INTO Track (title, album_id, genre_id, len, rating, count)\n VALUES ( ? , ? , ? , ? , ? , ? )\"\"\", (name,album_id,genre_id,time,rating,count,))\nconn.commit()" }, { "alpha_fraction": 0.6261261105537415, "alphanum_fraction": 0.6594594717025757, "avg_line_length": 37.24137878417969, "blob_id": "5c92862e4d6ab66f597ceeca7f8ce680621608c1", "content_id": "b4a12a180dc3669566797034865bf949126bc07b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1112, "license_type": "no_license", "max_line_length": 115, "num_lines": 29, "path": "/Python3Programming/course1/CH07.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# In Robert McCloskey’s book Make Way for Ducklings, the names of the ducklings are Jack, Kack, Lack, Mack, Nack,\n# Ouack, Pack, and Quack. This loop tries to output these names in order.\nprefixes = \"JKLMNOPQ\"\nsuffix = \"ack\"\nfor p in prefixes:\n if (p == \"O\") or (p == \"Q\"):\n suffix = \"uack\"\n print(p + suffix)\n\n# Get the user to enter some text and print it out in reverse order.\ntext = input(\"tell me a word\")\nnewText = \"\"\nfor let in range(len(text),0,-1):\n newText += text[let-1]\nprint(newText)\n\n# Write a program that uses a for loop to print\n# One of the months of the year is January\n# One of the months of the year is February\n# One of the months of the year is March, etc.\nmonths = [\"January\",\"February\",\"March\",\"April\",\"May\",\"June\",\"July\",\"September\",\"October\",\"November\",\"December\"]\nfor i in months:\n print(\"One of the months of the year is \" + i)\n\n# Assume you have a list of numbers 12, 10, 32, 3, 66, 17, 42, 99, 20. Write a loop that prints each number and its\n# square on a new line.\nnumbers = [12, 10, 32, 3, 66, 17, 42, 99, 20]\nfor i in numbers:\n print(\"The square of\",i,\"is\",i*i)\n\n" }, { "alpha_fraction": 0.6834924817085266, "alphanum_fraction": 0.7030468583106995, "avg_line_length": 46.815216064453125, "blob_id": "a1f9f19d1f23d11396931230f9bc0bb0fc4c3b3e", "content_id": "74a59be4002d96f2c09f079bb8333c84c872d7d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4430, "license_type": "no_license", "max_line_length": 121, "num_lines": 92, "path": "/Python3Programming/course1/CH08.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# rainfall_mi is a string that contains the average number of inches of rainfall in Michigan for every month\n# (in inches) with every month separated by a comma. Write code to compute the number of months that have more than\n# 3 inches of rainfall. Store the result in the variable num_rainy_months. In other words, count the number of items\n# with values > 3.0.\nrainfall_mi = \"1.65, 1.46, 2.05, 3.03, 3.35, 3.46, 2.83, 3.23, 3.5, 2.52, 2.8, 1.85\"\nrainfall_mi = rainfall_mi.split(\", \")\nnum_rainy_months = 0\nfor rain in rainfall_mi:\n if float(rain) > 3:\n num_rainy_months += 1\nprint(\"the number of rainy months are\",num_rainy_months)\n\n# The variable sentence stores a string. Write code to determine how many words in sentence start and end with the same\n# letter, including one-letter words. Store the result in the variable same_letter_count.\nsentence = \"students flock to the arb for a variety of outdoor activities such as jogging and picnicking\"\nsentence = sentence.split()\nsame_letter_count = 0\nfor words in sentence:\n if words[0] == words[-1]:\n same_letter_count += 1\nprint(\"the number of words that start and end with the same letter are\",same_letter_count)\n\n# Write code to count the number of strings in list items that have the character w in it. Assign that number to the\n# variable acc_num.\nitems = [\"whirring\", \"wow!\", \"calendar\", \"wry\", \"glass\", \"\", \"llama\",\"tumultuous\",\"owing\"]\nacc_num = 0\nfor item in items:\n if \"w\" in item:\n acc_num += 1\nprint(\"the number of words that have the letter w in it are\",acc_num)\n\n# Write code that counts the number of words in sentence that contain either an “a” or an “e”. Store the result in the\n# variable num_a_or_e.\nsentence = \"python is a high level general purpose programming language that can be applied to many different classes \" \\\n \"of problems.\"\nsentence = sentence.split()\nnum_a_or_e = 0\nfor words in sentence:\n if \"a\" in words or \"e\" in words:\n num_a_or_e += 1\nprint(\"the number of words in the sentence that contain either 'a' or 'e' are\",num_a_or_e)\n\n# Write code that will count the number of vowels in the sentence s and assign the result to the variable num_vowels.\n# For this problem, vowels are only a, e, i, o, and u. Hint: use the in operator with vowels.\ns = \"singing in the rain and playing in the rain are two entirely different situations but both can be fun\"\nvowels = ['a','e','i','o','u']\nnum_vowels = 0\nfor char in s:\n if char in vowels:\n num_vowels += 1\nprint(\"the number of vowels in this sentence are\",num_vowels)\n\n# Create one conditional so that if “Friendly” is in w, then “Friendly is here!” should be assigned to the variable wrd.\n# If it’s not, check if “Friend” is in w. If so, the string “Friend is here!” should be assigned to the variable wrd,\n# otherwise “No variation of friend is in here.” should be assigned to the variable wrd. (Also consider: does the order\n# of your conditional statements matter for this problem? Why?)\nw = \"Friendship is a wonderful human experience!\"\nif \"Friendly\" in w:\n wrd = \"Friendly is here!\"\nelif \"Friend\" in w:\n wrd = \"Friend is here!\"\nelse:\n wrd = \"No variation of friend is in here.\"\nprint(wrd)\n\n# Write code so that if \"STATS 250\" is in the list schedule, then the string \"You could be in Information Science!\" is\n# assigned to the variable resp. Otherwise, the string \"That's too bad.\" should be assigned to the variable resp.\nschedule = [\"SI 106\", \"STATS 250\", \"SI 110\", \"ENGLISH 124/125\"]\nif \"SI 106\" in schedule:\n resp = \"You could be in Information Science!\"\nelse:\n resp = \"That's too bad.\"\nprint(resp)\n\n# Create the variable z whose value is 30. Write code to see if z is greater than y. If so, add 5 to y’s value,\n# otherwise do nothing. Then, multiply z and y, and assign the resulting value to the variable x.\ny = 22\nz = 30\nif z > y:\n y += 5\nx = z * y\nprint(x)\n\n# For each string in wrd_lst, find the number of characters in the string. If the number of characters is less than 6,\n# add 1 to accum so that in the end, accum will contain an integer representing the total number of words in the list\n# that have fewer than 6 characters.\nwrd_lst = [\"Hello\", \"activecode\", \"Java\", \"C#\", \"Python\", \"HTML and CSS\", \"Javascript\", \"Swift\", \"php\"]\naccum = 0\nfor wrd in wrd_lst:\n if len(wrd) < 6:\n accum += 1\nprint(\"the number of words that have fewer than 6 characters are\",accum)" }, { "alpha_fraction": 0.8571428656578064, "alphanum_fraction": 0.8571428656578064, "avg_line_length": 97, "blob_id": "b09e5efa4becf1fe3e4531dc79608caa73d3b8f9", "content_id": "aa87475e1ebe5ed08b9659bc66372fc9c8e9b67e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 98, "license_type": "no_license", "max_line_length": 97, "num_lines": 1, "path": "/README.md", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "This are the assignments that I completed on various coursera specializations dealing with python\n" }, { "alpha_fraction": 0.6994801163673401, "alphanum_fraction": 0.7046791315078735, "avg_line_length": 56.514705657958984, "blob_id": "56c34e56449442690e5b16afd77d9cee11fb842e", "content_id": "5115ea20372c3e04fe29c94a0eed050897eb0a4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11859, "license_type": "no_license", "max_line_length": 120, "num_lines": 204, "path": "/Python3Programming/course4/projectdesc.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# This project will take you through the process of implementing a simplified version of the game Wheel of Fortune. Here\n# are the rules of our game:\n# There are num_human human players and num_computer computer players.\n# Every player has some amount of money ($0 at the start of the game)\n# Every player has a set of prizes (none at the start of the game)\n# The goal is to guess a phrase within a category. For example:\n# Category: Artist & Song | Phrase: Whitney Houston’s I Will Always Love You\n# Players see the category and an obscured version of the phrase where every alphanumeric character in the phrase starts\n# out as hidden (using underscores: _):\n# Category: Artist & Song | Phrase: _______ _______'_ _ ____ ______ ____ ___\n# Note that case (capitalization) does not matter\n# During their turn, every player spins the wheel to determine a prize amount and:\n# If the wheel lands on a cash square, players may do one of three actions:\n# Guess any letter that hasn't been guessed by typing a letter (a-z)\n# Vowels (a, e, i, o, u) cost $250 to guess and can’t be guessed if the player doesn’t have enough money. All other\n# letters are “free” to guess\n# The player can guess any letter that hasn’t been guessed and gets that cash amount for every time that letter appears\n# in the phrase\n# If there is a prize, the user also gets that prize (in addition to any prizes they already had)\n# If the letter does appear in the phrase, the user keeps their turn. Otherwise, it’s the next player’s turn\n# Example: The user lands on $500 and guesses ‘W’\n# There are three W’s in the phrase, so the player wins $1500\n# Guess the complete phrase by typing a phrase (anything over one character that isn’t ‘pass’)\n# If they are correct, they win the game, if they are incorrect, it is the next player’s turn\n# Pass their turn by entering 'pass'\n# If the wheel lands on “lose a turn”, the player loses their turn and the game moves on to the next player\n# If the wheel lands on “bankrupt”, the player loses their turn and loses their money but they keep all of the prizes\n# they have won so far.\n# The game continues until the entire phrase is revealed (or one player guesses the complete phrase)\n\n# First, let’s learn about a few functions and methods that we’ll use along the way to do this project. There are no\n# questions to answer in the next four active code windows. They are just here to introduce you to some functions and\n# methods that you may not be aware of. The active code window that starts with “Part A” is where you are first asked to\n# complete code.\n\n# CODE PROVIDED THAT I HAVE NOT WRITTEN\n# We’re going to define a few useful methods for you:\n# getNumberBetween(prompt, min, max)) repeatedly asks the user for a number between min and max with the prompt prompt\n# spinWheel() simulates spinning the wheel and returns a dictionary with a random prize\n# getRandomCategoryAndPhrase() returns a tuple with a random category and phrase for players to guess\n# obscurePhrase(phrase, guessed) returns a tuple with a random category and phrase for players to guess\nimport json\nimport random\nimport time\nLETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n# Repeatedly asks the user for a number between min & max (inclusive)\ndef getNumberBetween(prompt, min, max):\n userinp = input(prompt) # ask the first time\n while True:\n try:\n n = int(userinp) # try casting to an integer\n if n < min:\n errmessage = 'Must be at least {}'.format(min)\n elif n > max:\n errmessage = 'Must be at most {}'.format(max)\n else:\n return n\n except ValueError: # The user didn't enter a number\n errmessage = '{} is not a number.'.format(userinp)\n # If we haven't gotten a number yet, add the error message\n # and ask again\n userinp = input('{}\\n{}'.format(errmessage, prompt))\n\n# Spins the wheel of fortune wheel to give a random prize\n# Examples:\n# { \"type\": \"cash\", \"text\": \"$950\", \"value\": 950, \"prize\": \"A trip to Ann Arbor!\" },\n# { \"type\": \"bankrupt\", \"text\": \"Bankrupt\", \"prize\": false },\n# { \"type\": \"loseturn\", \"text\": \"Lose a turn\", \"prize\": false }\ndef spinWheel():\n with open(\"wheel.json\", 'r') as f: # don't have the wheel.json file unfortunately\n wheel = json.loads(f.read())\n return random.choice(wheel)\n\n# Returns a category & phrase (as a tuple) to guess\n# Example: (\"Artist & Song\", \"Whitney Houston's I Will Always Love You\")\ndef getRandomCategoryAndPhrase():\n with open(\"phrases.json\", 'r') as f: # don't have this file either\n phrases = json.loads(f.read())\n category = random.choice(list(phrases.keys()))\n phrase = random.choice(phrases[category])\n return (category, phrase.upper())\n\n# Given a phrase and a list of guessed letters, returns an obscured version\n# Example:\n# guessed: ['L', 'B', 'E', 'R', 'N', 'P', 'K', 'X', 'Z']\n# phrase: \"GLACIER NATIONAL PARK\"\n# returns> \"_L___ER N____N_L P_RK\"\ndef obscurePhrase(phrase, guessed):\n rv = ''\n for s in phrase:\n if (s in LETTERS) and (s not in guessed):\n rv = rv+'_'\n else:\n rv = rv+s\n return rv\n\n# Returns a string representing the current state of the game\ndef showBoard(category, obscuredPhrase, guessed):\n return \"\"\"\nCategory: {}\nPhrase: {}\nGuessed: {}\"\"\".format(category, obscuredPhrase, ', '.join(sorted(guessed)))\n\ncategory, phrase = getRandomCategoryAndPhrase()\n\nguessed = []\nfor x in range(random.randint(10, 20)):\n randomLetter = random.choice(LETTERS)\n if randomLetter not in guessed:\n guessed.append(randomLetter)\n\nprint(\"getRandomCategoryAndPhrase()\\n -> ('{}', '{}')\".format(category, phrase))\nprint(\"\\n{}\\n\".format(\"-\"*5))\nprint(\"obscurePhrase('{}', [{}])\\n -> {}\".format(phrase, ', '.join([\"'{}'\".format(c) for c in guessed]),\n obscurePhrase(phrase, guessed)))\nprint(\"\\n{}\\n\".format(\"-\"*5))\nobscured_phrase = obscurePhrase(phrase, guessed)\nprint(\"showBoard('{}', '{}', [{}])\\n -> {}\"\n .format(phrase, obscured_phrase, ','.join([\"'{}'\".format(c) for c in guessed]),\n showBoard(phrase, obscured_phrase, guessed)))\nprint(\"\\n{}\\n\".format(\"-\"*5))\nnum_times_to_spin = random.randint(2, 5)\nprint('Spinning the wheel {} times (normally this would just be done once per turn)'.format(num_times_to_spin))\nfor x in range(num_times_to_spin):\n print(\"\\n{}\\n\".format(\"-\"*2))\n print(\"spinWheel()\")\n print(spinWheel())\nprint(\"\\n{}\\n\".format(\"-\"*5))\nprint(\"In 2 seconds, will run getNumberBetween('Testing getNumberBetween(). Enter a number between 1 and 10', 1, 10)\")\ntime.sleep(2)\nprint(getNumberBetween('Testing getNumberBetween(). Enter a number between 1 and 10', 1, 10))\n\n# Part A: WOFPlayer\n# We’re going to start by defining a class to represent a Wheel of Fortune player, called WOFPlayer. Every instance of\n# WOFPlayer has three instance variables:\n# -.name: The name of the player (should be passed into the constructor)\n# -.prizeMoney: The amount of prize money for this player (an integer, initialized to 0)\n# -.prizes: The prizes this player has won so far (a list, initialized to [])\n# Of these instance variables, only name should be passed into the constructor.\n# It should also have the following methods (note: we will exclude self in our descriptions):\n# -.addMoney(amt): Add amt to self.prizeMoney\n# -.goBankrupt(): Set self.prizeMoney to 0\n# -.addPrize(prize): Append prize to self.prizes\n# -.__str__(): Returns the player’s name and prize money in the following format:\n# Steve ($1800) (for a player with instance variables .name == 'Steve' and prizeMoney == 1800)\n#\n# Part B: WOFHumanPlayer\n# Next, we’re going to define a class named WOFHumanPlayer, which should inherit from WOFPlayer (part A). This class is\n# going to represent a human player. In addition to having all of the instance variables and methods that WOFPlayer has,\n# WOFHumanPlayer should have an additional method:\n# .getMove(category, obscuredPhrase, guessed): Should ask the user to enter a move (using input()) and return whatever\n# string they entered.\n# .getMove()’s prompt should be:\n# {name} has ${prizeMoney}\n#\n# Category: {category}\n# Phrase: {obscured_phrase}\n# Guessed: {guessed}\n#\n# Guess a letter, phrase, or type 'exit' or 'pass':\n# The user can then enter:\n# -'exit' to exit the game\n# -'pass' to skip their turn\n# -a single character to guess that letter\n# -a complete phrase (a multi-character phrase other than 'exit' or 'pass') to guess that phrase\n# Note that .getMove() does not need to enforce anything about the user’s input; that will be done via the game logic\n# that we define in the next ActiveCode window.\n#\n# Part C: WOFComputerPlayer\n# Finally, we’re going to define a class named WOFComputerPlayer, which should inherit from WOFPlayer (part A). This\n# class is going to represent a computer player.\n# Every computer player will have a difficulty instance variable. Players with a higher difficulty generally play\n# “better”. There are many ways to implement this. We’ll do the following:\n# If there aren't any possible letters to choose (for example: if the last character is a vowel but this player doesn't\n# have enough to guess a vowel), we’ll 'pass'\n# Otherwise, semi-randomly decide whether to make a “good” move or a “bad” move on a given turn (a higher difficulty\n# should make it more likely for the player to make a “good” move)\n# To make a “bad” move, we’ll randomly decide on a possible letter.\n# To make a “good” move, we’ll choose a letter according to their overall frequency in the English language.\n# In addition to having all of the instance variables and methods that WOFPlayer has, WOFComputerPlayer should have:\n# -Class variable\n# --- .SORTED_FREQUENCIES: Should be set to 'ZQXJKVBPYGFWMUCLDRHSNIOATE', which is a list of English characters sorted\n# from least frequent ('Z') to most frequent ('E'). We’ll use this when trying to make a “good” move.\n# -Additional Instance variable\n# --- .difficulty: The level of difficulty for this computer (should be passed as the second argument into the\n# constructor after .name)\n# -Methods\n# --- .smartCoinFlip(): This method will help us decide semi-randomly whether to make a “good” or “bad” move. A higher\n# difficulty should make us more likely to make a “good” move. Implement this by choosing a random number between 1 and\n# 10 using random.randint(1, 10) (see above) and returning True if that random number is greater than self.difficulty.\n# If the random number is less than or equal to self.difficulty, return False.\n# --- .getPossibleLetters(guessed): This method should return a list of letters that can be guessed.\n# ----- These should be characters that are in LETTERS ('ABCDEFGHIJKLMNOPQRSTUVWXYZ') but not in the guessed parameter.\n# ----- Additionally, if this player doesn't have enough prize money to guess a vowel (variable VOWEL_COST set to 250),\n# then vowels (variable VOWELS set to 'AEIOU') should not be included\n# --- .getMove(category, obscuredPhrase, guessed): Should return a valid move.\n# ----- Use the .getPossibleLetters(guessed) method described above.\n# ----- If there aren't any letters that can be guessed (this can happen if the only letters left to guess are vowels\n# and the player doesn't have enough for vowels), return 'pass'\n# ----- Use the .smartCoinFlip() method to decide whether to make a “good” or a “bad” move\n# ------- If making a “good” move (.smartCoinFlip() returns True), then return the most frequent (highest index in\n# .SORTED_FREQUENCIES) possible character\n# ------- If making a “bad” move (.smartCoinFlip() returns False), then return a random character from the set of\n# possible characters (use random.choice())\n" }, { "alpha_fraction": 0.6954314708709717, "alphanum_fraction": 0.7213761806488037, "avg_line_length": 42.26829147338867, "blob_id": "6111883536805b3c00a7477f4ed7ba993d5b8932", "content_id": "477eade6b94665678dd845b4f67f0f51ebde6dc4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1773, "license_type": "no_license", "max_line_length": 117, "num_lines": 41, "path": "/PythonForEverybody/course4/CH15-01.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# Instructions\n# Create a SQLITE database or use an existing database and create a table in the database called \"Ages\":\n# CREATE TABLE Ages (\n# name VARCHAR(128),\n# age INTEGER\n# )\n# Then make sure the table is empty by deleting any rows that you previously inserted, and insert these rows and only\n# these rows with the following commands:\n#\n# DELETE FROM Ages;\n# Insert rows: ('Gabby', 27); ('Benn', 39); ('Abdulkhader', 37); ('Esther', 30); ('Jaii', 39); ('Romi', 24);\n# Once the inserts are done, run the following SQL command:\n# SELECT hex(name || age) AS X FROM Ages ORDER BY X\n#\n# Find the first row in the resulting record set and enter the long string that looks like 53656C696E613333.\n# Note: This assignment must be done using SQLite - in particular, the SELECT query above will not work in any other\n# database. So you cannot use MySQL or Oracle for this assignment.\n\nimport sqlite3\n\n# connect and get a cursor for sqlite\nconn = sqlite3.connect(\"sql1.db\")\ncurr = conn.cursor()\n\n# deleting table ages if it exists, if it doesn't nothing happens\ncurr.execute(\"DROP TABLE IF EXISTS Ages\")\n# creating new ages table\ncurr.execute(\"CREATE TABLE Ages(name TEXT, age INTEGERS)\")\n\n# insert values into the table and commit\ncurr.execute(\"INSERT INTO Ages (name, age) VALUES ('Gabby', 27)\")\ncurr.execute(\"INSERT INTO Ages (name, age) VALUES('Benn', 39)\")\ncurr.execute(\"INSERT INTO Ages (name, age) VALUES ('Abdulkhader', 37)\")\ncurr.execute(\"INSERT INTO Ages (name, age) VALUES ('Esther', 30)\")\ncurr.execute(\"INSERT INTO Ages (name, age) VALUES ('Jaii', 39)\")\ncurr.execute(\"INSERT INTO Ages (name, age) VALUES ('Romi', 24)\")\nconn.commit()\n\nSQLcommand = curr.execute(\"SELECT hex(name||age) AS X FROM Ages ORDER BY X\")\nrow = [rows[0] for rows in SQLcommand]\nprint(row[0])" }, { "alpha_fraction": 0.8163265585899353, "alphanum_fraction": 0.8163265585899353, "avg_line_length": 97, "blob_id": "74d58676da90b40a609e05fb71f9cc2ad885bfea", "content_id": "860070fd8e4dda49bbb2375ab9c653d28381ce24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 98, "license_type": "no_license", "max_line_length": 97, "num_lines": 1, "path": "/PythonForEverybody/course2/README.MD", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "this is the course work i did for Python Data Structures, the second course of the specialization\n" }, { "alpha_fraction": 0.7064256072044373, "alphanum_fraction": 0.7095696330070496, "avg_line_length": 57.379310607910156, "blob_id": "6d58b0c9479f6ce02b6eeab21d0fc61bb778eae4", "content_id": "952d9690bd9429461e04034cc2bfe496c61aed1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5095, "license_type": "no_license", "max_line_length": 120, "num_lines": 87, "path": "/Python3Programming/course2/classifier.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# We have provided some synthetic (fake, semi-randomly generated) twitter data in a csv file named project_twitter_\n# data.csv which has the text of a tweet, the number of retweets of that tweet, and the number of replies to that tweet.\n# We have also words that express positive sentiment and negative sentiment, in the files positive_words.txt and\n# negative_words.txt.\n# Your task is to build a sentiment classifier, which will detect how positive or negative each tweet is. You will\n# create a csv file, which contains columns for the Number of Retweets, Number of Replies, Positive Score (which is how\n# many happy words are in the tweet), Negative Score (which is how many angry words are in the tweet), and the Net Score\n# for each tweet. At the end, you upload the csv file to Excel or Google Sheets, and produce a graph of the Net Score vs\n# Number of Retweets.\n\n# To start, define a function called strip_punctuation which takes one parameter, a string which represents a word, and\n# removes characters considered punctuation from everywhere in the word. (Hint: remember the .replace() method for\n# strings.)\npunctuation_chars = [\"'\", '\"', \",\", \".\", \"!\", \":\", \";\", '#', '@']\ndef strip_punctuation(string):\n newString =\"\"\n for char in string:\n if char not in punctuation_chars:\n newString = newString + char\n return newString\n\n# Next, copy in your strip_punctuation function and define a function called get_pos which takes one parameter, a\n# string which represents one or more sentences, and calculates how many words in the string are considered positive\n# words. Use the list, positive_words to determine what words will count as positive. The function should return a\n# positive integer - how many occurrences there are of positive words in the text. Note that all of the words in\n# positive_words are lower cased, so you’ll need to convert all the words in the input string to lower case as well.\npositive_words = []\nwith open(\"positive_words.txt\") as pos_f:\n for lin in pos_f:\n if lin[0] != ';' and lin[0] != '\\n':\n positive_words.append(lin.strip())\n\ndef get_pos(string):\n count = 0\n for word in string.lower().split():\n if strip_punctuation(word) in positive_words:\n count = count + 1\n return count\n\n# Next, copy in your strip_punctuation function and define a function called get_neg which takes one parameter, a\n# string which represents one or more sentences, and calculates how many words in the string are considered negative\n# words. Use the list, negative_words to determine what words will count as negative. The function should return a\n# positive integer - how many occurrences there are of negative words in the text. Note that all of the words in\n# negative_words are lower cased, so you’ll need to convert all the words in the input string to lower case as well.\nnegative_words = []\nwith open(\"negative_words.txt\") as pos_f:\n for lin in pos_f:\n if lin[0] != ';' and lin[0] != '\\n':\n negative_words.append(lin.strip())\n\ndef get_neg(string):\n count = 0\n for word in string.lower().split():\n if strip_punctuation(word) in negative_words:\n count = count + 1\n return count\n\n# Finally, copy in your previous functions and write code that opens the file project_twitter_data.csv which has the\n# fake generated twitter data (the text of a tweet, the number of retweets of that tweet, and the number of replies to\n# that tweet). Your task is to build a sentiment classifier, which will detect how positive or negative each tweet is.\n# Copy the code from the code windows above, and put that in the top of this code window. Now, you will write code to\n# create a csv file called resulting_data.csv, which contains the Number of Retweets, Number of Replies, Positive Score\n# (which is how many happy words are in the tweet), Negative Score (which is how many angry words are in the tweet), and\n# the Net Score (how positive or negative the text is overall) for each tweet. The file should have those headers in\n# that order. Remember that there is another component to this project. You will upload the csv file to Excel or Google\n# Sheets and produce a graph of the Net Score vs Number of Retweets. Check Coursera for that portion of the assignment,\n# if you’re accessing this textbook from Coursera.\ntweets = []\nwith open(\"project_twitter_data.csv\") as twitterdata:\n for line in twitterdata:\n lines = line.strip().split(\",\")\n retweets = lines[1]\n replies = lines[2]\n pos = get_pos(line)\n neg = get_neg(line)\n net = pos - neg\n tweets.append((retweets,replies,pos,net,net))\nwith open(\"resulting_data.csv\",\"w\") as writing:\n writing.write(\"Number of Retweets, Number of Replies, Positive Score, Negative Score, Net Score\\n\")\n for tweet in tweets[1:]:\n retweets = tweet[0]\n replies = tweet[1]\n pos = tweet[2]\n neg = tweet[3]\n net = tweet[4]\n writing.write(\"{},{},{},{},{}\".format(retweets,replies,pos,neg,net))\n writing.write(\"\\n\")\n\n\n " }, { "alpha_fraction": 0.7124541997909546, "alphanum_fraction": 0.7188644409179688, "avg_line_length": 39.44444274902344, "blob_id": "66b6e6ae78684e9e153a785760f908b0840185cd", "content_id": "d05a0cea4825e95ca0f57a85f25eddefd5da8dfe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1092, "license_type": "no_license", "max_line_length": 119, "num_lines": 27, "path": "/PythonForEverybody/course2/CH9.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# assignment 9.4\n# Write a program to read through the mbox-short.txt and figure out who has sent the greatest number of mail messages.\n# The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. The\n# program creates a Python dictionary that maps the sender's mail address to a count of the number of times they appear\n# in the file. After the dictionary is produced, the program reads through the dictionary using a maximum loop to find\n# the most prolific committer.\n\n# open file\nfName = input(\"Enter file: \")\nif len(fName) < 1:\n fName = \"mbox-short.txt\"\nfHandle = open(fName)\n# create a dictionary of the email address and their counts\nemails = dict()\nfor line in fHandle:\n if line.startswith(\"From \"):\n emails[line.split()[1]] = emails.get(line.split()[1], 0) + 1\n else:\n continue\n# find the email address with the highest count\nbigEmail = None\nbigCount = None\nfor key,value in emails.items():\n if bigCount is None or value > bigCount:\n bigEmail = key\n bigCount = value\nprint(bigEmail,bigCount)\n" }, { "alpha_fraction": 0.7330794334411621, "alphanum_fraction": 0.7360221743583679, "avg_line_length": 56.779998779296875, "blob_id": "85cd120a5e288749940fcce39671ccc18659e13e", "content_id": "55be9d790a88a61ee17e79b02abb2f988bf6250e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5811, "license_type": "no_license", "max_line_length": 120, "num_lines": 100, "path": "/Python3Programming/course3/project.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# This project will take you through the process of mashing up data from two different APIs to make movie\n# recommendations. The TasteDive API lets you provide a movie (or bands, TV shows, etc.) as a query input, and returns\n# a set of related items. The OMDB API lets you provide a movie title as a query input and get back data about the\n# movie, including scores from various review sites (Rotten Tomatoes, IMDB, etc.).\n#\n# You will put those two together. You will use TasteDive to get related movies for a whole list of titles. You’ll\n# combine the resulting lists of related movies, and sort them according to their Rotten Tomatoes scores (which will\n# require making API calls to the OMDB API.)\n#\n# To avoid problems with rate limits and site accessibility, we have provided a cache file with results for all the\n# queries you need to make to both OMDB and TasteDive. Just use requests_with_caching.get() rather than requests.get().\n# If you’re having trouble, you may not be formatting your queries properly, or you may not be asking for data that\n# exists in our cache. We will try to provide as much information as we can to help guide you to form queries for which\n# data exists in the cache.\n#\n# Your first task will be to fetch data from TasteDive. The documentation for the API is at\n# https://tastedive.com/read/api.\n#\n# Define a function, called get_movies_from_tastedive. It should take one input parameter, a string that is the name of\n# a movie or music artist. The function should return the 5 TasteDive results that are associated with that string; be\n# sure to only get movies, not other kinds of media. It will be a python dictionary with just one key, ‘Similar’.\n#\n# Try invoking your function with the input “Black Panther”.\n#\n# HINT: Be sure to include only q, type, and limit as parameters in order to extract data from the cache. If any other\n# parameters are included, then the function will not be able to recognize the data that you’re attempting to pull from\n# the cache. Remember, you will not need an api key in order to complete the project, because all data will be found in\n# the cache.\n#\n# The cache includes data for the following queries:\n#\n# q | type | limit\n# Black Panther | <omitted> | <omitted>\n# Black Panther | <omitted> | 5\n# Black Panther | movies | <omitted>\n# Black Panther | movies | 5\n# Tony Bennett | <omitted> | 5\n# Tony Bennett | movies | 5\n# Captain Marvel | movies | 5\n# Bridesmaids | movies | 5\n# Sherlock Holmes | movies | 5\n\nimport requests_with_caching # doesn't exist outside of my coursera course, in order to work in the real world, the\n# api needs an api-key that I don't have\nimport json\ndef get_movies_from_tastedive(movie):\n baseurl = \"https://tastedive.com/api/similar\"\n parameters = {\"q\": movie, \"type\": \"movies\", \"limit\": 5}\n req = requests_with_caching.get(baseurl,params = parameters)\n res = req.json()\n return res\n\n# Next, you will need to write a function that extracts just the list of movie titles from a dictionary returned by get_\n# movies_from_tastedive. Call it extract_movie_titles.\ndef extract_movie_titles(json):\n return [title[\"Name\"] for title in json[\"Similar\"][\"Results\"]]\n\n# Next, you’ll write a function, called get_related_titles. It takes a list of movie titles as input. It gets five\n# related movies for each from TasteDive, extracts the titles for all of them, and combines them all into a single list.\n# Don’t include the same movie twice.\ndef get_related_titles(movieList):\n fullList = []\n for movie in movieList:\n for relMovie in extract_movie_titles(get_movies_from_tastedive(movie)):\n if relMovie not in fullList:\n fullList.append(relMovie)\n return fullList\n\n# Your next task will be to fetch data from OMDB. The documentation for the API is at https://www.omdbapi.com/\n# Define a function called get_movie_data. It takes in one parameter which is a string that should represent the title\n# of a movie you want to search. The function should return a dictionary with information about that movie.\n# Again, use requests_with_caching.get(). For the queries on movies that are already in the cache, you won’t need an api\n# key. You will need to provide the following keys: t and r. As with the TasteDive cache, be sure to only include those\n# two parameters in order to extract existing data from the cache.\ndef get_movie_data(movie):\n baseurl = \"http://www.omdbapi.com/\"\n parameters = {\"t\": movie, \"r\": \"json\"}\n req = requests_with_caching.get(baseurl, params = parameters)\n res = req.json()\n return res\n\n# Now write a function called get_movie_rating. It takes an OMDB dictionary result for one movie and extracts the Rotten\n# Tomatoes rating as an integer. For example, if given the OMDB dictionary for “Black Panther”, it would return 97. If\n# there is no Rotten Tomatoes rating, return 0.\ndef get_movie_rating(OMDBdict):\n RT = 0\n for sources in OMDBdict[\"Ratings\"]:\n if sources[\"Source\"] == \"Rotten Tomatoes\":\n RT = int(str(sources[\"Value\"])[:-1])\n return RT\n\n# Define a function get_sorted_recommendations. It takes a list of movie titles as an input. It returns a sorted list of\n# related movie titles as output, up to five related movies for each input movie title. The movies should be sorted in\n# descending order by their Rotten Tomatoes rating, as returned by the get_movie_rating function. Break ties in reverse\n# alphabetic order, so that ‘Yahşi Batı’ comes before ‘Eyyvah Eyvah’.\ndef get_sorted_recommendations(movieTitles):\n ratings = [get_movie_rating(get_movie_data(movie)) for movie in get_related_titles(movieTitles)]\n related = get_related_titles(movieTitles)\n rec = sorted(zip(related,ratings),key=lambda tup: (tup[1],tup[0]), reverse=True)\n return [tup[0] for tup in rec]" }, { "alpha_fraction": 0.8350515365600586, "alphanum_fraction": 0.8350515365600586, "avg_line_length": 96, "blob_id": "4bd02c5e7594726fe6a5f5cbb727c12d666fead7", "content_id": "535691f6091bc551d4931ac7b6f76cb7f37947cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 97, "license_type": "no_license", "max_line_length": 96, "num_lines": 1, "path": "/PythonForEverybody/course4/README.md", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "this is the coursework from the fourth course in the specialization: Using Databases with Python\n" }, { "alpha_fraction": 0.6982455849647522, "alphanum_fraction": 0.7087719440460205, "avg_line_length": 38.61111068725586, "blob_id": "3f9ece84aec420a43f88d6f962ff0096d333adb7", "content_id": "cc4dc164f805ea3488f1b3d0cf9283fb0ba7ff1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1437, "license_type": "no_license", "max_line_length": 120, "num_lines": 36, "path": "/Python3Programming/course2/CH12.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# Write a function called int_return that takes an integer as input and returns the same integer.\ndef int_return(num):\n return num\n\n# Write a function called add that takes any number as its input and returns that sum with 2 added.\ndef add(num):\n return num + 2\n\n# Write a function called change that takes any string, adds “Nice to meet you!” to the end of the argument given, and\n# returns that new string.\ndef change(string):\n return \"{}Nice to meet you!\".format(string)\n\n# Write a function, accum, that takes a list of integers as input and returns the sum of those integers.\ndef accum(lst):\n tot = 0\n for num in lst:\n tot = tot + num\n return tot\n\n# Write a function, length, that takes in a list as the input. If the length of the list is greater than or equal to 5,\n# return “Longer than 5”. If the length is less than 5, return “Less than 5”.\ndef length(lst):\n if len(lst) >= 5:\n return \"Longer than 5\"\n else:\n return \"Less than 5\"\n\n# You will need to write two functions for this problem. The first function, divide that takes in any number and returns\n# that same number divided by 2. The second function called sum should take any number, divide it by 2, and add 6. It\n# should return this new number. You should call the divide function within the sum function. Do not worry about\n# decimals.\ndef divide(num):\n return num / 2\ndef sum(num):\n return divide(num) + 6" }, { "alpha_fraction": 0.65817791223526, "alphanum_fraction": 0.6750358939170837, "avg_line_length": 40.62686538696289, "blob_id": "e45d5a3d934286d29615acc1989d8655b6635bbe", "content_id": "753a9f34324939ee7b8cc662ceabfaac6e491dfa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2808, "license_type": "no_license", "max_line_length": 120, "num_lines": 67, "path": "/Python3Programming/course2/CH14.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# Write a function, sublist, that takes in a list of numbers as the parameter. In the function, use a while loop to\n# return a sublist of the input list. The sublist should contain the same values of the original list up until it\n# reaches the number 5 (it should not contain the number 5).\ndef sublist(listy):\n sub = []\n num = 0\n while num < len(listy) and listy[num] != 5:\n sub.append(listy[num])\n num = num + 1\n return sub\n\n# Write a function called check_nums that takes a list as its parameter, and contains a while loop that only stops once\n# the element of the list is the number 7. What is returned is a list of all of the numbers up until it reaches 7.\ndef check_nums(listy):\n sub = []\n num = 0\n while num < len(listy) and listy[num] != 7:\n sub.append(listy[num])\n num = num + 1\n return sub\n\n# Write a function, sublist, that takes in a list of strings as the parameter. In the function, use a while loop to\n# return a sublist of the input list. The sublist should contain the same values of the original list up until it\n# reaches the string “STOP” (it should not contain the string “STOP”).\ndef sublist(listy):\n sub = []\n num = 0\n while num < len(listy) and listy[num] != \"STOP\":\n sub.append(listy[num])\n num = num + 1\n return sub\n\n# Write a function called stop_at_z that iterates through a list of strings. Using a while loop, append each string to\n# a new list until the string that appears is “z”. The function should return the new list.\ndef stop_at_z(listy):\n sub = []\n num = 0\n while num < len(listy) and listy[num] != \"z\":\n sub.append(listy[num])\n num = num + 1\n return sub\n\n# Below is a for loop that works. Underneath the for loop, rewrite the problem so that it does the same thing, but using\n# a while loop instead of a for loop. Assign the accumulated total in the while loop code to the variable sum2. Once\n# complete, sum2 should equal sum1.\nsum1 = 0\nlst = [65, 78, 21, 33]\nfor x in lst:\n sum1 = sum1 + x\n## my code\nnum = 0\nsum2 = 0\nwhile num < len(lst):\n sum2 = sum2 + lst[num]\n num = num + 1\n\n# Challenge: Write a function called beginning that takes a list as input and contains a while loop that only stops once\n# the element of the list is the string ‘bye’. What is returned is a list that contains up to the first 10 strings,\n# regardless of where the loop stops. (i.e., if it stops on the 32nd element, the first 10 are returned. If “bye” is the\n# 5th element, the first 4 are returned.) If you want to make this even more of a challenge, do this without slicing\ndef beginning(listy):\n num = 0\n sub = []\n while num < len(listy) and num < 10 and listy[num] != \"bye\":\n sub.append(listy[num])\n num = num + 1\n return sub" }, { "alpha_fraction": 0.7723076939582825, "alphanum_fraction": 0.7753846049308777, "avg_line_length": 91.85713958740234, "blob_id": "809696e7bacfd26842c97bcf6d4db88f42632ae5", "content_id": "8043a812690fc3d80eac86a2dfd1697041ed8b75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 650, "license_type": "no_license", "max_line_length": 118, "num_lines": 7, "path": "/PythonForEverybody/course4/CH16.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# Retrieving GEOData\n# Download the code from http://www.py4e.com/code3/geodata.zip - then unzip the file and edit where.data to add an\n# address nearby where you live - don't reveal where you live. Then run the geoload.py to lookup all of the entries in\n# where.data (including the new one) and produce the geodata.sqlite. Then run geodump.py to read the database and p\n# roduce where.js. You can run the programs and then scroll back to take your screen shots when the program finishes.\n# Then open where.html to visualize the map. Take screen shots as described below. Make sure that your added location\n# shows in all three of your screen shots.\n" }, { "alpha_fraction": 0.7169811129570007, "alphanum_fraction": 0.7358490824699402, "avg_line_length": 34.33333206176758, "blob_id": "84d16b961ec86fddb821839d619c6ff5fdb7d3b5", "content_id": "667d9d3322a75350fc9a12a07bcc6e461d503264", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 106, "license_type": "no_license", "max_line_length": 67, "num_lines": 3, "path": "/PythonForEverybody/course1/CH1.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# assignment 1.1\n# Write a program that uses a print statement to say 'hello world'.\nprint(\"hello world\")\n" }, { "alpha_fraction": 0.6955860257148743, "alphanum_fraction": 0.7214611768722534, "avg_line_length": 49.53845977783203, "blob_id": "474aed6d825997e467985ca7259557dde5b8522b", "content_id": "a54004f38ea1360396dbcbbe73c11ffc024f8d44", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 657, "license_type": "no_license", "max_line_length": 118, "num_lines": 13, "path": "/PythonForEverybody/course1/CH2.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# Assignment 2.2\n# 2.2 Write a program that uses input to prompt a user for their name and then welcomes them. Note that input will pop\n# up a dialog box.\nname = input(\"Enter your name \")\nprint(\"Hello \" + name)\n\n# Assignment 2.3\n# 2.3 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Use 35 hours\n# and a rate of 2.75 per hour to test the program (the pay should be 96.25). You should use input to read a string\n# and float() to convert the string to a number. Do not worry about error checking or bad user data.\nhrs = input(\"Enter Hours: \")\nrate = input(\"Enter Rate: \")\nprint(\"Pay:\", float(hrs)*float(rate))\n" }, { "alpha_fraction": 0.6571325063705444, "alphanum_fraction": 0.7128891944885254, "avg_line_length": 61.79545593261719, "blob_id": "61b1df754a46314ee3ec3b326231d422caa8af0a", "content_id": "59f24d435427e791d533cc4d8c5e24f3c2f84517", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2764, "license_type": "no_license", "max_line_length": 120, "num_lines": 44, "path": "/Python3Programming/course2/CH16.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# Sort the following string alphabetically, from z to a, and assign it to the variable sorted_letters.\nletters = \"alwnfiwaksuezlaeiajsdl\"\nsorted_letters = sorted(letters, reverse=True)\n\n# Sort the list below, animals, into alphabetical order, a-z. Save the new list as animals_sorted.\nanimals = ['elephant', 'cat', 'moose', 'antelope', 'elk', 'rabbit', 'zebra', 'yak', 'salamander', 'deer', 'otter',\n 'minx', 'giraffe', 'goat', 'cow', 'tiger', 'bear']\nanimals_sorted = sorted(animals)\n\n# The dictionary, medals, shows the medal count for six countries during the Rio Olympics. Sort the country names so\n# they appear alphabetically. Save this list to the variable alphabetical.\nmedals = {'Japan':41, 'Russia':56, 'South Korea':21, 'United States':121, 'Germany':42, 'China':70}\nalphabetical = sorted(medals)\n\n# Given the same dictionary, medals, now sort by the medal count. Save the three countries with the highest medal count\n# to the list, top_three.\nmedals = {'Japan':41, 'Russia':56, 'South Korea':21, 'United States':121, 'Germany':42, 'China':70}\nmedalsSorted = sorted(medals, reverse=True, key= lambda k: medals[k])\ntop_three = [medalsSorted[i] for i in range(3)]\n\n# We have provided the dictionary groceries. You should return a list of its keys, but they should be sorted by their\n# values, from highest to lowest. Save the new list as most_needed.\ngroceries = {'apples': 5, 'pasta': 3, 'carrots': 12, 'orange juice': 2, 'bananas': 8, 'popcorn': 1, 'salsa': 3,\n 'cereal': 4, 'coffee': 5, 'granola bars': 15, 'onions': 7, 'rice': 1, 'peanut butter': 2, 'spinach': 9}\nmost_needed = sorted(groceries, reverse=True, key= lambda k: groceries[k])\n\n# Create a function called last_four that takes in an ID number and returns the last four digits. For example, the\n# number 17573005 should return 3005. Then, use this function to sort the list of ids stored in the variable, ids, from\n# lowest to highest. Save this sorted list in the variable, sorted_ids. Hint: Remember that only strings can be indexed,\n# so conversions may be needed.\ndef last_four(x):\n return x[-4:]\nids = [17573005, 17572342, 17579000, 17570002, 17572345, 17579329]\nsorted_ids = sorted(ids,key=lambda k: last_four(str(k)))\n\n# Sort the list ids by the last four digits of each id. Do this using lambda and not using a defined function. Save\n# this sorted list in the variable sorted_id.\nids = [17573005, 17572342, 17579000, 17570002, 17572345, 17579329]\nsorted_id = sorted(ids,key=lambda k: str(k)[-4])\n\n# Sort the following list by each element’s second letter a to z. Do so by using lambda. Assign the resulting value to\n# the variable lambda_sort.\nex_lst = ['hi', 'how are you', 'bye', 'apple', 'zebra', 'dance']\nlambda_sort = sorted(ex_lst,key=lambda k: k[1])" }, { "alpha_fraction": 0.7264692783355713, "alphanum_fraction": 0.7317720055580139, "avg_line_length": 44.2599983215332, "blob_id": "1deaec978893e64ce11c70914a8ff6ec73b871ee", "content_id": "0aaa2347ca093c2532ce39651283c4344143dacc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2263, "license_type": "no_license", "max_line_length": 118, "num_lines": 50, "path": "/PythonForEverybody/course4/CH15-02.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# Counting Organizations\n# This application will read the mailbox data (mbox.txt) and count the number of email messages per organization\n# (i.e. domain name of the email address) using a database with the following schema to maintain the counts.\n#\n# CREATE TABLE Counts (org TEXT, count INTEGER)\n# When you have run the program on mbox.txt upload the resulting database file above for grading.\n# If you run the program multiple times in testing or with different files, make sure to empty out the data before\n# each run.\n#\n# You can use this code as a starting point for your application: http://www.py4e.com/code3/emaildb.py.\n#\n# The data file for this application is the same as in previous assignments: http://www.py4e.com/code3/mbox.txt.\n#\n# Because the sample code is using an UPDATE statement and committing the results to the database as each record is\n# read in the loop, it might take as long as a few minutes to process all the data. The commit insists on completely\n# writing all the data to disk every time it is called.\n#\n# The program can be sped up greatly by moving the commit operation outside of the loop. In any database program,\n# there is a balance between the number of operations you execute between commits and the importance of not losing the\n# results of operations that have not yet been committed.\n\nimport sqlite3\nimport urllib.request, urllib.parse, urllib.error\nimport re\n\n# open and read the file\nfile = input(\"Enter file: \")\nif len(file) < 1: file = \"files/mbox-short.txt\"\nfOpen = open(file)\n\n# open and connect to the db\nconn = sqlite3.connect(\"sql2.sqlite\")\ncurr = conn.cursor()\n\n# if table exists, delete it then make a new one\ncurr.execute(\"DROP TABLE IF EXISTS Counts\")\ncurr.execute(\"CREATE TABLE Counts (org TEXT, count INTEGER)\")\n\nfor line in fOpen:\n # find the email domains\n if not line.startswith(\"From: \"): continue\n else: email = line.split()[1].split(\"@\")[1]\n # see if the email domain is already in the db\n curr.execute(\"SELECT * FROM Counts WHERE org = ?\", (email,))\n row = curr.fetchone()\n if row is None:\n curr.execute(\"INSERT INTO Counts (org, count) VALUES (?,1)\", (email,))\n else:\n curr.execute(\"UPDATE Counts SET count = count + 1 where org = ?\", (email,))\nconn.commit()\n" }, { "alpha_fraction": 0.711904764175415, "alphanum_fraction": 0.7321428656578064, "avg_line_length": 37.227272033691406, "blob_id": "08c4453f9dcb1508eb4e7fbc4d7a78086f183319", "content_id": "c41d92c0b226d8ce56acfb264928c1e89d18dbf8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 840, "license_type": "no_license", "max_line_length": 113, "num_lines": 22, "path": "/PythonForEverybody/course3/CH13-02.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# Extracting Data from JSON\n#\n# The program will prompt for a URL, read the JSON data from that URL using urllib and then parse and extract the\n# comment counts from the JSON data, compute the sum of the numbers in the file and enter the sum below:\n#\n# Sample data: http://py4e-data.dr-chuck.net/comments_42.json (Sum=2553)\n# Actual data: http://py4e-data.dr-chuck.net/comments_1109156.json (Sum ends with 37)\n\nimport urllib.request, urllib.error, urllib.parse\nimport json\n\n#access the website\nurl = input(\"Enter URL: \")\ndata = urllib.request.urlopen(url).read().decode()\nprint(\"Retrieved\",len(data),\"characters\")\n\n#gets the JSON data in python form\njs = json.loads(data)\n\n#find all nums in [\"comments\"][iterable][\"count\"] and add them up\ncounts = [int(js[\"comments\"][num][\"count\"]) for num in range(len(js[\"comments\"]))]\nprint(sum(counts))" }, { "alpha_fraction": 0.692307710647583, "alphanum_fraction": 0.6948717832565308, "avg_line_length": 51.06666564941406, "blob_id": "0cd4840a3fb6fd8fb7c0ff9da4a59d86d74ac26e", "content_id": "94fdd35942bcd5ee028e2a917e630fb16159dae0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 780, "license_type": "no_license", "max_line_length": 117, "num_lines": 15, "path": "/Python3Programming/course1/CH06.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# Write a program that will print out the length of each item in the list as well as the first and last\n# characters of the item.\nweather = [\"sunny\", \"cloudy\", \"partially sunny\", \"rainy\", \"storming\", \"windy\", \"foggy\", \"snowy\", \"hailing\"]\nfor condition in weather:\n print(\"The word is\", len(condition), \"characters long\")\n first_char = condition[0]\n last_char = condition[-1]\n print(\"The first character is\", first_char)\n print(\"The last character is\",last_char)\n\n# Write code to determine how many t's are in the following sentences.\nphrases = [\"My, what a lovely day today is!\", \"Have you mastered cooking yet? A tasty treat could be in your future\",\n \"Have you ever seen the leaves change color?\"]\nfor sentence in phrases:\n print(sentence.count(\"t\"))" }, { "alpha_fraction": 0.5748065114021301, "alphanum_fraction": 0.5963026881217957, "avg_line_length": 30.876712799072266, "blob_id": "0ca29dddee0fde482c726b87531cb72be6caf0bb", "content_id": "30f848f81b275524622f223ebb77659deacaf710", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2326, "license_type": "no_license", "max_line_length": 119, "num_lines": 73, "path": "/Python3Programming/course5/assignment1.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "import PIL\nfrom PIL import Image, ImageDraw, ImageFont\n\n# read image and convert to RGB\nimage = Image.open(\"cclogo.jpeg\")\nimage = image.convert('RGBA')\n\n# loop over pixels\ndef colorChange(color,percent,row):\n newIm = Image.new(\"RGBA\",(image.width,int(image.height*1.1)))\n newIm.paste(image,(0,0))\n height = newIm.height\n width = newIm.width\n for x in range(width):\n for y in range(height):\n r,g,b,e = newIm.getpixel((x,y))\n if color == \"red\":\n r = int(r * percent)\n if color == \"green\":\n g = int(g * percent)\n if color == \"blue\":\n b = int(b * percent)\n newIm.putpixel((x,y),(r,g,b))\n r,g,b = 255,255,255\n if color == \"red\":\n r = int(255 * percent)\n if color == \"green\":\n g = int(255 * percent)\n if color == \"blue\":\n b = int(255 * percent)\n txt = ImageDraw.Draw(newIm)\n font = ImageFont.truetype(\"/Users/docopeland/IdeaProjects/python-coursera/Python3Programming/course5/arial.ttf\",15)\n txt.text((0,image.height),\"channel {} intensity {}\".format(row,percent),fill=(r,g,b),font=font)\n return newIm\n\nimages = []\nfor row in range(3):\n if row == 0:\n color = \"red\"\n if row == 1:\n color = \"green\"\n if row == 2:\n color = \"blue\"\n for col in range(3):\n if col == 0:\n img = colorChange(color,0.1,row)\n if col == 1:\n img = colorChange(color,0.5,row)\n if col == 2:\n img = colorChange(color,0.9,row)\n images.append(img)\n\n\n# create a contact sheet from different brightnesses\nfirst_image=images[0]\ncontact_sheet=PIL.Image.new(first_image.mode, (first_image.width*3,first_image.height*3))\nx=0\ny=0\n\nfor img in images:\n # Lets paste the current image into the contact sheet\n contact_sheet.paste(img, (x, y) )\n # Now we update our X position. If it is going to be the width of the image, then we set it to 0\n # and update Y as well to point to the next \"line\" of the contact sheet.\n if x+first_image.width == contact_sheet.width:\n x=0\n y=y+first_image.height\n else:\n x=x+first_image.width\n\n# resize and display the contact sheet\ncontact_sheet = contact_sheet.resize((int(contact_sheet.width/2),int(contact_sheet.height/2) ))\ncontact_sheet.show()" }, { "alpha_fraction": 0.7121896147727966, "alphanum_fraction": 0.718397319316864, "avg_line_length": 35.18367385864258, "blob_id": "ac7a0d1366dde741385429739f6a46304235e406", "content_id": "3c1eecc8a8c91744460de6e39051b9d48c7acf3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1776, "license_type": "no_license", "max_line_length": 118, "num_lines": 49, "path": "/Python3Programming/course2/CH10.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# The textfile, travel_plans.txt, contains the summer travel plans for someone with some commentary. Find the total\n# number of characters in the file and save to the variable num.\ntxt = open(\"travel_plans.txt\")\ntxtR = txt.read()\nnum = len(txtR)\ntxt.close()\n\n# We have provided a file called emotion_words.txt that contains lines of words that describe emotions. Find the total\n# number of words in the file and assign this value to the variable num_words.\ntxt = open(\"emotion_words.txt\")\ntxtR = txt.read().strip().split()\nnum_words = len(txtR)\n\n# Assign to the variable num_lines the number of lines in the file school_prompt.txt.\ntxt = open(\"school_prompt.txt\")\ntxtR = txt.readlines()\nnum_lines = len(txtR)\n\n# Assign the first 30 characters of school_prompt.txt as a string to the variable beginning_chars.\ntxt = open(\"school_prompt.txt\")\ntxtR = txt.read()\nbeginning_chars = txtR[:30]\n\n# Challenge: Using the file school_prompt.txt, assign the third word of every line to a list called three.\ntxt = open(\"school_prompt.txt\")\nthree = []\nfor line in txt:\n word = line.split()\n three.append(word[2])\n\n# Challenge: Create a list called emotions that contains the first word of every line in emotion_words.txt.\ntxt = open(\"emotion_words.txt\")\nemotions = []\nfor line in txt:\n word = line.split()\n emotions.append(word[0])\n\n# Assign the first 33 characters from the textfile, travel_plans.txt to the variable first_chars.\ntxt = open(\"travel_plans.txt\")\ntxtR = txt.read()\nfirst_chars = txtR[:33]\n\n# Challenge: Using the file school_prompt.txt, if the character ‘p’ is in a word, then add the word to a list called\n# p_words.\ntxt = open(\"school_prompt.txt\")\np_words = []\nfor word in txt.read().split():\n if word.lower().count(\"p\") > 0:\n p_words.append(word)" }, { "alpha_fraction": 0.676254153251648, "alphanum_fraction": 0.6882942914962769, "avg_line_length": 39.4054069519043, "blob_id": "a905a89497f2a904b807493d9fa5848d4bc5f01b", "content_id": "c32319dacd6804ea2a7924ef55134cd6a37cd8bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1495, "license_type": "no_license", "max_line_length": 118, "num_lines": 37, "path": "/PythonForEverybody/course2/CH8.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# assignment 8.4\n# Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the\n# split() method. The program should build a list of words. For each word on each line check to see if the word is\n# already in the list and if not append it to the list. When the program completes, sort and print the resulting\n# words in alphabetical order.\n\nfName = input(\"Enter file name: \")\nfOpen = open(fName)\nwordsList = list()\nfor line in fOpen:\n words = line.rstrip().split()\n for word in words:\n if word in wordsList:\n continue\n else:\n wordsList.append(word)\nprint(sorted(wordsList))\n\n# assignment 8.5\n# Open the file mbox-short.txt and read it line by line. When you find a line that starts with 'From ' like the\n# following line: From [email protected] Sat Jan 5 09:14:16 2008\n# You will parse the From line using split() and print out the second word in the line (i.e. the entire address of the\n# person who sent the message). Then print out a count at the end.\n# Hint: make sure not to include the lines that start with 'From:'. Also look at the last line of the sample output\n# to see how to print the count.\n\nfName = input(\"Enter file name: \")\nfOpen = open(fName)\ncount = 0\nfor line in fOpen:\n if line.startswith(\"From \"):\n words = line.rstrip().split()\n print(words[1])\n count = count + 1\n else:\n continue\nprint(\"There were\", count, \"lines in the file with From as the first word\")\n" }, { "alpha_fraction": 0.7208821773529053, "alphanum_fraction": 0.7291523218154907, "avg_line_length": 49.068965911865234, "blob_id": "3d5cb7cf05271b7b61c0b54c2e58482a3b8a0453", "content_id": "737bd33ad631ba6c8fad8a75f32c272af6992fc5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1451, "license_type": "no_license", "max_line_length": 120, "num_lines": 29, "path": "/PythonForEverybody/course3/CH12-03.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# Following Links in Python\n# The program will use urllib to read the HTML from the data files below, extract the href= values from the anchor tags,\n# scan for a tag that is in a particular position relative to the first name in the list, follow that link and repeat\n# the process a number of times and report the last name you find.\n\n# Sample problem: Start at http://py4e-data.dr-chuck.net/known_by_Fikret.html\n# Find the link at position 3 (the first name is 1). Follow that link. Repeat this process 4 times. The answer is the\n# last name that you retrieve. Sequence: Fikret Montgomery Mhairade Butchi Anayah; Last name in sequence: Anayah\n# Actual problem: Start at: http://py4e-data.dr-chuck.net/known_by_Conli.html\n# Find the link at position 18 (the first name is 1). Follow that link. Repeat this process 7 times. The answer is the\n# last name that you retrieve.\n\nimport urllib.request, urllib.parse, urllib.error\nfrom bs4 import BeautifulSoup\nimport re\n\n# choose the beginner url, number of times to repeat the process, the position to use\nurl = input(\"Enter URL: \")\nranges = int(input(\"Enter count: \"))\nposition = int(input(\"Enter position: \"))\n\nfor i in range(ranges+1):\n print(url)\n html = urllib.request.urlopen(url).read()\n soup = BeautifulSoup(html, 'html.parser')\n tags = soup('a')\n urls = [re.findall('href=\"(\\S+)\"', tag.decode()) for tag in tags]\n allLinks = [subSubUrls for subUrls in urls for subSubUrls in subUrls]\n url = allLinks[position-1]" }, { "alpha_fraction": 0.6858947277069092, "alphanum_fraction": 0.699368417263031, "avg_line_length": 35, "blob_id": "463418314c54c5e346b9d08a73ad5104843f98e8", "content_id": "398fbcc7fd5a58831ef48fcf13ec1b9aa92edf4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2375, "license_type": "no_license", "max_line_length": 119, "num_lines": 66, "path": "/PythonForEverybody/course4/CH15-04.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# Instructions\n# This application will read roster data in JSON format, parse the file, and then produce an SQLite database that\n# contains a User, Course, and Member table and populate the tables from the data file.\n#\n# Once you have made the necessary changes to the program and it has been run successfully reading the above JSON data,\n# run the following SQL command:\n#\n# SELECT User.name,Course.title, Member.role FROM\n# User JOIN Member JOIN Course\n# ON User.id = Member.user_id AND Member.course_id = Course.id\n# ORDER BY User.name DESC, Course.title DESC, Member.role DESC LIMIT 2;\n# The output should look as follows:\n# Zoha|si430|0\n# Ziyaan|si334|0\n# Once that query gives the correct data, run this query:\n# SELECT 'XYZZY' || hex(User.name || Course.title || Member.role ) AS X FROM\n# User JOIN Member JOIN Course\n# ON User.id = Member.user_id AND Member.course_id = Course.id\n# ORDER BY X LIMIT 1;\n# You should get one row with a string that looks like XYZZY53656C696E613333.\n\nimport json\nimport sqlite3\n\n# open the file\nfile = input(\"Enter file: \")\nif len(file) <1: file = \"files/roster_data.json\"\nfOpen = open(file).read()\n\n# set up sql connection & cursor\nconn = sqlite3.connect(\"roster.sqlite\")\ncurr = conn.cursor()\n\n# drop & create the sql tables\ncurr.executescript(\"\"\"\nDROP TABLE IF EXISTS User;\nDROP TABLE IF EXISTS Course;\nDROP TABLE IF EXISTS Member;\nCREATE TABLE User (\n id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,\n name TEXT UNIQUE);\nCREATE TABLE Course (\n id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,\n title TEXT UNIQUE);\nCREATE TABLE Member (\n user_id INTEGER,\n course_id INTEGER,\n role INTEGER);\"\"\")\n\n# load the data\njs = json.loads(fOpen)\nfor entry in js:\n name = entry[0]\n course = entry[1]\n role = entry[2]\n # get user_id\n curr.execute(\"INSERT OR IGNORE INTO User (name) VALUES (?)\", (name,))\n curr.execute(\"SELECT id FROM User WHERE name = ?\", (name,))\n user_id = curr.fetchone()[0]\n # get course id\n curr.execute(\"INSERT OR IGNORE INTO Course (title) VALUES (?)\", (course,))\n curr.execute(\"SELECT id FROM Course WHERE title = ?\", (course,))\n course_id = curr.fetchone()[0]\n # set user and course into member table\n curr.execute(\"INSERT OR REPLACE INTO Member (user_id,course_id,role) VALUES (?,?,?)\", (user_id,course_id,role,))\nconn.commit()" }, { "alpha_fraction": 0.8134328126907349, "alphanum_fraction": 0.8134328126907349, "avg_line_length": 133, "blob_id": "df695f4f3f0a5b4771146c22d69ef2a2bda56612", "content_id": "ff102336fa66820cb526a01a1dd298730586a435", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 134, "license_type": "no_license", "max_line_length": 133, "num_lines": 1, "path": "/PythonForEverybody/course1/README.md", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "this is the course work i did for the Programming for Everybody (Getting Started with Python), the first course of the specialization\n" }, { "alpha_fraction": 0.7068345546722412, "alphanum_fraction": 0.7266187071800232, "avg_line_length": 40.22222137451172, "blob_id": "356b0de1c644ec85998cc39d7f05e8a14938359a", "content_id": "76630d7c300ecbf37a2fcb18f7763f2ae2f3fa77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1112, "license_type": "no_license", "max_line_length": 116, "num_lines": 27, "path": "/PythonForEverybody/course3/CH12-02.py", "repo_name": "docopeland/python-coursera", "src_encoding": "UTF-8", "text": "# Scraping Numbers from HTML using BeautifulSoup\n# The program will use urllib to read the HTML from data files, and parse the data, extracting numbers and compute\n# the sum of the numbers in the file.\n#\n# Data Format\n# The file is a table of names and comment counts. You can ignore most of the data in the file except for lines with\n# span. You are to find all the <span> tags in the file and pull out the numbers from the tag and sum the numbers.\n#\n# <tr><td>Modu</td><td><span class=\"comments\">90</span></td></tr>\n# Sample data: http://py4e-data.dr-chuck.net/comments_42.html (Sum=2553)\n# Actual data: http://py4e-data.dr-chuck.net/comments_1109153.html (Sum ends with 82)\n\n\nimport urllib.request, urllib.parse, urllib.error\nfrom bs4 import BeautifulSoup\nimport re\n\n# getting info from a url\nurl = input(\"Enter URL here: \")\nhtml = urllib.request.urlopen(url).read()\nsoup = BeautifulSoup(html,'html.parser')\n\n# find all the numbers in the span tag and add them\ntags = soup('span')\nvals = [re.findall('>([0-9]+)<',tag.decode()) for tag in tags]\nnums = [int(num) for val in vals for num in val]\nprint(sum(nums))" } ]
45
zabini/flask-rest-api-example
https://github.com/zabini/flask-rest-api-example
7e39e99f88bd10a0b8f59031d900011af2f62b3d
d0fb5a4f65cec7cc849e475a6fd832b8bbb9e173
157d43b188be4717abdabbf9e3f2d733f0f306d8
refs/heads/master
2020-03-14T08:25:50.990326
2018-05-04T16:41:07
2018-05-04T16:41:07
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6510612964630127, "alphanum_fraction": 0.6671295166015625, "avg_line_length": 27.485876083374023, "blob_id": "efc0e603f8cf8f23f2bdf9e8e88481912f9fbf7e", "content_id": "fc4f371932b3dea9b97f0fd6e69ff2c27c03f474", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5041, "license_type": "no_license", "max_line_length": 96, "num_lines": 177, "path": "/routes.py", "repo_name": "zabini/flask-rest-api-example", "src_encoding": "UTF-8", "text": "import datetime\nimport json\nfrom flask import Blueprint,request,jsonify,render_template\n\nimport models\n\n# Routes for clients\nclients_bp = Blueprint('clients', __name__)\n\n@clients_bp.route('/clients', methods=['POST'] )\ndef clients_create( ):\n\n data = request.get_json( )\n\n try:\n client = models.Client(**data)\n except :\n return jsonify({'message' : 'Invalid parameter for client'}), 403\n\n if models.Client.get_one( id=client.id ) != None:\n return jsonify({'message' : 'Resource already exists'}), 409\n\n if not client.add( ) :\n return jsonify({'message' : 'Something is going wrong'}), 500\n\n return jsonify( { 'client' : models.ClientSchema( ).dump(client).data } ), 201\n ## end of clients_create method\n\n\n@clients_bp.route('/clients', methods=['GET'] )\ndef clients_get_all( ):\n\n clientsList = models.Client().get_all( )\n\n return jsonify( { 'clients' : models.ClientSchema(many=True).dump(clientsList).data } ), 200\n ## end of clients_get_all method\n\n\n@clients_bp.route('/clients/<int:id>', methods=['GET'] )\ndef clients_get(id):\n\n client = models.Client.get_one( id=id )\n\n if client == None:\n return jsonify({'message' : 'Resource not found'}), 404\n\n return jsonify( { 'client' : models.ClientSchema( ).dump(client).data } ), 200\n ## end of clients_get method\n\n\n@clients_bp.route('/clients/<int:id>', methods=['PUT'] )\ndef clients_update(id):\n\n data = request.get_json()\n\n client = models.Client.get_one( id=id )\n\n if client == None:\n return jsonify({'message' : 'Resource not found'}), 404\n\n for key in data:\n if hasattr(client,key) and key != 'id' :\n setattr(client,key,data[key])\n\n if not client.update( ) :\n return jsonify({'message' : 'Something is going wrong'}), 500\n\n return jsonify( { 'client' : models.ClientSchema( ).dump(client).data } ), 200\n ## end of clients_update method\n\n\n@clients_bp.route('/clients/<int:id>', methods=['DELETE'] )\ndef clients_delete(id):\n\n client = models.Client.get_one( id=id )\n\n if client == None:\n return jsonify({'message' : 'Resource not found'}), 404\n\n if not client.delete( ) :\n return jsonify({'message' : 'Something is going wrong'}), 500\n\n return 'This content response will not be displayed', 204\n ## end of clients_delete method\n\n# Routes for contacts of clients\ncontacts_bp = Blueprint('contacts', __name__)\n\n@contacts_bp.route('/clients/<int:id>/contacts', methods=['POST'] )\ndef contacts_create(id):\n\n data = request.get_json()\n\n try:\n contact = models.Contact(**data)\n except :\n return jsonify({'message' : 'Invalid parameters for contact'}), 403\n\n if models.Contact.get_one( id=contact.id ) != None:\n return jsonify({'message' : 'Resource already exists'}), 409\n\n contact.client = models.Client().get_one(id=id)\n\n if contact.client == None :\n return jsonify({'message' : 'resource not found'}), 404\n\n if not contact.add( ) :\n return jsonify({'message' : 'Something is going wrong'}), 500\n\n return jsonify( { 'contact' : models.ContactSchema( ).dump(contact).data } ), 201\n ## end of contacts_create method\n\n\n@contacts_bp.route('/clients/<int:id>/contacts', methods=['GET'] )\ndef contacts_search(id):\n\n contactList = models.Contact().get_all(client_id=id)\n\n return jsonify( { 'contacts' : models.ContactSchema(many=True).dump(contactList).data } ), 200\n ## end of contacts_search method\n\n\n@contacts_bp.route('/clients/<int:id>/contacts/<int:contact_id>', methods=['GET'] )\ndef contacts_get(id,contact_id):\n\n contact = models.Contact.get_one( client_id=id, id=contact_id )\n\n if contact == None:\n return jsonify({'message' : 'Resource not found'}), 404\n\n return jsonify( { 'contact' : models.ContactSchema( ).dump(contact).data } ), 200\n ## end of contacts_get method\n\n\n@contacts_bp.route('/clients/<int:id>/contacts/<int:contact_id>', methods=['PUT'] )\ndef contacts_update(id,contact_id):\n\n data = request.get_json()\n \n contact = models.Contact.get_one( client_id=id, id=contact_id )\n\n if contact == None:\n return jsonify({'message' : 'Resource not found'}), 404\n\n for key in data:\n if hasattr(contact,key) and key != 'id' and key != 'client_id' :\n setattr(contact,key,data[key])\n\n if not contact.update( ) :\n return jsonify({'message' : 'Something is going wrong'}), 500\n\n return jsonify( { 'contact' : models.ContactSchema( ).dump(contact).data } ), 200\n ## end of contacts_update method\n\n\n@contacts_bp.route('/clients/<int:id>/contacts/<int:contact_id>', methods=['DELETE'] )\ndef contacts_delete(id,contact_id):\n \n contact = models.Contact.get_one( client_id=id, id=contact_id )\n\n if contact == None:\n return jsonify({'message' : 'Resource not found'}), 404\n\n if not contact.delete( ) :\n return jsonify({'message' : 'Something is going wrong'}), 500\n\n return 'This content response will not be displayed', 204\n ## end of contacts_delete method\n\n# Routes for clients\nstatic_bp = Blueprint('static', __name__)\n\n@static_bp.route('/' )\ndef index():\n year = datetime.date.today()\n return render_template(\"index.html\",date_now=year)\n ## end of index method" }, { "alpha_fraction": 0.7156398296356201, "alphanum_fraction": 0.7156398296356201, "avg_line_length": 41.20000076293945, "blob_id": "64ef8b9c8c3760e8de83f1a8f73ef325e32b1789", "content_id": "4e43da1b5c274a1f10434627531126deb3396231", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 211, "license_type": "no_license", "max_line_length": 61, "num_lines": 5, "path": "/configs.py", "repo_name": "zabini/flask-rest-api-example", "src_encoding": "UTF-8", "text": "def create_configs( app ) :\n app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'\n app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True\n return app\n" }, { "alpha_fraction": 0.6186943650245667, "alphanum_fraction": 0.6226508617401123, "avg_line_length": 19.59183692932129, "blob_id": "29d9fd7f54eb99a9a230dc7eb8a47b7804320fbf", "content_id": "b29a71ee89e55e95fec7301e48f0908fcc2eef95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2022, "license_type": "no_license", "max_line_length": 87, "num_lines": 98, "path": "/models.py", "repo_name": "zabini/flask-rest-api-example", "src_encoding": "UTF-8", "text": "from app import db,ma\nfrom flask_sqlalchemy import SQLAlchemy\n\nclass Client(db.Model):\n\n id = db.Column(db.Integer, primary_key=True,index=True)\n name = db.Column(db.String(100))\n observation = db.Column(db.Text)\n contacts = db.relationship('Contact', backref='client', cascade='all, delete-orphan')\n\n def add(self):\n try:\n db.session.add(self)\n db.session.commit()\n return True\n except:\n return False\n\n def update(self):\n try:\n db.session.commit()\n return True\n except:\n return False\n\n def delete(self):\n try:\n db.session.delete(self)\n db.session.commit()\n return True\n except:\n return False\n\n @classmethod\n def get_one(cls,**kwargs):\n try:\n return db.session.query(cls).filter_by(**kwargs).first( )\n except:\n return None\n\n @classmethod\n def get_all(cls,**kwargs):\n try:\n return db.session.query(cls).filter_by(**kwargs).all( )\n except:\n return None\n\nclass Contact(db.Model):\n\n id = db.Column(db.Integer, primary_key=True,index=True)\n type = db.Column(db.String(10))\n value = db.Column(db.String(100))\n client_id = db.Column(db.Integer, db.ForeignKey('client.id'),nullable=False)\n \n def add(self):\n try:\n db.session.add(self)\n db.session.commit()\n return True\n except:\n return False\n \n def update(self):\n try:\n db.session.commit()\n return True\n except:\n return False\n \n def delete(self):\n try:\n db.session.delete(self)\n db.session.commit()\n return True\n except:\n return False\n\n @classmethod\n def get_one(cls,**kwargs):\n try:\n return db.session.query(cls).filter_by(**kwargs).first( )\n except:\n return None\n\n @classmethod\n def get_all(cls,**kwargs):\n try:\n return db.session.query(cls).filter_by(**kwargs).all( )\n except:\n return None\n\nclass ClientSchema(ma.ModelSchema):\n class Meta:\n model = Client \n\nclass ContactSchema(ma.ModelSchema):\n class Meta:\n model = Contact\n " }, { "alpha_fraction": 0.7553191781044006, "alphanum_fraction": 0.758865237236023, "avg_line_length": 25.904762268066406, "blob_id": "1bb9bac0474f96999dc4b8bd02920a355ef88b7f", "content_id": "a97ce5f90897b8bc08d16a784b145dc42f93b6be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 564, "license_type": "no_license", "max_line_length": 56, "num_lines": 21, "path": "/app.py", "repo_name": "zabini/flask-rest-api-example", "src_encoding": "UTF-8", "text": "from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_marshmallow import Marshmallow\nfrom configs import create_configs\n\napp = Flask(__name__,template_folder='static')\napp = create_configs(app)\n\ndb = SQLAlchemy(app,session_options={'autoflush': True})\nma = Marshmallow(app)\n\nfrom models import *\n\n# import routes from file\nfrom routes import clients_bp,contacts_bp,static_bp\napp.register_blueprint( clients_bp )\napp.register_blueprint( contacts_bp )\napp.register_blueprint( static_bp )\n\nif __name__ == \"__main__\":\n app.run(debug=True,port=80)" } ]
4
dimakuv/python-algos
https://github.com/dimakuv/python-algos
057026f9aafa0b78603dfe61b52763d71f777671
911e36837cbbf6f6d12ec9417a730284a1daf7e2
655ca78ee809f5edc6af7f4d0259cb5ecb50fa23
refs/heads/master
2021-01-22T21:23:08.187503
2017-06-20T12:26:23
2017-06-20T12:26:23
85,424,262
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5432224869728088, "alphanum_fraction": 0.554475724697113, "avg_line_length": 36.61538314819336, "blob_id": "2e7fa6edd889b4dc8ca11fe115254e2707c4f0b1", "content_id": "288e4a6e4a54f7269d1eda3e0762ffd158d93afa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1955, "license_type": "permissive", "max_line_length": 117, "num_lines": 52, "path": "/shortestpath/dijkstra.py", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "# shortest path for graphs without negative cycles\n# NOTE: we use a simple list instead of minheap for simplicity;\n# this gives O(V^2 + E) = O(V^2)\n\nfrom collections import OrderedDict\nfrom spvertex import SPVertex\n\ndef extractmin(queue):\n # find vertex with minimal distance; O(V)\n resi,resv = 0,queue[0]\n for i,v in enumerate(queue):\n if v.dist is not None and (resv.dist is None or v.dist < resv.dist):\n resi = i\n resv = v\n # remove this vertex from queue (don't care about order)\n queue[resi], queue[-1] = queue[-1], queue[resi]\n del queue[-1]\n return resv\n\ndef shortestpath(G, W, s, t=None):\n \"\"\"shortest path from start vertex s to end vertex t (or to all reachable if t=None)\"\"\"\n # initialize\n for v in G.keys():\n v.reset()\n s.dist = 0\n # go through all vertices in order of increasing dist and relax their edges; O(V^2)\n queue = G.keys()\n while len(queue) > 0:\n u = extractmin(queue)\n if t == u:\n break\n for i, v in enumerate(G[u]):\n v.relax(u, W[u][i])\n\ndef printshortestpath(s, t):\n \"\"\"print shortest path from s to t; shortestpath(.., s) must be run previously\"\"\"\n if t.dist is None:\n print \"No path found from %s to %s\" % (str(s), str(t))\n return\n sp = [t]\n while sp[-1].pi:\n sp.append(sp[-1].pi)\n print \"shortestpath:\", \"->\".join([str(v) for v in reversed(sp)]), \"(dist = %d)\" % t.dist\n\n\ndef test():\n a = SPVertex('a'); b = SPVertex('b'); c = SPVertex('c'); d = SPVertex('d'); e = SPVertex('e'); f = SPVertex('f');\n g = SPVertex('g'); h = SPVertex('h'); i = SPVertex('i'); j = SPVertex('j'); k = SPVertex('k'); l = SPVertex('l');\n G = OrderedDict([ (a,[b, c]), (b,[c, d]), (c,[d, e, f]), (d,[ e, f]), (e,[ f]), (f,[]) ])\n W = OrderedDict([ (a,[5, 3]), (b,[2, 6]), (c,[7, 4, 2]), (d,[-1, 1]), (e,[-2]), (f,[]) ])\n shortestpath(G, W, b)\n printshortestpath(b, f)" }, { "alpha_fraction": 0.5321229100227356, "alphanum_fraction": 0.5502793192863464, "avg_line_length": 22.899999618530273, "blob_id": "aca183cfe492582ec325eec7c25a44b34fdee6c8", "content_id": "2cba971472bea8861411f39ebe99fbb660037614", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 716, "license_type": "permissive", "max_line_length": 64, "num_lines": 30, "path": "/sorting/counting.py", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "# counting sort (simple one-digit int)\n\nDIGITS = 10\n\ndef sort(a, digit = 0):\n freq = []\n for k in range(DIGITS):\n freq.append(0)\n\n # frequency of each digit in a + init res\n res = []\n for i in range(len(a)):\n d = (a[i]/10**digit) % DIGITS\n freq[d] += 1\n res.append(0)\n\n # cummulative frequency of each digit\n for k in range(1, len(freq)):\n freq[k] += freq[k-1]\n\n # reverse-populate res array based on cummulated frequencies\n # (reverse to preserve stability)\n for i in reversed(xrange(len(a))):\n d = (a[i]/10**digit) % DIGITS\n freq[d] -= 1\n idx = freq[d]\n res[idx] = a[i]\n\n # it was clearly not in-place\n return res" }, { "alpha_fraction": 0.5047089457511902, "alphanum_fraction": 0.5075456500053406, "avg_line_length": 39.063636779785156, "blob_id": "b86eb2cd665d6f8cfb5ec08c30ff2dfb1b0133e4", "content_id": "43aaf6b7e8a5c0bcb96608f9d063490829e7acb5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8813, "license_type": "permissive", "max_line_length": 100, "num_lines": 220, "path": "/tree/rb.py", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "# balanced Red-Black (RB) tree\n# NOTE: RB trees are surprisingly hard to wrap your head around, and I personally\n# dislike them, thus no attempts to make the following code look nice\n\n# for reuse of left & right rotates, inherit RB from AVL trees\nfrom avl import *\n\nclass Color:\n Black = 0\n Red = 1\n\nclass RBNode(Node):\n def __init__(self, key):\n Node.__init__(self, key)\n self.color = Color.Red # by agreement, all new nodes are Red\n\n def __str__(self):\n s = \"\"\n s += str(self.key) + \":\" + str(self.color)\n s += \" -> ( \"\n s += str(self.left) if self.left else \"--\"\n s += \" , \"\n s += str(self.right) if self.right else \"--\"\n s += \" ) \"\n return s\n\n\ndef getcolor(node):\n return node.color if (node and isinstance(node, RBNode)) else Color.Black\n\n\nclass RBTree(AVLTree):\n \"\"\"\n Red-Black trees have the following four invariants:\n 1. Every RBNode has either Black or Red color\n 2. Root is always Black; None nodes are always Black\n 3. There can be no two adjacent Red nodes (i.e., no parent-child can be both Red)\n 4. Each path from any node to leaf has same number of Black nodes\n \"\"\"\n\n def rebalanceinsert(self, node):\n \"\"\"based on RB-Insert-Fixup() from Introduction to Algorithms book\"\"\"\n if node == None:\n return\n\n while getcolor(node.parent) == Color.Red:\n # at this point, node's parent is Red, node's grandpa exists and is Black\n parent = node.parent\n grandpa = parent.parent\n uncle = grandpa.left if grandpa.right == parent else grandpa.right\n\n if getcolor(uncle) == Color.Red:\n # case 1: me, my parent, and my uncle are Red, grandpa is Black\n # --> enough to recolor and move upwards to check grandpa\n parent.color = Color.Black\n uncle.color = Color.Black\n grandpa.color = Color.Red\n node = grandpa\n else:\n # cases 2 & 3: parent is Red, grandpa is Black, and uncle is Black\n # --> rebalance & recolor them\n if grandpa.left == parent:\n if parent.right == node:\n # case 2: left rotate first\n node = parent\n self.leftrotate(node)\n # fall-through to case 3: right rotate and done\n node.parent.color = Color.Black\n node.parent.parent.color = Color.Red\n self.rightrotate(node.parent.parent)\n else:\n if parent.left == node:\n node = parent\n self.rightrotate(node)\n node.parent.color = Color.Black\n node.parent.parent.color = Color.Red\n self.leftrotate(node.parent.parent)\n\n self.root.color = Color.Black\n\n def insertnode(self, node):\n BinarySearchTree.insertnode(self, node)\n self.rebalanceinsert(node)\n\n def insert(self, key):\n node = RBNode(key)\n self.insertnode(node)\n\n def rebalancedelete(self, node, parent):\n \"\"\"\n based on RB-Delete-Fixup() from Introduction to Algorithms book\n NOTE: we don't use special Nil node, so we add `parent` argument\n \"\"\"\n if node == None or parent == None:\n return\n\n while node != self.root and getcolor(node) == Color.Black:\n if node == parent.left:\n sibling = parent.right\n if getcolor(sibling) == Color.Red:\n # case 1: me and my parent are Black, sibling is Red\n # --> recolor & left rotate to make sibling Black and\n # fall-through to cases 2-4\n sibling.color = Color.Black\n parent.color = Color.Red\n self.leftrotate(parent)\n sibling = parent.right\n\n if getcolor(sibling.left) == Color.Black and getcolor(sibling.right) == Color.Black:\n # case 2: me and my sibling are Black, and both his children are Black\n # --> recolor sibling to Red, thus removing my double-blackness\n # (may lead to two adjacent Reds, so recurse)\n sibling.color = Color.Red\n node = parent\n parent = node.parent\n else:\n if getcolor(sibling.right) == Color.Black:\n # case 3: me and my sibling are Black, but his left child is Red\n # --> recolor and rotate to make his right child Red and\n # fall-through to case 4\n sibling.left.color = Color.Black\n sibling.color = Color.Red\n self.rightrotate(sibling)\n sibling = parent.right\n # case 4: me and my sibling are Black, his right child is Red\n # --> remove my double-blackness by recoloring & rotation\n sibling.color = parent.color\n parent.color = Color.Black\n sibling.right.color = Color.Black\n self.leftrotate(parent)\n node = self.root # for loop-exit condition\n\n else:\n sibling = parent.left\n if getcolor(sibling) == Color.Red:\n # case 1: me and my parent are Black, sibling is Red\n # --> recolor & right rotate to make sibling Black and\n # fall-through to cases 2-4\n sibling.color = Color.Black\n parent.color = Color.Red\n self.rightrotate(parent)\n sibling = parent.left\n\n if getcolor(sibling.left) == Color.Black and getcolor(sibling.right) == Color.Black:\n # case 2: me and my sibling are Black, and both his children are Black\n # --> recolor sibling to Red, thus removing my double-blackness\n # (may lead to two adjacent Reds, so recurse)\n sibling.color = Color.Red\n node = parent\n parent = node.parent\n else:\n if getcolor(sibling.left) == Color.Black:\n # case 3: me and my sibling are Black, but his right child is Red\n # --> recolor and rotate to make his left child Red and\n # fall-through to case 4\n sibling.right.color = Color.Black\n sibling.color = Color.Red\n self.leftrotate(sibling)\n sibling = parent.left\n # case 4: me and my sibling are Black, his left child is Red\n # --> remove my double-blackness by recoloring & rotation\n sibling.color = parent.color\n parent.color = Color.Black\n sibling.left.color = Color.Black\n self.rightrotate(parent)\n node = self.root # for loop-exit condition\n\n node.color = Color.Black\n\n def deletenode(self, node):\n if node == None:\n return\n\n removed = node\n removedcolor = getcolor(removed)\n\n if node.left == None:\n replace = node.right\n replaceparent = node\n self.rewireparent(node, node.right)\n elif node.right == None:\n replace = node.left\n replaceparent = node\n self.rewireparent(node, node.left)\n else:\n removed = self.next(node)\n removedcolor = getcolor(removed)\n\n replace = removed.right\n replaceparent = removed\n\n if removed.parent != node:\n self.rewireparent(removed, removed.right)\n removed.right = node.right\n node.right.parent = removed\n\n self.rewireparent(node, removed)\n removed.left = node.left\n removed.left.parent = removed\n removed.color = node.color\n\n self.updatesizes(node)\n\n if removedcolor == Color.Black:\n self.rebalancedelete(replace, replaceparent)\n\ndef sort(a):\n rb = RBTree()\n\n for key in a:\n rb.insert(key)\n\n node = rb.findmin()\n res = []\n while node:\n res.append(node.key)\n node = rb.next(node)\n\n # not in-place\n return res" }, { "alpha_fraction": 0.4560260474681854, "alphanum_fraction": 0.47231268882751465, "avg_line_length": 20.964284896850586, "blob_id": "a97265f4d5d842991ba88adc414b59df64dea5ed", "content_id": "feb9a9de50eee4612638fa233d8839f8b14a1630", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 614, "license_type": "permissive", "max_line_length": 57, "num_lines": 28, "path": "/sorting/merge.py", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "# merge sort\n\ndef sort(a):\n if len(a) == 1:\n return a\n\n # step 1: sort left and right recursively\n l, r = sort(a[:len(a)/2]), sort(a[len(a)/2:])\n\n # step 2: use two-finger traversal to combine l and r\n res = []\n li, ri = 0, 0\n while li < len(l) and ri < len(r):\n if l[li] <= r[ri]:\n res.append(l[li])\n li += 1\n else:\n res.append(r[ri])\n ri += 1\n\n # step 3: add the rest from l or r\n if li < len(l):\n res.extend(l[li:])\n if ri < len(r):\n res.extend(r[ri:])\n\n # it was clearly not in-place\n return res" }, { "alpha_fraction": 0.5068881511688232, "alphanum_fraction": 0.5081037282943726, "avg_line_length": 24.448453903198242, "blob_id": "e37c2dae079a2a6369c56280d9743a04c2fc5f0e", "content_id": "cdd4fd502874112bc27e8db942284b4dc7727d0f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4936, "license_type": "permissive", "max_line_length": 73, "num_lines": 194, "path": "/tree/bst.py", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "# simple unbalanced Binary Search Tree (BST)\n\nclass Node(object):\n\n def __init__(self, key):\n self.parent = None\n self.left = None\n self.right = None\n self.size = 1\n self.key = key\n\n def __str__(self):\n s = \"\"\n s += str(self.key)\n s += \" -> ( \"\n s += str(self.left) if self.left else \"--\"\n s += \" , \"\n s += str(self.right) if self.right else \"--\"\n s += \" ) \"\n return s\n\n\nclass BinarySearchTree(object):\n\n def __init__(self):\n self.root = None\n\n def findpair(self, key, node, parent):\n \"\"\"a pair <found Node or None, parent>\"\"\"\n if node == None:\n return (None, parent)\n if key == node.key:\n return (node, parent)\n elif key < node.key:\n return self.findpair(key, node.left, node)\n else:\n return self.findpair(key, node.right, node)\n\n def find(self, key):\n \"\"\"found Node or None\"\"\"\n if self.root == None:\n return None\n return self.findpair(key, self.root, None)[0]\n\n def __findmin(self, node):\n while node and node.left:\n node = node.left\n return node\n\n def findmin(self):\n return self.__findmin(self.root)\n\n def __findmax(self, node):\n while node and node.right:\n node = node.right\n return node\n\n def findmax(self):\n return self.__findmax(self.root)\n\n def next(self, node):\n if node == None:\n return None\n if node.right:\n return self.__findmin(node.right)\n while node.parent and node.parent.left != node:\n node = node.parent\n return node.parent\n\n def prev(self, node):\n if node == None:\n return None\n if node.left:\n return self.__findmax(node.left)\n while node.parent and node.parent.right != node:\n node = node.parent\n return node.parent\n\n def updatesizes(self, node):\n while node and node.parent:\n node = node.parent\n node.size = 1\n if node.left:\n node.size += node.left.size\n if node.right:\n node.size += node.right.size\n\n def insertnode(self, node):\n \"\"\"insert node in BST if no existing node already\"\"\"\n assert node == None or isinstance(node, Node)\n\n if self.root == None:\n self.root = node\n\n found, parent = self.findpair(node.key, self.root, None)\n if found:\n return False\n\n assert parent != None\n node.parent = parent\n if node.key < parent.key:\n assert parent.left == None\n parent.left = node\n else:\n assert parent.right == None\n parent.right = node\n\n self.updatesizes(node)\n return True\n\n def insert(self, key):\n node = Node(key)\n self.insertnode(node)\n\n def rewireparent(self, node, newnode):\n \"\"\"detach node and make a link between node.parent and newnode\"\"\"\n if newnode:\n newnode.parent = node.parent\n if node == self.root:\n self.root = newnode\n return\n if node.parent.left == node:\n node.parent.left = newnode\n else:\n node.parent.right = newnode\n\n def deletenode(self, node):\n if node == None:\n return\n\n if node.left == None:\n self.rewireparent(node, node.right)\n elif node.right == None:\n self.rewireparent(node, node.left)\n else:\n replace = self.next(node)\n\n if replace.parent != node:\n self.rewireparent(replace, replace.right)\n replace.right = node.right\n node.right.parent = replace\n\n self.rewireparent(node, replace)\n replace.left = node.left\n node.left.parent = replace\n\n self.updatesizes(node)\n\n def delete(self, key):\n node = self.find(key)\n self.deletenode(node)\n\n def size(self):\n \"\"\"total number of nodes in the tree\"\"\"\n if self.root == None:\n return 0\n return self.root.size\n\n def rank(self, key):\n \"\"\"number of nodes less than or equal to key\"\"\"\n res = 0\n\n node = self.root\n while node:\n if key < node.key:\n node = node.left\n else:\n res += 1\n if node.left:\n res += node.left.size\n if key == node.key:\n break\n node = node.right\n\n return res\n\n def __str__(self):\n return str(self.root) + \".\"\n\n\ndef sort(a):\n bst = BinarySearchTree()\n\n for key in a:\n bst.insert(key)\n\n node = bst.findmin()\n res = []\n while node:\n res.append(node.key)\n node = bst.next(node)\n\n # not in-place\n return res" }, { "alpha_fraction": 0.4915558695793152, "alphanum_fraction": 0.5282069444656372, "avg_line_length": 27.69072151184082, "blob_id": "e3b38116eeffa50e094419dce5e5299b0b6cd3d3", "content_id": "3f048e036cbe8d8d00f42ff8e5f4a0abe45490dc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2783, "license_type": "permissive", "max_line_length": 94, "num_lines": 97, "path": "/hashtable/openaddressing.py", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "# hash table with open addressing (simple, all objects = their int keys)\n\ndef hash1(x):\n return x % 11\n\ndef hash2(x):\n return x % 7 + 1\n\nDELETED = -1 # assume that hashtable items are always non-negative\n\nclass HashTable(object):\n\n def __init__(self):\n self.n = 0 # number of elements\n self.m = 4 # number of slots, always power of 2\n self.slots = [None] * self.m\n\n def doublehash(self, x, i):\n return (hash1(x) + i*hash2(x)) % self.m\n\n def resize(self, newm):\n oldm = self.m\n oldslots = self.slots\n self.m = newm\n self.n = 0\n self.slots = [None] * self.m\n for k in range(oldm):\n if oldslots[k] is not None and oldslots[k] != DELETED:\n self.insert(oldslots[k])\n\n def search(self, x):\n \"\"\"returns item index in underlying slots array\"\"\"\n i = 0\n while i < self.m:\n idx = self.doublehash(x, i)\n if self.slots[idx] == x:\n return idx\n i += 1\n return None\n\n def insert(self, x):\n \"\"\"returns True if successfully inserted (found empty slot and not already present)\"\"\"\n res = False\n i = 0\n while i < self.m:\n idx = self.doublehash(x, i)\n if self.slots[idx] == x:\n return False\n if self.slots[idx] == None or self.slots[idx] == DELETED:\n self.slots[idx] = x\n self.n += 1\n res = True\n break\n i += 1\n # need resizing (if half-full or could not insert)\n # -> rehash all items and move to 2m array\n if res == False or (self.n*100)/self.m >= 50:\n self.resize(self.m*2)\n return res\n\n def delete(self, x):\n \"\"\"returns True if successfully deleted (found x)\"\"\"\n idx = self.search(x)\n if idx == None:\n return False\n self.slots[idx] = DELETED\n self.n -= 1\n # need resizing (if 1/4-full) -> rehash all items and move to m/2 array\n if self.m > 4 and (self.n*100)/self.m <= 25:\n self.resize(self.m/2)\n return True\n\ndef test():\n h = HashTable()\n h.insert(0)\n h.insert(1)\t\n h.insert(7)\n h.insert(24)\t\n print \"after 4 inserts: \", h.slots\n h.insert(42)\t\n h.insert(558)\t\n h.insert(16961)\t\n h.insert(16963)\t\n print \"after 8 inserts: \", h.slots\n print \"searching for 7: \", h.search(7)\n print \"searching for 16962: \", h.search(16962)\t\n print \"searching for 16961: \", h.search(16961)\n h.delete(16963)\n h.delete(16961)\t\n h.delete(558)\t\n h.delete(42)\t\n print \"after 4 deletes: \", h.slots\n h.delete(24)\t\n h.delete(7)\n h.delete(1)\t\n h.delete(0)\n print \"after 8 deletes: \", h.slots\n" }, { "alpha_fraction": 0.5388141870498657, "alphanum_fraction": 0.5406479239463806, "avg_line_length": 29.58878517150879, "blob_id": "a1901ef61fb00097b10b10302c6010dcd9e7d251", "content_id": "ffcb4b18ef9509e2aa10d4f37221adb6a5b5d536", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3272, "license_type": "permissive", "max_line_length": 92, "num_lines": 107, "path": "/tree/avl.py", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "# balanced AVL tree\n\nfrom bst import *\n\nclass AVLNode(Node):\n def __init__(self, key):\n Node.__init__(self, key)\n self.height = 0\n\n\ndef getheight(node):\n return node.height if (node and isinstance(node, AVLNode)) else -1\n\n\nclass AVLTree(BinarySearchTree):\n\n def leftrotate(self, x):\n \"\"\"change subtree of form x->(A, y->(B,C)) to y->(x->(A,B), C); O(1)\"\"\"\n if x == None or x.right == None:\n return\n y = x.right\n self.rewireparent(x, y)\n x.parent = y\n x.right = y.left\n y.left = x\n if x.right:\n x.right.parent = x\n\n def rightrotate(self, y):\n \"\"\"change subtree of form y->(x->(A,B), C) to x->(A, y->(B,C)); O(1)\"\"\"\n if y == None or y.left == None:\n return\n x = y.left\n self.rewireparent(y, x)\n y.parent = x\n y.left = x.right\n x.right = y\n if y.left:\n y.left.parent = y\n\n def rebalance(self, node):\n \"\"\"starting from node, fix AVL property if violated and move upwards; O(lg n)\"\"\"\n if node == None:\n return\n\n if abs(getheight(node.left) - getheight(node.right)) > 1:\n # violated property of \"height of one child at most one greater than of another\"\n if getheight(node.right) > getheight(node.left):\n if getheight(node.right.right) >= getheight(node.right.left):\n # node.right is right-heavy (or balanced): straight-line simple case\n self.leftrotate(node)\n else:\n # node.right is left-heavy: zigzag complex case\n self.rightrotate(node.right)\n self.leftrotate(node)\n else:\n if getheight(node.left.left) >= getheight(node.left.right):\n # node.left is left-heavy (or balanced): straight-line simple case\n self.rightrotate(node)\n else:\n # node.left is right-heavy: zigzag complex case\n self.leftrotate(node.left)\n self.rightrotate(node)\n\n node.height = max(getheight(node.left), getheight(node.right)) + 1\n self.rebalance(node.parent)\n\n def insertnode(self, node):\n if BinarySearchTree.insertnode(self, node):\n self.rebalance(node)\n\n def insert(self, key):\n node = AVLNode(key)\n self.insertnode(node)\n\n def deletenode(self, node):\n if node == None:\n return\n\n rebalancenode = None\n if node.left == None or node.right == None:\n # simple cases of node del: rebalance starting from node's parent\n rebalancenode = node.parent\n else:\n # complex case with two children: rebalance starting from next()'s parent\n rebalancenode = self.next(node)\n if rebalancenode:\n rebalancenode = rebalancenode.parent\n\n BinarySearchTree.deletenode(self, node)\n self.rebalance(rebalancenode)\n\n\ndef sort(a):\n avl = AVLTree()\n\n for key in a:\n avl.insert(key)\n\n node = avl.findmin()\n res = []\n while node:\n res.append(node.key)\n node = avl.next(node)\n\n # not in-place\n return res" }, { "alpha_fraction": 0.6113207340240479, "alphanum_fraction": 0.6226415038108826, "avg_line_length": 16.66666603088379, "blob_id": "ed6a527736a4befdc41bfb37017bafcb9eb8e36e", "content_id": "3ab5da87814708a6a1676f9755ef9f68e7a86ac2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 265, "license_type": "permissive", "max_line_length": 49, "num_lines": 15, "path": "/test.py", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport sys\nimport random\nimport importlib\n\ntry:\n MODULE = importlib.import_module(sys.argv[1])\n test = getattr(MODULE, \"test\")\n print \"=====\", sys.argv[1], \"test =====\"\nexcept:\n print \"[do nothing]\"\n sys.exit(0)\n\nMODULE.test()\n" }, { "alpha_fraction": 0.5154638886451721, "alphanum_fraction": 0.524836003780365, "avg_line_length": 24.710844039916992, "blob_id": "4330a8e0dc6c22f389534fba42f11aa7993be7be", "content_id": "cafc98d972d2af36fba45b61bb72251649699e88", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2134, "license_type": "permissive", "max_line_length": 80, "num_lines": 83, "path": "/heap/nodeheap.py", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "# abstract heap, minheap, and maxheap -- implementations using Node objects\n# NOTE: with Node objects, can support delete() operation with O(lg n)\n\nclass Node(object):\n __slots__ = ['value', 'heap', 'idx']\n def __init__(self, value):\n self.value = value\n\ndef parent(i):\n return (i-1)//2\n\ndef left(i):\n return i*2+1\n\ndef right(i):\n return i*2+2\n\nclass AbstractHeap(object):\n def __init__(self):\n self.a = []\n\n def compare(self, l, r):\n raise NotImplementedError(\"AbstractHeap does not implement comparison!\")\n\n def swap(self, i, j):\n self.a[i].idx = j\n self.a[j].idx = i\n self.a[i], self.a[j] = self.a[j], self.a[i]\n\n def upheap(self, i):\n if i == 0: return\n p = parent(i)\n if self.compare(self.a[i], self.a[p]):\n self.swap(i, p)\n self.upheap(p)\n\n def downheap(self, i):\n l, r = left(i), right(i)\n toswap = i\n if l < len(self.a) and self.compare(self.a[l], self.a[toswap]):\n toswap = l\n if r < len(self.a) and self.compare(self.a[r], self.a[toswap]):\n toswap = r\n if toswap != i:\n self.swap(i, toswap)\n self.downheap(toswap)\n\n def insert(self, v):\n i = len(self.a)\n v.heap = self\n v.idx = i\n self.a.append(v)\n self.upheap(i)\n\n def peek(self):\n return self.a[0].value if len(self.a) > 0 else 1000\n\n def extract(self):\n if len(self.a) == 1: return self.a.pop()\n res = self.a[0]\n self.a[0] = self.a.pop()\n self.downheap(0)\n return res\n\n def delete(self, node):\n idx = node.idx\n if idx == len(self.a)-1:\n self.a.pop()\n return\n self.swap(idx, len(self.a)-1)\n self.a.pop()\n if idx != 0 and self.compare(self.a[idx], self.a[parent(idx)]):\n self.upheap(idx)\n else:\n self.downheap(idx)\n\nclass MaxHeap(AbstractHeap):\n def compare(self, l, r):\n return l.value > r.value\n\nclass MinHeap(AbstractHeap):\n def compare(self, l, r):\n return l.value < r.value\n" }, { "alpha_fraction": 0.43508583307266235, "alphanum_fraction": 0.43830472230911255, "avg_line_length": 26.82089614868164, "blob_id": "98f6124377da89cef28b98aa64f5bf55b5de746e", "content_id": "dd6e6e5e6355feef0dc4eb7dd70efaf3b616342d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1864, "license_type": "permissive", "max_line_length": 113, "num_lines": 67, "path": "/graph/bfs.py", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "# Breadth-First Search (BFS)\n\nfrom collections import deque\nfrom vertex import Vertex\n\nclass Graph(object):\n\n def __init__(self, G):\n self.G = G\n\n def __str__(self):\n s = \"\"\n for v in self.G.keys():\n s += \"%s: %d %s %d %d\\n\" % (v.name, v.level, str(v.parent), v.start, v.finish)\n return s\n\n def reset(self):\n for v in self.G.keys():\n v.reset()\n\n def BFS(self, s):\n self.reset()\n queue = deque([s])\n s.level = 0\n s.start = 0\n\n timestamp = 0\n while len(queue):\n v = queue.popleft()\n for u in self.G[v]:\n if u.start == None:\n u.level = v.level + 1\n u.parent = v\n timestamp += 1\n u.start = timestamp\n queue.append(u)\n timestamp += 1\n v.finish = timestamp\n\n def shortestpath(self, s, f):\n path = []\n v = f\n while v:\n path.append(v)\n if v == s: break\n v = v.parent\n else:\n print \"shortest path:\", \"No path from\", str(s), \"to\", str(f)\n return\n print \"shortest path:\", \"->\".join([str(v) for v in reversed(path)])\n\n\ndef test():\n a = Vertex('a'); s = Vertex('s'); c = Vertex('c'); d = Vertex('d'); b = Vertex('b');\n z = Vertex('z'); x = Vertex('x'); v = Vertex('v'); f = Vertex('f'); e = Vertex('e');\n # undirected graph\n G = Graph( { a: [s, z], z: [a], s: [a, x], x: [s, d, c], d: [x, c, f], c: [x,d,f,v], f: [d,c,v], v: [f,c] } )\n G.BFS(s)\n G.shortestpath(s, f)\n G.shortestpath(s, v)\n G.shortestpath(s, z)\n # directed graph\n G = Graph( { a: [b, c], b: [d], c: [d, f], d: [e], e: [], f: [] } )\n G.BFS(a)\n G.shortestpath(a, e)\n G.shortestpath(a, f)\n G.shortestpath(s, e)\n" }, { "alpha_fraction": 0.5199999809265137, "alphanum_fraction": 0.6240000128746033, "avg_line_length": 15.733333587646484, "blob_id": "620cb63730a9024528fc72f8dbdbb1af57df25d5", "content_id": "15c7cc6274fccf31d1c1ca8b981d414f2c2ec5a2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 250, "license_type": "permissive", "max_line_length": 50, "num_lines": 15, "path": "/sorting/radix.py", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "# radix sort (simple, up to 1,000)\n\n# radix relies on counting for one-digit sort\nimport counting\n\nDIGITS = 3\n\ndef sort(a):\n for i in range(DIGITS):\n a = counting.sort(a, i)\n\n return a\n\n\ntestlist = [123, 321, 58, 255, 1, 0, 132, 59, 254]" }, { "alpha_fraction": 0.46073299646377563, "alphanum_fraction": 0.519371747970581, "avg_line_length": 33.10714340209961, "blob_id": "a201134b7b543ca9398cb89295a8ea524e29b02c", "content_id": "14b94d2127baca7e7c14a067010c13a1c77b1ee6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 955, "license_type": "permissive", "max_line_length": 85, "num_lines": 28, "path": "/stuff/stuff.py", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "# random simple math problems\n\n# Greatest Common Divisor (GCD), Euclidean method (division)\ndef gcd(a, b):\n while b != 0:\n a, b = b, a % b\n return a\n\n# Least Common Multiple (LCM), via GCD\ndef lcm(a, b):\n if a == 0 and b == 0:\n return 0\n return abs(a*b)/gcd(a, b)\n\n# side of the line determined by (xa,ya) and (xb,yb) on which point (x,y) lies\n# returns positive number if on \"plus\" side, negative if on \"neg\" side, 0 if on line\ndef pointside(xa, ya, xb, yb, x, y):\n return (xa-xb)*(y-ya) - (ya - yb)*(x-xa)\n\ndef test():\n pairs = [(0, 0), (0, 1), (1, 0), (21, 6), (1071, 462), (462, 1071), (1386, 3213)]\n for a,b in pairs:\n print \"%d\\t%d\\t: gcd=%d\\t lcm=%d\" % (a, b, gcd(a,b), lcm(a,b))\n\n points = [(0, 0), (2, 2), (2, 1), (1, 2), (3, 1), (2, 3)]\n for x,y in points:\n print \"line from (%d,%d) and (%d,%d): point (%d,%d) is on side %d\" % \\\n (1,1, 3,3, x,y, pointside(1, 1, 3, 3, x, y))\n" }, { "alpha_fraction": 0.5266106724739075, "alphanum_fraction": 0.593837559223175, "avg_line_length": 16.414634704589844, "blob_id": "f4b4a574568c0ded992e2e90905d3b296d198da4", "content_id": "f8cdf838ed55e4684cd9bcce9491f080681a5561", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 714, "license_type": "permissive", "max_line_length": 54, "num_lines": 41, "path": "/testsort.py", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport sys\nimport random\nimport importlib\n\ndef baseline(a):\n a.sort()\n return a\n\ndef test(a):\n print SORTFUNCSTR, \": \",\n print a,\n\n a = SORTFUNC(a)\n\n # check invariant\n for i in range(1, len(a)):\n assert a[i] >= a[i-1]\n\n print \" --> \",\n print a\n\n\nSORTFUNC = baseline\nSORTFUNCSTR = \"baseline\"\nif len(sys.argv) > 1:\n SORTFUNCSTR = sys.argv[1]\n SORTMODULE = importlib.import_module(SORTFUNCSTR)\n SORTFUNC = SORTMODULE.sort\n\ntest([0,1,2,3,4,5,6,7,8,9])\ntest([9,8,7,6,5,4,3,2,1,0])\ntest([1,1,1,1,1,1,1,1,1,1])\ntest([1,2,3,4,3,2,1,4,3,2])\ntest([int(10*random.random()) for i in xrange(10)])\n\ntry:\n test(SORTMODULE.testlist)\nexcept:\n pass\n" }, { "alpha_fraction": 0.5093708038330078, "alphanum_fraction": 0.5180723071098328, "avg_line_length": 33.74418640136719, "blob_id": "bc2d4274ab0095a9146b375fdc16f9768bd14454", "content_id": "99ad2ea1125ee37e8a898d19d5642e319f979efc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1494, "license_type": "permissive", "max_line_length": 117, "num_lines": 43, "path": "/shortestpath/dag.py", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "# shortest path for a special case of DAGs\n# -> enough to do toposort and relax each edge\n\nfrom os import sys, path\nsys.path.append(path.dirname(path.dirname(path.abspath(__file__))))\n\nfrom collections import OrderedDict\nfrom spvertex import SPVertex\nfrom graph.dfs import Graph\n\ndef shortestpath(G, W, s, t):\n \"\"\"shortest path from start vertex s to end vertex t\"\"\"\n GDFS = Graph(G)\n GDFS.DFS() # O(V+E)\n\n started = False\n for u in reversed(GDFS.finished): # O(V+E)\n if u == s:\n u.dist = 0\n started = True\n if not started:\n continue\n if u == t:\n break\n for i, v in enumerate(G[u]):\n v.relax(u, W[u][i])\n else:\n if started: print \"No path found from %s to %s\" % (str(s), str(t))\n else: print \"No start vertex %s found\" % str(s)\n return\n\n sp = [t]\n while sp[-1].pi:\n sp.append(sp[-1].pi)\n print \"shortestpath:\", \"->\".join([str(v) for v in reversed(sp)]), \"(dist = %d)\" % t.dist\n\n\ndef test():\n a = SPVertex('a'); b = SPVertex('b'); c = SPVertex('c'); d = SPVertex('d'); e = SPVertex('e'); f = SPVertex('f');\n g = SPVertex('g'); h = SPVertex('h'); i = SPVertex('i'); j = SPVertex('j'); k = SPVertex('k'); l = SPVertex('l');\n G = OrderedDict([ (a,[b, c]), (b,[c, d]), (c,[d, e, f]), (d,[ e, f]), (e,[ f]), (f,[]) ])\n W = OrderedDict([ (a,[5, 3]), (b,[2, 6]), (c,[7, 4, 2]), (d,[-1, 1]), (e,[-2]), (f,[]) ])\n shortestpath(G, W, b, f)\n" }, { "alpha_fraction": 0.5864406824111938, "alphanum_fraction": 0.5864406824111938, "avg_line_length": 14.578947067260742, "blob_id": "3fd358428a4fc1b5632f2c2f0d8895bedc854a1c", "content_id": "893d38e406041318be38248fc13488313cd79c3e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 295, "license_type": "permissive", "max_line_length": 38, "num_lines": 19, "path": "/heap/minheap.py", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "# maxheap\n\nfrom abstractheap import *\n\nclass MinHeap(AbstractHeap):\n \"\"\"priority queue using minheap\"\"\"\n\n def compare(self, l, r):\n return l < r\n\n\ndef sort(a):\n heap = MinHeap(a)\n\n for i in range(len(a)):\n heap.buildmaxheap()\n a[i] = heap.extract()\n\n return a" }, { "alpha_fraction": 0.5926928520202637, "alphanum_fraction": 0.5926928520202637, "avg_line_length": 27.423076629638672, "blob_id": "94c8a1532ee271f70cd3aac1b26d1b2441d851c3", "content_id": "8a3d5b7b6cd6ee9e102fc114189968153ffb471b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 739, "license_type": "permissive", "max_line_length": 67, "num_lines": 26, "path": "/shortestpath/spvertex.py", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "# vertex class augmented for shortest path problem\n\nfrom os import sys, path\nsys.path.append(path.dirname(path.dirname(path.abspath(__file__))))\n\nfrom graph.vertex import Vertex\n\nclass SPVertex(Vertex):\n\n def __init__(self, name):\n Vertex.__init__(self, name)\n self.dist = None # current shortest path distance\n self.pi = None # parent for shortest path\n\n def reset(self):\n Vertex.reset(self)\n self.dist = None\n self.pi = None\n\n def relax(self, u, w):\n \"\"\"relax vertex reachable from u via edge with weight w\"\"\"\n if u.dist is None:\n return\n if self.dist is None or self.dist > u.dist + w:\n self.dist = u.dist + w\n self.pi = u\n" }, { "alpha_fraction": 0.47866666316986084, "alphanum_fraction": 0.503333330154419, "avg_line_length": 26.77777862548828, "blob_id": "e60bb38c1ee2b4ead1992c12e0addf92001b344b", "content_id": "20267b2790b7aa12b7cd58376a28e33d9b8d993c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1500, "license_type": "permissive", "max_line_length": 85, "num_lines": 54, "path": "/dp/knapsack.py", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "# knapsack\n\nHUGENUM = 2**30 # substitute for +Inf, for simplicity\n\nclass Item(object):\n def __init__(self, name, value, weight):\n self.name = name\n self.value = value\n self.weight = weight\n\ndef knapsack(items, S):\n dp = {} # dict of (item idx, remaining S) -> (maximized value, item taken)\n val = knapsack_recurse(dp, items, 0, S)\n print \"for capacity: \", S, \"maximum value:\", val, \" items:\",\n for idx, item in enumerate(items):\n if S <= 0: break\n if dp[(idx, S)][1] == True:\n S -= items[idx].weight\n print items[idx].name,\n print\n\ndef knapsack_recurse(dp, items, i, S):\n if S < 0:\n return -HUGENUM\n if i == len(items):\n return 0\n if dp.get((i, S)) is not None:\n return dp[(i, S)][0]\n taken = items[i].value + knapsack_recurse(dp, items, i+1, S - items[i].weight)\n nottaken = knapsack_recurse(dp, items, i+1, S)\n if taken > nottaken:\n dp[(i, S)] = (taken, True)\n return taken\n dp[(i, S)] = (nottaken, False)\n return nottaken\n\ndef test():\n items = [\n Item(\"green\", 4, 12), \n Item(\"gray\", 2, 1), \n Item(\"yellow\", 10, 4), \n Item(\"blue\", 2, 2), \n Item(\"red\", 1, 1), \n ]\n knapsack(items, 15)\n knapsack(items, 5)\n\n items = [\n Item(\"ring\", 15, 1), \n Item(\"candelabra\", 10, 5), \n Item(\"radio\", 9, 3), \n Item(\"elvis\", 5, 4), \n ]\n knapsack(items, 8)\n" }, { "alpha_fraction": 0.5947712659835815, "alphanum_fraction": 0.5947712659835815, "avg_line_length": 15.1578950881958, "blob_id": "9741817e980055f6e68f1afee2d90dc31fc70b93", "content_id": "c927805a5bbcd0183ce8ad397c885e85fae4a879", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 306, "license_type": "permissive", "max_line_length": 38, "num_lines": 19, "path": "/heap/maxheap.py", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "# maxheap\n\nfrom abstractheap import *\n\nclass MaxHeap(AbstractHeap):\n \"\"\"priority queue using maxheap\"\"\"\n\n def compare(self, l, r):\n return l > r\n\n\ndef sort(a):\n heap = MaxHeap(a)\n\n for i in reversed(xrange(len(a))):\n heap.buildmaxheap()\n a[i] = heap.extract()\n\n return a" }, { "alpha_fraction": 0.37973272800445557, "alphanum_fraction": 0.4576837420463562, "avg_line_length": 26.24242401123047, "blob_id": "1ad7a8007d353308625775312d16a28ce9c58fdd", "content_id": "d70f9c29e53f7daca99ebe71dc12f9bceb19c5b0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 898, "license_type": "permissive", "max_line_length": 77, "num_lines": 33, "path": "/dp/lis.py", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "# longest increasing subsequence\n\ndef lis(l):\n # step 1: dynamic programming, O(n^2)\n dp = [(0, None)] * len(l) # list of tuples (size of lis, parent pointer)\n for i in reversed(range(len(l))):\n dp[i] = (1, None)\n for j in range(i+1, len(l)):\n if l[i] <= l[j] and dp[i] <= dp[j]:\n dp[i] = (1+dp[j][0], j)\n # step 2: find beginning of subsequence, O(n)\n print \"lis:\",\n idx, max = 0, 0\n for i,v in enumerate(dp):\n if max < v[0]:\n idx, max = i, v[0]\n # step 3: print subsequence, O(n)\n while idx is not None:\n print str(l[idx]),\n idx = dp[idx][1]\n print \"\"\n\ndef test():\n l = [\n [7,1,3,5,4,8,1,9,2],\n [1,1,1,1,1,1,1,1,1],\n [9,8,7,6,5,4,3,2,1],\n [1,2,3,4,5,6,7,8,9],\n [123, 7, 42, 24, 132, 133, 558, 999],\n ]\n for ll in l:\n print ll,\n lis(ll)" }, { "alpha_fraction": 0.5423497557640076, "alphanum_fraction": 0.556010901927948, "avg_line_length": 23.433332443237305, "blob_id": "882c6e6a2f0cb0024fffa6e4136e58961f5454b7", "content_id": "1da0ede8346c7d50d500f3a7a18e2bf3aa6b853d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 732, "license_type": "permissive", "max_line_length": 81, "num_lines": 30, "path": "/sorting/quicksort.py", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "# quicksort\n\ndef quicksort(a, lo, hi):\n \"\"\"actual recursive quicksort implementation (Lomuto scheme)\"\"\"\n if hi - lo <= 0:\n return\n\n # step 1: find pivot, move smaller items to left, bigger -- to right of pivot\n pivot = a[hi] # last item initially\n\n li, ri = lo, hi-1\n while True:\n while a[li] <= pivot and li < hi: li += 1\n while a[ri] >= pivot and ri > lo: ri -= 1\n\n if li >= ri: break\n\n a[li], a[ri] = a[ri], a[li]\n\n a[hi], a[li] = a[li], a[hi] # finally move pivot\n\n # step 2: recursively quicksort left and right (w/o pivot point)\n quicksort(a, lo, li-1)\n quicksort(a, li+1, hi)\n\n\ndef sort(a):\n quicksort(a, 0, len(a)-1)\n # it was in-place\n return a" }, { "alpha_fraction": 0.42554643750190735, "alphanum_fraction": 0.46038252115249634, "avg_line_length": 35.625, "blob_id": "540f5e5a8c706cc08c2c80317ae486fb0c46367d", "content_id": "6bce3fb5a67d3a9958ad0f0a639ce57ccd165650", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1464, "license_type": "permissive", "max_line_length": 68, "num_lines": 40, "path": "/dp/lcs.py", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "# longest common subsequence of two strings\n\nHUGENUM = 2**31 # substitute for +Inf, for simplicity\n\ndef lcs(x, y):\n # step 1: init dp with tuples (+Inf, x_idx, y_idx); O(|x|*|y|)\n dp = []\n for i in range(len(x)+1):\n dpy = [(HUGENUM, 0, 0)] * (len(y)+1)\n dp.append(dpy)\n for i in range(len(x)+1): # guard row\n dp[i][len(y)] = (len(x)-i, 0, 0)\n for j in range(len(y)+1): # guard column\n dp[len(x)][j] = (len(y)-j, 0, 0)\n # step 2: dynamic programming on suffixes of x and y; O(|x|*|y|)\n for i in reversed(range(len(x))):\n for j in reversed(range(len(y))):\n # case 1: replacement, cost 0\n if x[i] == y[j]:\n if dp[i][j][0] > dp[i+1][j+1][0]:\n dp[i][j] = (dp[i+1][j+1][0], i+1, j+1)\n # case 2: delete from x, cost 1\n if dp[i][j][0] > 1 + dp[i+1][j][0]:\n dp[i][j] = (1 + dp[i+1][j][0], i+1, j)\n # case 3: delete from y, cost 1\n if dp[i][j][0] > 1 + dp[i][j+1][0]:\n dp[i][j] = (1 + dp[i][j+1][0], i, j+1)\n # step 3: print out common subsequence; O(max(|x|,|y|))\n print \"lcs for x=`%s` and y=`%s`:\" % (x, y),\n i, j = 0, 0\n while i < len(x) and j < len(y):\n if x[i] == y[j]:\n print x[i],\n i, j = dp[i][j][1], dp[i][j][2]\n print\n\n\ndef test():\n lcs(\"HIEROGLYPHOLOGY\", \"MICHAELANGELO\")\n lcs(\"HAWKBILL THESE PROFITS\", \"UNSKILLED OTHER PROOF\")" }, { "alpha_fraction": 0.5265932083129883, "alphanum_fraction": 0.5366554856300354, "avg_line_length": 39.13461685180664, "blob_id": "7d11578d6bd14e799099b105255826afed4815bd", "content_id": "f7d4ddf07311ad4d3e8998d3405c1c5437452b7d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2087, "license_type": "permissive", "max_line_length": 117, "num_lines": 52, "path": "/shortestpath/bellmanford.py", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "# shortest path for graphs with negative cycles\n\nfrom collections import OrderedDict\nfrom spvertex import SPVertex\n\ndef shortestpath(G, W, s):\n \"\"\"shortest path from start vertex s to all reachable vertices or False if found neg cycle\"\"\"\n # initialize\n for v in G.keys():\n v.reset()\n s.dist = 0\n # go through all vertices |V|-1 times and relax their edges; O(VE) ~= O(V^3)\n for _ in range(len(G.keys())-1):\n for u in G.keys():\n for i, v in enumerate(G[u]):\n v.relax(u, W[u][i])\n # one last iteration to check for negative cycles\n # (if some v.dist didn't converge after |V|-1, it's due to neg cycle)\n for u in G.keys():\n for i, v in enumerate(G[u]):\n if (v.dist is not None and u.dist is not None\n and v.dist > u.dist + W[u][i]):\n return False\n return True\n\ndef printshortestpath(s, t):\n \"\"\"print shortest path from s to t; shortestpath(.., s) must be run previously\"\"\"\n if t.dist is None:\n print \"No path found from %s to %s\" % (str(s), str(t))\n return\n sp = [t]\n while sp[-1].pi:\n sp.append(sp[-1].pi)\n print \"shortestpath:\", \"->\".join([str(v) for v in reversed(sp)]), \"(dist = %d)\" % t.dist\n\ndef findprintshortestpath(G, W, s, t):\n if shortestpath(G, W, s):\n printshortestpath(s, t)\n else:\n print \"Found negative cycle, cannot compute\"\n\n\ndef test():\n a = SPVertex('a'); b = SPVertex('b'); c = SPVertex('c'); d = SPVertex('d'); e = SPVertex('e'); f = SPVertex('f');\n g = SPVertex('g'); h = SPVertex('h'); i = SPVertex('i'); j = SPVertex('j'); k = SPVertex('k'); l = SPVertex('l');\n G = OrderedDict([ (a,[b, c]), (b,[c, d]), (c,[d, e, f]), (d,[ e, f]), (e,[ f]), (f,[]) ])\n W = OrderedDict([ (a,[5, 3]), (b,[2, 6]), (c,[7, 4, 2]), (d,[-1, 1]), (e,[-2]), (f,[]) ])\n findprintshortestpath(G, W, b, f)\n # simple neg cycle example\n G = OrderedDict([ (a,[ b]), (b,[ c]), (c,[ d]), (d,[ b]) ])\n W = OrderedDict([ (a,[-2]), (b,[-2]), (c,[-2]), (d,[-2]) ])\n findprintshortestpath(G, W, a, d)\n" }, { "alpha_fraction": 0.5404255390167236, "alphanum_fraction": 0.5489361882209778, "avg_line_length": 33.814815521240234, "blob_id": "18156a29f1f24abd461a4ae7be06a6b187e5a3f3", "content_id": "8d81b671359a95e63a6f658d857022f3e971c1b7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 940, "license_type": "permissive", "max_line_length": 77, "num_lines": 27, "path": "/graph/dfs_nonrecursive.py", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "# quick & dirty implementation of the non-recursive DFS\n# based on: http://dave.dkjones.org/posts/2014/nonrecursive-dfs.html\n\nclass Vertex(object):\n __slots__ = ['pre', 'post', 'value']\n\ndef DFS(edges, s):\n stack = [s]\n while len(stack):\n v = stack.pop()\n if v.post: # stage 3: after postprocessing, skip\n continue\n if v.pre: # stage 2: after preprocessing, do postprocessing\n # in this example, we calculate sums of subtrees\n value = 0\n for u in edges[v]:\n if u.post == False: continue # is it parent?\n value += u.value\n v.value += value\n v.post = True\n continue\n # stage 1: before preprocessing, put both me and my children in stack\n stack.append(v)\n v.pre = True\n for u in edges[v]:\n if u.pre == True: continue # already visited?\n stack.append(u)\n" }, { "alpha_fraction": 0.5762763023376465, "alphanum_fraction": 0.5771771669387817, "avg_line_length": 29.842592239379883, "blob_id": "5d7b3fcbacce948c012f3fadfed996049563ea95", "content_id": "e0121c0e43691d111644c3ef8fb6e1dfa560ae8b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3330, "license_type": "permissive", "max_line_length": 93, "num_lines": 108, "path": "/tree/splay.py", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "# balanced Splay tree\n# for reuse of left & right rotates, inherit from AVL trees\nfrom avl import *\n\nclass SplayTree(AVLTree):\n \"\"\"\n Splay trees have the following features:\n 1. _No_ metadata needed (compare to colors in RB and heights in AVL)\n 2. Each operation, even find, moves (splays) node up to the root\n - benefit: perfect for non-random workloads\n 3. Amortized O(lg n) performance, but O(n) worst-case\n\n Note that insert() and deletenode() are inherted from AVLTree and call rebalance()\n \"\"\"\n\n def rebalance(self, node):\n \"\"\"starting from node, splay node and move upwards; O(lg n)\"\"\"\n if node == None:\n return\n parent = node.parent\n if parent == None:\n # I am root\n self.root = node\n return\n\n grandpa = parent.parent\n if grandpa == None:\n # zig case: I am child of root\n if parent.left == node: self.rightrotate(parent)\n else: self.leftrotate(parent)\n elif parent.left == node and grandpa.right == parent:\n # zig-zag case: I am left child of right child\n self.rightrotate(parent)\n self.leftrotate(grandpa)\n elif parent.right == node and grandpa.left == parent:\n # zig-zag case (mirrored): I am right child of left child\n self.leftrotate(parent)\n self.rightrotate(grandpa)\n elif parent.left == node and grandpa.left == parent:\n # zig-zig case: I am left child of left child\n self.rightrotate(grandpa)\n self.rightrotate(parent)\n else:\n # zig-zig case (mirrored): I am right child of right child\n self.leftrotate(grandpa)\n self.leftrotate(parent)\n\n self.rebalance(node)\n\n def find(self, key):\n \"the difference from vanilla BST is the need to rebalance, even if nothing was found\"\n if self.root == None:\n return None\n node, parent = self.findpair(key, self.root, None)\n if node == None: self.rebalance(parent)\n else: self.rebalance(node)\n return node\n\n def findmin(self):\n node = BinarySearchTree.findmin(self)\n self.rebalance(node)\n return node\n\n def findmax(self):\n node = BinarySearchTree.findmax(self)\n self.rebalance(node)\n return node\n\n def next(self, node):\n node = BinarySearchTree.next(self, node)\n self.rebalance(node)\n return node\n\n def prev(self, node):\n node = BinarySearchTree.prev(self, node)\n self.rebalance(node)\n return node\n\n def insertnode(self, node):\n if BinarySearchTree.insertnode(self, node):\n self.rebalance(node)\n\n def insert(self, key):\n node = Node(key)\n self.insertnode(node)\n\n def delete(self, key):\n if self.root == None:\n return\n node, parent = self.findpair(key, self.root, None)\n if node == None: self.rebalance(parent)\n else: self.deletenode(node)\n\n\ndef sort(a):\n sp = SplayTree()\n\n for key in a:\n sp.insert(key)\n\n node = sp.findmin()\n res = []\n while node:\n res.append(node.key)\n node = sp.next(node)\n\n # not in-place\n return res" }, { "alpha_fraction": 0.43791723251342773, "alphanum_fraction": 0.5060080289840698, "avg_line_length": 21.606060028076172, "blob_id": "f9ee70a346bcc66d7bb8c903076c0c10e4d6f77e", "content_id": "f10d8387d78f0dcabab2320f7ebc9bb8ae712323", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 749, "license_type": "permissive", "max_line_length": 73, "num_lines": 33, "path": "/dp/fib.py", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "# dynamic programming: fibonacci\n\n# naive, O(2^f)\ndef naive(f):\n if f == 1 or f == 2:\n return 1\n return naive(f-1) + naive(f-2)\n\n# top-down (recursive), #subproblems = O(f), #choices = O(1), time = O(f)\ndef dp1(f):\n dp = [0] * f\n dp[0] = 1; dp[1] = 1\n return dp1recurse(dp, f-1)\n\ndef dp1recurse(dp, f):\n if dp[f] > 0:\n return dp[f]\n res = dp1recurse(dp, f-1) + dp1recurse(dp, f-2)\n dp[f] = res\n return res\n\n# bottom-up (topological order), time = O(f)\ndef dp2(f):\n dp = [0] * f\n dp[0] = 1; dp[1] = 1\n for i in range(2, f):\n dp[i] = dp[i-1] + dp[i-2]\n return dp[f-1]\n\n\ndef test():\n print \"fib(10) =\", dp1(10), \"fib(50) =\", dp1(50)\n print \"fib(10) =\", dp2(10), \"fib(50) =\", dp2(50) " }, { "alpha_fraction": 0.5313366651535034, "alphanum_fraction": 0.5407654047012329, "avg_line_length": 24.757143020629883, "blob_id": "60e4d6db38afe2ca7d6742bd0a299f2429ecb373", "content_id": "38db95cb45e46ae9ab20492e34d48c11e67034d4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1803, "license_type": "permissive", "max_line_length": 80, "num_lines": 70, "path": "/heap/abstractheap.py", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "# abstract heap\n\ndef parent(i):\n return (i-1)/2\n\ndef left(i):\n return i*2+1\n\ndef right(i):\n return i*2+2\n\n\nclass AbstractHeap(object):\n \"\"\"priority queue using heap (abstract parent class)\"\"\"\n\n def __init__(self, a = None):\n self.a = a[:] if a else [] # copy list if provided\n\n def compare(self, l, r):\n raise NotImplementedError(\"AbstractHeap does not implement comparison!\")\n\n def upheap(self, i):\n if i == 0: return\n p = parent(i)\n if self.compare(self.a[i], self.a[p]):\n self.a[i], self.a[p] = self.a[p], self.a[i]\n self.upheap(p)\n\n def downheap(self, i):\n # assumption: subtrees at left & right children are maxheaps already\n l, r = left(i), right(i)\n toswap = i\n if l < len(self.a) and self.compare(self.a[l], self.a[toswap]):\n toswap = l\n if r < len(self.a) and self.compare(self.a[r], self.a[toswap]):\n toswap = r\n\n if toswap != i:\n self.a[i], self.a[toswap] = self.a[toswap], self.a[i]\n self.downheap(toswap)\n\n def buildmaxheap(self):\n lastparent = parent(len(self.a)-1)\n for i in reversed(xrange(lastparent+1)):\n # traverse from last parent to root to downheap subtrees\n self.downheap(i)\n\n def insert(self, v):\n i = len(self.a)\n self.a.append(v)\n self.upheap(i)\n\n def peek(self):\n return self.a[0] if len(self.a) > 0 else None\n\n def extract(self):\n if len(self.a) == 0: return None\n if len(self.a) == 1: return self.a.pop()\n\n res = self.a[0]\n self.a[0] = self.a.pop()\n self.downheap(0)\n\n return res\n\n def empty(self):\n return len(self.a) == 0\n\n def __str__(self):\n return str(self.a)\n" }, { "alpha_fraction": 0.4597701132297516, "alphanum_fraction": 0.46666666865348816, "avg_line_length": 24.647058486938477, "blob_id": "b421627d4a81679d27efaf13d0505406bcb55f80", "content_id": "a0a21b8d7a463727b85b5169a631ae25e6c3ffa2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 435, "license_type": "permissive", "max_line_length": 66, "num_lines": 17, "path": "/sorting/insertion.py", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "# insertion sort\n\ndef sort(a):\n for i in xrange(len(a)):\n curr = a[i]\n for j in reversed(xrange(i)):\n if a[j] < curr:\n # found the biggest item from right in sorted part\n a[j+1] = curr\n break\n a[j+1] = a[j]\n else:\n # traversed the whole sorted part -> curr is smallest\n a[0] = curr\n\n # it was in-place sort\n return a" }, { "alpha_fraction": 0.4699849784374237, "alphanum_fraction": 0.4727363586425781, "avg_line_length": 31.770492553710938, "blob_id": "8d5e9d17c8a399897ed06b802232ab1d033c9c3e", "content_id": "2250f7d1dfd4a7b128dc359ddc061ad1a05d6a51", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3998, "license_type": "permissive", "max_line_length": 134, "num_lines": 122, "path": "/graph/dfs.py", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "# Depth-First Search (DFS)\n\nfrom collections import OrderedDict\nfrom vertex import Vertex\n\nclass Graph(object):\n\n def __init__(self, G):\n self.G = G\n self.timestamp = 0\n self.finished = []\n self.SCCstring = \"\"\n\n def __str__(self):\n s = \"\"\n for v in self.G.keys():\n s += \"%s: %d %s %d %d\\n\" % (v.name, v.level, str(v.parent), v.start, v.finish)\n return s\n\n def reset(self):\n self.finished = []\n self.timestamp = 0\n for v in self.G.keys():\n v.reset()\n\n def DFSvisit(self, s):\n self.timestamp += 1\n s.start = self.timestamp\n self.SCCstring += str(s) + \", \"\n\n for v in self.G[s]:\n if v.start == None:\n v.level = s.level + 1\n v.parent = s\n self.DFSvisit(v)\n\n self.timestamp += 1\n self.finished.append(s)\n s.finish = self.timestamp\n\n\n def DFS(self):\n self.reset()\n for v in self.G.keys():\n if v.start == None:\n self.SCCstring += \"New SCC: \"\n v.level = 0\n self.DFSvisit(v)\n self.SCCstring += \"\\n\"\n\n def classifyedges(self):\n if self.timestamp == 0:\n print \"Error: need to run DFS first!\"\n return\n print \"classifyedges:\"\n for v in self.G.keys():\n for u in self.G[v]:\n print \" edge\", str(v), str(u), \": \",\n if u.parent == v:\n print \"tree\"\n elif v.start < u.start and v.finish > u.finish:\n print \"forward\"\n elif v.start > u.start and v.finish < u.finish:\n print \"backward\"\n else:\n print \"cross\"\n\n def toposort(self):\n if self.timestamp == 0:\n print \"Error: need to run DFS first!\"\n return\n print \"toposort:\", \"->\".join([str(v) for v in reversed(self.finished)])\n\n def SCC(self):\n # step 1: run DFS and memorized finished times; O(V+E)\n self.DFS()\n # step 2: transpose original graph; O(V+E)\n # note how vertices are put in Gt in the G-finished order\n Gt = Graph(OrderedDict([(v, []) for v in reversed(self.finished)]))\n for v in self.G.keys():\n for u in self.G[v]:\n Gt.G.setdefault(u, []).append(v)\n print Gt\n # step 3: run DFS again on Gt\n Gt.DFS()\n print Gt.SCCstring\n\n\ndef test():\n a = Vertex('a'); s = Vertex('s'); c = Vertex('c'); d = Vertex('d'); b = Vertex('b'); g = Vertex('g');\n z = Vertex('z'); x = Vertex('x'); v = Vertex('v'); f = Vertex('f'); e = Vertex('e'); h = Vertex('h');\n # undirected graph\n G = Graph( OrderedDict([ (s,[a, x]), (a,[s, z]), (z,[a]), (x,[s, d, c]), (d,[x, c, f]), (c,[x,d,f,v]), (f,[d,c,v]), (v,[f,c]) ]) )\n G.DFS()\n G.classifyedges()\n G.toposort() # bogus since graph is undirected and cyclic\n # directed graph\n G = Graph( OrderedDict([ (a,[b, c]), (b,[d]), (c,[d, f]), (d,[e]), (e,[]), (f,[]) ]) )\n G.DFS()\n G.classifyedges()\n G.toposort()\n G.SCC()\n # directed graph for SCC (from Cormen)\n G = Graph( OrderedDict([ (a,[b]), (b,[e,f,c]), (c,[g, d]), (d,[c, h]), (e,[a, f]), (f,[g]), (g,[f, h]), (h,[h]) ]) )\n G.SCC()\n # Prof. Bumstead gets dressed in the morning\n undershorts = Vertex('undershorts'); pants = Vertex('pants'); belt = Vertex('belt');\n shirt = Vertex('shirt'); tie = Vertex('tie'); jacket = Vertex('jacket'); watch = Vertex('watch');\n socks = Vertex('socks'); shoes = Vertex('shoes');\n Bumstead = Graph( OrderedDict([\n (undershorts, [pants, shoes]),\n (pants, [belt, shoes]),\n (belt, [jacket]),\n (shirt, [belt, tie]),\n (tie, [jacket]),\n (jacket, []),\n (socks, [shoes]),\n (shoes, []),\n (watch, [watch]),\n ]) )\n Bumstead.DFS()\n Bumstead.toposort()\n" }, { "alpha_fraction": 0.7557789087295532, "alphanum_fraction": 0.7597990036010742, "avg_line_length": 94.65384674072266, "blob_id": "821ded26926834bf65c156b6ea7cf0d01ee121d1", "content_id": "44368b557ea546935018df8fc653ad5e716475b2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4975, "license_type": "permissive", "max_line_length": 535, "num_lines": 52, "path": "/README.md", "repo_name": "dimakuv/python-algos", "src_encoding": "UTF-8", "text": "Algorithms from \"Introduction to Algorithms\" written in Python\n\n# Quick Usage\n\n`./testsort.py heap.minheap` for sorting algos\n`./test.py hashtable.openaddressing` for other algos (must implement func `test`)\n\n# TODO\n\n* Interval tree\n* 2-3-4 tree\n* Minimum spanning tree\n\n# Random Notes\n\n## Python\n\n**Built-in functions are fast** -- built-in functions are written in C and highly optimized. For performance, one should use them even when there is a more pythonic way of solving the same task, but in pure Python. For example, string functions (e.g., `replace()`) are much faster than custom-made for-loops.\n\n**Functions that work on iterables are slow** -- functions like `max()` take an iterable as argument which is generally slow. Performance of costructs like `max(var1, var2)` is worse than a more verbose `var1 if var1>var2 else var2`.\n\n**Python is a memory hog** -- Python's integers are 24B in size, dicts are ridiculously voracious, and empty objects take ~80B. For tiny objects, one should specify `__slots__ = ['field1', 'field2', ...]` to reduce space waste. *Never play with garbage collection!*\n\n**Inner loops in CPython are slooow** -- In cases you cannot remove inner loops, try running in PyPy.\n\n## Algorithms\n\n**Rabin-Karp algorithm (rolling hash)** -- finds a *set* of `p` patterns (combined length `m`) in a string `n`. Useful when there is one huge string and several patterns (of the same length) to find. Can be twicked to find patterns of different length: need to maintain several rolling hashes over the string. Rolling hash function can be as simple as *addition*. The algorithm can be generalized to 2D case. Average time: `O(n+m)`, worst-case time: `O(nm)`, space `O(p)`.\n\n**Aho-Corasick algorithm** -- finds a *set* of patterns (combined length `m`) in a string `n`. Differs from Rabin-Karp in that the set of patterns is *preprocessed* into a finite state machine resembling a trie-with-failures. Useful when there is a dictionary of patterns such that it is stored in a FSM format and invoked on many strings. Worst-case time: `O(n+m)`, space: `O(m)`.\n\n**Longest Common Subsequence (LCS)** -- dynamic programming algorithm that maintains a 2D table of *lengths of LCS in prefixes*. If we only need the length, can skip the backtracking part and only use *two rows* -- one row of previous lengths + one row of current lengths. This saves space greatly.\n\n**Preprocessing in greedy algorithms** -- algorithms that look like *backtracking* or *dynamic programming* can sometimes be transformed into greedy. The key is to perform some preprocessing on the input that will facilitate finding the optimum local decision.\n\n**Non-recursive DFS is non-trivial** -- non-recursive DFS is *kinda* BFS with a stack instead of a queue. However, it is more complicated because pre- and post-processing are cumbersome. In short, each vertex is added to the stack *two times* -- once for preprocessing and examination of its edges and once for postprocessing. Thus, each vertex has *three stages*: not visited, visited awaiting postprocessing, and visited-and-done. Simple example is in `graph/dfs_nonrecursive.py`.\n\n## Data Structures\n\n**Streaming Median** -- stores a median over the last `n` items in the array. Uses MinHeap + MaxHeap with the invariant that all items in MinHeap are *greater than or equal to* all items in MaxHeap. (I.e., MinHeap provides the minimum item greater than the maximum item in MaxHeap.) The median is always the combination of peeks into MinHeap and MaxHeap. To implement streaming -- when the oldest item is evicted and a new one is appended -- one needs the `remove()` operation in both heaps, which can be implemented in `O(lg n)` time.\n\n## Common Sense\n\n**Counting frequencies** -- counting frequences of letters in alphabet over an input string (distribution of letters) can be beneficial. Python `dict`s are an obvious choice of weapon.\n\n**Principle of mass conservation** -- if some quantity is moved from one container to the other, or the quantities are swapped, it is beneficial to check if the quantity in the initial state equals to the quantity in the final state.\n\n**Iterate over arrays via skipping redundant iterations** -- Knuth-Morris-Pratt and Boyer-Moore string search algorithms are great examples. Basically, if there is a possibility to skip redundant iterations, even though it does not change asymptotic worst-case runtime, it helps a lot in practice.\n\n**Properties of sorted arrays work also on reversed order** -- if some property (e.g., *minimal absolute difference between two consequtive items*) holds for a asc-sorted array, it usually also holds for a reverse-sorted array.\n\n**Minimum number of swaps between two arrays** -- calculated using cycles (see *cyclesort*). The idea is to follow the chain \"value at current index in 1st array -> index of this value in 2nd array -> value at new index in 1st array -> etc\" thus creating cycles. Length of each cycle gives the number of swaps plus one. \n" } ]
29
alexanfl/uio-subjects
https://github.com/alexanfl/uio-subjects
0dd8f5ccb12850327422ca47c0c0fe18f8383044
e962f516025a7d171e6eadc8e878fc7f9ab6ac63
8d164719ded89f12070d0d01d5e9db533503e1dc
refs/heads/master
2021-01-09T22:38:47.247841
2017-05-29T12:26:48
2017-05-29T12:26:48
92,737,459
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.585631787776947, "alphanum_fraction": 0.6260423064231873, "avg_line_length": 25.879310607910156, "blob_id": "0f20183bcead1c8eaf2a979589fd72158afa0344", "content_id": "b9f759751c22bcf447958acc4a4a94809c81439e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1559, "license_type": "no_license", "max_line_length": 67, "num_lines": 58, "path": "/fys2130/prosjekt2016/src/problem6.py", "repo_name": "alexanfl/uio-subjects", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as an\n\n# Number of mass points\nN = 200\n\n# All mass points have the same mass (except endpoints):\nm = 0.02*np.ones(N) # kg\nm[0] = m[-1] = 1.\n\n# Spring stiffness / constant\nk = 10*np.ones(N) # kg/s^2\n\nvB = np.sqrt(k[10]/m[10])\n\n# Length of time step\ndt = 0.1*np.sqrt(m[10]/k[10]) # s\nnumberOfTimeSteps = 1200 #int(t_max/dt) + 1\nt_max = 1200*dt\nprint(\"t_max: \", t_max)\nprint(\"Time steps: \", numberOfTimeSteps)\n\n# Matrix of the fluctuations of the string (for time and x values)\n# End points are zero due to reflecting edges.\ny = np.zeros([N,numberOfTimeSteps])\n\n# Set the initial conditions, t = 0 and \nfor i in range(N):\n y[i,0] = np.sin(7*np.pi*i/(N-1))\n\n # Since we don't have an expression for y(-dt)\n y[i,numberOfTimeSteps-1] = np.sin(7*np.pi*i/(N-1))\n\ntotalEnergy = np.zeros(numberOfTimeSteps)\n\nfor j in range(numberOfTimeSteps-1):\n potentialEnergy = 0\n kineticEnergy = 0\n for i in range(1,N-1):\n\n F_left = -k[i-1]*(y[i,j] - y[i-1,j])\n F_right = -k[i]*(y[i,j] - y[i+1,j])\n F_i = F_left + F_right\n\n y[i,j+1] = F_i*dt**2/m[i] + 2*y[i,j] - y[i,j-1]\n\n potentialEnergy += 0.5*k[i]*(y[i,j] - y[i-1,j])**2\n kineticEnergy += 0.5*m[i]*((y[i,j+1]-y[i,j])/dt)**2\n\n totalEnergy[j+1] = potentialEnergy + kineticEnergy\n\nplt.plot(np.linspace(1,t_max,numberOfTimeSteps-1), totalEnergy[1:])\nplt.xlabel(\"Tid [s]\")\nplt.ylabel(\"Energi [J]\")\nplt.title(\"Totalenergi, endring gjennom svingetiden\")\nplt.savefig(\"problem6.png\")\nplt.show()\n" }, { "alpha_fraction": 0.5151016116142273, "alphanum_fraction": 0.5716639161109924, "avg_line_length": 20.93975830078125, "blob_id": "aad958b77165c64be930d181d1641d5cbb9a9a75", "content_id": "5e8315806824e31234de2118d9f1ac4a9f87e629", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1822, "license_type": "no_license", "max_line_length": 76, "num_lines": 83, "path": "/fys2130/prosjekt2016/src/problem8.py", "repo_name": "alexanfl/uio-subjects", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as an\n\n# Number of mass points\nN = 200\n\n# All mass points have the same mass (except endpoints):\nm = 0.02*np.ones(N) # kg\nm[0] = m[-1] = 1.\n\n# Spring stiffness / constant\nk = 10*np.ones(N) # kg/s^2\n\nvB = np.sqrt(k[10]/m[10])\n\nwave_length = N/3.5\nfrequency = vB/wave_length\nperiod = 1./frequency\n\nt_max = 10*period\n\nprint(\"Propagation speed: \", vB)\nprint(\"Frequency: \", frequency)\n\n# Length of time step\ndt = 0.1*np.sqrt(m[10]/k[10]) # s\nnumberOfTimeSteps = int(t_max/dt) + 1\nprint(\"t_max: \", t_max)\nprint(\"Time steps: \", numberOfTimeSteps)\n\n# Matrix of the fluctuations of the string (for time and x values)\n# End points are zero due to reflecting edges.\ny = np.zeros([N,numberOfTimeSteps])\n\n# Set the initial conditions, t = 0 and \nfor i in range(N):\n if 1 <= i <= 30:\n y[i,0] = i/30.\n elif 31 <= i <= 60:\n y[i,0] = (60. - i)/30.\n else:\n y[i,0] = 0\n\n\n \nfor i in range(N):\n if 0 <= i <= 29:\n y[i,-1] = y[i,0] + 1/30.*dt*vB\n elif 30 <= i <= 59:\n y[i,-1] = y[i,0] - 1/30.*dt*vB\n else:\n y[i,-1] = y[i,0]\n\n\n\n\n# fig = plt.figure()\n# images = []\n\nfor j in range(numberOfTimeSteps-1):\n for i in range(1,N-1):\n\n F_left = -k[i-1]*(y[i,j] - y[i-1,j])\n F_right = -k[i]*(y[i,j] - y[i+1,j])\n F_i = F_left + F_right\n\n y[i,j+1] = F_i*dt**2/m[i] + 2*y[i,j] - y[i,j-1]\n \n # images.append(plt.plot(y[:,j+1], \"-b\"))\n\nplt.title(\"Trekantølge som beveger seg sidelengs for forskjellige tidssteg\")\nplt.plot(y[:,0])\nplt.plot(y[:,800])\nplt.plot(y[:,1800])\nplt.plot(y[:,2500])\nplt.legend([\"t = 0\", \"t = 800\", \"t = 1800\", \"t = 2500\"])\nplt.xlabel(\"\")\nplt.savefig(\"problem8.png\")\nplt.show()\n\n# theanimation = an.ArtistAnimation(fig, images, interval=10)\n# plt.show()\n" }, { "alpha_fraction": 0.5120627284049988, "alphanum_fraction": 0.5729795098304749, "avg_line_length": 22.685714721679688, "blob_id": "5be2bcecb4410a9ac91fbace157d3ad8be79e1be", "content_id": "ba01a86094fbc150d29fd938ac1f61cd5e0b113f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1659, "license_type": "no_license", "max_line_length": 81, "num_lines": 70, "path": "/fys2130/prosjekt2016/src/problem9.py", "repo_name": "alexanfl/uio-subjects", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as an\n\n# Number of mass points\nN = 400\n\n# All mass points have the same mass (except endpoints):\nm = 0.02*np.ones(N) # kg\nm[0] = m[-1] = 1.\n# Increase the mass of the last 200 mass points of the string\nm[200:-1] *= 3.\n\n# Spring stiffness / constant\nk = 10*np.ones(N) # kg/s^2\n\n# Propagatiion speed\nvB = np.sqrt(k[10]/m[10])\n\n# Length of time step\ndt = 0.1*np.sqrt(m[10]/k[10]) # s\nnumberOfTimeSteps = 5000\n\n# Matrix of the fluctuations of the string (for time and x values)\n# End points are zero due to reflecting edges.\ny = np.zeros([N,numberOfTimeSteps])\n\n# Set the initial conditions, t = 0 and \nfor i in range(N):\n if 1 <= i <= 30:\n y[i,0] = i/30.\n elif 31 <= i <= 60:\n y[i,0] = (60. - i)/30.\n else:\n y[i,0] = 0\n\n\n \nfor i in range(N):\n if 0 <= i <= 29:\n y[i,-1] = y[i,0] + 1/30.*dt*vB\n elif 30 <= i <= 59:\n y[i,-1] = y[i,0] - 1/30.*dt*vB\n else:\n y[i,-1] = y[i,0]\n\nfig = plt.figure()\nimages = []\n\nfor j in range(numberOfTimeSteps-1):\n for i in range(1,N-1):\n\n F_left = -k[i-1]*(y[i,j] - y[i-1,j])\n F_right = -k[i]*(y[i,j] - y[i+1,j])\n F_i = F_left + F_right\n\n y[i,j+1] = F_i*dt**2/m[i] + 2*y[i,j] - y[i,j-1]\n \n # images.append(plt.plot(y[:,j+1], \"-b\"))\n\nprint(np.min(y[:,2500]), np.max(y[:,2500]))\nprint(np.max(y[:,0]))\n\n# theanimation = an.ArtistAnimation(fig, images, interval=10)\nplt.plot(y[:,2500])\nplt.title(r\"Transmittert og reflektert trekantbølge for og massepunkter $N=200$\")\nplt.xlabel(\"x [m]\")\nplt.ylabel(\"Amplitude [m]\")\nplt.savefig(\"problem9.png\")\nplt.show()\n" }, { "alpha_fraction": 0.5736241936683655, "alphanum_fraction": 0.6261774897575378, "avg_line_length": 25.539474487304688, "blob_id": "f2655c50546cb658e08c9e16998b9eca08a86f7f", "content_id": "ebd5832882d649b34f3ae5e37263e0006a6062ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2017, "license_type": "no_license", "max_line_length": 120, "num_lines": 76, "path": "/fys2130/prosjekt2016/src/problem4.py", "repo_name": "alexanfl/uio-subjects", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as an\n\n# Number of mass points\nN = 200\n\n# All mass points have the same mass (except endpoints):\nm = 0.02*np.ones(N) # kg\nm[0] = m[-1] = 1.\n\n# Spring stiffness / constant\nk = 10*np.ones(N) # kg/s^2\n\nvB = np.sqrt(k[10]/m[10])\n\nwave_length = N/3.5\nfrequency = vB/wave_length\n\n\nprint(\"prop speed: \", vB)\nprint(\"Frequency: \", frequency)\n\n# Length of time step\ndt = 0.1*np.sqrt(m[10]/k[10]) # s\nnumberOfTimeSteps = 1200\nt_max = numberOfTimeSteps*dt # s\ntime = dt*range(numberOfTimeSteps)\n\n# Matrix of the fluctuations of the string (for time and x values)\n# End points are zero due to reflecting edges.\ny = np.zeros([N,numberOfTimeSteps])\n\n# Set the initial conditions, t = 0\nfor i in range(N):\n y[i,0] = np.sin(7*np.pi*i/(N-1))\n y[i,numberOfTimeSteps-1] = np.sin(7*np.pi*i/(N-1))\n\nfor j in range(numberOfTimeSteps-1):\n for i in range(1,N-1):\n\n F_left = -k[i-1]*(y[i,j] - y[i-1,j])\n F_right = -k[i]*(y[i,j] - y[i+1,j])\n F_i = F_left + F_right\n\n # y[i,j-1] = 0 since we haven't calculated y[i,-1] yet:\n y[i,j+1] = F_i*dt**2/m[i] + 2*y[i,j] - y[i,j-1]\n\n\n\n\n# plt.legend([\"timestep = 0\", \"timestep = 60\", \"timestep = 120\", \"timestep = 140\", \"timestep = 170\", \"timestep = 250\"])\n\n\nfig = plt.figure()\nax = plt.subplot(111)\n\nax.plot(y[:,0], label=r\"t = $0\\cdot\\Delta t$\")\nax.plot(y[:,60], label=r\"t = $60\\cdot\\Delta t$\")\nax.plot(y[:,120], label=r\"t = $120\\cdot\\Delta t$\")\nax.plot(y[:,140], label=r\"t = $140\\cdot\\Delta t$\")\nax.plot(y[:,170], label=r\"t = $250\\cdot\\Delta t$\")\nax.plot(y[:,250], label=r\"t = $250\\cdot\\Delta t$\")\nplt.title(\"Strengens svinginger ved forskjellige tidssteg\")\nax.set_xlabel(r\"x [$\\Delta x$]\")\nax.set_ylabel(\"Amplitude\")\n\n# Shrink current axis by 20%\nbox = ax.get_position()\nax.set_position([box.x0, box.y0, box.width * 0.8, box.height])\n\n# Put a legend to the right of the current axis\nax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\nplt.savefig(\"problem4.png\")\n\nplt.show()\n" }, { "alpha_fraction": 0.5704003572463989, "alphanum_fraction": 0.620782732963562, "avg_line_length": 23.700000762939453, "blob_id": "1c2f5a7c7a5a0ecda1d54b918bd3f82c58ea36a6", "content_id": "46a1bc0eec2f366684d42e32b59ee12bd4041538", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2224, "license_type": "no_license", "max_line_length": 87, "num_lines": 90, "path": "/fys2130/prosjekt2016/src/problem5.py", "repo_name": "alexanfl/uio-subjects", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as an\n\n# Number of mass points\nN = 200\n\n# All mass points have the same mass (except endpoints):\nm = 0.02*np.ones(N) # kg\nm[0] = m[-1] = 1.\n\n# Spring stiffness / constant\nk = 10*np.ones(N) # kg/s^2\n\nvB = np.sqrt(k[10]/m[10])\n\nwave_length = N/3.5\nfrequency = vB/wave_length\nperiod = 1./frequency\n\nt_max = 10*period\n\nprint(\"Propagation speed: \", vB)\nprint(\"Frequency: \", frequency)\n\n# Length of time step\ndt = 0.1*np.sqrt(m[10]/k[10]) # s\nnumberOfTimeSteps = int(t_max/dt) + 1\nprint(\"t_max: \", t_max)\nprint(\"Time steps: \", numberOfTimeSteps)\n\n# Matrix of the fluctuations of the string (for time and x values)\n# End points are zero due to reflecting edges.\ny = np.zeros([N,numberOfTimeSteps])\n\n# Set the initial conditions, t = 0 and \nfor i in range(N):\n y[i,0] = np.sin(7*np.pi*i/(N-1))\n\n # Since we don't have an expression for y(-dt)\n y[i,numberOfTimeSteps-1] = np.sin(7*np.pi*i/(N-1))\n\nt_0 = 0\nt_1 = 0\ncounted_freq = 0\ntol = 0.00005\ncnt = 0\n\n\nfor j in range(numberOfTimeSteps-1):\n for i in range(1,N-1):\n\n F_left = -k[i-1]*(y[i,j] - y[i-1,j])\n F_right = -k[i]*(y[i,j] - y[i+1,j])\n F_i = F_left + F_right\n\n y[i,j+1] = F_i*dt**2/m[i] + 2*y[i,j] - y[i,j-1]\n\n # Count how many minimum points we encounter in y_99(t):\n if y[99, j+1] - y[99, t_0] < tol and j+1-t_0 > 1:\n t_1 = j+1\n\n counted_freq = 1./(dt*(t_1 - t_0))\n t_0 = t_1\n\n cnt += 1\n\nprint(\"Counted frequency: \", cnt/(dt*t_1))\n\n# The take the Fast Fourier Transform of y_99(t):\ny99_abs = abs(np.fft.fft(y[99,:]))**2\n\nfreqs = np.linspace(0, 1./dt, numberOfTimeSteps)\nprint(\"FFT frequency: \", freqs[10])\n\nplt.plot(range(numberOfTimeSteps)/t_max, y99_abs[:]/numberOfTimeSteps**2)\nplt.axis([0.3,0.5,0,0.25])\nplt.title(r\"Frekvensspekter for $y_{99}(t)$\")\nplt.xlabel(\"Frekvens [Hz]\")\nplt.ylabel(r\"|FFT[$y_{99}(t)$]|$^2$ [Arbitrær enhet]\")\nplt.savefig(\"problem5-frekvens.png\")\nplt.show()\n\nplt.plot(y[99, :])\nplt.title(\"Svingning til det 99-ende massepunktet for %d tidssteg\" % numberOfTimeSteps)\nplt.xlabel(\"Tid [s]\")\nplt.ylabel(\"Amplitude [m]\")\nplt.legend([r\"$y_{99}(t)$\"])\nplt.savefig(\"problem5-svingning.png\")\nplt.show()\n" }, { "alpha_fraction": 0.5310541391372681, "alphanum_fraction": 0.5846154093742371, "avg_line_length": 22.092105865478516, "blob_id": "d2ccbae29eed3c7cc9830fecef551ea9cea36850", "content_id": "5187c87b5b176b7c349adf229511bcb186a27b43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1756, "license_type": "no_license", "max_line_length": 75, "num_lines": 76, "path": "/fys2130/prosjekt2016/src/problem7.py", "repo_name": "alexanfl/uio-subjects", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as an\n\n# Number of mass points\nN = 200\n\n# All mass points have the same mass (except endpoints):\nm = 0.02*np.ones(N) # kg\nm[0] = m[-1] = 1.\n\n# Spring stiffness / constant\nk = 10*np.ones(N) # kg/s^2\n\nvB = np.sqrt(k[10]/m[10])\n\nwave_length = N/3.5\nfrequency = vB/wave_length\nperiod = 1./frequency\n\nt_max = 10*period\n\nprint(\"Propagation speed: \", vB)\nprint(\"Frequency: \", frequency)\n\n# Length of time step\ndt = 0.1*np.sqrt(m[10]/k[10]) # s\nnumberOfTimeSteps = int(t_max/dt) + 1\nprint(\"t_max: \", t_max)\nprint(\"Time steps: \", numberOfTimeSteps)\n\n# Matrix of the fluctuations of the string (for time and x values)\n# End points are zero due to reflecting edges.\ny = np.zeros([N,numberOfTimeSteps])\n\n# Set the initial conditions, t = 0 and \nfor i in range(N):\n if 70 <= i <= 99:\n y[i,0] = (i - 69.)/30.\n y[i,-1] = y[i,0]\n elif 100 <= i <= 128:\n y[i,0] = (129. - i)/30.\n y[i,-1] = y[i,0]\n else:\n y[i,0] = 0\n y[i,-1] = y[i,0]\n\n\n# fig = plt.figure()\n# images = []\n\nfor j in range(numberOfTimeSteps-1):\n for i in range(1,N-1):\n\n F_left = -k[i-1]*(y[i,j] - y[i-1,j])\n F_right = -k[i]*(y[i,j] - y[i+1,j])\n F_i = F_left + F_right\n\n y[i,j+1] = F_i*dt**2/m[i] + 2*y[i,j] - y[i,j-1]\n \n # images.append(plt.plot(y[:,j+1], \"-b\"))\n\n\nplt.plot(y[:,0])\nplt.plot(y[:,200])\nplt.plot(y[:,400])\nplt.plot(y[:,1200])\nplt.title(\"Trekantbølge sentrert om midtpunktet ved forskjellige tidssteg\")\nplt.xlabel(r\"x [$\\Delta x$]\")\nplt.ylabel(\"Amplitude\")\nplt.legend([\"t = 0\", \"t = 200\", \"t = 400\", \"t = 1200\"])\nplt.savefig(\"problem7.png\")\nplt.show()\n\n# theanimation = an.ArtistAnimation(fig, images, interval=10)\n# plt.show()\n" } ]
6
nikitph/projectnameheretemplate
https://github.com/nikitph/projectnameheretemplate
3d2f7f534ad2721802e7ff8bdd0a28ff25137ad8
95294aa7e12e0d35a3a1d25c6470021c86e0cf02
956a2c4318490723e92099207ff49074baab81dc
refs/heads/master
2021-01-10T06:23:02.305627
2016-02-11T21:34:18
2016-02-11T21:34:18
51,546,971
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7274881601333618, "alphanum_fraction": 0.7274881601333618, "avg_line_length": 27.133333206176758, "blob_id": "2abf16e36371bba6b10c1b5f9d0afcb0dc5fe080", "content_id": "aac9b9a0c988a26a71656da762ab319bb5b6676f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 422, "license_type": "no_license", "max_line_length": 84, "num_lines": 15, "path": "/user/views.py", "repo_name": "nikitph/projectnameheretemplate", "src_encoding": "UTF-8", "text": "from flask import Blueprint, request, session, redirect, url_for, flash, g\nfrom flask.ext.security import login_required, logout_user, login_user, current_user\nfrom flask.templating import render_template\n\nbp_user = Blueprint('users', __name__, static_folder='../static')\n\n\n@bp_user.before_request\ndef before_request():\n g.user = current_user\n\n\n@bp_user.route('/')\ndef index():\n return render_template('index.html')\n" }, { "alpha_fraction": 0.748031497001648, "alphanum_fraction": 0.748031497001648, "avg_line_length": 33.54545593261719, "blob_id": "2c223d4ba1c72bfe88d6d59f07c6bfe604104cdd", "content_id": "c7cf0feafabd74fa11d4657f04d90111aa1a3260", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 381, "license_type": "no_license", "max_line_length": 69, "num_lines": 11, "path": "/public/models.py", "repo_name": "nikitph/projectnameheretemplate", "src_encoding": "UTF-8", "text": "from extensions import db\nfrom datetime import datetime\n\n\nclass Thought(db.Document):\n dys_thought = db.StringField(required=True)\n user = db.StringField(required=True)\n rational = db.StringField(required=False)\n distress = db.IntField(required=True)\n distortion = db.StringField(required=True)\n timestamp = db.StringField(required=True, default=datetime.now())\n\n" } ]
2
davidcerezal/django-oidc-provider
https://github.com/davidcerezal/django-oidc-provider
dded28a1c36b6155d22c7a6ccf86bf6e0571e86b
989b110bf0a0681db45036cd1a130634b278d971
29d5adf7ddddd78ea7ca57486ca6c3d9f1f942ce
refs/heads/master
2021-01-18T18:42:49.433692
2015-04-20T16:49:45
2015-04-20T16:49:45
34,320,592
1
0
null
2015-04-21T10:33:02
2015-04-20T16:49:46
2015-04-20T16:49:46
null
[ { "alpha_fraction": 0.5958747267723083, "alphanum_fraction": 0.6012223362922668, "avg_line_length": 31.454545974731445, "blob_id": "3dd516aec77e38201759993dc4cb62d7db6cad84", "content_id": "6ea419dd5237fe55cc2aa46c186bc03f019efed5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3927, "license_type": "permissive", "max_line_length": 78, "num_lines": 121, "path": "/oidc_provider/tests/test_token_endpoint.py", "repo_name": "davidcerezal/django-oidc-provider", "src_encoding": "UTF-8", "text": "import json\nfrom urllib import urlencode\nimport uuid\n\nfrom django.test import RequestFactory\nfrom django.test import TestCase\n\nfrom oidc_provider.lib.utils.token import *\nfrom oidc_provider.tests.utils import *\nfrom oidc_provider.views import *\n\n\nclass TokenTestCase(TestCase):\n \"\"\"\n To obtain an Access Token and an ID Token, the RP Client sends a\n Token Request to the Token Endpoint to obtain a Token Response\n when using the Authorization Code Flow.\n \"\"\"\n\n def setUp(self):\n self.factory = RequestFactory()\n self.user = create_fake_user()\n self.client = create_fake_client(response_type='code')\n self.state = uuid.uuid4().hex\n\n def _post_request(self, post_data):\n \"\"\"\n Makes a request to the token endpoint by sending the\n `post_data` parameters using the 'application/x-www-form-urlencoded'\n format.\n \"\"\"\n url = reverse('oidc_provider:token')\n\n request = self.factory.post(url,\n data=urlencode(post_data),\n content_type='application/x-www-form-urlencoded')\n\n response = TokenView.as_view()(request)\n\n return response\n\n def _create_code(self):\n \"\"\"\n Generate a valid grant code.\n \"\"\"\n code = create_code(\n user=self.user,\n client=self.client,\n scope=['openid', 'email'])\n code.save()\n\n return code\n\n def test_request_methods(self):\n \"\"\"\n Client sends an HTTP POST request to the Token Endpoint. Other request\n methods MUST NOT be allowed.\n \"\"\"\n url = reverse('oidc_provider:token')\n\n requests = [\n self.factory.get(url),\n self.factory.put(url),\n self.factory.delete(url),\n ]\n\n for request in requests:\n response = TokenView.as_view()(request)\n\n self.assertEqual(response.status_code == 405, True,\n msg=request.method+' request does not return a 405 status.')\n\n request = self.factory.post(url)\n\n response = TokenView.as_view()(request)\n\n self.assertEqual(response.status_code == 400, True,\n msg=request.method+' request does not return a 400 status.')\n\n def test_client_authentication(self):\n \"\"\"\n The authorization server support including the\n client credentials in the request-body using the `client_id` and\n `client_secret`parameters.\n\n See: http://tools.ietf.org/html/rfc6749#section-2.3.1\n \"\"\"\n code = self._create_code()\n\n # Test a valid request to the token endpoint.\n post_data = {\n 'client_id': self.client.client_id,\n 'client_secret': self.client.client_secret,\n 'redirect_uri': self.client.default_redirect_uri,\n 'grant_type': 'authorization_code',\n 'code': code.code,\n 'state': self.state,\n }\n response = self._post_request(post_data)\n response_dic = json.loads(response.content)\n\n self.assertEqual('access_token' in response_dic, True,\n msg='\"access_token\" key is missing in response.')\n self.assertEqual('error' in response_dic, False,\n msg='\"error\" key should not exists in response.')\n\n # Now, test with an invalid client_id.\n invalid_data = post_data.copy()\n invalid_data['client_id'] = self.client.client_id * 2 # Fake id.\n\n # Create another grant code.\n code = self._create_code()\n invalid_data['code'] = code.code\n\n response = self._post_request(invalid_data)\n response_dic = json.loads(response.content)\n\n self.assertEqual('error' in response_dic, True,\n msg='\"error\" key should exists in response.')\n self.assertEqual(response_dic.get('error') == 'invalid_client', True,\n msg='\"error\" key value should be \"invalid_client\".')\n" }, { "alpha_fraction": 0.6162513494491577, "alphanum_fraction": 0.6303358674049377, "avg_line_length": 33.19259262084961, "blob_id": "cf4efbfe6b4738f83ef79b02ac12e3f1ea0d0cd5", "content_id": "120f0107c53c3602706f9068555809420e4f8133", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4615, "license_type": "permissive", "max_line_length": 80, "num_lines": 135, "path": "/oidc_provider/models.py", "repo_name": "davidcerezal/django-oidc-provider", "src_encoding": "UTF-8", "text": "import json\n\nfrom django.db import models\nfrom django.utils import timezone\nfrom django.contrib.auth.models import User\n\n\ndef scope_property():\n def fget(self):\n return self._scope.split()\n def fset(self, value):\n self._scope = ' '.join(value)\n\n return locals()\n\n\nclass Client(models.Model):\n\n RESPONSE_TYPE_CHOICES = [\n ('code', 'code (Authorization Code Flow)'),\n ('id_token', 'id_token (Implicit Flow)'),\n ('id_token token', 'id_token token (Implicit Flow)'),\n ]\n\n name = models.CharField(max_length=100, default='')\n client_id = models.CharField(max_length=255, unique=True)\n client_secret = models.CharField(max_length=255, unique=True)\n response_type = models.CharField(max_length=30,\n choices=RESPONSE_TYPE_CHOICES)\n\n _redirect_uris = models.TextField(default='')\n\n def redirect_uris():\n def fget(self):\n return self._redirect_uris.splitlines()\n def fset(self, value):\n self._redirect_uris = '\\n'.join(value)\n return locals()\n redirect_uris = property(**redirect_uris())\n\n @property\n def default_redirect_uri(self):\n return self.redirect_uris[0] if self.redirect_uris else ''\n\n\nclass Code(models.Model):\n\n user = models.ForeignKey(User)\n client = models.ForeignKey(Client)\n code = models.CharField(max_length=255, unique=True)\n expires_at = models.DateTimeField()\n\n _scope = models.TextField(default='')\n scope = property(**scope_property())\n\n def has_expired(self):\n return timezone.now() >= self.expires_at\n\n\nclass Token(models.Model):\n\n user = models.ForeignKey(User)\n client = models.ForeignKey(Client)\n access_token = models.CharField(max_length=255, unique=True)\n expires_at = models.DateTimeField()\n\n _scope = models.TextField(default='')\n scope = property(**scope_property())\n\n _id_token = models.TextField()\n\n def id_token():\n def fget(self):\n return json.loads(self._id_token)\n def fset(self, value):\n self._id_token = json.dumps(value)\n return locals()\n id_token = property(**id_token())\n\n\nclass UserInfo(models.Model):\n\n GENDER_CHOICES = [\n ('F', 'Female'),\n ('M', 'Male'),\n ]\n\n user = models.OneToOneField(User, primary_key=True)\n given_name = models.CharField(max_length=255, blank=True, null=True)\n family_name = models.CharField(max_length=255, blank=True, null=True)\n middle_name = models.CharField(max_length=255, blank=True, null=True)\n nickname = models.CharField(max_length=255, blank=True, null=True)\n gender = models.CharField(max_length=100, choices=GENDER_CHOICES, null=True)\n birthdate = models.DateField(null=True)\n zoneinfo = models.CharField(max_length=100, default='', blank=True,\n null=True)\n locale = models.CharField(max_length=100, default='', blank=True, null=True)\n preferred_username = models.CharField(max_length=255, blank=True, null=True)\n profile = models.URLField(default='', null=True, blank=True)\n picture = models.URLField(default='', null=True, blank=True)\n website = models.URLField(default='', null=True, blank=True)\n email_verified = models.NullBooleanField(default=False)\n locale = models.CharField(max_length=100, blank=True, null=True)\n phone_number = models.CharField(max_length=255, blank=True, null=True)\n phone_number_verified = models.NullBooleanField(default=False)\n address_street_address = models.CharField(max_length=255, blank=True,\n null=True)\n address_locality = models.CharField(max_length=255, blank=True, null=True)\n address_region = models.CharField(max_length=255, blank=True, null=True)\n address_postal_code = models.CharField(max_length=255, blank=True,\n null=True)\n address_country = models.CharField(max_length=255, blank=True, null=True)\n updated_at = models.DateTimeField(auto_now=True, null=True)\n\n @property\n def name(self):\n name = ''\n if self.given_name:\n name = self.given_name\n if self.family_name:\n name = name + ' ' + self.family_name\n\n return name\n\n @property\n def address_formatted(self):\n formatted = ', '.join([\n self.address_street_address,\n self.address_locality,\n self.address_country])\n\n if formatted.startswith(', '):\n formatted = formatted[2:]\n if formatted.endswith(', '):\n formatted = formatted[:-2]" }, { "alpha_fraction": 0.7211796045303345, "alphanum_fraction": 0.7238605618476868, "avg_line_length": 22.3125, "blob_id": "115c3c2dd541ce8c6fdbb367aba74d3b46d8908b", "content_id": "7f0a62663ae0774b2ac8cd38e2a99dca28e4661f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 373, "license_type": "permissive", "max_line_length": 72, "num_lines": 16, "path": "/oidc_provider/lib/utils/common.py", "repo_name": "davidcerezal/django-oidc-provider", "src_encoding": "UTF-8", "text": "from django.core.urlresolvers import reverse\n\nfrom oidc_provider import settings\n\n\ndef get_issuer():\n\t\"\"\"\n\tConstruct the issuer full url. Basically is the site url with some path\n\tappended.\n\t\"\"\"\n\tsite_url = settings.get('SITE_URL')\n\tpath = reverse('oidc_provider:provider_info') \\\n\t\t.split('/.well-known/openid-configuration/')[0]\n\tissuer = site_url + path\n\n\treturn issuer\n" }, { "alpha_fraction": 0.6784141063690186, "alphanum_fraction": 0.6872246861457825, "avg_line_length": 17.91666603088379, "blob_id": "42f130a580571ebd5fbbbfa370bc6d03e2612693", "content_id": "1d613395ea530e38dc1f0a4ef01ee637d92d176a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 681, "license_type": "permissive", "max_line_length": 54, "num_lines": 36, "path": "/oidc_provider/tests/utils.py", "repo_name": "davidcerezal/django-oidc-provider", "src_encoding": "UTF-8", "text": "from django.contrib.auth.models import User\nfrom oidc_provider.models import *\n\n\ndef create_fake_user():\n\t\"\"\"\n\tCreate a test user.\n\n\tReturn a User object.\n\t\"\"\"\n\tuser = User()\n\tuser.username = 'johndoe'\n\tuser.email = '[email protected]'\n\tuser.set_password('1234')\n\n\tuser.save()\n\n\treturn user\n\ndef create_fake_client(response_type):\n\t\"\"\"\n\tCreate a test client, response_type argument MUST be:\n\t'code', 'id_token' or 'id_token token'.\n\n\tReturn a Client object.\n\t\"\"\"\n\tclient = Client()\n\tclient.name = 'Some Client'\n\tclient.client_id = '123'\n\tclient.client_secret = '456'\n\tclient.response_type = response_type\n\tclient.redirect_uris = ['http://example.com/']\n\n\tclient.save()\n\n\treturn client\n" }, { "alpha_fraction": 0.8144329786300659, "alphanum_fraction": 0.8144329786300659, "avg_line_length": 26.85714340209961, "blob_id": "bd48868f378083441307b967528ec21982857866", "content_id": "f98d4d4df759efe273d1deb0d3d061289ece03f8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 194, "license_type": "permissive", "max_line_length": 49, "num_lines": 7, "path": "/oidc_provider/admin.py", "repo_name": "davidcerezal/django-oidc-provider", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Client, Code, Token, UserInfo\n\nadmin.site.register(Client)\nadmin.site.register(Code)\nadmin.site.register(Token)\nadmin.site.register(UserInfo)" }, { "alpha_fraction": 0.7078189253807068, "alphanum_fraction": 0.7078189253807068, "avg_line_length": 29.375, "blob_id": "e233c74626ec0c2ee327612009ea9e54a9d273cd", "content_id": "747fd50db4ed41da39e899ac1436cf9b5bb94a4c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 243, "license_type": "permissive", "max_line_length": 79, "num_lines": 8, "path": "/example_app/provider_app/urls.py", "repo_name": "davidcerezal/django-oidc-provider", "src_encoding": "UTF-8", "text": "from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\n\nurlpatterns = patterns('',\n url(r'^openid/', include('oidc_provider.urls', namespace='oidc_provider')),\n\n url(r'^admin/', include(admin.site.urls)),\n)\n" }, { "alpha_fraction": 0.5500863790512085, "alphanum_fraction": 0.5509499311447144, "avg_line_length": 27.016128540039062, "blob_id": "1d77b6540a6d7c09885e69256c5ec373230e75d1", "content_id": "5977e144e9db2cebe3d189f3877a5f1e53c84a57", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3474, "license_type": "permissive", "max_line_length": 76, "num_lines": 124, "path": "/oidc_provider/lib/claims.py", "repo_name": "davidcerezal/django-oidc-provider", "src_encoding": "UTF-8", "text": "from django.utils.translation import ugettext as _\nfrom oidc_provider.models import UserInfo\n\n\nclass AbstractScopeClaims(object):\n\n def __init__(self, user, scopes):\n self.user = user\n self.scopes = scopes\n\n self.setup()\n\n def setup(self):\n pass\n\n def create_response_dic(self):\n \"\"\"\n Generate the dic that will be jsonify. Checking scopes given vs\n registered.\n\n Returns a dic.\n \"\"\"\n dic = {}\n\n for scope in self.scopes:\n\n if scope in self._scopes_registered():\n dic.update(getattr(self, 'scope_' + scope)(self.user))\n\n dic = self._clean_dic(dic)\n\n return dic\n\n def _scopes_registered(self):\n \"\"\"\n Return a list that contains all the scopes registered\n in the class.\n \"\"\"\n scopes = []\n\n for name in self.__class__.__dict__:\n\n if name.startswith('scope_'):\n scope = name.split('scope_')[1]\n scopes.append(scope)\n\n return scopes\n\n def _clean_dic(self, dic):\n \"\"\"\n Clean recursively all empty or None values inside a dict.\n \"\"\"\n aux_dic = dic.copy()\n for key, value in dic.iteritems():\n\n if not value:\n del aux_dic[key]\n elif type(value) is dict:\n aux_dic[key] = self._clean_dic(value)\n\n return aux_dic\n\nclass StandardScopeClaims(AbstractScopeClaims):\n \"\"\"\n Based on OpenID Standard Claims.\n See: http://openid.net/specs/openid-connect-core-1_0.html#StandardClaims\n \"\"\"\n\n def setup(self):\n try:\n self.userinfo = UserInfo.objects.get(user=self.user)\n except UserInfo.DoesNotExist:\n # Create an empty model object.\n self.userinfo = UserInfo()\n\n def scope_profile(self, user):\n dic = {\n 'name': self.userinfo.name,\n 'given_name': self.userinfo.given_name,\n 'family_name': self.userinfo.family_name,\n 'middle_name': self.userinfo.middle_name,\n 'nickname': self.userinfo.nickname,\n 'preferred_username': self.userinfo.preferred_username,\n 'profile': self.userinfo.profile,\n 'picture': self.userinfo.picture,\n 'website': self.userinfo.website,\n 'gender': self.userinfo.gender,\n 'birthdate': self.userinfo.birthdate,\n 'zoneinfo': self.userinfo.zoneinfo,\n 'locale': self.userinfo.locale,\n 'updated_at': self.userinfo.updated_at,\n }\n\n return dic\n\n def scope_email(self, user):\n dic = {\n 'email': self.user.email,\n 'email_verified': self.userinfo.email_verified,\n }\n\n return dic\n\n def scope_phone(self, user):\n dic = {\n 'phone_number': self.userinfo.phone_number,\n 'phone_number_verified': self.userinfo.phone_number_verified,\n }\n\n return dic\n\n def scope_address(self, user):\n dic = {\n 'address': {\n 'formatted': self.userinfo.address_formatted,\n 'street_address': self.userinfo.address_street_address,\n 'locality': self.userinfo.address_locality,\n 'region': self.userinfo.address_region,\n 'postal_code': self.userinfo.address_postal_code,\n 'country': self.userinfo.address_country,\n }\n }\n\n return dic\n" }, { "alpha_fraction": 0.6176065802574158, "alphanum_fraction": 0.6781293153762817, "avg_line_length": 18.13157844543457, "blob_id": "a05e2180a85b26b3e5337cddf0e0834fe158edfc", "content_id": "624deafc3ed799faf858fdf4260c4052c9b4a851", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 727, "license_type": "permissive", "max_line_length": 68, "num_lines": 38, "path": "/CHANGELOG.md", "repo_name": "davidcerezal/django-oidc-provider", "src_encoding": "UTF-8", "text": "# CHANGELOG\n\nAll notable changes to this project will be documented in this file.\n\n### [Unreleased]\n\n##### Fixed\n- Important bug with id_token when using implicit flow.\n\n### [0.0.3] - 2015-04-15\n\n##### Added\n- Normalize gender field in UserInfo.\n\n##### Changed\n- Make address_formatted a property inside UserInfo.\n\n##### Fixed\n- Important bug in claims response.\n\n### [0.0.2] - 2015-03-26\n\n##### Added\n- Setting OIDC_AFTER_USERLOGIN_HOOK.\n\n##### Fixed\n- Tests failing because an incorrect tag in one template.\n\n### [0.0.1] - 2015-03-13\n\n##### Added\n- Provider Configuration Information endpoint.\n- Setting OIDC_IDTOKEN_SUB_GENERATOR.\n\n##### Changed\n- Now use setup in OIDC_EXTRA_SCOPE_CLAIMS setting.\n\n### [0.0.0] - 2015-02-26\n" }, { "alpha_fraction": 0.7380530834197998, "alphanum_fraction": 0.7380530834197998, "avg_line_length": 30.33333396911621, "blob_id": "49c3ac450ba9a874105343c206dcddd9f192b7be", "content_id": "cc1baa450ef2e549d89533624c88b0a45821833c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 565, "license_type": "permissive", "max_line_length": 159, "num_lines": 18, "path": "/README.rst", "repo_name": "davidcerezal/django-oidc-provider", "src_encoding": "UTF-8", "text": "\nDjango OIDC Provider\n####################\n\nDjango OIDC Provider can help you providing out of the box all the endpoints, data and logic needed to add OpenID Connect capabilities to your Django projects.\n\nRead docs for more info.\n\nhttps://github.com/juanifioren/django-oidc-provider/blob/master/DOC.md\n\nSee changelog here.\n\nhttps://github.com/juanifioren/django-oidc-provider/blob/master/CHANGELOG.md\n\n************\nContributing\n************\n\nWe love contributions, so please feel free to fix bugs, improve things, provide documentation. Just submit a Pull Request.\n" }, { "alpha_fraction": 0.6310641765594482, "alphanum_fraction": 0.6394757628440857, "avg_line_length": 34.5, "blob_id": "952f8013bd7af4f58aac5af87823a89e4c63ee42", "content_id": "51ba9f35304bfed4db3f648ff2ecd7191cec6f85", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5112, "license_type": "permissive", "max_line_length": 120, "num_lines": 144, "path": "/oidc_provider/lib/errors.py", "repo_name": "davidcerezal/django-oidc-provider", "src_encoding": "UTF-8", "text": "import urllib\n\n\nclass RedirectUriError(Exception):\n\n error = 'Redirect URI Error'\n description = 'The request fails due to a missing, invalid, or mismatching redirection URI (redirect_uri).'\n\n\nclass ClientIdError(Exception):\n\n error = 'Client ID Error'\n description = 'The client identifier (client_id) is missing or invalid.'\n\n\nclass AuthorizeError(Exception):\n\n _errors = {\n # Oauth2 errors.\n # https://tools.ietf.org/html/rfc6749#section-4.1.2.1\n 'invalid_request': 'The request is otherwise malformed',\n\n 'unauthorized_client': 'The client is not authorized to request an authorization code using this method',\n\n 'access_denied': 'The resource owner or authorization server denied the request',\n\n 'unsupported_response_type': 'The authorization server does not support obtaining an authorization code using '\n 'this method',\n\n 'invalid_scope': 'The requested scope is invalid, unknown, or malformed',\n\n 'server_error': 'The authorization server encountered an error',\n\n 'temporarily_unavailable': 'The authorization server is currently unable to handle the request due to a '\n 'temporary overloading or maintenance of the server',\n\n # OpenID errors.\n # http://openid.net/specs/openid-connect-core-1_0.html#AuthError\n 'interaction_required': 'The Authorization Server requires End-User interaction of some form to proceed',\n\n 'login_required': 'The Authorization Server requires End-User authentication',\n\n 'account_selection_required': 'The End-User is required to select a session at the Authorization Server',\n\n 'consent_required': 'The Authorization Server requires End-User consent',\n\n 'invalid_request_uri': 'The request_uri in the Authorization Request returns an error or contains invalid data',\n\n 'invalid_request_object': 'The request parameter contains an invalid Request Object',\n\n 'request_not_supported': 'The provider does not support use of the request parameter',\n\n 'request_uri_not_supported': 'The provider does not support use of the request_uri parameter',\n\n 'registration_not_supported': 'The provider does not support use of the registration parameter',\n }\n\n def __init__(self, redirect_uri, error, grant_type):\n\n self.error = error\n self.description = self._errors.get(error)\n self.redirect_uri = redirect_uri\n self.grant_type = grant_type\n\n def create_uri(self, redirect_uri, state):\n\n description = urllib.quote(self.description)\n\n # See: http://openid.net/specs/openid-connect-core-1_0.html#ImplicitAuthError\n hash_or_question = '#' if self.grant_type == 'implicit' else '?'\n\n uri = '{0}{1}error={2}&error_description={3}'.format(\n redirect_uri,\n hash_or_question,\n self.error,\n description)\n\n # Add state if present.\n uri = uri + ('&state={0}'.format(state) if state else '')\n\n return uri\n\n @property\n def response(self):\n pass\n\n\nclass TokenError(Exception):\n\n _errors = {\n # Oauth2 errors.\n # https://tools.ietf.org/html/rfc6749#section-5.2\n 'invalid_request': 'The request is otherwise malformed',\n\n 'invalid_client': 'Client authentication failed (e.g., unknown client, no client authentication included, '\n 'or unsupported authentication method)',\n\n 'invalid_grant': 'The provided authorization grant or refresh token is invalid, expired, revoked, does not '\n 'match the redirection URI used in the authorization request, or was issued to another client',\n\n 'unauthorized_client': 'The authenticated client is not authorized to use this authorization grant type',\n\n 'unsupported_grant_type': 'The authorization grant type is not supported by the authorization server',\n\n 'invalid_scope': 'The requested scope is invalid, unknown, malformed, or exceeds the scope granted by the '\n 'resource owner',\n }\n\n def __init__(self, error):\n\n self.error = error\n self.description = self._errors.get(error)\n\n def create_dict(self):\n\n dic = {\n 'error': self.error,\n 'error_description': self.description,\n }\n\n return dic\n\n\nclass UserInfoError(Exception):\n _errors = {\n # Oauth2 errors.\n # https://tools.ietf.org/html/rfc6750#section-3.1\n 'invalid_request': (\n 'The request is otherwise malformed', 400\n ),\n 'invalid_token': (\n 'The access token provided is expired, revoked, malformed, or invalid for other reasons', 401\n ),\n 'insufficient_scope': (\n 'The request requires higher privileges than provided by the access token', 403\n ),\n }\n\n def __init__(self, code):\n\n self.code = code\n error_tuple = self._errors.get(code, ('', ''))\n self.description = error_tuple[0]\n self.status = error_tuple[1]\n" }, { "alpha_fraction": 0.649789035320282, "alphanum_fraction": 0.652953565120697, "avg_line_length": 29.612903594970703, "blob_id": "050bf3956a32caa61eeb9386bf3046ef0875eda4", "content_id": "945695f12a3b13e4d5bbd33e9ba3b121f8222cf8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 948, "license_type": "permissive", "max_line_length": 85, "num_lines": 31, "path": "/oidc_provider/lib/endpoints/discovery.py", "repo_name": "davidcerezal/django-oidc-provider", "src_encoding": "UTF-8", "text": "from django.core.urlresolvers import reverse\n\nfrom oidc_provider import settings\nfrom oidc_provider.lib.utils.common import get_issuer\n\n\nclass ProviderInfoEndpoint(object):\n\n @classmethod\n def create_response_dic(cls):\n dic = {}\n\n dic['issuer'] = get_issuer()\n\n SITE_URL = settings.get('SITE_URL')\n\n dic['authorization_endpoint'] = SITE_URL + reverse('oidc_provider:authorize')\n dic['token_endpoint'] = SITE_URL + reverse('oidc_provider:token')\n dic['userinfo_endpoint'] = SITE_URL + reverse('oidc_provider:userinfo')\n\n from oidc_provider.models import Client\n types_supported = [x[0] for x in Client.RESPONSE_TYPE_CHOICES]\n dic['response_types_supported'] = types_supported\n\n # TODO:\n #dic['jwks_uri'] = None\n\n # See: http://openid.net/specs/openid-connect-core-1_0.html#SubjectIDTypes\n dic['subject_types_supported'] = ['public']\n\n return dic" }, { "alpha_fraction": 0.5714285969734192, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 20, "blob_id": "4b92a7daa4e18d3447064cc91c0f9b6eb111b47e", "content_id": "3397367c12c46d51328b6b79947dc789b496d626", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 42, "license_type": "permissive", "max_line_length": 27, "num_lines": 2, "path": "/example_app/requirements.txt", "repo_name": "davidcerezal/django-oidc-provider", "src_encoding": "UTF-8", "text": "django==1.7.7\ndjango-oidc-provider==0.0.1\n" }, { "alpha_fraction": 0.6282508969306946, "alphanum_fraction": 0.6308006048202515, "avg_line_length": 21.55172348022461, "blob_id": "da4cc5ec90273860a71a7297a2e8c582e8ae930c", "content_id": "74d04cb1ecb3dca35b5ba5aa8abb95a2f33869d1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1961, "license_type": "permissive", "max_line_length": 77, "num_lines": 87, "path": "/oidc_provider/lib/utils/token.py", "repo_name": "davidcerezal/django-oidc-provider", "src_encoding": "UTF-8", "text": "from datetime import timedelta\nimport time\nimport uuid\n\nfrom django.utils import timezone\nimport jwt\n\nfrom oidc_provider.models import *\nfrom oidc_provider import settings\n\n\ndef create_id_token(iss, sub, aud, auth_time):\n \"\"\"\n Receives a user object, iss (issuer) and aud (audience).\n Then creates the id_token dic.\n See: http://openid.net/specs/openid-connect-core-1_0.html#IDToken\n\n Return a dic.\n \"\"\"\n expires_in = settings.get('OIDC_IDTOKEN_EXPIRE')\n\n now = timezone.now()\n\n # Convert datetimes into timestamps.\n iat_time = time.mktime(now.timetuple())\n exp_time = time.mktime((now + timedelta(seconds=expires_in)).timetuple())\n user_auth_time = time.mktime(auth_time.timetuple())\n\n dic = {\n 'iss': iss,\n 'sub': sub,\n 'aud': aud,\n 'exp': exp_time,\n 'iat': iat_time,\n 'auth_time': user_auth_time,\n }\n\n return dic\n\n\ndef encode_id_token(id_token_dic, client_secret):\n \"\"\"\n Represent the ID Token as a JSON Web Token (JWT).\n\n Return a hash.\n \"\"\"\n id_token_hash = jwt.encode(id_token_dic, client_secret)\n\n return id_token_hash\n\n\ndef create_token(user, client, id_token_dic, scope):\n \"\"\"\n Create and populate a Token object.\n\n Return a Token object.\n \"\"\"\n token = Token()\n token.user = user\n token.client = client\n token.access_token = uuid.uuid4().hex\n\n token.id_token = id_token_dic\n\n token.refresh_token = uuid.uuid4().hex\n token.expires_at = timezone.now() + timedelta(\n seconds=settings.get('OIDC_TOKEN_EXPIRE'))\n token.scope = scope\n\n return token\n\n\ndef create_code(user, client, scope):\n \"\"\"\n Create and populate a Code object.\n\n Return a Code object.\n \"\"\"\n code = Code()\n code.user = user\n code.client = client\n code.code = uuid.uuid4().hex\n code.expires_at = timezone.now() + timedelta(\n seconds=settings.get('OIDC_CODE_EXPIRE'))\n code.scope = scope\n\n return code" }, { "alpha_fraction": 0.5913271903991699, "alphanum_fraction": 0.5921156406402588, "avg_line_length": 28.27692222595215, "blob_id": "aaf4aa1265014b911177bb2154d9da3e86e13773", "content_id": "4850e30114fa9a613ce0c666b87a032ea6ba5015", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3805, "license_type": "permissive", "max_line_length": 79, "num_lines": 130, "path": "/oidc_provider/views.py", "repo_name": "davidcerezal/django-oidc-provider", "src_encoding": "UTF-8", "text": "from django.contrib.auth.views import redirect_to_login\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom django.shortcuts import render\nfrom django.template.loader import render_to_string\nfrom django.views.decorators.http import require_http_methods\nfrom django.views.generic import View\n\nfrom oidc_provider.lib.endpoints.authorize import *\nfrom oidc_provider.lib.endpoints.discovery import *\nfrom oidc_provider.lib.endpoints.token import *\nfrom oidc_provider.lib.endpoints.userinfo import *\nfrom oidc_provider.lib.errors import *\n\n\nclass AuthorizeView(View):\n\n def get(self, request, *args, **kwargs):\n\n authorize = AuthorizeEndpoint(request)\n\n try:\n authorize.validate_params()\n\n if request.user.is_authenticated():\n # Check if there's a hook setted.\n hook_resp = settings.get('OIDC_AFTER_USERLOGIN_HOOK')(\n request=request, user=request.user,\n client=authorize.client)\n if hook_resp:\n return hook_resp\n\n # Generate hidden inputs for the form.\n context = {\n 'params': authorize.params,\n }\n hidden_inputs = render_to_string(\n 'oidc_provider/hidden_inputs.html', context)\n\n # Remove `openid` from scope list\n # since we don't need to print it.\n authorize.params.scope.remove('openid')\n\n context = {\n 'client': authorize.client,\n 'hidden_inputs': hidden_inputs,\n 'params': authorize.params,\n }\n\n return render(request, 'oidc_provider/authorize.html', context)\n else:\n path = request.get_full_path()\n return redirect_to_login(path)\n\n except (ClientIdError, RedirectUriError) as error:\n context = {\n 'error': error.error,\n 'description': error.description,\n }\n\n return render(request, 'oidc_provider/error.html', context)\n\n except (AuthorizeError) as error:\n uri = error.create_uri(\n authorize.params.redirect_uri,\n authorize.params.state)\n\n return HttpResponseRedirect(uri)\n\n def post(self, request, *args, **kwargs):\n\n authorize = AuthorizeEndpoint(request)\n\n allow = True if request.POST.get('allow') else False\n\n try: \n uri = authorize.create_response_uri(allow)\n\n return HttpResponseRedirect(uri)\n\n except (AuthorizeError) as error:\n uri = error.create_uri(\n authorize.params.redirect_uri,\n authorize.params.state)\n\n return HttpResponseRedirect(uri)\n\n\nclass TokenView(View):\n\n def post(self, request, *args, **kwargs):\n \n token = TokenEndpoint(request)\n\n try:\n token.validate_params()\n\n dic = token.create_response_dic()\n\n return TokenEndpoint.response(dic)\n\n except (TokenError) as error:\n return TokenEndpoint.response(error.create_dict(), status=400)\n\n\n@require_http_methods(['GET', 'POST'])\ndef userinfo(request):\n\n userinfo = UserInfoEndpoint(request)\n \n try:\n userinfo.validate_params()\n\n dic = userinfo.create_response_dic()\n\n return UserInfoEndpoint.response(dic)\n\n except (UserInfoError) as error:\n return UserInfoEndpoint.error_response(\n error.code,\n error.description,\n error.status)\n\n\nclass ProviderInfoView(View):\n\n def get(self, request, *args, **kwargs):\n\n dic = ProviderInfoEndpoint.create_response_dic()\n\n return JsonResponse(dic)" }, { "alpha_fraction": 0.5338966250419617, "alphanum_fraction": 0.5366476774215698, "avg_line_length": 32.04545593261719, "blob_id": "0cf7f4cfe9a06535a9c9926c50816185c7937fc6", "content_id": "ff2e20675267628848cbe2e57a27accf3154e8cb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5089, "license_type": "permissive", "max_line_length": 99, "num_lines": 154, "path": "/oidc_provider/lib/endpoints/authorize.py", "repo_name": "davidcerezal/django-oidc-provider", "src_encoding": "UTF-8", "text": "from datetime import timedelta\nimport uuid\n\nfrom django.utils import timezone\n\nfrom oidc_provider.lib.errors import *\nfrom oidc_provider.lib.utils.common import get_issuer\nfrom oidc_provider.lib.utils.params import *\nfrom oidc_provider.lib.utils.token import *\nfrom oidc_provider.models import *\nfrom oidc_provider import settings\n\n\nclass AuthorizeEndpoint(object):\n\n def __init__(self, request):\n\n self.request = request\n\n self.params = Params()\n\n # Because in this endpoint we handle both GET\n # and POST request.\n self.query_dict = (self.request.POST if self.request.method == 'POST'\n else self.request.GET)\n\n self._extract_params()\n\n # Determine which flow to use.\n if self.params.response_type in ['code']:\n self.grant_type = 'authorization_code'\n elif self.params.response_type in ['id_token', 'id_token token']:\n self.grant_type = 'implicit'\n self._extract_implicit_params()\n else:\n self.grant_type = None\n\n def _extract_params(self):\n \"\"\"\n Get all the params used by the Authorization Code Flow\n (and also for the Implicit).\n\n See: http://openid.net/specs/openid-connect-core-1_0.html#AuthRequest\n \"\"\"\n self.params.client_id = self.query_dict.get('client_id', '')\n self.params.redirect_uri = self.query_dict.get('redirect_uri', '')\n self.params.response_type = self.query_dict.get('response_type', '')\n self.params.scope = self.query_dict.get('scope', '').split()\n self.params.state = self.query_dict.get('state', '')\n\n def _extract_implicit_params(self):\n \"\"\"\n Get specific params used by the Implicit Flow.\n\n See: http://openid.net/specs/openid-connect-core-1_0.html#ImplicitAuthRequest\n \"\"\"\n self.params.nonce = self.query_dict.get('nonce', '')\n\n def validate_params(self):\n\n if not self.params.redirect_uri:\n raise RedirectUriError()\n\n if not ('openid' in self.params.scope):\n raise AuthorizeError(\n self.params.redirect_uri,\n 'invalid_scope',\n self.grant_type)\n\n try:\n self.client = Client.objects.get(client_id=self.params.client_id)\n\n if not (self.params.redirect_uri in self.client.redirect_uris):\n raise RedirectUriError()\n\n if not self.grant_type or not (self.params.response_type == self.client.response_type):\n\n raise AuthorizeError(\n self.params.redirect_uri,\n 'unsupported_response_type',\n self.grant_type)\n\n except Client.DoesNotExist:\n raise ClientIdError()\n\n def create_response_uri(self, allow):\n\n if not allow:\n raise AuthorizeError(\n self.params.redirect_uri,\n 'access_denied',\n self.grant_type)\n\n try:\n self.validate_params()\n\n if self.grant_type == 'authorization_code':\n\n code = create_code(\n user=self.request.user,\n client=self.client,\n scope=self.params.scope)\n \n code.save()\n\n # Create the response uri.\n uri = self.params.redirect_uri + '?code={0}'.format(code.code)\n\n else: # Implicit Flow\n\n # TODO refactor since it's the same as the token endpoint\n sub = settings.get('OIDC_IDTOKEN_SUB_GENERATOR')(\n user=self.request.user)\n\n id_token_dic = create_id_token(\n iss=get_issuer(),\n sub=sub,\n aud=self.client.client_id,\n auth_time=self.request.user.last_login)\n\n token = create_token(\n user=self.request.user,\n client=self.client,\n id_token_dic=id_token_dic,\n scope=self.params.scope)\n\n # Store the token.\n token.save()\n\n id_token = encode_id_token(\n id_token_dic, self.client.client_secret)\n\n # Create the response uri.\n uri = self.params.redirect_uri + \\\n '#token_type={0}&id_token={1}&expires_in={2}'.format(\n 'bearer',\n id_token,\n 60 * 10,\n )\n\n # Check if response_type is 'id_token token' then\n # add access_token to the fragment.\n if self.params.response_type == 'id_token token':\n uri += '&access_token={0}'.format(token.access_token)\n except:\n raise AuthorizeError(\n self.params.redirect_uri,\n 'server_error',\n self.grant_type)\n\n # Add state if present.\n uri += ('&state={0}'.format(self.params.state) if self.params.state else '')\n\n return uri\n" }, { "alpha_fraction": 0.5228716731071472, "alphanum_fraction": 0.5304955244064331, "avg_line_length": 17.97590446472168, "blob_id": "f0a5d69cf541b2c8871f49bcf11c04e89faf3bbc", "content_id": "26288b8927ba510f53bfeb4550c952dc67010817", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1574, "license_type": "permissive", "max_line_length": 74, "num_lines": 83, "path": "/oidc_provider/settings.py", "repo_name": "davidcerezal/django-oidc-provider", "src_encoding": "UTF-8", "text": "from django.conf import settings\n\n\nclass DefaultSettings(object):\n\n @property\n def LOGIN_URL(self):\n \"\"\"\n REQUIRED.\n \"\"\"\n return None\n\n @property\n def SITE_URL(self):\n \"\"\"\n REQUIRED.\n \"\"\"\n return None\n\n @property\n def OIDC_AFTER_USERLOGIN_HOOK(self):\n \"\"\"\n OPTIONAL.\n \"\"\"\n def default_hook_func(request, user, client):\n return None\n\n return default_hook_func\n\n @property\n def OIDC_CODE_EXPIRE(self):\n \"\"\"\n OPTIONAL.\n \"\"\"\n return 60*10\n\n @property\n def OIDC_EXTRA_SCOPE_CLAIMS(self):\n \"\"\"\n OPTIONAL.\n \"\"\"\n from oidc_provider.lib.claims import AbstractScopeClaims\n\n return AbstractScopeClaims\n\n @property\n def OIDC_IDTOKEN_EXPIRE(self):\n \"\"\"\n OPTIONAL.\n \"\"\"\n return 60*10\n\n @property\n def OIDC_IDTOKEN_SUB_GENERATOR(self):\n \"\"\"\n OPTIONAL.\n \"\"\"\n def default_sub_generator(user):\n return user.id\n\n return default_sub_generator\n\n @property\n def OIDC_TOKEN_EXPIRE(self):\n \"\"\"\n OPTIONAL.\n \"\"\"\n return 60*60\n\ndefault_settings = DefaultSettings()\n\ndef get(name):\n '''\n Helper function to use inside the package.\n '''\n try:\n value = getattr(default_settings, name)\n value = getattr(settings, name)\n except AttributeError:\n if value == None:\n raise Exception('You must set ' + name + ' in your settings.')\n\n return value" }, { "alpha_fraction": 0.7538200616836548, "alphanum_fraction": 0.7538200616836548, "avg_line_length": 24.65217399597168, "blob_id": "a09b28c6b99dee78e53dd49623f18ee9ca914292", "content_id": "34dc26d9c155196afdf5633b3508b70107c7365b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 589, "license_type": "permissive", "max_line_length": 107, "num_lines": 23, "path": "/example_app/README.md", "repo_name": "davidcerezal/django-oidc-provider", "src_encoding": "UTF-8", "text": "# Example Django App\n\nThis is just a simple Django app with all the necessary things to work with `django-oidc-provider` package.\n\n## Setup & Running\n\nSetup project environment with [virtualenv](https://virtualenv.pypa.io) and [pip](https://pip.pypa.io).\n\n```bash\n$ virtualenv project_env\n$ source project_env/bin/activate\n$ git clone https://github.com/juanifioren/django-oidc-provider.git\n$ cd django-oidc-provider/example_app\n$ pip install -r requirements.txt\n```\n\nRun your provider.\n\n```bash\n$ python manage.py makemigrations\n$ python manage.py migrate\n$ python manage.py runserver\n```" }, { "alpha_fraction": 0.597743034362793, "alphanum_fraction": 0.6038556694984436, "avg_line_length": 34.30290603637695, "blob_id": "df9df50928ecd596c3a7d1b4b35492aed4cae7df", "content_id": "0deffa01677748334371408a743c7452df1852b7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8507, "license_type": "permissive", "max_line_length": 87, "num_lines": 241, "path": "/oidc_provider/tests/test_authorize_endpoint.py", "repo_name": "davidcerezal/django-oidc-provider", "src_encoding": "UTF-8", "text": "import urllib\nimport uuid\n\nfrom django.contrib.auth import REDIRECT_FIELD_NAME\nfrom django.contrib.auth.models import AnonymousUser\nfrom django.core.urlresolvers import reverse\nfrom django.test import RequestFactory\nfrom django.test import TestCase\n\nfrom oidc_provider import settings\nfrom oidc_provider.models import *\nfrom oidc_provider.tests.utils import *\nfrom oidc_provider.views import *\n\n\nclass AuthorizationCodeFlowTestCase(TestCase):\n \"\"\"\n Test cases for Authorize Endpoint using Authorization Code Flow.\n \"\"\"\n\n def setUp(self):\n self.factory = RequestFactory()\n self.user = create_fake_user()\n self.client = create_fake_client(response_type='code')\n self.state = uuid.uuid4().hex\n\n def test_missing_parameters(self):\n \"\"\"\n If the request fails due to a missing, invalid, or mismatching\n redirection URI, or if the client identifier is missing or invalid,\n the authorization server SHOULD inform the resource owner of the error.\n\n See: https://tools.ietf.org/html/rfc6749#section-4.1.2.1\n \"\"\"\n url = reverse('oidc_provider:authorize')\n\n request = self.factory.get(url)\n\n response = AuthorizeView.as_view()(request)\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(bool(response.content), True)\n\n def test_invalid_response_type(self):\n \"\"\"\n The OP informs the RP by using the Error Response parameters defined\n in Section 4.1.2.1 of OAuth 2.0.\n\n See: http://openid.net/specs/openid-connect-core-1_0.html#AuthError\n \"\"\"\n # Create an authorize request with an unsupported response_type.\n query_str = urllib.urlencode({\n 'client_id': self.client.client_id,\n 'response_type': 'something_wrong',\n 'redirect_uri': self.client.default_redirect_uri,\n 'scope': 'openid email',\n 'state': self.state,\n }).replace('+', '%20')\n\n url = reverse('oidc_provider:authorize') + '?' + query_str\n\n request = self.factory.get(url)\n\n response = AuthorizeView.as_view()(request)\n\n self.assertEqual(response.status_code, 302)\n self.assertEqual(response.has_header('Location'), True)\n\n # Should be an 'error' component in query.\n query_exists = 'error=' in response['Location']\n self.assertEqual(query_exists, True)\n\n def test_user_not_logged(self):\n \"\"\"\n The Authorization Server attempts to Authenticate the End-User by\n redirecting to the login view.\n\n See: http://openid.net/specs/openid-connect-core-1_0.html#Authenticates\n \"\"\"\n query_str = urllib.urlencode({\n 'client_id': self.client.client_id,\n 'response_type': 'code',\n 'redirect_uri': self.client.default_redirect_uri,\n 'scope': 'openid email',\n 'state': self.state,\n }).replace('+', '%20')\n\n url = reverse('oidc_provider:authorize') + '?' + query_str\n\n request = self.factory.get(url)\n request.user = AnonymousUser()\n\n response = AuthorizeView.as_view()(request)\n\n # Check if user was redirected to the login view.\n login_url_exists = settings.get('LOGIN_URL') in response['Location']\n self.assertEqual(login_url_exists, True)\n\n # Check if the login will redirect to a valid url.\n try:\n next_value = response['Location'].split(REDIRECT_FIELD_NAME + '=')[1]\n next_url = urllib.unquote(next_value)\n is_next_ok = next_url == url\n except:\n is_next_ok = False\n self.assertEqual(is_next_ok, True)\n\n def test_user_consent_inputs(self):\n \"\"\"\n Once the End-User is authenticated, the Authorization Server MUST\n obtain an authorization decision before releasing information to\n the Client.\n\n See: http://openid.net/specs/openid-connect-core-1_0.html#Consent\n \"\"\"\n query_str = urllib.urlencode({\n 'client_id': self.client.client_id,\n 'response_type': 'code',\n 'redirect_uri': self.client.default_redirect_uri,\n 'scope': 'openid email',\n 'state': self.state,\n }).replace('+', '%20')\n\n url = reverse('oidc_provider:authorize') + '?' + query_str\n\n request = self.factory.get(url)\n # Simulate that the user is logged.\n request.user = self.user\n\n # Remove the hook, because we want to test default behaviour.\n OIDC_AFTER_USERLOGIN_HOOK = settings.default_settings.OIDC_AFTER_USERLOGIN_HOOK\n with self.settings(\n OIDC_AFTER_USERLOGIN_HOOK=OIDC_AFTER_USERLOGIN_HOOK):\n response = AuthorizeView.as_view()(request)\n\n # Check if hidden inputs exists in the form,\n # also if their values are valid.\n input_html = '<input name=\"{0}\" type=\"hidden\" value=\"{1}\" />'\n\n to_check = {\n 'client_id': self.client.client_id,\n 'redirect_uri': self.client.default_redirect_uri,\n 'response_type': 'code',\n }\n\n for key, value in to_check.iteritems():\n is_input_ok = input_html.format(key, value) in response.content\n self.assertEqual(is_input_ok, True,\n msg='Hidden input for \"'+key+'\" fails.')\n\n def test_user_consent_response(self):\n \"\"\"\n First,\n if the user denied the consent we must ensure that\n the error response parameters are added to the query component\n of the Redirection URI.\n\n Second,\n if the user allow the RP then the server MUST return\n the parameters defined in Section 4.1.2 of OAuth 2.0 [RFC6749]\n by adding them as query parameters to the redirect_uri.\n \"\"\"\n response_type = 'code'\n\n url = reverse('oidc_provider:authorize')\n\n post_data = {\n 'client_id': self.client.client_id,\n 'redirect_uri': self.client.default_redirect_uri,\n 'response_type': response_type,\n 'scope': 'openid email',\n 'state': self.state,\n }\n\n request = self.factory.post(url, data=post_data)\n # Simulate that the user is logged.\n request.user = self.user\n\n response = AuthorizeView.as_view()(request)\n\n # Because user doesn't allow app, SHOULD exists an error parameter\n # in the query.\n self.assertEqual('error=' in response['Location'], True,\n msg='error param is missing.')\n self.assertEqual('access_denied' in response['Location'], True,\n msg='access_denied param is missing.')\n\n # Simulate user authorization.\n post_data['allow'] = 'Accept' # Should be the value of the button.\n\n request = self.factory.post(url, data=post_data)\n # Simulate that the user is logged.\n request.user = self.user\n\n response = AuthorizeView.as_view()(request)\n\n # Validate the code returned by the OP.\n code = (response['Location'].split('code='))[1].split('&')[0]\n try:\n code = Code.objects.get(code=code)\n is_code_ok = (code.client == self.client) and \\\n (code.user == self.user)\n except:\n is_code_ok = False\n self.assertEqual(is_code_ok, True,\n msg='Code returned is invalid.')\n\n # Check if the state is returned.\n state = (response['Location'].split('state='))[1].split('&')[0]\n self.assertEqual(state == self.state, True,\n msg='State change or is missing.')\n\n\nclass AuthorizationImplicitFlowTestCase(TestCase):\n \"\"\"\n Test cases for Authorize Endpoint using Implicit Flow.\n \"\"\"\n \n def setUp(self):\n self.factory = RequestFactory()\n self.user = create_fake_user()\n self.client = create_fake_client(response_type='id_token token')\n self.state = uuid.uuid4().hex\n\n # TODO\n def test_something(self):\n query_str = urllib.urlencode({\n 'client_id': self.client.client_id,\n 'response_type': 'id_token token',\n 'redirect_uri': self.client.default_redirect_uri,\n 'scope': 'openid email',\n 'state': self.state,\n }).replace('+', '%20')\n\n url = reverse('oidc_provider:authorize') + '#' + query_str\n\n request = self.factory.get(url)\n # Simulate that the user is logged.\n request.user = self.user\n\n response = AuthorizeView.as_view()(request)" } ]
18
MichaelHolley/Codewars.com_mySolutions
https://github.com/MichaelHolley/Codewars.com_mySolutions
1554b9a93eb21fcea26ae52ecd3d4ba7f2e30977
c9eec780c919b6698f2d4df23e71a617c5edd629
b08d9ea9e9a5cea7d6eede9cb0c96602dd9d2a84
refs/heads/master
2020-04-22T01:02:40.690721
2020-01-30T13:26:03
2020-01-30T13:26:03
170,001,521
1
1
null
null
null
null
null
[ { "alpha_fraction": 0.6200000047683716, "alphanum_fraction": 0.6679999828338623, "avg_line_length": 24, "blob_id": "bd92f10bea60847c940d36f52c8666f0f3986570", "content_id": "a2ef83b9789bf330e65d7ea08f3e4003dabcba07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 250, "license_type": "no_license", "max_line_length": 79, "num_lines": 10, "path": "/Java 8/4kyu - BinaryMultipleOf3.java", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "import java.util.regex.Pattern;\n\npublic class BinaryRegexp {\n\n public static Pattern multipleOf3() {\n // Regular expression that matches binary inputs that are multiple of 3\n return Pattern.compile(\"(0|11|10(1|00)*01)*\");\n }\n \n}\n" }, { "alpha_fraction": 0.49845200777053833, "alphanum_fraction": 0.5232198238372803, "avg_line_length": 25.91666603088379, "blob_id": "75aa2e44616f2abc300b74c5b3c714e1ee7b4a76", "content_id": "fb3d4d6165a94ce1adfa20519d8db74d4d2922ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 323, "license_type": "no_license", "max_line_length": 84, "num_lines": 12, "path": "/JS/6kyu - TribonacciSequence.js", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "function tribonacci(signature,n){\n if(n == 0) {\n return [];\n } else if(n < 3) {\n return signature.slice(0, n);\n }\n for(i = 0; i < n-3; i++) {\n let sumOfLastThree = signature[0 + i] + signature[1 + i] + signature[2 + i];\n signature.push(sumOfLastThree);\n }\n return signature;\n}\n" }, { "alpha_fraction": 0.5878787636756897, "alphanum_fraction": 0.5939394235610962, "avg_line_length": 28, "blob_id": "044f97da34980cdae56782ee1ce3fc9a53385f2d", "content_id": "fe0a05d3bc86ef7f6a7b371371389f84ad65f705", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 330, "license_type": "no_license", "max_line_length": 38, "num_lines": 11, "path": "/Python 3/7kyu - sumTwoSmallest.py", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "def sum_two_smallest_numbers(numbers):\r\n smallest = numbers[0]\r\n for x in numbers:\r\n if x < smallest:\r\n smallest = x\r\n numbers.remove(smallest)\r\n secondSmallest = numbers[0]\r\n for y in numbers:\r\n if y < secondSmallest:\r\n secondSmallest = y\r\n return smallest + secondSmallest\r\n" }, { "alpha_fraction": 0.28835979104042053, "alphanum_fraction": 0.29894179105758667, "avg_line_length": 20, "blob_id": "969767f513499cea9fcb4b1d94f7a279aca4a923", "content_id": "f53da55c9a2fdd825f9b038943a1fe2aa6222187", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 378, "license_type": "no_license", "max_line_length": 40, "num_lines": 18, "path": "/JS/5kyu - MemoizedFibonacci.js", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "var fibonacci = (function(n) {\n var memory = {};\n function f(n) {\n var x;\n if (n === 0 || n == 1) {\n return n;\n } else {\n if (n in memory) {\n x = memory[n];\n } else {\n x = f(n - 1) + f(n - 2);\n }\n memory[n] = x;\n }\n return x;\n }\n return f;\n})();\n" }, { "alpha_fraction": 0.7425607442855835, "alphanum_fraction": 0.7526617646217346, "avg_line_length": 68.77143096923828, "blob_id": "46dff46aed2cb2b14bcffa6d0419d9279ca77f95", "content_id": "6aa4a8d1ae105fee7421c3d2b55b73dc3eec45cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7326, "license_type": "no_license", "max_line_length": 317, "num_lines": 105, "path": "/JS/README.md", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "# Disclaimer\nThis is my folder where I collect my code and solutions for the codewars coding challenges for JavaScript.\nI just started learning JS, so the difficulty of it will increase.\n\n# KeepHydrated\nNathan loves cycling. Because Nathan knows it is important to stay hydrated, he drinks 0.5 litres of water per hour of cycling. You get given the time in hours and you need to return the number of litres Nathan will drink, rounded to the smallest value.\n\n# SmallestInteger\nReturn smallest integer in array.\n\n# ReversedString\nTakes a String as parameter and returns it reversed.\n\n# ComplementaryDNA\nIn DNA strings, symbols \"A\" and \"T\" are complements of each other, as \"C\" and \"G\". You have function with one side of the DNA (string, except for Haskell); you need to get the other complementary side. DNA strand is never empty or there is no DNA at all (again, except for Haskell).\n\n# CountingDoubles\nWrite a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits.\n- Example: \"aabBcde\" -> 2 # 'a' occurs twice and 'b' twice (`b` and `B`)\n\n# JadenCasingStrings\nJaden Smith, the son of Will Smith, is the star of films such as The Karate Kid (2010) and After Earth (2013). Jaden is also known for some of his philosophy that he delivers via Twitter. When writing on Twitter, he is known for almost always capitalizing every word.\nYour task is to convert strings to how they would be written by Jaden Smith. The strings are actual quotes from Jaden Smith, but they are not capitalized in the same way he originally typed them. Example:\n- Not Jaden-Cased: \"How can mirrors be real if our eyes aren't real\"\n- Jaden-Cased: \"How Can Mirrors Be Real If Our Eyes Aren't Real\"\n\n# EqualSidesOfArray\nYou are going to be given an array of integers. Your job is to take that array and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return -1.\n\n# MiddleCharacter\nWrite a function which returns the middle character of a string if the string has a odd length - and the middle two chars if it has even length.\n\n# FindOddInt\nGiven an array, find the int that appears an odd number of times. There will always be only one integer that appears an odd number of times.\n\n# OddOrEven\nReturn \"Odd\" if the given int is odd or \"Even\" if the given int is even.\n\n# VowelCount\nCount vowel-letter appearance (vowel: a, e, i, o, u) - Capital\n\n# Highest&Lowest\nIn this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number.\n\n# ShortestWord\nSimple, given a string of words, return the length of the shortest word(s). String will never be empty and you do not need to account for different data types.\n\n# ValidParentheses\nWrite a function called that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return true if the string is valid, and false if it's invalid.\n\n# SortArrayByStringLength\nWrite a function that takes an array of strings as an argument and returns a sorted array containing the same strings, ordered from shortest to longest.\n- For example, if this array were passed as an argument: [\"Telescopes\", \"Glasses\", \"Eyes\", \"Monocles\"]\n- Your function would return the following array: [\"Eyes\", \"Glasses\", \"Monocles\", \"Telescopes\"]\n\nAll of the strings in the array passed to your function will be different lengths, so you will not have to decide how to order multiple strings of the same length.\n\n# OddOrEvenArraysum\nGiven an array of numbers (a list in groovy), determine whether the sum of all of the numbers is odd or even. Give your answer in string format as 'odd' or 'even'.\n\n# WhoLikesIt\nYou probably know the \"like\" system from Facebook and other pages. People can \"like\" blog posts, pictures or other items. We want to create the text that should be displayed next to such an item.\nImplement a function likes :: [String] -> String, which must take in input array, containing the names of people who like an item. It must return the display text as shown in the examples:\n- likes [] // must be \"no one likes this\"\n- likes [\"Peter\"] // must be \"Peter likes this\"\n- likes [\"Jacob\", \"Alex\"] // must be \"Jacob and Alex like this\"\n- likes [\"Max\", \"John\", \"Mark\"] // must be \"Max, John and Mark like this\"\n- likes [\"Alex\", \"Jacob\", \"Mark\", \"Max\"] // must be \"Alex, Jacob and 2 others like this\"\n\n# TribonacciSequence\nWell met with Fibonacci bigger brother, AKA Tribonacci. As the name may already reveal, it works basically like a Fibonacci, but summing the last 3 (instead of 2) numbers of the sequence to generate the next. And, worse part of it, regrettably I won't get to hear non-native Italian speakers trying to pronounce it :(\n\n- So, if we are to start our Tribonacci sequence with [1, 1, 1] as a starting input (AKA signature), we have this sequence: [1, 1 ,1, 3, 5, 9, 17, 31, ...]\n\nBut what if we started with [0, 0, 1] as a signature? As starting with [0, 1] instead of [1, 1] basically shifts the common Fibonacci sequence by once place, you may be tempted to think that we would get the same sequence shifted by 2 places, but that is not the case and we would get:\n[0, 0, 1, 1, 2, 4, 7, 13, 24, ...]\n\n# TortoiseRacing\nTwo tortoises named A and B must run a race. A starts with an average speed of 720 feet per hour. Young B knows she runs faster than A, and furthermore has not finished her cabbage.\nWhen she starts, at last, she can see that A has a 70 feet lead but B's speed is 850 feet per hour. How long will it take B to catch A?\nMore generally: given two speeds v1 (A's speed, integer > 0) and v2 (B's speed, integer > 0) and a lead g (integer > 0) how long will it take B to catch A?\nThe result will be an array [hour, min, sec] which is the time needed in hours, minutes and seconds (round down to the nearest second) or a string in some languages.\n\n# MemoizedFibonacci\nhttps://www.codewars.com/kata/memoized-fibonacci\n\n# Mumbling\nThis time no story, no theory. The examples below show you how to write function accum:\nExamples:\n- accum(\"abcd\") -> \"A-Bb-Ccc-Dddd\"\n- accum(\"RqaEzty\") -> \"R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy\"\n- accum(\"cwAt\") -> \"C-Ww-Aaa-Tttt\"\n\nThe parameter of accum is a string which includes only letters from a..z and A..Z.\n\n# StopSpinningMyWords\nWrite a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present.\n\n# SumOfDigits / DigitalRoot\nA digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers.\n\n# MaximumSubarraySum\nThe maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers: \nmaxSequence([-2, 1, -3, 4, -1, 2, 1, -5, 4])\n// should be 6: [4, -1, 2, 1]\n" }, { "alpha_fraction": 0.7688171863555908, "alphanum_fraction": 0.7768816947937012, "avg_line_length": 45.5, "blob_id": "c0d64ce96eda8855b4508811b538032f6a8eea6d", "content_id": "e666362d1df2c3cadef3db710a4b6714129ec6df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 372, "license_type": "no_license", "max_line_length": 123, "num_lines": 8, "path": "/README.md", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "# Codewars.com_mySolutions\nThis is a collection of my solutions for the coding-challenges listed on codewars.com - this includes Java 1.8 and Python 3\n\n# My Profile\n[![Profile badge](https://www.codewars.com/users/MichaelHolley/badges/large)](https://www.codewars.com/users/MichaelHolley)\n\n# Website\n[Codewars.com Website](https://www.codewars.com \"codewars.com Website\")\n" }, { "alpha_fraction": 0.2980392277240753, "alphanum_fraction": 0.3176470696926117, "avg_line_length": 20.25, "blob_id": "f709edf7b04c2df5bdfd64857c93d5dd6f897388", "content_id": "dd8276a6d4acc2ca96a787d56d1a9002530a5c47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 255, "license_type": "no_license", "max_line_length": 38, "num_lines": 12, "path": "/JS/6kyu - FindOddInt.js", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "function findOdd(A) {\n for(i = 0; i < A.length; ++i) {\n var count = 0;\n for(j = 0; j < A.length; ++j){\n if(A[j] == A[i])\n count++;\n }\n if (count%2 == 1) {\n return A[i];\n }\n }\n}\n" }, { "alpha_fraction": 0.5123456716537476, "alphanum_fraction": 0.5339506268501282, "avg_line_length": 28.454545974731445, "blob_id": "ecd858479cb5224db7e61dffada5f1da7f200b83", "content_id": "32c44795c3334bf580ab85e53b631df07b406d20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 648, "license_type": "no_license", "max_line_length": 69, "num_lines": 22, "path": "/Python 3/6kyu - Valid_IPv4-Address.py", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "def is_valid_IP(strng):\n #Split input into list - split at '.'\n list = []\n list = strng.split('.')\n \n #check if list-length is 4\n if len(list) is not 4:\n return False\n \n #check every value in list and return false if false value occurs\n for s in list:\n #not digit\n if not s.isdigit():\n return False\n #check if value is 0\n if int(s) == 0:\n continue\n #check if value is > 255 or < 0 or has leading-zero\n if int(s) > 255 or int(s) < 0 or s.startswith(\"0\"):\n print(\"Num or leading 0 or not digit\")\n return False\n return True\n" }, { "alpha_fraction": 0.7127272486686707, "alphanum_fraction": 0.7200000286102295, "avg_line_length": 21.91666603088379, "blob_id": "5fe8097669e2b874aa8a00e6f3631b23e91787ea", "content_id": "7a36afc0c5f438547b2517cf6068c1a867c7d6f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 275, "license_type": "no_license", "max_line_length": 88, "num_lines": 12, "path": "/C#/6kyu - DetectPangram.cs", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\n\npublic static class Kata\n{\n public static bool IsPangram(string str)\n {\n return str.ToLower().Where(ch => Char.IsLetter(ch)).GroupBy(ch => ch).Count() == 26;\n }\n}\n" }, { "alpha_fraction": 0.51408451795578, "alphanum_fraction": 0.5246478915214539, "avg_line_length": 27.399999618530273, "blob_id": "f0b46525e890a9f9f2a6d897b90bd99d45930b72", "content_id": "3bea5717df59c983db6805b54006e9a07367874e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 284, "license_type": "no_license", "max_line_length": 67, "num_lines": 10, "path": "/Python 3/6kyu - CountCharsInString.py", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "def count(string):\n if string is \"\":\n return {}\n charDic = {}\n for i in range(0, len(string)):\n if string[i] not in charDic:\n charDic[string[i]] = 1\n else:\n charDic.update({string[i]: charDic.get(string[i]) + 1})\n return charDic\n" }, { "alpha_fraction": 0.4010416567325592, "alphanum_fraction": 0.4427083432674408, "avg_line_length": 26.428571701049805, "blob_id": "520aca893fa1f0e3e1e19af422d60e0ed71987c3", "content_id": "7eedc5e86267707055826da9b14974af9f36f7ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 192, "license_type": "no_license", "max_line_length": 54, "num_lines": 7, "path": "/Python 3/6kyu - SplitStrings.py", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "def solution(s):\n result = []\n if len(s)%2 == 0:\n return [s[i:i+2] for i in range(0, len(s), 2)]\n else:\n s += \"_\"\n return [s[i:i+2] for i in range(0, len(s), 2)]\n" }, { "alpha_fraction": 0.3325471580028534, "alphanum_fraction": 0.3396226465702057, "avg_line_length": 19.238094329833984, "blob_id": "a179a560697a3d2c91548d5445447e841f2c3fc7", "content_id": "a1528e68d196db6ea669f507bd4d6d185d449c59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 424, "license_type": "no_license", "max_line_length": 54, "num_lines": 21, "path": "/C#/7kyu-IsThisTriangle.cs", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "public class Triangle\n{\n public static bool IsTriangle(int a, int b, int c)\n {\n if(a <= 0 || b <= 0 || c<= 0)\n return false;\n \n if(a > b && a >= c && b + c > a) {\n return true;\n }\n if(b > a && b >= c && a + c > b) {\n return true;\n }\n if(c > a && c >= b && a + b> c) {\n return true;\n }\n \n return false;\n \n }\n}" }, { "alpha_fraction": 0.4513888955116272, "alphanum_fraction": 0.4583333432674408, "avg_line_length": 27, "blob_id": "1f9994952ef11c31b2b81e21354e4747f1a66560", "content_id": "8c2e4c4658eac71bcb3a2edc740a6b393a477d54", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 288, "license_type": "no_license", "max_line_length": 52, "num_lines": 10, "path": "/JS/6kyu - StopSpinningMyWords.js", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "function spinWords(s) {\r\n var words = s.split(\" \");\r\n for(var i = 0; i < words.length; i++) {\r\n if(words[i].length >= 5) {\r\n let wordArray = words[i].split(\"\");\r\n words[i] = wordArray.reverse().join(\"\");\r\n }\r\n }\r\n return words.join(\" \");\r\n}" }, { "alpha_fraction": 0.5271966457366943, "alphanum_fraction": 0.5313807725906372, "avg_line_length": 28.125, "blob_id": "16741b2b3ad60c46dd81a09a5cdbccbbe021bdde", "content_id": "d11e3d7b1616eca7c033f78911b8592bf0f17d61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 239, "license_type": "no_license", "max_line_length": 77, "num_lines": 8, "path": "/JS/7kyu - Mumbling.js", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "function accum(s) {\r\n\tvar chars = s.split(\"\");\r\n var words = new Array(s.length);\r\n for(i = 0; i < s.length; i++) {\r\n words[i] = chars[i].toUpperCase() + chars[i].toLowerCase().repeat(i);\r\n }\r\n return words.join(\"-\");\r\n}" }, { "alpha_fraction": 0.46721312403678894, "alphanum_fraction": 0.5, "avg_line_length": 19.5, "blob_id": "034d8839bdc348704548fe5b3abcc3148d2e60b8", "content_id": "323d8feb8c23ba77f491cb89162a6a76536987ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 122, "license_type": "no_license", "max_line_length": 30, "num_lines": 6, "path": "/Python 3/6kyu-FindUniqueNum.py", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "def find_uniq(arr):\n arr.sort()\n if arr[0] != arr[1]:\n return arr[0]\n else:\n return arr[len(arr)-1]" }, { "alpha_fraction": 0.6433408856391907, "alphanum_fraction": 0.6501128673553467, "avg_line_length": 35.91666793823242, "blob_id": "0490e1c99f05c005899b70e73b878f5934f4eec4", "content_id": "8c6b2ffa79966c9b8bf1b4bde07cc573d056308c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 443, "license_type": "no_license", "max_line_length": 111, "num_lines": 12, "path": "/Python 3/5kyu - BestTravel.py", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "from itertools import combinations\n\ndef choose_best_sum(t, k, ls):\n #t (maximum sum of distances, integer >= 0)\n #k (number of towns to visit, k >= 1) \n #ls (list of distances, all distances are positive or null integers and this list has at least one element)\n \n bestChoice = 0\n for c in combinations(ls, k):\n if bestChoice < sum(c) <= t:\n bestChoice = sum(c)\n return bestChoice if bestChoice else None\n" }, { "alpha_fraction": 0.5871211886405945, "alphanum_fraction": 0.6060606241226196, "avg_line_length": 23, "blob_id": "29daf68cff2cf834817a1a42156f4be4e48982c1", "content_id": "3e9c7911094e0745998b13f1ce52a27a3c347d74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 264, "license_type": "no_license", "max_line_length": 36, "num_lines": 11, "path": "/Python 3/8kyu - CountSheep.py", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "def count_sheeps(arrayOfSheeps):\n counter = 0\n i = 0\n while i < len(arrayOfSheeps):\n if arrayOfSheeps[i] is True:\n counter += 1\n i += 1\n return counter\n \ndef count_sheeps2(arrayOfSheeps):\n return arrayOfSheeps.count(True)\n" }, { "alpha_fraction": 0.46370968222618103, "alphanum_fraction": 0.47580644488334656, "avg_line_length": 19.66666603088379, "blob_id": "b6a8da280802b20c6ba1fb57b672b1b293ae22a2", "content_id": "1c37b99e1fefb669244f45f59db14283530094fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 248, "license_type": "no_license", "max_line_length": 42, "num_lines": 12, "path": "/JS/6kyu - SumOfDigits_DigitalRoot.js", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "function digital_root(n) {\n var nStr = n.toString();\n var sum = 0;\n for(var i = 0; i < nStr.length; i++) {\n sum += parseInt(nStr[i]);\n }\n if(sum <= 9) {\n return sum;\n } else {\n return digital_root(sum);\n }\n}\n" }, { "alpha_fraction": 0.45112180709838867, "alphanum_fraction": 0.49358972907066345, "avg_line_length": 26.733333587646484, "blob_id": "58497495261e7067c9b191d897363c0346b71915", "content_id": "e00ba9751a42bdf3fbebbaffc1510a09d5548067", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1248, "license_type": "no_license", "max_line_length": 68, "num_lines": 45, "path": "/Python 3/5kyu - TicTacToeChecker.py", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "def isSolved(board):\n #Variable if board has empty spots\n b = False\n \n #Check HorizontalRows\n for x in board:\n if checkRow(x) == \"X\":\n return 1\n elif checkRow(x) == \"O\":\n return 2\n elif checkRow(x) == 0:\n b = True\n \n #Check VerticalRows\n for i in range(len(board)):\n if checkRow([board[0][i],board[1][i],board[2][i]]) == \"X\":\n return 1\n elif checkRow([board[0][i],board[1][i],board[2][i]]) == \"O\":\n return 2\n\n #Diagonal LowerLeft2UpperRight\n if checkRow([board[2][0], board[1][1], board[0][2]]) == \"X\":\n return 1\n elif checkRow([board[2][0], board[1][1], board[0][2]]) == \"O\":\n return 2\n \n #Diagonal UpperLeft2LowerRight\n if checkRow([board[0][0], board[1][1], board[2][2]]) == \"X\":\n return 1\n elif checkRow([board[0][0], board[1][1], board[2][2]]) == \"O\":\n return 2\n\n #Dependent of Boolean b: True -> EMPTY | False -> DRAW\n if b == True:\n return -1\n elif b == False:\n return 0\n \ndef checkRow(arr):\n if arr[0] == arr[1] == arr[2] == 1:\n return \"X\"\n elif arr[0] == arr[1] == arr[2] == 2:\n return \"O\"\n elif 0 in arr:\n return 0\n" }, { "alpha_fraction": 0.3588850200176239, "alphanum_fraction": 0.39024388790130615, "avg_line_length": 21.076923370361328, "blob_id": "2458f395f2c1a01195e375a550373da760569cf3", "content_id": "2a627ed81e9b8cfe5660abd66640c70ed0545c4c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1435, "license_type": "no_license", "max_line_length": 65, "num_lines": 65, "path": "/Python 3/4kyu - HumanReadableDuration.py", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "def format_duration(seconds):\n #case if seconds == 0\n if seconds == 0: return \"now\"\n \n #initialize variables\n yrs, day, hrs, mns, sec = 0, 0, 0, 0, seconds\n unit, v = [], []\n y, d, h, m, s = \" year\", \" day\", \" hour\",\" minute\", \" second\"\n \n #calculate distribution of years, days, ...\n while sec >= 60:\n mns += 1\n sec -= 60 \n while mns >= 60:\n hrs += 1\n mns -= 60 \n while hrs >= 24:\n day += 1\n hrs -= 24; \n while day >= 365:\n yrs += 1\n day -= 365\n\n if yrs > 0:\n if yrs > 1:\n y += \"s\"\n unit.append(y)\n v.append(yrs)\n\n #edit values and presetstrings\n if day > 0:\n if day > 1:\n d += \"s\"\n unit.append(d)\n v.append(day)\n \n if hrs > 0:\n if hrs > 1:\n h += \"s\"\n unit.append(h)\n v.append(hrs)\n \n if mns > 0:\n if mns > 1:\n m += \"s\"\n unit.append(m)\n v.append(mns)\n \n if sec > 0:\n if sec > 1:\n s += \"s\"\n unit.append(s)\n v.append(sec)\n\n #addem together\n i = len(unit) -1\n res = \"\"\n while i >= 0:\n res = str(v[i]) +unit[i] + res \n if i == len(unit) -1 and len(unit) > 1:\n res = ' and ' +res\n elif i <= len(unit) -2 and i > 0:\n res = \", \" +res \n i -= 1\n return res\n" }, { "alpha_fraction": 0.6052631735801697, "alphanum_fraction": 0.6228070259094238, "avg_line_length": 11.666666984558105, "blob_id": "5a0faf020ac5d5cd8669081252f28084ad10afa0", "content_id": "47ce3f6f80b91e79c4bc415caee72ff0b522fd2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 114, "license_type": "no_license", "max_line_length": 36, "num_lines": 9, "path": "/C#/7kyu - IsSquare.cs", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "using System;\n\npublic class Kata\n{\n public static bool IsSquare(int n)\n {\n return Math.Sqrt(n)%1 == 0;\n }\n}\n" }, { "alpha_fraction": 0.4570637047290802, "alphanum_fraction": 0.4653739631175995, "avg_line_length": 29.08333396911621, "blob_id": "965f28e72cc0da5926cda14ba2c6207e5ad8c044", "content_id": "e1b9fadd72fcc343a9ab570ecbc530e41c57a7a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 361, "license_type": "no_license", "max_line_length": 64, "num_lines": 12, "path": "/Python 3/5kyu - MoveZerosToEnd.py", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "def move_zeros(array):\n rest = []\n zeros = []\n for i in range(len(array)):\n if array[i] == 0 or array[i] == 0.0:\n if type(array[i]) == int or type(array[i]) == float:\n zeros.append(array[i])\n else:\n rest.append(array[i])\n else:\n rest.append(array[i])\n return rest + zeros\n" }, { "alpha_fraction": 0.4013157784938812, "alphanum_fraction": 0.45394736528396606, "avg_line_length": 29.399999618530273, "blob_id": "a22f4f5cb20f0bb72550a39fd452c7fd04e60dd2", "content_id": "4ba712cd74890e8cb9b36bdaa7656c13d9108a15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 152, "license_type": "no_license", "max_line_length": 52, "num_lines": 5, "path": "/Python 3/7kyu - getMiddleChar.py", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "def get_middle(s):\n if len(s) % 2 == 1:\n return s[int(len(s)/2)]\n if len(s) % 2 == 0:\n return s[int((len(s)/2)-1)]+s[int(len(s)/2)]\n" }, { "alpha_fraction": 0.7238725423812866, "alphanum_fraction": 0.7428043484687805, "avg_line_length": 65.2959213256836, "blob_id": "16e13ea2698fb99d7c65adf8771967e2c9cf3728", "content_id": "d87cff92f8b34ece339d6aa4eec46d38898db965", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6497, "license_type": "no_license", "max_line_length": 503, "num_lines": 98, "path": "/Python 3/README.md", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "# VowelCount\nReturn the number (count) of vowels in the given string.\nWe will consider a, e, i, o, and u as vowels for this Kata.\nThe input string will only consist of lower case letters and/or spaces.\n\n# SumTwoSmallest\nCreate a function that returns the sum of the two lowest positive numbers given an array of minimum 4 integers. No floats or empty arrays will be passed.\nFor example, when an array is passed like [19, 5, 42, 2, 77], the output should be 7.\n\n# GetMiddleChar\nYou are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters.\n\n# CountingSheeps\nConsider an array of sheep where some sheep may be missing from their place. We need a function that counts the number of sheep present in the array (true means present).\nFor example,\n[True, True, True, False,\n True, True, True, True ,\n True, False, True, False,\n True, False, False, True ,\n True, True, True, True ,\n False, False, True, True]\nThe correct answer would be 17.\n\n# GrowthDurationTillTarget\nCalculates the duration till a amount/number of \"p0\" with a growth of percent \"percent\" with a additional amount of \"aug\" reaches value \"p\".\n\n# SplitStrings\nComplete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_').\n\n# RomanNumeralToInteger\nCreate a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral.\n\n# CountCharsInString\nThe main idea is to count all the occuring characters(UTF-8) in string. If you have string like this aba then the result should be { 'a': 2, 'b': 1 }\nWhat if the string is empty ? Then the result should be empty object literal { }\n\n# Delete occurrences of an element if it occurs more than n times\nGiven a list lst and a number N, create a new list that contains each number of lst at most N times without reordering. For example if N = 2, and the input is [1,2,3,1,2,1,2,3], you take [1,2,3,1,2], drop the next [1,2] since this would lead to 1 and 2 being in the result 3 times, and then take 3, which leads to [1,2,3,1,2,3].\n\n# PartOfAList\nWrite a function partlist that gives all the ways to divide a list (an array) of at least two elements into two non-empty parts.\na = [\"az\", \"toto\", \"picaro\", \"zone\", \"kiwi\"] -->\n[[\"az\", \"toto picaro zone kiwi\"], [\"az toto\", \"picaro zone kiwi\"], [\"az toto picaro\", \"zone kiwi\"], [\"az toto picaro zone\", \"kiwi\"]]\n\n# Valid_IPv4_Address\nWrite an algorithm that will identify valid IPv4 addresses in dot-decimal format. IPs should be considered valid if they consist of four octets, with values between 0 and 255, inclusive.\nInput to the function is guaranteed to be a single string.\n\n# Perimeter of squares in a rectangle\nThe drawing shows 6 squares the sides of which have a length of 1, 1, 2, 3, 5, 8. It's easy to see that the sum of the perimeters of these squares is : 4 * (1 + 1 + 2 + 3 + 5 + 8) = 4 * 20 = 80\nCould you give the sum of the perimeters of all the squares in a rectangle when there are n + 1 squares?!\n\n# Permutations\nIn this kata you have to create all permutations of an input string and remove duplicates, if present. This means, you have to shuffle all letters from the input in all possible orders.\n\n# BouncingBall\nA child is playing with a ball on the nth floor of a tall building. The height of this floor, h, is known. He drops the ball out of the window. The ball bounces (for example), to two-thirds of its height (a bounce of 0.66). His mother looks out of a window 1.5 meters from the ground.\nHow many times will the mother see the ball pass in front of her window (including when it's falling and bouncing?)\nThree conditions must be met for a valid experiment:\n- Float parameter \"h\" in meters must be greater than 0\n- Float parameter \"bounce\" must be greater than 0 and less than 1\n- Float parameter \"window\" must be less than h.\n\nIf all three conditions above are fulfilled, return a positive integer, otherwise return -1.\n\n# TicTacToe-Checker\nIf we were to set up a Tic-Tac-Toe game, we would want to know whether the board's current state is solved, wouldn't we? Our goal is to create a function that will check that for us!\nAssume that the board comes in the form of a 3x3 array, where the value is 0 if a spot is empty, 1 if it is an \"X\", or 2 if it is an \"O\", like so:\n[[0, 0, 1],\n [0, 1, 2],\n [2, 1, 0]]\nWe want our function to return:\n- -1 if the board is not yet finished (there are empty spots),\n- 1 if \"X\" won,\n- 2 if \"O\" won,\n- 0 if it's a cat's game (i.e. a draw).\n\nYou may assume that the board passed in is valid in the context of a game of Tic-Tac-Toe.\n\n# GreedIsGood\nhttps://www.codewars.com/kata/greed-is-good/python\n\n# HumanReadableDuration\nYour task in order to complete this Kata is to write a function which formats a duration, given as a number of seconds, in a human-friendly way.\nThe function must accept a non-negative integer. If it is zero, it just returns \"now\". Otherwise, the duration is expressed as a combination of years, days, hours, minutes and seconds.\nIt is much easier to understand with an example:\n- format_duration(62) # returns \"1 minute and 2 seconds\"\n- format_duration(3662) # returns \"1 hour, 1 minute and 2 seconds\"\n\n# JosephusPermutation\nhttps://www.codewars.com/kata/josephus-permutation/python\n\n# MoveZerosToEnd\nWrite an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.\n\n# Best Travel\nJohn and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns. ls = [50, 55, 57, 58, 60]. John is tired of driving and he says to Mary that he doesn't want to drive more than t = 174 miles and he will visit only 3 towns.\nThe function chooseBestSum (or choose_best_sum or ... depending on the language) will take as parameters t (maximum sum of distances, integer >= 0), k (number of towns to visit, k >= 1) and ls (list of distances, all distances are positive or null integers and this list has at least one element). The function returns the \"best\" sum ie the biggest possible sum of k distances less than or equal to the given limit t, if that sum exists, or otherwise nil, null, None, Nothing, depending on the language.\n" }, { "alpha_fraction": 0.3526569902896881, "alphanum_fraction": 0.4202898442745209, "avg_line_length": 17.81818199157715, "blob_id": "c44cd61aaacf36070c2fe2e27809a85b4643360e", "content_id": "08203558b4464e292770252d65965ffe823e0fb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 207, "license_type": "no_license", "max_line_length": 27, "num_lines": 11, "path": "/Python 3/5kyu - PerimeterOfSquareInRectangle.py", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "def perimeter(n):\n if not n > 1:\n return False\n sum = 2\n f1 = f2 = 1\n for i in range(2, n+1):\n temp = f2\n f2 = f1 + f2\n f1 = temp\n sum += f2\n return 4 * sum\n" }, { "alpha_fraction": 0.6454545259475708, "alphanum_fraction": 0.6454545259475708, "avg_line_length": 20.399999618530273, "blob_id": "2dc009eaba14db4ddcae2ff83d26534a56e8073e", "content_id": "5f701031358943467318f0b7ba5e8559488b6e6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 110, "license_type": "no_license", "max_line_length": 40, "num_lines": 5, "path": "/JS/8kyu - SmallestInteger.js", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "class SmallestIntegerFinder {\r\n findSmallestInt(args) {\r\n return Math.min.apply(null, args);\r\n }\r\n}" }, { "alpha_fraction": 0.43103447556495667, "alphanum_fraction": 0.4396551847457886, "avg_line_length": 23.421052932739258, "blob_id": "b326191c81d0a32618deb7465e4a956d26be36ac", "content_id": "f0e2ee5cfadcc01059e77b4c6675583cbc254378", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 464, "license_type": "no_license", "max_line_length": 52, "num_lines": 19, "path": "/Python 3/6kyu - DeleteN-th+OccurenceInList.py", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "def delete_nth(order,max_e):\n for x in order:\n counter = 0\n index = -1\n for y in order:\n index += 1\n if x == y:\n counter += 1\n if counter > max_e:\n del order[index]\n return order\n \n# -------------------------\n \ndef delete_nth_alternative(order, max_e):\n answer = []\n for x in order:\n if answer.count(x) < max_e: answer.append(x)\n return answer\n" }, { "alpha_fraction": 0.5416666865348816, "alphanum_fraction": 0.5601851940155029, "avg_line_length": 23, "blob_id": "279eaef02f3c96270d13e4cd4c68fe6da76b75f5", "content_id": "5d053c21b4b5f25d6e5103f8c59a1470bd9fd069", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 216, "license_type": "no_license", "max_line_length": 87, "num_lines": 9, "path": "/C#/7kyu - FindTheStrayNumbers.cs", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "using System;\nclass Solution \n{\n public static int Stray(int[] numbers)\n {\n Array.Sort(numbers);\n return numbers[0] == numbers[1] ? numbers[numbers.Length - 1] : numbers[0];\n }\n}\n" }, { "alpha_fraction": 0.3692307770252228, "alphanum_fraction": 0.4338461458683014, "avg_line_length": 24, "blob_id": "2f2b554b57f75015cdd5d62538288c0a035a8696", "content_id": "d9b70d76e0cc75017e2bd91220b5de5c8576102b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 325, "license_type": "no_license", "max_line_length": 46, "num_lines": 13, "path": "/Python 3/5kyu - GreedIsGood.py", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "def score(dice):\n result = 0\n for x in range(1, 7):\n if x == 1:\n if dice.count(x) >= 3:\n result += 1000 \n result += 100 * (dice.count(x) % 3)\n else:\n if dice.count(x) >= 3:\n result += 100 * x\n if x == 5:\n result += 50 * (dice.count(x) % 3)\n return result\n" }, { "alpha_fraction": 0.3085399568080902, "alphanum_fraction": 0.3112947642803192, "avg_line_length": 22.33333396911621, "blob_id": "ab9a70149716969f96111de7f1ffaa691dda613e", "content_id": "2076e06123ed7e89b9363c675d3bd1ba4b9c7001", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 363, "license_type": "no_license", "max_line_length": 37, "num_lines": 15, "path": "/JS/7kyu - DNA_Strand.js", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "function DNAStrand(dna){\r\n let comp = \"\";\r\n for(i = 0; i < dna.length; i++) {\r\n if(dna[i] == 'T') {\r\n comp += 'A';\r\n } else if(dna[i] == 'A') {\r\n comp += 'T';\r\n } else if(dna[i] == 'G') {\r\n comp += 'C';\r\n } else if(dna[i] == 'C') {\r\n comp += 'G';\r\n }\r\n }\r\n return comp;\r\n}" }, { "alpha_fraction": 0.4649122953414917, "alphanum_fraction": 0.49561402201652527, "avg_line_length": 21.799999237060547, "blob_id": "1144312be37ad5313655fb0c9e41ecf76f68f9d5", "content_id": "23e0f3bb3ff34cb91afc1a74f9fe3ae20b97e42e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 228, "license_type": "no_license", "max_line_length": 36, "num_lines": 10, "path": "/Python 3/6kyu - BouncingBall.py", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "def bouncingBall(h, bounce, window):\n if bounce > 1 or bounce < 0:\n return -1\n count = 0\n while h > window:\n count += 1\n h *= bounce\n if h > window:\n count += 1\n return count or -1\n" }, { "alpha_fraction": 0.49226805567741394, "alphanum_fraction": 0.5, "avg_line_length": 24, "blob_id": "b78892df3ed53dd3994e7bfca693c9a1ebf64cbf", "content_id": "a4a064cdd5284eb0782cb0d819ffef358ca58825", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 388, "license_type": "no_license", "max_line_length": 41, "num_lines": 15, "path": "/JS/7kyu - HighestAndLowest.js", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "function highAndLow(numbers){\r\n var numArray = numbers.split(' ');\r\n var max = numArray[0];\r\n var min = numArray[0];\r\n for(i = 0; i < numArray.length; i++){\r\n if(parseInt(numArray[i]) > max){\r\n max = numArray[i];\r\n }\r\n if(parseInt(numArray[i]) < min){\r\n min = numArray[i]\r\n }\r\n }\r\n var result = max + ' ' + min;\r\n return result;\r\n }" }, { "alpha_fraction": 0.7763066291809082, "alphanum_fraction": 0.7825784087181091, "avg_line_length": 88.6875, "blob_id": "a1f6b6da1c2d7595dedc1a2fa8cea6b01a85f64a", "content_id": "2f5d70a968723638c1633e8d27f44209a05a733f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1435, "license_type": "no_license", "max_line_length": 299, "num_lines": 16, "path": "/C#/README.md", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "# Disclaimer\nThis is my folder where I collect my code and solutions for the codewars coding challenges for C#. I just started learning C#, so the difficulty of it will increase.\n\n# FindTheStrayNumber\nYou are given an odd-length array of integers, in which all of them are the same, except for one single number. Complete the method which accepts such an array, and returns that single different number.\n\n# DetectPangram\nA pangram is a sentence that contains every single letter of the alphabet at least once. For example, the sentence \"The quick brown fox jumps over the lazy dog\" is a pangram, because it uses the letters A-Z at least once (case is irrelevant).\n\n# ConvertBoolToYesAndNo\nComplete the method that takes a boolean value and return a \"Yes\" string for true, or a \"No\" string for false.\n\n# Vasya-Clerk\nThe new \"Avengers\" movie has just been released! There are a lot of people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 dollars bill. An \"Avengers\" ticket costs 25 dollars.\nVasya is currently working as a clerk. He wants to sell a ticket to every single person in this line.\nCan Vasya sell a ticket to each person and give the change if he initially has no money and sells the tickets strictly in the order people follow in the line? Return YES, if Vasya can sell a ticket to each person and give the change with the bills he has at hand at that moment. Otherwise return NO.\n" }, { "alpha_fraction": 0.5187667608261108, "alphanum_fraction": 0.5616621971130371, "avg_line_length": 25.64285659790039, "blob_id": "6fd26b31881f4178b2b17db1e52890b0c783745d", "content_id": "bf0805b4bb77cf04bda532b813ec09b95568d572", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 746, "license_type": "no_license", "max_line_length": 62, "num_lines": 28, "path": "/Java 8/6kyu - ExpandForm.java", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "public class Kata {\n\t\n\tpublic static String expandedForm(int num) {\n\t\tString s = Integer.toString(num);\n\t\tString result = \"\";\n\t\tfor (int i = 0; i < s.length(); i++) {\n\t\t\tif (s.charAt(i) != '0') {\n\t\t\t\tresult += s.charAt(i);\n\t\t\t\tfor (int j = 0; j < s.length() - 1 - i; j++) {\n\t\t\t\t\tresult += \"0\";\n\t\t\t\t}\n\t\t\t\tif(i != s.length()-1 && !s.substring(i+1).matches(\"[0]+\"))\n\t\t\t\t\tresult += \" + \";\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic static void main(String args[]) {\n\t\tSystem.out.println(expandedForm(42));\n\t\tSystem.out.println(\"----------\");\n\t\tSystem.out.println(expandedForm(70304));\n\t\tSystem.out.println(\"----------\");\n\t\tSystem.out.println(expandedForm(11050600));\n\t\tSystem.out.println(\"----------\");\n\t\tSystem.out.println(expandedForm(210123010));\n\t}\n}\n" }, { "alpha_fraction": 0.7441728115081787, "alphanum_fraction": 0.7632177472114563, "avg_line_length": 54.841270446777344, "blob_id": "1cf12dcb64172d7bc518e12bc06acdbbddb20634", "content_id": "badb35ef886dfe9a410df16360064198440a8388", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3518, "license_type": "no_license", "max_line_length": 375, "num_lines": 63, "path": "/Java 8/README.md", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "# MakeNegative\nIn this simple assignment you are given a number and have to make it negative. But maybe the number is already negative?\n\n# CountPositivesSumNegatives\nGiven an array of integers.\nReturn an array, where the first element is the count of positives numbers and the second element is sum of negative numbers.\nIf the input array is empty or null, return an empty array.\n\n# ExpandedForm\nYou will be given a number and you will need to return it as a string in Expanded Form. For example:\n- Kata.expandedForm(12); # Should return \"10 + 2\"\n- Kata.expandedForm(42); # Should return \"40 + 2\"\n- Kata.expandedForm(70304); # Should return \"70000 + 300 + 4\"\n\nNOTE: All numbers will be whole numbers greater than 0.\n\n# TrippleDouble\n- Return 1, if first long containts a digit 3 times in a row and the second long contains that digit 2 times\n- Return 0, if not\n\n# IntToRomanNumeral\nWrite a method which takes a int as parameter and returns a String which represents the result as roman numeral.\n\n# AgePrediction\nMy grandfather always predicted how old people would get, and right before he passed away he revealed his secret!\nIn honor of my grandfather's memory we will write a function using his formula!\n- Take a list of ages when each of your great-grandparent died.\n- Multiply each number by itself.\n- Add them all together.\n- Take the square root of the result.\n- Divide by two.\n\n# Accumulation_Mumbling\nThis time no story, no theory. The examples below show you how to write function accum:\n- accum(\"abcd\") -> \"A-Bb-Ccc-Dddd\"\n- accum(\"RqaEzty\") -> \"R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy\"\n- accum(\"cwAt\") -> \"C-Ww-Aaa-Tttt\"\n\n# AddTwo\nDescription:\nWrite a function that takes an array of numbers (integers for the tests) and a target number. It should find two different items in the array that, when added together, give the target value. The indices of these items should then be returned in an array like so: [index1, index2].\nFor the purposes of this kata, some tests may have multiple answers; any valid solutions will be accepted.\n\n# PigLatin\nMove the first letter of each word to the end of it, then add \"ay\" to the end of the word. Leave punctuation marks untouched.\n\n# Stocklist\nA bookseller has lots of books classified in 26 categories labeled A, B, ... Z. Each book has a code c of 3, 4, 5 or more capitals letters. The 1st letter of a code is the capital letter of the book category. In the bookseller's stocklist each code c is followed by a space and by a positive integer n (int n >= 0) which indicates the quantity of books of this code in stock.\n\n# HumanReadableTime\nWrite a function, which takes a non-negative integer (seconds) as input and returns the time in a human-readable format (HH:MM:SS)\n- HH = hours, padded to 2 digits, range: 00 - 99\n- MM = minutes, padded to 2 digits, range: 00 - 59\n- SS = seconds, padded to 2 digits, range: 00 - 59\n\nThe maximum time never exceeds 359999 (99:59:59)\n\n# SortTheOdd\nYou have an array of numbers. Your task is to sort ascending odd numbers but even numbers must be on their places.\nZero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it.\n\n# SudokuValidator\nWrite a function validSolution/ValidateSolution/valid_solution() that accepts a 2D array representing a Sudoku board, and returns true if it is a valid solution, or false otherwise. The cells of the sudoku board may also contain 0's, which will represent empty cells. Boards containing one or more zeroes are considered to be invalid solutions.\n" }, { "alpha_fraction": 0.4424242377281189, "alphanum_fraction": 0.46666666865348816, "avg_line_length": 22.571428298950195, "blob_id": "20540b829dd69b77b44036962b6919e6a19b7be0", "content_id": "1549f121c168b012f030e132f5d588ed80cc6dda", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 165, "license_type": "no_license", "max_line_length": 44, "num_lines": 7, "path": "/JS/7kyu - OddOrEvenArraysum.js", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "function oddOrEven(array) {\n var sum = 0;\n for(var i = 0; i < array.length; i ++)\n sum += array[i];\n \n return sum % 2 == 0 ? \"even\" : \"odd\";\n}\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5561797618865967, "avg_line_length": 25.370370864868164, "blob_id": "b3990e4c65740849843d258f69280b7f310eb0b1", "content_id": "c6c2bf9150e44b5a115f9854e676ab7669324ac9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 712, "license_type": "no_license", "max_line_length": 65, "num_lines": 27, "path": "/JS/6kyu - TortoiseRacing.js", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "function race(v1, v2, g) {\n //v1 and v1 in feet per second\n var v1_feetPerSecond = v1 / 3600;\n var v2_feetPerSecond = v2 / 3600;\n var v1_distanceTravelled = g;\n var v2_distanceTravelled = 0;\n var secondsPassed = 0;\n\n if(v1 > v2) {\n return null;\n } else {\n //seconds passed till A and B travelled the same distance\n secondsPassed = Math.floor(g / (v2 - v1) * 3600);\n }\n \n //convert seconds and return [h:m:s]\n var hours = 0;\n var minutes = 0;\n while(secondsPassed >= 60) {\n minutes += 1;\n secondsPassed -= 60;\n }\n while(minutes >= 60) {\n hours += 1;\n minutes -= 60;\n }\n return [hours, minutes, secondsPassed];\n" }, { "alpha_fraction": 0.4960629940032959, "alphanum_fraction": 0.5118110179901123, "avg_line_length": 27.22222137451172, "blob_id": "34dfa0fc41f4bda7cb878751557787029aa04c21", "content_id": "ab3378ab2c47bb3ee9e5fd8917d653684369d1b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 254, "license_type": "no_license", "max_line_length": 48, "num_lines": 9, "path": "/Python 3/5kyu - JosephusPermutation.py", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "def josephus(items,k):\n result = []\n index = 0\n for i in range(0, len(items)):\n while len(items) > 0:\n index = (index + k - 1) % len(items)\n result.append(items[index])\n del items[index]\n return result\n" }, { "alpha_fraction": 0.6421052813529968, "alphanum_fraction": 0.6473684310913086, "avg_line_length": 46.5, "blob_id": "cb56dbd907406ce9fb55a22f3d2099ae59b4899e", "content_id": "d7b741aa37b0b78b6ed4df641bb237e3d9de4442", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 190, "license_type": "no_license", "max_line_length": 124, "num_lines": 4, "path": "/Python 3/7kyu - VowelCount.py", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "def getCount(inputStr):\n num_vowels = 0\n num_vowels = inputStr.count(\"a\") + inputStr.count(\"e\") + inputStr.count(\"i\") + inputStr.count(\"u\") + inputStr.count(\"o\")\n return num_vowels\n" }, { "alpha_fraction": 0.6095890402793884, "alphanum_fraction": 0.6301369667053223, "avg_line_length": 22.360000610351562, "blob_id": "14499ce367a4661e74b059bd8738e0023ac584ab", "content_id": "d95dd56d9a3dc8d0c398915f882fe21179b3b22e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 584, "license_type": "no_license", "max_line_length": 147, "num_lines": 25, "path": "/Java 8/5kyu - HumanReadableTime.java", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "public class HumanReadableTime {\n\tpublic static String makeReadable(int seconds) {\n\t\tint sec = 0;\n\t\tint min = 0;\n\t\tint hours = 0;\n\t\twhile(seconds != 0) {\n\t\t\tsec++;\n\t\t\tif(sec > 59) {\n\t\t\t\tsec = 0;\n\t\t\t\tmin++;\n\t\t\t\tif(min > 59) {\n\t\t\t\t\tmin = 0;\n\t\t\t\t\thours++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tseconds--;\n\t\t}\n\t\treturn intToTwoDigitStringWithLeadingZero(hours) + \":\" + intToTwoDigitStringWithLeadingZero(min) + \":\" + intToTwoDigitStringWithLeadingZero(sec);\n\t}\n\t\n\tpublic static String intToTwoDigitStringWithLeadingZero(int x) {\n\t\tif(x <= 9) return \"0\" + String.valueOf(x);\n\t\telse return String.valueOf(x);\n\t}\n}\n" }, { "alpha_fraction": 0.4610389471054077, "alphanum_fraction": 0.4740259647369385, "avg_line_length": 20.285715103149414, "blob_id": "622ea680c6ed929ade88b6c75815add6471782dd", "content_id": "0b7fa9fdd82421ee4ba87eebdc6d5bae6d303516", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 154, "license_type": "no_license", "max_line_length": 42, "num_lines": 7, "path": "/JS/8kyu - ReversedString.js", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "function solution(str){\r\n string = \"\";\r\n for(i = 0; i < str.length; i++) {\r\n string += str[str.length - 1 - i];\r\n }\r\n return string;\r\n}" }, { "alpha_fraction": 0.503496527671814, "alphanum_fraction": 0.5268065333366394, "avg_line_length": 18.5, "blob_id": "cadbb9a52ec54266723540b4091f0eb6edca3ae4", "content_id": "4fe6ba0c75fe881c02f7904bc595afe515a258e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 429, "license_type": "no_license", "max_line_length": 43, "num_lines": 22, "path": "/Python 3/6kyu - GrowthDurationTillTarget.py", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "def solution(number):\n result = []\n \n list3 = (multipleTillBorder(3, number))\n result += list3\n\n list5 = (multipleTillBorder(5, number))\n for x in list5:\n if x not in result:\n result.append(x)\n\n result.sort()\n return sum(result)\n \n\ndef multipleTillBorder(x , b):\n result = []\n i = 0\n while x * (i + 1) < b:\n result.append(x * (i + 1))\n i += 1\n return result\n" }, { "alpha_fraction": 0.5796703100204468, "alphanum_fraction": 0.6153846383094788, "avg_line_length": 20.41176414489746, "blob_id": "c000e7d0e3e3c63e5d7ba54a8c1bfa0bf960b8e5", "content_id": "c58cb55830474f53fbc722610f05a9eecedacac1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 364, "license_type": "no_license", "max_line_length": 58, "num_lines": 17, "path": "/Java 8/6kyu - TrippleDouble.java", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "public class Kata {\n\n\tpublic static int TripleDouble(long num1, long num2) {\n\t\tString sNum1 = String.valueOf(num1);\n\t\tString sNum2 = String.valueOf(num2);\n\t\tfor (int i = 0; i < 10; i++) {\n\t\t\tString n = String.valueOf(i);\n\t\t\tif (sNum1.contains(n + n + n) && sNum2.contains(n + n))\n\t\t\t\treturn 1;\n\t\t}\n\t\treturn 0;\n\t}\n\n\tpublic static void main(String args[]) {\n\t\t\n\t}\n}\n" }, { "alpha_fraction": 0.4920634925365448, "alphanum_fraction": 0.5026454925537109, "avg_line_length": 26, "blob_id": "831323d0bc1f37d9bf1f9afe36936ff1d580c12d", "content_id": "2bb0570e69f0fac9e4693100a9dd666843129d35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 189, "license_type": "no_license", "max_line_length": 35, "num_lines": 7, "path": "/Python 3/7kyu - PartsOfAList.py", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "def partlist(arr):\n result = []\n for i in range(1, len(arr)):\n first = ' '.join(arr[0:i])\n sec = ' '.join(arr[i:])\n result.append((first, sec))\n return result\n" }, { "alpha_fraction": 0.4413265287876129, "alphanum_fraction": 0.4948979616165161, "avg_line_length": 24.29032325744629, "blob_id": "990cf027ae85b5e03ea1899e57bf85ef0067a876", "content_id": "868d41e3c95b899fa1048b76f1815ff7498e9a03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 784, "license_type": "no_license", "max_line_length": 58, "num_lines": 31, "path": "/Java 8/4kyu - SudokuValidator.java", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "public class SudokuValidator {\n\n\tpublic static boolean check(int[][] sudoku) {\n\t\tint[] sumColumns = new int[] {0,0,0,0,0,0,0,0,0};\n\t\tint[] sumLines = new int[] {0,0,0,0,0,0,0,0,0};\n\t\tint[][] sumBoard = new int[3][3];\n\t\t\n\t\t//Checking Vertical and Horizonal Lines\n\t\tfor (int i = 0; i < 9; i++) {\n\t\t\tfor (int j = 0; j < 9; j++) {\n\t\t\t\tint n = (sudoku[i][j] * sudoku[i][j]);\t\t\n\t\t\t\t\n\t\t\t\tsumLines[i] = ((sumLines[i]) + n);\n\t\t\t\tsumColumns[j] = ((sumColumns[j]) + n);\n\t\t\t\tsumBoard[(i/3)][(j/3)] = (sumBoard[(i/3)][(j/3)]) + n;\n\n\t\t\t\tif (i == 8 && sumColumns[j] != 285) break;\n\t\t\t} \n\t\t\n\t\t\tif (sumLines[i] != 285) break;\n\t\t}\n\t \n\t\t//Checking Blocks\n\t\tfor (int k = 0; k < 3; k++) {\n\t\t\tfor (int l = 0; l < 3; l++) {\n\t\t\t\tif (sumBoard[k][l] != 285) return false;\n\t\t\t}\n\t\t}\t\t\t\n\t\treturn true;\n }\n}\n" }, { "alpha_fraction": 0.4501510560512543, "alphanum_fraction": 0.5075528621673584, "avg_line_length": 32.099998474121094, "blob_id": "ca9320d0e8ba0d3d054de57dd5dffba4f2b4a6c0", "content_id": "8b1449957b3891e682c05f5f2deed3f17d3c1627", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 331, "license_type": "no_license", "max_line_length": 78, "num_lines": 10, "path": "/Python 3/6kyu - RomanNumeralToInteger.py", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "def solution(roman):\n romanNumerals = {\"I\":1, \"V\":5, \"X\":10, \"L\":50, \"C\":100, \"D\":500, \"M\":1000}\n sum = 0\n for i in range(len(roman)):\n value = romanNumerals[roman[i]]\n if i+1 < len(roman) and romanNumerals[roman[i+1]] > value:\n sum -= value\n else: \n sum += value\n return sum\n" }, { "alpha_fraction": 0.47783252596855164, "alphanum_fraction": 0.5073891878128052, "avg_line_length": 18.5, "blob_id": "3c5f71c981e5c1ab410384f4ad547abdcc66bd83", "content_id": "0505262ef0ae3be0ccf0a3d7dc341082f77fde42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 203, "license_type": "no_license", "max_line_length": 49, "num_lines": 10, "path": "/JS/7kyu - MiddleCharacter.js", "repo_name": "MichaelHolley/Codewars.com_mySolutions", "src_encoding": "UTF-8", "text": "function getMiddle(s)\r\n{\r\n let result = \"\";\r\n if(s.length % 2 == 0) {\r\n result = s[s.length/2 - 1] + s[s.length/2];\r\n } else {\r\n result = s[Math.floor(s.length/2)];\r\n }\r\n return result;\r\n}" } ]
47
leon-weingartner/PublicFiles
https://github.com/leon-weingartner/PublicFiles
b2cac5f74daa13fbbe591706d230780151582f36
804d9c2e7baf23660b566674291a167115f21eee
a72a692a02c3a7651d5ae5da6bb00b4e0c6b1520
refs/heads/main
2023-05-09T23:55:24.324594
2021-06-10T00:40:19
2021-06-10T00:40:19
374,775,142
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5630713105201721, "alphanum_fraction": 0.5822669267654419, "avg_line_length": 43.759090423583984, "blob_id": "7f3c715199714ffc6d64ed53232b741977a49980", "content_id": "dd70798bddcb81b07f97fc86a10c48408cce1e90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9910, "license_type": "no_license", "max_line_length": 141, "num_lines": 220, "path": "/Pair-Trading/ExperimentalScripts/robin.py", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "import click, json, math\nimport robin_stocks as rh\n\[email protected]()\ndef main():\n print(\"main\")\n content = open('config.json').read()\n config = json.loads(content)\n rh.login(config['username'], config['password'])\n\[email protected](help='gets a stock quote for one or more symbols')\[email protected]('symbols', nargs =- 1)\ndef quote(symbols):\n \n\n quotes = rh.get_quotes(symbols)\n \n for quote in quotes:\n print(\"{} | {}\".format(quote['symbol'], quote['ask_price']))\n #print(symbols)\n #for symbol in symbols:\n #print(\"Getting a stock quote for symbol {}\".format(symbol))\n\[email protected](help='Gets quotes for all stocks in your watchlist')\ndef watchlist():\n print(\"Getting quotes for watchist\")\n with open('watchlist') as w:\n \n\n symbols = w.read().splitlines()\n quotes = rh.get_quotes(symbols)\n\n for quote in quotes:\n print(\"{} | {}\".format(quote['symbol'], quote['ask_price']))\n\n\[email protected](help='buy stock with given ticker')\[email protected]('ticker', type=click.STRING)\[email protected]('quantity', type=click.FLOAT)\[email protected]('--limit', type=click.FLOAT)\ndef buy(ticker, quantity, limit):\n\n if limit is not None:\n click.echo(click.style(\"Buying {} share/s of {} at {}\".format(quantity,ticker,limit), fg=\"green\", bold=True))\n result = rh.order_buy_limit(ticker,quantity,limit)\n\n else:\n click.echo(click.style(\"Buying {} share/s of {}\".format(quantity,ticker), fg=\"green\", bold=True))\n result = rh.orders.order_buy_fractional_by_quantity(ticker, quantity)\n\n click.echo(click.style(str(result), fg = \"green\", bold = True))\n \[email protected](help='sell stock with given ticker')\[email protected]('ticker', type=click.STRING)\[email protected]('quantity', type=click.FLOAT)\[email protected]('--limit', type=click.FLOAT)\ndef sell(ticker, quantity, limit):\n\n if limit is not None:\n click.echo(click.style(\"Buying {} share/s of {} at {}\".format(quantity,ticker,limit), fg=\"green\", bold=True))\n result = rh.order_sell_limit(ticker,quantity,limit)\n\n else:\n click.echo(click.style(\"Buying {} share/s of {}\".format(quantity,ticker), fg=\"green\", bold=True))\n result = rh.orders.order_sell_fractional_by_quantity(ticker, quantity)\n\n if 'ref_id' in result:\n click.echo(click.style(str(result), fg = \"green\", bold = True))\n else:\n click.echo(click.style(str(result), fg = \"red\", bold = True))\n\n\[email protected](help='get stock history')\[email protected]('--ticker', prompt='ticker: ')\[email protected]('--interval', prompt='interval: ') # ‘5minute’, ‘10minute’, ‘hour’, ‘day’, ‘week’. Default is ‘hour’.\[email protected]('--span', prompt='span: ') # ‘day’, ‘week’, ‘month’, ‘3month’, ‘year’, or ‘5year’. Default is ‘week’.\[email protected]('--bounds', prompt='bounds: ') #‘extended’, ‘trading’, or ‘regular’\ndef history(ticker, interval, span, bounds):\n historyDict = rh.stocks.get_stock_historicals(ticker, interval = interval, span = span, bounds = bounds, info = None)\n\n\n\[email protected](help='get similarity correlation')\[email protected]('--tick1', prompt = '1st ticker: ')\[email protected]('--tick2', prompt = '2nd ticker: ')\[email protected]('--indicator', prompt = 'indicator: ') # 'open_price', 'close_price', 'high_price', 'low_price', 'volume', 'pc'\ndef similarity(tick1, tick2, indicator):\n historyDict1 = rh.stocks.get_stock_historicals(tick1, interval = 'week', span = 'year', bounds = 'regular', info = None)\n historyDict2 = rh.stocks.get_stock_historicals(tick2, interval = 'week', span = 'year', bounds = 'regular', info = None)\n list1 = []\n list2 = []\n aDotb = 0\n normA = 0\n normB = 0\n buySellBack = False\n afterBuy = False\n highMargin = 2\n lowMargin = .5\n s1Amount = 1\n s2Amount = 1\n bsFrac = 1\n\n for i, hist in enumerate(historyDict1, start=0):\n if(indicator == 'pc'):\n list1.append((float(hist['close_price']) - float(hist['open_price']))/float(hist['open_price']))\n list2.append((float(historyDict2[i]['close_price']) - float(historyDict2[i]['open_price']))/float(historyDict2[i]['open_price']))\n else:\n list1.append(float(hist[indicator]))\n list2.append(float(historyDict2[i][indicator]))\n\n #print(\"{} | {}\".format(100*(list1[i]-list2[i]), hist['begins_at']))\n \n \n\n if(hist['begins_at'] == '2020-04-27T00:00:00Z'):\n #initial buy\n afterBuy = True\n s1 = s1Amount*float(hist['open_price'])\n s2 = s2Amount*float(historyDict2[i]['open_price'])\n initialBuy = s1+s2\n invested = s1+s2\n buyPow = 0\n \n print(\"initial buy at: {}\".format(initialBuy))\n print(\"Bought {} shares of {} at the price of: {}\".format(s1Amount, tick1, hist['open_price']))\n print(\"Bought {} shares of {} at the price of: {}\".format(s2Amount, tick2, historyDict2[i]['open_price']))\n print(\"________________\")\n \n if(100*(list1[i]-list2[i]) > highMargin and buySellBack == False and afterBuy == True):\n #sell from list1 buy from list2 \n list1Sold = True\n buySellBack = True\n s1 = s1Amount*float(hist['open_price'])-bsFrac*s1Amount*float(hist['open_price'])\n s2 = s2Amount*float(historyDict2[i]['open_price'])+bsFrac*s2Amount*float(historyDict2[i]['open_price'])\n invested = s1+s2\n buyPow += bsFrac*s1Amount*float(hist['open_price']) - bsFrac*s2Amount*float(historyDict2[i]['open_price']) \n # print(hist['begins_at'])\n # print(100*(list1[i]-list2[i]))\n # print(\"BUY & SELL\")\n # print(\"Sold {} at the price of: {}\".format(tick1, hist['open_price']))\n # print(\"Bought {} at the price of: {}\".format(tick2, historyDict2[i]['open_price']))\n # print(\"Invested: {}\".format(invested))\n # print(\"Buying Power: {}\".format(buyPow))\n # print(\"Total: {}\".format(invested+buyPow))\n # print(\"Profit: {}\".format(invested+buyPow-initialBuy))\n # print(\"________________\")\n elif(100*(list1[i]-list2[i]) < -highMargin and buySellBack == False and afterBuy == True):\n #buy from list1 sell from list2\n list1Sold = False\n buySellBack = True\n s1 = s1Amount*float(hist['open_price'])+bsFrac*s1Amount*float(hist['open_price'])\n s2 = s2Amount*float(historyDict2[i]['open_price'])-bsFrac*s2Amount*float(historyDict2[i]['open_price'])\n invested = s1+s2\n buyPow += -bsFrac*s1Amount*float(hist['open_price']) + bsFrac*s2Amount*float(historyDict2[i]['open_price'])\n # print(hist['begins_at'])\n # print(100*(list1[i]-list2[i]))\n # print(\"BUY & SELL\")\n # print(\"Bought {} at the price of: {}\".format(tick1, hist['open_price']))\n # print(\"Sold {} at the price of: {}\".format(tick2, historyDict2[i]['open_price']))\n # print(\"Invested: {}\".format(invested))\n # print(\"Buying Power: {}\".format(buyPow))\n # print(\"Total: {}\".format(invested+buyPow))\n # print(\"Profit: {}\".format(invested+buyPow-initialBuy))\n # print(\"________________\")\n elif(abs(100*(list1[i]-list2[i])) < lowMargin and buySellBack == True and list1Sold == True and afterBuy == True):\n #buy and sell back \n buySellBack = False\n s1 = s1Amount*float(hist['open_price'])\n s2 = s2Amount*float(historyDict2[i]['open_price'])\n invested = s1+s2\n buyPow += -bsFrac*s1Amount*float(hist['open_price']) + bsFrac*s2Amount*float(historyDict2[i]['open_price'])\n # print(hist['begins_at'])\n # print(100*(list1[i]-list2[i]))\n # print(\"BUY & SELL BACK\")\n # print(\"Bought {} at the price of: {}\".format(tick1, hist['open_price']))\n # print(\"Sold {} at the price of: {}\".format(tick2, historyDict2[i]['open_price']))\n # print(\"Invested: {}\".format(invested))\n # print(\"Buying Power: {}\".format(buyPow))\n # print(\"Total: {}\".format(invested+buyPow))\n # print(\"Profit: {}\".format(invested+buyPow-initialBuy))\n # print(\"________________\")\n elif(abs(100*(list1[i]-list2[i])) < lowMargin and buySellBack == True and list1Sold == False and afterBuy == True):\n #buy and sell back \n buySellBack = False\n s1 = s1Amount*float(hist['open_price'])\n s2 = s2Amount*float(historyDict2[i]['open_price'])\n invested = s1+s2\n buyPow += bsFrac*s1Amount*float(hist['open_price']) - bsFrac*s2Amount*float(historyDict2[i]['open_price']) \n # print(hist['begins_at'])\n # print(100*(list1[i]-list2[i]))\n # print(\"BUY & SELL BACK\")\n # print(\"Sold {} at the price of: {}\".format(tick1, hist['open_price']))\n # print(\"Bought {} at the price of: {}\".format(tick2, historyDict2[i]['open_price']))\n # print(\"Invested: {}\".format(invested))\n # print(\"Buying Power: {}\".format(buyPow))\n # print(\"Total: {}\".format(invested+buyPow))\n # print(\"Profit: {}\".format(invested+buyPow-initialBuy))\n # print(\"________________\")\n\n print(\"total profit: {}\".format(invested+buyPow-initialBuy))\n print(\"annual growth: +%{}\".format(100*(invested+buyPow-initialBuy)/initialBuy))\n \n\n\n for i, ind in enumerate(list1, start=0):\n aDotb += list1[i]*list2[i]\n normA += list1[i] ** 2\n normB += list2[i] ** 2\n\n print(\"A dot B: {}, norm A: {}, norm B: {}\".format(aDotb, normA, normB))\n\n print(\"the similarity correlation is: {}\".format(aDotb/(math.sqrt(normA * normB))))\n\n\n\n\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.5278028249740601, "alphanum_fraction": 0.5576819181442261, "avg_line_length": 48.68161392211914, "blob_id": "35d3bcc02f1d5b178ba482545573f34d028b7f4d", "content_id": "3592434437e212a945c07ad21b0dc4fe2870edd8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11078, "license_type": "no_license", "max_line_length": 237, "num_lines": 223, "path": "/Pair-Trading/ExperimentalScripts/robin2.py", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "import click, json, time, math\nimport robin_stocks as rh\nimport numpy\nfrom scipy.stats.stats import pearsonr \nfrom scipy.stats import spearmanr\n\ndef main():\n content = open('config.json').read()\n config = json.loads(content)\n rh.login(config['username'], config['password'])\n\n with open('Stocks') as w:\n\n symbols = w.read().splitlines()\n \n for i in range(0,len(symbols)-2):\n for j in range(i+1,len(symbols)-1):\n simCo = similarity(symbols[i], symbols[j])\n backtest(symbols[i],symbols[j], simCo)\n \n \n \n\n\n\n\ndef backtest(tick1, tick2, sim):\n historyDict1 = rh.stocks.get_stock_historicals(tick1, interval = 'day', span = 'year', bounds = 'regular', info = None)\n historyDict2 = rh.stocks.get_stock_historicals(tick2, interval = 'day', span = 'year', bounds = 'regular', info = None)\n list1 = []\n list2 = []\n \n buySellBack = False\n afterBuy = False\n startLists = False\n highMargin = .25-(sim/1.8)**(2.4)\n if(.23-(sim/1.8)**(2.4) > 0):\n lowMargin = .23-(sim/1.8)**(2.4)\n else:\n lowMargin = .005\n\n # print(highMargin,lowMargin)\n \n bsFrac = 1\n lastI = 0\n count = 0\n \n \n\n for i, hist in enumerate(historyDict1, start=0):\n\n \n \n #print(\"{} | {}\".format(100*(list1[i]-list2[i]), hist['begins_at']))\n \n \n\n if(hist['begins_at'] == '2020-01-27T00:00:00Z'): #'2020-01-27T00:00:00Z'\n #initial buy\n afterBuy = True\n s1Amount = 1 \n s2Amount = float(hist['close_price'])/float(historyDict2[i]['close_price'])\n \n s1 = s1Amount*float(hist['close_price'])\n s2 = s2Amount*float(historyDict2[i]['close_price'])\n initialBuy = s1+s2\n invested = s1+s2\n buyPow = 0\n \n # print(\"initial buy at: {}\".format(initialBuy))\n # print(\"Bought {} shares of {} at the price of: {}\".format(s1Amount, tick1, hist['close_price']))\n # print(\"Bought {} shares of {} at the price of: {}\".format(s2Amount, tick2, historyDict2[i]['close_price']))\n # print(\"________________\")\n lastI = i\n startLists = True\n j = 0\n initIndex = i\n \n\n if(startLists == True):\n list1.append((float(hist['close_price'])-float(historyDict1[initIndex]['close_price']))/float(historyDict1[initIndex]['close_price']))\n list2.append((float(historyDict2[i]['close_price'])-float(historyDict2[initIndex]['close_price']))/float(historyDict2[initIndex]['close_price']))\n \n if(list1[j]-list2[j] > highMargin and buySellBack == False and afterBuy == True):\n #sell from list1 buy from list2 \n list1Sold = True\n buySellBack = True\n s1 = s1Amount*float(hist['close_price'])-bsFrac*s1Amount*float(hist['close_price'])\n s2 = s2Amount*float(historyDict2[i]['close_price'])+bsFrac*s2Amount*float(historyDict2[i]['close_price'])\n invested = s1+s2\n buyPow += bsFrac*s1Amount*float(hist['close_price']) - bsFrac*s2Amount*float(historyDict2[i]['close_price']) \n # print(hist['begins_at'])\n # print(100*(list1[j]-list2[j]))\n # print(\"BUY & SELL\")\n # print(\"Sold {} at the price of: {}\".format(tick1, hist['close_price']))\n # print(\"Bought {} at the price of: {}\".format(tick2, historyDict2[i]['close_price']))\n # print(\"Invested: {}\".format(invested))\n # print(\"Buying Power: {}\".format(buyPow))\n # print(\"Total: {}\".format(invested+buyPow))\n # print(\"Profit: {}\".format(invested+buyPow-initialBuy))\n # print(s1Amount*float(historyDict1[i]['close_price']) + s2Amount*float(historyDict2[i]['close_price']) - initialBuy)\n # print(100*list1[j], 100*list2[j])\n # print()\n # print(\"________________\")\n \n count += 1\n elif(list1[j]-list2[j] < -highMargin and buySellBack == False and afterBuy == True):\n #buy from list1 sell from list2\n list1Sold = False\n buySellBack = True\n s1 = s1Amount*float(hist['close_price'])+bsFrac*s1Amount*float(hist['close_price'])\n s2 = s2Amount*float(historyDict2[i]['close_price'])-bsFrac*s2Amount*float(historyDict2[i]['close_price'])\n invested = s1+s2\n buyPow += -bsFrac*s1Amount*float(hist['close_price']) + bsFrac*s2Amount*float(historyDict2[i]['close_price'])\n # print(hist['begins_at'])\n # print(100*(list1[j]-list2[j]))\n # print(\"BUY & SELL\")\n # print(\"Bought {} at the price of: {}\".format(tick1, hist['close_price']))\n # print(\"Sold {} at the price of: {}\".format(tick2, historyDict2[i]['close_price']))\n # print(\"Invested: {}\".format(invested))\n # print(\"Buying Power: {}\".format(buyPow))\n # print(\"Total: {}\".format(invested+buyPow))\n # print(\"Profit: {}\".format(invested+buyPow-initialBuy))\n # print(s1Amount*float(historyDict1[i]['close_price']) + s2Amount*float(historyDict2[i]['close_price']) - initialBuy)\n # print(100*list1[j], 100*list2[j])\n # print(\"________________\")\n \n count += 1\n elif(abs(list1[j]-list2[j]) < lowMargin and buySellBack == True and list1Sold == True and afterBuy == True):\n #buy and sell back \n buySellBack = False\n s1 = s1Amount*float(hist['close_price'])\n s2 = s2Amount*float(historyDict2[i]['close_price'])\n invested = s1+s2\n buyPow += -bsFrac*s1Amount*float(hist['close_price']) + bsFrac*s2Amount*float(historyDict2[i]['close_price'])\n # print(hist['begins_at'])\n # print(100*(list1[j]-list2[j]))\n # print(\"BUY & SELL BACK\")\n # print(\"Bought {} at the price of: {}\".format(tick1, hist['close_price']))\n # print(\"Sold {} at the price of: {}\".format(tick2, historyDict2[i]['close_price']))\n # print(\"Invested: {}\".format(invested))\n # print(\"Buying Power: {}\".format(buyPow))\n # print(\"Total: {}\".format(invested+buyPow))\n # print(\"Profit: {}\".format(invested+buyPow-initialBuy))\n # print(s1Amount*float(historyDict1[i]['close_price']) + s2Amount*float(historyDict2[i]['close_price']) - initialBuy)\n # print(100*list1[j], 100*list2[j])\n # print(\"________________\")\n \n count += 1\n elif(abs(list1[j]-list2[j]) < lowMargin and buySellBack == True and list1Sold == False and afterBuy == True):\n #buy and sell back \n buySellBack = False\n s1 = s1Amount*float(hist['close_price'])\n s2 = s2Amount*float(historyDict2[i]['close_price'])\n invested = s1+s2\n buyPow += bsFrac*s1Amount*float(hist['close_price']) - bsFrac*s2Amount*float(historyDict2[i]['close_price']) \n # print(hist['begins_at'])\n # print(100*(list1[j]-list2[j]))\n # print(\"BUY & SELL BACK\")\n # print(\"Sold {} at the price of: {}\".format(tick1, hist['close_price']))\n # print(\"Bought {} at the price of: {}\".format(tick2, historyDict2[i]['close_price']))\n # print(\"Invested: {}\".format(invested))\n # print(\"Buying Power: {}\".format(buyPow))\n # print(\"Total: {}\".format(invested+buyPow))\n # print(\"Profit: {}\".format(invested+buyPow-initialBuy))\n # print(s1Amount*float(historyDict1[i]['close_price']) + s2Amount*float(historyDict2[i]['close_price']) - initialBuy)\n # print(100*list1[j], 100*list2[j])\n # print(\"________________\")\n \n count += 1\n j+=1\n # print(s1Amount*float(historyDict1[i]['close_price']))\n # print(s2Amount*float(historyDict2[i]['close_price']))\n # print(s1Amount*float(historyDict1[i]['close_price'])+s2Amount*float(historyDict2[i]['close_price']))\n # print()\n lastI = i\n\n #sell invested\n if buySellBack == False:\n buyPow += s1Amount*float(historyDict1[lastI]['close_price']) + s2Amount*float(historyDict2[lastI]['close_price']) \n elif buySellBack == True and list1Sold == True:\n buyPow += s1Amount*float(historyDict1[lastI]['close_price'])-bsFrac*s1Amount*float(historyDict1[lastI]['close_price']) + s2Amount*float(historyDict2[lastI]['close_price'])+bsFrac*s2Amount*float(historyDict2[lastI]['close_price'])\n elif buySellBack == True and list1Sold == False:\n buyPow += s1Amount*float(historyDict1[lastI]['close_price'])+bsFrac*s1Amount*float(historyDict1[lastI]['close_price']) + s2Amount*float(historyDict2[lastI]['close_price'])-bsFrac*s2Amount*float(historyDict2[lastI]['close_price'])\n\n invested = 0\n\n # print(\"total profit w/algorithm: {}\".format(invested+buyPow-initialBuy))\n # print(\"annual growth w/algorithm: +%{}\".format(100*(invested+buyPow-initialBuy)/initialBuy))\n # print(\"------------------\")\n # print(\"total profit w/o algorithm: {}\".format(s1Amount*float(historyDict1[lastI]['close_price']) + s2Amount*float(historyDict2[lastI]['close_price']) - initialBuy))\n # print(\"annual growth w/o algorithm: +%{}\".format(100*s1Amount*(float(historyDict1[lastI]['close_price']) + s2Amount*float(historyDict2[lastI]['close_price'])-initialBuy)/initialBuy))\n # print(count)\n # print(highMargin)\n # print(lowMargin)\n # print(similarity(tick1,tick2))\n growthw = 100*(invested+buyPow-initialBuy)/initialBuy\n growthwo = 100*(s1Amount*float(historyDict1[lastI]['close_price']) + s2Amount*float(historyDict2[lastI]['close_price'])-initialBuy)/initialBuy\n\n print(\"{} {}, {}, {}, {}, {}, {}, {}, {}\".format(tick1,tick2, count, growthw, growthwo, growthw-growthwo, invested+buyPow-initialBuy, initialBuy, sim))\n \n\n\n\n \n\ndef similarity(tick1, tick2):\n historyDict1 = rh.stocks.get_stock_historicals(tick1, interval = 'day', span = 'year', bounds = 'regular', info = None)\n historyDict2 = rh.stocks.get_stock_historicals(tick2, interval = 'day', span = 'year', bounds = 'regular', info = None)\n initPrice1 = float(historyDict1[0]['close_price'])\n initPrice2 = float(historyDict2[0]['close_price'])\n list1 = []\n list2 = []\n \n for i, hist in enumerate(historyDict1, start=0):\n list1.append((float(hist['close_price'])-initPrice1)/initPrice1)\n list2.append((float(historyDict2[i]['close_price'])-initPrice2)/initPrice2)\n\n return(spearmanr(list1,list2)[0])\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.598870038986206, "alphanum_fraction": 0.598870038986206, "avg_line_length": 13.833333015441895, "blob_id": "c2142feecb02b875e73ee5fa0c08814aac3685c7", "content_id": "8a7b219b8638f807eb21e4ebfdc6b9af99fc8876", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 179, "license_type": "no_license", "max_line_length": 56, "num_lines": 12, "path": "/Lost-Island/Computer Game Uncompiled Code/AudioTest.js", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "#pragma strict\n\n\npublic var sound : AudioClip;\nfunction Update () {\n if(Input.GetKeyDown(\"e\"))\n {\n\n \n GetComponent.<AudioSource>().PlayOneShot(sound);\n }\n}" }, { "alpha_fraction": 0.539691150188446, "alphanum_fraction": 0.5421295166015625, "avg_line_length": 34.83495330810547, "blob_id": "767aa3075372b4739048753263127ad7f4c0a8ce", "content_id": "45681bd130176adfb7081a483f4506dccb9b453c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 3692, "license_type": "no_license", "max_line_length": 425, "num_lines": 103, "path": "/Deliver-Lake-Powell-Startup/DelivererTab/MoveToCompletedViewController.swift", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "//\n// MoveToCompletedViewController.swift\n// DeliverPage\n//\n// Created by Leon Weingartner on 6/22/20.\n// Copyright © 2020 Leon Weingartner. All rights reserved.\n//\n\nimport UIKit\nimport Firebase\nimport FirebaseFirestore\n\nclass MoveToCompletedViewController: UIViewController {\n \n @IBOutlet weak var orderIDLabel: UILabel!\n @IBOutlet weak var restLabel: UILabel!\n @IBOutlet weak var nameLabel: UILabel!\n @IBOutlet weak var phoneLabel: UILabel!\n @IBOutlet weak var orderDesLabel: UITextView!\n @IBOutlet weak var paymentTypeLabel: UILabel!\n @IBOutlet weak var claimedByLabel: UILabel!\n @IBOutlet weak var dodLabel: UILabel!\n @IBOutlet weak var todLabel: UILabel!\n @IBOutlet weak var locationLabel: UILabel!\n @IBOutlet weak var destinationLabel: UITextView!\n \n\n \n \n @IBAction func btnComplete(_ sender: Any) {\n //add document to claimedorders\n Firestore.firestore().collection(\"CompletedOrders\").document(globSelectOrderID.name).setData([\"name\": nameLabel.text, \"orderdes\": orderDesLabel.text, \"paymentmeth\": paymentTypeLabel.text, \"phonenum\": phoneLabel.text, \"restaurant\": restLabel.text, \"claimedby\": claimedByLabel.text, \"dateofdelivery\": dodLabel.text, \"timeofdelivery\": todLabel.text, \"location\": locationLabel.text, \"destination\": destinationLabel.text])\n \n \n //delete document from unclaimedorders\n Firestore.firestore().collection(\"ClaimedOrders\").document(globSelectOrderID.name).delete() { err in\n if let err = err {\n print(\"Error removing document: \\(err)\")\n } else {\n print(\"Document successfully removed!\")\n }\n }\n \n \n }\n \n \n \n \n \n override func viewDidLoad() {\n super.viewDidLoad()\n\n fetchData()\n // Do any additional setup after loading the view.\n }\n \n\n func fetchData(){\n \n \n \n Firestore.firestore().collection(\"ClaimedOrders\").getDocuments() { (querySnapshot, err) in\n if let err = err {\n print(\"Error getting documents: \\(err)\")\n } else {\n for document in (querySnapshot?.documents)! {\n \n // print(document.documentID)\n \n \n if document.documentID == globSelectOrderID.name {\n \n \n \n self.orderIDLabel.text = globSelectOrderID.name\n self.restLabel.text = (document.data()[\"restaurant\"] as! String)\n self.nameLabel.text = (document.data()[\"name\"] as! String)\n self.phoneLabel.text = (document.data()[\"phonenum\"] as! String)\n self.orderDesLabel.text = (document.data()[\"orderdes\"] as! String)\n self.paymentTypeLabel.text = (document.data()[\"paymentmeth\"] as! String)\n \n self.claimedByLabel.text = (document.data()[\"claimedby\"] as! String)\n self.dodLabel.text = (document.data()[\"dateofdelivery\"] as! String)\n self.todLabel.text = (document.data()[\"timeofdelivery\"] as! String)\n self.locationLabel.text = (document.data()[\"location\"] as! String)\n self.destinationLabel.text = (document.data()[\"destination\"] as! String)\n \n \n \n \n }\n \n }\n \n \n }\n \n }\n \n }\n\n}\n" }, { "alpha_fraction": 0.5410053133964539, "alphanum_fraction": 0.5502645373344421, "avg_line_length": 27.346153259277344, "blob_id": "574c3f6344164f6c4332bce1887650545deaabad", "content_id": "5a053f7388990d2ab443f14b5d7f58e37af76b41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1514, "license_type": "no_license", "max_line_length": 109, "num_lines": 52, "path": "/Lost-Island/Computer Game Uncompiled Code/TentBuild.js", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "#pragma strict\n\nvar tentPrefab : Transform;\nvar player : GameObject;\nvar check7 : GameObject;\nvar BtoB : GameObject;\n\nprivate var canBuild : boolean = true;\nprivate var inventory : Inv;\n\nfunction Start()\n{\n GetComponent.<Renderer>().material.color = Color.green;\r\n GetComponent.<Renderer>().material.color.a = 0.5;\r\n inventory = GameObject.Find(\"FPSController\").GetComponent(Inv);\r\n}\r\n\r\nfunction OnTriggerEnter(Col : Collider)\r\n {\r\n if(Col.gameObject.tag == \"Terrain\" || Col.gameObject.tag == \"Tree\") \r\n\r\n {\r\n GetComponent.<Renderer>().material.color = Color.red;\r\n GetComponent.<Renderer>().material.color.a = 0.5;\r\n canBuild = false;\r\n }\r\n }\r\n\r\n\r\n function OnTriggerExit(Col : Collider)\r\n {\r\n if(Col.gameObject.tag == \"Terrain\" || Col.gameObject.tag == \"Tree\") \r\n\r\n {\r\n GetComponent.<Renderer>().material.color = Color.green;\r\n GetComponent.<Renderer>().material.color.a = 0.5;\r\n canBuild = true;\r\n }\r\n }\r\n\r\n\r\n function Update()\r\n {\r\n if(Input.GetKeyDown(\"b\") && canBuild == true)\r\n {\r\n Instantiate(tentPrefab, player.transform.position + Vector3(10, 0, 10), Quaternion.identity);\r\n player.GetComponent(Crafting).tent.SetActive(false);\r\n check7.SetActive(true);\r\n inventory.i = true;\r\n BtoB.SetActive(false);\r\n }\r\n }" }, { "alpha_fraction": 0.6382588148117065, "alphanum_fraction": 0.6441588997840881, "avg_line_length": 34.64018630981445, "blob_id": "2e6f134f90c83f60f4d05c8e8f8b84789341c8cb", "content_id": "b11c7c0fbda2639351696b2bfeb39a0fc34878f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 7628, "license_type": "no_license", "max_line_length": 176, "num_lines": 214, "path": "/Deliver-Lake-Powell-Startup/UserTab/Order1ViewController.swift", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "//\n// Order1ViewController.swift\n// DeliverPage\n//\n// Created by Leon Weingartner on 6/24/20.\n// Copyright © 2020 Leon Weingartner. All rights reserved.\n//\n\nimport UIKit\n\nclass Order1ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate, UITextViewDelegate {\n func numberOfComponents(in pickerView: UIPickerView) -> Int {\n return 1\n }\n \n func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {\n return pickerDest.count\n }\n func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {\n return pickerDest[row]\n }\n func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {\n destination = pickerDest[row]\n }\n \n\n \n @IBOutlet weak var restLabel: UILabel!\n \n @IBOutlet weak var errorLabel: UILabel!\n @IBOutlet weak var txtName: UITextField!\n @IBOutlet weak var txtPhone: UITextField!\n @IBOutlet weak var pickerView: UIPickerView!\n @IBOutlet weak var txtDestination: UITextView!\n \n var pickerDest:[String] = [String]()\n var destination: String?\n \n let screenSize: CGRect = UIScreen.main.bounds\n \n \n @IBAction func btnNext(_ sender: Any) {\n \n if(txtPhone.text != \"\" && txtName.text != \"\" && txtDestination.text != \"\" && txtDestination.text != \"Info about destination\\nEx. house boat, slip# 12\"){\n globName.name = txtName.text!\n globPhone.name = txtPhone.text!\n globDestination.name = destination ?? \"\"\n globDestDes.name = txtDestination.text!\n performSegue(withIdentifier: \"order2segue\", sender: nil)\n }else{\n errorLabel.text = \"Required Field/s are empty\"\n }\n \n }\n \n @objc func dismissKeyboard() {\n //Causes the view (or one of its embedded text fields) to resign the first responder status.\n view.endEditing(true)\n }\n \n \n private func setupNavigationBarItems() {\n \n let titleImageView = UIImageView(image: #imageLiteral(resourceName: \"Deliver Logo\"))\n titleImageView.frame = CGRect(x: 0, y: 0, width: 34, height: 34)\n titleImageView.contentMode = .scaleAspectFit\n let widthConstraint = titleImageView.widthAnchor.constraint(equalToConstant: 120)\n let heightConstraint = titleImageView.heightAnchor.constraint(equalToConstant: 48)\n heightConstraint.isActive = true\n widthConstraint.isActive = true\n navigationItem.titleView = titleImageView\n \n \n }\n \n override func viewDidLoad() {\n super.viewDidLoad()\n errorLabel.text = \"\"\n \n setupNavigationBarItems()\n \n let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))\n \n view.addGestureRecognizer(tap)\n \n self.pickerView.delegate = self\n self.pickerView.dataSource = self\n \n \n \n pickerDest = [\"Whaweap\", \"Antelope\"]\n \n txtDestination.text = \"Info about destination\\nEx. house boat, slip# 12\"\n txtDestination.textColor = UIColor.lightGray\n txtDestination.layer.cornerRadius = 5\n txtDestination.layer.borderColor = UIColor.orange.cgColor\n txtDestination.layer.borderWidth = 1\n self.txtDestination.delegate = self\n \n textViewDidBeginEditing(txtDestination)\n textViewDidEndEditing(txtDestination)\n \n txtPhone.layer.cornerRadius = 5\n txtPhone.layer.borderColor = UIColor.orange.cgColor\n txtPhone.layer.borderWidth = 1\n \n txtName.layer.cornerRadius = 5\n txtName.layer.borderColor = UIColor.orange.cgColor\n txtName.layer.borderWidth = 1\n \n pickerView.layer.cornerRadius = 5\n pickerView.layer.borderColor = UIColor.orange.cgColor\n pickerView.layer.borderWidth = 1\n \n pickerView.selectRow(0, inComponent: 0, animated: true)\n destination = pickerDest[0]\n \n txtName.delegate = self\n \n let toolBar = UIToolbar()\n toolBar.sizeToFit()\n \n let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)\n \n let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: self, action: #selector(self.doneClicked))\n \n toolBar.setItems([flexibleSpace, doneButton], animated: false)\n \n txtPhone.inputAccessoryView = toolBar\n txtDestination.inputAccessoryView = toolBar\n txtName.inputAccessoryView = toolBar\n //listen for keyboard events\n NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)\n NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)\n NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)\n \n }\n \n @objc func doneClicked() {\n view.endEditing(true)\n }\n \n deinit {\n NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)\n NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)\n NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillChangeFrameNotification, object: nil)\n }\n override func viewWillAppear(_ animated: Bool) {\n \n restLabel.text = globRest.name\n \n }\n override func viewWillDisappear(_ animated: Bool) {\n errorLabel.text = \"\"\n }\n \n \n \n \n //keyboard methods\n \n //UITextFieldDelegate methods\n func textFieldShouldReturn(_ textField: UITextField) -> Bool {\n if txtName.isEditing {\n txtName.resignFirstResponder()\n }else if txtPhone.isEditing{\n txtPhone.resignFirstResponder()\n }\n return true\n }\n \n \n @objc func keyboardWillChange(notification: Notification) {\n print(\"keyboard will show: \\(notification.name.rawValue)\")\n \n guard let keyboardRect = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else{\n return\n }\n \n if notification.name == UIResponder.keyboardWillShowNotification || notification.name == UIResponder.keyboardWillChangeFrameNotification{\n \n if txtName.isEditing {\n \n }else if txtPhone.isEditing{\n \n }else{\n view.frame.origin.y = -keyboardRect.height + (screenSize.height - (txtDestination.frame.origin.y + 200))\n }\n \n }else{\n view.frame.origin.y = 0\n }\n \n \n }\n \n func textViewDidBeginEditing(_ textView: UITextView) {\n if textView.textColor == UIColor.lightGray {\n textView.text = \"\"\n textView.textColor = UIColor.black\n }\n }\n func textViewDidEndEditing(_ textView: UITextView) {\n if textView.text.isEmpty {\n textView.text = \"Info about destination\\nEx. house boat, slip# 12\"\n textView.textColor = UIColor.lightGray\n }\n }\n \n \n \n\n \n}\n" }, { "alpha_fraction": 0.5278566479682922, "alphanum_fraction": 0.5353943705558777, "avg_line_length": 29.513334274291992, "blob_id": "ab576683d173479a3b3a656cc5527263cdb149da", "content_id": "3f52ecf14dd9a027d66412d19f4ff12de769ed1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 9155, "license_type": "no_license", "max_line_length": 163, "num_lines": 300, "path": "/Deliver-Lake-Powell-Startup/UserTab/Order3ViewController.swift", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "//\n// Order3ViewController.swift\n// DeliverPage\n//\n// Created by Leon Weingartner on 6/24/20.\n// Copyright © 2020 Leon Weingartner. All rights reserved.\n//\n\nimport UIKit\nimport Firebase\nimport FirebaseFirestore\n\nclass Order3ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource{\n \n \n @IBOutlet weak var loadSlotIndicator: UIActivityIndicatorView!\n \n @IBOutlet weak var restLabel: UILabel!\n @IBOutlet weak var paymentPicker: UIPickerView!\n @IBOutlet weak var txtDate: UITextField!\n @IBOutlet weak var timePicker: UIPickerView!\n \n @IBOutlet weak var errorLabel: UILabel!\n \n @IBAction func btnNext(_ sender: Any) {\n if(txtDate.text != \"\" && selectedTime != \"\"){\n globPayment.name = selectedPayment!\n globDateOfDelivery.name = selectedDate!\n globTimeOfDelivery.name = selectedTime!\n errorLabel.text = \"\"\n performSegue(withIdentifier: \"summarysegue\", sender: nil)\n }else{\n errorLabel.text = \"Required Field/s are empty\"\n }\n \n }\n \n let datePicker = UIDatePicker()\n \n \n var pickerData:[String] = [String]()\n var pickerTime:[String] = [String]()\n \n let group = DispatchGroup()\n \n override func viewWillAppear(_ animated: Bool) {\n errorLabel.text = \"\"\n }\n \n private func setupNavigationBarItems() {\n \n let titleImageView = UIImageView(image: #imageLiteral(resourceName: \"Deliver Logo\"))\n titleImageView.frame = CGRect(x: 0, y: 0, width: 34, height: 34)\n titleImageView.contentMode = .scaleAspectFit\n let widthConstraint = titleImageView.widthAnchor.constraint(equalToConstant: 120)\n let heightConstraint = titleImageView.heightAnchor.constraint(equalToConstant: 48)\n heightConstraint.isActive = true\n widthConstraint.isActive = true\n navigationItem.titleView = titleImageView\n \n \n }\n \n \n override func viewDidLoad() {\n \n super.viewDidLoad()\n \n setupNavigationBarItems()\n \n restLabel.text = globRest.name\n \n createDatePicker()\n \n loadSlotIndicator.stopAnimating()\n self.timePicker.delegate = self\n self.timePicker.dataSource = self\n self.paymentPicker.delegate = self\n self.paymentPicker.dataSource = self\n \n paymentPicker.tag = 0\n timePicker.tag = 1\n \n timePicker.layer.cornerRadius = 5\n timePicker.layer.borderColor = UIColor.orange.cgColor\n timePicker.layer.borderWidth = 1\n \n paymentPicker.layer.cornerRadius = 5\n paymentPicker.layer.borderColor = UIColor.orange.cgColor\n paymentPicker.layer.borderWidth = 1\n \n txtDate.layer.cornerRadius = 5\n txtDate.layer.borderColor = UIColor.orange.cgColor\n txtDate.layer.borderWidth = 1\n \n \n pickerData = [\"Cash\", \"Credit\", \"Venmo\"]\n \n paymentPicker.selectRow(1, inComponent: 0, animated: true)\n selectedPayment = pickerData[0]\n \n timePicker.selectRow(0, inComponent: 0, animated: true)\n selectedTime = \"\"\n selectedDate = \"\"\n errorLabel.text = \"\"\n \n \n \n }\n \n \n //payment picker\n var selectedPayment: String?\n var selectedTime: String?\n public func numberOfComponents(in pickerView: UIPickerView) -> Int {\n return 1\n }\n \n public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {\n \n if pickerView.tag == 0{\n return pickerData.count\n } else if pickerView.tag == 1{\n return pickerTime.count\n }\n return 0\n }\n public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {\n \n if pickerView.tag == 0{\n return pickerData[row]\n } else if pickerView.tag == 1{\n return pickerTime[row]\n }\n return \"\"\n \n \n \n }\n public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {\n print(pickerView.tag)\n \n if pickerView.tag == 0{\n selectedPayment = pickerData[row]\n } else if pickerView.tag == 1{\n if pickerTime.count > 0{\n selectedTime = pickerTime[row]\n \n getOrderID()\n \n \n \n }\n }\n }\n \n func getOrderID() {\n let rndNumber : Int = Int.random(in: 1...300)\n \n let n = selectedTime?.replacingOccurrences(of: \"pm\", with: \"\") ?? \"1\"\n let hour = Int(n)\n \n let date = datePicker.calendar.date(byAdding: .hour, value: hour ?? 1, to: datePicker.date)\n \n let interval = date?.timeIntervalSince1970\n \n globOrderID.name = String(Int(interval!) + rndNumber)\n \n }\n \n \n \n func createDatePicker() {\n //toolbar\n let toolbar = UIToolbar()\n toolbar.sizeToFit()\n //bar button\n let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePressed))\n toolbar.setItems([doneBtn], animated: true)\n //assign toolbar\n txtDate.inputAccessoryView = toolbar\n //assign dat picker to the text field\n txtDate.inputView = datePicker\n //date picker mode\n datePicker.datePickerMode = .date\n //set min and max date\n datePicker.minimumDate = Calendar.current.date(byAdding: .day, value: 0, to: Date())\n datePicker.maximumDate = Calendar.current.date(byAdding: .day, value: 14, to: Date())\n }\n var selectedDate: String?\n\n @objc func donePressed(){\n \n pickerTime.removeAll()\n \n //formatter\n let formatter = DateFormatter()\n formatter.dateStyle = .medium\n formatter.timeStyle = .none\n \n txtDate.text = formatter.string(from: datePicker.date)\n selectedDate = txtDate.text\n fetchData(date: txtDate.text ?? \"\")\n self.view.endEditing(true)\n loadSlotIndicator.startAnimating()\n \n group.notify(queue: .main){\n \n //sort array\n self.pickerTime = self.pickerTime.sorted {$0.localizedStandardCompare($1) == .orderedAscending}\n print(self.pickerTime)\n \n let currentHour = Calendar.current.component(.hour, from: Date())\n \n for s in self.pickerTime {\n let sCut = s.replacingOccurrences(of: \"pm\", with: \"\")\n let sInt = Int(sCut)\n if sInt! + 12 < currentHour + 2 && Calendar.current.component(.day, from: Date()) == Calendar.current.component(.day, from: self.datePicker.date) {\n self.pickerTime.removeAll(where: {$0 == s})\n }\n \n \n }\n \n \n let date = Date()\n let calendar = Calendar.current\n let hour = calendar.component(.hour, from: date)\n //let minutes = calendar.component(.minute, from: date)\n print(Int(hour))\n \n \n \n \n self.loadSlotIndicator.stopAnimating()\n self.timePicker.reloadAllComponents()\n self.timePicker.selectRow(0, inComponent: 0, animated: true)\n if self.pickerTime.count > 0{\n self.selectedTime = self.pickerTime[0]\n self.errorLabel.text = \"\"\n self.getOrderID()\n }else{\n self.selectedTime = \"\"\n self.errorLabel.text = \"There are no available time slots available for this date\"\n }\n \n }\n \n //Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(callback), userInfo: nil, repeats: false)\n \n \n //find slots with given date\n \n \n \n }\n \n \n\n \n \n func fetchData(date: String){\n group.enter()\n Firestore.firestore().collection(\"TimeSlots\").getDocuments() { (querySnapshot, err) in\n if let err = err {\n print(\"Error getting documents: \\(err)\")\n } else {\n for document in (querySnapshot?.documents)! {\n \n if document.documentID == date {\n \n let dict = document.data()\n \n \n for(key,value) in dict{\n print(\"value\")\n if(value as! Int > 0){\n self.pickerTime.append(key)\n \n }\n }\n \n }\n }\n self.group.leave()\n \n }\n }\n }\n \n \n \n \n \n \n \n \n \n \n}\n" }, { "alpha_fraction": 0.5684351325035095, "alphanum_fraction": 0.5704413652420044, "avg_line_length": 34.88800048828125, "blob_id": "92f57a34cd2bd7db8e29ac83aca36681c1ec7ba7", "content_id": "0782820d9cf2cba96a5c5572fd815f9664ec7872", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 4487, "license_type": "no_license", "max_line_length": 420, "num_lines": 125, "path": "/Deliver-Lake-Powell-Startup/DelivererTab/MoveToClaimedViewController.swift", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "//\n// MoveToClaimedViewController.swift\n// DeliverPage\n//\n// Created by Leon Weingartner on 6/21/20.\n// Copyright © 2020 Leon Weingartner. All rights reserved.\n//\n\nimport UIKit\nimport Firebase\nimport FirebaseFirestore\n\nclass MoveToClaimedViewController: UIViewController {\n\n @IBOutlet weak var orderIDLabel: UILabel!\n @IBOutlet weak var restLabel: UILabel!\n @IBOutlet weak var nameLabel: UILabel!\n @IBOutlet weak var phoneLabel: UILabel!\n @IBOutlet weak var orderDesLabel: UITextView!\n @IBOutlet weak var paymentTypeLabel: UILabel!\n \n @IBOutlet weak var doDLabel: UILabel!\n \n @IBOutlet weak var toDLabel: UILabel!\n \n @IBOutlet weak var locationLabel: UILabel!\n \n @IBOutlet weak var destinationLabel: UITextView!\n \n \n @IBAction func btnClaim(_ sender: Any) {\n \n globalClaimedName.name = claimedName.text!\n \n //add document to claimedorders\n Firestore.firestore().collection(\"ClaimedOrders\").document(globSelectOrderID.name).setData([\"name\": nameLabel.text, \"orderdes\": orderDesLabel.text, \"paymentmeth\": paymentTypeLabel.text, \"phonenum\": phoneLabel.text, \"restaurant\": restLabel.text, \"claimedby\": claimedName.text, \"dateofdelivery\": doDLabel.text, \"timeofdelivery\": toDLabel.text, \"location\": locationLabel.text, \"destination\": destinationLabel.text])\n \n \n //delete document from unclaimedorders\n Firestore.firestore().collection(\"UnclaimedOrders\").document(globSelectOrderID.name).delete() { err in\n if let err = err {\n print(\"Error removing document: \\(err)\")\n } else {\n print(\"Document successfully removed!\")\n }\n }\n \n \n }\n @IBOutlet weak var claimedName: UITextField!\n \n override func viewDidLoad() {\n super.viewDidLoad()\n let toolBar = UIToolbar()\n toolBar.sizeToFit()\n \n let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)\n \n let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: self, action: #selector(self.dismissKeyboard))\n \n toolBar.setItems([flexibleSpace, doneButton], animated: false)\n \n claimedName.inputAccessoryView = toolBar\n \n fetchData()\n \n let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))\n \n view.addGestureRecognizer(tap)\n \n \n \n \n // Do any additional setup after loading the view.\n }\n \n \n \n @objc func dismissKeyboard() {\n //Causes the view (or one of its embedded text fields) to resign the first responder status.\n view.endEditing(true)\n }\n \n \n func fetchData(){\n \n \n \n Firestore.firestore().collection(\"UnclaimedOrders\").getDocuments() { (querySnapshot, err) in\n if let err = err {\n print(\"Error getting documents: \\(err)\")\n } else {\n for document in (querySnapshot?.documents)! {\n \n // print(document.documentID)\n \n \n if document.documentID == globSelectOrderID.name {\n \n \n \n self.orderIDLabel.text = globSelectOrderID.name\n self.restLabel.text = (document.data()[\"restaurant\"] as! String)\n self.nameLabel.text = (document.data()[\"name\"] as! String)\n self.phoneLabel.text = (document.data()[\"phonenum\"] as! String)\n self.orderDesLabel.text = (document.data()[\"orderdes\"] as! String)\n self.paymentTypeLabel.text = (document.data()[\"paymentmeth\"] as! String)\n self.doDLabel.text = (document.data()[\"dateofdelivery\"] as! String)\n self.toDLabel.text = (document.data()[\"timeofdelivery\"] as! String)\n self.locationLabel.text = (document.data()[\"location\"] as! String)\n self.destinationLabel.text = (document.data()[\"destination\"] as! String)\n \n \n }\n \n }\n \n \n }\n \n }\n \n }\n\n}\n" }, { "alpha_fraction": 0.5474452376365662, "alphanum_fraction": 0.6131386756896973, "avg_line_length": 18.14285659790039, "blob_id": "03bd81c7ef3471442353f41f847358f263c87d6e", "content_id": "bb5ad369b28775ced742728729f1b8bb58ea657c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 138, "license_type": "no_license", "max_line_length": 49, "num_lines": 7, "path": "/Deliver-Lake-Powell-Startup/DeliverPage/Services/NetworkService.swift", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "//\n// NetworkService.swift\n// DeliverPage\n//\n// Created by Leon Weingartner on 6/17/20.\n// Copyright © 2020 Leon Weingartner. All rights reserved.\n//\n\n\n\n" }, { "alpha_fraction": 0.6182634830474854, "alphanum_fraction": 0.6317365169525146, "avg_line_length": 22.034482955932617, "blob_id": "6449c89d156d577282d5328517d0d6a28929eabd", "content_id": "8d658346696b95ceefe6fa2af8809eaed24a7be4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 669, "license_type": "no_license", "max_line_length": 117, "num_lines": 29, "path": "/Deliver-Lake-Powell-Startup/DeliverPage/Order.swift", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "//\n// Order.swift\n// DeliverPage\n//\n// Created by Leon Weingartner on 6/21/20.\n// Copyright © 2020 Leon Weingartner. All rights reserved.\n//\nimport Foundation\nimport UIKit\nclass Order {\n var restaurant: String\n var name: String\n var timeOfDelivery: String\n var claimedBy: String\n var orderID: String\n var date: String\n \n init(restaurant: String, name: String, timeOfDelivery: String, claimedBy: String, orderID: String, date: String){\n self.restaurant = restaurant\n self.name = name\n self.timeOfDelivery = timeOfDelivery\n self.claimedBy = claimedBy\n self.orderID = orderID\n self.date = date\n \n }\n \n \n}\n" }, { "alpha_fraction": 0.7512437701225281, "alphanum_fraction": 0.7738580107688904, "avg_line_length": 50.595237731933594, "blob_id": "6626e157ee1c9f8e157354163a68078105abfc1a", "content_id": "b73a93ce6080bb5217c266c09d8637157324b394", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2211, "license_type": "no_license", "max_line_length": 257, "num_lines": 42, "path": "/Lost-Island/ReadMe.md", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "![escape-the-island-gameplay](https://user-images.githubusercontent.com/35469554/35026027-dd82e3ae-fb05-11e7-92e6-64774193095c.png)\r\n\r\nDue to github restrictions, the actual game was too big to push to the repo. \r\nTo play, please download the game here ->\r\nhttps://drive.google.com/file/d/1oST5rnOM4RjzF-auQ7-7KVHNFJzagZ3U/view?usp=sharing\r\n\r\nWelcome to Leon & Felix Weingartner's Game Development and simulation programming game!\r\nAny problems, questions, or concerns please feel free to contact us at [email protected]\r\nAll code and documentation of this program are under copyright, all rights reserved\r\n(Note- Have this file on word wrap for easier reading, and highlight to keep track of your progress)\r\n\r\nAll code is in the Computer Game Application Code folder. They are currently in forms such as javascript and csharp, but you can open them in a text view such as notepad, word, etc.\r\n\r\nSystem Requirments\r\n-4gb of ram recommended\r\n-Windows 7 or higher (older versions could work, but have never been tested)\r\n-10 gb of space is required\r\n\r\nThings to note\r\n-Upon startup of game, you will be prompted to choose screen resolution, graphics quality, and monitor selection. We strongly recommend that these options are chosen best to the testing computer's/Monitor's capability (start with lower graphics to be safe)\r\n-There is an exit button that leads to the main menu\r\n-Press esc to pause the game\r\n-At the beginning of new levels, press space to begin\r\n\r\nHow to run the game\r\n-open the \"Fbla Project lost island final\" folder\r\n-Locate the lostilandgame1.exe file (has the unity logo icon)\r\n-Run that .exe file \r\n\r\n\r\nTips when playing the game:\r\n-This game is touchscreen compatable when on the inventory screen, you may use the touchscreen to craft and consume different items.\r\n-Objects may be a bit tricky to pick up sometimes, so just try different distances when picking up if neccessary\r\n-Game controls should be explained but just in case here they are\r\nW A S D keys to move\r\nShift key to run\r\nI to open and close inventory\r\nB to place crafted objects\r\ne to pick up objects\r\nmouse1 click to attack\r\nSpace bar to continue (on text briefs)\r\nEsc key to pause (Note- You can change graphics quality and show fps)\r\n\r\n" }, { "alpha_fraction": 0.49110719561576843, "alphanum_fraction": 0.5409389734268188, "avg_line_length": 29.29611587524414, "blob_id": "014555fd6bc3f3c49c1386bb4112ab12dc1c554f", "content_id": "1099666e5a77c56fc9c2354d50f8775f621991a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6241, "license_type": "no_license", "max_line_length": 220, "num_lines": 206, "path": "/Pair-Trading/Algorithms/PairTradingalgo.py", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "import click, json, time, math\nimport robin_stocks as rh\nimport numpy\nfrom scipy.stats.stats import pearsonr \nfrom scipy.stats import spearmanr\nimport yfinance as yf\nimport csv\n\n\n\n\n \n\ndef main():\n content = open('config.json').read()\n config = json.loads(content)\n rh.login(config['username'], config['password'])\n \n stockString = \"\"\n tick1Prices = []\n tick2Prices = []\n testTick1Prices = []\n testTick2Prices = []\n # tick1OpenPrices = []\n # tick2OpenPrices = []\n\n testDate = \"2020-2-26\"\n startDate = \"2020-3-26\"\n endDate = \"2020-04-26\"\n\n\n with open('Stocks') as w:\n\n symbols = w.read().splitlines()\n \n for i in range(0,len(symbols)):\n stockString += symbols[i] + \" \"\n\n data = yf.download(stockString, start = startDate, end = endDate)\n data2 = yf.download(stockString, start = testDate, end = startDate)\n csvList = []\n print(data)\n print(\"Working on it chief!\")\n\n \n \n for i in range(0, len(symbols)-1):\n for j in range(i+1,len(symbols)):\n\n #print(symbols[i], symbols[j])\n tick1Prices = data['Close'][symbols[i]]\n tick2Prices = data['Close'][symbols[j]]\n testTick1Prices = data2['Close'][symbols[i]]\n testTick2Prices = data2['Close'][symbols[j]]\n \n\n simCo = similarity(symbols[i], symbols[j], testTick1Prices, testTick2Prices)\n csvList.append(backtest(symbols[i],symbols[j], simCo, tick1Prices, tick2Prices))\n\n with open('stonks.csv', 'w', newline='') as f:\n write = csv.writer(f) \n write.writerow(['TICK 1','TICK 2','TRADES #', 'GROWTH W ALGO %', 'GROWTH WO ALGO %', 'GROWTH DIFF', 'PROFIT', 'INITIAL BUY', 'COEFFICIENT']) \n write.writerow(['','','=SUBTOTAL(1,C5:C130000)', '=SUBTOTAL(1,D5:D130000)', '=SUBTOTAL(1,E5:E130000)', '=SUBTOTAL(1,F5:F130000)', '=SUBTOTAL(1,G5:G130000)', '=SUBTOTAL(1,H5:H130000)', '=SUBTOTAL(1,I5:I130000)']) \n write.writerow([]) \n write.writerow([]) \n write.writerows(csvList)\n \n\n\n \n \n \n\n\n\n\ndef backtest(tick1, tick2, sim, t1p, t2p):\n\n \n \n list1 = []\n list2 = []\n \n buySellBack = False\n highMargin = .25-((sim+1)/2.55)**(5.8)\n if .23-((sim+1)/2.55)**(5.8) > 0:\n lowMargin = .23-((sim+1)/2.55)**(5.8)\n else:\n lowMargin = .005\n\n # print(highMargin,lowMargin)\n \n bsFrac = 1\n lastI = 0\n count = 0\n \n\n for i in range(0, len(t1p)-1):\n\n \n\n if(i == 0):\n #initial buy\n \n s1Amount = 1 \n s2Amount = float(t1p[i])/float(t2p[i])\n \n s1 = s1Amount*float(t1p[i])\n s2 = s2Amount*float(t2p[i])\n initialBuy = s1+s2\n invested = s1+s2\n buyPow = 0\n count += 1\n \n \n list1.append((float(t1p[i])-float(t1p[1]))/float(t1p[1]))\n list2.append((float(t2p[i])-float(t2p[1]))/float(t2p[1]))\n\n \n \n if(list1[i]-list2[i] > highMargin and buySellBack == False):\n #sell from list1 buy from list2 \n list1Sold = True\n buySellBack = True\n s1 = s1Amount*float(t1p[i])-bsFrac*s1Amount*float(t1p[i])\n s2 = s2Amount*float(t2p[i])+bsFrac*s2Amount*float(t2p[i])\n invested = s1+s2\n buyPow += bsFrac*s1Amount*float(t1p[i]) - bsFrac*s2Amount*float(t2p[i]) \n \n \n count += 1\n elif(list1[i]-list2[i] < -highMargin and buySellBack == False):\n #buy from list1 sell from list2\n list1Sold = False\n buySellBack = True\n s1 = s1Amount*float(t1p[i])+bsFrac*s1Amount*float(t1p[i])\n s2 = s2Amount*float(t2p[i])-bsFrac*s2Amount*float(t2p[i])\n invested = s1+s2\n buyPow += -bsFrac*s1Amount*float(t1p[i]) + bsFrac*s2Amount*float(t2p[i]) \n \n \n count += 1\n elif(abs(list1[i]-list2[i]) < lowMargin and buySellBack == True and list1Sold == True):\n #buy and sell back \n buySellBack = False\n s1 = s1Amount*float(t1p[i])\n s2 = s2Amount*float(t2p[i])\n invested = s1+s2\n buyPow += -bsFrac*s1Amount*float(t1p[i]) + bsFrac*s2Amount*float(t2p[i])\n \n \n count += 1\n elif(abs(list1[i]-list2[i]) < lowMargin and buySellBack == True and list1Sold == False):\n #buy and sell back \n buySellBack = False\n s1 = s1Amount*float(t1p[i])\n s2 = s2Amount*float(t2p[i])\n invested = s1+s2\n buyPow += bsFrac*s1Amount*float(t1p[i]) - bsFrac*s2Amount*float(t2p[i]) \n \n count += 1\n\n \n\n \n lastI = i\n\n if buySellBack == False:\n buyPow += s1Amount*float(t1p[lastI]) + s2Amount*float(t2p[lastI]) \n elif buySellBack == True and list1Sold == True:\n buyPow += s1Amount*float(t1p[lastI])-bsFrac*s1Amount*float(t1p[lastI]) + s2Amount*float(t2p[lastI])+bsFrac*s2Amount*float(t2p[lastI])\n elif buySellBack == True and list1Sold == False:\n buyPow += s1Amount*float(t1p[lastI])+bsFrac*s1Amount*float(t1p[lastI]) + s2Amount*float(t2p[lastI])-bsFrac*s2Amount*float(t2p[lastI])\n\n invested = 0\n \n \n growthw = 100*(invested+buyPow-initialBuy)/initialBuy\n growthwo = 100*(s1Amount*float(t1p[lastI]) + s2Amount*float(t2p[lastI])-initialBuy)/initialBuy\n\n #print(\"{} {}, {}, {}, {}, {}, {}, {}, {}\".format(tick1,tick2, count, growthw, growthwo, growthw-growthwo, invested+buyPow-initialBuy, initialBuy, sim))\n return([tick1,tick2, count, growthw, growthwo, growthw-growthwo, invested+buyPow-initialBuy, initialBuy, sim])\n \n\n\n\n \n\ndef similarity(tick1, tick2, t1p, t2p):\n \n \n list1 = []\n list2 = []\n \n for i in range(1, len(t1p)-1):\n list1.append((float(t1p[i])-float(t1p[1]))/float(t1p[1]))\n list2.append((float(t2p[i])-float(t2p[1]))/float(t2p[1]))\n \n \n #print(t1p)\n #print(spearmanr(list1,list2))\n return(spearmanr(list1,list2)[0])\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6716247200965881, "alphanum_fraction": 0.681922197341919, "avg_line_length": 26.3125, "blob_id": "3714a906443f9e9299c3c03c183efd973f6ca366", "content_id": "907d01a75f692ecd6997554fa8790c189d4b0a99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 875, "license_type": "no_license", "max_line_length": 79, "num_lines": 32, "path": "/Deliver-Lake-Powell-Startup/UserTab/FinalOrderScreenViewController.swift", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "//\n// FinalOrderScreenViewController.swift\n// DeliverPage\n//\n// Created by Leon Weingartner on 6/24/20.\n// Copyright © 2020 Leon Weingartner. All rights reserved.\n//\n\nimport UIKit\n\nclass FinalOrderScreenViewController: UIViewController {\n\n @IBOutlet weak var txtBox: UILabel!\n @IBOutlet weak var txtTitle: UITextView!\n override func viewDidLoad() {\n super.viewDidLoad()\n txtTitle.text = \"\\(globName.name), Your order has been received!\"\n txtBox.text = \"We will call you when your order is ready!\"\n \n\n // Do any additional setup after loading the view.\n }\n override func viewWillAppear(_ animated: Bool) {\n navigationController?.setNavigationBarHidden(true, animated: animated)\n }\n override func viewWillDisappear(_ animated: Bool) {\n navigationController?.setNavigationBarHidden(false, animated: animated)\n }\n \n\n\n}\n" }, { "alpha_fraction": 0.4481605291366577, "alphanum_fraction": 0.48494982719421387, "avg_line_length": 16.647058486938477, "blob_id": "5fddb83a2fd38a34628a4d4a15f47cbe05c4f8a5", "content_id": "1e46ef21e64f6023719191a461eb32a35a9abedf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 299, "license_type": "no_license", "max_line_length": 55, "num_lines": 17, "path": "/Pair-Trading/ExperimentalScripts/Black-Scholes.py", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "def main():\n s1 = \"ABC\"\n s2 = \"CBA\"\n are_reverses(s1,s2)\n\n\n\ndef are_reverses(string_1, string_2):\n for i in range(len(string_1)):\n if(string_1[i] != string_2[len(string_1)-1-i]):\n return False\n \n return True\n \n \nif __name__ == \"__main__\":\n main()" }, { "alpha_fraction": 0.6094674468040466, "alphanum_fraction": 0.6597633361816406, "avg_line_length": 21.600000381469727, "blob_id": "ba8f11dd036eaf473b39493ab7ba6bf26e80bea9", "content_id": "722c5aeba5036d8f643775eb004142bff6a7df41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 338, "license_type": "no_license", "max_line_length": 67, "num_lines": 15, "path": "/Pair-Trading/ExperimentalScripts/test.py", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "import click, json, time, math\nimport robin_stocks as rh\nimport numpy\nfrom scipy.stats.stats import pearsonr \nfrom scipy.stats import spearmanr\nimport yfinance as yf\n\n\ndef main(): \n data = yf.download(\"JPM\", start=\"2017-01-01\", end=\"2017-04-30\")\n #tick1 = yf.Ticker(\"MSFT\")\n print(data)\n \nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.6297850012779236, "alphanum_fraction": 0.6402726769447327, "avg_line_length": 32.165218353271484, "blob_id": "11f06ef5ff76b20736a10e2f19327cac3e260160", "content_id": "cebeb0b3f7a69877efa1af6971528a4c3240e4fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 3815, "license_type": "no_license", "max_line_length": 149, "num_lines": 115, "path": "/Deliver-Lake-Powell-Startup/UserTab/Order2ViewController.swift", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "//\n// Order2ViewController.swift\n// DeliverPage\n//\n// Created by Leon Weingartner on 6/24/20.\n// Copyright © 2020 Leon Weingartner. All rights reserved.\n//\n\nimport UIKit\nimport SafariServices\n\nclass Order2ViewController: UIViewController, UITextViewDelegate {\n\n @IBOutlet weak var restLabel: UILabel!\n @IBOutlet weak var errorLabel: UILabel!\n @IBAction func btnNext(_ sender: Any) {\n if(txtOrder.text != \"\" && txtOrder.text != \"1x ferruccine alfredo\\n2x 12 piece chicken wings mild sauce\\n3x large pepironi pizza\"){\n globOrder.name = txtOrder.text\n performSegue(withIdentifier: \"order3segue\", sender: nil)\n }else{\n errorLabel.text = \"Required Field/s are empty\"\n }\n }\n \n @IBAction func btnMenu(_ sender: Any) {\n showSafariVC(for: globMenuLink.name)\n }\n func showSafariVC(for url: String) {\n guard let url = URL(string: url) else{\n return\n }\n let safariVC = SFSafariViewController(url: url)\n present(safariVC, animated: true)\n }\n \n private func setupNavigationBarItems() {\n \n let titleImageView = UIImageView(image: #imageLiteral(resourceName: \"Deliver Logo\"))\n titleImageView.frame = CGRect(x: 0, y: 0, width: 34, height: 34)\n titleImageView.contentMode = .scaleAspectFit\n let widthConstraint = titleImageView.widthAnchor.constraint(equalToConstant: 120)\n let heightConstraint = titleImageView.heightAnchor.constraint(equalToConstant: 48)\n heightConstraint.isActive = true\n widthConstraint.isActive = true\n navigationItem.titleView = titleImageView\n \n \n }\n \n @IBOutlet weak var txtOrder: UITextView!\n \n override func viewDidLoad() {\n \n setupNavigationBarItems()\n \n restLabel.text = globRest.name\n errorLabel.text = \"\"\n super.viewDidLoad()\n txtOrder.delegate = self\n textViewDidBeginEditing(txtOrder)\n textViewDidEndEditing(txtOrder)\n \n txtOrder.text = \"1x ferruccine alfredo\\n2x 12 piece chicken wings mild sauce\\n3x large pepironi pizza\"\n txtOrder.textColor = UIColor.lightGray\n txtOrder.layer.cornerRadius = 5\n txtOrder.layer.borderColor = UIColor.orange.cgColor\n txtOrder.layer.borderWidth = 1\n \n \n let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: \"dismissKeyboard\")\n \n view.addGestureRecognizer(tap)\n \n let toolBar = UIToolbar()\n toolBar.sizeToFit()\n \n let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)\n \n let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: self, action: #selector(self.dismissKeyboard))\n \n toolBar.setItems([flexibleSpace, doneButton], animated: false)\n \n txtOrder.inputAccessoryView = toolBar\n }\n \n @objc func dismissKeyboard() {\n //Causes the view (or one of its embedded text fields) to resign the first responder status.\n view.endEditing(true)\n }\n \n \n \n //add placeholder\n \n override func viewWillAppear(_ animated: Bool) {\n errorLabel.text = \"\"\n }\n \n func textViewDidBeginEditing(_ textView: UITextView) {\n if textView.textColor == UIColor.lightGray {\n textView.text = \"\"\n textView.textColor = UIColor.black\n }\n }\n func textViewDidEndEditing(_ textView: UITextView) {\n if textView.text.isEmpty {\n textView.text = \"1x ferruccine alfredo\\n2x 12 piece chicken wings mild sauce\\n3x large pepironi pizza\"\n textView.textColor = UIColor.lightGray\n }\n }\n \n\n \n\n}\n" }, { "alpha_fraction": 0.7177605032920837, "alphanum_fraction": 0.7367587685585022, "avg_line_length": 34.81443405151367, "blob_id": "e4e632d7f7562af80cfc0d27370e981165fc0a5b", "content_id": "ddbf42780ec4c96fb7c7d0947a2d4e5ba451347e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 6948, "license_type": "no_license", "max_line_length": 200, "num_lines": 194, "path": "/Quantified-Happiness/QuantifiedHappiness.Rmd", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "---\ntitle: \"3080Project\"\nauthor: \"Leon Weingartner\"\ndate: \"5/1/2021\"\noutput: html_document\n---\n\n\n\n\n\n\n\n\n\n\n```{r,tidy=TRUE}\n#Correlation plot against every pair of variables\n\nsetwd(\"C:/Users/leonw/OneDrive/Desktop/Math 3800 project\")\nhappinessfile <- \"HappinessRegressions.csv\"\nhappinessData <- read.csv(happinessfile)\n\n\nlibrary(corrplot) \ncol <- colorRampPalette(c(\"#BB4444\", \"#EE9988\", \"#FFFFFF\", \"#77AADD\", \"#4477AA\")) #setup color palette for plot\nX <- cor(subset(happinessData, select = -c(Overall.rank, Country.or.region, Continent))) #create a subset of all columns in the data set except non-quantifiable ones\ncorrplot(X, method = \"color\", col = col(200), type = \"upper\", number.cex = .7, addCoef.col = \"black\", tl.col = \"black\", tl.srt = 90, sig.level = 0.01, insig = \"blank\", diag = FALSE) #plot correlations\n```\n\n```{r,tidy=TRUE}\n#distribution of score\nsetwd(\"C:/Users/leonw/OneDrive/Desktop/Math 3800 project\")\nhappinessfile <- \"HappinessRegressions.csv\"\nhappinessData <- read.csv(happinessfile)\n\n#plot distribution of happiness scores using histogram\nx<- happinessData$Score\nh<-hist(x,breaks = 10, col = \"steelblue\", xlab = \"Happiness Score\", ylab = \"Count\", main = \"Happiness Score with Normal Curve\")\n\n#draw normal curve with same mean and sd. \nxfit<-seq(min(x),max(x),length=40)\nyfit<-dnorm(xfit,mean=mean(x),sd=sd(x))\nyfit <- yfit*diff(h$mids[1:2])*length(x)\nlines(xfit, yfit, col=\"blue\", lwd=2)\n\n#qq plot\nqqnorm(happinessData$Score, pch = 1, frame = FALSE)\nqqline(happinessData$Score, col = \"red\", lwd = 2)\nsummary(happinessData$Score)\n\n\n\n```\n\n```{r,tidy=TRUE}\nsetwd(\"C:/Users/leonw/OneDrive/Desktop/Math 3800 project\")\nhappinessfile <- \"HappinessRegressions.csv\"\nhappinessData <- read.csv(happinessfile)\n\n\n#freedom to make life choices\n\n#simple regression line\nsummary(happinessData$Freedom.to.make.life.choices)\nsummary(lm(Score~Freedom.to.make.life.choices, happinessData))\nplot(Score~Freedom.to.make.life.choices, happinessData, pch = 16)\nabline(lm(Score~Freedom.to.make.life.choices, happinessData), col = \"red\")\n\n#distribution of Freedom.to.make.life.choices\nx<- happinessData$Freedom.to.make.life.choices\nh<-hist(x,breaks = 10, col = \"steelblue\", xlab = \"Freedom.to.make.life.choices\", ylab = \"Count\", main = \"Freedom to Make Life Choices Distribution\")\n\n#Plot residuals \nscore.lm = lm(Score~Freedom.to.make.life.choices, happinessData)\nscore.res = resid(score.lm)\nplot(happinessData$Freedom.to.make.life.choices, score.res, ylab = \"Residuals\", xlab = \"Freedom to Make Life Choices\", main = \"Happiness~Freedom to Make Life Choices Residuals\")\nabline(0,0)\n\n\n\n#Healthy Life Expectancy\n\n#simple regression line\nsummary(happinessData$Healthy.life.expectancy)\nsummary(lm(Score~Healthy.life.expectancy, happinessData))\nplot(Score~Healthy.life.expectancy, happinessData, pch = 16)\nabline(lm(Score~Healthy.life.expectancy, happinessData), col = \"red\")\n\n#distribution of Healthy.life.expectancy\nx<- happinessData$Healthy.life.expectancy\nh<-hist(x,breaks = 10, col = \"steelblue\", xlab = \"Healthy.life.expectancy\", ylab = \"Count\", main = \"Healthy Life Expectancy Distribution\")\n\n#Plot residuals\nscore.lm = lm(Score~Healthy.life.expectancy, happinessData)\nscore.res = resid(score.lm)\nplot(happinessData$Healthy.life.expectancy, score.res, ylab = \"Residuals\", xlab = \"Healthy Life Expectancy\", main = \"Happiness~Healthy Life Expectancy Residuals\")\nabline(0,0)\n\n\n\n#Social Support\n\n#simple regression line\nsummary(happinessData$Social.support)\nsummary(lm(Score~Social.support, happinessData))\nplot(Score~Social.support, happinessData, pch = 16)\nabline(lm(Score~Social.support, happinessData), col = \"red\")\n\n#distribution of Social.support\nx<- happinessData$Social.support\nh<-hist(x,breaks = 10, col = \"steelblue\", xlab = \"Social.support\", ylab = \"Count\", main = \"Social Support Distribution\")\n\n#Plot residuals\nscore.lm = lm(Score~Social.support, happinessData)\nscore.res = resid(score.lm)\nplot(happinessData$Social.support, score.res, ylab = \"Residuals\", xlab = \"Social Support\", main = \"Happiness~Social Support Residuals\")\nabline(0,0)\n\n\n\n\n```\n\n```{r,tidy=TRUE}\nsetwd(\"C:/Users/leonw/OneDrive/Desktop/Math 3800 project\")\nhappinessfile <- \"HappinessRegressions.csv\"\nhappinessData <- read.csv(happinessfile)\n\n\n#Experimental model with variables that have low correlation\nmodel1 <- lm(formula = Score ~ GDP.per.capita + Perceptions.of.corruption + Generosity, data = happinessData)\nplot(model1)\nsummary(model1)\n\n#summary of final model using 4 significant variables\nmodel2 <- lm(formula = Score ~ GDP.per.capita + Social.support + Healthy.life.expectancy + Freedom.to.make.life.choices , data = happinessData)\nplot(model2)\nsummary(model2)\n\n#data of the country suriname from 2015\nd <- data.frame(GDP.per.capita = c(.99534), Social.support = c(.972), Healthy.life.expectancy = c(.6082), Freedom.to.make.life.choices = c(.5966))\n#predict happiness of suriname and find prediction interval\npredict(model2, newdata = d, interval = \"predict\")\n\n\n#summary of model including all 6 variables\nmodel3 <- lm(formula = Score ~ GDP.per.capita + Social.support + Healthy.life.expectancy + Freedom.to.make.life.choices + Generosity + Perceptions.of.corruption , data = happinessData)\nplot(model3)\nsummary(model3)\n\n```\n\n\n\n```{r,tidy=TRUE}\nsetwd(\"C:/Users/leonw/OneDrive/Desktop/Math 3800 project\")\nhappinessfile <- \"HappinessRegressions.csv\"\nhappinessData <- read.csv(happinessfile)\n\n#visualize count of countries by continent\nx<- happinessData$Continent\nbarplot(table(x))\n\n#happiness distribution of countries in Europe\nEurope <- subset(happinessData, Continent == \"Europe\")\nh<-hist(Europe$Score,xlim = c(2,9),breaks = seq(2, 9), col = \"steelblue\", xlab = \"Happiness Score\", ylab = \"Count\", main = \"Happiness Score in Europe\")\nprint(\"Europe\")\nsummary(Europe$Score)\n\n#happiness distribution of countries in Asia\nAsia <- subset(happinessData, Continent == \"Asia\")\nh<-hist(Asia$Score,xlim = c(2,9),breaks = seq(2, 9), col = \"steelblue\", xlab = \"Happiness Score\", ylab = \"Count\", main = \"Happiness Score in Asia\")\nprint(\"Asia\")\nsummary(Asia$Score)\n\n#happiness distribution of countries in Africa\nAfrica <- subset(happinessData, Continent == \"Africa\")\nh<-hist(Africa$Score,xlim = c(2,9),breaks = seq(2, 9), col = \"steelblue\", xlab = \"Happiness Score\", ylab = \"Count\", main = \"Happiness Score in Africa\")\nprint(\"Africa\")\nsummary(Africa$Score)\n\n#happiness distribution of countries in North America\nNAm <- subset(happinessData, Continent == \"North America\")\nh<-hist(NAm$Score,xlim = c(2,9),breaks = seq(2, 9), col = \"steelblue\", xlab = \"Happiness Score\", ylab = \"Count\", main = \"Happiness Score in North America\")\nprint(\"North America\")\nsummary(NAm$Score)\n\n#happiness distribution of countries in South America\nSAm <- subset(happinessData, Continent == \"South America\")\nh<-hist(SAm$Score,xlim = c(2,9),breaks = seq(2, 9), col = \"steelblue\", xlab = \"Happiness Score\", ylab = \"Count\", main = \"Happiness Score in South America\")\nprint(\"South America\")\nsummary(SAm$Score)\n```\n" }, { "alpha_fraction": 0.6279069781303406, "alphanum_fraction": 0.6279069781303406, "avg_line_length": 16.714284896850586, "blob_id": "2256e781642594d22bf7bc852d48ca842c87703a", "content_id": "a3a7ce76aa7f0c935aa4b206badeee2093c3c816", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 131, "license_type": "no_license", "max_line_length": 52, "num_lines": 7, "path": "/Lost-Island/Computer Game Uncompiled Code/NoCursor.js", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "#pragma strict\nvar sound : AudioClip;\nfunction Start(){\r\n \r\n GetComponent.<AudioSource>().PlayOneShot(sound);\r\n \r\n}\r\n" }, { "alpha_fraction": 0.5745635628700256, "alphanum_fraction": 0.6069825291633606, "avg_line_length": 24.0625, "blob_id": "38c366b85af0b67b3a8aa75169b9b6a9205b2cd2", "content_id": "cf07377252be11eaf35368f87b9891dcb141fd8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2005, "license_type": "no_license", "max_line_length": 123, "num_lines": 80, "path": "/Pair-Trading/ExperimentalScripts/Stonks.py", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "import click, json, time, math\nimport robin_stocks as rh\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\[email protected]()\ndef main():\n content = open('config.json').read()\n config = json.loads(content)\n rh.login(config['username'], config['password'])\n\n\n\n\[email protected](help='backtest')\[email protected]('--tick1', prompt = '1st ticker: ')\[email protected]('--tick2', prompt = '2nd ticker: ')\ndef backtest(tick1, tick2):\n print(tick1, tick2)\n\n historyDict1 = rh.stocks.get_stock_historicals(tick1, interval = 'day', span = 'year', bounds = 'regular', info = None)\n historyDict2 = rh.stocks.get_stock_historicals(tick2, interval = 'day', span = 'year', bounds = 'regular', info = None)\n\n\n price1 = []\n price2 = []\n vol1 = []\n vol2 = []\n priceFrac = float(historyDict1[0]['close_price'])/float(historyDict2[0]['close_price'])\n test = [i for i in range(1,254)]\n\n\n\n\n #print(test)\n #print(\"______\")\n #print(len(test))\n\n for i, hist in enumerate(historyDict1, start=0):\n \n price1.append(float(hist['close_price']))\n price2.append(float(historyDict2[i]['close_price'])*priceFrac)\n\n vol1.append(float(hist['volume']))\n vol2.append(float(historyDict2[i]['volume']))\n\n\n #print(\"volume of {} --- {}\".format(tick1, vol1))\n\n #plt.plot(test, vol1, label='volume')\n #plt.plot(test, price1, label='price')\n #plt.xlabel(\"Time (days)\")\n #plt.ylabel(\"price\")\n #plt.legend()\n\n fig = plt.figure()\n ax1=fig.add_subplot(1,2,1)\n ax2=fig.add_subplot(1,2,2)\n ax1.plot(test, price1,label='price1')\n ax1.plot(test, price2, label = 'price2')\n ax2.plot(test, vol1, label='volume')\n ax1.set_xlabel('Time (D)')\n ax1.set_ylabel('price')\n ax1.set_title('Price over Year')\n ax1.legend()\n ax2.set_xlabel('Time (D)')\n ax2.set_ylabel('volume')\n ax2.set_title('volume over Year')\n ax2.legend()\n\n \n\n plt.show()\n\n\n #plt.plot([i for i in (1,254)], vol1)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.7389659285545349, "alphanum_fraction": 0.7856242060661316, "avg_line_length": 65.08333587646484, "blob_id": "575550e16c3d77f69ef9e622be99396cdeeaaf61", "content_id": "0100f8fd197cb24be41e89e8542c120b32207747", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 793, "license_type": "no_license", "max_line_length": 154, "num_lines": 12, "path": "/Ridiculous-Dungeons/ReadMe.md", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "![game-view](https://user-images.githubusercontent.com/35469554/35026125-58fef356-fb06-11e7-9888-3e7ceab454b3.PNG)\n\nThis is a 2D Top-Down strategy game where you, the player, are trying to escape a randomly generated dungeon.\nThe complexity of the randomly generated dungeon is based on the level.\nThe objective is to reach the hidden relic in the fastest time, but its not that simple.\nYour score is also based on how many enemies you kill, how many gems your pick up, how much health you have remaining, and how quickly you find the relic.\n\nTo view more game info, or get a quick overview of how the game looks, please see the power point presentation.\n\nTo play the game, run the exe in the \"Ridiculous Dungeons' Folder.\n\nTo view the code, navigate to the scripts folder in the .gmx folder.\n" }, { "alpha_fraction": 0.48067861795425415, "alphanum_fraction": 0.5014137625694275, "avg_line_length": 16.700000762939453, "blob_id": "6c60eb217a677fbebb1ebbd5620ae7f2d3427a8d", "content_id": "832355b6f022c932011ca3e03a0b02fc35a59dab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1061, "license_type": "no_license", "max_line_length": 73, "num_lines": 60, "path": "/Pair-Trading/ExperimentalScripts/RSIalgo.py", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "def main():\n\n content = open('config.json').read()\n config = json.loads(content)\n rh.login(config['username'], config['password'])\n \n stockString = \"\"\n tickPrices = []\n\n\n \n startDate = \"2020-01-25\"\n endDate = \"2021-01-25\"\n\n\n with open('Stocks') as w:\n\n symbols = w.read().splitlines()\n \n for i in range(0,len(symbols)):\n stockString += symbols[i] + \" \"\n\n data = yf.download(stockString, start = startDate, end = endDate)\n\n csvList = []\n \n print(\"Working on it chief!\")\n\n \n \n for i in range(0,len(symbols)):\n tickPrices = data['Close'][symbols[i]]\n \n\n\ndef backtest(priceList, RSI, rsiPeriod):\n\n highMargin = .7\n lowMargin = .3\n didBuy = False\n shares = 1\n\n\n for i in range(0, len(RSI)):\n\n if(RSI[i] > highMargin and didBuy == False):\n didBuy == True \n \n\n\n elif(RSI[i] < lowMargin and didBuy == True):\n didBuy == False\n\n\n \n\n\n\nif __name__ == \"__main__\":\n main()" }, { "alpha_fraction": 0.543698251247406, "alphanum_fraction": 0.5517479181289673, "avg_line_length": 31.207406997680664, "blob_id": "5236a927c575a528ac28c1303138dd438f76b092", "content_id": "2a18d5dd8353d572130b0bc7f8383f4363783b1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 4349, "license_type": "no_license", "max_line_length": 130, "num_lines": 135, "path": "/Deliver-Lake-Powell-Startup/UserTab/ActiveOrderViewController.swift", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "//\n// ActiveOrderViewController.swift\n// DeliverPage\n//\n// Created by Leon Weingartner on 6/23/20.\n// Copyright © 2020 Leon Weingartner. All rights reserved.\n//\n\nimport UIKit\nimport Firebase\nimport FirebaseFirestore\n\n\nclass ActiveOrderViewController: UIViewController {\n \n \n @IBAction func btnCall(_ sender: Any) {\n guard let url = URL(string: \"telprompt://4355926614\") else {\n return\n }\n \n UIApplication.shared.open(url)\n }\n \n @IBOutlet weak var orderDateLabel: UILabel!\n @IBOutlet weak var orderFromLabel: UILabel!\n \n @IBOutlet weak var orderIDLabel: UILabel!\n \n @IBOutlet weak var orderStatusLabel: UILabel!\n \n @IBOutlet weak var statusImg: UIImageView!\n \n let group = DispatchGroup()\n var collectionNum: Int = 0\n \n private func setupNavigationBarItems() {\n \n let titleImageView = UIImageView(image: #imageLiteral(resourceName: \"Deliver Logo\"))\n titleImageView.frame = CGRect(x: 0, y: 0, width: 34, height: 34)\n titleImageView.contentMode = .scaleAspectFit\n let widthConstraint = titleImageView.widthAnchor.constraint(equalToConstant: 120)\n let heightConstraint = titleImageView.heightAnchor.constraint(equalToConstant: 48)\n heightConstraint.isActive = true\n widthConstraint.isActive = true\n navigationItem.titleView = titleImageView\n \n \n }\n \n \n override func viewDidLoad() {\n super.viewDidLoad()\n setupNavigationBarItems()\n statusImg.image = nil\n \n orderIDLabel.text = \"\"\n orderFromLabel.text = \"\"\n orderDateLabel.text = \"\"\n orderStatusLabel.text = \"Loading...\"\n checkCat(collection: \"UnclaimedOrders\")\n checkCat(collection: \"ClaimedOrders\")\n group.notify(queue: .main){\n if(self.collectionNum == 1){\n self.statusImg.image = UIImage(named: \"lightOrangeStatusOrder\")\n self.orderFromLabel.text = \"Order From: \\(String(UserDefaults.standard.string(forKey: \"activeOrderRest\")!))\"\n self.orderIDLabel.text = \"OrderID: \\(String(UserDefaults.standard.string(forKey: \"activeOrder\")!))\"\n self.orderDateLabel.text = \"Time of Delivery: \\(String(UserDefaults.standard.string(forKey: \"activeOrderDate\")!))\"\n self.orderStatusLabel.text = \"Your order has been processed!\"\n \n }else if(self.collectionNum == 2){\n self.statusImg.image = UIImage(named: \"lightOrangeStatusClaim\")\n self.orderFromLabel.text = \"Order From: \\(String(UserDefaults.standard.string(forKey: \"activeOrderRest\")!))\"\n self.orderIDLabel.text = \"OrderID: \\(String(UserDefaults.standard.string(forKey: \"activeOrder\")!))\"\n self.orderDateLabel.text = \"Time of Delivery: \\(String(UserDefaults.standard.string(forKey: \"activeOrderDate\")!))\"\n self.orderStatusLabel.text = \"Your food is on its way!\"\n }else{\n self.orderStatusLabel.text = \"You have no active orders\"\n }\n }\n \n \n \n \n }\n override func viewWillAppear(_ animated: Bool)\n {\n \n \n\n \n }\n \n\n \n \n \n \n \n func checkCat (collection: String){\n \n \n group.enter()\n Firestore.firestore().collection(collection).getDocuments() { (querySnapshot, err) in\n \n \n if let err = err {\n print(\"Error getting documents: \\(err)\")\n } else {\n for document in (querySnapshot?.documents)! {\n \n if let userDe = UserDefaults.standard.object(forKey: \"activeOrder\") as? String{\n \n if document.documentID == userDe && collection == \"UnclaimedOrders\"{\n self.collectionNum = 1\n \n \n }else if document.documentID == userDe && collection == \"ClaimedOrders\"{\n self.collectionNum = 2\n \n }\n }\n }\n }\n self.group.leave()\n }\n \n \n }\n \n \n \n \n \n}\n" }, { "alpha_fraction": 0.5275590419769287, "alphanum_fraction": 0.5565944910049438, "avg_line_length": 26.106666564941406, "blob_id": "0ccfc5649dcda7af85408ce34b2ce8e4efb115d0", "content_id": "8b69717b6fa327d4871dce3789adadd7d0e75a51", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2032, "license_type": "no_license", "max_line_length": 125, "num_lines": 75, "path": "/Pair-Trading/ExperimentalScripts/SimilarityChecker.py", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "import click, json, time, math\nimport robin_stocks as rh\n\n\ndef main():\n content = open('config.json').read()\n config = json.loads(content)\n rh.login(config['username'], config['password'])\n list1 = []\n list2 = []\n\n\n with open('Stocks') as w:\n\n symbols = w.read().splitlines()\n \n for i in range(0,len(symbols)-2):\n for j in range(i+1,len(symbols)-1):\n simCo = similarity(symbols[i], symbols[j])\n print(symbols[i], symbols[j], simCo)\n if simCo >= .997:\n list1.append(\"{} {} {}\".format(symbols[i], symbols[j], simCo))\n #print(symbols[j], symbols[j], simCo)\n print()\n\n\n print(list1)\n\n \n\n\n\n\ndef similarity(tick1, tick2):\n \n historyDict1 = rh.stocks.get_stock_historicals(tick1, interval = 'week', span = '5year', bounds = 'regular', info = None)\n historyDict2 = rh.stocks.get_stock_historicals(tick2, interval = 'week', span = '5year', bounds = 'regular', info = None)\n \n \n initPrice1 = historyDict1[0]['close_price']\n initPrice2 = historyDict2[0]['close_price']\n list1 = []\n list2 = []\n aDotb = 0\n normA = 0\n normB = 0\n if(initPrice1 == None or initPrice2 == None or float(initPrice1) == 0 or float(initPrice2) == 0):\n return 0\n \n for i, hist in enumerate(historyDict1, start=0):\n\n # list1.append((float(hist['close_price'])-float(initPrice1))/float(initPrice1))\n # list2.append((float(historyDict2[i]['close_price'])-float(initPrice2))/float(initPrice2))\n\n list1.append(float(hist['close_price']))\n list2.append(float(historyDict2[i]['close_price']))\n aDotb += list1[i]*list2[i]\n normA += list1[i] ** 2\n normB += list2[i] ** 2\n\n \n \n # print(tick1)\n # print(tick2)\n # print(aDotb/(math.sqrt(normA * normB)))\n # print()\n \n if(normA*normB == 0):\n return 0\n\n return(aDotb/(math.sqrt(normA * normB)))\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.5824933052062988, "alphanum_fraction": 0.6026540994644165, "avg_line_length": 21.402297973632812, "blob_id": "47d775cb11a6b1c4c27914cbc45251ce99cc8dee", "content_id": "338fabfb847618ba750e4ebb6a78286e4560bd0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 7839, "license_type": "no_license", "max_line_length": 113, "num_lines": 348, "path": "/Lost-Island/Computer Game Uncompiled Code/PlayerGUI3.js", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "#pragma strict\n\n\n//Size of Textures\n\nvar size : Vector2 = new Vector2(240, 40);\n\nvar hasPlayed : boolean = false;\nvar x : int = 0;\nvar y : int = 0;\nvar z : int = 0;\n\n\n//Health Variables\nvar healthPos : Vector2 = new Vector2(20, 20);\nvar healthBarDisplay : float = 1;\nvar healthBarEmpty : Texture2D;\nvar healthBarFull : Texture2D;\n\n//Hunger Variables\nvar hungerPos : Vector2 = new Vector2(20, 60);\nvar hungerBarDisplay : float = 1;\nvar hungerBarEmpty : Texture2D;\nvar hungerBarFull : Texture2D;\n\n//Thirst Variables\nvar thirstPos : Vector2 = new Vector2(20, 100);\nvar thirstBarDisplay : float = 1;\nvar thirstBarEmpty : Texture2D;\nvar thirstBarFull : Texture2D;\n\n//Stamina Variables\nvar staminaPos : Vector2 = new Vector2(20, 140);\nvar staminaBarDisplay : float = 1;\nvar staminaBarEmpty : Texture2D;\nvar staminaBarFull : Texture2D;\n\n//Fall Rate\nvar healthFallRate : int = 150;\nvar hungerFallRate : int = 150;\nvar thirstFallRate : int = 100;\nvar staminaFallRate : int = 35;\n\nvar infoicon : GameObject;\nvar infoicon1 : GameObject;\nvar infoicon2 : GameObject;\n\nvar Info : AudioClip;\n\nvar damageGUI : GameObject;\n\nvar quit = false;\n\nprivate var textScript: text2;\n\n//private var FPC : FirstPersonController;\nprivate var controller : CharacterController;\n//private var imessage : message;\n\nvar canJump : boolean = false;\n\nvar jumpTimer : float = 0.7;\n\n\nvar destination : Transform;\nvar RespawnGUI : GameObject;\n//var tent : GameObject;\n\nfunction Start()\n{\r\n \n //FPC = GetComponent(FirstPersonController);\n controller = GetComponent(CharacterController);\n textScript = GameObject.Find(\"Objectives\").GetComponent(text2);\n\n}\n\nfunction OnGUI()\n{\n //Health GUI\n GUI.BeginGroup(new Rect (healthPos.x, healthPos.y, size.x, size.y));\n GUI.Box(Rect(0, 0, size.x, size.y), healthBarEmpty);\n\t\n GUI.BeginGroup(new Rect (0, 0, size.x * healthBarDisplay, size.y));\n GUI.Box(Rect(0, 0, size.x, size.y), healthBarFull);\n\t\n GUI.EndGroup();\n GUI.EndGroup();\n\t\n //Hunger GUI\n GUI.BeginGroup(new Rect (hungerPos.x, hungerPos.y, size.x, size.y));\n GUI.Box(Rect(0, 0, size.x, size.y), hungerBarEmpty);\n\t\n GUI.BeginGroup(new Rect (0, 0, size.x * hungerBarDisplay, size.y));\n GUI.Box(Rect(0, 0, size.x, size.y), hungerBarFull);\n\t\n GUI.EndGroup();\n GUI.EndGroup();\n\t\n //Thirst GUI\n GUI.BeginGroup(new Rect (thirstPos.x, thirstPos.y, size.x, size.y));\n GUI.Box(Rect(0, 0, size.x, size.y), thirstBarEmpty);\n\t\n GUI.BeginGroup(new Rect (0, 0, size.x * thirstBarDisplay, size.y));\n GUI.Box(Rect(0, 0, size.x, size.y), thirstBarFull);\n\t\n GUI.EndGroup();\n GUI.EndGroup();\n\t\n //Stamina GUI\n GUI.BeginGroup(new Rect (staminaPos.x, staminaPos.y, size.x, size.y));\n GUI.Box(Rect(0, 0, size.x, size.y), staminaBarEmpty);\n\t\n GUI.BeginGroup(new Rect (0, 0, size.x * staminaBarDisplay, size.y));\n GUI.Box(Rect(0, 0, size.x, size.y), staminaBarFull);\n\t\n GUI.EndGroup();\n GUI.EndGroup();\n}\n\nfunction Update()\n{\n //imessage = GameObject.Find(\"message\");\n //tent.FindGameObjectsWithTag(\"tent\");\n //HEALTH CONTROL SECTION\n if(hungerBarDisplay <= 0 && (thirstBarDisplay <= 0))\n {\n healthBarDisplay -= Time.deltaTime / healthFallRate * 2;\n }\n\t\n else\n {\n if(hungerBarDisplay <= 0 || thirstBarDisplay <= 0)\n {\n healthBarDisplay -= Time.deltaTime / healthFallRate;\n // imessage.\n\t\t \n \n }\n }\n\t\n if(healthBarDisplay <= 0)\n {\n\t \n //yield WaitForSeconds(6);\n Respawn();\n\n }\n\t\n //HUNGER CONTROL SECTION\n if(hungerBarDisplay >= 0)\n {\n hungerBarDisplay -= Time.deltaTime / hungerFallRate;\n damageGUI.SetActive(false);\n }\n\t\n if(hungerBarDisplay <= 0)\n {\n hungerBarDisplay = 0;\n damageGUI.SetActive(true);\n textScript.calm = false;\n textScript.someText.text = \"You are Loosing Health!\";\n infoicon2.SetActive(true);\n\n }\n\t\n if(hungerBarDisplay >= 1)\n {\n hungerBarDisplay = 1;\n }\n\t\n //THIRST CONTROL SECTION\n if(thirstBarDisplay >= 0)\n {\n thirstBarDisplay -= Time.deltaTime / thirstFallRate;\n damageGUI.SetActive(false);\n }\n\t\n if(thirstBarDisplay <= 0)\n {\n thirstBarDisplay = 0;\n damageGUI.SetActive(true);\n textScript.calm = false;\n textScript.someText.text = \"You are Loosing Health!\";\n infoicon.SetActive(true);\n }\n\t\n if(thirstBarDisplay >= 1)\n {\n thirstBarDisplay = 1;\n }\n\n //problem situations\n\n if(healthBarDisplay <= .3)\n {\n\n textScript.calm = false;\n Debug.Log(\"sup dooggg\");\n\t \n\n\t \n textScript.someText.text = \"Heal yourself! your Health is low!\";\r\n infoicon1.SetActive(true);\r\n z++;\r\n if(z == 5)\r\n {\r\n\t \n GetComponent.<AudioSource>().PlayOneShot(Info);\r\n }\r\n }\n if(hungerBarDisplay <= .3 && hungerBarDisplay > .0001)\n {\n\t \n textScript.calm = false;\n\t \n textScript.someText.text = \"Eat something! your Hunger bar is low!\";\r\n infoicon2.SetActive(true);\r\n y++;\r\n if(y == 5)\r\n {\r\n\t \n GetComponent.<AudioSource>().PlayOneShot(Info);\r\n }\r\n }\n if(thirstBarDisplay <= .3 && thirstBarDisplay > .0001)\n {\n infoicon.SetActive(true);\n textScript.calm = false;\n Debug.Log(\"Noiccee\");\n textScript.someText.text = \"Drink something! your thirst bar is low!\";\r\n x++;\r\n if(x == 5)\r\n {\r\n\t \n GetComponent.<AudioSource>().PlayOneShot(Info);\r\n }\r\n\t \r\n\t\r\n\r\n\t \r\n }\n\n \n if(healthBarDisplay >= .31)\n {\t \n textScript.problem = 0;\r\n infoicon1.SetActive(false);\r\n z = 0;\r\n }\n if(hungerBarDisplay >= .31)\n {\n textScript.problem = 0;\r\n infoicon2.SetActive(false);\r\n y = 0;\r\n\t \r\n }\n if(thirstBarDisplay >= .31)\n {\n textScript.problem = 0;\r\n infoicon.SetActive(false);\r\n x = 0;\r\n }\n\n\n\n\n\t\n //STAMINA CONTROL SECTION\n if(Input.GetKey(KeyCode.LeftShift))\n {\n\t\t\n staminaBarDisplay -= Time.deltaTime / staminaFallRate;\n\t \n }\n \n\n\t\n else\n {\n //chMotor.movement.maxForwardSpeed = 6;\n //chMotor.movement.maxSidewaysSpeed = 6;\n staminaBarDisplay += Time.deltaTime / staminaFallRate;\n }\n\n\n\t\n\t\n\t\n if(staminaBarDisplay >= 1)\n {\n staminaBarDisplay = 1;\n }\n\t\n if(staminaBarDisplay <= 0)\n {\n\t\t\n staminaBarDisplay = 0;\n canJump = false;\n\t\t\n }\n}\n\nfunction Respawn()\n{\n Time.timeScale = 0;\n RespawnGUI.SetActive(true);\n (GameObject.FindWithTag(\"Player\").GetComponent(\"FirstPersonController\") as MonoBehaviour).enabled = false;\r\n (GameObject.FindWithTag(\"Axe\").GetComponent(\"idletoslash\")as MonoBehaviour).enabled = false;\n \n if(Input.GetKeyDown(\"space\"))\n {\n Time.timeScale = 1;\n Debug.Log(\"homeslice\");\n \n RespawnGUI.SetActive(false);\n this.gameObject.transform.position = destination.position + Vector3(20, 5, 5);\n \n healthBarDisplay = .5;\n hungerBarDisplay = 1;\n thirstBarDisplay = 1;\n staminaBarDisplay = 1;\n (GameObject.FindWithTag(\"Player\").GetComponent(\"FirstPersonController\") as MonoBehaviour).enabled = true;\r\n (GameObject.FindWithTag(\"Axe\").GetComponent(\"idletoslash\")as MonoBehaviour).enabled = true;\n\n var inventoryScript = GetComponent(Inv);\n inventoryScript.Reset();\r\n }\n if(Input.GetKeyDown(\"escape\"))\n {\n Time.timeScale = 1;\n RespawnGUI.SetActive(false);\n Application.LoadLevel(0);\r\n }\n\n \n}\n\nfunction Wait()\n{\n yield WaitForSeconds(0.5);\n //canJump = false;\n}\nfunction Play()\n{\n GetComponent.<AudioSource>().PlayOneShot(Info);\r\n \r\n}\n" }, { "alpha_fraction": 0.49073830246925354, "alphanum_fraction": 0.5296374559402466, "avg_line_length": 36.606964111328125, "blob_id": "dd18c6951b8241e452e3fe0076e6ba3181f3a0a0", "content_id": "c55f21db2234c00b6e5b523929697a7edb40ee5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7558, "license_type": "no_license", "max_line_length": 155, "num_lines": 201, "path": "/Pair-Trading/ExperimentalScripts/PairTradingPC.py", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "import click, json, time, math\nimport robin_stocks as rh\nfrom scipy.stats import spearmanr\nimport yfinance as yf\n\[email protected]()\ndef main():\n content = open('config.json').read()\n config = json.loads(content)\n rh.login(config['username'], config['password'])\n \n \n\n\n\[email protected](help='backtest')\[email protected]('--tick1', prompt = '1st ticker: ')\[email protected]('--tick2', prompt = '2nd ticker: ')\ndef backtest(tick1, tick2):\n stockString = tick1 + \" \" + tick2\n \n data = yf.download(stockString, start = \"2020-01-27\", end = \"2021-01-27\")\n\n list1 = []\n list2 = []\n t1p = data['Close'][tick1]\n t2p = data['Close'][tick2]\n sim = similarity(tick1,tick2)\n\n \n buySellBack = False\n highMargin = .25-((sim+1)/2.55)**(5.8)\n if.23-((sim+1)/2.55)**(5.8) > 0:\n lowMargin = .23-((sim+1)/2.55)**(5.8)\n else:\n lowMargin = .005\n\n # print(highMargin,lowMargin)\n \n bsFrac = 1\n lastI = 0\n count = 0\n \n\n for i in range(0, len(t1p)):\n\n \n\n if(i == 0):\n #initial buy\n \n s1Amount = 1 \n s2Amount = float(t1p[i])/float(t2p[i])\n \n s1 = s1Amount*float(t1p[i])\n s2 = s2Amount*float(t2p[i])\n initialBuy = s1+s2\n invested = s1+s2\n buyPow = 0\n print(\"initial buy at: {}\".format(initialBuy))\n print(\"Bought {} shares of {} at the price of: {}\".format(s1Amount, tick1, t1p[i]))\n print(\"Bought {} shares of {} at the price of: {}\".format(s2Amount, tick2, t2p[i]))\n print(\"________________\")\n \n \n list1.append((float(t1p[i])-float(t1p[0]))/float(t1p[0]))\n list2.append((float(t2p[i])-float(t2p[0]))/float(t2p[0]))\n\n \n \n if(list1[i]-list2[i] > highMargin and buySellBack == False):\n #sell from list1 buy from list2 \n list1Sold = True\n buySellBack = True\n s1 = s1Amount*float(t1p[i])-bsFrac*s1Amount*float(t1p[i])\n s2 = s2Amount*float(t2p[i])+bsFrac*s2Amount*float(t2p[i])\n invested = s1+s2\n buyPow += bsFrac*s1Amount*float(t1p[i]) - bsFrac*s2Amount*float(t2p[i]) \n count += 1\n\n print(i)\n print(\"Percent Change: {}\".format(100*list1[i]-list2[i]))\n print(\"BUY & SELL\")\n print(\"Sold {} at the price of: {}\".format(tick1, t1p[i]))\n print(\"Bought {} at the price of: {}\".format(tick2, t2p[i]))\n print(\"Invested: {}\".format(invested))\n print(\"Buying Power: {}\".format(buyPow))\n print(\"Total: {}\".format(invested+buyPow))\n print(\"Profit: {}\".format(invested+buyPow-initialBuy))\n print(\"________________\")\n print()\n elif(list1[i]-list2[i] < -highMargin and buySellBack == False):\n #buy from list1 sell from list2\n list1Sold = False\n buySellBack = True\n s1 = s1Amount*float(t1p[i])+bsFrac*s1Amount*float(t1p[i])\n s2 = s2Amount*float(t2p[i])-bsFrac*s2Amount*float(t2p[i])\n invested = s1+s2\n buyPow += -bsFrac*s1Amount*float(t1p[i]) + bsFrac*s2Amount*float(t2p[i]) \n count += 1\n print(i)\n print(\"Percent Change: {}\".format(100*list1[i]-list2[i]))\n print(\"BUY & SELL\")\n print(\"Bought {} at the price of: {}\".format(tick1, t1p[i]))\n print(\"Sold {} at the price of: {}\".format(tick2, t2p[i]))\n print(\"Invested: {}\".format(invested))\n print(\"Buying Power: {}\".format(buyPow))\n print(\"Total: {}\".format(invested+buyPow))\n print(\"Profit: {}\".format(invested+buyPow-initialBuy))\n print(\"________________\")\n print()\n elif(abs(list1[i]-list2[i]) < lowMargin and buySellBack == True and list1Sold == True):\n #buy and sell back \n buySellBack = False\n s1 = s1Amount*float(t1p[i])\n s2 = s2Amount*float(t2p[i])\n invested = s1+s2\n buyPow += -bsFrac*s1Amount*float(t1p[i]) + bsFrac*s2Amount*float(t2p[i]) \n count += 1\n print(i)\n print(\"Percent Change: {}\".format(100*list1[i]-list2[i]))\n print(\"BUY & SELL BACK\")\n print(\"Bought {} at the price of: {}\".format(tick1, t1p[i]))\n print(\"Sold {} at the price of: {}\".format(tick2, t2p[i]))\n print(\"Invested: {}\".format(invested))\n print(\"Buying Power: {}\".format(buyPow))\n print(\"Total: {}\".format(invested+buyPow))\n print(\"Profit: {}\".format(invested+buyPow-initialBuy))\n print(\"________________\")\n print()\n elif(abs(list1[i]-list2[i]) < lowMargin and buySellBack == True and list1Sold == False):\n #buy and sell back \n buySellBack = False\n s1 = s1Amount*float(t1p[i])\n s2 = s2Amount*float(t2p[i])\n invested = s1+s2\n buyPow += bsFrac*s1Amount*float(t1p[i]) - bsFrac*s2Amount*float(t2p[i]) \n count += 1\n print(i)\n print(\"Percent Change: {}\".format(100*list1[i]-list2[i]))\n print(\"BUY & SELL BACK\")\n print(\"Sold {} at the price of: {}\".format(tick1, t1p[i]))\n print(\"Bought {} at the price of: {}\".format(tick2, t2p[i]))\n print(\"Invested: {}\".format(invested))\n print(\"Buying Power: {}\".format(buyPow))\n print(\"Total: {}\".format(invested+buyPow))\n print(\"Profit: {}\".format(invested+buyPow-initialBuy))\n print(\"________________\")\n print()\n \n lastI = i\n\n if buySellBack == False:\n buyPow += s1Amount*float(t1p[lastI]) + s2Amount*float(t2p[lastI]) \n elif buySellBack == True and list1Sold == True:\n buyPow += s1Amount*float(t1p[lastI])-bsFrac*s1Amount*float(t1p[lastI]) + s2Amount*float(t2p[lastI])+bsFrac*s2Amount*float(t2p[lastI])\n elif buySellBack == True and list1Sold == False:\n buyPow += s1Amount*float(t1p[lastI])+bsFrac*s1Amount*float(t1p[lastI]) + s2Amount*float(t2p[lastI])-bsFrac*s2Amount*float(t2p[lastI])\n\n invested = 0\n \n \n growthw = 100*(invested+buyPow-initialBuy)/initialBuy\n growthwo = 100*(s1Amount*float(t1p[lastI]) + s2Amount*float(t2p[lastI])-initialBuy)/initialBuy\n\n print(\"{} {}, {}, {}, {}, {}, {}, {}, {}\".format(tick1,tick2, count, growthw, growthwo, growthw-growthwo, invested+buyPow-initialBuy, initialBuy, sim))\n print(\"_______________________________________________________________________________\")\n\n print(\"total profit w/algorithm: {}\".format(invested+buyPow-initialBuy))\n print(\"annual growth w/algorithm: +%{}\".format(growthw))\n print(\"------------------\")\n print(\"total profit w/o algorithm: {}\".format(s1Amount*float(t1p[lastI]) + s2Amount*float(t2p[lastI]) - initialBuy))\n print(\"annual growth w/o algorithm: +%{}\".format(growthwo))\n print(\"Number of Trades: {}\".format(count))\n \n \n\n\n\n \n\ndef similarity(tick1, tick2):\n stockString = tick1 + \" \" + tick2\n data = yf.download(stockString, start = \"2019-01-27\", end = \"2020-01-27\")\n t1p = data['Close'][tick1]\n t2p = data['Close'][tick2]\n list1 = []\n list2 = []\n \n for i in range(0, len(t1p)):\n list1.append((float(t1p[i])-float(t1p[0]))/float(t1p[0]))\n list2.append((float(t2p[i])-float(t2p[0]))/float(t2p[0]))\n \n \n\n return(spearmanr(list1,list2)[0])\n\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.4836116135120392, "alphanum_fraction": 0.5293753743171692, "avg_line_length": 17.375, "blob_id": "93f7ecc88f16cd522c601fb314265459c0f998c0", "content_id": "3171d08449c3acd08c57c7ff7ffd684c6962fe0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1617, "license_type": "no_license", "max_line_length": 90, "num_lines": 88, "path": "/Pair-Trading/ExperimentalScripts/Growth.py", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "import click, json, time, math\nimport robin_stocks as rh\nimport numpy\nfrom scipy.stats.stats import pearsonr \nfrom scipy.stats import spearmanr\nimport yfinance as yf\n\n\n\n # data = yf.download(\"SPY AAPL\", start=\"2017-01-01\", end=\"2017-04-30\")\n # print(data['Close']['SPY'][3])\n\n\n \n\ndef main():\n content = open('config.json').read()\n config = json.loads(content)\n rh.login(config['username'], config['password'])\n \n stockString = \"\"\n tick1Prices = []\n \n\n \n startDate = \"2020-01-27\"\n endDate = \"2021-01-27\"\n\n\n with open('Stocks') as w:\n\n symbols = w.read().splitlines()\n \n for i in range(0,len(symbols)):\n stockString += symbols[i] + \" \"\n\n data = yf.download(stockString, start = startDate, end = endDate)\n \n \n \n\n \n \n for i in range(0,len(symbols)):\n \n tick1Prices = data['Close'][symbols[i]]\n # simCo = similarity(symbols[i], symbols[j], testTick1Prices, testTick2Prices)\n backtest(symbols[i], tick1Prices)\n \n\n\n \n \n \n\n\n\n\ndef backtest(tick , t1p):\n\n \n growthwo = 100*(float(t1p[len(t1p)-1])-float(t1p[0]))/float(t1p[0])\n print(growthwo)\n\n \n \n\n\n\n \n\ndef similarity(tick1, tick2, t1p, t2p):\n \n \n list1 = []\n list2 = []\n \n for i in range(0, len(t1p)):\n list1.append((float(t1p[i])-float(t1p[0]))/float(t1p[0]))\n list2.append((float(t2p[i])-float(t2p[0]))/float(t2p[0]))\n \n \n\n return(spearmanr(list1,list2)[0])\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6216030120849609, "alphanum_fraction": 0.6253870129585266, "avg_line_length": 33.20000076293945, "blob_id": "51d2e3b46a5e1bd8202e5b8d3aa939bbb0a03bb0", "content_id": "0c9c14c63eba2e5b3f7acfa863edc0fc30c82886", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 5815, "license_type": "no_license", "max_line_length": 397, "num_lines": 170, "path": "/Deliver-Lake-Powell-Startup/UserTab/ViewController.swift", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "//\n// ViewController.swift\n// DeliverPage\n//\n// Created by Leon Weingartner on 6/17/20.\n// Copyright © 2020 Leon Weingartner. All rights reserved.\n//\nimport UIKit\nimport iOSDropDown\nimport Firebase\nimport FirebaseFirestore\nimport SystemConfiguration\nimport SwiftUI\n\n\npublic class ViewController: UIViewController{\n \n \n private let reachability = SCNetworkReachabilityCreateWithName(nil, \"www.apple.com\")\n \n @IBOutlet weak var loadIndicator: UIActivityIndicatorView!\n \n @IBOutlet weak var txtRest: UILabel!\n \n @IBOutlet weak var txtName: UILabel!\n \n @IBOutlet weak var txtPhone: UILabel!\n \n @IBOutlet weak var txtOrder: UITextView!\n \n @IBOutlet weak var txtPayment: UILabel!\n \n \n @IBOutlet weak var txtDoD: UILabel!\n \n @IBOutlet weak var txtToD: UILabel!\n \n @IBOutlet weak var txtLocation: UILabel!\n \n @IBOutlet weak var txtLocationInfo: UITextView!\n \n private func setupNavigationBarItems() {\n \n let titleImageView = UIImageView(image: #imageLiteral(resourceName: \"Deliver Logo\"))\n titleImageView.frame = CGRect(x: 0, y: 0, width: 34, height: 34)\n titleImageView.contentMode = .scaleAspectFit\n let widthConstraint = titleImageView.widthAnchor.constraint(equalToConstant: 120)\n let heightConstraint = titleImageView.heightAnchor.constraint(equalToConstant: 48)\n heightConstraint.isActive = true\n widthConstraint.isActive = true\n navigationItem.titleView = titleImageView\n \n \n }\n \n public override func viewWillAppear(_ animated: Bool) {\n \n txtRest.text = globRest.name\n txtName.text = globName.name\n txtPhone.text = globPhone.name\n txtOrder.text = globOrder.name\n txtPayment.text = globPayment.name\n txtDoD.text = globDateOfDelivery.name\n txtToD.text = globTimeOfDelivery.name\n txtLocation.text = globDestination.name\n txtLocationInfo.text = globDestDes.name\n }\n override public func viewDidLoad() {\n super.viewDidLoad()\n \n setupNavigationBarItems()\n \n submitBtn.isEnabled = true\n \n //hide load indicator on start\n loadIndicator.hidesWhenStopped = true\n loadIndicator.stopAnimating()\n \n \n let db = Firestore.firestore()\n \n \n \n \n \n }\n \n //check if there is internet connection\n private func isNetworkReachable(with flags : SCNetworkReachabilityFlags) -> Bool {\n let isReachable = flags.contains(.reachable)\n let needsConnection = flags.contains(.connectionRequired)\n let canConnectAutomatically = flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic)\n let canConnectWithoutInteraction = canConnectAutomatically && !flags.contains(.interventionRequired)\n \n return isReachable && (!needsConnection || canConnectWithoutInteraction)\n }\n \n @objc private func callback() {\n performSegue(withIdentifier: \"ordersegue\", sender: nil)\n self.loadIndicator.stopAnimating()\n }\n \n \n @IBOutlet weak var submitBtn: UIButton!\n \n @IBAction func btn(_ sender: Any) {\n \n submitBtn.isEnabled = false\n \n var flags = SCNetworkReachabilityFlags()\n SCNetworkReachabilityGetFlags(self.reachability!, &flags)\n \n //show load indicator\n loadIndicator.startAnimating()\n \n if self.isNetworkReachable(with: flags){\n \n \n Firestore.firestore().collection(\"UnclaimedOrders\").document(globOrderID.name).setData([\"restaurant\": globRest.name, \"orderdes\": globOrder.name, \"name\": globName.name, \"phonenum\" : globPhone.name, \"paymentmeth\" : globPayment.name, \"timeofdelivery\" : globTimeOfDelivery.name, \"dateofdelivery\": globDateOfDelivery.name, \"location\": globDestination.name, \"destination\": globDestDes.name])\n \n \n UserDefaults.standard.set(globOrderID.name, forKey: \"activeOrder\")\n UserDefaults.standard.set(globRest.name, forKey: \"activeOrderRest\")\n UserDefaults.standard.set(\"\\(globDateOfDelivery.name) \\(globTimeOfDelivery.name)\", forKey: \"activeOrderDate\")\n tickDownSlot(date: globDateOfDelivery.name)\n //timer for loading indicator\n Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(callback), userInfo: nil, repeats: false)\n \n \n } else{\n self.loadIndicator.stopAnimating()\n createAlert(title: \"NETWORK ERROR\", message: \"Please check wifi or cellular connection\")\n }\n \n \n }\n \n \n func createAlert (title:String, message: String){\n let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)\n \n alert.addAction(UIAlertAction(title: \"OK\", style: UIAlertAction.Style.default, handler: {(action) in\n alert.dismiss(animated: true, completion: nil)\n }))\n \n self.present(alert, animated: true, completion: nil)\n }\n \n func tickDownSlot(date: String){\n \n Firestore.firestore().collection(\"TimeSlots\").getDocuments() { (querySnapshot, err) in\n if let err = err {\n print(\"Error getting documents: \\(err)\")\n } else {\n for document in (querySnapshot?.documents)! {\n \n if document.documentID == date {\n \n document.reference.updateData([globTimeOfDelivery.name : document.get(globTimeOfDelivery.name) as! Int - 1])\n \n \n }\n }\n }\n }\n }\n \n \n \n}\n" }, { "alpha_fraction": 0.5302267074584961, "alphanum_fraction": 0.5384131073951721, "avg_line_length": 27.127273559570312, "blob_id": "f0d26f5ebd5a96b7faf69a0acb5f7bb9ef83704d", "content_id": "855a79b13bac27a6b6ff1c793e7e02d58ec31361", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1590, "license_type": "no_license", "max_line_length": 113, "num_lines": 55, "path": "/Lost-Island/Computer Game Uncompiled Code/WaterWellBuild.js", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "#pragma strict\n\nvar waterwellPrefab : Transform;\nvar player : GameObject;\n\nprivate var canBuild : boolean = true;\nvar check6 : GameObject;\nprivate var inventory : Inv;\nvar BtoB : GameObject;\n\nfunction Start()\n{\n GetComponent.<Renderer>().material.color = Color.green;\r\n GetComponent.<Renderer>().material.color.a = 0.5;\r\n inventory = GameObject.Find(\"FPSController\").GetComponent(Inv);\r\n}\r\n\r\nfunction OnTriggerEnter(Col : Collider)\r\n {\r\n if(Col.gameObject.tag == \"Terrain\" || Col.gameObject.tag == \"Tree\") \r\n\r\n {\r\n GetComponent.<Renderer>().material.color = Color.red;\r\n GetComponent.<Renderer>().material.color.a = 0.5;\r\n canBuild = false;\r\n }\r\n }\r\n\r\n\r\n function OnTriggerExit(Col : Collider)\r\n {\r\n if(Col.gameObject.tag == \"Terrain\" || Col.gameObject.tag == \"Tree\") \r\n\r\n {\r\n GetComponent.<Renderer>().material.color = Color.green;\r\n GetComponent.<Renderer>().material.color.a = 0.5;\r\n canBuild = true;\r\n }\r\n }\r\n\r\n\r\n function Update()\r\n {\r\n if(Input.GetKeyDown(\"b\") && canBuild == true)\r\n {\r\n \r\n Instantiate(waterwellPrefab, player.transform.position + Vector3(0, 0, 10), Quaternion.identity);\r\n player.GetComponent(Crafting).waterWell.SetActive(false);\r\n \r\n check6.SetActive(true);\r\n inventory.waterwellCount ++;\r\n BtoB.SetActive(false);\r\n \r\n }\r\n }" }, { "alpha_fraction": 0.47999998927116394, "alphanum_fraction": 0.5014634132385254, "avg_line_length": 14.671875, "blob_id": "1e0a6b2113c03b6e4fe7b51a7be9e3511a1720db", "content_id": "7cf98ad7973b348da8aebb5cebcf837cc64116d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1027, "license_type": "no_license", "max_line_length": 89, "num_lines": 64, "path": "/Lost-Island/Computer Game Uncompiled Code/Text#2.js", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "#pragma strict\nvar text1 : GameObject;\nvar text2 : GameObject;\nvar text3 : GameObject;\nvar text4 : GameObject;\nvar text5 : GameObject;\n\n\n//var Text1 : UI.Text;\\\n\nvar someText : UI.Text;\n\nvar calm : boolean = true;\nvar x : int = 0;\n\n\n\nprivate var seq : int = 1;\n\n\n\n\n\nprivate var TC : RayCastChop;\nprivate var inventory : Inv;\n\n\n\nfunction Start () {\n \n someText.text = \"sup\";\n \n\n}\n\n\nfunction Update () {\n\n if(calm == true)\n {\n if(x == 0)\r\n {\r\n someText.text = \"You can Pick Up bottles to fill them with water at a well.\";\r\n\r\n }\r\n\r\n else if (x == 1000)\r\n {\r\n someText.text = \"Crafting a campfire will allow you to cook raw meat.\";\r\n }\r\n else if (x == 2000)\r\n {\r\n someText.text = \"You can press \" + '\"i\"' + \" to open the inventory.\";\r\n }\r\n else if (x == 3000)\r\n {\r\n someText.text = \"You can eat coconuts to restore some hunger.\";\r\n x = -1;\r\n }\r\n x++;\r\n }\n\n \n}\n\n\n" }, { "alpha_fraction": 0.522835910320282, "alphanum_fraction": 0.5284121036529541, "avg_line_length": 27.530303955078125, "blob_id": "142843e7e0bda3982c56d3f3b28ae61ebf6ce78f", "content_id": "50103a97591b64866bd533cedf846639e3e14a44", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 3767, "license_type": "no_license", "max_line_length": 149, "num_lines": 132, "path": "/Deliver-Lake-Powell-Startup/DelivererTab/OTPViewController.swift", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "//\n// OTPViewController.swift\n// DeliverPage\n//\n// Created by Leon Weingartner on 6/21/20.\n// Copyright © 2020 Leon Weingartner. All rights reserved.\n//\n\nimport UIKit\nimport Firebase\nimport FirebaseFirestore\n\nclass OTPViewController: UIViewController {\n\n\n @IBOutlet weak var passField: UITextField!\n @IBOutlet weak var passCheckLabel: UILabel!\n var pass: String = \"1112\"\n \n private func setupNavigationBarItems() {\n \n let titleImageView = UIImageView(image: #imageLiteral(resourceName: \"Deliver Logo\"))\n titleImageView.frame = CGRect(x: 0, y: 0, width: 34, height: 34)\n titleImageView.contentMode = .scaleAspectFit\n let widthConstraint = titleImageView.widthAnchor.constraint(equalToConstant: 120)\n let heightConstraint = titleImageView.heightAnchor.constraint(equalToConstant: 48)\n heightConstraint.isActive = true\n widthConstraint.isActive = true\n navigationItem.titleView = titleImageView\n \n \n }\n \n override func viewDidLoad() {\n super.viewDidLoad()\n \n setupNavigationBarItems()\n \n passField.becomeFirstResponder()\n passField.text = \"\"\n passCheckLabel.text = \"\"\n \n \n \n let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: \"dismissKeyboard\")\n \n view.addGestureRecognizer(tap)\n \n let toolBar = UIToolbar()\n toolBar.sizeToFit()\n \n let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)\n \n let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: self, action: #selector(self.doneClicked))\n \n toolBar.setItems([flexibleSpace, doneButton], animated: false)\n \n passField.inputAccessoryView = toolBar\n \n //listen for keyboard events\n \n \n }\n \n @objc func doneClicked() {\n view.endEditing(true)\n \n if passField.text == pass {\n passCheckLabel.text = \"\"\n \n //perform segue\n performSegue(withIdentifier: \"unclaimedOrderSegue\", sender: nil)\n \n }else{\n passCheckLabel.text = \"Invalid ID\"\n passField.text = \"\"\n passField.becomeFirstResponder()\n }\n \n \n \n //check if password is correct\n \n }\n \n func findCode(){\n \n \n \n Firestore.firestore().collection(\"DelivererPasscode\").getDocuments() { (querySnapshot, err) in\n if let err = err {\n print(\"Error getting documents: \\(err)\")\n } else {\n for document in (querySnapshot?.documents)! {\n \n let dict = document.data()\n \n \n for(key,value) in dict{\n if key == \"code\" {\n self.pass = value as! String\n }\n }\n }\n }\n }\n }\n \n \n override func viewWillAppear(_ animated: Bool) {\n findCode()\n passCheckLabel.text = \"\"\n passField.text = \"\"\n passField.becomeFirstResponder()\n //tf1.becomeFirstResponder()\n }\n \n \n \n @objc func dismissKeyboard() {\n //Causes the view (or one of its embedded text fields) to resign the first responder status.\n view.endEditing(true)\n }\n \n \n \n \n \n \n\n\n}\n" }, { "alpha_fraction": 0.68660968542099, "alphanum_fraction": 0.6951566934585571, "avg_line_length": 12.5, "blob_id": "79fbcd0c03a4db50865bdfa1713d85a98587ee9c", "content_id": "18287525a341461277177f0f0f6a986b24086d1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 351, "license_type": "no_license", "max_line_length": 32, "num_lines": 26, "path": "/Deliver-Lake-Powell-Startup/Podfile", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "platform :ios, '10.0'\n\ntarget 'DeliverPage' do\n use_frameworks!\n\n # Pods for DeliverPage\n\npod 'iOSDropDown'\npod 'Firebase/Core'\npod 'Firebase/Auth'\npod 'Firebase/Firestore'\npod 'SideMenu'\n\n\n\n\n target 'DeliverPageTests' do\n inherit! :search_paths\n # Pods for testing\n end\n\n target 'DeliverPageUITests' do\n # Pods for testing\n end\n\nend\n" }, { "alpha_fraction": 0.6012773513793945, "alphanum_fraction": 0.6268247961997986, "avg_line_length": 21.36170196533203, "blob_id": "5fd6776b12d569dd6a3555e2cd747dc7811f42d5", "content_id": "ca79bfb0974b53062256076aefcd2cdd6fd3c2a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1098, "license_type": "no_license", "max_line_length": 95, "num_lines": 47, "path": "/Lost-Island/Computer Game Uncompiled Code/PigController.js", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "#pragma strict\r\n\r\nvar pigHealth : int = 5;\r\n\r\nvar pork : Transform;\r\nvar pig : GameObject;\r\n\r\nvar speed : int = 8;\r\nprivate var inventory : Inv;\r\n\r\nfunction Start ()\r\n{\r\n inventory = GameObject.Find(\"FPSController\").GetComponent(Inv);\r\n pig = this.gameObject;\r\n GetComponent.<Rigidbody>().isKinematic = true;\r\n\r\n}\r\n\r\nfunction Update()\r\n{\r\n if(pigHealth <=0)\r\n {\r\n GetComponent.<Rigidbody>().isKinematic = false;\r\n GetComponent.<Rigidbody>().AddForce(transform.forward * speed);\r\n DestroyPig();\r\n \r\n\r\n }\r\n}\r\n\r\nfunction DestroyPig()\r\n{\r\n \r\n //Debug.Log (\"pig should die\");\r\n yield WaitForSeconds(1);\r\n Destroy(pig);\r\n\r\n var position : Vector3 = Vector3(Random.Range(-1.0, 1.0), 0, Random.Range(-1.0, 1.0));\r\n Instantiate(pork, pig.transform.position + Vector3(0,0,0) + position, Quaternion.identity);\r\n Instantiate(pork, pig.transform.position + Vector3(0,0,2) + position, Quaternion.identity);\r\n Instantiate(pork, pig.transform.position + Vector3(0,0,4) + position, Quaternion.identity);\r\n inventory.Pkills += 1;\r\n\r\n\r\n\r\n\r\n}" }, { "alpha_fraction": 0.5433255434036255, "alphanum_fraction": 0.5644028186798096, "avg_line_length": 15.423076629638672, "blob_id": "13eaf78e90d305c626bcf07f5ee9590930022e95", "content_id": "92e78bb7291538036388a74edc29fdade27bc39f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 428, "license_type": "no_license", "max_line_length": 54, "num_lines": 26, "path": "/Deliver-Lake-Powell-Startup/DeliverPage/Restaurant.swift", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "//\n// Restaurant.swift\n// DeliverPage\n//\n// Created by Leon Weingartner on 6/20/20.\n// Copyright © 2020 Leon Weingartner. All rights reserved.\n//\n\nimport Foundation\nimport UIKit\nclass Restaurant {\n var image: UIImage\n var title: String\n var link: String\n \n \n init(image: UIImage, title: String, link: String){\n self.image = image\n self.title = title\n self.link = link\n \n \n }\n \n \n}\n" }, { "alpha_fraction": 0.7856603860855103, "alphanum_fraction": 0.796981155872345, "avg_line_length": 87.26667022705078, "blob_id": "5743a749988555c00ab065e3c11661869e25438b", "content_id": "8c7f749f324bb5abea63e588f7a0241fbf1b8e9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 1325, "license_type": "no_license", "max_line_length": 280, "num_lines": 15, "path": "/Family-Fun-Entertainment-Center/Family Fun Entertainment Center App/README.txt", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "\nThis project is for the desktop programming category - FBLA.\nThe user interface should be simple to navigate, but instructions are provided in the help window.\nThe project was created using Microsoft Visual Studio 2015 Enterprise, and no templates were used. The project code can be located as pdf files in the folder.\nNote that all information is saved on a Microsoft Sql Server Database, so an internet connection is required to save and edit information.\n\nSystem Requirements:\nBest bet is to run on Windows 8 or Windows 10, but Windows 7 should work as well.\nHave at least 65 mb of RAM availiable\nA processor capable of running a web browser should be sufficient enough.\nAn internet connection, if you are getting problems with saving data, your firewall might be blocking the app\nIf the app will not run at all, the most likely reason would be your version of .NET is too old. To download the latest .NET, go to https://www.microsoft.com/en-us/download/confirmation.aspx?id=49981\n\nTo Run the app:\nOpen the FEC_Project_Weingartner folder\nrun the FEC.application file, then click install. The setup file should work too, they seem to do the same thing. This should just run the program and and will not install anything on your machine. To completley remove the application, just close and delete the project folder.\n" }, { "alpha_fraction": 0.5468509793281555, "alphanum_fraction": 0.557603657245636, "avg_line_length": 16.405405044555664, "blob_id": "525f4adbe0d69ee2b220833381bfcd1dc8109c47", "content_id": "d5c84a7757583139e7e80acd539d0695fe56d238", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 653, "license_type": "no_license", "max_line_length": 130, "num_lines": 37, "path": "/Lost-Island/Computer Game Uncompiled Code/Trig#1.js", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "#pragma strict\n\nvar played = false;\nvar trig = false;\nprivate var Obj : Inv;\n\nvar sound: AudioClip;\n\nfunction Start () {\n\n}\n\nfunction OnTriggerEnter (other : Collider)\n {\n trig = true;\r\n }\n\n function Update () {\n Obj = GameObject.Find(\"FPSController\").GetComponent(Inv);\n if(trig == true) //&& Obj.kills >= 5 && Obj.Pkills >= 3 && Obj.wood >=10 && Obj.campfireCount >= 1 && Obj.waterwellCount >= 1)\n {\n\n PlaySound();\r\n Application.LoadLevel(2);\t\t\t\t\n \r\n }\n \n}\n\nfunction PlaySound()\n{\n if(!played)\r\n {\r\n played = true;\r\n GetComponent.<AudioSource>().PlayOneShot(sound);\r\n }\r\n}" }, { "alpha_fraction": 0.6302040815353394, "alphanum_fraction": 0.663673460483551, "avg_line_length": 27.214284896850586, "blob_id": "72fc5222a63523e16410c33863ebb70f5822f7db", "content_id": "64fe4eca0cc8a65cdbd0d3994d43722a9aa1cbaf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1227, "license_type": "no_license", "max_line_length": 98, "num_lines": 42, "path": "/Lost-Island/Computer Game Uncompiled Code/RockController.js", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "#pragma strict\r\n\r\nvar rockHealth : int = 8;\r\n\r\nvar stone : Transform;\r\nvar rock : GameObject;\r\n\r\nvar speed : int = 8;\r\n\r\nfunction Start ()\r\n{\r\n rock = this.gameObject;\r\n GetComponent.<Rigidbody>().isKinematic = true;\r\n\r\n}\r\n\r\nfunction Update()\r\n{\r\n if(rockHealth <=0)\r\n {\r\n GetComponent.<Rigidbody>().isKinematic = false;\r\n GetComponent.<Rigidbody>().AddForce(transform.forward * speed);\r\n Destroyrock();\r\n\r\n }\r\n}\r\n\r\nfunction Destroyrock()\r\n{\r\n yield WaitForSeconds(1);\r\n Destroy(rock);\r\n\r\n var position : Vector3 = Vector3(Random.Range(-1.0, 1.0), 0, Random.Range(-1.0, 1.0));\r\n Instantiate(stone, rock.transform.position + Vector3(0,0,0) + position, Quaternion.identity);\r\n Instantiate(stone, rock.transform.position + Vector3(0,0,3) + position, Quaternion.identity);\r\n Instantiate(stone, rock.transform.position + Vector3(0,0,6) + position, Quaternion.identity);\r\n Instantiate(stone, rock.transform.position + Vector3(2,0,9) + position, Quaternion.identity);\r\n Instantiate(stone, rock.transform.position + Vector3(2,0,12) + position, Quaternion.identity);\r\n Instantiate(stone, rock.transform.position + Vector3(2,0,15) + position, Quaternion.identity);\r\n\r\n\r\n}" }, { "alpha_fraction": 0.454485148191452, "alphanum_fraction": 0.4990711212158203, "avg_line_length": 19.044692993164062, "blob_id": "fa2b263d766a4a2ddb9b7f5c1e2abef4ab8fa2f3", "content_id": "bfb2d6d9fead61b7c45ce75002805ae6030eb29d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 7538, "license_type": "no_license", "max_line_length": 114, "num_lines": 358, "path": "/Lost-Island/Computer Game Uncompiled Code/Inv.js", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "#pragma strict\r\n\r\nvar menuSkin : GUISkin;\r\n\r\nvar wood : int = 0;\r\nvar stone : int = 0;\r\nvar metal : int = 0;\r\nvar thatch : int = 0;\r\n\r\n\r\n\r\nvar a : boolean = false;\r\nvar b : boolean = false;\r\nvar c : boolean = false;\r\nvar d : boolean = false;\r\nvar e : boolean = false;\r\nvar f1 : boolean = false;\r\n\r\nvar g : boolean = false;\r\nvar h : boolean = false;\r\nvar i : boolean = false;\r\nvar trig : GameObject;\r\nvar trig2 : GameObject;\r\n\r\nvar woodCount : int = 0;\r\nvar bandageCount : int = 0;\r\nvar campfireCount : int = 0;\r\nvar waterwellCount : int = 0;\r\n\r\nvar bridge : GameObject;\r\n\r\nvar sound : AudioClip;\r\n\r\nvar kills : int = 0;\r\nvar Pkills : int = 0;\r\n\r\nvar pork : int = 0;\r\nvar cookedPork : int = 0;\r\n\r\nvar coconut : int = 0;\r\n\r\nvar bottle : int = 0;\r\nvar bottledWater : int = 0;\r\n\r\nvar bandage : int = 0;\r\n\r\nvar check1 : GameObject;\r\nvar check2 : GameObject;\r\nvar check3 : GameObject;\r\nvar check4 : GameObject;\r\n\r\nvar check5 : GameObject;\r\nvar check6 : GameObject;\r\nvar check7 : GameObject;\r\n\r\nvar finishGUI : GameObject;\r\nvar finishGUI2 : GameObject;\r\n\r\n\r\n//var script : FirstPersonController;\r\n\r\nprivate var showGUI : boolean = false;\r\n\r\n//private var playerGUI : PlayerGUI;\r\n\r\nvar minimumVal : int = 0;\r\n\r\nprivate var craft : Crafting;\r\nprivate var playerGUI : PlayerGUI;\r\nplayerGUI = GameObject.Find(\"FPSController\").GetComponent(PlayerGUI);\r\n//craft - GameObject.Find(\"FPSController\").GetComponent(Crafting);\r\nfunction Start()\r\n{\r\n \r\n}\r\n\r\nfunction Update ()\r\n\r\n\r\n{\r\n\r\n\r\n if(wood <= 0)\r\n {\r\n wood = minimumVal;\r\n }\r\n\r\n if(stone <= 0)\r\n {\r\n stone = minimumVal;\r\n }\r\n\r\n if(metal <= 0)\r\n {\r\n metal = minimumVal;\r\n }\r\n \r\n if(thatch <= 0)\r\n {\r\n thatch = minimumVal;\r\n }\r\n \r\n if(pork <= 0)\r\n {\r\n pork = minimumVal;\r\n }\r\n \r\n if(cookedPork <= 0)\r\n {\r\n cookedPork = minimumVal;\r\n }\r\n \r\n if(bottle <= 0)\r\n {\r\n bottle = minimumVal;\r\n }\r\n\r\n if(bottledWater <= 0)\r\n {\r\n bottledWater = minimumVal;\r\n }\r\n\r\n if(bandage <= 0)\r\n {\r\n bandage = minimumVal;\r\n }\r\n\r\n if(coconut<= 0)\r\n {\r\n coconut = minimumVal;\r\n }\r\n if(kills<= 0)\r\n {\r\n kills = minimumVal;\r\n }\r\n \r\n if(Input.GetKeyDown(\"i\"))\r\n {\r\n showGUI = !showGUI;\r\n \r\n }\r\n //objectives\r\n\r\n if(kills >= 5)\r\n {\r\n check1.SetActive(true);\r\n a = true;\r\n \r\n \r\n }\r\n\r\n if(Pkills >= 3)\r\n {\r\n check2.SetActive(true);\r\n b = true;\r\n }\r\n \r\n if(woodCount >= 10)\r\n {\r\n check3.SetActive(true);\r\n c = true;\r\n\r\n }\r\n if(bandageCount >= 6)\r\n {\r\n check4.SetActive(true);\r\n d = true;\r\n }\r\n if(campfireCount >= 1)\r\n {\r\n e = true;\r\n }\r\n if(waterwellCount >= 1)\r\n {\r\n f1 = true;\r\n }\r\n if(a == true && b == true && c == true && d == true && e == true && f1 == true)\r\n {\r\n trig.SetActive(true);\r\n finishGUI.SetActive(true);\r\n }\r\n\r\n //objectives level 3\r\n if(bandageCount >= 5)\r\n {\r\n Debug.Log(\"Hommie up in here brah\");\r\n check5.SetActive(true);\r\n g = true;\r\n\r\n }\r\n if(kills >= 8)\r\n {\r\n check6.SetActive(true);\r\n h = true;\r\n }\r\n if(g == true && h == true && i == true)\r\n {\r\n trig2.SetActive(true);\r\n finishGUI2.SetActive(true);\r\n \r\n \r\n }\r\n \r\n \r\n\r\n if(showGUI == true)\r\n {\r\n\r\n (GameObject.FindWithTag(\"Player\").GetComponent(\"FirstPersonController\") as MonoBehaviour).enabled = false;\r\n (GameObject.FindWithTag(\"Axe\").GetComponent(\"idletoslash\")as MonoBehaviour).enabled = false;\r\n \r\n }\r\n\r\n\r\n if(showGUI == false)\r\n {\r\n \r\n (GameObject.FindWithTag(\"Player\").GetComponent(\"FirstPersonController\") as MonoBehaviour).enabled = true;\r\n (GameObject.FindWithTag(\"Axe\").GetComponent(\"idletoslash\")as MonoBehaviour).enabled = true;\r\n }\r\n\r\n\r\n}\r\n\r\nfunction OnGUI()\r\n{\r\n if(showGUI == true)\r\n {\r\n (GameObject.FindWithTag(\"Player\").GetComponent(\"FirstPersonController\") as MonoBehaviour).enabled = false;\r\n (GameObject.FindWithTag(\"Axe\").GetComponent(\"idletoslash\")as MonoBehaviour).enabled = false;\r\n \r\n\r\n // Cursor.visible = true;\r\n GUI.skin = menuSkin;\r\n GUI.BeginGroup(new Rect(Screen.width / 2 - 150, Screen.height / 2 - 450 , 300, 300));\r\n GUI.Box(Rect(0, 0, 300, 300), \"Inventory\");\r\n \r\n \r\n \r\n \r\n //Resources collected\r\n GUI.Label(Rect(10, 50, 50, 50), \"Wood\");\r\n GUI.skin.box.fontSize=13;\r\n GUI.Box(Rect(60, 50, 20, 20), \"\" + wood);\r\n\r\n GUI.Label(Rect(90, 50, 50, 50), \"Stone\");\r\n GUI.Box(Rect(130, 50, 20, 20), \"\" + stone);\r\n\r\n GUI.Label(Rect(160, 50, 50, 50), \"Metal\");\r\n GUI.Box(Rect(200, 50, 20, 20), \"\" + metal);\r\n\r\n GUI.Label(Rect(225, 50, 50, 50), \"Thatch\");\r\n GUI.Box(Rect(270, 50, 20, 20), \"\" + thatch);\r\n // Empty\r\n\r\n GUI.Label(Rect(10, 130, 50, 50), \"Pork\");\r\n GUI.Box(Rect(60, 130, 20, 20), \"\" + pork);\r\n\r\n GUI.Label(Rect(10, 150, 50, 50), \"Bottle\");\r\n GUI.Box(Rect(60, 150, 20, 20), \"\" + bottle);\r\n\r\n GUI.Label(Rect(100, 100, 100, 50), \"Enemy kills\");\r\n GUI.Box(Rect(180, 100, 20, 20), \"\" + kills);\r\n //Edable Items\r\n GUI.Label(Rect(10, 190, 50, 50), \"C.Pork\");\r\n GUI.Box(Rect(60, 190, 20, 20), \"\" + cookedPork);\r\n if(GUI.Button(Rect(100, 190, 100, 20), \"Eat C.Pork?\"))\r\n {\r\n if(cookedPork >= 1)\r\n {\r\n cookedPork--;\r\n Eat();\r\n \r\n }\r\n }\r\n\r\n GUI.Label(Rect(10, 210, 50, 50), \"B.Water\");\r\n GUI.Box(Rect(60, 210, 20, 20), \"\" + bottledWater);\r\n if(GUI.Button(Rect(100, 210, 100, 20), \"Drink Water?\"))\r\n {\r\n if(bottledWater >= 1)\r\n {\r\n bottledWater--;\r\n Drink();\r\n }\r\n }\r\n\r\n GUI.Label(Rect(10, 240, 50, 50), \"Heal\");\r\n GUI.Box(Rect(60, 240, 20, 20), \"\" + bandage);\r\n if(GUI.Button(Rect(100, 240, 100, 20), \"Use Bandage?\"))\r\n {\r\n if(bandage >= 1)\r\n {\r\n bandage--;\r\n Heal();\r\n }\r\n }\r\n\r\n GUI.Label(Rect(10, 270, 50, 50), \"Coconut\");\r\n GUI.Box(Rect(60, 270, 20, 20), \"\" + coconut);\r\n if(GUI.Button(Rect(100, 270, 100, 20), \"Eat Coconut?\"))\r\n {\r\n if(coconut >= 1)\r\n {\r\n coconut--;\r\n Eat1();\r\n }\r\n }\r\n\r\n\r\n \r\n GUI.EndGroup();\r\n\r\n\r\n }\r\n if(showGUI == false)\r\n {\r\n (GameObject.FindWithTag(\"Player\").GetComponent(\"FirstPersonController\") as MonoBehaviour).enabled = true;\r\n (GameObject.FindWithTag(\"Axe\").GetComponent(\"idletoslash\")as MonoBehaviour).enabled = true;\r\n }\r\n //Cursor.visible = false;\r\n }\r\n\r\n\r\nfunction Eat()\r\n{\r\n playerGUI.hungerBarDisplay += .2;\r\n \r\n}\r\n\r\nfunction Drink()\r\n{\r\n playerGUI.thirstBarDisplay += .2;\r\n}\r\n\r\nfunction Heal ()\r\n{\r\n playerGUI.healthBarDisplay += .25;\r\n}\r\n\r\nfunction Eat1()\r\n{\r\n playerGUI.hungerBarDisplay += .05;\r\n}\r\n\r\nfunction Reset()\r\n{\r\n wood = minimumVal;\r\n stone = minimumVal;\r\n metal = minimumVal;\r\n thatch = minimumVal;\r\n pork = minimumVal;\r\n cookedPork = minimumVal;\r\n bottle = minimumVal;\r\n bottledWater = minimumVal;\r\n bandage = minimumVal;\r\n coconut = minimumVal;\r\n}\r\n\r\n" }, { "alpha_fraction": 0.7019089460372925, "alphanum_fraction": 0.8179148435592651, "avg_line_length": 67.19999694824219, "blob_id": "5657901be22b7486568c491cc049c011a950203b", "content_id": "79c160c4c0d01edfbe593252984e01f26e94637e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 681, "license_type": "no_license", "max_line_length": 119, "num_lines": 10, "path": "/Family-Fun-Entertainment-Center/ReadMe.md", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "![ffec-flow-view](https://user-images.githubusercontent.com/35469554/35026048-003f20ce-fb06-11e7-9888-8d9d52610773.PNG)\n![homepage](https://user-images.githubusercontent.com/35469554/35026049-005482c0-fb06-11e7-9e0e-6a5281d0a562.PNG)\n\nThis project is a desktop application for a Family Fun Entertainment Center business.\nIt allows for an intuitive way to manage client funds and information print reports.\nThe best feature of this application is the SQL server functionality, so multiple locations can be integrated.\n\nSee the power point for a quick visual overview.\n\nTo look deeper into the application code and libraries itself, please see the 'README.txt' in application folder." }, { "alpha_fraction": 0.6437699794769287, "alphanum_fraction": 0.6581469774246216, "avg_line_length": 19.799999237060547, "blob_id": "e5e3f851704cd7dd9a095371623183027668255b", "content_id": "4deb4adf55cbd5d83fae7453c7fb8cdfd2f2fe79", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 627, "license_type": "no_license", "max_line_length": 49, "num_lines": 30, "path": "/Deliver-Lake-Powell-Startup/DeliverPage/ClaimedOrderCell.swift", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "//\n// ClaimedOrderCell.swift\n// DeliverPage\n//\n// Created by Leon Weingartner on 6/22/20.\n// Copyright © 2020 Leon Weingartner. All rights reserved.\n//\n\nimport Foundation\nimport UIKit\n\nclass ClaimedOrderCell: UITableViewCell{\n \n\n @IBOutlet weak var claimedByLabel: UILabel!\n \n @IBOutlet weak var restLabel: UILabel!\n \n @IBOutlet weak var nameLabel: UILabel!\n \n @IBOutlet weak var TODLabel: UILabel!\n \n \n func setOrder(order: Order){\n restLabel.text = order.restaurant\n nameLabel.text = order.name\n TODLabel.text = order.timeOfDelivery\n claimedByLabel.text = order.claimedBy\n }\n}\n\n\n" }, { "alpha_fraction": 0.6241469979286194, "alphanum_fraction": 0.8057742714881897, "avg_line_length": 23.41025733947754, "blob_id": "29f5e5743bec4777aca18e1c2dba06cd33591ffd", "content_id": "6ef0f107540b6ab874fc73320579f8d6a47d67b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1905, "license_type": "no_license", "max_line_length": 121, "num_lines": 78, "path": "/Deliver-Lake-Powell-Startup/ReadMe.md", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "Deliver Lake Powell Application Walkthrough\n\n\n\nhttps://user-images.githubusercontent.com/17464149/121131462-16492100-c7ed-11eb-93f0-5aad1056c102.mp4\n\nLaunch screen and food selection screens\n\n\n\n\nhttps://user-images.githubusercontent.com/17464149/121131510-26610080-c7ed-11eb-869f-719efbd8c6a2.mp4\n\nFood delivery status button (top right) and menu redirect implementation\n\n\n\n\nhttps://user-images.githubusercontent.com/17464149/121131536-2e20a500-c7ed-11eb-925e-a45888b305fc.mp4\n\nPlacing an order (example):\n\nLocation information:\n Name\n Phone number\n Dock name\n Description of location (slip #)\n\nFood Order:\n Description of food order\n\n\n\n\nhttps://user-images.githubusercontent.com/17464149/121131562-34af1c80-c7ed-11eb-9855-9679989c1620.mp4\n\nDelivery Information:\n Type of payment: Cash, Credit, Venmo\n Date of delivery: Month Day, Year\n Desired Time: available time slots for a given date (retrieved from database)\n \n\n\n\nhttps://user-images.githubusercontent.com/17464149/121131584-3d9fee00-c7ed-11eb-9235-1972e327965e.mp4\n\nDelivery View:\n Claim a placed order as a certified deliverer.\n\n\n\n\nhttps://user-images.githubusercontent.com/17464149/121131598-40024800-c7ed-11eb-8a2b-8b8df4e66ad0.mp4\n\n\n Customers delivery status will update accordingly and cannot place another order until original order has been completed\n\n\n\n\nhttps://user-images.githubusercontent.com/17464149/121131610-4264a200-c7ed-11eb-8b60-20851a220b0a.mp4\n\nDelivery View:\n Complete an order after successfully delivering the food. \n\n\n\n\nhttps://user-images.githubusercontent.com/17464149/121131705-67f1ab80-c7ed-11eb-8c36-e1747df14969.mp4\n\nDelivery status shows no more pending order and the customer can now place a new one. \n\n\n\n\nhttps://user-images.githubusercontent.com/17464149/121131750-750e9a80-c7ed-11eb-87cb-d74c4f4a4c0a.mp4\n\nUsing firebase I can view/edit orders, available delivery time slots, and deliverer passcodes\n\n" }, { "alpha_fraction": 0.5810019373893738, "alphanum_fraction": 0.598893940448761, "avg_line_length": 36.4878044128418, "blob_id": "ef287bba97fa93c693b934157845be92a5387e43", "content_id": "b394175c546d6f258e15ffcff2d76abaa4b1734a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 3075, "license_type": "no_license", "max_line_length": 332, "num_lines": 82, "path": "/Deliver-Lake-Powell-Startup/WelcomeViewController.swift", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "//\n// WelcomeViewController.swift\n// DeliverPage\n//\n// Created by Leon Weingartner on 6/26/20.\n// Copyright © 2020 Leon Weingartner. All rights reserved.\n//\n\nimport UIKit\n\nclass WelcomeViewController: UIViewController {\n\n @IBOutlet var holderView: UIView!\n let scrollView = UIScrollView()\n \n override func viewDidLoad() {\n super.viewDidLoad()\n \n // Do any additional setup after loading the view.\n }\n \n \n override func viewDidLayoutSubviews() {\n configure()\n }\n \n private func configure(){\n scrollView.frame = holderView.bounds\n holderView.addSubview(scrollView)\n \n let titles = [\"Welcome, we're Deliver Lake Powell. A locally owned and operated food delivery service!\", \"Choose from a variety of restaurants in Page, AZ\", \"Plan ahead and select a delivery date thats right for you\", \"Submit your order\", \"View your order status live! we'll contact you when your order is ready for pickup\"]\n \n for x in 0..<5 {\n let pageView = UIView(frame: CGRect(x: CGFloat(x)*(holderView.frame.size.width), y: 0, width: holderView.frame.size.width, height: holderView.frame.size.height))\n \n scrollView.addSubview(pageView)\n \n //title, image, button\n let label = UILabel(frame: CGRect(x: 10, y: 10, width: pageView.frame.size.width - 20, height: 120))\n \n let imageView = UIImageView(frame: CGRect(x: 10, y: 10+100, width: pageView.frame.size.width - 20, height: pageView.frame.size.height - 60 - 130 - 15))\n \n let button = UIButton(frame: CGRect(x: 10, y: pageView.frame.size.height - 60, width: pageView.frame.size.width - 20, height: 50))\n \n label.numberOfLines = 0\n label.textAlignment = .center\n label.font = UIFont(name: \"Avenir-Bold\", size: 16)\n pageView.addSubview(label)\n label.text = titles[x]\n \n imageView.contentMode = .scaleAspectFit\n imageView.image = UIImage(named: \"welcome_\\(x+1)\")\n pageView.addSubview(imageView)\n \n button.setTitleColor(.white, for: .normal)\n button.backgroundColor = .orange\n button.setTitle(\"Continue\", for: .normal)\n if x == 4 {\n button.setTitle(\"Get Started\", for: .normal)\n }\n button.addTarget(self, action: #selector(didTapButton), for: .touchUpInside)\n button.tag = x+1\n pageView.addSubview(button)\n }\n scrollView.contentSize = CGSize(width: holderView.frame.size.width*5, height: 0)\n scrollView.isPagingEnabled = true\n }\n \n @objc func didTapButton(_ button: UIButton){\n guard button.tag < 5 else{\n Core.shared.setIsNotNewUser()\n dismiss(animated: true, completion: nil)\n return\n }\n //scroll to next page\n scrollView.setContentOffset(CGPoint(x: holderView.frame.size.width*CGFloat(button.tag),y: 0), animated: true)\n }\n \n \n\n\n}\n" }, { "alpha_fraction": 0.5215481519699097, "alphanum_fraction": 0.529508650302887, "avg_line_length": 33.70476150512695, "blob_id": "545122c550450f2f5c6edab09f542ad70ff90852", "content_id": "6c437c292dcdcef61927fc521bb7fc7ca39cc817", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3643, "license_type": "no_license", "max_line_length": 239, "num_lines": 105, "path": "/Pair-Trading/ExperimentalScripts/AutoTrader.py", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "import click, json, time\nimport robin_stocks as rh\n\n\n\n\n#@click.group()\ndef main():\n print(\"main\")\n sharePrices = []\n buyList = []\n soldList = []\n content = open('config.json').read()\n config = json.loads(content)\n rh.login(config['username'], config['password']) \n getSharePrices(sharePrices, buyList)\n #buy stocks here\n #runLoop(sharePrices, buyList, soldList)\n historyDict = rh.stocks.get_stock_historicals('JPM', interval = '10minute', span = 'week', bounds = 'regular', info = None)\n\n #print(historyDict)\n\n #for quote in quotes:#print(\"{} | {}\".format(quote['symbol'], quote['ask_price']))\n\n for hist in historyDict:\n #print(\"{}\".format(float(hist['open_price'])))\n print(\"open price is {}, and close price is {}, with a percentage change of {}\".format(float(hist['open_price']), float(hist['close_price']), 100*(float(hist['close_price']) - float(hist['open_price']))/ float(hist['open_price'])))\n #print(\"{}\".format(100*(float(hist['close_price']) - float(hist['open_price']))/ float(hist['open_price'])))\n\n\n\n \n\ndef getSharePrices(sharePrices, buyList):\n print(\"Getting quotes for buylist\")\n with open('buylist') as w:\n\n symbols = w.read().splitlines()\n latestPrices = rh.get_latest_price(symbols)\n for i, price in enumerate(latestPrices, start = 0):\n print(\"{} | {}\".format(symbols[i], float(latestPrices[i])))\n sharePrices.append(float(latestPrices[i]))\n buyList.append(symbols[i])\n\n #print(sharePrices)\n\ndef runLoop(sharePrices, buyList, soldList):\n \n profitsList = []\n \n while True:\n\n with open('buylist') as w:\n\n symbols = w.read().splitlines()\n latestPrices = rh.get_latest_price(symbols)\n\n for i, price in enumerate(latestPrices, start=0):\n\n if(float(latestPrices[i]) <= (sharePrices[i])*(1-.005) and symbols[i] in buyList):\n print(\"sell {} at {}\".format(symbols[i], float(latestPrices[i])))\n print(\"loss of ${} - ${} = ${}\".format(float(latestPrices[i]), sharePrices[i], float(latestPrices[i])-sharePrices[i]))\n profitsList.append(float(latestPrices[i])-sharePrices[i])\n #sell\n\n soldList.append(symbols[i])\n buyList.remove(symbols[i])\n if not buyList:\n break\n \n elif(float(latestPrices[i]) >= (sharePrices[i])*(1+.0025) and symbols[i] in buyList):\n print(\"sell {} at {}\".format(symbols[i], float(latestPrices[i])))\n print(\"profit of ${} - ${} = ${}\".format(float(latestPrices[i]), sharePrices[i], float(latestPrices[i])-sharePrices[i]))\n profitsList.append(float(latestPrices[i])-sharePrices[i])\n #sell\n\n soldList.append(symbols[i])\n buyList.remove(symbols[i])\n if not buyList:\n break\n else:\n print(symbols[i])\n if symbols[i] in soldList:\n print(\"(SOLD)\")\n else:\n print(float(latestPrices[i]))\n print((sharePrices[i])*(1-.005))\n print((sharePrices[i])*(1+.0025))\n print(\"dont sell\")\n print(\"-------------\")\n\n if not buyList:\n break\n \n print(\"_____________________________________________________________-\")\n \n time.sleep(5)\n\n for profit in profitsList:\n total += profit\n \n print(total)\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.5501781702041626, "alphanum_fraction": 0.5774940848350525, "avg_line_length": 43.12663650512695, "blob_id": "a463a35507b4f82728c68f2459cdb9071c09db29", "content_id": "0ab141d94a6fe5ba604e272308e9279823de7b31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10104, "license_type": "no_license", "max_line_length": 186, "num_lines": 229, "path": "/Pair-Trading/ExperimentalScripts/PairTradingPrice.py", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "import click, json, time, math\nimport robin_stocks as rh\n\[email protected]()\ndef main():\n content = open('config.json').read()\n config = json.loads(content)\n rh.login(config['username'], config['password'])\n\n\[email protected](help='backtest')\[email protected]('--tick1', prompt = '1st ticker: ')\[email protected]('--tick2', prompt = '2nd ticker: ')\ndef backtest(tick1, tick2):\n historyDict1 = rh.stocks.get_stock_historicals(tick1, interval = 'day', span = 'year', bounds = 'regular', info = None)\n historyDict2 = rh.stocks.get_stock_historicals(tick2, interval = 'day', span = 'year', bounds = 'regular', info = None)\n list1 = []\n list2 = []\n buySellBack = False\n afterBuy = False\n highMargin = .05\n lowMargin = .03\n \n bsFrac = 1\n lastI = 0\n stockFrac = 0\n aDotb = 0\n normA = 0\n normB = 0\n bsCount = 0\n\n for i, hist in enumerate(historyDict1, start=0):\n\n list1.append(float(hist['close_price']))\n list2.append(float(historyDict2[i]['close_price']))\n \n #print(\"{} | {}\".format(100*(list1[i]-list2[i]), hist['begins_at']))\n # print(lowMargin*list1[i])\n # print(highMargin*list1[i])\n # print(list1[i]-stockFrac*list2[i])\n #print()\n\n if(hist['begins_at'] == '2020-01-27T00:00:00Z'): #'2020-01-27T00:00:00Z'\n #initial buy\n\n s1Amount = 1 \n s2Amount = float(hist['close_price'])/float(historyDict2[i]['close_price'])\n afterBuy = True\n s1 = s1Amount*float(hist['close_price'])\n s2 = s2Amount*float(historyDict2[i]['close_price'])\n initialBuy = s1+s2\n invested = s1+s2\n buyPow = 0\n stockFrac = float(hist['close_price'])/float(historyDict2[i]['close_price'])\n \n print(\"initial buy at: {}\".format(initialBuy))\n print(\"Bought {} shares of {} at the price of: {}\".format(s1Amount, tick1, hist['close_price']))\n print(\"Bought {} shares of {} at the price of: {}\".format(s2Amount, tick2, historyDict2[i]['close_price']))\n print(\"________________\")\n lastI = i\n \n \n if(list1[i]-stockFrac*list2[i] > highMargin*list1[i] and buySellBack == False and afterBuy == True):\n #sell from list1 buy from list2 \n list1Sold = True\n buySellBack = True\n s1 = s1Amount*float(hist['close_price'])-bsFrac*s1Amount*float(hist['close_price'])\n s2 = s2Amount*float(historyDict2[i]['close_price'])+bsFrac*s2Amount*float(historyDict2[i]['close_price'])\n invested = s1+s2\n buyPow += bsFrac*s1Amount*float(hist['close_price']) - bsFrac*s2Amount*float(historyDict2[i]['close_price']) \n \n print(hist['begins_at'])\n\n print(list1[i]-stockFrac*list2[i])\n print(highMargin*list1[i])\n print(\"Own {} shares of {} and {} shares of {}\".format(s1Amount-bsFrac*s1Amount, tick1, s2Amount+bsFrac*s2Amount,tick2))\n\n print(\"BUY & SELL\")\n print(\"Sold {} at the price of: {}\".format(tick1, hist['close_price']))\n print(\"Bought {} at the price of: {}\".format(tick2, historyDict2[i]['close_price']))\n print(\"Invested: {}\".format(invested))\n print(\"Buying Power: {}\".format(buyPow))\n print(\"Total: {}\".format(invested+buyPow))\n print(\"Profit: {}\".format(invested+buyPow-initialBuy))\n print(\"________________\")\n lastI = i\n bsCount += 1\n elif(list1[i]-stockFrac*list2[i] < - highMargin*list1[i] and buySellBack == False and afterBuy == True):\n #buy from list1 sell from list2\n list1Sold = False\n buySellBack = True\n s1 = s1Amount*float(hist['close_price'])+bsFrac*s1Amount*float(hist['close_price'])\n s2 = s2Amount*float(historyDict2[i]['close_price'])-bsFrac*s2Amount*float(historyDict2[i]['close_price'])\n invested = s1+s2\n buyPow += -bsFrac*s1Amount*float(hist['close_price']) + bsFrac*s2Amount*float(historyDict2[i]['close_price'])\n print(hist['begins_at'])\n\n print(list1[i]-stockFrac*list2[i])\n print(highMargin*list1[i])\n print(\"Own {} shares of {} and {} shares of {}\".format(s1Amount+bsFrac*s1Amount, tick1, s2Amount-bsFrac*s2Amount,tick2))\n\n print(\"BUY & SELL\")\n print(\"Bought {} at the price of: {}\".format(tick1, hist['close_price']))\n print(\"Sold {} at the price of: {}\".format(tick2, historyDict2[i]['close_price']))\n print(\"Invested: {}\".format(invested))\n print(\"Buying Power: {}\".format(buyPow))\n print(\"Total: {}\".format(invested+buyPow))\n print(\"Profit: {}\".format(invested+buyPow-initialBuy))\n print(\"________________\")\n lastI = i\n bsCount += 1\n elif(abs(list1[i]-stockFrac*list2[i]) < lowMargin*list1[i] and buySellBack == True and list1Sold == True and afterBuy == True):\n #buy and sell back \n buySellBack = False\n s1 = s1Amount*float(hist['close_price'])\n s2 = s2Amount*float(historyDict2[i]['close_price'])\n invested = s1+s2\n buyPow += -bsFrac*s1Amount*float(hist['close_price']) + bsFrac*s2Amount*float(historyDict2[i]['close_price'])\n print(hist['begins_at'])\n\n print(list1[i]-stockFrac*list2[i])\n print(lowMargin*list1[i])\n print(\"Own {} shares of {} and {} shares of {}\".format(s1Amount, tick1, s2Amount,tick2))\n\n print(\"BUY & SELL BACK\")\n print(\"Bought {} at the price of: {}\".format(tick1, hist['close_price']))\n print(\"Sold {} at the price of: {}\".format(tick2, historyDict2[i]['close_price']))\n print(\"Invested: {}\".format(invested))\n print(\"Buying Power: {}\".format(buyPow))\n print(\"Total: {}\".format(invested+buyPow))\n print(\"Profit: {}\".format(invested+buyPow-initialBuy))\n print(\"________________\")\n lastI = i\n bsCount += 1\n elif(abs(list1[i]-stockFrac*list2[i]) < lowMargin*list1[i] and buySellBack == True and list1Sold == False and afterBuy == True):\n #buy and sell back \n buySellBack = False\n s1 = s1Amount*float(hist['close_price'])\n s2 = s2Amount*float(historyDict2[i]['close_price'])\n invested = s1+s2\n buyPow += bsFrac*s1Amount*float(hist['close_price']) - bsFrac*s2Amount*float(historyDict2[i]['close_price']) \n print(hist['begins_at'])\n\n print(list1[i]-stockFrac*list2[i])\n print(lowMargin*list1[i])\n print(\"Own {} shares of {} and {} shares of {}\".format(s1Amount, tick1, s2Amount,tick2))\n\n print(\"BUY & SELL BACK\")\n print(\"Sold {} at the price of: {}\".format(tick1, hist['close_price']))\n print(\"Bought {} at the price of: {}\".format(tick2, historyDict2[i]['close_price']))\n print(\"Invested: {}\".format(invested))\n print(\"Buying Power: {}\".format(buyPow))\n print(\"Total: {}\".format(invested+buyPow))\n print(\"Profit: {}\".format(invested+buyPow-initialBuy))\n print(\"________________\")\n lastI = i\n bsCount += 1\n # print(s1Amount*float(historyDict1[i]['close_price']))\n # print(s2Amount*float(historyDict2[i]['close_price']))\n # print(s1Amount*float(historyDict1[i]['close_price'])+s2Amount*float(historyDict2[i]['close_price']))\n # print()\n\n print(\"total profit w/algorithm: {}\".format(invested+buyPow-initialBuy))\n print(\"annual growth w/algorithm: +%{}\".format(100*(invested+buyPow-initialBuy)/initialBuy))\n print(\"------------------\")\n print(\"total profit w/o algorithm: {}\".format(s1Amount*float(historyDict1[lastI]['close_price']) + s2Amount*float(historyDict2[lastI]['close_price']) - initialBuy))\n print(\"annual growth w/o algorithm: +%{}\".format(100*(s1Amount*float(historyDict1[lastI]['close_price']) + s2Amount*float(historyDict2[lastI]['close_price'])-initialBuy)/initialBuy))\n print()\n\n print(\"{}({})\".format(tick1,s1Amount))\n print(\"{}({})\".format(tick2,s2Amount))\n print(invested+buyPow-initialBuy)\n print(100*(invested+buyPow-initialBuy)/initialBuy)\n print(s1Amount*float(historyDict1[lastI]['close_price']) + s2Amount*float(historyDict2[lastI]['close_price']) - initialBuy)\n print(100*(s1Amount*float(historyDict1[lastI]['close_price']) + s2Amount*float(historyDict2[lastI]['close_price'])-initialBuy)/initialBuy)\n \n\n for i, hist in enumerate(historyDict1, start=0):\n\n list1.append(float(hist['close_price']))\n list2.append(float(historyDict2[i]['close_price']))\n aDotb += list1[i]*list2[i]\n normA += list1[i] ** 2\n normB += list2[i] ** 2\n\n \n #print(\"A dot B: {}, norm A: {}, norm B: {}\".format(aDotb, normA, normB))\n\n #print(\"the similarity correlation is: {}\".format(aDotb/(math.sqrt(normA * normB))))\n print(aDotb/(math.sqrt(normA * normB)))\n print(bsCount)\n\n \n \n\n\n\n \[email protected](help='similarity')\[email protected]('--tick1', prompt = '1st ticker: ')\[email protected]('--tick2', prompt = '2nd ticker: ')\ndef similarity(tick1, tick2):\n historyDict1 = rh.stocks.get_stock_historicals(tick1, interval = 'day', span = 'year', bounds = 'regular', info = None)\n historyDict2 = rh.stocks.get_stock_historicals(tick2, interval = 'day', span = 'year', bounds = 'regular', info = None)\n list1 = []\n list2 = []\n aDotb = 0\n normA = 0\n normB = 0\n\n for i, hist in enumerate(historyDict1, start=0):\n\n list1.append(float(hist['close_price']))\n list2.append(float(historyDict2[i]['close_price']))\n aDotb += list1[i]*list2[i]\n normA += list1[i] ** 2\n normB += list2[i] ** 2\n\n \n print(\"A dot B: {}, norm A: {}, norm B: {}\".format(aDotb, normA, normB))\n\n print(\"the similarity correlation is: {}\".format(aDotb/(math.sqrt(normA * normB))))\n\n\n \n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.5597845315933228, "alphanum_fraction": 0.5630161762237549, "avg_line_length": 24.31818199157715, "blob_id": "a3bbf95a866c55b5854eea6f1026dcf4e453a7d4", "content_id": "344c6cb17c8d7159f5284f5d4d86701bedb24ff0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 2786, "license_type": "no_license", "max_line_length": 142, "num_lines": 110, "path": "/Deliver-Lake-Powell-Startup/DelivererTab/UnclaimedViewController.swift", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "//\n// UnclaimedViewController.swift\n// DeliverPage\n//\n// Created by Leon Weingartner on 6/21/20.\n// Copyright © 2020 Leon Weingartner. All rights reserved.\n//\n\nimport UIKit\nimport Firebase\nimport FirebaseFirestore\n\nclass UnclaimedViewController: UIViewController {\n\n @IBOutlet weak var tableView: UITableView!\n \n \n \n \n @IBAction func unwindToUnclaimedList(_ sender: UIStoryboardSegue){}\n \n \n \n var orders: [Order] = []\n \n \n override func viewDidLoad() {\n super.viewDidLoad()\n \n //orders = createArray()\n globSelectOrderID.name = \"\"\n \n tableView.delegate = self\n tableView.dataSource = self\n \n \n \n\n // Do any additional setup after loading the view.\n }\n \n\n \n \n override func viewWillAppear(_ animated: Bool) {\n orders.removeAll()\n Firestore.firestore().collection(\"UnclaimedOrders\").getDocuments() { (querySnapshot, err) in\n if let err = err {\n print(\"Error getting documents: \\(err)\")\n } else {\n for document in (querySnapshot?.documents)! {\n let data = document.data()\n let restaurant = data[\"restaurant\"] as? String ?? \"Anonymous\"\n let name = data[\"name\"] as? String ?? \"Anonymous\"\n let tod = data[\"timeofdelivery\"] as? String ?? \"Anonymous\"\n let orderId = document.documentID\n let date = data[\"dateofdelivery\"] as? String ?? \"Anonymous\"\n \n let newOrder = Order(restaurant: restaurant, name: name, timeOfDelivery: tod, claimedBy: \"\", orderID: orderId, date: date)\n \n self.orders.append(newOrder)\n \n \n }\n self.tableView.reloadData()\n }\n }\n }\n \n \n \n \n \n }\nextension UnclaimedViewController: UITableViewDataSource, UITableViewDelegate{\n\nfunc tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {\n return orders.count\n}\n\n func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {\n let order = orders[indexPath.row]\n let cell = tableView.dequeueReusableCell(withIdentifier: \"OrderCell\") as! OrderCell\n \n cell.setOrder(order: order)\n \n return cell\n }\n \nfunc tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {\n \n tableView.deselectRow(at: indexPath, animated: true)\n globSelectOrderID.name = orders[indexPath.row].orderID \n performSegue(withIdentifier: \"moveToClaimedSegue\", sender: nil)\n \n \n \n \n \n}\n \n \n \n \n \n \n\n \n\n}\n" }, { "alpha_fraction": 0.6138763427734375, "alphanum_fraction": 0.6290430426597595, "avg_line_length": 42.083030700683594, "blob_id": "359adee6df83c46b3495dd87c9a45002e983c8fe", "content_id": "24173c7172df1937db44d275c143907ef43aae39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 11937, "license_type": "no_license", "max_line_length": 231, "num_lines": 277, "path": "/Deliver-Lake-Powell-Startup/UserTab/RestaurantPageViewController.swift", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "//\n// ViewControllerRestaurantPageViewController.swift\n// DeliverPage\n//\n// Created by Leon Weingartner on 6/20/20.\n// Copyright © 2020 Leon Weingartner. All rights reserved.\n//\n\nimport UIKit\nimport SafariServices\nimport Firebase\nimport FirebaseFirestore\n\nclass RestaurantPageViewController: UIViewController {\n\n @IBOutlet weak var tableView: UITableView!\n \n \n var restaurants: [Restaurant] = []\n var isAcitve: Bool = false\n \n let group = DispatchGroup()\n //var loadIndicator = UIActivityIndicatorView()\n \n\n \n private func setupNavigationBarItems() {\n \n let titleImageView = UIImageView(image: #imageLiteral(resourceName: \"Deliver Logo\"))\n titleImageView.frame = CGRect(x: 0, y: 0, width: 34, height: 34)\n titleImageView.contentMode = .scaleAspectFit\n let widthConstraint = titleImageView.widthAnchor.constraint(equalToConstant: 120)\n let heightConstraint = titleImageView.heightAnchor.constraint(equalToConstant: 48)\n heightConstraint.isActive = true\n widthConstraint.isActive = true\n navigationItem.titleView = titleImageView\n \n \n }\n \n \n override func viewWillAppear(_ animated: Bool) {\n super.viewWillAppear(animated)\n \n navigationController?.setNavigationBarHidden(false, animated: true)\n }\n \n override func viewDidLoad() {\n super.viewDidLoad()\n // activityIndicator()\n // loadIndicator.backgroundColor = .white\n //loadIndicator.stopAnimating()\n \n setupNavigationBarItems()\n \n \n globRest.name = \"\"\n globOrder.name = \"\"\n globName.name = \"\"\n globPhone.name = \"\"\n globPayment.name = \"\"\n globOrderID.name = \"\"\n globTimeOfDelivery.name = \"\"\n globDateOfDelivery.name = \"\"\n globDestDes.name = \"\"\n globDestination.name = \"\"\n globMenuLink.name = \"\"\n\n restaurants = createArray()\n \n tableView.delegate = self\n tableView.dataSource = self\n\n // Do any additional setup after loading the view.\n }\n \n \n func createArray() -> [Restaurant] {\n var tempRestaurants: [Restaurant] = []\n \n let rest1 = Restaurant(image: #imageLiteral(resourceName: \"o-1\"), title: \"Bird House $$\", link: \"https://www.birdhouseaz.com/\")\n let rest2 = Restaurant(image: #imageLiteral(resourceName: \"BigJohnsBBQ.jpg\"), title: \"Big John's Texas BBQ $$\", link: \"http://bigjohnstexasbbq.com/menus/pagelake-powell-restaurant-menu/\")\n let rest3 = Restaurant(image: #imageLiteral(resourceName: \"BlueBuddha_Youjeen_Cho\"), title: \"Blue Buddha $$\", link: \"https://bluebuddhasushilounge.com/menu\")\n let rest4 = Restaurant(image: #imageLiteral(resourceName: \"Bonkers_Markus_Winkler\"), title: \"Bonkers $$\", link: \"http://bonkerspageaz.com/menu.html\")\n let rest5 = Restaurant(image: #imageLiteral(resourceName: \"DDB\"), title: \"Dam Bar & Grille $$\", link: \"http://www.damplaza.com/images/images/menus/2020/DamBar_AllDay_Menu2020.pdf\")\n let rest6 = Restaurant(image: #imageLiteral(resourceName: \"Denny's_Zachary_Spears\"), title: \"Denny's $$\", link: \"https://www.dennys.com/food/\")\n let rest7 = Restaurant(image: #imageLiteral(resourceName: \"DarTai_Makrus_Winkler\"), title: \"Dara Thai Express $$\", link: \"https://zmenu.com/dara-thai-express-page-online-menu/\")\n let rest8 = Restaurant(image: #imageLiteral(resourceName: \"Dominos_brett_jordan\"), title: \"Domino's $$\", link: \"https://www.dominos.com/en/pages/order/menu#!/menu/category/viewall/\")\n let rest9 = Restaurant(image: #imageLiteral(resourceName: \"ElTapitio\"), title: \"El Tapitio $$\", link: \"https://tapatiorestaurants.com/\")\n let rest10 = Restaurant(image: #imageLiteral(resourceName: \"FiestaMexicana\"), title: \"Fiesta Mexicana $$\", link: \"https://fiestamexrest.com/dinner/\")\n let rest11 = Restaurant(image: #imageLiteral(resourceName: \"GlenSteakHouse_Loija_Nguyen\"), title: \"Glen Canyon Steak House $$\", link: \"http://places.singleplatform.com/glen-canyon-steak-house/menu?ref=google#menu_1658982\")\n let rest12 = Restaurant(image: #imageLiteral(resourceName: \"unnamed-2\"), title: \"Gone West $$\", link: \"http://www.gonewestfamilyrestaurant.com/menu.html\")\n let rest13 = Restaurant(image: #imageLiteral(resourceName: \"JackInTheBox\"), title: \"Jack In The Box $\", link: \"https://www.jackinthebox.com/food\")\n let rest14 = Restaurant(image: #imageLiteral(resourceName: \"LittleCeasers_Alan_Hardman\"), title: \"Little Caesars $\", link: \"https://littlecaesars.com/en-us/\")\n let rest15 = Restaurant(image: #imageLiteral(resourceName: \"McDonalds_Sepet\"), title: \"Mcdonald's $\", link: \"https://www.mcdonalds.com/us/en-us/full-menu.html\")\n let rest16 = Restaurant(image: #imageLiteral(resourceName: \"NemosFish\"), title: \"Nemo's Fish and Chips $$\", link: \"http://s3-media4.fl.yelpcdn.com/bphoto/wbccK6XJlHtfPy205vHHbg/o.jpg\")\n let rest17 = Restaurant(image: #imageLiteral(resourceName: \"PacosTacos_Tai's_Captures\"), title: \"Paco's Tacos $\", link: \"https://zmenu.com/pacos-tacos-page-online-menu/\")\n let rest18 = Restaurant(image: #imageLiteral(resourceName: \"unnamed-4\"), title: \"Pizza Hut $$\", link: \"https://www.pizzahut.com/index.php#/home\")\n let rest19 = Restaurant(image: #imageLiteral(resourceName: \"unnamed\"), title: \"R D's $$\", link: \"https://s3-media1.fl.yelpcdn.com/bphoto/6FsZYZLqbV0_jvlYa6cKBA/o.jpg\")\n \n let rest21 = Restaurant(image: #imageLiteral(resourceName: \"Slakers_Jake_Weirick\"), title: \"Slakers $$\", link: \"https://slackersqualitygrub.com/menu/\")\n let rest22 = Restaurant(image: #imageLiteral(resourceName: \"o-3\"), title: \"Sonic $\", link: \"https://www.sonicdrivein.com/menu\")\n let rest23 = Restaurant(image: #imageLiteral(resourceName: \"o\"), title: \"Starlite Diner $\", link: \"https://www.zomato.com/page-az/starlite-chinese-american-page/menu\")\n let rest24 = Restaurant(image: #imageLiteral(resourceName: \"State48_Andreas_M\"), title: \"State 48 Taver $$\", link: \"https://state48tavern.com/\")\n let rest25 = Restaurant(image: #imageLiteral(resourceName: \"steer\"), title: \"Steer89 $$\", link: \"https://steer89.com/wp-content/uploads/2018/06/Steer-89-Menu.pdf\")\n let rest26 = Restaurant(image: #imageLiteral(resourceName: \"Stroms_Jonas_Kakaroto\"), title: \"Strombolli’s Italian $$\", link: \"https://strombollisrestaurant.com/page/full-menu-page/\")\n let rest27 = Restaurant(image: #imageLiteral(resourceName: \"unnamed-3\"), title: \"Subway $\", link: \"https://www.subway.com/en-US/MenuNutrition/Menu\")\n let rest28 = Restaurant(image: #imageLiteral(resourceName: \"20191108-182629-largejpg\"), title: \"Sunset89 $$\", link: \"https://www.sunset89.com/menu\")\n let rest29 = Restaurant(image: #imageLiteral(resourceName: \"TacoBell\"), title: \"Taco Bell $\", link: \"https://www.tacobell.com/food\")\n \n \n \n tempRestaurants.append(rest2)\n tempRestaurants.append(rest1)\n tempRestaurants.append(rest3)\n tempRestaurants.append(rest4)\n tempRestaurants.append(rest5)\n tempRestaurants.append(rest6)\n tempRestaurants.append(rest7)\n tempRestaurants.append(rest8)\n tempRestaurants.append(rest9)\n tempRestaurants.append(rest10)\n tempRestaurants.append(rest11)\n tempRestaurants.append(rest12)\n tempRestaurants.append(rest13)\n tempRestaurants.append(rest14)\n tempRestaurants.append(rest15)\n tempRestaurants.append(rest16)\n tempRestaurants.append(rest17)\n tempRestaurants.append(rest18)\n tempRestaurants.append(rest19)\n \n tempRestaurants.append(rest21)\n tempRestaurants.append(rest22)\n tempRestaurants.append(rest23)\n tempRestaurants.append(rest24)\n tempRestaurants.append(rest25)\n tempRestaurants.append(rest26)\n tempRestaurants.append(rest27)\n \n tempRestaurants.append(rest28)\n tempRestaurants.append(rest29)\n \n \n \n \n \n \n return tempRestaurants\n }\n\n \n\n}\n\nextension RestaurantPageViewController: RestaurantCellDelegate{\n func didTapMenu(url: String) {\n let menuURL = URL(string: url)!\n let safariVC = SFSafariViewController(url: menuURL)\n present(safariVC, animated: true, completion: nil)\n }\n}\n\nextension RestaurantPageViewController: UITableViewDataSource, UITableViewDelegate {\n func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {\n return restaurants.count\n }\n \n func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {\n let restaurant = restaurants[indexPath.row]\n let cell = tableView.dequeueReusableCell(withIdentifier: \"RestaurantCell\") as! RestaurantCell\n let backgroundView = UIView()\n backgroundView.backgroundColor = UIColor.gray\n cell.selectedBackgroundView = backgroundView\n \n \n cell.setRestaurant(restaurant: restaurant)\n cell.delegate = self\n \n \n \n return cell\n }\n func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {\n tableView.deselectRow(at: indexPath, animated: true)\n let restaurant = restaurants[indexPath.row]\n isAcitve = false\n \n \n \n globRest.name = restaurant.title.replacingOccurrences(of: \"$\", with: \"\")\n globMenuLink.name = restaurant.link\n \n tableView.allowsSelection = false\n \n //start animating load indicator\n //loadIndicator.stopAnimating()\n\n \n \n fetchDataIsActive(coll: \"UnclaimedOrders\", doc: UserDefaults.standard.string(forKey: \"activeOrder\") ?? \"\")\n \n \n fetchDataIsActive(coll: \"ClaimedOrders\", doc: UserDefaults.standard.string(forKey: \"activeOrder\") ?? \"\")\n \n \n \n group.notify(queue: .main){\n \n print(self.isAcitve)\n \n tableView.allowsSelection = true\n if(self.isAcitve == true){\n self.createAlert(title: \"CANT CREATE ORDER\", message: \"You can't have more than one active order. Check your active orders page to view the status of your delivery\")\n }else{\n \n self.performSegue(withIdentifier: \"cellToOrder\", sender: nil)\n }\n }\n \n \n \n }\n \n \n func fetchDataIsActive(coll: String, doc: String){\n \n \n group.enter()\n\n \n Firestore.firestore().collection(coll).getDocuments() { (querySnapshot, err) in\n \n \n if let err = err {\n print(\"Error getting documents: \\(err)\")\n } else {\n \n for document in (querySnapshot?.documents)! {\n \n if document.documentID == doc {\n \n print(\"found it\")\n self.isAcitve = true \n \n }\n }\n \n \n self.group.leave()\n \n }\n }\n \n \n }\n \n @IBAction func unwindToOne(_sender: UIStoryboardSegue){}\n \n \n func createAlert (title:String, message: String){\n let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)\n \n alert.addAction(UIAlertAction(title: \"OK\", style: UIAlertAction.Style.default, handler: {(action) in\n alert.dismiss(animated: true, completion: nil)\n }))\n \n self.present(alert, animated: true, completion: nil)\n }\n \n \n\n \n \n \n \n}\n" }, { "alpha_fraction": 0.6479290127754211, "alphanum_fraction": 0.6612426042556763, "avg_line_length": 22.275861740112305, "blob_id": "9be815bb8397be0a094047f55643b3ef8d64c6d6", "content_id": "1aa3ba4b6b0cdf18ffe3d86f390a72760e62cf46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 677, "license_type": "no_license", "max_line_length": 49, "num_lines": 29, "path": "/Deliver-Lake-Powell-Startup/DeliverPage/global.swift", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "//\n// global.swift\n// DeliverPage\n//\n// Created by Leon Weingartner on 6/19/20.\n// Copyright © 2020 Leon Weingartner. All rights reserved.\n//\n\nimport Foundation\n\nclass Main {\n var name:String\n init(name:String) {\n self.name = name\n }\n}\nvar globRest = Main(name:\"\")\nvar globOrder = Main(name:\"\")\nvar globName = Main(name:\"\")\nvar globPhone = Main(name:\"\")\nvar globPayment = Main(name:\"\")\nvar globOrderID = Main(name:\"\")\nvar globSelectOrderID = Main(name:\"\")\nvar globalClaimedName = Main(name:\"\")\nvar globDateOfDelivery = Main(name:\"\")\nvar globTimeOfDelivery = Main(name:\"\")\nvar globDestination = Main(name:\"\")\nvar globDestDes = Main(name: \"\")\nvar globMenuLink = Main(name: \"\")\n\n" }, { "alpha_fraction": 0.6447507739067078, "alphanum_fraction": 0.6564157009124756, "avg_line_length": 18.64583396911621, "blob_id": "63fcc7085f09aad74fd6fd41589c34f27927d0a0", "content_id": "f5b331c249cecc9bab101b1a7fe271aefacddc95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 944, "license_type": "no_license", "max_line_length": 56, "num_lines": 48, "path": "/Deliver-Lake-Powell-Startup/DeliverPage/RestaurantCell.swift", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "//\n// RestaurantCell.swift\n// DeliverPage\n//\n// Created by Leon Weingartner on 6/20/20.\n// Copyright © 2020 Leon Weingartner. All rights reserved.\n//\n\nimport UIKit\nimport SafariServices\n\n\nprotocol RestaurantCellDelegate {\n func didTapMenu(url: String)\n}\n\nclass RestaurantCell: UITableViewCell{\n \n \n \n \n @IBOutlet weak var restaurantImageView: UIImageView!\n @IBOutlet weak var restaurantTitleLabel: UILabel!\n \n var delegate: RestaurantCellDelegate?\n var restItem: Restaurant!\n \n @IBAction func menuTapped(_ sender: Any) {\n delegate?.didTapMenu(url: restItem.link)\n }\n \n \n \n func setRestaurant(restaurant: Restaurant){\n restItem = restaurant\n restaurantImageView.image = restaurant.image\n restaurantTitleLabel.text = restaurant.title\n restaurantImageView.layer.cornerRadius = 8.0\n restaurantImageView.layer.masksToBounds = true\n \n }\n \n \n \n \n \n\n}\n" }, { "alpha_fraction": 0.4835452437400818, "alphanum_fraction": 0.4891548156738281, "avg_line_length": 24.594058990478516, "blob_id": "e7811fb3d1e1ac6594d09f1ba074393736ac89b0", "content_id": "d3191a8f4c8e2a60949de32dc8219d2b5280937f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2676, "license_type": "no_license", "max_line_length": 102, "num_lines": 101, "path": "/Lost-Island/Computer Game Uncompiled Code/RayCastChop.js", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "#pragma strict\n\nvar rayLength : int = 5;\n\nprivate var treeScript : TreeController;\nprivate var rockScript : RockController;\nprivate var metalScript : MetalController;\nprivate var pigScript : PigController;\nprivate var enemyScript : enemyController;\n\nvar count : int = 0;\n\nfunction Update()\n{\n var hit : RaycastHit;\r\n var fwd = transform.TransformDirection(Vector3.forward);\r\n\r\n if(Physics.Raycast(transform.position, fwd, hit, rayLength))\r\n {\r\n if(hit.collider.gameObject.tag == \"Tree\")\r\n {\r\n treeScript = GameObject.Find(hit.collider.gameObject.name).GetComponent(TreeController);\r\n \r\n\r\n if(Input.GetButtonDown(\"Fire1\") == true)\r\n {\r\n print(\"eagle has landed\");\r\n treeScript.treeHealth -=1;\r\n \r\n if(treeScript.treeHealth == 0)\r\n {\r\n // yield WaitForSeconds(5);\r\n count++;\r\n \r\n }\r\n }\r\n }\r\n\r\n\r\n\r\n\r\n if(hit.collider.gameObject.tag == \"rock\")\r\n {\r\n rockScript = GameObject.Find(hit.collider.gameObject.name).GetComponent(RockController);\r\n \r\n\r\n if(Input.GetButtonDown(\"Fire1\") == true)\r\n {\r\n print(\"eagle has landed\");\r\n rockScript.rockHealth -=1;\r\n \r\n }\r\n }\r\n\r\n\r\n\r\n if(hit.collider.gameObject.tag == \"metal\")\r\n {\r\n metalScript = GameObject.Find(hit.collider.gameObject.name).GetComponent(MetalController);\r\n \r\n\r\n if(Input.GetButtonDown(\"Fire1\") == true)\r\n {\r\n print(\"eagle has landed\");\r\n metalScript.metalHealth -=1;\r\n \r\n }\r\n }\r\n\r\n if(hit.collider.gameObject.tag == \"pig\")\r\n {\r\n pigScript = GameObject.Find(hit.collider.gameObject.name).GetComponent(PigController);\r\n Debug.Log(\"It knows the Script\");\r\n \r\n\r\n if(Input.GetButtonDown(\"Fire1\") == true)\r\n {\r\n print(\"eagle has landed\");\r\n pigScript.pigHealth -=1;\r\n \r\n }\r\n }\r\n\r\n if(hit.collider.gameObject.tag == \"enemy\")\r\n {\r\n enemyScript = GameObject.Find(hit.collider.gameObject.name).GetComponent(enemyController);\r\n Debug.Log(\"It knows the Script\");\r\n \r\n\r\n if(Input.GetButtonDown(\"Fire1\") == true)\r\n {\r\n print(\"eagle has landed\");\r\n enemyScript.enemyHealth -=1;\r\n \r\n }\r\n }\r\n\r\n\r\n\r\n }\r\n}\r\n\r\n" }, { "alpha_fraction": 0.6426116824150085, "alphanum_fraction": 0.6580756306648254, "avg_line_length": 21.384614944458008, "blob_id": "864675a24c92bde834db4b94ce01d973f6041215", "content_id": "19df41600585a70dd5e4565fbc3dc1368b019c74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 583, "license_type": "no_license", "max_line_length": 49, "num_lines": 26, "path": "/Deliver-Lake-Powell-Startup/DeliverPage/OrderCell.swift", "repo_name": "leon-weingartner/PublicFiles", "src_encoding": "UTF-8", "text": "//\n// OrderCell.swift\n// DeliverPage\n//\n// Created by Leon Weingartner on 6/21/20.\n// Copyright © 2020 Leon Weingartner. All rights reserved.\n//\n\nimport Foundation\nimport UIKit\n\nclass OrderCell: UITableViewCell{\n \n @IBOutlet weak var restLabel: UILabel!\n @IBOutlet weak var nameLabel: UILabel!\n @IBOutlet weak var TODLabel: UILabel!\n @IBOutlet weak var dateLabel: UILabel!\n \n \n func setOrder(order: Order){\n restLabel.text = order.restaurant\n nameLabel.text = order.name\n TODLabel.text = order.timeOfDelivery\n dateLabel.text = order.date\n }\n}\n" } ]
49
tincan39/Bot
https://github.com/tincan39/Bot
bc36eeecbc9ccf9cfb1f465ca9e25ad089307b4c
17a0ad693b8ba8a2ba690047c2b7404bc36a17c7
e3d51987d72ccb9c5b31320e205863ce05ecee81
refs/heads/master
2020-12-27T23:22:10.403598
2020-02-04T02:04:47
2020-02-04T02:04:47
238,102,758
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.769784152507782, "alphanum_fraction": 0.769784152507782, "avg_line_length": 33.75, "blob_id": "752dfbc982d68e1ee9e9b958e32f3a28179d8d6d", "content_id": "c0e0f918d7e164ece4a4120a782f0e4310b77a26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 139, "license_type": "no_license", "max_line_length": 75, "num_lines": 4, "path": "/README.md", "repo_name": "tincan39/Bot", "src_encoding": "UTF-8", "text": "# InfoBot\nA bot which extracts urls from user messages which can be accessed later. \n\nUse the $help command to access a list of commands.\n" }, { "alpha_fraction": 0.5789473652839661, "alphanum_fraction": 0.5951417088508606, "avg_line_length": 29.875, "blob_id": "1c5199f52bf7a616c232f0e13a71316e9fe8a860", "content_id": "8902d0b107327d9030a6a9f447f79f44741c0bf0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 741, "license_type": "no_license", "max_line_length": 74, "num_lines": 24, "path": "/urllist.py", "repo_name": "tincan39/Bot", "src_encoding": "UTF-8", "text": "class UrlList:\n\n def __init__(self):\n self.uList = []\n\n # adds a link to the list and removes the oldest one if it exceeds 500\n def add_elem(self, emb_list: list):\n if len(self.uList) > 500:\n self.uList.pop(0)\n self.uList.extend(emb_list)\n\n def last_5(self):\n return self.uList[0:5]\n\n # returns a specified number of urls\n def get_n_elem(self, num: int) -> list:\n if num > len(self.uList):\n raise IndexError(\"That number exceeds the amount of urls\")\n return self.uList[0:num]\n\n # returns urls by its extension type\n def get_by_ext(self, num: int, ext: str):\n val_links = [x for x in self.uList if x.endswith(ext)]\n return val_links[0:num]\n" }, { "alpha_fraction": 0.664550244808197, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 31.19318199157715, "blob_id": "d969ba61a18e946491cfc8beee1bd9280eccf4b2", "content_id": "fa7e341c773cbb731e91dd4f00b153d7e6dfa925", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2835, "license_type": "no_license", "max_line_length": 118, "num_lines": 88, "path": "/bot.py", "repo_name": "tincan39/Bot", "src_encoding": "UTF-8", "text": "import discord\nimport re\nfrom discord.ext import commands\nfrom urllist import UrlList\n\nurls = UrlList() # manages the urls\n\nhelp_msg = \"This discord bot extracts urls/links from user messages and these links\" \\\n \"be accessed easily via the bot.\\n\\n\" \\\n \"Commands:\\n\\n\" \\\n \"$last5links : \\n returns the last 5 urls/links sent on the server\\n\\n\" \\\n \"$getlinks number_of_links :\\n returns a specified amount of links if available. An error message is \" \\\n \"returned\" \\\n \"if there isn't\\n\\n\" \\\n \"$getlinktype number_of_links ext :\\n returns links based on the extension(e.g: .pdf). If the link\" \\\n \"amount exceeds what is available, then whatever is available is returned\"\nclient = commands.Bot(command_prefix='$')\nclient.remove_command('help') # removes the default help command\n\n\n# function that displays a list's contents in a single string\ndef list_to_str(url_list):\n message = ''\n for url in url_list:\n message += url + '\\n\\n'\n return message\n\n\[email protected] # variable is client, so decorator must be client.____\nasync def on_ready(): # causes the bot to go online\n print('bot is ready.')\n\n\n# reads messages and extracts links\[email protected]\nasync def on_message(message):\n if not message.author.bot: # ignores messages from bots\n msg = message.content\n url_list = re.findall(r'(https?://\\S+)', msg) # extracts all links into a list\n urls.add_elem(url_list)\n await client.process_commands(message)\n\n\[email protected](name='getlinks')\nasync def _get_links(ctx, arg: int):\n \"\"\"\n Gets a certain amount of links based on the number provided\n -if number exceeds amount of urls, on_command_error() gets called\n arg:number of links requested\n \"\"\"\n url = list_to_str(urls.get_n_elem(arg))\n await ctx.send(url)\n\n\[email protected](name='getlinktype')\nasync def _get_link_ext(ctx, num: int, ext: str):\n \"\"\"\n Gets links based on the extension type(e.g .pdf, .html, .png)\n arg - number of links requested.\n ext- the extension used to filter\n\n If arg exceeds the number of links with a particular extension, the all the links with that extension are sent\n \"\"\"\n url = list_to_str(urls.get_by_ext(num, ext))\n await ctx.send(url)\n\n\n# returns the last 5 links sent in the discord chat\[email protected](name='last5links')\nasync def last_5_links(ctx):\n msg = list_to_str(urls.last_5())\n await ctx.send(msg)\n\n\[email protected](pass_context=True)\nasync def help(ctx):\n user = ctx.message.author\n await user.send(help_msg)\n\n\n# message that gets sent when a command is called incorrectly\[email protected]\nasync def on_command_error(ctx, error):\n await ctx.send(\"Invalid arguments\")\n\nif __name__=='__main__':\n import config\n client.run(config.token)\n\n\n" } ]
3
ncbrown1/timeclock
https://github.com/ncbrown1/timeclock
b625eb625687b08446f6f46944790177602829ad
8dcbfc7e8600956aa2d06f7c1ce4d4ce424305b7
4fae05808e8b98ba206a3e14afd191a2bda57ea2
refs/heads/master
2021-01-10T06:59:03.402360
2015-10-07T22:50:34
2015-10-07T22:50:34
43,849,187
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7931034564971924, "alphanum_fraction": 0.8054187297821045, "avg_line_length": 35.90909194946289, "blob_id": "cbb62a255a4e59b2d81309d7f28dcc996be3ae99", "content_id": "da3ae8dd3fa48ec00ad660e6c9200e65537e9d3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 406, "license_type": "no_license", "max_line_length": 136, "num_lines": 11, "path": "/Dockerfile", "repo_name": "ncbrown1/timeclock", "src_encoding": "UTF-8", "text": "FROM \t\tfedora\nMAINTAINER \tNick Brown \"[email protected]\"\n\nRUN yum -y update\nRUN yum -y install python-pip python-devel gcc\nRUN yum -y install openssl-devel mysql-devel\nRUN mkdir ~/timeclock\nRUN pip install django MySQL-python Pillow django-widget-tweaks flup httplib2 requests simplejson wsgiref django-secure django-sslserver\nADD timeclock /timeclock\nRUN python /timeclock/manage.py collectstatic --noinput\nEXPOSE 8000\n" }, { "alpha_fraction": 0.639284610748291, "alphanum_fraction": 0.6465595364570618, "avg_line_length": 42.407894134521484, "blob_id": "39ce6136dfdd7837112d5f58e311948322326f4d", "content_id": "d57d7c3db1994834f3e66abb2698ddd34cb53327", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 3299, "license_type": "no_license", "max_line_length": 136, "num_lines": 76, "path": "/templates/timeclock/register.html", "repo_name": "ncbrown1/timeclock", "src_encoding": "UTF-8", "text": "{% extends 'base.html' %}\n{% load widget_tweaks %}\n{% load static from staticfiles %}\n{% block content %}\n <head> \n <!-- Custom Style for this Template -->\n <link rel=\"stylesheet\" href=\"{% static 'css/signin.css' %}\">\n </head>\n\n <body>\n <div class=\"container\" style=\"background-color:rgba(255,255,255,0.3);\"> \n <a href=\"/login\" style=\"color:#EEF;\"><span class=\"glyphicon glyphicon-chevron-left\" style=\"color: #EEF;\"></span> Back to Login</a>\n </div>\n <div class=\"container\" style=\"background-color:rgba(255,255,255,0.3);\">\n {% if registered %}\n\t<div class=\"container text-center\">\n\t <br /> <br /> <br /> <br />\n\t <p><strong>Thank you for registering</strong></p>\n\t {% if user.is_superuser %}<a href=\"/admin/\">Go to admin page.</a><br />{% endif %}\n\t</div>\n {% else %}\n <h2 class=\"form-signin-heading text-center\">User Registration</h2>\n <form class=\"form-horizontal form-signin\" role=\"form\" method=\"post\" action=\"{% url 'clock.views.register' %}\"\n\t\t{% if employee_form.is_multipart %}enctype=\"multipart/form-data\"{% endif %}>\n\t{% csrf_token %}\n\t{% for err in user_form.non_field_errors %}\n\t <p class=\"text-danger\">{{ err }}</p>\n\t{% endfor %}\n\t{% for err in employee_form.non_field_errors %}\n\t <p class=\"text-danger\">{{ err }}</p>\n\t{% endfor %}\n\t<div class=\"fieldWrapper\">\n\t <label>Username*</label>\n\t <p class=\"text-danger\">{{ user_form.username.errors|striptags }}</p>\n\t {{ user_form.username|add_class:\"form-control\"|append_attr:'placeholder:Username' }}\n\t</div>\n\t<div class=\"fieldWrapper\">\n\t <label>First Name</label>\n\t <p class=\"text-danger\">{{ user_form.first_name.errors|striptags }}</p>\n\t {{ user_form.first_name|add_class:\"form-control\"|append_attr:'placeholder:First Name' }}\n\t</div>\n\t<div class=\"fieldWrapper\">\n\t <label>Last Name</label>\n\t <p class=\"text-danger\">{{ user_form.last_name.errors|striptags }}</p>\n\t {{ user_form.last_name|add_class:\"form-control\"|append_attr:'placeholder:Last Name' }}\n\t</div>\n\t<div class=\"fieldWrapper\">\n\t <label>Email Address*</label>\n\t <p class=\"text-danger\">{{ user_form.email.errors|striptags }}</p>\n\t {{ user_form.email|add_class:\"form-control\"|append_attr:'placeholder:Email Address' }}\n\t</div>\n\t<div class=\"fieldWrapper\">\n\t <label>Password*</label>\n\t <p class=\"text-danger\">{{ user_form.password.errors|striptags }}</p>\n\t {{ user_form.password|add_class:\"form-control\"|append_attr:'placeholder:Password' }}\n\t</div>\n\t<div class=\"fieldWrapper\">\n\t <label>Confirm Password*</label>\n\t <p class=\"text-danger\">{{ user_form.password_confirm.errors|striptags }}</p>\n\t {{ user_form.password_confirm|add_class:\"form-control\"|append_attr:'placeholder:Confirm Password' }}\n\t</div>\n\t<div class=\"fieldWrapper\">\n\t <label>Profile Picture</label>\n\t <p class=\"text-danger\">{{ employee_form.profile_pic.errors|striptags }}</p>\n\t {{ employee_form.profile_pic|add_class:\"form-control\" }}\n\t <p class=\"help-block\">Please make sure the picture you choose is roughly square.</p>\n\t <p class=\"help-block\">You may add a profile picture later if you desire.</p>\n\t</div>\n\t<button class=\"btn btn-lg btn-primary btn-block\" type=\"submit\">Create New Account</button> </br>\n <p><i>*These fields are required.</i></p>\n </form>\n {% endif %}\n </div> <!-- /container -->\n \n </body>\n{% endblock %}\n" }, { "alpha_fraction": 0.7516129016876221, "alphanum_fraction": 0.7516129016876221, "avg_line_length": 33.44444274902344, "blob_id": "12a65704880920c6c4c80f17e651bad8dd7a4cc5", "content_id": "030c38fefe8e8ad582fb0b394229d6d08ecc8322", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 310, "license_type": "no_license", "max_line_length": 91, "num_lines": 9, "path": "/clock/admin.py", "repo_name": "ncbrown1/timeclock", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom clock.models import *\n\nclass ClockEventAdmin(admin.ModelAdmin):\n\tlist_display = ['employee','date','time_in','time_out','time_worked','message', 'created']\n\tlist_filter = ['employee', 'date']\n\nadmin.site.register(ClockEvent, ClockEventAdmin)\nadmin.site.register(Employee)\n" }, { "alpha_fraction": 0.6572961807250977, "alphanum_fraction": 0.6672629714012146, "avg_line_length": 23.006134033203125, "blob_id": "041f5834c70ccb3257dc8bae3618c6d75e91a7bb", "content_id": "4646a0d469b3472d7a7dbc29c24075cbcfa02a16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3913, "license_type": "no_license", "max_line_length": 110, "num_lines": 163, "path": "/timeclock/settings.py", "repo_name": "ncbrown1/timeclock", "src_encoding": "UTF-8", "text": "\"\"\"\nDjango settings for timeclock project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.6/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.6/ref/settings/\n\"\"\"\n\nADMINS = (\n ('Nick Brown', '[email protected]'),\n)\nEMAIL_SUBJECT_PREFIX = '[Django Timeclock]'\nSEND_BROKEN_LINK_EMAILS = True\n\nEMAIL_HOST = ''\nEMAIL_PORT = 587\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\nTEMPLATE_DIRS = (\n os.path.join(BASE_DIR, 'templates'),\n os.path.join(BASE_DIR, 'clock/templates'),\n)\n\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media')\n\nFILE_UPLOAD_PERMISSIONS = 0755\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = 'd+@lm_+l$_+k8_6*tipu7x737ajn959lh$d)j#aeb#lrc_oas5'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = False \n\nTEMPLATE_DEBUG = False \n\nALLOWED_HOSTS = ['localhost']\n\n\n# Application definition\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.humanize',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'flup',\n 'widget_tweaks',\n 'clock',\n 'forum',\n 'sslserver',\n 'djangosecure',\n)\n\nMIDDLEWARE_CLASSES = (\n 'djangosecure.middleware.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'timeclock.urls'\n\nWSGI_APPLICATION = 'timeclock.wsgi.application'\n\nAUTHENTICATION_BACKENDS = ('timeclock.authbackend.ClockBackend',)#'django.contrib.auth.backends.ModelBackend')\n\nLOGIN_URL = '/login/'\nLOGIN_REDIRECT_URL = 'login_success'\nLOGOUT_URL = '/logout/'\n\nCSRF_COOKIE_SECURE = True\nSESSION_COOKIE_AGE = 86400\nSESSION_COOKIE_SECURE = True\nSESSION_COOKIE_HTTPONLY = True\nSESSION_EXPIRE_AT_BROWSER_CLOSE = True\nSESSION_SAVE_EVERY_REQUEST = True\n\nSECURE_SSL_REDIRECT = True\nSECURE_HSTS_SECONDS = 31536000\nSECURE_HSTS_INCLUDE_SUBDOMAINS = True\nSECURE_FRAME_DENY = True\nSECURE_CONTENT_TYPE_NOSNIFF = True\nSECURE_BROWSER_XSS_FILTER = True\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https')\n\n# Database\n# https://docs.djangoproject.com/en/1.6/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'timeclock',\n\t'USER': '',\n\t'PASSWORD': '',\n\t'HOST': 'localhost',\n }\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.6/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'America/Los_Angeles'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = False\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.6/howto/static-files/\n\nSTATIC_ROOT = os.path.join(BASE_DIR, 'site-static')\nSTATIC_URL = '/static/'\nSTATICFILES_DIRS = (\n\tos.path.join(BASE_DIR, 'static'),\n)\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n },\n 'console':{\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n },\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n }\n}\n" }, { "alpha_fraction": 0.6111929416656494, "alphanum_fraction": 0.630338728427887, "avg_line_length": 41.4375, "blob_id": "32b81547c887398629ab7470f1813b00f9936231", "content_id": "697f9aec465f1bfd7d9d0867ec13893523988061", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 679, "license_type": "no_license", "max_line_length": 98, "num_lines": 16, "path": "/forum/forms.py", "repo_name": "ncbrown1/timeclock", "src_encoding": "UTF-8", "text": "from django import forms\nfrom forum.models import *\n\nclass ThreadForm(forms.ModelForm):\n title = forms.CharField(max_length=60, required=True, label=\"Title\")\n description = forms.CharField(max_length=5000, widget=forms.Textarea, label=\"Description\")\n class Meta:\n model = Thread\n exclude = ('creator','created','forum','updated')\n\nclass PostForm(forms.ModelForm):\n title = forms.CharField(max_length=255, label=\"Title\")\n body = forms.CharField(max_length=5000, widget=forms.Textarea, label=\"Body\")\n class Meta:\n model = Post\n exclude = ('creator','updated','created','thread')\n" }, { "alpha_fraction": 0.6917229890823364, "alphanum_fraction": 0.6917229890823364, "avg_line_length": 49.38298034667969, "blob_id": "3b44c80a0d70ff3a44c26df84ee98d80e29e17cd", "content_id": "744be966a416ee5d2ab9feb08189229893e390d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2368, "license_type": "no_license", "max_line_length": 149, "num_lines": 47, "path": "/timeclock/urls.py", "repo_name": "ncbrown1/timeclock", "src_encoding": "UTF-8", "text": "from django.conf import settings\nfrom django.conf.urls import patterns, include, url, RegexURLResolver\nfrom django.contrib.auth.models import User\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\nfrom django.contrib.auth.views import login, logout, password_change, password_change_done\nfrom django.views.generic import TemplateView\nfrom clock import views\nfrom forum import views as fviews\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\ndef group(regex, *args):\n\treturn RegexURLResolver(regex, args)\n\nurlpatterns = patterns('',\n url(r'^admin/', include(admin.site.urls)),\n url(r'^$', views.index, name='home'),\n (r'^login/', login, {'template_name': 'timeclock/login.html'}),\n url(r'login_success/', views.login_success, name=\"login_success\"),\n (r'^logout/', logout, {'next_page': '/'}),\n (r'^password-change/', password_change, {'template_name': 'timeclock/passwordchange.html', 'post_change_redirect': '/password-change-success/'}),\n (r'^password-change-success/', TemplateView.as_view(template_name='timeclock/passwordchangesuccess.html')),\n url(r'^register/', views.register, name=\"register\"),\n group(r'^profile/', \n\turl(r'^$', views.profile, name=\"user-profile\"),\n\turl(r'^clockevent-history/', views.clockevent_history, name=\"clockevent-history\"),\n ),\n url(r'^superprofile/', views.superprofile, name=\"superprofile\"),\n group(r'^super-clockevent-history/', \n\turl(r'^$', views.super_clockevent_history, name=\"super-clockevent-history\"),\n\turl(r'(\\d+)/$', views.employee_history, name=\"employee-history\")\n ),\n url(r'^edit-profile/', views.edit_profile, name=\"edit-profile\"),\n group(r'^staff-forum/',\n\turl(r'^$', fviews.main_forum, name='main_forum'),\n\turl(r'^(\\d+)/$', fviews.forum, name='forum-detail'),\n\turl(r'^thread/(\\d+)/$', fviews.thread, name=\"thread-detail\"),\n\turl(r'^reply/(\\d+)/$', fviews.post_reply, name=\"reply\"),\n\turl(r'^newthread/(\\d+)/$', fviews.new_thread, name=\"new-thread\"),\n ),\n url(r'^get-clocked-in-employees', views.json_in_employees, name=\"get-clocked-in-employees\"),\n (r'^static/(?P<path>.*)$', 'django.views.static.serve', { 'document_root': settings.STATIC_ROOT, 'show_indexes': True }),\n url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True }),\n)\n\nurlpatterns += staticfiles_urlpatterns()\n" }, { "alpha_fraction": 0.727477490901947, "alphanum_fraction": 0.7394894957542419, "avg_line_length": 37.05714416503906, "blob_id": "1797c3a110e1f7cef9222d61f675d087cbd25dd2", "content_id": "39a52bdbd9d49c8ea25a40d1d25332f1a1a01a42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1332, "license_type": "no_license", "max_line_length": 132, "num_lines": 35, "path": "/clock/models.py", "repo_name": "ncbrown1/timeclock", "src_encoding": "UTF-8", "text": "from datetime import datetime, timedelta\nfrom django.db import models\nfrom django.contrib.auth.models import User\n\nclass Employee(models.Model):\n\tuser = models.OneToOneField(User)\n\t\n\tclocked_in = models.BooleanField(default=False)\n\tlast_clocked_in = models.DateTimeField(blank=True, null=True)\n\tlast_clocked_out = models.DateTimeField(blank=True, null=True)\n\tlast_message = models.CharField(max_length=500, blank=True, null=True, default=\"\")\n\tpay_rate = models.FloatField(default='15.00')\n\tprofile_pic = models.ImageField(upload_to='profile_images', default=\"/static/profile_images/default-pp.png\", blank=True, null=True)\n\t\n\tdef __unicode__(self):\n\t\treturn self.user.username\n\n\tclass Meta:\n\t\tverbose_name = 'Employee'\n\t\tverbose_name_plural = 'Employees'\n\nclass ClockEvent(models.Model):\n\temployee = models.ForeignKey(Employee, unique=True)\n\tmessage = models.TextField(max_length=500)\n\tdate = models.DateField(auto_now_add=True)\n\ttime_in = models.TimeField()\n\ttime_out = models.TimeField()\n\tcreated = models.DateTimeField(auto_now_add=True)\n\t\n\tdef time_worked(self):\n\t\tdt = datetime.combine(self.date, self.time_out) - datetime.combine(self.date, self.time_in)\n\t\treturn timedelta(seconds=dt.total_seconds()%(24*60*60))\n\t\n\tdef __unicode__(self):\n\t\treturn u'%s - %s - %s - %s' % (self.employee, self.date, self.time_in, self.time_out)\n" }, { "alpha_fraction": 0.7151989340782166, "alphanum_fraction": 0.718824565410614, "avg_line_length": 41.433197021484375, "blob_id": "5a03cd0c5cb57dd557815654a00ae7cab889dbe3", "content_id": "01b34fd6cc6768712c5c63b13ef66434e40fd57b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10481, "license_type": "no_license", "max_line_length": 218, "num_lines": 247, "path": "/clock/views.py", "repo_name": "ncbrown1/timeclock", "src_encoding": "UTF-8", "text": "from datetime import datetime, timedelta, date\nfrom django.contrib.auth import logout\nfrom django.contrib.auth.decorators import login_required, user_passes_test\nfrom django.contrib.auth.views import login\nfrom django.core.context_processors import csrf\nfrom django.core.mail import send_mail, EmailMessage\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.shortcuts import render, render_to_response, redirect, get_object_or_404\nfrom django.template import RequestContext\nfrom django.template.response import TemplateResponse\nfrom clock.models import * \nfrom clock.forms import *\nfrom clock.controllers import *\n\ndef login_success(request):\n\tif request.user.groups.filter(name=\"Supervisor\").exists():\n\t\treturn redirect('superprofile')\n\telse:\n\t\treturn redirect('user-profile')\n\ndef json_in_employees(request):\n\treturn HttpResponse(json_employees('in'), 'application/json')\n\n@login_required\n@user_passes_test(is_employee, login_url='/login/')\ndef profile(request):\n\tif request.user.groups.filter(name='Supervisor').count() == 1:\n\t\treturn redirect('superprofile')\n\telif request.user.groups.filter(name='Help Desk Staff').count == 0 and request.user.groups.filter(name='Supervisor').count == 0:\n\t\tlogout(request)\n\t\treturn TemplateResponse(request, 'timeclock/forbidden.html', {'user': request.user})\n\tcontext = RequestContext(request)\n\temployee = Employee.objects.get(user=request.user)\n\tnow = datetime.now() #- timedelta(hours=10)\n\tin_form = ClockInForm(initial={'time_in': now.time(), 'time_out': now.time()})\n\tout_form = ClockOutForm(initial={'time_out': now.time()})\n\tin_employees = get_clocked_in_employees()\n\t\n\terrors = False\n\t\n\tif request.method == 'POST':\n\t\tif request.POST.get('action', False) == 'clock_in':\n\t\t\tform = ClockInForm(request.POST)\n\t\t\tif form.is_valid():\n\t\t\t\tevent = ClockEvent()\n\t\t\t\tevent.employee = employee\n\t\t\t\tevent.message = form.cleaned_data['message']\n\t\t\t\tevent.time_in = form.cleaned_data['time_in']\n\t\t\t\tevent.time_out = form.cleaned_data['time_out']\n\t\t\t\tif can_clock_in(event):\n\t\t\t\t\terrors = False\n\t\t\t\t\tevent.save()\n\t\t\t\t\temployee.clocked_in = True\n\t\t\t\t\temployee.last_clocked_in = datetime.combine(event.date, event.time_in)\n\t\t\t\t\temployee.last_clocked_out = datetime.combine(event.date, event.time_out)\n\t\t\t\t\temployee.last_message = event.message\n\t\t\t\t\temployee.save()\n\t\t\t\telse:\n\t\t\t\t\terrors = True\n\n\t\telif request.POST.get('action', False) == 'clock_out':\n\t\t\tevent = ClockEvent.objects.filter(employee=employee).order_by(\"-created\")[0]\n\t\t\tform = ClockOutForm(request.POST)\n\t\t\tif form.is_valid():\n\t\t\t\tevent.message = form.cleaned_data['message']\n\t\t\t\tevent.time_out = form.cleaned_data['time_out']\n\t\t\t\tevent.save()\n\t\t\t\temployee.clocked_in = False\n\t\t\t\temployee.last_clocked_out = datetime.combine(event.date, event.time_out)\n\t\t\t\temployee.last_message = event.message\n\t\t\t\temployee.save()\n\tevents = ClockEvent.objects.filter(employee=employee).order_by(\"-created\")\n\treturn render_to_response('clock/profile.html', {'employee': employee,'events': events,'user': request.user, 'out_form': out_form, 'in_form': in_form, 'clocked_in_employees': in_employees, 'errors': errors }, context)\n\n@login_required\ndef superprofile(request):\n\tif request.user.groups.filter(name='Supervisor').count() == 0:\n\t\treturn TemplateResponse(request, 'timeclock/forbidden.html', {'user': request.user})\n\telse:\n\t\tadmin = request.user\n\t\tcontext = RequestContext(request)\n\t\temployees = Employee.objects.all().order_by('user').order_by('-clocked_in').filter(user__groups__name='Help Desk Staff')\n\t\tclocked_in_employees = get_clocked_in_employees()\n\t\treturn render_to_response('clock/superprofile.html', {'employees': employees, 'admin': admin, 'clocked_in_employees': clocked_in_employees, 'user': request.user })\n\n@login_required\ndef super_clockevent_history(request):\n\tif request.user.groups.filter(name=\"Supervisor\").count() == 0:\n\t\treturn TempateResponse(request, 'timeclock/forbidden.html', {'user': request.user})\n\telse:\n\t\tcontext = RequestContext(request)\n\t\tevents = ClockEvent.objects.all()\n\t\tnow = datetime.now()\n\t\tstart_date = (now - timedelta(weeks=2)).date()\n\t\tend_date = now.date()\n\t\thistory_form = FilterClockEventForm(initial={'start_date': start_date, 'end_date': end_date})\n\t\t\n\t\tif request.method == 'POST':\n\t\t\thistory_form = FilterClockEventForm(request.POST)\n\t\t\tif history_form.is_valid():\n\t\t\t\tstart_date = history_form.cleaned_data['start_date']\n\t\t\t\tend_date = history_form.cleaned_data['end_date']\n\t\tevents = get_clock_events_between(start_date, end_date)\n\t\thour_total = 0.0\n\t\ttotal_cost = 0.0\n\t\tfor e in events:\n\t\t\thour_amount = e.time_worked().total_seconds()/3600\n\t\t\thour_total += hour_amount\n\t\t\ttotal_cost += hour_amount * e.employee.pay_rate\n\t\t\t\n\t\treturn render_to_response('clock/superclockhistory.html', {'events': events, 'hour_total': hour_total, 'total_cost': total_cost, 'history_form': history_form }, context)\n\n@login_required\ndef employee_history(request, employee_id):\n\tif request.user.groups.filter(name=\"Supervisor\").count == 0:\n\t\treturn TemplateResponse(request, 'timeclock/forbidden.html', {'user': request.user})\n\tcontext = RequestContext(request)\n\temployee = Employee.objects.get(pk=employee_id)\n\tevents = ClockEvent.objects.filter(employee=employee)\n\tnow = datetime.now()\n\tstart_date = (now - timedelta(weeks=2)).date()\n\tend_date = now.date()\n\thistory_form = FilterClockEventForm(initial={'start_date': start_date, 'end_date': end_date})\n\t\n\tif request.method == 'POST':\n\t\thistory_form = FilterClockEventForm(request.POST)\n\t\tif history_form.is_valid():\n\t\t\tstart_date = history_form.cleaned_data['start_date']\n\t\t\tend_date = history_form.cleaned_data['end_date']\n\tevents = get_clock_events_between(start_date, end_date).filter(employee=employee)\n\thour_total = 0.0\n\ttotal_cost = 0.0\n\tfor e in events:\n\t\thour_amount = e.time_worked().total_seconds()/3600\n\t\thour_total += hour_amount\n\t\ttotal_cost += hour_amount * e.employee.pay_rate\n\t\n\treturn render_to_response('clock/employeehistory.html', {'events': events, 'hour_total': hour_total, 'total_cost': total_cost, 'history_form': history_form, 'employee': employee }, context)\n\n@login_required\n@user_passes_test(is_employee, login_url='/login/')\ndef clockevent_history(request):\n\tif request.user.groups.filter(name='Supervisor').count() == 1:\n\t\treturn HttpResponseRedirect('/super-clockevent-history/')\n\tcontext = RequestContext(request)\n\temployee = Employee.objects.get(user=request.user)\n\tnow = datetime.now()\n\tstart_date = (now - timedelta(weeks=2)).date()\n\tend_date = now.date()\n\thistory_form = FilterClockEventForm(initial={'start_date': start_date,'end_date': end_date})\n\t\n\tif request.method == 'POST':\n\t\thistory_form = FilterClockEventForm(request.POST)\n\t\tif history_form.is_valid():\n\t\t\tstart_date = history_form.cleaned_data['start_date']\n\t\t\tend_date = history_form.cleaned_data['end_date']\n\tevents = get_clock_events_between(start_date, end_date).filter(employee=employee)\n\ttotal_time = timedelta(0)\n\tfor e in events:\n\t\ttotal_time += e.time_worked()\n\thour_total = total_time.total_seconds()/3600\n\ttimecard = populate_timesheet(employee, start_date)\n\tlink = timecard.name.split('k/')[1]\n\treturn render_to_response('clock/clockhistory.html', {'timecard': link,'employee': employee, 'events': events, 'user': request.user,'time_worked': hour_total, 'history_form': history_form }, context)\n\n@login_required\n@user_passes_test(is_employee, login_url='/login/')\ndef edit_profile(request):\n\tcontext = RequestContext(request)\n\tedited = False\n\tvalid = True\n\tif request.method == 'POST':\n\t\tuser_form = UpdateUserForm(request.POST, instance=request.user)\n\t\temployee_form = EmployeeForm(request.POST, request.FILES)\n\t\tif user_form.is_valid() and employee_form.is_valid():\n\t\t\tuser = request.user\n\t\t\tuser.set_password(user.password)\n\t\t\tuser.first_name = user_form.cleaned_data['first_name']\n\t\t\tuser.last_name = user_form.cleaned_data['last_name']\n\t\t\tuser.email = user_form.cleaned_data['email']\n\t\t\tuser.save()\n\t\t\t\n\t\t\temployee = Employee.objects.get(user=request.user)\n\t\t\tif 'profile_pic' in request.FILES:\n\t\t\t\temployee.profile_pic = employee_form.files['profile_pic']\n\t\t\t\tpic = request.FILES['profile_pic']\n\t\t\t\tmail = EmailMessage('[Django Timeclock] New Profile Picture for ' + user.first_name, '/media/profile_images/' + employee.profile_pic.name, '[email protected]', [])\n\t\t\t\tmail.attach(pic.name, pic.read(), pic.content_type)\n\t\t\t\tmail.send()\n\t\t\temployee.save()\n\n\t\t\tedited = True\n\t\t\treturn render_to_response('clock/editprofile.html', {'user_form': user_form, 'employee_form': employee_form, 'edited': edited, 'valid': valid,}, context)\n\t\telse: valid = False\n\telse:\n\t\tuser_form = UpdateUserForm(instance=request.user)\n\t\temployee_form = EmployeeForm()\n\treturn render_to_response('clock/editprofile.html', {'user_form': user_form, 'employee_form': employee_form, 'edited': edited, 'valid': valid,}, context)\n\ndef index(request):\n\tcontext = RequestContext(request)\n\tclock_employees = Employee.objects.order_by('user__first_name').filter(user__groups__name='Help Desk Staff')\n\tuser = request.user\n\tif user.is_authenticated:\n\t\tresponse = render_to_response('clock/home.html', {'user': user, 'clock_employees': clock_employees})\n\telse:\n\t\tresponse = render_to_response('clock/home.html', {'clock_employees': clock_employees})\n\treturn response\n\ndef register(request):\n\tcontext = RequestContext(request)\n\t# Set to True upon successful registration\n\tregistered = False\n\n\tif request.method == 'POST':\n\t\tuser_form = UserForm(data=request.POST)\n\t\temployee_form = EmployeeForm(data=request.POST)\n\t\t# If these forms are valid\n\t\tif user_form.is_valid() and employee_form.is_valid():\n\t\t\t# Save user form data to database\n\t\t\tuser = user_form.save()\n\t\t\t\n\t\t\t# Hash the password so we can update\n\t\t\tuser.set_password(user.password)\n\t\t\tuser.save()\n\t\t\t\n\t\t\t#print user.get_full_name()\n\t\t\t\t\n\t\t\temployee = employee_form.save(commit=False)\n\t\t\temployee.user = user\n\t\t\n\t\t\tif 'profile_pic' in request.FILES:\n\t\t\t\temployee.profile_pic = request.files['profile_pic']\n\t\t\temployee.save()\n\t\t\tregistered = True # Registration was successful\n\t\t\treturn render_to_response('timeclock/register.html',\n\t\t\t\t{'user_form': user_form, 'employee_form': employee_form, 'registered': registered,'user': request.user},\n\t\t\t\tcontext)\n\t# Not an HTTP POST, so render blank forms\n\telse:\n\t\tuser_form = UserForm()\n\t\temployee_form = EmployeeForm()\n\t\n\targs = {}\n\targs.update(csrf(request))\n\treturn render(request, 'timeclock/register.html',\n\t\t{'user_form': user_form, 'employee_form': employee_form, 'registered': registered,'user': request.user,})\n" }, { "alpha_fraction": 0.5771040320396423, "alphanum_fraction": 0.5969681143760681, "avg_line_length": 34.425926208496094, "blob_id": "724739b2e34ed1b698c7c30701794c076a21be64", "content_id": "582368f255351a5947d1b9e2cbff6004be8efdeb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1913, "license_type": "no_license", "max_line_length": 241, "num_lines": 54, "path": "/clock/templates/clock/superprofile.html", "repo_name": "ncbrown1/timeclock", "src_encoding": "UTF-8", "text": "{% extends 'base.html' %}\n{% load humanize %}\n\n{% block content %}\n<div class=\"container\" style=\"background-color:rgba(255,255,255,0.3);\">\n <div class=\"jumbotron\" style=\"background-color: #FFF;\">\n\t<h2>Greetings, Master {{ admin.last_name }}.</h2>\n\t<p>There are currently {{ clocked_in_employees.count }} minion(s) at your service.</p>\n </div>\n <h2 class=\"subheader\">Helpdesk Employees</h2>\n<div class=\"table-responsive\">\n <table class=\"table table-hover\">\n\t<thead style=\"background-color:rgba(255,255,255,0.3);\">\n\t <tr>\n\t\t<th>User</th>\n\t\t<th>First Name</th>\n\t\t<th>Surname</th>\n\t\t<th>Pay Rate<th>\n\t\t<th>Clocked In</th>\n\t\t<th>From</th>\n\t\t<th>To</th>\n\t\t<th>Last Message</th>\n\t\t<th><a href=\"/super-clockevent-history/\">History</a><th>\n\t </tr>\n\t</thead>\n\t<tbody>\n\t {% for emp in employees %}\n\t\t<tr class=\"active {% if emp.clocked_in %}success{% else %}danger{% endif %}\" style=\"word-wrap: break-word;\">\n\t\t <td>{{ emp.user.username }}</td>\n\t\t <td>{{ emp.user.first_name }}</td>\n\t\t <td>{{ emp.user.last_name }}</td>\n\t\t <td>${{ emp.pay_rate|floatformat:2 }}</td>\n\t\t <td colspan=\"2\" class=\"text-center\"> {% if emp.clocked_in %}<span class=\"glyphicon glyphicon-ok-circle\" style=\"color: green;\"></span>{% else %}<span class=\"glyphicon glyphicon-remove-circle\" style=\"color: red;\"></span>{% endif %} </td>\n\t\t {% if emp.clocked_in %}\n\t\t\t<td>{{ emp.last_clocked_in.time }}</td>\n\t\t\t<td>{{ emp.last_clocked_out.time }}</td>\n\t\t {% else %}\n\t\t\t<td></td><td></td>\n\t\t {% endif %}\n\t\t <td>{{ emp.last_message }}</td>\n\t\t <td><a href=\"{% url 'employee-history' emp.pk %}\">View</a></td>\n\t\t</tr>\n\t {% endfor %}\n\t</tbody>\n </table>\n</div>\n\n<div class=\"container text-center\">\n<h2 class=\"subheader\">Help Desk Calendar</h2>\n <iframe src=\"<googlecalendarlink>\" style=\" border-width:0 \" width=\"850\" height=\"638\" frameborder=\"0\" scrolling=\"no\"></iframe>\n</div>\n\n</div>\n{% endblock %}\n" }, { "alpha_fraction": 0.7415319085121155, "alphanum_fraction": 0.7470247149467468, "avg_line_length": 38.96341323852539, "blob_id": "3f29950db19d16fb77cfe2fe4906b93cac666b94", "content_id": "4f4477d1f5833f76ac5010aa1b0b602b829486c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3277, "license_type": "no_license", "max_line_length": 137, "num_lines": 82, "path": "/clock/forms.py", "repo_name": "ncbrown1/timeclock", "src_encoding": "UTF-8", "text": "from datetime import datetime, timedelta\nfrom clock.models import *\nfrom django.contrib.auth import authenticate\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import ValidationError\nfrom django.forms.extras.widgets import SelectDateWidget\nfrom clock.models import ClockEvent\nfrom clock.widgets import SelectTimeWidget\nfrom django import forms\n\ndef validate_username_unique(value):\n\t\"\"\"Custom validator for user uniqueness\"\"\"\n\tif User.objects.filter(username=value).exists():\n\t\traise ValidationError(u'That username is taken.')\n\nclass UserForm(forms.ModelForm):\n\tusername = forms.CharField(validators=[validate_username_unique])\n\tpassword = forms.CharField(widget=forms.PasswordInput)\n\tpassword_confirm = forms.CharField(widget=forms.PasswordInput)\n\t\n\tdef clean_password_confirm(self):\n\t\t\"\"\"Required custom validation for the form.\"\"\"\n\t\t# super(UserForm,self).clean()\n\t\tif 'password' in self.cleaned_data and 'password_confirm' in self.cleaned_data:\n\t\t\tif self.cleaned_data['password'] != self.cleaned_data['password_confirm']:\n\t\t\t\tself._errors['password'] = u'* Passwords must match.'\n\t\t\t\tself._errors['password_confirm'] = u'* Passwords must match.'\n\t\treturn self.cleaned_data\n\t\t\n\tclass Meta:\n\t\tmodel = User\n\t\tfields = ('username', 'first_name', 'last_name', 'email', 'password',)\n\ndef auth(u, p):\n\treturn authenticate(username=u, password=p)\n\nclass UpdateUserForm(forms.ModelForm):\n\tusername = forms.CharField(label=\"Your Current Username\")\n\tpassword = forms.CharField(widget=forms.PasswordInput, label=\"Your Current Password\")\n\t\n\tdef clean(self):\n\t\tcleaned_data = super(UpdateUserForm, self).clean()\n\t\tform_password = cleaned_data.get('password')\n\t\tform_username = cleaned_data.get('username')\n\t\t\n\t\tif form_password and form_username:\n\t\t\tform_user = auth(form_username, form_password)\n\t\t\tif form_user is None:\n\t\t\t\tself.errors['password'] = u'You have entered an incorrect password.'\n\t\treturn self.cleaned_data\n\t\t\t\n\t\n\tclass Meta:\n\t\tmodel = User\n\t\tfields = ('first_name', 'last_name', 'email', 'username', 'password')\n\nclass EmployeeForm(forms.ModelForm):\n\tprofile_pic = forms.FileField(widget=forms.FileInput, required=False)\n\tclass Meta:\n\t\tmodel = Employee\n\t\tfields = ('profile_pic',)\n\nclass ClockInForm(forms.ModelForm):\n\ttime_in = forms.TimeField(widget=SelectTimeWidget(minute_step=15, second_step=60, twelve_hr=True), label=\"Time In\")\n\ttime_out = forms.TimeField(widget=SelectTimeWidget(minute_step=15, second_step=60, twelve_hr=True), label=\"Expected Time Out\")\n\tmessage = forms.CharField(max_length=500, widget=forms.TextInput(attrs={'class':'form-control'}), label=\"What will you be doing today?\")\n\t\n\tclass Meta:\n\t\tmodel = ClockEvent\n\t\texclude = ('employee','date','created')\n\nclass ClockOutForm(forms.ModelForm):\n\ttime_out = forms.TimeField(widget=SelectTimeWidget(minute_step=15, second_step=60, twelve_hr=True), label=\"Time Out\")\n\tmessage = forms.CharField(max_length=500, widget=forms.TextInput(attrs={'class':'form-control'}), label=\"What did you do today?\")\n\t\n\tclass Meta:\n\t\tmodel = ClockEvent\n\t\texclude = ('employee','time_in','date','created')\n\nclass FilterClockEventForm(forms.Form):\n\tstart_date = forms.DateField(widget=SelectDateWidget, label=\"Start Date\")\n\tend_date = forms.DateField(widget=SelectDateWidget, label=\"End Date\")\n" }, { "alpha_fraction": 0.5377774238586426, "alphanum_fraction": 0.5857539176940918, "avg_line_length": 29.7167911529541, "blob_id": "3bc56036f6c4167a7f3fe7a7d42c39596e9bb234", "content_id": "4df09d256066f53878214161f0158024ec08eb43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12256, "license_type": "no_license", "max_line_length": 197, "num_lines": 399, "path": "/clock/controllers.py", "repo_name": "ncbrown1/timeclock", "src_encoding": "UTF-8", "text": "import json\nimport os\nfrom datetime import datetime, date, timedelta\nfrom django.conf import settings\nfrom clock.models import ClockEvent, Employee\nfrom string import Template\nimport tempfile\n\ndef is_helpdesk_staff(user):\n if user:\n return user.groups.filter(name='Help Desk Staff').count() == 1\n return False\n\ndef is_supervisor(user):\n\tif user:\n\t\treturn user.groups.filter(name='Supervisor').count() == 1\n\treturn False\n\ndef is_employee(user):\n\treturn is_helpdesk_staff(user) or is_supervisor(user)\n\ndef is_supervisor(user):\n if user:\n return user.groups.filter(name='Supervisor').count() == 1\n return False\n\ndef get_clocked_in_employees():\n return Employee.objects.filter(clocked_in=True).order_by('-last_clocked_in')\n\ndef get_clocked_out_employees():\n return Employee.objects.filter(clocked_in=False).order_by('last_clocked_out').filter(user__groups__name='Help Desk Staff')\n\ndef get_clock_events_between(date1, date2):\n return ClockEvent.objects.filter(date__range=[date1, date2]).order_by('-created')\n\ndef json_employees(in_out_or_all):\n if in_out_or_all == 'in':\n query = get_clocked_in_employees()\n elif in_out_or_all == 'out':\n query = get_clocked_out_employees()\n elif in_out_or_all == 'all':\n query = Employee.objects.all()\n else:\n return json.dumps(['Invalid input'])\n data = []\n for row in query:\n data.append({'id': row.pk, 'username': row.user.username, 'first_name': row.user.first_name, 'last_name': row.user.last_name, 'email': row.user.email, 'clocked_in': row.clocked_in})\n data_as_json = json.dumps(data, sort_keys=True, indent=2)\n return data_as_json\n\ndef time_is_after(t1, t2): # arg1 is time in question, arg2 is time in reference\n day = datetime.now().date()\n d1 = datetime.combine(day, t1)\n d2 = datetime.combine(day, t2)\n td = d1 - d2\n if td.total_seconds() > 0:\n return True\n else: return False\n\ndef time_is_before(t1, t2): # arg1 is time in question, arg2 is time in reference\n day = datetime.now().date()\n d1 = datetime.combine(day, t1)\n d2 = datetime.combine(day, t2)\n td = d1 - d2\n if td.total_seconds() < 0:\n return True\n else: return False\n\ndef time_is_equal(t1, t2):\n day = datetime.now().date()\n d1 = datetime.combine(day, t1)\n d2 = datetime.combine(day, t2)\n td = d1 - d2\n if td.total_seconds() == 0:\n return True\n else: return False \n\ndef can_clock_in(event):\n events = ClockEvent.objects.filter(employee=event.employee).filter(date=datetime.now().date())\n for e in events:\n if time_is_after(event.time_in, e.time_in) and time_is_before(event.time_in, e.time_out):\n return False\n elif time_is_before(event.time_in, e.time_in) and time_is_after(event.time_out, e.time_out): \n return False\n elif time_is_before(event.time_in, e.time_in) and time_is_after(event.time_out, e.time_in) and time_is_before(event.time_out, e.time_out):\n return False\n elif time_is_equal(event.time_in, e.time_in):\n return False\n return True\n\ndef find_closest_sunday(time):\n\tback = time\n\tfwd = time\n\twhile back.strftime('%A') != 'Sunday':\n\t\tback = back - timedelta(days=1)\n\twhile fwd.strftime('%A') != 'Sunday':\n\t\tfwd = fwd + timedelta(days=1)\n\td_back = time-back\n\td_fwd = fwd-time\n\tif d_back > d_fwd:\n\t\treturn fwd\n\telse:\n\t\treturn back\n\ndef split_into_day_lists(employee,start_date):\n\tstart = find_closest_sunday(start_date)\n\tdata = []\t\n\ts = start\n\twhile s != (start+timedelta(weeks=2)):\n\t\tevs = ClockEvent.objects.filter(date=s).filter(employee=employee)\n\t\td = []\n\t\tfor e in evs:\n\t\t\td.append(e)\n\t\tdata.append(d)\n\t\ts = s + timedelta(days=1)\n\treturn data\n\ndef populate_timesheet(employee, start_date):\n\ttimes = dict(\n\t\tName=\"\", PeriodStart=\"\", PeriodEnd=\"\",\n\n\t\tSunIn1=\"\",SunIn2=\"\",SunIn3=\"\",SunIn4=\"\",\n\t\tSunOut1=\"\",SunOut2=\"\",SunOut3=\"\",SunOut4=\"\",\n\t\tTotalSun1=\"\", TotalSun2=\"\",\n\n\t\tMonIn1=\"\",MonIn2=\"\",MonIn3=\"\",MonIn4=\"\",\n\t\tMonOut1=\"\",MonOut2=\"\",MonOut3=\"\",MonOut4=\"\",\n\t\tTotalMon1=\"\", TotalMon2=\"\",\n\n\t\tTueIn1=\"\",TueIn2=\"\",TueIn3=\"\",TueIn4=\"\",\n\t\tTueOut1=\"\",TueOut2=\"\",TueOut3=\"\",TueOut4=\"\",\n\t\tTotalTue1=\"\", TotalTue2=\"\",\n\n\t\tWedIn1=\"\",WedIn2=\"\",WedIn3=\"\",WedIn4=\"\",\n\t\tWedOut1=\"\",WedOut2=\"\",WedOut3=\"\",WedOut4=\"\",\n\t\tTotalWed1=\"\", TotalWed2=\"\",\n\n\t\tThurIn1=\"\",ThurIn2=\"\",ThurIn3=\"\",ThurIn4=\"\",\n\t\tThurOut1=\"\",ThurOut2=\"\",ThurOut3=\"\",ThurOut4=\"\",\n\t\tTotalThur1=\"\", TotalThur2=\"\",\n\n\t\tFriIn1=\"\",FriIn2=\"\",FriIn3=\"\",FriIn4=\"\",\n\t\tFriOut1=\"\",FriOut2=\"\",FriOut3=\"\",FriOut4=\"\",\n\t\tTotalFri1=\"\", TotalFri2=\"\",\n\n\t\tSatIn1=\"\",SatIn2=\"\",SatIn3=\"\",SatIn4=\"\",\n\t\tSatOut1=\"\",SatOut2=\"\",SatOut3=\"\",SatOut4=\"\",\n\t\tTotalSat1=\"\", TotalSat2=\"\",\n\t\t\n\t\tTotalAll=\"\",\n\t)\n\td = split_into_day_lists(employee,start_date)\n\tsu1t = timedelta(0)\n\tmo1t = timedelta(0)\n\ttu1t = timedelta(0)\n\twe1t = timedelta(0)\n\tth1t = timedelta(0)\n\tfr1t = timedelta(0)\n\tsa1t = timedelta(0)\n\tsu2t = timedelta(0)\n\tmo2t = timedelta(0)\n\ttu2t = timedelta(0)\n\twe2t = timedelta(0)\n\tth2t = timedelta(0)\n\tfr2t = timedelta(0)\n\tsa2t = timedelta(0)\n\ttry:\n\t\tif d[0][0]: \n\t\t\ttimes['SunIn1'] = d[0][0].time_in.strftime('%I:%M %p')\n\t\t\ttimes['SunOut1'] = d[0][0].time_out.strftime('%I:%M %p')\n\t\t\tsu1t += d[0][0].time_worked()\n\texcept:\n\t\tpass\n\ttry:\n\t\tif d[0][1]:\n\t\t\ttimes['SunIn2'] = d[0][1].time_in.strftime('%I:%M %p')\n\t\t\ttimes['SunOut2'] = d[0][1].time_out.strftime('%I:%M %p')\n\t\t\tsu1t += d[0][1].time_worked()\n\texcept:\n\t\tpass\n\ttry:\n\t\tif d[1][0]: \n\t\t\ttimes['MonIn1'] = d[1][0].time_in.strftime('%I:%M %p')\n\t\t\ttimes['MonOut1'] = d[1][0].time_out.strftime('%I:%M %p')\n\t\t\tmo1t += d[1][0].time_worked()\n\texcept:\n\t\tpass\n\ttry:\n\t\tif d[1][1]:\n\t\t\ttimes['MonIn2'] = d[1][1].time_in.strftime('%I:%M %p')\n\t\t\ttimes['MonOut2'] = d[1][1].time_out.strftime('%I:%M %p')\n\t\t\tmo1t += d[1][1].time_worked()\n\texcept:\n\t\tpass\n\ttry:\n\t\tif d[2][0]: \n\t\t\ttimes['TueIn1'] = d[2][0].time_in.strftime('%I:%M %p')\n\t\t\ttimes['TueOut1'] = d[2][0].time_out.strftime('%I:%M %p')\n\t\t\ttu1t += d[2][0].time_worked()\n\texcept:\n\t\tpass\n\ttry:\n\t\tif d[2][1]:\n\t\t\ttimes['TueIn2'] = d[2][1].time_in.strftime('%I:%M %p')\n\t\t\ttimes['TueOut2'] = d[2][1].time_out.strftime('%I:%M %p')\n\t\t\ttu1t += d[2][1].time_worked()\n\texcept:\n\t\tpass\n\ttry:\n\t\tif d[3][0]: \n\t\t\ttimes['WedIn1'] = d[3][0].time_in.strftime('%I:%M %p')\n\t\t\ttimes['WedOut1'] = d[3][0].time_out.strftime('%I:%M %p')\n\t\t\twe1t += d[3][0].time_worked()\n\texcept:\n\t\tpass\n\ttry:\n\t\tif d[3][1]:\n\t\t\ttimes['WedIn2'] = d[3][1].time_in.strftime('%I:%M %p')\n\t\t\ttimes['WedOut2'] = d[3][1].time_out.strftime('%I:%M %p')\n\t\t\tweu1t += d[3][1].time_worked()\n\texcept:\n\t\tpass\n\ttry:\n\t\tif d[4][0]: \n\t\t\ttimes['ThurIn1'] = d[4][0].time_in.strftime('%I:%M %p')\n\t\t\ttimes['ThurOut1'] = d[4][0].time_out.strftime('%I:%M %p')\n\t\t\tth1t += d[4][0].time_worked()\n\texcept:\n\t\tpass\n\ttry:\n\t\tif d[4][1]:\n\t\t\ttimes['ThurIn2'] = d[4][1].time_in.strftime('%I:%M %p')\n\t\t\ttimes['ThurOut2'] = d[4][1].time_out.strftime('%I:%M %p')\n\t\t\tth1t += d[4][1].time_worked()\n\texcept:\n\t\tpass\n\ttry:\n\t\tif d[5][0]: \n\t\t\ttimes['FriIn1'] = d[5][0].time_in.strftime('%I:%M %p')\n\t\t\ttimes['FriOut1'] = d[5][0].time_out.strftime('%I:%M %p')\n\t\t\tfr1t += d[5][0].time_worked()\n\texcept:\n\t\tpass\n\ttry:\n\t\tif d[5][1]:\n\t\t\ttimes['FriIn2'] = d[5][1].time_in.strftime('%I:%M %p')\n\t\t\ttimes['FriOut2'] = d[5][1].time_out.strftime('%I:%M %p')\n\t\t\tfr1t += d[5][1].time_worked()\n\texcept:\n\t\tpass\n\ttry:\n\t\tif d[6][0]: \n\t\t\ttimes['SatIn1'] = d[6][0].time_in.strftime('%I:%M %p')\n\t\t\ttimes['SatOut1'] = d[6][0].time_out.strftime('%I:%M %p')\n\t\t\tsa1t += d[6][0].time_worked()\n\texcept:\n\t\tpass\n\ttry:\n\t\tif d[6][1]:\n\t\t\ttimes['SatIn2'] = d[6][1].time_in.strftime('%I:%M %p')\n\t\t\ttimes['SatOut2'] = d[6][1].time_out.strftime('%I:%M %p')\n\t\t\tsa1t += d[6][1].time_worked()\n\texcept:\n\t\tpass\n\ttry:\n\t\tif d[7][0]: \n\t\t\ttimes['SunIn3'] = d[7][0].time_in.strftime('%I:%M %p')\n\t\t\ttimes['SunOut3'] = d[7][0].time_out.strftime('%I:%M %p')\n\t\t\tsu2t += d[7][0].time_worked()\n\texcept:\n\t\tpass\n\ttry:\n\t\tif d[7][1]:\n\t\t\ttimes['SunIn4'] = d[7][1].time_in.strftime('%I:%M %p')\n\t\t\ttimes['SunOut4'] = d[7][1].time_out.strftime('%I:%M %p')\n\t\t\tsu2t += d[7][1].time_worked()\n\texcept:\n\t\tpass\n\ttry:\n\t\tif d[8][0]: \n\t\t\ttimes['MonIn3'] = d[8][0].time_in.strftime('%I:%M %p')\n\t\t\ttimes['MonOut3'] = d[8][0].time_out.strftime('%I:%M %p')\n\t\t\tmo2t += d[8][0].time_worked()\n\texcept:\n\t\tpass\n\ttry:\n\t\tif d[8][1]:\n\t\t\ttimes['MonIn4'] = d[8][1].time_in.strftime('%I:%M %p')\n\t\t\ttimes['MonOut4'] = d[8][1].time_out.strftime('%I:%M %p')\n\t\t\tmo2t += d[8][1].time_worked()\n\texcept:\n\t\tpass\n\ttry:\n\t\tif d[9][0]: \n\t\t\ttimes['TueIn3'] = d[9][0].time_in.strftime('%I:%M %p')\n\t\t\ttimes['TueOut3'] = d[9][0].time_out.strftime('%I:%M %p')\n\t\t\ttu2t += d[9][0].time_worked()\n\texcept:\n\t\tpass\n\ttry:\n\t\tif d[9][1]:\n\t\t\ttimes['TueIn4'] = d[9][1].time_in.strftime('%I:%M %p')\n\t\t\ttimes['TueOut4'] = d[9][1].time_out.strftime('%I:%M %p')\n\t\t\ttu2t += d[9][1].time_worked()\n\texcept:\n\t\tpass\n\ttry:\n\t\tif d[10][0]: \n\t\t\ttimes['WedIn3'] = d[10][0].time_in.strftime('%I:%M %p')\n\t\t\ttimes['WedOut3'] = d[10][0].time_out.strftime('%I:%M %p')\n\t\t\twe2t += d[10][0].time_worked()\n\texcept:\n\t\tpass\n\ttry:\n\t\tif d[10][1]:\n\t\t\ttimes['WedIn4'] = d[10][1].time_in.strftime('%I:%M %p')\n\t\t\ttimes['WedOut4'] = d[10][1].time_out.strftime('%I:%M %p')\n\t\t\twe2t += d[10][1].time_worked()\n\texcept:\n\t\tpass\n\ttry:\n\t\tif d[11][0]: \n\t\t\ttimes['ThurIn3'] = d[11][0].time_in.strftime('%I:%M %p')\n\t\t\ttimes['ThurOut3'] = d[11][0].time_out.strftime('%I:%M %p')\n\t\t\tth2t += d[11][0].time_worked()\n\texcept:\n\t\tpass\n\ttry:\n\t\tif d[11][1]:\n\t\t\ttimes['ThurIn4'] = d[11][1].time_in.strftime('%I:%M %p')\n\t\t\ttimes['ThurOut4'] = d[11][1].time_out.strftime('%I:%M %p')\n\t\t\tth2t += d[11][1].time_worked()\n\texcept:\n\t\tpass\n\ttry:\n\t\tif d[12][0]: \n\t\t\ttimes['FriIn3'] = d[12][0].time_in.strftime('%I:%M %p')\n\t\t\ttimes['FriOut3'] = d[12][0].time_out.strftime('%I:%M %p')\n\t\t\tfr2t += d[12][0].time_worked()\n\texcept:\n\t\tpass\n\ttry:\n\t\tif d[12][1]:\n\t\t\ttimes['FriIn4'] = d[12][1].time_in.strftime('%I:%M %p')\n\t\t\ttimes['FriOut4'] = d[12][1].time_out.strftime('%I:%M %p')\n\t\t\tfr2t += d[12][1].time_worked()\n\texcept:\n\t\tpass\n\ttry:\n\t\tif d[13][0]: \n\t\t\ttimes['SatIn3'] = d[14][0].time_in.strftime('%I:%M %p')\n\t\t\ttimes['SatOut3'] = d[14][0].time_out.strftime('%I:%M %p')\n\t\t\tsa2t += d[13][0].time_worked()\n\texcept:\n\t\tpass\n\ttry:\n\t\tif d[13][1]:\n\t\t\ttimes['SatIn4'] = d[14][1].time_in.strftime('%I:%M %p')\n\t\t\ttimes['SatOut4'] = d[14][1].time_out.strftime('%I:%M %p')\n\t\t\tsa2t += d[13][1].time_worked()\n\texcept:\n\t\tpass\n\ttimes['TotalSun1'] = su1t.total_seconds()/3600 \n\ttimes['TotalMon1'] = mo1t.total_seconds()/3600\n\ttimes['TotalTue1'] = tu1t.total_seconds()/3600\n\ttimes['TotalWed1'] = we1t.total_seconds()/3600\n\ttimes['TotalThur1'] = th1t.total_seconds()/3600\n\ttimes['TotalFri1'] = fr1t.total_seconds()/3600\n\ttimes['TotalSat1'] = sa1t.total_seconds()/3600\n\ttimes['TotalSun2'] = su2t.total_seconds()/3600\n\ttimes['TotalMon2'] = mo2t.total_seconds()/3600\n\ttimes['TotalTue2'] = tu2t.total_seconds()/3600\n\ttimes['TotalWed2'] = we2t.total_seconds()/3600\n\ttimes['TotalThur2'] = th2t.total_seconds()/3600\n\ttimes['TotalFri2'] = fr2t.total_seconds()/3600\n\ttimes['TotalSat2'] = sa2t.total_seconds()/3600\n\ttimes['TotalAll'] = (su1t+mo1t+tu1t+we1t+th1t+fr1t+sa1t+su2t+mo2t+tu2t+we2t+th2t+fr2t+sa2t).total_seconds()/3600\n\tstart = find_closest_sunday(start_date)\n\ttimes['PeriodStart'] = start.strftime('%b %d')\n\ttimes['PeriodEnd'] = (start+timedelta(weeks=2,days=-1)).strftime('%b %d')\n\tname = \"%s %s\" % (employee.user.first_name, employee.user.last_name)\n\ttimes['Name'] = str(name)\n\n\n\timport os \n\tfolder = os.path.join(settings.MEDIA_ROOT,'files/temp')\n\tfor the_file in os.listdir(folder):\n\t file_path = os.path.join(folder, the_file)\n\t try:\n\t os.unlink(file_path)\n\t except:\n\t pass\t\n\tf = open(os.path.join(settings.STATIC_ROOT, 'downloads/timesheet.html'), 'r')\n\ttext = f.read()\n\tf.close()\n\tnewText = Template(text).substitute(times)\n\tf2 = tempfile.NamedTemporaryFile(mode=\"w\",suffix=\".html\",dir=os.path.join(settings.MEDIA_ROOT, \"files/temp/\"),delete=False) # open('populated_timesheet.html', 'w')\n\tf2.write(newText)\n\treturn f2\n" }, { "alpha_fraction": 0.7511177062988281, "alphanum_fraction": 0.7540983557701111, "avg_line_length": 40.9375, "blob_id": "757982107af4ee2ee96e4f6d270447a4e66ab144", "content_id": "017ac27381ecfa11ac650befd38d356838f0bc12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 671, "license_type": "no_license", "max_line_length": 152, "num_lines": 16, "path": "/timeclock/authbackend.py", "repo_name": "ncbrown1/timeclock", "src_encoding": "UTF-8", "text": "from django.contrib.auth import get_user_model\nfrom django.contrib.auth.backends import ModelBackend\nfrom django.contrib.auth.models import User\n\nclass ClockBackend(ModelBackend):\n\t\n\tdef authenticate(self, username=None, password=None, **kwargs):\n\t\tUserModel = get_user_model()\n\t\tif username is None:\n\t\t\tusername = kwargs.get(UserModel.USERNAME_FIELD)\n\t\ttry:\n\t\t\tuser = UserModel._default_manager.get_by_natural_key(username)\n\t\t\tif user.check_password(password) and (user.groups.filter(name='Supervisor').count() == 1 or user.groups.filter(name='Help Desk Staff').count() == 1):\n\t\t\t\treturn user\n\t\texcept UserModel.DoesNotExist:\n\t\t\tUserModel().set_password(password)\n" }, { "alpha_fraction": 0.6183205842971802, "alphanum_fraction": 0.6183205842971802, "avg_line_length": 17.714284896850586, "blob_id": "8251be0a4f4a27ea3207a7f5e55fb2034e6f3a1a", "content_id": "a2cfd17b2425b5e61f71518b0ba0c9810a158f07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 131, "license_type": "no_license", "max_line_length": 64, "num_lines": 7, "path": "/README.md", "repo_name": "ncbrown1/timeclock", "src_encoding": "UTF-8", "text": "timeclock\n=========\nA Django web-app utility for use by the UCSB ECI Helpdesk staff.\n\nDescription\n===========\n<-- Coming soon! -->\n" }, { "alpha_fraction": 0.659744381904602, "alphanum_fraction": 0.659744381904602, "avg_line_length": 30.299999237060547, "blob_id": "7c43ffa7cdca79ad326bfb5df784056cae3adf1e", "content_id": "5f50b0d8ad57c7e9802c54574ad687d8d10223d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 626, "license_type": "no_license", "max_line_length": 64, "num_lines": 20, "path": "/forum/admin.py", "repo_name": "ncbrown1/timeclock", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom forum.models import *\n\nclass ForumAdmin(admin.ModelAdmin):\n pass\n\nclass ThreadAdmin(admin.ModelAdmin):\n list_display = ['title', 'forum', 'creator', 'created']\n lsit_filter = ['forum', 'creator']\n\nclass PostAdmin(admin.ModelAdmin):\n list_display = ['title', 'thread', 'creator', 'created']\n list_filter = ['created', 'creator']\n search_fields = ['title', 'creator']\n date_hierarchy = 'created'\n save_on_top = True\n\nadmin.site.register(Forum, ForumAdmin)\nadmin.site.register(Thread, ThreadAdmin)\nadmin.site.register(Post, PostAdmin)\n" }, { "alpha_fraction": 0.6162612438201904, "alphanum_fraction": 0.6197677254676819, "avg_line_length": 47.031578063964844, "blob_id": "c088dd1dd10e03ac8673740f5d8e8e199e2e49f3", "content_id": "019d4580cb5b87ae60663f3000b0c6641c6c8cac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4563, "license_type": "no_license", "max_line_length": 195, "num_lines": 95, "path": "/forum/views.py", "repo_name": "ncbrown1/timeclock", "src_encoding": "UTF-8", "text": "from django.contrib.auth.decorators import login_required, user_passes_test\nfrom django.core.mail import send_mail\nfrom django.core.paginator import Paginator\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render_to_response, get_object_or_404\nfrom django.template import RequestContext\nfrom clock.controllers import *\nfrom clock.models import Employee\nfrom forum.models import *\nfrom forum.forms import *\n\nsignature = \"\\n\\nThis message was sent via the Helpdesk Timeclock Internal Forum. If you would like to reply to this message,\\\n\t please\tgo to the forum and submit your reply there. https://localhost:8000/staff-forum/\"\n\n@login_required\n@user_passes_test(is_employee, login_url='/login/')\ndef main_forum(request):\n forums = Forum.objects.all()\n return render_to_response('forum/list.html', {'forums': forums, 'user': request.user}, context_instance=RequestContext(request))\n\ndef mk_paginator(request, items, num_items):\n paginator = Paginator(items, num_items)\n try: page = int(request.GET.get(\"page\", '1'))\n except ValueError: page = 1\n\n try: items = paginator.page(page)\n except (InvalidPage, EmptyPage): items = paginator.page(paginator.num_pages)\n return items\n\n@login_required\n@user_passes_test(is_employee, login_url='/login/')\ndef forum(request, forum_id):\n threads = Thread.objects.filter(forum=forum_id).order_by('-created')\n threads = mk_paginator(request, threads, 15)\n return render_to_response('forum/forum.html', {'threads': threads, 'pk': forum_id, 'user': request.user}, context_instance=RequestContext(request))\n\n@login_required\n@user_passes_test(is_employee, login_url='/login/')\ndef thread(request, thread_id):\n posts = Post.objects.filter(thread=thread_id).order_by(\"created\")\n posts = mk_paginator(request, posts, 15)\n t = Thread.objects.get(pk=thread_id)\n return render_to_response('forum/thread.html', {'posts': posts, 'pk': thread_id, 'title': t.title, 'forum_pk': t.forum.pk, 'user': request.user}, context_instance=RequestContext(request))\n\n@login_required\n@user_passes_test(is_employee, login_url='/login/')\ndef post_reply(request, thread_id):\n form = PostForm()\n thread = Thread.objects.get(pk=thread_id)\n\n if request.method == 'POST':\n form = PostForm(request.POST)\n if form.is_valid():\n post = Post()\n post.thread = thread\n post.title = form.cleaned_data['title']\n post.body = form.cleaned_data['body']\n post.creator = request.user\n post.save()\n return HttpResponseRedirect(reverse('thread-detail', args=(thread_id,)))\n\telse:\n\t\tpost = Post()\n\t\tpost.title = 'RE: %s' % thread.title\n\t\tform = PostForm(instance=post)\n return render_to_response('forum/reply.html', {'form':form, 'thread':thread,}, context_instance=RequestContext(request))\n\n@login_required\n@user_passes_test(is_employee, login_url='/login/')\ndef new_thread(request, forum_id):\n form = ThreadForm()\n forum = get_object_or_404(Forum, pk=forum_id)\n if request.method == 'POST':\n form = ThreadForm(request.POST)\n if form.is_valid():\n thread = Thread()\n thread.title = form.cleaned_data['title']\n thread.description = form.cleaned_data['description']\n thread.forum = forum\n thread.creator = request.user\n thread.save()\n\t\t\tpost = Post()\n\t\t\tpost.thread = thread\n\t\t\tpost.title = thread.title\n\t\t\tpost.body = thread.description\n\t\t\tpost.creator = request.user\n\t\t\tpost.save()\n if forum.title == 'Announcements':\n employees = Employee.objects.filter(user__groups__name='Help Desk Staff')\n rcpts = []\n for emp in employees:\n rcpts.append(emp.user.email)\n send_mail('[Help Desk Announcement] ' + thread.title, thread.description + signature, '[email protected]', rcpts, fail_silently=False)\n return HttpResponseRedirect(reverse('forum-detail', args=(forum_id, )))\n return render_to_response('forum/new-topic.html', {'form':form, 'forum':forum, }, context_instance=RequestContext(request))\n" } ]
15
mister-magpie/sonification
https://github.com/mister-magpie/sonification
b9ae0f601912abc5be2e884e99ca030f371a331e
a92957da41b7b34237bbd25a0cc2bdeebd883a30
245dc22b0571ab7e3525a812bf12968a485b7601
refs/heads/master
2021-03-27T15:12:08.835532
2018-03-16T14:46:27
2018-03-16T14:46:27
110,675,805
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4794841706752777, "alphanum_fraction": 0.5404455065727234, "avg_line_length": 28.413793563842773, "blob_id": "a0c92adc0c976e4360c4c79c2dd9b797e005477b", "content_id": "440d1ff5af11be9d110c71e01b5078986fe32302", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 853, "license_type": "no_license", "max_line_length": 54, "num_lines": 29, "path": "/img2json.py", "repo_name": "mister-magpie/sonification", "src_encoding": "UTF-8", "text": "import os\nimport sys\nfrom PIL import Image\nimport json\n\nif __name__ == '__main__':\n print \"converting 100x100 map image to json array\"\n imgpath = sys.argv[1]\n jsonpath = sys.argv[2]\n im = Image.open(imgpath)\n assert im.size == (100,100)\n print \"loading \" + imgpath\n p = im.load()\n result = []\n for i in range(10000):\n r,g,b = p[i/100,i%100]\n if(r==0 and g==0 and b==255):\n result.append(\"sea\")\n elif(r==0 and g==255 and b==0):\n result.append(\"grass\")\n elif(r==255 and g==255 and b==0):\n result.append(\"sand\")\n elif(r==255 and g==0 and b==255):\n result.append(\"marsh\")\n elif(r==0 and g==0 and b==0):\n result.append(\"urban\")\n print \"dumping \" + jsonpath\n with open(jsonpath, 'wb') as target:\n json.dump(result,target)\n" }, { "alpha_fraction": 0.4945288300514221, "alphanum_fraction": 0.5185366868972778, "avg_line_length": 27.746479034423828, "blob_id": "819d3da29993ee294b5d0653c3bb6fcebef31fdc", "content_id": "2371a67e5666566ead1656a8720cd12dfe42d3dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 6123, "license_type": "no_license", "max_line_length": 81, "num_lines": 213, "path": "/static/js/agents.js", "repo_name": "mister-magpie/sonification", "src_encoding": "UTF-8", "text": "var hashMap = new Map()\n\nfunction cubeSprite(x,y,color){\n let rec = new PIXI.Graphics()\n rec.beginFill(color);\n rec.lineStyle(1,\"0x000000\",1);\n rec.drawRect(x,y,pixelSize,pixelSize);\n rec.endFill();\n //rec.boundsPadding = 0;\n let texture = rec.generateTexture();\n var sprite = new PIXI.Sprite(texture);\n sprite.setTransform(x*pixelSize,y*pixelSize);\n app.stage.addChild(sprite);\n return sprite\n}\n\n\n/*\nbirds are white and fly around the map\n*/\nvar bird = function(position){\n this.type = \"bird\";\n this.x = Math.floor(position/100) //| Math.round(Math.random()*99);\n this.y = position%100 //| Math.round(Math.random()*99);\n this.color = \"0xffffff\";\n this.sprite = cubeSprite(this.x,this.y,this.color);\n this.energy = 100;\n\n app.stage.addChild(this.sprite);\n\n // movement\n this.move = function(dx,dy){\n var newx = this.x + (dx | Math.round(Math.random()*2 - 1));\n var newy = this.y + (dy | Math.round(Math.random()*2 - 1));\n if (newx < 0) newx += 100;\n if (this.y < 0) this.y += 100;\n if (newx > 99) newx -= 100;\n if (newy > 99) newy -= 100;\n //check for hash collision here?\n console.log(\"new position \" + newx+newy);\n this.x = newx\n this.y = newy\n }\n this.step = function(){\n console.log(\"steppin\");\n //hashMap.delete(hashLocation(this.x,this.y));\n this.move();\n this.sprite.x = this.x*pixelSize;\n this.sprite.y = this.y*pixelSize;\n //hashMap.set(hashLocation(this.x,this.y), this);\n\n }\n\n this._stepz = function(){\n //this.energy -= 1;\n if (false) {\n //if energy is 0 bird dies\n console.log(\"starve\");\n //this.dispose()\n }\n // remove me from my current hashMap position\n hashMap.delete(hashLocation(this.x,this.y));\n\n // Random movement\n this.move();\n // update sprite position\n this.sprite.x = this.x*pixelSize;\n this.sprite.y = this.y*pixelSize;\n\n // update hashMap\n // let collision = hashMap.get(hashLocation(this.x,this.y));\n // console.log(collision);\n // if (collision !== undefined & collision !== this) {\n // //console.log(collision.length)\n // for(i=0;i<collision.length;i++){\n // switch (collision[i].type) {\n //\n // case \"bird\":\n // console.log(\"bird collision: \" + this.x + \" - \" + this.y);\n // collision[i].sprite.tint = \"0xff0000\"\n // this.sprite.tint = \"0xff0000\"\n // break;\n //\n // case \"fish\":\n // //fish dies\n // console.log(\"bird eats fish\")\n // //collision.dispose()\n // this.energy += 1\n //\n // default:\n // //default\n // }\n // }\n // }\n hashMap.set(hashLocation(this.x,this.y),this)\n }\n // death\n this.dispose = function(){\n console.log(\"bird dies of starvation\");\n app.stage.removeChild(this.sprite);\n setTimeout(function(){\n //console.log(\"disposing\");\n hashMap.delete(hashLocation(this.x,this.y))\n },500);\n }\n}\n\n\n/*\nFishes are dark blue and wonder in the sea\n*/\nvar fish = function(position){\n this.type = \"fish\";\n //let rand = getRandomSeaTile(); // |notation is bugged\n let pos = position;\n this.x = Math.floor(pos/100);\n this.y = pos%100;\n this.color = \"0x000044\";\n this.sprite = cubeSprite(this.x,this.y,this.color);\n this.energy = 100;\n\n app.stage.addChild(this.sprite);\n\n\n // movement\n this.move = function(dx,dy){\n while (true) {\n this.x += dx | Math.round(Math.random()*2 - 1);\n this.y += dy | Math.round(Math.random()*2 - 1);\n if (this.x < 0) this.x += 100;\n if (this.y < 0) this.y += 100;\n if (this.x > 99) this.x -= 100;\n if (this.y > 99) this.y -= 100;\n let k = this.x*100 + this.y\n if(seaTiles.includes(k)) break;\n }\n }\n this.adjacent = function(){\n var k = this.x*100 + this.y\n var a = [k+1,k-1,k+100,k-100,k+99,k-99,k+101,k-101]\n for (var i = 0; i < a.length; i++) {\n if (seaTiles.includes(a[i]) & hashMap.get(a[i]) === undefined){\n //console.log(\"not sea\");\n return a[i]\n }\n }\n }\n this.step = function(){\n //water quality can kill fish\n let wq = 1;\n if (wq < 1) {\n \"fish dead by pollution\"\n if(Math.random() > wq) this.dispose();\n }\n // reproduce\n if(Math.random() <= 0.1){\n let t = this.adjacent();\n if (t!==undefined) {\n console.log(\"fish is born on \" + t)\n hashMap.set(t,new fish(t))\n }\n }\n }\n // death\n this.dispose = function(){\n app.stage.removeChild(this.sprite);\n setTimeout(function(){\n //console.log(\"disposing\");\n //creatures.pop(creatures.indexOf(this))\n hashMap.delete(hashLocation(this.x,this.y))\n },100);\n }\n}\n/*FISHES*/\n\n//var creatures = new Set();\nfunction createBirds(m){\n n = m | 50\n for(i=0;i<n;i++){\n //creatures.add(new bird());\n hashMap.set(getRandomSeaTile(), new fish(getRandomSeaTile()));\n }\n hashMap.set(getRandomGrassTile(), new bird(getRandomGrassTile()));\n\n}\n\nfunction getRandomSeaTile(){\n let i = Math.floor(Math.random()*4370);\n return seaTiles[i];\n}\nfunction getRandomGrassTile(){\n let i = Math.floor(Math.random()*2554);\n return grassTiles[i];\n}\n\nfunction hashLocation(posX,posY){\n return posX*100 + posY\n}\n\nfunction addToHashMap(key,obj){\n\n}\nfunction updateHashMap(key, obj){\n //console.log(\"adding to hash\");\n collision = null;\n if(hashMap.get(key) ){\n hashMap.set(key, obj);\n }\n else{\n collision = hashMap.get(key)\n }\n return collision;\n}\n" }, { "alpha_fraction": 0.5302438735961914, "alphanum_fraction": 0.5476829409599304, "avg_line_length": 28.71014404296875, "blob_id": "09d46fef42d2ce1986bb5f7aa90dbf575e789640", "content_id": "fbd9f189394a288db390415680b0e2b0fa7a851b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 8200, "license_type": "no_license", "max_line_length": 122, "num_lines": 276, "path": "/static/timeseries.js", "repo_name": "mister-magpie/sonification", "src_encoding": "UTF-8", "text": "var timedata;\nvar td_norm;\n$(document).ready(function() {\n // Stuff to do as soon as the DOM is ready\n $.getJSON(\"./data_int.json\",function(data){\n timedata = data.slice()\n console.log(\"data loaded\");\n //$(\"#play-btn\").prop(\"disabled\", false);\n });\n $.getJSON(\"./data_int.json\",function(data_int){\n td_norm = normalizedTimeseries(data_int.slice());\n //loadGraphs(td_norm)\n loadCanvas();\n checkboxes();\n })\n document.getElementById(\"play-btn\").disabled = false;\n});\n\nfunction checkboxes(){\n var container = $(\"#checkboxes\");\n for (var i = 0; i < timedata.length; i++) {\n $('<input />', { type: 'checkbox', id: 'chkbx-'+i, value: timedata[i].label , checked: true}).appendTo(container);\n $('<label />', { 'for': 'chkbx-'+i, text: timedata[i].label }).appendTo(container);\n }\n}\n\n\n\nvar year = 0;\nvar drum = new Tone.MembraneSynth().toMaster();\n drum.oscillator.type = \"sine\";\n drum.volume.value = -12\n\nvar bell = new Tone.MetalSynth().toMaster();\n\nvar freeverb = new Tone.Freeverb(0.5,600);\nTone.Master.volume.value = -12;\n\n//mute master until user presses play\n//Tone.Master.mute = true;\nTone.Master.chain(freeverb);\n\nvar oscillators = createOsc();\n\nTone.Transport.scheduleRepeat(function(time){\n console.log(\"playing\");\n //console.log(year++);// + \" - year: \" + (1890 + (year/0.126)));\n if (year == 1000) {\n stop();\n }\n drum.triggerAttackRelease(\"C4\", \"16n\",Tone.now,0.2);\n\n oscillators.forEach(function(el,idx){\n if(el === null){\n return\n };\n el.osc.mute = false;\n if($(\"#chkbx-\"+idx).prop(\"checked\") & td_norm[idx].timeseries[year] != null){\n el.osc.mute = false;\n el.play(timedata,td_norm);\n }\n if(td_norm[idx].timeseries[year] === null){\n el.osc.mute = true;\n }\n });\n}, \"16n\");\n\nfunction play(startingFrom){\n year = startingFrom | 0;\n Tone.Master.mute = false;\n Tone.Transport.start();\n}\n\nfunction stop(){\n Tone.Transport.stop();\n Tone.Transport.clear();\n bell.triggerAttack();\n oscillators.forEach(function(el){\n if(el === null) return;\n el.osc.stop();\n })\n //Tone.Master.mute = true;\n year = 0;\n}\n\nfunction loadGraphs(d){\n plotData = []\n\n d.forEach(function(el,idx){\n let trace = {\n x: [...Array(timedata[0].timeseries.length).keys()], //spread operator, dirty hack :(\n y: el.timeseries,//normalize(el.timeseries),\n type: 'scatter',\n name: idx +\" - \"+ el.label\n };\n plotData[idx] = trace;\n })\n Plotly.newPlot('graphs', plotData);\n}\n\nfunction loadCanvas(){\n var can = document.getElementById(\"canvas\");\n can.height = 520;\n can.width = 999;\n var ctx = can.getContext(\"2d\");\n\n timedata.forEach(function(el,idx){\n //console.log(\"printing \" + el.label);\n ctx.fillStyle = stringToColour(el.label);\n ctx.fillRect(0,40*idx,999,40);\n });\n}\n\nfunction normalizedTimeseries(tmdt){\n var res = tmdt.slice();\n res.forEach(function(el,idx){\n res[idx].timeseries = normalize(res[idx].timeseries);\n })\n return res;\n}\n\nfunction normalize(tms){\n let a = new Array(1000);\n let max = Math.max.apply(Math, tms);\n tms.forEach(function(el,idx) {\n if (el == null) {\n a[idx] = el;\n }else{\n a[idx] = el / max;\n }\n });\n return a;\n}\n\nfunction createOsc(){\n var oscillators = new Array(13);\n\n oscillators[0] = {\n osc: new Tone.OmniOscillator(\"C5\",\"fmsquare\").toMaster(),\n play: function(timedata, td_norm){\n if(timedata[0].timeseries[year] != null){\n if(this.osc.state == \"stopped\") this.osc.start();\n this.osc.frequency.value = td_norm[0].timeseries[year]*880;\n }\n }\n }\n //\n oscillators[1] = {\n osc: new Tone.OmniOscillator(\"C2\",\"fmsine\").toMaster(),\n play: function(timedata, td_norm){\n if(this.osc.state == \"stopped\") this.osc.start();\n this.osc.modulationIndex.value = td_norm[1].timeseries[year]*10;\n }\n }\n\n oscillators[2] = {\n osc: new Tone.OmniOscillator(\"B3\",\"fmsine\").toMaster(),\n play: function(timedata, td_norm){\n if(timedata[2].timeseries[year] != null){\n if(this.osc.state == \"stopped\") this.osc.start();\n this.osc.modulationIndex.value = td_norm[2].timeseries[year];\n }\n }\n }\n\n oscillators[3] = {\n osc: new Tone.OmniOscillator(\"F#5\",\"fatsine\").toMaster(),\n play: function(timedata, td_norm){\n if(timedata[3].timeseries[year] != null){\n if(this.osc.state == \"stopped\") this.osc.start();\n this.osc.detune.value = timedata[3].timeseries[year];\n this.osc.spread = -40 + timedata[4].timeseries[year];\n }\n }\n }\n\n oscillators[4] = null;//oscillator[3]\n\n oscillators[5] = {\n osc: new Tone.OmniOscillator(\"D5\",\"fatsine\").toMaster(),\n play: function(timedata, td_norm){\n if(timedata[5].timeseries[year] != null){\n if(this.osc.state == \"stopped\") this.osc.start();\n this.osc.frequency.value = 880 + timedata[5].timeseries[year];\n }\n }\n }\n\n oscillators[6] = {\n osc: new Tone.OmniOscillator(\"C2\",\"fatsquare\").toMaster(),\n play: function(timedata, td_norm){\n if(timedata[6].timeseries[year] != null){\n if(this.osc.state == \"stopped\") this.osc.start();\n this.osc.frequency.value = timedata[6].timeseries[year];\n }\n }\n }\n\n oscillators[7] = {\n osc: new Tone.OmniOscillator(\"G2\",\"fmsine\").toMaster(),\n play: function(timedata, td_norm){\n if(this.osc.state == \"stopped\") this.osc.start();\n this.osc.modulationIndex.value = timedata[7].timeseries[year]*2;\n }\n }\n\n oscillators[8] = {\n osc: new Tone.OmniOscillator(\"C2\",\"fmsquare\").toMaster(),\n play: function(timedata, td_norm){\n if(timedata[8].timeseries[year] != null){\n if(this.osc.state == \"stopped\") this.osc.start();\n this.osc.frequency.value = timedata[8].timeseries[year];\n }\n }\n }\n\n oscillators[9] = {\n osc: new Tone.OmniOscillator(\"G2\",\"fmsquare\").toMaster(),\n play: function(timedata, td_norm){\n if(timedata[9].timeseries[year] != null){\n if(this.osc.state == \"stopped\") this.osc.start();\n this.osc.frequency.value = timedata[9].timeseries[year]/10;\n }\n }\n }\n\n oscillators[10] = {\n osc: new Tone.OmniOscillator(\"F5\",\"fatsine\").toMaster(),\n play: function(timedata, td_norm){\n if(timedata[10].timeseries[year] != null){\n if(this.osc.state == \"stopped\") this.osc.start();\n this.osc.frequency.value = timedata[10].timeseries[year]/10;\n }\n }\n }\n\n oscillators[11] = {\n osc: new Tone.OmniOscillator(\"G2\",\"fmsquare\").toMaster(),\n play: function(timedata, td_norm){\n if(timedata[11].timeseries[year] != null){\n if(this.osc.state == \"stopped\") this.osc.start();\n this.osc.frequency.value = timedata[11].timeseries[year]*30;\n }\n }\n }\n\n oscillators[12] = {\n osc: new Tone.OmniOscillator(\"G6\",\"fatsine\").toMaster(),\n play: function(timedata, td_norm){\n if(timedata[12].timeseries[year] != null){\n if(this.osc.state == \"stopped\") this.osc.start();\n this.osc.spread = timedata[12].timeseries[year];\n }\n }\n\n }\n\n oscillators.forEach(function(el){\n if(el === null) return;\n el.osc.volume.value = -12;\n });\n return oscillators\n}\n\nvar stringToColour = function(str) {\n var hash = 0;\n for (var i = 0; i < str.length; i++) {\n hash = str.charCodeAt(i) + ((hash << 5) - hash);\n }\n var colour = '#';\n for (var i = 0; i < 3; i++) {\n var value = (hash >> (i * 8)) & 0xFF;\n colour += ('00' + value.toString(16)).substr(-2);\n }\n return colour;\n}\n" }, { "alpha_fraction": 0.7599999904632568, "alphanum_fraction": 0.7599999904632568, "avg_line_length": 24, "blob_id": "007cb397db8627b8ba8f599b8d6c9dc0929c4118", "content_id": "1af4b8579bab98ca12c8e36d7fced6ba14261fa8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 100, "license_type": "no_license", "max_line_length": 40, "num_lines": 4, "path": "/README.md", "repo_name": "mister-magpie/sonification", "src_encoding": "UTF-8", "text": "# Sonifications\nstart nodejs server with\n`$ nodejs app.js`\nthe latest sonification is **/brownsea**\n" }, { "alpha_fraction": 0.521053671836853, "alphanum_fraction": 0.5655557513237, "avg_line_length": 26.685083389282227, "blob_id": "57f0fe2f7b799d5663091819d54b45582372a60d", "content_id": "feabadddaefbf442c2b8e1d2fdaac5ec2cbb2129", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5011, "license_type": "no_license", "max_line_length": 95, "num_lines": 181, "path": "/static/js/simulation.js", "repo_name": "mister-magpie/sonification", "src_encoding": "UTF-8", "text": "const pixelSize = 5//Math.floor(screen.availHeight/100) - 1\n\n//Create the renderer\n// var renderer = PIXI.autoDetectRenderer(256, 256);\n// renderer.view.style.borderStyle = \"solid\";\n// renderer.view.style.borderColor = \"rgba(0,0,0,1)\";\n// renderer.view.style.borderWidth = \"0px 0px 1px 1px\";\n// renderer.backgroundColor = 0x061639;\n// renderer.view.style.float = \"left\";\n// // autoResize assures that size matches resolution\n// renderer.autoResize = true;\n// renderer.resize(pixelSize*100, pixelSize*100);\n//Add the canvas to the HTML document\n//document.body.appendChild(renderer.view);\nvar app = new PIXI.Application(500, 500, {autoStart : true, antialias: false });\ndocument.body.appendChild(app.view);\n\n//Create a container object called the `stage`\n//var stage = app.stage;\n//Tell the `renderer` to `render` the `stage`\n//renderer.render(stage);\nvar canvasGrid = create2DArray(100)\n\nfunction create2DArray(dimension){\n var a = new Array(dimension)\n for(i=0;i<dimension;i++){\n a[i] = new Array(dimension)\n }\n return a;\n}\n\nfunction initCanvasGrid(grid){\n for(i=0;i<100;i++){\n for(j=0;j<100;j++){\n grid[i][j] = new tile(\"0xaa8855\",i*pixelSize,j*pixelSize)\n app.stage.addChild(grid[i][j].rectangle)\n }\n }\n //renderer.render(stage)\n try {\n colorgrid()\n } catch (e) {\n console.log(e)\n } finally {\n setTimeout(function () {\n colorgrid()\n }, 200);\n }\n}\n\nfunction initSimGrid(grid){\n for(i=0;i<100;i++){\n for(j=0;j<100;j++){\n let p = Math.random();\n if(p < 0.7){\n grid[i][j] = new tree();\n }\n }\n }\n}\n\ninitCanvasGrid(canvasGrid)\n\nfunction updateTile(tile, color){\n tile.rectangle.beginFill(color);\n tile.rectangle.lineStyle(1,\"0x000000\",1);\n tile.rectangle.drawRect(tile.x,tile.y,pixelSize,pixelSize);\n tile.rectangle.endFill();\n app.stage.addChild(tile.rectangle)\n}\n\nfunction updateCanvasGrid(){\n //var s = Math.floor(Math.random()*256)//16777215)\n for(i=0;i<100;i++){\n for(j=0;j<100;j++){\n let x = canvasGrid[i][j];\n let y = simGrid[i][j];\n //console.log(\"update grid \" + i +\" - \"+j)\n //let color = \"0x\" + (s).toString(16) + (i+100).toString(16) +(j+100).toString(16);\n //console.log(color);\n if(y === undefined){\n continue;\n }\n if(y.type === 'tree'){\n updateTile(x, y.color)\n }\n }\n }\n //renderer.render(stage)\n}\n\n\n//tile object constructor\nfunction tile(color,posX,posY){\n rec = new PIXI.Graphics()\n rec.beginFill(color);\n rec.lineStyle(1,\"0x000000\",1);\n rec.drawRect(posX,posY,pixelSize,pixelSize);\n rec.endFill();\n this.rectangle = rec;\n this.x = posX;\n this.y = posY;\n}\n\nfunction randomHexColor(){\n // random hex number\n return '0x'+Math.floor(Math.random()*16777215).toString(16)\n}\n\n//var timer = setInterval(test, 2000);\nfunction Get(yourUrl){\n var Httpreq = new XMLHttpRequest(); // a new request\n Httpreq.open(\"GET\",yourUrl,false);\n Httpreq.send(null);\n return Httpreq.responseText;\n}\n//var jsonmap = JSON.parse(Get(\"./mapdata2.json\"));\n//console.log(\"this is the author name: \"+json_obj.author_name);\n\nvar seaTiles = [];\nvar grassTiles = [];\nfunction colorgrid(){\n for(i=0; i<10000; i++){\n let x = Math.floor(i/100);\n let y = i%100;\n let color = \"0xff0000\";\n //console.log(x + \" \" + y + \" \" + color);\n let tile = canvasGrid[x][y];\n switch (mapdata[i]) {\n case 'urban':\n let grey = Math.floor(100 + Math.random()*50).toString(16);\n color = \"0x\" + grey + grey + grey\n break;\n case 'sea':\n seaTiles.push(i);\n color = \"0x0022\"+ Math.floor(155 + Math.random()*100).toString(16);\n break;\n case 'sand':\n color = \"0xff\" + Math.floor(155 + Math.random()*100).toString(16) + \"33\";\n break;\n case 'marsh':\n color = \"0x66\" + Math.floor(100 + Math.random()*100).toString(16) +\"55\"\n break;\n case 'grass':\n grassTiles.push(i)\n color = \"0x00\" + Math.floor(50 + Math.random()*100).toString(16) + \"00\"\n break;\n default:\n color = \"0xff0000\"\n\n }\n //canvasGrid[x][y] = new tile(color,x*pixelSize,y*pixelSize);\n updateTile(tile, color)\n }\n //renderer.render(stage)\n}\n\nvar stepCounter = 0;\nfunction nextStep(){\n // update step counter\n stepCounter += 1;\n let c = document.getElementById(\"step\")\n c.style.fontWeight = 700\n c.innerText = stepCounter;\n // move things\n hashMap.forEach(function(value,key){\n value.step()\n });\n}\n\n\nvar inter;\nfunction start(){\n inter = setInterval(function () {\n nextStep()\n }, 500);\n}\n\nfunction stop(){\n clearInterval(inter);\n}\n" } ]
5
ramalingareddy2/alation-task
https://github.com/ramalingareddy2/alation-task
ea339e5d89be310ef3a4f95e3bc3007eba5fc45f
8822db7af4fc25b580e0550c17ed342d54f0cb0d
e056a829aae4c24abd421794eeef254dec7352b6
refs/heads/main
2023-04-14T13:38:08.304815
2021-04-26T13:46:50
2021-04-26T13:46:50
361,762,940
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.767123281955719, "alphanum_fraction": 0.767123281955719, "avg_line_length": 23.5, "blob_id": "c0884ed4c1ced08b318a84ade198f6444030e559", "content_id": "8380b73e5465eea561b27d8691d8cb1a0a059051", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 146, "license_type": "no_license", "max_line_length": 74, "num_lines": 6, "path": "/alation-test.py", "repo_name": "ramalingareddy2/alation-task", "src_encoding": "UTF-8", "text": "# Function to curl load balancer endpoint and return web server ip address\n\n# Function to bring down web server, with input (ip address)\n\n\n# Tests" }, { "alpha_fraction": 0.7137339115142822, "alphanum_fraction": 0.724678099155426, "avg_line_length": 50.21977996826172, "blob_id": "8ba125a766c252a8125ac04ec660d210e6610e59", "content_id": "11a10e0cf1dd07eb7c54e146527a1e266927c10d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4660, "license_type": "no_license", "max_line_length": 344, "num_lines": 91, "path": "/README.md", "repo_name": "ramalingareddy2/alation-task", "src_encoding": "UTF-8", "text": "# Automating two-tier infrastructure provisioning through Ansible & Terraform\n\n## Technology stack\nAWS | Terraform | Ansible | Nginx | HAProxy\n:-------------------------:|:-------------------------:|:-------------------------:|:-------------------------:|:-------------------------:\n<img src=\"images/aws.png\" width=\"100\"> | <img src=\"images/terraform.png\" width=\"100\"> | <img src=\"images/ansible.png\" width=\"100\"> | <img src=\"images/nginx.png\" width=\"100\"> | <img src=\"images/haproxy.png\" width=\"100\"> \n---\n## Motivation\nAs part of interview process with Alation...(fill in text)\n\n---\n## Requirements\nThis guide assumes the user is running a WindowsOS with the following software installed and configured:\n\n| Software | Version |\n| ------------- | ------------- |\n| Git CLI | >= 2.3 |\n| Terraform | >= 0.14 |\n| AWS CLI | >= 2.0 (**with credentials configured**) |\n\n\nFor Git CLI installation, [this guide](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) will be helpful.\n\nFor Terraform, there are [various ways to install the binary on Windows](https://learn.hashicorp.com/tutorials/terraform/install-cli). For simplicity sake, you can download the updated zipped package and add the unzipped binary's path to your `PATH`.\n\nFor AWS CLI, you may follow this [guide to install AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2-windows.html) using the MSI installer.\n<br><br>\n\n---\n## Set-up & Configurations\nBefore we're able to deploy our resources, there are some set-up steps required. These steps are not recommended to be automated as they do not conform to best practices from a security and reliability perspective.\n\n### Creating a region-specific key pair on AWS console\nOn your favourite browser, [log in to your AWS account](https://aws.amazon.com/console/) and access the EC2 page. Since key pairs are region-specific, select the region you plan to deploy AWS resources at the top right hand corner. For the purpose of this demonstration, we are using ```US East (N. Virginia) us-east-1``` as the default region.\n\n1. Select ```US East (N. Virginia) us-east-1``` as your region at top right corner.\n\n2. Access the ```Key Pairs``` tab on the left-most pane under ```Network & Security```. \n\n3. Click ```Create Key Pair```. Give your key pair an acceptable name, select File Format as ```pem```, and proceed to create the key pair. This will create your Key Pair resource and automatically download the {your-key-pair-name}.pem file which we can use to attach to our EC2 instances for OpenSSH access. \n\n4. Copy ```{your-key-pair-name}.pem``` file to both the terraform folder as ```terraform/{your-key-pair-name}.pem``` and ansible folder as ```ansible/{your-key-pair-name}.pem```.\n\n5. Edit the ```key_pair``` variable in ```terraform/terraform.tfvars``` file to your key pair name ```your-key-pair-name```.\n\nYou're all set!\n\n> Note: Since key pairs are region-specific, trying to deploy your EC2 resources in a region without the configured key pair will fail.\n\n<br>\n\n---\n\n## Infrastructure deployment\n\nUsing git bash, clone this repository and cd into the terraform folder.\n```bash\ngit clone https://github.com/ramalingareddy2/alation-task.git\ncd alation-task/terraform\n```\n\nRun the terraform initialize command to initialize the working directory containing Terraform configuration files. It is safe to now run the plan command to view our infrastructure plan and check if there are any misconfigured resources. (Note: This doesn't provision anything yet)\n\nSince we're using AWS as the provider, Terraform interacts with the AWS CLI and deploys the infrastructure with our configured AWS account. Run the terraform apply command to apply all changes and start up our defined cloud services. \n```bash\nterraform init\nterraform plan\nterraform apply -auto-approve # Only run this when you're sure of provisioning infrastructure\n```\nTerraform will proceed to spin up our cloud resources using AWS CLI, \n\n---\n\n## Pitfalls\n1. There should be one public subnet and two private subnets\n-- Web servers should be in private subnet and not allow inbound web traffic\n-- Web servers should be allowed to connect to Internet for apt update / upgrade (NAT gateway?)\n-- \n\n2. Web server count should be dynamic. \n-- Spin up multiple web servers based on count variable\n-- Store list of public and private IPs to hosts for ansible\n\n3. AWS AMI should be dynamic. Pull Ubuntu v20 AMI based on region.\n\n4. Ansible playbook only for ubuntu v20. Should make it for RHEL / CentOS too\n\n\n## References\n\nDynamic inventory hosts: https://stackoverflow.com/questions/45489534/best-way-currently-to-create-an-ansible-inventory-from-terraform" } ]
2
ravi2708/Sample-login-using-python
https://github.com/ravi2708/Sample-login-using-python
3217be34cafff572e3dfd44aa08b53a94c882cdb
b65800e63c9ca0de09c1c0e067c1dc628c51919c
127da9da294c1a7549477851de948a994a9ecc95
refs/heads/master
2022-11-23T07:49:46.330282
2020-08-03T14:29:07
2020-08-03T14:29:07
284,720,661
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7887324094772339, "alphanum_fraction": 0.7887324094772339, "avg_line_length": 70, "blob_id": "10def63e38e2461e3d867ee59acea99e6c5c35a3", "content_id": "15cc706accd81a06c8c39e6a0d52b85e9f48392d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 142, "license_type": "no_license", "max_line_length": 113, "num_lines": 2, "path": "/README.md", "repo_name": "ravi2708/Sample-login-using-python", "src_encoding": "UTF-8", "text": "# Sample-login-using-python\nCreate a database named \"projectloginpage\" and in that create a table named \"people\" as shown in the login image.\n" }, { "alpha_fraction": 0.5543246865272522, "alphanum_fraction": 0.6007669568061829, "avg_line_length": 20.371429443359375, "blob_id": "243af8e41d9578956686d33e6558751fbfa85309", "content_id": "059551c9e0d4cff430a145dd43f08e25bc36d059", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2347, "license_type": "no_license", "max_line_length": 102, "num_lines": 105, "path": "/login.py", "repo_name": "ravi2708/Sample-login-using-python", "src_encoding": "UTF-8", "text": "from tkinter import *\r\nimport mysql.connector\r\n\r\n\r\nmydb= mysql.connector.connect(host=\"localhost\", user=\"root\", password=\"\", database=\"projectloginpage\")\r\ncursor= mydb.cursor()\r\n\r\ndef addpeople():\r\n fullname = e5.get()\r\n username = e3.get()\r\n password = e4.get()\r\n\r\n sql = \"INSERT INTO people VALUES(%s, %s, %s)\"\r\n cursor.execute(sql,(fullname, username, password))\r\n mydb.commit()\r\n print(\"Person added\")\r\n return True\r\n\r\ndef displaypeople():\r\n username = e1.get()\r\n password = e2.get()\r\n sql = \"SELECT * FROM people WHERE username = %s and password = %s\"\r\n cursor.execute(sql,(username, password))\r\n result = cursor.fetchall()\r\n if not result:\r\n print(\"Wrong username or password\")\r\n else:\r\n print(\"You are logged in\")\r\n\r\n\r\ndef Login():\r\n\r\n window1 = Tk()\r\n window1.title(\"LOGIN\")\r\n window1.geometry(\"500x300\")\r\n global e1,e2\r\n\r\n l1 = Label(window1,text= \"Login System\", font=\"Arial\", bg=\"black\", fg=\"White\")\r\n l1.grid()\r\n\r\n f1=Frame(window1)\r\n l2=Label(f1,text=\"USERNAME\")\r\n e1=Entry(f1)\r\n l3=Label(f1,text=\"Password\")\r\n e2=Entry(f1)\r\n\r\n l2.grid(column=1,row=1)\r\n e1.grid(column=2,row=1)\r\n l3.grid(column=1,row=2)\r\n e2.grid(column=2,row=2)\r\n\r\n s2 = Button(window1, text=\"Login\", command=displaypeople)\r\n\r\n f1.grid()\r\n s2.grid()\r\n\r\n\r\n window1.mainloop()\r\n\r\ndef Signup():\r\n window2 = Tk()\r\n window2.title(\"SIGNUP\")\r\n window2.geometry(\"500x300\")\r\n global e3,e4,e5\r\n\r\n l5 = Label(window2, text=\"SIGN UP\", font=\"Arial\", bg=\"black\", fg=\"White\")\r\n l5.grid()\r\n\r\n f2=Frame(window2)\r\n l8=Label(f2,text=\"Fullname\")\r\n e5=Entry(f2)\r\n l6=Label(f2,text=\"USERNAME\")\r\n e3=Entry(f2)\r\n l7=Label(f2,text=\"Password\")\r\n e4=Entry(f2)\r\n\r\n l8.grid(column=1,row=0)\r\n e5.grid(column=2,row=0)\r\n l6.grid(column=1,row=1)\r\n e3.grid(column=2,row=1)\r\n l7.grid(column=1,row=2)\r\n e4.grid(column=2,row=2)\r\n\r\n s1=Button(window2, text=\"Submit\", command=addpeople)\r\n\r\n f2.grid()\r\n s1.grid()\r\n\r\n window2.mainloop()\r\n\r\n\r\nwindow = Tk()\r\nwindow.title(\"LOGIN\")\r\nwindow.geometry(\"500x300\")\r\n\r\nl4=Label(window,text=\"Do you want to:\", font=\"Arial\")\r\nl4.grid()\r\nb1=Button(window,text=\"Login\",command=Login)\r\nb1.grid()\r\nb2=Button(window,text=\"Sign Up\", command=Signup)\r\nb2.grid()\r\n\r\n\r\n\r\nwindow.mainloop()" } ]
2
tchaly-bethmaure/ProjetGrid
https://github.com/tchaly-bethmaure/ProjetGrid
ae8531fe5ba2095c441c4adaea145f364a9b6a06
b90615318134a1e9d17fa41dd47b6832cf728964
c8f145b19c50685351c8303d56d9153bab1ee6cc
refs/heads/master
2021-01-10T20:25:59.732344
2014-07-24T12:20:47
2014-07-24T12:20:47
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5454545617103577, "alphanum_fraction": 0.5454545617103577, "avg_line_length": 21, "blob_id": "7824b645a0c9c9036316a7f18d1ff95dfea8b2a9", "content_id": "2344319264b278d4dfae0bf168fab85c72dd0d60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22, "license_type": "no_license", "max_line_length": 21, "num_lines": 1, "path": "/script/__init__.py", "repo_name": "tchaly-bethmaure/ProjetGrid", "src_encoding": "UTF-8", "text": "__author__ = 'tchaly'\n" }, { "alpha_fraction": 0.5798653364181519, "alphanum_fraction": 0.5843550562858582, "avg_line_length": 36.121795654296875, "blob_id": "0b354f07469cd51015d129e2fb828838e7a3a2f4", "content_id": "05a622cb863853565a8a0d951abaaa015f25466e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5791, "license_type": "no_license", "max_line_length": 127, "num_lines": 156, "path": "/Tools/ScriptBrowser.py", "repo_name": "tchaly-bethmaure/ProjetGrid", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# imports\nfrom Model.Script import Script\nfrom Tools.Prompter import Prompter\nfrom Tools.CmdLineExplorer import CmdLineExplorer\nfrom Tools.JobExecutor import JobExecutor\n\n##\n#\nclass ScriptBrowser(Prompter, object):\n ## available choices for menu\n choix_menu = {\n 1: \"Add a script to queue\",\n 2: \"Delete a script from queue\",\n 3: \"Next step\"\n }\n ## available choices for folder mode selection\n choix_folder_mode = {\n 1: \"Add a script located in this folder\",\n 2: \"Parent folder\",\n 3: \"Go in a specific folder\",\n 4: \"Previous menu\"\n }\n ## available choices for file removing\n choix_deletion_mode = {\n 1: \"Delete file from stack\",\n 2: \"Previous menu\"\n }\n\n question = \"Choose an action among those : \"\n\n ## constructor\n def __init__(self, init_root):\n super(ScriptBrowser, self).__init__()\n self.file_exec = []\n self.initial_root = init_root\n\n ## display script stack\n def display_stack(self):\n self.print_msg(\"######## Current script stack : \")\n string_to_print = \"[ \"\n i = 0\n while i < len(self.file_exec):\n script_object = self.file_exec[i]\n if i != 0:\n string_to_print += \", \" + str(script_object)\n else:\n\n string_to_print += str(script_object)\n i += 1\n string_to_print += \" ]\"\n self.print_msg(string_to_print)\n\n ## launch the prompt menu\n def prompt_menu(self):\n choix_utilisateur = \"-1\"\n\n while choix_utilisateur != \"3\":\n self.clear_screen()\n self.display_stack()\n self.print_msg(\"\") # saut de ligne\n choix_utilisateur = self.prompt_choice(ScriptBrowser.question, ScriptBrowser.choix_menu.itervalues())\n self.print_option_choosen(choix_utilisateur, ScriptBrowser.choix_menu)\n\n self.press_a_key_continue()\n\n # Mode : menu d'exploration de dossier et ajout de script dans la file.\n if choix_utilisateur == \"1\":\n self.prompt_folder_mode()\n # Mode : menu de suppression de fichier.\n if choix_utilisateur == \"2\":\n self.prompt_stack_deletion_mode()\n\n ## launch the prompter for folder selection\n def prompt_folder_mode(self):\n choix_utilisateur = \"-1\"\n file_explorer = CmdLineExplorer(self.initial_root)\n\n while choix_utilisateur != \"4\":\n self.clear_screen()\n self.display_stack()\n self.print_msg(\"\\n######## Current folder : \" + file_explorer.current_path)\n file_explorer.display_folder_information()\n self.print_msg(\"\")\n choix_utilisateur = self.prompt_choice(ScriptBrowser.question, ScriptBrowser.choix_folder_mode.itervalues())\n self.print_option_choosen(choix_utilisateur, ScriptBrowser.choix_folder_mode)\n\n # add a script\n if choix_utilisateur == \"1\":\n file = self.prompt_question(\"Which file to stack ?\")\n if file_explorer.is_in_folder(file) and file_explorer.is_a_file(file_explorer.current_path + \"/\" + file):\n tool = self.prompt_question(\"With which tool do you want to execute this tool ?\")\n self.add_script_in_stack(file, tool, file_explorer.current_path + \"/\" + file)\n\n # go to a specific folder\n if choix_utilisateur == \"3\":\n folder = self.prompt_question(\"In which folder would you like to go into ?\")\n if file_explorer.is_in_folder(folder) and file_explorer.is_a_folder(file_explorer.current_path + \"/\" + folder):\n file_explorer.go_forward(folder)\n\n self.press_a_key_continue()\n\n # go back to the parent folder\n if choix_utilisateur == \"2\" or choix_utilisateur == \"cd ..\":\n file_explorer.go_backward()\n\n ## launch the prompter for removing file from stack\n def prompt_stack_deletion_mode(self):\n choix_utilisateur = \"-1\"\n\n while choix_utilisateur != \"2\":\n self.clear_screen()\n self.display_stack()\n self.print_msg(\"\")\n choix_utilisateur = self.prompt_choice(ScriptBrowser.question, ScriptBrowser.choix_deletion_mode.itervalues())\n self.print_option_choosen(choix_utilisateur, ScriptBrowser.choix_deletion_mode)\n\n # the user want to remove a file\n if choix_utilisateur == \"1\":\n file = self.prompt_question(\"Which file to delete from stack ?\")\n file_deleted = False\n for script in self.file_exec:\n if script.intitule == file:\n self.delete_scrit_from_stack(script)\n file_deleted = True\n if not file_deleted:\n self.print_output_msg(\"File hasn't been found.\")\n self.press_a_key_continue()\n self.prompt_menu()\n\n ## add the specified script into the stack\n def add_script_in_stack(self, file_name, tool, file_full_path):\n s = Script(file_name, tool, file_full_path)\n self.file_exec.append(s)\n self.print_output_msg(\"Script has been added.\")\n\n ## delete the specified script from the stack\n def delete_scrit_from_stack(self, element_object):\n self.file_exec.remove(element_object)\n self.print_output_msg(\"Script has been deleted.\")\n\n## test\ndef test():\n sbp = ScriptBrowser()\n # Options selection\n sbp.prompt_menu()\n #for script in sbp.file_exec:\n # print script.intitule\n exe = JobExecutor()\n exe.executeScripts(sbp.file_exec, \"node0\")\n\n## launch test\nif __name__ == \"__main__\":\n test()\n" }, { "alpha_fraction": 0.7530864477157593, "alphanum_fraction": 0.7530864477157593, "avg_line_length": 26, "blob_id": "676d481375a96d92cda8f5483e82edcf0a31c302", "content_id": "ebc20ae0cd9a8d71b5b67efdb2cc6964cb83789a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 165, "license_type": "no_license", "max_line_length": 73, "num_lines": 6, "path": "/README.md", "repo_name": "tchaly-bethmaure/ProjetGrid", "src_encoding": "UTF-8", "text": "ProjetGrid\n==========\n\nProjet grille et grappe sur l'API ClusterShell\nRéalisé en python\nTravaux découlant des enseignements de l'intervenant P. Lucas (Univ' Evry).\n" }, { "alpha_fraction": 0.5678284168243408, "alphanum_fraction": 0.5699731707572937, "avg_line_length": 28.125, "blob_id": "4118fe8d08e2da230593a9232b57f740a471cbc6", "content_id": "c14c614450659ee3fa42b6e05bacf2f84abe28b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1865, "license_type": "no_license", "max_line_length": 96, "num_lines": 64, "path": "/Model/Nodes.py", "repo_name": "tchaly-bethmaure/ProjetGrid", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# imports\nimport sys\nfrom ClusterShell.NodeSet import NodeSet\nfrom ClusterShell.Task import task_self\nfrom ClusterShell.NodeSet import NodeSetException\n\n##\n#\nclass Nodes:\n\n ## initialize the object\n def __init__(self, nodeset):\n # the node set\n self.ns = nodeset\n # active nodes\n self.ns_ok = NodeSet()\n # inactive or inexisting nodes\n self.ns_ko = NodeSet()\n \n ## add the specified node\n def add(self, node):\n self.ns |= NodeSet.fromlist(node)\n\n ## delete the specified node\n def delete(self, node):\n self.ns -= NodeSet.fromlist(node)\n\n ## check if the submitted nodes are active\n def checkNodes(self):\n try:\n # print command info\n print '\\n== Checking active nodes =='\n # launch ping on the specified nodes\n task_self().run('echo OK', nodes=self.ns)\n # retrieve and check return code\n for retcode, nodes in task_self().iter_retcodes():\n if retcode in (0, 1, 2):\n # add nodes to OK set\n self.ns_ok |= NodeSet.fromlist(nodes)\n print '%s : OK' % nodes\n else:\n # add nodes to KO set\n self.ns_ko |= NodeSet.fromlist(nodes)\n print '%s : KO' % nodes\n # syntax error\n except NodeSetException:\n print >> sys.stderr, '(!) Error : the submitted nodeset [%s] is not valid' % self.ns\n\n ## get all submitted nodes (include invalid)\n def getAllNodes(self):\n return self.ns\n\n ## retrieve the active nodes \n def getActiveNodes(self):\n return self.ns_ok\n\n## check and retrieve active nodes\ndef filter_disfunctional_nodes(ns):\n n = Nodes(ns)\n n.checkNodes()\n return n.getActiveNodes()\n\n" }, { "alpha_fraction": 0.6076977252960205, "alphanum_fraction": 0.6087570786476135, "avg_line_length": 30.10988998413086, "blob_id": "713ce7feb2d447fdf59ee037e19ddbd28b12f682", "content_id": "6b1541cc763fc439f71ae2e4b0637a21e00c8b34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2832, "license_type": "no_license", "max_line_length": 124, "num_lines": 91, "path": "/View/IHM.py", "repo_name": "tchaly-bethmaure/ProjetGrid", "src_encoding": "UTF-8", "text": "#! /usr/bin/python\n\n# imports\nimport os\nimport sys\nfrom Model.Nodes import Nodes\nfrom Model.ConfFileManager import ConfFileManager\nfrom Tools.ScriptBrowser import ScriptBrowser\nfrom Tools.NodeBrowser import NodeBrowser\nfrom Tools.Prompter import Prompter\nfrom Tools.JobExecutor import JobExecutor\n\n##\n#\nclass IHM(Prompter):\n\n ## constructor\n def __init__(self):\n # the task executor\n self.exe = JobExecutor()\n\n ## a GUI for static mode execution\n def staticMode(self, nodes, service, action):\n # check and retrieve active nodes\n ns = Nodes(nodes)\n ns.checkNodes()\n ns_ok = ns.getActiveNodes()\n\n # execute the specified service\n self.exe.executeService(ns_ok, service, action)\n\n ## a GUI for conf file processing and execution\n def fileConfigMode(self, fileName):\n # instantiate the conf file manager\n s = ConfFileManager(None, None, None)\n try:\n # launch it\n s.executeFromFile(fileName)\n # catch Ctrl + C\n except KeyboardInterrupt :\n print '\\n Bye bye !\\n'\n sys.exit(1)\n\n ## a GUI for nodes and service browsing and execution\n def interactiveMode(self):\n # clear screen\n os.system('clear')\n print '\\n== Welcome to Clustershell ! =='\n\n # browse node\n nbp = NodeBrowser()\n nbp.promptMenu()\n\n # browse service and action\n nbp.submitService()\n nbp.submitAction()\n \n # retrieve active nodes and execute\n self.exe.executeService(nbp.ns, nbp.service, nbp.action) \n\n ## a GUI for scripts browsing and execution\n def fullInteractiveMode(self):\n # clear screen\n os.system('clear')\n print '\\n== Welcome to Clustershell ! =='\n\n # browse nodes\n nbp = NodeBrowser()\n nbp.promptMenu()\n \n try:\n # browse script\n sbp = ScriptBrowser(self.prompt_question(\"Script root folder ?\"))\n sbp.prompt_menu()\n # catch Ctrl + C\n except KeyboardInterrupt :\n print '\\n Bye bye !\\n'\n sys.exit(1)\n\n # execute the script to the specified nodes\n self.exe.executeScripts(sbp.file_exec, nbp.ns)\n\n ## display error msg if invalid arguments\n def displayErrorMsg(self):\n \n print >> sys.stderr,'\\n== Error : invalid arguments =='\n print >> sys.stderr,'=> Right syntax for static mode : python Launcher.py -s <nodeset> <service> <action>'\n print >> sys.stderr,'=> Right syntax for conf file mode : python Launcher.py -f <filename>'\n print >> sys.stderr,'=> Right syntax for interactive mode : python Launcher.py -i'\n print >> sys.stderr,'=> Right syntax for full interactive mode : python Launcher.py -fi'\n exit(1)\n\n" }, { "alpha_fraction": 0.5090909004211426, "alphanum_fraction": 0.5130909085273743, "avg_line_length": 33.79747009277344, "blob_id": "4e5840161192f6eabe7a7adba9c2450ad57eb85b", "content_id": "cebac1508757ecb284a120cdc717e90c8f45fcf5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2750, "license_type": "no_license", "max_line_length": 146, "num_lines": 79, "path": "/Model/ConfFileManager.py", "repo_name": "tchaly-bethmaure/ProjetGrid", "src_encoding": "UTF-8", "text": "#! /usr/bin/python\n\n# imports\nimport sys\nfrom Model.Nodes import Nodes\nfrom Tools.JobExecutor import JobExecutor\nfrom ClusterShell.NodeSet import NodeSet\nfrom ClusterShell.Task import task_self\n\n##\n#\nclass ConfFileManager:\n\n ## constructor (noeuds, service et action)\n def __init__(self, ns, service, action):\n # check params\n if(ns is not None and service is not None and action is not None):\n self.ns = NodeSet(ns) \n self.service = service \n self.action = action # <start|stop|restart|status>\n else:\n self.ns = None\n self.service = ''\n self.action = ''\n # the service executor \n self.executor = JobExecutor()\n\n ## parse the file and execute it\n def executeFromFile(self,nom_fichier):\n\tfichier = open(nom_fichier,'r')\n line = ''\n\tfor ligne in fichier.readlines():\n # remove blanks\n\t line = ligne.replace(' ','')\n # check if not empty => prevent parsing error\n if str(line) > 0 and line[0] != '\\n' and line[0] != '#':\n # parse line \n\t\tself.executeFromLine(line)\n # close the file\n\tfichier.close()\n\n ## parse the line and execute it\n def executeFromLine(self,line):\n # the error message to be printed\n\terror_len_3 = 'Error : configuration file usage is <set of services>::<set of nodes>::<action>[-> <set of services>::<set of nodes>::<action>]\\n'\n # the node set\n self.ns = None\n\tcommande = ''\n\t# ignore comment or empty lines\n if line == '' or line[0] == '#':\n pass\n else:\n # retrieve each block \n for bloc_dependance in line.split('->'):\n # retrieve each item\n split = bloc_dependance.split('::')\n\n # parse error\n if len(split) != 3:\n print '%s' % error_len_3\n exit(1)\n # retrieve services, nodes and action\n services = split[0]\n nodes = split[1]\n self.action = split[2].replace('\\n','')\n\n print '***************************************'\n print '* Handling \\'%s\\' *' % bloc_dependance\n print '***************************************'\n # check nodes\n nodeList = Nodes(nodes)\n nodeList.checkNodes()\n # update node list\n self.ns = nodeList.getActiveNodes()\n \n # execute each service for the specified nodes\n for service in services.split(','):\n self.service = service\n self.executor.executeService(self.ns, self.service, self.action)\n\n" }, { "alpha_fraction": 0.6731634140014648, "alphanum_fraction": 0.6821589469909668, "avg_line_length": 28, "blob_id": "ff9f32ec27b20e2a5541de9dadb64e6f68138f4d", "content_id": "d25676f6cdb1288335d6bd2e067c26fb3253c0c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 670, "license_type": "no_license", "max_line_length": 81, "num_lines": 23, "path": "/script/zip.py", "repo_name": "tchaly-bethmaure/ProjetGrid", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\n\n# variables utilisées\nname_of_file = \"tail5authlog\"\ndefault_path = \"/root/scpy\"\nstorage_remote_name = \"supervisor\"\n\nprint(\"Installing 7zip if needed.\")\nos.system(\"apt-get install -yq p7zip\")\n\nprint(\"Zipping this file.\")\nos.system(\"7z a \"+ default_path +\"/logfile.7z \"+ default_path +\"/\"+ name_of_file)\n\nprint(\"Removing original file : \" + name_of_file)\nos.system(\"rm \"+default_path+\"/\"+name_of_file)\n\n# marche, mais à tenter si la config du réseau est stable\n#print(\"Fetch it on remote storage : \"+storage_remote_name+\".\")\n#os.system(\"clush -w \"+ storage_remote_name +\" --copy \"+ default_path)\n\nprint(\"Done.\")\n" }, { "alpha_fraction": 0.5587467551231384, "alphanum_fraction": 0.5757180452346802, "avg_line_length": 25.413793563842773, "blob_id": "9b4490691e75fafc425c89b816c1f67e92f055c9", "content_id": "fa7792f00f9121e0094ca4c3a727f4841493a859", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 766, "license_type": "no_license", "max_line_length": 81, "num_lines": 29, "path": "/launcher.py", "repo_name": "tchaly-bethmaure/ProjetGrid", "src_encoding": "UTF-8", "text": "#! /usr/bin/python\n\nimport sys\nfrom View.IHM import IHM\n\nif __name__ == '__main__':\n\n # instantiate the GUI\n view = IHM()\n\n # check params and launch the appropriate mode\n if len(sys.argv) == 5 and (sys.argv[1] == '-s' or sys.argv[1] == '--static'):\n # launch static mode\n view.staticMode(sys.argv[2], sys.argv[3], sys.argv[4])\n\n elif len(sys.argv) == 3 and sys.argv[1] == '-f':\n # launch conf mode\n view.fileConfigMode(sys.argv[2])\n\n elif len(sys.argv) == 2 and sys.argv[1] == '-i':\n # launch interactive mode\n view.interactiveMode()\n\n elif len(sys.argv) == 2 and sys.argv[1] == '-fi':\n # launch full interactive mode\n view.fullInteractiveMode()\n\n else:\n view.displayErrorMsg()\n" }, { "alpha_fraction": 0.6812227368354797, "alphanum_fraction": 0.6986899375915527, "avg_line_length": 21.899999618530273, "blob_id": "c6faf96fc1dd15f3adcd497e33cace038e9ad615", "content_id": "ad0defc6d563c943c000d534520b4c4340b081be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 229, "license_type": "no_license", "max_line_length": 80, "num_lines": 10, "path": "/script/get_log.sh", "repo_name": "tchaly-bethmaure/ProjetGrid", "src_encoding": "UTF-8", "text": "#! /bin/bash\necho \"\"\necho \"Get 5 first line of auth log and storing them into a 'tail5authlog' file.\"\n# file : a changer si besoin\npath=/root/scpy\nfile=tail5authlog\ncd $path\ntail -5 /var/log/auth.log > $file\necho \"Done.\"\necho \"\"\n" }, { "alpha_fraction": 0.5195484757423401, "alphanum_fraction": 0.5236784219741821, "avg_line_length": 32.94392395019531, "blob_id": "8bde5df17b97158b4617c9c874d0a18cc1ea4613", "content_id": "5a9ac3f1ff554ae2bcb883b4016976b007967534", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3632, "license_type": "no_license", "max_line_length": 119, "num_lines": 107, "path": "/Tools/NodeBrowser.py", "repo_name": "tchaly-bethmaure/ProjetGrid", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# imports\nimport sys\nfrom ClusterShell.NodeSet import NodeSet\nfrom ClusterShell.NodeSet import NodeSetException\nfrom Model.Nodes import Nodes\nfrom Tools.Prompter import Prompter\n\n##\n#\nclass NodeBrowser(Prompter):\n\n ## constructor\n def __init__(self):\n self.ns = NodeSet()\n self.service = ''\n self.action = ''\n\n ## launch the prompt menu\n def promptMenu(self):\n try:\n # launch the prompter for node selection\n self.submitNodeList()\n # catch Ctrl + C\n except KeyboardInterrupt :\n print '\\n Bye bye !\\n'\n sys.exit(1)\n \n ## ask the user to submit the node list\n def submitNodeList(self):\n # info msg\n print '\\n# Step 1 of 3 : Please enter nodes name below (using the clustershell syntax <azur1>, <azur[1-2]>) :' \n # retrieve keyboard input\n try:\n self.ns = NodeSet(self.input_request(''))\n repeat = True\n \n # ask if the user wants to add another node/node group\n while repeat :\n # print added nodes\n for node in self.ns:\n print 'node : %s' % node\n # user want to add nodes ?\n print '\\n### Add nodes ? (yes | no)'\n # retrieve answer\n ans = self.input_request('')\n # check the ans\n if ans == 'Yes' or ans == 'Y' or ans == 'y' or ans == 'yes':\n print '### Please enter the node/group list below : '\n # retrieve and append nodes\n self.ns.add(self.input_request(''))\n # the user don't want to add additionnal nodes\n else:\n # unset flag\n repeat = False\n # check submitted nodes\n self.ns = self.checkSubmittedNodes(self.ns)\n\n # invalid submitted node list / syntax error\n except NodeSetException :\n print >> sys.stderr, '\\n(!) Error : the submitted node list is not valid\\n' % self.ns\n\n ## retrieve the service to be performed\n def submitService(self):\n\n # specify the service\n print '\\n# Step 2 of 3: Please enter the service to be launched'\n self.service = self.input_request('')\n \n ## retrieve the action to be performed\n def submitAction(self):\n # choose action to be executed\n print '\\n# Step 3 of 3 : Please choose the action to perform '\n actionList = ['start','stop','restart','status']\n self.print_choice(actionList)\n\n # flag for the prompter\n repeat = True \n # retrieve user's choice\n while repeat :\n # show prompter\n choice = self.input_request('')\n if choice == '1' or choice == 'start':\n self.action = 'start'\n repeat = False\n elif choice == '2' or choice == 'stop':\n self.action = 'stop'\n repeat = False\n elif choice == '3' or choice == 'restart':\n self.action = 'restart'\n repeat = False\n elif choice == '4' or choice == 'status':\n self.action = 'status'\n repeat = False\n else:\n print >> sys.stderr,'Error : invalid choice' \n\n ## check and retrieves ok nodes\n def checkSubmittedNodes(self, nodes):\n # create nodeset\n ns = Nodes(nodes)\n # ping nodes\n ns.checkNodes() \n # return active nodes\n return ns.getActiveNodes()\n" }, { "alpha_fraction": 0.5776481032371521, "alphanum_fraction": 0.580341100692749, "avg_line_length": 24.609195709228516, "blob_id": "bce074a2ded45ec0e2ecdadcd21b290dc31c41ab", "content_id": "4c5e2185d4f045c538f7e0df11c206c1df2d13b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2228, "license_type": "no_license", "max_line_length": 107, "num_lines": 87, "path": "/Tools/Prompter.py", "repo_name": "tchaly-bethmaure/ProjetGrid", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# imports\nimport os\n\n##\n#\nclass Prompter:\n\n ## constructor\n def __init__(self):\n pass\n\n ## list available choices\n def prompt_choice(self, question, iterable):\n self.print_question(question)\n self.print_choice(iterable)\n return self.input_request(\"choose an option (1, 2, 3, ...) ?\")\n\n ## ask a question\n def prompt_question(self, sentence):\n self.print_msg(\"\")\n self.print_question(sentence)\n return self.input_request(\" type here : \")\n\n ## ask the user to press a key to continue\n def press_a_key_continue(self):\n self.input_request(\"Press a key to continue...\")\n\n ## retrieve the user's choice\n def print_option_choosen(self, rep, liste):\n try:\n self.print_output_msg(\"You've choosen : \" + str(liste[int(rep)]))\n except:\n self.print_output_msg(str(rep) + \" is not in the list.\")\n\n ## print the user's choice\n def print_choice(self, iterable):\n i = 1\n for option in iterable:\n self.print_option(i, option)\n i += 1\n\n ## print option\n def print_option(self, number, msg):\n self.print_msg(str(number) + \") \" + msg)\n\n ## print question\n def print_question(self, msg):\n self.print_msg(\"? : \" + str(msg))\n\n ## print output msg\n def print_output_msg(self, msg):\n self.print_msg(\"\")\n self.print_msg(\"[Output] : \" + msg)\n return msg\n\n ## print the specified message\n def print_msg(self, msg):\n print(msg)\n\n ## prompter\n def input_request(self, msg):\n some_text = raw_input(\"-> \" + str(msg))\n return some_text\n\n ## clear the screen\n def clear_screen(self):\n os.system(\"clear\")\n\n\n## test\ndef test():\n p = Prompter()\n\n # the question\n p.print_output_msg(p.prompt_question(\"Is python a good language ?\"))\n\n # available choices\n list = [\"SUPAman doh\", \"Make me feel cool\", \"Back to the old scripting fashion time...\"]\n index = p.print_output_msg(p.prompt_choice(\"What's developping in Python makes you feel like ?\", list))\n p.print_option_choosen(index, list)\n\n## launch test\nif __name__ == \"__main__\":\n test()\n" }, { "alpha_fraction": 0.5449029207229614, "alphanum_fraction": 0.5467233061790466, "avg_line_length": 27.413793563842773, "blob_id": "3361a220066a10ce2b211f163491b5fd1bca8f5b", "content_id": "8be109e122837efbf0000a84e438969cf126e3b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3296, "license_type": "no_license", "max_line_length": 85, "num_lines": 116, "path": "/Tools/CmdLineExplorer.py", "repo_name": "tchaly-bethmaure/ProjetGrid", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# imports\nimport os\nfrom Prompter import Prompter\n\n##\n#\nclass CmdLineExplorer(Prompter, object):\n ## constructor\n def __init__(self, root_folder):\n super(CmdLineExplorer, self).__init__()\n # set paths\n self.initial_path = root_folder\n self.current_path = root_folder\n # set folder infos\n self.folder_information = \"\"\n self.set_folder_information()\n\n ## go to the specified folder\n def go_in_folder(self, folder_name):\n if folder_name != \"\":\n if folder_name == \"..\":\n self.go_backward()\n else:\n self.go_forward(folder_name)\n\n ## go the the folder\n def go_forward(self, folder):\n new_path = self.current_path\n if new_path != \"/\":\n new_path += \"/\"\n new_path += folder\n if self.is_a_folder(new_path):\n self.current_path = new_path\n self.set_folder_information()\n\n ## go back to the parent folder\n def go_backward(self):\n tab = str(self.current_path).split(\"/\")\n new_path = \"\"\n tab.reverse()\n\n while len(tab) != 1:\n element = tab.pop()\n if element != \"\":\n new_path += \"/\" + element\n if new_path != \"\":\n self.current_path = new_path\n else:\n self.current_path = \"/\"\n self.set_folder_information()\n\n ## set directory info\n def set_folder_information(self):\n try:\n self.folder_information = os.listdir(self.current_path)\n except:\n self.print_output_msg(\"No can't do.\")\n finally:\n pass\n\n ## display directory information\n def display_folder_information(self):\n self.print_msg(\"# List of files and folders : \")\n self.print_msg(\"\")\n j = 0\n to_print = \"\"\n for entity in self.folder_information:\n to_print += entity + \" \"\n if j == 6:\n j = 0\n to_print += \"\\n\"\n j += 1\n print to_print\n\n ## check if the specified file is in the current folder\n def is_in_folder(self, file_or_folder):\n if file_or_folder in self.folder_information:\n return True\n else:\n self.print_output_msg(file_or_folder + \" is not located in this folder.\")\n return False\n\n ## check if the specified file path is a directory\n def is_a_folder(self, folder_full_path):\n if os.path.isdir(folder_full_path):\n return True\n else:\n self.print_output_msg(\"Not a folder.\")\n\n ## check if the specified file path is a regular file\n def is_a_file(self, file_full_path):\n if os.path.isfile(file_full_path):\n return True\n else:\n self.print_output_msg(\"Not a file.\")\n\n## test the current class\ndef test():\n cle = CmdLineExplorer(\"/home/tchaly/EspaceDeTravail/Git\")\n #cle.display_folder_information()\n #cle.go_forward(\"ProjetGrid\")\n #cle.display_folder_information()\n #cle.go_backward()\n #cle.display_folder_information()\n\n while True:\n cle.go_backward()\n print cle.current_path\n cle.press_a_key_continue()\n\n## launch test\nif __name__ == \"__main__\":\n test()\n" }, { "alpha_fraction": 0.5307599306106567, "alphanum_fraction": 0.5313630700111389, "avg_line_length": 29.703702926635742, "blob_id": "83a523b3ae989e4c7bd1eb559f0c8f6db9dcfc87", "content_id": "fc901d2e6ff3b7733bb088231db58f2d3ef91017", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1658, "license_type": "no_license", "max_line_length": 76, "num_lines": 54, "path": "/Tools/JobExecutor.py", "repo_name": "tchaly-bethmaure/ProjetGrid", "src_encoding": "UTF-8", "text": "#! /usr/bin/python\n\n# imports\nfrom ClusterShell.NodeSet import NodeSet\nfrom ClusterShell.Task import task_self\nfrom Tools.Prompter import Prompter\n\n## class for executing commands\n#\nclass JobExecutor(Prompter):\n\n ## constructor\n def __init__(self):\n # task launcher\n self.task = task_self()\n\n ## execute a service\n def executeService(self, ns, service, action):\n # set command\n command = 'service ' + service + ' ' + action\n\n # print info message\n if action == 'start':\n print '\\n== Launching \\'%s\\' on [%s] ==' % (service, ns)\n elif action == 'stop':\n print '\\n== Stopping \\'%s\\' on [%s] ==' % (service, ns)\n elif action == 'restart':\n print '\\n== Restarting \\'%s\\' on [%s] ==' % (service, ns)\n elif action == 'status':\n print '\\n== Get status of \\'%s\\' on [%s] ==' % (service, ns)\n else:\n print 'Error : <action> must be start | stop | restart | status'\n exit(1)\n\n # run command\n self.task.run(command, nodes=ns)\n\n # handling output\n for output, nodes in self.task.iter_buffers():\n # agregate and print output\n print '%s : %s' % (nodes, output)\n # print blank line\n print ''\n\n ## execute the stack of jobs\n def executeScripts(self, stack, ns):\n for job in stack:\n self.task.run(job.tool + \" \" + job.path, nodes=ns)\n\n # handling output\n for output, nodes in self.task.iter_buffers():\n # agregate and print output\n print '%s : %s' % (nodes, output)\n print \"\"\n" }, { "alpha_fraction": 0.5717131495475769, "alphanum_fraction": 0.5717131495475769, "avg_line_length": 22.85714340209961, "blob_id": "d6cb6dc32a2d08614959bb15ba24b2f61c73ce47", "content_id": "5568835c49496ee12869b419fd7409d0e479d963", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 502, "license_type": "no_license", "max_line_length": 64, "num_lines": 21, "path": "/Model/Script.py", "repo_name": "tchaly-bethmaure/ProjetGrid", "src_encoding": "UTF-8", "text": "\n## class for handling scripts\n#\nclass Script(object):\n\n ## constructor\n def __init__(self, nom_script, tool_script, chemin_fichier):\n super(Script,self).__init__()\n # script name\n self.intitule = nom_script\n # tool\n self.tool = tool_script\n # script path\n self.path = chemin_fichier\n \n ## get script name\n def __str__(self):\n return self.intitule\n\n ## get script path\n def get_file_with_path(self):\n return self.path\n" } ]
14
falconmaf/stack-test
https://github.com/falconmaf/stack-test
34f987d56ceec41b3ada20a53d1a178a657d4d92
986f83acf94c56f40810330599d75fea6b790555
9367f66c90f44cba00929975e64f1cb19eb86764
refs/heads/main
2023-08-30T23:54:55.918732
2021-10-04T18:15:14
2021-10-04T18:15:14
413,430,187
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4548611044883728, "alphanum_fraction": 0.4548611044883728, "avg_line_length": 23, "blob_id": "3a040c9cb3687a623bc256e289e043294e31a9d1", "content_id": "ac9cffbbd1d3780575e50efffabb67966e653cca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 288, "license_type": "no_license", "max_line_length": 40, "num_lines": 12, "path": "/main.py", "repo_name": "falconmaf/stack-test", "src_encoding": "UTF-8", "text": "class dot:\n def __init__(self, *params, **keys):\n self.params = params\n self.keys = keys\n\n def log(self):\n if self.params:\n for p in self.params:\n print(p)\n if self.keys:\n for k in self.keys:\n print(k)\n" }, { "alpha_fraction": 0.761904776096344, "alphanum_fraction": 0.761904776096344, "avg_line_length": 20, "blob_id": "cecd35fb7d4c924a6538fe8819697e053132e1f8", "content_id": "b5ca4b714030e13cb26f24c9ae5b2cfecbffb8a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 63, "license_type": "no_license", "max_line_length": 48, "num_lines": 3, "path": "/README.md", "repo_name": "falconmaf/stack-test", "src_encoding": "UTF-8", "text": "# stack-test\n\nThis is just for testing new features in github.\n" } ]
2
RemiPapillier/Systeme_Expert
https://github.com/RemiPapillier/Systeme_Expert
9eeec1a52f4a24c09d8d1888608eef5a000e8245
c301429489f24bb6043c9f13bc2205ca334aa61a
f308525565bde059dfe071265234b3ac2e51c739
refs/heads/master
2022-09-17T20:10:40.295606
2020-05-26T09:55:40
2020-05-26T09:55:40
265,863,337
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7115789651870728, "alphanum_fraction": 0.7115789651870728, "avg_line_length": 38.66666793823242, "blob_id": "7207ef23644d043cfeeaa925777a973927dac31b", "content_id": "28b1f77414707fbb0e4ea85411b1c964855b6c44", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 476, "license_type": "no_license", "max_line_length": 103, "num_lines": 12, "path": "/pythonObjects/equation.py", "repo_name": "RemiPapillier/Systeme_Expert", "src_encoding": "UTF-8", "text": "#Premisse (avant le égal) Conclusion (apres le egal)\nclass Equation:\n\n #Constructeur qui prend en parametre la premisse et la conclusion de l'equation sous forme de liste\n #La premisse et la conclusion sont des attributs de l'objet equation\n def __init__(self, premisse, conclusion):\n self.premisse = premisse\n self.conclusion = conclusion\n\n #On vide l'attribut conclusion d'une equation\n def remove_conclusion(self):\n self.conclusion = []" }, { "alpha_fraction": 0.6191567182540894, "alphanum_fraction": 0.6200733184814453, "avg_line_length": 36.60344696044922, "blob_id": "f9827deacabd1f22e7571ed35ced5c9884a4401a", "content_id": "cb0f5b0bc810acad6058ad4ce735f86829e080ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2205, "license_type": "no_license", "max_line_length": 142, "num_lines": 58, "path": "/pythonObjects/main.py", "repo_name": "RemiPapillier/Systeme_Expert", "src_encoding": "UTF-8", "text": "from .hypothese import *\nfrom .systeme import *\nfrom .equation import *\n\n#Fonction principale appelée lorsqu'on appuie sur Start et qui prend en paramètre un dictionnaire de dictionnaire contenant toutes les données\ndef get_solution(myDic):\n #Initialisation d'un système et d'une hypothèse\n S = Systeme()\n H = Hypothese()\n\n #Boucle pour récupérer les faits dans l'hypothese\n hyp = myDic['0']['hypothese']\n for i in hyp:\n if i.isalpha():\n H.append_fact(i)\n\n #Boucle pour créer les equations avec leur premisse et conclusion puis ajoutant l'équation au systeme\n indice = len(myDic)\n for i in range(1, indice):\n prem, conc = myDic[str(i)]['premisse'], myDic[str(i)]['conclusion']\n #Récupération de la premisse de l'equation i\n premisse_list=[]\n for i in prem:\n if i.isalpha():\n premisse_list.append(i)\n #Récupération de la conclusion de l'equation i\n conclusion_list = []\n for j in conc:\n if j.isalpha():\n conclusion_list.append(j)\n #Création de l'equation et ajout au systeme\n S.append_equation(Equation(premisse_list, conclusion_list))\n\n #tour d'algorithme pour éliminer les conclusions s'il n'y a pas de premisse\n for e in S.systeme:\n if(not e.premisse and e.conclusion):\n e.remove_conclusion()\n\n #Algorithme principal pour récupérer la solution\n solution = []\n #Tant qu'on a des faits\n while H.facts:\n fait = H.first_item()\n #On parcours les equations du systeme\n for e in S.systeme:\n if(fait in e.premisse):\n e.premisse.remove(fait)\n #Condition qui permet d'éviter de relire une ligne dont on a déjà récupéré la conclusion\n if(not e.premisse and e.conclusion):\n for f in e.conclusion:\n H.append_fact(f)\n e.remove_conclusion()\n #Si le fait n'est pas deja dans la solution, on l'ajout\n if(fait not in solution):\n solution.append(fait)\n H.delete_first_item()\n #On renvoie la solution en chaine de caractere\n return(str(solution))\n\n" }, { "alpha_fraction": 0.607272744178772, "alphanum_fraction": 0.607272744178772, "avg_line_length": 21.95833396911621, "blob_id": "4696eabc9c099db8ba4258336ac6724233be1794", "content_id": "f7aadd216a45c80be7a205903c7e08aaf553af2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 550, "license_type": "no_license", "max_line_length": 58, "num_lines": 24, "path": "/app.py", "repo_name": "RemiPapillier/Systeme_Expert", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, request, jsonify\nfrom pythonObjects.main import *\n\napp = Flask(__name__)\n\[email protected]('/')\ndef index():\n\treturn render_template('home.html')\n\n\[email protected]('/solution', methods=['POST','GET'])\ndef solution():\n data = request.get_json()\n solution = get_solution(data)\n #Creation d'un string contenant les solutions\n str_sol = \"{ \"\n for i in solution:\n if i.isalpha():\n str_sol += str(i) + \" \"\n str_sol += \"}\"\n return str_sol\n\nif __name__ == '__main__':\n\tapp.run(debug=True)" }, { "alpha_fraction": 0.7197943329811096, "alphanum_fraction": 0.7197943329811096, "avg_line_length": 31.5, "blob_id": "caf45ddf8db5130653562c616d442a5f78e792a2", "content_id": "82100496f70e2f4bb4333f74836d652251d43007", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 394, "license_type": "no_license", "max_line_length": 137, "num_lines": 12, "path": "/pythonObjects/systeme.py", "repo_name": "RemiPapillier/Systeme_Expert", "src_encoding": "UTF-8", "text": "#Un certain nombre d'équations\nfrom .equation import *\n\nclass Systeme:\n\n #Constructeur par défaut qui initialise un attribut systeme correspondant à une liste vide qui sera ensuite composé d'objets Equation\n def __init__(self):\n self.systeme = []\n\n #Fonction pour ajouter une équation dans la liste systeme\n def append_equation(self, eq):\n self.systeme.append(eq)" }, { "alpha_fraction": 0.6723163723945618, "alphanum_fraction": 0.6760828495025635, "avg_line_length": 28.55555534362793, "blob_id": "8831950da11fde6bfe2cc4cd8487da65d973f96f", "content_id": "de0176d8dbb1b32c48d6c72b6b2b11c17459a1aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 535, "license_type": "no_license", "max_line_length": 101, "num_lines": 18, "path": "/pythonObjects/hypothese.py", "repo_name": "RemiPapillier/Systeme_Expert", "src_encoding": "UTF-8", "text": "#Comporte les faits\nclass Hypothese:\n\n #Constructeur par defaut de l'hypothese qui cree un attribut facts correspondant à une liste vide\n def __init__(self):\n self.facts = []\n\n #Fonction pour ajouter un fait à l'attribut\n def append_fact(self, fact):\n self.facts.append(fact)\n\n #Fonction pour récupérer le premier fait de la liste\n def first_item(self):\n return self.facts[0]\n\n #Fonction pour supprimer le premier fait de la liste\n def delete_first_item(self):\n del self.facts[0]" } ]
5
hnlee/colony_counting
https://github.com/hnlee/colony_counting
1246ce8cc40c27f486a30742fc7ac0fc7820c1b5
8168e3ddccb920f379e4930e321b694d4150deda
cfce5191bdf2be949c15642cdf24e64e9f5f1d7d
refs/heads/master
2020-04-13T01:07:28.049216
2013-05-23T20:57:32
2013-05-23T20:57:32
10,084,575
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6931818127632141, "alphanum_fraction": 0.6931818127632141, "avg_line_length": 21, "blob_id": "232cd5c1211a76cf48b6f85bfc8a1f3ebb1beaff", "content_id": "50e7d858aad6edf094dcdc620b456744ff0b82e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 88, "license_type": "no_license", "max_line_length": 54, "num_lines": 4, "path": "/README.md", "repo_name": "hnlee/colony_counting", "src_encoding": "UTF-8", "text": "colony_counting\n===============\n\nSemiautomated method of counting colonies from photos.\n" }, { "alpha_fraction": 0.6140725016593933, "alphanum_fraction": 0.6460554599761963, "avg_line_length": 18.5, "blob_id": "d2f967c3e8c2782aa5555d40a74e3202faeb2b40", "content_id": "a692efe67c1ee0d78c9aac299be51b6262914d02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 469, "license_type": "no_license", "max_line_length": 55, "num_lines": 24, "path": "/countpixels.py", "repo_name": "hnlee/colony_counting", "src_encoding": "UTF-8", "text": "#!/usr/bin/python/\n\nimport Image\nimport sys\nimport os\n\nfiledir = sys.argv[1]\noutputfile = sys.argv[2]\n\nfiles = os.listdir(filedir)\noutput = open(outputfile, \"w\")\n\nfor file in files:\n\tgreen = 0\n\tim = Image.open(filedir + file)\n\tstrain = file.split(\"-\")[0]\n\tcolors = im.getcolors(im.size[0]*im.size[1])\n\tfor n in range(len(colors)):\n\t\tif colors[n][1] == (0,255,0):\n\t\t\tgreen = colors[n][0]\n\t\t\tbreak\n\toutput.write(\"%s\\t%i\\t%i\\n\" % (strain,green,green/25))\n\noutput.close()\t\n" } ]
2
patrickdeyoreo/rhino-repo
https://github.com/patrickdeyoreo/rhino-repo
5b34972633c00747c2cf490d8ff4987aa50af4d1
8248d980414a91e4305028839951bede2fe3bc5f
7f1da44d0cf83ef303782222ed2220381ed80b73
refs/heads/master
2021-01-08T12:20:34.478014
2020-02-24T18:10:39
2020-02-24T18:10:39
242,024,994
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.3846607804298401, "alphanum_fraction": 0.3958702087402344, "avg_line_length": 37.08988952636719, "blob_id": "0ba1ded956c065c0c9e2d7f85b5bf7dc3cf53ce5", "content_id": "94ac6a3722e0f883d9be27d2568a8e6f5b01d78b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3390, "license_type": "permissive", "max_line_length": 72, "num_lines": 89, "path": "/rhinoscraper/scrapers/test_file_scraper.py", "repo_name": "patrickdeyoreo/rhino-repo", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"Module for TestFileScraper\"\"\"\nimport sys\n\n\nclass TestFileScraper:\n \"\"\"TestFileScraper class\n\n Scrapes test files from any projects.\n\n Args:\n soup (obj): BeautifulSoup obj containing parsed link\n \"\"\"\n def __init__(self, soup):\n \"\"\"Initialize a test file scraper\n \"\"\"\n self.soup = soup\n self.pre = self.find_test_files()\n\n def find_test_files(self):\n \"\"\"Find test files\n \"\"\"\n return self.soup.select(\"pre\")\n\n def write_test_files(self):\n \"\"\"Write test files\n \"\"\"\n print(\"> Writing test files...\")\n for item in self.pre:\n find_c = item.text.find(\"main.c\")\n find_html = item.text.find(\".html\")\n find_js = item.text.find(\".js\")\n find_py = item.text.find(\".py\")\n find_sql = item.text.find(\".sql\")\n find_test = item.text.find(\"cat\")\n\n # find_main checks if there are main files on project page\n if find_test != -1 and any([\n i != -1 for i in\n [find_c, find_html, find_js, find_py, find_sql]\n ]):\n try:\n name = item.text.split(\"cat \", 1)[1]\n user = item.text.split(\"$\", 1)[0]\n if find_c != -1:\n name = name.split(\".c\", 1)[0] + \".c\"\n elif find_sql != -1:\n name = name.split(\".sql\", 1)[0] + \".sql\"\n elif find_js != -1:\n name = name.split(\".js\", 1)[0] + \".js\"\n else:\n name = name.split(\".py\", 1)[0] + \".py\"\n # html edge case test text creation\n if find_html != -1:\n text = item.text.split(\".html\")[1]\n text = str(text.split(user, 1)[0])\n text = text.split(\"\\n\", 1)[1]\n name = name.split(\".html\", 1)[0] + \".html\"\n else:\n text = item.text.split(name, 1)[1]\n text = text.split(\"\\n\", 1)[1]\n text = text.split(user, 1)[0]\n text = text.split(\"\\n\")\n w_test_file = open(name, \"w+\")\n for i in range(len(text) - 1):\n if find_html != -1:\n w_test_file.write(text[i])\n else:\n w_test_file.write(text[i] + '\\n')\n w_test_file.close()\n except (AttributeError, IndexError):\n name = item.text\n newlines = 0\n # Checks if test file's name has more than 1 newline\n for i in name:\n if newlines > 1:\n name = \"[Not a test file]\"\n break\n if i == \"\\n\":\n newlines += 1\n print(\"* [ERROR] Could not create test file\", name,\n file=sys.stderr)\n continue\n except IOError:\n print(\"* [ERROR] Could not create a test file\",\n file=sys.stderr)\n continue\n else:\n pass\n" }, { "alpha_fraction": 0.5768779516220093, "alphanum_fraction": 0.5850939154624939, "avg_line_length": 28.379310607910156, "blob_id": "86ce0c0c59db8d3ce5ff482745a618b4ae5b86a1", "content_id": "690d0c31e92eac88da14fc33adbbafad9d9f282e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1704, "license_type": "permissive", "max_line_length": 78, "num_lines": 58, "path": "/rhinoscraper/__init__.py", "repo_name": "patrickdeyoreo/rhino-repo", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"\nProvides the rhinoscraper module\n\"\"\"\nimport requests\nfrom bs4 import BeautifulSoup\nfrom . rhinoproject import RhinoProject\nfrom . rhinoread import RhinoRead\n\n\ndef rhinoscrape(soup, github_user, github_name):\n \"\"\"\n Run the rhinoproject and rhinoreadme scrapers\n \"\"\"\n rhino = RhinoProject(soup)\n rhino.run()\n rhino = RhinoRead(soup, github_user, github_name)\n rhino.run()\n\n\ndef get_soup(session, project):\n \"\"\"\n Request project data and parse it with BeautifulSoup\n Return parsed HTML as a BeautifulSoup object\n \"\"\"\n resp = session.get('https://intranet.hbtn.io/projects/{}'.format(project))\n if 200 <= resp.status_code < 300:\n return BeautifulSoup(resp.content, features='html.parser')\n return None\n\n\ndef create_session(hbtn_user, hbtn_pass):\n \"\"\"\n Log in to intranet.hbtn.io\n Return the login session\n \"\"\"\n auth_url = 'https://intranet.hbtn.io/auth/sign_in'\n with requests.Session() as session:\n resp = session.get(auth_url)\n soup = BeautifulSoup(resp.content, features='html.parser')\n try:\n auth_data = {\n 'user[login]': hbtn_user,\n 'user[password]': hbtn_pass,\n 'authenticity_token': soup.find(\n 'input', {'name': 'authenticity_token'}\n ).get('value'),\n 'commit': soup.find(\n 'input', {'name': 'commit'}\n ).get('value')\n }\n except AttributeError:\n pass\n else:\n resp = session.post(auth_url, data=auth_data)\n if 200 <= resp.status_code < 300:\n return session\n return None\n" }, { "alpha_fraction": 0.7237569093704224, "alphanum_fraction": 0.7237569093704224, "avg_line_length": 30.603174209594727, "blob_id": "301824a6e2605818a5271830a574a19bcadf533a", "content_id": "ad022e65d296eccd2e240a8cff34ea8a1d59b87a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1991, "license_type": "permissive", "max_line_length": 130, "num_lines": 63, "path": "/README.md", "repo_name": "patrickdeyoreo/rhino-repo", "src_encoding": "UTF-8", "text": "# Rhino-Repo\n\nThis web-application allows for building and deploying of Holberton Project Repositories onto Github. \n\n## Getting Started\nGo to [Rhino-Repo Huerko App ](http://rhinorepo.herokuapp.com/)\n### Prerequisites\n\nYou will not need to download anything \n\n```\nWill have more info when added to Repo.\n```\n\n### Installing\n\n* Go to the website and just login with your Github credentials\n* Enter Holberton Email\n* Enter Holberton Password\n* Enter Holberton API Key\n\n## How Does it work?\n\nHere is a diagram that shows the data flow that creates the project repository when the user enters their credentials and API key.\n\n* [PLACE HOLDER]\n\n### Struggles with the project.\nThe Project had front-end connectivity issue with UI/UX not coming all together. What we learned is that what may work \non the commandline does not always translate\n\n## Built With\n\n* [Heroku](/) - The web framework used\n* [Flask](/) - Dependency Management\n* [Javascript](/) - Used to for scripting in the front end.\n* [REST API](/) - Used as communication with HTTP requests and Posts to with all the APIs\n* [HTML & CSS](/) - Used to generate Homepage\n\n\n## Authors (Alphabetical)\n\n* **Akeem Seymens** - Technical Writer - [akeemseymens](https://github.com/akeemseymens)\n* **Diva Lei** - Front-End - [lei-diva](https://github.com/lei-diva)\n* **Marco Chan** - Back-End - [inspiredtolive](https://github.com/inspiredtolive)\n* **Minh-Huy Vu** - Contributor - [miuywu](https://github.com/miuywu)\n* **Patrick DeYoreo** - Back-End - [patrickdeyoreo](https://github.com/patrickdeyoreo)\n* **Pierre Beaujuge** - Front-End - [PierreBeaujuge](https://github.com/pierreBeaujuge)\n* **Rashaad Colbert** - Attendee - [PurpleBooth](https://github.com/PurpleBooth)\n\n\n\nSee also the list of [contributors](https://github.com/your/rhino-repo/contributors) who participated in this project.\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details\n\n## Acknowledgments\n\n* Hat tip to anyone whose code was used\n* Inspiration\n* etc\n" }, { "alpha_fraction": 0.6256499290466309, "alphanum_fraction": 0.6291161179542542, "avg_line_length": 31.05555534362793, "blob_id": "21191fbfc53eeac44dcdda1cbe4137bb76006ac0", "content_id": "7c2a125933b05a2bf4305e92de85dc987fc2ee9c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3462, "license_type": "permissive", "max_line_length": 78, "num_lines": 108, "path": "/api/v1/views/project.py", "repo_name": "patrickdeyoreo/rhino-repo", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"\nProvides RESTful API routes for Holberton\n\"\"\"\nimport os\nimport shlex\nimport shutil\nimport subprocess\nimport tempfile\nimport flask\nimport requests\nfrom rhinoscraper import create_session, get_soup, rhinoscrape\nfrom . import app_views\n\nAUTH_KEYS = {'hbtn_email', 'hbtn_password', 'hbtn_api_key', 'github_password'}\n\n\n@app_views.route(\"/<project_id>\", methods=['POST'])\ndef hbtn_project(project_id):\n \"\"\"\n Log into holberton and retrieve a project given it's ID\n Params:\n hbtn_email\n hbtn_password\n hbtn_api_key\n github_password\n \"\"\"\n auth = flask.request.get_json()\n if AUTH_KEYS - auth.keys():\n flask.abort(400)\n auth['hbtn_email'] = auth['hbtn_email'].split('@')[0]\n if not auth['hbtn_email'].isnumeric():\n flask.abort(400)\n auth['hbtn_email'] = '@'.join([\n auth['hbtn_email'], 'holbertonschool.com'\n ])\n auth['hbtn_token'] = hbtn_api_auth_token(\n auth['hbtn_email'], auth['hbtn_password'], auth['hbtn_api_key']\n )\n user = hbtn_api_user(auth['hbtn_token'])\n proj = hbtn_api_project(project_id, auth['hbtn_token'])\n repo = proj['tasks'][0]['github_repo']\n with create_session(auth['hbtn_email'], auth['hbtn_password']) as session:\n git_project(get_soup(session, project_id),\n github_user=user['github_username'],\n github_pass=auth['github_password'],\n github_name=user['full_name'],\n github_repo=repo)\n return (os.path.join(repo, proj['name']), 200)\n\n\ndef git_project(soup, github_user, github_pass, github_repo, github_name):\n \"\"\"\n Scrape project and perform git operations\n \"\"\"\n giturl = 'https://{user}:{password}@github.com/{user}/{repo}.git'.format(\n user=github_user, password=github_pass, repo=github_repo\n )\n oldcwd = os.getcwd()\n tmpdir = tempfile.mkdtemp()\n gitdir = os.path.join(tmpdir, github_repo)\n cmd = 'git clone {} {}'.format(shlex.quote(giturl), shlex.quote(gitdir))\n subprocess.run(shlex.split(cmd), check=False)\n os.chdir(gitdir)\n rhinoscrape(soup, github_user, github_name)\n cmd = 'git add .'\n subprocess.run(shlex.split(cmd), check=False)\n msg = 'Project committed by Rhino Repo'\n cmd = 'git commit -m {}'.format(shlex.quote(msg))\n subprocess.run(shlex.split(cmd), check=False)\n cmd = 'git push {}'.format(shlex.quote(giturl))\n subprocess.run(shlex.split(cmd), check=False)\n os.chdir(oldcwd)\n shutil.rmtree(tmpdir, ignore_errors=True)\n\n\ndef hbtn_api_auth_token(hbtn_email, hbtn_password, hbtn_api_key):\n \"\"\"\n Get holberton auth token\n \"\"\"\n url = 'https://intranet.hbtn.io/users/auth_token.json'\n params = {\n 'email': hbtn_email,\n 'password': hbtn_password,\n 'api_key': hbtn_api_key,\n 'scope': 'checker'\n }\n resp = requests.post(url, params=params)\n return resp.json().get('auth_token')\n\n\ndef hbtn_api_user(hbtn_auth_token):\n \"\"\"\n Get holberton user info\n \"\"\"\n url = 'https://intranet.hbtn.io/users/me.json'\n resp = requests.get(url, params={'auth_token': hbtn_auth_token})\n return resp.json()\n\n\ndef hbtn_api_project(hbtn_project_id, hbtn_auth_token):\n \"\"\"\n Get holberton project info\n \"\"\"\n url = 'https://intranet.hbtn.io/projects/{}.json'.format(hbtn_project_id)\n params = {'auth_token': hbtn_auth_token, 'id': hbtn_project_id}\n resp = requests.get(url, params=params)\n return resp.json()\n" }, { "alpha_fraction": 0.6493688821792603, "alphanum_fraction": 0.6802244186401367, "avg_line_length": 24.464284896850586, "blob_id": "d875b80933378a7c3f54f202a97030a28f8bb699", "content_id": "7c1982c5644750dc0707ebf293c6eed6ba07c210", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 713, "license_type": "permissive", "max_line_length": 71, "num_lines": 28, "path": "/api/v1/app.py", "repo_name": "patrickdeyoreo/rhino-repo", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"\nReturns the status of the API\n\"\"\"\n\nfrom os import getenv\nfrom flask import Flask, jsonify, make_response\nfrom flask_cors import CORS\nfrom api.v1.views import app_views\n\nHOST = getenv('RHINO_API_HOST', '0.0.0.0')\nPORT = getenv('RHINE_API_PORT', '5000')\ncors = CORS(app_views, resources={r\"/*\": {\"origins\": '*'}})\n\napp = Flask(__name__)\napp.url_map.strict_slashes = False\napp.config['JSONIFY_PRETTYPRINT_REGULAR'] = True\napp.register_blueprint(app_views)\n\n\[email protected](404)\ndef error_404(err):\n \"\"\"Produce a 404 error message\"\"\"\n return make_response(jsonify(error=\"oops, I did it again...\"), 404)\n\n\nif __name__ == \"__main__\":\n app.run(host=HOST, port=PORT, threaded=True)\n" }, { "alpha_fraction": 0.46898895502090454, "alphanum_fraction": 0.4736618399620056, "avg_line_length": 33.87407302856445, "blob_id": "0887d048cbcbc1a92f520d99eea6c5b48155e884", "content_id": "0c50fb30fc02a7287c8b3233a223b7e29f80a655", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4708, "license_type": "permissive", "max_line_length": 74, "num_lines": 135, "path": "/rhinoscraper/scrapers/high_scraper.py", "repo_name": "patrickdeyoreo/rhino-repo", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"Module for HighScraper\"\"\"\nimport os\nimport re\nimport sys\n\n\nclass HighScraper:\n \"\"\"HighScraper class\n\n High-Level_Programming project scraper.\n\n Args:\n soup (obj): BeautifulSoup obj containing parsed link\n\n Attributes:\n py_flag (int): For write_checker()\n py_js (int): For write_checker()\n \"\"\"\n py_flag = 0\n js_flag = 0\n\n def __init__(self, soup):\n self.soup = soup\n self.file_names = self.find_files()\n self.prototypes_list = self.find_prototypes()\n\n def find_prototypes(self):\n \"\"\"Method to scrape python prototypes\n\n Has a failsafe incase there are non-python files in scraped data.\n \"\"\"\n res = []\n find_protos = self.soup.find_all(string=re.compile(\"Prototype: \"))\n for item in find_protos:\n py_proto = item.next_sibling.text\n find_py = py_proto.find(\":\")\n if find_py != 1:\n res.append(py_proto)\n else:\n pass\n return res\n\n def find_files(self):\n \"\"\"Method to scrape for python file names\"\"\"\n return self.soup.find_all(string=re.compile(\"File: \"))\n\n def write_files(self):\n \"\"\"Method to write/create python files\n\n Has a function that creates directories if found in `file_name`.\n Last function creates required files in additional directory.\n \"\"\"\n new_dir_files = []\n file_idx = 0\n one_dir_check = 0\n folder_name = None\n\n print(\"> Creating task files...\")\n for item in self.file_names:\n text_file = item.next_sibling.text\n try:\n find_pyfile = text_file.find(\".py\")\n find_comma = re.search('(.+?),', text_file)\n\n # Creating sub directories if exists\n find_folder = re.search(', (.+?)/', text_file)\n\n find_dir_file = re.search('/(.+?)$', text_file)\n if find_dir_file is not None:\n new_dir_files.append(str(find_dir_file.group(1)))\n if find_folder is not None and one_dir_check == 0:\n folder_name = str(find_folder.group(1))\n os.mkdir(folder_name)\n one_dir_check += 1\n\n # Handling multiple files\n if \",\" in text_file:\n create_name = str(find_comma.group(1))\n make_comma = open(create_name, \"w+\")\n make_comma.close()\n elif \".\" not in text_file and one_dir_check != 1:\n os.mkdir(text_file)\n else:\n w_file_name = open(text_file, \"w+\")\n if \".py\" in text_file:\n self.py_flag = 1\n w_file_name.write(\"#!/usr/bin/python3\\n\")\n elif \".sh\" in text_file:\n w_file_name.write(\"#!/bin/bash\\n\")\n elif \".js\" in text_file:\n self.js_flag = 1\n w_file_name.write(\"#!/usr/bin/node\\n\")\n else:\n pass\n # Creating prototypes in parallel with files\n if find_pyfile != -1:\n w_file_name.write(self.prototypes_list[file_idx])\n file_idx += 1\n else:\n pass\n w_file_name.close()\n except AttributeError:\n print(\"* [ERROR] Failed to write\", text_file,\n file=sys.stderr)\n continue\n except IOError:\n print(\"* [ERROR] Failed to write file\",\n file=sys.stderr)\n except IndexError:\n pass\n\n # Check if new dir created, insert files if there is\n if folder_name is not None and one_dir_check == 1:\n os.chdir(folder_name)\n for item in new_dir_files:\n if \",\" in item:\n item_obj = re.search('/(.+?)$', text_file)\n item = str(item_obj.group(1))\n dir_file = open(item, \"w+\")\n dir_file.close()\n os.chdir(\"..\")\n\n def write_checker(self):\n \"\"\"Write checker data\n \"\"\"\n with open(\"check.sh\", \"w\") as ofile:\n ofile.write(\"#!/usr/bin/env bash\\n\")\n if self.js_flag == 1:\n ofile.write(\"semistandard --fix \")\n if self.py_flag == 1:\n ofile.write(\"pep8 \")\n if self.file_names:\n for i in self.file_names:\n ofile.write('\"%s\" ' % i.next_sibling.text)\n" }, { "alpha_fraction": 0.6909871101379395, "alphanum_fraction": 0.7081544995307922, "avg_line_length": 22.299999237060547, "blob_id": "9ed220a65c37cdc80694057c6362b11ffdee35f3", "content_id": "69c38a00811ebe58e0a6d4cfddf53d8bd06e5c2f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 233, "license_type": "permissive", "max_line_length": 72, "num_lines": 10, "path": "/api/v1/views/__init__.py", "repo_name": "patrickdeyoreo/rhino-repo", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"\ninitializes the api views from a flask blueprint set up in api/v1/app.py\n\"\"\"\n\nfrom flask import Blueprint\n\napp_views = Blueprint('app_views', __name__, url_prefix='/api/v1')\n\nfrom api.v1.views.project import *\n" }, { "alpha_fraction": 0.6001405715942383, "alphanum_fraction": 0.6008433103561401, "avg_line_length": 33.28915786743164, "blob_id": "2081ed5dfdc90db426dc2fdd27c0273903132e14", "content_id": "c81dccc7886959c74844d380ef07b78c97391efa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2846, "license_type": "permissive", "max_line_length": 78, "num_lines": 83, "path": "/rhinoscraper/rhinoproject.py", "repo_name": "patrickdeyoreo/rhino-repo", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"\nProvides a class to scrape project data and create project files\n\"\"\"\nimport os\nimport re\nimport shutil\nimport stat\nimport sys\nfrom bs4 import BeautifulSoup\nfrom . scrapers.high_scraper import HighScraper\nfrom . scrapers.low_scraper import LowScraper\nfrom . scrapers.sys_scraper import SysScraper\nfrom . scrapers.test_file_scraper import TestFileScraper\n\n\nclass RhinoProject:\n \"\"\"\n Definition of a class to scrape project data and create project files\n \"\"\"\n def __init__(self, soup):\n \"\"\"\n Instantiate a RhinoProject with a BeautifulSoup object\n \"\"\"\n if not isinstance(soup, BeautifulSoup):\n raise TypeError(\"'soup' must be a 'BeautifulSoup'\")\n self.soup = soup\n self.project_name = self.scrape_name()\n self.project_type = self.scrape_type()\n\n def scrape_name(self):\n \"\"\"\n Scrape the project directory name by locating 'Directory:'\n Return the project directory name\n \"\"\"\n pattern = re.compile(r'^directory:\\s+', flags=re.I)\n element = self.soup.find(string=pattern)\n if element is None:\n raise ValueError('Unable to determine project name')\n return element.next_element.text\n\n def scrape_type(self):\n \"\"\"\n Scrape the project type by locating 'GitHub repository:'\n Return the project type\n \"\"\"\n pattern = re.compile(r'^github\\s+repository:\\s+', flags=re.I)\n element = self.soup.find(string=pattern)\n if element is None:\n raise ValueError('Unable to determine project type')\n return element.next_sibling.text\n\n def run(self):\n \"\"\"\n Scrape project data based on the project type and write project files\n Return an absolute path to the project directory\n \"\"\"\n olddir = os.getcwd()\n os.mkdir(self.project_name)\n os.chdir(self.project_name)\n newdir = os.getcwd()\n try:\n if re.search(r'-high', self.project_type):\n task_scraper = HighScraper(self.soup)\n elif re.search(r'-low', self.project_type):\n task_scraper = LowScraper(self.soup)\n elif re.search(r'-sys', self.project_type):\n task_scraper = SysScraper(self.soup)\n else:\n raise ValueError('Invalid project type')\n test_scraper = TestFileScraper(self.soup)\n task_scraper.write_files()\n test_scraper.write_test_files()\n for name in os.listdir():\n try:\n os.chmod(name, stat.S_IRWXU | stat.S_IRGRP | stat.S_IROTH)\n except OSError:\n pass\n except Exception:\n shutil.rmtree(newdir, ignore_errors=True)\n raise\n finally:\n os.chdir(olddir)\n" }, { "alpha_fraction": 0.5311667323112488, "alphanum_fraction": 0.5338305830955505, "avg_line_length": 31.929824829101562, "blob_id": "afa6f147d56cee8ed07d409748012d0cc2898e48", "content_id": "da7f6d88226b69f42ded7fdb1e5692ff8a90e036", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1877, "license_type": "permissive", "max_line_length": 78, "num_lines": 57, "path": "/rhinoscraper/scrapers/sys_scraper.py", "repo_name": "patrickdeyoreo/rhino-repo", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"Module for SysScraper\"\"\"\nimport re\nimport sys\n\n\nclass SysScraper:\n \"\"\"SysScraper class\n\n System-Engineering_Devops project scraper.\n\n Args:\n soup (obj): BeautifulSoup obj containing parsed link\n\n Attributes:\n ruby_check (str): if ruby exists, assign to 0. Else scrape empty list\n file_names (list): scraped file names from find_files()\n \"\"\"\n\n def __init__(self, soup):\n self.soup = soup\n self.file_names = self.find_files()\n self.ruby_check = self.ruby_checker()\n\n def ruby_checker(self):\n \"\"\"Method that checks for ruby files in project\n \"\"\"\n tmp = self.soup.find_all(string=re.compile(\"env ruby\"))\n if tmp != []:\n return 0\n return tmp\n\n def find_files(self):\n \"\"\"Method that scrapes bash or ruby for file names\"\"\"\n return self.soup.find_all(string=re.compile(\"File: \"))\n\n def write_files(self):\n \"\"\"Method that writes/creates bash or ruby files\"\"\"\n print(\"> Creating task files...\")\n for item in self.file_names:\n try:\n w_file_name = open(item.next_sibling.text, \"w\")\n if self.ruby_check == 0:\n w_file_name.write(\"#!/usr/bin/env ruby\\n\")\n elif \".py\" in item.next_sibling.text:\n w_file_name.write(\"#!/usr/bin/python3\\n\")\n else:\n w_file_name.write(\"#!/usr/bin/env bash\\n\")\n w_file_name.close()\n except (AttributeError, IndexError):\n try:\n print(\"* [ERROR] Failed to write\", item.next_sibling.text,\n file=sys.stderr)\n except AttributeError:\n print(\"* [ERROR] Failed to find task files\",\n file=sys.stderr)\n continue\n" }, { "alpha_fraction": 0.5995475053787231, "alphanum_fraction": 0.6199095249176025, "avg_line_length": 17.040817260742188, "blob_id": "a9ce304f535871e9b2b467c56148e040dc5ee66e", "content_id": "692fc6b4a84fd4eacd4ee64ee0137ea16c9474ec", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 884, "license_type": "permissive", "max_line_length": 62, "num_lines": 49, "path": "/integrate.py", "repo_name": "patrickdeyoreo/rhino-repo", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"\nFlask App that integrates with Rhino-Repo static HTML Template\n\"\"\"\nfrom flask import Flask, render_template, url_for\n\n# flask setup\napp = Flask(__name__)\napp.url_map.strict_slashes = False\nport = 5001\nhost = '0.0.0.0'\n\n\[email protected]('/')\ndef index():\n \"\"\"\n handles request to custom template\n \"\"\"\n return render_template('index.html')\n\n\[email protected]('/credent/')\ndef credent():\n \"\"\"\n handles request to custom template\n \"\"\"\n return render_template('credent.html')\n\n\[email protected]('/done/<repo>')\ndef done(repo):\n \"\"\"\n handles request to custom template\n \"\"\"\n return render_template('done.html', repo=repo)\n\n\[email protected]('/404/')\ndef error_404():\n \"\"\"\n handles request to custom template\n \"\"\"\n return render_template('404.html')\n\n\nif __name__ == \"__main__\":\n \"\"\"\n MAIN Flask App\"\"\"\n app.run(host=host, port=port)\n" }, { "alpha_fraction": 0.5899419784545898, "alphanum_fraction": 0.5909090638160706, "avg_line_length": 29.41176414489746, "blob_id": "7a3a68694626b4215e928dada62fd864f853070c", "content_id": "256397cfb089c97e7258bf2281d37e8d290eb29b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1034, "license_type": "permissive", "max_line_length": 73, "num_lines": 34, "path": "/rhinoscraper/rhinoread.py", "repo_name": "patrickdeyoreo/rhino-repo", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"\nProvides a class to scrape project data and produce a README\n\"\"\"\nfrom . scrapers.read_scraper import ReadScraper\n\n\nclass RhinoRead(ReadScraper):\n \"\"\"\n Definition of a class to scrape project data and create project files\n \"\"\"\n def __init__(self, soup, github_user, github_name):\n \"\"\"\n Instantiate a RhinoRead object\n \"\"\"\n super().__init__(soup)\n if not isinstance(github_user, str):\n raise TypeError(\"'user' must be a 'str'\")\n if not isinstance(github_name, str):\n raise TypeError(\"'name' must be a 'str'\")\n self.user = github_user\n self.name = github_name\n\n def run(self):\n \"\"\"\n Scrape project data and create a README\n \"\"\"\n # Write README.md with scraped data\n self.open_readme()\n self.write_title()\n self.write_info()\n self.write_tasks()\n profile = 'https://github.com/{}'.format(self.user)\n self.write_footer(self.name, self.user, profile)\n" }, { "alpha_fraction": 0.5234723687171936, "alphanum_fraction": 0.5262428522109985, "avg_line_length": 34.69780349731445, "blob_id": "b0686cc3da03998fae5af737c65ab72bd7759642", "content_id": "eb2f269d52564aaa825c7d11bf021ac9785d4fbb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6497, "license_type": "permissive", "max_line_length": 79, "num_lines": 182, "path": "/rhinoscraper/scrapers/read_scraper.py", "repo_name": "patrickdeyoreo/rhino-repo", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"Module for ReadScraper\"\"\"\nimport os\nimport re\nimport sys\nimport requests\nfrom bs4 import BeautifulSoup, Comment\n\n\nclass ReadScraper:\n \"\"\"ReadScraper class\n\n README.md scraper\n\n Args:\n soup (obj): BeautifulSoup obj containing parsed link\n\n Attributes:\n title (str):\n repo_name ():\n dir_name ():\n \"\"\"\n big_project_type = 0\n task_info = []\n readme = None\n\n def __init__(self, soup):\n self.soup = soup\n self.title = self.find_title()\n self.repo_name = self.find_repo_name()\n self.dir_name = self.check_big_project()\n self.prj_info = self.find_learning()\n self.file_names = self.find_files()\n self.task_names = self.find_tasks()\n self.task_info = self.find_task_de()\n\n def find_title(self):\n \"\"\"Method that finds title of project\"\"\"\n prj_title = self.soup.find(\"h1\")\n return prj_title.text\n\n def find_repo_name(self):\n \"\"\"Method that finds the repository name\"\"\"\n r_name = self.soup.find(string=re.compile(\"GitHub repository: \"))\n return r_name.next_element\n\n def check_big_project(self):\n \"\"\"Method that checks if project is a big one\"\"\"\n try:\n tmp = self.repo_name.find_next(\"li\").next_element.next_element.text\n if \"-\" in tmp:\n return tmp\n raise AttributeError\n except AttributeError:\n print(\"* [ERROR] Failed to scrape project directory\",\n file=sys.stderr)\n self.big_project_type = 1\n return \"\"\n\n def find_learning(self):\n \"\"\"Method that finds the learning objectives\"\"\"\n try:\n h2 = self.soup.find(\"h2\", string=re.compile(\"Learning Objectives\"))\n h3 = h2.find_next(\"h3\").next_element.next_element.next_element.text\n return h3.splitlines()\n except AttributeError:\n print(\"* [ERROR] Failed to scrape learning objectives\",\n file=sys.stderr)\n return \"\"\n\n def find_files(self):\n \"\"\"Method that finds file names\"\"\"\n temp = []\n try:\n file_list = self.soup.find_all(string=re.compile(\"File: \"))\n for idx in file_list:\n file_text = idx.next_sibling.text\n # Finding comma index for multiple files listed\n find_comma = file_text.find(\",\")\n if find_comma != -1:\n temp.append(file_text[:find_comma])\n else:\n temp.append(file_text)\n return temp\n except (IndexError, AttributeError):\n print(\"* [ERROR] Failed to scrape project filenames\",\n file=sys.stderr)\n return None\n\n def find_tasks(self):\n \"\"\"Method that finds task names\"\"\"\n temp = []\n try:\n task_list = self.soup.find_all(\"h4\", class_=\"task\")\n for idx in task_list:\n item = idx.next_element.strip(\"\\n\").strip()\n temp.append(item)\n return temp\n except (IndexError, AttributeError):\n print(\"* [ERROR] Failed to scrape task titles\",\n file=sys.stderr)\n return None\n\n def find_task_de(self):\n \"\"\"Method that finds the task descriptions\"\"\"\n temp = []\n try:\n info_list = self.soup.find_all(\n string=lambda text: isinstance(text, Comment))\n for comments in info_list:\n if comments == \" Task Body \":\n info_text = comments.next_element.next_element.text\n temp.append(info_text)\n return temp\n except (IndexError, AttributeError):\n print(\"* [ERROR] Failed to scrape task descriptions\",\n file=sys.stderr)\n return None\n\n def open_readme(self):\n \"\"\"Method that opens the README.md file\"\"\"\n try:\n if self.big_project_type == 1:\n raise IOError\n filename = self.dir_name + \"/README.md\"\n self.readme = open(filename, \"w+\")\n except IOError:\n self.readme = open(\"README.md\", \"w\")\n\n def write_title(self):\n \"\"\"Method that writes the title to README.md\"\"\"\n print(\"> Writing project title...\")\n self.readme.write(\"# {}\\n\".format(self.title))\n self.readme.write(\"\\n\")\n\n def write_info(self):\n \"\"\"Method that writes project info to README.md\"\"\"\n print(\"> Writing learning objectives...\")\n self.readme.write(\"## Description\\n\")\n self.readme.write(\"What you should learn from this project:\\n\")\n try:\n for item in self.prj_info:\n if len(item) == 0:\n self.readme.write(\"{}\\n\".format(item))\n continue\n self.readme.write(\"* {}\\n\".format(item))\n except (AttributeError, IndexError, UnicodeEncodeError):\n print(\"* [ERROR] Failed to write learning objectives\",\n file=sys.stderr)\n self.readme.write(\"\\n\")\n self.readme.write(\"---\\n\")\n\n def write_tasks(self):\n \"\"\"Method that writes the entire tasks to README.md\"\"\"\n if (self.task_names is not None and self.file_names is not None and\n self.task_info is not None):\n print(\"> Writing task information...\")\n count = 0\n while count < len(self.task_names):\n try:\n self.readme.write(\"\\n\")\n self.readme.write(\n \"### [{}](./{})\\n\".format(\n self.task_names[count], self.file_names[count]))\n self.readme.write(\"* {}\\n\".format(self.task_info[count]))\n self.readme.write(\"\\n\")\n count += 1\n except IndexError:\n print(\"* [ERROR] Could not write\", self.task_names[count],\n file=sys.stderr)\n count += 1\n continue\n\n def write_footer(self, author, user, git_link):\n \"\"\"Method that writes the footer to README.md\"\"\"\n print(\"> Writing author information...\")\n self.readme.write(\"---\\n\")\n self.readme.write(\"\\n\")\n self.readme.write(\"## Author\\n\")\n self.readme.write(\"* **{}** - \".format(author))\n self.readme.write(\"[{}]\".format(user))\n self.readme.write(\"({})\".format(git_link))\n" }, { "alpha_fraction": 0.6604434251785278, "alphanum_fraction": 0.6662777066230774, "avg_line_length": 28.55172348022461, "blob_id": "f392506e642004c72ed15035d167ae9741589fc6", "content_id": "ec2a809f74e1f058a0af1d64070be098786be0d6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 857, "license_type": "permissive", "max_line_length": 74, "num_lines": 29, "path": "/rhinoscraper/tests/test_base_parse.py", "repo_name": "patrickdeyoreo/rhino-repo", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"Unittest for LowScraper\"\"\"\nimport unittest\nfrom scrapers import *\n\n\nclass TestBaseParse(unittest.TestCase):\n \"\"\"Test for LowScraper\"\"\"\n\n def setUp(self):\n self.parse = BaseParse(\"https://intranet.hbtn.io/projects/232\")\n self.parse.get_json()\n\n def tearDown(self):\n del self.parse\n\n def test_base_object(self):\n self.assertIsNotNone(self.parse)\n self.assertIsInstance(self.parse, object)\n self.assertIn(\"scrapers.base_parse.BaseParse\", str(self.parse))\n\n def test_json_data(self):\n self.assertIsInstance(self.parse.json_data, dict)\n\n def test_get_soup(self):\n self.parse.get_soup()\n self.assertIsNotNone(self.parse.soup)\n self.assertIsInstance(self.parse.soup, object)\n self.assertIn(\"bs4.BeautifulSoup\", str(self.parse.soup.__class__))\n" }, { "alpha_fraction": 0.5134880542755127, "alphanum_fraction": 0.5153701305389404, "avg_line_length": 33.464866638183594, "blob_id": "c9e88a42d43b01b74c1d6d4059f46ee5c78bb39f", "content_id": "0191879ed8f3462d9f87d18073bb5fe087d92ea6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6376, "license_type": "permissive", "max_line_length": 78, "num_lines": 185, "path": "/rhinoscraper/scrapers/low_scraper.py", "repo_name": "patrickdeyoreo/rhino-repo", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"Module for LowScraper\"\"\"\nimport re\nimport sys\nfrom bs4 import BeautifulSoup\n\nPUTCHAR = \"\"\"\n#include <unistd.h>\n\n/**\n * _putchar - writes the character c to stdout\n * @c: The character to print\n *\n * Return: On success 1.\n * On error, -1 is returned, and errno is set appropriately.\n */\nint _putchar(char c)\n{\n\\treturn (write(1, &c, 1));\n}\n\"\"\"\n\n\nclass LowScraper:\n \"\"\"\n Low-Level_Programming project scraper.\n Public instance methods:\n detect_putchar\n scrape_prototypes\n scrape_header\n write_putchar\n write_header\n write_files\n\n Public instance attributes:\n putchar_required: bool: is a custom putchar required\n header: str: name of C header file\n prototypes: list: function prototypes\n files: list: project files\n \"\"\"\n def __init__(self, soup):\n \"\"\"\n Instantiate a LowScraper with a BeautifulSoup object\n Args:\n soup: BeautifulSoup: Parsed HTML from a Holberton project\n \"\"\"\n if not isinstance(soup, BeautifulSoup):\n raise TypeError(\"'soup' must be a 'BeautifulSoup'\")\n self.soup = soup\n self.detect_putchar()\n self.scrape_header()\n self.scrape_prototypes()\n self.scrape_files()\n\n def detect_putchar(self):\n \"\"\"\n Check if custom '_putchar' is required\n Returns\n \"\"\"\n print(\"> Checking if a custom '_putchar' is required...\")\n regex = re.compile(r'^you\\s+are\\s+allowed\\s+to\\s+use\\b', flags=re.I)\n match = self.soup.find(string=regex)\n try:\n self.putchar_required = match.next_sibling.text == '_putchar'\n except (TypeError, ValueError):\n self.putchar_required = False\n return self.putchar_required\n\n def scrape_header(self):\n \"\"\"\n Scrape C header file name\n \"\"\"\n print(\"> Scraping name of header file...\")\n try:\n regex = re.compile(r'\\bforget\\s+to\\s+push\\s+your\\s+header\\s+file')\n match = self.soup.find(string=regex).previous_element\n self.header = match.previous_element.previous_element\n except AttributeError:\n self.header = None\n return self.header\n\n def scrape_prototypes(self):\n \"\"\"\n Scrape C prototypes\n \"\"\"\n print(\"> Scraping function prototypes...\")\n if self.putchar_required:\n self.prototypes = ['int _putchar(char c)']\n else:\n self.prototypes = []\n regex = re.compile(r\"\\bprototype:\\s\", flags=re.I)\n self.prototypes.extend([element.next_sibling.text.replace(';', '') for\n element in self.soup.find_all(string=regex)])\n return self.prototypes\n\n def scrape_files(self):\n \"\"\"\n Scrape C file names\n \"\"\"\n print(\"> Scraping file names...\")\n regex = re.compile(r'\\bfile: ', flags=re.I)\n self.files = self.soup.find_all(string=regex) or []\n return self.files\n\n def write_putchar(self):\n \"\"\"\n Write '_putchar' if required\n \"\"\"\n if self.putchar_required:\n print(\"> Writing '_putchar.c'...\")\n try:\n with open('_putchar.c', 'w') as ofile:\n print(PUTCHAR.strip(), file=ofile)\n except OSError:\n pass\n\n def write_header(self):\n \"\"\"\n Write C header file (if required)\n \"\"\"\n if self.header:\n print(\"> Writing header file... \")\n try:\n include_guard = self.header.replace('.', '_', 1).upper()\n prototypes = ['{};'.format(s) for s in self.prototypes]\n with open(self.header, 'w') as ofile:\n print('#ifndef {}'.format(include_guard), file=ofile)\n print('#define {}'.format(include_guard), file=ofile)\n print('', file=ofile)\n print('#include <stdio.h>', file=ofile)\n print('#include <stdlib.h>', file=ofile)\n print('', file=ofile)\n print(*prototypes, sep='\\n', file=ofile)\n print('', file=ofile)\n print('#endif /* {} */'.format(include_guard), file=ofile)\n except (AttributeError, OSError):\n print(\"* [ERROR] Failed to write header file\", self.header,\n file=sys.stderr)\n\n def write_files(self):\n \"\"\"\n Write project files\n Handles multiple file names by searching for ','.\n \"\"\"\n self.write_header()\n self.write_putchar()\n print(\"> Writing task files...\")\n for element, prototype in zip(self.files, self.prototypes):\n try:\n filename = element.next_sibling.text.split(\",\")[0]\n funcname = prototype.split(\"(\", maxsplit=1)[0].split(\" \")\n funcname = funcname[len(funcname)-1].split(\"*\")\n funcname = funcname[len(funcname)-1]\n if self.header is not None:\n with open(filename, 'w') as ofile:\n print('#include', self.header, file=ofile)\n print('', file=ofile)\n print('/**', file=ofile)\n print(' *', funcname, '-', file=ofile)\n print(' *', file=ofile)\n print(' * Return:', file=ofile)\n print(' */', file=ofile)\n print(prototype, file=ofile)\n print('{', file=ofile)\n print('', file=ofile)\n print('}', file=ofile)\n except (AttributeError, OSError):\n print(\"* [ERROR] Failed to write task file\", filename,\n file=sys.stderr)\n\n def write_checker(self):\n \"\"\"\n Write betty style checker\n \"\"\"\n try:\n line = ['betty']\n if self.header:\n line.append(self.header)\n if self.files:\n line.extend([item.next_sibling.text for item in self.files])\n with open('check.sh', 'w') as ofile:\n print('#!/usr/bin/env bash', file=ofile)\n print(*line, file=ofile)\n except (OSError, TypeError, ValueError):\n pass\n" } ]
14
redyandri/doc2vec-master
https://github.com/redyandri/doc2vec-master
9a6496f62eb003a6c5d682771a1a993c84bf5088
54f8b187fb1260e09747c765ad5425aa39dacfe8
e14935f5319f0340b30cb02de2e0529c8ac94f19
refs/heads/master
2022-08-18T14:52:11.302326
2022-07-27T11:51:42
2022-07-27T11:51:42
243,535,906
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5625385046005249, "alphanum_fraction": 0.6019716858863831, "avg_line_length": 26.94827651977539, "blob_id": "2184f8725010eb2a0d656e4c080d153f0652bd23", "content_id": "0ea94635e6e65c37723d922a8304a0b25a509169", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1623, "license_type": "permissive", "max_line_length": 95, "num_lines": 58, "path": "/summarizer.py", "repo_name": "redyandri/doc2vec-master", "src_encoding": "UTF-8", "text": "from gensim.summarization.summarizer import summarize\nimport pandas as pd\nimport numpy as np\nfrom victorinox import victorinox\n\nclass MyIter(object):\n path=\"\"\n def __init__(self,fp):\n self.path=fp\n\n def __iter__(self):\n # path = datapath(self.path)\n with open(self.path, 'r', encoding='utf-8') as fin:\n for line in fin:\n yield line\n\ntool=victorinox()\n\n\ncsvsrc=r\"data/dataset_lower_clean_stem_staff_group_with_periods.csv\"\ncsvsummary=r\"data/dataset_lower_clean_stem_staff_group_with_periods_summary.csv\"\n\n\n# df=pd.read_csv(csvsrc,sep=\";\")\n# dftarget=df[df.values==\"196808172003121001_syafarrudin\"]#196302201983111001_dedysulistiarto\"]\n# text=\"\\n\".join(dftarget.iloc[:,0])\n# print(text)\n# print(\"########################################################\")\n# summ=summarize(text)\n# print(summ)\n# sumsentences=str(summ).splitlines()\n# print(\"COUNT ori:%d\" %len(dftarget))\n# print(\"COUNT summary:%d\" %len(sumsentences))\n\n\n# df=pd.read_csv(csvsrc,sep=\";\")\n# lengths=[]\n# for idx,row in df.iterrows():\n# lengths.append(len(str(row[\"KOMPETENSI\"]).split()))\n# print(np.mean(lengths))\n###9.421897018021408\n\ncorpus=MyIter(csvsrc)\nwith open(csvsummary,\"a+\") as f:\n i=1\n for line in corpus:\n parts=line.split(\";\")\n id = parts[0]\n if(id==\"ID_PEGAWAI\"):\n continue\n doc=parts[1]\n lineddoc=\"\\n\".join(doc.split(\".\"))\n summary=summarize(lineddoc)\n summary=\". \".join(summary.split(\"\\n\"))\n l=\";\".join([id,summary])\n f.write(l+\"\\n\")\n print(\"\\rwrite %d / 114253\"%(i),end=\"\",flush=True)\n i+=1\n\n\n" }, { "alpha_fraction": 0.5494223237037659, "alphanum_fraction": 0.5744544267654419, "avg_line_length": 30.474746704101562, "blob_id": "0eaad6f88e09989bbfe3e63a5bb0014df1df0b6f", "content_id": "5422192c60ecb8d5f158c0b2305604eb7e788493", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3116, "license_type": "permissive", "max_line_length": 91, "num_lines": 99, "path": "/train_fasttext.py", "repo_name": "redyandri/doc2vec-master", "src_encoding": "UTF-8", "text": "from victorinox import victorinox\nfrom gensim.models import FastText\nfrom gensim.test.utils import datapath\nfrom gensim.test.utils import get_tmpfile\nfrom gensim.utils import tokenize\nfrom gensim import utils\nimport logging\n\n\n\n#enable logging\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\nclass MyIter(object):\n path=\"\"\n def __init__(self,fp):\n self.path=fp\n\n def __iter__(self):\n # path = datapath(self.path)\n with utils.open(self.path, 'r', encoding='utf-8') as fin:\n for line in fin:\n yield list(tokenize(line))\n\n#https://radimrehurek.com/gensim/models/fasttext.html\n# vector_size = 100\n# window_size = 5\n# min_count = 1\n# sampling_threshold = 1e-5\n# negative_size = 5\n# train_epoch = 100\n# dm = 0 #0 = dbow; 1 = dmpv\n# worker_count = 1\n# sg=0\n# dataset_path=r\"data\\dataset_lower_clean_stem_sentence.csv\"\n# corpus_file = datapath(dataset_path)\n# model_path=r\"model\\fasttext100.bin\"\n# pretrained=r\"model\\cc.id.300.bin\\cc.id.300.bin\"\n# pretrained_vec=r\"model\\cc.id.300.vec\\cc.id.300.vec\"\n# corpus=MyIter(dataset_path)\n# fasttext_model=FastText(corpus,\n# size=vector_size,\n# window=window_size,\n# min_count=min_count,\n# sample=sampling_threshold,\n# workers=worker_count,\n# hs=0,\n# sg=sg,\n# #dm=dm,\n# negative=negative_size,\n# #dbow_words=1,\n# #dm_concat=1,\n# #pretrained_emb=pretrained_vec,\n# iter=train_epoch)\n# fasttext_model.save(model_path)\n#\n#\n# model_path=r\"model\\fasttext100.bin\"\n# fasttext_model = FastText.load(model_path)\n# sim=fasttext_model.wv.most_similar(['nosql', 'mongodb'])\n# print(sim)\n\n\nvector_size = 100\nwindow_size = 5\nmin_count = 5\nsampling_threshold = 1e-5\nnegative_size = 5\ntrain_epoch = 100\ndm = 0 #0 = dbow; 1 = dmpv\nworker_count = 1\nsg=0\ndataset_path=r\"data/dataset_lower_clean_stem_sentence.csv\"\ncorpus_file = datapath(dataset_path)\nmodel_path=r\"model/fasttext100/fasttext100_retrain.bin\"\npretrained=r\"model/fasttext100/fasttext100.bin\"\npretrained_vec=r\"model\\cc.id.300.vec\\cc.id.300.vec\"\ncorpus=MyIter(dataset_path)\nfasttext_model=FastText(corpus,\n size=vector_size,\n window=window_size,\n min_count=min_count,\n sample=sampling_threshold,\n workers=worker_count,\n hs=0,\n sg=sg,\n #dm=dm,\n negative=negative_size,\n #dbow_words=1,\n #dm_concat=1,\n #pretrained_emb=pretrained_vec,\n iter=train_epoch)\nfasttext_model.save(model_path)\n\n\nmodel_path=r\"model\\fasttext100.bin\"\nfasttext_model = FastText.load(model_path)\nsim=fasttext_model.wv.most_similar(['nosql', 'mongodb'])\nprint(sim)\n" }, { "alpha_fraction": 0.760869562625885, "alphanum_fraction": 0.7950310707092285, "avg_line_length": 34.88888931274414, "blob_id": "5b61112e8df6bb312843f741e0c51da4efe7d491", "content_id": "b4312027999f8a18181b7efbe74417cbea46d576", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 322, "license_type": "permissive", "max_line_length": 51, "num_lines": 9, "path": "/runner.py", "repo_name": "redyandri/doc2vec-master", "src_encoding": "UTF-8", "text": "from gensim.models import Word2Vec\nfrom gensim.models import FastText\n\nmodel_path=r\"model\\fasttext100.bin\"\nfasttext_model = FastText.load(model_path)\nprint(fasttext_model.wv.most_similar(\"sql server\"))\nmodel_path=r\"model\\word2vec100.bin\"\nw2v_model = Word2Vec.load(model_path)\nprint(w2v_model.wv.most_similar(\"sql server\"))" }, { "alpha_fraction": 0.6198436617851257, "alphanum_fraction": 0.6355839967727661, "avg_line_length": 38.17021179199219, "blob_id": "d0a0a109bafbd1547b5321785fcd06290e1cb3eb", "content_id": "05bb6ca7034f20e894590de1329406340d003801", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9212, "license_type": "permissive", "max_line_length": 159, "num_lines": 235, "path": "/preprocess.py", "repo_name": "redyandri/doc2vec-master", "src_encoding": "UTF-8", "text": "from victorinox import victorinox\nimport nltk\nimport pandas as pd\nimport logging\nimport pickle\n\n#enable logging\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\nclass MyIter(object):\n path=\"\"\n def __init__(self,fp):\n self.path=fp\n\n def __iter__(self):\n # path = datapath(self.path)\n with open(self.path, 'r', encoding='utf-8') as fin:\n for line in fin:\n yield line\n\ntool=victorinox()\n\ndatapath_staffs=r\"data/dataset_lower_clean_stem_staff.csv\"\ndatapath_staffs_nip=r\"data/dataset_lower_clean_stem_staff_with_nip.csv\"\ndataset_vector=r\"data/tfidf_per_sentence_vectors.csv\"\ndataset_vector_nip=r\"data/tfidf_per_sentence_vectors_nip.csv\"\ndataset_vector_idseq=r\"data/tfidf_per_sentence_vectors_idseq.csv\"\nstaff_dictionary=r\"data/staff_dictionary.pkl\"\nstaff_dictionary_by_sequence=r\"data/staff_dictionary_by_sequence.pkl\"\nstaff_dictionary_by_sequence_reveresed=r\"data/staff_dictionary_by_sequence_reversed.pkl\"\n# xls_p=r\"C:\\Users\\redy.andriyansah\\Documents\\project\\competence_analytics\\doc2vec\\doc2vec-master\\data\\training.xlsx\"\n# csv_p=r\"C:\\Users\\redy.andriyansah\\Documents\\project\\competence_analytics\\doc2vec\\doc2vec-master\\data\\training.csv\"\n# xls_pegawai=r\"C:\\Users\\redy.andriyansah\\Documents\\project\\competence_analytics\\doc2vec\\doc2vec-master\\data\\pegawai_pusintek.xlsx\"\n# csv_pegawai=r\"C:\\Users\\redy.andriyansah\\Documents\\project\\competence_analytics\\doc2vec\\doc2vec-master\\data\\pegawai.csv\"\n\n# # get name,training\n# tool.convert_xls_to_csv(xls_path=xls_p,\n# csv_path=csv_p,\n# sheet_name=\"training\",\n# row_start_idx=1,\n# column_idx=[1,5])\n#\n# # get nip, name\n# tool.convert_xls_to_csv(xls_path=xls_pegawai,\n# csv_path=csv_pegawai,\n# sheet_name=\"Data\",\n# row_start_idx=1,\n# column_idx=[-2,-1])\n\n# csv_nip_training=r\"C:\\Users\\redy.andriyansah\\Documents\\project\\competence_analytics\\doc2vec\\doc2vec-master\\data\\training_nipname.csv\"\n# tool.merge_csv(csv_path1=csv_p,\n# csv_path2=csv_pegawai,\n# csv_dest=csv_nip_training,\n# sep=\";\",\n# join_op=\"left\",\n# join_col=\"name\")\n\n# name_nip=r\"C:\\Users\\redy.andriyansah\\Documents\\project\\competence_analytics\\doc2vec\\doc2vec-master\\data\\name_nip.csv\"\n# disposisi_nip=r\"C:\\Users\\redy.andriyansah\\Documents\\project\\competence_analytics\\doc2vec\\doc2vec-master\\data\\disposisi_normalized_pusintek2.csv\"\n# disposisi_nipname=r\"C:\\Users\\redy.andriyansah\\Documents\\project\\competence_analytics\\doc2vec\\doc2vec-master\\data\\disposisi_nipname.csv\"\n# tool.merge_csv(csv_path1=disposisi_nip,\n# csv_path2=name_nip,\n# csv_dest=disposisi_nipname,\n# sep=\";\",\n# join_op=\"left\",\n# join_col=\"nip\",\n# out_cols=[\"disposisi\",\"nip\"])\n\n# disposisi_path=r\"C:\\Users\\redy.andriyansah\\Documents\\project\\competence_analytics\\doc2vec\\doc2vec-master\\data\\disposisi_pusintek.csv\"\n# disposisi_normalized_path=r\"C:\\Users\\redy.andriyansah\\Documents\\project\\competence_analytics\\doc2vec\\doc2vec-master\\data\\disposisi_normalized_pusintek.csv\"\n# tool.replace_string_in_file(file_path=disposisi_path,\n# file_path_dest=disposisi_normalized_path)\n\n\n# disposisi_normalized_path=r\"C:\\Users\\redy.andriyansah\\Documents\\project\\competence_analytics\\doc2vec\\doc2vec-master\\data\\disposisi_normalized_pusintek.csv\"\n# disposisi_normalized_path2=r\"C:\\Users\\redy.andriyansah\\Documents\\project\\competence_analytics\\doc2vec\\doc2vec-master\\data\\disposisi_normalized_pusintek2.csv\"\n# tool.switch_columns(disposisi_normalized_path,disposisi_normalized_path2)\n\n# dataset=r\"data/id_kompetensi_flag.csv\"\n# dataset_lower=r\"data/id_kompetensi_flag_lower.csv\"\n# tool.lower_contents(csv_src=dataset,\n# csv_dest=dataset_lower,\n# sep=\";\")\n\n# dataset_lower=r\"data/id_kompetensi_flag_lower.csv\"\n# dataset_lower_clean=r\"data/dataset_lower_clean.csv\"\n# tool.remove_stopwords(csv_src=dataset_lower,\n# csv_dest=dataset_lower_clean,\n# cols_to_clean=[\"KOMPETENSI\"],\n# sep=\";\")\n\n#nltk.download('wordnet')\n\n# dataset_lower_clean=r\"data/dataset_lower_clean.csv\"\n# dataset_lower_clean_stem=r\"data/dataset_lower_clean_stem.csv\"\n# tool.stem(csv_src=dataset_lower_clean,\n# csv_dest=dataset_lower_clean_stem,\n# cols_to_clean=\"KOMPETENSI\",\n# sep=\";\")\n\n# dataset_lower_clean_stem=r\"data/dataset_lower_clean_stem.csv\"\n# dataset_lower_clean_stem_sentence=r\"data/dataset_lower_clean_stem_sentence.csv\"\n# tool.create_sentence_list(csv_src=dataset_lower_clean_stem,\n# csv_dest=dataset_lower_clean_stem_sentence,\n# cols_to_write=\"KOMPETENSI\",\n# sep=\";\")\n\n\n# dataset_lower_clean_stem=r\"data/dataset_lower_clean_stem.csv\"\n# dataset_lower_clean_stem_group=r\"data/dataset_lower_clean_stem_group.csv\"\n# tool.group_sentences(csv_src=dataset_lower_clean_stem,\n# csv_dest=dataset_lower_clean_stem_group,\n# col_to_groupby=\"ID_PEGAWAI\",\n# sep=\";\")\n\n\n# xls_pegawai=r\"data/monitoring data pegawai april 2018 -share.xlsx\"\n# csv_pegawai=r\"data/pegawai.csv\"\n# tool.convert_xls_to_csv(xls_path=xls_pegawai,\n# csv_path=csv_pegawai,\n# sheet_name=\"monev\",\n# row_start_idx=0,\n# column_idx=[0,1,2,3,4,5,6,7,8,9])\n\n\n# csv_employees=r\"data/dataset_lower_clean_stem_group.csv\"\n# csv_leaders=r\"data/leaders.csv\"\n# csv_emploees_noleader=r\"data/dataset_lower_clean_stem_group_staffs.csv\"\n# leaders=[]\n# with open(csv_leaders) as f:\n# leaders=f.read().splitlines()\n# df=pd.read_csv(csv_employees,sep=\";\")\n# ID_PEGAWAI=[]\n# KOMPETENSI=[]\n# for idx,row in df.iterrows():\n# nip=str(row[\"ID_PEGAWAI\"]).split(\"_\")[0]\n# if(nip in leaders):\n# continue\n# ID_PEGAWAI.append(row[\"ID_PEGAWAI\"])\n# KOMPETENSI.append(row[\"KOMPETENSI\"])\n# newdf_json={\"ID_PEGAWAI\":ID_PEGAWAI,\n# \"KOMPETENSI\":KOMPETENSI}\n# newdf=pd.DataFrame(newdf_json)\n# newdf.to_csv(csv_emploees_noleader,sep=\";\",index=None)\n\n\n# csv_emploees_noleader=r\"data/dataset_lower_clean_stem_group_staffs.csv\"\n# csv_emploees_noleader_sentences=r\"data/dataset_lower_clean_stem_group_staffs_sentences.csv\"\n# df=pd.read_csv(csv_emploees_noleader,sep=\";\")\n# df=df.KOMPETENSI\n# df.to_csv(csv_emploees_noleader_sentences,index=None)\n\n\n\n\n# corpus=MyIter(dataset_vector)\n# with open(dataset_vector_nip,\"a+\") as f:\n# for line in corpus:\n# parts=line.split(\";\")\n# vec = parts[0:-1]\n# id = parts[-1].replace(\"\\n\", \"\")\n# nip=id.split(\"_\")[0]\n# l=vec+[nip]\n# f.write(\";\".join(l))\n# f.write(\"\\n\")\n\n\n# corpus=MyIter(dataset_vector)\n# dct={}\n# with open(dataset_vector_nip,\"a+\") as f:\n# for line in corpus:\n# parts=line.split(\";\")\n# id = parts[-1].replace(\"\\n\", \"\")\n# idparts=id.split(\"_\")\n# nip=idparts[0]\n# name = idparts[-1]\n# dct[nip]=name\n# with open(staff_dictionary,\"wb+\") as f:\n# pickle.dump(dct,f)\n# with open(staff_dictionary,\"rb\") as f:\n# kamus=pickle.load(f)\n# print(\"nip:198401112009011004, name:%s\"%(kamus[\"198401112009011004\"]))\n\n\n# corpus=MyIter(dataset_vector)\n# dct={}\n# i=0\n# with open(staff_dictionary,\"rb\") as f:\n# kamus=pickle.load(f)\n# for k,v in kamus.items():\n# dct[i]=k+\"_\"+v\n# i+=1\n# with open(staff_dictionary_by_sequence,\"wb+\") as f:\n# pickle.dump(dct,f)\n# with open(staff_dictionary_by_sequence,\"rb\") as f:\n# kamus2=pickle.load(f)\n# print(\"employee id 0=%s\"%(kamus2[0]))\n\n\n\n# dct={}\n# with open(staff_dictionary_by_sequence,\"rb\") as f:\n# kamus=pickle.load(f)\n# for k,v in kamus.items():\n# dct[v]=k\n# with open(staff_dictionary_by_sequence_reveresed,\"wb+\") as f:\n# pickle.dump(dct,f)\n# with open(staff_dictionary_by_sequence_reveresed,\"rb\") as f:\n# kamus2=pickle.load(f)\n# print(\"employee id 198401112009011004_redyandriyansah=%s\"%(kamus2[\"198401112009011004_redyandriyansah\"]))\n\n\n\n# with open(staff_dictionary_by_sequence_reveresed,\"rb\") as f:\n# kamus=pickle.load(f)\n# corpus=MyIter(dataset_vector)\n# with open(dataset_vector_idseq,\"a+\") as f:\n# for line in corpus:\n# parts=line.split(\";\")\n# vec = parts[0:-1]\n# id = parts[-1].replace(\"\\n\", \"\")\n# newid=str(kamus[id])\n# l=vec+[newid]\n# f.write(\";\".join(l))\n# f.write(\"\\n\")\n\n\n\ndataset_lower_clean_stem=r\"data/dataset_lower_clean_stem_staff.csv\"\ndataset_lower_clean_stem_group_in_lines=r\"data/dataset_lower_clean_stem_staff_group_with_periods.csv\"\ntool.group_sentences(csv_src=dataset_lower_clean_stem,\n csv_dest=dataset_lower_clean_stem_group_in_lines,\n col_to_groupby=\"ID_PEGAWAI\",\n sep=\";\",\n sentence_link=\". \")\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.7783641219139099, "alphanum_fraction": 0.8047493696212769, "avg_line_length": 41.22222137451172, "blob_id": "c7824d483e86f28f82b5c5cc236750bf78557b4d", "content_id": "649cbb7b40cddae3148073b8388c9a70f55394a5", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 379, "license_type": "permissive", "max_line_length": 87, "num_lines": 9, "path": "/train.py", "repo_name": "redyandri/doc2vec-master", "src_encoding": "UTF-8", "text": "from victorinox import victorinox\nfrom gensim.models import FastText\n\n#https://radimrehurek.com/gensim/models/fasttext.html\ndataset_path=r\"data/dataset_lower_clean_stem_sentence.csv\"\nmodel_path=r\"model/fasttext300.bin\"\nfasttext_model= FastText(dataset_path, size=300, window=5, min_count=5, workers=4,sg=1)\nfasttext_model.save(model_path)\nfasttext_model.wv.most_similar(\"nadine\")" }, { "alpha_fraction": 0.678074836730957, "alphanum_fraction": 0.7069518566131592, "avg_line_length": 33.66666793823242, "blob_id": "e690c3d2adc42d7e04f18d43f18a2a67dae4953e", "content_id": "d6cfe3c5c14ed45a433f77ef09693203d19d5d2f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 935, "license_type": "permissive", "max_line_length": 85, "num_lines": 27, "path": "/train_doc2vec.py", "repo_name": "redyandri/doc2vec-master", "src_encoding": "UTF-8", "text": "from gensim.models.doc2vec import Doc2Vec, TaggedDocument\nfrom gensim.utils import tokenize\nfrom gensim import utils\n\nclass MyIter(object):\n path=\"\"\n def __init__(self,fp):\n self.path=fp\n\n def __iter__(self):\n # path = datapath(self.path)\n with utils.open(self.path, 'r', encoding='utf-8') as fin:\n for line in fin:\n yield list(tokenize(line))\n\ndataset_path=r\"data\\dataset_lower_clean_stem_sentence.csv\"\nmodel_path=r\"model\\doc2vec100.bin\"\ncorpus=MyIter(dataset_path)\ndocuments = [TaggedDocument(doc, [i]) for i, doc in enumerate(corpus)]\nd2v_model = Doc2Vec(vector_size=100, window=2, min_count=1, workers=4)\nd2v_model.build_vocab(documents)\nd2v_model.train(documents,total_words=d2v_model.corpus_count,epochs=d2v_model.epochs)\nd2v_model.save(model_path)\n\nmodel_path=r\"model\\doc2vec100.bin\"\nd2v_model = Doc2Vec.load(model_path)\nprint(d2v_model.wv.most_similar([\"naskah\",\"dinas\"]))" }, { "alpha_fraction": 0.6866242289543152, "alphanum_fraction": 0.6989384293556213, "avg_line_length": 31.26027488708496, "blob_id": "a787c54a3520c7e5ad88667d6ec2bcca32b6e95d", "content_id": "4508957950250a4068c6b25816e4200f55746c1d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2355, "license_type": "permissive", "max_line_length": 207, "num_lines": 73, "path": "/app.py", "repo_name": "redyandri/doc2vec-master", "src_encoding": "UTF-8", "text": "import pymssql\nfrom flask import Flask\nfrom flask import render_template\nfrom flask_restful import reqparse, abort, Api, Resource\nimport pickle\nimport numpy as np\nfrom flask import request\nimport flask\nfrom victorinox import victorinox\nimport os\nimport logging\nfrom PIL import Image\n#import cv2\n#import tensorflow as tf\nimport jsonify\nimport sys\nimport pandas as pd\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.neighbors import KNeighborsClassifier\nimport sys\nimport time\nimport json\nfrom flask import Response\n\napp = Flask(__name__,static_url_path='')\napi = Api(app)\ntool=victorinox()\ntfidf_vectors=r\"data/tfidf_group_vectors.csv\"\ntfidf_model=r\"data/tfidf_group_model.pkl\"\ndf=pd.read_csv(tfidf_vectors,sep=\";\",header=None)\ntransformer = TfidfTransformer()\nloaded_vec = CountVectorizer(decode_error=\"replace\",vocabulary=pickle.load(open(tfidf_model, \"rb\")))\nt1=time.time()\nknn = KNeighborsClassifier(n_neighbors=len(df))\nknn.fit(df.iloc[:,:-1], df.iloc[:,-1])\nprint(\"train KNN DONE in %f\"%(time.time()-t1),file=sys.stdout)\n\[email protected]('/user_by_competence', methods = ['GET'])\ndef user_by_competence():\n q = request.args.get(\"q\")\n q = tool.preprocess_sentence(q)\n qv = transformer.fit_transform(loaded_vec.fit_transform([q])).toarray()[0].tolist()\n (distances, indices) = knn.kneighbors([qv], n_neighbors=5)\n indices = indices.tolist()[0]\n res = df.iloc[indices, -1]\n dbConn = pymssql.connect('IP ADDRESS', 'USER', 'PASS', \"DBNAME\")\n oldCursor = dbConn.cursor()\n dbConn.commit()\n data = list(res)\n response = []\n nips = []\n for x in data:\n nips.append(x.split('_')[0])\n query = 'select nama, nip18, ref_unit.nama_organisasi from ref_user inner join ref_unit on ref_user.id_organisasi=ref_unit.id_organisasi where nip18 in (%s)'%(','.join((\"'{0}'\".format(w) for w in nips)))\n print(query)\n oldCursor.execute(query)\n result = []\n for x in oldCursor.fetchall():\n result.append({'nama': x[0], 'nip': x[1], 'unit': x[2]})\n js = json.dumps(result)\n\n resp = Response(js, status=200, mimetype='application/json')\n return json.dumps(result)\n\n\[email protected]('/')\ndef hello_world():\n return render_template(\"index.html\")\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000,debug=True)\n" }, { "alpha_fraction": 0.7003012299537659, "alphanum_fraction": 0.7153614163398743, "avg_line_length": 25.559999465942383, "blob_id": "4be4889b97ce15716f06d9b0d983ed98f28322ca", "content_id": "36445a73c02565398f2e37e75dd7ea4740452038", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 664, "license_type": "permissive", "max_line_length": 110, "num_lines": 25, "path": "/infer_test.py", "repo_name": "redyandri/doc2vec-master", "src_encoding": "UTF-8", "text": "#python example to infer document vectors from trained doc2vec model\nimport gensim.models as g\nimport codecs\n\n#parameters\nmodel=r\"toy_data\\model.bin\"\ntest_docs=r\"toy_data\\test_docs.txt\"\noutput_file=r\"toy_data\\test_vectors.txt\"\n\n#inference hyper-parameters\nstart_alpha=0.01\ninfer_epoch=1000\n\n#load model\nm = g.Doc2Vec.load(model)\ntest_docs = [ x.strip().split() for x in codecs.open(test_docs, \"r\", \"utf-8\").readlines() ]\n\n#infer test vectors\noutput = open(output_file, \"w\")\nfor d in test_docs:\n output.write( \" \".join([str(x) for x in m.infer_vector(d, alpha=start_alpha, steps=infer_epoch)]) + \"\\n\" )\noutput.flush()\noutput.close()\n\n# m.most_similar([\"paris\"])\n" }, { "alpha_fraction": 0.42405471205711365, "alphanum_fraction": 0.4309588372707367, "avg_line_length": 35.44941329956055, "blob_id": "12a1f4015f197d383942564485f5c69673d3f650", "content_id": "aa555d8e7209a0578a770812ac7ce5e6f325382a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15498, "license_type": "permissive", "max_line_length": 114, "num_lines": 425, "path": "/victorinox.py", "repo_name": "redyandri/doc2vec-master", "src_encoding": "UTF-8", "text": "from collections import Counter\nimport pandas as pd\nimport numpy as np\nimport re\nimport csv\nfrom Sastrawi.StopWordRemover.StopWordRemoverFactory import StopWordRemoverFactory,StopWordRemover,ArrayDictionary\nfrom Sastrawi.Stemmer.StemmerFactory import StemmerFactory\nfrom gensim.models import FastText\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk.stem.wordnet import WordNetLemmatizer\nfrom sklearn.metrics.pairwise import cosine_similarity\n\n\nclass victorinox(object):\n def __init__(self):\n return\n\n def check_column_redundancy(self,\n column_id=3,\n fp=\"\\a.csv\"):\n records=[]\n with open(fp,\"r\") as file:\n lines=file.readlines()\n i=0\n for row in lines:\n if i==0:\n i+=1\n continue\n fields=str(row).split(\";\")\n try:\n email = fields[column_id]\n records.append(email)\n except Exception as x:\n print(fields)\n break\n c=Counter(records)\n redundant=[]\n for k,v in c.items():\n if int(v)>1:\n redundant.append(k)\n print(redundant)\n\n def check_column_multivalue(self,\n column_id=3,\n delimiter=\" \",\n fp=\"\\a.csv\"):\n records=[]\n with open(fp,\"r\") as file:\n lines=file.readlines()\n i=0\n for row in lines:\n if i==0:\n i+=1\n continue\n fields=str(row).split(\";\")\n try:\n vals = fields[column_id]\n flds=str(vals).split(delimiter)\n if len(flds)>1:\n records.append(vals)\n except Exception as x:\n print(fields)\n break\n print(records)\n\n def replace_column_string(self,\n column_id=3,\n old=\",\",\n new=\"\",\n fp=\"\\a.csv\",\n dest_fp=\"\\b.csv\"\n ):\n records=[]\n with open(fp,\"r\") as file:\n lines=file.readlines()\n i=0\n for row in lines:\n if i==0:\n i+=1\n continue\n fields=str(row).split(\";\")\n try:\n val = fields[column_id]\n val=str(val).replace(old,new)\n fields[column_id]=val\n l=\";\".join(fields)\n records.append(l)\n except Exception as x:\n print(fields)\n break\n # print(records)\n with open(dest_fp, \"w+\") as f:\n f.writelines(records)\n\n def split_csv_into_batches(self,\n batch_length=400,\n fp=\"\\a.csv\",\n dest_fp=\"\\b.csv\",\n sep=\",\",\n insert_header=False,\n replace_string=False\n ):\n\n df=pd.read_csv(fp,sep=sep,delimiter=sep)\n npd=np.array(df)\n max=len(npd)\n err=0\n for i in range(0,max,batch_length):\n try:\n if i > max:\n break\n d = str(dest_fp).replace(\".csv\", \"_\" + str(i) + \".csv\")\n to = i + batch_length\n arr = npd[i:to, :]\n # arr=np.chararray.encode(arr,\"utf-8\")\n np.savetxt(d, arr, fmt=\"%s\", delimiter=sep,encoding=\"utf-8\")\n if insert_header:\n self.insert_header(d)\n if replace_string:\n self.replace_string(\";nan\", sep, d)\n print(\"saved: \", str(d))\n except Exception as e:\n print(\"Error:\", str(e))\n err+=1\n continue\n print(\"Done. %d erro found\"%(err))\n\n\n def replace_string(self,\n old=\";nan\",\n new=\";\",\n fp=\"\\a.csv\",\n header=None\n ):\n records = []\n with open(fp, \"r\") as file:\n lines = file.readlines()\n i = 0\n for row in lines:\n if header is not None:\n i += 1\n continue\n try:\n val = str(row).replace(old, new)\n records.append(val)\n except Exception as x:\n print(val)\n break\n # print(records)\n with open(fp, \"w+\") as f:\n f.writelines(records)\n\n def insert_header(self,fp=\"\\a.csv\",\n header=\"NAME;LAST_NAME;PASSWORD;EMAIL;LOGIN;\"\n \"IBLOCK_SECTION_NAME_1;IBLOCK_SECTION_NAME_2;IBLOCK_SECTION_NAME_3;\"\n \"IBLOCK_SECTION_NAME_4;IBLOCK_SECTION_NAME_5\\n\"):\n records = []\n with open(fp, \"r\") as file:\n lines = file.readlines()\n i = 0\n records.append(header)\n for row in lines:\n try:\n records.append(row)\n except Exception as x:\n print(row)\n break\n # print(records)\n with open(fp, \"w+\") as f:\n f.writelines(records)\n\n\n def select_by_column_string(self,\n column_id=6,\n column_val=\"Sekretariat Jenderal\",\n fp=\"\\a.csv\",\n dest_fp=\"\\b.csv\",\n header=None\n ):\n records=[]\n with open(fp,\"r\") as file:\n lines=file.readlines()\n i=0\n for row in lines:\n if header is not None:\n if i==0:\n i+=1\n continue\n fields=str(row).split(\";\")\n try:\n val = fields[column_id]\n if val==column_val:\n l=\";\".join(fields)\n records.append(l)\n except Exception as x:\n print(fields)\n break\n # print(records)\n with open(dest_fp, \"w+\") as f:\n f.writelines(records)\n\n\n def select_leaders(self,\n echelon_id=1,\n fp=\"\\a.csv\",\n dest_fp=\"\\b.csv\",\n header=None\n ):\n records=[]\n with open(fp,\"r\") as file:\n lines=file.readlines()\n suffix=\"\"\n if echelon_id==3:\n suffix=\";\"\n elif echelon_id==2:\n suffix=\";;\"\n elif echelon_id==1:\n suffix=\";;;\"\n else:\n suffix=\"\"\n\n i=0\n for row in lines:\n if header is not None:\n if i==0:\n i+=1\n continue\n # fields=str(row).split(\";\")\n try:\n if str(row).__contains__(suffix):\n records.append(row)\n # l=\";\".join(fields)\n # records.append(l)\n except Exception as x:\n print(row)\n break\n # print(records)\n with open(dest_fp, \"w+\") as f:\n f.writelines(records)\n\n def convert_xls_to_csv(self,xls_path=\"\",\n csv_path=\"\",\n sheet_name=\"\",\n index_col=None,\n row_start_idx=1,\n column_idx=[1,5]):\n data_xls = pd.read_excel(xls_path, sheet_name, index_col=index_col)\n data_xls=data_xls.iloc[row_start_idx:,column_idx]\n data_xls.to_csv(csv_path,\n encoding='utf-8',\n index=False,\n sep=\";\",\n header=None)\n print(\"done on %d rows\"%data_xls.shape[0])\n\n def merge_csv(self,csv_path1=\"\",\n csv_path2=\"\",\n csv_dest=\"\",\n sep=\";\",\n join_op=\"left\",\n join_col=\"\",\n out_cols=[\"training\",\"nip\"]):\n data_xls1 = pd.read_csv(csv_path1,sep=sep)\n data_xls2 = pd.read_csv(csv_path2, sep=sep)\n data_xls1 = data_xls1.astype({col: str for col in data_xls1.columns})\n data_xls2 = data_xls2.astype({col: str for col in data_xls2.columns})\n data_xls3=pd.merge(data_xls1,\n data_xls2,\n how=join_op,\n on=join_col)\n data_xls3[\"nip\"]=data_xls3[\"nip\"]+\"_\"+data_xls3[\"name\"]\n if out_cols!= None:\n data_xls3[out_cols].to_csv(csv_dest,encoding='utf-8',index=False,sep=\";\")\n else:\n data_xls3.to_csv(csv_dest,encoding='utf-8',index=False,sep=\";\")\n print(\"done on %d rows\"%data_xls3.shape[0])\n\n def replace_string_in_file(self,\n file_path=\"\",\n file_path_dest=\"\",\n string_to_replace=\"\",\n replacement_string=\"\"):\n regex = re.compile(r\"\\d{18},\", re.IGNORECASE)\n regex2 = re.compile(r\"\\d{18}\", re.IGNORECASE)\n res=[]\n with open(file_path,encoding=\"utf8\") as f:\n lines =f.readlines()\n for line in lines:\n try:\n nip = regex2.findall(line)[0]\n line = regex.sub(nip + \";\", line)\n line=line.replace(\"\\n\",\"\")\n res.append([x for x in line.split(\";\")])\n except Exception as e:\n print(\"error line:%s\"%line)\n continue\n nparr=np.array(res)\n df=pd.DataFrame(nparr)\n df.to_csv(file_path_dest,\n header=None,\n index=None,\n sep=\";\")\n print(\"done saving %d rows\"%len(res))\n\n\n def switch_columns(self,\n csv_path=\"\",\n csv_dest_path=\"\",\n sep=\";\"):\n df=pd.read_csv(csv_path,delimiter=sep,error_bad_lines=False)\n df=df.iloc[:,[-1,-2]]\n df.to_csv(csv_dest_path,\n sep=sep,\n header=None,\n index=None)\n\n def lower_contents(self,\n csv_src=\"\",\n csv_dest=\"\",\n sep=\";\"):\n df=pd.read_csv(csv_src,sep=sep)\n for c in df.columns:\n df[c]=df[c].str.lower()\n df.to_csv(csv_dest,sep=sep,index=None)\n print(\"lower %d rows\"%len(df))\n\n\n def remove_stopwords(self,csv_src=\"\",\n csv_dest=\"\",\n cols_to_clean=[\"KOMPETENSI\"],\n sep=\";\"):\n #factory = StopWordRemoverFactory()\n default_stopwords = StopWordRemoverFactory().get_stop_words()\n additional_stopwords=[\"(\",\")\",\"senin\",\"selasa\",\"rabu\",\"kamis\",\"jumat\",\"sabtu\",\"minggu\"]\n dictionary=ArrayDictionary(default_stopwords+additional_stopwords)\n stopword = StopWordRemover(dictionary)#factory.create_stop_word_remover(dictionary = dictionary)\n tokenizer = RegexpTokenizer(r'\\w+')\n df = pd.read_csv(csv_src, sep=sep)\n for c in cols_to_clean:\n df[c] = df[c].map(lambda x: \" \".join(tokenizer.tokenize(x))) #get only words without symbols\n df[c]=df[c].map(lambda x:stopword.remove(x)) #remove stop words\n df.to_csv(csv_dest, sep=sep, index=None)\n print(\"lower %d rows\" % len(df))\n\n\n def stem(self,csv_src=\"\",\n csv_dest=\"\",\n cols_to_clean=\"KOMPETENSI\",\n sep=\";\"):\n factory = StemmerFactory()\n stemmer = factory.create_stemmer()\n df = pd.read_csv(csv_src, sep=sep)\n df[cols_to_clean]=df[cols_to_clean].astype(str)\n df[cols_to_clean] = df[cols_to_clean].map(lambda x: stemmer.stem(x))\n df.to_csv(csv_dest, sep=sep, index=None)\n print(\"lower %d rows\" % len(df))\n\n def create_sentence_list(self,\n csv_src=\"\",\n csv_dest=\"\",\n cols_to_write=\"KOMPETENSI\",\n sep=\";\"):\n df = pd.read_csv(csv_src, sep=sep)\n df[cols_to_write].to_csv(csv_dest, sep=sep, index=None)\n print(\"lower %d rows\" % len(df))\n\n def document_vector(self,word2vec_model, doc):\n # remove out-of-vocabulary words\n doc = [word for word in doc if word in word2vec_model.wv.vocab]\n return np.mean(word2vec_model[doc], axis=0)\n\n def measure_similarity(self,vec1,vec2):\n vec1=np.array(vec1).reshape(1,-1)\n vec2 = np.array(vec2).reshape(1, -1)\n return cosine_similarity(vec1,vec2)\n\n def group_sentences(self,\n csv_src=\"\",\n csv_dest=\"\",\n col_to_groupby=\"ID_PEGAWAI\",\n col_to_group=\"KOMPETENSI\",\n sep=\";\",\n sentence_link=\" \"):\n df=pd.read_csv(csv_src,sep=sep)\n df2= df.groupby(col_to_groupby)\n ids=[]\n datas = []\n for group_name, dfgroup in df2:\n groupcontent=\"\"\n for idx, row in dfgroup.iterrows():\n groupcontent+=str(row[col_to_group])+sentence_link\n datas.append(groupcontent)\n ids.append(row[col_to_groupby])\n result={col_to_groupby:ids,\n col_to_group:datas}\n dfresult=pd.DataFrame(result)\n dfresult.to_csv(csv_dest, sep=sep, index=None)\n print(\"group into %d rows\"%len(df))\n\n def get_list_from_txt(self,\n txt_src=\"\",\n sep=\";\"):\n with open(txt_src) as f:\n mylist=f.read().splitlines()\n return mylist\n\n def concat_dataframe(self,df1,df2,axis=1,csv_dest=\"\"):\n df3 = pd.concat([df1, df2], axis=1)\n df3.to_csv(csv_dest,sep=\";\",index=None)\n print(\"done merging %d rows\"%len(df3))\n\n def preprocess_sentence(self,q=\"\"):\n #tokenize, lower, stopword,stem\n default_stopwords = StopWordRemoverFactory().get_stop_words()\n additional_stopwords = [\"(\", \")\", \"senin\", \"selasa\", \"rabu\", \"kamis\", \"jumat\", \"sabtu\", \"minggu\"]\n dictionary = ArrayDictionary(default_stopwords + additional_stopwords)\n stopword = StopWordRemover(dictionary)\n factory = StemmerFactory()\n stemmer = factory.create_stemmer()\n tokenizer = RegexpTokenizer(r'\\w+')\n res=\" \".join(tokenizer.tokenize(q))\n res=res.lower()\n res=stopword.remove(res)\n res=factory =stemmer.stem(res)\n return res\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5894760489463806, "alphanum_fraction": 0.6216696500778198, "avg_line_length": 33.653846740722656, "blob_id": "29af5268e58817997f3129c01d4448ef96e99d9c", "content_id": "d92e29a34d53c555e77bd7960d28cce40f60f22e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4504, "license_type": "permissive", "max_line_length": 92, "num_lines": 130, "path": "/train_word2vec.py", "repo_name": "redyandri/doc2vec-master", "src_encoding": "UTF-8", "text": "from gensim.models import Word2Vec\nfrom gensim.utils import tokenize\nfrom gensim import utils\nfrom gensim.test.utils import datapath\nfrom gensim.utils import tokenize\nfrom gensim import utils\nimport logging\nfrom gensim.models import KeyedVectors\nimport gensim.downloader as api\nfrom victorinox import victorinox\n\n#enable logging\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\nclass MyIter(object):\n path=\"\"\n def __init__(self,fp):\n self.path=fp\n\n def __iter__(self):\n # path = datapath(self.path)\n with open(self.path, 'r', encoding='utf-8') as fin:\n for line in fin:\n yield list(tokenize(line))\n\n# #https://radimrehurek.com/gensim/models/doc2vec.html\n# vector_size = 300\n# window_size = 4\n# min_count = 1\n# sampling_threshold = 1e-5\n# negative_size = 5\n# train_epoch = 100\n# dm = 0 #0 = dbow; 1 = dmpv\n# sg=1 #CBOW\n# worker_count = 1\n# dataset_path=r\"data/dataset_lower_clean_stem_sentence.csv\"\n# corpus_file = datapath(dataset_path)\n# model_path=r\"model/word2vec100_cbow.bin\"\n# corpus=MyIter(dataset_path)\n# word2vec_model=Word2Vec(corpus,\n# size=vector_size,\n# window=window_size,\n# min_count=min_count,\n# sample=sampling_threshold,\n# workers=worker_count,\n# hs=0,\n# #dm=dm,\n# negative=negative_size,\n# #dbow_words=1,\n# #dm_concat=1,\n# #pretrained_emb=pretrained_vec,\n# sg=sg,\n# iter=train_epoch)\n# word2vec_model.save(model_path)\n\n# model_path=r\"model/word2vec100_cbow.bin\"\n# w2v_model = Word2Vec.load(model_path)\n# print(w2v_model.wv.most_similar(\"pegawai\"))\n# print(w2v_model.wv.most_similar(\"gaji\"))\n\n\n# vector_size = 300\n# window_size = 4\n# min_count = 1\n# sampling_threshold = 1e-5\n# negative_size = 5\n# train_epoch = 100\n# dm = 0 #0 = dbow; 1 = dmpv\n# sg=0 #SKIP ThOUGHT\n# worker_count = 1\n# dataset_path=r\"data/dataset_lower_clean_stem_sentence.csv\"\n# corpus_file = datapath(dataset_path)\n# model_path=r\"model/word2vec300_skipthought.bin\"\n# corpus=MyIter(dataset_path)\n# word2vec_model=Word2Vec(corpus,\n# size=vector_size,\n# window=window_size,\n# min_count=min_count,\n# sample=sampling_threshold,\n# workers=worker_count,\n# hs=0,\n# #dm=dm,\n# negative=negative_size,\n# #dbow_words=1,\n# #dm_concat=1,\n# #pretrained_emb=pretrained_vec,\n# sg=sg,\n# iter=train_epoch)\n# word2vec_model.save(model_path)\n#\n# model_path=r\"model/word2vec300_skipthought.bin\"\n# w2v_model = Word2Vec.load(model_path)\n# print(w2v_model.wv.most_similar(\"database\"))\n\n\nidwiki_word2vec_model=r\"model/idwiki_word2vec_300/idwiki_word2vec_300.model\"\nidwiki_word2vec_model_retrain=r\"model/idwiki_word2vec_300/idwiki_word2vec_300_retrain.model\"\ndataset_path=r\"data/dataset_lower_clean_stem_sentence.csv\"\ncorpus=MyIter(dataset_path)\nvector_size = 300\nwindow_size = 4\nmin_count = 1\nsampling_threshold = 1e-5\nnegative_size = 5\ntrain_epoch = 100\ndm = 0 #0 = dbow; 1 = dmpv\nsg=0 #SKIP ThOUGHT\nworker_count = 1\nword2vec_model=Word2Vec.load(idwiki_word2vec_model)\n# word2vec_model=api.load(idwiki_word2vec_model)\n# word2vec_model.build_vocab(sentences=corpus,update=True)\n# word2vec_model.train(corpus,\n# total_examples=word2vec_model.corpus_count,\n# epochs=train_epoch)\n# word2vec_model.save(idwiki_word2vec_model_retrain)\nword2vec_model2=Word2Vec.load(idwiki_word2vec_model_retrain)\n# print(word2vec_model.wv.most_similar(\"yang\"))\n# print(word2vec_model2.wv.most_similar(\"yang\"))\ntool=victorinox()\ns1=\"kemampuan analisa sql server\"\ns2=\"analisa jaringan komputer\"\ns3=\"pengolahan database\"\ns1_emb=tool.document_vector(word2vec_model2,s1)\ns2_emb=tool.document_vector(word2vec_model2,s2)\ns3_emb=tool.document_vector(word2vec_model2,s3)\nprint(tool.measure_similarity(s1_emb,s1_emb))\nprint(tool.measure_similarity(s1_emb,s2_emb))\nprint(tool.measure_similarity(s1_emb,s3_emb))\nprint(tool.measure_similarity(s2_emb,s3_emb))\nprint(\".\" in word2vec_model.wv.vocab)" } ]
10
yusuke-matsu/studyPython
https://github.com/yusuke-matsu/studyPython
a03a7448a1cf7eff87e7c223c1de87e3c4e9786a
02739e75b4ccd4b936ed7ba891385446197e9433
d2178d27fbe082be937c5b7bc857d2e7502f1bd5
refs/heads/master
2021-01-02T23:09:55.491623
2017-08-13T09:57:26
2017-08-13T09:57:26
99,481,973
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.43103447556495667, "alphanum_fraction": 0.5517241358757019, "avg_line_length": 14.818181991577148, "blob_id": "cf2e828c401eaf11c97af4b49b304d6ee105c71d", "content_id": "cfdd23d615f49aae19ca23123560462652d6840f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 174, "license_type": "no_license", "max_line_length": 22, "num_lines": 11, "path": "/study2/range.py", "repo_name": "yusuke-matsu/studyPython", "src_encoding": "UTF-8", "text": "print('Im')\nfor i in range(5):\n print(str(i))\n### show 12,13,14,15\nfor i in range(12,16)\n print(str(i))\n\n####show 2 4 6 8\nfor i in range(0,10,2)\n print(str(i))\n####\n" }, { "alpha_fraction": 0.6327345371246338, "alphanum_fraction": 0.6487026214599609, "avg_line_length": 19.875, "blob_id": "e671751942ca9b8940f34ea224bfae5f145161b1", "content_id": "3e137ea7601b55c998952bdcd8e1b7ff6cef77c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 501, "license_type": "no_license", "max_line_length": 51, "num_lines": 24, "path": "/study3/numberGame.py", "repo_name": "yusuke-matsu/studyPython", "src_encoding": "UTF-8", "text": "import random\nsecretNumber = random.randint(1,20)\n\nprint('please ansewer the number between 1 and 20')\n\nfor guessesTaken in range(1,7):\n print('please input number')\n guess = int(input())\n\n if guess < secretNumber:\n print('small')\n\n elif guess > secretNumber:\n print('biggggggggg')\n\n else:\n print('gooooooooood!!')\n break\n\nprint(guess)\nif guess == secretNumber:\n print('collect'+ str(guessesTaken))\nelse:\n print('collet Number is '+ str(secretNumber))\n" }, { "alpha_fraction": 0.5363636612892151, "alphanum_fraction": 0.5363636612892151, "avg_line_length": 14.714285850524902, "blob_id": "37f38bc3a21c80c1fe9ee0a599cd6732507b7aa0", "content_id": "e1b18c90218a82e30e176b0356089a28efb9ec86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 110, "license_type": "no_license", "max_line_length": 27, "num_lines": 7, "path": "/study2/while.py", "repo_name": "yusuke-matsu/studyPython", "src_encoding": "UTF-8", "text": "### while flow\nname = ''\nwhile name != 'test':\n print('what your name')\n name = input()\nprint('OK')\n###\n" }, { "alpha_fraction": 0.6274510025978088, "alphanum_fraction": 0.656862735748291, "avg_line_length": 13.571428298950195, "blob_id": "4e39987a4eb139cfca6233463c7eaa5fe3924808", "content_id": "ddae84561bd14c6f65225a13701af75e0baab7f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 204, "license_type": "no_license", "max_line_length": 29, "num_lines": 14, "path": "/study4/ref.py", "repo_name": "yusuke-matsu/studyPython", "src_encoding": "UTF-8", "text": "import copy\n\ndef eggs(params):\n params.append('hello')\n\nspam = [1,2,3]\neggs(spam)\nprint(spam)\n\nstrList = ['a','b','c','d']\ncopyList = copy.copy(strList)\ncopyList[1] = 42\nprint(strList)\nprint(copyList)\n" }, { "alpha_fraction": 0.6138613820075989, "alphanum_fraction": 0.6303630471229553, "avg_line_length": 17.9375, "blob_id": "31795facbc140a3aa3586ba1577c32d22350ebf1", "content_id": "16262748cb65de1f0d0113bb1dfacff8a6100653", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 303, "license_type": "no_license", "max_line_length": 32, "num_lines": 16, "path": "/study5/directoryFuncs.py", "repo_name": "yusuke-matsu/studyPython", "src_encoding": "UTF-8", "text": "## getfunc\nitems = {'apples':5 , 'books':2}\nprint(str(items.get('books',0)))\nprint(str(items.get('test',0)))\n\n#setdefault\n\ntest = {'name':'alice','age':5}\n# if 'color' not in test:\n# test['color'] = 'black'\n\ntest.setdefault('color','black')\nprint(test)\n\ntest.setdefault('color','white')\nprint(test)\n" }, { "alpha_fraction": 0.7193675637245178, "alphanum_fraction": 0.7272727489471436, "avg_line_length": 20.08333396911621, "blob_id": "9293f334a4ab8ed325de02faf545694ec18ed8a3", "content_id": "158b8b2c5c1dc6f4ac47b53e9343e43651894a2b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 253, "license_type": "no_license", "max_line_length": 85, "num_lines": 12, "path": "/study5/charCount.py", "repo_name": "yusuke-matsu/studyPython", "src_encoding": "UTF-8", "text": "import pprint\n\nmessage = 'it was a bright cokd day in April , and the clocks were striking thirteen'\n\ncount={}\n\nfor character in message:\n count.setdefault(character, 0)\n count[character] = count[character] + 1\n\n#print(count)\npprint.pprint(count)\n" }, { "alpha_fraction": 0.4374009370803833, "alphanum_fraction": 0.4389857351779938, "avg_line_length": 25.29166603088379, "blob_id": "baea347aa68e75222fea124b6b0b568adcb7b92c", "content_id": "9c86e8293c6ac73458dbfad9cf635be13c8e7d01", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 631, "license_type": "no_license", "max_line_length": 62, "num_lines": 24, "path": "/study5/bord.py", "repo_name": "yusuke-matsu/studyPython", "src_encoding": "UTF-8", "text": "theBord = {'top-L':' ', 'top-M':' ', 'top-R':' ',\n 'mid-L':' ', 'mid-M':' ', 'mid-R':' ',\n 'low-L':' ', 'low-M':' ', 'low-R':' '}\n\ndef printBord(bord):\n print(bord['top-L'] +'|'+bord['top-M']+'|'+ bord['top-R'])\n print('-+-+-')\n print(bord['mid-L'] +'|'+bord['mid-M']+'|'+ bord['mid-R'])\n print('-+-+-')\n print(bord['low-L'] +'|'+bord['low-M']+'|'+ bord['low-R'])\n\nturn = 'X'\nfor i in range(9):\n printBord(theBord)\n print(turn+ 's turn. where do you put?')\n move = input()\n theBord[move] = turn\n\n if turn == 'X':\n turn = 'O'\n else:\n turn = 'X'\n\nprintBord(theBord)\n" }, { "alpha_fraction": 0.5997023582458496, "alphanum_fraction": 0.6145833134651184, "avg_line_length": 31, "blob_id": "270b59587b48428d083476c7a7945567052e9c26", "content_id": "5ff7ee597c89d16ffef69922536a7b137dd20137", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 672, "license_type": "no_license", "max_line_length": 53, "num_lines": 21, "path": "/study5/nestBoj.py", "repo_name": "yusuke-matsu/studyPython", "src_encoding": "UTF-8", "text": "allGuests = {'alice': {'apple':5,'banana':6},\n 'bob': {'lemon':10,'cup':5},\n 'tom': {'test':5, 'hoge':10}\n}\n\ndef totalBought(guests,items):\n num = 0\n for key, v in guests.items():\n print(key)\n print(v)\n num = num + v.get(items,0)\n return num\n\nprint('items number')\nprint('apple'+ str(totalBought(allGuests, 'apple')))\nprint('banana'+ str(totalBought(allGuests,'banana')))\nprint('lemon'+ str(totalBought(allGuests,'lemon')))\nprint('cup'+ str(totalBought(allGuests,'cup')))\nprint('test'+ str(totalBought(allGuests,'test')))\nprint('hoge'+ str(totalBought(allGuests,'hoge')))\nprint('ok'+ str(totalBought(allGuests,'ok')))\n" }, { "alpha_fraction": 0.6749116778373718, "alphanum_fraction": 0.6784452199935913, "avg_line_length": 30.44444465637207, "blob_id": "0343fa5938968b11d1ac13c7f2a9e5436888001c", "content_id": "4fce99c13691ea763c0414e20998688d4fc81648", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 283, "license_type": "no_license", "max_line_length": 55, "num_lines": 9, "path": "/study1/test.py", "repo_name": "yusuke-matsu/studyPython", "src_encoding": "UTF-8", "text": "print('hello world')\nprint('what your name?')\nmyName = input() #input name from console\nprint('it is good to meet you '+ myName)\nprint('the length of your name is:')\nprint(len(myName))\nprint('what is your age')\nmyAge = input()\nprint('you will be'+ str(int(myAge) + 1)+ 'in a year.')\n" }, { "alpha_fraction": 0.6767857074737549, "alphanum_fraction": 0.6964285969734192, "avg_line_length": 17.064516067504883, "blob_id": "151fcf3bd6c70e4c5789a521d7d46722db4870b9", "content_id": "bd0987fc1b9c23ae233bfb20842aa016f42144f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 560, "license_type": "no_license", "max_line_length": 49, "num_lines": 31, "path": "/study4/forList.py", "repo_name": "yusuke-matsu/studyPython", "src_encoding": "UTF-8", "text": "supplies = ['pen','staplers', 'flower','binders']\n\nfor i in range(len(supplies)):\n print(str(i) + '' + supplies[i])\n\n## check index number\n\n# express number 0\nprint(supplies.index('pen'))\n\nsupplies.append('goods')\n\n##append goods end of supplies\nprint(supplies)\n\nsupplies.insert(2, 'human')\n##human insert index 2 to supplies\nprint(supplies)\n\nsupplies.remove('pen')\n\n##remove pen from supplies\nprint(supplies)\n\n\nnumberList = [-7,23,11,32,5]\nstrList = ['apple','king','cook','test','burger']\nnumberList.sort()\nstrList.sort()\nprint(numberList)\nprint(strList)\n" }, { "alpha_fraction": 0.5656565427780151, "alphanum_fraction": 0.5656565427780151, "avg_line_length": 11.375, "blob_id": "0915b69d00e44503bc688e452e8b24c646fb36c4", "content_id": "9b0665791ecd001f3378beedee9bcab9186e2382", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 99, "license_type": "no_license", "max_line_length": 25, "num_lines": 8, "path": "/study3/function.py", "repo_name": "yusuke-matsu/studyPython", "src_encoding": "UTF-8", "text": "def hello():\n print('hello')\n print('hi')\n print('good morning')\n\nhello()\nhello()\nhello()\n" }, { "alpha_fraction": 0.5534188151359558, "alphanum_fraction": 0.5683760643005371, "avg_line_length": 28.25, "blob_id": "d9b78e1f2973f01db8322479e55d4ff5cd7442e8", "content_id": "f1c6eac3ddfa4ffe4963a3775a52f108d6e1cd42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 468, "license_type": "no_license", "max_line_length": 71, "num_lines": 16, "path": "/study5/dictionary.py", "repo_name": "yusuke-matsu/studyPython", "src_encoding": "UTF-8", "text": "birthdays = {'alice':'4/1','bob':'2/1', 'iva':'2/21'}\n\nwhile True:\n print('please input the name. if you want to quite, please enter ')\n name = input()\n if name == '':\n break\n\n if name in birthdays:\n print(name + 'birthday is' + birthdays[name])\n else:\n print(name + 'birthday is not recorded')\n print('please input birthday')\n birthday = input()\n birthdays[name] = birthday\n print('update birthday!!!')\n" }, { "alpha_fraction": 0.5617647171020508, "alphanum_fraction": 0.5882353186607361, "avg_line_length": 21.66666603088379, "blob_id": "188ee49d76c8c6a49c444e6f1b54c301df2f3a43", "content_id": "694e752d0c28b5248a02e52a42923e2ecbb5bae4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 340, "license_type": "no_license", "max_line_length": 45, "num_lines": 15, "path": "/study2/block.py", "repo_name": "yusuke-matsu/studyPython", "src_encoding": "UTF-8", "text": "## how to write flow if and else\nif name == 'mary'\n print('hello')\n if password == 'test':\n print('complete')\n else:\n print('NG')\n\n## how to wirte flow elseif\nif name == 'alice':\n print('hi alice')\nelif age < 12:\n print('you are not alice')\nelif age >2000000\n print('you are not alice. you are zonbe')\n" }, { "alpha_fraction": 0.6015625, "alphanum_fraction": 0.6015625, "avg_line_length": 24.600000381469727, "blob_id": "4741fcc006e6b78cb2af0896ba6351502996ec33", "content_id": "9c3dd5b584435d65de8cdcbd2a4172b81ee96110", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 256, "license_type": "no_license", "max_line_length": 73, "num_lines": 10, "path": "/study4/list.py", "repo_name": "yusuke-matsu/studyPython", "src_encoding": "UTF-8", "text": "catNames = []\nwhile True:\n print('please enter the name of cat. If you want to end, type enter')\n name = input()\n if name == '':\n break\n catNames = catNames + [name]\nprint('cat name is bellow')\nfor name in catNames:\n print(' '+ name)\n" } ]
14
kamreo/Webmap
https://github.com/kamreo/Webmap
2aec06782e57b9d736314fc794dbbe55bf1bc1b7
1b0ef74cf885aa7d737061de13f7ef49e678f856
32fbabb14c4db26b538d2ee8b863f73f6b44145c
refs/heads/master
2021-04-09T04:30:17.049928
2020-08-05T22:14:48
2020-08-05T22:14:48
248,838,629
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7916666865348816, "alphanum_fraction": 0.7916666865348816, "avg_line_length": 23, "blob_id": "c693ac01700b30bf797bbad3c861ad2401142f04", "content_id": "490fac222f6a9b5396291709f45195479228d145", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 48, "license_type": "permissive", "max_line_length": 38, "num_lines": 2, "path": "/README.md", "repo_name": "kamreo/Webmap", "src_encoding": "UTF-8", "text": "# Webmap\n Webmap with python and folium library\n" }, { "alpha_fraction": 0.5659679174423218, "alphanum_fraction": 0.6048088669776917, "avg_line_length": 27.127166748046875, "blob_id": "b8401a739a750db95a9a6beb661530df8eca6d74", "content_id": "226c52e1523758cb90a794e9511102dfd8b8482e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4866, "license_type": "permissive", "max_line_length": 118, "num_lines": 173, "path": "/map1.py", "repo_name": "kamreo/Webmap", "src_encoding": "UTF-8", "text": "import folium\nimport pandas as pd\nimport random\nimport numpy as np\nfrom branca.element import Template, MacroElement\n\ndata=pd.read_csv(\"Volcanoes_USA.txt\")\n\ndef color_maker(elevation):\n if elevation <1000:\n return 'green'\n elif 1000<=elevation<3000:\n return 'orange'\n else:\n return 'red'\n\nmap = folium.Map( location=[48.853, 2.35], zoom_start=6, tiles='cartodbdark_matter')\n\nfg = folium.FeatureGroup(name=\"My Map\")\n\nlatitude=list(data[\"LAT\"])\nlongitude=list(data[\"LON\"])\nelevation= list(data[\"ELEV\"])\n\nfgv = folium.FeatureGroup(name=\"Volcanoes in USA\")\n\nfor lt,ln,el in zip(latitude,longitude,elevation):\n popup_message=\"Height: \"+str(el)+\"m\"\n fgv.add_child(folium.CircleMarker(location=[lt,ln], radius =6, fill_color=color_maker(el),\n popup=popup_message, color = 'black',fill_opacity=0.7, fill=True))\n\n\nfgp=folium.FeatureGroup(name=\"Population\")\n\nfgp.add_child(folium.GeoJson(data=open('world.json','r',encoding='utf-8-sig').read(),\n style_function=lambda x: {'fillColor':'blue' if x['properties']['POP2005']<9000000\n else 'green' if 9000000 <= x['properties']['POP2005']<20000000\n else 'yellow' if 20000000<= x['properties']['POP2005']<100000000\n else 'red'}))\n\n\n\ntemplate = \"\"\"\n{% macro html(this, kwargs) %}\n\n<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <title>Map</title>\n <link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n\n <script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n <script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n\n <script>\n $( function() {\n $( \"#maplegend\" ).draggable({\n start: function (event, ui) {\n $(this).css({\n right: \"auto\",\n top: \"auto\",\n bottom: \"auto\"\n });\n }\n });\n});\n\n </script>\n</head>\n<body>\n\n\n<div id='maplegend' class='maplegend'\n style='position: absolute; z-index:9999; border:2px solid grey; background-color:rgba(255, 255, 255, 0.8);\n border-radius:6px; padding: 10px; font-size:14px; right: 20px; bottom: 20px;'>\n\n<div class='legend-title'>Population size</div>\n<div class='legend-scale'>\n <ul class='legend-labels'>\n <li><span style='background:red;opacity:0.7;'></span>Big (more than 100 million people)</li>\n <li><span style='background:orange;opacity:0.7;'></span>Medium (between 20 and 100 million people)</li>\n <li><span style='background:green;opacity:0.7;'></span>Small (between 10 and 20 million people)</li>\n <li><span style='background:blue;opacity:0.7;'></span>Very Small (less than 10 million people)</li>\n\n </ul>\n</div>\n</div>\n\n</body>\n</html>\n\n<style type='text/css'>\n .maplegend .legend-title {\n text-align: left;\n margin-bottom: 5px;\n font-weight: bold;\n font-size: 90%;\n }\n .maplegend .legend-scale ul {\n margin: 0;\n margin-bottom: 5px;\n padding: 0;\n float: left;\n list-style: none;\n }\n .maplegend .legend-scale ul li {\n font-size: 80%;\n list-style: none;\n margin-left: 0;\n line-height: 18px;\n margin-bottom: 2px;\n }\n .maplegend ul.legend-labels li span {\n display: block;\n float: left;\n height: 16px;\n width: 30px;\n margin-right: 5px;\n margin-left: 0;\n border: 1px solid #999;\n }\n .maplegend .legend-source {\n font-size: 80%;\n color: #777;\n clear: both;\n }\n .maplegend a {\n color: #777;\n }\n</style>\n{% endmacro %}\"\"\"\n\nmacro = MacroElement()\nmacro._template = Template(template)\n\nmap.get_root().add_child(macro)\nmap.add_child(fgv)\nmap.add_child(fgp)\nmap.add_child(folium.LayerControl())\n\n\n\n\n#code for generating random coordinates\n# w, h = 2, 10;\n# generated_coordinates = [[0 for x in range(w)] for y in range(h)]\n#\n# # generating random coordinates\n# for x in range (0,h):\n# latitude=random.uniform(-90,90)\n# longitude=random.uniform(-180,180)\n# generated_coordinates[x][0]=latitude\n# generated_coordinates[x][1]=longitude\n#\n# generated_coordinates=np.array(generated_coordinates)\n# dimensions=generated_coordinates.shape\n# rows=dimensions[0]\n# columns=dimensions[1]\n\n# creating markers using our coordinates array\n\n# for x in range(0,rows):\n#\n# popup_message=\"Latitude:{} Longitude:{}\".format(generated_coordinates[x][0],generated_coordinates[x][1])\n# fg.add_child(folium.Marker(location=generated_coordinates[x],\n# popup=popup_message,icon=folium.Icon(color='white')))\n#\n# map.add_child(fg)\n\n\nmap.save(\"index.html\")\n" } ]
2
victorhahncastell/sqltool
https://github.com/victorhahncastell/sqltool
a8db2b58dcad3b78545ac19b3b96b3856431e4b2
bfb48ff400479ecf60b7d4ec2675d73b685e23ee
44ff3bd8c2d91a662dedab42cd71c9f224cb0870
refs/heads/master
2019-01-02T02:35:29.499163
2018-01-15T15:35:14
2018-01-15T15:35:14
15,349,183
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6456437110900879, "alphanum_fraction": 0.6478897929191589, "avg_line_length": 38.34418487548828, "blob_id": "3612603dc13d0484c54b88e59716dd1f4b58b4a5", "content_id": "e19a7c14aee9899d71dd6c838dd8c31a64681f50", "detected_licenses": [ "WTFPL" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16918, "license_type": "permissive", "max_line_length": 135, "num_lines": 430, "path": "/sqltool.py", "repo_name": "victorhahncastell/sqltool", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n## @mainpage\n# sqltool analyzes SQL scripts or logs.\n# It's main use is determining read/write ratios and the distribution of writes over transactions\n# which is a crucial factor influencing performance in distributed database systems.\n#\n# @author Victor Hahn\n# @author [email protected]\n# @version 0.1.1\n#\n## @copyright\n# Copyright 2013, Flexoptix GmbH.\n# This work is free. Do with it whatever you want.\n# To emphasize, this work is officially licensed under the terms of the\n# Do What The Fuck You Want To Public License (WTFPL), Version 2, as published by Sam Hocevar.\n\n\n# load always needed libraries\nimport argparse\nimport re\nimport sys\nimport math\n\n\n##\n# Reads data from a text file.\n# Provides for a callback after each line read.\nclass FileParser:\n ##\n # @param inputfile File handler to read from. Default is standard input.\n # @param preformat If the input file is not a plain SQL script, specify its type.\n # So far, only MySQL General Query Logs (\"gql\") are supported besides plain SQL.\n # @param linecallback Reference to a function which shall be call after each line read.\n # This function must accept exactly one line of text as parameter.\n def __init__(self, inputfile=sys.stdin, preformat=False, linecallback = False):\n self.inputfile = inputfile\n self.preformat = preformat\n self.linecallback = linecallback\n\n def read_line(self):\n self.process_line(self.inputfile.read_line())\n\n def readall(self):\n for line in self.inputfile:\n self.process_line(line)\n\n def process_line(self, line):\n if self.preformat==\"gql\":\n pattern = re.compile(\" Query\\t\")\n parts = pattern.split(line)\n if len(parts)>1:\n line = parts[1]\n else:\n return\n if self.linecallback:\n self.linecallback(line)\n\n\n##\n# Provides static methods to split SQL statements and get their types.\n# Can be configured to use the sqlparse library or a faster (and probably more error prone)\n# string operation based solution as backend.\nclass SqlWrapper:\n ##\n # Split a line of SQL code into a list of individual statements.\n # If you've chosen the fast and dirty implementation, this basically splits the line by semicolons.\n @staticmethod\n def sqlsplit(input):\n splitted = sqlparse.split(input)\n return splitted\n\n ##\n # Extract the type of SQL instruction from a single SQL statement.\n # If you've chosen the fast and dirty implementation, this basically gives you\n # the statement's first word.\n @staticmethod\n def sqlparsetype(input):\n type = sqlparse.parse(input)[0].get_type()\n return type\n\n ##\n # Fast and dirty implementation of the sqlsplit method.\n @staticmethod\n def manualsplit(input):\n # split at semicolon; then remove leading whitespace\n splittedRaw = input.split(\";\")\n splitted = []\n for statement in splittedRaw:\n statement = statement.lstrip()\n # discard empty \"statements\" (e.g. just a semicolon)\n if statement != \"\": splitted.append(statement)\n return splitted\n\n ##\n # Fast and dirty implementation of the sqlparsetype method.\n @staticmethod\n def manualparsetype(input):\n splitted = input.split(\" \");\n return splitted[0].rstrip()\n\n # static member initialization\n # default to sqlparse backend\n split = manualsplit\n parsetype = manualparsetype\n\n\n##\n# Groups SQL statements into transactions for further analyzation.\nclass TransactionSplitter:\n ##\n # @param autocommit Whether the DBMS this log comes from ran in autocommit mode.\n # In autocommit mode, statements which are not surrounded by a BEGIN/COMMIT block\n # are committed instantaneously.\n # Otherwise (in standard SQL code), a statement automatically opens a new transaction\n # which will only be committed when explicitly told so.\n # @param transactioncallback Shall we call a function after each transaction we identified?\n # If so, this parameter must be set to a function or closure to be called.\n # @param savetransaction Shall we keep a list of all transactions in RAM?\n # If not, each transaction will be discarded immediately after it has been completely identified\n # and the transaction callback was performed, if applicable.\n # @param stats Whether to store transaction sized for statistics.\n def __init__(self, autocommit=True, transactioncallback=False, savetransaction=False, stats=False):\n self.autocommit = autocommit\n self.savetransaction = savetransaction\n self.transactioncallback = transactioncallback\n self.stats = stats\n\n ## @property transactions\n # will contain a list of all transactions\n # each transaction is itself a list of statements\n # each statement is a string\n self.transactions = []\n\n ## @property transactionsizes\n # Will contain a list of transaction sizes, i.e. number of statements per transaction\n self.transactionsizes = []\n\n ## @property currentTransaction\n ## @private The transaction currently being parsed.\n # Will be added to transactions when parsing is finished.\n self.currentTransaction = []\n\n ## @property manualTransaction\n ## @private will be set to True if there is an explicit BEGIN or START in autocommit mode\n self.manualTransaction = False\n\n ## @property largest\n # The largest number of statements encountered in a transaction.\n self.largest = False\n\n ## @property smallest\n # The smallest number of statements encountered in a transaction.\n self.smallest = False\n\n ## @property mean\n # Mean number of statements per transaction.\n # calcstats() must be called to calculate this value.\n self.mean = False\n\n ## @property std\n # Standard deviation from the mean number of statements per transaction.\n # calcstats() must be called to calculate this value.\n self.std = False\n\n ##\n # Analyze a single line of SQL code.\n # A line may contain multiple statements.\n # This method can be used as a callback for a fileparser object.\n # @param line A new line of code to be analyzed.\n def execute_line(self, line):\n statements = SqlWrapper.split(line)\n for statement in statements:\n self.handle_statement(statement)\n\n ##\n # Analyze a single SQL statement\n # @param statement A new statement to be analyzed.\n def handle_statement(self, statement):\n type = SqlWrapper.parsetype(statement)\n if type == \"BEGIN\" or type == \"START\":\n self.manualTransaction = True\n elif type == \"COMMIT\" or type == \"ROLLBACK\":\n self.finalize_transaction()\n else:\n self.currentTransaction.append(statement)\n if self.autocommit and not self.manualTransaction:\n self.finalize_transaction()\n\n ##\n # Private method which will be called after a complete transaction has been identified.\n def finalize_transaction(self):\n # Save processed transaction to array if this feature is enabled:\n if self.savetransaction:\n self.transactions.append(self.currentTransaction)\n\n # Perform per-transaction callback if this feature is enabled:\n if self.transactioncallback:\n self.transactioncallback(self.currentTransaction)\n\n # Save transaction size for statistics if this feature is enabled:\n if self.stats == True:\n if len(self.currentTransaction) > 0:\n self.transactionsizes.append(len(self.currentTransaction))\n\n # clean up an discard current transaction\n self.currentTransaction = []\n self.manualTransaction = False\n\n ##\n # Update object's statistics, calculate mean transaction size and standard deviation.\n def calcstats(self):\n # Did we even collect data?\n if len(self.transactionsizes) == 0: return False, False\n\n # calculate mean and determine largest/smallest transaction\n sum = 0\n self.largest = False\n self.smallest = False\n for value in self.transactionsizes:\n sum += value\n if not self.largest or value > self.largest: self.largest = value\n if not self.smallest or value < self.smallest: self.smallest = value\n self.mean = float(sum) / len(self.transactionsizes)\n\n # calculate standard deviation\n sum = 0\n for value in self.transactionsizes:\n summand = (self.mean-value)**2\n sum += summand\n self.std = math.sqrt(sum / ( len(self.transactionsizes) - 1))\n\n\n##\n# Analyzes transactions for write operations.\n# Stores the number of transactions containing at least one write.\nclass WriteCounter:\n ##\n # @param transactions A list of transactions to analyze.\n # Expected to be a list of transactions where each transaction is a list of statements.\n # Incidentally, this is exactly what the output a TransactionSplitter looks like.\n def __init__(self, transactions = []):\n\n ## @property transactions\n # Store of all transactions to analyze.\n # Note that it is not necessary to use this store; transactions can also be analyzed\n # one by one (e.g. by using analyzeTransaction as a callback from a TransactionSplitter)\n self.transactions = transactions\n\n ## @property total\n # Total number of transactions analyzed.\n # Is 0 on construction as transaction will be counted as they are analyzed.\n self.total = 0\n\n ## @property withwrite\n # Result will be stored here: Number of transactions containing writes.\n self.withwrite = 0\n\n ##\n # Analyzes all transactions currently stored in this object.\n # Note that calling this two times might well double your result.\n def analyze_all(self):\n for transaction in self.transactions:\n self.analyze_transaction(transaction)\n\n ##\n # Analyze a single transaction given as parameter.\n # Note that calling this two times on the same transaction might well double your result.\n # @param transaction Transaction to be analyzed as a list of statements\n def analyze_transaction(self, transaction):\n write = False\n for statement in transaction:\n write = self.analyze_statement(statement)\n if write: break\n self.total = self.total + 1\n if write:\n self.withwrite = self.withwrite + 1\n\n ##\n # Analyze a single line of raw SQL code, possibly containing multiple statements.\n # This (only) makes sense if you want to determine a statement write ratio,\n # not a transaction based one.\n # @param line Line of raw SQL code to be analyzed.\n def analyze_line(self, line):\n statements = SqlWrapper.split(line)\n for statement in statements:\n self.total += 1\n if self.analyze_statement(statement): self.withwrite += 1\n\n ##\n # Analyze a single SQL statement.\n # @param statement Single statement to be analyzed.\n # @return True if this statement is a write, false otherwise.\n def analyze_statement(self, statement):\n type = SqlWrapper.parsetype(statement)\n if type == \"UPDATE\" or type == \"INSERT\" or type == \"DELETE\":\n return True\n\n\nclass PrintWriter:\n def __init__(self, parser):\n self.parser = parser\n global args\n if args.output is not None:\n self.file = open(args.output, 'w')\n else:\n self.file = None\n\n self.parser.linecallback = self.write_line\n self.parser.readall()\n\n def write_line(self, text):\n text = text.rstrip(\"\\r\\n\")\n if self.file is not None:\n self.file.write(text + \"\\n\")\n else:\n print(text)\n\n\n# HELPER FUNCTIONS\ndef make_fileparser():\n p = FileParser(preformat=args.preformat)\n if args.inputfile != \"-\":\n file = open(args.inputfile)\n p.inputfile = file\n return p\n\n\ndef make_transaction_splitter():\n a = TransactionSplitter(stats=True)\n if args.autocommit == \"no\":\n a.autocommit = False\n return a\n\n\ndef main():\n ##\n # Parse command line arguments, then determine which additional libraries to import\n # also provide command line help\n parser = argparse.ArgumentParser(\n description=\"A tool to determine the write ratio of SQL script, group SQL queries by transaction, and other purposes.\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\"action\", choices=[\"writeratio\", \"split\", \"print\"],\n help=\"Select what to do.\\n\" +\n \"writeratio calculates the percentage of writes in the log.\\n\" +\n \"split writes each transaction to its own file.\\n\" +\n \"print just echoes the SQL script (after any specified preprocessing has been applied)\")\n parser.add_argument(\"--base\", \"-b\", default=\"transaction\", choices=[\"transaction\", \"statement\"],\n help=\"Whether to use whole transactions or single statements as base blocks of information, where applicable.\")\n parser.add_argument(\"--autocommit\", \"-c\", default=\"yes\", choices=[\"yes\", \"no\"],\n help=\"Specify whether this script is supposed to run in autocommit mode\")\n parser.add_argument(\"--preformat\", \"-f\", default=\"none\", choices=[\"none\", \"gql\"],\n help=\"Preformat the input file. \\\"gpl\\\" expects a MySQL General Query Log.\")\n parser.add_argument(\"--parsemode\", \"-p\", default=\"quick\", choices=[\"quick\", \"slow\"],\n help=\"Switch between quick'n'dirty and slow'n'correct SQL parsing. Possibly correct, that is.\")\n parser.add_argument(\"--inputfile\", \"-i\", default=\"-\", help=\"File with input data. \\\"-\\\" means stdin.\")\n parser.add_argument(\"--output\", \"-o\", help=\"Base name for output file. Only needed for action split.\")\n\n global args\n args = parser.parse_args()\n\n # conditional imports\n if args.parsemode == \"slow\":\n try:\n global sqlparse\n import sqlparse\n except ImportError:\n print(\"To use --parsemode slow please install the sqlparse library: pip install sqlparse\")\n exit(1)\n\n # set global/static stuff according to arguments\n if args.parsemode == \"slow\":\n SqlWrapper.split = staticmethod(SqlWrapper.sqlsplit)\n SqlWrapper.parsetype = staticmethod(SqlWrapper.sqlparsetype)\n\n if args.action == \"writeratio\":\n fileparser = make_fileparser()\n transactionsplitter = make_transaction_splitter()\n writecounter = WriteCounter()\n\n if args.base == \"transaction\":\n fileparser.linecallback = transactionsplitter.execute_line\n transactionsplitter.transactioncallback = writecounter.analyze_transaction\n fileparser.readall()\n transactionsplitter.calcstats()\n ratio = float(writecounter.withwrite*100)/writecounter.total\n print(\"Total number of transactions: \" + str(writecounter.total))\n print(\"Transactions containing writes: \" + str(writecounter.withwrite))\n print(\"Ratio: \" + \"{:.2f}\".format(ratio) + \"%\")\n print(\"Mean transaction size: \" + \"{:.2f}\".format(transactionsplitter.mean) + \" (s = \" +\n \"{:.2f}\".format(transactionsplitter.std) + \", smallest \" + str(transactionsplitter.smallest) +\n \", largest \" + str(transactionsplitter.largest) + \")\")\n\n elif args.base == \"statement\":\n fileparser.linecallback = writecounter.analyze_line\n fileparser.readall()\n ratio = float(writecounter.withwrite*100)/writecounter.total\n print(\"Total number of statements: \" + str(writecounter.total))\n print(\"Write statements: \" + str(writecounter.withwrite))\n print(\"Ratio: \" + \"{:.2f}\".format(ratio) + \"%\")\n else:\n return False\n\n if args.action == \"split\":\n if args.base == \"statement\":\n print(\"Sorry, split is not implemented for --base statement.\")\n sys.exit()\n if not args.output:\n print(\"Cannot split file if output file not specified.\")\n sys.exit()\n\n p = make_fileparser()\n a = make_transaction_splitter()\n p.linecallback = a.execute_line\n a.savetransaction=True\n p.readall()\n counter = 1\n for transaction in a.transactions:\n file = open(args.output + str(counter), \"w\")\n for line in transaction:\n file.write(line)\n counter += 1\n\n if args.action == \"print\":\n parser = make_fileparser()\n writer = PrintWriter(parser)\n\n\nif __name__== \"__main__\":\n main()\n" }, { "alpha_fraction": 0.7777777910232544, "alphanum_fraction": 0.7875243425369263, "avg_line_length": 41.75, "blob_id": "9463af69e804d72281a6aa712b49da2fb20f9aea", "content_id": "87da1e9cea2f907a1ac057bfe5e1e638d7f624b8", "detected_licenses": [ "WTFPL" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 513, "license_type": "permissive", "max_line_length": 178, "num_lines": 12, "path": "/README.md", "repo_name": "victorhahncastell/sqltool", "src_encoding": "UTF-8", "text": "# sqltool\nsqltool analyzes SQL scripts or logs.\n\nIt's main use is determining read/write ratios and the distribution of writes over transactions which is a crucial factor influencing performance in distributed database systems.\n\n## Licensing\nCopyright 2013, Flexoptix GmbH.\n\nThis work is free. Do with it whatever you want.\n\nTo emphasize, this work is officially licensed under the terms of the\nDo What The Fuck You Want To Public License (WTFPL), Version 2, as [published by Sam Hocevar](http://www.wtfpl.net/).\n" } ]
2
cudjoeab/programming_reinforcement
https://github.com/cudjoeab/programming_reinforcement
1e290dce6739509d48205f33239d23f185bc5011
11d6ae2949dce3cc1cc993f69a59fb95eceafa8b
41a2b567be186de797b662fc6ca9ac91275ecd06
refs/heads/master
2020-06-28T00:42:01.660356
2019-08-02T01:42:02
2019-08-02T01:42:02
200,096,278
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5368098020553589, "alphanum_fraction": 0.5398772954940796, "avg_line_length": 33.26315689086914, "blob_id": "792c2aed38b42b8757dc330804f427a69c1d688d", "content_id": "422c0d32697bdafe6bc8d0a741d722857d45c390", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 652, "license_type": "no_license", "max_line_length": 103, "num_lines": 19, "path": "/seating.py", "repo_name": "cudjoeab/programming_reinforcement", "src_encoding": "UTF-8", "text": "classroom_seating = [\n [None, \"Pumpkin\", None, None],\n [\"Socks\", None, \"Mimi\", None],\n [\"Gismo\", \"Shadow\", None, None],\n [\"Smokey\",\"Toast\",\"Pacha\",\"Mau\"]\n]\n\ndef find_free_seats(classroom): \n new_classroom = classroom \n for row_index, row in enumerate(classroom):\n for col_index, column in enumerate(row):\n\n if not column: \n print(f'Row {row_index+1} seat {col_index+1} is free. Do you want to sit there? (y/n)')\n sit_here = input().lower()\n\n if sit_here == 'y':\n print('What is your name?')\n new_classroom[row_index][col_index] = your_name\n\n" } ]
1
kaushalmeena1996/myapp-blog
https://github.com/kaushalmeena1996/myapp-blog
6e765abadcccc63e4e1ea708e103c2a0c92688c3
7f2b95e6d8b4d40ba10745ecc4efae323596d756
8196a102e8b7d6f24ee0a361f1e3530c869e3cd2
refs/heads/master
2020-01-23T21:37:52.842063
2016-11-24T12:03:19
2016-11-24T12:03:19
74,692,642
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5497679114341736, "alphanum_fraction": 0.550283670425415, "avg_line_length": 30.786884307861328, "blob_id": "874d9eab145ab734ba1994c50bfb50d6c8aa805c", "content_id": "99acafadbbf7f4bd8e0259ddd4a8e1a353bad417", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1939, "license_type": "no_license", "max_line_length": 73, "num_lines": 61, "path": "/handlers/signin.py", "repo_name": "kaushalmeena1996/myapp-blog", "src_encoding": "UTF-8", "text": "#signin.py\n\"\"\"Contains class defination for handler class SignInHandler.\"\"\"\n\nfrom blog import BlogHandler\nfrom models.user import USER\nfrom helper.helper import valid_username, valid_password\n\nclass SignInHandler(BlogHandler):\n \"\"\"Handler for SIGN-IN page which allows users to login.\"\"\"\n\n def get(self):\n \"\"\"Renders SIGN-IN page if user has not logged in otherwise\n renders WELCOME page.\"\"\"\n\n if self.user:\n self.redirect(\"/welcome\")\n else:\n self.render(\"signin.html\", page_title = \"SIGN-IN\")\n\n def post(self):\n \"\"\"Validates user sign-in's form information for errors and\n accordingly redirects the page.\"\"\"\n\n username = self.request.get(\"username\")\n password = self.request.get(\"password\")\n\n err_username = ''\n err_password = ''\n\n signin_err = False\n\n if not valid_username(username):\n err_username = \"Please enter valid username !\"\n signin_err = True\n\n if not valid_password(password):\n err_password = \"Password must contain atleast 3 characters !\"\n signin_err = True\n\n template_values = {\n 'page_title': 'SIGN-IN',\n 'err_username': err_username,\n 'err_password': err_password,\n 'input_username': username,\n 'input_password': password\n }\n\n if signin_err == False:\n user = USER.login(username, password)\n\n if user:\n self.login(user)\n self.redirect(\"/welcome\")\n else:\n self.render(\"signin.html\",\n err_login = \"Invalid username or password.\",\n input_username = username,\n input_password = password,\n page_title = \"SIGN-IN\")\n else:\n self.render_template(\"signin.html\", template_values)\n" }, { "alpha_fraction": 0.6174904704093933, "alphanum_fraction": 0.6174904704093933, "avg_line_length": 32.71794891357422, "blob_id": "dc4c996e99ad22a0a8c29fe66780e973e67b3d59", "content_id": "4e02d42918477441cb3e712a3acdede2d8486b63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1315, "license_type": "no_license", "max_line_length": 69, "num_lines": 39, "path": "/models/post.py", "repo_name": "kaushalmeena1996/myapp-blog", "src_encoding": "UTF-8", "text": "#post.py\n\"\"\"Contains class defination for model class POST.\"\"\"\n\nfrom google.appengine.ext import db\n\nfrom helper.helper import posts_key\n\nclass POST(db.Model):\n \"\"\"Provides way to store blog's post related information.\"\"\"\n\n user_id = db.StringProperty(required = True)\n post_subject = db.StringProperty(required = True)\n post_content = db.TextProperty(required = True)\n created = db.DateTimeProperty(auto_now_add = True)\n last_modified = db.DateTimeProperty(auto_now = True)\n\n @classmethod\n def by_id(cls, post_id):\n \"\"\"Returns a list of POST entities which have post_id same\n as passed parameter.\"\"\"\n return POST.get_by_id(post_id, parent = posts_key())\n\n @classmethod\n def by_user_id(cls, user_id):\n \"\"\"Returns a list of POST entities which have user_id same\n as passed parameter.\"\"\"\n\n posts = db.GqlQuery(\"SELECT * FROM POST WHERE user_id = '%s'\"\n % user_id)\n return posts\n\n @classmethod\n def create_post(cls, user_id, post_subject, post_content):\n \"\"\"Creates a new POST entitiy using passed parameters.\"\"\"\n\n return POST(parent = posts_key(),\n user_id = user_id,\n post_subject = post_subject,\n post_content = post_content)\n" }, { "alpha_fraction": 0.578772783279419, "alphanum_fraction": 0.578772783279419, "avg_line_length": 30.736841201782227, "blob_id": "48a31f4594dc6dd3f353c226937e0010085b148c", "content_id": "226d8da871dee9e39d08aeb0b4dedc0f59108e39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 603, "license_type": "no_license", "max_line_length": 72, "num_lines": 19, "path": "/handlers/welcome.py", "repo_name": "kaushalmeena1996/myapp-blog", "src_encoding": "UTF-8", "text": "#welcome.py\n\"\"\"Contains class defination for handler class WelcomeHandler.\"\"\"\n\nimport blog\n\nclass WelcomeHandler(blog.BlogHandler):\n \"\"\"Handler for WELCOME page which is showed to users after login.\"\"\"\n\n def get(self):\n \"\"\"Renders WELCOME page if user has logged in otherwise\n renders SIGN-IN page.\"\"\"\n\n if self.user:\n self.render(\"welcome.html\",\n input_username = self.user.username,\n username = self.user.username,\n page_title = \"WELCOME\")\n else:\n self.redirect(\"/signin\")\n" }, { "alpha_fraction": 0.48234590888023376, "alphanum_fraction": 0.4847396910190582, "avg_line_length": 35.326087951660156, "blob_id": "b1b9be38816b8494ad1bb135f1b6e3131cf2abe8", "content_id": "0a0a53417e0bc57557952ed784d9d16b1a54fa16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1671, "license_type": "no_license", "max_line_length": 80, "num_lines": 46, "path": "/handlers/home.py", "repo_name": "kaushalmeena1996/myapp-blog", "src_encoding": "UTF-8", "text": "#home.py\n\"\"\"Contains class defination for handler class MainHandler.\"\"\"\n\nfrom google.appengine.ext import db\n\nfrom blog import BlogHandler\nfrom models.post import POST\nfrom models.comment import COMMENT\n\nclass MainHandler(BlogHandler):\n \"\"\"Handler for HOME page which displays the blog posts along\n with their comments.\"\"\"\n\n def get(self):\n \"\"\"Renders HOME page after querying appropriate data for\n comments and post.\"\"\"\n\n posts = db.GqlQuery(\"SELECT * FROM POST ORDER BY created DESC LIMIT 20\")\n comments = []\n for post in posts:\n query_comments = db.GqlQuery(\"SELECT * FROM COMMENT \"\n \"WHERE post_id = '%s' \"\n \"LIMIT 10\"\n % str(post.key().id()))\n if query_comments:\n for comment in query_comments:\n comments.append(comment)\n\n if self.user:\n liked_post = []\n for post in posts:\n if str(post.key().id()) in self.user.liked_post:\n liked_post.append(str(post.key().id()))\n\n self.render(\"home.html\",\n posts = posts,\n comments = comments,\n liked_post = liked_post,\n user_id = str(self.user.key().id()),\n username = self.user.username,\n page_title = \"HOME\")\n else:\n self.render(\"home.html\",\n posts = posts,\n comments = comments,\n page_title = \"HOME\")\n" }, { "alpha_fraction": 0.6765578389167786, "alphanum_fraction": 0.6765578389167786, "avg_line_length": 27.08333396911621, "blob_id": "62d2ba1ff1fd72bf9f57af953ce543993cc5647c", "content_id": "4ac307fcce099e05d5d6fb45a7db2261647f8834", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 337, "license_type": "no_license", "max_line_length": 65, "num_lines": 12, "path": "/handlers/signout.py", "repo_name": "kaushalmeena1996/myapp-blog", "src_encoding": "UTF-8", "text": "#signout.py\n\"\"\"Contains class defination for handler class SignOutHandler.\"\"\"\n\nfrom blog import BlogHandler\n\nclass SignOutHandler(BlogHandler):\n \"\"\"Handler for SIGN-OUT page which allows users to logout.\"\"\"\n\n def get(self):\n \"\"\"Logout the user and redirects to HOME page.\"\"\"\n self.logout()\n self.redirect('/')\n" }, { "alpha_fraction": 0.5764241218566895, "alphanum_fraction": 0.5854483842849731, "avg_line_length": 45.657894134521484, "blob_id": "0499d70729bf8121074e0882d7a1b2547451ae04", "content_id": "3106c443c0a44cb376040a640594cf9432c24654", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1773, "license_type": "no_license", "max_line_length": 97, "num_lines": 38, "path": "/main.py", "repo_name": "kaushalmeena1996/myapp-blog", "src_encoding": "UTF-8", "text": "#main.py\n\"\"\"Python script for myapp-blog website.\"\"\"\n\n#python modules\nimport webapp2\n\nfrom handlers.deletecomment import DeleteCommentHandler\nfrom handlers.deletepost import DeletePostHandler\nfrom handlers.dislike import DislikeHandler\nfrom handlers.editcomment import EditCommentHandler\nfrom handlers.editpost import EditPostHandler\nfrom handlers.home import MainHandler\nfrom handlers.like import LikeHandler\nfrom handlers.mypost import MyPostHandler\nfrom handlers.newpost import NewPostHandler\nfrom handlers.permalink import PermalinkHandler\nfrom handlers.setting import SettingHandler\nfrom handlers.signin import SignInHandler\nfrom handlers.signout import SignOutHandler\nfrom handlers.signup import SignUpHandler\nfrom handlers.welcome import WelcomeHandler\n\n\napp = webapp2.WSGIApplication([('/',MainHandler),\n ('/signup', SignUpHandler),\n ('/signin', SignInHandler),\n ('/signout', SignOutHandler),\n ('/welcome', WelcomeHandler),\n ('/newpost', NewPostHandler),\n ('/post/([0-9]+)/edit', EditPostHandler),\n ('/comment/([0-9]+)/edit', EditCommentHandler),\n ('/mypost', MyPostHandler),\n ('/setting', SettingHandler),\n ('/post/([0-9]+)', PermalinkHandler),\n ('/post/([0-9]+)/like', LikeHandler),\n ('/post/([0-9]+)/dislike', DislikeHandler),\n ('/post/([0-9]+)/delete', DeletePostHandler),\n ('/comment/([0-9]+)/delete', DeleteCommentHandler)], debug = True)\n" }, { "alpha_fraction": 0.5040896534919739, "alphanum_fraction": 0.5068160891532898, "avg_line_length": 38.2976188659668, "blob_id": "ccd15045a0c4e15c4cbededd40e9219ac40478a5", "content_id": "4a5ba3a39f8521f8841da741853501c28d8e0782", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3301, "license_type": "no_license", "max_line_length": 76, "num_lines": 84, "path": "/handlers/editcomment.py", "repo_name": "kaushalmeena1996/myapp-blog", "src_encoding": "UTF-8", "text": "#editcomment.py\n\"\"\"Contains class defination for handler class EditCommentHandler.\"\"\"\n\nfrom blog import BlogHandler\nfrom models.comment import COMMENT\nfrom helper.helper import valid_email\n\n\nclass EditCommentHandler(BlogHandler):\n \"\"\"Handler for EDITING a comment post of user.\"\"\"\n\n def get(self, comment_id):\n \"\"\"Renders EDIT-COMMENT page if user has logged in after\n querying appropriate data otherwise redirects to SIGN-IN page.\"\"\"\n\n if self.user:\n comment = COMMENT.by_id(int(comment_id))\n if comment:\n if comment.user_id == str(self.user.key().id()):\n self.render(\"editcomment.html\",\n input_name = comment.name,\n input_email = comment.email,\n comment_content = comment.comment_content,\n post_id = comment.post_id,\n page_title = \"EDIT-COMMENT\")\n else:\n page_error = \"ERROR 500 : You don't own this comment.\"\n self.render(\"error.html\",\n page_error = page_error,\n username = self.user.username,\n page_title = \"ERROR\")\n else:\n page_error = \"ERROR 404 : Comment post not found.\"\n self.render(\"error.html\",\n page_error = page_error,\n username = self.user.username,\n page_title= \"ERROR\")\n\n else:\n self.redirect(\"/signin\")\n\n def post(self, comment_id):\n \"\"\"Checks the posted comment's form information for errors and\n accordingly changes the values of appropriate entities\n and redirects the page.\"\"\"\n\n input_name = self.request.get(\"name\")\n input_email = self.request.get(\"email\")\n comment_content = self.request.get(\"comment_content\")\n post_id = self.request.get(\"post_id\")\n\n comment_err = False\n err_email = ''\n\n if not valid_email(input_email):\n err_email = \"Please enter valid e-mail !\"\n comment_err = True\n\n template_values = {\n 'page_title': 'PERMALINK',\n 'post_id': post_id,\n 'username' : self.user.username,\n 'err_email': err_email,\n 'input_name': input_name,\n 'input_email': input_email,\n 'comment_content': comment_content\n }\n\n if comment_err == False:\n comment = COMMENT.by_id(int(comment_id))\n if comment.user_id == str(self.user.key().id()):\n comment.name = input_name\n comment.email = input_email\n comment.comment_content = comment_content\n comment.put()\n self.redirect(\"/post/\" + post_id)\n else:\n page_error = \"ERROR 500 : You don't own this comment.\"\n self.render(\"error.html\",\n page_error = page_error,\n username = self.user.username,\n page_title= \"ERROR\")\n else:\n self.render_template(\"editcomment.html\", template_values)\n" }, { "alpha_fraction": 0.5200573205947876, "alphanum_fraction": 0.5204154849052429, "avg_line_length": 31.465116500854492, "blob_id": "45edac0fe70cb2103c6ed2407822fbf2c8de7e7d", "content_id": "6d201e21f79bf58bac35505ed894ef57a67e35ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2792, "license_type": "no_license", "max_line_length": 78, "num_lines": 86, "path": "/handlers/signup.py", "repo_name": "kaushalmeena1996/myapp-blog", "src_encoding": "UTF-8", "text": "#signup.py\n\"\"\"Contains class defination for handler class SignUpHandler.\"\"\"\n\nfrom blog import BlogHandler\nfrom models.user import USER\nfrom helper.helper import valid_username, valid_password, valid_email\n\nclass SignUpHandler(BlogHandler):\n \"\"\"Handler for SIGN-UP page which allows users to register.\"\"\"\n\n def get(self):\n \"\"\"Renders SIGN-UP page if user has not registered otherwise\n renders WELCOME page.\"\"\"\n\n if self.user:\n self.redirect(\"/welcome\")\n else:\n self.render(\"signup.html\", page_title = \"SIGN-UP\")\n\n def post(self):\n \"\"\"Validates user sign-up's form information for errors and\n accordingly redirects the page.\"\"\"\n\n username = self.request.get(\"username\")\n password = self.request.get(\"password\")\n verify = self.request.get(\"verify\")\n name = self.request.get(\"name\")\n email = self.request.get(\"email\")\n\n err_username = ''\n err_password = ''\n err_verify = ''\n err_email = ''\n\n signup_err = False\n\n if not valid_username(username):\n err_username = \"Please enter valid username !\"\n signup_err = True\n\n if not valid_password(password):\n err_password = \"Password must contain atleast 3 characters !\"\n signup_err = True\n\n if not valid_password(verify):\n err_verify = \"Password must contain atleast 3 characters !\"\n signup_err = True\n\n elif not password == verify:\n err_verify = \"Password don't match !\"\n signup_err = True\n\n if email:\n if not valid_email(email):\n err_email = \"Please enter valid e-mail !\"\n signup_err = True\n\n template_values = {\n 'page_title': 'SIGN-UP',\n 'err_username': err_username,\n 'err_password': err_password,\n 'err_verify': err_verify,\n 'err_email': err_email,\n 'input_username': username,\n 'input_password': password,\n 'input_verify': verify,\n 'input_email': email,\n 'input_name': name,\n }\n\n if signup_err == False:\n user = USER.by_username(username)\n if user:\n self.render(\"signup.html\",\n err_username = \"Specified username alredy exits.\",\n page_title = \"SIGN-UP\")\n else:\n user = USER.register(username,\n password,\n name,\n email)\n user.put()\n self.login(user)\n self.redirect(\"/welcome\")\n else:\n self.render_template(\"signup.html\", template_values)\n" }, { "alpha_fraction": 0.4948051869869232, "alphanum_fraction": 0.4987013041973114, "avg_line_length": 36.56097412109375, "blob_id": "c119e60bc223aec7a4cf72c774b3420d251680ce", "content_id": "a35ac31d6195767a98fd2709c4a99c96b4cef6fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1540, "license_type": "no_license", "max_line_length": 74, "num_lines": 41, "path": "/handlers/deletecomment.py", "repo_name": "kaushalmeena1996/myapp-blog", "src_encoding": "UTF-8", "text": "#deletecomment.py\n\"\"\"Contains class defination for handler class DeleteCommentHandler.\"\"\"\n\nfrom blog import BlogHandler\nfrom models.comment import COMMENT\n\nclass DeleteCommentHandler(BlogHandler):\n \"\"\"Handler for DELETING a comment post of user.\"\"\"\n\n def get(self, comment_id):\n \"\"\"Validates the posted comment's form information for\n errors and accordingly deletes the values of appropriate\n entities and redirects the page.\"\"\"\n\n if self.user:\n comment = COMMENT.by_id(int(comment_id))\n\n if comment:\n if comment.user_id == str(self.user.key().id()):\n comment.delete()\n\n referrer = self.request.headers.get('referer')\n if referrer:\n self.redirect(referrer)\n else:\n self.redirect('/')\n else:\n page_error = \"ERROR 500 : You don't own this comment.\"\n self.render(\"error.html\",\n page_error = page_error,\n username = self.user.username,\n page_title = \"ERROR\")\n else:\n page_error = \"ERROR 404 : Comment post not found.\"\n self.render(\"error.html\",\n page_error = page_error,\n username = self.user.username,\n page_title= \"ERROR\")\n\n else:\n self.redirect(\"/signin\")\n" }, { "alpha_fraction": 0.5641025900840759, "alphanum_fraction": 0.5641025900840759, "avg_line_length": 33.125, "blob_id": "2e9c109a5b95fba8801bb33e1f7e99893f900e35", "content_id": "1dbc4ef150a941ba8265d7d74e321baa39a30207", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1911, "license_type": "no_license", "max_line_length": 75, "num_lines": 56, "path": "/models/comment.py", "repo_name": "kaushalmeena1996/myapp-blog", "src_encoding": "UTF-8", "text": "#comment.py\n\"\"\"Contains class defination for model class COMMENT.\"\"\"\n\nfrom google.appengine.ext import db\nfrom helper.helper import comments_key\n\nclass COMMENT(db.Model):\n \"\"\"Provides way to store blog's comment related information.\"\"\"\n\n user_id = db.StringProperty(required = True)\n post_id = db.StringProperty(required = True)\n name = db.StringProperty(required = True)\n email = db.StringProperty(required = True)\n comment_content = db.TextProperty(required = True)\n created = db.DateTimeProperty(auto_now_add = True)\n\n @classmethod\n def by_id(cls, comment_id):\n \"\"\"Returns a list of COMMENT entities which have comment_id\n same as passed parameter.\"\"\"\n\n return COMMENT.get_by_id(comment_id, parent = comments_key())\n\n @classmethod\n def by_post_id(cls, post_id):\n \"\"\"Returns a list of COMMENT entities which have comment_id\n same as passed parameter.\"\"\"\n\n comments = db.GqlQuery(\"SELECT * FROM COMMENT WHERE post_id = '%s'\"\n % post_id)\n return comments\n\n @classmethod\n def by_user_id(cls, user_id):\n \"\"\"Returns a list of COMMENT entities which have user_id\n same as passed parameter.\"\"\"\n\n comments = db.GqlQuery(\"SELECT * FROM COMMENT WHERE user_id = '%s'\"\n % user_id)\n return comments\n\n @classmethod\n def create_comment(cls,\n user_id,\n post_id,\n name,\n email,\n comment_content):\n \"\"\"Creates a new COMMENT entitiy using passed parameters.\"\"\"\n\n return COMMENT(parent = comments_key(),\n user_id = user_id,\n post_id = post_id,\n name = name,\n email = email,\n comment_content = comment_content)\n" }, { "alpha_fraction": 0.6281094551086426, "alphanum_fraction": 0.6293532252311707, "avg_line_length": 33.956520080566406, "blob_id": "671b35f0576731c728a45ab8497712bee3252c34", "content_id": "28078e15b95ecc08a697cc1946e37c5f59399330", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2412, "license_type": "no_license", "max_line_length": 95, "num_lines": 69, "path": "/handlers/blog.py", "repo_name": "kaushalmeena1996/myapp-blog", "src_encoding": "UTF-8", "text": "#blog.py\n\"\"\"Contains class defination for handler class BlogHandler.\"\"\"\n\nimport webapp2\n\nfrom models.user import USER\nfrom helper.helper import render_str, render_template_str, make_secure_val, check_secure_val \n\nclass BlogHandler(webapp2.RequestHandler):\n \"\"\"Main handler for BLOG website which is parent of all other\n handler classes.\"\"\"\n\n def write(self, *a, **kw):\n \"\"\"Writes the passed parameters in webpage.\"\"\"\n self.response.out.write(*a, **kw)\n\n def render_str(self, template, **params):\n \"\"\"Renders template using passed parameters in webpage.\"\"\"\n\n params['user'] = self.user\n return render_str(template, **params)\n\n def render_template_str(self, template, template_values):\n \"\"\"Renders template using passed dictionary in webpage.\"\"\"\n\n return render_template_str(template, template_values)\n\n def render(self, template, **kw):\n \"\"\"Writes template using passed parameters in webpage.\"\"\"\n\n self.write(self.render_str(template, **kw))\n\n def render_template(self, template, template_values):\n \"\"\"Writes template using passed dictionary in webpage.\"\"\"\n\n self.write(self.render_template_str(template, template_values))\n\n def set_secure_cookie(self, username, val):\n \"\"\"Sets cookie for current user in browser.\"\"\"\n\n cookie_val = make_secure_val(val)\n self.response.headers.add_header('Set-Cookie', '%s=%s; Path=/'\n % (username, cookie_val))\n\n def read_secure_cookie(self, username):\n \"\"\"Reads cookie from browser for passed parameters.\"\"\"\n\n cookie_val = self.request.cookies.get(username)\n return cookie_val and check_secure_val(cookie_val)\n\n def login(self, user):\n \"\"\"Sets cookie in browser for passed parameter.\"\"\"\n\n self.user = user\n self.set_secure_cookie('user_id', str(user.key().id()))\n\n def logout(self):\n \"\"\"Deletes cookie from browser for current user.\"\"\"\n\n self.response.headers.add_header('Set-Cookie',\n 'user_id=; Path=/')\n\n def initialize(self, *a, **kw):\n \"\"\"Initializes class's USER entitity from cookie info\n stored in browser.\"\"\"\n\n webapp2.RequestHandler.initialize(self, *a, **kw)\n user_id = self.read_secure_cookie('user_id')\n self.user = user_id and USER.by_id(int(user_id))\n" }, { "alpha_fraction": 0.5996430516242981, "alphanum_fraction": 0.5996430516242981, "avg_line_length": 34.02083206176758, "blob_id": "b6aab2a9ef5ff9a9088da2d2c4af38b7529599fc", "content_id": "20fb1c2447e90b63b38c6819bf0dd6f51d15a917", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1681, "license_type": "no_license", "max_line_length": 74, "num_lines": 48, "path": "/models/user.py", "repo_name": "kaushalmeena1996/myapp-blog", "src_encoding": "UTF-8", "text": "#user.py\n\"\"\"Contains class defination for model class USER.\"\"\"\n\nfrom google.appengine.ext import db\nfrom helper.helper import users_key, make_password_hash, validate_password\n\nclass USER(db.Model):\n \"\"\"Provides way to store blog's user related information.\"\"\"\n\n username = db.StringProperty(required = True)\n password_hash = db.StringProperty(required = True)\n name = db.StringProperty()\n email = db.StringProperty()\n liked_post = db.StringListProperty(default=[])\n\n @classmethod\n def by_id(cls, user_id):\n \"\"\"Returns a list of USER entities which have id same as\n passed parameter.\"\"\"\n\n return USER.get_by_id(user_id, parent = users_key())\n\n @classmethod\n def by_username(cls, username):\n \"\"\"Returns a list of USER entities which have username same\n as passed parameter.\"\"\"\n\n user = USER.all().filter('username =', username).get()\n return user\n\n @classmethod\n def register(cls, username, password, name = None, email = None):\n \"\"\"Create a new USER entitity using passed parameters.\"\"\"\n\n password_hash = make_password_hash(username, password)\n return USER(parent = users_key(),\n username = username,\n password_hash = password_hash,\n name = name,\n email = email)\n @classmethod\n def login(cls, username, password):\n \"\"\"Validates the user login information.\"\"\"\n user = cls.by_username(username)\n if user and validate_password(username,\n password,\n user.password_hash):\n return user\n" }, { "alpha_fraction": 0.4692169725894928, "alphanum_fraction": 0.47280335426330566, "avg_line_length": 37.022727966308594, "blob_id": "94f96af0b574e3eba9b0efceafe8cc27b599c5ad", "content_id": "b4080d7a04b08e418a6be3d92d9b1abc221eca21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1673, "license_type": "no_license", "max_line_length": 71, "num_lines": 44, "path": "/handlers/deletepost.py", "repo_name": "kaushalmeena1996/myapp-blog", "src_encoding": "UTF-8", "text": "#deletepost.py\n\"\"\"Contains class defination for handler class DeletePostHandler.\"\"\"\n\nfrom blog import BlogHandler\nfrom models.post import POST\n\nclass DeletePostHandler(BlogHandler):\n \"\"\"Handler for DELETING a blog post of user.\"\"\"\n\n def get(self, post_id):\n \"\"\"Validates the posted blog post's form information for\n errors and accordingly deletes the values of appropriate\n entities and redirects the page.\"\"\"\n\n if self.user:\n post = POST.by_id(int(post_id))\n if post:\n if post.user_id == str(self.user.key().id()):\n if post_id in self.user.liked_post:\n self.user.liked_post.remove(post_id)\n self.user.put()\n post.delete()\n\n referrer = self.request.headers.get('referer')\n if referrer:\n self.redirect(referrer)\n else:\n self.redirect('/')\n else:\n page_error = \"ERROR 500 : You don't own this post.\"\n self.render(\"error.html\",\n page_error = page_error,\n username = self.user.username,\n page_title= \"ERROR\")\n \n else:\n page_error = \"ERROR 404 : Blog post not found.\"\n self.render(\"error.html\",\n page_error = page_error,\n username = self.user.username,\n page_title= \"ERROR\")\n\n else:\n self.redirect(\"/signin\")\n" }, { "alpha_fraction": 0.4919447600841522, "alphanum_fraction": 0.4928078353404999, "avg_line_length": 37.622222900390625, "blob_id": "4b12b06e0654ac4d121915a0cd62c1b53903307e", "content_id": "deb14e9a3f1696ead5fd780b65630ac466daef06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3476, "license_type": "no_license", "max_line_length": 79, "num_lines": 90, "path": "/handlers/permalink.py", "repo_name": "kaushalmeena1996/myapp-blog", "src_encoding": "UTF-8", "text": "#permalink.py\n\"\"\"Contains class defination for handler class PermalinkHandler.\"\"\"\n\nfrom blog import BlogHandler\nfrom models.post import POST\nfrom models.comment import COMMENT\nfrom helper.helper import valid_email\n \nclass PermalinkHandler(BlogHandler):\n \"\"\"Handler for PERMALINK page a which displays individual\n blog post's information and also allows users to post their\n comments on that blog.\"\"\"\n\n def get(self, post_id):\n \"\"\"Renders PERMALINK page in after fetching appropriate data.\"\"\"\n\n post = POST.by_id(int(post_id))\n comments = COMMENT.by_post_id(post_id)\n\n if not post:\n page_error = \"ERROR 404 : Blog post not found.\"\n self.render(\"error.html\",\n username = self.user.username,\n page_error = page_error,\n page_title = \"ERROR\")\n else:\n if self.user:\n show_form = True\n if post.user_id == str(self.user.key().id()):\n show_form = False\n\n liked_post = []\n if str(post.key().id()) in self.user.liked_post:\n liked_post.append(str(post.key().id()))\n\n self.render(\"permalink.html\",\n post = post,\n comments = comments,\n liked_post = liked_post,\n username = self.user.username,\n user_id = str(self.user.key().id()),\n show_form = show_form,\n input_name = self.user.name,\n input_email = self.user.email,\n page_title = \"PERMALINK\")\n else:\n self.render(\"permalink.html\",\n post = post,\n comments = comments,\n page_title = \"PERMALINK\")\n\n def post(self, post_id):\n \"\"\"Checks the posted comment's form information for errors\n and accordingly creates appropriate entity and redirects\n the page. Also incresess the appropriate blog post's\n comment count.\"\"\"\n\n input_name = self.request.get(\"input_name\")\n input_email = self.request.get(\"input_email\")\n comment_content = self.request.get(\"comment_content\")\n post_id = self.request.get(\"post_id\")\n\n comment_err = False\n err_email = ''\n post = POST.by_id(int(post_id))\n\n if not valid_email(input_email):\n err_email = \"Please enter valid e-mail !\"\n comment_err = True\n\n template_values = {\n 'page_title': 'PERMALINK',\n 'username' : self.user.username,\n 'err_email': err_email,\n 'input_name': input_name,\n 'input_email': input_email,\n 'comment_content': comment_content,\n 'post': post\n }\n\n if comment_err == False:\n comment = COMMENT.create_comment(str(self.user.key().id()),\n post_id,\n name = input_name,\n email = input_email,\n comment_content = comment_content)\n comment.put()\n self.redirect(\"/post/\" + post_id)\n else:\n self.render_template(\"permalink.html\", template_values)\n" }, { "alpha_fraction": 0.7556935548782349, "alphanum_fraction": 0.7556935548782349, "avg_line_length": 39.20833206176758, "blob_id": "db75b7a44450f738c855ebb1f3ac59f2b3d58988", "content_id": "bcf5346e9fba10e65667d2aa2fd4c5a50868a571", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 970, "license_type": "no_license", "max_line_length": 204, "num_lines": 24, "path": "/ReadMe.md", "repo_name": "kaushalmeena1996/myapp-blog", "src_encoding": "UTF-8", "text": "# [Project : Multi User Blog]\n\n### [ Synopsis ]\nA multi user blog where users can sign in and post blog posts as well as 'Like' and 'Comment' on other posts made on the blog.\n\n- For live version visit page: http://myapp-blog.appspot.com/\n\n### [Prerequisities]\n- Python\n - https://www.python.org/downloads/\n- Google App Engine SDK.\n - https://cloud.google.com/appengine/downloads\n\n### [Usage]\n\n- Install Python if necessary.\n- Install Google App Engine SDK.\n- Open GoogleAppEngineLauncher.\n- Sign Up for a Google App Engine Account.\n- Create a new project in Google’s Developer Console using a unique name.\n- Create a new project from the file menu and choose this project's folder.\n- Deploy this project by pressing deploy in GoogleAppEngineLauncher.\n\nWhen developing locally, click 'Run' in GoogleAppEngineLauncher and visit localhost:Port in your favorite browser, where Port is the number listed in GoogleAppEngineLauncher’s table under the column Port.\n\n" }, { "alpha_fraction": 0.5009835958480835, "alphanum_fraction": 0.5009835958480835, "avg_line_length": 35.30952453613281, "blob_id": "884965bcd0caac586a37e9d9908f5c4332b57b24", "content_id": "9159f28645c9cb92d764c2093cee1ef51e0f3da8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1525, "license_type": "no_license", "max_line_length": 73, "num_lines": 42, "path": "/handlers/mypost.py", "repo_name": "kaushalmeena1996/myapp-blog", "src_encoding": "UTF-8", "text": "#blog.py\n\"\"\"Contains class defination for handler class MyPostHandler.\"\"\"\n\nfrom google.appengine.ext import db\n\nfrom blog import BlogHandler\nfrom models.post import POST\nfrom models.comment import COMMENT\n\nclass MyPostHandler(BlogHandler):\n \"\"\"Handler for MY-POST page which show users their own blog posts.\"\"\"\n\n def get(self):\n \"\"\"Renders MY-POST page if user has logged in after querying\n appropriate data otherwise renders SIGN-IN page.\"\"\"\n\n if self.user:\n posts = POST.by_user_id(str(self.user.key().id()))\n comments = []\n\n for post in posts:\n query_comments = db.GqlQuery(\"SELECT * FROM COMMENT \"\n \"WHERE post_id = '%s'\"\n % str(post.key().id()))\n if query_comments:\n for comment in query_comments:\n comments.append(comment)\n\n liked_post = []\n for post in posts:\n if str(post.key().id()) in self.user.liked_post:\n liked_post.append(str(post.key().id()))\n\n self.render(\"mypost.html\",\n posts = posts,\n comments = comments,\n liked_post = liked_post,\n user_id = str(self.user.key().id()),\n username = self.user.username,\n page_title = \"MY-POST\")\n else:\n self.redirect(\"/signin\")\n" }, { "alpha_fraction": 0.6478190422058105, "alphanum_fraction": 0.6535887122154236, "avg_line_length": 25.10240936279297, "blob_id": "5cb50465284f92c1f09846c3f5e81979afee3814", "content_id": "e3e3338705cb78a91e774b91e022beeab41c79fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4333, "license_type": "no_license", "max_line_length": 86, "num_lines": 166, "path": "/helper/helper.py", "repo_name": "kaushalmeena1996/myapp-blog", "src_encoding": "UTF-8", "text": "#helper.py\n\"\"\"Python function definations for helper function.\"\"\"\n\n#python modules\nimport webapp2\nimport os\nimport jinja2\nimport codecs\nimport re\nimport hashlib\nimport hmac\nimport random\nimport string\n\nfrom google.appengine.ext import db\nfrom secret.secret import get_secret\n\n#regular expression patterns\nUSERNAME_RE = re.compile(r\"^[a-zA-Z0-9_-]{3,20}$\")\nPASSWORD_RE = re.compile(r\"^.{3,20}$\")\nEMAIL_RE = re.compile(r\"^[\\S]+@[\\S]+.[\\S]+$\")\n\n#jinja environment defination\nTEMPLATE_DIR = os.path.join(os.path.dirname(__file__), '../template')\nJINJA_ENVIRONMENT = jinja2.Environment(loader = jinja2.FileSystemLoader(TEMPLATE_DIR),\n autoescape = True)\n#global jinja2 function\ndef count_likes(post_id, liked_post):\n \"\"\"Counts the no. likes using passed parameters.\"\"\"\n\n post_id = str(post_id)\n\n if liked_post:\n like_count = 0\n for liked_post_id in liked_post :\n if post_id == liked_post_id:\n like_count += 1\n\n return like_count\n\n else:\n return 0\n\ndef user_liked_post(post_id, liked_post):\n \"\"\"Returns True post_id is present in liked_post otherwise\n returns False.\"\"\"\n\n post_id = str(post_id)\n\n user_liked_post = False\n if liked_post:\n for liked_post_id in liked_post :\n if post_id == liked_post_id:\n user_liked_post = True\n break\n\n return user_liked_post\n\n else:\n return user_liked_post\n \n \n\ndef count_comments(post_id, comments):\n \"\"\"Counts the no. likes using passed parameters.\"\"\"\n\n post_id = str(post_id)\n\n if comments:\n comment_count = 0\n for comment in comments :\n if post_id == comment.post_id:\n comment_count += 1\n\n return comment_count\n\n else:\n return 0\n\nJINJA_ENVIRONMENT.globals['count_likes'] = count_likes\nJINJA_ENVIRONMENT.globals['user_liked_post'] = user_liked_post \nJINJA_ENVIRONMENT.globals['count_comments'] = count_comments\n\n#secret string\nSECRET = get_secret()\n\n#function definations\ndef users_key(group = 'default'):\n \"\"\"Creates a new user key object from parent.\"\"\"\n\n return db.Key.from_path('users', group)\n\ndef posts_key(group = 'default'):\n \"\"\"Creates a new post key object from parent.\"\"\"\n\n return db.Key.from_path('posts', group)\n\ndef comments_key(group = 'default'):\n \"\"\"Creates a new comment key object from parent.\"\"\"\n\n return db.Key.from_path('comments', group)\n \ndef render_str(template, **params):\n \"\"\"Renders the template using passed parameters.\"\"\"\n\n template = JINJA_ENVIRONMENT.get_template(template)\n return template.render(params)\n\ndef render_template_str(template, template_values):\n \"\"\"Renders the template using dictionary.\"\"\"\n\n template = JINJA_ENVIRONMENT.get_template(template)\n return template.render(template_values)\n\ndef make_salt(length = 5):\n \"\"\"Creates random string of length same as passed parameter.\"\"\"\n\n salt = ''.join(random.choice(string.letters) for x in xrange(length))\n return salt\n\ndef make_password_hash(username, password, salt = None):\n \"\"\"Creates hash using passed parameters.\"\"\"\n\n if not salt:\n salt = make_salt()\n hash_val = hashlib.sha256(username + password + salt).hexdigest()\n\n return '%s,%s' % (salt, hash_val)\n\ndef validate_password(username, password, hash_val):\n \"\"\"Validates username and password using hash value.\"\"\"\n\n salt = hash_val.split(',')[0]\n return hash_val == make_password_hash(username, password, salt)\n\ndef hash_str(string):\n \"\"\"Returns a hash value of passed string.\"\"\"\n\n return hmac.new(SECRET, string).hexdigest()\n\ndef make_secure_val(string):\n \"\"\"Creates a password hash using passed string.\"\"\"\n\n return \"%s|%s\" % (string, hash_str(string))\n\ndef check_secure_val(hash_val):\n \"\"\"Checks if passed hash value is correct or not.\"\"\"\n\n val = hash_val.split('|')[0]\n if hash_val == make_secure_val(val):\n return val\n\ndef valid_username(username):\n \"\"\"Validates username using regular expressions.\"\"\"\n\n return USERNAME_RE.match(username)\n\ndef valid_password(password):\n \"\"\"Validates password using regular expressions.\"\"\"\n\n return PASSWORD_RE.match(password)\n\ndef valid_email(email):\n \"\"\"Validates email using regular expressions.\"\"\"\n\n return EMAIL_RE.match(email)\n" }, { "alpha_fraction": 0.5206834673881531, "alphanum_fraction": 0.523156464099884, "avg_line_length": 34.870967864990234, "blob_id": "c84a91436ba0d7108c301fcbd287380b6dbeb219", "content_id": "89aaf3367dc22efc6b41f30007196b95522c1a13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4448, "license_type": "no_license", "max_line_length": 80, "num_lines": 124, "path": "/handlers/setting.py", "repo_name": "kaushalmeena1996/myapp-blog", "src_encoding": "UTF-8", "text": "#setting.py\n\"\"\"Contains class defination for handler class SettingHandler.\"\"\"\n\nfrom blog import BlogHandler\nfrom models.post import POST\nfrom models.comment import COMMENT\nfrom helper.helper import valid_password, valid_email, make_password_hash \n\n\nclass SettingHandler(BlogHandler):\n \"\"\"Handler for SETTING page a which allows users to change\n their profile settings and passwords and also allows users\n to delete all their post, comments or even acount.\"\"\"\n\n def get(self):\n \"\"\"Renders SETTING page in if user has logged in otherwise\n redirects to SIGN-IN page after fetching appropriate data.\"\"\"\n\n if self.user:\n self.render(\"setting.html\",\n username = self.user.username,\n input_name = self.user.name,\n input_email = self.user.email,\n page_title = \"SETTING\")\n else:\n self.redirect(\"/signin\")\n\n def post(self):\n \"\"\"Checks the posted setting's form information for errors\n and accordingly changes the values of appropriate entities\n and redirects the page. Also perform the task of deleting\n all their posts, comments or even account if specified.\"\"\"\n\n\n name = self.request.get(\"name\")\n email = self.request.get(\"email\")\n password = self.request.get(\"password\")\n verify = self.request.get(\"verify\")\n delete1 = self.request.get(\"delete1\")\n delete2 = self.request.get(\"delete2\")\n delete3 = self.request.get(\"delete3\")\n\n setting_err = False\n err_email = ''\n err_password = ''\n err_verify = ''\n\n if not name == self.user.name:\n self.user.name = name\n self.user.put()\n\n if not email == self.user.email:\n if not valid_email(email):\n err_email = \"Please enter valid e-mail !\"\n setting_err = True\n else:\n self.user.email = email\n self.user.put()\n\n if password and password.strip():\n if not valid_password(password):\n err_password = \"Password must contain atleast 3 characters !\"\n setting_err = True\n\n if not valid_password(verify):\n err_verify = \"Password must contain atleast 3 characters !\"\n setting_err = True\n\n elif not password == verify:\n err_verify = \"Password don't match !\"\n setting_err = True\n\n else:\n password_hash = make_password_hash(self.user.username, password)\n self.user.password_hash = password_hash\n self.user.put()\n\n template_values = {\n 'page_title': 'SETTING',\n 'username' : self.user.username,\n 'err_email': err_email,\n 'err_password': err_password,\n 'err_verify': err_verify,\n 'input_name': name,\n 'input_email': email,\n 'input_password': password,\n 'input_verify': verify,\n }\n\n if setting_err == False:\n if delete1:\n comments = COMMENT.by_user_id(str(self.user.key().id()))\n for comment in comments :\n post = POST.by_id(int(comment.post_id))\n post.put()\n comment.delete()\n\n if delete2:\n posts = POST.by_user_id(str(self.user.key().id()))\n for post in posts :\n if str(post.key().id()) in self.user.liked_post:\n self.user.liked_post.remove(str(post.key().id()))\n self.user.put()\n comments = COMMENT.by_post_id(str(post.key().id()))\n for comment in comments :\n comment.delete()\n\n post.delete()\n\n if delete3:\n comments = COMMENT.by_user_id(str(self.user.key().id()))\n posts = POST.by_user_id(str(self.user.key().id()))\n for post in posts :\n post.delete()\n for comment in comments :\n comment.delete()\n\n self.user.delete()\n self.logout()\n self.redirect(\"/\")\n else:\n self.redirect(\"/setting\")\n else:\n self.render_template(\"setting.html\", template_values)\n" }, { "alpha_fraction": 0.5493230223655701, "alphanum_fraction": 0.5493230223655701, "avg_line_length": 35.069766998291016, "blob_id": "34dce5681a9e916eb402e5bb373440733d3758ff", "content_id": "49a1457b0c4c4e7429ef7a86920f26f746536a09", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1551, "license_type": "no_license", "max_line_length": 82, "num_lines": 43, "path": "/handlers/newpost.py", "repo_name": "kaushalmeena1996/myapp-blog", "src_encoding": "UTF-8", "text": "#newpost.py\n\"\"\"Contains class defination for handler class NewPostHandler.\"\"\"\n\nfrom blog import BlogHandler\nfrom models.post import POST\nfrom models.comment import COMMENT\n\n\nclass NewPostHandler(BlogHandler):\n \"\"\"Handler for NEW-POST page which allows users to create\n new blog posts.\"\"\"\n\n def get(self):\n \"\"\"Renders NEW-POST page if user has logged in otherwise\n renders SIGN-IN page.\"\"\"\n\n if self.user:\n self.render(\"newpost.html\",\n username = self.user.username,\n page_title = \"NEW-POST\")\n else:\n self.redirect(\"/signin\")\n\n def post(self):\n \"\"\"Validates the posted blog post's form information for\n errors and accordingly creates the appropriate entities\n and redirects the page.\"\"\"\n\n post_subject = self.request.get(\"subject\")\n post_content = self.request.get(\"content\")\n\n if post_subject and post_content:\n post = POST.create_post(user_id = str(self.user.key().id()),\n post_subject = post_subject,\n post_content = post_content)\n post.put()\n self.redirect(\"/post/\" + str(post.key().id()))\n else :\n self.render(\"newpost.html\",\n err_msg = \"Both SUBJECT and CONTENT can't be left empty.\",\n post_subject = post_subject,\n post_content = post_content,\n page_title = \"NEW-POST\")\n" }, { "alpha_fraction": 0.4772135317325592, "alphanum_fraction": 0.4811197817325592, "avg_line_length": 33.90909194946289, "blob_id": "9ffe26b660ded4ea82a59d1daa7ea1e68c7e10ac", "content_id": "74e7e3142402372366f61112cce0911b6d6cbf10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1536, "license_type": "no_license", "max_line_length": 79, "num_lines": 44, "path": "/handlers/dislike.py", "repo_name": "kaushalmeena1996/myapp-blog", "src_encoding": "UTF-8", "text": "#dislike.py\n\"\"\"Contains class defination for handler class DislikeHandler.\"\"\"\n\nfrom blog import BlogHandler\nfrom models.post import POST\n\n\nclass DislikeHandler(BlogHandler):\n \"\"\"Handler for DISLIKING a blog post.\"\"\"\n\n def get(self, post_id):\n \"\"\"Deletes the passed post_id from user's list of liked_post\n and redirects the page accordingly.\"\"\"\n\n if self.user:\n post = POST.by_id(int(post_id))\n if post:\n if not post.user_id == str(self.user.key().id()):\n if post_id in self.user.liked_post:\n self.user.liked_post.remove(post_id)\n self.user.put()\n post.put()\n\n referrer = self.request.headers.get('referer')\n if referrer:\n self.redirect(referrer)\n else:\n self.redirect('/')\n else:\n page_error = \"ERROR 500 : You can't dislike your own post.\"\n self.render(\"error.html\",\n page_error = page_error,\n\t\t\t\tusername = self.user.username,\n\t\t\t\tpage_title = \"ERROR\")\n\n else:\n page_error = \"ERROR 404 : Blog post not found.\"\n self.render(\"error.html\",\n page_error = page_error,\n username = self.user.username,\n page_title = \"ERROR\")\n\n else:\n self.redirect(\"/signin\")\n" }, { "alpha_fraction": 0.47482797503471375, "alphanum_fraction": 0.4780876636505127, "avg_line_length": 39.60293960571289, "blob_id": "ecfabbf78b2bf57566c7b23ceb5dd100d9d86aac", "content_id": "835b477ff338f2953a4f903796639da676cf9dfa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2761, "license_type": "no_license", "max_line_length": 71, "num_lines": 68, "path": "/handlers/editpost.py", "repo_name": "kaushalmeena1996/myapp-blog", "src_encoding": "UTF-8", "text": "#editpost.py\n\"\"\"Contains class defination for handler class EditPostHandler.\"\"\"\n\nfrom blog import BlogHandler\nfrom models.post import POST\n\nclass EditPostHandler(BlogHandler):\n \"\"\"Handler for EDITING a blog post of user.\"\"\"\n\n def get(self, post_id):\n \"\"\"Renders EDIT-POST page if user has logged in after querying\n appropriate data otherwise redirects to SIGN-IN page.\"\"\"\n\n if self.user:\n post = POST.by_id(int(post_id))\n if post:\n if post.user_id == str(self.user.key().id()):\n self.render(\"editpost.html\",\n post_subject = post.post_subject,\n post_content = post.post_content,\n username = self.user.username,\n page_title = \"EDIT-POST\")\n else:\n page_error = \"ERROR 500 : You don't own this post.\"\n self.render(\"error.html\",\n page_error = page_error,\n username = self.user.username,\n page_title = \"ERROR\")\n else:\n page_error = \"ERROR 404 : Blog post not found.\"\n self.render(\"error.html\",\n page_error = page_error,\n username = self.user.username,\n page_title = \"ERROR\")\n\n else:\n self.redirect(\"/signin\")\n\n def post(self, post_id):\n \"\"\"Checks the posted blog post's form information for\n errors and accordingly changes the values of appropriate\n entities and redirects the page.\"\"\"\n\n post_subject = self.request.get(\"subject\")\n post_content = self.request.get(\"content\")\n\n if post_subject and post_content:\n post = POST.by_id(int(post_id))\n \n if post.user_id == str(self.user.key().id()):\n post.post_subject = post_subject\n post.post_content = post_content\n post.put()\n self.redirect(\"/mypost\")\n else:\n page_error = \"ERROR 500 : You don't own this post.\"\n self.render(\"error.html\",\n page_error = page_error,\n username = self.user.username,\n page_title = \"ERROR\")\n \n else :\n err_msg = \"Both SUBJECT and CONTENT can't be left empty.\"\n self.render(\"editpost.html\",\n err_msg = err_msg,\n post_subject = post_subject,\n post_content = post_content,\n page_title = \"EDIT-POST\")\n" } ]
21
Briareos/aws-sdk-php
https://github.com/Briareos/aws-sdk-php
c6ef8812c114b35bd4645f2741c70cdac0a20007
d8fdc45497fceb2abb32ef8d0e7a80373e832e9d
2756248ab23cdeba292ec3daa17253f4b1fde842
refs/heads/master
2023-08-10T15:25:47.117419
2015-03-27T12:44:52
2015-03-27T12:44:52
31,963,482
1
1
null
null
null
null
null
[ { "alpha_fraction": 0.6200480461120605, "alphanum_fraction": 0.6200480461120605, "avg_line_length": 27.724138259887695, "blob_id": "57363d97d5533fccc039b4d32ce0a18cf011c557", "content_id": "e5014e44c2d506b9e24ee0b4d8f1af14c9b0636b", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1666, "license_type": "permissive", "max_line_length": 79, "num_lines": 58, "path": "/src/Subscriber/SourceFile.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Subscriber;\n\nuse Aws\\Api\\Service;\nuse GuzzleHttp\\Command\\Event\\InitEvent;\nuse GuzzleHttp\\Event\\SubscriberInterface;\nuse GuzzleHttp\\Stream;\nuse GuzzleHttp\\Stream\\LazyOpenStream;\n\n/**\n * Looks for instances of a \"Filename\" parameter and turns it into a Body param\n * that is only opened when the first byte is attempted to be read.\n */\nclass SourceFile implements SubscriberInterface\n{\n /** @var Service */\n private $api;\n\n /** @var string The key for the upload body parameter */\n private $bodyParameter;\n\n /** @var string The key for the source file parameter */\n private $sourceParameter;\n\n /**\n * @param Service $api API being accessed.\n * @param string $bodyParameter The key for the body parameter\n * @param string $sourceParameter The key for the source file parameter\n */\n public function __construct(\n Service $api,\n $bodyParameter = 'Body',\n $sourceParameter = 'SourceFile'\n ) {\n $this->api = $api;\n $this->bodyParameter = (string) $bodyParameter;\n $this->sourceParameter = (string) $sourceParameter;\n }\n\n public function getEvents()\n {\n return ['init' => ['onInit']];\n }\n\n public function onInit(InitEvent $event)\n {\n $c = $event->getCommand();\n $operation = $this->api->getOperation($c->getName());\n $source = $c[$this->sourceParameter];\n\n if ($source !== null\n && $operation->getInput()->hasMember($this->bodyParameter)\n ) {\n $c[$this->bodyParameter] = new LazyOpenStream($source, 'r');\n unset($c[$this->sourceParameter]);\n }\n }\n}\n" }, { "alpha_fraction": 0.5142611861228943, "alphanum_fraction": 0.5165486931800842, "avg_line_length": 31.38194465637207, "blob_id": "ab23106c69a46b1a72338e91cce5af0978a12084", "content_id": "d9a1d8b9d26ec000e6fd91d7cca1a3db72ab4e2f", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 13989, "license_type": "permissive", "max_line_length": 121, "num_lines": 432, "path": "/tests/ClientResolverTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test;\n\nuse Aws\\ClientResolver;\nuse Aws\\Credentials\\Credentials;\nuse Aws\\DynamoDb\\DynamoDbClient;\nuse Aws\\Exception\\AwsException;\nuse Aws\\S3\\S3Client;\nuse GuzzleHttp\\Client;\nuse Aws\\Credentials\\CredentialProvider;\nuse GuzzleHttp\\Event\\Emitter;\n\n/**\n * @covers Aws\\ClientResolver\n */\nclass ClientResolverTest extends \\PHPUnit_Framework_TestCase\n{\n use UsesServiceTrait;\n\n /**\n * @expectedException \\InvalidArgumentException\n * @expectedExceptionMessage Missing required client configuration options\n */\n public function testEnsuresRequiredArgumentsAreProvided()\n {\n $r = new ClientResolver(ClientResolver::getDefaultArguments());\n $r->resolve([], new Emitter());\n }\n\n public function testAddsValidationSubscriber()\n {\n $c = new DynamoDbClient([\n 'region' => 'x',\n 'version' => 'latest'\n ]);\n\n try {\n // CreateTable requires actual input parameters.\n $c->createTable([]);\n $this->fail('Did not validate');\n } catch (AwsException $e) {}\n }\n\n /**\n * @expectedException \\Aws\\Exception\\AwsException\n * @expectedExceptionMessage Throwing!\n */\n public function testCanDisableValidation()\n {\n $c = new DynamoDbClient([\n 'region' => 'x',\n 'version' => 'latest',\n 'validate' => false\n ]);\n $command = $c->getCommand('CreateTable');\n $command->getEmitter()->on('prepared', function () {\n throw new \\Exception('Throwing!');\n });\n $c->execute($command);\n }\n\n public function testAppliesApiProvider()\n {\n $r = new ClientResolver(ClientResolver::getDefaultArguments());\n $provider = function () {\n return ['metadata' => ['protocol' => 'query']];\n };\n $conf = $r->resolve([\n 'service' => 'dynamodb',\n 'region' => 'x',\n 'api_provider' => $provider,\n 'version' => 'latest'\n ], new Emitter());\n $this->assertArrayHasKey('api', $conf);\n $this->assertArrayHasKey('error_parser', $conf);\n $this->assertArrayHasKey('serializer', $conf);\n }\n\n /**\n * @expectedException \\InvalidArgumentException\n * @expectedExceptionMessage Invalid configuration value provided for \"foo\". Expected string, but got int(-1)\n */\n public function testValidatesInput()\n {\n $r = new ClientResolver([\n 'foo' => [\n 'type' => 'value',\n 'valid' => ['string']\n ]\n ]);\n $r->resolve(['foo' => -1], new Emitter());\n }\n\n /**\n * @expectedException \\InvalidArgumentException\n * @expectedExceptionMessage Invalid configuration value provided for \"foo\". Expected callable, but got string(1) \"c\"\n */\n public function testValidatesCallables()\n {\n $r = new ClientResolver([\n 'foo' => [\n 'type' => 'value',\n 'valid' => ['callable']\n ]\n ]);\n $r->resolve(['foo' => 'c'], new Emitter());\n }\n\n\n /**\n * @expectedException \\InvalidArgumentException\n * @expectedExceptionMessage Credentials must be an\n */\n public function testValidatesCredentials()\n {\n $r = new ClientResolver([\n 'credentials' => ClientResolver::getDefaultArguments()['credentials']\n ]);\n $r->resolve(['credentials' => []], new Emitter());\n }\n\n public function testLoadsFromDefaultChainIfNeeded()\n {\n $key = getenv(CredentialProvider::ENV_KEY);\n $secret = getenv(CredentialProvider::ENV_SECRET);\n putenv(CredentialProvider::ENV_KEY . '=foo');\n putenv(CredentialProvider::ENV_SECRET . '=bar');\n $r = new ClientResolver(ClientResolver::getDefaultArguments());\n $conf = $r->resolve([\n 'service' => 'sqs',\n 'region' => 'x',\n 'version' => 'latest'\n ], new Emitter());\n $c = $conf['credentials'];\n $this->assertInstanceOf('Aws\\Credentials\\CredentialsInterface', $c);\n $this->assertEquals('foo', $c->getAccessKeyId());\n $this->assertEquals('bar', $c->getSecretKey());\n putenv(CredentialProvider::ENV_KEY . \"=$key\");\n putenv(CredentialProvider::ENV_SECRET . \"=$secret\");\n }\n\n public function testCreatesFromArray()\n {\n $exp = time() + 500;\n $r = new ClientResolver(ClientResolver::getDefaultArguments());\n $conf = $r->resolve([\n 'service' => 'sqs',\n 'region' => 'x',\n 'version' => 'latest',\n 'credentials' => [\n 'key' => 'foo',\n 'secret' => 'baz',\n 'token' => 'tok',\n 'expires' => $exp\n ]\n ], new Emitter());\n $creds = $conf['credentials'];\n $this->assertEquals('foo', $creds->getAccessKeyId());\n $this->assertEquals('baz', $creds->getSecretKey());\n $this->assertEquals('tok', $creds->getSecurityToken());\n $this->assertEquals($exp, $creds->getExpiration());\n }\n\n public function testCanDisableRetries()\n {\n $client = new Client();\n $r = new ClientResolver(ClientResolver::getDefaultArguments());\n $r->resolve([\n 'service' => 's3',\n 'region' => 'baz',\n 'version' => 'latest',\n 'retries' => 0,\n 'client' => $client\n ], new Emitter());\n $this->assertCount(0, $client->getEmitter()->listeners('error'));\n }\n\n public function testCanEnableRetries()\n {\n $client = new Client();\n $r = new ClientResolver(ClientResolver::getDefaultArguments());\n $r->resolve([\n 'service' => 's3',\n 'region' => 'baz',\n 'version' => 'latest',\n 'retries' => 2,\n 'client' => $client\n ], new Emitter());\n $this->assertGreaterThan(0, $client->getEmitter()->listeners('error'));\n }\n\n public function testCanCreateNullCredentials()\n {\n $r = new ClientResolver(ClientResolver::getDefaultArguments());\n $conf = $r->resolve([\n 'service' => 'sqs',\n 'region' => 'x',\n 'credentials' => false,\n 'version' => 'latest'\n ], new Emitter());\n $this->assertInstanceOf(\n 'Aws\\Credentials\\NullCredentials',\n $conf['credentials']\n );\n $this->assertEquals('anonymous', $conf['config']['signature_version']);\n }\n\n public function testCanCreateCredentialsFromProvider()\n {\n $c = new Credentials('foo', 'bar');\n $r = new ClientResolver(ClientResolver::getDefaultArguments());\n $conf = $r->resolve([\n 'service' => 'sqs',\n 'region' => 'x',\n 'credentials' => function () use ($c) { return $c; },\n 'version' => 'latest'\n ], new Emitter());\n $this->assertSame($c, $conf['credentials']);\n }\n\n public function testCanCreateCredentialsFromProfile()\n {\n $dir = sys_get_temp_dir() . '/.aws';\n if (!is_dir($dir)) {\n mkdir($dir, 0777, true);\n }\n $ini = <<<EOT\n[foo]\naws_access_key_id = foo\naws_secret_access_key = baz\naws_security_token = tok\nEOT;\n file_put_contents($dir . '/credentials', $ini);\n $home = getenv('HOME');\n putenv('HOME=' . dirname($dir));\n $r = new ClientResolver(ClientResolver::getDefaultArguments());\n $conf = $r->resolve([\n 'service' => 'sqs',\n 'region' => 'x',\n 'profile' => 'foo',\n 'version' => 'latest'\n ], new Emitter());\n $creds = $conf['credentials'];\n $this->assertEquals('foo', $creds->getAccessKeyId());\n $this->assertEquals('baz', $creds->getSecretKey());\n $this->assertEquals('tok', $creds->getSecurityToken());\n unlink($dir . '/credentials');\n putenv(\"HOME=$home\");\n }\n\n public function testCanUseCredentialsObject()\n {\n $c = new Credentials('foo', 'bar');\n $r = new ClientResolver(ClientResolver::getDefaultArguments());\n $conf = $r->resolve([\n 'service' => 'sqs',\n 'region' => 'x',\n 'credentials' => $c,\n 'version' => 'latest'\n ], new Emitter());\n $this->assertSame($c, $conf['credentials']);\n }\n\n public function testCanUseCustomEndpointProviderWithExtraData()\n {\n $p = function () {\n return [\n 'endpoint' => 'http://foo.com',\n 'signatureVersion' => 'v2'\n ];\n };\n $r = new ClientResolver(ClientResolver::getDefaultArguments());\n $conf = $r->resolve([\n 'service' => 'sqs',\n 'region' => 'x',\n 'endpoint_provider' => $p,\n 'version' => 'latest'\n ], new Emitter());\n $this->assertEquals('v2', $conf['config']['signature_version']);\n }\n\n public function testAddsLogger()\n {\n $r = new ClientResolver(ClientResolver::getDefaultArguments());\n $logger = $this->getMockBuilder('Psr\\Log\\LoggerInterface')\n ->getMockForAbstractClass();\n $conf = $r->resolve([\n 'service' => 'sqs',\n 'region' => 'x',\n 'retries' => 2,\n 'retry_logger' => $logger,\n 'endpoint' => 'http://us-east-1.foo.amazonaws.com',\n 'version' => 'latest'\n ], new Emitter());\n $this->assertTrue(SdkTest::hasListener(\n $conf['client']->getEmitter(),\n 'GuzzleHttp\\Subscriber\\Retry\\RetrySubscriber',\n 'error'\n ));\n }\n\n public function testAddsLoggerWithDebugSettings()\n {\n $r = new ClientResolver(ClientResolver::getDefaultArguments());\n $conf = $r->resolve([\n 'service' => 'sqs',\n 'region' => 'x',\n 'retry_logger' => 'debug',\n 'endpoint' => 'http://us-east-1.foo.amazonaws.com',\n 'version' => 'latest'\n ], new Emitter());\n $this->assertTrue(SdkTest::hasListener(\n $conf['client']->getEmitter(),\n 'GuzzleHttp\\Subscriber\\Retry\\RetrySubscriber',\n 'error'\n ));\n }\n\n public function testAddsDebugListener()\n {\n $em = new Emitter();\n $r = new ClientResolver(ClientResolver::getDefaultArguments());\n $r->resolve([\n 'service' => 'sqs',\n 'region' => 'x',\n 'debug' => true,\n 'endpoint' => 'http://us-east-1.foo.amazonaws.com',\n 'version' => 'latest'\n ], $em);\n $this->assertTrue(SdkTest::hasListener(\n $em,\n 'GuzzleHttp\\Command\\Subscriber\\Debug',\n 'prepared'\n ));\n }\n\n public function canSetDebugToFalse()\n {\n $em = new Emitter();\n $r = new ClientResolver(ClientResolver::getDefaultArguments());\n $r->resolve([\n 'service' => 'sqs',\n 'region' => 'x',\n 'debug' => false,\n 'endpoint' => 'http://us-east-1.foo.amazonaws.com',\n 'version' => 'latest'\n ], $em);\n $this->assertFalse(SdkTest::hasListener(\n $em,\n 'GuzzleHttp\\Command\\Subscriber\\Debug',\n 'prepared'\n ));\n }\n\n /**\n * @expectedException \\GuzzleHttp\\Exception\\RequestException\n * @expectedExceptionMessage foo\n */\n public function testCanProvideCallableClient()\n {\n $r = new ClientResolver(ClientResolver::getDefaultArguments());\n $conf = $r->resolve([\n 'service' => 'dynamodb',\n 'region' => 'x',\n 'version' => 'latest',\n 'client' => function (array $args) {\n return new Client([\n 'handler' => function () {\n throw new \\UnexpectedValueException('foo');\n }\n ]);\n }\n ], new Emitter());\n\n $conf['client']->get('http://localhost:123');\n }\n\n public function testCanAddHttpClientDefaultOptions()\n {\n $r = new ClientResolver(ClientResolver::getDefaultArguments());\n $conf = $r->resolve([\n 'service' => 'sqs',\n 'region' => 'x',\n 'version' => 'latest',\n 'http' => ['foo' => 'bar']\n ], new Emitter());\n $this->assertEquals('bar', $conf['client']->getDefaultOption('foo'));\n }\n\n public function testCanAddConfigOptions()\n {\n $c = new S3Client([\n 'version' => 'latest',\n 'region' => 'us-west-2',\n 'calculate_md5' => true\n ]);\n $this->assertTrue($c->getConfig('calculate_md5'));\n }\n\n public function testSkipsNonRequiredKeys()\n {\n $r = new ClientResolver([\n 'foo' => [\n 'valid' => ['int'],\n 'type' => 'value'\n ]\n ]);\n $r->resolve([], new Emitter());\n }\n\n /**\n * @expectedException \\InvalidArgumentException\n * @expectedExceptionMessage A \"version\" configuration value is required\n */\n public function testHasSpecificMessageForMissingVersion()\n {\n $args = ClientResolver::getDefaultArguments()['version'];\n $r = new ClientResolver(['version' => $args]);\n $r->resolve(['service' => 'foo'], new Emitter());\n }\n\n /**\n * @expectedException \\InvalidArgumentException\n * @expectedExceptionMessage A \"region\" configuration value is required for the \"foo\" service\n */\n public function testHasSpecificMessageForMissingRegion()\n {\n $args = ClientResolver::getDefaultArguments()['region'];\n $r = new ClientResolver(['region' => $args]);\n $r->resolve(['service' => 'foo'], new Emitter());\n }\n}\n" }, { "alpha_fraction": 0.5285714268684387, "alphanum_fraction": 0.5387755036354065, "avg_line_length": 26.22222137451172, "blob_id": "a915556f82bc7b11df9568c64200a9b21e564343", "content_id": "0f14a7a4c0fb3f6745a2f43b978a25fccabf20b8", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1470, "license_type": "permissive", "max_line_length": 77, "num_lines": 54, "path": "/tests/S3/PutObjectUrlSubscriberTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\S3\\Subscriber;\n\nuse Aws\\Test\\UsesServiceTrait;\nuse GuzzleHttp\\Client;\nuse GuzzleHttp\\Event\\BeforeEvent;\nuse GuzzleHttp\\Message\\Response;\n\n/**\n * @covers Aws\\S3\\PutObjectUrlSubscriber\n */\nclass PutObjectUrlTest extends \\PHPUnit_Framework_TestCase\n{\n use UsesServiceTrait;\n\n public function testAddsObjectUrl()\n {\n $http = new Client();\n $http->getEmitter()->on('before', function (BeforeEvent $e) {\n $e->intercept(new Response(200));\n });\n\n $client = $this->getTestClient('s3', ['client' => $http]);\n $result = $client->putObject([\n 'Bucket' => 'test',\n 'Key' => 'key',\n 'Body' => 'hi'\n ]);\n\n $this->assertEquals(\n 'https://test.s3.amazonaws.com/key',\n $result['ObjectURL']\n );\n }\n\n public function testAddsObjectUrlToCompleteMultipart()\n {\n $http = new Client();\n $http->getEmitter()->on('before', function (BeforeEvent $e) {\n $e->intercept(new Response(200, [\n 'Location' => 'https://test.s3.amazonaws.com/key'\n ]));\n });\n\n $client = $this->getTestClient('s3', ['client' => $http]);\n $result = $client->completeMultipartUpload([\n 'Bucket' => 'test',\n 'Key' => 'key',\n 'UploadId' => '123'\n ]);\n\n $this->assertTrue(array_key_exists('ObjectURL', $result->toArray()));\n }\n}\n" }, { "alpha_fraction": 0.5395559668540955, "alphanum_fraction": 0.544729471206665, "avg_line_length": 35.384315490722656, "blob_id": "8b153dd00fcf5bda6dcb311d3c637f1572276829", "content_id": "9d068c6a457c37456fe7f1f17081873bd7f9585d", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 18556, "license_type": "permissive", "max_line_length": 104, "num_lines": 510, "path": "/src/S3/S3Client.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\S3;\n\nuse Aws\\AwsClient;\nuse Aws\\S3\\Exception\\S3Exception;\nuse Aws\\Result;\nuse Aws\\Retry\\ThrottlingFilter;\nuse Aws\\ClientResolver;\nuse Aws\\Retry\\S3TimeoutFilter;\nuse Aws\\Subscriber\\SaveAs;\nuse Aws\\Subscriber\\SourceFile;\nuse GuzzleHttp\\Command\\Event\\InitEvent;\nuse GuzzleHttp\\Event\\EmitterInterface;\nuse GuzzleHttp\\Message\\ResponseInterface;\nuse GuzzleHttp\\Subscriber\\Retry\\RetrySubscriber;\nuse GuzzleHttp\\Stream\\AppendStream;\nuse GuzzleHttp\\Stream\\Stream;\nuse GuzzleHttp\\Command\\CommandInterface;\nuse GuzzleHttp\\Stream\\StreamInterface;\nuse GuzzleHttp\\Stream\\Utils;\n\n/**\n * Client used to interact with **Amazon Simple Storage Service (Amazon S3)**.\n */\nclass S3Client extends AwsClient\n{\n public static function getArguments()\n {\n $args = parent::getArguments();\n // S3 does not require a region for the \"classic\" endpoint.\n $args['region']['default'] = 'us-east-1';\n // Apply custom retry strategy.\n $args['retries']['fn'] = self::createRetry();\n // Handle HEAD request error parsing.\n $args['api_provider']['fn'] = self::applyApiProvider();\n\n return $args + [\n 'force_path_style' => [\n 'type' => 'config',\n 'valid' => ['bool'],\n 'doc' => 'Set to true to send requests using path style '\n . 'bucket addressing (e.g., '\n . 'https://s3.amazonaws.com/bucket/key).',\n 'fn' => function ($value, $_, EmitterInterface $em) {\n if ($value === true) {\n $em->on('init', function (InitEvent $e) {\n $e->getCommand()['PathStyle'] = true;\n });\n }\n },\n ],\n 'calculate_md5' => [\n 'type' => 'config',\n 'valid' => ['bool'],\n 'doc' => 'Set to false to disable calculating an MD5 for '\n . 'all Amazon S3 signed uploads.',\n 'default' => function (array &$args) {\n // S3Client should calculate MD5 checksums for uploads\n // unless explicitly disabled or using a v4 signer.\n return $args['config']['signature_version'] != 'v4';\n },\n ],\n 'bucket_endpoint' => [\n 'type' => 'config',\n 'valid' => ['bool'],\n 'doc' => 'Set to true to send requests to a hardcoded bucket '\n . 'endpoint rather than create an endpoint as a '\n . 'result of injecting the bucket into the URL. This '\n . 'option is useful for interacting with CNAME '\n . 'endpoints.',\n ]\n ];\n }\n\n /**\n * {@inheritdoc}\n *\n * In addition to the options available to\n * {@see Aws\\AwsClient::__construct}, S3Client accepts the following\n * options:\n *\n * - bucket_endpoint: (bool) Set to true to send requests to a\n * hardcoded bucket endpoint rather than create an endpoint as a result\n * of injecting the bucket into the URL. This option is useful for\n * interacting with CNAME endpoints.\n * - calculate_md5: (bool) Set to false to disable calculating an MD5\n * for all Amazon S3 signed uploads.\n * - force_path_style: (bool) Set to true to send requests using path\n * style bucket addressing (e.g., https://s3.amazonaws.com/bucket/key).\n *\n * @param array $args\n */\n public function __construct(array $args)\n {\n parent::__construct($args);\n $em = $this->getEmitter();\n $em->attach(new BucketStyleSubscriber($this->getConfig('bucket_endpoint')));\n $em->attach(new PermanentRedirectSubscriber());\n $em->attach(new SSECSubscriber());\n $em->attach(new PutObjectUrlSubscriber());\n $em->attach(new SourceFile($this->getApi()));\n $em->attach(new ApplyMd5Subscriber());\n $em->attach(new SaveAs());\n }\n\n /**\n * Determine if a string is a valid name for a DNS compatible Amazon S3\n * bucket.\n *\n * DNS compatible bucket names can be used as a subdomain in a URL (e.g.,\n * \"<bucket>.s3.amazonaws.com\").\n *\n * @param string $bucket Bucket name to check.\n *\n * @return bool\n */\n public static function isBucketDnsCompatible($bucket)\n {\n $bucketLen = strlen($bucket);\n\n return ($bucketLen >= 3 && $bucketLen <= 63) &&\n // Cannot look like an IP address\n !filter_var($bucket, FILTER_VALIDATE_IP) &&\n preg_match('/^[a-z0-9]([a-z0-9\\-\\.]*[a-z0-9])?$/', $bucket);\n }\n\n /**\n * Create a pre-signed URL for the given S3 command object.\n *\n * @param CommandInterface $command Command to create a pre-signed\n * URL for.\n * @param int|string|\\DateTime $expires The time at which the URL should\n * expire. This can be a Unix\n * timestamp, a PHP DateTime object,\n * or a string that can be evaluated\n * by strtotime\n * @return string\n */\n public function createPresignedUrl(CommandInterface $command, $expires)\n {\n $signer = call_user_func(\n $this->getSignatureProvider(),\n $this->getConfig('signature_version'),\n $this->getApi()->getSigningName(),\n $this->getRegion()\n );\n\n return $signer->createPresignedUrl(\n $this->initTransaction($command)->request,\n $this->getCredentials(),\n $expires\n );\n }\n\n /**\n * Returns the URL to an object identified by its bucket and key.\n *\n * If an expiration time is provided, the URL will be signed and set to\n * expire at the provided time.\n *\n * @param string $bucket The name of the bucket where the object is located\n * @param string $key The key of the object\n * @param mixed $expires The time at which the URL should expire.\n * @param array $args Associative array of additional arguments found\n * in the GetObject API operation.\n *\n * @return string The URL to the object\n */\n public function getObjectUrl($bucket, $key, $expires = null, array $args = [])\n {\n $args = ['Bucket' => $bucket, 'Key' => $key] + $args;\n $command = $this->getCommand('GetObject', $args);\n\n return $expires\n ? $this->createPresignedUrl($command, $expires)\n : $this->initTransaction($command)->request->getUrl();\n }\n\n /**\n * Determines whether or not a bucket exists by name.\n *\n * @param string $bucket The name of the bucket\n *\n * @return bool\n */\n public function doesBucketExist($bucket)\n {\n return $this->checkExistenceWithCommand(\n $this->getCommand('HeadBucket', ['Bucket' => $bucket])\n );\n }\n\n /**\n * Determines whether or not an object exists by name.\n *\n * @param string $bucket The name of the bucket\n * @param string $key The key of the object\n * @param array $options Additional options available in the HeadObject\n * operation (e.g., VersionId).\n *\n * @return bool\n */\n public function doesObjectExist($bucket, $key, array $options = [])\n {\n return $this->checkExistenceWithCommand(\n $this->getCommand('HeadObject', [\n 'Bucket' => $bucket,\n 'Key' => $key\n ] + $options)\n );\n }\n\n /**\n * Raw URL encode a key and allow for '/' characters\n *\n * @param string $key Key to encode\n *\n * @return string Returns the encoded key\n */\n public static function encodeKey($key)\n {\n return str_replace('%2F', '/', rawurlencode($key));\n }\n\n /**\n * Register the Amazon S3 stream wrapper with this client instance.\n */\n public function registerStreamWrapper()\n {\n StreamWrapper::register($this);\n }\n\n /**\n * Deletes objects from Amazon S3 that match the result of a ListObjects\n * operation. For example, this allows you to do things like delete all\n * objects that match a specific key prefix.\n *\n * @param string $bucket Bucket that contains the object keys\n * @param string $prefix Optionally delete only objects under this key prefix\n * @param string $regex Delete only objects that match this regex\n * @param array $options Options used when deleting the object:\n * - before: Callable to invoke before each delete is called. This\n * callable accepts the underlying iterator being used and an array\n * of the keys that are about to be deleted.\n *\n * @see Aws\\S3\\S3Client::listObjects\n * @see Aws\\S3\\ClearBucket For more options or customization\n * @throws \\RuntimeException if no prefix and no regex is given\n */\n public function deleteMatchingObjects(\n $bucket,\n $prefix = '',\n $regex = '',\n array $options = []\n ) {\n if (!$prefix && !$regex) {\n throw new \\RuntimeException('A prefix or regex is required.');\n }\n\n $options['iterator'] = $this->getIterator('ListObjects', [\n 'Bucket' => $bucket,\n 'Prefix' => $prefix\n ]);\n\n if ($regex) {\n $options['iterator'] = new \\CallbackFilterIterator(\n $options['iterator'],\n function ($c) use ($regex) {\n return preg_match($regex, $c['Key']);\n }\n );\n $options['iterator']->rewind();\n }\n\n (new ClearBucket($this, $bucket, $options))->clear();\n }\n\n /**\n * Upload a file, stream, or string to a bucket.\n *\n * If the upload size exceeds the specified threshold, the upload will be\n * performed using parallel multipart uploads.\n *\n * @param string $bucket Bucket to upload the object\n * @param string $key Key of the object\n * @param mixed $body Object data to upload. Can be a\n * GuzzleHttp\\Stream\\StreamInterface, PHP stream\n * resource, or a string of data to upload.\n * @param string $acl ACL to apply to the object\n * @param array $options Custom options used when executing commands:\n *\n * - before_upload: Callback to invoke before each multipart upload.\n * The callback will receive a relevant Guzzle Event object.\n * - concurrency: Maximum number of concurrent multipart uploads.\n * - params: Custom parameters to use with the upload. The parameters\n * must map to the parameters specified in the PutObject operation.\n * - part_size: Minimum size to allow for each uploaded part when\n * performing a multipart upload.\n * - threshold: The minimum size, in bytes, the upload must be before\n * a multipart upload is required.\n *\n * @see Aws\\S3\\Model\\MultipartUpload\\UploadBuilder for more information.\n * @return Result Returns the modeled result of the performed operation.\n */\n public function upload(\n $bucket,\n $key,\n $body,\n $acl = 'private',\n array $options = []\n ) {\n // Apply default options.\n $options += [\n 'before_upload' => null,\n 'concurrency' => 1,\n 'params' => [],\n 'part_size' => null,\n 'threshold' => 16777216 // 16 MB\n ];\n\n // Perform the needed operations to upload the S3 Object.\n $body = Stream::factory($body);\n $params = ['ACL' => $acl] + $options['params'];\n\n if (!$this->requiresMultipart($body, $options['threshold'])) {\n return $this->execute($this->getCommand('PutObject', [\n 'Bucket' => $bucket,\n 'Key' => $key,\n 'Body' => $body,\n ] + $params));\n }\n\n return (new UploadBuilder)\n ->setClient($this)\n ->setSource($body)\n ->setBucket($bucket)\n ->setKey($key)\n ->addParams('initiate', $params)\n ->setPartSize($options['part_size'])\n ->build()\n ->upload($options['concurrency'], $options['before_upload']);\n }\n\n /**\n * Recursively uploads all files in a given directory to a given bucket.\n *\n * @param string $directory Full path to a directory to upload\n * @param string $bucket Name of the bucket\n * @param string $keyPrefix Virtual directory key prefix to add to each upload\n * @param array $options Options available in Aws\\S3\\Transfer::__construct\n *\n * @see Aws\\S3\\Transfer for more options and customization\n */\n public function uploadDirectory(\n $directory,\n $bucket,\n $keyPrefix = null,\n array $options = []\n ) {\n $d = \"s3://$bucket\" . ($keyPrefix ? '/' . ltrim($keyPrefix, '/') : '');\n (new Transfer($this, $directory, $d, $options))->transfer();\n }\n\n /**\n * Downloads a bucket to the local filesystem\n *\n * @param string $directory Directory to download to\n * @param string $bucket Bucket to download from\n * @param string $keyPrefix Only download objects that use this key prefix\n * @param array $options Options available in Aws\\S3\\Transfer::__construct\n */\n public function downloadBucket(\n $directory,\n $bucket,\n $keyPrefix = '',\n array $options = []\n ) {\n $s = \"s3://$bucket\" . ($keyPrefix ? '/' . ltrim($keyPrefix, '/') : '');\n (new Transfer($this, $s, $directory, $options))->transfer();\n }\n\n /**\n * Determines if the body should be uploaded using PutObject or the\n * Multipart Upload System. It also modifies the passed-in $body as needed\n * to support the upload.\n *\n * @param StreamInterface $body Stream representing the body.\n * @param integer $threshold Minimum bytes before using Multipart.\n *\n * @return bool\n */\n private function requiresMultipart(StreamInterface &$body, $threshold)\n {\n // If body size known, compare to threshold to determine if Multipart.\n if ($body->getSize() !== null) {\n return $body->getSize() < $threshold ? false : true;\n }\n\n // Handle the situation where the body size is unknown.\n // Read up to 5MB into a buffer to determine how to upload the body.\n $buffer = Stream::factory();\n Utils::copyToStream($body, $buffer, 5242880);\n\n // If body < 5MB, use PutObject with the buffer.\n if ($buffer->getSize() < 5242880) {\n $buffer->seek(0);\n $body = $buffer;\n return false;\n }\n\n // If >= 5 MB, and seekable, use Multipart with rewound body.\n if ($body->isSeekable()) {\n $body->seek(0);\n return true;\n }\n\n // If >= 5 MB, and non-seekable, use Multipart, but stitch the\n // buffer and the body together into one stream. This avoids\n // needing to seek and unnecessary disc usage, while requiring\n // only the 5 MB buffer to be re-read by the Multipart system.\n $buffer->seek(0);\n $body = new AppendStream([$buffer, $body]);\n\n return true;\n }\n\n /**\n * Determines whether or not a resource exists using a command\n *\n * @param CommandInterface $command Command used to poll for the resource\n *\n * @return bool\n * @throws S3Exception|\\Exception if there is an unhandled exception\n */\n private function checkExistenceWithCommand(CommandInterface $command)\n {\n try {\n $this->execute($command);\n return true;\n } catch (S3Exception $e) {\n if ($e->getAwsErrorCode() == 'AccessDenied') {\n return true;\n }\n if ($e->getStatusCode() >= 500) {\n throw $e;\n }\n return false;\n }\n }\n\n /**\n * @deprecated This method is deprecated. Use Aws\\S3\\ClearBucket directly.\n */\n public function clearBucket($bucket)\n {\n (new ClearBucket($this, $bucket))->clear();\n }\n\n /**\n * @deprecated Use Aws\\S3\\S3Client::isBucketDnsCompatible() directly\n */\n public static function isValidBucketName($bucket)\n {\n return self::isBucketDnsCompatible($bucket);\n }\n\n private static function createRetry()\n {\n return function ($value, array &$args) {\n if ($value) {\n $args['client']->getEmitter()->attach(new RetrySubscriber(\n ClientResolver::_wrapDebugLogger($args, [\n 'max' => $value,\n 'delay' => ['GuzzleHttp\\Subscriber\\Retry\\RetrySubscriber', 'exponentialDelay'],\n 'filter' => RetrySubscriber::createChainFilter([\n new S3TimeoutFilter(),\n new ThrottlingFilter($args['error_parser']),\n RetrySubscriber::createStatusFilter(),\n RetrySubscriber::createConnectFilter()\n ])\n ])\n ));\n }\n };\n }\n\n private static function applyApiProvider()\n {\n return function ($value, &$args) {\n ClientResolver::_apply_api_provider($value, $args);\n $parser = function (ResponseInterface $response) use ($args) {\n // Call the original parser.\n $errorData = $args['error_parser']($response);\n // Handle 404 responses where the code was not parsed.\n if (!isset($errorData['code'])\n && $response->getStatusCode() == 404\n ) {\n $url = (new S3UriParser)->parse($response->getEffectiveUrl());\n if (isset($url['key'])) {\n $errorData['code'] = 'NoSuchKey';\n } elseif ($url['bucket']) {\n $errorData['code'] = 'NoSuchBucket';\n }\n }\n return $errorData;\n };\n $args['error_parser'] = $parser;\n };\n }\n}\n" }, { "alpha_fraction": 0.4392523467540741, "alphanum_fraction": 0.4392523467540741, "avg_line_length": 14.285714149475098, "blob_id": "cf7a114d124187497dfa698cdac9c836da636bf9", "content_id": "85675576b8ce3f455e18fd77532da391c4f1f3f5", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 107, "license_type": "permissive", "max_line_length": 34, "num_lines": 7, "path": "/src/data/sqs-2012-11-05.paginators.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php return [\n 'pagination' => [\n 'ListQueues' => [\n 'result_key' => 'QueueUrls',\n ],\n ],\n];\n" }, { "alpha_fraction": 0.5518239736557007, "alphanum_fraction": 0.5616676211357117, "avg_line_length": 27.78333282470703, "blob_id": "8f1846d11c55267fcbb9eb084fb146424f271fd2", "content_id": "9a52f99527146ead21b041c914acadbf4c5519d5", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1727, "license_type": "permissive", "max_line_length": 77, "num_lines": 60, "path": "/src/Signature/SignatureV2.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Signature;\n\nuse Aws\\Credentials\\CredentialsInterface;\nuse GuzzleHttp\\Message\\RequestInterface;\nuse GuzzleHttp\\Post\\PostBodyInterface;\n\n/**\n * Implementation of Signature Version 2\n * @link http://aws.amazon.com/articles/1928\n */\nclass SignatureV2 extends AbstractSignature\n{\n public function signRequest(\n RequestInterface $request,\n CredentialsInterface $credentials\n ) {\n /** @var PostBodyInterface $body */\n $body = $request->getBody();\n $body->setField('Timestamp', gmdate('c'));\n $body->setField('SignatureVersion', '2');\n $body->setField('SignatureMethod', 'HmacSHA256');\n $body->setField('AWSAccessKeyId', $credentials->getAccessKeyId());\n\n if ($token = $credentials->getSecurityToken()) {\n $body->setField('SecurityToken', $token);\n }\n\n // build string to sign\n $sign = $request->getMethod() . \"\\n\"\n . $request->getHost() . \"\\n\"\n . '/' . \"\\n\"\n . $this->getCanonicalizedParameterString($body);\n\n $request->getConfig()->set('aws.signature', $sign);\n\n $body->setField('Signature', base64_encode(\n hash_hmac(\n 'sha256',\n $sign,\n $credentials->getSecretKey(),\n true\n )\n ));\n }\n\n private function getCanonicalizedParameterString(PostBodyInterface $body)\n {\n $params = $body->getFields();\n unset($params['Signature']);\n uksort($params, 'strcmp');\n\n $str = '';\n foreach ($params as $key => $val) {\n $str .= rawurlencode($key) . '=' . rawurlencode($val) . '&';\n }\n\n return substr($str, 0, -1);\n }\n}\n" }, { "alpha_fraction": 0.5226299166679382, "alphanum_fraction": 0.5305011868476868, "avg_line_length": 29.964157104492188, "blob_id": "d8de9a645cf9ccd88cae277ec39ac18666aa22fe", "content_id": "1606e4e93247d890639ad32689470155c36aaa3d", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 8639, "license_type": "permissive", "max_line_length": 86, "num_lines": 279, "path": "/src/Glacier/UploadBuilder.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Glacier;\n\nuse Aws\\Multipart\\AbstractUploadBuilder;\nuse Aws\\Multipart\\UploadState;\nuse Aws\\Result;\nuse GuzzleHttp\\Command\\CommandInterface;\nuse GuzzleHttp\\Stream\\Stream;\nuse GuzzleHttp\\Stream\\StreamInterface;\nuse GuzzleHttp\\Stream\\Utils;\nuse GuzzleHttp\\Subscriber\\MessageIntegrity\\HashingStream;\nuse GuzzleHttp\\Subscriber\\MessageIntegrity\\PhpHash;\n\n/**\n * Creates a multipart uploader used to easily upload large archives to Glacier.\n */\nclass UploadBuilder extends AbstractUploadBuilder\n{\n protected $config = [\n 'id' => ['accountId', 'vaultName', 'uploadId'],\n 'part' => [\n 'min_size' => 1048576,\n 'max_size' => 4294967296,\n 'max_num' => 10000,\n 'param' => 'range',\n ],\n 'initiate' => [\n 'command' => 'InitiateMultipartUpload',\n 'params' => [],\n ],\n 'upload' => [\n 'command' => 'UploadMultipartPart',\n 'params' => [],\n ],\n 'complete' => [\n 'command' => 'CompleteMultipartUpload',\n 'params' => [],\n ],\n 'abort' => [\n 'command' => 'AbortMultipartUpload',\n 'params' => [],\n ],\n ];\n\n /** @var string Archive description. */\n protected $archiveDescription;\n\n public function __construct()\n {\n parent::__construct();\n $this->uploadId['accountId'] = '-';\n }\n\n /**\n * Set the account ID of the the archive.\n *\n * @param string $accountId ID of the account.\n *\n * @return self\n */\n public function setAccountId($accountId)\n {\n $this->uploadId['accountId'] = $accountId;\n\n return $this;\n }\n\n /**\n * Set the vault name to upload the archive to.\n *\n * @param string $vaultName Name of the vault.\n *\n * @return self\n */\n public function setVaultName($vaultName)\n {\n $this->uploadId['vaultName'] = $vaultName;\n\n return $this;\n }\n\n /**\n * Set the upload ID of the upload.\n *\n * @param string $uploadId ID of the upload.\n *\n * @return self\n */\n public function setUploadId($uploadId)\n {\n $this->uploadId['uploadId'] = $uploadId;\n\n return $this;\n }\n\n /**\n * Set the archive description.\n *\n * @param string $description Description to associate with the archive.\n *\n * @return self\n */\n public function setArchiveDescription($description)\n {\n $this->config['initiate']['params']['archiveDescription'] = $description;\n\n return $this;\n }\n\n protected function prepareParams()\n {\n $this->config['initiate']['params']['partSize'] = $this->state->getPartSize();\n }\n\n protected function loadStateByUploadId(array $params = [])\n {\n $state = new UploadState($params);\n\n // Get all of the parts and archive information\n $partSize = null;\n $results = $this->client->getPaginator('ListParts', $params);\n foreach ($results as $result) {\n if (!$partSize) $partSize = $result['PartSizeInBytes'];\n foreach ($result['Parts'] as $part) {\n $rangeData = $this->parseRange($part['RangeInBytes'], $partSize);\n $state->markPartAsUploaded($rangeData['PartNumber'], [\n 'size' => $rangeData['Size'],\n 'checksum' => $part['SHA256TreeHash'],\n ]);\n }\n }\n $state->setPartSize('partSize', $partSize);\n $state->setStatus($state::INITIATED);\n\n return $state;\n }\n\n protected function determinePartSize()\n {\n // Make sure the part size is set.\n $partSize = $this->specifiedPartSize ?: $this->config['part']['min_size'];\n\n // Calculate list of valid part sizes.\n static $validSizes;\n if (!$validSizes) {\n $validSizes = array_map(function ($n) {\n return pow(2, $n) * $this->config['part']['min_size'];\n }, range(0, 12));\n }\n\n // Ensure that the part size is valid.\n if (!in_array($partSize, $validSizes)) {\n throw new \\InvalidArgumentException('The part size must be a power '\n . 'of 2, in megabytes, such that 1 MB <= PART_SIZE <= 4 GB.');\n }\n\n return $partSize;\n }\n\n protected function getCompleteParamsFn()\n {\n return function () {\n $treeHash = new TreeHash();\n $archiveSize = 0;\n foreach ($this->state->getUploadedParts() as $part) {\n $archiveSize += $part['size'];\n $treeHash->addChecksum($part['checksum']);\n }\n\n return [\n 'archiveSize' => $archiveSize,\n 'checksum' => bin2hex($treeHash->complete()),\n ];\n };\n }\n\n protected function getResultHandlerFn()\n {\n return function (CommandInterface $command, Result $result) {\n // Get data from the range.\n $rangeData = $this->parseRange(\n $command['range'],\n $this->state->getPartSize()\n );\n\n // Store the data we need for later.\n $this->state->markPartAsUploaded($rangeData['PartNumber'], [\n 'size' => $rangeData['Size'],\n 'checksum' => $command['checksum']\n ]);\n };\n }\n\n protected function getCreatePartFn()\n {\n return function ($seekable) {\n $data = [];\n $firstByte = $this->source->tell();\n\n // Read from the source to create the body stream. This also\n // calculates the linear and tree hashes as the data is read.\n if ($seekable) {\n // Case 1: Stream is seekable, can make stream from new handle.\n $body = Utils::open($this->source->getMetadata('uri'), 'r');\n $body = $this->limitPartStream(Stream::factory($body));\n // Create another stream decorated with hashing streams and read\n // through it, so we can get the hash values for the part.\n $decoratedBody = $this->decorateWithHashes($body, $data);\n while (!$decoratedBody->eof()) $decoratedBody->read(1048576);\n // Seek the original source forward to the end of the range.\n $this->source->seek($this->source->tell() + $body->getSize());\n } else {\n // Case 2: Stream is not seekable, must store part in temp stream.\n $source = $this->limitPartStream($this->source);\n $source = $this->decorateWithHashes($source, $data);\n $body = Stream::factory();\n Utils::copyToStream($source, $body);\n }\n\n $body->seek(0);\n $data['body'] = $body;\n $lastByte = $this->source->tell() - 1;\n $data['range'] = \"bytes {$firstByte}-{$lastByte}/*\";\n\n return $data;\n };\n }\n\n /**\n * Decorates a stream with a tree AND linear sha256 hashing stream.\n *\n * @param StreamInterface $stream Stream to decorate.\n * @param array $data Data bag that results are injected into.\n *\n * @return StreamInterface\n */\n private function decorateWithHashes(StreamInterface $stream, array &$data) {\n // Make sure that a tree hash is calculated.\n $stream = new HashingStream($stream, new TreeHash(),\n function ($result) use (&$data) {\n $data['checksum'] = bin2hex($result);\n }\n );\n\n // Make sure that a linear SHA256 hash is calculated.\n $stream = new HashingStream($stream, new PhpHash('sha256'),\n function ($result) use (&$data) {\n $data['ContentSHA256'] = bin2hex($result);\n }\n );\n\n return $stream;\n }\n\n /**\n * Parses a Glacier range string into a size and part number.\n *\n * @param string $range Glacier range string (e.g., \"bytes 5-5000/*\")\n * @param int $partSize The part size\n *\n * @return array\n */\n private function parseRange($range, $partSize)\n {\n // Strip away the prefix and suffix.\n if (strpos($range, 'bytes') !== false) {\n $range = substr($range, 6, -2);\n }\n\n // Split that range into it's parts.\n list($firstByte, $lastByte) = explode('-', $range);\n\n // Calculate and return data from the range.\n return [\n 'Size' => $lastByte - $firstByte + 1,\n 'PartNumber' => intval($firstByte / $partSize) + 1,\n ];\n }\n}\n" }, { "alpha_fraction": 0.5802047848701477, "alphanum_fraction": 0.585324227809906, "avg_line_length": 25.636363983154297, "blob_id": "ce320110d03b9f8fd068eef42c9262c1af21ed9d", "content_id": "8547dc20c649adf7624896ca3db2db3702c9d880", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 586, "license_type": "permissive", "max_line_length": 66, "num_lines": 22, "path": "/tests/S3/Exception/ClearBucketExceptionTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\S3\\Exception;\n\nuse Aws\\S3\\Exception\\ClearBucketException;\n\n/**\n * @covers Aws\\S3\\Exception\\ClearBucketException\n */\nclass ClearBucketExceptionTest extends \\PHPUnit_Framework_TestCase\n{\n public function testReturnsData()\n {\n $p = new \\Exception('a');\n $i = new \\ArrayIterator([]);\n $e = new ClearBucketException([\n ['Key' => 'foo']\n ], $i, $p);\n $this->assertSame([['Key' => 'foo']], $e->getErrors());\n $this->assertSame($i, $e->getIterator());\n $this->assertSame($p, $e->getPrevious());\n }\n}\n" }, { "alpha_fraction": 0.5915687680244446, "alphanum_fraction": 0.6344160437583923, "avg_line_length": 35.17499923706055, "blob_id": "92baddbc4d47d04c1b8b70b8a66e9a60b8bf236d", "content_id": "fc8d422b5108dcd920b0d46777a11cca0e390362", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1447, "license_type": "permissive", "max_line_length": 229, "num_lines": 40, "path": "/tests/Signature/SignatureV2Test.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Signature;\n\nrequire_once __DIR__ . '/sig_hack.php';\n\nuse Aws\\Credentials\\Credentials;\nuse Aws\\Signature\\SignatureV2;\nuse GuzzleHttp\\Message\\MessageFactory;\n\n/**\n * @covers Aws\\Signature\\SignatureV2\n */\nclass SignatureV2Test extends \\PHPUnit_Framework_TestCase\n{\n const DEFAULT_KEY = 'AKIDEXAMPLE';\n const DEFAULT_SECRET = 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY';\n const DEFAULT_DATETIME = 'Fri, 09 Sep 2011 23:36:00 GMT';\n\n public function testSignsRequestsWithSecurityToken()\n {\n $_SERVER['aws_time'] = true;\n $request = (new MessageFactory)->createRequest(\n 'POST',\n 'http://foo.com',\n ['body' => ['Test' => '123', 'Other' => '456']]\n );\n $request->removeHeader('User-Agent');\n $c = new Credentials(self::DEFAULT_KEY, self::DEFAULT_SECRET, 'foo');\n $sig = new SignatureV2();\n $sig->signRequest($request, $c);\n $request->getBody()->applyRequestHeaders($request);\n\n $expected = \"POST / HTTP/1.1\\r\\n\"\n . \"Host: foo.com\\r\\n\"\n . \"Content-Type: application/x-www-form-urlencoded\\r\\n\"\n . \"Content-Length: 212\\r\\n\\r\\n\"\n . \"Test=123&Other=456&Timestamp=Fri%2C+09+Sep+2011+23%3A36%3A00+GMT&SignatureVersion=2&SignatureMethod=HmacSHA256&AWSAccessKeyId=AKIDEXAMPLE&SecurityToken=foo&Signature=NzQ9b5Kx6qlKj2UIK6QHIrmq5ypogh9PhBHVXKA4RU4%3D\";\n $this->assertEquals($expected, (string) $request);\n }\n}\n" }, { "alpha_fraction": 0.7501969933509827, "alphanum_fraction": 0.7536117434501648, "avg_line_length": 41.29999923706055, "blob_id": "d3b85c9fe5e37326f185547631ee6600e798fc14", "content_id": "97692aa8da2b41e181b9ec13bce02c67eb5cfb18", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 3807, "license_type": "permissive", "max_line_length": 88, "num_lines": 90, "path": "/docs/requirements.rst", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "============\nRequirements\n============\n\nAside from a baseline understanding of object-oriented programming in PHP\n(including PHP namespaces and autoloading), there are a few minimum system\nrequirements to start using the AWS SDK for PHP.\n\n\nMinimum requirements\n--------------------\n\n* PHP >= 5.5.0\n\n\nOptional requirements\n---------------------\n\n`OpenSSL PHP extension <http://php.net/manual/en/book.openssl.php>`_\n To work with Amazon CloudFront private distributions, you must have the\n OpenSSL PHP extension to sign private CloudFront URLs.\n\n\n.. _optimal-settings:\n\nOptimal settings\n----------------\n\n`cURL <http://php.net/manual/en/book.curl.php>`_ >= 7.16.2\n While not required, we recommend installing a recent version of cURL compiled\n with OpenSSL/NSS and zlib. If cURL is not installed on your system and you do\n not configure a custom `RingPHP adapter <http://ringphp.readthedocs.org/en/latest/>`_,\n the SDK will use the PHP stream wrapper.\n\n The AWS SDK for PHP utilizes Guzzle as an HTTP client. Guzzle uses a handler\n system called `RingPHP <http://ringphp.readthedocs.org/en/latest/>`_ to allow\n Guzzle to utilize any sort of underlying transport (whether it's cURL, PHP\n sockets, PHP stream wrappers, etc.). You can configure which handler is used\n by the SDK using the ``client`` client constructor option and supplying a\n custom \"handler\" option to the created client.\n\n`OPCache <http://php.net/manual/en/book.opcache.php>`_\n Using the OPcache extension improves PHP performance by storing precompiled\n script bytecode in shared memory, thereby removing the need for PHP to load\n and parse scripts on each request. This extension is typically enabled by\n default.\n\n When running on Amazon Linux, you need to install the ``php55-opcache``\n yum package to utilize the OPCache extension.\n\nUninstall `Xdebug <http://xdebug.org/>`_\n Xdebug is an amazing tool that can be used to identify performance\n bottlenecks. However, if performance is critical to your application, do not\n install the Xdebug extension on your production environment. Simply loading\n the extension will greatly slow down the SDK.\n\n When running on Amazon Linux, Xdebug can be removed with the following\n command:\n\n .. code-block:: bash\n\n yum remove php55-pecl-xdebug\n\nUse a `Composer <http://getcomposer.org>`_ classmap autoloader\n Autoloaders are used to lazily load classes as they are required by a PHP\n script. Composer will generate an autoloader that is able to autoload the PHP\n scripts of your application and all of the PHP scripts of the vendors\n required by your application (i.e. the AWS SDK for PHP). When running in\n production, it is highly recommended that you use a classmap autoloader to\n improve the autoloader's speed. You can generate a classmap autoloader by\n passing the ``-o`` or ``--optimize-autoloader`` option to Composer's\n `install command <http://getcomposer.org/doc/03-cli.md#install>`_.\n\n\nCompatibility test\n------------------\n\nRun the `compatibility-test.php` file in the SDK to quickly check if your\nsystem is capable of running the SDK. In addition to meeting the minimum system\nrequirements of the SDK, the compatibility test checks for optional settings\nand makes recommendations that can help you to improve the performance of the\nSDK. The compatibility test can output text for the command line or a web\nbrowser. When running in a browser, successful checks appear in green, warnings\nin purple, and failures in red. When running from the CLI, the result of a\ncheck will appear on each line.\n\nWhen reporting an issue with the SDK, it is often helpful to share information\nabout your system. Supplying the output of the compatibility test in forum\nposts or GitHub issues can help to streamline the process of identifying the\nroot cause of an issue.\n" }, { "alpha_fraction": 0.5035136938095093, "alphanum_fraction": 0.51335209608078, "avg_line_length": 29.276596069335938, "blob_id": "80771f7f7e59da296453e8141605916e287ca72c", "content_id": "2f18f5f19445b30dd99acd639b74ffaa775f89e2", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2846, "license_type": "permissive", "max_line_length": 89, "num_lines": 94, "path": "/tests/S3/SSECSubscriberTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Tests\\S3;\n\nuse Aws\\S3\\SSECSubscriber;\nuse Aws\\Test\\UsesServiceTrait;\nuse GuzzleHttp\\Command\\Command;\nuse GuzzleHttp\\Command\\CommandTransaction;\nuse GuzzleHttp\\Command\\Event\\InitEvent;\nuse GuzzleHttp\\Message\\Response;\nuse GuzzleHttp\\Subscriber\\Mock;\n\n/**\n * @covers Aws\\S3\\SSECSubscriber\n */\nclass SseCpkListenerTest extends \\PHPUnit_Framework_TestCase\n{\n use UsesServiceTrait;\n\n /**\n * @dataProvider getListenerTestCases\n */\n public function testSseCpkListener($operation, array $params, array $expectedResults)\n {\n $command = new Command($operation, $params);\n $transaction = new CommandTransaction(\n $this->getTestClient('s3'),\n $command\n );\n $event = new InitEvent($transaction);\n $listener = new SSECSubscriber();\n $listener->onInit($event);\n foreach ($expectedResults as $key => $value) {\n $this->assertEquals($value, $expectedResults[$key]);\n }\n }\n\n public function getListenerTestCases()\n {\n return array(\n array(\n 'CopyObject',\n array(\n 'SSECustomerKey' => 'foo',\n 'CopySourceSSECustomerKey' => 'bar',\n ),\n array(\n 'SSECustomerAlgorithm' => null,\n 'SSECustomerKey' => base64_encode('foo'),\n 'SSECustomerKeyMD5' => base64_encode(md5('foo', true)),\n 'CopySourceSSECustomerKey' => base64_encode('bar'),\n 'CopySourceSSECustomerKeyMD5' => base64_encode(md5('bar', true)),\n )\n ),\n array(\n 'PutObject',\n array(\n 'SSECustomerKey' => 'foo',\n 'SSECustomerKeyMD5' => 'bar',\n ),\n array(\n 'SSECustomerKey' => base64_encode('foo'),\n 'SSECustomerKeyMD5' => base64_encode('bar'),\n )\n ),\n array(\n 'ListObjects',\n array(),\n array(\n 'SSECustomerKey' => null,\n 'SSECustomerKeyMD5' => null,\n )\n ),\n );\n }\n\n /**\n * @expectedException \\RuntimeException\n */\n public function testCannotUseWithoutHttps()\n {\n $client = $this->getTestClient('s3', ['scheme' => 'http']);\n $client->listBuckets([\n 'SSECustomerKey' => 'foo',\n 'CopySourceSSECustomerKey' => 'bar',\n ]);\n }\n\n public function testCanUseWithoutHttpsForNonSse()\n {\n $client = $this->getTestClient('s3', ['scheme' => 'http']);\n $client->getHttpClient()->getEmitter()->attach(new Mock([new Response(200)]));\n $client->listBuckets();\n }\n}\n" }, { "alpha_fraction": 0.5677888989448547, "alphanum_fraction": 0.5677888989448547, "avg_line_length": 26.247934341430664, "blob_id": "a44d642669ff583e67dd89c5ec83e1f3137547ac", "content_id": "4540a9c7b0783843200fdb43f76b273b1df72d45", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3297, "license_type": "permissive", "max_line_length": 113, "num_lines": 121, "path": "/src/Sns/MessageValidator/Message.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Sns\\MessageValidator;\n\nuse GuzzleHttp\\Collection;\nuse GuzzleHttp\\Utils;\n\nclass Message\n{\n private static $requiredKeys = [\n '__default' => ['Message', 'MessageId', 'Timestamp', 'TopicArn',\n 'Type', 'Signature', 'SigningCertURL',],\n 'SubscriptionConfirmation' => ['SubscribeURL', 'Token'],\n 'UnsubscribeConfirmation' => ['SubscribeURL', 'Token']\n ];\n\n private static $signableKeys = ['Message', 'MessageId', 'Subject',\n 'SubscribeURL', 'Timestamp', 'Token', 'TopicArn', 'Type'];\n\n /**\n * @var Collection The message data\n */\n private $data;\n\n /**\n * Creates a Message object from an array of raw message data\n *\n * @param array $data The message data\n *\n * @return Message\n * @throws \\InvalidArgumentException If a valid type is not provided or there are other required keys missing\n */\n public static function fromArray(array $data)\n {\n // Make sure the type key is set\n if (!isset($data['Type'])) {\n throw new \\InvalidArgumentException('The \"Type\" key must be '\n . 'provided to instantiate a Message object.');\n }\n\n // Determine required keys and create a collection from the message data\n $requiredKeys = array_merge(\n self::$requiredKeys['__default'],\n isset(self::$requiredKeys[$data['Type']])\n ? self::$requiredKeys[$data['Type']]\n : []\n );\n\n $data = Collection::fromConfig($data, [], $requiredKeys);\n\n return new self($data);\n }\n\n /**\n * Creates a message object from the raw POST data\n *\n * @return Message\n * @throws \\RuntimeException If the POST data is absent, or not a valid JSON document\n */\n public static function fromRawPostData()\n {\n if (!isset($_SERVER['HTTP_X_AMZ_SNS_MESSAGE_TYPE'])) {\n throw new \\RuntimeException('SNS message type header not provided.');\n }\n\n $data = Utils::jsonDecode(file_get_contents('php://input'), true);\n\n if (!is_array($data)) {\n throw new \\RuntimeException('POST data invalid');\n }\n\n return self::fromArray($data);\n }\n\n /**\n * @param Collection $data A Collection of message data with all required keys\n */\n public function __construct(Collection $data)\n {\n $this->data = $data;\n }\n\n /**\n * Get the entire message data as a Collection\n *\n * @return Collection\n */\n public function getData()\n {\n return $this->data;\n }\n\n /**\n * Gets a single key from the message data\n *\n * @param string $key Key to retrieve\n *\n * @return string\n */\n public function get($key)\n {\n return $this->data->get($key);\n }\n\n /**\n * Builds a newline delimited string to sign according to the specs\n *\n * @return string\n * @link http://docs.aws.amazon.com/sns/latest/gsg/SendMessageToHttp.verify.signature.html\n */\n public function getStringToSign()\n {\n $stringToSign = '';\n foreach (self::$signableKeys as $key) {\n if ($value = $this->get($key)) {\n $stringToSign .= \"{$key}\\n{$value}\\n\";\n }\n }\n\n return $stringToSign;\n }\n}\n" }, { "alpha_fraction": 0.5836052298545837, "alphanum_fraction": 0.585003674030304, "avg_line_length": 34.004661560058594, "blob_id": "f9bf4ddb5604ec644ee5ee896f5820976ca0d6ce", "content_id": "69f870557912ad2e48673b0b8c8fb25c796e0b3c", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 15017, "license_type": "permissive", "max_line_length": 93, "num_lines": 429, "path": "/src/AwsClient.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws;\n\nuse Aws\\Exception\\AwsException;\nuse Aws\\Api\\Service;\nuse Aws\\Credentials\\CredentialsInterface;\nuse Aws\\Signature\\SignatureProvider;\nuse GuzzleHttp\\Client;\nuse GuzzleHttp\\Command\\AbstractClient;\nuse GuzzleHttp\\Command\\Command;\nuse GuzzleHttp\\Command\\CommandInterface;\nuse GuzzleHttp\\Command\\CommandTransaction;\nuse GuzzleHttp\\Event\\BeforeEvent;\nuse GuzzleHttp\\Event\\RequestEvents;\nuse GuzzleHttp\\Exception\\RequestException;\nuse GuzzleHttp\\Command\\Event\\ProcessEvent;\n\n/**\n * Default AWS client implementation\n */\nclass AwsClient extends AbstractClient implements AwsClientInterface\n{\n /** @var CredentialsInterface AWS credentials */\n private $credentials;\n\n /** @var string */\n private $region;\n\n /** @var string */\n private $endpoint;\n\n /** @var Service */\n private $api;\n\n /** @var string */\n private $commandException = 'Aws\\Exception\\AwsException';\n\n /** @var callable */\n private $errorParser;\n\n /** @var callable */\n private $serializer;\n\n /** @var callable */\n private $signatureProvider;\n\n /** @var callable */\n private $defaultSignatureListener;\n\n /**\n * Get an array of client constructor arguments used by the client.\n *\n * @return array\n */\n public static function getArguments()\n {\n return ClientResolver::getDefaultArguments();\n }\n\n /**\n * The client constructor accepts the following options:\n *\n * - api_provider: (callable) An optional PHP callable that accepts a\n * type, service, and version argument, and returns an array of\n * corresponding configuration data. The type value can be one of api,\n * waiter, or paginator.\n * - client: (GuzzleHttp\\ClientInterface) Optional Guzzle client used to\n * transfer requests over the wire. If you do not specify a client, the\n * SDK will create a new client that uses a shared Ring HTTP handler\n * with other clients.\n * - credentials:\n * (array|Aws\\Credentials\\CredentialsInterface|bool|callable) An\n * Aws\\Credentials\\CredentialsInterface object to use with each, an\n * associative array of \"key\", \"secret\", and \"token\" key value pairs,\n * `false` to utilize null credentials, or a callable credentials\n * provider function to create credentials using a function. If no\n * credentials are provided, the SDK will attempt to load them from the\n * environment.\n * - debug: (bool|resource) Set to true to display debug information\n * when sending requests. Provide a stream resource to write debug\n * information to a specific resource.\n * - endpoint: (string) The full URI of the webservice. This is only\n * required when connecting to a custom endpoint (e.g., a local version\n * of S3).\n * - endpoint_provider: (callable) An optional PHP callable that\n * accepts a hash of options including a service and region key and\n * returns a hash of endpoint data, of which the endpoint key is\n * required.\n * - http: (array) Set to an array of Guzzle client request options\n * (e.g., proxy, verify, etc.). See\n * http://docs.guzzlephp.org/en/latest/clients.html#request-options for a\n * list of available options.\n * - profile: (string) Allows you to specify which profile to use when\n * credentials are created from the AWS credentials file in your HOME\n * directory. This setting overrides the AWS_PROFILE environment\n * variable. Note: Specifying \"profile\" will cause the \"credentials\" key\n * to be ignored.\n * - region: (string, required) Region to connect to. See\n * http://docs.aws.amazon.com/general/latest/gr/rande.html for a list of\n * available regions.\n * - retries: (int, default=int(3)) Configures the maximum number of\n * allowed retries for a client (pass 0 to disable retries).\n * - retry_logger: (string|Psr\\Log\\LoggerInterface) When the string \"debug\"\n * is provided, all retries will be logged to STDOUT. Provide a PSR-3\n * logger to log retries to a specific logger instance.\n * - ringphp_handler: (callable) RingPHP handler used to transfer HTTP\n * requests (see http://ringphp.readthedocs.org/en/latest/).\n * - scheme: (string, default=string(5) \"https\") URI scheme to use when\n * connecting connect.\n * - service: (string, required) Name of the service to utilize. This\n * value will be supplied by default.\n * - signature_provider: (callable) A callable that accepts a signature\n * version name (e.g., v4, s3), a service name, and region, and returns a\n * SignatureInterface object. This provider is used to create signers\n * utilized by the client.\n * - signature_version: (string) A string representing a custom\n * signature version to use with a service (e.g., v4, s3, v2). Note that\n * per/operation signature version MAY override this requested signature\n * version.\n * - validate: (bool, default=bool(true)) Set to false to disable\n * client-side parameter validation.\n * - version: (string, required) The version of the webservice to\n * utilize (e.g., 2006-03-01).\n *\n * @param array $args Client configuration arguments.\n *\n * @throws \\InvalidArgumentException if any required options are missing\n */\n public function __construct(array $args)\n {\n $service = $this->parseClass();\n $withResolved = null;\n\n if (!isset($args['service'])) {\n $args['service'] = $service;\n }\n\n $resolver = new ClientResolver(static::getArguments());\n $config = $resolver->resolve($args, $this->getEmitter());\n $this->api = $config['api'];\n $this->serializer = $config['serializer'];\n $this->errorParser = $config['error_parser'];\n $this->signatureProvider = $config['signature_provider'];\n $this->endpoint = $config['endpoint'];\n $this->credentials = $config['credentials'];\n $this->region = isset($config['region']) ? $config['region'] : null;\n $this->applyParser();\n $this->initSigners($config['config']['signature_version']);\n parent::__construct($config['client'], $config['config']);\n\n // Make sure the user agent is prefixed by the SDK version.\n $client = $this->getHttpClient();\n $client->setDefaultOption('allow_redirects', false);\n $client->setDefaultOption(\n 'headers/User-Agent',\n 'aws-sdk-php/' . Sdk::VERSION . ' ' . Client::getDefaultUserAgent()\n );\n\n if (isset($args['with_resolved'])) {\n /** @var callable $withResolved */\n $args['with_resolved']($config);\n }\n }\n\n /**\n * @deprecated\n * @return static\n */\n public static function factory(array $config = [])\n {\n return new static($config);\n }\n\n public function getCredentials()\n {\n return $this->credentials;\n }\n\n public function getEndpoint()\n {\n return $this->endpoint;\n }\n\n public function getRegion()\n {\n return $this->region;\n }\n\n public function getApi()\n {\n return $this->api;\n }\n\n /**\n * Executes an AWS command.\n *\n * @param CommandInterface $command Command to execute\n *\n * @return mixed Returns the result of the command\n * @throws AwsException when an error occurs during transfer\n */\n public function execute(CommandInterface $command)\n {\n try {\n return parent::execute($command);\n } catch (AwsException $e) {\n throw $e;\n } catch (\\Exception $e) {\n // Wrap other uncaught exceptions for consistency\n $exceptionClass = $this->commandException;\n throw new $exceptionClass(\n sprintf('Uncaught exception while executing %s::%s - %s',\n get_class($this),\n $command->getName(),\n $e->getMessage()),\n new CommandTransaction($this, $command),\n $e\n );\n }\n }\n\n public function getCommand($name, array $args = [])\n {\n // Fail fast if the command cannot be found in the description.\n if (!isset($this->api['operations'][$name])) {\n $name = ucfirst($name);\n if (!isset($this->api['operations'][$name])) {\n throw new \\InvalidArgumentException(\"Operation not found: $name\");\n }\n }\n\n if (isset($args['@future'])) {\n $future = $args['@future'];\n unset($args['@future']);\n } else {\n $future = false;\n }\n\n return new Command($name, $args, [\n 'emitter' => clone $this->getEmitter(),\n 'future' => $future\n ]);\n }\n\n public function getIterator($name, array $args = [])\n {\n $config = $this->api->getPaginatorConfig($name);\n if (!$config['result_key']) {\n throw new \\UnexpectedValueException(sprintf(\n 'There are no resources to iterate for the %s operation of %s',\n $name, $this->api['serviceFullName']\n ));\n }\n\n $key = is_array($config['result_key'])\n ? $config['result_key'][0]\n : $config['result_key'];\n\n if ($config['output_token'] && $config['input_token']) {\n return $this->getPaginator($name, $args)->search($key);\n }\n\n $result = $this->getCommand($name, $args)->search($key);\n\n return new \\ArrayIterator((array) $result);\n }\n\n public function getPaginator($name, array $args = [], array $config = [])\n {\n $config += $this->api->getPaginatorConfig($name);\n\n return new ResultPaginator($this, $name, $args, $config);\n }\n\n public function waitUntil($name, array $args = [], array $config = [])\n {\n // Create the waiter. If async, then waiting begins immediately.\n $config += $this->api->getWaiterConfig($name);\n $waiter = new Waiter($this, $name, $args, $config);\n\n // If async, return the future, for access to then()/wait()/cancel().\n if (!empty($args['@future'])) {\n return $waiter;\n }\n\n // For synchronous waiting, call wait() and don't return anything.\n $waiter->wait();\n }\n\n /**\n * Creates AWS specific exceptions.\n *\n * {@inheritdoc}\n *\n * @return AwsException\n */\n public function createCommandException(CommandTransaction $transaction)\n {\n // Throw AWS exceptions as-is\n if ($transaction->exception instanceof AwsException) {\n return $transaction->exception;\n }\n\n // Set default values (e.g., for non-RequestException)\n $url = null;\n $transaction->context['aws_error'] = [];\n $serviceError = $transaction->exception->getMessage();\n\n if ($transaction->exception instanceof RequestException) {\n $url = $transaction->exception->getRequest()->getUrl();\n if ($response = $transaction->exception->getResponse()) {\n $parser = $this->errorParser;\n // Add the parsed response error to the exception.\n $transaction->context['aws_error'] = $parser($response);\n // Only use the AWS error code if the parser could parse response.\n if (!$transaction->context->getPath('aws_error/type')) {\n $serviceError = $transaction->exception->getMessage();\n } else {\n // Create an easy to read error message.\n $serviceError = trim($transaction->context->getPath('aws_error/code')\n . ' (' . $transaction->context->getPath('aws_error/type')\n . ' error): ' . $transaction->context->getPath('aws_error/message'));\n }\n }\n }\n\n $exceptionClass = $this->commandException;\n return new $exceptionClass(\n sprintf('Error executing %s::%s() on \"%s\"; %s',\n get_class($this),\n lcfirst($transaction->command->getName()),\n $url,\n $serviceError),\n $transaction,\n $transaction->exception\n );\n }\n\n final protected function createFutureResult(CommandTransaction $transaction)\n {\n return new FutureResult(\n $transaction->response->then(function () use ($transaction) {\n return $transaction->result;\n }),\n [$transaction->response, 'wait'],\n [$transaction->response, 'cancel']\n );\n }\n\n final protected function serializeRequest(CommandTransaction $trans)\n {\n $fn = $this->serializer;\n $request = $fn($trans);\n\n // Note: We can later update this to allow custom per/operation\n // signers, by checking the corresponding operation for a\n // signatureVersion override and attaching a different listener.\n $request->getEmitter()->on(\n 'before',\n $this->defaultSignatureListener,\n RequestEvents::SIGN_REQUEST\n );\n\n return $request;\n }\n\n /**\n * Get the signature_provider function of the client.\n *\n * @return callable\n */\n final protected function getSignatureProvider()\n {\n return $this->signatureProvider;\n }\n\n private function initSigners($defaultVersion)\n {\n $credentials = $this->credentials;\n $defaultSigner = SignatureProvider::resolve(\n $this->signatureProvider,\n $defaultVersion,\n $this->api->getSigningName(),\n $this->region\n );\n $this->defaultSignatureListener = static function (BeforeEvent $e) use (\n $credentials,\n $defaultSigner\n ) {\n $defaultSigner->signRequest($e->getRequest(), $credentials);\n };\n }\n\n private function parseClass()\n {\n $klass = get_class($this);\n\n if ($klass === __CLASS__) {\n return '';\n }\n\n $service = substr($klass, strrpos($klass, '\\\\') + 1, -6);\n $this->commandException = \"Aws\\\\{$service}\\\\Exception\\\\{$service}Exception\";\n\n return strtolower($service);\n }\n\n private function applyParser()\n {\n $parser = Service::createParser($this->api);\n $this->getEmitter()->on(\n 'process',\n static function (ProcessEvent $e) use ($parser) {\n // Guard against exceptions and injected results.\n if ($e->getException() || $e->getResult()) {\n return;\n }\n\n // Ensure a response exists in order to parse.\n $response = $e->getResponse();\n if (!$response) {\n throw new \\RuntimeException('No response was received.');\n }\n\n $e->setResult($parser($e->getCommand(), $response));\n }\n );\n }\n}\n" }, { "alpha_fraction": 0.5145425796508789, "alphanum_fraction": 0.5145425796508789, "avg_line_length": 29.015872955322266, "blob_id": "a6c06242e9a611236ef33b4e722e7601cc7b6b30", "content_id": "3fe961cba190f0a4e120c0991bb930e5f5b794bd", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3782, "license_type": "permissive", "max_line_length": 76, "num_lines": 126, "path": "/src/data/iam-2010-05-08.paginators.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php return [\n 'pagination' => [\n 'GetAccountAuthorizationDetails' => [\n 'input_token' => 'Marker',\n 'output_token' => 'Marker',\n 'more_results' => 'IsTruncated',\n 'limit_key' => 'MaxItems',\n 'result_key' => 'UserDetailList || GroupDetailList || RoleDetailList',\n ],\n 'GetGroup' => [\n 'input_token' => 'Marker',\n 'output_token' => 'Marker',\n 'more_results' => 'IsTruncated',\n 'limit_key' => 'MaxItems',\n 'result_key' => 'Users',\n ],\n 'ListAccessKeys' => [\n 'input_token' => 'Marker',\n 'output_token' => 'Marker',\n 'more_results' => 'IsTruncated',\n 'limit_key' => 'MaxItems',\n 'result_key' => 'AccessKeyMetadata',\n ],\n 'ListAccountAliases' => [\n 'input_token' => 'Marker',\n 'output_token' => 'Marker',\n 'more_results' => 'IsTruncated',\n 'limit_key' => 'MaxItems',\n 'result_key' => 'AccountAliases',\n ],\n 'ListGroupPolicies' => [\n 'input_token' => 'Marker',\n 'output_token' => 'Marker',\n 'more_results' => 'IsTruncated',\n 'limit_key' => 'MaxItems',\n 'result_key' => 'PolicyNames',\n ],\n 'ListGroups' => [\n 'input_token' => 'Marker',\n 'output_token' => 'Marker',\n 'more_results' => 'IsTruncated',\n 'limit_key' => 'MaxItems',\n 'result_key' => 'Groups',\n ],\n 'ListGroupsForUser' => [\n 'input_token' => 'Marker',\n 'output_token' => 'Marker',\n 'more_results' => 'IsTruncated',\n 'limit_key' => 'MaxItems',\n 'result_key' => 'Groups',\n ],\n 'ListInstanceProfiles' => [\n 'input_token' => 'Marker',\n 'output_token' => 'Marker',\n 'more_results' => 'IsTruncated',\n 'limit_key' => 'MaxItems',\n 'result_key' => 'InstanceProfiles',\n ],\n 'ListInstanceProfilesForRole' => [\n 'input_token' => 'Marker',\n 'output_token' => 'Marker',\n 'more_results' => 'IsTruncated',\n 'limit_key' => 'MaxItems',\n 'result_key' => 'InstanceProfiles',\n ],\n 'ListMFADevices' => [\n 'input_token' => 'Marker',\n 'output_token' => 'Marker',\n 'more_results' => 'IsTruncated',\n 'limit_key' => 'MaxItems',\n 'result_key' => 'MFADevices',\n ],\n 'ListRolePolicies' => [\n 'input_token' => 'Marker',\n 'output_token' => 'Marker',\n 'more_results' => 'IsTruncated',\n 'limit_key' => 'MaxItems',\n 'result_key' => 'PolicyNames',\n ],\n 'ListRoles' => [\n 'input_token' => 'Marker',\n 'output_token' => 'Marker',\n 'more_results' => 'IsTruncated',\n 'limit_key' => 'MaxItems',\n 'result_key' => 'Roles',\n ],\n 'ListSAMLProviders' => [\n 'result_key' => 'SAMLProviderList',\n ],\n 'ListServerCertificates' => [\n 'input_token' => 'Marker',\n 'output_token' => 'Marker',\n 'more_results' => 'IsTruncated',\n 'limit_key' => 'MaxItems',\n 'result_key' => 'ServerCertificateMetadataList',\n ],\n 'ListSigningCertificates' => [\n 'input_token' => 'Marker',\n 'output_token' => 'Marker',\n 'more_results' => 'IsTruncated',\n 'limit_key' => 'MaxItems',\n 'result_key' => 'Certificates',\n ],\n 'ListUserPolicies' => [\n 'input_token' => 'Marker',\n 'output_token' => 'Marker',\n 'more_results' => 'IsTruncated',\n 'limit_key' => 'MaxItems',\n 'result_key' => 'PolicyNames',\n ],\n 'ListUsers' => [\n 'input_token' => 'Marker',\n 'output_token' => 'Marker',\n 'more_results' => 'IsTruncated',\n 'limit_key' => 'MaxItems',\n 'result_key' => 'Users',\n ],\n 'ListVirtualMFADevices' => [\n 'input_token' => 'Marker',\n 'output_token' => 'Marker',\n 'more_results' => 'IsTruncated',\n 'limit_key' => 'MaxItems',\n 'result_key' => 'VirtualMFADevices',\n ],\n ],\n];\n" }, { "alpha_fraction": 0.4872935116291046, "alphanum_fraction": 0.5019059777259827, "avg_line_length": 20.875, "blob_id": "e0861406071213e99c952518bebeae037bfc79f8", "content_id": "5c0b7a3d25dd3e1b54679d1aa45b0ce031438aac", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1574, "license_type": "permissive", "max_line_length": 65, "num_lines": 72, "path": "/tests/Multipart/TestUploadBuilder.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Multipart;\n\nuse Aws\\Multipart\\UploadState;\nuse Aws\\Multipart\\AbstractUploadBuilder;\n\n/**\n * Concrete UploadBuilder for the purposes of the following test.\n */\nclass TestUploadBuilder extends AbstractUploadBuilder\n{\n protected $config = [\n 'part' => [\n 'min_size' => 5242880,\n 'max_size' => 5368709120,\n 'max_num' => 10000,\n 'param' => 'PartNumber',\n ],\n 'id' => ['foo', 'bar', 'baz'],\n 'initiate' => [\n 'command' => 'CreateMultipartUpload',\n 'params' => [],\n ],\n 'upload' => [\n 'command' => 'UploadPart',\n 'params' => [],\n ],\n 'complete' => [\n 'command' => 'CompleteMultipartUpload',\n 'params' => [],\n ],\n 'abort' => [\n 'command' => 'AbortMultipartUpload',\n 'params' => [],\n ],\n ];\n\n public function __construct(array $params = [])\n {\n $this->uploadId = $params + $this->uploadId;\n }\n\n protected function loadStateByUploadId(array $params = [])\n {\n return new UploadState($params);\n }\n\n protected function prepareParams()\n {\n // No-op\n }\n\n protected function determinePartSize()\n {\n return 5;\n }\n\n protected function getCreatePartFn()\n {\n return function () {};\n }\n\n protected function getCompleteParamsFn()\n {\n return function () {};\n }\n\n protected function getResultHandlerFn()\n {\n return function () {};\n }\n}" }, { "alpha_fraction": 0.5476091504096985, "alphanum_fraction": 0.552598774433136, "avg_line_length": 27.630952835083008, "blob_id": "4e63de8290e4ea55014ea418e450d16f6dbec25d", "content_id": "a01dd5f34786493da04f7b4122937eeb1a97b487", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2405, "license_type": "permissive", "max_line_length": 83, "num_lines": 84, "path": "/tests/FutureResultTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test;\n\nuse Aws\\FutureResult;\nuse Aws\\Result;\nuse React\\Promise\\FulfilledPromise;\n\n/**\n * @covers Aws\\FutureResult\n */\nclass ResultModelTest extends \\PHPUnit_Framework_TestCase\n{\n public function testHasData()\n {\n $c = new FutureResult(new FulfilledPromise(new Result(['a' => 1])));\n $this->assertEquals(['a' => 1], $c->wait()->toArray());\n }\n\n public function testResultCanBeToArray()\n {\n $c = new FutureResult(new FulfilledPromise(new Result(['foo' => 'bar'])));\n $c->wait();\n $this->assertEquals('bar', $c['foo']);\n $this->assertEquals(1, count($c));\n }\n\n public function testResultCanBeSearched()\n {\n $c = new FutureResult(\n new FulfilledPromise(\n new Result(['foo' => ['bar' => 'baz']])\n )\n );\n $this->assertEquals('baz', $c->search('foo.bar'));\n }\n\n /**\n * @expectedException \\RuntimeException\n */\n public function testValidatesResult()\n {\n $c = new FutureResult(new FulfilledPromise('foo'));\n $c->wait();\n }\n\n public function testProxiesToUnderlyingData()\n {\n $c = new FutureResult(new FulfilledPromise(new Result(['a' => 1])));\n $this->assertEquals(1, count($c));\n $this->assertEquals(['a' => 1], $c->toArray());\n $this->assertEquals(['a' => 1], $c->getIterator()->getArrayCopy());\n $this->assertEquals(1, $c['a']);\n $this->assertEquals(1, $c->get('a'));\n $this->assertNull($c['b']);\n $this->assertTrue(isset($c['a']));\n $c['b'] = 2;\n $this->assertTrue(isset($c['b']));\n unset($c['b']);\n $this->assertFalse(isset($c['b']));\n $this->assertEquals(1, $c->getPath('a'));\n $c->setPath('foo/bar', 'baz');\n $this->assertEquals('baz', $c['foo']['bar']);\n $this->assertTrue($c->hasKey('a'));\n }\n\n /**\n * @expectedException \\RuntimeException\n */\n public function testThrowsWhenPropertyInvalid()\n {\n $c = new FutureResult(new FulfilledPromise(new Result(['a' => 1])));\n $c->notThere;\n }\n\n /**\n * @expectedException \\GuzzleHttp\\Ring\\Exception\\CancelledFutureAccessException\n */\n public function testThrowsWhenAccessingCancelledFuture()\n {\n $c = new FutureResult(new FulfilledPromise(new Result([])));\n $c->cancel();\n $c['foo'];\n }\n}\n" }, { "alpha_fraction": 0.573026716709137, "alphanum_fraction": 0.5854567885398865, "avg_line_length": 27.73214340209961, "blob_id": "8ba75de020f92d3f3caf0f4bc821e40900a78d8a", "content_id": "98520b75d5f16e265a288c63f12562335e09f954", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1609, "license_type": "permissive", "max_line_length": 79, "num_lines": 56, "path": "/src/S3/ApplyMd5Subscriber.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\S3;\n\nuse Aws\\Exception\\CouldNotCreateChecksumException;\nuse GuzzleHttp\\Command\\Event\\PreparedEvent;\nuse GuzzleHttp\\Event\\SubscriberInterface;\nuse GuzzleHttp\\Stream\\Utils;\n\n/**\n * Adds required and optional Content-MD5 headers.\n *\n * @internal\n */\nclass ApplyMd5Subscriber implements SubscriberInterface\n{\n private static $requireMd5 = [\n 'DeleteObjects',\n 'PutBucketCors',\n 'PutBucketLifecycle',\n ];\n\n private static $canMd5 = ['PutObject', 'UploadPart'];\n\n public function getEvents()\n {\n return ['prepared' => ['setMd5', 'last']];\n }\n\n public function setMd5(PreparedEvent $event)\n {\n $client = $event->getClient();\n $command = $event->getCommand();\n $body = $event->getRequest()->getBody();\n\n // If ContentMD5 is set or there is no body, there is nothing to do.\n if ($command['ContentMD5'] || !$body) {\n return;\n }\n\n // If and MD5 is required or enabled, add one.\n $optional = $client->getConfig('calculate_md5')\n && in_array($command->getName(), self::$canMd5);\n if (in_array($command->getName(), self::$requireMd5) || $optional) {\n // Throw exception is calculating and MD5 would result in an error.\n if (!$body->isSeekable()) {\n throw new CouldNotCreateChecksumException('md5');\n }\n\n // Set the Content-MD5 header.\n $event->getRequest()->setHeader(\n 'Content-MD5',\n base64_encode(Utils::hash($body, 'md5', true))\n );\n }\n }\n}\n" }, { "alpha_fraction": 0.6297070980072021, "alphanum_fraction": 0.6307531595230103, "avg_line_length": 30.866666793823242, "blob_id": "cfe1222b98f616f645e9ad457cd78a8fcfc0c179", "content_id": "7ed7167c59d1ed96c91d46eaaa6b247ab4caed32", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 956, "license_type": "permissive", "max_line_length": 71, "num_lines": 30, "path": "/tests/Sqs/QueueUrlSubscriberTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Sqs;\n\nuse Aws\\Sqs\\SqsClient;\nuse GuzzleHttp\\Command\\CommandTransaction;\nuse GuzzleHttp\\Command\\Event\\PreparedEvent;\nuse GuzzleHttp\\Message\\Request;\n\n/**\n * @covers Aws\\Sqs\\QueueUrlSubscriber\n */\nclass QueueUrlListenerTest extends \\PHPUnit_Framework_TestCase\n{\n public function testUpdatesUrl()\n {\n // Setup state of command/request\n $newUrl = 'https://queue.amazonaws.com/stuff/in/the/path';\n $client = SqsClient::factory([\n 'region' => 'us-east-1',\n 'version' => 'latest'\n ]);\n $command = $client->getCommand('ReceiveMessage');\n $command['QueueUrl'] = $newUrl;\n $ct = new CommandTransaction($client, $command);\n $ct->request = new Request('GET', 'https://sqs.amazonaws.com');\n $event = new PreparedEvent($ct);\n $command->getEmitter()->emit('prepared', $event);\n $this->assertEquals($newUrl, $ct->request->getUrl());\n }\n}\n" }, { "alpha_fraction": 0.49709975719451904, "alphanum_fraction": 0.5063804984092712, "avg_line_length": 26.80645179748535, "blob_id": "fe8504dc58de76d687d046aca7cec8440590fb40", "content_id": "5b562c2df51d4b9da5fa9a5ead18f320024b6fc2", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1724, "license_type": "permissive", "max_line_length": 88, "num_lines": 62, "path": "/tests/Integ/ConcurrencyTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Integ;\n\nuse GuzzleHttp\\Command\\Event\\ProcessEvent;\n\nclass ConcurrencyTest extends \\PHPUnit_Framework_TestCase\n{\n use IntegUtils;\n\n public function testSendsRequestsConcurrently()\n {\n $s3 = $this->getSdk()->getS3();\n\n $commands = [\n $s3->getCommand('ListBuckets'),\n $s3->getCommand('ListBuckets'),\n $s3->getCommand('ListBuckets')\n ];\n $results = [];\n $s3->executeAll($commands, [\n 'process' => function (ProcessEvent $e) use (&$results) {\n $results[] = $e->getResult();\n }\n ]);\n $this->assertCount(3, $results);\n $this->assertCount(1, array_unique(\\JmesPath\\search('[*].Owner.ID', $results)));\n }\n\n public function testSendsRequestsConcurrentlyWithPool()\n {\n $s3 = $this->getSdk()->getS3();\n\n $commands = [\n $s3->getCommand('ListBuckets'),\n $s3->getCommand('ListBuckets'),\n $s3->getCommand('ListBuckets')\n ];\n\n $resolved = false;\n $processResults = $progress = [];\n $pool = $s3->createPool($commands, [\n 'process' => function (ProcessEvent $e) use (&$processResults) {\n $processResults[] = $e->getResult();\n }\n ]);\n\n $pool->then(\n function ($result) use (&$resolved) {\n $resolved = $result;\n },\n null,\n function ($result) use (&$progress) {\n $progress[] = $result;\n }\n );\n\n $pool->wait();\n $this->assertCount(3, $processResults);\n $this->assertCount(3, $progress);\n $this->assertSame(true, $resolved);\n }\n}\n" }, { "alpha_fraction": 0.4972222149372101, "alphanum_fraction": 0.5075926184654236, "avg_line_length": 33.83871078491211, "blob_id": "a6249877b86ff24215b9d950344cf46c1cefa474", "content_id": "becf9bdd286be6920d47da59f4de8899b9f869cb", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 5400, "license_type": "permissive", "max_line_length": 101, "num_lines": 155, "path": "/tests/ResultPaginatorTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test;\n\nuse Aws\\Result;\nuse Aws\\Test\\UsesServiceTrait;\n\n/**\n * @covers Aws\\ResultPaginator\n */\nclass ResultPaginatorTest extends \\PHPUnit_Framework_TestCase\n{\n use UsesServiceTrait;\n\n /**\n * @dataProvider getPaginatorIterationData\n */\n public function testStandardIterationWorkflow(\n array $config,\n array $results,\n $expectedRequestCount,\n array $expectedTableNames\n ) {\n $requestCount = 0;\n\n // Create the client and paginator\n $client = $this->getTestClient('dynamodb');\n $this->addMockResults($client, $results);\n $paginator = $client->getPaginator('ListTables', [], $config + [\n 'process' => function () use (&$requestCount) {$requestCount++;}\n ]);\n\n // Iterate over the paginator and keep track of the keys and values\n $tableNames = [];\n $lastKey = $result = null;\n foreach ($paginator as $key => $result) {\n $tableNames = array_merge($tableNames, $result['TableNames']);\n $lastKey = $key;\n }\n\n // Make sure the paginator yields the expected results\n $this->assertInstanceOf('Aws\\\\Result', $result);\n $this->assertEquals($expectedRequestCount, $requestCount);\n $this->assertEquals($expectedRequestCount - 1, $lastKey);\n $this->assertEquals($expectedTableNames, $tableNames);\n }\n\n public function testNonIterator()\n {\n // Get test data\n $config = $this->getPaginatorIterationData()[0][0];\n $results = $this->getPaginatorIterationData()[0][1];\n\n // Create the client and paginator\n $client = $this->getTestClient('dynamodb');\n $this->addMockResults($client, $results);\n $paginator = $client->getPaginator('ListTables', [], $config);\n $paginator->next();\n $this->assertEquals(['test1', 'test2'], $paginator->current()['TableNames']);\n $this->assertEquals('test2', $this->readAttribute($paginator, 'nextToken'));\n $paginator->next();\n $this->assertEquals([], $paginator->current()['TableNames']);\n $this->assertEquals('test2', $this->readAttribute($paginator, 'nextToken'));\n $paginator->next();\n $this->assertEquals(['test3'], $paginator->current()['TableNames']);\n $this->assertNull($this->readAttribute($paginator, 'nextToken'));\n }\n\n /**\n * @return array Test data\n */\n public function getPaginatorIterationData()\n {\n return [\n // Single field token case\n [\n // Config\n ['input_token' => 'NextToken', 'output_token' => 'LastToken'],\n // Results\n [\n new Result(['LastToken' => 'test2', 'TableNames' => ['test1', 'test2']]),\n new Result(['LastToken' => 'test2', 'TableNames' => []]),\n new Result(['TableNames' => ['test3']]),\n ],\n // Request count\n 3,\n // Table names\n ['test1', 'test2', 'test3'],\n ],\n [\n // Config\n ['input_token' => ['NT1', 'NT2'], 'output_token' => ['LT1', 'LT2']],\n // Results\n [\n new Result(['LT1' => 'foo', 'LT2' => 'bar', 'TableNames' => ['test1', 'test2']]),\n new Result(['LT1' => 'foo', 'LT2' => 'bar', 'TableNames' => []]),\n new Result(['TableNames' => ['test3']]),\n ],\n // Request count\n 3,\n // Table names\n ['test1', 'test2', 'test3'],\n ]\n ];\n }\n\n public function testCanSearchOverResultsUsingFlatMap()\n {\n $requestCount = 0;\n $client = $this->getTestClient('dynamodb');\n $this->addMockResults($client, [\n new Result(['LastToken' => 'b2', 'TableNames' => ['a1', 'b2']]),\n new Result(['LastToken' => 'b2', 'TableNames' => []]),\n new Result(['TableNames' => ['c3']]),\n new Result(['TableNames' => ['d4']]),\n ]);\n\n $paginator = $client->getPaginator('ListTables', [], [\n 'input_token' => 'NextToken',\n 'output_token' => 'LastToken',\n 'process' => function () use (&$requestCount) {\n $requestCount++;\n }\n ]);\n\n $tableNames = [];\n foreach ($paginator->search('TableNames[][::-1]', 3) as $table) {\n $tableNames[] = $table;\n }\n\n $this->assertEquals(3, $requestCount);\n $this->assertEquals(['1a', '2b', '3c'], $tableNames);\n }\n\n public function testGracefullyHandlesSingleValueResults()\n {\n $client = $this->getTestClient('dynamodb');\n $this->addMockResults($client, [\n new Result(['LastToken' => 'b2', 'TableNames' => ['a1', 'b2']]),\n new Result(['LastToken' => 'b2', 'TableNames' => []]),\n new Result(['TableNames' => ['c3']]),\n ]);\n\n $paginator = $client->getPaginator('ListTables', [], [\n 'input_token' => 'NextToken',\n 'output_token' => 'LastToken'\n ]);\n\n $tableNames = [];\n foreach ($paginator->search('TableNames[0]') as $table) {\n $tableNames[] = $table;\n }\n\n $this->assertEquals(['a1', 'c3'], $tableNames);\n }\n}\n" }, { "alpha_fraction": 0.5591915249824524, "alphanum_fraction": 0.5640038251876831, "avg_line_length": 26.342105865478516, "blob_id": "6b911712692e4f76578141199a2c08ac5b66d37c", "content_id": "54b26259f93aa49a0b5e6aefe008824af7c9e341", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1039, "license_type": "permissive", "max_line_length": 78, "num_lines": 38, "path": "/src/Sqs/Md5ValidatorSubscriber.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Sqs;\n\nuse Aws\\Sqs\\Exception\\SqsException;\nuse GuzzleHttp\\Command\\Event\\ProcessEvent;\nuse GuzzleHttp\\Event\\RequestEvents;\nuse GuzzleHttp\\Event\\SubscriberInterface;\n\n/**\n * Listener used to validate the MD5 of the ReceiveMessage body.\n */\nclass Md5ValidatorSubscriber implements SubscriberInterface\n{\n public function getEvents()\n {\n return ['process' => ['onProcess', RequestEvents::LATE]];\n }\n\n public function onProcess(ProcessEvent $event)\n {\n if ($event->getCommand()->getName() !== 'ReceiveMessage') {\n return;\n }\n\n $result = $event->getResult();\n\n if (isset($result['Messages'])) {\n foreach ($result['Messages'] as $message) {\n if ($message['MD5OfBody'] != md5($message['Body'])) {\n throw new SqsException(\n 'Body MD5 mismatch for ' . var_export($message, true),\n $event->getTransaction()\n );\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5850999355316162, "alphanum_fraction": 0.6093276739120483, "avg_line_length": 25.629032135009766, "blob_id": "1eae5ea8bd07add76748dffc21971907e6b8fae3", "content_id": "f631fa090f80f6bc66813bcf5021673251f0b4c8", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1651, "license_type": "permissive", "max_line_length": 65, "num_lines": 62, "path": "/tests/Retry/Crc32FilterTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Retry;\n\nuse Aws\\Retry\\Crc32Filter;\nuse GuzzleHttp\\Transaction;\nuse GuzzleHttp\\Client;\nuse GuzzleHttp\\Event\\CompleteEvent;\nuse GuzzleHttp\\Message\\Request;\nuse GuzzleHttp\\Message\\Response;\nuse GuzzleHttp\\Subscriber\\Retry\\RetrySubscriber;\nuse GuzzleHttp\\Stream\\Stream;\n\n/**\n * @covers \\Aws\\Retry\\Crc32Filter\n */\nclass Crc32FilterTest extends \\PHPUnit_Framework_TestCase\n{\n public function testIngoresWhenNoResponseIsPresent()\n {\n $ate = $this->getTrans();\n $c = new Crc32Filter();\n $this->assertEquals(RetrySubscriber::DEFER, $c(2, $ate));\n }\n\n public function testIgnoresWhenNoHeaderIsPresent()\n {\n $ate = $this->getTrans();\n $ate->intercept(new Response(200));\n $c = new Crc32Filter();\n $this->assertEquals(RetrySubscriber::DEFER, $c(2, $ate));\n }\n\n public function testRetriesWhenCrc32Fails()\n {\n $ate = $this->getTrans();\n $ate->intercept(new Response(200, [\n 'x-amz-crc32' => '123'\n ], Stream::factory('foo')));\n\n $c = new Crc32Filter();\n $this->assertEquals(RetrySubscriber::RETRY, $c(2, $ate));\n }\n\n public function testDefersWhenCrc32Matches()\n {\n $ate = $this->getTrans();\n $ate->intercept(new Response(200, [\n 'x-amz-crc32' => crc32('foo')\n ], Stream::factory('foo')));\n\n $c = new Crc32Filter();\n $this->assertEquals(RetrySubscriber::DEFER, $c(2, $ate));\n }\n\n private function getTrans()\n {\n return new CompleteEvent(new Transaction(\n new Client(),\n new Request('GET', 'http://foo.com')\n ));\n }\n}\n" }, { "alpha_fraction": 0.6402943730354309, "alphanum_fraction": 0.6412143707275391, "avg_line_length": 29.19444465637207, "blob_id": "9f26cf15e5acf8d8ecb19b521eb6d981e53ec4c8", "content_id": "58cb85fda59eeef39379f30afbd89673f809682f", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1087, "license_type": "permissive", "max_line_length": 79, "num_lines": 36, "path": "/src/CloudSearch/CloudSearchClient.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\CloudSearch;\n\nuse Aws\\AwsClient;\nuse Aws\\CloudSearchDomain\\CloudSearchDomainClient;\n\n/**\n * This client is used to interact with the **Amazon CloudSearch** service.\n */\nclass CloudSearchClient extends AwsClient\n{\n /**\n * Create a CloudSearchDomainClient for a particular domain to do searching\n * and document uploads.\n *\n * @param string $domainName Name of the CloudSearch domain.\n * @param array $config Config options for the CloudSearchDomainClient\n *\n * @return CloudSearchDomainClient\n */\n public function getDomainClient($domainName, array $config = [])\n {\n $config['endpoint'] = $this->describeDomains([\n 'DomainNames' => [$domainName]\n ])->getPath('DomainStatusList/0/SearchService/Endpoint');\n\n if (!isset($config['scheme'])) {\n $config['scheme'] = 'https';\n }\n\n // Create an absolute URI for the endpoint.\n $config['endpoint'] = $config['scheme'] . '://' . $config['endpoint'];\n\n return CloudSearchDomainClient::factory($config);\n }\n}\n" }, { "alpha_fraction": 0.5275903940200806, "alphanum_fraction": 0.5345095992088318, "avg_line_length": 33.41071319580078, "blob_id": "a9fe3f92235ac181743986bffc0b162d74384f44", "content_id": "efd2650ee14a76ab06a83f9b4ded209e2bd82ed5", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 5781, "license_type": "permissive", "max_line_length": 122, "num_lines": 168, "path": "/tests/DynamoDb/WriteRequestBatchTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\DynamoDb;\n\nuse Aws\\Result;\nuse Aws\\DynamoDb\\WriteRequestBatch;\nuse Aws\\Test\\UsesServiceTrait;\nuse GuzzleHttp\\Message\\Response;\nuse GuzzleHttp\\Stream\\Stream;\n\n/**\n * @covers Aws\\DynamoDb\\WriteRequestBatch\n */\nclass WriteRequestBatchTest extends \\PHPUnit_Framework_TestCase\n{\n use UsesServiceTrait;\n\n public function testInstantiateWriteRequestBatch()\n {\n // Ensure threshold is correctly calculated\n $batch = new WriteRequestBatch($this->getMockClient(), ['pool_size' => 2]);\n $this->assertEquals(\n 50,\n $this->readAttribute($batch, 'config')['threshold']\n );\n\n // Ensure exception is thrown if batch size is invalid\n $this->setExpectedException('DomainException');\n $batch = new WriteRequestBatch($this->getMockClient(), ['batch_size' => 1]);\n }\n\n public function testAddItems()\n {\n $batch = new WriteRequestBatch($this->getMockClient(), [\n 'autoflush' => false,\n 'table' => 'foo',\n ]);\n $batch->put(['a' => 'b']);\n $batch->delete(['c' => 'd'], 'bar');\n\n $this->assertEquals(\n [\n [\n 'table' => 'foo',\n 'data' => ['PutRequest' => ['Item' => ['a' => 'b']]],\n ],\n [\n 'table' => 'bar',\n 'data' => ['DeleteRequest' => ['Key' => ['c' => 'd']]],\n ]\n ],\n $this->readAttribute($batch, 'queue')\n );\n }\n\n public function testMustProvideTable()\n {\n $batch = new WriteRequestBatch($this->getMockClient());\n\n $this->setExpectedException('RuntimeException');\n $batch->put(['a' => 'b']);\n }\n\n public function testCreateCommandsFromQueueViaAutoflush()\n {\n $commandCount = 0;\n $flushCount = 0;\n\n // Setup client to not actually execute any commands, just keep track\n // of how many commands are created.\n $client = $this->getMockClient();\n $client->expects($this->any())\n ->method('executeAll')\n ->willReturnCallback(function($commands) use (&$commandCount) {\n $commandCount = count($commands);\n });\n\n // Configure batch such so autoflush will happen for every 4 items.\n // The flush callback will keep track of how many flushed happen.\n $batch = new WriteRequestBatch($client, [\n 'batch_size' => 2,\n 'pool_size' => 2,\n 'table' => 'foo',\n 'flush' => function() use (&$flushCount) {$flushCount++;}\n ]);\n\n // Adding 5 items (Note: only 4 should be flushed)\n $batch->put(['letter' => ['S' => 'a']]);\n $batch->put(['letter' => ['S' => 'b']]);\n $batch->put(['letter' => ['S' => 'c']]);\n $batch->put(['letter' => ['S' => 'd']]);\n $batch->put(['letter' => ['S' => 'e']]);\n\n // Ensure that 2 commands and 1 flush happened, with 1 left in queue.\n $this->assertEquals(2, $commandCount);\n $this->assertEquals(1, $flushCount);\n $this->assertCount(1, $this->readAttribute($batch, 'queue'));\n }\n\n public function testUnprocessedItemsAreRequeued()\n {\n // Setup client with successful (200) responses, but the first one will\n // return UnprocessedItems\n $client = $this->getTestClient('dynamodb');\n $this->addMockResults($client, [\n new Result(['UnprocessedItems' => ['foo' => [\n ['PutRequest' => ['Item' => ['id' => ['S' => 'b']]]],\n ]]]),\n new Result([])\n ]);\n\n $batch = new WriteRequestBatch($client, ['table' => 'foo']);\n\n $batch->put(['id' => ['S' => 'a']]);\n $batch->put(['id' => ['S' => 'b']]);\n $batch->flush();\n\n $this->assertCount(0, $this->readAttribute($batch, 'queue'));\n }\n\n public function testErrorsAreHandled()\n {\n $unhandledErrors = 0;\n\n // Setup client with 3 error responses. The first should cause the items\n // to be re-queued; then second and third should trigger the callback.\n $client = $this->getTestClient('dynamodb');\n $this->addMockResponses($client, [\n new Response(400, [], Stream::factory('{\"__type\":\"ProvisionedThroughputExceededException\",\"message\":\"foo\"}')),\n new Response(400, [], Stream::factory('{\"__type\":\"ValidationError\",\"message\":\"foo\"}')),\n new Response(413),\n ]);\n\n $batch = new WriteRequestBatch($client, [\n 'table' => 'foo',\n 'error' => function($e) use (&$unhandledErrors) {\n $unhandledErrors++;\n }\n ]);\n\n $batch->put(['id' => ['S' => 'a']]);\n $batch->put(['id' => ['S' => 'b']]);\n\n // There should be two items in the queue before we flush.\n $this->assertCount(2, $this->readAttribute($batch, 'queue'));\n\n $batch->flush(false);\n\n // The 1st response should be a ProvisionedThroughputExceededException,\n // which means the items should be re-queued, keeping the count at 2.\n $this->assertCount(2, $this->readAttribute($batch, 'queue'));\n\n $batch->flush();\n $batch->put(['id' => ['S' => 'c']]);\n $batch->flush();\n\n // After 2 complete flushes, the queue should be empty, and there should\n // been 2 unhandled errors that would have triggered the callback.\n $this->assertCount(0, $this->readAttribute($batch, 'queue'));\n $this->assertEquals(2, $unhandledErrors);\n }\n\n private function getMockClient()\n {\n return $this->getMockBuilder('Aws\\DynamoDb\\DynamoDbClient')\n ->disableOriginalConstructor()\n ->getMock();\n }\n}\n" }, { "alpha_fraction": 0.6196808218955994, "alphanum_fraction": 0.623670220375061, "avg_line_length": 27.923076629638672, "blob_id": "b2b6cd74df49afec081653a9f9dc456ba0becccf", "content_id": "0735aa2f89f363defa0b28ec8d753b3f97476124", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 752, "license_type": "permissive", "max_line_length": 70, "num_lines": 26, "path": "/tests/Integ/UseStreamTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Integ;\n\nuse GuzzleHttp\\Client;\nuse GuzzleHttp\\Ring\\Client\\StreamHandler;\n\nclass UseStreamTest extends \\PHPUnit_Framework_TestCase\n{\n use IntegUtils;\n\n public function testCanUseStreamForGet()\n {\n $client = new Client(['adapter' => new StreamHandler()]);\n $s3 = $this->getSdk()->getS3(['client' => $client]);\n $result = $s3->listBuckets();\n $this->assertNotEmpty($result->search('Owner.ID'));\n }\n\n public function testCanUseStreamForPut()\n {\n $client = new Client(['adapter' => new StreamHandler()]);\n $ddb = $this->getSdk()->createDynamoDb(['client' => $client]);\n $result = $ddb->listTables();\n $this->assertArrayHasKey('TableNames', $result);\n }\n}\n" }, { "alpha_fraction": 0.5066666603088379, "alphanum_fraction": 0.5081704258918762, "avg_line_length": 40.21900939941406, "blob_id": "d152d118babde79ebc7ca9c102b2353f163473b3", "content_id": "685fc422f7c51154ec11147b02cf196d9972e8c8", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 9975, "license_type": "permissive", "max_line_length": 121, "num_lines": 242, "path": "/build/docs/classes/DocsBuilder.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Build\\Docs;\n\nuse Aws\\Common\\Api\\FilesystemApiProvider;\nuse Aws\\Common\\Api\\Operation;\nuse Aws\\Common\\Api\\Service as Api;\n\nclass DocsBuilder\n{\n /** @var string */\n private $themeSource;\n\n /** @var string */\n private $apiModelsDir;\n\n /** @var string */\n private $outputDir;\n\n public function __construct($apiModelsDir, $outputDir)\n {\n $this->apiModelsDir = $apiModelsDir;\n $this->outputDir = $outputDir;\n $this->themeSource = realpath(__DIR__ . '/../theme');\n }\n\n public function getSami($sourceDir)\n {\n $this->generateTheme();\n\n if (!class_exists($sami = '\\Sami\\Sami')) {\n throw new \\RuntimeException('Sami class is not available. Are you sure you are using Sami right now?');\n }\n\n return new $sami($sourceDir, [\n 'title' => 'AWS SDK for PHP',\n 'theme' => 'aws',\n 'template_dirs' => [\"{$this->outputDir}/theme\"],\n 'build_dir' => \"{$this->outputDir}/build\",\n 'cache_dir' => \"{$this->outputDir}/cache\",\n 'default_opened_level' => 1,\n ]);\n }\n\n private function generateTheme()\n {\n // Create API pages, manifest, and sami.js twigs. Copy static artifacts.\n $services = [];\n $manifest = '';\n $indexes = '';\n\n foreach (glob($this->apiModelsDir . '/*.api.php') as $file) {\n $file = basename($file, '.api.php');\n if (preg_match('/([a-z0-9-]+?)-([0-9-]+)/', $file, $matches)) {\n list(/*skip*/, $name, $version) = $matches;\n $apiProvider = new FilesystemApiProvider($this->apiModelsDir);\n $service = new Service(\n $name,\n new Api($apiProvider, $name, $version),\n new DocModel($this->apiModelsDir, $name, $version)\n );\n\n $indexes .= $this->createIndexEntryForService($service);\n\n $html = (new HtmlDocument)->open('section', 'Operations');\n $html->append($this->createHtmlForToc($service->api->getOperations()));\n foreach ($service->api->getOperations() as $opName => $operation) {\n $indexes .= $this->createIndexEntryForOperation($service, $opName);\n $html->append($this->createHtmlForOperation($service, $opName, $operation));\n }\n $html->close();\n $this->writeServiceApiPage($service, $html);\n\n $manifest .= \" '{$service->slug}.twig': '{$service->serviceLink}'\\n\";\n\n if (!isset($services[$service->title])) $services[$service->title] = [];\n $services[$service->title][$version] = $service;\n }\n }\n $this->writeThemeFile('manifest.yml', [':manifest' => $manifest]);\n $this->writeThemeFile('sami.js.twig', [':indexes' => $indexes]);\n $this->writeThemeFile('layout/layout.twig');\n $this->writeThemeFile('img/service-sprites.png');\n\n // Create index and class twigs.\n ksort($services, SORT_NATURAL | SORT_FLAG_CASE);\n $servicesTable = '';\n $classBlocks = '';\n foreach ($services as $versions) {\n krsort($versions);\n $service = reset($versions);\n $servicesTable .= \"<tr><td><a href=\\\"{$service->serviceLink}\\\">{$service->title}</a></td>\";\n $servicesTable .= \"<td><a href=\\\"{$service->clientLink}\\\">{$service->client}</a></td>\";\n $servicesTable .= \"<td><ul class=\\\"list-unstyled\\\">\";\n $classBlocks .= \"\\t{% elseif class.shortname == '{$service->clientName}' %}\\n\\t\\t{% set apiLinks = '\";\n $latest = count($versions) > 1 ? ' (latest)' : '';\n foreach ($versions as $sv) {\n $servicesTable .= \"<li><a href=\\\"{$sv->serviceLink}\\\">{$sv->version} {$latest}</a></li>\";\n $classBlocks .= \"<li><a href=\\\"{$sv->slug}.html\\\">{$sv->shortTitle} &ndash; {$sv->version} API</a></li>\";\n $latest = '';\n }\n $classBlocks .= \"' %}\\n\\t\\t{{ block('client_heading') }}\\n\";\n $servicesTable .= \"</ul></td></tr>\";\n }\n $this->writeThemeFile('index.twig', [':services' => $servicesTable]);\n $this->writeThemeFile('class.twig', [':services' => $classBlocks]);\n }\n\n private function createIndexEntryForService(Service $service)\n {\n return json_encode([\n 'type' => 'Service',\n 'fromName' => $service->client,\n 'fromLink' => $service->clientLink,\n 'link' => $service->serviceLink,\n 'name' => $service->fullTitle,\n 'doc' => \"API documentation for the {$service->version} version of the {$service->title} service.\",\n ]) . \",\\n\";\n }\n\n private function createIndexEntryForOperation(Service $service, $operation)\n {\n return json_encode([\n 'type' => 'Operation',\n 'fromName' => $service->client,\n 'fromLink' => $service->clientLink,\n 'link' => $service->serviceLink . '#' . strtolower($operation),\n 'name' => \"{$service->namespace}Client::\" . lcfirst($operation) . \" ({$service->version})\",\n 'doc' => \"API documentation for the {$operation} operation called using the {$service->client}.\",\n ]) . \",\\n\";\n }\n\n private function createHtmlForToc(array $operations)\n {\n $html = (new HtmlDocument)->open('div', 'toc list-group');\n foreach ($operations as $opName => $operation) {\n $item = '<strong>' . $html->glyph('cog') . ' '\n . '<a href=\"#' . $html->slug($opName) . '\">' . \"{$opName}</a></strong> &mdash; \"\n . '<a href=\"#' . $html->slug($opName . '-parameters') . '\">Parameters</a> | '\n . '<a href=\"#' . $html->slug($opName . '-results') . '\">Results</a> | '\n . '<a href=\"#' . $html->slug($opName . '-errors') . '\">Errors</a>';\n $html->elem('div', 'list-group-item', $item);\n }\n $html->close();\n\n return $html;\n }\n\n private function createHtmlForOperation(Service $service, $name, Operation $operation)\n {\n $html = new HtmlDocument;\n\n // Name\n $html->section(2, $html->glyph('cog') . ' ' . $name, null, 'operation');\n\n // Code\n $html->elem('pre', 'opcode', '$result = $client-&gt;<code>' . lcfirst($name) . '</code>([...]);');\n\n // Description\n if ($description = $service->docs->getOperationDocs($name)) {\n $html->elem('div', 'well', $description);\n }\n\n // Parameters\n $inputShapes = new ShapeIterator($operation->getInput(), $service->docs);\n $inputExample = new ExampleBuilder($name);\n $inputDocs = new ThemeBuilder($name);\n foreach ($inputShapes as $shape) {\n $inputExample->addShape($shape);\n $inputDocs->addShape($shape);\n }\n $html->section(3, 'Parameters', $name)\n ->elem('h5', null, 'Formatting Example')\n ->elem('pre', null, htmlentities($inputExample->getCode()))\n ->elem('h5', null, 'Parameter Details')\n ->open('ul')->append($inputDocs->getHtml())->close()\n ->close();\n\n // Results\n $html->section(3, 'Results', $name);\n if (count($operation->getOutput()->getMembers())) {\n $outputShapes = new ShapeIterator($operation->getOutput(), $service->docs);\n $outputExample = new ExampleBuilder($name, false);\n $outputDocs = new ThemeBuilder($name, false);\n foreach ($outputShapes as $shape) {\n $outputExample->addShape($shape);\n $outputDocs->addShape($shape);\n }\n $html->elem('h5', null, 'Formatting Example')\n ->elem('pre', null, htmlentities($outputExample->getCode()))\n ->elem('h5', null, 'Results Details')\n ->open('ul')->append($outputDocs->getHtml())->close();\n } else {\n $html->elem('div', 'alert alert-info', 'The results for this operation are always empty.');\n }\n $html->close();\n\n // Errors\n $html->section(3, 'Errors', $name);\n if ($errors = $operation->getErrors()) {\n foreach ($errors as $error) {\n $html->open('div', 'panel panel-default')\n ->open('div', 'panel-heading')->elem('h5', 'panel-title', $error['name'])->close()\n ->elem('div', 'panel-body', $service->docs->getErrorDocs($error->getName())\n ?: 'This error does not currently have a description.')\n ->close();\n }\n } else {\n $html->elem('p', null, 'There are no errors described for this operation.');\n }\n $html->close();\n\n return $html->close();\n }\n\n private function writeServiceApiPage(Service $service, HtmlDocument $html)\n {\n $this->writeThemeFile(['api.twig', \"{$service->slug}.twig\"], [\n ':service' => $service->title,\n ':namespace' => $service->namespace,\n ':version' => $service->version,\n ':slug' => \"'service:{$service->slug}'\",\n ':content' => $html->render(),\n ]);\n }\n\n private function writeThemeFile($name, array $data = null)\n {\n if (is_array($name)) {\n list($in, $out) = $name;\n } else {\n $in = $out = $name;\n }\n\n fwrite(STDOUT, \"Writing theme file: {$out}.\\n\");\n if ($data) {\n $content = strtr(file_get_contents(\"{$this->themeSource}/{$in}\"), $data);\n return (bool) file_put_contents(\"{$this->outputDir}/theme/{$out}\", $content);\n } else {\n return copy(\"{$this->themeSource}/{$in}\", \"{$this->outputDir}/theme/{$out}\");\n }\n }\n}\n" }, { "alpha_fraction": 0.5150914192199707, "alphanum_fraction": 0.516853928565979, "avg_line_length": 27.727848052978516, "blob_id": "6b2ee791b90774b06f7037b37deedcfd6fd1cf13", "content_id": "93a77458b559da6766af86db875185ab530f74d0", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4539, "license_type": "permissive", "max_line_length": 80, "num_lines": 158, "path": "/tests/UsesServiceTrait.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test;\n\nuse Aws\\AwsClientInterface;\nuse Aws\\Result;\nuse Aws\\Sdk;\nuse Aws\\Api\\Service;\nuse GuzzleHttp\\Ring\\Client\\MockHandler;\nuse GuzzleHttp\\Command\\CommandTransaction;\nuse GuzzleHttp\\Command\\Event\\PreparedEvent;\nuse GuzzleHttp\\Command\\Exception\\CommandException;\nuse GuzzleHttp\\Message\\Response;\nuse GuzzleHttp\\Subscriber\\Mock;\n\n/**\n * @internal\n */\ntrait UsesServiceTrait\n{\n /**\n * Creates an instance of the AWS SDK for a test\n *\n * @param array $args\n *\n * @return Sdk\n */\n private function getTestSdk(array $args = [])\n {\n return new Sdk($args + [\n 'region' => 'us-east-1',\n 'version' => 'latest',\n 'retries' => 0\n ]);\n }\n\n /**\n * Creates an instance of a service client for a test\n *\n * @param string $service\n * @param array $args\n *\n * @return AwsClientInterface\n */\n private function getTestClient($service, array $args = [])\n {\n // Disable network access. If the INTEGRATION envvar is set, then this\n // disabling is not done.\n if (!isset($_SERVER['INTEGRATION'])\n && !isset($args['client'])\n && !isset($args['ringphp_handler'])\n ) {\n $args['ringphp_handler'] = new MockHandler(function () {\n return ['error' => new \\RuntimeException('No network access')];\n });\n }\n\n return $this->getTestSdk()->createClient($service, $args);\n }\n\n /**\n * Queues up mock Result objects for a client\n *\n * @param AwsClientInterface $client\n * @param Result[]|array[] $results\n *\n * @return AwsClientInterface\n */\n private function addMockResults(AwsClientInterface $client, array $results)\n {\n $client->getEmitter()->on('prepared',\n function (PreparedEvent $event) use (&$results) {\n $result = array_shift($results);\n if (is_array($result)) {\n $event->intercept(new Result($result));\n $event->getTransaction()->response = new Response(200);\n } elseif ($result instanceof Result) {\n $event->intercept($result);\n $event->getTransaction()->response = new Response(200);\n } elseif ($result instanceof CommandException) {\n throw $result;\n } else {\n throw new \\Exception('There are no more mock results left. '\n . 'This client executed more commands than expected.');\n }\n },\n 'last'\n );\n\n return $client;\n }\n\n /**\n * Queues up mock HTTP Response objects for a client\n *\n * @param AwsClientInterface $client\n * @param Response[] $responses\n * @param bool $readBodies\n *\n * @return AwsClientInterface\n * @throws \\InvalidArgumentException\n */\n private function addMockResponses(\n $client,\n array $responses,\n $readBodies = true\n ) {\n $mock = new Mock($responses, $readBodies);\n $client->getHttpClient()->getEmitter()->attach($mock);\n\n return $client;\n }\n\n /**\n * Creates a mock CommandException with a given error code\n *\n * @param string $code\n * @param string $type\n * @param string|null $message\n *\n * @return CommandException\n */\n private function createMockAwsException(\n $code = null,\n $type = null,\n $message = null\n ) {\n $code = $code ?: 'ERROR';\n $type = $type ?: 'Aws\\Exception\\AwsException';\n\n $client = $this->getMockBuilder('Aws\\AwsClientInterface')\n ->setMethods(['getApi'])\n ->getMockForAbstractClass();\n\n $client->expects($this->any())\n ->method('getApi')\n ->will($this->returnValue(\n new Service(\n function () {\n return ['metadata' => ['endpointPrefix' => 'foo']];\n },\n 'service',\n 'version'\n )));\n\n $trans = new CommandTransaction(\n $client,\n $this->getMock('GuzzleHttp\\Command\\CommandInterface'),\n [\n 'aws_error' => [\n 'message' => $message ?: 'Test error',\n 'code' => $code\n ]\n ]\n );\n\n return new $type($message ?: 'Test error', $trans);\n }\n}\n" }, { "alpha_fraction": 0.6717527508735657, "alphanum_fraction": 0.6762519478797913, "avg_line_length": 32.411766052246094, "blob_id": "288fda02f53c5d9ec540d7ea748a3ee0eb55de91", "content_id": "f83f7e1c9d54a5efbb2c2ab1e5bb139f12a6bfc4", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 5116, "license_type": "permissive", "max_line_length": 82, "num_lines": 153, "path": "/docs/commands.rst", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "===============\nCommand Objects\n===============\n\nCommand objects are useful for performing :ref:`performing operations\nconcurrently <concurrent_commands>`, using the command event system, and\nsending asynchronous requests.\n\n\nTypical SDK usage\n-----------------\n\n.. include:: _snippets/performing-operations.txt\n\n\nA peek under the hood\n---------------------\n\nIf you examine a client class, you will see that the methods corresponding to\nthe operations do not actually exist. They are implemented using the\n``__call()`` magic method behavior. These pseudo-methods are actually shortcuts\nthat encapsulate the SDK's — and the underlying Guzzle library's — use of\ncommand objects.\n\nFor example, you could perform the same ``DescribeTable`` operation from the\npreceding section using command objects:\n\n.. code-block:: php\n\n $command = $dynamoDbClient->getCommand('DescribeTable', [\n 'TableName' => 'YourTableName',\n ]);\n\n $result = $dynamoDbClient->execute($command);\n\nA **Command** is an object that represents the execution of a service\noperation. Command objects are an abstraction of the process of formatting a\nrequest to a service, executing the request, receiving the response, and\nformatting the results. Commands are created and executed by the client and\ncontain references to **Request** and **Response** objects.\n\n\nUsing command objects\n---------------------\n\nUsing the magic-methods for performing operations is preferred for typical use\ncases, but command objects provide greater flexibility and access to additional\ndata.\n\n\nManipulating command objects before execution\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nWhen you create a command using a client's ``getCommand()`` method, it does not\nimmediately execute. Because commands are lazily executed, it is possible to\npass the command object around and add or modify the parameters. The following\nexamples show how to work with command objects:\n\n.. code-block:: php\n\n // You can add parameters after instantiation\n $command = $s3Client->getCommand('ListObjects');\n $command[MaxKeys'] = 50;\n $command['Prefix'] = 'foo/baz/';\n $result = $s3Client->execute($command);\n\n // You can also modify parameters\n $command = $s3Client->getCommand('ListObjects', [\n 'MaxKeys' => 50,\n 'Prefix' => 'foo/baz/',\n ]);\n $command['MaxKeys'] = 100;\n $result = $s3Client->execute($command);\n\nTake a look at the `API docs for commands\n<http://docs.aws.amazon.com/aws-sdk-php/v3/api/GuzzleHttp/Command/Command.html>`_.\nfor more information on the PHP API.\n\n\n.. _concurrent_commands:\n\nExecuting commands concurrently\n-------------------------------\n\nYou can send commands concurrently using the asynchronous features of Guzzle.\nSetting the ``@future`` option of a command to true will create a futue result\nobject that is completed asynchronously. This allows you to create multiple\nfutures and have them send HTTP request concurrently when the underlying HTTP\nhandler transfers the requests.\n\n.. code-block:: php\n\n use Aws\\S3\\Exception\\S3Exception;\n\n // Create a future result. This call returns almost immediately.\n $futureResult = $s3Client->listBuckets(['@future' => true]);\n\n // Do other stuff...\n // ...\n\n // Block until the result is ready.\n try {\n $result = $futureResult->wait();\n } catch (S3Exception $e) {\n echo $e->getMessage();\n }\n\nWhen a future result is used in a blocking manner (whether by accessing the\nresult as a normal result object or explicitly calling the ``wait()`` method),\nthe result will complete and an exception could be raised if an error was\nencountered while completing the request.\n\nWhen using the SDK with an event loop library, you will not want to block on\nresults, but rather use the ``then()`` method of a result to access a promise\nthat is resolved or rejected when the operation completes.\n\n.. code-block:: php\n\n $futureResult = $s3Client->listBuckets(['@future' => true]);\n $futureResult->then(\n function ($result) {\n echo 'Got a result: ' . var_export($result, true);\n },\n function ($error) {\n echo 'Got an error: ' . $error->getMessage();\n }\n );\n\nIf you want to send a large number of requests concurrently and wait until all\nof the requests have completed, then you should use the ``executeAll`` method\nof a client. The ``executeAll`` method takes an iterator or array that contains\ncommand object and sends them concurrently using a fixed pool size. As commands\ncomplete, more are added to the pool of requests.\n\n.. code-block:: php\n\n use GuzzleHttp\\Command\\Event\\ProcessEvent;\n\n $generator = function ($total) use ($s3Client) {\n while ($i-- > 0) {\n yield $s3Client->getCommand('ListBuckets');\n }\n };\n\n $s3Client->executeAll($generator(10), [\n 'process' => function (ProcessEvent $e) {\n if ($e->getException()) {\n echo 'Got error: ' . $e->getException()->getMessage();\n } else {\n echo 'Got result: ' . var_export($e->getResult(), true);\n }\n }\n ]);\n" }, { "alpha_fraction": 0.45950156450271606, "alphanum_fraction": 0.46053996682167053, "avg_line_length": 30.57377052307129, "blob_id": "cf1bdf484c1d5a71899b744861f7d946c321226e", "content_id": "d0d10cd4fdd0495bf529f3e4f4e87529632f1084", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1926, "license_type": "permissive", "max_line_length": 87, "num_lines": 61, "path": "/tests/Api/Serializer/QuerySerializerTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Api\\Serializer;\n\nuse Aws\\Api\\Serializer\\QuerySerializer;\nuse Aws\\Api\\Service;\nuse GuzzleHttp\\Command\\Command;\nuse Aws\\Test\\UsesServiceTrait;\nuse GuzzleHttp\\Client;\nuse GuzzleHttp\\Command\\CommandTransaction;\n\n/**\n * @covers Aws\\Api\\Serializer\\QuerySerializer\n */\nclass QuerySerializerTest extends \\PHPUnit_Framework_TestCase\n{\n use UsesServiceTrait;\n\n public function testSerializesEmptyLists()\n {\n $service = new Service(function () {\n return [\n 'metadata'=> ['protocol' => 'query', 'apiVersion' => '1'],\n 'operations' => [\n 'foo' => [\n 'http' => ['httpMethod' => 'POST'],\n 'input' => [\n 'type' => 'structure',\n 'members' => [\n 'baz' => [\n 'type' => 'list',\n 'member' => ['type' => 'string']\n ]\n ]\n ]\n ]\n ]\n ];\n }, 'service', 'region');\n\n $http = new Client();\n\n $aws = $this->getMockBuilder('Aws\\AwsClient')\n ->setMethods(['getHttpClient'])\n ->disableOriginalConstructor()\n ->getMock();\n\n $aws->expects($this->once())\n ->method('getHttpClient')\n ->will($this->returnValue($http));\n\n $q = new QuerySerializer($service, 'http://foo.com');\n $trans = new CommandTransaction(\n $aws,\n new Command('foo', ['baz' => []])\n );\n $request = $q($trans);\n $this->assertEquals('POST', $request->getMethod());\n $this->assertEquals('http://foo.com', $request->getUrl());\n $this->assertEquals('Action=foo&Version=1&baz=', (string) $request->getBody());\n }\n}\n" }, { "alpha_fraction": 0.7298850417137146, "alphanum_fraction": 0.7298850417137146, "avg_line_length": 18.33333396911621, "blob_id": "0ccdbc23a0af6b527942108b056d3ac3d575c161", "content_id": "eea95fb79749a89d88a8de238b0557b3edcc4a00", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 174, "license_type": "permissive", "max_line_length": 72, "num_lines": 9, "path": "/src/SimpleDb/SimpleDbClient.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\SimpleDb;\n\nuse Aws\\AwsClient;\n\n/**\n * This client is used to interact with the **Amazon SimpleDB** service.\n */\nclass SimpleDbClient extends AwsClient {}\n" }, { "alpha_fraction": 0.535932719707489, "alphanum_fraction": 0.535932719707489, "avg_line_length": 23.679244995117188, "blob_id": "9b76ebe3660ee56b9948894cc0d725536723c43d", "content_id": "db1bfd8efd9afb20f6c4ba6cd42802c51a8c40b2", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1308, "license_type": "permissive", "max_line_length": 74, "num_lines": 53, "path": "/src/Api/Serializer/QuerySerializer.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Api\\Serializer;\n\nuse Aws\\Api\\Service;\nuse GuzzleHttp\\Command\\CommandTransaction;\n\n/**\n * Serializes a query protocol request.\n * @internal\n */\nclass QuerySerializer\n{\n private $endpoint;\n private $api;\n private $paramBuilder;\n\n public function __construct(\n Service $api,\n $endpoint,\n callable $paramBuilder = null\n ) {\n $this->api = $api;\n $this->endpoint = $endpoint;\n $this->paramBuilder = $paramBuilder ?: new QueryParamBuilder();\n }\n\n public function __invoke(CommandTransaction $trans)\n {\n $command = $trans->command;\n $operation = $this->api->getOperation($command->getName());\n\n $body = [\n 'Action' => $command->getName(),\n 'Version' => $this->api->getMetadata('apiVersion')\n ];\n\n $params = $command->toArray();\n // Only build up the parameters when there are parameters to build\n if ($params) {\n $body += call_user_func(\n $this->paramBuilder,\n $operation->getInput(),\n $params\n );\n }\n\n return $trans->client->createRequest(\n 'POST',\n $this->endpoint,\n ['body' => $body, 'config' => ['command' => $command]]\n );\n }\n}\n" }, { "alpha_fraction": 0.38670602440834045, "alphanum_fraction": 0.38734355568885803, "avg_line_length": 21.57802963256836, "blob_id": "74cc635206843c47b4a8e83d72a2ca77d4a9ee2b", "content_id": "f0ce87ee274efcf5c337f9dcaf949d7dac61035d", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 29803, "license_type": "permissive", "max_line_length": 65, "num_lines": 1320, "path": "/src/data/ecs-2014-11-13.api.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php return [\n 'metadata' => [\n 'apiVersion' => '2014-11-13',\n 'endpointPrefix' => 'ecs',\n 'serviceAbbreviation' => 'Amazon ECS',\n 'serviceFullName' => 'Amazon EC2 Container Service',\n 'signatureVersion' => 'v4',\n 'signingName' => 'ecs',\n 'xmlNamespace' => 'http://ecs.amazonaws.com/doc/2014-11-13/',\n 'protocol' => 'query',\n ],\n 'operations' => [\n 'CreateCluster' => [\n 'name' => 'CreateCluster',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateClusterRequest',\n ],\n 'output' => [\n 'shape' => 'CreateClusterResponse',\n 'resultWrapper' => 'CreateClusterResult',\n ],\n 'errors' => [\n [\n 'shape' => 'ServerException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ClientException',\n 'exception' => true,\n ],\n ],\n ],\n 'DeleteCluster' => [\n 'name' => 'DeleteCluster',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteClusterRequest',\n ],\n 'output' => [\n 'shape' => 'DeleteClusterResponse',\n 'resultWrapper' => 'DeleteClusterResult',\n ],\n 'errors' => [\n [\n 'shape' => 'ServerException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ClientException',\n 'exception' => true,\n ],\n ],\n ],\n 'DeregisterContainerInstance' => [\n 'name' => 'DeregisterContainerInstance',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeregisterContainerInstanceRequest',\n ],\n 'output' => [\n 'shape' => 'DeregisterContainerInstanceResponse',\n 'resultWrapper' => 'DeregisterContainerInstanceResult',\n ],\n 'errors' => [\n [\n 'shape' => 'ServerException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ClientException',\n 'exception' => true,\n ],\n ],\n ],\n 'DeregisterTaskDefinition' => [\n 'name' => 'DeregisterTaskDefinition',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeregisterTaskDefinitionRequest',\n ],\n 'output' => [\n 'shape' => 'DeregisterTaskDefinitionResponse',\n 'resultWrapper' => 'DeregisterTaskDefinitionResult',\n ],\n 'errors' => [\n [\n 'shape' => 'ServerException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ClientException',\n 'exception' => true,\n ],\n ],\n ],\n 'DescribeClusters' => [\n 'name' => 'DescribeClusters',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeClustersRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeClustersResponse',\n 'resultWrapper' => 'DescribeClustersResult',\n ],\n 'errors' => [\n [\n 'shape' => 'ServerException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ClientException',\n 'exception' => true,\n ],\n ],\n ],\n 'DescribeContainerInstances' => [\n 'name' => 'DescribeContainerInstances',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeContainerInstancesRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeContainerInstancesResponse',\n 'resultWrapper' => 'DescribeContainerInstancesResult',\n ],\n 'errors' => [\n [\n 'shape' => 'ServerException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ClientException',\n 'exception' => true,\n ],\n ],\n ],\n 'DescribeTaskDefinition' => [\n 'name' => 'DescribeTaskDefinition',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeTaskDefinitionRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeTaskDefinitionResponse',\n 'resultWrapper' => 'DescribeTaskDefinitionResult',\n ],\n 'errors' => [\n [\n 'shape' => 'ServerException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ClientException',\n 'exception' => true,\n ],\n ],\n ],\n 'DescribeTasks' => [\n 'name' => 'DescribeTasks',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeTasksRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeTasksResponse',\n 'resultWrapper' => 'DescribeTasksResult',\n ],\n 'errors' => [\n [\n 'shape' => 'ServerException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ClientException',\n 'exception' => true,\n ],\n ],\n ],\n 'DiscoverPollEndpoint' => [\n 'name' => 'DiscoverPollEndpoint',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DiscoverPollEndpointRequest',\n ],\n 'output' => [\n 'shape' => 'DiscoverPollEndpointResponse',\n 'resultWrapper' => 'DiscoverPollEndpointResult',\n ],\n 'errors' => [\n [\n 'shape' => 'ServerException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ClientException',\n 'exception' => true,\n ],\n ],\n ],\n 'ListClusters' => [\n 'name' => 'ListClusters',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ListClustersRequest',\n ],\n 'output' => [\n 'shape' => 'ListClustersResponse',\n 'resultWrapper' => 'ListClustersResult',\n ],\n 'errors' => [\n [\n 'shape' => 'ServerException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ClientException',\n 'exception' => true,\n ],\n ],\n ],\n 'ListContainerInstances' => [\n 'name' => 'ListContainerInstances',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ListContainerInstancesRequest',\n ],\n 'output' => [\n 'shape' => 'ListContainerInstancesResponse',\n 'resultWrapper' => 'ListContainerInstancesResult',\n ],\n 'errors' => [\n [\n 'shape' => 'ServerException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ClientException',\n 'exception' => true,\n ],\n ],\n ],\n 'ListTaskDefinitions' => [\n 'name' => 'ListTaskDefinitions',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ListTaskDefinitionsRequest',\n ],\n 'output' => [\n 'shape' => 'ListTaskDefinitionsResponse',\n 'resultWrapper' => 'ListTaskDefinitionsResult',\n ],\n 'errors' => [\n [\n 'shape' => 'ServerException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ClientException',\n 'exception' => true,\n ],\n ],\n ],\n 'ListTasks' => [\n 'name' => 'ListTasks',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ListTasksRequest',\n ],\n 'output' => [\n 'shape' => 'ListTasksResponse',\n 'resultWrapper' => 'ListTasksResult',\n ],\n 'errors' => [\n [\n 'shape' => 'ServerException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ClientException',\n 'exception' => true,\n ],\n ],\n ],\n 'RegisterContainerInstance' => [\n 'name' => 'RegisterContainerInstance',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'RegisterContainerInstanceRequest',\n ],\n 'output' => [\n 'shape' => 'RegisterContainerInstanceResponse',\n 'resultWrapper' => 'RegisterContainerInstanceResult',\n ],\n 'errors' => [\n [\n 'shape' => 'ServerException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ClientException',\n 'exception' => true,\n ],\n ],\n ],\n 'RegisterTaskDefinition' => [\n 'name' => 'RegisterTaskDefinition',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'RegisterTaskDefinitionRequest',\n ],\n 'output' => [\n 'shape' => 'RegisterTaskDefinitionResponse',\n 'resultWrapper' => 'RegisterTaskDefinitionResult',\n ],\n 'errors' => [\n [\n 'shape' => 'ServerException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ClientException',\n 'exception' => true,\n ],\n ],\n ],\n 'RunTask' => [\n 'name' => 'RunTask',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'RunTaskRequest',\n ],\n 'output' => [\n 'shape' => 'RunTaskResponse',\n 'resultWrapper' => 'RunTaskResult',\n ],\n 'errors' => [\n [\n 'shape' => 'ServerException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ClientException',\n 'exception' => true,\n ],\n ],\n ],\n 'StartTask' => [\n 'name' => 'StartTask',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'StartTaskRequest',\n ],\n 'output' => [\n 'shape' => 'StartTaskResponse',\n 'resultWrapper' => 'StartTaskResult',\n ],\n 'errors' => [\n [\n 'shape' => 'ServerException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ClientException',\n 'exception' => true,\n ],\n ],\n ],\n 'StopTask' => [\n 'name' => 'StopTask',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'StopTaskRequest',\n ],\n 'output' => [\n 'shape' => 'StopTaskResponse',\n 'resultWrapper' => 'StopTaskResult',\n ],\n 'errors' => [\n [\n 'shape' => 'ServerException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ClientException',\n 'exception' => true,\n ],\n ],\n ],\n 'SubmitContainerStateChange' => [\n 'name' => 'SubmitContainerStateChange',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'SubmitContainerStateChangeRequest',\n ],\n 'output' => [\n 'shape' => 'SubmitContainerStateChangeResponse',\n 'resultWrapper' => 'SubmitContainerStateChangeResult',\n ],\n 'errors' => [\n [\n 'shape' => 'ServerException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ClientException',\n 'exception' => true,\n ],\n ],\n ],\n 'SubmitTaskStateChange' => [\n 'name' => 'SubmitTaskStateChange',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'SubmitTaskStateChangeRequest',\n ],\n 'output' => [\n 'shape' => 'SubmitTaskStateChangeResponse',\n 'resultWrapper' => 'SubmitTaskStateChangeResult',\n ],\n 'errors' => [\n [\n 'shape' => 'ServerException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ClientException',\n 'exception' => true,\n ],\n ],\n ],\n ],\n 'shapes' => [\n 'Boolean' => [\n 'type' => 'boolean',\n ],\n 'BoxedBoolean' => [\n 'type' => 'boolean',\n 'box' => true,\n ],\n 'BoxedInteger' => [\n 'type' => 'integer',\n 'box' => true,\n ],\n 'ClientException' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'String',\n ],\n ],\n 'exception' => true,\n ],\n 'Cluster' => [\n 'type' => 'structure',\n 'members' => [\n 'clusterArn' => [\n 'shape' => 'String',\n ],\n 'clusterName' => [\n 'shape' => 'String',\n ],\n 'status' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'Clusters' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'Cluster',\n ],\n ],\n 'Container' => [\n 'type' => 'structure',\n 'members' => [\n 'containerArn' => [\n 'shape' => 'String',\n ],\n 'taskArn' => [\n 'shape' => 'String',\n ],\n 'name' => [\n 'shape' => 'String',\n ],\n 'lastStatus' => [\n 'shape' => 'String',\n ],\n 'exitCode' => [\n 'shape' => 'BoxedInteger',\n ],\n 'reason' => [\n 'shape' => 'String',\n ],\n 'networkBindings' => [\n 'shape' => 'NetworkBindings',\n ],\n ],\n ],\n 'ContainerDefinition' => [\n 'type' => 'structure',\n 'members' => [\n 'name' => [\n 'shape' => 'String',\n ],\n 'image' => [\n 'shape' => 'String',\n ],\n 'cpu' => [\n 'shape' => 'Integer',\n ],\n 'memory' => [\n 'shape' => 'Integer',\n ],\n 'links' => [\n 'shape' => 'StringList',\n ],\n 'portMappings' => [\n 'shape' => 'PortMappingList',\n ],\n 'essential' => [\n 'shape' => 'BoxedBoolean',\n ],\n 'entryPoint' => [\n 'shape' => 'StringList',\n ],\n 'command' => [\n 'shape' => 'StringList',\n ],\n 'environment' => [\n 'shape' => 'EnvironmentVariables',\n ],\n ],\n ],\n 'ContainerDefinitions' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'ContainerDefinition',\n ],\n ],\n 'ContainerInstance' => [\n 'type' => 'structure',\n 'members' => [\n 'containerInstanceArn' => [\n 'shape' => 'String',\n ],\n 'ec2InstanceId' => [\n 'shape' => 'String',\n ],\n 'remainingResources' => [\n 'shape' => 'Resources',\n ],\n 'registeredResources' => [\n 'shape' => 'Resources',\n ],\n 'status' => [\n 'shape' => 'String',\n ],\n 'agentConnected' => [\n 'shape' => 'Boolean',\n ],\n ],\n ],\n 'ContainerInstances' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'ContainerInstance',\n ],\n ],\n 'ContainerOverride' => [\n 'type' => 'structure',\n 'members' => [\n 'name' => [\n 'shape' => 'String',\n ],\n 'command' => [\n 'shape' => 'StringList',\n ],\n ],\n ],\n 'ContainerOverrides' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'ContainerOverride',\n ],\n ],\n 'Containers' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'Container',\n ],\n ],\n 'CreateClusterRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'clusterName' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'CreateClusterResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'cluster' => [\n 'shape' => 'Cluster',\n ],\n ],\n ],\n 'DeleteClusterRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'cluster',\n ],\n 'members' => [\n 'cluster' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'DeleteClusterResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'cluster' => [\n 'shape' => 'Cluster',\n ],\n ],\n ],\n 'DeregisterContainerInstanceRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'containerInstance',\n ],\n 'members' => [\n 'cluster' => [\n 'shape' => 'String',\n ],\n 'containerInstance' => [\n 'shape' => 'String',\n ],\n 'force' => [\n 'shape' => 'BoxedBoolean',\n ],\n ],\n ],\n 'DeregisterContainerInstanceResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'containerInstance' => [\n 'shape' => 'ContainerInstance',\n ],\n ],\n ],\n 'DeregisterTaskDefinitionRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'taskDefinition',\n ],\n 'members' => [\n 'taskDefinition' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'DeregisterTaskDefinitionResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'taskDefinition' => [\n 'shape' => 'TaskDefinition',\n ],\n ],\n ],\n 'DescribeClustersRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'clusters' => [\n 'shape' => 'StringList',\n ],\n ],\n ],\n 'DescribeClustersResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'clusters' => [\n 'shape' => 'Clusters',\n ],\n 'failures' => [\n 'shape' => 'Failures',\n ],\n ],\n ],\n 'DescribeContainerInstancesRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'containerInstances',\n ],\n 'members' => [\n 'cluster' => [\n 'shape' => 'String',\n ],\n 'containerInstances' => [\n 'shape' => 'StringList',\n ],\n ],\n ],\n 'DescribeContainerInstancesResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'containerInstances' => [\n 'shape' => 'ContainerInstances',\n ],\n 'failures' => [\n 'shape' => 'Failures',\n ],\n ],\n ],\n 'DescribeTaskDefinitionRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'taskDefinition',\n ],\n 'members' => [\n 'taskDefinition' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'DescribeTaskDefinitionResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'taskDefinition' => [\n 'shape' => 'TaskDefinition',\n ],\n ],\n ],\n 'DescribeTasksRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'tasks',\n ],\n 'members' => [\n 'cluster' => [\n 'shape' => 'String',\n ],\n 'tasks' => [\n 'shape' => 'StringList',\n ],\n ],\n ],\n 'DescribeTasksResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'tasks' => [\n 'shape' => 'Tasks',\n ],\n 'failures' => [\n 'shape' => 'Failures',\n ],\n ],\n ],\n 'DiscoverPollEndpointRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'containerInstance' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'DiscoverPollEndpointResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'endpoint' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'Double' => [\n 'type' => 'double',\n ],\n 'EnvironmentVariables' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'KeyValuePair',\n ],\n ],\n 'Failure' => [\n 'type' => 'structure',\n 'members' => [\n 'arn' => [\n 'shape' => 'String',\n ],\n 'reason' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'Failures' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'Failure',\n ],\n ],\n 'Integer' => [\n 'type' => 'integer',\n ],\n 'KeyValuePair' => [\n 'type' => 'structure',\n 'members' => [\n 'name' => [\n 'shape' => 'String',\n ],\n 'value' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'ListClustersRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'nextToken' => [\n 'shape' => 'String',\n ],\n 'maxResults' => [\n 'shape' => 'BoxedInteger',\n ],\n ],\n ],\n 'ListClustersResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'clusterArns' => [\n 'shape' => 'StringList',\n ],\n 'nextToken' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'ListContainerInstancesRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'cluster' => [\n 'shape' => 'String',\n ],\n 'nextToken' => [\n 'shape' => 'String',\n ],\n 'maxResults' => [\n 'shape' => 'BoxedInteger',\n ],\n ],\n ],\n 'ListContainerInstancesResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'containerInstanceArns' => [\n 'shape' => 'StringList',\n ],\n 'nextToken' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'ListTaskDefinitionsRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'familyPrefix' => [\n 'shape' => 'String',\n ],\n 'nextToken' => [\n 'shape' => 'String',\n ],\n 'maxResults' => [\n 'shape' => 'BoxedInteger',\n ],\n ],\n ],\n 'ListTaskDefinitionsResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'taskDefinitionArns' => [\n 'shape' => 'StringList',\n ],\n 'nextToken' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'ListTasksRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'cluster' => [\n 'shape' => 'String',\n ],\n 'containerInstance' => [\n 'shape' => 'String',\n ],\n 'family' => [\n 'shape' => 'String',\n ],\n 'nextToken' => [\n 'shape' => 'String',\n ],\n 'maxResults' => [\n 'shape' => 'BoxedInteger',\n ],\n ],\n ],\n 'ListTasksResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'taskArns' => [\n 'shape' => 'StringList',\n ],\n 'nextToken' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'Long' => [\n 'type' => 'long',\n ],\n 'NetworkBinding' => [\n 'type' => 'structure',\n 'members' => [\n 'bindIP' => [\n 'shape' => 'String',\n ],\n 'containerPort' => [\n 'shape' => 'BoxedInteger',\n ],\n 'hostPort' => [\n 'shape' => 'BoxedInteger',\n ],\n ],\n ],\n 'NetworkBindings' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'NetworkBinding',\n ],\n ],\n 'PortMapping' => [\n 'type' => 'structure',\n 'members' => [\n 'containerPort' => [\n 'shape' => 'Integer',\n ],\n 'hostPort' => [\n 'shape' => 'Integer',\n ],\n ],\n ],\n 'PortMappingList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'PortMapping',\n ],\n ],\n 'RegisterContainerInstanceRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'cluster' => [\n 'shape' => 'String',\n ],\n 'instanceIdentityDocument' => [\n 'shape' => 'String',\n ],\n 'instanceIdentityDocumentSignature' => [\n 'shape' => 'String',\n ],\n 'totalResources' => [\n 'shape' => 'Resources',\n ],\n ],\n ],\n 'RegisterContainerInstanceResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'containerInstance' => [\n 'shape' => 'ContainerInstance',\n ],\n ],\n ],\n 'RegisterTaskDefinitionRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'family',\n 'containerDefinitions',\n ],\n 'members' => [\n 'family' => [\n 'shape' => 'String',\n ],\n 'containerDefinitions' => [\n 'shape' => 'ContainerDefinitions',\n ],\n ],\n ],\n 'RegisterTaskDefinitionResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'taskDefinition' => [\n 'shape' => 'TaskDefinition',\n ],\n ],\n ],\n 'Resource' => [\n 'type' => 'structure',\n 'members' => [\n 'name' => [\n 'shape' => 'String',\n ],\n 'type' => [\n 'shape' => 'String',\n ],\n 'doubleValue' => [\n 'shape' => 'Double',\n ],\n 'longValue' => [\n 'shape' => 'Long',\n ],\n 'integerValue' => [\n 'shape' => 'Integer',\n ],\n 'stringSetValue' => [\n 'shape' => 'StringList',\n ],\n ],\n ],\n 'Resources' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'Resource',\n ],\n ],\n 'RunTaskRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'taskDefinition',\n ],\n 'members' => [\n 'cluster' => [\n 'shape' => 'String',\n ],\n 'taskDefinition' => [\n 'shape' => 'String',\n ],\n 'overrides' => [\n 'shape' => 'TaskOverride',\n ],\n 'count' => [\n 'shape' => 'BoxedInteger',\n ],\n ],\n ],\n 'RunTaskResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'tasks' => [\n 'shape' => 'Tasks',\n ],\n 'failures' => [\n 'shape' => 'Failures',\n ],\n ],\n ],\n 'ServerException' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'String',\n ],\n ],\n 'exception' => true,\n ],\n 'StartTaskRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'taskDefinition',\n 'containerInstances',\n ],\n 'members' => [\n 'cluster' => [\n 'shape' => 'String',\n ],\n 'taskDefinition' => [\n 'shape' => 'String',\n ],\n 'overrides' => [\n 'shape' => 'TaskOverride',\n ],\n 'containerInstances' => [\n 'shape' => 'StringList',\n ],\n ],\n ],\n 'StartTaskResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'tasks' => [\n 'shape' => 'Tasks',\n ],\n 'failures' => [\n 'shape' => 'Failures',\n ],\n ],\n ],\n 'StopTaskRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'task',\n ],\n 'members' => [\n 'cluster' => [\n 'shape' => 'String',\n ],\n 'task' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'StopTaskResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'task' => [\n 'shape' => 'Task',\n ],\n ],\n ],\n 'String' => [\n 'type' => 'string',\n ],\n 'StringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n ],\n ],\n 'SubmitContainerStateChangeRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'cluster' => [\n 'shape' => 'String',\n ],\n 'task' => [\n 'shape' => 'String',\n ],\n 'containerName' => [\n 'shape' => 'String',\n ],\n 'status' => [\n 'shape' => 'String',\n ],\n 'exitCode' => [\n 'shape' => 'BoxedInteger',\n ],\n 'reason' => [\n 'shape' => 'String',\n ],\n 'networkBindings' => [\n 'shape' => 'NetworkBindings',\n ],\n ],\n ],\n 'SubmitContainerStateChangeResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'acknowledgment' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'SubmitTaskStateChangeRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'cluster' => [\n 'shape' => 'String',\n ],\n 'task' => [\n 'shape' => 'String',\n ],\n 'status' => [\n 'shape' => 'String',\n ],\n 'reason' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'SubmitTaskStateChangeResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'acknowledgment' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'Task' => [\n 'type' => 'structure',\n 'members' => [\n 'taskArn' => [\n 'shape' => 'String',\n ],\n 'clusterArn' => [\n 'shape' => 'String',\n ],\n 'taskDefinitionArn' => [\n 'shape' => 'String',\n ],\n 'containerInstanceArn' => [\n 'shape' => 'String',\n ],\n 'overrides' => [\n 'shape' => 'TaskOverride',\n ],\n 'lastStatus' => [\n 'shape' => 'String',\n ],\n 'desiredStatus' => [\n 'shape' => 'String',\n ],\n 'containers' => [\n 'shape' => 'Containers',\n ],\n ],\n ],\n 'TaskDefinition' => [\n 'type' => 'structure',\n 'members' => [\n 'taskDefinitionArn' => [\n 'shape' => 'String',\n ],\n 'containerDefinitions' => [\n 'shape' => 'ContainerDefinitions',\n ],\n 'family' => [\n 'shape' => 'String',\n ],\n 'revision' => [\n 'shape' => 'Integer',\n ],\n ],\n ],\n 'TaskOverride' => [\n 'type' => 'structure',\n 'members' => [\n 'containerOverrides' => [\n 'shape' => 'ContainerOverrides',\n ],\n ],\n ],\n 'Tasks' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'Task',\n ],\n ],\n ],\n];\n" }, { "alpha_fraction": 0.45945945382118225, "alphanum_fraction": 0.45945945382118225, "avg_line_length": 14.857142448425293, "blob_id": "7948b6be94b0aeacebd0e0f2663dfcf4112b0615", "content_id": "c2f8cd6c2af739a8c14d2e0dcb33680be248be61", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 111, "license_type": "permissive", "max_line_length": 34, "num_lines": 7, "path": "/src/data/cloudtrail-2013-11-01.paginators.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php return [\n 'pagination' => [\n 'DescribeTrails' => [\n 'result_key' => 'trailList',\n ],\n ],\n];\n" }, { "alpha_fraction": 0.5032265186309814, "alphanum_fraction": 0.5061795711517334, "avg_line_length": 28.879085540771484, "blob_id": "146b1ddc8b63ca8aaaa062ed44dd41d89676ea38", "content_id": "0fb1b41f59344c29766b3459c3277b14d9941571", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 9143, "license_type": "permissive", "max_line_length": 99, "num_lines": 306, "path": "/tests/AwsClientTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test;\n\nuse Aws\\AwsClient;\nuse Aws\\Credentials\\Credentials;\nuse Aws\\Ec2\\Ec2Client;\nuse Aws\\Signature\\SignatureV4;\nuse Aws\\Sqs\\SqsClient;\nuse Aws\\Sts\\StsClient;\nuse GuzzleHttp\\Client;\nuse GuzzleHttp\\Command\\Event\\PreparedEvent;\nuse GuzzleHttp\\Event\\BeforeEvent;\nuse GuzzleHttp\\Event\\RequestEvents;\nuse GuzzleHttp\\Message\\Request;\nuse GuzzleHttp\\Message\\Response;\n\n/**\n * @covers Aws\\AwsClient\n */\nclass AwsClientTest extends \\PHPUnit_Framework_TestCase\n{\n use UsesServiceTrait;\n\n private function getApiProvider()\n {\n return function () {\n return [\n 'metadata' => [\n 'protocol' => 'query',\n 'endpointPrefix' => 'foo'\n ]\n ];\n };\n }\n\n public function testHasGetters()\n {\n $config = [\n 'client' => new Client(),\n 'credentials' => new Credentials('foo', 'bar'),\n 'region' => 'foo',\n 'endpoint' => 'http://us-east-1.foo.amazonaws.com',\n 'serializer' => function () {},\n 'api_provider' => $this->getApiProvider(),\n 'service' => 'foo',\n 'error_parser' => function () {},\n 'version' => 'latest'\n ];\n\n $client = new AwsClient($config);\n $this->assertSame($config['client'], $client->getHttpClient());\n $this->assertSame($config['credentials'], $client->getCredentials());\n $this->assertSame($config['region'], $client->getRegion());\n $this->assertEquals('foo', $client->getApi()->getEndpointPrefix());\n }\n\n /**\n * @expectedException \\InvalidArgumentException\n * @expectedExceptionMessage Operation not found: Foo\n */\n public function testEnsuresOperationIsFoundWhenCreatingCommands()\n {\n $this->createClient()->getCommand('foo');\n }\n\n public function testReturnsCommandForOperation()\n {\n $client = $this->createClient([\n 'operations' => [\n 'foo' => [\n 'http' => ['method' => 'POST']\n ]\n ]\n ]);\n\n $this->assertInstanceOf(\n 'GuzzleHttp\\Command\\CommandInterface',\n $client->getCommand('foo')\n );\n }\n\n /**\n * @expectedException \\Aws\\Exception\\AwsException\n * @expectedExceptionMessage Uncaught exception while executing Aws\\AwsClient::foo - Baz Bar!\n */\n public function testWrapsUncaughtExceptions()\n {\n $client = $this->createClient(\n ['operations' => ['foo' => ['http' => ['method' => 'POST']]]]\n );\n $command = $client->getCommand('foo');\n $command->getEmitter()->on('init', function () {\n throw new \\RuntimeException('Baz Bar!');\n });\n $client->execute($command);\n }\n\n /**\n * @expectedException \\Aws\\Exception\\AwsException\n * @expectedExceptionMessage Error executing Aws\\AwsClient::foo() on \"http://foo.com\"; Baz Bar!\n */\n public function testHandlesNetworkingErrorsGracefully()\n {\n $r = new Request('GET', 'http://foo.com');\n $client = $this->createClient(\n ['operations' => ['foo' => ['http' => ['method' => 'POST']]]],\n [\n 'serializer' => function () use ($r) { return $r; },\n 'endpoint' => 'http://foo.com'\n ]\n );\n $command = $client->getCommand('foo');\n $command->getEmitter()->on('prepared', function (PreparedEvent $e) {\n $e->getRequest()->getEmitter()->on('before', function () {\n throw new \\RuntimeException('Baz Bar!');\n });\n });\n $client->execute($command);\n }\n\n public function testChecksBothLowercaseAndUppercaseOperationNames()\n {\n $client = $this->createClient(['operations' => ['Foo' => [\n 'http' => ['method' => 'POST']\n ]]]);\n\n $this->assertInstanceOf(\n 'GuzzleHttp\\Command\\CommandInterface',\n $client->getCommand('foo')\n );\n }\n\n public function testCanGetIterator()\n {\n $client = $this->getTestClient('s3');\n $this->assertInstanceOf(\n 'Generator',\n $client->getIterator('ListObjects', ['Bucket' => 'foobar'])\n );\n }\n\n /**\n * @expectedException \\UnexpectedValueException\n */\n public function testGetIteratorFailsForMissingConfig()\n {\n $client = $this->createClient();\n $client->getIterator('ListObjects');\n }\n\n public function testCanGetPaginator()\n {\n $client = $this->createClient(['pagination' => [\n 'ListObjects' => [\n 'input_token' => 'foo',\n 'output_token' => 'foo',\n ]\n ]]);\n\n $this->assertInstanceOf(\n 'Aws\\ResultPaginator',\n $client->getPaginator('ListObjects', ['Bucket' => 'foobar'])\n );\n }\n\n /**\n * @expectedException \\UnexpectedValueException\n */\n public function testGetPaginatorFailsForMissingConfig()\n {\n $client = $this->createClient();\n $client->getPaginator('ListObjects');\n }\n\n /**\n * @expectedException \\InvalidArgumentException\n * @expectedExceptionMessage Operation not found\n */\n public function testCanWaitSynchronously()\n {\n $client = $this->createClient(['waiters' => ['PigsFly' => [\n 'acceptors' => [],\n 'delay' => 1,\n 'maxAttempts' => 1,\n 'operation' => 'DescribePigs',\n ]]]);\n\n $client->waitUntil('PigsFly');\n }\n\n /**\n * @expectedException \\UnexpectedValueException\n */\n public function testGetWaiterFailsForMissingConfig()\n {\n $client = $this->createClient();\n $client->waitUntil('PigsFly');\n }\n\n public function testCreatesClientsFromFactoryMethod()\n {\n $client = new SqsClient([\n 'region' => 'us-west-2',\n 'version' => 'latest'\n ]);\n $this->assertInstanceOf('Aws\\Sqs\\SqsClient', $client);\n $this->assertEquals('us-west-2', $client->getRegion());\n\n $client = new StsClient([\n 'region' => 'us-west-2',\n 'version' => 'latest'\n ]);\n $this->assertInstanceOf('Aws\\Sts\\StsClient', $client);\n $this->assertEquals('us-west-2', $client->getRegion());\n }\n\n public function testCanGetEndpoint()\n {\n $client = $this->createClient();\n $this->assertEquals(\n 'http://us-east-1.foo.amazonaws.com',\n $client->getEndpoint()\n );\n }\n\n private function createClient(array $service = [], array $config = [])\n {\n $apiProvider = function ($type) use ($service, $config) {\n if ($type == 'paginator') {\n return isset($service['pagination'])\n ? ['pagination' => $service['pagination']]\n : ['pagination' => []];\n } elseif ($type == 'waiter') {\n return isset($service['waiters'])\n ? ['waiters' => $service['waiters']]\n : ['waiters' => []];\n } else {\n if (!isset($service['metadata'])) {\n $service['metadata'] = [];\n }\n $service['metadata']['protocol'] = 'query';\n return $service;\n }\n };\n\n return new AwsClient($config + [\n 'client' => new Client(),\n 'credentials' => new Credentials('foo', 'bar'),\n 'signature' => new SignatureV4('foo', 'bar'),\n 'endpoint' => 'http://us-east-1.foo.amazonaws.com',\n 'region' => 'foo',\n 'service' => 'foo',\n 'api_provider' => $apiProvider,\n 'serializer' => function () {},\n 'error_parser' => function () {},\n 'version' => 'latest'\n ]);\n }\n\n public function signerProvider()\n {\n return [\n [null, 'AWS4-HMAC-SHA256'],\n ['v2', 'SignatureVersion']\n ];\n }\n\n /**\n * @dataProvider signerProvider\n */\n public function testSignsRequestsUsingSigner($version, $search)\n {\n $conf = [\n 'region' => 'us-east-1',\n 'version' => 'latest',\n 'credentials' => [\n 'key' => 'foo',\n 'secret' => 'bar'\n ]\n ];\n\n if ($version) {\n $conf['signature_version'] = $version;\n }\n\n $client = new Ec2Client($conf);\n $client->getHttpClient()->getEmitter()->on(\n 'before',\n function (BeforeEvent $e) use ($search) {\n $str = (string) $e->getRequest();\n $this->assertContains($search, $str);\n $e->intercept(new Response(200));\n },\n RequestEvents::SIGN_REQUEST - 1\n );\n $client->describeInstances();\n }\n\n public function testAllowsFactoryMethodForBc()\n {\n Ec2Client::factory([\n 'region' => 'us-west-2',\n 'version' => 'latest'\n ]);\n }\n}\n" }, { "alpha_fraction": 0.5367558002471924, "alphanum_fraction": 0.5425273180007935, "avg_line_length": 29.481481552124023, "blob_id": "17fa11b7799e98dbd7b780afb2af006ac2475b06", "content_id": "8e2d6da16187e2c0b13483d57167158a1584cfee", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3292, "license_type": "permissive", "max_line_length": 92, "num_lines": 108, "path": "/src/Credentials/InstanceProfileProvider.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Credentials;\n\nuse Aws\\Exception\\CredentialsException;\nuse GuzzleHttp\\Client;\nuse GuzzleHttp\\Utils;\n\n/**\n * Loads credentials from the EC2 metadata server. If the profile cannot bef\n * found, the provider returns null.\n */\nclass InstanceProfileProvider\n{\n /** @var string */\n private $profile;\n\n /** @var int */\n private $retries;\n\n /** @var Client */\n private $client;\n\n /**\n * The constructor accepts the following options:\n *\n * - timeout: Connection timeout, in seconds.\n * - retries: Optional number of exponential backoff retries to use.\n * - profile: Optional EC2 profile name, if known.\n *\n * @param array $config Configuration options.\n */\n public function __construct(array $config = [])\n {\n $this->timeout = isset($config['timeout']) ? $config['timeout'] : 1.0;\n $this->profile = isset($config['profile']) ? $config['profile'] : null;\n $this->retries = isset($config['retries']) ? $config['retries'] : 3;\n\n if (isset($config['client'])) {\n // Internal use only. Not part of the public API.\n $this->client = $config['client'];\n } else {\n $this->client = $this->client = new Client([\n 'base_url' => 'http://169.254.169.254/latest/',\n 'defaults' => ['connect_timeout' => 1]\n ]);\n }\n }\n\n /**\n * Loads refreshable profile credentials if they are available, otherwise\n * returns null.\n *\n * @return RefreshableCredentials|null\n */\n public function __invoke()\n {\n // Pass if the profile cannot be loaded or was not provided.\n if (!$this->profile) {\n try {\n $this->profile = $this->request('meta-data/iam/security-credentials/');\n } catch (CredentialsException $e) {\n return null;\n }\n }\n\n return new RefreshableCredentials(function () {\n $response = $this->request(\"meta-data/iam/security-credentials/$this->profile\");\n $result = Utils::jsonDecode($response, true);\n if ($result['Code'] !== 'Success') {\n throw new CredentialsException('Unexpected instance profile response'\n . \" code: {$result['Code']}\");\n }\n return new Credentials(\n $result['AccessKeyId'],\n $result['SecretAccessKey'],\n $result['Token'],\n strtotime($result['Expiration'])\n );\n });\n }\n\n /**\n * @param string $url\n *\n * @throws CredentialsException\n * @return string\n */\n private function request($url)\n {\n $retryCount = 0;\n start_over:\n try {\n return (string) $this->client->get($url)->getBody();\n } catch (\\Exception $e) {\n if (++$retryCount > $this->retries) {\n $message = $this->createErrorMessage($e->getMessage());\n throw new CredentialsException($message, $e->getCode());\n }\n goto start_over;\n }\n }\n\n private function createErrorMessage($previous)\n {\n return \"Error retrieving credentials from the instance profile \"\n . \"metadata server. ({$previous})\";\n }\n}\n" }, { "alpha_fraction": 0.5805755257606506, "alphanum_fraction": 0.5827338099479675, "avg_line_length": 32.90243911743164, "blob_id": "969f44d45103108041757cdc8451dc281ee66c27", "content_id": "36d5064caf4718dffa53177e735deaabda2a49f8", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1390, "license_type": "permissive", "max_line_length": 70, "num_lines": 41, "path": "/tests/Integ/PromisesTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Integ;\n\nclass PromisesTest extends \\PHPUnit_Framework_TestCase\n{\n use IntegUtils;\n\n public function testSendsSynchronously()\n {\n $client = $this->getSdk()->createClient('s3');\n $result = $client->listBuckets();\n $this->assertInstanceOf('Aws\\Result', $result);\n $this->assertInternalType('string', $result['Owner']['ID']);\n }\n\n public function testProvidesFutures()\n {\n $client = $this->getSdk()->createClient('s3');\n $result = $client->listBuckets(['@future' => true]);\n $this->assertInstanceOf('Aws\\FutureResult', $result);\n // Block until it's ready\n $this->assertInternalType('string', $result['Owner']['ID']);\n }\n\n public function testFuturesProvidePromises()\n {\n $client = $this->getSdk()->createClient('s3');\n $resolved = null;\n $result = $client->listBuckets(['@future' => true]);\n $result\n ->then(function ($result) use (&$resolved) {\n $resolved = $result;\n $this->assertInstanceOf('Aws\\Result', $result);\n });\n // Block to trigger the promise resolution.\n $result->wait();\n $this->assertInstanceOf('Aws\\FutureResult', $result);\n $this->assertInstanceOf('Aws\\Result', $resolved);\n $this->assertInternalType('string', $resolved['Owner']['ID']);\n }\n}\n" }, { "alpha_fraction": 0.5243070125579834, "alphanum_fraction": 0.5305752754211426, "avg_line_length": 30.077922821044922, "blob_id": "5ce65a91e2c55283709df45e7ed9d33733908c14", "content_id": "4d9042377cbd203e821466291fe35b7757cd46f3", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 7179, "license_type": "permissive", "max_line_length": 84, "num_lines": 231, "path": "/src/S3/UploadBuilder.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\S3;\n\nuse Aws\\Multipart\\AbstractUploadBuilder;\nuse Aws\\Multipart\\UploadState;\nuse Aws\\Result;\nuse GuzzleHttp\\Command\\CommandInterface;\nuse GuzzleHttp\\Mimetypes;\nuse GuzzleHttp\\Stream\\LazyOpenStream;\nuse GuzzleHttp\\Stream\\Stream;\nuse GuzzleHttp\\Stream\\StreamInterface;\nuse GuzzleHttp\\Stream\\Utils;\nuse GuzzleHttp\\Subscriber\\MessageIntegrity\\HashingStream;\nuse GuzzleHttp\\Subscriber\\MessageIntegrity\\PhpHash;\n\n/**\n * Creates a multipart uploader used to easily upload large objects to S3.\n */\nclass UploadBuilder extends AbstractUploadBuilder\n{\n protected $config = [\n 'id' => ['Bucket', 'Key', 'UploadId'],\n 'part' => [\n 'min_size' => 5242880,\n 'max_size' => 5368709120,\n 'max_num' => 10000,\n 'param' => 'PartNumber',\n ],\n 'initiate' => [\n 'command' => 'CreateMultipartUpload',\n 'params' => [],\n ],\n 'upload' => [\n 'command' => 'UploadPart',\n 'params' => [],\n ],\n 'complete' => [\n 'command' => 'CompleteMultipartUpload',\n 'params' => [],\n ],\n 'abort' => [\n 'command' => 'AbortMultipartUpload',\n 'params' => [],\n ],\n ];\n\n /**\n * Set the bucket to upload the object to\n *\n * @param string $bucket Name of the bucket\n *\n * @return self\n */\n public function setBucket($bucket)\n {\n $this->uploadId['Bucket'] = $bucket;\n\n return $this;\n }\n\n /**\n * Set the key of the object\n *\n * @param string $key Key of the object to upload\n *\n * @return self\n */\n public function setKey($key)\n {\n $this->uploadId['Key'] = $key;\n\n return $this;\n }\n\n /**\n * Set the upload ID of the upload.\n *\n * @param string $uploadId ID of the upload.\n *\n * @return self\n */\n public function setUploadId($uploadId)\n {\n $this->uploadId['UploadId'] = $uploadId;\n\n return $this;\n }\n\n protected function prepareParams()\n {\n // Set the content type, if not specified, and can be detected.\n if (!isset($this->config['initiate']['params']['ContentType'])\n && ($uri = $this->source->getMetadata('uri'))\n ) {\n if ($mimeType = Mimetypes::getInstance()->fromFilename($uri)) {\n $this->config['initiate']['params']['ContentType'] = $mimeType;\n }\n }\n }\n\n protected function loadStateByUploadId(array $params = [])\n {\n $state = new UploadState($params);\n\n $partSize = null;\n foreach ($this->client->getIterator('ListParts', $params) as $part) {\n if (!$partSize) $partSize = $part['Size'];\n $state->markPartAsUploaded($part['PartNumber'], [\n 'PartNumber' => $part['PartNumber'],\n 'ETag' => $part['ETag']\n ]);\n }\n $state->setPartSize($partSize);\n $state->setStatus($state::INITIATED);\n\n return $state;\n }\n\n protected function determinePartSize()\n {\n // Make sure the part size is set.\n $partSize = $this->specifiedPartSize ?: $this->config['part']['min_size'];\n\n // Adjust the part size to be larger for known, x-large uploads.\n if ($sourceSize = $this->source->getSize()) {\n $partSize = (int) max(\n $partSize,\n ceil($sourceSize / $this->config['part']['max_num'])\n );\n }\n\n // Ensure that the part size follows the rules: 5 MB <= size <= 5 GB\n if ($partSize < $this->config['part']['min_size']\n || $partSize > $this->config['part']['max_size']\n ) {\n throw new \\InvalidArgumentException('The part size must be no less '\n . 'than 5 MB and not greater than 5 GB.');\n }\n\n return $partSize;\n }\n\n protected function getCreatePartFn()\n {\n return function ($seekable, $number) {\n // Initialize the array of part data that will be returned.\n $data = ['PartNumber' => $number];\n\n // Read from the source to create the body stream.\n if ($seekable) {\n // Case 1: Source is seekable, use lazy stream to defer work.\n $body = $this->limitPartStream(\n new LazyOpenStream($this->source->getMetadata('uri'), 'r')\n );\n } else {\n // Case 2: Stream is not seekable; must store in temp stream.\n $source = $this->limitPartStream($this->source);\n $source = $this->decorateWithHashes($source,\n function ($result, $type) use (&$data) {\n $data['Content' . strtoupper($type)] = $result;\n }\n );\n $body = Stream::factory();\n Utils::copyToStream($source, $body);\n $data['ContentLength'] = $body->getSize();\n }\n\n $body->seek(0);\n $data['Body'] = $body;\n\n return $data;\n };\n }\n\n protected function getCompleteParamsFn()\n {\n return function () {\n return [\n 'MultipartUpload' => [\n 'Parts' => $this->state->getUploadedParts()\n ]\n ];\n };\n }\n\n protected function getResultHandlerFn()\n {\n return function (CommandInterface $command, Result $result) {\n $this->state->markPartAsUploaded($command['PartNumber'], [\n 'PartNumber' => $command['PartNumber'],\n 'ETag' => $result['ETag']\n ]);\n };\n }\n\n /**\n * Decorates a stream with a md5/sha256 linear hashing stream if needed.\n *\n * S3 does not typically require content hashes (unless using Signature V4),\n * but they can be used to ensure the message integrity of the upload.\n * When using non-seekable/remote streams, we must do the work of reading\n * through the body to calculate parts. In this case, we can wrap the parts'\n * body streams with a hashing stream decorator to calculate the hashes at\n * the same time, instead of having to buffer the stream to disk and re-read\n * the stream later.\n *\n * @param StreamInterface $stream Stream to decorate.\n * @param callable $complete Callback to execute for the hash result.\n *\n * @return StreamInterface\n */\n private function decorateWithHashes(StreamInterface $stream, callable $complete)\n {\n // Determine if the checksum needs to be calculated.\n if ($this->client->getConfig('signature_version') == 'v4') {\n $type = 'sha256';\n } elseif ($this->client->getConfig('calculate_md5')) {\n $type = 'md5';\n } else {\n return $stream;\n }\n\n // Decorate source with a hashing stream\n $hash = new PhpHash($type, ['base64' => true]);\n return new HashingStream($stream, $hash,\n function ($result) use ($type, $complete) {\n return $complete($result, $type);\n }\n );\n }\n}\n" }, { "alpha_fraction": 0.6429814696311951, "alphanum_fraction": 0.6573417782783508, "avg_line_length": 27.07329750061035, "blob_id": "9e562395ef59523c16046c80afbd859effcfc7ca", "content_id": "4a17e3712c1499485ed7831f6af426470d0631b3", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 16086, "license_type": "permissive", "max_line_length": 151, "num_lines": 573, "path": "/docs/configuration.rst", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "=============\nConfiguration\n=============\n\nThis guide describes client constructor options. These options can be provided\nin a client constructor or to the ``Aws\\Sdk`` class. The following example\nshows how to pass options into an Amazon S3 client constructor.\n\n.. code-block:: php\n\n use Aws\\S3\\S3Client;\n\n $options = [\n 'region' => 'us-west-2',\n 'version' => '2006-03-01',\n 'signature_version' => 'v4'\n ];\n\n $s3Client = new S3Client($options);\n\nRefer to the :doc:`basic usage guide <basic-usage>` for more\ninformation on constructing clients.\n\n\napi_provider\n~~~~~~~~~~~~\n\n:Type: ``callable``\n\nA PHP callable that accepts a type, service, and version argument, and returns\nan array of corresponding configuration data. The type value can be one of\n``api``, ``waiter``, or ``paginator``.\n\nBy default, the SDK will use an instance of ``Aws\\Api\\FileSystemApiProvider``\nthat loads credentials from the ``src/data`` folder of the SDK.\n\n\nclient\n~~~~~~\n\n:Type: ``callable|GuzzleHttp\\ClientInterface``\n\nA function that accepts an array of options and returns a\n``GuzzleHttp\\ClientInterface``, or a ``GuzzleHttp\\ClientInterface`` client used\nto transfer requests over the wire.\n\n.. note::\n\n If you do not specify a client and use the ``Aws\\Sdk`` class to create\n clients, then the SDK will create a new client that uses a shared Ring\n HTTP handler.\n\n.. code-block:: php\n\n use Aws\\S3\\S3Client;\n use GuzzleHttp\\Client;\n\n // Create a custom Guzzle client.\n $myClient = new Client();\n\n // Pass the Guzzle client into an Amazon S3 client.\n $s3 = new S3Client([\n 'version' => 'latest',\n 'region' => 'us-west-2',\n 'client' => $myClient\n ]);\n\n $clientFactory = function (array $options) {\n return new Client([\n // 'handler' => $myCustomHandler\n ]);\n };\n\n $s3 = new S3Client([\n 'version' => 'latest',\n 'region' => 'us-west-2',\n 'client' => $clientFactory\n ]);\n\n\ncredentials\n~~~~~~~~~~~\n\n:Type: ``array|Aws\\Credentials\\CredentialsInterface|bool|callable``\n\nIf you do not provide a ``credentials`` option, the SDK will attempt to load\ncredentials from your environment in the following order:\n\n1. Load credentials from :ref:`environment variables <environment_credentials>`\n2. Load credentials from a :ref:`credentials ini file <credential_profiles>`\n3. Load credentials from an :ref:`IAM instance profile <instance_profile_credentials>`.\n\nYou can provide an associative array of \"key\", \"secret\", and \"token\" key value\npairs to use :ref:`hardcoded credentials <hardcoded_credentials>`.\n\n.. code-block:: php\n\n // Hardcoded credentials.\n $s3 = new Aws\\S3\\S3Client([\n 'version' => 'latest',\n 'region' => 'us-west-2',\n 'credentials' => [\n 'key' => 'abc',\n 'secret' => '123'\n ]\n ]);\n\nPass an ``Aws\\Credentials\\CredentialsInterface`` object to use a specific\ncredentials instance.\n\n.. code-block:: php\n\n $credentials = new Aws\\Credentials\\Credentials('key', 'secret');\n\n $s3 = new Aws\\S3\\S3Client([\n 'version' => 'latest',\n 'region' => 'us-west-2',\n 'credentials' => $credentials\n ]);\n\nPass `false` to utilize null credentials and not sign requests.\n\n.. code-block:: php\n\n $s3 = new Aws\\S3\\S3Client([\n 'version' => 'latest',\n 'region' => 'us-west-2',\n 'credentials' => false\n ]);\n\nPass a callable :ref:`credential provider <credential_provider>` function to\ncreate credentials using a function.\n\n.. code-block:: php\n\n use Aws\\Credentials\\CredentialProvider;\n\n $provider = CredentialProvider::env();\n $s3 = new Aws\\S3\\S3Client([\n 'version' => 'latest',\n 'region' => 'us-west-2',\n 'credentials' => $provider\n ]);\n\nYou can find more information about providing credentials to a client in the\n:doc:`credentials` guide.\n\n\ndebug\n~~~~~\n\n:Type: ``bool|resource``\n\nSet to ``true`` to display debug information when sending requests. Provide a\nstream resource to write debug information to a specific resource.\n\nDebug information contains information about each state change of a transaction\nas it is prepared and sent over the wire. Also included in the debug output\nis information of the specific RingPHP adapter used by a client (e.g., debug\ncURL output).\n\n.. code-block:: php\n\n // Write debug output to STDOUT\n $s3 = new Aws\\S3\\S3Client([\n 'version' => 'latest',\n 'region' => 'us-west-2',\n 'debug' => true\n ]);\n\n $s3->listBuckets();\n\nRunning the above example will have output similar to\n:download:`this example <_downloads/debug-example.txt>`.\n\n\nendpoint\n~~~~~~~~\n\n:Type: ``string``\n\nThe full URI of the webservice. This is only required when connecting to a\ncustom endpoint (e.g., a local version of Amazon S3 or Amazon DynamoDB\nlocal).\n\nHere's an example of connecting to `Amazon DynamoDB Local <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tools.DynamoDBLocal.html>`_:\n\n.. code-block:: php\n\n $client = new Aws\\DynamoDb\\DynamoDbClient([\n 'version' => '2012-08-10',\n 'region' => 'us-east-1'\n 'endpoint' => 'http://localhost:8000'\n ]);\n\nSee http://docs.aws.amazon.com/general/latest/gr/rande.html for a list of\navailable regions and endpoints.\n\n\nendpoint_provider\n~~~~~~~~~~~~~~~~~\n\n:Type: ``callable``\n\nAn optional PHP callable that accepts a hash of options including a \"service\"\nand \"region\" key and returns ``NULL`` or a hash of endpoint data, of which the\n\"endpoint\" key is required.\n\n\nhttp\n~~~~\n\n:Type: ``array``\n\nSet to an array of Guzzle client request options (e.g., proxy, verify, etc.).\nSee http://docs.guzzlephp.org/en/latest/clients.html#request-options for a\nlist of available options. The following are examples of some of the more\ncommon request options you may need to set.\n\n\nSSL/TLS certificate verification\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nYou can customize the peer SSL/TLS certificate verification behavior of the SDK\nusing the ``verify`` ``http`` option.\n\n* Set to ``true`` to enable SSL/TLS peer certificate verification and use the\n default CA bundle provided by operating system.\n* Set to ``false`` to disable peer certificate verification (this is\n insecure!).\n* Set to a string to provide the path to a CA cert bundle to enable\n verification using a custom CA bundle.\n\nIf the CA bundle cannot be found for your system and you receive an error,\nthen you will need to provide the path to a CA bundle to the SDK. If you do not\nneed a specific CA bundle, then Mozilla provides a commonly used CA bundle\nwhich can be downloaded `here <https://raw.githubusercontent.com/bagder/ca-bundle/master/ca-bundle.crt>`_\n(this is maintained by the maintainer of cURL). Once you have a CA bundle\navailable on disk, you can set the ``openssl.cafile`` PHP ini setting to point\nto the path to the file, allowing you to omit the ``verify`` request option.\nMuch more detail on SSL certificates can be found on the\n`cURL website <http://curl.haxx.se/docs/sslcerts.html>`_.\n\n.. code-block:: php\n\n use Aws\\DynamoDb\\DynamoDbClient;\n\n // Use a custom CA bundle.\n $client = new DynamoDbClient([\n 'region' => 'us-west-2',\n 'version' => 'latest',\n 'http' => [\n 'verify' => '/path/to/my/cert.pem'\n ]\n ]);\n\n // Disable SSL/TLS verification.\n $client = new DynamoDbClient([\n 'region' => 'us-west-2',\n 'version' => 'latest',\n 'http' => [\n 'verify' => false\n ]\n ]);\n\n\nUsing a proxy\n^^^^^^^^^^^^^\n\nYou can connect to an AWS service through a proxy using the ``proxy`` ``http``\noption. You can provide proxy URLs that contain a scheme, username, and\npassword. For example, ``\"http://username:[email protected]:10\"``.\n\n.. code-block:: php\n\n use Aws\\DynamoDb\\DynamoDbClient;\n\n // Send requests through a proxy.\n $client = new DynamoDbClient([\n 'region' => 'us-west-2',\n 'version' => 'latest',\n 'http' => [\n 'proxy' => 'http://192.168.16.1:10'\n ]\n ]);\n\nYou can use the ``HTTP_PROXY`` environment variable to configure an \"http\"\nprotocol specific proxy, and the ``HTTPS_PROXY`` environment variable to\nconfigure an \"https\" specific proxy.\n\nSee http://docs.guzzlephp.org/en/latest/clients.html#proxy for more information\non configuring a Guzzle client proxy.\n\n\nTimeouts\n^^^^^^^^\n\nYou can modify the timeout settings of the SDK by configuring the ``timeout``\nand ``connect_timeout`` ``http`` options.\n\n``timeout`` is a float describing the timeout of the request in seconds. Use\n``0`` to wait indefinitely (the default behavior).\n\n.. code-block:: php\n\n use Aws\\DynamoDb\\DynamoDbClient;\n\n // Timeout after 5 seconds.\n $client = new DynamoDbClient([\n 'region' => 'us-west-2',\n 'version' => 'latest',\n 'http' => [\n 'timeout' => 5\n ]\n ]);\n\n``connect_timeout`` is a float describing the number of seconds to wait while\ntrying to connect to a server. Use 0 to wait indefinitely (the default\nbehavior).\n\n.. code-block:: php\n\n use Aws\\DynamoDb\\DynamoDbClient;\n\n // Timeout after attempting to connect for 5 seconds.\n $client = new DynamoDbClient([\n 'region' => 'us-west-2',\n 'version' => 'latest',\n 'http' => [\n 'connect_timeout' => 5\n ]\n ]);\n\n\nprofile\n~~~~~~~\n\n:Type: ``string``\n\nAllows you to specify which profile to use when credentials are created from\nthe AWS credentials file in your HOME directory. This setting overrides the\n``AWS_PROFILE`` environment variable. Note: Specifying \"profile\" will cause\nthe \"credentials\" key to be ignored.\n\n.. code-block:: php\n\n // Use the \"production\" profile from your credentials file.\n $ec2 = new Aws\\Ec2\\Ec2Client([\n 'version' => '2014-10-01',\n 'region' => 'us-west-2',\n 'profile' => 'production'\n ]);\n\nSee :doc:`credentials` for more information on configuring credentials and the\nINI file format.\n\n\n.. _cfg_region:\n\nregion\n~~~~~~\n\n:Type: ``string``\n:Required: true\n\nRegion to connect to. See http://docs.aws.amazon.com/general/latest/gr/rande.html\nfor a list of available regions.\n\n.. code-block:: php\n\n // Set the region to the EU (Frankfurt) region.\n $s3 = new Aws\\S3\\S3Client([\n 'region' => 'eu-central-1',\n 'version' => '2006-03-01'\n ]);\n\n\nretries\n~~~~~~~\n\n:Type: ``int``\n:Default: ``int(3)``\n\nConfigures the maximum number of allowed retries for a client. Pass ``0`` to\ndisable retries.\n\nThe following example disables retries for the Amazon DynamoDB client.\n\n.. code-block:: php\n\n // Disable retries by setting \"retries\" to 0\n $client = new Aws\\DynamoDb\\DynamoDbClient([\n 'version' => '2012-08-10',\n 'region' => 'us-west-2',\n 'retries' => 0\n ]);\n\n\nretry_logger\n~~~~~~~~~~~~\n\n:Type: ``string|Psr\\Log\\LoggerInterface``\n\nWhen the string \"debug\" is provided, all retries will be logged to STDOUT.\nProvide a `PSR-3 logger <http://www.php-fig.org/psr/psr-3/>`_ to log\nretries to a specific logger instance. A retry is typically triggered when a\nservice returns some type of throttling response.\n\nThe following example uses `Monolog <https://github.com/Seldaek/monolog>`_ to\nlog retries. Each time the SDK retries a request, the following information\nabout the retry is logged: timestamp, HTTP method, URI, status code, reason\nphrase, number of retries, connection time, total time, and error message.\n\n.. code-block:: php\n\n use Monolog\\Logger;\n use Monolog\\Handler\\StreamHandler;\n use Aws\\DynamoDb\\DynamoDbClient;\n\n $logger = new Logger('retries');\n $handler = new StreamHandler('path/to/your.log', Logger::WARNING);\n $logger->pushHandler($handler);\n\n $client = new DynamoDbClient([\n 'version' => '2012-08-10',\n 'region' => 'us-west-2',\n 'retry_logger' => $logger\n ]);\n\n\nscheme\n~~~~~~\n\n:Type: ``string``\n:Default: ``string(5) \"https\"``\n\nURI scheme to use when connecting connect. The SDK will utilize \"https\"\nendpoints (i.e., utilize SSL/TLS connections) by default. You can attempt to\nconnect to a service over an unencrypted \"http\" endpoint by setting ``scheme``\nto \"http\".\n\n.. code-block:: php\n\n $s3 = new Aws\\S3\\S3Client([\n 'version' => '2006-03-01',\n 'region' => 'us-west-2',\n 'scheme' => 'http'\n ]);\n\nSee http://docs.aws.amazon.com/general/latest/gr/rande.html for a list of\nendpoints whether or not a service supports the ``http`` scheme.\n\n\nservice\n~~~~~~~\n\n:Type: ``string``\n:Required: true\n\nName of the service to utilize. This value will be supplied by default when\nusing a client provided by the SDK (i.e., ``Aws\\S3\\S3Client``). This option\nis useful when testing a service that has not yet been published in the SDK\nbut you have available on disk.\n\n\nsignature_provider\n~~~~~~~~~~~~~~~~~~\n\n:Type: ``callable``\n\nA callable that accepts a signature version name (e.g., v4, s3), a service\nname, and region, and returns a ``Aws\\Signature\\SignatureInterface`` object or\n``NULL``. This provider is used to create signers utilized by the client.\n\nThere are various functions provided by the SDK in the\n``Aws\\Signature\\SignatureProvider`` class that can be used to create customized\nsignature providers.\n\n\nsignature_version\n~~~~~~~~~~~~~~~~~\n\n:Type: ``string``\n\nA string representing a custom signature version to use with a service\n(e.g., ``v4``, ``s3``, ``v2``, etc.). Note that per/operation signature version\nMAY override this requested signature version if needed.\n\nThe following examples show how to configure an Amazon S3 client to use\n`signature version 4 <http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html>`_:\n\n.. code-block:: php\n\n // Set a preferred signature version.\n $s3 = new Aws\\S3\\S3Client([\n 'version' => '2006-03-01',\n 'region' => 'us-west-2',\n 'signature_version' => 'v4'\n ]);\n\n.. note::\n\n The ``signature_provider`` used by your client MUST be able to create the\n ``signature_version`` option you provide. The default ``signature_provider``\n used by the SDK can create signature objects for \"v2\", \"v4\", and \"s3\"\n signature versions.\n\n\nvalidate\n~~~~~~~~\n\n:Type: ``bool``\n:Default: ``bool(true)``\n\nSet to false to disable client-side parameter validation. You may find that\nturning validation off will slightly improve client performance, but the\ndifference is negligible.\n\n.. code-block:: php\n\n // Disable client-side validation.\n $s3 = new Aws\\S3\\S3Client([\n 'version' => '2006-03-01',\n 'region' => 'eu-west-1',\n 'validate' => false\n ]);\n\n\n.. _cfg_version:\n\nversion\n~~~~~~~\n\n:Type: ``string``\n:Required: true\n\nThe version of the web service to utilize (e.g., ``2006-03-01``).\n\nA \"version\" configuration value is required. Specifying a version constraint\nensures that your code will not be affected by a breaking change made to the\nservice. For example, when using Amazon S3, you can lock your API version to\n``2006-03-01``.\n\n.. code-block:: php\n\n $s3 = new Aws\\S3\\S3Client([\n 'version' => '2006-03-01',\n 'region' => 'us-east-1'\n ]);\n\nA list of available API versions can be found on each client's API\ndocumentation page: http://docs.aws.amazon.com/aws-sdk-php/v3/api/index.html.\nIf you are unable to load a specific API version, then you may need to update\nyour copy of the SDK.\n\nYou may provide the string ``latest`` to the \"version\" configuration value to\nutilize the most recent available API version that your client's API provider\ncan find (the default api_provider will scan the ``src/data`` directory of the\nSDK for ``*.api.php`` and ``*.api.json`` files).\n\n.. code-block:: php\n\n // Use the latest version available.\n $s3 = new Aws\\S3\\S3Client([\n 'version' => 'latest',\n 'region' => 'us-east-1'\n ]);\n\n.. warning::\n\n Using ``latest`` in a production application is not recommended because\n pulling in a new minor version of the SDK that includes an API update could\n break your production application.\n" }, { "alpha_fraction": 0.5750979781150818, "alphanum_fraction": 0.578199028968811, "avg_line_length": 57.72852325439453, "blob_id": "8d9bab80bc6c5ac01a94b6f53eac7e2edbf15cd9", "content_id": "68cdf2cf7d5f84c2940addad3ac41f7ed151a98e", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 17091, "license_type": "permissive", "max_line_length": 122, "num_lines": 291, "path": "/docs/feature-dynamodb-session-handler.rst", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "========================\nDynamoDB Session Handler\n========================\n\nIntroduction\n------------\n\nThe **DynamoDB Session Handler** is a custom session handler for PHP that allows developers to use Amazon DynamoDB as a\nsession store. Using DynamoDB for session storage alleviates issues that occur with session handling in a distributed\nweb application by moving sessions off of the local file system and into a shared location. DynamoDB is fast, scalable,\neasy to setup, and handles replication of your data automatically.\n\nThe DynamoDB Session Handler uses the ``session_set_save_handler()`` function to hook DynamoDB operations into PHP's\n`native session functions <http://www.php.net/manual/en/ref.session.php>`_ to allow for a true drop in replacement. This\nincludes support for features like session locking and garbage collection which are a part of PHP's default session\nhandler.\n\nFor more information on the Amazon DynamoDB service, please visit the `Amazon DynamoDB homepage\n<http://aws.amazon.com/dynamodb>`_.\n\nBasic Usage\n-----------\n\n1. Register the handler\n~~~~~~~~~~~~~~~~~~~~~~~\n\nThe first step is to instantiate the Amazon DynamoDB client and register the session handler.\n\n.. code-block:: php\n\n require 'vendor/autoload.php';\n\n use Aws\\DynamoDb\\DynamoDbClient;\n\n $dynamoDb = DynamoDbClient::factory(array(\n 'key' => '<aws access key>',\n 'secret' => '<aws secret key>',\n 'region' => '<region name>'\n ));\n\n $sessionHandler = $dynamoDb->registerSessionHandler(array(\n 'table_name' => 'sessions'\n ));\n\nYou can also instantiate the ``SessionHandler`` object directly using it's ``factory`` method.\n\n.. code-block:: php\n\n require 'vendor/autoload.php';\n\n use Aws\\DynamoDb\\DynamoDbClient;\n use Aws\\DynamoDb\\Session\\SessionHandler;\n\n $dynamoDb = DynamoDbClient::factory(array(\n 'key' => '<aws access key>',\n 'secret' => '<aws secret key>',\n 'region' => '<region name>',\n ));\n\n $sessionHandler = SessionHandler::factory(array(\n 'dynamodb_client' => $dynamoDb,\n 'table_name' => 'sessions',\n ));\n $sessionHandler->register();\n\n2. Create a table for storing your sessions\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nBefore you can actually use the session handler, you need to create a table in which to store the sessions. This can be\ndone ahead of time through the `AWS Console for Amazon DynamoDB <https://console.aws.amazon.com/dynamodb/home>`_, or you\ncan use the session handler object (which you've already configured with the table name) by doing the following:\n\n.. code-block:: php\n\n $sessionHandler->createSessionsTable(5, 5);\n\nThe two parameters for this function are used to specify the read and write provisioned throughput for the table,\nrespectively.\n\n.. note::\n\n The ``createSessionsTable`` function uses the ``TableExists`` :doc:`waiter <waiters>` internally, so this\n function call will block until the table exists and is ready to be used.\n\n3. Use PHP sessions like normal\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nOnce the session handler is registered and the table exists, you can write to and read from the session using the\n``$_SESSION`` superglobal, just like you normally do with PHP's default session handler. The DynamoDB Session Handler\nencapsulates and abstracts the interactions with Amazon DynamoDB and enables you to simply use PHP's native session\nfunctions and interface.\n\n.. code-block:: php\n\n // Start the session\n session_start();\n\n // Alter the session data\n $_SESSION['user.name'] = 'jeremy';\n $_SESSION['user.role'] = 'admin';\n\n // Close the session (optional, but recommended)\n session_write_close();\n\nConfiguration\n-------------\n\nYou may configure the behavior of the session handler using the following options. All options are optional, but you\nshould make sure to understand what the defaults are.\n\n============================ ===========================================================================================\n``table_name`` The name of the DynamoDB table in which to store the sessions. This defaults to ``sessions``.\n---------------------------- -------------------------------------------------------------------------------------------\n``hash_key`` The name of the hash key in the DynamoDB sessions table. This defaults to ``id``.\n---------------------------- -------------------------------------------------------------------------------------------\n``session_lifetime`` The lifetime of an inactive session before it should be garbage collected. If it is not\n provided, then the actual lifetime value that will be used is\n ``ini_get('session.gc_maxlifetime')``.\n---------------------------- -------------------------------------------------------------------------------------------\n``consistent_read`` Whether or not the session handler should use consistent reads for the ``GetItem``\n operation. This defaults to ``true``.\n---------------------------- -------------------------------------------------------------------------------------------\n``locking_strategy`` The strategy used for doing session locking. By default the handler uses the\n ``NullLockingStrategy``, which means that session locking is **not** enabled (see the\n :ref:`ddbsh-session-locking` section for more information). Valid values for this option\n include null, 'null', 'pessemistic', or an instance of ``NullLockingStrategy`` or\n ``PessimisticLockingStrategy``.\n---------------------------- -------------------------------------------------------------------------------------------\n``automatic_gc`` Whether or not to use PHP's session auto garbage collection. This defaults to the value of\n ``(bool) ini_get('session.gc_probability')``, but the recommended value is ``false``. (see\n the :ref:`ddbsh-garbage-collection` section for more information).\n---------------------------- -------------------------------------------------------------------------------------------\n``gc_batch_size`` The batch size used for removing expired sessions during garbage collection. This defaults\n to ``25``, which is the maximum size of a single ``BatchWriteItem`` operation. This value\n should also take your provisioned throughput into account as well as the timing of your\n garbage collection.\n---------------------------- -------------------------------------------------------------------------------------------\n``gc_operation_delay`` The delay (in seconds) between service operations performed during garbage collection. This\n defaults to ``0``. Increasing this value allows you to throttle your own requests in an\n attempt to stay within your provisioned throughput capacity during garbage collection.\n---------------------------- -------------------------------------------------------------------------------------------\n``max_lock_wait_time`` Maximum time (in seconds) that the session handler should wait to acquire a lock before\n giving up. This defaults to ``10`` and is only used with the ``PessimisticLockingStrategy``.\n---------------------------- -------------------------------------------------------------------------------------------\n``min_lock_retry_microtime`` Minimum time (in microseconds) that the session handler should wait between attempts\n to acquire a lock. This defaults to ``10000`` and is only used with the\n ``PessimisticLockingStrategy``.\n---------------------------- -------------------------------------------------------------------------------------------\n``max_lock_retry_microtime`` Maximum time (in microseconds) that the session handler should wait between attempts\n to acquire a lock. This defaults to ``50000`` and is only used with the\n ``PessimisticLockingStrategy``.\n---------------------------- -------------------------------------------------------------------------------------------\n``dynamodb_client`` The ``DynamoDbClient`` object that should be used for performing DynamoDB operations. If\n you register the session handler from a client object using the ``registerSessionHandler()``\n method, this will default to the client you are registering it from. If using the\n ``SessionHandler::factory()`` method, you are required to provide an instance of\n ``DynamoDbClient``.\n============================ ===========================================================================================\n\nTo configure the Session Handler, you must specify the configuration options when you instantiate the handler. The\nfollowing code is an example with all of the configuration options specified.\n\n.. code-block:: php\n\n $sessionHandler = $dynamoDb->registerSessionHandler(array(\n 'table_name' => 'sessions',\n 'hash_key' => 'id',\n 'session_lifetime' => 3600,\n 'consistent_read' => true,\n 'locking_strategy' => null,\n 'automatic_gc' => 0,\n 'gc_batch_size' => 50,\n 'max_lock_wait_time' => 15,\n 'min_lock_retry_microtime' => 5000,\n 'max_lock_retry_microtime' => 50000,\n ));\n\nPricing\n-------\n\nAside from data storage and data transfer fees, the costs associated with using Amazon DynamoDB are calculated based on\nthe provisioned throughput capacity of your table (see the `Amazon DynamoDB pricing details\n<http://aws.amazon.com/dynamodb/#pricing>`_). Throughput is measured in units of Write Capacity and Read Capacity. The\nAmazon DynamoDB homepage says:\n\n A unit of Write Capacity enables you to perform one write per second for items of up to 1KB in size. Similarly, a\n unit of Read Capacity enables you to perform one strongly consistent read per second (or two eventually consistent\n reads per second) of items of up to 1KB in size. Larger items will require more capacity. You can calculate the\n number of units of read and write capacity you need by estimating the number of reads or writes you need to do per\n second and multiplying by the size of your items (rounded up to the nearest KB).\n\nUltimately, the throughput and the costs required for your sessions table is going to correlate with your expected\ntraffic and session size. The following table explains the amount of read and write operations that are performed on\nyour DynamoDB table for each of the session functions.\n\n+----------------------------------------+-----------------------------------------------------------------------------+\n| Read via ``session_start()`` | * 1 read operation (only 0.5 if ``consistent_read`` is ``false``). |\n| (Using ``NullLockingStrategy``) | * (Conditional) 1 write operation to delete the session if it is expired. |\n+----------------------------------------+-----------------------------------------------------------------------------+\n| Read via ``session_start()`` | * A minimum of 1 *write* operation. |\n| (Using ``PessimisticLockingStrategy``) | * (Conditional) Additional write operations for each attempt at acquiring a |\n| | lock on the session. Based on configured lock wait time and retry options.|\n| | * (Conditional) 1 write operation to delete the session if it is expired. |\n+----------------------------------------+-----------------------------------------------------------------------------+\n| Write via ``session_write_close()`` | * 1 write operation. |\n+----------------------------------------+-----------------------------------------------------------------------------+\n| Delete via ``session_destroy()`` | * 1 write operation. |\n+----------------------------------------+-----------------------------------------------------------------------------+\n| Garbage Collection | * 0.5 read operations **per KB of data in the table** to scan for expired |\n| | sessions. |\n| | * 1 write operation **per expired item** to delete it. |\n+----------------------------------------+-----------------------------------------------------------------------------+\n\n.. _ddbsh-session-locking:\n\nSession Locking\n---------------\n\nThe DynamoDB Session Handler supports pessimistic session locking in order to mimic the behavior of PHP's default\nsession handler. By default the DynamoDB Session Handler has this feature *turned off* since it can become a performance\nbottleneck and drive up costs, especially when an application accesses the session when using ajax requests or iframes.\nYou should carefully consider whether or not your application requires session locking or not before enabling it.\n\nBy default the session handler uses the ``NullLockingStrategy`` which does not do any session locking. To enable session\nlocking, you should use the ``PessimisticLockingStrategy``, which can be specified when the session handler is created.\n\n.. code-block:: php\n\n $sessionHandler = $dynamoDb->registerSessionHandler(array(\n 'table_name' => 'sessions',\n 'locking_strategy' => 'pessimistic',\n ));\n\n.. _ddbsh-garbage-collection:\n\nGarbage Collection\n------------------\n\nThe DynamoDB Session Handler supports session garbage collection by using a series of ``Scan`` and ``BatchWriteItem``\noperations. Due to the nature of how the ``Scan`` operation works and in order to find all of the expired sessions and\ndelete them, the garbage collection process can require a lot of provisioned throughput.\n\nFor this reason it is discouraged to rely on the PHP's normal session garbage collection triggers (i.e., the\n``session.gc_probability`` and ``session.gc_divisor`` ini settings). A better practice is to set\n``session.gc_probability`` to ``0`` and schedule the garbage collection to occur during an off-peak time where a\nburst of consumed throughput will not disrupt the rest of the application.\n\nFor example, you could have a nightly cron job trigger a script to run the garbage collection. This script might look\nsomething like the following:\n\n.. code-block:: php\n\n require 'vendor/autoload.php';\n\n use Aws\\DynamoDb\\DynamoDbClient;\n use Aws\\DynamoDb\\Session\\SessionHandler;\n\n $dynamoDb = DynamoDbClient::factory(array(\n 'key' => '<aws access key>',\n 'secret' => '<aws secret key>',\n 'region' => '<region name>',\n ));\n\n $sessionHandler = SessionHandler::factory(array(\n 'dynamodb_client' => $dynamoDb,\n 'table_name' => 'sessions',\n ));\n\n $sessionHandler->garbageCollect();\n\nYou can also use the ``gc_operation_delay`` configuration option on the session handler to introduce delays in between\nthe ``Scan`` and ``BatchWriteItem`` operations that are performed by the garbage collection process. This will increase\nthe amount of time it takes the garbage collection to complete, but it can help you spread out the requests made by the\nsession handler in order to help you stay close to or within your provisioned throughput capacity during garbage\ncollection.\n\nBest Practices\n--------------\n\n#. Create your sessions table in a region that is geographically closest to or in the same region as your application\n servers. This will ensure the lowest latency between your application and DynamoDB database.\n#. Choose the provisioned throughput capacity of your sessions table carefully, taking into account the expected traffic\n to your application and the expected size of your sessions.\n#. Monitor your consumed throughput through the AWS Management Console or with Amazon CloudWatch and adjust your\n throughput settings as needed to meet the demands of your application.\n#. Keep the size of your sessions small. Sessions that are less than 1KB will perform better and require less\n provisioned throughput capacity.\n#. Do not use session locking unless your application requires it.\n#. Instead of using PHP's built-in session garbage collection triggers, schedule your garbage collection via a cron job,\n or another scheduling mechanism, to run during off-peak hours. Use the ``gc_operation_delay`` option to add delays\n in between the requests performed for the garbage collection process.\n\n" }, { "alpha_fraction": 0.42868444323539734, "alphanum_fraction": 0.4297092854976654, "avg_line_length": 22.963376998901367, "blob_id": "4ba8b29666886d7d3e7f66e6e6a9dfbe9ea08220", "content_id": "11e1dba58091fafd81aee30b3cf16cce0d60a8fe", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 55619, "license_type": "permissive", "max_line_length": 63, "num_lines": 2321, "path": "/src/data/codedeploy-2014-10-06.api.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php return [\n 'metadata' => [\n 'apiVersion' => '2014-10-06',\n 'endpointPrefix' => 'codedeploy',\n 'jsonVersion' => '1.1',\n 'serviceAbbreviation' => 'CodeDeploy',\n 'serviceFullName' => 'AWS CodeDeploy',\n 'signatureVersion' => 'v4',\n 'targetPrefix' => 'CodeDeploy_20141006',\n 'timestampFormat' => 'unixTimestamp',\n 'protocol' => 'json',\n ],\n 'operations' => [\n 'BatchGetApplications' => [\n 'name' => 'BatchGetApplications',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'BatchGetApplicationsInput',\n ],\n 'output' => [\n 'shape' => 'BatchGetApplicationsOutput',\n ],\n 'errors' => [\n [\n 'shape' => 'ApplicationNameRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidApplicationNameException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ApplicationDoesNotExistException',\n 'exception' => true,\n ],\n ],\n ],\n 'BatchGetDeployments' => [\n 'name' => 'BatchGetDeployments',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'BatchGetDeploymentsInput',\n ],\n 'output' => [\n 'shape' => 'BatchGetDeploymentsOutput',\n ],\n 'errors' => [\n [\n 'shape' => 'DeploymentIdRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidDeploymentIdException',\n 'exception' => true,\n ],\n ],\n ],\n 'CreateApplication' => [\n 'name' => 'CreateApplication',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateApplicationInput',\n ],\n 'output' => [\n 'shape' => 'CreateApplicationOutput',\n ],\n 'errors' => [\n [\n 'shape' => 'ApplicationNameRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidApplicationNameException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ApplicationAlreadyExistsException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ApplicationLimitExceededException',\n 'exception' => true,\n ],\n ],\n ],\n 'CreateDeployment' => [\n 'name' => 'CreateDeployment',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateDeploymentInput',\n ],\n 'output' => [\n 'shape' => 'CreateDeploymentOutput',\n ],\n 'errors' => [\n [\n 'shape' => 'ApplicationNameRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidApplicationNameException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ApplicationDoesNotExistException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentGroupNameRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidDeploymentGroupNameException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentGroupDoesNotExistException',\n 'exception' => true,\n ],\n [\n 'shape' => 'RevisionRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidRevisionException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidDeploymentConfigNameException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentConfigDoesNotExistException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DescriptionTooLongException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentLimitExceededException',\n 'exception' => true,\n ],\n ],\n ],\n 'CreateDeploymentConfig' => [\n 'name' => 'CreateDeploymentConfig',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateDeploymentConfigInput',\n ],\n 'output' => [\n 'shape' => 'CreateDeploymentConfigOutput',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidDeploymentConfigNameException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentConfigNameRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentConfigAlreadyExistsException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidMinimumHealthyHostValueException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentConfigLimitExceededException',\n 'exception' => true,\n ],\n ],\n ],\n 'CreateDeploymentGroup' => [\n 'name' => 'CreateDeploymentGroup',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateDeploymentGroupInput',\n ],\n 'output' => [\n 'shape' => 'CreateDeploymentGroupOutput',\n ],\n 'errors' => [\n [\n 'shape' => 'ApplicationNameRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidApplicationNameException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ApplicationDoesNotExistException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentGroupNameRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidDeploymentGroupNameException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentGroupAlreadyExistsException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidEC2TagException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidAutoScalingGroupException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidDeploymentConfigNameException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentConfigDoesNotExistException',\n 'exception' => true,\n ],\n [\n 'shape' => 'RoleRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidRoleException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentGroupLimitExceededException',\n 'exception' => true,\n ],\n ],\n ],\n 'DeleteApplication' => [\n 'name' => 'DeleteApplication',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteApplicationInput',\n ],\n 'errors' => [\n [\n 'shape' => 'ApplicationNameRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidApplicationNameException',\n 'exception' => true,\n ],\n ],\n ],\n 'DeleteDeploymentConfig' => [\n 'name' => 'DeleteDeploymentConfig',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteDeploymentConfigInput',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidDeploymentConfigNameException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentConfigNameRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentConfigInUseException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidOperationException',\n 'exception' => true,\n ],\n ],\n ],\n 'DeleteDeploymentGroup' => [\n 'name' => 'DeleteDeploymentGroup',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteDeploymentGroupInput',\n ],\n 'output' => [\n 'shape' => 'DeleteDeploymentGroupOutput',\n ],\n 'errors' => [\n [\n 'shape' => 'ApplicationNameRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidApplicationNameException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentGroupNameRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidDeploymentGroupNameException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidRoleException',\n 'exception' => true,\n ],\n ],\n ],\n 'GetApplication' => [\n 'name' => 'GetApplication',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'GetApplicationInput',\n ],\n 'output' => [\n 'shape' => 'GetApplicationOutput',\n ],\n 'errors' => [\n [\n 'shape' => 'ApplicationNameRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidApplicationNameException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ApplicationDoesNotExistException',\n 'exception' => true,\n ],\n ],\n ],\n 'GetApplicationRevision' => [\n 'name' => 'GetApplicationRevision',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'GetApplicationRevisionInput',\n ],\n 'output' => [\n 'shape' => 'GetApplicationRevisionOutput',\n ],\n 'errors' => [\n [\n 'shape' => 'ApplicationDoesNotExistException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ApplicationNameRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidApplicationNameException',\n 'exception' => true,\n ],\n [\n 'shape' => 'RevisionDoesNotExistException',\n 'exception' => true,\n ],\n [\n 'shape' => 'RevisionRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidRevisionException',\n 'exception' => true,\n ],\n ],\n ],\n 'GetDeployment' => [\n 'name' => 'GetDeployment',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'GetDeploymentInput',\n ],\n 'output' => [\n 'shape' => 'GetDeploymentOutput',\n ],\n 'errors' => [\n [\n 'shape' => 'DeploymentIdRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidDeploymentIdException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentDoesNotExistException',\n 'exception' => true,\n ],\n ],\n ],\n 'GetDeploymentConfig' => [\n 'name' => 'GetDeploymentConfig',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'GetDeploymentConfigInput',\n ],\n 'output' => [\n 'shape' => 'GetDeploymentConfigOutput',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidDeploymentConfigNameException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentConfigNameRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentConfigDoesNotExistException',\n 'exception' => true,\n ],\n ],\n ],\n 'GetDeploymentGroup' => [\n 'name' => 'GetDeploymentGroup',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'GetDeploymentGroupInput',\n ],\n 'output' => [\n 'shape' => 'GetDeploymentGroupOutput',\n ],\n 'errors' => [\n [\n 'shape' => 'ApplicationNameRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidApplicationNameException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ApplicationDoesNotExistException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentGroupNameRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidDeploymentGroupNameException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentGroupDoesNotExistException',\n 'exception' => true,\n ],\n ],\n ],\n 'GetDeploymentInstance' => [\n 'name' => 'GetDeploymentInstance',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'GetDeploymentInstanceInput',\n ],\n 'output' => [\n 'shape' => 'GetDeploymentInstanceOutput',\n ],\n 'errors' => [\n [\n 'shape' => 'DeploymentIdRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentDoesNotExistException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InstanceIdRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidDeploymentIdException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InstanceDoesNotExistException',\n 'exception' => true,\n ],\n ],\n ],\n 'ListApplicationRevisions' => [\n 'name' => 'ListApplicationRevisions',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ListApplicationRevisionsInput',\n ],\n 'output' => [\n 'shape' => 'ListApplicationRevisionsOutput',\n ],\n 'errors' => [\n [\n 'shape' => 'ApplicationDoesNotExistException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ApplicationNameRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidApplicationNameException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidSortByException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidSortOrderException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidBucketNameFilterException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidKeyPrefixFilterException',\n 'exception' => true,\n ],\n [\n 'shape' => 'BucketNameFilterRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidDeployedStateFilterException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidNextTokenException',\n 'exception' => true,\n ],\n ],\n ],\n 'ListApplications' => [\n 'name' => 'ListApplications',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ListApplicationsInput',\n ],\n 'output' => [\n 'shape' => 'ListApplicationsOutput',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidNextTokenException',\n 'exception' => true,\n ],\n ],\n ],\n 'ListDeploymentConfigs' => [\n 'name' => 'ListDeploymentConfigs',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ListDeploymentConfigsInput',\n ],\n 'output' => [\n 'shape' => 'ListDeploymentConfigsOutput',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidNextTokenException',\n 'exception' => true,\n ],\n ],\n ],\n 'ListDeploymentGroups' => [\n 'name' => 'ListDeploymentGroups',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ListDeploymentGroupsInput',\n ],\n 'output' => [\n 'shape' => 'ListDeploymentGroupsOutput',\n ],\n 'errors' => [\n [\n 'shape' => 'ApplicationNameRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidApplicationNameException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ApplicationDoesNotExistException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidNextTokenException',\n 'exception' => true,\n ],\n ],\n ],\n 'ListDeploymentInstances' => [\n 'name' => 'ListDeploymentInstances',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ListDeploymentInstancesInput',\n ],\n 'output' => [\n 'shape' => 'ListDeploymentInstancesOutput',\n ],\n 'errors' => [\n [\n 'shape' => 'DeploymentIdRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentDoesNotExistException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentNotStartedException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidNextTokenException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidDeploymentIdException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidInstanceStatusException',\n 'exception' => true,\n ],\n ],\n ],\n 'ListDeployments' => [\n 'name' => 'ListDeployments',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ListDeploymentsInput',\n ],\n 'output' => [\n 'shape' => 'ListDeploymentsOutput',\n ],\n 'errors' => [\n [\n 'shape' => 'ApplicationNameRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidApplicationNameException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ApplicationDoesNotExistException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidDeploymentGroupNameException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentGroupDoesNotExistException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentGroupNameRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidTimeRangeException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidDeploymentStatusException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidNextTokenException',\n 'exception' => true,\n ],\n ],\n ],\n 'RegisterApplicationRevision' => [\n 'name' => 'RegisterApplicationRevision',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'RegisterApplicationRevisionInput',\n ],\n 'errors' => [\n [\n 'shape' => 'ApplicationDoesNotExistException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ApplicationNameRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidApplicationNameException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DescriptionTooLongException',\n 'exception' => true,\n ],\n [\n 'shape' => 'RevisionRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidRevisionException',\n 'exception' => true,\n ],\n ],\n ],\n 'StopDeployment' => [\n 'name' => 'StopDeployment',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'StopDeploymentInput',\n ],\n 'output' => [\n 'shape' => 'StopDeploymentOutput',\n ],\n 'errors' => [\n [\n 'shape' => 'DeploymentIdRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentDoesNotExistException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentAlreadyCompletedException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidDeploymentIdException',\n 'exception' => true,\n ],\n ],\n ],\n 'UpdateApplication' => [\n 'name' => 'UpdateApplication',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'UpdateApplicationInput',\n ],\n 'errors' => [\n [\n 'shape' => 'ApplicationNameRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidApplicationNameException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ApplicationAlreadyExistsException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ApplicationDoesNotExistException',\n 'exception' => true,\n ],\n ],\n ],\n 'UpdateDeploymentGroup' => [\n 'name' => 'UpdateDeploymentGroup',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'UpdateDeploymentGroupInput',\n ],\n 'output' => [\n 'shape' => 'UpdateDeploymentGroupOutput',\n ],\n 'errors' => [\n [\n 'shape' => 'ApplicationNameRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidApplicationNameException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ApplicationDoesNotExistException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidDeploymentGroupNameException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentGroupAlreadyExistsException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentGroupNameRequiredException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidEC2TagException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidAutoScalingGroupException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidDeploymentConfigNameException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DeploymentConfigDoesNotExistException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidRoleException',\n 'exception' => true,\n ],\n ],\n ],\n ],\n 'shapes' => [\n 'ApplicationAlreadyExistsException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'ApplicationDoesNotExistException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'ApplicationId' => [\n 'type' => 'string',\n ],\n 'ApplicationInfo' => [\n 'type' => 'structure',\n 'members' => [\n 'applicationId' => [\n 'shape' => 'ApplicationId',\n ],\n 'applicationName' => [\n 'shape' => 'ApplicationName',\n ],\n 'createTime' => [\n 'shape' => 'Timestamp',\n ],\n 'linkedToGitHub' => [\n 'shape' => 'Boolean',\n ],\n ],\n ],\n 'ApplicationLimitExceededException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'ApplicationName' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 100,\n ],\n 'ApplicationNameRequiredException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'ApplicationRevisionSortBy' => [\n 'type' => 'string',\n 'enum' => [\n 'registerTime',\n 'firstUsedTime',\n 'lastUsedTime',\n ],\n ],\n 'ApplicationsInfoList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'ApplicationInfo',\n ],\n ],\n 'ApplicationsList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'ApplicationName',\n ],\n ],\n 'AutoScalingGroup' => [\n 'type' => 'structure',\n 'members' => [\n 'name' => [\n 'shape' => 'AutoScalingGroupName',\n ],\n 'hook' => [\n 'shape' => 'AutoScalingGroupHook',\n ],\n ],\n ],\n 'AutoScalingGroupHook' => [\n 'type' => 'string',\n ],\n 'AutoScalingGroupList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'AutoScalingGroup',\n ],\n ],\n 'AutoScalingGroupName' => [\n 'type' => 'string',\n ],\n 'AutoScalingGroupNameList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'AutoScalingGroupName',\n ],\n ],\n 'BatchGetApplicationsInput' => [\n 'type' => 'structure',\n 'members' => [\n 'applicationNames' => [\n 'shape' => 'ApplicationsList',\n ],\n ],\n ],\n 'BatchGetApplicationsOutput' => [\n 'type' => 'structure',\n 'members' => [\n 'applicationsInfo' => [\n 'shape' => 'ApplicationsInfoList',\n ],\n ],\n ],\n 'BatchGetDeploymentsInput' => [\n 'type' => 'structure',\n 'members' => [\n 'deploymentIds' => [\n 'shape' => 'DeploymentsList',\n ],\n ],\n ],\n 'BatchGetDeploymentsOutput' => [\n 'type' => 'structure',\n 'members' => [\n 'deploymentsInfo' => [\n 'shape' => 'DeploymentsInfoList',\n ],\n ],\n ],\n 'Boolean' => [\n 'type' => 'boolean',\n ],\n 'BucketNameFilterRequiredException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'BundleType' => [\n 'type' => 'string',\n 'enum' => [\n 'tar',\n 'tgz',\n 'zip',\n ],\n ],\n 'CommitId' => [\n 'type' => 'string',\n ],\n 'CreateApplicationInput' => [\n 'type' => 'structure',\n 'required' => [\n 'applicationName',\n ],\n 'members' => [\n 'applicationName' => [\n 'shape' => 'ApplicationName',\n ],\n ],\n ],\n 'CreateApplicationOutput' => [\n 'type' => 'structure',\n 'members' => [\n 'applicationId' => [\n 'shape' => 'ApplicationId',\n ],\n ],\n ],\n 'CreateDeploymentConfigInput' => [\n 'type' => 'structure',\n 'required' => [\n 'deploymentConfigName',\n ],\n 'members' => [\n 'deploymentConfigName' => [\n 'shape' => 'DeploymentConfigName',\n ],\n 'minimumHealthyHosts' => [\n 'shape' => 'MinimumHealthyHosts',\n ],\n ],\n ],\n 'CreateDeploymentConfigOutput' => [\n 'type' => 'structure',\n 'members' => [\n 'deploymentConfigId' => [\n 'shape' => 'DeploymentConfigId',\n ],\n ],\n ],\n 'CreateDeploymentGroupInput' => [\n 'type' => 'structure',\n 'required' => [\n 'applicationName',\n 'deploymentGroupName',\n ],\n 'members' => [\n 'applicationName' => [\n 'shape' => 'ApplicationName',\n ],\n 'deploymentGroupName' => [\n 'shape' => 'DeploymentGroupName',\n ],\n 'deploymentConfigName' => [\n 'shape' => 'DeploymentConfigName',\n ],\n 'ec2TagFilters' => [\n 'shape' => 'EC2TagFilterList',\n ],\n 'autoScalingGroups' => [\n 'shape' => 'AutoScalingGroupNameList',\n ],\n 'serviceRoleArn' => [\n 'shape' => 'Role',\n ],\n ],\n ],\n 'CreateDeploymentGroupOutput' => [\n 'type' => 'structure',\n 'members' => [\n 'deploymentGroupId' => [\n 'shape' => 'DeploymentGroupId',\n ],\n ],\n ],\n 'CreateDeploymentInput' => [\n 'type' => 'structure',\n 'required' => [\n 'applicationName',\n ],\n 'members' => [\n 'applicationName' => [\n 'shape' => 'ApplicationName',\n ],\n 'deploymentGroupName' => [\n 'shape' => 'DeploymentGroupName',\n ],\n 'revision' => [\n 'shape' => 'RevisionLocation',\n ],\n 'deploymentConfigName' => [\n 'shape' => 'DeploymentConfigName',\n ],\n 'description' => [\n 'shape' => 'Description',\n ],\n 'ignoreApplicationStopFailures' => [\n 'shape' => 'Boolean',\n ],\n ],\n ],\n 'CreateDeploymentOutput' => [\n 'type' => 'structure',\n 'members' => [\n 'deploymentId' => [\n 'shape' => 'DeploymentId',\n ],\n ],\n ],\n 'DeleteApplicationInput' => [\n 'type' => 'structure',\n 'required' => [\n 'applicationName',\n ],\n 'members' => [\n 'applicationName' => [\n 'shape' => 'ApplicationName',\n ],\n ],\n ],\n 'DeleteDeploymentConfigInput' => [\n 'type' => 'structure',\n 'required' => [\n 'deploymentConfigName',\n ],\n 'members' => [\n 'deploymentConfigName' => [\n 'shape' => 'DeploymentConfigName',\n ],\n ],\n ],\n 'DeleteDeploymentGroupInput' => [\n 'type' => 'structure',\n 'required' => [\n 'applicationName',\n 'deploymentGroupName',\n ],\n 'members' => [\n 'applicationName' => [\n 'shape' => 'ApplicationName',\n ],\n 'deploymentGroupName' => [\n 'shape' => 'DeploymentGroupName',\n ],\n ],\n ],\n 'DeleteDeploymentGroupOutput' => [\n 'type' => 'structure',\n 'members' => [\n 'hooksNotCleanedUp' => [\n 'shape' => 'AutoScalingGroupList',\n ],\n ],\n ],\n 'DeploymentAlreadyCompletedException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'DeploymentConfigAlreadyExistsException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'DeploymentConfigDoesNotExistException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'DeploymentConfigId' => [\n 'type' => 'string',\n ],\n 'DeploymentConfigInUseException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'DeploymentConfigInfo' => [\n 'type' => 'structure',\n 'members' => [\n 'deploymentConfigId' => [\n 'shape' => 'DeploymentConfigId',\n ],\n 'deploymentConfigName' => [\n 'shape' => 'DeploymentConfigName',\n ],\n 'minimumHealthyHosts' => [\n 'shape' => 'MinimumHealthyHosts',\n ],\n 'createTime' => [\n 'shape' => 'Timestamp',\n ],\n ],\n ],\n 'DeploymentConfigLimitExceededException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'DeploymentConfigName' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 100,\n ],\n 'DeploymentConfigNameRequiredException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'DeploymentConfigsList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'DeploymentConfigName',\n ],\n ],\n 'DeploymentCreator' => [\n 'type' => 'string',\n 'enum' => [\n 'user',\n 'autoscaling',\n ],\n ],\n 'DeploymentDoesNotExistException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'DeploymentGroupAlreadyExistsException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'DeploymentGroupDoesNotExistException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'DeploymentGroupId' => [\n 'type' => 'string',\n ],\n 'DeploymentGroupInfo' => [\n 'type' => 'structure',\n 'members' => [\n 'applicationName' => [\n 'shape' => 'ApplicationName',\n ],\n 'deploymentGroupId' => [\n 'shape' => 'DeploymentGroupId',\n ],\n 'deploymentGroupName' => [\n 'shape' => 'DeploymentGroupName',\n ],\n 'deploymentConfigName' => [\n 'shape' => 'DeploymentConfigName',\n ],\n 'ec2TagFilters' => [\n 'shape' => 'EC2TagFilterList',\n ],\n 'autoScalingGroups' => [\n 'shape' => 'AutoScalingGroupList',\n ],\n 'serviceRoleArn' => [\n 'shape' => 'Role',\n ],\n 'targetRevision' => [\n 'shape' => 'RevisionLocation',\n ],\n ],\n ],\n 'DeploymentGroupLimitExceededException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'DeploymentGroupName' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 100,\n ],\n 'DeploymentGroupNameRequiredException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'DeploymentGroupsList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'DeploymentGroupName',\n ],\n ],\n 'DeploymentId' => [\n 'type' => 'string',\n ],\n 'DeploymentIdRequiredException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'DeploymentInfo' => [\n 'type' => 'structure',\n 'members' => [\n 'applicationName' => [\n 'shape' => 'ApplicationName',\n ],\n 'deploymentGroupName' => [\n 'shape' => 'DeploymentGroupName',\n ],\n 'deploymentConfigName' => [\n 'shape' => 'DeploymentConfigName',\n ],\n 'deploymentId' => [\n 'shape' => 'DeploymentId',\n ],\n 'revision' => [\n 'shape' => 'RevisionLocation',\n ],\n 'status' => [\n 'shape' => 'DeploymentStatus',\n ],\n 'errorInformation' => [\n 'shape' => 'ErrorInformation',\n ],\n 'createTime' => [\n 'shape' => 'Timestamp',\n ],\n 'startTime' => [\n 'shape' => 'Timestamp',\n ],\n 'completeTime' => [\n 'shape' => 'Timestamp',\n ],\n 'deploymentOverview' => [\n 'shape' => 'DeploymentOverview',\n ],\n 'description' => [\n 'shape' => 'Description',\n ],\n 'creator' => [\n 'shape' => 'DeploymentCreator',\n ],\n 'ignoreApplicationStopFailures' => [\n 'shape' => 'Boolean',\n ],\n ],\n ],\n 'DeploymentLimitExceededException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'DeploymentNotStartedException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'DeploymentOverview' => [\n 'type' => 'structure',\n 'members' => [\n 'Pending' => [\n 'shape' => 'InstanceCount',\n ],\n 'InProgress' => [\n 'shape' => 'InstanceCount',\n ],\n 'Succeeded' => [\n 'shape' => 'InstanceCount',\n ],\n 'Failed' => [\n 'shape' => 'InstanceCount',\n ],\n 'Skipped' => [\n 'shape' => 'InstanceCount',\n ],\n ],\n ],\n 'DeploymentStatus' => [\n 'type' => 'string',\n 'enum' => [\n 'Created',\n 'Queued',\n 'InProgress',\n 'Succeeded',\n 'Failed',\n 'Stopped',\n ],\n ],\n 'DeploymentStatusList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'DeploymentStatus',\n ],\n ],\n 'DeploymentsInfoList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'DeploymentInfo',\n ],\n ],\n 'DeploymentsList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'DeploymentId',\n ],\n ],\n 'Description' => [\n 'type' => 'string',\n ],\n 'DescriptionTooLongException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'Diagnostics' => [\n 'type' => 'structure',\n 'members' => [\n 'errorCode' => [\n 'shape' => 'LifecycleErrorCode',\n ],\n 'scriptName' => [\n 'shape' => 'ScriptName',\n ],\n 'message' => [\n 'shape' => 'LifecycleMessage',\n ],\n 'logTail' => [\n 'shape' => 'LogTail',\n ],\n ],\n ],\n 'EC2TagFilter' => [\n 'type' => 'structure',\n 'members' => [\n 'Key' => [\n 'shape' => 'Key',\n ],\n 'Value' => [\n 'shape' => 'Value',\n ],\n 'Type' => [\n 'shape' => 'EC2TagFilterType',\n ],\n ],\n ],\n 'EC2TagFilterList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'EC2TagFilter',\n ],\n ],\n 'EC2TagFilterType' => [\n 'type' => 'string',\n 'enum' => [\n 'KEY_ONLY',\n 'VALUE_ONLY',\n 'KEY_AND_VALUE',\n ],\n ],\n 'ETag' => [\n 'type' => 'string',\n ],\n 'ErrorCode' => [\n 'type' => 'string',\n 'enum' => [\n 'DEPLOYMENT_GROUP_MISSING',\n 'APPLICATION_MISSING',\n 'REVISION_MISSING',\n 'IAM_ROLE_MISSING',\n 'IAM_ROLE_PERMISSIONS',\n 'OVER_MAX_INSTANCES',\n 'NO_INSTANCES',\n 'TIMEOUT',\n 'HEALTH_CONSTRAINTS_INVALID',\n 'HEALTH_CONSTRAINTS',\n 'INTERNAL_ERROR',\n ],\n ],\n 'ErrorInformation' => [\n 'type' => 'structure',\n 'members' => [\n 'code' => [\n 'shape' => 'ErrorCode',\n ],\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n ],\n 'ErrorMessage' => [\n 'type' => 'string',\n ],\n 'GenericRevisionInfo' => [\n 'type' => 'structure',\n 'members' => [\n 'description' => [\n 'shape' => 'Description',\n ],\n 'deploymentGroups' => [\n 'shape' => 'DeploymentGroupsList',\n ],\n 'firstUsedTime' => [\n 'shape' => 'Timestamp',\n ],\n 'lastUsedTime' => [\n 'shape' => 'Timestamp',\n ],\n 'registerTime' => [\n 'shape' => 'Timestamp',\n ],\n ],\n ],\n 'GetApplicationInput' => [\n 'type' => 'structure',\n 'required' => [\n 'applicationName',\n ],\n 'members' => [\n 'applicationName' => [\n 'shape' => 'ApplicationName',\n ],\n ],\n ],\n 'GetApplicationOutput' => [\n 'type' => 'structure',\n 'members' => [\n 'application' => [\n 'shape' => 'ApplicationInfo',\n ],\n ],\n ],\n 'GetApplicationRevisionInput' => [\n 'type' => 'structure',\n 'required' => [\n 'applicationName',\n 'revision',\n ],\n 'members' => [\n 'applicationName' => [\n 'shape' => 'ApplicationName',\n ],\n 'revision' => [\n 'shape' => 'RevisionLocation',\n ],\n ],\n ],\n 'GetApplicationRevisionOutput' => [\n 'type' => 'structure',\n 'members' => [\n 'applicationName' => [\n 'shape' => 'ApplicationName',\n ],\n 'revision' => [\n 'shape' => 'RevisionLocation',\n ],\n 'revisionInfo' => [\n 'shape' => 'GenericRevisionInfo',\n ],\n ],\n ],\n 'GetDeploymentConfigInput' => [\n 'type' => 'structure',\n 'required' => [\n 'deploymentConfigName',\n ],\n 'members' => [\n 'deploymentConfigName' => [\n 'shape' => 'DeploymentConfigName',\n ],\n ],\n ],\n 'GetDeploymentConfigOutput' => [\n 'type' => 'structure',\n 'members' => [\n 'deploymentConfigInfo' => [\n 'shape' => 'DeploymentConfigInfo',\n ],\n ],\n ],\n 'GetDeploymentGroupInput' => [\n 'type' => 'structure',\n 'required' => [\n 'applicationName',\n 'deploymentGroupName',\n ],\n 'members' => [\n 'applicationName' => [\n 'shape' => 'ApplicationName',\n ],\n 'deploymentGroupName' => [\n 'shape' => 'DeploymentGroupName',\n ],\n ],\n ],\n 'GetDeploymentGroupOutput' => [\n 'type' => 'structure',\n 'members' => [\n 'deploymentGroupInfo' => [\n 'shape' => 'DeploymentGroupInfo',\n ],\n ],\n ],\n 'GetDeploymentInput' => [\n 'type' => 'structure',\n 'required' => [\n 'deploymentId',\n ],\n 'members' => [\n 'deploymentId' => [\n 'shape' => 'DeploymentId',\n ],\n ],\n ],\n 'GetDeploymentInstanceInput' => [\n 'type' => 'structure',\n 'required' => [\n 'deploymentId',\n 'instanceId',\n ],\n 'members' => [\n 'deploymentId' => [\n 'shape' => 'DeploymentId',\n ],\n 'instanceId' => [\n 'shape' => 'InstanceId',\n ],\n ],\n ],\n 'GetDeploymentInstanceOutput' => [\n 'type' => 'structure',\n 'members' => [\n 'instanceSummary' => [\n 'shape' => 'InstanceSummary',\n ],\n ],\n ],\n 'GetDeploymentOutput' => [\n 'type' => 'structure',\n 'members' => [\n 'deploymentInfo' => [\n 'shape' => 'DeploymentInfo',\n ],\n ],\n ],\n 'GitHubLocation' => [\n 'type' => 'structure',\n 'members' => [\n 'repository' => [\n 'shape' => 'Repository',\n ],\n 'commitId' => [\n 'shape' => 'CommitId',\n ],\n ],\n ],\n 'InstanceCount' => [\n 'type' => 'long',\n ],\n 'InstanceDoesNotExistException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'InstanceId' => [\n 'type' => 'string',\n ],\n 'InstanceIdRequiredException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'InstanceStatus' => [\n 'type' => 'string',\n 'enum' => [\n 'Pending',\n 'InProgress',\n 'Succeeded',\n 'Failed',\n 'Skipped',\n 'Unknown',\n ],\n ],\n 'InstanceStatusList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'InstanceStatus',\n ],\n ],\n 'InstanceSummary' => [\n 'type' => 'structure',\n 'members' => [\n 'deploymentId' => [\n 'shape' => 'DeploymentId',\n ],\n 'instanceId' => [\n 'shape' => 'InstanceId',\n ],\n 'status' => [\n 'shape' => 'InstanceStatus',\n ],\n 'lastUpdatedAt' => [\n 'shape' => 'Timestamp',\n ],\n 'lifecycleEvents' => [\n 'shape' => 'LifecycleEventList',\n ],\n ],\n ],\n 'InstancesList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'InstanceId',\n ],\n ],\n 'InvalidApplicationNameException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'InvalidAutoScalingGroupException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'InvalidBucketNameFilterException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'InvalidDeployedStateFilterException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'InvalidDeploymentConfigNameException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'InvalidDeploymentGroupNameException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'InvalidDeploymentIdException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'InvalidDeploymentStatusException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'InvalidEC2TagException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'InvalidInstanceStatusException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'InvalidKeyPrefixFilterException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'InvalidMinimumHealthyHostValueException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'InvalidNextTokenException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'InvalidOperationException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'InvalidRevisionException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'InvalidRoleException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'InvalidSortByException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'InvalidSortOrderException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'InvalidTimeRangeException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'Key' => [\n 'type' => 'string',\n ],\n 'LifecycleErrorCode' => [\n 'type' => 'string',\n 'enum' => [\n 'Success',\n 'ScriptMissing',\n 'ScriptNotExecutable',\n 'ScriptTimedOut',\n 'ScriptFailed',\n 'UnknownError',\n ],\n ],\n 'LifecycleEvent' => [\n 'type' => 'structure',\n 'members' => [\n 'lifecycleEventName' => [\n 'shape' => 'LifecycleEventName',\n ],\n 'diagnostics' => [\n 'shape' => 'Diagnostics',\n ],\n 'startTime' => [\n 'shape' => 'Timestamp',\n ],\n 'endTime' => [\n 'shape' => 'Timestamp',\n ],\n 'status' => [\n 'shape' => 'LifecycleEventStatus',\n ],\n ],\n ],\n 'LifecycleEventList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'LifecycleEvent',\n ],\n ],\n 'LifecycleEventName' => [\n 'type' => 'string',\n ],\n 'LifecycleEventStatus' => [\n 'type' => 'string',\n 'enum' => [\n 'Pending',\n 'InProgress',\n 'Succeeded',\n 'Failed',\n 'Skipped',\n 'Unknown',\n ],\n ],\n 'LifecycleMessage' => [\n 'type' => 'string',\n ],\n 'ListApplicationRevisionsInput' => [\n 'type' => 'structure',\n 'required' => [\n 'applicationName',\n ],\n 'members' => [\n 'applicationName' => [\n 'shape' => 'ApplicationName',\n ],\n 'sortBy' => [\n 'shape' => 'ApplicationRevisionSortBy',\n ],\n 'sortOrder' => [\n 'shape' => 'SortOrder',\n ],\n 's3Bucket' => [\n 'shape' => 'S3Bucket',\n ],\n 's3KeyPrefix' => [\n 'shape' => 'S3Key',\n ],\n 'deployed' => [\n 'shape' => 'ListStateFilterAction',\n ],\n 'nextToken' => [\n 'shape' => 'NextToken',\n ],\n ],\n ],\n 'ListApplicationRevisionsOutput' => [\n 'type' => 'structure',\n 'members' => [\n 'revisions' => [\n 'shape' => 'RevisionLocationList',\n ],\n 'nextToken' => [\n 'shape' => 'NextToken',\n ],\n ],\n ],\n 'ListApplicationsInput' => [\n 'type' => 'structure',\n 'members' => [\n 'nextToken' => [\n 'shape' => 'NextToken',\n ],\n ],\n ],\n 'ListApplicationsOutput' => [\n 'type' => 'structure',\n 'members' => [\n 'applications' => [\n 'shape' => 'ApplicationsList',\n ],\n 'nextToken' => [\n 'shape' => 'NextToken',\n ],\n ],\n ],\n 'ListDeploymentConfigsInput' => [\n 'type' => 'structure',\n 'members' => [\n 'nextToken' => [\n 'shape' => 'NextToken',\n ],\n ],\n ],\n 'ListDeploymentConfigsOutput' => [\n 'type' => 'structure',\n 'members' => [\n 'deploymentConfigsList' => [\n 'shape' => 'DeploymentConfigsList',\n ],\n 'nextToken' => [\n 'shape' => 'NextToken',\n ],\n ],\n ],\n 'ListDeploymentGroupsInput' => [\n 'type' => 'structure',\n 'required' => [\n 'applicationName',\n ],\n 'members' => [\n 'applicationName' => [\n 'shape' => 'ApplicationName',\n ],\n 'nextToken' => [\n 'shape' => 'NextToken',\n ],\n ],\n ],\n 'ListDeploymentGroupsOutput' => [\n 'type' => 'structure',\n 'members' => [\n 'applicationName' => [\n 'shape' => 'ApplicationName',\n ],\n 'deploymentGroups' => [\n 'shape' => 'DeploymentGroupsList',\n ],\n 'nextToken' => [\n 'shape' => 'NextToken',\n ],\n ],\n ],\n 'ListDeploymentInstancesInput' => [\n 'type' => 'structure',\n 'required' => [\n 'deploymentId',\n ],\n 'members' => [\n 'deploymentId' => [\n 'shape' => 'DeploymentId',\n ],\n 'nextToken' => [\n 'shape' => 'NextToken',\n ],\n 'instanceStatusFilter' => [\n 'shape' => 'InstanceStatusList',\n ],\n ],\n ],\n 'ListDeploymentInstancesOutput' => [\n 'type' => 'structure',\n 'members' => [\n 'instancesList' => [\n 'shape' => 'InstancesList',\n ],\n 'nextToken' => [\n 'shape' => 'NextToken',\n ],\n ],\n ],\n 'ListDeploymentsInput' => [\n 'type' => 'structure',\n 'members' => [\n 'applicationName' => [\n 'shape' => 'ApplicationName',\n ],\n 'deploymentGroupName' => [\n 'shape' => 'DeploymentGroupName',\n ],\n 'includeOnlyStatuses' => [\n 'shape' => 'DeploymentStatusList',\n ],\n 'createTimeRange' => [\n 'shape' => 'TimeRange',\n ],\n 'nextToken' => [\n 'shape' => 'NextToken',\n ],\n ],\n ],\n 'ListDeploymentsOutput' => [\n 'type' => 'structure',\n 'members' => [\n 'deployments' => [\n 'shape' => 'DeploymentsList',\n ],\n 'nextToken' => [\n 'shape' => 'NextToken',\n ],\n ],\n ],\n 'ListStateFilterAction' => [\n 'type' => 'string',\n 'enum' => [\n 'include',\n 'exclude',\n 'ignore',\n ],\n ],\n 'LogTail' => [\n 'type' => 'string',\n ],\n 'Message' => [\n 'type' => 'string',\n ],\n 'MinimumHealthyHosts' => [\n 'type' => 'structure',\n 'members' => [\n 'value' => [\n 'shape' => 'MinimumHealthyHostsValue',\n ],\n 'type' => [\n 'shape' => 'MinimumHealthyHostsType',\n ],\n ],\n ],\n 'MinimumHealthyHostsType' => [\n 'type' => 'string',\n 'enum' => [\n 'HOST_COUNT',\n 'FLEET_PERCENT',\n ],\n ],\n 'MinimumHealthyHostsValue' => [\n 'type' => 'integer',\n ],\n 'NextToken' => [\n 'type' => 'string',\n ],\n 'RegisterApplicationRevisionInput' => [\n 'type' => 'structure',\n 'required' => [\n 'applicationName',\n 'revision',\n ],\n 'members' => [\n 'applicationName' => [\n 'shape' => 'ApplicationName',\n ],\n 'description' => [\n 'shape' => 'Description',\n ],\n 'revision' => [\n 'shape' => 'RevisionLocation',\n ],\n ],\n ],\n 'Repository' => [\n 'type' => 'string',\n ],\n 'RevisionDoesNotExistException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'RevisionLocation' => [\n 'type' => 'structure',\n 'members' => [\n 'revisionType' => [\n 'shape' => 'RevisionLocationType',\n ],\n 's3Location' => [\n 'shape' => 'S3Location',\n ],\n 'gitHubLocation' => [\n 'shape' => 'GitHubLocation',\n ],\n ],\n ],\n 'RevisionLocationList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'RevisionLocation',\n ],\n ],\n 'RevisionLocationType' => [\n 'type' => 'string',\n 'enum' => [\n 'S3',\n 'GitHub',\n ],\n ],\n 'RevisionRequiredException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'Role' => [\n 'type' => 'string',\n ],\n 'RoleRequiredException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'S3Bucket' => [\n 'type' => 'string',\n ],\n 'S3Key' => [\n 'type' => 'string',\n ],\n 'S3Location' => [\n 'type' => 'structure',\n 'members' => [\n 'bucket' => [\n 'shape' => 'S3Bucket',\n ],\n 'key' => [\n 'shape' => 'S3Key',\n ],\n 'bundleType' => [\n 'shape' => 'BundleType',\n ],\n 'version' => [\n 'shape' => 'VersionId',\n ],\n 'eTag' => [\n 'shape' => 'ETag',\n ],\n ],\n ],\n 'ScriptName' => [\n 'type' => 'string',\n ],\n 'SortOrder' => [\n 'type' => 'string',\n 'enum' => [\n 'ascending',\n 'descending',\n ],\n ],\n 'StopDeploymentInput' => [\n 'type' => 'structure',\n 'required' => [\n 'deploymentId',\n ],\n 'members' => [\n 'deploymentId' => [\n 'shape' => 'DeploymentId',\n ],\n ],\n ],\n 'StopDeploymentOutput' => [\n 'type' => 'structure',\n 'members' => [\n 'status' => [\n 'shape' => 'StopStatus',\n ],\n 'statusMessage' => [\n 'shape' => 'Message',\n ],\n ],\n ],\n 'StopStatus' => [\n 'type' => 'string',\n 'enum' => [\n 'Pending',\n 'Succeeded',\n ],\n ],\n 'TimeRange' => [\n 'type' => 'structure',\n 'members' => [\n 'start' => [\n 'shape' => 'Timestamp',\n ],\n 'end' => [\n 'shape' => 'Timestamp',\n ],\n ],\n ],\n 'Timestamp' => [\n 'type' => 'timestamp',\n ],\n 'UpdateApplicationInput' => [\n 'type' => 'structure',\n 'members' => [\n 'applicationName' => [\n 'shape' => 'ApplicationName',\n ],\n 'newApplicationName' => [\n 'shape' => 'ApplicationName',\n ],\n ],\n ],\n 'UpdateDeploymentGroupInput' => [\n 'type' => 'structure',\n 'required' => [\n 'applicationName',\n 'currentDeploymentGroupName',\n ],\n 'members' => [\n 'applicationName' => [\n 'shape' => 'ApplicationName',\n ],\n 'currentDeploymentGroupName' => [\n 'shape' => 'DeploymentGroupName',\n ],\n 'newDeploymentGroupName' => [\n 'shape' => 'DeploymentGroupName',\n ],\n 'deploymentConfigName' => [\n 'shape' => 'DeploymentConfigName',\n ],\n 'ec2TagFilters' => [\n 'shape' => 'EC2TagFilterList',\n ],\n 'autoScalingGroups' => [\n 'shape' => 'AutoScalingGroupNameList',\n ],\n 'serviceRoleArn' => [\n 'shape' => 'Role',\n ],\n ],\n ],\n 'UpdateDeploymentGroupOutput' => [\n 'type' => 'structure',\n 'members' => [\n 'hooksNotCleanedUp' => [\n 'shape' => 'AutoScalingGroupList',\n ],\n ],\n ],\n 'Value' => [\n 'type' => 'string',\n ],\n 'VersionId' => [\n 'type' => 'string',\n ],\n ],\n];\n" }, { "alpha_fraction": 0.5805970430374146, "alphanum_fraction": 0.5805970430374146, "avg_line_length": 26.91666603088379, "blob_id": "d2f09f85531c02572858b0325caba9d763931b16", "content_id": "9e9bf80c54914e024efff059aa9499b67595071a", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 670, "license_type": "permissive", "max_line_length": 78, "num_lines": 24, "path": "/tests/Credentials/NullCredentialsTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Credentials;\n\nuse Aws\\Credentials\\NullCredentials;\n\n/**\n * @covers \\Aws\\Credentials\\NullCredentials\n */\nclass NullCredentialsTest extends \\PHPUnit_Framework_TestCase\n{\n public function testIsNullish()\n {\n $n = new NullCredentials();\n $this->assertSame('', $n->getAccessKeyId());\n $this->assertSame('', $n->getSecretKey());\n $this->assertNull($n->getSecurityToken());\n $this->assertNull($n->getExpiration());\n $this->assertFalse($n->isExpired());\n $this->assertSame(\n ['key' => '', 'secret' => '', 'token' => null, 'expires' => null],\n $n->toArray()\n );\n }\n}\n" }, { "alpha_fraction": 0.5199999809265137, "alphanum_fraction": 0.5199999809265137, "avg_line_length": 21.36842155456543, "blob_id": "e1a30ab3f757f0172794326a77a671855a6d5536", "content_id": "7deb232e4cddfc6bf52786b56884f52dedff1277", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 425, "license_type": "permissive", "max_line_length": 41, "num_lines": 19, "path": "/src/data/cloudsearch-2013-01-01.paginators.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php return [\n 'pagination' => [\n 'DescribeAnalysisSchemes' => [\n 'result_key' => 'AnalysisSchemes',\n ],\n 'DescribeDomains' => [\n 'result_key' => 'DomainStatusList',\n ],\n 'DescribeExpressions' => [\n 'result_key' => 'Expressions',\n ],\n 'DescribeIndexFields' => [\n 'result_key' => 'IndexFields',\n ],\n 'DescribeSuggesters' => [\n 'result_key' => 'Suggesters',\n ],\n ],\n];\n" }, { "alpha_fraction": 0.5972850918769836, "alphanum_fraction": 0.6040723919868469, "avg_line_length": 22.263158798217773, "blob_id": "254f0ea1d2138165d8860fcbae5cbe6985cb528b", "content_id": "338da1ff466a17dd72ef60570fbd46f5721d07cf", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 442, "license_type": "permissive", "max_line_length": 79, "num_lines": 19, "path": "/src/Ec2/Ec2Client.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Ec2;\n\nuse Aws\\AwsClient;\n\n/**\n * This client is used to interact with **Amazon EC2**.\n */\nclass Ec2Client extends AwsClient\n{\n public function __construct(array $args)\n {\n $args['with_resolved'] = function (array $args) {\n $copySnap = new CopySnapshotSubscriber($args['endpoint_provider']);\n $this->getEmitter()->attach($copySnap);\n };\n parent::__construct($args);\n }\n}\n" }, { "alpha_fraction": 0.3791923224925995, "alphanum_fraction": 0.4049737751483917, "avg_line_length": 31.708955764770508, "blob_id": "88e7d6405fea26f93246c05677fa16611940e978", "content_id": "1ac1531d054b3ca431a7f1c3f45faded6ff6bda6", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4383, "license_type": "permissive", "max_line_length": 90, "num_lines": 134, "path": "/tests/DynamoDb/DynamoDbClientTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\DynamoDb;\n\nuse Aws\\DynamoDb\\DynamoDbClient;\nuse Aws\\Test\\SdkTest;\nuse Aws\\Test\\UsesServiceTrait;\nuse GuzzleHttp\\Stream\\Stream;\nuse GuzzleHttp\\Subscriber\\Retry\\RetrySubscriber;\n\n/**\n * @covers \\Aws\\DynamoDb\\DynamoDbClient\n */\nclass DynamoDbClientTest extends \\PHPUnit_Framework_TestCase\n{\n use UsesServiceTrait;\n\n public function testDisablesRedirects()\n {\n $client = new DynamoDbClient([\n 'service' => 'dynamodb',\n 'region' => 'us-west-2',\n 'version' => 'latest'\n ]);\n $this->assertFalse($client->getHttpClient()->getDefaultOption('allow_redirects'));\n }\n\n public function testUsesCustomBackoffStrategy()\n {\n $client = new DynamoDbClient([\n 'service' => 'dynamodb',\n 'region' => 'us-west-2',\n 'version' => 'latest'\n ]);\n $c = $client->getHttpClient();\n $found = false;\n\n foreach ($c->getEmitter()->listeners('error') as $listener) {\n if (is_array($listener) &&\n $listener[0] instanceof RetrySubscriber\n ) {\n $found = $listener[0];\n }\n }\n\n if (!$found) {\n $this->fail('RetrySubscriber not registered');\n }\n\n $delay = $this->readAttribute($found, 'delayFn');\n $this->assertInternalType('callable', $delay);\n $this->assertEquals(0, call_user_func($delay, 0));\n $this->assertEquals(0.05, call_user_func($delay, 1));\n $this->assertEquals(0.10, call_user_func($delay, 2));\n }\n\n public function testCanDisableRetries()\n {\n $client = new DynamoDbClient([\n 'service' => 'dynamodb',\n 'region' => 'us-west-2',\n 'retries' => 0,\n 'version' => 'latest'\n ]);\n $c = $client->getHttpClient();\n $this->assertFalse(SdkTest::hasListener(\n $c->getEmitter(),\n 'GuzzleHttp\\Subscriber\\Retry\\RetrySubscriber',\n 'error'\n ));\n }\n\n public function testRegisterSessionHandlerReturnsHandler()\n {\n $client = $this->getTestSdk()->createDynamoDb();\n $sh = $client->registerSessionHandler(['locking' => true]);\n $this->assertInstanceOf(\n 'Aws\\DynamoDb\\LockingSessionConnection',\n $this->readAttribute($sh, 'connection')\n );\n }\n\n public function dataForFormatValueTest()\n {\n $handle = fopen('php://memory', 'w+');\n fwrite($handle, 'foo');\n rewind($handle);\n $stream = Stream::factory('bar');\n\n return [\n // String values\n [ 'foo', '{\"S\":\"foo\"}' ],\n [ ['foo'], '{\"SS\":[\"foo\"]}' ],\n [ ['foo', 'bar', 'baz'], '{\"SS\":[\"foo\",\"bar\",\"baz\"]}' ],\n\n // Numerical values\n [ 1, '{\"N\":\"1\"}' ],\n [ 0, '{\"N\":\"0\"}' ],\n [ 50, '{\"N\":\"50\"}' ],\n [ 1.23, '{\"N\":\"1.23\"}' ],\n [ 1e10, '{\"N\":\"10000000000\"}' ],\n [ [1], '{\"NS\":[\"1\"]}' ],\n [ [0], '{\"NS\":[\"0\"]}' ],\n [ [1, 2, 3], '{\"NS\":[\"1\",\"2\",\"3\"]}' ],\n [ [1.2, 3.4, 5.6], '{\"NS\":[\"1.2\",\"3.4\",\"5.6\"]}' ],\n\n // Numerical strings values\n [ '1', '{\"S\":\"1\"}' ],\n [ '0', '{\"S\":\"0\"}' ],\n [ '50', '{\"S\":\"50\"}' ],\n [ '1.23', '{\"S\":\"1.23\"}' ],\n [ '1e10', '{\"S\":\"1e10\"}' ],\n [ ['1'], '{\"SS\":[\"1\"]}' ],\n [ ['0'], '{\"SS\":[\"0\"]}' ],\n [ ['1', '2', '3'], '{\"SS\":[\"1\",\"2\",\"3\"]}' ],\n [ ['1.2', '3.4', '5.6'], '{\"SS\":[\"1.2\",\"3.4\",\"5.6\"]}' ],\n\n // Boolean values\n [ true, '{\"N\":\"1\"}' ],\n [ false, '{\"N\":\"0\"}' ],\n [ [true], '{\"NS\":[\"1\"]}' ],\n [ [false], '{\"NS\":[\"0\"]}' ],\n\n // Empty and non-scalar values\n [ '', null ],\n [ null, null ],\n [ [], null ],\n [ [null], null ],\n [ ['foo', 1], null ],\n [ new \\stdClass, null ],\n [ $handle, '{\"B\":\"foo\"}' ],\n [ $stream, '{\"B\":\"bar\"}' ],\n ];\n }\n}\n" }, { "alpha_fraction": 0.7894737124443054, "alphanum_fraction": 0.7894737124443054, "avg_line_length": 22.22222137451172, "blob_id": "0c35329b5ee31c2e34568262d085201a5c102bd2", "content_id": "a4306eaaffe2f7d23f91aa1cd0308fb2eebdd57a", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 209, "license_type": "permissive", "max_line_length": 70, "num_lines": 9, "path": "/src/ImportExport/Exception/ImportExportException.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\ImportExport\\Exception;\n\nuse Aws\\Exception\\AwsException;\n\n/**\n * Represents an error interacting with the AWS Import/Export service.\n */\nclass ImportExportException extends AwsException {}\n" }, { "alpha_fraction": 0.6442674994468689, "alphanum_fraction": 0.6480891704559326, "avg_line_length": 29.485437393188477, "blob_id": "3543e203255f5ca8bfdb3b63a72bc7321e78d5a9", "content_id": "92a251a719c7c5de3e62492b1045796e866f340e", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 3140, "license_type": "permissive", "max_line_length": 119, "num_lines": 103, "path": "/docs/service-sqs.rst", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "================\nAmazon SQS Guide\n================\n\nCreating a queue\n----------------\n\nNow, let's create a queue. You can create a standard queue by just providing a name. Make sure to get the queue's URL\nfrom the result, since the queue URL is the unique identifier used to specify the queue in order to send and receive\nmessages.\n\n.. code-block:: php\n\n $result = $client->createQueue(array('QueueName' => 'my-queue'));\n $queueUrl = $result->get('QueueUrl');\n\nYou can also set attributes on your queue when you create it.\n\n.. code-block:: php\n\n use Aws\\Common\\Enum\\Size;\n use Aws\\Sqs\\Enum\\QueueAttribute;\n\n $result = $client->createQueue(array(\n 'QueueName' => 'my-queue',\n 'Attributes' => array(\n QueueAttribute::DELAY_SECONDS => 5,\n QueueAttribute::MAXIMUM_MESSAGE_SIZE => 4 * Size::KB,\n ),\n ));\n $queueUrl = $result->get('QueueUrl');\n\nOr you can also set queue attributes later.\n\n.. code-block:: php\n\n use Aws\\Common\\Enum\\Time;\n use Aws\\Sqs\\Enum\\QueueAttribute;\n\n $result = $client->setQueueAttributes(array(\n 'QueueUrl' => $queueUrl,\n 'Attributes' => array(\n QueueAttribute::VISIBILITY_TIMEOUT => 2 * Time::MINUTES,\n ),\n ));\n\nSending messages\n----------------\n\nSending a message to a queue is straight forward with the ``SendMessage`` command.\n\n.. code-block:: php\n\n $client->sendMessage(array(\n 'QueueUrl' => $queueUrl,\n 'MessageBody' => 'An awesome message!',\n ));\n\nYou can overwrite the queue's default delay for a message when you send it.\n\n.. code-block:: php\n\n $client->sendMessage(array(\n 'QueueUrl' => $queueUrl,\n 'MessageBody' => 'An awesome message!',\n 'DelaySeconds' => 30,\n ));\n\nReceiving messages\n------------------\n\nReceiving messages is done with the ``ReceiveMessage`` command.\n\n.. code-block:: php\n\n $result = $client->receiveMessage(array(\n 'QueueUrl' => $queueUrl,\n ));\n\n foreach ($result->getPath('Messages/*/Body') as $messageBody) {\n // Do something with the message\n echo $messageBody;\n }\n\nBy default, only one message will be returned. If you want to get more messages, make sure to use the\n``MaxNumberOfMessages`` parameter and specify a number of messages (1 to 10). Remember that you are not guaranteed to\nreceive that many messages, but you can receive up to that amount depending on how many are actually in the queue at\nthe time of your request.\n\nSQS also supports `\"long polling\"\n<http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-long-polling.html>`_, meaning that you\ncan instruct SQS to hold the connection open with the SDK for up to 20 seconds in order to wait for a message to arrive\nin the queue. To configure this behavior, you must use the ``WaitTimeSeconds`` parameter.\n\n.. code-block:: php\n\n $result = $client->receiveMessage(array(\n 'QueueUrl' => $queueUrl,\n 'WaitTimeSeconds' => 10,\n ));\n\n.. note:: You can also configure long-polling at the queue level by setting the ``ReceiveMessageWaitTimeSeconds`` queue\n attribute.\n" }, { "alpha_fraction": 0.4088541567325592, "alphanum_fraction": 0.421875, "avg_line_length": 20.33333396911621, "blob_id": "330c2795cb42d215cccac5920241a3dc98416200", "content_id": "6195f45549b05c8fe6f042d75d16044d09200c74", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 384, "license_type": "permissive", "max_line_length": 57, "num_lines": 18, "path": "/src/data/kinesis-2013-12-02.waiters2.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php return [\n 'version' => 2,\n 'waiters' => [\n 'StreamExists' => [\n 'delay' => 10,\n 'operation' => 'DescribeStream',\n 'maxAttempts' => 18,\n 'acceptors' => [\n [\n 'expected' => 'ACTIVE',\n 'matcher' => 'path',\n 'state' => 'success',\n 'argument' => 'StreamDescription.StreamStatus',\n ],\n ],\n ],\n ],\n];\n" }, { "alpha_fraction": 0.3988763988018036, "alphanum_fraction": 0.40355804562568665, "avg_line_length": 24.428571701049805, "blob_id": "1c822723cd6377e9c8266834b057fb434bfe9a1c", "content_id": "1ca3450c08ce9a35e3bb7260d24dc401cdd0ccb8", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1068, "license_type": "permissive", "max_line_length": 49, "num_lines": 42, "path": "/src/data/elasticmapreduce-2009-03-31.waiters2.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php return [\n 'version' => 2,\n 'waiters' => [\n 'ClusterRunning' => [\n 'delay' => 30,\n 'operation' => 'DescribeCluster',\n 'maxAttempts' => 60,\n 'acceptors' => [\n [\n 'state' => 'success',\n 'matcher' => 'path',\n 'argument' => 'Cluster.Status.State',\n 'expected' => 'RUNNING',\n ],\n [\n 'state' => 'success',\n 'matcher' => 'path',\n 'argument' => 'Cluster.Status.State',\n 'expected' => 'WAITING',\n ],\n [\n 'state' => 'failure',\n 'matcher' => 'path',\n 'argument' => 'Cluster.Status.State',\n 'expected' => 'TERMINATING',\n ],\n [\n 'state' => 'failure',\n 'matcher' => 'path',\n 'argument' => 'Cluster.Status.State',\n 'expected' => 'TERMINATED',\n ],\n [\n 'state' => 'failure',\n 'matcher' => 'path',\n 'argument' => 'Cluster.Status.State',\n 'expected' => 'TERMINATED_WITH_ERRORS',\n ],\n ],\n ],\n ],\n];\n" }, { "alpha_fraction": 0.45138055086135864, "alphanum_fraction": 0.4549819827079773, "avg_line_length": 33.70833206176758, "blob_id": "119e171c9c4f9bf0110df8a3f157a3bfeabcbc74", "content_id": "cc0b1d305d1ca962356510a4ee0cf03e32ecae38", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4998, "license_type": "permissive", "max_line_length": 89, "num_lines": 144, "path": "/tests/Integ/WaiterTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Integ;\n\nuse Aws\\Exception\\AwsException;\nuse GuzzleHttp\\Command\\Event\\PreparedEvent;\nuse GuzzleHttp\\Command\\Event\\ProcessEvent;\n\nclass WaitersTest extends \\PHPUnit_Framework_TestCase\n{\n use IntegUtils;\n\n public function testNormalWaiters()\n {\n $client = self::getSdk()->createDynamoDb();\n $table = self::getResourcePrefix() . '-test-table';\n\n self::log('Testing synchronous waiters.');\n\n try {\n self::log('Creating table.');\n $client->createTable([\n 'TableName' => $table,\n 'AttributeDefinitions' => [\n ['AttributeName' => 'id', 'AttributeType' => 'N']\n ],\n 'KeySchema' => [\n ['AttributeName' => 'id', 'KeyType' => 'HASH']\n ],\n 'ProvisionedThroughput' => [\n 'ReadCapacityUnits' => 20,\n 'WriteCapacityUnits' => 20\n ]\n ]);\n\n self::log('Waiting for the table to be active.');\n $client->waitUntil(\n 'TableExists',\n ['TableName' => $table],\n ['retry' => function ($attempt) {\n self::log(\"TableExists waiter has made {$attempt} attempts.\");\n }]\n );\n\n self::log('Deleting table.');\n $client->deleteTable(['TableName' => $table]);\n\n self::log('Waiting for the table to be deleted.');\n $client->waitUntil(\n 'TableNotExists',\n ['TableName' => $table],\n [\n 'initDelay' => 1,\n 'retry' => function ($attempt) {\n self::log(\"TableNotExists waiter has made {$attempt} attempts.\");\n }\n ]\n );\n\n self::log('All done waiting.');\n } catch (\\Exception $e) {\n self::log($e->getMessage());\n $this->fail('Synchronous waiters failed.');\n }\n }\n\n public function asyncTestAsyncWaiters()\n {\n $sdk = self::getSdk();\n\n $client = $sdk->createDynamoDb();\n $table = self::getResourcePrefix() . '-test-table';\n\n self::log('Testing asynchronous waiters.');\n\n $promises = [];\n\n $promises[] = $client->createTable([\n 'TableName' => $table,\n 'AttributeDefinitions' => [\n ['AttributeName' => 'id', 'AttributeType' => 'N']\n ],\n 'KeySchema' => [\n ['AttributeName' => 'id', 'KeyType' => 'HASH']\n ],\n 'ProvisionedThroughput' => [\n 'ReadCapacityUnits' => 20,\n 'WriteCapacityUnits' => 20\n ],\n '@future' => true\n ])->then(\n function () use ($client, $table) {\n self::log('Creating table.');\n self::log('Waiting for the table to be active.');\n return $client->waitUntil('TableExists', [\n 'TableName' => $table,\n '@future' => true,\n ])->then(null, null, function ($attempt) {\n self::log(\"TableExists waiter has made {$attempt} attempts.\");\n });\n }\n )->then(\n function () use ($client, $table) {\n return $client->deleteTable([\n 'TableName' => $table,\n '@future' => true\n ])->promise();\n }\n )->then(\n function () use ($client, $table) {\n self::log('Deleting table.');\n self::log('Waiting for the table to be deleted.');\n return $client->waitUntil('TableNotExists', [\n 'TableName' => $table,\n '@future' => true,\n ])->then(null, null, function ($attempt) {\n self::log(\"TableNotExists waiter has made {$attempt} attempts.\");\n });\n }\n )->then(\n function () use ($client, $table) {\n self::log('All done waiting.');\n },\n function (AwsException $error) {\n self::log($error->getMessage());\n $this->fail('Asynchronous waiters failed.');\n }\n );\n\n $s3 = $sdk->getS3();\n $command = $s3->getCommand('ListBuckets', ['@future' => true]);\n $command->getEmitter()->on('prepared', function (PreparedEvent $event) {\n self::log('Initiating a ListBuckets operation.');\n $event->getRequest()->getConfig()->set('delay', 20000);\n });\n $command->getEmitter()->on('process', function (ProcessEvent $event) {\n self::log('Completed the ListBuckets operation.');\n });\n $promises[] = $s3->execute($command);\n\n \\React\\Promise\\all($promises)->then(function () {\n self::log('Done with everything!');\n });\n }\n}\n" }, { "alpha_fraction": 0.5771195292472839, "alphanum_fraction": 0.5858018398284912, "avg_line_length": 30.079364776611328, "blob_id": "0713040fe3d4d4072a650edf97349904faa44561", "content_id": "1b71d1863393453b61ed5b27b85d9b64080cdf4c", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1958, "license_type": "permissive", "max_line_length": 76, "num_lines": 63, "path": "/tests/Exception/AwsExceptionTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test;\n\nuse Aws\\Exception\\AwsException;\nuse GuzzleHttp\\Command\\Command;\nuse GuzzleHttp\\Command\\CommandTransaction;\nuse GuzzleHttp\\Message\\Response;\n\n/**\n * @covers Aws\\Exception\\AwsException\n */\nclass AwsExceptionTest extends \\PHPUnit_Framework_TestCase\n{\n use UsesServiceTrait;\n\n public function testReturnsClient()\n {\n $client = $this->getTestClient('s3');\n $trans = new CommandTransaction($client, new Command('foo'));\n $e = new AwsException('Foo', $trans);\n $this->assertSame($client, $e->getClient());\n }\n\n public function testProvidesContextShortcuts()\n {\n $coll = [\n 'aws_error' => [\n 'request_id' => '10',\n 'type' => 'mytype',\n 'code' => 'mycode'\n ]\n ];\n\n $client = $this->getTestClient('s3');\n $trans = new CommandTransaction($client, new Command('foo'), $coll);\n $e = new AwsException('Foo', $trans);\n $this->assertEquals('10', $e->getAwsRequestId());\n $this->assertEquals('10', $e->getRequestId());\n\n $this->assertEquals('mytype', $e->getAwsErrorType());\n $this->assertEquals('mytype', $e->getExceptionType());\n\n $this->assertEquals('mycode', $e->getAwsErrorCode());\n $this->assertEquals('mycode', $e->getExceptionCode());\n }\n\n public function testReturnsServiceName()\n {\n $client = $this->getTestClient('s3');\n $trans = new CommandTransaction($client, new Command('foo'));\n $e = new AwsException('Foo', $trans);\n $this->assertSame('s3', $e->getServiceName());\n }\n\n public function testReturnsStatusCode()\n {\n $client = $this->getTestClient('s3');\n $trans = new CommandTransaction($client, new Command('foo'));\n $trans->response = new Response(400);\n $e = new AwsException('Foo', $trans);\n $this->assertEquals(400, $e->getStatusCode());\n }\n}\n" }, { "alpha_fraction": 0.5398298501968384, "alphanum_fraction": 0.5545243620872498, "avg_line_length": 29.785715103149414, "blob_id": "bd02c04990ddc4e212e742287b1d61e8c1ad5d7f", "content_id": "865e3bae7feedbe5246a41384472c53fac474619", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1293, "license_type": "permissive", "max_line_length": 88, "num_lines": 42, "path": "/tests/Integ/S3SignatureTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Integ;\n\nuse Aws\\S3\\S3Client;\nuse GuzzleHttp\\Command\\Command;\nuse GuzzleHttp\\Command\\Exception\\CommandException;\n\nclass S3SignatureTest extends \\PHPUnit_Framework_TestCase\n{\n use IntegUtils;\n\n public function signProvider()\n {\n return [\n [['Bucket' => uniqid('notthere'), 'PathStyle' => true]],\n [['Version' => 'foo', 'Bucket' => uniqid('notthere'), 'PathStyle' => true]],\n [['Bucket' => uniqid('notthere'), 'Key' => 'foo', 'PathStyle' => true]],\n [['Bucket' => uniqid('notthere')]],\n [['Version' => 'foo', 'Bucket' => uniqid('notthere')]],\n [['Bucket' => uniqid('notthere'), 'Key' => 'foo', 'PathStyle' => true]],\n ];\n }\n\n /**\n * @dataProvider signProvider\n */\n public function testSignsS3Requests($args)\n {\n $s3 = $this->getSdk()->createClient('s3', ['region' => 'us-east-1']);\n $command = $s3->getCommand('HeadBucket', $args);\n $this->ensureNot403($command, $s3);\n }\n\n private function ensureNot403(Command $command, S3Client $client)\n {\n try {\n $client->execute($command);\n } catch (CommandException $e) {\n $this->assertNotEquals(403, $e->getResponse()->getStatusCode());\n }\n }\n}\n" }, { "alpha_fraction": 0.5539112091064453, "alphanum_fraction": 0.5539112091064453, "avg_line_length": 29.84782600402832, "blob_id": "86c9c77e53b764f0119b86250219ff733544250c", "content_id": "3170e708f506870339d0817cd90e8fda310dca70", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1419, "license_type": "permissive", "max_line_length": 40, "num_lines": 46, "path": "/src/data/swf-2012-01-25.paginators.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php return [\n 'pagination' => [\n 'GetWorkflowExecutionHistory' => [\n 'limit_key' => 'maximumPageSize',\n 'input_token' => 'nextPageToken',\n 'output_token' => 'nextPageToken',\n 'result_key' => 'events',\n ],\n 'ListActivityTypes' => [\n 'limit_key' => 'maximumPageSize',\n 'input_token' => 'nextPageToken',\n 'output_token' => 'nextPageToken',\n 'result_key' => 'typeInfos',\n ],\n 'ListClosedWorkflowExecutions' => [\n 'limit_key' => 'maximumPageSize',\n 'input_token' => 'nextPageToken',\n 'output_token' => 'nextPageToken',\n 'result_key' => 'executionInfos',\n ],\n 'ListDomains' => [\n 'limit_key' => 'maximumPageSize',\n 'input_token' => 'nextPageToken',\n 'output_token' => 'nextPageToken',\n 'result_key' => 'domainInfos',\n ],\n 'ListOpenWorkflowExecutions' => [\n 'limit_key' => 'maximumPageSize',\n 'input_token' => 'nextPageToken',\n 'output_token' => 'nextPageToken',\n 'result_key' => 'executionInfos',\n ],\n 'ListWorkflowTypes' => [\n 'limit_key' => 'maximumPageSize',\n 'input_token' => 'nextPageToken',\n 'output_token' => 'nextPageToken',\n 'result_key' => 'typeInfos',\n ],\n 'PollForDecisionTask' => [\n 'limit_key' => 'maximumPageSize',\n 'input_token' => 'nextPageToken',\n 'output_token' => 'nextPageToken',\n 'result_key' => 'events',\n ],\n ],\n];\n" }, { "alpha_fraction": 0.488023966550827, "alphanum_fraction": 0.491708904504776, "avg_line_length": 27.379085540771484, "blob_id": "6af54f6a107014ce81527651011a1e8415a388ce", "content_id": "029f88cdeb048bb1ea38173f8c80d2723a11a3e6", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4342, "license_type": "permissive", "max_line_length": 84, "num_lines": 153, "path": "/tests/S3/ClearBucketTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\S3;\n\nuse Aws\\S3\\Exception\\ClearBucketException;\nuse Aws\\S3\\S3Client;\nuse Aws\\S3\\ClearBucket;\nuse Aws\\Test\\UsesServiceTrait;\n\n/**\n * @covers Aws\\S3\\ClearBucket\n */\nclass ClearBucketTest extends \\PHPUnit_Framework_TestCase\n{\n use UsesServiceTrait;\n\n /** @var S3Client */\n protected $client;\n\n public function setUp()\n {\n $this->client = $this->getTestClient('s3', ['region' => 'us-east-1']);\n }\n\n /**\n * @expectedException \\InvalidArgumentException\n * @expectedExceptionMessage Invalid option provided: baz\n */\n public function testValidatesInput()\n {\n new ClearBucket($this->client, 'foo', ['baz' => 'bar']);\n }\n\n /**\n * @expectedException \\InvalidArgumentException\n * @expectedExceptionMessage iterator must be an instance of Iterator\n */\n public function testValidatesIterator()\n {\n new ClearBucket($this->client, 'foo', ['iterator' => 'bar']);\n }\n\n /**\n * @expectedException \\InvalidArgumentException\n * @expectedExceptionMessage batch_size must be > 0\n */\n public function testValidatesBatchSize()\n {\n new ClearBucket($this->client, 'foo', ['batch_size' => 0]);\n }\n\n public function testEnsuresEachKeyIsValid()\n {\n try {\n $c = new ClearBucket($this->client, 'foo', [\n 'iterator' => new \\ArrayIterator(['baz!'])\n ]);\n $c->clear();\n $this->fail('Did not throw');\n } catch (ClearBucketException $e) {\n $this->assertEquals([\n [\n 'Key' => null,\n 'Value' => 'baz!',\n 'Message' => 'Invalid value returned from iterator'\n ]\n ], $e->getErrors());\n }\n }\n\n /**\n * @expectedException \\Aws\\S3\\Exception\\ClearBucketException\n */\n public function testEnsuresEachKeyHasKey()\n {\n $iter = new \\ArrayIterator(['foo' => 'bar']);\n $c = new ClearBucket($this->client, 'foo', ['iterator' => $iter]);\n $c->clear();\n }\n\n public function testCreatesDefaultIterator()\n {\n $c = new ClearBucket($this->client, 'foo');\n $i = $this->readAttribute($c, 'iterator');\n $this->assertInstanceOf('Generator', $i);\n }\n\n public function testAddsMfaOptions()\n {\n $c = new ClearBucket($this->client, 'foo', ['mfa' => 'foo']);\n $o = $this->readAttribute($c, 'options');\n $this->assertEquals('foo', $o['mfa']);\n }\n\n public function testBatchDeletes()\n {\n $calls = [];\n $c = new ClearBucket($this->client, 'bucket', [\n 'batch_size' => 3,\n 'before' => function (\\Iterator $i, array $keys) use (&$calls) {\n $calls[] = $keys;\n }\n ]);\n\n $keys = [\n ['Key' => 'a'],\n ['Key' => 'b'],\n ['Key' => 'c'],\n ['Key' => 'd'],\n ['Key' => 'e']\n ];\n\n $this->addMockResults($this->client, [\n ['IsTruncated' => false, 'Contents' => $keys],\n ['Deleted' => []],\n ['Deleted' => []],\n ]);\n\n $c->clear();\n $this->assertCount(2, $calls);\n $this->assertEquals(\n [['Key' => 'a'], ['Key' => 'b'], ['Key' => 'c']],\n $calls[0]\n );\n $this->assertEquals(\n [['Key' => 'd'], ['Key' => 'e']],\n $calls[1]\n );\n }\n\n public function testThrowsClearBucketExceptionOnBatchDeleteError()\n {\n $i = new \\ArrayIterator([['Key' => 'foo'], ['Key' => 'bar']]);\n $c = new ClearBucket($this->client, 'bucket', ['iterator' => $i]);\n $deleted = [['Key' => 'foo']];\n $errors = [['Key' => 'bar', 'Code' => 'code', 'Message' => 'msg']];\n\n $this->addMockResults($this->client, [\n ['Deleted' => $deleted, 'Errors' => $errors]\n ]);\n\n try {\n $c->clear();\n $this->fail('Did not throw');\n } catch (ClearBucketException $e) {\n $this->assertSame($errors, $e->getErrors());\n $this->assertSame($i, $e->getIterator());\n $this->assertEquals(\n 'One or more errors occurred while clearing the bucket: <code> msg',\n $e->getMessage()\n );\n }\n }\n}\n" }, { "alpha_fraction": 0.5292425751686096, "alphanum_fraction": 0.5311601161956787, "avg_line_length": 25.743589401245117, "blob_id": "ab0168b2dd1c5f1ffdcab942a0e53f2b1e24ca4d", "content_id": "bd3a27bf3a2f1f0c51edfe3b8ca4f93835504e6c", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1043, "license_type": "permissive", "max_line_length": 63, "num_lines": 39, "path": "/tests/Signature/AnonymousSignatureTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Signature;\n\nuse Aws\\Credentials\\Credentials;\nuse Aws\\Signature\\AnonymousSignature;\nuse GuzzleHttp\\Message\\MessageFactory;\n\n/**\n * @covers Aws\\Signature\\AnonymousSignature\n */\nclass AnonymousTest extends \\PHPUnit_Framework_TestCase\n{\n public function testDoesNotSignsRequests()\n {\n $creds = new Credentials('foo', 'bar', 'baz');\n $signature = new AnonymousSignature();\n $request = (new MessageFactory)->createRequest(\n 'PUT',\n 'http://s3.amazonaws.com/bucket/key',\n [\n 'body' => 'body',\n 'headers' => [\n 'Content-Type' => 'Baz',\n 'X-Amz-Meta-Boo' => 'bam'\n ]\n ]\n );\n $str = (string)$request;\n\n $signature->signRequest($request, $creds);\n $this->assertSame($str, (string)$request);\n\n $this->assertEquals('', $signature->createPresignedUrl(\n $request,\n $creds,\n '+1 minute'\n ));\n }\n}\n" }, { "alpha_fraction": 0.6072834730148315, "alphanum_fraction": 0.6200787425041199, "avg_line_length": 29.787878036499023, "blob_id": "e42f200f4fe8b631161f4235d030308081a0515e", "content_id": "8fd01884b001807a242cd987fffef2b5cae108bf", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1016, "license_type": "permissive", "max_line_length": 68, "num_lines": 33, "path": "/tests/Route53/CleanIdSubscriberTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Route53;\n\nuse Aws\\Route53\\Route53Client;\nuse Aws\\Route53\\CleanIdSubscriber;\nuse GuzzleHttp\\Command\\CommandTransaction;\nuse GuzzleHttp\\Command\\Event\\InitEvent;\n\n/**\n * @covers Aws\\Route53\\CleanIdSubscriber\n */\nclass CleanIdSubscriberTest extends \\PHPUnit_Framework_TestCase\n{\n public function testCleansIds()\n {\n $client = Route53Client::factory([\n 'region' => 'us-west-2',\n 'version' => 'latest'\n ]);\n $command = $client->getCommand('ChangeResourceRecordSets', [\n 'HostedZoneId' => '/hostedzone/foo'\n ]);\n $trans = new CommandTransaction($client, $command);\n $event = new InitEvent($trans);\n $listener = new CleanIdSubscriber();\n $listener->onInit($event);\n $this->assertEquals('foo', $command['HostedZoneId']);\n unset($command['HostedZoneId']);\n $command['Id'] = '/change/foo';\n $listener->onInit($event);\n $this->assertEquals('foo', $command['Id']);\n }\n}\n" }, { "alpha_fraction": 0.643757164478302, "alphanum_fraction": 0.6529209613800049, "avg_line_length": 29.63157844543457, "blob_id": "92acd94aacfb7a718740099422ff5efd02a69070", "content_id": "cfc8e7510c1679c119ff8dd5364438f7237488a5", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1746, "license_type": "permissive", "max_line_length": 101, "num_lines": 57, "path": "/tests/Retry/ThrottlingFilterTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Retry;\n\nuse Aws\\Api\\ErrorParser\\JsonRpcErrorParser;\nuse Aws\\Retry\\ThrottlingFilter;\nuse GuzzleHttp\\Transaction;\nuse GuzzleHttp\\Client;\nuse GuzzleHttp\\Event\\CompleteEvent;\nuse GuzzleHttp\\Message\\Request;\nuse GuzzleHttp\\Message\\Response;\nuse GuzzleHttp\\Subscriber\\Retry\\RetrySubscriber;\nuse GuzzleHttp\\Stream\\Stream;\n\n/**\n * @covers \\Aws\\Retry\\ThrottlingFilter\n */\nclass ThrottlingFilterTest extends \\PHPUnit_Framework_TestCase\n{\n public function testIngoresWhenNoResponseIsPresent()\n {\n $ate = $this->getTrans();\n $f = new ThrottlingFilter(new JsonRpcErrorParser());\n $this->assertEquals(RetrySubscriber::DEFER, $f(2, $ate));\n }\n\n public function testIgnoresWhenNot400()\n {\n $ate = $this->getTrans();\n $ate->intercept(new Response(303));\n $f = new ThrottlingFilter(new JsonRpcErrorParser());\n $this->assertEquals(RetrySubscriber::DEFER, $f(2, $ate));\n }\n\n public function testRetriesWhenThrottled()\n {\n $ate = $this->getTrans();\n $ate->intercept(new Response(401, [], Stream::factory('{\"__type\":\"RequestLimitExceeded\"}')));\n $f = new ThrottlingFilter(new JsonRpcErrorParser());\n $this->assertEquals(RetrySubscriber::RETRY, $f(2, $ate));\n }\n\n public function testDefersWhenNotThrottled()\n {\n $ate = $this->getTrans();\n $ate->intercept(new Response(401, [], Stream::factory('{}')));\n $f = new ThrottlingFilter(new JsonRpcErrorParser());\n $this->assertEquals(RetrySubscriber::DEFER, $f(2, $ate));\n }\n\n private function getTrans()\n {\n return new CompleteEvent(new Transaction(\n new Client(),\n new Request('GET', 'http://foo.com')\n ));\n }\n}\n" }, { "alpha_fraction": 0.5315249562263489, "alphanum_fraction": 0.5315249562263489, "avg_line_length": 28.65217399597168, "blob_id": "d8470924cf39db514e5c32d9c7a1575aa1ddcbb8", "content_id": "c4da2dd0bf95676239fb20152473bab994f38a36", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1364, "license_type": "permissive", "max_line_length": 61, "num_lines": 46, "path": "/tests/UtilsTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test;\n\nuse Aws\\Utils;\n\n/**\n * @covers Aws\\Utils\n */\nclass UtilsTest extends \\PHPUnit_Framework_TestCase\n{\n public function testCreatesRecursiveDirIterator()\n {\n $iter = Utils::recursiveDirIterator(__DIR__);\n $this->assertInstanceOf('Iterator', $iter);\n $files = iterator_to_array($iter);\n $this->assertContains(__FILE__, $files);\n }\n\n public function testCreatesNonRecursiveDirIterator()\n {\n $iter = Utils::dirIterator(__DIR__);\n $this->assertInstanceOf('Iterator', $iter);\n $files = iterator_to_array($iter);\n $this->assertContains('UtilsTest.php', $files);\n }\n\n public function testComposesOrFunctions()\n {\n $a = function ($a, $b) { return null; };\n $b = function ($a, $b) { return $a . $b; };\n $c = function ($a, $b) { return 'C'; };\n $comp = Utils::orFn($a, $b, $c);\n $this->assertEquals('+-', $comp('+', '-'));\n }\n\n public function testReturnsNullWhenNonResolve()\n {\n $called = [];\n $a = function () use (&$called) { $called[] = 'a'; };\n $b = function () use (&$called) { $called[] = 'b'; };\n $c = function () use (&$called) { $called[] = 'c'; };\n $comp = Utils::orFn($a, $b, $c);\n $this->assertNull($comp());\n $this->assertEquals(['a', 'b', 'c'], $called);\n }\n}\n" }, { "alpha_fraction": 0.517241358757019, "alphanum_fraction": 0.5182266235351562, "avg_line_length": 26.432432174682617, "blob_id": "8e0fc193590b11e3941aa27d4537c439ac9f0317", "content_id": "bbb8c85772ef2319dcee5a9806f0b201464cafd2", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1015, "license_type": "permissive", "max_line_length": 89, "num_lines": 37, "path": "/src/Sqs/SqsClient.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Sqs;\n\nuse Aws\\AwsClient;\n\n/**\n * This client is used to interact with the **Amazon Simple Queue Service (Amazon SQS)**.\n */\nclass SqsClient extends AwsClient\n{\n public function __construct(array $config)\n {\n parent::__construct($config);\n $emitter = $this->getEmitter();\n $emitter->attach(new QueueUrlSubscriber());\n $emitter->attach(new Md5ValidatorSubscriber());\n }\n\n /**\n * Converts a queue URL into a queue ARN.\n *\n * @param string $queueUrl The queue URL to perform the action on.\n * Retrieved when the queue is first created.\n *\n * @return string An ARN representation of the queue URL.\n */\n public function getQueueArn($queueUrl)\n {\n return strtr($queueUrl, array(\n 'http://' => 'arn:aws:',\n 'https://' => 'arn:aws:',\n '.amazonaws.com' => '',\n '/' => ':',\n '.' => ':',\n ));\n }\n}\n" }, { "alpha_fraction": 0.394307941198349, "alphanum_fraction": 0.3973690867424011, "avg_line_length": 21.848772048950195, "blob_id": "63045137dd27fe9da261b3900ff1931b34e91b00", "content_id": "26c2a9467521d149edde6deeb8a54c93cdcd8806", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 24174, "license_type": "permissive", "max_line_length": 54, "num_lines": 1058, "path": "/src/data/logs-2014-03-28.api.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php return [\n 'metadata' => [\n 'apiVersion' => '2014-03-28',\n 'endpointPrefix' => 'logs',\n 'jsonVersion' => '1.1',\n 'serviceFullName' => 'Amazon CloudWatch Logs',\n 'signatureVersion' => 'v4',\n 'targetPrefix' => 'Logs_20140328',\n 'protocol' => 'json',\n ],\n 'operations' => [\n 'CreateLogGroup' => [\n 'name' => 'CreateLogGroup',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateLogGroupRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidParameterException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ResourceAlreadyExistsException',\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'exception' => true,\n ],\n [\n 'shape' => 'OperationAbortedException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ServiceUnavailableException',\n 'exception' => true,\n 'fault' => true,\n ],\n ],\n ],\n 'CreateLogStream' => [\n 'name' => 'CreateLogStream',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateLogStreamRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidParameterException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ResourceAlreadyExistsException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ResourceNotFoundException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ServiceUnavailableException',\n 'exception' => true,\n 'fault' => true,\n ],\n ],\n ],\n 'DeleteLogGroup' => [\n 'name' => 'DeleteLogGroup',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteLogGroupRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidParameterException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ResourceNotFoundException',\n 'exception' => true,\n ],\n [\n 'shape' => 'OperationAbortedException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ServiceUnavailableException',\n 'exception' => true,\n 'fault' => true,\n ],\n ],\n ],\n 'DeleteLogStream' => [\n 'name' => 'DeleteLogStream',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteLogStreamRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidParameterException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ResourceNotFoundException',\n 'exception' => true,\n ],\n [\n 'shape' => 'OperationAbortedException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ServiceUnavailableException',\n 'exception' => true,\n 'fault' => true,\n ],\n ],\n ],\n 'DeleteMetricFilter' => [\n 'name' => 'DeleteMetricFilter',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteMetricFilterRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidParameterException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ResourceNotFoundException',\n 'exception' => true,\n ],\n [\n 'shape' => 'OperationAbortedException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ServiceUnavailableException',\n 'exception' => true,\n 'fault' => true,\n ],\n ],\n ],\n 'DeleteRetentionPolicy' => [\n 'name' => 'DeleteRetentionPolicy',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteRetentionPolicyRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidParameterException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ResourceNotFoundException',\n 'exception' => true,\n ],\n [\n 'shape' => 'OperationAbortedException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ServiceUnavailableException',\n 'exception' => true,\n 'fault' => true,\n ],\n ],\n ],\n 'DescribeLogGroups' => [\n 'name' => 'DescribeLogGroups',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeLogGroupsRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeLogGroupsResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidParameterException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ServiceUnavailableException',\n 'exception' => true,\n 'fault' => true,\n ],\n ],\n ],\n 'DescribeLogStreams' => [\n 'name' => 'DescribeLogStreams',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeLogStreamsRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeLogStreamsResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidParameterException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ResourceNotFoundException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ServiceUnavailableException',\n 'exception' => true,\n 'fault' => true,\n ],\n ],\n ],\n 'DescribeMetricFilters' => [\n 'name' => 'DescribeMetricFilters',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeMetricFiltersRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeMetricFiltersResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidParameterException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ResourceNotFoundException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ServiceUnavailableException',\n 'exception' => true,\n 'fault' => true,\n ],\n ],\n ],\n 'GetLogEvents' => [\n 'name' => 'GetLogEvents',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'GetLogEventsRequest',\n ],\n 'output' => [\n 'shape' => 'GetLogEventsResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidParameterException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ResourceNotFoundException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ServiceUnavailableException',\n 'exception' => true,\n 'fault' => true,\n ],\n ],\n ],\n 'PutLogEvents' => [\n 'name' => 'PutLogEvents',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'PutLogEventsRequest',\n ],\n 'output' => [\n 'shape' => 'PutLogEventsResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidParameterException',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidSequenceTokenException',\n 'exception' => true,\n ],\n [\n 'shape' => 'DataAlreadyAcceptedException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ResourceNotFoundException',\n 'exception' => true,\n ],\n [\n 'shape' => 'OperationAbortedException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ServiceUnavailableException',\n 'exception' => true,\n 'fault' => true,\n ],\n ],\n ],\n 'PutMetricFilter' => [\n 'name' => 'PutMetricFilter',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'PutMetricFilterRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidParameterException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ResourceNotFoundException',\n 'exception' => true,\n ],\n [\n 'shape' => 'OperationAbortedException',\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ServiceUnavailableException',\n 'exception' => true,\n 'fault' => true,\n ],\n ],\n ],\n 'PutRetentionPolicy' => [\n 'name' => 'PutRetentionPolicy',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'PutRetentionPolicyRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidParameterException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ResourceNotFoundException',\n 'exception' => true,\n ],\n [\n 'shape' => 'OperationAbortedException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ServiceUnavailableException',\n 'exception' => true,\n 'fault' => true,\n ],\n ],\n ],\n 'TestMetricFilter' => [\n 'name' => 'TestMetricFilter',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'TestMetricFilterRequest',\n ],\n 'output' => [\n 'shape' => 'TestMetricFilterResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidParameterException',\n 'exception' => true,\n ],\n [\n 'shape' => 'ServiceUnavailableException',\n 'exception' => true,\n 'fault' => true,\n ],\n ],\n ],\n ],\n 'shapes' => [\n 'Arn' => [\n 'type' => 'string',\n ],\n 'CreateLogGroupRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'logGroupName',\n ],\n 'members' => [\n 'logGroupName' => [\n 'shape' => 'LogGroupName',\n ],\n ],\n ],\n 'CreateLogStreamRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'logGroupName',\n 'logStreamName',\n ],\n 'members' => [\n 'logGroupName' => [\n 'shape' => 'LogGroupName',\n ],\n 'logStreamName' => [\n 'shape' => 'LogStreamName',\n ],\n ],\n ],\n 'DataAlreadyAcceptedException' => [\n 'type' => 'structure',\n 'members' => [\n 'expectedSequenceToken' => [\n 'shape' => 'SequenceToken',\n ],\n ],\n 'exception' => true,\n ],\n 'Days' => [\n 'type' => 'integer',\n ],\n 'DeleteLogGroupRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'logGroupName',\n ],\n 'members' => [\n 'logGroupName' => [\n 'shape' => 'LogGroupName',\n ],\n ],\n ],\n 'DeleteLogStreamRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'logGroupName',\n 'logStreamName',\n ],\n 'members' => [\n 'logGroupName' => [\n 'shape' => 'LogGroupName',\n ],\n 'logStreamName' => [\n 'shape' => 'LogStreamName',\n ],\n ],\n ],\n 'DeleteMetricFilterRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'logGroupName',\n 'filterName',\n ],\n 'members' => [\n 'logGroupName' => [\n 'shape' => 'LogGroupName',\n ],\n 'filterName' => [\n 'shape' => 'FilterName',\n ],\n ],\n ],\n 'DeleteRetentionPolicyRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'logGroupName',\n ],\n 'members' => [\n 'logGroupName' => [\n 'shape' => 'LogGroupName',\n ],\n ],\n ],\n 'DescribeLimit' => [\n 'type' => 'integer',\n 'min' => 1,\n 'max' => 50,\n ],\n 'DescribeLogGroupsRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'logGroupNamePrefix' => [\n 'shape' => 'LogGroupName',\n ],\n 'nextToken' => [\n 'shape' => 'NextToken',\n ],\n 'limit' => [\n 'shape' => 'DescribeLimit',\n ],\n ],\n ],\n 'DescribeLogGroupsResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'logGroups' => [\n 'shape' => 'LogGroups',\n ],\n 'nextToken' => [\n 'shape' => 'NextToken',\n ],\n ],\n ],\n 'DescribeLogStreamsRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'logGroupName',\n ],\n 'members' => [\n 'logGroupName' => [\n 'shape' => 'LogGroupName',\n ],\n 'logStreamNamePrefix' => [\n 'shape' => 'LogStreamName',\n ],\n 'nextToken' => [\n 'shape' => 'NextToken',\n ],\n 'limit' => [\n 'shape' => 'DescribeLimit',\n ],\n ],\n ],\n 'DescribeLogStreamsResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'logStreams' => [\n 'shape' => 'LogStreams',\n ],\n 'nextToken' => [\n 'shape' => 'NextToken',\n ],\n ],\n ],\n 'DescribeMetricFiltersRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'logGroupName',\n ],\n 'members' => [\n 'logGroupName' => [\n 'shape' => 'LogGroupName',\n ],\n 'filterNamePrefix' => [\n 'shape' => 'FilterName',\n ],\n 'nextToken' => [\n 'shape' => 'NextToken',\n ],\n 'limit' => [\n 'shape' => 'DescribeLimit',\n ],\n ],\n ],\n 'DescribeMetricFiltersResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'metricFilters' => [\n 'shape' => 'MetricFilters',\n ],\n 'nextToken' => [\n 'shape' => 'NextToken',\n ],\n ],\n ],\n 'EventMessage' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 32768,\n ],\n 'EventNumber' => [\n 'type' => 'long',\n ],\n 'EventsLimit' => [\n 'type' => 'integer',\n 'min' => 1,\n 'max' => 10000,\n ],\n 'ExtractedValues' => [\n 'type' => 'map',\n 'key' => [\n 'shape' => 'Token',\n ],\n 'value' => [\n 'shape' => 'Value',\n ],\n ],\n 'FilterCount' => [\n 'type' => 'integer',\n ],\n 'FilterName' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 512,\n 'pattern' => '[^:*]*',\n ],\n 'FilterPattern' => [\n 'type' => 'string',\n 'min' => 0,\n 'max' => 512,\n ],\n 'GetLogEventsRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'logGroupName',\n 'logStreamName',\n ],\n 'members' => [\n 'logGroupName' => [\n 'shape' => 'LogGroupName',\n ],\n 'logStreamName' => [\n 'shape' => 'LogStreamName',\n ],\n 'startTime' => [\n 'shape' => 'Timestamp',\n ],\n 'endTime' => [\n 'shape' => 'Timestamp',\n ],\n 'nextToken' => [\n 'shape' => 'NextToken',\n ],\n 'limit' => [\n 'shape' => 'EventsLimit',\n ],\n 'startFromHead' => [\n 'shape' => 'StartFromHead',\n ],\n ],\n ],\n 'GetLogEventsResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'events' => [\n 'shape' => 'OutputLogEvents',\n ],\n 'nextForwardToken' => [\n 'shape' => 'NextToken',\n ],\n 'nextBackwardToken' => [\n 'shape' => 'NextToken',\n ],\n ],\n ],\n 'InputLogEvent' => [\n 'type' => 'structure',\n 'required' => [\n 'timestamp',\n 'message',\n ],\n 'members' => [\n 'timestamp' => [\n 'shape' => 'Timestamp',\n ],\n 'message' => [\n 'shape' => 'EventMessage',\n ],\n ],\n ],\n 'InputLogEvents' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'InputLogEvent',\n ],\n 'min' => 1,\n 'max' => 1000,\n ],\n 'InvalidParameterException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'InvalidSequenceTokenException' => [\n 'type' => 'structure',\n 'members' => [\n 'expectedSequenceToken' => [\n 'shape' => 'SequenceToken',\n ],\n ],\n 'exception' => true,\n ],\n 'LimitExceededException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'LogGroup' => [\n 'type' => 'structure',\n 'members' => [\n 'logGroupName' => [\n 'shape' => 'LogGroupName',\n ],\n 'creationTime' => [\n 'shape' => 'Timestamp',\n ],\n 'retentionInDays' => [\n 'shape' => 'Days',\n ],\n 'metricFilterCount' => [\n 'shape' => 'FilterCount',\n ],\n 'arn' => [\n 'shape' => 'Arn',\n ],\n 'storedBytes' => [\n 'shape' => 'StoredBytes',\n ],\n ],\n ],\n 'LogGroupName' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 512,\n 'pattern' => '[\\\\.\\\\-_/#A-Za-z0-9]+',\n ],\n 'LogGroups' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'LogGroup',\n ],\n ],\n 'LogStream' => [\n 'type' => 'structure',\n 'members' => [\n 'logStreamName' => [\n 'shape' => 'LogStreamName',\n ],\n 'creationTime' => [\n 'shape' => 'Timestamp',\n ],\n 'firstEventTimestamp' => [\n 'shape' => 'Timestamp',\n ],\n 'lastEventTimestamp' => [\n 'shape' => 'Timestamp',\n ],\n 'lastIngestionTime' => [\n 'shape' => 'Timestamp',\n ],\n 'uploadSequenceToken' => [\n 'shape' => 'SequenceToken',\n ],\n 'arn' => [\n 'shape' => 'Arn',\n ],\n 'storedBytes' => [\n 'shape' => 'StoredBytes',\n ],\n ],\n ],\n 'LogStreamName' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 512,\n 'pattern' => '[^:*]*',\n ],\n 'LogStreams' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'LogStream',\n ],\n ],\n 'MetricFilter' => [\n 'type' => 'structure',\n 'members' => [\n 'filterName' => [\n 'shape' => 'FilterName',\n ],\n 'filterPattern' => [\n 'shape' => 'FilterPattern',\n ],\n 'metricTransformations' => [\n 'shape' => 'MetricTransformations',\n ],\n 'creationTime' => [\n 'shape' => 'Timestamp',\n ],\n ],\n ],\n 'MetricFilterMatchRecord' => [\n 'type' => 'structure',\n 'members' => [\n 'eventNumber' => [\n 'shape' => 'EventNumber',\n ],\n 'eventMessage' => [\n 'shape' => 'EventMessage',\n ],\n 'extractedValues' => [\n 'shape' => 'ExtractedValues',\n ],\n ],\n ],\n 'MetricFilterMatches' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'MetricFilterMatchRecord',\n ],\n ],\n 'MetricFilters' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'MetricFilter',\n ],\n ],\n 'MetricName' => [\n 'type' => 'string',\n 'max' => 255,\n 'pattern' => '[^:*$]*',\n ],\n 'MetricNamespace' => [\n 'type' => 'string',\n 'max' => 255,\n 'pattern' => '[^:*$]*',\n ],\n 'MetricTransformation' => [\n 'type' => 'structure',\n 'required' => [\n 'metricName',\n 'metricNamespace',\n 'metricValue',\n ],\n 'members' => [\n 'metricName' => [\n 'shape' => 'MetricName',\n ],\n 'metricNamespace' => [\n 'shape' => 'MetricNamespace',\n ],\n 'metricValue' => [\n 'shape' => 'MetricValue',\n ],\n ],\n ],\n 'MetricTransformations' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'MetricTransformation',\n ],\n 'min' => 1,\n 'max' => 1,\n ],\n 'MetricValue' => [\n 'type' => 'string',\n 'max' => 100,\n ],\n 'NextToken' => [\n 'type' => 'string',\n ],\n 'OperationAbortedException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'OutputLogEvent' => [\n 'type' => 'structure',\n 'members' => [\n 'timestamp' => [\n 'shape' => 'Timestamp',\n ],\n 'message' => [\n 'shape' => 'EventMessage',\n ],\n 'ingestionTime' => [\n 'shape' => 'Timestamp',\n ],\n ],\n ],\n 'OutputLogEvents' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'OutputLogEvent',\n ],\n ],\n 'PutLogEventsRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'logGroupName',\n 'logStreamName',\n 'logEvents',\n ],\n 'members' => [\n 'logGroupName' => [\n 'shape' => 'LogGroupName',\n ],\n 'logStreamName' => [\n 'shape' => 'LogStreamName',\n ],\n 'logEvents' => [\n 'shape' => 'InputLogEvents',\n ],\n 'sequenceToken' => [\n 'shape' => 'SequenceToken',\n ],\n ],\n ],\n 'PutLogEventsResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'nextSequenceToken' => [\n 'shape' => 'SequenceToken',\n ],\n ],\n ],\n 'PutMetricFilterRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'logGroupName',\n 'filterName',\n 'filterPattern',\n 'metricTransformations',\n ],\n 'members' => [\n 'logGroupName' => [\n 'shape' => 'LogGroupName',\n ],\n 'filterName' => [\n 'shape' => 'FilterName',\n ],\n 'filterPattern' => [\n 'shape' => 'FilterPattern',\n ],\n 'metricTransformations' => [\n 'shape' => 'MetricTransformations',\n ],\n ],\n ],\n 'PutRetentionPolicyRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'logGroupName',\n 'retentionInDays',\n ],\n 'members' => [\n 'logGroupName' => [\n 'shape' => 'LogGroupName',\n ],\n 'retentionInDays' => [\n 'shape' => 'Days',\n ],\n ],\n ],\n 'ResourceAlreadyExistsException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'ResourceNotFoundException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n ],\n 'SequenceToken' => [\n 'type' => 'string',\n 'min' => 1,\n ],\n 'ServiceUnavailableException' => [\n 'type' => 'structure',\n 'members' => [],\n 'exception' => true,\n 'fault' => true,\n ],\n 'StartFromHead' => [\n 'type' => 'boolean',\n ],\n 'StoredBytes' => [\n 'type' => 'long',\n 'min' => 0,\n ],\n 'TestEventMessages' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'EventMessage',\n ],\n 'min' => 1,\n 'max' => 50,\n ],\n 'TestMetricFilterRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'filterPattern',\n 'logEventMessages',\n ],\n 'members' => [\n 'filterPattern' => [\n 'shape' => 'FilterPattern',\n ],\n 'logEventMessages' => [\n 'shape' => 'TestEventMessages',\n ],\n ],\n ],\n 'TestMetricFilterResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'matches' => [\n 'shape' => 'MetricFilterMatches',\n ],\n ],\n ],\n 'Timestamp' => [\n 'type' => 'long',\n 'min' => 0,\n ],\n 'Token' => [\n 'type' => 'string',\n ],\n 'Value' => [\n 'type' => 'string',\n ],\n ],\n];\n" }, { "alpha_fraction": 0.5468208193778992, "alphanum_fraction": 0.5849710702896118, "avg_line_length": 25.212121963500977, "blob_id": "4ff09377a0e08fcf7ed9325e892adea9b39d0574", "content_id": "239c32036f2955078b56080be9a4f1245c3e5f40", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 865, "license_type": "permissive", "max_line_length": 62, "num_lines": 33, "path": "/tests/Signature/sig_hack.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Signature;\n\nuse Aws\\Test\\Signature\\SignatureV2Test;\nuse Aws\\Test\\Signature\\SignatureV3HttpsTest;\n\n// Hack gmdate() to returned the canned result.\nfunction gmdate() {\n\n if (isset($_SERVER['aws_time'])) {\n switch (basename(debug_backtrace()[0]['file'])) {\n case 'SignatureV4.php':\n return '20110909T233600Z';\n case 'SignatureV2.php':\n return SignatureV2Test::DEFAULT_DATETIME;\n case 'SignatureV3Https.php':\n return SignatureV3HttpsTest::DEFAULT_DATETIME;\n }\n }\n\n return call_user_func_array('gmdate', func_get_args());\n}\n\nfunction time()\n{\n if (isset($_SERVER['aws_time'])) {\n return $_SERVER['aws_time'] === true\n ? strtotime('December 5, 2013 00:00:00 UTC')\n : $_SERVER['aws_time'];\n }\n\n return \\time();\n}\n" }, { "alpha_fraction": 0.7425287365913391, "alphanum_fraction": 0.7455938458442688, "avg_line_length": 28.659090042114258, "blob_id": "c559dfa77451001523b78562fe8f232378f24cae", "content_id": "c92b21536450b8d47469dbe2b75e8bf8bd7406fa", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 2610, "license_type": "permissive", "max_line_length": 124, "num_lines": 88, "path": "/Makefile", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "all: clean coverage docs\n\nclean:\n\trm -rf build/artifacts/*\n\tcd docs && make clean\n\ntest:\n\tvendor/bin/phpunit --testsuite=unit $(TEST)\n\ntravis:\n\tvendor/bin/phpunit --colors --testsuite=unit --coverage-text\n\ncoverage:\n\tvendor/bin/phpunit --testsuite=unit --coverage-html=build/artifacts/coverage $(TEST)\n\ncoverage-show:\n\topen build/artifacts/coverage/index.html\n\ninteg:\n\tvendor/bin/phpunit --debug --testsuite=integ $(TEST)\n\n# Packages the phar and zip\npackage: burgomaster\n\ttime php build/packager.php $(SERVICE)\n\n# Downloads a copy of Burgomaster\nburgomaster:\n\tmkdir -p build/artifacts\n\tcurl -s https://raw.githubusercontent.com/mtdowling/Burgomaster/0.0.2/src/Burgomaster.php > build/artifacts/Burgomaster.php\n\nguide:\n\tcd docs && make html\n\nguide-show:\n\topen docs/_build/html/index.html\n\napi:\n\ttime php build/artifacts/sami.phar update build/docs.php\n\napi-clean:\n\trm -rf build/artifacts/docs/build build/artifacts/docs/cache build/artifacts/docs/theme build/artifacts/aws-docs-api.zip\n\napi-show:\n\topen build/artifacts/docs/build/index.html\n\napi-package:\n\tzip -r build/artifacts/aws-docs-api.zip build/artifacts/docs/build\n\napi-all: api-clean api api-package api-show\n\nbuild-apis:\n\tcd build && . build-apis.sh $(SRC)\n\n# Ensures that the TAG variable was passed to the make command\ncheck_tag:\n\t$(if $(TAG),,$(error TAG is not defined. Pass via \"make tag TAG=4.2.1\"))\n\n# Creates a release but does not push it. This task updates the changelog\n# with the TAG environment variable, replaces the VERSION constant, ensures\n# that the source is still valid after updating, commits the changelog and\n# updated VERSION constant, creates an annotated git tag using chag, and\n# prints out a diff of the last commit.\ntag: check_tag\n\t@echo Tagging $(TAG)\n\tchag update $(TAG)\n\tsed -i '' -e \"s/VERSION = '.*'/VERSION = '$(TAG)'/\" src/Sdk.php\n\tphp -l src/Sdk.php\n\tgit commit -a -m '$(TAG) release'\n\tchag tag\n\t@echo \"Release has been created. Push using 'make release'\"\n\t@echo \"Changes made in the release commit\"\n\tgit diff HEAD~1 HEAD\n\n# Creates a release based on the master branch and latest tag. This task\n# pushes the latest tag, pushes master, creates a phar and zip, and creates\n# a Github release. Use \"TAG=X.Y.Z make tag\" to create a release, and use\n# \"make release\" to push a release. This task requires that the\n# OAUTH_TOKEN environment variable is available and the token has permission\n# to push to the repository.\nrelease: check_tag package\n\tgit push origin v3\n\tgit push origin $(TAG)\n\tphp build/gh-release.php $(TAG)\n\n# Tags the repo and publishes a release.\nfull_release: tag release\n\n.PHONY: docs build-apis\n" }, { "alpha_fraction": 0.8514851331710815, "alphanum_fraction": 0.8514851331710815, "avg_line_length": 24.25, "blob_id": "22502d0a22549969417b60700a145a4efc22548d", "content_id": "17e432a9a01316660415fd90ea1d1a2b02a50197", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 101, "license_type": "permissive", "max_line_length": 68, "num_lines": 4, "path": "/src/Exception/UnresolvedCredentialsException.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Exception;\n\nclass UnresolvedCredentialsException extends CredentialsException {}\n" }, { "alpha_fraction": 0.5062500238418579, "alphanum_fraction": 0.550000011920929, "avg_line_length": 25.046510696411133, "blob_id": "cb1cac37367b21f2e213f82ad939bba65001032a", "content_id": "89bcc788afecf0b2c297a7c26e12f34174dae1aa", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1120, "license_type": "permissive", "max_line_length": 97, "num_lines": 43, "path": "/tests/Sqs/SqsClientTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Sqs;\n\nuse Aws\\Sqs\\SqsClient;\nuse Aws\\Test\\SdkTest;\n\n/**\n * @covers Aws\\Sqs\\SqsClient\n */\nclass SqsClientTest extends \\PHPUnit_Framework_TestCase\n{\n public function testAttachesSubscribers()\n {\n $client = new SqsClient([\n 'service' => 'sqs',\n 'region' => 'us-west-2',\n 'version' => 'latest'\n ]);\n\n $this->assertTrue(SdkTest::hasListener(\n $client->getEmitter(),\n 'Aws\\Sqs\\QueueUrlSubscriber',\n 'prepared'\n ));\n\n $this->assertTrue(SdkTest::hasListener(\n $client->getEmitter(),\n 'Aws\\Sqs\\Md5ValidatorSubscriber',\n 'process'\n ));\n }\n\n public function testGetQueueArn()\n {\n $url = 'https://sqs.us-east-1.amazonaws.com/057737625318/php-integ-sqs-queue-1359765974';\n $arn = 'arn:aws:sqs:us-east-1:057737625318:php-integ-sqs-queue-1359765974';\n $sqs = SqsClient::factory([\n 'region' => 'us-east-1',\n 'version' => 'latest'\n ]);\n $this->assertEquals($arn, $sqs->getQueueArn($url));\n }\n}\n" }, { "alpha_fraction": 0.5425100922584534, "alphanum_fraction": 0.5463205575942993, "avg_line_length": 26.625, "blob_id": "4fb25de2a412f2f86b722f7b13dc9a3f6119550f", "content_id": "c3dd49029bbd2e4e8fee0763f97c4e5a561c2bad", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4199, "license_type": "permissive", "max_line_length": 80, "num_lines": 152, "path": "/src/S3/BatchDelete.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\S3;\n\nuse Aws\\AwsClientInterface;\nuse Aws\\Result;\nuse Aws\\S3\\Exception\\DeleteMultipleObjectsException;\nuse GuzzleHttp\\Command\\Event\\PreparedEvent;\n\n/**\n * Implements a queue for deleting objects from an Amazon S3 bucket.\n *\n * You can enqueue objects to delete using the addObject() method by passing\n * the object key and optional version ID. Call the delete() method of\n * BatchDelete when you are ready to delete the queued objects.\n */\nclass BatchDelete implements \\Countable\n{\n private $client;\n private $bucket;\n private $mfa;\n private $batchSize = 1000;\n private $objects = [];\n\n /**\n * The constructor accepts an optional hash of configuration options:\n *\n * - mfa: MFA token used when contacting the Amazon S3 API.\n * - batch_size: The size of each delete batch. Defaults to 1000.\n *\n * @param AwsClientInterface $client Client used to transfer the requests\n * @param string $bucket Bucket that stores the objects\n * @param array $options Hash of options used with the batch\n * @throws \\InvalidArgumentException if the provided batch_size is <= 0\n */\n public function __construct(\n AwsClientInterface $client,\n $bucket,\n array $options = []\n ) {\n $this->client = $client;\n $this->bucket = $bucket;\n\n if (isset($options['mfa'])) {\n $this->mfa = $options['mfa'];\n }\n\n if (isset($options['batch_size'])) {\n if ($options['batch_size'] <= 0) {\n throw new \\InvalidArgumentException('batch_size is not > 0');\n }\n $this->batchSize = $options['batch_size'];\n }\n }\n\n /**\n * Add an object to the batch to be deleted.\n *\n * @param string $key Key name of the object to delete.\n * @param string $versionId VersionId for the specific version of the\n * object to delete.\n */\n public function addObject($key, $versionId = null)\n {\n if (!$versionId) {\n $this->objects[] = ['Key' => $key];\n } else {\n $this->objects[] = ['Key' => $key, 'VersionId' => $versionId];\n }\n }\n\n /**\n * Returns an array of the objects that are queued for deletion.\n *\n * @return array\n */\n public function getQueue()\n {\n return $this->objects;\n }\n\n /**\n * Returns the number of enqueued objects to delete\n *\n * @return int\n */\n public function count()\n {\n return count($this->objects);\n }\n\n /**\n * Deletes the queued objects.\n *\n * @return array Returns an array of deleted key information. Each value\n * in the array contains a 'Key' and optionally\n * 'DeleteMarker' and 'DeleteMarkerVersionId' keys.\n *\n * @throws DeleteMultipleObjectsException\n */\n public function delete()\n {\n $results = [];\n\n while ($batch = $this->getNextBatch()) {\n $result = $this->deleteBatch($batch);\n $results = array_merge($results, (array) $result['Deleted']);\n }\n\n return $results;\n }\n\n private function getNextBatch()\n {\n $batch = [];\n\n for ($i = 0; $i < $this->batchSize && $this->objects; $i++) {\n $batch[] = array_shift($this->objects);\n }\n\n return $batch;\n }\n\n private function deleteBatch(array $batch)\n {\n $command = $this->client->getCommand('DeleteObjects', [\n 'Bucket' => $this->bucket,\n 'Delete' => [\n 'Objects' => $batch\n ]\n ]);\n\n if ($this->mfa) {\n $command->getEmitter()->on('prepared', function (PreparedEvent $e) {\n $e->getRequest()->setHeader('x-amz-mfa', $this->mfa);\n });\n }\n\n return $this->process($this->client->execute($command));\n }\n\n private function process(Result $result)\n {\n if (!empty($result['Errors'])) {\n throw new DeleteMultipleObjectsException(\n $result['Deleted'] ?: [],\n $result['Errors']\n );\n }\n\n return $result;\n }\n}\n" }, { "alpha_fraction": 0.5261003375053406, "alphanum_fraction": 0.5454784631729126, "avg_line_length": 32.621212005615234, "blob_id": "b6c6d9a13d704139895e64c0d06fc889c3ed3d21", "content_id": "4a3f7d028268f56ec834069b0f7e5d861f6f6b7a", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 26628, "license_type": "permissive", "max_line_length": 91, "num_lines": 792, "path": "/tests/S3/StreamWrapperTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\S3;\n\nuse Aws\\S3\\S3Client;\nuse Aws\\S3\\StreamWrapper;\nuse Aws\\Test\\UsesServiceTrait;\nuse GuzzleHttp\\Message\\Response;\nuse GuzzleHttp\\Stream\\NoSeekStream;\nuse GuzzleHttp\\Stream\\Stream;\nuse GuzzleHttp\\Subscriber\\History;\nuse GuzzleHttp\\Command\\Event\\PreparedEvent;\n\n/**\n * @covers Aws\\S3\\StreamWrapper\n */\nclass StreamWrapperTest extends \\PHPUnit_Framework_TestCase\n{\n use UsesServiceTrait;\n\n /** @var S3Client */\n private $client;\n\n public function setUp()\n {\n $this->client = $this->getTestClient('S3', ['region' => 'us-east-1']);\n $this->client->registerStreamWrapper();\n }\n\n public function tearDown()\n {\n stream_wrapper_unregister('s3');\n $this->client = null;\n }\n\n public function testRegistersStreamWrapperOnlyOnce()\n {\n StreamWrapper::register($this->client);\n $this->assertContains('s3', stream_get_wrappers());\n StreamWrapper::register($this->client);\n }\n\n /**\n * @expectedException \\PHPUnit_Framework_Error_Warning\n * @expectedExceptionMessage Cannot open a bucket\n */\n public function testCannotOpenBuckets()\n {\n fopen('s3://bucket', 'r');\n }\n\n /**\n * @expectedException \\PHPUnit_Framework_Error_Warning\n * @expectedExceptionMessage Mode not supported\n */\n public function testSupportsOnlyReadWriteXA()\n {\n fopen('s3://bucket/key', 'c');\n }\n\n /**\n * @expectedException \\PHPUnit_Framework_Error_Warning\n * @expectedExceptionMessage s3://bucket/key already exists on Amazon S3\n */\n public function testValidatesXMode()\n {\n $this->addMockResponses($this->client, [new Response(200)]);\n fopen('s3://bucket/key', 'x');\n }\n\n public function testSuccessfulXMode()\n {\n $this->addMockResponses(\n $this->client,\n [new Response(404), new Response(200)]\n );\n $r = fopen('s3://bucket/key', 'x');\n fclose($r);\n }\n\n public function testOpensNonSeekableReadStream()\n {\n $stream = fopen('php://temp', 'r+');\n fwrite($stream, 'foo');\n fseek($stream, 0);\n\n $this->addMockResponses($this->client, [\n new Response(200, [], new NoSeekStream(new Stream($stream)))\n ], false);\n\n $s = fopen('s3://bucket/key', 'r');\n $this->assertEquals(0, ftell($s));\n $this->assertFalse(feof($s));\n $this->assertEquals('foo', fread($s, 4));\n $this->assertEquals(3, ftell($s));\n $this->assertEquals(-1, fseek($s, 0));\n $this->assertEquals('', stream_get_contents($s));\n $this->assertTrue(feof($s));\n $this->assertTrue(fclose($s));\n }\n\n public function testOpensSeekableReadStream()\n {\n $stream = fopen('php://temp', 'r+');\n fwrite($stream, 'testing 123');\n fseek($stream, 0);\n\n $this->addMockResponses($this->client, [\n new Response(200, [], new NoSeekStream(new Stream($stream)))\n ], false);\n\n $s = fopen('s3://bucket/ket', 'r', false, stream_context_create([\n 's3' => ['seekable' => true]\n ]));\n\n $this->assertEquals(0, ftell($s));\n $this->assertFalse(feof($s));\n $this->assertEquals('test', fread($s, 4));\n $this->assertEquals(4, ftell($s));\n $this->assertEquals(0, fseek($s, 0));\n $this->assertEquals('testing 123', stream_get_contents($s));\n $this->assertTrue(feof($s));\n $this->assertTrue(fclose($s));\n }\n\n public function testAttemptsToGuessTheContentType()\n {\n $history = new History();\n $this->client->getHttpClient()->getEmitter()->attach($history);\n $this->addMockResponses($this->client, [new Response(200)]);\n file_put_contents('s3://foo/bar.xml', 'test');\n $this->assertEquals(\n 'application/xml',\n $history->getLastRequest()->getHeader('Content-Type')\n );\n }\n\n public function testCanOpenWriteOnlyStreams()\n {\n $history = new History();\n $this->client->getHttpClient()->getEmitter()->attach($history);\n $this->addMockResponses($this->client, [new Response(204)]);\n $s = fopen('s3://bucket/key', 'w');\n $this->assertEquals(4, fwrite($s, 'test'));\n $this->assertTrue(fclose($s));\n\n // Ensure that the stream was flushed and sent the upload\n $request = $history->getLastRequest();\n $this->assertEquals(1, count($history));\n $this->assertEquals('PUT', $request->getMethod());\n $this->assertEquals('test', (string) $request->getBody());\n $this->assertEquals(4, (string) $request->getHeader('Content-Length'));\n }\n\n /**\n * @expectedException \\PHPUnit_Framework_Error_Warning\n * @expectedExceptionMessage 403 Forbidden\n */\n public function testTriggersErrorInsteadOfExceptionWhenWriteFlushFails()\n {\n $this->addMockResponses($this->client, [new Response(403)]);\n $s = fopen('s3://bucket/key', 'w');\n fwrite($s, 'test');\n fclose($s);\n }\n\n public function testCanOpenAppendStreamsWithOriginalFile()\n {\n $history = new History();\n $this->client->getHttpClient()->getEmitter()->attach($history);\n\n // Queue the 200 response that will load the original, and queue the\n // 204 flush response\n $this->addMockResponses($this->client, [\n new Response(200, [], Stream::factory('test')),\n new Response(204)\n ]);\n\n $s = fopen('s3://bucket/key', 'a');\n $this->assertEquals(4, ftell($s));\n $this->assertEquals(3, fwrite($s, 'ing'));\n $this->assertTrue(fclose($s));\n\n // Ensure that the stream was flushed and sent the upload\n $requests = $history->getRequests();\n $this->assertEquals(2, count($requests));\n $this->assertEquals('GET', $requests[0]->getMethod());\n $this->assertEquals('/key', $requests[0]->getResource());\n $this->assertEquals('PUT', $requests[1]->getMethod());\n $this->assertEquals('/key', $requests[1]->getResource());\n $this->assertEquals('testing', (string) $requests[1]->getBody());\n $this->assertEquals(7, $requests[1]->getHeader('Content-Length'));\n }\n\n public function testCanOpenAppendStreamsWithMissingFile()\n {\n $this->addMockResponses($this->client, [\n new Response(404),\n new Response(204)\n ]);\n\n $s = fopen('s3://bucket/key', 'a');\n $this->assertEquals(0, ftell($s));\n $this->assertTrue(fclose($s));\n }\n\n public function testCanUnlinkFiles()\n {\n $history = new History();\n $this->client->getHttpClient()->getEmitter()->attach($history);\n $this->addMockResponses($this->client, [new Response(204)]);\n $this->assertTrue(unlink('s3://bucket/key'));\n $requests = $history->getRequests();\n $this->assertEquals(1, count($requests));\n $this->assertEquals('DELETE', $requests[0]->getMethod());\n $this->assertEquals('/key', $requests[0]->getResource());\n $this->assertEquals('bucket.s3.amazonaws.com', $requests[0]->getHost());\n }\n\n /**\n * @expectedException \\PHPUnit_Framework_Error_Warning\n * @expectedExceptionMessage 403 Forbidden\n */\n public function testThrowsErrorsWhenUnlinkFails()\n {\n $this->addMockResponses($this->client, [new Response(403)]);\n $this->assertFalse(unlink('s3://bucket/key'));\n }\n\n public function testCreatingBucketWithNoBucketReturnsFalse()\n {\n $this->assertFalse(mkdir('s3://'));\n }\n\n /**\n * @expectedExceptionMessage Bucket already exists: s3://already-existing-bucket\n * @expectedException \\PHPUnit_Framework_Error_Warning\n */\n public function testCreatingAlreadyExistingBucketRaisesError()\n {\n $this->addMockResponses($this->client, [new Response(200)]);\n mkdir('s3://already-existing-bucket');\n }\n\n /**\n * @expectedExceptionMessage Subfolder already exists: s3://already-existing-bucket/key\n * @expectedException \\PHPUnit_Framework_Error_Warning\n */\n public function testCreatingAlreadyExistingBucketForKeyRaisesError()\n {\n $this->addMockResponses($this->client, [new Response(200)]);\n mkdir('s3://already-existing-bucket/key');\n }\n\n public function testCreatingBucketsSetsAclBasedOnPermissions()\n {\n $history = new History();\n $this->client->getHttpClient()->getEmitter()->attach($history);\n\n $this->addMockResponses($this->client, [\n new Response(404), new Response(204), // mkdir #1\n new Response(404), new Response(204), // mkdir #2\n new Response(404), new Response(204), // mkdir #3\n ]);\n\n $this->assertTrue(mkdir('s3://bucket', 0777));\n $this->assertTrue(mkdir('s3://bucket', 0601));\n $this->assertTrue(mkdir('s3://bucket', 0500));\n\n $requests = $history->getRequests();\n $this->assertEquals(6, count($requests));\n\n $this->assertEquals('HEAD', $requests[0]->getMethod());\n $this->assertEquals('HEAD', $requests[2]->getMethod());\n $this->assertEquals('HEAD', $requests[4]->getMethod());\n\n $this->assertEquals('PUT', $requests[1]->getMethod());\n $this->assertEquals('/', $requests[1]->getResource());\n $this->assertEquals('bucket.s3.amazonaws.com', $requests[1]->getHost());\n $this->assertContains('public-read', (string) $requests[1]);\n $this->assertContains('authenticated-read', (string) $requests[3]);\n $this->assertContains('private', (string) $requests[5]);\n }\n\n public function testCreatesNestedSubfolder()\n {\n $history = new History();\n $this->client->getHttpClient()->getEmitter()->attach($history);\n\n $this->addMockResponses($this->client, [\n new Response(404), new Response(204)\n ]);\n\n $this->assertTrue(mkdir('s3://bucket/key/', 0777));\n $requests = $history->getRequests();\n $this->assertEquals(2, count($requests));\n $this->assertEquals('HEAD', $requests[0]->getMethod());\n $this->assertEquals('PUT', $requests[1]->getMethod());\n $this->assertContains('public-read', (string) $requests[1]);\n }\n\n /**\n * @expectedException \\PHPUnit_Framework_Error_Warning\n * @expectedExceptionMessage specify a bucket\n */\n public function testCannotDeleteS3()\n {\n rmdir('s3://');\n }\n\n /**\n * @expectedException \\PHPUnit_Framework_Error_Warning\n * @expectedExceptionMessage 403 Forbidden\n */\n public function testRmDirWithExceptionTriggersError()\n {\n $this->addMockResponses($this->client, [new Response(403)]);\n rmdir('s3://bucket');\n }\n\n public function testCanDeleteBucketWithRmDir()\n {\n $history = new History();\n $this->client->getHttpClient()->getEmitter()->attach($history);\n $this->addMockResponses($this->client, [new Response(204)]);\n $this->assertTrue(rmdir('s3://bucket'));\n $requests = $history->getRequests();\n $this->assertEquals(1, count($requests));\n $this->assertEquals('DELETE', $requests[0]->getMethod());\n $this->assertEquals('/', $requests[0]->getResource());\n $this->assertEquals('bucket.s3.amazonaws.com', $requests[0]->getHost());\n }\n\n public function rmdirProvider()\n {\n return array(\n array('s3://bucket/object/'),\n array('s3://bucket/object'),\n );\n }\n\n /**\n * @dataProvider rmdirProvider\n */\n public function testCanDeleteObjectWithRmDir($path)\n {\n $history = new History();\n $this->client->getHttpClient()->getEmitter()->attach($history);\n $this->addMockResponses($this->client, [\n new Response(200),\n new Response(204)\n ]);\n $this->assertTrue(rmdir($path));\n $requests = $history->getRequests();\n $this->assertEquals(1, count($requests));\n $this->assertEquals('GET', $requests[0]->getMethod());\n $this->assertEquals('object/', $requests[0]->getQuery()['prefix']);\n }\n\n public function testCanDeleteNestedFolderWithRmDir()\n {\n $history = new History();\n $this->client->getHttpClient()->getEmitter()->attach($history);\n $xml = <<<EOT\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">\n <Name>foo</Name>\n <Delimiter>/</Delimiter>\n <IsTruncated>false</IsTruncated>\n <Contents>\n <Key>bar/</Key>\n </Contents>\n</ListBucketResult>\nEOT;\n $this->addMockResponses($this->client, [\n new Response(200, [], Stream::factory($xml)),\n new Response(204)\n ]);\n $this->assertTrue(rmdir('s3://foo/bar'));\n $requests = $history->getRequests();\n $this->assertEquals(2, count($requests));\n $this->assertEquals('GET', $requests[0]->getMethod());\n $this->assertEquals('bar/', $requests[0]->getQuery()['prefix']);\n $this->assertEquals('DELETE', $requests[1]->getMethod());\n $this->assertEquals('/bar/', $requests[1]->getPath());\n }\n\n /**\n * @expectedException \\PHPUnit_Framework_Error_Warning\n * @expectedExceptionMessage The Amazon S3 stream wrapper only supports copying objects\n */\n public function testRenameEnsuresKeyIsSet()\n {\n rename('s3://foo/bar', 's3://baz');\n }\n\n /**\n * @expectedException \\PHPUnit_Framework_Error_Warning\n * @expectedExceptionMessage Forbidden\n */\n public function testRenameWithExceptionThrowsError()\n {\n $this->addMockResponses($this->client, [new Response(403)]);\n rename('s3://foo/bar', 's3://baz/bar');\n }\n\n public function testCanRenameObjects()\n {\n $history = new History();\n $this->client->getHttpClient()->getEmitter()->attach($history);\n $this->addMockResponses($this->client, [\n new Response(204),\n new Response(204)\n ]);\n $this->assertTrue(rename('s3://bucket/key', 's3://other/new_key'));\n $requests = $history->getRequests();\n $this->assertEquals(2, count($requests));\n $this->assertEquals('PUT', $requests[0]->getMethod());\n $this->assertEquals('/new_key', $requests[0]->getResource());\n $this->assertEquals('other.s3.amazonaws.com', $requests[0]->getHost());\n $this->assertEquals(\n '/bucket/key',\n $requests[0]->getHeader('x-amz-copy-source')\n );\n $this->assertEquals(\n 'COPY',\n $requests[0]->getHeader('x-amz-metadata-directive')\n );\n $this->assertEquals('DELETE', $requests[1]->getMethod());\n $this->assertEquals('/key', $requests[1]->getResource());\n $this->assertEquals('bucket.s3.amazonaws.com', $requests[1]->getHost());\n }\n\n public function testCanRenameObjectsWithCustomSettings()\n {\n $history = new History();\n $this->client->getHttpClient()->getEmitter()->attach($history);\n $this->addMockResponses($this->client, [\n new Response(204),\n new Response(204)\n ]);\n $this->assertTrue(rename(\n 's3://bucket/key',\n 's3://other/new_key',\n stream_context_create(['s3' => ['MetadataDirective' => 'REPLACE']])\n ));\n $requests = $history->getRequests();\n $this->assertEquals(2, count($requests));\n $this->assertEquals('PUT', $requests[0]->getMethod());\n $this->assertEquals('/new_key', $requests[0]->getResource());\n $this->assertEquals('other.s3.amazonaws.com', $requests[0]->getHost());\n $this->assertEquals(\n '/bucket/key',\n $requests[0]->getHeader('x-amz-copy-source')\n );\n $this->assertEquals(\n 'REPLACE',\n $requests[0]->getHeader('x-amz-metadata-directive')\n );\n }\n\n public function testStatS3andBuckets()\n {\n clearstatcache('s3://');\n $stat = stat('s3://');\n $this->assertEquals(0040777, $stat['mode']);\n $this->addMockResponses($this->client, [new Response(200)]);\n clearstatcache('s3://bucket');\n $stat = stat('s3://bucket');\n $this->assertEquals(0040777, $stat['mode']);\n }\n\n /**\n * @expectedException \\PHPUnit_Framework_Error_Warning\n * @expectedExceptionMessage Forbidden\n */\n public function testFailingStatTriggersError()\n {\n // Sends one request for HeadObject, then another for ListObjects\n $this->addMockResponses(\n $this->client,\n [new Response(403), new Response(403)]\n );\n clearstatcache('s3://bucket/key');\n stat('s3://bucket/key');\n }\n\n /**\n * @expectedException \\PHPUnit_Framework_Error_Warning\n * @expectedExceptionMessage File or directory not found: s3://bucket\n */\n public function testBucketNotFoundTriggersError()\n {\n $this->addMockResponses($this->client, [new Response(404)]);\n clearstatcache('s3://bucket');\n stat('s3://bucket');\n }\n\n public function testStatsRegularObjects()\n {\n $ts = strtotime('Tuesday, April 9 2013');\n $this->addMockResponses($this->client, [\n new Response(200, [\n 'Content-Length' => 5,\n 'Last-Modified' => gmdate('r', $ts)\n ])\n ]);\n clearstatcache('s3://bucket/key');\n $stat = stat('s3://bucket/key');\n $this->assertEquals(0100777, $stat['mode']);\n $this->assertEquals(5, $stat['size']);\n $this->assertEquals($ts, $stat['mtime']);\n $this->assertEquals($ts, $stat['ctime']);\n }\n\n public function testCanStatPrefix()\n {\n $xml = <<<EOT\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">\n <Name>bucket-1</Name>\n <Prefix></Prefix>\n <Marker></Marker>\n <MaxKeys></MaxKeys>\n <Delimiter>/</Delimiter>\n <IsTruncated>false</IsTruncated>\n <CommonPrefixes>\n <Prefix>g/</Prefix>\n </CommonPrefixes>\n</ListBucketResult>\nEOT;\n $this->addMockResponses($this->client, [\n new Response(404),\n new Response(200, [], Stream::factory($xml))\n ]);\n clearstatcache('s3://bucket/prefix');\n $stat = stat('s3://bucket/prefix');\n $this->assertEquals(0040777, $stat['mode']);\n }\n\n /**\n * @expectedException \\PHPUnit_Framework_Error_Warning\n * @expectedExceptionMessage File or directory not found: s3://bucket/prefix\n */\n public function testCannotStatPrefixWithNoResults()\n {\n $this->addMockResponses($this->client, [\n new Response(404),\n new Response(200)\n ]);\n clearstatcache('s3://bucket/prefix');\n stat('s3://bucket/prefix');\n }\n\n public function fileTypeProvider()\n {\n $none = <<<EOT\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">\n <IsTruncated>false</IsTruncated>\n</ListBucketResult>\nEOT;\n\n $hasKeys = <<<EOT\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">\n <Name>bucket-1</Name>\n <Prefix></Prefix>\n <Marker></Marker>\n <MaxKeys></MaxKeys>\n <Delimiter>/</Delimiter>\n <IsTruncated>true</IsTruncated>\n <Contents>\n <Key>e</Key>\n </Contents>\n</ListBucketResult>\nEOT;\n\n return [\n ['s3://', [], 'dir'],\n ['s3://t123', [new Response(200)], 'dir'],\n ['s3://t123/', [new Response(200)], 'dir'],\n ['s3://t123', [new Response(404)], 'error'],\n ['s3://t123/', [new Response(404)], 'error'],\n ['s3://t123/abc', [new Response(200)], 'file'],\n ['s3://t123/abc/', [new Response(200)], 'dir'],\n // Contains several keys, so this is a key prefix (directory)\n ['s3://t123/abc/', [\n new Response(404),\n new Response(200, [], Stream::factory($hasKeys))\n ], 'dir'],\n // No valid keys were found in the list objects call, so it's not\n // a file, directory, or key prefix.\n ['s3://t123/abc/', [\n new Response(404),\n new Response(200, [], Stream::factory($none))\n ], 'error'],\n ];\n }\n\n /**\n * @dataProvider fileTypeProvider\n */\n public function testDeterminesIfFileOrDir($uri, $responses, $result)\n {\n $history = new History();\n $this->client->getHttpClient()->getEmitter()->attach($history);\n\n if ($responses) {\n $this->addMockResponses($this->client, $responses);\n }\n\n clearstatcache();\n if ($result == 'error') {\n $err = false;\n set_error_handler(function ($e) use (&$err) { $err = true; });\n $actual = filetype($uri);\n restore_error_handler();\n $this->assertFalse($actual);\n $this->assertTrue($err);\n } else {\n $actual = filetype($uri);\n $this->assertSame($actual, $result);\n }\n\n $this->assertEquals(\n count($responses),\n count($history)\n );\n }\n\n /**\n * @expectedException \\PHPUnit_Framework_Error_Warning\n * @expectedExceptionMessage cannot represent a stream of type user-space\n */\n public function testStreamCastIsNotPossible()\n {\n $this->addMockResponses($this->client, [\n new Response(200, [], Stream::factory(''))\n ]);\n $r = fopen('s3://bucket/key', 'r');\n $read = [$r];\n $write = $except = null;\n stream_select($read, $write, $except, 0);\n }\n\n /**\n * @expectedException \\PHPUnit_Framework_Error_Warning\n * @expectedExceptionMessage No client in stream context\n */\n public function testEnsuresClientIsSet()\n {\n fopen('s3://bucket/key', 'r', false, stream_context_create([\n 's3' => ['client' => null]\n ]));\n }\n\n public function testDoesNotErrorOnIsLink()\n {\n $this->addMockResponses($this->client, [new Response(404)]);\n $this->assertFalse(is_link('s3://bucket/key'));\n }\n\n public function testDoesNotErrorOnFileExists()\n {\n $this->addMockResponses($this->client, [new Response(404)]);\n $this->assertFalse(file_exists('s3://bucket/key'));\n }\n\n public function testProvidesDirectoriesForS3()\n {\n $results = [\n [\n 'IsTruncated' => true,\n 'NextMarker' => 'b/',\n 'Delimiter' => '/',\n 'Name' => 'bucket',\n 'Prefix' => '',\n 'MaxKeys' => 1000,\n 'CommonPrefixes' => [['Prefix' => 'a/'], ['Prefix' => 'b/']]\n ],\n [\n 'IsTruncated' => true,\n 'Marker' => '',\n 'Delimiter' => '/',\n 'Contents' => [['Key' => 'c']],\n 'Name' => 'bucket',\n 'Prefix' => '',\n 'MaxKeys' => 1000,\n 'CommonPrefixes' => [['Prefix' => 'd/']]\n ],\n [\n 'IsTruncated' => true,\n 'Marker' => '',\n 'Delimiter' => '/',\n 'Contents' => [['Key' => 'e'], ['Key' => 'f']],\n 'Name' => 'bucket',\n 'Prefix' => '',\n 'MaxKeys' => 1000\n ],\n [\n 'IsTruncated' => true,\n 'Marker' => '',\n 'Delimiter' => '/',\n 'Name' => 'bucket',\n 'Prefix' => '',\n 'NextMarker' => 'DUMMY',\n 'MaxKeys' => 1000\n ],\n [\n 'IsTruncated' => false,\n 'Delimiter' => '/',\n 'Name' => 'bucket',\n 'NextMarker' => 'DUMMY',\n 'MaxKeys' => 1000,\n 'CommonPrefixes' => [['Prefix' => 'g/']]\n ]\n ];\n\n $this->addMockResults($this->client, array_merge($results, $results));\n\n $this->client->getEmitter()->on('prepared', function (PreparedEvent $e) {\n $c = $e->getCommand();\n $this->assertEquals('bucket', $c['Bucket']);\n $this->assertEquals('/', $c['Delimiter']);\n $this->assertEquals('key/', $c['Prefix']);\n });\n\n $dir = 's3://bucket/key/';\n $r = opendir($dir);\n $this->assertInternalType('resource', $r);\n\n $files = [];\n while (($file = readdir($r)) !== false) {\n $files[] = $file;\n }\n\n // This is the order that the mock responses should provide\n $expected = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];\n $this->assertEquals($expected, $files);\n\n closedir($r);\n }\n\n public function testCanSetDelimiterStreamContext()\n {\n $this->client->getEmitter()->on('prepared', function (PreparedEvent $e) {\n $c = $e->getCommand();\n $this->assertEquals('bucket', $c['Bucket']);\n $this->assertEquals('', $c['Delimiter']);\n $this->assertEquals('', $c['Prefix']);\n });\n\n $this->addMockResults($this->client, [\n [\n 'IsTruncated' => false,\n 'Marker' => '',\n 'Contents' => [],\n 'Name' => 'bucket',\n 'Prefix' => '',\n 'MaxKeys' => 1000,\n 'CommonPrefixes' => [['Prefix' => 'foo']]\n ]\n ]);\n\n $context = stream_context_create(['s3' => ['delimiter' => '']]);\n $r = opendir('s3://bucket', $context);\n closedir($r);\n }\n\n public function testCanClearStatCache()\n {\n StreamWrapper::clearCache();\n $this->assertEmpty($this->readAttribute('Aws\\S3\\StreamWrapper', 'statCache'));\n $results = [\n [\n 'IsTruncated' => false,\n 'Delimiter' => '/',\n 'Name' => 'bucket',\n 'Prefix' => '',\n 'MaxKeys' => 1000,\n 'Contents' => [['Key' => 'a'], ['Key' => 'b']],\n ]\n ];\n\n $this->addMockResults($this->client, $results);\n $dir = 's3://bucket/key/';\n $r = opendir($dir);\n while (($file = readdir($r)) !== false);\n $this->assertNotEmpty($this->readAttribute('Aws\\S3\\StreamWrapper', 'statCache'));\n closedir($r);\n }\n}\n" }, { "alpha_fraction": 0.5380645394325256, "alphanum_fraction": 0.5400000214576721, "avg_line_length": 28.245283126831055, "blob_id": "8b293a815c2418476e9567c0279c8c0782a3d3d3", "content_id": "ad797449953946b015a3c598cec1bf069d2a9c4c", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1550, "license_type": "permissive", "max_line_length": 80, "num_lines": 53, "path": "/tests/Glacier/GlacierClientTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Glacier;\n\nuse Aws\\Glacier\\GlacierClient;\nuse Aws\\Result;\nuse GuzzleHttp\\Command\\Event\\PreparedEvent;\n\n/**\n * @covers Aws\\Glacier\\GlacierClient\n */\nclass GlacierClientTest extends \\PHPUnit_Framework_TestCase\n{\n public function testHasNecessaryDefaults()\n {\n $client = new GlacierClient([\n 'service' => 'glacier',\n 'region' => 'us-west-2',\n 'version' => 'latest'\n ]);\n\n $command = $client->getCommand('ListVaults');\n $this->assertEquals('-', $command['accountId']);\n\n $command->getEmitter()->on('prepared', function (PreparedEvent $event) {\n $event->setResult(new Result([]));\n $this->assertEquals(\n $event->createClient()->getApi()->getMetadata('apiVersion'),\n $event->getRequest()->getHeader('x-amz-glacier-version')\n );\n });\n }\n\n public function testCreatesClientWithSubscribers()\n {\n $client = new GlacierClient([\n 'service' => 'glacier',\n 'region' => 'us-west-2',\n 'version' => 'latest'\n ]);\n\n $found = [];\n foreach ($client->getEmitter()->listeners() as $value) {\n foreach ($value as $val) {\n $found[] = is_array($val)\n ? get_class($val[0])\n : get_class($val);\n }\n }\n\n $this->assertContains('Aws\\Subscriber\\SourceFile', $found);\n $this->assertContains('Aws\\Glacier\\ApplyChecksumsSubscriber', $found);\n }\n}\n" }, { "alpha_fraction": 0.543216347694397, "alphanum_fraction": 0.5454862713813782, "avg_line_length": 32.49122619628906, "blob_id": "9f942725481f2a8d7fa3227a357463bc4d4fe6c3", "content_id": "be9d22145e5149bc4d886cc32a2059e63b588244", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 5727, "license_type": "permissive", "max_line_length": 117, "num_lines": 171, "path": "/src/CloudFront/UrlSigner.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\CloudFront;\n\nuse GuzzleHttp\\Query;\nuse GuzzleHttp\\Url;\n\n/**\n * Creates signed URLs for Amazon CloudFront resources.\n */\nclass UrlSigner\n{\n private $keyPairId;\n private $pk;\n\n /**\n * @param $keyPairId string ID of the key pair\n * @param $privateKey string Path to the private key used for signing\n *\n * @throws \\RuntimeException if the openssl extension is missing\n * @throws \\InvalidArgumentException if the private key cannot be found.\n */\n public function __construct($keyPairId, $privateKey)\n {\n if (!extension_loaded('openssl')) {\n //@codeCoverageIgnoreStart\n throw new \\RuntimeException('The openssl extension is required to '\n . 'sign CloudFront urls.');\n //@codeCoverageIgnoreEnd\n }\n\n $this->keyPairId = $keyPairId;\n\n if (!file_exists($privateKey)) {\n throw new \\InvalidArgumentException(\"PK file not found: $privateKey\");\n }\n\n $this->pk = file_get_contents($privateKey);\n }\n\n /**\n * Create a signed Amazon CloudFront URL.\n *\n * Keep in mind that URLs meant for use in media/flash players may have\n * different requirements for URL formats (e.g. some require that the\n * extension be removed, some require the file name to be prefixed\n * - mp4:<path>, some require you to add \"/cfx/st\" into your URL).\n *\n * @param string $url URL to sign (can include query\n * string string and wildcards\n * @param string|integer|null $expires UTC Unix timestamp used when signing\n * with a canned policy. Not required\n * when passing a custom $policy.\n * @param string $policy JSON policy. Use this option when\n * creating a signed URL for a custom\n * policy.\n *\n * @return string The file URL with authentication parameters\n * @throws \\InvalidArgumentException if the URL provided is invalid\n * @link http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/WorkingWithStreamingDistributions.html\n */\n public function getUrlSigner($url, $expires = null, $policy = null)\n {\n // Determine the scheme of the url\n $urlSections = explode('://', $url);\n\n if (count($urlSections) < 2) {\n throw new \\InvalidArgumentException(\"Invalid URL: {$url}\");\n }\n\n // Get the real scheme by removing wildcards from the scheme\n $scheme = str_replace('*', '', $urlSections[0]);\n\n if ($policy) {\n $isCustom = true;\n } else {\n $isCustom = false;\n $policy = $this->createCannedPolicy($scheme, $url, $expires);\n }\n\n $policy = str_replace(' ', '', $policy);\n $url = Url::fromString($scheme . '://' . $urlSections[1]);\n $this->prepareQuery($isCustom, $policy, $url->getQuery(), $expires);\n\n return $scheme === 'rtmp'\n ? $this->createRtmpUrl($url)\n : (string) $url;\n }\n\n private function prepareQuery($isCustom, $policy, Query $query, $expires)\n {\n if ($isCustom) {\n // Custom policies require the encoded policy be specified in query\n $query['Policy'] = strtr(base64_encode($policy), '+=/', '-_~');\n } else {\n // Canned policies require \"Expires\" in the URL.\n $query['Expires'] = $expires;\n }\n\n $query['Signature'] = $this->signPolicy($policy);\n $query['Key-Pair-Id'] = $this->keyPairId;\n }\n\n private function rsaSha1Sign($policy)\n {\n $signature = '';\n openssl_sign($policy, $signature, $this->pk);\n\n return $signature;\n }\n\n private function createCannedPolicy($scheme, $url, $expires)\n {\n if (!$expires) {\n throw new \\InvalidArgumentException('An expires option is '\n . 'required when using a canned policy');\n }\n\n return sprintf(\n '{\"Statement\":[{\"Resource\":\"%s\",\"Condition\":{\"DateLessThan\":{\"AWS:EpochTime\":%d}}}]}',\n $this->createResource($scheme, $url),\n $expires\n );\n }\n\n private function signPolicy($policy)\n {\n // Sign the policy using the CloudFront private key\n $signedPolicy = $this->rsaSha1Sign($policy);\n // Remove whitespace, base64 encode the policy, and replace special\n // characters.\n $signedPolicy = strtr(base64_encode($signedPolicy), '+=/', '-_~');\n\n return $signedPolicy;\n }\n\n private function createResource($scheme, $url)\n {\n switch ($scheme) {\n case 'http':\n case 'https':\n return $url;\n case 'rtmp':\n $parts = parse_url($url);\n $pathParts = pathinfo($parts['path']);\n $resource = ltrim(\n $pathParts['dirname'] . '/' . $pathParts['basename'],\n '/'\n );\n\n // Add a query string if present.\n if (isset($parts['query'])) {\n $resource .= \"?{$parts['query']}\";\n }\n\n return $resource;\n }\n\n throw new \\InvalidArgumentException(\"Invalid URI scheme: {$scheme}. \"\n . \"Scheme must be one of: http, https, or rtmp\");\n }\n\n private function createRtmpUrl(Url $url)\n {\n // Use a relative URL when creating Flash player URLs\n $url->getQuery()->setEncodingType(false);\n $url->setScheme(null);\n $url->setHost(null);\n\n return substr($url, 1);\n }\n}\n" }, { "alpha_fraction": 0.5687150955200195, "alphanum_fraction": 0.5687150955200195, "avg_line_length": 18.45652198791504, "blob_id": "ce11e9fa76b2963e8aba68e925b6c5abc82a3497", "content_id": "7466721a3e9095a69ea67696b5fbc20a67b5e2e4", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 895, "license_type": "permissive", "max_line_length": 79, "num_lines": 46, "path": "/src/Credentials/NullCredentials.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Credentials;\n\n/**\n * A blank set of credentials. AWS clients must be provided credentials, but\n * there are some types of requests that do not need authentication. This class\n * can be used to pivot on that scenario, and also serve as a mock credentials\n * object when testing.\n */\nclass NullCredentials implements CredentialsInterface\n{\n public function getAccessKeyId()\n {\n return '';\n }\n\n public function getSecretKey()\n {\n return '';\n }\n\n public function getSecurityToken()\n {\n return null;\n }\n\n public function getExpiration()\n {\n return null;\n }\n\n public function isExpired()\n {\n return false;\n }\n\n public function toArray()\n {\n return [\n 'key' => '',\n 'secret' => '',\n 'token' => null,\n 'expires' => null\n ];\n }\n}\n" }, { "alpha_fraction": 0.5600902438163757, "alphanum_fraction": 0.5793683528900146, "avg_line_length": 30.256410598754883, "blob_id": "705937d536c46d86803230c059d0e76339c8d022", "content_id": "a40b2f3fb421e4ce37996ef1a04e9a3b1bf978ea", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4876, "license_type": "permissive", "max_line_length": 83, "num_lines": 156, "path": "/tests/Api/ApiProviderTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Api;\n\nuse Aws\\Api\\ApiProvider;\nuse Aws\\Exception\\UnresolvedApiException;\n\n/**\n * @covers Aws\\Api\\ApiProvider\n */\nclass ApiProviderTest extends \\PHPUnit_Framework_TestCase\n{\n /**\n * @return ApiProvider;\n */\n private function getTestApiProvider($useManifest = true)\n {\n $dir = __DIR__ . '/api_provider_fixtures';\n $manifest = include $dir . '/api-version-manifest.php';\n\n return $useManifest\n ? ApiProvider::manifest($dir, $manifest)\n : ApiProvider::filesystem($dir);\n }\n\n public function testCanResolveProvider()\n {\n $p = function ($a, $b, $c) {return [];};\n $this->assertEquals([], ApiProvider::resolve($p, 't', 's', 'v'));\n\n $p = function ($a, $b, $c) {return null;};\n $this->setExpectedException(UnresolvedApiException::class);\n ApiProvider::resolve($p, 't', 's', 'v');\n }\n\n public function testCanGetServiceVersions()\n {\n $mp = $this->getTestApiProvider();\n $this->assertEquals(\n ['2012-08-10', '2010-02-04'],\n $mp->getVersions('dynamodb')\n );\n $this->assertEquals([], $mp->getVersions('foo'));\n\n $fp = $this->getTestApiProvider(false);\n $this->assertEquals(\n ['2012-08-10', '2010-02-04'],\n $fp->getVersions('dynamodb')\n );\n }\n\n public function testCanGetDefaultProvider()\n {\n $p = ApiProvider::defaultProvider();\n $this->assertArrayHasKey('s3', $this->readAttribute($p, 'versions'));\n }\n\n public function testManifestProviderReturnsNullForMissingService()\n {\n $p = $this->getTestApiProvider();\n $this->assertNull($p('api', 'foo', '2015-02-02'));\n }\n\n public function testManifestProviderCanLoadData()\n {\n $p = $this->getTestApiProvider();\n $data = $p('api', 'dynamodb', 'latest');\n $this->assertInternalType('array', $data);\n $this->assertArrayHasKey('foo', $data);\n }\n\n /**\n * @expectedException \\InvalidArgumentException\n */\n public function testFilesystemProviderEnsuresDirectoryIsValid()\n {\n ApiProvider::filesystem('/path/to/invalid/dir');\n }\n\n public function testEnsuresValidJson()\n {\n $path = sys_get_temp_dir() . '/invalid-2010-12-05.api.json';\n file_put_contents($path, 'foo, bar');\n $p = ApiProvider::filesystem(sys_get_temp_dir());\n try {\n $p('api', 'invalid', '2010-12-05');\n $this->fail('Did not throw');\n } catch (\\Exception $e) {\n $this->assertInstanceOf('InvalidArgumentException', $e);\n } finally {\n unlink($path);\n }\n }\n\n public function testNullOnMissingFile()\n {\n $p = $this->getTestApiProvider();\n $this->assertNull($p('api', 'nofile', 'latest'));\n }\n\n public function testReturnsLatestServiceData()\n {\n $p = ApiProvider::filesystem(__DIR__ . '/api_provider_fixtures');\n $this->assertEquals(['foo' => 'bar'], $p('api', 'dynamodb', 'latest'));\n }\n\n public function testCanLoadPhpFile()\n {\n $p = ApiProvider::filesystem(__DIR__ . '/api_provider_fixtures');\n $this->assertEquals(['foo' => 'bar'], $p('api', 'dynamodb', '2010-02-04'));\n }\n\n public function testReturnsNullWhenNoLatestVersionIsAvailable()\n {\n $p = ApiProvider::filesystem(__DIR__ . '/api_provider_fixtures');\n $this->assertnull($p('api', 'dodo', 'latest'));\n }\n\n public function testReturnsPaginatorConfigsForLatestCompatibleVersion()\n {\n $p = $this->getTestApiProvider();\n $result = $p('paginator', 'dynamodb', 'latest');\n $this->assertEquals(['abc' => '123'], $result);\n $result = $p('paginator', 'dynamodb', '2011-12-05');\n $this->assertEquals(['abc' => '123'], $result);\n }\n\n public function testReturnsWaiterConfigsForLatestCompatibleVersion()\n {\n $p = $this->getTestApiProvider();\n $result = $p('waiter', 'dynamodb', 'latest');\n $this->assertEquals(['abc' => '456'], $result);\n $result = $p('waiter', 'dynamodb', '2011-12-05');\n $this->assertEquals(['abc' => '456'], $result);\n }\n\n public function testThrowsOnBadType()\n {\n $this->setExpectedException(UnresolvedApiException::class);\n $p = $this->getTestApiProvider();\n ApiProvider::resolve($p, 'foo', 's3', 'latest');\n }\n\n public function testThrowsOnBadService()\n {\n $this->setExpectedException(UnresolvedApiException::class);\n $p = $this->getTestApiProvider();\n ApiProvider::resolve($p, 'api', '', 'latest');\n }\n\n public function testThrowsOnBadVersion()\n {\n $this->setExpectedException(UnresolvedApiException::class);\n $p = $this->getTestApiProvider();\n ApiProvider::resolve($p, 'api', 'dynamodb', 'derp');\n }\n}\n" }, { "alpha_fraction": 0.5299999713897705, "alphanum_fraction": 0.5299999713897705, "avg_line_length": 23.489795684814453, "blob_id": "274ef9afe12af26144604c65adc7f1bf4d00e617", "content_id": "e8e8273aeaf776f33b0dce32f3cbf7b73d1d009b", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1200, "license_type": "permissive", "max_line_length": 59, "num_lines": 49, "path": "/src/data/opsworks-2013-02-18.paginators.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php return [\n 'pagination' => [\n 'DescribeApps' => [\n 'result_key' => 'Apps',\n ],\n 'DescribeCommands' => [\n 'result_key' => 'Commands',\n ],\n 'DescribeDeployments' => [\n 'result_key' => 'Deployments',\n ],\n 'DescribeElasticIps' => [\n 'result_key' => 'ElasticIps',\n ],\n 'DescribeElasticLoadBalancers' => [\n 'result_key' => 'ElasticLoadBalancers',\n ],\n 'DescribeInstances' => [\n 'result_key' => 'Instances',\n ],\n 'DescribeLayers' => [\n 'result_key' => 'Layers',\n ],\n 'DescribeLoadBasedAutoScaling' => [\n 'result_key' => 'LoadBasedAutoScalingConfigurations',\n ],\n 'DescribePermissions' => [\n 'result_key' => 'Permissions',\n ],\n 'DescribeRaidArrays' => [\n 'result_key' => 'RaidArrays',\n ],\n 'DescribeServiceErrors' => [\n 'result_key' => 'ServiceErrors',\n ],\n 'DescribeStacks' => [\n 'result_key' => 'Stacks',\n ],\n 'DescribeTimeBasedAutoScaling' => [\n 'result_key' => 'TimeBasedAutoScalingConfigurations',\n ],\n 'DescribeUserProfiles' => [\n 'result_key' => 'UserProfiles',\n ],\n 'DescribeVolumes' => [\n 'result_key' => 'Volumes',\n ],\n ],\n];\n" }, { "alpha_fraction": 0.6303520202636719, "alphanum_fraction": 0.6336821913719177, "avg_line_length": 31.84375, "blob_id": "f42935ca19d5c6385323378db90b215e7c5c344a", "content_id": "be93384d491498231f5a4a8f9e2373bebb0a0306", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2102, "license_type": "permissive", "max_line_length": 76, "num_lines": 64, "path": "/src/Ec2/CopySnapshotSubscriber.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Ec2;\n\nuse Aws\\AwsClientInterface;\nuse Aws\\Signature\\SignatureV4;\nuse Aws\\Endpoint\\EndpointProvider;\nuse GuzzleHttp\\Command\\CommandInterface;\nuse GuzzleHttp\\Command\\Event\\InitEvent;\nuse GuzzleHttp\\Event\\RequestEvents;\nuse GuzzleHttp\\Event\\SubscriberInterface;\nuse GuzzleHttp\\Url;\n\n/**\n * @internal Adds computed values to the CopySnapshot operation.\n */\nclass CopySnapshotSubscriber implements SubscriberInterface\n{\n private $endpointProvider;\n\n public function __construct(callable $endpointProvider)\n {\n $this->endpointProvider = $endpointProvider;\n }\n\n public function getEvents()\n {\n return ['init' => ['onInit', RequestEvents::LATE]];\n }\n\n public function onInit(InitEvent $event)\n {\n $cmd = $event->getCommand();\n if ($cmd->getName() == 'CopySnapshot') {\n /** @var AwsClientInterface $client */\n $client = $event->getClient();\n $cmd['PresignedUrl'] = $this->createPresignedUrl($client, $cmd);\n $cmd['DestinationRegion'] = $client->getRegion();\n }\n }\n\n private function createPresignedUrl(\n AwsClientInterface $client,\n CommandInterface $cmd\n ) {\n $newCmd = $client->getCommand('CopySnapshot', $cmd->toArray());\n $newCmd->getEmitter()->detach($this);\n // Serialize a request for the CopySnapshot operation.\n $request = $client->initTransaction($newCmd)->request;\n // Create the new endpoint for the target endpoint.\n $endpoint = EndpointProvider::resolve($this->endpointProvider, [\n 'region' => $cmd['SourceRegion'],\n 'service' => 'ec2'\n ])['endpoint'];\n // Set the request to hit the target endpoint.\n $request->setHost(Url::fromString($endpoint)->getHost());\n // Create a presigned URL for our generated request.\n $signer = new SignatureV4('ec2', $cmd['SourceRegion']);\n return $signer->createPresignedUrl(\n SignatureV4::convertPostToGet($request),\n $client->getCredentials(),\n '+1 hour'\n );\n }\n}\n" }, { "alpha_fraction": 0.5986642241477966, "alphanum_fraction": 0.5986642241477966, "avg_line_length": 20.959999084472656, "blob_id": "de9ed562692a1270951b933bee775cd8597eb757", "content_id": "6f713b1b39e4908ccb29d92cb7e50c666034bbd8", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1647, "license_type": "permissive", "max_line_length": 76, "num_lines": 75, "path": "/src/Credentials/RefreshableCredentials.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Credentials;\n\nuse Aws\\Exception\\CredentialsException;\n\n/**\n * Refreshes credentials using a callback function when they are expired.\n */\nclass RefreshableCredentials implements CredentialsInterface\n{\n /** @var CredentialsInterface Wrapped credentials object */\n private $credentials;\n\n /** @var callable */\n private $provider;\n\n /**\n * @param callable $provider A credentials provider function.\n */\n public function __construct(callable $provider)\n {\n $this->provider = $provider;\n $this->refresh();\n }\n\n public function getAccessKeyId()\n {\n return $this->getCreds()->getAccessKeyId();\n }\n\n public function getSecretKey()\n {\n return $this->getCreds()->getSecretKey();\n }\n\n public function getSecurityToken()\n {\n return $this->getCreds()->getSecurityToken();\n }\n\n public function toArray()\n {\n return $this->getCreds()->toArray();\n }\n\n public function getExpiration()\n {\n return $this->credentials->getExpiration();\n }\n\n public function isExpired()\n {\n return $this->credentials->isExpired();\n }\n\n private function getCreds()\n {\n if ($this->credentials->isExpired()) {\n $this->refresh();\n }\n\n return $this->credentials;\n }\n\n private function refresh()\n {\n $this->credentials = null;\n $fn = $this->provider;\n $creds = CredentialProvider::resolve($fn);\n if ($creds->isExpired()) {\n throw new CredentialsException('Could not refresh credentials');\n }\n $this->credentials = $creds;\n }\n}\n" }, { "alpha_fraction": 0.47060340642929077, "alphanum_fraction": 0.4770500361919403, "avg_line_length": 27.101449966430664, "blob_id": "d56b2fb224343d02da2c683d2a16b00c8f7bf4f7", "content_id": "88ef8d56abe58a52dbcda98655d43b208692009a", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3878, "license_type": "permissive", "max_line_length": 78, "num_lines": 138, "path": "/tests/S3/BatchDeleteTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\S3;\n\nuse Aws\\S3\\S3Client;\nuse Aws\\S3\\BatchDelete;\nuse Aws\\S3\\Exception\\DeleteMultipleObjectsException;\nuse Aws\\Test\\UsesServiceTrait;\nuse GuzzleHttp\\Command\\Event\\PreparedEvent;\n\n/**\n * @covers Aws\\S3\\BatchDelete\n */\nclass BatchDeleteTest extends \\PHPUnit_Framework_TestCase\n{\n use UsesServiceTrait;\n\n /** @var S3Client */\n protected $client;\n\n public function setUp()\n {\n $this->client = $this->getTestClient('s3', ['region' => 'us-east-1']);\n }\n\n public function testCountsAndReturnsQueue()\n {\n $b = new BatchDelete($this->client, 'bucket');\n $this->assertCount(0, $b);\n $b->addObject('foo');\n $this->assertCount(1, $b);\n $this->assertEquals([['Key' => 'foo']], $b->getQueue());\n }\n\n public function testSendsBatchRequestsPerThousand()\n {\n $b = new BatchDelete($this->client, 'bucket', ['batch_size' => 10]);\n\n $batches = $deleted = [];\n foreach ([0, 1] as $batch) {\n for ($i = 0; $i < 10; $i++) {\n $name = 'o-' . (($batch * 10) + $i);\n $b->addObject($name);\n $deleted[] = ['Key' => $name];\n $batches[$batch][] = ['Key' => $name];\n }\n }\n\n $called = 0;\n $this->client->getEmitter()->on(\n 'prepared',\n function (PreparedEvent $e) use (&$called, $batches) {\n $this->assertSame(\n $batches[$called],\n $e->getCommand()['Delete']['Objects']\n );\n $called++;\n }\n );\n\n $this->addMockResults($this->client, [\n ['Deleted' => $batches[0]],\n ['Deleted' => $batches[1]],\n ]);\n\n $this->assertEquals($deleted, $b->delete());\n }\n\n public function testDeletesWithVersionId()\n {\n $b = new BatchDelete($this->client, 'bucket');\n $b->addObject('foo', 'bar');\n $deleted = [['Key' => 'foo', 'VersionId' => 'bar']];\n\n $this->client->getEmitter()->on(\n 'prepared',\n function (PreparedEvent $e) {\n $this->assertEquals(\n [['Key' => 'foo', 'VersionId' => 'bar']],\n $e->getCommand()['Delete']['Objects']\n );\n }\n );\n\n $this->addMockResults($this->client, [\n ['Deleted' => $deleted]\n ]);\n\n $this->assertEquals($deleted, $b->delete());\n }\n\n public function testValidatesErrors()\n {\n $b = new BatchDelete($this->client, 'bucket');\n $b->addObject('foo');\n $b->addObject('bar');\n $deleted = [['Key' => 'foo']];\n $errors = [['Key' => 'bar', 'Code' => 'code', 'Message' => 'msg']];\n\n $this->addMockResults($this->client, [\n ['Deleted' => $deleted, 'Errors' => $errors]\n ]);\n\n try {\n $b->delete();\n $this->fail('Did not throw');\n } catch (DeleteMultipleObjectsException $e) {\n $this->assertSame($deleted, $e->getDeleted());\n $this->assertSame($errors, $e->getErrors());\n }\n }\n\n public function testAddsMfa()\n {\n $b = new BatchDelete($this->client, 'bucket', ['mfa' => 'mfa!']);\n $b->addObject('foo', 'bar');\n\n $this->client->getEmitter()->on(\n 'prepared',\n function (PreparedEvent $e) {\n $this->assertEquals(\n 'mfa!',\n $e->getRequest()->getHeader('x-amz-mfa')\n );\n }, -1\n );\n\n $this->addMockResults($this->client, [['Deleted' => []]]);\n $b->delete();\n }\n\n /**\n * @expectedException \\InvalidArgumentException\n */\n public function testEnsuresBatchSizeIsGtZero()\n {\n new BatchDelete($this->client, 'bucket', ['batch_size' => 0]);\n }\n}\n" }, { "alpha_fraction": 0.6907991766929626, "alphanum_fraction": 0.69619220495224, "avg_line_length": 40.067115783691406, "blob_id": "6d676deea25100212c59fe558e875b8b3989921c", "content_id": "75cb4304153dea9ec592770f29f2dbcba9a24f25", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 6121, "license_type": "permissive", "max_line_length": 159, "num_lines": 149, "path": "/docs/faq.rst", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "================================\nFrequently Asked Questions (FAQ)\n================================\n\n\nWhat methods are available on a client?\n---------------------------------------\n\nThe AWS SDK for PHP utilizes service descriptions and dynamic\n`magic __call() methods <http://www.php.net/manual/en/language.oop5.overloading.php#object.call>`_ to execute API\noperations. You can find a full list of methods available for a web service\nclient in the `API documentation <http://docs.aws.amazon.com/aws-sdk-php/v3/api/index.html>`_\nof the client.\n\n\nWhat do I do about a cURL SSL certificate error?\n------------------------------------------------\n\nThis issue can occur when using an out of date CA bundle with cURL and SSL. You\ncan get around this issue by updating the CA bundle on your server or\ndownloading a more up to date CA bundle from the\n`cURL website directly <http://curl.haxx.se/ca/cacert.pem>`_.\n\nThe SDK will by default use the CA bundle that is configured when PHP is\ncompiled. You can change the default CA bundle used by PHP by modifying the\n``openssl.cafile`` PHP ini configuration setting to be set to the path a CA\nfile on disk. You can find out more about how cURL bundles the CA bundle here:\nhttp://curl.haxx.se/docs/caextract.html\n\n\nHow do I disable SSL?\n---------------------\n\n.. warning::\n\n Because SSL requires all data to be encrypted and requires more TCP packets\n to complete a connection handshake than just TCP, disabling SSL may provide\n a small performance improvement. However, with SSL disabled, all data is\n sent over the wire unencrypted. Before disabling SSL, you must carefully\n consider the security implications and the potential for eavesdropping over\n the network.\n\nYou can disable SSL by setting the ``scheme`` parameter in a client factory\nmethod to 'http'.\n\n.. code-block:: php\n\n $client = Aws\\DynamoDb\\DynamoDbClient::factory(array(\n 'region' => 'us-west-2',\n 'scheme' => 'http'\n ));\n\n\nWhy can't I upload or download files greater than 2GB?\n------------------------------------------------------\n\nBecause PHP's integer type is signed and many platforms use 32-bit integers, the\nAWS SDK for PHP does not correctly handle files larger than 2GB on a 32-bit\nstack (where \"stack\" includes CPU, OS, web server, and PHP binary). This is a\n`well-known PHP issue <http://www.google.com/search?q=php+2gb+32-bit>`_. In the\ncase of Microsoft® Windows®, there are no official builds of PHP that support\n64-bit integers.\n\nThe recommended solution is to use a `64-bit Linux stack <http://aws.amazon.com/amazon-linux-ami/>`_,\nsuch as the 64-bit Amazon Linux AMI with the latest version of PHP installed.\n\nFor more information, please see: `PHP filesize :Return values <http://docs.php.net/manual/en/function.filesize.php#refsect1-function.filesize-returnvalues>`_.\n\n\nHow can I see what data is sent over the wire?\n----------------------------------------------\n\nYou can get debug information, including the data sent over the wire, using the\n``debug`` option in a client constructor. When this option is set to ``true``\nall of the mutations of the command being executed, the request being sent, the\nresponse being recieved, and the result be processed will be emitted to STDOUT.\nThis includes the data that is sent and received over the wire.\n\n.. code-block:: php\n\n $s3Client = S3Client::factory(['debug' => true]);\n\n\nHow can I set arbitrary headers on a request?\n---------------------------------------------\n\nYou can add any arbitrary headers to a service operation by listening to the\ncommand's ``prepared`` event and mutating the request object associated with\nthe event. The following example shows how to add an ``X-Foo-Baz`` header to an\nAmazon S3 PutObject operation.\n\n.. code-block:: php\n\n use GuzzleHttp\\Command\\Event\\PreparedEvent;\n\n $s3Client = S3Client::factory();\n\n $command = $s3Client->getCommand('PutObject', [\n 'Key' => 'test',\n 'Bucket' => 'mybucket'\n ));\n\n $command->getEmitter()->on('prepared', function (PreparedEvent $e) {\n $e->getRequest()->setHeader('X-Foo-Baz', 'Bar');\n });\n\n\n\nWhy am I seeing a \"Cannot redeclare class\" error?\n-------------------------------------------------\n\nWe have observed this error a few times when using the ``aws.phar`` from the\nCLI with APC enabled. This is due to some kind of issue with phars and APC.\nLuckily there are a few ways to get around this. Please choose the one that\nmakes the most sense for your environment and application.\n\n1. **Don't use APC** - PHP 5.5, for example, comes with Zend OpCache built in.\n This problem has not been observed with Zend OpCache.\n2. **Disable APC for CLI** - Change the ``apc.enable_cli`` INI setting to\n ``Off``.\n3. **Tell APC not to cache phars** - Change the ``apc.filters`` INI setting to\n include ``\"^phar://\"``.\n4. **Don't use the phar** - When all else fails, you should install the SDK\n through Composer (recommended) or by using the zip file.\n\n\nWhat is an InstanceProfileCredentialsException?\n-----------------------------------------------\n\nIf you are seeing an ``Aws\\Common\\Exception\\InstanceProfileCredentialsException``\nwhile using the SDK, this means that the SDK was not provided with any\ncredentials.\n\nIf you instantiate a client *without* credentials, on the first time that you\nperform a service operation, the SDK will attempt to find credentials. It first\nchecks in some specific environment variables, then it looks for instance\nprofile credentials, which are only available on configured Amazon EC2\ninstances. If absolutely no credentials are provided or found, an\n``Aws\\Common\\Exception\\InstanceProfileCredentialsException`` is thrown.\n\nIf you are seeing this error and you are intending to use instance profile\ncredentials, then you need to make sure that the Amazon EC2 instance that the\nSDK is running on is configured with an appropriate IAM role.\n\nIf you are seeing this error and you are **not** intending to use instance\nprofile credentials, then you need to make sure that you are properly providing\ncredentials to the SDK.\n\nFor more information, see :doc:`credentials`.\n" }, { "alpha_fraction": 0.5270327925682068, "alphanum_fraction": 0.5300127863883972, "avg_line_length": 34.726234436035156, "blob_id": "97b32b8e462aa30754cf950bc109523a2f67116f", "content_id": "32ed5b3917715f551b3e3b4218554985e80e4d82", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 9396, "license_type": "permissive", "max_line_length": 86, "num_lines": 263, "path": "/src/DynamoDb/WriteRequestBatch.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\DynamoDb;\n\nuse GuzzleHttp\\Command\\CommandInterface;\nuse GuzzleHttp\\Command\\Event\\ProcessEvent;\n\n/**\n * The WriteRequestBatch is an object that is capable of efficiently sending\n * DynamoDB BatchWriteItem requests from queued up put and delete item requests.\n * requests. The batch attempts to send the requests with the fewest requests\n * to DynamoDB as possible and also re-queues any unprocessed items to ensure\n * that all items are sent.\n */\nclass WriteRequestBatch\n{\n /** @var DynamoDbClient DynamoDB client used to perform write operations. */\n private $client;\n\n /** @var array Configuration options for the batch. */\n private $config;\n\n /** @var array Queue of pending put/delete requests in the batch. */\n private $queue;\n\n /**\n * Creates a WriteRequestBatch object that is capable of efficiently sending\n * DynamoDB BatchWriteItem requests from queued up Put and Delete requests.\n *\n * @param DynamoDbClient $client DynamoDB client used to send batches.\n * @param array $config Batch configuration options.\n * - table: DynamoDB table used by the batch, this can be overridden for\n * each individual put() or delete() call.\n * - batch_size: The size of each batch (default: 25). The batch size\n * must be between 2 and 25. If you are sending batches of large\n * items, you may consider lowering the batch size, otherwise, you\n * should use 25.\n * - pool_size: This number dictates how many BatchWriteItem requests\n * you would like to do in parallel. For example, if the \"batch_size\"\n * is 25, and \"pool_size\" is 3, then you would send 3 BatchWriteItem\n * requests at a time, each with 25 items. Please keep your\n * throughput in mind when choosing the \"pool_size\" option.\n * - autoflush: This option allows the batch to automatically flush once\n * there are enough items (i.e., \"batch_size\" * \"pool_size\") in the\n * queue. This defaults to true, so you must set this to false to\n * stop autoflush.\n * - error: Set this to a callback to handle errors from the commands\n * executed by the batch, otherwise errors are ignored. The callback\n * should accept a \\GuzzleHttp\\Command\\Event\\ProcessEvent as its\n * argument.\n * - flush: Set this to a callback to perform an action after the batch\n * has been autoflushed. The callback will not be triggered on manual\n * flushes.\n *\n * @throws \\DomainException if the batch size is not between 2 and 25.\n */\n public function __construct(DynamoDbClient $client, array $config = [])\n {\n // Apply defaults\n $config += [\n 'table' => null,\n 'batch_size' => 25,\n 'pool_size' => 1,\n 'autoflush' => true,\n 'error' => null,\n 'flush' => null\n ];\n\n // Ensure the batch size is valid\n if ($config['batch_size'] > 25 || $config['batch_size'] < 2) {\n throw new \\DomainException('batch_size must be between 2 and 25.');\n }\n\n // If autoflush is enabled, set the threshold\n if ($config['autoflush']) {\n $config['threshold'] = $config['batch_size'] * $config['pool_size'];\n }\n\n $this->client = $client;\n $this->config = $config;\n $this->queue = [];\n }\n\n /**\n * Adds a put item request to the batch.\n *\n * @param array $item Data for an item to put. Format:\n * [\n * 'attribute1' => ['type' => 'value'],\n * 'attribute2' => ['type' => 'value'],\n * ...\n * ]\n * @param string|null $table The name of the table. This must be specified\n * unless the \"table\" option was provided in the\n * config of the WriteRequestBatch.\n *\n * @return $this\n */\n public function put(array $item, $table = null)\n {\n $this->queue[] = [\n 'table' => $this->determineTable($table),\n 'data' => ['PutRequest' => ['Item' => $item]],\n ];\n\n $this->autoFlush();\n\n return $this;\n }\n\n /**\n * Adds a delete item request to the batch.\n *\n * @param array $key Key of an item to delete. Format:\n * [\n * 'key1' => ['type' => 'value'],\n * ...\n * ]\n * @param string|null $table The name of the table. This must be specified\n * unless the \"table\" option was provided in the\n * config of the WriteRequestBatch.\n *\n * @return $this\n */\n public function delete(array $key, $table = null)\n {\n $this->queue[] = [\n 'table' => $this->determineTable($table),\n 'data' => ['DeleteRequest' => ['Key' => $key]],\n ];\n\n $this->autoFlush();\n\n return $this;\n }\n\n /**\n * Flushes the batch by combining all the queued put and delete requests\n * into BatchWriteItem commands and executing them. Unprocessed items are\n * automatically re-queued.\n *\n * @param bool $untilEmpty If true, flushing will continue until the queue\n * is completely empty. This will make sure that\n * unprocessed items are all eventually sent.\n *\n * @return $this\n */\n public function flush($untilEmpty = true)\n {\n // Send BatchWriteItem requests until the queue is empty\n $keepFlushing = true;\n while ($this->queue && $keepFlushing) {\n $commands = $this->prepareCommands();\n $this->client->executeAll($commands, [\n 'pool_size' => $this->config['pool_size'],\n 'process' => function (ProcessEvent $e) {\n if ($e->getException()) {\n $code = $e->getContext()->getPath('aws_error/code');\n if ($code === 'ProvisionedThroughputExceededException') {\n $this->retryUnprocessed($e->getCommand()['RequestItems']);\n } elseif (is_callable($this->config['error'])) {\n $this->config['error']($e);\n }\n } else {\n // Re-queue any unprocessed items\n $result = $e->getResult();\n if ($result->hasKey('UnprocessedItems')) {\n $this->retryUnprocessed($result['UnprocessedItems']);\n }\n }\n }\n ]);\n $keepFlushing = (bool) $untilEmpty;\n }\n\n return $this;\n }\n\n /**\n * Creates BatchWriteItem commands from the items in the queue.\n *\n * @return CommandInterface[]\n */\n private function prepareCommands()\n {\n // Chunk the queue into batches\n $batches = array_chunk($this->queue, $this->config['batch_size']);\n $this->queue = [];\n\n // Create BatchWriteItem commands for each batch\n $commands = [];\n foreach ($batches as $batch) {\n $requests = [];\n foreach ($batch as $item) {\n if (!isset($requests[$item['table']])) {\n $requests[$item['table']] = [];\n }\n $requests[$item['table']][] = $item['data'];\n }\n $commands[] = $this->client->getCommand(\n 'BatchWriteItem',\n ['RequestItems' => $requests]\n );\n }\n\n return $commands;\n }\n\n /**\n * Re-queues unprocessed results with the correct data.\n *\n * @param array $unprocessed Unprocessed items from a result.\n */\n private function retryUnprocessed(array $unprocessed)\n {\n foreach ($unprocessed as $table => $requests) {\n foreach ($requests as $request) {\n $this->queue[] = [\n 'table' => $table,\n 'data' => isset($request['PutRequest'])\n ? $request['PutRequest']\n : $request['DeleteRequest']\n ];\n }\n }\n }\n\n /**\n * If autoflush is enabled and the threshold is met, flush the batch\n */\n private function autoFlush()\n {\n if ($this->config['autoflush']\n && count($this->queue) >= $this->config['threshold']\n ) {\n // Flush only once. Unprocessed items are handled in a later flush.\n $this->flush(false);\n\n // Call the flush callback if one was provided\n if (is_callable($this->config['flush'])) {\n $this->config['flush']();\n }\n }\n }\n\n /**\n * Determine the table name by looking at what was provided and what the\n * WriteRequestBatch was originally configured with.\n *\n * @param string|null $table The table name.\n *\n * @return string\n * @throws \\RuntimeException if there was no table specified.\n */\n private function determineTable($table)\n {\n $table = $table ?: $this->config['table'];\n if (!$table) {\n throw new \\RuntimeException('There was no table specified.');\n }\n\n return $table;\n }\n}\n" }, { "alpha_fraction": 0.5855855941772461, "alphanum_fraction": 0.5881595611572266, "avg_line_length": 22.545454025268555, "blob_id": "aeb7b5c6665535d05d397b68d1392059332350f3", "content_id": "bfccdc90b2d9f05d3ff568daec6477b74a68ab50", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 777, "license_type": "permissive", "max_line_length": 68, "num_lines": 33, "path": "/src/Route53/CleanIdSubscriber.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Route53;\n\nuse GuzzleHttp\\Command\\Event\\InitEvent;\nuse GuzzleHttp\\Event\\SubscriberInterface;\n\n/**\n * Strips prefixes (if present) from operations that uses an Id or\n * HostedZoneId parameter.\n */\nclass CleanIdSubscriber implements SubscriberInterface\n{\n public function getEvents()\n {\n return ['init' => ['onInit']];\n }\n\n public function onInit(InitEvent $event)\n {\n $c = $event->getCommand();\n\n if ($c->hasParam('Id')) {\n $c['Id'] = $this->cleanId($c['Id']);\n } elseif ($c->hasParam('HostedZoneId')) {\n $c['HostedZoneId'] = $this->cleanId($c['HostedZoneId']);\n }\n }\n\n private function cleanId($id)\n {\n return str_replace(['/hostedzone/', '/change/'], '', $id);\n }\n}\n" }, { "alpha_fraction": 0.37353646755218506, "alphanum_fraction": 0.38637325167655945, "avg_line_length": 22.815229415893555, "blob_id": "a5e821f9f2a66a3bb1fa0bbd6d3dacb0bce6c749", "content_id": "eb8c0544ab72c431e43eacb2d65501471451384c", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 21267, "license_type": "permissive", "max_line_length": 157, "num_lines": 893, "path": "/src/data/lambda-2014-11-11.api.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php return [\n 'metadata' => [\n 'apiVersion' => '2014-11-11',\n 'endpointPrefix' => 'lambda',\n 'serviceFullName' => 'AWS Lambda',\n 'signatureVersion' => 'v4',\n 'protocol' => 'rest-json',\n ],\n 'operations' => [\n 'AddEventSource' => [\n 'name' => 'AddEventSource',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/2014-11-13/event-source-mappings/',\n ],\n 'input' => [\n 'shape' => 'AddEventSourceRequest',\n ],\n 'output' => [\n 'shape' => 'EventSourceConfiguration',\n ],\n 'errors' => [\n [\n 'shape' => 'ServiceException',\n 'error' => [\n 'httpStatusCode' => 500,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidParameterValueException',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'DeleteFunction' => [\n 'name' => 'DeleteFunction',\n 'http' => [\n 'method' => 'DELETE',\n 'requestUri' => '/2014-11-13/functions/{FunctionName}',\n 'responseCode' => 204,\n ],\n 'input' => [\n 'shape' => 'DeleteFunctionRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'ServiceException',\n 'error' => [\n 'httpStatusCode' => 500,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'ResourceNotFoundException',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'GetEventSource' => [\n 'name' => 'GetEventSource',\n 'http' => [\n 'method' => 'GET',\n 'requestUri' => '/2014-11-13/event-source-mappings/{UUID}',\n 'responseCode' => 200,\n ],\n 'input' => [\n 'shape' => 'GetEventSourceRequest',\n ],\n 'output' => [\n 'shape' => 'EventSourceConfiguration',\n ],\n 'errors' => [\n [\n 'shape' => 'ServiceException',\n 'error' => [\n 'httpStatusCode' => 500,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'ResourceNotFoundException',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidParameterValueException',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'GetFunction' => [\n 'name' => 'GetFunction',\n 'http' => [\n 'method' => 'GET',\n 'requestUri' => '/2014-11-13/functions/{FunctionName}',\n 'responseCode' => 200,\n ],\n 'input' => [\n 'shape' => 'GetFunctionRequest',\n ],\n 'output' => [\n 'shape' => 'GetFunctionResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'ServiceException',\n 'error' => [\n 'httpStatusCode' => 500,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'ResourceNotFoundException',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'GetFunctionConfiguration' => [\n 'name' => 'GetFunctionConfiguration',\n 'http' => [\n 'method' => 'GET',\n 'requestUri' => '/2014-11-13/functions/{FunctionName}/configuration',\n 'responseCode' => 200,\n ],\n 'input' => [\n 'shape' => 'GetFunctionConfigurationRequest',\n ],\n 'output' => [\n 'shape' => 'FunctionConfiguration',\n ],\n 'errors' => [\n [\n 'shape' => 'ServiceException',\n 'error' => [\n 'httpStatusCode' => 500,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'ResourceNotFoundException',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'InvokeAsync' => [\n 'name' => 'InvokeAsync',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/2014-11-13/functions/{FunctionName}/invoke-async/',\n 'responseCode' => 202,\n ],\n 'input' => [\n 'shape' => 'InvokeAsyncRequest',\n ],\n 'output' => [\n 'shape' => 'InvokeAsyncResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'ServiceException',\n 'error' => [\n 'httpStatusCode' => 500,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'ResourceNotFoundException',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidRequestContentException',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'ListEventSources' => [\n 'name' => 'ListEventSources',\n 'http' => [\n 'method' => 'GET',\n 'requestUri' => '/2014-11-13/event-source-mappings/',\n 'responseCode' => 200,\n ],\n 'input' => [\n 'shape' => 'ListEventSourcesRequest',\n ],\n 'output' => [\n 'shape' => 'ListEventSourcesResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'ServiceException',\n 'error' => [\n 'httpStatusCode' => 500,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'ResourceNotFoundException',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidParameterValueException',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'ListFunctions' => [\n 'name' => 'ListFunctions',\n 'http' => [\n 'method' => 'GET',\n 'requestUri' => '/2014-11-13/functions/',\n 'responseCode' => 200,\n ],\n 'input' => [\n 'shape' => 'ListFunctionsRequest',\n ],\n 'output' => [\n 'shape' => 'ListFunctionsResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'ServiceException',\n 'error' => [\n 'httpStatusCode' => 500,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'RemoveEventSource' => [\n 'name' => 'RemoveEventSource',\n 'http' => [\n 'method' => 'DELETE',\n 'requestUri' => '/2014-11-13/event-source-mappings/{UUID}',\n 'responseCode' => 204,\n ],\n 'input' => [\n 'shape' => 'RemoveEventSourceRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'ServiceException',\n 'error' => [\n 'httpStatusCode' => 500,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'ResourceNotFoundException',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidParameterValueException',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'UpdateFunctionConfiguration' => [\n 'name' => 'UpdateFunctionConfiguration',\n 'http' => [\n 'method' => 'PUT',\n 'requestUri' => '/2014-11-13/functions/{FunctionName}/configuration',\n 'responseCode' => 200,\n ],\n 'input' => [\n 'shape' => 'UpdateFunctionConfigurationRequest',\n ],\n 'output' => [\n 'shape' => 'FunctionConfiguration',\n ],\n 'errors' => [\n [\n 'shape' => 'ServiceException',\n 'error' => [\n 'httpStatusCode' => 500,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'ResourceNotFoundException',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidParameterValueException',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'UploadFunction' => [\n 'name' => 'UploadFunction',\n 'http' => [\n 'method' => 'PUT',\n 'requestUri' => '/2014-11-13/functions/{FunctionName}',\n 'responseCode' => 201,\n ],\n 'input' => [\n 'shape' => 'UploadFunctionRequest',\n ],\n 'output' => [\n 'shape' => 'FunctionConfiguration',\n ],\n 'errors' => [\n [\n 'shape' => 'ServiceException',\n 'error' => [\n 'httpStatusCode' => 500,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidParameterValueException',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'ResourceNotFoundException',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n ],\n ],\n ],\n 'shapes' => [\n 'AddEventSourceRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'EventSource',\n 'FunctionName',\n 'Role',\n ],\n 'members' => [\n 'EventSource' => [\n 'shape' => 'String',\n ],\n 'FunctionName' => [\n 'shape' => 'FunctionName',\n ],\n 'Role' => [\n 'shape' => 'RoleArn',\n ],\n 'BatchSize' => [\n 'shape' => 'Integer',\n ],\n 'Parameters' => [\n 'shape' => 'Map',\n ],\n ],\n ],\n 'Blob' => [\n 'type' => 'blob',\n 'streaming' => true,\n ],\n 'DeleteFunctionRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'FunctionName',\n ],\n 'members' => [\n 'FunctionName' => [\n 'shape' => 'FunctionName',\n 'location' => 'uri',\n 'locationName' => 'FunctionName',\n ],\n ],\n ],\n 'Description' => [\n 'type' => 'string',\n 'min' => 0,\n 'max' => 256,\n ],\n 'EventSourceConfiguration' => [\n 'type' => 'structure',\n 'members' => [\n 'UUID' => [\n 'shape' => 'String',\n ],\n 'BatchSize' => [\n 'shape' => 'Integer',\n ],\n 'EventSource' => [\n 'shape' => 'String',\n ],\n 'FunctionName' => [\n 'shape' => 'FunctionName',\n ],\n 'Parameters' => [\n 'shape' => 'Map',\n ],\n 'Role' => [\n 'shape' => 'RoleArn',\n ],\n 'LastModified' => [\n 'shape' => 'Timestamp',\n ],\n 'IsActive' => [\n 'shape' => 'Boolean',\n ],\n 'Status' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'EventSourceList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'EventSourceConfiguration',\n ],\n ],\n 'FunctionArn' => [\n 'type' => 'string',\n 'pattern' => 'arn:aws:lambda:[a-z]{2}-[a-z]+-\\\\d{1}:\\\\d{12}:function:[a-zA-Z0-9-_]+(\\\\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}]?',\n ],\n 'FunctionCodeLocation' => [\n 'type' => 'structure',\n 'members' => [\n 'RepositoryType' => [\n 'shape' => 'String',\n ],\n 'Location' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'FunctionConfiguration' => [\n 'type' => 'structure',\n 'members' => [\n 'FunctionName' => [\n 'shape' => 'FunctionName',\n ],\n 'FunctionARN' => [\n 'shape' => 'FunctionArn',\n ],\n 'ConfigurationId' => [\n 'shape' => 'String',\n ],\n 'Runtime' => [\n 'shape' => 'Runtime',\n ],\n 'Role' => [\n 'shape' => 'RoleArn',\n ],\n 'Handler' => [\n 'shape' => 'Handler',\n ],\n 'Mode' => [\n 'shape' => 'Mode',\n ],\n 'CodeSize' => [\n 'shape' => 'Long',\n ],\n 'Description' => [\n 'shape' => 'Description',\n ],\n 'Timeout' => [\n 'shape' => 'Timeout',\n ],\n 'MemorySize' => [\n 'shape' => 'MemorySize',\n ],\n 'LastModified' => [\n 'shape' => 'Timestamp',\n ],\n ],\n ],\n 'FunctionList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'FunctionConfiguration',\n ],\n ],\n 'FunctionName' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 64,\n 'pattern' => '[a-zA-Z0-9-_]+',\n ],\n 'GetEventSourceRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'UUID',\n ],\n 'members' => [\n 'UUID' => [\n 'shape' => 'String',\n 'location' => 'uri',\n 'locationName' => 'UUID',\n ],\n ],\n ],\n 'GetFunctionConfigurationRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'FunctionName',\n ],\n 'members' => [\n 'FunctionName' => [\n 'shape' => 'FunctionName',\n 'location' => 'uri',\n 'locationName' => 'FunctionName',\n ],\n ],\n ],\n 'GetFunctionRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'FunctionName',\n ],\n 'members' => [\n 'FunctionName' => [\n 'shape' => 'FunctionName',\n 'location' => 'uri',\n 'locationName' => 'FunctionName',\n ],\n ],\n ],\n 'GetFunctionResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'Configuration' => [\n 'shape' => 'FunctionConfiguration',\n ],\n 'Code' => [\n 'shape' => 'FunctionCodeLocation',\n ],\n ],\n ],\n 'Handler' => [\n 'type' => 'string',\n 'pattern' => '[a-zA-Z0-9./\\\\-_]+',\n ],\n 'HttpStatus' => [\n 'type' => 'integer',\n ],\n 'Integer' => [\n 'type' => 'integer',\n ],\n 'InvalidParameterValueException' => [\n 'type' => 'structure',\n 'members' => [\n 'Type' => [\n 'shape' => 'String',\n ],\n 'message' => [\n 'shape' => 'String',\n ],\n ],\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n 'InvalidRequestContentException' => [\n 'type' => 'structure',\n 'members' => [\n 'Type' => [\n 'shape' => 'String',\n ],\n 'message' => [\n 'shape' => 'String',\n ],\n ],\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n 'InvokeAsyncRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'FunctionName',\n 'InvokeArgs',\n ],\n 'members' => [\n 'FunctionName' => [\n 'shape' => 'FunctionName',\n 'location' => 'uri',\n 'locationName' => 'FunctionName',\n ],\n 'InvokeArgs' => [\n 'shape' => 'Blob',\n ],\n ],\n 'payload' => 'InvokeArgs',\n ],\n 'InvokeAsyncResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'Status' => [\n 'shape' => 'HttpStatus',\n 'location' => 'statusCode',\n ],\n ],\n ],\n 'ListEventSourcesRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'EventSourceArn' => [\n 'shape' => 'String',\n 'location' => 'querystring',\n 'locationName' => 'EventSource',\n ],\n 'FunctionName' => [\n 'shape' => 'FunctionName',\n 'location' => 'querystring',\n 'locationName' => 'FunctionName',\n ],\n 'Marker' => [\n 'shape' => 'String',\n 'location' => 'querystring',\n 'locationName' => 'Marker',\n ],\n 'MaxItems' => [\n 'shape' => 'MaxListItems',\n 'location' => 'querystring',\n 'locationName' => 'MaxItems',\n ],\n ],\n ],\n 'ListEventSourcesResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'NextMarker' => [\n 'shape' => 'String',\n ],\n 'EventSources' => [\n 'shape' => 'EventSourceList',\n ],\n ],\n ],\n 'ListFunctionsRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'Marker' => [\n 'shape' => 'String',\n 'location' => 'querystring',\n 'locationName' => 'Marker',\n ],\n 'MaxItems' => [\n 'shape' => 'MaxListItems',\n 'location' => 'querystring',\n 'locationName' => 'MaxItems',\n ],\n ],\n ],\n 'ListFunctionsResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'NextMarker' => [\n 'shape' => 'String',\n ],\n 'Functions' => [\n 'shape' => 'FunctionList',\n ],\n ],\n ],\n 'Long' => [\n 'type' => 'long',\n ],\n 'Map' => [\n 'type' => 'map',\n 'key' => [\n 'shape' => 'String',\n ],\n 'value' => [\n 'shape' => 'String',\n ],\n ],\n 'MaxListItems' => [\n 'type' => 'integer',\n 'min' => 1,\n 'max' => 10000,\n ],\n 'MemorySize' => [\n 'type' => 'integer',\n 'min' => 128,\n 'max' => 1024,\n ],\n 'Mode' => [\n 'type' => 'string',\n 'enum' => [\n 'event',\n ],\n ],\n 'RemoveEventSourceRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'UUID',\n ],\n 'members' => [\n 'UUID' => [\n 'shape' => 'String',\n 'location' => 'uri',\n 'locationName' => 'UUID',\n ],\n ],\n ],\n 'ResourceNotFoundException' => [\n 'type' => 'structure',\n 'members' => [\n 'Type' => [\n 'shape' => 'String',\n ],\n 'Message' => [\n 'shape' => 'String',\n ],\n ],\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n 'RoleArn' => [\n 'type' => 'string',\n 'pattern' => 'arn:aws:iam::\\\\d{12}:role/?[a-zA-Z_0-9+=,.@\\\\-_/]+',\n ],\n 'Runtime' => [\n 'type' => 'string',\n 'enum' => [\n 'nodejs',\n ],\n ],\n 'ServiceException' => [\n 'type' => 'structure',\n 'members' => [\n 'Type' => [\n 'shape' => 'String',\n ],\n 'Message' => [\n 'shape' => 'String',\n ],\n ],\n 'error' => [\n 'httpStatusCode' => 500,\n ],\n 'exception' => true,\n ],\n 'String' => [\n 'type' => 'string',\n ],\n 'Timeout' => [\n 'type' => 'integer',\n 'min' => 1,\n 'max' => 60,\n ],\n 'Timestamp' => [\n 'type' => 'string',\n ],\n 'UpdateFunctionConfigurationRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'FunctionName',\n ],\n 'members' => [\n 'FunctionName' => [\n 'shape' => 'FunctionName',\n 'location' => 'uri',\n 'locationName' => 'FunctionName',\n ],\n 'Role' => [\n 'shape' => 'RoleArn',\n 'location' => 'querystring',\n 'locationName' => 'Role',\n ],\n 'Handler' => [\n 'shape' => 'Handler',\n 'location' => 'querystring',\n 'locationName' => 'Handler',\n ],\n 'Description' => [\n 'shape' => 'Description',\n 'location' => 'querystring',\n 'locationName' => 'Description',\n ],\n 'Timeout' => [\n 'shape' => 'Timeout',\n 'location' => 'querystring',\n 'locationName' => 'Timeout',\n ],\n 'MemorySize' => [\n 'shape' => 'MemorySize',\n 'location' => 'querystring',\n 'locationName' => 'MemorySize',\n ],\n ],\n ],\n 'UploadFunctionRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'FunctionName',\n 'FunctionZip',\n 'Runtime',\n 'Role',\n 'Handler',\n 'Mode',\n ],\n 'members' => [\n 'FunctionName' => [\n 'shape' => 'FunctionName',\n 'location' => 'uri',\n 'locationName' => 'FunctionName',\n ],\n 'FunctionZip' => [\n 'shape' => 'Blob',\n ],\n 'Runtime' => [\n 'shape' => 'Runtime',\n 'location' => 'querystring',\n 'locationName' => 'Runtime',\n ],\n 'Role' => [\n 'shape' => 'RoleArn',\n 'location' => 'querystring',\n 'locationName' => 'Role',\n ],\n 'Handler' => [\n 'shape' => 'Handler',\n 'location' => 'querystring',\n 'locationName' => 'Handler',\n ],\n 'Mode' => [\n 'shape' => 'Mode',\n 'location' => 'querystring',\n 'locationName' => 'Mode',\n ],\n 'Description' => [\n 'shape' => 'Description',\n 'location' => 'querystring',\n 'locationName' => 'Description',\n ],\n 'Timeout' => [\n 'shape' => 'Timeout',\n 'location' => 'querystring',\n 'locationName' => 'Timeout',\n ],\n 'MemorySize' => [\n 'shape' => 'MemorySize',\n 'location' => 'querystring',\n 'locationName' => 'MemorySize',\n ],\n ],\n 'payload' => 'FunctionZip',\n ],\n 'Boolean' => [\n 'type' => 'boolean',\n ],\n ],\n];\n" }, { "alpha_fraction": 0.4849246144294739, "alphanum_fraction": 0.4849246144294739, "avg_line_length": 23.875, "blob_id": "e61ff1b3edc611aaa389523eb25282f141204270", "content_id": "98e5b69f0999cc0273c9fdb5fd7132e60dfd426c", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 796, "license_type": "permissive", "max_line_length": 41, "num_lines": 32, "path": "/src/data/elasticmapreduce-2009-03-31.paginators.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php return [\n 'pagination' => [\n 'DescribeJobFlows' => [\n 'result_key' => 'JobFlows',\n ],\n 'ListBootstrapActions' => [\n 'input_token' => 'Marker',\n 'output_token' => 'Marker',\n 'result_key' => 'BootstrapActions',\n ],\n 'ListClusters' => [\n 'input_token' => 'Marker',\n 'output_token' => 'Marker',\n 'result_key' => 'Clusters',\n ],\n 'ListInstanceGroups' => [\n 'input_token' => 'Marker',\n 'output_token' => 'Marker',\n 'result_key' => 'InstanceGroups',\n ],\n 'ListInstances' => [\n 'input_token' => 'Marker',\n 'output_token' => 'Marker',\n 'result_key' => 'Instances',\n ],\n 'ListSteps' => [\n 'input_token' => 'Marker',\n 'output_token' => 'Marker',\n 'result_key' => 'Steps',\n ],\n ],\n];\n" }, { "alpha_fraction": 0.5354896783828735, "alphanum_fraction": 0.5422282218933105, "avg_line_length": 26.481481552124023, "blob_id": "340d14f99077c23a7284362f07da7ce5e89594ff", "content_id": "77cfecfe59b043d922119bb0d30cf0a8f5f8099a", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2226, "license_type": "permissive", "max_line_length": 71, "num_lines": 81, "path": "/tests/Credentials/RefreshableCredentialsTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Credentials;\n\nuse Aws\\Credentials\\Credentials;\nuse Aws\\Credentials\\RefreshableCredentials;\n\n/**\n * @covers Aws\\Credentials\\RefreshableCredentials\n */\nclass RefreshableCredentialsTest extends \\PHPUnit_Framework_TestCase\n{\n public function proxyMethods()\n {\n return [\n ['getAccessKeyId'],\n ['getSecretKey'],\n ['getSecurityToken'],\n ['toArray']\n ];\n }\n\n /**\n * @dataProvider proxyMethods\n */\n public function testRefreshesWhenProxying($method)\n {\n $retVal = new Credentials('a', 'b', 'c', time() + 5000);\n\n $old = $this->getMockBuilder('Aws\\Credentials\\Credentials')\n ->setConstructorArgs(['a', 'b', 'c'])\n ->setMethods(['isExpired'])\n ->getMock();\n $old->expects($this->exactly(2))\n ->method('isExpired')\n ->will($this->returnCallback(function () {\n static $i = 0;\n return ++$i == 2;\n }));\n\n $queue = [$old, $retVal];\n $creds = new RefreshableCredentials(function () use (&$queue) {\n return array_shift($queue);\n });\n\n $a = $retVal->{$method}();\n $b = $creds->{$method}();\n if ($method == 'toArray') {\n unset($a['expires'], $b['expires']);\n }\n\n $this->assertSame($a, $b);\n }\n\n public function testPassesThroughExpirationMethods()\n {\n $a = new Credentials('a', 'b', 'c', time() + 5000);\n $b = new RefreshableCredentials(function () use ($a) {\n return $a;\n });\n $this->assertSame($a->isExpired(), $b->isExpired());\n $this->assertSame($a->getExpiration(), $b->getExpiration());\n }\n\n /**\n * @expectedException \\Aws\\Exception\\CredentialsException\n */\n public function testEnsuresCredentialsAreValid()\n {\n new RefreshableCredentials(function () { return 'foo'; });\n }\n\n /**\n * @expectedException \\Aws\\Exception\\CredentialsException\n */\n public function testEnsuresCredentialsAreRefreshed()\n {\n new RefreshableCredentials(function () {\n return new Credentials('a', 'b', 'c', time() - 1000);\n });\n }\n}\n" }, { "alpha_fraction": 0.5785518884658813, "alphanum_fraction": 0.5812841653823853, "avg_line_length": 27.705883026123047, "blob_id": "11845bdfb9db0a304262259facb8a1f729f94e6a", "content_id": "77122cbb876cf699fd133027d11c8abbf74a697e", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1464, "license_type": "permissive", "max_line_length": 68, "num_lines": 51, "path": "/src/Retry/ThrottlingFilter.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Retry;\n\nuse GuzzleHttp\\Event\\AbstractTransferEvent;\nuse GuzzleHttp\\Subscriber\\Retry\\RetrySubscriber;\n\n/**\n * Retries throttling responses.\n */\nclass ThrottlingFilter\n{\n /** @var array Error codes that indicate throttling */\n private static $throttlingExceptions = [\n 'RequestLimitExceeded' => true,\n 'Throttling' => true,\n 'ThrottlingException' => true,\n 'ProvisionedThroughputExceededException' => true,\n 'RequestThrottled' => true,\n ];\n\n /** @var callable */\n private $exceptionParser;\n\n /**\n * @param callable $exceptionParser Exception parser to use\n */\n public function __construct(callable $exceptionParser)\n {\n $this->exceptionParser = $exceptionParser;\n }\n\n public function __invoke($retries, AbstractTransferEvent $event)\n {\n // Doesn't mess with networking errors.\n if (!($response = $event->getResponse())) {\n return RetrySubscriber::DEFER;\n }\n\n // Only works on 4xx respsonses\n if (substr($response->getStatusCode(), 0, 1) != '4') {\n return RetrySubscriber::DEFER;\n }\n\n $parser = $this->exceptionParser;\n $parts = $parser($response);\n\n return isset(self::$throttlingExceptions[$parts['code']])\n ? RetrySubscriber::RETRY\n : RetrySubscriber::DEFER;\n }\n}\n" }, { "alpha_fraction": 0.5642637014389038, "alphanum_fraction": 0.5690097212791443, "avg_line_length": 30.562753677368164, "blob_id": "5212287bdeaced68126c2a7e3ca08b5a0008c6d2", "content_id": "e140b73ac45c3e698937aa50927733411f449c54", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 7796, "license_type": "permissive", "max_line_length": 81, "num_lines": 247, "path": "/src/S3/PostObject.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\S3;\n\nuse GuzzleHttp\\Collection;\nuse GuzzleHttp\\Url;\n\n/**\n * Encapsulates the logic for getting the data for an S3 object POST upload form\n */\nclass PostObject extends Collection\n{\n /** @var S3Client The S3 client being used to sign the policy */\n private $client;\n\n /** @var string The bucket name where the object will be posted */\n private $bucket;\n\n /** @var array The <form> tag attributes as an array */\n private $formAttributes;\n\n /** @var array The form's <input> elements as an array */\n private $formInputs;\n\n /** @var string The raw json policy */\n private $jsonPolicy;\n\n /**\n * Constructs the PostObject\n *\n * The options array accepts the following keys:\n *\n * - acl: The access control setting to apply to the uploaded file. Accepts\n * any of the CannedAcl constants.\n * - Cache-Control: The Cache-Control HTTP header value to apply to the\n * uploaded file\n * - Content-Disposition: The Content-Disposition HTTP header value to\n * apply to the uploaded file\n * - Content-Encoding: The Content-Encoding HTTP header value to apply to\n * the uploaded file.\n * - Content-Type: The Content-Type HTTP header value to apply to the\n * uploaded file. The default value is `application/octet-stream`.\n * - Expires: The Expires HTTP header value to apply to the uploaded file\n * - key: The location where the file should be uploaded to. The default\n * value is `^${filename}` which will use the name of the uploaded file.\n * - policy: A raw policy in JSON format. By default, the PostObject\n * creates one for you.\n * - policy_callback: A callback used to modify the policy before encoding\n * and signing it. The method signature for the callback should accept an\n * array of the policy data as the 1st argument, (optionally) the\n * PostObject as the 2nd argument, and return the policy data with the\n * desired modifications.\n * - success_action_redirect: The URI for Amazon S3 to redirect to upon\n * successful upload.\n * - success_action_status: The status code for Amazon S3 to return upon\n * successful upload.\n * - ttd: The expiration time for the generated upload form data\n * - x-amz-meta-*: Any custom meta tag that should be set to the object\n * - x-amz-server-side-encryption: The server-side encryption mechanism to\n * use\n * - x-amz-storage-class: The storage setting to apply to the object\n * - x-amz-storage-class: The storage setting to apply to the object\n * - x-amz-server-side-encryption-customer-algorithm: The SSE-C algorithm\n * - x-amz-server-side-encryption-customer-key: The SSE-C secret key\n * - x-amz-server-side-encryption-customer-key-MD5: MD5 hash of the\n * SSE-C customer secret key\n *\n * For the Cache-Control, Content-Disposition, Content-Encoding,\n * Content-Type, Expires, and key options, to use a \"starts-with\" comparison\n * instead of an equals comparison, prefix the value with a ^ (carat)\n * character.\n *\n * @param S3Client $client Client used with the POST object\n * @param string $bucket Bucket to use\n * @param array $options Associative array of options\n */\n public function __construct(S3Client $client, $bucket, array $options = [])\n {\n $this->client = $client;\n $this->bucket = $bucket;\n parent::__construct($options);\n }\n\n /**\n * Prepares the POST object to be utilzed to build a POST form.\n *\n * @return PostObject\n */\n public function prepareData()\n {\n // Validate required options\n $options = Collection::fromConfig($this->data, [\n 'ttd' => '+1 hour',\n 'key' => '^${filename}',\n ]);\n\n $ttd = $this->pluckTtd($options);\n\n // If a policy or policy callback were provided, extract those from\n // the options.\n $rawJsonPolicy = $options['policy'];\n $policyCallback = $options['policy_callback'];\n unset($options['policy'], $options['policy_callback']);\n\n // Setup policy document\n $policy = [\n 'expiration' => gmdate('Y-m-d\\TH:i:s\\Z', $ttd),\n 'conditions' => [['bucket' => $this->bucket]]\n ];\n\n // Setup basic form\n $this->formAttributes = [\n 'action' => $this->generateUrl($options),\n 'method' => 'POST',\n 'enctype' => 'multipart/form-data'\n ];\n\n $this->formInputs = [\n 'AWSAccessKeyId' => $this->client->getCredentials()->getAccessKeyId()\n ];\n\n // Add success action status\n $status = (int) $options->get('success_action_status');\n\n if ($status && in_array($status, [200, 201, 204])) {\n $this->formInputs['success_action_status'] = (string) $status;\n $policy['conditions'][] = [\n 'success_action_status' => (string) $status\n ];\n unset($options['success_action_status']);\n }\n\n // Add other options\n foreach ($options as $key => $value) {\n $value = (string) $value;\n if ($value[0] === '^') {\n $value = substr($value, 1);\n $this->formInputs[$key] = $value;\n $value = preg_replace('/\\$\\{(\\w*)\\}/', '', $value);\n $policy['conditions'][] = ['starts-with', '$' . $key, $value];\n } else {\n $this->formInputs[$key] = $value;\n $policy['conditions'][] = [$key => $value];\n }\n }\n\n // Handle the policy\n $policy = is_callable($policyCallback)\n ? $policyCallback($policy, $this)\n : $policy;\n $this->jsonPolicy = $rawJsonPolicy ?: json_encode($policy);\n $this->applyPolicy();\n\n return $this;\n }\n\n /**\n * Gets the S3 client.\n *\n * @return S3Client\n */\n public function getClient()\n {\n return $this->client;\n }\n\n /**\n * Gets the bucket name.\n *\n * @return string\n */\n public function getBucket()\n {\n return $this->bucket;\n }\n\n /**\n * Gets the form attributes as an array.\n *\n * @return array\n */\n public function getFormAttributes()\n {\n return $this->formAttributes;\n }\n\n /**\n * Gets the form inputs as an array.\n *\n * @return array\n */\n public function getFormInputs()\n {\n return $this->formInputs;\n }\n\n /**\n * Gets the raw JSON policy.\n *\n * @return string\n */\n public function getJsonPolicy()\n {\n return $this->jsonPolicy;\n }\n\n private function pluckTtd(Collection $options)\n {\n $ttd = $options['ttd'];\n $ttd = is_numeric($ttd) ? (int) $ttd : strtotime($ttd);\n unset($options['ttd']);\n\n return $ttd;\n }\n\n private function generateUrl()\n {\n $url = Url::fromString($this->client->getEndpoint());\n\n if ($url->getScheme() === 'https' &&\n strpos($this->bucket, '.') !== false\n ) {\n // Use path-style URLs\n $url->setPath($this->bucket);\n } else {\n // Use virtual-style URLs\n $url->setHost($this->bucket . '.' . $url->getHost());\n }\n\n return $url;\n }\n\n /**\n * Handles the encoding, signing, and injecting of the policy\n */\n protected function applyPolicy()\n {\n $jsonPolicy64 = base64_encode($this->jsonPolicy);\n $this->formInputs['policy'] = $jsonPolicy64;\n\n $this->formInputs['signature'] = base64_encode(hash_hmac(\n 'sha1',\n $jsonPolicy64,\n $this->client->getCredentials()->getSecretKey(),\n true\n ));\n }\n}\n" }, { "alpha_fraction": 0.5847665667533875, "alphanum_fraction": 0.5884521007537842, "avg_line_length": 23.66666603088379, "blob_id": "f03969f31b7f3e1aa6a71d75a0fd975ea1aa219d", "content_id": "fc61802760945c0c4a7f7c78877b66df391dc24f", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 814, "license_type": "permissive", "max_line_length": 71, "num_lines": 33, "path": "/src/S3/PutObjectUrlSubscriber.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\S3;\n\nuse GuzzleHttp\\Command\\Event\\ProcessEvent;\nuse GuzzleHttp\\Event\\SubscriberInterface;\n\n/**\n * Injects ObjectURL into the result model of the PutObject operation.\n *\n * @internal\n */\nclass PutObjectUrlSubscriber implements SubscriberInterface\n{\n public function getEvents()\n {\n return ['process' => ['addObjectUrl', -10]];\n }\n\n public function addObjectUrl(ProcessEvent $e)\n {\n if ($e->getException()) {\n return;\n }\n\n $name = $e->getCommand()->getName();\n\n if ($name === 'PutObject' || $name === 'CopyObject') {\n $e->getResult()['ObjectURL'] = $e->getRequest()->getUrl();\n } elseif ($name === 'CompleteMultipartUpload') {\n $e->getResult()['ObjectURL'] = $e->getResult()['Location'];\n }\n }\n}\n" }, { "alpha_fraction": 0.5814254879951477, "alphanum_fraction": 0.5831533670425415, "avg_line_length": 30.283782958984375, "blob_id": "447cafa3ddb4ef7ac47e7eb53db0d5d06c5b95f7", "content_id": "cf18839450a976fa6f9ef684dfb815f4a0025d8a", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2315, "license_type": "permissive", "max_line_length": 79, "num_lines": 74, "path": "/src/S3/BucketStyleSubscriber.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\S3;\n\nuse GuzzleHttp\\Command\\Event\\PreparedEvent;\nuse GuzzleHttp\\Event\\SubscriberInterface;\n\n/**\n * Used to change the style in which buckets are inserted in to the URL\n * (path or virtual style) based on the context.\n *\n * @internal\n */\nclass BucketStyleSubscriber implements SubscriberInterface\n{\n private static $exclusions = ['GetBucketLocation' => true];\n private $bucketEndpoint;\n\n /**\n * @param bool $bucketEndpoint Set to true to send requests to a bucket\n * specific endpoint and not inject a bucket\n * in the request host or path.\n */\n public function __construct($bucketEndpoint = false)\n {\n $this->bucketEndpoint = $bucketEndpoint;\n }\n\n public function getEvents()\n {\n return ['prepared' => ['setBucketStyle', 'last']];\n }\n\n /**\n * Changes how buckets are referenced in the HTTP request\n *\n * @param PreparedEvent $event Event emitted\n */\n public function setBucketStyle(PreparedEvent $event)\n {\n $command = $event->getCommand();\n $request = $event->getRequest();\n $bucket = $command['Bucket'];\n $path = $request->getPath();\n\n if (!$bucket || isset(self::$exclusions[$command->getName()])) {\n return;\n }\n\n if ($this->bucketEndpoint) {\n $path = $this->removeBucketFromPath($path, $bucket);\n } elseif (!$command['PathStyle']\n && S3Client::isBucketDnsCompatible($bucket)\n && !($request->getScheme() == 'https' && strpos($bucket, '.'))\n ) {\n // Switch to virtual if PathStyle is disabled, or not a DNS\n // compatible bucket name, or the scheme is https and there are no\n // dots in the hostheader (avoids SSL issues).\n $request->setHost($bucket . '.' . $request->getHost());\n $path = $this->removeBucketFromPath($path, $bucket);\n }\n\n // Modify the Key to make sure the key is encoded, but slashes are not.\n if ($command['Key']) {\n $path = S3Client::encodeKey(rawurldecode($path));\n }\n\n $request->setPath($path);\n }\n\n private function removeBucketFromPath($path, $bucket)\n {\n return substr($path, strlen($bucket) + 2);\n }\n}\n" }, { "alpha_fraction": 0.614814817905426, "alphanum_fraction": 0.6222222447395325, "avg_line_length": 18.285715103149414, "blob_id": "9720fff122acc4941f87c0482f6c4c6b26c6488e", "content_id": "2caa2e282565635b26c8132bf51e945af717a698", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 405, "license_type": "permissive", "max_line_length": 61, "num_lines": 21, "path": "/build/json-to-php.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\n/*\n * Converts a JSON file to a PHP file that can be require()d.\n */\n\nrequire __DIR__ . '/functions.php';\n\nif (!isset($argv[1])) {\n die('A source file path was not provided in argument 1');\n}\n\n$file = $argv[1];\n\nif (!is_file($file)) {\n die('The source file must be a readable file.');\n}\n\n$json = json_decode(file_get_contents($file), true);\n$script = get_code_for_array($json);\n\necho $script;\n" }, { "alpha_fraction": 0.7229862213134766, "alphanum_fraction": 0.7229862213134766, "avg_line_length": 22.136363983154297, "blob_id": "152867d6d48133b7dad7f471a739fa7235f9749d", "content_id": "c564ee83cfd763352c2b03aef66cd56a2b5e7bbd", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 509, "license_type": "permissive", "max_line_length": 61, "num_lines": 22, "path": "/src/Signature/AnonymousSignature.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Signature;\n\nuse Aws\\Credentials\\CredentialsInterface;\nuse GuzzleHttp\\Message\\RequestInterface;\n\n/**\n * Provides anonymous client access (does not sign requests).\n */\nclass AnonymousSignature implements SignatureInterface\n{\n public function signRequest(\n RequestInterface $request,\n CredentialsInterface $credentials\n ) {}\n\n public function createPresignedUrl(\n RequestInterface $request,\n CredentialsInterface $credentials,\n $expires\n ) {}\n}\n" }, { "alpha_fraction": 0.5620437860488892, "alphanum_fraction": 0.5628548264503479, "avg_line_length": 25.23404312133789, "blob_id": "04a5b9ce9d1f268b8b4eda005cbb25c36ba75290", "content_id": "480512efaec186039c92179730a526548b54a92e", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1233, "license_type": "permissive", "max_line_length": 78, "num_lines": 47, "path": "/src/Exception/MultipartUploadException.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Exception;\n\nuse Aws\\Multipart\\UploadState;\n\nclass MultipartUploadException extends \\RuntimeException\n{\n const MSG_TEMPLATE = 'An exception occurred while %s a multipart upload.';\n\n /** @var UploadState State of the erroneous transfer */\n private $state;\n\n /**\n * @param UploadState $state Upload state at time of the exception.\n * @param string $action Action being taken.\n * @param \\Exception $prev Exception being thrown.\n */\n public function __construct(\n UploadState $state,\n $action,\n \\Exception $prev = null\n ) {\n if (is_array($action)) {\n $message = sprintf(self::MSG_TEMPLATE, 'uploading parts to');\n $message .= \" The following parts had errors:\\n\";\n foreach ($action as $part => $error) {\n $message .= \"- Part {$part}: {$error}\\n\";\n }\n } else {\n $message = sprintf(self::MSG_TEMPLATE, $action);\n }\n\n parent::__construct($message, 0, $prev);\n\n $this->state = $state;\n }\n\n /**\n * Get the state of the transfer\n *\n * @return UploadState\n */\n public function getState()\n {\n return $this->state;\n }\n}\n" }, { "alpha_fraction": 0.5470737814903259, "alphanum_fraction": 0.5597964525222778, "avg_line_length": 30.190475463867188, "blob_id": "288686652e0f8af66d47075db8bc4dfe47ab7f66", "content_id": "752c8960c1c563f9e3c70be46d630a2e9106ff24", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3930, "license_type": "permissive", "max_line_length": 84, "num_lines": 126, "path": "/tests/Credentials/InstanceProfileProviderTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Credentials;\n\nuse Aws\\Credentials\\InstanceProfileProvider;\nuse GuzzleHttp\\Client;\nuse GuzzleHttp\\Exception\\RequestException;\nuse GuzzleHttp\\Message\\Request;\nuse GuzzleHttp\\Message\\Response;\nuse GuzzleHttp\\Stream\\Stream;\nuse GuzzleHttp\\Subscriber\\Mock;\n\n/**\n * @covers Aws\\Credentials\\InstanceProfileProvider\n */\nclass InstanceProfileProviderTest extends \\PHPUnit_Framework_TestCase\n{\n private function getCredentialArray(\n $key, $secret, $token = null, $time = null, $success = true\n ) {\n return [\n 'Code' => $success ? 'Success' : 'Failed',\n 'AccessKeyId' => $key,\n 'SecretAccessKey' => $secret,\n 'Token' => $token,\n 'Expiration' => $time\n ];\n }\n\n private function getTestCreds($result, $profile = null, Response $more = null)\n {\n $client = new Client([\n 'base_url' => 'http://169.254.169.254/latest/'\n ]);\n\n $responses = [];\n if (!$profile) {\n $responses[] = new Response(200, [], Stream::factory('test'));\n }\n $responses[] = new Response(200, [], Stream::factory(json_encode($result)));\n if ($more) {\n $responses[] = $more;\n }\n $client->getEmitter()->attach(new Mock($responses));\n\n $args = ['profile' => $profile];\n $args['client'] = $client;\n $provider = new InstanceProfileProvider($args);\n\n return $provider();\n }\n\n public function testSeedsInitialCredentials()\n {\n $t = time() + 1000;\n $c = $this->getTestCreds(\n $this->getCredentialArray('foo', 'baz', null, \"@{$t}\"),\n 'foo'\n );\n $this->assertEquals('foo', $c->getAccessKeyId());\n $this->assertEquals('baz', $c->getSecretKey());\n $this->assertEquals(null, $c->getSecurityToken());\n $this->assertEquals($t, $c->getExpiration());\n }\n\n public function testReturnsNullIfProfileIsNotAvailable()\n {\n $client = new Client(['base_url' => 'http://169.254.169.254/latest/']);\n $client->getEmitter()->attach(\n new Mock([\n new RequestException('foo', new Request('GET', 'http://foo'))\n ])\n );\n $p = new InstanceProfileProvider(['client' => $client]);\n $this->assertNull($p());\n }\n\n /**\n * @expectedException \\Aws\\Exception\\CredentialsException\n * @expectedExceptionMessage Error retrieving credentials from the instance\n */\n public function testThrowsExceptionIfCredentialsNotAvailable()\n {\n $client = new Client(['base_url' => 'http://169.254.169.254/latest/']);\n $client->getEmitter()->attach(\n new Mock([\n new RequestException('foo', new Request('GET', 'http://foo'))\n ])\n );\n $args['client'] = $client;\n $args['profile'] = 'foo';\n $p = new InstanceProfileProvider([\n 'client' => $client,\n 'profile' => 'foo'\n ]);\n $p();\n }\n\n /**\n * @expectedException \\Aws\\Exception\\CredentialsException\n * @expectedExceptionMessage Unexpected instance profile response\n */\n public function testThrowsExceptionOnInvalidMetadata()\n {\n $this->getTestCreds(\n $this->getCredentialArray(null, null, null, null, false),\n 'foo'\n );\n }\n\n public function testLoadsCredentialsAndProfile()\n {\n $t = time() + 1000;\n $c = $this->getTestCreds(\n $this->getCredentialArray('foo', 'baz', null, \"@{$t}\")\n );\n $this->assertEquals('foo', $c->getAccessKeyId());\n $this->assertEquals('baz', $c->getSecretKey());\n $this->assertEquals(null, $c->getSecurityToken());\n $this->assertEquals($t, $c->getExpiration());\n }\n\n public function testDoesNotRequireConfig()\n {\n new InstanceProfileProvider();\n }\n}\n" }, { "alpha_fraction": 0.5330874919891357, "alphanum_fraction": 0.5415898561477661, "avg_line_length": 32.77854537963867, "blob_id": "677ba8a413c11ebb1d4fb5172afadb1fe8d7691e", "content_id": "fca798c2a2b94d06c33e6708c7cacfbfc7dccc49", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 9762, "license_type": "permissive", "max_line_length": 94, "num_lines": 289, "path": "/src/S3/Transfer.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\S3;\n\nuse Aws\\Utils;\nuse GuzzleHttp\\Command\\Command;\nuse GuzzleHttp\\Command\\CommandInterface;\nuse GuzzleHttp\\Command\\Event\\PreparedEvent;\nuse transducers as t;\n\n/**\n * Transfers files from the local filesystem to S3 or from S3 to the local\n * filesystem.\n *\n * This class does not support copying from the local filesystem to somewhere\n * else on the local filesystem or from one S3 bucket to another.\n */\nclass Transfer\n{\n private $client;\n private $source;\n private $sourceScheme;\n private $dest;\n private $destScheme;\n private $s3Args = [];\n\n // Available options.\n private $concurrency = 5;\n private $mup_threshold = 20971520;\n private $base_dir;\n private $before;\n private $debug = false;\n\n /**\n * When providing the $source argument, you may provide a string referencing\n * the path to a directory on disk to upload, an s3 scheme URI that contains\n * the bucket and key (e.g., \"s3://bucket/key\"), or an \\Iterator object\n * that yields strings containing filenames that are the path to a file on\n * disk or an s3 scheme URI. The \"/key\" portion of an s3 URI is optional.\n *\n * When providing an iterator for the $source argument, you must also\n * provide a 'base_dir' key value pair in the $options argument.\n *\n * The $dest argument can be the path to a directory on disk or an s3\n * scheme URI (e.g., \"s3://bucket/key\").\n *\n * The options array can contain the following key value pairs:\n *\n * - base_dir: The directory to remove from the filename when saving.\n * - before: A callable that accepts the following positional arguments:\n * source, dest, command; where command is an instance of a Command\n * object. The provided command will be either a GetObject, PutObject,\n * InitiateMultipartUpload, or UploadPart command.\n * - mup_threshold: Size in bytes in which a multipart upload should be\n * used instead of PutObject. Defaults to 20971520 (20 MB).\n * - concurrency: Number of files to upload concurrently. Defaults to 5.\n * - debug: Set to true to print out debug information for transfers. Set\n * to an fopen() resource to write to a specific stream.\n *\n * @param S3Client $client Client used for transfers.\n * @param string|\\Iterator $source Where the files are transferred from.\n * @param string $dest Where the files are transferred to.\n * @param array $options Hash of options.\n */\n public function __construct(\n S3Client $client,\n $source,\n $dest,\n array $options = []\n ) {\n $client->registerStreamWrapper();\n if (is_string($source)) {\n $this->base_dir = $source;\n $source = Utils::recursiveDirIterator($source);\n } elseif (!$source instanceof \\Iterator) {\n throw new \\InvalidArgumentException('source must be the path to a '\n . 'directory or an iterator that yields file names.');\n } elseif (!$this->base_dir) {\n throw new \\InvalidArgumentException('You must provide the source '\n . 'argument as a string or provide the \"base_dir\" option.');\n }\n\n $valid = ['mup_threshold', 'base_dir', 'before', 'concurrency', 'debug'];\n foreach ($valid as $opt) {\n if (isset($options[$opt])) {\n $this->{$opt} = $options[$opt];\n }\n }\n\n if ($this->mup_threshold < 5248000) {\n throw new \\InvalidArgumentException('mup_threshold must be >= 5248000');\n }\n\n // Normalize the destination and source directory.\n $this->dest = rtrim(str_replace('\\\\', '/', $dest), '/');\n $this->base_dir = rtrim(str_replace('\\\\', '/', $this->base_dir), '/');\n $this->destScheme = $this->getScheme($this->dest);\n $this->sourceScheme = $this->getScheme($this->base_dir);\n $this->client = $client;\n\n if ($this->destScheme == 's3') {\n $this->s3Args = $this->getS3Args($this->dest);\n }\n\n if ($this->debug) {\n $this->wrapDebug();\n }\n\n $this->source = $this->wrapIterator($source);\n }\n\n /**\n * Transfers the files.\n */\n public function transfer()\n {\n if (!$this->source->valid()) {\n $this->source->rewind();\n }\n\n $options = ['pool_size' => $this->concurrency];\n $this->client->executeAll($this->source, $options);\n }\n\n /**\n * Creates an array that contains Bucket and Key by parsing the filename.\n *\n * @param string $filename Filename to parse.\n *\n * @return array\n */\n private function getS3Args($filename)\n {\n $parts = explode('/', str_replace('s3://', '', $filename), 2);\n $args = ['Bucket' => $parts[0]];\n if (isset($parts[1])) {\n $args['Key'] = $parts[1];\n }\n\n return $args;\n }\n\n /**\n * Creates an iterator that yields Commands from each filename.\n *\n * @param \\Iterator $iter Iterator to wrap.\n *\n * @return \\Iterator\n */\n private function wrapIterator(\\Iterator $iter)\n {\n $comp = [];\n // Filter out MUP uploads to send separate operations.\n if ($this->destScheme == 's3' && $this->sourceScheme == 'file') {\n $comp[] = t\\filter(function ($file) {\n if ($this->sourceScheme == 'file'\n && filesize($file) >= $this->mup_threshold\n ) {\n $this->mup($file);\n return false;\n }\n // Filter out \"/\" files stored on S3 as buckets.\n return substr($file, -1, 1) != '/';\n });\n }\n $comp[] = t\\map($this->getTransferFunction($this->sourceScheme, $this->destScheme));\n\n return t\\to_iter($iter, call_user_func_array('transducers\\comp', $comp));\n }\n\n /**\n * Parses the scheme from a filename.\n *\n * @param string $file Filename to parse.\n *\n * @return string\n */\n private function getScheme($file)\n {\n return !strpos($file, '://') ? 'file' : explode('://', $file)[0];\n }\n\n private function createS3Key($filename)\n {\n if (!isset($this->s3Args['Key'])) {\n return '';\n }\n\n $args = $this->s3Args;\n $args['Key'] = rtrim($args['Key'], '/');\n $args['Key'] .= preg_replace('#^' . preg_quote($this->base_dir) . '#', '', $filename);\n\n return $args['Key'];\n }\n\n private function wrapBefore($source, $dest, Command $command)\n {\n if ($this->before) {\n $command->getEmitter()->on(\n 'init',\n function () use ($source, $dest, $command) {\n call_user_func($this->before, $source, $dest, $command);\n }\n );\n }\n\n return $command;\n }\n\n private function getObject($filename)\n {\n $args = $this->getS3Args($filename);\n $dest = preg_replace('#^' . preg_quote($this->base_dir) . '#', '', $filename);\n $dest = $this->dest . '/' . ltrim($dest, '/');\n $args['SaveAs'] = $dest;\n $cmd = $this->client->getCommand('GetObject', $args);\n $dir = dirname($args['SaveAs']);\n\n // Create the directory if needed.\n if (!is_dir($dir) && !mkdir($dir, 0777, true)) {\n throw new \\RuntimeException(\"Could not create dir: $dir\");\n }\n\n return $this->wrapBefore($filename, $dest, $cmd);\n }\n\n private function putObject($filename)\n {\n $args = $this->s3Args;\n $args['SourceFile'] = $filename;\n $args['Key'] = $this->createS3Key($filename);\n $cmd = $this->client->getCommand('PutObject', $args);\n $dest = 's3://' . $args['Bucket'] . '/' . $args['Key'];\n\n return $this->wrapBefore($filename, $dest, $cmd);\n }\n\n private function getTransferFunction($source, $dest)\n {\n if ($dest == 's3' && $source == 's3') {\n throw new \\InvalidArgumentException('Cannot copy from s3 to s3');\n } elseif ($dest == 's3') {\n return function ($f) { return $this->putObject($f); };\n } elseif ($source == 's3') {\n return function ($f) { return $this->getObject($f); };\n }\n\n throw new \\InvalidArgumentException('Cannot copy local file to local file');\n }\n\n private function mup($filename)\n {\n $dest = 's3://' . $this->s3Args['Bucket']\n . '/' . $this->createS3Key($filename);\n $uploader = (new UploadBuilder())\n ->setBucket($this->s3Args['Bucket'])\n ->setKey($this->createS3Key($filename))\n ->setSource($filename)\n ->setClient($this->client)\n ->build();\n\n $fn = null;\n if ($this->before) {\n $fn = function(PreparedEvent $e) use ($filename, $dest) {\n $cmd = $e->getCommand();\n $cmd->debugStr = \"Part={$cmd['PartNumber']}\";\n call_user_func($this->before, $filename, $dest, $cmd);\n };\n }\n\n $uploader->upload($this->concurrency, $fn);\n }\n\n private function wrapDebug()\n {\n if ($this->debug === true) {\n $this->debug = fopen('php://output', 'w');\n }\n\n $before = $this->before;\n $this->before = function ($source, $dest, CommandInterface $command) use ($before) {\n $before and $before($source, $dest, $command);\n $ctx = sprintf('%s -> %s (%s)', $source, $dest, $command->getName());\n if (!empty($command->debugStr)) {\n $ctx .= ' : ' . $command->debugStr;\n }\n fwrite($this->debug, \"Transferring {$ctx}\\n\");\n };\n }\n}\n" }, { "alpha_fraction": 0.36837607622146606, "alphanum_fraction": 0.4231546223163605, "avg_line_length": 37.417911529541016, "blob_id": "15341b7eeb089b737b772a6395358d3c94875df5", "content_id": "d135f22fa0103c49a83a1f5058ddbda660031aad", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 12870, "license_type": "permissive", "max_line_length": 136, "num_lines": 335, "path": "/tests/Signature/S3SignatureTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Signature;\n\nuse Aws\\Credentials\\Credentials;\nuse Aws\\Signature\\S3Signature;\nuse GuzzleHttp\\Message\\MessageFactory;\nuse GuzzleHttp\\Message\\Request;\n\n/**\n * @covers Aws\\Signature\\S3Signature\n */\nclass S3SignatureTest extends \\PHPUnit_Framework_TestCase\n{\n public function testSignsRequest()\n {\n $creds = new Credentials('foo', 'bar', 'baz');\n $signature = new S3Signature();\n $request = (new MessageFactory)->createRequest(\n 'PUT',\n 'http://s3.amazonaws.com/bucket/key',\n [\n 'body' => 'body',\n 'headers' => [\n 'Content-Type' => 'Baz',\n 'X-Amz-Meta-Boo' => 'bam'\n ]\n ]\n );\n\n $signature->signRequest($request, $creds);\n $this->assertEquals('baz', $request->getHeader('X-Amz-Security-Token'));\n $this->assertTrue($request->hasHeader('Date'));\n $this->assertFalse($request->hasHeader('X-Amz-Date'));\n $this->assertTrue($request->hasHeader('Authorization'));\n $this->assertContains('AWS foo:', $request->getHeader('Authorization'));\n\n $creq = $request->getConfig()->get('aws.signature');\n $lines = explode(\"\\n\", $creq);\n $this->assertTrue(time() - strtotime($lines[3]) < 100);\n unset($lines[3]);\n\n $creq = implode(\"\\n\", $lines);\n $this->assertEquals(\n \"PUT\\n\\nBaz\\nx-amz-meta-boo:bam\\nx-amz-security-token:baz\\n/bucket/key\",\n $creq\n );\n }\n\n public function presignedUrlProvider()\n {\n return [\n [\n \"GET /t1234/test\\r\\nHost: s3.amazonaws.com\\r\\n\\r\\n\",\n 'http://s3.amazonaws.com/t1234/test?AWSAccessKeyId=foo&Expires=1397952000&Signature=hIZ2sBC96XAf1hiqE%2BuCC8VNKt8%3D'\n ],\n [\n \"PUT /t1234/put\\r\\nHost: s3.amazonaws.com\\r\\n\\r\\n\",\n 'http://s3.amazonaws.com/t1234/put?AWSAccessKeyId=foo&Expires=1397952000&Signature=X5F%2FUBPes8Fc6vr%2Bl%2FQ5ltmKxc0%3D'\n ],\n [\n \"PUT /t1234/put\\r\\nContent-Type: foo\\r\\nHost: s3.amazonaws.com\\r\\n\\r\\n\",\n 'http://s3.amazonaws.com/t1234/put?AWSAccessKeyId=foo&Expires=1397952000&Signature=cAUmoCjwcyKXjY2ilsGX7ghlHUI%3D'\n ],\n [\n \"HEAD /test\\r\\nHost: test.s3.amazonaws.com\\r\\n\\r\\n\",\n 'http://test.s3.amazonaws.com/test?AWSAccessKeyId=foo&Expires=1397952000&Signature=1DQjgb9HhOH91oLFbwX8wze1tGs%3D'\n ],\n ];\n }\n\n /**\n * @dataProvider presignedUrlProvider\n */\n public function testCreatesPresignedUrls($message, $url)\n {\n $dt = 'April 20, 2014';\n $creds = new Credentials('foo', 'bar');\n $signature = new S3Signature();\n $req = (new MessageFactory())->fromMessage($message);\n // Try with string\n $res = $signature->createPresignedUrl($req, $creds, $dt);\n $this->assertSame($url, $res);\n // Try with timestamp\n $res = $signature->createPresignedUrl($req, $creds, new \\DateTime($dt));\n $this->assertSame($url, $res);\n }\n\n public function signatureDataProvider()\n {\n return [\n // Use two subresources to set the ACL of a specific version and\n // make sure subresources are sorted correctly\n [\n [\n 'verb' => 'PUT',\n 'path' => '/key?versionId=1234&acl=',\n 'headers' => [\n 'Host' => 'test.s3.amazonaws.com',\n 'Date' => 'Tue, 27 Mar 2007 21:06:08 +0000',\n 'Content-Length' => '15'\n ]\n ],\n \"PUT\\n\\n\\nTue, 27 Mar 2007 21:06:08 +0000\\n/test/key?acl&versionId=1234\"\n ],\n // DELETE a path hosted object with a folder prefix and custom headers\n [\n [\n 'verb' => 'DELETE',\n 'path' => '/johnsmith/photos/puppy.jpg',\n 'headers' => [\n 'User-Agent' => 'dotnet',\n 'Host' => 's3.amazonaws.com',\n 'x-amz-date' => 'Tue, 27 Mar 2007 21:20:26 +0000'\n ]\n ], \"DELETE\\n\\n\\n\\nx-amz-date:Tue, 27 Mar 2007 21:20:26 +0000\\n/johnsmith/photos/puppy.jpg\"\n ],\n // List buckets\n [\n [\n 'verb' => 'GET',\n 'path' => '/',\n 'headers' => [\n 'Host' => 's3.amazonaws.com',\n 'Date' => 'Wed, 28 Mar 2007 01:29:59 +0000'\n ]\n ], \"GET\\n\\n\\nWed, 28 Mar 2007 01:29:59 +0000\\n/\"\n ],\n // GET the ACL of a virtual hosted bucket\n [\n [\n 'verb' => 'GET',\n 'path' => '/?acl=',\n 'headers' => [\n 'Host' => 'johnsmith.s3.amazonaws.com',\n 'Date' => 'Tue, 27 Mar 2007 19:44:46 +0000'\n ]\n ], \"GET\\n\\n\\nTue, 27 Mar 2007 19:44:46 +0000\\n/johnsmith/?acl\"\n ],\n // GET the contents of a bucket using parameters\n [\n [\n 'verb' => 'GET',\n 'path' => '/?prefix=photos&max-keys=50&marker=puppy',\n 'headers' => [\n 'User-Agent' => 'Mozilla/5.0',\n 'Host' => 'johnsmith.s3.amazonaws.com',\n 'Date' => 'Tue, 27 Mar 2007 19:42:41 +0000'\n ]\n ], \"GET\\n\\n\\nTue, 27 Mar 2007 19:42:41 +0000\\n/johnsmith/\"\n ],\n // PUT an object with a folder prefix from a virtual hosted bucket\n [\n [\n 'verb' => 'PUT',\n 'path' => '/photos/puppy.jpg',\n 'headers' => [\n 'Content-Type' => 'image/jpeg',\n 'Content-Length' => '94328',\n 'Host' => 'johnsmith.s3.amazonaws.com',\n 'Date' => 'Tue, 27 Mar 2007 21:15:45 +0000'\n ]\n ], \"PUT\\n\\nimage/jpeg\\nTue, 27 Mar 2007 21:15:45 +0000\\n/johnsmith/photos/puppy.jpg\"\n ],\n // GET an object with a folder prefix from a virtual hosted bucket\n [\n [\n 'verb' => 'GET',\n 'path' => '/photos/puppy.jpg',\n 'headers' => [\n 'Host' => 'johnsmith.s3.amazonaws.com',\n 'Date' => 'Tue, 27 Mar 2007 19:36:42 +0000'\n ]\n ], \"GET\\n\\n\\nTue, 27 Mar 2007 19:36:42 +0000\\n/johnsmith/photos/puppy.jpg\"\n ],\n // Set the ACL of an object\n [\n [\n 'verb' => 'PUT',\n 'path' => '/photos/puppy.jpg?acl=',\n 'headers' => [\n 'Host' => 'johnsmith.s3.amazonaws.com',\n 'Date' => 'Tue, 27 Mar 2007 19:36:42 +0000'\n ]\n ], \"PUT\\n\\n\\nTue, 27 Mar 2007 19:36:42 +0000\\n/johnsmith/photos/puppy.jpg?acl\"\n ],\n // Set the ACL of an object with no prefix\n [\n [\n 'verb' => 'PUT',\n 'path' => '/photos/puppy?acl=',\n 'headers' => [\n 'Host' => 'johnsmith.s3.amazonaws.com',\n 'Date' => 'Tue, 27 Mar 2007 19:36:42 +0000'\n ]\n ], \"PUT\\n\\n\\nTue, 27 Mar 2007 19:36:42 +0000\\n/johnsmith/photos/puppy?acl\"\n ],\n // Set the ACL of an object with no prefix in a path hosted bucket\n [\n [\n 'verb' => 'PUT',\n 'path' => '/johnsmith/photos/puppy?acl=',\n 'headers' => [\n 'Host' => 's3.amazonaws.com',\n 'Date' => 'Tue, 27 Mar 2007 19:36:42 +0000'\n ]\n ], \"PUT\\n\\n\\nTue, 27 Mar 2007 19:36:42 +0000\\n/johnsmith/photos/puppy?acl\"\n ],\n // Set the ACL of a path hosted bucket\n [\n [\n 'verb' => 'PUT',\n 'path' => '/johnsmith?acl=',\n 'headers' => [\n 'Host' => 's3.amazonaws.com',\n 'Date' => 'Tue, 27 Mar 2007 19:36:42 +0000'\n ]\n ], \"PUT\\n\\n\\nTue, 27 Mar 2007 19:36:42 +0000\\n/johnsmith?acl\"\n ],\n // Set the ACL of a path hosted bucket with an erroneous path value\n [\n [\n 'verb' => 'PUT',\n 'path' => '/johnsmith?acl=',\n 'headers' => [\n 'Host' => 's3.amazonaws.com',\n 'Date' => 'Tue, 27 Mar 2007 19:36:42 +0000'\n ],\n ], \"PUT\\n\\n\\nTue, 27 Mar 2007 19:36:42 +0000\\n/johnsmith?acl\"\n ],\n // Send a request to the EU region\n [\n [\n 'verb' => 'GET',\n 'path' => '/johnsmith',\n 'headers' => [\n 'Host' => 'test.s3-eu-west-1.amazonaws.com',\n 'Date' => 'Tue, 27 Mar 2007 19:36:42 +0000'\n ],\n ], \"GET\\n\\n\\nTue, 27 Mar 2007 19:36:42 +0000\\n/test/johnsmith\"\n ],\n // Use a bucket with hyphens and a region\n [\n [\n 'verb' => 'GET',\n 'path' => '/bar',\n 'headers' => [\n 'Host' => 'foo-s3-test-bucket.s3-eu-west-1.amazonaws.com',\n 'Date' => 'Tue, 27 Mar 2007 19:36:42 +0000'\n ],\n ], \"GET\\n\\n\\nTue, 27 Mar 2007 19:36:42 +0000\\n/foo-s3-test-bucket/bar\"\n ],\n // Use a bucket with hyphens and the default region\n [\n [\n 'verb' => 'GET',\n 'path' => '/bar',\n 'headers' => [\n 'Host' => 'foo-s3-test-bucket.s3.amazonaws.com',\n 'Date' => 'Tue, 27 Mar 2007 19:36:42 +0000'\n ],\n ], \"GET\\n\\n\\nTue, 27 Mar 2007 19:36:42 +0000\\n/foo-s3-test-bucket/bar\"\n ],\n [\n [\n 'verb' => 'GET',\n 'path' => '/',\n 'headers' => [\n 'Host' => 'foo.s3.amazonaws.com',\n 'Date' => 'Tue, 27 Mar 2007 19:36:42 +0000'\n ],\n ], \"GET\\n\\n\\nTue, 27 Mar 2007 19:36:42 +0000\\n/foo/\"\n ],\n [\n [\n 'verb' => 'GET',\n 'path' => '/foo',\n 'headers' => [\n 'Host' => 's3.amazonaws.com',\n 'Date' => 'Tue, 27 Mar 2007 19:36:42 +0000'\n ],\n ], \"GET\\n\\n\\nTue, 27 Mar 2007 19:36:42 +0000\\n/foo\"\n ],\n ];\n }\n\n /**\n * @dataProvider signatureDataProvider\n */\n public function testCreatesCanonicalizedString(\n $input,\n $result,\n $expires = null\n ) {\n $signature = new S3Signature();\n $meth = new \\ReflectionMethod($signature, 'createCanonicalizedString');\n $meth->setAccessible(true);\n\n $request = (new MessageFactory())->createRequest(\n $input['verb'],\n 'http://' . $input['headers']['Host'] . $input['path'],\n ['headers' => $input['headers']]\n );\n\n $this->assertEquals(\n $result,\n $meth->invoke($signature, $request, $expires)\n );\n }\n\n public function testCreatesPreSignedUrlWithXAmzHeaders()\n {\n $signature = new S3Signature();\n $meth = new \\ReflectionMethod($signature, 'createCanonicalizedString');\n $meth->setAccessible(true);\n\n $request = new Request('GET', 'https://s3.amazonaws.com', [\n 'X-Amz-Acl' => 'public-read',\n 'X-Amz-Foo' => 'bar'\n ]);\n\n $this->assertContains(\n 'x-amz-acl:public-read',\n $meth->invoke($signature, $request, time())\n );\n\n $result = $signature->createPresignedUrl(\n $request,\n new Credentials('foo', 'bar', 'baz'),\n time()\n );\n\n $this->assertContains('&x-amz-acl=public-read', $result);\n $this->assertContains('x-amz-foo=bar', $result);\n }\n}\n" }, { "alpha_fraction": 0.5381295084953308, "alphanum_fraction": 0.5387461185455322, "avg_line_length": 26.95977020263672, "blob_id": "5940ba7b846ef46f0484f39441f76280bbfa462b", "content_id": "96bf3844b8a7971964fd7bebf12aa4495e7ba1e4", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4865, "license_type": "permissive", "max_line_length": 80, "num_lines": 174, "path": "/src/ResultPaginator.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws;\n\nuse GuzzleHttp\\Event\\ListenerAttacherTrait;\nuse transducers as t;\n\n/**\n * Iterator that yields each page of results of a pageable operation.\n */\nclass ResultPaginator implements \\Iterator\n{\n use ListenerAttacherTrait;\n\n /** @var AwsClientInterface Client performing operations. */\n private $client;\n\n /** @var string Name of the operation being paginated. */\n private $operation;\n\n /** @var array Args for the operation. */\n private $args;\n\n /** @var array Configuration for the paginator. */\n private $config;\n\n /** @var Result Most recent result from the client. */\n private $result;\n\n /** @var string|array Next token to use for pagination. */\n private $nextToken;\n\n /** @var int Number of operations/requests performed. */\n private $requestCount = 0;\n\n /** @var array Event listeners. */\n private $listeners;\n\n /**\n * @param AwsClientInterface $client\n * @param string $operation\n * @param array $args\n * @param array $config\n */\n public function __construct(\n AwsClientInterface $client,\n $operation,\n array $args,\n array $config\n ) {\n $this->client = $client;\n $this->operation = $operation;\n $this->args = $args;\n $this->config = $config;\n $this->listeners = $this->prepareListeners(\n $config,\n ['prepared', 'process', 'error']\n );\n }\n\n /**\n * Returns an iterator that iterates over the values of applying a JMESPath\n * search to each result yielded by the iterator as a flat sequence.\n *\n * @param string $expression JMESPath expression to apply to each result.\n * @param int|null $limit Total number of items that should be returned\n * or null for no limit.\n *\n * @return \\Iterator\n */\n public function search($expression, $limit = null)\n {\n // Apply JMESPath expression on each result, but as a flat sequence.\n $xf = t\\mapcat(function (Result $result) use ($expression) {\n return (array) $result->search($expression);\n });\n\n // Apply a limit to the total items returned.\n if ($limit) {\n $xf = t\\comp($xf, t\\take($limit));\n }\n\n // Return items as an iterator.\n return t\\to_iter($this, $xf);\n }\n\n /**\n * @return Result\n */\n public function current()\n {\n return $this->valid() ? $this->result : false;\n }\n\n public function key()\n {\n return $this->valid() ? $this->requestCount - 1 : null;\n }\n\n public function next()\n {\n $this->getNext();\n }\n\n public function valid()\n {\n return (bool) $this->result;\n }\n\n public function rewind()\n {\n $this->requestCount = 0;\n $this->nextToken = null;\n $this->next();\n }\n\n /**\n * Loads the next result by executing another command using the next token.\n */\n private function loadNextResult()\n {\n // Create the command\n $args = $this->args;\n $command = $this->client->getCommand($this->operation, $args);\n $this->attachListeners($command, $this->listeners);\n\n // Set the next token\n if ($this->nextToken) {\n $inputArg = $this->config['input_token'];\n if (is_array($this->nextToken) && is_array($inputArg)) {\n foreach ($inputArg as $index => $arg) {\n $command[$arg] = $this->nextToken[$index];\n }\n } else {\n $command[$inputArg] = $this->nextToken;\n }\n }\n\n // Get the next result\n $this->result = $this->client->execute($command);\n $this->requestCount++;\n $this->nextToken = null;\n\n // If there is no more_results to check or more_results is true\n if ($this->config['more_results'] === null\n || $this->result->search($this->config['more_results'])\n ) {\n // Get the next token's value\n if ($key = $this->config['output_token']) {\n if (is_array($key)) {\n $this->nextToken = $this->result->search(json_encode($key));\n $this->nextToken = array_filter($this->nextToken);\n } else {\n $this->nextToken = $this->result->search($key);\n }\n }\n }\n }\n\n /**\n * Fetch the next result for the command managed by the paginator.\n *\n * @return Result|null\n */\n private function getNext()\n {\n $this->result = null;\n // Load next result if there's a next token or it's the first request.\n if (!$this->requestCount || $this->nextToken) {\n $this->loadNextResult();\n }\n\n return $this->result;\n }\n}\n" }, { "alpha_fraction": 0.6715781092643738, "alphanum_fraction": 0.6772685647010803, "avg_line_length": 38.68144989013672, "blob_id": "0a4ec56bcd12a0f8e6af83c2d350643228560e04", "content_id": "23c7356e482475d5ca188c6ae25a6cb7b17f0cb9", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 9841, "license_type": "permissive", "max_line_length": 109, "num_lines": 248, "path": "/docs/basic-usage.rst", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "===============\nBasic SDK Usage\n===============\n\nThis guide focuses on basic usage patterns of the **AWS SDK for PHP**. This\nguide assumes that you have already :doc:`downloaded and installed the SDK\n<installation>` and retrieved your `AWS access keys\n<http://aws.amazon.com/developers/access-keys/>`_.\n\n\nIncluding the SDK\n-----------------\n\nNo matter which technique you have used to to install the SDK, you can include\nthe SDK into your code with just a single ``require`` statement. Please refer to\nthe following table for the PHP code that best fits your installation technique.\nPlease replace any instances of ``/path/to/`` with the actual path on your system.\n\n========================== =====================================================\nInstallation Technique Require Statement\n========================== =====================================================\nUsing Composer ``require '/path/to/vendor/autoload.php';``\n-------------------------- -----------------------------------------------------\nUsing the Phar ``require '/path/to/aws.phar';``\n-------------------------- -----------------------------------------------------\nUsing the Zip ``require '/path/to/aws-autoloader.php';``\n========================== =====================================================\n\nFor the remainder of this guide, we will show examples that assume the Composer\ninstallation method. If you are using a different installation method, then you\ncan refer back to this section to substitute in the proper ``require`` code.\n\n\nUsage Summary\n-------------\n\nThe basic usage pattern of the SDK is that you instantiate a **Client** object\nfor the AWS service you want to interact with. Client objects have methods that\ncorrespond one-to-one with operations in the service's API. To execute a\nparticular operation, you call its corresponding method, which either returns an\narray-like **Result** object on success, or throws an **Exception** on failure.\n\n\nCreating a client\n-----------------\n\nYou can create a client by passing an associative array of options to a\nclient's constructor.\n\n.. code-block:: php\n\n <?php\n // Include the SDK using the Composer autoloader\n require 'vendor/autoload.php';\n\n $s3 = new Aws\\S3\\S3Client([\n 'version' => 'latest',\n 'region' => 'us-west-2'\n ]);\n\nNotice that we did **not** explicitly provide credentials to the client. That's\nbecause the credentials should be detected by the SDK from either\n:ref:`environment variables <environment_credentials>` (via\n``AWS_ACCESS_KEY_ID`` and ``AWS_SECRET_ACCESS_KEY``), an\n:ref:`AWS credentials INI file <credential_profiles>` in your HOME\ndirectory, AWS Identity and Access Management (IAM)\n:ref:`instance profile credentials <instance_profile_credentials>`, or\n:ref:`credential providers <credential_provider>`. If needed, you can also\nexplicitly set your credentials by passing the ``key`` and ``secret`` (and\n``token``, if using temporary credentials) key-value pairs in the\n``credentials`` client configuration setting array. We recommend against\nhardcoding credentials into your application code for your own security.\n\nAll of the general client configuration options are described in detail in\nthe :doc:`configuration guide <configuration>`. The array of options provided\nto a client may vary based on which client you are creating. These custom\nclient configuration options are described in the\n`API documentation <http://docs.aws.amazon.com/aws-sdk-php/latest/>`_ of each\nclient.\n\n\nUsing the Sdk class\n-------------------\n\nThe ``Aws\\Sdk`` class is used to manage shared configuration options across\nmultiple clients. For example, the ``Aws\\Sdk`` class will automatically ensure\nthat each client it creates shares the same RingPHP adapter, allowing the\nclients to send asynchronous requests concurrently, even to different services.\n\nThe same options that can be provided to a specific client constructor can also\nbe supplied to the ``Aws\\Sdk`` class. These options are then applied to each\nclient constructor.\n\n.. code-block:: php\n\n // Use the us-west-2 region and latest version of each client.\n $sharedConfig = [\n 'region' => 'us-west-2',\n 'version' => 'latest'\n ];\n\n // Create an SDK class used to share configuration across clients.\n $sdk = new Aws\\Sdk($sharedConfig);\n\n // Create an Amazon S3 client using the shared configuration data.\n $client = $sdk->createS3();\n\nOptions that are shared across all clients are placed in root-level key-value\npairs. Service-specific configuration data can be provided in a key that is the\nnamespace of a service (e.g., \"S3\", \"DynamoDb\", etc.).\n\n.. code-block:: php\n\n $sdk = new Aws\\Sdk([\n 'region' => 'us-west-2',\n 'version' => 'latest',\n 'DynamoDb' => [\n 'region' => 'eu-central-1'\n ]\n ]);\n\n // Creating a DynamoDb client will use the \"eu-central-1\" region.\n $client = $sdk->createDynamoDb();\n\nService-specific configuration values are a union of the service-specific\nvalues and the root-level values (i.e., service-specific values are shallow\nmerged onto root level values).\n\n\nExecuting service operations\n----------------------------\n\nYou can execute a service operation by calling the method of the same name on\na client object. For example, to perform the Amazon S3 `PutObject operation\n<http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html>`_, you must\ncall the ``Aws\\S3\\S3Client::putObject()`` method.\n\n.. code-block:: php\n\n // Use an Aws\\Sdk class to create the S3Client object.\n $s3 = $sdk->createS3();\n\n // Send a PutObject request and get the result object.\n $result = $s3Client->putObject([\n 'Bucket' => 'my-bucket',\n 'Key' => 'my-key',\n 'Body' => 'this is the body!'\n ]);\n\n // Download the contents of the object.\n $result = $s3Client->getObject([\n 'Bucket' => 'my-bucket',\n 'Key' => 'my-key'\n ]);\n\n // Print the body of the result by indexing into the result object.\n echo $result['Body'];\n\nOperations available to a client and the structure of the input and output are\ndefined at runtime based on a service description file. When creating a client,\nyou must provide a version (e.g., `\"2006-03-01\"` or `\"latest\"`). The SDK will\nfind the corresponding configuration file based on the provided version.\nOperations methods like ``putObject()`` all accept a single argument that is an\nassociative array of values representing the parameters to the operation. The\nstructure of this array (and the structure of the result object) is defined for\neach operation in the SDK's API Documentation (e.g., see the API docs for\n`putObject operation <http://docs.aws.amazon.com/aws-sdk-php/v3/api/Aws/S3/s3-2006-03-01.html#putObject>`__).\n\nYou can send requests concurrently and utilize the command event system by\nusing a command object. Please refer to the :doc:`command object guide\n<commands>` for more information.\n\n\nWorking with Result objects\n---------------------------\n\nExecuting an successful operation return an ``Aws\\Result`` object. Instead of\nreturning the raw XML or JSON data of a service, the SDK coerces the response\ndata into an associative array structure and normalizes some aspects of the data\nbased on its knowledge of the specific service and the underlying response\nstructure.\n\nYou can access data from the result object like an associative PHP array.\n\n.. code-block:: php\n\n // Use an Aws\\Sdk class to create the S3Client object.\n $s3 = $sdk->createS3();\n $result = $s3->listBuckets();\n\n foreach ($result['Buckets'] as $bucket) {\n echo $bucket['Name'] . \"\\n\";\n }\n\n // Convert the result object to a PHP array\n $asArray = $result->toArray();\n\nThe contents of the result object depends on the operation that was executed\nand the version of a service. The result structure of each API operation is\ndocumented in the API docs for each operation (e.g., see the *Results* section\nin the API docs for each operation.\n\nThe SDK is integrated with `JMESPath <http://jmespath.org/>`_, a `DSL\n<http://en.wikipedia.org/wiki/Domain-specific_language>`_ use to search and\nmanipulate JSON data, or PHP arrays, in our case. The result object contains a\n``search()`` method that allows you to more declaratively extract data from the\nresult.\n\n.. code-block:: php\n\n $s3 = $sdk->createS3();\n $result = $s3Client->listBuckets();\n // Get the name of each bucket\n $results = $result->search('Buckets[*].Name');\n\n\nHandling errors\n---------------\n\nThe return value of performing an operation is an ``Aws\\Result`` object. If an\nerror occurs while performing an operation, then an exception is thrown. For\nthis reason, you should use ``try``/``catch`` blocks around your operations if\nyou need to handle errors in your code. The SDK throws service-specific\nexceptions when an error occurs.\n\nIn the following example, the ``Aws\\S3\\S3Client`` is used. If there is an\nerror, the exception thrown will be of the type ``Aws\\S3\\Exception\\S3Exception``.\nAll service specific exceptions thrown by the SDK extend from the\n``Aws\\Exception\\AwsException`` class. This class contains useful information\nabout the failure, including the request-id, error code, and error type.\n\n.. code-block:: php\n\n use Aws\\Exception\\AwsException;\n use Aws\\S3\\Exception\\S3Exception;\n\n try {\n $s3Client->createBucket(['Bucket' => 'my-bucket']);\n } catch (S3Exception $e) {\n // Catch an S3 specific exception.\n echo $e->getMessage();\n } catch (AwsException $e) {\n // This catches the more generic AwsException. You can grab information\n // from the exception using methods of the exception object.\n echo $e->getAwsRequestId() . \"\\n\";\n echo $e->getAwsErrorType() . \"\\n\";\n echo $e->getAwsErrorCode() . \"\\n\"\n }\n" }, { "alpha_fraction": 0.618969738483429, "alphanum_fraction": 0.6287816762924194, "avg_line_length": 29.575000762939453, "blob_id": "c70b55734eb974da59f56bf897f3418b282ae74c", "content_id": "d2949727198000b62d48b3cc3c80931e990abd13", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1223, "license_type": "permissive", "max_line_length": 116, "num_lines": 40, "path": "/tests/S3/PermanentRedirectSubscriberTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\S3\\Subscriber;\n\nuse Aws\\Test\\UsesServiceTrait;\nuse GuzzleHttp\\Client;\nuse GuzzleHttp\\Event\\BeforeEvent;\nuse GuzzleHttp\\Message\\Response;\n\n/**\n * @covers Aws\\S3\\PermanentRedirectSubscriber\n */\nclass PermanentRedirectTest extends \\PHPUnit_Framework_TestCase\n{\n use UsesServiceTrait;\n\n /**\n * @expectedException \\Aws\\S3\\Exception\\PermanentRedirectException\n * @expectedExceptionMessage Encountered a permanent redirect while requesting https://test.s3.amazonaws.com/key\n */\n public function testThrowsSpecificException()\n {\n $http = new Client();\n $http->getEmitter()->on('before', function (BeforeEvent $e) {\n $e->intercept(new Response(301));\n });\n\n $client = $this->getTestClient('s3', ['client' => $http]);\n $client->getObject(['Bucket' => 'test', 'Key' => 'key']);\n }\n\n public function testPassesThroughUntouched()\n {\n $http = new Client();\n $http->getEmitter()->on('before', function (BeforeEvent $e) {\n $e->intercept(new Response(200));\n });\n $client = $this->getTestClient('s3', ['client' => $http]);\n $client->getObject(['Bucket' => 'test', 'Key' => 'key']);\n }\n}\n" }, { "alpha_fraction": 0.68831866979599, "alphanum_fraction": 0.6966394782066345, "avg_line_length": 34.14717102050781, "blob_id": "31e07bd24df669a82736706fa9ac4b26b1f0b5bd", "content_id": "63ea58b124565eeb82bd58c74983f2de0fa02c75", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 18628, "license_type": "permissive", "max_line_length": 137, "num_lines": 530, "path": "/docs/credentials.rst", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "===========\nCredentials\n===========\n\nIn order to authenticate requests, AWS services require you to provide your\n`AWS access keys <http://aws.amazon.com/developers/access-keys/>`_, also known\nas your AWS **access key ID** and **secret access key**. In the AWS SDK for\nPHP, these access keys are often referred to collectively as your\n**credentials**. This guide demonstrates how to provide your credentials to the\nAWS SDK for SDK using one of the following methods:\n\n#. :ref:`environment_credentials`\n#. :ref:`instance_profile_credentials`\n#. :ref:`credential_profiles`\n#. :ref:`hardcoded_credentials`\n#. :ref:`credential_provider`\n#. :ref:`temporary_credentials`\n\nIn general, it is recommended that you use IAM roles when running your\napplication on Amazon EC2 and use credential profiles or environment variables\nelsewhere. Regardless of how you supply credentials to the SDK, it is encouraged that\nyou follow the `IAM Best Practices <http://docs.aws.amazon.com/IAM/latest/UserGuide/IAMBestPractices.html>`_\nwhen managing your credentials.\n\n\n.. _environment_credentials:\n\nUsing credentials from environment variables\n--------------------------------------------\n\nIf you do not provide credentials to a client object at the time of its\ninstantiation, the SDK will attempt to find credentials in your environment.\nThe first place the SDK will check for credentials is in your environment\nvariables. The SDK will use the ``getenv()`` function function to look for the\n``AWS_ACCESS_KEY_ID``, ``AWS_SECRET_ACCESS_KEY``, and ``AWS_SESSION_TOKEN``\nenvironment variables. These credentials are referred to as\n**environment credentials**.\n\n\n.. _instance_profile_credentials:\n\nUsing IAM roles for Amazon EC2 instances\n----------------------------------------\n\n*Using IAM roles is the preferred technique for providing credentials to\napplications running on Amazon EC2.* IAM roles remove the need to worry about\ncredential management from your application. They allow an instance to \"assume\"\na role by retrieving temporary credentials from the EC2 instance's metadata\nserver. These temporary credentials, often referred to as\n**instance profile credentials**, allow access to the actions and resources\nthat the role's policy allows.\n\nWhen launching an EC2 instance, you can choose to associate it with an IAM\nrole. Any application running on that EC2 instance is then allowed to assume\nthe associated role. Amazon EC2 handles all the legwork of securely\nauthenticating instances to the IAM service to assume the role and periodically\nrefreshing the retrieved role credentials, keeping your application secure with\nalmost no work on your part.\n\nIf you do not explicitly provide credentials to the client object and no\nenvironment variable credentials are available, the SDK attempts to retrieve\ninstance profile credentials from an Amazon EC2 instance metadata server. These\ncredentials are available only when running on Amazon EC2 instances that have\nbeen configured with an IAM role.\n\n.. note::\n\n Instance profile credentials and other temporary credentials generated by\n the AWS Security Token Service (AWS STS) are not supported by every\n service. Please check if the service you are using supports temporary\n credentials by reading `AWS Services that Support AWS STS <http://docs.aws.amazon.com/STS/latest/UsingSTS/UsingTokens.html>`_.\n\nFor more information, see `IAM Roles for Amazon EC2 <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_.\n\n\n.. _credential_profiles:\n\nUsing the AWS credentials file and credential profiles\n------------------------------------------------------\n\nStarting with the AWS SDK for PHP version 2.6.2, you can use an AWS credentials\nfile to specify your credentials. This is a special, INI-formatted file stored\nunder your HOME directory, and is a good way to manage credentials for your\ndevelopment environment. The file should be placed at ``~/.aws/credentials``,\nwhere ``~`` represents your HOME directory.\n\nUsing an AWS credentials file offers a few benefits:\n\n1. Your projects' credentials are stored outside of your projects, so there is\n no chance of accidentally committing them into version control.\n2. You can define and name multiple sets of credentials in one place.\n3. You can easily reuse the same credentials between projects.\n4. Other AWS SDKs and tools support, or will soon support, this same\n credentials file. This allows you to reuse your credentials with other\n tools.\n\nThe format of the AWS credentials file should look something like the\nfollowing:\n\n.. code-block:: ini\n\n [default]\n aws_access_key_id = YOUR_AWS_ACCESS_KEY_ID\n aws_secret_access_key = YOUR_AWS_SECRET_ACCESS_KEY\n\n [project1]\n aws_access_key_id = ANOTHER_AWS_ACCESS_KEY_ID\n aws_secret_access_key = ANOTHER_AWS_SECRET_ACCESS_KEY\n\nEach section (e.g., ``[default]``, ``[project1]``), represents a separate\ncredential **profile**. Profiles can be referenced from a SDK configuration\nfile, or when you are instantiating a client, using the ``profile`` option:\n\n.. code-block:: php\n\n <?php\n\n use Aws\\DynamoDb\\DynamoDbClient;\n\n // Instantiate a client with the credentials from the project1 profile\n $client = new DynamoDbClient([\n 'profile' => 'project1',\n 'region' => 'us-west-2',\n 'version' => 'latest'\n ]);\n\nIf no credentials or profiles were explicitly provided to the SDK and no\ncredentials were defined in environment variables, but a credentials file is\ndefined, the SDK will use the \"default\" profile. You can change the default\nprofile by specifying an alternate profile name in the ``AWS_PROFILE``\nenvironment variable.\n\n\n.. _hardcoded_credentials:\n\nUsing hard-coded credentials\n----------------------------\n\nYou can provide hard-coded credentials to a SDK client by providing the \"key\",\n\"secret\", and optional \"token\" key value pairs to the \"credentials\" option of\na client constructor.\n\n.. code-block:: php\n\n $s3Client = new S3Client([\n 'version' => 'latest',\n 'region' => 'us-west-2',\n 'credentials' => [\n 'key' => 'my-access-key-id',\n 'secret' => 'my-secret-access-key',\n ],\n ]);\n\n.. warning::\n\n Hard-coding your credentials can be dangerous, because it is easy to\n accidentally commit your credentials into an SCM repository, potentially\n exposing your credentials to more people than intended. It can also make it\n difficult to rotate credentials in the future.\n\n\n.. _credential_provider:\n\nUsing a credential provider\n---------------------------\n\nA credential provider is a function that returns ``NULL`` or an\n``Aws\\Credentials\\CredentialsInterface`` object. You can use credential\nproviders to implement your own custom logic for creating credentials.\n\nCredential providers are passed into the ``credentials`` client constructor\noption:\n\n.. code-block:: php\n\n use Aws\\Credentials\\CredentialProvider;\n use Aws\\S3\\S3Client;\n\n // Only allow environment variable credentials.\n $provider = CredentialProvider::env();\n\n // Pass the provider to the client.\n $client = new S3Client([\n 'region' => 'us-west-2',\n 'version' => '2006-03-01',\n 'credentials' => $provider\n ]);\n\nPassing in a credential provider function to a SDK client constructor will\ninvoke the provider and ensure that it returns an instance of\n``Aws\\Credentials\\CredentialsInterface``. If the provider does not return a\ncredential object, an ``Aws\\Exception\\UnresolvedCredentialsException`` is\nthrown.\n\nThe SDK ships with several built-in providers that can be combined together\nalong with any custom providers.\n\n\nenv provider\n~~~~~~~~~~~~\n\n``Aws\\Credentials\\CredentialProvider::env`` attempts to load credentials from\nenvironment variables.\n\n.. code-block:: php\n\n use Aws\\Credentials\\CredentialProvider;\n use Aws\\S3\\S3Client;\n\n $client = new S3Client([\n 'region' => 'us-west-2',\n 'version' => '2006-03-01',\n 'credentials' => CredentialProvider::env()\n ]);\n\n\nini provider\n~~~~~~~~~~~~\n\n``Aws\\Credentials\\CredentialProvider::ini`` attempts to load credentials from\nan :ref:`ini credential file <credential_profiles>`. The SDK will by default\nattempt to load the \"default\" profile from a file located at\n``~/.aws/credentials``.\n\n.. code-block:: php\n\n use Aws\\Credentials\\CredentialProvider;\n use Aws\\S3\\S3Client;\n\n $client = new S3Client([\n 'region' => 'us-west-2',\n 'version' => '2006-03-01',\n 'credentials' => CredentialProvider::ini()\n ]);\n\nYou can use a custom profile or ini file location by providing arguments to\nthe function that creates the provider.\n\n.. code-block:: php\n\n $profile = 'production';\n $path = '/full/path/to/credentials.ini';\n\n $client = new S3Client([\n 'region' => 'us-west-2',\n 'version' => '2006-03-01',\n 'credentials' => CredentialProvider::ini($profile, $path)\n ]);\n\n\ninstanceProfile provider\n~~~~~~~~~~~~~~~~~~~~~~~~\n\n``Aws\\Credentials\\CredentialProvider::instanceProfile`` attempts to load\ncredentials from Amazon EC2 instance profiles.\n\n.. code-block:: php\n\n use Aws\\Credentials\\CredentialProvider;\n use Aws\\S3\\S3Client;\n\n $client = new S3Client([\n 'region' => 'us-west-2',\n 'version' => '2006-03-01',\n 'credentials' => CredentialProvider::instanceProfile()\n ]);\n\n\ndefaultProvider provider\n~~~~~~~~~~~~~~~~~~~~~~~~\n\n``Aws\\Credentials\\CredentialProvider::defaultProvider`` is the default\ncredential provider. This provider is used if you omit a ``credentials`` option\nwhen creating a client. It first attempts to load credentials from environment\nvariables, then from an ini file, then from an instance profile.\n\n\nCreating a custom provider\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nCredential providers are simply functions that when invoked return either\n``NULL`` or an ``Aws\\Credentials\\CredentialsInterface`` object. A credential\nprovider should have the following logic:\n\n1. Return ``NULL`` if the provider is not capable of providing credentials\n given the arguments in which it was created.\n2. Throw an ``Aws\\Exception\\CredentialsException`` if the provider encounters\n an exceptional situation (e.g., a corrupted file, an invalid format, etc.).\n3. Return an instance of ``Aws\\Credentials\\CredentialsInterface`` if the\n provider is able to provide credentials.\n\nA best practice for creating providers is to create a function that is invoked\nto create a credential provider. As an example, here's the source of the\n``env`` provider:\n\n.. code-block:: php\n\n // This function CREATES a credential provider.\n public static function env()\n {\n // This function IS the credential provider.\n return function () {\n // Use credentials from environment variables, if available\n $key = getenv(self::ENV_KEY);\n $secret = getenv(self::ENV_SECRET);\n return $key && $secret\n ? new Credentials($key, $secret, getenv(self::ENV_SESSION))\n : null;\n };\n }\n\n\nChaining providers\n~~~~~~~~~~~~~~~~~~\n\nCredential providers can be chained using the ``Aws\\Utils::orFn()`` function.\nThis function accepts a variadic number of arguments, each of which are\ncredential provider functions. This function then returns a new function that\nis the composition of the provided functions such that they are invoked one\nafter the other until a function returns a non-null value.\n\nThe ``defaultProvider`` uses this composition in order to check multiple\nproviders before returning ``NULL``. The source of the ``defaultProvider``\ndemonstrates the use of the ``orFn``.\n\n.. code-block:: php\n\n // This function returns a provider.\n public static function defaultProvider(array $config = [])\n {\n // This function is the provider, which is actually the composition\n // of multiple providers.\n return Utils::orFn(\n self::env(),\n self::ini(),\n self::instanceProfile($config)\n );\n }\n\n\nRefreshable Credentials\n~~~~~~~~~~~~~~~~~~~~~~~\n\nSome credentials are only temporary and must be periodically refreshed. In\nfact, the instance profile credentials provided by the ``instanceProfile``\nprovider will create credentials that automatically refresh when they expire.\nUse the ``Aws\\Credentials\\RefreshableCredentials`` class if you need to create\na custom credential provider that returns temporary credentials that are\nautomatically refreshed.\n\nThe ``RefreshableCredentials`` class accepts a single argument in the\nconstructor: a credential provider. When instantiated, the\n``RefreshableCredentials`` class immediately invokes the provider and uses the\nprovided credentials. When the decorated credentials expire, the class will\nautomatically invoke the credential provider to retrieve new credentials.\n\n\nMemoizing Credentials\n~~~~~~~~~~~~~~~~~~~~~\n\nIt is sometimes necessary to create a credential provider that remembers the\nprevious return value. This can be useful when using the ``Aws\\Sdk`` class to\nshare a credential provider across multiple clients. You can add memoization to\na credential provider by wrapping the credential provider function in a\nmemoization function:\n\n.. code-block:: php\n\n use Aws\\Credentials\\CredentialProvider;\n\n $provider = CredentialProvider::instanceProfile();\n $provider = CredentialProvider::memoize($provider);\n\n // Pass the provider into the Sdk class and share the provider\n // across multiple clients. Each time a new client is constructed,\n // it will use the previously returned credentials as long as\n // they have not yet expired.\n $sdk = new Aws\\Sdk(['credentials' => $provider]);\n\n $s3 = $sdk->getS3(['region' => 'us-west-2', 'version' => 'latest']);\n $ec2 = $sdk->getEc2(['region' => 'us-west-2', 'version' => 'latest']);\n\n assert($s3->getCredentials() === $ec2->getCredentials());\n\n\n.. _temporary_credentials:\n\nUsing temporary credentials from AWS STS\n----------------------------------------\n\n`AWS Security Token Service <http://docs.aws.amazon.com/STS/latest/APIReference/Welcome.html>`_\n(AWS STS) enables you to request limited-privilege, **temporary credentials**\nfor AWS IAM users or for users that you authenticate via identity federation.\nOne common use case for using temporary credentials is to grant mobile or\nclient-side applications access to AWS resources by authenticating users\nthrough third-party identity providers (read more about `Web Identity Federation\n<http://docs.aws.amazon.com/STS/latest/UsingSTS/CreatingWIF.html>`_).\n\n.. note::\n\n Temporary credentials generated by AWS STS are not supported by every\n service. Please check if the service you are using supports temporary\n credentials by reading `AWS Services that Support AWS STS <http://docs.aws.amazon.com/STS/latest/UsingSTS/UsingTokens.html>`_.\n\n\nGetting temporary credentials\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nAWS STS has several operations that return temporary credentials, but the\n``GetSessionToken`` operation is the simplest for demonstration purposes.\nAssuming you have an instance of ``Aws\\Sts\\StsClient`` stored in the\n``$stsClient`` variable, this is how you call it:\n\n.. code-block:: php\n\n $result = $stsClient->getSessionToken();\n\nThe result for ``GetSessionToken`` and the other AWS STS operations always\ncontains a ``'Credentials'`` value. If you print the result\n(e.g., ``print_r($result)``), it looks like the following:\n\n::\n\n Array\n (\n ...\n [Credentials] => Array\n (\n [SessionToken] => '<base64 encoded session token value>'\n [SecretAccessKey] => '<temporary secret access key value>'\n [Expiration] => 2013-11-01T01:57:52Z\n [AccessKeyId] => '<temporary access key value>'\n )\n ...\n )\n\n\nProviding temporary credentials to the SDK\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nYou can use temporary credentials with another AWS client by instantiating\nthe client and passing in the values received from AWS STS directly.\n\n.. code-block:: php\n\n use Aws\\S3\\S3Client;\n\n $result = $stsClient->getSessionToken();\n\n $s3Client = new S3Client([\n 'version' => '2006-03-01',\n 'region' => 'us-west-2',\n 'credentials' => [\n 'key' => $result['Credentials']['AccessKeyId'],\n 'secret' => $result['Credentials']['SecretAccessKey'],\n 'token' => $result['Credentials']['SessionToken']\n ]\n ]);\n\nYou can also construct a ``Aws\\Credentials\\Credentials`` object and use that\nwhen instantiating the client.\n\n.. code-block:: php\n\n use Aws\\Credentials\\Credentials;\n use Aws\\S3\\S3Client;\n\n $result = $stsClient->getSessionToken();\n\n $credentials = new Credentials(\n $result['Credentials']['AccessKeyId'],\n $result['Credentials']['SecretAccessKey'],\n $result['Credentials']['SessionToken']\n );\n\n $s3Client = new S3Client([\n 'version' => '2006-03-01',\n 'region' => 'us-west-2',\n 'credentials' => $credentials\n ]);\n\nHowever, the *best* way to provide temporary credentials is to use the\n``createCredentials()`` helper method included with the ``StsClient``. This\nmethod extracts the data from an AWS STS result and creates the ``Credentials``\nobject for you.\n\n.. code-block:: php\n\n $result = $stsClient->getSessionToken();\n $credentials = $stsClient->createCredentials($result);\n\n $s3Client = new S3Client([\n 'version' => '2006-03-01',\n 'region' => 'us-west-2',\n 'credentials' => $credentials\n ]);\n\nFor more information about why you might need to use temporary credentials in\nyour application or project, see `Scenarios for Granting Temporary Access\n<http://docs.aws.amazon.com/STS/latest/UsingSTS/STSUseCases.html>`_ in the AWS\nSTS documentation.\n\n\n.. _anonymous_access:\n\nCreating Anonymous Clients\n--------------------------\n\nIn some cases, you may want to create a client that is not associated with any\ncredentials. This allows you to make anonymous requests to a service. For\nexample, both S3 Objects and CloudSearch Domains can be configured to allow\nanonymous access.\n\nTo create an anonymous client, you can set the ``'credentials'`` option to\n``false``.\n\n.. code-block:: php\n\n $s3Client = new S3Client([\n 'version' => 'latest',\n 'region' => 'us-west-2',\n 'credentials' => false\n ]);\n\n // Makes an anonymous request. The Object would need to be publicly\n // readable for this to succeed.\n $result = $s3Client->getObject([\n 'Bucket' => 'my-bucket',\n 'Key' => 'my-key',\n ]);\n" }, { "alpha_fraction": 0.5281661748886108, "alphanum_fraction": 0.5429484844207764, "avg_line_length": 32.37333297729492, "blob_id": "8e574c5083fd8b42065b476475edbafafad0bb87", "content_id": "0423ef4dfe754bf5d4df3104f04af84c99af9bd6", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2503, "license_type": "permissive", "max_line_length": 78, "num_lines": 75, "path": "/src/Glacier/ApplyChecksumsSubscriber.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Glacier;\n\nuse Aws\\Exception\\CouldNotCreateChecksumException;\nuse GuzzleHttp\\Command\\Event\\PreparedEvent;\nuse GuzzleHttp\\Event\\SubscriberInterface;\nuse GuzzleHttp\\Subscriber\\MessageIntegrity\\HashingStream;\nuse GuzzleHttp\\Subscriber\\MessageIntegrity\\PhpHash;\n\n/**\n * Adds the content sha256 and tree hash to Glacier upload requests if not set\n *\n * @internal\n */\nclass ApplyChecksumsSubscriber implements SubscriberInterface\n{\n public function getEvents()\n {\n return ['prepared' => ['onPrepared', 'last']];\n }\n\n /**\n * Update a command with the content and tree hash headers, as needed.\n *\n * @param PreparedEvent $event Event emitted.\n *\n * @throws \\RuntimeException if the body is not seekable.\n */\n public function onPrepared(PreparedEvent $event)\n {\n $command = $event->getCommand();\n $name = $command->getName();\n\n // Determine if there is a need to calculate any hashes.\n $needsHashes = ($name === 'UploadArchive' || $name === 'UploadPart')\n && (!$command['checksum'] || !$command['ContentSHA256']);\n\n if ($needsHashes) {\n $body = $event->getRequest()->getBody();\n if (!$body->isSeekable()) {\n throw new CouldNotCreateChecksumException('sha256');\n }\n\n // Add a tree hash if not provided.\n if (!$command['checksum']) {\n $body = new HashingStream($body, new TreeHash(),\n function ($result) use ($command, $event) {\n $event->getRequest()->setHeader(\n 'x-amz-sha256-tree-hash',\n bin2hex($result)\n );\n }\n );\n }\n\n // Add a linear content hash if not provided.\n if (!$command['ContentSHA256']) {\n $body = new HashingStream($body, new PhpHash('sha256'),\n function ($result) use ($command) {\n $command['ContentSHA256'] = bin2hex($result);\n }\n );\n }\n\n // Read the stream in order to calculate the hashes.\n while (!$body->eof()) $body->read(1048576);\n $body->seek(0);\n }\n\n // Set the content hash header if there is a value to set.\n if ($hash = $command['ContentSHA256']) {\n $event->getRequest()->addHeader('x-amz-content-sha256', $hash);\n }\n }\n}\n" }, { "alpha_fraction": 0.6711798906326294, "alphanum_fraction": 0.6756930947303772, "avg_line_length": 28.826923370361328, "blob_id": "620edd29d07cb2e60f616e738514208ba427fff2", "content_id": "24287f59696d62192e33b85b34cb4d611f50e91e", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1551, "license_type": "permissive", "max_line_length": 73, "num_lines": 52, "path": "/docs/conf.py", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "import sys, os, subprocess\nfrom sphinx.highlighting import lexers\nfrom pygments.lexers.web import PhpLexer\n\n\nlexers['php'] = PhpLexer(startinline=True, linenos=1)\nlexers['php-annotations'] = PhpLexer(startinline=True, linenos=1)\nprimary_domain = 'php'\n\nproject = u'AWS SDK for PHP'\ncopyright = u'2015, Amazon Web Services'\nmaster_doc = 'index'\n\nsys.path.append(os.path.abspath('_ext/'))\nextensions = ['aws']\n\ntemplates_path = ['_templates']\nsource_suffix = '.rst'\n\n# Parse the version from the latest git tag\nversion_command = 'git describe --abbrev=0 --tags'\ngit_verson = subprocess.check_output(version_command, shell=True)\nversion = os.getenv('VERSION', git_verson.strip())\n\nexclude_patterns = ['_build']\nhtml_static_path = ['_static']\n\n# -- HTML theme settings ------------------------------------------------\n\nhtml_show_sourcelink = False\nhtml_sidebars = {\n '**': ['sidebarlogo.html',\n 'localtoc.html',\n 'searchbox.html',\n 'feedback.html']\n}\n\nimport guzzle_sphinx_theme\nextensions.append(\"guzzle_sphinx_theme\")\nhtml_translator_class = 'guzzle_sphinx_theme.HTMLTranslator'\nhtml_theme_path = guzzle_sphinx_theme.html_theme_path()\nhtml_theme = 'guzzle_sphinx_theme'\n\n# Guzzle theme options (see theme.conf for more information)\nhtml_theme_options = {\n # hack to add tracking\n \"google_analytics_account\": os.getenv('TRACKING', False),\n \"project_nav_name\": \"AWS SDK for PHP\",\n \"github_user\": \"aws\",\n \"github_repo\": \"aws-sdk-php\",\n \"base_url\": \"http://docs.aws.amazon.com/aws-sdk-php/guide/latest/\"\n}\n" }, { "alpha_fraction": 0.5478261113166809, "alphanum_fraction": 0.5686956644058228, "avg_line_length": 22, "blob_id": "f373136f61fa527ff6d0180ca063b1f385a6ef85", "content_id": "00cb15f983bd02798541321890135affd6cf33bd", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 575, "license_type": "permissive", "max_line_length": 79, "num_lines": 25, "path": "/tests/Ec2/Ec2ClientTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Ec2;\n\nuse Aws\\Ec2\\CopySnapshotSubscriber;\nuse Aws\\Ec2\\Ec2Client;\n\n/**\n * @covers Aws\\Ec2\\Ec2Client\n */\nclass Ec2ClientTest extends \\PHPUnit_Framework_TestCase\n{\n public function testAddsSubscribers()\n {\n $ec2 = new Ec2Client([\n 'region' => 'us-east-1',\n 'version' => 'latest'\n ]);\n\n $this->assertNotEmpty(\n array_filter($ec2->getEmitter()->listeners('init'), function ($e) {\n return is_array($e) && $e[0] instanceof CopySnapshotSubscriber;\n })\n );\n }\n}\n" }, { "alpha_fraction": 0.6035616397857666, "alphanum_fraction": 0.6057534217834473, "avg_line_length": 32.181819915771484, "blob_id": "2f9ca716f0ebc4198d0fe587c23f788260050728", "content_id": "8afd41b346e80cfd5425d0ab44d7085a794fe26e", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3650, "license_type": "permissive", "max_line_length": 79, "num_lines": 110, "path": "/src/Sns/MessageValidator/MessageValidator.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Sns\\MessageValidator;\n\nuse Aws\\Sns\\Exception\\MessageValidatorException;\nuse GuzzleHttp\\Client;\nuse GuzzleHttp\\ClientInterface;\nuse GuzzleHttp\\Url;\n\n/**\n * This class uses openssl to verify SNS messages to ensure that they were sent\n * by AWS.\n */\nclass MessageValidator\n{\n /** @var ClientInterface The HTTP client used to fetch the certificate */\n protected $client;\n\n /**\n * Constructs the Message Validator object and ensures that openssl is\n * installed.\n *\n * @param ClientInterface $client Client used to fetch a certificate\n *\n * @throws \\RuntimeException If openssl is not installed\n */\n public function __construct(ClientInterface $client = null)\n {\n if (!extension_loaded('openssl')) {\n //@codeCoverageIgnoreStart\n throw new \\RuntimeException('The openssl extension is required to '\n . 'use the SNS message validator. Please install this '\n . 'extension in order to use this feature.');\n //@codeCoverageIgnoreEnd\n }\n\n $this->client = $client ?: new Client();\n }\n\n /**\n * Validates a message from SNS to ensure that it was delivered by AWS\n *\n * @param Message $message The message to validate\n *\n * @throws MessageValidatorException If the certificate cannot be\n * retrieved, if the certificate's source cannot be verified, or if the\n * message's signature is invalid.\n */\n public function validate(Message $message)\n {\n // Get and validate the URL for the certificate.\n $certUrl = Url::fromString($message->get('SigningCertURL'));\n $this->validateUrl($certUrl);\n\n // Get the cert itself and extract the public key\n $certificate = $this->client->get((string) $certUrl)->getBody();\n $key = openssl_get_publickey($certificate);\n if (!$key) {\n throw new MessageValidatorException('Cannot get the public key '\n . 'from the certificate.');\n }\n\n // Verify the signature of the message\n $content = $message->getStringToSign();\n $signature = base64_decode($message->get('Signature'));\n\n if (!openssl_verify($content, $signature, $key, OPENSSL_ALGO_SHA1)) {\n throw new MessageValidatorException('The message signature is '\n . 'invalid.');\n }\n }\n\n /**\n * Determines if a message is valid and that is was delivered by AWS. This\n * method does not throw exceptions and returns a simple boolean value.\n *\n * @param Message $message The message to validate\n *\n * @return bool\n */\n public function isValid(Message $message)\n {\n try {\n $this->validate($message);\n return true;\n } catch (MessageValidatorException $e) {\n return false;\n }\n }\n\n /**\n * Ensures that the url of the certificate is one belonging to AWS, and not\n * just something from the amazonaws domain, which includes S3 buckets.\n *\n * @param Url $url\n *\n * @throws MessageValidatorException if the cert url is invalid\n */\n private function validateUrl(Url $url)\n {\n // The cert URL must be https, a .pem, and match the following pattern.\n $hostPattern = '/^sns\\.[a-zA-Z0-9\\-]{3,}\\.amazonaws\\.com(\\.cn)?$/';\n if ($url->getScheme() !== 'https'\n || substr($url, -4) !== '.pem'\n || !preg_match($hostPattern, $url->getHost())\n ) {\n throw new MessageValidatorException('The certificate is located '\n . 'on an invalid domain.');\n }\n }\n}\n" }, { "alpha_fraction": 0.557528555393219, "alphanum_fraction": 0.5594745874404907, "avg_line_length": 23.61676597595215, "blob_id": "4134e978e48c5d4b2f0259cec283883c308d37ac", "content_id": "66bf02c67d62be161f78165c5e11730fb136920e", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4111, "license_type": "permissive", "max_line_length": 80, "num_lines": 167, "path": "/tests/Sns/MessageValidator/MessageTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Sns\\MessageValidator;\n\nuse Aws\\Sns\\MessageValidator\\Message;\nuse GuzzleHttp\\Collection;\n\n/**\n * @covers Aws\\Sns\\MessageValidator\\Message\n */\nclass MessageTest extends \\PHPUnit_Framework_TestCase\n{\n public $messageData = array(\n 'Message' => 'a',\n 'MessageId' => 'b',\n 'Timestamp' => 'c',\n 'TopicArn' => 'd',\n 'Type' => 'e',\n 'Subject' => 'f',\n 'Signature' => 'g',\n 'SigningCertURL' => 'h',\n 'SubscribeURL' => 'i',\n 'Token' => 'j',\n );\n\n public function testGetters()\n {\n $message = new Message(new Collection($this->messageData));\n\n $this->assertInstanceOf('GuzzleHttp\\Collection', $message->getData());\n\n foreach ($this->messageData as $key => $expectedValue) {\n $this->assertEquals($expectedValue, $message->get($key));\n }\n }\n\n public function testFactorySucceedsWithGoodData()\n {\n $this->assertInstanceOf(\n 'Aws\\Sns\\MessageValidator\\Message',\n Message::fromArray($this->messageData)\n );\n }\n\n /**\n * @expectedException \\InvalidArgumentException\n */\n public function testFactoryFailsWithNoType()\n {\n $data = $this->messageData;\n unset($data['Type']);\n Message::fromArray($data);\n }\n\n /**\n * @expectedException \\InvalidArgumentException\n */\n public function testFactoryFailsWithMissingData()\n {\n Message::fromArray(array('Type' => 'Notification'));\n }\n\n public function testCanCreateFromRawPost()\n {\n $_SERVER['HTTP_X_AMZ_SNS_MESSAGE_TYPE'] = 'Notification';\n\n // Prep php://input with mocked data\n MockPhpStream::setStartingData(json_encode($this->messageData));\n stream_wrapper_unregister('php');\n stream_wrapper_register('php', __NAMESPACE__ . '\\MockPhpStream');\n\n $message = Message::fromRawPostData();\n $this->assertInstanceOf('Aws\\Sns\\MessageValidator\\Message', $message);\n\n stream_wrapper_restore(\"php\");\n unset($_SERVER['HTTP_X_AMZ_SNS_MESSAGE_TYPE']);\n }\n\n /**\n * @expectedException \\RuntimeException\n */\n public function testCreateFromRawPostFailsWithMissingHeader()\n {\n Message::fromRawPostData();\n }\n\n /**\n * @expectedException \\RuntimeException\n */\n public function testCreateFromRawPostFailsWithMissingData()\n {\n $_SERVER['HTTP_X_AMZ_SNS_MESSAGE_TYPE'] = 'Notification';\n Message::fromRawPostData();\n unset($_SERVER['HTTP_X_AMZ_SNS_MESSAGE_TYPE']);\n }\n\n /**\n * @dataProvider getDataForStringToSignTest\n */\n public function testBuildsStringToSignCorrectly(\n array $messageData,\n $expectedSubject,\n $expectedStringToSign\n ) {\n $message = new Message(new Collection($messageData));\n $this->assertEquals($expectedSubject, $message->get('Subject'));\n $this->assertEquals($expectedStringToSign, $message->getStringToSign());\n }\n\n public function getDataForStringToSignTest()\n {\n $testCases = array();\n\n // Test case where one key is not signable\n $testCases[0] = array();\n $testCases[0][] = array(\n 'TopicArn' => 'd',\n 'Message' => 'a',\n 'Timestamp' => 'c',\n 'Type' => 'e',\n 'MessageId' => 'b',\n 'FooBar' => 'f',\n );\n $testCases[0][] = null;\n $testCases[0][] = <<< STRINGTOSIGN\nMessage\na\nMessageId\nb\nTimestamp\nc\nTopicArn\nd\nType\ne\n\nSTRINGTOSIGN;\n\n // Test case where all keys are signable\n $testCases[1] = array();\n $testCases[1][] = array(\n 'TopicArn' => 'e',\n 'Message' => 'a',\n 'Timestamp' => 'd',\n 'Type' => 'f',\n 'MessageId' => 'b',\n 'Subject' => 'c',\n );\n $testCases[1][] = 'c';\n $testCases[1][] = <<< STRINGTOSIGN\nMessage\na\nMessageId\nb\nSubject\nc\nTimestamp\nd\nTopicArn\ne\nType\nf\n\nSTRINGTOSIGN;\n\n return $testCases;\n }\n}\n" }, { "alpha_fraction": 0.6102809906005859, "alphanum_fraction": 0.6104180812835693, "avg_line_length": 34.585365295410156, "blob_id": "b323541f869526327d860c4c042ab2c8593cbedc", "content_id": "def2cb9067c1c879cb10b414ad7a13b1ff90694c", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 7295, "license_type": "permissive", "max_line_length": 89, "num_lines": 205, "path": "/src/Credentials/CredentialProvider.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Credentials;\n\nuse Aws\\Exception\\CredentialsException;\nuse Aws\\Exception\\UnresolvedCredentialsException;\nuse Aws\\Utils;\n\n/**\n * Credential providers are functions that create credentials and can be\n * composed to create credentials using conditional logic that can create\n * different credentials in different environments.\n *\n * A credential provider is a function that accepts no arguments and returns\n * {@see CredentialsInterface} object on success or NULL if no credentials can\n * be created. Note: exceptions MAY be thrown in credential providers if\n * necessary though this should only be the result of an error (e.g., malformed\n * file, bad permissions, etc.) and not the result of missing credentials.\n *\n * You can wrap your calls to a credential provider with the\n * {@see CredentialProvider::resolve} function to ensure that a credentials\n * object is created. If a credentials object is not created, then the\n * resolve() function will throw a {@see Aws\\Exception\\UnresolvedCredentialsException}.\n *\n * use Aws\\Credentials\\CredentialProvider;\n * $provider = CredentialProvider::defaultProvider();\n * // Returns a CredentialsInterface or NULL.\n * $creds = $provider();\n * // Returns a CredentialsInterface or throws.\n * $creds = CredentialProvider::resolve($provider);\n *\n * You can compose multiple providers into a single provider using\n * {@see Aws\\Utils::orFn}. This function accepts providers as arguments and\n * returns a new function that will invoke each provider until a non-null value\n * is returned.\n *\n * // First try an INI file at this location.\n * $a = CredentialProvider::ini(null, '/path/to/file.ini');\n * // Then try an INI file at this location.\n * $b = CredentialProvider::ini(null, '/path/to/other-file.ini');\n * // Then try loading from envrionment variables.\n * $c = CredentialProvider::env();\n * // Combine the three providers together.\n * $composed = Aws\\Utils::orFn($a, $b, $c);\n * // Returns creds or NULL\n * $creds = $composed();\n * // Returns creds or throws.\n * $creds = CredentialProvider::resolve($composed);\n */\nclass CredentialProvider\n{\n const ENV_KEY = 'AWS_ACCESS_KEY_ID';\n const ENV_SECRET = 'AWS_SECRET_ACCESS_KEY';\n const ENV_SESSION = 'AWS_SESSION_TOKEN';\n const ENV_PROFILE = 'AWS_PROFILE';\n\n /**\n * Invokes a credential provider and ensures that the provider returns a\n * CredentialsInterface object.\n *\n * @param callable $provider Credential provider function\n *\n * @return CredentialsInterface\n * @throws CredentialsException\n */\n public static function resolve(callable $provider)\n {\n $result = $provider();\n if ($result instanceof CredentialsInterface) {\n return $result;\n }\n\n throw new UnresolvedCredentialsException('Could not load credentials');\n }\n\n /**\n * Provider that creates credentials from environment variables\n * AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_SESSION_TOKEN.\n *\n * @return callable\n */\n public static function env()\n {\n return function () {\n // Use credentials from environment variables, if available\n $key = getenv(self::ENV_KEY);\n $secret = getenv(self::ENV_SECRET);\n return $key && $secret\n ? new Credentials($key, $secret, getenv(self::ENV_SESSION))\n : null;\n };\n }\n\n /**\n * Credential provider that creates credentials using instance profile\n * credentials.\n *\n * @param array $config Array of configuration data.\n *\n * @return InstanceProfileProvider\n * @see Aws\\Credentials\\InstanceProfileProvider for $config details.\n */\n public static function instanceProfile(array $config = [])\n {\n return new InstanceProfileProvider($config);\n }\n\n /**\n * Credentials provider that creates credentials using an ini file stored\n * in the current user's home directory.\n *\n * @param string|null $profile Profile to use. If not specified will use\n * the \"default\" profile.\n * @param string|null $filename If provided, uses a custom filename rather\n * than looking in the home directory for the\n *\n * @return callable\n */\n public static function ini($profile = null, $filename = null)\n {\n $filename = $filename ?: (self::getHomeDir() . '/.aws/credentials');\n $profile = $profile ?: (getenv(self::ENV_PROFILE) ?: 'default');\n\n return function () use ($profile, $filename) {\n if (!file_exists($filename)) {\n return null;\n }\n if (!is_readable($filename)) {\n throw new CredentialsException(\"Cannot read credentials from $filename\");\n }\n if (!($data = parse_ini_file($filename, true))) {\n throw new CredentialsException(\"Invalid credentials file: {$filename}\");\n }\n if (!isset($data[$profile]['aws_access_key_id'])\n || !isset($data[$profile]['aws_secret_access_key'])\n ) {\n return null;\n }\n return new Credentials(\n $data[$profile]['aws_access_key_id'],\n $data[$profile]['aws_secret_access_key'],\n isset($data[$profile]['aws_security_token'])\n ? $data[$profile]['aws_security_token']\n : null\n );\n };\n }\n\n /**\n * Wraps a credential provider and caches previously provided credentials.\n *\n * Ensures that cached credentials are refreshed when they expire.\n *\n * @param callable $provider Credentials provider function to wrap.\n *\n * @return callable\n */\n public static function memoize(callable $provider)\n {\n $result = null;\n return function () use (&$result, $provider) {\n if (!$result || $result->isExpired()) {\n $result = $provider();\n }\n return $result;\n };\n }\n\n /**\n * Create a default credential provider that first checks for environment\n * variables, then checks for the \"default\" profile in ~/.aws/credentials,\n * and finally checks for credentials using EC2 instance profile\n * credentials.\n *\n * @param array $config Optional array of instance profile credentials\n * provider options.\n * @return callable\n */\n public static function defaultProvider(array $config = [])\n {\n return Utils::orFn(\n self::env(),\n self::ini(),\n self::instanceProfile($config)\n );\n }\n\n /**\n * Gets the environment's HOME directory if available.\n *\n * @return null|string\n */\n private static function getHomeDir()\n {\n // On Linux/Unix-like systems, use the HOME environment variable\n if ($homeDir = getenv('HOME')) {\n return $homeDir;\n }\n\n // Get the HOMEDRIVE and HOMEPATH values for Windows hosts\n $homeDrive = getenv('HOMEDRIVE');\n $homePath = getenv('HOMEPATH');\n\n return ($homeDrive && $homePath) ? $homeDrive . $homePath : null;\n }\n}\n" }, { "alpha_fraction": 0.5688889026641846, "alphanum_fraction": 0.5822222232818604, "avg_line_length": 27.846153259277344, "blob_id": "a2078a17d80f02984af754d9f906d1d3ba720399", "content_id": "e5b40ee7e5c3a256576a42c923af75ce1924e562", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1125, "license_type": "permissive", "max_line_length": 82, "num_lines": 39, "path": "/tests/CloudTrail/LogFileReaderTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\CloudTrail;\n\nuse Aws\\CloudTrail\\LogFileReader;\nuse Aws\\S3\\S3Client;\nuse GuzzleHttp\\Subscriber\\Mock;\nuse GuzzleHttp\\Message\\Response;\nuse GuzzleHttp\\Stream\\Stream;\n\n/**\n * @covers Aws\\CloudTrail\\LogFileReader\n */\nclass LogFileReaderTest extends \\PHPUnit_Framework_TestCase\n{\n /**\n * @dataProvider dataForLogReadingTest\n */\n public function testCorrectlyReadsLogFiles($responseBody, $recordCount)\n {\n $mock = new Mock([new Response(200, [], Stream::factory($responseBody))]);\n $s3Client = S3Client::factory([\n 'version' => 'latest',\n 'credentials' => ['key' => 'foo', 'secret' => 'bar'],\n ]);\n $s3Client->getHttpClient()->getEmitter()->attach($mock);\n $reader = new LogFileReader($s3Client);\n $records = $reader->read('test-bucket', 'test-key');\n $this->assertCount($recordCount, $records);\n }\n\n public function dataForLogReadingTest()\n {\n return [\n ['{\"Records\":[{\"foo\":\"1\"},{\"bar\":\"2\"},{\"baz\":\"3\"}]}', 3],\n ['{\"Records\":[]}', 0],\n ['', 0],\n ];\n }\n}\n" }, { "alpha_fraction": 0.6767371892929077, "alphanum_fraction": 0.6827794313430786, "avg_line_length": 29.090909957885742, "blob_id": "a2f2a9950d7bf8410c6aee6466c8dd63152452a5", "content_id": "8313df4050ce87ae34b437e59518c956045a2f1c", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 993, "license_type": "permissive", "max_line_length": 112, "num_lines": 33, "path": "/tests/Subscriber/ValidationSubscriberTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Subscriber;\n\nuse Aws\\Api\\Validator;\nuse Aws\\Subscriber\\Validation;\nuse Aws\\Test\\UsesServiceTrait;\nuse GuzzleHttp\\Command\\CommandTransaction;\nuse GuzzleHttp\\Command\\Event\\InitEvent;\n\n/**\n * @covers Aws\\Subscriber\\Validation\n */\nclass ValidationTest extends \\PHPUnit_Framework_TestCase\n{\n use UsesServiceTrait;\n\n /**\n * @expectedException \\InvalidArgumentException\n * @expectedExceptionMessage Found 2 errors while validating the input provided for the GetObject operation:\n */\n public function testValdiatesBeforeSerialization()\n {\n $s3 = $this->getTestClient('s3');\n $api = $s3->getApi();\n $command = $s3->getCommand('GetObject');\n $trans = new CommandTransaction($s3, $command);\n $event = new InitEvent($trans);\n $validator = new Validator();\n $validation = new Validation($api, $validator);\n $this->assertNotEmpty($validation->getEvents());\n $validation->onInit($event);\n }\n}\n" }, { "alpha_fraction": 0.5215641856193542, "alphanum_fraction": 0.5234953165054321, "avg_line_length": 28.037384033203125, "blob_id": "1b920561517db8733f7d63bea3b461c54c25018b", "content_id": "9654c83cf0a3becbb85df10ca77e134db5c36b13", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 6214, "license_type": "permissive", "max_line_length": 80, "num_lines": 214, "path": "/src/Api/Serializer/RestSerializer.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Api\\Serializer;\n\nuse Aws\\Api\\Service;\nuse Aws\\Api\\Operation;\nuse Aws\\Api\\Shape;\nuse Aws\\Api\\StructureShape;\nuse Aws\\Api\\TimestampShape;\nuse GuzzleHttp\\Command\\CommandTransaction;\nuse GuzzleHttp\\Message\\RequestInterface;\nuse GuzzleHttp\\Query;\nuse GuzzleHttp\\Url;\nuse GuzzleHttp\\Stream\\Stream;\n\n/**\n * Serializes HTTP locations like header, uri, payload, etc...\n * @internal\n */\nabstract class RestSerializer\n{\n /** @var Service */\n private $api;\n\n /** @var Url */\n private $endpoint;\n\n /** @var callable */\n private $aggregator;\n\n /**\n * @param Service $api Service API description\n * @param string $endpoint Endpoint to connect to\n */\n public function __construct(Service $api, $endpoint)\n {\n $this->api = $api;\n $this->endpoint = Url::fromString($endpoint);\n $this->aggregator = Query::duplicateAggregator();\n }\n\n public function getEvents()\n {\n return ['prepared' => ['onPrepare']];\n }\n\n public function __invoke(CommandTransaction $trans)\n {\n $command = $trans->command;\n $operation = $this->api->getOperation($command->getName());\n $args = $command->toArray();\n\n $request = $trans->client->createRequest(\n $operation['http']['method'],\n $this->buildEndpoint($operation, $args),\n ['config' => ['command' => $command]]\n );\n\n // Ensure that query string lists are serialized as duplicates.\n $request->getQuery()->setAggregator($this->aggregator);\n\n return $this->serialize($request, $operation, $args);\n }\n\n /**\n * Applies a payload body to a request.\n *\n * @param RequestInterface $request Request to apply.\n * @param StructureShape $member Member to serialize\n * @param array $value Value to serialize\n *\n * @return \\GuzzleHttp\\Stream\\StreamInterface\n */\n abstract protected function payload(\n RequestInterface $request,\n StructureShape $member,\n array $value\n );\n\n private function serialize(\n RequestInterface $request,\n Operation $operation,\n array $args\n ) {\n $input = $operation->getInput();\n\n // Apply the payload trait if present\n if ($payload = $input['payload']) {\n $this->applyPayload($request, $input, $payload, $args);\n }\n\n foreach ($args as $name => $value) {\n if ($input->hasMember($name)) {\n $member = $input->getMember($name);\n $location = $member['location'];\n if (!$payload && !$location) {\n $bodyMembers[$name] = $value;\n } elseif ($location == 'header') {\n $this->applyHeader($request, $name, $member, $value);\n } elseif ($location == 'querystring') {\n $this->applyQuery($request, $name, $member, $value);\n } elseif ($location == 'headers') {\n $this->applyHeaderMap($request, $name, $member, $value);\n }\n }\n }\n\n if (isset($bodyMembers)) {\n $this->payload($request, $operation->getInput(), $bodyMembers);\n }\n\n return $request;\n }\n\n private function applyPayload(\n RequestInterface $request,\n StructureShape $input,\n $name,\n array $args\n ) {\n if (!isset($args[$name])) {\n return;\n }\n\n $m = $input->getMember($name);\n\n if ($m['streaming'] ||\n ($m['type'] == 'string' || $m['type'] == 'blob')\n ) {\n // Streaming bodies or payloads that are strings are\n // always just a stream of data.\n $request->setBody(Stream::factory($args[$name]));\n } else {\n $this->payload($request, $m, $args[$name]);\n }\n }\n\n private function applyHeader(\n RequestInterface $request,\n $name,\n Shape $member,\n $value\n ) {\n if ($member->getType() == 'timestamp') {\n $value = TimestampShape::format($value, 'rfc822');\n }\n\n $request->setHeader($member['locationName'] ?: $name, $value);\n }\n\n /**\n * Note: This is currently only present in the Amazon S3 model.\n */\n private function applyHeaderMap(\n RequestInterface $request,\n $name,\n Shape $member,\n array $value\n ) {\n $prefix = $member['locationName'];\n foreach ($value as $k => $v) {\n $request->setHeader($prefix . $k, $v);\n }\n }\n\n private function applyQuery(\n RequestInterface $request,\n $name,\n Shape $member,\n $value\n ) {\n if ($value !== null) {\n $request->getQuery()->set($member['locationName'] ?: $name, $value);\n }\n }\n\n /**\n * Builds the URI template for a REST based request.\n *\n * @param Operation $operation\n * @param array $args\n *\n * @return array\n */\n private function buildEndpoint(Operation $operation, array $args)\n {\n $varspecs = [];\n\n // Create an associative array of varspecs used in expansions\n foreach ($operation->getInput()->getMembers() as $name => $member) {\n if ($member['location'] == 'uri') {\n $varspecs[$member['locationName'] ?: $name] =\n isset($args[$name]) ? $args[$name] : null;\n }\n }\n\n // Expand path place holders using Amazon's slightly different URI\n // template syntax.\n return $this->endpoint->combine(preg_replace_callback(\n '/\\{([^\\}]+)\\}/',\n function (array $matches) use ($varspecs) {\n $isGreedy = substr($matches[1], -1, 1) == '+';\n $k = $isGreedy ? substr($matches[1], 0, -1) : $matches[1];\n if (!isset($varspecs[$k])) {\n return '';\n } elseif ($isGreedy) {\n return str_replace('%2F', '/', rawurlencode($varspecs[$k]));\n } else {\n return rawurlencode($varspecs[$k]);\n }\n },\n $operation['http']['requestUri']\n ));\n }\n}\n" }, { "alpha_fraction": 0.5480668544769287, "alphanum_fraction": 0.5559038519859314, "avg_line_length": 28.44615364074707, "blob_id": "c392d669db689ed67a7afe0bd126076de40aad91", "content_id": "a6438af206b106dd01ad481b8c20895c0337a203", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1914, "license_type": "permissive", "max_line_length": 76, "num_lines": 65, "path": "/src/DynamoDb/DynamoDbClient.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\DynamoDb;\n\nuse Aws\\AwsClient;\nuse Aws\\ClientResolver;\nuse Aws\\Retry\\ThrottlingFilter;\nuse Aws\\Retry\\Crc32Filter;\nuse GuzzleHttp\\Subscriber\\Retry\\RetrySubscriber;\n\n/**\n * This client is used to interact with the **Amazon DynamoDB** service.\n */\nclass DynamoDbClient extends AwsClient\n{\n public static function getArguments()\n {\n $args = parent::getArguments();\n // Apply custom retry strategy for DynamoDB.\n $args['retries']['default'] = 11;\n $args['retries']['fn'] = [__CLASS__, '_applyRetryConfig'];\n\n return $args;\n }\n\n /**\n * Convenience method for instantiating and registering the DynamoDB\n * Session handler with this DynamoDB client object.\n *\n * @param array $config Array of options for the session handler factory\n *\n * @return SessionHandler\n */\n public function registerSessionHandler(array $config = [])\n {\n $handler = SessionHandler::fromClient($this, $config);\n $handler->register();\n\n return $handler;\n }\n\n /** @internal */\n public static function _applyRetryConfig($value, array &$args)\n {\n if (!$value) {\n return;\n }\n\n $args['client']->getEmitter()->attach(new RetrySubscriber(\n ClientResolver::_wrapDebugLogger($args, [\n 'max' => $value,\n 'delay' => function ($retries) {\n return $retries\n ? (50 * (int)pow(2, $retries - 1)) / 1000\n : 0;\n },\n 'filter' => RetrySubscriber::createChainFilter([\n new ThrottlingFilter($args['error_parser']),\n new Crc32Filter($args['error_parser']),\n RetrySubscriber::createStatusFilter(),\n RetrySubscriber::createConnectFilter()\n ])\n ])\n ));\n }\n}\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6701754331588745, "avg_line_length": 35.53845977783203, "blob_id": "2b9b1ed84f0e61b9d42bd1690d410a394298aa97", "content_id": "73345f161bf36534b4fe8fbe1190e7555c08b678", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 2850, "license_type": "permissive", "max_line_length": 119, "num_lines": 78, "path": "/docs/service-redshift.rst", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "=====================\nAmazon RedShift Guide\n=====================\n\nCreating a cluster\n------------------\n\nThe primary resource in Amazon Redshift is the cluster. To create a cluster you will use the ``CreateCluster``\noperation. There are several parameters you can send when creating a cluster, so please refer to the API docs to\ndetermine which parameters to use. The following is basic example.\n\n.. code-block:: php\n\n $client->createCluster(array(\n 'ClusterIdentifier' => 'your-unique-cluster-id',\n 'ClusterType' => 'multi-node',\n 'MasterUsername' => 'yourusername',\n 'MasterUserPassword' => 'Y0urP@$$w0rd',\n 'NodeType' => 'dw.hs1.xlarge',\n 'NumberOfNodes' => 2,\n ));\n\nAfter the ``CreateCluster`` operation is complete, the record for your cluster will exist, but it will still take some\ntime before the cluster is actually available for use. You can describe your cluster to check it's status.\n\n.. code-block:: php\n\n $result = $client->describeClusters(array(\n 'ClusterIdentifier' => 'your-unique-cluster-id',\n ));\n $clusters = $result->get('Clusters');\n $status = $clusters['ClusterStatus'];\n\nIf you would like your code to wait until the cluster is available, you can use the the ``ClusterAvailable`` waiter.\n\n.. code-block:: php\n\n $client->waitUntilClusterAvailable(array(\n 'ClusterIdentifier' => 'your-unique-cluster-id',\n ));\n\n.. warning:: It can take over 20 minutes for a cluster to become available.\n\nCreating snapshots\n------------------\n\nYou can also take snapshots of your cluster with the ``CreateClusterSnapshot`` operation. Snapshots can take a little\ntime before they become available as well, so there is a corresponding ``SnapshotAvailable`` waiter.\n\n.. code-block:: php\n\n $client->createClusterSnapshot(array(\n 'ClusterIdentifier' => 'your-unique-cluster-id',\n 'SnapshotIdentifier' => 'your-unique-snapshot-id',\n ));\n $client->waitUntilSnapshotAvailable(array(\n 'SnapshotIdentifier' => 'your-unique-snapshot-id',\n ));\n\nEvents\n------\n\nAmazon Redshift records events that take place with your clusters and account. These events are available for up to 14\ndays and can be retrieved via the ``DescribeEvents`` operation. Only 100 events can be returned at a time, so using the\nSDK's iterators feature allows you to easily fetch and iterate over all the events in your query without having to\nmanually send repeated requests. The ``StartTime`` and ``EndTime`` parameters can take any PHP date string or DateTime\nobject.\n\n.. code-block:: php\n\n $events = $client->getIterator('DescribeEvents', array(\n 'StartTime' => strtotime('-3 days'),\n 'EndTime' => strtotime('now'),\n ));\n\n foreach ($events as $event) {\n echo \"{$event['Date']}: {$event['Message']}\\n\";\n }\n" }, { "alpha_fraction": 0.6741388440132141, "alphanum_fraction": 0.675754725933075, "avg_line_length": 75.90138244628906, "blob_id": "ffe64aa4541ac028d998365408767174f7f4aa71", "content_id": "b7cf8278510fb2f7ea6967e29571ea6df4319957", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 38989, "license_type": "permissive", "max_line_length": 859, "num_lines": 507, "path": "/src/data/ecs-2014-11-13.docs.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php return [\n 'operations' => [\n 'CreateCluster' => '<p>Creates a new Amazon ECS cluster. By default, your account will receive a <code>default</code> cluster when you launch your first container instance. However, you can create your own cluster with a unique name with the <code>CreateCluster</code> action.</p> <important> <p>During the preview, each account is limited to two clusters.</p> </important>',\n 'DeleteCluster' => '<p>Deletes the specified cluster. You must deregister all container instances from this cluster before you may delete it. You can list the container instances in a cluster with <a>ListContainerInstances</a> and deregister them with <a>DeregisterContainerInstance</a>.</p>',\n 'DeregisterContainerInstance' => '<p>Deregisters an Amazon ECS container instance from the specified cluster. This instance will no longer be available to run tasks.</p>',\n 'DeregisterTaskDefinition' => '<p>Deregisters the specified task definition. You will no longer be able to run tasks from this definition after deregistration.</p>',\n 'DescribeClusters' => '<p>Describes one or more of your clusters.</p>',\n 'DescribeContainerInstances' => '<p>Describes Amazon EC2 Container Service container instances. Returns metadata about registered and remaining resources on each container instance requested.</p>',\n 'DescribeTaskDefinition' => '<p>Describes a task definition.</p>',\n 'DescribeTasks' => '<p>Describes a specified task or tasks.</p>',\n 'DiscoverPollEndpoint' => '<note><p>This action is only used by the Amazon EC2 Container Service agent, and it is not intended for use outside of the agent.</p></note> <p>Returns an endpoint for the Amazon EC2 Container Service agent to poll for updates.</p>',\n 'ListClusters' => '<p>Returns a list of existing clusters.</p>',\n 'ListContainerInstances' => '<p>Returns a list of container instances in a specified cluster.</p>',\n 'ListTaskDefinitions' => '<p>Returns a list of task definitions that are registered to your account. You can filter the results by family name with the <code>familyPrefix</code> parameter.</p>',\n 'ListTasks' => '<p>Returns a list of tasks for a specified cluster. You can filter the results by family name or by a particular container instance with the <code>family</code> and <code>containerInstance</code> parameters.</p>',\n 'RegisterContainerInstance' => '<note><p>This action is only used by the Amazon EC2 Container Service agent, and it is not intended for use outside of the agent.</p></note> <p>Registers an Amazon EC2 instance into the specified cluster. This instance will become available to place containers on.</p>',\n 'RegisterTaskDefinition' => '<p>Registers a new task definition from the supplied <code>family</code> and <code>containerDefinitions</code>.</p>',\n 'RunTask' => '<p>Start a task using random placement and the default Amazon ECS scheduler. If you want to use your own scheduler or place a task on a specific container instance, use <code>StartTask</code> instead.</p>',\n 'StartTask' => '<p>Starts a new task from the specified task definition on the specified container instance or instances. If you want to use the default Amazon ECS scheduler to place your task, use <code>RunTask</code> instead.</p>',\n 'StopTask' => '<p>Stops a running task.</p>',\n 'SubmitContainerStateChange' => '<note><p>This action is only used by the Amazon EC2 Container Service agent, and it is not intended for use outside of the agent.</p></note> <p>Sent to acknowledge that a container changed states.</p>',\n 'SubmitTaskStateChange' => '<note><p>This action is only used by the Amazon EC2 Container Service agent, and it is not intended for use outside of the agent.</p></note> <p>Sent to acknowledge that a task changed states.</p>',\n ],\n 'service' => '<p>Amazon EC2 Container Service (Amazon ECS] is a highly scalable, fast, container management service that makes it easy to run, stop, and manage Docker containers on a cluster of Amazon EC2 instances. Amazon ECS lets you launch and stop container-enabled applications with simple API calls, allows you to get the state of your cluster from a centralized service, and gives you access to many familiar Amazon EC2 features like security groups, Amazon EBS volumes, and IAM roles.</p> <p>You can use Amazon ECS to schedule the placement of containers across your cluster based on your resource needs, isolation policies, and availability requirements. Amazon EC2 Container Service eliminates the need for you to operate your own cluster management and configuration management systems or worry about scaling your management infrastructure.</p>',\n 'shapes' => [\n 'Boolean' => [\n 'base' => NULL,\n 'refs' => [\n 'ContainerInstance$agentConnected' => '<p>This parameter returns <code>true</code> if the agent is actually connected to Amazon ECS. Registered instances with an agent that may be unhealthy or stopped will return <code>false</code>, and instances without a connected agent cannot accept placement request.</p>',\n ],\n ],\n 'BoxedBoolean' => [\n 'base' => NULL,\n 'refs' => [\n 'ContainerDefinition$essential' => '<p>If the <code>essential</code> parameter of a container is marked as <code>true</code>, the failure of that container will stop the task. If the <code>essential</code> parameter of a container is marked as <code>false</code>, then its failure will not affect the rest of the containers in a task.</p>',\n 'DeregisterContainerInstanceRequest$force' => '<p>Force the deregistration of the container instance. You can use the <code>force</code> parameter if you have several tasks running on a container instance and you don\\'t want to run <code>StopTask</code> for each task before deregistering the container instance.</p>',\n ],\n ],\n 'BoxedInteger' => [\n 'base' => NULL,\n 'refs' => [\n 'Container$exitCode' => '<p>The exit code returned from the container.</p>',\n 'ListClustersRequest$maxResults' => '<p>The maximum number of cluster results returned by <code>ListClusters</code> in paginated output. When this parameter is used, <code>ListClusters</code> only returns <code>maxResults</code> results in a single page along with a <code>nextToken</code> response element. The remaining results of the initial request can be seen by sending another <code>ListClusters</code> request with the returned <code>nextToken</code> value. This value can be between 1 and 100. If this parameter is not used, then <code>ListClusters</code> returns up to 100 results and a <code>nextToken</code> value if applicable.</p>',\n 'ListContainerInstancesRequest$maxResults' => '<p>The maximum number of container instance results returned by <code>ListContainerInstances</code> in paginated output. When this parameter is used, <code>ListContainerInstances</code> only returns <code>maxResults</code> results in a single page along with a <code>nextToken</code> response element. The remaining results of the initial request can be seen by sending another <code>ListContainerInstances</code> request with the returned <code>nextToken</code> value. This value can be between 1 and 100. If this parameter is not used, then <code>ListContainerInstances</code> returns up to 100 results and a <code>nextToken</code> value if applicable.</p>',\n 'ListTaskDefinitionsRequest$maxResults' => '<p>The maximum number of task definition results returned by <code>ListTaskDefinitions</code> in paginated output. When this parameter is used, <code>ListTaskDefinitions</code> only returns <code>maxResults</code> results in a single page along with a <code>nextToken</code> response element. The remaining results of the initial request can be seen by sending another <code>ListTaskDefinitions</code> request with the returned <code>nextToken</code> value. This value can be between 1 and 100. If this parameter is not used, then <code>ListTaskDefinitions</code> returns up to 100 results and a <code>nextToken</code> value if applicable.</p>',\n 'ListTasksRequest$maxResults' => '<p>The maximum number of task results returned by <code>ListTasks</code> in paginated output. When this parameter is used, <code>ListTasks</code> only returns <code>maxResults</code> results in a single page along with a <code>nextToken</code> response element. The remaining results of the initial request can be seen by sending another <code>ListTasks</code> request with the returned <code>nextToken</code> value. This value can be between 1 and 100. If this parameter is not used, then <code>ListTasks</code> returns up to 100 results and a <code>nextToken</code> value if applicable.</p>',\n 'NetworkBinding$containerPort' => '<p>The port number on the container that should be used with the network binding.</p>',\n 'NetworkBinding$hostPort' => '<p>The port number on the host that should be used with the network binding.</p>',\n 'RunTaskRequest$count' => '<p>The number of instances of the specified task that you would like to place on your cluster.</p>',\n 'SubmitContainerStateChangeRequest$exitCode' => '<p>The exit code returned for the state change request.</p>',\n ],\n ],\n 'ClientException' => [\n 'base' => '<p>These errors are usually caused by something the client did, such as use an action or resource on behalf of a user that doesn\\'t have permission to use the action or resource, or specify an identifier that is not valid.</p>',\n 'refs' => [],\n ],\n 'Cluster' => [\n 'base' => '<p>A regional grouping of one or more container instances on which you can run task requests. Each account receives a default cluster the first time you use the Amazon ECS service, but you may also create other clusters. Clusters may contain more than one instance type simultaneously.</p> <important> <p>During the preview, each account is limited to two clusters.</p> </important>',\n 'refs' => [\n 'Clusters$member' => NULL,\n 'CreateClusterResponse$cluster' => '<p>The full description of your new cluster.</p>',\n 'DeleteClusterResponse$cluster' => '<p>The full description of the deleted cluster.</p>',\n ],\n ],\n 'Clusters' => [\n 'base' => NULL,\n 'refs' => [\n 'DescribeClustersResponse$clusters' => '<p>The list of clusters.</p>',\n ],\n ],\n 'Container' => [\n 'base' => NULL,\n 'refs' => [\n 'Containers$member' => NULL,\n ],\n ],\n 'ContainerDefinition' => [\n 'base' => '<p>Container definitions are used in task definitions to describe the different containers that are launched as part of a task.</p>',\n 'refs' => [\n 'ContainerDefinitions$member' => NULL,\n ],\n ],\n 'ContainerDefinitions' => [\n 'base' => NULL,\n 'refs' => [\n 'RegisterTaskDefinitionRequest$containerDefinitions' => '<p>A list of container definitions in JSON format that describe the different containers that make up your task.</p>',\n 'TaskDefinition$containerDefinitions' => '<p>A list of container definitions in JSON format that describe the different containers that make up your task.</p>',\n ],\n ],\n 'ContainerInstance' => [\n 'base' => '<p>An Amazon EC2 instance that is running the Amazon ECS agent and has been registered with a cluster.</p>',\n 'refs' => [\n 'ContainerInstances$member' => NULL,\n 'DeregisterContainerInstanceResponse$containerInstance' => NULL,\n 'RegisterContainerInstanceResponse$containerInstance' => NULL,\n ],\n ],\n 'ContainerInstances' => [\n 'base' => NULL,\n 'refs' => [\n 'DescribeContainerInstancesResponse$containerInstances' => '<p>The list of container instances.</p>',\n ],\n ],\n 'ContainerOverride' => [\n 'base' => NULL,\n 'refs' => [\n 'ContainerOverrides$member' => NULL,\n ],\n ],\n 'ContainerOverrides' => [\n 'base' => NULL,\n 'refs' => [\n 'TaskOverride$containerOverrides' => '<p>One or more container overrides to send when running a task.</p>',\n ],\n ],\n 'Containers' => [\n 'base' => NULL,\n 'refs' => [\n 'Task$containers' => '<p>The containers associated with the task.</p>',\n ],\n ],\n 'CreateClusterRequest' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'CreateClusterResponse' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'DeleteClusterRequest' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'DeleteClusterResponse' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'DeregisterContainerInstanceRequest' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'DeregisterContainerInstanceResponse' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'DeregisterTaskDefinitionRequest' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'DeregisterTaskDefinitionResponse' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'DescribeClustersRequest' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'DescribeClustersResponse' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'DescribeContainerInstancesRequest' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'DescribeContainerInstancesResponse' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'DescribeTaskDefinitionRequest' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'DescribeTaskDefinitionResponse' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'DescribeTasksRequest' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'DescribeTasksResponse' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'DiscoverPollEndpointRequest' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'DiscoverPollEndpointResponse' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'Double' => [\n 'base' => NULL,\n 'refs' => [\n 'Resource$doubleValue' => '<p>When the <code>doubleValue</code> type is set, the value of the resource must be a double precision floating-point type.</p>',\n ],\n ],\n 'EnvironmentVariables' => [\n 'base' => NULL,\n 'refs' => [\n 'ContainerDefinition$environment' => '<p>The environment variables to pass to a container.</p>',\n ],\n ],\n 'Failure' => [\n 'base' => NULL,\n 'refs' => [\n 'Failures$member' => NULL,\n ],\n ],\n 'Failures' => [\n 'base' => NULL,\n 'refs' => [\n 'DescribeClustersResponse$failures' => NULL,\n 'DescribeContainerInstancesResponse$failures' => NULL,\n 'DescribeTasksResponse$failures' => NULL,\n 'RunTaskResponse$failures' => '<p>Any failed tasks from your <code>RunTask</code> action are listed here.</p>',\n 'StartTaskResponse$failures' => '<p>Any failed tasks from your <code>StartTask</code> action are listed here.</p>',\n ],\n ],\n 'Integer' => [\n 'base' => NULL,\n 'refs' => [\n 'ContainerDefinition$cpu' => '<p>The number of <code>cpu</code> units reserved for the container. A container instance has 1,024 <code>cpu</code> units for every CPU core.</p>',\n 'ContainerDefinition$memory' => '<p>The number of MiB of memory reserved for the container. Docker will allocate a minimum of 4 MiB of memory to a container.</p>',\n 'PortMapping$containerPort' => '<p>The port number on the container that should be used with the port mapping.</p>',\n 'PortMapping$hostPort' => '<p>The port number on the host that should be used with the port mapping.</p>',\n 'Resource$integerValue' => '<p>When the <code>integerValue</code> type is set, the value of the resource must be an integer.</p>',\n 'TaskDefinition$revision' => '<p>The revision of the task in a particular family. You can think of the revision as a version number of a task definition in a family. When you register a task definition for the first time, the revision is <code>1</code>, and each time you register a task definition in the same family, the revision value increases by one.</p>',\n ],\n ],\n 'KeyValuePair' => [\n 'base' => NULL,\n 'refs' => [\n 'EnvironmentVariables$member' => NULL,\n ],\n ],\n 'ListClustersRequest' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'ListClustersResponse' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'ListContainerInstancesRequest' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'ListContainerInstancesResponse' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'ListTaskDefinitionsRequest' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'ListTaskDefinitionsResponse' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'ListTasksRequest' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'ListTasksResponse' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'Long' => [\n 'base' => NULL,\n 'refs' => [\n 'Resource$longValue' => '<p>When the <code>longValue</code> type is set, the value of the resource must be an extended precision floating-point type.</p>',\n ],\n ],\n 'NetworkBinding' => [\n 'base' => NULL,\n 'refs' => [\n 'NetworkBindings$member' => NULL,\n ],\n ],\n 'NetworkBindings' => [\n 'base' => NULL,\n 'refs' => [\n 'Container$networkBindings' => NULL,\n 'SubmitContainerStateChangeRequest$networkBindings' => '<p>The network bindings of the container.</p>',\n ],\n ],\n 'PortMapping' => [\n 'base' => '<p>Port mappings allow containers to access ports on the host container instance to send or receive traffic. Port mappings are specified as part of the container definition.</p>',\n 'refs' => [\n 'PortMappingList$member' => NULL,\n ],\n ],\n 'PortMappingList' => [\n 'base' => NULL,\n 'refs' => [\n 'ContainerDefinition$portMappings' => '<p>The list of port mappings for the container.</p>',\n ],\n ],\n 'RegisterContainerInstanceRequest' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'RegisterContainerInstanceResponse' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'RegisterTaskDefinitionRequest' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'RegisterTaskDefinitionResponse' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'Resource' => [\n 'base' => '<p>Describes the resources available for a container instance.</p>',\n 'refs' => [\n 'Resources$member' => NULL,\n ],\n ],\n 'Resources' => [\n 'base' => NULL,\n 'refs' => [\n 'ContainerInstance$remainingResources' => '<p>The remaining resources of the container instance that are available for new tasks.</p>',\n 'ContainerInstance$registeredResources' => '<p>The registered resources on the container instance that are in use by current tasks.</p>',\n 'RegisterContainerInstanceRequest$totalResources' => NULL,\n ],\n ],\n 'RunTaskRequest' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'RunTaskResponse' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'ServerException' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'StartTaskRequest' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'StartTaskResponse' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'StopTaskRequest' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'StopTaskResponse' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'String' => [\n 'base' => NULL,\n 'refs' => [\n 'ClientException$message' => '<p>These errors are usually caused by something the client did, such as use an action or resource on behalf of a user that doesn\\'t have permission to use the action or resource, or specify an identifier that is not valid.</p>',\n 'Cluster$clusterArn' => '<p>The Amazon Resource Name (ARN] that identifies the cluster. The ARN contains the <code>arn:aws:ecs</code> namespace, followed by the region of the cluster, the AWS account ID of the cluster owner, the <code>cluster</code> namespace, and then the cluster name. For example, arn:aws:ecs:<i>region</i>:<i>012345678910</i>:cluster/<i>test</i>.</p>',\n 'Cluster$clusterName' => '<p>A user-generated string that you can use to identify your cluster.</p>',\n 'Cluster$status' => '<p>The status of the cluster. The valid values are <code>ACTIVE</code> or <code>INACTIVE</code>. <code>ACTIVE</code> indicates that you can register container instances with the cluster and the associated instances can accept tasks.</p>',\n 'Container$containerArn' => '<p>The Amazon Resource Name (ARN] of the container.</p>',\n 'Container$taskArn' => '<p>The Amazon Resource Name (ARN] of the task.</p>',\n 'Container$name' => '<p>The name of the container.</p>',\n 'Container$lastStatus' => '<p>The last known status of the container.</p>',\n 'Container$reason' => '<p>A short (255 max characters] human-readable string to provide additional detail about a running or stopped container.</p>',\n 'ContainerDefinition$name' => '<p>The name of a container. If you are linking multiple containers together in a task definition, the <code>name</code> of one container can be entered in the <code>links</code> of another container to connect the containers.</p>',\n 'ContainerDefinition$image' => '<p>The image used to start a container. This string is passed directly to the Docker daemon. Images in the Docker Hub registry are available by default. Other repositories are specified with <code><i>repository-url</i>/<i>image</i>:<i>tag</i></code>.</p>',\n 'ContainerInstance$containerInstanceArn' => '<p>The Amazon Resource Name (ARN] of the container instance. The ARN contains the <code>arn:aws:ecs</code> namespace, followed by the region of the container instance, the AWS account ID of the container instance owner, the <code>container-instance</code> namespace, and then the container instance UUID. For example, arn:aws:ecs:<i>region</i>:<i>aws_account_id</i>:container-instance/<i>container_instance_UUID</i>.</p>',\n 'ContainerInstance$ec2InstanceId' => '<p>The Amazon EC2 instance ID of the container instance.</p>',\n 'ContainerInstance$status' => '<p>The status of the container instance. The valid values are <code>ACTIVE</code> or <code>INACTIVE</code>. <code>ACTIVE</code> indicates that the container instance can accept tasks.</p>',\n 'ContainerOverride$name' => '<p>The name of the container that receives the override.</p>',\n 'CreateClusterRequest$clusterName' => '<p>The name of your cluster. If you do not specify a name for your cluster, you will create a cluster named <code>default</code>.</p>',\n 'DeleteClusterRequest$cluster' => '<p>The cluster you want to delete.</p>',\n 'DeregisterContainerInstanceRequest$cluster' => '<p>The short name or full Amazon Resource Name (ARN] of the cluster that hosts the container instance you want to deregister. If you do not specify a cluster, the default cluster is assumed.</p>',\n 'DeregisterContainerInstanceRequest$containerInstance' => '<p>The container instance UUID or full Amazon Resource Name (ARN] of the container instance you want to deregister. The ARN contains the <code>arn:aws:ecs</code> namespace, followed by the region of the container instance, the AWS account ID of the container instance owner, the <code>container-instance</code> namespace, and then the container instance UUID. For example, arn:aws:ecs:<i>region</i>:<i>aws_account_id</i>:container-instance/<i>container_instance_UUID</i>.</p>',\n 'DeregisterTaskDefinitionRequest$taskDefinition' => '<p>The <code>family</code> and <code>revision</code> (<code>family:revision</code>] or full Amazon Resource Name (ARN] of the task definition that you want to deregister.</p>',\n 'DescribeContainerInstancesRequest$cluster' => '<p>The short name or full Amazon Resource Name (ARN] of the cluster that hosts the container instances you want to describe. If you do not specify a cluster, the default cluster is assumed.</p>',\n 'DescribeTaskDefinitionRequest$taskDefinition' => '<p>The <code>family</code> and <code>revision</code> (<code>family:revision</code>] or full Amazon Resource Name (ARN] of the task definition that you want to describe.</p>',\n 'DescribeTasksRequest$cluster' => '<p>The short name or full Amazon Resource Name (ARN] of the cluster that hosts the task you want to describe. If you do not specify a cluster, the default cluster is assumed.</p>',\n 'DiscoverPollEndpointRequest$containerInstance' => '<p>The container instance UUID or full Amazon Resource Name (ARN] of the container instance. The ARN contains the <code>arn:aws:ecs</code> namespace, followed by the region of the container instance, the AWS account ID of the container instance owner, the <code>container-instance</code> namespace, and then the container instance UUID. For example, arn:aws:ecs:<i>region</i>:<i>aws_account_id</i>:container-instance/<i>container_instance_UUID</i>.</p>',\n 'DiscoverPollEndpointResponse$endpoint' => '<p>The endpoint for the Amazon ECS agent to poll.</p>',\n 'Failure$arn' => '<p>The Amazon Resource Name (ARN] of the failed resource.</p>',\n 'Failure$reason' => '<p>The reason for the failure.</p>',\n 'KeyValuePair$name' => '<p>The name of the key value pair.</p>',\n 'KeyValuePair$value' => '<p>The value of the key value pair.</p>',\n 'ListClustersRequest$nextToken' => '<p>The <code>nextToken</code> value returned from a previous paginated <code>ListClusters</code> request where <code>maxResults</code> was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the <code>nextToken</code> value. This value is <code>null</code> when there are no more results to return.</p>',\n 'ListClustersResponse$nextToken' => '<p>The <code>nextToken</code> value to include in a future <code>ListClusters</code> request. When the results of a <code>ListClusters</code> request exceed <code>maxResults</code>, this value can be used to retrieve the next page of results. This value is <code>null</code> when there are no more results to return.</p>',\n 'ListContainerInstancesRequest$cluster' => '<p>The short name or full Amazon Resource Name (ARN] of the cluster that hosts the container instances you want to list. If you do not specify a cluster, the default cluster is assumed..</p>',\n 'ListContainerInstancesRequest$nextToken' => '<p>The <code>nextToken</code> value returned from a previous paginated <code>ListContainerInstances</code> request where <code>maxResults</code> was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the <code>nextToken</code> value. This value is <code>null</code> when there are no more results to return.</p>',\n 'ListContainerInstancesResponse$nextToken' => '<p>The <code>nextToken</code> value to include in a future <code>ListContainerInstances</code> request. When the results of a <code>ListContainerInstances</code> request exceed <code>maxResults</code>, this value can be used to retrieve the next page of results. This value is <code>null</code> when there are no more results to return.</p>',\n 'ListTaskDefinitionsRequest$familyPrefix' => '<p>The name of the family that you want to filter the <code>ListTaskDefinitions</code> results with. Specifying a <code>familyPrefix</code> will limit the listed task definitions to definitions that belong to that family.</p>',\n 'ListTaskDefinitionsRequest$nextToken' => '<p>The <code>nextToken</code> value returned from a previous paginated <code>ListTaskDefinitions</code> request where <code>maxResults</code> was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the <code>nextToken</code> value. This value is <code>null</code> when there are no more results to return.</p>',\n 'ListTaskDefinitionsResponse$nextToken' => '<p>The <code>nextToken</code> value to include in a future <code>ListTaskDefinitions</code> request. When the results of a <code>ListTaskDefinitions</code> request exceed <code>maxResults</code>, this value can be used to retrieve the next page of results. This value is <code>null</code> when there are no more results to return.</p>',\n 'ListTasksRequest$cluster' => '<p>The short name or full Amazon Resource Name (ARN] of the cluster that hosts the tasks you want to list. If you do not specify a cluster, the default cluster is assumed..</p>',\n 'ListTasksRequest$containerInstance' => '<p>The container instance UUID or full Amazon Resource Name (ARN] of the container instance that you want to filter the <code>ListTasks</code> results with. Specifying a <code>containerInstance</code> will limit the results to tasks that belong to that container instance.</p>',\n 'ListTasksRequest$family' => '<p>The name of the family that you want to filter the <code>ListTasks</code> results with. Specifying a <code>family</code> will limit the results to tasks that belong to that family.</p>',\n 'ListTasksRequest$nextToken' => '<p>The <code>nextToken</code> value returned from a previous paginated <code>ListTasks</code> request where <code>maxResults</code> was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the <code>nextToken</code> value. This value is <code>null</code> when there are no more results to return.</p>',\n 'ListTasksResponse$nextToken' => '<p>The <code>nextToken</code> value to include in a future <code>ListTasks</code> request. When the results of a <code>ListTasks</code> request exceed <code>maxResults</code>, this value can be used to retrieve the next page of results. This value is <code>null</code> when there are no more results to return.</p>',\n 'NetworkBinding$bindIP' => '<p>The IP address that the container is bound to on the container instance.</p>',\n 'RegisterContainerInstanceRequest$cluster' => '<p>The short name or full Amazon Resource Name (ARN] of the cluster that you want to register your container instance with. If you do not specify a cluster, the default cluster is assumed..</p>',\n 'RegisterContainerInstanceRequest$instanceIdentityDocument' => NULL,\n 'RegisterContainerInstanceRequest$instanceIdentityDocumentSignature' => NULL,\n 'RegisterTaskDefinitionRequest$family' => '<p>You can specify a <code>family</code> for a task definition, which allows you to track multiple versions of the same task definition. You can think of the <code>family</code> as a name for your task definition.</p>',\n 'Resource$name' => '<p>The name of the resource, such as <code>CPU</code>, <code>MEMORY</code>, <code>PORTS</code>, or a user-defined resource.</p>',\n 'Resource$type' => '<p>The type of the resource, such as <code>INTEGER</code>, <code>DOUBLE</code>, <code>LONG</code>, or <code>STRINGSET</code>.</p>',\n 'RunTaskRequest$cluster' => '<p>The short name or full Amazon Resource Name (ARN] of the cluster that you want to run your task on. If you do not specify a cluster, the default cluster is assumed..</p>',\n 'RunTaskRequest$taskDefinition' => '<p>The <code>family</code> and <code>revision</code> (<code>family:revision</code>] or full Amazon Resource Name (ARN] of the task definition that you want to run.</p>',\n 'ServerException$message' => '<p>These errors are usually caused by a server-side issue.</p>',\n 'StartTaskRequest$cluster' => '<p>The short name or full Amazon Resource Name (ARN] of the cluster that you want to start your task on. If you do not specify a cluster, the default cluster is assumed..</p>',\n 'StartTaskRequest$taskDefinition' => '<p>The <code>family</code> and <code>revision</code> (<code>family:revision</code>] or full Amazon Resource Name (ARN] of the task definition that you want to start.</p>',\n 'StopTaskRequest$cluster' => '<p>The short name or full Amazon Resource Name (ARN] of the cluster that hosts the task you want to stop. If you do not specify a cluster, the default cluster is assumed..</p>',\n 'StopTaskRequest$task' => '<p>The task UUIDs or full Amazon Resource Name (ARN] entry of the task you would like to stop.</p>',\n 'StringList$member' => NULL,\n 'SubmitContainerStateChangeRequest$cluster' => '<p>The short name or full Amazon Resource Name (ARN] of the cluster that hosts the container.</p>',\n 'SubmitContainerStateChangeRequest$task' => '<p>The task UUID or full Amazon Resource Name (ARN] of the task that hosts the container.</p>',\n 'SubmitContainerStateChangeRequest$containerName' => '<p>The name of the container.</p>',\n 'SubmitContainerStateChangeRequest$status' => '<p>The status of the state change request.</p>',\n 'SubmitContainerStateChangeRequest$reason' => '<p>The reason for the state change request.</p>',\n 'SubmitContainerStateChangeResponse$acknowledgment' => '<p>Acknowledgement of the state change.</p>',\n 'SubmitTaskStateChangeRequest$cluster' => '<p>The short name or full Amazon Resource Name (ARN] of the cluster that hosts the task.</p>',\n 'SubmitTaskStateChangeRequest$task' => '<p>The task UUID or full Amazon Resource Name (ARN] of the task in the state change request.</p>',\n 'SubmitTaskStateChangeRequest$status' => '<p>The status of the state change request.</p>',\n 'SubmitTaskStateChangeRequest$reason' => '<p>The reason for the state change request.</p>',\n 'SubmitTaskStateChangeResponse$acknowledgment' => '<p>Acknowledgement of the state change.</p>',\n 'Task$taskArn' => '<p>The Amazon Resource Name (ARN] of the task.</p>',\n 'Task$clusterArn' => '<p>The Amazon Resource Name (ARN] of the of the cluster that hosts the task.</p>',\n 'Task$taskDefinitionArn' => '<p>The Amazon Resource Name (ARN] of the of the task definition that creates the task.</p>',\n 'Task$containerInstanceArn' => '<p>The Amazon Resource Name (ARN] of the container instances that host the task.</p>',\n 'Task$lastStatus' => '<p>The last known status of the task.</p>',\n 'Task$desiredStatus' => '<p>The desired status of the task.</p>',\n 'TaskDefinition$taskDefinitionArn' => '<p>The full Amazon Resource Name (ARN] of the of the task definition.</p>',\n 'TaskDefinition$family' => '<p>The family of your task definition. You can think of the <code>family</code> as the name of your task definition.</p>',\n ],\n ],\n 'StringList' => [\n 'base' => NULL,\n 'refs' => [\n 'ContainerDefinition$links' => '<p>The <code>link</code> parameter allows containers to communicate with each other without the need for port mappings, using the <code>name</code> parameter. For more information on linking Docker containers, see <a href=\"https://docs.docker.com/userguide/dockerlinks/\">https://docs.docker.com/userguide/dockerlinks/</a>.</p>',\n 'ContainerDefinition$entryPoint' => '<p>The <code>ENTRYPOINT</code> that is passed to the container. For more information on the Docker <code>ENTRYPOINT</code> parameter, see <a href=\"https://docs.docker.com/reference/builder/#entrypoint\">https://docs.docker.com/reference/builder/#entrypoint</a>.</p>',\n 'ContainerDefinition$command' => '<p>The <code>CMD</code> that is passed to the container. For more information on the Docker <code>CMD</code> parameter, see <a href=\"https://docs.docker.com/reference/builder/#cmd\">https://docs.docker.com/reference/builder/#cmd</a>.</p>',\n 'ContainerOverride$command' => '<p>The command to send to the container that receives the override.</p>',\n 'DescribeClustersRequest$clusters' => '<p>A space-separated list of cluster names or full cluster Amazon Resource Name (ARN] entries. If you do not specify a cluster, the default cluster is assumed.</p>',\n 'DescribeContainerInstancesRequest$containerInstances' => '<p>A space-separated list of container instance UUIDs or full Amazon Resource Name (ARN] entries.</p>',\n 'DescribeTasksRequest$tasks' => '<p>A space-separated list of task UUIDs or full Amazon Resource Name (ARN] entries.</p>',\n 'ListClustersResponse$clusterArns' => '<p>The list of full Amazon Resource Name (ARN] entries for each cluster associated with your account.</p>',\n 'ListContainerInstancesResponse$containerInstanceArns' => '<p>The list of container instance full Amazon Resource Name (ARN] entries for each container instance associated with the specified cluster.</p>',\n 'ListTaskDefinitionsResponse$taskDefinitionArns' => '<p>The list of task definition Amazon Resource Name (ARN] entries for the <code>ListTaskDefintions</code> request.</p>',\n 'ListTasksResponse$taskArns' => '<p>The list of task Amazon Resource Name (ARN] entries for the <code>ListTasks</code> request.</p>',\n 'Resource$stringSetValue' => '<p>When the <code>stringSetValue</code> type is set, the value of the resource must be a string type.</p>',\n 'StartTaskRequest$containerInstances' => '<p>The container instance UUIDs or full Amazon Resource Name (ARN] entries for the container instances on which you would like to place your task.</p>',\n ],\n ],\n 'SubmitContainerStateChangeRequest' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'SubmitContainerStateChangeResponse' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'SubmitTaskStateChangeRequest' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'SubmitTaskStateChangeResponse' => [\n 'base' => NULL,\n 'refs' => [],\n ],\n 'Task' => [\n 'base' => NULL,\n 'refs' => [\n 'StopTaskResponse$task' => NULL,\n 'Tasks$member' => NULL,\n ],\n ],\n 'TaskDefinition' => [\n 'base' => NULL,\n 'refs' => [\n 'DeregisterTaskDefinitionResponse$taskDefinition' => '<p>The full description of the deregistered task.</p>',\n 'DescribeTaskDefinitionResponse$taskDefinition' => '<p>The full task definition description.</p>',\n 'RegisterTaskDefinitionResponse$taskDefinition' => NULL,\n ],\n ],\n 'TaskOverride' => [\n 'base' => NULL,\n 'refs' => [\n 'RunTaskRequest$overrides' => NULL,\n 'StartTaskRequest$overrides' => NULL,\n 'Task$overrides' => '<p>One or more container overrides.</p>',\n ],\n ],\n 'Tasks' => [\n 'base' => NULL,\n 'refs' => [\n 'DescribeTasksResponse$tasks' => '<p>The list of tasks.</p>',\n 'RunTaskResponse$tasks' => '<p>A full description of the tasks that were run. Each task that was successfully placed on your cluster will be described here.</p>',\n 'StartTaskResponse$tasks' => '<p>A full description of the tasks that were started. Each task that was successfully placed on your container instances will be described here.</p>',\n ],\n ],\n ],\n];\n" }, { "alpha_fraction": 0.5350539088249207, "alphanum_fraction": 0.5450693368911743, "avg_line_length": 28.16853904724121, "blob_id": "e5a2fb68423796c5a8c9c48ef828692060d698c5", "content_id": "2e3e7eff42e457e2e2624ceedc191e80ab2e25b0", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2596, "license_type": "permissive", "max_line_length": 75, "num_lines": 89, "path": "/tests/Integ/S3MultipartTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Integ\\Multipart;\n\nuse Aws\\Exception\\MultipartUploadException;\nuse Aws\\S3\\ClearBucket;\nuse Aws\\S3\\UploadBuilder;\nuse Aws\\Test\\Integ\\IntegUtils;\nuse GuzzleHttp\\Stream\\NoSeekStream;\nuse GuzzleHttp\\Stream\\Stream;\n\nclass S3Multipart extends \\PHPUnit_Framework_TestCase\n{\n use IntegUtils;\n\n const MB = 1048576;\n const BUCKET = 'php-integ-s3multipart-test';\n\n public static function setUpBeforeClass()\n {\n $client = self::getSdk()->getS3();\n if (!$client->doesBucketExist(self::BUCKET)) {\n $client->createBucket(['Bucket' => self::BUCKET]);\n $client->waitUntil('BucketExists', ['Bucket' => self::BUCKET]);\n }\n }\n\n public static function tearDownAfterClass()\n {\n $client = self::getSdk()->getS3();\n (new ClearBucket($client, self::BUCKET))->clear();\n $client->deleteBucket(['Bucket' => self::BUCKET]);\n }\n\n public function useCasesProvider()\n {\n return [\n ['SeekableSerialUpload', true, 1],\n ['NonSeekableSerialUpload', false, 3],\n ['SeekableConcurrentUpload', true, 1],\n ['NonSeekableConcurrentUpload', false, 3],\n ];\n }\n\n /**\n * @param string $key\n * @param bool $seekable\n * @param int $concurrency\n * @dataProvider useCasesProvider\n */\n public function testMultipartUpload($key, $seekable, $concurrency)\n {\n // Create a temp file\n $client = self::getSdk()->getS3();\n $tmpFile = sys_get_temp_dir() . '/aws-php-sdk-integ-s3-mup';\n file_put_contents($tmpFile, str_repeat('x', 10 * self::MB + 1024));\n\n // Create a stream\n $stream = Stream::factory(fopen($tmpFile, 'r'));\n if (!$seekable) {\n $stream = new NoSeekStream($stream);\n }\n\n // Create the uploader\n $uploader = (new UploadBuilder)\n ->setClient($client)\n ->setBucket(self::BUCKET)\n ->setKey($key)\n ->setSource($stream)\n ->setPartSize(5 * self::MB)\n ->build();\n\n // Perform the upload\n try {\n $result = $uploader->upload($concurrency);\n $this->assertArrayHasKey('ObjectURL', $result);\n } catch (MultipartUploadException $e) {\n $uploader->abort();\n $message = \"=====\\n\";\n while ($e) {\n $message .= $e->getMessage() . \"\\n\";\n $e = $e->getPrevious();\n }\n $message .= \"=====\\n\";\n $this->fail($message);\n }\n\n @unlink($tmpFile);\n }\n}\n" }, { "alpha_fraction": 0.6738461256027222, "alphanum_fraction": 0.6769230961799622, "avg_line_length": 27.2608699798584, "blob_id": "fde0ce487c0857b23a6e3c64f82f60d9c5837eb6", "content_id": "a1236d1b1d3e5250f593e89be425a5360308d014", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 650, "license_type": "permissive", "max_line_length": 73, "num_lines": 23, "path": "/tests/Signature/AbstractSignatureTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Signature;\n\nuse Aws\\Credentials\\Credentials;\nuse GuzzleHttp\\Message\\Request;\n\n/**\n * @covers Aws\\Signature\\AbstractSignature\n */\nclass AbstractSignatureTest extends \\PHPUnit_Framework_TestCase\n{\n /**\n * @expectedException \\BadMethodCallException\n */\n public function testThrowsWhenNotImplemented()\n {\n $mock = $this->getMockBuilder('Aws\\Signature\\AbstractSignature')\n ->getMockForAbstractClass();\n $request = new Request('GET', 'http://foo.com');\n $credentials = new Credentials('foo', 'bar');\n $mock->createPresignedUrl($request, $credentials, '+10 minutes');\n }\n}\n" }, { "alpha_fraction": 0.6476964950561523, "alphanum_fraction": 0.6476964950561523, "avg_line_length": 24.44827651977539, "blob_id": "6d4756bd23f49be128ec0dda6411cc3cff4039d7", "content_id": "723118b3429b3fe120be03567b230924400b8377", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 738, "license_type": "permissive", "max_line_length": 67, "num_lines": 29, "path": "/src/Sqs/QueueUrlSubscriber.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Sqs;\n\nuse GuzzleHttp\\Command\\Event\\PreparedEvent;\nuse GuzzleHttp\\Event\\RequestEvents;\nuse GuzzleHttp\\Event\\SubscriberInterface;\nuse GuzzleHttp\\Url;\n\n/**\n * Listener used to change the endpoint to the queue URL\n */\nclass QueueUrlSubscriber implements SubscriberInterface\n{\n public function getEvents()\n {\n return ['prepared' => ['onPrepared', RequestEvents::LATE]];\n }\n\n public function onPrepared(PreparedEvent $event)\n {\n $command = $event->getCommand();\n\n if ($command->hasParam('QueueUrl')) {\n $request = $event->getRequest();\n $url = Url::fromString($request->getUrl());\n $request->setUrl($url->combine($command['QueueUrl']));\n }\n }\n}\n" }, { "alpha_fraction": 0.5448392629623413, "alphanum_fraction": 0.5482233762741089, "avg_line_length": 24.69565200805664, "blob_id": "812821b2efc65b9ef8ee1b48069252a85a543ce5", "content_id": "3d640eb18e5dda42c99d6b5025910b61f148e422", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 591, "license_type": "permissive", "max_line_length": 79, "num_lines": 23, "path": "/src/Api/ErrorParser/JsonParserTrait.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Api\\ErrorParser;\n\nuse GuzzleHttp\\Message\\ResponseInterface;\n\n/**\n * Provides basic JSON error parsing functionality.\n */\ntrait JsonParserTrait\n{\n private function genericHandler(ResponseInterface $response)\n {\n $code = (string) $response->getStatusCode();\n\n return [\n 'request_id' => (string) $response->getHeader('x-amzn-requestid'),\n 'code' => null,\n 'message' => null,\n 'type' => $code[0] == '4' ? 'client' : 'server',\n 'parsed' => $response->json()\n ];\n }\n}\n" }, { "alpha_fraction": 0.5482190251350403, "alphanum_fraction": 0.5489768981933594, "avg_line_length": 30.04705810546875, "blob_id": "a7549a7e4f422850648d9321ddc32b8296bec0ef", "content_id": "414bc43a3538a637d5a4d324b3ee002084acf343", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 10556, "license_type": "permissive", "max_line_length": 84, "num_lines": 340, "path": "/src/Waiter.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws;\n\nuse GuzzleHttp\\Command\\Event\\PreparedEvent;\nuse GuzzleHttp\\Command\\Event\\ProcessEvent;\nuse GuzzleHttp\\Ring\\Future\\BaseFutureTrait;\nuse GuzzleHttp\\Ring\\Future\\FutureInterface;\nuse React\\Promise\\Deferred;\n\n/**\n * A \"waiter\" associated with an AWS resource (e.g., EC2 instance) that polls\n * the resource and waits until the resource is in a particular state.\n *\n * The configuration for the waiter must include information about the operation\n * and the conditions for wait completion. Waiters can be used in a blocking or\n * non-blocking manner and implement the same future/promise characteristics\n * that normal operations do.\n */\nclass Waiter implements FutureInterface\n{\n use BaseFutureTrait {\n BaseFutureTrait::wait as parentWait;\n }\n\n /** @var AwsClientInterface Client used to execute each attempt. */\n private $client;\n\n /** @var string Name of the waiter. */\n private $name;\n\n /** @var array Params to use with each attempt operation. */\n private $args;\n\n /** @var array Waiter configuration. */\n private $config;\n\n /** @var int The number of the current attempt to poll the resource. */\n private $attempt;\n\n /** @var Deferred Represents the async state of the waiter. */\n private $deferred;\n\n /** @var callable Callback executed when attempt response is processed. */\n private $processfn;\n\n /** @var FutureResult Future of the most recent attempt. */\n private $currentFuture;\n\n /** @var array Default configuration options. */\n private static $defaults = [\n 'initDelay' => 0,\n 'retry' => null,\n ];\n\n /** @var array Required configuration options. */\n private static $required = [\n 'acceptors',\n 'delay',\n 'maxAttempts',\n 'operation',\n ];\n\n /**\n * @param AwsClientInterface $client Client used to execute commands.\n * @param string $name Waiter name.\n * @param array $args Arguments for command.\n * @param array $config Waiter config that overrides defaults.\n *\n * @throws \\InvalidArgumentException if the configuration is incomplete.\n */\n public function __construct(\n AwsClientInterface $client,\n $name,\n array $args = [],\n array $config = []\n ) {\n // Set the necessary items to configure the waiter.\n $this->client = $client;\n $this->name = $name;\n $this->args = $args;\n $this->config = $config + self::$defaults;\n foreach (self::$required as $key) {\n if (!isset($this->config[$key])) {\n throw new \\InvalidArgumentException(\n 'The provided waiter configuration was incomplete.'\n );\n }\n }\n if (isset($this->config['retry']) && !is_callable($this->config['retry'])) {\n throw new \\InvalidArgumentException(\n 'The provided \"retry\" callback is not callable.'\n );\n }\n\n // Configure the asynchronous behavior.\n $this->deferred = new Deferred();\n $this->wrappedPromise = $this->deferred->promise();\n\n // Setup callbacks.\n $this->processfn = $this->getProcessFn();\n $this->waitfn = function () {\n // If doing a blocking wait, just do attempts in a loop.\n while (!$this->isRealized\n && $this->attempt < $this->config['maxAttempts']\n ) {\n $this->pollResource();\n }\n };\n $this->cancelfn = function () {\n if ($this->currentFuture instanceof FutureInterface) {\n $this->currentFuture->cancel();\n }\n };\n\n // If async, begin waiting.\n if (!empty($this->args['@future'])) {\n $this->pollResource();\n }\n }\n\n public function wait()\n {\n $this->args['@future'] = false;\n if ($this->currentFuture instanceof FutureInterface) {\n $this->currentFuture->wait();\n }\n return $this->parentWait();\n }\n\n /**\n * Returns a callback function that will be called during the \"process\"\n * event of every attempt of polling the resource.\n *\n * @return callable\n */\n private function getProcessFn()\n {\n return function (ProcessEvent $event) {\n $state = $this->determineState($event);\n if ($state === 'success') {\n $this->deferred->resolve($event->getResult());\n } elseif ($state === 'failed') {\n $this->deferred->reject(new \\RuntimeException(\n \"The {$this->name} waiter entered a failure state.\", 0,\n $event->getException()\n ));\n $event->setResult(true);\n } elseif ($this->attempt < $this->config['maxAttempts']) {\n if ($this->config['retry']) {\n $this->config['retry']($this->attempt);\n }\n if ($this->args['@future'] === true) {\n $this->deferred->progress($this->attempt);\n $this->pollResource();\n }\n } else {\n $this->deferred->reject(new \\RuntimeException(\n \"Waiter failed after the attempt #{$this->attempt}.\"\n ));\n }\n };\n }\n\n /**\n * Executes the command that polls the status of the resource to see if the\n * waiter can stop waiting.\n */\n private function pollResource()\n {\n // If the waiter's future is realized, do not make any more attempts.\n if ($this->isRealized) {\n return;\n }\n\n $this->attempt++;\n\n // Create the command use to check the resource's status\n $command = $this->client->getCommand(\n $this->config['operation'],\n $this->args\n );\n\n // Add listeners to set delay for and process results of the attempt.\n $emitter = $command->getEmitter();\n $emitter->on('process', $this->processfn, 'last');\n if ($delayFn = $this->getDelayFn()) {\n $emitter->on('prepared', $delayFn);\n }\n\n $this->currentFuture = $this->client->execute($command);\n }\n\n /**\n * Returns a callback function that will set the delay of a request when\n * attached to a \"prepared\" event.\n *\n * @return callable|null\n */\n private function getDelayFn()\n {\n // Get the configured delay for this attempt.\n $delay = ($this->attempt === 1)\n ? $this->config['initDelay']\n : $this->config['delay'];\n if (is_callable($delay)) {\n $delay = $delay($this->attempt);\n }\n\n // Set the delay as a request config option so it is managed at the\n // HTTP adapter layer in a potentially concurrent way.\n if ($delay) {\n return function (PreparedEvent $event) use ($delay) {\n $delay *= 1000; // RingPHP expects delay in milliseconds.\n $event->getRequest()->getConfig()->set('delay', $delay);\n };\n }\n\n return null;\n }\n\n /**\n * Determines the state of the waiter attempt, based on the result of\n * polling the resource. A waiter can have the state of \"success\", \"failed\",\n * or \"retry\".\n *\n * @param ProcessEvent $event\n *\n * @return string Will be \"success\", \"failed\", or \"retry\"\n */\n private function determineState(ProcessEvent $event)\n {\n foreach ($this->config['acceptors'] as $acceptor) {\n $matcher = 'matches' . ucfirst($acceptor['matcher']);\n if ($this->{$matcher}($event, $acceptor)) {\n return $acceptor['state'];\n }\n }\n\n return $event->getException() ? 'failed' : 'retry';\n }\n\n /**\n * @param ProcessEvent $event Process event of the attempt.\n * @param array $acceptor Acceptor configuration being checked.\n *\n * @return bool\n */\n private function matchesPath(ProcessEvent $event, array $acceptor)\n {\n if (!$event->getResult()) {\n return false;\n }\n\n $actual = $event->getResult()->search($acceptor['argument']);\n\n return $acceptor['expected'] == $actual;\n }\n\n /**\n * @param ProcessEvent $event Process event of the attempt.\n * @param array $acceptor Acceptor configuration being checked.\n *\n * @return bool\n */\n private function matchesPathAll(ProcessEvent $event, array $acceptor)\n {\n if (!$event->getResult()) {\n return false;\n }\n\n $actuals = $event->getResult()->search($acceptor['argument']) ?: [];\n foreach ($actuals as $actual) {\n if ($actual != $acceptor['expected']) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * @param ProcessEvent $event Process event of the attempt.\n * @param array $acceptor Acceptor configuration being checked.\n *\n * @return bool\n */\n private function matchesPathAny(ProcessEvent $event, array $acceptor)\n {\n if (!$event->getResult()) {\n return false;\n }\n\n $actuals = $event->getResult()->search($acceptor['argument']) ?: [];\n foreach ($actuals as $actual) {\n if ($actual == $acceptor['expected']) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * @param ProcessEvent $event Process event of the attempt.\n * @param array $acceptor Acceptor configuration being checked.\n *\n * @return bool\n */\n private function matchesStatus(ProcessEvent $event, array $acceptor)\n {\n if (!$event->getResponse()) {\n return false;\n }\n\n return $acceptor['expected'] == $event->getResponse()->getStatusCode();\n }\n\n /**\n * @param ProcessEvent $event Process event of the attempt.\n * @param array $acceptor Acceptor configuration being checked.\n *\n * @return bool\n */\n private function matchesError(ProcessEvent $event, array $acceptor)\n {\n /** @var \\Aws\\Exception\\AwsException $exception */\n $exception = $event->getException();\n if (!$exception) {\n return false;\n }\n\n $actual = $exception->getAwsErrorCode();\n if ($actual == $acceptor['expected']) {\n $event->setResult(true); // a.k.a do not throw the exception.\n return true;\n }\n\n return false;\n }\n}\n" }, { "alpha_fraction": 0.6803030371665955, "alphanum_fraction": 0.6886363625526428, "avg_line_length": 34.67567443847656, "blob_id": "ec013925e2d96c31e6b620c80c1ad499350a501b", "content_id": "e1cacfe10033023987b8572bb4fee8d34e3821a2", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1320, "license_type": "permissive", "max_line_length": 113, "num_lines": 37, "path": "/src/Retry/S3TimeoutFilter.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Retry;\n\nuse GuzzleHttp\\Event\\AbstractTransferEvent;\nuse GuzzleHttp\\Subscriber\\Retry\\RetrySubscriber;\n\n/**\n * Custom S3 exponential backoff checking use to retry 400 responses containing\n * the following reason phrase: \"Your socket connection to the server was not\n * read from or written to within the timeout period.\".\n *\n * This error has been reported as intermittent/random, and in most cases,\n * seems to occur during the middle of a transfer. This plugin will attempt to\n * retry these failed requests, and if using a local file, will clear the stat\n * cache of the file and set a new content-length header on the upload.\n */\nclass S3TimeoutFilter\n{\n const ERR = 'Your socket connection to the server was not read from or written to within the timeout period';\n\n public function __invoke($retries, AbstractTransferEvent $event)\n {\n // Don't mess with networking errors.\n if (!($response = $event->getResponse())) {\n return RetrySubscriber::DEFER;\n }\n\n // Only retry 400 errors that contain the targeted exception message.\n if ($response->getStatusCode() != 400 ||\n strpos($response->getBody(), self::ERR) === false\n ) {\n return RetrySubscriber::DEFER;\n }\n\n return RetrySubscriber::RETRY;\n }\n}\n" }, { "alpha_fraction": 0.739130437374115, "alphanum_fraction": 0.739130437374115, "avg_line_length": 19.44444465637207, "blob_id": "8e37e517c26971dae918f07bf6a7761c3d1ab394", "content_id": "f62b3619db020b534429c4b4dc51dfd658d33f66", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 184, "license_type": "permissive", "max_line_length": 74, "num_lines": 9, "path": "/src/ImportExport/ImportExportClient.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\ImportExport;\n\nuse Aws\\AwsClient;\n\n/**\n * This client is used to interact with the **AWS Import/Export** service.\n */\nclass ImportExportClient extends AwsClient {}\n" }, { "alpha_fraction": 0.5236051678657532, "alphanum_fraction": 0.5236051678657532, "avg_line_length": 22.299999237060547, "blob_id": "e557e6d673d79a38ad2d4d33120595574fb397ec", "content_id": "4a36e81d9704b970af1167f06ee8933d622843a6", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 233, "license_type": "permissive", "max_line_length": 43, "num_lines": 10, "path": "/src/data/config-2014-10-17.paginators.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php return [\n 'pagination' => [\n 'GetResourceConfigHistory' => [\n 'input_token' => 'nextToken',\n 'output_token' => 'nextToken',\n 'limit_key' => 'limit',\n 'result_key' => 'configurationItems',\n ],\n ],\n];\n" }, { "alpha_fraction": 0.556235671043396, "alphanum_fraction": 0.5883703231811523, "avg_line_length": 29.87401580810547, "blob_id": "87b3e0c87a5c92cc8a5c9f336f2f47f02bb13f43", "content_id": "65816ff382c7d95234408a7abc61ae56cd4687ce", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3921, "license_type": "permissive", "max_line_length": 74, "num_lines": 127, "path": "/tests/Signature/S3SignatureV4Test.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Signature;\n\nuse Aws\\Credentials\\Credentials;\nuse Aws\\Signature\\S3SignatureV4;\nuse GuzzleHttp\\Message\\Request;\nuse GuzzleHttp\\Stream\\Stream;\n\nrequire __DIR__ . '/sig_hack.php';\n\n/**\n * @covers Aws\\Signature\\S3SignatureV4\n */\nclass S3SignatureV4Test extends \\PHPUnit_Framework_TestCase\n{\n public static function setUpBeforeClass()\n {\n $_SERVER['aws_time'] = strtotime('December 5, 2013 00:00:00 UTC');\n }\n\n private function getFixtures()\n {\n $request = new Request('GET', 'http://foo.com');\n $credentials = new Credentials('foo', 'bar');\n $signature = new S3SignatureV4('service', 'region');\n\n return array($request, $credentials, $signature);\n }\n\n public function testAlwaysAddsContentSha256()\n {\n list($request, $credentials, $signature) = $this->getFixtures();\n $signature->signRequest($request, $credentials);\n $this->assertEquals(\n hash('sha256', ''),\n $request->getHeader('x-amz-content-sha256')\n );\n }\n\n public function testAddsContentSha256WhenBodyIsPresent()\n {\n $request = new Request('PUT', 'http://foo.com');\n $request->setBody(Stream::factory('foo'));\n $credentials = new Credentials('foo', 'bar');\n $signature = new S3SignatureV4('service', 'region');\n $signature->signRequest($request, $credentials);\n $this->assertEquals(\n hash('sha256', 'foo'),\n $request->getHeader('x-amz-content-sha256')\n );\n }\n\n public function testDoesNotRemoveDotSegments()\n {\n list($request, $credentials, $signature) = $this->getFixtures();\n $request->setPath('/.././foo');\n $signature->signRequest($request, $credentials);\n $context = $request->getConfig()->get('aws.signature');\n $this->assertStringStartsWith(\n \"GET\\n/.././foo\",\n $context['creq']\n );\n }\n\n public function testCreatesPresignedDatesFromDateTime()\n {\n list($request, $credentials, $signature) = $this->getFixtures();\n $url = $signature->createPresignedUrl(\n $request,\n $credentials,\n new \\DateTime('December 11, 2013 00:00:00 UTC')\n );\n $this->assertContains('X-Amz-Expires=518400', $url);\n }\n\n public function testCreatesPresignedDatesFromUnixTimestamp()\n {\n list($request, $credentials, $signature) = $this->getFixtures();\n $url = $signature->createPresignedUrl(\n $request,\n $credentials,\n 1386720000\n );\n $this->assertContains('X-Amz-Expires=518400', $url);\n }\n\n public function testCreatesPresignedDateFromStrtotime()\n {\n list($request, $credentials, $signature) = $this->getFixtures();\n $url = $signature->createPresignedUrl(\n $request,\n $credentials,\n 'December 11, 2013 00:00:00 UTC'\n );\n $this->assertContains('X-Amz-Expires=518400', $url);\n }\n\n public function testAddsSecurityTokenIfPresent()\n {\n list($request, $credentials, $signature) = $this->getFixtures();\n $credentials = new Credentials(\n $credentials->getAccessKeyId(),\n $credentials->getSecretKey(),\n '123'\n );\n $url = $signature->createPresignedUrl(\n $request,\n $credentials,\n 1386720000\n );\n $this->assertContains('X-Amz-Security-Token=123', $url);\n $this->assertContains('X-Amz-Expires=518400', $url);\n }\n\n /**\n * @expectedException \\InvalidArgumentException\n */\n public function testEnsuresSigV4DurationIsLessThanOneWeek()\n {\n list($request, $credentials, $signature) = $this->getFixtures();\n $signature->createPresignedUrl(\n $request,\n $credentials,\n 'December 31, 2026 00:00:00 UTC'\n );\n }\n}\n" }, { "alpha_fraction": 0.6756701469421387, "alphanum_fraction": 0.6882033944129944, "avg_line_length": 42.439998626708984, "blob_id": "deb3f2dfc5ae01a0e335dc26a7a45e8d447b72f9", "content_id": "72125787dcb996633076307c0ac00bebf3cb21bf", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 19548, "license_type": "permissive", "max_line_length": 124, "num_lines": 450, "path": "/docs/service-s3.rst", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "===============\nAmazon S3 Guide\n===============\n\nCreating a bucket\n-----------------\n\nNow that we've created a client object, let's create a bucket. This bucket will be used throughout the remainder of this\nguide.\n\n.. S3/Integration/S3_20060301_Test.php testBucketAlreadyExists\n\nIf you run the above code example unaltered, you'll probably trigger the following exception::\n\n PHP Fatal error: Uncaught Aws\\S3\\Exception\\BucketAlreadyExistsException: AWS Error\n Code: BucketAlreadyExists, Status Code: 409, AWS Request ID: D94E6394791E98A4,\n AWS Error Type: client, AWS Error Message: The requested bucket name is not\n available. The bucket namespace is shared by all users of the system. Please select\n a different name and try again.\n\nThis is because bucket names in Amazon S3 reside in a global namespace. You'll need to change the actual name of the\nbucket used in the examples of this tutorial in order for them to work correctly.\n\nCreating a bucket in another region\n-----------------------------------\n\nThe above example creates a bucket in the standard US-EAST-1 region. You can change the bucket location by passing a\n``LocationConstraint`` value.\n\n.. S3/Integration/S3_20060301_Test.php testCreateBucketInRegion\n\nYou'll notice in the above example that we are using the ``Aws\\Common\\Enum\\Region`` object to provide the ``US_WEST_2``\nconstant. The SDK provides various Enum classes under the ``Aws\\Common\\Enum`` namespace that can be useful for\nremembering available values and ensuring you do not enter a typo.\n\n.. note::\n\n Using the enum classes is not required. You could just pass 'us-west-2' in the ``LocationConstraint`` key.\n\nWaiting until the bucket exists\n-------------------------------\n\nNow that we've created a bucket, let's force our application to wait until the bucket exists. This can be done easily\nusing a *waiter*. The following snippet of code will poll the bucket until it exists or the maximum number of\npolling attempts are completed.\n\n.. S3/Integration/S3_20060301_Test.php testWaitUntilBucketExists\n\nUploading objects\n-----------------\n\nNow that you've created a bucket, let's put some data in it. The following example creates an object in your bucket\ncalled data.txt that contains 'Hello!'.\n\n.. S3/Integration/S3_20060301_Test.php testPutObject\n\nThe AWS SDK for PHP will attempt to automatically determine the most appropriate Content-Type header used to store the\nobject. If you are using a less common file extension and your Content-Type header is not added automatically, you can\nadd a Content-Type header by passing a ``ContentType`` option to the operation.\n\nUploading a file\n~~~~~~~~~~~~~~~~\n\nThe above example uploaded text data to your object. You can alternatively upload the contents of a file by passing\nthe ``SourceFile`` option. Let's also put some metadata on the object.\n\n.. S3/Integration/S3_20060301_Test.php testPutObjectFromFile\n\nUploading from a stream\n~~~~~~~~~~~~~~~~~~~~~~~\n\nAlternatively, you can pass a resource returned from an ``fopen`` call to the ``Body`` parameter.\n\n.. S3/Integration/S3_20060301_Test.php testPutObjectFromStream\n\nBecause the AWS SDK for PHP is built around Guzzle, you can also pass an EntityBody object.\n\n.. S3/Integration/S3_20060301_Test.php testPutObjectFromEntityBody\n\nListing your buckets\n--------------------\n\nYou can list all of the buckets owned by your account using the ``listBuckets`` method.\n\n.. S3/Integration/S3_20060301_Test.php testListBuckets\n\nAll service operation calls using the AWS SDK for PHP return a ``Guzzle\\Service\\Resource\\Model`` object. This object\ncontains all of the data returned from the service in a normalized array like object. The object also contains a\n``get()`` method used to retrieve values from the model by name, and a ``getPath()`` method that can be used to\nretrieve nested values.\n\n.. S3/Integration/S3_20060301_Test.php testListBucketsWithGetPath\n\nListing objects in your buckets\n-------------------------------\n\nListing objects is a lot easier in the new SDK thanks to *iterators*. You can list all of the objects in a bucket using\nthe ``ListObjectsIterator``.\n\n.. S3/Integration/S3_20060301_Test.php testListObjectsWithIterator\n\nIterators will handle sending any required subsequent requests when a response is truncated. The ListObjects iterator\nworks with other parameters too.\n\n.. code-block:: php\n\n $iterator = $client->getIterator('ListObjects', array(\n 'Bucket' => $bucket,\n 'Prefix' => 'foo'\n ));\n\n foreach ($iterator as $object) {\n echo $object['Key'] . \"\\n\";\n }\n\nYou can convert any iterator to an array using the ``toArray()`` method of the iterator.\n\n.. note::\n\n Converting an iterator to an array will load the entire contents of the iterator into memory.\n\nDownloading objects\n-------------------\n\nYou can use the ``GetObject`` operation to download an object.\n\n.. S3/Integration/S3_20060301_Test.php testGetObject\n\nThe contents of the object are stored in the ``Body`` parameter of the model object. Other parameters are stored in\nmodel including ``ContentType``, ``ContentLength``, ``VersionId``, ``ETag``, etc...\n\nThe ``Body`` parameter stores a reference to a ``Guzzle\\Http\\EntityBody`` object. The SDK will store the data in a\ntemporary PHP stream by default. This will work for most use-cases and will automatically protect your application from\nattempting to download extremely large files into memory.\n\nThe EntityBody object has other nice features that allow you to read data using streams.\n\n.. S3/Integration/S3_20060301_Test.php testGetObjectUsingEntityBody\n\nSaving objects to a file\n~~~~~~~~~~~~~~~~~~~~~~~~\n\nYou can save the contents of an object to a file by setting the SaveAs parameter.\n\n.. S3/Integration/S3_20060301_Test.php testGetObjectWithSaveAs\n\nUploading large files using multipart uploads\n---------------------------------------------\n\nAmazon S3 allows you to uploads large files in pieces. The AWS SDK for PHP provides an abstraction layer that makes it\neasier to upload large files using multipart upload.\n\n.. code-block:: php\n\n use Aws\\Common\\Enum\\Size;\n use Aws\\Common\\Exception\\MultipartUploadException;\n use Aws\\S3\\Model\\MultipartUpload\\UploadBuilder;\n\n $uploader = UploadBuilder::newInstance()\n ->setClient($client)\n ->setSource('/path/to/large/file.mov')\n ->setBucket('mybucket')\n ->setKey('my-object-key')\n ->setOption('Metadata', array('Foo' => 'Bar'))\n ->setOption('CacheControl', 'max-age=3600')\n ->build();\n\n // Perform the upload. Abort the upload if something goes wrong\n try {\n $uploader->upload();\n echo \"Upload complete.\\n\";\n } catch (MultipartUploadException $e) {\n $uploader->abort();\n echo \"Upload failed.\\n\";\n }\n\nYou can attempt to upload parts in parallel by specifying the concurrency option on the UploadBuilder object. The\nfollowing example will create a transfer object that will attempt to upload three parts in parallel until the entire\nobject has been uploaded.\n\n.. code-block:: php\n\n $uploader = UploadBuilder::newInstance()\n ->setClient($client)\n ->setSource('/path/to/large/file.mov')\n ->setBucket('mybucket')\n ->setKey('my-object-key')\n ->setConcurrency(3)\n ->build();\n\nYou can use the ``Aws\\S3\\S3Client::upload()`` method if you just want to upload files and not worry if they are too\nlarge to send in a single PutObject operation or require a multipart upload.\n\n.. code-block:: php\n\n $client->upload('bucket', 'key', 'object body', 'public-read');\n\nSetting ACLs and Access Control Policies\n----------------------------------------\n\nYou can specify a canned ACL on an object when uploading:\n\n.. code-block:: php\n\n $client->putObject(array(\n 'Bucket' => 'mybucket',\n 'Key' => 'data.txt',\n 'SourceFile' => '/path/to/data.txt',\n 'ACL' => 'public-read'\n ));\n\nYou can use the ``Aws\\S3\\Enum\\CannedAcl`` object to provide canned ACL constants:\n\n.. code-block:: php\n\n use Aws\\S3\\Enum\\CannedAcl;\n\n $client->putObject(array(\n 'Bucket' => 'mybucket',\n 'Key' => 'data.txt',\n 'SourceFile' => '/path/to/data.txt',\n 'ACL' => CannedAcl::PUBLIC_READ\n ));\n\nYou can specify more complex ACLs using the ``ACP`` parameter when sending PutObject, CopyObject, CreateBucket,\nCreateMultipartUpload, PutBucketAcl, PutObjectAcl, and other operations that accept a canned ACL. Using the ``ACP``\nparameter allows you specify more granular access control policies using a ``Aws\\S3\\Model\\Acp`` object. The easiest\nway to create an Acp object is through the ``Aws\\S3\\Model\\AcpBuilder``.\n\n.. code-block:: php\n\n use Aws\\S3\\Enum\\Permission;\n use Aws\\S3\\Enum\\Group;\n use Aws\\S3\\Model\\AcpBuilder;\n\n $acp = AcpBuilder::newInstance()\n ->setOwner($myOwnerId)\n ->addGrantForEmail(Permission::READ, '[email protected]')\n ->addGrantForUser(Permission::FULL_CONTROL, 'user-id')\n ->addGrantForGroup(Permission::READ, Group::AUTHENTICATED_USERS)\n ->build();\n\n $client->putObject(array(\n 'Bucket' => 'mybucket',\n 'Key' => 'data.txt',\n 'SourceFile' => '/path/to/data.txt',\n 'ACP' => $acp\n ));\n\nCreating a pre-signed URL\n-------------------------\n\nYou can authenticate certain types of requests by passing the required information as query-string parameters instead\nof using the Authorization HTTP header. This is useful for enabling direct third-party browser access to your private\nAmazon S3 data, without proxying the request. The idea is to construct a \"pre-signed\" request and encode it as a URL\nthat an end-user's browser can retrieve. Additionally, you can limit a pre-signed request by specifying an expiration\ntime.\n\nThe most common scenario is creating a pre-signed URL to GET an object. The easiest way to do this is to use the\n``getObjectUrl`` method of the Amazon S3 client. This same method can also be used to get an unsigned URL of a public\nS3 object.\n\n.. S3/Integration/S3_20060301_Test.php testGetObjectUrl\n\nYou can also create pre-signed URLs for any Amazon S3 operation using the ``getCommand`` method for creating a Guzzle\ncommand object and then calling the ``createPresignedUrl()`` method on the command.\n\n.. S3/Integration/S3_20060301_Test.php testCreatePresignedUrlFromCommand\n\nIf you need more flexibility in creating your pre-signed URL, then you can create a pre-signed URL for a completely\ncustom ``Guzzle\\Http\\Message\\RequestInterface`` object. You can use the ``get()``, ``post()``, ``head()``, ``put()``,\nand ``delete()`` methods of a client object to easily create a Guzzle request object.\n\n.. S3/Integration/S3_20060301_Test.php testCreatePresignedUrl\n\nAmazon S3 stream wrapper\n------------------------\n\nThe Amazon S3 stream wrapper allows you to store and retrieve data from Amazon S3 using built-in PHP functions like\n``file_get_contents``, ``fopen``, ``copy``, ``rename``, ``unlink``, ``mkdir``, ``rmdir``, etc.\n\nSee :doc:`feature-s3-stream-wrapper`.\n\nSyncing data with Amazon S3\n---------------------------\n\nUploading a directory to a bucket\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nUploading a local directory to an Amazon S3 bucket is rather simple:\n\n.. code-block:: php\n\n $client->uploadDirectory('/local/directory', 'my-bucket');\n\nThe ``uploadDirectory()`` method of a client will compare the contents of the local directory to the contents in the\nAmazon S3 bucket and only transfer files that have changed. While iterating over the keys in the bucket and comparing\nagainst the names of local files using a customizable filename to key converter, the changed files are added to an in\nmemory queue and uploaded concurrently. When the size of a file exceeds a customizable ``multipart_upload_size``\nparameter, the uploader will automatically upload the file using a multipart upload.\n\nCustomizing the upload sync\n^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nThe method signature of the `uploadDirectory()` method allows for the following arguments:\n\n.. code-block:: php\n\n public function uploadDirectory($directory, $bucket, $keyPrefix = null, array $options = array())\n\nBy specifying ``$keyPrefix``, you can cause the uploaded objects to be placed under a virtual folder in the Amazon S3\nbucket. For example, if the ``$bucket`` name is ``my-bucket`` and the ``$keyPrefix`` is 'testing/', then your files\nwill be uploaded to ``my-bucket`` under the ``testing/`` virtual folder:\n``https://my-bucket.s3.amazonaws.com/testing/filename.txt``\n\nThe ``uploadDirectory()`` method also accepts an optional associative array of ``$options`` that can be used to further\ncontrol the transfer.\n\n=========== ============================================================================================================\nparams Array of parameters to use with each ``PutObject`` or ``CreateMultipartUpload`` operation performed during\n the transfer. For example, you can specify an ``ACL`` key to change the ACL of each uploaded object.\n See `PutObject <http://docs.aws.amazon.com/aws-sdk-php/latest/class-Aws.S3.S3Client.html#_putObject>`_\n for a list of available options.\nbase_dir Base directory to remove from each object key. By default, the ``$directory`` passed into the\n ``uploadDirectory()`` method will be removed from each object key.\nforce Set to true to upload every file, even if the file is already in Amazon S3 and has not changed.\nconcurrency Maximum number of parallel uploads (defaults to 5)\ndebug Set to true to enable debug mode to print information about each upload. Setting this value to an ``fopen``\n resource will write the debug output to a stream rather than to ``STDOUT``.\n=========== ============================================================================================================\n\nIn the following example, a local directory is uploaded with each object stored in the bucket using a ``public-read``\nACL, 20 requests are sent in parallel, and debug information is printed to standard output as each request is\ntransferred.\n\n.. code-block:: php\n\n $dir = '/local/directory';\n $bucket = 'my-bucket';\n $keyPrefix = '';\n\n $client->uploadDirectory($dir, $bucket, $keyPrefix, array(\n 'params' => array('ACL' => 'public-read'),\n 'concurrency' => 20,\n 'debug' => true\n ));\n\nMore control with the UploadSyncBuilder\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nThe ``uploadDirectory()`` method is an abstraction layer over the much more powerful ``Aws\\S3\\Sync\\UploadSyncBuilder``.\nYou can use an ``UploadSyncBuilder`` object directly if you need more control over the transfer. Using an\n``UploadSyncBuilder`` allows for the following advanced features:\n\n* Can upload only files that match a glob expression\n* Can upload only files that match a regular expression\n* Can specify a custom ``\\Iterator`` object to use to yield files to an ``UploadSync`` object. This can be used, for\n example, to filter out which files are transferred even further using something like the\n `Symfony 2 Finder component <http://symfony.com/doc/master/components/finder.html>`_.\n* Can specify the ``Aws\\S3\\Sync\\FilenameConverterInterface`` objects used to convert Amazon S3 object names to local\n filenames and vice versa. This can be useful if you require files to be renamed in a specific way.\n\n.. code-block:: php\n\n use Aws\\S3\\Sync\\UploadSyncBuilder;\n\n UploadSyncBuilder::getInstance()\n ->setClient($client)\n ->setBucket('my-bucket')\n ->setAcl('public-read')\n ->uploadFromGlob('/path/to/file/*.php')\n ->build()\n ->transfer();\n\nDownloading a bucket to a directory\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nYou can download the objects stored in an Amazon S3 bucket using features similar to the ``uploadDirectory()`` method\nand the ``UploadSyncBuilder``. You can download the entire contents of a bucket using the\n``Aws\\S3\\S3Client::downloadBucket()`` method.\n\nThe following example will download all of the objects from ``my-bucket`` and store them in ``/local/directory``.\nObject keys that are under virtual subfolders are converted into a nested directory structure when downloading the\nobjects. Any directories missing on the local filesystem will be created automatically.\n\n.. code-block:: php\n\n $client->downloadBucket('/local/directory', 'my-bucket');\n\nCustomizing the download sync\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nThe method signature of the ``downloadBucket()`` method allows for the following arguments:\n\n.. code-block:: php\n\n public function downloadBucket($directory, $bucket, $keyPrefix = null, array $options = array())\n\nBy specifying ``$keyPrefix``, you can limit the downloaded objects to only keys that begin with the specified\n``$keyPrefix``. This, for example, can be useful for downloading objects under a specific virtual directory.\n\nThe ``downloadBucket()`` method also accepts an optional associative array of ``$options`` that can be used to further\ncontrol the transfer.\n\n=============== ============================================================================================================\nparams Array of parameters to use with each ``GetObject`` operation performed during the transfer. See\n `GetObject <http://docs.aws.amazon.com/aws-sdk-php/latest/class-Aws.S3.S3Client.html#_getObject>`_\n for a list of available options.\nbase_dir Base directory to remove from each object key when downloading. By default, the entire object key is\n used to determine the path to the file on the local filesystem.\nforce Set to true to download every file, even if the file is already on the local filesystem and has not\n changed.\nconcurrency Maximum number of parallel downloads (defaults to 10)\ndebug Set to true to enable debug mode to print information about each download. Setting this value to an\n ``fopen`` resource will write the debug output to a stream rather than to ``STDOUT``.\nallow_resumable Set to true to allow previously interrupted downloads to be resumed using a Range GET\n=============== ============================================================================================================\n\nMore control with the DownloadSyncBuilder\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nThe ``downloadBucket()`` method is an abstraction layer over the much more powerful\n``Aws\\S3\\Sync\\DownloadSyncBuilder``. You can use a ``DownloadSyncBuilder`` object directly if you need more control\nover the transfer. Using the ``DownloadSyncBuilder`` allows for the following advanced features:\n\n* Can download only files that match a regular expression\n* Just like the ``UploadSyncBuilder``, you can specify a custom ``\\Iterator`` object to use to yield files to a\n ``DownloadSync`` object.\n* Can specify the ``Aws\\S3\\Sync\\FilenameConverterInterface`` objects used to convert Amazon S3 object names to local\n filenames and vice versa.\n\n.. code-block:: php\n\n use Aws\\S3\\Sync\\DownloadSyncBuilder;\n\n DownloadSyncBuilder::getInstance()\n ->setClient($client)\n ->setDirectory('/path/to/directory')\n ->setBucket('my-bucket')\n ->setKeyPrefix('/under-prefix')\n ->allowResumableDownloads()\n ->build()\n ->transfer();\n\nCleaning up\n-----------\n\nNow that we've taken a tour of how you can use the Amazon S3 client, let's clean up any resources we may have created.\n\n.. S3/Integration/S3_20060301_Test.php testCleanUpBucket\n" }, { "alpha_fraction": 0.5573961138725281, "alphanum_fraction": 0.5573961138725281, "avg_line_length": 25.674419403076172, "blob_id": "6f0f6a25ccd58e1c3fd5f70cfb60283a4ddb9f76", "content_id": "0ae6b48ae3615c1744c44c83a04538e4bff64b32", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3441, "license_type": "permissive", "max_line_length": 81, "num_lines": 129, "path": "/build/docs/classes/DocModel.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Build\\Docs;\n\nuse GuzzleHttp\\Collection;\nuse GuzzleHttp\\Utils;\n\n/**\n * Encapsulates the documentation strings for a given service-version and\n * provides methods for extracting the desired parts related to a service,\n * operation, error, or shape (i.e., parameter).\n *\n * @internal\n */\nclass DocModel\n{\n /** @var string */\n private $serviceName;\n\n /** @var string */\n private $apiVersion;\n\n /** @var Collection */\n private $docs;\n\n /**\n * @param string $docModelsDir\n * @param string $serviceName\n * @param string $apiVersion\n *\n * @throws \\RuntimeException\n */\n public function __construct($docModelsDir, $serviceName, $apiVersion)\n {\n if (!extension_loaded('tidy')) {\n throw new \\RuntimeException('The \"tidy\" PHP extension is required.');\n }\n\n $this->serviceName = $serviceName;\n $this->apiVersion = $apiVersion;\n\n $docModel = \"{$docModelsDir}/{$serviceName}-{$apiVersion}.docs.json\";\n if (!is_readable($docModel)) {\n throw new \\RuntimeException(\"The doc model for the {$apiVersion} \"\n . \"of {$serviceName} could not be loaded.\");\n }\n\n $this->docs = new Collection(\n Utils::jsonDecode(file_get_contents($docModel), true)\n );\n }\n\n /**\n * Retrieves documentation about the service.\n *\n * @return null|string\n */\n public function getServiceDocs()\n {\n return $this->getContent('service');\n }\n\n /**\n * Retrieves documentation about an operation.\n *\n * @param string $operation Name of the operation\n *\n * @return null|string\n */\n public function getOperationDocs($operation)\n {\n return $this->getContent(\"operations/{$operation}\");\n }\n\n /**\n * Retrieves documentation about an error.\n *\n * @param string $error Name of the error\n *\n * @return null|string\n */\n public function getErrorDocs($error)\n {\n return $this->getContent(\"shapes/{$error}/base\");\n }\n\n /**\n * Retrieves documentation about a shape, specific to the context.\n *\n * @param string $shapeName Name of the shape.\n * @param string $parentName Name of the parent/context shape.\n * @param string $ref Name used by the context to reference the shape.\n *\n * @return null|string\n */\n public function getShapeDocs($shapeName, $parentName, $ref)\n {\n $prefix = \"shapes/{$shapeName}\";\n return $this->getContent(\"{$prefix}/refs/{$parentName}\\${$ref}\")\n ?: $this->getContent(\"{$prefix}/base\");\n }\n\n /**\n * @param string $path A Guzzle getPath expression to evaluate on the model.\n *\n * @return null|string\n */\n private function getContent($path)\n {\n if ($content = $this->docs->getPath($path)) {\n $tidy = new \\Tidy();\n $tidy->parseString($content, [\n 'indent' => true,\n 'doctype' => 'omit',\n 'output-html' => true,\n 'show-body-only' => true,\n 'drop-empty-paras' => true,\n 'drop-font-tags' => true,\n 'drop-proprietary-attributes' => true,\n 'hide-comments' => true,\n 'logical-emphasis' => true\n ]);\n $tidy->cleanRepair();\n\n return (string) $content;\n }\n\n return null;\n }\n}\n" }, { "alpha_fraction": 0.618677020072937, "alphanum_fraction": 0.6316472291946411, "avg_line_length": 24.700000762939453, "blob_id": "bea6b3014798287ce34332e8ba0a15b177f21cab", "content_id": "196d02adebef88fa7c9647481aa68f05b437f85f", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 771, "license_type": "permissive", "max_line_length": 68, "num_lines": 30, "path": "/src/Retry/Crc32Filter.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Retry;\n\nuse GuzzleHttp\\Event\\AbstractTransferEvent;\nuse GuzzleHttp\\Subscriber\\Retry\\RetrySubscriber;\nuse GuzzleHttp\\Stream;\nuse GuzzleHttp\\Stream\\Utils;\n\n/**\n * Retries requests based on the x-amz-crc32 response header.\n */\nclass Crc32Filter\n{\n public function __invoke($retries, AbstractTransferEvent $event)\n {\n if (!($response = $event->getResponse())) {\n return RetrySubscriber::DEFER;\n }\n\n if (!$response->hasHeader('x-amz-crc32')) {\n return RetrySubscriber::DEFER;\n }\n\n $hash = hexdec(Utils::hash($response->getBody(), 'crc32b'));\n\n return (int) $response->getHeader('x-amz-crc32') !== $hash\n ? RetrySubscriber::RETRY\n : RetrySubscriber::DEFER;\n }\n}\n" }, { "alpha_fraction": 0.6171027421951294, "alphanum_fraction": 0.6171027421951294, "avg_line_length": 30.34000015258789, "blob_id": "273d4198e586ed7a4a84abd0605d29209811ae0e", "content_id": "3d6e2fa3fe8dc8605105ba12b0807d74cfe88d23", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3134, "license_type": "permissive", "max_line_length": 78, "num_lines": 100, "path": "/src/AwsClientInterface.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws;\n\nuse GuzzleHttp\\Command\\CommandInterface;\nuse GuzzleHttp\\Command\\ServiceClientInterface;\n\n/**\n * Represents an AWS client.\n */\ninterface AwsClientInterface extends ServiceClientInterface\n{\n /**\n * Returns the AWS credentials associated with the client.\n *\n * @return \\Aws\\Credentials\\CredentialsInterface\n */\n public function getCredentials();\n\n /**\n * Get the region to which the client is configured to send requests.\n *\n * @return string\n */\n public function getRegion();\n\n /**\n * Gets the default endpoint, or base URL, used by the client.\n *\n * @return string\n */\n public function getEndpoint();\n\n /**\n * Get the service description associated with the client.\n *\n * @return \\Aws\\Api\\Service\n */\n public function getApi();\n\n /**\n * Get a resource iterator for the specified operation.\n *\n * @param string $name Name of the iterator to retrieve.\n * @param array $args Command arguments to use with each command.\n *\n * @return \\Iterator\n * @throws \\UnexpectedValueException if the iterator config is invalid.\n */\n public function getIterator($name, array $args = []);\n\n /**\n * Get a result paginator for the specified operation.\n *\n * @param string $name Name of the operation used for iterator\n * @param array $args Command args to be used with each command\n * @param array $config Hash of paginator options.\n *\n * @return \\Aws\\ResultPaginator\n * @throws \\UnexpectedValueException if the iterator config is invalid.\n */\n public function getPaginator($name, array $args = [], array $config = []);\n\n /**\n * Wait until a resource is in a particular state.\n *\n * @param string|callable $name Name of the waiter that defines the wait\n * configuration and conditions.\n * @param array $args Args to be used with each command executed\n * by the waiter. Use `'@future' => true` to\n * make the waiter work asynchronously.\n * @param array $config Waiter configuration. Use this to override\n * the defaults for the specified waiter.\n *\n * @return \\Aws\\Waiter|void\n * @throws \\UnexpectedValueException if the waiter is invalid.\n */\n public function waitUntil($name, array $args = [], array $config = []);\n\n /**\n * Creates and executes a command for an operation by name.\n *\n * @param string $name Name of the command to execute.\n * @param array $arguments Arguments to pass to the getCommand method.\n *\n * @return ResultInterface\n * @throws \\Exception\n * @see \\GuzzleHttp\\Command\\ServiceClientInterface::getCommand\n */\n public function __call($name, array $arguments);\n\n /**\n * Execute a single command.\n *\n * @param CommandInterface $command Command to execute\n *\n * @return ResultInterface\n * @throws \\Exception\n */\n public function execute(CommandInterface $command);\n}\n" }, { "alpha_fraction": 0.5564032793045044, "alphanum_fraction": 0.5574932098388672, "avg_line_length": 23.144737243652344, "blob_id": "f92590fd048c1f6f294cf42363259520bfaee55d", "content_id": "46308f34b47a66c0b4954caa09be94d01051439c", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3670, "license_type": "permissive", "max_line_length": 79, "num_lines": 152, "path": "/src/Multipart/UploadState.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Multipart;\n\n/**\n * Representation of the multipart upload.\n *\n * This object keeps track of the state of the upload, including the status and\n * which parts have been uploaded.\n */\nclass UploadState\n{\n const CREATED = 0;\n const INITIATED = 1;\n const COMPLETED = 2;\n const ABORTED = 3;\n\n /** @var array Params used to identity the upload. */\n private $uploadId;\n\n /** @var int Part size being used by the upload. */\n private $partSize;\n\n /** @var array Parts that have been uploaded. */\n private $uploadedParts = [];\n\n /** @var int Identifies the status the upload. */\n private $status = self::CREATED;\n\n /**\n * @param array $uploadId\n */\n public function __construct(array $uploadId)\n {\n $this->uploadId = $uploadId;\n }\n\n /**\n * Get the upload's ID, which is a triad of parameters that can uniquely\n * identify the upload.\n *\n * @return array\n */\n public function getUploadId()\n {\n return $this->uploadId;\n }\n\n /**\n * Get the part size.\n *\n * @return int\n */\n public function getPartSize()\n {\n return $this->partSize;\n }\n\n /**\n * Set the part size.\n *\n * @param $partSize Size of upload parts.\n */\n public function setPartSize($partSize)\n {\n $this->partSize = $partSize;\n }\n\n /**\n * Marks a part as being uploaded.\n *\n * @param int $partNumber The part number.\n * @param array $partData Data from the upload operation that needs to be\n * recalled during the complete operation.\n */\n public function markPartAsUploaded($partNumber, array $partData = [])\n {\n $this->uploadedParts[$partNumber] = $partData;\n }\n\n /**\n * Returns whether a part has been uploaded.\n *\n * @param int $partNumber The part number.\n *\n * @return bool\n */\n public function hasPartBeenUploaded($partNumber)\n {\n return isset($this->uploadedParts[$partNumber]);\n }\n\n /**\n * Returns a sorted list of all the uploaded parts.\n *\n * @return array\n */\n public function getUploadedParts()\n {\n ksort($this->uploadedParts);\n\n return $this->uploadedParts;\n }\n\n /**\n * Set the status of the upload.\n *\n * @param int $status Status is an integer code defined by the\n * constants CREATED, INITIATED, COMPLETED, and\n * ABORTED defined on this class.\n * @param array $newUploadId An array representing an upload ID that you'd\n * like to set for this upload state at the time\n * of a status change. This is only when setting\n * the status to INITIATED.\n */\n public function setStatus($status, array $newUploadId = null)\n {\n $this->status = $status;\n if (is_array($newUploadId)) {\n $this->uploadId = $newUploadId;\n }\n }\n\n /**\n * Determines whether the upload state is in the INITIATED status.\n *\n * @return bool\n */\n public function isInitiated()\n {\n return $this->status >= self::INITIATED;\n }\n\n /**\n * Determines whether the upload state is in the ABORTED status.\n *\n * @return bool\n */\n public function isAborted()\n {\n return $this->status === self::ABORTED;\n }\n\n /**\n * Determines whether the upload state is in the COMPLETED status.\n *\n * @return bool\n */\n public function isCompleted()\n {\n return $this->status === self::COMPLETED;\n }\n}\n" }, { "alpha_fraction": 0.5496569871902466, "alphanum_fraction": 0.5534139275550842, "avg_line_length": 31.913978576660156, "blob_id": "f8f0c6c4d0adde8c38afce8b02e6356a85a22fa0", "content_id": "d4d6b2473c56d3ba16d88a6a791b206d56a23bd3", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 6122, "license_type": "permissive", "max_line_length": 80, "num_lines": 186, "path": "/src/Signature/S3Signature.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Signature;\n\nuse Aws\\Credentials\\CredentialsInterface;\nuse Aws\\S3\\S3Client;\nuse Aws\\S3\\S3UriParser;\nuse GuzzleHttp\\Message\\RequestInterface;\n\n/**\n * Default Amazon S3 signature implementation\n * @link http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html\n */\nclass S3Signature extends AbstractSignature\n{\n /** @var array Query string values that must be signed */\n private $signableQueryString = [\n 'acl', 'cors', 'delete', 'lifecycle', 'location', 'logging',\n 'notification', 'partNumber', 'policy', 'requestPayment',\n 'response-cache-control', 'response-content-disposition',\n 'response-content-encoding', 'response-content-language',\n 'response-content-type', 'response-expires', 'restore', 'tagging',\n 'torrent', 'uploadId', 'uploads', 'versionId', 'versioning',\n 'versions', 'website'\n ];\n\n /** @var array Sorted headers that must be signed */\n private $signableHeaders = ['Content-MD5', 'Content-Type'];\n\n /** @var \\Aws\\S3\\S3UriParser S3 URI parser */\n private $parser;\n\n public function __construct()\n {\n $this->parser = new S3UriParser();\n }\n\n public function signRequest(\n RequestInterface $request,\n CredentialsInterface $credentials\n ) {\n // Ensure that the signable query string parameters are sorted\n sort($this->signableQueryString);\n\n // Add the security token header if one is being used by the credentials\n if ($token = $credentials->getSecurityToken()) {\n $request->setHeader('X-Amz-Security-Token', $token);\n }\n\n // Add a date header if one is not set\n $request->removeHeader('X-Amz-Date');\n $request->setHeader('Date', gmdate(\\DateTime::RFC2822));\n $stringToSign = $this->createCanonicalizedString($request);\n $request->getConfig()['aws.signature'] = $stringToSign;\n\n $request->setHeader(\n 'Authorization',\n 'AWS ' . $credentials->getAccessKeyId() . ':'\n . $this->signString($stringToSign, $credentials)\n );\n }\n\n public function createPresignedUrl(\n RequestInterface $request,\n CredentialsInterface $credentials,\n $expires\n ) {\n // Operate on a clone of the request, so the original is not altered.\n $request = clone $request;\n\n // URL encoding already occurs in the URI template expansion. Undo that\n // and encode using the same encoding as GET object, PUT object, etc.\n $path = S3Client::encodeKey(rawurldecode($request->getPath()));\n $request->setPath($path);\n\n // Make sure to handle temporary credentials\n if ($token = $credentials->getSecurityToken()) {\n $request->setHeader('X-Amz-Security-Token', $token);\n $request->getQuery()->set('X-Amz-Security-Token', $token);\n }\n\n if ($expires instanceof \\DateTime) {\n $expires = $expires->getTimestamp();\n } elseif (!is_numeric($expires)) {\n $expires = strtotime($expires);\n }\n\n // Set query params required for pre-signed URLs\n $query = $request->getQuery();\n $query['AWSAccessKeyId'] = $credentials->getAccessKeyId();\n $query['Expires'] = $expires;\n $query['Signature'] = $this->signString(\n $this->createCanonicalizedString($request, $expires),\n $credentials\n );\n\n // Move X-Amz-* headers to the query string\n foreach ($request->getHeaders() as $name => $header) {\n $name = strtolower($name);\n if (strpos($name, 'x-amz-') === 0) {\n $request->getQuery()->set($name, implode(',', $header));\n $request->removeHeader($name);\n }\n }\n\n return $request->getUrl();\n }\n\n private function signString($string, CredentialsInterface $credentials)\n {\n return base64_encode(\n hash_hmac('sha1', $string, $credentials->getSecretKey(), true)\n );\n }\n\n private function createCanonicalizedString(\n RequestInterface $request,\n $expires = null\n ) {\n $buffer = $request->getMethod() . \"\\n\";\n\n // Add the interesting headers\n foreach ($this->signableHeaders as $header) {\n $buffer .= $request->getHeader($header) . \"\\n\";\n }\n\n $date = $expires ?: $request->getHeader('date');\n $buffer .= \"{$date}\\n\"\n . $this->createCanonicalizedAmzHeaders($request)\n . $this->createCanonicalizedResource($request);\n\n return $buffer;\n }\n\n private function createCanonicalizedAmzHeaders(RequestInterface $request)\n {\n $headers = [];\n foreach ($request->getHeaders() as $name => $header) {\n $name = strtolower($name);\n if (strpos($name, 'x-amz-') === 0) {\n $value = implode(',', $header);\n if (strlen($value) > 0) {\n $headers[$name] = $name . ':' . $value;\n }\n }\n }\n\n if (!$headers) {\n return '';\n }\n\n ksort($headers);\n\n return implode(\"\\n\", $headers) . \"\\n\";\n }\n\n private function createCanonicalizedResource(RequestInterface $request)\n {\n $data = $this->parser->parse($request->getUrl());\n $buffer = '/';\n\n if ($data['bucket']) {\n $buffer .= $data['bucket'];\n if (!empty($data['key']) || !$data['path_style']) {\n $buffer .= '/' . $data['key'];\n }\n }\n\n // Add sub resource parameters\n $query = $request->getQuery();\n $first = true;\n foreach ($this->signableQueryString as $key) {\n if ($query->hasKey($key)) {\n $value = $query[$key];\n $buffer .= $first ? '?' : '&';\n $first = false;\n $buffer .= $key;\n // Don't add values for empty sub-resources\n if (strlen($value)) {\n $buffer .= \"={$value}\";\n }\n }\n }\n\n return $buffer;\n }\n}\n" }, { "alpha_fraction": 0.5827006101608276, "alphanum_fraction": 0.5828031897544861, "avg_line_length": 29.74448013305664, "blob_id": "636f5f3a9d2ebdefa1562b31ad065a0b3ec8afe4", "content_id": "dbebb2aa4aef42d2e6b7ed1ffcbf1fe9b2a243dc", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 9746, "license_type": "permissive", "max_line_length": 86, "num_lines": 317, "path": "/src/Multipart/AbstractUploadBuilder.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Multipart;\n\nuse Aws\\AwsClientInterface;\nuse GuzzleHttp\\Stream\\LimitStream;\nuse GuzzleHttp\\Stream\\Stream;\nuse GuzzleHttp\\Stream\\StreamInterface;\n\n/**\n * Base class for the service-specific UploadBuilders\n *\n * @internal\n */\nabstract class AbstractUploadBuilder\n{\n /** @var array Set of three parameters required to identify an upload. */\n protected $uploadId = [];\n\n /** @var AwsClientInterface Client used to transfer requests. */\n protected $client;\n\n /** @var UploadState State of the transfer. */\n protected $state;\n\n /** @var StreamInterface Source of the data. */\n protected $source;\n\n /** @var int Size, in bytes, of each part. */\n protected $specifiedPartSize;\n\n /** @var array Service-specific configuration for uploader. */\n protected $config = [];\n\n /**\n * Sets up an empty upload identity.\n */\n public function __construct()\n {\n foreach ($this->config['id'] as $param) {\n $this->uploadId[$param] = null;\n }\n }\n\n /**\n * Set the client used to connect to the AWS service.\n *\n * @param AwsClientInterface $client Client to use\n *\n * @return static\n */\n public function setClient(AwsClientInterface $client)\n {\n $this->client = $client;\n\n return $this;\n }\n\n /**\n * Set the state of the upload. This is useful for resuming from a\n * previously started multipart upload. It is the responsibility to provide\n * the source that correlates to the provided state.\n *\n * @param UploadState $state Upload state to resume from.\n *\n * @return static\n */\n public function setState(UploadState $state)\n {\n $this->state = $state;\n\n return $this;\n }\n\n /**\n * Set the data source of the transfer.\n *\n * @param resource|string|StreamInterface $source Source of the upload.\n * Pass a string to transfer from a file on disk. You can also stream\n * from a resource returned from fopen or a Guzzle StreamInterface.\n *\n * @return static\n * @throws \\InvalidArgumentException when the source cannot be opened/read.\n */\n public function setSource($source)\n {\n // Use the contents of a file as the data source\n if (is_string($source)) {\n if (!file_exists($source)) {\n throw new \\InvalidArgumentException(\"File does not exist: {$source}\");\n }\n // Clear the cache so that we send accurate file sizes\n clearstatcache(true, $source);\n $source = fopen($source, 'r');\n }\n\n $this->source = Stream::factory($source);\n if (!$this->source->isReadable()) {\n throw new \\InvalidArgumentException('Source stream must be readable.');\n }\n\n return $this;\n }\n\n /**\n * Set the size of the upload parts.\n *\n * @param int $partSize Part size, in bytes.\n *\n * @return static\n */\n public function setPartSize($partSize)\n {\n $this->specifiedPartSize = $partSize;\n\n return $this;\n }\n\n /**\n * Set additional parameters to be used with an operation.\n *\n * @param string $operation Operation type to add parameters to. Should be\n * \"initiate\", \"upload\", \"complete\", or \"abort\".\n * @param array $params Parameters to include for the operation.\n *\n * @return static\n */\n public function addParams($operation, array $params)\n {\n foreach ($params as $key => $value) {\n $this->config[$operation]['params'][$key] = $value;\n }\n\n return $this;\n }\n\n /**\n * Build the uploader based on the provided configuration.\n *\n * @return Uploader\n */\n public function build()\n {\n // Determine the state, including the part size.\n $this->determineUploadState();\n\n // Prepare the parameters.\n $this->prepareParams();\n\n // Prepare the config.\n $this->config['fn'] = [\n 'complete' => $this->getCompleteParamsFn(),\n 'result' => $this->getResultHandlerFn()\n ];\n\n // Create an uploader object to encapsulate this upload.\n return new Uploader(\n $this->client,\n $this->state,\n $this->getPartGenerator($this->getCreatePartFn()),\n $this->config\n );\n }\n\n /**\n * Create a stream for a part that starts at the current position and\n * has a length of the upload part size (or less with the final part).\n *\n * @param StreamInterface $stream\n *\n * @return LimitStream\n */\n protected function limitPartStream(StreamInterface $stream)\n {\n // Limit what is read from the stream to the part size.\n return new LimitStream(\n $stream,\n $this->state->getPartSize(),\n $this->source->tell()\n );\n }\n\n /**\n * Creates an upload state by listing existing parts to assemble a state.\n *\n * @param array $params Parameters used to identify an upload.\n *\n * @return UploadState\n */\n abstract protected function loadStateByUploadId(array $params = []);\n\n /**\n * Performs service-specific logic to prepare parameters.\n */\n abstract protected function prepareParams();\n\n /**\n * Determines the part size to use for upload parts.\n *\n * Examines the provided partSize value and the source to determine the\n * best possible part size.\n *\n * @throws \\InvalidArgumentException if the part size is invalid.\n *\n * @return int\n */\n abstract protected function determinePartSize();\n\n /**\n * Creates a function used to generate an upload part's parameters.\n *\n * This function callable passed into PartGenerator and must analyze a range\n * of the source starting from the current offset up to the part size to\n * create a set of parameters that will be required to create an upload part\n * command. This should include a seekable stream, representing the analyzed\n * range, that will will be sent as the body.\n *\n * @return callable\n */\n abstract protected function getCreatePartFn();\n\n /**\n * Creates a service-specific callback function for getting the command\n * params for completing a multipart upload.\n *\n * @return callable\n */\n abstract protected function getCompleteParamsFn();\n\n /**\n * Creates a service-specific callback function that uses information from\n * the Command and Result to determine which part was uploaded and mark it\n * as uploaded in the upload's state.\n *\n * @return callable\n */\n abstract protected function getResultHandlerFn();\n\n /**\n * Determines the upload state using the provided upload params.\n *\n * @throws \\InvalidArgumentException if required upload params not included.\n */\n private function determineUploadState()\n {\n if (!($this->state instanceof UploadState)) {\n // Get the required and uploadId param names.\n $requiredParams = $this->config['id'];\n $uploadIdParam = array_pop($requiredParams);\n\n // Make sure that essential upload params are set.\n foreach ($requiredParams as $param) {\n if (!isset($this->uploadId[$param])) {\n throw new \\InvalidArgumentException('You must provide an '\n . $param . ' value to the UploadBuilder.');\n }\n }\n\n // Create a state from the upload params.\n if (isset($this->uploadId[$uploadIdParam])) {\n $this->state = $this->loadStateByUploadId($this->uploadId);\n } else {\n $this->state = new UploadState($this->uploadId);\n }\n }\n\n if (!$this->state->getPartSize()) {\n $this->state->setPartSize($this->determinePartSize());\n }\n }\n\n /**\n * Creates a generator that yields part data for the provided source.\n *\n * Yields associative arrays of parameters that are ultimately merged in\n * with others to form the complete parameters of an UploadPart (or\n * UploadMultipartPart for Glacier) command. This includes the Body\n * parameter, which is a limited stream (i.e., a Stream object, decorated\n * with a LimitStream).\n *\n * @param callable $createPart Service-specific logic for defining a part.\n *\n * @return \\Generator\n */\n private function getPartGenerator(callable $createPart)\n {\n // Determine if the source can be seeked.\n $seekable = $this->source->isSeekable()\n && $this->source->getMetadata('wrapper_type') === 'plainfile';\n\n for (\n $partNumber = 1;\n $seekable ?\n $this->source->tell() < $this->source->getSize() :\n !$this->source->eof();\n $partNumber++\n ) {\n // If we haven't already uploaded this part, yield a new part.\n if (!$this->state->hasPartBeenUploaded($partNumber)) {\n $partStartPos = $this->source->tell();\n yield $partNumber => $createPart($seekable, $partNumber);\n if ($this->source->tell() > $partStartPos) {\n continue;\n }\n }\n\n // Advance the source's offset if not already advanced.\n if ($seekable) {\n $this->source->seek(min(\n $this->source->tell() + $this->state->getPartSize(),\n $this->source->getSize()\n ));\n } else {\n $this->source->read($this->state->getPartSize());\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6303249001502991, "alphanum_fraction": 0.6303249001502991, "avg_line_length": 26.156862258911133, "blob_id": "1e8a016098d2ba72c8c180092250235d630684e9", "content_id": "82ae44c356761133fef8ca22cef9c2ef31aa20b5", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1385, "license_type": "permissive", "max_line_length": 78, "num_lines": 51, "path": "/src/Subscriber/Validation.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Subscriber;\n\nuse Aws\\Api\\Service;\nuse GuzzleHttp\\Command\\Event\\InitEvent;\nuse GuzzleHttp\\Event\\SubscriberInterface;\n\n/**\n * @internal Validates input before serializing\n */\nclass Validation implements SubscriberInterface\n{\n /** @var \\Aws\\Api\\Validator */\n private $validator;\n\n /** @var Service */\n private $api;\n\n /**\n * The provided validator function is a callable that accepts the\n * following positional arguments:\n *\n * - string, name of the operation\n * - Aws\\Api\\Shape, shape being validated against\n * - array, input data being validated\n *\n * The callable is expected to throw an \\InvalidArgumentException when the\n * provided input data does not match the shape.\n *\n * @param Service $api API being hit.\n * @param callable $validator Function used to validate input.\n */\n public function __construct(Service $api, callable $validator)\n {\n $this->validator = $validator;\n $this->api = $api;\n }\n\n public function getEvents()\n {\n return ['init' => ['onInit']];\n }\n\n public function onInit(InitEvent $event)\n {\n $command = $event->getCommand();\n $operation = $this->api->getOperation($command->getName());\n $fn = $this->validator;\n $fn($command->getName(), $operation->getInput(), $command->toArray());\n }\n}\n" }, { "alpha_fraction": 0.5714995265007019, "alphanum_fraction": 0.5714995265007019, "avg_line_length": 19.5510196685791, "blob_id": "13fa6efd2f07bcf79a8efc5e5556621fa7d2ccde", "content_id": "737e814d8604a473fc69d5cec5e6e4999f71c77e", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2014, "license_type": "permissive", "max_line_length": 76, "num_lines": 98, "path": "/src/FutureResult.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws;\n\nuse GuzzleHttp\\Ring\\Core;\nuse GuzzleHttp\\Ring\\Future\\FutureInterface;\nuse GuzzleHttp\\Ring\\Future\\MagicFutureTrait;\n\n/**\n * Future result that may not have finished.\n */\nclass FutureResult implements ResultInterface, FutureInterface\n{\n use MagicFutureTrait {\n MagicFutureTrait::wait as parentWait;\n }\n\n public function wait()\n {\n $result = $this->parentWait();\n\n if (!$result instanceof ResultInterface) {\n throw new \\RuntimeException('Expected a ResultInterface. Found '\n . Core::describeType($result));\n }\n\n return $result;\n }\n\n public function hasKey($name)\n {\n return $this->_value->hasKey($name);\n }\n\n public function get($name)\n {\n return $this->_value->get($name);\n }\n\n public function getIterator()\n {\n return $this->_value->getIterator();\n }\n\n public function offsetGet($offset)\n {\n return $this->_value->offsetGet($offset);\n }\n\n public function offsetSet($offset, $value)\n {\n $this->_value->offsetSet($offset, $value);\n }\n\n public function offsetExists($offset)\n {\n return $this->_value->offsetExists($offset);\n }\n\n public function offsetUnset($offset)\n {\n $this->_value->offsetUnset($offset);\n }\n\n public function toArray()\n {\n return $this->_value->toArray();\n }\n\n public function count()\n {\n return $this->_value->count();\n }\n\n public function getPath($path)\n {\n return $this->_value->getPath($path);\n }\n\n public function setPath($path, $value)\n {\n $this->_value->setPath($path, $value);\n }\n\n public function search($expression)\n {\n return $this->_value->search($expression);\n }\n\n public function __toString()\n {\n try {\n return (string) $this->_value;\n } catch (\\Exception $e) {\n trigger_error($e->getMessage(), E_USER_WARNING);\n return '';\n }\n }\n}\n" }, { "alpha_fraction": 0.27835050225257874, "alphanum_fraction": 0.27835050225257874, "avg_line_length": 31, "blob_id": "a7ce0f871ec6b854c64bec1f86ee283f65f51a92", "content_id": "3c9f87cf6e9e8d8cb8fa7ef0a0f4de52ff89d3dd", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 97, "license_type": "permissive", "max_line_length": 31, "num_lines": 3, "path": "/docs/jmespath.rst", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "===============================\nJMESPath Expressions in the SDK\n===============================\n\n" }, { "alpha_fraction": 0.6041396856307983, "alphanum_fraction": 0.6041396856307983, "avg_line_length": 22.663265228271484, "blob_id": "63476cfb040c422d37d64d463ebfa387ba65cf84", "content_id": "2ff55d48003caf08d2bc95b2e5159c9561e35b76", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2319, "license_type": "permissive", "max_line_length": 81, "num_lines": 98, "path": "/src/Exception/AwsException.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Exception;\n\nuse GuzzleHttp\\Command\\Exception\\CommandException;\n\n/**\n * Represents an AWS exception that is thrown when a command fails.\n */\nclass AwsException extends CommandException\n{\n /**\n * Gets the client that executed the command.\n *\n * @return \\Aws\\AwsClientInterface\n */\n public function getClient()\n {\n return $this->getTransaction()->serviceClient;\n }\n\n /**\n * Get the name of the web service that encountered the error.\n *\n * @return string\n */\n public function getServiceName()\n {\n return $this->getClient()->getApi()->getMetadata('endpointPrefix');\n }\n\n /**\n * If available, gets the HTTP status code of the corresponding response\n *\n * @return int|null\n */\n public function getStatusCode()\n {\n return $this->getTransaction()->response\n ? $this->getTransaction()->response->getStatusCode()\n : null;\n }\n\n /**\n * Get the request ID of the error. This value is only present if a\n * response was received and is not present in the event of a networking\n * error.\n *\n * @return string|null Returns null if no response was received\n */\n public function getAwsRequestId()\n {\n return $this->getTransaction()->context->getPath('aws_error/request_id');\n }\n\n /**\n * Get the AWS error type.\n *\n * @return string|null Returns null if no response was received\n */\n public function getAwsErrorType()\n {\n return $this->getTransaction()->context->getPath('aws_error/type');\n }\n\n /**\n * Get the AWS error code.\n *\n * @return string|null Returns null if no response was received\n */\n public function getAwsErrorCode()\n {\n return $this->getTransaction()->context->getPath('aws_error/code');\n }\n\n /**\n * @deprecated Use getAwsRequestId() instead\n */\n public function getRequestId()\n {\n return $this->getAwsRequestId();\n }\n\n /**\n * @deprecated Use getAwsErrorCode() instead\n */\n public function getExceptionCode()\n {\n return $this->getAwsErrorCode();\n }\n\n /**\n * @deprecated Use getAwsErrorType() instead\n */\n public function getExceptionType()\n {\n return $this->getAwsErrorType();\n }\n}\n" }, { "alpha_fraction": 0.5579553842544556, "alphanum_fraction": 0.5723541975021362, "avg_line_length": 36.20535659790039, "blob_id": "767f1109c9e18da9e056c153d0dbee3917e665f6", "content_id": "539285ed2775f0d81e722297982697f5e32ff8f6", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4167, "license_type": "permissive", "max_line_length": 94, "num_lines": 112, "path": "/tests/S3/BucketStyleSubscriberTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\S3;\n\nuse Aws\\S3\\BucketStyleSubscriber;\nuse Aws\\Test\\UsesServiceTrait;\nuse GuzzleHttp\\Command\\CommandTransaction;\nuse GuzzleHttp\\Command\\Event\\PreparedEvent;\nuse GuzzleHttp\\Command\\Event\\ProcessEvent;\nuse GuzzleHttp\\Message\\Request;\nuse GuzzleHttp\\Message\\Response;\n\n/**\n * @covers Aws\\S3\\BucketStyleSubscriber\n */\nclass BucketStyleTest extends \\PHPUnit_Framework_TestCase\n{\n use UsesServiceTrait;\n\n public function testHasEvents()\n {\n $this->assertNotEmpty((new BucketStyleSubscriber)->getEvents());\n }\n\n public function testUsesPathStyleWhenHttpsContainsDots()\n {\n $s3 = $this->getTestClient('s3');\n $this->addMockResponses($s3, [new Response(200)]);\n $command = $s3->getCommand('GetObject', array(\n 'Bucket' => 'test.123',\n 'Key' => 'Bar'\n ));\n $command->getEmitter()->on('process', function (ProcessEvent $e) {\n $this->assertEquals('s3.amazonaws.com', $e->getRequest()->getHost());\n $this->assertEquals('/test.123/Bar', $e->getRequest()->getResource());\n });\n $s3->execute($command);\n }\n\n public function testUsesPathStyleWhenNotDnsCompatible()\n {\n $s3 = $this->getTestClient('s3');\n $this->addMockResponses($s3, [new Response(200)]);\n $command = $s3->getCommand('GetObject', array(\n 'Bucket' => '_baz_!',\n 'Key' => 'Bar'\n ));\n $command->getEmitter()->on('process', function (ProcessEvent $e) {\n $this->assertEquals('s3.amazonaws.com', $e->getRequest()->getHost());\n $this->assertEquals('/_baz_%21/Bar', $e->getRequest()->getResource());\n });\n $s3->execute($command);\n }\n\n public function testUsesPathStyleWhenForced()\n {\n $s3 = $this->getTestClient('s3');\n $this->addMockResponses($s3, [new Response(200)]);\n $command = $s3->getCommand('GetObject', array(\n 'Bucket' => 'foo',\n 'Key' => 'Bar',\n 'PathStyle' => true\n ));\n $command->getEmitter()->on('process', function (ProcessEvent $e) {\n $this->assertEquals('s3.amazonaws.com', $e->getRequest()->getHost());\n $this->assertEquals('/foo/Bar', $e->getRequest()->getResource());\n });\n $s3->execute($command);\n }\n\n public function testUsesVirtualHostedWhenPossible()\n {\n $s3 = $this->getTestClient('s3');\n $this->addMockResponses($s3, [new Response(200)]);\n $command = $s3->getCommand('GetObject', array('Bucket' => 'foo', 'Key' => 'Bar/Baz'));\n $command->getEmitter()->on('process', function (ProcessEvent $e) {\n $this->assertEquals('foo.s3.amazonaws.com', $e->getRequest()->getHost());\n $this->assertEquals('/Bar/Baz', $e->getRequest()->getResource());\n });\n $s3->execute($command);\n }\n\n public function testIgnoresExcludedCommands()\n {\n $s3 = $this->getTestClient('s3');\n $this->addMockResponses($s3, [new Response(200)]);\n $command = $s3->getCommand('GetBucketLocation', ['Bucket' => 'foo']);\n $command->getEmitter()->on('process', function (ProcessEvent $e) {\n $this->assertEquals('s3.amazonaws.com', $e->getRequest()->getHost());\n $this->assertEquals('/foo?location', $e->getRequest()->getResource());\n });\n $s3->execute($command);\n }\n\n public function testRemovesBucketWhenBucketEndpoint()\n {\n $s3 = $this->getTestClient('s3', [\n 'endpoint' => 'http://test.domain.com',\n 'bucket_endpoint' => true\n ]);\n $command = $s3->getCommand('GetObject', array(\n 'Bucket' => 'test',\n 'Key' => 'key'\n ));\n $ct = new CommandTransaction($s3, $command);\n $ct->request = new Request('GET', 'http://test.domain.com/test/key');\n $event = new PreparedEvent($ct);\n $bs = new BucketStyleSubscriber(true);\n $bs->setBucketStyle($event);\n $this->assertEquals('/key', $ct->request->getResource());\n $this->assertEquals('test.domain.com', $ct->request->getHost());\n }\n}\n" }, { "alpha_fraction": 0.5583164095878601, "alphanum_fraction": 0.574056088924408, "avg_line_length": 35.717533111572266, "blob_id": "666c2f74ab118af305dbbecc4b53eef67db14541", "content_id": "612f9b4610d7f6d4a2d00472614c56320b2a7edc", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 11309, "license_type": "permissive", "max_line_length": 111, "num_lines": 308, "path": "/tests/Signature/SignatureV4Test.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Signature;\n\nuse Aws\\Credentials\\Credentials;\nuse Aws\\Signature\\SignatureV4;\nuse GuzzleHttp\\Client;\nuse GuzzleHttp\\Message\\Request;\nuse GuzzleHttp\\Message\\MessageFactory;\n\nrequire_once __DIR__ . '/sig_hack.php';\n\n// Super hacky stuff to get the date right for real request vs the test-suite.\nclass HackRequest extends Request\n{\n public function setHeader($header, $value)\n {\n parent::setHeader(\n $header,\n $header == 'Date' ? SignatureV4Test::DEFAULT_DATETIME : $value\n );\n }\n}\n\n/**\n * @covers Aws\\Signature\\SignatureV4\n */\nclass SignatureV4Test extends \\PHPUnit_Framework_TestCase\n{\n const DEFAULT_KEY = 'AKIDEXAMPLE';\n const DEFAULT_SECRET = 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY';\n const DEFAULT_DATETIME = 'Mon, 09 Sep 2011 23:36:00 GMT';\n\n public function setup()\n {\n $_SERVER['aws_time'] = strtotime('December 5, 2013 00:00:00 UTC');\n }\n\n public function testReturnsRegionAndService()\n {\n $s = new SignatureV4('foo', 'bar');\n $this->assertEquals('foo', $this->readAttribute($s, 'service'));\n $this->assertEquals('bar', $this->readAttribute($s, 'region'));\n }\n\n public function testAddsSecurityTokenIfPresent()\n {\n $s = new SignatureV4('foo', 'bar');\n $c = new Credentials('a', 'b', 'AddMe!');\n $r = new Request('GET', 'http://httpbin.org');\n $s->signRequest($r, $c);\n $this->assertContains('x-amz-security-token: AddMe!', (string) $r);\n $ctx = $r->getConfig()->get('aws.signature');\n $this->assertContains('x-amz-security-token:AddMe!', $ctx['creq']);\n $this->assertContains('date;host;x-amz-security-token', $ctx['creq']);\n $this->assertContains('x-amz-security-token', $ctx['headers']);\n }\n\n public function testSignsRequestsWithMultiValuedHeaders()\n {\n $s = new SignatureV4('foo', 'bar');\n $c = new Credentials('a', 'b');\n $r = new Request('GET', 'http://httpbin.org', [\n 'X-amz-Foo' => ['baz', ' bar ']\n ]);\n $s->signRequest($r, $c);\n $this->assertContains('SignedHeaders=date;host;x-amz-foo', (string) $r);\n $ctx = $r->getConfig()->get('aws.signature');\n $this->assertContains('x-amz-foo:bar,baz', $ctx['creq']);\n $this->assertContains('date;host;x-amz-foo', $ctx['creq']);\n $this->assertNotContains('x-amz-security-token', $ctx['headers']);\n }\n\n /**\n * @dataProvider testSuiteProvider\n */\n public function testSignsRequestsProperly($group)\n {\n // Create a request based on the '.req' file\n $requestString = file_get_contents($group['req']);\n $request = (new MessageFactory)->fromMessage($requestString);\n // Hack the request to get the broken test suite working.\n $request = new HackRequest(\n $request->getMethod(),\n $request->getUrl(),\n $request->getHeaders(),\n $request->getBody()\n );\n // Sanitize the request\n $request->removeHeader('User-Agent');\n $request->removeHeader('Content-Length');\n // Sign the request using the test credentials\n $credentials = new Credentials(self::DEFAULT_KEY, self::DEFAULT_SECRET);\n // Get a mock signature object\n $signature = new SignatureV4('host', 'us-east-1');\n // Sign the request\n $signature->signRequest($request, $credentials);\n // Get debug signature information\n $context = $request->getConfig()['aws.signature'];\n // Test that the canonical request is correct\n $this->assertEquals(\n str_replace(\"\\r\", '', file_get_contents($group['creq'])),\n $context['creq']\n );\n // Test that the string to sign is correct\n $this->assertEquals(\n str_replace(\"\\r\", '', file_get_contents($group['sts'])),\n $context['string_to_sign']\n );\n // Test that the authorization header is correct\n $this->assertEquals(\n str_replace(\"\\r\", '', file_get_contents($group['authz'])),\n $request->getHeader('Authorization')\n );\n }\n\n /**\n * @return array\n */\n public function testSuiteProvider()\n {\n // Gather a list of files sorted by name\n $files = glob(__DIR__ . DIRECTORY_SEPARATOR\n . 'aws4_testsuite' . DIRECTORY_SEPARATOR . '*');\n\n // Skip the get-header-key-duplicate.* and\n // get-header-value-order.authz.* test files for now; they are believed\n // to be invalid tests. See https://github.com/aws/aws-sdk-php/issues/161\n $files = array_filter($files, function($file) {\n return ((strpos($file, 'get-header-key-duplicate.') === false) &&\n (strpos($file, 'get-header-value-order.' ) === false));\n });\n sort($files);\n\n // Break the files up into groups of five for each test case\n $groups = $group = [];\n for ($i = 0, $c = count($files); $i < $c; $i++) {\n $types = explode('.', $files[$i]);\n $type = end($types);\n $group[$type] = $files[$i];\n if (count($group) == 5) {\n $groups[] = [$group];\n $group = [];\n }\n }\n\n return $groups;\n }\n\n public function testUsesExistingSha256HashIfPresent()\n {\n $sig = new SignatureV4('foo', 'bar');\n $creds = new Credentials('a', 'b');\n $req = new Request('PUT', 'http://foo.com', [\n 'x-amz-content-sha256' => '123'\n ]);\n $sig->signRequest($req, $creds);\n $creq = $req->getConfig()->get('aws.signature')['creq'];\n $this->assertContains('amz-content-sha256:123', $creq);\n }\n\n public function testMaintainsCappedCache()\n {\n $sig = new SignatureV4('foo', 'bar');\n // Hack the class so that it thinks it needs 3 more entries to be full\n $p = new \\ReflectionProperty($sig, 'cacheSize');\n $p->setAccessible(true);\n $p->setValue($sig, 47);\n\n $request = new Request('GET', 'http://www.example.com');\n $credentials = new Credentials('fizz', 'buzz');\n $sig->signRequest($request, $credentials);\n $this->assertEquals(1, count($this->readAttribute($sig, 'cache')));\n\n $credentials = new Credentials('fizz', 'baz');\n $sig->signRequest($request, $credentials);\n $this->assertEquals(2, count($this->readAttribute($sig, 'cache')));\n\n $credentials = new Credentials('fizz', 'paz');\n $sig->signRequest($request, $credentials);\n $this->assertEquals(3, count($this->readAttribute($sig, 'cache')));\n\n $credentials = new Credentials('fizz', 'foobar');\n $sig->signRequest($request, $credentials);\n $this->assertEquals(1, count($this->readAttribute($sig, 'cache')));\n }\n\n public function queryProvider()\n {\n return [\n [[], ''],\n [['X-Amz-Signature' => 'foo'], ''],\n [['Foo' => '123', 'Bar' => '456'], 'Bar=456&Foo=123'],\n [['Foo' => ['b', 'a'], 'a' => 'bc'], 'Foo=a&Foo=b&a=bc'],\n [['Foo' => '', 'a' => 'b' ], 'Foo=&a=b']\n ];\n }\n\n /**\n * @covers Aws\\Signature\\SignatureV4::getCanonicalizedQuery\n * @dataProvider queryProvider\n */\n public function testCreatesCanonicalizedQuery($data, $string)\n {\n $method = new \\ReflectionMethod(\n 'Aws\\Signature\\SignatureV4',\n 'getCanonicalizedQuery'\n );\n $method->setAccessible(true);\n\n // Create a request and replace the headers with the test headers\n $request = new Request('GET', 'http://www.example.com');\n $request->getQuery()->replace($data);\n\n $signature = $this->getMockBuilder('Aws\\Signature\\SignatureV4')\n ->disableOriginalConstructor()\n ->getMockForAbstractClass();\n\n $this->assertEquals($string, $method->invoke($signature, $request));\n }\n\n private function getFixtures()\n {\n $request = new Request('GET', 'http://foo.com');\n $credentials = new Credentials('foo', 'bar');\n $signature = new SignatureV4('service', 'region');\n $ref = new \\ReflectionMethod($signature, 'convertExpires');\n $ref->setAccessible(true);\n\n return array($request, $credentials, $signature, $ref);\n }\n\n public function testCreatesPresignedDatesFromDateTime()\n {\n $_SERVER['override_v4_time'] = true;\n list($request, $credentials, $signature, $ref) = $this->getFixtures();\n $this->assertEquals(518400, $ref->invoke($signature, new \\DateTime('December 11, 2013 00:00:00 UTC')));\n }\n\n public function testCreatesPresignedDatesFromUnixTimestamp()\n {\n $_SERVER['override_v4_time'] = true;\n list($request, $credentials, $signature, $ref) = $this->getFixtures();\n $this->assertEquals(518400, $ref->invoke($signature, 1386720000));\n }\n\n public function testCreatesPresignedDateFromStrtotime()\n {\n $_SERVER['override_v4_time'] = true;\n list($request, $credentials, $signature, $ref) = $this->getFixtures();\n $this->assertEquals(518400, $ref->invoke($signature, 'December 11, 2013 00:00:00 UTC'));\n }\n\n public function testAddsSecurityTokenIfPresentInPresigned()\n {\n $_SERVER['override_v4_time'] = true;\n list($request, $credentials, $signature) = $this->getFixtures();\n $credentials = new Credentials('foo', 'bar', '123');\n $url = $signature->createPresignedUrl($request, $credentials, 1386720000);\n $this->assertContains('X-Amz-Security-Token=123', $url);\n $this->assertContains('X-Amz-Expires=518400', $url);\n }\n\n /**\n * @expectedException \\InvalidArgumentException\n */\n public function testEnsuresSigV4DurationIsLessThanOneWeek()\n {\n $_SERVER['override_v4_time'] = true;\n list($request, $credentials, $signature) = $this->getFixtures();\n $signature->createPresignedUrl($request, $credentials, 'December 31, 2013 00:00:00 UTC');\n }\n\n public function testConvertsPostToGet()\n {\n $client = new Client();\n $request = $client->createRequest('POST', 'http://foo.com');\n $request->getBody()->setField('foo', 'bar');\n $request->getBody()->setField('baz', 'bam');\n $request = SignatureV4::convertPostToGet($request);\n $this->assertEquals('GET', $request->getMethod());\n $this->assertEquals('bar', $request->getQuery()->get('foo'));\n $this->assertEquals('bam', $request->getQuery()->get('baz'));\n }\n\n /**\n * @expectedException \\InvalidArgumentException\n */\n public function testEnsuresMethodIsPost()\n {\n $request = new Request('PUT', 'http://foo.com');\n SignatureV4::convertPostToGet($request);\n }\n\n public function testSignSpecificHeaders()\n {\n $sig = new SignatureV4('foo', 'bar');\n $creds = new Credentials('a', 'b');\n $req = new Request('PUT', 'http://foo.com', [\n 'date' => 'today',\n 'host' => 'foo.com',\n 'x-amz-foo' => '123',\n 'content-md5' => 'bogus'\n ]);\n $sig->signRequest($req, $creds);\n $creq = $req->getConfig()->get('aws.signature')['creq'];\n $this->assertContains('content-md5;date;host;x-amz-foo', $creq);\n }\n}\n" }, { "alpha_fraction": 0.4024640619754791, "alphanum_fraction": 0.412180095911026, "avg_line_length": 24.274682998657227, "blob_id": "f0544581637260f70505d11a51b4389af66c4438", "content_id": "37dbcfe8600b194187e6ac312360beb432064cec", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 19967, "license_type": "permissive", "max_line_length": 79, "num_lines": 790, "path": "/src/data/cloudtrail-2013-11-01.api.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php return [\n 'metadata' => [\n 'apiVersion' => '2013-11-01',\n 'endpointPrefix' => 'cloudtrail',\n 'jsonVersion' => '1.1',\n 'serviceAbbreviation' => 'CloudTrail',\n 'serviceFullName' => 'AWS CloudTrail',\n 'signatureVersion' => 'v4',\n 'targetPrefix' => 'com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101',\n 'protocol' => 'json',\n ],\n 'operations' => [\n 'CreateTrail' => [\n 'name' => 'CreateTrail',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateTrailRequest',\n ],\n 'output' => [\n 'shape' => 'CreateTrailResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'MaximumNumberOfTrailsExceededException',\n 'error' => [\n 'code' => 'MaximumNumberOfTrailsExceeded',\n 'httpStatusCode' => 403,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'TrailAlreadyExistsException',\n 'error' => [\n 'code' => 'TrailAlreadyExists',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'S3BucketDoesNotExistException',\n 'error' => [\n 'code' => 'S3BucketDoesNotExist',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InsufficientS3BucketPolicyException',\n 'error' => [\n 'code' => 'InsufficientS3BucketPolicy',\n 'httpStatusCode' => 403,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InsufficientSnsTopicPolicyException',\n 'error' => [\n 'code' => 'InsufficientSnsTopicPolicy',\n 'httpStatusCode' => 403,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidS3BucketNameException',\n 'error' => [\n 'code' => 'InvalidS3BucketName',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidS3PrefixException',\n 'error' => [\n 'code' => 'InvalidS3Prefix',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidSnsTopicNameException',\n 'error' => [\n 'code' => 'InvalidSnsTopicName',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidTrailNameException',\n 'error' => [\n 'code' => 'InvalidTrailName',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidCloudWatchLogsLogGroupArnException',\n 'error' => [\n 'code' => 'InvalidCloudWatchLogsLogGroupArn',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidCloudWatchLogsRoleArnException',\n 'error' => [\n 'code' => 'InvalidCloudWatchLogsRoleArn',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'CloudWatchLogsDeliveryUnavailableException',\n 'error' => [\n 'code' => 'CloudWatchLogsDeliveryUnavailable',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'DeleteTrail' => [\n 'name' => 'DeleteTrail',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteTrailRequest',\n ],\n 'output' => [\n 'shape' => 'DeleteTrailResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'TrailNotFoundException',\n 'error' => [\n 'code' => 'TrailNotFound',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidTrailNameException',\n 'error' => [\n 'code' => 'InvalidTrailName',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'DescribeTrails' => [\n 'name' => 'DescribeTrails',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeTrailsRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeTrailsResponse',\n ],\n ],\n 'GetTrailStatus' => [\n 'name' => 'GetTrailStatus',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'GetTrailStatusRequest',\n ],\n 'output' => [\n 'shape' => 'GetTrailStatusResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'TrailNotFoundException',\n 'error' => [\n 'code' => 'TrailNotFound',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidTrailNameException',\n 'error' => [\n 'code' => 'InvalidTrailName',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'StartLogging' => [\n 'name' => 'StartLogging',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'StartLoggingRequest',\n ],\n 'output' => [\n 'shape' => 'StartLoggingResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'TrailNotFoundException',\n 'error' => [\n 'code' => 'TrailNotFound',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidTrailNameException',\n 'error' => [\n 'code' => 'InvalidTrailName',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'StopLogging' => [\n 'name' => 'StopLogging',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'StopLoggingRequest',\n ],\n 'output' => [\n 'shape' => 'StopLoggingResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'TrailNotFoundException',\n 'error' => [\n 'code' => 'TrailNotFound',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidTrailNameException',\n 'error' => [\n 'code' => 'InvalidTrailName',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'UpdateTrail' => [\n 'name' => 'UpdateTrail',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'UpdateTrailRequest',\n ],\n 'output' => [\n 'shape' => 'UpdateTrailResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'S3BucketDoesNotExistException',\n 'error' => [\n 'code' => 'S3BucketDoesNotExist',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InsufficientS3BucketPolicyException',\n 'error' => [\n 'code' => 'InsufficientS3BucketPolicy',\n 'httpStatusCode' => 403,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InsufficientSnsTopicPolicyException',\n 'error' => [\n 'code' => 'InsufficientSnsTopicPolicy',\n 'httpStatusCode' => 403,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'TrailNotFoundException',\n 'error' => [\n 'code' => 'TrailNotFound',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidS3BucketNameException',\n 'error' => [\n 'code' => 'InvalidS3BucketName',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidS3PrefixException',\n 'error' => [\n 'code' => 'InvalidS3Prefix',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidSnsTopicNameException',\n 'error' => [\n 'code' => 'InvalidSnsTopicName',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidTrailNameException',\n 'error' => [\n 'code' => 'InvalidTrailName',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidCloudWatchLogsLogGroupArnException',\n 'error' => [\n 'code' => 'InvalidCloudWatchLogsLogGroupArn',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidCloudWatchLogsRoleArnException',\n 'error' => [\n 'code' => 'InvalidCloudWatchLogsRoleArn',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'CloudWatchLogsDeliveryUnavailableException',\n 'error' => [\n 'code' => 'CloudWatchLogsDeliveryUnavailable',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n ],\n 'shapes' => [\n 'Boolean' => [\n 'type' => 'boolean',\n ],\n 'CloudWatchLogsDeliveryUnavailableException' => [\n 'type' => 'structure',\n 'members' => [],\n 'error' => [\n 'code' => 'CloudWatchLogsDeliveryUnavailable',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'CreateTrailRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'Name',\n 'S3BucketName',\n ],\n 'members' => [\n 'Name' => [\n 'shape' => 'String',\n ],\n 'S3BucketName' => [\n 'shape' => 'String',\n ],\n 'S3KeyPrefix' => [\n 'shape' => 'String',\n ],\n 'SnsTopicName' => [\n 'shape' => 'String',\n ],\n 'IncludeGlobalServiceEvents' => [\n 'shape' => 'Boolean',\n ],\n 'CloudWatchLogsLogGroupArn' => [\n 'shape' => 'String',\n ],\n 'CloudWatchLogsRoleArn' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'CreateTrailResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'Name' => [\n 'shape' => 'String',\n ],\n 'S3BucketName' => [\n 'shape' => 'String',\n ],\n 'S3KeyPrefix' => [\n 'shape' => 'String',\n ],\n 'SnsTopicName' => [\n 'shape' => 'String',\n ],\n 'IncludeGlobalServiceEvents' => [\n 'shape' => 'Boolean',\n ],\n 'CloudWatchLogsLogGroupArn' => [\n 'shape' => 'String',\n ],\n 'CloudWatchLogsRoleArn' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'Date' => [\n 'type' => 'timestamp',\n ],\n 'DeleteTrailRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'Name',\n ],\n 'members' => [\n 'Name' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'DeleteTrailResponse' => [\n 'type' => 'structure',\n 'members' => [],\n ],\n 'DescribeTrailsRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'trailNameList' => [\n 'shape' => 'TrailNameList',\n ],\n ],\n ],\n 'DescribeTrailsResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'trailList' => [\n 'shape' => 'TrailList',\n ],\n ],\n ],\n 'GetTrailStatusRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'Name',\n ],\n 'members' => [\n 'Name' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'GetTrailStatusResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'IsLogging' => [\n 'shape' => 'Boolean',\n ],\n 'LatestDeliveryError' => [\n 'shape' => 'String',\n ],\n 'LatestNotificationError' => [\n 'shape' => 'String',\n ],\n 'LatestDeliveryTime' => [\n 'shape' => 'Date',\n ],\n 'LatestNotificationTime' => [\n 'shape' => 'Date',\n ],\n 'StartLoggingTime' => [\n 'shape' => 'Date',\n ],\n 'StopLoggingTime' => [\n 'shape' => 'Date',\n ],\n 'LatestCloudWatchLogsDeliveryError' => [\n 'shape' => 'String',\n ],\n 'LatestCloudWatchLogsDeliveryTime' => [\n 'shape' => 'Date',\n ],\n ],\n ],\n 'InsufficientS3BucketPolicyException' => [\n 'type' => 'structure',\n 'members' => [],\n 'error' => [\n 'code' => 'InsufficientS3BucketPolicy',\n 'httpStatusCode' => 403,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'InsufficientSnsTopicPolicyException' => [\n 'type' => 'structure',\n 'members' => [],\n 'error' => [\n 'code' => 'InsufficientSnsTopicPolicy',\n 'httpStatusCode' => 403,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'InvalidCloudWatchLogsLogGroupArnException' => [\n 'type' => 'structure',\n 'members' => [],\n 'error' => [\n 'code' => 'InvalidCloudWatchLogsLogGroupArn',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'InvalidCloudWatchLogsRoleArnException' => [\n 'type' => 'structure',\n 'members' => [],\n 'error' => [\n 'code' => 'InvalidCloudWatchLogsRoleArn',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'InvalidS3BucketNameException' => [\n 'type' => 'structure',\n 'members' => [],\n 'error' => [\n 'code' => 'InvalidS3BucketName',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'InvalidS3PrefixException' => [\n 'type' => 'structure',\n 'members' => [],\n 'error' => [\n 'code' => 'InvalidS3Prefix',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'InvalidSnsTopicNameException' => [\n 'type' => 'structure',\n 'members' => [],\n 'error' => [\n 'code' => 'InvalidSnsTopicName',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'InvalidTrailNameException' => [\n 'type' => 'structure',\n 'members' => [],\n 'error' => [\n 'code' => 'InvalidTrailName',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'MaximumNumberOfTrailsExceededException' => [\n 'type' => 'structure',\n 'members' => [],\n 'error' => [\n 'code' => 'MaximumNumberOfTrailsExceeded',\n 'httpStatusCode' => 403,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'S3BucketDoesNotExistException' => [\n 'type' => 'structure',\n 'members' => [],\n 'error' => [\n 'code' => 'S3BucketDoesNotExist',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'StartLoggingRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'Name',\n ],\n 'members' => [\n 'Name' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'StartLoggingResponse' => [\n 'type' => 'structure',\n 'members' => [],\n ],\n 'StopLoggingRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'Name',\n ],\n 'members' => [\n 'Name' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'StopLoggingResponse' => [\n 'type' => 'structure',\n 'members' => [],\n ],\n 'String' => [\n 'type' => 'string',\n ],\n 'Trail' => [\n 'type' => 'structure',\n 'members' => [\n 'Name' => [\n 'shape' => 'String',\n ],\n 'S3BucketName' => [\n 'shape' => 'String',\n ],\n 'S3KeyPrefix' => [\n 'shape' => 'String',\n ],\n 'SnsTopicName' => [\n 'shape' => 'String',\n ],\n 'IncludeGlobalServiceEvents' => [\n 'shape' => 'Boolean',\n ],\n 'CloudWatchLogsLogGroupArn' => [\n 'shape' => 'String',\n ],\n 'CloudWatchLogsRoleArn' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'TrailAlreadyExistsException' => [\n 'type' => 'structure',\n 'members' => [],\n 'error' => [\n 'code' => 'TrailAlreadyExists',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'TrailList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'Trail',\n ],\n ],\n 'TrailNameList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n ],\n ],\n 'TrailNotFoundException' => [\n 'type' => 'structure',\n 'members' => [],\n 'error' => [\n 'code' => 'TrailNotFound',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'UpdateTrailRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'Name',\n ],\n 'members' => [\n 'Name' => [\n 'shape' => 'String',\n ],\n 'S3BucketName' => [\n 'shape' => 'String',\n ],\n 'S3KeyPrefix' => [\n 'shape' => 'String',\n ],\n 'SnsTopicName' => [\n 'shape' => 'String',\n ],\n 'IncludeGlobalServiceEvents' => [\n 'shape' => 'Boolean',\n ],\n 'CloudWatchLogsLogGroupArn' => [\n 'shape' => 'String',\n ],\n 'CloudWatchLogsRoleArn' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'UpdateTrailResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'Name' => [\n 'shape' => 'String',\n ],\n 'S3BucketName' => [\n 'shape' => 'String',\n ],\n 'S3KeyPrefix' => [\n 'shape' => 'String',\n ],\n 'SnsTopicName' => [\n 'shape' => 'String',\n ],\n 'IncludeGlobalServiceEvents' => [\n 'shape' => 'Boolean',\n ],\n 'CloudWatchLogsLogGroupArn' => [\n 'shape' => 'String',\n ],\n 'CloudWatchLogsRoleArn' => [\n 'shape' => 'String',\n ],\n ],\n ],\n ],\n];\n" }, { "alpha_fraction": 0.5283153057098389, "alphanum_fraction": 0.5378485918045044, "avg_line_length": 31.537036895751953, "blob_id": "3fbc0d65e469a9ef56e72e45b1add68f91c4704f", "content_id": "ad789bec188c8cb21148541605a4dd6c115459ff", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 7028, "license_type": "permissive", "max_line_length": 96, "num_lines": 216, "path": "/tests/S3/UploadBuilderTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\S3;\n\nuse Aws\\Multipart\\UploadState;\nuse Aws\\S3\\UploadBuilder;\nuse Aws\\Result;\nuse Aws\\Test\\UsesServiceTrait;\nuse GuzzleHttp\\Stream\\Stream;\n\n/**\n * @covers Aws\\S3\\UploadBuilder\n */\nclass UploadBuilderTest extends \\PHPUnit_Framework_TestCase\n{\n use UsesServiceTrait;\n\n const MB = 1048576;\n\n public function testCanCreateBuilder()\n {\n $builder = (new UploadBuilder)\n ->setClient($this->getMock('Aws\\AwsClientInterface'))\n ->setSource(__FILE__)\n ->setBucket('foo')\n ->setKey('bar');\n $builder2 = clone $builder;\n\n $uploader = $builder->build();\n $config = $this->readAttribute($uploader, 'config');\n $params = $config['initiate']['params'];\n $this->assertArrayHasKey('ContentType', $params);\n $this->assertInstanceOf('Aws\\Multipart\\Uploader', $uploader);\n\n $builder2->setUploadId('baz');\n $this->assertEquals(\n ['Bucket' => 'foo', 'Key' => 'bar', 'UploadId' => 'baz'],\n $this->readAttribute($builder2, 'uploadId')\n );\n }\n\n public function testThrowsExceptionOnBadPartSize()\n {\n $uploader = (new UploadBuilder)\n ->setClient($this->getMock('Aws\\AwsClientInterface'))\n ->setSource(__FILE__)\n ->setBucket('foo')\n ->setKey('bar')\n ->setPartSize(1024);\n\n $this->setExpectedException('InvalidArgumentException');\n $uploader->build();\n }\n\n public function testCanLoadStateFromUploadId()\n {\n $client = $this->getTestClient('S3');\n $this->addMockResults($client, [\n new Result([\n 'Parts' => [\n ['PartNumber' => 1, 'ETag' => 'foo', 'Size' => 1024],\n ['PartNumber' => 2, 'ETag' => 'bar', 'Size' => 1024],\n ['PartNumber' => 3, 'ETag' => 'baz', 'Size' => 1024],\n ]\n ])\n ]);\n\n $builder = (new UploadBuilder)->setClient($client);\n $method = (new \\ReflectionObject($builder))\n ->getMethod('loadStateByUploadId');\n $method->setAccessible(true);\n /** @var UploadState $state */\n $state = $method->invoke($builder, [\n 'Bucket' => 'foo',\n 'Key' => 'bar',\n 'UploadId' => 'baz'\n ]);\n\n $part = $state->getUploadedParts()[3];\n $this->assertEquals(3, $part['PartNumber']);\n $this->assertEquals('baz', $part['ETag']);\n }\n\n /**\n * @dataProvider checksumTestProvider\n */\n public function testKnowsWhenToCalculateChecksums($client, $expected)\n {\n $uploader = (new UploadBuilder)->setClient($client);\n $stream = Stream::factory('foo');\n\n $method = (new \\ReflectionClass('Aws\\S3\\UploadBuilder'))\n ->getMethod('decorateWithHashes');\n $method->setAccessible(true);\n\n $actual = null;\n $stream = $method->invoke($uploader, $stream, function ($result, $type) use (&$actual) {\n $actual = [$type, $result];\n });\n $stream->getContents();\n $this->assertEquals($expected, $actual);\n }\n\n public function checksumTestProvider()\n {\n $hasher = function ($type, $value) {\n return base64_encode(hash($type, $value, true));\n };\n\n return [\n [\n $this->getTestClient('S3'),\n ['md5', $hasher('md5', 'foo')]\n ],\n [\n $this->getTestClient('S3', ['calculate_md5' => false]),\n null\n ],\n [\n $this->getTestClient('S3', ['signature_version' => 'v4']),\n ['sha256', $hasher('sha256', 'foo')]\n ]\n ];\n }\n\n public function testCanCreatePartGeneratorCallback()\n {\n $source = Stream::factory('foo');\n $state = new UploadState([]);\n $state->setPartSize(5);\n $builder = (new UploadBuilder)\n ->setClient($this->getTestClient('S3'))\n ->setState($state)\n ->setSource($source);\n\n $method = (new \\ReflectionObject($builder))\n ->getMethod('getCreatePartFn');\n $method->setAccessible(true);\n /** @var callable $createPart */\n $createPart = $method->invoke($builder);\n\n $data = $createPart(true, 2);\n $this->assertEquals(2, $data['PartNumber']);\n $this->assertInstanceOf('GuzzleHttp\\Stream\\LimitStream', $data['Body']);\n\n $source->seek(0);\n $data = $createPart(false, 2);\n $this->assertEquals(2, $data['PartNumber']);\n $this->assertInstanceOf('GuzzleHttp\\Stream\\Stream', $data['Body']);\n $this->assertArrayHasKey('ContentLength', $data);\n $this->assertArrayHasKey('ContentMD5', $data);\n }\n\n public function testCallbackCreatesCorrectCompleteCommandParams()\n {\n // Prepare state.\n $state = new UploadState([]);\n $parts = [\n 1 => ['ETag' => 'foo'],\n 2 => ['ETag' => 'bar'],\n 3 => ['ETag' => 'baz'],\n ];\n foreach ($parts as $number => $data) {\n $state->markPartAsUploaded($number, $data);\n }\n\n // Prepare builder.\n $builder = (new UploadBuilder)\n ->setClient($this->getTestClient('S3'))\n ->setState($state)\n ->setSource(Stream::factory('foo'));\n\n // Get function.\n $method = (new \\ReflectionObject($builder))\n ->getMethod('getCompleteParamsFn');\n $method->setAccessible(true);\n /** @var callable $getCommandParams */\n $getCommandParams = $method->invoke($builder);\n\n // Validate function results.\n $params = $getCommandParams();\n $this->assertTrue(isset($params['MultipartUpload']['Parts']));\n $this->assertEquals($parts, $params['MultipartUpload']['Parts']);\n }\n\n public function testCallbackHandlesResultsOfUploadPart()\n {\n $state = new UploadState([]);\n\n $builder = (new UploadBuilder)\n ->setClient($this->getTestClient('S3'))\n ->setState($state)\n ->setSource(Stream::factory('foo'));\n\n $method = (new \\ReflectionObject($builder))\n ->getMethod('getResultHandlerFn');\n $method->setAccessible(true);\n /** @var callable $handleResult */\n $handleResult = $method->invoke($builder);\n\n // Mock arguments.\n $command = $this->getMockBuilder('GuzzleHttp\\Command\\Command')\n ->disableOriginalConstructor()\n ->getMock();\n $command->method('offsetGet')->willReturn(2);\n $result = $this->getMockBuilder('Aws\\Result')\n ->disableOriginalConstructor()\n ->getMock();\n $result->method('offsetGet')->willReturn('foo');\n\n $handleResult($command, $result);\n\n $uploadedParts = $state->getUploadedParts();\n $this->assertTrue(isset($uploadedParts[2]['ETag']));\n $this->assertEquals('foo', $uploadedParts[2]['ETag']);\n }\n}\n" }, { "alpha_fraction": 0.5911133289337158, "alphanum_fraction": 0.6015976071357727, "avg_line_length": 29.34848403930664, "blob_id": "ef0cf025f88c47956ad185a239953f6c062c76f3", "content_id": "3a982f5e933c77f5a4485412e8de735a0f0341db", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2003, "license_type": "permissive", "max_line_length": 85, "num_lines": 66, "path": "/src/S3/SSECSubscriber.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\S3;\n\nuse Aws\\AwsClientInterface;\nuse GuzzleHttp\\Command\\Event\\InitEvent;\nuse GuzzleHttp\\Event\\SubscriberInterface;\nuse GuzzleHttp\\Command\\CommandInterface;\n\n/**\n * This listener simplifies the SSE-C process by encoding and hashing the key.\n */\nclass SSECSubscriber implements SubscriberInterface\n{\n public function getEvents()\n {\n return ['init' => ['onInit']];\n }\n\n public function onInit(InitEvent $e)\n {\n $command = $e->getCommand();\n\n // Allows only HTTPS connections when using SSE-C\n if ($command['SSECustomerKey'] ||\n $command['CopySourceSSECustomerKey']\n ) {\n $this->validateScheme($e->getClient());\n }\n\n // Prepare the normal SSE-CPK headers\n if ($command['SSECustomerKey']) {\n $this->prepareSseParams($command);\n }\n\n // If it's a copy operation, prepare the SSE-CPK headers for the source.\n if ($command['CopySourceSSECustomerKey']) {\n $this->prepareSseParams($command, true);\n }\n }\n\n private function validateScheme(AwsClientInterface $client)\n {\n if (strpos($client->getEndpoint(), 'https') !== 0) {\n throw new \\RuntimeException('You must configure your S3 client to '\n . 'use HTTPS in order to use the SSE-C features.');\n }\n }\n\n private function prepareSseParams(\n CommandInterface $command,\n $isCopy = false\n ) {\n $prefix = $isCopy ? 'CopySource' : '';\n\n // Base64 encode the provided key\n $key = $command[$prefix . 'SSECustomerKey'];\n $command[$prefix . 'SSECustomerKey'] = base64_encode($key);\n\n // Base64 the provided MD5 or, generate an MD5 if not provided\n if ($md5 = $command[$prefix . 'SSECustomerKeyMD5']) {\n $command[$prefix . 'SSECustomerKeyMD5'] = base64_encode($md5);\n } else {\n $command[$prefix . 'SSECustomerKeyMD5'] = base64_encode(md5($key, true));\n }\n }\n}\n" }, { "alpha_fraction": 0.7337246537208557, "alphanum_fraction": 0.7337246537208557, "avg_line_length": 47.0512809753418, "blob_id": "97cc9366ea6e222d3dbf39865bd1cbbc4cc6f243", "content_id": "c4a60204ccab94e9b1229768cc60174edb6303fa", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1874, "license_type": "permissive", "max_line_length": 124, "num_lines": 39, "path": "/build/packager.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nrequire __DIR__ . '/artifacts/Burgomaster.php';\nrequire __DIR__ . '/../vendor/autoload.php';\n\n$stageDirectory = __DIR__ . '/artifacts/staging';\n$projectRoot = __DIR__ . '/../';\n$burgomaster = new \\Burgomaster($stageDirectory, $projectRoot);\n$autoloaderFilename = 'aws-autoloader.php';\n\n$metaFiles = ['README.md', 'LICENSE.md', 'NOTICE.md', 'CHANGELOG.md'];\nforeach ($metaFiles as $file) {\n $burgomaster->deepCopy($file, $file);\n}\n\n$burgomaster->recursiveCopy('src', 'Aws', ['php', 'json']);\n$burgomaster->recursiveCopy('vendor/mtdowling/transducers/src', 'Transducers');\n$burgomaster->recursiveCopy('vendor/guzzlehttp/guzzle/src', 'GuzzleHttp');\n$burgomaster->recursiveCopy('vendor/guzzlehttp/ringphp/src', 'GuzzleHttp/Ring');\n$burgomaster->recursiveCopy('vendor/guzzlehttp/streams/src', 'GuzzleHttp/Stream');\n$burgomaster->recursiveCopy('vendor/guzzlehttp/Command/src', 'GuzzleHttp/Command');\n$burgomaster->recursiveCopy('vendor/guzzlehttp/message-integrity-subscriber/src', 'GuzzleHttp/Subscriber/MessageIntegrity');\n$burgomaster->recursiveCopy('vendor/guzzlehttp/retry-subscriber/src', 'GuzzleHttp/Subscriber/Retry');\n$burgomaster->recursiveCopy('vendor/guzzlehttp/log-subscriber/src', 'GuzzleHttp/Subscriber/Log');\n$burgomaster->recursiveCopy('vendor/mtdowling/jmespath.php/src', 'JmesPath');\n$burgomaster->recursiveCopy('vendor/psr/log/Psr/Log', 'Psr/Log');\n$burgomaster->recursiveCopy('vendor/react/promise/src', 'React/Promise');\n\n$burgomaster->createAutoloader([\n 'React/Promise/functions.php',\n 'JmesPath/JmesPath.php',\n 'Transducers/transducers.php'\n], $autoloaderFilename);\n\n$burgomaster->createZip(__DIR__ . \"/artifacts/aws.zip\");\n$burgomaster->createPhar(__DIR__ . \"/artifacts/aws.phar\", null, $autoloaderFilename);\n\n$burgomaster->startSection('test-phar');\n$burgomaster->exec('php ' . __DIR__ . '/test-phar.php');\n$burgomaster->endSection();\n" }, { "alpha_fraction": 0.5506528615951538, "alphanum_fraction": 0.5578567981719971, "avg_line_length": 28.613332748413086, "blob_id": "af518f96fddf1698fd1f8f3bf15d311ac8719186", "content_id": "2a5a3d43fa5a75de1bd4909e200f0d79637f996f", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2221, "license_type": "permissive", "max_line_length": 78, "num_lines": 75, "path": "/tests/Integ/GlacierMultipartTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Integ\\Multipart;\n\nuse Aws\\Exception\\MultipartUploadException;\nuse Aws\\Glacier\\UploadBuilder;\nuse Aws\\Test\\Integ\\IntegUtils;\nuse GuzzleHttp\\Stream\\NoSeekStream;\nuse GuzzleHttp\\Stream\\Stream;\n\nclass GlacierMultipart extends \\PHPUnit_Framework_TestCase\n{\n use IntegUtils;\n\n const MB = 1048576;\n const VAULT = 'php-integ-glacier-multipart';\n\n public static function setUpBeforeClass()\n {\n $client = self::getSdk()->getGlacier();\n $client->createVault(['vaultName' => self::VAULT]);\n $client->waitUntil('VaultExists', ['vaultName' => self::VAULT]);\n }\n\n public function useCasesProvider()\n {\n return [\n ['SeekableSerialUpload', true, 1],\n ['NonSeekableSerialUpload', false, 3],\n ['SeekableConcurrentUpload', true, 1],\n ['NonSeekableConcurrentUpload', false, 3],\n ];\n }\n\n /**\n * @param string $description\n * @param bool $seekable\n * @param int $concurrency\n * @dataProvider useCasesProvider\n */\n public function testMultipartUpload($description, $seekable, $concurrency)\n {\n $client = self::getSdk()->getGlacier();\n $tmpFile = sys_get_temp_dir() . '/aws-php-sdk-integ-glacier-mup';\n file_put_contents($tmpFile, str_repeat('x', 2 * self::MB + 1024));\n\n $stream = Stream::factory(fopen($tmpFile, 'r'));\n if (!$seekable) {\n $stream = new NoSeekStream($stream);\n }\n\n $uploader = (new UploadBuilder)\n ->setClient($client)\n ->setVaultName(self::VAULT)\n ->setArchiveDescription($description)\n ->setSource($stream)\n ->setPartSize(self::MB)\n ->build();\n\n try {\n $result = $uploader->upload($concurrency);\n $this->assertArrayHasKey('location', $result);\n } catch (MultipartUploadException $e) {\n $uploader->abort();\n $message = \"=====\\n\";\n while ($e) {\n $message .= $e->getMessage() . \"\\n\";\n $e = $e->getPrevious();\n }\n $message .= \"=====\\n\";\n $this->fail($message);\n }\n\n @unlink($tmpFile);\n }\n}\n" }, { "alpha_fraction": 0.47507840394973755, "alphanum_fraction": 0.4930681586265564, "avg_line_length": 31.40106964111328, "blob_id": "e5807c6126f84959a93a67fa16baa9296ce6d7a5", "content_id": "f004e6165dc84acdff908e49cc82a1c03df5e81c", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 12118, "license_type": "permissive", "max_line_length": 97, "num_lines": 374, "path": "/tests/S3/S3ClientTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\S3;\n\nuse Aws\\Credentials\\NullCredentials;\nuse Aws\\Result;\nuse Aws\\S3\\S3Client;\nuse Aws\\Test\\UsesServiceTrait;\nuse GuzzleHttp\\Command\\Event\\PreparedEvent;\nuse GuzzleHttp\\Stream\\FnStream;\nuse GuzzleHttp\\Stream\\Stream;\nuse GuzzleHttp\\Stream\\StreamInterface;\n\n/**\n * @covers Aws\\S3\\S3Client\n */\nclass S3ClientTest extends \\PHPUnit_Framework_TestCase\n{\n use UsesServiceTrait;\n\n public function testCanForcePathStyleOnAllOperations()\n {\n $c = new S3Client([\n 'version' => 'latest',\n 'force_path_style' => true\n ]);\n\n $this->addMockResults($c, [[]]);\n $command = $c->getCommand('GetObject', [\n 'Bucket' => 'foo',\n 'Key' => 'baz'\n ]);\n $c->execute($command);\n $this->assertTrue($command['PathStyle']);\n }\n\n public function testCreatesClientWithSubscribers()\n {\n $c = new S3Client(['version' => 'latest']);\n $l = $c->getEmitter()->listeners();\n\n $found = [];\n foreach ($l as $value) {\n foreach ($value as $val) {\n $found[] = is_array($val)\n ? get_class($val[0])\n : get_class($val);\n }\n }\n\n $this->assertContains('Aws\\Subscriber\\SourceFile', $found);\n $this->assertContains('Aws\\S3\\BucketStyleSubscriber', $found);\n $this->assertContains('Aws\\S3\\ApplyMd5Subscriber', $found);\n $this->assertContains('Aws\\S3\\PermanentRedirectSubscriber', $found);\n $this->assertContains('Aws\\S3\\PutObjectUrlSubscriber', $found);\n }\n\n public function testCanUseBucketEndpoint()\n {\n $c = new S3Client([\n 'version' => 'latest',\n 'endpoint' => 'http://test.domain.com',\n 'bucket_endpoint' => true\n ]);\n $this->assertEquals(\n 'http://test.domain.com/key',\n $c->getObjectUrl('test', 'key')\n );\n }\n\n public function testAddsMd5ToConfig()\n {\n $c = new S3Client([\n 'version' => 'latest',\n 'calculate_md5' => true\n ]);\n $this->assertTrue($c->getConfig('calculate_md5'));\n }\n\n public function bucketNameProvider()\n {\n return [\n ['.bucket', false],\n ['bucket.', false],\n ['192.168.1.1', false],\n ['1.1.1.100', false],\n ['test@42!@$5_', false],\n ['ab', false],\n ['12', false],\n ['bucket_name', false],\n ['bucket-name', true],\n ['bucket', true],\n ['my.bucket.com', true],\n ['test-fooCaps', false],\n ['w-w', true],\n ['w------', false]\n ];\n }\n\n /**\n * @dataProvider bucketNameProvider\n */\n public function testValidatesDnsBucketNames($bucket, $valid)\n {\n $this->assertEquals($valid, s3Client::isBucketDnsCompatible($bucket));\n $this->assertEquals($valid, s3Client::isValidBucketName($bucket));\n }\n\n /**\n * @covers Aws\\S3\\S3Client::createPresignedUrl\n */\n public function testCreatesPresignedUrls()\n {\n $client = $this->getTestClient('S3', [\n 'region' => 'us-east-1',\n 'credentials' => ['key' => 'foo', 'secret' => 'bar']\n ]);\n $command = $client->getCommand('GetObject', ['Bucket' => 'foo', 'Key' => 'bar']);\n $url = $client->createPresignedUrl($command, 1342138769);\n $this->assertContains(\n 'https://foo.s3.amazonaws.com/bar?AWSAccessKeyId=',\n $url\n );\n $this->assertContains('Expires=', $url);\n $this->assertContains('Signature=', $url);\n }\n\n /**\n * @covers Aws\\S3\\S3Client::createPresignedUrl\n */\n public function testCreatesPresignedUrlsWithSpecialCharacters()\n {\n $client = S3Client::factory([\n 'region' => 'us-east-1',\n 'version' => 'latest',\n 'credentials' => ['key' => 'foo', 'secret' => 'bar']\n ]);\n $command = $client->getCommand('GetObject', [\n 'Bucket' => 'foobar test: abc',\n 'Key' => '+%.a'\n ]);\n $url = $client->createPresignedUrl($command, 1342138769);\n $this->assertContains(\n 'https://s3.amazonaws.com/foobar%20test%3A%20abc/%2B%25.a?AWSAccessKeyId=',\n $url\n );\n }\n\n public function testClearsBucket()\n {\n $s3 = $this->getTestClient('S3', ['region' => 'us-east-1']);\n $this->addMockResults($s3, [[]]);\n $s3->clearBucket('foo');\n }\n\n public function testRegistersStreamWrapper()\n {\n $s3 = $this->getTestClient('S3', ['region' => 'us-east-1']);\n $s3->registerStreamWrapper();\n $this->assertContains('s3', stream_get_wrappers());\n stream_wrapper_unregister('s3');\n }\n\n public function doesExistProvider()\n {\n return [\n ['foo', null, true, []],\n ['foo', 'bar', true, []],\n ['foo', null, true, $this->getS3ErrorMock('AccessDenied', 403)],\n ['foo', 'bar', true, $this->getS3ErrorMock('AccessDenied', 403)],\n ['foo', null, false, $this->getS3ErrorMock('Foo', 401)],\n ['foo', 'bar', false, $this->getS3ErrorMock('Foo', 401)],\n ['foo', null, -1, $this->getS3ErrorMock('Foo', 500)],\n ['foo', 'bar', -1, $this->getS3ErrorMock('Foo', 500)],\n ];\n }\n\n private function getS3ErrorMock($errCode, $statusCode)\n {\n $e = $this->getMockBuilder('Aws\\S3\\Exception\\S3Exception')\n ->disableOriginalConstructor()\n ->setMethods(['getAwsErrorCode', 'getStatusCode'])\n ->getMock();\n $e->expects($this->any())\n ->method('getAwsErrorCode')\n ->will($this->returnValue($errCode));\n $e->expects($this->any())\n ->method('getStatusCode')\n ->will($this->returnValue($statusCode));\n\n return $e;\n }\n\n /**\n * @dataProvider doesExistProvider\n */\n public function testsIfExists($bucket, $key, $exists, $result)\n {\n $s3 = $this->getTestClient('S3', ['region' => 'us-east-1']);\n $this->addMockResults($s3, [$result]);\n try {\n if ($key) {\n $this->assertSame($exists, $s3->doesObjectExist($bucket, $key));\n } else {\n $this->assertSame($exists, $s3->doesBucketExist($bucket));\n }\n } catch (\\Exception $e) {\n $this->assertEquals(-1, $exists);\n }\n }\n\n public function testReturnsObjectUrl()\n {\n $s3 = $this->getTestClient('S3', [\n 'region' => 'us-east-1',\n 'credentials' => new NullCredentials()\n ]);\n $this->assertEquals('https://foo.s3.amazonaws.com/bar', $s3->getObjectUrl('foo', 'bar'));\n }\n\n public function testReturnsObjectUrlViaPath()\n {\n $s3 = $this->getTestClient('S3', [\n 'region' => 'us-east-1',\n 'credentials' => new NullCredentials()\n ]);\n $this->assertEquals(\n 'https://s3.amazonaws.com/foo.baz/bar',\n $s3->getObjectUrl('foo.baz', 'bar')\n );\n }\n\n /**\n * @dataProvider getUploadTestCases\n */\n public function testUploadHelperDoesCorrectOperation(\n StreamInterface $body,\n array $mockedResults,\n array $options\n ) {\n /** @var \\Aws\\S3\\S3Client $client */\n $client = $this->getTestClient('S3');\n $this->addMockResults($client, $mockedResults);\n $result = $client->upload('bucket', 'key', $body, 'private', $options);\n $this->assertEquals('https://bucket.s3.amazonaws.com/key', $result['ObjectURL']);\n }\n\n /**\n * @expectedException \\RuntimeException\n */\n public function testEnsuresPrefixOrRegexSuppliedForDeleteMatchingObjects()\n {\n $client = $this->getTestClient('S3');\n $client->deleteMatchingObjects('foo');\n }\n\n public function testDeletesMatchingObjectsByPrefixAndRegex()\n {\n $client = $this->getTestClient('S3');\n\n $client->getEmitter()->on('prepared', function (PreparedEvent $e) {\n $this->assertEquals('bucket', $e->getCommand()['Bucket']);\n $e->intercept(new Result([\n 'IsTruncated' => false,\n 'Marker' => '',\n 'Contents' => [\n ['Key' => 'foo/bar'],\n ['Key' => 'foo/bar/baz'],\n ['Key' => 'foo/test'],\n ['Key' => 'foo/bar/bam'],\n ['Key' => 'foo/bar/001'],\n ['Key' => 'foo/other']\n ]\n ]));\n });\n\n $agg = [];\n $client->deleteMatchingObjects('bucket', 'foo/bar/', '/^foo\\/bar\\/[a-z]+$/', [\n 'before' => function ($iter, array $keys) use (&$agg) {\n foreach ($keys as $k) {\n $agg[] = $k['Key'];\n }\n }\n ]);\n\n $this->assertEquals(['foo/bar/baz', 'foo/bar/bam'], $agg);\n }\n\n public function getUploadTestCases()\n {\n $putObject = new Result([]);\n $initiate = new Result(['UploadId' => 'foo']);\n $putPart = new Result(['ETag' => 'bar']);\n $complete = new Result(['Location' => 'https://bucket.s3.amazonaws.com/key']);\n\n return [\n [\n // 3 MB, known-size stream (put)\n $this->generateStream(1024 * 1024 * 3),\n [$putObject],\n []\n ],\n [\n // 3 MB, unknown-size stream (put)\n $this->generateStream(1024 * 1024 * 3, false),\n [$putObject],\n []\n ],\n [\n // 6 MB, known-size stream (put)\n $this->generateStream(1024 * 1024 * 6),\n [$putObject],\n []\n ],\n [\n // 6 MB, known-size stream, above threshold (mup)\n $this->generateStream(1024 * 1024 * 6),\n [$initiate, $putPart, $putPart, $complete],\n ['threshold' => 1024 * 1024 * 4]\n ],\n [\n // 6 MB, unknown-size stream (mup)\n $this->generateStream(1024 * 1024 * 6, false),\n [$initiate, $putPart, $putPart, $complete],\n []\n ],\n [\n // 6 MB, unknown-size, non-seekable stream (mup)\n $this->generateStream(1024 * 1024 * 6, false, false),\n [$initiate, $putPart, $putPart, $complete],\n []\n ]\n ];\n }\n\n private function generateStream($size, $sizeKnown = true, $seekable = true)\n {\n return FnStream::decorate(Stream::factory(str_repeat('.', $size)), [\n 'getSize' => function () use ($sizeKnown, $size) {\n return $sizeKnown ? $size : null;\n },\n 'isSeekable' => function () use ($seekable) {\n return (bool) $seekable;\n }\n ]);\n }\n\n public function testProxiesToTransferObjectPut()\n {\n $client = $this->getTestClient('S3');\n $c = null;\n $client->getEmitter()->on('prepared', function (PreparedEvent $e) use (&$c) {\n $this->assertEquals('PutObject', $e->getCommand()->getName());\n $this->assertEquals('test', $e->getCommand()['Bucket']);\n $e->intercept(new Result([]));\n $c = true;\n });\n $client->uploadDirectory(__DIR__, 'test');\n $this->assertTrue($c);\n }\n\n public function testProxiesToTransferObjectGet()\n {\n $client = $this->getTestClient('S3');\n $c = null;\n $client->getEmitter()->on('prepared', function (PreparedEvent $e) use (&$c) {\n $n = $e->getCommand()->getName();\n $this->assertTrue($n == 'GetObject' || $n == 'ListObjects');\n $e->intercept(new Result([]));\n $c = true;\n });\n $client->downloadBucket(__DIR__, 'test');\n $this->assertTrue($c);\n }\n}\n" }, { "alpha_fraction": 0.45631641149520874, "alphanum_fraction": 0.46871310472488403, "avg_line_length": 29.52252197265625, "blob_id": "eef4bb24242143d1ee506830dad369c6193df2b7", "content_id": "cdef8e808d43fe34b1d029e983fe02b901e0715a", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3388, "license_type": "permissive", "max_line_length": 103, "num_lines": 111, "path": "/tests/S3/ApplyMd5SubscriberTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\S3\\Subscriber;\n\nuse Aws\\S3\\Exception\\S3Exception;\nuse Aws\\Test\\UsesServiceTrait;\nuse GuzzleHttp\\Command\\Event\\PreparedEvent;\nuse GuzzleHttp\\Message\\Response;\nuse GuzzleHttp\\Stream\\Stream;\nuse GuzzleHttp\\Stream\\NoSeekStream;\n\n/**\n * @covers Aws\\S3\\ApplyMd5Subscriber\n */\nclass ApplyMd5SubscriberTest extends \\PHPUnit_Framework_TestCase\n{\n use UsesServiceTrait;\n\n public function testThrowsExceptionIfBodyIsNotSeekable()\n {\n $s3 = $this->getTestClient('s3');\n $command = $s3->getCommand('PutObject', [\n 'Bucket' => 'foo',\n 'Key' => 'bar',\n 'Body' => new NoSeekStream(Stream::factory('foo')),\n ]);\n try {\n $s3->execute($command);\n $this->fail('An exception should have been thrown.');\n } catch (S3Exception $e) {\n $this->assertInstanceOf(\n 'Aws\\Exception\\CouldNotCreateChecksumException',\n $e->getPrevious()\n );\n }\n }\n\n /**\n * @dataProvider getContentMd5UseCases\n */\n public function testAddsContentMd5AsAppropriate($options, $operation, $args, $md5Added, $md5Value)\n {\n $s3 = $this->getTestClient('s3', $options);\n $this->addMockResponses($s3, [new Response(200)]);\n\n $command = $s3->getCommand($operation, $args);\n $command->getEmitter()->on('prepared', function (PreparedEvent $e) use ($md5Added, $md5Value) {\n $this->assertSame($md5Added, $e->getRequest()->hasHeader('Content-MD5'));\n if ($md5Value !== 'SKIP') {\n $this->assertEquals($md5Value, $e->getRequest()->getHeader('Content-MD5'));\n }\n }, 'last');\n $s3->execute($command);\n }\n\n public function getContentMd5UseCases()\n {\n $args = ['Bucket' => 'foo', 'Key' => 'bar'];\n $md5 = base64_encode(md5('baz', true));\n\n return [\n // Do nothing if Content MD% was explicitly provided.\n [\n [],\n 'PutObject',\n $args + ['ContentMD5' => $md5],\n true,\n $md5\n ],\n // Gets added for operations that require it\n [\n [],\n 'DeleteObjects',\n ['Bucket' => 'foo', 'Delete' => ['Objects' => [['Key' => 'bar']]]],\n true,\n 'SKIP'\n ],\n // Gets added for upload operations by default\n [\n [],\n 'PutObject',\n $args + ['Body' => 'baz'],\n true,\n $md5,\n ],\n // Not added for upload operations when turned off at client level\n [\n ['calculate_md5' => false],\n 'PutObject',\n $args + ['Body' => 'baz'],\n false,\n null,\n ],\n // Not added for operations that does not require it\n [\n [],\n 'GetObject',\n $args,\n false,\n null,\n ],\n // Not added to upload operations when using SigV4\n [\n ['signature_version' => 'v4'],\n 'PutObject',\n $args + ['Body' => 'baz'],\n false,\n null,\n ],\n ];\n }\n}\n" }, { "alpha_fraction": 0.5489078760147095, "alphanum_fraction": 0.5645774006843567, "avg_line_length": 29.521739959716797, "blob_id": "7bb01ed9d3a532ac55f7bfed334b2f1b785c7f73", "content_id": "6c9557e2a8a3ffa6b3ded9290e21d64573e34761", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2106, "license_type": "permissive", "max_line_length": 77, "num_lines": 69, "path": "/tests/Sqs/Md5ValidatorSubscriberTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Sqs;\n\nuse Aws\\Result;\nuse Aws\\Sqs\\Md5ValidatorSubscriber;\nuse Aws\\Sqs\\SqsClient;\nuse GuzzleHttp\\Command\\CommandTransaction;\nuse GuzzleHttp\\Command\\Event\\ProcessEvent;\n\n/**\n * @covers Aws\\Sqs\\Md5ValidatorSubscriber\n */\nclass Md5ValidatorSubscriberTest extends \\PHPUnit_Framework_TestCase\n{\n /**\n * @expectedException \\Aws\\Sqs\\Exception\\SqsException\n */\n public function testValidatesMd5WithException()\n {\n $model = new Result([\n 'Messages' => [['MD5OfBody' => 'foo', 'Body' => 'Bar']]\n ]);\n $client = SqsClient::factory([\n 'region' => 'us-west-2',\n 'version' => 'latest'\n ]);\n $command = $client->getCommand('ReceiveMessage');\n $event = new ProcessEvent(new CommandTransaction($client, $command));\n $event->setResult($model);\n $listener = new Md5ValidatorSubscriber();\n $listener->onProcess($event);\n }\n\n public function testValidatesMd5()\n {\n $model = new Result([\n 'Messages' => [\n [\n 'MD5OfBody' => 'fafb00f5732ab283681e124bf8747ed1',\n 'Body' => 'This is a test message'\n ]\n ]\n ]);\n\n $client = SqsClient::factory([\n 'region' => 'us-west-2',\n 'version' => 'latest'\n ]);\n $command = $client->getCommand('ReceiveMessage');\n $event = new ProcessEvent(new CommandTransaction($client, $command));\n $event->setResult($model);\n $listener = new Md5ValidatorSubscriber();\n $listener->onProcess($event);\n }\n\n public function testIgnoresIrrelevantCommands()\n {\n $model = new Result([]);\n $client = SqsClient::factory([\n 'region' => 'us-west-2',\n 'version' => 'latest'\n ]);\n $command = $client->getCommand('ListQueues');\n $event = new ProcessEvent(new CommandTransaction($client, $command));\n $event->setResult($model);\n $listener = new Md5ValidatorSubscriber();\n $listener->onProcess($event);\n }\n}\n" }, { "alpha_fraction": 0.6091825366020203, "alphanum_fraction": 0.6103023290634155, "avg_line_length": 27.80645179748535, "blob_id": "bc542ab1a44b2cab0a0d8450d6e69d7ea82a6ebc", "content_id": "e666bdfc61bbb88a629183820cb7ecd7548fc975", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 893, "license_type": "permissive", "max_line_length": 64, "num_lines": 31, "path": "/tests/Subscriber/SaveAsTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\TestCommon\\Subscriber;\n\nuse Aws\\Test\\UsesServiceTrait;\nuse GuzzleHttp\\Command\\CommandTransaction;\nuse GuzzleHttp\\Command\\Event\\PreparedEvent;\nuse GuzzleHttp\\Message\\Request;\n\n/**\n * @covers Aws\\Subscriber\\SaveAs\n */\nclass SaveAsTest extends \\PHPUnit_Framework_TestCase\n{\n use UsesServiceTrait;\n\n public function testModifiesRequestWithSaveTo()\n {\n $client = $this->getTestClient('s3');\n $command = $client->getCommand('GetObject', [\n 'Bucket' => 'a',\n 'Key' => 'b',\n 'SaveAs' => '/abc'\n ]);\n $trans = new CommandTransaction($client, $command);\n $r = new Request('GET', 'http://foo.com');\n $trans->request = $r;\n $event = new PreparedEvent($trans);\n $command->getEmitter()->emit('prepared', $event);\n $this->assertEquals('/abc', $r->getConfig()['save_to']);\n }\n}\n" }, { "alpha_fraction": 0.6273584961891174, "alphanum_fraction": 0.6367924809455872, "avg_line_length": 24.696969985961914, "blob_id": "420b10aeaf9bd1992b38e740f5e5fc470683ad96", "content_id": "6e1ed1594d30552a030953f4f86d12490767229b", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 848, "license_type": "permissive", "max_line_length": 71, "num_lines": 33, "path": "/src/S3/PermanentRedirectSubscriber.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\S3;\n\nuse Aws\\S3\\Exception\\PermanentRedirectException;\nuse GuzzleHttp\\Command\\Event\\ProcessEvent;\nuse GuzzleHttp\\Event\\SubscriberInterface;\n\n/**\n * Throws a PermanentRedirectException exception when a 301 redirect is\n * encountered.\n *\n * @internal\n */\nclass PermanentRedirectSubscriber implements SubscriberInterface\n{\n public function getEvents()\n {\n return ['process' => ['checkForPermanentRedirect', 'last']];\n }\n\n public function checkForPermanentRedirect(ProcessEvent $e)\n {\n $res = $e->getResponse();\n\n if ($res && $res->getStatusCode() == 301) {\n throw new PermanentRedirectException(\n 'Encountered a permanent redirect while requesting '\n . $e->getRequest()->getUrl(),\n $e->getTransaction()\n );\n }\n }\n}\n" }, { "alpha_fraction": 0.4470720589160919, "alphanum_fraction": 0.4485735595226288, "avg_line_length": 32.09316635131836, "blob_id": "f762f41a16f6191f2097814e76893badb3b818fd", "content_id": "fc7e1dc4290264ec6b567c0ef47568e89047d609", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 5328, "license_type": "permissive", "max_line_length": 116, "num_lines": 161, "path": "/build/docs/classes/ThemeBuilder.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\n\nnamespace Aws\\Build\\Docs;\n\nclass ThemeBuilder\n{\n private $html;\n private $operation;\n private $skipLevel;\n private $isInput;\n\n public function __construct($operation, $isInput = true)\n {\n $this->html = new HtmlDocument();\n $this->operation = $operation;\n $this->skipLevel = 0;\n $this->isInput = $isInput;\n }\n\n public function getHtml()\n {\n return $this->html;\n }\n\n public function addShape(array $shape)\n {\n // Handle skips and closers\n if ($this->skipLevel) {\n $this->skipLevel--;\n return;\n } elseif ($shape['name'] === 'closer') {\n $this->html->close();\n $this->html->close();\n return;\n }\n\n // Write the parameter key.\n $this->html->open('li', 'parameter');\n\n $key = htmlentities($shape['param'] . ' => ' . $this->getTypeLabel($shape));\n $this->html->open('h4', ['id' => $this->getPathAnchor($shape['path'])])\n ->elem('span', 'param-title', $key);\n if ($this->isInput && $shape['required']) {\n $this->html->elem('span', 'required label label-danger', 'required');\n }\n $this->html->close(true);\n\n if (is_array($shape['enum'])) {\n $message = $this->getEnumConstraint($shape);\n $this->html->elem('div', 'alert alert-info', \"<b>Constraint:</b> {$message}\");\n }\n\n if ($shape['min'] || $shape['max']) {\n $message = $this->addMinMaxConstraint($shape);\n $this->html->elem('div', 'alert alert-info', \"<b>Constraint:</b> {$message}\");\n }\n\n if ($shape['docs']) {\n $this->html->elem('div', 'well', $shape['docs']);\n }\n\n // Write the parameter value.\n if ($shape['complex']) {\n if ($shape['recursive']) {\n $path = implode('.', $shape['recursive']);\n $this->html->elem('div', 'alert alert-warning', '<strong>This '\n . 'is a recursive parameter.</strong> Click <a href=\"#'\n . $this->getPathAnchor($path) . '\">here</a> to jump back to'\n . ' <code>' . htmlentities($path) . '</code>.');\n $this->html->close();\n } elseif (!in_array($shape['complex'], ['structure', 'list', 'map', 'mixed'])) {\n $this->skipLevel += 2;\n $this->html->close();\n } else {\n $this->html->open('ul');\n }\n } else {\n $this->html->close();\n }\n }\n\n private function getPathAnchor($path)\n {\n if (is_array($path)) {\n $path = implode('', $path);\n }\n $path = strtr($path, ['<' => '', '>' => '']);\n\n return $this->html->slug($this->operation . '-' . $path);\n }\n\n private function getEnumConstraint(array $shape)\n {\n $values = array_map(\n function ($v) { return \"<em>{$v}</em>\"; },\n $shape['enum']\n );\n $last = array_pop($values);\n $comma = count($values) > 1 ? ',' : '';\n $content = implode(', ', $values) . $comma . ' or ' . $last;\n\n return \"The value must be one of the following: {$content}.\";\n }\n\n private function addMinMaxConstraint(array $shape)\n {\n if ($shape['type'] === 'integer') {\n $message = ['be', '>= %s', '<= %s'];\n } elseif ($shape['type'] === 'string' || $shape['type'] === 'stream') {\n $message = ['have', 'a minimum length of %s', 'a maximum length of %s'];\n } elseif ($shape['type'] === 'list' || $shape['type'] === 'map') {\n $message = ['have', 'at least %s item%s', 'at most %s items'];\n } else {\n throw new \\UnexpectedValueException('Type ' . $shape['type'] . ' not handled for min/max constraints.');\n }\n\n $content = $message[0];\n if (isset($shape['min'])) {\n $content .= ' '\n . sprintf($message[1], $shape['min'], ($shape['min'] > 1) ? 's' : '')\n . (isset($shape['max']) ? ' and' : '');\n }\n if (isset($shape['max'])) {\n $content .= ' ' . sprintf($message[2], $shape['max']);\n }\n\n return \"The value must {$content}.\";\n }\n\n private function getTypeLabel($shape)\n {\n if (!is_array($shape)) {\n $shape = ['type' => $shape, 'complex' => null];\n }\n\n switch ($shape['type']) {\n case 'structure':\n return ($shape['complex']) ? 'array<string,mixed>' : 'array';\n case 'map':\n $type = 'array';\n if ($subType = $shape['complex']) {\n $subType = $this->getTypeLabel($subType);\n $type .= \"<string,{$subType}>\";\n }\n return $type;\n case 'list':\n $type = 'array';\n if ($subType = $shape['complex']) {\n $subType = $this->getTypeLabel($subType);\n $type .= \"<{$subType}>\";\n }\n return $type;\n case 'timestamp':\n return 'string|int|\\\\DateTime';\n case 'stream':\n return 'GuzzleHttp\\\\Stream\\\\Stream';\n default:\n return $shape['type'];\n }\n }\n}\n" }, { "alpha_fraction": 0.4192522168159485, "alphanum_fraction": 0.4199415445327759, "avg_line_length": 24.067523956298828, "blob_id": "93e5e2e7235f8c6c0f134a360214310c22109cae", "content_id": "554e9facd6efc3f6783cecadbd1e1c0844e4c7f8", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 282887, "license_type": "permissive", "max_line_length": 72, "num_lines": 11285, "path": "/src/data/ec2-2014-10-01.api.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php return [\n 'metadata' => [\n 'apiVersion' => '2014-10-01',\n 'endpointPrefix' => 'ec2',\n 'serviceAbbreviation' => 'Amazon EC2',\n 'serviceFullName' => 'Amazon Elastic Compute Cloud',\n 'signatureVersion' => 'v4',\n 'xmlNamespace' => 'http://ec2.amazonaws.com/doc/2014-10-01',\n 'protocol' => 'ec2',\n 'compatibleApiVersions' => [\n '2014-09-01',\n '2014-06-15',\n '2014-05-01',\n '2014-02-01',\n '2013-10-15',\n '2013-10-01',\n '2013-08-15',\n '2013-07-15',\n '2013-06-15',\n '2013-02-01'\n ],\n ],\n 'operations' => [\n 'AcceptVpcPeeringConnection' => [\n 'name' => 'AcceptVpcPeeringConnection',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'AcceptVpcPeeringConnectionRequest',\n ],\n 'output' => [\n 'shape' => 'AcceptVpcPeeringConnectionResult',\n ],\n ],\n 'AllocateAddress' => [\n 'name' => 'AllocateAddress',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'AllocateAddressRequest',\n ],\n 'output' => [\n 'shape' => 'AllocateAddressResult',\n ],\n ],\n 'AssignPrivateIpAddresses' => [\n 'name' => 'AssignPrivateIpAddresses',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'AssignPrivateIpAddressesRequest',\n ],\n ],\n 'AssociateAddress' => [\n 'name' => 'AssociateAddress',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'AssociateAddressRequest',\n ],\n 'output' => [\n 'shape' => 'AssociateAddressResult',\n ],\n ],\n 'AssociateDhcpOptions' => [\n 'name' => 'AssociateDhcpOptions',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'AssociateDhcpOptionsRequest',\n ],\n ],\n 'AssociateRouteTable' => [\n 'name' => 'AssociateRouteTable',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'AssociateRouteTableRequest',\n ],\n 'output' => [\n 'shape' => 'AssociateRouteTableResult',\n ],\n ],\n 'AttachClassicLinkVpc' => [\n 'name' => 'AttachClassicLinkVpc',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'AttachClassicLinkVpcRequest',\n ],\n 'output' => [\n 'shape' => 'AttachClassicLinkVpcResult',\n ],\n ],\n 'AttachInternetGateway' => [\n 'name' => 'AttachInternetGateway',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'AttachInternetGatewayRequest',\n ],\n ],\n 'AttachNetworkInterface' => [\n 'name' => 'AttachNetworkInterface',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'AttachNetworkInterfaceRequest',\n ],\n 'output' => [\n 'shape' => 'AttachNetworkInterfaceResult',\n ],\n ],\n 'AttachVolume' => [\n 'name' => 'AttachVolume',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'AttachVolumeRequest',\n ],\n 'output' => [\n 'shape' => 'VolumeAttachment',\n 'locationName' => 'attachment',\n ],\n ],\n 'AttachVpnGateway' => [\n 'name' => 'AttachVpnGateway',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'AttachVpnGatewayRequest',\n ],\n 'output' => [\n 'shape' => 'AttachVpnGatewayResult',\n ],\n ],\n 'AuthorizeSecurityGroupEgress' => [\n 'name' => 'AuthorizeSecurityGroupEgress',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'AuthorizeSecurityGroupEgressRequest',\n ],\n ],\n 'AuthorizeSecurityGroupIngress' => [\n 'name' => 'AuthorizeSecurityGroupIngress',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'AuthorizeSecurityGroupIngressRequest',\n ],\n ],\n 'BundleInstance' => [\n 'name' => 'BundleInstance',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'BundleInstanceRequest',\n ],\n 'output' => [\n 'shape' => 'BundleInstanceResult',\n ],\n ],\n 'CancelBundleTask' => [\n 'name' => 'CancelBundleTask',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CancelBundleTaskRequest',\n ],\n 'output' => [\n 'shape' => 'CancelBundleTaskResult',\n ],\n ],\n 'CancelConversionTask' => [\n 'name' => 'CancelConversionTask',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CancelConversionRequest',\n ],\n ],\n 'CancelExportTask' => [\n 'name' => 'CancelExportTask',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CancelExportTaskRequest',\n ],\n ],\n 'CancelReservedInstancesListing' => [\n 'name' => 'CancelReservedInstancesListing',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CancelReservedInstancesListingRequest',\n ],\n 'output' => [\n 'shape' => 'CancelReservedInstancesListingResult',\n ],\n ],\n 'CancelSpotInstanceRequests' => [\n 'name' => 'CancelSpotInstanceRequests',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CancelSpotInstanceRequestsRequest',\n ],\n 'output' => [\n 'shape' => 'CancelSpotInstanceRequestsResult',\n ],\n ],\n 'ConfirmProductInstance' => [\n 'name' => 'ConfirmProductInstance',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ConfirmProductInstanceRequest',\n ],\n 'output' => [\n 'shape' => 'ConfirmProductInstanceResult',\n ],\n ],\n 'CopyImage' => [\n 'name' => 'CopyImage',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CopyImageRequest',\n ],\n 'output' => [\n 'shape' => 'CopyImageResult',\n ],\n ],\n 'CopySnapshot' => [\n 'name' => 'CopySnapshot',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CopySnapshotRequest',\n ],\n 'output' => [\n 'shape' => 'CopySnapshotResult',\n ],\n ],\n 'CreateCustomerGateway' => [\n 'name' => 'CreateCustomerGateway',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateCustomerGatewayRequest',\n ],\n 'output' => [\n 'shape' => 'CreateCustomerGatewayResult',\n ],\n ],\n 'CreateDhcpOptions' => [\n 'name' => 'CreateDhcpOptions',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateDhcpOptionsRequest',\n ],\n 'output' => [\n 'shape' => 'CreateDhcpOptionsResult',\n ],\n ],\n 'CreateImage' => [\n 'name' => 'CreateImage',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateImageRequest',\n ],\n 'output' => [\n 'shape' => 'CreateImageResult',\n ],\n ],\n 'CreateInstanceExportTask' => [\n 'name' => 'CreateInstanceExportTask',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateInstanceExportTaskRequest',\n ],\n 'output' => [\n 'shape' => 'CreateInstanceExportTaskResult',\n ],\n ],\n 'CreateInternetGateway' => [\n 'name' => 'CreateInternetGateway',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateInternetGatewayRequest',\n ],\n 'output' => [\n 'shape' => 'CreateInternetGatewayResult',\n ],\n ],\n 'CreateKeyPair' => [\n 'name' => 'CreateKeyPair',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateKeyPairRequest',\n ],\n 'output' => [\n 'shape' => 'KeyPair',\n 'locationName' => 'keyPair',\n ],\n ],\n 'CreateNetworkAcl' => [\n 'name' => 'CreateNetworkAcl',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateNetworkAclRequest',\n ],\n 'output' => [\n 'shape' => 'CreateNetworkAclResult',\n ],\n ],\n 'CreateNetworkAclEntry' => [\n 'name' => 'CreateNetworkAclEntry',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateNetworkAclEntryRequest',\n ],\n ],\n 'CreateNetworkInterface' => [\n 'name' => 'CreateNetworkInterface',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateNetworkInterfaceRequest',\n ],\n 'output' => [\n 'shape' => 'CreateNetworkInterfaceResult',\n ],\n ],\n 'CreatePlacementGroup' => [\n 'name' => 'CreatePlacementGroup',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreatePlacementGroupRequest',\n ],\n ],\n 'CreateReservedInstancesListing' => [\n 'name' => 'CreateReservedInstancesListing',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateReservedInstancesListingRequest',\n ],\n 'output' => [\n 'shape' => 'CreateReservedInstancesListingResult',\n ],\n ],\n 'CreateRoute' => [\n 'name' => 'CreateRoute',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateRouteRequest',\n ],\n ],\n 'CreateRouteTable' => [\n 'name' => 'CreateRouteTable',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateRouteTableRequest',\n ],\n 'output' => [\n 'shape' => 'CreateRouteTableResult',\n ],\n ],\n 'CreateSecurityGroup' => [\n 'name' => 'CreateSecurityGroup',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateSecurityGroupRequest',\n ],\n 'output' => [\n 'shape' => 'CreateSecurityGroupResult',\n ],\n ],\n 'CreateSnapshot' => [\n 'name' => 'CreateSnapshot',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateSnapshotRequest',\n ],\n 'output' => [\n 'shape' => 'Snapshot',\n 'locationName' => 'snapshot',\n ],\n ],\n 'CreateSpotDatafeedSubscription' => [\n 'name' => 'CreateSpotDatafeedSubscription',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateSpotDatafeedSubscriptionRequest',\n ],\n 'output' => [\n 'shape' => 'CreateSpotDatafeedSubscriptionResult',\n ],\n ],\n 'CreateSubnet' => [\n 'name' => 'CreateSubnet',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateSubnetRequest',\n ],\n 'output' => [\n 'shape' => 'CreateSubnetResult',\n ],\n ],\n 'CreateTags' => [\n 'name' => 'CreateTags',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateTagsRequest',\n ],\n ],\n 'CreateVolume' => [\n 'name' => 'CreateVolume',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateVolumeRequest',\n ],\n 'output' => [\n 'shape' => 'Volume',\n 'locationName' => 'volume',\n ],\n ],\n 'CreateVpc' => [\n 'name' => 'CreateVpc',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateVpcRequest',\n ],\n 'output' => [\n 'shape' => 'CreateVpcResult',\n ],\n ],\n 'CreateVpcPeeringConnection' => [\n 'name' => 'CreateVpcPeeringConnection',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateVpcPeeringConnectionRequest',\n ],\n 'output' => [\n 'shape' => 'CreateVpcPeeringConnectionResult',\n ],\n ],\n 'CreateVpnConnection' => [\n 'name' => 'CreateVpnConnection',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateVpnConnectionRequest',\n ],\n 'output' => [\n 'shape' => 'CreateVpnConnectionResult',\n ],\n ],\n 'CreateVpnConnectionRoute' => [\n 'name' => 'CreateVpnConnectionRoute',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateVpnConnectionRouteRequest',\n ],\n ],\n 'CreateVpnGateway' => [\n 'name' => 'CreateVpnGateway',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateVpnGatewayRequest',\n ],\n 'output' => [\n 'shape' => 'CreateVpnGatewayResult',\n ],\n ],\n 'DeleteCustomerGateway' => [\n 'name' => 'DeleteCustomerGateway',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteCustomerGatewayRequest',\n ],\n ],\n 'DeleteDhcpOptions' => [\n 'name' => 'DeleteDhcpOptions',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteDhcpOptionsRequest',\n ],\n ],\n 'DeleteInternetGateway' => [\n 'name' => 'DeleteInternetGateway',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteInternetGatewayRequest',\n ],\n ],\n 'DeleteKeyPair' => [\n 'name' => 'DeleteKeyPair',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteKeyPairRequest',\n ],\n ],\n 'DeleteNetworkAcl' => [\n 'name' => 'DeleteNetworkAcl',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteNetworkAclRequest',\n ],\n ],\n 'DeleteNetworkAclEntry' => [\n 'name' => 'DeleteNetworkAclEntry',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteNetworkAclEntryRequest',\n ],\n ],\n 'DeleteNetworkInterface' => [\n 'name' => 'DeleteNetworkInterface',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteNetworkInterfaceRequest',\n ],\n ],\n 'DeletePlacementGroup' => [\n 'name' => 'DeletePlacementGroup',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeletePlacementGroupRequest',\n ],\n ],\n 'DeleteRoute' => [\n 'name' => 'DeleteRoute',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteRouteRequest',\n ],\n ],\n 'DeleteRouteTable' => [\n 'name' => 'DeleteRouteTable',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteRouteTableRequest',\n ],\n ],\n 'DeleteSecurityGroup' => [\n 'name' => 'DeleteSecurityGroup',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteSecurityGroupRequest',\n ],\n ],\n 'DeleteSnapshot' => [\n 'name' => 'DeleteSnapshot',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteSnapshotRequest',\n ],\n ],\n 'DeleteSpotDatafeedSubscription' => [\n 'name' => 'DeleteSpotDatafeedSubscription',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteSpotDatafeedSubscriptionRequest',\n ],\n ],\n 'DeleteSubnet' => [\n 'name' => 'DeleteSubnet',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteSubnetRequest',\n ],\n ],\n 'DeleteTags' => [\n 'name' => 'DeleteTags',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteTagsRequest',\n ],\n ],\n 'DeleteVolume' => [\n 'name' => 'DeleteVolume',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteVolumeRequest',\n ],\n ],\n 'DeleteVpc' => [\n 'name' => 'DeleteVpc',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteVpcRequest',\n ],\n ],\n 'DeleteVpcPeeringConnection' => [\n 'name' => 'DeleteVpcPeeringConnection',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteVpcPeeringConnectionRequest',\n ],\n 'output' => [\n 'shape' => 'DeleteVpcPeeringConnectionResult',\n ],\n ],\n 'DeleteVpnConnection' => [\n 'name' => 'DeleteVpnConnection',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteVpnConnectionRequest',\n ],\n ],\n 'DeleteVpnConnectionRoute' => [\n 'name' => 'DeleteVpnConnectionRoute',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteVpnConnectionRouteRequest',\n ],\n ],\n 'DeleteVpnGateway' => [\n 'name' => 'DeleteVpnGateway',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteVpnGatewayRequest',\n ],\n ],\n 'DeregisterImage' => [\n 'name' => 'DeregisterImage',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeregisterImageRequest',\n ],\n ],\n 'DescribeAccountAttributes' => [\n 'name' => 'DescribeAccountAttributes',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeAccountAttributesRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeAccountAttributesResult',\n ],\n ],\n 'DescribeAddresses' => [\n 'name' => 'DescribeAddresses',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeAddressesRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeAddressesResult',\n ],\n ],\n 'DescribeAvailabilityZones' => [\n 'name' => 'DescribeAvailabilityZones',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeAvailabilityZonesRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeAvailabilityZonesResult',\n ],\n ],\n 'DescribeBundleTasks' => [\n 'name' => 'DescribeBundleTasks',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeBundleTasksRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeBundleTasksResult',\n ],\n ],\n 'DescribeClassicLinkInstances' => [\n 'name' => 'DescribeClassicLinkInstances',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeClassicLinkInstancesRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeClassicLinkInstancesResult',\n ],\n ],\n 'DescribeConversionTasks' => [\n 'name' => 'DescribeConversionTasks',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeConversionTasksRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeConversionTasksResult',\n ],\n ],\n 'DescribeCustomerGateways' => [\n 'name' => 'DescribeCustomerGateways',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeCustomerGatewaysRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeCustomerGatewaysResult',\n ],\n ],\n 'DescribeDhcpOptions' => [\n 'name' => 'DescribeDhcpOptions',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeDhcpOptionsRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeDhcpOptionsResult',\n ],\n ],\n 'DescribeExportTasks' => [\n 'name' => 'DescribeExportTasks',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeExportTasksRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeExportTasksResult',\n ],\n ],\n 'DescribeImageAttribute' => [\n 'name' => 'DescribeImageAttribute',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeImageAttributeRequest',\n ],\n 'output' => [\n 'shape' => 'ImageAttribute',\n 'locationName' => 'imageAttribute',\n ],\n ],\n 'DescribeImages' => [\n 'name' => 'DescribeImages',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeImagesRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeImagesResult',\n ],\n ],\n 'DescribeInstanceAttribute' => [\n 'name' => 'DescribeInstanceAttribute',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeInstanceAttributeRequest',\n ],\n 'output' => [\n 'shape' => 'InstanceAttribute',\n ],\n ],\n 'DescribeInstanceStatus' => [\n 'name' => 'DescribeInstanceStatus',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeInstanceStatusRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeInstanceStatusResult',\n ],\n ],\n 'DescribeInstances' => [\n 'name' => 'DescribeInstances',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeInstancesRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeInstancesResult',\n ],\n ],\n 'DescribeInternetGateways' => [\n 'name' => 'DescribeInternetGateways',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeInternetGatewaysRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeInternetGatewaysResult',\n ],\n ],\n 'DescribeKeyPairs' => [\n 'name' => 'DescribeKeyPairs',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeKeyPairsRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeKeyPairsResult',\n ],\n ],\n 'DescribeNetworkAcls' => [\n 'name' => 'DescribeNetworkAcls',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeNetworkAclsRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeNetworkAclsResult',\n ],\n ],\n 'DescribeNetworkInterfaceAttribute' => [\n 'name' => 'DescribeNetworkInterfaceAttribute',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeNetworkInterfaceAttributeRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeNetworkInterfaceAttributeResult',\n ],\n ],\n 'DescribeNetworkInterfaces' => [\n 'name' => 'DescribeNetworkInterfaces',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeNetworkInterfacesRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeNetworkInterfacesResult',\n ],\n ],\n 'DescribePlacementGroups' => [\n 'name' => 'DescribePlacementGroups',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribePlacementGroupsRequest',\n ],\n 'output' => [\n 'shape' => 'DescribePlacementGroupsResult',\n ],\n ],\n 'DescribeRegions' => [\n 'name' => 'DescribeRegions',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeRegionsRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeRegionsResult',\n ],\n ],\n 'DescribeReservedInstances' => [\n 'name' => 'DescribeReservedInstances',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeReservedInstancesRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeReservedInstancesResult',\n ],\n ],\n 'DescribeReservedInstancesListings' => [\n 'name' => 'DescribeReservedInstancesListings',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeReservedInstancesListingsRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeReservedInstancesListingsResult',\n ],\n ],\n 'DescribeReservedInstancesModifications' => [\n 'name' => 'DescribeReservedInstancesModifications',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeReservedInstancesModificationsRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeReservedInstancesModificationsResult',\n ],\n ],\n 'DescribeReservedInstancesOfferings' => [\n 'name' => 'DescribeReservedInstancesOfferings',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeReservedInstancesOfferingsRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeReservedInstancesOfferingsResult',\n ],\n ],\n 'DescribeRouteTables' => [\n 'name' => 'DescribeRouteTables',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeRouteTablesRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeRouteTablesResult',\n ],\n ],\n 'DescribeSecurityGroups' => [\n 'name' => 'DescribeSecurityGroups',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeSecurityGroupsRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeSecurityGroupsResult',\n ],\n ],\n 'DescribeSnapshotAttribute' => [\n 'name' => 'DescribeSnapshotAttribute',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeSnapshotAttributeRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeSnapshotAttributeResult',\n ],\n ],\n 'DescribeSnapshots' => [\n 'name' => 'DescribeSnapshots',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeSnapshotsRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeSnapshotsResult',\n ],\n ],\n 'DescribeSpotDatafeedSubscription' => [\n 'name' => 'DescribeSpotDatafeedSubscription',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeSpotDatafeedSubscriptionRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeSpotDatafeedSubscriptionResult',\n ],\n ],\n 'DescribeSpotInstanceRequests' => [\n 'name' => 'DescribeSpotInstanceRequests',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeSpotInstanceRequestsRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeSpotInstanceRequestsResult',\n ],\n ],\n 'DescribeSpotPriceHistory' => [\n 'name' => 'DescribeSpotPriceHistory',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeSpotPriceHistoryRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeSpotPriceHistoryResult',\n ],\n ],\n 'DescribeSubnets' => [\n 'name' => 'DescribeSubnets',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeSubnetsRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeSubnetsResult',\n ],\n ],\n 'DescribeTags' => [\n 'name' => 'DescribeTags',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeTagsRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeTagsResult',\n ],\n ],\n 'DescribeVolumeAttribute' => [\n 'name' => 'DescribeVolumeAttribute',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeVolumeAttributeRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeVolumeAttributeResult',\n ],\n ],\n 'DescribeVolumeStatus' => [\n 'name' => 'DescribeVolumeStatus',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeVolumeStatusRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeVolumeStatusResult',\n ],\n ],\n 'DescribeVolumes' => [\n 'name' => 'DescribeVolumes',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeVolumesRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeVolumesResult',\n ],\n ],\n 'DescribeVpcAttribute' => [\n 'name' => 'DescribeVpcAttribute',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeVpcAttributeRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeVpcAttributeResult',\n ],\n ],\n 'DescribeVpcClassicLink' => [\n 'name' => 'DescribeVpcClassicLink',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeVpcClassicLinkRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeVpcClassicLinkResult',\n ],\n ],\n 'DescribeVpcPeeringConnections' => [\n 'name' => 'DescribeVpcPeeringConnections',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeVpcPeeringConnectionsRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeVpcPeeringConnectionsResult',\n ],\n ],\n 'DescribeVpcs' => [\n 'name' => 'DescribeVpcs',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeVpcsRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeVpcsResult',\n ],\n ],\n 'DescribeVpnConnections' => [\n 'name' => 'DescribeVpnConnections',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeVpnConnectionsRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeVpnConnectionsResult',\n ],\n ],\n 'DescribeVpnGateways' => [\n 'name' => 'DescribeVpnGateways',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DescribeVpnGatewaysRequest',\n ],\n 'output' => [\n 'shape' => 'DescribeVpnGatewaysResult',\n ],\n ],\n 'DetachClassicLinkVpc' => [\n 'name' => 'DetachClassicLinkVpc',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DetachClassicLinkVpcRequest',\n ],\n 'output' => [\n 'shape' => 'DetachClassicLinkVpcResult',\n ],\n ],\n 'DetachInternetGateway' => [\n 'name' => 'DetachInternetGateway',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DetachInternetGatewayRequest',\n ],\n ],\n 'DetachNetworkInterface' => [\n 'name' => 'DetachNetworkInterface',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DetachNetworkInterfaceRequest',\n ],\n ],\n 'DetachVolume' => [\n 'name' => 'DetachVolume',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DetachVolumeRequest',\n ],\n 'output' => [\n 'shape' => 'VolumeAttachment',\n 'locationName' => 'attachment',\n ],\n ],\n 'DetachVpnGateway' => [\n 'name' => 'DetachVpnGateway',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DetachVpnGatewayRequest',\n ],\n ],\n 'DisableVgwRoutePropagation' => [\n 'name' => 'DisableVgwRoutePropagation',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DisableVgwRoutePropagationRequest',\n ],\n ],\n 'DisableVpcClassicLink' => [\n 'name' => 'DisableVpcClassicLink',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DisableVpcClassicLinkRequest',\n ],\n 'output' => [\n 'shape' => 'DisableVpcClassicLinkResult',\n ],\n ],\n 'DisassociateAddress' => [\n 'name' => 'DisassociateAddress',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DisassociateAddressRequest',\n ],\n ],\n 'DisassociateRouteTable' => [\n 'name' => 'DisassociateRouteTable',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DisassociateRouteTableRequest',\n ],\n ],\n 'EnableVgwRoutePropagation' => [\n 'name' => 'EnableVgwRoutePropagation',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'EnableVgwRoutePropagationRequest',\n ],\n ],\n 'EnableVolumeIO' => [\n 'name' => 'EnableVolumeIO',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'EnableVolumeIORequest',\n ],\n ],\n 'EnableVpcClassicLink' => [\n 'name' => 'EnableVpcClassicLink',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'EnableVpcClassicLinkRequest',\n ],\n 'output' => [\n 'shape' => 'EnableVpcClassicLinkResult',\n ],\n ],\n 'GetConsoleOutput' => [\n 'name' => 'GetConsoleOutput',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'GetConsoleOutputRequest',\n ],\n 'output' => [\n 'shape' => 'GetConsoleOutputResult',\n ],\n ],\n 'GetPasswordData' => [\n 'name' => 'GetPasswordData',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'GetPasswordDataRequest',\n ],\n 'output' => [\n 'shape' => 'GetPasswordDataResult',\n ],\n ],\n 'ImportInstance' => [\n 'name' => 'ImportInstance',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ImportInstanceRequest',\n ],\n 'output' => [\n 'shape' => 'ImportInstanceResult',\n ],\n ],\n 'ImportKeyPair' => [\n 'name' => 'ImportKeyPair',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ImportKeyPairRequest',\n ],\n 'output' => [\n 'shape' => 'ImportKeyPairResult',\n ],\n ],\n 'ImportVolume' => [\n 'name' => 'ImportVolume',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ImportVolumeRequest',\n ],\n 'output' => [\n 'shape' => 'ImportVolumeResult',\n ],\n ],\n 'ModifyImageAttribute' => [\n 'name' => 'ModifyImageAttribute',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ModifyImageAttributeRequest',\n ],\n ],\n 'ModifyInstanceAttribute' => [\n 'name' => 'ModifyInstanceAttribute',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ModifyInstanceAttributeRequest',\n ],\n ],\n 'ModifyNetworkInterfaceAttribute' => [\n 'name' => 'ModifyNetworkInterfaceAttribute',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ModifyNetworkInterfaceAttributeRequest',\n ],\n ],\n 'ModifyReservedInstances' => [\n 'name' => 'ModifyReservedInstances',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ModifyReservedInstancesRequest',\n ],\n 'output' => [\n 'shape' => 'ModifyReservedInstancesResult',\n ],\n ],\n 'ModifySnapshotAttribute' => [\n 'name' => 'ModifySnapshotAttribute',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ModifySnapshotAttributeRequest',\n ],\n ],\n 'ModifySubnetAttribute' => [\n 'name' => 'ModifySubnetAttribute',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ModifySubnetAttributeRequest',\n ],\n ],\n 'ModifyVolumeAttribute' => [\n 'name' => 'ModifyVolumeAttribute',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ModifyVolumeAttributeRequest',\n ],\n ],\n 'ModifyVpcAttribute' => [\n 'name' => 'ModifyVpcAttribute',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ModifyVpcAttributeRequest',\n ],\n ],\n 'MonitorInstances' => [\n 'name' => 'MonitorInstances',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'MonitorInstancesRequest',\n ],\n 'output' => [\n 'shape' => 'MonitorInstancesResult',\n ],\n ],\n 'PurchaseReservedInstancesOffering' => [\n 'name' => 'PurchaseReservedInstancesOffering',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'PurchaseReservedInstancesOfferingRequest',\n ],\n 'output' => [\n 'shape' => 'PurchaseReservedInstancesOfferingResult',\n ],\n ],\n 'RebootInstances' => [\n 'name' => 'RebootInstances',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'RebootInstancesRequest',\n ],\n ],\n 'RegisterImage' => [\n 'name' => 'RegisterImage',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'RegisterImageRequest',\n ],\n 'output' => [\n 'shape' => 'RegisterImageResult',\n ],\n ],\n 'RejectVpcPeeringConnection' => [\n 'name' => 'RejectVpcPeeringConnection',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'RejectVpcPeeringConnectionRequest',\n ],\n 'output' => [\n 'shape' => 'RejectVpcPeeringConnectionResult',\n ],\n ],\n 'ReleaseAddress' => [\n 'name' => 'ReleaseAddress',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ReleaseAddressRequest',\n ],\n ],\n 'ReplaceNetworkAclAssociation' => [\n 'name' => 'ReplaceNetworkAclAssociation',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ReplaceNetworkAclAssociationRequest',\n ],\n 'output' => [\n 'shape' => 'ReplaceNetworkAclAssociationResult',\n ],\n ],\n 'ReplaceNetworkAclEntry' => [\n 'name' => 'ReplaceNetworkAclEntry',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ReplaceNetworkAclEntryRequest',\n ],\n ],\n 'ReplaceRoute' => [\n 'name' => 'ReplaceRoute',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ReplaceRouteRequest',\n ],\n ],\n 'ReplaceRouteTableAssociation' => [\n 'name' => 'ReplaceRouteTableAssociation',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ReplaceRouteTableAssociationRequest',\n ],\n 'output' => [\n 'shape' => 'ReplaceRouteTableAssociationResult',\n ],\n ],\n 'ReportInstanceStatus' => [\n 'name' => 'ReportInstanceStatus',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ReportInstanceStatusRequest',\n ],\n ],\n 'RequestSpotInstances' => [\n 'name' => 'RequestSpotInstances',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'RequestSpotInstancesRequest',\n ],\n 'output' => [\n 'shape' => 'RequestSpotInstancesResult',\n ],\n ],\n 'ResetImageAttribute' => [\n 'name' => 'ResetImageAttribute',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ResetImageAttributeRequest',\n ],\n ],\n 'ResetInstanceAttribute' => [\n 'name' => 'ResetInstanceAttribute',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ResetInstanceAttributeRequest',\n ],\n ],\n 'ResetNetworkInterfaceAttribute' => [\n 'name' => 'ResetNetworkInterfaceAttribute',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ResetNetworkInterfaceAttributeRequest',\n ],\n ],\n 'ResetSnapshotAttribute' => [\n 'name' => 'ResetSnapshotAttribute',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ResetSnapshotAttributeRequest',\n ],\n ],\n 'RevokeSecurityGroupEgress' => [\n 'name' => 'RevokeSecurityGroupEgress',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'RevokeSecurityGroupEgressRequest',\n ],\n ],\n 'RevokeSecurityGroupIngress' => [\n 'name' => 'RevokeSecurityGroupIngress',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'RevokeSecurityGroupIngressRequest',\n ],\n ],\n 'RunInstances' => [\n 'name' => 'RunInstances',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'RunInstancesRequest',\n ],\n 'output' => [\n 'shape' => 'Reservation',\n 'locationName' => 'reservation',\n ],\n ],\n 'StartInstances' => [\n 'name' => 'StartInstances',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'StartInstancesRequest',\n ],\n 'output' => [\n 'shape' => 'StartInstancesResult',\n ],\n ],\n 'StopInstances' => [\n 'name' => 'StopInstances',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'StopInstancesRequest',\n ],\n 'output' => [\n 'shape' => 'StopInstancesResult',\n ],\n ],\n 'TerminateInstances' => [\n 'name' => 'TerminateInstances',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'TerminateInstancesRequest',\n ],\n 'output' => [\n 'shape' => 'TerminateInstancesResult',\n ],\n ],\n 'UnassignPrivateIpAddresses' => [\n 'name' => 'UnassignPrivateIpAddresses',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'UnassignPrivateIpAddressesRequest',\n ],\n ],\n 'UnmonitorInstances' => [\n 'name' => 'UnmonitorInstances',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'UnmonitorInstancesRequest',\n ],\n 'output' => [\n 'shape' => 'UnmonitorInstancesResult',\n ],\n ],\n ],\n 'shapes' => [\n 'AcceptVpcPeeringConnectionRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VpcPeeringConnectionId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcPeeringConnectionId',\n ],\n ],\n ],\n 'AcceptVpcPeeringConnectionResult' => [\n 'type' => 'structure',\n 'members' => [\n 'VpcPeeringConnection' => [\n 'shape' => 'VpcPeeringConnection',\n 'locationName' => 'vpcPeeringConnection',\n ],\n ],\n ],\n 'AccountAttribute' => [\n 'type' => 'structure',\n 'members' => [\n 'AttributeName' => [\n 'shape' => 'String',\n 'locationName' => 'attributeName',\n ],\n 'AttributeValues' => [\n 'shape' => 'AccountAttributeValueList',\n 'locationName' => 'attributeValueSet',\n ],\n ],\n ],\n 'AccountAttributeList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'AccountAttribute',\n 'locationName' => 'item',\n ],\n ],\n 'AccountAttributeName' => [\n 'type' => 'string',\n 'enum' => [\n 'supported-platforms',\n 'default-vpc',\n ],\n ],\n 'AccountAttributeNameStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'AccountAttributeName',\n 'locationName' => 'attributeName',\n ],\n ],\n 'AccountAttributeValue' => [\n 'type' => 'structure',\n 'members' => [\n 'AttributeValue' => [\n 'shape' => 'String',\n 'locationName' => 'attributeValue',\n ],\n ],\n ],\n 'AccountAttributeValueList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'AccountAttributeValue',\n 'locationName' => 'item',\n ],\n ],\n 'Address' => [\n 'type' => 'structure',\n 'members' => [\n 'InstanceId' => [\n 'shape' => 'String',\n 'locationName' => 'instanceId',\n ],\n 'PublicIp' => [\n 'shape' => 'String',\n 'locationName' => 'publicIp',\n ],\n 'AllocationId' => [\n 'shape' => 'String',\n 'locationName' => 'allocationId',\n ],\n 'AssociationId' => [\n 'shape' => 'String',\n 'locationName' => 'associationId',\n ],\n 'Domain' => [\n 'shape' => 'DomainType',\n 'locationName' => 'domain',\n ],\n 'NetworkInterfaceId' => [\n 'shape' => 'String',\n 'locationName' => 'networkInterfaceId',\n ],\n 'NetworkInterfaceOwnerId' => [\n 'shape' => 'String',\n 'locationName' => 'networkInterfaceOwnerId',\n ],\n 'PrivateIpAddress' => [\n 'shape' => 'String',\n 'locationName' => 'privateIpAddress',\n ],\n ],\n ],\n 'AddressList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'Address',\n 'locationName' => 'item',\n ],\n ],\n 'AllocateAddressRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'Domain' => [\n 'shape' => 'DomainType',\n ],\n ],\n ],\n 'AllocateAddressResult' => [\n 'type' => 'structure',\n 'members' => [\n 'PublicIp' => [\n 'shape' => 'String',\n 'locationName' => 'publicIp',\n ],\n 'Domain' => [\n 'shape' => 'DomainType',\n 'locationName' => 'domain',\n ],\n 'AllocationId' => [\n 'shape' => 'String',\n 'locationName' => 'allocationId',\n ],\n ],\n ],\n 'AllocationIdList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'AllocationId',\n ],\n ],\n 'ArchitectureValues' => [\n 'type' => 'string',\n 'enum' => [\n 'i386',\n 'x86_64',\n ],\n ],\n 'AssignPrivateIpAddressesRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'NetworkInterfaceId',\n ],\n 'members' => [\n 'NetworkInterfaceId' => [\n 'shape' => 'String',\n 'locationName' => 'networkInterfaceId',\n ],\n 'PrivateIpAddresses' => [\n 'shape' => 'PrivateIpAddressStringList',\n 'locationName' => 'privateIpAddress',\n ],\n 'SecondaryPrivateIpAddressCount' => [\n 'shape' => 'Integer',\n 'locationName' => 'secondaryPrivateIpAddressCount',\n ],\n 'AllowReassignment' => [\n 'shape' => 'Boolean',\n 'locationName' => 'allowReassignment',\n ],\n ],\n ],\n 'AssociateAddressRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'InstanceId' => [\n 'shape' => 'String',\n ],\n 'PublicIp' => [\n 'shape' => 'String',\n ],\n 'AllocationId' => [\n 'shape' => 'String',\n ],\n 'NetworkInterfaceId' => [\n 'shape' => 'String',\n 'locationName' => 'networkInterfaceId',\n ],\n 'PrivateIpAddress' => [\n 'shape' => 'String',\n 'locationName' => 'privateIpAddress',\n ],\n 'AllowReassociation' => [\n 'shape' => 'Boolean',\n 'locationName' => 'allowReassociation',\n ],\n ],\n ],\n 'AssociateAddressResult' => [\n 'type' => 'structure',\n 'members' => [\n 'AssociationId' => [\n 'shape' => 'String',\n 'locationName' => 'associationId',\n ],\n ],\n ],\n 'AssociateDhcpOptionsRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'DhcpOptionsId',\n 'VpcId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'DhcpOptionsId' => [\n 'shape' => 'String',\n ],\n 'VpcId' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'AssociateRouteTableRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'SubnetId',\n 'RouteTableId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'SubnetId' => [\n 'shape' => 'String',\n 'locationName' => 'subnetId',\n ],\n 'RouteTableId' => [\n 'shape' => 'String',\n 'locationName' => 'routeTableId',\n ],\n ],\n ],\n 'AssociateRouteTableResult' => [\n 'type' => 'structure',\n 'members' => [\n 'AssociationId' => [\n 'shape' => 'String',\n 'locationName' => 'associationId',\n ],\n ],\n ],\n 'AttachClassicLinkVpcRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'InstanceId',\n 'VpcId',\n 'Groups',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'InstanceId' => [\n 'shape' => 'String',\n 'locationName' => 'instanceId',\n ],\n 'VpcId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcId',\n ],\n 'Groups' => [\n 'shape' => 'GroupIdStringList',\n 'locationName' => 'SecurityGroupId',\n ],\n ],\n ],\n 'AttachClassicLinkVpcResult' => [\n 'type' => 'structure',\n 'members' => [\n 'Return' => [\n 'shape' => 'Boolean',\n 'locationName' => 'return',\n ],\n ],\n ],\n 'AttachInternetGatewayRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'InternetGatewayId',\n 'VpcId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'InternetGatewayId' => [\n 'shape' => 'String',\n 'locationName' => 'internetGatewayId',\n ],\n 'VpcId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcId',\n ],\n ],\n ],\n 'AttachNetworkInterfaceRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'NetworkInterfaceId',\n 'InstanceId',\n 'DeviceIndex',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'NetworkInterfaceId' => [\n 'shape' => 'String',\n 'locationName' => 'networkInterfaceId',\n ],\n 'InstanceId' => [\n 'shape' => 'String',\n 'locationName' => 'instanceId',\n ],\n 'DeviceIndex' => [\n 'shape' => 'Integer',\n 'locationName' => 'deviceIndex',\n ],\n ],\n ],\n 'AttachNetworkInterfaceResult' => [\n 'type' => 'structure',\n 'members' => [\n 'AttachmentId' => [\n 'shape' => 'String',\n 'locationName' => 'attachmentId',\n ],\n ],\n ],\n 'AttachVolumeRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'VolumeId',\n 'InstanceId',\n 'Device',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VolumeId' => [\n 'shape' => 'String',\n ],\n 'InstanceId' => [\n 'shape' => 'String',\n ],\n 'Device' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'AttachVpnGatewayRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'VpnGatewayId',\n 'VpcId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VpnGatewayId' => [\n 'shape' => 'String',\n ],\n 'VpcId' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'AttachVpnGatewayResult' => [\n 'type' => 'structure',\n 'members' => [\n 'VpcAttachment' => [\n 'shape' => 'VpcAttachment',\n 'locationName' => 'attachment',\n ],\n ],\n ],\n 'AttachmentStatus' => [\n 'type' => 'string',\n 'enum' => [\n 'attaching',\n 'attached',\n 'detaching',\n 'detached',\n ],\n ],\n 'AttributeBooleanValue' => [\n 'type' => 'structure',\n 'members' => [\n 'Value' => [\n 'shape' => 'Boolean',\n 'locationName' => 'value',\n ],\n ],\n ],\n 'AttributeValue' => [\n 'type' => 'structure',\n 'members' => [\n 'Value' => [\n 'shape' => 'String',\n 'locationName' => 'value',\n ],\n ],\n ],\n 'AuthorizeSecurityGroupEgressRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'GroupId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'GroupId' => [\n 'shape' => 'String',\n 'locationName' => 'groupId',\n ],\n 'SourceSecurityGroupName' => [\n 'shape' => 'String',\n 'locationName' => 'sourceSecurityGroupName',\n ],\n 'SourceSecurityGroupOwnerId' => [\n 'shape' => 'String',\n 'locationName' => 'sourceSecurityGroupOwnerId',\n ],\n 'IpProtocol' => [\n 'shape' => 'String',\n 'locationName' => 'ipProtocol',\n ],\n 'FromPort' => [\n 'shape' => 'Integer',\n 'locationName' => 'fromPort',\n ],\n 'ToPort' => [\n 'shape' => 'Integer',\n 'locationName' => 'toPort',\n ],\n 'CidrIp' => [\n 'shape' => 'String',\n 'locationName' => 'cidrIp',\n ],\n 'IpPermissions' => [\n 'shape' => 'IpPermissionList',\n 'locationName' => 'ipPermissions',\n ],\n ],\n ],\n 'AuthorizeSecurityGroupIngressRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'GroupName' => [\n 'shape' => 'String',\n ],\n 'GroupId' => [\n 'shape' => 'String',\n ],\n 'SourceSecurityGroupName' => [\n 'shape' => 'String',\n ],\n 'SourceSecurityGroupOwnerId' => [\n 'shape' => 'String',\n ],\n 'IpProtocol' => [\n 'shape' => 'String',\n ],\n 'FromPort' => [\n 'shape' => 'Integer',\n ],\n 'ToPort' => [\n 'shape' => 'Integer',\n ],\n 'CidrIp' => [\n 'shape' => 'String',\n ],\n 'IpPermissions' => [\n 'shape' => 'IpPermissionList',\n ],\n ],\n ],\n 'AvailabilityZone' => [\n 'type' => 'structure',\n 'members' => [\n 'ZoneName' => [\n 'shape' => 'String',\n 'locationName' => 'zoneName',\n ],\n 'State' => [\n 'shape' => 'AvailabilityZoneState',\n 'locationName' => 'zoneState',\n ],\n 'RegionName' => [\n 'shape' => 'String',\n 'locationName' => 'regionName',\n ],\n 'Messages' => [\n 'shape' => 'AvailabilityZoneMessageList',\n 'locationName' => 'messageSet',\n ],\n ],\n ],\n 'AvailabilityZoneList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'AvailabilityZone',\n 'locationName' => 'item',\n ],\n ],\n 'AvailabilityZoneMessage' => [\n 'type' => 'structure',\n 'members' => [\n 'Message' => [\n 'shape' => 'String',\n 'locationName' => 'message',\n ],\n ],\n ],\n 'AvailabilityZoneMessageList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'AvailabilityZoneMessage',\n 'locationName' => 'item',\n ],\n ],\n 'AvailabilityZoneState' => [\n 'type' => 'string',\n 'enum' => [\n 'available',\n ],\n ],\n 'BlockDeviceMapping' => [\n 'type' => 'structure',\n 'members' => [\n 'VirtualName' => [\n 'shape' => 'String',\n 'locationName' => 'virtualName',\n ],\n 'DeviceName' => [\n 'shape' => 'String',\n 'locationName' => 'deviceName',\n ],\n 'Ebs' => [\n 'shape' => 'EbsBlockDevice',\n 'locationName' => 'ebs',\n ],\n 'NoDevice' => [\n 'shape' => 'String',\n 'locationName' => 'noDevice',\n ],\n ],\n ],\n 'BlockDeviceMappingList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'BlockDeviceMapping',\n 'locationName' => 'item',\n ],\n ],\n 'BlockDeviceMappingRequestList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'BlockDeviceMapping',\n 'locationName' => 'BlockDeviceMapping',\n ],\n ],\n 'Boolean' => [\n 'type' => 'boolean',\n ],\n 'BundleIdStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'BundleId',\n ],\n ],\n 'BundleInstanceRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'InstanceId',\n 'Storage',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'InstanceId' => [\n 'shape' => 'String',\n ],\n 'Storage' => [\n 'shape' => 'Storage',\n ],\n ],\n ],\n 'BundleInstanceResult' => [\n 'type' => 'structure',\n 'members' => [\n 'BundleTask' => [\n 'shape' => 'BundleTask',\n 'locationName' => 'bundleInstanceTask',\n ],\n ],\n ],\n 'BundleTask' => [\n 'type' => 'structure',\n 'members' => [\n 'InstanceId' => [\n 'shape' => 'String',\n 'locationName' => 'instanceId',\n ],\n 'BundleId' => [\n 'shape' => 'String',\n 'locationName' => 'bundleId',\n ],\n 'State' => [\n 'shape' => 'BundleTaskState',\n 'locationName' => 'state',\n ],\n 'StartTime' => [\n 'shape' => 'DateTime',\n 'locationName' => 'startTime',\n ],\n 'UpdateTime' => [\n 'shape' => 'DateTime',\n 'locationName' => 'updateTime',\n ],\n 'Storage' => [\n 'shape' => 'Storage',\n 'locationName' => 'storage',\n ],\n 'Progress' => [\n 'shape' => 'String',\n 'locationName' => 'progress',\n ],\n 'BundleTaskError' => [\n 'shape' => 'BundleTaskError',\n 'locationName' => 'error',\n ],\n ],\n ],\n 'BundleTaskError' => [\n 'type' => 'structure',\n 'members' => [\n 'Code' => [\n 'shape' => 'String',\n 'locationName' => 'code',\n ],\n 'Message' => [\n 'shape' => 'String',\n 'locationName' => 'message',\n ],\n ],\n ],\n 'BundleTaskList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'BundleTask',\n 'locationName' => 'item',\n ],\n ],\n 'BundleTaskState' => [\n 'type' => 'string',\n 'enum' => [\n 'pending',\n 'waiting-for-shutdown',\n 'bundling',\n 'storing',\n 'cancelling',\n 'complete',\n 'failed',\n ],\n ],\n 'CancelBundleTaskRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'BundleId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'BundleId' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'CancelBundleTaskResult' => [\n 'type' => 'structure',\n 'members' => [\n 'BundleTask' => [\n 'shape' => 'BundleTask',\n 'locationName' => 'bundleInstanceTask',\n ],\n ],\n ],\n 'CancelConversionRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'ConversionTaskId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'ConversionTaskId' => [\n 'shape' => 'String',\n 'locationName' => 'conversionTaskId',\n ],\n 'ReasonMessage' => [\n 'shape' => 'String',\n 'locationName' => 'reasonMessage',\n ],\n ],\n ],\n 'CancelExportTaskRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'ExportTaskId',\n ],\n 'members' => [\n 'ExportTaskId' => [\n 'shape' => 'String',\n 'locationName' => 'exportTaskId',\n ],\n ],\n ],\n 'CancelReservedInstancesListingRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'ReservedInstancesListingId',\n ],\n 'members' => [\n 'ReservedInstancesListingId' => [\n 'shape' => 'String',\n 'locationName' => 'reservedInstancesListingId',\n ],\n ],\n ],\n 'CancelReservedInstancesListingResult' => [\n 'type' => 'structure',\n 'members' => [\n 'ReservedInstancesListings' => [\n 'shape' => 'ReservedInstancesListingList',\n 'locationName' => 'reservedInstancesListingsSet',\n ],\n ],\n ],\n 'CancelSpotInstanceRequestState' => [\n 'type' => 'string',\n 'enum' => [\n 'active',\n 'open',\n 'closed',\n 'cancelled',\n 'completed',\n ],\n ],\n 'CancelSpotInstanceRequestsRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'SpotInstanceRequestIds',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'SpotInstanceRequestIds' => [\n 'shape' => 'SpotInstanceRequestIdList',\n 'locationName' => 'SpotInstanceRequestId',\n ],\n ],\n ],\n 'CancelSpotInstanceRequestsResult' => [\n 'type' => 'structure',\n 'members' => [\n 'CancelledSpotInstanceRequests' => [\n 'shape' => 'CancelledSpotInstanceRequestList',\n 'locationName' => 'spotInstanceRequestSet',\n ],\n ],\n ],\n 'CancelledSpotInstanceRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'SpotInstanceRequestId' => [\n 'shape' => 'String',\n 'locationName' => 'spotInstanceRequestId',\n ],\n 'State' => [\n 'shape' => 'CancelSpotInstanceRequestState',\n 'locationName' => 'state',\n ],\n ],\n ],\n 'CancelledSpotInstanceRequestList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'CancelledSpotInstanceRequest',\n 'locationName' => 'item',\n ],\n ],\n 'ClassicLinkInstance' => [\n 'type' => 'structure',\n 'members' => [\n 'InstanceId' => [\n 'shape' => 'String',\n 'locationName' => 'instanceId',\n ],\n 'VpcId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcId',\n ],\n 'Groups' => [\n 'shape' => 'GroupIdentifierList',\n 'locationName' => 'groupSet',\n ],\n 'Tags' => [\n 'shape' => 'TagList',\n 'locationName' => 'tagSet',\n ],\n ],\n ],\n 'ClassicLinkInstanceList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'ClassicLinkInstance',\n 'locationName' => 'item',\n ],\n ],\n 'ConfirmProductInstanceRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'ProductCode',\n 'InstanceId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'ProductCode' => [\n 'shape' => 'String',\n ],\n 'InstanceId' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'ConfirmProductInstanceResult' => [\n 'type' => 'structure',\n 'members' => [\n 'OwnerId' => [\n 'shape' => 'String',\n 'locationName' => 'ownerId',\n ],\n ],\n ],\n 'ContainerFormat' => [\n 'type' => 'string',\n 'enum' => [\n 'ova',\n ],\n ],\n 'ConversionIdStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'item',\n ],\n ],\n 'ConversionTask' => [\n 'type' => 'structure',\n 'required' => [\n 'ConversionTaskId',\n 'State',\n ],\n 'members' => [\n 'ConversionTaskId' => [\n 'shape' => 'String',\n 'locationName' => 'conversionTaskId',\n ],\n 'ExpirationTime' => [\n 'shape' => 'String',\n 'locationName' => 'expirationTime',\n ],\n 'ImportInstance' => [\n 'shape' => 'ImportInstanceTaskDetails',\n 'locationName' => 'importInstance',\n ],\n 'ImportVolume' => [\n 'shape' => 'ImportVolumeTaskDetails',\n 'locationName' => 'importVolume',\n ],\n 'State' => [\n 'shape' => 'ConversionTaskState',\n 'locationName' => 'state',\n ],\n 'StatusMessage' => [\n 'shape' => 'String',\n 'locationName' => 'statusMessage',\n ],\n 'Tags' => [\n 'shape' => 'TagList',\n 'locationName' => 'tagSet',\n ],\n ],\n ],\n 'ConversionTaskState' => [\n 'type' => 'string',\n 'enum' => [\n 'active',\n 'cancelling',\n 'cancelled',\n 'completed',\n ],\n ],\n 'CopyImageRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'SourceRegion',\n 'SourceImageId',\n 'Name',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'SourceRegion' => [\n 'shape' => 'String',\n ],\n 'SourceImageId' => [\n 'shape' => 'String',\n ],\n 'Name' => [\n 'shape' => 'String',\n ],\n 'Description' => [\n 'shape' => 'String',\n ],\n 'ClientToken' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'CopyImageResult' => [\n 'type' => 'structure',\n 'members' => [\n 'ImageId' => [\n 'shape' => 'String',\n 'locationName' => 'imageId',\n ],\n ],\n ],\n 'CopySnapshotRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'SourceRegion',\n 'SourceSnapshotId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'SourceRegion' => [\n 'shape' => 'String',\n ],\n 'SourceSnapshotId' => [\n 'shape' => 'String',\n ],\n 'Description' => [\n 'shape' => 'String',\n ],\n 'DestinationRegion' => [\n 'shape' => 'String',\n 'locationName' => 'destinationRegion',\n ],\n 'PresignedUrl' => [\n 'shape' => 'String',\n 'locationName' => 'presignedUrl',\n ],\n ],\n ],\n 'CopySnapshotResult' => [\n 'type' => 'structure',\n 'members' => [\n 'SnapshotId' => [\n 'shape' => 'String',\n 'locationName' => 'snapshotId',\n ],\n ],\n ],\n 'CreateCustomerGatewayRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'Type',\n 'PublicIp',\n 'BgpAsn',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'Type' => [\n 'shape' => 'GatewayType',\n ],\n 'PublicIp' => [\n 'shape' => 'String',\n 'locationName' => 'IpAddress',\n ],\n 'BgpAsn' => [\n 'shape' => 'Integer',\n ],\n ],\n ],\n 'CreateCustomerGatewayResult' => [\n 'type' => 'structure',\n 'members' => [\n 'CustomerGateway' => [\n 'shape' => 'CustomerGateway',\n 'locationName' => 'customerGateway',\n ],\n ],\n ],\n 'CreateDhcpOptionsRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'DhcpConfigurations',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'DhcpConfigurations' => [\n 'shape' => 'NewDhcpConfigurationList',\n 'locationName' => 'dhcpConfiguration',\n ],\n ],\n ],\n 'CreateDhcpOptionsResult' => [\n 'type' => 'structure',\n 'members' => [\n 'DhcpOptions' => [\n 'shape' => 'DhcpOptions',\n 'locationName' => 'dhcpOptions',\n ],\n ],\n ],\n 'CreateImageRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'InstanceId',\n 'Name',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'InstanceId' => [\n 'shape' => 'String',\n 'locationName' => 'instanceId',\n ],\n 'Name' => [\n 'shape' => 'String',\n 'locationName' => 'name',\n ],\n 'Description' => [\n 'shape' => 'String',\n 'locationName' => 'description',\n ],\n 'NoReboot' => [\n 'shape' => 'Boolean',\n 'locationName' => 'noReboot',\n ],\n 'BlockDeviceMappings' => [\n 'shape' => 'BlockDeviceMappingRequestList',\n 'locationName' => 'blockDeviceMapping',\n ],\n ],\n ],\n 'CreateImageResult' => [\n 'type' => 'structure',\n 'members' => [\n 'ImageId' => [\n 'shape' => 'String',\n 'locationName' => 'imageId',\n ],\n ],\n ],\n 'CreateInstanceExportTaskRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'InstanceId',\n ],\n 'members' => [\n 'Description' => [\n 'shape' => 'String',\n 'locationName' => 'description',\n ],\n 'InstanceId' => [\n 'shape' => 'String',\n 'locationName' => 'instanceId',\n ],\n 'TargetEnvironment' => [\n 'shape' => 'ExportEnvironment',\n 'locationName' => 'targetEnvironment',\n ],\n 'ExportToS3Task' => [\n 'shape' => 'ExportToS3TaskSpecification',\n 'locationName' => 'exportToS3',\n ],\n ],\n ],\n 'CreateInstanceExportTaskResult' => [\n 'type' => 'structure',\n 'members' => [\n 'ExportTask' => [\n 'shape' => 'ExportTask',\n 'locationName' => 'exportTask',\n ],\n ],\n ],\n 'CreateInternetGatewayRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n ],\n ],\n 'CreateInternetGatewayResult' => [\n 'type' => 'structure',\n 'members' => [\n 'InternetGateway' => [\n 'shape' => 'InternetGateway',\n 'locationName' => 'internetGateway',\n ],\n ],\n ],\n 'CreateKeyPairRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'KeyName',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'KeyName' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'CreateNetworkAclEntryRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'NetworkAclId',\n 'RuleNumber',\n 'Protocol',\n 'RuleAction',\n 'Egress',\n 'CidrBlock',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'NetworkAclId' => [\n 'shape' => 'String',\n 'locationName' => 'networkAclId',\n ],\n 'RuleNumber' => [\n 'shape' => 'Integer',\n 'locationName' => 'ruleNumber',\n ],\n 'Protocol' => [\n 'shape' => 'String',\n 'locationName' => 'protocol',\n ],\n 'RuleAction' => [\n 'shape' => 'RuleAction',\n 'locationName' => 'ruleAction',\n ],\n 'Egress' => [\n 'shape' => 'Boolean',\n 'locationName' => 'egress',\n ],\n 'CidrBlock' => [\n 'shape' => 'String',\n 'locationName' => 'cidrBlock',\n ],\n 'IcmpTypeCode' => [\n 'shape' => 'IcmpTypeCode',\n 'locationName' => 'Icmp',\n ],\n 'PortRange' => [\n 'shape' => 'PortRange',\n 'locationName' => 'portRange',\n ],\n ],\n ],\n 'CreateNetworkAclRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'VpcId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VpcId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcId',\n ],\n ],\n ],\n 'CreateNetworkAclResult' => [\n 'type' => 'structure',\n 'members' => [\n 'NetworkAcl' => [\n 'shape' => 'NetworkAcl',\n 'locationName' => 'networkAcl',\n ],\n ],\n ],\n 'CreateNetworkInterfaceRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'SubnetId',\n ],\n 'members' => [\n 'SubnetId' => [\n 'shape' => 'String',\n 'locationName' => 'subnetId',\n ],\n 'Description' => [\n 'shape' => 'String',\n 'locationName' => 'description',\n ],\n 'PrivateIpAddress' => [\n 'shape' => 'String',\n 'locationName' => 'privateIpAddress',\n ],\n 'Groups' => [\n 'shape' => 'SecurityGroupIdStringList',\n 'locationName' => 'SecurityGroupId',\n ],\n 'PrivateIpAddresses' => [\n 'shape' => 'PrivateIpAddressSpecificationList',\n 'locationName' => 'privateIpAddresses',\n ],\n 'SecondaryPrivateIpAddressCount' => [\n 'shape' => 'Integer',\n 'locationName' => 'secondaryPrivateIpAddressCount',\n ],\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n ],\n ],\n 'CreateNetworkInterfaceResult' => [\n 'type' => 'structure',\n 'members' => [\n 'NetworkInterface' => [\n 'shape' => 'NetworkInterface',\n 'locationName' => 'networkInterface',\n ],\n ],\n ],\n 'CreatePlacementGroupRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'GroupName',\n 'Strategy',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'GroupName' => [\n 'shape' => 'String',\n 'locationName' => 'groupName',\n ],\n 'Strategy' => [\n 'shape' => 'PlacementStrategy',\n 'locationName' => 'strategy',\n ],\n ],\n ],\n 'CreateReservedInstancesListingRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'ReservedInstancesId',\n 'InstanceCount',\n 'PriceSchedules',\n 'ClientToken',\n ],\n 'members' => [\n 'ReservedInstancesId' => [\n 'shape' => 'String',\n 'locationName' => 'reservedInstancesId',\n ],\n 'InstanceCount' => [\n 'shape' => 'Integer',\n 'locationName' => 'instanceCount',\n ],\n 'PriceSchedules' => [\n 'shape' => 'PriceScheduleSpecificationList',\n 'locationName' => 'priceSchedules',\n ],\n 'ClientToken' => [\n 'shape' => 'String',\n 'locationName' => 'clientToken',\n ],\n ],\n ],\n 'CreateReservedInstancesListingResult' => [\n 'type' => 'structure',\n 'members' => [\n 'ReservedInstancesListings' => [\n 'shape' => 'ReservedInstancesListingList',\n 'locationName' => 'reservedInstancesListingsSet',\n ],\n ],\n ],\n 'CreateRouteRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'RouteTableId',\n 'DestinationCidrBlock',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'RouteTableId' => [\n 'shape' => 'String',\n 'locationName' => 'routeTableId',\n ],\n 'DestinationCidrBlock' => [\n 'shape' => 'String',\n 'locationName' => 'destinationCidrBlock',\n ],\n 'GatewayId' => [\n 'shape' => 'String',\n 'locationName' => 'gatewayId',\n ],\n 'InstanceId' => [\n 'shape' => 'String',\n 'locationName' => 'instanceId',\n ],\n 'NetworkInterfaceId' => [\n 'shape' => 'String',\n 'locationName' => 'networkInterfaceId',\n ],\n 'VpcPeeringConnectionId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcPeeringConnectionId',\n ],\n ],\n ],\n 'CreateRouteTableRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'VpcId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VpcId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcId',\n ],\n ],\n ],\n 'CreateRouteTableResult' => [\n 'type' => 'structure',\n 'members' => [\n 'RouteTable' => [\n 'shape' => 'RouteTable',\n 'locationName' => 'routeTable',\n ],\n ],\n ],\n 'CreateSecurityGroupRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'GroupName',\n 'Description',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'GroupName' => [\n 'shape' => 'String',\n ],\n 'Description' => [\n 'shape' => 'String',\n 'locationName' => 'GroupDescription',\n ],\n 'VpcId' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'CreateSecurityGroupResult' => [\n 'type' => 'structure',\n 'members' => [\n 'GroupId' => [\n 'shape' => 'String',\n 'locationName' => 'groupId',\n ],\n ],\n ],\n 'CreateSnapshotRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'VolumeId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VolumeId' => [\n 'shape' => 'String',\n ],\n 'Description' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'CreateSpotDatafeedSubscriptionRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'Bucket',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'Bucket' => [\n 'shape' => 'String',\n 'locationName' => 'bucket',\n ],\n 'Prefix' => [\n 'shape' => 'String',\n 'locationName' => 'prefix',\n ],\n ],\n ],\n 'CreateSpotDatafeedSubscriptionResult' => [\n 'type' => 'structure',\n 'members' => [\n 'SpotDatafeedSubscription' => [\n 'shape' => 'SpotDatafeedSubscription',\n 'locationName' => 'spotDatafeedSubscription',\n ],\n ],\n ],\n 'CreateSubnetRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'VpcId',\n 'CidrBlock',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VpcId' => [\n 'shape' => 'String',\n ],\n 'CidrBlock' => [\n 'shape' => 'String',\n ],\n 'AvailabilityZone' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'CreateSubnetResult' => [\n 'type' => 'structure',\n 'members' => [\n 'Subnet' => [\n 'shape' => 'Subnet',\n 'locationName' => 'subnet',\n ],\n ],\n ],\n 'CreateTagsRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'Resources',\n 'Tags',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'Resources' => [\n 'shape' => 'ResourceIdList',\n 'locationName' => 'ResourceId',\n ],\n 'Tags' => [\n 'shape' => 'TagList',\n 'locationName' => 'Tag',\n ],\n ],\n ],\n 'CreateVolumePermission' => [\n 'type' => 'structure',\n 'members' => [\n 'UserId' => [\n 'shape' => 'String',\n 'locationName' => 'userId',\n ],\n 'Group' => [\n 'shape' => 'PermissionGroup',\n 'locationName' => 'group',\n ],\n ],\n ],\n 'CreateVolumePermissionList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'CreateVolumePermission',\n 'locationName' => 'item',\n ],\n ],\n 'CreateVolumePermissionModifications' => [\n 'type' => 'structure',\n 'members' => [\n 'Add' => [\n 'shape' => 'CreateVolumePermissionList',\n ],\n 'Remove' => [\n 'shape' => 'CreateVolumePermissionList',\n ],\n ],\n ],\n 'CreateVolumeRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'AvailabilityZone',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'Size' => [\n 'shape' => 'Integer',\n ],\n 'SnapshotId' => [\n 'shape' => 'String',\n ],\n 'AvailabilityZone' => [\n 'shape' => 'String',\n ],\n 'VolumeType' => [\n 'shape' => 'VolumeType',\n ],\n 'Iops' => [\n 'shape' => 'Integer',\n ],\n 'Encrypted' => [\n 'shape' => 'Boolean',\n 'locationName' => 'encrypted',\n ],\n 'KmsKeyId' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'CreateVpcPeeringConnectionRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VpcId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcId',\n ],\n 'PeerVpcId' => [\n 'shape' => 'String',\n 'locationName' => 'peerVpcId',\n ],\n 'PeerOwnerId' => [\n 'shape' => 'String',\n 'locationName' => 'peerOwnerId',\n ],\n ],\n ],\n 'CreateVpcPeeringConnectionResult' => [\n 'type' => 'structure',\n 'members' => [\n 'VpcPeeringConnection' => [\n 'shape' => 'VpcPeeringConnection',\n 'locationName' => 'vpcPeeringConnection',\n ],\n ],\n ],\n 'CreateVpcRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'CidrBlock',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'CidrBlock' => [\n 'shape' => 'String',\n ],\n 'InstanceTenancy' => [\n 'shape' => 'Tenancy',\n 'locationName' => 'instanceTenancy',\n ],\n ],\n ],\n 'CreateVpcResult' => [\n 'type' => 'structure',\n 'members' => [\n 'Vpc' => [\n 'shape' => 'Vpc',\n 'locationName' => 'vpc',\n ],\n ],\n ],\n 'CreateVpnConnectionRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'Type',\n 'CustomerGatewayId',\n 'VpnGatewayId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'Type' => [\n 'shape' => 'String',\n ],\n 'CustomerGatewayId' => [\n 'shape' => 'String',\n ],\n 'VpnGatewayId' => [\n 'shape' => 'String',\n ],\n 'Options' => [\n 'shape' => 'VpnConnectionOptionsSpecification',\n 'locationName' => 'options',\n ],\n ],\n ],\n 'CreateVpnConnectionResult' => [\n 'type' => 'structure',\n 'members' => [\n 'VpnConnection' => [\n 'shape' => 'VpnConnection',\n 'locationName' => 'vpnConnection',\n ],\n ],\n ],\n 'CreateVpnConnectionRouteRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'VpnConnectionId',\n 'DestinationCidrBlock',\n ],\n 'members' => [\n 'VpnConnectionId' => [\n 'shape' => 'String',\n ],\n 'DestinationCidrBlock' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'CreateVpnGatewayRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'Type',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'Type' => [\n 'shape' => 'GatewayType',\n ],\n 'AvailabilityZone' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'CreateVpnGatewayResult' => [\n 'type' => 'structure',\n 'members' => [\n 'VpnGateway' => [\n 'shape' => 'VpnGateway',\n 'locationName' => 'vpnGateway',\n ],\n ],\n ],\n 'CurrencyCodeValues' => [\n 'type' => 'string',\n 'enum' => [\n 'USD',\n ],\n ],\n 'CustomerGateway' => [\n 'type' => 'structure',\n 'members' => [\n 'CustomerGatewayId' => [\n 'shape' => 'String',\n 'locationName' => 'customerGatewayId',\n ],\n 'State' => [\n 'shape' => 'String',\n 'locationName' => 'state',\n ],\n 'Type' => [\n 'shape' => 'String',\n 'locationName' => 'type',\n ],\n 'IpAddress' => [\n 'shape' => 'String',\n 'locationName' => 'ipAddress',\n ],\n 'BgpAsn' => [\n 'shape' => 'String',\n 'locationName' => 'bgpAsn',\n ],\n 'Tags' => [\n 'shape' => 'TagList',\n 'locationName' => 'tagSet',\n ],\n ],\n ],\n 'CustomerGatewayIdStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'CustomerGatewayId',\n ],\n ],\n 'CustomerGatewayList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'CustomerGateway',\n 'locationName' => 'item',\n ],\n ],\n 'DatafeedSubscriptionState' => [\n 'type' => 'string',\n 'enum' => [\n 'Active',\n 'Inactive',\n ],\n ],\n 'DateTime' => [\n 'type' => 'timestamp',\n ],\n 'DeleteCustomerGatewayRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'CustomerGatewayId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'CustomerGatewayId' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'DeleteDhcpOptionsRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'DhcpOptionsId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'DhcpOptionsId' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'DeleteInternetGatewayRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'InternetGatewayId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'InternetGatewayId' => [\n 'shape' => 'String',\n 'locationName' => 'internetGatewayId',\n ],\n ],\n ],\n 'DeleteKeyPairRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'KeyName',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'KeyName' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'DeleteNetworkAclEntryRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'NetworkAclId',\n 'RuleNumber',\n 'Egress',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'NetworkAclId' => [\n 'shape' => 'String',\n 'locationName' => 'networkAclId',\n ],\n 'RuleNumber' => [\n 'shape' => 'Integer',\n 'locationName' => 'ruleNumber',\n ],\n 'Egress' => [\n 'shape' => 'Boolean',\n 'locationName' => 'egress',\n ],\n ],\n ],\n 'DeleteNetworkAclRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'NetworkAclId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'NetworkAclId' => [\n 'shape' => 'String',\n 'locationName' => 'networkAclId',\n ],\n ],\n ],\n 'DeleteNetworkInterfaceRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'NetworkInterfaceId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'NetworkInterfaceId' => [\n 'shape' => 'String',\n 'locationName' => 'networkInterfaceId',\n ],\n ],\n ],\n 'DeletePlacementGroupRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'GroupName',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'GroupName' => [\n 'shape' => 'String',\n 'locationName' => 'groupName',\n ],\n ],\n ],\n 'DeleteRouteRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'RouteTableId',\n 'DestinationCidrBlock',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'RouteTableId' => [\n 'shape' => 'String',\n 'locationName' => 'routeTableId',\n ],\n 'DestinationCidrBlock' => [\n 'shape' => 'String',\n 'locationName' => 'destinationCidrBlock',\n ],\n ],\n ],\n 'DeleteRouteTableRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'RouteTableId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'RouteTableId' => [\n 'shape' => 'String',\n 'locationName' => 'routeTableId',\n ],\n ],\n ],\n 'DeleteSecurityGroupRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'GroupName' => [\n 'shape' => 'String',\n ],\n 'GroupId' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'DeleteSnapshotRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'SnapshotId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'SnapshotId' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'DeleteSpotDatafeedSubscriptionRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n ],\n ],\n 'DeleteSubnetRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'SubnetId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'SubnetId' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'DeleteTagsRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'Resources',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'Resources' => [\n 'shape' => 'ResourceIdList',\n 'locationName' => 'resourceId',\n ],\n 'Tags' => [\n 'shape' => 'TagList',\n 'locationName' => 'tag',\n ],\n ],\n ],\n 'DeleteVolumeRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'VolumeId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VolumeId' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'DeleteVpcPeeringConnectionRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'VpcPeeringConnectionId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VpcPeeringConnectionId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcPeeringConnectionId',\n ],\n ],\n ],\n 'DeleteVpcPeeringConnectionResult' => [\n 'type' => 'structure',\n 'members' => [\n 'Return' => [\n 'shape' => 'Boolean',\n 'locationName' => 'return',\n ],\n ],\n ],\n 'DeleteVpcRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'VpcId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VpcId' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'DeleteVpnConnectionRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'VpnConnectionId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VpnConnectionId' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'DeleteVpnConnectionRouteRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'VpnConnectionId',\n 'DestinationCidrBlock',\n ],\n 'members' => [\n 'VpnConnectionId' => [\n 'shape' => 'String',\n ],\n 'DestinationCidrBlock' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'DeleteVpnGatewayRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'VpnGatewayId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VpnGatewayId' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'DeregisterImageRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'ImageId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'ImageId' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'DescribeAccountAttributesRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'AttributeNames' => [\n 'shape' => 'AccountAttributeNameStringList',\n 'locationName' => 'attributeName',\n ],\n ],\n ],\n 'DescribeAccountAttributesResult' => [\n 'type' => 'structure',\n 'members' => [\n 'AccountAttributes' => [\n 'shape' => 'AccountAttributeList',\n 'locationName' => 'accountAttributeSet',\n ],\n ],\n ],\n 'DescribeAddressesRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'PublicIps' => [\n 'shape' => 'PublicIpStringList',\n 'locationName' => 'PublicIp',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n 'AllocationIds' => [\n 'shape' => 'AllocationIdList',\n 'locationName' => 'AllocationId',\n ],\n ],\n ],\n 'DescribeAddressesResult' => [\n 'type' => 'structure',\n 'members' => [\n 'Addresses' => [\n 'shape' => 'AddressList',\n 'locationName' => 'addressesSet',\n ],\n ],\n ],\n 'DescribeAvailabilityZonesRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'ZoneNames' => [\n 'shape' => 'ZoneNameStringList',\n 'locationName' => 'ZoneName',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n ],\n ],\n 'DescribeAvailabilityZonesResult' => [\n 'type' => 'structure',\n 'members' => [\n 'AvailabilityZones' => [\n 'shape' => 'AvailabilityZoneList',\n 'locationName' => 'availabilityZoneInfo',\n ],\n ],\n ],\n 'DescribeBundleTasksRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'BundleIds' => [\n 'shape' => 'BundleIdStringList',\n 'locationName' => 'BundleId',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n ],\n ],\n 'DescribeBundleTasksResult' => [\n 'type' => 'structure',\n 'members' => [\n 'BundleTasks' => [\n 'shape' => 'BundleTaskList',\n 'locationName' => 'bundleInstanceTasksSet',\n ],\n ],\n ],\n 'DescribeClassicLinkInstancesRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'InstanceIds' => [\n 'shape' => 'InstanceIdStringList',\n 'locationName' => 'InstanceId',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n 'NextToken' => [\n 'shape' => 'String',\n 'locationName' => 'nextToken',\n ],\n 'MaxResults' => [\n 'shape' => 'Integer',\n 'locationName' => 'maxResults',\n ],\n ],\n ],\n 'DescribeClassicLinkInstancesResult' => [\n 'type' => 'structure',\n 'members' => [\n 'Instances' => [\n 'shape' => 'ClassicLinkInstanceList',\n 'locationName' => 'instancesSet',\n ],\n 'NextToken' => [\n 'shape' => 'String',\n 'locationName' => 'nextToken',\n ],\n ],\n ],\n 'DescribeConversionTaskList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'ConversionTask',\n 'locationName' => 'item',\n ],\n ],\n 'DescribeConversionTasksRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'filter',\n ],\n 'ConversionTaskIds' => [\n 'shape' => 'ConversionIdStringList',\n 'locationName' => 'conversionTaskId',\n ],\n ],\n ],\n 'DescribeConversionTasksResult' => [\n 'type' => 'structure',\n 'members' => [\n 'ConversionTasks' => [\n 'shape' => 'DescribeConversionTaskList',\n 'locationName' => 'conversionTasks',\n ],\n ],\n ],\n 'DescribeCustomerGatewaysRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'CustomerGatewayIds' => [\n 'shape' => 'CustomerGatewayIdStringList',\n 'locationName' => 'CustomerGatewayId',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n ],\n ],\n 'DescribeCustomerGatewaysResult' => [\n 'type' => 'structure',\n 'members' => [\n 'CustomerGateways' => [\n 'shape' => 'CustomerGatewayList',\n 'locationName' => 'customerGatewaySet',\n ],\n ],\n ],\n 'DescribeDhcpOptionsRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'DhcpOptionsIds' => [\n 'shape' => 'DhcpOptionsIdStringList',\n 'locationName' => 'DhcpOptionsId',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n ],\n ],\n 'DescribeDhcpOptionsResult' => [\n 'type' => 'structure',\n 'members' => [\n 'DhcpOptions' => [\n 'shape' => 'DhcpOptionsList',\n 'locationName' => 'dhcpOptionsSet',\n ],\n ],\n ],\n 'DescribeExportTasksRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'ExportTaskIds' => [\n 'shape' => 'ExportTaskIdStringList',\n 'locationName' => 'exportTaskId',\n ],\n ],\n ],\n 'DescribeExportTasksResult' => [\n 'type' => 'structure',\n 'members' => [\n 'ExportTasks' => [\n 'shape' => 'ExportTaskList',\n 'locationName' => 'exportTaskSet',\n ],\n ],\n ],\n 'DescribeImageAttributeRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'ImageId',\n 'Attribute',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'ImageId' => [\n 'shape' => 'String',\n ],\n 'Attribute' => [\n 'shape' => 'ImageAttributeName',\n ],\n ],\n ],\n 'DescribeImagesRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'ImageIds' => [\n 'shape' => 'ImageIdStringList',\n 'locationName' => 'ImageId',\n ],\n 'Owners' => [\n 'shape' => 'OwnerStringList',\n 'locationName' => 'Owner',\n ],\n 'ExecutableUsers' => [\n 'shape' => 'ExecutableByStringList',\n 'locationName' => 'ExecutableBy',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n ],\n ],\n 'DescribeImagesResult' => [\n 'type' => 'structure',\n 'members' => [\n 'Images' => [\n 'shape' => 'ImageList',\n 'locationName' => 'imagesSet',\n ],\n ],\n ],\n 'DescribeInstanceAttributeRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'InstanceId',\n 'Attribute',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'InstanceId' => [\n 'shape' => 'String',\n 'locationName' => 'instanceId',\n ],\n 'Attribute' => [\n 'shape' => 'InstanceAttributeName',\n 'locationName' => 'attribute',\n ],\n ],\n ],\n 'DescribeInstanceStatusRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'InstanceIds' => [\n 'shape' => 'InstanceIdStringList',\n 'locationName' => 'InstanceId',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n 'NextToken' => [\n 'shape' => 'String',\n ],\n 'MaxResults' => [\n 'shape' => 'Integer',\n ],\n 'IncludeAllInstances' => [\n 'shape' => 'Boolean',\n 'locationName' => 'includeAllInstances',\n ],\n ],\n ],\n 'DescribeInstanceStatusResult' => [\n 'type' => 'structure',\n 'members' => [\n 'InstanceStatuses' => [\n 'shape' => 'InstanceStatusList',\n 'locationName' => 'instanceStatusSet',\n ],\n 'NextToken' => [\n 'shape' => 'String',\n 'locationName' => 'nextToken',\n ],\n ],\n ],\n 'DescribeInstancesRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'InstanceIds' => [\n 'shape' => 'InstanceIdStringList',\n 'locationName' => 'InstanceId',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n 'NextToken' => [\n 'shape' => 'String',\n 'locationName' => 'nextToken',\n ],\n 'MaxResults' => [\n 'shape' => 'Integer',\n 'locationName' => 'maxResults',\n ],\n ],\n ],\n 'DescribeInstancesResult' => [\n 'type' => 'structure',\n 'members' => [\n 'Reservations' => [\n 'shape' => 'ReservationList',\n 'locationName' => 'reservationSet',\n ],\n 'NextToken' => [\n 'shape' => 'String',\n 'locationName' => 'nextToken',\n ],\n ],\n ],\n 'DescribeInternetGatewaysRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'InternetGatewayIds' => [\n 'shape' => 'ValueStringList',\n 'locationName' => 'internetGatewayId',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n ],\n ],\n 'DescribeInternetGatewaysResult' => [\n 'type' => 'structure',\n 'members' => [\n 'InternetGateways' => [\n 'shape' => 'InternetGatewayList',\n 'locationName' => 'internetGatewaySet',\n ],\n ],\n ],\n 'DescribeKeyPairsRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'KeyNames' => [\n 'shape' => 'KeyNameStringList',\n 'locationName' => 'KeyName',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n ],\n ],\n 'DescribeKeyPairsResult' => [\n 'type' => 'structure',\n 'members' => [\n 'KeyPairs' => [\n 'shape' => 'KeyPairList',\n 'locationName' => 'keySet',\n ],\n ],\n ],\n 'DescribeNetworkAclsRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'NetworkAclIds' => [\n 'shape' => 'ValueStringList',\n 'locationName' => 'NetworkAclId',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n ],\n ],\n 'DescribeNetworkAclsResult' => [\n 'type' => 'structure',\n 'members' => [\n 'NetworkAcls' => [\n 'shape' => 'NetworkAclList',\n 'locationName' => 'networkAclSet',\n ],\n ],\n ],\n 'DescribeNetworkInterfaceAttributeRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'NetworkInterfaceId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'NetworkInterfaceId' => [\n 'shape' => 'String',\n 'locationName' => 'networkInterfaceId',\n ],\n 'Attribute' => [\n 'shape' => 'NetworkInterfaceAttribute',\n 'locationName' => 'attribute',\n ],\n ],\n ],\n 'DescribeNetworkInterfaceAttributeResult' => [\n 'type' => 'structure',\n 'members' => [\n 'NetworkInterfaceId' => [\n 'shape' => 'String',\n 'locationName' => 'networkInterfaceId',\n ],\n 'Description' => [\n 'shape' => 'AttributeValue',\n 'locationName' => 'description',\n ],\n 'SourceDestCheck' => [\n 'shape' => 'AttributeBooleanValue',\n 'locationName' => 'sourceDestCheck',\n ],\n 'Groups' => [\n 'shape' => 'GroupIdentifierList',\n 'locationName' => 'groupSet',\n ],\n 'Attachment' => [\n 'shape' => 'NetworkInterfaceAttachment',\n 'locationName' => 'attachment',\n ],\n ],\n ],\n 'DescribeNetworkInterfacesRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'NetworkInterfaceIds' => [\n 'shape' => 'NetworkInterfaceIdList',\n 'locationName' => 'NetworkInterfaceId',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'filter',\n ],\n ],\n ],\n 'DescribeNetworkInterfacesResult' => [\n 'type' => 'structure',\n 'members' => [\n 'NetworkInterfaces' => [\n 'shape' => 'NetworkInterfaceList',\n 'locationName' => 'networkInterfaceSet',\n ],\n ],\n ],\n 'DescribePlacementGroupsRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'GroupNames' => [\n 'shape' => 'PlacementGroupStringList',\n 'locationName' => 'groupName',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n ],\n ],\n 'DescribePlacementGroupsResult' => [\n 'type' => 'structure',\n 'members' => [\n 'PlacementGroups' => [\n 'shape' => 'PlacementGroupList',\n 'locationName' => 'placementGroupSet',\n ],\n ],\n ],\n 'DescribeRegionsRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'RegionNames' => [\n 'shape' => 'RegionNameStringList',\n 'locationName' => 'RegionName',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n ],\n ],\n 'DescribeRegionsResult' => [\n 'type' => 'structure',\n 'members' => [\n 'Regions' => [\n 'shape' => 'RegionList',\n 'locationName' => 'regionInfo',\n ],\n ],\n ],\n 'DescribeReservedInstancesListingsRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'ReservedInstancesId' => [\n 'shape' => 'String',\n 'locationName' => 'reservedInstancesId',\n ],\n 'ReservedInstancesListingId' => [\n 'shape' => 'String',\n 'locationName' => 'reservedInstancesListingId',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'filters',\n ],\n ],\n ],\n 'DescribeReservedInstancesListingsResult' => [\n 'type' => 'structure',\n 'members' => [\n 'ReservedInstancesListings' => [\n 'shape' => 'ReservedInstancesListingList',\n 'locationName' => 'reservedInstancesListingsSet',\n ],\n ],\n ],\n 'DescribeReservedInstancesModificationsRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'ReservedInstancesModificationIds' => [\n 'shape' => 'ReservedInstancesModificationIdStringList',\n 'locationName' => 'ReservedInstancesModificationId',\n ],\n 'NextToken' => [\n 'shape' => 'String',\n 'locationName' => 'nextToken',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n ],\n ],\n 'DescribeReservedInstancesModificationsResult' => [\n 'type' => 'structure',\n 'members' => [\n 'ReservedInstancesModifications' => [\n 'shape' => 'ReservedInstancesModificationList',\n 'locationName' => 'reservedInstancesModificationsSet',\n ],\n 'NextToken' => [\n 'shape' => 'String',\n 'locationName' => 'nextToken',\n ],\n ],\n ],\n 'DescribeReservedInstancesOfferingsRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'ReservedInstancesOfferingIds' => [\n 'shape' => 'ReservedInstancesOfferingIdStringList',\n 'locationName' => 'ReservedInstancesOfferingId',\n ],\n 'InstanceType' => [\n 'shape' => 'InstanceType',\n ],\n 'AvailabilityZone' => [\n 'shape' => 'String',\n ],\n 'ProductDescription' => [\n 'shape' => 'RIProductDescription',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n 'InstanceTenancy' => [\n 'shape' => 'Tenancy',\n 'locationName' => 'instanceTenancy',\n ],\n 'OfferingType' => [\n 'shape' => 'OfferingTypeValues',\n 'locationName' => 'offeringType',\n ],\n 'NextToken' => [\n 'shape' => 'String',\n 'locationName' => 'nextToken',\n ],\n 'MaxResults' => [\n 'shape' => 'Integer',\n 'locationName' => 'maxResults',\n ],\n 'IncludeMarketplace' => [\n 'shape' => 'Boolean',\n ],\n 'MinDuration' => [\n 'shape' => 'Long',\n ],\n 'MaxDuration' => [\n 'shape' => 'Long',\n ],\n 'MaxInstanceCount' => [\n 'shape' => 'Integer',\n ],\n ],\n ],\n 'DescribeReservedInstancesOfferingsResult' => [\n 'type' => 'structure',\n 'members' => [\n 'ReservedInstancesOfferings' => [\n 'shape' => 'ReservedInstancesOfferingList',\n 'locationName' => 'reservedInstancesOfferingsSet',\n ],\n 'NextToken' => [\n 'shape' => 'String',\n 'locationName' => 'nextToken',\n ],\n ],\n ],\n 'DescribeReservedInstancesRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'ReservedInstancesIds' => [\n 'shape' => 'ReservedInstancesIdStringList',\n 'locationName' => 'ReservedInstancesId',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n 'OfferingType' => [\n 'shape' => 'OfferingTypeValues',\n 'locationName' => 'offeringType',\n ],\n ],\n ],\n 'DescribeReservedInstancesResult' => [\n 'type' => 'structure',\n 'members' => [\n 'ReservedInstances' => [\n 'shape' => 'ReservedInstancesList',\n 'locationName' => 'reservedInstancesSet',\n ],\n ],\n ],\n 'DescribeRouteTablesRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'RouteTableIds' => [\n 'shape' => 'ValueStringList',\n 'locationName' => 'RouteTableId',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n ],\n ],\n 'DescribeRouteTablesResult' => [\n 'type' => 'structure',\n 'members' => [\n 'RouteTables' => [\n 'shape' => 'RouteTableList',\n 'locationName' => 'routeTableSet',\n ],\n ],\n ],\n 'DescribeSecurityGroupsRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'GroupNames' => [\n 'shape' => 'GroupNameStringList',\n 'locationName' => 'GroupName',\n ],\n 'GroupIds' => [\n 'shape' => 'GroupIdStringList',\n 'locationName' => 'GroupId',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n ],\n ],\n 'DescribeSecurityGroupsResult' => [\n 'type' => 'structure',\n 'members' => [\n 'SecurityGroups' => [\n 'shape' => 'SecurityGroupList',\n 'locationName' => 'securityGroupInfo',\n ],\n ],\n ],\n 'DescribeSnapshotAttributeRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'SnapshotId',\n 'Attribute',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'SnapshotId' => [\n 'shape' => 'String',\n ],\n 'Attribute' => [\n 'shape' => 'SnapshotAttributeName',\n ],\n ],\n ],\n 'DescribeSnapshotAttributeResult' => [\n 'type' => 'structure',\n 'members' => [\n 'SnapshotId' => [\n 'shape' => 'String',\n 'locationName' => 'snapshotId',\n ],\n 'CreateVolumePermissions' => [\n 'shape' => 'CreateVolumePermissionList',\n 'locationName' => 'createVolumePermission',\n ],\n 'ProductCodes' => [\n 'shape' => 'ProductCodeList',\n 'locationName' => 'productCodes',\n ],\n ],\n ],\n 'DescribeSnapshotsRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'SnapshotIds' => [\n 'shape' => 'SnapshotIdStringList',\n 'locationName' => 'SnapshotId',\n ],\n 'OwnerIds' => [\n 'shape' => 'OwnerStringList',\n 'locationName' => 'Owner',\n ],\n 'RestorableByUserIds' => [\n 'shape' => 'RestorableByStringList',\n 'locationName' => 'RestorableBy',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n ],\n ],\n 'DescribeSnapshotsResult' => [\n 'type' => 'structure',\n 'members' => [\n 'Snapshots' => [\n 'shape' => 'SnapshotList',\n 'locationName' => 'snapshotSet',\n ],\n ],\n ],\n 'DescribeSpotDatafeedSubscriptionRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n ],\n ],\n 'DescribeSpotDatafeedSubscriptionResult' => [\n 'type' => 'structure',\n 'members' => [\n 'SpotDatafeedSubscription' => [\n 'shape' => 'SpotDatafeedSubscription',\n 'locationName' => 'spotDatafeedSubscription',\n ],\n ],\n ],\n 'DescribeSpotInstanceRequestsRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'SpotInstanceRequestIds' => [\n 'shape' => 'SpotInstanceRequestIdList',\n 'locationName' => 'SpotInstanceRequestId',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n ],\n ],\n 'DescribeSpotInstanceRequestsResult' => [\n 'type' => 'structure',\n 'members' => [\n 'SpotInstanceRequests' => [\n 'shape' => 'SpotInstanceRequestList',\n 'locationName' => 'spotInstanceRequestSet',\n ],\n ],\n ],\n 'DescribeSpotPriceHistoryRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'StartTime' => [\n 'shape' => 'DateTime',\n 'locationName' => 'startTime',\n ],\n 'EndTime' => [\n 'shape' => 'DateTime',\n 'locationName' => 'endTime',\n ],\n 'InstanceTypes' => [\n 'shape' => 'InstanceTypeList',\n 'locationName' => 'InstanceType',\n ],\n 'ProductDescriptions' => [\n 'shape' => 'ProductDescriptionList',\n 'locationName' => 'ProductDescription',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n 'AvailabilityZone' => [\n 'shape' => 'String',\n 'locationName' => 'availabilityZone',\n ],\n 'MaxResults' => [\n 'shape' => 'Integer',\n 'locationName' => 'maxResults',\n ],\n 'NextToken' => [\n 'shape' => 'String',\n 'locationName' => 'nextToken',\n ],\n ],\n ],\n 'DescribeSpotPriceHistoryResult' => [\n 'type' => 'structure',\n 'members' => [\n 'SpotPriceHistory' => [\n 'shape' => 'SpotPriceHistoryList',\n 'locationName' => 'spotPriceHistorySet',\n ],\n 'NextToken' => [\n 'shape' => 'String',\n 'locationName' => 'nextToken',\n ],\n ],\n ],\n 'DescribeSubnetsRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'SubnetIds' => [\n 'shape' => 'SubnetIdStringList',\n 'locationName' => 'SubnetId',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n ],\n ],\n 'DescribeSubnetsResult' => [\n 'type' => 'structure',\n 'members' => [\n 'Subnets' => [\n 'shape' => 'SubnetList',\n 'locationName' => 'subnetSet',\n ],\n ],\n ],\n 'DescribeTagsRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n 'MaxResults' => [\n 'shape' => 'Integer',\n 'locationName' => 'maxResults',\n ],\n 'NextToken' => [\n 'shape' => 'String',\n 'locationName' => 'nextToken',\n ],\n ],\n ],\n 'DescribeTagsResult' => [\n 'type' => 'structure',\n 'members' => [\n 'Tags' => [\n 'shape' => 'TagDescriptionList',\n 'locationName' => 'tagSet',\n ],\n 'NextToken' => [\n 'shape' => 'String',\n 'locationName' => 'nextToken',\n ],\n ],\n ],\n 'DescribeVolumeAttributeRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'VolumeId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VolumeId' => [\n 'shape' => 'String',\n ],\n 'Attribute' => [\n 'shape' => 'VolumeAttributeName',\n ],\n ],\n ],\n 'DescribeVolumeAttributeResult' => [\n 'type' => 'structure',\n 'members' => [\n 'VolumeId' => [\n 'shape' => 'String',\n 'locationName' => 'volumeId',\n ],\n 'AutoEnableIO' => [\n 'shape' => 'AttributeBooleanValue',\n 'locationName' => 'autoEnableIO',\n ],\n 'ProductCodes' => [\n 'shape' => 'ProductCodeList',\n 'locationName' => 'productCodes',\n ],\n ],\n ],\n 'DescribeVolumeStatusRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VolumeIds' => [\n 'shape' => 'VolumeIdStringList',\n 'locationName' => 'VolumeId',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n 'NextToken' => [\n 'shape' => 'String',\n ],\n 'MaxResults' => [\n 'shape' => 'Integer',\n ],\n ],\n ],\n 'DescribeVolumeStatusResult' => [\n 'type' => 'structure',\n 'members' => [\n 'VolumeStatuses' => [\n 'shape' => 'VolumeStatusList',\n 'locationName' => 'volumeStatusSet',\n ],\n 'NextToken' => [\n 'shape' => 'String',\n 'locationName' => 'nextToken',\n ],\n ],\n ],\n 'DescribeVolumesRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VolumeIds' => [\n 'shape' => 'VolumeIdStringList',\n 'locationName' => 'VolumeId',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n 'NextToken' => [\n 'shape' => 'String',\n 'locationName' => 'nextToken',\n ],\n 'MaxResults' => [\n 'shape' => 'Integer',\n 'locationName' => 'maxResults',\n ],\n ],\n ],\n 'DescribeVolumesResult' => [\n 'type' => 'structure',\n 'members' => [\n 'Volumes' => [\n 'shape' => 'VolumeList',\n 'locationName' => 'volumeSet',\n ],\n 'NextToken' => [\n 'shape' => 'String',\n 'locationName' => 'nextToken',\n ],\n ],\n ],\n 'DescribeVpcAttributeRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'VpcId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VpcId' => [\n 'shape' => 'String',\n ],\n 'Attribute' => [\n 'shape' => 'VpcAttributeName',\n ],\n ],\n ],\n 'DescribeVpcAttributeResult' => [\n 'type' => 'structure',\n 'members' => [\n 'VpcId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcId',\n ],\n 'EnableDnsSupport' => [\n 'shape' => 'AttributeBooleanValue',\n 'locationName' => 'enableDnsSupport',\n ],\n 'EnableDnsHostnames' => [\n 'shape' => 'AttributeBooleanValue',\n 'locationName' => 'enableDnsHostnames',\n ],\n ],\n ],\n 'DescribeVpcClassicLinkRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VpcIds' => [\n 'shape' => 'VpcClassicLinkIdList',\n 'locationName' => 'VpcId',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n ],\n ],\n 'DescribeVpcClassicLinkResult' => [\n 'type' => 'structure',\n 'members' => [\n 'Vpcs' => [\n 'shape' => 'VpcClassicLinkList',\n 'locationName' => 'vpcSet',\n ],\n ],\n ],\n 'DescribeVpcPeeringConnectionsRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VpcPeeringConnectionIds' => [\n 'shape' => 'ValueStringList',\n 'locationName' => 'VpcPeeringConnectionId',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n ],\n ],\n 'DescribeVpcPeeringConnectionsResult' => [\n 'type' => 'structure',\n 'members' => [\n 'VpcPeeringConnections' => [\n 'shape' => 'VpcPeeringConnectionList',\n 'locationName' => 'vpcPeeringConnectionSet',\n ],\n ],\n ],\n 'DescribeVpcsRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VpcIds' => [\n 'shape' => 'VpcIdStringList',\n 'locationName' => 'VpcId',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n ],\n ],\n 'DescribeVpcsResult' => [\n 'type' => 'structure',\n 'members' => [\n 'Vpcs' => [\n 'shape' => 'VpcList',\n 'locationName' => 'vpcSet',\n ],\n ],\n ],\n 'DescribeVpnConnectionsRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VpnConnectionIds' => [\n 'shape' => 'VpnConnectionIdStringList',\n 'locationName' => 'VpnConnectionId',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n ],\n ],\n 'DescribeVpnConnectionsResult' => [\n 'type' => 'structure',\n 'members' => [\n 'VpnConnections' => [\n 'shape' => 'VpnConnectionList',\n 'locationName' => 'vpnConnectionSet',\n ],\n ],\n ],\n 'DescribeVpnGatewaysRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VpnGatewayIds' => [\n 'shape' => 'VpnGatewayIdStringList',\n 'locationName' => 'VpnGatewayId',\n ],\n 'Filters' => [\n 'shape' => 'FilterList',\n 'locationName' => 'Filter',\n ],\n ],\n ],\n 'DescribeVpnGatewaysResult' => [\n 'type' => 'structure',\n 'members' => [\n 'VpnGateways' => [\n 'shape' => 'VpnGatewayList',\n 'locationName' => 'vpnGatewaySet',\n ],\n ],\n ],\n 'DetachClassicLinkVpcRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'InstanceId',\n 'VpcId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'InstanceId' => [\n 'shape' => 'String',\n 'locationName' => 'instanceId',\n ],\n 'VpcId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcId',\n ],\n ],\n ],\n 'DetachClassicLinkVpcResult' => [\n 'type' => 'structure',\n 'members' => [\n 'Return' => [\n 'shape' => 'Boolean',\n 'locationName' => 'return',\n ],\n ],\n ],\n 'DetachInternetGatewayRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'InternetGatewayId',\n 'VpcId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'InternetGatewayId' => [\n 'shape' => 'String',\n 'locationName' => 'internetGatewayId',\n ],\n 'VpcId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcId',\n ],\n ],\n ],\n 'DetachNetworkInterfaceRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'AttachmentId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'AttachmentId' => [\n 'shape' => 'String',\n 'locationName' => 'attachmentId',\n ],\n 'Force' => [\n 'shape' => 'Boolean',\n 'locationName' => 'force',\n ],\n ],\n ],\n 'DetachVolumeRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'VolumeId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VolumeId' => [\n 'shape' => 'String',\n ],\n 'InstanceId' => [\n 'shape' => 'String',\n ],\n 'Device' => [\n 'shape' => 'String',\n ],\n 'Force' => [\n 'shape' => 'Boolean',\n ],\n ],\n ],\n 'DetachVpnGatewayRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'VpnGatewayId',\n 'VpcId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VpnGatewayId' => [\n 'shape' => 'String',\n ],\n 'VpcId' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'DeviceType' => [\n 'type' => 'string',\n 'enum' => [\n 'ebs',\n 'instance-store',\n ],\n ],\n 'DhcpConfiguration' => [\n 'type' => 'structure',\n 'members' => [\n 'Key' => [\n 'shape' => 'String',\n 'locationName' => 'key',\n ],\n 'Values' => [\n 'shape' => 'DhcpConfigurationValueList',\n 'locationName' => 'valueSet',\n ],\n ],\n ],\n 'DhcpConfigurationList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'DhcpConfiguration',\n 'locationName' => 'item',\n ],\n ],\n 'DhcpOptions' => [\n 'type' => 'structure',\n 'members' => [\n 'DhcpOptionsId' => [\n 'shape' => 'String',\n 'locationName' => 'dhcpOptionsId',\n ],\n 'DhcpConfigurations' => [\n 'shape' => 'DhcpConfigurationList',\n 'locationName' => 'dhcpConfigurationSet',\n ],\n 'Tags' => [\n 'shape' => 'TagList',\n 'locationName' => 'tagSet',\n ],\n ],\n ],\n 'DhcpOptionsIdStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'DhcpOptionsId',\n ],\n ],\n 'DhcpOptionsList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'DhcpOptions',\n 'locationName' => 'item',\n ],\n ],\n 'DisableVgwRoutePropagationRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'RouteTableId',\n 'GatewayId',\n ],\n 'members' => [\n 'RouteTableId' => [\n 'shape' => 'String',\n ],\n 'GatewayId' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'DisableVpcClassicLinkRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'VpcId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VpcId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcId',\n ],\n ],\n ],\n 'DisableVpcClassicLinkResult' => [\n 'type' => 'structure',\n 'members' => [\n 'Return' => [\n 'shape' => 'Boolean',\n 'locationName' => 'return',\n ],\n ],\n ],\n 'DisassociateAddressRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'PublicIp' => [\n 'shape' => 'String',\n ],\n 'AssociationId' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'DisassociateRouteTableRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'AssociationId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'AssociationId' => [\n 'shape' => 'String',\n 'locationName' => 'associationId',\n ],\n ],\n ],\n 'DiskImage' => [\n 'type' => 'structure',\n 'members' => [\n 'Image' => [\n 'shape' => 'DiskImageDetail',\n ],\n 'Description' => [\n 'shape' => 'String',\n ],\n 'Volume' => [\n 'shape' => 'VolumeDetail',\n ],\n ],\n ],\n 'DiskImageDescription' => [\n 'type' => 'structure',\n 'required' => [\n 'Format',\n 'Size',\n 'ImportManifestUrl',\n ],\n 'members' => [\n 'Format' => [\n 'shape' => 'DiskImageFormat',\n 'locationName' => 'format',\n ],\n 'Size' => [\n 'shape' => 'Long',\n 'locationName' => 'size',\n ],\n 'ImportManifestUrl' => [\n 'shape' => 'String',\n 'locationName' => 'importManifestUrl',\n ],\n 'Checksum' => [\n 'shape' => 'String',\n 'locationName' => 'checksum',\n ],\n ],\n ],\n 'DiskImageDetail' => [\n 'type' => 'structure',\n 'required' => [\n 'Format',\n 'Bytes',\n 'ImportManifestUrl',\n ],\n 'members' => [\n 'Format' => [\n 'shape' => 'DiskImageFormat',\n 'locationName' => 'format',\n ],\n 'Bytes' => [\n 'shape' => 'Long',\n 'locationName' => 'bytes',\n ],\n 'ImportManifestUrl' => [\n 'shape' => 'String',\n 'locationName' => 'importManifestUrl',\n ],\n ],\n ],\n 'DiskImageFormat' => [\n 'type' => 'string',\n 'enum' => [\n 'VMDK',\n 'RAW',\n 'VHD',\n ],\n ],\n 'DiskImageList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'DiskImage',\n ],\n ],\n 'DiskImageVolumeDescription' => [\n 'type' => 'structure',\n 'required' => [\n 'Id',\n ],\n 'members' => [\n 'Size' => [\n 'shape' => 'Long',\n 'locationName' => 'size',\n ],\n 'Id' => [\n 'shape' => 'String',\n 'locationName' => 'id',\n ],\n ],\n ],\n 'DomainType' => [\n 'type' => 'string',\n 'enum' => [\n 'vpc',\n 'standard',\n ],\n ],\n 'Double' => [\n 'type' => 'double',\n ],\n 'EbsBlockDevice' => [\n 'type' => 'structure',\n 'members' => [\n 'SnapshotId' => [\n 'shape' => 'String',\n 'locationName' => 'snapshotId',\n ],\n 'VolumeSize' => [\n 'shape' => 'Integer',\n 'locationName' => 'volumeSize',\n ],\n 'DeleteOnTermination' => [\n 'shape' => 'Boolean',\n 'locationName' => 'deleteOnTermination',\n ],\n 'VolumeType' => [\n 'shape' => 'VolumeType',\n 'locationName' => 'volumeType',\n ],\n 'Iops' => [\n 'shape' => 'Integer',\n 'locationName' => 'iops',\n ],\n 'Encrypted' => [\n 'shape' => 'Boolean',\n 'locationName' => 'encrypted',\n ],\n ],\n ],\n 'EbsInstanceBlockDevice' => [\n 'type' => 'structure',\n 'members' => [\n 'VolumeId' => [\n 'shape' => 'String',\n 'locationName' => 'volumeId',\n ],\n 'Status' => [\n 'shape' => 'AttachmentStatus',\n 'locationName' => 'status',\n ],\n 'AttachTime' => [\n 'shape' => 'DateTime',\n 'locationName' => 'attachTime',\n ],\n 'DeleteOnTermination' => [\n 'shape' => 'Boolean',\n 'locationName' => 'deleteOnTermination',\n ],\n ],\n ],\n 'EbsInstanceBlockDeviceSpecification' => [\n 'type' => 'structure',\n 'members' => [\n 'VolumeId' => [\n 'shape' => 'String',\n 'locationName' => 'volumeId',\n ],\n 'DeleteOnTermination' => [\n 'shape' => 'Boolean',\n 'locationName' => 'deleteOnTermination',\n ],\n ],\n ],\n 'EnableVgwRoutePropagationRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'RouteTableId',\n 'GatewayId',\n ],\n 'members' => [\n 'RouteTableId' => [\n 'shape' => 'String',\n ],\n 'GatewayId' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'EnableVolumeIORequest' => [\n 'type' => 'structure',\n 'required' => [\n 'VolumeId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VolumeId' => [\n 'shape' => 'String',\n 'locationName' => 'volumeId',\n ],\n ],\n ],\n 'EnableVpcClassicLinkRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'VpcId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VpcId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcId',\n ],\n ],\n ],\n 'EnableVpcClassicLinkResult' => [\n 'type' => 'structure',\n 'members' => [\n 'Return' => [\n 'shape' => 'Boolean',\n 'locationName' => 'return',\n ],\n ],\n ],\n 'EventCode' => [\n 'type' => 'string',\n 'enum' => [\n 'instance-reboot',\n 'system-reboot',\n 'system-maintenance',\n 'instance-retirement',\n 'instance-stop',\n ],\n ],\n 'ExecutableByStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'ExecutableBy',\n ],\n ],\n 'ExportEnvironment' => [\n 'type' => 'string',\n 'enum' => [\n 'citrix',\n 'vmware',\n 'microsoft',\n ],\n ],\n 'ExportTask' => [\n 'type' => 'structure',\n 'members' => [\n 'ExportTaskId' => [\n 'shape' => 'String',\n 'locationName' => 'exportTaskId',\n ],\n 'Description' => [\n 'shape' => 'String',\n 'locationName' => 'description',\n ],\n 'State' => [\n 'shape' => 'ExportTaskState',\n 'locationName' => 'state',\n ],\n 'StatusMessage' => [\n 'shape' => 'String',\n 'locationName' => 'statusMessage',\n ],\n 'InstanceExportDetails' => [\n 'shape' => 'InstanceExportDetails',\n 'locationName' => 'instanceExport',\n ],\n 'ExportToS3Task' => [\n 'shape' => 'ExportToS3Task',\n 'locationName' => 'exportToS3',\n ],\n ],\n ],\n 'ExportTaskIdStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'ExportTaskId',\n ],\n ],\n 'ExportTaskList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'ExportTask',\n 'locationName' => 'item',\n ],\n ],\n 'ExportTaskState' => [\n 'type' => 'string',\n 'enum' => [\n 'active',\n 'cancelling',\n 'cancelled',\n 'completed',\n ],\n ],\n 'ExportToS3Task' => [\n 'type' => 'structure',\n 'members' => [\n 'DiskImageFormat' => [\n 'shape' => 'DiskImageFormat',\n 'locationName' => 'diskImageFormat',\n ],\n 'ContainerFormat' => [\n 'shape' => 'ContainerFormat',\n 'locationName' => 'containerFormat',\n ],\n 'S3Bucket' => [\n 'shape' => 'String',\n 'locationName' => 's3Bucket',\n ],\n 'S3Key' => [\n 'shape' => 'String',\n 'locationName' => 's3Key',\n ],\n ],\n ],\n 'ExportToS3TaskSpecification' => [\n 'type' => 'structure',\n 'members' => [\n 'DiskImageFormat' => [\n 'shape' => 'DiskImageFormat',\n 'locationName' => 'diskImageFormat',\n ],\n 'ContainerFormat' => [\n 'shape' => 'ContainerFormat',\n 'locationName' => 'containerFormat',\n ],\n 'S3Bucket' => [\n 'shape' => 'String',\n 'locationName' => 's3Bucket',\n ],\n 'S3Prefix' => [\n 'shape' => 'String',\n 'locationName' => 's3Prefix',\n ],\n ],\n ],\n 'Filter' => [\n 'type' => 'structure',\n 'members' => [\n 'Name' => [\n 'shape' => 'String',\n ],\n 'Values' => [\n 'shape' => 'ValueStringList',\n 'locationName' => 'Value',\n ],\n ],\n ],\n 'FilterList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'Filter',\n 'locationName' => 'Filter',\n ],\n ],\n 'Float' => [\n 'type' => 'float',\n ],\n 'GatewayType' => [\n 'type' => 'string',\n 'enum' => [\n 'ipsec.1',\n ],\n ],\n 'GetConsoleOutputRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'InstanceId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'InstanceId' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'GetConsoleOutputResult' => [\n 'type' => 'structure',\n 'members' => [\n 'InstanceId' => [\n 'shape' => 'String',\n 'locationName' => 'instanceId',\n ],\n 'Timestamp' => [\n 'shape' => 'DateTime',\n 'locationName' => 'timestamp',\n ],\n 'Output' => [\n 'shape' => 'String',\n 'locationName' => 'output',\n ],\n ],\n ],\n 'GetPasswordDataRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'InstanceId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'InstanceId' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'GetPasswordDataResult' => [\n 'type' => 'structure',\n 'members' => [\n 'InstanceId' => [\n 'shape' => 'String',\n 'locationName' => 'instanceId',\n ],\n 'Timestamp' => [\n 'shape' => 'DateTime',\n 'locationName' => 'timestamp',\n ],\n 'PasswordData' => [\n 'shape' => 'String',\n 'locationName' => 'passwordData',\n ],\n ],\n ],\n 'GroupIdStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'groupId',\n ],\n ],\n 'GroupIdentifier' => [\n 'type' => 'structure',\n 'members' => [\n 'GroupName' => [\n 'shape' => 'String',\n 'locationName' => 'groupName',\n ],\n 'GroupId' => [\n 'shape' => 'String',\n 'locationName' => 'groupId',\n ],\n ],\n ],\n 'GroupIdentifierList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'GroupIdentifier',\n 'locationName' => 'item',\n ],\n ],\n 'GroupNameStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'GroupName',\n ],\n ],\n 'HypervisorType' => [\n 'type' => 'string',\n 'enum' => [\n 'ovm',\n 'xen',\n ],\n ],\n 'IamInstanceProfile' => [\n 'type' => 'structure',\n 'members' => [\n 'Arn' => [\n 'shape' => 'String',\n 'locationName' => 'arn',\n ],\n 'Id' => [\n 'shape' => 'String',\n 'locationName' => 'id',\n ],\n ],\n ],\n 'IamInstanceProfileSpecification' => [\n 'type' => 'structure',\n 'members' => [\n 'Arn' => [\n 'shape' => 'String',\n 'locationName' => 'arn',\n ],\n 'Name' => [\n 'shape' => 'String',\n 'locationName' => 'name',\n ],\n ],\n ],\n 'IcmpTypeCode' => [\n 'type' => 'structure',\n 'members' => [\n 'Type' => [\n 'shape' => 'Integer',\n 'locationName' => 'type',\n ],\n 'Code' => [\n 'shape' => 'Integer',\n 'locationName' => 'code',\n ],\n ],\n ],\n 'Image' => [\n 'type' => 'structure',\n 'members' => [\n 'ImageId' => [\n 'shape' => 'String',\n 'locationName' => 'imageId',\n ],\n 'ImageLocation' => [\n 'shape' => 'String',\n 'locationName' => 'imageLocation',\n ],\n 'State' => [\n 'shape' => 'ImageState',\n 'locationName' => 'imageState',\n ],\n 'OwnerId' => [\n 'shape' => 'String',\n 'locationName' => 'imageOwnerId',\n ],\n 'CreationDate' => [\n 'shape' => 'String',\n 'locationName' => 'creationDate',\n ],\n 'Public' => [\n 'shape' => 'Boolean',\n 'locationName' => 'isPublic',\n ],\n 'ProductCodes' => [\n 'shape' => 'ProductCodeList',\n 'locationName' => 'productCodes',\n ],\n 'Architecture' => [\n 'shape' => 'ArchitectureValues',\n 'locationName' => 'architecture',\n ],\n 'ImageType' => [\n 'shape' => 'ImageTypeValues',\n 'locationName' => 'imageType',\n ],\n 'KernelId' => [\n 'shape' => 'String',\n 'locationName' => 'kernelId',\n ],\n 'RamdiskId' => [\n 'shape' => 'String',\n 'locationName' => 'ramdiskId',\n ],\n 'Platform' => [\n 'shape' => 'PlatformValues',\n 'locationName' => 'platform',\n ],\n 'SriovNetSupport' => [\n 'shape' => 'String',\n 'locationName' => 'sriovNetSupport',\n ],\n 'StateReason' => [\n 'shape' => 'StateReason',\n 'locationName' => 'stateReason',\n ],\n 'ImageOwnerAlias' => [\n 'shape' => 'String',\n 'locationName' => 'imageOwnerAlias',\n ],\n 'Name' => [\n 'shape' => 'String',\n 'locationName' => 'name',\n ],\n 'Description' => [\n 'shape' => 'String',\n 'locationName' => 'description',\n ],\n 'RootDeviceType' => [\n 'shape' => 'DeviceType',\n 'locationName' => 'rootDeviceType',\n ],\n 'RootDeviceName' => [\n 'shape' => 'String',\n 'locationName' => 'rootDeviceName',\n ],\n 'BlockDeviceMappings' => [\n 'shape' => 'BlockDeviceMappingList',\n 'locationName' => 'blockDeviceMapping',\n ],\n 'VirtualizationType' => [\n 'shape' => 'VirtualizationType',\n 'locationName' => 'virtualizationType',\n ],\n 'Tags' => [\n 'shape' => 'TagList',\n 'locationName' => 'tagSet',\n ],\n 'Hypervisor' => [\n 'shape' => 'HypervisorType',\n 'locationName' => 'hypervisor',\n ],\n ],\n ],\n 'ImageAttribute' => [\n 'type' => 'structure',\n 'members' => [\n 'ImageId' => [\n 'shape' => 'String',\n 'locationName' => 'imageId',\n ],\n 'LaunchPermissions' => [\n 'shape' => 'LaunchPermissionList',\n 'locationName' => 'launchPermission',\n ],\n 'ProductCodes' => [\n 'shape' => 'ProductCodeList',\n 'locationName' => 'productCodes',\n ],\n 'KernelId' => [\n 'shape' => 'AttributeValue',\n 'locationName' => 'kernel',\n ],\n 'RamdiskId' => [\n 'shape' => 'AttributeValue',\n 'locationName' => 'ramdisk',\n ],\n 'Description' => [\n 'shape' => 'AttributeValue',\n 'locationName' => 'description',\n ],\n 'SriovNetSupport' => [\n 'shape' => 'AttributeValue',\n 'locationName' => 'sriovNetSupport',\n ],\n 'BlockDeviceMappings' => [\n 'shape' => 'BlockDeviceMappingList',\n 'locationName' => 'blockDeviceMapping',\n ],\n ],\n ],\n 'ImageAttributeName' => [\n 'type' => 'string',\n 'enum' => [\n 'description',\n 'kernel',\n 'ramdisk',\n 'launchPermission',\n 'productCodes',\n 'blockDeviceMapping',\n ],\n ],\n 'ImageIdStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'ImageId',\n ],\n ],\n 'ImageList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'Image',\n 'locationName' => 'item',\n ],\n ],\n 'ImageState' => [\n 'type' => 'string',\n 'enum' => [\n 'available',\n 'deregistered',\n ],\n ],\n 'ImageTypeValues' => [\n 'type' => 'string',\n 'enum' => [\n 'machine',\n 'kernel',\n 'ramdisk',\n ],\n ],\n 'ImportInstanceLaunchSpecification' => [\n 'type' => 'structure',\n 'members' => [\n 'Architecture' => [\n 'shape' => 'ArchitectureValues',\n 'locationName' => 'architecture',\n ],\n 'GroupNames' => [\n 'shape' => 'SecurityGroupStringList',\n 'locationName' => 'GroupName',\n ],\n 'GroupIds' => [\n 'shape' => 'SecurityGroupIdStringList',\n 'locationName' => 'GroupId',\n ],\n 'AdditionalInfo' => [\n 'shape' => 'String',\n 'locationName' => 'additionalInfo',\n ],\n 'UserData' => [\n 'shape' => 'UserData',\n 'locationName' => 'userData',\n ],\n 'InstanceType' => [\n 'shape' => 'InstanceType',\n 'locationName' => 'instanceType',\n ],\n 'Placement' => [\n 'shape' => 'Placement',\n 'locationName' => 'placement',\n ],\n 'Monitoring' => [\n 'shape' => 'Boolean',\n 'locationName' => 'monitoring',\n ],\n 'SubnetId' => [\n 'shape' => 'String',\n 'locationName' => 'subnetId',\n ],\n 'InstanceInitiatedShutdownBehavior' => [\n 'shape' => 'ShutdownBehavior',\n 'locationName' => 'instanceInitiatedShutdownBehavior',\n ],\n 'PrivateIpAddress' => [\n 'shape' => 'String',\n 'locationName' => 'privateIpAddress',\n ],\n ],\n ],\n 'ImportInstanceRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'Platform',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'Description' => [\n 'shape' => 'String',\n 'locationName' => 'description',\n ],\n 'LaunchSpecification' => [\n 'shape' => 'ImportInstanceLaunchSpecification',\n 'locationName' => 'launchSpecification',\n ],\n 'DiskImages' => [\n 'shape' => 'DiskImageList',\n 'locationName' => 'diskImage',\n ],\n 'Platform' => [\n 'shape' => 'PlatformValues',\n 'locationName' => 'platform',\n ],\n ],\n ],\n 'ImportInstanceResult' => [\n 'type' => 'structure',\n 'members' => [\n 'ConversionTask' => [\n 'shape' => 'ConversionTask',\n 'locationName' => 'conversionTask',\n ],\n ],\n ],\n 'ImportInstanceTaskDetails' => [\n 'type' => 'structure',\n 'required' => [\n 'Volumes',\n ],\n 'members' => [\n 'Volumes' => [\n 'shape' => 'ImportInstanceVolumeDetailSet',\n 'locationName' => 'volumes',\n ],\n 'InstanceId' => [\n 'shape' => 'String',\n 'locationName' => 'instanceId',\n ],\n 'Platform' => [\n 'shape' => 'PlatformValues',\n 'locationName' => 'platform',\n ],\n 'Description' => [\n 'shape' => 'String',\n 'locationName' => 'description',\n ],\n ],\n ],\n 'ImportInstanceVolumeDetailItem' => [\n 'type' => 'structure',\n 'required' => [\n 'BytesConverted',\n 'AvailabilityZone',\n 'Image',\n 'Volume',\n 'Status',\n ],\n 'members' => [\n 'BytesConverted' => [\n 'shape' => 'Long',\n 'locationName' => 'bytesConverted',\n ],\n 'AvailabilityZone' => [\n 'shape' => 'String',\n 'locationName' => 'availabilityZone',\n ],\n 'Image' => [\n 'shape' => 'DiskImageDescription',\n 'locationName' => 'image',\n ],\n 'Volume' => [\n 'shape' => 'DiskImageVolumeDescription',\n 'locationName' => 'volume',\n ],\n 'Status' => [\n 'shape' => 'String',\n 'locationName' => 'status',\n ],\n 'StatusMessage' => [\n 'shape' => 'String',\n 'locationName' => 'statusMessage',\n ],\n 'Description' => [\n 'shape' => 'String',\n 'locationName' => 'description',\n ],\n ],\n ],\n 'ImportInstanceVolumeDetailSet' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'ImportInstanceVolumeDetailItem',\n 'locationName' => 'item',\n ],\n ],\n 'ImportKeyPairRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'KeyName',\n 'PublicKeyMaterial',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'KeyName' => [\n 'shape' => 'String',\n 'locationName' => 'keyName',\n ],\n 'PublicKeyMaterial' => [\n 'shape' => 'Blob',\n 'locationName' => 'publicKeyMaterial',\n ],\n ],\n ],\n 'ImportKeyPairResult' => [\n 'type' => 'structure',\n 'members' => [\n 'KeyName' => [\n 'shape' => 'String',\n 'locationName' => 'keyName',\n ],\n 'KeyFingerprint' => [\n 'shape' => 'String',\n 'locationName' => 'keyFingerprint',\n ],\n ],\n ],\n 'ImportVolumeRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'AvailabilityZone',\n 'Image',\n 'Volume',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'AvailabilityZone' => [\n 'shape' => 'String',\n 'locationName' => 'availabilityZone',\n ],\n 'Image' => [\n 'shape' => 'DiskImageDetail',\n 'locationName' => 'image',\n ],\n 'Description' => [\n 'shape' => 'String',\n 'locationName' => 'description',\n ],\n 'Volume' => [\n 'shape' => 'VolumeDetail',\n 'locationName' => 'volume',\n ],\n ],\n ],\n 'ImportVolumeResult' => [\n 'type' => 'structure',\n 'members' => [\n 'ConversionTask' => [\n 'shape' => 'ConversionTask',\n 'locationName' => 'conversionTask',\n ],\n ],\n ],\n 'ImportVolumeTaskDetails' => [\n 'type' => 'structure',\n 'required' => [\n 'BytesConverted',\n 'AvailabilityZone',\n 'Image',\n 'Volume',\n ],\n 'members' => [\n 'BytesConverted' => [\n 'shape' => 'Long',\n 'locationName' => 'bytesConverted',\n ],\n 'AvailabilityZone' => [\n 'shape' => 'String',\n 'locationName' => 'availabilityZone',\n ],\n 'Description' => [\n 'shape' => 'String',\n 'locationName' => 'description',\n ],\n 'Image' => [\n 'shape' => 'DiskImageDescription',\n 'locationName' => 'image',\n ],\n 'Volume' => [\n 'shape' => 'DiskImageVolumeDescription',\n 'locationName' => 'volume',\n ],\n ],\n ],\n 'Instance' => [\n 'type' => 'structure',\n 'members' => [\n 'InstanceId' => [\n 'shape' => 'String',\n 'locationName' => 'instanceId',\n ],\n 'ImageId' => [\n 'shape' => 'String',\n 'locationName' => 'imageId',\n ],\n 'State' => [\n 'shape' => 'InstanceState',\n 'locationName' => 'instanceState',\n ],\n 'PrivateDnsName' => [\n 'shape' => 'String',\n 'locationName' => 'privateDnsName',\n ],\n 'PublicDnsName' => [\n 'shape' => 'String',\n 'locationName' => 'dnsName',\n ],\n 'StateTransitionReason' => [\n 'shape' => 'String',\n 'locationName' => 'reason',\n ],\n 'KeyName' => [\n 'shape' => 'String',\n 'locationName' => 'keyName',\n ],\n 'AmiLaunchIndex' => [\n 'shape' => 'Integer',\n 'locationName' => 'amiLaunchIndex',\n ],\n 'ProductCodes' => [\n 'shape' => 'ProductCodeList',\n 'locationName' => 'productCodes',\n ],\n 'InstanceType' => [\n 'shape' => 'InstanceType',\n 'locationName' => 'instanceType',\n ],\n 'LaunchTime' => [\n 'shape' => 'DateTime',\n 'locationName' => 'launchTime',\n ],\n 'Placement' => [\n 'shape' => 'Placement',\n 'locationName' => 'placement',\n ],\n 'KernelId' => [\n 'shape' => 'String',\n 'locationName' => 'kernelId',\n ],\n 'RamdiskId' => [\n 'shape' => 'String',\n 'locationName' => 'ramdiskId',\n ],\n 'Platform' => [\n 'shape' => 'PlatformValues',\n 'locationName' => 'platform',\n ],\n 'Monitoring' => [\n 'shape' => 'Monitoring',\n 'locationName' => 'monitoring',\n ],\n 'SubnetId' => [\n 'shape' => 'String',\n 'locationName' => 'subnetId',\n ],\n 'VpcId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcId',\n ],\n 'PrivateIpAddress' => [\n 'shape' => 'String',\n 'locationName' => 'privateIpAddress',\n ],\n 'PublicIpAddress' => [\n 'shape' => 'String',\n 'locationName' => 'ipAddress',\n ],\n 'StateReason' => [\n 'shape' => 'StateReason',\n 'locationName' => 'stateReason',\n ],\n 'Architecture' => [\n 'shape' => 'ArchitectureValues',\n 'locationName' => 'architecture',\n ],\n 'RootDeviceType' => [\n 'shape' => 'DeviceType',\n 'locationName' => 'rootDeviceType',\n ],\n 'RootDeviceName' => [\n 'shape' => 'String',\n 'locationName' => 'rootDeviceName',\n ],\n 'BlockDeviceMappings' => [\n 'shape' => 'InstanceBlockDeviceMappingList',\n 'locationName' => 'blockDeviceMapping',\n ],\n 'VirtualizationType' => [\n 'shape' => 'VirtualizationType',\n 'locationName' => 'virtualizationType',\n ],\n 'InstanceLifecycle' => [\n 'shape' => 'InstanceLifecycleType',\n 'locationName' => 'instanceLifecycle',\n ],\n 'SpotInstanceRequestId' => [\n 'shape' => 'String',\n 'locationName' => 'spotInstanceRequestId',\n ],\n 'ClientToken' => [\n 'shape' => 'String',\n 'locationName' => 'clientToken',\n ],\n 'Tags' => [\n 'shape' => 'TagList',\n 'locationName' => 'tagSet',\n ],\n 'SecurityGroups' => [\n 'shape' => 'GroupIdentifierList',\n 'locationName' => 'groupSet',\n ],\n 'SourceDestCheck' => [\n 'shape' => 'Boolean',\n 'locationName' => 'sourceDestCheck',\n ],\n 'Hypervisor' => [\n 'shape' => 'HypervisorType',\n 'locationName' => 'hypervisor',\n ],\n 'NetworkInterfaces' => [\n 'shape' => 'InstanceNetworkInterfaceList',\n 'locationName' => 'networkInterfaceSet',\n ],\n 'IamInstanceProfile' => [\n 'shape' => 'IamInstanceProfile',\n 'locationName' => 'iamInstanceProfile',\n ],\n 'EbsOptimized' => [\n 'shape' => 'Boolean',\n 'locationName' => 'ebsOptimized',\n ],\n 'SriovNetSupport' => [\n 'shape' => 'String',\n 'locationName' => 'sriovNetSupport',\n ],\n ],\n ],\n 'InstanceAttribute' => [\n 'type' => 'structure',\n 'members' => [\n 'InstanceId' => [\n 'shape' => 'String',\n 'locationName' => 'instanceId',\n ],\n 'InstanceType' => [\n 'shape' => 'AttributeValue',\n 'locationName' => 'instanceType',\n ],\n 'KernelId' => [\n 'shape' => 'AttributeValue',\n 'locationName' => 'kernel',\n ],\n 'RamdiskId' => [\n 'shape' => 'AttributeValue',\n 'locationName' => 'ramdisk',\n ],\n 'UserData' => [\n 'shape' => 'AttributeValue',\n 'locationName' => 'userData',\n ],\n 'DisableApiTermination' => [\n 'shape' => 'AttributeBooleanValue',\n 'locationName' => 'disableApiTermination',\n ],\n 'InstanceInitiatedShutdownBehavior' => [\n 'shape' => 'AttributeValue',\n 'locationName' => 'instanceInitiatedShutdownBehavior',\n ],\n 'RootDeviceName' => [\n 'shape' => 'AttributeValue',\n 'locationName' => 'rootDeviceName',\n ],\n 'BlockDeviceMappings' => [\n 'shape' => 'InstanceBlockDeviceMappingList',\n 'locationName' => 'blockDeviceMapping',\n ],\n 'ProductCodes' => [\n 'shape' => 'ProductCodeList',\n 'locationName' => 'productCodes',\n ],\n 'EbsOptimized' => [\n 'shape' => 'AttributeBooleanValue',\n 'locationName' => 'ebsOptimized',\n ],\n 'SriovNetSupport' => [\n 'shape' => 'AttributeValue',\n 'locationName' => 'sriovNetSupport',\n ],\n 'SourceDestCheck' => [\n 'shape' => 'AttributeBooleanValue',\n 'locationName' => 'sourceDestCheck',\n ],\n 'Groups' => [\n 'shape' => 'GroupIdentifierList',\n 'locationName' => 'groupSet',\n ],\n ],\n ],\n 'InstanceAttributeName' => [\n 'type' => 'string',\n 'enum' => [\n 'instanceType',\n 'kernel',\n 'ramdisk',\n 'userData',\n 'disableApiTermination',\n 'instanceInitiatedShutdownBehavior',\n 'rootDeviceName',\n 'blockDeviceMapping',\n 'productCodes',\n 'sourceDestCheck',\n 'groupSet',\n 'ebsOptimized',\n 'sriovNetSupport',\n ],\n ],\n 'InstanceBlockDeviceMapping' => [\n 'type' => 'structure',\n 'members' => [\n 'DeviceName' => [\n 'shape' => 'String',\n 'locationName' => 'deviceName',\n ],\n 'Ebs' => [\n 'shape' => 'EbsInstanceBlockDevice',\n 'locationName' => 'ebs',\n ],\n ],\n ],\n 'InstanceBlockDeviceMappingList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'InstanceBlockDeviceMapping',\n 'locationName' => 'item',\n ],\n ],\n 'InstanceBlockDeviceMappingSpecification' => [\n 'type' => 'structure',\n 'members' => [\n 'DeviceName' => [\n 'shape' => 'String',\n 'locationName' => 'deviceName',\n ],\n 'Ebs' => [\n 'shape' => 'EbsInstanceBlockDeviceSpecification',\n 'locationName' => 'ebs',\n ],\n 'VirtualName' => [\n 'shape' => 'String',\n 'locationName' => 'virtualName',\n ],\n 'NoDevice' => [\n 'shape' => 'String',\n 'locationName' => 'noDevice',\n ],\n ],\n ],\n 'InstanceBlockDeviceMappingSpecificationList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'InstanceBlockDeviceMappingSpecification',\n 'locationName' => 'item',\n ],\n ],\n 'InstanceCount' => [\n 'type' => 'structure',\n 'members' => [\n 'State' => [\n 'shape' => 'ListingState',\n 'locationName' => 'state',\n ],\n 'InstanceCount' => [\n 'shape' => 'Integer',\n 'locationName' => 'instanceCount',\n ],\n ],\n ],\n 'InstanceCountList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'InstanceCount',\n 'locationName' => 'item',\n ],\n ],\n 'InstanceExportDetails' => [\n 'type' => 'structure',\n 'members' => [\n 'InstanceId' => [\n 'shape' => 'String',\n 'locationName' => 'instanceId',\n ],\n 'TargetEnvironment' => [\n 'shape' => 'ExportEnvironment',\n 'locationName' => 'targetEnvironment',\n ],\n ],\n ],\n 'InstanceIdStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'InstanceId',\n ],\n ],\n 'InstanceLifecycleType' => [\n 'type' => 'string',\n 'enum' => [\n 'spot',\n ],\n ],\n 'InstanceList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'Instance',\n 'locationName' => 'item',\n ],\n ],\n 'InstanceMonitoring' => [\n 'type' => 'structure',\n 'members' => [\n 'InstanceId' => [\n 'shape' => 'String',\n 'locationName' => 'instanceId',\n ],\n 'Monitoring' => [\n 'shape' => 'Monitoring',\n 'locationName' => 'monitoring',\n ],\n ],\n ],\n 'InstanceMonitoringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'InstanceMonitoring',\n 'locationName' => 'item',\n ],\n ],\n 'InstanceNetworkInterface' => [\n 'type' => 'structure',\n 'members' => [\n 'NetworkInterfaceId' => [\n 'shape' => 'String',\n 'locationName' => 'networkInterfaceId',\n ],\n 'SubnetId' => [\n 'shape' => 'String',\n 'locationName' => 'subnetId',\n ],\n 'VpcId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcId',\n ],\n 'Description' => [\n 'shape' => 'String',\n 'locationName' => 'description',\n ],\n 'OwnerId' => [\n 'shape' => 'String',\n 'locationName' => 'ownerId',\n ],\n 'Status' => [\n 'shape' => 'NetworkInterfaceStatus',\n 'locationName' => 'status',\n ],\n 'MacAddress' => [\n 'shape' => 'String',\n 'locationName' => 'macAddress',\n ],\n 'PrivateIpAddress' => [\n 'shape' => 'String',\n 'locationName' => 'privateIpAddress',\n ],\n 'PrivateDnsName' => [\n 'shape' => 'String',\n 'locationName' => 'privateDnsName',\n ],\n 'SourceDestCheck' => [\n 'shape' => 'Boolean',\n 'locationName' => 'sourceDestCheck',\n ],\n 'Groups' => [\n 'shape' => 'GroupIdentifierList',\n 'locationName' => 'groupSet',\n ],\n 'Attachment' => [\n 'shape' => 'InstanceNetworkInterfaceAttachment',\n 'locationName' => 'attachment',\n ],\n 'Association' => [\n 'shape' => 'InstanceNetworkInterfaceAssociation',\n 'locationName' => 'association',\n ],\n 'PrivateIpAddresses' => [\n 'shape' => 'InstancePrivateIpAddressList',\n 'locationName' => 'privateIpAddressesSet',\n ],\n ],\n ],\n 'InstanceNetworkInterfaceAssociation' => [\n 'type' => 'structure',\n 'members' => [\n 'PublicIp' => [\n 'shape' => 'String',\n 'locationName' => 'publicIp',\n ],\n 'PublicDnsName' => [\n 'shape' => 'String',\n 'locationName' => 'publicDnsName',\n ],\n 'IpOwnerId' => [\n 'shape' => 'String',\n 'locationName' => 'ipOwnerId',\n ],\n ],\n ],\n 'InstanceNetworkInterfaceAttachment' => [\n 'type' => 'structure',\n 'members' => [\n 'AttachmentId' => [\n 'shape' => 'String',\n 'locationName' => 'attachmentId',\n ],\n 'DeviceIndex' => [\n 'shape' => 'Integer',\n 'locationName' => 'deviceIndex',\n ],\n 'Status' => [\n 'shape' => 'AttachmentStatus',\n 'locationName' => 'status',\n ],\n 'AttachTime' => [\n 'shape' => 'DateTime',\n 'locationName' => 'attachTime',\n ],\n 'DeleteOnTermination' => [\n 'shape' => 'Boolean',\n 'locationName' => 'deleteOnTermination',\n ],\n ],\n ],\n 'InstanceNetworkInterfaceList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'InstanceNetworkInterface',\n 'locationName' => 'item',\n ],\n ],\n 'InstanceNetworkInterfaceSpecification' => [\n 'type' => 'structure',\n 'members' => [\n 'NetworkInterfaceId' => [\n 'shape' => 'String',\n 'locationName' => 'networkInterfaceId',\n ],\n 'DeviceIndex' => [\n 'shape' => 'Integer',\n 'locationName' => 'deviceIndex',\n ],\n 'SubnetId' => [\n 'shape' => 'String',\n 'locationName' => 'subnetId',\n ],\n 'Description' => [\n 'shape' => 'String',\n 'locationName' => 'description',\n ],\n 'PrivateIpAddress' => [\n 'shape' => 'String',\n 'locationName' => 'privateIpAddress',\n ],\n 'Groups' => [\n 'shape' => 'SecurityGroupIdStringList',\n 'locationName' => 'SecurityGroupId',\n ],\n 'DeleteOnTermination' => [\n 'shape' => 'Boolean',\n 'locationName' => 'deleteOnTermination',\n ],\n 'PrivateIpAddresses' => [\n 'shape' => 'PrivateIpAddressSpecificationList',\n 'locationName' => 'privateIpAddressesSet',\n 'queryName' => 'PrivateIpAddresses',\n ],\n 'SecondaryPrivateIpAddressCount' => [\n 'shape' => 'Integer',\n 'locationName' => 'secondaryPrivateIpAddressCount',\n ],\n 'AssociatePublicIpAddress' => [\n 'shape' => 'Boolean',\n 'locationName' => 'associatePublicIpAddress',\n ],\n ],\n ],\n 'InstanceNetworkInterfaceSpecificationList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'InstanceNetworkInterfaceSpecification',\n 'locationName' => 'item',\n ],\n ],\n 'InstancePrivateIpAddress' => [\n 'type' => 'structure',\n 'members' => [\n 'PrivateIpAddress' => [\n 'shape' => 'String',\n 'locationName' => 'privateIpAddress',\n ],\n 'PrivateDnsName' => [\n 'shape' => 'String',\n 'locationName' => 'privateDnsName',\n ],\n 'Primary' => [\n 'shape' => 'Boolean',\n 'locationName' => 'primary',\n ],\n 'Association' => [\n 'shape' => 'InstanceNetworkInterfaceAssociation',\n 'locationName' => 'association',\n ],\n ],\n ],\n 'InstancePrivateIpAddressList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'InstancePrivateIpAddress',\n 'locationName' => 'item',\n ],\n ],\n 'InstanceState' => [\n 'type' => 'structure',\n 'members' => [\n 'Code' => [\n 'shape' => 'Integer',\n 'locationName' => 'code',\n ],\n 'Name' => [\n 'shape' => 'InstanceStateName',\n 'locationName' => 'name',\n ],\n ],\n ],\n 'InstanceStateChange' => [\n 'type' => 'structure',\n 'members' => [\n 'InstanceId' => [\n 'shape' => 'String',\n 'locationName' => 'instanceId',\n ],\n 'CurrentState' => [\n 'shape' => 'InstanceState',\n 'locationName' => 'currentState',\n ],\n 'PreviousState' => [\n 'shape' => 'InstanceState',\n 'locationName' => 'previousState',\n ],\n ],\n ],\n 'InstanceStateChangeList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'InstanceStateChange',\n 'locationName' => 'item',\n ],\n ],\n 'InstanceStateName' => [\n 'type' => 'string',\n 'enum' => [\n 'pending',\n 'running',\n 'shutting-down',\n 'terminated',\n 'stopping',\n 'stopped',\n ],\n ],\n 'InstanceStatus' => [\n 'type' => 'structure',\n 'members' => [\n 'InstanceId' => [\n 'shape' => 'String',\n 'locationName' => 'instanceId',\n ],\n 'AvailabilityZone' => [\n 'shape' => 'String',\n 'locationName' => 'availabilityZone',\n ],\n 'Events' => [\n 'shape' => 'InstanceStatusEventList',\n 'locationName' => 'eventsSet',\n ],\n 'InstanceState' => [\n 'shape' => 'InstanceState',\n 'locationName' => 'instanceState',\n ],\n 'SystemStatus' => [\n 'shape' => 'InstanceStatusSummary',\n 'locationName' => 'systemStatus',\n ],\n 'InstanceStatus' => [\n 'shape' => 'InstanceStatusSummary',\n 'locationName' => 'instanceStatus',\n ],\n ],\n ],\n 'InstanceStatusDetails' => [\n 'type' => 'structure',\n 'members' => [\n 'Name' => [\n 'shape' => 'StatusName',\n 'locationName' => 'name',\n ],\n 'Status' => [\n 'shape' => 'StatusType',\n 'locationName' => 'status',\n ],\n 'ImpairedSince' => [\n 'shape' => 'DateTime',\n 'locationName' => 'impairedSince',\n ],\n ],\n ],\n 'InstanceStatusDetailsList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'InstanceStatusDetails',\n 'locationName' => 'item',\n ],\n ],\n 'InstanceStatusEvent' => [\n 'type' => 'structure',\n 'members' => [\n 'Code' => [\n 'shape' => 'EventCode',\n 'locationName' => 'code',\n ],\n 'Description' => [\n 'shape' => 'String',\n 'locationName' => 'description',\n ],\n 'NotBefore' => [\n 'shape' => 'DateTime',\n 'locationName' => 'notBefore',\n ],\n 'NotAfter' => [\n 'shape' => 'DateTime',\n 'locationName' => 'notAfter',\n ],\n ],\n ],\n 'InstanceStatusEventList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'InstanceStatusEvent',\n 'locationName' => 'item',\n ],\n ],\n 'InstanceStatusList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'InstanceStatus',\n 'locationName' => 'item',\n ],\n ],\n 'InstanceStatusSummary' => [\n 'type' => 'structure',\n 'members' => [\n 'Status' => [\n 'shape' => 'SummaryStatus',\n 'locationName' => 'status',\n ],\n 'Details' => [\n 'shape' => 'InstanceStatusDetailsList',\n 'locationName' => 'details',\n ],\n ],\n ],\n 'InstanceType' => [\n 'type' => 'string',\n 'enum' => [\n 't1.micro',\n 'm1.small',\n 'm1.medium',\n 'm1.large',\n 'm1.xlarge',\n 'm3.medium',\n 'm3.large',\n 'm3.xlarge',\n 'm3.2xlarge',\n 't2.micro',\n 't2.small',\n 't2.medium',\n 'm2.xlarge',\n 'm2.2xlarge',\n 'm2.4xlarge',\n 'cr1.8xlarge',\n 'i2.xlarge',\n 'i2.2xlarge',\n 'i2.4xlarge',\n 'i2.8xlarge',\n 'hi1.4xlarge',\n 'hs1.8xlarge',\n 'c1.medium',\n 'c1.xlarge',\n 'c3.large',\n 'c3.xlarge',\n 'c3.2xlarge',\n 'c3.4xlarge',\n 'c3.8xlarge',\n 'c4.large',\n 'c4.xlarge',\n 'c4.2xlarge',\n 'c4.4xlarge',\n 'c4.8xlarge',\n 'cc1.4xlarge',\n 'cc2.8xlarge',\n 'g2.2xlarge',\n 'cg1.4xlarge',\n 'r3.large',\n 'r3.xlarge',\n 'r3.2xlarge',\n 'r3.4xlarge',\n 'r3.8xlarge',\n ],\n ],\n 'InstanceTypeList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'InstanceType',\n ],\n ],\n 'Integer' => [\n 'type' => 'integer',\n ],\n 'InternetGateway' => [\n 'type' => 'structure',\n 'members' => [\n 'InternetGatewayId' => [\n 'shape' => 'String',\n 'locationName' => 'internetGatewayId',\n ],\n 'Attachments' => [\n 'shape' => 'InternetGatewayAttachmentList',\n 'locationName' => 'attachmentSet',\n ],\n 'Tags' => [\n 'shape' => 'TagList',\n 'locationName' => 'tagSet',\n ],\n ],\n ],\n 'InternetGatewayAttachment' => [\n 'type' => 'structure',\n 'members' => [\n 'VpcId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcId',\n ],\n 'State' => [\n 'shape' => 'AttachmentStatus',\n 'locationName' => 'state',\n ],\n ],\n ],\n 'InternetGatewayAttachmentList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'InternetGatewayAttachment',\n 'locationName' => 'item',\n ],\n ],\n 'InternetGatewayList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'InternetGateway',\n 'locationName' => 'item',\n ],\n ],\n 'IpPermission' => [\n 'type' => 'structure',\n 'members' => [\n 'IpProtocol' => [\n 'shape' => 'String',\n 'locationName' => 'ipProtocol',\n ],\n 'FromPort' => [\n 'shape' => 'Integer',\n 'locationName' => 'fromPort',\n ],\n 'ToPort' => [\n 'shape' => 'Integer',\n 'locationName' => 'toPort',\n ],\n 'UserIdGroupPairs' => [\n 'shape' => 'UserIdGroupPairList',\n 'locationName' => 'groups',\n ],\n 'IpRanges' => [\n 'shape' => 'IpRangeList',\n 'locationName' => 'ipRanges',\n ],\n ],\n ],\n 'IpPermissionList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'IpPermission',\n 'locationName' => 'item',\n ],\n ],\n 'IpRange' => [\n 'type' => 'structure',\n 'members' => [\n 'CidrIp' => [\n 'shape' => 'String',\n 'locationName' => 'cidrIp',\n ],\n ],\n ],\n 'IpRangeList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'IpRange',\n 'locationName' => 'item',\n ],\n ],\n 'KeyNameStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'KeyName',\n ],\n ],\n 'KeyPair' => [\n 'type' => 'structure',\n 'members' => [\n 'KeyName' => [\n 'shape' => 'String',\n 'locationName' => 'keyName',\n ],\n 'KeyFingerprint' => [\n 'shape' => 'String',\n 'locationName' => 'keyFingerprint',\n ],\n 'KeyMaterial' => [\n 'shape' => 'String',\n 'locationName' => 'keyMaterial',\n ],\n ],\n ],\n 'KeyPairInfo' => [\n 'type' => 'structure',\n 'members' => [\n 'KeyName' => [\n 'shape' => 'String',\n 'locationName' => 'keyName',\n ],\n 'KeyFingerprint' => [\n 'shape' => 'String',\n 'locationName' => 'keyFingerprint',\n ],\n ],\n ],\n 'KeyPairList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'KeyPairInfo',\n 'locationName' => 'item',\n ],\n ],\n 'LaunchPermission' => [\n 'type' => 'structure',\n 'members' => [\n 'UserId' => [\n 'shape' => 'String',\n 'locationName' => 'userId',\n ],\n 'Group' => [\n 'shape' => 'PermissionGroup',\n 'locationName' => 'group',\n ],\n ],\n ],\n 'LaunchPermissionList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'LaunchPermission',\n 'locationName' => 'item',\n ],\n ],\n 'LaunchPermissionModifications' => [\n 'type' => 'structure',\n 'members' => [\n 'Add' => [\n 'shape' => 'LaunchPermissionList',\n ],\n 'Remove' => [\n 'shape' => 'LaunchPermissionList',\n ],\n ],\n ],\n 'LaunchSpecification' => [\n 'type' => 'structure',\n 'members' => [\n 'ImageId' => [\n 'shape' => 'String',\n 'locationName' => 'imageId',\n ],\n 'KeyName' => [\n 'shape' => 'String',\n 'locationName' => 'keyName',\n ],\n 'SecurityGroups' => [\n 'shape' => 'GroupIdentifierList',\n 'locationName' => 'groupSet',\n ],\n 'UserData' => [\n 'shape' => 'String',\n 'locationName' => 'userData',\n ],\n 'AddressingType' => [\n 'shape' => 'String',\n 'locationName' => 'addressingType',\n ],\n 'InstanceType' => [\n 'shape' => 'InstanceType',\n 'locationName' => 'instanceType',\n ],\n 'Placement' => [\n 'shape' => 'SpotPlacement',\n 'locationName' => 'placement',\n ],\n 'KernelId' => [\n 'shape' => 'String',\n 'locationName' => 'kernelId',\n ],\n 'RamdiskId' => [\n 'shape' => 'String',\n 'locationName' => 'ramdiskId',\n ],\n 'BlockDeviceMappings' => [\n 'shape' => 'BlockDeviceMappingList',\n 'locationName' => 'blockDeviceMapping',\n ],\n 'SubnetId' => [\n 'shape' => 'String',\n 'locationName' => 'subnetId',\n ],\n 'NetworkInterfaces' => [\n 'shape' => 'InstanceNetworkInterfaceSpecificationList',\n 'locationName' => 'networkInterfaceSet',\n ],\n 'IamInstanceProfile' => [\n 'shape' => 'IamInstanceProfileSpecification',\n 'locationName' => 'iamInstanceProfile',\n ],\n 'EbsOptimized' => [\n 'shape' => 'Boolean',\n 'locationName' => 'ebsOptimized',\n ],\n 'Monitoring' => [\n 'shape' => 'RunInstancesMonitoringEnabled',\n 'locationName' => 'monitoring',\n ],\n ],\n ],\n 'ListingState' => [\n 'type' => 'string',\n 'enum' => [\n 'available',\n 'sold',\n 'cancelled',\n 'pending',\n ],\n ],\n 'ListingStatus' => [\n 'type' => 'string',\n 'enum' => [\n 'active',\n 'pending',\n 'cancelled',\n 'closed',\n ],\n ],\n 'Long' => [\n 'type' => 'long',\n ],\n 'ModifyImageAttributeRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'ImageId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'ImageId' => [\n 'shape' => 'String',\n ],\n 'Attribute' => [\n 'shape' => 'String',\n ],\n 'OperationType' => [\n 'shape' => 'String',\n ],\n 'UserIds' => [\n 'shape' => 'UserIdStringList',\n 'locationName' => 'UserId',\n ],\n 'UserGroups' => [\n 'shape' => 'UserGroupStringList',\n 'locationName' => 'UserGroup',\n ],\n 'ProductCodes' => [\n 'shape' => 'ProductCodeStringList',\n 'locationName' => 'ProductCode',\n ],\n 'Value' => [\n 'shape' => 'String',\n ],\n 'LaunchPermission' => [\n 'shape' => 'LaunchPermissionModifications',\n ],\n 'Description' => [\n 'shape' => 'AttributeValue',\n ],\n ],\n ],\n 'ModifyInstanceAttributeRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'InstanceId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'InstanceId' => [\n 'shape' => 'String',\n 'locationName' => 'instanceId',\n ],\n 'Attribute' => [\n 'shape' => 'InstanceAttributeName',\n 'locationName' => 'attribute',\n ],\n 'Value' => [\n 'shape' => 'String',\n 'locationName' => 'value',\n ],\n 'BlockDeviceMappings' => [\n 'shape' => 'InstanceBlockDeviceMappingSpecificationList',\n 'locationName' => 'blockDeviceMapping',\n ],\n 'SourceDestCheck' => [\n 'shape' => 'AttributeBooleanValue',\n ],\n 'DisableApiTermination' => [\n 'shape' => 'AttributeBooleanValue',\n 'locationName' => 'disableApiTermination',\n ],\n 'InstanceType' => [\n 'shape' => 'AttributeValue',\n 'locationName' => 'instanceType',\n ],\n 'Kernel' => [\n 'shape' => 'AttributeValue',\n 'locationName' => 'kernel',\n ],\n 'Ramdisk' => [\n 'shape' => 'AttributeValue',\n 'locationName' => 'ramdisk',\n ],\n 'UserData' => [\n 'shape' => 'BlobAttributeValue',\n 'locationName' => 'userData',\n ],\n 'InstanceInitiatedShutdownBehavior' => [\n 'shape' => 'AttributeValue',\n 'locationName' => 'instanceInitiatedShutdownBehavior',\n ],\n 'Groups' => [\n 'shape' => 'GroupIdStringList',\n 'locationName' => 'GroupId',\n ],\n 'EbsOptimized' => [\n 'shape' => 'AttributeBooleanValue',\n 'locationName' => 'ebsOptimized',\n ],\n 'SriovNetSupport' => [\n 'shape' => 'AttributeValue',\n 'locationName' => 'sriovNetSupport',\n ],\n ],\n ],\n 'ModifyNetworkInterfaceAttributeRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'NetworkInterfaceId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'NetworkInterfaceId' => [\n 'shape' => 'String',\n 'locationName' => 'networkInterfaceId',\n ],\n 'Description' => [\n 'shape' => 'AttributeValue',\n 'locationName' => 'description',\n ],\n 'SourceDestCheck' => [\n 'shape' => 'AttributeBooleanValue',\n 'locationName' => 'sourceDestCheck',\n ],\n 'Groups' => [\n 'shape' => 'SecurityGroupIdStringList',\n 'locationName' => 'SecurityGroupId',\n ],\n 'Attachment' => [\n 'shape' => 'NetworkInterfaceAttachmentChanges',\n 'locationName' => 'attachment',\n ],\n ],\n ],\n 'ModifyReservedInstancesRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'ReservedInstancesIds',\n 'TargetConfigurations',\n ],\n 'members' => [\n 'ClientToken' => [\n 'shape' => 'String',\n 'locationName' => 'clientToken',\n ],\n 'ReservedInstancesIds' => [\n 'shape' => 'ReservedInstancesIdStringList',\n 'locationName' => 'ReservedInstancesId',\n ],\n 'TargetConfigurations' => [\n 'shape' => 'ReservedInstancesConfigurationList',\n 'locationName' => 'ReservedInstancesConfigurationSetItemType',\n ],\n ],\n ],\n 'ModifyReservedInstancesResult' => [\n 'type' => 'structure',\n 'members' => [\n 'ReservedInstancesModificationId' => [\n 'shape' => 'String',\n 'locationName' => 'reservedInstancesModificationId',\n ],\n ],\n ],\n 'ModifySnapshotAttributeRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'SnapshotId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'SnapshotId' => [\n 'shape' => 'String',\n ],\n 'Attribute' => [\n 'shape' => 'SnapshotAttributeName',\n ],\n 'OperationType' => [\n 'shape' => 'String',\n ],\n 'UserIds' => [\n 'shape' => 'UserIdStringList',\n 'locationName' => 'UserId',\n ],\n 'GroupNames' => [\n 'shape' => 'GroupNameStringList',\n 'locationName' => 'UserGroup',\n ],\n 'CreateVolumePermission' => [\n 'shape' => 'CreateVolumePermissionModifications',\n ],\n ],\n ],\n 'ModifySubnetAttributeRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'SubnetId',\n ],\n 'members' => [\n 'SubnetId' => [\n 'shape' => 'String',\n 'locationName' => 'subnetId',\n ],\n 'MapPublicIpOnLaunch' => [\n 'shape' => 'AttributeBooleanValue',\n ],\n ],\n ],\n 'ModifyVolumeAttributeRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'VolumeId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VolumeId' => [\n 'shape' => 'String',\n ],\n 'AutoEnableIO' => [\n 'shape' => 'AttributeBooleanValue',\n ],\n ],\n ],\n 'ModifyVpcAttributeRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'VpcId',\n ],\n 'members' => [\n 'VpcId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcId',\n ],\n 'EnableDnsSupport' => [\n 'shape' => 'AttributeBooleanValue',\n ],\n 'EnableDnsHostnames' => [\n 'shape' => 'AttributeBooleanValue',\n ],\n ],\n ],\n 'MonitorInstancesRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'InstanceIds',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'InstanceIds' => [\n 'shape' => 'InstanceIdStringList',\n 'locationName' => 'InstanceId',\n ],\n ],\n ],\n 'MonitorInstancesResult' => [\n 'type' => 'structure',\n 'members' => [\n 'InstanceMonitorings' => [\n 'shape' => 'InstanceMonitoringList',\n 'locationName' => 'instancesSet',\n ],\n ],\n ],\n 'Monitoring' => [\n 'type' => 'structure',\n 'members' => [\n 'State' => [\n 'shape' => 'MonitoringState',\n 'locationName' => 'state',\n ],\n ],\n ],\n 'MonitoringState' => [\n 'type' => 'string',\n 'enum' => [\n 'disabled',\n 'enabled',\n 'pending',\n ],\n ],\n 'NetworkAcl' => [\n 'type' => 'structure',\n 'members' => [\n 'NetworkAclId' => [\n 'shape' => 'String',\n 'locationName' => 'networkAclId',\n ],\n 'VpcId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcId',\n ],\n 'IsDefault' => [\n 'shape' => 'Boolean',\n 'locationName' => 'default',\n ],\n 'Entries' => [\n 'shape' => 'NetworkAclEntryList',\n 'locationName' => 'entrySet',\n ],\n 'Associations' => [\n 'shape' => 'NetworkAclAssociationList',\n 'locationName' => 'associationSet',\n ],\n 'Tags' => [\n 'shape' => 'TagList',\n 'locationName' => 'tagSet',\n ],\n ],\n ],\n 'NetworkAclAssociation' => [\n 'type' => 'structure',\n 'members' => [\n 'NetworkAclAssociationId' => [\n 'shape' => 'String',\n 'locationName' => 'networkAclAssociationId',\n ],\n 'NetworkAclId' => [\n 'shape' => 'String',\n 'locationName' => 'networkAclId',\n ],\n 'SubnetId' => [\n 'shape' => 'String',\n 'locationName' => 'subnetId',\n ],\n ],\n ],\n 'NetworkAclAssociationList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'NetworkAclAssociation',\n 'locationName' => 'item',\n ],\n ],\n 'NetworkAclEntry' => [\n 'type' => 'structure',\n 'members' => [\n 'RuleNumber' => [\n 'shape' => 'Integer',\n 'locationName' => 'ruleNumber',\n ],\n 'Protocol' => [\n 'shape' => 'String',\n 'locationName' => 'protocol',\n ],\n 'RuleAction' => [\n 'shape' => 'RuleAction',\n 'locationName' => 'ruleAction',\n ],\n 'Egress' => [\n 'shape' => 'Boolean',\n 'locationName' => 'egress',\n ],\n 'CidrBlock' => [\n 'shape' => 'String',\n 'locationName' => 'cidrBlock',\n ],\n 'IcmpTypeCode' => [\n 'shape' => 'IcmpTypeCode',\n 'locationName' => 'icmpTypeCode',\n ],\n 'PortRange' => [\n 'shape' => 'PortRange',\n 'locationName' => 'portRange',\n ],\n ],\n ],\n 'NetworkAclEntryList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'NetworkAclEntry',\n 'locationName' => 'item',\n ],\n ],\n 'NetworkAclList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'NetworkAcl',\n 'locationName' => 'item',\n ],\n ],\n 'NetworkInterface' => [\n 'type' => 'structure',\n 'members' => [\n 'NetworkInterfaceId' => [\n 'shape' => 'String',\n 'locationName' => 'networkInterfaceId',\n ],\n 'SubnetId' => [\n 'shape' => 'String',\n 'locationName' => 'subnetId',\n ],\n 'VpcId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcId',\n ],\n 'AvailabilityZone' => [\n 'shape' => 'String',\n 'locationName' => 'availabilityZone',\n ],\n 'Description' => [\n 'shape' => 'String',\n 'locationName' => 'description',\n ],\n 'OwnerId' => [\n 'shape' => 'String',\n 'locationName' => 'ownerId',\n ],\n 'RequesterId' => [\n 'shape' => 'String',\n 'locationName' => 'requesterId',\n ],\n 'RequesterManaged' => [\n 'shape' => 'Boolean',\n 'locationName' => 'requesterManaged',\n ],\n 'Status' => [\n 'shape' => 'NetworkInterfaceStatus',\n 'locationName' => 'status',\n ],\n 'MacAddress' => [\n 'shape' => 'String',\n 'locationName' => 'macAddress',\n ],\n 'PrivateIpAddress' => [\n 'shape' => 'String',\n 'locationName' => 'privateIpAddress',\n ],\n 'PrivateDnsName' => [\n 'shape' => 'String',\n 'locationName' => 'privateDnsName',\n ],\n 'SourceDestCheck' => [\n 'shape' => 'Boolean',\n 'locationName' => 'sourceDestCheck',\n ],\n 'Groups' => [\n 'shape' => 'GroupIdentifierList',\n 'locationName' => 'groupSet',\n ],\n 'Attachment' => [\n 'shape' => 'NetworkInterfaceAttachment',\n 'locationName' => 'attachment',\n ],\n 'Association' => [\n 'shape' => 'NetworkInterfaceAssociation',\n 'locationName' => 'association',\n ],\n 'TagSet' => [\n 'shape' => 'TagList',\n 'locationName' => 'tagSet',\n ],\n 'PrivateIpAddresses' => [\n 'shape' => 'NetworkInterfacePrivateIpAddressList',\n 'locationName' => 'privateIpAddressesSet',\n ],\n ],\n ],\n 'NetworkInterfaceAssociation' => [\n 'type' => 'structure',\n 'members' => [\n 'PublicIp' => [\n 'shape' => 'String',\n 'locationName' => 'publicIp',\n ],\n 'PublicDnsName' => [\n 'shape' => 'String',\n 'locationName' => 'publicDnsName',\n ],\n 'IpOwnerId' => [\n 'shape' => 'String',\n 'locationName' => 'ipOwnerId',\n ],\n 'AllocationId' => [\n 'shape' => 'String',\n 'locationName' => 'allocationId',\n ],\n 'AssociationId' => [\n 'shape' => 'String',\n 'locationName' => 'associationId',\n ],\n ],\n ],\n 'NetworkInterfaceAttachment' => [\n 'type' => 'structure',\n 'members' => [\n 'AttachmentId' => [\n 'shape' => 'String',\n 'locationName' => 'attachmentId',\n ],\n 'InstanceId' => [\n 'shape' => 'String',\n 'locationName' => 'instanceId',\n ],\n 'InstanceOwnerId' => [\n 'shape' => 'String',\n 'locationName' => 'instanceOwnerId',\n ],\n 'DeviceIndex' => [\n 'shape' => 'Integer',\n 'locationName' => 'deviceIndex',\n ],\n 'Status' => [\n 'shape' => 'AttachmentStatus',\n 'locationName' => 'status',\n ],\n 'AttachTime' => [\n 'shape' => 'DateTime',\n 'locationName' => 'attachTime',\n ],\n 'DeleteOnTermination' => [\n 'shape' => 'Boolean',\n 'locationName' => 'deleteOnTermination',\n ],\n ],\n ],\n 'NetworkInterfaceAttachmentChanges' => [\n 'type' => 'structure',\n 'members' => [\n 'AttachmentId' => [\n 'shape' => 'String',\n 'locationName' => 'attachmentId',\n ],\n 'DeleteOnTermination' => [\n 'shape' => 'Boolean',\n 'locationName' => 'deleteOnTermination',\n ],\n ],\n ],\n 'NetworkInterfaceAttribute' => [\n 'type' => 'string',\n 'enum' => [\n 'description',\n 'groupSet',\n 'sourceDestCheck',\n 'attachment',\n ],\n ],\n 'NetworkInterfaceIdList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'item',\n ],\n ],\n 'NetworkInterfaceList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'NetworkInterface',\n 'locationName' => 'item',\n ],\n ],\n 'NetworkInterfacePrivateIpAddress' => [\n 'type' => 'structure',\n 'members' => [\n 'PrivateIpAddress' => [\n 'shape' => 'String',\n 'locationName' => 'privateIpAddress',\n ],\n 'PrivateDnsName' => [\n 'shape' => 'String',\n 'locationName' => 'privateDnsName',\n ],\n 'Primary' => [\n 'shape' => 'Boolean',\n 'locationName' => 'primary',\n ],\n 'Association' => [\n 'shape' => 'NetworkInterfaceAssociation',\n 'locationName' => 'association',\n ],\n ],\n ],\n 'NetworkInterfacePrivateIpAddressList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'NetworkInterfacePrivateIpAddress',\n 'locationName' => 'item',\n ],\n ],\n 'NetworkInterfaceStatus' => [\n 'type' => 'string',\n 'enum' => [\n 'available',\n 'attaching',\n 'in-use',\n 'detaching',\n ],\n ],\n 'OfferingTypeValues' => [\n 'type' => 'string',\n 'enum' => [\n 'Heavy Utilization',\n 'Medium Utilization',\n 'Light Utilization',\n ],\n ],\n 'OwnerStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'Owner',\n ],\n ],\n 'PermissionGroup' => [\n 'type' => 'string',\n 'enum' => [\n 'all',\n ],\n ],\n 'Placement' => [\n 'type' => 'structure',\n 'members' => [\n 'AvailabilityZone' => [\n 'shape' => 'String',\n 'locationName' => 'availabilityZone',\n ],\n 'GroupName' => [\n 'shape' => 'String',\n 'locationName' => 'groupName',\n ],\n 'Tenancy' => [\n 'shape' => 'Tenancy',\n 'locationName' => 'tenancy',\n ],\n ],\n ],\n 'PlacementGroup' => [\n 'type' => 'structure',\n 'members' => [\n 'GroupName' => [\n 'shape' => 'String',\n 'locationName' => 'groupName',\n ],\n 'Strategy' => [\n 'shape' => 'PlacementStrategy',\n 'locationName' => 'strategy',\n ],\n 'State' => [\n 'shape' => 'PlacementGroupState',\n 'locationName' => 'state',\n ],\n ],\n ],\n 'PlacementGroupList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'PlacementGroup',\n 'locationName' => 'item',\n ],\n ],\n 'PlacementGroupState' => [\n 'type' => 'string',\n 'enum' => [\n 'pending',\n 'available',\n 'deleting',\n 'deleted',\n ],\n ],\n 'PlacementGroupStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n ],\n ],\n 'PlacementStrategy' => [\n 'type' => 'string',\n 'enum' => [\n 'cluster',\n ],\n ],\n 'PlatformValues' => [\n 'type' => 'string',\n 'enum' => [\n 'Windows',\n ],\n ],\n 'PortRange' => [\n 'type' => 'structure',\n 'members' => [\n 'From' => [\n 'shape' => 'Integer',\n 'locationName' => 'from',\n ],\n 'To' => [\n 'shape' => 'Integer',\n 'locationName' => 'to',\n ],\n ],\n ],\n 'PriceSchedule' => [\n 'type' => 'structure',\n 'members' => [\n 'Term' => [\n 'shape' => 'Long',\n 'locationName' => 'term',\n ],\n 'Price' => [\n 'shape' => 'Double',\n 'locationName' => 'price',\n ],\n 'CurrencyCode' => [\n 'shape' => 'CurrencyCodeValues',\n 'locationName' => 'currencyCode',\n ],\n 'Active' => [\n 'shape' => 'Boolean',\n 'locationName' => 'active',\n ],\n ],\n ],\n 'PriceScheduleList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'PriceSchedule',\n 'locationName' => 'item',\n ],\n ],\n 'PriceScheduleSpecification' => [\n 'type' => 'structure',\n 'members' => [\n 'Term' => [\n 'shape' => 'Long',\n 'locationName' => 'term',\n ],\n 'Price' => [\n 'shape' => 'Double',\n 'locationName' => 'price',\n ],\n 'CurrencyCode' => [\n 'shape' => 'CurrencyCodeValues',\n 'locationName' => 'currencyCode',\n ],\n ],\n ],\n 'PriceScheduleSpecificationList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'PriceScheduleSpecification',\n 'locationName' => 'item',\n ],\n ],\n 'PricingDetail' => [\n 'type' => 'structure',\n 'members' => [\n 'Price' => [\n 'shape' => 'Double',\n 'locationName' => 'price',\n ],\n 'Count' => [\n 'shape' => 'Integer',\n 'locationName' => 'count',\n ],\n ],\n ],\n 'PricingDetailsList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'PricingDetail',\n 'locationName' => 'item',\n ],\n ],\n 'PrivateIpAddressSpecification' => [\n 'type' => 'structure',\n 'required' => [\n 'PrivateIpAddress',\n ],\n 'members' => [\n 'PrivateIpAddress' => [\n 'shape' => 'String',\n 'locationName' => 'privateIpAddress',\n ],\n 'Primary' => [\n 'shape' => 'Boolean',\n 'locationName' => 'primary',\n ],\n ],\n ],\n 'PrivateIpAddressSpecificationList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'PrivateIpAddressSpecification',\n 'locationName' => 'item',\n ],\n ],\n 'PrivateIpAddressStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'PrivateIpAddress',\n ],\n ],\n 'ProductCode' => [\n 'type' => 'structure',\n 'members' => [\n 'ProductCodeId' => [\n 'shape' => 'String',\n 'locationName' => 'productCode',\n ],\n 'ProductCodeType' => [\n 'shape' => 'ProductCodeValues',\n 'locationName' => 'type',\n ],\n ],\n ],\n 'ProductCodeList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'ProductCode',\n 'locationName' => 'item',\n ],\n ],\n 'ProductCodeStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'ProductCode',\n ],\n ],\n 'ProductCodeValues' => [\n 'type' => 'string',\n 'enum' => [\n 'devpay',\n 'marketplace',\n ],\n ],\n 'ProductDescriptionList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n ],\n ],\n 'PropagatingVgw' => [\n 'type' => 'structure',\n 'members' => [\n 'GatewayId' => [\n 'shape' => 'String',\n 'locationName' => 'gatewayId',\n ],\n ],\n ],\n 'PropagatingVgwList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'PropagatingVgw',\n 'locationName' => 'item',\n ],\n ],\n 'PublicIpStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'PublicIp',\n ],\n ],\n 'PurchaseReservedInstancesOfferingRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'ReservedInstancesOfferingId',\n 'InstanceCount',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'ReservedInstancesOfferingId' => [\n 'shape' => 'String',\n ],\n 'InstanceCount' => [\n 'shape' => 'Integer',\n ],\n 'LimitPrice' => [\n 'shape' => 'ReservedInstanceLimitPrice',\n 'locationName' => 'limitPrice',\n ],\n ],\n ],\n 'PurchaseReservedInstancesOfferingResult' => [\n 'type' => 'structure',\n 'members' => [\n 'ReservedInstancesId' => [\n 'shape' => 'String',\n 'locationName' => 'reservedInstancesId',\n ],\n ],\n ],\n 'RIProductDescription' => [\n 'type' => 'string',\n 'enum' => [\n 'Linux/UNIX',\n 'Linux/UNIX (Amazon VPC]',\n 'Windows',\n 'Windows (Amazon VPC]',\n ],\n ],\n 'ReasonCodesList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'ReportInstanceReasonCodes',\n 'locationName' => 'item',\n ],\n ],\n 'RebootInstancesRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'InstanceIds',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'InstanceIds' => [\n 'shape' => 'InstanceIdStringList',\n 'locationName' => 'InstanceId',\n ],\n ],\n ],\n 'RecurringCharge' => [\n 'type' => 'structure',\n 'members' => [\n 'Frequency' => [\n 'shape' => 'RecurringChargeFrequency',\n 'locationName' => 'frequency',\n ],\n 'Amount' => [\n 'shape' => 'Double',\n 'locationName' => 'amount',\n ],\n ],\n ],\n 'RecurringChargeFrequency' => [\n 'type' => 'string',\n 'enum' => [\n 'Hourly',\n ],\n ],\n 'RecurringChargesList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'RecurringCharge',\n 'locationName' => 'item',\n ],\n ],\n 'Region' => [\n 'type' => 'structure',\n 'members' => [\n 'RegionName' => [\n 'shape' => 'String',\n 'locationName' => 'regionName',\n ],\n 'Endpoint' => [\n 'shape' => 'String',\n 'locationName' => 'regionEndpoint',\n ],\n ],\n ],\n 'RegionList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'Region',\n 'locationName' => 'item',\n ],\n ],\n 'RegionNameStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'RegionName',\n ],\n ],\n 'RegisterImageRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'Name',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'ImageLocation' => [\n 'shape' => 'String',\n ],\n 'Name' => [\n 'shape' => 'String',\n 'locationName' => 'name',\n ],\n 'Description' => [\n 'shape' => 'String',\n 'locationName' => 'description',\n ],\n 'Architecture' => [\n 'shape' => 'ArchitectureValues',\n 'locationName' => 'architecture',\n ],\n 'KernelId' => [\n 'shape' => 'String',\n 'locationName' => 'kernelId',\n ],\n 'RamdiskId' => [\n 'shape' => 'String',\n 'locationName' => 'ramdiskId',\n ],\n 'RootDeviceName' => [\n 'shape' => 'String',\n 'locationName' => 'rootDeviceName',\n ],\n 'BlockDeviceMappings' => [\n 'shape' => 'BlockDeviceMappingRequestList',\n 'locationName' => 'BlockDeviceMapping',\n ],\n 'VirtualizationType' => [\n 'shape' => 'String',\n 'locationName' => 'virtualizationType',\n ],\n 'SriovNetSupport' => [\n 'shape' => 'String',\n 'locationName' => 'sriovNetSupport',\n ],\n ],\n ],\n 'RegisterImageResult' => [\n 'type' => 'structure',\n 'members' => [\n 'ImageId' => [\n 'shape' => 'String',\n 'locationName' => 'imageId',\n ],\n ],\n ],\n 'RejectVpcPeeringConnectionRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'VpcPeeringConnectionId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'VpcPeeringConnectionId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcPeeringConnectionId',\n ],\n ],\n ],\n 'RejectVpcPeeringConnectionResult' => [\n 'type' => 'structure',\n 'members' => [\n 'Return' => [\n 'shape' => 'Boolean',\n 'locationName' => 'return',\n ],\n ],\n ],\n 'ReleaseAddressRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'PublicIp' => [\n 'shape' => 'String',\n ],\n 'AllocationId' => [\n 'shape' => 'String',\n ],\n ],\n ],\n 'ReplaceNetworkAclAssociationRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'AssociationId',\n 'NetworkAclId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'AssociationId' => [\n 'shape' => 'String',\n 'locationName' => 'associationId',\n ],\n 'NetworkAclId' => [\n 'shape' => 'String',\n 'locationName' => 'networkAclId',\n ],\n ],\n ],\n 'ReplaceNetworkAclAssociationResult' => [\n 'type' => 'structure',\n 'members' => [\n 'NewAssociationId' => [\n 'shape' => 'String',\n 'locationName' => 'newAssociationId',\n ],\n ],\n ],\n 'ReplaceNetworkAclEntryRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'NetworkAclId',\n 'RuleNumber',\n 'Protocol',\n 'RuleAction',\n 'Egress',\n 'CidrBlock',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'NetworkAclId' => [\n 'shape' => 'String',\n 'locationName' => 'networkAclId',\n ],\n 'RuleNumber' => [\n 'shape' => 'Integer',\n 'locationName' => 'ruleNumber',\n ],\n 'Protocol' => [\n 'shape' => 'String',\n 'locationName' => 'protocol',\n ],\n 'RuleAction' => [\n 'shape' => 'RuleAction',\n 'locationName' => 'ruleAction',\n ],\n 'Egress' => [\n 'shape' => 'Boolean',\n 'locationName' => 'egress',\n ],\n 'CidrBlock' => [\n 'shape' => 'String',\n 'locationName' => 'cidrBlock',\n ],\n 'IcmpTypeCode' => [\n 'shape' => 'IcmpTypeCode',\n 'locationName' => 'Icmp',\n ],\n 'PortRange' => [\n 'shape' => 'PortRange',\n 'locationName' => 'portRange',\n ],\n ],\n ],\n 'ReplaceRouteRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'RouteTableId',\n 'DestinationCidrBlock',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'RouteTableId' => [\n 'shape' => 'String',\n 'locationName' => 'routeTableId',\n ],\n 'DestinationCidrBlock' => [\n 'shape' => 'String',\n 'locationName' => 'destinationCidrBlock',\n ],\n 'GatewayId' => [\n 'shape' => 'String',\n 'locationName' => 'gatewayId',\n ],\n 'InstanceId' => [\n 'shape' => 'String',\n 'locationName' => 'instanceId',\n ],\n 'NetworkInterfaceId' => [\n 'shape' => 'String',\n 'locationName' => 'networkInterfaceId',\n ],\n 'VpcPeeringConnectionId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcPeeringConnectionId',\n ],\n ],\n ],\n 'ReplaceRouteTableAssociationRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'AssociationId',\n 'RouteTableId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'AssociationId' => [\n 'shape' => 'String',\n 'locationName' => 'associationId',\n ],\n 'RouteTableId' => [\n 'shape' => 'String',\n 'locationName' => 'routeTableId',\n ],\n ],\n ],\n 'ReplaceRouteTableAssociationResult' => [\n 'type' => 'structure',\n 'members' => [\n 'NewAssociationId' => [\n 'shape' => 'String',\n 'locationName' => 'newAssociationId',\n ],\n ],\n ],\n 'ReportInstanceReasonCodes' => [\n 'type' => 'string',\n 'enum' => [\n 'instance-stuck-in-state',\n 'unresponsive',\n 'not-accepting-credentials',\n 'password-not-available',\n 'performance-network',\n 'performance-instance-store',\n 'performance-ebs-volume',\n 'performance-other',\n 'other',\n ],\n ],\n 'ReportInstanceStatusRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'Instances',\n 'Status',\n 'ReasonCodes',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'Instances' => [\n 'shape' => 'InstanceIdStringList',\n 'locationName' => 'instanceId',\n ],\n 'Status' => [\n 'shape' => 'ReportStatusType',\n 'locationName' => 'status',\n ],\n 'StartTime' => [\n 'shape' => 'DateTime',\n 'locationName' => 'startTime',\n ],\n 'EndTime' => [\n 'shape' => 'DateTime',\n 'locationName' => 'endTime',\n ],\n 'ReasonCodes' => [\n 'shape' => 'ReasonCodesList',\n 'locationName' => 'reasonCode',\n ],\n 'Description' => [\n 'shape' => 'String',\n 'locationName' => 'description',\n ],\n ],\n ],\n 'ReportStatusType' => [\n 'type' => 'string',\n 'enum' => [\n 'ok',\n 'impaired',\n ],\n ],\n 'RequestSpotInstancesRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'SpotPrice',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'SpotPrice' => [\n 'shape' => 'String',\n 'locationName' => 'spotPrice',\n ],\n 'InstanceCount' => [\n 'shape' => 'Integer',\n 'locationName' => 'instanceCount',\n ],\n 'Type' => [\n 'shape' => 'SpotInstanceType',\n 'locationName' => 'type',\n ],\n 'ValidFrom' => [\n 'shape' => 'DateTime',\n 'locationName' => 'validFrom',\n ],\n 'ValidUntil' => [\n 'shape' => 'DateTime',\n 'locationName' => 'validUntil',\n ],\n 'LaunchGroup' => [\n 'shape' => 'String',\n 'locationName' => 'launchGroup',\n ],\n 'AvailabilityZoneGroup' => [\n 'shape' => 'String',\n 'locationName' => 'availabilityZoneGroup',\n ],\n 'LaunchSpecification' => [\n 'shape' => 'RequestSpotLaunchSpecification',\n ],\n ],\n ],\n 'RequestSpotInstancesResult' => [\n 'type' => 'structure',\n 'members' => [\n 'SpotInstanceRequests' => [\n 'shape' => 'SpotInstanceRequestList',\n 'locationName' => 'spotInstanceRequestSet',\n ],\n ],\n ],\n 'Reservation' => [\n 'type' => 'structure',\n 'members' => [\n 'ReservationId' => [\n 'shape' => 'String',\n 'locationName' => 'reservationId',\n ],\n 'OwnerId' => [\n 'shape' => 'String',\n 'locationName' => 'ownerId',\n ],\n 'RequesterId' => [\n 'shape' => 'String',\n 'locationName' => 'requesterId',\n ],\n 'Groups' => [\n 'shape' => 'GroupIdentifierList',\n 'locationName' => 'groupSet',\n ],\n 'Instances' => [\n 'shape' => 'InstanceList',\n 'locationName' => 'instancesSet',\n ],\n ],\n ],\n 'ReservationList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'Reservation',\n 'locationName' => 'item',\n ],\n ],\n 'ReservedInstanceLimitPrice' => [\n 'type' => 'structure',\n 'members' => [\n 'Amount' => [\n 'shape' => 'Double',\n 'locationName' => 'amount',\n ],\n 'CurrencyCode' => [\n 'shape' => 'CurrencyCodeValues',\n 'locationName' => 'currencyCode',\n ],\n ],\n ],\n 'ReservedInstanceState' => [\n 'type' => 'string',\n 'enum' => [\n 'payment-pending',\n 'active',\n 'payment-failed',\n 'retired',\n ],\n ],\n 'ReservedInstances' => [\n 'type' => 'structure',\n 'members' => [\n 'ReservedInstancesId' => [\n 'shape' => 'String',\n 'locationName' => 'reservedInstancesId',\n ],\n 'InstanceType' => [\n 'shape' => 'InstanceType',\n 'locationName' => 'instanceType',\n ],\n 'AvailabilityZone' => [\n 'shape' => 'String',\n 'locationName' => 'availabilityZone',\n ],\n 'Start' => [\n 'shape' => 'DateTime',\n 'locationName' => 'start',\n ],\n 'End' => [\n 'shape' => 'DateTime',\n 'locationName' => 'end',\n ],\n 'Duration' => [\n 'shape' => 'Long',\n 'locationName' => 'duration',\n ],\n 'UsagePrice' => [\n 'shape' => 'Float',\n 'locationName' => 'usagePrice',\n ],\n 'FixedPrice' => [\n 'shape' => 'Float',\n 'locationName' => 'fixedPrice',\n ],\n 'InstanceCount' => [\n 'shape' => 'Integer',\n 'locationName' => 'instanceCount',\n ],\n 'ProductDescription' => [\n 'shape' => 'RIProductDescription',\n 'locationName' => 'productDescription',\n ],\n 'State' => [\n 'shape' => 'ReservedInstanceState',\n 'locationName' => 'state',\n ],\n 'Tags' => [\n 'shape' => 'TagList',\n 'locationName' => 'tagSet',\n ],\n 'InstanceTenancy' => [\n 'shape' => 'Tenancy',\n 'locationName' => 'instanceTenancy',\n ],\n 'CurrencyCode' => [\n 'shape' => 'CurrencyCodeValues',\n 'locationName' => 'currencyCode',\n ],\n 'OfferingType' => [\n 'shape' => 'OfferingTypeValues',\n 'locationName' => 'offeringType',\n ],\n 'RecurringCharges' => [\n 'shape' => 'RecurringChargesList',\n 'locationName' => 'recurringCharges',\n ],\n ],\n ],\n 'ReservedInstancesConfiguration' => [\n 'type' => 'structure',\n 'members' => [\n 'AvailabilityZone' => [\n 'shape' => 'String',\n 'locationName' => 'availabilityZone',\n ],\n 'Platform' => [\n 'shape' => 'String',\n 'locationName' => 'platform',\n ],\n 'InstanceCount' => [\n 'shape' => 'Integer',\n 'locationName' => 'instanceCount',\n ],\n 'InstanceType' => [\n 'shape' => 'InstanceType',\n 'locationName' => 'instanceType',\n ],\n ],\n ],\n 'ReservedInstancesConfigurationList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'ReservedInstancesConfiguration',\n 'locationName' => 'item',\n ],\n ],\n 'ReservedInstancesId' => [\n 'type' => 'structure',\n 'members' => [\n 'ReservedInstancesId' => [\n 'shape' => 'String',\n 'locationName' => 'reservedInstancesId',\n ],\n ],\n ],\n 'ReservedInstancesIdStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'ReservedInstancesId',\n ],\n ],\n 'ReservedInstancesList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'ReservedInstances',\n 'locationName' => 'item',\n ],\n ],\n 'ReservedInstancesListing' => [\n 'type' => 'structure',\n 'members' => [\n 'ReservedInstancesListingId' => [\n 'shape' => 'String',\n 'locationName' => 'reservedInstancesListingId',\n ],\n 'ReservedInstancesId' => [\n 'shape' => 'String',\n 'locationName' => 'reservedInstancesId',\n ],\n 'CreateDate' => [\n 'shape' => 'DateTime',\n 'locationName' => 'createDate',\n ],\n 'UpdateDate' => [\n 'shape' => 'DateTime',\n 'locationName' => 'updateDate',\n ],\n 'Status' => [\n 'shape' => 'ListingStatus',\n 'locationName' => 'status',\n ],\n 'StatusMessage' => [\n 'shape' => 'String',\n 'locationName' => 'statusMessage',\n ],\n 'InstanceCounts' => [\n 'shape' => 'InstanceCountList',\n 'locationName' => 'instanceCounts',\n ],\n 'PriceSchedules' => [\n 'shape' => 'PriceScheduleList',\n 'locationName' => 'priceSchedules',\n ],\n 'Tags' => [\n 'shape' => 'TagList',\n 'locationName' => 'tagSet',\n ],\n 'ClientToken' => [\n 'shape' => 'String',\n 'locationName' => 'clientToken',\n ],\n ],\n ],\n 'ReservedInstancesListingList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'ReservedInstancesListing',\n 'locationName' => 'item',\n ],\n ],\n 'ReservedInstancesModification' => [\n 'type' => 'structure',\n 'members' => [\n 'ReservedInstancesModificationId' => [\n 'shape' => 'String',\n 'locationName' => 'reservedInstancesModificationId',\n ],\n 'ReservedInstancesIds' => [\n 'shape' => 'ReservedIntancesIds',\n 'locationName' => 'reservedInstancesSet',\n ],\n 'ModificationResults' => [\n 'shape' => 'ReservedInstancesModificationResultList',\n 'locationName' => 'modificationResultSet',\n ],\n 'CreateDate' => [\n 'shape' => 'DateTime',\n 'locationName' => 'createDate',\n ],\n 'UpdateDate' => [\n 'shape' => 'DateTime',\n 'locationName' => 'updateDate',\n ],\n 'EffectiveDate' => [\n 'shape' => 'DateTime',\n 'locationName' => 'effectiveDate',\n ],\n 'Status' => [\n 'shape' => 'String',\n 'locationName' => 'status',\n ],\n 'StatusMessage' => [\n 'shape' => 'String',\n 'locationName' => 'statusMessage',\n ],\n 'ClientToken' => [\n 'shape' => 'String',\n 'locationName' => 'clientToken',\n ],\n ],\n ],\n 'ReservedInstancesModificationIdStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'ReservedInstancesModificationId',\n ],\n ],\n 'ReservedInstancesModificationList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'ReservedInstancesModification',\n 'locationName' => 'item',\n ],\n ],\n 'ReservedInstancesModificationResult' => [\n 'type' => 'structure',\n 'members' => [\n 'ReservedInstancesId' => [\n 'shape' => 'String',\n 'locationName' => 'reservedInstancesId',\n ],\n 'TargetConfiguration' => [\n 'shape' => 'ReservedInstancesConfiguration',\n 'locationName' => 'targetConfiguration',\n ],\n ],\n ],\n 'ReservedInstancesModificationResultList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'ReservedInstancesModificationResult',\n 'locationName' => 'item',\n ],\n ],\n 'ReservedInstancesOffering' => [\n 'type' => 'structure',\n 'members' => [\n 'ReservedInstancesOfferingId' => [\n 'shape' => 'String',\n 'locationName' => 'reservedInstancesOfferingId',\n ],\n 'InstanceType' => [\n 'shape' => 'InstanceType',\n 'locationName' => 'instanceType',\n ],\n 'AvailabilityZone' => [\n 'shape' => 'String',\n 'locationName' => 'availabilityZone',\n ],\n 'Duration' => [\n 'shape' => 'Long',\n 'locationName' => 'duration',\n ],\n 'UsagePrice' => [\n 'shape' => 'Float',\n 'locationName' => 'usagePrice',\n ],\n 'FixedPrice' => [\n 'shape' => 'Float',\n 'locationName' => 'fixedPrice',\n ],\n 'ProductDescription' => [\n 'shape' => 'RIProductDescription',\n 'locationName' => 'productDescription',\n ],\n 'InstanceTenancy' => [\n 'shape' => 'Tenancy',\n 'locationName' => 'instanceTenancy',\n ],\n 'CurrencyCode' => [\n 'shape' => 'CurrencyCodeValues',\n 'locationName' => 'currencyCode',\n ],\n 'OfferingType' => [\n 'shape' => 'OfferingTypeValues',\n 'locationName' => 'offeringType',\n ],\n 'RecurringCharges' => [\n 'shape' => 'RecurringChargesList',\n 'locationName' => 'recurringCharges',\n ],\n 'Marketplace' => [\n 'shape' => 'Boolean',\n 'locationName' => 'marketplace',\n ],\n 'PricingDetails' => [\n 'shape' => 'PricingDetailsList',\n 'locationName' => 'pricingDetailsSet',\n ],\n ],\n ],\n 'ReservedInstancesOfferingIdStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n ],\n ],\n 'ReservedInstancesOfferingList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'ReservedInstancesOffering',\n 'locationName' => 'item',\n ],\n ],\n 'ReservedIntancesIds' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'ReservedInstancesId',\n 'locationName' => 'item',\n ],\n ],\n 'ResetImageAttributeName' => [\n 'type' => 'string',\n 'enum' => [\n 'launchPermission',\n ],\n ],\n 'ResetImageAttributeRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'ImageId',\n 'Attribute',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'ImageId' => [\n 'shape' => 'String',\n ],\n 'Attribute' => [\n 'shape' => 'ResetImageAttributeName',\n ],\n ],\n ],\n 'ResetInstanceAttributeRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'InstanceId',\n 'Attribute',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'InstanceId' => [\n 'shape' => 'String',\n 'locationName' => 'instanceId',\n ],\n 'Attribute' => [\n 'shape' => 'InstanceAttributeName',\n 'locationName' => 'attribute',\n ],\n ],\n ],\n 'ResetNetworkInterfaceAttributeRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'NetworkInterfaceId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'NetworkInterfaceId' => [\n 'shape' => 'String',\n 'locationName' => 'networkInterfaceId',\n ],\n 'SourceDestCheck' => [\n 'shape' => 'String',\n 'locationName' => 'sourceDestCheck',\n ],\n ],\n ],\n 'ResetSnapshotAttributeRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'SnapshotId',\n 'Attribute',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'SnapshotId' => [\n 'shape' => 'String',\n ],\n 'Attribute' => [\n 'shape' => 'SnapshotAttributeName',\n ],\n ],\n ],\n 'ResourceIdList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n ],\n ],\n 'ResourceType' => [\n 'type' => 'string',\n 'enum' => [\n 'customer-gateway',\n 'dhcp-options',\n 'image',\n 'instance',\n 'internet-gateway',\n 'network-acl',\n 'network-interface',\n 'reserved-instances',\n 'route-table',\n 'snapshot',\n 'spot-instances-request',\n 'subnet',\n 'security-group',\n 'volume',\n 'vpc',\n 'vpn-connection',\n 'vpn-gateway',\n ],\n ],\n 'RestorableByStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n ],\n ],\n 'RevokeSecurityGroupEgressRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'GroupId',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'GroupId' => [\n 'shape' => 'String',\n 'locationName' => 'groupId',\n ],\n 'SourceSecurityGroupName' => [\n 'shape' => 'String',\n 'locationName' => 'sourceSecurityGroupName',\n ],\n 'SourceSecurityGroupOwnerId' => [\n 'shape' => 'String',\n 'locationName' => 'sourceSecurityGroupOwnerId',\n ],\n 'IpProtocol' => [\n 'shape' => 'String',\n 'locationName' => 'ipProtocol',\n ],\n 'FromPort' => [\n 'shape' => 'Integer',\n 'locationName' => 'fromPort',\n ],\n 'ToPort' => [\n 'shape' => 'Integer',\n 'locationName' => 'toPort',\n ],\n 'CidrIp' => [\n 'shape' => 'String',\n 'locationName' => 'cidrIp',\n ],\n 'IpPermissions' => [\n 'shape' => 'IpPermissionList',\n 'locationName' => 'ipPermissions',\n ],\n ],\n ],\n 'RevokeSecurityGroupIngressRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'GroupName' => [\n 'shape' => 'String',\n ],\n 'GroupId' => [\n 'shape' => 'String',\n ],\n 'SourceSecurityGroupName' => [\n 'shape' => 'String',\n ],\n 'SourceSecurityGroupOwnerId' => [\n 'shape' => 'String',\n ],\n 'IpProtocol' => [\n 'shape' => 'String',\n ],\n 'FromPort' => [\n 'shape' => 'Integer',\n ],\n 'ToPort' => [\n 'shape' => 'Integer',\n ],\n 'CidrIp' => [\n 'shape' => 'String',\n ],\n 'IpPermissions' => [\n 'shape' => 'IpPermissionList',\n ],\n ],\n ],\n 'Route' => [\n 'type' => 'structure',\n 'members' => [\n 'DestinationCidrBlock' => [\n 'shape' => 'String',\n 'locationName' => 'destinationCidrBlock',\n ],\n 'GatewayId' => [\n 'shape' => 'String',\n 'locationName' => 'gatewayId',\n ],\n 'InstanceId' => [\n 'shape' => 'String',\n 'locationName' => 'instanceId',\n ],\n 'InstanceOwnerId' => [\n 'shape' => 'String',\n 'locationName' => 'instanceOwnerId',\n ],\n 'NetworkInterfaceId' => [\n 'shape' => 'String',\n 'locationName' => 'networkInterfaceId',\n ],\n 'VpcPeeringConnectionId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcPeeringConnectionId',\n ],\n 'State' => [\n 'shape' => 'RouteState',\n 'locationName' => 'state',\n ],\n 'Origin' => [\n 'shape' => 'RouteOrigin',\n 'locationName' => 'origin',\n ],\n ],\n ],\n 'RouteList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'Route',\n 'locationName' => 'item',\n ],\n ],\n 'RouteOrigin' => [\n 'type' => 'string',\n 'enum' => [\n 'CreateRouteTable',\n 'CreateRoute',\n 'EnableVgwRoutePropagation',\n ],\n ],\n 'RouteState' => [\n 'type' => 'string',\n 'enum' => [\n 'active',\n 'blackhole',\n ],\n ],\n 'RouteTable' => [\n 'type' => 'structure',\n 'members' => [\n 'RouteTableId' => [\n 'shape' => 'String',\n 'locationName' => 'routeTableId',\n ],\n 'VpcId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcId',\n ],\n 'Routes' => [\n 'shape' => 'RouteList',\n 'locationName' => 'routeSet',\n ],\n 'Associations' => [\n 'shape' => 'RouteTableAssociationList',\n 'locationName' => 'associationSet',\n ],\n 'Tags' => [\n 'shape' => 'TagList',\n 'locationName' => 'tagSet',\n ],\n 'PropagatingVgws' => [\n 'shape' => 'PropagatingVgwList',\n 'locationName' => 'propagatingVgwSet',\n ],\n ],\n ],\n 'RouteTableAssociation' => [\n 'type' => 'structure',\n 'members' => [\n 'RouteTableAssociationId' => [\n 'shape' => 'String',\n 'locationName' => 'routeTableAssociationId',\n ],\n 'RouteTableId' => [\n 'shape' => 'String',\n 'locationName' => 'routeTableId',\n ],\n 'SubnetId' => [\n 'shape' => 'String',\n 'locationName' => 'subnetId',\n ],\n 'Main' => [\n 'shape' => 'Boolean',\n 'locationName' => 'main',\n ],\n ],\n ],\n 'RouteTableAssociationList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'RouteTableAssociation',\n 'locationName' => 'item',\n ],\n ],\n 'RouteTableList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'RouteTable',\n 'locationName' => 'item',\n ],\n ],\n 'RuleAction' => [\n 'type' => 'string',\n 'enum' => [\n 'allow',\n 'deny',\n ],\n ],\n 'RunInstancesMonitoringEnabled' => [\n 'type' => 'structure',\n 'required' => [\n 'Enabled',\n ],\n 'members' => [\n 'Enabled' => [\n 'shape' => 'Boolean',\n 'locationName' => 'enabled',\n ],\n ],\n ],\n 'RunInstancesRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'ImageId',\n 'MinCount',\n 'MaxCount',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'ImageId' => [\n 'shape' => 'String',\n ],\n 'MinCount' => [\n 'shape' => 'Integer',\n ],\n 'MaxCount' => [\n 'shape' => 'Integer',\n ],\n 'KeyName' => [\n 'shape' => 'String',\n ],\n 'SecurityGroups' => [\n 'shape' => 'SecurityGroupStringList',\n 'locationName' => 'SecurityGroup',\n ],\n 'SecurityGroupIds' => [\n 'shape' => 'SecurityGroupIdStringList',\n 'locationName' => 'SecurityGroupId',\n ],\n 'UserData' => [\n 'shape' => 'String',\n ],\n 'InstanceType' => [\n 'shape' => 'InstanceType',\n ],\n 'Placement' => [\n 'shape' => 'Placement',\n ],\n 'KernelId' => [\n 'shape' => 'String',\n ],\n 'RamdiskId' => [\n 'shape' => 'String',\n ],\n 'BlockDeviceMappings' => [\n 'shape' => 'BlockDeviceMappingRequestList',\n 'locationName' => 'BlockDeviceMapping',\n ],\n 'Monitoring' => [\n 'shape' => 'RunInstancesMonitoringEnabled',\n ],\n 'SubnetId' => [\n 'shape' => 'String',\n ],\n 'DisableApiTermination' => [\n 'shape' => 'Boolean',\n 'locationName' => 'disableApiTermination',\n ],\n 'InstanceInitiatedShutdownBehavior' => [\n 'shape' => 'ShutdownBehavior',\n 'locationName' => 'instanceInitiatedShutdownBehavior',\n ],\n 'PrivateIpAddress' => [\n 'shape' => 'String',\n 'locationName' => 'privateIpAddress',\n ],\n 'ClientToken' => [\n 'shape' => 'String',\n 'locationName' => 'clientToken',\n ],\n 'AdditionalInfo' => [\n 'shape' => 'String',\n 'locationName' => 'additionalInfo',\n ],\n 'NetworkInterfaces' => [\n 'shape' => 'InstanceNetworkInterfaceSpecificationList',\n 'locationName' => 'networkInterface',\n ],\n 'IamInstanceProfile' => [\n 'shape' => 'IamInstanceProfileSpecification',\n 'locationName' => 'iamInstanceProfile',\n ],\n 'EbsOptimized' => [\n 'shape' => 'Boolean',\n 'locationName' => 'ebsOptimized',\n ],\n ],\n ],\n 'S3Storage' => [\n 'type' => 'structure',\n 'members' => [\n 'Bucket' => [\n 'shape' => 'String',\n 'locationName' => 'bucket',\n ],\n 'Prefix' => [\n 'shape' => 'String',\n 'locationName' => 'prefix',\n ],\n 'AWSAccessKeyId' => [\n 'shape' => 'String',\n ],\n 'UploadPolicy' => [\n 'shape' => 'Blob',\n 'locationName' => 'uploadPolicy',\n ],\n 'UploadPolicySignature' => [\n 'shape' => 'String',\n 'locationName' => 'uploadPolicySignature',\n ],\n ],\n ],\n 'SecurityGroup' => [\n 'type' => 'structure',\n 'members' => [\n 'OwnerId' => [\n 'shape' => 'String',\n 'locationName' => 'ownerId',\n ],\n 'GroupName' => [\n 'shape' => 'String',\n 'locationName' => 'groupName',\n ],\n 'GroupId' => [\n 'shape' => 'String',\n 'locationName' => 'groupId',\n ],\n 'Description' => [\n 'shape' => 'String',\n 'locationName' => 'groupDescription',\n ],\n 'IpPermissions' => [\n 'shape' => 'IpPermissionList',\n 'locationName' => 'ipPermissions',\n ],\n 'IpPermissionsEgress' => [\n 'shape' => 'IpPermissionList',\n 'locationName' => 'ipPermissionsEgress',\n ],\n 'VpcId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcId',\n ],\n 'Tags' => [\n 'shape' => 'TagList',\n 'locationName' => 'tagSet',\n ],\n ],\n ],\n 'SecurityGroupIdStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'SecurityGroupId',\n ],\n ],\n 'SecurityGroupList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'SecurityGroup',\n 'locationName' => 'item',\n ],\n ],\n 'SecurityGroupStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'SecurityGroup',\n ],\n ],\n 'ShutdownBehavior' => [\n 'type' => 'string',\n 'enum' => [\n 'stop',\n 'terminate',\n ],\n ],\n 'Snapshot' => [\n 'type' => 'structure',\n 'members' => [\n 'SnapshotId' => [\n 'shape' => 'String',\n 'locationName' => 'snapshotId',\n ],\n 'VolumeId' => [\n 'shape' => 'String',\n 'locationName' => 'volumeId',\n ],\n 'State' => [\n 'shape' => 'SnapshotState',\n 'locationName' => 'status',\n ],\n 'StartTime' => [\n 'shape' => 'DateTime',\n 'locationName' => 'startTime',\n ],\n 'Progress' => [\n 'shape' => 'String',\n 'locationName' => 'progress',\n ],\n 'OwnerId' => [\n 'shape' => 'String',\n 'locationName' => 'ownerId',\n ],\n 'Description' => [\n 'shape' => 'String',\n 'locationName' => 'description',\n ],\n 'VolumeSize' => [\n 'shape' => 'Integer',\n 'locationName' => 'volumeSize',\n ],\n 'OwnerAlias' => [\n 'shape' => 'String',\n 'locationName' => 'ownerAlias',\n ],\n 'Tags' => [\n 'shape' => 'TagList',\n 'locationName' => 'tagSet',\n ],\n 'Encrypted' => [\n 'shape' => 'Boolean',\n 'locationName' => 'encrypted',\n ],\n 'KmsKeyId' => [\n 'shape' => 'String',\n 'locationName' => 'kmsKeyId',\n ],\n ],\n ],\n 'SnapshotAttributeName' => [\n 'type' => 'string',\n 'enum' => [\n 'productCodes',\n 'createVolumePermission',\n ],\n ],\n 'SnapshotIdStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'SnapshotId',\n ],\n ],\n 'SnapshotList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'Snapshot',\n 'locationName' => 'item',\n ],\n ],\n 'SnapshotState' => [\n 'type' => 'string',\n 'enum' => [\n 'pending',\n 'completed',\n 'error',\n ],\n ],\n 'SpotDatafeedSubscription' => [\n 'type' => 'structure',\n 'members' => [\n 'OwnerId' => [\n 'shape' => 'String',\n 'locationName' => 'ownerId',\n ],\n 'Bucket' => [\n 'shape' => 'String',\n 'locationName' => 'bucket',\n ],\n 'Prefix' => [\n 'shape' => 'String',\n 'locationName' => 'prefix',\n ],\n 'State' => [\n 'shape' => 'DatafeedSubscriptionState',\n 'locationName' => 'state',\n ],\n 'Fault' => [\n 'shape' => 'SpotInstanceStateFault',\n 'locationName' => 'fault',\n ],\n ],\n ],\n 'SpotInstanceRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'SpotInstanceRequestId' => [\n 'shape' => 'String',\n 'locationName' => 'spotInstanceRequestId',\n ],\n 'SpotPrice' => [\n 'shape' => 'String',\n 'locationName' => 'spotPrice',\n ],\n 'Type' => [\n 'shape' => 'SpotInstanceType',\n 'locationName' => 'type',\n ],\n 'State' => [\n 'shape' => 'SpotInstanceState',\n 'locationName' => 'state',\n ],\n 'Fault' => [\n 'shape' => 'SpotInstanceStateFault',\n 'locationName' => 'fault',\n ],\n 'Status' => [\n 'shape' => 'SpotInstanceStatus',\n 'locationName' => 'status',\n ],\n 'ValidFrom' => [\n 'shape' => 'DateTime',\n 'locationName' => 'validFrom',\n ],\n 'ValidUntil' => [\n 'shape' => 'DateTime',\n 'locationName' => 'validUntil',\n ],\n 'LaunchGroup' => [\n 'shape' => 'String',\n 'locationName' => 'launchGroup',\n ],\n 'AvailabilityZoneGroup' => [\n 'shape' => 'String',\n 'locationName' => 'availabilityZoneGroup',\n ],\n 'LaunchSpecification' => [\n 'shape' => 'LaunchSpecification',\n 'locationName' => 'launchSpecification',\n ],\n 'InstanceId' => [\n 'shape' => 'String',\n 'locationName' => 'instanceId',\n ],\n 'CreateTime' => [\n 'shape' => 'DateTime',\n 'locationName' => 'createTime',\n ],\n 'ProductDescription' => [\n 'shape' => 'RIProductDescription',\n 'locationName' => 'productDescription',\n ],\n 'Tags' => [\n 'shape' => 'TagList',\n 'locationName' => 'tagSet',\n ],\n 'LaunchedAvailabilityZone' => [\n 'shape' => 'String',\n 'locationName' => 'launchedAvailabilityZone',\n ],\n ],\n ],\n 'SpotInstanceRequestIdList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'SpotInstanceRequestId',\n ],\n ],\n 'SpotInstanceRequestList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'SpotInstanceRequest',\n 'locationName' => 'item',\n ],\n ],\n 'SpotInstanceState' => [\n 'type' => 'string',\n 'enum' => [\n 'open',\n 'active',\n 'closed',\n 'cancelled',\n 'failed',\n ],\n ],\n 'SpotInstanceStateFault' => [\n 'type' => 'structure',\n 'members' => [\n 'Code' => [\n 'shape' => 'String',\n 'locationName' => 'code',\n ],\n 'Message' => [\n 'shape' => 'String',\n 'locationName' => 'message',\n ],\n ],\n ],\n 'SpotInstanceStatus' => [\n 'type' => 'structure',\n 'members' => [\n 'Code' => [\n 'shape' => 'String',\n 'locationName' => 'code',\n ],\n 'UpdateTime' => [\n 'shape' => 'DateTime',\n 'locationName' => 'updateTime',\n ],\n 'Message' => [\n 'shape' => 'String',\n 'locationName' => 'message',\n ],\n ],\n ],\n 'SpotInstanceType' => [\n 'type' => 'string',\n 'enum' => [\n 'one-time',\n 'persistent',\n ],\n ],\n 'SpotPlacement' => [\n 'type' => 'structure',\n 'members' => [\n 'AvailabilityZone' => [\n 'shape' => 'String',\n 'locationName' => 'availabilityZone',\n ],\n 'GroupName' => [\n 'shape' => 'String',\n 'locationName' => 'groupName',\n ],\n ],\n ],\n 'SpotPrice' => [\n 'type' => 'structure',\n 'members' => [\n 'InstanceType' => [\n 'shape' => 'InstanceType',\n 'locationName' => 'instanceType',\n ],\n 'ProductDescription' => [\n 'shape' => 'RIProductDescription',\n 'locationName' => 'productDescription',\n ],\n 'SpotPrice' => [\n 'shape' => 'String',\n 'locationName' => 'spotPrice',\n ],\n 'Timestamp' => [\n 'shape' => 'DateTime',\n 'locationName' => 'timestamp',\n ],\n 'AvailabilityZone' => [\n 'shape' => 'String',\n 'locationName' => 'availabilityZone',\n ],\n ],\n ],\n 'SpotPriceHistoryList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'SpotPrice',\n 'locationName' => 'item',\n ],\n ],\n 'StartInstancesRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'InstanceIds',\n ],\n 'members' => [\n 'InstanceIds' => [\n 'shape' => 'InstanceIdStringList',\n 'locationName' => 'InstanceId',\n ],\n 'AdditionalInfo' => [\n 'shape' => 'String',\n 'locationName' => 'additionalInfo',\n ],\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n ],\n ],\n 'StartInstancesResult' => [\n 'type' => 'structure',\n 'members' => [\n 'StartingInstances' => [\n 'shape' => 'InstanceStateChangeList',\n 'locationName' => 'instancesSet',\n ],\n ],\n ],\n 'StateReason' => [\n 'type' => 'structure',\n 'members' => [\n 'Code' => [\n 'shape' => 'String',\n 'locationName' => 'code',\n ],\n 'Message' => [\n 'shape' => 'String',\n 'locationName' => 'message',\n ],\n ],\n ],\n 'StatusName' => [\n 'type' => 'string',\n 'enum' => [\n 'reachability',\n ],\n ],\n 'StatusType' => [\n 'type' => 'string',\n 'enum' => [\n 'passed',\n 'failed',\n 'insufficient-data',\n ],\n ],\n 'StopInstancesRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'InstanceIds',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'InstanceIds' => [\n 'shape' => 'InstanceIdStringList',\n 'locationName' => 'InstanceId',\n ],\n 'Force' => [\n 'shape' => 'Boolean',\n 'locationName' => 'force',\n ],\n ],\n ],\n 'StopInstancesResult' => [\n 'type' => 'structure',\n 'members' => [\n 'StoppingInstances' => [\n 'shape' => 'InstanceStateChangeList',\n 'locationName' => 'instancesSet',\n ],\n ],\n ],\n 'Storage' => [\n 'type' => 'structure',\n 'members' => [\n 'S3' => [\n 'shape' => 'S3Storage',\n ],\n ],\n ],\n 'String' => [\n 'type' => 'string',\n ],\n 'Subnet' => [\n 'type' => 'structure',\n 'members' => [\n 'SubnetId' => [\n 'shape' => 'String',\n 'locationName' => 'subnetId',\n ],\n 'State' => [\n 'shape' => 'SubnetState',\n 'locationName' => 'state',\n ],\n 'VpcId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcId',\n ],\n 'CidrBlock' => [\n 'shape' => 'String',\n 'locationName' => 'cidrBlock',\n ],\n 'AvailableIpAddressCount' => [\n 'shape' => 'Integer',\n 'locationName' => 'availableIpAddressCount',\n ],\n 'AvailabilityZone' => [\n 'shape' => 'String',\n 'locationName' => 'availabilityZone',\n ],\n 'DefaultForAz' => [\n 'shape' => 'Boolean',\n 'locationName' => 'defaultForAz',\n ],\n 'MapPublicIpOnLaunch' => [\n 'shape' => 'Boolean',\n 'locationName' => 'mapPublicIpOnLaunch',\n ],\n 'Tags' => [\n 'shape' => 'TagList',\n 'locationName' => 'tagSet',\n ],\n ],\n ],\n 'SubnetIdStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'SubnetId',\n ],\n ],\n 'SubnetList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'Subnet',\n 'locationName' => 'item',\n ],\n ],\n 'SubnetState' => [\n 'type' => 'string',\n 'enum' => [\n 'pending',\n 'available',\n ],\n ],\n 'SummaryStatus' => [\n 'type' => 'string',\n 'enum' => [\n 'ok',\n 'impaired',\n 'insufficient-data',\n 'not-applicable',\n ],\n ],\n 'Tag' => [\n 'type' => 'structure',\n 'members' => [\n 'Key' => [\n 'shape' => 'String',\n 'locationName' => 'key',\n ],\n 'Value' => [\n 'shape' => 'String',\n 'locationName' => 'value',\n ],\n ],\n ],\n 'TagDescription' => [\n 'type' => 'structure',\n 'members' => [\n 'ResourceId' => [\n 'shape' => 'String',\n 'locationName' => 'resourceId',\n ],\n 'ResourceType' => [\n 'shape' => 'ResourceType',\n 'locationName' => 'resourceType',\n ],\n 'Key' => [\n 'shape' => 'String',\n 'locationName' => 'key',\n ],\n 'Value' => [\n 'shape' => 'String',\n 'locationName' => 'value',\n ],\n ],\n ],\n 'TagDescriptionList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'TagDescription',\n 'locationName' => 'item',\n ],\n ],\n 'TagList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'Tag',\n 'locationName' => 'item',\n ],\n ],\n 'TelemetryStatus' => [\n 'type' => 'string',\n 'enum' => [\n 'UP',\n 'DOWN',\n ],\n ],\n 'Tenancy' => [\n 'type' => 'string',\n 'enum' => [\n 'default',\n 'dedicated',\n ],\n ],\n 'TerminateInstancesRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'InstanceIds',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'InstanceIds' => [\n 'shape' => 'InstanceIdStringList',\n 'locationName' => 'InstanceId',\n ],\n ],\n ],\n 'TerminateInstancesResult' => [\n 'type' => 'structure',\n 'members' => [\n 'TerminatingInstances' => [\n 'shape' => 'InstanceStateChangeList',\n 'locationName' => 'instancesSet',\n ],\n ],\n ],\n 'UnassignPrivateIpAddressesRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'NetworkInterfaceId',\n 'PrivateIpAddresses',\n ],\n 'members' => [\n 'NetworkInterfaceId' => [\n 'shape' => 'String',\n 'locationName' => 'networkInterfaceId',\n ],\n 'PrivateIpAddresses' => [\n 'shape' => 'PrivateIpAddressStringList',\n 'locationName' => 'privateIpAddress',\n ],\n ],\n ],\n 'UnmonitorInstancesRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'InstanceIds',\n ],\n 'members' => [\n 'DryRun' => [\n 'shape' => 'Boolean',\n 'locationName' => 'dryRun',\n ],\n 'InstanceIds' => [\n 'shape' => 'InstanceIdStringList',\n 'locationName' => 'InstanceId',\n ],\n ],\n ],\n 'UnmonitorInstancesResult' => [\n 'type' => 'structure',\n 'members' => [\n 'InstanceMonitorings' => [\n 'shape' => 'InstanceMonitoringList',\n 'locationName' => 'instancesSet',\n ],\n ],\n ],\n 'UserData' => [\n 'type' => 'structure',\n 'members' => [\n 'Data' => [\n 'shape' => 'String',\n 'locationName' => 'data',\n ],\n ],\n ],\n 'UserGroupStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'UserGroup',\n ],\n ],\n 'UserIdGroupPair' => [\n 'type' => 'structure',\n 'members' => [\n 'UserId' => [\n 'shape' => 'String',\n 'locationName' => 'userId',\n ],\n 'GroupName' => [\n 'shape' => 'String',\n 'locationName' => 'groupName',\n ],\n 'GroupId' => [\n 'shape' => 'String',\n 'locationName' => 'groupId',\n ],\n ],\n ],\n 'UserIdGroupPairList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'UserIdGroupPair',\n 'locationName' => 'item',\n ],\n ],\n 'UserIdStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'UserId',\n ],\n ],\n 'ValueStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'item',\n ],\n ],\n 'VgwTelemetry' => [\n 'type' => 'structure',\n 'members' => [\n 'OutsideIpAddress' => [\n 'shape' => 'String',\n 'locationName' => 'outsideIpAddress',\n ],\n 'Status' => [\n 'shape' => 'TelemetryStatus',\n 'locationName' => 'status',\n ],\n 'LastStatusChange' => [\n 'shape' => 'DateTime',\n 'locationName' => 'lastStatusChange',\n ],\n 'StatusMessage' => [\n 'shape' => 'String',\n 'locationName' => 'statusMessage',\n ],\n 'AcceptedRouteCount' => [\n 'shape' => 'Integer',\n 'locationName' => 'acceptedRouteCount',\n ],\n ],\n ],\n 'VgwTelemetryList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'VgwTelemetry',\n 'locationName' => 'item',\n ],\n ],\n 'VirtualizationType' => [\n 'type' => 'string',\n 'enum' => [\n 'hvm',\n 'paravirtual',\n ],\n ],\n 'Volume' => [\n 'type' => 'structure',\n 'members' => [\n 'VolumeId' => [\n 'shape' => 'String',\n 'locationName' => 'volumeId',\n ],\n 'Size' => [\n 'shape' => 'Integer',\n 'locationName' => 'size',\n ],\n 'SnapshotId' => [\n 'shape' => 'String',\n 'locationName' => 'snapshotId',\n ],\n 'AvailabilityZone' => [\n 'shape' => 'String',\n 'locationName' => 'availabilityZone',\n ],\n 'State' => [\n 'shape' => 'VolumeState',\n 'locationName' => 'status',\n ],\n 'CreateTime' => [\n 'shape' => 'DateTime',\n 'locationName' => 'createTime',\n ],\n 'Attachments' => [\n 'shape' => 'VolumeAttachmentList',\n 'locationName' => 'attachmentSet',\n ],\n 'Tags' => [\n 'shape' => 'TagList',\n 'locationName' => 'tagSet',\n ],\n 'VolumeType' => [\n 'shape' => 'VolumeType',\n 'locationName' => 'volumeType',\n ],\n 'Iops' => [\n 'shape' => 'Integer',\n 'locationName' => 'iops',\n ],\n 'Encrypted' => [\n 'shape' => 'Boolean',\n 'locationName' => 'encrypted',\n ],\n 'KmsKeyId' => [\n 'shape' => 'String',\n 'locationName' => 'kmsKeyId',\n ],\n ],\n ],\n 'VolumeAttachment' => [\n 'type' => 'structure',\n 'members' => [\n 'VolumeId' => [\n 'shape' => 'String',\n 'locationName' => 'volumeId',\n ],\n 'InstanceId' => [\n 'shape' => 'String',\n 'locationName' => 'instanceId',\n ],\n 'Device' => [\n 'shape' => 'String',\n 'locationName' => 'device',\n ],\n 'State' => [\n 'shape' => 'VolumeAttachmentState',\n 'locationName' => 'status',\n ],\n 'AttachTime' => [\n 'shape' => 'DateTime',\n 'locationName' => 'attachTime',\n ],\n 'DeleteOnTermination' => [\n 'shape' => 'Boolean',\n 'locationName' => 'deleteOnTermination',\n ],\n ],\n ],\n 'VolumeAttachmentList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'VolumeAttachment',\n 'locationName' => 'item',\n ],\n ],\n 'VolumeAttachmentState' => [\n 'type' => 'string',\n 'enum' => [\n 'attaching',\n 'attached',\n 'detaching',\n 'detached',\n ],\n ],\n 'VolumeAttributeName' => [\n 'type' => 'string',\n 'enum' => [\n 'autoEnableIO',\n 'productCodes',\n ],\n ],\n 'VolumeDetail' => [\n 'type' => 'structure',\n 'required' => [\n 'Size',\n ],\n 'members' => [\n 'Size' => [\n 'shape' => 'Long',\n 'locationName' => 'size',\n ],\n ],\n ],\n 'VolumeIdStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'VolumeId',\n ],\n ],\n 'VolumeList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'Volume',\n 'locationName' => 'item',\n ],\n ],\n 'VolumeState' => [\n 'type' => 'string',\n 'enum' => [\n 'creating',\n 'available',\n 'in-use',\n 'deleting',\n 'deleted',\n 'error',\n ],\n ],\n 'VolumeStatusAction' => [\n 'type' => 'structure',\n 'members' => [\n 'Code' => [\n 'shape' => 'String',\n 'locationName' => 'code',\n ],\n 'Description' => [\n 'shape' => 'String',\n 'locationName' => 'description',\n ],\n 'EventType' => [\n 'shape' => 'String',\n 'locationName' => 'eventType',\n ],\n 'EventId' => [\n 'shape' => 'String',\n 'locationName' => 'eventId',\n ],\n ],\n ],\n 'VolumeStatusActionsList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'VolumeStatusAction',\n 'locationName' => 'item',\n ],\n ],\n 'VolumeStatusDetails' => [\n 'type' => 'structure',\n 'members' => [\n 'Name' => [\n 'shape' => 'VolumeStatusName',\n 'locationName' => 'name',\n ],\n 'Status' => [\n 'shape' => 'String',\n 'locationName' => 'status',\n ],\n ],\n ],\n 'VolumeStatusDetailsList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'VolumeStatusDetails',\n 'locationName' => 'item',\n ],\n ],\n 'VolumeStatusEvent' => [\n 'type' => 'structure',\n 'members' => [\n 'EventType' => [\n 'shape' => 'String',\n 'locationName' => 'eventType',\n ],\n 'Description' => [\n 'shape' => 'String',\n 'locationName' => 'description',\n ],\n 'NotBefore' => [\n 'shape' => 'DateTime',\n 'locationName' => 'notBefore',\n ],\n 'NotAfter' => [\n 'shape' => 'DateTime',\n 'locationName' => 'notAfter',\n ],\n 'EventId' => [\n 'shape' => 'String',\n 'locationName' => 'eventId',\n ],\n ],\n ],\n 'VolumeStatusEventsList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'VolumeStatusEvent',\n 'locationName' => 'item',\n ],\n ],\n 'VolumeStatusInfo' => [\n 'type' => 'structure',\n 'members' => [\n 'Status' => [\n 'shape' => 'VolumeStatusInfoStatus',\n 'locationName' => 'status',\n ],\n 'Details' => [\n 'shape' => 'VolumeStatusDetailsList',\n 'locationName' => 'details',\n ],\n ],\n ],\n 'VolumeStatusInfoStatus' => [\n 'type' => 'string',\n 'enum' => [\n 'ok',\n 'impaired',\n 'insufficient-data',\n ],\n ],\n 'VolumeStatusItem' => [\n 'type' => 'structure',\n 'members' => [\n 'VolumeId' => [\n 'shape' => 'String',\n 'locationName' => 'volumeId',\n ],\n 'AvailabilityZone' => [\n 'shape' => 'String',\n 'locationName' => 'availabilityZone',\n ],\n 'VolumeStatus' => [\n 'shape' => 'VolumeStatusInfo',\n 'locationName' => 'volumeStatus',\n ],\n 'Events' => [\n 'shape' => 'VolumeStatusEventsList',\n 'locationName' => 'eventsSet',\n ],\n 'Actions' => [\n 'shape' => 'VolumeStatusActionsList',\n 'locationName' => 'actionsSet',\n ],\n ],\n ],\n 'VolumeStatusList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'VolumeStatusItem',\n 'locationName' => 'item',\n ],\n ],\n 'VolumeStatusName' => [\n 'type' => 'string',\n 'enum' => [\n 'io-enabled',\n 'io-performance',\n ],\n ],\n 'VolumeType' => [\n 'type' => 'string',\n 'enum' => [\n 'standard',\n 'io1',\n 'gp2',\n ],\n ],\n 'Vpc' => [\n 'type' => 'structure',\n 'members' => [\n 'VpcId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcId',\n ],\n 'State' => [\n 'shape' => 'VpcState',\n 'locationName' => 'state',\n ],\n 'CidrBlock' => [\n 'shape' => 'String',\n 'locationName' => 'cidrBlock',\n ],\n 'DhcpOptionsId' => [\n 'shape' => 'String',\n 'locationName' => 'dhcpOptionsId',\n ],\n 'Tags' => [\n 'shape' => 'TagList',\n 'locationName' => 'tagSet',\n ],\n 'InstanceTenancy' => [\n 'shape' => 'Tenancy',\n 'locationName' => 'instanceTenancy',\n ],\n 'IsDefault' => [\n 'shape' => 'Boolean',\n 'locationName' => 'isDefault',\n ],\n ],\n ],\n 'VpcAttachment' => [\n 'type' => 'structure',\n 'members' => [\n 'VpcId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcId',\n ],\n 'State' => [\n 'shape' => 'AttachmentStatus',\n 'locationName' => 'state',\n ],\n ],\n ],\n 'VpcAttachmentList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'VpcAttachment',\n 'locationName' => 'item',\n ],\n ],\n 'VpcAttributeName' => [\n 'type' => 'string',\n 'enum' => [\n 'enableDnsSupport',\n 'enableDnsHostnames',\n ],\n ],\n 'VpcClassicLink' => [\n 'type' => 'structure',\n 'members' => [\n 'VpcId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcId',\n ],\n 'ClassicLinkEnabled' => [\n 'shape' => 'Boolean',\n 'locationName' => 'classicLinkEnabled',\n ],\n 'Tags' => [\n 'shape' => 'TagList',\n 'locationName' => 'tagSet',\n ],\n ],\n ],\n 'VpcClassicLinkIdList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'VpcId',\n ],\n ],\n 'VpcClassicLinkList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'VpcClassicLink',\n 'locationName' => 'item',\n ],\n ],\n 'VpcIdStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'VpcId',\n ],\n ],\n 'VpcList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'Vpc',\n 'locationName' => 'item',\n ],\n ],\n 'VpcPeeringConnection' => [\n 'type' => 'structure',\n 'members' => [\n 'AccepterVpcInfo' => [\n 'shape' => 'VpcPeeringConnectionVpcInfo',\n 'locationName' => 'accepterVpcInfo',\n ],\n 'ExpirationTime' => [\n 'shape' => 'DateTime',\n 'locationName' => 'expirationTime',\n ],\n 'RequesterVpcInfo' => [\n 'shape' => 'VpcPeeringConnectionVpcInfo',\n 'locationName' => 'requesterVpcInfo',\n ],\n 'Status' => [\n 'shape' => 'VpcPeeringConnectionStateReason',\n 'locationName' => 'status',\n ],\n 'Tags' => [\n 'shape' => 'TagList',\n 'locationName' => 'tagSet',\n ],\n 'VpcPeeringConnectionId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcPeeringConnectionId',\n ],\n ],\n ],\n 'VpcPeeringConnectionList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'VpcPeeringConnection',\n 'locationName' => 'item',\n ],\n ],\n 'VpcPeeringConnectionStateReason' => [\n 'type' => 'structure',\n 'members' => [\n 'Code' => [\n 'shape' => 'String',\n 'locationName' => 'code',\n ],\n 'Message' => [\n 'shape' => 'String',\n 'locationName' => 'message',\n ],\n ],\n ],\n 'VpcPeeringConnectionVpcInfo' => [\n 'type' => 'structure',\n 'members' => [\n 'CidrBlock' => [\n 'shape' => 'String',\n 'locationName' => 'cidrBlock',\n ],\n 'OwnerId' => [\n 'shape' => 'String',\n 'locationName' => 'ownerId',\n ],\n 'VpcId' => [\n 'shape' => 'String',\n 'locationName' => 'vpcId',\n ],\n ],\n ],\n 'VpcState' => [\n 'type' => 'string',\n 'enum' => [\n 'pending',\n 'available',\n ],\n ],\n 'VpnConnection' => [\n 'type' => 'structure',\n 'members' => [\n 'VpnConnectionId' => [\n 'shape' => 'String',\n 'locationName' => 'vpnConnectionId',\n ],\n 'State' => [\n 'shape' => 'VpnState',\n 'locationName' => 'state',\n ],\n 'CustomerGatewayConfiguration' => [\n 'shape' => 'String',\n 'locationName' => 'customerGatewayConfiguration',\n ],\n 'Type' => [\n 'shape' => 'GatewayType',\n 'locationName' => 'type',\n ],\n 'CustomerGatewayId' => [\n 'shape' => 'String',\n 'locationName' => 'customerGatewayId',\n ],\n 'VpnGatewayId' => [\n 'shape' => 'String',\n 'locationName' => 'vpnGatewayId',\n ],\n 'Tags' => [\n 'shape' => 'TagList',\n 'locationName' => 'tagSet',\n ],\n 'VgwTelemetry' => [\n 'shape' => 'VgwTelemetryList',\n 'locationName' => 'vgwTelemetry',\n ],\n 'Options' => [\n 'shape' => 'VpnConnectionOptions',\n 'locationName' => 'options',\n ],\n 'Routes' => [\n 'shape' => 'VpnStaticRouteList',\n 'locationName' => 'routes',\n ],\n ],\n ],\n 'VpnConnectionIdStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'VpnConnectionId',\n ],\n ],\n 'VpnConnectionList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'VpnConnection',\n 'locationName' => 'item',\n ],\n ],\n 'VpnConnectionOptions' => [\n 'type' => 'structure',\n 'members' => [\n 'StaticRoutesOnly' => [\n 'shape' => 'Boolean',\n 'locationName' => 'staticRoutesOnly',\n ],\n ],\n ],\n 'VpnConnectionOptionsSpecification' => [\n 'type' => 'structure',\n 'members' => [\n 'StaticRoutesOnly' => [\n 'shape' => 'Boolean',\n 'locationName' => 'staticRoutesOnly',\n ],\n ],\n ],\n 'VpnGateway' => [\n 'type' => 'structure',\n 'members' => [\n 'VpnGatewayId' => [\n 'shape' => 'String',\n 'locationName' => 'vpnGatewayId',\n ],\n 'State' => [\n 'shape' => 'VpnState',\n 'locationName' => 'state',\n ],\n 'Type' => [\n 'shape' => 'GatewayType',\n 'locationName' => 'type',\n ],\n 'AvailabilityZone' => [\n 'shape' => 'String',\n 'locationName' => 'availabilityZone',\n ],\n 'VpcAttachments' => [\n 'shape' => 'VpcAttachmentList',\n 'locationName' => 'attachments',\n ],\n 'Tags' => [\n 'shape' => 'TagList',\n 'locationName' => 'tagSet',\n ],\n ],\n ],\n 'VpnGatewayIdStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'VpnGatewayId',\n ],\n ],\n 'VpnGatewayList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'VpnGateway',\n 'locationName' => 'item',\n ],\n ],\n 'VpnState' => [\n 'type' => 'string',\n 'enum' => [\n 'pending',\n 'available',\n 'deleting',\n 'deleted',\n ],\n ],\n 'VpnStaticRoute' => [\n 'type' => 'structure',\n 'members' => [\n 'DestinationCidrBlock' => [\n 'shape' => 'String',\n 'locationName' => 'destinationCidrBlock',\n ],\n 'Source' => [\n 'shape' => 'VpnStaticRouteSource',\n 'locationName' => 'source',\n ],\n 'State' => [\n 'shape' => 'VpnState',\n 'locationName' => 'state',\n ],\n ],\n ],\n 'VpnStaticRouteList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'VpnStaticRoute',\n 'locationName' => 'item',\n ],\n ],\n 'VpnStaticRouteSource' => [\n 'type' => 'string',\n 'enum' => [\n 'Static',\n ],\n ],\n 'ZoneNameStringList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'String',\n 'locationName' => 'ZoneName',\n ],\n ],\n 'NewDhcpConfigurationList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'NewDhcpConfiguration',\n 'locationName' => 'item',\n ],\n ],\n 'NewDhcpConfiguration' => [\n 'type' => 'structure',\n 'members' => [\n 'Key' => [\n 'shape' => 'String',\n 'locationName' => 'key',\n ],\n 'Values' => [\n 'shape' => 'ValueStringList',\n 'locationName' => 'Value',\n ],\n ],\n ],\n 'DhcpConfigurationValueList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'AttributeValue',\n 'locationName' => 'item',\n ],\n ],\n 'Blob' => [\n 'type' => 'blob',\n ],\n 'BlobAttributeValue' => [\n 'type' => 'structure',\n 'members' => [\n 'Value' => [\n 'shape' => 'Blob',\n 'locationName' => 'value',\n ],\n ],\n ],\n 'RequestSpotLaunchSpecification' => [\n 'type' => 'structure',\n 'members' => [\n 'ImageId' => [\n 'shape' => 'String',\n 'locationName' => 'imageId',\n ],\n 'KeyName' => [\n 'shape' => 'String',\n 'locationName' => 'keyName',\n ],\n 'SecurityGroups' => [\n 'shape' => 'ValueStringList',\n 'locationName' => 'SecurityGroup',\n ],\n 'UserData' => [\n 'shape' => 'String',\n 'locationName' => 'userData',\n ],\n 'AddressingType' => [\n 'shape' => 'String',\n 'locationName' => 'addressingType',\n ],\n 'InstanceType' => [\n 'shape' => 'InstanceType',\n 'locationName' => 'instanceType',\n ],\n 'Placement' => [\n 'shape' => 'SpotPlacement',\n 'locationName' => 'placement',\n ],\n 'KernelId' => [\n 'shape' => 'String',\n 'locationName' => 'kernelId',\n ],\n 'RamdiskId' => [\n 'shape' => 'String',\n 'locationName' => 'ramdiskId',\n ],\n 'BlockDeviceMappings' => [\n 'shape' => 'BlockDeviceMappingList',\n 'locationName' => 'blockDeviceMapping',\n ],\n 'SubnetId' => [\n 'shape' => 'String',\n 'locationName' => 'subnetId',\n ],\n 'NetworkInterfaces' => [\n 'shape' => 'InstanceNetworkInterfaceSpecificationList',\n 'locationName' => 'NetworkInterface',\n ],\n 'IamInstanceProfile' => [\n 'shape' => 'IamInstanceProfileSpecification',\n 'locationName' => 'iamInstanceProfile',\n ],\n 'EbsOptimized' => [\n 'shape' => 'Boolean',\n 'locationName' => 'ebsOptimized',\n ],\n 'Monitoring' => [\n 'shape' => 'RunInstancesMonitoringEnabled',\n 'locationName' => 'monitoring',\n ],\n 'SecurityGroupIds' => [\n 'shape' => 'ValueStringList',\n 'locationName' => 'SecurityGroupId',\n ],\n ],\n ],\n ],\n];\n" }, { "alpha_fraction": 0.4941500425338745, "alphanum_fraction": 0.49896764755249023, "avg_line_length": 24.946428298950195, "blob_id": "8d1404da2129194f763ac54a924f011aedcd5146", "content_id": "07af57e974e9a0f20b6b8070833edd2dceee9eaf", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2906, "license_type": "permissive", "max_line_length": 78, "num_lines": 112, "path": "/tests/SdkTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test;\n\nuse Aws\\Sdk;\nuse GuzzleHttp\\Event\\EmitterInterface;\nuse JmesPath\\Env as JmesPath;\n\n/**\n * @covers Aws\\Sdk\n */\nclass SdkTest extends \\PHPUnit_Framework_TestCase\n{\n /**\n * Check if the given emitter has the provided event listener\n *\n * @param EmitterInterface $emitter Emitter to search\n * @param string|object $value Can be a class name or listener object\n * @param null $event Specific event to search (optional)\n *\n * @return bool\n */\n public static function hasListener(\n EmitterInterface $emitter,\n $value,\n $event = null\n ) {\n $expression = $event\n ? '[*][0]'\n : '*[*][0]';\n\n $listeners = $event\n ? $emitter->listeners($event)\n : $emitter->listeners();\n\n $result = JmesPath::search($expression, $listeners) ?: [];\n\n if (!is_object($value)) {\n $result = array_map(function($o) {\n return get_class($o);\n }, $result);\n }\n\n return in_array($value, $result, true);\n }\n\n /**\n * @expectedException \\BadMethodCallException\n */\n public function testEnsuresMissingMethodThrowsException()\n {\n (new Sdk())->foo();\n }\n\n public function testHasMagicMethods()\n {\n $sdk = $this->getMockBuilder('Aws\\Sdk')\n ->setMethods(['createClient'])\n ->getMock();\n $sdk->expects($this->once())\n ->method('createClient')\n ->with('Foo', ['bar' => 'baz']);\n $sdk->createFoo(['bar' => 'baz']);\n }\n\n public function testCreatesClients()\n {\n $this->assertInstanceOf(\n 'Aws\\AwsClientInterface',\n (new Sdk())->createDynamoDb([\n 'region' => 'us-east-1',\n 'version' => 'latest'\n ])\n );\n }\n\n public function testCreatesClientsWithAlias()\n {\n $this->assertInstanceOf(\n 'Aws\\AwsClientInterface',\n (new Sdk())->createCloudWatch([\n 'region' => 'us-east-1',\n 'version' => 'latest'\n ])\n );\n }\n\n public function testUsesSharedHandler()\n {\n $sdk = new Sdk();\n $c1 = $sdk->createClient('s3', [\n 'version' => 'latest',\n 'credentials' => ['key' => 'a', 'secret' => 'b']\n ]);\n $c2 = $sdk->createClient('s3', [\n 'version' => 'latest',\n 'credentials' => ['key' => 'a', 'secret' => 'b']\n ]);\n $fsm1 = $this->readAttribute($c1->getHttpClient(), 'fsm');\n $fsm2 = $this->readAttribute($c2->getHttpClient(), 'fsm');\n $this->assertSame(\n $this->readAttribute($fsm1, 'handler'),\n $this->readAttribute($fsm2, 'handler')\n );\n }\n}\n\nclass FooFactory\n{\n function create($args) {\n return $args;\n }\n}\n" }, { "alpha_fraction": 0.580692708492279, "alphanum_fraction": 0.5821665525436401, "avg_line_length": 24.129629135131836, "blob_id": "e19e4b23101f1256cba46b4730285c32030990b4", "content_id": "5f822d879b5ce36074e53ea979e28909856794f2", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1357, "license_type": "permissive", "max_line_length": 81, "num_lines": 54, "path": "/src/S3/Exception/ClearBucketException.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\S3\\Exception;\n\n/**\n * Exception thrown when errors occur while using the ClearBucket class\n */\nclass ClearBucketException extends \\Exception\n{\n private $iterator;\n private $errors;\n\n /**\n * @param array $errors The errored keys\n * @param \\Iterator $iterator Iterator that was used\n * @param \\Exception $previous Previous exception (if any)\n */\n public function __construct(\n array $errors,\n \\Iterator $iterator,\n \\Exception $previous = null\n ) {\n $this->iterator = $iterator;\n $this->errors = $errors;\n $msgs = DeleteMultipleObjectsException::createMessageFromErrors($errors);\n parent::__construct(\n 'One or more errors occurred while clearing the bucket: ' . $msgs,\n 0,\n $previous\n );\n }\n\n /**\n * Get the errored objects\n *\n * @return array Returns an array of associative arrays, each containing\n * a 'Code', 'Message', and 'Key' key.\n */\n public function getErrors()\n {\n return $this->errors;\n }\n\n /**\n * Get iterator being used to clear the bucket.\n *\n * You can use this iterator to possible resume the deletion.\n *\n * @return \\Iterator\n */\n public function getIterator()\n {\n return $this->iterator;\n }\n}\n" }, { "alpha_fraction": 0.5066313147544861, "alphanum_fraction": 0.5079575777053833, "avg_line_length": 25.928571701049805, "blob_id": "1c74285cba0ffec5e2ab800fe2a04c6df324fbdc", "content_id": "84a5b84a37e11f1bf2e935313a684c49d22a7517", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 754, "license_type": "permissive", "max_line_length": 63, "num_lines": 28, "path": "/build/functions.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\n\nfunction get_code_for_array(array $array)\n{\n // Use var_export as a starting point.\n $code = \"<?php return \" . var_export($array, true) . \";\\n\";\n\n // Convert \"array()\" to \"[]\".\n $code = str_replace('array (', '[', $code);\n $code = str_replace(')', ']', $code);\n\n // Removing trailing whitespace.\n $code = preg_replace('/\\s+$/m', '', $code);\n\n // Move arrays to the same line.\n $code = preg_replace('/=>\\s*\\n\\s*\\[/', '=> [', $code);\n\n // Get rid of numbered array indexes.\n $code = preg_replace('/(\\s*)(\\d+ => )/', '$1', $code);\n\n // Make empty arrays span only a single line.\n $code = preg_replace('/=>\\s*\\[\\n\\s*\\]/', '=> []', $code);\n\n // Add a trailing new line.\n $code .= \"\\n\";\n\n return $code;\n}\n" }, { "alpha_fraction": 0.6017391085624695, "alphanum_fraction": 0.6017391085624695, "avg_line_length": 29.263158798217773, "blob_id": "cdc547f54c9bcbba0b6e504ebc41efbcc59be93c", "content_id": "3433583a87452017803ed5ae4c4df4ce17ea9c9f", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1150, "license_type": "permissive", "max_line_length": 79, "num_lines": 38, "path": "/src/Glacier/GlacierClient.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Glacier;\n\nuse Aws\\AwsClient;\nuse Aws\\Subscriber\\SourceFile;\n\n/**\n * This client is used to interact with the **Amazon Glacier** service.\n */\nclass GlacierClient extends AwsClient\n{\n public function __construct(array $args)\n {\n parent::__construct($args);\n $api = $this->getApi();\n // Add the Glacier version header required for all operations.\n $this->getHttpClient()->setDefaultOption(\n 'headers/x-amz-glacier-version',\n $api->getMetadata('apiVersion')\n );\n $em = $this->getEmitter();\n // Allow for specifying bodies with file paths and file handles.\n $em->attach(new SourceFile($api, 'body', 'sourceFile'));\n // Listen for upload operations and make sure the required hash headers\n // are added.\n $em->attach(new ApplyChecksumsSubscriber());\n }\n\n public function getCommand($name, array $args = [])\n {\n // Set the default accountId to \"-\" for all operations.\n if (!isset($args['accountId'])) {\n $args['accountId'] = '-';\n }\n\n return parent::getCommand($name, $args);\n }\n}\n" }, { "alpha_fraction": 0.6028985381126404, "alphanum_fraction": 0.6028985381126404, "avg_line_length": 15.428571701049805, "blob_id": "30f42593893f45d0f73a54b0e1cab23d9ce351a2", "content_id": "a5e42e830ffb09919e9664b2a53e7ea15bb91205", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 345, "license_type": "permissive", "max_line_length": 65, "num_lines": 21, "path": "/src/Api/Parser/AbstractParser.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Api\\Parser;\n\nuse Aws\\Api\\Service;\n\n/**\n * @internal\n */\nabstract class AbstractParser\n{\n /** @var \\Aws\\Api\\Service Representation of the service API*/\n protected $api;\n\n /**\n * @param Service $api Service description\n */\n public function __construct(Service $api)\n {\n $this->api = $api;\n }\n}\n" }, { "alpha_fraction": 0.5765536427497864, "alphanum_fraction": 0.5781073570251465, "avg_line_length": 34.049503326416016, "blob_id": "0f0e1022177f1738a9432a24dddd41aefa9c4224", "content_id": "afb948aecb65cf33c3a5b82100ddb223f35fef9d", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 7080, "license_type": "permissive", "max_line_length": 94, "num_lines": 202, "path": "/src/Multipart/Uploader.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Multipart;\n\nuse Aws\\AwsClientInterface;\nuse Aws\\Exception\\AwsException;\nuse Aws\\Exception\\MultipartUploadException;\nuse Aws\\Result;\nuse GuzzleHttp\\Command\\CommandInterface as Command;\nuse GuzzleHttp\\Command\\Event\\ProcessEvent;\nuse transducers as t;\n\n/**\n * Encapsulates the execution of a multipart upload to S3 or Glacier.\n */\nclass Uploader\n{\n /** @var AwsClientInterface Client used for the upload. */\n private $client;\n\n /** @var UploadState State used to manage the upload. */\n private $state;\n\n /** @var \\Traversable Generator that yields sets of upload part params. */\n private $parts;\n\n /** @var array Service-specific configuration used to perform the upload. */\n private $config;\n\n /**\n * Construct a new transfer object\n *\n * @param AwsClientInterface $client Client used for the upload.\n * @param UploadState $state State used to manage the upload.\n * @param \\Traversable $parts Generator that yields sets of params\n * for each upload part operation,\n * including the upload body.\n * @param array $config Service-specific configuration relevant\n * to performing the upload.\n */\n public function __construct(\n AwsClientInterface $client,\n UploadState $state,\n \\Traversable $parts,\n array $config = []\n ) {\n $this->client = $client;\n $this->state = $state;\n $this->parts = $parts;\n $this->config = $config;\n }\n\n public function __invoke($concurrency = 1, callable $before = null)\n {\n return $this->upload($concurrency, $before);\n }\n\n /**\n * Returns the current state of the upload\n *\n * @return UploadState\n */\n public function getState()\n {\n return $this->state;\n }\n\n /**\n * Abort the multipart upload.\n *\n * @return Result\n * @throws \\LogicException if the upload has not been initiated yet.\n * @throws MultipartUploadException if the abort operation fails.\n */\n public function abort()\n {\n if (!$this->state->isInitiated()) {\n throw new \\LogicException('The upload has not been initiated.');\n }\n\n try {\n $result = $this->client->execute($this->createCommand('abort'));\n $this->state->setStatus(UploadState::ABORTED);\n return $result;\n } catch (AwsException $e) {\n throw new MultipartUploadException($this->state, 'aborting', $e);\n }\n }\n\n /**\n * Initiate the multipart upload.\n *\n * @throws MultipartUploadException if the initiate operation fails.\n */\n private function initiate()\n {\n try {\n $result = $this->client->execute($this->createCommand('initiate'));\n $params = $this->state->getUploadId();\n $params[$this->config['id'][2]] = $result[$this->config['id'][2]];\n $this->state->setStatus(UploadState::INITIATED, $params);\n } catch (AwsException $e) {\n throw new MultipartUploadException($this->state, 'initiating', $e);\n }\n }\n\n /**\n * Complete the multipart upload.\n *\n * @return Result\n * @throws MultipartUploadException if the complete operation fails.\n */\n private function complete()\n {\n try {\n $result = $this->client->execute($this->createCommand('complete',\n $this->config['fn']['complete']()\n ));\n $this->state->setStatus(UploadState::COMPLETED);\n return $result;\n } catch (AwsException $e) {\n throw new MultipartUploadException($this->state, 'completing', $e);\n }\n }\n\n /**\n * Upload the source to S3 using multipart upload operations.\n *\n * @param int $concurrency Number of parts that the Uploader will upload\n * concurrently (in parallel). This defaults to 1. You may need to do\n * some experimenting to find the most optimum concurrency value\n * for your system, but using 20-25 usually yields decent results.\n * @param callable|null $before Callback to execute before each upload.\n * This callback will receive a PreparedEvent object as its argument.\n *\n * @return Result The result of the CompleteMultipartUpload operation.\n * @throws \\LogicException if the upload is already complete or aborted.\n * @throws MultipartUploadException if an upload operation fails.\n */\n public function upload($concurrency = 1, callable $before = null)\n {\n // Ensure the upload is in a valid state for uploading parts.\n if (!$this->state->isInitiated()) {\n $this->initiate();\n } elseif ($this->state->isCompleted()) {\n throw new \\LogicException('The upload has been completed.');\n } elseif ($this->state->isAborted()) {\n throw new \\LogicException('This upload has been aborted.');\n }\n\n // Create iterator that will yield UploadPart commands for each part.\n $commands = t\\to_iter($this->parts, t\\map(function (array $partData) {\n return $this->createCommand('upload', $partData);\n }));\n\n // Execute the commands in parallel and process results. This collects\n // unhandled errors along the way and throws an exception at the end\n // that contains the state and a list of the failed parts.\n $errors = [];\n $this->client->executeAll($commands, [\n 'pool_size' => $concurrency,\n 'prepared' => $before,\n 'process' => [\n 'fn' => function (ProcessEvent $event) use (&$errors) {\n $command = $event->getCommand();\n $partNumber = $command[$this->config['part']['param']];\n if ($ex = $event->getException()) {\n $errors[$partNumber] = $ex->getMessage();\n } else {\n unset($errors[$partNumber]);\n $this->config['fn']['result']($command, $event->getResult());\n }\n },\n 'priority' => 'last'\n ]\n ]);\n\n if ($errors) {\n throw new MultipartUploadException($this->state, $errors);\n }\n\n return $this->complete();\n }\n\n /**\n * Creates a command with all of the relevant parameters from the operation\n * name and an array of additional parameters.\n *\n * @param string $operation Name of the operation (e.g., UploadPart).\n * @param array $computedParams Extra params not stored in the Uploader.\n *\n * @return Command\n */\n private function createCommand($operation, array $computedParams = [])\n {\n $configuredParams = $this->state->getUploadId() + $this->config[$operation]['params'];\n\n return $this->client->getCommand(\n $this->config[$operation]['command'],\n $computedParams + $configuredParams\n );\n }\n}\n" }, { "alpha_fraction": 0.5510241985321045, "alphanum_fraction": 0.553607702255249, "avg_line_length": 28.451086044311523, "blob_id": "5445fd54a2ee3a92ae07c2e3c7834394e35caa85", "content_id": "b41f19cab95651f00022f4c505b59ef639bc412d", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 5419, "license_type": "permissive", "max_line_length": 79, "num_lines": 184, "path": "/src/S3/ClearBucket.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\S3;\n\nuse Aws\\AwsClientInterface;\nuse Aws\\S3\\Exception\\ClearBucketException;\nuse Aws\\S3\\Exception\\DeleteMultipleObjectsException;\n\n/**\n * Deletes objects from a bucket.\n *\n * This class can be used to efficiently delete all objects of a bucket or\n * to delete only objects yielded by an iterator.\n *\n * If an error occurs while deleting objects, a ClearBucketException is thrown.\n * This exception allows you to resume the transfer if needed by inspecting the\n * failures and using the same iterator to continue deleting objects. The\n * iterator is not rewound in this class, so you can utilize non-seekable\n * iterators like Generators and still recover from failure.\n */\nclass ClearBucket\n{\n /** @var AwsClientInterface */\n private $client;\n\n /** @var \\Iterator */\n private $iterator;\n\n private $options = [];\n private $batchSize = 1000;\n private $before;\n\n /**\n * This function accepts a hash of options:\n *\n * - iterator: An \\Iterator instance that yields associative arrays that\n * contain a 'Key' and optional 'VersionId'.\n * - before: Callable to invoke before each delete is called. This callable\n * accepts the underlying iterator being used and an array of the keys\n * that are about to be deleted.\n * - batch_size: The size of each delete batch. Defaults to 1000.\n * - mfa: MFA token used when contacting the Amazon S3 API.\n *\n * @param AwsClientInterface $client Client used to execute requests\n * @param string $bucket Name of the bucket to delete from\n * @param array $options Hash of options used with the class\n * @throws \\InvalidArgumentException if the provided iterator is invalid\n */\n public function __construct(\n AwsClientInterface $client,\n $bucket,\n array $options = []\n ) {\n $this->client = $client;\n $this->bucket = $bucket;\n $this->handleOptions($options);\n\n if (!$this->iterator) {\n $this->iterator = $this->client->getIterator('ListObjects', [\n 'Bucket' => $this->bucket\n ]);\n }\n }\n\n /**\n * Removes the keys from the bucket that are yielded from the underlying\n * iterator.\n *\n * WARNING: If no iterator was provided in the constructor, then ALL keys\n * will be removed from the bucket!\n *\n * @throws ClearBucketException if an error occurs while transferring\n */\n public function clear()\n {\n $batch = new BatchDelete($this->client, $this->bucket, $this->options);\n\n while ($this->iterator->valid()) {\n\n $object = $this->validateObject($this->iterator->current());\n $batch->addObject(\n $object['Key'],\n isset($object['VersionId']) ? $object['VersionId'] : null\n );\n\n if (count($batch) >= $this->batchSize) {\n $this->sendBatch($batch);\n }\n\n $this->iterator->next();\n }\n\n if (count($batch)) {\n $this->sendBatch($batch);\n }\n }\n\n /**\n * Validate the provided options.\n *\n * Gets the iterator from the options hash or creates one to delete all\n * objects from the bucket.\n *\n * @throws \\InvalidArgumentException if invalid options are provided.\n */\n private function handleOptions(array $options)\n {\n // Double dispatch on each provided option\n foreach ($options as $key => $value) {\n if (!method_exists($this, \"handle_{$key}\")) {\n throw new \\InvalidArgumentException(\n \"Invalid option provided: $key\"\n );\n }\n $this->{\"handle_{$key}\"}($value);\n }\n }\n\n private function handle_iterator($value)\n {\n if (!($value instanceof \\Iterator)) {\n throw new \\InvalidArgumentException('iterator must be an '\n . 'instance of Iterator');\n }\n\n $this->iterator = $value;\n }\n\n private function handle_batch_size($value)\n {\n if ($value <= 0) {\n throw new \\InvalidArgumentException('batch_size must be > 0');\n }\n\n $this->batchSize = $this->options['batch_size'] = $value;\n }\n\n private function handle_before($value)\n {\n $this->before = $value;\n }\n\n private function handle_mfa($value)\n {\n $this->options['mfa'] = $value;\n }\n\n private function validateObject($object)\n {\n if (is_array($object) && isset($object['Key'])) {\n return $object;\n }\n\n throw new ClearBucketException(\n [\n [\n 'Key' => null,\n 'Message' => 'Invalid value returned from iterator',\n 'Value' => $object\n ]\n ],\n $this->iterator\n );\n }\n\n private function sendBatch(BatchDelete $batch)\n {\n try {\n if ($this->before) {\n call_user_func(\n $this->before,\n $this->iterator,\n $batch->getQueue()\n );\n }\n $batch->delete();\n } catch (DeleteMultipleObjectsException $e) {\n throw new ClearBucketException(\n $e->getErrors(),\n $this->iterator,\n $e\n );\n }\n }\n}\n" }, { "alpha_fraction": 0.5040783286094666, "alphanum_fraction": 0.5040783286094666, "avg_line_length": 24.54166603088379, "blob_id": "5745dbbd809458479aa19f25acc25a1b83adcb6a", "content_id": "d7a355fa8daaec7839fbcb04ddb43be27dc5bcc5", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 613, "license_type": "permissive", "max_line_length": 40, "num_lines": 24, "path": "/src/data/elastictranscoder-2012-09-25.paginators.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php return [\n 'pagination' => [\n 'ListJobsByPipeline' => [\n 'input_token' => 'PageToken',\n 'output_token' => 'NextPageToken',\n 'result_key' => 'Jobs',\n ],\n 'ListJobsByStatus' => [\n 'input_token' => 'PageToken',\n 'output_token' => 'NextPageToken',\n 'result_key' => 'Jobs',\n ],\n 'ListPipelines' => [\n 'input_token' => 'PageToken',\n 'output_token' => 'NextPageToken',\n 'result_key' => 'Pipelines',\n ],\n 'ListPresets' => [\n 'input_token' => 'PageToken',\n 'output_token' => 'NextPageToken',\n 'result_key' => 'Presets',\n ],\n ],\n];\n" }, { "alpha_fraction": 0.49373432993888855, "alphanum_fraction": 0.49373432993888855, "avg_line_length": 23.9375, "blob_id": "81919ffe4eb04221a358bdcd7ac6e4e2706e499b", "content_id": "087178cc3f203a3aeb1950ae58f0bfeeecb97d84", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 399, "license_type": "permissive", "max_line_length": 41, "num_lines": 16, "path": "/src/data/lambda-2014-11-11.paginators.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php return [\n 'pagination' => [\n 'ListEventSources' => [\n 'input_token' => 'Marker',\n 'output_token' => 'NextMarker',\n 'limit_key' => 'MaxItems',\n 'result_key' => 'EventSources',\n ],\n 'ListFunctions' => [\n 'input_token' => 'Marker',\n 'output_token' => 'NextMarker',\n 'limit_key' => 'MaxItems',\n 'result_key' => 'Functions',\n ],\n ],\n];\n" }, { "alpha_fraction": 0.5368978977203369, "alphanum_fraction": 0.54131680727005, "avg_line_length": 27.287500381469727, "blob_id": "7130fabb5978ef68806505eb72836eae0af70238", "content_id": "24d97fafaa8b683d4c3c51f845665a6ea2cea175", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2263, "license_type": "permissive", "max_line_length": 95, "num_lines": 80, "path": "/tests/Subscriber/SourceFileTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\TestCommon\\Subscriber;\n\nuse Aws\\Test\\UsesServiceTrait;\nuse GuzzleHttp\\Subscriber\\History;\nuse GuzzleHttp\\Subscriber\\Mock;\nuse GuzzleHttp\\Message\\Response;\n\n/**\n * @covers Aws\\Subscriber\\SourceFile\n */\nclass SourceFileTest extends \\PHPUnit_Framework_TestCase\n{\n use UsesServiceTrait;\n\n public function testAddsUploadBody()\n {\n $history = new History();\n $client = $this->getTestClient('s3');\n $httpClient = $client->getHttpClient();\n $httpClient->getEmitter()->attach(new Mock([new Response(200)]));\n $httpClient->getEmitter()->attach($history);\n\n $client->putObject([\n 'Bucket' => 'foo',\n 'Key' => 'bar',\n 'SourceFile' => __FILE__\n ]);\n\n $this->assertEquals(\n file_get_contents(__FILE__),\n (string) $history->getLastRequest()->getBody()\n );\n }\n\n public function testDoesNotModifyExistingBody()\n {\n $history = new History();\n $client = $this->getTestClient('s3');\n $httpClient = $client->getHttpClient();\n $httpClient->getEmitter()->attach(new Mock([new Response(200)]));\n $httpClient->getEmitter()->attach($history);\n\n $client->putObject([\n 'Bucket' => 'foo',\n 'Key' => 'bar',\n 'Body' => 'foo'\n ]);\n\n $this->assertEquals(\n 'foo',\n (string) $history->getLastRequest()->getBody()\n );\n }\n\n public function testEnsuresBodyParamExists()\n {\n $client = $this->getTestClient('s3');\n $this->addMockResults($client, [[]]);\n $command = $client->getObject([\n 'Bucket' => 'foo',\n 'Key' => 'bar',\n 'SourceFile' => __FILE__\n ]);\n $this->assertNull($command['Body']);\n }\n\n /**\n * @expectedException \\Aws\\Exception\\AwsException\n * @expectedExceptionMessage Unable to open /tmp/foo/baz/bar/_doesNotExist.txt using mode r\n */\n public function testEnsuresSourceParamExists()\n {\n $this->getTestClient('s3')->putObject([\n 'Bucket' => 'foo',\n 'Key' => 'bar',\n 'SourceFile' => '/tmp/foo/baz/bar/_doesNotExist.txt'\n ]);\n }\n}\n" }, { "alpha_fraction": 0.4593496024608612, "alphanum_fraction": 0.46341463923454285, "avg_line_length": 21.363636016845703, "blob_id": "8c191e101004d616d79529495365ace338ad43dd", "content_id": "2d24a6bc525066297b7b736df456ad3d98850125", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 246, "license_type": "permissive", "max_line_length": 41, "num_lines": 11, "path": "/src/data/importexport-2010-06-01.paginators.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php return [\n 'pagination' => [\n 'ListJobs' => [\n 'input_token' => 'Marker',\n 'output_token' => 'Jobs[-1].JobId',\n 'more_results' => 'IsTruncated',\n 'limit_key' => 'MaxJobs',\n 'result_key' => 'Jobs',\n ],\n ],\n];\n" }, { "alpha_fraction": 0.6487320065498352, "alphanum_fraction": 0.6579849123954773, "avg_line_length": 31.422222137451172, "blob_id": "7e123cd3472047433fc3d6d7a0fae9318780a83e", "content_id": "3e0b9a9b4f06e23df2ec6c602144d2a8a4cb01f4", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 2918, "license_type": "permissive", "max_line_length": 120, "num_lines": 90, "path": "/docs/service-sts.rst", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "=============\nAWS STS Guide\n=============\n\n.. note::\n\n For information about why you might need to use temporary credentials in your application or project, see\n `Scenarios for Granting Temporary Access <http://docs.aws.amazon.com/STS/latest/UsingSTS/STSUseCases.html>`_ in the\n AWS STS documentation.\n\nGetting Temporary Credentials\n-----------------------------\n\nAWS STS has five operations that return temporary credentials: ``AssumeRole``, ``AssumeRoleWithWebIdentity``,\n``AssumeRoleWithSAML``, ``GetFederationToken``, and ``GetSessionToken``. Using the ``GetSessionToken`` operation is\ntrivial, so let's use that one as an example.\n\n.. code-block:: php\n\n $result = $client->getSessionToken();\n\nThe result for ``GetSessionToken`` and the other AWS STS operations always contains a ``'Credentials'`` value. If you\nprint the result (e.g., ``print_r($result)``), it looks like the following:\n\n.. code-block:: php\n\n Array\n (\n ...\n [Credentials] => Array\n (\n [SessionToken] => '<base64 encoded session token value>'\n [SecretAccessKey] => '<temporary secret access key value>'\n [Expiration] => 2013-11-01T01:57:52Z\n [AccessKeyId] => '<temporary access key value>'\n )\n ...\n )\n\nUsing Temporary Credentials\n---------------------------\n\nYou can use temporary credentials with another AWS client by instantiating the client and passing in the values received\nfrom AWS STS directly.\n\n.. code-block:: php\n\n use Aws\\S3\\S3Client;\n\n $result = $client->getSessionToken();\n\n $s3 = S3Client::factory(array(\n 'key' => $result['Credentials']['AccessKeyId'],\n 'secret' => $result['Credentials']['SecretAccessKey'],\n 'token' => $result['Credentials']['SessionToken'],\n ));\n\nYou can also construct a ``Credentials`` object and use that when instantiating the client.\n\n.. code-block:: php\n\n use Aws\\Common\\Credentials\\Credentials;\n use Aws\\S3\\S3Client;\n\n $result = $client->getSessionToken();\n\n $credentials = new Credentials(\n $result['Credentials']['AccessKeyId'],\n $result['Credentials']['SecretAccessKey'],\n $result['Credentials']['SessionToken']\n );\n\n $s3 = S3Client::factory(array('credentials' => $credentials));\n\nHowever, the *best* way to provide temporary credentials is to use the ``createCredentials()`` helper method included\nwith ``StsClient``. This method extracts the data from an AWS STS result and creates the ``Credentials`` object for you.\n\n.. code-block:: php\n\n $result = $sts->getSessionToken();\n $credentials = $sts->createCredentials($result);\n\n $s3 = S3Client::factory(array('credentials' => $credentials));\n\nYou can also use the same technique when setting credentials on an existing client object.\n\n.. code-block:: php\n\n $credentials = $sts->createCredentials($sts->getSessionToken());\n $s3->setCredentials($credentials);\n" }, { "alpha_fraction": 0.5429156422615051, "alphanum_fraction": 0.5614855885505676, "avg_line_length": 33.3668327331543, "blob_id": "e9c63bba7416adf7223d23796bbdab96f4ad593a", "content_id": "60b2bcc80bec85231cd9a23e10b1d37a8659f6a5", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 6839, "license_type": "permissive", "max_line_length": 85, "num_lines": 199, "path": "/tests/Glacier/UploadBuilderTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\n\nnamespace Aws\\Test\\Glacier;\n\nuse Aws\\Glacier\\TreeHash;\nuse Aws\\Multipart\\UploadState;\nuse Aws\\Glacier\\UploadBuilder;\nuse Aws\\Result;\nuse Aws\\Test\\UsesServiceTrait;\nuse GuzzleHttp\\Stream\\Stream;\n\n/**\n * @covers Aws\\Glacier\\UploadBuilder\n */\nclass UploadBuilderTest extends \\PHPUnit_Framework_TestCase\n{\n use UsesServiceTrait;\n\n public function testCanCreateBuilder()\n {\n $builder = (new UploadBuilder)\n ->setClient($this->getMock('Aws\\AwsClientInterface'))\n ->setSource(__FILE__)\n ->setAccountId('foo')\n ->setVaultName('bar')\n ->setArchiveDescription('baz');\n $builder2 = clone $builder;\n\n $uploader = $builder->build();\n $config = $this->readAttribute($uploader, 'config');\n $params = $config['initiate']['params'];\n $this->assertInstanceOf('Aws\\Multipart\\Uploader', $uploader);\n $this->assertArrayHasKey('archiveDescription', $params);\n $this->assertArrayHasKey('partSize', $params);\n\n $builder2->setUploadId('baz');\n $this->assertEquals(\n ['accountId' => 'foo', 'vaultName' => 'bar', 'uploadId' => 'baz'],\n $this->readAttribute($builder2, 'uploadId')\n );\n }\n\n public function testThrowsExceptionOnBadPartSize()\n {\n $uploader = (new UploadBuilder)\n ->setClient($this->getMock('Aws\\AwsClientInterface'))\n ->setSource(__FILE__)\n ->setVaultName('foo')\n ->setPartSize(1024);\n\n $this->setExpectedException('InvalidArgumentException');\n $uploader->build();\n }\n\n public function testCanLoadStateFromUploadId()\n {\n $client = $this->getTestClient('glacier');\n $this->addMockResults($client, [\n new Result([\n 'PartSizeInBytes' => 1048576,\n 'Parts' => [\n ['RangeInBytes' => '0-1048575', 'SHA256TreeHash' => 'foo'],\n ['RangeInBytes' => '1048576-2097151', 'SHA256TreeHash' => 'bar'],\n ]\n ])\n ]);\n\n $builder = (new UploadBuilder)->setClient($client);\n $method = (new \\ReflectionObject($builder))\n ->getMethod('loadStateByUploadId');\n $method->setAccessible(true);\n /** @var UploadState $state */\n $state = $method->invoke($builder, [\n 'accountId' => '-',\n 'vaultName' => 'foo',\n 'uploadId' => 'bar'\n ]);\n\n $part = $state->getUploadedParts()[2];\n $this->assertEquals(1048576, $part['size']);\n $this->assertEquals('bar', $part['checksum']);\n }\n\n public function testCanCreatePartGeneratorCallback()\n {\n $source = Stream::factory('foo');\n $state = new UploadState([]);\n $state->setPartSize(5);\n $builder = (new UploadBuilder)\n ->setClient($this->getTestClient('glacier'))\n ->setState($state)\n ->setSource($source);\n\n $method = (new \\ReflectionObject($builder))\n ->getMethod('getCreatePartFn');\n $method->setAccessible(true);\n /** @var callable $createPart */\n $createPart = $method->invoke($builder);\n\n $data = $createPart(true);\n // Range is an odd value here, because we are using a non-file stream\n $this->assertEquals('bytes 0--1/*', $data['range']);\n $this->assertInstanceOf('GuzzleHttp\\Stream\\LimitStream', $data['body']);\n\n $source->seek(0);\n $data = $createPart(false);\n $this->assertEquals('bytes 0-2/*', $data['range']);\n $this->assertInstanceOf('GuzzleHttp\\Stream\\Stream', $data['body']);\n $this->assertArrayHasKey('checksum', $data);\n $this->assertArrayHasKey('ContentSHA256', $data);\n }\n\n public function testCanParseARange()\n {\n $builder = new UploadBuilder;\n $method = (new \\ReflectionObject($builder))->getMethod('parseRange');\n $method->setAccessible(true);\n $data = $method->invoke($builder, 'bytes 2097152-4194303/*', 2097152);\n $this->assertEquals(2097152, $data['Size']);\n $this->assertEquals(2, $data['PartNumber']);\n }\n\n public function testCallbackCreatesCorrectCompleteCommandParams()\n {\n // Create dummy hashes.\n $checksums = [\n hash('sha256', 'a'),\n hash('sha256', 'b'),\n hash('sha256', 'c'),\n ];\n $treeHash = new TreeHash();\n foreach ($checksums as $checksum) {\n $treeHash->addChecksum($checksum);\n }\n $expectedChecksum = bin2hex($treeHash->complete());\n\n // Prepare state.\n $state = new UploadState([]);\n $parts = [\n 1 => ['size' => 3, 'checksum' => $checksums[0]],\n 2 => ['size' => 1, 'checksum' => $checksums[1]],\n 3 => ['size' => 5, 'checksum' => $checksums[2]],\n ];\n foreach ($parts as $number => $data) {\n $state->markPartAsUploaded($number, $data);\n }\n\n // Prepare builder.\n $builder = (new UploadBuilder)\n ->setClient($this->getTestClient('s3'))\n ->setState($state)\n ->setSource(Stream::factory('foo'));\n\n // Get the function.\n $method = (new \\ReflectionObject($builder))\n ->getMethod('getCompleteParamsFn');\n $method->setAccessible(true);\n /** @var callable $getCommandParams */\n $getCommandParams = $method->invoke($builder);\n \n // Validate function results.\n $params = $getCommandParams();\n $this->assertEquals(9, $params['archiveSize']);\n $this->assertEquals($expectedChecksum, $params['checksum']);\n }\n\n public function testCallbackHandlesResultsOfUploadPart()\n {\n $state = new UploadState([]);\n $state->setPartSize(2097152);\n\n $builder = (new UploadBuilder)\n ->setClient($this->getTestClient('s3'))\n ->setState($state)\n ->setSource(Stream::factory('foo'));\n\n $method = (new \\ReflectionObject($builder))\n ->getMethod('getResultHandlerFn');\n $method->setAccessible(true);\n /** @var callable $handleResult */\n $handleResult = $method->invoke($builder);\n\n // Mock arguments.\n $command = $this->getMockBuilder('GuzzleHttp\\Command\\Command')\n ->disableOriginalConstructor()\n ->getMock();\n $command->method('offsetGet')\n ->willReturnOnConsecutiveCalls('0-2097151', 'foo');\n $result = $this->getMockBuilder('Aws\\Result')\n ->disableOriginalConstructor()\n ->getMock();\n\n $handleResult($command, $result);\n\n $uploadedParts = $state->getUploadedParts();\n $this->assertTrue(isset($uploadedParts[1]['checksum']));\n $this->assertEquals('foo', $uploadedParts[1]['checksum']);\n }\n}\n" }, { "alpha_fraction": 0.7297531366348267, "alphanum_fraction": 0.7444481253623962, "avg_line_length": 41.95389938354492, "blob_id": "0aa9eb5ef5dc4c0700461847f9c9ccf976854845", "content_id": "4154ae3234de69a2f849719f38a10265757c4261", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 24230, "license_type": "permissive", "max_line_length": 166, "num_lines": 564, "path": "/UPGRADING.md", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "Upgrading Guide\n===============\n\nUpgrade from 2.x to 3.x\n-----------------------\n\nVersion 3 is a new major version of the SDK that represents a lot of new work\nand refactoring. While the fundamental way the you use the SDK has not changed,\nthere are changes in several parts to accomplish our goals, including adding\nnew functionality, improving performance, simplifying interfaces, and\nreducing bloat.\n\n### Dependencies\n\n* **PHP 5.5+** - PHP version 5.5 or higher is now required, because the SDK and\n its dependencies use various PHP 5.4/5.5 features including traits,\n generators, and `callable` typehints,\n* **[Guzzle 5](http://guzzlephp.org/)** - The underlying HTTP library for the\n SDK. The update from Guzzle 3 to Guzzle 5 provides many of the new features of\n the SDK, including async requests, the new event system, the \"debug\" client\n option, and more.\n* **[jmespath.php](https://github.com/jmespath/jmespath.php)** - Provides the\n ability to query Result data, especially deeply nested results. It implements\n the [JMESPath specification](http://jmespath.org/), which is also supported\n by the [AWS CLI](https://github.com/aws/aws-cli).\n\n### SDK instantiation and configuration\n\nVersion 3 of the SDK introduces the `Aws\\Sdk` class to replace `Aws\\Common\\Aws`.\nThe `Sdk` class does extend from Guzzle and does not act as a service locator.\nIt does act as a client factory though, and you can use it to create a service\nclient.\n\n```php\n$aws = new \\Aws\\Sdk();\n\n// Use the getClient method to instantiate a client.\n$aws->getClient('s3', [\n // Provide client options.\n 'region' => 'us-west-2',\n 'version' => '2006-03-01',\n]);\n\n// OR... you can use the magic methods that have IDE autocompletion.\n$aws->getS3([\n // Provide client options.\n 'region' => 'us-west-2',\n 'version' => 'latest',\n]);\n```\n\nThe client options are a little different from the Version 2 options. Please see\nthe [API docs for `Aws\\Sdk::getClient()`](http://docs.aws.amazon.com/aws-sdk-php/v3/api/Aws/Sdk.html#method_getClient)\nfor a list of the client options.\n\nYou can also, pass client options to the constructor of `Aws\\Sdk`. These options\nwill be global options to all clients created with this instance of the `Sdk`\nobject. They can be overwritten when calling the `getClient()` method as above.\n\n```php\n$aws = new \\Aws\\Sdk([\n 'region' => 'us-west-2',\n 'version' => 'latest',\n]);\n\n// Will use global client options.\n$dynamoDb = $aws->getDynamoDb();\n\n// Will use global client options, but will overwrite the region.\n$dynamoDb = $aws->getDynamoDb([\n 'region' => 'ap-northeast-1',\n]);\n```\n\nYou can add service-specific global options by using the service name as a key\nin the options.\n\n```php\n$aws = new \\Aws\\Sdk([\n 'region' => 'us-west-2',\n 'version' => 'latest',\n 'dynamodb' => [\n 'region' => 'ap-northeast-1',\n ]\n]);\n```\n\n#### Creating clients\n\nUsing the `factory()` method of a client is now deprecated. v3 of the SDK now\nallows you to create clients using the `new` operator:\n\n```php\n$client = new \\Aws\\S3\\S3Client([\n 'region' => 'us-west-2',\n 'version' => '2006-03-01'\n]);\n```\n\n#### The `version` client option\n\nYou are required to provide the API version when you instantiate a client. This\nis important, because it allows you to lock-in to the API versions of the\nservices you are using. This helps the SDK and you maintain backward\ncompatibility between future SDK releases, because you will be in control of\nwhich API versions you are using. Your code will never be impacted by new\nservice API versions until you update your version setting. If this is not a\nconcern for you, you can default to the latest API version by setting\n`'version'` to `'latest'` (this is essentially the default behavior of V2).\n\n### Removal of Enum classes\n\nEnums in Version 2 of the SDK (e.g., `Aws\\S3\\Enum\\CannedAcl`) were concrete\nclasses within the public API of the SDK that contained constants representing\ngroups of valid parameter values to use when making calls to various service\noperations. We thought at the time, that these would be helpful to customers,\nbut we quickly ran into issues.\n\n1. **Enum values change over time** - Services add and remove enum values from\n their APIs over time. Sometimes services make backward-incompatible changes\n to their API (they change their API version, and the SDK has to support both\n versions). We have to make sure the Enum classes are backward-compatible,\n even if the services' APIs change. Because of this, many Enum classes in\n Version 2 contain constants that may or may not be valid, depending on which\n version of the API you are using.\n\n2. **Some Enum values are reserved words in PHP** - Some service APIs end up\n declaring Enum values that are named the same as a reserved word in PHP. In\n those cases, we have to change the name to something else in order to put it\n in an enum class. This makes some of the Version 2 enum classes inconsistent\n with the actual service's API.\n\n3. **Enum classes add bloat to the SDK** - There are over 150 Enum classes in\n Version 2.\n\n4. **Statically generated enum classes conflict with our dynamically driven API\n model approach.** - The SDK currently supports multiple API versions based on\n a user-supplied \"version\" parameter. By statically generating enum classes,\n we are locking those enum classes to a specific API version, while at the\n same time, promising that you can change the API version of a client at\n runtime. These two things are not compatible with one another.\n\n5. **Enum classes provide little to no value**\n\n 1. Enum classes required you to know about and import (via use) them before\n you could actually use them.\n 2. They provided autocomplete support, but only for IDE-using customers, and\n only in the case where you know which enum to use for nested API\n parameters.\n 3. There is no way to indicate which Enums are used with each operation and\n to which parameters.\n 4. Writing out an Enum value is longer than writing the actual value (e.g.,\n `CannedAcl::PUBLIC_READ` vs. ``'public-read'``).\n 5. The constant name is basically the same as the literal string value, so\n the constant isn't actually abstracting anything.\n\nBecause of these issues, we decided that we needed to remove Enums. For V2, we\nstopped updating them and stopped documenting them, and in V3, we have\nremoved them completely.\n\n### Removal of fine-grained Exception classes\n\nWe have removed the fine-grained exception classes that lived in the each of the\nservices namespaces (e.g., `Aws\\Rds\\Exception\\{SpecificErrorCase}Exception`) for\nvery similar reasons that we removed Enums. The exceptions thrown by a\nservice/operation are dependent on which API version (i.e, they can change from\nversion to version) is used. Also, we are not technically able to provide the\ncomplete list of what exceptions can be thrown by a given operation (long\nstory). This makes the fine-grained exception classes fairly useless.\n\nSimilarly to Enums, we have not been updating these classes in V2 for several\nmonths, and have already removed them from our documentation.\n\nYou should handle errors by catching the root exception class for each service\n(e.g. `Aws\\Rds\\Exception\\RdsException`). You can use the `getAwsErrorCode()`\nmethod (formerly called `getExceptionCode()` in V2) of the exception to check\nfor specific error codes. This is functionally equivalent to catching different\nexception classes, but provides that function without adding bloat to the SDK or\nsetting false expectations.\n\n### Some API results have changed\n\nIn order to provide consistency in how the SDK parses the result of an API\noperation, Amazon ElastiCache, Amazon RDS, and Amazon RedShift now have an\nadditional wrapping element on some API responses.\n\nFor example, calling Amazon RDS's [DescribeEngineDefaultParameters](http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_DescribeEngineDefaultParameters.html)\nresult in v3 now includes a wrapping \"EngineDefaults\" element whereas in v2\nthis element was not present.\n\n```php\n$client = new Aws\\Rds\\RdsClient([\n 'region' => 'us-west-1',\n 'version' => '2014-09-01'\n]);\n\n// Version 2:\n$result = $client->describeEngineDefaultParameters();\n$family = $result['DBParameterGroupFamily'];\n$marker = $result['Marker'];\n\n// Version 3:\n$result = $client->describeEngineDefaultParameters();\n$family = $result['EngineDefaults']['DBParameterGroupFamily'];\n$marker = $result['EngineDefaults']['Marker'];\n```\n\nThe following operations are affected and now contain a wrapping element in the\noutput of the result (provided below in parenthesis):\n\n- Amazon ElastiCache\n - AuthorizeCacheSecurityGroupIngress (CacheSecurityGroup)\n - CopySnapshot (Snapshot)\n - CreateCacheCluster (CacheCluster)\n - CreateCacheParameterGroup (CacheParameterGroup)\n - CreateCacheSecurityGroup (CacheSecurityGroup)\n - CreateCacheSubnetGroup (CacheSubnetGroup)\n - CreateReplicationGroup (ReplicationGroup)\n - CreateSnapshot (Snapshot)\n - DeleteCacheCluster (CacheCluster)\n - DeleteReplicationGroup (ReplicationGroup)\n - DeleteSnapshot (Snapshot)\n - DescribeEngineDefaultParameters (EngineDefaults)\n - ModifyCacheCluster (CacheCluster)\n - ModifyCacheSubnetGroup (CacheSubnetGroup)\n - ModifyReplicationGroup (ReplicationGroup)\n - PurchaseReservedCacheNodesOffering (ReservedCacheNode)\n - RebootCacheCluster (CacheCluster)\n - RevokeCacheSecurityGroupIngress (CacheSecurityGroup)\n- Amazon RDS\n - AddSourceIdentifierToSubscription (EventSubscription)\n - AuthorizeDBSecurityGroupIngress (DBSecurityGroup)\n - CopyDBParameterGroup (DBParameterGroup)\n - CopyDBSnapshot (DBSnapshot)\n - CopyOptionGroup (OptionGroup)\n - CreateDBInstance (DBInstance)\n - CreateDBInstanceReadReplica (DBInstance)\n - CreateDBParameterGroup (DBParameterGroup)\n - CreateDBSecurityGroup (DBSecurityGroup)\n - CreateDBSnapshot (DBSnapshot)\n - CreateDBSubnetGroup (DBSubnetGroup)\n - CreateEventSubscription (EventSubscription)\n - CreateOptionGroup (OptionGroup)\n - DeleteDBInstance (DBInstance)\n - DeleteDBSnapshot (DBSnapshot)\n - DeleteEventSubscription (EventSubscription)\n - DescribeEngineDefaultParameters (EngineDefaults)\n - ModifyDBInstance (DBInstance)\n - ModifyDBSubnetGroup (DBSubnetGroup)\n - ModifyEventSubscription (EventSubscription)\n - ModifyOptionGroup (OptionGroup)\n - PromoteReadReplica (DBInstance)\n - PurchaseReservedDBInstancesOffering (ReservedDBInstance)\n - RebootDBInstance (DBInstance)\n - RemoveSourceIdentifierFromSubscription (EventSubscription)\n - RestoreDBInstanceFromDBSnapshot (DBInstance)\n - RestoreDBInstanceToPointInTime (DBInstance)\n - RevokeDBSecurityGroupIngress (DBSecurityGroup)\n- Amazon Redshift\n - AuthorizeClusterSecurityGroupIngress (ClusterSecurityGroup)\n - AuthorizeSnapshotAccess (Snapshot)\n - CopyClusterSnapshot (Snapshot)\n - CreateCluster (Cluster)\n - CreateClusterParameterGroup (ClusterParameterGroup)\n - CreateClusterSecurityGroup (ClusterSecurityGroup)\n - CreateClusterSnapshot (Snapshot)\n - CreateClusterSubnetGroup (ClusterSubnetGroup)\n - CreateEventSubscription (EventSubscription)\n - CreateHsmClientCertificate (HsmClientCertificate)\n - CreateHsmConfiguration (HsmConfiguration)\n - DeleteCluster (Cluster)\n - DeleteClusterSnapshot (Snapshot)\n - DescribeDefaultClusterParameters (DefaultClusterParameters)\n - DisableSnapshotCopy (Cluster)\n - EnableSnapshotCopy (Cluster)\n - ModifyCluster (Cluster)\n - ModifyClusterSubnetGroup (ClusterSubnetGroup)\n - ModifyEventSubscription (EventSubscription)\n - ModifySnapshotCopyRetentionPeriod (Cluster)\n - PurchaseReservedNodeOffering (ReservedNode)\n - RebootCluster (Cluster)\n - RestoreFromClusterSnapshot (Cluster)\n - RevokeClusterSecurityGroupIngress (ClusterSecurityGroup)\n - RevokeSnapshotAccess (Snapshot)\n - RotateEncryptionKey (Cluster)\n\n### @TODO\n\nMore will be added to the UPGRADING guide soon about:\n\n- Client objects\n- Waiters and Iterators\n- Service descriptions\n- Result objects\n- Service-specific changes\n\nUpgrade from 2.6 to 2.7\n-----------------------\n\nVersion 2.7 is backward-compatible with version 2.6. The version bump was\nnecessary in order to mark some things in the DynamoDb namespace as deprecated.\nSee the [CHANGELOG entry for 2.7.0](https://github.com/aws/aws-sdk-php/blob/v3/CHANGELOG.md#270-2014-10-08)\nfor more details.\n\nUpgrade from 2.5 to 2.6\n-----------------------\n\n**IMPORTANT:** Version 2.6 *is* backward-compatible with version 2.5, *unless* you are using the Amazon CloudSearch\nclient. If you are using CloudSearch, please read the next section carefully.\n\n### Amazon CloudSearch\n\nVersion 2.6 of the AWS SDK for PHP has been updated to use the 2013-01-01 API version of Amazon CloudSearch by default.\n\nThe 2013-01-01 API marks a significant upgrade of Amazon CloudSearch, but includes numerous breaking changes to the API.\nCloudSearch now supports 33 languages, highlighting, autocomplete suggestions, geospatial search, AWS IAM integration to\ncontrol access to domain configuration actions, and user configurable scaling and availability options. These new\nfeatures are reflected in the changes to the method and parameters of the CloudSearch client.\n\nFor details about the new API and how to update your usage of CloudSearch, please consult the [Configuration API\nReference for Amazon CloudSearch](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuration-api.html)\nand the guide for [Migrating to the Amazon CloudSearch 2013-01-01 API](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/migrating.html).\n\nIf you would like to continue using the older 2011-02-01 API, you can configure this when you instantiate the\n`CloudSearchClient`:\n\n```php\nuse Aws\\CloudSearch\\CloudSearchClient;\n\n$client = CloudSearchClient::factory(array(\n 'key' => '<aws access key>',\n 'secret' => '<aws secret key>',\n 'region' => '<region name>',\n 'version' => '2011-02-01',\n));\n```\n\nUpgrade from 2.4 to 2.5\n-----------------------\n\n### Amazon EC2\n\nA small, backwards-incompatible change has been made to the Amazon EC2 API. The `LaunchConfiguration.MonitoringEnabled`\nparameter of the `RequestSpotInstances` operation has been change to `LaunchConfiguration.Monitoring.Enabled` See [this\ncommit](https://github.com/aws/aws-sdk-php/commit/36ae0f68d2a6dcc3bc28222f60ecb318449c4092#diff-bad2f6eac12565bb684f2015364c22bd)\nfor the exact change. You are only affected by this change if you are using this specific parameter. To fix your code to\nwork with the updated parameter, you will need to change the structure of your request slightly.\n\n```php\n// The OLD way\n$result = $ec2->requestSpotInstances(array(\n // ...\n 'LaunchSpecification' => array(\n // ...\n 'MonitoringEnabled' => true,\n // ...\n ),\n // ...\n));\n\n// The NEW way\n$result = $ec2->requestSpotInstances(array(\n // ...\n 'LaunchSpecification' => array(\n // ...\n 'Monitoring' => array(\n 'Enabled' => true,\n ),\n // ...\n ),\n // ...\n));\n```\n\n### AWS CloudTrail\n\nAWS CloudTrail has made changes to their API. If you are not using the CloudTrail service, then you will not be\naffected by this change.\n\nHere is an excerpt (with minor modifications) directly from the [CloudTrail team's\nannouncement](https://forums.aws.amazon.com/ann.jspa?annID=2286) regarding this change:\n\n> [...] We have made some minor improvements/fixes to the service API, based on early feedback. The impact of these\n> changes to you depends on how you are currently interacting with the CloudTrail service. [...] If you have code that\n> calls the APIs below, you will need to make minor changes.\n>\n> There are two changes:\n>\n> 1) `CreateTrail` / `UpdateTrail`: These APIs originally took a single parameter, a `Trail` object. [...] We have\n> changed this so that you can now simply pass individual parameters directly to these APIs. The same applies to the\n> responses of these APIs, namely the APIs return individual fields directly [...]\n> 2) `GetTrailStatus`: The actual values of the fields returned and their data types were not all as intended. As such,\n> we are deprecating a set of fields, and adding a new set of replacement fields. The following fields are now\n> deprecated, and should no longer be used:\n>\n> * `LatestDeliveryAttemptTime` (String): Time CloudTrail most recently attempted to deliver a file to S3 configured\n> bucket.\n> * `LatestNotificationAttemptTime` (String): As above, but for publishing a notification to configured SNS topic.\n> * `LatestDeliveryAttemptSucceeded` (String): This one had a mismatch between implementation and documentation. As\n> documented: whether or not the latest file delivery was successful. As implemented: Time of most recent successful\n> file delivery.\n> * `LatestNotificationAttemptSucceeded` (String): As above, but for SNS notifications.\n> * `TimeLoggingStarted` (String): Time `StartLogging` was most recently called. [...]\n> * `TimeLoggingStarted` (String): Time `StopLogging` was most recently called.\n>\n> The following fields are new, and replace the fields above:\n>\n> * `LatestDeliveryTime` (Date): Date/Time that CloudTrail most recently delivered a log file.\n> * `LatestNotificationTime` (Date): As above, for SNS notifications.\n> * `StartLoggingTime` (Date): Same as `TimeLoggingStarted`, but with more consistent naming, and correct data type.\n> * `StopLoggingTime` (Date): Same as `TimeLoggingStopped`, but with more consistent naming, and correct data type.\n>\n> Note that `LatestDeliveryAttemptSucceeded` and `LatestNotificationAttemptSucceeded` have no direct replacement. To\n> query whether everything is configured correctly for log file delivery, it is sufficient to query LatestDeliveryError,\n> and if non-empty that means that there is a configuration problem preventing CloudTrail from being able to deliver\n> logs successfully. Basically either the bucket doesn’t exist, or CloudTrail doesn’t have sufficient permissions to\n> write to the configured path in the bucket. Likewise for `LatestNotificationAttemptSucceeded`.\n>\n> The deprecated fields will be removed in the future, no earlier than February 15. Both set of fields will coexist on\n> the service during this period to give those who are using the deprecated fields time to switch over to the use the\n> new fields. However new SDKs and CLIs will remove the deprecated fields sooner than that. Previous SDK and CLI\n> versions will continue to work until the deprecated fields are removed from the service.\n>\n> We apologize for any inconvenience, and appreciate your understanding as we make these adjustments to improve the\n> long-term usability of the CloudTrail APIs.\n\nWe are marking this as a breaking change now, preemptive of the February 15th cutoff, and we encourage everyone to\nupdate their code now. The changes to how you use `createTrail()` and `updateTrail()` are easy changes:\n\n```php\n// The OLD way\n$cloudTrail->createTrail(array(\n 'trail' => array(\n 'Name' => 'TRAIL_NAME',\n 'S3BucketName' => 'BUCKET_NAME',\n )\n));\n\n// The NEW way\n$cloudTrail->createTrail(array(\n 'Name' => 'TRAIL_NAME',\n 'S3BucketName' => 'BUCKET_NAME',\n));\n```\n\n### China (Beijing) Region / Signatures\n\nThis release adds support for the new China (Beijing) Region. This region requires that Signature V4 be used for both\nAmazon S3 and Amazon EC2 requests. We've added support for Signature V4 in both of these services for clients\nconfigured for this region. While doing this work, we did some refactoring to the signature classes and also removed\nsupport for Signature V3, as it is no longer needed. Unless you are explicitly referencing Signature V3 or explicitly\ninteracting with signature objects, these changes should not affect you.\n\nUpgrade from 2.3 to 2.4\n-----------------------\n\n### Amazon CloudFront Client\n\nThe new 2013-05-12 API version of Amazon CloudFront includes support for custom SSL certificates via the\n`ViewerCertificate` parameter, but also introduces breaking changes to the API. Version 2.4 of the SDK now ships with\ntwo versions of the Amazon CloudFront service description, one for the new 2013-05-12 API and one for the next most\nrecent 2012-05-05 API. The SDK defaults to using the newest API version, so CloudFront users may experience a breaking\nchange to their projects when upgrading. This can be easily circumvented by switching back to the 2012-05-05 API by\nusing the `version` option when instantiating the CloudFront client.\n\n### Guzzle 3.7\n\nVersion 2.4 of the AWS SDK for PHP requires at least version 3.7 of Guzzle.\n\nUpgrade from 2.2 to 2.3\n-----------------------\n\n### Amazon DynamoDB Client\n\nThe newly released 2012-08-10 API version of the Amazon DynamoDB service includes the new Local Secondary Indexes\nfeature, but also introduces breaking changes to the API. The most notable change is in the way that you specify keys\nwhen creating tables and retrieving items. Version 2.3 of the SDK now ships with 2 versions of the DynamoDB service\ndescription, one for the new 2012-08-10 API and one for the next most recent 2011-12-05 API. The SDK defaults to using\nthe newest API version, so DynamoDB users may experience a breaking change to their projects when upgrading. This can be\neasily fixed by switching back to the 2011-12-05 API by using the new `version` configuration setting when instantiating\nthe DynamoDB client.\n\n```php\nuse Aws\\DynamoDb\\DynamoDbClient;\n\n$client = DynamoDbClient::factory(array(\n 'key' => '<aws access key>',\n 'secret' => '<aws secret key>',\n 'region' => '<region name>',\n 'version' => '2011-12-05'\n));\n```\n\nIf you are using a config file with `Aws\\Common\\Aws`, then you can modify your file like the following.\n\n```json\n{\n \"includes\": [\"_aws\"],\n \"services\": {\n \"default_settings\": {\n \"params\": {\n \"key\": \"<aws access key>\",\n \"secret\": \"<aws secret key>\",\n \"region\": \"<region name>\"\n }\n },\n \"dynamodb\": {\n \"extends\": \"dynamodb\",\n \"params\": {\n \"version\": \"2011-12-05\"\n }\n }\n }\n}\n```\n\nThe [SDK user guide](http://docs.aws.amazon.com/aws-sdk-php/guide/latest/index.html) has a guide and examples for both\nversions of the API.\n\n### Guzzle 3.4.1\n\nVersion 2.3 of the AWS SDK for PHP requires at least version 3.4.1 of Guzzle.\n\nUpgrade from 2.1 to 2.2\n-----------------------\n\n### Full Service Coverage\n\nThe AWS SDK for PHP now supports the full set of AWS services.\n\n### Guzzle 3.3\n\nVersion 2.2 of the AWS SDK for PHP requires at least version 3.3 of Guzzle.\n\nUpgrade from 2.0 to 2.1\n-----------------------\n\n### General\n\nService descriptions are now versioned under the Resources/ directory of each client.\n\n### Waiters\n\nWaiters now require an associative array as input for the underlying operation performed by a waiter. The configuration\nsystem for waiters under 2.0.x utilized strings to determine the parameters used to create an operation. For example,\nwhen waiting for an object to exist with Amazon S3, you would pass a string containing the bucket name concatenated\nwith the object name using a '/' separator (e.g. 'foo/baz'). In the 2.1 release, these parameters are now more\nexplicitly tied to the underlying operation utilized by a waiter. For example, to use the ObjectExists waiter of\nAmazon S3 pass an associative array of `array('Bucket' => 'foo', 'Key' => 'baz')`. These options match the option names\nand rules associated with the HeadObject operation performed by the waiter. The API documentation of each client\ndescribes the waiters associated with the client and what underlying operation is responsible for waiting on the\nresource. Waiter specific options like the maximum number of attempts (max_attempts) or interval to wait between\nretries (interval) can be specified in this same configuration array by prefixing the keys with `waiter.`.\n\nWaiters can also be invoked using magic methods on the client. These magic methods are listed in each client's docblock\nusing `@method` tags.\n\n```php\n$s3Client->waitUntilObjectExists(array(\n 'Bucket' => 'foo',\n 'Key' => 'bar',\n 'waiter.max_attempts' => 3\n));\n```\n" }, { "alpha_fraction": 0.598317563533783, "alphanum_fraction": 0.608832836151123, "avg_line_length": 20.133333206176758, "blob_id": "c810dc85acd1836d3d4ac88e302c29827c6a8bdc", "content_id": "2a3c49f9fb0e21072b2c6eded30e365964e282fa", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 951, "license_type": "permissive", "max_line_length": 77, "num_lines": 45, "path": "/build/build-apis.sh", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n# Converts a single API file or multiple API files to PHP config files.\n\nset -e\n\nusage() {\n cat <<EOT\nUsage: build-apis [--help] SRC\n\nCopies a source JSON file or directory of JSON files to the API folder as PHP\nconfig files.\n\nOptions:\n --help Displays this help message.\n\nArguments:\n SRC Path to a JSON file, a directory that contains files, or a glob\n that contains JSON files.\nEOT\n}\n\n# Ensure that at least one argument was passed.\n[ $# -eq 0 ] && usage && exit 1\n[ \"$1\" == \"--help\" ] && usage && exit 0\n\n# Get the current script directory.\nDIR=$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\n\nto_php() {\n f=${1:?\"a filename is required\"}\n [ \"$f\" == \".\" ] && return\n topath=\"$DIR/../src/data/`basename $f .json`.php\"\n php json-to-php.php $f > \"$topath\"\n}\n\nmax_jobs=25\ncounter=0\n\nfor f in \"$@\"; do\n to_php $f &\n ((counter++))\n [ $counter -eq \"$max_jobs\" ] && wait\ndone\n\n[ $counter -ne 0 ] && wait\n" }, { "alpha_fraction": 0.5664491653442383, "alphanum_fraction": 0.5705700516700745, "avg_line_length": 35.400001525878906, "blob_id": "38e902cce66be04f284fde47ad50606e57fdc510", "content_id": "4eafb6af83bea2ae82df87e17a18297e78a7dba2", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 5824, "license_type": "permissive", "max_line_length": 90, "num_lines": 160, "path": "/tests/Multipart/AbstractUploadBuilderTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Multipart;\n\nuse Aws\\Multipart\\UploadState;\nuse Aws\\Multipart\\Uploader;\nuse GuzzleHttp\\Stream\\NoSeekStream;\nuse GuzzleHttp\\Stream\\Stream;\n\n/**\n * @covers Aws\\Multipart\\AbstractUploadBuilder\n */\nclass AbstractUploadBuilderTest extends \\PHPUnit_Framework_TestCase\n{\n public function testCanSetOptionsInChainableWay()\n {\n $client = $this->getMockForAbstractClass('Aws\\\\AwsClientInterface');\n $state = new UploadState([]);\n $source = Stream::factory();\n\n $builder = (new TestUploadBuilder)\n ->setClient($client)\n ->setState($state)\n ->setPartSize(5)\n ->addParams('initiate', ['foo' => 'bar', 'fizz' => 'buzz'])\n ->addParams('initiate', ['fuzz' => 'buzz'])\n ->addParams('complete', ['fuzz' => 'buzz'])\n ->setSource($source);\n\n $this->assertSame($client, $this->readAttribute($builder, 'client'));\n $this->assertSame($state, $this->readAttribute($builder, 'state'));\n $this->assertSame($source, $this->readAttribute($builder, 'source'));\n $this->assertEquals(5, $this->readAttribute($builder, 'specifiedPartSize'));\n $this->assertEquals(\n ['foo' => 'bar', 'fizz' => 'buzz', 'fuzz' => 'buzz'],\n $this->readAttribute($builder, 'config')['initiate']['params']\n );\n $this->assertEquals(\n ['fuzz' => 'buzz'],\n $this->readAttribute($builder, 'config')['complete']['params']\n );\n }\n\n public function testCanSetSourceFromFilenameIfExists()\n {\n // CASE 1: Filename exists.\n $builder = (new TestUploadBuilder)->setSource(__FILE__);\n $this->assertInstanceOf(\n 'GuzzleHttp\\Stream\\StreamInterface',\n $this->readAttribute($builder, 'source')\n );\n\n // CASE 2: Filename does not exist.\n $exception = null;\n try {\n $builder->setSource('non-existent-file.foobar');\n } catch (\\InvalidArgumentException $exception) {}\n $this->assertInstanceOf('InvalidArgumentException', $exception);\n\n // CASE 3: Source stream is not readable.\n $exception = null;\n try {\n $builder->setSource(STDERR);\n } catch (\\InvalidArgumentException $exception) {}\n $this->assertInstanceOf('InvalidArgumentException', $exception);\n }\n\n public function testCanDetermineStateIfNotProvided()\n {\n $c = $this->getMockForAbstractClass('Aws\\\\AwsClientInterface');\n\n // CASE 1: All upload params are provided. State is loaded.\n $params = ['foo' => 1, 'bar' => 2, 'baz' => 3];\n $uploader = (new TestUploadBuilder($params))->setClient($c)->build();\n $this->assertInstanceOf(Uploader::class, $uploader);\n\n // CASE 2: All required upload params are provided. State is created.\n $params['baz'] = null;\n $uploader = (new TestUploadBuilder($params))->setClient($c)->build();\n $this->assertInstanceOf(Uploader::class, $uploader);\n\n // CASE 3: Required upload params are not provided. Exception thrown.\n $params['bar'] = null;\n $this->setExpectedException('InvalidArgumentException');\n $uploader = (new TestUploadBuilder($params))->setClient($c)->build();\n }\n\n /**\n * @param bool $seekable\n * @param UploadState $state\n * @param array $expectedParts\n *\n * @dataProvider getPartGeneratorTestCases\n */\n public function testCanCreatePartGenerator(\n $seekable,\n UploadState $state,\n array $expectedParts\n ) {\n // Instantiate Builder.\n $builder = (new TestUploadBuilder)\n ->setClient($this->getMockForAbstractClass('Aws\\\\AwsClientInterface'))\n ->setSource($this->getTestSource($seekable))\n ->setState($state);\n\n // Prepare a pseudo createPartFn closure.\n $createPartFn = function ($seekable, $partNumber) {\n if ($seekable) {\n $body = Stream::factory(fopen($this->source->getMetadata('uri'), 'r'));\n $body = $this->limitPartStream($body);\n } else {\n $body = Stream::factory($this->source->read($this->state->getPartSize()));\n }\n return ['Body' => $body->getContents()];\n };\n $createPartFn = $createPartFn->bindTo($builder, $builder);\n\n // Use reflection to call getPartGenerator.\n $getPartGenerator = (new \\ReflectionObject($builder))\n ->getMethod('getPartGenerator');\n $getPartGenerator->setAccessible(true);\n $parts = $getPartGenerator->invoke($builder, $createPartFn);\n\n $this->assertEquals($expectedParts, iterator_to_array($parts, true));\n }\n\n public function getPartGeneratorTestCases()\n {\n $expected = [\n 1 => ['Body' => 'AA'],\n 2 => ['Body' => 'BB'],\n 3 => ['Body' => 'CC'],\n 4 => ['Body' => 'DD'],\n 5 => ['Body' => 'EE'],\n 6 => ['Body' => 'F' ],\n ];\n $expectedSkip = $expected;\n unset($expectedSkip[1], $expectedSkip[2], $expectedSkip[4]);\n $state = new UploadState([]);\n $state->setPartSize(2);\n $stateSkip = clone $state;\n $stateSkip->markPartAsUploaded(1);\n $stateSkip->markPartAsUploaded(2);\n $stateSkip->markPartAsUploaded(4);\n return [\n [true, $state, $expected],\n [false, $state, $expected],\n [true, $stateSkip, $expectedSkip],\n [false, $stateSkip, $expectedSkip],\n ];\n }\n\n private function getTestSource($seekable)\n {\n $source = Stream::factory(fopen(__DIR__ . '/source.txt', 'r'));\n if (!$seekable) {\n $source = new NoSeekStream($source);\n }\n return $source;\n }\n}\n" }, { "alpha_fraction": 0.5336134433746338, "alphanum_fraction": 0.5336134433746338, "avg_line_length": 27, "blob_id": "4b4b093622680ded2a2c9be6825e7e1f9773b9f0", "content_id": "dbb81eaf31a4fbcb88f365a95e6940e67bc89e28", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 952, "license_type": "permissive", "max_line_length": 46, "num_lines": 34, "path": "/src/data/codedeploy-2014-10-06.paginators.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php return [\n 'pagination' => [\n 'ListApplicationRevisions' => [\n 'input_token' => 'nextToken',\n 'output_token' => 'nextToken',\n 'result_key' => 'revisions',\n ],\n 'ListApplications' => [\n 'input_token' => 'nextToken',\n 'output_token' => 'nextToken',\n 'result_key' => 'applications',\n ],\n 'ListDeploymentConfigs' => [\n 'input_token' => 'nextToken',\n 'output_token' => 'nextToken',\n 'result_key' => 'deploymentConfigsList',\n ],\n 'ListDeploymentGroups' => [\n 'input_token' => 'nextToken',\n 'output_token' => 'nextToken',\n 'result_key' => 'deploymentGroups',\n ],\n 'ListDeploymentInstances' => [\n 'input_token' => 'nextToken',\n 'output_token' => 'nextToken',\n 'result_key' => 'instancesList',\n ],\n 'ListDeployments' => [\n 'input_token' => 'nextToken',\n 'output_token' => 'nextToken',\n 'result_key' => 'deployments',\n ],\n ],\n];\n" }, { "alpha_fraction": 0.4901408553123474, "alphanum_fraction": 0.4901408553123474, "avg_line_length": 22.66666603088379, "blob_id": "6ce5acd60fd9e1b1e98ad00cff1c0f5e3266ef92", "content_id": "4ac60734c355ee59179405b7f1abac981993d3a5", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 355, "license_type": "permissive", "max_line_length": 42, "num_lines": 15, "path": "/src/data/sdb-2009-04-15.paginators.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php return [\n 'pagination' => [\n 'ListDomains' => [\n 'input_token' => 'NextToken',\n 'output_token' => 'NextToken',\n 'limit_key' => 'MaxNumberOfDomains',\n 'result_key' => 'DomainNames',\n ],\n 'Select' => [\n 'input_token' => 'NextToken',\n 'output_token' => 'NextToken',\n 'result_key' => 'Items',\n ],\n ],\n];\n" }, { "alpha_fraction": 0.45864349603652954, "alphanum_fraction": 0.4772539436817169, "avg_line_length": 34.55882263183594, "blob_id": "8dad75f85013670bd8a0b0dd103e25abc30d2b53", "content_id": "e7907f85f8a51654e90802e9637815d35f551c3c", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4836, "license_type": "permissive", "max_line_length": 242, "num_lines": 136, "path": "/tests/S3/PostObjectTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\S3;\n\nuse Aws\\S3\\PostObject;\nuse Aws\\S3\\S3Client;\nuse Aws\\Test\\UsesServiceTrait;\n\n/**\n * @covers Aws\\S3\\PostObject\n */\nclass PostObjectTest extends \\PHPUnit_Framework_TestCase\n{\n use UsesServiceTrait;\n\n /** @var S3Client */\n protected $client;\n\n public function setUp()\n {\n $credentials = $this->getMockBuilder('Aws\\Credentials\\Credentials')\n ->disableOriginalConstructor()\n ->getMock();\n $credentials->expects($this->any())\n ->method('getAccessKeyId')\n ->will($this->returnValue('AKIAXXXXXXXXXXXXXXX'));\n $credentials->expects($this->any())\n ->method('getSecretKey')\n ->will($this->returnValue('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'));\n\n $this->client = $this->getTestClient(\n 's3',\n ['credentials' => $credentials]\n );\n }\n\n public function getDataForPostObjectTest()\n {\n $cases = [];\n\n // Inputs capturing starts-with and success_action_status behaviors\n $cases[] = [\n // Options\n [\n 'Content-Type' => '^text/',\n 'ttd' => 'Nov 24, 1984, midnight GMT',\n 'acl' => 'private',\n 'success_action_status' => 201,\n 'key' => '^foo/bar/${filename}',\n 'policy_callback' => function (array $policy) {\n $policy['conditions'][] = ['fizz' => 'buzz'];\n return $policy;\n }\n ],\n // Expected Results\n [\n 'attributes' => [\n 'action' => 'https://foo.s3.amazonaws.com',\n 'method' => 'POST',\n 'enctype' => 'multipart/form-data'\n ],\n 'inputs' => [\n 'AWSAccessKeyId' => 'AKIAXXXXXXXXXXXXXXX',\n 'success_action_status' => '201',\n 'key' => 'foo/bar/${filename}',\n 'Content-Type' => 'text/',\n 'acl' => 'private',\n 'policy' => 'eyJleHBpcmF0aW9uIjoiMTk4NC0xMS0yNFQwMDowMDowMFoiLCJjb25kaXRpb25zIjpbeyJidWNrZXQiOiJmb28ifSx7InN1Y2Nlc3NfYWN0aW9uX3N0YXR1cyI6IjIwMSJ9LFsic3RhcnRzLXdpdGgiLCIkQ29udGVudC1UeXBlIiwidGV4dFwvIl0seyJhY2wiOiJwcml2YXRlIn0sWyJzdGFydHMtd2l0aCIsIiRrZXkiLCJmb29cL2JhclwvIl0seyJmaXp6IjoiYnV6eiJ9XX0=',\n 'signature' => 'XKwHh/c1moTcCw1L5xY/xmb/b58='\n ],\n 'policy' => '{\"expiration\":\"1984-11-24T00:00:00Z\",\"conditions\":[{\"bucket\":\"foo\"},{\"success_action_status\":\"201\"},[\"starts-with\",\"$Content-Type\",\"text\\/\"],{\"acl\":\"private\"},[\"starts-with\",\"$key\",\"foo\\/bar\\/\"],{\"fizz\":\"buzz\"}]}'\n ]\n ];\n\n // Passing in a raw policy\n $cases[] = [\n // Options\n [\n 'policy' => '{\"expiration\":\"1984-11-24T00:00:00Z\",\"conditions\":[{\"bucket\":\"foo\"},{\"success_action_stat'\n . 'us\":\"201\"},[\"starts-with\",\"$key\",\"foo\\\\/bar\\\\/\"],[\"starts-with\",\"$Content-Type\",\"text\\\\/\"]]}'\n ],\n // Expected Results\n [\n 'attributes' => [\n 'action' => 'https://foo.s3.amazonaws.com',\n 'method' => 'POST',\n 'enctype' => 'multipart/form-data'\n ],\n 'inputs' => [\n 'AWSAccessKeyId' => 'AKIAXXXXXXXXXXXXXXX',\n 'key' => '${filename}',\n 'policy' => 'eyJleHBpcmF0aW9uIjoiMTk4NC0xMS0yNFQwMDowMDowMFoiLCJjb25kaXRpb25zIjpbeyJidWNrZXQiOiJmb'\n . '28ifSx7InN1Y2Nlc3NfYWN0aW9uX3N0YXR1cyI6IjIwMSJ9LFsic3RhcnRzLXdpdGgiLCIka2V5IiwiZm9vXC9iYXJc'\n . 'LyJdLFsic3RhcnRzLXdpdGgiLCIkQ29udGVudC1UeXBlIiwidGV4dFwvIl1dfQ==',\n 'signature' => 'h92mKuUkaKTNmJMqnHDZ51+2+GY='\n ],\n 'policy' => '{\"expiration\":\"1984-11-24T00:00:00Z\",\"conditions\":[{\"bucket\":\"foo\"},{\"success_action_stat'\n . 'us\":\"201\"},[\"starts-with\",\"$key\",\"foo\\\\/bar\\\\/\"],[\"starts-with\",\"$Content-Type\",\"text\\\\/\"]]}'\n ]\n ];\n\n return $cases;\n }\n\n /**\n * @dataProvider getDataForPostObjectTest\n */\n public function testGetPostObjectData(array $options, array $expected)\n {\n $postObject = new PostObject($this->client, 'foo', $options);\n $postObject->prepareData();\n $this->assertEquals(\n $expected['attributes'],\n $postObject->getFormAttributes()\n );\n $this->assertEquals($expected['inputs'], $postObject->getFormInputs());\n $this->assertEquals($expected['policy'], $postObject->getJsonPolicy());\n }\n\n public function testClientAndBucketGetters()\n {\n $postObject = new PostObject($this->client, 'foo');\n $this->assertSame($this->client, $postObject->getClient());\n $this->assertSame('foo', $postObject->getBucket());\n }\n\n public function testCanHandleDomainsWithDots()\n {\n $postObject = new PostObject($this->client, 'foo.bar');\n $postObject->prepareData();\n $formAttrs = $postObject->getFormAttributes();\n $this->assertEquals(\n 'https://s3.amazonaws.com/foo.bar',\n $formAttrs['action']\n );\n }\n}\n" }, { "alpha_fraction": 0.6622806787490845, "alphanum_fraction": 0.6710526347160339, "avg_line_length": 24.33333396911621, "blob_id": "2377205b906976e0e71d92eba62bc60e3199ad7c", "content_id": "a67472a6e71773838f7f0a5608e72352df62033d", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 228, "license_type": "permissive", "max_line_length": 54, "num_lines": 9, "path": "/tests/bootstrap.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nerror_reporting(-1);\ndate_default_timezone_set('UTC');\n\n// Include the composer autoloader\n$loader = require __DIR__ . '/../vendor/autoload.php';\n$loader->addPsr4('Aws\\\\Test\\\\', __DIR__);\n\nJmesPath\\Env::cleanCompileDir();\n" }, { "alpha_fraction": 0.5374556183815002, "alphanum_fraction": 0.5498785972595215, "avg_line_length": 32.145511627197266, "blob_id": "a0ec8b4dea755b088eb845cb216d1d85f81feb41", "content_id": "32fe1606d73973b5e763ffa047b9c3190a346f9c", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 10706, "license_type": "permissive", "max_line_length": 93, "num_lines": 323, "path": "/src/Signature/SignatureV4.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Signature;\n\nuse Aws\\Credentials\\CredentialsInterface;\nuse Aws\\Exception\\CouldNotCreateChecksumException;\nuse GuzzleHttp\\Message\\RequestInterface;\nuse GuzzleHttp\\Post\\PostBodyInterface;\nuse GuzzleHttp\\Stream\\Utils;\n\n/**\n * Signature Version 4\n * @link http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html\n */\nclass SignatureV4 extends AbstractSignature\n{\n const ISO8601_BASIC = 'Ymd\\THis\\Z';\n const EMPTY_PAYLOAD = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855';\n\n /** @var string */\n private $service;\n\n /** @var string */\n private $region;\n\n /** @var array Cache of previously signed values */\n private $cache = [];\n\n /** @var int Size of the hash cache */\n private $cacheSize = 0;\n\n /**\n * @param string $service Service name to use when signing\n * @param string $region Region name to use when signing\n */\n public function __construct($service, $region)\n {\n $this->service = $service;\n $this->region = $region;\n }\n\n public function signRequest(\n RequestInterface $request,\n CredentialsInterface $credentials\n ) {\n $ldt = gmdate(self::ISO8601_BASIC);\n $sdt = substr($ldt, 0, 8);\n $request->removeHeader('Authorization');\n $request->removeHeader('x-amz-date');\n $request->setHeader('Date', $ldt);\n\n if ($token = $credentials->getSecurityToken()) {\n $request->setHeader('x-amz-security-token', $token);\n }\n\n $cs = $this->createScope($sdt, $this->region, $this->service);\n $payload = $this->getPayload($request);\n $context = $this->createContext($request, $payload);\n $context['string_to_sign'] = $this->createStringToSign($ldt, $cs, $context['creq']);\n $signingKey = $this->getSigningKey(\n $sdt,\n $this->region,\n $this->service,\n $credentials->getSecretKey()\n );\n\n $signature = hash_hmac('sha256', $context['string_to_sign'], $signingKey);\n $request->setHeader('Authorization', \"AWS4-HMAC-SHA256 \"\n . \"Credential={$credentials->getAccessKeyId()}/{$cs}, \"\n . \"SignedHeaders={$context['headers']}, Signature={$signature}\");\n $request->getConfig()['aws.signature'] = $context;\n }\n\n public function createPresignedUrl(\n RequestInterface $request,\n CredentialsInterface $credentials,\n $expires\n ) {\n $request = $this->createPresignedRequest($request, $credentials);\n $query = $request->getQuery();\n $httpDate = gmdate(self::ISO8601_BASIC, time());\n $shortDate = substr($httpDate, 0, 8);\n $scope = $this->createScope($shortDate, $this->region, $this->service);\n $this->addQueryValues($scope, $request, $credentials, $expires);\n $payload = $this->getPresignedPayload($request);\n $context = $this->createContext($request, $payload);\n $stringToSign = $this->createStringToSign($httpDate, $scope, $context['creq']);\n $key = $this->getSigningKey(\n $shortDate,\n $this->region,\n $this->service,\n $credentials->getSecretKey()\n );\n $query['X-Amz-Signature'] = hash_hmac('sha256', $stringToSign, $key);\n\n return $request->getUrl();\n }\n\n /**\n * Converts a POST request to a GET request by moving POST fields into the\n * query string.\n *\n * Useful for pre-signing query protocol requests.\n *\n * @param RequestInterface $request Request to clone\n *\n * @return RequestInterface\n * @throws \\InvalidArgumentException if the method is not POST\n */\n public static function convertPostToGet(RequestInterface $request)\n {\n if ($request->getMethod() !== 'POST') {\n throw new \\InvalidArgumentException('Expected a POST request but '\n . 'received a ' . $request->getMethod() . ' request.');\n }\n\n $sr = clone $request;\n $sr->setMethod('GET');\n $sr->setBody(null);\n\n // Move POST fields to the query if they are present\n if ($request->getBody() instanceof PostBodyInterface) {\n foreach ($request->getBody()->getFields() as $name => $value) {\n $sr->getQuery()->set($name, $value);\n }\n }\n\n return $sr;\n }\n\n protected function getPayload(RequestInterface $request)\n {\n // Calculate the request signature payload\n if ($request->hasHeader('x-amz-content-sha256')) {\n // Handle streaming operations (e.g. Glacier.UploadArchive)\n return (string) $request->getHeader('x-amz-content-sha256');\n }\n\n if ($body = $request->getBody()) {\n if (!$body->isSeekable()) {\n throw new CouldNotCreateChecksumException('sha256');\n }\n return Utils::hash($body, 'sha256');\n }\n\n return self::EMPTY_PAYLOAD;\n }\n\n protected function getPresignedPayload(RequestInterface $request)\n {\n return $this->getPayload($request);\n }\n\n private function createStringToSign($longDate, $credentialScope, $creq)\n {\n return \"AWS4-HMAC-SHA256\\n{$longDate}\\n{$credentialScope}\\n\"\n . hash('sha256', $creq);\n }\n\n private function createPresignedRequest(\n RequestInterface $request,\n CredentialsInterface $credentials\n ) {\n $sr = clone $request;\n\n // Make sure to handle temporary credentials\n if ($token = $credentials->getSecurityToken()) {\n $sr->setHeader('X-Amz-Security-Token', $token);\n $sr->getQuery()->set('X-Amz-Security-Token', $token);\n }\n\n $this->moveHeadersToQuery($sr);\n\n return $sr;\n }\n\n /**\n * @internal Create the canonical representation of a request\n * @param RequestInterface $request Request to canonicalize\n * @param string $payload Hash of the request payload\n * @return array Returns an array of context information\n */\n private function createContext(RequestInterface $request, $payload)\n {\n static $signable = [\n 'host' => true,\n 'date' => true,\n 'content-md5' => true\n ];\n\n // Normalize the path as required by SigV4 and ensure it's absolute\n $canon = $request->getMethod() . \"\\n\"\n . '/' . ltrim($request->getPath(), '/') . \"\\n\"\n . $this->getCanonicalizedQuery($request) . \"\\n\";\n\n $canonHeaders = [];\n\n // Always include the \"host\", \"date\", and \"x-amz-\" headers.\n foreach ($request->getHeaders() as $key => $values) {\n $key = strtolower($key);\n if (isset($signable[$key]) || substr($key, 0, 6) === 'x-amz-') {\n if (count($values) == 1) {\n $values = $values[0];\n } else {\n sort($values);\n $values = implode(',', $values);\n }\n $canonHeaders[$key] = $key . ':' . preg_replace('/\\s+/', ' ', $values);\n }\n }\n\n ksort($canonHeaders);\n $signedHeadersString = implode(';', array_keys($canonHeaders));\n $canon .= implode(\"\\n\", $canonHeaders) . \"\\n\\n\"\n . $signedHeadersString . \"\\n\"\n . $payload;\n\n return ['creq' => $canon, 'headers' => $signedHeadersString];\n }\n\n private function getSigningKey($shortDate, $region, $service, $secretKey)\n {\n $k = $shortDate . '_' . $region . '_' . $service . '_' . $secretKey;\n\n if (!isset($this->cache[$k])) {\n // Clear the cache when it reaches 50 entries\n if (++$this->cacheSize > 50) {\n $this->cache = [];\n $this->cacheSize = 0;\n }\n $dateKey = hash_hmac('sha256', $shortDate, \"AWS4{$secretKey}\", true);\n $regionKey = hash_hmac('sha256', $region, $dateKey, true);\n $serviceKey = hash_hmac('sha256', $service, $regionKey, true);\n $this->cache[$k] = hash_hmac('sha256', 'aws4_request', $serviceKey, true);\n }\n\n return $this->cache[$k];\n }\n\n private function getCanonicalizedQuery(RequestInterface $request)\n {\n $queryParams = $request->getQuery()->toArray();\n unset($queryParams['X-Amz-Signature']);\n\n if (!$queryParams) {\n return '';\n }\n\n $qs = '';\n ksort($queryParams);\n foreach ($queryParams as $k => $v) {\n if (!is_array($v)) {\n $qs .= rawurlencode($k) . '=' . rawurlencode($v) . '&';\n } else {\n sort($v);\n foreach ($v as $value) {\n $qs .= rawurlencode($k) . '=' . rawurlencode($value) . '&';\n }\n }\n }\n\n return substr($qs, 0, -1);\n }\n\n private function convertExpires($expires)\n {\n if ($expires instanceof \\DateTime) {\n $expires = $expires->getTimestamp();\n } elseif (!is_numeric($expires)) {\n $expires = strtotime($expires);\n }\n\n $duration = $expires - time();\n\n // Ensure that the duration of the signature is not longer than a week\n if ($duration > 604800) {\n throw new \\InvalidArgumentException('The expiration date of a '\n . 'signature version 4 presigned URL must be less than one '\n . 'week');\n }\n\n return $duration;\n }\n\n private function createScope($shortDate, $region, $service)\n {\n return $shortDate\n . '/' . $region\n . '/' . $service\n . '/aws4_request';\n }\n\n private function addQueryValues(\n $scope,\n RequestInterface $request,\n CredentialsInterface $credentials,\n $expires\n ) {\n $credential = $credentials->getAccessKeyId() . '/' . $scope;\n\n // Set query params required for pre-signed URLs\n $query = $request->getQuery();\n $query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256';\n $query['X-Amz-Credential'] = $credential;\n $query['X-Amz-Date'] = gmdate('Ymd\\THis\\Z', time());\n $query['X-Amz-SignedHeaders']= 'Host';\n $query['X-Amz-Expires'] = $this->convertExpires($expires);\n }\n\n private function moveHeadersToQuery(RequestInterface $request)\n {\n $query = $request->getQuery();\n\n foreach ($request->getHeaders() as $name => $header) {\n $name = strtolower($name);\n if (substr($name, 0, 5) == 'x-amz') {\n $query[$name] = $header;\n }\n if ($name !== 'host') {\n $request->removeHeader($name);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.36977702379226685, "alphanum_fraction": 0.3754918575286865, "avg_line_length": 31.054054260253906, "blob_id": "4044c97fbcb38ee29fbe9725a328a049cc025794", "content_id": "15f5633dee7ad3937f37343e3a7c5201a8c8e13a", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 10674, "license_type": "permissive", "max_line_length": 87, "num_lines": 333, "path": "/tests/WaiterTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test;\n\nuse Aws\\Result;\nuse Aws\\Test\\UsesServiceTrait;\nuse GuzzleHttp\\Client;\nuse GuzzleHttp\\Message\\Response;\nuse GuzzleHttp\\Ring\\Client\\MockHandler;\n\n/**\n * @covers Aws\\Waiter\n */\nclass WaiterTest extends \\PHPUnit_Framework_TestCase\n{\n use UsesServiceTrait;\n\n /**\n * @expectedException \\InvalidArgumentException\n */\n public function testErrorOnBadConfig()\n {\n $client = $this->getTestClient('DynamoDb');\n $client->waitUntil(\n 'TableExists',\n ['TableName' => 'Meh'],\n ['delay' => null]\n );\n }\n\n public function testCanCancel()\n {\n $client = $this->getTestClient('DynamoDb');\n $client->waitUntil('TableExists', [\n 'TableName' => 'Meh',\n '@future' => true,\n ])->cancel();\n }\n\n public function testCanWait()\n {\n $i = 0;\n $client = $this->getTestClient('DynamoDb', [\n 'client' => function () {\n return new Client([\n 'handler' => new MockHandler(function () use (&$i) {\n if ($i++) {\n return [\n 'status' => 200,\n 'body' => '{\"Table\":{\"TableStatus\":\"ACTIVE\"}}'\n ];\n } else {\n return [\n 'status' => 200,\n 'body' => '{\"Table\":{\"TableStatus\":\"CREATING\"}}'\n ];\n }\n })\n ]);\n }\n ]);\n\n $client->waitUntil(\n 'TableExists',\n ['TableName' => 'Meh'],\n ['initDelay' => 0.1, 'delay' => 0.1]\n );\n }\n\n /**\n * @dataProvider getWaiterWorkflowTestCases\n */\n public function testWaiterWorkflow($results, $expectedException)\n {\n // Prepare a client\n $client = $this->getTestClient('DynamoDb', [\n 'api_provider' => $this->getApiProvider()\n ]);\n $this->addMockResults($client, $results);\n\n // Execute the waiter and verify the number of requests.\n $actualAttempt = 0;\n try {\n $client->waitUntil('TableExists', ['TableName' => 'WhoCares'], [\n 'retry' => function ($attempt) use (&$actualAttempt) {\n $actualAttempt = $attempt;\n }\n ]);\n $actualException = null;\n } catch (\\Exception $e) {\n $actualException = $e->getMessage();\n }\n\n $this->assertEquals(count($results) - 1, $actualAttempt);\n $this->assertEquals($expectedException, $actualException);\n }\n\n public function getWaiterWorkflowTestCases()\n {\n return [\n [\n [\n $this->createMockAwsException('ResourceNotFoundException'),\n new Result(['Table' => ['TableStatus' => 'CREATING']]),\n new Result(['Table' => ['TableStatus' => 'CREATING']]),\n new Result(['Table' => ['TableStatus' => 'ACTIVE']]),\n ],\n null\n ],\n [\n [\n new Result(['Table' => ['TableStatus' => 'CREATING']]),\n new Result(['Table' => ['TableStatus' => 'DELETING']]),\n ],\n 'The TableExists waiter entered a failure state.'\n ],\n [\n [\n new Result(['Table' => ['TableStatus' => 'CREATING']]),\n new Result(['Table' => ['TableStatus' => 'CREATING']]),\n new Result(['Table' => ['TableStatus' => 'CREATING']]),\n new Result(['Table' => ['TableStatus' => 'CREATING']]),\n new Result(['Table' => ['TableStatus' => 'CREATING']]),\n ],\n 'Waiter failed after the attempt #5.'\n ],\n [\n [\n $this->createMockAwsException(null, null, 'foo'),\n ],\n 'The TableExists waiter entered a failure state.'\n ],\n ];\n }\n\n private function getApiProvider()\n {\n return function ($type) {\n if ($type == 'api') {\n return [\n 'operations' => ['DescribeTable' => ['input' => []]],\n 'metadata' => [\n 'endpointPrefix' => 'foo',\n 'protocol' => 'json',\n 'signatureVersion' => 'v4'\n ],\n ];\n } else {\n return ['waiters' => [\n 'TableExists' => [\n 'delay' => function ($attempt) { return $attempt; },\n 'maxAttempts' => 5,\n 'operation' => 'DescribeTable',\n 'acceptors' => [\n [\n 'state' => 'success',\n 'matcher' => 'path',\n 'argument' => 'Table.TableStatus',\n 'expected' => 'ACTIVE',\n ],\n [\n 'state' => 'retry',\n 'matcher' => 'error',\n 'expected' => 'ResourceNotFoundException',\n ],\n [\n 'state' => 'failed',\n 'matcher' => 'path',\n 'argument' => 'Table.TableStatus',\n 'expected' => 'DELETING',\n ],\n ],\n ]\n ]];\n }\n };\n }\n\n /**\n * @dataProvider getMatchersTestCases\n */\n public function testMatchers($matcher, $event, $acceptor, $expected)\n {\n $waiter = new \\ReflectionClass('Aws\\Waiter');\n $matcher = $waiter->getMethod($matcher);\n $matcher->setAccessible(true);\n $waiter = $waiter->newInstanceWithoutConstructor();\n\n $this->assertEquals(\n $expected,\n $matcher->invoke($waiter, $event, $acceptor)\n );\n }\n\n public function getMatchersTestCases()\n {\n return [\n [\n 'matchesPath',\n $this->getMockProcessEvent(200, null),\n [],\n false\n ],\n [\n 'matchesPath',\n $this->getMockProcessEvent(200, ['a' => ['b' => 'c']]),\n ['argument' => 'a.b', 'expected' => 'c'],\n true\n ],\n [\n 'matchesPath',\n $this->getMockProcessEvent(200, ['a' => ['b' => 'c']]),\n ['argument' => 'a', 'expected' => 'z'],\n false\n ],\n [\n 'matchesPathAll',\n $this->getMockProcessEvent(200, null),\n [],\n false\n ],\n [\n 'matchesPathAll',\n $this->getMockProcessEvent(200, ['a' => [\n ['b' => 'c'],\n ['b' => 'c'],\n ['b' => 'c']\n ]]),\n ['argument' => 'a[].b', 'expected' => 'c'],\n true\n ],\n [\n 'matchesPathAll',\n $this->getMockProcessEvent(200, ['a' => [\n ['b' => 'c'],\n ['b' => 'z'],\n ['b' => 'c']\n ]]),\n ['argument' => 'a[].b', 'expected' => 'c'],\n false\n ],\n [\n 'matchesPathAny',\n $this->getMockProcessEvent(200, null),\n [],\n false\n ],\n [\n 'matchesPathAny',\n $this->getMockProcessEvent(200, ['a' => [\n ['b' => 'c'],\n ['b' => 'd'],\n ['b' => 'e']\n ]]),\n ['argument' => 'a[].b', 'expected' => 'c'],\n true\n ],\n [\n 'matchesPathAny',\n $this->getMockProcessEvent(200, ['a' => [\n ['b' => 'x'],\n ['b' => 'y'],\n ['b' => 'z']\n ]]),\n ['argument' => 'a[].b', 'expected' => 'c'],\n false\n ],\n [\n 'matchesStatus',\n $this->getMockProcessEvent(null),\n [],\n false\n ],\n [\n 'matchesStatus',\n $this->getMockProcessEvent(200),\n ['expected' => 200],\n true\n ],\n [\n 'matchesStatus',\n $this->getMockProcessEvent(200),\n ['expected' => 400],\n false\n ],\n [\n 'matchesError',\n $this->getMockProcessEvent(),\n [],\n false\n ],\n [\n 'matchesError',\n $this->getMockProcessEvent(400, [], 'InvalidData'),\n ['expected' => 'InvalidData'],\n true\n ],\n [\n 'matchesError',\n $this->getMockProcessEvent(400, [], 'InvalidData'),\n ['expected' => 'Foo'],\n false\n ],\n ];\n }\n\n private function getMockProcessEvent($status = null, $result = null, $error = null)\n {\n $event = $this->getMockBuilder('GuzzleHttp\\Command\\Event\\ProcessEvent')\n ->disableOriginalConstructor()\n ->setMethods(['getException', 'getResponse', 'getResult', 'setResult'])\n ->getMock();\n\n if ($status) {\n $event->method('getResponse')->willReturn(new Response($status));\n }\n\n if ($result) {\n $event->method('getResult')->willReturn(new Result($result));\n }\n\n if ($error) {\n $exception = $this->getMockBuilder('Aws\\Exception\\AwsException')\n ->disableOriginalConstructor()\n ->setMethods(['getAwsErrorCode'])\n ->getMock();\n $exception->method('getAwsErrorCode')->willReturn($error);\n $event->method('getException')->willReturn($exception);\n $event->method('setResult')->with(true);\n }\n\n return $event;\n }\n}\n" }, { "alpha_fraction": 0.5733752846717834, "alphanum_fraction": 0.5796645879745483, "avg_line_length": 29.774192810058594, "blob_id": "7d519735ebe3a230151edf2f272696ed841a113a", "content_id": "694ce30efa38669347872eecab468573a148351f", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1908, "license_type": "permissive", "max_line_length": 80, "num_lines": 62, "path": "/tests/Glacier/ApplyChecksumsSubscriberTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Glacier;\n\nuse Aws\\Glacier\\Exception\\GlacierException;\nuse Aws\\Result;\nuse Aws\\Test\\UsesServiceTrait;\nuse GuzzleHttp\\Command\\Event\\PreparedEvent;\nuse GuzzleHttp\\Message\\Response;\nuse GuzzleHttp\\Stream\\Stream;\nuse GuzzleHttp\\Stream\\NoSeekStream;\n\n/**\n * @covers Aws\\Glacier\\ApplyChecksumsSubscriber\n */\nclass ApplyChecksumsSubscriberTest extends \\PHPUnit_Framework_TestCase\n{\n use UsesServiceTrait;\n\n public function testThrowsExceptionIfBodyIsNotSeekable()\n {\n $glacier = $this->getTestClient('Glacier');\n $command = $glacier->getCommand('UploadArchive', [\n 'vaultName' => 'foo',\n 'body' => new NoSeekStream(Stream::factory('foo')),\n ]);\n try {\n $glacier->execute($command);\n $this->fail('An exception should have been thrown.');\n } catch (GlacierException $e) {\n $this->assertInstanceOf(\n 'Aws\\Exception\\CouldNotCreateChecksumException',\n $e->getPrevious()\n );\n }\n }\n\n public function testAddsChecksumsIfNeeded()\n {\n $glacier = $this->getTestClient('Glacier');\n $this->addMockResponses($glacier, [new Response(200)]);\n\n $command = $glacier->getCommand('UploadArchive', [\n 'vaultName' => 'foo',\n 'body' => 'bar',\n ]);\n\n $command->getEmitter()->on('prepared', function (PreparedEvent $event) {\n $event->intercept(new Result([]));\n $expectedHash = hash('sha256', 'bar');\n $this->assertEquals(\n $expectedHash,\n $event->getRequest()->getHeader('x-amz-content-sha256')\n );\n $this->assertEquals(\n $expectedHash,\n $event->getRequest()->getHeader('x-amz-sha256-tree-hash')\n );\n }, 'last');\n\n $glacier->execute($command);\n }\n}\n" }, { "alpha_fraction": 0.4695393741130829, "alphanum_fraction": 0.47028231620788574, "avg_line_length": 22.61403465270996, "blob_id": "cf31ef0cc9523b59092a09b333e2f1a9382947b2", "content_id": "8c9ebe202d02c133248b2b3e9a7ecc2029729300", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1346, "license_type": "permissive", "max_line_length": 57, "num_lines": 57, "path": "/src/data/s3-2006-03-01.paginators.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php return [\n 'pagination' => [\n 'ListBuckets' => [\n 'result_key' => 'Buckets',\n ],\n 'ListMultipartUploads' => [\n 'limit_key' => 'MaxUploads',\n 'more_results' => 'IsTruncated',\n 'output_token' => [\n 'NextKeyMarker',\n 'NextUploadIdMarker',\n ],\n 'input_token' => [\n 'KeyMarker',\n 'UploadIdMarker',\n ],\n 'result_key' => [\n 'Uploads',\n 'CommonPrefixes',\n ],\n ],\n 'ListObjectVersions' => [\n 'more_results' => 'IsTruncated',\n 'limit_key' => 'MaxKeys',\n 'output_token' => [\n 'NextKeyMarker',\n 'NextVersionIdMarker',\n ],\n 'input_token' => [\n 'KeyMarker',\n 'VersionIdMarker',\n ],\n 'result_key' => [\n 'Versions',\n 'DeleteMarkers',\n 'CommonPrefixes',\n ],\n ],\n 'ListObjects' => [\n 'more_results' => 'IsTruncated',\n 'limit_key' => 'MaxKeys',\n 'output_token' => 'NextMarker || Contents[-1].Key',\n 'input_token' => 'Marker',\n 'result_key' => [\n 'Contents',\n 'CommonPrefixes',\n ],\n ],\n 'ListParts' => [\n 'more_results' => 'IsTruncated',\n 'limit_key' => 'MaxParts',\n 'output_token' => 'NextPartNumberMarker',\n 'input_token' => 'PartNumberMarker',\n 'result_key' => 'Parts',\n ],\n ],\n];\n" }, { "alpha_fraction": 0.6215022206306458, "alphanum_fraction": 0.6229749917984009, "avg_line_length": 27.29166603088379, "blob_id": "f60452a9c1280906a3b64f7c97737de2144e57c4", "content_id": "a8a1eebb15f0f341517bae6c04b27d103e430555", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 679, "license_type": "permissive", "max_line_length": 90, "num_lines": 24, "path": "/src/CloudSearchDomain/CloudSearchDomainClient.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\CloudSearchDomain;\n\nuse Aws\\AwsClient;\nuse GuzzleHttp\\Url;\n\n/**\n * This client is used to search and upload documents to an **Amazon CloudSearch** Domain.\n */\nclass CloudSearchDomainClient extends AwsClient\n{\n public static function getArguments()\n {\n $args = parent::getArguments();\n $args['endpoint']['required'] = true;\n $args['region']['default'] = function (array $args) {\n // Determine the region from the provided endpoint.\n // (e.g. http://search-blah.{region}.cloudsearch.amazonaws.com)\n return explode('.', Url::fromString($args['endpoint']))[1];\n };\n\n return $args;\n }\n}\n" }, { "alpha_fraction": 0.389477014541626, "alphanum_fraction": 0.4008423089981079, "avg_line_length": 22.5269775390625, "blob_id": "731d3ea35d37886f4836c71cae35be27130b76a4", "content_id": "c6a696a0947bc392855bf8aee1e4b4443cf75506", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 69334, "license_type": "permissive", "max_line_length": 128, "num_lines": 2947, "path": "/src/data/route53-2013-04-01.api.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php return [\n 'metadata' => [\n 'apiVersion' => '2013-04-01',\n 'endpointPrefix' => 'route53',\n 'globalEndpoint' => 'route53.amazonaws.com',\n 'serviceAbbreviation' => 'Route 53',\n 'serviceFullName' => 'Amazon Route 53',\n 'signatureVersion' => 'v4',\n 'protocol' => 'rest-xml',\n ],\n 'operations' => [\n 'AssociateVPCWithHostedZone' => [\n 'name' => 'AssociateVPCWithHostedZone',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/2013-04-01/hostedzone/{Id}/associatevpc',\n ],\n 'input' => [\n 'shape' => 'AssociateVPCWithHostedZoneRequest',\n 'xmlNamespace' => [\n 'uri' => 'https://route53.amazonaws.com/doc/2013-04-01/',\n ],\n 'locationName' => 'AssociateVPCWithHostedZoneRequest',\n ],\n 'output' => [\n 'shape' => 'AssociateVPCWithHostedZoneResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchHostedZone',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidVPCId',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidInput',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'PublicZoneVPCAssociation',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'ConflictingDomainExists',\n 'exception' => true,\n ],\n ],\n ],\n 'ChangeResourceRecordSets' => [\n 'name' => 'ChangeResourceRecordSets',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/2013-04-01/hostedzone/{Id}/rrset/',\n ],\n 'input' => [\n 'shape' => 'ChangeResourceRecordSetsRequest',\n 'xmlNamespace' => [\n 'uri' => 'https://route53.amazonaws.com/doc/2013-04-01/',\n ],\n 'locationName' => 'ChangeResourceRecordSetsRequest',\n ],\n 'output' => [\n 'shape' => 'ChangeResourceRecordSetsResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchHostedZone',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'NoSuchHealthCheck',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidChangeBatch',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidInput',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'PriorRequestNotComplete',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'ChangeTagsForResource' => [\n 'name' => 'ChangeTagsForResource',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/2013-04-01/tags/{ResourceType}/{ResourceId}',\n ],\n 'input' => [\n 'shape' => 'ChangeTagsForResourceRequest',\n 'xmlNamespace' => [\n 'uri' => 'https://route53.amazonaws.com/doc/2013-04-01/',\n ],\n 'locationName' => 'ChangeTagsForResourceRequest',\n ],\n 'output' => [\n 'shape' => 'ChangeTagsForResourceResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidInput',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'NoSuchHealthCheck',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'NoSuchHostedZone',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'PriorRequestNotComplete',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'ThrottlingException',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'CreateHealthCheck' => [\n 'name' => 'CreateHealthCheck',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/2013-04-01/healthcheck',\n 'responseCode' => 201,\n ],\n 'input' => [\n 'shape' => 'CreateHealthCheckRequest',\n 'xmlNamespace' => [\n 'uri' => 'https://route53.amazonaws.com/doc/2013-04-01/',\n ],\n 'locationName' => 'CreateHealthCheckRequest',\n ],\n 'output' => [\n 'shape' => 'CreateHealthCheckResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'TooManyHealthChecks',\n 'exception' => true,\n ],\n [\n 'shape' => 'HealthCheckAlreadyExists',\n 'error' => [\n 'httpStatusCode' => 409,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidInput',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'CreateHostedZone' => [\n 'name' => 'CreateHostedZone',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/2013-04-01/hostedzone',\n 'responseCode' => 201,\n ],\n 'input' => [\n 'shape' => 'CreateHostedZoneRequest',\n 'xmlNamespace' => [\n 'uri' => 'https://route53.amazonaws.com/doc/2013-04-01/',\n ],\n 'locationName' => 'CreateHostedZoneRequest',\n ],\n 'output' => [\n 'shape' => 'CreateHostedZoneResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidDomainName',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'HostedZoneAlreadyExists',\n 'error' => [\n 'httpStatusCode' => 409,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'TooManyHostedZones',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidVPCId',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidInput',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'DelegationSetNotAvailable',\n 'exception' => true,\n ],\n [\n 'shape' => 'ConflictingDomainExists',\n 'exception' => true,\n ],\n [\n 'shape' => 'NoSuchDelegationSet',\n 'exception' => true,\n ],\n [\n 'shape' => 'DelegationSetNotReusable',\n 'exception' => true,\n ],\n ],\n ],\n 'CreateReusableDelegationSet' => [\n 'name' => 'CreateReusableDelegationSet',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/2013-04-01/delegationset',\n 'responseCode' => 201,\n ],\n 'input' => [\n 'shape' => 'CreateReusableDelegationSetRequest',\n 'xmlNamespace' => [\n 'uri' => 'https://route53.amazonaws.com/doc/2013-04-01/',\n ],\n 'locationName' => 'CreateReusableDelegationSetRequest',\n ],\n 'output' => [\n 'shape' => 'CreateReusableDelegationSetResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'DelegationSetAlreadyCreated',\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitsExceeded',\n 'exception' => true,\n ],\n [\n 'shape' => 'HostedZoneNotFound',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidArgument',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidInput',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'DelegationSetNotAvailable',\n 'exception' => true,\n ],\n [\n 'shape' => 'DelegationSetAlreadyReusable',\n 'exception' => true,\n ],\n ],\n ],\n 'DeleteHealthCheck' => [\n 'name' => 'DeleteHealthCheck',\n 'http' => [\n 'method' => 'DELETE',\n 'requestUri' => '/2013-04-01/healthcheck/{HealthCheckId}',\n ],\n 'input' => [\n 'shape' => 'DeleteHealthCheckRequest',\n ],\n 'output' => [\n 'shape' => 'DeleteHealthCheckResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchHealthCheck',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'HealthCheckInUse',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidInput',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'DeleteHostedZone' => [\n 'name' => 'DeleteHostedZone',\n 'http' => [\n 'method' => 'DELETE',\n 'requestUri' => '/2013-04-01/hostedzone/{Id}',\n ],\n 'input' => [\n 'shape' => 'DeleteHostedZoneRequest',\n ],\n 'output' => [\n 'shape' => 'DeleteHostedZoneResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchHostedZone',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'HostedZoneNotEmpty',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'PriorRequestNotComplete',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidInput',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'DeleteReusableDelegationSet' => [\n 'name' => 'DeleteReusableDelegationSet',\n 'http' => [\n 'method' => 'DELETE',\n 'requestUri' => '/2013-04-01/delegationset/{Id}',\n ],\n 'input' => [\n 'shape' => 'DeleteReusableDelegationSetRequest',\n ],\n 'output' => [\n 'shape' => 'DeleteReusableDelegationSetResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchDelegationSet',\n 'exception' => true,\n ],\n [\n 'shape' => 'DelegationSetInUse',\n 'exception' => true,\n ],\n [\n 'shape' => 'DelegationSetNotReusable',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidInput',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'DisassociateVPCFromHostedZone' => [\n 'name' => 'DisassociateVPCFromHostedZone',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/2013-04-01/hostedzone/{Id}/disassociatevpc',\n ],\n 'input' => [\n 'shape' => 'DisassociateVPCFromHostedZoneRequest',\n 'xmlNamespace' => [\n 'uri' => 'https://route53.amazonaws.com/doc/2013-04-01/',\n ],\n 'locationName' => 'DisassociateVPCFromHostedZoneRequest',\n ],\n 'output' => [\n 'shape' => 'DisassociateVPCFromHostedZoneResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchHostedZone',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidVPCId',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'VPCAssociationNotFound',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LastVPCAssociation',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidInput',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'GetChange' => [\n 'name' => 'GetChange',\n 'http' => [\n 'method' => 'GET',\n 'requestUri' => '/2013-04-01/change/{Id}',\n ],\n 'input' => [\n 'shape' => 'GetChangeRequest',\n ],\n 'output' => [\n 'shape' => 'GetChangeResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchChange',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidInput',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'GetCheckerIpRanges' => [\n 'name' => 'GetCheckerIpRanges',\n 'http' => [\n 'method' => 'GET',\n 'requestUri' => '/2013-04-01/checkeripranges',\n ],\n 'input' => [\n 'shape' => 'GetCheckerIpRangesRequest',\n ],\n 'output' => [\n 'shape' => 'GetCheckerIpRangesResponse',\n ],\n ],\n 'GetGeoLocation' => [\n 'name' => 'GetGeoLocation',\n 'http' => [\n 'method' => 'GET',\n 'requestUri' => '/2013-04-01/geolocation',\n ],\n 'input' => [\n 'shape' => 'GetGeoLocationRequest',\n ],\n 'output' => [\n 'shape' => 'GetGeoLocationResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchGeoLocation',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidInput',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'GetHealthCheck' => [\n 'name' => 'GetHealthCheck',\n 'http' => [\n 'method' => 'GET',\n 'requestUri' => '/2013-04-01/healthcheck/{HealthCheckId}',\n ],\n 'input' => [\n 'shape' => 'GetHealthCheckRequest',\n ],\n 'output' => [\n 'shape' => 'GetHealthCheckResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchHealthCheck',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidInput',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'IncompatibleVersion',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'GetHealthCheckCount' => [\n 'name' => 'GetHealthCheckCount',\n 'http' => [\n 'method' => 'GET',\n 'requestUri' => '/2013-04-01/healthcheckcount',\n ],\n 'input' => [\n 'shape' => 'GetHealthCheckCountRequest',\n ],\n 'output' => [\n 'shape' => 'GetHealthCheckCountResponse',\n ],\n ],\n 'GetHealthCheckLastFailureReason' => [\n 'name' => 'GetHealthCheckLastFailureReason',\n 'http' => [\n 'method' => 'GET',\n 'requestUri' => '/2013-04-01/healthcheck/{HealthCheckId}/lastfailurereason',\n ],\n 'input' => [\n 'shape' => 'GetHealthCheckLastFailureReasonRequest',\n ],\n 'output' => [\n 'shape' => 'GetHealthCheckLastFailureReasonResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchHealthCheck',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'GetHealthCheckStatus' => [\n 'name' => 'GetHealthCheckStatus',\n 'http' => [\n 'method' => 'GET',\n 'requestUri' => '/2013-04-01/healthcheck/{HealthCheckId}/status',\n ],\n 'input' => [\n 'shape' => 'GetHealthCheckStatusRequest',\n ],\n 'output' => [\n 'shape' => 'GetHealthCheckStatusResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchHealthCheck',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'GetHostedZone' => [\n 'name' => 'GetHostedZone',\n 'http' => [\n 'method' => 'GET',\n 'requestUri' => '/2013-04-01/hostedzone/{Id}',\n ],\n 'input' => [\n 'shape' => 'GetHostedZoneRequest',\n ],\n 'output' => [\n 'shape' => 'GetHostedZoneResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchHostedZone',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidInput',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'GetReusableDelegationSet' => [\n 'name' => 'GetReusableDelegationSet',\n 'http' => [\n 'method' => 'GET',\n 'requestUri' => '/2013-04-01/delegationset/{Id}',\n ],\n 'input' => [\n 'shape' => 'GetReusableDelegationSetRequest',\n ],\n 'output' => [\n 'shape' => 'GetReusableDelegationSetResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchDelegationSet',\n 'exception' => true,\n ],\n [\n 'shape' => 'DelegationSetNotReusable',\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidInput',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'ListGeoLocations' => [\n 'name' => 'ListGeoLocations',\n 'http' => [\n 'method' => 'GET',\n 'requestUri' => '/2013-04-01/geolocations',\n ],\n 'input' => [\n 'shape' => 'ListGeoLocationsRequest',\n ],\n 'output' => [\n 'shape' => 'ListGeoLocationsResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidInput',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'ListHealthChecks' => [\n 'name' => 'ListHealthChecks',\n 'http' => [\n 'method' => 'GET',\n 'requestUri' => '/2013-04-01/healthcheck',\n ],\n 'input' => [\n 'shape' => 'ListHealthChecksRequest',\n ],\n 'output' => [\n 'shape' => 'ListHealthChecksResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidInput',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'IncompatibleVersion',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'ListHostedZones' => [\n 'name' => 'ListHostedZones',\n 'http' => [\n 'method' => 'GET',\n 'requestUri' => '/2013-04-01/hostedzone',\n ],\n 'input' => [\n 'shape' => 'ListHostedZonesRequest',\n ],\n 'output' => [\n 'shape' => 'ListHostedZonesResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidInput',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'NoSuchDelegationSet',\n 'exception' => true,\n ],\n [\n 'shape' => 'DelegationSetNotReusable',\n 'exception' => true,\n ],\n ],\n ],\n 'ListResourceRecordSets' => [\n 'name' => 'ListResourceRecordSets',\n 'http' => [\n 'method' => 'GET',\n 'requestUri' => '/2013-04-01/hostedzone/{Id}/rrset',\n ],\n 'input' => [\n 'shape' => 'ListResourceRecordSetsRequest',\n ],\n 'output' => [\n 'shape' => 'ListResourceRecordSetsResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchHostedZone',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidInput',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'ListReusableDelegationSets' => [\n 'name' => 'ListReusableDelegationSets',\n 'http' => [\n 'method' => 'GET',\n 'requestUri' => '/2013-04-01/delegationset',\n ],\n 'input' => [\n 'shape' => 'ListReusableDelegationSetsRequest',\n ],\n 'output' => [\n 'shape' => 'ListReusableDelegationSetsResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidInput',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'ListTagsForResource' => [\n 'name' => 'ListTagsForResource',\n 'http' => [\n 'method' => 'GET',\n 'requestUri' => '/2013-04-01/tags/{ResourceType}/{ResourceId}',\n ],\n 'input' => [\n 'shape' => 'ListTagsForResourceRequest',\n ],\n 'output' => [\n 'shape' => 'ListTagsForResourceResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidInput',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'NoSuchHealthCheck',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'NoSuchHostedZone',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'PriorRequestNotComplete',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'ThrottlingException',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'ListTagsForResources' => [\n 'name' => 'ListTagsForResources',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/2013-04-01/tags/{ResourceType}',\n ],\n 'input' => [\n 'shape' => 'ListTagsForResourcesRequest',\n 'xmlNamespace' => [\n 'uri' => 'https://route53.amazonaws.com/doc/2013-04-01/',\n ],\n 'locationName' => 'ListTagsForResourcesRequest',\n ],\n 'output' => [\n 'shape' => 'ListTagsForResourcesResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidInput',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'NoSuchHealthCheck',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'NoSuchHostedZone',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'PriorRequestNotComplete',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'ThrottlingException',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'UpdateHealthCheck' => [\n 'name' => 'UpdateHealthCheck',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/2013-04-01/healthcheck/{HealthCheckId}',\n ],\n 'input' => [\n 'shape' => 'UpdateHealthCheckRequest',\n 'xmlNamespace' => [\n 'uri' => 'https://route53.amazonaws.com/doc/2013-04-01/',\n ],\n 'locationName' => 'UpdateHealthCheckRequest',\n ],\n 'output' => [\n 'shape' => 'UpdateHealthCheckResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchHealthCheck',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidInput',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'HealthCheckVersionMismatch',\n 'error' => [\n 'httpStatusCode' => 409,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'UpdateHostedZoneComment' => [\n 'name' => 'UpdateHostedZoneComment',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/2013-04-01/hostedzone/{Id}',\n ],\n 'input' => [\n 'shape' => 'UpdateHostedZoneCommentRequest',\n 'xmlNamespace' => [\n 'uri' => 'https://route53.amazonaws.com/doc/2013-04-01/',\n ],\n 'locationName' => 'UpdateHostedZoneCommentRequest',\n ],\n 'output' => [\n 'shape' => 'UpdateHostedZoneCommentResponse',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchHostedZone',\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidInput',\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n ],\n ],\n ],\n 'shapes' => [\n 'AliasHealthEnabled' => [\n 'type' => 'boolean',\n ],\n 'AliasTarget' => [\n 'type' => 'structure',\n 'required' => [\n 'HostedZoneId',\n 'DNSName',\n 'EvaluateTargetHealth',\n ],\n 'members' => [\n 'HostedZoneId' => [\n 'shape' => 'ResourceId',\n ],\n 'DNSName' => [\n 'shape' => 'DNSName',\n ],\n 'EvaluateTargetHealth' => [\n 'shape' => 'AliasHealthEnabled',\n ],\n ],\n ],\n 'AssociateVPCComment' => [\n 'type' => 'string',\n ],\n 'AssociateVPCWithHostedZoneRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'HostedZoneId',\n 'VPC',\n ],\n 'members' => [\n 'HostedZoneId' => [\n 'shape' => 'ResourceId',\n 'location' => 'uri',\n 'locationName' => 'Id',\n ],\n 'VPC' => [\n 'shape' => 'VPC',\n ],\n 'Comment' => [\n 'shape' => 'AssociateVPCComment',\n ],\n ],\n ],\n 'AssociateVPCWithHostedZoneResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'ChangeInfo',\n ],\n 'members' => [\n 'ChangeInfo' => [\n 'shape' => 'ChangeInfo',\n ],\n ],\n ],\n 'Change' => [\n 'type' => 'structure',\n 'required' => [\n 'Action',\n 'ResourceRecordSet',\n ],\n 'members' => [\n 'Action' => [\n 'shape' => 'ChangeAction',\n ],\n 'ResourceRecordSet' => [\n 'shape' => 'ResourceRecordSet',\n ],\n ],\n ],\n 'ChangeAction' => [\n 'type' => 'string',\n 'enum' => [\n 'CREATE',\n 'DELETE',\n 'UPSERT',\n ],\n ],\n 'ChangeBatch' => [\n 'type' => 'structure',\n 'required' => [\n 'Changes',\n ],\n 'members' => [\n 'Comment' => [\n 'shape' => 'ResourceDescription',\n ],\n 'Changes' => [\n 'shape' => 'Changes',\n ],\n ],\n ],\n 'ChangeInfo' => [\n 'type' => 'structure',\n 'required' => [\n 'Id',\n 'Status',\n 'SubmittedAt',\n ],\n 'members' => [\n 'Id' => [\n 'shape' => 'ResourceId',\n ],\n 'Status' => [\n 'shape' => 'ChangeStatus',\n ],\n 'SubmittedAt' => [\n 'shape' => 'TimeStamp',\n ],\n 'Comment' => [\n 'shape' => 'ResourceDescription',\n ],\n ],\n ],\n 'ChangeResourceRecordSetsRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'HostedZoneId',\n 'ChangeBatch',\n ],\n 'members' => [\n 'HostedZoneId' => [\n 'shape' => 'ResourceId',\n 'location' => 'uri',\n 'locationName' => 'Id',\n ],\n 'ChangeBatch' => [\n 'shape' => 'ChangeBatch',\n ],\n ],\n ],\n 'ChangeResourceRecordSetsResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'ChangeInfo',\n ],\n 'members' => [\n 'ChangeInfo' => [\n 'shape' => 'ChangeInfo',\n ],\n ],\n ],\n 'ChangeStatus' => [\n 'type' => 'string',\n 'enum' => [\n 'PENDING',\n 'INSYNC',\n ],\n ],\n 'ChangeTagsForResourceRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'ResourceType',\n 'ResourceId',\n ],\n 'members' => [\n 'ResourceType' => [\n 'shape' => 'TagResourceType',\n 'location' => 'uri',\n 'locationName' => 'ResourceType',\n ],\n 'ResourceId' => [\n 'shape' => 'TagResourceId',\n 'location' => 'uri',\n 'locationName' => 'ResourceId',\n ],\n 'AddTags' => [\n 'shape' => 'TagList',\n ],\n 'RemoveTagKeys' => [\n 'shape' => 'TagKeyList',\n ],\n ],\n ],\n 'ChangeTagsForResourceResponse' => [\n 'type' => 'structure',\n 'members' => [],\n ],\n 'Changes' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'Change',\n 'locationName' => 'Change',\n ],\n 'min' => 1,\n ],\n 'CheckerIpRanges' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'IPAddressCidr',\n ],\n ],\n 'ConflictingDomainExists' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'exception' => true,\n ],\n 'CreateHealthCheckRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'CallerReference',\n 'HealthCheckConfig',\n ],\n 'members' => [\n 'CallerReference' => [\n 'shape' => 'HealthCheckNonce',\n ],\n 'HealthCheckConfig' => [\n 'shape' => 'HealthCheckConfig',\n ],\n ],\n ],\n 'CreateHealthCheckResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'HealthCheck',\n 'Location',\n ],\n 'members' => [\n 'HealthCheck' => [\n 'shape' => 'HealthCheck',\n ],\n 'Location' => [\n 'shape' => 'ResourceURI',\n 'location' => 'header',\n 'locationName' => 'Location',\n ],\n ],\n ],\n 'CreateHostedZoneRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'Name',\n 'CallerReference',\n ],\n 'members' => [\n 'Name' => [\n 'shape' => 'DNSName',\n ],\n 'VPC' => [\n 'shape' => 'VPC',\n ],\n 'CallerReference' => [\n 'shape' => 'Nonce',\n ],\n 'HostedZoneConfig' => [\n 'shape' => 'HostedZoneConfig',\n ],\n 'DelegationSetId' => [\n 'shape' => 'ResourceId',\n ],\n ],\n ],\n 'CreateHostedZoneResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'HostedZone',\n 'ChangeInfo',\n 'DelegationSet',\n 'Location',\n ],\n 'members' => [\n 'HostedZone' => [\n 'shape' => 'HostedZone',\n ],\n 'ChangeInfo' => [\n 'shape' => 'ChangeInfo',\n ],\n 'DelegationSet' => [\n 'shape' => 'DelegationSet',\n ],\n 'VPC' => [\n 'shape' => 'VPC',\n ],\n 'Location' => [\n 'shape' => 'ResourceURI',\n 'location' => 'header',\n 'locationName' => 'Location',\n ],\n ],\n ],\n 'CreateReusableDelegationSetRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'CallerReference',\n ],\n 'members' => [\n 'CallerReference' => [\n 'shape' => 'Nonce',\n ],\n 'HostedZoneId' => [\n 'shape' => 'ResourceId',\n ],\n ],\n ],\n 'CreateReusableDelegationSetResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'DelegationSet',\n 'Location',\n ],\n 'members' => [\n 'DelegationSet' => [\n 'shape' => 'DelegationSet',\n ],\n 'Location' => [\n 'shape' => 'ResourceURI',\n 'location' => 'header',\n 'locationName' => 'Location',\n ],\n ],\n ],\n 'DNSName' => [\n 'type' => 'string',\n 'max' => 1024,\n ],\n 'DelegationSet' => [\n 'type' => 'structure',\n 'required' => [\n 'NameServers',\n ],\n 'members' => [\n 'Id' => [\n 'shape' => 'ResourceId',\n ],\n 'CallerReference' => [\n 'shape' => 'Nonce',\n ],\n 'NameServers' => [\n 'shape' => 'DelegationSetNameServers',\n ],\n ],\n ],\n 'DelegationSetAlreadyCreated' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'exception' => true,\n ],\n 'DelegationSetAlreadyReusable' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'exception' => true,\n ],\n 'DelegationSetInUse' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'exception' => true,\n ],\n 'DelegationSetNameServers' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'DNSName',\n 'locationName' => 'NameServer',\n ],\n 'min' => 1,\n ],\n 'DelegationSetNotAvailable' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'exception' => true,\n ],\n 'DelegationSetNotReusable' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'exception' => true,\n ],\n 'DelegationSets' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'DelegationSet',\n 'locationName' => 'DelegationSet',\n ],\n ],\n 'DeleteHealthCheckRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'HealthCheckId',\n ],\n 'members' => [\n 'HealthCheckId' => [\n 'shape' => 'HealthCheckId',\n 'location' => 'uri',\n 'locationName' => 'HealthCheckId',\n ],\n ],\n ],\n 'DeleteHealthCheckResponse' => [\n 'type' => 'structure',\n 'members' => [],\n ],\n 'DeleteHostedZoneRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'Id',\n ],\n 'members' => [\n 'Id' => [\n 'shape' => 'ResourceId',\n 'location' => 'uri',\n 'locationName' => 'Id',\n ],\n ],\n ],\n 'DeleteHostedZoneResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'ChangeInfo',\n ],\n 'members' => [\n 'ChangeInfo' => [\n 'shape' => 'ChangeInfo',\n ],\n ],\n ],\n 'DeleteReusableDelegationSetRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'Id',\n ],\n 'members' => [\n 'Id' => [\n 'shape' => 'ResourceId',\n 'location' => 'uri',\n 'locationName' => 'Id',\n ],\n ],\n ],\n 'DeleteReusableDelegationSetResponse' => [\n 'type' => 'structure',\n 'members' => [],\n ],\n 'DisassociateVPCComment' => [\n 'type' => 'string',\n ],\n 'DisassociateVPCFromHostedZoneRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'HostedZoneId',\n 'VPC',\n ],\n 'members' => [\n 'HostedZoneId' => [\n 'shape' => 'ResourceId',\n 'location' => 'uri',\n 'locationName' => 'Id',\n ],\n 'VPC' => [\n 'shape' => 'VPC',\n ],\n 'Comment' => [\n 'shape' => 'DisassociateVPCComment',\n ],\n ],\n ],\n 'DisassociateVPCFromHostedZoneResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'ChangeInfo',\n ],\n 'members' => [\n 'ChangeInfo' => [\n 'shape' => 'ChangeInfo',\n ],\n ],\n ],\n 'ErrorMessage' => [\n 'type' => 'string',\n ],\n 'ErrorMessages' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'ErrorMessage',\n 'locationName' => 'Message',\n ],\n ],\n 'FailureThreshold' => [\n 'type' => 'integer',\n 'min' => 1,\n 'max' => 10,\n ],\n 'FullyQualifiedDomainName' => [\n 'type' => 'string',\n 'max' => 255,\n ],\n 'GeoLocation' => [\n 'type' => 'structure',\n 'members' => [\n 'ContinentCode' => [\n 'shape' => 'GeoLocationContinentCode',\n ],\n 'CountryCode' => [\n 'shape' => 'GeoLocationCountryCode',\n ],\n 'SubdivisionCode' => [\n 'shape' => 'GeoLocationSubdivisionCode',\n ],\n ],\n ],\n 'GeoLocationContinentCode' => [\n 'type' => 'string',\n 'min' => 2,\n 'max' => 2,\n ],\n 'GeoLocationContinentName' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 32,\n ],\n 'GeoLocationCountryCode' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 2,\n ],\n 'GeoLocationCountryName' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 64,\n ],\n 'GeoLocationDetails' => [\n 'type' => 'structure',\n 'members' => [\n 'ContinentCode' => [\n 'shape' => 'GeoLocationContinentCode',\n ],\n 'ContinentName' => [\n 'shape' => 'GeoLocationContinentName',\n ],\n 'CountryCode' => [\n 'shape' => 'GeoLocationCountryCode',\n ],\n 'CountryName' => [\n 'shape' => 'GeoLocationCountryName',\n ],\n 'SubdivisionCode' => [\n 'shape' => 'GeoLocationSubdivisionCode',\n ],\n 'SubdivisionName' => [\n 'shape' => 'GeoLocationSubdivisionName',\n ],\n ],\n ],\n 'GeoLocationDetailsList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'GeoLocationDetails',\n 'locationName' => 'GeoLocationDetails',\n ],\n ],\n 'GeoLocationSubdivisionCode' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 3,\n ],\n 'GeoLocationSubdivisionName' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 64,\n ],\n 'GetChangeRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'Id',\n ],\n 'members' => [\n 'Id' => [\n 'shape' => 'ResourceId',\n 'location' => 'uri',\n 'locationName' => 'Id',\n ],\n ],\n ],\n 'GetChangeResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'ChangeInfo',\n ],\n 'members' => [\n 'ChangeInfo' => [\n 'shape' => 'ChangeInfo',\n ],\n ],\n ],\n 'GetCheckerIpRangesRequest' => [\n 'type' => 'structure',\n 'members' => [],\n ],\n 'GetCheckerIpRangesResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'CheckerIpRanges',\n ],\n 'members' => [\n 'CheckerIpRanges' => [\n 'shape' => 'CheckerIpRanges',\n ],\n ],\n ],\n 'GetGeoLocationRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'ContinentCode' => [\n 'shape' => 'GeoLocationContinentCode',\n 'location' => 'querystring',\n 'locationName' => 'continentcode',\n ],\n 'CountryCode' => [\n 'shape' => 'GeoLocationCountryCode',\n 'location' => 'querystring',\n 'locationName' => 'countrycode',\n ],\n 'SubdivisionCode' => [\n 'shape' => 'GeoLocationSubdivisionCode',\n 'location' => 'querystring',\n 'locationName' => 'subdivisioncode',\n ],\n ],\n ],\n 'GetGeoLocationResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'GeoLocationDetails',\n ],\n 'members' => [\n 'GeoLocationDetails' => [\n 'shape' => 'GeoLocationDetails',\n ],\n ],\n ],\n 'GetHealthCheckCountRequest' => [\n 'type' => 'structure',\n 'members' => [],\n ],\n 'GetHealthCheckCountResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'HealthCheckCount',\n ],\n 'members' => [\n 'HealthCheckCount' => [\n 'shape' => 'HealthCheckCount',\n ],\n ],\n ],\n 'GetHealthCheckLastFailureReasonRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'HealthCheckId',\n ],\n 'members' => [\n 'HealthCheckId' => [\n 'shape' => 'HealthCheckId',\n 'location' => 'uri',\n 'locationName' => 'HealthCheckId',\n ],\n ],\n ],\n 'GetHealthCheckLastFailureReasonResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'HealthCheckObservations',\n ],\n 'members' => [\n 'HealthCheckObservations' => [\n 'shape' => 'HealthCheckObservations',\n ],\n ],\n ],\n 'GetHealthCheckRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'HealthCheckId',\n ],\n 'members' => [\n 'HealthCheckId' => [\n 'shape' => 'HealthCheckId',\n 'location' => 'uri',\n 'locationName' => 'HealthCheckId',\n ],\n ],\n ],\n 'GetHealthCheckResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'HealthCheck',\n ],\n 'members' => [\n 'HealthCheck' => [\n 'shape' => 'HealthCheck',\n ],\n ],\n ],\n 'GetHealthCheckStatusRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'HealthCheckId',\n ],\n 'members' => [\n 'HealthCheckId' => [\n 'shape' => 'HealthCheckId',\n 'location' => 'uri',\n 'locationName' => 'HealthCheckId',\n ],\n ],\n ],\n 'GetHealthCheckStatusResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'HealthCheckObservations',\n ],\n 'members' => [\n 'HealthCheckObservations' => [\n 'shape' => 'HealthCheckObservations',\n ],\n ],\n ],\n 'GetHostedZoneRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'Id',\n ],\n 'members' => [\n 'Id' => [\n 'shape' => 'ResourceId',\n 'location' => 'uri',\n 'locationName' => 'Id',\n ],\n ],\n ],\n 'GetHostedZoneResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'HostedZone',\n ],\n 'members' => [\n 'HostedZone' => [\n 'shape' => 'HostedZone',\n ],\n 'DelegationSet' => [\n 'shape' => 'DelegationSet',\n ],\n 'VPCs' => [\n 'shape' => 'VPCs',\n ],\n ],\n ],\n 'GetReusableDelegationSetRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'Id',\n ],\n 'members' => [\n 'Id' => [\n 'shape' => 'ResourceId',\n 'location' => 'uri',\n 'locationName' => 'Id',\n ],\n ],\n ],\n 'GetReusableDelegationSetResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'DelegationSet',\n ],\n 'members' => [\n 'DelegationSet' => [\n 'shape' => 'DelegationSet',\n ],\n ],\n ],\n 'HealthCheck' => [\n 'type' => 'structure',\n 'required' => [\n 'Id',\n 'CallerReference',\n 'HealthCheckConfig',\n 'HealthCheckVersion',\n ],\n 'members' => [\n 'Id' => [\n 'shape' => 'HealthCheckId',\n ],\n 'CallerReference' => [\n 'shape' => 'HealthCheckNonce',\n ],\n 'HealthCheckConfig' => [\n 'shape' => 'HealthCheckConfig',\n ],\n 'HealthCheckVersion' => [\n 'shape' => 'HealthCheckVersion',\n ],\n ],\n ],\n 'HealthCheckAlreadyExists' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'error' => [\n 'httpStatusCode' => 409,\n ],\n 'exception' => true,\n ],\n 'HealthCheckConfig' => [\n 'type' => 'structure',\n 'required' => [\n 'Type',\n ],\n 'members' => [\n 'IPAddress' => [\n 'shape' => 'IPAddress',\n ],\n 'Port' => [\n 'shape' => 'Port',\n ],\n 'Type' => [\n 'shape' => 'HealthCheckType',\n ],\n 'ResourcePath' => [\n 'shape' => 'ResourcePath',\n ],\n 'FullyQualifiedDomainName' => [\n 'shape' => 'FullyQualifiedDomainName',\n ],\n 'SearchString' => [\n 'shape' => 'SearchString',\n ],\n 'RequestInterval' => [\n 'shape' => 'RequestInterval',\n ],\n 'FailureThreshold' => [\n 'shape' => 'FailureThreshold',\n ],\n ],\n ],\n 'HealthCheckCount' => [\n 'type' => 'long',\n ],\n 'HealthCheckId' => [\n 'type' => 'string',\n 'max' => 64,\n ],\n 'HealthCheckInUse' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n 'HealthCheckNonce' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 64,\n ],\n 'HealthCheckObservation' => [\n 'type' => 'structure',\n 'members' => [\n 'IPAddress' => [\n 'shape' => 'IPAddress',\n ],\n 'StatusReport' => [\n 'shape' => 'StatusReport',\n ],\n ],\n ],\n 'HealthCheckObservations' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'HealthCheckObservation',\n 'locationName' => 'HealthCheckObservation',\n ],\n ],\n 'HealthCheckType' => [\n 'type' => 'string',\n 'enum' => [\n 'HTTP',\n 'HTTPS',\n 'HTTP_STR_MATCH',\n 'HTTPS_STR_MATCH',\n 'TCP',\n ],\n ],\n 'HealthCheckVersion' => [\n 'type' => 'long',\n 'min' => 1,\n ],\n 'HealthCheckVersionMismatch' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'error' => [\n 'httpStatusCode' => 409,\n ],\n 'exception' => true,\n ],\n 'HealthChecks' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'HealthCheck',\n 'locationName' => 'HealthCheck',\n ],\n ],\n 'HostedZone' => [\n 'type' => 'structure',\n 'required' => [\n 'Id',\n 'Name',\n 'CallerReference',\n ],\n 'members' => [\n 'Id' => [\n 'shape' => 'ResourceId',\n ],\n 'Name' => [\n 'shape' => 'DNSName',\n ],\n 'CallerReference' => [\n 'shape' => 'Nonce',\n ],\n 'Config' => [\n 'shape' => 'HostedZoneConfig',\n ],\n 'ResourceRecordSetCount' => [\n 'shape' => 'HostedZoneRRSetCount',\n ],\n ],\n ],\n 'HostedZoneAlreadyExists' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'error' => [\n 'httpStatusCode' => 409,\n ],\n 'exception' => true,\n ],\n 'HostedZoneConfig' => [\n 'type' => 'structure',\n 'members' => [\n 'Comment' => [\n 'shape' => 'ResourceDescription',\n ],\n 'PrivateZone' => [\n 'shape' => 'IsPrivateZone',\n ],\n ],\n ],\n 'HostedZoneNotEmpty' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n 'HostedZoneNotFound' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'exception' => true,\n ],\n 'HostedZoneRRSetCount' => [\n 'type' => 'long',\n ],\n 'HostedZones' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'HostedZone',\n 'locationName' => 'HostedZone',\n ],\n ],\n 'IPAddress' => [\n 'type' => 'string',\n 'max' => 15,\n 'pattern' => '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]]\\\\.]{3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]]$',\n ],\n 'IPAddressCidr' => [\n 'type' => 'string',\n ],\n 'IncompatibleVersion' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n 'InvalidArgument' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'exception' => true,\n ],\n 'InvalidChangeBatch' => [\n 'type' => 'structure',\n 'members' => [\n 'messages' => [\n 'shape' => 'ErrorMessages',\n ],\n ],\n 'exception' => true,\n ],\n 'InvalidDomainName' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n 'InvalidInput' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n 'InvalidVPCId' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n 'IsPrivateZone' => [\n 'type' => 'boolean',\n ],\n 'LastVPCAssociation' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n 'LimitsExceeded' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'exception' => true,\n ],\n 'ListGeoLocationsRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'StartContinentCode' => [\n 'shape' => 'GeoLocationContinentCode',\n 'location' => 'querystring',\n 'locationName' => 'startcontinentcode',\n ],\n 'StartCountryCode' => [\n 'shape' => 'GeoLocationCountryCode',\n 'location' => 'querystring',\n 'locationName' => 'startcountrycode',\n ],\n 'StartSubdivisionCode' => [\n 'shape' => 'GeoLocationSubdivisionCode',\n 'location' => 'querystring',\n 'locationName' => 'startsubdivisioncode',\n ],\n 'MaxItems' => [\n 'shape' => 'PageMaxItems',\n 'location' => 'querystring',\n 'locationName' => 'maxitems',\n ],\n ],\n ],\n 'ListGeoLocationsResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'GeoLocationDetailsList',\n 'IsTruncated',\n 'MaxItems',\n ],\n 'members' => [\n 'GeoLocationDetailsList' => [\n 'shape' => 'GeoLocationDetailsList',\n ],\n 'IsTruncated' => [\n 'shape' => 'PageTruncated',\n ],\n 'NextContinentCode' => [\n 'shape' => 'GeoLocationContinentCode',\n ],\n 'NextCountryCode' => [\n 'shape' => 'GeoLocationCountryCode',\n ],\n 'NextSubdivisionCode' => [\n 'shape' => 'GeoLocationSubdivisionCode',\n ],\n 'MaxItems' => [\n 'shape' => 'PageMaxItems',\n ],\n ],\n ],\n 'ListHealthChecksRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'Marker' => [\n 'shape' => 'PageMarker',\n 'location' => 'querystring',\n 'locationName' => 'marker',\n ],\n 'MaxItems' => [\n 'shape' => 'PageMaxItems',\n 'location' => 'querystring',\n 'locationName' => 'maxitems',\n ],\n ],\n ],\n 'ListHealthChecksResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'HealthChecks',\n 'Marker',\n 'IsTruncated',\n 'MaxItems',\n ],\n 'members' => [\n 'HealthChecks' => [\n 'shape' => 'HealthChecks',\n ],\n 'Marker' => [\n 'shape' => 'PageMarker',\n ],\n 'IsTruncated' => [\n 'shape' => 'PageTruncated',\n ],\n 'NextMarker' => [\n 'shape' => 'PageMarker',\n ],\n 'MaxItems' => [\n 'shape' => 'PageMaxItems',\n ],\n ],\n ],\n 'ListHostedZonesRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'Marker' => [\n 'shape' => 'PageMarker',\n 'location' => 'querystring',\n 'locationName' => 'marker',\n ],\n 'MaxItems' => [\n 'shape' => 'PageMaxItems',\n 'location' => 'querystring',\n 'locationName' => 'maxitems',\n ],\n 'DelegationSetId' => [\n 'shape' => 'ResourceId',\n 'location' => 'querystring',\n 'locationName' => 'delegationsetid',\n ],\n ],\n ],\n 'ListHostedZonesResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'HostedZones',\n 'Marker',\n 'IsTruncated',\n 'MaxItems',\n ],\n 'members' => [\n 'HostedZones' => [\n 'shape' => 'HostedZones',\n ],\n 'Marker' => [\n 'shape' => 'PageMarker',\n ],\n 'IsTruncated' => [\n 'shape' => 'PageTruncated',\n ],\n 'NextMarker' => [\n 'shape' => 'PageMarker',\n ],\n 'MaxItems' => [\n 'shape' => 'PageMaxItems',\n ],\n ],\n ],\n 'ListResourceRecordSetsRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'HostedZoneId',\n ],\n 'members' => [\n 'HostedZoneId' => [\n 'shape' => 'ResourceId',\n 'location' => 'uri',\n 'locationName' => 'Id',\n ],\n 'StartRecordName' => [\n 'shape' => 'DNSName',\n 'location' => 'querystring',\n 'locationName' => 'name',\n ],\n 'StartRecordType' => [\n 'shape' => 'RRType',\n 'location' => 'querystring',\n 'locationName' => 'type',\n ],\n 'StartRecordIdentifier' => [\n 'shape' => 'ResourceRecordSetIdentifier',\n 'location' => 'querystring',\n 'locationName' => 'identifier',\n ],\n 'MaxItems' => [\n 'shape' => 'PageMaxItems',\n 'location' => 'querystring',\n 'locationName' => 'maxitems',\n ],\n ],\n ],\n 'ListResourceRecordSetsResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'ResourceRecordSets',\n 'IsTruncated',\n 'MaxItems',\n ],\n 'members' => [\n 'ResourceRecordSets' => [\n 'shape' => 'ResourceRecordSets',\n ],\n 'IsTruncated' => [\n 'shape' => 'PageTruncated',\n ],\n 'NextRecordName' => [\n 'shape' => 'DNSName',\n ],\n 'NextRecordType' => [\n 'shape' => 'RRType',\n ],\n 'NextRecordIdentifier' => [\n 'shape' => 'ResourceRecordSetIdentifier',\n ],\n 'MaxItems' => [\n 'shape' => 'PageMaxItems',\n ],\n ],\n ],\n 'ListReusableDelegationSetsRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'Marker' => [\n 'shape' => 'PageMarker',\n 'location' => 'querystring',\n 'locationName' => 'marker',\n ],\n 'MaxItems' => [\n 'shape' => 'PageMaxItems',\n 'location' => 'querystring',\n 'locationName' => 'maxitems',\n ],\n ],\n ],\n 'ListReusableDelegationSetsResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'DelegationSets',\n 'Marker',\n 'IsTruncated',\n 'MaxItems',\n ],\n 'members' => [\n 'DelegationSets' => [\n 'shape' => 'DelegationSets',\n ],\n 'Marker' => [\n 'shape' => 'PageMarker',\n ],\n 'IsTruncated' => [\n 'shape' => 'PageTruncated',\n ],\n 'NextMarker' => [\n 'shape' => 'PageMarker',\n ],\n 'MaxItems' => [\n 'shape' => 'PageMaxItems',\n ],\n ],\n ],\n 'ListTagsForResourceRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'ResourceType',\n 'ResourceId',\n ],\n 'members' => [\n 'ResourceType' => [\n 'shape' => 'TagResourceType',\n 'location' => 'uri',\n 'locationName' => 'ResourceType',\n ],\n 'ResourceId' => [\n 'shape' => 'TagResourceId',\n 'location' => 'uri',\n 'locationName' => 'ResourceId',\n ],\n ],\n ],\n 'ListTagsForResourceResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'ResourceTagSet',\n ],\n 'members' => [\n 'ResourceTagSet' => [\n 'shape' => 'ResourceTagSet',\n ],\n ],\n ],\n 'ListTagsForResourcesRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'ResourceType',\n 'ResourceIds',\n ],\n 'members' => [\n 'ResourceType' => [\n 'shape' => 'TagResourceType',\n 'location' => 'uri',\n 'locationName' => 'ResourceType',\n ],\n 'ResourceIds' => [\n 'shape' => 'TagResourceIdList',\n ],\n ],\n ],\n 'ListTagsForResourcesResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'ResourceTagSets',\n ],\n 'members' => [\n 'ResourceTagSets' => [\n 'shape' => 'ResourceTagSetList',\n ],\n ],\n ],\n 'NoSuchChange' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n 'NoSuchDelegationSet' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'exception' => true,\n ],\n 'NoSuchGeoLocation' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n 'NoSuchHealthCheck' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n 'NoSuchHostedZone' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n 'Nonce' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 128,\n ],\n 'PageMarker' => [\n 'type' => 'string',\n 'max' => 64,\n ],\n 'PageMaxItems' => [\n 'type' => 'string',\n ],\n 'PageTruncated' => [\n 'type' => 'boolean',\n ],\n 'Port' => [\n 'type' => 'integer',\n 'min' => 1,\n 'max' => 65535,\n ],\n 'PriorRequestNotComplete' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n 'PublicZoneVPCAssociation' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n 'RData' => [\n 'type' => 'string',\n 'max' => 4000,\n ],\n 'RRType' => [\n 'type' => 'string',\n 'enum' => [\n 'SOA',\n 'A',\n 'TXT',\n 'NS',\n 'CNAME',\n 'MX',\n 'PTR',\n 'SRV',\n 'SPF',\n 'AAAA',\n ],\n ],\n 'RequestInterval' => [\n 'type' => 'integer',\n 'min' => 10,\n 'max' => 30,\n ],\n 'ResourceDescription' => [\n 'type' => 'string',\n 'max' => 256,\n ],\n 'ResourceId' => [\n 'type' => 'string',\n 'max' => 32,\n ],\n 'ResourcePath' => [\n 'type' => 'string',\n 'max' => 255,\n ],\n 'ResourceRecord' => [\n 'type' => 'structure',\n 'required' => [\n 'Value',\n ],\n 'members' => [\n 'Value' => [\n 'shape' => 'RData',\n ],\n ],\n ],\n 'ResourceRecordSet' => [\n 'type' => 'structure',\n 'required' => [\n 'Name',\n 'Type',\n ],\n 'members' => [\n 'Name' => [\n 'shape' => 'DNSName',\n ],\n 'Type' => [\n 'shape' => 'RRType',\n ],\n 'SetIdentifier' => [\n 'shape' => 'ResourceRecordSetIdentifier',\n ],\n 'Weight' => [\n 'shape' => 'ResourceRecordSetWeight',\n ],\n 'Region' => [\n 'shape' => 'ResourceRecordSetRegion',\n ],\n 'GeoLocation' => [\n 'shape' => 'GeoLocation',\n ],\n 'Failover' => [\n 'shape' => 'ResourceRecordSetFailover',\n ],\n 'TTL' => [\n 'shape' => 'TTL',\n ],\n 'ResourceRecords' => [\n 'shape' => 'ResourceRecords',\n ],\n 'AliasTarget' => [\n 'shape' => 'AliasTarget',\n ],\n 'HealthCheckId' => [\n 'shape' => 'HealthCheckId',\n ],\n ],\n ],\n 'ResourceRecordSetFailover' => [\n 'type' => 'string',\n 'enum' => [\n 'PRIMARY',\n 'SECONDARY',\n ],\n ],\n 'ResourceRecordSetIdentifier' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 128,\n ],\n 'ResourceRecordSetRegion' => [\n 'type' => 'string',\n 'enum' => [\n 'us-east-1',\n 'us-west-1',\n 'us-west-2',\n 'eu-west-1',\n 'eu-central-1',\n 'ap-southeast-1',\n 'ap-southeast-2',\n 'ap-northeast-1',\n 'sa-east-1',\n 'cn-north-1',\n ],\n 'min' => 1,\n 'max' => 64,\n ],\n 'ResourceRecordSetWeight' => [\n 'type' => 'long',\n 'min' => 0,\n 'max' => 255,\n ],\n 'ResourceRecordSets' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'ResourceRecordSet',\n 'locationName' => 'ResourceRecordSet',\n ],\n ],\n 'ResourceRecords' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'ResourceRecord',\n 'locationName' => 'ResourceRecord',\n ],\n 'min' => 1,\n ],\n 'ResourceTagSet' => [\n 'type' => 'structure',\n 'members' => [\n 'ResourceType' => [\n 'shape' => 'TagResourceType',\n ],\n 'ResourceId' => [\n 'shape' => 'TagResourceId',\n ],\n 'Tags' => [\n 'shape' => 'TagList',\n ],\n ],\n ],\n 'ResourceTagSetList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'ResourceTagSet',\n 'locationName' => 'ResourceTagSet',\n ],\n ],\n 'ResourceURI' => [\n 'type' => 'string',\n 'max' => 1024,\n ],\n 'SearchString' => [\n 'type' => 'string',\n 'max' => 255,\n ],\n 'Status' => [\n 'type' => 'string',\n ],\n 'StatusReport' => [\n 'type' => 'structure',\n 'members' => [\n 'Status' => [\n 'shape' => 'Status',\n ],\n 'CheckedTime' => [\n 'shape' => 'TimeStamp',\n ],\n ],\n ],\n 'TTL' => [\n 'type' => 'long',\n 'min' => 0,\n 'max' => 2147483647,\n ],\n 'Tag' => [\n 'type' => 'structure',\n 'members' => [\n 'Key' => [\n 'shape' => 'TagKey',\n ],\n 'Value' => [\n 'shape' => 'TagValue',\n ],\n ],\n ],\n 'TagKey' => [\n 'type' => 'string',\n 'max' => 128,\n ],\n 'TagKeyList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'TagKey',\n 'locationName' => 'Key',\n ],\n 'min' => 1,\n 'max' => 10,\n ],\n 'TagList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'Tag',\n 'locationName' => 'Tag',\n ],\n 'min' => 1,\n 'max' => 10,\n ],\n 'TagResourceId' => [\n 'type' => 'string',\n 'max' => 64,\n ],\n 'TagResourceIdList' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'TagResourceId',\n 'locationName' => 'ResourceId',\n ],\n 'min' => 1,\n 'max' => 10,\n ],\n 'TagResourceType' => [\n 'type' => 'string',\n 'enum' => [\n 'healthcheck',\n 'hostedzone',\n ],\n ],\n 'TagValue' => [\n 'type' => 'string',\n 'max' => 256,\n ],\n 'ThrottlingException' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n 'TimeStamp' => [\n 'type' => 'timestamp',\n ],\n 'TooManyHealthChecks' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'exception' => true,\n ],\n 'TooManyHostedZones' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'error' => [\n 'httpStatusCode' => 400,\n ],\n 'exception' => true,\n ],\n 'UpdateHealthCheckRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'HealthCheckId',\n ],\n 'members' => [\n 'HealthCheckId' => [\n 'shape' => 'HealthCheckId',\n 'location' => 'uri',\n 'locationName' => 'HealthCheckId',\n ],\n 'HealthCheckVersion' => [\n 'shape' => 'HealthCheckVersion',\n ],\n 'IPAddress' => [\n 'shape' => 'IPAddress',\n ],\n 'Port' => [\n 'shape' => 'Port',\n ],\n 'ResourcePath' => [\n 'shape' => 'ResourcePath',\n ],\n 'FullyQualifiedDomainName' => [\n 'shape' => 'FullyQualifiedDomainName',\n ],\n 'SearchString' => [\n 'shape' => 'SearchString',\n ],\n 'FailureThreshold' => [\n 'shape' => 'FailureThreshold',\n ],\n ],\n ],\n 'UpdateHealthCheckResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'HealthCheck',\n ],\n 'members' => [\n 'HealthCheck' => [\n 'shape' => 'HealthCheck',\n ],\n ],\n ],\n 'UpdateHostedZoneCommentRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'Id',\n ],\n 'members' => [\n 'Id' => [\n 'shape' => 'ResourceId',\n 'location' => 'uri',\n 'locationName' => 'Id',\n ],\n 'Comment' => [\n 'shape' => 'ResourceDescription',\n ],\n ],\n ],\n 'UpdateHostedZoneCommentResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'HostedZone',\n ],\n 'members' => [\n 'HostedZone' => [\n 'shape' => 'HostedZone',\n ],\n ],\n ],\n 'VPC' => [\n 'type' => 'structure',\n 'members' => [\n 'VPCRegion' => [\n 'shape' => 'VPCRegion',\n ],\n 'VPCId' => [\n 'shape' => 'VPCId',\n ],\n ],\n ],\n 'VPCAssociationNotFound' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'ErrorMessage',\n ],\n ],\n 'error' => [\n 'httpStatusCode' => 404,\n ],\n 'exception' => true,\n ],\n 'VPCId' => [\n 'type' => 'string',\n 'max' => 1024,\n ],\n 'VPCRegion' => [\n 'type' => 'string',\n 'enum' => [\n 'us-east-1',\n 'us-west-1',\n 'us-west-2',\n 'eu-west-1',\n 'eu-central-1',\n 'ap-southeast-1',\n 'ap-southeast-2',\n 'ap-northeast-1',\n 'sa-east-1',\n 'cn-north-1',\n ],\n 'min' => 1,\n 'max' => 64,\n ],\n 'VPCs' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'VPC',\n 'locationName' => 'VPC',\n ],\n 'min' => 1,\n ],\n ],\n];\n" }, { "alpha_fraction": 0.6132930517196655, "alphanum_fraction": 0.6132930517196655, "avg_line_length": 23.219512939453125, "blob_id": "385e5eaf601ccd4b2ce087655f0b02ba30fcab82", "content_id": "8a6b0d6ac3a4c40b8be9d7a5be70ef31862d24e8", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 993, "license_type": "permissive", "max_line_length": 63, "num_lines": 41, "path": "/src/Api/Serializer/RestXmlSerializer.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Api\\Serializer;\n\nuse Aws\\Api\\StructureShape;\nuse Aws\\Api\\Service;\nuse GuzzleHttp\\Message\\RequestInterface;\nuse GuzzleHttp\\Stream\\Stream;\n\n/**\n * @internal\n */\nclass RestXmlSerializer extends RestSerializer\n{\n /** @var XmlBody */\n private $xmlBody;\n\n /**\n * @param Service $api Service API description\n * @param string $endpoint Endpoint to connect to\n * @param XmlBody $xmlBody Optional XML formatter to use\n */\n public function __construct(\n Service $api,\n $endpoint,\n XmlBody $xmlBody = null\n ) {\n parent::__construct($api, $endpoint);\n $this->xmlBody = $xmlBody ?: new XmlBody($api);\n }\n\n protected function payload(\n RequestInterface $request,\n StructureShape $member,\n array $value\n ) {\n $request->setHeader('Content-Type', 'application/xml');\n $request->setBody(Stream::factory(\n $this->xmlBody->build($member, $value)\n ));\n }\n}\n" }, { "alpha_fraction": 0.4004097282886505, "alphanum_fraction": 0.40664324164390564, "avg_line_length": 23.3853702545166, "blob_id": "b296649b0c2f8cdf42147e66fdcb8e5f857639e4", "content_id": "384d94435eb80d261cd526427d08c4c46b6dc028", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 136680, "license_type": "permissive", "max_line_length": 68, "num_lines": 5605, "path": "/src/data/iam-2010-05-08.api.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php return [\n 'metadata' => [\n 'apiVersion' => '2010-05-08',\n 'endpointPrefix' => 'iam',\n 'globalEndpoint' => 'iam.amazonaws.com',\n 'serviceAbbreviation' => 'IAM',\n 'serviceFullName' => 'AWS Identity and Access Management',\n 'signatureVersion' => 'v4',\n 'xmlNamespace' => 'https://iam.amazonaws.com/doc/2010-05-08/',\n 'protocol' => 'query',\n ],\n 'operations' => [\n 'AddClientIDToOpenIDConnectProvider' => [\n 'name' => 'AddClientIDToOpenIDConnectProvider',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'AddClientIDToOpenIDConnectProviderRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidInputException',\n 'error' => [\n 'code' => 'InvalidInput',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'AddRoleToInstanceProfile' => [\n 'name' => 'AddRoleToInstanceProfile',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'AddRoleToInstanceProfileRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'EntityAlreadyExistsException',\n 'error' => [\n 'code' => 'EntityAlreadyExists',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'AddUserToGroup' => [\n 'name' => 'AddUserToGroup',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'AddUserToGroupRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'ChangePassword' => [\n 'name' => 'ChangePassword',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ChangePasswordRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidUserTypeException',\n 'error' => [\n 'code' => 'InvalidUserType',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'EntityTemporarilyUnmodifiableException',\n 'error' => [\n 'code' => 'EntityTemporarilyUnmodifiable',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'PasswordPolicyViolationException',\n 'error' => [\n 'code' => 'PasswordPolicyViolation',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'CreateAccessKey' => [\n 'name' => 'CreateAccessKey',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateAccessKeyRequest',\n ],\n 'output' => [\n 'shape' => 'CreateAccessKeyResponse',\n 'resultWrapper' => 'CreateAccessKeyResult',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'CreateAccountAlias' => [\n 'name' => 'CreateAccountAlias',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateAccountAliasRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'EntityAlreadyExistsException',\n 'error' => [\n 'code' => 'EntityAlreadyExists',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'CreateGroup' => [\n 'name' => 'CreateGroup',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateGroupRequest',\n ],\n 'output' => [\n 'shape' => 'CreateGroupResponse',\n 'resultWrapper' => 'CreateGroupResult',\n ],\n 'errors' => [\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'EntityAlreadyExistsException',\n 'error' => [\n 'code' => 'EntityAlreadyExists',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'CreateInstanceProfile' => [\n 'name' => 'CreateInstanceProfile',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateInstanceProfileRequest',\n ],\n 'output' => [\n 'shape' => 'CreateInstanceProfileResponse',\n 'resultWrapper' => 'CreateInstanceProfileResult',\n ],\n 'errors' => [\n [\n 'shape' => 'EntityAlreadyExistsException',\n 'error' => [\n 'code' => 'EntityAlreadyExists',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'CreateLoginProfile' => [\n 'name' => 'CreateLoginProfile',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateLoginProfileRequest',\n ],\n 'output' => [\n 'shape' => 'CreateLoginProfileResponse',\n 'resultWrapper' => 'CreateLoginProfileResult',\n ],\n 'errors' => [\n [\n 'shape' => 'EntityAlreadyExistsException',\n 'error' => [\n 'code' => 'EntityAlreadyExists',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'PasswordPolicyViolationException',\n 'error' => [\n 'code' => 'PasswordPolicyViolation',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'CreateOpenIDConnectProvider' => [\n 'name' => 'CreateOpenIDConnectProvider',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateOpenIDConnectProviderRequest',\n ],\n 'output' => [\n 'shape' => 'CreateOpenIDConnectProviderResponse',\n 'resultWrapper' => 'CreateOpenIDConnectProviderResult',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidInputException',\n 'error' => [\n 'code' => 'InvalidInput',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'EntityAlreadyExistsException',\n 'error' => [\n 'code' => 'EntityAlreadyExists',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'CreateRole' => [\n 'name' => 'CreateRole',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateRoleRequest',\n ],\n 'output' => [\n 'shape' => 'CreateRoleResponse',\n 'resultWrapper' => 'CreateRoleResult',\n ],\n 'errors' => [\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'EntityAlreadyExistsException',\n 'error' => [\n 'code' => 'EntityAlreadyExists',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'MalformedPolicyDocumentException',\n 'error' => [\n 'code' => 'MalformedPolicyDocument',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'CreateSAMLProvider' => [\n 'name' => 'CreateSAMLProvider',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateSAMLProviderRequest',\n ],\n 'output' => [\n 'shape' => 'CreateSAMLProviderResponse',\n 'resultWrapper' => 'CreateSAMLProviderResult',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidInputException',\n 'error' => [\n 'code' => 'InvalidInput',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'EntityAlreadyExistsException',\n 'error' => [\n 'code' => 'EntityAlreadyExists',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'CreateUser' => [\n 'name' => 'CreateUser',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateUserRequest',\n ],\n 'output' => [\n 'shape' => 'CreateUserResponse',\n 'resultWrapper' => 'CreateUserResult',\n ],\n 'errors' => [\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'EntityAlreadyExistsException',\n 'error' => [\n 'code' => 'EntityAlreadyExists',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'CreateVirtualMFADevice' => [\n 'name' => 'CreateVirtualMFADevice',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'CreateVirtualMFADeviceRequest',\n ],\n 'output' => [\n 'shape' => 'CreateVirtualMFADeviceResponse',\n 'resultWrapper' => 'CreateVirtualMFADeviceResult',\n ],\n 'errors' => [\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'EntityAlreadyExistsException',\n 'error' => [\n 'code' => 'EntityAlreadyExists',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'DeactivateMFADevice' => [\n 'name' => 'DeactivateMFADevice',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeactivateMFADeviceRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'EntityTemporarilyUnmodifiableException',\n 'error' => [\n 'code' => 'EntityTemporarilyUnmodifiable',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'DeleteAccessKey' => [\n 'name' => 'DeleteAccessKey',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteAccessKeyRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'DeleteAccountAlias' => [\n 'name' => 'DeleteAccountAlias',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteAccountAliasRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'DeleteAccountPasswordPolicy' => [\n 'name' => 'DeleteAccountPasswordPolicy',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'DeleteGroup' => [\n 'name' => 'DeleteGroup',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteGroupRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'DeleteConflictException',\n 'error' => [\n 'code' => 'DeleteConflict',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'DeleteGroupPolicy' => [\n 'name' => 'DeleteGroupPolicy',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteGroupPolicyRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'DeleteInstanceProfile' => [\n 'name' => 'DeleteInstanceProfile',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteInstanceProfileRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'DeleteConflictException',\n 'error' => [\n 'code' => 'DeleteConflict',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'DeleteLoginProfile' => [\n 'name' => 'DeleteLoginProfile',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteLoginProfileRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'EntityTemporarilyUnmodifiableException',\n 'error' => [\n 'code' => 'EntityTemporarilyUnmodifiable',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'DeleteOpenIDConnectProvider' => [\n 'name' => 'DeleteOpenIDConnectProvider',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteOpenIDConnectProviderRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidInputException',\n 'error' => [\n 'code' => 'InvalidInput',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'DeleteRole' => [\n 'name' => 'DeleteRole',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteRoleRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'DeleteConflictException',\n 'error' => [\n 'code' => 'DeleteConflict',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'DeleteRolePolicy' => [\n 'name' => 'DeleteRolePolicy',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteRolePolicyRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'DeleteSAMLProvider' => [\n 'name' => 'DeleteSAMLProvider',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteSAMLProviderRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidInputException',\n 'error' => [\n 'code' => 'InvalidInput',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'DeleteServerCertificate' => [\n 'name' => 'DeleteServerCertificate',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteServerCertificateRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'DeleteConflictException',\n 'error' => [\n 'code' => 'DeleteConflict',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'DeleteSigningCertificate' => [\n 'name' => 'DeleteSigningCertificate',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteSigningCertificateRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'DeleteUser' => [\n 'name' => 'DeleteUser',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteUserRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'DeleteConflictException',\n 'error' => [\n 'code' => 'DeleteConflict',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'DeleteUserPolicy' => [\n 'name' => 'DeleteUserPolicy',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteUserPolicyRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'DeleteVirtualMFADevice' => [\n 'name' => 'DeleteVirtualMFADevice',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'DeleteVirtualMFADeviceRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'DeleteConflictException',\n 'error' => [\n 'code' => 'DeleteConflict',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'EnableMFADevice' => [\n 'name' => 'EnableMFADevice',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'EnableMFADeviceRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'EntityAlreadyExistsException',\n 'error' => [\n 'code' => 'EntityAlreadyExists',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'EntityTemporarilyUnmodifiableException',\n 'error' => [\n 'code' => 'EntityTemporarilyUnmodifiable',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidAuthenticationCodeException',\n 'error' => [\n 'code' => 'InvalidAuthenticationCode',\n 'httpStatusCode' => 403,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'GenerateCredentialReport' => [\n 'name' => 'GenerateCredentialReport',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'output' => [\n 'shape' => 'GenerateCredentialReportResponse',\n 'resultWrapper' => 'GenerateCredentialReportResult',\n ],\n 'errors' => [\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'GetAccountAuthorizationDetails' => [\n 'name' => 'GetAccountAuthorizationDetails',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'GetAccountAuthorizationDetailsRequest',\n ],\n 'output' => [\n 'shape' => 'GetAccountAuthorizationDetailsResponse',\n 'resultWrapper' => 'GetAccountAuthorizationDetailsResult',\n ],\n ],\n 'GetAccountPasswordPolicy' => [\n 'name' => 'GetAccountPasswordPolicy',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'output' => [\n 'shape' => 'GetAccountPasswordPolicyResponse',\n 'resultWrapper' => 'GetAccountPasswordPolicyResult',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'GetAccountSummary' => [\n 'name' => 'GetAccountSummary',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'output' => [\n 'shape' => 'GetAccountSummaryResponse',\n 'resultWrapper' => 'GetAccountSummaryResult',\n ],\n ],\n 'GetCredentialReport' => [\n 'name' => 'GetCredentialReport',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'output' => [\n 'shape' => 'GetCredentialReportResponse',\n 'resultWrapper' => 'GetCredentialReportResult',\n ],\n 'errors' => [\n [\n 'shape' => 'CredentialReportNotPresentException',\n 'error' => [\n 'code' => 'ReportNotPresent',\n 'httpStatusCode' => 410,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'CredentialReportExpiredException',\n 'error' => [\n 'code' => 'ReportExpired',\n 'httpStatusCode' => 410,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'CredentialReportNotReadyException',\n 'error' => [\n 'code' => 'ReportInProgress',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'GetGroup' => [\n 'name' => 'GetGroup',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'GetGroupRequest',\n ],\n 'output' => [\n 'shape' => 'GetGroupResponse',\n 'resultWrapper' => 'GetGroupResult',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'GetGroupPolicy' => [\n 'name' => 'GetGroupPolicy',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'GetGroupPolicyRequest',\n ],\n 'output' => [\n 'shape' => 'GetGroupPolicyResponse',\n 'resultWrapper' => 'GetGroupPolicyResult',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'GetInstanceProfile' => [\n 'name' => 'GetInstanceProfile',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'GetInstanceProfileRequest',\n ],\n 'output' => [\n 'shape' => 'GetInstanceProfileResponse',\n 'resultWrapper' => 'GetInstanceProfileResult',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'GetLoginProfile' => [\n 'name' => 'GetLoginProfile',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'GetLoginProfileRequest',\n ],\n 'output' => [\n 'shape' => 'GetLoginProfileResponse',\n 'resultWrapper' => 'GetLoginProfileResult',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'GetOpenIDConnectProvider' => [\n 'name' => 'GetOpenIDConnectProvider',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'GetOpenIDConnectProviderRequest',\n ],\n 'output' => [\n 'shape' => 'GetOpenIDConnectProviderResponse',\n 'resultWrapper' => 'GetOpenIDConnectProviderResult',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidInputException',\n 'error' => [\n 'code' => 'InvalidInput',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'GetRole' => [\n 'name' => 'GetRole',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'GetRoleRequest',\n ],\n 'output' => [\n 'shape' => 'GetRoleResponse',\n 'resultWrapper' => 'GetRoleResult',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'GetRolePolicy' => [\n 'name' => 'GetRolePolicy',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'GetRolePolicyRequest',\n ],\n 'output' => [\n 'shape' => 'GetRolePolicyResponse',\n 'resultWrapper' => 'GetRolePolicyResult',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'GetSAMLProvider' => [\n 'name' => 'GetSAMLProvider',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'GetSAMLProviderRequest',\n ],\n 'output' => [\n 'shape' => 'GetSAMLProviderResponse',\n 'resultWrapper' => 'GetSAMLProviderResult',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidInputException',\n 'error' => [\n 'code' => 'InvalidInput',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'GetServerCertificate' => [\n 'name' => 'GetServerCertificate',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'GetServerCertificateRequest',\n ],\n 'output' => [\n 'shape' => 'GetServerCertificateResponse',\n 'resultWrapper' => 'GetServerCertificateResult',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'GetUser' => [\n 'name' => 'GetUser',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'GetUserRequest',\n ],\n 'output' => [\n 'shape' => 'GetUserResponse',\n 'resultWrapper' => 'GetUserResult',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'GetUserPolicy' => [\n 'name' => 'GetUserPolicy',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'GetUserPolicyRequest',\n ],\n 'output' => [\n 'shape' => 'GetUserPolicyResponse',\n 'resultWrapper' => 'GetUserPolicyResult',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'ListAccessKeys' => [\n 'name' => 'ListAccessKeys',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ListAccessKeysRequest',\n ],\n 'output' => [\n 'shape' => 'ListAccessKeysResponse',\n 'resultWrapper' => 'ListAccessKeysResult',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'ListAccountAliases' => [\n 'name' => 'ListAccountAliases',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ListAccountAliasesRequest',\n ],\n 'output' => [\n 'shape' => 'ListAccountAliasesResponse',\n 'resultWrapper' => 'ListAccountAliasesResult',\n ],\n ],\n 'ListGroupPolicies' => [\n 'name' => 'ListGroupPolicies',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ListGroupPoliciesRequest',\n ],\n 'output' => [\n 'shape' => 'ListGroupPoliciesResponse',\n 'resultWrapper' => 'ListGroupPoliciesResult',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'ListGroups' => [\n 'name' => 'ListGroups',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ListGroupsRequest',\n ],\n 'output' => [\n 'shape' => 'ListGroupsResponse',\n 'resultWrapper' => 'ListGroupsResult',\n ],\n ],\n 'ListGroupsForUser' => [\n 'name' => 'ListGroupsForUser',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ListGroupsForUserRequest',\n ],\n 'output' => [\n 'shape' => 'ListGroupsForUserResponse',\n 'resultWrapper' => 'ListGroupsForUserResult',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'ListInstanceProfiles' => [\n 'name' => 'ListInstanceProfiles',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ListInstanceProfilesRequest',\n ],\n 'output' => [\n 'shape' => 'ListInstanceProfilesResponse',\n 'resultWrapper' => 'ListInstanceProfilesResult',\n ],\n ],\n 'ListInstanceProfilesForRole' => [\n 'name' => 'ListInstanceProfilesForRole',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ListInstanceProfilesForRoleRequest',\n ],\n 'output' => [\n 'shape' => 'ListInstanceProfilesForRoleResponse',\n 'resultWrapper' => 'ListInstanceProfilesForRoleResult',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'ListMFADevices' => [\n 'name' => 'ListMFADevices',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ListMFADevicesRequest',\n ],\n 'output' => [\n 'shape' => 'ListMFADevicesResponse',\n 'resultWrapper' => 'ListMFADevicesResult',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'ListOpenIDConnectProviders' => [\n 'name' => 'ListOpenIDConnectProviders',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ListOpenIDConnectProvidersRequest',\n ],\n 'output' => [\n 'shape' => 'ListOpenIDConnectProvidersResponse',\n 'resultWrapper' => 'ListOpenIDConnectProvidersResult',\n ],\n ],\n 'ListRolePolicies' => [\n 'name' => 'ListRolePolicies',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ListRolePoliciesRequest',\n ],\n 'output' => [\n 'shape' => 'ListRolePoliciesResponse',\n 'resultWrapper' => 'ListRolePoliciesResult',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'ListRoles' => [\n 'name' => 'ListRoles',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ListRolesRequest',\n ],\n 'output' => [\n 'shape' => 'ListRolesResponse',\n 'resultWrapper' => 'ListRolesResult',\n ],\n ],\n 'ListSAMLProviders' => [\n 'name' => 'ListSAMLProviders',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ListSAMLProvidersRequest',\n ],\n 'output' => [\n 'shape' => 'ListSAMLProvidersResponse',\n 'resultWrapper' => 'ListSAMLProvidersResult',\n ],\n ],\n 'ListServerCertificates' => [\n 'name' => 'ListServerCertificates',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ListServerCertificatesRequest',\n ],\n 'output' => [\n 'shape' => 'ListServerCertificatesResponse',\n 'resultWrapper' => 'ListServerCertificatesResult',\n ],\n ],\n 'ListSigningCertificates' => [\n 'name' => 'ListSigningCertificates',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ListSigningCertificatesRequest',\n ],\n 'output' => [\n 'shape' => 'ListSigningCertificatesResponse',\n 'resultWrapper' => 'ListSigningCertificatesResult',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'ListUserPolicies' => [\n 'name' => 'ListUserPolicies',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ListUserPoliciesRequest',\n ],\n 'output' => [\n 'shape' => 'ListUserPoliciesResponse',\n 'resultWrapper' => 'ListUserPoliciesResult',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'ListUsers' => [\n 'name' => 'ListUsers',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ListUsersRequest',\n ],\n 'output' => [\n 'shape' => 'ListUsersResponse',\n 'resultWrapper' => 'ListUsersResult',\n ],\n ],\n 'ListVirtualMFADevices' => [\n 'name' => 'ListVirtualMFADevices',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ListVirtualMFADevicesRequest',\n ],\n 'output' => [\n 'shape' => 'ListVirtualMFADevicesResponse',\n 'resultWrapper' => 'ListVirtualMFADevicesResult',\n ],\n ],\n 'PutGroupPolicy' => [\n 'name' => 'PutGroupPolicy',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'PutGroupPolicyRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'MalformedPolicyDocumentException',\n 'error' => [\n 'code' => 'MalformedPolicyDocument',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'PutRolePolicy' => [\n 'name' => 'PutRolePolicy',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'PutRolePolicyRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'MalformedPolicyDocumentException',\n 'error' => [\n 'code' => 'MalformedPolicyDocument',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'PutUserPolicy' => [\n 'name' => 'PutUserPolicy',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'PutUserPolicyRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'MalformedPolicyDocumentException',\n 'error' => [\n 'code' => 'MalformedPolicyDocument',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'RemoveClientIDFromOpenIDConnectProvider' => [\n 'name' => 'RemoveClientIDFromOpenIDConnectProvider',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'RemoveClientIDFromOpenIDConnectProviderRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidInputException',\n 'error' => [\n 'code' => 'InvalidInput',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'RemoveRoleFromInstanceProfile' => [\n 'name' => 'RemoveRoleFromInstanceProfile',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'RemoveRoleFromInstanceProfileRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'RemoveUserFromGroup' => [\n 'name' => 'RemoveUserFromGroup',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'RemoveUserFromGroupRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'ResyncMFADevice' => [\n 'name' => 'ResyncMFADevice',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'ResyncMFADeviceRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidAuthenticationCodeException',\n 'error' => [\n 'code' => 'InvalidAuthenticationCode',\n 'httpStatusCode' => 403,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'UpdateAccessKey' => [\n 'name' => 'UpdateAccessKey',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'UpdateAccessKeyRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'UpdateAccountPasswordPolicy' => [\n 'name' => 'UpdateAccountPasswordPolicy',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'UpdateAccountPasswordPolicyRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'MalformedPolicyDocumentException',\n 'error' => [\n 'code' => 'MalformedPolicyDocument',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'UpdateAssumeRolePolicy' => [\n 'name' => 'UpdateAssumeRolePolicy',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'UpdateAssumeRolePolicyRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'MalformedPolicyDocumentException',\n 'error' => [\n 'code' => 'MalformedPolicyDocument',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'UpdateGroup' => [\n 'name' => 'UpdateGroup',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'UpdateGroupRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'EntityAlreadyExistsException',\n 'error' => [\n 'code' => 'EntityAlreadyExists',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'UpdateLoginProfile' => [\n 'name' => 'UpdateLoginProfile',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'UpdateLoginProfileRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'EntityTemporarilyUnmodifiableException',\n 'error' => [\n 'code' => 'EntityTemporarilyUnmodifiable',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'PasswordPolicyViolationException',\n 'error' => [\n 'code' => 'PasswordPolicyViolation',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'UpdateOpenIDConnectProviderThumbprint' => [\n 'name' => 'UpdateOpenIDConnectProviderThumbprint',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'UpdateOpenIDConnectProviderThumbprintRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'InvalidInputException',\n 'error' => [\n 'code' => 'InvalidInput',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'UpdateSAMLProvider' => [\n 'name' => 'UpdateSAMLProvider',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'UpdateSAMLProviderRequest',\n ],\n 'output' => [\n 'shape' => 'UpdateSAMLProviderResponse',\n 'resultWrapper' => 'UpdateSAMLProviderResult',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidInputException',\n 'error' => [\n 'code' => 'InvalidInput',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'UpdateServerCertificate' => [\n 'name' => 'UpdateServerCertificate',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'UpdateServerCertificateRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'EntityAlreadyExistsException',\n 'error' => [\n 'code' => 'EntityAlreadyExists',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'UpdateSigningCertificate' => [\n 'name' => 'UpdateSigningCertificate',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'UpdateSigningCertificateRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'UpdateUser' => [\n 'name' => 'UpdateUser',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'UpdateUserRequest',\n ],\n 'errors' => [\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'EntityAlreadyExistsException',\n 'error' => [\n 'code' => 'EntityAlreadyExists',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'EntityTemporarilyUnmodifiableException',\n 'error' => [\n 'code' => 'EntityTemporarilyUnmodifiable',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'UploadServerCertificate' => [\n 'name' => 'UploadServerCertificate',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'UploadServerCertificateRequest',\n ],\n 'output' => [\n 'shape' => 'UploadServerCertificateResponse',\n 'resultWrapper' => 'UploadServerCertificateResult',\n ],\n 'errors' => [\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'EntityAlreadyExistsException',\n 'error' => [\n 'code' => 'EntityAlreadyExists',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'MalformedCertificateException',\n 'error' => [\n 'code' => 'MalformedCertificate',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'KeyPairMismatchException',\n 'error' => [\n 'code' => 'KeyPairMismatch',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n 'UploadSigningCertificate' => [\n 'name' => 'UploadSigningCertificate',\n 'http' => [\n 'method' => 'POST',\n 'requestUri' => '/',\n ],\n 'input' => [\n 'shape' => 'UploadSigningCertificateRequest',\n ],\n 'output' => [\n 'shape' => 'UploadSigningCertificateResponse',\n 'resultWrapper' => 'UploadSigningCertificateResult',\n ],\n 'errors' => [\n [\n 'shape' => 'LimitExceededException',\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'EntityAlreadyExistsException',\n 'error' => [\n 'code' => 'EntityAlreadyExists',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'MalformedCertificateException',\n 'error' => [\n 'code' => 'MalformedCertificate',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'InvalidCertificateException',\n 'error' => [\n 'code' => 'InvalidCertificate',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'DuplicateCertificateException',\n 'error' => [\n 'code' => 'DuplicateCertificate',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n [\n 'shape' => 'NoSuchEntityException',\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n ],\n ],\n ],\n 'shapes' => [\n 'AccessKey' => [\n 'type' => 'structure',\n 'required' => [\n 'UserName',\n 'AccessKeyId',\n 'Status',\n 'SecretAccessKey',\n ],\n 'members' => [\n 'UserName' => [\n 'shape' => 'userNameType',\n ],\n 'AccessKeyId' => [\n 'shape' => 'accessKeyIdType',\n ],\n 'Status' => [\n 'shape' => 'statusType',\n ],\n 'SecretAccessKey' => [\n 'shape' => 'accessKeySecretType',\n ],\n 'CreateDate' => [\n 'shape' => 'dateType',\n ],\n ],\n ],\n 'AccessKeyMetadata' => [\n 'type' => 'structure',\n 'members' => [\n 'UserName' => [\n 'shape' => 'userNameType',\n ],\n 'AccessKeyId' => [\n 'shape' => 'accessKeyIdType',\n ],\n 'Status' => [\n 'shape' => 'statusType',\n ],\n 'CreateDate' => [\n 'shape' => 'dateType',\n ],\n ],\n ],\n 'AddClientIDToOpenIDConnectProviderRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'OpenIDConnectProviderArn',\n 'ClientID',\n ],\n 'members' => [\n 'OpenIDConnectProviderArn' => [\n 'shape' => 'arnType',\n ],\n 'ClientID' => [\n 'shape' => 'clientIDType',\n ],\n ],\n ],\n 'AddRoleToInstanceProfileRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'InstanceProfileName',\n 'RoleName',\n ],\n 'members' => [\n 'InstanceProfileName' => [\n 'shape' => 'instanceProfileNameType',\n ],\n 'RoleName' => [\n 'shape' => 'roleNameType',\n ],\n ],\n ],\n 'AddUserToGroupRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'GroupName',\n 'UserName',\n ],\n 'members' => [\n 'GroupName' => [\n 'shape' => 'groupNameType',\n ],\n 'UserName' => [\n 'shape' => 'existingUserNameType',\n ],\n ],\n ],\n 'BootstrapDatum' => [\n 'type' => 'blob',\n 'sensitive' => true,\n ],\n 'ChangePasswordRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'OldPassword',\n 'NewPassword',\n ],\n 'members' => [\n 'OldPassword' => [\n 'shape' => 'passwordType',\n ],\n 'NewPassword' => [\n 'shape' => 'passwordType',\n ],\n ],\n ],\n 'CreateAccessKeyRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'UserName' => [\n 'shape' => 'existingUserNameType',\n ],\n ],\n ],\n 'CreateAccessKeyResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'AccessKey',\n ],\n 'members' => [\n 'AccessKey' => [\n 'shape' => 'AccessKey',\n ],\n ],\n ],\n 'CreateAccountAliasRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'AccountAlias',\n ],\n 'members' => [\n 'AccountAlias' => [\n 'shape' => 'accountAliasType',\n ],\n ],\n ],\n 'CreateGroupRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'GroupName',\n ],\n 'members' => [\n 'Path' => [\n 'shape' => 'pathType',\n ],\n 'GroupName' => [\n 'shape' => 'groupNameType',\n ],\n ],\n ],\n 'CreateGroupResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'Group',\n ],\n 'members' => [\n 'Group' => [\n 'shape' => 'Group',\n ],\n ],\n ],\n 'CreateInstanceProfileRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'InstanceProfileName',\n ],\n 'members' => [\n 'InstanceProfileName' => [\n 'shape' => 'instanceProfileNameType',\n ],\n 'Path' => [\n 'shape' => 'pathType',\n ],\n ],\n ],\n 'CreateInstanceProfileResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'InstanceProfile',\n ],\n 'members' => [\n 'InstanceProfile' => [\n 'shape' => 'InstanceProfile',\n ],\n ],\n ],\n 'CreateLoginProfileRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'UserName',\n 'Password',\n ],\n 'members' => [\n 'UserName' => [\n 'shape' => 'userNameType',\n ],\n 'Password' => [\n 'shape' => 'passwordType',\n ],\n 'PasswordResetRequired' => [\n 'shape' => 'booleanType',\n ],\n ],\n ],\n 'CreateLoginProfileResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'LoginProfile',\n ],\n 'members' => [\n 'LoginProfile' => [\n 'shape' => 'LoginProfile',\n ],\n ],\n ],\n 'CreateOpenIDConnectProviderRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'Url',\n 'ThumbprintList',\n ],\n 'members' => [\n 'Url' => [\n 'shape' => 'OpenIDConnectProviderUrlType',\n ],\n 'ClientIDList' => [\n 'shape' => 'clientIDListType',\n ],\n 'ThumbprintList' => [\n 'shape' => 'thumbprintListType',\n ],\n ],\n ],\n 'CreateOpenIDConnectProviderResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'OpenIDConnectProviderArn' => [\n 'shape' => 'arnType',\n ],\n ],\n ],\n 'CreateRoleRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'RoleName',\n 'AssumeRolePolicyDocument',\n ],\n 'members' => [\n 'Path' => [\n 'shape' => 'pathType',\n ],\n 'RoleName' => [\n 'shape' => 'roleNameType',\n ],\n 'AssumeRolePolicyDocument' => [\n 'shape' => 'policyDocumentType',\n ],\n ],\n ],\n 'CreateRoleResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'Role',\n ],\n 'members' => [\n 'Role' => [\n 'shape' => 'Role',\n ],\n ],\n ],\n 'CreateSAMLProviderRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'SAMLMetadataDocument',\n 'Name',\n ],\n 'members' => [\n 'SAMLMetadataDocument' => [\n 'shape' => 'SAMLMetadataDocumentType',\n ],\n 'Name' => [\n 'shape' => 'SAMLProviderNameType',\n ],\n ],\n ],\n 'CreateSAMLProviderResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'SAMLProviderArn' => [\n 'shape' => 'arnType',\n ],\n ],\n ],\n 'CreateUserRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'UserName',\n ],\n 'members' => [\n 'Path' => [\n 'shape' => 'pathType',\n ],\n 'UserName' => [\n 'shape' => 'userNameType',\n ],\n ],\n ],\n 'CreateUserResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'User' => [\n 'shape' => 'User',\n ],\n ],\n ],\n 'CreateVirtualMFADeviceRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'VirtualMFADeviceName',\n ],\n 'members' => [\n 'Path' => [\n 'shape' => 'pathType',\n ],\n 'VirtualMFADeviceName' => [\n 'shape' => 'virtualMFADeviceName',\n ],\n ],\n ],\n 'CreateVirtualMFADeviceResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'VirtualMFADevice',\n ],\n 'members' => [\n 'VirtualMFADevice' => [\n 'shape' => 'VirtualMFADevice',\n ],\n ],\n ],\n 'CredentialReportExpiredException' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'credentialReportExpiredExceptionMessage',\n ],\n ],\n 'error' => [\n 'code' => 'ReportExpired',\n 'httpStatusCode' => 410,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'CredentialReportNotPresentException' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'credentialReportNotPresentExceptionMessage',\n ],\n ],\n 'error' => [\n 'code' => 'ReportNotPresent',\n 'httpStatusCode' => 410,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'CredentialReportNotReadyException' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'credentialReportNotReadyExceptionMessage',\n ],\n ],\n 'error' => [\n 'code' => 'ReportInProgress',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'DeactivateMFADeviceRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'UserName',\n 'SerialNumber',\n ],\n 'members' => [\n 'UserName' => [\n 'shape' => 'existingUserNameType',\n ],\n 'SerialNumber' => [\n 'shape' => 'serialNumberType',\n ],\n ],\n ],\n 'DeleteAccessKeyRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'AccessKeyId',\n ],\n 'members' => [\n 'UserName' => [\n 'shape' => 'existingUserNameType',\n ],\n 'AccessKeyId' => [\n 'shape' => 'accessKeyIdType',\n ],\n ],\n ],\n 'DeleteAccountAliasRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'AccountAlias',\n ],\n 'members' => [\n 'AccountAlias' => [\n 'shape' => 'accountAliasType',\n ],\n ],\n ],\n 'DeleteConflictException' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'deleteConflictMessage',\n ],\n ],\n 'error' => [\n 'code' => 'DeleteConflict',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'DeleteGroupPolicyRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'GroupName',\n 'PolicyName',\n ],\n 'members' => [\n 'GroupName' => [\n 'shape' => 'groupNameType',\n ],\n 'PolicyName' => [\n 'shape' => 'policyNameType',\n ],\n ],\n ],\n 'DeleteGroupRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'GroupName',\n ],\n 'members' => [\n 'GroupName' => [\n 'shape' => 'groupNameType',\n ],\n ],\n ],\n 'DeleteInstanceProfileRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'InstanceProfileName',\n ],\n 'members' => [\n 'InstanceProfileName' => [\n 'shape' => 'instanceProfileNameType',\n ],\n ],\n ],\n 'DeleteLoginProfileRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'UserName',\n ],\n 'members' => [\n 'UserName' => [\n 'shape' => 'userNameType',\n ],\n ],\n ],\n 'DeleteOpenIDConnectProviderRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'OpenIDConnectProviderArn',\n ],\n 'members' => [\n 'OpenIDConnectProviderArn' => [\n 'shape' => 'arnType',\n ],\n ],\n ],\n 'DeleteRolePolicyRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'RoleName',\n 'PolicyName',\n ],\n 'members' => [\n 'RoleName' => [\n 'shape' => 'roleNameType',\n ],\n 'PolicyName' => [\n 'shape' => 'policyNameType',\n ],\n ],\n ],\n 'DeleteRoleRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'RoleName',\n ],\n 'members' => [\n 'RoleName' => [\n 'shape' => 'roleNameType',\n ],\n ],\n ],\n 'DeleteSAMLProviderRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'SAMLProviderArn',\n ],\n 'members' => [\n 'SAMLProviderArn' => [\n 'shape' => 'arnType',\n ],\n ],\n ],\n 'DeleteServerCertificateRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'ServerCertificateName',\n ],\n 'members' => [\n 'ServerCertificateName' => [\n 'shape' => 'serverCertificateNameType',\n ],\n ],\n ],\n 'DeleteSigningCertificateRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'CertificateId',\n ],\n 'members' => [\n 'UserName' => [\n 'shape' => 'existingUserNameType',\n ],\n 'CertificateId' => [\n 'shape' => 'certificateIdType',\n ],\n ],\n ],\n 'DeleteUserPolicyRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'UserName',\n 'PolicyName',\n ],\n 'members' => [\n 'UserName' => [\n 'shape' => 'existingUserNameType',\n ],\n 'PolicyName' => [\n 'shape' => 'policyNameType',\n ],\n ],\n ],\n 'DeleteUserRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'UserName',\n ],\n 'members' => [\n 'UserName' => [\n 'shape' => 'existingUserNameType',\n ],\n ],\n ],\n 'DeleteVirtualMFADeviceRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'SerialNumber',\n ],\n 'members' => [\n 'SerialNumber' => [\n 'shape' => 'serialNumberType',\n ],\n ],\n ],\n 'DuplicateCertificateException' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'duplicateCertificateMessage',\n ],\n ],\n 'error' => [\n 'code' => 'DuplicateCertificate',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'EnableMFADeviceRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'UserName',\n 'SerialNumber',\n 'AuthenticationCode1',\n 'AuthenticationCode2',\n ],\n 'members' => [\n 'UserName' => [\n 'shape' => 'existingUserNameType',\n ],\n 'SerialNumber' => [\n 'shape' => 'serialNumberType',\n ],\n 'AuthenticationCode1' => [\n 'shape' => 'authenticationCodeType',\n ],\n 'AuthenticationCode2' => [\n 'shape' => 'authenticationCodeType',\n ],\n ],\n ],\n 'EntityAlreadyExistsException' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'entityAlreadyExistsMessage',\n ],\n ],\n 'error' => [\n 'code' => 'EntityAlreadyExists',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'EntityTemporarilyUnmodifiableException' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'entityTemporarilyUnmodifiableMessage',\n ],\n ],\n 'error' => [\n 'code' => 'EntityTemporarilyUnmodifiable',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'EntityType' => [\n 'type' => 'string',\n 'enum' => [\n 'User',\n 'Role',\n 'Group',\n ],\n ],\n 'GenerateCredentialReportResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'State' => [\n 'shape' => 'ReportStateType',\n ],\n 'Description' => [\n 'shape' => 'ReportStateDescriptionType',\n ],\n ],\n ],\n 'GetAccountAuthorizationDetailsRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'Filter' => [\n 'shape' => 'entityListType',\n ],\n 'MaxItems' => [\n 'shape' => 'maxItemsType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n ],\n ],\n 'GetAccountAuthorizationDetailsResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'UserDetailList' => [\n 'shape' => 'userDetailListType',\n ],\n 'GroupDetailList' => [\n 'shape' => 'groupDetailListType',\n ],\n 'RoleDetailList' => [\n 'shape' => 'roleDetailListType',\n ],\n 'IsTruncated' => [\n 'shape' => 'booleanType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n ],\n ],\n 'GetAccountPasswordPolicyResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'PasswordPolicy',\n ],\n 'members' => [\n 'PasswordPolicy' => [\n 'shape' => 'PasswordPolicy',\n ],\n ],\n ],\n 'GetAccountSummaryResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'SummaryMap' => [\n 'shape' => 'summaryMapType',\n ],\n ],\n ],\n 'GetCredentialReportResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'Content' => [\n 'shape' => 'ReportContentType',\n ],\n 'ReportFormat' => [\n 'shape' => 'ReportFormatType',\n ],\n 'GeneratedTime' => [\n 'shape' => 'dateType',\n ],\n ],\n ],\n 'GetGroupPolicyRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'GroupName',\n 'PolicyName',\n ],\n 'members' => [\n 'GroupName' => [\n 'shape' => 'groupNameType',\n ],\n 'PolicyName' => [\n 'shape' => 'policyNameType',\n ],\n ],\n ],\n 'GetGroupPolicyResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'GroupName',\n 'PolicyName',\n 'PolicyDocument',\n ],\n 'members' => [\n 'GroupName' => [\n 'shape' => 'groupNameType',\n ],\n 'PolicyName' => [\n 'shape' => 'policyNameType',\n ],\n 'PolicyDocument' => [\n 'shape' => 'policyDocumentType',\n ],\n ],\n ],\n 'GetGroupRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'GroupName',\n ],\n 'members' => [\n 'GroupName' => [\n 'shape' => 'groupNameType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n 'MaxItems' => [\n 'shape' => 'maxItemsType',\n ],\n ],\n ],\n 'GetGroupResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'Group',\n 'Users',\n ],\n 'members' => [\n 'Group' => [\n 'shape' => 'Group',\n ],\n 'Users' => [\n 'shape' => 'userListType',\n ],\n 'IsTruncated' => [\n 'shape' => 'booleanType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n ],\n ],\n 'GetInstanceProfileRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'InstanceProfileName',\n ],\n 'members' => [\n 'InstanceProfileName' => [\n 'shape' => 'instanceProfileNameType',\n ],\n ],\n ],\n 'GetInstanceProfileResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'InstanceProfile',\n ],\n 'members' => [\n 'InstanceProfile' => [\n 'shape' => 'InstanceProfile',\n ],\n ],\n ],\n 'GetLoginProfileRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'UserName',\n ],\n 'members' => [\n 'UserName' => [\n 'shape' => 'userNameType',\n ],\n ],\n ],\n 'GetLoginProfileResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'LoginProfile',\n ],\n 'members' => [\n 'LoginProfile' => [\n 'shape' => 'LoginProfile',\n ],\n ],\n ],\n 'GetOpenIDConnectProviderRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'OpenIDConnectProviderArn',\n ],\n 'members' => [\n 'OpenIDConnectProviderArn' => [\n 'shape' => 'arnType',\n ],\n ],\n ],\n 'GetOpenIDConnectProviderResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'Url' => [\n 'shape' => 'OpenIDConnectProviderUrlType',\n ],\n 'ClientIDList' => [\n 'shape' => 'clientIDListType',\n ],\n 'ThumbprintList' => [\n 'shape' => 'thumbprintListType',\n ],\n 'CreateDate' => [\n 'shape' => 'dateType',\n ],\n ],\n ],\n 'GetRolePolicyRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'RoleName',\n 'PolicyName',\n ],\n 'members' => [\n 'RoleName' => [\n 'shape' => 'roleNameType',\n ],\n 'PolicyName' => [\n 'shape' => 'policyNameType',\n ],\n ],\n ],\n 'GetRolePolicyResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'RoleName',\n 'PolicyName',\n 'PolicyDocument',\n ],\n 'members' => [\n 'RoleName' => [\n 'shape' => 'roleNameType',\n ],\n 'PolicyName' => [\n 'shape' => 'policyNameType',\n ],\n 'PolicyDocument' => [\n 'shape' => 'policyDocumentType',\n ],\n ],\n ],\n 'GetRoleRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'RoleName',\n ],\n 'members' => [\n 'RoleName' => [\n 'shape' => 'roleNameType',\n ],\n ],\n ],\n 'GetRoleResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'Role',\n ],\n 'members' => [\n 'Role' => [\n 'shape' => 'Role',\n ],\n ],\n ],\n 'GetSAMLProviderRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'SAMLProviderArn',\n ],\n 'members' => [\n 'SAMLProviderArn' => [\n 'shape' => 'arnType',\n ],\n ],\n ],\n 'GetSAMLProviderResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'SAMLMetadataDocument' => [\n 'shape' => 'SAMLMetadataDocumentType',\n ],\n 'CreateDate' => [\n 'shape' => 'dateType',\n ],\n 'ValidUntil' => [\n 'shape' => 'dateType',\n ],\n ],\n ],\n 'GetServerCertificateRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'ServerCertificateName',\n ],\n 'members' => [\n 'ServerCertificateName' => [\n 'shape' => 'serverCertificateNameType',\n ],\n ],\n ],\n 'GetServerCertificateResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'ServerCertificate',\n ],\n 'members' => [\n 'ServerCertificate' => [\n 'shape' => 'ServerCertificate',\n ],\n ],\n ],\n 'GetUserPolicyRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'UserName',\n 'PolicyName',\n ],\n 'members' => [\n 'UserName' => [\n 'shape' => 'existingUserNameType',\n ],\n 'PolicyName' => [\n 'shape' => 'policyNameType',\n ],\n ],\n ],\n 'GetUserPolicyResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'UserName',\n 'PolicyName',\n 'PolicyDocument',\n ],\n 'members' => [\n 'UserName' => [\n 'shape' => 'existingUserNameType',\n ],\n 'PolicyName' => [\n 'shape' => 'policyNameType',\n ],\n 'PolicyDocument' => [\n 'shape' => 'policyDocumentType',\n ],\n ],\n ],\n 'GetUserRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'UserName' => [\n 'shape' => 'existingUserNameType',\n ],\n ],\n ],\n 'GetUserResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'User',\n ],\n 'members' => [\n 'User' => [\n 'shape' => 'User',\n ],\n ],\n ],\n 'Group' => [\n 'type' => 'structure',\n 'required' => [\n 'Path',\n 'GroupName',\n 'GroupId',\n 'Arn',\n 'CreateDate',\n ],\n 'members' => [\n 'Path' => [\n 'shape' => 'pathType',\n ],\n 'GroupName' => [\n 'shape' => 'groupNameType',\n ],\n 'GroupId' => [\n 'shape' => 'idType',\n ],\n 'Arn' => [\n 'shape' => 'arnType',\n ],\n 'CreateDate' => [\n 'shape' => 'dateType',\n ],\n ],\n ],\n 'GroupDetail' => [\n 'type' => 'structure',\n 'members' => [\n 'Path' => [\n 'shape' => 'pathType',\n ],\n 'GroupName' => [\n 'shape' => 'groupNameType',\n ],\n 'GroupId' => [\n 'shape' => 'idType',\n ],\n 'Arn' => [\n 'shape' => 'arnType',\n ],\n 'CreateDate' => [\n 'shape' => 'dateType',\n ],\n 'GroupPolicyList' => [\n 'shape' => 'policyDetailListType',\n ],\n ],\n ],\n 'InstanceProfile' => [\n 'type' => 'structure',\n 'required' => [\n 'Path',\n 'InstanceProfileName',\n 'InstanceProfileId',\n 'Arn',\n 'CreateDate',\n 'Roles',\n ],\n 'members' => [\n 'Path' => [\n 'shape' => 'pathType',\n ],\n 'InstanceProfileName' => [\n 'shape' => 'instanceProfileNameType',\n ],\n 'InstanceProfileId' => [\n 'shape' => 'idType',\n ],\n 'Arn' => [\n 'shape' => 'arnType',\n ],\n 'CreateDate' => [\n 'shape' => 'dateType',\n ],\n 'Roles' => [\n 'shape' => 'roleListType',\n ],\n ],\n ],\n 'InvalidAuthenticationCodeException' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'invalidAuthenticationCodeMessage',\n ],\n ],\n 'error' => [\n 'code' => 'InvalidAuthenticationCode',\n 'httpStatusCode' => 403,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'InvalidCertificateException' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'invalidCertificateMessage',\n ],\n ],\n 'error' => [\n 'code' => 'InvalidCertificate',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'InvalidInputException' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'invalidInputMessage',\n ],\n ],\n 'error' => [\n 'code' => 'InvalidInput',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'InvalidUserTypeException' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'invalidUserTypeMessage',\n ],\n ],\n 'error' => [\n 'code' => 'InvalidUserType',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'KeyPairMismatchException' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'keyPairMismatchMessage',\n ],\n ],\n 'error' => [\n 'code' => 'KeyPairMismatch',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'LimitExceededException' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'limitExceededMessage',\n ],\n ],\n 'error' => [\n 'code' => 'LimitExceeded',\n 'httpStatusCode' => 409,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'ListAccessKeysRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'UserName' => [\n 'shape' => 'existingUserNameType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n 'MaxItems' => [\n 'shape' => 'maxItemsType',\n ],\n ],\n ],\n 'ListAccessKeysResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'AccessKeyMetadata',\n ],\n 'members' => [\n 'AccessKeyMetadata' => [\n 'shape' => 'accessKeyMetadataListType',\n ],\n 'IsTruncated' => [\n 'shape' => 'booleanType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n ],\n ],\n 'ListAccountAliasesRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n 'MaxItems' => [\n 'shape' => 'maxItemsType',\n ],\n ],\n ],\n 'ListAccountAliasesResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'AccountAliases',\n ],\n 'members' => [\n 'AccountAliases' => [\n 'shape' => 'accountAliasListType',\n ],\n 'IsTruncated' => [\n 'shape' => 'booleanType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n ],\n ],\n 'ListGroupPoliciesRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'GroupName',\n ],\n 'members' => [\n 'GroupName' => [\n 'shape' => 'groupNameType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n 'MaxItems' => [\n 'shape' => 'maxItemsType',\n ],\n ],\n ],\n 'ListGroupPoliciesResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'PolicyNames',\n ],\n 'members' => [\n 'PolicyNames' => [\n 'shape' => 'policyNameListType',\n ],\n 'IsTruncated' => [\n 'shape' => 'booleanType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n ],\n ],\n 'ListGroupsForUserRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'UserName',\n ],\n 'members' => [\n 'UserName' => [\n 'shape' => 'existingUserNameType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n 'MaxItems' => [\n 'shape' => 'maxItemsType',\n ],\n ],\n ],\n 'ListGroupsForUserResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'Groups',\n ],\n 'members' => [\n 'Groups' => [\n 'shape' => 'groupListType',\n ],\n 'IsTruncated' => [\n 'shape' => 'booleanType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n ],\n ],\n 'ListGroupsRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'PathPrefix' => [\n 'shape' => 'pathPrefixType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n 'MaxItems' => [\n 'shape' => 'maxItemsType',\n ],\n ],\n ],\n 'ListGroupsResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'Groups',\n ],\n 'members' => [\n 'Groups' => [\n 'shape' => 'groupListType',\n ],\n 'IsTruncated' => [\n 'shape' => 'booleanType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n ],\n ],\n 'ListInstanceProfilesForRoleRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'RoleName',\n ],\n 'members' => [\n 'RoleName' => [\n 'shape' => 'roleNameType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n 'MaxItems' => [\n 'shape' => 'maxItemsType',\n ],\n ],\n ],\n 'ListInstanceProfilesForRoleResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'InstanceProfiles',\n ],\n 'members' => [\n 'InstanceProfiles' => [\n 'shape' => 'instanceProfileListType',\n ],\n 'IsTruncated' => [\n 'shape' => 'booleanType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n ],\n ],\n 'ListInstanceProfilesRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'PathPrefix' => [\n 'shape' => 'pathPrefixType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n 'MaxItems' => [\n 'shape' => 'maxItemsType',\n ],\n ],\n ],\n 'ListInstanceProfilesResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'InstanceProfiles',\n ],\n 'members' => [\n 'InstanceProfiles' => [\n 'shape' => 'instanceProfileListType',\n ],\n 'IsTruncated' => [\n 'shape' => 'booleanType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n ],\n ],\n 'ListMFADevicesRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'UserName' => [\n 'shape' => 'existingUserNameType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n 'MaxItems' => [\n 'shape' => 'maxItemsType',\n ],\n ],\n ],\n 'ListMFADevicesResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'MFADevices',\n ],\n 'members' => [\n 'MFADevices' => [\n 'shape' => 'mfaDeviceListType',\n ],\n 'IsTruncated' => [\n 'shape' => 'booleanType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n ],\n ],\n 'ListOpenIDConnectProvidersRequest' => [\n 'type' => 'structure',\n 'members' => [],\n ],\n 'ListOpenIDConnectProvidersResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'OpenIDConnectProviderList' => [\n 'shape' => 'OpenIDConnectProviderListType',\n ],\n ],\n ],\n 'ListRolePoliciesRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'RoleName',\n ],\n 'members' => [\n 'RoleName' => [\n 'shape' => 'roleNameType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n 'MaxItems' => [\n 'shape' => 'maxItemsType',\n ],\n ],\n ],\n 'ListRolePoliciesResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'PolicyNames',\n ],\n 'members' => [\n 'PolicyNames' => [\n 'shape' => 'policyNameListType',\n ],\n 'IsTruncated' => [\n 'shape' => 'booleanType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n ],\n ],\n 'ListRolesRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'PathPrefix' => [\n 'shape' => 'pathPrefixType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n 'MaxItems' => [\n 'shape' => 'maxItemsType',\n ],\n ],\n ],\n 'ListRolesResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'Roles',\n ],\n 'members' => [\n 'Roles' => [\n 'shape' => 'roleListType',\n ],\n 'IsTruncated' => [\n 'shape' => 'booleanType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n ],\n ],\n 'ListSAMLProvidersRequest' => [\n 'type' => 'structure',\n 'members' => [],\n ],\n 'ListSAMLProvidersResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'SAMLProviderList' => [\n 'shape' => 'SAMLProviderListType',\n ],\n ],\n ],\n 'ListServerCertificatesRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'PathPrefix' => [\n 'shape' => 'pathPrefixType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n 'MaxItems' => [\n 'shape' => 'maxItemsType',\n ],\n ],\n ],\n 'ListServerCertificatesResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'ServerCertificateMetadataList',\n ],\n 'members' => [\n 'ServerCertificateMetadataList' => [\n 'shape' => 'serverCertificateMetadataListType',\n ],\n 'IsTruncated' => [\n 'shape' => 'booleanType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n ],\n ],\n 'ListSigningCertificatesRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'UserName' => [\n 'shape' => 'existingUserNameType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n 'MaxItems' => [\n 'shape' => 'maxItemsType',\n ],\n ],\n ],\n 'ListSigningCertificatesResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'Certificates',\n ],\n 'members' => [\n 'Certificates' => [\n 'shape' => 'certificateListType',\n ],\n 'IsTruncated' => [\n 'shape' => 'booleanType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n ],\n ],\n 'ListUserPoliciesRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'UserName',\n ],\n 'members' => [\n 'UserName' => [\n 'shape' => 'existingUserNameType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n 'MaxItems' => [\n 'shape' => 'maxItemsType',\n ],\n ],\n ],\n 'ListUserPoliciesResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'PolicyNames',\n ],\n 'members' => [\n 'PolicyNames' => [\n 'shape' => 'policyNameListType',\n ],\n 'IsTruncated' => [\n 'shape' => 'booleanType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n ],\n ],\n 'ListUsersRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'PathPrefix' => [\n 'shape' => 'pathPrefixType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n 'MaxItems' => [\n 'shape' => 'maxItemsType',\n ],\n ],\n ],\n 'ListUsersResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'Users',\n ],\n 'members' => [\n 'Users' => [\n 'shape' => 'userListType',\n ],\n 'IsTruncated' => [\n 'shape' => 'booleanType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n ],\n ],\n 'ListVirtualMFADevicesRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'AssignmentStatus' => [\n 'shape' => 'assignmentStatusType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n 'MaxItems' => [\n 'shape' => 'maxItemsType',\n ],\n ],\n ],\n 'ListVirtualMFADevicesResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'VirtualMFADevices',\n ],\n 'members' => [\n 'VirtualMFADevices' => [\n 'shape' => 'virtualMFADeviceListType',\n ],\n 'IsTruncated' => [\n 'shape' => 'booleanType',\n ],\n 'Marker' => [\n 'shape' => 'markerType',\n ],\n ],\n ],\n 'LoginProfile' => [\n 'type' => 'structure',\n 'required' => [\n 'UserName',\n 'CreateDate',\n ],\n 'members' => [\n 'UserName' => [\n 'shape' => 'userNameType',\n ],\n 'CreateDate' => [\n 'shape' => 'dateType',\n ],\n 'PasswordResetRequired' => [\n 'shape' => 'booleanType',\n ],\n ],\n ],\n 'MFADevice' => [\n 'type' => 'structure',\n 'required' => [\n 'UserName',\n 'SerialNumber',\n 'EnableDate',\n ],\n 'members' => [\n 'UserName' => [\n 'shape' => 'userNameType',\n ],\n 'SerialNumber' => [\n 'shape' => 'serialNumberType',\n ],\n 'EnableDate' => [\n 'shape' => 'dateType',\n ],\n ],\n ],\n 'MalformedCertificateException' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'malformedCertificateMessage',\n ],\n ],\n 'error' => [\n 'code' => 'MalformedCertificate',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'MalformedPolicyDocumentException' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'malformedPolicyDocumentMessage',\n ],\n ],\n 'error' => [\n 'code' => 'MalformedPolicyDocument',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'NoSuchEntityException' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'noSuchEntityMessage',\n ],\n ],\n 'error' => [\n 'code' => 'NoSuchEntity',\n 'httpStatusCode' => 404,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'OpenIDConnectProviderListEntry' => [\n 'type' => 'structure',\n 'members' => [\n 'Arn' => [\n 'shape' => 'arnType',\n ],\n ],\n ],\n 'OpenIDConnectProviderListType' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'OpenIDConnectProviderListEntry',\n ],\n ],\n 'OpenIDConnectProviderUrlType' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 255,\n ],\n 'PasswordPolicy' => [\n 'type' => 'structure',\n 'members' => [\n 'MinimumPasswordLength' => [\n 'shape' => 'minimumPasswordLengthType',\n ],\n 'RequireSymbols' => [\n 'shape' => 'booleanType',\n ],\n 'RequireNumbers' => [\n 'shape' => 'booleanType',\n ],\n 'RequireUppercaseCharacters' => [\n 'shape' => 'booleanType',\n ],\n 'RequireLowercaseCharacters' => [\n 'shape' => 'booleanType',\n ],\n 'AllowUsersToChangePassword' => [\n 'shape' => 'booleanType',\n ],\n 'ExpirePasswords' => [\n 'shape' => 'booleanType',\n ],\n 'MaxPasswordAge' => [\n 'shape' => 'maxPasswordAgeType',\n ],\n 'PasswordReusePrevention' => [\n 'shape' => 'passwordReusePreventionType',\n ],\n 'HardExpiry' => [\n 'shape' => 'booleanObjectType',\n ],\n ],\n ],\n 'PasswordPolicyViolationException' => [\n 'type' => 'structure',\n 'members' => [\n 'message' => [\n 'shape' => 'passwordPolicyViolationMessage',\n ],\n ],\n 'error' => [\n 'code' => 'PasswordPolicyViolation',\n 'httpStatusCode' => 400,\n 'senderFault' => true,\n ],\n 'exception' => true,\n ],\n 'PolicyDetail' => [\n 'type' => 'structure',\n 'members' => [\n 'PolicyName' => [\n 'shape' => 'policyNameType',\n ],\n 'PolicyDocument' => [\n 'shape' => 'policyDocumentType',\n ],\n ],\n ],\n 'PutGroupPolicyRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'GroupName',\n 'PolicyName',\n 'PolicyDocument',\n ],\n 'members' => [\n 'GroupName' => [\n 'shape' => 'groupNameType',\n ],\n 'PolicyName' => [\n 'shape' => 'policyNameType',\n ],\n 'PolicyDocument' => [\n 'shape' => 'policyDocumentType',\n ],\n ],\n ],\n 'PutRolePolicyRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'RoleName',\n 'PolicyName',\n 'PolicyDocument',\n ],\n 'members' => [\n 'RoleName' => [\n 'shape' => 'roleNameType',\n ],\n 'PolicyName' => [\n 'shape' => 'policyNameType',\n ],\n 'PolicyDocument' => [\n 'shape' => 'policyDocumentType',\n ],\n ],\n ],\n 'PutUserPolicyRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'UserName',\n 'PolicyName',\n 'PolicyDocument',\n ],\n 'members' => [\n 'UserName' => [\n 'shape' => 'existingUserNameType',\n ],\n 'PolicyName' => [\n 'shape' => 'policyNameType',\n ],\n 'PolicyDocument' => [\n 'shape' => 'policyDocumentType',\n ],\n ],\n ],\n 'RemoveClientIDFromOpenIDConnectProviderRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'OpenIDConnectProviderArn',\n 'ClientID',\n ],\n 'members' => [\n 'OpenIDConnectProviderArn' => [\n 'shape' => 'arnType',\n ],\n 'ClientID' => [\n 'shape' => 'clientIDType',\n ],\n ],\n ],\n 'RemoveRoleFromInstanceProfileRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'InstanceProfileName',\n 'RoleName',\n ],\n 'members' => [\n 'InstanceProfileName' => [\n 'shape' => 'instanceProfileNameType',\n ],\n 'RoleName' => [\n 'shape' => 'roleNameType',\n ],\n ],\n ],\n 'RemoveUserFromGroupRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'GroupName',\n 'UserName',\n ],\n 'members' => [\n 'GroupName' => [\n 'shape' => 'groupNameType',\n ],\n 'UserName' => [\n 'shape' => 'existingUserNameType',\n ],\n ],\n ],\n 'ReportContentType' => [\n 'type' => 'blob',\n ],\n 'ReportFormatType' => [\n 'type' => 'string',\n 'enum' => [\n 'text/csv',\n ],\n ],\n 'ReportStateDescriptionType' => [\n 'type' => 'string',\n ],\n 'ReportStateType' => [\n 'type' => 'string',\n 'enum' => [\n 'STARTED',\n 'INPROGRESS',\n 'COMPLETE',\n ],\n ],\n 'ResyncMFADeviceRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'UserName',\n 'SerialNumber',\n 'AuthenticationCode1',\n 'AuthenticationCode2',\n ],\n 'members' => [\n 'UserName' => [\n 'shape' => 'existingUserNameType',\n ],\n 'SerialNumber' => [\n 'shape' => 'serialNumberType',\n ],\n 'AuthenticationCode1' => [\n 'shape' => 'authenticationCodeType',\n ],\n 'AuthenticationCode2' => [\n 'shape' => 'authenticationCodeType',\n ],\n ],\n ],\n 'Role' => [\n 'type' => 'structure',\n 'required' => [\n 'Path',\n 'RoleName',\n 'RoleId',\n 'Arn',\n 'CreateDate',\n ],\n 'members' => [\n 'Path' => [\n 'shape' => 'pathType',\n ],\n 'RoleName' => [\n 'shape' => 'roleNameType',\n ],\n 'RoleId' => [\n 'shape' => 'idType',\n ],\n 'Arn' => [\n 'shape' => 'arnType',\n ],\n 'CreateDate' => [\n 'shape' => 'dateType',\n ],\n 'AssumeRolePolicyDocument' => [\n 'shape' => 'policyDocumentType',\n ],\n ],\n ],\n 'RoleDetail' => [\n 'type' => 'structure',\n 'members' => [\n 'Path' => [\n 'shape' => 'pathType',\n ],\n 'RoleName' => [\n 'shape' => 'roleNameType',\n ],\n 'RoleId' => [\n 'shape' => 'idType',\n ],\n 'Arn' => [\n 'shape' => 'arnType',\n ],\n 'CreateDate' => [\n 'shape' => 'dateType',\n ],\n 'AssumeRolePolicyDocument' => [\n 'shape' => 'policyDocumentType',\n ],\n 'InstanceProfileList' => [\n 'shape' => 'instanceProfileListType',\n ],\n 'RolePolicyList' => [\n 'shape' => 'policyDetailListType',\n ],\n ],\n ],\n 'SAMLMetadataDocumentType' => [\n 'type' => 'string',\n 'min' => 1000,\n 'max' => 10000000,\n ],\n 'SAMLProviderListEntry' => [\n 'type' => 'structure',\n 'members' => [\n 'Arn' => [\n 'shape' => 'arnType',\n ],\n 'ValidUntil' => [\n 'shape' => 'dateType',\n ],\n 'CreateDate' => [\n 'shape' => 'dateType',\n ],\n ],\n ],\n 'SAMLProviderListType' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'SAMLProviderListEntry',\n ],\n ],\n 'SAMLProviderNameType' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 128,\n 'pattern' => '[\\\\w._-]*',\n ],\n 'ServerCertificate' => [\n 'type' => 'structure',\n 'required' => [\n 'ServerCertificateMetadata',\n 'CertificateBody',\n ],\n 'members' => [\n 'ServerCertificateMetadata' => [\n 'shape' => 'ServerCertificateMetadata',\n ],\n 'CertificateBody' => [\n 'shape' => 'certificateBodyType',\n ],\n 'CertificateChain' => [\n 'shape' => 'certificateChainType',\n ],\n ],\n ],\n 'ServerCertificateMetadata' => [\n 'type' => 'structure',\n 'required' => [\n 'Path',\n 'ServerCertificateName',\n 'ServerCertificateId',\n 'Arn',\n ],\n 'members' => [\n 'Path' => [\n 'shape' => 'pathType',\n ],\n 'ServerCertificateName' => [\n 'shape' => 'serverCertificateNameType',\n ],\n 'ServerCertificateId' => [\n 'shape' => 'idType',\n ],\n 'Arn' => [\n 'shape' => 'arnType',\n ],\n 'UploadDate' => [\n 'shape' => 'dateType',\n ],\n 'Expiration' => [\n 'shape' => 'dateType',\n ],\n ],\n ],\n 'SigningCertificate' => [\n 'type' => 'structure',\n 'required' => [\n 'UserName',\n 'CertificateId',\n 'CertificateBody',\n 'Status',\n ],\n 'members' => [\n 'UserName' => [\n 'shape' => 'userNameType',\n ],\n 'CertificateId' => [\n 'shape' => 'certificateIdType',\n ],\n 'CertificateBody' => [\n 'shape' => 'certificateBodyType',\n ],\n 'Status' => [\n 'shape' => 'statusType',\n ],\n 'UploadDate' => [\n 'shape' => 'dateType',\n ],\n ],\n ],\n 'UpdateAccessKeyRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'AccessKeyId',\n 'Status',\n ],\n 'members' => [\n 'UserName' => [\n 'shape' => 'existingUserNameType',\n ],\n 'AccessKeyId' => [\n 'shape' => 'accessKeyIdType',\n ],\n 'Status' => [\n 'shape' => 'statusType',\n ],\n ],\n ],\n 'UpdateAccountPasswordPolicyRequest' => [\n 'type' => 'structure',\n 'members' => [\n 'MinimumPasswordLength' => [\n 'shape' => 'minimumPasswordLengthType',\n ],\n 'RequireSymbols' => [\n 'shape' => 'booleanType',\n ],\n 'RequireNumbers' => [\n 'shape' => 'booleanType',\n ],\n 'RequireUppercaseCharacters' => [\n 'shape' => 'booleanType',\n ],\n 'RequireLowercaseCharacters' => [\n 'shape' => 'booleanType',\n ],\n 'AllowUsersToChangePassword' => [\n 'shape' => 'booleanType',\n ],\n 'MaxPasswordAge' => [\n 'shape' => 'maxPasswordAgeType',\n ],\n 'PasswordReusePrevention' => [\n 'shape' => 'passwordReusePreventionType',\n ],\n 'HardExpiry' => [\n 'shape' => 'booleanObjectType',\n ],\n ],\n ],\n 'UpdateAssumeRolePolicyRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'RoleName',\n 'PolicyDocument',\n ],\n 'members' => [\n 'RoleName' => [\n 'shape' => 'roleNameType',\n ],\n 'PolicyDocument' => [\n 'shape' => 'policyDocumentType',\n ],\n ],\n ],\n 'UpdateGroupRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'GroupName',\n ],\n 'members' => [\n 'GroupName' => [\n 'shape' => 'groupNameType',\n ],\n 'NewPath' => [\n 'shape' => 'pathType',\n ],\n 'NewGroupName' => [\n 'shape' => 'groupNameType',\n ],\n ],\n ],\n 'UpdateLoginProfileRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'UserName',\n ],\n 'members' => [\n 'UserName' => [\n 'shape' => 'userNameType',\n ],\n 'Password' => [\n 'shape' => 'passwordType',\n ],\n 'PasswordResetRequired' => [\n 'shape' => 'booleanObjectType',\n ],\n ],\n ],\n 'UpdateOpenIDConnectProviderThumbprintRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'OpenIDConnectProviderArn',\n 'ThumbprintList',\n ],\n 'members' => [\n 'OpenIDConnectProviderArn' => [\n 'shape' => 'arnType',\n ],\n 'ThumbprintList' => [\n 'shape' => 'thumbprintListType',\n ],\n ],\n ],\n 'UpdateSAMLProviderRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'SAMLMetadataDocument',\n 'SAMLProviderArn',\n ],\n 'members' => [\n 'SAMLMetadataDocument' => [\n 'shape' => 'SAMLMetadataDocumentType',\n ],\n 'SAMLProviderArn' => [\n 'shape' => 'arnType',\n ],\n ],\n ],\n 'UpdateSAMLProviderResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'SAMLProviderArn' => [\n 'shape' => 'arnType',\n ],\n ],\n ],\n 'UpdateServerCertificateRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'ServerCertificateName',\n ],\n 'members' => [\n 'ServerCertificateName' => [\n 'shape' => 'serverCertificateNameType',\n ],\n 'NewPath' => [\n 'shape' => 'pathType',\n ],\n 'NewServerCertificateName' => [\n 'shape' => 'serverCertificateNameType',\n ],\n ],\n ],\n 'UpdateSigningCertificateRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'CertificateId',\n 'Status',\n ],\n 'members' => [\n 'UserName' => [\n 'shape' => 'existingUserNameType',\n ],\n 'CertificateId' => [\n 'shape' => 'certificateIdType',\n ],\n 'Status' => [\n 'shape' => 'statusType',\n ],\n ],\n ],\n 'UpdateUserRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'UserName',\n ],\n 'members' => [\n 'UserName' => [\n 'shape' => 'existingUserNameType',\n ],\n 'NewPath' => [\n 'shape' => 'pathType',\n ],\n 'NewUserName' => [\n 'shape' => 'userNameType',\n ],\n ],\n ],\n 'UploadServerCertificateRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'ServerCertificateName',\n 'CertificateBody',\n 'PrivateKey',\n ],\n 'members' => [\n 'Path' => [\n 'shape' => 'pathType',\n ],\n 'ServerCertificateName' => [\n 'shape' => 'serverCertificateNameType',\n ],\n 'CertificateBody' => [\n 'shape' => 'certificateBodyType',\n ],\n 'PrivateKey' => [\n 'shape' => 'privateKeyType',\n ],\n 'CertificateChain' => [\n 'shape' => 'certificateChainType',\n ],\n ],\n ],\n 'UploadServerCertificateResponse' => [\n 'type' => 'structure',\n 'members' => [\n 'ServerCertificateMetadata' => [\n 'shape' => 'ServerCertificateMetadata',\n ],\n ],\n ],\n 'UploadSigningCertificateRequest' => [\n 'type' => 'structure',\n 'required' => [\n 'CertificateBody',\n ],\n 'members' => [\n 'UserName' => [\n 'shape' => 'existingUserNameType',\n ],\n 'CertificateBody' => [\n 'shape' => 'certificateBodyType',\n ],\n ],\n ],\n 'UploadSigningCertificateResponse' => [\n 'type' => 'structure',\n 'required' => [\n 'Certificate',\n ],\n 'members' => [\n 'Certificate' => [\n 'shape' => 'SigningCertificate',\n ],\n ],\n ],\n 'User' => [\n 'type' => 'structure',\n 'required' => [\n 'Path',\n 'UserName',\n 'UserId',\n 'Arn',\n 'CreateDate',\n ],\n 'members' => [\n 'Path' => [\n 'shape' => 'pathType',\n ],\n 'UserName' => [\n 'shape' => 'userNameType',\n ],\n 'UserId' => [\n 'shape' => 'idType',\n ],\n 'Arn' => [\n 'shape' => 'arnType',\n ],\n 'CreateDate' => [\n 'shape' => 'dateType',\n ],\n 'PasswordLastUsed' => [\n 'shape' => 'dateType',\n ],\n ],\n ],\n 'UserDetail' => [\n 'type' => 'structure',\n 'members' => [\n 'Path' => [\n 'shape' => 'pathType',\n ],\n 'UserName' => [\n 'shape' => 'userNameType',\n ],\n 'UserId' => [\n 'shape' => 'idType',\n ],\n 'Arn' => [\n 'shape' => 'arnType',\n ],\n 'CreateDate' => [\n 'shape' => 'dateType',\n ],\n 'UserPolicyList' => [\n 'shape' => 'policyDetailListType',\n ],\n 'GroupList' => [\n 'shape' => 'groupNameListType',\n ],\n ],\n ],\n 'VirtualMFADevice' => [\n 'type' => 'structure',\n 'required' => [\n 'SerialNumber',\n ],\n 'members' => [\n 'SerialNumber' => [\n 'shape' => 'serialNumberType',\n ],\n 'Base32StringSeed' => [\n 'shape' => 'BootstrapDatum',\n ],\n 'QRCodePNG' => [\n 'shape' => 'BootstrapDatum',\n ],\n 'User' => [\n 'shape' => 'User',\n ],\n 'EnableDate' => [\n 'shape' => 'dateType',\n ],\n ],\n ],\n 'accessKeyIdType' => [\n 'type' => 'string',\n 'min' => 16,\n 'max' => 32,\n 'pattern' => '[\\\\w]*',\n ],\n 'accessKeyMetadataListType' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'AccessKeyMetadata',\n ],\n ],\n 'accessKeySecretType' => [\n 'type' => 'string',\n 'sensitive' => true,\n ],\n 'accountAliasListType' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'accountAliasType',\n ],\n ],\n 'accountAliasType' => [\n 'type' => 'string',\n 'min' => 3,\n 'max' => 63,\n 'pattern' => '^[a-z0-9](([a-z0-9]|-(?!-]]*[a-z0-9]]?$',\n ],\n 'arnType' => [\n 'type' => 'string',\n 'min' => 20,\n 'max' => 2048,\n ],\n 'assignmentStatusType' => [\n 'type' => 'string',\n 'enum' => [\n 'Assigned',\n 'Unassigned',\n 'Any',\n ],\n ],\n 'authenticationCodeType' => [\n 'type' => 'string',\n 'min' => 6,\n 'max' => 6,\n 'pattern' => '[\\\\d]*',\n ],\n 'booleanObjectType' => [\n 'type' => 'boolean',\n 'box' => true,\n ],\n 'booleanType' => [\n 'type' => 'boolean',\n ],\n 'certificateBodyType' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 16384,\n 'pattern' => '[\\\\u0009\\\\u000A\\\\u000D\\\\u0020-\\\\u00FF]+',\n ],\n 'certificateChainType' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 2097152,\n 'pattern' => '[\\\\u0009\\\\u000A\\\\u000D\\\\u0020-\\\\u00FF]*',\n ],\n 'certificateIdType' => [\n 'type' => 'string',\n 'min' => 24,\n 'max' => 128,\n 'pattern' => '[\\\\w]*',\n ],\n 'certificateListType' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'SigningCertificate',\n ],\n ],\n 'clientIDListType' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'clientIDType',\n ],\n ],\n 'clientIDType' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 255,\n ],\n 'credentialReportExpiredExceptionMessage' => [\n 'type' => 'string',\n ],\n 'credentialReportNotPresentExceptionMessage' => [\n 'type' => 'string',\n ],\n 'credentialReportNotReadyExceptionMessage' => [\n 'type' => 'string',\n ],\n 'dateType' => [\n 'type' => 'timestamp',\n ],\n 'deleteConflictMessage' => [\n 'type' => 'string',\n ],\n 'duplicateCertificateMessage' => [\n 'type' => 'string',\n ],\n 'entityAlreadyExistsMessage' => [\n 'type' => 'string',\n ],\n 'entityListType' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'EntityType',\n ],\n ],\n 'entityTemporarilyUnmodifiableMessage' => [\n 'type' => 'string',\n ],\n 'existingUserNameType' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 128,\n 'pattern' => '[\\\\w+=,.@-]*',\n ],\n 'groupDetailListType' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'GroupDetail',\n ],\n ],\n 'groupListType' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'Group',\n ],\n ],\n 'groupNameListType' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'groupNameType',\n ],\n ],\n 'groupNameType' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 128,\n 'pattern' => '[\\\\w+=,.@-]*',\n ],\n 'idType' => [\n 'type' => 'string',\n 'min' => 16,\n 'max' => 32,\n 'pattern' => '[\\\\w]*',\n ],\n 'instanceProfileListType' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'InstanceProfile',\n ],\n ],\n 'instanceProfileNameType' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 128,\n 'pattern' => '[\\\\w+=,.@-]*',\n ],\n 'invalidAuthenticationCodeMessage' => [\n 'type' => 'string',\n ],\n 'invalidCertificateMessage' => [\n 'type' => 'string',\n ],\n 'invalidInputMessage' => [\n 'type' => 'string',\n ],\n 'invalidUserTypeMessage' => [\n 'type' => 'string',\n ],\n 'keyPairMismatchMessage' => [\n 'type' => 'string',\n ],\n 'limitExceededMessage' => [\n 'type' => 'string',\n ],\n 'malformedCertificateMessage' => [\n 'type' => 'string',\n ],\n 'malformedPolicyDocumentMessage' => [\n 'type' => 'string',\n ],\n 'markerType' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 320,\n 'pattern' => '[\\\\u0020-\\\\u00FF]*',\n ],\n 'maxItemsType' => [\n 'type' => 'integer',\n 'min' => 1,\n 'max' => 1000,\n ],\n 'maxPasswordAgeType' => [\n 'type' => 'integer',\n 'min' => 1,\n 'max' => 1095,\n 'box' => true,\n ],\n 'mfaDeviceListType' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'MFADevice',\n ],\n ],\n 'minimumPasswordLengthType' => [\n 'type' => 'integer',\n 'min' => 6,\n 'max' => 128,\n ],\n 'noSuchEntityMessage' => [\n 'type' => 'string',\n ],\n 'passwordPolicyViolationMessage' => [\n 'type' => 'string',\n ],\n 'passwordReusePreventionType' => [\n 'type' => 'integer',\n 'min' => 1,\n 'max' => 24,\n 'box' => true,\n ],\n 'passwordType' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 128,\n 'pattern' => '[\\\\u0009\\\\u000A\\\\u000D\\\\u0020-\\\\u00FF]+',\n 'sensitive' => true,\n ],\n 'pathPrefixType' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 512,\n 'pattern' => '\\\\u002F[\\\\u0021-\\\\u007F]*',\n ],\n 'pathType' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 512,\n 'pattern' => '(\\\\u002F]|(\\\\u002F[\\\\u0021-\\\\u007F]+\\\\u002F]',\n ],\n 'policyDetailListType' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'PolicyDetail',\n ],\n ],\n 'policyDocumentType' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 131072,\n 'pattern' => '[\\\\u0009\\\\u000A\\\\u000D\\\\u0020-\\\\u00FF]+',\n ],\n 'policyNameListType' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'policyNameType',\n ],\n ],\n 'policyNameType' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 128,\n 'pattern' => '[\\\\w+=,.@-]*',\n ],\n 'privateKeyType' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 16384,\n 'pattern' => '[\\\\u0009\\\\u000A\\\\u000D\\\\u0020-\\\\u00FF]*',\n 'sensitive' => true,\n ],\n 'roleDetailListType' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'RoleDetail',\n ],\n ],\n 'roleListType' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'Role',\n ],\n ],\n 'roleNameType' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 64,\n 'pattern' => '[\\\\w+=,.@-]*',\n ],\n 'serialNumberType' => [\n 'type' => 'string',\n 'min' => 9,\n 'max' => 256,\n 'pattern' => '[\\\\w+=/:,.@-]*',\n ],\n 'serverCertificateMetadataListType' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'ServerCertificateMetadata',\n ],\n ],\n 'serverCertificateNameType' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 128,\n 'pattern' => '[\\\\w+=,.@-]*',\n ],\n 'statusType' => [\n 'type' => 'string',\n 'enum' => [\n 'Active',\n 'Inactive',\n ],\n ],\n 'summaryKeyType' => [\n 'type' => 'string',\n 'enum' => [\n 'Users',\n 'UsersQuota',\n 'Groups',\n 'GroupsQuota',\n 'ServerCertificates',\n 'ServerCertificatesQuota',\n 'UserPolicySizeQuota',\n 'GroupPolicySizeQuota',\n 'GroupsPerUserQuota',\n 'SigningCertificatesPerUserQuota',\n 'AccessKeysPerUserQuota',\n 'MFADevices',\n 'MFADevicesInUse',\n 'AccountMFAEnabled',\n ],\n ],\n 'summaryMapType' => [\n 'type' => 'map',\n 'key' => [\n 'shape' => 'summaryKeyType',\n ],\n 'value' => [\n 'shape' => 'summaryValueType',\n ],\n ],\n 'summaryValueType' => [\n 'type' => 'integer',\n ],\n 'thumbprintListType' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'thumbprintType',\n ],\n ],\n 'thumbprintType' => [\n 'type' => 'string',\n 'min' => 40,\n 'max' => 40,\n ],\n 'userDetailListType' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'UserDetail',\n ],\n ],\n 'userListType' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'User',\n ],\n ],\n 'userNameType' => [\n 'type' => 'string',\n 'min' => 1,\n 'max' => 64,\n 'pattern' => '[\\\\w+=,.@-]*',\n ],\n 'virtualMFADeviceListType' => [\n 'type' => 'list',\n 'member' => [\n 'shape' => 'VirtualMFADevice',\n ],\n ],\n 'virtualMFADeviceName' => [\n 'type' => 'string',\n 'min' => 1,\n 'pattern' => '[\\\\w+=,.@-]*',\n ],\n ],\n];\n" }, { "alpha_fraction": 0.5995694398880005, "alphanum_fraction": 0.6049515604972839, "avg_line_length": 27.15151596069336, "blob_id": "956d65aca4b34573ffcd5bea27dc3be66c0812e5", "content_id": "9be16e6f46bfaffd1f7e7c9d2d65c1720c1b3d20", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 929, "license_type": "permissive", "max_line_length": 86, "num_lines": 33, "path": "/build/docs.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nuse Aws\\Build\\Docs\\DocsBuilder;\n\n// Setup autoloading for SDK and build classes.\n$loader = require __DIR__ . '/../vendor/autoload.php';\n$loader->addPsr4('Aws\\\\Build\\\\Docs\\\\', __DIR__ . '/docs/classes');\n\n// Setup directories.\n$sourceDir = __DIR__ . '/artifacts/staging';\n$apiModelsDir = realpath(__DIR__ . '/../src/Common/Resources/api');\n$outputDir = __DIR__ . '/artifacts/docs';\n$themeDir = $outputDir . '/theme';\n\nforeach ([$outputDir, $themeDir, $themeDir . '/layout', $themeDir . '/img'] as $dir) {\n if (!is_dir($dir)) {\n if (!mkdir($dir, 0755)) {\n fwrite(STDERR, \"Could not create directory: {$dir}.\");\n exit();\n }\n }\n}\n\n// Generate API docs\n$builder = new DocsBuilder($apiModelsDir, $outputDir);\nreturn $builder->getSami($sourceDir);\n\n/**\n * TODO:\n * ------\n * - Ordering/tweaking search.\n * - Visual tweaks to API pages.\n * - Get theme updates into official Sami phar.\n */\n" }, { "alpha_fraction": 0.48423707485198975, "alphanum_fraction": 0.48612862825393677, "avg_line_length": 31.701030731201172, "blob_id": "14431194fb78d0a7c8d83f3a9002c37e5097a67d", "content_id": "1a1bb21beb40fc901ca9d2cf3589854a8ec5e773", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3172, "license_type": "permissive", "max_line_length": 79, "num_lines": 97, "path": "/src/Utils.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws;\n\nuse transducers as t;\n\nfinal class Utils\n{\n /**\n * Iterates over the files in a directory and works with custom wrappers.\n *\n * @param string $path Path to open (e.g., \"s3://foo/bar\").\n * @param resource $context Stream wrapper context.\n *\n * @return \\Generator Yields relative filename strings.\n */\n public static function dirIterator($path, $context = null)\n {\n $dh = $context ? opendir($path, $context) : opendir($path);\n if (!$dh) {\n throw new \\InvalidArgumentException('File not found: ' . $path);\n }\n while (($file = readdir($dh)) !== false) {\n yield $file;\n }\n closedir($dh);\n }\n\n /**\n * Returns a recursive directory iterator that yields absolute filenames.\n *\n * This iterator is not broken like PHP's built-in DirectoryIterator (which\n * will read the first file from a stream wrapper, then rewind, then read\n * it again).\n *\n * @param string $path Path to traverse (e.g., s3://bucket/key, /tmp)\n * @param resource $context Stream context options.\n *\n * @return \\Generator Yields absolute filenames.\n */\n public static function recursiveDirIterator($path, $context = null)\n {\n $invalid = ['.' => true, '..' => true];\n $pathLen = strlen($path) + 1;\n $iterator = self::dirIterator($path, $context);\n $queue = [];\n do {\n while ($iterator->valid()) {\n $file = $iterator->current();\n $iterator->next();\n if (isset($invalid[basename($file)])) {\n continue;\n }\n $fullPath = \"{$path}/{$file}\";\n yield $fullPath;\n if (is_dir($fullPath)) {\n $queue[] = $iterator;\n $iterator = t\\to_iter(\n self::dirIterator($fullPath, $context),\n t\\map(function ($file) use ($fullPath, $pathLen) {\n return substr(\"{$fullPath}/{$file}\", $pathLen);\n })\n );\n continue;\n }\n }\n $iterator = array_pop($queue);\n } while ($iterator);\n }\n\n /**\n * Returns a function that invokes the provided variadic functions one\n * after the other until one of the functions returns a non-null value.\n * The return function will call each passed function with any arguments it\n * is provided.\n *\n * $a = function ($x, $y) { return null; };\n * $b = function ($x, $y) { return $x + $y; };\n * $fn = Utils::orFn($a, $b);\n * echo $fn(1, 2); // 3\n *\n * @return callable\n */\n public static function orFn()\n {\n $fns = func_get_args();\n return function () use ($fns) {\n $args = func_get_args();\n foreach ($fns as $fn) {\n $result = $args ? call_user_func_array($fn, $args) : $fn();\n if ($result) {\n return $result;\n }\n }\n return null;\n };\n }\n}\n" }, { "alpha_fraction": 0.7730061411857605, "alphanum_fraction": 0.7730061411857605, "avg_line_length": 22.285715103149414, "blob_id": "ba4396673d810f29596dc243e28e5eae9c8719d0", "content_id": "55a7de3a1a7af068f5efc5d0332145d244d57725", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 163, "license_type": "permissive", "max_line_length": 60, "num_lines": 7, "path": "/src/Sns/Exception/MessageValidatorException.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Sns\\Exception;\n\n/**\n * Generic exception thrown by the SNS Message Validator.\n */\nclass MessageValidatorException extends \\RuntimeException {}\n" }, { "alpha_fraction": 0.6371951103210449, "alphanum_fraction": 0.6554877758026123, "avg_line_length": 19.5, "blob_id": "2272b74bbc24c69496b704cfd9bc3f7c15d0aab3", "content_id": "de556cb597d224b0fcfa750df7f698dd95887d07", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 328, "license_type": "permissive", "max_line_length": 72, "num_lines": 16, "path": "/src/Route53/Route53Client.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Route53;\n\nuse Aws\\AwsClient;\n\n/**\n * This client is used to interact with the **Amazon Route 53** service.\n */\nclass Route53Client extends AwsClient\n{\n public function __construct(array $args)\n {\n parent::__construct($args);\n $this->getEmitter()->attach(new CleanIdSubscriber());\n }\n}\n" }, { "alpha_fraction": 0.49957647919654846, "alphanum_fraction": 0.5051668882369995, "avg_line_length": 29.42783546447754, "blob_id": "ff650501c0cd08aeb7a4ea7c8758f72a8fb1f731", "content_id": "cca66db7ff2f46d318a09f5e9372778fd31ab13d", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 5903, "license_type": "permissive", "max_line_length": 90, "num_lines": 194, "path": "/tests/Multipart/UploaderTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Multipart;\n\nuse Aws\\Exception\\MultipartUploadException;\nuse Aws\\Multipart\\Uploader;\nuse Aws\\Multipart\\UploadState;\nuse Aws\\Result;\nuse Aws\\Test\\UsesServiceTrait;\n\n/**\n * @covers Aws\\Multipart\\Uploader\n */\nclass UploaderTest extends \\PHPUnit_Framework_TestCase\n{\n use UsesServiceTrait;\n\n /**\n * @expectedException \\Aws\\Exception\\MultipartUploadException\n */\n public function testThrowsExceptionOnBadInitiateRequest()\n {\n $uploader = $this->getMockUploader(\n [$this->createMockAwsException()] // Initiate\n );\n $uploader->upload();\n }\n\n /**\n * @expectedException \\LogicException\n */\n public function testThrowsExceptionIfStateIsCompleted()\n {\n $uploader = $this->getMockUploader([], UploadState::COMPLETED);\n $this->assertTrue($uploader->getState()->isCompleted());\n $uploader();\n }\n\n /**\n * @expectedException \\LogicException\n */\n public function testThrowsExceptionIfStateIsAborted()\n {\n $uploader = $this->getMockUploader([], UploadState::ABORTED);\n $uploader->upload();\n }\n\n /**\n * @expectedException \\Aws\\Exception\\MultipartUploadException\n */\n public function testThrowsExceptionOnBadCompleteRequest()\n {\n $uploader = $this->getMockUploader([\n new Result([]), // Initiate\n $this->createMockAwsException() // Complete\n ]);\n $uploader->upload();\n }\n\n public function testSuccessfulCompleteReturnsResult()\n {\n $uploader = $this->getMockUploader([\n new Result([]), // Initiate\n new Result(['test' => true]) // Complete\n ]);\n $this->assertTrue($uploader->upload()['test']);\n }\n\n /**\n * @expectedException \\LogicException\n */\n public function testThrowsExceptionIfAbortingWhenNotInitiated()\n {\n $uploader = $this->getMockUploader();\n $uploader->abort();\n }\n\n /**\n * @expectedException \\Aws\\Exception\\MultipartUploadException\n */\n public function testThrowsExceptionOnBadAbortRequest()\n {\n $uploader = $this->getMockUploader(\n [$this->createMockAwsException()], // Abort\n UploadState::INITIATED\n );\n $uploader->abort();\n }\n\n public function testSuccessfulAbortReturnsResult()\n {\n $uploader = $this->getMockUploader(\n [new Result(['test' => true])], // Abort\n UploadState::INITIATED\n );\n $this->assertTrue($uploader->abort()['test']);\n }\n\n public function testThrowsExceptionOnBadUploadRequest()\n {\n $uploader = $this->getMockUploader(\n [\n new Result([]), // Initiate\n $this->createMockAwsException('ERROR', 'Aws\\Exception\\AwsException', '1'),\n $this->createMockAwsException('ERROR', 'Aws\\Exception\\AwsException', '2'),\n $this->createMockAwsException('ERROR', 'Aws\\Exception\\AwsException', '3'),\n ],\n null,\n [\n ['PartNumber' => 1],\n ['PartNumber' => 2],\n ['PartNumber' => 3],\n ]\n );\n\n try {\n $uploader->upload(3);\n $this->fail('No exception was thrown.');\n } catch (MultipartUploadException $e) {\n $this->assertContains('Part 3', $e->getMessage());\n }\n }\n\n public function testCallsProvidedBeforeCallback()\n {\n $called = false;\n $uploader = $this->getMockUploader([\n new Result([]), // Initiate\n new Result([]), // Upload\n new Result([]) // Complete\n ], null, [[]]);\n $uploader->upload(1, function () use (&$called) {\n $called = true;\n });\n $this->assertTrue($called);\n }\n\n private function getMockUploader(\n array $results = [],\n $status = null,\n array $parts = []\n ) {\n $client = $this->getTestClient('s3', [\n 'retries' => 0,\n 'validate' => false,\n ]);\n $this->addMockResults($client, $results);\n $state = new UploadState(['Bucket' => 'foo', 'Key' => 'bar']);\n $state->setStatus($status ?: UploadState::CREATED);\n $parts = new \\ArrayIterator($parts);\n\n // Create the mock uploader\n $uploader = $this->getMockBuilder('Aws\\Multipart\\Uploader')\n ->setConstructorArgs([$client, $state, $parts, [\n 'id' => ['Bucket', 'Key', 'UploadId'],\n 'part' => [\n 'min_size' => 5242880,\n 'max_size' => 5368709120,\n 'max_num' => 10000,\n 'param' => 'PartNumber',\n ],\n 'initiate' => [\n 'command' => 'CreateMultipartUpload',\n 'params' => ['fizz' => 'buzz'],\n ],\n 'upload' => [\n 'command' => 'UploadPart',\n 'params' => [],\n ],\n 'complete' => [\n 'command' => 'CompleteMultipartUpload',\n 'params' => [],\n ],\n 'abort' => [\n 'command' => 'AbortMultipartUpload',\n 'params' => [],\n ],\n 'fn' => [\n 'complete' => function () {return [];},\n 'result' => function () {},\n ]\n ]])\n ->setMethods(['getCompleteCommand'])\n ->getMockForAbstractClass();\n $uploader->expects($this->any())\n ->method('getCompleteCommand')\n ->willReturn($client->getCommand('CompleteMultipartUpload', [\n 'Bucket' => 'foo',\n 'Key' => 'bar'\n ]));\n\n /** @var Uploader $uploader */\n return $uploader;\n }\n}\n" }, { "alpha_fraction": 0.644723117351532, "alphanum_fraction": 0.644723117351532, "avg_line_length": 24.1842098236084, "blob_id": "0a185ac125e52a496c761916a07ce935a0d5cc83", "content_id": "165ad847f3e68c317f17898172f41188ff380e0f", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 957, "license_type": "permissive", "max_line_length": 79, "num_lines": 38, "path": "/src/Subscriber/SaveAs.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Subscriber;\n\nuse GuzzleHttp\\Command\\Event\\PreparedEvent;\nuse GuzzleHttp\\Event\\RequestEvents;\nuse GuzzleHttp\\Event\\SubscriberInterface;\n\n/**\n * Changes the location to which a REST web service downloads the body of a\n * response.\n */\nclass SaveAs implements SubscriberInterface\n{\n /** @var string The key for the name of the parameter used to control it */\n private $paramName;\n\n /**\n * @param string $paramName The key used to control the SaveAs behavior\n */\n public function __construct($paramName = 'SaveAs')\n {\n $this->paramName = $paramName;\n }\n\n public function getEvents()\n {\n return ['prepared' => ['onPrepared', RequestEvents::LATE]];\n }\n\n public function onPrepared(PreparedEvent $event)\n {\n $command = $event->getCommand();\n\n if ($value = $command[$this->paramName]) {\n $event->getRequest()->getConfig()->set('save_to', $value);\n }\n }\n}\n" }, { "alpha_fraction": 0.6182483434677124, "alphanum_fraction": 0.6240585446357727, "avg_line_length": 33.939849853515625, "blob_id": "7edb7b852620ceb387de69552f441b038b4679a3", "content_id": "6bdeee87762c88a6b609248bf752d7fcfc9ddbdf", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4647, "license_type": "permissive", "max_line_length": 90, "num_lines": 133, "path": "/tests/Sns/MessageValidator/MessageValidatorTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Sns\\MessageValidator;\n\nuse Aws\\Sns\\MessageValidator\\Message;\nuse Aws\\Sns\\MessageValidator\\MessageValidator;\nuse GuzzleHttp\\Collection;\nuse GuzzleHttp\\Subscriber\\Mock;\nuse GuzzleHttp\\Message\\Response;\nuse GuzzleHttp\\Client;\nuse GuzzleHttp\\Stream\\Stream;\n\n/**\n * @covers \\Aws\\Sns\\MessageValidator\\MessageValidator\n */\nclass MessageValidatorTest extends \\PHPUnit_Framework_TestCase\n{\n const VALID_CERT_URL = \"https://sns.foo.amazonaws.com/bar.pem\";\n\n protected function setUp()\n {\n if (!extension_loaded('openssl')) {\n $this->markTestSkipped('The OpenSSL extension is required to run '\n . 'the tests for MessageValidator.');\n }\n }\n\n public function testIsValidReturnsFalseOnFailedValidation()\n {\n $validator = new MessageValidator();\n $message = new Message(new Collection());\n $this->assertFalse($validator->isValid($message));\n }\n\n /**\n * @expectedException \\Aws\\Sns\\Exception\\MessageValidatorException\n * @expectedExceptionMessage The certificate is located on an invalid domain.\n */\n public function testValidateFailsWhenCertUrlInvalid()\n {\n $validator = new MessageValidator();\n $message = new Message(new Collection([\n 'SigningCertURL' => 'https://foo.amazonaws.com/bar'\n ]));\n $validator->validate($message);\n }\n\n /**\n * @expectedException \\Aws\\Sns\\Exception\\MessageValidatorException\n * @expectedExceptionMessage Cannot get the public key from the certificate.\n */\n public function testValidateFailsWhenCannotDeterminePublicKey()\n {\n $client = $this->getMockClient();\n $validator = new MessageValidator($client);\n $message = new Message(new Collection([\n 'SigningCertURL' => self::VALID_CERT_URL\n ]));\n $validator->validate($message);\n }\n\n /**\n * @expectedException \\Aws\\Sns\\Exception\\MessageValidatorException\n * @expectedExceptionMessage The message signature is invalid.\n */\n public function testValidateFailsWhenMessageIsInvalid()\n {\n // Get the signature for some dummy data\n list($signature, $certificate) = $this->getSignature('foo');\n // Create the validator with a mock HTTP client that will respond with\n // the certificate\n $client = $this->getMockClient(new Response(200, [], $certificate));\n $validator = new MessageValidator($client);\n $message = new Message(new Collection([\n 'SigningCertURL' => self::VALID_CERT_URL,\n 'Signature' => $signature,\n ]));\n $validator->validate($message);\n }\n\n public function testValidateSucceedsWhenMessageIsValid()\n {\n // Create a real message\n $message = Message::fromArray([\n 'Message' => 'foo',\n 'MessageId' => 'bar',\n 'Timestamp' => time(),\n 'TopicArn' => 'baz',\n 'Type' => 'Notification',\n 'SigningCertURL' => self::VALID_CERT_URL,\n 'Signature' => '',\n ]);\n\n // Get the signature for a real message\n list($signature, $certificate) = $this->getSignature($message->getStringToSign());\n $message->getData()->set('Signature', $signature);\n\n // Create the validator with a mock HTTP client that will respond with\n // the certificate\n $client = $this->getMockClient(new Response(200, [], $certificate));\n $validator = new MessageValidator($client);\n\n // The message should validate\n $this->assertTrue($validator->isValid($message));\n }\n\n protected function getMockClient(Response $response = null)\n {\n $response = $response ?: new Response(200);\n $plugin = new Mock();\n $plugin->addResponse($response);\n $client = new Client();\n $client->getEmitter()->attach($plugin);\n\n return $client;\n }\n\n protected function getSignature($stringToSign)\n {\n // Generate a new Certificate Signing Request and public/private keypair\n $csr = openssl_csr_new(array(), $keypair);\n // Create the self-signed certificate\n $x509 = openssl_csr_sign($csr, null, $keypair, 1);\n openssl_x509_export($x509, $certificate);\n // Create the signature\n $privateKey = openssl_get_privatekey($keypair);\n openssl_sign($stringToSign, $signature, $privateKey);\n // Free the openssl resources used\n openssl_pkey_free($keypair);\n openssl_x509_free($x509);\n\n return [base64_encode($signature), Stream::factory($certificate)];\n }\n}\n" }, { "alpha_fraction": 0.612863302230835, "alphanum_fraction": 0.6277056336402893, "avg_line_length": 26.879310607910156, "blob_id": "3073cb8cc32f9841a8d5627d0e81ffc8169053ac", "content_id": "fb283399b70e431358fdca0213dbdba1631afa5f", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1617, "license_type": "permissive", "max_line_length": 74, "num_lines": 58, "path": "/tests/Retry/S3TimeoutFilterTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Retry;\n\nuse Aws\\Retry\\S3TimeoutFilter;\nuse GuzzleHttp\\Transaction;\nuse GuzzleHttp\\Client;\nuse GuzzleHttp\\Event\\CompleteEvent;\nuse GuzzleHttp\\Message\\Request;\nuse GuzzleHttp\\Message\\Response;\nuse GuzzleHttp\\Stream\\Stream;\nuse GuzzleHttp\\Subscriber\\Retry\\RetrySubscriber;\n\n/**\n * @covers \\Aws\\Retry\\S3TimeoutFilter\n */\nclass S3TimeoutFilterTest extends \\PHPUnit_Framework_TestCase\n{\n public function testIngoresWhenNoResponseIsPresent()\n {\n $ate = $this->getTrans();\n $f = new S3TimeoutFilter();\n $this->assertEquals(RetrySubscriber::DEFER, $f(2, $ate));\n }\n\n public function testIgnoresWhenNot400()\n {\n $ate = $this->getTrans();\n $ate->intercept(new Response(302));\n $f = new S3TimeoutFilter();\n $this->assertEquals(RetrySubscriber::DEFER, $f(2, $ate));\n }\n\n public function testRetriesWhenTimeoutIsDetected()\n {\n $ate = $this->getTrans();\n $ate->intercept(\n new Response(400, [], Stream::factory(S3TimeoutFilter::ERR))\n );\n $f = new S3TimeoutFilter();\n $this->assertEquals(RetrySubscriber::RETRY, $f(2, $ate));\n }\n\n public function testDefersWhenNotTimedOut()\n {\n $ate = $this->getTrans();\n $ate->intercept(new Response(400, [], Stream::factory('foo :(')));\n $f = new S3TimeoutFilter();\n $this->assertEquals(RetrySubscriber::DEFER, $f(2, $ate));\n }\n\n private function getTrans()\n {\n return new CompleteEvent(new Transaction(\n new Client(),\n new Request('GET', 'http://foo.com')\n ));\n }\n}\n" }, { "alpha_fraction": 0.4945460557937622, "alphanum_fraction": 0.5123342871665955, "avg_line_length": 29.403060913085938, "blob_id": "500f62d8a88e986adb411507d1215bfc99b7cd4d", "content_id": "a84223ff6c667847a3d4f564d56fbf83d9fc099f", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 5959, "license_type": "permissive", "max_line_length": 113, "num_lines": 196, "path": "/tests/S3/TransferTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Tests\\S3;\n\nuse Aws\\Result;\nuse Aws\\S3\\Transfer;\nuse Aws\\Test\\UsesServiceTrait;\nuse GuzzleHttp\\Command\\CommandInterface;\nuse GuzzleHttp\\Command\\Event\\PreparedEvent;\nuse GuzzleHttp\\Event\\RequestEvents;\n\n/**\n * @covers Aws\\S3\\Transfer\n */\nclass TransferTest extends \\PHPUnit_Framework_TestCase\n{\n use UsesServiceTrait;\n\n /**\n * @expectedException \\InvalidArgumentException\n * @expectedExceptionMessage base_dir\n */\n public function testEnsuresBaseDirIsAvailable()\n {\n $s3 = $this->getTestClient('s3');\n (new Transfer($s3, new \\ArrayIterator([]), 's3://foo/bar'));\n }\n\n /**\n * @expectedException \\InvalidArgumentException\n * @expectedExceptionMessage Cannot copy from s3 to s3\n */\n public function testCannotCopyS3ToS3()\n {\n $s3 = $this->getTestClient('s3');\n $s3->getEmitter()->on('prepared', function (PreparedEvent $e) {\n $e->intercept(new Result([]));\n });\n (new Transfer($s3, 's3://baz/bam', 's3://foo/bar'));\n }\n\n /**\n * @expectedException \\InvalidArgumentException\n * @expectedExceptionMessage Cannot copy local file to local file\n */\n public function testCannotCopyLocal()\n {\n $s3 = $this->getTestClient('s3');\n (new Transfer($s3, __DIR__, __DIR__));\n }\n\n /**\n * @expectedException \\InvalidArgumentException\n * @expectedExceptionMessage mup_threshold must be >= 5248000\n */\n public function testEnsuresMupSizeIsValid()\n {\n $s3 = $this->getTestClient('s3');\n (new Transfer($s3, __DIR__, 's3://foo/bar', ['mup_threshold' => 10]));\n }\n\n /**\n * @expectedException \\InvalidArgumentException\n * @expectedExceptionMessage source must be the path to a directory or an iterator that yields file names\n */\n public function testEnsuresSourceIsValid()\n {\n $s3 = $this->getTestClient('s3');\n (new Transfer($s3, false, 's3://foo/bar'));\n }\n\n public function testUsesFileIteratorIfStringIsProvided()\n {\n $s3 = $this->getTestClient('s3');\n $t = new Transfer($s3, __DIR__, 's3://foo/bar');\n $this->assertInstanceOf('Iterator', $this->readAttribute($t, 'source'));\n }\n\n public function testCanSetCustomOptions()\n {\n $opts = [\n 'mup_threshold' => 5248000,\n 'base_dir' => 'foo!',\n 'concurrency' => 12\n ];\n $s3 = $this->getTestClient('s3');\n $t = new Transfer($s3, __DIR__, 's3://foo/bar', $opts);\n foreach ($opts as $k => $v) {\n $this->assertSame($v, $this->readAttribute($t, $k));\n }\n }\n\n public function testCanSetBeforeOptionForUploadsAndUsedWithDebug()\n {\n $s3 = $this->getTestClient('s3');\n $c = [];\n $t = new Transfer($s3, __DIR__, 's3://foo/bar', [\n 'before' => function ($source, $dest, CommandInterface $command) use (&$c) {\n $c[] = func_get_args();\n },\n 'debug' => true\n ]);\n $s3->getEmitter()->on('prepared', function (PreparedEvent $e) {\n $e->intercept(new Result([]));\n });\n ob_start();\n $t->transfer();\n $output = ob_get_clean();\n $this->assertNotEmpty($c);\n\n foreach ($c as $test) {\n $this->assertContains(__DIR__, $test[0]);\n $this->assertContains('s3://foo/bar', $test[1]);\n $this->assertEquals('PutObject', $test[2]->getName());\n $this->assertEquals('foo', $test[2]['Bucket']);\n $this->assertStringStartsWith('bar/', $test[2]['Key']);\n $this->assertContains($test[2]['SourceFile'] . ' -> s3://foo/bar', $output);\n }\n }\n\n public function testDoesMupUploadsForLargeFiles()\n {\n $s3 = $this->getTestClient('s3');\n $q = [\n ['UploadId' => '123'],\n ['ETag' => 'a'],\n ['ETag' => 'b'],\n ['UploadId' => '123']\n ];\n\n $s3->getEmitter()->on('prepared', function (PreparedEvent $e) use (&$q) {\n $e->intercept(new Result(array_shift($q)));\n }, RequestEvents::LATE);\n\n $dir = sys_get_temp_dir() . '/unittest';\n `rm -rf $dir`;\n mkdir($dir);\n $filename = $dir . '/large.txt';\n $f = fopen($filename, 'w+');\n $line = str_repeat('.', 1024);\n for ($i = 0; $i < 6000; $i++) {\n fwrite($f, $line);\n }\n fclose($f);\n\n $res = fopen('php://temp', 'r+');\n $t = new Transfer($s3, $dir, 's3://foo/bar', [\n 'mup_threshold' => 5248000,\n 'debug' => $res\n ]);\n\n $t->transfer();\n rewind($res);\n $output = stream_get_contents($res);\n $this->assertContains(\"Transferring $filename -> s3://foo/bar/large.txt (UploadPart) : Part=1\", $output);\n\n unlink($filename);\n rmdir($dir);\n }\n\n public function testDownloadsObjects()\n {\n $s3 = $this->getTestClient('s3');\n $lso = [\n 'IsTruncated' => false,\n 'Contents' => [\n ['Key' => 'foo/bar'],\n ['Key' => 'baz/bam'],\n ]\n ];\n\n $q = [\n $lso,\n $lso,\n ['Body' => 'test'],\n ['Body' => '123']\n ];\n\n $s3->getEmitter()->on('prepared', function (PreparedEvent $e) use (&$q) {\n $e->intercept(new Result(array_shift($q)));\n });\n\n $dir = sys_get_temp_dir() . '/unittest';\n !is_dir($dir) and mkdir($dir);\n $res = fopen('php://temp', 'r+');\n $t = new Transfer($s3, 's3://foo/bar', $dir, ['debug' => $res]);\n $t->transfer();\n rewind($res);\n $output = stream_get_contents($res);\n $this->assertContains('s3://foo/bar/foo/bar -> ', $output);\n $this->assertContains('s3://foo/bar/baz/bam -> ', $output);\n\n rmdir($dir . '/foo');\n rmdir($dir . '/baz');\n rmdir($dir);\n }\n}\n" }, { "alpha_fraction": 0.697617769241333, "alphanum_fraction": 0.7041147947311401, "avg_line_length": 40.0444450378418, "blob_id": "851c261735acbe767e1c7f0aed9f608aca21c844", "content_id": "0a4dc62e7bab44c5a611bca2fb9c7a5572c03c24", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 3694, "license_type": "permissive", "max_line_length": 90, "num_lines": 90, "path": "/docs/paginators.rst", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "==========\nPaginators\n==========\n\nIntroduction\n------------\n\nSome AWS service operations are paginated and respond with truncated results.\nFor example, Amazon S3's ``ListObjects`` operation only returns up to 1000\nobjects at a time. Operations like these (typically prefixed with \"list\" or\n\"describe\") require making subsequent requests with token (or marker) parameters\nto retrieve the entire set of results.\n\n**Paginators** are a feature of the SDK that act as an abstraction over\nthis process to make it easier for developers to use paginated APIs. A Paginator\nis essentially an iterator of results. They are created via the\n``getPaginator()`` method of the client. When you call ``getPaginator()``, you\nmust provide the name of the operation and the operation's arguments (in the\nsame way as when you execute an operation). You can iterate over a Paginator\nobject using ``foreach`` to get individual ``Aws\\Result`` objects.\n\n.. code-block:: php\n\n $results = $s3Client->getPaginator('ListObjects', ['Bucket' => 'my-bucket']);\n\n foreach ($results as $result) {\n foreach ($result['Contents'] as $object) {\n echo $object['Key'] . \"\\n\";\n }\n }\n\nPaginator Objects\n-----------------\n\nThe actual object returned by ``getPaginator()`` method is an instance of the\n``Aws\\ResultPaginator`` class. This class implements PHP's native ``Iterator``\ninterface, which is why it works with ``foreach``. It can also be used with\niterator functions, like ``iterator_to_array``, and integrates well with\n`SPL iterators <http://www.php.net/manual/en/spl.iterators.php>`_ like the\n``LimitIterator`` object.\n\nPaginator objects only hold one \"page\" of results at a time and are executed\nlazily. This means that they make only as many requests as they need to yield\nthe current page of results. For example, The S3 ``ListObjects`` operation only\nreturns up to 1000 objects at a time, so if your bucket has ~10000 objects, then\nthe paginator would need to do 10 requests total. When you iterate through the\nresults, the first request is executed when you start iterating, the second in\nthe second iteration of the loop, and so forth.\n\nEnumerating Data from Results\n-----------------------------\n\nPaginator objects have a method called ``search()``, which allows you to create\niterators for data within a set of results. When you call ``search()``, you must\nprovide a :doc:`JMESPath expression <jmespath>` to specify what data to extract.\nCalling ``search()`` returns an iterator that yields the results of the\nexpression on each page of results. This is evaluated lazily, as you iterate\nthrough the returned iterator.\n\nThe following example is equivalent to the preceding code sample, but uses the\n``ResultPaginator::search()``, method to be more concise.\n\n.. code-block:: php\n\n $results = $s3Client->getPaginator('ListObjects', ['Bucket' => 'my-bucket']);\n foreach ($results->search('Contents[].Key') as $key) {\n echo $key . \"\\n\";\n }\n\nYou can also limit the number of items you want returned by using the second\nargument of ``search()``.\n\n.. code-block:: php\n\n $keys = $results->search('Contents[].Key', 2500);\n\nJMESPath expressions allow you to do fairly complex things. For example, if you\nwanted to print all of the object keys and common prefixes (i.e., do an ``ls``\nof a bucket), you could do the following.\n\n.. code-block:: php\n\n // List all prefixes (\"directories\") and objects (\"files\") in the bucket.\n $results = $s3Client->getPaginator('ListObjects', [\n 'Bucket' => 'my-bucket',\n 'Delimiter' => '/'\n ]);\n foreach ($paginator->search('[CommonPrefixes[].Prefix, Contents[].Key][]') as $item) {\n echo $item . \"\\n\";\n }\n" }, { "alpha_fraction": 0.48210135102272034, "alphanum_fraction": 0.48396095633506775, "avg_line_length": 30.632352828979492, "blob_id": "679699c9489f63cc3a85831463901f01e0d766ca", "content_id": "45c93869d4f98b369b8a3b42f8b5810a18272515", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2151, "license_type": "permissive", "max_line_length": 77, "num_lines": 68, "path": "/tests/Api/Serializer/JsonRpcSerializerTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Api\\Serializer;\n\nuse Aws\\Api\\Serializer\\JsonRpcSerializer;\nuse Aws\\Api\\Service;\nuse Aws\\Test\\UsesServiceTrait;\nuse GuzzleHttp\\Client;\nuse GuzzleHttp\\Command\\Command;\nuse GuzzleHttp\\Command\\CommandTransaction;\n\n/**\n * @covers Aws\\Api\\Serializer\\JsonRpcSerializer\n */\nclass JsonRpcSerializerTest extends \\PHPUnit_Framework_TestCase\n{\n use UsesServiceTrait;\n\n public function testPreparesRequests()\n {\n $service = new Service(function () {\n return [\n 'metadata'=> [\n 'targetPrefix' => 'test',\n 'jsonVersion' => '1.1'\n ],\n 'operations' => [\n 'foo' => [\n 'http' => ['httpMethod' => 'POST'],\n 'input' => [\n 'type' => 'structure',\n 'members' => [\n 'baz' => ['type' => 'string']\n ]\n ]\n ]\n ]\n ];\n }, 'service', 'region');\n\n $http = new Client();\n\n $aws = $this->getMockBuilder('Aws\\AwsClient')\n ->setMethods(['getHttpClient'])\n ->disableOriginalConstructor()\n ->getMock();\n\n $aws->expects($this->once())\n ->method('getHttpClient')\n ->will($this->returnValue($http));\n\n $j = new JsonRpcSerializer($service, 'http://foo.com');\n $trans = new CommandTransaction(\n $aws,\n new Command('foo', ['baz' => 'bam'])\n );\n $trans->request = $j($trans);\n $request = $trans->request;\n $this->assertEquals('POST', $request->getMethod());\n $this->assertEquals('http://foo.com', $request->getUrl());\n $this->assertTrue($request->hasHeader('User-Agent'));\n $this->assertEquals(\n 'application/x-amz-json-1.1',\n $request->getHeader('Content-Type')\n );\n $this->assertEquals('test.foo', $request->getHeader('X-Amz-Target'));\n $this->assertEquals('{\"baz\":\"bam\"}', $request->getBody());\n }\n}\n" }, { "alpha_fraction": 0.5267857313156128, "alphanum_fraction": 0.5267857313156128, "avg_line_length": 24.454545974731445, "blob_id": "8ac23dc6d92ef545b3006d5ef3fa7a81b6552faf", "content_id": "6526d4d226a0daa86e79ff7aa4dd68aeaa02b5e6", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 560, "license_type": "permissive", "max_line_length": 57, "num_lines": 22, "path": "/tests/ResultTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test;\n\nuse Aws\\Result;\n\n/**\n * @covers Aws\\Result\n */\nclass ResultTest extends \\PHPUnit_Framework_TestCase\n{\n public function testHasData()\n {\n $c = new Result(['a' => 'b', 'c' => 'd']);\n $this->assertEquals('b', $c['a']);\n $this->assertEquals('d', $c['c']);\n $this->assertEquals('d', $c->get('c'));\n $this->assertTrue($c->hasKey('c'));\n $this->assertFalse($c->hasKey('f'));\n $this->assertEquals('b', $c->search('a'));\n $this->assertContains('Model Data', (string) $c);\n }\n}\n" }, { "alpha_fraction": 0.6627882122993469, "alphanum_fraction": 0.6674423813819885, "avg_line_length": 34.26865768432617, "blob_id": "9544722f309697a3a818a5717fafc3a4a05eb3bb", "content_id": "0f2cff10ab9fec07a1aeeb3305e892864ab39dbd", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 4741, "license_type": "permissive", "max_line_length": 120, "num_lines": 134, "path": "/docs/waiters.rst", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "=======\nWaiters\n=======\n\nIntroduction\n------------\n\n.. include:: _snippets/waiters-intro.txt\n\nIf the waiter has to poll the bucket too many times, it will throw an ``Aws\\Common\\Exception\\RuntimeException``\nexception.\n\nThe \"``waitUntil[…]``\" methods are all implemented via the ``__call`` magic method, and are a more discoverable shortcut\nto using the concrete ``waitUntil()`` method, since many IDEs can auto-complete methods defined using the ``@method``\nannotation. The following code uses the ``waitUntil()`` method, but is equivalent to the previous code sample.\n\n.. code-block:: php\n\n $s3Client->waitUntil('BucketExists', array('Bucket' => 'my-bucket'));\n\nBasic Configuration\n-------------------\n\nYou can tune the number of polling attempts issued by a waiter or the number of seconds to delay between each poll by\npassing optional values prefixed with \"waiter.\":\n\n.. code-block:: php\n\n $s3Client->waitUntilBucketExists(array(\n 'Bucket' => 'my-bucket',\n 'waiter.interval' => 10,\n 'waiter.max_attempts' => 3\n ));\n\nWaiter Objects\n--------------\n\nTo interact with the waiter object directly, you must use the ``getWaiter()`` method. The following code is equivalent\nto the example in the preceding section.\n\n.. code-block:: php\n\n $bucketExistsWaiter = $s3Client->getWaiter('BucketExists')\n ->setConfig(array('Bucket' => 'my-bucket'))\n ->setInterval(10)\n ->setMaxAttempts(3);\n $bucketExistsWaiter->wait();\n\nWaiter Events\n-------------\n\nOne benefit of working directly with the waiter object is that you can attach event listeners. Waiters emit up to two\nevents in each **wait cycle**. A wait cycle does the following:\n\n#. Dispatch the ``waiter.before_attempt`` event.\n#. Attempt to resolve the wait condition by making a request to the service and checking the result.\n#. If the wait condition is resolved, the wait cycle exits. If ``max_attempts`` is reached, an exception is thrown.\n#. Dispatch the ``waiter.before_wait`` event.\n#. Sleep ``interval`` amount of seconds.\n\nWaiter objects extend the ``Guzzle\\Common\\AbstractHasDispatcher`` class which exposes the ``addSubscriber()`` method and\n``getEventDispatcher()`` method. To attach listeners, you can use the following example, which is a modified version of\nthe previous one.\n\n.. code-block:: php\n\n // Get and configure the waiter object\n $waiter = $s3Client->getWaiter('BucketExists')\n ->setConfig(array('Bucket' => 'my-bucket'))\n ->setInterval(10)\n ->setMaxAttempts(3);\n\n // Get the event dispatcher and register listeners for both events emitted by the waiter\n $dispatcher = $waiter->getEventDispatcher();\n $dispatcher->addListener('waiter.before_attempt', function () {\n echo \"Checking if the wait condition has been met…\\n\";\n });\n $dispatcher->addListener('waiter.before_wait', function () use ($waiter) {\n $interval = $waiter->getInterval();\n echo \"Sleeping for {$interval} seconds…\\n\";\n });\n\n $waiter->wait();\n\nCustom Waiters\n--------------\n\nIt is possible to implement custom waiter objects if your use case requires application-specific waiter logic or waiters\nthat are not yet supported by the SDK. You can use the ``getWaiterFactory()`` and ``setWaiterFactory()`` methods on the\nclient to manipulate the waiter factory used by the client such that your custom waiter can be instantiated. By default\nthe service clients use a ``Aws\\Common\\Waiter\\CompositeWaiterFactory`` which allows you to add additional factories if\nneeded. The following example shows how to implement a contrived custom waiter class and then modify a client's waiter\nfactory such that it can create instances of the custom waiter.\n\n.. code-block:: php\n\n namespace MyApp\\FakeWaiters\n {\n use Aws\\Common\\Waiter\\AbstractResourceWaiter;\n\n class SleptThreeTimes extends AbstractResourceWaiter\n {\n public function doWait()\n {\n if ($this->attempts < 3) {\n echo \"Need to sleep…\\n\";\n return false;\n } else {\n echo \"Now I've slept 3 times.\\n\";\n return true;\n }\n }\n }\n }\n\n namespace\n {\n use Aws\\S3\\S3Client;\n use Aws\\Common\\Waiter\\WaiterClassFactory;\n\n $s3Client = S3Client::factory();\n\n $compositeFactory = $s3Client->getWaiterFactory();\n $compositeFactory->addFactory(new WaiterClassFactory('MyApp\\FakeWaiters'));\n\n $waiter = $s3Client->waitUntilSleptThreeTimes();\n }\n\nThe result of this code should look like the following::\n\n Need to sleep…\n Need to sleep…\n Need to sleep…\n Now I've slept 3 times.\n\n" }, { "alpha_fraction": 0.6010709404945374, "alphanum_fraction": 0.6010709404945374, "avg_line_length": 32.95454406738281, "blob_id": "8b433425449356734769be3832aa7140b0711443", "content_id": "07de745f323e0c4a097ea2c7eafcd625c34b4b8b", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 747, "license_type": "permissive", "max_line_length": 89, "num_lines": 22, "path": "/build/build-version-manifest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\n\nrequire __DIR__ . '/functions.php';\n\n$manifest = [];\nforeach (glob(__DIR__ . '/../src/data/*.api.php') as $file) {\n $model = include $file;\n $metadata = $model['metadata'] + ['compatibleApiVersions' => []];\n $manifest[$metadata['endpointPrefix']] = [\n 'latest' => $metadata['apiVersion'],\n $metadata['apiVersion'] => $metadata['apiVersion'],\n ];\n foreach ($metadata['compatibleApiVersions'] as $compatVersion) {\n $manifest[$metadata['endpointPrefix']][$compatVersion] = $metadata['apiVersion'];\n }\n}\n\n$data = get_code_for_array($manifest);\n$file = __DIR__ . '/../src/data/api-version-manifest.php';\nfile_put_contents($file, $data);\n\necho \"Wrote the following data to {$file}:\\n>>>>>\\n{$data}<<<<<\\n\";\n" }, { "alpha_fraction": 0.6243611574172974, "alphanum_fraction": 0.6252129673957825, "avg_line_length": 26.302326202392578, "blob_id": "67c09214c580cf81d2ca8a9adda9627b23197c27", "content_id": "ec438e84829ff15436d4aa9e236d20e14719fe6c", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1174, "license_type": "permissive", "max_line_length": 85, "num_lines": 43, "path": "/src/Sts/StsClient.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Sts;\n\nuse Aws\\AwsClient;\nuse Aws\\Result;\nuse Aws\\Credentials\\Credentials;\n\n/**\n * This client is used to interact with the **AWS Security Token Service (AWS STS)**.\n */\nclass StsClient extends AwsClient\n{\n public static function getArguments()\n {\n $args = parent::getArguments();\n // STS does not require a region.\n $args['region']['default'] = 'us-east-1';\n\n return $args;\n }\n\n /**\n * Creates credentials from the result of an STS operations\n *\n * @param Result $result Result of an STS operation\n *\n * @return Credentials\n * @throws \\InvalidArgumentException if the result contains no credentials\n */\n public function createCredentials(Result $result)\n {\n if (!$result->hasKey('Credentials')) {\n throw new \\InvalidArgumentException('Result contains no credentials');\n }\n\n return new Credentials(\n $result->getPath('Credentials/AccessKeyId'),\n $result->getPath('Credentials/SecretAccessKey'),\n $result->getPath('Credentials/SessionToken'),\n $result->getPath('Credentials/Expiration')\n );\n }\n}\n" }, { "alpha_fraction": 0.6899622082710266, "alphanum_fraction": 0.6956287026405334, "avg_line_length": 28.648000717163086, "blob_id": "3c8709ccc60ffbee464409bb597118834e110f4a", "content_id": "37ba6130efda4dfb7820e509cac479a733f960e1", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 3710, "license_type": "permissive", "max_line_length": 93, "num_lines": 125, "path": "/docs/index.rst", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "===============\nAWS SDK for PHP\n===============\n\n.. toctree::\n :hidden:\n\n requirements\n installation\n basic-usage\n\n concepts\n configuration\n credentials\n commands\n waiters\n paginators\n faq\n\n service-cloudfront\n service-dynamodb\n feature-dynamodb-session-handler\n service-redshift\n service-s3\n feature-s3-stream-wrapper\n service-sqs\n service-sts\n\n migration-guide\n\nThe **AWS SDK for PHP** enables PHP developers to use\n`Amazon Web Services <http://aws.amazon.com/>`_ from their PHP code, and build\nrobust applications and software using services like Amazon S3, Amazon\nDynamoDB, Amazon Glacier, etc. You can get started in minutes by installing the\nSDK through Composer — by requiring the ``aws/aws-sdk-php`` package — or by\ndownloading the standalone `aws.zip <http://pear.amazonwebservices.com/get/aws.zip>`_\nor `aws.phar <http://pear.amazonwebservices.com/get/aws.phar>`_ files.\n\nExternal links: `API Docs <http://docs.aws.amazon.com/aws-sdk-php/v3/api/>`_\n| `GitHub <https://github.com/aws/aws-sdk-php>`_\n| `Twitter <https://twitter.com/awsforphp>`_\n| `Gitter <https://gitter.im/aws/aws-sdk-php>`_\n| `Blog <http://blogs.aws.amazon.com/php>`_\n| `Forum <https://forums.aws.amazon.com/forum.jspa?forumID=80>`_\n| `Packagist <https://packagist.org/packages/aws/aws-sdk-php>`_\n\n\nGetting Started\n---------------\n\n1. :doc:`requirements`\n2. :doc:`installation`\n3. :doc:`basic-usage`\n\n.. 4. `Sample Project <http://aws.amazon.com/developers/getting-started/php/>`_\n\n\nSDK Details\n-----------\n\n* :doc:`concepts`\n* :doc:`configuration`\n* :doc:`credentials`\n* :doc:`paginators`\n* :doc:`waiters`\n* :doc:`commands`\n* :doc:`faq`\n* `Contributing to the SDK <https://github.com/aws/aws-sdk-php/blob/master/CONTRIBUTING.md>`_\n* `Guzzle Documentation <http://guzzlephp.org>`_\n\n\n.. _supported-services:\n\nSupported Services\n------------------\n\n- :apiref:`Amazon CloudFront | CloudFront`\n - :doc:`service-cloudfront`\n- :apiref:`Amazon CloudWatch | CloudWatch`\n- :apiref:`Amazon DynamoDB | DynamoDb`\n\n - :doc:`service-dynamodb`\n - :doc:`DynamoDB Session Handler <feature-dynamodb-session-handler>`\n\n- :apiref:`Amazon Elastic Compute Cloud (Amazon EC2) | Ec2`\n- :apiref:`Amazon Elastic MapReduce (Amazon EMR) | Emr`\n- :apiref:`Amazon Elastic Transcoder | ElasticTranscoder`\n- :apiref:`Amazon ElastiCache | ElastiCacheClient`\n- :apiref:`Amazon Glacier | Glacier`\n- :apiref:`Amazon Kinesis | Kinesis`\n- :apiref:`Amazon Redshift | Redshift`\n\n - :doc:`service-redshift`\n- :apiref:`Amazon Relational Database Service (Amazon RDS) | Rds`\n\n- :apiref:`Amazon Route 53 | Route53`\n- :apiref:`Amazon Simple Email Service (Amazon SES) | Ses`\n- :apiref:`Amazon Simple Notification Service (Amazon SNS) | Sns`\n- :apiref:`Amazon Simple Queue Service (Amazon SQS) | Sqs`\n\n - :doc:`service-sqs`\n\n- :apiref:`Amazon Simple Storage Service (Amazon S3) | S3`\n\n - :doc:`service-s3`\n - :doc:`Amazon S3 Stream Wrapper <feature-s3-stream-wrapper>`\n\n- :apiref:`Amazon Simple Workflow Service (Amazon SWF) | Swf`\n- :apiref:`Amazon SimpleDB | SimpleDb`\n- :apiref:`Auto Scaling | AutoScaling`\n- :apiref:`AWS CloudFormation | CloudFormation`\n- :apiref:`AWS CloudTrail | CloudTrail`\n- :apiref:`AWS Data Pipeline | DataPipeline`\n- :apiref:`AWS Direct Connect | DirectConnect`\n- :apiref:`AWS Elastic Beanstalk | ElasticBeanstalk`\n- :apiref:`AWS Identity and Access Management (AWS IAM) | Iam`\n- :apiref:`AWS Import/Export | ImportExport`\n- :apiref:`AWS OpsWorks | OpsWorks`\n- :apiref:`AWS Security Token Service (AWS STS) | Sts`\n\n - :doc:`service-sts`\n\n- :apiref:`AWS Storage Gateway | StorageGateway`\n- :apiref:`AWS Support | Support`\n- :apiref:`Elastic Load Balancing | ElasticLoadBalancing`\n" }, { "alpha_fraction": 0.45477619767189026, "alphanum_fraction": 0.45800647139549255, "avg_line_length": 35.420169830322266, "blob_id": "148e5127ef173e68d70370df6e24733fbd987fa0", "content_id": "5eec1c2db4d2e71f5e89a688afa1ddcb8c7e0f29", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4334, "license_type": "permissive", "max_line_length": 76, "num_lines": 119, "path": "/tests/Api/Serializer/RestJsonSerializerTest.php", "repo_name": "Briareos/aws-sdk-php", "src_encoding": "UTF-8", "text": "<?php\nnamespace Aws\\Test\\Api\\Serializer;\n\nuse Aws\\Api\\Service;\nuse GuzzleHttp\\Command\\Command;\nuse Aws\\Api\\Serializer\\RestJsonSerializer;\nuse Aws\\Test\\UsesServiceTrait;\nuse GuzzleHttp\\Client;\nuse GuzzleHttp\\Command\\CommandTransaction;\n\n/**\n * @covers Aws\\Api\\Serializer\\RestJsonSerializer\n */\nclass RestJsonSerializerTest extends \\PHPUnit_Framework_TestCase\n{\n use UsesServiceTrait;\n\n private function getTestService()\n {\n return new Service(function () {\n return [\n 'metadata'=> [\n 'targetPrefix' => 'test',\n 'jsonVersion' => '1.1'\n ],\n 'operations' => [\n 'foo' => [\n 'http' => ['httpMethod' => 'POST'],\n 'input' => ['shape' => 'FooInput'],\n ],\n 'bar' => [\n 'http' => ['httpMethod' => 'POST'],\n 'input' => ['shape' => 'BarInput'],\n ],\n 'baz' => [\n 'http' => ['httpMethod' => 'POST'],\n 'input' => ['shape' => 'BazInput']\n ]\n ],\n 'shapes' => [\n 'FooInput' => [\n 'type' => 'structure',\n 'members' => [\n 'baz' => ['shape' => 'BazShape']\n ]\n ],\n 'BarInput' => [\n 'type' => 'structure',\n 'members' => [\n 'baz' => ['shape' => 'BlobShape']\n ],\n 'payload' => 'baz'\n ],\n 'BazInput' => [\n 'type' => 'structure',\n 'members' => ['baz' => ['shape' => 'FooInput']],\n 'payload' => 'baz'\n ],\n 'BlobShape' => ['type' => 'blob'],\n 'BazShape' => ['type' => 'string']\n ]\n ];\n }, 'service', 'region');\n }\n\n private function getRequest($commandName, $input)\n {\n $http = new Client();\n $service = $this->getTestService();\n $command = new Command($commandName, $input);\n $j = new RestJsonSerializer($service, 'http://foo.com');\n $aws = $this->getMockBuilder('Aws\\AwsClient')\n ->setMethods(['getHttpClient'])\n ->disableOriginalConstructor()\n ->getMock();\n $aws->expects($this->once())\n ->method('getHttpClient')\n ->will($this->returnValue($http));\n $trans = new CommandTransaction($aws, $command);\n\n return $j($trans);\n }\n\n public function testPreparesRequestsWithContentType()\n {\n $request = $this->getRequest('foo', ['baz' => 'bar']);\n $this->assertEquals('POST', $request->getMethod());\n $this->assertEquals('http://foo.com/', $request->getUrl());\n $this->assertTrue($request->hasHeader('User-Agent'));\n $this->assertEquals('{\"baz\":\"bar\"}', (string) $request->getBody());\n $this->assertEquals(\n 'application/x-amz-json-1.1',\n $request->getHeader('Content-Type')\n );\n }\n\n public function testPreparesRequestsWithBlobButNoForcedContentType()\n {\n $request = $this->getRequest('bar', ['baz' => 'bar']);\n $this->assertEquals('POST', $request->getMethod());\n $this->assertEquals('http://foo.com/', $request->getUrl());\n $this->assertTrue($request->hasHeader('User-Agent'));\n $this->assertEquals('bar', (string) $request->getBody());\n $this->assertEquals('', $request->getHeader('Content-Type'));\n }\n\n public function testPreparesRequestsWithStructPayload()\n {\n $request = $this->getRequest('baz', ['baz' => ['baz' => '1234']]);\n $this->assertEquals('POST', $request->getMethod());\n $this->assertEquals('http://foo.com/', $request->getUrl());\n $this->assertTrue($request->hasHeader('User-Agent'));\n $this->assertEquals('{\"baz\":\"1234\"}', (string) $request->getBody());\n $this->assertEquals(\n 'application/x-amz-json-1.1',\n $request->getHeader('Content-Type')\n );\n }\n}\n" } ]
184
piyush6348/learnxinyminutes-pdf
https://github.com/piyush6348/learnxinyminutes-pdf
f43f1f1c57235503fc03f3f5fd34d2c0f28487fd
11072fd1512a8d8cc9de7c1e4c8ed70c42f61a55
92b6edd93497af40a8f1b1a56b60673d6e9f8034
refs/heads/master
2021-01-02T22:48:49.388916
2016-08-27T15:11:03
2016-08-27T15:11:03
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7209580540657043, "alphanum_fraction": 0.7694610953330994, "avg_line_length": 48.117645263671875, "blob_id": "01e3a2a37ac7a9593783220920de12c0a485ece3", "content_id": "28dffe8e806f96939940cb4ea327a68288025331", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1670, "license_type": "no_license", "max_line_length": 320, "num_lines": 34, "path": "/README.md", "repo_name": "piyush6348/learnxinyminutes-pdf", "src_encoding": "UTF-8", "text": "# Learn X in Y minutes - PDF\n\n(**Updated** 27/8/16) [Learn X in Y minutes](http://learnxinyminutes.com) as PDF. Source = https://github.com/adambard/learnxinyminutes-docs\n\n\n## Preview\n![Screenshot](https://cloud.githubusercontent.com/assets/4047597/18028175/063ccd6a-6c95-11e6-9ebf-fba11c516afc.png)\n\n\n## Download\n\n* Downloads are hosted on [GitHub Releases](https://github.com/aviaryan/learnxinyminutes-pdf/releases/tag/v2016.08.27)\n* [learnxinyminutes.pdf](https://github.com/aviaryan/learnxinyminutes-pdf/releases/download/v2016.08.27/learnxinyminutes.pdf) is the all-in-one PDF.\n* The individual PDF files can be found as [release attachments](https://github.com/aviaryan/learnxinyminutes-pdf/releases/tag/v2016.08.27).\n* If you want a zip of all individual PDF's, then download [learnxinyminutes_all.zip](https://github.com/aviaryan/learnxinyminutes-pdf/releases/download/v2016.08.27/learnxinyminutes_all.zip).\n\n\n### Limitations\n\n* `learnxinyminutes.pdf` doesn't include 2 languages; latex and markdown. This is because they caused conflicts while building the pdf (you can guess why). If needed, you can always download their individual pdf's from the [release attachments](https://github.com/aviaryan/learnxinyminutes-pdf/releases/tag/v2016.08.27).\n\n\n### Build Requirements\n\n* Python 3\n* Pandoc\n* Latex\n\n\n### Build Instructions\n\n1. Run `genpdf.py`. It generates the all-in-one pdf and the parsed markdown files. \n2. Run `_genpdf.sh`. It generates the individual pdf-s. Note that this takes the generated files from Python script (in _temp directory) as the input.\n3. To update on GitHub, first create a new release from the web UI. Then run `upload-releases.py`.\n" }, { "alpha_fraction": 0.7072538733482361, "alphanum_fraction": 0.7150259017944336, "avg_line_length": 31.25, "blob_id": "ce4f83a225c58d2ff9d35f7361cae090098e3f6d", "content_id": "07c61a53f6cd5601b99732b34fbff5d82fe263ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 386, "license_type": "no_license", "max_line_length": 110, "num_lines": 12, "path": "/_genpdf.sh", "repo_name": "piyush6348/learnxinyminutes-pdf", "src_encoding": "UTF-8", "text": "mkdir _pdfs;\n#pandoc coffeescript.html.markdown -s -o _pdfs/coffeescript.pdf -V geometry:margin=1in --latex-engine=xelatex;\n#exit 1;\nfor file in _temp/*.html.markdown\ndo\n\tbase=$(basename $file);\n\tlangname=${base//\\.html\\.markdown/};\n\techo \"Making PDF $langname\";\n\tpandoc $file -s -o _pdfs/$langname.pdf -V geometry:margin=1in --latex-engine=xelatex\ndone\n\nmv _pdfs/c++.pdf _pdfs/cpp.pdf;" }, { "alpha_fraction": 0.6470588445663452, "alphanum_fraction": 0.7058823704719543, "avg_line_length": 16, "blob_id": "19f4bc743afddf193fe4b3a93d8c61a3714b31ba", "content_id": "09655f40a3e5658ef7f3efad787f7d3d6ef966e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 17, "license_type": "no_license", "max_line_length": 16, "num_lines": 1, "path": "/requirements.txt", "repo_name": "piyush6348/learnxinyminutes-pdf", "src_encoding": "UTF-8", "text": "github3.py --pre\n" }, { "alpha_fraction": 0.6791641116142273, "alphanum_fraction": 0.6816226243972778, "avg_line_length": 21.929576873779297, "blob_id": "df6d089453e24ced864db8839341e8c5fcc1fddf", "content_id": "8cd7cc2212dc9a5df10c6cc3a7ae8e36e0df9fe6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1627, "license_type": "no_license", "max_line_length": 80, "num_lines": 71, "path": "/upload-releases.py", "repo_name": "piyush6348/learnxinyminutes-pdf", "src_encoding": "UTF-8", "text": "from github3 import login\nimport os\nfrom sys import exit\nimport shutil\n\n# uploads on the latest release . So create a relase first, then run this script\n\nrelease = []\n\ndef upload(file, mime = 'application/pdf'):\n\tname = os.path.basename(file)\n\tfdata = open(file, 'rb').read()\n\tasset = release.upload_asset(mime, name, fdata)\n\treturn asset\n\n\nusername = 'aviaryan'\nrepo = 'learnxinyminutes-pdf'\ntokentxt = open('token.txt', 'r').read()\ngh = login(token = tokentxt)\n\nuser = gh.user(username)\nrepo = gh.repository(username, repo)\nprint(user.name)\n\nfor i in repo.releases():\n\tprint(i)\n\trelease = i\n\tprint(i.tag_name, 'name = ', i.name, i.body, i.id)\n\tbreak\n\n# upload main pdf\nfile = 'learnxinyminutes.pdf'\nprint('Uploading ' + file)\ntry:\n\tupload(file)\nexcept Exception as e:\n\tprint(file, 'upload failed %s' % str(e))\n\texit(1)\n\ncount = 0\n# upload single pdf's\nfor file in os.listdir('_pdfs'):\n\tprint('Uploading ' + file)\n\ttry:\n\t\tupload('_pdfs/' + file)\n\t\tcount += 1\n\texcept:\n\t\tprint('Failed', file)\nprint('Uploaded', count, 'single pdfs')\n\n# upload all pdf\nzipname = 'learnxinyminutes_all'\nprint('Uploading ' + zipname)\nif os.path.isfile(zipname + '.zip'):\n\tos.remove(zipname + '.zip')\nshutil.make_archive(zipname, 'zip', '_pdfs') # the all pdf\ntry:\n\tupload(zipname + '.zip', 'application/zip')\nexcept:\n\tprint('all zip failed')\n\n# release = repo.create_release(version)\n# print(release.edit(body='test release by API'))\n\n# x = \"C:\\\\Users\\\\Avi\\\\Documents\\\\GitHub\\\\learnxinyminutes-pdf\\\\_pdfs\\\\java.pdf\"\n# file = open(x, 'rb').read()\n# mime = 'application/pdf'\n# name = 'java-test.pdf'\n\n# asset = release.upload_asset(mime, name, file)" } ]
4
dbluvstein/cs20-S16-lab03
https://github.com/dbluvstein/cs20-S16-lab03
c5ef278b8c3bedb735f70e3a3009d3fc21470a82
09e71eed7e195d00197935c9ed08c9eb7fedd552
1fc45cd9b7b2843175bfbdb57992cea60d85eb6d
refs/heads/master
2021-01-01T05:15:30.946692
2016-04-21T19:14:04
2016-04-21T19:14:04
56,796,450
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6545454263687134, "alphanum_fraction": 0.7636363506317139, "avg_line_length": 26.5, "blob_id": "7ddd2ef971a0e38735dc335c925bf88baafe9187", "content_id": "d4b1155fcd6d9b45e774cd74d07220169e000642", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 55, "license_type": "no_license", "max_line_length": 37, "num_lines": 2, "path": "/README.md", "repo_name": "dbluvstein/cs20-S16-lab03", "src_encoding": "UTF-8", "text": "# cs20-S16-lab03\nPython code for my CCS CompSci class.\n" }, { "alpha_fraction": 0.5166908502578735, "alphanum_fraction": 0.6052249670028687, "avg_line_length": 14.659090995788574, "blob_id": "4b3f0d2c84cbbea6cf7a79b2375101fb3f30826b", "content_id": "5ee65252870ac27286762e311fe0b021a20be2cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 689, "license_type": "no_license", "max_line_length": 34, "num_lines": 44, "path": "/turtleinitials.py", "repo_name": "dbluvstein/cs20-S16-lab03", "src_encoding": "UTF-8", "text": "import turtle, math, random\n\ndef drawArc(turtle,dy):\n turtle.setheading(0)\n for i in range(21):\n turtle.forward(dy/12)\n turtle.right(9)\n\ndef drawD(d,width1,height1,x1,y1):\n d.up()\n d.goto(x1,y1)\n d.down()\n d.setheading(90)\n d.forward(height1)\n drawArc(d,height1)\n\ndef drawB(b,width2,height2,x2,y2):\n b.up()\n b.goto(x2,y2)\n b.down()\n b.setheading(90)\n b.forward(height1)\n drawArc(b,(height2)/2)\n drawArc(b,(height2)/2)\n\n\nx1 = -100\ny1 = 0\nheight1 = 150\nwidth1 = 50\n\nx2 = 0\ny2 = 0\nheight2 = 150\nwidth2 = 50\n\nd = turtle.Turtle()\nb = turtle.Turtle()\n\ndef go():\n drawD(d,width1,height1,x1,y1)\n drawB(b,width2,height2,x2,y2)\n\ngo()\n" } ]
2
xiaowu5759/search-spider
https://github.com/xiaowu5759/search-spider
7d1f4be0c432e8b79a33312e94bef2b217728667
16c8ba400a70febf3b27d24555d30f03d4f809a7
51d3519a4e7c27cc8f30602636fae0c99720fde7
refs/heads/master
2022-04-19T17:15:23.003570
2020-03-27T08:02:08
2020-03-27T08:02:08
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.3103448152542114, "alphanum_fraction": 0.48275861144065857, "avg_line_length": 16.600000381469727, "blob_id": "1dae59760dad1f6e13e3337274df5e98803f790e", "content_id": "5d84f3d804ccddb8d9978c2da2732872738f1489", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 87, "license_type": "permissive", "max_line_length": 32, "num_lines": 5, "path": "/article-spider/ArticleSpider/tools/__init__.py", "repo_name": "xiaowu5759/search-spider", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n'''\n@createBy : xiaowu \n@date : 2019/11/01 11:16:32\n'''" }, { "alpha_fraction": 0.78125, "alphanum_fraction": 0.78125, "avg_line_length": 9.333333015441895, "blob_id": "48f42cb771497bef6d6ad1c83bcf3f6e187a5e9d", "content_id": "cddb279585064eb0293746b67ffcee1e959a44e3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 46, "license_type": "permissive", "max_line_length": 15, "num_lines": 3, "path": "/README.md", "repo_name": "xiaowu5759/search-spider", "src_encoding": "UTF-8", "text": "# search-spider\n\n利用scrapy框架的爬虫\n\n" }, { "alpha_fraction": 0.6487213969230652, "alphanum_fraction": 0.6554508805274963, "avg_line_length": 43.58000183105469, "blob_id": "2f63dcdc65edc1a93ef679f137ac9b7316edec2a", "content_id": "446fc4ab7ad0b6c080961074a1000ef65c3ded8d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2475, "license_type": "permissive", "max_line_length": 137, "num_lines": 50, "path": "/article-spider/ArticleSpider/spiders/itcodemonkey.py", "repo_name": "xiaowu5759/search-spider", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy.http import Request\nfrom urllib import parse\nfrom datetime import datetime\nfrom scrapy.loader import ItemLoader\n\nfrom ArticleSpider.items import ItcodemonkeyArticleItem, JobBoleArticleItemLoader\nfrom ArticleSpider.util.common import get_md5\n\n# 继承spider\nclass ItcodemonkeySpider(scrapy.Spider):\n name = 'itcodemonkey'\n allowed_domains = ['www.itcodemonkey.com']\n start_urls = ['https://www.itcodemonkey.com/p/153/']\n\n def parse(self, response):\n # 1. 获取文章列表页中的文章url 并交给scrapy下载后解析函数进行具体字段解析\n # 2. 获取下一页的url并交给scrapy进行下载 下载完成后交给parse\n\n # 解析列表页中的所有文章url 并交给scrapy下载后并进行解析\n post_urls = response.css('div.list-boxes > h2 > a::attr(href)').extract()\n for post_url in post_urls:\n # post_url = response.url + post_url\n yield Request(url = parse.urljoin(response.url,post_url), callback=self.parse_detail)\n # print(post_url.extract())\n \n # 提取下一页并交给 scrapy下载\n current_page = response.css('li.active.current > span::text').extract_first(\"\")\n # 直到没有 下一页,爬虫结束\n if(current_page):\n # 空 无法强转\n current_page = int(current_page)\n next_page = '/p/{0}/'.format(current_page+1)\n yield Request(url = parse.urljoin(response.url,next_page), callback = self.parse)\n\n def parse_detail(self, response):\n article_item = ItcodemonkeyArticleItem()\n # 提取文章的具体字段\n item_loader = JobBoleArticleItemLoader(item=ItcodemonkeyArticleItem(),response=response)\n # 针对css选择器\n item_loader.add_css('title','body > div.container.tc-main > div.row > div.span9 > div > h2::text')\n item_loader.add_css('create_time', 'body > div.container.tc-main > div.row > div.span9 > div > div.article-infobox > span::text')\n item_loader.add_css('classify','body > div.container.tc-main > div.row > div.span9 > div > div.article-infobox > span > a::text')\n item_loader.add_css('content', '#article_content')\n # 针对直接取值的情况\n item_loader.add_value('url', response.url)\n item_loader.add_value('url_object_id', get_md5(response.url))\n article_item = item_loader.load_item()\n yield article_item\n" }, { "alpha_fraction": 0.5048543810844421, "alphanum_fraction": 0.6310679316520691, "avg_line_length": 19.700000762939453, "blob_id": "00612838e44d110519d4cc470c086492d798a58e", "content_id": "7a5844c6d9e9dfeb55359c31678c9255ee724a8c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 206, "license_type": "permissive", "max_line_length": 39, "num_lines": 10, "path": "/python_test/regular/regular.py", "repo_name": "xiaowu5759/search-spider", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'xiaowu'\n\nimport re\n\nline = \"x00000000000000000000xxowu5759\"\nregex_str = \".*?(x.*?x).*\"\nmatch_obj = re.match(regex_str, line)\nif match_obj:\n print(match_obj.group(1))" }, { "alpha_fraction": 0.5567282438278198, "alphanum_fraction": 0.559366762638092, "avg_line_length": 24.33333396911621, "blob_id": "cd3f0e8981f3ae94867493e8a5314a8d50746e1f", "content_id": "3c85668e0a935d8bebc7327ac86c43a4ba76416a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 415, "license_type": "permissive", "max_line_length": 40, "num_lines": 15, "path": "/python_test/algorithm/level.py", "repo_name": "xiaowu5759/search-spider", "src_encoding": "UTF-8", "text": "\"\"\"利用队列实现树的广度优先遍历\"\"\"\ndef level_queue(root):\n if root is None:\n return\n my_queue = []\n node = root\n my_queue.append(node)\n # 循环队列\n while my_queue:\n node = my_queue.pop(0)\n print(node.elem)\n if node.lchid is not None:\n my_queue.append(node.lchild)\n if node.rchild is not None:\n my_queue.append(node.rchild)" }, { "alpha_fraction": 0.606918215751648, "alphanum_fraction": 0.6540880799293518, "avg_line_length": 18.9375, "blob_id": "6f395cf59f421cf6b3341526b33be637ed1a191b", "content_id": "4c4647c264dcd54a5450619e4a6733de328dea93", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 326, "license_type": "permissive", "max_line_length": 59, "num_lines": 16, "path": "/article-spider/main.py", "repo_name": "xiaowu5759/search-spider", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n'''\n@createBy : xiaowu \n@date : 2019/09/16 18:22:17\n'''\n\nfrom scrapy.cmdline import execute\n\nimport sys\nimport os\n\n# print(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(os.path.dirname(os.path.abspath(__file__)))\n\n# 调用execute方法\nexecute([\"scrapy\", \"crawl\", \"itcodemonkey\"])" }, { "alpha_fraction": 0.658823549747467, "alphanum_fraction": 0.702786386013031, "avg_line_length": 32.66666793823242, "blob_id": "4b090eca8d3fb23c4ebe2a390b894c65795e455f", "content_id": "5df6c07f4a98e913844bb318984242e03fad1b9e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1731, "license_type": "permissive", "max_line_length": 146, "num_lines": 48, "path": "/article-spider/ArticleSpider/tools/selenium_spider.py", "repo_name": "xiaowu5759/search-spider", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n'''\n@createBy : xiaowu \n@date : 2019/11/01 11:15:22\n'''\n\nfrom selenium import webdriver\nfrom scrapy.selector import Selector\n# 可以设置参数 executable_path = '驱动地址'\nbrowser = webdriver.Chrome()\n# browser.get('https://www.baidu.com')\n\n# print(browser.page_source)\n# t_selector = Selector(text=browser.page_source)\n# t_selector.css('')\n\n# browser.get('https://www.zhihu.com/signin')\n\n# browser.find_element_by_css_selector('div.SignFlow-tabs > div:nth-child(2)').click()\n\n# # 账号\n# browser.find_element_by_css_selector('div.SignFlow-account > div > label > input').send_keys('18895386003')\n# # 密码\n# browser.find_element_by_css_selector('div.SignFlow-password > div > label > input').send_keys('961119101125')\n# # 点击按钮\n# browser.find_element_by_css_selector('div.Card.SignContainer-content > div > form > button').click()\n\n# browser.get('https://www.weibo.com/login.php')\n\n# browser.maximize_window()\n# # 账号\n# browser.find_element_by_css_selector('#loginname').send_keys('18895386003')\n# # 密码\n# browser.find_element_by_css_selector('#pl_login_form > div > div:nth-child(3) > div.info_list.password > div > input').send_keys('961119101125')\n# # 点击登录\n# # 有时候js,页面没有加载完成,点击和查找是失败的\n# import time\n# time.sleep(10)\n# browser.find_element_by_css_selector('#pl_login_form > div > div:nth-child(3) > div.info_list.login_btn > a').click()\n\n# 开源中国博客\nbrowser.get('https://www.oschina.net/blog')\n# 执行js代码\nimport time\ntime.sleep(10)\nfor _ in range(3):\n browser.execute_script('window.scrollTo(0, document.body.scrollHeight); var lenOfPage=document.body.scrollHeight; return lenOfPage;')\n time.sleep(3)" }, { "alpha_fraction": 0.688746988773346, "alphanum_fraction": 0.6903432011604309, "avg_line_length": 25.10416603088379, "blob_id": "d741aa244062dbb8d6e1eff2b6d2dd3fd4efa25e", "content_id": "9bbaecd168166645921a6896912dffd1b46ef83d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1377, "license_type": "permissive", "max_line_length": 71, "num_lines": 48, "path": "/article-spider/ArticleSpider/items.py", "repo_name": "xiaowu5759/search-spider", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Define here the models for your scraped items\n#\n# See documentation in:\n# https://doc.scrapy.org/en/latest/topics/items.html\n\nfrom datetime import datetime\n\nimport scrapy\nfrom scrapy.loader import ItemLoader\nfrom scrapy.loader.processors import MapCompose,TakeFirst\n\nclass ArticlespiderItem(scrapy.Item):\n # define the fields for your item here like:\n # name = scrapy.Field()\n pass\n\ndef add_title(value):\n return value+\"-xiaowu\"\n\n# 时间转换处理\ndef date_convert(value):\n try:\n create_time = datetime.strptime(value, '%Y-%m-%d %H:%M:%S')\n except:\n create_time = datetime.now()\n return create_time\n\n# 自定义ITemLoader\nclass JobBoleArticleItemLoader(ItemLoader):\n # 改写默认的output_processor\n default_output_processor = TakeFirst()\n\nclass ItcodemonkeyArticleItem(scrapy.Item):\n title = scrapy.Field(\n # 代表当item传入值的时候,我们可以对这些值进行一些预处理,MapCompose可以传入任意多个函数\n input_processor = MapCompose(lambda x: x+\"-jobbole\",add_title),\n # title上会添加-jobbole\n )\n create_time = scrapy.Field(\n input_processor=MapCompose(date_convert),\n )\n url = scrapy.Field()\n # url 通过md5 设置成固定长度\n url_object_id = scrapy.Field()\n classify = scrapy.Field()\n content = scrapy.Field()\n" }, { "alpha_fraction": 0.6053639650344849, "alphanum_fraction": 0.6053639650344849, "avg_line_length": 36.42856979370117, "blob_id": "c7f755ae713abc433718f8531013b80edab7d553", "content_id": "2f571fcad70011482ed6f31535473826d04db2f4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 261, "license_type": "permissive", "max_line_length": 47, "num_lines": 7, "path": "/python_test/algorithm/depth.py", "repo_name": "xiaowu5759/search-spider", "src_encoding": "UTF-8", "text": "def depth_tree(tree_node):\n if tree_node is not None:\n print(tree_node._data)\n if tree_node.left is not None:\n return depth_tree(tree_node._left)\n if tree_node.right is not None:\n return depth_tree(tree_node._right)" } ]
9
fmohr/AILibs
https://github.com/fmohr/AILibs
5e73a737587e53b1c9c7e79a1f26ea54668ba808
112538a8a461280b59bff101c3f5d0de27c03d51
a1bbe4d5b3827c5a1e628987f40d4bf454d41131
HEAD
2018-10-15T15:57:35.972151
2018-09-28T14:05:27
2018-09-28T14:05:27
95,635,499
25
29
null
null
null
null
null
[ { "alpha_fraction": 0.7551020383834839, "alphanum_fraction": 0.7551020383834839, "avg_line_length": 17.375, "blob_id": "31eccb102d787d129debbfde51bfc8e6525c355b", "content_id": "62299227d7670b1991039590ea47a2749b60e081", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 147, "license_type": "no_license", "max_line_length": 54, "num_lines": 8, "path": "/JAICore/jaicore-ml/src/jaicore/ml/interfaces/LabeledInstance.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.ml.interfaces;\n\npublic interface LabeledInstance<L> extends Instance {\n\t\n\tpublic void setLabel(L label);\n\t\n\tpublic L getLabel();\n}\n" }, { "alpha_fraction": 0.7331046462059021, "alphanum_fraction": 0.7375643253326416, "avg_line_length": 36.38461685180664, "blob_id": "8dbc60d70882e52dcafc0d212dfb25981cb59e93", "content_id": "141a66d6001c09899c974a096390de6b64753aa5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2915, "license_type": "no_license", "max_line_length": 210, "num_lines": 78, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/bestfirst/BestFirstEpsilon.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.bestfirst;\n\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.PriorityQueue;\nimport java.util.stream.Collectors;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport jaicore.search.algorithms.standard.bestfirst.nodeevaluation.INodeEvaluator;\nimport jaicore.search.model.probleminputs.GeneralEvaluatedTraversalTree;\nimport jaicore.search.model.travesaltree.Node;\n\n/**\n * A* algorithm implementation using the method design pattern.\n *\n * @author Felix Mohr\n */\npublic class BestFirstEpsilon<T, A, W extends Comparable<W>> extends StandardBestFirst<T, A, Double> {\n\t\n\tprivate final static Logger logger = LoggerFactory.getLogger(BestFirstEpsilon.class);\n\n\tprivate final INodeEvaluator<T, W> secondaryNodeEvaluator;\n\tprivate final Map<Node<T,Double>, W> secondaryCache = new HashMap<>();\n\tprivate final OpenList focalBasedOpenList = new OpenList();\n\tprivate final boolean absolute;\n\tprivate final double epsilon;\n\t\n\t@SuppressWarnings(\"serial\")\n\tprivate class OpenList extends PriorityQueue<Node<T,Double>> {\n\t\t\n\t\t@Override\n\t\tpublic Node<T,Double> peek() {\n\t\t\tif (epsilon <= 0 || open.isEmpty())\n\t\t\t\treturn super.peek();\n\t\t\t\n\t\t\t/* build focal list and compute secondary f values for the elements in the list */\n\t\t\tdouble best = super.peek().getInternalLabel();\n\t\t\tdouble threshold = (absolute ? (best >= 0 ? best + epsilon : best - epsilon) : best * (best >= 0 ? 1 + epsilon : 1 - epsilon));\n\t\t\tCollection<Node<T,Double>> focal = super.stream().filter(n -> n.getInternalLabel() <= threshold).collect(Collectors.toList());\n\t\t\tfocal.stream().filter(n -> !secondaryCache.containsKey(n)).forEach(n -> {\n\t\t\t\ttry {\n\t\t\t\t\tsecondaryCache.put(n, secondaryNodeEvaluator.f(n));\n\t\t\t\t} catch (Throwable e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t});\n\t\t\tNode<T, Double> choice = focal.stream().min((p1, p2) -> secondaryCache.get(p1).compareTo(secondaryCache.get(p2))).get();\n\t\t\tlogger.info(\"Best score is {}. Threshold for focal is {}. Choose node with f1 {} and best f2 {}. Size of focal was {}.\", best, threshold, choice.getInternalLabel(), secondaryCache.get(choice), focal.size());\n\t\t\treturn choice;\n\t\t}\n\t}\n\n\t\n\tpublic BestFirstEpsilon(GeneralEvaluatedTraversalTree<T, A, Double> problem, INodeEvaluator<T, W> pSecondaryNodeEvaluator, int epsilon) throws InterruptedException {\n\t\tthis(problem, pSecondaryNodeEvaluator, epsilon, true);\n\t}\n\t\n\tpublic BestFirstEpsilon(GeneralEvaluatedTraversalTree<T, A, Double> problem, INodeEvaluator<T, W> pSecondaryNodeEvaluator, double epsilon, boolean absolute) throws InterruptedException {\n\t\tsuper(problem);\n\t\tthis.secondaryNodeEvaluator = pSecondaryNodeEvaluator;\n\t\tthis.epsilon = epsilon;\n\t\tthis.absolute = absolute;\n\t\t\n\t\t/* overwrite node selector */\n\t\tthis.setOpen(focalBasedOpenList);\n\t}\n\n\tpublic boolean isAbsolute() {\n\t\treturn absolute;\n\t}\n\n\tpublic double getEpsilon() {\n\t\treturn epsilon;\n\t}\n}" }, { "alpha_fraction": 0.6923795938491821, "alphanum_fraction": 0.7068723440170288, "avg_line_length": 34.879310607910156, "blob_id": "0f3d239118ef8630c2c7a35eeac97622aaa47a82", "content_id": "48d682bf9c69634f433bf1ee89dba29463c9abcf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2139, "license_type": "no_license", "max_line_length": 149, "num_lines": 58, "path": "/JAICore/jaicore-ml/src/jaicore/ml/multilabel/evaluators/F1AverageMultilabelEvaluator.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.ml.multilabel.evaluators;\r\n\r\nimport java.util.Collection;\r\nimport java.util.HashSet;\r\nimport java.util.Random;\r\n\r\nimport org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport jaicore.basic.sets.SetUtil;\r\nimport meka.classifiers.multilabel.Evaluation;\r\nimport meka.classifiers.multilabel.MultiLabelClassifier;\r\nimport meka.core.Result;\r\nimport weka.core.Instances;\r\n\r\n@SuppressWarnings(\"serial\")\r\npublic class F1AverageMultilabelEvaluator extends MultilabelEvaluator {\r\n\tprivate static final Logger logger = LoggerFactory.getLogger(F1AverageMultilabelEvaluator.class);\r\n\r\n\tpublic F1AverageMultilabelEvaluator(Random r) {\r\n\t\tsuper(r);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic double loss(MultiLabelClassifier builtClassifier, Instances test) throws Exception {\r\n\t\tResult result = Evaluation.testClassifier(builtClassifier, test);\r\n\t\tint[][] actuals = result.allTrueValues();\r\n\t\tint[][] decisions = result.allPredictions(.5);\r\n\t\tDescriptiveStatistics stats = new DescriptiveStatistics();\r\n\t\tif (actuals.length == 0) {\r\n\t\t\tlogger.error(\"Cannot compute F1 measure, because apparently there are no test instances. In fact, size of test instance set is {}!\", test.size());\r\n\t\t\tthrow new IllegalArgumentException(\"No test data given\");\r\n\t\t}\r\n\t\tint numLabels = actuals[0].length;\r\n\t\tfor (int row = 0; row < actuals.length; row ++) {\r\n\t\t\tCollection<Integer> t = new HashSet<>();\r\n\t\t\tCollection<Integer> p = new HashSet<>();\r\n\t\t\tfor (int col = 0; col < numLabels; col ++) {\r\n\t\t\t\tif (actuals[row][col] == 1)\r\n\t\t\t\t\tt.add(col);\r\n\t\t\t\tif (decisions[row][col] == 1)\r\n\t\t\t\t\tp.add(col);\r\n\t\t\t}\r\n\t\t\tint correctlyClassified = SetUtil.intersection(t, p).size();\r\n\t\t\tint numberOfPredicted = p.size();\r\n\t\t\tint numberOfTrue = t.size();\r\n\t\t\tdouble precision = numberOfPredicted > 0 ? (correctlyClassified * 1f / numberOfPredicted) : 0;\r\n\t\t\tdouble recall = numberOfTrue > 0 ? (correctlyClassified * 1f / numberOfTrue) : 0;\r\n\t\t\tdouble f1 = (2f / (1 / precision + 1 / recall));\r\n\t\t\tdouble f1Error = 100 * (1 - f1);\r\n\t\t\tstats.addValue(f1Error);\r\n\t\t}\r\n\t\treturn stats.getMean();\r\n\t}\r\n\r\n\r\n}\r\n" }, { "alpha_fraction": 0.6339492201805115, "alphanum_fraction": 0.6408776044845581, "avg_line_length": 29.564706802368164, "blob_id": "22b8dca9482e8ce1473718084b6472752f049960", "content_id": "b4c131e12a6f5e91ba426d8bb88c50a441f3a5c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2598, "license_type": "no_license", "max_line_length": 105, "num_lines": 85, "path": "/JAICore/jaicore-processes/src/jaicore/processes/ProcessList.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.processes;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.ArrayList;\nimport java.util.List;\n\n@SuppressWarnings(\"serial\")\npublic class ProcessList extends ArrayList<ProcessInfo> {\n\n\tprivate final long timestamp = System.currentTimeMillis();\n\tprivate final List<Integer> fieldSeparationIndices = new ArrayList<>();\n\n\tpublic static void main(String[] args) throws IOException {\n\t\tnew ProcessList().stream().forEach(p -> System.out.println(p));\n\t}\n\n\tpublic ProcessList() throws IOException {\n\t\tString line;\n\t\tProcess p = ProcessUtil.getProcessListProcess();\n\t\ttry (BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()))) {\n\t\t\tboolean tableInitialized = false;\n\t\t\tint lineNumber = 0;\n\t\t\twhile ((line = input.readLine()) != null) {\n\t\t\t\tswitch (ProcessUtil.getOS()) {\n\t\t\t\tcase WIN: {\n\t\t\t\t\tif (!tableInitialized) {\n\t\t\t\t\t\tif (line.startsWith(\"===\")) {\n\t\t\t\t\t\t\tint offset = 0;\n\t\t\t\t\t\t\tString[] headerLineParts = line.split(\" \");\n\t\t\t\t\t\t\tfor (int i = 0; i < headerLineParts.length; i++) {\n\t\t\t\t\t\t\t\toffset += headerLineParts[i].length();\n\t\t\t\t\t\t\t\tfieldSeparationIndices.add(offset);\n\t\t\t\t\t\t\t\toffset++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttableInitialized = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tList<String> entries = new ArrayList<>();\n\t\t\t\t\t\tint indexFrom = 0;\n\t\t\t\t\t\tint indexTo = 0;\n\t\t\t\t\t\tfor (int i = 0; i < fieldSeparationIndices.size(); i++) {\n\t\t\t\t\t\t\tindexTo = fieldSeparationIndices.get(i);\n\t\t\t\t\t\t\tentries.add(line.substring(indexFrom, indexTo).trim());\n\t\t\t\t\t\t\tindexFrom = indexTo + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tentries.add(line.substring(indexTo).trim());\n\t\t\t\t\t\tthis.add(new ProcessInfo(Integer.parseInt(entries.get(1)), entries.get(0), entries.get(4)));\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase LINUX: {\n\t\t\t\t\tif (lineNumber > 0) {\n\t\t\t\t\t\tString remainingLine = line;\n\t\t\t\t\t\tList<String> entries = new ArrayList<>();\n\t\t\t\t\t\tfor (int i = 0; i < 6; i++) {\n\t\t\t\t\t\t\tint indexOfNextSpace = remainingLine.indexOf(\" \");\n\t\t\t\t\t\t\tif (indexOfNextSpace >= 0) {\n\t\t\t\t\t\t\t\tentries.add(remainingLine.substring(0, indexOfNextSpace));\n\t\t\t\t\t\t\t\tremainingLine = remainingLine.substring(indexOfNextSpace).trim();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tentries.add(remainingLine);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.add(new ProcessInfo(Integer.parseInt(entries.get(1)), entries.get(5), entries.get(4)));\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new UnsupportedOperationException(\"Cannot create process list for OS \" + ProcessUtil.getOS());\n\t\t\t\t}\n\t\t\t\tlineNumber++;\n\t\t\t}\n\t\t} catch (\n\n\t\tIOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tpublic long getTimestamp() {\n\t\treturn timestamp;\n\t}\n}\n" }, { "alpha_fraction": 0.6830732226371765, "alphanum_fraction": 0.6998799443244934, "avg_line_length": 25.766666412353516, "blob_id": "d075ca67bda02a5979559e053274f8f51d97166f", "content_id": "2edf3a093eeb0dbd76ba1db533452a36bb6272df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 833, "license_type": "no_license", "max_line_length": 204, "num_lines": 30, "path": "/JAICore/jaicore-basic/src/jaicore/basic/algorithm/IAlgorithmConfig.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.basic.algorithm;\r\n\r\nimport org.aeonbits.owner.Mutable;\r\n\r\npublic interface IAlgorithmConfig extends Mutable {\r\n\tpublic static final String K_CPUS = \"cpus\";\r\n\tpublic static final String K_MEMORY = \"memory\";\r\n\tpublic static final String K_TIMEOUT = \"timeout\";\r\n\r\n\t/**\r\n\t * @return Number of CPU cores available for parallelization\r\n\t */\r\n\t@Key(K_CPUS)\r\n\t@DefaultValue(\"1\")\r\n\tpublic int cpus();\r\n\r\n\t/**\r\n\t * @return The main memory that is available to be used. This is merely a documentation variable since the true memory must be set over the JVM initialization anyway and cannot be restricted inside of it\r\n\t */\r\n\t@Key(K_MEMORY)\r\n\t@DefaultValue(\"256\")\r\n\tpublic int memory();\r\n\r\n\t/**\r\n\t * @return Overall timeout for the configuration.\r\n\t */\r\n\t@Key(K_TIMEOUT)\r\n\t@DefaultValue(\"1000000000\")\r\n\tpublic int timeout();\r\n}\r\n" }, { "alpha_fraction": 0.7819790840148926, "alphanum_fraction": 0.7819790840148926, "avg_line_length": 30.100000381469727, "blob_id": "ad933ece6cc46c5f970193c6cdd98215abe2e0f3", "content_id": "ec179323e2bd6f49a23280d84f1e2eb8a361940a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1243, "license_type": "no_license", "max_line_length": 113, "num_lines": 40, "path": "/JAICore/jaicore-ml/src/jaicore/ml/metafeatures/NoProbingCharacterizer.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.ml.metafeatures;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\n\nimport org.openml.webapplication.fantail.dc.Characterizer;\nimport org.openml.webapplication.fantail.dc.statistical.Cardinality;\nimport org.openml.webapplication.fantail.dc.statistical.NominalAttDistinctValues;\nimport org.openml.webapplication.fantail.dc.statistical.SimpleMetaFeatures;\nimport org.openml.webapplication.fantail.dc.statistical.Statistical;\n\n/**\n * A Characterizer that applies several characterizers to a data set, but does\n * not use any probing.\n * \n * @author Helena Graf\n *\n */\npublic class NoProbingCharacterizer extends GlobalCharacterizer {\n\n\t/**\n\t * Constructs a new NoProbingCharacterizer. Construction is the same as for the\n\t * {@link ranker.core.metafeatures.GlobalCharacterizer}, except that only Characterizers that do not use probing\n\t * are initialized.\n\t * \n\t * @throws Exception\n\t */\n\tpublic NoProbingCharacterizer() throws Exception {\n\t\tsuper();\n\t}\n\n\t@Override\n\tprotected void initializeCharacterizers() {\n\t\tCharacterizer[] characterizerArray = { new SimpleMetaFeatures(), new Statistical(),\n\t\t\t\tnew NominalAttDistinctValues(), new Cardinality() };\n\n\t\tcharacterizers = new ArrayList<>(Arrays.asList(characterizerArray));\n\t}\n\n}" }, { "alpha_fraction": 0.5666280388832092, "alphanum_fraction": 0.6037079691886902, "avg_line_length": 20.30864143371582, "blob_id": "c27e4870d5dddab1e732d35fc1f3669851942d8d", "content_id": "5f34f9c17cef4e312df6ec2b60e17edb7f685728", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1726, "license_type": "no_license", "max_line_length": 90, "num_lines": 81, "path": "/JAICore/jaicore-logic/src/jaicore/logic/fol/algorithms/resolution/ResolutionPair.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.logic.fol.algorithms.resolution;\n\nimport jaicore.logic.fol.structure.Clause;\nimport jaicore.logic.fol.structure.Literal;\n\npublic class ResolutionPair {\n\tprivate Clause c1, c2;\n\tprivate Literal l1, l2;\n\n\tpublic ResolutionPair(Clause c1, Clause c2, Literal l1, Literal l2) {\n\t\tsuper();\n\t\tthis.c1 = c1;\n\t\tthis.c2 = c2;\n\t\tthis.l1 = l1;\n\t\tthis.l2 = l2;\n\t}\n\n\tpublic Clause getC1() {\n\t\treturn c1;\n\t}\n\n\tpublic Clause getC2() {\n\t\treturn c2;\n\t}\n\n\tpublic Literal getL1() {\n\t\treturn l1;\n\t}\n\n\tpublic Literal getL2() {\n\t\treturn l2;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((c1 == null) ? 0 : c1.hashCode());\n\t\tresult = prime * result + ((c2 == null) ? 0 : c2.hashCode());\n\t\tresult = prime * result + ((l1 == null) ? 0 : l1.hashCode());\n\t\tresult = prime * result + ((l2 == null) ? 0 : l2.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tResolutionPair other = (ResolutionPair) obj;\n\t\tif (c1 == null) {\n\t\t\tif (other.c1 != null)\n\t\t\t\treturn false;\n\t\t} else if (!c1.equals(other.c1))\n\t\t\treturn false;\n\t\tif (c2 == null) {\n\t\t\tif (other.c2 != null)\n\t\t\t\treturn false;\n\t\t} else if (!c2.equals(other.c2))\n\t\t\treturn false;\n\t\tif (l1 == null) {\n\t\t\tif (other.l1 != null)\n\t\t\t\treturn false;\n\t\t} else if (!l1.equals(other.l1))\n\t\t\treturn false;\n\t\tif (l2 == null) {\n\t\t\tif (other.l2 != null)\n\t\t\t\treturn false;\n\t\t} else if (!l2.equals(other.l2))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"PL1ResolutionPair [c1=\" + c1 + \", c2=\" + c2 + \", l1=\" + l1 + \", l2=\" + l2 + \"]\";\n\t}\n}\n" }, { "alpha_fraction": 0.7572815418243408, "alphanum_fraction": 0.7864077687263489, "avg_line_length": 18.600000381469727, "blob_id": "202bced8dcfee79e21cb8bc39a1ed74a3e283bf5", "content_id": "aa9bdb2426de720c3288fe3469d6ef25053f4122", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 103, "license_type": "no_license", "max_line_length": 42, "num_lines": 5, "path": "/softwareconfiguration/mlplan/src/de/upb/crc901/mlplan/multiclass/MultiClassPerformanceMeasure.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package de.upb.crc901.mlplan.multiclass;\r\n\r\npublic enum MultiClassPerformanceMeasure {\r\n\tERRORRATE\r\n}\r\n" }, { "alpha_fraction": 0.807674765586853, "alphanum_fraction": 0.807674765586853, "avg_line_length": 34.88524627685547, "blob_id": "ad1e7226419b77c05f269e1d00875baad263d855", "content_id": "68dbf2f9eea7e4316b8948ddb9905b5ad5f5544e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2189, "license_type": "no_license", "max_line_length": 136, "num_lines": 61, "path": "/JAICore/jaicore-planning/src/jaicore/planning/graphgenerators/strips/forward/StripsForwardPlanningGraphGenerator.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.graphgenerators.strips.forward;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport jaicore.logic.fol.structure.Monom;\nimport jaicore.planning.model.core.PlannerUtil;\nimport jaicore.planning.model.strips.StripsAction;\nimport jaicore.planning.model.strips.StripsPlanningDomain;\nimport jaicore.planning.model.strips.StripsPlanningProblem;\nimport jaicore.search.core.interfaces.GraphGenerator;\nimport jaicore.search.model.travesaltree.NodeExpansionDescription;\nimport jaicore.search.model.travesaltree.NodeType;\nimport jaicore.search.structure.graphgenerator.NodeGoalTester;\nimport jaicore.search.structure.graphgenerator.SingleRootGenerator;\nimport jaicore.search.structure.graphgenerator.SuccessorGenerator;\n\npublic class StripsForwardPlanningGraphGenerator implements GraphGenerator<StripsForwardPlanningNode,String> {\n\n\tprivate final StripsPlanningProblem problem;\n\t\t\n\tpublic StripsForwardPlanningGraphGenerator(StripsPlanningProblem problem) {\n\t\tthis.problem = problem;\n\t}\n\n\t@Override\n\tpublic SingleRootGenerator<StripsForwardPlanningNode> getRootGenerator() {\n\t\treturn () -> new StripsForwardPlanningNode(problem.getInitState(), null);\n\t}\n\n\t@Override\n\tpublic SuccessorGenerator<StripsForwardPlanningNode,String> getSuccessorGenerator() {\n\t\treturn l -> {\n\t\t\tList<NodeExpansionDescription<StripsForwardPlanningNode,String>> successors = new ArrayList<>();\n\t\t\tMonom state = l.getState();\n\t\t\tfor (StripsAction action : PlannerUtil.getApplicableActionsInState(state, (StripsPlanningDomain)problem.getDomain())) {\n\t\t\t\tMonom successorState = new Monom(state);\n\t\t\t\tsuccessorState.removeAll(action.getDeleteList());\n\t\t\t\tsuccessorState.addAll(action.getAddList());\n\t\t\t\tsuccessors.add(new NodeExpansionDescription<>(l, new StripsForwardPlanningNode(successorState, action), \"edge label\", NodeType.OR));\n\t\t\t}\n\t\t\treturn successors;\n\t\t};\n\t}\n\n\t@Override\n\tpublic NodeGoalTester<StripsForwardPlanningNode> getGoalTester() {\n\t\treturn l -> l.getState().containsAll(problem.getGoalState());\n\t}\n\n\t@Override\n\tpublic boolean isSelfContained() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic void setNodeNumbering(boolean nodenumbering) {\n\t\t// TODO Auto-generated method stub\n\t\t\n\t}\n}\n" }, { "alpha_fraction": 0.7041102051734924, "alphanum_fraction": 0.7053623795509338, "avg_line_length": 28.513044357299805, "blob_id": "ea14386de78bd9bfc599dcc0afb882fa71f3e08f", "content_id": "f777d661e91b08325313fdd983d73aa9d419b7f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 13576, "license_type": "no_license", "max_line_length": 134, "num_lines": 460, "path": "/JAICore/jaicore-graphvisualizer/src/jaicore/graphvisualizer/gui/Recorder.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.graphvisualizer.gui;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.SerializationFeature;\nimport com.google.common.eventbus.EventBus;\nimport com.google.common.eventbus.Subscribe;\n\nimport jaicore.graph.IGraphAlgorithm;\nimport jaicore.graphvisualizer.events.controlEvents.ControlEvent;\nimport jaicore.graphvisualizer.events.controlEvents.FileEvent;\nimport jaicore.graphvisualizer.events.controlEvents.NodePushed;\nimport jaicore.graphvisualizer.events.controlEvents.ResetEvent;\nimport jaicore.graphvisualizer.events.controlEvents.StepEvent;\nimport jaicore.graphvisualizer.events.graphEvents.GraphEvent;\nimport jaicore.graphvisualizer.events.graphEvents.GraphInitializedEvent;\nimport jaicore.graphvisualizer.events.graphEvents.NodeReachedEvent;\nimport jaicore.graphvisualizer.events.graphEvents.NodeRemovedEvent;\nimport jaicore.graphvisualizer.events.graphEvents.NodeTypeSwitchEvent;\nimport jaicore.graphvisualizer.events.misc.AddSupplierEvent;\nimport jaicore.graphvisualizer.events.misc.InfoEvent;\nimport jaicore.graphvisualizer.gui.dataSupplier.ISupplier;\nimport jaicore.graphvisualizer.gui.dataSupplier.ReconstructionDataSupplier;\n\n/**\n * A recorder class, which is used to record GraphEvents. These graphevents are\n * usually created by a search-algorithm. If is possible to store the recorded\n * events in a file and later load them from one. The recorder is controlled by\n * controll-events.\n *\n * @author jkoepe\n */\npublic class Recorder<V,E> {\n\n// Algorithm to listen to\n\tprivate IGraphAlgorithm<?,?,V,E> algorithm;\n\n// List for storing the events\n\tprivate List<Object> receivedEvents;\n\tprivate List<Long> receivingTimes;\n\tprivate long firstEventTime;\n\n// Index to know where in the replay the recorder is\n\tprivate int index;\n\n// EventBuses\n\tprivate EventBus replayBus;\n\tprivate EventBus infoBus;\n\n// Nodemap to store types of nodes\n\tprivate Map<Object, List> nodeMap;\n\n// List with every datasupplier\n\tList<ISupplier> supplier;\n\n\t/**\n\t * A constructor for an empty recorder. The empty recorder does not listen to an\n\t * algorithm but it can load a replay.\n\t */\n\tpublic Recorder() {\n\t\tthis(null);\n\t}\n\n\t/**\n\t * Creates a recorder which listens to an algorithm.\n\t * \n\t * @param algorithm The algorithm from which the reocrder receives the events.\n\t */\n\tpublic Recorder(IGraphAlgorithm<?, ?, V, E> algorithm) {\n\t\tif (algorithm != null)\n\t\t\talgorithm.registerListener(this);\n\n\t\tthis.algorithm = algorithm;\n\n\t\t// initializing variables\n\n\t\tthis.index = 0;\n\n\t\tthis.receivedEvents = new ArrayList<>();\n\t\tthis.receivingTimes = new ArrayList<>();\n\t\tthis.replayBus = new EventBus();\n\t\tthis.infoBus = new EventBus();\n\n\t\tthis.nodeMap = new HashMap<>();\n\t\tsupplier = new ArrayList<>();\n\t}\n\n\t/**\n\t * Register a listener to the replay-Eventbus to receive the graphevents, that\n\t * are outgoing of the recorder.\n\t * \n\t * @param listener The listener, which is going to receive the graph-Events.\n\t */\n\tpublic void registerReplayListener(Object listener) {\n\t\tthis.replayBus.register(listener);\n\t}\n\n\t/**\n\t * Register a listener to the info-Eventbus to receive general information of\n\t * the state of the replay and recorder. Such information are for example the\n\t * number of received events.\n\t * \n\t * @param listener The listener, which is going to receive the Info-Events.\n\t *\n\t */\n\tpublic void registerInfoListener(Object listener) {\n\t\tthis.infoBus.register(listener);\n\t}\n\n\t/**\n\t * This method is used to receive GraphEvents\n\t * \n\t * @param event\n\t */\n\t@Subscribe\n\tpublic void receiveGraphEvent(GraphEvent event) {\n\n\t\t// receive event and save the time\n\t\tthis.receivedEvents.add(event);\n\t\tlong receiveTime = System.currentTimeMillis();\n\n\t\t// check if it is the first event\n\t\tif (firstEventTime == 0)\n\t\t\tfirstEventTime = receiveTime;\n\n\t\t// compute the absolute time of the event in relation to the first event\n\t\tlong eventTime = receiveTime - firstEventTime;\n\t\treceivingTimes.add(eventTime);\n\t\tthis.infoBus.post(new InfoEvent(receivedEvents.size(), eventTime, 0));\n\n\t}\n\n\t/**\n\t * Receive a control event and make the appropiate action\n\t * \n\t * @param event\n\t */\n\t@Subscribe\n\tpublic void receiveControlEvent(ControlEvent event) {\n\t\tif (event instanceof StepEvent) {\n\t\t\tif (((StepEvent) event).forward())\n\t\t\t\tforward(((StepEvent) event).getSteps());\n\t\t\telse\n\t\t\t\tbackward(((StepEvent) event).getSteps());\n\t\t}\n\t\tif (event instanceof ResetEvent)\n\t\t\treset();\n\t\tif (event instanceof FileEvent) {\n\t\t\tif (((FileEvent) event).isLoad())\n\t\t\t\tthis.load(((FileEvent) event).getFile());\n\t\t\telse\n\t\t\t\tthis.save(((FileEvent) event).getFile());\n\t\t}\n\t}\n\n\t/**\n\t * Goes the number of steps forward in the graph. Usually the index + steps do\n\t * not get higher the number of received Events. The exeption is when there is\n\t * only one step to do and the index is equal to the number of received Events.\n\t * In this case the algorithm is triggered.\n\t *\n\t * @param steps The number of steps to do.\n\t */\n\tprivate void forward(int steps) {\n\t\tif (this.index == this.receivedEvents.size())\n\t\t\tif (this.algorithm.hasNext())\n\t\t\t\tthis.algorithm.next();\n\t\twhile (steps != 0) {\n\t\t\tif (this.index < this.receivedEvents.size()) {\n\t\t\t\tObject event = this.receivedEvents.get(index);\n\t\t\t\tthis.replayBus.post(event);\n\n\t\t\t\tthis.addType(event);\n\t\t\t\tindex++;\n\t\t\t\tif (this.index == this.receivedEvents.size())\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tsteps--;\n\t\t}\n\t}\n\n\t/**\n\t * Go backward the number of steps which are given as a paramter\n\t * \n\t * @param steps The steps to go forward.\n\t */\n\tprivate void backward(int steps) {\n\t\tif (index == 0)\n\t\t\treturn;\n\t\twhile (index > 0 && steps != 0) {\n\t\t\tindex--;\n\t\t\tthis.replayBus.post(counterEvent(receivedEvents.get(index)));\n\t\t\tsteps--;\n\t\t}\n\t}\n\n\t/**\n\t * Creates a counterevent to the event which was given. Currently the events\n\t * which can be countered are most of the graphevents\n\t * \n\t * @param event The event to which a counter event should be created\n\t * @return The counter event\n\t */\n\tpublic Object counterEvent(Object event) {\n\t\tObject counter = null;\n\n\t\tswitch (event.getClass().getSimpleName()) {\n//\t\t\tcounter for a GraphInitializedEvent\n\t\tcase \"GraphInitializedEvent\":\n\t\t\t// just for completion\n\t\t\tcounter = null;\n\t\t\tbreak;\n\n//\t\t\t\tcounter for a nodetypeswitchevent\n\t\tcase \"NodeTypeSwitchEvent\":\n\t\t\tNodeTypeSwitchEvent nodeTypeSwitchEvent = (NodeTypeSwitchEvent) event;\n\t\t\tList<String> typeList = nodeMap.get(nodeTypeSwitchEvent.getNode());\n\t\t\ttypeList.remove(typeList.size() - 1);\n\t\t\tcounter = new NodeTypeSwitchEvent(nodeTypeSwitchEvent.getNode(), typeList.get(typeList.size() - 1));\n\t\t\tbreak;\n\n//\t\t\t\tcounter for a nodereached event\n\t\tcase \"NodeReachedEvent\":\n\t\t\tNodeReachedEvent nodeReachedEvent = (NodeReachedEvent) event;\n\t\t\tcounter = new NodeRemovedEvent(nodeReachedEvent.getNode());\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tSystem.out.println(\"not an allowed event\");\n\t\t\tbreak;\n\t\t}\n\t\treturn counter;\n\t}\n\n\t/**\n\t * Adds the type of a node to the typelist of this node\n\t * \n\t * @param event The event which contains the node\n\t */\n\tprivate void addType(Object event) {\n\t\tList<String> types;\n// switch the event corresponding to the current event to get the right type of the node\n\t\tswitch (event.getClass().getSimpleName()) {\n\t\tcase \"GraphInitializedEvent\":\n\t\t\tGraphInitializedEvent initializedEvent = (GraphInitializedEvent) event;\n\t\t\ttypes = new ArrayList();\n\t\t\ttypes.add(\"root\");\n\t\t\tthis.nodeMap.put(initializedEvent.getRoot(), types);\n\t\t\tbreak;\n\n\t\tcase \"NodeTypeSwitchEvent\":\n\t\t\tNodeTypeSwitchEvent nodeTypeSwitchEvent = (NodeTypeSwitchEvent) event;\n\t\t\tthis.nodeMap.get(nodeTypeSwitchEvent.getNode()).add(nodeTypeSwitchEvent.getType());\n\t\t\tbreak;\n\n\t\tcase \"NodeReachedEvent\":\n\t\t\tNodeReachedEvent nodeReachedEvent = (NodeReachedEvent) event;\n\t\t\ttypes = new ArrayList<>();\n\t\t\ttypes.add(nodeReachedEvent.getType());\n\t\t\tthis.nodeMap.put(nodeReachedEvent.getNode(), types);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tSystem.out.println(\"not an allowed event\");\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t/**\n\t * Resets the recorder. To do this only the current nodemap and the index a\n\t * clear or set to 0.\n\t */\n\tprivate void reset() {\n\t\tthis.index = 0;\n\t\tnodeMap.clear();\n\t}\n\n\t/**\n\t * Adds a new Datasupplier to the recorder. The datasupplier it self is\n\t * registered at the replaybus to get graphevents from the recorder.\n\t * \n\t * @param iSupplier\n\t */\n\tpublic void addDataSupplier(ISupplier iSupplier) {\n\t\tthis.registerReplayListener(iSupplier);\n\t\tthis.supplier.add(iSupplier);\n\t}\n\n\t/**\n\t * Posts every known DataSupplier as an addSupplierevent on the InfoBus\n\t */\n\tpublic void getSupplier() {\n\t\tfor (ISupplier s : supplier)\n\t\t\tthis.infoBus.post(new AddSupplierEvent(s));\n\t}\n\n\t/**\n\t * Receive a nodePushedEvent and expand the node, does not matter where the\n\t * search currently is\n\t */\n\t@Subscribe\n\tpublic void receiveNodePushedEvent(NodePushed event) {\n\t\t// TODO node pushed\n\t\tif (this.index == this.receivedEvents.size()) {\n\t\t\tObject node = event.getNode();\n// if (this.algorithm instanceof IControllableGraphAlgorithm) {\n// try {\n// ((IControllableGraphAlgorithm) this.algorithm).step(node);\n//\n// } catch (Exception e){\n// System.out.println(\"test2\");\n// }\n// }\n\t\t}\n\t}\n\n\t/**\n\t * Saves the Events in a file\n\t *\n\t * @param file The file to which the events are stored.\n\t */\n\tprivate void save(File file) {\n\t\tObjectMapper mapper = new ObjectMapper();\n\n\t\tmapper.enable(SerializationFeature.INDENT_OUTPUT);\n\t\ttry {\n\t\t\tList mapperList = new ArrayList();\n\n\t\t\tList<LinkedHashMap<Long, Object>> saveList = new ArrayList();\n\n\t\t\tfor (int i = 0; i < receivedEvents.size(); i++) {\n\t\t\t\tObject event = receivedEvents.get(i);\n\t\t\t\tLinkedHashMap<Long, Object> timeToEvent = new LinkedHashMap();\n\t\t\t\tint code = 0;\n\n\t\t\t\t// Maps times to the hashcodes of the events\n\t\t\t\tswitch (event.getClass().getSimpleName()) {\n\t\t\t\tcase \"GraphInitializedEvent\":\n\t\t\t\t\tGraphInitializedEvent graphInitializedEvent = (GraphInitializedEvent) event;\n\t\t\t\t\tcode = graphInitializedEvent.getRoot().hashCode();\n\t\t\t\t\ttimeToEvent.put(receivingTimes.get(i), new GraphInitializedEvent(code));\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase \"NodeTypeSwitchEvent\":\n\t\t\t\t\tNodeTypeSwitchEvent nodeTypeSwitchEvent = (NodeTypeSwitchEvent) event;\n\t\t\t\t\tcode = nodeTypeSwitchEvent.getNode().hashCode();\n\n\t\t\t\t\ttimeToEvent.put(receivingTimes.get(i),\n\t\t\t\t\t\t\tnew NodeTypeSwitchEvent(code, nodeTypeSwitchEvent.getType()));\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase \"NodeReachedEvent\":\n\t\t\t\t\tNodeReachedEvent nodeReachedEvent = (NodeReachedEvent) event;\n\t\t\t\t\tcode = nodeReachedEvent.getNode().hashCode();\n\t\t\t\t\ttimeToEvent.put(receivingTimes.get(i), new NodeReachedEvent(nodeReachedEvent.getParent().hashCode(),\n\t\t\t\t\t\t\tcode, nodeReachedEvent.getType()));\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tSystem.out.println(\"not an allowed event\");\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tsaveList.add(timeToEvent);\n\t\t\t}\n//\t\t\tadd the serialized supplier to a list which gets saved\n\t\t\tmapperList.add(saveList);\n\t\t\tHashSet<JsonNode> supplierHashSet = new HashSet<>();\n\n\t\t\tsupplier.stream().forEach(supplier -> {\n\t\t\t\tsupplierHashSet.add(supplier.getSerialization());\n\t\t\t});\n\n\t\t\tmapperList.add(supplierHashSet);\n\n\t\t\tmapper.writeValue(file, mapperList);\n\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t}\n\n\t/**\n\t * Load events from a file\n\t * \n\t * @param file\n\t */\n\tprivate void load(File file) {\n\n\t\t// clear existing events\n\t\tthis.receivedEvents.clear();\n\t\tthis.receivingTimes.clear();\n\n\t\tthis.reset();\n\n\t\tObjectMapper mapper = new ObjectMapper();\n\n\t\ttry {\n\t\t\tList mapperList = mapper.readValue(file,\n\t\t\t\t\tmapper.getTypeFactory().constructCollectionType(List.class, Object.class));\n\t\t\tArrayList eventList = (ArrayList) mapperList.get(0);\n//\t\t\tcreate the events out of the stored ones. In the newly loaded events the hashcode of the nodes of the old ones are the whole node\n\t\t\teventList.stream().forEach(n -> {\n\t\t\t\tLinkedHashMap map = (LinkedHashMap) n;\n\t\t\t\tmap.keySet().stream().forEach(time -> receivingTimes.add(Long.parseLong((String) time)));\n\t\t\t\tmap.values().stream().forEach(v -> {\n\t\t\t\t\tLinkedHashMap eventMap = (LinkedHashMap) v;\n\n\t\t\t\t\tint node;\n\t\t\t\t\tObject event;\n\t\t\t\t\tswitch (eventMap.get(\"name\").toString()) {\n\t\t\t\t\tcase \"GraphInitializedEvent\":\n\t\t\t\t\t\tint hashCode = (int) eventMap.get(\"root\");\n\t\t\t\t\t\tevent = new GraphInitializedEvent(Integer.parseInt(String.valueOf(eventMap.get(\"root\"))));\n\t\t\t\t\t\tSystem.out.println(hashCode);\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"NodeTypeSwitchEvent\":\n\t\t\t\t\t\tnode = Integer.parseInt(String.valueOf(eventMap.get(\"node\")));\n\t\t\t\t\t\tevent = new NodeTypeSwitchEvent(node, eventMap.get(\"type\").toString());\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"NodeReachedEvent\":\n\t\t\t\t\t\tint parent = Integer.parseInt(String.valueOf(eventMap.get(\"parent\")));\n\t\t\t\t\t\tnode = Integer.parseInt(String.valueOf(eventMap.get(\"node\")));\n\t\t\t\t\t\tevent = new NodeReachedEvent(parent, node, eventMap.get(\"type\").toString());\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tevent = null;\n\n\t\t\t\t\t}\n\t\t\t\t\tif (event != null)\n\t\t\t\t\t\tthis.receiveGraphEvent((GraphEvent) event);\n\t\t\t\t});\n\t\t\t});\n// create the supplier if possible\n\t\t\tmapperList.stream().filter(o -> mapperList.indexOf(o) != 0).forEach(o -> {\n\t\t\t\tArrayList m = (ArrayList) o;\n\t\t\t\tLinkedHashMap map = (LinkedHashMap) m.get(0);\n\t\t\t\tReconstructionDataSupplier supplier = new ReconstructionDataSupplier(map);\n\t\t\t\tthis.addDataSupplier(supplier);\n\t\t\t});\n\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t}\n}\n" }, { "alpha_fraction": 0.7405784130096436, "alphanum_fraction": 0.7405784130096436, "avg_line_length": 33.65625, "blob_id": "c4ac915603c76a0972d6cf8d4ebb103513e9529e", "content_id": "23b5fb229124086f71b4d0e12dae9e34312ae3f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1141, "license_type": "no_license", "max_line_length": 112, "num_lines": 32, "path": "/JAICore/jaicore-search/src/jaicore/search/model/probleminputs/GeneralEvaluatedTraversalTree.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.model.probleminputs;\r\n\r\nimport jaicore.search.algorithms.standard.bestfirst.nodeevaluation.INodeEvaluator;\r\nimport jaicore.search.core.interfaces.GraphGenerator;\r\n\r\n/**\r\n * Many algorithms such as best first and A* use a traversal tree to browse the underlying\r\n * graph. Each node in this tree corresponds to a node in the original graph but has only\r\n * one predecessor, which may be updated over time.\r\n * \r\n * The underlying class Node<T,V> implicitly defines a back pointer PATH from the node to\r\n * the root. Therefore, evaluating a node of this class equals evaluating a path in the\r\n * original graph.\r\n * \r\n * @author fmohr\r\n *\r\n * @param <N>\r\n * @param <A>\r\n * @param <V>\r\n */\r\npublic class GeneralEvaluatedTraversalTree<N, A, V extends Comparable<V>> extends GraphSearchInput<N, A> {\r\n\tprivate final INodeEvaluator<N, V> nodeEvaluator;\r\n\r\n\tpublic GeneralEvaluatedTraversalTree(GraphGenerator<N, A> graphGenerator, INodeEvaluator<N, V> nodeEvaluator) {\r\n\t\tsuper(graphGenerator);\r\n\t\tthis.nodeEvaluator = nodeEvaluator;\r\n\t}\r\n\r\n\tpublic INodeEvaluator<N, V> getNodeEvaluator() {\r\n\t\treturn nodeEvaluator;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7373737096786499, "alphanum_fraction": 0.7373737096786499, "avg_line_length": 27.700000762939453, "blob_id": "18cd2e1a616ca931c801956a1e0a7e9c19d40de7", "content_id": "56163f1317fb0b1ea9524e7f84c4fce98dda4f13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1485, "license_type": "no_license", "max_line_length": 91, "num_lines": 50, "path": "/JAICore/jaicore-experiments/examples/mlexample/IExampleMCCConfig.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package mlexample;\r\n\r\nimport java.io.File;\r\nimport java.util.List;\r\n\r\nimport org.aeonbits.owner.Config.Sources;\r\n\r\nimport jaicore.experiments.IExperimentSetConfig;\r\n\r\n/**\r\n * In fact, this config is an exact copy of IMultiClassClassificationExperimentConfig,\r\n * which cannot be used here to avoid cyclic dependencies.\r\n * Typically, in this case, you just would extend IMultiClassClassificationExperimentConfig\r\n * and leave the interface (mostly) empty except that you define the URL for the file.\r\n * \r\n * \r\n * @author fmohr\r\n *\r\n */\r\n@Sources({ \"file:./examples/mlexample/setup.properties\" })\r\npublic interface IExampleMCCConfig extends IExperimentSetConfig {\r\n\tpublic static final String DATASETS = \"datasets\";\r\n\tpublic static final String ALGORITHMS = \"algorithms\";\r\n\tpublic static final String ALGORITHMMODES = \"algorithmmodes\";\r\n\tpublic static final String SEEDS = \"seeds\";\r\n\tpublic static final String TIMEOUTS_IN_SECONDS = \"timeouts\";\r\n\tpublic static final String MEASURES = \"measures\";\r\n\tpublic static final String datasetFolder = \"datasetfolder\";\r\n\t\r\n\t@Key(DATASETS)\r\n\tpublic List<String> getDatasets();\r\n\t\r\n\t@Key(ALGORITHMS)\r\n\tpublic List<String> getAlgorithms();\r\n\t\r\n\t@Key(ALGORITHMMODES)\r\n\tpublic List<String> getAlgorithmModes();\r\n\t\r\n\t@Key(SEEDS)\r\n\tpublic List<String> getSeeds();\r\n\t\r\n\t@Key(TIMEOUTS_IN_SECONDS)\r\n\tpublic List<String> getTimeouts();\r\n\t\r\n\t@Key(MEASURES)\r\n\tpublic List<String> getMeasures();\r\n\t\r\n\t@Key(datasetFolder)\r\n\tpublic File getDatasetFolder();\r\n}\r\n" }, { "alpha_fraction": 0.6854512095451355, "alphanum_fraction": 0.6861878633499146, "avg_line_length": 26.149999618530273, "blob_id": "54ef0a254af3949347567c8b088ffbc9119478bc", "content_id": "8405b4e2545c522551c7442caeae72d49d366f02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2715, "license_type": "no_license", "max_line_length": 91, "num_lines": 100, "path": "/JAICore/jaicore-logic/src/jaicore/logic/fol/structure/InterpretedLiteral.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.logic.fol.structure;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n@SuppressWarnings(\"serial\")\npublic class InterpretedLiteral extends Literal {\n\tprivate final static Logger logger = LoggerFactory.getLogger(InterpretedLiteral.class);\n\n\t/**\n\t * Copy constructor for an existing literal under giving mapping.\n\t * \n\t * @param l\n\t * Literal to be copied\n\t * @param map\n\t * Mapping for projecting existing literal to a new literal.\n\t */\n\tpublic InterpretedLiteral(Literal l, Map<VariableParam, ? extends LiteralParam> map) {\n\t\tsuper(l, map);\n\t}\n\n\t/**\n\t * Creates a monadic literal (with only one parameter).\n\t * \n\t * @param property\n\t * The property defined by this literal.\n\t * @param parameter\n\t * The parameter of this literal.\n\t */\n\tpublic InterpretedLiteral(String property, LiteralParam parameter) {\n\t\tsuper(property, parameter);\n\t}\n\n\t/**\n\t * Creates a literal with a list of parameters.\n\t * \n\t * @param property\n\t * The property defined by this literal.\n\t * @param parameter\n\t * The parameters of this literal defined as a list.\n\t */\n\tpublic InterpretedLiteral(String property, List<LiteralParam> parameters) {\n\t\tsuper(property, parameters);\n\t}\n\n\t/**\n\t * Protected helper constructor. Ensure the literal gets parameters!!\n\t */\n\tpublic InterpretedLiteral(String property) {\n\t\tsuper(property);\n\t}\n\n\tpublic InterpretedLiteral(String predicateName, List<LiteralParam> params, boolean b) {\n\t\tsuper(predicateName, params, b);\n\t}\n\n\t@Override\n\tpublic Literal clone() {\n\t\treturn new InterpretedLiteral(this.getProperty(), this.getParameters());\n\t}\n\n\t/**\n\t * Creates a copy of this literal on which the given parameter mapping is\n\t * applied.\n\t * \n\t * @param mapping\n\t * A mapping of parameters.\n\t * @return A copy of this literal on which the given parameter mapping is\n\t * applied.\n\t */\n\tpublic Literal clone(Map<? extends VariableParam, ? extends LiteralParam> mapping) {\n\t\tlogger.debug(\"start cloning\");\n\t\tLiteral clone = new InterpretedLiteral(this.getProperty());\n\n\t\t// add parameters corresponding to mapping\n\t\tfor (LiteralParam v : this.getParameters()) {\n\t\t\tif (v instanceof VariableParam) {\n\t\t\t\tif (mapping != null && mapping.containsKey(v)) {\n\t\t\t\t\tlogger.trace(\"Params: {}\", clone.parameters);\n\t\t\t\t}\n\t\t\t\tclone.parameters.add((mapping != null && mapping.containsKey(v)) ? mapping.get(v) : v);\n\t\t\t} else\n\t\t\t\tclone.parameters.add(v);\n\t\t}\n\t\tlogger.debug(\"finished cloning\");\n\t\treturn clone;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tsb.append(\"i*\");\n\t\tsb.append(super.toString());\n\t\treturn sb.toString();\n\t}\n\n}\n" }, { "alpha_fraction": 0.7846238017082214, "alphanum_fraction": 0.7857142686843872, "avg_line_length": 31.75, "blob_id": "095626a21a9b09a6c7cb28d25febce36bbce7768", "content_id": "6031b1389ef4db3bc933b7a3cb0311399ca39c06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1834, "license_type": "no_license", "max_line_length": 182, "num_lines": 56, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/astar/AStarFactory.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.astar;\n\nimport jaicore.search.algorithms.standard.bestfirst.nodeevaluation.INodeEvaluator;\nimport jaicore.search.core.interfaces.IGraphSearch;\nimport jaicore.search.core.interfaces.StandardORGraphSearchFactory;\nimport jaicore.search.model.other.EvaluatedSearchGraphPath;\nimport jaicore.search.model.probleminputs.NumberBasedAdditiveTraversalTree;\nimport jaicore.search.model.travesaltree.Node;\n\npublic class AStarFactory<T, A> extends StandardORGraphSearchFactory<NumberBasedAdditiveTraversalTree<T,A>, EvaluatedSearchGraphPath<T, A, Double>, T, A, Double, Node<T,Double>, A> {\n\n\tprivate int timeoutForFInMS;\n\tprivate INodeEvaluator<T, Double> timeoutEvaluator;\n\tprivate String loggerName;\n\n\tpublic AStarFactory() {\n\t\tsuper();\n\t}\n\n\tpublic AStarFactory(final int timeoutForFInMS) {\n\t\tthis();\n\t\tif (timeoutForFInMS > 0) {\n\t\t\tthis.timeoutForFInMS = timeoutForFInMS;\n\t\t}\n\t}\n\n\t@Override\n\tpublic IGraphSearch<NumberBasedAdditiveTraversalTree<T,A>, EvaluatedSearchGraphPath<T, A, Double>, T, A, Double, Node<T,Double>, A> getAlgorithm() {\n\t\tAStar<T, A> search = new AStar<T,A>(getProblemInput());\n\t\tsearch.setTimeoutForComputationOfF(this.timeoutForFInMS, this.timeoutEvaluator);\n\t\tif (loggerName != null && loggerName.length() > 0)\n\t\t\tsearch.setLoggerName(loggerName);\n\t\treturn search;\n\t}\n\n\tpublic void setTimeoutForFComputation(final int timeoutInMS, final INodeEvaluator<T, Double> timeoutEvaluator) {\n\t\tthis.timeoutForFInMS = timeoutInMS;\n\t\tthis.timeoutEvaluator = timeoutEvaluator;\n\t}\n\n\tpublic int getTimeoutForFInMS() {\n\t\treturn this.timeoutForFInMS;\n\t}\n\n\tpublic INodeEvaluator<T, Double> getTimeoutEvaluator() {\n\t\treturn this.timeoutEvaluator;\n\t}\n\n\tpublic String getLoggerName() {\n\t\treturn loggerName;\n\t}\n\n\tpublic void setLoggerName(String loggerName) {\n\t\tthis.loggerName = loggerName;\n\t}\n}\n" }, { "alpha_fraction": 0.6622892618179321, "alphanum_fraction": 0.6704525351524353, "avg_line_length": 36.07432556152344, "blob_id": "5b84c5ff60cf0bd99ab0f5e402323ffae534ccb8", "content_id": "cb5b4e44756ac2ac50cf185b47f527d4c3e050d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5635, "license_type": "no_license", "max_line_length": 161, "num_lines": 148, "path": "/JAICore/jaicore-search/test/jaicore/search/algorithms/parallel/parallelexploration/distributed/clustertest/DistributedBestFirstTester.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "//package jaicore.search.algorithms.parallel.parallelexploration.distributed.clustertest;\r\n//\r\n//import java.io.Serializable;\r\n//import java.nio.file.Path;\r\n//import java.nio.file.Paths;\r\n//import java.util.ArrayList;\r\n//import java.util.List;\r\n//import java.util.Random;\r\n//\r\n//import org.junit.Test;\r\n//\r\n//import jaicore.graphvisualizer.SimpleGraphVisualizationWindow;\r\n//import jaicore.search.algorithms.parallel.parallelexploration.distributed.DistributedOrSearch;\r\n//import jaicore.search.algorithms.parallel.parallelexploration.distributed.DistributedOrSearchCoworker;\r\n//import jaicore.search.algorithms.parallel.parallelexploration.distributed.FolderBasedDistributedSearchCommunicationLayer;\r\n//import jaicore.search.algorithms.parallel.parallelexploration.distributed.interfaces.DistributedSearchCommunicationLayer;\r\n//import jaicore.search.algorithms.parallel.parallelexploration.distributed.interfaces.SerializableGraphGenerator;\r\n//import jaicore.search.algorithms.parallel.parallelexploration.distributed.interfaces.SerializableNodeEvaluator;\r\n//import jaicore.search.algorithms.standard.bestfirst.model.Node;\r\n//import jaicore.search.algorithms.standard.bestfirst.model.NodeExpansionDescription;\r\n//import jaicore.search.algorithms.standard.bestfirst.model.NodeType;\r\n//import jaicore.search.structure.graphgenerator.NodeGoalTester;\r\n//import jaicore.search.structure.graphgenerator.SingleRootGenerator;\r\n//import jaicore.search.structure.graphgenerator.SuccessorGenerator;\r\n//\r\n//public class DistributedBestFirstTester implements Serializable {\r\n//\r\n//\tstatic class TestNode implements Serializable {\r\n//\t\tprivate static final long serialVersionUID = 793618120417152627L;\r\n//\t\tfinal int depth;\r\n//\t\tfinal int min, max;\r\n//\r\n//\t\tpublic TestNode(int depth, int min, int max) {\r\n//\t\t\tsuper();\r\n//\t\t\tthis.depth = depth;\r\n//\t\t\tthis.min = min;\r\n//\t\t\tthis.max = max;\r\n//\t\t}\r\n//\r\n//\t\tpublic String toString() {\r\n//\t\t\treturn min + \"/\" + max;\r\n//\t\t}\r\n//\r\n//\t\t@Override\r\n//\t\tpublic int hashCode() {\r\n//\t\t\tfinal int prime = 31;\r\n//\t\t\tint result = 1;\r\n//\t\t\tresult = prime * result + max;\r\n//\t\t\tresult = prime * result + min;\r\n//\t\t\treturn result;\r\n//\t\t}\r\n//\r\n//\t\t@Override\r\n//\t\tpublic boolean equals(Object obj) {\r\n//\t\t\tif (this == obj)\r\n//\t\t\t\treturn true;\r\n//\t\t\tif (obj == null)\r\n//\t\t\t\treturn false;\r\n//\t\t\tif (getClass() != obj.getClass())\r\n//\t\t\t\treturn false;\r\n//\t\t\tTestNode other = (TestNode) obj;\r\n//\t\t\tif (max != other.max)\r\n//\t\t\t\treturn false;\r\n//\t\t\tif (min != other.min)\r\n//\t\t\t\treturn false;\r\n//\t\t\treturn true;\r\n//\t\t}\r\n//\t}\r\n//\r\n//\t@Test\r\n//\tpublic void test() throws InterruptedException {\r\n//\r\n//\t\tRandom rand = new Random(1);\r\n//\t\tint size = (int) Math.pow(2, 20);\r\n//\t\tint target = (int) Math.round(rand.nextDouble() * size);\r\n//\t\tSystem.out.println(\"Trying to find \" + target + \" within a space of \" + size + \" items.\");\r\n//\r\n//\t\tSerializableGraphGenerator<TestNode, String> gen = new SerializableGraphGenerator<TestNode, String>() {\r\n//\r\n//\t\t\t@Override\r\n//\t\t\tpublic SingleRootGenerator<TestNode> getRootGenerator() {\r\n//\t\t\t\treturn () -> new TestNode(0, 0, size);\r\n//\t\t\t}\r\n//\r\n//\t\t\t@Override\r\n//\t\t\tpublic SuccessorGenerator<TestNode, String> getSuccessorGenerator() {\r\n//\t\t\t\treturn n -> {\r\n//\t\t\t\t\tList<NodeExpansionDescription<TestNode, String>> l = new ArrayList<>();\r\n//\t\t\t\t\tTestNode parent = n;\r\n//\t\t\t\t\ttry {\r\n//\t\t\t\t\t\tThread.sleep(10 * n.depth);\r\n//\t\t\t\t\t} catch (InterruptedException e) {\r\n//\t\t\t\t\t\te.printStackTrace();\r\n//\t\t\t\t\t}\r\n//\t\t\t\t\tif (parent.min < parent.max) {\r\n//\t\t\t\t\t\tint split = (int) Math.floor((parent.min + parent.max) / 2f);\r\n//\t\t\t\t\t\tl.add(new NodeExpansionDescription<>(parent, new TestNode(parent.depth + 1, parent.min, split), \"edge label\", NodeType.OR));\r\n//\t\t\t\t\t\tl.add(new NodeExpansionDescription<>(parent, new TestNode(parent.depth + 1, split + 1, parent.max), \"edge label\", NodeType.OR));\r\n//\t\t\t\t\t}\r\n//\t\t\t\t\treturn l;\r\n//\t\t\t\t};\r\n//\t\t\t}\r\n//\r\n//\t\t\t@Override\r\n//\t\t\tpublic NodeGoalTester<TestNode> getGoalTester() {\r\n//\t\t\t\treturn n -> (n.min == n.max && n.min == target);\r\n//\t\t\t}\r\n//\r\n//\t\t\t@Override\r\n//\t\t\tpublic boolean isSelfContained() {\r\n//\t\t\t\treturn false;\r\n//\t\t\t}\r\n//\r\n//\t\t\t@Override\r\n//\t\t\tpublic void setNodeNumbering(boolean nodenumbering) {\r\n//\t\t\t\t// TODO Auto-generated method stub\r\n//\r\n//\t\t\t}\r\n//\t\t};\r\n//\r\n//\t\tfinal Path folder = Paths.get(\"Z:/pc2/distsearch/testrsc/comm\");\r\n//\t\tDistributedSearchCommunicationLayer<TestNode, String, Integer> masterCommunicationLayer = new FolderBasedDistributedSearchCommunicationLayer<>(folder, true);\r\n//\r\n//\t\tSerializableNodeEvaluator<TestNode, Integer> evaluator = n -> -1 * n.externalPath().size();\r\n//\t\tDistributedOrSearch<TestNode, String, Integer> master = new DistributedOrSearch<>(gen, evaluator, masterCommunicationLayer);\r\n//\r\n//\t\t/* setup coworkers */\r\n//\t\tint coworkers = 5;\r\n//\t\tfor (int i = 1; i <= coworkers; i++) {\r\n//\t\t\tfinal String name = \"cw\" + i;\r\n//\t\t\tfinal String[] args = { folder.toFile().getAbsolutePath(), name, \"5\", \"1000\", \"true\" };\r\n//\t\t\tnew Thread(() -> DistributedOrSearchCoworker.main(args)).start();\r\n//\t\t}\r\n//\r\n//\t\t/* run master in separate thread */\r\n//\t\tSimpleGraphVisualizationWindow<Node<TestNode, Integer>> window = new SimpleGraphVisualizationWindow<>(master);\r\n//\t\twindow.setTitle(\"Master\");\r\n//\t\twindow.getPanel().setTooltipGenerator(n -> (n.getPoint().min + \"-\" + n.getPoint().max));\r\n//\r\n//\t\tlong start = System.currentTimeMillis();\r\n//\t\tList<TestNode> solution = master.nextSolution();\r\n//\t\tlong end = System.currentTimeMillis();\r\n//\t\torg.junit.Assert.assertNotNull(solution);\r\n//\t\tSystem.out.println(solution);\r\n//\t\tSystem.out.println(\"Found after \" + (end - start) / 1000f + \" seconds.\");\r\n//\t}\r\n//\r\n//}\r\n" }, { "alpha_fraction": 0.7443026304244995, "alphanum_fraction": 0.7465816140174866, "avg_line_length": 29.054794311523438, "blob_id": "f205c50db4bfb3a94722466069746a616c8f50f9", "content_id": "be699b65b790b687136ec3534fd72711a613d024", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2194, "license_type": "no_license", "max_line_length": 92, "num_lines": 73, "path": "/JAICore/jaicore-logic/test/jaicore/logic/LiteralTest.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.logic;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertTrue;\n\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport jaicore.logic.fol.structure.Literal;\nimport jaicore.logic.fol.structure.LiteralParam;\nimport jaicore.logic.fol.structure.Type;\nimport jaicore.logic.fol.structure.TypeModule;\nimport jaicore.logic.fol.structure.VariableParam;\n\n/**\n * Test case for the Literal class.\n * \n * @author mbunse\n */\npublic class LiteralTest {\n\n\t@Before\n\tpublic void setUp() throws Exception {\n\t}\n\n\t/**\n\t * Tests, if the constructor \"Literal(Literal literal, Map<VariableParam,\n\t * VariableParam> mapping)\" produces a correctly mapped version of the\n\t * literal parameter.\n\t */\n\t@Test\n\tpublic void testMappingConstructor() {\n\t\t\n\t\tTypeModule typeModule = new TypeModule();\n\n\t\t// create original literal\n\t\tList<LiteralParam> params = new LinkedList<>();\n\t\tType dummyType = typeModule.getType(\"http://dummy.type\");\n\t\tparams.add(new VariableParam(\"v1\", dummyType));\n\t\tparams.add(new VariableParam(\"v2\", dummyType));\n\n\t\tLiteral orig = new Literal(\"p\", params);\n\n\t\t// create mapped version of original\n\t\tMap<VariableParam, VariableParam> mapping = new HashMap<>();\n\t\tmapping.put(new VariableParam(\"v1\", dummyType), new VariableParam(\"s\", dummyType));\n\n\t\tLiteral mappedOrig = orig.clone(mapping);\n\n\t\t// check mapped version\n\t\tassertEquals(\"Properties of original and mapped version are unequal!\", orig.getProperty(),\n\t\t\t\tmappedOrig.getProperty());\n\n\t\tassertTrue(\"Mapped version has other number of parameters!\",\n\t\t\t\tmappedOrig.getParameters().size() == orig.getParameters().size());\n\n\t\tassertTrue(\"Mapped version does not contain variable map target!\",\n\t\t\t\tmappedOrig.getParameters().contains(new VariableParam(\"s\", dummyType)));\n\n\t\tassertTrue(\"Mapped version does not contain unmapped parameter!\",\n\t\t\t\tmappedOrig.getParameters().contains(new VariableParam(\"v2\", dummyType)));\n\n\t\tassertTrue(\"Mapped version contains the substituted parameter!\",\n\t\t\t\t!mappedOrig.getParameters().contains(new VariableParam(\"v1\", dummyType)));\n\n\t} // testMappingConstructor\n\n}\n" }, { "alpha_fraction": 0.804168701171875, "alphanum_fraction": 0.804168701171875, "avg_line_length": 41.89361572265625, "blob_id": "f5ed5068a6a5816d9cc8a02904a9a9703fcc911d", "content_id": "6e8ddf8fc25d686a8bab80ed3e794619ab1b6665", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2063, "license_type": "no_license", "max_line_length": 171, "num_lines": 47, "path": "/softwareconfiguration/hasco/src/hasco/core/DefaultHASCOPlanningGraphGeneratorDeriver.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package hasco.core;\r\n\r\nimport java.util.List;\r\n\r\nimport jaicore.planning.graphgenerators.IPlanningGraphGeneratorDeriver;\r\nimport jaicore.planning.model.ceoc.CEOCAction;\r\nimport jaicore.planning.model.ceoc.CEOCOperation;\r\nimport jaicore.planning.model.core.Plan;\r\nimport jaicore.planning.model.task.ceocipstn.CEOCIPSTNPlanningProblem;\r\nimport jaicore.planning.model.task.ceocipstn.OCIPMethod;\r\nimport jaicore.search.core.interfaces.GraphGenerator;\r\n\r\n/**\r\n * This class only serves to facilitate the usage of HASCO when passing a IPlanningGraphGeneratorDeriver.\r\n * HASCO requires a IHASCOPlanningGraphGeneratorDeriver, which only takes away some of the generics of IPlanningGraphGeneratorDeriver,\r\n * but this implies that you cannot just use arbitrary IPlanningGraphGeneratorDeriver objects anymore.\r\n * To circumvent this problem, this class implements the IHASCOPlanningGraphGeneratorDeriver and wraps any IPlanningGraphGeneratorDeriver.\r\n * \r\n * @author fmohr\r\n *\r\n * @param <N>\r\n * @param <A>\r\n */\r\npublic class DefaultHASCOPlanningGraphGeneratorDeriver<N,A> implements IHASCOPlanningGraphGeneratorDeriver<N, A> {\r\n\r\n\tprivate final IPlanningGraphGeneratorDeriver<CEOCOperation, OCIPMethod, CEOCAction, CEOCIPSTNPlanningProblem<CEOCOperation, OCIPMethod, CEOCAction>, N, A> wrappedDeriver;\r\n\t\r\n\tpublic DefaultHASCOPlanningGraphGeneratorDeriver(\r\n\t\t\tIPlanningGraphGeneratorDeriver<CEOCOperation, OCIPMethod, CEOCAction, CEOCIPSTNPlanningProblem<CEOCOperation, OCIPMethod, CEOCAction>, N, A> wrappedDeriver) {\r\n\t\tsuper();\r\n\t\tthis.wrappedDeriver = wrappedDeriver;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic GraphGenerator<N, A> transform(CEOCIPSTNPlanningProblem<CEOCOperation, OCIPMethod, CEOCAction> problem) {\r\n\t\treturn wrappedDeriver.transform(problem);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic Plan<CEOCAction> getPlan(List<N> path) {\r\n\t\treturn wrappedDeriver.getPlan(path);\r\n\t}\r\n\r\n\tpublic IPlanningGraphGeneratorDeriver<CEOCOperation, OCIPMethod, CEOCAction, CEOCIPSTNPlanningProblem<CEOCOperation, OCIPMethod, CEOCAction>, N, A> getWrappedDeriver() {\r\n\t\treturn wrappedDeriver;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7074366211891174, "alphanum_fraction": 0.7102066874504089, "avg_line_length": 31.762590408325195, "blob_id": "b22d99315078998ad57c0ae3eb2968f955c4281a", "content_id": "672de7180845211926315e25b3bae9042fe913b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4693, "license_type": "no_license", "max_line_length": 212, "num_lines": 139, "path": "/softwareconfiguration/mlplan/src/de/upb/crc901/reduction/single/ReductionExperiment.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package de.upb.crc901.reduction.single;\r\n\r\npublic class ReductionExperiment {\r\n\tprivate final int seed;\r\n\tprivate final String dataset;\r\n\tprivate final String nameOfLeftClassifier, nameOfInnerClassifier, nameOfRightClassifier;\r\n\tprivate String exceptionLeft, exceptionInner, exceptionRight;\r\n\r\n\tpublic ReductionExperiment(int seed, String dataset, String nameOfLeftClassifier, String nameOfInnerClassifier, String nameOfRightClassifier) {\r\n\t\tsuper();\r\n\t\tthis.seed = seed;\r\n\t\tthis.dataset = dataset;\r\n\t\tthis.nameOfLeftClassifier = nameOfLeftClassifier;\r\n\t\tthis.nameOfInnerClassifier = nameOfInnerClassifier;\r\n\t\tthis.nameOfRightClassifier = nameOfRightClassifier;\r\n\t}\r\n\t\r\n\tpublic ReductionExperiment(int seed, String dataset, String nameOfLeftClassifier, String nameOfInnerClassifier, String nameOfRightClassifier, String exceptionLeft, String exceptionInner, String exceptionRight) {\r\n\t\tthis(seed,dataset,nameOfLeftClassifier,nameOfInnerClassifier,nameOfRightClassifier);\r\n\t\tthis.exceptionLeft = exceptionLeft;\r\n\t\tthis.exceptionInner = exceptionInner;\r\n\t\tthis.exceptionRight = exceptionRight;\r\n\t}\r\n\r\n\tpublic int getSeed() {\r\n\t\treturn seed;\r\n\t}\r\n\r\n\tpublic String getDataset() {\r\n\t\treturn dataset;\r\n\t}\r\n\r\n\tpublic String getNameOfLeftClassifier() {\r\n\t\treturn nameOfLeftClassifier;\r\n\t}\r\n\r\n\tpublic String getNameOfInnerClassifier() {\r\n\t\treturn nameOfInnerClassifier;\r\n\t}\r\n\r\n\tpublic String getNameOfRightClassifier() {\r\n\t\treturn nameOfRightClassifier;\r\n\t}\r\n\r\n\tpublic String getExceptionLeft() {\r\n\t\treturn exceptionLeft;\r\n\t}\r\n\r\n\tpublic void setExceptionLeft(String exceptionLeft) {\r\n\t\tthis.exceptionLeft = exceptionLeft;\r\n\t}\r\n\r\n\tpublic String getExceptionInner() {\r\n\t\treturn exceptionInner;\r\n\t}\r\n\r\n\tpublic void setExceptionInner(String exceptionInner) {\r\n\t\tthis.exceptionInner = exceptionInner;\r\n\t}\r\n\r\n\tpublic String getExceptionRight() {\r\n\t\treturn exceptionRight;\r\n\t}\r\n\r\n\tpublic void setExceptionRight(String exceptionRight) {\r\n\t\tthis.exceptionRight = exceptionRight;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + ((dataset == null) ? 0 : dataset.hashCode());\r\n\t\tresult = prime * result + ((exceptionInner == null) ? 0 : exceptionInner.hashCode());\r\n\t\tresult = prime * result + ((exceptionLeft == null) ? 0 : exceptionLeft.hashCode());\r\n\t\tresult = prime * result + ((exceptionRight == null) ? 0 : exceptionRight.hashCode());\r\n\t\tresult = prime * result + ((nameOfInnerClassifier == null) ? 0 : nameOfInnerClassifier.hashCode());\r\n\t\tresult = prime * result + ((nameOfLeftClassifier == null) ? 0 : nameOfLeftClassifier.hashCode());\r\n\t\tresult = prime * result + ((nameOfRightClassifier == null) ? 0 : nameOfRightClassifier.hashCode());\r\n\t\tresult = prime * result + seed;\r\n\t\treturn result;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean equals(Object obj) {\r\n\t\tif (this == obj)\r\n\t\t\treturn true;\r\n\t\tif (obj == null)\r\n\t\t\treturn false;\r\n\t\tif (getClass() != obj.getClass())\r\n\t\t\treturn false;\r\n\t\tReductionExperiment other = (ReductionExperiment) obj;\r\n\t\tif (dataset == null) {\r\n\t\t\tif (other.dataset != null)\r\n\t\t\t\treturn false;\r\n\t\t} else if (!dataset.equals(other.dataset))\r\n\t\t\treturn false;\r\n\t\tif (exceptionInner == null) {\r\n\t\t\tif (other.exceptionInner != null)\r\n\t\t\t\treturn false;\r\n\t\t} else if (!exceptionInner.equals(other.exceptionInner))\r\n\t\t\treturn false;\r\n\t\tif (exceptionLeft == null) {\r\n\t\t\tif (other.exceptionLeft != null)\r\n\t\t\t\treturn false;\r\n\t\t} else if (!exceptionLeft.equals(other.exceptionLeft))\r\n\t\t\treturn false;\r\n\t\tif (exceptionRight == null) {\r\n\t\t\tif (other.exceptionRight != null)\r\n\t\t\t\treturn false;\r\n\t\t} else if (!exceptionRight.equals(other.exceptionRight))\r\n\t\t\treturn false;\r\n\t\tif (nameOfInnerClassifier == null) {\r\n\t\t\tif (other.nameOfInnerClassifier != null)\r\n\t\t\t\treturn false;\r\n\t\t} else if (!nameOfInnerClassifier.equals(other.nameOfInnerClassifier))\r\n\t\t\treturn false;\r\n\t\tif (nameOfLeftClassifier == null) {\r\n\t\t\tif (other.nameOfLeftClassifier != null)\r\n\t\t\t\treturn false;\r\n\t\t} else if (!nameOfLeftClassifier.equals(other.nameOfLeftClassifier))\r\n\t\t\treturn false;\r\n\t\tif (nameOfRightClassifier == null) {\r\n\t\t\tif (other.nameOfRightClassifier != null)\r\n\t\t\t\treturn false;\r\n\t\t} else if (!nameOfRightClassifier.equals(other.nameOfRightClassifier))\r\n\t\t\treturn false;\r\n\t\tif (seed != other.seed)\r\n\t\t\treturn false;\r\n\t\treturn true;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\treturn \"ReductionExperiment [seed=\" + seed + \", dataset=\" + dataset + \", nameOfLeftClassifier=\" + nameOfLeftClassifier + \", nameOfInnerClassifier=\" + nameOfInnerClassifier\r\n\t\t\t\t+ \", nameOfRightClassifier=\" + nameOfRightClassifier + \", exceptionLeft=\" + exceptionLeft + \", exceptionInner=\"\r\n\t\t\t\t+ exceptionInner + \", exceptionRight=\" + exceptionRight + \"]\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7346570491790771, "alphanum_fraction": 0.7346570491790771, "avg_line_length": 18.785715103149414, "blob_id": "65528b3e64a3f7b04d7becb348f4394fe9ee3d96", "content_id": "5965da4d5f1c0e917112a88f8e5194f87fe42927", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 554, "license_type": "no_license", "max_line_length": 65, "num_lines": 28, "path": "/JAICore/jaicore-graphvisualizer/src/jaicore/graphvisualizer/events/graphEvents/NodeParentSwitchEvent.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.graphvisualizer.events.graphEvents;\n\npublic class NodeParentSwitchEvent<T> implements GraphEvent {\n\tprivate final T node;\n\tprivate final T oldParent;\n\tprivate final T newParent;\n\tpublic final String name = \"NodeParentSwitchEvent\";\n\n\tpublic NodeParentSwitchEvent(T node, T oldParent, T newParent) {\n\t\tsuper();\n\t\tthis.node = node;\n\t\tthis.oldParent = oldParent;\n\t\tthis.newParent = newParent;\n\t}\n\n\tpublic T getNode() {\n\t\treturn node;\n\t}\n\n\tpublic T getOldParent() {\n\t\treturn oldParent;\n\t}\n\n\tpublic T getNewParent() {\n\t\treturn newParent;\n\t}\n\n}\n" }, { "alpha_fraction": 0.8107230067253113, "alphanum_fraction": 0.8107230067253113, "avg_line_length": 39.03333282470703, "blob_id": "6cfdccc917048dbfcbe6e65bb947c92a0d6456c1", "content_id": "0a977d7788fbe57d15b0965f225961a05dfe0215", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1231, "license_type": "no_license", "max_line_length": 154, "num_lines": 30, "path": "/JAICore/jaicore-search/test/jaicore/search/algorithms/standard/random/RandomSearchEnhancedTTSPTester.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.random;\r\n\r\nimport jaicore.basic.algorithm.AlgorithmProblemTransformer;\r\nimport jaicore.search.core.interfaces.IGraphSearchFactory;\r\nimport jaicore.search.model.probleminputs.GraphSearchInput;\r\nimport jaicore.search.testproblems.enhancedttsp.EnhancedTTSP;\r\nimport jaicore.search.testproblems.enhancedttsp.EnhancedTTSPNode;\r\nimport jaicore.search.testproblems.enhancedttsp.EnhancedTTSPTester;\r\n\r\npublic class RandomSearchEnhancedTTSPTester extends EnhancedTTSPTester<GraphSearchInput<EnhancedTTSPNode, String>, Object, EnhancedTTSPNode, String> {\r\n\r\n\t\r\n\r\n\t@Override\r\n\tpublic IGraphSearchFactory<GraphSearchInput<EnhancedTTSPNode, String>, Object, EnhancedTTSPNode, String, Double, EnhancedTTSPNode, String> getFactory() {\r\n\t\treturn new RandomSearchFactory<>();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic AlgorithmProblemTransformer<EnhancedTTSP, GraphSearchInput<EnhancedTTSPNode, String>> getProblemReducer() {\r\n\t\treturn new AlgorithmProblemTransformer<EnhancedTTSP, GraphSearchInput<EnhancedTTSPNode,String>>() {\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic GraphSearchInput<EnhancedTTSPNode, String> transform(EnhancedTTSP problem) {\r\n\t\t\t\treturn new GraphSearchInput<>(problem.getGraphGenerator());\r\n\t\t\t}\r\n\t\t};\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.7545454502105713, "alphanum_fraction": 0.7552447319030762, "avg_line_length": 40.30769348144531, "blob_id": "3bc48a0a341d5a611e8b429d1782bec152f6008b", "content_id": "28276cdccc0944e9905b25624e32bb35bde39833", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 7150, "license_type": "no_license", "max_line_length": 189, "num_lines": 169, "path": "/JAICore/jaicore-planning/src/jaicore/planning/graphgenerators/task/tfd/TFDGraphGenerator.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.graphgenerators.task.tfd;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.Collection;\r\nimport java.util.HashMap;\r\nimport java.util.List;\r\nimport java.util.Map;\r\nimport java.util.regex.Matcher;\r\nimport java.util.regex.Pattern;\r\nimport java.util.stream.Collectors;\r\n\r\nimport jaicore.logic.fol.structure.Literal;\r\nimport jaicore.logic.fol.structure.Monom;\r\nimport jaicore.planning.graphgenerators.task.TaskPlannerUtil;\r\nimport jaicore.planning.model.core.Action;\r\nimport jaicore.planning.model.core.Operation;\r\nimport jaicore.planning.model.core.PlannerUtil;\r\nimport jaicore.planning.model.task.IHTNPlanningProblem;\r\nimport jaicore.planning.model.task.stn.Method;\r\nimport jaicore.planning.model.task.stn.MethodInstance;\r\nimport jaicore.search.algorithms.parallel.parallelexploration.distributed.interfaces.SerializableGraphGenerator;\r\nimport jaicore.search.core.interfaces.PathUnifyingGraphGenerator;\r\nimport jaicore.search.model.travesaltree.NodeExpansionDescription;\r\nimport jaicore.search.model.travesaltree.NodeType;\r\nimport jaicore.search.structure.graphgenerator.NodeGoalTester;\r\nimport jaicore.search.structure.graphgenerator.SingleRootGenerator;\r\nimport jaicore.search.structure.graphgenerator.SuccessorGenerator;\r\n\r\n@SuppressWarnings(\"serial\")\r\npublic class TFDGraphGenerator<O extends Operation, M extends Method, A extends Action> implements SerializableGraphGenerator<TFDNode, String>, PathUnifyingGraphGenerator<TFDNode, String> {\r\n\r\n\tprotected TaskPlannerUtil util = new TaskPlannerUtil(null);\r\n\tprotected final IHTNPlanningProblem<O, M, A> problem;\r\n\tprotected final Map<String, Operation> primitiveTasks = new HashMap<>();\r\n\r\n\tpublic TFDGraphGenerator(IHTNPlanningProblem<O, M, A> problem) {\r\n\t\tthis.problem = problem;\r\n\t\tfor (Operation op : problem.getDomain().getOperations())\r\n\t\t\tprimitiveTasks.put(op.getName(), op);\r\n\t}\r\n\r\n\tprotected Collection<TFDNode> getSuccessorsResultingFromResolvingPrimitiveTask(Monom state, Literal taskToBeResolved, List<Literal> remainingOtherTasks) {\r\n\t\tCollection<TFDNode> successors = new ArrayList<>();\r\n\t\tfor (Action applicableAction : util.getActionsForPrimitiveTaskThatAreApplicableInState(null, primitiveTasks.get(taskToBeResolved.getPropertyName()), taskToBeResolved, state)) {\r\n\t\t\tMonom stateCopy = new Monom(state);\r\n\t\t\tPlannerUtil.updateState(stateCopy, applicableAction);\r\n\t\t\tsuccessors.add(postProcessPrimitiveTaskNode(new TFDNode(stateCopy, remainingOtherTasks, null, applicableAction)));\r\n\t\t}\r\n\t\treturn successors;\r\n\t}\r\n\r\n\tprotected Collection<TFDNode> getSuccessorsResultingFromResolvingComplexTask(Monom state, Literal taskToBeResolved, List<Literal> remainingOtherTasks) {\r\n\t\tCollection<TFDNode> successors = new ArrayList<>();\r\n\t\tfor (MethodInstance instance : util.getMethodInstancesForTaskThatAreApplicableInState(null, this.problem.getDomain().getMethods(), taskToBeResolved, state, remainingOtherTasks)) {\r\n\r\n\t\t\t/* derive remaining network for this instance */\r\n\t\t\tList<Literal> remainingTasks = stripTNPrefixes(util.getTaskChainOfTotallyOrderedNetwork(instance.getNetwork()));\r\n\t\t\tremainingTasks.addAll(remainingOtherTasks);\r\n\t\t\tsuccessors.add(postProcessComplexTaskNode(new TFDNode(state, remainingTasks, instance, null)));\r\n\t\t}\r\n\t\treturn successors;\r\n\t}\r\n\r\n\tprotected List<Literal> stripTNPrefixes(List<Literal> taskList) {\r\n\t\treturn taskList.stream().map(l -> {\r\n\t\t\tString taskName = l.getPropertyName().substring(l.getPropertyName().indexOf(\"-\") + 1, l.getPropertyName().length());\r\n\t\t\treturn new Literal(taskName, l.getParameters(), l.isPositive());\r\n\t\t}).collect(Collectors.toList());\r\n\t}\r\n\r\n\t/**\r\n\t * A hook for extending classes that can be used to change the nodes before they are attached\r\n\t * \r\n\t * @param node\r\n\t * @return\r\n\t */\r\n\tprotected TFDNode postProcessPrimitiveTaskNode(TFDNode node) {\r\n\t\treturn node;\r\n\t}\r\n\r\n\t/**\r\n\t * A hook for extending classes that can be used to change the nodes before they are attached\r\n\t * \r\n\t * @param node\r\n\t * @return\r\n\t */\r\n\tprotected TFDNode postProcessComplexTaskNode(TFDNode node) {\r\n\t\treturn node;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic SingleRootGenerator<TFDNode> getRootGenerator() {\r\n\t\tTaskPlannerUtil util = new TaskPlannerUtil(null);\r\n\t\treturn () -> new TFDNode(problem.getInit(), stripTNPrefixes(util.getTaskChainOfTotallyOrderedNetwork(problem.getNetwork())));\r\n\t}\r\n\r\n\t@Override\r\n\tpublic SuccessorGenerator<TFDNode, String> getSuccessorGenerator() {\r\n\t\treturn l -> {\r\n\t\t\tMonom state = l.getState();\r\n\t\t\tList<Literal> currentlyRemainingTasks = new ArrayList<>(l.getRemainingTasks());\r\n\t\t\tif (currentlyRemainingTasks.isEmpty())\r\n\t\t\t\treturn new ArrayList<>();\r\n\t\t\tLiteral nextTaskTmp = currentlyRemainingTasks.get(0);\r\n\t\t\tcurrentlyRemainingTasks.remove(0);\r\n\t\t\tString nextTaskName = nextTaskTmp.getPropertyName();\r\n\t\t\tLiteral nextTask = new Literal(nextTaskName, nextTaskTmp.getParameters());\r\n\r\n\t\t\t/* get the child nodes */\r\n\t\t\tCollection<TFDNode> successors = primitiveTasks.containsKey(nextTask.getPropertyName()) ? getSuccessorsResultingFromResolvingPrimitiveTask(state, nextTask, currentlyRemainingTasks)\r\n\t\t\t\t\t: getSuccessorsResultingFromResolvingComplexTask(state, nextTask, currentlyRemainingTasks);\r\n\r\n\t\t\t/* change order in remaining tasks based on numbered prefixes */\r\n\t\t\tsuccessors = successors.stream().map(s -> orderRemainingTasksByPriority(s)).collect(Collectors.toList());\r\n\r\n\t\t\t/* derive successor descriptions from the nodes */\r\n\t\t\treturn successors.stream().map(n -> new NodeExpansionDescription<TFDNode, String>(l, n, \"\", NodeType.OR)).collect(Collectors.toList());\r\n\t\t};\r\n\t}\r\n\r\n\tpublic TFDNode orderRemainingTasksByPriority(TFDNode node) {\r\n\r\n\t\t/* determine order of tasks based on the prefixes */\r\n\t\tPattern p = Pattern.compile(\"(\\\\d+)_\");\r\n\t\tList<Literal> unorderedLiterals = new ArrayList<>();\r\n\t\tMap<Integer, List<Literal>> orderedLiterals = new HashMap<>();\r\n\t\tnode.getRemainingTasks().forEach(t -> {\r\n\t\t\tMatcher m = p.matcher(t.getPropertyName());\r\n\t\t\tif (m.find()) {\r\n\t\t\t\tint order = Integer.valueOf(m.group(1));\r\n\t\t\t\tif (!orderedLiterals.containsKey(order))\r\n\t\t\t\t\torderedLiterals.put(order, new ArrayList<>());\r\n\t\t\t\tList<Literal> tasksWithorder = orderedLiterals.get(order);\r\n\t\t\t\ttasksWithorder.add(t);\r\n\t\t\t} else\r\n\t\t\t\tunorderedLiterals.add(t);\r\n\t\t});\r\n\r\n\t\t/* reorganize task network */\r\n\t\tList<Literal> newLiteralList = new ArrayList<>();\r\n\t\torderedLiterals.keySet().stream().sorted().forEach(order -> newLiteralList.addAll(orderedLiterals.get(order)));\r\n\t\tnewLiteralList.addAll(unorderedLiterals);\r\n\t\treturn new TFDNode(node.getState(), newLiteralList, node.getAppliedMethodInstance(), node.getAppliedAction());\r\n\t}\r\n\r\n\t@Override\r\n\tpublic NodeGoalTester<TFDNode> getGoalTester() {\r\n\t\treturn l -> l.getRemainingTasks().isEmpty();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean isSelfContained() {\r\n\t\treturn false;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void setNodeNumbering(boolean nodenumbering) {\r\n\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean isPathSemanticallySubsumed(List<TFDNode> path, List<TFDNode> potentialSuperPath) throws InterruptedException {\r\n\t\tint n = path.size();\r\n\t\tfor (int i = 0; i < n; i++)\r\n\t\t\tif (!path.get(i).equals(potentialSuperPath.get(i)))\r\n\t\t\t\treturn false;\r\n\t\treturn true;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.8085106611251831, "alphanum_fraction": 0.8085106611251831, "avg_line_length": 19.14285659790039, "blob_id": "8fceb3de4d781ec86e5706f75839f742afec04b2", "content_id": "6aee0cfb45d944da9e345220ee8d775c2eb24f87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 141, "license_type": "no_license", "max_line_length": 48, "num_lines": 7, "path": "/JAICore/jaicore-search/src/jaicore/search/model/travesaltree/GraphEventBus.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.model.travesaltree;\n\nimport com.google.common.eventbus.EventBus;\n\npublic class GraphEventBus<T> extends EventBus {\n\n}\n" }, { "alpha_fraction": 0.6492027044296265, "alphanum_fraction": 0.6492027044296265, "avg_line_length": 16.29166603088379, "blob_id": "ef7b11d994b99074463967a8491948ef677dc48c", "content_id": "6efa93d4ee333e0bcf496719a053b8e204847302", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 439, "license_type": "no_license", "max_line_length": 53, "num_lines": 24, "path": "/JAICore/jaicore-search/test/jaicore/search/testproblems/npuzzle/standard/NPuzzleProblem.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.testproblems.npuzzle.standard;\r\n\r\npublic class NPuzzleProblem {\r\n\r\n\tprivate final int[][] board;\r\n\tprivate final int dim;\r\n\r\n\tpublic NPuzzleProblem(int[][] board) {\r\n\t\tthis.board = board;\r\n\t\tthis.dim = board.length;\r\n\t}\r\n\r\n\tpublic NPuzzleProblem(int dim, int seed) {\r\n\t\tthis(new NPuzzleNode(dim, seed).board);\r\n\t}\r\n\r\n\tpublic int[][] getBoard() {\r\n\t\treturn board;\r\n\t}\r\n\r\n\tpublic int getDim() {\r\n\t\treturn dim;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7394191026687622, "alphanum_fraction": 0.7394191026687622, "avg_line_length": 24.10416603088379, "blob_id": "8fba4c2df96a875fb10fb99c7730a04fbb600ea1", "content_id": "de8148bc90a7bfaf7d3568f53739084f4b64ded0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1205, "license_type": "no_license", "max_line_length": 80, "num_lines": 48, "path": "/JAICore/jaicore-graphvisualizer/src/jaicore/graphvisualizer/gui/dataSupplier/ISupplier.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.graphvisualizer.gui.dataSupplier;\n\nimport com.fasterxml.jackson.databind.JsonNode;\n\nimport jaicore.graphvisualizer.events.controlEvents.ControlEvent;\nimport jaicore.graphvisualizer.events.graphEvents.GraphEvent;\n\n/**\n * This interface describes a supplier, which computes data. The data is send\n * out over an eventbus and received by an IVisualizer.\n * \n * @author jkoepe\n *\n */\npublic interface ISupplier {\n\n\t/**\n\t * Register an listener to this supplier. In most cases this will be an\n\t * IVisualizer\n\t * \n\t * @param listener\n\t */\n\tvoid registerListener(Object listener);\n\n\t/**\n\t * This function computes what is happening if a VisuEvent is incoming.\n\t * \n\t * @param event The received VisuEvent\n\t */\n\tvoid receiveGraphEvent(GraphEvent event);\n\n\t/**\n\t * This function describes what is happening, if an ControlEvent is incoming.\n\t * Usually these events will start at a FXController.\n\t * \n\t * @param event\n\t */\n\tvoid receiveControlEvent(ControlEvent event);\n\n\t/**\n\t * Returns a Jsonnode, which contains this serialization. This Jasonnode can be\n\t * used to recreate the Supplier.\n\t * \n\t * @return A JsonNode containing information of the supplier.\n\t */\n\tJsonNode getSerialization();\n\n}\n" }, { "alpha_fraction": 0.792535662651062, "alphanum_fraction": 0.8133918642997742, "avg_line_length": 38.60869598388672, "blob_id": "96463305d51aeca7260b62a1b4675e79ee549f1f", "content_id": "916d835f85f8d79e8470ca1bbde70b5054fd71df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 911, "license_type": "no_license", "max_line_length": 183, "num_lines": 23, "path": "/JAICore/jaicore-ml/src/jaicore/ml/classification/multiclass/reduction/MCTreeMergeNode.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.ml.classification.multiclass.reduction;\n\nimport java.util.Collection;\nimport java.util.List;\n\nimport weka.classifiers.Classifier;\n\npublic class MCTreeMergeNode extends MCTreeNodeReD {\n /**\n * Default generated serial version UID.\n */\n private static final long serialVersionUID = -6282530004580334598L;\n\n public MCTreeMergeNode(final String innerNodeClassifier, final Collection<String> leftChildClasses, final Classifier leftChildClassifier, final Collection<String> rightChildClasses,\n final Classifier rightChildClassifier) throws Exception {\n super(innerNodeClassifier, leftChildClasses, leftChildClassifier, rightChildClasses, rightChildClassifier);\n }\n\n public MCTreeMergeNode(final Classifier innerNodeClassifier, final List<Collection<String>> childClasses, final List<Classifier> childClassifier) {\n super(innerNodeClassifier, childClasses, childClassifier);\n }\n\n}\n" }, { "alpha_fraction": 0.687494158744812, "alphanum_fraction": 0.6907581686973572, "avg_line_length": 26.82526969909668, "blob_id": "22722e309ddab4a24a1f18bc671a4836b56e0b37", "content_id": "c97dfc5cdc577280a29741c4ccfbdb9ddb873c40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 10723, "license_type": "no_license", "max_line_length": 174, "num_lines": 372, "path": "/JAICore/jaicore-ml/src/jaicore/ml/classification/multiclass/reduction/MCTreeNode.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.ml.classification.multiclass.reduction;\r\n\r\nimport java.io.Serializable;\r\nimport java.util.ArrayList;\r\nimport java.util.Collection;\r\nimport java.util.HashMap;\r\nimport java.util.HashSet;\r\nimport java.util.Iterator;\r\nimport java.util.List;\r\nimport java.util.Map;\r\nimport java.util.Set;\r\nimport java.util.concurrent.atomic.AtomicInteger;\r\nimport java.util.concurrent.locks.Lock;\r\nimport java.util.concurrent.locks.ReentrantLock;\r\nimport java.util.stream.Collectors;\r\nimport java.util.stream.IntStream;\r\n\r\nimport org.apache.commons.lang3.builder.HashCodeBuilder;\r\n\r\nimport jaicore.ml.WekaUtil;\r\nimport weka.classifiers.AbstractClassifier;\r\nimport weka.classifiers.Classifier;\r\nimport weka.classifiers.meta.MultiClassClassifier;\r\nimport weka.classifiers.rules.ZeroR;\r\nimport weka.core.Capabilities;\r\nimport weka.core.Instance;\r\nimport weka.core.Instances;\r\nimport weka.core.WekaException;\r\n\r\npublic class MCTreeNode implements Classifier, ITreeClassifier, Serializable, Iterable<MCTreeNode> {\r\n\r\n\t/**\r\n\t *\r\n\t */\r\n\tprivate static final long serialVersionUID = 8873192747068561266L;\r\n\r\n\tprivate EMCNodeType nodeType;\r\n\tprivate List<MCTreeNode> children = new ArrayList<>();\r\n\tprivate Classifier classifier;\r\n\tprivate String classifierID;\r\n\tprivate final List<Integer> containedClasses;\r\n\tprivate boolean trained = false;\r\n\tprivate boolean fromCache = false;\r\n\r\n\tpublic static AtomicInteger cacheRetrievals = new AtomicInteger();\r\n\tprivate static Map<String, Classifier> classifierCacheMap = new HashMap<>();\r\n\tprivate static Lock classifierCacheMapLock = new ReentrantLock();\r\n\r\n\tpublic MCTreeNode(final Classifier left, final Classifier right, final String baseClassifier) {\r\n\t\tthis.containedClasses = new ArrayList<>();\r\n\t}\r\n\r\n\tpublic MCTreeNode(final List<Integer> containedClasses) {\r\n\t\tthis.containedClasses = containedClasses;\r\n\t}\r\n\r\n\tpublic MCTreeNode(final List<Integer> containedClasses, final EMCNodeType nodeType, final String classifierID) throws Exception {\r\n\t\tthis(containedClasses, nodeType, AbstractClassifier.forName(classifierID, null));\r\n\t}\r\n\r\n\tpublic MCTreeNode(final List<Integer> containedClasses, final EMCNodeType nodeType, final Classifier baseClassifier) {\r\n\t\tthis(containedClasses);\r\n\t\tthis.setNodeType(nodeType);\r\n\t\tthis.setBaseClassifier(baseClassifier);\r\n\t}\r\n\r\n\tpublic EMCNodeType getNodeType() {\r\n\t\treturn this.nodeType;\r\n\t}\r\n\r\n\tpublic void addChild(final MCTreeNode newNode) {\r\n\t\tif (newNode.getNodeType() == EMCNodeType.MERGE) {\r\n\t\t\tfor (MCTreeNode child : newNode.getChildren()) {\r\n\t\t\t\tthis.children.add(child);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tthis.children.add(newNode);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic List<MCTreeNode> getChildren() {\r\n\t\treturn this.children;\r\n\t}\r\n\r\n\tpublic Collection<Integer> getContainedClasses() {\r\n\t\treturn this.containedClasses;\r\n\t}\r\n\r\n\tpublic boolean isCompletelyConfigured() {\r\n\t\tif (this.classifier == null) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tif (this.children.isEmpty()) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tfor (MCTreeNode child : this.children) {\r\n\t\t\tif (!child.isCompletelyConfigured()) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void buildClassifier(final Instances data) throws Exception {\r\n\t\tassert (this.getNodeType() != EMCNodeType.MERGE) : \"MERGE node detected while building classifier. This must not happen!\";\r\n\t\tassert !data.isEmpty() : \"Cannot train MCTree with empty set of instances.\";\r\n\t\tassert !this.children.isEmpty() : \"Cannot train MCTree without children\";\r\n\r\n\t\t// sort class split into clusters\r\n\t\tList<Set<String>> instancesCluster = new ArrayList<>();\r\n\t\tIntStream.range(0, this.children.size()).forEach(x -> instancesCluster.add(new HashSet<>()));\r\n\t\tint index = 0;\r\n\t\tfor (MCTreeNode child : this.children) {\r\n\t\t\tfor (Integer classIndex : child.getContainedClasses()) {\r\n\t\t\t\tinstancesCluster.get(index).add(data.classAttribute().value(classIndex));\r\n\t\t\t}\r\n\t\t\tindex++;\r\n\t\t}\r\n\r\n\t\tString classifierKey = this.classifier.getClass().getName() + \"#\" + instancesCluster + \"#\" + data.size() + \"#\" + new HashCodeBuilder().append(data.toString()).toHashCode();\r\n\r\n\t\t// refactor training data with respect to the split clusters and build the classifier\r\n\t\tInstances trainingData = WekaUtil.mergeClassesOfInstances(data, instancesCluster);\r\n\r\n\t\tClassifier cachedClassifier = null;\r\n\t\tclassifierCacheMapLock.lock();\r\n\t\ttry {\r\n\t\t\tcachedClassifier = AbstractClassifier.makeCopy(classifierCacheMap.get(classifierKey));\r\n\t\t\tthis.fromCache = true;\r\n\t\t} finally {\r\n\t\t\tclassifierCacheMapLock.unlock();\r\n\t\t}\r\n\t\tcachedClassifier = null;\r\n\r\n\t\tif (cachedClassifier != null) {\r\n\t\t\tthis.classifier = cachedClassifier;\r\n\t\t} else {\r\n\t\t\ttry {\r\n\t\t\t\tthis.classifier.buildClassifier(trainingData);\r\n\t\t\t} catch (WekaException e) {\r\n\t\t\t\tthis.classifier = new ZeroR();\r\n\t\t\t\tthis.classifier.buildClassifier(trainingData);\r\n\t\t\t}\r\n\r\n\t\t\tclassifierCacheMapLock.lock();\r\n\t\t\ttry {\r\n\t\t\t\tclassifierCacheMap.put(classifierKey, this.classifier);\r\n\t\t\t} finally {\r\n\t\t\t\tclassifierCacheMapLock.unlock();\r\n\t\t\t}\r\n\r\n\t\t}\r\n\r\n\t\t// recursively build classifiers for children\r\n\t\tthis.children.stream().parallel().forEach(child -> {\r\n\t\t\ttry {\r\n\t\t\t\tchild.buildClassifier(data);\r\n\t\t\t} catch (Exception e) {\r\n\t\t\t\te.printStackTrace();\r\n\t\t\t}\r\n\t\t});\r\n\t\tthis.trained = true;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic double classifyInstance(final Instance instance) throws Exception {\r\n\t\tdouble selection = -1;\r\n\t\tdouble best = 0;\r\n\t\tdouble[] dist = this.distributionForInstance(instance);\r\n\t\tfor (int i = 0; i < dist.length; i++) {\r\n\t\t\tdouble score = dist[i];\r\n\t\t\tif (score > best) {\r\n\t\t\t\tbest = score;\r\n\t\t\t\tselection = i;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this.containedClasses.get((int) selection);\r\n\t}\r\n\r\n\tpublic void distributionForInstance(final Instance instance, final double[] distribution) throws Exception {\r\n\t\tInstance iNew = WekaUtil.getRefactoredInstance(instance, IntStream.range(0, this.children.size()).mapToObj(x -> x + \".0\").collect(Collectors.toList()));\r\n\r\n\t\tdouble[] localDistribution = new double[this.containedClasses.size()];\r\n\t\tlocalDistribution = this.classifier.distributionForInstance(iNew);\r\n\r\n\t\tfor (MCTreeNode child : this.children) {\r\n\t\t\tchild.distributionForInstance(instance, distribution);\r\n\t\t\tint indexOfChild = this.children.indexOf(child);\r\n\r\n\t\t\tfor (Integer classContainedInChild : child.getContainedClasses()) {\r\n\t\t\t\tdistribution[classContainedInChild] *= localDistribution[indexOfChild];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic double[] distributionForInstance(final Instance instance) throws Exception {\r\n\t\tassert this.trained : \"Cannot get distribution from untrained classifier \" + this.toStringWithOffset();\r\n\r\n\t\tdouble[] classDistribution = new double[this.containedClasses.size()];\r\n\t\tthis.distributionForInstance(instance, classDistribution);\r\n\t\treturn classDistribution;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic Capabilities getCapabilities() {\r\n\t\treturn this.classifier.getCapabilities();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int getHeight() {\r\n\t\treturn 1 + this.children.stream().map(x -> x.getHeight()).mapToInt(x -> (int) x).max().getAsInt();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int getDepthOfFirstCommonParent(final List<Integer> classes) {\r\n\t\tfor (MCTreeNode child : this.children) {\r\n\t\t\tif (child.getContainedClasses().containsAll(classes)) {\r\n\t\t\t\treturn 1 + child.getDepthOfFirstCommonParent(classes);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn 1;\r\n\t}\r\n\r\n\tpublic static void clearCache() {\r\n\t\tclassifierCacheMap.clear();\r\n\t}\r\n\r\n\tpublic static Map<String, Classifier> getClassifierCache() {\r\n\t\treturn classifierCacheMap;\r\n\t}\r\n\r\n\tpublic Classifier getClassifier() {\r\n\t\treturn this.classifier;\r\n\t}\r\n\r\n\tpublic void setBaseClassifier(final Classifier classifier) {\r\n\r\n\t\tassert classifier != null : \"Cannot set null classifier!\";\r\n\r\n\t\tthis.classifierID = classifier.getClass().getName();\r\n\t\tswitch (this.nodeType) {\r\n\t\tcase ONEVSREST: {\r\n\t\t\tMultiClassClassifier mcc = new MultiClassClassifier();\r\n\t\t\tmcc.setClassifier(classifier);\r\n\t\t\tthis.classifier = mcc;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcase ALLPAIRS: {\r\n\t\t\tMultiClassClassifier mcc = new MultiClassClassifier();\r\n\t\t\ttry {\r\n\t\t\t\tmcc.setOptions(new String[] { \"-M\", \"\" + 3 });\r\n\t\t\t} catch (Exception e) {\r\n\t\t\t\te.printStackTrace();\r\n\t\t\t}\r\n\t\t\tmcc.setClassifier(classifier);\r\n\t\t\tthis.classifier = mcc;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcase DIRECT:\r\n\t\t\tthis.classifier = classifier;\r\n\t\t\tbreak;\r\n\t\tdefault:\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void setNodeType(final EMCNodeType nodeType) {\r\n\t\tthis.nodeType = nodeType;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\tStringBuilder sb = new StringBuilder();\r\n\r\n\t\tsb.append(\"(\");\r\n\t\tsb.append(this.classifierID);\r\n\t\tsb.append(\":\");\r\n\t\tsb.append(this.nodeType);\r\n\t\tsb.append(\")\");\r\n\r\n\t\tsb.append(\"{\");\r\n\r\n\t\tboolean first = true;\r\n\t\tfor (MCTreeNode child : this.children) {\r\n\t\t\tif (first) {\r\n\t\t\t\tfirst = false;\r\n\t\t\t} else {\r\n\t\t\t\tsb.append(\",\");\r\n\t\t\t}\r\n\t\t\tsb.append(child);\r\n\t\t}\r\n\t\tsb.append(\"}\");\r\n\t\treturn sb.toString();\r\n\t}\r\n\r\n\tpublic String toStringWithOffset() {\r\n\t\treturn this.toStringWithOffset(\"\");\r\n\t}\r\n\r\n\tpublic String toStringWithOffset(final String offset) {\r\n\t\tStringBuilder sb = new StringBuilder();\r\n\r\n\t\tsb.append(offset);\r\n\t\tsb.append(\"(\");\r\n\t\tsb.append(this.getContainedClasses());\r\n\t\tsb.append(\":\");\r\n\t\tsb.append(this.classifierID);\r\n\t\tsb.append(\":\");\r\n\t\tsb.append(this.nodeType);\r\n\t\tsb.append(\") {\");\r\n\t\tboolean first = true;\r\n\t\tfor (MCTreeNode child : this.children) {\r\n\t\t\tif (first) {\r\n\t\t\t\tfirst = false;\r\n\t\t\t} else {\r\n\t\t\t\tsb.append(\",\");\r\n\t\t\t}\r\n\t\t\tsb.append(\"\\n\");\r\n\t\t\tsb.append(child.toStringWithOffset(offset + \" \"));\r\n\t\t}\r\n\t\tsb.append(\"\\n\");\r\n\t\tsb.append(offset);\r\n\t\tsb.append(\"}\");\r\n\t\treturn sb.toString();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic Iterator<MCTreeNode> iterator() {\r\n\t\tIterator<MCTreeNode> iterator = new Iterator<MCTreeNode>() {\r\n\r\n\t\t\tint currentlyTraversedChild = -1;\r\n\t\t\tIterator<MCTreeNode> childIterator = null;\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic boolean hasNext() {\r\n\t\t\t\tif (this.currentlyTraversedChild < 0) {\r\n\t\t\t\t\treturn true;\r\n\t\t\t\t}\r\n\t\t\t\tif (MCTreeNode.this.children.isEmpty()) {\r\n\t\t\t\t\treturn false;\r\n\t\t\t\t}\r\n\t\t\t\tif (this.childIterator == null) {\r\n\t\t\t\t\tthis.childIterator = MCTreeNode.this.children.get(this.currentlyTraversedChild).iterator();\r\n\t\t\t\t}\r\n\t\t\t\tif (this.childIterator.hasNext()) {\r\n\t\t\t\t\treturn true;\r\n\t\t\t\t}\r\n\t\t\t\tif (this.currentlyTraversedChild == MCTreeNode.this.children.size() - 1) {\r\n\t\t\t\t\treturn false;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/* no set the iterator to the new child and return its val */\r\n\t\t\t\tthis.currentlyTraversedChild++;\r\n\t\t\t\tthis.childIterator = MCTreeNode.this.children.get(this.currentlyTraversedChild).iterator();\r\n\t\t\t\treturn this.childIterator.hasNext();\r\n\t\t\t}\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic MCTreeNode next() {\r\n\t\t\t\tif (this.currentlyTraversedChild == -1) {\r\n\t\t\t\t\tthis.currentlyTraversedChild++;\r\n\t\t\t\t\treturn MCTreeNode.this;\r\n\t\t\t\t} else {\r\n\t\t\t\t\treturn this.childIterator.next();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t};\r\n\t\treturn iterator;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.840474009513855, "alphanum_fraction": 0.840474009513855, "avg_line_length": 55.73684310913086, "blob_id": "e2da2c72660266e9fe841ce046afe3bea7345c24", "content_id": "7ba44fac72c4c70ab623c51d56dc82d4819b0538", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1097, "license_type": "no_license", "max_line_length": 185, "num_lines": 19, "path": "/softwareconfiguration/hasco/src/hasco/variants/forwarddecomposition/HASCOViaFD.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package hasco.variants.forwarddecomposition;\r\n\r\nimport hasco.core.DefaultHASCOPlanningGraphGeneratorDeriver;\r\nimport hasco.core.HASCO;\r\nimport hasco.core.RefinementConfiguredSoftwareConfigurationProblem;\r\nimport jaicore.basic.algorithm.AlgorithmProblemTransformer;\r\nimport jaicore.planning.algorithms.forwarddecomposition.ForwardDecompositionReducer;\r\nimport jaicore.planning.graphgenerators.task.tfd.TFDNode;\r\nimport jaicore.search.core.interfaces.IGraphSearchFactory;\r\nimport jaicore.search.model.probleminputs.GraphSearchProblemInput;\r\n\r\npublic class HASCOViaFD<ISearch, V extends Comparable<V>> extends HASCO<ISearch, TFDNode, String, V> {\r\n\r\n\tpublic HASCOViaFD(RefinementConfiguredSoftwareConfigurationProblem<V> configurationProblem,\r\n\t\t\tIGraphSearchFactory<ISearch, ?, TFDNode, String, V, ?, ?> searchFactory, AlgorithmProblemTransformer<GraphSearchProblemInput<TFDNode, String, V>, ISearch> searchProblemTransformer) {\r\n\t\tsuper(configurationProblem, new DefaultHASCOPlanningGraphGeneratorDeriver<>(new ForwardDecompositionReducer<>()), searchFactory, searchProblemTransformer);\r\n\t}\r\n\t\r\n}\r\n" }, { "alpha_fraction": 0.7946256995201111, "alphanum_fraction": 0.7946256995201111, "avg_line_length": 27.94444465637207, "blob_id": "ec6a4401aec58ecd02a4fe49248c63f4f850da25", "content_id": "181958edd097ba27097e8c1bf0ae1116a1318356", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 521, "license_type": "no_license", "max_line_length": 113, "num_lines": 18, "path": "/JAICore/jaicore-planning/src/jaicore/planning/model/task/ceocstn/CEOCSTNPlanningDomain.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.model.task.ceocstn;\n\nimport java.util.Collection;\n\nimport jaicore.planning.model.ceoc.CEOCOperation;\nimport jaicore.planning.model.task.stn.STNPlanningDomain;\n\n@SuppressWarnings(\"serial\")\npublic class CEOCSTNPlanningDomain<O extends CEOCOperation, M extends OCMethod> extends STNPlanningDomain<O, M> {\n\n\tpublic CEOCSTNPlanningDomain(Collection<O> operations, Collection<M> methods) {\n\t\tsuper(operations, methods);\n\t}\n\t\n\tpublic Collection<O> getOperations() {\n\t\treturn super.getOperations();\n\t}\n}\n" }, { "alpha_fraction": 0.5983740091323853, "alphanum_fraction": 0.6130081415176392, "avg_line_length": 23.639999389648438, "blob_id": "cb7d58c6f51ac931ff728e0288c193a1033ced45", "content_id": "2f34bc0db648de4cb1d77e065f8b085d0a373a36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Gradle", "length_bytes": 615, "license_type": "no_license", "max_line_length": 88, "num_lines": 25, "path": "/JAICore/jaicore-search/build.gradle", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "sourceSets {\n main {\n java {\n srcDir 'src'\n }\n resources {\n srcDir 'conf'\n }\n }\n test {\n \tjava {\n \t\tsrcDir 'test'\n \t}\n }\n}\ndependencies {\n\tcompile project(\":JAICore:jaicore-graph\")\n\tcompile project(\":JAICore:jaicore-basic\")\n\tcompile project(\":JAICore:jaicore-concurrent\")\n\tcompile project(\":JAICore:jaicore-graphvisualizer\")\n\t\n\tcompile group: 'org.knowm.xchart', name: 'xchart', version: '3.5.2'\n\tcompile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.6'\n\tcompile group: 'it.unimi.dsi', name: 'fastutil', version: '8.2.1'\n}" }, { "alpha_fraction": 0.8177965879440308, "alphanum_fraction": 0.8432203531265259, "avg_line_length": 37.33333206176758, "blob_id": "49ca77911efd0204a980442b84762c74caa54e73", "content_id": "f59a6eea52bad17ddfd271d7755a15f5ba57b2b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 236, "license_type": "no_license", "max_line_length": 84, "num_lines": 6, "path": "/softwareconfiguration/mlplan/src/de/upb/crc901/mlplan/multiclass/wekamlplan/sophisticated/featuregen/FeatureGenerator.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package de.upb.crc901.mlplan.multiclass.wekamlplan.sophisticated.featuregen;\r\n\r\nimport de.upb.crc901.mlplan.multiclass.wekamlplan.sophisticated.FeaturePreprocessor;\r\n\r\npublic interface FeatureGenerator extends FeaturePreprocessor {\r\n}\r\n" }, { "alpha_fraction": 0.6980425119400024, "alphanum_fraction": 0.7013744115829468, "avg_line_length": 30.445945739746094, "blob_id": "da45079b7ac4946bd180f1257ca8527574555a86", "content_id": "dbe9d77bc5d4598f6ba45560537688298bf561ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2401, "license_type": "no_license", "max_line_length": 121, "num_lines": 74, "path": "/softwareconfiguration/mlplan/src/de/upb/crc901/mlplan/multiclass/wekamlplan/sophisticated/featuregen/InteractingFeatures.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package de.upb.crc901.mlplan.multiclass.wekamlplan.sophisticated.featuregen;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\n\r\nimport jaicore.basic.sets.SetUtil;\r\nimport jaicore.basic.sets.SetUtil.Pair;\r\nimport weka.core.Attribute;\r\nimport weka.core.DenseInstance;\r\nimport weka.core.Instance;\r\nimport weka.core.Instances;\r\n\r\npublic class InteractingFeatures implements FeatureGenerator {\r\n\t\r\n\tprivate boolean isPrepared;\r\n\tprivate List<Integer> indicesToInteract = new ArrayList<>();\r\n\r\n\t@Override\r\n\tpublic void prepare(Instances data) throws Exception {\r\n\t\tArrayList<Attribute> attributes = new ArrayList<>();\r\n\t\tindicesToInteract.clear();\r\n\t\tfor (int i = 0; i < data.numAttributes(); i++) {\r\n\t\t\tif (data.attribute(i).isNumeric()) {\r\n\t\t\t\tattributes.add(new weka.core.Attribute(\"q\" + i, false));\r\n\t\t\t\tindicesToInteract.add(i);\r\n\t\t\t}\r\n\t\t}\r\n//\t\tInstances squares = new Instances(\"squares\", attributes, data.size());\r\n\t\tisPrepared = true;\r\n\t}\r\n\t\r\n\tprivate Instances getEmptyDataset() {\r\n\t\tif (!isPrepared)\r\n\t\t\tthrow new IllegalStateException(\"Cannot get empty dataset before preparation\");\r\n\t\tArrayList<Attribute> attributes = new ArrayList<>();\r\n\t\tfor (Pair<Integer, Integer> pair : SetUtil.cartesianProduct(indicesToInteract, indicesToInteract)) {\r\n\t\t\tif (pair.getX() < pair.getY()) {\r\n\t\t\t\tattributes.add(new Attribute(\"interaction_\" + pair.getX() + \"_\" + pair.getY(), false));\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn new Instances(\"interaction\", attributes, 0);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic Instance apply(Instance data) throws Exception {\r\n\t\tInstance newInstance = new DenseInstance(((int) Math.pow(indicesToInteract.size(), 2) - indicesToInteract.size()) / 2);\r\n\t\tint index = 0;\r\n\t\tfor (Pair<Integer, Integer> pair : SetUtil.cartesianProduct(indicesToInteract, indicesToInteract)) {\r\n\t\t\tif (pair.getX() < pair.getY()) {\r\n\t\t\t\tnewInstance.setValue(index ++, data.value(pair.getX()) * data.value(pair.getY()));\r\n\t\t\t}\r\n\t\t}\r\n\t\tInstances dataset = getEmptyDataset();\r\n\t\tdataset.add(newInstance);\r\n\t\tnewInstance.setDataset(dataset);\r\n\t\treturn newInstance;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic Instances apply(Instances data) throws Exception {\r\n\t\tInstances newDataset = getEmptyDataset();\r\n\t\tfor (Instance inst : data) {\r\n\t\t\tInstance modInst = apply(inst);\r\n\t\t\tnewDataset.add(modInst);\r\n\t\t\tmodInst.setDataset(newDataset);\r\n\t\t}\r\n\t\treturn newDataset;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean isPrepared() {\r\n\t\treturn isPrepared;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6696781516075134, "alphanum_fraction": 0.6719367504119873, "avg_line_length": 37.5, "blob_id": "7818a6908aaaf19cddbeb1bbde014fd1675aaff9", "content_id": "8522b138f3f22bafb78372e4c9616eb92704fe08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1771, "license_type": "no_license", "max_line_length": 80, "num_lines": 46, "path": "/softwareconfiguration/mlplan/src/de/upb/crc901/mlplan/metamining/similaritymeasures/IHeterogenousSimilarityMeasureComputer.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package de.upb.crc901.mlplan.metamining.similaritymeasures;\n\nimport org.nd4j.linalg.api.ndarray.INDArray;\n\n/**\n * Encapsulates a model that is trained to compute the similarity between two\n * multidimensional measures, e.g. data set meta features, algorithm meta\n * features and algorithm performance on a data set.\n * \n * @author Helena Graf\n *\n */\npublic interface IHeterogenousSimilarityMeasureComputer {\n\n\t/**\n\t * Build a model based on training data that can then be used to estimate the\n\t * similarity of two measures for a new problem.\n\t * \n\t * @param X\n\t * Feature values for instances of the first measure (One row =\n\t * features of one instance, e.g. meta features of a data set)\n\t * @param W\n\t * Feature values for instances of the second measure (One row =\n\t * features of one instance, e.g. a characterization of a machine\n\t * learning pipeline)\n\t * @param R\n\t * A matrix giving an indication of how good of a match a specific\n\t * instance of the first measure is to a specific instance of the\n\t * second measure, i.e. how well a pipeline performs on a data set\n\t */\n\tpublic void build(INDArray X, INDArray W, INDArray R);\n\n\t/**\n\t * Compute the 'quality of the match' of given feature values for a new problem\n\t * instance based on the training.\n\t * \n\t * @param x\n\t * Feature values for the instance for the first measure (e.g. meta\n\t * data of a new data set)\n\t * @param w\n\t * Feature values for the instance for the second measure (e.g. a\n\t * characterization of machine learning pipeline)\n\t * @return The quality of the match, or similarity for the given vectors\n\t */\n\tpublic double computeSimilarity(INDArray x, INDArray w);\n}\n" }, { "alpha_fraction": 0.8352941274642944, "alphanum_fraction": 0.8352941274642944, "avg_line_length": 20.25, "blob_id": "b124b80fd433473f2deaa616d7b71ed03d7fc730", "content_id": "7505c0337f45bc4c1faf3a87bc3f52b66887acac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 85, "license_type": "no_license", "max_line_length": 51, "num_lines": 4, "path": "/JAICore/jaicore-graphvisualizer/src/jaicore/graphvisualizer/events/graphEvents/GraphEvent.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.graphvisualizer.events.graphEvents;\n\npublic interface GraphEvent {\n}\n" }, { "alpha_fraction": 0.6368943452835083, "alphanum_fraction": 0.6468184590339661, "avg_line_length": 22.154930114746094, "blob_id": "4c98887d4368381958c28759043d8ef877cf576d", "content_id": "8ff0ad10aca4cb812bca61a7cd40543e435aed8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1713, "license_type": "no_license", "max_line_length": 62, "num_lines": 71, "path": "/softwareconfiguration/mlplan/testrsc/hascoSL/template.py", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "import sys\r\nimport arffcontainer\r\nimport numpy as np\r\nimport sklearn.metrics\r\nfrom sklearn.externals import joblib\r\n#import#\r\n\r\nmode=sys.argv[1]\r\n\r\nif mode == \"trainAndPredict\":\r\n\ttrainFile=sys.argv[2]\r\n\ttestFile=sys.argv[3]\r\n\tobjFile=sys.argv[4]\r\n\t\r\n\ttrainData = arffcontainer.parse(trainFile)\r\n\tX_train = trainData.input_matrix\r\n\ty_train = []\r\n\tfor crow in trainData.output_matrix:\r\n\t for x in range(0, len(crow)):\r\n\t\t if crow[x] == 1:\r\n\t\t\t y_train.append(x)\r\n\t\r\n\ttestData = arffcontainer.parse(testFile)\r\n\tX_test = testData.input_matrix\r\n\ty_test = []\r\n\tfor crow in testData.output_matrix:\r\n\t for x in range(0, len(crow)):\r\n\t\t if crow[x] == 1:\r\n\t\t\t y_test.append(x)\r\n\t \r\n\tmlpipeline = #pipeline#\r\n\t\r\n\tmlpipeline.fit(X_train, y_train)\r\n\tjoblib.dump(mlpipeline, objFile)\r\n\t\r\n\ty_hat = mlpipeline.predict(X_test)\r\n\tprint(y_hat)\r\nelif mode == \"train\":\r\n\ttrainFile=sys.argv[2]\r\n\tobjFile=sys.argv[3]\r\n\t\r\n\ttrainData = arffcontainer.parse(trainFile)\r\n\tX_train = trainData.input_matrix\r\n\ty_train = []\r\n\tfor crow in trainData.output_matrix:\r\n\t for x in range(0, len(crow)):\r\n\t\t if crow[x] == 1:\r\n\t\t\t y_train.append(x)\r\n\t\t \r\n\tmlpipeline = #pipeline#\r\n\t\r\n\tmlpipeline.fit(X_train, y_train)\r\n\tjoblib.dump(mlpipeline, objFile)\r\nelif mode == \"predict\":\r\n\ttestFile=sys.argv[2]\r\n\tobjFile=sys.argv[3]\r\n\t\r\n\ttestData = arffcontainer.parse(testFile)\r\n\tX_test = testData.input_matrix\r\n\ty_test = []\r\n\tfor crow in testData.output_matrix:\r\n\t for x in range(0, len(crow)):\r\n\t\t if crow[x] == 1:\r\n\t\t\t y_test.append(x)\r\n\t\r\n\tmlpipeline = joblib.load(objFile)\t \r\n\ty_hat = mlpipeline.predict(X_test)\r\n\tprint(y_hat)\r\n\t\r\n\terrorRate = 1 - sklearn.metrics.accuracy_score(y_test, y_hat)\r\n\tprint(errorRate)" }, { "alpha_fraction": 0.8412483334541321, "alphanum_fraction": 0.8412483334541321, "avg_line_length": 50.64285659790039, "blob_id": "cc6c9202b5a47257bcdd738b8bc700fc1b6b73ff", "content_id": "64240e4e0a4094e3baea48ef79e516e5c87a7dda", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 737, "license_type": "no_license", "max_line_length": 177, "num_lines": 14, "path": "/JAICore/jaicore-search/test/jaicore/search/testproblems/npuzzle/standard/NPuzzleToGeneralTraversalTreeReducer.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.testproblems.npuzzle.standard;\r\n\r\nimport jaicore.basic.algorithm.AlgorithmProblemTransformer;\r\nimport jaicore.search.core.interfaces.EdgeCountingSolutionEvaluator;\r\nimport jaicore.search.model.probleminputs.GeneralEvaluatedTraversalTree;\r\n\r\npublic class NPuzzleToGeneralTraversalTreeReducer implements AlgorithmProblemTransformer<NPuzzleProblem, GeneralEvaluatedTraversalTree<NPuzzleNode, String, Double>>{\r\n\r\n\t@Override\r\n\tpublic GeneralEvaluatedTraversalTree<NPuzzleNode, String, Double> transform(NPuzzleProblem problem) {\r\n\t\treturn new GeneralEvaluatedTraversalTree<>(new NPuzzleGenerator(problem.getBoard()), n -> new EdgeCountingSolutionEvaluator<NPuzzleNode>().evaluateSolution(n.externalPath()));\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.7251772880554199, "alphanum_fraction": 0.728723406791687, "avg_line_length": 27.81751823425293, "blob_id": "40fc06080adca36a59c9163ebaf0ed51088ba1f8", "content_id": "73a88d47298dcecd94bd720155930ab5ae2af246", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3948, "license_type": "no_license", "max_line_length": 128, "num_lines": 137, "path": "/JAICore/jaicore-planning/src/jaicore/planning/graphgenerators/pddl/PDDLGraphGenerator.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.graphgenerators.pddl;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport fr.uga.pddl4j.encoding.CodedProblem;\nimport fr.uga.pddl4j.heuristics.relaxation.Heuristic;\nimport fr.uga.pddl4j.heuristics.relaxation.HeuristicToolKit;\nimport fr.uga.pddl4j.planners.ProblemFactory;\nimport fr.uga.pddl4j.planners.hsp.Node;\nimport fr.uga.pddl4j.util.BitOp;\nimport fr.uga.pddl4j.util.BitState;\nimport fr.uga.pddl4j.util.SequentialPlan;\nimport jaicore.search.model.travesaltree.AbstractGraphGenerator;\nimport jaicore.search.model.travesaltree.NodeExpansionDescription;\nimport jaicore.search.model.travesaltree.NodeType;\nimport jaicore.search.structure.graphgenerator.NodeGoalTester;\nimport jaicore.search.structure.graphgenerator.SingleRootGenerator;\nimport jaicore.search.structure.graphgenerator.SuccessorGenerator;\n\npublic class PDDLGraphGenerator extends AbstractGraphGenerator<PDDLNode,String> {\n\n\tProblemFactory factory;\n\tCodedProblem problem;\n\t\n /**\n * The type of heuristics that must use to solve the problem.\n */\n private Heuristic.Type heuristicType;\n\t\n\tHeuristic heuristic;\n\t\n\t/**\n\t * Constructor for the pddlgraphgenerator which gets a domain file and a problem file\n\t * @param domain\n\t * \t\tThe domain file.\n\t * @param problem\n\t * \t\tThe problem file.\n\t */\n\tpublic PDDLGraphGenerator(File domainFile, File problemFile) {\n\t\tthis.factory= new ProblemFactory();\n\t\ttry {\n\t\t\tfactory.parse(domainFile, problemFile);\n\t\t\tproblem = factory.encode();\n\t\t\tthis.setHeuristicType(Heuristic.Type.FAST_FORWARD);\n\t\t\theuristic = HeuristicToolKit.createHeuristic(this.heuristicType, problem);\n\t\t} catch (IOException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t\t\n\t\t\n\t\t\n\t}\n\n\t@Override\n\tpublic SingleRootGenerator<PDDLNode> getRootGenerator() {\n\t\t//Create a root node and return it\n\t\tBitState init = new BitState(problem.getInit());\n\t\treturn () -> new PDDLNode(new Node(init, null, -1, 0, heuristic.estimate(init, problem.getGoal())), this.nextID());\n\t}\n\n\t@Override\n\tpublic SuccessorGenerator<PDDLNode, String> getSuccessorGenerator() {\n\t\treturn s->{\n\t\t\tNode current = s.getNode();\n\t\t\tList<NodeExpansionDescription<PDDLNode, String>> list = new ArrayList<>();\n\t\t\tfor(BitOp op: problem.getOperators()) {\n\t\t\t\tif(op.isApplicable(current)) {\n\t\t\t\t\tNode state = new Node(current);\n\t\t\t\t\top.getCondEffects().stream().filter(ce -> current.satisfy(ce.getCondition())).forEach(ce ->\n // Apply the effect to the successor node\n state.apply(ce.getEffects()));\n\t\t\t\t\tlist.add(new NodeExpansionDescription<PDDLNode, String>(s, new PDDLNode(state, this.nextID()), \"edge label\", NodeType.OR));\n//\t\t\t\t\tlist.add(new NodeExpansionDescription<Node, String>(s, state, \"edge label\", NodeType.OR));\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn list;\n\t\t};\n\t}\n\n\t@Override\n\tpublic NodeGoalTester<PDDLNode> getGoalTester() {\n\t\treturn state ->{\n\t\t\treturn state.getNode().satisfy(problem.getGoal());\n\t\t};\n\t}\n\n\t@Override\n\tpublic boolean isSelfContained() {\n\t\treturn false;\n\t}\n\n\tpublic Heuristic.Type getHeuristicType() {\n\t\treturn heuristicType;\n\t}\n\n\tpublic void setHeuristicType(Heuristic.Type heuristicType) {\n\t\tthis.heuristicType = heuristicType;\n\t}\n\n\tpublic Heuristic getHeuristic() {\n\t\treturn heuristic;\n\t}\n\n\tpublic void setHeuristic(Heuristic heuristic) {\n\t\tthis.heuristic = heuristic;\n\t}\n\n\tpublic CodedProblem getProblem() {\n\t\treturn problem;\n\t}\n\n\tpublic void setProblem(CodedProblem problem) {\n\t\tthis.problem = problem;\n\t}\n\t\n\t//extracts the plan similar to extractPlan in HSP from pddl4j\n\tpublic SequentialPlan extractPlan(List<PDDLNode> solution) {\n\t\tint i = solution.size()-1;\n\t\tNode n = solution.get(i).getNode();\n\t\tSequentialPlan plan = new SequentialPlan();\n\t\twhile(n.getOperator() != -1) {\n\t\t\tfinal BitOp op = problem.getOperators().get(n.getOperator());\n\t\t\tplan.add(0, op);\n\t\t\ti--;\n\t\t\tn = solution.get(i).getNode();\n\t\t}\n\t\t\n\t\treturn plan;\n\t\t\n\t}\n\t\n}\n" }, { "alpha_fraction": 0.7437471151351929, "alphanum_fraction": 0.744846522808075, "avg_line_length": 37.43309783935547, "blob_id": "417967f59ff89b8ed62a06f6ff3b34a95f4f5d06", "content_id": "0efe2316ab74f56783afc50a9509c11886d599fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 10915, "license_type": "no_license", "max_line_length": 222, "num_lines": 284, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/awastar/AwaStarSearch.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.awastar;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.PriorityQueue;\nimport java.util.Queue;\nimport java.util.concurrent.TimeoutException;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.google.common.eventbus.Subscribe;\n\nimport jaicore.basic.algorithm.AlgorithmEvent;\nimport jaicore.basic.algorithm.AlgorithmFinishedEvent;\nimport jaicore.basic.algorithm.AlgorithmInitializedEvent;\nimport jaicore.basic.algorithm.AlgorithmState;\nimport jaicore.graphvisualizer.events.graphEvents.GraphInitializedEvent;\nimport jaicore.graphvisualizer.events.graphEvents.NodeReachedEvent;\nimport jaicore.graphvisualizer.events.graphEvents.NodeTypeSwitchEvent;\nimport jaicore.search.algorithms.standard.AbstractORGraphSearch;\nimport jaicore.search.algorithms.standard.bestfirst.events.EvaluatedSearchSolutionCandidateFoundEvent;\nimport jaicore.search.algorithms.standard.bestfirst.events.GraphSearchSolutionCandidateFoundEvent;\nimport jaicore.search.algorithms.standard.bestfirst.nodeevaluation.ICancelableNodeEvaluator;\nimport jaicore.search.algorithms.standard.bestfirst.nodeevaluation.INodeEvaluator;\nimport jaicore.search.algorithms.standard.bestfirst.nodeevaluation.ISolutionReportingNodeEvaluator;\nimport jaicore.search.core.interfaces.GraphGenerator;\nimport jaicore.search.model.other.EvaluatedSearchGraphPath;\nimport jaicore.search.model.probleminputs.GeneralEvaluatedTraversalTree;\nimport jaicore.search.model.travesaltree.Node;\nimport jaicore.search.model.travesaltree.NodeExpansionDescription;\nimport jaicore.search.structure.graphgenerator.GoalTester;\nimport jaicore.search.structure.graphgenerator.NodeGoalTester;\nimport jaicore.search.structure.graphgenerator.PathGoalTester;\nimport jaicore.search.structure.graphgenerator.SingleRootGenerator;\nimport jaicore.search.structure.graphgenerator.SuccessorGenerator;\n\n/**\n * This is a modified version of the AWA* algorithm for problems without admissible heuristic. Important differences are: - no early termination if a best-f-valued solution is found as f is not optimistic\n * \n * @author lbrandt2 and fmohr\n *\n * @param <T>\n * @param <A>\n * @param <V>\n */\npublic class AwaStarSearch<I extends GeneralEvaluatedTraversalTree<T, A, V>, T, A, V extends Comparable<V>>\n\t\textends AbstractORGraphSearch<I, EvaluatedSearchGraphPath<T, A, V>, T, A, V, Node<T, V>, A> {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(AwaStarSearch.class);\n\n\tprivate boolean timeouted = false;\n\n\tprivate SingleRootGenerator<T> rootNodeGenerator;\n\tprivate SuccessorGenerator<T, A> successorGenerator;\n\tprivate GoalTester<T> goalTester;\n\tprivate INodeEvaluator<T, V> nodeEvaluator;\n\tprivate Queue<Node<T, V>> closedList, suspendList, openList;\n\tprivate int currentLevel = -1;\n\tprivate int windowSize;\n\tprivate List<EvaluatedSearchGraphPath<T, A, V>> unconfirmedSolutions = new ArrayList<>(); // these are solutions emitted on the basis of the node evaluator but whose solutions have not been found in the original graph yet\n\tprivate List<EvaluatedSearchSolutionCandidateFoundEvent<T, A, V>> unreturnedSolutionEvents = new ArrayList<>();\n\n\tprivate int timeoutInMS = Integer.MAX_VALUE;\n\n\tpublic AwaStarSearch(I problem) {\n\t\tsuper(problem);\n\t\trootNodeGenerator = (SingleRootGenerator<T>) problem.getGraphGenerator().getRootGenerator();\n\t\tsuccessorGenerator = problem.getGraphGenerator().getSuccessorGenerator();\n\t\tgoalTester = problem.getGraphGenerator().getGoalTester();\n\t\tnodeEvaluator = problem.getNodeEvaluator();\n\n\t\tclosedList = new PriorityQueue<>();\n\t\tsuspendList = new PriorityQueue<>();\n\t\topenList = new PriorityQueue<>();\n\t\twindowSize = 0;\n\t\tif (nodeEvaluator instanceof ISolutionReportingNodeEvaluator) {\n\t\t\t((ISolutionReportingNodeEvaluator) nodeEvaluator).registerSolutionListener(this);\n\t\t}\n\t}\n\n\tprivate AlgorithmEvent processUntilNextEvent() throws Exception {\n\n\t\tlogger.info(\"Searching for next solution.\");\n\n\t\t/* return pending solutions if there are any */\n\t\twhile (unreturnedSolutionEvents.isEmpty()) {\n\n\t\t\t/* check whether execution shoud be halted */\n\t\t\tcheckTermination();\n\n\t\t\t/* if the current graph has been exhausted, add all suspended nodes to OPEN and increase window size */\n\t\t\tif (openList.isEmpty()) {\n\t\t\t\tif (suspendList.isEmpty()) {\n\t\t\t\t\tlogger.info(\"The whole graph has been exhausted. No more solutions can be found!\");\n\t\t\t\t\treturn new AlgorithmFinishedEvent();\n\t\t\t\t} else {\n\t\t\t\t\tlogger.info(\"Search with window size {} is exhausted. Reactivating {} suspended nodes and incrementing window size.\", windowSize, suspendList.size());\n\t\t\t\t\topenList.addAll(suspendList);\n\t\t\t\t\tsuspendList.clear();\n\t\t\t\t\twindowSize++;\n\t\t\t\t\tcurrentLevel = -1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlogger.info(\"Running core algorithm with window size {} and current level {}. {} items are in OPEN\", windowSize, currentLevel, openList.size());\n\t\t\twindowAStar();\n\t\t}\n\t\tEvaluatedSearchSolutionCandidateFoundEvent<T, A, V> toReturn = unreturnedSolutionEvents.get(0);\n\t\tunreturnedSolutionEvents.remove(0);\n\t\treturn toReturn;\n\t}\n\n\tprivate void windowAStar() throws Exception {\n\t\twhile (!openList.isEmpty()) {\n\t\t\tcheckTermination();\n\t\t\tif (!unreturnedSolutionEvents.isEmpty()) {\n\t\t\t\tlogger.info(\"Not doing anything because there are still unreturned solutions.\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tNode<T, V> n = openList.peek();\n\t\t\topenList.remove(n);\n\t\t\tclosedList.add(n);\n\t\t\tif (!n.isGoal())\n\t\t\t\tpostEvent(new NodeTypeSwitchEvent<>(n, \"or_closed\"));\n\n\t\t\t/* check whether this node is outside the window and suspend it */\n\t\t\tint nLevel = n.externalPath().size() - 1;\n\t\t\tif (nLevel <= (currentLevel - windowSize)) {\n\t\t\t\tclosedList.remove(n);\n\t\t\t\tsuspendList.add(n);\n\t\t\t\tlogger.info(\"Suspending node {} with level {}, which is lower than {}\", n, nLevel, currentLevel - windowSize);\n\t\t\t\tpostEvent(new NodeTypeSwitchEvent<>(n, \"or_suspended\"));\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/* if the level should even be increased, do this now */\n\t\t\tif (nLevel > currentLevel) {\n\t\t\t\tlogger.info(\"Switching level from {} to {}\", currentLevel, nLevel);\n\t\t\t\tcurrentLevel = nLevel;\n\t\t\t}\n\t\t\tcheckTermination();\n\n\t\t\t/* compute successors of the expanded node */\n\t\t\tCollection<NodeExpansionDescription<T, A>> successors = successorGenerator.generateSuccessors(n.getPoint());\n\t\t\tlogger.info(\"Expanding {}. Identified {} successors.\", n.getPoint(), successors.size());\n\t\t\tfor (NodeExpansionDescription<T, A> expansionDescription : successors) {\n\t\t\t\tcheckTermination();\n\t\t\t\tNode<T, V> nPrime = new Node<>(n, expansionDescription.getTo());\n\t\t\t\tif (goalTester instanceof NodeGoalTester<?>) {\n\t\t\t\t\tnPrime.setGoal(((NodeGoalTester<T>) goalTester).isGoal(nPrime.getPoint()));\n\t\t\t\t} else if (goalTester instanceof PathGoalTester<?>) {\n\t\t\t\t\tnPrime.setGoal(((PathGoalTester<T>) goalTester).isGoal(nPrime.externalPath()));\n\t\t\t\t}\n\t\t\t\tV nPrimeScore = nodeEvaluator.f(nPrime);\n\n\t\t\t\t/* ignore nodes whose value cannot be determined */\n\t\t\t\tif (nPrimeScore == null) {\n\t\t\t\t\tlogger.debug(\"Discarding node {} for which no f-value could be computed.\", nPrime);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t/* determine whether this is a goal node */\n\t\t\t\tif (nPrime.isGoal()) {\n\t\t\t\t\tList<T> newSolution = nPrime.externalPath();\n\t\t\t\t\tEvaluatedSearchGraphPath<T, A, V> solution = new EvaluatedSearchGraphPath<>(newSolution, null, nPrimeScore);\n\t\t\t\t\tregisterNewSolutionCandidate(solution);\n\t\t\t\t}\n\n\t\t\t\tif (!openList.contains(nPrime) && !closedList.contains(nPrime) && !suspendList.contains(nPrime)) {\n\t\t\t\t\tnPrime.setParent(n);\n\t\t\t\t\tnPrime.setInternalLabel(nPrimeScore);\n\t\t\t\t\tif (!nPrime.isGoal())\n\t\t\t\t\t\topenList.add(nPrime);\n\t\t\t\t\tpostEvent(new NodeReachedEvent<>(n, nPrime, nPrime.isGoal() ? \"or_solution\" : \"or_open\"));\n\t\t\t\t} else if (openList.contains(nPrime) || suspendList.contains(nPrime)) {\n\t\t\t\t\tV oldScore = nPrime.getInternalLabel();\n\t\t\t\t\tif (oldScore != null && oldScore.compareTo(nPrimeScore) > 0) {\n\t\t\t\t\t\tnPrime.setParent(n);\n\t\t\t\t\t\tnPrime.setInternalLabel(nPrimeScore);\n\t\t\t\t\t}\n\t\t\t\t} else if (closedList.contains(nPrime)) {\n\t\t\t\t\tV oldScore = nPrime.getInternalLabel();\n\t\t\t\t\tif (oldScore != null && oldScore.compareTo(nPrimeScore) > 0) {\n\t\t\t\t\t\tnPrime.setParent(n);\n\t\t\t\t\t\tnPrime.setInternalLabel(nPrimeScore);\n\t\t\t\t\t}\n\t\t\t\t\tif (!nPrime.isGoal())\n\t\t\t\t\t\topenList.add(nPrime);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t@Subscribe\n\tpublic void receiveSolutionEvent(EvaluatedSearchSolutionCandidateFoundEvent<T, A, V> solutionEvent) {\n\t\tregisterNewSolutionCandidate(solutionEvent.getSolutionCandidate());\n\t\tunconfirmedSolutions.add(solutionEvent.getSolutionCandidate());\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic EvaluatedSearchSolutionCandidateFoundEvent<T, A, V> registerNewSolutionCandidate(EvaluatedSearchGraphPath<T, A, V> solution) {\n\t\tEvaluatedSearchSolutionCandidateFoundEvent<T, A, V> event = (EvaluatedSearchSolutionCandidateFoundEvent<T, A, V>) registerSolution(solution);\n\t\tunreturnedSolutionEvents.add(event);\n\t\treturn event;\n\t}\n\n\t@Override\n\tpublic AlgorithmEvent nextWithException() throws Exception {\n\t\t// logger.info(\"Next step in {}. State is {}\", this, getState());\n\t\tcheckTermination();\n\t\tswitch (getState()) {\n\t\tcase created: {\n\t\t\tactivateTimeoutTimer(\"AWA*-Timeouter\");\n\t\t\tT externalRootNode = rootNodeGenerator.getRoot();\n\t\t\tNode<T, V> rootNode = new Node<T, V>(null, externalRootNode);\n\t\t\tlogger.info(\"Initializing graph and OPEN with {}.\", rootNode);\n\t\t\topenList.add(rootNode);\n\t\t\tpostEvent(new GraphInitializedEvent<>(rootNode));\n\t\t\trootNode.setInternalLabel(this.nodeEvaluator.f(rootNode));\n\t\t\tswitchState(AlgorithmState.active);\n\t\t\tAlgorithmEvent e = new AlgorithmInitializedEvent();\n\t\t\tpostEvent(e);\n\t\t\treturn e;\n\t\t}\n\t\tcase active: {\n\t\t\tAlgorithmEvent event;\n\t\t\ttry {\n\t\t\t\tevent = processUntilNextEvent();\n\t\t\t\tif (event instanceof AlgorithmFinishedEvent) {\n\t\t\t\t\tsuper.unregisterThreadAndShutdown();\n\t\t\t\t}\n\t\t\t} catch (TimeoutException e) {\n\t\t\t\tsuper.unregisterThreadAndShutdown();\n\t\t\t\tevent = new AlgorithmFinishedEvent();\n\t\t\t}\n\t\t\tif (!(event instanceof GraphSearchSolutionCandidateFoundEvent)) { // solution events are sent directly over the event bus\n\t\t\t\tpostEvent(event);\n\t\t\t}\n\t\t\treturn event;\n\t\t}\n\t\tdefault:\n\t\t\tthrow new IllegalStateException(\"Cannot do anything in state \" + getState());\n\t\t}\n\t}\n\n\tprotected void shutdown() {\n\n\t\tif (isShutdownInitialized())\n\t\t\treturn;\n\n\t\t/* set state to inactive*/\n\t\tlogger.info(\"Invoking shutdown routine ...\");\n\n\t\tsuper.shutdown();\n\n\t\t/* cancel node evaluator */\n\t\tif (this.nodeEvaluator instanceof ICancelableNodeEvaluator) {\n\t\t\tlogger.info(\"Canceling node evaluator.\");\n\t\t\t((ICancelableNodeEvaluator) this.nodeEvaluator).cancel();\n\t\t}\n\n\t}\n\n\t@Override\n\tpublic void setNumCPUs(int numberOfCPUs) {\n\t\tlogger.warn(\"Currently no support for parallelization\");\n\t}\n\n\t@Override\n\tpublic int getNumCPUs() {\n\t\treturn 1;\n\t}\n\n\t@Override\n\tpublic GraphGenerator<T, A> getGraphGenerator() {\n\t\treturn problem.getGraphGenerator();\n\t}\n\n\t@Override\n\tpublic EvaluatedSearchGraphPath<T, A, V> getSolutionProvidedToCall() {\n\t\treturn getBestSeenSolution();\n\t}\n}\n" }, { "alpha_fraction": 0.5892472863197327, "alphanum_fraction": 0.7139784693717957, "avg_line_length": 25.47058868408203, "blob_id": "4b95a94f22dd24cfe8a1c7a4a2558d6f6806b805", "content_id": "84771aec69429e627f6d7b992daf83829bcfd501", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 465, "license_type": "no_license", "max_line_length": 88, "num_lines": 17, "path": "/JAICore/jaicore-experiments/examples/mlexample/setup.properties", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "mem.max = 4098\r\ncpu.max = 1\r\n\r\ndb.host = isys-db.cs.upb.de\r\ndb.username = johndoe\r\ndb.password = NYpYtgpGD37OerWD\r\ndb.database = johndoe\r\ndb.table = results\r\n\r\nkeyfields = datasets, classifiers, seeds\r\nresultfields = loss, traintime\r\n\r\nseeds = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30\r\nclassifiers = weka.classifiers.trees.J48, weka.classifiers.functions.SMO\r\ndatasets = autos,car,glass\r\n\r\ndatasetfolder = ./examples/mlexample/data" }, { "alpha_fraction": 0.7952041625976562, "alphanum_fraction": 0.7990926504135132, "avg_line_length": 30.82978630065918, "blob_id": "c5a63f68d515ea3676a1916a5ae61f67a0f5027d", "content_id": "6a3108492a47b12e2512c0d3b24fd395ce5c1d76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1543, "license_type": "no_license", "max_line_length": 130, "num_lines": 47, "path": "/softwareconfiguration/mlplan/src/de/upb/crc901/mlplan/multiclass/wekamlplan/MLPlanWekaBuilder.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package de.upb.crc901.mlplan.multiclass.wekamlplan;\r\n\r\nimport java.io.File;\r\n\r\nimport de.upb.crc901.mlplan.multiclass.MultiClassPerformanceMeasure;\r\n\r\npublic class MLPlanWekaBuilder {\r\n\tprivate File searchSpaceConfigFile = new File(\"conf/automl/searchmodels/weka/weka-all-autoweka.json\");\r\n\tprivate File alhorithmConfigFile = new File(\"conf/mlplan.properties\");\r\n\tprivate MultiClassPerformanceMeasure performanceMeasure = MultiClassPerformanceMeasure.ERRORRATE;\r\n\r\n\tpublic MLPlanWekaBuilder() { }\r\n\t\r\n\tpublic MLPlanWekaBuilder(File searchSpaceConfigFile, File alhorithmConfigFile, MultiClassPerformanceMeasure performanceMeasure) {\r\n\t\tsuper();\r\n\t\tthis.searchSpaceConfigFile = searchSpaceConfigFile;\r\n\t\tthis.alhorithmConfigFile = alhorithmConfigFile;\r\n\t\tthis.performanceMeasure = performanceMeasure;\r\n\t}\r\n\r\n\tpublic File getSearchSpaceConfigFile() {\r\n\t\treturn searchSpaceConfigFile;\r\n\t}\r\n\r\n\tpublic File getAlhorithmConfigFile() {\r\n\t\treturn alhorithmConfigFile;\r\n\t}\r\n\r\n\tpublic MultiClassPerformanceMeasure getPerformanceMeasure() {\r\n\t\treturn performanceMeasure;\r\n\t}\r\n\r\n\tpublic MLPlanWekaBuilder withSearchSpaceConfigFile(File searchSpaceConfig) {\r\n\t\tthis.searchSpaceConfigFile = searchSpaceConfig;\r\n\t\treturn this;\r\n\t}\r\n\r\n\tpublic MLPlanWekaBuilder withAlgorithmConfigFile(File algorithmConfigFile) {\r\n\t\tthis.alhorithmConfigFile = algorithmConfigFile;\r\n\t\treturn this;\r\n\t}\r\n\r\n\tpublic MLPlanWekaBuilder withPerformanceMeasure(MultiClassPerformanceMeasure performanceMeasure) {\r\n\t\tthis.performanceMeasure = performanceMeasure;\r\n\t\treturn this;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.779891312122345, "alphanum_fraction": 0.779891312122345, "avg_line_length": 34.79999923706055, "blob_id": "ab7146a837e6a7681fee53d8d641aba3c00cec0c", "content_id": "c3ce82739795359b7cbe30b4b9cc206b625864c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 368, "license_type": "no_license", "max_line_length": 128, "num_lines": 10, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/bestfirst/StandardBestFirst.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.bestfirst;\r\n\r\nimport jaicore.search.model.probleminputs.GeneralEvaluatedTraversalTree;\r\n\r\npublic class StandardBestFirst<N,A,V extends Comparable<V>> extends BestFirst<GeneralEvaluatedTraversalTree<N, A, V>, N, A, V> {\r\n\r\n\tpublic StandardBestFirst(GeneralEvaluatedTraversalTree<N, A, V> problem) {\r\n\t\tsuper(problem);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7402099967002869, "alphanum_fraction": 0.744998574256897, "avg_line_length": 45.38151168823242, "blob_id": "5f9bdcca2040814b27a45778c698041cc49442fc", "content_id": "70b2b0ac40602c7b9534da868e7d303107bece22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 28192, "license_type": "no_license", "max_line_length": 285, "num_lines": 595, "path": "/softwareconfiguration/hasco/src/hasco/variants/forwarddecomposition/twophase/TwoPhaseHASCO.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package hasco.variants.forwarddecomposition.twophase;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.Collection;\r\nimport java.util.Collections;\r\nimport java.util.Iterator;\r\nimport java.util.List;\r\nimport java.util.NoSuchElementException;\r\nimport java.util.Queue;\r\nimport java.util.Random;\r\nimport java.util.concurrent.ExecutorService;\r\nimport java.util.concurrent.Executors;\r\nimport java.util.concurrent.LinkedBlockingQueue;\r\nimport java.util.concurrent.Semaphore;\r\nimport java.util.concurrent.TimeUnit;\r\nimport java.util.concurrent.atomic.AtomicInteger;\r\nimport java.util.stream.Collectors;\r\n\r\nimport org.aeonbits.owner.ConfigFactory;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.google.common.eventbus.EventBus;\r\nimport com.google.common.eventbus.Subscribe;\r\n\r\nimport hasco.core.HASCOSolutionCandidate;\r\nimport hasco.core.RefinementConfiguredSoftwareConfigurationProblem;\r\nimport hasco.model.ComponentInstance;\r\nimport hasco.optimizingfactory.SoftwareConfigurationAlgorithm;\r\nimport hasco.variants.forwarddecomposition.DefaultPathPriorizingPredicate;\r\nimport hasco.variants.forwarddecomposition.HASCOViaFDAndBestFirstWithRandomCompletions;\r\nimport jaicore.basic.ILoggingCustomizable;\r\nimport jaicore.basic.IObjectEvaluator;\r\nimport jaicore.basic.algorithm.AlgorithmEvent;\r\nimport jaicore.basic.algorithm.AlgorithmExecutionCanceledException;\r\nimport jaicore.basic.algorithm.AlgorithmFinishedEvent;\r\nimport jaicore.basic.algorithm.AlgorithmInitializedEvent;\r\nimport jaicore.basic.algorithm.AlgorithmState;\r\nimport jaicore.basic.algorithm.IAlgorithmConfig;\r\nimport jaicore.basic.algorithm.IOptimizerResult;\r\nimport jaicore.basic.algorithm.SolutionCandidateFoundEvent;\r\nimport jaicore.basic.sets.SetUtil;\r\nimport jaicore.concurrent.TimeoutTimer;\r\nimport jaicore.concurrent.TimeoutTimer.TimeoutSubmitter;\r\nimport jaicore.logging.LoggerUtil;\r\nimport jaicore.planning.graphgenerators.task.tfd.TFDNode;\r\nimport jaicore.search.algorithms.standard.bestfirst.nodeevaluation.INodeEvaluator;\r\nimport jaicore.search.core.interfaces.GraphGenerator;\r\n\r\npublic class TwoPhaseHASCO implements SoftwareConfigurationAlgorithm<TwoPhaseSoftwareConfigurationProblem, TwoPhaseHASCOReport, Double>, ILoggingCustomizable {\r\n\r\n\t/** Logger for controlled outputs. */\r\n\tprivate Logger logger = LoggerFactory.getLogger(TwoPhaseHASCO.class);\r\n\r\n\t/** Name for configuring the output of this class' logger in a more convenient way. */\r\n\tprivate String loggerName;\r\n\tprivate final EventBus eventBus = new EventBus();\r\n\t\r\n\t/* algorithm inputs */\r\n\tprivate final TwoPhaseSoftwareConfigurationProblem problem;\r\n\tprivate final TwoPhaseHASCOConfig config;\r\n\tprivate INodeEvaluator<TFDNode, Double> preferredNodeEvaluator;\r\n\r\n\t/** The classifier selected during selection phase. */\r\n\tprivate HASCOSolutionCandidate<Double> selectedHASCOSolution;\r\n\r\n\t/** evaluator for the selection phase. */\r\n\tprivate HASCOViaFDAndBestFirstWithRandomCompletions<Double> hasco;\r\n\r\n\t/* state variables during the run */\r\n\tprivate AlgorithmState state = AlgorithmState.created;\r\n\tprivate HASCOSolutionCandidate<Double> currentlyBestKnownSolution;\r\n\tprivate final Queue<HASCOSolutionCandidate<Double>> phase1ResultQueue = new LinkedBlockingQueue<>();\r\n\r\n\t/* statistics */\r\n\tprivate long timeOfStart = -1;\r\n\tprivate int secondsSpentInPhase1;\r\n\t\r\n\r\n\t\r\n\tprivate Thread timeoutControl = null;\r\n\r\n\tpublic TwoPhaseHASCO(TwoPhaseSoftwareConfigurationProblem problem, TwoPhaseHASCOConfig config) {\r\n\t\tif (problem == null)\r\n\t\t\tthrow new IllegalArgumentException(\"Cannot work with NULL problem\");\r\n\t\tthis.problem = problem;\r\n\t\tthis.config = config != null ? config : ConfigFactory.create(TwoPhaseHASCOConfig.class);\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic boolean hasNext() {\r\n\t\treturn state != AlgorithmState.inactive;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic AlgorithmEvent next() {\r\n\t\ttry {\r\n\t\t\treturn nextWithException();\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new RuntimeException(e);\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic AlgorithmEvent nextWithException() throws Exception {\r\n\t\tswitch (state) {\r\n\t\tcase created: {\r\n\t\t\tthis.timeOfStart = System.currentTimeMillis();\r\n\t\t\tthis.logger.info(\r\n\t\t\t\t\t\"Starting 2-Phase HASCO with the following setup:\\n\\tCPUs:{},\\n\\tTimeout: {}s\\n\\tTimeout per node evaluation: {}ms\\n\\tTimeout per candidate: {}ms\\n\\tNumber of Random Completions: {}\\n\\tExpected blow-ups are {} (selection) and {} (post-processing). Preferred node evaluator is {}\",\r\n\t\t\t\t\tgetNumCPUs(), getTimeout(), config.timeoutForNodeEvaluation(), config.randomCompletions(), config.timeoutForCandidateEvaluation(), config.expectedBlowupInSelection(), config.expectedBlowupInPostprocessing(),\r\n\t\t\t\t\tpreferredNodeEvaluator);\r\n\r\n\t\t\t/* create HASCO object */\r\n\t\t\tRefinementConfiguredSoftwareConfigurationProblem<Double> hascoProblem = new RefinementConfiguredSoftwareConfigurationProblem<>(problem, problem.getParamRefinementConfig());\r\n\t\t\tDefaultPathPriorizingPredicate<TFDNode,String> prioritizingPredicate = new DefaultPathPriorizingPredicate<>();\r\n\t\t\thasco = new HASCOViaFDAndBestFirstWithRandomCompletions<>(hascoProblem, prioritizingPredicate, config.randomCompletions(), config.randomSeed(), config.timeoutForCandidateEvaluation(),\r\n\t\t\t\t\tconfig.timeoutForNodeEvaluation(), preferredNodeEvaluator);\r\n\t\t\thasco.setLoggerName(loggerName + \".hasco\");\r\n\t\t\thasco.setConfig(config);\r\n\t\t\thasco.registerListener(this); // this is to register solutions during runtime\r\n\t\t\t\r\n\t\t\t/* set HASCO objects within the default path prioritizing node evaluator */\r\n\t\t\tprioritizingPredicate.setHasco(hasco);\r\n\t\t\t\r\n\t\t\t/* initialize HASCO and set state of this algorithm to initialized */\r\n\t\t\thasco.init();\r\n\t\t\tstate = AlgorithmState.active;\r\n\t\t\treturn new AlgorithmInitializedEvent();\r\n\t\t}\r\n\t\t\r\n\t\t/* active is only one step in this model; this could be refined */\r\n\t\tcase active: {\r\n\t\t\t\r\n\t\t\t/* phase 1: gather solutions */\r\n\t\t\tthis.timeoutControl = new Thread(new Runnable() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic void run() {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\twhile (!Thread.currentThread().isInterrupted()) {\r\n\t\t\t\t\t\t\tThread.sleep(1000);\r\n\t\t\t\t\t\t\tint timeElapsed = (int) (System.currentTimeMillis() - TwoPhaseHASCO.this.timeOfStart);\r\n\t\t\t\t\t\t\tint timeRemaining = config.timeout() * 1000 - timeElapsed;\r\n\t\t\t\t\t\t\tif (timeRemaining < 2000 || TwoPhaseHASCO.this.shouldSearchTerminate(timeRemaining)) {\r\n\t\t\t\t\t\t\t\tlogger.info(\"Canceling HASCO (first phase). {}ms remaining.\", timeRemaining);\r\n\t\t\t\t\t\t\t\thasco.cancel();\r\n\t\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\t\tSystem.err.println(\"Timeouter died away. This must not happen; killing the whole application. The exception responsible for this is:\");\r\n\t\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t\t\tSystem.exit(1);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t}\r\n\t\t\t}, \"Phase 1 time bound observer\");\r\n\t\t\tthis.timeoutControl.start();\r\n\t\t\ttry {\r\n\t\t\t\thasco.call();\r\n\t\t\t}\r\n\t\t\tcatch (AlgorithmExecutionCanceledException e) {\r\n\t\t\t\tlogger.info(\"HASCO has terminated due to a cancel.\");\r\n\t\t\t}\r\n\t\t\tsecondsSpentInPhase1 = (int) Math.round(System.currentTimeMillis() - timeOfStart / 1000.0);\r\n\r\n\t\t\tthis.logger.info(\"HASCO has finished. {} solutions were found.\", phase1ResultQueue.size());\r\n\t\t\tif (phase1ResultQueue.isEmpty()) {\r\n\t\t\t\tthrow new NoSuchElementException(\"No classifier could be built within the given timeout.\");\r\n\t\t\t}\r\n\r\n\t\t\t/* phase 2: select model */\r\n\t\t\tlogger.info(\"Entering phase 2\");\r\n\t\t\tthis.selectedHASCOSolution = this.selectModel();\r\n\t\t\tstate = AlgorithmState.inactive;\r\n\t\t\treturn new AlgorithmFinishedEvent();\r\n\t\t}\r\n\t\tdefault:\r\n\t\t\tthrow new IllegalStateException(\"Cannot do anything in state \" + state);\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic TwoPhaseSoftwareConfigurationProblem getInput() {\r\n\t\treturn problem;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic TwoPhaseHASCOReport call() throws Exception {\r\n\t\twhile (this.hasNext())\r\n\t\t\tthis.nextWithException();\r\n\t\treturn new TwoPhaseHASCOReport(phase1ResultQueue.size(), secondsSpentInPhase1, selectedHASCOSolution);\r\n\t}\r\n\r\n\tprotected boolean shouldSearchTerminate(final long timeRemaining) {\r\n\t\tCollection<HASCOSolutionCandidate<Double>> currentSelection = this.getSelectionForPhase2();\r\n\t\tint estimateForRemainingRuntime = this.getExpectedTotalRemainingRuntimeForAGivenPool(currentSelection, true);\r\n\t\tboolean terminatePhase1 = estimateForRemainingRuntime + 5000 > timeRemaining;\r\n\t\tthis.logger.debug(\"{}ms of the available time remaining in total, and we estimate a remaining runtime of {}ms. Terminate phase 1: {}\", timeRemaining, estimateForRemainingRuntime, terminatePhase1);\r\n\t\treturn terminatePhase1;\r\n\t}\r\n\r\n\tprivate synchronized List<HASCOSolutionCandidate<Double>> getSelectionForPhase2() {\r\n\t\treturn this.getSelectionForPhase2(Integer.MAX_VALUE);\r\n\t}\r\n\r\n\tprivate static final double MAX_MARGIN_FROM_BEST = 0.03;\r\n\r\n\tprivate synchronized List<HASCOSolutionCandidate<Double>> getSelectionForPhase2(final int remainingTime) {\r\n\t\tif (this.getNumberOfConsideredSolutions() < 1) {\r\n\t\t\tthrow new UnsupportedOperationException(\r\n\t\t\t\t\t\"Cannot determine candidates for phase 2 if their number is set to a value less than 1. Here, it has been set to \" + this.getNumberOfConsideredSolutions());\r\n\t\t}\r\n\r\n\t\t/* some initial checks for cases where we do not really have to do anything */\r\n\t\tif (remainingTime < 0) {\r\n\t\t\tthrow new IllegalArgumentException(\"Cannot do anything in negative time (\" + remainingTime + \"ms)\");\r\n\t\t}\r\n\t\tHASCOSolutionCandidate<Double> internallyOptimalSolution = currentlyBestKnownSolution;\r\n\t\tif (internallyOptimalSolution == null) {\r\n\t\t\treturn new ArrayList<>();\r\n\t\t}\r\n\r\n\t\t/*\r\n\t\t * compute k pipeline candidates (the k/2 best, and k/2 random ones that do not deviate too much from the best one)\r\n\t\t */\r\n\t\tdouble optimalInternalScore = internallyOptimalSolution.getScore();\r\n\t\tint bestK = (int) Math.ceil(this.getNumberOfConsideredSolutions() / 2);\r\n\t\tint randomK = this.getNumberOfConsideredSolutions() - bestK;\r\n\t\tCollection<HASCOSolutionCandidate<Double>> potentialCandidates = new ArrayList<>(phase1ResultQueue).stream().filter(solution -> {\r\n\t\t\treturn solution.getScore() <= optimalInternalScore + MAX_MARGIN_FROM_BEST;\r\n\t\t}).collect(Collectors.toList());\r\n\t\tthis.logger.debug(\"Computing {} best and {} random solutions for a max runtime of {}. Number of candidates that are at most {} worse than optimum {} is: {}/{}\", bestK, randomK, remainingTime,\r\n\t\t\t\tMAX_MARGIN_FROM_BEST, optimalInternalScore, potentialCandidates.size(), phase1ResultQueue.size());\r\n\t\tList<HASCOSolutionCandidate<Double>> selectionCandidates = potentialCandidates.stream().limit(bestK).collect(Collectors.toList());\r\n\t\tList<HASCOSolutionCandidate<Double>> remainingCandidates = new ArrayList<>(SetUtil.difference(potentialCandidates, selectionCandidates));\r\n\t\tCollections.shuffle(remainingCandidates, new Random(this.getConfig().randomSeed()));\r\n\t\tselectionCandidates.addAll(remainingCandidates.stream().limit(randomK).collect(Collectors.toList()));\r\n\r\n\t\t/* if the candidates can be evaluated in the remaining time, return all of them */\r\n\t\tint budget = this.getExpectedTotalRemainingRuntimeForAGivenPool(selectionCandidates, true);\r\n\t\tif (budget < remainingTime) {\r\n\t\t\treturn selectionCandidates;\r\n\t\t}\r\n\r\n\t\t/* otherwise return as much as can be expectedly done in the time */\r\n\t\tList<HASCOSolutionCandidate<Double>> actuallySelectedSolutions = new ArrayList<>();\r\n\t\tint expectedRuntime;\r\n\t\tfor (HASCOSolutionCandidate<Double> pl : selectionCandidates) {\r\n\t\t\tactuallySelectedSolutions.add(pl);\r\n\t\t\texpectedRuntime = this.getExpectedTotalRemainingRuntimeForAGivenPool(actuallySelectedSolutions, true);\r\n\t\t\tif (expectedRuntime > remainingTime && actuallySelectedSolutions.size() > 1) {\r\n\t\t\t\tthis.logger.info(\"Not considering solution {} for phase 2, because the expected runtime of the whole thing would be {}/{}\", pl, expectedRuntime, remainingTime);\r\n\t\t\t\tactuallySelectedSolutions.remove(pl);\r\n\t\t\t}\r\n\t\t}\r\n\t\t// assert this.getExpectedRuntimeForPhase2ForAGivenPool(actuallySelectedSolutions) > remainingTime : \"Invalid result. Expected runtime is higher than it should be based on the computation.\";\r\n\t\treturn actuallySelectedSolutions;\r\n\t}\r\n\r\n\tprivate int getInSearchEvaluationTimeOfSolutionSet(final Collection<HASCOSolutionCandidate<Double>> solutions) {\r\n\t\treturn solutions.stream().map(x -> x.getTimeToEvaluateCandidate()).mapToInt(x -> x).sum();\r\n\t}\r\n\r\n\tpublic int getExpectedTotalRemainingRuntimeForAGivenPool(final Collection<HASCOSolutionCandidate<Double>> solutions, boolean assumeCurrentlyBestCandidateToBeSelected) {\r\n\t\tint timeForPhase2 = getExpectedRuntimeForPhase2ForAGivenPool(solutions);\r\n\t\tint timeForPostprocessing = 0;\r\n\t\tif (assumeCurrentlyBestCandidateToBeSelected && currentlyBestKnownSolution != null) {\r\n\t\t\ttimeForPostprocessing = getPostprocessingTimeOfCurrentlyBest();\r\n\t\t} else {\r\n\t\t\ttimeForPostprocessing = getMaximumPostprocessingTimeOfAnyPoolMember(solutions);\r\n\t\t}\r\n\t\treturn timeForPhase2 + timeForPostprocessing;\r\n\t}\r\n\t\r\n\tpublic int getPostprocessingTimeOfCurrentlyBest() {\r\n\t\treturn (int) Math.round(currentlyBestKnownSolution.getTimeToEvaluateCandidate() * config.expectedBlowupInSelection() * config.expectedBlowupInPostprocessing());\r\n\t}\r\n\t\r\n\tpublic int getMaximumPostprocessingTimeOfAnyPoolMember(final Collection<HASCOSolutionCandidate<Double>> solutions) {\r\n\t\tint max = 0;\r\n\t\tfor (HASCOSolutionCandidate<Double> candidate : solutions) {\r\n\t\t\tint expectedPostProcessingTime = (int) Math.ceil(candidate.getTimeToEvaluateCandidate() * config.expectedBlowupInSelection() * config.expectedBlowupInPostprocessing());\r\n\t\t\tmax = Math.max(max, expectedPostProcessingTime);\r\n\t\t}\r\n\t\treturn max;\r\n\t}\r\n\r\n\tpublic int getExpectedRuntimeForPhase2ForAGivenPool(final Collection<HASCOSolutionCandidate<Double>> solutions) {\r\n\t\tint inSearchMCEvalTime = this.getInSearchEvaluationTimeOfSolutionSet(solutions);\r\n\t\tint estimateEvaluationTimeForSelectionPhase = (int) (inSearchMCEvalTime * config.expectedBlowupInSelection());\r\n\t\tint usableCPUs = Math.min(this.getConfig().cpus(), solutions.size());\r\n\t\tint runtime = (int) (estimateEvaluationTimeForSelectionPhase / Math.max(1, usableCPUs));\r\n\t\tthis.logger.debug(\"Expected runtime is {} = {} * {} / {} for a pool of size {}\", runtime, inSearchMCEvalTime,\r\n\t\t\t\tconfig.expectedBlowupInSelection(), usableCPUs, solutions.size());\r\n\t\treturn runtime;\r\n\t}\r\n\r\n\tprotected HASCOSolutionCandidate<Double> selectModel() {\r\n\t\tfinal IObjectEvaluator<ComponentInstance, Double> evaluator = problem.getSelectionBenchmark();\r\n\t\tfinal HASCOSolutionCandidate<Double> bestSolution = phase1ResultQueue.stream().min((s1, s2) -> s1.getScore().compareTo(s2.getScore())).get();\r\n\t\tdouble scoreOfBestSolution = bestSolution.getScore();\r\n\r\n\t\t/* determine the models from which we want to select */\r\n\t\tthis.logger.info(\"Starting with phase 2: Selection of final model among the {} solutions that were identified.\", phase1ResultQueue.size());\r\n\t\tlong startOfPhase2 = System.currentTimeMillis();\r\n\t\tList<HASCOSolutionCandidate<Double>> ensembleToSelectFrom;\r\n\t\tif (this.getConfig().timeout() > 0) {\r\n\t\t\tint remainingTime = (int) (this.getConfig().timeout() * 1000 - (System.currentTimeMillis() - this.timeOfStart));\r\n\t\t\t/* check remaining time, otherwise just return the solution with best F-Value. */\r\n\t\t\tif (remainingTime < 0) {\r\n\t\t\t\tthis.logger.info(\"Timelimit is already exhausted, just returning a greedy solution that had internal error {}.\", scoreOfBestSolution);\r\n\t\t\t\treturn bestSolution;\r\n\t\t\t}\r\n\r\n\t\t\t/* Get a queue of solutions to perform selection evaluation for. */\r\n\t\t\tensembleToSelectFrom = this.getSelectionForPhase2(remainingTime); // should be ordered by scores already (at least the first k)\r\n\t\t\tint expectedTimeForPhase2 = this.getExpectedRuntimeForPhase2ForAGivenPool(ensembleToSelectFrom);\r\n\t\t\tint expectedPostprocessingTime = this.getPostprocessingTimeOfCurrentlyBest();\r\n\t\t\tint expectedMaximumRemainingRuntime = expectedTimeForPhase2 + expectedPostprocessingTime;\r\n\t\t\tremainingTime = (int) (this.getConfig().timeout() * 1000 - (System.currentTimeMillis() - this.timeOfStart));\r\n\r\n\t\t\tif (expectedMaximumRemainingRuntime > remainingTime) {\r\n\t\t\t\tthis.logger.warn(\"Only {}ms remaining. We probably cannot make it in time.\", remainingTime);\r\n\t\t\t}\r\n\t\t\tthis.logger.info(\"We expect phase 2 to consume {}ms for {} candidates, and post-processing is assumed to take at most {}ms, which is a total remaining runtime of {}ms. {}ms are permitted by timeout. The following pipelines are considered: \", expectedTimeForPhase2,\r\n\t\t\t\t\tensembleToSelectFrom.size(), expectedPostprocessingTime, expectedMaximumRemainingRuntime, remainingTime);\r\n\t\t} else {\r\n\t\t\tensembleToSelectFrom = this.getSelectionForPhase2();\r\n\t\t}\r\n\r\n\t\tAtomicInteger evaluatorCounter = new AtomicInteger(0);\r\n\r\n\t\tthis.logger.info(\"Create a thread pool for phase 2 of size {}.\", this.getConfig().cpus());\r\n\t\tExecutorService pool = Executors.newFixedThreadPool(this.getConfig().cpus(), r -> {\r\n\t\t\tThread t = new Thread(r);\r\n\t\t\tt.setName(\"final-evaluator-\" + evaluatorCounter.incrementAndGet());\r\n\t\t\treturn t;\r\n\t\t});\r\n\t\tHASCOSolutionCandidate<Double> selectedModel = bestSolution; // backup solution\r\n\t\tfinal Semaphore sem = new Semaphore(0);\r\n\t\tlong timestampOfDeadline = this.timeOfStart + this.getTimeout() * 1000 - 2000;\r\n\r\n\t\t/* evaluate each candiate */\r\n\t\tList<Double> stats = new ArrayList<>();\r\n\t\tfinal TimeoutSubmitter ts = TimeoutTimer.getInstance().getSubmitter();\r\n\t\tensembleToSelectFrom.forEach(c -> stats.add(Double.MAX_VALUE));\r\n\r\n\t\tint n = ensembleToSelectFrom.size();\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tHASCOSolutionCandidate<Double> c = ensembleToSelectFrom.get(i);\r\n\r\n\t\t\tfinal int run = i;\r\n\r\n\t\t\tpool.submit(new Runnable() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic void run() {\r\n\t\t\t\t\tlong timestampStart = System.currentTimeMillis();\r\n\r\n\t\t\t\t\t/* Time needed to compute the score of this solution in phase 1 */\r\n\t\t\t\t\tint inSearchSolutionEvaluationTime = c.getTimeToEvaluateCandidate();\r\n\r\n\t\t\t\t\t/* We assume linear growth of the evaluation time here to estimate\r\n\t\t\t\t\t * (A) time for selection phase,\r\n\t\t\t\t\t * (B) time for post-processing the solution in case it gets selected. */\r\n\t\t\t\t\tint estimatedInSelectionSingleIterationEvaluationTime = (int) Math.round(inSearchSolutionEvaluationTime * config.expectedBlowupInSelection());\r\n\t\t\t\t\tint estimatedPostProcessingTime = (int) Math.round(estimatedInSelectionSingleIterationEvaluationTime * config.expectedBlowupInPostprocessing());\r\n\t\t\t\t\tint estimatedTotalEffortInCaseOfSelection = estimatedInSelectionSingleIterationEvaluationTime + Math.max(estimatedPostProcessingTime, getPostprocessingTimeOfCurrentlyBest());\r\n\t\t\t\t\tlogger.info(\r\n\t\t\t\t\t\t\t\"During search, the currently chosen model {} had a total evaluation time of {}ms ({}ms per iteration). \"\r\n\t\t\t\t\t\t\t\t\t+ \"We estimate an evaluation in the selection phase to take {}ms, and the final build to take {}. \" + \"This yields a total time of {}ms.\",\r\n\t\t\t\t\t\t\tc.getComponentInstance(), inSearchSolutionEvaluationTime, inSearchSolutionEvaluationTime, estimatedInSelectionSingleIterationEvaluationTime, estimatedPostProcessingTime,\r\n\t\t\t\t\t\t\testimatedTotalEffortInCaseOfSelection);\r\n\r\n\t\t\t\t\t// /* Old computation as coded by fmohr: we assume a linear growth */\r\n\t\t\t\t\t// int evaluationTimeOfCurrentlyChosenCandidateInsideSearch = currentlyChosenSolution.getTimeToComputeScore();\r\n\t\t\t\t\t// int estimatedEvaluationTimeOfCurrentlyChosenCandidateInSelection = (int) Math.round(evaluationTimeOfCurrentlyChosenCandidateInsideSearch * config.expectedBlowupInSelection());\r\n\t\t\t\t\t// int estimatedPostprocessingTimeOfCurrentlyChosenCandidate = (int) Math.round(estimatedEvaluationTimeOfCurrentlyChosenCandidateInSelection * config.expectedBlowupInPostprocessing());\r\n\t\t\t\t\t// trainingTimeForChosenModelInsideSearch = inSearchSolutionEvaluationTime;\r\n\t\t\t\t\t// estimatedOverallTrainingTimeForChosenModel = estimatedFinalBuildTime;\r\n\t\t\t\t\t// expectedTrainingTimeOfThisModel = estimatedInSelectionSingleIterationEvaluationTime;\r\n\r\n\t\t\t\t\t/* Schedule a timeout for this evaluation, which is 10% over the estimated time */\r\n\t\t\t\t\tint timeoutForEvaluation = (int) (estimatedInSelectionSingleIterationEvaluationTime * (1 + config.selectionPhaseTimeoutTolerance()));\r\n\t\t\t\t\tint taskId = ts.interruptMeAfterMS(timeoutForEvaluation);\r\n\r\n\t\t\t\t\t/* If we have a global timeout, check whether considering this model is feasible. */\r\n\t\t\t\t\tif (TwoPhaseHASCO.this.getConfig().timeout() > 0) {\r\n\t\t\t\t\t\tint remainingTime = (int) (timestampOfDeadline - System.currentTimeMillis());\r\n\t\t\t\t\t\tif (estimatedTotalEffortInCaseOfSelection >= remainingTime) {\r\n\t\t\t\t\t\t\tTwoPhaseHASCO.this.logger.info(\r\n\t\t\t\t\t\t\t\t\t\"Not evaluating solution {} anymore, because its insearch evaluation time was {}, expected evaluation time for selection is {}, and expected post-processing time is {}. This adds up to {}, which exceeds the remaining time of {}!\",\r\n\t\t\t\t\t\t\t\t\tc.getComponentInstance(), c.getTimeToEvaluateCandidate(), estimatedInSelectionSingleIterationEvaluationTime, estimatedPostProcessingTime,\r\n\t\t\t\t\t\t\t\t\testimatedTotalEffortInCaseOfSelection, remainingTime);\r\n\t\t\t\t\t\t\tsem.release();\r\n\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tdouble selectionScore = evaluator.evaluate(c.getComponentInstance());\r\n\t\t\t\t\t\tlong trueEvaluationTime = (System.currentTimeMillis() - timestampStart);\r\n\t\t\t\t\t\tlogger.info(\"Evaluated candidate {} with score {} (score assigned by HASCO was {}). Time to evaluate was {}ms\", c.getComponentInstance(), selectionScore, c.getScore(), trueEvaluationTime);\r\n\t\t\t\t\t\tstats.set(run, selectionScore);\r\n\t\t\t\t\t} catch (InterruptedException e) {\r\n\t\t\t\t\t\tlogger.info(\"Selection eval of {} got interrupted after {}ms. Defined timeout was: {}ms\", c.getComponentInstance(), (System.currentTimeMillis() - timestampStart),\r\n\t\t\t\t\t\t\t\ttimeoutForEvaluation);\r\n\t\t\t\t\t} catch (Throwable e) {\r\n\t\t\t\t\t\t/* Print only an exception if it is not expected. */\r\n\t\t\t\t\t\tif (!e.getMessage().contains(\"Killed WEKA!\")) {\r\n\t\t\t\t\t\t\tTwoPhaseHASCO.this.logger.error(\"Observed an exeption when trying to evaluate a candidate in the selection phase.\\n{}\", LoggerUtil.getExceptionInfo(e));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} finally {\r\n\t\t\t\t\t\tsem.release();\r\n\t\t\t\t\t\tlogger.debug(\"Released. Sem state: {}\", sem.availablePermits());\r\n\t\t\t\t\t\tif (taskId >= 0) {\r\n\t\t\t\t\t\t\tts.cancelTimeout(taskId);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t}\r\n\t\ttry {\r\n\t\t\t\r\n\t\t\t/* now wait for results */\r\n\t\t\tthis.logger.info(\"Waiting for termination of {} threads that compute the selection scores.\", n);\r\n\t\t\tsem.acquire(n);\r\n\t\t\tlong endOfPhase2 = System.currentTimeMillis();\r\n\t\t\tthis.logger.info(\"Finished phase 2 within {}ms net. Total runtime was {}ms. \", endOfPhase2 - startOfPhase2, endOfPhase2 - this.timeOfStart);\r\n\t\t\tthis.logger.debug(\"Shutting down thread pool\");\r\n\t\t\tpool.shutdownNow();\r\n\t\t\tpool.awaitTermination(5, TimeUnit.SECONDS);\r\n\r\n\t\t\tif (!pool.isShutdown()) {\r\n\t\t\t\tthis.logger.warn(\"Thread pool is not shut down yet!\");\r\n\t\t\t}\r\n\r\n\t\t\tts.close();\r\n\r\n\t\t\t/* set chosen model */\r\n\t\t\tif (ensembleToSelectFrom.isEmpty()) {\r\n\t\t\t\tthis.logger.warn(\"No solution contained in ensemble.\");\r\n\t\t\t} else {\r\n\t\t\t\tint selectedModelIndex = this.getCandidateThatWouldCurrentlyBeSelectedWithinPhase2(ensembleToSelectFrom, stats, true);\r\n\t\t\t\tif (selectedModelIndex < 0)\r\n\t\t\t\t\tthrow new NoSuchElementException(\"Could not identify any solution.\");\r\n\t\t\t\tselectedModel = ensembleToSelectFrom.get(selectedModelIndex);\r\n\t\t\t\t// DescriptiveStatistics statsOfBest = stats.get(selectedModelIndex);\r\n\t\t\t\tthis.logger.info(\"Selected a configuration: {}. Its internal score was {}. Selection score was {}\", selectedModel.getComponentInstance(), selectedModel.getScore(),\r\n\t\t\t\t\t\tstats.get(selectedModelIndex));\r\n\t\t\t}\r\n\r\n\t\t} catch (InterruptedException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t\treturn selectedModel;\r\n\t}\r\n\r\n\tprivate synchronized int getCandidateThatWouldCurrentlyBeSelectedWithinPhase2(final List<HASCOSolutionCandidate<Double>> ensembleToSelectFrom, final List<Double> stats,\r\n\t\t\tfinal boolean logComputations) {\r\n\t\tint selectedModel = -1;\r\n\t\tdouble best = Double.MAX_VALUE;\r\n\t\tfor (int i = 0; i < ensembleToSelectFrom.size(); i++) {\r\n\t\t\t// HASCOSolutionCandidate<Double> candidate = ensembleToSelectFrom.get(i);\r\n\t\t\t// DescriptiveStatistics statsOfCandidate = stats.get(i);\r\n\t\t\t// if (statsOfCandidate.getN() == 0) {\r\n\t\t\t// if (logComputations) {\r\n\t\t\t// this.logger.info(\"Ignoring candidate {} because no results were obtained in selection phase.\", candidate);\r\n\t\t\t// }\r\n\t\t\t// continue;\r\n\t\t\t// }\r\n\t\t\t// double avgError = statsOfCandidate.getMean() / 100f;\r\n\t\t\t// double quartileScore = statsOfCandidate.getPercentile(75) / 100;\r\n\t\t\t// double score = (avgError + quartileScore) / 2f;\r\n\t\t\t// if (logComputations) {\r\n\t\t\t// this.logger.info(\"Score of candidate {} is {} based on {} (avg) and {} (.75-pct) with {} samples\", candidate, score, avgError, quartileScore, statsOfCandidate.getN());\r\n\t\t\t// }\r\n\t\t\tdouble score = stats.get(i);\r\n\t\t\tif (score < best) {\r\n\t\t\t\tbest = score;\r\n\t\t\t\tselectedModel = i;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn selectedModel;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void cancel() {\r\n\t\tthis.timeoutControl.interrupt();\r\n\t}\r\n\r\n\t/**\r\n\t * @return The solution candidate selected by TwoPhase HASCO\r\n\t */\r\n\tpublic HASCOSolutionCandidate<Double> getSelectedSolutionCandidate() {\r\n\t\treturn this.selectedHASCOSolution;\r\n\t}\r\n\r\n\tpublic TwoPhaseHASCOConfig getConfig() {\r\n\t\treturn config;\r\n\t}\r\n\r\n\t/**\r\n\t * @return The number of considered solutions in the selection phase.\r\n\t */\r\n\tpublic int getNumberOfConsideredSolutions() {\r\n\t\treturn this.getConfig().selectionNumConsideredSolutions();\r\n\t}\r\n\r\n\t/**\r\n\t * @param numberOfConsideredSolutions\r\n\t * The number of considered solutions in the selection phase.\r\n\t */\r\n\tpublic void setNumberOfConsideredSolutions(final int numberOfConsideredSolutions) {\r\n\t\tthis.getConfig().setProperty(TwoPhaseHASCOConfig.K_SELECTION_NUM_CONSIDERED_SOLUTIONS, numberOfConsideredSolutions + \"\");\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void setLoggerName(final String name) {\r\n\t\tthis.logger.info(\"Switching logger from {} to {}\", this.logger.getName(), name);\r\n\t\tthis.loggerName = name;\r\n\t\tthis.logger = LoggerFactory.getLogger(name);\r\n\t\tthis.logger.info(\"Activated logger {} with name {}\", name, this.logger.getName());\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String getLoggerName() {\r\n\t\treturn this.loggerName;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic Iterator<AlgorithmEvent> iterator() {\r\n\t\treturn this;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void registerListener(Object listener) {\r\n\t\teventBus.register(listener);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void setNumCPUs(int numberOfCPUs) {\r\n\t\tconfig.setProperty(IAlgorithmConfig.K_CPUS, String.valueOf(numberOfCPUs));\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int getNumCPUs() {\r\n\t\treturn config.cpus();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void setTimeout(int timeout, TimeUnit timeUnit) {\r\n\t\tif (timeUnit != TimeUnit.SECONDS)\r\n\t\t\tthrow new IllegalArgumentException(\"only seconds supported\");\r\n\t\tthis.config.setProperty(IAlgorithmConfig.K_TIMEOUT, String.valueOf(timeout));\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int getTimeout() {\r\n\t\treturn config.timeout();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic TimeUnit getTimeoutUnit() {\r\n\t\treturn TimeUnit.SECONDS;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic IOptimizerResult<ComponentInstance, Double> getOptimizationResult() {\r\n\t\treturn new IOptimizerResult<ComponentInstance, Double>(selectedHASCOSolution.getComponentInstance(), selectedHASCOSolution.getScore());\r\n\t}\r\n\r\n\t@Subscribe\r\n\tpublic void receiveSolutionEvent(SolutionCandidateFoundEvent<HASCOSolutionCandidate<Double>> solutionEvent) {\r\n\t\tHASCOSolutionCandidate<Double> solution = solutionEvent.getSolutionCandidate();\r\n\t\tif (currentlyBestKnownSolution == null || solution.getScore().compareTo(currentlyBestKnownSolution.getScore()) < 0)\r\n\t\t\tcurrentlyBestKnownSolution = solution;\r\n\t\tlogger.info(\"Received new solution {} with score {} and evaluation time {}ms\", solution.getComponentInstance(), solution.getScore(), solution.getTimeToEvaluateCandidate());\r\n\t\tphase1ResultQueue.add(solution);\r\n\t\teventBus.post(solutionEvent);\r\n\t}\r\n\r\n\tpublic INodeEvaluator<TFDNode, Double> getPreferredNodeEvaluator() {\r\n\t\treturn preferredNodeEvaluator;\r\n\t}\r\n\r\n\tpublic void setPreferredNodeEvaluator(INodeEvaluator<TFDNode, Double> preferredNodeEvaluator) {\r\n\t\tthis.preferredNodeEvaluator = preferredNodeEvaluator;\r\n\t}\r\n\t\r\n\tpublic GraphGenerator<TFDNode, String> getGraphGenerator() {\r\n\t\tif (hasco == null)\r\n\t\t\tthrow new IllegalStateException(\"Cannot retrieve GraphGenerator prior to algorithm initialization.\");\r\n\t\treturn hasco.getGraphGenerator();\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.786928117275238, "alphanum_fraction": 0.786928117275238, "avg_line_length": 45.8125, "blob_id": "fda930497e6faa89dcd9a0318aa078d396448aef", "content_id": "ead41d5c66d1a8266d3399b17f985dead419ce31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 765, "license_type": "no_license", "max_line_length": 200, "num_lines": 16, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/lds/LimitedDiscrepancySearchFactory.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.lds;\r\n\r\nimport jaicore.graph.TreeNode;\r\nimport jaicore.search.core.interfaces.StandardORGraphSearchFactory;\r\nimport jaicore.search.model.other.EvaluatedSearchGraphPath;\r\nimport jaicore.search.model.probleminputs.NodeRecommendedTree;\r\n\r\npublic class LimitedDiscrepancySearchFactory<T, A, V extends Comparable<V>> extends StandardORGraphSearchFactory<NodeRecommendedTree<T, A>, EvaluatedSearchGraphPath<T, A,V>, T, A, V, TreeNode<T>, A> {\r\n\r\n\t@Override\r\n\tpublic LimitedDiscrepancySearch<T, A, V> getAlgorithm() {\r\n\t\tif (getProblemInput() == null)\r\n\t\t\tthrow new IllegalArgumentException(\"Cannot create algorithm; problem input has not been set yet\");\r\n\t\treturn new LimitedDiscrepancySearch<T,A,V>(getProblemInput());\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7180801630020142, "alphanum_fraction": 0.7227399945259094, "avg_line_length": 36.64912414550781, "blob_id": "fffed0b6c330847fe6c8d40ed3000a7c97d0b582", "content_id": "a8e38f626d734d709a841d8ec600b13256590f02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2146, "license_type": "no_license", "max_line_length": 123, "num_lines": 57, "path": "/JAICore/jaicore-logic/src/jaicore/logic/fol/util/LiteralStringParser.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.logic.fol.util;\n\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.regex.MatchResult;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport jaicore.logic.fol.structure.ConstantParam;\nimport jaicore.logic.fol.structure.InterpretedLiteral;\nimport jaicore.logic.fol.structure.Literal;\nimport jaicore.logic.fol.structure.LiteralParam;\nimport jaicore.logic.fol.structure.LiteralSet;\nimport jaicore.logic.fol.structure.VariableParam;\n\npublic class LiteralStringParser {\n\tprivate static Pattern basicPattern = Pattern.compile(\"(!|~)?(.*)\\\\(([^\\\\)]*)\\\\)\");\n\n\tpublic static LiteralSet convertStringToLiteralSetWithConst(String literalSetString, Set<String> evaluablePredicates) {\n\t\tLiteralSet literalSet = new LiteralSet();\n\n\t\tString[] literals = literalSetString.split(\"&\");\n\t\tif (!(literals.length == 1 && literals[0].isEmpty())) {\n\t\t\tfor (int i = 0; i < literals.length; i++) {\n\t\t\t\tliteralSet.add(convertStringToLiteralWithConst(literals[i], evaluablePredicates));\n\t\t\t}\n\t\t}\n\t\treturn literalSet;\n\t}\n\n\tpublic static Literal convertStringToLiteralWithConst(final String literalString, final Set<String> evaluablePredicates) {\n\t\tString string = literalString.replace(\" \", \"\");\n\t\tstring = string.trim();\n\n\t\tMatcher matcher = basicPattern.matcher(string);\n\t\tif (!matcher.find())\n\t\t\treturn null;\n\t\tMatchResult results = matcher.toMatchResult();\n\t\tString predicateName = results.group(2); // position 2 is predicate name\n\t\tString[] paramsAsStrings = results.group(3).split(\",\"); // position 3\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// are the\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// variables\n\t\tList<LiteralParam> params = new LinkedList<>();\n\t\tfor (int i = 0; i < paramsAsStrings.length; i++) {\n\t\t\tString param = paramsAsStrings[i].trim();\n\t\t\tparams.add(param.startsWith(\"'\") ? new ConstantParam(param.replace(\"'\", \"\")) : new VariableParam(param));\n\t\t}\n\n\t\t/* try to match suffix of predicate name */\n\t\tif (evaluablePredicates.contains(predicateName)) {\n\t\t\treturn new InterpretedLiteral(predicateName, params, results.group(1) == null);\n\t\t} else {\n\t\t\treturn new Literal(predicateName, params, results.group(1) == null);\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.683851420879364, "alphanum_fraction": 0.6876421570777893, "avg_line_length": 22.553571701049805, "blob_id": "ed1fcfd5f86497d24cb1947d171a493473ec6144", "content_id": "dbf0ed2bd8f02e48724c02718fddb18fbdf3d324", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1319, "license_type": "no_license", "max_line_length": 80, "num_lines": 56, "path": "/JAICore/jaicore-search/test/jaicore/search/testproblems/npuzzle/parentDiscarding/PDPuzzleNode.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.testproblems.npuzzle.parentDiscarding;\n\nimport java.util.Arrays;\n\nimport jaicore.search.testproblems.npuzzle.standard.NPuzzleNode;\n\npublic class PDPuzzleNode extends NPuzzleNode {\n\n\tpublic PDPuzzleNode(int[][] board, int emptyX, int emptyY, int numberOfMoves) {\n\t\tsuper(board, emptyX, emptyY, numberOfMoves);\n\t}\n\n\t\n\t/* (non-Javadoc)\n\t * @see jaicore.search.algorithms.standard.npuzzle.NPuzzleNode#getDistance()\n\t */\n\t@Override\n\tpublic double getDistance() {\n\t\n\t\treturn Math.abs((board.length-1)-emptyX)+Math.abs((board.length-1)-emptyY);\n\t}\n\t\n\t/* (non-Javadoc)\n\t * @see java.lang.Object#hashCode()\n\t */\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + Arrays.deepHashCode(board);\n//\t\tresult = prime * result + Arrays.hashCode(board);\n\t\tresult = prime * result + emptyX;\n\t\tresult = prime * result + emptyY;\n\t\treturn result;\n\t}\n\n\t/* (non-Javadoc)\n\t * @see java.lang.Object#equals(java.lang.Object)\n\t */\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tNPuzzleNode other = (NPuzzleNode) obj;\n\t\tif (emptyX != other.getEmptyX())\n\t\t\treturn false;\n\t\tif (emptyY != other.getEmptyY())\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n}\n" }, { "alpha_fraction": 0.47648903727531433, "alphanum_fraction": 0.4921630024909973, "avg_line_length": 15.722222328186035, "blob_id": "7f8b83dd838b85e5dcfaf6d42236bd6928273874", "content_id": "b8275d7f5c88feadc5898c9df72771fc10f1f8d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Gradle", "length_bytes": 319, "license_type": "no_license", "max_line_length": 75, "num_lines": 18, "path": "/JAICore/jaicore-experiments/build.gradle", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "sourceSets {\r\n main {\r\n java {\r\n srcDir 'src'\r\n srcDir 'examples'\r\n }\r\n }\r\n test {\r\n \tjava {\r\n \t\tsrcDir 'test'\r\n \t}\r\n }\r\n}\r\ndependencies {\r\n\tcompile project(\":JAICore:jaicore-basic\")\r\n\t\r\n\tcompile group: 'org.aeonbits.owner', name: 'owner-java8', version:'1.0.10'\r\n}\r\n" }, { "alpha_fraction": 0.7630331516265869, "alphanum_fraction": 0.7630331516265869, "avg_line_length": 16.58333396911621, "blob_id": "4e389ec8ff6134de345e76176bc9ad174b9c8ecf", "content_id": "b8069f86bc6f218e25e610176e3260e586738f53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 211, "license_type": "no_license", "max_line_length": 36, "num_lines": 12, "path": "/JAICore/jaicore-graphvisualizer/src/jaicore/graphvisualizer/NodeListener.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.graphvisualizer;\n\npublic interface NodeListener<T> {\n\n\tpublic void mouseOver(T node);\n\n\tpublic void mouseLeft(T node);\n\n\tpublic void buttonReleased(T node);\n\n\tpublic void buttonPushed(T node);\n}\n" }, { "alpha_fraction": 0.7591218948364258, "alphanum_fraction": 0.7591218948364258, "avg_line_length": 28.060344696044922, "blob_id": "52c60e0052b75fcb2c4c23099b17f379bdd9f9c1", "content_id": "47135f7ced513ff1d793123ea96b4afaf0a37a20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3371, "license_type": "no_license", "max_line_length": 107, "num_lines": 116, "path": "/JAICore/jaicore-graphvisualizer/src/jaicore/graphvisualizer/gui/dataSupplier/TooltipSupplier.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.graphvisualizer.gui.dataSupplier;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.SerializationFeature;\nimport com.google.common.eventbus.EventBus;\nimport com.google.common.eventbus.Subscribe;\n\nimport jaicore.graphvisualizer.TooltipGenerator;\nimport jaicore.graphvisualizer.events.controlEvents.ControlEvent;\nimport jaicore.graphvisualizer.events.controlEvents.NodePushed;\nimport jaicore.graphvisualizer.events.graphEvents.GraphEvent;\nimport jaicore.graphvisualizer.events.graphEvents.GraphInitializedEvent;\nimport jaicore.graphvisualizer.events.graphEvents.NodeReachedEvent;\nimport jaicore.graphvisualizer.events.graphEvents.NodeTypeSwitchEvent;\nimport jaicore.graphvisualizer.events.misc.HTMLEvent;\n\n/**\n * A Supplier which contains tooltips for the nodes and post them so that a\n * tooltip supplier can show them.\n * \n * @author jkoepe\n *\n */\npublic class TooltipSupplier implements ISupplier {\n\n\tprivate EventBus dataBus;\n\tprivate TooltipGenerator generator;\n// private String visualizer;\n\tprivate String title;\n\n\tprivate Map<Integer, String> tooltipMap;\n\n\tpublic TooltipSupplier() {\n\t\tthis.dataBus = new EventBus();\n\t\tthis.tooltipMap = new HashMap<>();\n// this.visualizer = \"HTMLVisualizer\";\n\t\tthis.title = \"Tooltips\";\n\t}\n\n\t@Override\n\tpublic void registerListener(Object listener) {\n\t\tthis.dataBus.register(listener);\n\t}\n\n// @Override\n// public String getVisualizerName() {\n// return visualizer;\n//\n// }\n\n// @Override\n// public String getVisualizerTitle() {\n// return title;\n// }\n\n\tpublic void setGenerator(TooltipGenerator generator) {\n\t\tthis.generator = generator;\n\t}\n\n\t@Override\n\tpublic JsonNode getSerialization() {\n\t\tObjectMapper mapper = new ObjectMapper();\n\t\tmapper.enable(SerializationFeature.INDENT_OUTPUT);\n\t\tHashMap<String, Object> map = new HashMap();\n\n// map.put(\"Visualizer\", visualizer);\n\t\tmap.put(\"Title\", title);\n\t\tmap.put(\"Data\", tooltipMap);\n\n\t\tList<String> doEvents = new ArrayList<>();\n\t\tdoEvents.add(\"NodePushed\");\n\t\tmap.put(\"DoEvents\", doEvents);\n\n\t\treturn mapper.valueToTree(map);\n\t}\n\n\t@Override\n\t@Subscribe\n\tpublic void receiveControlEvent(ControlEvent event) {\n\t\tif (event instanceof NodePushed)\n\t\t\tthis.dataBus.post(new HTMLEvent(tooltipMap.get(((NodePushed) event).getNode().hashCode())));\n\t}\n\n\t@Override\n\t@Subscribe\n\tpublic void receiveGraphEvent(GraphEvent event) {\n\t\tswitch (event.getClass().getSimpleName()) {\n\t\tcase \"GraphInitializedEvent\":\n\t\t\tGraphInitializedEvent initializedEvent = (GraphInitializedEvent) event;\n\t\t\tString tooltip = generator.getTooltip(initializedEvent.getRoot());\n\t\t\ttooltipMap.put(initializedEvent.getRoot().hashCode(), tooltip);\n\t\t\tbreak;\n\n\t\tcase \"NodeTypeSwitchEvent\":\n\t\t\tNodeTypeSwitchEvent switchEvent = (NodeTypeSwitchEvent) event;\n\t\t\tif (tooltipMap.containsKey(switchEvent.getNode().hashCode()))\n\t\t\t\ttooltipMap.put(switchEvent.getNode().hashCode(), generator.getTooltip(switchEvent.getNode()));\n\t\t\tbreak;\n\n\t\tcase \"NodeReachedEvent\":\n\t\t\tNodeReachedEvent nodeReachedEvent = (NodeReachedEvent) event;\n\t\t\ttooltipMap.put(nodeReachedEvent.getNode().hashCode(), generator.getTooltip(nodeReachedEvent.getNode()));\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\n}\n" }, { "alpha_fraction": 0.6983723044395447, "alphanum_fraction": 0.7075279951095581, "avg_line_length": 27.91176414489746, "blob_id": "0a974f882a274dd78ca48723565ac0e9b9ca4592", "content_id": "13bf74ba563b8a996af2826b6c308c99cdac725f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1966, "license_type": "no_license", "max_line_length": 80, "num_lines": 68, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/uncertainty/paretosearch/ParetoFrontVisualizer.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.uncertainty.paretosearch;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.knowm.xchart.SwingWrapper;\nimport org.knowm.xchart.XYChart;\nimport org.knowm.xchart.XYChartBuilder;\nimport org.knowm.xchart.XYSeries.XYSeriesRenderStyle;\nimport org.knowm.xchart.style.Styler.ChartTheme;\nimport org.knowm.xchart.style.Styler.LegendPosition;\n\npublic class ParetoFrontVisualizer {\n\n\tfinal XYChart chart;\n\tfinal SwingWrapper<XYChart> vis;\n\tfinal List<Double> fValues;\n\tfinal List<Double> uncertainties;\n\t\n\tpublic ParetoFrontVisualizer () {\n\t\tchart = new XYChartBuilder()\n\t\t\t\t.width(600)\n\t\t\t\t.height(500)\n\t\t\t\t.title(\"Paretofront Visualizer\")\n\t\t\t\t.theme(ChartTheme.Matlab)\n\t\t\t\t.xAxisTitle(\"Uncertainty\")\n\t\t\t\t.yAxisTitle(\"F Value\")\n\t\t\t\t.build();\n\t\t\n\t\tchart.getStyler().setYAxisMin(0.0d);\n\t\tchart.getStyler().setXAxisMin(0.0d);\n\t\tchart.getStyler().setYAxisMax(1.0d);\n\t\tchart.getStyler().setXAxisMax(1.0d);\n\t\tchart.getStyler().setDefaultSeriesRenderStyle(XYSeriesRenderStyle.Scatter);\n\t\tchart.getStyler().setLegendPosition(LegendPosition.OutsideS);\n\t\tchart.getStyler().setMarkerSize(4);\n\t\tchart.addSeries(\"Paretofront Candidates\", new double[] {1}, new double[] {1});\n\t\t\n\t\tvis = new SwingWrapper<>(chart);\n\t\t\n\t\tfValues = new ArrayList<>();\n\t\tuncertainties = new ArrayList<>();\n\t}\n\t\n\tpublic void show () {\n\t\tvis.displayChart();\n\t}\n\t\n\tpublic void update (double fValue, double uncertainty) {\n\t\tfValues.add(fValue);\n\t\tuncertainties.add(uncertainty);\n\t\t\n\t\tif (fValues.size() == uncertainties.size()) {\n\t\t\tdouble[] f = new double[fValues.size()];\n\t\t\tdouble[] u = new double[uncertainties.size()];\n\t\t\tfor (int i = 0; i < fValues.size(); i++) {\n\t\t\t\tf[i] = fValues.get(i);\n\t\t\t\tu[i] = uncertainties.get(i);\n\t\t\t}\n\t\t\tjavax.swing.SwingUtilities.invokeLater(() -> {\n\t\t\t\tchart.updateXYSeries(\"Paretofront Candidates\", u, f, null);\n\t\t\t\tvis.repaintChart();\n\t\t\t});\n\t\t} else {\n\t\t\tSystem.out.println(\"ERROR: Unqueal value amounts\");\n\t\t}\t\t\n\t}\n\t\n}\n" }, { "alpha_fraction": 0.6582417488098145, "alphanum_fraction": 0.6582417488098145, "avg_line_length": 17.219999313354492, "blob_id": "95d76d8e18cb6e38d80fe7b0d2052e5224566b39", "content_id": "652614a970c4b9f8b71dcb4400c017c09ad87649", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 910, "license_type": "no_license", "max_line_length": 65, "num_lines": 50, "path": "/JAICore/jaicore-logic/src/jaicore/logic/fol/structure/VariableParam.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.logic.fol.structure;\n\n/**\n * A variable parameter of a literal.\n * \n * @author mbunse, wever\n */\n@SuppressWarnings(\"serial\")\npublic class VariableParam extends LiteralParam {\n\t\n\tprivate Type type;\n\n\tpublic VariableParam(String name, Type type) {\n\t\tsuper(name);\n\t\tthis.type = type;\n\t}\n\n\tpublic VariableParam(String name) {\n\t\tsuper(name);\n\t}\n\n\tpublic VariableParam(VariableParam toBeCopied) {\n\t\tsuper(toBeCopied.getName());\n\t\tthis.type = toBeCopied.type;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (!(obj instanceof VariableParam))\n\t\t\treturn false;\n\t\treturn super.equals(obj);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tif (getType() != null) {\n\t\t\treturn \"<\" + this.getName() + \":\" + getType().getName() + \">\";\n\t\t} else {\n\t\t\treturn \"<\" + this.getName() + \":undefined>\";\n\t\t}\n\t}\n\n\tpublic Type getType() {\n\t\treturn type;\n\t}\n\n\tpublic void setType(Type type) {\n\t\tthis.type = type;\n\t}\n}" }, { "alpha_fraction": 0.7510316371917725, "alphanum_fraction": 0.7510316371917725, "avg_line_length": 25.961538314819336, "blob_id": "aa7b6fefacf0eee4a7e84d4af35633bc821eee4a", "content_id": "43565cc95976c6702b2f72ba2d0aba1097cb089a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Gradle", "length_bytes": 727, "license_type": "no_license", "max_line_length": 63, "num_lines": 26, "path": "/settings.gradle", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "def jaicorePrefix = 'JAICore/'\r\ndef configPrefix = 'softwareconfiguration/'\r\n\r\n// JAICore\r\n\r\ninclude \":JAICore:jaicore-basic\"\r\ninclude \":JAICore:jaicore-concurrent\"\r\ninclude \":JAICore:jaicore-experiments\"\r\ninclude \":JAICore:jaicore-graph\"\r\ninclude \":JAICore:jaicore-graphvisualizer\"\r\ninclude \":JAICore:jaicore-logic\"\r\ninclude \":JAICore:jaicore-math\"\r\ninclude \":JAICore:jaicore-ml\"\r\n\r\ninclude \":JAICore:jaicore-planning\"\r\ninclude \":JAICore:jaicore-processes\"\r\ninclude \":JAICore:jaicore-search\"\r\ninclude \":JAICore:jaicore-services\"\r\n\r\n\r\n// Software-Configuration\r\ninclude 'hasco'\r\nproject(\":hasco\").projectDir = new File(configPrefix,\"hasco\")\r\n\r\ninclude 'mlplan'\r\nproject(\":mlplan\").projectDir = new File(configPrefix,\"mlplan\")\r\n" }, { "alpha_fraction": 0.8218978047370911, "alphanum_fraction": 0.8218978047370911, "avg_line_length": 41.8125, "blob_id": "63b4bdf02bebd34e22dc1258bf66e096f20a6ecf", "content_id": "f85df32afc2ef3b05dea77ec4f55b8b3695a4320", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 685, "license_type": "no_license", "max_line_length": 140, "num_lines": 16, "path": "/JAICore/jaicore-planning/src/jaicore/planning/model/task/ceocstn/CEOCSTNPlanningProblem.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.model.task.ceocstn;\n\nimport jaicore.logic.fol.structure.CNFFormula;\nimport jaicore.logic.fol.structure.Monom;\nimport jaicore.planning.model.ceoc.CEOCAction;\nimport jaicore.planning.model.ceoc.CEOCOperation;\nimport jaicore.planning.model.task.stn.STNPlanningProblem;\nimport jaicore.planning.model.task.stn.TaskNetwork;\n\n@SuppressWarnings(\"serial\")\npublic class CEOCSTNPlanningProblem<O extends CEOCOperation, M extends OCMethod, A extends CEOCAction> extends STNPlanningProblem<O, M, A> {\n\n\tpublic CEOCSTNPlanningProblem(CEOCSTNPlanningDomain<O,M> domain, CNFFormula knowledge, Monom init, TaskNetwork network) {\n\t\tsuper(domain, knowledge, init, network);\n\t}\n}\n" }, { "alpha_fraction": 0.7382550239562988, "alphanum_fraction": 0.7382550239562988, "avg_line_length": 25.075000762939453, "blob_id": "7016565ef323f44cd2754b13375273d3d03fe77f", "content_id": "cef9b73f9568c135aba368dbf4cc268094ecfa9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1043, "license_type": "no_license", "max_line_length": 102, "num_lines": 40, "path": "/softwareconfiguration/hasco/src/hasco/model/ParameterRefinementConfiguration.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package hasco.model;\n\npublic class ParameterRefinementConfiguration {\n private final boolean initRefinementOnLogScale = true;\n private final int refinementsPerStep;\n private final double intervalLength;\n\n public ParameterRefinementConfiguration(final int refinementsPerStep, final double intervalLength) {\n super();\n this.refinementsPerStep = refinementsPerStep;\n this.intervalLength = intervalLength;\n }\n\n public boolean isInitRefinementOnLogScale() {\n return this.initRefinementOnLogScale;\n }\n\n public int getRefinementsPerStep() {\n return this.refinementsPerStep;\n }\n\n public double getIntervalLength() {\n return this.intervalLength;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n\n sb.append(\"[InitiallyLogScale:\");\n sb.append(this.initRefinementOnLogScale);\n sb.append(\",RefinementsPerStep:\");\n sb.append(this.refinementsPerStep);\n sb.append(\",intervalLength:\");\n sb.append(this.intervalLength);\n sb.append(\"]\");\n\n return sb.toString();\n }\n}\n" }, { "alpha_fraction": 0.7355229258537292, "alphanum_fraction": 0.7389801144599915, "avg_line_length": 28.66666603088379, "blob_id": "b2756b79d92cd9ea3161b1d3c29b82e8c61a9bb2", "content_id": "4267283f29edf307ba79ff0da832cd893e47efec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1157, "license_type": "no_license", "max_line_length": 96, "num_lines": 39, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/mcts/UniformRandomPolicy.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.mcts;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Random;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n\npublic class UniformRandomPolicy<T, A, V extends Comparable<V>> implements IPolicy<T, A, V> {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(UniformRandomPolicy.class);\n\tprivate final Random r;\n\n\tpublic UniformRandomPolicy(Random r) {\n\t\tsuper();\n\t\tthis.r = r;\n\t}\n\n\t@Override\n\tpublic A getAction(T node, Map<A,T> actionsWithTheirSuccessors) {\n\t\t\n\t\tlogger.info(\"Deriving action for node {}. Options are: {}\", node, actionsWithTheirSuccessors);\n\t\t\n\t\tif (actionsWithTheirSuccessors.isEmpty())\n\t\t\tthrow new IllegalArgumentException(\"Cannot determine action if no actions are given!\");\n\t\tif (actionsWithTheirSuccessors.size() == 1)\n\t\t\treturn actionsWithTheirSuccessors.keySet().iterator().next();\n\t\tList<A> keys = new ArrayList<>(actionsWithTheirSuccessors.keySet());\n\t\treturn keys.get(r.nextInt(keys.size() - 1));\n\t}\n\t\n\tpublic void updatePath(List<T> path, V score) {\n\t\t\n\t\tlogger.info(\"Updating path {} with score {}\", path, score);\n\t}\n}\n" }, { "alpha_fraction": 0.7613636255264282, "alphanum_fraction": 0.7613636255264282, "avg_line_length": 24.14285659790039, "blob_id": "84015855f3bbf47bfc2e0b19d9fd027704910fdf", "content_id": "ab182ad5cec876bb58887505e21a0c580723a3a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 176, "license_type": "no_license", "max_line_length": 72, "num_lines": 7, "path": "/softwareconfiguration/hasco/src/hasco/model/BooleanParameterDomain.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package hasco.model;\n\npublic class BooleanParameterDomain extends CategoricalParameterDomain {\n\tpublic BooleanParameterDomain() {\n\t\tsuper(new String[] {\"true\", \"false\"});\n\t}\n}\n" }, { "alpha_fraction": 0.6379147171974182, "alphanum_fraction": 0.6407582759857178, "avg_line_length": 24.04938316345215, "blob_id": "eb2f4d53b2b8c563e657aba1527f867e4869b2d2", "content_id": "ea45b21d9e587af8f0d2dec0d408cd21836cd10c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2110, "license_type": "no_license", "max_line_length": 103, "num_lines": 81, "path": "/JAICore/jaicore-search/src/jaicore/search/model/other/SearchGraphPath.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.model.other;\r\n\r\nimport java.util.Collections;\r\nimport java.util.HashMap;\r\nimport java.util.List;\r\nimport java.util.Map;\r\n\r\npublic class SearchGraphPath<N, A> {\r\n\tprivate final List<N> nodes;\r\n\tprivate final List<A> edges;\r\n\tprivate final Map<String, Object> annotations;\r\n\r\n\tpublic SearchGraphPath(List<N> nodes, List<A> edges) {\r\n\t\tthis(nodes, edges, new HashMap<>());\r\n\t}\r\n\r\n\tpublic SearchGraphPath(List<N> nodes, List<A> edges, Map<String, Object> annotations) {\r\n\t\tsuper();\r\n\t\tthis.nodes = nodes;\r\n\t\tthis.edges = edges;\r\n\t\tthis.annotations = annotations;\r\n\t}\r\n\r\n\tpublic List<N> getNodes() {\r\n\t\treturn Collections.unmodifiableList(nodes);\r\n\t}\r\n\r\n\tpublic List<A> getEdges() {\r\n\t\treturn edges != null ? Collections.unmodifiableList(edges) : null;\r\n\t}\r\n\r\n\tpublic Map<String, Object> getAnnotations() {\r\n\t\treturn annotations;\r\n\t}\r\n\r\n\tpublic void setAnnotation(String key, Object value) {\r\n\t\tthis.annotations.put(key, value);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + ((annotations == null) ? 0 : annotations.hashCode());\r\n\t\tresult = prime * result + ((edges == null) ? 0 : edges.hashCode());\r\n\t\tresult = prime * result + ((nodes == null) ? 0 : nodes.hashCode());\r\n\t\treturn result;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean equals(Object obj) {\r\n\t\tif (this == obj)\r\n\t\t\treturn true;\r\n\t\tif (obj == null)\r\n\t\t\treturn false;\r\n\t\tif (getClass() != obj.getClass())\r\n\t\t\treturn false;\r\n\t\tSearchGraphPath other = (SearchGraphPath) obj;\r\n\t\tif (annotations == null) {\r\n\t\t\tif (other.annotations != null)\r\n\t\t\t\treturn false;\r\n\t\t} else if (!annotations.equals(other.annotations))\r\n\t\t\treturn false;\r\n\t\tif (edges == null) {\r\n\t\t\tif (other.edges != null)\r\n\t\t\t\treturn false;\r\n\t\t} else if (!edges.equals(other.edges))\r\n\t\t\treturn false;\r\n\t\tif (nodes == null) {\r\n\t\t\tif (other.nodes != null)\r\n\t\t\t\treturn false;\r\n\t\t} else if (!nodes.equals(other.nodes))\r\n\t\t\treturn false;\r\n\t\treturn true;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\treturn \"SearchGraphPath [nodes=\" + nodes + \", edges=\" + edges + \", annotations=\" + annotations + \"]\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7682291865348816, "alphanum_fraction": 0.7760416865348816, "avg_line_length": 23.600000381469727, "blob_id": "b9c3fab788b94068104ba607cab3c97c825b0e9e", "content_id": "c56046b846877d1e78db71162a36e00bbba4b9d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 384, "license_type": "no_license", "max_line_length": 65, "num_lines": 15, "path": "/softwareconfiguration/mlplan/src/de/upb/crc901/mlplan/multiclass/wekamlplan/sophisticated/FeaturePreprocessor.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package de.upb.crc901.mlplan.multiclass.wekamlplan.sophisticated;\r\n\r\nimport weka.core.Instance;\r\nimport weka.core.Instances;\r\n\r\npublic interface FeaturePreprocessor {\r\n\r\n\tpublic void prepare(Instances data) throws Exception;\r\n\t\r\n\tpublic Instance apply(Instance data) throws Exception;\r\n\t\r\n\tpublic Instances apply(Instances data) throws Exception;\r\n\r\n\tpublic boolean isPrepared();\r\n}\r\n" }, { "alpha_fraction": 0.7519543766975403, "alphanum_fraction": 0.7529051303863525, "avg_line_length": 35.2681999206543, "blob_id": "1438dcf9885ab044d13a7002a814534e22674391", "content_id": "419012cbb2d254cb542b336da8c5ef02cf035610", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 9466, "license_type": "no_license", "max_line_length": 113, "num_lines": 261, "path": "/softwareconfiguration/mlplan/src/de/upb/crc901/mlplan/metamining/pipelinecharacterizing/WEKAOntologyConnector.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package de.upb.crc901.mlplan.metamining.pipelinecharacterizing;\n\nimport java.io.InputStream;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\nimport org.semanticweb.owlapi.apibinding.OWLManager;\nimport org.semanticweb.owlapi.model.ClassExpressionType;\nimport org.semanticweb.owlapi.model.OWLClass;\nimport org.semanticweb.owlapi.model.OWLDataFactory;\nimport org.semanticweb.owlapi.model.OWLNamedIndividual;\nimport org.semanticweb.owlapi.model.OWLOntology;\nimport org.semanticweb.owlapi.model.OWLOntologyCreationException;\nimport org.semanticweb.owlapi.model.OWLOntologyManager;\n\n/**\n * Represents the connection to the data minining optimization ontology (DMOP)\n * enriched by the implementations of algorithms by WEKA. Thus, an object of\n * this class can be queried for WEKA classifiers as well as instances of\n * ASSearch and ASEvaluation.\n * \n * @author Helena Graf\n *\n */\npublic class WEKAOntologyConnector implements IOntologyConnector {\n\n\tprivate static final List<String> classifierPortfolio = Arrays.asList(\"weka.classifiers.bayes.BayesNet\",\n\t\t\t\"weka.classifiers.bayes.NaiveBayes\", \"weka.classifiers.bayes.NaiveBayesMultinomial\",\n\t\t\t\"weka.classifiers.functions.Logistic\", \"weka.classifiers.functions.MultilayerPerceptron\",\n\t\t\t\"weka.classifiers.functions.SGD\", \"weka.classifiers.functions.SimpleLogistic\",\n\t\t\t\"weka.classifiers.functions.SMO\", \"weka.classifiers.functions.VotedPerceptron\", \"weka.classifiers.lazy.IBk\",\n\t\t\t\"weka.classifiers.lazy.KStar\", \"weka.classifiers.rules.DecisionTable\", \"weka.classifiers.rules.JRip\",\n\t\t\t\"weka.classifiers.rules.OneR\", \"weka.classifiers.rules.PART\", \"weka.classifiers.rules.ZeroR\",\n\t\t\t\"weka.classifiers.trees.DecisionStump\", \"weka.classifiers.trees.J48\", \"weka.classifiers.trees.LMT\",\n\t\t\t\"weka.classifiers.trees.RandomForest\", \"weka.classifiers.trees.RandomTree\",\n\t\t\t\"weka.classifiers.trees.REPTree\");\n\n\tprivate static final List<String> evaluatorPortfolio = Arrays.asList(\"weka.attributeSelection.CfsSubsetEval\",\n\t\t\t\"weka.attributeSelection.CorrelationAttributeEval\", \"weka.attributeSelection.GainRatioAttributeEval\",\n\t\t\t\"weka.attributeSelection.InfoGainAttributeEval\", \"weka.attributeSelection.OneRAttributeEval\",\n\t\t\t\"weka.attributeSelection.PrincipalComponents\", \"weka.attributeSelection.ReliefFAttributeEval\",\n\t\t\t\"weka.attributeSelection.SymmetricalUncertAttributeEval\");\n\n\tprivate static final List<String> searcherPortfolio = Arrays.asList(\"weka.attributeSelection.BestFirst\",\n\t\t\t\"weka.attributeSelection.GreedyStepwise\", \"weka.attributeSelection.Ranker\");\n\n\tprivate static final String ontologyFileName = \"DMOP_modified.owl\";\n\tprivate static final String ontologyIRI = \"http://www.e-lico.eu/ontologies/dmo/DMOP/DMOP.owl\";\n\tprivate static final String ontologyIRISeparator = \"#\";\n\n\tprivate String classifierTopNode = \"ModelingAlgorithm\";\n\tprivate String searcherTopNode = \"SearchStrategy\";\n\tprivate String evaluatorTopNode = \"DataProcessingAlgorithm\";\n\n\tprivate OWLDataFactory dataFactory;\n\tprivate OWLOntology ontology;\n\tprivate boolean includeEqualSuperClasses = true;\n\n\t/**\n\t * Creates an ontology connector using the standard ontology.\n\t * \n\t * @throws OWLOntologyCreationException\n\t * If the ontology cannot be created\n\t */\n\tpublic WEKAOntologyConnector() throws OWLOntologyCreationException {\n\t\tOWLOntologyManager ontologyManager = OWLManager.createOWLOntologyManager();\n\t\tdataFactory = ontologyManager.getOWLDataFactory();\n\t\tInputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(ontologyFileName);\n\t\tontology = ontologyManager.loadOntologyFromOntologyDocument(inputStream);\n\t}\n\n\t@Override\n\tpublic List<String> getAncestorsOfClassifier(String classifierName) {\n\t\tif (!classifierPortfolio.contains(classifierName)) {\n\t\t\tStringBuilder builder = new StringBuilder();\n\t\t\tbuilder.append(classifierName);\n\t\t\tbuilder.append(\" is not supported by the used ontology.\");\n\t\t\tthrow new IllegalArgumentException(builder.toString());\n\t\t}\n\t\treturn getAncestorsOfAlgorithmUntil(classifierName, classifierTopNode);\n\t}\n\n\t@Override\n\tpublic List<String> getAncestorsOfSearcher(String searcher) {\n\t\tif (!searcherPortfolio.contains(searcher)) {\n\t\t\tStringBuilder builder = new StringBuilder();\n\t\t\tbuilder.append(searcher);\n\t\t\tbuilder.append(\" is not supported by the used ontology.\");\n\t\t\tthrow new IllegalArgumentException(builder.toString());\n\t\t}\n\t\treturn getAncestorsOfAlgorithmUntil(searcher, searcherTopNode);\n\t}\n\n\t@Override\n\tpublic List<String> getAncestorsOfEvaluator(String evaluator) {\n\t\tif (!evaluatorPortfolio.contains(evaluator)) {\n\t\t\tStringBuilder builder = new StringBuilder();\n\t\t\tbuilder.append(evaluator);\n\t\t\tbuilder.append(\" is not supported by the used ontology.\");\n\t\t\tthrow new IllegalArgumentException(builder.toString());\n\t\t}\n\t\treturn getAncestorsOfAlgorithmUntil(evaluator, evaluatorTopNode);\n\t}\n\n\t/**\n\t * Get the list of ancestors from most general to most specific concept up until\n\t * the specified concept including the specified child and highest concept.\n\t * \n\t * @param algorithm\n\t * The child algorithm\n\t * @param until\n\t * The highest ancestor\n\t * @return The ancestors of the child algorithm from the highest ancestor to the\n\t * child algorithm itself\n\t */\n\tprotected List<String> getAncestorsOfAlgorithmUntil(String algorithm, String until) {\n\t\t// Get the individual represented by the algorithm\n\t\tOWLNamedIndividual algorithmAsIndividual = dataFactory.getOWLNamedIndividual(getAsOntologyElement(algorithm));\n\t\tOWLClass algorithmClass = ontology.classAssertionAxioms(algorithmAsIndividual).findFirst().get()\n\t\t\t\t.getClassExpression().asOWLClass();\n\n\t\t// Get ancestors\n\t\tArrayList<OWLClass> ancestors = new ArrayList<OWLClass>();\n\t\tancestors.add(algorithmClass);\n\t\tfor (int i = 0; i < ancestors.size(); i++) {\n\t\t\tint previousAncestorSize = ancestors.size();\n\t\t\tontology.subClassAxiomsForSubClass(ancestors.get(i))\n\t\t\t\t\t.filter(axiom -> axiom.getSuperClass().getClassExpressionType() == ClassExpressionType.OWL_CLASS)\n\t\t\t\t\t.forEach(axiom -> {\n\t\t\t\t\t\tOWLClass toAdd = axiom.getSuperClass().asOWLClass();\n\t\t\t\t\t\tancestors.add(toAdd);\n\t\t\t\t\t});\n\t\t\t// If we have not added an element\n\t\t\tif (includeEqualSuperClasses && ancestors.size() == previousAncestorSize) {\n\t\t\t\tontology.equivalentClassesAxioms(ancestors.get(i)).forEach(axiom -> {\n\t\t\t\t\taxiom.classExpressions().forEach(elem -> {\n\t\t\t\t\t\t// System.out.println(elem.conjunctSet().findFirst());\n\t\t\t\t\t\tif (!ancestors.contains(elem.conjunctSet().findFirst().get().asOWLClass())) {\n\t\t\t\t\t\t\tancestors.add(elem.conjunctSet().findFirst().get().asOWLClass());\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t}\n\t\t\t// If we have found the last element, stop\n\t\t\tif (ancestors.get(ancestors.size() - 1).getIRI().getShortForm().equals(until)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// Get names and invert order\n\t\tList<String> ancestorNames = new ArrayList<String>();\n\t\tboolean startAdding = true;\n\t\tfor (int i = ancestors.size() - 1; i >= 0; i--) {\n\t\t\tif (!startAdding) {\n\t\t\t\tString ancestorName = ancestors.get(i).getIRI().getShortForm();\n\t\t\t\tif (ancestorName.equals(until)) {\n\t\t\t\t\tancestorNames.add(ancestorName);\n\t\t\t\t\tstartAdding = true;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tancestorNames.add(ancestors.get(i).getIRI().getShortForm());\n\t\t\t}\n\t\t}\n\t\tancestorNames.add(algorithmAsIndividual.getIRI().getShortForm());\n\n\t\treturn ancestorNames;\n\t}\n\n\tprivate String getAsOntologyElement(String name) {\n\t\tStringBuilder builder = new StringBuilder();\n\t\tbuilder.append(ontologyIRI);\n\t\tbuilder.append(ontologyIRISeparator);\n\t\tbuilder.append(name);\n\n\t\treturn builder.toString();\n\t}\n\n\t/**\n\t * Get the ontology this connector uses.\n\t * \n\t * @return The used ontology\n\t */\n\tpublic OWLOntology getOntology() {\n\t\treturn ontology;\n\t}\n\n\t/**\n\t * Get the fully qualified names of WEKA classifiers that this ontology\n\t * connector can be queried for.\n\t * \n\t * @return The available classifiers\n\t */\n\tpublic List<String> getAvailableClassifiers() {\n\t\treturn classifierPortfolio;\n\t}\n\n\t/**\n\t * Get the fully qualified names of WEKA ASSearch algorithms that this ontology\n\t * can be queried for.\n\t * \n\t * @return THe available searchers\n\t */\n\tpublic List<String> getAvailableSearchers() {\n\t\treturn searcherPortfolio;\n\t}\n\n\t/**\n\t * Get the fully qualified names of WEKA ASEvaluation algorithms that this\n\t * ontology can be queried for.\n\t * \n\t * @return The evailable evaluators\n\t */\n\tpublic List<String> getAvailableEvaluators() {\n\t\treturn evaluatorPortfolio;\n\t}\n\n\tpublic static void main(String[] args) throws OWLOntologyCreationException {\n\t\tWEKAOntologyConnector connector = new WEKAOntologyConnector();\n\n\t\tfor (String classifier : classifierPortfolio) {\n\t\t\tSystem.out.println(connector.getAncestorsOfClassifier(classifier));\n\t\t}\n\n\t\tfor (String searcher : searcherPortfolio) {\n\t\t\tSystem.out.println(connector.getAncestorsOfSearcher(searcher));\n\t\t}\n\n\t\tfor (String evaluator : evaluatorPortfolio) {\n\t\t\tSystem.out.println(connector.getAncestorsOfEvaluator(evaluator));\n\t\t}\n\n\t}\n\n\t/**\n\t * Get the highest common node in the ontology for all classifiers\n\t * \n\t * @return The classifier top node\n\t */\n\tpublic String getClassifierTopNode() {\n\t\treturn classifierTopNode;\n\t}\n\n\t/**\n\t * Get the highest common node in the ontology for all searchers\n\t * \n\t * @return The searcher top node\n\t */\n\tpublic String getSearcherTopNode() {\n\t\treturn searcherTopNode;\n\t}\n\n\t/**\n\t * Get the highest common node in the ontology for all evaluators\n\t * \n\t * @return The evaluator top node\n\t */\n\tpublic String getEvaluatorTopNode() {\n\t\treturn evaluatorTopNode;\n\t}\n}\n" }, { "alpha_fraction": 0.7263768315315247, "alphanum_fraction": 0.7286956310272217, "avg_line_length": 24.74626922607422, "blob_id": "e76e3d02af2a860a7cd434a804a6304700d3fba7", "content_id": "0caed41cb6bcc11df92d5517831491f014ccc41b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1725, "license_type": "no_license", "max_line_length": 110, "num_lines": 67, "path": "/softwareconfiguration/hasco/src/hasco/model/CategoricalParameterDomain.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package hasco.model;\n\nimport java.util.Arrays;\nimport java.util.Collection;\n\npublic class CategoricalParameterDomain extends ParameterDomain {\n\tprivate final String[] values;\n\n\tpublic CategoricalParameterDomain(final String[] values) {\n\t\tsuper();\n\t\tthis.values = values;\n\t}\n\n\tpublic CategoricalParameterDomain(final Collection<String> values) {\n\t\tthis(values.toArray(new String[] {}));\n\t}\n\n\tpublic String[] getValues() {\n\t\treturn this.values;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + Arrays.hashCode(values);\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tCategoricalParameterDomain other = (CategoricalParameterDomain) obj;\n\t\tif (!Arrays.equals(values, other.values))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean contains(Object item) {\n\t\tif (item == null)\n\t\t\tthrow new IllegalArgumentException(\"Cannot request membership of NULL in a categorical parameter domain.\");\n\t\tString itemAsString = item.toString();\n\t\tfor (int i = 0; i < values.length; i++)\n\t\t\tif (values[i].equals(itemAsString))\n\t\t\t\treturn true;\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean subsumes(ParameterDomain otherDomain) {\n\t\tif (!(otherDomain instanceof CategoricalParameterDomain))\n\t\t\treturn false;\n\t\tCategoricalParameterDomain otherCategoricalDomain = (CategoricalParameterDomain)otherDomain;\n\t\treturn Arrays.asList(values).containsAll(Arrays.asList(otherCategoricalDomain.getValues()));\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"CategoricalParameterDomain [values=\" + Arrays.toString(values) + \"]\";\n\t}\n}\n" }, { "alpha_fraction": 0.7001007795333862, "alphanum_fraction": 0.710181474685669, "avg_line_length": 32.8070182800293, "blob_id": "c25f9df762e1f850c82e7d3d5a08f37b1a2b76d2", "content_id": "85f9b0e04d5ebf6eb8bd37319f999c50425a375c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1984, "license_type": "no_license", "max_line_length": 153, "num_lines": 57, "path": "/JAICore/jaicore-ml/src/jaicore/ml/classification/multiclass/reduction/ClassifierCache.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.ml.classification.multiclass.reduction;\r\n\r\nimport java.util.HashMap;\r\nimport java.util.concurrent.locks.Lock;\r\nimport java.util.concurrent.locks.ReentrantLock;\r\n\r\nimport org.apache.commons.lang3.builder.HashCodeBuilder;\r\n\r\nimport jaicore.basic.sets.SetUtil.Pair;\r\nimport weka.classifiers.Classifier;\r\nimport weka.core.Instances;\r\n\r\npublic class ClassifierCache extends HashMap<Integer, Pair<Classifier, Instances>> {\r\n\r\n /**\r\n *\r\n */\r\n private static final long serialVersionUID = -8463580964568016772L;\r\n\r\n private Lock cacheLock = new ReentrantLock();\r\n\r\n public ClassifierCache() {\r\n\r\n }\r\n\r\n public Classifier getCachedClassifier(final String classifierName, final EMCNodeType classificationStrategy, final Instances data) {\r\n int hashCode = new HashCodeBuilder().append(classifierName).append(classificationStrategy).append(data.toString()).toHashCode();\r\n Pair<Classifier, Instances> pair = this.get(hashCode);\r\n if (pair == null) {\r\n return null;\r\n } else {\r\n return this.get(hashCode).getX();\r\n }\r\n }\r\n\r\n public void cacheClassifier(final String classifierName, final EMCNodeType classificationStrategy, final Instances data, final Classifier classifier) {\r\n // int hashCode = new\r\n // HashCodeBuilder().append(classifierName).append(classificationStrategy).append(data.toString()).toHashCode();\r\n // this.cacheLock.lock();\r\n // try {\r\n // this.put(hashCode, new Pair<>(classifier, data));\r\n // } finally {\r\n // this.cacheLock.unlock();\r\n // }\r\n }\r\n\r\n public Instances getCachedTrainingData(final String classifierName, final EMCNodeType classificationStrategy, final Instances data) {\r\n int hashCode = new HashCodeBuilder().append(classifierName).append(classificationStrategy).append(data.toString()).toHashCode();\r\n Pair<Classifier, Instances> pair = this.get(hashCode);\r\n if (pair == null) {\r\n return null;\r\n } else {\r\n return this.get(hashCode).getY();\r\n }\r\n }\r\n\r\n}\r\n" }, { "alpha_fraction": 0.8167116045951843, "alphanum_fraction": 0.8167116045951843, "avg_line_length": 23.733333587646484, "blob_id": "def8c74a3ddf8039d3daf15e932230b695632062", "content_id": "9b8610107b77320f0a8dc05cc3fee551041cb07a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 371, "license_type": "no_license", "max_line_length": 75, "num_lines": 15, "path": "/JAICore/jaicore-ml/src/jaicore/ml/classification/multiclass/reduction/ITreeClassifier.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.ml.classification.multiclass.reduction;\n\nimport java.util.List;\n\nimport weka.classifiers.Classifier;\nimport weka.core.Instance;\n\npublic interface ITreeClassifier extends Classifier {\n\n public int getHeight();\n\n public double classifyInstance(final Instance instance) throws Exception;\n\n public int getDepthOfFirstCommonParent(List<Integer> classes);\n}\n" }, { "alpha_fraction": 0.7974217534065247, "alphanum_fraction": 0.8043277859687805, "avg_line_length": 43.25, "blob_id": "35e441339a436017146e56201621447084713b3a", "content_id": "2ae7624c264d602de7b36464efa032e628816ccf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2172, "license_type": "no_license", "max_line_length": 291, "num_lines": 48, "path": "/softwareconfiguration/mlplan/src/de/upb/crc901/mlplan/multiclass/wekamlplan/weka/WekaMLPlanWekaClassifier.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package de.upb.crc901.mlplan.multiclass.wekamlplan.weka;\r\n\r\nimport java.io.File;\r\nimport java.io.FileInputStream;\r\nimport java.io.IOException;\r\nimport java.util.Properties;\r\n\r\nimport org.aeonbits.owner.ConfigFactory;\r\n\r\nimport de.upb.crc901.mlplan.multiclass.LossFunctionBuilder;\r\nimport de.upb.crc901.mlplan.multiclass.MLPlanClassifierConfig;\r\nimport de.upb.crc901.mlplan.multiclass.wekamlplan.MLPlanWekaBuilder;\r\nimport de.upb.crc901.mlplan.multiclass.wekamlplan.MLPlanWekaClassifier;\r\nimport hasco.serialization.ComponentLoader;\r\nimport jaicore.basic.FileUtil;\r\nimport jaicore.planning.graphgenerators.task.tfd.TFDNode;\r\nimport jaicore.search.algorithms.standard.bestfirst.nodeevaluation.INodeEvaluator;\r\nimport weka.core.Instances;\r\n\r\npublic class WekaMLPlanWekaClassifier extends MLPlanWekaClassifier {\r\n\t\r\n\tstatic MLPlanClassifierConfig loadOwnerConfig(File configFile) throws IOException {\r\n\t\tProperties props = new Properties();\r\n\t\tif (configFile.exists()) {\r\n\t\t\tFileInputStream fis = new FileInputStream(configFile);\r\n\t\t\tprops.load(fis);\r\n\t\t}\r\n\t\telse\r\n\t\t\tSystem.out.println(\"Config file \" + configFile.getAbsolutePath() + \" not found, working with default parameters.\");\r\n\t\treturn ConfigFactory.create(MLPlanClassifierConfig.class, props);\r\n\t}\r\n\r\n\tpublic WekaMLPlanWekaClassifier(MLPlanWekaBuilder builder) throws IOException {\r\n\t\tsuper(builder.getSearchSpaceConfigFile(), new WEKAPipelineFactory(), new LossFunctionBuilder().getEvaluator(builder.getPerformanceMeasure()), builder.getAlhorithmConfigFile() != null ? loadOwnerConfig(builder.getAlhorithmConfigFile()) : ConfigFactory.create(MLPlanClassifierConfig.class));\r\n\t\tPreferenceBasedNodeEvaluator preferenceNodeEvaluator = new PreferenceBasedNodeEvaluator(new ComponentLoader(getComponentFile()).getComponents(), FileUtil.readFileAsList(getConfig().preferredComponents()));\r\n\t\tthis.setPreferredNodeEvaluator(preferenceNodeEvaluator);\r\n\t}\r\n\t\r\n\tpublic WekaMLPlanWekaClassifier() throws IOException {\r\n\t\tthis(new MLPlanWekaBuilder());\r\n\r\n\t}\r\n\r\n\t@Override\r\n\tprotected INodeEvaluator<TFDNode, Double> getSemanticNodeEvaluator(Instances data) {\r\n\t\treturn new SemanticNodeEvaluator(getComponents(), data);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.5634365677833557, "alphanum_fraction": 0.5729270577430725, "avg_line_length": 23.716049194335938, "blob_id": "b6f406039c84ff717a99f979405fc135a31e2ae6", "content_id": "f1515488536c0432b864c63f2377c7173de1a42b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2002, "license_type": "no_license", "max_line_length": 99, "num_lines": 81, "path": "/JAICore/jaicore-search/test/jaicore/search/testproblems/npuzzle/redundant/NPuzzleRedundantGenerator.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "//package jaicore.search.testproblems.npuzzle.redundant;\n//\n//import jaicore.search.testproblems.npuzzle.standard.NPuzzleGenerator;\n//\n//public class NPuzzleRedundantGenerator extends NPuzzleGenerator {\n//\n//\tpublic NPuzzleRedundantGenerator(int dim, int shuffle) {\n//\t\tsuper(dim, shuffle);\n//\t}\n//\n//\tpublic NPuzzleRedundantGenerator(int dim) {\n//\t\tsuper(dim);\n//\t\t\n//\t}\n//\n//\tpublic NPuzzleRedundantGenerator(int[][] board, int emptyX, int emptyY) {\n//\t\tsuper(board, emptyX, emptyY);\n//\t}\n//\t\n//\t\n//\t/**\n//\t * A method which computes a new PuzzleNode after the empty tile was moved.\n//\t * @param n\n//\t * \t\tThe node which contains the boardconfiguration.\n//\t * @param y\n//\t * \t\tThe movement on the y-axis. This value should be -1 if going upwards, 1 if going downwards.\n//\t * \t\tOtherwise it should be 0.\n//\t * @param x\n//\t * \t\tThe movement on the y-axis. This value should be -1 if going left, 1 if going right.\n//\t * \t\tOtherwise it should be 0.\n//\t */\n//\tpublic NPuzzleRedundantNode move(NPuzzleRedundantNode n,String move) {\n//\t\t//cloning the board for the new node\n//\t\tint y;\n//\t\tint x;\n//\t\t\n//\t\tswitch(move) {\n//\t\tcase \"l\" : \n//\t\t\ty = 0;\n//\t\t\tx = -1;\n//\t\t\tbreak;\n//\t\tcase \"r\" : \n//\t\t\ty = 0;\n//\t\t\tx = 1;\n//\t\t\tbreak;\n//\t\tcase \"d\" : \n//\t\t\ty = 1;\n//\t\t\tx = 0;\n//\t\t\tbreak;\n//\t\tcase \"u\" : \n//\t\t\ty = -1;\n//\t\t\tx = 0;\n//\t\t\tbreak;\n//\t\tdefault:\n//\t\t\tSystem.out.println(\"No Valid move.\");\n//\t\t\treturn null;\n//\t}\n//\t\t\n//\t\tif(x == y || Math.abs(x)>1 || Math.abs(y)>1) {\n//\t\t\tSystem.out.println(\"No valid move. No move is executed\");\n//\t\t\treturn null;\n//\t\t}\n//\t\t\n//\t\tint[][] b = new int[dimension][dimension];\n//\t\tfor(int i = 0; i< dimension; i++) {\n//\t\t\tfor(int j= 0; j < dimension ; j++) {\n//\t\t\t\tb[i][j] = n.getBoard()[i][j];\n//\t\t\t}\n//\t\t}\n//\t\tint eX = n.getEmptyX();\n//\t\tint eY = n.getEmptyY();\n////\t\tint help = b[eY][eX];\n//\t\tb[eY][eX] = b[eY +y][eX+x];\n//\t\tb[eY+y][eX+x] = 0;\n//\t\t\n//\t\tNPuzzleRedundantNode node = new NPuzzleRedundantNode(b, eX+x, eY+y, n.getMoves()+move);\n//\t\t\n//\t\treturn node;\t\t\n//\t}\n//\n//}\n" }, { "alpha_fraction": 0.6940667629241943, "alphanum_fraction": 0.6965389251708984, "avg_line_length": 24.682538986206055, "blob_id": "de3292a543c175e4947b06343405ec21d72c635d", "content_id": "bd622b131aad170eee7d2e01146653ab5f65adea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1618, "license_type": "no_license", "max_line_length": 124, "num_lines": 63, "path": "/JAICore/jaicore-planning/src/jaicore/planning/model/strips/StripsOperation.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.model.strips;\n\nimport java.util.List;\n\nimport jaicore.logic.fol.structure.Monom;\nimport jaicore.logic.fol.structure.VariableParam;\nimport jaicore.planning.model.core.Operation;\n\n@SuppressWarnings(\"serial\")\npublic class StripsOperation extends Operation {\n\t\n\tprivate final Monom addList, deleteList;\n\n\tpublic StripsOperation(String name, List<VariableParam> params, Monom precondition, Monom addList, Monom deleteList) {\n\t\tsuper(name, params, precondition);\n\t\tthis.addList = addList;\n\t\tthis.deleteList = deleteList;\n\t}\n\n\tpublic Monom getAddList() {\n\t\treturn addList;\n\t}\n\n\tpublic Monom getDeleteList() {\n\t\treturn deleteList;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"StripsOperation [precondition=\" + getPrecondition() + \", addList=\" + addList + \", deleteList=\" + deleteList + \"]\";\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = super.hashCode();\n\t\tresult = prime * result + ((addList == null) ? 0 : addList.hashCode());\n\t\tresult = prime * result + ((deleteList == null) ? 0 : deleteList.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (!super.equals(obj))\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tStripsOperation other = (StripsOperation) obj;\n\t\tif (addList == null) {\n\t\t\tif (other.addList != null)\n\t\t\t\treturn false;\n\t\t} else if (!addList.equals(other.addList))\n\t\t\treturn false;\n\t\tif (deleteList == null) {\n\t\t\tif (other.deleteList != null)\n\t\t\t\treturn false;\n\t\t} else if (!deleteList.equals(other.deleteList))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n}\n" }, { "alpha_fraction": 0.7779960632324219, "alphanum_fraction": 0.7779960632324219, "avg_line_length": 27.33333396911621, "blob_id": "f817c9818c9a4c2790a9cbef2ebf1f12872b708b", "content_id": "9cb69cbf31d824a37e6b037869b534e9e337f869", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 509, "license_type": "no_license", "max_line_length": 98, "num_lines": 18, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/astar/AStar.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.astar;\n\nimport jaicore.search.algorithms.standard.bestfirst.BestFirst;\nimport jaicore.search.model.probleminputs.NumberBasedAdditiveTraversalTree;\n\n/**\n * A* algorithm implementation that is nothing else than BestFirst with a\n * specific problem input.\n *\n * @author Felix Mohr\n */\npublic class AStar<N, A> extends BestFirst<NumberBasedAdditiveTraversalTree<N, A>, N, A, Double> {\n\n\tpublic AStar(NumberBasedAdditiveTraversalTree<N, A> problem) {\n\t\tsuper(problem);\n\t}\n\t\n}" }, { "alpha_fraction": 0.815315306186676, "alphanum_fraction": 0.815315306186676, "avg_line_length": 29.272727966308594, "blob_id": "bc385f421e4e74980e097f98937a823d5f4be070", "content_id": "9f79d59941596f0a72aed4af8cb8a858bb814538", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 666, "license_type": "no_license", "max_line_length": 116, "num_lines": 22, "path": "/JAICore/jaicore-planning/src/jaicore/planning/model/task/IHTNPlanningProblem.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.model.task;\n\nimport java.io.Serializable;\n\nimport jaicore.logic.fol.structure.CNFFormula;\nimport jaicore.logic.fol.structure.Monom;\nimport jaicore.planning.model.core.Action;\nimport jaicore.planning.model.core.Operation;\nimport jaicore.planning.model.task.stn.Method;\nimport jaicore.planning.model.task.stn.STNPlanningDomain;\nimport jaicore.planning.model.task.stn.TaskNetwork;\n\npublic interface IHTNPlanningProblem<O extends Operation, M extends Method, A extends Action> extends Serializable {\n\n\tpublic STNPlanningDomain<O, M> getDomain();\n\n\tpublic CNFFormula getKnowledge();\n\n\tpublic Monom getInit();\n\n\tpublic TaskNetwork getNetwork();\n}\n" }, { "alpha_fraction": 0.7568420767784119, "alphanum_fraction": 0.7615789771080017, "avg_line_length": 46.5, "blob_id": "de8615aa0bac354cb870d68ecd6d82eb17d67f72", "content_id": "f86f1f8c84588892cd1c7033cd802ee3145adf67", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1900, "license_type": "no_license", "max_line_length": 267, "num_lines": 40, "path": "/README.md", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "[![Build Status](https://travis-ci.org/fmohr/AILibs.svg?branch=dev)](https://travis-ci.org/fmohr/AILibs)\n\n\n# AILibs\nAILibs is a collection of Java libraries related to automated decision making. It currently consists of two building blocks. It is also home of the current version of the AutoML-tool [ML-Plan](https://github.com/fmohr/AILibs/tree/master/softwareconfiguration/mlplan).\n\n* **JAICore** (Java AI Core) is a collection of projects with basic general purpose AI algorithms mainly in the area of logic reasoning, heuristic search, and machine learning\n* **softwareconfiguration** is a collection of projects related to automatically configuring software systems. Here we also maintain the code for our AutoML flagship **[ML-Plan](https://github.com/fmohr/AILibs/tree/master/softwareconfiguration/mlplan)**\n\n## Using AILibs in your project\nYou can resolve snapshots of this projects via a maven-dependency.\n### Gradle \nFirst register our departements nexus as a maven repository:\n```\nrepositories {\n mavenCentral()\n\t maven { url \"https://nexus.cs.upb.de/repository/sfb901-snapshots/\" }\n}\n```\nThen, you can either import the bundeled library via:\n```\ndependencies {\n\t compile group: \"de.upb.isys\", name: \"AILibs\", version:\"0.0.1-SNAPSHOT\"\n}\n```\nOr, the different artifacts individually e.g.\n```\ndependencies {\n\t compile group: \"de.upb.isys\", name: \"jaicore-ml\", version:\"0.0.1-SNAPSHOT\"\n}\n```\n\n## Setting up your IDE to work with AILibs\n### Eclipse\nNavigate to the folder where you cloned this repository and run\n```\n ./gradlew eclipse\n```\nThis automatically creates the eclipse project files and configures the dependencies among the projects.\nThen open Eclipse and go to the import menu, e.g., in the package manager. Choose to import *Existing Projects into Workspace*, select the folder where you cloned the repository, and make sure to check the *Search for nested projects* option.\n" }, { "alpha_fraction": 0.6549526453018188, "alphanum_fraction": 0.6618432402610779, "avg_line_length": 36.19078826904297, "blob_id": "65cd31821e5aab9b5990336fae9eea4d501437e3", "content_id": "82da39c6ac8726e998fff6139a714801ec7ca74f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5805, "license_type": "no_license", "max_line_length": 114, "num_lines": 152, "path": "/softwareconfiguration/mlplan/examples/de/upb/crc901/mlplan/examples/multiclass/weka/MLPlanWekaCLI.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package de.upb.crc901.mlplan.examples.multiclass.weka;\r\n\r\nimport java.io.BufferedWriter;\r\nimport java.io.FileInputStream;\r\nimport java.io.FileNotFoundException;\r\nimport java.io.FileReader;\r\nimport java.io.FileWriter;\r\nimport java.io.IOException;\r\nimport java.sql.Time;\r\nimport java.util.List;\r\nimport java.util.Properties;\r\nimport java.util.Random;\r\n\r\nimport org.aeonbits.owner.ConfigFactory;\r\n\r\nimport de.upb.crc901.mlplan.multiclass.wekamlplan.MLPlanWekaClassifier;\r\nimport de.upb.crc901.mlplan.multiclass.wekamlplan.weka.WekaMLPlanWekaClassifier;\r\nimport jaicore.ml.WekaUtil;\r\nimport weka.classifiers.Evaluation;\r\nimport weka.core.Instances;\r\n\r\npublic class MLPlanWekaCLI {\r\n\r\n\tpublic static void main(final String[] args) throws FileNotFoundException, IOException {\r\n\t\t\r\n\t\tif (args.length > 0 && args[0].equals(\"-h\")) {\r\n\t\t\tSystem.out.println(\"Parameters to set: \");\r\n\t\t\tSystem.out.println(\"<dataset_file> <global_timeout> <evaluation_timeout>\");\r\n\t\t\tSystem.exit(0);\r\n\t\t}\r\n\t\t\r\n\t\tProperties properties = new Properties();\r\n\t\tproperties.load(new FileInputStream(\"conf/mlplan/mlplanwekacli.properties\"));\r\n\t\tfinal MLPlanWekaCLIConfig CLI_CONFIG = ConfigFactory.create(MLPlanWekaCLIConfig.class, properties);\r\n\t\tSystem.out.println(\"Config \" + CLI_CONFIG + \" initialized.\");\r\n\r\n\t\t/* set dataset file if given */\r\n\t\tif (args.length > 0) {\r\n\t\t\tCLI_CONFIG.setProperty(MLPlanWekaCLIConfig.K_MLPLAN_DATASET_FILE, args[0]);\r\n\t\t}\r\n\t\t/* set global timeout, if given */\r\n\t\tif (args.length > 1) {\r\n\t\t\tCLI_CONFIG.setProperty(MLPlanWekaCLIConfig.K_MLPLAN_TIMEOUT, args[1]);\r\n\t\t}\r\n\t\t/* set timeout for single evaluation, if given */\r\n\t\tif (args.length > 2) {\r\n\t\t\tCLI_CONFIG.setProperty(MLPlanWekaCLIConfig.K_MLPLAN_EVAL_TIMEOUT, args[2]);\r\n\t\t}\r\n\r\n\t\t/* set ports for pipeline plans */\r\n\t\tSystem.out.println(getTime() + \" Load dataset \" + CLI_CONFIG.datasetFile() + \"...\");\r\n\t\tInstances data = null;\r\n\t\ttry {\r\n\t\t\tdata = new Instances(new FileReader(CLI_CONFIG.datasetFile()));\r\n\t\t} catch (IOException e) {\r\n\t\t\tSystem.err.println(\"Could not load dataset at \" + CLI_CONFIG.datasetFile());\r\n\t\t\tSystem.exit(1);\r\n\t\t}\r\n\t\tdata.setClassIndex(data.numAttributes() - 1);\r\n\t\tSystem.out.println(getTime() + \" Dataset loaded.\");\r\n\r\n\t\t/* extract all relevant information about the experiment */\r\n\t\tSystem.out.println(getTime() + \" Initialize ML-Plan...\");\r\n\t\tMLPlanWekaClassifier mlPlan = new WekaMLPlanWekaClassifier();\r\n\t\tmlPlan.setTimeout(CLI_CONFIG.timeout());\r\n\t\tmlPlan.setTimeoutForSingleSolutionEvaluation(CLI_CONFIG.evalTimeout() * 1000);\r\n\t\tif (CLI_CONFIG.showGraphVisualization())\r\n\t\t\tmlPlan.activateVisualization();\r\n\r\n\t\tSystem.out.println(getTime() + \" Split the data into train and test set...\");\r\n\t\tList<Instances> testSplit = WekaUtil.getStratifiedSplit(data, new Random(mlPlan.getConfig().randomSeed()), 0.7);\r\n\t\tSystem.out.println(\"Data split created.\");\r\n\r\n\t\ttry {\r\n\t\t\tSystem.out.println(\"Run ML-Plan...\");\r\n\t\t\tmlPlan.buildClassifier(testSplit.get(0));\r\n\t\t\tSystem.out.println(\"Execution of ML-Plan finished.\");\r\n\r\n\t\t\tSystem.out.println(\"Best Solution found:\" + mlPlan.getSelectedClassifier());\r\n\r\n\t\t\tSystem.out.println(\"Assess quality of found \");\r\n\t\t\tEvaluation eval = new Evaluation(data);\r\n\t\t\teval.evaluateModel(mlPlan, testSplit.get(1), new Object[] {});\r\n\r\n\t\t\tStringBuilder sb = new StringBuilder();\r\n\t\t\tsb.append(\"Pct Correct: \" + eval.pctCorrect());\r\n\t\t\tsb.append(\"\\n\");\r\n\t\t\tsb.append(\"Pct Incorrect: \" + eval.pctIncorrect());\r\n\t\t\tsb.append(\"\\n\");\r\n\t\t\tsb.append(\"Pct Unclassified: \" + eval.pctUnclassified());\r\n\t\t\tsb.append(\"\\n\");\r\n\t\t\tsb.append(\"True Positive Rate: \" + eval.truePositiveRate(0));\r\n\t\t\tsb.append(\"\\n\");\r\n\t\t\tsb.append(\"False Positive Rate: \" + eval.falsePositiveRate(0));\r\n\t\t\tsb.append(\"\\n\");\r\n\t\t\tsb.append(\"False Negative Rate: \" + eval.falseNegativeRate(0));\r\n\t\t\tsb.append(\"\\n\");\r\n\t\t\tsb.append(\"True Negative Rate: \" + eval.trueNegativeRate(0));\r\n\t\t\tsb.append(\"\\n\");\r\n\t\t\tsb.append(\"F-Measure: \" + eval.fMeasure(0));\r\n\t\t\tsb.append(\"\\n\");\r\n\t\t\tsb.append(\"Weighted F-Measure: \" + eval.weightedFMeasure());\r\n\t\t\tsb.append(\"\\n\");\r\n\t\t\tsb.append(\"Area under ROC: \" + eval.areaUnderROC(0));\r\n\t\t\tsb.append(\"\\n\");\r\n\t\t\tsb.append(\"Area under PRC: \" + eval.areaUnderPRC(0));\r\n\t\t\tsb.append(\"\\n\");\r\n\t\t\tsb.append(\"Error Rate: \" + eval.errorRate());\r\n\t\t\tsb.append(\"\\n\");\r\n\t\t\tsb.append(\"Unclassified: \" + eval.unclassified());\r\n\t\t\tsb.append(\"\\n\");\r\n\t\t\tsb.append(\"Incorrect: \" + eval.incorrect());\r\n\t\t\tsb.append(\"\\n\");\r\n\t\t\tsb.append(\"Correct: \" + eval.correct());\r\n\t\t\tsb.append(\"\\n\");\r\n\t\t\tsb.append(\"Kappa: \" + eval.kappa());\r\n\t\t\tsb.append(\"\\n\");\r\n\t\t\tsb.append(\"Root Mean Squared Error: \" + eval.rootMeanSquaredError());\r\n\t\t\tsb.append(\"\\n\");\r\n\t\t\tsb.append(\"Mean Absolute Error: \" + eval.meanAbsoluteError());\r\n\t\t\tsb.append(\"\\n\");\r\n\t\t\tsb.append(\"Precision: \" + eval.precision(0));\r\n\t\t\tsb.append(\"\\n\");\r\n\t\t\tsb.append(\"Recall: \" + eval.recall(0));\r\n\t\t\tsb.append(\"\\n\");\r\n\r\n\t\t\tSystem.out.println(sb.toString());\r\n\r\n\t\t\ttry (BufferedWriter bw = new BufferedWriter(new FileWriter(CLI_CONFIG.outputFile()))) {\r\n\t\t\t\tbw.write(\"Best Solution found: \" + mlPlan.getSelectedClassifier());\r\n\t\t\t\tbw.write(\"\\n\");\r\n\t\t\t\tbw.write(\"============================================\");\r\n\t\t\t\tbw.write(\"\\n\");\r\n\t\t\t\tbw.write(\"Measured test performance: \");\r\n\t\t\t\tbw.write(\"\\n\");\r\n\t\t\t\tbw.write(sb.toString());\r\n\t\t\t}\r\n\r\n\t\t\tSystem.out.println(\"Accuracy: \" + eval.pctCorrect() / 100);\r\n\t\t\tSystem.out.println(\"Error Rate: \" + eval.errorRate());\r\n\t\t\tSystem.out.println(\"Unweighted Macro F Measure: \" + eval.unweightedMacroFmeasure());\r\n\t\t\tSystem.out.println(\"Weighted F Measure: \" + eval.weightedFMeasure());\r\n\t\t} catch (Exception e) {\r\n\t\t\tSystem.out.println(\"Could not successfully execute ML-PLan.\");\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static String getTime() {\r\n\t\treturn \"[\" + new Time(System.currentTimeMillis()).toString() + \"]\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7246127128601074, "alphanum_fraction": 0.8055077195167542, "avg_line_length": 25.454545974731445, "blob_id": "fe549bc80fb7cf74d8ab16761de4b542dda77971", "content_id": "ec4f9ba4b113049997b24aa57e943902718d1b9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 581, "license_type": "no_license", "max_line_length": 57, "num_lines": 22, "path": "/JAICore/JAICore/build/manifest/JAICore.properties", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "Manifest-Version=1.0\nImplementation-Title=de.upb.isys#JAICore;0.0.1-SNAPSHOT\nImplementation-Version=0.0.1-SNAPSHOT\nBuilt-Status=integration\nBuilt-By=elppa\nBuilt-OS=Mac OS X\nBuild-Date=2018-06-03_21:43:34\nGradle-Version=4.3.1\nModule-Source=/jaicore/JAICore\nModule-Origin=https://github.com/mirkojuergens/AILibs.git\nChange=01f9c6e\nBranch=master\nBuild-Host=Mirkos-MacBook-Pro.local\nBuild-Job=LOCAL\nBuild-Number=LOCAL\nBuild-Id=LOCAL\nCreated-By=1.8.0_151-b12 (Oracle Corporation)\nBuild-Java-Version=1.8.0_151\nModule-Owner=\nModule-Email=\nX-Compile-Target-JDK=1.8\nX-Compile-Source-JDK=1.8" }, { "alpha_fraction": 0.801886796951294, "alphanum_fraction": 0.801886796951294, "avg_line_length": 19.200000762939453, "blob_id": "934b105c21cc676570768fdeaea4691cfa18f1a5", "content_id": "2640e18f738ce081ecfa4328c552a89148d32d8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 106, "license_type": "no_license", "max_line_length": 63, "num_lines": 5, "path": "/JAICore/jaicore-basic/src/jaicore/basic/algorithm/AlgorithmFinishedEvent.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.basic.algorithm;\r\n\r\npublic class AlgorithmFinishedEvent implements AlgorithmEvent {\r\n\r\n}\r\n" }, { "alpha_fraction": 0.8139534592628479, "alphanum_fraction": 0.8139534592628479, "avg_line_length": 22.571428298950195, "blob_id": "9c4c5bb866262f00611018a369fd10a89b3c1fd0", "content_id": "1e93e63b932e53ce6a64da6e6dcddb9c2999307c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 172, "license_type": "no_license", "max_line_length": 64, "num_lines": 7, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/lds/NoMoreNodesOnLevelEvent.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.lds;\r\n\r\nimport jaicore.basic.algorithm.AlgorithmEvent;\r\n\r\npublic class NoMoreNodesOnLevelEvent implements AlgorithmEvent {\r\n\r\n}\r\n" }, { "alpha_fraction": 0.7715325355529785, "alphanum_fraction": 0.7715325355529785, "avg_line_length": 33.34722137451172, "blob_id": "f09947ff9ffe2dbed400fc6a90d10d166954cf8f", "content_id": "8058138c54ef5946e4f13c205bfe783b10b22435", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2473, "license_type": "no_license", "max_line_length": 154, "num_lines": 72, "path": "/JAICore/jaicore-ml/src/jaicore/ml/core/WekaCompatibleInstancesImpl.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.ml.core;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.node.ArrayNode;\nimport com.fasterxml.jackson.databind.node.ObjectNode;\n\nimport jaicore.basic.FileUtil;\nimport jaicore.ml.interfaces.LabeledInstance;\n\n@SuppressWarnings(\"serial\")\npublic class WekaCompatibleInstancesImpl extends SimpleLabeledInstancesImpl {\n\n\tprivate final List<String> declaredClasses;\n\n\tpublic WekaCompatibleInstancesImpl(List<String> declaredClasses) {\n\t\tthis.declaredClasses = new ArrayList<>(declaredClasses);\n\t}\n\t\n\tpublic WekaCompatibleInstancesImpl(String json) throws IOException {\n\t\tthis (new ObjectMapper().readTree(json));\n\t}\n\n\tpublic WekaCompatibleInstancesImpl(JsonNode jsonNode) {\n\t\tif (!jsonNode.has(\"declaredclasses\"))\n\t\t\tthrow new IllegalArgumentException(\"Given JSON serialization does not specify the declared classes, which is required for WEKA compatibility.\");\n\t\tJsonNode declaredClasses = jsonNode.get(\"declaredclasses\");\n\t\tif (!declaredClasses.isArray())\n\t\t\tthrow new IllegalArgumentException(\"Class declaration in given JSON is not an array, which is required for WEKA compatibility.\");\n\t\tthis.declaredClasses = new ArrayList<>();\n\t\tfor (JsonNode c : jsonNode.get(\"declaredclasses\")) {\n\t\t\tthis.declaredClasses.add(c.asText());\n\t\t}\n\t\taddAllFromJson(jsonNode);\n\t}\n\n\tpublic WekaCompatibleInstancesImpl(File jsonFile) throws IOException {\n\t\tthis (FileUtil.readFileAsString(jsonFile));\n\t}\n\n\tpublic boolean add(LabeledInstance<String> i) {\n\t\tif (!declaredClasses.contains(i.getLabel()))\n\t\t\tthrow new IllegalArgumentException(\"Instance with label \" + i.getLabel() + \" cannot be inserted in a dataset with declared labels \" + declaredClasses);\n\t\treturn super.add(i);\n\t}\n\n\tpublic List<String> getDeclaredClasses() {\n\t\treturn Collections.unmodifiableList(declaredClasses);\n\t}\n\t\n\t@Override\n\tpublic String toJson() {\n\t\tString json = super.toJson();\n\t\ttry {\n\t\t\tObjectNode node = (ObjectNode)new ObjectMapper().readTree(json);\n\t\t\tArrayNode declaredClasses = node.putArray(\"declaredclasses\");\n\t\t\tfor (String declaredClass : this.declaredClasses) {\n\t\t\t\tdeclaredClasses.add(declaredClass);\n\t\t\t}\n\t\t\treturn node.toString();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\tthrow new IllegalStateException(\"Could not convert dataset to json\");\n\t}\n}\n" }, { "alpha_fraction": 0.7953703999519348, "alphanum_fraction": 0.7953703999519348, "avg_line_length": 50.42856979370117, "blob_id": "5903faff31eff471dcbdfd888d2f0c8b25174768", "content_id": "ed0765f9f334609eb4eb91507350c44f69258227", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1080, "license_type": "no_license", "max_line_length": 128, "num_lines": 21, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/uncertainty/explorationexploitationsearch/IPhaseLengthAdjuster.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.uncertainty.explorationexploitationsearch;\n\npublic interface IPhaseLengthAdjuster {\n\t\n\t/**\n\t * Called before the search to set the phase lengths initially.\n\t * @param interval Overall length of both phases combined.\n\t * @return An array with two elements [newExplorationPhaseLength, newExploitationPhaseLength] to adjust the phase lengths.\n\t */\n\tpublic int[] getInitialPhaseLengths(int interval);\n\t\n\t/**\n\t * Called on every complete iteration of an exploration and an exploitation phase to determine how to change the phase lengths.\n\t * @param currentExplorationLength Current length of the exploration phase.\n\t * @param currentExploitationLength Current length of the exploitation phase.\n\t * @param passedTime Passed time of the search.\n\t * @param timout Timeout for the search.\n\t * @return An array with two elements [newExplorationPhaseLength, newExploitationPhaseLength] to adjust the phase lengths.\n\t */\n\tpublic int[] adjustPhaseLength (int currentExplorationLength, int currentExploitationLength, long passedTime, long timeout);\n}\n" }, { "alpha_fraction": 0.7228797078132629, "alphanum_fraction": 0.7243589758872986, "avg_line_length": 25, "blob_id": "8440d22256bb4d98d03744ee1bee4fffbe69497b", "content_id": "9538b40bc70f77ce6477f3c43615b685a75d1c97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2028, "license_type": "no_license", "max_line_length": 115, "num_lines": 78, "path": "/JAICore/jaicore-search/test/jaicore/search/testproblems/nqueens/NQueenGenerator.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.testproblems.nqueens;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport jaicore.search.algorithms.parallel.parallelexploration.distributed.interfaces.SerializableGraphGenerator;\nimport jaicore.search.model.travesaltree.NodeExpansionDescription;\nimport jaicore.search.model.travesaltree.NodeType;\nimport jaicore.search.structure.graphgenerator.MultipleRootGenerator;\nimport jaicore.search.structure.graphgenerator.NodeGoalTester;\nimport jaicore.search.structure.graphgenerator.SingleRootGenerator;\nimport jaicore.search.structure.graphgenerator.SuccessorGenerator;\n\n@SuppressWarnings(\"serial\")\npublic class NQueenGenerator implements SerializableGraphGenerator<QueenNode,String> {\n\t\n\tint dimension;\n\tMultipleRootGenerator<QueenNode> root;\n\t\n\tpublic NQueenGenerator(int dimension) {\n\t\tthis.dimension = dimension;\t\t\n\t}\n\n//\t@Override\n//\tpublic MultipleRootGenerator<QueenNode> getRootGenerator() {\n//\t\treturn () ->{\n//\t\t\tList<QueenNode> l = new ArrayList<>();\n//\t\t\tfor(int i = 0; i < dimension; i++) {\n//\t\t\t\tl.add(new QueenNode(0,i, dimension));\n//\t\t\t}\n//\t\t\treturn l;\n//\t\t};\n//\t}\n\t\n\t@Override\n\tpublic SingleRootGenerator<QueenNode> getRootGenerator(){\n\t\treturn () -> new QueenNode(dimension);\n\t}\n\n\t@Override\n\tpublic SuccessorGenerator<QueenNode, String> getSuccessorGenerator() {\n\t\treturn n ->{\n\t\t\tList<NodeExpansionDescription<QueenNode,String>> l = new ArrayList<>();\n\t\t\tint currentRow = n.getPositions().size();\n\t\t\tfor(int i = 0; i < dimension; i++) {\n\t\t\t\tif(! n.attack(currentRow, i)){\n\t\t\t\t\tl.add(new NodeExpansionDescription<>(n, new QueenNode(n, i), \"(\" + currentRow + \", \" + i + \")\", NodeType.OR));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn l;\n\t\t};\n\t}\n\n\t@Override\n\tpublic NodeGoalTester<QueenNode> getGoalTester() {\n\t\treturn n -> {\n\t\t\tif(n.getNumberOfQueens() == dimension)\n\t\t\t\treturn true;\n\t\t\telse\n\t\t\t\treturn false;\n\t\t\t\n\t\t};\n\t}\n\n\t@Override\n\tpublic boolean isSelfContained() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic void setNodeNumbering(boolean nodenumbering) {\n\t\t// TODO Auto-generated method stub\n\t\t\n\t}\n\t\n\t\n\n}\n" }, { "alpha_fraction": 0.621169924736023, "alphanum_fraction": 0.6309192180633545, "avg_line_length": 30.217391967773438, "blob_id": "8d52b3ac75024d88c3cef3b62b4057b112a763ae", "content_id": "9b72d0117c6d1d4a14e75e324e577debd36cd100", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 718, "license_type": "no_license", "max_line_length": 105, "num_lines": 23, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/uncertainty/paretosearch/RandomComparator.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.uncertainty.paretosearch;\n\nimport java.util.Comparator;\nimport java.util.Random;\n\npublic class RandomComparator<T, V extends Comparable<V>> implements Comparator<ParetoNode<T, V>> {\n\n /**\n * Randomly outputs a negative or positive integer. (Never zero).\n * @param first\n * @param second\n * @return negative iff first.n < second.n, 0 iff fist.n == second.n, positive iff first.n > second.n\n */\n public int compare(ParetoNode<T, V> first, ParetoNode<T, V> second) {\n Random random = new Random();\n int r = random.nextInt(2); // This is either 0 or 1.\n if (r==0)\n return -1;\n else\n return 1;\n }\n\n}\n" }, { "alpha_fraction": 0.7164179086685181, "alphanum_fraction": 0.7172320485115051, "avg_line_length": 29.204917907714844, "blob_id": "223e48e85574c5e5af5c36098ed31ae93083aaca", "content_id": "d8bcdc2decb67c538d51570cbeaff8a9560d93ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3685, "license_type": "no_license", "max_line_length": 160, "num_lines": 122, "path": "/JAICore/jaicore-ml/src/jaicore/ml/core/SimpleLabeledInstancesImpl.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.ml.core;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.node.ArrayNode;\nimport com.fasterxml.jackson.databind.node.ObjectNode;\n\nimport jaicore.basic.FileUtil;\nimport jaicore.ml.interfaces.LabeledInstance;\nimport jaicore.ml.interfaces.LabeledInstances;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.Set;\n\n@SuppressWarnings(\"serial\")\npublic class SimpleLabeledInstancesImpl extends ArrayList<LabeledInstance<String>> implements LabeledInstances<String> {\n\n private int numColumns = -1;\n\n private Set<String> occurringLabels = new HashSet<>();\n\n public SimpleLabeledInstancesImpl() {\n }\n\n public SimpleLabeledInstancesImpl(final String json) throws IOException {\n this.addAllFromJson(json);\n }\n\n public SimpleLabeledInstancesImpl(final JsonNode jsonNode) {\n this.addAllFromJson(jsonNode);\n }\n\n public SimpleLabeledInstancesImpl(final File jsonFile) throws IOException {\n this.addAllFromJson(jsonFile);\n }\n\n @Override\n public boolean add(final LabeledInstance<String> instance) {\n /* check instance format */\n if (this.numColumns < 0) {\n this.numColumns = instance.getNumberOfColumns();\n } else if (this.numColumns != instance.getNumberOfColumns()) {\n throw new IllegalArgumentException(\"Cannot add \" + instance.getNumberOfColumns() + \"-valued instance to dataset with \" + this.numColumns + \" instances.\");\n }\n\n this.occurringLabels.add(instance.getLabel());\n\n return super.add(instance);\n }\n\n @Override\n public int getNumberOfRows() {\n return this.size();\n }\n\n @Override\n public int getNumberOfColumns() {\n return this.numColumns;\n }\n\n @Override\n public String toJson() {\n ObjectMapper om = new ObjectMapper();\n ObjectNode root = om.createObjectNode();\n ArrayNode instances = root.putArray(\"instances\");\n ArrayNode labels = root.putArray(\"labels\");\n for (LabeledInstance<String> instance : this) {\n ArrayNode instanceArray = instances.addArray();\n for (Double val : instance) {\n instanceArray.add(val);\n }\n labels.add(instance.getLabel().toString());\n }\n try {\n return om.writeValueAsString(root);\n } catch (JsonProcessingException e) {\n e.printStackTrace();\n return null;\n }\n }\n\n @Override\n public ArrayList<String> getOccurringLabels() {\n return new ArrayList<>(this.occurringLabels);\n }\n\n @Override\n public void addAllFromJson(final String json) throws IOException {\n ObjectMapper mapper = new ObjectMapper();\n JsonNode root = mapper.readTree(json);\n this.addAllFromJson(root);\n }\n\n public void addAllFromJson(final JsonNode jsonNode) {\n JsonNode instances = jsonNode.get(\"instances\");\n JsonNode labels = jsonNode.get(\"labels\");\n if (labels == null) {\n throw new IllegalArgumentException(\"No labels provided in the dataset!\");\n }\n if (instances.size() != labels.size()) {\n throw new IllegalArgumentException(\"Number of labels does not match the number of instances!\");\n }\n int index = 0;\n for (JsonNode instance : instances) {\n LabeledInstance<String> labeledInstance = new SimpleLabeledInstanceImpl();\n for (JsonNode val : instance) {\n labeledInstance.add(val.asDouble());\n }\n labeledInstance.setLabel(labels.get(index++).asText());\n this.add(labeledInstance);\n }\n }\n\n @Override\n public void addAllFromJson(final File jsonFile) throws IOException {\n this.addAllFromJson(FileUtil.readFileAsString(jsonFile));\n }\n}\n" }, { "alpha_fraction": 0.7010582089424133, "alphanum_fraction": 0.7037037014961243, "avg_line_length": 29.85714340209961, "blob_id": "8fb8c057a3d1901ddd684e7259d44d9d1fa0aa2e", "content_id": "9086029cb76613fd597732ba281078b266b14152", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1512, "license_type": "no_license", "max_line_length": 85, "num_lines": 49, "path": "/JAICore/jaicore-services/src/jaicore/services/RuleReader.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.services;\n\nimport java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Collection;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class RuleReader {\n\tprivate List<Collection<String>> premises = new LinkedList<Collection<String>>();\n\tprivate List<Collection<String>> conclusions = new LinkedList<Collection<String>>();\n\t\n\tpublic RuleReader(String ruleFile) throws IOException {\n\t\tBufferedReader ruleReader = new BufferedReader(new FileReader(ruleFile));\n\t\tString strLine;\n\t\tint i = 0;\n\t\twhile ((strLine = ruleReader.readLine()) != null) {\n\t\t\tif (strLine.trim().startsWith(\"#\") || strLine.trim().equals(\"\"))\n\t\t\t\tcontinue;\n\t\t\tString[] parts = strLine.split(\"->\");\n\t\t\tif (parts.length < 2) {\n\t\t\t\truleReader.close();\n\t\t\t\tthrow new IOException(\"The rule \" + strLine + \" has not a \\\"->\\\" symbol.\");\n\t\t\t}\n\t\t\tCollection<String> premise = new HashSet<String>();\n\t\t\tCollection<String> conclusion = new HashSet<String>();\n\t\t\tfor (String literalInPremise : parts[0].split(\"&\"))\n\t\t\t\tpremise.add(literalInPremise);\n\t\t\tfor (String literalInConclusion : parts[1].split(\"&\"))\n\t\t\t\tconclusion.add(literalInConclusion);\n\t\t\tpremises.add(i, premise);\n\t\t\tconclusions.add(i, conclusion);\n\t\t\ti++;\n\t\t}\n\t\truleReader.close();\n\t}\n\t\n\tpublic int getRuleCount() { return this.premises.size(); }\n\n\tpublic List<Collection<String>> getPremises() {\n\t\treturn premises;\n\t}\n\n\tpublic List<Collection<String>> getConclusions() {\n\t\treturn conclusions;\n\t}\n}\n" }, { "alpha_fraction": 0.7381974458694458, "alphanum_fraction": 0.7381974458694458, "avg_line_length": 25.41176414489746, "blob_id": "0b7a3932194763d27ccd234c449a94172a6ee87b", "content_id": "c5255d17e8f7b9caa8f300adca2fda7b0121e575", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 466, "license_type": "no_license", "max_line_length": 77, "num_lines": 17, "path": "/softwareconfiguration/hasco/src/hasco/core/HASCOConfig.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package hasco.core;\r\n\r\nimport org.aeonbits.owner.Config.Sources;\r\n\r\nimport jaicore.basic.algorithm.IAlgorithmConfig;\r\n\r\n@Sources({ \"file:conf/hasco.properties\" })\r\npublic interface HASCOConfig extends IAlgorithmConfig {\r\n\tpublic static final String K_VISUALIZE = \"hasco.visualize\";\r\n\t\r\n\t/**\r\n\t * @return Whether or not the search conducted by HASCO should be visualized\r\n\t */\r\n\t@Key(K_VISUALIZE)\r\n\t@DefaultValue(\"false\")\r\n\tpublic boolean visualizationEnabled();\r\n}\r\n" }, { "alpha_fraction": 0.613632321357727, "alphanum_fraction": 0.6147001385688782, "avg_line_length": 21.47599983215332, "blob_id": "7cc6f4e4e6d7938d65aad208e7ad0c3ca12870a6", "content_id": "1735ac44bbf367154bd1445d089935bed4ab0f0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5619, "license_type": "no_license", "max_line_length": 99, "num_lines": 250, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/uncertainty/paretosearch/ParetoSelection.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.uncertainty.paretosearch;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.Queue;\n\nimport jaicore.search.model.travesaltree.Node;\n\n/**\n * Open collection pareto front implementation.\n * @param <T> internal label of node\n * @param <V> external label of node\n */\npublic class ParetoSelection <T, V extends Comparable<V>> implements Queue<Node<T, V>> {\n\n\t/* Contains all open nodes. */\n\tprivate final LinkedList<ParetoNode<T,V>> open;\n\n\t/* Contains all maximal open nodes. */\n\tprivate final Queue<ParetoNode<T,V>> pareto;\n\n\t/* Node counter. */\n\tprivate int n = 0;\n\n\t/**\n\t * Constructor.\n\t * @param pareto Pareto set implementation.\n\t */\n\tpublic ParetoSelection(Queue<ParetoNode<T,V>> pareto) {\n\t\topen = new LinkedList<>();\n\t\tthis.pareto = pareto;\n\t}\n\n\t/**\n\t * FIFO: ParetoSelection<T,V> p = new ParetoSelection(new PriorityQueue<ParetoNode<T,V>();)\n\t */\n\n\t/**\n\t * Tests if p dominates q.\n\t * @param p\n\t * @param q\n\t * @return true if p dominates q. False, otherwise.\n\t */\n\tprivate boolean dominates(Node<T, V> p, Node<T, V> q) {\n\t\t// Get f and u values of nodes\n\t\tV \t\tp_f = (V) p.getAnnotation(\"f\");\n\t\tdouble \tp_u = (double) p.getAnnotation(\"uncertainty\");\n\t\tV \t\tq_f = (V) q.getAnnotation(\"f\");\n\t\tdouble \tq_u = (double) q.getAnnotation(\"uncertainty\");\n\n\t\t// p dominates q <=> (q.f < p.f AND q.u <= p.u) OR (q.f <= p.f AND q.u < p.u)\n\t\tif (((p_f.compareTo(q_f) < 0) && (p_u <= q_u)) || ((p_f.compareTo(q_f) <= 0) && (p_u < q_u))) {\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Tests if p is maximal.\n\t * @param n\n\t * @return\n\t */\n\tprivate boolean isMaximal(ParetoNode n) {\n\t\treturn n.dominatedBy.size() == 0;\n\t}\n\n\t/**\n\t * Adds a node to the open list and, if its not dominated by any other point\n\t * also to the pareto front.\n\t * @param n\n\t * @return\n\t */\n\t@Override\n\tpublic boolean add(Node<T, V> n) {\n\t\tassert n.getInternalLabel() != null : \"Cannot add nodes with value NULL to OPEN!\";\n\t\tParetoNode p = new ParetoNode(n, this.n++);\n\t\tfor (ParetoNode q : this.open) {\n\t\t\t// p dominates q\n\t\t\tif (this.dominates(p.node, q.node)) {\n\t\t\t\tp.dominates.add(q);\n\t\t\t\tq.dominatedBy.add(p);\n\t\t\t\t// Remove q from pareto front if its now dominated i.e. not maximal anymore.\n\t\t\t\tif (!this.isMaximal(q)) {\n\t\t\t\t\tthis.pareto.remove(q);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// p dominated by q\n\t\t\tif (this.dominates(q.node, p.node)) {\n\t\t\t\tp.dominatedBy.add(q);\n\t\t\t\tq.dominates.add(p);\n\t\t\t}\n\t\t}\n\n\t\t// If p is not dominated by any other point, add it to pareto front.\n\t\tif (isMaximal(p)) {\n\t\t\tthis.pareto.add(p);\n\t\t}\n\n\t\treturn open.add(p);\n\t}\n\n\t@Override\n\tpublic boolean addAll(Collection<? extends Node<T, V>> c) {\n\t\tboolean changed = false;\n\t\tfor (Node<T, V> p : c) {\n\t\t\tchanged |= this.add(p);\n\t\t}\n\t\treturn changed;\n\t}\n\n\t@Override\n\tpublic void clear() {\n\t\topen.clear();\n\t}\n\n\t@Override\n\tpublic boolean contains(Object o) {\n\t\treturn open.contains(o);\n\t}\n\n\t@Override\n\tpublic boolean containsAll(Collection<?> c) {\n\t\treturn open.containsAll(c);\n\t}\n\n\t@Override\n\tpublic boolean isEmpty() {\n\t\treturn open.isEmpty();\n\t}\n\n\t@Override\n\tpublic Iterator<Node<T, V>> iterator() {\n\t\t// Convert ParetoNode-iterator from this.pareto to a Node<T,V>-iterator.\n\t\t// TODO: improve\n\t\tArrayList<Node<T,V>> a = new ArrayList<>();\n\t\tfor(ParetoNode<T,V> p : this.pareto)\n\t\t\ta.add(p.node);\n\t\treturn a.iterator();\n\t}\n\n\t@Override\n\tpublic boolean removeAll(Collection<?> c) {\n\t\treturn open.removeAll(c);\n\t}\n\n\t@Override\n\tpublic boolean retainAll(Collection<?> c) {\n\t\treturn open.retainAll(c);\n\t}\n\n\t@Override\n\tpublic int size() {\n\t\treturn open.size();\n\t}\n\n\t@Override\n\tpublic Object[] toArray() {\n\t\treturn open.toArray();\n\t}\n\n\t@Override\n\tpublic <X> X[] toArray(X[] a) {\n\t\treturn open.toArray(a);\n\t}\n\n\t/**\n\t * Return a node from pareto front.\n\t */\n\t@Override\n\tpublic Node<T, V> peek() {\n\t\treturn this.pareto.isEmpty() ? null : this.pareto.peek().node;\n\t}\n\n\t/**\n\t * Removes an Node from\n\t * @param o\n\t * @return\n\t */\n\t@Override\n\tpublic boolean remove(Object o) {\n\t\tif (o instanceof Node) {\n\t\t\t// Find corresponding pareto node p.\n\t\t\tParetoNode<T,V> p = null;\n\t\t\tfor (ParetoNode<T,V> q : this.open) {\n//\t\t\t\tString n_hex = Integer.toHexString(o.hashCode());\n//\t\t\t\tString q_hex = Integer.toHexString(q.node.hashCode());\n//\t\t\t\tSystem.out.println(\"Check. \" + q.node + \" with \" + o + \", \" + n_hex + \" == \" + q_hex);\n\t\t\t\tif (q.node == o)\n//\t\t\t\t\tSystem.out.println(\"Check true. \" + q.node + \" with \" + o + \", \" + n_hex + \" == \" + q_hex);\n\t\t\t\t\tp = q;\n\t\t\t}\n\t\t\tif (p == null) {\n\t\t\t\tthrow new IllegalArgumentException(\"Node to remove is not part of the open list (\" + o + \").\");\n\t\t\t}\n\t\t\t// Remove all associations of p.\n\t\t\tfor (ParetoNode<T,V> q : p.dominates) {\n\t\t\t\tq.dominatedBy.remove(p);\n\t\t\t\t// Add q to pareto if its now no longer dominated by any other point.\n\t\t\t\tif (this.isMaximal(q)) {\n\t\t\t\t\tthis.pareto.add(q);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (ParetoNode q : p.dominatedBy) {\n\t\t\t\tq.dominates.remove(p); // TODO: Is this even necessary?\n\t\t\t}\n\t\t\tthis.pareto.remove(p);\n\t\t\treturn this.open.remove(p);\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic String toString() {\n\t\tString s = \"OPEN LIST: \\n\";\n\t\tfor (ParetoNode p : this.open) {\n\t\t\ts += p.toString() + \"\\n\";\n\t\t}\n\t\ts += \"PARETO = [\";\n\t\tfor (ParetoNode<T,V> p : this.pareto) {\n\t\t\ts += p.node.getPoint() + \", \";\n\t\t}\n\t\ts += \"]\";\n\t\treturn s;\n\t}\n\n\t@Override\n\tpublic Node<T, V> element() {\n\t\treturn peek();\n\t}\n\n\t@Override\n\tpublic boolean offer(Node<T, V> arg0) {\n\t\treturn add(arg0);\n\t}\n\n\t@Override\n\tpublic Node<T, V> poll() {\n\t\tNode<T,V> n = peek();\n\t\tremove(n);\n\t\treturn n;\n\t}\n\n\t@Override\n\tpublic Node<T, V> remove() {\n\t\treturn poll();\n\t}\n}\n" }, { "alpha_fraction": 0.738170325756073, "alphanum_fraction": 0.738170325756073, "avg_line_length": 25.565217971801758, "blob_id": "b2cac2826e3bffd6d74fdbc4b9b05fe26e3f0fd0", "content_id": "bf82ca7944a3a8e84987f13ae456ab8d10d95cc7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 634, "license_type": "no_license", "max_line_length": 80, "num_lines": 23, "path": "/JAICore/jaicore-basic/src/jaicore/basic/algorithm/SolutionCandidateFoundEvent.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.basic.algorithm;\r\n\r\n/**\r\n * This is to notify listeners that an algorithm has found a solution candidate.\r\n * Note that this is generally not the answer returned by the algorithm but only\r\n * one possible candidate.\r\n * \r\n * @author fmohr\r\n *\r\n * @param <O> class from which solution elements stem from\r\n */\r\npublic class SolutionCandidateFoundEvent<O> implements AlgorithmEvent {\r\n\tprivate final O solutionCandidate;\r\n\r\n\tpublic SolutionCandidateFoundEvent(O solutionCandidate) {\r\n\t\tsuper();\r\n\t\tthis.solutionCandidate = solutionCandidate;\r\n\t}\r\n\r\n\tpublic O getSolutionCandidate() {\r\n\t\treturn solutionCandidate;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.8081140518188477, "alphanum_fraction": 0.8081140518188477, "avg_line_length": 25.823530197143555, "blob_id": "b0092bd6c691c0a73db17d2d2e95072c50850c1f", "content_id": "fd55cfe3a88c854780a631714ff7c66cc13894d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 912, "license_type": "no_license", "max_line_length": 126, "num_lines": 34, "path": "/JAICore/jaicore-planning/src/jaicore/planning/graphgenerators/task/rtn/RTNEdge.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.graphgenerators.task.rtn;\n\nimport java.util.Map;\n\nimport jaicore.logic.fol.structure.ConstantParam;\nimport jaicore.planning.model.ceoc.CEOCAction;\nimport jaicore.planning.model.task.stn.MethodInstance;\n\npublic class RTNEdge {\n\n\tprivate final Map<ConstantParam, ConstantParam> contextRecreator;\n\tprivate final MethodInstance methodInstance;\n\tprivate final CEOCAction appliedAction;\n\n\tpublic RTNEdge(Map<ConstantParam, ConstantParam> contextRecreator, MethodInstance methodInstance, CEOCAction appliedAction) {\n\t\tsuper();\n\t\tthis.contextRecreator = contextRecreator;\n\t\tthis.methodInstance = methodInstance;\n\t\tthis.appliedAction = appliedAction;\n\t}\n\n\tpublic Map<ConstantParam, ConstantParam> getContextRecreator() {\n\t\treturn contextRecreator;\n\t}\n\n\tpublic MethodInstance getMethodInstance() {\n\t\treturn methodInstance;\n\t}\n\n\tpublic CEOCAction getAppliedAction() {\n\t\treturn appliedAction;\n\t}\n\n}\n" }, { "alpha_fraction": 0.7900000214576721, "alphanum_fraction": 0.7900000214576721, "avg_line_length": 18, "blob_id": "f676251b3ed1ab3d6939f98e58762814ce8fd182", "content_id": "242372a6fb4fc6430757c663b170fec7eb9f2826", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 100, "license_type": "no_license", "max_line_length": 61, "num_lines": 5, "path": "/JAICore/jaicore-search/src/jaicore/search/util/GraphSeemsSaneResult.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.util;\r\n\r\npublic class GraphSeemsSaneResult extends SanityCheckResult {\r\n\r\n}\r\n" }, { "alpha_fraction": 0.5170603394508362, "alphanum_fraction": 0.5354330539703369, "avg_line_length": 21.8125, "blob_id": "1b899d40295a0bf48fb9dcc7425733f448387c0b", "content_id": "78b36eb8307c85e8a109485871c04bbd161758fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 381, "license_type": "no_license", "max_line_length": 54, "num_lines": 16, "path": "/JAICore/jaicore-basic/src/jaicore/basic/Combinatorics.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.basic;\r\n\r\npublic abstract class Combinatorics {\r\n\r\n\tpublic static boolean[][] getTruthTable(int n) {\r\n\t\tint rowCount = (int) Math.pow(2, n);\r\n\t\tboolean[][] table = new boolean[rowCount][n];\r\n\t\t\r\n\t\tfor (int i = 0; i < rowCount; i++) {\r\n\t\t\tfor (int j = n - 1; j >= 0; j--) {\r\n\t\t\t\ttable[i][j] = (i / (int) Math.pow(2, j)) % 2 == 1;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn table;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.5398010015487671, "alphanum_fraction": 0.5547263622283936, "avg_line_length": 20.33333396911621, "blob_id": "4fb99da2c5e2b35045428d40e241139f75f9d593", "content_id": "e8271d0ed89baf93d000196d3a8ae5453950c37a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Gradle", "length_bytes": 402, "license_type": "no_license", "max_line_length": 75, "num_lines": 18, "path": "/JAICore/jaicore-processes/build.gradle", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "sourceSets {\r\n main {\r\n java {\r\n srcDir 'src'\r\n }\r\n }\r\n test {\r\n \tjava {\r\n \t\tsrcDir 'test'\r\n \t}\r\n }\r\n}\r\ndependencies{\r\n\tcompile project(\":JAICore:jaicore-basic\")\r\n\tcompile project(\":JAICore:jaicore-concurrent\")\r\n\tcompile group: 'net.java.dev.jna', name: 'jna', version: '4.5.2'\r\n\tcompile group: 'org.apache.commons', name: 'commons-lang3', version: '3.8'\r\n}\r\n" }, { "alpha_fraction": 0.7356350421905518, "alphanum_fraction": 0.7377597093582153, "avg_line_length": 48.16282653808594, "blob_id": "79cc57ed852a09797bd261df5a852f31181a9afa", "content_id": "bd868ea2c292ed6d2b3411274b8bc8e18ac57142", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 32005, "license_type": "no_license", "max_line_length": 194, "num_lines": 651, "path": "/softwareconfiguration/hasco/src/hasco/core/Util.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package hasco.core;\n\nimport java.util.ArrayDeque;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Deque;\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.Stack;\nimport java.util.stream.Collectors;\n\nimport org.apache.commons.math3.geometry.euclidean.oned.Interval;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport hasco.model.CategoricalParameterDomain;\nimport hasco.model.Component;\nimport hasco.model.ComponentInstance;\nimport hasco.model.Dependency;\nimport hasco.model.NumericParameterDomain;\nimport hasco.model.Parameter;\nimport hasco.model.ParameterDomain;\nimport hasco.model.ParameterRefinementConfiguration;\nimport jaicore.basic.sets.SetUtil;\nimport jaicore.basic.sets.SetUtil.Pair;\nimport jaicore.logic.fol.structure.Literal;\nimport jaicore.logic.fol.structure.Monom;\nimport jaicore.planning.graphgenerators.IPlanningGraphGeneratorDeriver;\nimport jaicore.planning.model.core.Action;\nimport jaicore.planning.model.core.Plan;\nimport jaicore.planning.model.core.PlannerUtil;\nimport jaicore.search.model.travesaltree.Node;\n\npublic class Util {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(Util.class);\n\n\tstatic Map<String, String> getParameterContainerMap(final Monom state, final String objectName) {\n\t\tMap<String, String> parameterContainerMap = new HashMap<>();\n\t\tList<Literal> containerLiterals = state.stream().filter(l -> l.getPropertyName().equals(\"parameterContainer\") && l.getParameters().get(2).getName().equals(objectName))\n\t\t\t\t.collect(Collectors.toList());\n\t\tcontainerLiterals.forEach(l -> parameterContainerMap.put(l.getParameters().get(1).getName(), l.getParameters().get(3).getName()));\n\t\treturn parameterContainerMap;\n\t}\n\n\tpublic static Map<ComponentInstance, Map<Parameter, String>> getParametrizations(final Monom state, final Collection<Component> components, final boolean resolveIntervals) {\n\t\tMap<String, ComponentInstance> objectMap = new HashMap<>();\n\t\tMap<String, Map<String, String>> parameterContainerMap = new HashMap<>(); // stores for each object the name of the container of each parameter\n\t\tMap<String, String> parameterValues = new HashMap<>();\n\n\t\tMap<ComponentInstance, Map<Parameter, String>> parameterValuesPerComponentInstance = new HashMap<>();\n\n\t\tCollection<String> overwrittenDataContainers = getOverwrittenDatacontainersInState(state);\n\n\t\t/*\n\t\t * create (empty) component instances, detect containers for parameter values, and register the\n\t\t * values of the data containers\n\t\t */\n\t\tfor (Literal l : state) {\n\t\t\tString[] params = l.getParameters().stream().map(p -> p.getName()).collect(Collectors.toList()).toArray(new String[] {});\n\t\t\tswitch (l.getPropertyName()) {\n\t\t\tcase \"resolves\":\n\t\t\t\t// String parentObjectName = params[0];\n\t\t\t\t// String interfaceName = params[1];\n\t\t\t\tString componentName = params[2];\n\t\t\t\tString objectName = params[3];\n\t\t\t\tComponent component = components.stream().filter(c -> c.getName().equals(componentName)).findAny().get();\n\t\t\t\tComponentInstance object = new ComponentInstance(component, new HashMap<>(), new HashMap<>());\n\t\t\t\tobjectMap.put(objectName, object);\n\t\t\t\tbreak;\n\t\t\tcase \"parameterContainer\":\n\t\t\t\tif (!parameterContainerMap.containsKey(params[2])) {\n\t\t\t\t\tparameterContainerMap.put(params[2], new HashMap<>());\n\t\t\t\t}\n\t\t\t\tparameterContainerMap.get(params[2]).put(params[1], params[3]);\n\t\t\t\tbreak;\n\t\t\tcase \"val\":\n\t\t\t\tif (overwrittenDataContainers.contains(params[0])) {\n\t\t\t\t\tparameterValues.put(params[0], params[1]);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t/* update the configurations of the objects */\n\t\tfor (String objectName : objectMap.keySet()) {\n\t\t\tMap<Parameter, String> paramValuesForThisComponent = new HashMap<>();\n\t\t\tComponentInstance object = objectMap.get(objectName);\n\t\t\tparameterValuesPerComponentInstance.put(object, paramValuesForThisComponent);\n\t\t\tfor (Parameter p : object.getComponent().getParameters()) {\n\n\t\t\t\tassert parameterContainerMap.containsKey(objectName) : \"No parameter container map has been defined for object \" + objectName + \" of component \" + object.getComponent().getName()\n\t\t\t\t\t\t+ \"!\";\n\t\t\t\tassert parameterContainerMap.get(objectName).containsKey(p.getName()) : \"The data container for parameter \" + p.getName() + \" of \" + object.getComponent().getName()\n\t\t\t\t\t\t+ \" is not defined!\";\n\n\t\t\t\tString assignedValue = parameterValues.get(parameterContainerMap.get(objectName).get(p.getName()));\n\t\t\t\tString interpretedValue = \"\";\n\t\t\t\tif (assignedValue != null) {\n\t\t\t\t\tif (p.getDefaultDomain() instanceof NumericParameterDomain) {\n\t\t\t\t\t\tif (resolveIntervals) {\n\t\t\t\t\t\t\tNumericParameterDomain np = (NumericParameterDomain) p.getDefaultDomain();\n\t\t\t\t\t\t\tList<String> vals = SetUtil.unserializeList(assignedValue);\n\t\t\t\t\t\t\tInterval interval = new Interval(Double.valueOf(vals.get(0)), Double.valueOf(vals.get(1)));\n\t\t\t\t\t\t\tif (np.isInteger()) {\n\t\t\t\t\t\t\t\tinterpretedValue = String.valueOf((int) Math.round(interval.getBarycenter()));\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tinterpretedValue = String.valueOf(interval.getBarycenter());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tinterpretedValue = assignedValue;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (p.getDefaultDomain() instanceof CategoricalParameterDomain) {\n\t\t\t\t\t\tinterpretedValue = assignedValue;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthrow new UnsupportedOperationException(\"No support for parameters of type \" + p.getClass().getName());\n\t\t\t\t\t}\n\t\t\t\t\tparamValuesForThisComponent.put(p, interpretedValue);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn parameterValuesPerComponentInstance;\n\t}\n\n\tpublic static Collection<String> getOverwrittenDatacontainersInState(final Monom state) {\n\t\treturn state.stream().filter(l -> l.getPropertyName().equals(\"overwritten\")).map(l -> l.getParameters().get(0).getName()).collect(Collectors.toSet());\n\t}\n\n\tpublic static Collection<String> getClosedDatacontainersInState(final Monom state) {\n\t\treturn state.stream().filter(l -> l.getPropertyName().equals(\"closed\")).map(l -> l.getParameters().get(0).getName()).collect(Collectors.toSet());\n\t}\n\n\tstatic Map<String, ComponentInstance> getGroundComponentsFromState(final Monom state, final Collection<Component> components, final boolean resolveIntervals) {\n\t\tMap<String, ComponentInstance> objectMap = new HashMap<>();\n\t\tMap<String, Map<String, String>> parameterContainerMap = new HashMap<>(); // stores for each object the name of the container of each parameter\n\t\tMap<String, String> parameterValues = new HashMap<>();\n\t\tMap<String, String> interfaceContainerMap = new HashMap<>();\n\t\tCollection<String> overwrittenDatacontainers = getOverwrittenDatacontainersInState(state);\n\n\t\t/* create (empty) component instances, detect containers for parameter values, and register the values of the data containers */\n\t\tfor (Literal l : state) {\n\t\t\tString[] params = l.getParameters().stream().map(p -> p.getName()).collect(Collectors.toList()).toArray(new String[] {});\n\t\t\tswitch (l.getPropertyName()) {\n\t\t\tcase \"resolves\":\n\t\t\t\t// String parentObjectName = params[0];\n\t\t\t\t// String interfaceName = params[1];\n\t\t\t\tString componentName = params[2];\n\t\t\t\tString objectName = params[3];\n\n\t\t\t\tComponent component = components.stream().filter(c -> c.getName().equals(componentName)).findAny().get();\n\t\t\t\tComponentInstance object = new ComponentInstance(component, new HashMap<>(), new HashMap<>());\n\t\t\t\tobjectMap.put(objectName, object);\n\t\t\t\tbreak;\n\t\t\tcase \"parameterContainer\":\n\t\t\t\tif (!parameterContainerMap.containsKey(params[2])) {\n\t\t\t\t\tparameterContainerMap.put(params[2], new HashMap<>());\n\t\t\t\t}\n\t\t\t\tparameterContainerMap.get(params[2]).put(params[1], params[3]);\n\t\t\t\tbreak;\n\t\t\tcase \"val\":\n\t\t\t\tparameterValues.put(params[0], params[1]);\n\t\t\t\tbreak;\n\t\t\tcase \"interfaceIdentifier\":\n\t\t\t\tinterfaceContainerMap.put(params[3], params[1]);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t/* now establish the binding of the required interfaces of the component instances */\n\t\tstate.stream().filter(l -> l.getPropertyName().equals(\"resolves\")).forEach(l -> {\n\t\t\tString[] params = l.getParameters().stream().map(p -> p.getName()).collect(Collectors.toList()).toArray(new String[] {});\n\t\t\tString parentObjectName = params[0];\n\t\t\t// String interfaceName = params[1];\n\t\t\tString objectName = params[3];\n\n\t\t\tComponentInstance object = objectMap.get(objectName);\n\t\t\tif (!parentObjectName.equals(\"request\")) {\n\t\t\t\tassert interfaceContainerMap.containsKey(objectName) : \"Object name \" + objectName + \" for requried interface must have a defined identifier \";\n\t\t\t\tobjectMap.get(parentObjectName).getSatisfactionOfRequiredInterfaces().put(interfaceContainerMap.get(objectName), object);\n\t\t\t}\n\t\t});\n\n\t\t/* set the explicitly defined parameters (e.g. overwritten containers) in the component instances */\n\t\tfor (String objectName : objectMap.keySet()) {\n\t\t\tComponentInstance object = objectMap.get(objectName);\n\t\t\tfor (Parameter p : object.getComponent().getParameters()) {\n\n\t\t\t\tassert parameterContainerMap.containsKey(objectName) : \"No parameter container map has been defined for object \" + objectName + \" of component \" + object.getComponent().getName()\n\t\t\t\t\t\t+ \"!\";\n\t\t\t\tassert parameterContainerMap.get(objectName).containsKey(p.getName()) : \"The data container for parameter \" + p.getName() + \" of \" + object.getComponent().getName()\n\t\t\t\t\t\t+ \" is not defined!\";\n\t\t\t\tString paramContainerName = parameterContainerMap.get(objectName).get(p.getName());\n\t\t\t\tif (overwrittenDatacontainers.contains(paramContainerName)) {\n\t\t\t\t\tString assignedValue = parameterValues.get(paramContainerName);\n\t\t\t\t\tassert assignedValue != null : \"parameter containers must always have a value!\";\n\t\t\t\t\tobject.getParameterValues().put(p.getName(), getParamValue(p, assignedValue, resolveIntervals));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn objectMap;\n\t}\n\n\tpublic static <N, A, V extends Comparable<V>> ComponentInstance getSolutionCompositionForNode(final IPlanningGraphGeneratorDeriver<?, ?, ?, ?, N, A> planningGraphDeriver,\n\t\t\tfinal Collection<Component> components, final Monom initState, final Node<N, ?> path, final boolean resolveIntervals) {\n\t\treturn getSolutionCompositionForPlan(components, initState, planningGraphDeriver.getPlan(path.externalPath()), resolveIntervals);\n\t}\n\n\tpublic static <N, A, V extends Comparable<V>> ComponentInstance getComponentInstanceForNode(final IPlanningGraphGeneratorDeriver<?, ?, ?, ?, N, A> planningGraphDeriver,\n\t\t\tfinal Collection<Component> components, final Monom initState, final Node<N, ?> path, String name, final boolean resolveIntervals) {\n\t\treturn getComponentInstanceForPlan(components, initState, planningGraphDeriver.getPlan(path.externalPath()), name, resolveIntervals);\n\t}\n\n\tpublic static Monom getFinalStateOfPlan(final Monom initState, final Plan<? extends Action> plan) {\n\t\tMonom state = new Monom(initState);\n\t\tfor (Action a : plan.getActions()) {\n\t\t\tPlannerUtil.updateState(state, a);\n\t\t}\n\t\treturn state;\n\t}\n\n\tpublic static ComponentInstance getSolutionCompositionForPlan(final Collection<Component> components, final Monom initState, final Plan<? extends Action> plan, final boolean resolveIntervals) {\n\t\treturn getSolutionCompositionFromState(components, getFinalStateOfPlan(initState, plan), resolveIntervals);\n\t}\n\n\tpublic static ComponentInstance getComponentInstanceForPlan(final Collection<Component> components, final Monom initState, final Plan<? extends Action> plan, String name,\n\t\t\tfinal boolean resolveIntervals) {\n\t\treturn getComponentInstanceFromState(components, getFinalStateOfPlan(initState, plan), name, resolveIntervals);\n\t}\n\n\tpublic static ComponentInstance getSolutionCompositionFromState(final Collection<Component> components, final Monom state, final boolean resolveIntervals) {\n\t\treturn getComponentInstanceFromState(components, state, \"solution\", resolveIntervals);\n\t}\n\n\tpublic static ComponentInstance getComponentInstanceFromState(final Collection<Component> components, final Monom state, String name, final boolean resolveIntervals) {\n\t\treturn Util.getGroundComponentsFromState(state, components, resolveIntervals).get(name);\n\t}\n\n\t/**\n\t * Computes a String of component names that appear in the composition which can be used as an identifier for the composition\n\t * \n\t * @param composition\n\t * @return String of all component names in right to left depth-first order\n\t */\n\tpublic static String getComponentNamesOfComposition(ComponentInstance composition) {\n\t\tStringBuilder builder = new StringBuilder();\n\t\tDeque<ComponentInstance> componentInstances = new ArrayDeque<ComponentInstance>();\n\t\tcomponentInstances.push(composition);\n\t\tComponentInstance curInstance;\n\t\twhile (!componentInstances.isEmpty()) {\n\t\t\tcurInstance = componentInstances.pop();\n\t\t\tbuilder.append(curInstance.getComponent().getName());\n\t\t\tLinkedHashMap<String, String> requiredInterfaces = curInstance.getComponent().getRequiredInterfaces();\n\t\t\t// This set should be ordered\n\t\t\tSet<String> requiredInterfaceNames = requiredInterfaces.keySet();\n\t\t\tfor (String requiredInterfaceName : requiredInterfaceNames) {\n\t\t\t\tComponentInstance instance = curInstance.getSatisfactionOfRequiredInterfaces().get(requiredInterfaceName);\n\t\t\t\tcomponentInstances.push(instance);\n\t\t\t}\n\t\t}\n\t\treturn builder.toString();\n\t}\n\n\t/**\n\t * Computes a list of all components of the given composition.\n\t * \n\t * @param composition\n\t * @return List of components in right to left depth-first order\n\t */\n\tpublic static List<Component> getComponentsOfComposition(ComponentInstance composition) {\n\t\tList<Component> components = new LinkedList<Component>();\n\t\tDeque<ComponentInstance> componentInstances = new ArrayDeque<ComponentInstance>();\n\t\tcomponentInstances.push(composition);\n\t\tComponentInstance curInstance;\n\t\twhile (!componentInstances.isEmpty()) {\n\t\t\tcurInstance = componentInstances.pop();\n\t\t\tcomponents.add(curInstance.getComponent());\n\t\t\tLinkedHashMap<String, String> requiredInterfaces = curInstance.getComponent().getRequiredInterfaces();\n\t\t\t// This set should be ordered\n\t\t\tSet<String> requiredInterfaceNames = requiredInterfaces.keySet();\n\t\t\tfor (String requiredInterfaceName : requiredInterfaceNames) {\n\t\t\t\tComponentInstance instance = curInstance.getSatisfactionOfRequiredInterfaces().get(requiredInterfaceName);\n\t\t\t\tcomponentInstances.push(instance);\n\t\t\t}\n\t\t}\n\t\treturn components;\n\t}\n\n\tpublic static Map<Parameter, ParameterDomain> getUpdatedDomainsOfComponentParameters(final Monom state, final Component component, final String objectIdentifierInState) {\n\t\tMap<String, String> parameterContainerMap = new HashMap<>();\n\t\tMap<String, String> parameterContainerMapInv = new HashMap<>();\n\t\tMap<String, String> parameterValues = new HashMap<>();\n\n\t\t/* detect containers for parameter values, and register the values of the data containers */\n\t\tfor (Literal l : state) {\n\t\t\tString[] params = l.getParameters().stream().map(p -> p.getName()).collect(Collectors.toList()).toArray(new String[] {});\n\t\t\tswitch (l.getPropertyName()) {\n\t\t\tcase \"parameterContainer\":\n\t\t\t\tif (!params[2].equals(objectIdentifierInState)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tparameterContainerMap.put(params[1], params[3]);\n\t\t\t\tparameterContainerMapInv.put(params[3], params[1]);\n\t\t\t\tbreak;\n\t\t\tcase \"val\":\n\t\t\t\tparameterValues.put(params[0], params[1]);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t/* determine current values of the parameters of this component instance */\n\t\tMap<Parameter, String> paramValuesForThisComponentInstance = new HashMap<>();\n\t\tfor (Parameter p : component.getParameters()) {\n\t\t\tassert parameterContainerMap.containsKey(p.getName()) : \"The data container for parameter \" + p.getName() + \" of \" + objectIdentifierInState + \" is not defined!\";\n\t\t\tString assignedValue = parameterValues.get(parameterContainerMap.get(p.getName()));\n\t\t\tassert assignedValue != null : \"No value has been assigned to parameter \" + p.getName() + \" stored in container \" + parameterContainerMap.get(p.getName()) + \" in state \" + state;\n\t\t\tString value = getParamValue(p, assignedValue, false);\n\t\t\tassert value != null : \"Determined value NULL for parameter \" + p.getName() + \", which is not plausible.\";\n\t\t\tparamValuesForThisComponentInstance.put(p, value);\n\t\t}\n\n\t\t/* extract instance */\n\t\tCollection<Component> components = new ArrayList<>();\n\t\tcomponents.add(component);\n\t\tComponentInstance instance = getComponentInstanceFromState(components, state, objectIdentifierInState, false);\n\n\t\t/* now compute the new domains based on the current values */\n\t\tCollection<Parameter> overwrittenParams = getOverwrittenDatacontainersInState(state).stream().filter(containerName -> parameterContainerMap.containsValue(containerName))\n\t\t\t\t.map(containerName -> component.getParameterWithName(parameterContainerMapInv.get(containerName))).collect(Collectors.toList());\n\t\treturn getUpdatedDomainsOfComponentParameters(instance);\n\t\t// return null;\n\t}\n\n\t// public static Map<Parameter, ParameterDomain> getUpdatedDomainsOfComponentParameters(final ComponentInstance instance) {\n\t//\n\t// /* detect containers for parameter values, and register the values of the data containers */\n\t// Component component = instance.getComponent();\n\t//\n\t// /* determine current values of the parameters of this component instance */\n\t// Map<Parameter, String> paramValuesForThisComponentInstance = new HashMap<>();\n\t// for (Parameter p : component.getParameters()) {\n\t// String assignedValue = instance.getParameterValues().get(p.getName());\n\t// String value = getParamValue(p, assignedValue, false);\n\t// paramValuesForThisComponentInstance.put(p, value);\n\t// }\n\t//\n\t// /* now compute the new domains based on the current values */\n\t//// Collection<Parameter> overwrittenParams = getOverwrittenDatacontainersInState(state).stream().filter(containerName -> parameterContainerMap.containsValue(containerName))\n\t// // .map(containerName -> component.getParameter(parameterContainerMapInv.get(containerName))).collect(Collectors.toList());\n\t// return getUpdatedDomainsOfComponentParameters(component, paramValuesForThisComponentInstance, new ArrayList<>());\n\t// }\n\n\tprivate static String getParamValue(final Parameter p, final String assignedValue, final boolean resolveIntervals) {\n\t\tString interpretedValue = \"\";\n\t\tif (assignedValue == null) {\n\t\t\tthrow new IllegalArgumentException(\"Cannot determine true value for assigned param value \" + assignedValue + \" for parameter \" + p.getName());\n\t\t}\n\t\tif (p.isNumeric()) {\n\t\t\tif (resolveIntervals) {\n\t\t\t\tNumericParameterDomain np = (NumericParameterDomain) p.getDefaultDomain();\n\t\t\t\tList<String> vals = SetUtil.unserializeList(assignedValue);\n\t\t\t\tInterval interval = new Interval(Double.valueOf(vals.get(0)), Double.valueOf(vals.get(1)));\n\t\t\t\tif (np.isInteger()) {\n\t\t\t\t\tinterpretedValue = String.valueOf((int) Math.round(interval.getBarycenter()));\n\t\t\t\t} else {\n\t\t\t\t\tinterpretedValue = String.valueOf(interval.getBarycenter());\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tinterpretedValue = assignedValue;\n\t\t\t}\n\t\t} else if (p.getDefaultDomain() instanceof CategoricalParameterDomain) {\n\t\t\tinterpretedValue = assignedValue;\n\t\t} else {\n\t\t\tthrow new UnsupportedOperationException(\"No support for parameters of type \" + p.getClass().getName());\n\t\t}\n\t\treturn interpretedValue;\n\t}\n\n\tpublic static Map<Parameter, ParameterDomain> getUpdatedDomainsOfComponentParameters(final ComponentInstance componentInstance) {\n\t\tComponent component = componentInstance.getComponent();\n\n\t\t/* initialize all params for which a decision has been made already with their respective value */\n\t\tMap<Parameter, ParameterDomain> domains = new HashMap<>();\n\t\tfor (Parameter p : componentInstance.getParametersThatHaveBeenSetExplicitly()) {\n\t\t\tif (p.isNumeric()) {\n\t\t\t\tNumericParameterDomain defaultDomain = (NumericParameterDomain) p.getDefaultDomain();\n\t\t\t\tInterval interval = SetUtil.unserializeInterval(componentInstance.getParameterValue(p));\n\t\t\t\tdomains.put(p, new NumericParameterDomain(defaultDomain.isInteger(), interval.getInf(), interval.getSup()));\n\t\t\t} else if (p.isCategorical()) {\n\t\t\t\tdomains.put(p, new CategoricalParameterDomain(new String[] { componentInstance.getParameterValue(p) }));\n\t\t\t}\n\t\t}\n\n\t\t/* initialize all others with the default domain */\n\t\tfor (Parameter p : componentInstance.getParametersThatHaveNotBeenSetExplicitly()) {\n\t\t\tdomains.put(p, p.getDefaultDomain());\n\t\t}\n\t\tassert (domains.keySet().equals(component.getParameters())) : \"There are parameters for which no current domain was derived.\";\n\n\t\t/* update domains based on the dependencies defined for this component */\n\t\tfor (Dependency dependency : component.getDependencies()) {\n\t\t\tif (isDependencyPremiseSatisfied(dependency, domains)) {\n\t\t\t\tlogger.info(\"Premise of dependency {} is satisfied, applying its conclusions ...\", dependency);\n\t\t\t\tfor (Pair<Parameter, ParameterDomain> newDomain : dependency.getConclusion()) {\n\t\t\t\t\t/*\n\t\t\t\t\t * directly use the concluded domain if the current value is NOT subsumed by it. Otherwise, just\n\t\t\t\t\t * stick to the current domain\n\t\t\t\t\t */\n\t\t\t\t\tParameter param = newDomain.getX();\n\t\t\t\t\tParameterDomain concludedDomain = newDomain.getY();\n\t\t\t\t\tif (!componentInstance.getParametersThatHaveBeenSetExplicitly().contains(param)) {\n\t\t\t\t\t\tdomains.put(param, concludedDomain);\n\t\t\t\t\t\tlogger.debug(\"Changing domain of {} from {} to {}\", param, domains.get(param), concludedDomain);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlogger.debug(\"Not changing domain of {} since it has already been set explicitly in the past.\", param);\n\t\t\t\t\t}\n\t\t\t\t\t// }\n\t\t\t\t\t// else\n\t\t\t\t\t// logger.debug(\"Not changing domain of {} from {} to {}, because the current domain is already narrower.\", newDomain.getX(), domains.get(newDomain.getX()), newDomain.getY());\n\n\t\t\t\t\t// ParameterDomain intersection = null;\n\t\t\t\t\t// if (param.isNumeric()) {\n\t\t\t\t\t// NumericParameterDomain cConcludedDomain = (NumericParameterDomain)concludedDomain;\n\t\t\t\t\t// NumericParameterDomain currentDomain = (NumericParameterDomain)domains.get(newDomain.getX());\n\t\t\t\t\t// intersection = new NumericParameterDomain(cConcludedDomain.isInteger(),\n\t\t\t\t\t// Math.max(cConcludedDomain.getMin(), currentDomain.getMin()), Math.min(cConcludedDomain.getMax(),\n\t\t\t\t\t// currentDomain.getMax()));\n\t\t\t\t\t// }\n\t\t\t\t\t// else if (param.isCategorical()) {\n\t\t\t\t\t// CategoricalParameterDomain cConcludedDomain = (CategoricalParameterDomain)concludedDomain;\n\t\t\t\t\t// CategoricalParameterDomain currentDomain =\n\t\t\t\t\t// (CategoricalParameterDomain)domains.get(newDomain.getX());\n\t\t\t\t\t// intersection = new\n\t\t\t\t\t// CategoricalParameterDomain(SetUtil.intersection(Arrays.asList(cConcludedDomain.getValues()),\n\t\t\t\t\t// Arrays.asList(currentDomain.getValues())));\n\t\t\t\t\t// }\n\t\t\t\t\t// else\n\t\t\t\t\t// throw new UnsupportedOperationException(\"Cannot currently handle parameters that are not numeric\n\t\t\t\t\t// and not categorical.\");\n\t\t\t\t\t// assert intersection != null : \"The intersection of the current domain and the domain dictated by\n\t\t\t\t\t// a rule has failed\";\n\t\t\t\t\t// domains.put(param, intersection);\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\tlogger.debug(\"Ignoring unsatisfied dependency {}.\", dependency);\n\t\t}\n\t\treturn domains;\n\t}\n\n\tpublic static boolean isDependencyPremiseSatisfied(final Dependency dependency, final Map<Parameter, ParameterDomain> values) {\n\t\tlogger.debug(\"Checking satisfcation of dependency {} with values {}\", dependency, values);\n\t\tfor (Collection<Pair<Parameter, ParameterDomain>> condition : dependency.getPremise()) {\n\t\t\tboolean check = isDependencyConditionSatisfied(condition, values);\n\t\t\tlogger.trace(\"Result of check for condition {}: {}\", condition, check);\n\t\t\tif (!check)\n\t\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tpublic static boolean isDependencyConditionSatisfied(final Collection<Pair<Parameter, ParameterDomain>> condition, final Map<Parameter, ParameterDomain> values) {\n\t\tfor (Pair<Parameter, ParameterDomain> conditionItem : condition) {\n\t\t\tParameterDomain requiredDomain = conditionItem.getY();\n\t\t\tParameter param = conditionItem.getX();\n\t\t\tParameterDomain actualDomain = values.get(param);\n\t\t\tassert values.containsKey(param) : \"Cannot check condition \" + condition + \" as the value for parameter \" + param.getName() + \" is not defined in \" + values;\n\t\t\tassert values.get(param) != null : \"Cannot check condition \" + condition + \" as the value for parameter \" + param.getName() + \" is NULL in \" + values;\n\t\t\tif (!requiredDomain.subsumes(actualDomain))\n\t\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tpublic static List<Interval> getNumericParameterRefinement(final Interval interval, double focus, boolean integer, final ParameterRefinementConfiguration refinementConfig) {\n\n\t\tdouble inf = interval.getInf();\n\t\tdouble sup = interval.getSup();\n\n\t\t/* if there is nothing to refine anymore */\n\t\tif (inf == sup) {\n\t\t\treturn new ArrayList<>();\n\t\t}\n\n\t\t/*\n\t\t * if this is an integer and the number of comprised integers are at most as\n\t\t * many as the branching factor, enumerate them\n\t\t */\n\t\tif (integer && (Math.floor(sup) - Math.ceil(inf) + 1 <= refinementConfig.getRefinementsPerStep())) {\n\t\t\tList<Interval> proposedRefinements = new ArrayList<>();\n\t\t\tfor (int i = (int) Math.ceil(inf); i <= (int) Math.floor(sup); i++) {\n\t\t\t\tproposedRefinements.add(new Interval(i, i));\n\t\t\t}\n\t\t\treturn proposedRefinements;\n\t\t}\n\n\t\t/*\n\t\t * if the interval is already below the threshold for this parameter, no more\n\t\t * refinements will be allowed\n\t\t */\n\t\tif (sup - inf < refinementConfig.getIntervalLength()) {\n\t\t\treturn new ArrayList<>();\n\t\t}\n\n\t\tif (!refinementConfig.isInitRefinementOnLogScale()) {\n\t\t\tList<Interval> proposedRefinements = refineOnLinearScale(interval, refinementConfig.getRefinementsPerStep(), refinementConfig.getIntervalLength());\n\t\t\tfor (Interval proposedRefinement : proposedRefinements) {\n\t\t\t\tassert proposedRefinement.getInf() >= inf && proposedRefinement.getSup() <= sup : \"The proposed refinement [\" + proposedRefinement.getInf() + \", \" + proposedRefinement.getSup()\n\t\t\t\t\t\t+ \"] is not a sub-interval of [\" + inf + \", \" + sup + \"].\";\n\t\t\t\tassert !proposedRefinement.equals(interval) : \"No real refinement! Intervals are identical.\";\n\t\t\t}\n\t\t\treturn proposedRefinements;\n\t\t}\n\n\t\tList<Interval> proposedRefinements = refineOnLogScale(interval, refinementConfig.getRefinementsPerStep(), 2, focus);\n\t\tfor (Interval proposedRefinement : proposedRefinements) {\n\t\t\tdouble epsilon = 1E-7;\n\t\t\tassert proposedRefinement.getInf() + epsilon >= inf && proposedRefinement.getSup() <= sup + epsilon : \"The proposed refinement [\" + proposedRefinement.getInf() + \", \"\n\t\t\t\t\t+ proposedRefinement.getSup() + \"] is not a sub-interval of [\" + inf + \", \" + sup + \"].\";\n\t\t\tassert !proposedRefinement.equals(interval) : \"No real refinement! Intervals are identical.\";\n\t\t}\n\t\treturn proposedRefinements;\n\t}\n\n\tpublic static List<Interval> refineOnLinearScale(final Interval interval, final int maxNumberOfSubIntervals, final double minimumLengthOfIntervals) {\n\t\tdouble min = interval.getInf();\n\t\tdouble max = interval.getSup();\n\t\tdouble length = max - min;\n\t\tList<Interval> intervals = new ArrayList<>();\n\n\t\t/* if no refinement is possible, return just the interval itself */\n\t\tif (length <= minimumLengthOfIntervals) {\n\t\t\tintervals.add(interval);\n\t\t\treturn intervals;\n\t\t}\n\n\t\t/* otherwise compute the sub-intervals */\n\t\tint numberOfIntervals = Math.min((int) Math.ceil(length / minimumLengthOfIntervals), maxNumberOfSubIntervals);\n\t\tdouble stepSize = length / numberOfIntervals;\n\t\tfor (int i = 0; i < numberOfIntervals; i++) {\n\t\t\tintervals.add(new Interval(min + i * stepSize, min + ((i + 1) * stepSize)));\n\t\t}\n\t\treturn intervals;\n\t}\n\n\tpublic static List<Interval> refineOnLogScale(final Interval interval, final int n, final double basis, final double pointOfConcentration) {\n\t\tList<Interval> list = new ArrayList<>();\n\t\tdouble min = interval.getInf();\n\t\tdouble max = interval.getSup();\n\t\tdouble length = max - min;\n\n\t\t/*\n\t\t * if the point of concentration is exactly on the left or the right of the\n\t\t * interval, conduct the standard technique\n\t\t */\n\t\tif (pointOfConcentration <= min || pointOfConcentration >= max) {\n\t\t\tdouble lengthOfShortestInterval = length * (1 - basis) / (1 - Math.pow(basis, n));\n\t\t\tif (pointOfConcentration <= min) {\n\t\t\t\tdouble endOfLast = min;\n\t\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\t\tdouble start = endOfLast;\n\t\t\t\t\tendOfLast = start + Math.pow(basis, i) * lengthOfShortestInterval;\n\t\t\t\t\tlist.add(new Interval(start, endOfLast));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdouble endOfLast = max;\n\t\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\t\tdouble start = endOfLast;\n\t\t\t\t\tendOfLast = start - Math.pow(basis, i) * lengthOfShortestInterval;\n\t\t\t\t\tlist.add(new Interval(endOfLast, start));\n\t\t\t\t}\n\t\t\t\tCollections.reverse(list);\n\t\t\t}\n\t\t\treturn list;\n\t\t}\n\n\t\t/*\n\t\t * if the point of concentration is in the inner of the interval, split the\n\t\t * interval correspondingly and recursively solve the problem\n\t\t */\n\t\tdouble distanceFromMinToFocus = Math.abs(interval.getInf() - pointOfConcentration);\n\t\tint segmentsForLeft = (int) Math.max(1, Math.floor(n * distanceFromMinToFocus / length));\n\t\tint segmentsForRight = n - segmentsForLeft;\n\t\tlist.addAll(refineOnLogScale(new Interval(min, pointOfConcentration), segmentsForLeft, basis, pointOfConcentration));\n\t\tlist.addAll(refineOnLogScale(new Interval(pointOfConcentration, max), segmentsForRight, basis, pointOfConcentration));\n\t\treturn list;\n\t}\n\n\tpublic static void refineRecursively(final Interval interval, final int maxNumberOfSubIntervalsPerRefinement, final double basis, final double pointOfConcentration,\n\t\t\tfinal double factorForMaximumLengthOfFinestIntervals) {\n\n\t\t/* first, do a logarithmic refinement */\n\t\tList<Interval> initRefinement = refineOnLogScale(interval, maxNumberOfSubIntervalsPerRefinement, basis, pointOfConcentration);\n\t\tCollections.reverse(initRefinement);\n\n\t\tStack<Interval> openRefinements = new Stack<>();\n\t\topenRefinements.addAll(initRefinement);\n\t\tint depth = 0;\n\t\tdo {\n\t\t\tInterval intervalToRefine = openRefinements.pop();\n\t\t\tfor (int i = 0; i < depth; i++) {\n\t\t\t\tSystem.out.print(\"\\t\");\n\t\t\t}\n\t\t\tSystem.out.println(\"[\" + intervalToRefine.getInf() + \", \" + intervalToRefine.getSup() + \"]\");\n\n\t\t\t/* compute desired granularity for this specific interval */\n\t\t\tdouble distanceToPointOfContentration = Math.min(Math.abs(intervalToRefine.getInf() - pointOfConcentration), Math.abs(intervalToRefine.getSup() - pointOfConcentration));\n\t\t\tdouble maximumLengthOfFinestIntervals = Math.pow(distanceToPointOfContentration + 1, 2) * factorForMaximumLengthOfFinestIntervals;\n\t\t\tSystem.out.println(Math.pow(distanceToPointOfContentration + 1, 2) + \" * \" + factorForMaximumLengthOfFinestIntervals + \" = \" + maximumLengthOfFinestIntervals);\n\t\t\tList<Interval> refinements = refineOnLinearScale(intervalToRefine, maxNumberOfSubIntervalsPerRefinement, maximumLengthOfFinestIntervals);\n\n\t\t\tdepth++;\n\t\t\tif (refinements.size() == 1 && refinements.get(0).equals(intervalToRefine)) {\n\t\t\t\tdepth--;\n\t\t\t} else {\n\t\t\t\tCollections.reverse(refinements);\n\t\t\t\topenRefinements.addAll(refinements);\n\t\t\t}\n\n\t\t} while (!openRefinements.isEmpty());\n\t}\n\n\tpublic static boolean isDefaultConfiguration(ComponentInstance instance) {\n\t\tfor (Parameter p : instance.getParametersThatHaveBeenSetExplicitly()) {\n\t\t\tif (p.isNumeric()) {\n\t\t\t\tList<String> intervalAsList = SetUtil.unserializeList(instance.getParameterValue(p));\n\t\t\t\tdouble defaultValue = Double.parseDouble(p.getDefaultValue().toString());\n\t\t\t\tboolean isCompatibleWithDefaultValue = defaultValue >= Double.parseDouble(intervalAsList.get(0)) && defaultValue <= Double.parseDouble(intervalAsList.get(1));\n\t\t\t\tif (!isCompatibleWithDefaultValue) {\n\t\t\t\t\tlogger.info(p.getName() + \" has value \" + instance.getParameterValue(p) + \", which does not subsume the default value \" + defaultValue);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tlogger.info(p.getName() + \" has value \" + instance.getParameterValue(p) + \", which IS COMPATIBLE with the default value \" + defaultValue);\n\t\t\t} else {\n\t\t\t\tif (!instance.getParameterValue(p).equals(p.getDefaultValue().toString())) {\n\t\t\t\t\tlogger.info(p.getName() + \" has value \" + instance.getParameterValue(p) + \", which is not the default \" + p.getDefaultValue().toString());\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (ComponentInstance child : instance.getSatisfactionOfRequiredInterfaces().values()) {\n\t\t\tif (!isDefaultConfiguration(child))\n\t\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n}\n" }, { "alpha_fraction": 0.8410493731498718, "alphanum_fraction": 0.8410493731498718, "avg_line_length": 44.28571319580078, "blob_id": "2b8977d25d672a89d642f9115a3d7da36b772a43", "content_id": "0fb698b15173fde30d173e392de4bd92a624ab88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 648, "license_type": "no_license", "max_line_length": 166, "num_lines": 14, "path": "/JAICore/jaicore-search/test/jaicore/search/testproblems/knapsack/KnapsackToGraphSearchProblemInputReducer.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.testproblems.knapsack;\r\n\r\nimport jaicore.basic.algorithm.AlgorithmProblemTransformer;\r\nimport jaicore.search.model.probleminputs.GraphSearchProblemInput;\r\nimport jaicore.search.testproblems.knapsack.KnapsackProblem.KnapsackNode;\r\n\r\npublic class KnapsackToGraphSearchProblemInputReducer implements AlgorithmProblemTransformer<KnapsackProblem, GraphSearchProblemInput<KnapsackNode, String, Double>> {\r\n\r\n\t@Override\r\n\tpublic GraphSearchProblemInput<KnapsackNode, String, Double> transform(KnapsackProblem problem) {\r\n\t\treturn new GraphSearchProblemInput<>(problem.getGraphGenerator(), problem.getSolutionEvaluator());\r\n\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6288343667984009, "alphanum_fraction": 0.6441717743873596, "avg_line_length": 37.75609588623047, "blob_id": "20c9b9fdd603ac8f357559276bf614f6bb316165", "content_id": "f9efda76f1007b78cd9d15c7f8ea600ba8e11189", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1630, "license_type": "no_license", "max_line_length": 182, "num_lines": 41, "path": "/JAICore/jaicore-search/test/jaicore/search/testproblems/enhancedttsp/EnhancedTTSPGenerator.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.testproblems.enhancedttsp;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.Arrays;\r\nimport java.util.List;\r\nimport java.util.Random;\r\n\r\nimport jaicore.basic.sets.SetUtil.Pair;\r\nimport jaicore.graph.LabeledGraph;\r\n\r\npublic class EnhancedTTSPGenerator {\r\n\tpublic EnhancedTTSP generate(int n, int maxDistance) {\r\n\t\t\r\n\t\t/* create TTSP problem */\r\n\t\tRandom r = new Random(0);\r\n\t\tList<Boolean> blockedHours = Arrays.asList(\r\n\t\t\t\tnew Boolean[] { true, true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true });\r\n\t\tLabeledGraph<Short, Double> travelGraph;\r\n\t\ttravelGraph = new LabeledGraph<>();\r\n\t\tList<Pair<Double, Double>> coordinates = new ArrayList<>();\r\n\t\tfor (short i = 0; i < n; i++) {\r\n\t\t\tcoordinates.add(new Pair<>(r.nextDouble() * maxDistance, r.nextDouble() * maxDistance));\r\n\t\t\ttravelGraph.addItem(i);\r\n\t\t}\r\n\t\tfor (short i = 0; i < n; i++) {\r\n\t\t\tdouble x1 = coordinates.get(i).getX();\r\n\t\t\tdouble y1 = coordinates.get(i).getY();\r\n\t\t\tfor (short j = 0; j < i; j++) { // we assume a symmetric travel graph\r\n\t\t\t\tdouble x2 = coordinates.get(j).getX();\r\n\t\t\t\tdouble y2 = coordinates.get(j).getY();\r\n\t\t\t\tdouble minTravelTime = Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));\r\n\t\t\t\t// System.out.println(\"(\" + x1 + \", \" + y1 + \") to (\" +x2 +\", \" + y2 +\") = \"\r\n\t\t\t\t// +minTravelTime);\r\n\t\t\t\ttravelGraph.addEdge(i, j, minTravelTime);\r\n\t\t\t\ttravelGraph.addEdge(j, i, minTravelTime);\r\n\t\t\t}\r\n\t\t}\r\n\t\tEnhancedTTSP ttsp = new EnhancedTTSP(travelGraph, (short) 0, blockedHours, 8, 4.5, 1, 10);\r\n\t\treturn ttsp;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6737797856330872, "alphanum_fraction": 0.677979588508606, "avg_line_length": 27.42258071899414, "blob_id": "4b43511de0cb77a566b26b88f9e80cce0cf6ada2", "content_id": "e919932ee6e7dfbbf9104950806746f058d25d4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 8810, "license_type": "no_license", "max_line_length": 161, "num_lines": 310, "path": "/JAICore/jaicore-logic/src/jaicore/logic/fol/structure/Literal.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.logic.fol.structure;\n\nimport java.io.Serializable;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport jaicore.basic.StringUtil;\nimport jaicore.logic.fol.util.LogicUtil;\n\n\n/**\n * A literal defines a property over parameters. Note that literals can be cloned using the clone() methods.\n * \n * @author Felix Mohr\n */\n@SuppressWarnings(\"serial\")\npublic class Literal implements Serializable {\n\n\tprivate static Logger logger = LoggerFactory.getLogger(Literal.class);\n\n\t// private short getIntProperty(String property) {\n\t// boolean isNegated = property.startsWith(\"!\");\n\t// String propertyName = !isNegated ? property : property.substring(1);\n\t// if (!ext2int.containsKey(propertyName)) {\n\t// short id = counter ++;\n\t// if (id < 0)\n\t// throw new IllegalArgumentException(\"No support for more than \" + Short.MAX_VALUE + \" predicates!\");\n\t// ext2int.put(propertyName, id);\n\t// int2ext.put(id, propertyName);\n\t// }\n\t// return (short)(ext2int.get(propertyName) * (isNegated ? -1 : 1));\n\t// }\n\n\tprivate String property;\n\tprotected List<LiteralParam> parameters;\n\n\tpublic Literal(Literal l, Map<? extends LiteralParam, ? extends LiteralParam> map) {\n\t\tthis(l.getProperty());\n\t\tfor (LiteralParam p : l.getParameters()) {\n\t\t\tparameters.add(map.containsKey(p) ? map.get(p) : p);\n\t\t}\n\t}\n\n\t/**\n\t * Creates a monadic literal (with only one parameter).\n\t * \n\t * @param property\n\t * The property defined by this literal.\n\t * @param parameter\n\t * The parameter of this literal.\n\t */\n\tpublic Literal(String property, LiteralParam parameter) {\n\t\tthis(property);\n\t\tthis.parameters.add(parameter);\n\t}\n\n\t/**\n\t * Creates a monadic literal (with only one parameter).\n\t * \n\t * @param property\n\t * The property defined by this literal.\n\t * @param parameter\n\t * The parameter of this literal.\n\t */\n\t// private Literal(short property, List<LiteralParam> parameters) {\n\t// this(property);\n\t// this.parameters.addAll(parameters);\n\t// }\n\t//\n\t// private Literal(short property) {\n\t// this.parameters = new ArrayList<>();\n\t// this.property = property;\n\t// }\n\n\t/**\n\t * Creates a literal with a list of parameters.\n\t * \n\t * @param property\n\t * The property defined by this literal.\n\t * @param parameter\n\t * The parameters of this literal defined as a list.\n\t */\n\tpublic Literal(String property, List<? extends LiteralParam> parameters) {\n\t\tthis(property);\n\t\tif (parameters.contains(null))\n\t\t\tthrow new IllegalArgumentException(\"Literal parameters must not be null!\");\n\t\tthis.parameters.addAll(parameters);\n\t}\n\n\t/**\n\t * Protected helper constructor. Ensure the literal gets parameters!!\n\t */\n\tpublic Literal(String propertyWithParams) {\n\t\tsuper();\n\t\tthis.parameters = new ArrayList<>();\n\n\t\t/* detect special predicates = or != */\n\t\tif (propertyWithParams.contains(\"=\")) {\n\t\t\tString[] params = StringUtil.explode(propertyWithParams, \"=\");\n\t\t\tboolean isNegated = params.length > 0 && params[0].endsWith(\"!\");\n\t\t\tthis.property = isNegated ? \"!=\" : \"=\";\n\t\t\tif (params.length == 2) {\n\t\t\t\tint p1Length = isNegated ? params[0].length() - 1 : params[0].length();\n\t\t\t\tthis.parameters.add(LogicUtil.parseParamName(params[0].substring(0, p1Length).trim()));\n\t\t\t\tthis.parameters.add(LogicUtil.parseParamName(params[1].trim()));\n\t\t\t}\n\n\t\t}\n\n\t\t/* otherwise, if this is a normal predicate */\n\t\telse {\n\n\t\t\tboolean isPositive = true;\n\t\t\tif (propertyWithParams.startsWith(\"!\")) {\n\t\t\t\tisPositive = false;\n\t\t\t\tpropertyWithParams = propertyWithParams.substring(1);\n\t\t\t}\n\n\t\t\t/* add parameters if given in the string */\n\t\t\tif (propertyWithParams.contains(\"(\")) {\n\t\t\t\tif (propertyWithParams.contains(\")\")) {\n\t\t\t\t\tint index = propertyWithParams.indexOf('(');\n\t\t\t\t\tthis.property = propertyWithParams.substring(0, index);\n\t\t\t\t\tif (index < propertyWithParams.length() - 2) {\n\t\t\t\t\t\tthis.parameters.addAll(Arrays.asList(StringUtil.explode(propertyWithParams.substring(index + 1, propertyWithParams.length() - 1), \",\")).stream().map(s -> {\n\t\t\t\t\t\t\treturn LogicUtil.parseParamName(s.trim());\n\t\t\t\t\t\t}).collect(Collectors.toList()));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthis.property = propertyWithParams;\n\t\t\t}\n\t\t\tif (!isPositive) {\n\t\t\t\tthis.property = \"!\" + this.property;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic Literal(String property2, boolean isPositive) {\n\t\tthis(property2);\n\t\tif (isPositive && isNegated()) {\n\t\t\tthis.toggleNegation();\n\t\t} else if (!isPositive && isPositive()) {\n\t\t\tthis.toggleNegation();\n\t\t}\n\t}\n\n\tpublic Literal(String property2, List<? extends LiteralParam> parameters, boolean isPositive) {\n\t\tthis(property2, parameters);\n\t\tif (isPositive && isNegated()) {\n\t\t\tthis.toggleNegation();\n\t\t} else if (!isPositive && isPositive()) {\n\t\t\tthis.toggleNegation();\n\t\t}\n\t}\n\n\t/**\n\t * Returns a String representation of the property stated by this literal.\n\t */\n\tpublic final String getProperty() {\n\t\treturn (isNegated() ? \"!\" : \"\") + getPropertyName();\n\t}\n\n\t/**\n\t * Returns only the property name of this literal.\n\t */\n\tpublic final String getPropertyName() {\n\t\treturn isNegated() ? property.substring(1) : property;\n\t}\n\n\t/**\n\t * @return The parameters of this literal in an unmodifiable list.\n\t */\n\tpublic final List<LiteralParam> getParameters() {\n\t\treturn Collections.unmodifiableList(parameters);\n\t}\n\n\tpublic final boolean isNegated() {\n\t\treturn property.startsWith(\"!\");\n\t}\n\n\tpublic Literal toggleNegation() {\n\t\tproperty = isNegated() ? getPropertyName() : \"!\" + getPropertyName();\n\t\treturn this;\n\t}\n\n\t/**\n\t * @return The variable parameters of this literal in an unmodifiable list.\n\t */\n\tpublic final List<VariableParam> getVariableParams() {\n\t\tList<VariableParam> vars = new LinkedList<>();\n\t\tfor (LiteralParam param : parameters)\n\t\t\tif (param instanceof VariableParam)\n\t\t\t\tvars.add((VariableParam) param);\n\t\treturn Collections.unmodifiableList(vars);\n\t}\n\n\tpublic final List<ConstantParam> getConstantParams() {\n\t\tList<ConstantParam> constants = new ArrayList<>();\n\t\tfor (LiteralParam param : parameters)\n\t\t\tif (param instanceof ConstantParam)\n\t\t\t\tconstants.add((ConstantParam) param);\n\t\treturn Collections.unmodifiableList(constants);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((parameters == null) ? 0 : parameters.hashCode());\n\t\tresult = prime * result + ((property == null) ? 0 : property.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tLiteral other = (Literal) obj;\n\t\tif (parameters == null) {\n\t\t\tif (other.parameters != null)\n\t\t\t\treturn false;\n\t\t} else if (!parameters.equals(other.parameters))\n\t\t\treturn false;\n\t\tif (property == null) {\n\t\t\tif (other.property != null)\n\t\t\t\treturn false;\n\t\t} else if (!property.equals(other.property))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic Literal clone() {\n\t\treturn new Literal(this.property, this.parameters);\n\t}\n\n\t/**\n\t * Creates a copy of this literal on which the given parameter mapping is applied.\n\t * \n\t * @param mapping\n\t * A mapping of parameters.\n\t * @return A copy of this literal on which the given parameter mapping is applied.\n\t */\n\tpublic Literal clone(Map<? extends VariableParam, ? extends LiteralParam> mapping) {\n\t\tlogger.debug(\"start cloning\");\n\t\tLiteral clone = new Literal(this.property);\n\n\t\t// add parameters corresponding to mapping\n\t\tfor (LiteralParam v : this.getParameters()) {\n\t\t\tif (v instanceof VariableParam && mapping != null && mapping.containsKey(v)) {\n\t\t\t\tlogger.trace(\"Params: {}\", clone.parameters);\n\t\t\t\tif (mapping.get(v) == null)\n\t\t\t\t\tthrow new IllegalArgumentException(\"Mapping \" + mapping + \" assigns null to a parameter, which must not be the case!\");\n\t\t\t\tclone.parameters.add(mapping.get(v));\n\t\t\t} else\n\t\t\t\tclone.parameters.add(v);\n\t\t}\n\t\tlogger.debug(\"finished cloning\");\n\t\treturn clone;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\n\t\tStringBuilder sb = new StringBuilder();\n\t\tsb.append(property + \"(\");\n\n\t\t// iterate through parameter list\n\t\tint params = this.parameters.size();\n\t\tint i = 1;\n\t\tfor (LiteralParam p : this.parameters) {\n\t\t\tsb.append(p.toString());\n\t\t\tif (i++ < params)\n\t\t\t\tsb.append(\", \");\n\t\t}\n\t\tsb.append(\")\");\n\n\t\treturn sb.toString();\n\n\t}\n\n\tpublic boolean isNegationOf(Literal l) {\n\t\treturn l.getPropertyName().equals(this.getPropertyName()) && l.getParameters().equals(this.parameters) && l.isNegated() != this.isNegated();\n\t}\n\n\tpublic boolean isPositive() {\n\t\treturn !this.isNegated();\n\t}\n\n\tpublic boolean hasVariableParams() {\n\t\treturn !this.getVariableParams().isEmpty();\n\t}\n\n\tpublic final boolean isGround() {\n\t\treturn !hasVariableParams();\n\t}\n}" }, { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 26.91666603088379, "blob_id": "7eeb9b553972cf6bf1eb79f27c61abd12f264f19", "content_id": "c5504904b75f4eefd5773435da60255db12b9632", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 335, "license_type": "no_license", "max_line_length": 113, "num_lines": 12, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/uncertainty/IUncertaintySource.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.uncertainty;\n\nimport java.util.List;\n\nimport jaicore.search.model.travesaltree.Node;\n\n@FunctionalInterface\npublic interface IUncertaintySource <T, V extends Comparable<V>>{\n\n\tpublic double calculateUncertainty (Node<T, V> n, List<List<T>> simulationPaths, List<V> simulationEvaluations);\n\t\n}\n" }, { "alpha_fraction": 0.6729816198348999, "alphanum_fraction": 0.6762859225273132, "avg_line_length": 41.44019317626953, "blob_id": "b78731ed8a57a4d183ea81b6fb2ad34ec3f2998a", "content_id": "7c05b3bad73cdfa7e46f7bdbc2c1303911d52668", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 9079, "license_type": "no_license", "max_line_length": 198, "num_lines": 209, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/parallel/parallelexploration/distributed/DistributedOrSearchCoworker.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "//package jaicore.search.algorithms.parallel.parallelexploration.distributed;\r\n//\r\n//import java.nio.file.Path;\r\n//import java.nio.file.Paths;\r\n//import java.util.ArrayList;\r\n//import java.util.Collection;\r\n//import java.util.List;\r\n//import java.util.Set;\r\n//import java.util.Timer;\r\n//import java.util.TimerTask;\r\n//import java.util.stream.Collectors;\r\n//\r\n//import org.slf4j.Logger;\r\n//import org.slf4j.LoggerFactory;\r\n//\r\n//import jaicore.graphvisualizer.VisualizationWindow;\r\n//import jaicore.graphvisualizer.TooltipGenerator;\r\n//import jaicore.search.algorithms.interfaces.IORGraphSearch;\r\n//import jaicore.search.algorithms.interfaces.IORGraphSearchFactory;\r\n//import jaicore.search.algorithms.interfaces.IObservableORGraphSearch;\r\n//import jaicore.search.algorithms.parallel.parallelexploration.distributed.interfaces.DistributedSearchCommunicationLayer;\r\n//import jaicore.search.algorithms.standard.bestfirst.BestFirst;\r\n//import jaicore.search.algorithms.standard.bestfirst.model.GraphGenerator;\r\n//import jaicore.search.algorithms.standard.bestfirst.model.Node;\r\n//import jaicore.search.algorithms.standard.bestfirst.nodeevaluation.INodeEvaluator;\r\n//import meka.core.A;\r\n//\r\n//public class DistributedOrSearchCoworker<T, A, L extends IGraphAlgorithmListener<V,E>, V extends Comparable<V>> implements IORGraphSearch<T, A, L, O> {\r\n//\r\n//\tprivate final static Logger logger = LoggerFactory.getLogger(DistributedOrSearchCoworker.class);\r\n//\r\n//\tprivate final IORGraphSearchFactory<T, A, V> algorithmFactory;\r\n//\tprivate final DistributedSearchCommunicationLayer<T, A, V> coworkerInterface;\r\n//\tprotected final String id;\r\n//\tprivate final int searchTime;\r\n//\tprivate final int uptime;\r\n//\tprivate boolean shutdown = false;\r\n//\tprivate boolean showGraph;\r\n//\tprivate Class<?> tooltipGenerator;\r\n//\r\n//\tpublic DistributedOrSearchCoworker(IORGraphSearchFactory<T, A, V> algorithmFactory, DistributedSearchCommunicationLayer<T, A, V> coworkerInterface, String id, int uptime, int searchTime,\r\n//\t\t\tboolean showGraph) {\r\n//\t\tsuper();\r\n//\t\tthis.algorithmFactory = algorithmFactory;\r\n//\t\tthis.coworkerInterface = coworkerInterface;\r\n//\t\tthis.id = id;\r\n//\t\tthis.searchTime = searchTime;\r\n//\t\tthis.uptime = uptime;\r\n//\t\tthis.showGraph = showGraph;\r\n//\t\tlogger.info(\"Created new coworker {}\", this.id);\r\n//\t}\r\n//\r\n//\t@SuppressWarnings(\"unchecked\")\r\n//\tpublic void cowork() {\r\n//\r\n//\t\tfinal Thread runningThread = Thread.currentThread();\r\n//\t\tTimer timer = new Timer();\r\n//\t\ttimer.schedule(new TimerTask() {\r\n//\r\n//\t\t\t@Override\r\n//\t\t\tpublic void run() {\r\n//\t\t\t\tlogger.info(\"Uptime of coworker {} ended; shutting it down. Note that the shutdown will be effective not until the current job is finished.\", id);\r\n//\t\t\t\tshutdown = true;\r\n//\r\n//\t\t\t\t/* if we have not been attached, we stop working */\r\n//\t\t\t\tif (!coworkerInterface.isAttached(id)) {\r\n//\t\t\t\t\tlogger.info(\"Coworker has not been attached, so interrupting waiting thread.\");\r\n//\t\t\t\t\trunningThread.interrupt();\r\n//\t\t\t\t}\r\n//\t\t\t\tcoworkerInterface.unregister(id);\r\n//\t\t\t}\r\n//\t\t}, uptime);\r\n//\r\n//\t\t/* register this coworker and setup the timer for unregister */\r\n//\t\ttry {\r\n//\t\t\tcoworkerInterface.register(this.id);\r\n//\t\t\tlogger.info(\"Coworker has been attached.\");\r\n//\t\t} catch (InterruptedException e) {\r\n//\t\t\tlogger.info(\"Coworker was interrupted while waiting for attachment.\");\r\n//\t\t}\r\n//\r\n//\t\t/* now busily wait for jobs forever */\r\n//\t\tGraphGenerator<T, A> graphGenerator = null;\r\n//\t\tINodeEvaluator<T, V> nodeEvaluator = null;\r\n//\t\ttry {\r\n//\t\t\twhile (!shutdown || coworkerInterface.isAttached(this.id)) {\r\n//\r\n//\t\t\t\t/* wait until a new job has arrived */\r\n//\t\t\t\tlogger.info(\"Waiting for next job ...\");\r\n//\t\t\t\tfinal Collection<Node<T, V>> nodes = coworkerInterface.nextJob(this.id);\r\n//\t\t\t\tlogger.info(\"Found new job ...\");\r\n//\t\t\t\tif (nodes == null || nodes.isEmpty()) {\r\n//\t\t\t\t\tlogger.warn(\"Received NULL or EMPTY node list.\");\r\n//\t\t\t\t\tbreak;\r\n//\t\t\t\t}\r\n//\r\n//\t\t\t\t/* if this is the first job, get graph generator and node evaluator */\r\n//\t\t\t\tif (graphGenerator == null || nodeEvaluator == null) {\r\n//\t\t\t\t\tgraphGenerator = coworkerInterface.getGraphGenerator();\r\n//\t\t\t\t\tnodeEvaluator = coworkerInterface.getNodeEvaluator();\r\n//\t\t\t\t}\r\n//\r\n//\t\t\t\t/* if we became detached and want to shut down, leave loop */\r\n//\t\t\t\tif (shutdown && !coworkerInterface.isAttached(this.id)) {\r\n//\t\t\t\t\tlogger.info(\"Coworker will be shutdown since shutdown signal has been received and the coworker is not attached.\");\r\n//\t\t\t\t\tbreak;\r\n//\t\t\t\t}\r\n//\r\n//\t\t\t\t/*\r\n//\t\t\t\t * setup the search algorithm with the graph generator, and configure a time out\r\n//\t\t\t\t */\r\n//\t\t\t\tIObservableORGraphSearch<T, A, V> searchAlgorithm = (IObservableORGraphSearch<T, A, V>) algorithmFactory.getSearch(graphGenerator, nodeEvaluator);\r\n//\t\t\t\ttimer.schedule(new TimerTask() {\r\n//\t\t\t\t\t@Override\r\n//\t\t\t\t\tpublic void run() {\r\n//\t\t\t\t\t\tlogger.info(\"Search timeout triggered. Shutting down search process.\");\r\n//\t\t\t\t\t\tsearchAlgorithm.cancel();\r\n//\t\t\t\t\t}\r\n//\t\t\t\t}, searchTime);\r\n//\r\n//\t\t\t\t/* run the algorithm */\r\n//\t\t\t\tif (showGraph) {\r\n//\t\t\t\t\tVisualizationWindow<Node<T, V>> window = new VisualizationWindow<>(((IObservableORGraphSearch<T, A, V>) searchAlgorithm));\r\n//\t\t\t\t\twindow.setTitle(this.id);\r\n//\t\t\t\t\tif (tooltipGenerator != null)\r\n//\t\t\t\t\t\twindow.setTooltipGenerator((TooltipGenerator<Node<T, V>>) tooltipGenerator.getConstructor().newInstance());\r\n//\t\t\t\t}\r\n//\t\t\t\tList<T> solution;\r\n//\t\t\t\tList<Node<T, V>> solutionNodes = new ArrayList<>();\r\n//\t\t\t\tlogger.info(\"Running coworker {} with: {}\", this.id, nodes.stream().map(n -> n.getPoint()).collect(Collectors.toList()));\r\n//\t\t\t\tsearchAlgorithm.bootstrap(nodes);\r\n//\t\t\t\tdo {\r\n//\t\t\t\t\tsolution = searchAlgorithm.nextSolution();\r\n//\t\t\t\t\tif (solution != null)\r\n//\t\t\t\t\t\tsolutionNodes.add(searchAlgorithm.getInternalRepresentationOf(solution.get(solution.size() - 1)));\r\n//\t\t\t\t} while (solution != null);\r\n//\t\t\t\tlogger.info(\"Coworker {} finished, reporting results and going to wait for new jobs.\", this.id);\r\n//\r\n//\t\t\t\t/* report results */\r\n//\t\t\t\tCollection<Node<T, V>> openNodes = searchAlgorithm.getOpenSnapshot();\r\n//\t\t\t\tlogger.info(\"Reporting open list of size \" + openNodes.size() + \" and \" + solutionNodes.size() + \" solutions.\");\r\n//\t\t\t\tDistributedComputationResult<T, V> result = new DistributedComputationResult<>(this.id, openNodes, solutionNodes);\r\n//\t\t\t\tcoworkerInterface.reportResult(this.id, result);\r\n//\r\n//\t\t\t\t/* if we returned nothing, detach for debugging */\r\n//\t\t\t\tif (openNodes.isEmpty() && solutionNodes.isEmpty()) {\r\n//\t\t\t\t\tlogger.warn(\"Produced dead end!\");\r\n//\t\t\t\t}\r\n//\t\t\t}\r\n//\t\t} catch (InterruptedException e) {\r\n//\t\t\tlogger.info(\"Received interrupt.\");\r\n//\t\t} catch (NoClassDefFoundError | ClassNotFoundException e) {\r\n//\t\t\tlogger.error(\r\n//\t\t\t\t\t\"Cannot perform the search as the class {} was not found on the classpath. This is probably a problem of serialization. Simply make sure that the class is on the classpath for the coworker.\",\r\n//\t\t\t\t\te.getMessage());\r\n//\t\t} catch (Throwable e) {\r\n//\t\t\tlogger.error(\"Execution terminated unexpectedly. Please check error log!\");\r\n//\t\t\te.printStackTrace();\r\n//\t\t}\r\n//\r\n//\t\t/* shutdown infrastructure */\r\n//\t\ttimer.cancel();\r\n//\t\tif (coworkerInterface.isAttached(id))\r\n//\t\t\tcoworkerInterface.detachCoworker(id);\r\n//\t\telse\r\n//\t\t\tcoworkerInterface.unregister(id);\r\n//\t\tcoworkerInterface.close();\r\n//\t\tSet<Thread> threadSet = Thread.getAllStackTraces().keySet();\r\n//\t\tlogger.info(\"Terminating. Currently active threads: {}\", threadSet);\r\n//\t}\r\n//\r\n//\tpublic static <T, A, V extends Comparable<V>> void main(String[] args) {\r\n//\r\n//\t\tif (args.length < 5) {\r\n//\t\t\tSystem.err.println(\"Need at least 5 args: communicationFolder, coworkerId, searchTime (s), upTime (s), showGraph[, numThreads]\");\r\n//\t\t\tSystem.exit(1);\r\n//\t\t}\r\n//\r\n//\t\tPath folder = Paths.get(args[0]);\r\n//\t\tString id = args[1];\r\n//\t\tint searchTime = Integer.parseInt(args[2]) * 1000;\r\n//\t\tint uptime = Integer.parseInt(args[3]) * 1000;\r\n//\t\tboolean showGraph = Boolean.parseBoolean(args[4]);\r\n//\t\tint threads = (args.length > 5) ? Integer.parseInt(args[5]) : 1;\r\n//\r\n//\t\tlogger.info(\"Using {} threads.\", threads);\r\n//\t\tString strClassPath = System.getProperty(\"java.class.path\");\r\n//\t\tlogger.info(\"Classpath is \" + strClassPath);\r\n//\r\n//\t\tIORGraphSearchFactory<T, A, V> factory = (gen, eval) -> {\r\n//\t\t\tBestFirst<T, A, V> search = new jaicore.search.algorithms.standard.bestfirst.BestFirst<>(gen, eval);\r\n//\t\t\tif (threads > 1)\r\n//\t\t\t\tsearch.parallelizeNodeExpansion(threads);\r\n//\t\t\tsearch.setTimeoutForComputationOfF(1000, n -> null);\r\n//\t\t\treturn search;\r\n//\t\t};\r\n//\t\tDistributedSearchCommunicationLayer<T, A, V> communicationLayer = new FolderBasedDistributedSearchCommunicationLayer<>(folder, false);\r\n//\t\tDistributedOrSearchCoworker<T, A, V> coworker = new DistributedOrSearchCoworker<>(factory, communicationLayer, id, uptime, searchTime, showGraph);\r\n//\t\tif (args.length > 5) {\r\n//\t\t\ttry {\r\n//\t\t\t\tcoworker.tooltipGenerator = Class.forName(args[6]);\r\n//\t\t\t} catch (ClassNotFoundException e) {\r\n//\t\t\t\te.printStackTrace();\r\n//\t\t\t}\r\n//\t\t}\r\n//\t\tcoworker.cowork();\r\n//\t\tSystem.exit(0);\r\n//\t}\r\n//}\r\n" }, { "alpha_fraction": 0.7602837085723877, "alphanum_fraction": 0.7602837085723877, "avg_line_length": 22.5, "blob_id": "13aaf7272d937dd76067ac09b89f3eb4a9f7e0b1", "content_id": "4165a3b146fccceec802ed1eaf225682447261be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1410, "license_type": "no_license", "max_line_length": 78, "num_lines": 60, "path": "/JAICore/jaicore-graphvisualizer/src/jaicore/graphvisualizer/gui/dataVisualizer/NodeExpansionVisualizer.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.graphvisualizer.gui.dataVisualizer;\n\nimport com.google.common.eventbus.EventBus;\nimport com.google.common.eventbus.Subscribe;\n\nimport jaicore.graphvisualizer.events.controlEvents.ResetEvent;\nimport jaicore.graphvisualizer.events.graphEvents.GraphInitializedEvent;\nimport jaicore.graphvisualizer.gui.GraphVisualization;\nimport javafx.scene.Node;\n\n/**\n * The NodeExpansionVisualizer is used to show the events, which happen on one\n * branch of the search tree. Usually the needed events, which are shown are\n * provided by jaicore.search.gui.dataSupplier.NodeExpansionSupplier.\n * \n * @author jkoepe\n *\n */\npublic class NodeExpansionVisualizer implements IVisualizer {\n\n\tEventBus bus = new EventBus();\n\tGraphVisualization<?,?> visualization;\n\n\t/**\n\t * Crates a new NodeExpansionVisualizer.\n\t */\n\tpublic NodeExpansionVisualizer() {\n\n\t\tvisualization = new GraphVisualization<>();\n\n\t\tbus.register(visualization);\n\t}\n\n\t@Override\n\tpublic String getSupplier() {\n\t\treturn \"NodeExpansionSupplier\";\n\t}\n\n\t@Override\n\tpublic String getTitle() {\n\t\treturn \"NodeExpansion\";\n\t}\n\n\t@Override\n\tpublic Node getVisualization() {\n\t\treturn visualization.getFXNode();\n\t}\n\n\t@Subscribe\n\tpublic void receiveEvents(Object event) {\n\t\ttry {\n\t\t\tif (event instanceof GraphInitializedEvent || event instanceof ResetEvent)\n\t\t\t\tvisualization.reset();\n\t\t\tbus.post(event);\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n}\n" }, { "alpha_fraction": 0.728863000869751, "alphanum_fraction": 0.728863000869751, "avg_line_length": 19.787878036499023, "blob_id": "03845427a93515c007c8c161194b06f89cda4d37", "content_id": "95c5ae5ea60e6a4ca20e614d3638d990bd8532fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 686, "license_type": "no_license", "max_line_length": 30, "num_lines": 33, "path": "/JAICore/jaicore-ml/src/jaicore/ml/measures/PMMulticlass.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.ml.measures;\n\npublic enum PMMulticlass {\n areaAboveROC,\n areaUnderROC,\n avgCost,\n correct,\n correlationCoefficient,\n errorRate,\n falseNegativeRate,\n falsePositiveRate,\n fMeasure,\n incorrect,\n kappa,\n kBInformation,\n kBMeanInformation,\n kBRelativeInformation,\n meanAbsoluteError,\n pctCorrect,\n pctIncorrect,\n precision,\n relativeAbsoluteError,\n rootMeanSquaredError,\n rootRelativeSquaredError,\n weightedAreaUnderROC,\n weightedFalseNegativeRate,\n weightedFalsePositiveRate,\n weightedFMeasure,\n weightedPrecision,\n weightedRecall,\n weightedTrueNegativeRate,\n weightedTruePositiveRate\n}\n" }, { "alpha_fraction": 0.7698412537574768, "alphanum_fraction": 0.7825396656990051, "avg_line_length": 27.636363983154297, "blob_id": "d56812d8178d13dd6cbb7bfa9b37b0cbcda87c2d", "content_id": "05ca1e3136513738fd5e753c3a4cc49f932c0c74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 630, "license_type": "no_license", "max_line_length": 111, "num_lines": 22, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/bestfirst/nodeevaluation/RandomizedDepthFirstNodeEvaluator.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.bestfirst.nodeevaluation;\n\nimport java.util.Random;\n\nimport jaicore.search.algorithms.parallel.parallelexploration.distributed.interfaces.SerializableNodeEvaluator;\nimport jaicore.search.model.travesaltree.Node;\n\n@SuppressWarnings(\"serial\")\npublic class RandomizedDepthFirstNodeEvaluator<T> implements SerializableNodeEvaluator<T,Double> {\n\n\tprivate final Random rand;\n\n\tpublic RandomizedDepthFirstNodeEvaluator(Random rand) {\n\t\tsuper();\n\t\tthis.rand = rand;\n\t}\n\n\t@Override\n\tpublic Double f(Node<T,?> node) {\n\t\treturn (double) (-1 * (node.path().size() * 1000 + rand.nextInt(100)));\n\t}\n}\n" }, { "alpha_fraction": 0.710087776184082, "alphanum_fraction": 0.7193741202354431, "avg_line_length": 29.468992233276367, "blob_id": "d24c867f3acefb6b6ad3fd5160c1e2aa2f2aca97", "content_id": "3b1fcf044c6aae63c428f5c8b0ff7c373d466613", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 7861, "license_type": "no_license", "max_line_length": 111, "num_lines": 258, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/uncertainty/explorationexploitationsearch/UncertaintyExplorationOpenSelection.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.uncertainty.explorationexploitationsearch;\n\nimport java.util.Collection;\nimport java.util.Comparator;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.PriorityQueue;\nimport java.util.Queue;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport jaicore.search.algorithms.standard.uncertainty.ISolutionDistanceMetric;\nimport jaicore.search.model.travesaltree.Node;\n\npublic class UncertaintyExplorationOpenSelection<T, V extends Comparable<V>> implements Queue<Node<T, V>> {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(UncertaintyExplorationOpenSelection.class);\n\n\tprivate final Queue<Node<T, V>> exploitationOpen = new PriorityQueue<>();\n\tprivate final PriorityQueue<Node<T, V>> explorationOpen = new PriorityQueue<>();\n\tprivate final ISolutionDistanceMetric<T> solutionDistanceMetric;\n\tprivate final IPhaseLengthAdjuster phaseLengthAdjuster;\n\tprivate final IExplorationCandidateSelector<T, V> candidateSelector;\n\tprivate int explorationPhaseLength;\n\tprivate int exploitationPhaseLength;\n\tdouble exploitationScoreThreshold;\n\tdouble explorationUncertaintyThreshold;\n\tprivate int selectedNodes = 0;\n\tprivate int exploredNodes = 0;\n\tprivate long timeout;\n\tprivate long startTime;\n\tprivate boolean exploring = true;\n\n\tpublic UncertaintyExplorationOpenSelection(long timeout, int phaseInterval, double exploitationScoreThreshold,\n\t\t\tdouble explorationUncertaintyThreshold, IPhaseLengthAdjuster phaseLengthAdjuster,\n\t\t\tISolutionDistanceMetric<T> solutionDistanceMetric, IExplorationCandidateSelector<T, V> candidateSelector) {\n\t\tsuper();\n\t\tthis.timeout = timeout;\n\t\tthis.startTime = System.currentTimeMillis();\n\t\tint[] phaseLenghts = phaseLengthAdjuster.getInitialPhaseLengths(phaseInterval);\n\t\tassert phaseLenghts.length == 2;\n\t\tthis.explorationPhaseLength = phaseLenghts[0];\n\t\tthis.exploitationPhaseLength = phaseLenghts[1];\n\t\tthis.exploitationScoreThreshold = exploitationScoreThreshold;\n\t\tthis.explorationUncertaintyThreshold = explorationUncertaintyThreshold;\n\t\tthis.phaseLengthAdjuster = phaseLengthAdjuster;\n\t\tthis.solutionDistanceMetric = solutionDistanceMetric;\n\t\tthis.candidateSelector = candidateSelector;\n\t}\n\n\t@Override\n\tpublic Node<T, V> peek() {\n\t\treturn selectCandidate(exploring);\n\t}\n\n\tprivate Node<T, V> selectCandidate(boolean isExploring) {\n\t\tComparator<Node<T, V>> comparator = (n1, n2) -> {\n\t\t\ttry {\n\t\t\t\tDouble u1 = (Double) n1.getAnnotation(\"uncertainty\");\n\t\t\t\tDouble u2 = (Double) n2.getAnnotation(\"uncertainty\");\n\t\t\t\tV v1 = n1.getInternalLabel();\n\t\t\t\tV v2 = n2.getInternalLabel();\n\t\t\t\tif (isExploring) {\n\t\t\t\t\tif (Math.abs(u1 - u2) <= this.explorationUncertaintyThreshold) {\n\t\t\t\t\t\treturn -1 * v1.compareTo(v2);\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn Double.compare(u1, u2);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (v1 instanceof Double && v2 instanceof Double) {\n\t\t\t\t\t\tDouble s1 = (Double) v1;\n\t\t\t\t\t\tDouble s2 = (Double) v2;\n\t\t\t\t\t\tif (Math.abs(s1 - s2) <= this.exploitationScoreThreshold) {\n\t\t\t\t\t\t\treturn Double.compare(u1, u2);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treturn Double.compare(s1, s2);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (v1 instanceof Double && v2 instanceof Double) {\n\t\t\t\t\t\t\tDouble s1 = (Double) v1;\n\t\t\t\t\t\t\tDouble s2 = (Double) v2;\n\t\t\t\t\t\t\tif (Math.abs(s1 - s2) <= this.exploitationScoreThreshold) {\n\t\t\t\t\t\t\t\treturn Double.compare(u1, u2);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\treturn v1.compareTo(v2);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treturn v1.compareTo(v2);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\t\t\t\tlogger.error(e.getMessage());\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t};\n\t\tif (isExploring) {\n\t\t\treturn explorationOpen.stream().max(comparator).orElse(explorationOpen.peek());\n\t\t} else {\n\t\t\treturn exploitationOpen.stream().min(comparator).orElse(exploitationOpen.peek());\n\t\t}\n\t}\n\n\tprivate void adjustPhaseLengths(long passedTime) {\n\t\tint[] newPhaseLengths = this.phaseLengthAdjuster.adjustPhaseLength(explorationPhaseLength,\n\t\t\t\texploitationPhaseLength, passedTime, this.timeout);\n\t\tassert newPhaseLengths.length == 2;\n\t\tthis.explorationPhaseLength = newPhaseLengths[0];\n\t\tthis.exploitationPhaseLength = newPhaseLengths[1];\n\t}\n\n\t@Override\n\tpublic boolean add(Node<T, V> node) {\n\t\tassert node != null : \"Cannot add node NULL to OPEN\";\n\t\tassert !contains(node) : \"Node \" + node + \" is already there!\";\n\t\tif (exploring) {\n\t\t\treturn explorationOpen.add(node);\n\t\t} else\n\t\t\treturn exploitationOpen.add(node);\n\t}\n\n\t@Override\n\tpublic boolean remove(Object node) {\n\t\tassert !(exploitationOpen.contains(node) && explorationOpen.contains(node)) : \"A node (\" + node\n\t\t\t\t+ \") that is to be removed is in BOTH open lists!\";\n\t\tif (exploring) {\n\t\t\treturn explorationOpen.remove(node) || exploitationOpen.remove(node);\n\t\t} else {\n\t\t\treturn exploitationOpen.remove(node) || explorationOpen.remove(node);\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean addAll(Collection<? extends Node<T, V>> arg0) {\n\t\tassert exploitationOpen != null : \"Primary OPEN is NULL!\";\n\t\tif (arg0 == null)\n\t\t\tthrow new IllegalArgumentException(\"Cannot add NULL collection\");\n\t\tif (arg0.contains(null))\n\t\t\tthrow new IllegalArgumentException(\"Cannot add collection that contains NULL\");\n\t\tif (exploring) {\n\t\t\treturn explorationOpen.addAll(arg0);\n\t\t} else\n\t\t\treturn exploitationOpen.addAll(arg0);\n\t}\n\n\t@Override\n\tpublic void clear() {\n\t\texploitationOpen.clear();\n\t\texplorationOpen.clear();\n\t}\n\n\t@Override\n\tpublic boolean contains(Object arg0) {\n\t\treturn exploitationOpen.contains(arg0) || explorationOpen.contains(arg0);\n\t}\n\n\t@Override\n\tpublic boolean containsAll(Collection<?> arg0) {\n\t\tfor (Object o : arg0) {\n\t\t\tif (!contains(o))\n\t\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean isEmpty() {\n\t\treturn exploitationOpen.isEmpty() && explorationOpen.isEmpty();\n\t}\n\n\t@Override\n\tpublic Iterator<Node<T, V>> iterator() {\n\t\treturn exploring ? explorationOpen.iterator() : exploitationOpen.iterator();\n\t}\n\n\t@Override\n\tpublic boolean removeAll(Collection<?> arg0) {\n\t\treturn exploitationOpen.removeAll(arg0) && explorationOpen.removeAll(arg0);\n\t}\n\n\t@Override\n\tpublic boolean retainAll(Collection<?> arg0) {\n\t\treturn exploitationOpen.retainAll(arg0) && explorationOpen.retainAll(arg0);\n\t}\n\n\t@Override\n\tpublic int size() {\n\t\treturn exploitationOpen.size() + explorationOpen.size();\n\t}\n\n\t@Override\n\tpublic Object[] toArray() {\n\t\treturn exploitationOpen.toArray();\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\t@Override\n\tpublic <X> X[] toArray(X[] arg0) {\n\t\treturn (X[]) exploitationOpen.toArray();\n\t}\n\n\t@Override\n\tpublic Node<T, V> element() {\n\t\treturn peek();\n\t}\n\n\t@Override\n\tpublic boolean offer(Node<T, V> e) {\n\t\treturn add(e);\n\t}\n\n\t@Override\n\tpublic Node<T, V> poll() {\n\t\treturn remove();\n\t}\n\n\t@Override\n\tpublic Node<T, V> remove() {\n\n\t\t/* determine element to be returned and remove it from the respective list */\n\t\tNode<T, V> peek = peek();\n\t\tremove(peek);\n\n\t\t/* update internal state */\n\t\tif (!exploring) {\n\t\t\tselectedNodes++;\n\t\t\tif (selectedNodes % exploitationPhaseLength == 0) {\n\t\t\t\tList<Node<T, V>> explorationCandidates = candidateSelector.selectExplorationCandidates(exploitationOpen,\n\t\t\t\t\t\texploitationOpen.peek(), solutionDistanceMetric);\n\n\t\t\t\t/* enable exploration with the node selected by the explorer evaluator */\n\t\t\t\ttry {\n\t\t\t\t\tlogger.info(\"Entering exploration phase under {}\", explorationCandidates);\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tlogger.error(e.getMessage());\n\t\t\t\t}\n\t\t\t\texploring = true;\n\t\t\t\texploredNodes = 0;\n\t\t\t\texploitationOpen.removeAll(explorationCandidates);\n\t\t\t\texplorationOpen.clear();\n\t\t\t\texplorationOpen.addAll(explorationCandidates);\n\t\t\t}\n\t\t} else {\n\t\t\texploredNodes++;\n\t\t\tif (exploredNodes > explorationPhaseLength || explorationOpen.isEmpty()) {\n\t\t\t\tadjustPhaseLengths(System.currentTimeMillis() - this.startTime);\n\t\t\t\texploring = false;\n\t\t\t\texploitationOpen.addAll(explorationOpen);\n\t\t\t\texplorationOpen.clear();\n\t\t\t\tlogger.info(\"Entering exploitation phase\");\n\t\t\t}\n\t\t}\n\n\t\t/* return the peeked element */\n\t\treturn peek;\n\t}\n}\n" }, { "alpha_fraction": 0.6469957232475281, "alphanum_fraction": 0.6488733887672424, "avg_line_length": 31.701753616333008, "blob_id": "6704018b339d22b5f8f46c757eac240b6cd47859", "content_id": "72162ae94d82aba7ba409b9730365addc7b7a9ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3728, "license_type": "no_license", "max_line_length": 176, "num_lines": 114, "path": "/JAICore/jaicore-ml/src/jaicore/ml/core/WekaInstancesFeatureUnion.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.ml.core;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\n\nimport weka.core.Attribute;\nimport weka.core.DenseInstance;\nimport weka.core.Instance;\nimport weka.core.Instances;\n\npublic class WekaInstancesFeatureUnion {\n\n public Instances merge(final Instances dataA, final Instances dataB) {\n if (dataA == null || dataB == null) {\n throw new IllegalArgumentException(\"Instances objects must not be null.\");\n }\n\n List<Instances> datasetList = new LinkedList<>();\n datasetList.add(dataA);\n datasetList.add(dataB);\n\n return this.merge(datasetList);\n }\n\n public Instances merge(final Collection<Instances> data) {\n if (data.size() < 1) {\n throw new IllegalArgumentException(\"Merge cannot be invoked with empty collection of Instances\");\n } else if (data.size() == 1) {\n return data.iterator().next();\n }\n\n boolean allEqualSize = true;\n Iterator<Instances> dataIt = data.iterator();\n Instances currentInstances = dataIt.next();\n while (dataIt.hasNext()) {\n Instances nextInstances = dataIt.next();\n if (currentInstances.size() != nextInstances.size()) {\n allEqualSize = false;\n break;\n }\n currentInstances = nextInstances;\n }\n\n if (!allEqualSize) {\n throw new IllegalArgumentException(\"The sizes of the provided Instances objects are not equal, Instance should only differ in the features not in the instances itself.\");\n }\n\n // First of all merge the lists of attributes to construct the meta data of the feature merged\n // dataset.\n ArrayList<Attribute> mergedAttributeList = new ArrayList<>();\n Map<Attribute, Attribute> attributeMap = new HashMap<>();\n\n Attribute classAttribute = null;\n String relationName = null;\n Integer size = null;\n\n int ns = 0;\n for (Instances dataset : data) {\n if (classAttribute == null) {\n classAttribute = dataset.classAttribute().copy(ns + \"-\" + dataset.classAttribute().name());\n attributeMap.put(dataset.classAttribute(), classAttribute);\n }\n if (relationName == null) {\n relationName = dataset.relationName();\n }\n if (size == null) {\n size = dataset.size();\n }\n\n for (int i = 0; i < dataset.numAttributes(); i++) {\n if (i != dataset.classIndex()) {\n Attribute copiedAttribute = dataset.attribute(i).copy(ns + \"-\" + dataset.attribute(i).name());\n mergedAttributeList.add(copiedAttribute);\n attributeMap.put(dataset.attribute(i), copiedAttribute);\n }\n }\n ns++;\n }\n mergedAttributeList.add(classAttribute);\n\n Instances mergedInstances = new Instances(\"FeatureUnionInstances-\" + relationName, mergedAttributeList, size);\n mergedInstances.setClassIndex(mergedInstances.numAttributes() - 1);\n\n for (int i = 0; i < size; i++) {\n Instance iNew = new DenseInstance(mergedAttributeList.size());\n iNew.setDataset(mergedInstances);\n\n // copy attribute values from original instance objects\n for (Instances dataset : data) {\n Instance iDataset = dataset.get(i);\n for (int j = 0; j < dataset.numAttributes(); j++) {\n Attribute originalKey = null;\n for (Attribute key : attributeMap.keySet()) {\n if (key == iDataset.attribute(j)) {\n originalKey = key;\n }\n }\n if (originalKey != null) {\n iNew.setValue(attributeMap.get(dataset.attribute(j)), iDataset.value(dataset.attribute(j)));\n }\n }\n }\n mergedInstances.add(iNew);\n }\n\n return mergedInstances;\n }\n\n}\n" }, { "alpha_fraction": 0.8387500047683716, "alphanum_fraction": 0.8387500047683716, "avg_line_length": 42.44444274902344, "blob_id": "b640e147093c81eb0bfe20f9203cd7b8b3b23eac", "content_id": "dfe3b119b665f9cf255d6725126fb3c8e48877cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 800, "license_type": "no_license", "max_line_length": 157, "num_lines": 18, "path": "/softwareconfiguration/hasco/test/hasco/test/HASCOViaFDAndBestFirstWithRandomCompletionsTester.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package hasco.test;\r\n\r\nimport org.junit.AfterClass;\r\n\r\nimport hasco.core.HASCOFactory;\r\nimport hasco.variants.forwarddecomposition.HASCOViaFDAndBestFirstWithRandomCompletionsFactory;\r\nimport jaicore.planning.graphgenerators.task.tfd.TFDNode;\r\nimport jaicore.search.model.probleminputs.GeneralEvaluatedTraversalTree;\r\n\r\npublic class HASCOViaFDAndBestFirstWithRandomCompletionsTester extends HASCOTester<GeneralEvaluatedTraversalTree<TFDNode, String, Double>, TFDNode, String> {\r\n\r\n\t@Override\r\n\tpublic HASCOFactory<GeneralEvaluatedTraversalTree<TFDNode, String, Double>, TFDNode, String, Double> getFactory() {\r\n\t\tHASCOViaFDAndBestFirstWithRandomCompletionsFactory factory = new HASCOViaFDAndBestFirstWithRandomCompletionsFactory();\r\n\t\tfactory.setVisualizationEnabled(true);\r\n\t\treturn factory;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7183233499526978, "alphanum_fraction": 0.7192814350128174, "avg_line_length": 24.613496780395508, "blob_id": "b360c804aad3bb4c6c3d41b9330324de30f16643", "content_id": "6a7209562421a72d87f37cd3c775b2d13b3b328f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4175, "license_type": "no_license", "max_line_length": 87, "num_lines": 163, "path": "/JAICore/jaicore-search/src/jaicore/search/gui/dataSupplier/NodeExpansionSupplier.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.gui.dataSupplier;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.google.common.eventbus.EventBus;\nimport com.google.common.eventbus.Subscribe;\n\nimport jaicore.graphvisualizer.events.controlEvents.ControlEvent;\nimport jaicore.graphvisualizer.events.controlEvents.IsLiveEvent;\nimport jaicore.graphvisualizer.events.controlEvents.NodePushed;\nimport jaicore.graphvisualizer.events.controlEvents.ResetEvent;\nimport jaicore.graphvisualizer.events.controlEvents.StepEvent;\nimport jaicore.graphvisualizer.events.graphEvents.GraphEvent;\nimport jaicore.graphvisualizer.events.graphEvents.GraphInitializedEvent;\nimport jaicore.graphvisualizer.events.graphEvents.NodeReachedEvent;\nimport jaicore.graphvisualizer.events.graphEvents.NodeTypeSwitchEvent;\nimport jaicore.graphvisualizer.gui.dataSupplier.ISupplier;\nimport jaicore.search.model.travesaltree.Node;\n\n/**\n * A class which works similar to the recorder.\n * In contrast to the recorder the sent graphsEvents are filtered by the branch.\n * @author jkoepe\n *\n */\npublic class NodeExpansionSupplier implements ISupplier {\n\t\n\t// variabled\n\tstatic int i = 0;\n\t\n\tpublic EventBus eventbus;\n\t\n\tprivate List<GraphEvent> events;\n\t\n\tprivate Node currentRoot;\n\t\n\tprivate int index;\n\n\tprivate boolean live;\n\t\n\t/**\n\t * Creates a new NodeExpansionSupplier\n\t */\n\tpublic NodeExpansionSupplier() {\n\t\tsuper();\n\t\tthis.eventbus = new EventBus();\n\t\tevents = new ArrayList<GraphEvent>();\n\t\tcurrentRoot = null;\n\t\tindex = 0;\n\t\tthis.live = false;\n\t}\n\n\t\n\t@Override\n\tpublic void registerListener(Object listener) {\n\t\teventbus.register(listener);\n\t}\n\n\t@Override\n\t@Subscribe\n\tpublic void receiveGraphEvent(GraphEvent event) {\n\t\tthis.events.add(event);\n\t}\n\n\t@Override\n\t@Subscribe\n\tpublic void receiveControlEvent(ControlEvent event) {\n\t\t\n\t\t// if a node was pushed, the branch out of this node is the last pushed node\n\t\tif(event instanceof NodePushed) {\n\t\t\tthis.currentRoot = (Node) ((NodePushed) event).getNode();\n\t\t\tSystem.out.println(((NodePushed) event).getNode());\n\t\t\tshow(0);\n\t\t}\n\n\t\tif (event instanceof IsLiveEvent)\n\t\t\tthis.live = ((IsLiveEvent) event).isLive();\n\n\t\tif(!live && event instanceof StepEvent)\n\t\t\tif(((StepEvent) event).forward()) {\n\t\t\t\tindex += ((StepEvent) event).getSteps();\n\t\t\t\tif(currentRoot != null)\n\t\t\t\t\tshow(index-((StepEvent) event).getSteps());\n\t\t\t}\n\t\tif (event instanceof ResetEvent) {\n\t\t\tthis.index = 0;\n\t\t}\n\t}\n\n\t@Override\n\tpublic JsonNode getSerialization() {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\t\n\t \n/**\n * shows the branch and post every event till the current index given by the controller\n * @param start\n */\n\tprivate void show(int start){\n\t\t\n\t\tfor (int i = start; i < index; i++) {\n\t\t\tif(eventContains(currentRoot, events.get(i))) {\n\t\t\t\tif(events.get(i) instanceof NodeReachedEvent) {\n\t\t\t\t\tNodeReachedEvent event = (NodeReachedEvent) events.get(i);\n\t\t\t\t\tif(event.getNode().equals(currentRoot)) {\n\t\t\t\t\t\tthis.eventbus.post(new GraphInitializedEvent(event.getNode()));\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis.eventbus.post(events.get(i));\n\t\t\t}\n\t\t}\n\t}\n\t\n\t/**\n\t * Check if the branch contains a node\n\t * @param root\n\t * @param node\n\t * @return\n\t */\n\tprivate boolean contains(Node root, Node node) {\n\t\tif(root.equals(node))\n\t\t\treturn true;\n\t\telse {\n\t\t\tif(node.getParent()== null)\n\t\t\t\treturn false;\n\t\t\telse\n\t\t\t\treturn contains(root, node.getParent());\n\t\t}\n\t}\n\t\n\t/**\n\t * checks if the node is contained in an event\n\t * @param root\n\t * @param event\n\t * @return\n\t */\n\tprivate boolean eventContains(Node root, GraphEvent event ) {\n\t\tif(event instanceof GraphInitializedEvent) {\n\t\t\tif(((GraphInitializedEvent) event).getRoot() instanceof Node)\n\t\t\t\treturn contains(root, (Node) ((GraphInitializedEvent) event).getRoot());\n\t\t\t\n\t\t}\n\t\t\n\t\tif(event instanceof NodeReachedEvent) {\n\t\t\tif(((NodeReachedEvent) event).getNode() instanceof Node) {\n\t\t\t\treturn contains(root, (Node) ((NodeReachedEvent) event).getNode());\n\t\t\t}\n\t\t\t\n\t\t}\n\t\tif(event instanceof NodeTypeSwitchEvent) {\n\t\t\tif(((NodeTypeSwitchEvent) event).getNode() instanceof Node)\n\t\t\t\treturn contains(root, (Node) ((NodeTypeSwitchEvent) event).getNode());\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\n}\n" }, { "alpha_fraction": 0.7206099629402161, "alphanum_fraction": 0.7225774526596069, "avg_line_length": 28.463768005371094, "blob_id": "bfbb0d5e7a9f1b7488abc86d9020328a66dc5eaa", "content_id": "bb3816b62e8723f7f7c10d67c389352939ce2d8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2033, "license_type": "no_license", "max_line_length": 160, "num_lines": 69, "path": "/JAICore/jaicore-planning/src/jaicore/planning/model/conditional/CEOperation.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.model.conditional;\n\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\nimport jaicore.basic.StringUtil;\nimport jaicore.logic.fol.structure.CNFFormula;\nimport jaicore.logic.fol.structure.Monom;\nimport jaicore.logic.fol.structure.VariableParam;\nimport jaicore.planning.model.core.Operation;\n\n@SuppressWarnings(\"serial\")\npublic class CEOperation extends Operation {\n\n\tprivate final Map<CNFFormula, Monom> addLists, deleteLists;\n\n\tpublic CEOperation(String name, String params, Monom precondition, Map<CNFFormula, Monom> addLists, Map<CNFFormula, Monom> deleteLists) {\n\t\tthis(name, Arrays.asList(StringUtil.explode(params, \",\")).stream().map(s -> new VariableParam(s.trim())).collect(Collectors.toList()), precondition, addLists,\n\t\t\t\tdeleteLists);\n\t}\n\n\tpublic CEOperation(String name, List<VariableParam> params, Monom precondition, Map<CNFFormula, Monom> addLists, Map<CNFFormula, Monom> deleteLists) {\n\t\tsuper(name, params, precondition);\n\t\tthis.addLists = addLists;\n\t\tthis.deleteLists = deleteLists;\n\t}\n\n\tpublic Map<CNFFormula, Monom> getAddLists() {\n\t\treturn addLists;\n\t}\n\n\tpublic Map<CNFFormula, Monom> getDeleteLists() {\n\t\treturn deleteLists;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = super.hashCode();\n\t\tresult = prime * result + ((addLists == null) ? 0 : addLists.hashCode());\n\t\tresult = prime * result + ((deleteLists == null) ? 0 : deleteLists.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (!super.equals(obj))\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tCEOperation other = (CEOperation) obj;\n\t\tif (addLists == null) {\n\t\t\tif (other.addLists != null)\n\t\t\t\treturn false;\n\t\t} else if (!addLists.equals(other.addLists))\n\t\t\treturn false;\n\t\tif (deleteLists == null) {\n\t\t\tif (other.deleteLists != null)\n\t\t\t\treturn false;\n\t\t} else if (!deleteLists.equals(other.deleteLists))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n}\n" }, { "alpha_fraction": 0.6424624919891357, "alphanum_fraction": 0.6606156229972839, "avg_line_length": 23.326923370361328, "blob_id": "0657c802aacab8d6b6e9723d9bde6fb38415df3d", "content_id": "a6ecf38f1698207a4f34c606ba46c5acc9dea4f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Gradle", "length_bytes": 1267, "license_type": "no_license", "max_line_length": 97, "num_lines": 52, "path": "/softwareconfiguration/mlplan/build.gradle", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "plugins {\n\tid 'eclipse-wtp'\n}\n\nsourceSets {\n main {\n java {\n srcDir 'src'\n }\n resources {\n \tsrcDir 'conf'\n \tsrcDir 'resources'\n \t}\n }\n test {\n\t\tjava {\n\t\t\tsrcDir 'test'\n\t\t\tsrcDir 'examples'\n\t\t}\n }\n}\n\ndependencies {\n \t// basic dependencies\n\tcompile project(':hasco')\n\n\t// JAICore dependencies\n\tcompile project(':JAICore:jaicore-logic') \n\tcompile project(':JAICore:jaicore-basic')\n\tcompile project(':JAICore:jaicore-graph')\n\tcompile project(':JAICore:jaicore-planning')\n\tcompile project(':JAICore:jaicore-search')\n\tcompile project(':JAICore:jaicore-ml')\n\n\n\t// OWL API\n\tcompile 'net.sourceforge.owlapi:owlapi-distribution:5.1.0'\n\t// TreeMiner\n\tcompile 'com.github.helegraf:TreeMiner:-SNAPSHOT'\n\t// linear algebra\n\tcompile group: 'org.nd4j', name: 'nd4j-native-platform', version: '0.9.1'\n\tcompile group: 'org.nd4j', name: 'nd4j-api', version: '0.9.1'\n\t\n\t// gradient descent (but forbid that the guy uses his log4j-stuff, which we will bride to slf4j)\n\tcompile ('de.jungblut.common:thomasjungblut-common:1.1') {\n\t exclude group: 'log4j'\n\t exclude group: 'org.slf4j'\n\t exclude group: 'org.apache.logging.log4j', module: 'log4j-core'\n\t exclude group: 'org.apache.logging.log4j', module: 'log4j-api'\n\t}\n\t\n}\n\n\n" }, { "alpha_fraction": 0.7176724076271057, "alphanum_fraction": 0.7198275923728943, "avg_line_length": 21.45161247253418, "blob_id": "390ca4cabd9c2917cee71b72b5d61cd323f9b3a4", "content_id": "e56a444dbe278543ff1be144b1416062a860a0f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1392, "license_type": "no_license", "max_line_length": 101, "num_lines": 62, "path": "/JAICore/jaicore-graphvisualizer/src/jaicore/graphvisualizer/gui/dataVisualizer/HTMLVisualizer.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.graphvisualizer.gui.dataVisualizer;\n\nimport javax.swing.JLabel;\nimport javax.swing.JScrollPane;\nimport javax.swing.SwingConstants;\nimport javax.swing.SwingUtilities;\n\nimport com.google.common.eventbus.Subscribe;\n\nimport jaicore.graphvisualizer.events.misc.HTMLEvent;\nimport javafx.embed.swing.SwingNode;\nimport javafx.scene.Node;\n\npublic class HTMLVisualizer implements IVisualizer {\n\n\tSwingNode node;\n\tJLabel label;\n\n\tpublic HTMLVisualizer() {\n\t\tthis.label = new JLabel();\n\t\tthis.label.setText(\"<html></html>\");\n\t\tthis.label.setVerticalAlignment(SwingConstants.TOP);\n\t\tthis.node = new SwingNode();\n\t\tfillSwingnode(node);\n\n\t}\n\n\tprivate void fillSwingnode(SwingNode node) {\n\t\tJScrollPane pane = new JScrollPane();\n\t\tpane.setViewportView(label);\n\t\tSwingUtilities.invokeLater(() -> {\n\t\t\tnode.setContent(pane);\n\t\t});\n\t}\n\n\t@Override\n\tpublic Node getVisualization() {\n\t\treturn this.node;\n// return null;\n\t}\n\n\t@Override\n\tpublic String getSupplier() {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic String getTitle() {\n\t\treturn \"HTML\";\n\t}\n\n\t@Subscribe\n\tpublic void receiveData(HTMLEvent html) {\n\t\tStringBuilder sb = new StringBuilder();\n//\t\t\t\t\t\tsb.append(\"<html><div style='padding: 5px; background: #ffffcc; border: 1px solid black;'>\");\n\t\tsb.append(\"<html><div style='padding: 5px;'>\");\n\t\tsb.append(html.getText());\n\t\tsb.append(\"</div></html>\");\n\n\t\tlabel.setText(sb.toString());\n\t}\n}\n" }, { "alpha_fraction": 0.6988783478736877, "alphanum_fraction": 0.7006039619445801, "avg_line_length": 25.363636016845703, "blob_id": "e30931d406e3652588f91952ac3246db53c72ef6", "content_id": "93aaaf0eb031362192c98a0064f45e447ccf52fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1159, "license_type": "no_license", "max_line_length": 94, "num_lines": 44, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/bestfirst/nodeevaluation/SkippingNodeEvaluator.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.bestfirst.nodeevaluation;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Random;\n\nimport jaicore.search.model.travesaltree.Node;\n\npublic class SkippingNodeEvaluator<T,V extends Comparable<V>> implements INodeEvaluator<T,V> {\n\n\tprivate final INodeEvaluator<T,V> actualEvaluator;\n\tprivate final Random rand;\n\tprivate final float coin;\n\tprivate final Map<Node<T,?>, V> fCache = new HashMap<>();\n\n\tpublic SkippingNodeEvaluator(INodeEvaluator<T,V> actualEvaluator, Random rand, float coin) {\n\t\tsuper();\n\t\tthis.actualEvaluator = actualEvaluator;\n\t\tthis.rand = rand;\n\t\tthis.coin = coin;\n\t}\n\n\t@Override\n\tpublic V f(Node<T,?> node) throws Exception {\n\t\tint depth = node.path().size() - 1;\n\t\tif (!fCache.containsKey(node)) {\n\t\t\tif (depth == 0) {\n\t\t\t\tfCache.put(node, actualEvaluator.f(node));\n\t\t\t} else {\n\t\t\t\tif (rand.nextFloat() >= coin) {\n\t\t\t\t\tfCache.put(node, actualEvaluator.f(node));\n\t\t\t\t} else {\n\t\t\t\t\tfCache.put(node, f(node.getParent()));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn fCache.get(node);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"SkippingEvaluator [actualEvaluator=\" + actualEvaluator + \"]\";\n\t}\n}" }, { "alpha_fraction": 0.510506808757782, "alphanum_fraction": 0.52163165807724, "avg_line_length": 22.515151977539062, "blob_id": "778ca324a056c507e2d97d00aab4228bde739696", "content_id": "cbd946762bcff280a1b6b78d59f5961ddd1d0d93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 809, "license_type": "no_license", "max_line_length": 80, "num_lines": 33, "path": "/JAICore/jaicore-basic/src/jaicore/basic/MathExt.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.basic;\r\n\r\nimport java.util.HashSet;\r\nimport java.util.Set;\r\n\r\npublic abstract class MathExt {\r\n public static long binomial(int n, int k) {\r\n if (k>n-k)\r\n k=n-k;\r\n \r\n long b=1;\r\n for (int i=1, m=n; i<=k; i++, m--)\r\n b=b*m/i;\r\n return b;\r\n }\r\n \r\n public static Set<Integer> getIntegersFromTo(int from, int to) {\r\n \tSet<Integer> set = new HashSet<>();\r\n \tfor (int i = from; i <= to; i++)\r\n \t\tset.add(i);\r\n \treturn set;\r\n }\r\n \r\n public static int doubleFactorial(int k) {\r\n \tif (k <= 0)\r\n \t\treturn 1;\r\n \treturn k * doubleFactorial(k - 2);\r\n }\r\n \r\n public static double round(double d, int precision) {\r\n \treturn (Math.round(d * Math.pow(10, precision)) / Math.pow(10, precision));\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.8305470943450928, "alphanum_fraction": 0.8305470943450928, "avg_line_length": 45.85454559326172, "blob_id": "b2653b026f681a975f359bf433a5327991d18fb0", "content_id": "45ff98231d9edce197c53fe076767bfdf4c65182", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2632, "license_type": "no_license", "max_line_length": 278, "num_lines": 55, "path": "/JAICore/jaicore-search/src/jaicore/search/problemtransformers/GraphSearchProblemInputToGeneralEvaluatedTraversalTreeViaRDFS.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.problemtransformers;\r\n\r\nimport java.util.Random;\r\nimport java.util.function.Predicate;\r\n\r\nimport jaicore.basic.algorithm.AlgorithmProblemTransformer;\r\nimport jaicore.search.algorithms.standard.bestfirst.nodeevaluation.AlternativeNodeEvaluator;\r\nimport jaicore.search.algorithms.standard.bestfirst.nodeevaluation.INodeEvaluator;\r\nimport jaicore.search.algorithms.standard.bestfirst.nodeevaluation.RandomCompletionBasedNodeEvaluator;\r\nimport jaicore.search.model.probleminputs.GeneralEvaluatedTraversalTree;\r\nimport jaicore.search.model.probleminputs.GraphSearchProblemInput;\r\n\r\npublic class GraphSearchProblemInputToGeneralEvaluatedTraversalTreeViaRDFS<N, A, V extends Comparable<V>>\r\n\t\timplements AlgorithmProblemTransformer<GraphSearchProblemInput<N, A, V>, GeneralEvaluatedTraversalTree<N, A, V>> {\r\n\r\n\tprivate final INodeEvaluator<N, V> preferredNodeEvaluator;\r\n\tprivate final Predicate<N> prioritizedNodesInRandomCompletion;\r\n\tprivate final int seed;\r\n\tprivate final int numSamples;\r\n\tprivate final int timeoutForSingleCompletionEvaluationInMS;\r\n\tprivate final int timeoutForNodeEvaluationInMS;\r\n\r\n\tpublic GraphSearchProblemInputToGeneralEvaluatedTraversalTreeViaRDFS(INodeEvaluator<N, V> preferredNodeEvaluator, Predicate<N> preferredNodeEvaluatorForRandomCompletion, int seed, int numSamples, int timeoutForSingleCompletionEvaluationInMS, int timeoutForNodeEvaluationInMS) {\r\n\t\tsuper();\r\n\t\tthis.preferredNodeEvaluator = preferredNodeEvaluator;\r\n\t\tthis.prioritizedNodesInRandomCompletion = preferredNodeEvaluatorForRandomCompletion;\r\n\t\tthis.seed = seed;\r\n\t\tthis.numSamples = numSamples;\r\n\t\tthis.timeoutForSingleCompletionEvaluationInMS = timeoutForSingleCompletionEvaluationInMS;\r\n\t\tthis.timeoutForNodeEvaluationInMS = timeoutForNodeEvaluationInMS;\r\n\t}\r\n\r\n\tpublic INodeEvaluator<N, V> getPreferredNodeEvaluator() {\r\n\t\treturn preferredNodeEvaluator;\r\n\t}\r\n\r\n\tpublic Predicate<N> getPrioritizedNodePredicatesForRandomCompletion() {\r\n\t\treturn prioritizedNodesInRandomCompletion;\r\n\t}\r\n\r\n\tpublic int getSeed() {\r\n\t\treturn seed;\r\n\t}\r\n\r\n\tpublic int getNumSamples() {\r\n\t\treturn numSamples;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic GeneralEvaluatedTraversalTree<N, A, V> transform(GraphSearchProblemInput<N, A, V> problem) {\r\n\t\tRandomCompletionBasedNodeEvaluator<N, V> rc = new RandomCompletionBasedNodeEvaluator<>(new Random(seed), numSamples, problem.getPathEvaluator(), timeoutForSingleCompletionEvaluationInMS, timeoutForNodeEvaluationInMS, prioritizedNodesInRandomCompletion);\r\n\t\treturn new GeneralEvaluatedTraversalTree<>(problem.getGraphGenerator(), new AlternativeNodeEvaluator<>(preferredNodeEvaluator, rc));\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.6991150379180908, "alphanum_fraction": 0.6991150379180908, "avg_line_length": 29.38888931274414, "blob_id": "dd18a0bc36a7c16e66261e0bbd24e59f898c41e5", "content_id": "cc715e9282d69a74e5ab66f5f5c5eea350e566b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 565, "license_type": "no_license", "max_line_length": 94, "num_lines": 18, "path": "/JAICore/jaicore-graph/src/jaicore/graph/IGraphAlgorithm.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.graph;\r\n\r\nimport jaicore.basic.algorithm.IAlgorithm;\r\n\r\n/**\r\n * \r\n * @author fmohr\r\n *\r\n * @param <I> class of problem inputs\r\n * @param <O> class of solution candidates and returned solution\r\n * @param <P> class of the semantic problem definition established between elements of I and O\r\n * @param <N> class of nodes of the graph the algorithm works on\r\n * @param <A> class of the arcs the algorithm works on\r\n * @param <L> class that all listeners must belong to\r\n */\r\npublic interface IGraphAlgorithm<I, O, N, A> extends IAlgorithm<I, O> {\r\n\r\n}\r\n" }, { "alpha_fraction": 0.6737967729568481, "alphanum_fraction": 0.6737967729568481, "avg_line_length": 23.933332443237305, "blob_id": "7cbad66ce6da7b54e37c5c7a060e46e83dc44aa5", "content_id": "c7bcf8885467c2232e32082bd4348c337a654ffb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 374, "license_type": "no_license", "max_line_length": 76, "num_lines": 15, "path": "/JAICore/jaicore-search/src/jaicore/search/structure/graphgenerator/PathGoalTester.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.structure.graphgenerator;\n\nimport java.util.List;\n\npublic interface PathGoalTester<T> extends GoalTester<T> {\n\t\n\t/**\n\t * Check if the current node is a goal for the problem.\n\t * \n\t * @param node\n\t * The node to check.\n\t * @return <code>true</code> if it is a goal, <code>false</else> otherwise.\n\t */\n\tpublic boolean isGoal(List<T> node);\n}\n" }, { "alpha_fraction": 0.7236180901527405, "alphanum_fraction": 0.7236180901527405, "avg_line_length": 17.899999618530273, "blob_id": "9f5e2afa50112f118363308fcdbfe48ab110aa39", "content_id": "cf1d4490c2df6c5f4855f08dd5ba794123cb3c91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 398, "license_type": "no_license", "max_line_length": 56, "num_lines": 20, "path": "/JAICore/jaicore-concurrent/src/jaicore/concurrent/NamedTimerTask.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.concurrent;\r\n\r\nimport java.util.TimerTask;\r\n\r\npublic abstract class NamedTimerTask extends TimerTask {\r\n\tprivate String descriptor;\r\n\r\n\tpublic NamedTimerTask(String descriptor) {\r\n\t\tsuper();\r\n\t\tthis.descriptor = descriptor;\r\n\t}\r\n\r\n\tpublic String getDescriptor() {\r\n\t\treturn descriptor;\r\n\t}\r\n\r\n\tpublic void setDescriptor(String descriptor) {\r\n\t\tthis.descriptor = descriptor;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6989679932594299, "alphanum_fraction": 0.6993178129196167, "avg_line_length": 41.664180755615234, "blob_id": "83b5c7f4392e61a70fefa8fc0400f5c90fe1428d", "content_id": "69dae1e0051aeb4dae3b15c288511cbe5574913f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5717, "license_type": "no_license", "max_line_length": 179, "num_lines": 134, "path": "/JAICore/jaicore-basic/src/jaicore/basic/kvstore/KVStoreUtil.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.basic.kvstore;\n\nimport jaicore.basic.ValueUtil;\n\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\npublic class KVStoreUtil {\n\n public static String kvStoreCollectionToLaTeXTable(final Collection<SimpleKVStore> kvStoreCollection, final String rowIndex, final String columnIndex) {\n StringBuilder sb = new StringBuilder();\n Table<String> table = new Table<>();\n for (SimpleKVStore store : kvStoreCollection) {\n String rowValue = store.getValueAsString(rowIndex).replaceAll(\"\\\\_\", \"\\\\\\\\_\");\n String columnValue = store.getValueAsString(columnIndex).replaceAll(\"\\\\_\", \"\\\\\\\\_\");\n String tableEntry = ValueUtil.valueToString(store.getValueAsDouble(\"meanAccuracy\"), 2) + \"+-\" + ValueUtil.valueToString(store.getValueAsDouble(\"stdAccuracy\"), 2);\n table.addEntry(columnValue, rowValue, tableEntry);\n }\n sb.append(table.toLaTeX());\n return sb.toString();\n }\n\n public static String kvStoreCollectionToLaTeXTable(final Collection<SimpleKVStore> kvStoreCollection, final String rowIndex, final String columnIndex,\n final String cellFormatting) {\n\n StringBuilder sb = new StringBuilder();\n Table<String> table = new Table<>();\n for (SimpleKVStore store : kvStoreCollection) {\n\n String[] cellFormattingSplit = store.getValueAsString(cellFormatting).split(\"#\");\n List<String> cleanedCellFormatting = Arrays.stream(cellFormattingSplit).filter(x -> !x.equals(\"\")).collect(Collectors.toList());\n\n String rowValue = store.getValueAsString(rowIndex).replaceAll(\"\\\\_\", \"\\\\\\\\_\");\n String columnValue = store.getValueAsString(columnIndex).replaceAll(\"\\\\_\", \"\\\\\\\\_\");\n\n StringBuilder tableEntryBuilder = new StringBuilder();\n for (String cellKey : cleanedCellFormatting) {\n if (!store.containsKey(cellKey)) {\n tableEntryBuilder.append(cellKey);\n } else {\n tableEntryBuilder.append(store.getValueAsString(cellKey));\n }\n }\n\n table.addEntry(columnValue, rowValue, tableEntryBuilder.toString());\n }\n sb.append(table.toLaTeX());\n return sb.toString();\n }\n\n public static String kvStoreCollectionToLaTeXTable(final Collection<SimpleKVStore> kvStoreCollection, final String rowIndex, final String columnIndex,\n final String cellFormatting, final String missingEntry) {\n\n StringBuilder sb = new StringBuilder();\n Table<String> table = new Table<>();\n for (SimpleKVStore store : kvStoreCollection) {\n\n String[] cellFormattingSplit = store.getValueAsString(cellFormatting).split(\"#\");\n List<String> cleanedCellFormatting = Arrays.stream(cellFormattingSplit).filter(x -> !x.equals(\"\")).collect(Collectors.toList());\n\n String rowValue = store.getValueAsString(rowIndex).replaceAll(\"\\\\_\", \"\\\\\\\\_\");\n String columnValue = store.getValueAsString(columnIndex).replaceAll(\"\\\\_\", \"\\\\\\\\_\");\n\n StringBuilder tableEntryBuilder = new StringBuilder();\n for (String cellKey : cleanedCellFormatting) {\n if (!store.containsKey(cellKey)) {\n tableEntryBuilder.append(cellKey);\n } else {\n tableEntryBuilder.append(store.getValueAsString(cellKey));\n }\n }\n\n table.addEntry(columnValue, rowValue, tableEntryBuilder.toString());\n }\n sb.append(table.toLaTeX(missingEntry));\n return sb.toString();\n }\n\n public static String kvStoreCollectionToCSVTable(final Collection<SimpleKVStore> kvStoreCollection, final String rowIndex, final String columnIndex, final String cellFormatting,\n final String standardValue) {\n\n StringBuilder sb = new StringBuilder();\n Table<String> table = new Table<>();\n for (SimpleKVStore store : kvStoreCollection) {\n\n String[] cellFormattingSplit = store.getValueAsString(cellFormatting).split(\"#\");\n List<String> cleanedCellFormatting = Arrays.stream(cellFormattingSplit).filter(x -> !x.equals(\"\")).collect(Collectors.toList());\n\n String rowValue = store.getValueAsString(rowIndex).replaceAll(\"\\\\_\", \"\\\\\\\\_\");\n String columnValue = store.getValueAsString(columnIndex).replaceAll(\"\\\\_\", \"\\\\\\\\_\");\n\n StringBuilder tableEntryBuilder = new StringBuilder();\n for (String cellKey : cleanedCellFormatting) {\n if (!store.containsKey(cellKey)) {\n tableEntryBuilder.append(cellKey);\n } else {\n tableEntryBuilder.append(store.getValueAsString(cellKey));\n }\n }\n\n table.addEntry(columnValue, rowValue, tableEntryBuilder.toString());\n }\n sb.append(table.toCSV(standardValue));\n return sb.toString();\n }\n\n public static Table<String> kvStoreCollectionToTable(final Collection<SimpleKVStore> kvStoreCollection, final String rowIndex, final String columnIndex,\n final String cellFormatting, final String standardValue) {\n Table<String> table = new Table<>();\n for (SimpleKVStore store : kvStoreCollection) {\n\n String[] cellFormattingSplit = store.getValueAsString(cellFormatting).split(\"#\");\n List<String> cleanedCellFormatting = Arrays.stream(cellFormattingSplit).filter(x -> !x.equals(\"\")).collect(Collectors.toList());\n\n String rowValue = store.getValueAsString(rowIndex).replaceAll(\"\\\\_\", \"\\\\\\\\_\");\n String columnValue = store.getValueAsString(columnIndex).replaceAll(\"\\\\_\", \"\\\\\\\\_\");\n\n StringBuilder tableEntryBuilder = new StringBuilder();\n for (String cellKey : cleanedCellFormatting) {\n if (!store.containsKey(cellKey)) {\n tableEntryBuilder.append(cellKey);\n } else {\n tableEntryBuilder.append(store.getValueAsString(cellKey));\n }\n }\n\n table.addEntry(columnValue, rowValue, tableEntryBuilder.toString());\n }\n return table;\n }\n\n}\n" }, { "alpha_fraction": 0.781731903553009, "alphanum_fraction": 0.7826809287071228, "avg_line_length": 45.83333206176758, "blob_id": "75223eee0f01d96fa21ba0c77b1e1a6a78923eea", "content_id": "ba6ccd8a9ed5bdae955c1e080147adbc8cd84db3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4215, "license_type": "no_license", "max_line_length": 155, "num_lines": 90, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/uncertainty/UncertaintyORGraphSearchFactory.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.uncertainty;\n\nimport java.util.PriorityQueue;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport jaicore.search.algorithms.standard.bestfirst.BestFirst;\nimport jaicore.search.algorithms.standard.bestfirst.BestFirstFactory;\nimport jaicore.search.algorithms.standard.uncertainty.explorationexploitationsearch.BasicClockModelPhaseLengthAdjuster;\nimport jaicore.search.algorithms.standard.uncertainty.explorationexploitationsearch.BasicExplorationCandidateSelector;\nimport jaicore.search.algorithms.standard.uncertainty.explorationexploitationsearch.IPhaseLengthAdjuster;\nimport jaicore.search.algorithms.standard.uncertainty.explorationexploitationsearch.UncertaintyExplorationOpenSelection;\nimport jaicore.search.algorithms.standard.uncertainty.paretosearch.ParetoNode;\nimport jaicore.search.algorithms.standard.uncertainty.paretosearch.ParetoSelection;\nimport jaicore.search.model.probleminputs.UncertainlyEvaluatedTraversalTree;\n\npublic class UncertaintyORGraphSearchFactory<N, A, V extends Comparable<V>> extends BestFirstFactory<UncertainlyEvaluatedTraversalTree<N, A, V>, N, A, V> {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(UncertaintyORGraphSearchFactory.class);\n\t\n\tprivate OversearchAvoidanceConfig<N, V> oversearchAvoidanceConfig;\n\t\n\t@Override\n\tpublic BestFirst<UncertainlyEvaluatedTraversalTree<N, A, V>, N, A, V> getAlgorithm() {\n\t\tif (oversearchAvoidanceConfig == null)\n\t\t\tthrow new IllegalStateException(\"Uncertainty Config has not been set yet.\");\n\n\t\t/* let the best first factory configure general aspects of the best first search */\n\t\tBestFirst<UncertainlyEvaluatedTraversalTree<N, A, V>, N, A, V> search = super.getAlgorithm();\n\t\t\n\t\t/* now set uncertainty-specific behavior */\n\t\tswitch (oversearchAvoidanceConfig.getOversearchAvoidanceMode()) {\n\t\t\tcase NONE:\n\t\t\t\tlogger.warn(\"Usage of OversearchAvoidanceMode.NONE is deprecated! Use StandardBestFirst search instead.\");\n\t\t\t\tbreak;\n\t\t\tcase TWO_PHASE_SELECTION:\n\t\t\t\tif (oversearchAvoidanceConfig.getAdjustPhaseLengthsDynamically()) {\n\t\t\t\t\tsearch.setOpen(new UncertaintyExplorationOpenSelection<N, V>(\n\t\t\t\t\t\t\toversearchAvoidanceConfig.getTimeout(),\n\t\t\t\t\t\t\toversearchAvoidanceConfig.getInterval(),\n\t\t\t\t\t\t\toversearchAvoidanceConfig.getExploitationScoreThreshold(),\n\t\t\t\t\t\t\toversearchAvoidanceConfig.getExplorationUncertaintyThreshold(),\n\t\t\t\t\t\t\tnew BasicClockModelPhaseLengthAdjuster(),\n\t\t\t\t\t\t\toversearchAvoidanceConfig.getSolutionDistanceMetric(),\n\t\t\t\t\t\t\tnew BasicExplorationCandidateSelector<N, V>(oversearchAvoidanceConfig.getMinimumSolutionDistanceForExploration())\n\t\t\t\t\t));\n\t\t\t\t} else {\n\t\t\t\t\tsearch.setOpen(new UncertaintyExplorationOpenSelection<N, V>(\n\t\t\t\t\t\t\toversearchAvoidanceConfig.getTimeout(),\n\t\t\t\t\t\t\toversearchAvoidanceConfig.getInterval(),\n\t\t\t\t\t\t\toversearchAvoidanceConfig.getExploitationScoreThreshold(),\n\t\t\t\t\t\t\toversearchAvoidanceConfig.getExplorationUncertaintyThreshold(),\n\t\t\t\t\t\t\tnew IPhaseLengthAdjuster() {\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\tpublic int[] getInitialPhaseLengths(int interval) {\n\t\t\t\t\t\t\t\t\treturn new int[] {interval / 2, interval - (interval / 2)};\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\tpublic int[] adjustPhaseLength(int currentExplorationLength, int currentExploitationLength, long passedTime,\n\t\t\t\t\t\t\t\t\t\tlong timeout) {\n\t\t\t\t\t\t\t\t\treturn new int[] {currentExplorationLength, currentExploitationLength};\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\toversearchAvoidanceConfig.getSolutionDistanceMetric(),\n\t\t\t\t\t\t\tnew BasicExplorationCandidateSelector<N, V>(oversearchAvoidanceConfig.getMinimumSolutionDistanceForExploration())\n\t\t\t\t\t));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase PARETO_FRONT_SELECTION:\n\t\t\t\tPriorityQueue<ParetoNode<N, V>> pareto = new PriorityQueue<>(oversearchAvoidanceConfig.getParetoComperator());\n\t\t\t\tsearch.setOpen(new ParetoSelection<>(pareto));\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new UnsupportedOperationException(\"Mode \" + oversearchAvoidanceConfig.getOversearchAvoidanceMode() + \" is currently not supported.\");\n\t\t}\n\t\t\n\t\treturn search;\n\t}\n\n\tpublic OversearchAvoidanceConfig<N, V> getConfig() {\n\t\treturn this.oversearchAvoidanceConfig;\n\t}\n\n\tpublic void setConfig(OversearchAvoidanceConfig<N, V> config) {\n\t\tthis.oversearchAvoidanceConfig = config;\n\t}\n}\n" }, { "alpha_fraction": 0.8228403925895691, "alphanum_fraction": 0.8257686495780945, "avg_line_length": 46.78571319580078, "blob_id": "a2ab9f890ec4c9e16454997701b20b8934aa9761", "content_id": "62dab8b643783b9c1436bda9fbbfd0ec489b0ff7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 683, "license_type": "no_license", "max_line_length": 208, "num_lines": 14, "path": "/JAICore/jaicore-search/src/jaicore/search/problemtransformers/GraphSearchProblemInputToUninformedGeneralEvaluatedTraversalTree.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.problemtransformers;\r\n\r\nimport jaicore.basic.algorithm.AlgorithmProblemTransformer;\r\nimport jaicore.search.model.probleminputs.GeneralEvaluatedTraversalTree;\r\nimport jaicore.search.model.probleminputs.GraphSearchProblemInput;\r\n\r\npublic class GraphSearchProblemInputToUninformedGeneralEvaluatedTraversalTree<N, A> implements AlgorithmProblemTransformer<GraphSearchProblemInput<N, A, Double>, GeneralEvaluatedTraversalTree<N, A, Double>> {\r\n\r\n\t@Override\r\n\tpublic GeneralEvaluatedTraversalTree<N, A, Double> transform(GraphSearchProblemInput<N, A, Double> problem) {\r\n\t\treturn new GeneralEvaluatedTraversalTree<>(problem.getGraphGenerator(), n -> 0.0);\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.8195121884346008, "alphanum_fraction": 0.8195121884346008, "avg_line_length": 27.285715103149414, "blob_id": "26383ac43eaf30c4138af85e35bafdcff0753196", "content_id": "1813098d428d75be31f6524f3327cf81ac0e9b85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 205, "license_type": "no_license", "max_line_length": 88, "num_lines": 7, "path": "/softwareconfiguration/hasco/src/hasco/optimizingfactory/BaseFactory.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package hasco.optimizingfactory;\r\n\r\nimport hasco.model.ComponentInstance;\r\n\r\npublic interface BaseFactory<T> {\r\n\tpublic T getComponentInstantiation(ComponentInstance groundComponent) throws Exception;\r\n}\r\n" }, { "alpha_fraction": 0.6605148315429688, "alphanum_fraction": 0.6653715372085571, "avg_line_length": 37.48598098754883, "blob_id": "005d324ea3f7603853bb499ef5c8a24b8d093cba", "content_id": "abd4ee905644320ad33abd5edebd71813681dd1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4118, "license_type": "no_license", "max_line_length": 468, "num_lines": 107, "path": "/softwareconfiguration/hasco/src/hasco/eventlogger/HASCOSQLEventLogger.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package hasco.eventlogger;\n\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.google.common.eventbus.Subscribe;\n\nimport jaicore.basic.SQLAdapter;\n\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.text.SimpleDateFormat;\nimport java.time.Instant;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport hasco.events.HASCORunStartedEvent;\nimport hasco.events.HASCORunTerminatedEvent;\nimport hasco.events.HASCOSolutionEvaluationEvent;\n\npublic class HASCOSQLEventLogger<T, V extends Comparable<V>> {\n\n private int runId;\n private final SQLAdapter sqlAdapter;\n\n public HASCOSQLEventLogger(final SQLAdapter sqlAdapter) {\n super();\n this.sqlAdapter = sqlAdapter;\n\n /* initialize tables if not existent */\n try {\n ResultSet rs = sqlAdapter.getResultsOfQuery(\"SHOW TABLES\");\n boolean haveRunTable = false;\n boolean haveEvaluationTable = false;\n while (rs.next()) {\n String tableName = rs.getString(1);\n if (tableName.equals(\"runs\")) {\n haveRunTable = true;\n } else if (tableName.equals(\"evaluations\")) {\n haveEvaluationTable = true;\n }\n }\n\n if (!haveRunTable) {\n System.out.println(\"Creating table for runs\");\n sqlAdapter.update(\n \"CREATE TABLE `runs` ( `run_id` int(8) NOT NULL AUTO_INCREMENT, `seed` int(20) NOT NULL, `timeout` int(10) NOT NULL, `CPUs` int(2) NOT NULL, `benchmark` varchar(200) COLLATE utf8_bin DEFAULT NULL, `run_started` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `run_terminated` timestamp NULL DEFAULT NULL, `solution` json DEFAULT NULL, `score` double DEFAULT NULL, PRIMARY KEY (`run_id`)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_bin\",\n new ArrayList<>());\n }\n if (!haveEvaluationTable) {\n System.out.println(\"Creating table for evaluations\");\n sqlAdapter.update(\n \"CREATE TABLE `evaluations` (\\r\\n\" + \" `evaluation_id` int(10) NOT NULL AUTO_INCREMENT,\\r\\n\" + \" `run_id` int(8) NOT NULL,\\r\\n\" + \" `composition` json NOT NULL,\\r\\n\"\n + \" `score` double NOT NULL,\\r\\n\" + \" PRIMARY KEY (`evaluation_id`)\\r\\n\" + \") ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_bin\",\n new ArrayList<>());\n }\n\n } catch (SQLException e) {\n e.printStackTrace();\n }\n }\n\n @Subscribe\n public void receiveRunStartedEvent(final HASCORunStartedEvent<T, V> event) {\n try {\n Map<String, String> map = new HashMap<>();\n map.put(\"seed\", \"\" + event.getSeed());\n map.put(\"timeout\", \"\" + event.getTimeout());\n map.put(\"CPUs\", \"\" + event.getNumberOfCPUS());\n map.put(\"benchmark\", event.getBenchmark().toString());\n this.runId = this.sqlAdapter.insert(\"runs\", map);\n } catch (Throwable e) {\n e.printStackTrace();\n }\n }\n\n @Subscribe\n public void receiveSolutionEvaluationEvent(final HASCOSolutionEvaluationEvent<T, V> solution) {\n try {\n Map<String, String> map = new HashMap<>();\n map.put(\"run_id\", \"\" + this.runId);\n ObjectMapper mapper = new ObjectMapper();\n String composition = mapper.writeValueAsString(solution.getComposition());\n map.put(\"composition\", composition);\n map.put(\"score\", solution.getScore().toString());\n this.sqlAdapter.insert(\"evaluations\", map);\n } catch (Throwable e) {\n e.printStackTrace();\n }\n }\n\n @Subscribe\n public void receiveRunTerminatedEvent(final HASCORunTerminatedEvent<T, V> event) {\n try {\n Map<String, String> valueMap = new HashMap<>();\n valueMap.put(\"solution\", \"\" + new ObjectMapper().writeValueAsString(event.getCompositionOfSolution()));\n valueMap.put(\"run_terminated\", new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\").format(Date.from(Instant.now())));\n valueMap.put(\"score\", event.getScore().toString());\n\n Map<String, String> conditionMap = new HashMap<>();\n conditionMap.put(\"run_id\", \"\" + this.runId);\n this.sqlAdapter.update(\"runs\", valueMap, conditionMap);\n } catch (Throwable e) {\n e.printStackTrace();\n }\n }\n}\n" }, { "alpha_fraction": 0.75713050365448, "alphanum_fraction": 0.75713050365448, "avg_line_length": 37.89655303955078, "blob_id": "638d799c00f71e42125bef428aafcb66e72bcf5d", "content_id": "348af186c2beb80112afe09f7702947944671758", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1157, "license_type": "no_license", "max_line_length": 250, "num_lines": 29, "path": "/JAICore/jaicore-search/src/jaicore/search/core/interfaces/IGraphSearch.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.core.interfaces;\r\n\r\nimport java.util.NoSuchElementException;\r\n\r\nimport jaicore.basic.algorithm.AlgorithmExecutionCanceledException;\r\nimport jaicore.graph.IGraphAlgorithm;\r\nimport jaicore.search.model.other.EvaluatedSearchGraphPath;\r\nimport jaicore.search.model.other.SearchGraphPath;\r\n\r\n/**\r\n * Graph search algorithms take a graph <VSrc, ESrc> that is given in the form of a graph generator and search it. Usually, the algorithm uses internal wrapper classes to represent edges and nodes, which is why there are additional generics for that.\r\n * \r\n * @author fmohr\r\n * \r\n * @param <I>\r\n * @param <O>\r\n * @param <NSrc>\r\n * @param <ASrc>\r\n * @param <NSearch>\r\n * @param <ASearch>\r\n * @param <L>\r\n */\r\npublic interface IGraphSearch<I, O, NSrc, ASrc, V extends Comparable<V>, NSearch, ASearch> extends IGraphAlgorithm<I, O, NSearch, ASearch> {\r\n\tpublic GraphGenerator<NSrc, ASrc> getGraphGenerator();\r\n\r\n\tpublic <U extends SearchGraphPath<NSrc, ASrc>> U nextSolution() throws InterruptedException, AlgorithmExecutionCanceledException, NoSuchElementException;\r\n\r\n\tpublic EvaluatedSearchGraphPath<NSrc, ASrc, V> getBestSeenSolution();\r\n}\r\n" }, { "alpha_fraction": 0.7998448610305786, "alphanum_fraction": 0.7998448610305786, "avg_line_length": 49.560001373291016, "blob_id": "eaf764b43d74b0d88aa69bd84d3833fc39e314eb", "content_id": "115508f7c2a215bf345adedef3ddcea484e4f3ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1289, "license_type": "no_license", "max_line_length": 249, "num_lines": 25, "path": "/JAICore/jaicore-search/test/jaicore/search/algorithms/standard/lds/LDSNQueenTester.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "//package jaicore.search.algorithms.standard.lds;\r\n//\r\n//import jaicore.basic.algorithm.AlgorithmProblemReducer;\r\n//import jaicore.graph.IGraphAlgorithmListener;\r\n//import jaicore.graph.TreeNode;\r\n//import jaicore.search.core.interfaces.IORGraphSearchFactory;\r\n//import jaicore.search.model.other.EvaluatedSearchGraphPath;\r\n//import jaicore.search.model.probleminputs.NodeRecommendedTree;\r\n//import jaicore.search.testproblems.nqueens.NQueenTester;\r\n//import jaicore.search.testproblems.nqueens.NQueensToNodeRecommendedTreeReducer;\r\n//import jaicore.search.testproblems.nqueens.QueenNode;\r\n//\r\n//public class LDSNQueenTester extends NQueenTester<NodeRecommendedTree<QueenNode,String>,EvaluatedSearchGraphPath<QueenNode,String,Double>, TreeNode<QueenNode>,String> {\r\n//\r\n//\t@Override\r\n//\tpublic AlgorithmProblemReducer<Integer, NodeRecommendedTree<QueenNode, String>> getProblemReducer() {\r\n//\t\treturn new NQueensToNodeRecommendedTreeReducer();\r\n//\t}\r\n//\r\n//\t@Override\r\n//\tpublic IORGraphSearchFactory<NodeRecommendedTree<QueenNode, String>, EvaluatedSearchGraphPath<QueenNode, String, Double>, QueenNode, String, Double, TreeNode<QueenNode>, String, IGraphAlgorithmListener<TreeNode<QueenNode>, String>> getFactory() {\r\n//\t\treturn new LimitedDiscrepancySearchFactory<>();\r\n//\t}\r\n//\t\r\n//}\r\n" }, { "alpha_fraction": 0.6745283007621765, "alphanum_fraction": 0.6745283007621765, "avg_line_length": 17.272727966308594, "blob_id": "87eb2c12a3700c0cb46dbcc5d1fac4981e542ebd", "content_id": "b7c383d6957efc4cee623e0868d8bc08774b4d8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 212, "license_type": "no_license", "max_line_length": 76, "num_lines": 11, "path": "/JAICore/jaicore-math/src/numopt/ISingleMinimumComputer.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package numopt;\r\n\r\n/**\r\n * Interface to compute the place of a function f where f is locally minimal\r\n * \r\n * @author fmohr\r\n *\r\n */\r\npublic interface ISingleMinimumComputer {\r\n\tpublic double[] getMinimum();\r\n}\r\n" }, { "alpha_fraction": 0.7454545497894287, "alphanum_fraction": 0.7454545497894287, "avg_line_length": 25.5, "blob_id": "a64c91364873617818d625ca677ce3e998f9278c", "content_id": "0c45a149c7d79e423159537f277c86577c316bbe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 275, "license_type": "no_license", "max_line_length": 92, "num_lines": 10, "path": "/JAICore/jaicore-basic/src/jaicore/basic/algorithm/IAlgorithmFactory.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.basic.algorithm;\r\n\r\npublic interface IAlgorithmFactory<I, O> {\r\n\t\r\n\tpublic <P> void setProblemInput(P problemInput, AlgorithmProblemTransformer<P, I> reducer);\r\n\t\r\n\tpublic void setProblemInput(I problemInput);\r\n\t\r\n\tpublic IAlgorithm<I, O> getAlgorithm();\r\n}\r\n" }, { "alpha_fraction": 0.7180179953575134, "alphanum_fraction": 0.7184684872627258, "avg_line_length": 28.620689392089844, "blob_id": "0ceab33d9d3d91116bcb2eb44d92766652ad0d17", "content_id": "cbae30dff9509ad74643a3d0ad4f4878a5ac9421", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4440, "license_type": "no_license", "max_line_length": 199, "num_lines": 145, "path": "/JAICore/jaicore-search/src/jaicore/search/model/travesaltree/VersionedGraphGenerator.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.model.travesaltree;\r\n\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.Collection;\r\nimport java.util.List;\r\nimport java.util.Random;\r\n\r\nimport jaicore.search.core.interfaces.GraphGenerator;\r\nimport jaicore.search.structure.graphgenerator.MultipleRootGenerator;\r\nimport jaicore.search.structure.graphgenerator.NodeGoalTester;\r\nimport jaicore.search.structure.graphgenerator.PathGoalTester;\r\nimport jaicore.search.structure.graphgenerator.SingleRootGenerator;\r\nimport jaicore.search.structure.graphgenerator.SuccessorGenerator;\r\n\r\n/**\r\n * Class which wraps up a normal GraphGenerator and is adding a id to every node\r\n * @author jkoepe\r\n *\r\n */\r\npublic class VersionedGraphGenerator<T,A> implements VersionedGraphGeneratorInterface<VersionedDomainNode<T>,A> {\r\n\r\n\t//variables \r\n\tGraphGenerator<T, A> gen;\r\n\tboolean nodeNumbering;\r\n\tRandom rnd;\r\n\t\r\n\tpublic VersionedGraphGenerator(GraphGenerator<T,A> gen) {\r\n\t\tthis.gen = gen;\r\n\t\tnodeNumbering = true;\r\n\t\trnd = new Random();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Retrieves the next id\r\n\t * @return\r\n\t * \t\treturns a unique id if numbering is enable, otherwise -1\r\n\t */\r\n\tpublic int getNextID() {\r\n\t\tif(nodeNumbering)\r\n\t\t\treturn rnd.nextInt(Integer.MAX_VALUE);\r\n\t\telse\r\n\t\t\treturn -1;\t\r\n\t}\r\n\r\n\r\n\t@Override\r\n\tpublic SingleRootGenerator<VersionedDomainNode<T>> getRootGenerator() {\r\n\t\treturn () -> {\r\n\t\t\tSingleRootGenerator<T> rootGenerator = (SingleRootGenerator<T>) gen.getRootGenerator();\r\n\t\t\tT root = (T) rootGenerator.getRoot();\r\n\t\t\treturn new VersionedDomainNode<T>(root, this.getNextID());\r\n\t\t};\r\n\t}\r\n\t\r\n\tpublic SingleRootGenerator<VersionedDomainNode<T>> getSingleRootGenerator(){\r\n\t\treturn () -> {\r\n\t\t\tSingleRootGenerator<T> rootGenerator = (SingleRootGenerator<T>) gen.getRootGenerator();\r\n\t\t\tT root = (T) rootGenerator.getRoot();\r\n\t\t\treturn new VersionedDomainNode<T>(root, this.getNextID());\r\n\t\t};\r\n\t}\r\n\t\r\n\tpublic MultipleRootGenerator<VersionedDomainNode<T>> getMultipleRootGenerator(){\r\n\t\treturn () -> {\r\n\t\t\tMultipleRootGenerator<T> rootGenerator = (MultipleRootGenerator<T>) gen.getRootGenerator();\r\n\t\t\tCollection<VersionedDomainNode<T>> vRoots = new ArrayList<VersionedDomainNode<T>>();\r\n\t\t\tCollection<T> roots = rootGenerator.getRoots();\r\n\t\t\t\r\n\t\t\troots.stream().forEach(\r\n\t\t\t\t\tn -> vRoots.add(new VersionedDomainNode<T>(n, this.getNextID()))\r\n\t\t\t\t\t);\t\t\t\r\n\t\t\treturn (Collection<VersionedDomainNode<T>>) vRoots;\r\n\t\t};\r\n\t}\r\n\r\n\r\n\t@Override\r\n\tpublic SuccessorGenerator<VersionedDomainNode<T>, A> getSuccessorGenerator() {\r\n\t\treturn nodeToExpand ->{\r\n\t\t\tSuccessorGenerator<T,A> successorGenerator = (SuccessorGenerator<T, A>) gen.getSuccessorGenerator();\r\n\t\t\tCollection<NodeExpansionDescription<T,A>> successorDescriptions = successorGenerator.generateSuccessors(nodeToExpand.getNode());\r\n\t\t\t\r\n\t\t\tList<NodeExpansionDescription<VersionedDomainNode<T>,A>> versionedDescriptions = new ArrayList<>();\r\n\t\t\t\r\n\t\t\tsuccessorDescriptions.stream().forEach(description->\r\n\t\t\t\t\t\tversionedDescriptions.add(new NodeExpansionDescription<>(nodeToExpand, new VersionedDomainNode<>(description.getTo(), this.getNextID()), description.getAction(), description.getTypeOfToNode()))\r\n\t\t\t\t\t);\r\n\t\t\treturn versionedDescriptions;\r\n\t\t};\r\n\t}\r\n\r\n\r\n\r\n\t@Override\r\n\tpublic NodeGoalTester<VersionedDomainNode<T>> getGoalTester() {\r\n\t\t// TODO Auto-generated method stub\r\n\t\treturn n -> {\r\n\t\t\tNodeGoalTester<T> goalTester = (NodeGoalTester<T>) gen.getGoalTester();\r\n\t\t\treturn goalTester.isGoal(n.getNode());\r\n\t\t};\r\n\t}\r\n\t\r\n\t/**\r\n\t * A method which redirects the NodeGoalTester from VersionedT<T> to T\r\n\t * @return\r\n\t */\r\n\tpublic NodeGoalTester<VersionedDomainNode<T>> getNodeGoalTester(){\r\n\t\treturn n -> {\r\n\t\t\tNodeGoalTester<T> goalTester = (NodeGoalTester<T>) gen.getGoalTester();\r\n\t\t\treturn goalTester.isGoal(n.getNode());\r\n\t\t};\r\n\t}\r\n\t\r\n\t\r\n\t/**\r\n\t * Method which redirects the pathgoaltester from versioned<T> nodes to simple t nodes.\r\n\t * This method does currently not work as it is not implemented to extract the path from a versioned node\r\n\t * @return\r\n\t */\r\n\t@SuppressWarnings(\"unchecked\")\r\n\tpublic PathGoalTester<VersionedDomainNode<T>> getPathGoalTester(){\r\n\t\treturn n ->{\r\n\t\t\tPathGoalTester<T> goalTester = (PathGoalTester<T>)gen.getGoalTester();\r\n\t\t\treturn goalTester.isGoal((List<T>) n);\r\n\t\t};\r\n\t}\r\n\r\n\r\n\t@Override\r\n\tpublic boolean isSelfContained() {\r\n\t\r\n\t\treturn gen.isSelfContained();\r\n\t}\r\n\r\n\r\n\t@Override\r\n\tpublic void setNodeNumbering(boolean numbering) {\r\n\t\tthis.nodeNumbering = numbering;\r\n\t}\r\n\r\n\r\n\r\n\r\n}\r\n" }, { "alpha_fraction": 0.6432469487190247, "alphanum_fraction": 0.6459754705429077, "avg_line_length": 18.289474487304688, "blob_id": "f9dbabe87c22516a6ad9f4a9d0f4d2acf34865b5", "content_id": "4c57cb685ff705cac53e06c4ca30a3246058feca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1466, "license_type": "no_license", "max_line_length": 80, "num_lines": 76, "path": "/JAICore/jaicore-logic/src/jaicore/logic/fol/structure/LiteralParam.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.logic.fol.structure;\n\nimport java.io.Serializable;\n\n/**\n * The parameter of a literal.\n * \n * @author mbunse\n */\n@SuppressWarnings(\"serial\")\npublic abstract class LiteralParam implements Serializable {\n\n\tprivate String name;\n\tprotected Type type;\n\n\t/**\n\t * @param name\n\t * The name of this parameter;\n\t */\n\tpublic LiteralParam(String name) {\n\t\tthis.name = name;\n\t}\n\n\t/**\n\t * @param name\n\t * The name of this parameter;\n\t */\n\tpublic LiteralParam(String name, Type type) {\n\t\tthis(name);\n\t\tthis.setType(type);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((name == null) ? 0 : name.hashCode());\n\t\treturn result;\n\t}\n\n\t/**\n\t * It is with intention that the equals method does NOT check the type.\n\t * We assume that the name of a parameter is sufficient to identify it.\n\t * The type is rather optional to enable efficient processing in some contexts.\n\t * \n\t */\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tLiteralParam other = (LiteralParam) obj;\n\t\tif (name == null) {\n\t\t\tif (other.name != null)\n\t\t\t\treturn false;\n\t\t} else if (!name.equals(other.name))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic Type getType() {\n\t\treturn type;\n\t}\n\n\tpublic void setType(Type type) {\n\t\tthis.type = type;\n\t}\n\n}\n" }, { "alpha_fraction": 0.6450400948524475, "alphanum_fraction": 0.6473572254180908, "avg_line_length": 41.628414154052734, "blob_id": "9685f0d766574fae1fda7d7c5f17e4e011428d4f", "content_id": "d10c5c4cf33abbe1100ff6dc2a8078e5933fd272", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 15968, "license_type": "no_license", "max_line_length": 195, "num_lines": 366, "path": "/softwareconfiguration/hasco/src/hasco/serialization/ComponentLoader.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package hasco.serialization;\r\n\r\nimport java.io.BufferedReader;\r\nimport java.io.File;\r\nimport java.io.FileReader;\r\nimport java.io.IOException;\r\nimport java.util.ArrayList;\r\nimport java.util.Arrays;\r\nimport java.util.Collection;\r\nimport java.util.HashMap;\r\nimport java.util.HashSet;\r\nimport java.util.LinkedList;\r\nimport java.util.List;\r\nimport java.util.Map;\r\nimport java.util.Set;\r\nimport java.util.stream.Collectors;\r\n\r\nimport org.apache.commons.math3.geometry.euclidean.oned.Interval;\r\n\r\nimport com.fasterxml.jackson.databind.JsonNode;\r\nimport com.fasterxml.jackson.databind.ObjectMapper;\r\n\r\nimport hasco.model.BooleanParameterDomain;\r\nimport hasco.model.CategoricalParameterDomain;\r\nimport hasco.model.Component;\r\nimport hasco.model.Dependency;\r\nimport hasco.model.NumericParameterDomain;\r\nimport hasco.model.Parameter;\r\nimport hasco.model.ParameterDomain;\r\nimport hasco.model.ParameterRefinementConfiguration;\r\nimport jaicore.basic.sets.SetUtil;\r\nimport jaicore.basic.sets.SetUtil.Pair;\r\n\r\npublic class ComponentLoader {\r\n\r\n\tprivate Map<Component, Map<Parameter, ParameterRefinementConfiguration>> paramConfigs = new HashMap<>();\r\n\tprivate Collection<Component> components = new ArrayList<>();\r\n\tprivate final Set<String> parsedFiles = new HashSet<>();\r\n\tprivate final ObjectMapper objectMapper = new ObjectMapper();\r\n\tprivate Map<String, JsonNode> parameterMap = new HashMap<>();\r\n\tprivate Set<String> uniqueComponentNames = new HashSet<>();\r\n\r\n\tpublic ComponentLoader() {\r\n\t}\r\n\r\n\tpublic ComponentLoader(final File jsonFile) throws IOException {\r\n\t\tthis.parseFile(jsonFile);\r\n\t}\r\n\r\n\tprivate void parseFile(final File jsonFile) throws IOException {\r\n\t\tSystem.out.println(\"Parse file \" + jsonFile.getAbsolutePath());\r\n\t\tStringBuilder stringDescriptionSB = new StringBuilder();\r\n\t\tString line;\r\n\t\ttry (BufferedReader br = new BufferedReader(new FileReader(jsonFile))) {\r\n\t\t\twhile ((line = br.readLine()) != null) {\r\n\t\t\t\tstringDescriptionSB.append(line + \"\\n\");\r\n\t\t\t}\r\n\t\t}\r\n\t\tString jsonDescription = stringDescriptionSB.toString();\r\n\t\tjsonDescription = jsonDescription.replaceAll(\"/\\\\*(.*)\\\\*/\", \"\");\r\n\r\n\t\tJsonNode rootNode = this.objectMapper.readTree(jsonDescription);\r\n\r\n\t\tfor (JsonNode elem : rootNode.path(\"parameters\")) {\r\n\t\t\tthis.parameterMap.put(elem.get(\"name\").asText(), elem);\r\n\t\t}\r\n\t\tJsonNode includes = rootNode.path(\"include\");\r\n\r\n\t\tFile baseFolder = new File(jsonFile.getCanonicalPath());\r\n\t\tif (jsonFile.isFile()) {\r\n\t\t\tbaseFolder = new File(jsonFile.getCanonicalFile().getParentFile().getCanonicalPath());\r\n\t\t}\r\n\r\n\t\tfor (JsonNode includePathNode : includes) {\r\n\t\t\tString path = includePathNode.asText();\r\n\t\t\tFile subFile = new File(baseFolder.getAbsolutePath() + File.separator + path);\r\n\t\t\tif (!this.parsedFiles.contains(subFile.getCanonicalPath())) {\r\n\t\t\t\tif (!subFile.exists()) {\r\n\t\t\t\t\tthrow new IllegalArgumentException(\"Cannot load \" + subFile.getName() + \" as this file or folder does not exist in \" + subFile.getParent());\r\n\t\t\t\t}\r\n\t\t\t\tif (subFile.isFile()) {\r\n\t\t\t\t\tthis.parsedFiles.add(subFile.getCanonicalPath());\r\n\t\t\t\t\tthis.parseFile(subFile.getCanonicalFile());\r\n\t\t\t\t} else {\r\n\t\t\t\t\tfor (File subsubFile : subFile.listFiles()) {\r\n\t\t\t\t\t\tif (!this.parsedFiles.contains(subsubFile.getCanonicalPath()) && subsubFile.isFile() && subsubFile.getName().endsWith(\".json\")) {\r\n\t\t\t\t\t\t\tthis.parsedFiles.add(subsubFile.getCanonicalPath());\r\n\t\t\t\t\t\t\tthis.parseFile(subsubFile.getCanonicalFile());\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tthis.parsedFiles.add(subFile.getCanonicalPath());\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t// get the array of components\r\n\t\tJsonNode components = rootNode.path(\"components\");\r\n\t\tif (components != null) {\r\n\r\n\t\t\tComponent c;\r\n\t\t\tfor (JsonNode component : components) {\r\n\t\t\t\tc = new Component(component.get(\"name\").asText());\r\n\t\t\t\tif (!this.uniqueComponentNames.add(c.getName())) {\r\n\t\t\t\t\tthrow new IllegalArgumentException(\"Noticed a component with duplicative component name: \" + c.getName());\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// add provided interfaces\r\n\r\n\t\t\t\tfor (JsonNode providedInterface : component.path(\"providedInterface\")) {\r\n\t\t\t\t\tc.addProvidedInterface(providedInterface.asText());\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// add required interfaces\r\n\t\t\t\tfor (JsonNode requiredInterface : component.path(\"requiredInterface\")) {\r\n\t\t\t\t\tif (!requiredInterface.has(\"id\")) {\r\n\t\t\t\t\t\tthrow new IOException(\"No id has been specified for a required interface of \" + c.getName());\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (!requiredInterface.has(\"name\")) {\r\n\t\t\t\t\t\tthrow new IOException(\"No name has been specified for a required interface of \" + c.getName());\r\n\t\t\t\t\t}\r\n\t\t\t\t\tc.addRequiredInterface(requiredInterface.get(\"id\").asText(), requiredInterface.get(\"name\").asText());\r\n\t\t\t\t}\r\n\r\n\t\t\t\tMap<Parameter, ParameterRefinementConfiguration> paramConfig = new HashMap<>();\r\n\r\n\t\t\t\tfor (JsonNode parameter : component.path(\"parameter\")) {\r\n\t\t\t\t\t// name of the parameter\r\n\t\t\t\t\tString name = parameter.get(\"name\").asText();\r\n\t\t\t\t\t// possible string params\r\n\t\t\t\t\tString[] stringParams = new String[] { \"type\", \"values\", \"default\" };\r\n\t\t\t\t\tString[] stringParamValues = new String[stringParams.length];\r\n\t\t\t\t\t// possible boolean params\r\n\t\t\t\t\tString[] boolParams = new String[] { \"default\" };\r\n\t\t\t\t\tboolean[] boolParamValues = new boolean[boolParams.length];\r\n\t\t\t\t\t// possible double params\r\n\t\t\t\t\tString[] doubleParams = new String[] { \"default\", \"min\", \"max\", \"refineSplits\", \"minInterval\" };\r\n\t\t\t\t\tdouble[] doubleParamValues = new double[doubleParams.length];\r\n\r\n\t\t\t\t\tif (this.parameterMap.containsKey(name)) {\r\n\t\t\t\t\t\tJsonNode commonParameter = this.parameterMap.get(name);\r\n\t\t\t\t\t\t// get string parameter values from common parameter\r\n\t\t\t\t\t\tfor (int i = 0; i < stringParams.length; i++) {\r\n\t\t\t\t\t\t\tif (commonParameter.get(stringParams[i]) != null) {\r\n\t\t\t\t\t\t\t\tstringParamValues[i] = commonParameter.get(stringParams[i]).asText();\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t// get double parameter values from common parameter\r\n\t\t\t\t\t\tfor (int i = 0; i < doubleParams.length; i++) {\r\n\t\t\t\t\t\t\tif (commonParameter.get(doubleParams[i]) != null) {\r\n\t\t\t\t\t\t\t\tdoubleParamValues[i] = commonParameter.get(doubleParams[i]).asDouble();\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t// get boolean parameter values from common parameter\r\n\t\t\t\t\t\tfor (int i = 0; i < boolParams.length; i++) {\r\n\t\t\t\t\t\t\tif (commonParameter.get(boolParams[i]) != null) {\r\n\t\t\t\t\t\t\t\tboolParamValues[i] = commonParameter.get(boolParams[i]).asBoolean();\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t// get string parameter values from current parameter\r\n\t\t\t\t\tfor (int i = 0; i < stringParams.length; i++) {\r\n\t\t\t\t\t\tif (parameter.get(stringParams[i]) != null) {\r\n\t\t\t\t\t\t\tstringParamValues[i] = parameter.get(stringParams[i]).asText();\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\t// get double parameter values from current parameter\r\n\t\t\t\t\tfor (int i = 0; i < doubleParams.length; i++) {\r\n\t\t\t\t\t\tif (parameter.get(doubleParams[i]) != null) {\r\n\t\t\t\t\t\t\tdoubleParamValues[i] = parameter.get(doubleParams[i]).asDouble();\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\t// get boolean parameter values from current parameter\r\n\t\t\t\t\tfor (int i = 0; i < boolParams.length; i++) {\r\n\t\t\t\t\t\tif (parameter.get(boolParams[i]) != null) {\r\n\t\t\t\t\t\t\tboolParamValues[i] = parameter.get(boolParams[i]).asBoolean();\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tParameter p = null;\r\n\t\t\t\t\tString type = stringParamValues[Arrays.stream(stringParams).collect(Collectors.toList()).indexOf(\"type\")];\r\n\t\t\t\t\tswitch (type) {\r\n\t\t\t\t\tcase \"int\":\r\n\t\t\t\t\tcase \"double\":\r\n\t\t\t\t\t\tp = new Parameter(name, new NumericParameterDomain(type.equals(\"int\"), doubleParamValues[1], doubleParamValues[2]), doubleParamValues[0]);\r\n\t\t\t\t\t\tif (doubleParamValues[3] == 0) {\r\n\t\t\t\t\t\t\tthrow new IllegalArgumentException(\"Please specify the parameter \\\"refineSplits\\\" for the parameter \\\"\" + p.getName() + \"\\\" in component \\\"\" + c.getName() + \"\\\"\");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tif (doubleParamValues[4] <= 0) {\r\n\t\t\t\t\t\t\tthrow new IllegalArgumentException(\"Please specify a strictly positive parameter value for \\\"minInterval\\\" for the parameter \\\"\" + p.getName() + \"\\\" in component \\\"\" + c.getName() + \"\\\"\");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tparamConfig.put(p, new ParameterRefinementConfiguration((int) doubleParamValues[3], doubleParamValues[4]));\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"bool\":\r\n\t\t\t\t\tcase \"boolean\":\r\n\t\t\t\t\t\tp = new Parameter(name, new BooleanParameterDomain(), boolParamValues[0]);\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"cat\":\r\n\t\t\t\t\t\tif (parameter.get(\"values\") != null && parameter.get(\"values\").isTextual()) {\r\n\t\t\t\t\t\t\tp = new Parameter(name, new CategoricalParameterDomain(Arrays.stream(stringParamValues[1].split(\",\")).collect(Collectors.toList())), stringParamValues[2]);\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tList<String> values = new LinkedList<>();\r\n\r\n\t\t\t\t\t\t\tif (parameter.get(\"values\") != null) {\r\n\t\t\t\t\t\t\t\tfor (JsonNode value : parameter.get(\"values\")) {\r\n\t\t\t\t\t\t\t\t\tvalues.add(value.asText());\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t} else if (this.parameterMap.containsKey(name)) {\r\n\t\t\t\t\t\t\t\tfor (JsonNode value : this.parameterMap.get(name).get(\"values\")) {\r\n\t\t\t\t\t\t\t\t\tvalues.add(value.asText());\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\tSystem.err.println(\"Warning: Categorical parameter \" + name + \" in component \" + c.getName() + \" without value list.\");\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tp = new Parameter(name, new CategoricalParameterDomain(values), stringParamValues[2]);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tdefault:\r\n\t\t\t\t\t\tthrow new IllegalArgumentException(\"Unsupported parameter type \" + type);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (p != null) {\r\n\t\t\t\t\t\tc.addParameter(p);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/* now parse dependencies */\r\n\t\t\t\tfor (JsonNode dependency : component.path(\"dependencies\")) {\r\n\r\n\t\t\t\t\t/* parse precondition */\r\n\t\t\t\t\tString pre = dependency.get(\"pre\").asText();\r\n\t\t\t\t\tCollection<Collection<Pair<Parameter, ParameterDomain>>> premise = new ArrayList<>();\r\n\t\t\t\t\tCollection<String> monoms = Arrays.asList(pre.split(\"\\\\|\"));\r\n\t\t\t\t\tfor (String monom : monoms) {\r\n\t\t\t\t\t\tCollection<String> literals = Arrays.asList(monom.split(\"&\"));\r\n\t\t\t\t\t\tCollection<Pair<Parameter, ParameterDomain>> monomInPremise = new ArrayList<>();\r\n\r\n\t\t\t\t\t\tfor (String literal : literals) {\r\n\t\t\t\t\t\t\tString[] parts = literal.trim().split(\" \");\r\n\t\t\t\t\t\t\tif (parts.length != 3) {\r\n\t\t\t\t\t\t\t\tthrow new IllegalArgumentException(\"Cannot parse literal \" + literal + \". Literals must be of the form \\\"<a> P <b>\\\".\");\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\tParameter param = c.getParameterWithName(parts[0]);\r\n\t\t\t\t\t\t\tString target = parts[2];\r\n\t\t\t\t\t\t\tswitch (parts[1]) {\r\n\t\t\t\t\t\t\tcase \"=\": {\r\n\t\t\t\t\t\t\t\tPair<Parameter, ParameterDomain> conditionItem;\r\n\t\t\t\t\t\t\t\tif (param.isNumeric()) {\r\n\t\t\t\t\t\t\t\t\tdouble val = Double.valueOf(target);\r\n\t\t\t\t\t\t\t\t\tconditionItem = new Pair<>(param, new NumericParameterDomain(((NumericParameterDomain) param.getDefaultDomain()).isInteger(), val, val));\r\n\t\t\t\t\t\t\t\t} else if (param.isCategorical()) {\r\n\t\t\t\t\t\t\t\t\tconditionItem = new Pair<>(param, new CategoricalParameterDomain(new String[] { target }));\r\n\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\tthrow new IllegalArgumentException(\"Currently no support for parameters with domain \\\"\" + param.getDefaultDomain().getClass().getName() + \"\\\"\");\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\tmonomInPremise.add(conditionItem);\r\n\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tcase \"in\": {\r\n\t\t\t\t\t\t\t\tPair<Parameter, ParameterDomain> conditionItem;\r\n\t\t\t\t\t\t\t\tif (param.isNumeric()) {\r\n\t\t\t\t\t\t\t\t\tInterval interval = SetUtil.unserializeInterval(\"[\" + target.substring(1, target.length() - 1) + \"]\");\r\n\t\t\t\t\t\t\t\t\tconditionItem = new Pair<>(param, new NumericParameterDomain(((NumericParameterDomain) param.getDefaultDomain()).isInteger(), interval.getInf(), interval.getSup()));\r\n\t\t\t\t\t\t\t\t} else if (param.isCategorical()) {\r\n\t\t\t\t\t\t\t\t\tif (!target.startsWith(\"[\") && !target.startsWith(\"{\")) {\r\n\t\t\t\t\t\t\t\t\t\tthrow new IllegalArgumentException(\"Illegal literal \\\"\" + literal + \"\\\" in the postcondition of dependency. This should be a set, but the target is not described by [...] or {...}\");\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\tCollection<String> values = target.startsWith(\"[\") ? SetUtil.unserializeList(target) : SetUtil.unserializeSet(target);\r\n\t\t\t\t\t\t\t\t\tconditionItem = new Pair<>(param, new CategoricalParameterDomain(values));\r\n\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\tthrow new IllegalArgumentException(\"Currently no support for parameters with domain \\\"\" + param.getDefaultDomain().getClass().getName() + \"\\\"\");\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\tmonomInPremise.add(conditionItem);\r\n\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tdefault:\r\n\t\t\t\t\t\t\t\tthrow new IllegalArgumentException(\"Cannot parse literal \" + literal + \". Currently no support for predicate \\\"\" + parts[1] + \"\\\".\");\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tpremise.add(monomInPremise);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t/* parse postcondition */\r\n\t\t\t\t\tCollection<Pair<Parameter, ParameterDomain>> conclusion = new ArrayList<>();\r\n\t\t\t\t\tString post = dependency.get(\"post\").asText();\r\n\t\t\t\t\tCollection<String> literals = Arrays.asList(post.split(\"&\"));\r\n\r\n\t\t\t\t\tfor (String literal : literals) {\r\n\t\t\t\t\t\tString[] parts = literal.trim().split(\" \");\r\n\t\t\t\t\t\tif (parts.length < 3) {\r\n\t\t\t\t\t\t\tthrow new IllegalArgumentException(\"Cannot parse literal \" + literal + \". Literals must be of the form \\\"<a> P <b>\\\".\");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tif (parts.length > 3) {\r\n\t\t\t\t\t\t\tfor (int i = 3; i < parts.length; i++) {\r\n\t\t\t\t\t\t\t\tparts[2] += \" \" + parts[i];\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tParameter param = c.getParameterWithName(parts[0]);\r\n\t\t\t\t\t\tString target = parts[2];\r\n\t\t\t\t\t\tswitch (parts[1]) {\r\n\t\t\t\t\t\tcase \"=\": {\r\n\t\t\t\t\t\t\tPair<Parameter, ParameterDomain> conditionItem;\r\n\t\t\t\t\t\t\tif (param.isNumeric()) {\r\n\t\t\t\t\t\t\t\tdouble val = Double.valueOf(target);\r\n\t\t\t\t\t\t\t\tconditionItem = new Pair<>(param, new NumericParameterDomain(((NumericParameterDomain) param.getDefaultDomain()).isInteger(), val, val));\r\n\t\t\t\t\t\t\t} else if (param.isCategorical()) {\r\n\t\t\t\t\t\t\t\tconditionItem = new Pair<>(param, new CategoricalParameterDomain(new String[] { target }));\r\n\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\tthrow new IllegalArgumentException(\"Currently no support for parameters with domain \\\"\" + param.getDefaultDomain().getClass().getName() + \"\\\"\");\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tconclusion.add(conditionItem);\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tcase \"in\": {\r\n\t\t\t\t\t\t\tPair<Parameter, ParameterDomain> conditionItem;\r\n\t\t\t\t\t\t\tif (param.isNumeric()) {\r\n\t\t\t\t\t\t\t\tInterval interval = SetUtil.unserializeInterval(\"[\" + target.substring(1, target.length() - 1) + \"]\");\r\n\t\t\t\t\t\t\t\tconditionItem = new Pair<>(param, new NumericParameterDomain(((NumericParameterDomain) param.getDefaultDomain()).isInteger(), interval.getInf(), interval.getSup()));\r\n\t\t\t\t\t\t\t} else if (param.isCategorical()) {\r\n\t\t\t\t\t\t\t\tif (!target.startsWith(\"[\") && !target.startsWith(\"{\")) {\r\n\t\t\t\t\t\t\t\t\tthrow new IllegalArgumentException(\"Illegal literal \\\"\" + literal + \"\\\" in the postcondition of dependency. This should be a set, but the target is not described by [...] or {...}\");\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\tCollection<String> values = target.startsWith(\"[\") ? SetUtil.unserializeList(target) : SetUtil.unserializeSet(target);\r\n\t\t\t\t\t\t\t\tconditionItem = new Pair<>(param, new CategoricalParameterDomain(values));\r\n\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\tthrow new IllegalArgumentException(\"Currently no support for parameters with domain \\\"\" + param.getDefaultDomain().getClass().getName() + \"\\\"\");\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tconclusion.add(conditionItem);\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tdefault:\r\n\t\t\t\t\t\t\tthrow new IllegalArgumentException(\"Cannot parse literal \" + literal + \". Currently no support for predicate \\\"\" + parts[1] + \"\\\".\");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\t/* add dependency to the component */\r\n\t\t\t\t\tc.addDependency(new Dependency(premise, conclusion));\r\n\t\t\t\t}\r\n\r\n\t\t\t\tthis.paramConfigs.put(c, paramConfig);\r\n\t\t\t\tthis.components.add(c);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void loadComponents(final File componentDescriptionFile) throws IOException {\r\n\t\tthis.paramConfigs.clear();\r\n\t\tthis.components.clear();\r\n\t\tthis.uniqueComponentNames.clear();\r\n\r\n\t\tthis.parseFile(componentDescriptionFile);\r\n\t}\r\n\r\n\tpublic Map<Component, Map<Parameter, ParameterRefinementConfiguration>> getParamConfigs() {\r\n\t\treturn this.paramConfigs;\r\n\t}\r\n\r\n\tpublic Collection<Component> getComponents() {\r\n\t\treturn this.components;\r\n\t}\r\n\r\n\tpublic static void main(final String[] args) throws IOException {\r\n\t\tComponentLoader cl = new ComponentLoader();\r\n\t\tcl.loadComponents(new File(\"complexMLComponents.json\"));\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.6868008971214294, "alphanum_fraction": 0.6901565790176392, "avg_line_length": 22.526315689086914, "blob_id": "e633040c87e277a997418470fd73f80ae1bafcaa", "content_id": "3aeda37895c50e0ba39f31fd05e008c5a33b2006", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1788, "license_type": "no_license", "max_line_length": 85, "num_lines": 76, "path": "/softwareconfiguration/hasco/src/hasco/model/Parameter.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package hasco.model;\n\npublic class Parameter {\n\tprivate final String name;\n\tprivate final ParameterDomain defaultDomain;\n\tprivate final Object defaultValue;\n\n\tpublic Parameter(String name, ParameterDomain defaultDomain, Object defaultValue) {\n\t\tsuper();\n\t\tthis.name = name;\n\t\tthis.defaultDomain = defaultDomain;\n\t\tthis.defaultValue = defaultValue;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic ParameterDomain getDefaultDomain() {\n\t\treturn defaultDomain;\n\t}\n\n\tpublic Object getDefaultValue() {\n\t\treturn defaultValue;\n\t}\n\t\n\tpublic boolean isNumeric() {\n\t\treturn defaultDomain instanceof NumericParameterDomain;\n\t}\n\t\n\tpublic boolean isCategorical() {\n\t\treturn defaultDomain instanceof CategoricalParameterDomain;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((defaultDomain == null) ? 0 : defaultDomain.hashCode());\n\t\tresult = prime * result + ((defaultValue == null) ? 0 : defaultValue.hashCode());\n\t\tresult = prime * result + ((name == null) ? 0 : name.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tParameter other = (Parameter) obj;\n\t\tif (defaultDomain == null) {\n\t\t\tif (other.defaultDomain != null)\n\t\t\t\treturn false;\n\t\t} else if (!defaultDomain.equals(other.defaultDomain))\n\t\t\treturn false;\n\t\tif (defaultValue == null) {\n\t\t\tif (other.defaultValue != null)\n\t\t\t\treturn false;\n\t\t} else if (!defaultValue.equals(other.defaultValue))\n\t\t\treturn false;\n\t\tif (name == null) {\n\t\t\tif (other.name != null)\n\t\t\t\treturn false;\n\t\t} else if (!name.equals(other.name))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn name;\n\t}\n}\n" }, { "alpha_fraction": 0.589195966720581, "alphanum_fraction": 0.6130653023719788, "avg_line_length": 22.875, "blob_id": "9fad26126d405201c344370479f31d52f1fb93e0", "content_id": "26e58883fcfd02ec1a98e879521c3c5908e57f9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Gradle", "length_bytes": 796, "license_type": "no_license", "max_line_length": 88, "num_lines": 32, "path": "/JAICore/jaicore-graphvisualizer/build.gradle", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "sourceSets {\r\n main {\r\n java {\r\n srcDir 'src'\r\n }\r\n }\r\n test {\r\n \tjava {\r\n \t\tsrcDir 'test'\r\n \t}\r\n }\r\n}\r\ndependencies {\r\n\tcompile project(\":JAICore:jaicore-graph\")\r\n\t\r\n\tcompile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.6'\r\n\t\r\n\t//compile group: 'org.graphstream', name: 'gs-core', version: '1.3'\r\n\t//compile group: 'org.graphstream', name: 'gs-ui', version: '1.3'\r\n\tcompile group: 'com.google.guava', name: 'guava', version: '26.0-jre'\r\n\tcompile group: 'org.apache.commons', name: 'commons-math3', version: '3.0'\r\n\t\r\n\r\n\timplementation 'com.github.graphstream:gs-core:2.0-alpha'\r\n\timplementation 'com.github.graphstream:gs-ui-javafx:2.0-alpha'\r\n\timplementation 'com.github.graphstream:gs-algo:2.0-alpha'\r\n\r\n\r\n\t\r\n\t\r\n\t\r\n}\r\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.7896825671195984, "avg_line_length": 29.75, "blob_id": "a43f3c8171b0d2c1bcf988d87a95bf52a57b9f4a", "content_id": "41f7beecb27e71bdbf25d3ea42aad4b49838c7e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 252, "license_type": "no_license", "max_line_length": 81, "num_lines": 8, "path": "/softwareconfiguration/mlplan/conf/mlplanwekacli.properties", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "mem.max = 8192\r\ncpu.max = 8\r\n\r\nmlplanwekacli.globaltimeout = 300\r\nmlplanwekacli.evaltimeout = 10\r\nmlplanwekacli.datasetfile=../../../datasets/classification/multi-class/ecoli.arff\r\nmlplanwekacli.outputfile=out.txt\r\nmlplanwekacli.weka.cli.showgrpah=true" }, { "alpha_fraction": 0.6739130616188049, "alphanum_fraction": 0.695652186870575, "avg_line_length": 18.85714340209961, "blob_id": "708df93d30e78b68b1435dd85c1494b5d09774d3", "content_id": "e48ddd46ed2f1c5ab84ae65e01086e701af7c81b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 138, "license_type": "no_license", "max_line_length": 64, "num_lines": 7, "path": "/softwareconfiguration/mlplan/src/de/upb/crc901/mlplan/metamining/package-info.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "/**\n * Package containing an implementation of a meta-miner for WEKA\n * \n * @author Helena Graf\n *\n */\npackage de.upb.crc901.mlplan.metamining;" }, { "alpha_fraction": 0.8047493696212769, "alphanum_fraction": 0.8047493696212769, "avg_line_length": 28.153846740722656, "blob_id": "5c1f08417fe4ab3bb0e1797d88bd00b96df59ab1", "content_id": "2bac560a17e8aa785d4b5cb591774290d870ec7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 379, "license_type": "no_license", "max_line_length": 66, "num_lines": 13, "path": "/JAICore/jaicore-ml/src/jaicore/ml/interfaces/Instances.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.ml.interfaces;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.List;\n\npublic interface Instances extends List<Instance> {\n\tpublic int getNumberOfRows();\n\tpublic int getNumberOfColumns();\n\tpublic String toJson();\n\tpublic void addAllFromJson(String jsonString) throws IOException;\n\tpublic void addAllFromJson(File jsonFile) throws IOException;\n}\n" }, { "alpha_fraction": 0.6766025424003601, "alphanum_fraction": 0.6913461685180664, "avg_line_length": 30.52083396911621, "blob_id": "7ff71f083878cd9af986ba53e2cdf72b8641c4e1", "content_id": "ddbbca2055fa214087a0dc4ed0b87d7a3a46a28b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3120, "license_type": "no_license", "max_line_length": 153, "num_lines": 96, "path": "/JAICore/jaicore-ml/src/jaicore/ml/classification/multiclass/reduction/splitters/RPNDSplitter.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.ml.classification.multiclass.reduction.splitters;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.Collection;\r\nimport java.util.Collections;\r\nimport java.util.HashSet;\r\nimport java.util.List;\r\nimport java.util.Random;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport jaicore.basic.sets.SetUtil;\r\nimport jaicore.ml.WekaUtil;\r\nimport weka.classifiers.Classifier;\r\nimport weka.core.Instance;\r\nimport weka.core.Instances;\r\n\r\npublic class RPNDSplitter implements ISplitter {\r\n\r\n\tprivate static final Logger logger = LoggerFactory.getLogger(RPNDSplitter.class);\r\n\tprivate final Random rand;\r\n\tprivate final Classifier rpndClassifier;\r\n\r\n\tpublic RPNDSplitter(Random rand, Classifier rpndClassifier) {\r\n\t\tsuper();\r\n\t\tthis.rand = rand;\r\n\t\tthis.rpndClassifier = rpndClassifier;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic Collection<Collection<String>> split(Instances data) throws Exception {\r\n\r\n\t\tCollection<String> classes = WekaUtil.getClassesActuallyContainedInDataset(data);\r\n\t\t\r\n\t\t/* 2. if we have a leaf node, abort */\r\n\t\tif (classes.size() == 1) {\r\n\t\t\tCollection<Collection<String>> split = new ArrayList<>();\r\n\t\t\tsplit.add(classes);\r\n\t\t\treturn split;\r\n\t\t}\r\n\r\n\t\t/* 3a. otherwise select randomly two classes */\r\n\t\tList<String> copy = new ArrayList<>(classes);\r\n\t\tCollections.shuffle(copy, rand);\r\n\t\tString c1 = copy.get(0);\r\n\t\tString c2 = copy.get(1);\r\n\t\tCollection<String> s1 = new HashSet<>();\r\n\t\ts1.add(c1);\r\n\t\tCollection<String> s2 = new HashSet<>();\r\n\t\ts2.add(c2);\r\n\t\treturn split(copy, s1, s2, data);\r\n\t}\r\n\r\n\tpublic Collection<Collection<String>> split(Collection<String> classes, Collection<String> s1, Collection<String> s2, Instances data) throws Exception {\r\n\r\n\t\tlogger.info(\"Start creation of RPND split with basis {}/{} for classes {}\", s1, s2, classes);\r\n\r\n\t\t/* 3b. and 3c. train binary classifiers for c1 vs c2 */\r\n\t\tInstances reducedData = WekaUtil.mergeClassesOfInstances(data, s1, s2);\r\n\t\tlogger.debug(\"Building classifier for separating the two class sets {} and {}\", s1, s2);\r\n\t\trpndClassifier.buildClassifier(reducedData);\r\n\r\n\t\t/* 3d. insort the remaining classes */\r\n\t\tlogger.info(\"Now classifying the items of the other classes\");\r\n\t\tList<String> remainingClasses = new ArrayList<>(SetUtil.difference(SetUtil.difference(classes, s1), s2));\r\n\t\tfor (int i = 0; i < remainingClasses.size(); i++) {\r\n\t\t\tString className = remainingClasses.get(i);\r\n\t\t\tInstances testData = WekaUtil.getInstancesOfClass(data, className);\r\n\t\t\tlogger.debug(\"Classify {} instances of class {}\", testData.size(), className);\r\n\t\t\tint o1 = 0;\r\n\t\t\tint o2 = 0;\r\n\t\t\tfor (Instance inst : testData) {\r\n\t\t\t\tif (Thread.interrupted())\r\n\t\t\t\t\tthrow new InterruptedException();\r\n\t\t\t\ttry {\r\n\t\t\t\t\tdouble prediction = rpndClassifier.classifyInstance(WekaUtil.getRefactoredInstance(inst));\r\n\t\t\t\t\tif (prediction == 0)\r\n\t\t\t\t\t\to1++;\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\to2++;\r\n\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (o1 > o2)\r\n\t\t\t\ts1.add(className);\r\n\t\t\telse\r\n\t\t\t\ts2.add(className);\r\n\t\t}\r\n\t\tCollection<Collection<String>> split = new ArrayList<>();\r\n\t\tsplit.add(s1);\r\n\t\tsplit.add(s2);\r\n\t\treturn split;\r\n\t}\r\n}" }, { "alpha_fraction": 0.7491349577903748, "alphanum_fraction": 0.75, "avg_line_length": 24.130434036254883, "blob_id": "f94df6c87bf3b3ce49b8014959749c019d68108e", "content_id": "c0f689ff860ad3a5c4d752ecda4ebe934f49983d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1156, "license_type": "no_license", "max_line_length": 128, "num_lines": 46, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/random/RandomSearchFactory.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.random;\n\nimport jaicore.search.core.interfaces.StandardORGraphSearchFactory;\nimport jaicore.search.model.probleminputs.GraphSearchInput;\n\npublic class RandomSearchFactory<N, A> extends StandardORGraphSearchFactory<GraphSearchInput<N, A>, Object,N, A, Double, N, A> {\n\n\tprivate int timeoutForFInMS;\n\tprivate String loggerName;\n\tprivate int seed;\n\n\tpublic RandomSearchFactory() {\n\t\tsuper();\n\t}\n\n\tpublic RandomSearchFactory(final int timeoutForFInMS) {\n\t\tthis();\n\t\tif (timeoutForFInMS > 0) {\n\t\t\tthis.timeoutForFInMS = timeoutForFInMS;\n\t\t}\n\t}\n\n\t@Override\n\tpublic RandomSearch<N, A> getAlgorithm() {\n\t\tif (getProblemInput().getGraphGenerator() == null)\n\t\t\tthrow new IllegalStateException(\"Cannot produce RandomSearch searches before the graph generator is set in the problem.\");\n\t\tRandomSearch<N, A> search = new RandomSearch<>(getProblemInput(), seed);\n\t\treturn search;\n\t}\n\n\tpublic int getSeed() {\n\t\treturn seed;\n\t}\n\n\tpublic void setSeed(int seed) {\n\t\tthis.seed = seed;\n\t}\n\n\tpublic String getLoggerName() {\n\t\treturn loggerName;\n\t}\n\n\tpublic void setLoggerName(String loggerName) {\n\t\tthis.loggerName = loggerName;\n\t}\n}\n" }, { "alpha_fraction": 0.7066666483879089, "alphanum_fraction": 0.7066666483879089, "avg_line_length": 11.5, "blob_id": "c7638c5a195d46aa623b1e7807ba222a8a0e077f", "content_id": "cb6d361e9e7a800955077a71611905456fc33ea2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 75, "license_type": "no_license", "max_line_length": 24, "num_lines": 6, "path": "/JAICore/jaicore-basic/src/jaicore/basic/Score.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.basic;\n\npublic interface Score {\n\n double getScore();\n}\n" }, { "alpha_fraction": 0.6873519420623779, "alphanum_fraction": 0.6906679272651672, "avg_line_length": 25.415584564208984, "blob_id": "14fcefa7de4566f37750cbba92fb48b5a151b889", "content_id": "155ea0e366485d46f8641dbb9db4b81e66de557a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2111, "license_type": "no_license", "max_line_length": 82, "num_lines": 77, "path": "/softwareconfiguration/mlplan/src/de/upb/crc901/mlplan/multiclass/wekamlplan/sophisticated/featuregen/PolynomialFeatures.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package de.upb.crc901.mlplan.multiclass.wekamlplan.sophisticated.featuregen;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\n\r\nimport weka.core.Attribute;\r\nimport weka.core.DenseInstance;\r\nimport weka.core.Instance;\r\nimport weka.core.Instances;\r\n\r\npublic class PolynomialFeatures implements FeatureGenerator {\r\n\t\r\n\tprivate boolean isPrepared;\r\n\tprivate int potence = 2;\r\n\tprivate List<Integer> indicesToSquare = new ArrayList<>();\r\n\r\n\t@Override\r\n\tpublic void prepare(Instances data) throws Exception {\r\n\t\tArrayList<Attribute> attributes = new ArrayList<>();\r\n\t\tindicesToSquare.clear();\r\n\t\tfor (int i = 0; i < data.numAttributes(); i++) {\r\n\t\t\tif (data.attribute(i).isNumeric()) {\r\n\t\t\t\tattributes.add(new weka.core.Attribute(\"q\" + i, false));\r\n\t\t\t\tindicesToSquare.add(i);\r\n\t\t\t}\r\n\t\t}\r\n//\t\tInstances squares = new Instances(\"squares\", attributes, data.size());\r\n\t\tisPrepared = true;\r\n\t}\r\n\t\r\n\tprivate Instances getEmptyDataset() {\r\n\t\tif (!isPrepared)\r\n\t\t\tthrow new IllegalStateException(\"Cannot get empty dataset before preparation\");\r\n\t\tArrayList<Attribute> attributes = new ArrayList<>();\r\n\t\tfor (int indexToSquare : indicesToSquare) {\r\n\t\t\tattributes.add(new Attribute(\"pow_\" + potence + \"_\" + indexToSquare, false));\r\n\t\t}\r\n\t\treturn new Instances(\"potences\", attributes, 0);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic Instance apply(Instance data) throws Exception {\r\n\t\tInstance copy = new DenseInstance(indicesToSquare.size());\r\n\t\tint i = 0;\r\n\t\tfor (int index : indicesToSquare) {\r\n\t\t\tcopy.setValue(i++,Math.pow(data.value(index), potence));\r\n\t\t}\r\n\t\tInstances dataset = getEmptyDataset();\r\n\t\tdataset.add(copy);\r\n\t\tcopy.setDataset(dataset);\r\n\t\treturn copy;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic Instances apply(Instances data) throws Exception {\r\n\t\tInstances copy = getEmptyDataset();\r\n\t\tfor (Instance inst : data) {\r\n\t\t\tInstance modInst = apply(inst);\r\n\t\t\tcopy.add(modInst);\r\n\t\t\tmodInst.setDataset(copy);\r\n\t\t}\r\n\t\treturn copy;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean isPrepared() {\r\n\t\treturn isPrepared;\r\n\t}\r\n\r\n\tpublic int getPotence() {\r\n\t\treturn potence;\r\n\t}\r\n\r\n\tpublic void setPotence(int potence) {\r\n\t\tthis.potence = potence;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.721586287021637, "alphanum_fraction": 0.7248569130897522, "avg_line_length": 29.19753074645996, "blob_id": "db7d4f56cbf3595285180d2cc65d62f79b5dce57", "content_id": "28e8caf6d7cef805b9071469ea3996b9fa5feba4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2446, "license_type": "no_license", "max_line_length": 94, "num_lines": 81, "path": "/softwareconfiguration/hasco/src/hasco/metamining/MetaMinerBasedSorter.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package hasco.metamining;\n\nimport java.util.Comparator;\n\nimport hasco.core.HASCO;\nimport hasco.core.Util;\nimport hasco.model.ComponentInstance;\nimport hasco.serialization.ComponentLoader;\nimport jaicore.planning.graphgenerators.task.tfd.TFDNode;\n\n/**\n * A Comparator for {@link TFDNode}s that sorts based on meta information about\n * the underlying {@link ComponentInstance} of the node and possibly application\n * context.\n * \n * @author Helena Graf\n *\n */\npublic class MetaMinerBasedSorter implements Comparator<TFDNode> {\n\n\t/**\n\t * The ComponentLoader object used to get the available components\n\t */\n\tprivate ComponentLoader loader;\n\n\t/**\n\t * The \"MetaMiner\" has access to the meta information of the given\n\t * {@link ComponentInstance} and possibly its application context. It is used to\n\t * derive a score of a given ComponentInstance, based on which a comparison of\n\t * the given {@link TFDNode}s is made.\n\t */\n\tprivate IMetaMiner metaminer;\n\n\t/**\n\t * Creates a new MetaminerBasedSorter object that compares given\n\t * {@link TFDNode}s based on the attached {@link ComponentInstance}.\n\t * \n\t * @param metaminer\n\t * The {@link IMetaMiner} used to score the ComponentInstances\n\t * attached to a TFDNode. Has to already have been built.\n\t * @param hasco\n\t * The {@link HASCO} object used to get the available components\n\t */\n\tpublic MetaMinerBasedSorter(IMetaMiner metaminer, ComponentLoader loader) {\n\t\tthis.loader = loader;\n\t\tthis.metaminer = metaminer;\n\t}\n\n\t@Override\n\tpublic int compare(TFDNode o1, TFDNode o2) {\n\t\tdouble score1 = metaminer.score(convertToComponentInstance(o1));\n\t\tdouble score2 = metaminer.score(convertToComponentInstance(o2));\n\n\t\treturn (int) Math.signum(score1 - score2);\n\t}\n\n\tprivate ComponentInstance convertToComponentInstance(TFDNode node) {\n\t\treturn Util.getSolutionCompositionFromState(loader.getComponents(), node.getState(), false);\n\t}\n\n\t/**\n\t * Gets the {@link IMetaMiner}, which is used to derive a score for a given\n\t * {@link TFDNode} based on its attached {@link ComponentInstance}.\n\t * \n\t * @return The meta miner\n\t */\n\tpublic IMetaMiner getMetaminer() {\n\t\treturn metaminer;\n\t}\n\n\t/**\n\t * Sets the {@link IMetaMiner}, which is used to derive a score for a given\n\t * {@link TFDNode} based on its attached {@link ComponentInstance}.\n\t * \n\t * @param metaminer\n\t * The meta miner\n\t */\n\tpublic void setMetaminer(IMetaMiner metaminer) {\n\t\tthis.metaminer = metaminer;\n\t}\n}\n" }, { "alpha_fraction": 0.7426655292510986, "alphanum_fraction": 0.7502095699310303, "avg_line_length": 27.428571701049805, "blob_id": "cb17ab57908c7eaa31e683396c87e849c62181d7", "content_id": "6784f115566f58a9669f30159529797794f10813", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1193, "license_type": "no_license", "max_line_length": 84, "num_lines": 42, "path": "/JAICore/jaicore-ml/src/jaicore/ml/classification/multiclass/reduction/splitters/RandomSplitter.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.ml.classification.multiclass.reduction.splitters;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Random;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport jaicore.ml.WekaUtil;\nimport weka.core.Instances;\n\npublic class RandomSplitter implements ISplitter {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(RandomSplitter.class);\n\tprivate final Random rand;\n\n\tpublic RandomSplitter(Random rand) {\n\t\tsuper();\n\t\tthis.rand = rand;\n\t}\n\n\t@Override\n\tpublic Collection<Collection<String>> split(Instances data) throws Exception {\n\t\tCollection<Collection<String>> split = new ArrayList<>();\n\t\tCollection<String> classes = WekaUtil.getClassesActuallyContainedInDataset(data);\n\t\tif (classes.size() == 1) {\n\t\t\tsplit.add(classes);\n\t\t\treturn split;\n\t\t}\n\t\tList<String> copy = new ArrayList<>(classes);\n\t\tCollections.shuffle(copy, rand);\n\t\tint splitIndex = (int)Math.ceil(Math.random()*(classes.size() - 1));\n\t\tCollection<String> s1 = copy.subList(0, splitIndex);\n\t\tCollection<String> s2 = copy.subList(splitIndex, copy.size());\n\t\tsplit.add(s1);\n\t\tsplit.add(s2);\n\t\treturn split;\n\t}\n}" }, { "alpha_fraction": 0.7565217614173889, "alphanum_fraction": 0.7565217614173889, "avg_line_length": 18.33333396911621, "blob_id": "958df7e2cc25966d264df3c490bd0dfbcc4c9abe", "content_id": "8737474c414a3865e95a132293fb62b4569485a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 115, "license_type": "no_license", "max_line_length": 28, "num_lines": 6, "path": "/gradle.properties", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "nexusBaseUrl=\"\"\nnexusUpRepo=\"\"\nnexusUser=\"\"\nnexusPassword=\"\"\nsystemProp.sonar.host.url=\"\"\nsystemProp.sonar.login=\"\"" }, { "alpha_fraction": 0.7521197199821472, "alphanum_fraction": 0.7551122307777405, "avg_line_length": 32.41666793823242, "blob_id": "610b53f60e202c3cf2bbd3178879594daa3f1412", "content_id": "fa697e3dc77ad576027634064dbbfe7925d8ae24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2005, "license_type": "no_license", "max_line_length": 132, "num_lines": 60, "path": "/JAICore/jaicore-ml/src/jaicore/ml/multilabel/evaluators/MonteCarloCrossValidationEvaluator.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.ml.multilabel.evaluators;\n\nimport org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport jaicore.basic.IObjectEvaluator;\nimport meka.classifiers.multilabel.MultiLabelClassifier;\nimport weka.core.Instances;\n\npublic class MonteCarloCrossValidationEvaluator implements IObjectEvaluator<MultiLabelClassifier, Double> {\n\n\tstatic final Logger logger = LoggerFactory.getLogger(MonteCarloCrossValidationEvaluator.class);\n\tprivate final MultilabelEvaluator basicEvaluator;\n\tprivate final Instances data;\n\tprivate boolean canceled = false;\n\tprivate final int repeats;\n\tprivate final float trainingPortion;\n\n\tpublic MonteCarloCrossValidationEvaluator(MultilabelEvaluator basicEvaluator, int repeats, Instances data, float trainingPortion) {\n\t\tsuper();\n\t\tthis.basicEvaluator = basicEvaluator;\n\t\tthis.repeats = repeats;\n\t\tif (data == null)\n\t\t\tthrow new IllegalArgumentException(\"NULL data given to MCCV!\");\n\t\tthis.data = data;\n\t\tthis.trainingPortion = trainingPortion;\n\t}\n\n\tpublic void cancel() {\n\t\tlogger.info(\"Received cancel\");\n\t\tthis.canceled = true;\n\t}\n\t\n\t@Override\n\tpublic Double evaluate(MultiLabelClassifier pl) throws Exception {\n\t\t\n\t\tif (pl == null)\n\t\t\tthrow new IllegalArgumentException(\"Cannot compute score for null pipeline!\");\n\n\t\t/* perform random stratified split */\n\t\tDescriptiveStatistics stats = new DescriptiveStatistics();\n\t\tlogger.info(\"Starting evaluation of {}\", pl);\n\t\tfor (int i = 0; i < repeats && !canceled; i++) {\n\t\t\tlogger.info(\"Evaluating {} with split #{}/{}\", pl, i + 1, repeats);\n\t\t\tdouble score = basicEvaluator.getErrorRateForRandomSplit(pl, data, trainingPortion);\n\t\t\tlogger.info(\"Score for evaluation of {} with split #{}/{}: {}\", pl, i + 1, repeats, score);\n\t\t\tstats.addValue(score);\n\t\t}\n\n\t\tDouble score = stats.getMean();\n\t\tlogger.info(\"Obtained score of {} for classifier {}.\", score, pl);\n\t\treturn score;\n\t}\n\n\tpublic MultilabelEvaluator getEvaluator() {\n\t\treturn basicEvaluator;\n\t}\n\n}\n" }, { "alpha_fraction": 0.6555555462837219, "alphanum_fraction": 0.6555555462837219, "avg_line_length": 16, "blob_id": "adc94da55bb0e2a43cd66e4f4f95232d5b05f487", "content_id": "e3886877d35b996ff86f5ba816442fc56e4e532b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 360, "license_type": "no_license", "max_line_length": 59, "num_lines": 20, "path": "/JAICore/jaicore-basic/src/jaicore/basic/algorithm/IOptimizerResult.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.basic.algorithm;\r\n\r\npublic class IOptimizerResult<O, V extends Comparable<V>> {\r\n\tprivate final O result;\r\n\tprivate final V value;\r\n\r\n\tpublic IOptimizerResult(O result, V value) {\r\n\t\tsuper();\r\n\t\tthis.result = result;\r\n\t\tthis.value = value;\r\n\t}\r\n\r\n\tpublic O getResult() {\r\n\t\treturn result;\r\n\t}\r\n\r\n\tpublic V getValue() {\r\n\t\treturn value;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.621201753616333, "alphanum_fraction": 0.6275988221168518, "avg_line_length": 28.775510787963867, "blob_id": "aa3d290093a264465846093f65eeb29c5a4d7ff6", "content_id": "65a2bffc31e49abd730330d0d25548d224fccfbe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4377, "license_type": "no_license", "max_line_length": 169, "num_lines": 147, "path": "/JAICore/jaicore-search/test/jaicore/search/algorithms/standard/gbf/GeneralBestFirstTester.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "//package jaicore.search.algorithms.standard.gbf;\n//\n//import static org.junit.Assert.assertNotNull;\n//\n//import java.util.ArrayList;\n//\n//import org.junit.Test;\n//\n//import jaicore.graph.Graph;\n//import jaicore.graphvisualizer.SimpleGraphVisualizationWindow;\n//import jaicore.search.algorithms.standard.bestfirst.model.GraphGenerator;\n//import jaicore.search.algorithms.standard.bestfirst.model.Node;\n//import jaicore.search.algorithms.standard.bestfirst.nodeevaluation.INodeEvaluator;\n//import jaicore.search.structure.graphgenerator.NodeGoalTester;\n//import jaicore.search.structure.graphgenerator.SingleRootGenerator;\n//import jaicore.search.structure.graphgenerator.SuccessorGenerator;\n//\n//public class GeneralBestFirstTester {\n//\t\n//\tprivate static final boolean VISUALIZE = true;\n//\n//\tstatic class GameNode {\n//\t\t\n//\t\tfinal boolean active;\n//\t\tfinal int remaining;\n//\t\tpublic GameNode(boolean active, int remaining) {\n//\t\t\tsuper();\n//\t\t\tthis.active = active;\n//\t\t\tthis.remaining = remaining;\n//\t\t}\n//\t\t@Override\n//\t\tpublic int hashCode() {\n//\t\t\tfinal int prime = 31;\n//\t\t\tint result = 1;\n//\t\t\tresult = prime * result + (active ? 1231 : 1237);\n//\t\t\tresult = prime * result + remaining;\n//\t\t\treturn result;\n//\t\t}\n//\t\t@Override\n//\t\tpublic boolean equals(Object obj) {\n//\t\t\tif (this == obj)\n//\t\t\t\treturn true;\n//\t\t\tif (obj == null)\n//\t\t\t\treturn false;\n//\t\t\tif (getClass() != obj.getClass())\n//\t\t\t\treturn false;\n//\t\t\tGameNode other = (GameNode) obj;\n//\t\t\tif (active != other.active)\n//\t\t\t\treturn false;\n//\t\t\tif (remaining != other.remaining)\n//\t\t\t\treturn false;\n//\t\t\treturn true;\n//\t\t}\n//\t\t\n//\t\t@Override\n//\t\tpublic String toString() {\n//\t\t\treturn \"GameNode [active=\" + active + \", remaining=\" + remaining + \"]\";\n//\t\t}\n//\t}\n//\t\n//\tstatic class GameAction {\n//\t\tfinal String name;\n//\n//\t\tpublic GameAction(String name) {\n//\t\t\tsuper();\n//\t\t\tthis.name = name;\n//\t\t}\n//\t}\n//\n//\t@Test\n//\tpublic void test() {\n//\t\t\n//\t\tGraphGenerator<GameNode, GameAction> gen = new GraphGenerator<GeneralBestFirstTester.GameNode, GeneralBestFirstTester.GameAction>() {\n//\n//\t\t\t@Override\n//\t\t\tpublic SingleRootGenerator<GameNode> getRootGenerator() {\n//\t\t\t\treturn () -> new GameNode(true, 20);\n//\t\t\t}\n//\n//\t\t\t@Override\n//\t\t\tpublic SuccessorGenerator<GameNode, GameAction> getSuccessorGenerator() {\n//\t\t\t\treturn n -> {\n//\t\t\t\t\treturn new ArrayList<>();\t\n////\t\t\t\t\tif (n instanceof OrNode) { \n////\t\t\t\t\t\tList<NodeExpansionDescription<GameNode,GameAction>> successors = new ArrayList<>();\n////\t\t\t\t\t\tGameNode g = n.getPoint();\n////\t\t\t\t\t\tfor (int i = 0; i < 4; i++)\n////\t\t\t\t\t\t\tif (g.remaining > i)\n////\t\t\t\t\t\t\t\tsuccessors.add(new NodeExpansionDescription<>(n.getPoint(), new GameNode(false, g.remaining - i - 1), new GameAction(\"Take \" + (i + 1)), NodeType.AND));\n////\t\t\t\t\t\treturn successors;\n////\t\t\t\t\t}\n////\t\t\t\t\telse {\n////\t\t\t\t\t\tList<NodeExpansionDescription<GameNode,GameAction>> successors = new ArrayList<>();\n////\t\t\t\t\t\tGameNode g = n.getPoint();\n////\t\t\t\t\t\tfor (int i = 0; i < 2; i++)\n////\t\t\t\t\t\t\tif (g.remaining > i)\n////\t\t\t\t\t\t\t\tsuccessors.add(new NodeExpansionDescription<>(n.getPoint(), new GameNode(true, g.remaining - i - 1), new GameAction(\"Enemy takes \" + (i + 1)), NodeType.OR));\n////\t\t\t\t\t\treturn successors;\t\t\t\t\t\t\n////\t\t\t\t\t}\n//\t\t\t\t};\n//\t\t\t}\n//\n//\t\t\t@Override\n//\t\t\tpublic NodeGoalTester<GameNode> getGoalTester() {\n//\t\t\t\treturn l -> l.active && l.remaining == 0;\n//\t\t\t}\n//\n//\t\t\t@Override\n//\t\t\tpublic boolean isSelfContained() {\n//\t\t\t\t\n//\t\t\t\treturn false;\n//\t\t\t}\n//\n//\t\t\t@Override\n//\t\t\tpublic void setNodeNumbering(boolean nodenumbering) {\n//\t\t\t\t// TODO Auto-generated method stub\n//\t\t\t\t\n//\t\t\t}\n//\t\t};\n//\t\t\n//\t\tINodeEvaluator<GameNode, Integer> evaluator = new INodeEvaluator<GameNode,Integer>() {\n//\t\t\t@Override\n//\t\t\tpublic Integer f(Node<GameNode,?> path) {\n//\t\t\t\treturn 0;\n//\t\t\t}\n//\t\t};\n//\n//\t\tGeneralBestFirst<GameNode,GameAction> gbf = new GeneralBestFirst<GameNode,GameAction>(gen, map -> new ArrayList<>(map.keySet()), l -> 0, evaluator);\n//\t\t\n//\t\t\n//\t\t/* find solution */\n//\t\tif (VISUALIZE) {\n//\t\t\tnew SimpleGraphVisualizationWindow<>(gbf);\n//\t\t}\n//\t\tGraph<GameNode> solutionGraph = gbf.getSolution();\n//\t\tassertNotNull(solutionGraph);\n//\t\tSystem.out.println(\"Generated \" + gbf.getCreatedCounter() + \" nodes.\");\n//\t\tif (VISUALIZE) {\n//\t\t\tnew SimpleGraphVisualizationWindow<GameNode>(solutionGraph);\n//\t\t\tint j = 0;\n//\t\t\tint i = 0;\n//\t\t\twhile (j >= 0)\n//\t\t\t\ti = i + 1;\n//\t\t}\n//\t}\n//\n//}\n" }, { "alpha_fraction": 0.6968043446540833, "alphanum_fraction": 0.7022603154182434, "avg_line_length": 24.183673858642578, "blob_id": "dd011c2dc0fe983410ea5e450a2e419c596878b3", "content_id": "35c8c833bee6855a63529bc2b4428ead7eb8c19f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1283, "license_type": "no_license", "max_line_length": 122, "num_lines": 49, "path": "/softwareconfiguration/mlplan/src/de/upb/crc901/reduction/ensemble/simple/MySQLEnsembleOfSimpleOneStepReductionsExperiment.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package de.upb.crc901.reduction.ensemble.simple;\r\n\r\npublic class MySQLEnsembleOfSimpleOneStepReductionsExperiment {\r\n\tprivate final int id;\r\n\tprivate final EnsembleOfSimpleOneStepReductionsExperiment experiment;\r\n\r\n\tpublic MySQLEnsembleOfSimpleOneStepReductionsExperiment(int id, EnsembleOfSimpleOneStepReductionsExperiment experiment) {\r\n\t\tsuper();\r\n\t\tthis.id = id;\r\n\t\tthis.experiment = experiment;\r\n\t}\r\n\r\n\tpublic int getId() {\r\n\t\treturn id;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + ((experiment == null) ? 0 : experiment.hashCode());\r\n\t\tresult = prime * result + id;\r\n\t\treturn result;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean equals(Object obj) {\r\n\t\tif (this == obj)\r\n\t\t\treturn true;\r\n\t\tif (obj == null)\r\n\t\t\treturn false;\r\n\t\tif (getClass() != obj.getClass())\r\n\t\t\treturn false;\r\n\t\tMySQLEnsembleOfSimpleOneStepReductionsExperiment other = (MySQLEnsembleOfSimpleOneStepReductionsExperiment) obj;\r\n\t\tif (experiment == null) {\r\n\t\t\tif (other.experiment != null)\r\n\t\t\t\treturn false;\r\n\t\t} else if (!experiment.equals(other.experiment))\r\n\t\t\treturn false;\r\n\t\tif (id != other.id)\r\n\t\t\treturn false;\r\n\t\treturn true;\r\n\t}\r\n\r\n\tpublic EnsembleOfSimpleOneStepReductionsExperiment getExperiment() {\r\n\t\treturn experiment;\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.7536723017692566, "alphanum_fraction": 0.7568361759185791, "avg_line_length": 43.15306091308594, "blob_id": "d8c86ceba1fbc1d3dd9b4a51aae85119c4916301", "content_id": "49213e2ff91d5f362df4fd0b52a2b43ebaddbf1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4425, "license_type": "no_license", "max_line_length": 297, "num_lines": 98, "path": "/softwareconfiguration/mlplan/src/de/upb/crc901/reduction/single/heterogeneous/bestofkrandom/MySQLReductionExperimentRunnerWrapper.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package de.upb.crc901.reduction.single.heterogeneous.bestofkrandom;\r\n\r\nimport java.io.File;\r\nimport java.io.FileNotFoundException;\r\nimport java.io.IOException;\r\nimport java.sql.ResultSet;\r\nimport java.sql.SQLException;\r\nimport java.util.Collection;\r\nimport java.util.HashMap;\r\nimport java.util.HashSet;\r\nimport java.util.Map;\r\nimport java.util.Optional;\r\nimport java.util.Random;\r\n\r\nimport de.upb.crc901.reduction.single.BestOfKAtRandomExperiment;\r\nimport de.upb.crc901.reduction.single.ExperimentRunner;\r\nimport de.upb.crc901.reduction.single.MySQLReductionExperiment;\r\nimport jaicore.basic.SQLAdapter;\r\nimport jaicore.ml.classification.multiclass.reduction.splitters.RandomSplitter;\r\n\r\npublic class MySQLReductionExperimentRunnerWrapper {\r\n\r\n\tprivate static final String TABLE_NAME = \"reductionstumps_heterogeneous_random_bestofk\";\r\n\tprivate final SQLAdapter adapter;\r\n\tprivate final Collection<MySQLReductionExperiment> knownExperiments = new HashSet<>();\r\n\tprivate final int k;\r\n\tprivate final int mccvrepeats;\r\n\r\n\tpublic MySQLReductionExperimentRunnerWrapper(String host, String user, String password, String database, int k, int mccvRepeats) {\r\n\t\tadapter = new SQLAdapter(host, user, password, database);\r\n\t\tthis.k = k;\r\n\t\tthis.mccvrepeats = mccvRepeats;\r\n\t\ttry {\r\n\t\t\tknownExperiments.addAll(getConductedExperiments());\r\n\t\t} catch (SQLException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic Collection<MySQLReductionExperiment> getConductedExperiments() throws SQLException {\r\n\t\tCollection<MySQLReductionExperiment> experiments = new HashSet<>();\r\n\t\tResultSet rs = adapter.getRowsOfTable(TABLE_NAME);\r\n\t\twhile (rs.next()) {\r\n\t\t\texperiments.add(new MySQLReductionExperiment(rs.getInt(\"evaluation_id\"), new BestOfKAtRandomExperiment(rs.getInt(\"seed\"), rs.getString(\"dataset\"), rs.getString(\"left_classifier\"), rs.getString(\"inner_classifier\"), rs.getString(\"right_classifier\"), rs.getInt(\"k\"), rs.getInt(\"mccvrepeats\"))));\r\n\t\t}\r\n\t\treturn experiments;\r\n\t}\r\n\r\n\tpublic MySQLReductionExperiment createAndGetExperimentIfNotConducted(int seed, File dataFile, String nameOfLeftClassifier, String nameOfInnerClassifier, String nameOfRightClassifier) throws FileNotFoundException, IOException {\r\n\t\t\r\n\t\t/* first check whether exactly the same experiment (with the same seed) has been conducted previously */\r\n\t\tBestOfKAtRandomExperiment exp = new BestOfKAtRandomExperiment(seed, dataFile.getAbsolutePath(), nameOfLeftClassifier, nameOfInnerClassifier, nameOfRightClassifier, k, mccvrepeats);\r\n\t\tOptional<MySQLReductionExperiment> existingExperiment = knownExperiments.stream().filter(e -> e.getExperiment().equals(exp)).findAny();\r\n\t\tif (existingExperiment.isPresent())\r\n\t\t\treturn null;\r\n\t\t\r\n\t\tMap<String, Object> map = new HashMap<>();\r\n\t\tmap.put(\"seed\", seed);\r\n\t\tmap.put(\"dataset\", dataFile.getAbsolutePath());\r\n\t\tmap.put(\"left_classifier\", nameOfLeftClassifier);\r\n\t\tmap.put(\"inner_classifier\", nameOfInnerClassifier);\r\n\t\tmap.put(\"right_classifier\", nameOfRightClassifier);\r\n\t\tmap.put(\"k\", k);\r\n\t\tmap.put(\"mccvrepeats\", mccvrepeats);\r\n\t\ttry {\r\n\t\t\tint id = adapter.insert(TABLE_NAME, map);\r\n\t\t\treturn new MySQLReductionExperiment(id, exp);\r\n\t\t} catch (SQLException e) {\r\n\t\t\tSystem.err.println(e.getMessage());\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate void updateExperiment(MySQLReductionExperiment exp, Map<String,? extends Object> values) throws SQLException {\r\n\t\tMap<String,String> where = new HashMap<>();\r\n\t\twhere.put(\"evaluation_id\", String.valueOf(exp.getId()));\r\n\t\tadapter.update(TABLE_NAME, values, where);\r\n\t}\r\n\t\r\n\tpublic void conductExperiment(MySQLReductionExperiment exp) throws Exception {\r\n\t\tExperimentRunner<RandomSplitter> runner = new ExperimentRunner<RandomSplitter>(k, mccvrepeats, (seed) -> new RandomSplitter(new Random(seed)));\r\n\t\tMap<String,Object> results = runner.conductSingleOneStepReductionExperiment(exp.getExperiment());\r\n\t\tupdateExperiment(exp, results);\r\n\t}\r\n\t\r\n\tpublic void markExperimentAsUnsolvable(MySQLReductionExperiment exp) throws SQLException {\r\n\t\tMap<String, String> values = new HashMap<>();\r\n\t\tvalues.put(\"errorRate\", \"-1\");\r\n\t\tupdateExperiment(exp, values);\r\n\t}\r\n\t\r\n\tpublic void associateExperimentWithException(MySQLReductionExperiment exp, Throwable e) throws SQLException {\r\n\t\tMap<String, String> values = new HashMap<>();\r\n\t\t values.put(\"errorRate\", \"-1\");\r\n\t\tvalues.put(\"exception\", e.getClass().getName() + \"\\n\" + e.getMessage());\r\n\t\tupdateExperiment(exp, values);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.8296783566474915, "alphanum_fraction": 0.8296783566474915, "avg_line_length": 52.720001220703125, "blob_id": "7bf5fd8f4f43dfb9204a0fb89d2a908e27194239", "content_id": "261a83cfa11eceac2c0b11136c68eda9cbd52517", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1368, "license_type": "no_license", "max_line_length": 213, "num_lines": 25, "path": "/JAICore/jaicore-search/test/jaicore/search/algorithms/standard/bestfirst/BestFirstNQueensTester.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.bestfirst;\r\n\r\nimport jaicore.basic.algorithm.AlgorithmProblemTransformer;\r\nimport jaicore.search.core.interfaces.IGraphSearchFactory;\r\nimport jaicore.search.model.other.EvaluatedSearchGraphPath;\r\nimport jaicore.search.model.probleminputs.GeneralEvaluatedTraversalTree;\r\nimport jaicore.search.model.travesaltree.Node;\r\nimport jaicore.search.testproblems.nqueens.NQueenTester;\r\nimport jaicore.search.testproblems.nqueens.NQueensToGeneralTravesalTreeReducer;\r\nimport jaicore.search.testproblems.nqueens.QueenNode;\r\n\r\npublic class BestFirstNQueensTester\r\n\t\textends NQueenTester<GeneralEvaluatedTraversalTree<QueenNode, String, Double>, EvaluatedSearchGraphPath<QueenNode, String, Double>, Node<QueenNode, Double>, String> {\r\n\r\n\t@Override\r\n\tpublic IGraphSearchFactory<GeneralEvaluatedTraversalTree<QueenNode, String, Double>, EvaluatedSearchGraphPath<QueenNode, String, Double>, QueenNode, String, Double, Node<QueenNode, Double>, String> getFactory() {\r\n\t\tBestFirstFactory<GeneralEvaluatedTraversalTree<QueenNode, String, Double>,QueenNode, String, Double> searchFactory = new BestFirstFactory<>();\r\n\t\treturn searchFactory;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic AlgorithmProblemTransformer<Integer, GeneralEvaluatedTraversalTree<QueenNode, String, Double>> getProblemReducer() {\r\n\t\treturn new NQueensToGeneralTravesalTreeReducer();\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6921482682228088, "alphanum_fraction": 0.6985954642295837, "avg_line_length": 37.84403610229492, "blob_id": "1c113a8847b02c9b1100d22542ae2083348e8095", "content_id": "960cc9b908335c9069b95b8aeaa4ece24c0bf925", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4343, "license_type": "no_license", "max_line_length": 135, "num_lines": 109, "path": "/JAICore/jaicore-search/test/jaicore/search/algorithms/standard/bestfirst/abstractVersioning/AbstractVersioningTester.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "//package jaicore.search.algorithms.standard.bestfirst.abstractVersioning;\r\n//\r\n//import static org.junit.Assert.assertEquals;\r\n//import static org.junit.Assert.assertFalse;\r\n//import static org.junit.Assert.assertNotNull;\r\n//import static org.junit.Assert.assertTrue;\r\n//import static org.junit.Assert.fail;\r\n//\r\n//import java.util.HashSet;\r\n//import java.util.List;\r\n//import java.util.Set;\r\n//\r\n//import org.junit.Test;\r\n//\r\n//import jaicore.graph.IGraphAlgorithmListener;\r\n//import jaicore.search.algorithms.EvaluatedSearchAlgorithmSolution;\r\n//import jaicore.search.algorithms.interfaces.IORGraphSearch;\r\n//import jaicore.search.algorithms.interfaces.IORGraphSearchFactory;\r\n//import jaicore.search.algorithms.standard.ORGraphSearchTester;\r\n//import jaicore.search.algorithms.standard.bestfirst.BestFirst;\r\n//import jaicore.search.algorithms.standard.bestfirst.model.NodeExpansionDescription;\r\n//import jaicore.search.testproblems.bestfirst.abstractVersioning.TestGraphGenerator;\r\n//import jaicore.search.testproblems.bestfirst.abstractVersioning.TestNode;\r\n//import jaicore.search.testproblems.nqueens.QueenNode;\r\n//\r\n//public class AbstractVersioningTester<O> extends ORGraphSearchTester<TestNode, String, Double> {\r\n//\r\n//\tpublic void testSequential(IORGraphSearchFactory<V, E, IGraphAlgorithmListener<V, E>, O> factory) throws InterruptedException {\r\n//\t\tTestGraphGenerator gen = new TestGraphGenerator();\r\n//\r\n//\t\tBestFirst<TestNode, String, Double> bf = new BestFirst<>(gen, n -> (double) Math.round(Math.random() * 100));\r\n//\r\n//\t\t// new SimpleGraphVisualizationWindow<>(bf.getEventBus()).getPanel().setTooltipGenerator(n-> String.valueOf(n.getInternalLabel()));\r\n//\r\n//\t\t// set node numbering to false\r\n//\t\tgen.setNodeNumbering(false);\r\n//\r\n//\t\t/*find the solution*/\r\n//\t\tEvaluatedSearchAlgorithmSolution<TestNode, String, Double> solution = bf.nextSolution();\r\n//\t\tList<TestNode> solutionPath = solution.getNodes();\r\n//\t\tsolutionPath.stream().forEach(n -> {\r\n//\t\t\tassertEquals(n.getId(), -1);\r\n//\t\t});\r\n//\r\n//\t\t/*second test now with numbering.\r\n//\t\t */\r\n//\t\tgen.reset();\r\n//\t\tbf = new BestFirst<>(gen, n -> (double) Math.round(Math.random() * 100));\r\n//\t\t// new SimpleGraphVisualizationWindow<>(bf.getEventBus()).getPanel().setTooltipGenerator(n-> String.valueOf(n.getInternalLabel()));\r\n//\t\tgen.setNodeNumbering(true);\r\n//\t\tEvaluatedSearchAlgorithmSolution<TestNode, String, Double> solution2 = bf.nextSolution();\r\n//\t\tList<TestNode> solutionPath2 = solution2.getNodes();\r\n//\t\tSet<Integer> ids = new HashSet<Integer>();\r\n//\r\n//\t\tsolutionPath2.stream().forEach(n -> {\r\n//\t\t\tassertTrue(n.getId() > 0);\r\n//\t\t\tassertFalse(ids.contains(n.getId()));\r\n//\r\n//\t\t\tids.add(n.getId());\r\n//\t\t});\r\n//\r\n//\t}\r\n//\r\n//\tpublic void testParallelized(IORGraphSearchFactory<V, E, IGraphAlgorithmListener<V, E>, O> factory) throws InterruptedException {\r\n//\t\tTestGraphGenerator gen = new TestGraphGenerator();\r\n//\t\tgen.setNodeNumbering(true);\r\n//\r\n//\t\tBestFirst<TestNode, String, Double> bf = new BestFirst<>(gen, n -> (double) Math.round(Math.random() * 100));\r\n//\t\tbf.parallelizeNodeExpansion(2);\r\n//\t\tbf.setTimeoutForComputationOfF(350, node -> 100.0);\r\n//\r\n//\t\tEvaluatedSearchAlgorithmSolution<TestNode, String, Double> solution2 = bf.nextSolution();\r\n//\t\tList<TestNode> solutionPath2 = solution2.getNodes();\r\n//\t\tSet<Integer> ids = new HashSet<Integer>();\r\n//\r\n//\t\tsolutionPath2.stream().forEach(n -> {\r\n//\t\t\tassertTrue(n.getId() > 0);\r\n//\t\t\tassertFalse(ids.contains(n.getId()));\r\n//\r\n//\t\t\tids.add(n.getId());\r\n//\t\t});\r\n//\r\n//\t}\r\n//\r\n//\tpublic void testIterable(IORGraphSearchFactory<TestNode, String, IGraphAlgorithmListener<TestNode, String>, Double> factory) {\r\n//\t\tTestGraphGenerator gen = new TestGraphGenerator();\r\n//\t\tgen.setNodeNumbering(true);\r\n//\r\n//\t\tSet<Integer> ids = new HashSet<Integer>();\r\n//\r\n//\t\tIORGraphSearch<TestNode, String, ?, ?> bf = factory.getAlgorithm();\r\n//\r\n//\t\t/*find the solution*/\r\n//\t\tList<TestNode> solutionPath = null;\r\n//\r\n//\t\twhile (solutionPath == null) {\r\n//\t\t\tList<NodeExpansionDescription<TestNode, String>> expansion = bf.nextExpansion();\r\n//\t\t\tfor (NodeExpansionDescription des : expansion) {\r\n//\t\t\t\tif (ids.contains(((TestNode) des.getTo()).getId())) {\r\n//\t\t\t\t\tfail();\r\n//\t\t\t\t} else\r\n//\t\t\t\t\tids.add(((TestNode) des.getTo()).getId());\r\n//\t\t\t}\r\n//\t\t\tassertNotNull(expansion);\r\n//\t\t}\r\n//\r\n//\t}\r\n//\r\n//}\r\n" }, { "alpha_fraction": 0.7164179086685181, "alphanum_fraction": 0.7170668244361877, "avg_line_length": 33.022727966308594, "blob_id": "d583f8a272f5ac3e55c4131228afa52a71c7ac64", "content_id": "9d546224720daff5eb77b1c30651a0b436d035c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1541, "license_type": "no_license", "max_line_length": 210, "num_lines": 44, "path": "/softwareconfiguration/hasco/src/hasco/variants/forwarddecomposition/DefaultPathPriorizingPredicate.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package hasco.variants.forwarddecomposition;\r\n\r\nimport java.util.function.Predicate;\r\n\r\nimport hasco.core.HASCO;\r\nimport hasco.core.Util;\r\nimport hasco.model.ComponentInstance;\r\nimport jaicore.planning.graphgenerators.task.tfd.TFDNode;\r\n\r\n/**\r\n * This is a node evaluator that assigns 0 to all nodes encoding (partial) compositions where each component refinement is with its default parameters.\r\n * \r\n * This is a somewhat cyclic component, because it needs to know the HASCO object it will advise, but it is already needed to initialize HASCO. So to use it, the hasco variable must be set after initialization.\r\n * \r\n * @author fmohr\r\n *\r\n */\r\npublic class DefaultPathPriorizingPredicate<N, A> implements Predicate<N> {\r\n\r\n\tprivate HASCO<?, N, A, ?> hasco;\r\n\r\n\t@Override\r\n\tpublic boolean test(N node) {\r\n\t\tif (hasco == null)\r\n\t\t\tthrow new IllegalStateException(\"HASCO has not yet been set!\");\r\n\t\tif (!(node instanceof TFDNode)) {\r\n\t\t\tthrow new IllegalArgumentException(\"Currently we only support TFDNodes for node priorization\");\r\n\t\t}\r\n\t\tif (hasco.getInput() == null)\r\n\t\t\tthrow new IllegalStateException(\"HASCO exists, but its problem input has not been defined yet.\");\r\n\t\tComponentInstance inst = Util.getSolutionCompositionFromState(hasco.getInput().getComponents(), ((TFDNode) node).getState(), false);\r\n\t\tif (inst == null)\r\n\t\t\treturn true;\r\n\t\treturn Util.isDefaultConfiguration(inst);\r\n\t}\r\n\r\n\tpublic HASCO<?, N, A, ?> getHasco() {\r\n\t\treturn hasco;\r\n\t}\r\n\r\n\tpublic void setHasco(HASCO<?, N, A, ?> hasco) {\r\n\t\tthis.hasco = hasco;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7336043119430542, "alphanum_fraction": 0.7355013489723206, "avg_line_length": 49.971832275390625, "blob_id": "82e8145159f169ef4e06ce4d52bd0541e6e60a07", "content_id": "cbaf37829eb9a2a602b22bd77434c8fa0558307e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 7380, "license_type": "no_license", "max_line_length": 345, "num_lines": 142, "path": "/softwareconfiguration/mlplan/src/de/upb/crc901/reduction/single/heterogeneous/simplerpnd/MySQLExperimentRunner.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package de.upb.crc901.reduction.single.heterogeneous.simplerpnd;\r\n\r\nimport java.io.File;\r\nimport java.io.FileNotFoundException;\r\nimport java.io.IOException;\r\nimport java.sql.ResultSet;\r\nimport java.sql.SQLException;\r\nimport java.util.Collection;\r\nimport java.util.HashMap;\r\nimport java.util.HashSet;\r\nimport java.util.List;\r\nimport java.util.Map;\r\nimport java.util.Optional;\r\n\r\nimport org.apache.commons.math.stat.descriptive.DescriptiveStatistics;\r\n\r\nimport de.upb.crc901.reduction.Util;\r\nimport de.upb.crc901.reduction.single.MySQLReductionExperiment;\r\nimport de.upb.crc901.reduction.single.ReductionExperiment;\r\nimport jaicore.basic.SQLAdapter;\r\n\r\npublic class MySQLExperimentRunner {\r\n\r\n\tprivate static final String TABLE_NAME = \"reductionstumps\";\r\n\tprivate final SQLAdapter adapter;\r\n\tprivate final Collection<MySQLReductionExperiment> knownExperiments = new HashSet<>();\r\n\r\n\tpublic MySQLExperimentRunner(String host, String user, String password, String database) {\r\n\t\tadapter = new SQLAdapter(host, user, password, database);\r\n\t\ttry {\r\n\t\t\tknownExperiments.addAll(getConductedExperiments());\r\n\t\t} catch (SQLException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic Collection<MySQLReductionExperiment> getConductedExperiments() throws SQLException {\r\n\t\tCollection<MySQLReductionExperiment> experiments = new HashSet<>();\r\n\t\tResultSet rs = adapter.getRowsOfTable(TABLE_NAME);\r\n\t\twhile (rs.next()) {\r\n\t\t\texperiments.add(new MySQLReductionExperiment(rs.getInt(\"evaluation_id\"), new ReductionExperiment(rs.getInt(\"seed\"), rs.getString(\"dataset\"), rs.getString(\"left_classifier\"), rs.getString(\"inner_classifier\"), rs.getString(\"right_classifier\"), rs.getString(\"exception_left\"), rs.getString(\"exception_inner\"), rs.getString(\"exception_right\"))));\r\n\t\t}\r\n\t\treturn experiments;\r\n\t}\r\n\r\n\tpublic MySQLReductionExperiment createAndGetExperimentIfNotConducted(int seed, File dataFile, String nameOfLeftClassifier, String nameOfInnerClassifier,\r\n\t\t\tString nameOfRightClassifier) throws FileNotFoundException, IOException {\r\n\t\t\r\n\t\t/* first check whether exactly the same experiment (with the same seed) has been conducted previously */\r\n\t\tReductionExperiment exp = new ReductionExperiment(seed, dataFile.getAbsolutePath(), nameOfLeftClassifier, nameOfInnerClassifier, nameOfRightClassifier);\r\n\t\tOptional<MySQLReductionExperiment> existingExperiment = knownExperiments.stream().filter(e -> e.getExperiment().equals(exp)).findAny();\r\n\t\tif (existingExperiment.isPresent())\r\n\t\t\treturn null;\r\n\t\t\r\n\t\t/* otherwise, check if the same classifier combination has been tried before */\r\n\t\tif (canInfeasibilityBeDerived(knownExperiments, exp))\r\n\t\t\treturn null;\r\n\t\t\r\n\t\tMap<String, String> map = new HashMap<>();\r\n\t\tmap.put(\"seed\", String.valueOf(seed));\r\n\t\tmap.put(\"dataset\", dataFile.getAbsolutePath());\r\n\t\tmap.put(\"rpnd_classifier\", nameOfInnerClassifier);\r\n\t\tmap.put(\"left_classifier\", nameOfLeftClassifier);\r\n\t\tmap.put(\"inner_classifier\", nameOfInnerClassifier);\r\n\t\tmap.put(\"right_classifier\", nameOfRightClassifier);\r\n\t\ttry {\r\n\t\t\tint id = adapter.insert(TABLE_NAME, map);\r\n\t\t\treturn new MySQLReductionExperiment(id, exp);\r\n\t\t} catch (SQLException e) {\r\n\t\t\tSystem.err.println(e.getMessage());\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate void updateExperiment(MySQLReductionExperiment exp, Map<String,? extends Object> values) throws SQLException {\r\n\t\tMap<String,String> where = new HashMap<>();\r\n\t\twhere.put(\"evaluation_id\", String.valueOf(exp.getId()));\r\n\t\tadapter.update(TABLE_NAME, values, where);\r\n\t}\r\n\t\r\n\tpublic void conductExperiment(MySQLReductionExperiment exp) throws Exception {\r\n\t\tList<Map<String,Object>> mccvResults = Util.conductSingleOneStepReductionExperiment(exp.getExperiment());\r\n\t\tDescriptiveStatistics errorRate = new DescriptiveStatistics();\r\n\t\tDescriptiveStatistics runtime = new DescriptiveStatistics();\r\n\t\tfor (Map<String,Object> result : mccvResults) {\r\n\t\t\terrorRate.addValue((double)result.get(\"errorRate\"));\r\n\t\t\truntime.addValue((long)result.get(\"trainTime\"));\r\n\t\t}\r\n\t\t\r\n\t\t/* prepapre values for experiment update */\r\n\t\tMap<String, Object> values = new HashMap<>();\r\n\t\tvalues.put(\"error_rate_min\", errorRate.getMin());\r\n\t\tvalues.put(\"error_rate_max\", errorRate.getMax());\r\n\t\tvalues.put(\"error_rate_mean\", errorRate.getMean());\r\n\t\tvalues.put(\"error_rate_std\", errorRate.getStandardDeviation());\r\n\t\tvalues.put(\"runtime_min\", runtime.getMin());\r\n\t\tvalues.put(\"runtime_max\", runtime.getMax());\r\n\t\tvalues.put(\"runtime_mean\", runtime.getMean());\r\n\t\tvalues.put(\"runtime_std\", runtime.getStandardDeviation());\r\n\t\tupdateExperiment(exp, values);\r\n\t}\r\n\t\r\n\tpublic void markExperimentAsUnsolvable(MySQLReductionExperiment exp) throws SQLException {\r\n\t\tMap<String, String> values = new HashMap<>();\r\n\t\tfor (String key : new String[] {\"error_rate_min\", \"error_rate_max\", \"error_rate_mean\", \"error_rate_std\", \"runtime_min\", \"runtime_max\", \"runtime_mean\", \"runtime_std\" })\r\n\t\t\t values.put(key, \"-1\");\r\n\t\tupdateExperiment(exp, values);\r\n\t}\r\n\t\r\n\tpublic void associateExperimentWithException(MySQLReductionExperiment exp, String classifier, Throwable e) throws SQLException {\r\n\t\tMap<String, String> values = new HashMap<>();\r\n\t\tfor (String key : new String[] {\"error_rate_min\", \"error_rate_max\", \"error_rate_mean\", \"error_rate_std\", \"runtime_min\", \"runtime_max\", \"runtime_mean\", \"runtime_std\" })\r\n\t\t\t values.put(key, \"-1\");\r\n\t\tvalues.put(\"exception_\" + classifier, e.getClass().getName() + \"\\n\" + e.getMessage());\r\n\t\tupdateExperiment(exp, values);\r\n\t}\r\n\t\r\n\tprivate boolean canInfeasibilityBeDerived(Collection<MySQLReductionExperiment> experimentsWithResults, ReductionExperiment experimentInQuestion) {\r\n//\t\tfor (MySQLReductionExperiment knownExperiment : experimentsWithResults) {\r\n//\t\t\tif (!knownExperiment.getExperiment().getDataset().equals(experimentInQuestion.getDataset()))\r\n//\t\t\t\tcontinue;\r\n//\t\t\tReductionExperiment re = knownExperiment.getExperiment();\r\n//\t\t\tif (re.getExceptionRPND() != null && re.getNameOfClassifierForRPNDSplit().equals(experimentInQuestion.getExceptionRPND())) {\r\n//\t\t\t\tSystem.out.println(\"Skipping because \" + experimentInQuestion.getNameOfClassifierForRPNDSplit() + \" is known to be problematic as RPND classifier on \" + re.getDataset() + \" due to \" + re.getExceptionRPND());\r\n//\t\t\t\treturn true;\r\n//\t\t\t}\r\n//\t\t\telse if (re.getExceptionLeft() != null && re.getNameOfLeftClassifier().equals(experimentInQuestion.getNameOfLeftClassifier())) {\r\n//\t\t\t\tSystem.out.println(\"Skipping because \" + experimentInQuestion.getNameOfLeftClassifier() + \" is known to be problematic as left classifier on \" + re.getDataset() + \" due to \" + re.getExceptionLeft());\r\n//\t\t\t\treturn true;\r\n//\t\t\t}\r\n//\t\t\telse if (re.getExceptionInner() != null && re.getNameOfInnerClassifier().equals(experimentInQuestion.getNameOfInnerClassifier())) {\r\n//\t\t\t\tSystem.out.println(\"Skipping because \" + experimentInQuestion.getNameOfInnerClassifier() + \" is known to be problematic as left classifier on \" + re.getDataset() + \" due to \" + re.getExceptionInner());\r\n//\t\t\t\treturn true;\r\n//\t\t\t}\r\n//\t\t\telse if (re.getExceptionRight() != null && re.getNameOfRightClassifier().equals(experimentInQuestion.getNameOfRightClassifier())) {\r\n//\t\t\t\tSystem.out.println(\"Skipping because \" + experimentInQuestion.getNameOfRightClassifier() + \" is known to be problematic as right classifier on \" + re.getDataset() + \" due to \" + re.getExceptionRight());\r\n//\t\t\t\treturn true;\r\n//\t\t\t}\r\n//\t\t}\r\n\t\treturn false;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6755390167236328, "alphanum_fraction": 0.6888474822044373, "avg_line_length": 26.248119354248047, "blob_id": "4408133128aae08e788e4e88d8970a9a33275205", "content_id": "7f1788df7292d60369bcd22ab79960070421d858", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Gradle", "length_bytes": 3757, "license_type": "no_license", "max_line_length": 77, "num_lines": 133, "path": "/build.gradle", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "buildscript {\r\n\trepositories {\r\n\t\tmavenLocal()\r\n\t\tmavenCentral()\r\n\t\tmaven { url \"https://plugins.gradle.org/m2/\" }\r\n\t}\r\n\tdependencies {\r\n\t\tclasspath \"com.github.jengelman.gradle.plugins:shadow:2.0.4\"\r\n\t}\r\n}\r\n\r\n// Artifact publishing and versoning\r\nplugins {\r\n\tid 'nebula.release' version '6.0.2'\r\n\tid \"nebula.project\" version \"3.4.0\"\r\n\tid \"nebula.maven-base-publish\" version \"5.1.4\"\r\n\tid \"org.sonarqube\" version \"2.6.2\"\r\n}\r\n\r\nallprojects {\r\n\t//Shadow for fat-jars\r\n\tapply plugin: \"com.github.johnrengelman.shadow\"\r\n\r\n\t//IDE\r\n\tapply plugin: \"java\"\r\n\tapply plugin: \"eclipse\"\r\n\tapply plugin: \"idea\"\r\n\r\n\t//Other\r\n\tapply plugin: \"maven\"\r\n\tapply plugin: \"jacoco\"\r\n\r\n\t//Nebula\r\n\tapply plugin: 'nebula.project'\r\n\tapply plugin: 'nebula.nebula-release'\r\n\tapply plugin: 'nebula.maven-base-publish'\r\n\r\n\t//Java version\r\n\tsourceCompatibility = 1.8\r\n\ttargetCompatibility = 1.8\r\n\r\n\t//Project properties\r\n\tproject.group = 'de.upb.isys'\r\n\tproject.version = '0.0.1-SNAPSHOT'\r\n\r\n\t//Repositories\r\n\trepositories {\r\n\t\tmavenCentral()\r\n\t\tmavenLocal()\r\n\t\tmaven { url \"https://jitpack.io\" }\r\n\t\tmaven { url \"http://clojars.org/repo/\" }\r\n\t\tmaven { url \"https://plugins.gradle.org/m2/\" }\r\n\t\tmaven { url \"https://nexus.cs.upb.de/repository/maven-releases/\" }\r\n\t\tflatDir {\r\n\t\t\tdirs 'lib'\r\n\t\t}\r\n\t}\r\n\t//Dependencies for all(!) projects\r\n\tdependencies {\r\n\t\t//Logger\r\n\t\tcompile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25'\r\n\r\n\t\truntimeOnly group: 'org.slf4j', name:'slf4j-log4j12', version:'1.7.25'\r\n\r\n\t\t//Testing\r\n\t\ttestCompile group: 'junit', name: 'junit', version: '4.12'\r\n\t\ttestCompile group: 'org.hamcrest', name: 'hamcrest-all', version: '1.3'\r\n\t\ttestCompile group: 'org.mockito', name: 'mockito-all', version: '1.10.19'\r\n\t}\r\n\r\n\t//Always check for updates in SNAPSHOT versions, do not cache\r\n\tconfigurations.all {\r\n\t\t// check for updates every build\r\n\t\tresolutionStrategy.cacheChangingModulesFor 0, 'seconds'\r\n\t}\r\n\r\n\t//Nebula releases\r\n\tnebulaRelease { addReleaseBranchPattern('/dev/') }\r\n\r\n\t//Sonarqube config\r\n\tsonarqube {\r\n\t\tproperties {\r\n\t\t\tproperties[\"sonar.projectKey\"] = project.name\r\n\t\t\tproperties[\"sonar.projectName\"] = project.name\r\n\t\t\tproperties[\"sonar.projectDescription\"] = project.description\r\n\t\t\tproperties[\"sonar.projectVersion\"] = project.version\r\n\t\t\tproperties[\"sonar.projectBaseDir\"] = project.projectDir\r\n\t\t\tproperties[\"sonar.working.directory\"] = \"$project.buildDir/sonar\"\r\n\t\t\tproperties[\"sonar.sourceEncoding\"] = project.compileJava.options.encoding\r\n\t\t\tproperties[\"sonar.java.source\"] = project.sourceCompatibility\r\n\t\t\tproperties[\"sonar.java.target\"] = project.targetCompatibility\r\n\t\t\tproperties[\"sonar.java.binaries\"] = sourceSets.main.output.classesDir\r\n\t\t\tproperties[\"sonar.java.test.binaries\"] = sourceSets.test.output.classesDir\r\n\t\t}\r\n\t}\r\n\r\n\tpublishing {\r\n\t\tpublications {\r\n\t\t\tshadow(MavenPublication) { publication ->\r\n\t\t\t\tproject.shadow.component(publication)\r\n\t\t\t}\r\n \t\t}\t\r\n\t\trepositories {\r\n\t\t\tmaven {\r\n\t\t\t\turl \"${nexusBaseUrl}/repository/${nexusUpRepo}-${'snapshots'}\"\r\n\t\t\t\tcredentials {\r\n\t\t\t\t\tusername \"${nexusUser}\"\r\n\t\t\t\t\tpassword \"${nexusPassword}\"\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n}\r\n\r\ndependencies{\r\n\tcompile project(\":hasco\")\r\n\tcompile project(\":mlplan\")\r\n\tcompile project(\":JAICore:jaicore-basic\")\r\n\tcompile project(\":JAICore:jaicore-concurrent\")\r\n\tcompile project(\":JAICore:jaicore-experiments\")\r\n\tcompile project(\":JAICore:jaicore-graph\")\r\n\tcompile project(\":JAICore:jaicore-graphvisualizer\")\r\n\tcompile project(\":JAICore:jaicore-logic\")\r\n\tcompile project(\":JAICore:jaicore-math\")\r\n\tcompile project(\":JAICore:jaicore-ml\")\r\n\tcompile project(\":JAICore:jaicore-planning\")\r\n\tcompile project(\":JAICore:jaicore-processes\")\r\n\tcompile project(\":JAICore:jaicore-search\")\r\n\tcompile project(\":JAICore:jaicore-services\")\r\n}\r\n\r\npublish.dependsOn shadowJar\r\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.75, "avg_line_length": 13.199999809265137, "blob_id": "d59583a660501c5baef942123172c10a4e1dd3d4", "content_id": "ba1bac3d065b57303b6e3360d947bf0198af9ee0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 76, "license_type": "no_license", "max_line_length": 33, "num_lines": 5, "path": "/JAICore/jaicore-basic/src/jaicore/basic/algorithm/AlgorithmEvent.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.basic.algorithm;\r\n\r\npublic interface AlgorithmEvent {\r\n\r\n}\r\n" }, { "alpha_fraction": 0.6928186416625977, "alphanum_fraction": 0.6979571580886841, "avg_line_length": 34.10407257080078, "blob_id": "037948db4a0280a9e96c2c64546c625f3dc2cfc4", "content_id": "33072eb6cf3213b8ef9e9d0162f5870ad38598ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 7979, "license_type": "no_license", "max_line_length": 308, "num_lines": 221, "path": "/JAICore/jaicore-ml/src/jaicore/ml/classification/multiclass/reduction/reducer/ReductionOptimizer.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.ml.classification.multiclass.reduction.reducer;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.Collection;\r\nimport java.util.List;\r\nimport java.util.Random;\r\nimport java.util.Stack;\r\nimport java.util.stream.Collectors;\r\nimport java.util.stream.IntStream;\r\n\r\nimport jaicore.graphvisualizer.gui.VisualizationWindow;\r\nimport org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;\r\n\r\nimport jaicore.basic.MathExt;\r\nimport jaicore.graphvisualizer.TooltipGenerator;\r\nimport jaicore.ml.WekaUtil;\r\nimport jaicore.ml.classification.multiclass.reduction.EMCNodeType;\r\nimport jaicore.ml.classification.multiclass.reduction.MCTreeNode;\r\nimport jaicore.ml.classification.multiclass.reduction.MCTreeNodeLeaf;\r\nimport jaicore.search.algorithms.standard.bestfirst.BestFirstEpsilon;\r\nimport jaicore.search.model.other.EvaluatedSearchGraphPath;\r\nimport jaicore.search.model.probleminputs.GeneralEvaluatedTraversalTree;\r\nimport jaicore.search.model.probleminputs.GraphSearchProblemInput;\r\nimport jaicore.search.model.travesaltree.Node;\r\nimport weka.classifiers.Classifier;\r\nimport weka.classifiers.Evaluation;\r\nimport weka.classifiers.rules.OneR;\r\nimport weka.core.Attribute;\r\nimport weka.core.Capabilities;\r\nimport weka.core.Instance;\r\nimport weka.core.Instances;\r\n\r\npublic class ReductionOptimizer implements Classifier {\r\n\r\n\tprivate final Random rand;\r\n\tprivate MCTreeNode root;\r\n\r\n\tpublic ReductionOptimizer(Random rand) {\r\n\t\tsuper();\r\n\t\tthis.rand = rand;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void buildClassifier(Instances data) throws Exception {\r\n\t\tList<Instances> dataSplit = WekaUtil.getStratifiedSplit(data, rand, .6f);\r\n\t\tInstances train = dataSplit.get(0);\r\n\t\tInstances validate = dataSplit.get(1);\r\n\t\tBestFirstEpsilon<RestProblem, Decision, Double> search = new BestFirstEpsilon<RestProblem, Decision, Double>(new GeneralEvaluatedTraversalTree<>(new ReductionGraphGenerator(rand, train), n -> getLossForClassifier(getTreeFromSolution(n.externalPath(), data, false), data) * 1.0), n -> n.path().size() * -1.0\r\n\t\t, 0.1, false);\r\n\r\n\t\tVisualizationWindow<Node<RestProblem, Double>,Decision> window = new VisualizationWindow<>(search);\r\n\t\twindow.setTooltipGenerator(new TooltipGenerator<Node<RestProblem, Double>>() {\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic String getTooltip(Node<RestProblem, Double> node) {\r\n\t\t\t\treturn search.getFValue(node) + \"<pre>\" + getTreeFromSolution(node.externalPath(), data, false).toStringWithOffset() + \"</pre>\";\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t\t/* get best 20 solutions */\r\n\t\tint i = 0;\r\n\t\tCollection<EvaluatedSearchGraphPath<RestProblem,Decision,Double>> solutions = new ArrayList<>();\r\n\t\tEvaluatedSearchGraphPath<RestProblem,Decision,Double> solution;\r\n\t\twhile ((solution = search.nextSolution()) != null) {\r\n\t\t\tsolutions.add(solution);\r\n\t\t\tif (i++ > 100)\r\n\t\t\t\tbreak;\r\n\t\t}\r\n\t\tSystem.out.println(solutions.size());\r\n\r\n\t\t/* select */\r\n\t\tEvaluatedSearchGraphPath<RestProblem,Decision,Double> bestSolution = solutions.stream().min((s1, s2) -> s1.getScore().compareTo(s2.getScore())).get();\r\n\t\troot = getTreeFromSolution(bestSolution.getNodes(), data, true);\r\n\t\troot.buildClassifier(data);\r\n\t\tSystem.out.println(root.toStringWithOffset());\r\n\t\tSystem.out.println(bestSolution.getScore());\r\n\t}\r\n\r\n\t@Override\r\n\tpublic double classifyInstance(Instance instance) throws Exception {\r\n\t\treturn root.classifyInstance(instance);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic double[] distributionForInstance(Instance instance) throws Exception {\r\n\t\treturn root.distributionForInstance(instance);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic Capabilities getCapabilities() {\r\n\t\treturn null;\r\n\t}\r\n\r\n\tprivate void completeTree(MCTreeNode tree) {\r\n\r\n\t\t/* if the tree is not ready yet, complete it. The completion strategy is now just to set the node to \"direct\" with a random forest */\r\n\t\tif (!tree.isCompletelyConfigured()) {\r\n\t\t\tfor (MCTreeNode node : tree) {\r\n\t\t\t\tif (!node.getChildren().isEmpty())\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\tif (node.getContainedClasses().size() == 1)\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\tnode.setNodeType(EMCNodeType.DIRECT);\r\n\t\t\t\tnode.setBaseClassifier(new OneR());\r\n\t\t\t\tfor (int openClass : node.getContainedClasses()) {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tnode.addChild(new MCTreeNodeLeaf(openClass));\r\n\t\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprivate int getLossForClassifier(MCTreeNode tree, Instances data) {\r\n\r\n\t\tcompleteTree(tree);\r\n\r\n\t\tsynchronized (this) {\r\n\t\t\t/* now eval the tree */\r\n\t\t\ttry {\r\n\t\t\t\tDescriptiveStatistics stats = new DescriptiveStatistics();\r\n\t\t\t\tfor (int i = 0; i < 2; i++) {\r\n\t\t\t\t\tList<Instances> split = (WekaUtil.getStratifiedSplit(data, rand, .6f));\r\n\t\t\t\t\ttree.buildClassifier(split.get(0));\r\n\r\n\t\t\t\t\tEvaluation eval = new Evaluation(data);\r\n\t\t\t\t\teval.evaluateModel(tree, split.get(1));\r\n\t\t\t\t\tstats.addValue(eval.pctIncorrect());\r\n\t\t\t\t}\r\n\t\t\t\tint score = (int) Math.round((stats.getMean() * 100));\r\n\t\t\t\tSystem.out.println(score);\r\n\t\t\t\treturn score;\r\n\r\n\t\t\t} catch (Exception e) {\r\n\t\t\t\te.printStackTrace();\r\n\t\t\t\treturn Integer.MAX_VALUE;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t}\r\n\r\n\tprivate MCTreeNode getTreeFromSolution(List<RestProblem> solution, Instances data, boolean mustBeComplete) {\r\n\t\tList<Decision> decisions = solution.stream().filter(n -> n.getEdgeToParent() != null).map(n -> n.getEdgeToParent()).collect(Collectors.toList());\r\n\t\tStack<MCTreeNode> open = new Stack<>();\r\n\t\tAttribute classAttribute = data.classAttribute();\r\n\t\tMCTreeNode root = new MCTreeNode(IntStream.range(0, classAttribute.numValues()).mapToObj(i -> i).collect(Collectors.toList()));\r\n\t\topen.push(root);\r\n\t\tfor (Decision decision : decisions) {\r\n\t\t\tMCTreeNode nodeToRefine = open.pop(); // by construction of the search space, this node should belong to the decision\r\n\t\t\tif (nodeToRefine == null)\r\n\t\t\t\tthrow new IllegalStateException(\"No node to apply the decision to! Apparently, there are more decisions for nodes than there are inner nodes.\");\r\n\r\n\t\t\t/* insert decision to the node */\r\n\t\t\tnodeToRefine.setNodeType(decision.getClassificationType());\r\n\t\t\tnodeToRefine.setBaseClassifier(decision.getBaseClassifier());\r\n\r\n\t\t\tboolean isCutOff = !(decision.getLft() != null && decision.getRgt() != null);\r\n\r\n\t\t\tif (isCutOff) {\r\n\t\t\t\tfor (Integer c : nodeToRefine.getContainedClasses()) {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tnodeToRefine.addChild(new MCTreeNodeLeaf(c));\r\n\t\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\r\n\t\t\t\t/* set left child */\r\n\t\t\t\tboolean addedLeftChild = false;\r\n\t\t\t\tList<String> classesLft = new ArrayList<>(decision.getLft());\r\n\t\t\t\tif (classesLft.size() == 1) {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tnodeToRefine.addChild(new MCTreeNodeLeaf(classAttribute.indexOfValue(classesLft.get(0))));\r\n\t\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t\t}\r\n\t\t\t\t} else {\r\n\t\t\t\t\tMCTreeNode lft = new MCTreeNode(classesLft.stream().map(c -> classAttribute.indexOfValue(c)).collect(Collectors.toList()));\r\n\t\t\t\t\tnodeToRefine.addChild(lft);\r\n\t\t\t\t\taddedLeftChild = true;\r\n\t\t\t\t\topen.push(lft);\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/* set right child */\r\n\t\t\t\tList<String> classesRgt = new ArrayList<>(decision.getRgt());\r\n\t\t\t\tif (classesRgt.size() == 1) {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tnodeToRefine.addChild(new MCTreeNodeLeaf(data.classAttribute().indexOfValue(classesRgt.get(0))));\r\n\t\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t\t}\r\n\t\t\t\t} else {\r\n\t\t\t\t\tMCTreeNode rgt = new MCTreeNode(classesRgt.stream().map(c -> classAttribute.indexOfValue(c)).collect(Collectors.toList()));\r\n\t\t\t\t\tnodeToRefine.addChild(rgt);\r\n\t\t\t\t\tif (addedLeftChild) {\r\n\t\t\t\t\t\tMCTreeNode lft = open.pop();\r\n\t\t\t\t\t\topen.push(rgt);\r\n\t\t\t\t\t\topen.push(lft);\r\n\t\t\t\t\t} else\r\n\t\t\t\t\t\topen.push(rgt);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (mustBeComplete && !open.isEmpty())\r\n\t\t\tthrow new IllegalStateException(\"Not all nodes have been equipped with decisions!\");\r\n\t\treturn root;\r\n\t}\r\n\r\n\tprivate double getAccuracy(Classifier c, Instances test) throws Exception {\r\n\t\tint mistakes = 0;\r\n\t\tfor (Instance i : test) {\r\n\t\t\tif (c.classifyInstance(i) != i.classValue())\r\n\t\t\t\tmistakes++;\r\n\t\t}\r\n\t\treturn MathExt.round(100 * (1 - mistakes * 1f / test.size()), 2);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7323943376541138, "alphanum_fraction": 0.7323943376541138, "avg_line_length": 12.199999809265137, "blob_id": "676c740e1457d804cab25e1dc75208397091fb99", "content_id": "efc55698b6cc24d3c792487f260f31a1f135964b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 71, "license_type": "no_license", "max_line_length": 32, "num_lines": 5, "path": "/JAICore/jaicore-search/src/jaicore/search/util/SanityCheckResult.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.util;\r\n\r\npublic class SanityCheckResult {\r\n\r\n}\r\n" }, { "alpha_fraction": 0.6945946216583252, "alphanum_fraction": 0.6945946216583252, "avg_line_length": 13.230769157409668, "blob_id": "06ad68ce5e80906629b51644d4c8e9e5a04e486f", "content_id": "8858a09918dd64bd94dc102b223df7e02ec4b2f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 370, "license_type": "no_license", "max_line_length": 65, "num_lines": 26, "path": "/JAICore/jaicore-search/test/jaicore/search/testproblems/bestfirst/abstractVersioning/TestNode.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.testproblems.bestfirst.abstractVersioning;\n\nimport jaicore.search.model.travesaltree.AbstractNode;\n\npublic class TestNode extends AbstractNode {\n\t\n\tprivate int value;\n\t\n\tpublic TestNode(int v) {\n\t\tvalue = v;\n\t}\n\t\n\t\n\tpublic String toString() {\n\t\treturn \"\" +value;\n\t}\n\n\n\t/**\n\t * @return the value\n\t */\n\tpublic int getValue() {\n\t\treturn value;\n\t}\n\n}\n" }, { "alpha_fraction": 0.760188102722168, "alphanum_fraction": 0.760188102722168, "avg_line_length": 37.875, "blob_id": "0a84237d8149e376a6ccc2ce5796101193bfe9fe", "content_id": "28b144b49f0b003cda5e651953f4a90cbcc85fdc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1276, "license_type": "no_license", "max_line_length": 126, "num_lines": 32, "path": "/JAICore/jaicore-basic/src/jaicore/basic/algorithm/IAlgorithm.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.basic.algorithm;\r\n\r\nimport java.util.Iterator;\r\nimport java.util.concurrent.Callable;\r\nimport java.util.concurrent.TimeUnit;\r\n\r\nimport jaicore.basic.Cancelable;\r\n\r\n/**\r\n * The algorithms should actually also be interruptible, but since this is often not the case, we require the cancel method to\r\n * ensure that the authors of the algorithms provide a mechanism to stop the algorithm and free the used resources.\r\n * \r\n * Implementation of both Iterable and Iterator: We envision that an object of an algorithm really only represents one run, so\r\n * there is really no reason to have an additional object only to hold the state.\r\n * \r\n * @author fmohr\r\n *\r\n * @param <I> class of which inputs stems from\r\n * @param <O> class of which solution candidates and the eventually returned result stem from\r\n */\r\npublic interface IAlgorithm<I,O> extends Iterable<AlgorithmEvent>, Iterator<AlgorithmEvent>, Callable<O>, Cancelable {\r\n\t\r\n\tpublic I getInput();\r\n\tpublic void registerListener(Object listener);\r\n\tpublic void setNumCPUs(int numberOfCPUs);\r\n\tpublic int getNumCPUs();\r\n\tpublic void setTimeout(int timeout, TimeUnit timeUnit);\r\n\tpublic int getTimeout();\r\n\tpublic TimeUnit getTimeoutUnit();\r\n\t\r\n\tpublic AlgorithmEvent nextWithException() throws Exception;\r\n}\r\n" }, { "alpha_fraction": 0.7217015027999878, "alphanum_fraction": 0.7281903624534607, "avg_line_length": 23.35087776184082, "blob_id": "908ca40a8dceb275493d51c3e1eab602d44d13ed", "content_id": "381d1a70f1106c224e43ef9e53ac554ece3fefdf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Gradle", "length_bytes": 1387, "license_type": "no_license", "max_line_length": 68, "num_lines": 57, "path": "/JAICore/build.gradle", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "allprojects {\n\n\t//IDE\n\tapply plugin:\"java\"\n\tapply plugin:\"eclipse\"\n\tapply plugin:\"idea\"\n\n\t//Other\n\tapply plugin: \"maven\"\n\tapply plugin: \"jacoco\"\n\n\t//Java version\n\tsourceCompatibility = 1.8\n\ttargetCompatibility = 1.8\n\n\t//Project properties\n\tproject.group = 'de.upb.isys'\n\tproject.version = '0.0.1-SNAPSHOT'\n\n\t//Repositories\n\trepositories {\n\t\tmavenLocal()\n\t\tmaven { url \"https://jitpack.io\" }\n\t\tmaven { url \"http://clojars.org/repo/\" }\n\t\tmaven { url \"https://plugins.gradle.org/m2/\" }\n\t\tmaven { url \"https://nexus.cs.upb.de/repository/maven-releases/\" }\n\t\tmavenCentral()\n\t\tjcenter()\n\t}\n\n\n\t//Dependencies for all(!) projects\n\tdependencies {\n\n\t}\n\n\t//Always check for updates in SNAPSHOT versions, do not cache\n\tconfigurations.all {\n\t\t// check for updates every build\n\t\tresolutionStrategy.cacheChangingModulesFor 0, 'seconds'\n\t}\n}\n\ndependencies {\n\tcompile project(\":JAICore:jaicore-basic\")\n\tcompile project(\":JAICore:jaicore-concurrent\")\n\tcompile project(\":JAICore:jaicore-experiments\")\n\tcompile project(\":JAICore:jaicore-graph\")\n\tcompile project(\":JAICore:jaicore-graphvisualizer\")\n\tcompile project(\":JAICore:jaicore-logic\")\n\tcompile project(\":JAICore:jaicore-math\")\n\tcompile project(\":JAICore:jaicore-ml\")\n\tcompile project(\":JAICore:jaicore-planning\")\n\tcompile project(\":JAICore:jaicore-processes\")\n\tcompile project(\":JAICore:jaicore-search\")\n\tcompile project(\":JAICore:jaicore-services\")\n}" }, { "alpha_fraction": 0.7525773048400879, "alphanum_fraction": 0.7525773048400879, "avg_line_length": 17.399999618530273, "blob_id": "71226a447839c3c7e9257e3138ceb9b2b3394a55", "content_id": "4a6741148694f72fa7ac9c8c5d62217449ef3940", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 97, "license_type": "no_license", "max_line_length": 32, "num_lines": 5, "path": "/JAICore/jaicore-basic/src/jaicore/basic/algorithm/AlgorithmState.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.basic.algorithm;\r\n\r\npublic enum AlgorithmState {\r\n\tcreated, active, inactive\r\n}\r\n" }, { "alpha_fraction": 0.7568526268005371, "alphanum_fraction": 0.7581425309181213, "avg_line_length": 40.3466682434082, "blob_id": "fff020dfa25a9fda57f47e63289395865615410a", "content_id": "392f8cd4b44aba55df88c9442a813abc346581d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3101, "license_type": "no_license", "max_line_length": 187, "num_lines": 75, "path": "/JAICore/jaicore-planning/src/jaicore/planning/graphgenerators/task/ceociptfd/CEOCIPTFDGraphGenerator.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.graphgenerators.task.ceociptfd;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Map;\n\nimport jaicore.logic.fol.structure.Literal;\nimport jaicore.logic.fol.structure.Monom;\nimport jaicore.planning.graphgenerators.task.TaskPlannerUtil;\nimport jaicore.planning.graphgenerators.task.ceoctfd.CEOCTFDGraphGenerator;\nimport jaicore.planning.graphgenerators.task.tfd.TFDNode;\nimport jaicore.planning.model.ceoc.CEOCAction;\nimport jaicore.planning.model.ceoc.CEOCOperation;\nimport jaicore.planning.model.core.Action;\nimport jaicore.planning.model.core.PlannerUtil;\nimport jaicore.planning.model.task.ceocipstn.CEOCIPSTNPlanningProblem;\n\n/**\n * Graph Generator for HTN planning where (i) operations have conditional effects, (ii) operations may create new objects, and (iii) method preconditions may contain evaluable predicates.\n * \n * @author fmohr\n *\n */\n@SuppressWarnings(\"serial\")\npublic class CEOCIPTFDGraphGenerator extends CEOCTFDGraphGenerator {\n\n\tpublic CEOCIPTFDGraphGenerator(CEOCIPSTNPlanningProblem problem) {\n\t\tsuper(problem);\n\t\t\n\t\t/* now overwrite util to get access to the evaluable predicates */\n\t\tthis.util = new TaskPlannerUtil(problem.getEvaluablePlanningPredicates());\n\t}\n\n//\tprotected Collection<TFDNode> getSuccessorsResultingFromResolvingComplexTask(Monom state, Literal taskToBeResolved, List<Literal> remainingOtherTasks) {\n//\t\tCollection<TFDNode> successors = new ArrayList<>();\n//\t\tString nextTaskName = taskToBeResolved.getPropertyName();\n//\n//\t\t/* if there is an oracle for the task, use it */\n//\t\tMap<String, OracleTaskResolver> oracleResolvers = ((CEOCIPSTNPlanningProblem) problem).getOracleResolvers();\n//\t\tif (oracleResolvers != null && oracleResolvers.containsKey(nextTaskName)) {\n//\n//\t\t\t/* for each sub-solution produced by the oracle, create a successor node */\n//\t\t\ttry {\n//\t\t\t\tCollection<List<Action>> subsolutions = oracleResolvers.get(nextTaskName).getSubSolutions(state, taskToBeResolved);\n//\t\t\t\tfor (List<Action> subsolution : subsolutions) {\n//\t\t\t\t\tif (subsolution.size() > 1)\n//\t\t\t\t\t\tthrow new UnsupportedOperationException(\"Currently only subplans of length 1 possible!\");\n//\t\t\t\t\tAction applicableAction = subsolution.get(0);\n//\t\t\t\t\tMonom updatedState = new Monom(state, false);\n//\t\t\t\t\tPlannerUtil.updateState(updatedState, applicableAction);\n//\t\t\t\t\tList<Literal> remainingTasks = new ArrayList<>(remainingOtherTasks);\n//\t\t\t\t\tremainingTasks.remove(0);\n//\t\t\t\t\tsuccessors\n//\t\t\t\t\t\t\t.add(new TFDNode(updatedState, remainingTasks, null, new CEOCAction((CEOCOperation) applicableAction.getOperation(), applicableAction.getGrounding())));\n//\t\t\t\t}\n//\n//\t\t\t\treturn successors;\n//\t\t\t} catch (Exception e) {\n//\t\t\t\te.printStackTrace();\n//\t\t\t\treturn new ArrayList<>();\n//\t\t\t}\n//\t\t}\n//\n//\t\t/* otherwise, ordinary computation */\n//\t\telse\n//\t\t\treturn super.getSuccessorsResultingFromResolvingComplexTask(state, taskToBeResolved, remainingOtherTasks);\n//\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"CEOCIPTFDGraphGenerator [problem=\" + problem + \", primitiveTasks=\" + primitiveTasks + \"]\";\n\t}\n\n}\n" }, { "alpha_fraction": 0.77267986536026, "alphanum_fraction": 0.77267986536026, "avg_line_length": 29.935483932495117, "blob_id": "fec437ec1dd941c0a4d69c81f890b52f1efca87b", "content_id": "6ae7f4f688b636e7a1e311e767a1a8dc13371157", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 959, "license_type": "no_license", "max_line_length": 117, "num_lines": 31, "path": "/JAICore/jaicore-planning/src/jaicore/planning/EvaluatedSearchGraphBasedPlan.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning;\n\nimport java.util.List;\n\nimport jaicore.planning.model.core.Action;\nimport jaicore.planning.model.core.Plan;\nimport jaicore.search.model.other.SearchGraphPath;\n\npublic class EvaluatedSearchGraphBasedPlan<A extends Action,V extends Comparable<V>, N> extends EvaluatedPlan<A, V> {\n\n\tprivate final SearchGraphPath<N, ?> searchGraphPath;\n\n\tpublic EvaluatedSearchGraphBasedPlan(Plan<A> plan, V score, SearchGraphPath<N, ?> searchGraphPath) {\n\t\tsuper(plan, score);\n\t\tthis.searchGraphPath = searchGraphPath;\n\t}\n\t\n\tpublic EvaluatedSearchGraphBasedPlan(EvaluatedPlan<A, V> plan, SearchGraphPath<N, ?> searchGraphPath) {\n\t\tsuper(plan, plan.getScore());\n\t\tthis.searchGraphPath = searchGraphPath;\n\t}\n\t\n\tpublic EvaluatedSearchGraphBasedPlan(List<A> plan, V score, SearchGraphPath<N, ?> searchGraphPath) {\n\t\tsuper(plan, score);\n\t\tthis.searchGraphPath = searchGraphPath;\n\t}\n\n\tpublic SearchGraphPath<N, ?> getPath() {\n\t\treturn searchGraphPath;\n\t}\n}\n" }, { "alpha_fraction": 0.7472399473190308, "alphanum_fraction": 0.7518884539604187, "avg_line_length": 36.266666412353516, "blob_id": "2b41180553b674f44bd75b3fe4823303d2739611", "content_id": "8a00765f41721dd1b034200553160b8cd3e07afb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1721, "license_type": "no_license", "max_line_length": 167, "num_lines": 45, "path": "/softwareconfiguration/hasco/src/hasco/variants/forwarddecomposition/twophase/TwoPhaseHASCOConfig.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package hasco.variants.forwarddecomposition.twophase;\r\n\r\npublic interface TwoPhaseHASCOConfig extends HASCOWithRandomCompletionsConfig {\r\n\tpublic static final String K_RANDOM_SEED = \"hasco.seed\";\r\n\tpublic static final String K_BLOWUP_SELECTION = \"hasco.blowup.selection\";\r\n\tpublic static final String K_BLOWUP_POSTPROCESS = \"hasco.blowup.postprocess\";\r\n\tpublic static final String K_SELECTION_EVALUATION_TIMEOUT_TOLERANCE = \"hasco.selection.timeouttolerance\";\t\r\n\tpublic static final String K_SELECTION_NUM_CONSIDERED_SOLUTIONS = \"hasco.selection.num_considered_solutions\";\r\n\r\n\t/**\r\n\t * @return The seed for the pseudo randomness generator.\r\n\t */\r\n\t@Key(K_RANDOM_SEED)\r\n\t@DefaultValue(\"0\")\r\n\tpublic int randomSeed();\r\n\r\n\t\r\n\t/**\r\n\t * @return The number of solutions that are considered during selection phase.\r\n\t */\r\n\t@Key(K_SELECTION_NUM_CONSIDERED_SOLUTIONS)\r\n\t@DefaultValue(\"100\")\r\n\tpublic int selectionNumConsideredSolutions();\r\n\t\r\n\t/**\r\n\t * @return Expected multiplication in time for each solution candidate that will be required for evaluation\r\n\t */\r\n\t@Key(K_BLOWUP_SELECTION)\r\n\t@DefaultValue(\"1\")\r\n\tpublic double expectedBlowupInSelection();\r\n\t\r\n\t/**\r\n\t * @return Expected multiplication in time for each solution candidate that will be required for a postprocessing that should be considered when computing the timeout\r\n\t */\r\n\t@Key(K_BLOWUP_POSTPROCESS)\r\n\t@DefaultValue(\"1\")\r\n\tpublic double expectedBlowupInPostprocessing();\r\n\r\n\t/**\r\n\t * @return The factor by which the evaluation in the selection phase may exceed the time expected on the basis of the estimate given by the blow-up\r\n\t */\r\n\t@Key(K_SELECTION_EVALUATION_TIMEOUT_TOLERANCE)\r\n\t@DefaultValue(\"0.1\")\r\n\tpublic double selectionPhaseTimeoutTolerance();\n}\r\n" }, { "alpha_fraction": 0.7121710777282715, "alphanum_fraction": 0.7121710777282715, "avg_line_length": 26.952381134033203, "blob_id": "b2432609f726387e3c8b632ecb516e859c6b0408", "content_id": "6b1788bf759cb50c7b05c8507ea933651398bda9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 608, "license_type": "no_license", "max_line_length": 82, "num_lines": 21, "path": "/JAICore/jaicore-search/test/jaicore/search/algorithms/standard/rstar/GridWorldHeuristic.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.rstar;\r\n\r\nimport jaicore.search.algorithms.standard.bestfirst.nodeevaluation.INodeEvaluator;\r\nimport jaicore.search.model.travesaltree.Node;\r\n\r\npublic class GridWorldHeuristic implements INodeEvaluator<GridWorld, Double> {\r\n\r\n\tprivate GridWorld end;\r\n\r\n\tpublic GridWorldHeuristic(GridWorld end) {\r\n\t\tsuper();\r\n\t\tthis.end = end;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic Double f(Node<GridWorld, ?> node) throws Exception {\r\n\t\tint x_ = Math.abs(end.getX() - node.getPoint().getX());\r\n\t\tint y_ = Math.abs(end.getY() - node.getPoint().getY());\r\n\t\treturn new Double(x_ + y_);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6419295072555542, "alphanum_fraction": 0.6447124481201172, "avg_line_length": 21.434782028198242, "blob_id": "3549c113239b169b7067d90639d49833f8542af3", "content_id": "79bf7799355a3bd565b8bc3fb498c856b561b533", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1078, "license_type": "no_license", "max_line_length": 100, "num_lines": 46, "path": "/JAICore/jaicore-search/src/jaicore/search/model/other/EvaluatedSearchGraphPath.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.model.other;\r\n\r\nimport java.util.List;\r\n\r\npublic class EvaluatedSearchGraphPath<N, A, V extends Comparable<V>> extends SearchGraphPath<N, A> {\r\n\tprivate final V score;\r\n\r\n\tpublic EvaluatedSearchGraphPath(List<N> nodes, List<A> edges, V score) {\r\n\t\tsuper(nodes, edges);\r\n\t\tthis.score = score;\r\n\t}\r\n\r\n\tpublic V getScore() {\r\n\t\treturn score;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = super.hashCode();\r\n\t\tresult = prime * result + ((score == null) ? 0 : score.hashCode());\r\n\t\treturn result;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean equals(Object obj) {\r\n\t\tif (this == obj)\r\n\t\t\treturn true;\r\n\t\tif (!super.equals(obj))\r\n\t\t\treturn false;\r\n\t\tif (getClass() != obj.getClass())\r\n\t\t\treturn false;\r\n\t\tEvaluatedSearchGraphPath other = (EvaluatedSearchGraphPath) obj;\r\n\t\tif (score == null) {\r\n\t\t\tif (other.score != null)\r\n\t\t\t\treturn false;\r\n\t\t} else if (!score.equals(other.score))\r\n\t\t\treturn false;\r\n\t\treturn true;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\treturn \"EvaluatedSearchGraphPath [score=\" + score + \"]\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.8012422323226929, "alphanum_fraction": 0.8012422323226929, "avg_line_length": 21, "blob_id": "4a17b50c3349167186392d6e974d9817ebb2d6ac", "content_id": "a274cd59f147b88786de5c48ce23175ab4a5f442", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 161, "license_type": "no_license", "max_line_length": 74, "num_lines": 7, "path": "/JAICore/jaicore-graph/src/jaicore/graph/IGraphAlgorithmListener.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.graph;\r\n\r\nimport jaicore.basic.algorithm.IAlgorithmListener;\r\n\r\npublic interface IGraphAlgorithmListener<V,E> extends IAlgorithmListener {\r\n\r\n}\r\n" }, { "alpha_fraction": 0.7862949967384338, "alphanum_fraction": 0.7862949967384338, "avg_line_length": 51.8125, "blob_id": "5fbb9eaa7248d4e757811ebb9903637ea7e4c92c", "content_id": "1177e17601953793f64deb49f104ebe3507d3e41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 861, "license_type": "no_license", "max_line_length": 284, "num_lines": 16, "path": "/JAICore/jaicore-search/test/jaicore/search/algorithms/standard/bestfirst/npuzzle/test/NPuzzleRedundantTester.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.bestfirst.npuzzle.test;\r\n\r\npublic class NPuzzleRedundantTester {\r\n//\t\textends NPuzzleStandardTester<GeneralEvaluatedTraversalTree<NPuzzleNode, String, Double>, SearchAlgorithmSolution<NPuzzleNode, String, Double>, Node<NPuzzleNode, Double>, String> {\r\n//\r\n//\t@Override\r\n//\tpublic IORGraphSearchFactory<GeneralEvaluatedTraversalTree<NPuzzleNode, String, Double>, SearchAlgorithmSolution<NPuzzleNode, String, Double>, NPuzzleNode, String, Double, Node<NPuzzleNode, Double>, String, IGraphAlgorithmListener<Node<NPuzzleNode, Double>, String>> getFactory() {\r\n//\t\treturn new BestFirstFactory<>();\r\n//\t}\r\n//\r\n//\t@Override\r\n//\tpublic AlgorithmProblemReducer<NPuzzleProblem, GeneralEvaluatedTraversalTree<NPuzzleNode, String, Double>> getProblemReducer() {\r\n//\t\treturn new NPuzzleToGeneralTraversalTreeReducer();\r\n//\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.6831076145172119, "alphanum_fraction": 0.6849607825279236, "avg_line_length": 63.3577995300293, "blob_id": "ea30c1760a01c1193c03ac5a1c66c0aef5e0032e", "content_id": "48d204655aee06770a81a9bd1978d0152ea522f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 7015, "license_type": "no_license", "max_line_length": 430, "num_lines": 109, "path": "/JAICore/jaicore-planning/src/jaicore/planning/model/task/ceocipstn/StandardProblemFactory.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.model.task.ceocipstn;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\nimport jaicore.logic.fol.structure.CNFFormula;\nimport jaicore.logic.fol.structure.Literal;\nimport jaicore.logic.fol.structure.Monom;\nimport jaicore.logic.fol.structure.VariableParam;\nimport jaicore.logic.fol.theories.EvaluablePredicate;\nimport jaicore.planning.graphgenerators.task.ceociptfd.OracleTaskResolver;\nimport jaicore.planning.model.ceoc.CEOCOperation;\nimport jaicore.planning.model.task.stn.TaskNetwork;\n\npublic class StandardProblemFactory {\n\t\n\tpublic static CEOCIPSTNPlanningProblem getNestedDichotomyCreationProblem(String rootClusterName, Collection<String> classesInit, boolean objectCreation, int maxExpRange, int maxRefinement, Map<String, EvaluablePredicate> evaluablePredicates, Map<String, OracleTaskResolver> oracleResolvers) {\n\t\t\n\t\t/* define operations */\n\t\tList<String> classes = classesInit.stream().sorted().collect(Collectors.toList());\n\t\tif (!classes.equals(classesInit)) {\n\t\t\tSystem.out.println(\"Reordered classes!\");\n//\t\t\tSystem.out.println(classesInit);\n//\t\t\tSystem.out.println(classes);\n\t\t}\n\t\tList<CEOCOperation> operations = new ArrayList<>();\n\t\tMap<CNFFormula,Monom> addLists = new HashMap<>();\n\t\t\n\t\t/* operation to close a */\n\t\t\n\n\t\taddLists.put(new CNFFormula(), new Monom(\"cluster(lc) & cluster(rc) & parent(c,lc) & parent(c,rc) & rgt(lc,rc)\"));\n\t\toperations.add(new CEOCOperation(\"createclusters\", Arrays.asList(new VariableParam[] { new VariableParam(\"c\"), new VariableParam(\"lc\"), new VariableParam(\"rc\") }), new Monom(), addLists, new HashMap<>(), Arrays.asList()));\n\t\t\n\t\t\n\t\taddLists = new HashMap<>();\n\t\tMonom precondition = new Monom();\n\t\taddLists = new HashMap<>();\n\t\tfor (String c : classes) {\n\t\t\taddLists.put(new CNFFormula(new Monom(\"$contains('\" + c + \"', p) & $contains('\" + c + \"',ss)\")), new Monom(\"in('\" + c + \"', lc)\"));\n\t\t\taddLists.put(new CNFFormula(new Monom(\"$contains('\" + c + \"', p) & !$contains('\" + c + \"',ss)\")), new Monom(\"in('\" + c + \"', rc)\"));\n\t\t}\n\t\toperations.add(new CEOCOperation(\"configChildNodes\", Arrays.asList(new VariableParam[] { new VariableParam(\"p\"), new VariableParam(\"ss\"), new VariableParam(\"lc\"), new VariableParam(\"rc\") }), precondition, addLists, new HashMap<>(), Arrays.asList()));\n\t\t\n\t\t/* operation to set exponent value for SVM c parameter */\n\t\taddLists = new HashMap<>();\n\t\toperations.add(new CEOCOperation(\"setExpVal\", Arrays.asList(new VariableParam[] { new VariableParam(\"c\"), new VariableParam(\"x\") }), new Monom(), addLists, new HashMap<>(), new ArrayList<>()));\n\t\taddLists = new HashMap<>();\n\t\toperations.add(new CEOCOperation(\"setSVMCVal\", Arrays.asList(new VariableParam[] { new VariableParam(\"c\"), new VariableParam(\"k\"), new VariableParam(\"x\") }), new Monom(), addLists, new HashMap<>(), new ArrayList<>()));\n\t\t\n\t\t\n\t\t/* define STN methods for the domain */\n\t\tLiteral taskRefine = new Literal(\"refine(c)\");\n\t\tLiteral taskConfigureSVM = new Literal(\"configureSVM(c,l,r)\");\n\t\tLiteral taskConfigureChildNodes = new Literal(\"configChildNodesT(c,l,r)\");\n\t\t\n\t\tList<OCIPMethod> methods = new ArrayList<>();\n\t\tif (objectCreation) {\n\t\t\tmethods.add(new OCIPMethod(\"refineNode\", Arrays.asList(new VariableParam[] { new VariableParam(\"c\"), new VariableParam(\"lc\"), new VariableParam(\"rc\") }), taskRefine, new Monom(), new TaskNetwork(\"createclusters(c,lc,rc) -> configChildNodesT(c,lc,rc) -> refine(lc) -> refine(rc)\"), false, Arrays.asList(new VariableParam[]{ new VariableParam(\"lc\"), new VariableParam(\"rc\")}), new Monom(\"notempty(c)\")));\n\t\t}\n\t\telse {\n\t\t\tmethods.add(new OCIPMethod(\"refineNode\", Arrays.asList(new VariableParam[] { new VariableParam(\"c\"), new VariableParam(\"lc\"), new VariableParam(\"rc\"), new VariableParam(\"next\") }), taskRefine, new Monom(\"nextVar(lc) & succ(lc,rc) & succ(rc,next)\"), new TaskNetwork(\"configChildNodesT(c,lc,rc) -> refine(lc) -> refine(rc)\"), false, new ArrayList<>(), new Monom(\"notempty(c)\")));\n\t\t}\n\t\tmethods.add(new OCIPMethod(\"configChildNodesM\", Arrays.asList(new VariableParam[] { new VariableParam(\"c\"), new VariableParam(\"lc\"),new VariableParam(\"rc\"), new VariableParam(\"ss\")}), taskConfigureChildNodes, new Monom(\"cluster(c) & parent(c,lc) & parent(c,rc) & cluster(lc) & cluster(rc) & rgt(lc,rc)\"), new TaskNetwork(\"configChildNodes(c,ss,lc,rc)\"), false, new ArrayList<>(), new Monom(\"validRefinementChoice(ss,c)\")));\n\t\tmethods.add(new OCIPMethod(\"closeNode\", Arrays.asList(new VariableParam[] { new VariableParam(\"c\") }), taskRefine, new Monom(\"cluster(c)\"), new TaskNetwork(\"\"), false, new ArrayList<>(), new Monom(\"oneitem(c)\")));\n\t\t\n\t\tfor (int i = -1 * maxExpRange; i <= maxExpRange; i++)\n\t\t\tmethods.add(new OCIPMethod(\"setupSVMCForValue\" + i, Arrays.asList(new VariableParam[] { new VariableParam(\"c\"), new VariableParam(\"l\"), new VariableParam(\"r\")}), taskConfigureSVM, new Monom(), new TaskNetwork(\"configureSVM1thPlace(c,l,r)\"), false, new ArrayList<>(), new Monom()));\n\t\tfor (int i = 1; i <= maxRefinement; i++) {\n\t\t\tif (i < maxRefinement)\n\t\t\t\tmethods.add(new OCIPMethod(\"setPlace\" + i + \"ofSVMCParam\", \t\t \tArrays.asList(new VariableParam[] { new VariableParam(\"c\"), new VariableParam(\"l\"), new VariableParam(\"r\"), new VariableParam(\"x\") }), new Literal(\"configureSVM\" + i + \"thPlace(c,l,r)\"), new Monom(\"!configClosed(c) & digit(x)\"), new TaskNetwork(\"setSVMCVal(c, '\" + i + \"',x) -> configureSVM\" + (i + 1) + \"thPlace(c,l,r)\"), false, new ArrayList<>(), new Monom()));\n\t\t\tmethods.add(new OCIPMethod(\"setPlaceAndClose\" + i + \"ofSVMCParam\",\tArrays.asList(new VariableParam[] { new VariableParam(\"c\"), new VariableParam(\"l\"), new VariableParam(\"r\"), new VariableParam(\"x\") }), new Literal(\"configureSVM\" + i + \"thPlace(c,l,r)\"), new Monom(\"!configClosed(c) & digit(x)\"), new TaskNetwork(\"setSVMCVal(c, '\" + i + \"',x)\"), false, new ArrayList<>(), new Monom()));\n\t\t}\n\t\t\n\t\t/* create STN domain */\n\t\tCEOCIPSTNPlanningDomain domain = new CEOCIPSTNPlanningDomain(operations, methods);\n\t\t\n\t\tMonom init = new Monom();\n\t\tinit.add(new Literal(\"cluster('\" + rootClusterName + \"')\"));\n\t\tfor (String c : classes) {\n\t\t\tinit.add(new Literal(\"in('\" + c + \"','\" + rootClusterName + \"')\"));\n\t\t}\n\t\t\n\t\t/* for SVM config */\n\t\tfor (int exp = -5; exp <= 5; exp++)\n\t\t\tinit.add(new Literal(\"exponent('\" + exp + \"')\"));\n\t\tfor (int i = 0; i <= 9; i+=2)\n\t\t\tinit.add(new Literal(\"digit('\" + i + \"')\"));\n\t\t\n\t\t/* if no constant creation is allowed, add all successor objects */\n\t\tif (!objectCreation) {\n\t\t\tinit.add(new Literal(\"nextVar('var0')\"));\n\t\t\tString currentVar = \"var0\";\n\t\t\tfor (int i = 1; i < 2 * classes.size(); i++) {\n\t\t\t\tString nextVar = \"var\" + i;\n\t\t\t\tinit.add(new Literal(\"succ('\" + currentVar + \"', '\" + nextVar + \"')\"));\n\t\t\t\tcurrentVar = nextVar;\n\t\t\t}\n\t\t}\n\t\t\n\t\tTaskNetwork network = new TaskNetwork(\"refine('\" + rootClusterName + \"')\");\n\t\treturn new CEOCIPSTNPlanningProblem(domain, null, init, network, evaluablePredicates, oracleResolvers);\n\t}\n}\n" }, { "alpha_fraction": 0.6974973082542419, "alphanum_fraction": 0.6974973082542419, "avg_line_length": 21.975000381469727, "blob_id": "51d4e0366528a88c2cec49324bb5dff165c16e23", "content_id": "98e55e21ab4ad8fea188a05f059f7ee30492508a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 919, "license_type": "no_license", "max_line_length": 81, "num_lines": 40, "path": "/JAICore/jaicore-graphvisualizer/src/jaicore/graphvisualizer/gui/dataVisualizer/IVisualizer.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.graphvisualizer.gui.dataVisualizer;\n\nimport javafx.scene.Node;\n\n/**\n * An Interface, which describes Visualizer, which can be added to the gui.\n * \n * @author jkoepe\n *\n */\n\npublic interface IVisualizer {\n\n\t/**\n\t * Returns a javafx-node, which is later shown in the visualizer.\n\t * \n\t * @return javafx.node which contains the visualization.\n\t */\n\tpublic Node getVisualization();\n\n\t/**\n\t * This method determines, which supplier adds the events to this visualizer. To\n\t * add a supplier, the class name of the supplier is needed.\n\t * \n\t * @return Simpleclass name of the event supplier\n\t */\n\tdefault String getSupplier() {\n\t\treturn \"\";\n\t}\n\n\t/**\n\t * This method is used to get the title of the visualizer. The main application\n\t * is to set the title which is shown in the coorsponding tab in the main frame\n\t * \n\t * @return The title of the visualizer\n\t */\n\tdefault String getTitle() {\n\t\treturn \"\";\n\t}\n}\n" }, { "alpha_fraction": 0.7746815085411072, "alphanum_fraction": 0.7762739062309265, "avg_line_length": 29.399999618530273, "blob_id": "7d812beb6b1594de20d628540b07906d462b9fe7", "content_id": "17412d164ae689717445ae7d0bc6b02f4345e0ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1256, "license_type": "no_license", "max_line_length": 116, "num_lines": 40, "path": "/JAICore/jaicore-concurrent/src/jaicore/concurrent/CancellationTimerTask.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.concurrent;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport jaicore.basic.Cancelable;\r\n\r\npublic class CancellationTimerTask extends NamedTimerTask {\r\n\tprivate static final Logger logger = LoggerFactory.getLogger(InterruptionTimerTask.class);\r\n\tprivate final Cancelable thingToBeCanceled;\r\n\tprivate final Runnable hookToExecutePriorToCancel;\r\n\r\n\tpublic CancellationTimerTask(String descriptor, Cancelable cancelable, Runnable hookToExecutePriorToInterruption) {\r\n\t\tsuper(descriptor);\r\n\t\tthis.thingToBeCanceled = cancelable;\r\n\t\tthis.hookToExecutePriorToCancel = hookToExecutePriorToInterruption;\r\n\t}\r\n\r\n\tpublic CancellationTimerTask(String descriptor, Cancelable thingToBeCanceled) {\r\n\t\tthis(descriptor, thingToBeCanceled, null);\r\n\t}\r\n\r\n\tpublic Cancelable getCancelable() {\r\n\t\treturn thingToBeCanceled;\r\n\t}\r\n\r\n\tpublic Runnable getHookToExecutePriorToInterruption() {\r\n\t\treturn hookToExecutePriorToCancel;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void run() {\r\n\t\tif (hookToExecutePriorToCancel != null) {\r\n\t\t\tlogger.info(\"Executing pre-interruption hook.\");\r\n\t\t\thookToExecutePriorToCancel.run();\r\n\t\t}\r\n\t\tlogger.info(\"Executing cancel task {}. Canceling {}\", getDescriptor(), thingToBeCanceled);\r\n\t\tthingToBeCanceled.cancel();\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.533312201499939, "alphanum_fraction": 0.5605964660644531, "avg_line_length": 32.00523376464844, "blob_id": "cdaef1e9d8fb1781e501b65a1147c0759705bc16", "content_id": "0aa62cfcc8160b1b669776ca8463fa6d02c4731a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 6304, "license_type": "no_license", "max_line_length": 102, "num_lines": 191, "path": "/JAICore/jaicore-search/test/jaicore/search/algorithms/standard/uncertainty/TestParetoSelection.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.uncertainty;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport jaicore.search.algorithms.standard.uncertainty.paretosearch.CosinusDistanceComparator;\nimport jaicore.search.algorithms.standard.uncertainty.paretosearch.ParetoNode;\nimport jaicore.search.algorithms.standard.uncertainty.paretosearch.ParetoSelection;\nimport jaicore.search.model.travesaltree.Node;\n\nimport java.util.ArrayList;\nimport java.util.PriorityQueue;\n\npublic class TestParetoSelection {\n\n private Node<String, Double> p, q, r, s, t, u, p2, q2, r2, s2, t2, u2;\n\n @Before\n public void setUp() {\n p = new Node<>(null, \"1\");\n p.setAnnotation(\"f\", 2.0);\n p.setAnnotation(\"uncertainty\", 0.9d);\n\n q = new Node<>(null, \"2\");\n q.setAnnotation(\"f\", 3.0);\n q.setAnnotation(\"uncertainty\", 0.6d);\n\n r = new Node<>(null, \"3\");\n r.setAnnotation(\"f\", 5.0);\n r.setAnnotation(\"uncertainty\", 0.4);\n\n s = new Node<>(null, \"4\");\n s.setAnnotation(\"f\", 2.5d);\n s.setAnnotation(\"uncertainty\", 0.3);\n\n t = new Node<>(null, \"5\");\n t.setAnnotation(\"f\", 8.0);\n t.setAnnotation(\"uncertainty\", 0.3);\n\n u = new Node<>(null, \"6\");\n u.setAnnotation(\"f\", 7.0);\n u.setAnnotation(\"uncertainty\", 0.1);\n\n p2 = new Node<>(null, \"1\");\n p2.setAnnotation(\"f\", -2.0);\n p2.setAnnotation(\"uncertainty\", 0.9d);\n\n q2 = new Node<>(null, \"2\");\n q2.setAnnotation(\"f\", -3.0);\n q2.setAnnotation(\"uncertainty\", 0.6d);\n\n r2 = new Node<>(null, \"3\");\n r2.setAnnotation(\"f\", -5.0);\n r2.setAnnotation(\"uncertainty\", 0.4);\n\n s2 = new Node<>(null, \"4\");\n s2.setAnnotation(\"f\", -2.5d);\n s2.setAnnotation(\"uncertainty\", 0.3);\n\n t2 = new Node<>(null, \"5\");\n t2.setAnnotation(\"f\", -8.0);\n t2.setAnnotation(\"uncertainty\", 0.3);\n\n u2 = new Node<>(null, \"6\");\n u2.setAnnotation(\"f\", -7.0);\n u2.setAnnotation(\"uncertainty\", 0.1);\n }\n\n @Test\n public void testCosinusDistanceComparatorWithFNegativeValues() {\n CosinusDistanceComparator c = new CosinusDistanceComparator(-1.0, 1.0);\n\n double d1 = 1 - c.cosineSimilarity(2.0, 0.3d);\n double d4 = 1 - c.cosineSimilarity(-2.0d, 0.3d);\n\n System.out.println(d1);\n System.out.println(d4);\n //System.out.println(d6);\n\n }\n\n @Test\n public void testCosinusDistanceComparator() {\n CosinusDistanceComparator c = new CosinusDistanceComparator(10.0, 1.0);\n\n ParetoNode pp = new ParetoNode(p, 1);\n ParetoNode ss = new ParetoNode(s, 1);\n ParetoNode uu = new ParetoNode(u, 1);\n\n double d1 = 1 - c.cosineSimilarity(2.0, 0.9);\n double d4 = 1 - c.cosineSimilarity(2.5d, 0.3d);\n double d6 = 1 - c.cosineSimilarity(7, 0.1);\n\n System.out.println(\"d1 = \" + d1);\n System.out.println(\"d4 = \" + d4);\n System.out.println(\"d6 = \" + d6);\n\n System.out.println(\"Compare 1=(2, 0.9) to 4=(2.5, 0.3)\");\n System.out.println(c.compare(pp, ss));\n System.out.println(\"==============================\");\n\n System.out.println(\"Compare 6=(7, 0.1) to 4=(2.5, 0.3)\");\n System.out.println(c.compare(uu, ss));\n System.out.println(\"==============================\");\n\n System.out.println(\"Compare 6=(7, 0.1) to 1=(2, 0.9)\");\n System.out.println(c.compare(uu, pp));\n System.out.println(\"==============================\");\n\n }\n\n @Test\n public void testParetoFront() {\n CosinusDistanceComparator c = new CosinusDistanceComparator(-10.0, 1);\n PriorityQueue pareto = new PriorityQueue<ParetoNode<String, Double>>(c);\n ParetoSelection<String, Double> paretoSelection = new ParetoSelection<String, Double>(pareto);\n\n paretoSelection.add(p);\n System.out.println(paretoSelection);\n System.out.println(\"===================\");\n\n paretoSelection.add(q);\n System.out.println(paretoSelection);\n System.out.println(\"===================\");\n\n paretoSelection.add(r);\n System.out.println(paretoSelection);\n System.out.println(\"===================\");\n\n paretoSelection.add(s);\n System.out.println(paretoSelection);\n System.out.println(\"===================\");\n\n paretoSelection.add(t);\n System.out.println(paretoSelection);\n System.out.println(\"===================\");\n\n paretoSelection.add(u);\n System.out.println(paretoSelection);\n System.out.println(\"===================\");\n\n for (int i=0; i<=5; i++) {\n Node<String, Double> n = paretoSelection.peek();\n paretoSelection.remove(n);\n System.out.println(n);\n System.out.println(paretoSelection);\n System.out.println(\"===================\");\n }\n }\n\n @Test\n public void testParetoFrontWithNegativeFValues() {\n CosinusDistanceComparator c = new CosinusDistanceComparator(-10.0, 1);\n PriorityQueue pareto = new PriorityQueue<ParetoNode<String, Double>>(c);\n ParetoSelection<String, Double> paretoSelection = new ParetoSelection<String, Double>(pareto);\n\n paretoSelection.add(p);\n System.out.println(paretoSelection);\n System.out.println(\"===================\");\n\n paretoSelection.add(q);\n System.out.println(paretoSelection);\n System.out.println(\"===================\");\n\n paretoSelection.add(r);\n System.out.println(paretoSelection);\n System.out.println(\"===================\");\n\n paretoSelection.add(s);\n System.out.println(paretoSelection);\n System.out.println(\"===================\");\n\n paretoSelection.add(t);\n System.out.println(paretoSelection);\n System.out.println(\"===================\");\n\n paretoSelection.add(u);\n System.out.println(paretoSelection);\n System.out.println(\"===================\");\n\n for (int i=0; i<=5; i++) {\n Node<String, Double> n = paretoSelection.peek();\n paretoSelection.remove(n);\n System.out.println(n);\n System.out.println(paretoSelection);\n System.out.println(\"===================\");\n }\n\n }\n\n}\n" }, { "alpha_fraction": 0.5837717056274414, "alphanum_fraction": 0.5872788429260254, "avg_line_length": 49.167999267578125, "blob_id": "b8933a990981c9823d87f248dd0e042c0c5a7332", "content_id": "c378c0d8dd35d00f904f802521756fe3a77d9a04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6273, "license_type": "no_license", "max_line_length": 192, "num_lines": 125, "path": "/softwareconfiguration/mlplan/testrsc/hascoSL/arffcontainer.py", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "import arff\n\ndef parse(arff_, is_path = True, dense_mode = True):\n \"\"\" Opens and reads the file located at path. \n May also be called with the content string. \n arff_: either arff file path or arff file content. treated based on how is_bath is assigned.\n is_path: bool, if true, arff_ is an arff-file path. If false, arff_ is treated as the content of an arffile as a string\n Returns an ArffStructure object or None if there was an error.\n \"\"\"\n if is_path :\n arff_data = open(arff_,'r')\n else :\n arff_data = arff_ # here path is actualy the conent of an arff file.\n try:\n try:\n if dense_mode:\n mode = arff.DENSE\n else:\n mode = arff.LOD\n arff_parsed = arff.load(arff_data, return_type=mode, encode_nominal=True)\n except: # excpetion is thrown when sparsed data is loaded in DENSE mode.\n if dense_mode:\n arff_parsed = parse(arff_, is_path, False)# arff may be in sparse formate\n\n obj = ArffStructure(arff_parsed)\n return obj \n except Exception as e:\n import traceback\n traceback.print_tb(e.__traceback__)\n return None # return None to signify an error. (Raising Excpeiton might be a better solution)\n finally :\n if is_path : # close file if necessary\n arff_data.close()\n\n\n\nclass ArffStructure:\n \"\"\" Stores the arff data in a way it can be used by tensorflow.\n Args: \n arff_data: arff_data which is a dictionary returned by the arff.py module\n Instance Attributes:\n class_list: list of all the classes in this arff data\n in_size: size of the input layer of the neural network\n out_size: size of the output layer of the neural network\n entry_size: number of training entries. Its the height of the input matrix.\n input_matrix: a list of a list. input_matrix[i][j] stores the input values of attribute j of entry i from the arff file.\n output_matrix: a list of a list. output_vecotr[i] stores the training output of entry i from the arff file in a one-hot manner.\n \"\"\"\n def __init__(self, arff_data):\n \"\"\" Reads and encapsulates arff_data which is a dictionary returned by the arff.py module.\n \"\"\"\n attributes_list = arff_data['attributes'] # attribute list containing a tupels (x,y). \n # x = attribute name. y = attribute type\n data_list = arff_data['data'] # list of data entries. data entries are lists. \n\n # looking for the class attribute in the list and extracting it.\n class_index = 0 # save at which index the class attribute was found\n\n for tupel in attributes_list:\n if tupel[0] == 'class':\n classtupel = tupel\n self.class_list = classtupel[1]\n attributes_list.remove(tupel) # Now attribute list only consists of input attributes \n break\n class_index += 1\n \n if not hasattr(self, 'class_list'):\n # class list couldn'd be found. use last tupel in attributes_list instead\n self.class_list = attributes_list.pop()[1]\n class_index = len(attributes_list)\n\n self.in_size = len(attributes_list)\n if type(self.class_list) == str:\n # class is only a single type\n self.out_size = 1\n else :\n self.out_size = len(self.class_list)\n\n\n # Now, extract data from data_list which was taken from arff\n\n self.input_matrix = [] \n self.output_matrix = []\n\n sparse_format = type(data_list[0]) == dict # true, if arff was in a sparsed format. (Im new to python and dont know how to use ducktyping here.)\n\n acc_list = [0]*(self.in_size+1) # stores the accumulated values for every entry in attribute. We need this to fill missing data with the median of attribute values. *See end of method*\n missing_list = [] # list of tupel. stores the position of every missing entry.\n entry_index = 0;\n for entry in data_list:\n self.input_matrix.append([]) # append a new empty row \n # every entry contains a value for each attribute. Extract it and add it to the value_list\n # for every attribute extract value\n for attr_index in range(self.in_size + 1) : \n if sparse_format :\n # If sparse_format, entry is a dict (x,y). x is index of attribute. y is value.\n if attr_index in entry : # value wasnt omitted.\n value = (entry[attr_index]) # may return None if \"?\" value was used\n else : # was omitted in the arff data. So the value is 0.\n value = 0\n else :\n # Not sparse_format so entry is a list of every value. \n value = entry[attr_index] # may return None if \"?\" value was used\n # value has been extracted. Now decide where to store it\n if attr_index == class_index : # value is class number. add to output\n #one hot the output to be used with softmax in tensorflow\n self.output_matrix.append([])\n for class_index_ in range(self.out_size):\n self.output_matrix[-1].append( 1 if class_index_ == value else 0)\n else : # add to input\n self.input_matrix[-1].append(value) # add value to the last row\n if value is not None: # value is available\n acc_list[attr_index] += value\n else : # value is missing. add entry to missing_list\n missing_list.append((entry_index,attr_index))\n\n acc_list[attr_index] += value if value else 0 # accumulate value for this attribute\n \n entry_index += 1\n #store data set length\n self.entry_size = len(self.input_matrix)\n\n # substitute missing values with the average of the attribute\n for tupel in missing_list : \n self.input_matrix[tupel[0]][tupel[1]] = acc_list[tupel[1]] / len(data_list) # mean of this attribute\n\n\n" }, { "alpha_fraction": 0.7207692265510559, "alphanum_fraction": 0.7230769395828247, "avg_line_length": 25, "blob_id": "310f8f5e43e15e2896a3b05fdc3edf2546f70e0d", "content_id": "dbdd05d88ec56439f33370e491dc475f33a9ad38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1300, "license_type": "no_license", "max_line_length": 163, "num_lines": 50, "path": "/JAICore/jaicore-planning/src/jaicore/planning/model/task/ceocstn/OCMethod.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.model.task.ceocstn;\n\nimport java.util.List;\n\nimport jaicore.logic.fol.structure.Literal;\nimport jaicore.logic.fol.structure.Monom;\nimport jaicore.logic.fol.structure.VariableParam;\nimport jaicore.planning.model.task.stn.Method;\nimport jaicore.planning.model.task.stn.TaskNetwork;\n\n@SuppressWarnings(\"serial\")\npublic class OCMethod extends Method {\n\n\tprivate final List<VariableParam> outputs;\n\n\tpublic OCMethod(String name, List<VariableParam> parameters, Literal task, Monom precondition, TaskNetwork network, boolean lonely, List<VariableParam> outputs) {\n\t\tsuper(name, parameters, task, precondition, network, lonely);\n\t\tthis.outputs = outputs;\n\t}\n\n\tpublic List<VariableParam> getOutputs() {\n\t\treturn outputs;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = super.hashCode();\n\t\tresult = prime * result + ((outputs == null) ? 0 : outputs.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (!super.equals(obj))\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tOCMethod other = (OCMethod) obj;\n\t\tif (outputs == null) {\n\t\t\tif (other.outputs != null)\n\t\t\t\treturn false;\n\t\t} else if (!outputs.equals(other.outputs))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n}\n" }, { "alpha_fraction": 0.7685185074806213, "alphanum_fraction": 0.7740740776062012, "avg_line_length": 28, "blob_id": "2b12deb897821b34ce74fd480e3e36c600ad6722", "content_id": "e8b1d8838b680599aca3771b080270ca92ab7979", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 540, "license_type": "no_license", "max_line_length": 91, "num_lines": 18, "path": "/softwareconfiguration/mlplan/src/de/upb/crc901/mlplan/multilabel/MultiLabelMySQLHandle.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package de.upb.crc901.mlplan.multilabel;\r\n\r\nimport jaicore.ml.experiments.MySQLExperimentDatabaseHandle;\r\n\r\n@SuppressWarnings(\"serial\")\r\npublic class MultiLabelMySQLHandle extends MySQLExperimentDatabaseHandle {\r\n\r\n\tpublic MultiLabelMySQLHandle(String host, String user, String password, String database) {\r\n\t\tsuper(host, user, password, database);\r\n\t\t// TODO Auto-generated constructor stub\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic void addResultEntry(int runId, double score) throws Exception {\r\n\t\tthrow new UnsupportedOperationException();\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.7724595069885254, "alphanum_fraction": 0.7792710065841675, "avg_line_length": 32.95000076293945, "blob_id": "0f5c83a0d90ae58aa63ffffd1aab555d17120c51", "content_id": "bad08aeacdb0c86b6cbf8e7d781e0f27c247ad93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5432, "license_type": "no_license", "max_line_length": 111, "num_lines": 160, "path": "/softwareconfiguration/mlplan/src/de/upb/crc901/mlplan/metamining/WEKAMetaminer.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package de.upb.crc901.mlplan.metamining;\n\nimport java.util.ArrayList;\nimport java.util.Enumeration;\nimport java.util.HashMap;\n\nimport org.nd4j.linalg.api.ndarray.INDArray;\nimport org.nd4j.linalg.factory.Nd4j;\n\nimport de.upb.crc901.mlplan.metamining.pipelinecharacterizing.IPipelineCharacterizer;\nimport de.upb.crc901.mlplan.metamining.pipelinecharacterizing.WEKAPipelineCharacterizer;\nimport de.upb.crc901.mlplan.metamining.similaritymeasures.F3Optimizer;\nimport de.upb.crc901.mlplan.metamining.similaritymeasures.IHeterogenousSimilarityMeasureComputer;\nimport de.upb.crc901.mlplan.multiclass.wekamlplan.weka.WEKAPipelineFactory;\nimport de.upb.crc901.mlplan.multiclass.wekamlplan.weka.model.MLPipeline;\nimport hasco.metamining.IMetaMiner;\nimport hasco.model.ComponentInstance;\nimport hasco.serialization.ComponentLoader;\nimport weka.core.Attribute;\nimport weka.core.Instances;\n\npublic class WEKAMetaminer implements IMetaMiner {\n\n\tprivate boolean hasBeenBuilt = false;\n\tprivate WEKAPipelineFactory wekaPipelineFactory = new WEKAPipelineFactory();\n\n\tprivate Instances dataset;\n\tprivate INDArray datasetMetafeatures;\n\n\tprivate String datasetSet = \"all\";\n\tprivate String metafeatureSet = \"all\";\n\n\tprivate IHeterogenousSimilarityMeasureComputer similarityMeasure = new F3Optimizer(0.1);\n\tprivate IPipelineCharacterizer pipelineCharacterizer = new WEKAPipelineCharacterizer();\n\tprivate ComponentLoader componentLoader;\n\n\tpublic WEKAMetaminer(Instances dataset) {\n\t\tthis.dataset = dataset;\n\t}\n\n\t@Override\n\tpublic double score(ComponentInstance componentInstance) {\n\t\tif (!hasBeenBuilt) {\n\t\t\tthrow new RuntimeException(\"Metaminer has not been built!\");\n\t\t}\n\t\ttry {\n\t\t\tMLPipeline pipeline = wekaPipelineFactory.getComponentInstantiation(componentInstance);\n\t\t\tdouble[] pipelineMetafeatures = pipelineCharacterizer.characterize(pipeline);\n\t\t\treturn similarityMeasure.computeSimilarity(datasetMetafeatures, Nd4j.create(pipelineMetafeatures));\n\t\t} catch (Exception e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tpublic void build() throws Exception {\n\t\t// Check whether has been built\n\t\tif (hasBeenBuilt) {\n\t\t\tthrow new Exception(\"MetaMiner has already been built!\");\n\t\t}\n\n\t\t// ----- Data set Characterization -----\n\t\t// Get training data for given datasetSet and metaFeatureSet from DB connection\n\t\t// TODO import the db connection - will result in this info\n\t\tInstances metaFeatureInformation = null;\n\n\t\t// Convert to matrix (Matrix X with rows representing data sets) with ascending\n\t\t// data set indices (data set index itself excluded)\n\t\tINDArray datasetsMetafeatures = Nd4j.create(metaFeatureInformation.size() - 1,\n\t\t\t\tmetaFeatureInformation.numAttributes());\n\t\tfor (int i = 1; i < metaFeatureInformation.size(); i++) {\n\t\t\tdatasetsMetafeatures.putRow(i - 1, Nd4j.create(metaFeatureInformation.get(i).toDoubleArray()));\n\t\t}\n\n\t\t// Characterize the given data set with characterizer (set x)\n\t\t// TODO import data set characterizer - will result in this info\n\t\tHashMap<String, Double> datasetCharacterization = null;\n\n\t\t// Convert the characterization to a vector of double (ensure same order of\n\t\t// attributes as training data)\n\t\tdatasetMetafeatures = Nd4j.create(datasetCharacterization.size());\n\t\tint i = 0;\n\t\tfor (Enumeration<Attribute> attributes = metaFeatureInformation.enumerateAttributes(); attributes\n\t\t\t\t.hasMoreElements(); i++) {\n\t\t\tdatasetMetafeatures.putScalar(i, datasetCharacterization.get(attributes.nextElement().name()));\n\t\t}\n\t\t;\n\n\t\t// ----- Pipeline Characterization -----\n\t\t// Get PerformanceSamples from knowledge base according to given data set set\n\t\t// TODO import knowledge base\n\t\t// Compute Rank Matrix R\n\t\tINDArray rankMatrix = null;\n\t\t// Extract list of distinct pipelines from that (or purposefully get a only\n\t\t// samples for a list of pipelines before!)\n\t\tArrayList<MLPipeline> distinctPipelines = new ArrayList<MLPipeline>();\n\n\t\t// Initialize PipelineCharacterizer with list of distinct pipelines\n\t\tpipelineCharacterizer.build(distinctPipelines);\n\n\t\t// Get Characterization of base pipelines from PipelineCharacterizer (Matrix W)\n\t\tINDArray pipelinesMetafeatures = Nd4j.create(pipelineCharacterizer.getCharacterizationsOfTrainingExamples());\n\n\t\t// Initialize HeterogenousSimilarityMeasures\n\t\tsimilarityMeasure.build(datasetsMetafeatures, pipelinesMetafeatures, rankMatrix);\n\n\t\t// building is finished\n\t\thasBeenBuilt = true;\n\t}\n\n\tpublic Instances getDataset() {\n\t\treturn dataset;\n\t}\n\n\t/**\n\t * @return the datasetSet\n\t */\n\tpublic String getDatasetSet() {\n\t\treturn datasetSet;\n\t}\n\n\t/**\n\t * @param datasetSet\n\t * the datasetSet to set\n\t */\n\tpublic void setDatasetSet(String datasetSet) {\n\t\tthis.datasetSet = datasetSet;\n\t}\n\n\t/**\n\t * @return the metafeatureSet\n\t */\n\tpublic String getMetafeatureSet() {\n\t\treturn metafeatureSet;\n\t}\n\n\t/**\n\t * @param metafeatureSet\n\t * the metafeatureSet to set\n\t */\n\tpublic void setMetafeatureSet(String metafeatureSet) {\n\t\tthis.metafeatureSet = metafeatureSet;\n\t}\n\n\tpublic IHeterogenousSimilarityMeasureComputer getSimilarityMeasure() {\n\t\treturn similarityMeasure;\n\t}\n\n\tpublic void setSimilarityMeasure(IHeterogenousSimilarityMeasureComputer similarityMeasure) {\n\t\tthis.similarityMeasure = similarityMeasure;\n\t}\n\n\tpublic IPipelineCharacterizer getPipelineCharacterizer() {\n\t\treturn pipelineCharacterizer;\n\t}\n\n\tpublic void setPipelineCharacterizer(IPipelineCharacterizer pipelineCharacterizer) {\n\t\tthis.pipelineCharacterizer = pipelineCharacterizer;\n\t}\n\n}\n" }, { "alpha_fraction": 0.7414113283157349, "alphanum_fraction": 0.7497678995132446, "avg_line_length": 33.31147384643555, "blob_id": "0c7353e2a830177db9d00241d6256de67f6511c1", "content_id": "5ea0e95d1875e7598c601ab69cd24cb540360274", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2154, "license_type": "no_license", "max_line_length": 235, "num_lines": 61, "path": "/JAICore/jaicore-planning/test/jaicore/planning/task/ForwardDecompositionTest.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.task;\r\n\r\nimport static org.junit.Assert.assertEquals;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\n\r\nimport org.junit.Test;\r\n\r\nimport jaicore.basic.MathExt;\r\nimport jaicore.basic.algorithm.AlgorithmEvent;\r\nimport jaicore.planning.algorithms.events.PlanFoundEvent;\r\nimport jaicore.planning.algorithms.forwarddecomposition.ForwardDecompositionHTNPlannerBasedOnBestFirst;\r\nimport jaicore.planning.model.ceoc.CEOCAction;\r\nimport jaicore.planning.model.ceoc.CEOCOperation;\r\nimport jaicore.planning.model.task.ceocstn.CEOCSTNPlanningProblem;\r\nimport jaicore.planning.model.task.ceocstn.OCMethod;\r\nimport jaicore.planning.model.task.ceocstn.StandardProblemFactory;\r\n\r\npublic class ForwardDecompositionTest {\r\n\r\n\tprivate void solveNDProblem(int numClasses) {\r\n\t\tList<String> classes = new ArrayList<>();\r\n\t\tfor (int i = 1; i <= numClasses; i++)\r\n\t\t\tclasses.add(\"C\" + i);\r\n\t\t\t\r\n\t\tCEOCSTNPlanningProblem<CEOCOperation,OCMethod,CEOCAction> problem = StandardProblemFactory.getNestedDichotomyCreationProblem(\"root\", classes, true, 0, 0);\r\n\t\tForwardDecompositionHTNPlannerBasedOnBestFirst<CEOCOperation, OCMethod, CEOCAction, CEOCSTNPlanningProblem<CEOCOperation,OCMethod,CEOCAction>, Double> planner = new ForwardDecompositionHTNPlannerBasedOnBestFirst<>(problem, n -> 0.0);\r\n\t\t\r\n\t\t\r\n\t\t/* solve problem */\r\n\t\tSystem.out.println(\"Searching all nested dichotomies to sepratate \" + numClasses + \".\");\r\n\t\tint numSolutions = 0;\r\n\t\tfor (AlgorithmEvent ae : planner) {\r\n\t\t\tif (ae instanceof PlanFoundEvent) {\r\n\t\t\t\tnumSolutions ++;\r\n\t\t\t\tif (numSolutions % 100 == 0)\r\n\t\t\t\t\tSystem.out.println(\"Found \" + numSolutions + \" solutions so far ...\");\r\n\t\t\t}\r\n\t\t}\r\n\t\tint numberOfExpectedDichotomies = MathExt.doubleFactorial(2 * numClasses - 3);\r\n\t\tassertEquals(numberOfExpectedDichotomies, numSolutions);\r\n\t\tSystem.out.println(\"Ready, found exactly the expected \" + numberOfExpectedDichotomies + \" solutions.\");\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void solveNDWith3Classes() {\r\n\t\tsolveNDProblem(3);\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void solveNDWith4Classes() {\r\n\t\tsolveNDProblem(4);\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void solveNDWith5Classes() {\r\n\t\tsolveNDProblem(5);\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.6392467617988586, "alphanum_fraction": 0.6412289142608643, "avg_line_length": 20.46808433532715, "blob_id": "c441a38aa79d9d4094739a5115f5cd6d7c7acad8", "content_id": "6ff8bf904180e22a2890cb8f45e5075b6108247a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1009, "license_type": "no_license", "max_line_length": 79, "num_lines": 47, "path": "/JAICore/jaicore-planning/src/jaicore/planning/model/task/stn/TaskNetwork.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.model.task.stn;\n\nimport java.util.List;\n\nimport jaicore.basic.StringUtil;\nimport jaicore.graph.Graph;\nimport jaicore.logic.fol.structure.Literal;\n\n@SuppressWarnings(\"serial\")\npublic class TaskNetwork extends Graph<Literal> {\n\n\tpublic TaskNetwork() {\n\t\tsuper();\n\t}\n\t\n\tpublic TaskNetwork(List<Literal> chain) {\n\t\tint n = chain.size();\n\t\tLiteral prev = null;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tLiteral cur = chain.get(i);\n\t\t\tthis.addItem(cur);\n\t\t\tif (prev != null)\n\t\t\t\tthis.addEdge(prev, cur);\n\t\t\tprev = cur;\n\t\t}\n\t}\n\t\n\tpublic TaskNetwork(Graph<Literal> graph) {\n\t\tsuper(graph);\n\t}\n\n\tpublic TaskNetwork(String chain) {\n\t\tsuper();\n\t\tLiteral current = null;\n\t\tint id = 1;\n\t\tfor (String taskDescription : StringUtil.explode(chain, \"->\")) {\n\t\t\tif (!taskDescription.trim().isEmpty()) {\n\t\t\t\tLiteral task = new Literal(\"tn\" + \"_\" + id + \"-\" + taskDescription.trim());\n\t\t\t\tthis.addItem(task);\n\t\t\t\tif (current != null)\n\t\t\t\t\tthis.addEdge(current, task);\n\t\t\t\tcurrent = task;\n\t\t\t\tid++;\n\t\t\t}\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.7392417788505554, "alphanum_fraction": 0.7429559230804443, "avg_line_length": 34.9815673828125, "blob_id": "7d11625bed33828de59f87dfb47acd0cfb9dd270", "content_id": "dd14d68f90517923cfceb5b9500c4399918df0d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 7808, "license_type": "no_license", "max_line_length": 187, "num_lines": 217, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/lds/LimitedDiscrepancySearch.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.lds;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Comparator;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Queue;\nimport java.util.concurrent.LinkedBlockingQueue;\nimport java.util.stream.Collectors;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport jaicore.basic.algorithm.AlgorithmCanceledEvent;\nimport jaicore.basic.algorithm.AlgorithmEvent;\nimport jaicore.basic.algorithm.AlgorithmFinishedEvent;\nimport jaicore.basic.algorithm.AlgorithmInterruptedEvent;\nimport jaicore.basic.algorithm.SolutionCandidateFoundEvent;\nimport jaicore.graph.TreeNode;\nimport jaicore.graphvisualizer.events.graphEvents.GraphInitializedEvent;\nimport jaicore.graphvisualizer.events.graphEvents.NodeReachedEvent;\nimport jaicore.search.algorithms.standard.AbstractORGraphSearch;\nimport jaicore.search.core.interfaces.GraphGenerator;\nimport jaicore.search.model.other.EvaluatedSearchGraphPath;\nimport jaicore.search.model.probleminputs.NodeRecommendedTree;\nimport jaicore.search.model.travesaltree.NodeExpansionDescription;\nimport jaicore.search.structure.graphgenerator.NodeGoalTester;\nimport jaicore.search.structure.graphgenerator.PathGoalTester;\nimport jaicore.search.structure.graphgenerator.SingleRootGenerator;\nimport jaicore.search.structure.graphgenerator.SuccessorGenerator;\n\n/**\n * Implementation of the algorithm presented in\n * \n * @inproceedings{harvey1995, title={Limited discrepancy search}, author={Harvey, William D and Ginsberg, Matthew L}, booktitle={IJCAI (1)}, pages={607--615}, year={1995} }\n * \n * @author fmohr\n *\n */\npublic class LimitedDiscrepancySearch<T, A, V extends Comparable<V>> extends AbstractORGraphSearch<NodeRecommendedTree<T, A>, EvaluatedSearchGraphPath<T, A, V>, T, A, V, TreeNode<T>, A> {\n\n\t/* logging */\n\tprivate final Logger logger = LoggerFactory.getLogger(LimitedDiscrepancySearch.class);\n\n\t/* communication */\n\tprotected TreeNode<T> traversalTree;\n\tprotected Collection<TreeNode<T>> expanded = new HashSet<>();\n\tprotected final Queue<EvaluatedSearchGraphPath<T, A, V>> solutions = new LinkedBlockingQueue<>();\n\n\t/* graph construction helpers */\n\tprotected final SingleRootGenerator<T> rootGenerator;\n\tprotected final SuccessorGenerator<T, A> successorGenerator;\n\tprotected final boolean checkGoalPropertyOnEntirePath;\n\tprotected final PathGoalTester<T> pathGoalTester;\n\tprotected final NodeGoalTester<T> nodeGoalTester;\n\n\t/* graph travesal helpers */\n\tprotected final Comparator<T> heuristic;\n\n\t/* algorithm state */\n\tprivate int maxK = 1;\n\tprivate int currentK = 1;\n\tprivate boolean probeHasExpandedNode = false;\n\n\tpublic LimitedDiscrepancySearch(NodeRecommendedTree<T, A> problemInput) {\n\t\tsuper(problemInput);\n\t\tthis.rootGenerator = (SingleRootGenerator<T>) problem.getGraphGenerator().getRootGenerator();\n\t\tthis.successorGenerator = problem.getGraphGenerator().getSuccessorGenerator();\n\t\tcheckGoalPropertyOnEntirePath = !(problem.getGraphGenerator().getGoalTester() instanceof NodeGoalTester);\n\t\tif (checkGoalPropertyOnEntirePath) {\n\t\t\tthis.nodeGoalTester = null;\n\t\t\tthis.pathGoalTester = (PathGoalTester<T>) problem.getGraphGenerator().getGoalTester();\n\t\t\t;\n\t\t} else {\n\t\t\tthis.nodeGoalTester = (NodeGoalTester<T>) problem.getGraphGenerator().getGoalTester();\n\t\t\tthis.pathGoalTester = null;\n\t\t}\n\t\tthis.heuristic = problemInput.getRecommender();\n\t}\n\n\t@Override\n\tpublic AlgorithmEvent nextWithException() {\n\t\tswitch (getState()) {\n\t\tcase created: {\n\t\t\tthis.traversalTree = newNode(null, rootGenerator.getRoot());\n\t\t\tpostEvent(new GraphInitializedEvent<>(traversalTree));\n\t\t\treturn activate();\n\t\t}\n\t\tcase active: {\n\t\t\ttry {\n\t\t\t\tAlgorithmEvent event;\n\t\t\t\tevent = ldsProbe(traversalTree);\n\t\t\t\tif (event instanceof NoMoreNodesOnLevelEvent) {\n\t\t\t\t\tif (!probeHasExpandedNode) {\n\t\t\t\t\t\tlogger.info(\"Probe process has not expanded any node, finishing alogrithm\");\n\t\t\t\t\t\tshutdown();;\n\t\t\t\t\t\treturn new AlgorithmFinishedEvent();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlogger.info(\"Probe process has not more nodes to be considered, restarting with augmented k {}\", maxK + 1);\n\t\t\t\t\t\tmaxK++;\n\t\t\t\t\t\tcurrentK = maxK;\n\t\t\t\t\t\tprobeHasExpandedNode = false;\n\t\t\t\t\t\treturn event;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlogger.info(\"Returning event {}\", event);\n\t\t\t\t\treturn event;\n\t\t\t\t}\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\treturn new AlgorithmInterruptedEvent();\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow new RuntimeException(e);\n\t\t\t}\n\t\t}\n\t\tdefault:\n\t\t\tthrow new IllegalStateException(\"The algorithm cannot do anything in state \" + getState());\n\t\t}\n\t}\n\n\t/**\n\t * Computes a solution path that deviates k times from the heuristic (if possible)\n\t * \n\t * @param node\n\t * @param k\n\t * @return\n\t */\n\tprivate AlgorithmEvent ldsProbe(TreeNode<T> node) throws Exception {\n\t\tlogger.info(\"Probing under node {} with k = {}\", node.getValue(), currentK);\n\n\t\t/* return solution event if this is a solution node */\n\t\tif (nodeGoalTester.isGoal(node.getValue())) {\n\t\t\tList<T> path = node.getValuesOnPathFromRoot();\n\t\t\tEvaluatedSearchGraphPath<T, A, V> solution = new EvaluatedSearchGraphPath<>(path, null, null);\n\t\t\tsolutions.add(solution);\n\t\t\treturn new SolutionCandidateFoundEvent<>(solution);\n\t\t}\n\n\t\t/* if this node has not been expanded, compute successors and the priorities among them and attach them to search graph */\n\t\tif (!expanded.contains(node)) {\n\t\t\texpanded.add(node);\n\t\t\tprobeHasExpandedNode = true;\n\t\t\tCollection<NodeExpansionDescription<T, A>> succ = successorGenerator.generateSuccessors(node.getValue());\n\t\t\tif (succ == null || succ.isEmpty())\n\t\t\t\treturn new NoMoreNodesOnLevelEvent();\n\t\t\tList<NodeExpansionDescription<T, A>> prioSucc = succ.stream().sorted((d1, d2) -> heuristic.compare(d1.getTo(), d2.getTo())).collect(Collectors.toList());\n\t\t\tList<TreeNode<T>> generatedNodes = new ArrayList<>();\n\t\t\tfor (NodeExpansionDescription<T, A> successorDescription : prioSucc) {\n\t\t\t\tif (Thread.currentThread().isInterrupted()) {\n\t\t\t\t\tthis.cancel();\n\t\t\t\t\tthrow new InterruptedException(\"Thread that executes LDS has been interrupted. The LDS has been canceled.\");\n\t\t\t\t}\n\t\t\t\tif (this.isCanceled())\n\t\t\t\t\treturn new AlgorithmCanceledEvent();\n\t\t\t\tTreeNode<T> newNode = newNode(node, successorDescription.getTo());\n\t\t\t\tgeneratedNodes.add(newNode);\n\t\t\t}\n\t\t} else\n\t\t\tlogger.info(\"Not expanding node {} again.\", node.getValue());\n\t\tList<TreeNode<T>> children = node.getChildren();\n\t\tif (children.isEmpty())\n\t\t\treturn new NoMoreNodesOnLevelEvent();\n\n\t\t/* otherwise, deviate from the heuristic if this brings a solution */\n\t\t/* if no more discrepancies are allowed, keep searching under the first child */\n\t\tif (currentK > 0 && children.size() > 1) {\n\t\t\tcurrentK--;\n\t\t\treturn ldsProbe(children.get(1));\n\t\t}\n\t\treturn ldsProbe(children.get(0));\n\t}\n\n\tprotected synchronized TreeNode<T> newNode(TreeNode<T> parent, T newNode) {\n\n\t\t/* attach new node to traversal tree */\n\t\tTreeNode<T> newTree = parent != null ? parent.addChild(newNode) : new TreeNode<>(newNode);\n\n\t\t/* send events for this new node */\n\t\tif (parent != null) {\n\t\t\tboolean isGoal = nodeGoalTester.isGoal(newNode);\n\t\t\tpostEvent(new NodeReachedEvent<TreeNode<T>>(parent, newTree, \"or_\" + (isGoal ? \"solution\" : \"created\")));\n\t\t}\n\t\treturn newTree;\n\t}\n\n\t@Override\n\tpublic void setNumCPUs(int numberOfCPUs) {\n\t\tlogger.warn(\"Currently no support for parallelization\");\n\t}\n\n\n\t@Override\n\tpublic EvaluatedSearchGraphPath<T, A, V> call() throws Exception {\n\t\tnextSolution();\n\t\treturn solutions.peek();\n\t}\n\n\t@Override\n\tpublic int getNumCPUs() {\n\t\treturn 1;\n\t}\n\n\t@Override\n\tpublic GraphGenerator<T, A> getGraphGenerator() {\n\t\treturn getInput().getGraphGenerator();\n\t}\n\n\t@Override\n\tpublic EvaluatedSearchGraphPath<T, A, V> getBestSeenSolution() {\n\t\tthrow new UnsupportedOperationException();\n\t}\n\n\t@Override\n\tpublic EvaluatedSearchGraphPath<T, A, V> getSolutionProvidedToCall() {\n\t\treturn solutions.peek();\n\t}\n}\n" }, { "alpha_fraction": 0.7039105892181396, "alphanum_fraction": 0.7203417420387268, "avg_line_length": 40.29166793823242, "blob_id": "2c2be6533906c4af3da0b0980f19bed435161c59", "content_id": "1de0f6bf5afa1aefaf6d9d817d7dbdd6771c4278", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3043, "license_type": "no_license", "max_line_length": 163, "num_lines": 72, "path": "/softwareconfiguration/mlplan/examples/de/upb/crc901/mlplan/examples/MetaMinerExample.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "//package de.upb.crc901.mlplan.examples;\r\n//\r\n//import java.io.BufferedReader;\r\n//import java.io.File;\r\n//import java.io.FileReader;\r\n//import java.util.List;\r\n//import java.util.Random;\r\n//\r\n//import org.openml.apiconnector.io.OpenmlConnector;\r\n//import org.openml.apiconnector.xml.DataSetDescription;\r\n//\r\n//import de.upb.crc901.automl.hascoml.supervised.multiclass.weka.HASCOForWekaML;\r\n//import hasco.reduction.HASCOReduction;\r\n//import hasco.serialization.ComponentLoader;\r\n//import jaicore.graphvisualizer.SimpleGraphVisualizationWindow;\r\n//import jaicore.ml.WekaUtil;\r\n//import jaicore.planning.algorithms.forwarddecomposition.ForwardDecompositionHTNPlannerFactory;\r\n//import jaicore.planning.graphgenerators.task.tfd.TFDNode;\r\n//import jaicore.search.algorithms.standard.bestfirst.BestFirst;\r\n//import jaicore.search.core.interfaces.GraphGenerator;\r\n//import weka.core.Instances;\r\n//\r\n///**\r\n// * Illustrates the usage of the WEKAMetaMiner.\r\n// *\r\n// * @author Helena Graf\r\n// *\r\n// */\r\n//public class MetaMinerExample {\r\n//\r\n//\tpublic static void main(final String[] args) throws Exception {\r\n//\t\t/* load data for segment dataset and create a train-test-split */\r\n//\t\tOpenmlConnector connector = new OpenmlConnector();\r\n//\t\tDataSetDescription ds = connector.dataGet(40983);\r\n//\t\tFile file = ds.getDataset(\"4350e421cdc16404033ef1812ea38c01\");\r\n//\t\tInstances data = new Instances(new BufferedReader(new FileReader(file)));\r\n//\t\tdata.setClassIndex(data.numAttributes() - 1);\r\n//\t\tList<Instances> instances = WekaUtil.getStratifiedSplit(data, new Random(0), .7f);\r\n//\r\n//\t\t/* initialize mlplan, and let it run for 30 seconds */\r\n//\t\tFile configFile = new File(\"model/weka/weka-all-autoweka.json\");\r\n//\t\tHASCOForWekaML hasco = new HASCOForWekaML();\r\n//\t\tComponentLoader componentLoader = hasco.getComponentLoader();\r\n//\r\n//\t\t/* get the graph generator from the reduction */\r\n//\t\tHASCOReduction reduction = new HASCOReduction(configFile, \"AbstractClassifier\", true);\r\n//\t\tGraphGenerator<TFDNode, String> graphGenerator = reduction.getGraphGeneratorUsedByHASCOForSpecificPlanner(new ForwardDecompositionHTNPlannerFactory<Double>());\r\n//\t\tBestFirst<TFDNode, String> bf = new BestFirst<>(graphGenerator, n -> n.externalPath().size() * -1.0);\r\n//\t\tnew SimpleGraphVisualizationWindow<>(bf);\r\n//\t\twhile (true) {\r\n//\t\t\tbf.nextSolution();\r\n//\t\t}\r\n//\r\n//\t\t// System.out.println(hasco.getGraphGenerator());\r\n//\r\n//\t\t// WEKAMetaminer metaMiner = new WEKAMetaminer(data);\r\n//\t\t// metaMiner.build();\r\n//\t\t// MetaMinerBasedSorter comparator = new MetaMinerBasedSorter(metaMiner,\r\n//\t\t// componentLoader);\r\n//\t\t// mlplan.get.setOrGraphSearchFactory(new\r\n//\t\t// ImprovedLimitedDiscrepancySearchFactory(comparator));\r\n//\r\n//\t\t// mlplan.buildClassifier(split.get(0));\r\n//\r\n//\t\t/* evaluate solution produced by mlplan */\r\n//\t\t// Evaluation eval = new Evaluation(split.get(0));\r\n//\t\t// eval.evaluateModel(mlplan, split.get(1));\r\n//\t\t// System.out.println(\"Error Rate of the solution produced by ML-Plan: \" + (100\r\n//\t\t// - eval.pctCorrect()) / 100f);\r\n//\t}\r\n//\r\n//}" }, { "alpha_fraction": 0.7476458549499512, "alphanum_fraction": 0.7501307725906372, "avg_line_length": 53.41992950439453, "blob_id": "532a403cca85f78be5cd68c04bda23862fba82b2", "content_id": "1d85daf2a23034f8d3522e703a6cdee9ef6f2bb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 15292, "license_type": "no_license", "max_line_length": 347, "num_lines": 281, "path": "/softwareconfiguration/hasco/src/hasco/core/isValidParameterRangeRefinementPredicate.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package hasco.core;\n\nimport jaicore.basic.sets.SetUtil;\nimport jaicore.logic.fol.structure.ConstantParam;\nimport jaicore.logic.fol.structure.Literal;\nimport jaicore.logic.fol.structure.Monom;\nimport jaicore.logic.fol.theories.EvaluablePredicate;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.Stack;\nimport java.util.stream.Collectors;\n\nimport org.apache.commons.lang3.NotImplementedException;\nimport org.apache.commons.math3.geometry.euclidean.oned.Interval;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport hasco.model.CategoricalParameterDomain;\nimport hasco.model.Component;\nimport hasco.model.ComponentInstance;\nimport hasco.model.NumericParameterDomain;\nimport hasco.model.Parameter;\nimport hasco.model.ParameterDomain;\nimport hasco.model.ParameterRefinementConfiguration;\n\npublic class isValidParameterRangeRefinementPredicate implements EvaluablePredicate {\n\n\tprivate final Logger logger = LoggerFactory.getLogger(isValidParameterRangeRefinementPredicate.class);\n\n\tprivate final Collection<Component> components;\n\tprivate final Map<Component, Map<Parameter, ParameterRefinementConfiguration>> refinementConfiguration;\n\tprivate final Map<ComponentInstance, Double> knownCompositionsAndTheirScore = new HashMap<>();\n\n\tpublic isValidParameterRangeRefinementPredicate(final Collection<Component> components, final Map<Component, Map<Parameter, ParameterRefinementConfiguration>> refinementConfiguration) {\n\t\tsuper();\n\t\tthis.components = components;\n\t\tthis.refinementConfiguration = refinementConfiguration;\n\t}\n\n\t@Override\n\tpublic Collection<List<ConstantParam>> getParamsForPositiveEvaluation(final Monom state, final ConstantParam... partialGrounding) {\n\t\t/* determine the context for which the interval refinement should be oracled */\n\t\tif (partialGrounding.length != 6) {\n\t\t\tthrow new IllegalArgumentException(\"The interpreted predicate \" + this.getClass().getName() + \" requires 6 arguments when oracled but \" + partialGrounding.length + \" have been provided!\");\n\t\t}\n\t\tString componentName = partialGrounding[0].getName();\n\t\tString componentIdentifier = partialGrounding[1].getName();\n\t\tString parameterName = partialGrounding[2].getName();\n\t\tComponent component = this.components.stream().filter(c -> c.getName().equals(componentName)).findAny().get();\n\t\tParameter param = component.getParameters().stream().filter(p -> p.getName().equals(parameterName)).findAny().get();\n\t\tList<ConstantParam> partialGroundingAsList = Arrays.asList(partialGrounding);\n\t\tString containerName = partialGrounding[3].getName();\n\t\tString currentParamValue = partialGrounding[4].getName(); // this is not really used, because the current value is again read from the state\n\t\tlogger.info(\"Determining positive evaluations for isValidParameterRangeRefinementPredicate({},{},{},{},{},{})\", componentName, componentIdentifier, parameterName, containerName,\n\t\t\t\tcurrentParamValue, partialGrounding[5]);\n\t\tboolean hasBeenSetBefore = state.contains(new Literal(\"overwritten('\" + containerName + \"')\"));\n\n\t\t/* determine component instance and the true domain of parameter */\n\t\tComponentInstance instance = Util.getComponentInstanceFromState(components, state, componentIdentifier, false);\n\t\tlogger.debug(\"Derived component instance to be refined: {}. Parameter to refine: {}. Current value of parameter: {}\", instance, param, currentParamValue);\n\t\ttry {\n\t\t\tMap<Parameter, ParameterDomain> paramDomains = Util.getUpdatedDomainsOfComponentParameters(instance);\n\t\t\tif (logger.isDebugEnabled()) {\n\t\t\t\tlogger.debug(\"Parameter domains are: {}\", paramDomains.keySet().stream().map(k -> \"\\n\\t\" + k + \": \" + paramDomains.get(k)).collect(Collectors.joining()));\n\t\t\t}\n\t\t\t\n\t\t\t/* determine refinements for numeric parameters */\n\t\t\tif (param.isNumeric()) {\n\t\t\t\tNumericParameterDomain currentlyActiveDomain = (NumericParameterDomain) paramDomains.get(param);\n\t\t\t\tInterval currentInterval = new Interval(currentlyActiveDomain.getMin(), currentlyActiveDomain.getMax());\n\t\t\t\tassert (!hasBeenSetBefore || (currentInterval.getInf() == Double.valueOf(SetUtil.unserializeList(currentParamValue).get(0)) && currentInterval.getSup() == Double.valueOf(SetUtil.unserializeList(currentParamValue).get(1)))) : \"The derived currently active domain of an explicitly set parameter deviates from the domain specified in the state!\";\n\t\t\t\tParameterRefinementConfiguration refinementConfig = this.refinementConfiguration.get(component).get(param);\n\t\t\t\tif (refinementConfig == null) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"No refinement configuration for parameter \\\"\" + parameterName + \"\\\" of component \\\"\" + componentName + \"\\\" has been supplied!\");\n\t\t\t\t}\n\n\t\t\t\t/* if the interval is under the distinction threshold, return an empty list of possible refinements (predicate will always be false here) */\n\t\t\t\tif (currentInterval.getSup() - currentInterval.getInf() < refinementConfig.getIntervalLength()) {\n\t\t\t\t\tlogger.info(\"Returning an empty list as this is a numeric parameter that has been narrowed sufficiently. Required interval length is {}, and actual interval length is {}\",\n\t\t\t\t\t\t\trefinementConfig.getIntervalLength(), currentInterval.getSup() - currentInterval.getInf());\n\t\t\t\t\tif (!hasBeenSetBefore) {\n\t\t\t\t\t\tList<Interval> unmodifiedRefinement = new ArrayList<>();\n\t\t\t\t\t\tunmodifiedRefinement.add(currentInterval);\n\t\t\t\t\t\treturn this.getGroundingsForIntervals(unmodifiedRefinement, partialGroundingAsList);\n\t\t\t\t\t}\n\t\t\t\t\treturn new ArrayList<>();\n\t\t\t\t}\n\n\t\t\t\t/* if this is an integer and the number of comprised integers are at most as many as the branching factor, enumerate them */\n\t\t\t\tif (currentlyActiveDomain.isInteger() && (Math.floor(currentInterval.getSup()) - Math.ceil(currentInterval.getInf()) + 1 <= refinementConfig.getRefinementsPerStep())) {\n\t\t\t\t\tList<Interval> proposedRefinements = new ArrayList<>();\n\t\t\t\t\tfor (int i = (int) Math.ceil(currentInterval.getInf()); i <= (int) Math.floor(currentInterval.getSup()); i++) {\n\t\t\t\t\t\tproposedRefinements.add(new Interval(i, i));\n\t\t\t\t\t}\n\t\t\t\t\tlogger.info(\"Ultimate level of integer refinement reached. Returning refinements: {}.\", proposedRefinements);\n\t\t\t\t\treturn this.getGroundingsForIntervals(proposedRefinements, partialGroundingAsList);\n\t\t\t\t}\n\t\t\t\tif (hasBeenSetBefore || !refinementConfig.isInitRefinementOnLogScale()) {\n\t\t\t\t\tList<Interval> proposedRefinements = this.refineOnLinearScale(currentInterval, refinementConfig.getRefinementsPerStep(), refinementConfig.getIntervalLength());\n\t\t\t\t\tfor (Interval proposedRefinement : proposedRefinements) {\n\t\t\t\t\t\tassert proposedRefinement.getInf() >= currentInterval.getInf() && proposedRefinement.getSup() <= currentInterval.getSup() : \"The proposed refinement [\"\n\t\t\t\t\t\t\t\t+ proposedRefinement.getInf() + \", \" + proposedRefinement.getSup() + \"] is not a sub-interval of \" + currentParamValue + \"].\";\n\t\t\t\t\t\tassert !proposedRefinement.equals(currentInterval) : \"No real refinement! Intervals are identical.\";\n\t\t\t\t\t}\n\t\t\t\t\tlogger.info(\"Returning linear refinements: {}.\", proposedRefinements);\n\t\t\t\t\treturn this.getGroundingsForIntervals(proposedRefinements, partialGroundingAsList);\n\t\t\t\t}\n\t\t\t\tOptional<Literal> focusPredicate = state.stream().filter(\n\t\t\t\t\t\tl -> l.getPropertyName().equals(\"parameterFocus\") && l.getParameters().get(0).getName().equals(componentIdentifier) && l.getParameters().get(1).getName().equals(parameterName))\n\t\t\t\t\t\t.findAny();\n\t\t\t\tif (!focusPredicate.isPresent()) {\n\t\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\t\"The given state does not specify a parameter focus for the log-scale parameter \" + parameterName + \" on object \\\"\" + componentIdentifier + \"\\\"\");\n\t\t\t\t}\n\t\t\t\tdouble focus = Double.parseDouble(focusPredicate.get().getParameters().get(2).getName());\n\t\t\t\tList<Interval> proposedRefinements = this.refineOnLogScale(currentInterval, refinementConfig.getRefinementsPerStep(), 2, focus);\n\t\t\t\tfor (Interval proposedRefinement : proposedRefinements) {\n\t\t\t\t\tdouble epsilon = 1E-7;\n\t\t\t\t\tassert proposedRefinement.getInf() + epsilon >= currentInterval.getInf() && proposedRefinement.getSup() <= currentInterval.getSup() + epsilon : \"The proposed refinement [\"\n\t\t\t\t\t\t\t+ proposedRefinement.getInf() + \", \" + proposedRefinement.getSup() + \"] is not a sub-interval of \" + currentParamValue + \"].\";\n\t\t\t\t\tassert !proposedRefinement.equals(currentInterval) : \"No real refinement! Intervals are identical.\";\n\t\t\t\t}\n\t\t\t\tlogger.info(\"Returning default refinements: {}.\", proposedRefinements);\n\t\t\t\treturn this.getGroundingsForIntervals(proposedRefinements, partialGroundingAsList);\n\t\t\t} else if (param.isCategorical()) {\n\t\t\t\tList<String> possibleValues = new ArrayList<>();\n\t\t\t\tif (hasBeenSetBefore) {\n\t\t\t\t\tlogger.info(\"Returning empty list since param has been set before.\");\n\t\t\t\t\treturn new ArrayList<>();\n\t\t\t\t}\n\t\t\t\tfor (Object valAsObject : ((CategoricalParameterDomain) paramDomains.get(param)).getValues()) {\n\t\t\t\t\tpossibleValues.add(valAsObject.toString());\n\t\t\t\t}\n\t\t\t\tlogger.info(\"Returning possible values {}.\", possibleValues);\n\t\t\t\treturn this.getGroundingsForOracledValues(possibleValues, partialGroundingAsList);\n\t\t\t} else {\n\t\t\t\tthrow new UnsupportedOperationException(\"Currently no support for parameters of class \\\"\" + param.getClass().getName() + \"\\\"\");\n\t\t\t}\n\t\t} catch (Throwable e) {\n\t\t\te.printStackTrace();\n\t\t\tSystem.exit(1);\n\t\t\treturn null;\n\t\t}\n\t\t// throw new NotImplementedException(\"Apparentely, there is an unimplemented\n\t\t// case!\");\n\t}\n\n\tprivate Collection<List<ConstantParam>> getGroundingsForIntervals(final List<Interval> refinements, final List<ConstantParam> partialGrounding) {\n\t\tList<String> paramValues = new ArrayList<>();\n\t\tfor (Interval oracledInterval : refinements) {\n\t\t\tparamValues.add(\"[\" + oracledInterval.getInf() + \", \" + oracledInterval.getSup() + \"]\");\n\t\t}\n\t\treturn this.getGroundingsForOracledValues(paramValues, partialGrounding);\n\t}\n\n\tprivate Collection<List<ConstantParam>> getGroundingsForOracledValues(final List<String> refinements, final List<ConstantParam> partialGrounding) {\n\t\tCollection<List<ConstantParam>> groundings = new ArrayList<>();\n\t\tfor (String oracledValue : refinements) {\n\t\t\tList<ConstantParam> grounding = new ArrayList<>(partialGrounding);\n\t\t\tgrounding.set(5, new ConstantParam(oracledValue));\n\t\t\tgroundings.add(grounding);\n\t\t}\n\t\treturn groundings;\n\t}\n\n\tpublic void informAboutNewSolution(final ComponentInstance solution, final double score) {\n\t\tthis.knownCompositionsAndTheirScore.put(solution, score);\n\t}\n\n\t@Override\n\tpublic boolean isOracable() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic Collection<List<ConstantParam>> getParamsForNegativeEvaluation(final Monom state, final ConstantParam... partialGrounding) {\n\t\tthrow new UnsupportedOperationException();\n\t}\n\n\t@Override\n\tpublic boolean test(final Monom state, final ConstantParam... params) {\n\t\tthrow new NotImplementedException(\"Testing the validity-predicate is currently not supported. This is indirectly possible using the oracle.\");\n\t}\n\n\tpublic List<Interval> refineOnLinearScale(final Interval interval, final int maxNumberOfSubIntervals, final double minimumLengthOfIntervals) {\n\t\tdouble min = interval.getInf();\n\t\tdouble max = interval.getSup();\n\t\tdouble length = max - min;\n\t\tList<Interval> intervals = new ArrayList<>();\n\t\t/* if no refinement is possible, return just the interval itself */\n\t\tif (length <= minimumLengthOfIntervals) {\n\t\t\tintervals.add(interval);\n\t\t\treturn intervals;\n\t\t}\n\t\t/* otherwise compute the sub-intervals */\n\t\tint numberOfIntervals = Math.min((int) Math.ceil(length / minimumLengthOfIntervals), maxNumberOfSubIntervals);\n\t\tdouble stepSize = length / numberOfIntervals;\n\t\tfor (int i = 0; i < numberOfIntervals; i++) {\n\t\t\tintervals.add(new Interval(min + i * stepSize, min + ((i + 1) * stepSize)));\n\t\t}\n\t\treturn intervals;\n\t}\n\n\tpublic List<Interval> refineOnLogScale(final Interval interval, final int n, final double basis, final double pointOfConcentration) {\n\t\tList<Interval> list = new ArrayList<>();\n\t\tdouble min = interval.getInf();\n\t\tdouble max = interval.getSup();\n\t\tdouble length = max - min;\n\t\t/*\n\t\t * if the point of concentration is exactly on the left or the right of the\n\t\t * interval, conduct the standard technique\n\t\t */\n\t\tif (pointOfConcentration <= min || pointOfConcentration >= max) {\n\t\t\tdouble lengthOfShortestInterval = length * (1 - basis) / (1 - Math.pow(basis, n));\n\t\t\tif (pointOfConcentration <= min) {\n\t\t\t\tdouble endOfLast = min;\n\t\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\t\tdouble start = endOfLast;\n\t\t\t\t\tendOfLast = start + Math.pow(basis, i) * lengthOfShortestInterval;\n\t\t\t\t\tlist.add(new Interval(start, endOfLast));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdouble endOfLast = max;\n\t\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\t\tdouble start = endOfLast;\n\t\t\t\t\tendOfLast = start - Math.pow(basis, i) * lengthOfShortestInterval;\n\t\t\t\t\tlist.add(new Interval(endOfLast, start));\n\t\t\t\t}\n\t\t\t\tCollections.reverse(list);\n\t\t\t}\n\t\t\treturn list;\n\t\t}\n\t\t/*\n\t\t * if the point of concentration is in the inner of the interval, split the\n\t\t * interval correspondingly and recursively solve the problem\n\t\t */\n\t\tdouble distanceFromMinToFocus = Math.abs(interval.getInf() - pointOfConcentration);\n\t\tint segmentsForLeft = (int) Math.max(1, Math.floor(n * distanceFromMinToFocus / length));\n\t\tint segmentsForRight = n - segmentsForLeft;\n\t\tlist.addAll(this.refineOnLogScale(new Interval(min, pointOfConcentration), segmentsForLeft, basis, pointOfConcentration));\n\t\tlist.addAll(this.refineOnLogScale(new Interval(pointOfConcentration, max), segmentsForRight, basis, pointOfConcentration));\n\t\treturn list;\n\t}\n\n\tpublic void refineRecursively(final Interval interval, final int maxNumberOfSubIntervalsPerRefinement, final double basis, final double pointOfConcentration,\n\t\t\tfinal double factorForMaximumLengthOfFinestIntervals) {\n\t\t/* first, do a logarithmic refinement */\n\t\tList<Interval> initRefinement = this.refineOnLogScale(interval, maxNumberOfSubIntervalsPerRefinement, basis, pointOfConcentration);\n\t\tCollections.reverse(initRefinement);\n\t\tStack<Interval> openRefinements = new Stack<>();\n\t\topenRefinements.addAll(initRefinement);\n\t\tint depth = 0;\n\t\tdo {\n\t\t\tInterval intervalToRefine = openRefinements.pop();\n\t\t\tfor (int i = 0; i < depth; i++) {\n\t\t\t\tSystem.out.print(\"\\t\");\n\t\t\t}\n\t\t\tSystem.out.println(\"[\" + intervalToRefine.getInf() + \", \" + intervalToRefine.getSup() + \"]\");\n\t\t\t/* compute desired granularity for this specific interval */\n\t\t\tdouble distanceToPointOfContentration = Math.min(Math.abs(intervalToRefine.getInf() - pointOfConcentration), Math.abs(intervalToRefine.getSup() - pointOfConcentration));\n\t\t\tdouble maximumLengthOfFinestIntervals = Math.pow(distanceToPointOfContentration + 1, 2) * factorForMaximumLengthOfFinestIntervals;\n\t\t\tSystem.out.println(Math.pow(distanceToPointOfContentration + 1, 2) + \" * \" + factorForMaximumLengthOfFinestIntervals + \" = \" + maximumLengthOfFinestIntervals);\n\t\t\tList<Interval> refinements = this.refineOnLinearScale(intervalToRefine, maxNumberOfSubIntervalsPerRefinement, maximumLengthOfFinestIntervals);\n\t\t\tdepth++;\n\t\t\tif (refinements.size() == 1 && refinements.get(0).equals(intervalToRefine)) {\n\t\t\t\tdepth--;\n\t\t\t} else {\n\t\t\t\tCollections.reverse(refinements);\n\t\t\t\topenRefinements.addAll(refinements);\n\t\t\t}\n\t\t} while (!openRefinements.isEmpty());\n\t}\n\n}\n" }, { "alpha_fraction": 0.7754490971565247, "alphanum_fraction": 0.7754490971565247, "avg_line_length": 32.400001525878906, "blob_id": "d9fa93bb81388938f4c8bfb2f6675f2fe4e7c2cc", "content_id": "dcf180431da983a6de35bb4976bef12de521acec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 334, "license_type": "no_license", "max_line_length": 97, "num_lines": 10, "path": "/JAICore/jaicore-search/src/jaicore/search/core/interfaces/IGraphSearchFactory.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.core.interfaces;\n\nimport jaicore.graph.IGraphAlgorithmFactory;\n\npublic interface IGraphSearchFactory<I, O, NSrc, ASrc, V extends Comparable<V>, NSearch, ASearch>\n\t\textends IGraphAlgorithmFactory<I, O, NSearch, ASearch> {\n\n\t@Override\n\tpublic IGraphSearch<I, O, NSrc, ASrc, V, NSearch, ASearch> getAlgorithm();\n}\n" }, { "alpha_fraction": 0.7058823704719543, "alphanum_fraction": 0.7058823704719543, "avg_line_length": 18.399999618530273, "blob_id": "2ce34a1bd2196821cf5d066d958eb71dd7495f32", "content_id": "ac93149fdfee938bc858c0844ba28ea3f250974b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 102, "license_type": "no_license", "max_line_length": 39, "num_lines": 5, "path": "/JAICore/jaicore-basic/src/jaicore/basic/IBinaryAggregator.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.basic;\r\n\r\npublic interface IBinaryAggregator<V> {\r\n\tpublic V aggregate(V a, V b);\r\n}\r\n" }, { "alpha_fraction": 0.6675862073898315, "alphanum_fraction": 0.6675862073898315, "avg_line_length": 21.65625, "blob_id": "b573036dc85768733fe0cee0e87836f86b720e3f", "content_id": "002811afbfaa92cee3b8eb8c3693390fe60696e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 725, "license_type": "no_license", "max_line_length": 68, "num_lines": 32, "path": "/JAICore/jaicore-basic/src/jaicore/basic/EntitySelector.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.basic;\n\nimport java.util.Collection;\nimport java.util.HashSet;\nimport java.util.Set;\n\npublic abstract class EntitySelector<T> {\n\tprotected final Set<T> init;\n\tprotected final Set<T> current;\n\t\n\tpublic EntitySelector(Collection<T> items) {\n\t\tinit = new HashSet<>(items);\n\t\tcurrent = new HashSet<>(items);\n\t}\n\t\n\tpublic Set<T> get() {\n\t\treturn new HashSet<>(current);\n\t}\n\t\n\tpublic Set<T> getInverted() {\n\t\tSet<T> inverted = new HashSet<>();\n\t\tinit.forEach(i -> { if (!current.contains(i)) inverted.add(i); });\n\t\treturn inverted;\n\t}\n\n\tpublic EntitySelector<T> invert() {\n\t\tSet<T> tmp = new HashSet<>(current);\n\t\tcurrent.clear();\n\t\tinit.forEach(i -> { if (!tmp.contains(i)) current.add(i); });\n\t\treturn this;\n\t}\n}\n" }, { "alpha_fraction": 0.6812855005264282, "alphanum_fraction": 0.6827059388160706, "avg_line_length": 29.11602210998535, "blob_id": "019f193d6bde644f1952fa6e13fd6ad819910abf", "content_id": "865602de353d5a507f54263b0508cb511738cdbb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5632, "license_type": "no_license", "max_line_length": 210, "num_lines": 181, "path": "/softwareconfiguration/hasco/src/hasco/model/Component.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package hasco.model;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.Collection;\r\nimport java.util.HashSet;\r\nimport java.util.LinkedHashMap;\r\nimport java.util.List;\r\nimport java.util.Optional;\r\nimport java.util.TreeMap;\r\n\r\nimport jaicore.basic.sets.PartialOrderedSet;\r\n\r\npublic class Component {\r\n\tprivate final String name;\r\n\tprivate final Collection<String> providedInterfaces = new ArrayList<>();\r\n\tprivate final LinkedHashMap<String, String> requiredInterfaces = new LinkedHashMap<>();\r\n\tprivate final PartialOrderedSet<Parameter> parameters = new PartialOrderedSet<>();\r\n\tprivate final Collection<Dependency> dependencies = new ArrayList<>();\r\n\r\n\tpublic Component(final String name) {\r\n\t\tsuper();\r\n\t\tthis.name = name;\r\n\t\tthis.getProvidedInterfaces().add(this.name);\r\n\t}\r\n\r\n\tpublic Component(final String name, final TreeMap<String, String> requiredInterfaces, final Collection<String> providedInterfaces, final List<Parameter> parameters, final Collection<Dependency> dependencies) {\r\n\t\tthis(name);\r\n\t\tthis.requiredInterfaces.putAll(requiredInterfaces);\r\n\t\tthis.providedInterfaces.addAll(providedInterfaces);\r\n\t\tif (!this.providedInterfaces.contains(name)) {\r\n\t\t\tthis.providedInterfaces.add(name);\r\n\t\t}\r\n\r\n\t\tparameters.forEach(param -> this.addParameter(param));\r\n\t\tthis.dependencies.addAll(dependencies);\r\n\t}\r\n\r\n\tpublic String getName() {\r\n\t\treturn this.name;\r\n\t}\r\n\r\n\tpublic LinkedHashMap<String, String> getRequiredInterfaces() {\r\n\t\treturn this.requiredInterfaces;\r\n\t}\r\n\r\n\tpublic Collection<String> getProvidedInterfaces() {\r\n\t\treturn this.providedInterfaces;\r\n\t}\r\n\r\n\tpublic PartialOrderedSet<Parameter> getParameters() {\r\n\t\treturn this.parameters;\r\n\t}\r\n\r\n\tpublic Parameter getParameterWithName(final String paramName) {\r\n\t\tOptional<Parameter> param = this.parameters.stream().filter(p -> p.getName().equals(paramName)).findFirst();\r\n\t\tif (!param.isPresent()) {\r\n\t\t\tthrow new IllegalArgumentException(\"Component \" + this.name + \" has no parameter with name \\\"\" + paramName + \"\\\"\");\r\n\t\t}\r\n\t\treturn param.get();\r\n\t}\r\n\r\n\tpublic void addProvidedInterface(final String interfaceName) {\r\n\t\tthis.providedInterfaces.add(interfaceName);\r\n\t}\r\n\r\n\tpublic void addRequiredInterface(final String interfaceID, final String interfaceName) {\r\n\t\tthis.requiredInterfaces.put(interfaceID, interfaceName);\r\n\t}\r\n\r\n\tpublic void addParameter(final Parameter param) {\r\n\t\tassert !this.parameters.stream().filter(p -> p.getName().equals(param.getName())).findAny().isPresent() : \"Component \" + this.name + \" already has parameter with name \" + param.getName();\r\n\t\tthis.parameters.add(param);\r\n\t}\r\n\r\n\tpublic void addDependency(final Dependency dependency) {\r\n\r\n\t\t/* check whether this dependency is coherent with the current partial order on the parameters */\r\n\t\tCollection<Parameter> paramsInPremise = new HashSet<>();\r\n\t\tdependency.getPremise().forEach(c -> c.forEach(i -> paramsInPremise.add(i.getX())));\r\n\t\tCollection<Parameter> paramsInConclusion = new HashSet<>();\r\n\t\tdependency.getConclusion().forEach(i -> paramsInConclusion.add(i.getX()));\r\n\t\tfor (Parameter before : paramsInPremise) {\r\n\t\t\tfor (Parameter after : paramsInConclusion) {\r\n\t\t\t\tthis.parameters.requireABeforeB(before, after);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/* add the dependency to the set of dependencies */\r\n\t\tthis.dependencies.add(dependency);\r\n\t}\r\n\r\n\tpublic Collection<Dependency> getDependencies() {\r\n\t\treturn this.dependencies;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\tStringBuilder sb = new StringBuilder();\r\n\r\n\t\tsb.append(this.providedInterfaces);\r\n\t\tsb.append(\":\");\r\n\t\tsb.append(this.name);\r\n\t\tsb.append(\"(\");\r\n\t\tboolean first = true;\r\n\t\tfor (Parameter p : this.parameters) {\r\n\t\t\tif (first) {\r\n\t\t\t\tfirst = false;\r\n\t\t\t} else {\r\n\t\t\t\tsb.append(\",\");\r\n\t\t\t}\r\n\t\t\tsb.append(p);\r\n\t\t}\r\n\t\tsb.append(\")\");\r\n\t\tsb.append(\":\");\r\n\t\tsb.append(this.requiredInterfaces);\r\n\r\n\t\treturn sb.toString();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + ((this.dependencies == null) ? 0 : this.dependencies.hashCode());\r\n\t\tresult = prime * result + ((this.name == null) ? 0 : this.name.hashCode());\r\n\t\tresult = prime * result + ((this.parameters == null) ? 0 : this.parameters.hashCode());\r\n\t\tresult = prime * result + ((this.providedInterfaces == null) ? 0 : this.providedInterfaces.hashCode());\r\n\t\tresult = prime * result + ((this.requiredInterfaces == null) ? 0 : this.requiredInterfaces.hashCode());\r\n\t\treturn result;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean equals(final Object obj) {\r\n\t\tif (this == obj) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tif (obj == null) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tif (this.getClass() != obj.getClass()) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tComponent other = (Component) obj;\r\n\t\tif (this.dependencies == null) {\r\n\t\t\tif (other.dependencies != null) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t} else if (!this.dependencies.equals(other.dependencies)) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tif (this.name == null) {\r\n\t\t\tif (other.name != null) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t} else if (!this.name.equals(other.name)) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tif (this.parameters == null) {\r\n\t\t\tif (other.parameters != null) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t} else if (!this.parameters.equals(other.parameters)) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tif (this.providedInterfaces == null) {\r\n\t\t\tif (other.providedInterfaces != null) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t} else if (!this.providedInterfaces.equals(other.providedInterfaces)) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tif (this.requiredInterfaces == null) {\r\n\t\t\tif (other.requiredInterfaces != null) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t} else if (!this.requiredInterfaces.equals(other.requiredInterfaces)) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7444794774055481, "alphanum_fraction": 0.7444794774055481, "avg_line_length": 20.64285659790039, "blob_id": "934134b9e1f605ced96641d4bae606862be7cd9c", "content_id": "c90df1eca5055e04ff2cd4e6ccec27ad682c172a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 317, "license_type": "no_license", "max_line_length": 60, "num_lines": 14, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/bestfirst/events/NodeExpansionCompletedEvent.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.bestfirst.events;\r\n\r\npublic class NodeExpansionCompletedEvent<N> {\r\n\tprivate final N expandedNode;\r\n\r\n\tpublic NodeExpansionCompletedEvent(N expandedNode) {\r\n\t\tsuper();\r\n\t\tthis.expandedNode = expandedNode;\r\n\t}\r\n\r\n\tpublic N getExpandedNode() {\r\n\t\treturn expandedNode;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7494138479232788, "alphanum_fraction": 0.7532238960266113, "avg_line_length": 40.12345504760742, "blob_id": "7b67c506e751011da18f50877c8d8d213760bf4e", "content_id": "e4d7704d06ce7dc0f2edd459ea6ac465105ce21a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3412, "license_type": "no_license", "max_line_length": 163, "num_lines": 81, "path": "/softwareconfiguration/mlplan/src/de/upb/crc901/reduction/single/ExperimentRunner.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package de.upb.crc901.reduction.single;\r\n\r\nimport java.io.BufferedReader;\r\nimport java.io.FileReader;\r\nimport java.util.ArrayList;\r\nimport java.util.Collection;\r\nimport java.util.HashMap;\r\nimport java.util.List;\r\nimport java.util.Map;\r\nimport java.util.Random;\r\n\r\nimport jaicore.ml.WekaUtil;\r\nimport jaicore.ml.classification.multiclass.reduction.MCTreeNodeReD;\r\nimport jaicore.ml.classification.multiclass.reduction.splitters.ISplitter;\r\nimport jaicore.ml.classification.multiclass.reduction.splitters.ISplitterFactory;\r\nimport jaicore.ml.evaluation.MonteCarloCrossValidationEvaluator;\r\nimport jaicore.ml.evaluation.MulticlassEvaluator;\r\nimport weka.classifiers.AbstractClassifier;\r\nimport weka.classifiers.Classifier;\r\nimport weka.core.Instances;\r\n\r\npublic class ExperimentRunner<T extends ISplitter> {\r\n\t\r\n\tprivate final int k;\r\n\tprivate final int mccvRepeats;\r\n\tprivate final ISplitterFactory<T> splitterFactory;\r\n\t\r\n\tpublic ExperimentRunner(int k, int mccvRepeats, ISplitterFactory<T> splitterFactory) {\r\n\t\tsuper();\r\n\t\tthis.k = k;\r\n\t\tthis.mccvRepeats = mccvRepeats;\r\n\t\tthis.splitterFactory = splitterFactory;\r\n\t}\r\n\r\n\r\n\tpublic Map<String, Object> conductSingleOneStepReductionExperiment(ReductionExperiment experiment) throws Exception {\r\n\r\n\t\t/* load data */\r\n\t\tInstances data = new Instances(new BufferedReader(new FileReader(experiment.getDataset())));\r\n\t\tdata.setClassIndex(data.numAttributes() - 1);\r\n\r\n\t\t/* prepare basis for experiments */\r\n\t\tint seed = experiment.getSeed();\r\n\t\tClassifier leftClassifier = AbstractClassifier.forName(experiment.getNameOfLeftClassifier(), null);\r\n\t\tClassifier innerClassifier = AbstractClassifier.forName(experiment.getNameOfInnerClassifier(), null);\r\n\t\tClassifier rightClassifier = AbstractClassifier.forName(experiment.getNameOfRightClassifier(), null);\r\n\t\tList<Instances> outerSplit = WekaUtil.getStratifiedSplit(data, new Random(experiment.getSeed()), .7f);\r\n\t\tMonteCarloCrossValidationEvaluator mccv = new MonteCarloCrossValidationEvaluator(new MulticlassEvaluator(new Random(seed)), mccvRepeats, outerSplit.get(0), .7f);\r\n\t\tISplitter splitter = splitterFactory.getSplitter(seed);\r\n\t\t\r\n\t\t/* compute best of k splits */\r\n\t\tMCTreeNodeReD bestFoundClassifier = null;\r\n\t\tdouble bestFoundScore = Double.MAX_VALUE;\r\n\t\tfor (int i = 0; i < k; i++) {\r\n\t\t\tList<Collection<String>> classSplit;\r\n\t\t\ttry {\r\n\t\t\t\tclassSplit = new ArrayList<>(splitter.split(outerSplit.get(0)));\r\n\t\t\t} catch (Throwable e) {\r\n\t\t\t\tthrow new RuntimeException(\"Could not create a split.\", e);\r\n\t\t\t}\r\n\t\t\tMCTreeNodeReD classifier = new MCTreeNodeReD(innerClassifier, classSplit.get(0), leftClassifier, classSplit.get(1), rightClassifier);\r\n\t\t\tdouble loss = mccv.evaluate(classifier);\r\n\t\t\tSystem.out.println(\"\\t\\t\\tComputed loss \" + loss);\r\n\t\t\tif (loss < bestFoundScore) {\r\n\t\t\t\tbestFoundScore = loss;\r\n\t\t\t\tbestFoundClassifier = classifier;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\t/* train classifier on all data */\r\n\t\tbestFoundClassifier.buildClassifier(outerSplit.get(0));\r\n\t\tMulticlassEvaluator evaluator = new MulticlassEvaluator(new Random(seed));\r\n\t\tdouble loss = evaluator.loss(bestFoundClassifier, outerSplit.get(1));\r\n\r\n\t\tMap<String, Object> result = new HashMap<>();\r\n\t\tSystem.out.println(\"\\t\\t\\tBest previously observed loss was \" + bestFoundScore + \". The retrained classifier achieves \" + loss + \" on the full data.\");\r\n\t\tresult.put(\"errorRate\", loss);\r\n//\t\tresult.put(\"trainTime\", time);\r\n\t\treturn result;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6935698986053467, "alphanum_fraction": 0.697438657283783, "avg_line_length": 34.565853118896484, "blob_id": "3400fb0942eb960f724df5e8d4f01543f393b664", "content_id": "4e4c614c01158bd96ad80da280988521be7f8a6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 7496, "license_type": "no_license", "max_line_length": 162, "num_lines": 205, "path": "/JAICore/jaicore-logic/src/jaicore/logic/fol/util/LogicUtil.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.logic.fol.util;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.Collection;\r\nimport java.util.HashMap;\r\nimport java.util.HashSet;\r\nimport java.util.List;\r\nimport java.util.Map;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport jaicore.basic.sets.SetUtil;\r\nimport jaicore.logic.fol.structure.CNFFormula;\r\nimport jaicore.logic.fol.structure.Clause;\r\nimport jaicore.logic.fol.structure.ConstantParam;\r\nimport jaicore.logic.fol.structure.Literal;\r\nimport jaicore.logic.fol.structure.LiteralParam;\r\nimport jaicore.logic.fol.structure.LiteralSet;\r\nimport jaicore.logic.fol.structure.Monom;\r\nimport jaicore.logic.fol.structure.VariableParam;\r\n\r\n/**\r\n * Utility class for the logic package.\r\n * \r\n * @author fmohr, mbunse\r\n */\r\npublic class LogicUtil {\r\n\r\n\tprivate static final Logger logger = LoggerFactory.getLogger(LogicUtil.class);\r\n\r\n\t/**\r\n\t * @param a\r\n\t * The literal set A.\r\n\t * @param b\r\n\t * The literal set B.\r\n\t * @return The intersection of A and B.\r\n\t */\r\n\tpublic static LiteralSet intersectionOfLiteralSets(LiteralSet a, LiteralSet b) {\r\n\r\n\t\treturn new LiteralSet(SetUtil.intersection(a, b));\r\n\r\n\t}\r\n\r\n\t/**\r\n\t * @param a\r\n\t * The literal set A.\r\n\t * @param b\r\n\t * The literal set B.\r\n\t * @return The difference A \\ B.\r\n\t */\r\n\tpublic static LiteralSet differenceOfLiteralSets(LiteralSet a, LiteralSet b) {\r\n\r\n\t\treturn new LiteralSet(SetUtil.difference(a, b));\r\n\r\n\t}\r\n\t\r\n\tpublic static Collection<Map<VariableParam, LiteralParam>> getSubstitutionsThatEnableForwardChaining(Collection<Literal> factbase, Collection<Literal> premise) {\r\n\t\treturn getSubstitutionsThatEnableForwardChaining(factbase, new ArrayList<>(premise));\r\n\t}\r\n\t\r\n\tpublic static boolean doesPremiseContainAGroundLiteralThatIsNotInFactBase(Collection<Literal> factbase, Collection<Literal> premise) {\r\n\t\tfor (Literal l : premise) {\r\n\t\t\tif (l.isGround() && !factbase.contains(l))\r\n\t\t\t\treturn true;\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\tpublic static boolean doesPremiseContainAGroundLiteralThatIsNotInFactBaseCWA(Collection<Literal> factbase, Collection<Literal> premise) {\r\n\t\tfor (Literal l : premise) {\r\n\t\t\tif (!l.isGround())\r\n\t\t\t\tcontinue;\r\n\t\t\tif (l.isPositive()) {\r\n\t\t\t\tif (!factbase.contains(l))\r\n\t\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tif (factbase.contains(l.clone().toggleNegation()))\r\n\t\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\r\n\tprivate static Collection<Map<VariableParam, LiteralParam>> getSubstitutionsThatEnableForwardChaining(Collection<Literal> factbase, List<Literal> premise) {\r\n\t\t\r\n\t\tlogger.info(\"Computing substitution for {} that enable forward chaining from {}\", premise, factbase);\r\n\t\tCollection<Map<VariableParam, LiteralParam>> mappings = new HashSet<>();\r\n\r\n\t\t/* if the premise is empty, add the empty mapping */\r\n\t\tif (premise.isEmpty()) {\r\n\t\t\tmappings.add(new HashMap<>());\r\n\t\t\treturn mappings;\r\n\t\t}\r\n\r\n\t\t/* in any other case, select a literal and compute remaining premise, which is the premise minus the first element, minus all other ground elements */\r\n\t\tLiteral nextLiteral = premise.get(0);\r\n\t\tList<Literal> remainingPremise = new ArrayList<>();\r\n\t\tfor (int i = 1; i < premise.size(); i++) {\r\n\t\t\tif (!premise.get(i).getVariableParams().isEmpty())\r\n\t\t\t\tremainingPremise.add(premise.get(i));\r\n\t\t}\r\n\t\tList<VariableParam> openParams = nextLiteral.getVariableParams();\r\n\r\n\t\t/* if there are no open params, we do not need to make decisions here, so just compute subsolutions */\r\n\t\tCollection<Map<VariableParam, LiteralParam>> choices = new HashSet<>();\r\n\t\tif (openParams.isEmpty()) {\r\n\t\t\tchoices.add(new HashMap<>());\r\n\t\t}\r\n\r\n\t\t/* otherwise, select literal from the factbase that could be used for unification */\r\n\t\telse {\r\n\t\t\tfor (Literal fact : factbase) {\r\n\t\t\t\tif (!fact.getPropertyName().equals(nextLiteral.getPropertyName()) || fact.isPositive() != nextLiteral.isPositive())\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\tList<LiteralParam> factParams = fact.getParameters(); // should only contain constant params\r\n\t\t\t\tList<LiteralParam> nextLiteralParams = nextLiteral.getParameters();\r\n\t\t\t\tMap<VariableParam, LiteralParam> submap = new HashMap<>();\r\n\r\n\t\t\t\t/* create a substitution that grounds the rest of the literal */\r\n\t\t\t\tfor (int i = 0; i < factParams.size(); i++) {\r\n\t\t\t\t\tif (nextLiteralParams.get(i) instanceof VariableParam) {\r\n\t\t\t\t\t\tsubmap.put((VariableParam) nextLiteralParams.get(i), factParams.get(i));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tchoices.add(submap);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/* now apply the different possible choices substitution to the remaining premise and compute possible submappings */\r\n\t\tfor (Map<VariableParam, LiteralParam> submap : choices) {\r\n\t\t\tMonom modifiedRemainingPremise = new Monom(remainingPremise, submap);\r\n\t\t\t\r\n\t\t\t/* if there is a ground literal in the modified remaining premise that is not in the fact base, skip this option */\r\n\t\t\tif (doesPremiseContainAGroundLiteralThatIsNotInFactBase(factbase, modifiedRemainingPremise))\r\n\t\t\t\tcontinue;\r\n\t\t\t\r\n\t\t\t/* otherwise recurse */\r\n\t\t\tCollection<Map<VariableParam, LiteralParam>> subsolutions = getSubstitutionsThatEnableForwardChaining(factbase, modifiedRemainingPremise);\r\n\t\t\tfor (Map<VariableParam, LiteralParam> subsolution : subsolutions) {\r\n\t\t\t\tMap<VariableParam, LiteralParam> solutionToReturn = new HashMap<>(subsolution);\r\n\t\t\t\tsolutionToReturn.putAll(submap);\r\n\t\t\t\tmappings.add(solutionToReturn);\r\n\t\t\t}\r\n\t\t}\r\n\t\tlogger.info(\"Finished computation of substitution for {} that enable forward chaining from {}: {}\", premise, factbase, mappings);\r\n\t\treturn mappings;\r\n\t}\r\n\r\n\tpublic static boolean canLiteralBeUnifiedWithLiteralFromDatabase(Collection<Literal> set, Literal literal) {\r\n\t\tfor (Literal candidate : set) {\r\n\t\t\tif (areLiteralsUnifiable(candidate, literal))\r\n\t\t\t\treturn true;\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\r\n\tpublic static boolean areLiteralsUnifiable(Literal l1, Literal l2) {\r\n\t\tif (!l1.getPropertyName().equals(l2.getPropertyName()))\r\n\t\t\treturn false;\r\n\t\tList<LiteralParam> paramsOfL1 = l1.getParameters();\r\n\t\tList<LiteralParam> paramsOfL2 = l2.getParameters();\r\n\t\tfor (int i = 0; i < paramsOfL1.size(); i++) {\r\n\t\t\tif (paramsOfL1.get(i) instanceof ConstantParam && paramsOfL2.get(i) instanceof ConstantParam && !paramsOfL1.get(i).equals(paramsOfL2.get(i)))\r\n\t\t\t\treturn false;\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\r\n\tpublic static LiteralParam parseParamName(String name) {\r\n\t\treturn (name.startsWith(\"'\") && name.endsWith(\"'\")) ? new ConstantParam(name.substring(1, name.length() - 1)) : new VariableParam(name);\r\n\t}\r\n\r\n\tpublic static boolean evalEquality(Literal l) {\r\n\t\tList<LiteralParam> params = l.getParameters();\r\n\t\tif (!(params.get(0) instanceof ConstantParam) || !(params.get(1) instanceof ConstantParam))\r\n\t\t\tthrow new IllegalArgumentException(\"Equality cannot be evaluated for non-constants!\");\r\n\t\treturn params.get(0).equals(params.get(1)) == l.isPositive();\r\n\t}\r\n\r\n\tpublic static CNFFormula evalEqualityLiteralsUnderUNA(CNFFormula set) {\r\n\t\tCNFFormula newFormula = new CNFFormula();\r\n\r\n\t\tfor (Clause c : set) {\r\n\t\t\tClause cNew = new Clause();\r\n\t\t\tfor (Literal l : c) {\r\n\t\t\t\tif (l.getPropertyName().equals(\"=\")) {\r\n\t\t\t\t\tList<LiteralParam> params = l.getParameters();\r\n\t\t\t\t\tif (params.get(0) instanceof ConstantParam && params.get(1) instanceof ConstantParam) {\r\n\t\t\t\t\t\tif (params.get(0).equals(params.get(1)) != l.isPositive())\r\n\t\t\t\t\t\t\treturn new CNFFormula(new Monom(\"A & !A\"));\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tcNew.add(l);\r\n\t\t\t\t\t}\r\n\t\t\t\t} else {\r\n\t\t\t\t\tcNew.add(l);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (!cNew.isEmpty())\r\n\t\t\t\tnewFormula.add(cNew);\r\n\t\t}\r\n\t\treturn newFormula;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6045340299606323, "alphanum_fraction": 0.6259445548057556, "avg_line_length": 25.44827651977539, "blob_id": "e22c6bc6e79ecd0ec981b2ff38620c9f3a747dc8", "content_id": "1bf2e3c8cc4d81d13adf4dfe03e3805ae04a0403", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Gradle", "length_bytes": 794, "license_type": "no_license", "max_line_length": 67, "num_lines": 29, "path": "/JAICore/jaicore-planning/build.gradle", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "sourceSets {\r\n main {\r\n java {\r\n srcDir 'src'\r\n }\r\n }\r\n test {\r\n \tjava {\r\n \t\tsrcDir 'test'\r\n \t}\r\n }\r\n}\r\ndependencies {\r\n\tcompile project(\":JAICore:jaicore-search\")\r\n\tcompile project(\":JAICore:jaicore-basic\")\r\n\tcompile project(\":JAICore:jaicore-logic\")\r\n\tcompile project(\":JAICore:jaicore-graphvisualizer\")\r\n\tcompile project(\":JAICore:jaicore-graph\")\r\n\t\r\n\t//pddl4j\r\n\tcompile ('com.github.pellierd:pddl4j:v3.5.0') {\r\n exclude group: 'org.apache.logging.log4j', module: 'log4j-core'\r\n exclude group: 'org.apache.logging.log4j', module: 'log4j-api'\r\n }\r\n\truntime ('com.github.pellierd:pddl4j:v3.5.0') {\r\n exclude group: 'org.apache.logging.log4j', module: 'log4j-core'\r\n exclude group: 'org.apache.logging.log4j', module: 'log4j-api'\r\n }\r\n}" }, { "alpha_fraction": 0.6965517401695251, "alphanum_fraction": 0.6965517401695251, "avg_line_length": 19.85714340209961, "blob_id": "e9a3530cfcb18309d9d6ea3833a944bf66c7fe0f", "content_id": "8fcf3acf824481f50297fbace70b75a0548172be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 145, "license_type": "no_license", "max_line_length": 86, "num_lines": 7, "path": "/softwareconfiguration/hasco/src/hasco/metamining/package-info.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "/**\n * Classes used to gain meta information about a given (partial) software composition.\n * \n * @author Helena Graf\n *\n */\npackage hasco.metamining;" }, { "alpha_fraction": 0.7114914655685425, "alphanum_fraction": 0.7114914655685425, "avg_line_length": 18.4761905670166, "blob_id": "193be416458e80d4952b64b03905498d247f5480", "content_id": "62d5b54d95318bbd292bdce6e9a804fade3a436a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 409, "license_type": "no_license", "max_line_length": 72, "num_lines": 21, "path": "/JAICore/jaicore-basic/src/jaicore/basic/kvstore/KeyValueType.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.basic.kvstore;\n\npublic class KeyValueType<V> {\n\n private Class<V> typeClass;\n private V standardValue;\n\n public KeyValueType(final Class<V> typeClass, final V standardValue) {\n this.typeClass = typeClass;\n this.standardValue = standardValue;\n }\n\n public Class<V> getTypeClass() {\n return this.typeClass;\n }\n\n public V getStandardValue() {\n return this.standardValue;\n }\n\n}\n" }, { "alpha_fraction": 0.7338645458221436, "alphanum_fraction": 0.7338645458221436, "avg_line_length": 24.14583396911621, "blob_id": "84cf0183702be75fc875133eaff342d32d6bc845", "content_id": "b117ea0aefc2118a9d473ec2289b5871dd24c8da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1255, "license_type": "no_license", "max_line_length": 115, "num_lines": 48, "path": "/JAICore/jaicore-search/src/jaicore/search/structure/graphgenerator/SubGraphGenerator.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.structure.graphgenerator;\r\n\r\nimport jaicore.search.core.interfaces.GraphGenerator;\r\n\r\n/**\r\n * This is a graph generator that takes another graph generator and generates its sub-graph under a given root node\r\n * \r\n * @author fmohr\r\n *\r\n * @param <N>\r\n * @param <A>\r\n */\r\npublic class SubGraphGenerator<N,A> implements GraphGenerator<N, A> {\r\n\t\r\n\tprivate final GraphGenerator<N,A> actualGraphGenerator;\r\n\tprivate final N newRoot;\r\n\r\n\tpublic SubGraphGenerator(GraphGenerator<N, A> actualGraphGenerator, N newRoot) {\r\n\t\tsuper();\r\n\t\tthis.actualGraphGenerator = actualGraphGenerator;\r\n\t\tthis.newRoot = newRoot;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic SingleRootGenerator<N> getRootGenerator() {\r\n\t\treturn () -> newRoot;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic SuccessorGenerator<N, A> getSuccessorGenerator() {\r\n\t\treturn actualGraphGenerator.getSuccessorGenerator();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic GoalTester<N> getGoalTester() {\r\n\t\treturn actualGraphGenerator.getGoalTester();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean isSelfContained() {\r\n\t\treturn actualGraphGenerator.isSelfContained();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void setNodeNumbering(boolean nodenumbering) {\r\n\t\tthrow new UnsupportedOperationException(\"Node numering cannot be modified on sub graph generator\");\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.8457047343254089, "alphanum_fraction": 0.8457047343254089, "avg_line_length": 51.130435943603516, "blob_id": "dbf8e931b60aea3e91f7cde3ed9eb102d18c5e9f", "content_id": "4a12701be54769e4e318ba001e80b08e0bf1336f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1199, "license_type": "no_license", "max_line_length": 213, "num_lines": 23, "path": "/JAICore/jaicore-search/test/jaicore/search/algorithms/standard/awastar/AwaStarNQueensTest.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.awastar;\n\nimport jaicore.basic.algorithm.AlgorithmProblemTransformer;\nimport jaicore.search.core.interfaces.IGraphSearchFactory;\nimport jaicore.search.model.other.EvaluatedSearchGraphPath;\nimport jaicore.search.model.probleminputs.GeneralEvaluatedTraversalTree;\nimport jaicore.search.model.travesaltree.Node;\nimport jaicore.search.testproblems.nqueens.NQueenTester;\nimport jaicore.search.testproblems.nqueens.NQueensToGeneralTravesalTreeReducer;\nimport jaicore.search.testproblems.nqueens.QueenNode;\n\npublic class AwaStarNQueensTest extends NQueenTester<GeneralEvaluatedTraversalTree<QueenNode, String, Double>, EvaluatedSearchGraphPath<QueenNode, String, Double>, Node<QueenNode, Double>, String> {\n\n\t@Override\n\tpublic IGraphSearchFactory<GeneralEvaluatedTraversalTree<QueenNode, String, Double>, EvaluatedSearchGraphPath<QueenNode, String, Double>, QueenNode, String, Double, Node<QueenNode, Double>, String> getFactory() {\n\t\treturn new AWAStarFactory<>();\n\t}\n\n\t@Override\n\tpublic AlgorithmProblemTransformer<Integer, GeneralEvaluatedTraversalTree<QueenNode, String, Double>> getProblemReducer() {\n\t\treturn new NQueensToGeneralTravesalTreeReducer();\n\t}\n}\n" }, { "alpha_fraction": 0.7008175849914551, "alphanum_fraction": 0.7010730504989624, "avg_line_length": 37.53535461425781, "blob_id": "588ecef3c868866d438fd1e0db0a3a311e2794b1", "content_id": "cfb089eea1b4484dbd5adb238c4ec70e75c72ab1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3914, "license_type": "no_license", "max_line_length": 171, "num_lines": 99, "path": "/JAICore/jaicore-search/test/jaicore/search/testproblems/bipartitions/BiPartitionFinder.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "//package jaicore.search.testproblems.bipartitions;\r\n//\r\n//import java.util.ArrayList;\r\n//import java.util.Collection;\r\n//import java.util.HashSet;\r\n//import java.util.List;\r\n//\r\n//import jaicore.basic.IObjectEvaluator;\r\n//import jaicore.basic.sets.SetUtil.Pair;\r\n//import jaicore.graphvisualizer.SimpleGraphVisualizationWindow;\r\n//import jaicore.search.algorithms.standard.bestfirst.BestFirst;\r\n//import jaicore.search.algorithms.standard.bestfirst.model.GraphGenerator;\r\n//import jaicore.search.algorithms.standard.bestfirst.model.NodeExpansionDescription;\r\n//import jaicore.search.algorithms.standard.bestfirst.model.NodeType;\r\n//import jaicore.search.core.searchproblems.EvaluatedSearchAlgorithmSolution;\r\n//import jaicore.search.structure.graphgenerator.NodeGoalTester;\r\n//import jaicore.search.structure.graphgenerator.SingleRootGenerator;\r\n//import jaicore.search.structure.graphgenerator.SuccessorGenerator;\r\n//\r\n//public class BiPartitionFinder<T> {\r\n//\r\n//\t/**\r\n//\t * Class to maintain the choices\r\n//\t * \r\n//\t * @author fmohr\r\n//\t *\r\n//\t */\r\n//\tprivate class BFNode {\r\n//\t\tCollection<T> itemsOnLeft;\r\n//\t\tCollection<T> itemsOnRight;\r\n//\r\n//\t\tpublic BFNode(Collection<T> itemsOnLeft, Collection<T> itemsOnRight) {\r\n//\t\t\tsuper();\r\n//\t\t\tthis.itemsOnLeft = itemsOnLeft;\r\n//\t\t\tthis.itemsOnRight = itemsOnRight;\r\n//\t\t}\r\n//\r\n//\t\t@Override\r\n//\t\tpublic String toString() {\r\n//\t\t\treturn \"BFNode [itemsOnLeft=\" + itemsOnLeft + \", itemsOnRight=\" + itemsOnRight + \"]\";\r\n//\t\t}\r\n//\t}\r\n//\r\n//\tprivate class BFGraphGenerator implements GraphGenerator<BFNode, Boolean> {\r\n//\r\n//\t\t@Override\r\n//\t\tpublic SingleRootGenerator<BFNode> getRootGenerator() {\r\n//\t\t\treturn () -> new BFNode(new HashSet<>(), new HashSet<>());\r\n//\t\t}\r\n//\r\n//\t\t@Override\r\n//\t\tpublic SuccessorGenerator<BiPartitionFinder<T>.BFNode, Boolean> getSuccessorGenerator() {\r\n//\t\t\treturn n -> {\r\n//\t\t\t\tList<NodeExpansionDescription<BFNode, Boolean>> successors = new ArrayList<>();\r\n//\t\t\t\tint k = n.itemsOnLeft.size() + n.itemsOnRight.size();\r\n//\t\t\t\tT newItem = items.get(k);\r\n//\t\t\t\tCollection<T> aLeft = new HashSet<>(n.itemsOnLeft);\r\n//\t\t\t\taLeft.add(newItem);\r\n//\t\t\t\tCollection<T> aRight = new HashSet<>(n.itemsOnRight);\r\n//\t\t\t\taRight.add(newItem);\r\n//\t\t\t\tsuccessors.add(new NodeExpansionDescription<BiPartitionFinder<T>.BFNode, Boolean>(n, new BFNode(aLeft, n.itemsOnRight), true, NodeType.OR));\r\n//\t\t\t\tsuccessors.add(new NodeExpansionDescription<BiPartitionFinder<T>.BFNode, Boolean>(n, new BFNode(n.itemsOnLeft, aRight), false, NodeType.OR));\r\n//\t\t\t\treturn successors;\r\n//\t\t\t};\r\n//\t\t}\r\n//\r\n//\t\t@Override\r\n//\t\tpublic NodeGoalTester<BiPartitionFinder<T>.BFNode> getGoalTester() {\r\n//\t\t\treturn n -> n.itemsOnLeft.size() + n.itemsOnRight.size() == items.size();\r\n//\t\t}\r\n//\r\n//\t\t@Override\r\n//\t\tpublic boolean isSelfContained() {\r\n//\t\t\treturn true;\r\n//\t\t}\r\n//\r\n//\t\t@Override\r\n//\t\tpublic void setNodeNumbering(boolean nodenumbering) {\r\n//\t\t\tthrow new UnsupportedOperationException(\"No node numbering supported.\");\r\n//\t\t}\r\n//\t}\r\n//\r\n//\tprivate final List<T> items;\r\n//\tprivate final BestFirst<BFNode, Boolean, Double> search;\r\n//\r\n//\tpublic BiPartitionFinder(Collection<T> items, IObjectEvaluator<Pair<Collection<T>, Collection<T>>, Double> evaluator) {\r\n//\t\tsuper();\r\n//\t\tthis.items = new ArrayList<>(items);\r\n//\t\tthis.search = new BestFirst<BFNode, Boolean, Double>(new BFGraphGenerator(), n -> evaluator.evaluate(new Pair<>(n.getPoint().itemsOnLeft, n.getPoint().itemsOnRight)));\r\n//\t}\r\n//\r\n//\tpublic Pair<Collection<T>, Collection<T>> getPartition() throws InterruptedException {\r\n//\t\tnew SimpleGraphVisualizationWindow<>(this.search);\r\n//\t\tEvaluatedSearchAlgorithmSolution<BiPartitionFinder<T>.BFNode,Boolean,Double> solution = this.search.nextSolution();\r\n//\t\tList<BFNode> solutionPath = solution.getNodes();\r\n//\t\tBFNode lastNode = solutionPath.get(solutionPath.size() - 1);\r\n//\t\treturn new Pair<>(lastNode.itemsOnLeft, lastNode.itemsOnRight);\r\n//\t}\r\n//}\r\n" }, { "alpha_fraction": 0.6687548756599426, "alphanum_fraction": 0.6746280193328857, "avg_line_length": 29.04705810546875, "blob_id": "70bd2cc91fc3f032e3ad0cd33b8157a330e3024b", "content_id": "ce5674ac995f59d152caa4d8a3f8864188184a9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5108, "license_type": "no_license", "max_line_length": 189, "num_lines": 170, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/opencollections/TimedEnforcedExplorationOpenSelection.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "//package jaicore.search.algorithms.standard.opencollections;\n//\n//import java.util.Collection;\n//import java.util.Iterator;\n//\n//import org.slf4j.Logger;\n//import org.slf4j.LoggerFactory;\n//\n//import jaicore.search.algorithms.standard.bestfirst.model.OpenCollection;\n//import jaicore.search.algorithms.standard.bestfirst.model.PriorityQueueOpen;\n//import jaicore.search.algorithms.standard.bestfirst.nodeevaluation.INodeEvaluator;\n//import jaicore.search.model.travesaltree.Node;\n//\n///**\n// * This is like EnforcedExplorationOpenSelection except that there is a fixed rule how the restriction on exploration is set.\n// * \n// * @author fmohr\n// *\n// * @param <N>\n// * @param <V>\n// * @param <W>\n// */\n//public class TimedEnforcedExplorationOpenSelection<N,V extends Comparable<V>,W extends Comparable<W>> extends EnforcedExplorationOpenSelection<N, V, W> {\n//\t\n//\tprivate static final Logger logger = LoggerFactory.getLogger(TimedEnforcedExplorationOpenSelection.class);\n//\t\n//\tprivate final PriorityQueueOpen<Node<N, V>> secondaryOpen = new PriorityQueueOpen<>();\n//\tprivate final INodeEvaluator<N, W> explorationEvaluator;\n//\tprivate int explorationPhaseLength = 10;\n//\tprivate int exploitationPhaseLength = 50;\n//\tprivate int selectedNodes = 0;\n//\tprivate int exploredNodes = 0;\n//\tprivate boolean exploring = false;\n//\n//\tpublic TimedEnforcedExplorationOpenSelection(OpenCollection<Node<N, V>> primaryOpen, INodeEvaluator<N, W> explorationEvaluator, int explorationPhaseLength, int exploitationPhaseLength) {\n//\t\tsuper(primaryOpen);\n//\t\tthis.explorationEvaluator = explorationEvaluator;\n//\t\tthis.explorationPhaseLength = explorationPhaseLength;\n//\t\tthis.exploitationPhaseLength = exploitationPhaseLength;\n//\t}\n//\n//\t@Override\n//\tpublic Node<N, V> peek() {\n//\t\t\n//\t\tif (!exploring) {\n//\t\t\tselectedNodes++;\n//\t\t\tif (selectedNodes % exploitationPhaseLength != 0) {\n//\t\t\t\t// System.out.println(\"Exploiting ...\");\n//\t\t\t\treturn primaryOpen.peek();\n//\t\t\t}\n//\n//\t\t\t/* now chose particular node for expansion */\n//\t\t\tNode<N, V> nodeToBeExplored = primaryOpen.stream().min((n1, n2) -> {\n//\t\t\t\ttry {\n//\t\t\t\t\treturn explorationEvaluator.f(n1).compareTo(explorationEvaluator.f(n2));\n//\t\t\t\t} catch (Throwable e) {\n//\t\t\t\t\te.printStackTrace();\n//\t\t\t\t}\n//\t\t\t\treturn 0;\n//\t\t\t}).get();\n//\n//\t\t\t/* enable exploration with the node selected by the explorer evaluator */\n//\t\t\ttry {\n//\t\t\t\tif (logger.isInfoEnabled())\n//\t\t\t\t\tlogger.info(\"Entering exploration phase under {} with exploration value: {}\", nodeToBeExplored, explorationEvaluator.f(nodeToBeExplored));\n//\t\t\t} catch (Throwable e) {\n//\t\t\t\te.printStackTrace();\n//\t\t\t}\n//\t\t\texploring = true;\n//\t\t\texploredNodes = 0;\n//\t\t\tprimaryOpen.remove(nodeToBeExplored);\n//\t\t\tsecondaryOpen.clear();\n//\t\t\tsecondaryOpen.add(nodeToBeExplored);\n//\t\t\treturn nodeToBeExplored;\n//\t\t} else {\n//\t\t\texploredNodes++;\n//\t\t\tif (exploredNodes > explorationPhaseLength || secondaryOpen.isEmpty()) {\n//\t\t\t\texploring = false;\n//\t\t\t\tprimaryOpen.addAll(secondaryOpen);\n//\t\t\t\tsecondaryOpen.clear();\n//\t\t\t\treturn primaryOpen.peek();\n//\t\t\t}\n//\t\t\treturn secondaryOpen.peek();\n//\t\t}\n//\t}\n//\n//\t@Override\n//\tpublic boolean add(Node<N, V> node) {\n//\t\tassert !contains(node) : \"Node \" + node + \" is already there!\";\n//\t\tif (exploring) {\n//\t\t\treturn secondaryOpen.add(node);\n//\t\t} else\n//\t\t\treturn primaryOpen.add(node);\n//\t}\n//\n//\t@Override\n//\tpublic boolean remove(Object node) {\n//\t\tassert !(primaryOpen.contains(node) && secondaryOpen.contains(node)) : \"A node (\" + node + \") that is to be removed is in BOTH open lists!\";\n//\t\tif (exploring) {\n//\t\t\treturn secondaryOpen.remove(node) || primaryOpen.remove(node);\n//\t\t} else {\n//\t\t\treturn primaryOpen.remove(node) || secondaryOpen.remove(node);\n//\t\t}\n//\t}\n//\n//\t@Override\n//\tpublic boolean addAll(Collection<? extends Node<N, V>> arg0) {\n//\t\tif (exploring) {\n//\t\t\treturn secondaryOpen.addAll(arg0);\n//\t\t} else\n//\t\t\treturn primaryOpen.addAll(arg0);\n//\t}\n//\n//\t@Override\n//\tpublic void clear() {\n//\t\tprimaryOpen.clear();\n//\t\tsecondaryOpen.clear();\n//\t}\n//\n//\t@Override\n//\tpublic boolean contains(Object arg0) {\n//\t\treturn primaryOpen.contains(arg0) || secondaryOpen.contains(arg0);\n//\t}\n//\n//\t@Override\n//\tpublic boolean containsAll(Collection<?> arg0) {\n//\t\tfor (Object o : arg0) {\n//\t\t\tif (!contains(o))\n//\t\t\t\treturn false;\n//\t\t}\n//\t\treturn true;\n//\t}\n//\n//\t@Override\n//\tpublic boolean isEmpty() {\n//\t\treturn primaryOpen.isEmpty() && secondaryOpen.isEmpty();\n//\t}\n//\n//\t@Override\n//\tpublic Iterator<Node<N, V>> iterator() {\n//\t\treturn null;\n//\t}\n//\n//\t@Override\n//\tpublic boolean removeAll(Collection<?> arg0) {\n//\t\treturn primaryOpen.removeAll(arg0) && secondaryOpen.removeAll(arg0);\n//\t}\n//\n//\t@Override\n//\tpublic boolean retainAll(Collection<?> arg0) {\n//\t\treturn primaryOpen.retainAll(arg0) && secondaryOpen.retainAll(arg0);\n//\t}\n//\n//\t@Override\n//\tpublic int size() {\n//\t\treturn primaryOpen.size() + secondaryOpen.size();\n//\t}\n//\n//\t@Override\n//\tpublic Object[] toArray() {\n//\t\treturn primaryOpen.toArray();\n//\t}\n//\n//\t@SuppressWarnings(\"unchecked\")\n//\t@Override\n//\tpublic <T> T[] toArray(T[] arg0) {\n//\t\treturn (T[]) primaryOpen.toArray();\n//\t}\n//\n//}\n" }, { "alpha_fraction": 0.7701975107192993, "alphanum_fraction": 0.7701975107192993, "avg_line_length": 29.828571319580078, "blob_id": "8e084c120baa065bc57818e28ef25845fc5369a9", "content_id": "dd6f107de301fea7835b8d9205a0a06d03257a8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1114, "license_type": "no_license", "max_line_length": 120, "num_lines": 35, "path": "/softwareconfiguration/hasco/src/hasco/core/TimeRecordingEvaluationWrapper.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package hasco.core;\r\n\r\nimport java.util.HashMap;\r\nimport java.util.Map;\r\n\r\nimport hasco.model.ComponentInstance;\r\nimport jaicore.basic.IObjectEvaluator;\r\n\r\npublic class TimeRecordingEvaluationWrapper<V extends Comparable<V>> implements IObjectEvaluator<ComponentInstance, V> {\r\n\r\n\tprivate final IObjectEvaluator<ComponentInstance, V> baseEvaluator;\r\n\tprivate final Map<ComponentInstance, Integer> consumedTimes = new HashMap<>();\r\n\r\n\tpublic TimeRecordingEvaluationWrapper(IObjectEvaluator<ComponentInstance, V> baseEvaluator) {\r\n\t\tsuper();\r\n\t\tthis.baseEvaluator = baseEvaluator;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic V evaluate(ComponentInstance object) throws Exception {\r\n\t\tlong start = System.currentTimeMillis();\r\n\t\tV score = baseEvaluator.evaluate(object);\r\n\t\tlong end = System.currentTimeMillis();\r\n\t\tconsumedTimes.put(object, (int) (end - start));\r\n\t\treturn score;\r\n\t}\r\n\t\r\n\tpublic boolean hasEvaluationForComponentInstance(ComponentInstance inst) {\r\n\t\treturn consumedTimes.containsKey(inst);\r\n\t}\r\n\r\n\tpublic int getEvaluationTimeForComponentInstance(ComponentInstance inst) {\r\n\t\treturn consumedTimes.get(inst);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.75, "avg_line_length": 28, "blob_id": "2da895d536ae52e6faf537d660a957d24f35776d", "content_id": "55c612a769b238fb584d185e7cc4d1875fddbb46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Gradle", "length_bytes": 28, "license_type": "no_license", "max_line_length": 28, "num_lines": 1, "path": "/softwareconfiguration/mlplan/settings.gradle", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "rootProject.name = 'ML-Plan'" }, { "alpha_fraction": 0.7301662564277649, "alphanum_fraction": 0.7344418168067932, "avg_line_length": 19.92708396911621, "blob_id": "68736881ed3540dc29e04ab0f798a3bbfe8b1aaa", "content_id": "04579e9fbd47d83c6f615be5054eb8e15eadd9bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2105, "license_type": "no_license", "max_line_length": 105, "num_lines": 96, "path": "/softwareconfiguration/mlplan/src/de/upb/crc901/mlplan/multilabel/MultilabelMLPipeline.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package de.upb.crc901.mlplan.multilabel;\r\n\r\nimport java.io.Serializable;\r\nimport java.util.Enumeration;\r\n\r\nimport de.upb.crc901.mlplan.multiclass.wekamlplan.weka.model.MLPipeline;\r\nimport meka.classifiers.multilabel.MultiLabelClassifier;\r\nimport weka.attributeSelection.ASEvaluation;\r\nimport weka.attributeSelection.ASSearch;\r\nimport weka.core.Capabilities;\r\nimport weka.core.Instance;\r\nimport weka.core.Instances;\r\nimport weka.core.Option;\r\n\r\n/**\r\n * \r\n * @author Felix Mohr\r\n *\r\n */\r\n@SuppressWarnings(\"serial\")\r\npublic class MultilabelMLPipeline implements MultiLabelClassifier, Serializable {\r\n\r\n\tprivate final MLPipeline actualPipeline;\r\n\t\r\n\tprivate MultilabelMLPipeline(MLPipeline pl) {\r\n\t\tactualPipeline = pl;\r\n\t}\r\n\r\n\tpublic MultilabelMLPipeline(ASSearch search, ASEvaluation evaluation, MultiLabelClassifier classifier) {\r\n\t\tsuper();\r\n\t\tthis.actualPipeline = new MLPipeline(search, evaluation, classifier);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void buildClassifier(Instances trainingSet) throws Exception {\r\n\t\tactualPipeline.buildClassifier(trainingSet);;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic double[] distributionForInstance(Instance i) throws Exception {\r\n\t\treturn actualPipeline.distributionForInstance(i);\r\n\t}\r\n\t\r\n\tpublic MultilabelMLPipeline clone() {\r\n\t\treturn new MultilabelMLPipeline(actualPipeline.clone());\r\n\t}\r\n\r\n\t@Override\r\n\tpublic double classifyInstance(Instance arg0) throws Exception {\r\n\t\treturn actualPipeline.classifyInstance(arg0);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic Capabilities getCapabilities() {\r\n\t\treturn actualPipeline.getCapabilities();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String[] getOptions() {\r\n\t\treturn null;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic Enumeration<Option> listOptions() {\r\n\t\treturn null;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void setOptions(String[] arg0) throws Exception {\r\n\t\t\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void setDebug(boolean debug) {\r\n\t\t\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean getDebug() {\r\n\t\treturn false;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String debugTipText() {\r\n\t\treturn null;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String getModel() {\r\n\t\treturn null;\r\n\t}\r\n\r\n\tpublic MLPipeline getActualPipeline() {\r\n\t\treturn actualPipeline;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7181687951087952, "alphanum_fraction": 0.7213876843452454, "avg_line_length": 35.279998779296875, "blob_id": "338891ac47dd9122ef4f81d2262af2ef0d0b54be", "content_id": "9298b8d54ee49206396de5bca7387b682d274ec9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2796, "license_type": "no_license", "max_line_length": 157, "num_lines": 75, "path": "/softwareconfiguration/mlplan/src/de/upb/crc901/mlplan/multiclass/wekamlplan/weka/SemanticNodeEvaluator.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package de.upb.crc901.mlplan.multiclass.wekamlplan.weka;\r\n\r\nimport java.util.Collection;\r\n\r\nimport hasco.core.Util;\r\nimport hasco.model.Component;\r\nimport hasco.model.ComponentInstance;\r\nimport jaicore.planning.graphgenerators.task.tfd.TFDNode;\r\nimport jaicore.search.algorithms.standard.bestfirst.nodeevaluation.INodeEvaluator;\r\nimport jaicore.search.model.travesaltree.Node;\r\nimport weka.core.Attribute;\r\nimport weka.core.Instances;\r\n\r\npublic class SemanticNodeEvaluator implements INodeEvaluator<TFDNode, Double> {\r\n\r\n\tprivate final Instances data;\r\n\tprivate final Collection<Component> components;\r\n\r\n\t/* the predicates of the dataset */\r\n\tprivate final boolean binaryClass;\r\n\tprivate final boolean multiValuedNominalAttributes;\r\n\r\n\tpublic SemanticNodeEvaluator(final Collection<Component> components, final Instances data) {\r\n\t\tthis.data = data;\r\n\t\tthis.components = components;\r\n\r\n\t\t/* compute binary class predicate */\r\n\t\tbinaryClass = this.data.numClasses() == 2;\r\n\t\t\r\n\t\t/* determine whether the dataset is multi-valued nominal */\r\n\t\tboolean multiValuedNominalAttributes = false;\r\n\t\tfor (int i = 0; i < this.data.numAttributes(); i++) {\r\n\t\t\tAttribute att = this.data.attribute(i);\r\n\t\t\tif (att != this.data.classAttribute()) {\r\n\t\t\t\tif (att.isNominal() && att.numValues() > 2) {\r\n\t\t\t\t\tmultiValuedNominalAttributes = true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tthis.multiValuedNominalAttributes = multiValuedNominalAttributes;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic Double f(final Node<TFDNode, ?> n) throws Exception {\r\n\t\t/* get partial component */\r\n\t\tComponentInstance instance = Util.getSolutionCompositionFromState(this.components, n.getPoint().getState(), false);\r\n\r\n\t\tif (instance != null) {\r\n\t\t\tComponentInstance classifier;\r\n\r\n\t\t\tif (instance.getComponent().getName().toLowerCase().contains(\"pipeline\")) {\r\n\t\t\t\tclassifier = instance.getSatisfactionOfRequiredInterfaces().get(\"classifier\");\r\n\t\t\t} else {\r\n\t\t\t\tclassifier = instance;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif (classifier != null) {\r\n\t\t\t\t\r\n\t\t\t\tString classifierName = classifier.getComponent().getName().toLowerCase();\r\n\t\t\t\t\r\n\t\t\t\t/* forbid M5regression algorithms on non-binary classes */\r\n\t\t\t\tif (!this.binaryClass && classifierName.matches(\"(.*)(additiveregression|simplelinearregression|m5rules|votedperceptron|m5p)(.*)\"))\r\n\t\t\t\t\tthrow new IllegalArgumentException(\"Cannot adopt classifier \" + classifier.getClass().getName() + \" on non-binary datasets.\");\r\n\t\t\t\t\r\n\t\t\t\t/* forbid NaiveBayesMultinomial on multi-valued nominal attributes */\r\n\t\t\t\tif (multiValuedNominalAttributes && (classifierName.matches(\"(.*)(naivebayesmultinomial|simplelinearregression)(.*)\"))) {\r\n\t\t\t\t\tthrow new IllegalArgumentException(\"Cannot adopt classifier \" + classifier.getClass().getName() + \" on datasets with multi-valued nominal attributes.\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn null;\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.6977300047874451, "alphanum_fraction": 0.6977300047874451, "avg_line_length": 19.461538314819336, "blob_id": "3576fd78862f2fd620df2020d9d2ec401ba9b9e7", "content_id": "6ad4c98dcac0e9d6baa5460f574cbb80d28584e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 837, "license_type": "no_license", "max_line_length": 65, "num_lines": 39, "path": "/JAICore/jaicore-basic/src/jaicore/basic/TimeOut.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.basic;\r\n\r\nimport java.util.concurrent.TimeUnit;\r\n\r\npublic class TimeOut {\r\n\r\n\tprivate TimeUnit unit;\r\n\tprivate long duration;\r\n\r\n\tpublic TimeOut(final long duration, final TimeUnit unit) {\r\n\t\tthis.duration = duration;\r\n\t\tthis.unit = unit;\r\n\t}\r\n\r\n\tpublic long nanoseconds() {\r\n\t\treturn TimeUnit.NANOSECONDS.convert(this.duration, this.unit);\r\n\t}\r\n\r\n\tpublic long milliseconds() {\r\n\t\treturn TimeUnit.MILLISECONDS.convert(this.duration, this.unit);\r\n\t}\r\n\r\n\tpublic long minutes() {\r\n\t\treturn TimeUnit.MINUTES.convert(this.duration, this.unit);\r\n\t}\r\n\r\n\tpublic long seconds() {\r\n\t\treturn TimeUnit.SECONDS.convert(this.duration, this.unit);\r\n\t}\r\n\r\n\tpublic long hours() {\r\n\t\treturn TimeUnit.HOURS.convert(this.duration, this.unit);\r\n\t}\r\n\r\n\tpublic long days() {\r\n\t\treturn TimeUnit.DAYS.convert(this.duration, this.unit);\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.6887710094451904, "alphanum_fraction": 0.692307710647583, "avg_line_length": 22.081632614135742, "blob_id": "e81f9efed221ad29045e4633c366994d852c2326", "content_id": "fb64f97e5f08dfff1971b87bd24d556dc6e03928", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1131, "license_type": "no_license", "max_line_length": 83, "num_lines": 49, "path": "/JAICore/jaicore-ml/src/jaicore/ml/classification/multiclass/reduction/reducer/RestProblem.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.ml.classification.multiclass.reduction.reducer;\n\nimport java.util.ArrayList;\nimport java.util.Set;\n\n@SuppressWarnings(\"serial\")\nclass RestProblem extends ArrayList<Set<String>> {\n\t\n\tprivate static int counter = 0;\n\tprivate final int id = (counter ++);\n\tprivate final Decision edgeToParent;\n\n\tpublic RestProblem(Decision edgeToParent) {\n\t\tsuper();\n\t\tthis.edgeToParent = edgeToParent;\n\t}\n\n\tpublic Decision getEdgeToParent() {\n\t\treturn edgeToParent;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = super.hashCode();\n\t\tresult = prime * result + ((edgeToParent == null) ? 0 : edgeToParent.hashCode());\n\t\tresult = prime * result + id;\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (!super.equals(obj))\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tRestProblem other = (RestProblem) obj;\n\t\tif (edgeToParent == null) {\n\t\t\tif (other.edgeToParent != null)\n\t\t\t\treturn false;\n\t\t} else if (!edgeToParent.equals(other.edgeToParent))\n\t\t\treturn false;\n\t\tif (id != other.id)\n\t\t\treturn false;\n\t\treturn true;\n\t}\n}\n" }, { "alpha_fraction": 0.5928753018379211, "alphanum_fraction": 0.6017811894416809, "avg_line_length": 20.457143783569336, "blob_id": "93a29fdb9b891b14296f48cb29bf24222cb0743c", "content_id": "03e22fb26d86ff8ed1935cf92c7a4a7a3d1c1658", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Gradle", "length_bytes": 786, "license_type": "no_license", "max_line_length": 83, "num_lines": 35, "path": "/softwareconfiguration/hasco/build.gradle", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "plugins {\r\n\tid 'java'\r\n\tid 'eclipse-wtp'\r\n}\r\n\r\nsourceSets {\r\n main {\r\n java {\r\n srcDir 'src'\r\n }\r\n resources {\r\n \tsrcDir 'conf'\r\n \t}\r\n }\r\n test {\r\n\t \tjava {\r\n\t \t\tsrcDir 'test'\r\n\t \t}\r\n }\r\n}\r\n\r\ndependencies {\r\n\tcompile project(':JAICore:jaicore-basic')\r\n\tcompile project(':JAICore:jaicore-logic')\r\n\tcompile project(':JAICore:jaicore-graph')\r\n\tcompile project(':JAICore:jaicore-planning')\r\n\tcompile project(':JAICore:jaicore-search')\r\n\t\r\n\t// basic dependencies\r\n\tcompile group: 'org.apache.commons', name: 'commons-lang3', version: '3.6'\r\n\t// database connector\t\r\n\tcompile group: 'mysql', name: 'mysql-connector-java', version: '5.1.45'\r\n\t\r\n\ttestCompile project(path: ':JAICore:jaicore-basic', configuration: 'testArchives')\r\n}\r\n" }, { "alpha_fraction": 0.8172042965888977, "alphanum_fraction": 0.8172042965888977, "avg_line_length": 23.799999237060547, "blob_id": "2a9fe0ce17c5f472722926b3257f20f4d1694369", "content_id": "41526f70e946c407dae7ff26733582849c088c7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 372, "license_type": "no_license", "max_line_length": 66, "num_lines": 15, "path": "/JAICore/jaicore-planning/src/jaicore/planning/model/ceoc/CEOCPlanningDomain.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.model.ceoc;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\n\nimport jaicore.planning.model.core.Operation;\nimport jaicore.planning.model.core.PlanningDomain;\n\npublic class CEOCPlanningDomain extends PlanningDomain {\n\n\tpublic CEOCPlanningDomain(Collection<CEOCOperation> operations) {\n\t\tsuper(new ArrayList<Operation>(operations));\n\t}\n\n}\n" }, { "alpha_fraction": 0.776190459728241, "alphanum_fraction": 0.776190459728241, "avg_line_length": 38.38461685180664, "blob_id": "8890cb5c189e5859399863fa7cca628d955002f7", "content_id": "4bf24fa17347390cb356930fcc491af2d8564eb2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2100, "license_type": "no_license", "max_line_length": 194, "num_lines": 52, "path": "/JAICore/jaicore-planning/src/jaicore/planning/model/CostSensitivePlanningToSearchProblemTransformer.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.model;\r\n\r\nimport java.util.List;\r\n\r\nimport jaicore.basic.algorithm.AlgorithmProblemTransformer;\r\nimport jaicore.planning.graphgenerators.IPlanningGraphGeneratorDeriver;\r\nimport jaicore.planning.model.core.Action;\r\nimport jaicore.planning.model.core.Operation;\r\nimport jaicore.planning.model.task.IHTNPlanningProblem;\r\nimport jaicore.planning.model.task.stn.Method;\r\nimport jaicore.search.core.interfaces.ISolutionEvaluator;\r\nimport jaicore.search.model.probleminputs.GraphSearchProblemInput;\r\n\r\npublic class CostSensitivePlanningToSearchProblemTransformer<PO extends Operation, PM extends Method, PA extends Action, I extends IHTNPlanningProblem<PO, PM, PA>, V extends Comparable<V>, N, A>\r\n\t\timplements AlgorithmProblemTransformer<CostSensitiveHTNPlanningProblem<PO, PM, PA, I, V>, GraphSearchProblemInput<N, A, V>> {\r\n\r\n\tprivate final IPlanningGraphGeneratorDeriver<PO, PM, PA, I, N, A> graphGeneratorDeriver;\r\n\r\n\tpublic CostSensitivePlanningToSearchProblemTransformer(IPlanningGraphGeneratorDeriver<PO, PM, PA, I, N, A> graphGeneratorDeriver) {\r\n\t\tsuper();\r\n\t\tthis.graphGeneratorDeriver = graphGeneratorDeriver;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic GraphSearchProblemInput<N, A, V> transform(CostSensitiveHTNPlanningProblem<PO, PM, PA, I, V> problem) {\r\n\r\n\t\tISolutionEvaluator<N, V> solutionEvaluator = new ISolutionEvaluator<N,V>() {\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic V evaluateSolution(List<N> solutionPath) throws Exception {\r\n\t\t\t\treturn problem.getPlanEvaluator().evaluate(graphGeneratorDeriver.getPlan(solutionPath));\r\n\t\t\t}\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic boolean doesLastActionAffectScoreOfAnySubsequentSolution(List<N> partialSolutionPath) {\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic void cancel() {\r\n\t\t\t\t// TODO Auto-generated method stub\r\n\t\t\t\t\r\n\t\t\t}\r\n\t\t};\r\n\t\t/* derive the concrete graph search problem input */\r\n\t\treturn new GraphSearchProblemInput<>(graphGeneratorDeriver.transform(problem.getCorePlanningProblem()), solutionEvaluator);\r\n\t}\r\n\r\n\tpublic IPlanningGraphGeneratorDeriver<PO, PM, PA, I, N, A> getGraphGeneratorDeriver() {\r\n\t\treturn graphGeneratorDeriver;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.641791045665741, "alphanum_fraction": 0.6525372862815857, "avg_line_length": 27.879310607910156, "blob_id": "49052f99d799d587f4f266c7fb47baca3286f533", "content_id": "8fb1b90c83125f86790e7c358c8efef5f996b352", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1675, "license_type": "no_license", "max_line_length": 124, "num_lines": 58, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/uncertainty/BasicUncertaintySource.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.uncertainty;\n\nimport java.util.List;\n\nimport jaicore.search.model.travesaltree.Node;\n\npublic class BasicUncertaintySource<T, V extends Comparable<V>> implements IUncertaintySource<T, V> {\n\n\t@Override\n\tpublic double calculateUncertainty(Node<T, V> n, List<List<T>> simulationPaths, List<V> simulationEvaluations) {\n\t\t\n\t\tdouble uncertainty = 1.0d;\n\t\t\n\t\tif (simulationPaths != null && !simulationPaths.isEmpty()) {\n\t\t\tT t = n.getPoint();\n\t\t\tdouble meanDepth = 0.0d;\n\t\t\tfor (List<T> path : simulationPaths) {\n\t\t\t\tif (path.contains(t)) {\n\t\t\t\t\tdouble post = 0.0d;\n\t\t\t\t\tboolean startsCounting = false;\n\t\t\t\t\tfor (T pe : path) {\n\t\t\t\t\t\tif (startsCounting) {\n\t\t\t\t\t\t\tpost++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (pe.equals(t)) {\n\t\t\t\t\t\t\tstartsCounting = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tmeanDepth += post / (double) path.size();\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (meanDepth != 0.0d) {\n\t\t\t\tuncertainty = meanDepth / ((double) simulationPaths.size());\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (simulationEvaluations != null && !simulationEvaluations.isEmpty() && simulationEvaluations.get(0) instanceof Double) {\n\t\t\tdouble mean = 0.0d;\n\t\t\tdouble sampleVariance = 0.0d;\n\t\t\tfor (V f : simulationEvaluations) {\n\t\t\t\tmean += (Double)f;\n\t\t\t}\n\t\t\tmean /= simulationEvaluations.size();\n\t\t\tfor (V f : simulationEvaluations) {\n\t\t\t\tsampleVariance += ((Double)f - mean) * ((Double)f - mean);\n\t\t\t}\n\t\t\tsampleVariance = Math.sqrt(sampleVariance / (simulationEvaluations.size() - 1));\n\t\t\tif (mean != 0.0d) {\n\t\t\t\tdouble coefficientOfVariation = sampleVariance / mean;\n\t\t\t\tcoefficientOfVariation = Math.max(Math.abs(coefficientOfVariation), 1.0d);\n\t\t\t\tuncertainty *= coefficientOfVariation;\n\t\t\t}\n\t\t}\n\t\treturn uncertainty;\n\t}\n\n}\n" }, { "alpha_fraction": 0.7927590608596802, "alphanum_fraction": 0.8008739352226257, "avg_line_length": 59.69230651855469, "blob_id": "4eac4e4e09ac93a0e71998d11cb5787843cb81e8", "content_id": "cc04361ded141008491973dbfcc1ff6a173cbc40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1602, "license_type": "no_license", "max_line_length": 155, "num_lines": 26, "path": "/JAICore/jaicore-search/test/jaicore/search/algorithms/parallel/parallelexploration/distributed/clustertest/DistributedBestFirstClusterTesterMaster.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "//package jaicore.search.algorithms.parallel.parallelexploration.distributed.clustertest;\r\n//\r\n//import java.nio.file.Path;\r\n//import java.nio.file.Paths;\r\n//import java.util.List;\r\n//\r\n//import jaicore.graphvisualizer.SimpleGraphVisualizationWindow;\r\n//import jaicore.search.algorithms.parallel.parallelexploration.distributed.DistributedOrSearch;\r\n//import jaicore.search.algorithms.parallel.parallelexploration.distributed.FolderBasedDistributedSearchCommunicationLayer;\r\n//import jaicore.search.algorithms.parallel.parallelexploration.distributed.interfaces.DistributedSearchCommunicationLayer;\r\n//import jaicore.search.algorithms.parallel.parallelexploration.distributed.interfaces.SerializableNodeEvaluator;\r\n//\r\n//public class DistributedBestFirstClusterTesterMaster {\r\n//\r\n//\tpublic static void main(String[] args) throws InterruptedException {\r\n//\t\tPath folder = Paths.get(\"Z:/pc2/distsearch/testrsc/comm\");\r\n//\t\tDistributedBestFirstClusterTesterGenerator gen = new DistributedBestFirstClusterTesterGenerator((int) Math.pow(2, 25), 12345678);\r\n//\t\tSerializableNodeEvaluator<TestNode, Integer> evaluator = n -> -1 * n.externalPath().size();\r\n//\t\tDistributedSearchCommunicationLayer<TestNode, String, Integer> communicationLayer = new FolderBasedDistributedSearchCommunicationLayer<>(folder, true);\r\n//\t\tDistributedOrSearch<TestNode, String, Integer> master = new DistributedOrSearch<>(gen, evaluator, communicationLayer);\r\n//\t\tnew SimpleGraphVisualizationWindow<>(master);\r\n//\t\tList<TestNode> solution = master.nextSolution();\r\n//\t\tmaster.cancel();\r\n//\t\tSystem.out.println(solution);\r\n//\t}\r\n//}" }, { "alpha_fraction": 0.7990654110908508, "alphanum_fraction": 0.8130841255187988, "avg_line_length": 24.75, "blob_id": "4811d8b36f6327b7978f7b84d3aa982aa6ad5132", "content_id": "1f4ed52b8d59aca2c86a28c35aac6f6bb5f87c04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 214, "license_type": "no_license", "max_line_length": 68, "num_lines": 8, "path": "/softwareconfiguration/mlplan/src/de/upb/crc901/mlplan/multiclass/wekamlplan/ClassifierFactory.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package de.upb.crc901.mlplan.multiclass.wekamlplan;\r\n\r\nimport hasco.optimizingfactory.BaseFactory;\r\nimport weka.classifiers.Classifier;\r\n\r\npublic interface ClassifierFactory extends BaseFactory<Classifier> {\r\n\r\n}\r\n" }, { "alpha_fraction": 0.5756097435951233, "alphanum_fraction": 0.6048780679702759, "avg_line_length": 19.600000381469727, "blob_id": "acb8229dfe0ebd5a1a8249aa436f36c8459546a6", "content_id": "e9a61ae2bff6daee4d0a20452fc4a3a61e9cadaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 205, "license_type": "no_license", "max_line_length": 35, "num_lines": 10, "path": "/JAICore/jaicore-processes/src/jaicore/processes/W32Errors.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.processes;\n\npublic interface W32Errors {\n\t\n int NO_ERROR = 0;\n int ERROR_INVALID_FUNCTION = 1;\n int ERROR_FILE_NOT_FOUND = 2;\n int ERROR_PATH_NOT_FOUND = 3;\n\n}" }, { "alpha_fraction": 0.7536764740943909, "alphanum_fraction": 0.7536764740943909, "avg_line_length": 19.923076629638672, "blob_id": "6c758b051c09175b7eee5b50fbdce7892672f496", "content_id": "71e14aee5c1e429f35d7ff843fd5f902b1c4646e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 272, "license_type": "no_license", "max_line_length": 82, "num_lines": 13, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/parallel/parallelexploration/distributed/events/NodePassedToCoworkerEvent.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.parallel.parallelexploration.distributed.events;\n\npublic class NodePassedToCoworkerEvent<T> {\n\tprivate final T node;\n\n\tpublic NodePassedToCoworkerEvent(T node) {\n\t\tsuper();\n\t\tthis.node = node;\n\t}\n\n\tpublic T getNode() {\n\t\treturn node;\n\t}}\n" }, { "alpha_fraction": 0.7440670132637024, "alphanum_fraction": 0.7482550144195557, "avg_line_length": 36.375, "blob_id": "1a6e7d1a0abbf9edb1da05c75bdb6ce7f80f517a", "content_id": "dbcbb124d879661a4b467b80cc93eff88e3b5a96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4298, "license_type": "no_license", "max_line_length": 164, "num_lines": 112, "path": "/JAICore/jaicore-search/test/jaicore/search/testproblems/npuzzle/standard/NPuzzleStandardTester.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.testproblems.npuzzle.standard;\r\n\r\nimport static org.junit.Assert.assertNotNull;\r\nimport static org.junit.Assert.assertTrue;\r\n\r\nimport java.util.Iterator;\r\nimport java.util.List;\r\nimport java.util.concurrent.atomic.AtomicInteger;\r\n\r\nimport com.google.common.eventbus.Subscribe;\r\n\r\nimport jaicore.basic.algorithm.AlgorithmEvent;\r\nimport jaicore.basic.algorithm.AlgorithmFinishedEvent;\r\nimport jaicore.basic.algorithm.AlgorithmInitializedEvent;\r\nimport jaicore.graph.IGraphAlgorithmListener;\r\nimport jaicore.graphvisualizer.gui.VisualizationWindow;\r\nimport jaicore.search.algorithms.standard.ORGraphSearchTester;\r\nimport jaicore.search.algorithms.standard.bestfirst.events.EvaluatedSearchSolutionCandidateFoundEvent;\r\nimport jaicore.search.algorithms.standard.bestfirst.events.GraphSearchSolutionCandidateFoundEvent;\r\nimport jaicore.search.core.interfaces.IGraphSearch;\r\nimport jaicore.search.core.interfaces.IGraphSearchFactory;\r\n\r\npublic abstract class NPuzzleStandardTester<I, O, VSearch, ESearch> extends ORGraphSearchTester<NPuzzleProblem, I, O, NPuzzleNode, String, Double, VSearch, ESearch>\r\n\t\timplements IGraphAlgorithmListener<VSearch, ESearch> {\r\n\r\n\tprivate final static int SEED = 0;\r\n\tprivate int max_n = 4;\r\n\tprivate int max_solutions = 100;\r\n\tprivate AtomicInteger seenSolutions = new AtomicInteger(0);\r\n\tprivate boolean showGraphs = false;\r\n\r\n\tprivate IGraphSearch<I, O, NPuzzleNode, String, Double, VSearch, ESearch> getSearch(int n, int seed) {\r\n\t\tIGraphSearchFactory<I, O, NPuzzleNode, String, Double, VSearch, ESearch> factory = getFactory();\r\n\t\tfactory.setProblemInput(new NPuzzleProblem(n, seed), getProblemReducer());\r\n\t\treturn factory.getAlgorithm();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void testThatIteratorReturnsEachPossibleSolution() {\r\n\t\tfor (int n = 3; n <= max_n; n++) {\r\n\t\t\tSystem.out.print(\"Checking first 100 solutions of \" + n + \"-puzzle ... \");\r\n\t\t\tIGraphSearch<I,O,NPuzzleNode, String, Double, VSearch, ESearch> search = getSearch(n, SEED);\r\n\t\t\tassertNotNull(\"The factory has not returned any search object.\", search);\r\n\t\t\tif (showGraphs)\r\n\t\t\t\tnew VisualizationWindow<>(search);\r\n\t\t\tboolean initialized = false;\r\n\t\t\tboolean terminated = false;\r\n\t\t\tint solutions = 0;\r\n\t\t\tIterator<AlgorithmEvent> iterator = search.iterator();\r\n\t\t\tassertNotNull(\"The search algorithm does return NULL as an iterator for itself.\", iterator);\r\n\t\t\twhile (iterator.hasNext()) {\r\n\t\t\t\tAlgorithmEvent e = search.next();\r\n\t\t\t\tassertNotNull(\"The search iterator has returned NULL even though hasNext suggested that more event should come.\", e);\r\n\t\t\t\tif (!initialized) {\r\n\t\t\t\t\tassertTrue(e instanceof AlgorithmInitializedEvent);\r\n\t\t\t\t\tinitialized = true;\r\n\t\t\t\t} else if (e instanceof AlgorithmFinishedEvent) {\r\n\t\t\t\t\tterminated = true;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tassertTrue(!terminated);\r\n\t\t\t\t\tif (e instanceof GraphSearchSolutionCandidateFoundEvent) {\r\n\t\t\t\t\t\tsolutions++;\r\n\t\t\t\t\t\t@SuppressWarnings(\"unchecked\")\r\n\t\t\t\t\t\tList<NPuzzleNode> solutionPath = ((EvaluatedSearchSolutionCandidateFoundEvent<NPuzzleNode, String, Double>) e).getSolutionCandidate().getNodes();\r\n\t\t\t\t\t\tNPuzzleNode finalNode = solutionPath.get(solutionPath.size() - 1);\r\n\t\t\t\t\t\tassertTrue(\"Number of wrong tiles in solution \" + finalNode.toString() + \" is \" + finalNode.getNumberOfWrongTiles(), finalNode.getNumberOfWrongTiles() == 0);\r\n\t\t\t\t\t\tif (solutions >= max_solutions)\r\n\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tSystem.out.println(\"done\");\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t@Subscribe\r\n\tpublic void registerSolution(EvaluatedSearchSolutionCandidateFoundEvent<NPuzzleNode, String, Double> solution) {\r\n\r\n\t\tseenSolutions.incrementAndGet();\r\n\t}\r\n\r\n\tpublic boolean isShowGraphs() {\r\n\t\treturn showGraphs;\r\n\t}\r\n\r\n\tpublic void setShowGraphs(boolean showGraphs) {\r\n\t\tthis.showGraphs = showGraphs;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void testThatAnEventForEachPossibleSolutionIsEmittedInSimpleCall() throws Throwable {\r\n\t\t\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void testThatAnEventForEachPossibleSolutionIsEmittedInParallelizedCall() throws Throwable {\r\n\t\t\r\n\t}\r\n\t\r\n\r\n\r\n\t@Override\r\n\tpublic I getSimpleProblemInputForGeneralTestPurposes() {\r\n\t\treturn getProblemReducer().transform(new NPuzzleProblem(4, 0));\r\n\t}\r\n\r\n\t@Override\r\n\tpublic I getDifficultProblemInputForGeneralTestPurposes() {\r\n\t\treturn getProblemReducer().transform(new NPuzzleProblem(10, 0));\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7194381356239319, "alphanum_fraction": 0.7198177576065063, "avg_line_length": 34.13333511352539, "blob_id": "8fd9d67b55bc82cc4f90d718da069bc7bd43e0a8", "content_id": "b227ec509da9c6329f66c73844fa849aea9c0ca1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2634, "license_type": "no_license", "max_line_length": 142, "num_lines": 75, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/gbf/RandomizedAndOrSearch.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "//package jaicore.search.algorithms.standard.gbf;\n//\n//import java.util.ArrayList;\n//import java.util.Collection;\n//import java.util.LinkedList;\n//import java.util.Queue;\n//\n//import jaicore.graph.Graph;\n//import jaicore.search.algorithms.standard.bestfirst.model.Node;\n//import jaicore.search.algorithms.standard.bestfirst.model.NodeExpansionDescription;\n//import jaicore.search.algorithms.standard.bestfirst.model.NodeType;\n//import jaicore.search.structure.graphgenerator.GoalTester;\n//import jaicore.search.structure.graphgenerator.SingleRootGenerator;\n//import jaicore.search.structure.graphgenerator.SuccessorGenerator;\n//\n///**\n// * A* algorithm implementation using the method design pattern.\n// *\n// * @author Felix Mohr\n// */\n//public class RandomizedAndOrSearch<T,A> extends ANDORGraphSearch<T,A,Integer> {\n//\n//\n//\tprivate Node<T,Integer> root;\n//\tprivate final Queue<Node<T,Integer>> open = new LinkedList<>();\n//\t\n//\tpublic RandomizedAndOrSearch(SingleRootGenerator<T> rootGenerator, SuccessorGenerator<T, A> successorGenerator, GoalTester<T> goalTester) {\n//\t\tsuper(rootGenerator, successorGenerator, goalTester);\n//\t}\n//\n//\t@Override\n//\tprotected Node<T,Integer> initialize() {\n//\t\troot = getOrNode(null, rootGenerator.getRoot(), null);\n//\t\topen.add(root);\n//\t\treturn root;\n//\t}\n//\n//\t@Override\n//\tprotected Graph<Node<T,Integer>> nextSolutionBase() {\n//\t\treturn null;\n//\t}\n//\t\n//\t@Override\n//\tprotected Node<T,Integer> nextNode(Graph<Node<T,Integer>> solutionBase) {\n//\t\treturn open.poll();\n//\t}\n//\n//\t@Override\n//\tprotected Collection<Node<T,Integer>> expand(Node<T,Integer> expanded) {\n//\t\tCollection<NodeExpansionDescription<T, A>> successorNodes = successorGenerator.generateSuccessors(expanded.getPoint());\n//\t\tCollection<Node<T,Integer>> successors = new ArrayList<>();\n//\t\tfor (NodeExpansionDescription<T, A> successorDescription : successorNodes) {\n//\t\t\t\n//\t\t\t/* no reopening of nodes we already know */\n//\t\t\tT successor = successorDescription.getTo();\n//\t\t\tboolean isKnown = ext2int.containsKey(successor);\n//\t\t\tNode<T,Integer> node = null;\n//\t\t\tNodeType type = successorDescription.getTypeOfToNode();\n//\t\t\tif (type == NodeType.AND)\n//\t\t\t\tnode = getAndNode(expanded, successor, successorDescription.getAction());\n//\t\t\tif (type == NodeType.OR)\n//\t\t\t\tnode = getOrNode(expanded, successor, successorDescription.getAction());\n//\t\t\tsuccessors.add(node);\n//\t\t\tif (!isKnown && !goalTester.isGoal(node.getPoint())) {\n//\t\t\t\topen.add(node);\n//\t\t\t}\n//\t\t}\n//\t\treturn successors;\n//\t}\n//\t\n//\t@Override\n//\tprotected int getNumberOfOpenNodesInSolutionBase(Graph<Node<T,Integer>> solutionBase) {\n//\t\treturn open.size();\n//\t}\n//}" }, { "alpha_fraction": 0.792888879776001, "alphanum_fraction": 0.792888879776001, "avg_line_length": 35.5, "blob_id": "c7305f6df9e9fef6b0784fce955dc925d972d8ef", "content_id": "f210ea9d1eba449b17ffe8876177e4655bc265d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1125, "license_type": "no_license", "max_line_length": 133, "num_lines": 30, "path": "/JAICore/jaicore-search/test/jaicore/search/algorithms/standard/random/RandomSearchNQueensTester.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.random;\r\n\r\nimport jaicore.basic.algorithm.AlgorithmProblemTransformer;\r\nimport jaicore.search.core.interfaces.IGraphSearchFactory;\r\nimport jaicore.search.model.probleminputs.GraphSearchInput;\r\nimport jaicore.search.testproblems.nqueens.NQueenGenerator;\r\nimport jaicore.search.testproblems.nqueens.NQueenTester;\r\nimport jaicore.search.testproblems.nqueens.QueenNode;\r\n\r\npublic class RandomSearchNQueensTester extends NQueenTester<GraphSearchInput<QueenNode, String>, Object, QueenNode, String> {\r\n\r\n\t\r\n\r\n\t@Override\r\n\tpublic IGraphSearchFactory<GraphSearchInput<QueenNode, String>, Object, QueenNode, String, Double, QueenNode, String> getFactory() {\r\n\t\treturn new RandomSearchFactory<>();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic AlgorithmProblemTransformer<Integer, GraphSearchInput<QueenNode, String>> getProblemReducer() {\r\n\t\treturn new AlgorithmProblemTransformer<Integer, GraphSearchInput<QueenNode,String>>() {\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic GraphSearchInput<QueenNode, String> transform(Integer problem) {\r\n\t\t\t\treturn new GraphSearchInput<>(new NQueenGenerator(problem));\r\n\t\t\t}\r\n\t\t};\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.7330654263496399, "alphanum_fraction": 0.7385189533233643, "avg_line_length": 43.24675369262695, "blob_id": "d907a87bbd1eb2d4e36e8b1e1d46da4e33acee9b", "content_id": "1efadc1c8c11ce35d929373d6b6e091c5bf2b607", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3484, "license_type": "no_license", "max_line_length": 191, "num_lines": 77, "path": "/JAICore/jaicore-planning/test/jaicore/planning/graphgenerators/CEOCTFDTester.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.graphgenerators;\r\n\r\nimport java.util.Arrays;\r\nimport java.util.Collection;\r\nimport java.util.HashSet;\r\nimport java.util.List;\r\nimport java.util.stream.Collectors;\r\n\r\nimport jaicore.graphvisualizer.gui.VisualizationWindow;\r\nimport org.junit.Assert;\r\nimport org.junit.Before;\r\nimport org.junit.Test;\r\n\r\nimport jaicore.basic.MathExt;\r\nimport jaicore.basic.algorithm.AlgorithmExecutionCanceledException;\r\nimport jaicore.planning.graphgenerators.task.ceoctfd.CEOCTFDGraphGenerator;\r\nimport jaicore.planning.graphgenerators.task.tfd.TFDNode;\r\nimport jaicore.planning.graphgenerators.task.tfd.TFDTooltipGenerator;\r\nimport jaicore.planning.model.ceoc.CEOCAction;\r\nimport jaicore.planning.model.ceoc.CEOCOperation;\r\nimport jaicore.planning.model.task.ceocstn.CEOCSTNPlanningProblem;\r\nimport jaicore.planning.model.task.ceocstn.OCMethod;\r\nimport jaicore.planning.model.task.ceocstn.StandardProblemFactory;\r\nimport jaicore.search.algorithms.standard.astar.AStar;\r\nimport jaicore.search.model.probleminputs.NumberBasedAdditiveTraversalTree;\r\nimport jaicore.search.model.travesaltree.Node;\r\nimport jaicore.search.model.travesaltree.NodeTooltipGenerator;\r\n\r\npublic class CEOCTFDTester {\r\n\r\n\tprivate List<String> classes;\r\n\r\n\t@Before\r\n\tpublic void setClasses() {\r\n\t\tclasses = Arrays.asList(new String[] { \"A\", \"B\", \"C\", \"D\", \"E\" });\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testNestedDichotomy() throws Exception {\r\n\t\tsolveProblemUsingAStar(StandardProblemFactory.getNestedDichotomyCreationProblem(\"root\", classes, true, 1, 1));\r\n\t}\r\n\r\n\tprivate void solveProblemUsingAStar(CEOCSTNPlanningProblem problem) throws InterruptedException, AlgorithmExecutionCanceledException {\r\n\r\n\t\t/* create AStar algorithm to solve the problem */\r\n\t\tSystem.out.print(\"Generate problem ...\");\r\n\t\tCEOCTFDGraphGenerator<CEOCOperation, OCMethod, CEOCAction> generator = new CEOCTFDGraphGenerator<>(problem);\r\n\t\tSystem.out.println(\" done\");\r\n\t\tSystem.out.print(\"Starting Search Process\");\r\n\t\tlong start = System.currentTimeMillis();\r\n\t\tAStar<TFDNode, String> astar = new AStar<TFDNode, String>(new NumberBasedAdditiveTraversalTree<TFDNode, String>(generator, (n1, n2) -> -1 * (Math.random() * 1000), n -> 0.0));\r\n\r\n\t\tnew VisualizationWindow<Node<TFDNode, Double>, String>(astar).setTooltipGenerator(new NodeTooltipGenerator<>(new TFDTooltipGenerator<>()));\r\n\r\n\t\tList<TFDNode> solution = null;\r\n\t\tCollection<List<TFDNode>> solutions = new HashSet<>();\r\n\t\tdo {\r\n\t\t\tsolution = astar.nextSolution().getNodes();\r\n\t\t\tsolutions.add(solution);\r\n\t\t} while (solution != null);\r\n\t\tlong end = System.currentTimeMillis();\r\n\t\tfloat time = (int) Math.round((end - start) / 10.0) / 100f;\r\n\t\tSystem.out.println(\" done\");\r\n\t\tint expectedNumber = (int) MathExt.doubleFactorial((short) (2 * classes.size() - 3));\r\n\t\tSystem.out.println(\"Found \" + solutions.size() + \" solutions in \" + time + \"s. Expected number is \" + expectedNumber);\r\n\t\tAssert.assertTrue(solutions.size() == expectedNumber);\r\n\r\n\t\tSystem.out.println();\r\n\t\tList<String> solutionAsStringList = solutions.iterator().next().stream().filter(n -> n.getAppliedAction() != null).map(n -> n.getAppliedAction().getEncoding()).collect(Collectors.toList());\r\n\t\tSystem.out.println(\"Found solution of length \" + solutionAsStringList.size() + \" after \" + time + \"s.\");\r\n\t\tSystem.out.println(\"Start solution\\n---------------------\");\r\n\t\tfor (String s : solutionAsStringList) {\r\n\t\t\tSystem.out.println(s);\r\n\t\t}\r\n\t\tSystem.out.println(\"End solution. \\n---------------------\");\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6787233948707581, "alphanum_fraction": 0.6787233948707581, "avg_line_length": 18.434782028198242, "blob_id": "bb9a0cddb18d057a215bcc3e3f566c9264f9d4e4", "content_id": "dfcd1741fafa992f1171cbbfbe32f95cdcc45ffd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 470, "license_type": "no_license", "max_line_length": 65, "num_lines": 23, "path": "/JAICore/jaicore-planning/src/jaicore/planning/EvaluatedPlan.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning;\r\n\r\nimport java.util.List;\r\n\r\nimport jaicore.planning.model.core.Action;\r\nimport jaicore.planning.model.core.Plan;\r\n\r\npublic class EvaluatedPlan<A extends Action, V> extends Plan<A> {\r\n\tprivate final V score;\r\n\r\n\tpublic EvaluatedPlan(Plan<A> plan, V score) {\r\n\t\tthis (plan.getActions(), score);\r\n\t}\r\n\t\r\n\tpublic EvaluatedPlan(List<A> plan, V score) {\r\n\t\tsuper(plan);\r\n\t\tthis.score = score;\r\n\t}\r\n\t\r\n\tpublic V getScore() {\r\n\t\treturn score;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6654782891273499, "alphanum_fraction": 0.6690433621406555, "avg_line_length": 23.042856216430664, "blob_id": "3191cc39249c4b39dfbb986d1b845bc4d2d69d83", "content_id": "0e23dc719d91246468b232b56d8a3391fed00d66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1683, "license_type": "no_license", "max_line_length": 109, "num_lines": 70, "path": "/JAICore/jaicore-planning/src/jaicore/planning/model/core/PlanningProblem.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.model.core;\n\nimport jaicore.logic.fol.structure.Monom;\n\npublic class PlanningProblem {\n\n\tprivate final PlanningDomain domain;\n\tprivate final Monom initState, goalState;\n\n\tpublic PlanningProblem(PlanningDomain domain, Monom initState, Monom goalState) {\n\t\tsuper();\n\t\tthis.domain = domain;\n\t\tthis.initState = initState;\n\t\tthis.goalState = goalState;\n\t}\n\n\tpublic PlanningDomain getDomain() {\n\t\treturn domain;\n\t}\n\n\tpublic Monom getInitState() {\n\t\treturn initState;\n\t}\n\n\tpublic Monom getGoalState() {\n\t\treturn goalState;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((domain == null) ? 0 : domain.hashCode());\n\t\tresult = prime * result + ((goalState == null) ? 0 : goalState.hashCode());\n\t\tresult = prime * result + ((initState == null) ? 0 : initState.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tPlanningProblem other = (PlanningProblem) obj;\n\t\tif (domain == null) {\n\t\t\tif (other.domain != null)\n\t\t\t\treturn false;\n\t\t} else if (!domain.equals(other.domain))\n\t\t\treturn false;\n\t\tif (goalState == null) {\n\t\t\tif (other.goalState != null)\n\t\t\t\treturn false;\n\t\t} else if (!goalState.equals(other.goalState))\n\t\t\treturn false;\n\t\tif (initState == null) {\n\t\t\tif (other.initState != null)\n\t\t\t\treturn false;\n\t\t} else if (!initState.equals(other.initState))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"PlanningProblem [domain=\" + domain + \", initState=\" + initState + \", goalState=\" + goalState + \"]\";\n\t}\n}\n" }, { "alpha_fraction": 0.7818659543991089, "alphanum_fraction": 0.7827420234680176, "avg_line_length": 37.694915771484375, "blob_id": "067b9a39f1aea78fad2d188a128e384ca686c55b", "content_id": "f4e4341423353e76e2851b57fe4667194b713640", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2283, "license_type": "no_license", "max_line_length": 169, "num_lines": 59, "path": "/JAICore/jaicore-ml/test/jaicore/ml/MLExperimentTester.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.ml;\n\nimport jaicore.basic.SQLAdapter;\nimport jaicore.experiments.ExperimentDBEntry;\nimport jaicore.experiments.ExperimentRunner;\nimport jaicore.experiments.IExperimentIntermediateResultProcessor;\nimport jaicore.experiments.IExperimentSetConfig;\nimport jaicore.experiments.IExperimentSetEvaluator;\nimport jaicore.ml.evaluation.MulticlassEvaluator;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Random;\n\nimport org.aeonbits.owner.ConfigCache;\n\nimport weka.classifiers.AbstractClassifier;\nimport weka.classifiers.Classifier;\nimport weka.core.Instances;\n\npublic class MLExperimentTester implements IExperimentSetEvaluator {\n\n private final ISpecificMLExperimentConfig config = ConfigCache.getOrCreate(ISpecificMLExperimentConfig.class);\n\n @Override\n public IExperimentSetConfig getConfig() {\n return this.config;\n }\n\n @Override\n public void evaluate(final ExperimentDBEntry experimentEntry, final SQLAdapter adapter, final IExperimentIntermediateResultProcessor processor) throws Exception {\n if (this.config.getDatasetFolder() == null || (!this.config.getDatasetFolder().exists())) {\n throw new IllegalArgumentException(\"config specifies invalid dataset folder \" + this.config.getDatasetFolder());\n }\n Map<String, String> description = experimentEntry.getExperiment().getValuesOfKeyFields();\n Classifier c = AbstractClassifier.forName(description.get(\"classifier\"), null);\n Instances data = new Instances(new BufferedReader(new FileReader(new File(this.config.getDatasetFolder() + File.separator + description.get(\"dataset\") + \".arff\"))));\n data.setClassIndex(data.numAttributes() - 1);\n int seed = Integer.valueOf(description.get(\"seed\"));\n\n System.out.println(c.getClass().getName());\n Map<String, Object> results = new HashMap<>();\n MulticlassEvaluator eval = new MulticlassEvaluator(new Random(seed));\n double loss = eval.getErrorRateForRandomSplit(c, data, .7f);\n\n results.put(\"loss\", loss);\n processor.processResults(results);\n\n }\n\n public static void main(final String[] args) {\n ExperimentRunner runner = new ExperimentRunner(new MLExperimentTester());\n runner.randomlyConductExperiments(true);\n }\n\n}\n" }, { "alpha_fraction": 0.6970964670181274, "alphanum_fraction": 0.7091535329818726, "avg_line_length": 33.964603424072266, "blob_id": "481d180901f5b4f29b2ecd5a6e778ee8a2dd553a", "content_id": "3fa3b72a536ad4499422c2f9b43b1d49b95009db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4064, "license_type": "no_license", "max_line_length": 171, "num_lines": 113, "path": "/softwareconfiguration/mlplan/src/de/upb/crc901/mlplan/multiclasswithreduction/NestedDichotomyUtil.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package de.upb.crc901.mlplan.multiclasswithreduction;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.Collection;\r\nimport java.util.Collections;\r\nimport java.util.HashSet;\r\nimport java.util.Iterator;\r\nimport java.util.List;\r\nimport java.util.Random;\r\n\r\nimport de.upb.crc901.mlplan.multiclass.wekamlplan.weka.model.MLPipeline;\r\nimport jaicore.basic.sets.SetUtil;\r\nimport jaicore.ml.WekaUtil;\r\nimport jaicore.ml.classification.multiclass.reduction.splitters.RPNDSplitter;\r\nimport weka.attributeSelection.InfoGainAttributeEval;\r\nimport weka.attributeSelection.Ranker;\r\nimport weka.classifiers.AbstractClassifier;\r\nimport weka.classifiers.Classifier;\r\nimport weka.core.Instance;\r\nimport weka.core.Instances;\r\n\r\npublic class NestedDichotomyUtil {\r\n\r\n//\tprivate static final Logger logger = LoggerFactory.getLogger(NestedDichotomyUtil.class);\r\n\r\n\tpublic static ClassSplit<String> createGeneralRPNDBasedSplit(Collection<String> classes, Random rand, String classifierName, Instances data) throws InterruptedException {\r\n\t\tif (classes.size() < 2)\r\n\t\t\tthrow new IllegalArgumentException(\"Cannot compute split for less than two classes!\");\r\n\t\ttry {\r\n\t\t\tRPNDSplitter splitter = new RPNDSplitter(rand, new MLPipeline(new Ranker(), new InfoGainAttributeEval(), AbstractClassifier.forName(classifierName, null)));\r\n\t\t\tCollection<Collection<String>> splitAsCollection = null;\r\n\t\t\tsplitAsCollection = splitter.split(data);\r\n\t\t\tIterator<Collection<String>> it = splitAsCollection.iterator();\r\n\t\t\treturn new ClassSplit<>(classes, it.next(), it.next());\r\n\t\t} catch (InterruptedException e) {\r\n\t\t\tthrow e;\r\n\t\t} catch (Exception e) {\r\n\t\t\te.printStackTrace();\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic static ClassSplit<String> createGeneralRPNDBasedSplit(Collection<String> classes, Collection<String> s1, Collection<String> s2, Random rand, String classifierName,\r\n\t\t\tInstances data) {\r\n\t\ttry {\r\n\t\t\tRPNDSplitter splitter = new RPNDSplitter(rand, AbstractClassifier.forName(classifierName, new String[] {}));\r\n\t\t\tCollection<Collection<String>> splitAsCollection = null;\r\n\r\n\t\t\tsplitAsCollection = splitter.split(classes, s1, s2, data);\r\n\t\t\tIterator<Collection<String>> it = splitAsCollection.iterator();\r\n\t\t\treturn new ClassSplit<>(classes, it.next(), it.next());\r\n\t\t} catch (Exception e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\r\n\tpublic static ClassSplit<String> createUnaryRPNDBasedSplit(Collection<String> classes, Random rand, String classifierName, Instances data) {\r\n\r\n\t\t/* 2. if we have a leaf node, abort */\r\n\t\tif (classes.size() == 1)\r\n\t\t\treturn new ClassSplit<>(classes, null, null);\r\n\r\n\t\t/* 3a. otherwise select randomly two classes */\r\n\t\tList<String> copy = new ArrayList<>(classes);\r\n\t\tCollections.shuffle(copy, rand);\r\n\t\tString c1 = copy.get(0);\r\n\t\tString c2 = copy.get(1);\r\n\t\tCollection<String> s1 = new HashSet<>();\r\n\t\ts1.add(c1);\r\n\t\tCollection<String> s2 = new HashSet<>();\r\n\t\ts2.add(c2);\r\n\r\n\t\t/* 3b. and 3c. train binary classifiers for c1 vs c2 */\r\n\t\tInstances reducedData = WekaUtil.mergeClassesOfInstances(data, s1, s2);\r\n\t\tClassifier c = null;\r\n\t\ttry {\r\n\t\t\tc = AbstractClassifier.forName(classifierName, new String[] {});\r\n\t\t} catch (Exception e1) {\r\n\t\t\te1.printStackTrace();\r\n\t\t}\r\n\t\ttry {\r\n\t\t\tc.buildClassifier(reducedData);\r\n\t\t} catch (Exception e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\r\n\t\t/* 3d. insort the remaining classes */\r\n\t\tList<String> remainingClasses = new ArrayList<>(SetUtil.difference(SetUtil.difference(classes, s1), s2));\r\n\t\tint o1 = 0;\r\n\t\tint o2 = 0;\r\n\t\tfor (int i = 0; i < remainingClasses.size(); i++) {\r\n\t\t\tString className = remainingClasses.get(i);\r\n\t\t\tInstances testData = WekaUtil.getInstancesOfClass(data, className);\r\n\t\t\tfor (Instance inst : testData) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tdouble prediction = c.classifyInstance(WekaUtil.getRefactoredInstance(inst));\r\n\t\t\t\t\tif (prediction == 0)\r\n\t\t\t\t\t\to1++;\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\to2++;\r\n\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (o1 > o2)\r\n\t\t\ts1.addAll(remainingClasses);\r\n\t\telse\r\n\t\t\ts2.addAll(remainingClasses);\r\n\t\treturn new ClassSplit<>(classes, s1, s2);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.8181818127632141, "alphanum_fraction": 0.8181818127632141, "avg_line_length": 26.5, "blob_id": "61c0a5ac0814eb5dd6c36747d66a44df6eedf244", "content_id": "7731aa44c299b3a9dd9a34ca04c576a5201e66e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 330, "license_type": "no_license", "max_line_length": 86, "num_lines": 12, "path": "/JAICore/jaicore-planning/src/jaicore/planning/model/conditional/CEPlanningProblem.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.model.conditional;\n\nimport jaicore.logic.fol.structure.Monom;\nimport jaicore.planning.model.core.PlanningProblem;\n\npublic class CEPlanningProblem extends PlanningProblem {\n\n\tpublic CEPlanningProblem(CEPlanningDomain domain, Monom initState, Monom goalState) {\n\t\tsuper(domain, initState, goalState);\n\t}\n\n}\n" }, { "alpha_fraction": 0.8064981698989868, "alphanum_fraction": 0.8064981698989868, "avg_line_length": 49.296295166015625, "blob_id": "1e7d9ba3f0170581c6644100d80f397279c672ce", "content_id": "9943d855efa8ce9a22b0b77f78389d2938d4eb5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1385, "license_type": "no_license", "max_line_length": 235, "num_lines": 27, "path": "/JAICore/jaicore-planning/src/jaicore/planning/algorithms/forwarddecomposition/ForwardDecompositionHTNPlanner.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.algorithms.forwarddecomposition;\r\n\r\nimport jaicore.basic.algorithm.IAlgorithmListener;\r\nimport jaicore.planning.algorithms.GraphSearchBasedHTNPlanningAlgorithm;\r\nimport jaicore.planning.graphgenerators.task.tfd.TFDNode;\r\nimport jaicore.planning.model.core.Action;\r\nimport jaicore.planning.model.core.Operation;\r\nimport jaicore.planning.model.task.IHTNPlanningProblem;\r\nimport jaicore.planning.model.task.stn.Method;\r\nimport jaicore.search.core.interfaces.IGraphSearchFactory;\r\nimport jaicore.search.model.probleminputs.builders.SearchProblemInputBuilder;\r\n\r\n/**\r\n * Hierarchically create an object of type T\r\n * \r\n * @author fmohr\r\n *\r\n * @param <T>\r\n */\r\npublic class ForwardDecompositionHTNPlanner<PO extends Operation, PM extends Method, PA extends Action, I extends IHTNPlanningProblem<PO,PM,PA>, V extends Comparable<V>, ISearch, OSearch, NSearch, ASearch, L extends IAlgorithmListener>\r\n\t\textends GraphSearchBasedHTNPlanningAlgorithm<PA, I, ISearch, OSearch, TFDNode, String, V, NSearch, ASearch, IAlgorithmListener> {\r\n\r\n\tpublic ForwardDecompositionHTNPlanner(I problem, IGraphSearchFactory<ISearch, OSearch, TFDNode, String, V, NSearch, ASearch> searchFactory,\r\n\t\t\tSearchProblemInputBuilder<TFDNode, String, ISearch> searchProblemBuilder) {\r\n\t\tsuper(problem, new ForwardDecompositionReducer<PO,PM,PA,I>(), searchFactory, searchProblemBuilder);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6550094485282898, "alphanum_fraction": 0.6635160446166992, "avg_line_length": 30.117647171020508, "blob_id": "8e8fc27a63d608da2d95d72f091a84f6aebf4851", "content_id": "989d3ca365e844d4db2a4d7b9714981b79cdc5e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2116, "license_type": "no_license", "max_line_length": 141, "num_lines": 68, "path": "/JAICore/jaicore-search/test/jaicore/search/algorithms/standard/rstar/GridWorldRCGGG.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.rstar;\n\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport jaicore.search.core.interfaces.ISolutionEvaluator;\n\nimport java.util.List;\nimport java.util.stream.Collectors;\n\npublic class GridWorldRCGGG {\n\n static GridWorldBasicGraphGenerator graphGenerator;\n static RandomCompletionGammaGraphGenerator<GridWorld> ggg;\n\n\n @BeforeClass\n public static void setUp() {\n graphGenerator = new GridWorldBasicGraphGenerator(0, 0, 15, 15);\n\n ISolutionEvaluator<GridWorld, Double> solutionEvaluator = new ISolutionEvaluator<GridWorld, Double>() {\n @Override\n public Double evaluateSolution(List<GridWorld> solutionPath) throws Exception {\n return null;\n }\n\n @Override\n public boolean doesLastActionAffectScoreOfAnySubsequentSolution(List<GridWorld> partialSolutionPath) {\n return false;\n }\n\n\t\t\t@Override\n\t\t\tpublic void cancel() {\n\t\t\t\t/* nothing to do here */\n\t\t\t}\n };\n\n ggg = new RandomCompletionGammaGraphGenerator(graphGenerator, solutionEvaluator, 5, 42 );\n\n }\n\n @Test\n public void testRandom() {\n RStar<GridWorld, String, Integer> rStar = new RStar<>(ggg, 1, 10, 5);\n rStar.start();\n\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n System.out.println(\"Exception while sleeping.\");\n }\n rStar.interrupt();\n List<GridWorld> solution = rStar.getSolutionPath();\n double costOfSolution = 0;\n for (GridWorld pos : solution)\n costOfSolution += GridWorld.myGrid[pos.getX()][pos.getY()];\n\n List<GammaNode<GridWorld, RStarK>> gammaSolution = rStar.getGammaSolutionPath();\n //List<GridWorld> intermediateHopsChosenByGammaSolution = gammaSolution.stream().map(n -> n.getPoint()).collect(Collectors.toList());\n System.out.println(gammaSolution);\n //System.out.println(intermediateHopsChosenByGammaSolution);\n\n System.out.println(solution);\n System.out.println(costOfSolution);\n\n }\n\n}\n" }, { "alpha_fraction": 0.7140198349952698, "alphanum_fraction": 0.7140198349952698, "avg_line_length": 38.63865661621094, "blob_id": "208722ff0f54a330368db50161ce683bdd26678d", "content_id": "4b830ed44cc46060f6eec929913cd5619894377e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4836, "license_type": "no_license", "max_line_length": 191, "num_lines": 119, "path": "/JAICore/jaicore-planning/src/jaicore/planning/model/core/PlannerUtil.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.model.core;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.Collection;\r\nimport java.util.List;\r\nimport java.util.Map;\r\nimport java.util.stream.Collectors;\r\n\r\nimport jaicore.basic.sets.SetUtil;\r\nimport jaicore.logic.fol.structure.CNFFormula;\r\nimport jaicore.logic.fol.structure.Clause;\r\nimport jaicore.logic.fol.structure.ConstantParam;\r\nimport jaicore.logic.fol.structure.Literal;\r\nimport jaicore.logic.fol.structure.Monom;\r\nimport jaicore.logic.fol.structure.VariableParam;\r\nimport jaicore.planning.model.conditional.CEAction;\r\nimport jaicore.planning.model.conditional.CEOperation;\r\nimport jaicore.planning.model.strips.StripsAction;\r\nimport jaicore.planning.model.strips.StripsOperation;\r\nimport jaicore.planning.model.strips.StripsPlanningDomain;\r\n\r\npublic class PlannerUtil {\r\n\t\r\n\tpublic static Collection<StripsAction> getApplicableActionsInState(Monom state, StripsPlanningDomain domain) {\r\n\t\tCollection<StripsAction> applicableDerivedActions = new ArrayList<>();\r\n\t\tfor (Operation op : domain.getOperations()) {\r\n\t\t\tapplicableDerivedActions.addAll(getPossibleOperationGroundingsForState(state, (StripsOperation)op));\r\n\t\t}\r\n\t\treturn applicableDerivedActions;\r\n\t}\r\n\t\r\n\tpublic static Collection<StripsAction> getPossibleOperationGroundingsForState(Monom state, StripsOperation operation) {\r\n\t\tCollection<StripsAction> applicableDerivedActions = new ArrayList<>();\r\n\t\t\r\n\t\t/* implement groundings here */\r\n\t\ttry {\r\n\t\t\tfor (Map<VariableParam,ConstantParam> grounding: SetUtil.allTotalMappings(operation.getParams(), state.getConstantParams())) {\r\n\t\t\t\tMonom precondition = new Monom(operation.getPrecondition(), grounding);\r\n\t\t\t\tList<Literal> positiveLiterals = precondition.stream().filter(l -> l.isPositive()).collect(Collectors.toList());\r\n\t\t\t\tList<Literal> negativeLiterals = precondition.stream().filter(l -> l.isNegated()).map(l -> l.clone().toggleNegation()).collect(Collectors.toList());\r\n\t\t\t\tif (state.containsAll(positiveLiterals) && SetUtil.intersection(state, negativeLiterals).isEmpty())\r\n\t\t\t\t\tapplicableDerivedActions.add(new StripsAction(operation, grounding));\r\n\t\t\t}\r\n\t\t} catch (InterruptedException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t\t\r\n\t\treturn applicableDerivedActions;\r\n\t}\r\n\t\r\n\r\n\tpublic static void updateState(Monom state, Action appliedAction) {\r\n\r\n\t\t// assert state.containsAll(appliedAction.getPrecondition().stream().filter(lit -> lit.isPositive()).collect(Collectors.toList())) && SetUtil.disjoint(state,\r\n\t\t// appliedAction.getPrecondition().stream().filter(lit -> lit.isNegated()).collect(Collectors.toList())) : (\"Action \" + appliedAction + \" is supposed to be aplpicable in state \" + state + \"\r\n\t\t// but it is not!\");\r\n\t\t/* apply effects of action (STRIPS) */\r\n\t\tif (appliedAction.getOperation() instanceof StripsOperation) {\r\n\t\t\tAction a = new StripsAction((StripsOperation) appliedAction.getOperation(), appliedAction.getGrounding());\r\n\t\t\tstate.removeAll(((StripsAction) a).getDeleteList());\r\n\t\t\tstate.addAll(((StripsAction) a).getAddList());\r\n\t\t}\r\n\r\n\t\t/* apply effects of action (ConditionalEffect operations) */\r\n\t\telse if (appliedAction.getOperation() instanceof CEOperation) {\r\n\t\t\tCEAction a = new CEAction((CEOperation) appliedAction.getOperation(), appliedAction.getGrounding());\r\n\t\t\tMap<CNFFormula, Monom> addLists = a.getAddLists();\r\n\r\n\t\t\t/* determine literals to remove */\r\n\t\t\tMap<CNFFormula, Monom> deleteLists = a.getDeleteLists();\r\n\t\t\tCollection<Literal> toRemove = new ArrayList<>();\r\n\t\t\tfor (CNFFormula condition : deleteLists.keySet()) {\r\n\t\t\t\tif (condition.entailedBy(state)) {\r\n\t\t\t\t\ttoRemove.addAll(deleteLists.get(condition));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/* determine literals to add */\r\n\t\t\tCollection<Literal> toAdd = new ArrayList<>();\r\n\t\t\tfor (CNFFormula condition : addLists.keySet()) {\r\n\t\t\t\t\r\n\t\t\t\t/* evaluate interpreted predicates */\r\n\t\t\t\tCNFFormula modifiedCondition = new CNFFormula();\r\n\t\t\t\tboolean conditionIsSatisfiable = true;\r\n\t\t\t\tfor (Clause c : condition) {\r\n\t\t\t\t\tClause modifiedClause = new Clause();\r\n\t\t\t\t\tboolean clauseContainsTrue = false;\r\n\t\t\t\t\tfor (Literal l : c) {\r\n\t\t\t\t\t\tmodifiedClause.add(l);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t/* if the clause is not empty, add it to the condition */\r\n\t\t\t\t\t\tif (!clauseContainsTrue) {\r\n\t\t\t\t\t\t\tif (!modifiedClause.isEmpty())\r\n\t\t\t\t\t\t\t\tmodifiedCondition.add(modifiedClause);\r\n\t\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t\tconditionIsSatisfiable = false;\r\n\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (conditionIsSatisfiable && modifiedCondition.entailedBy(state)) {\r\n\t\t\t\t\ttoAdd.addAll(addLists.get(condition));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/* now conduct update */\r\n\t\t\tstate.removeAll(toRemove);\r\n\t\t\tstate.addAll(toAdd);\r\n\t\t\t\r\n\t\t} else {\r\n\t\t\tSystem.err.println(\"No support for operations of class \" + appliedAction.getOperation().getClass());\r\n\t\t}\r\n\t}\r\n\r\n\tpublic static void main(String[] args) {\r\n\t\tSystem.out.println(\"NON-PRIMITIVE!\");\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6123157739639282, "alphanum_fraction": 0.6135016083717346, "avg_line_length": 43.217227935791016, "blob_id": "65823fc4263969a6bd891c3821754ef6629b08c8", "content_id": "72217fd6c8f3fe925716065d97f8f56b0ad0d89d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 11807, "license_type": "no_license", "max_line_length": 179, "num_lines": 267, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/rstar/RandomCompletionGammaGraphGenerator.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.rstar;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Random;\n\nimport jaicore.concurrent.TimeoutTimer;\nimport jaicore.search.algorithms.parallel.parallelexploration.distributed.interfaces.SerializableGraphGenerator;\nimport jaicore.search.algorithms.standard.bestfirst.nodeevaluation.RandomCompletionBasedNodeEvaluator;\nimport jaicore.search.core.interfaces.GraphGenerator;\nimport jaicore.search.core.interfaces.ISolutionEvaluator;\nimport jaicore.search.model.travesaltree.Node;\nimport jaicore.search.model.travesaltree.NodeExpansionDescription;\nimport jaicore.search.structure.graphgenerator.GoalTester;\nimport jaicore.search.structure.graphgenerator.MultipleRootGenerator;\nimport jaicore.search.structure.graphgenerator.NodeGoalTester;\nimport jaicore.search.structure.graphgenerator.RootGenerator;\nimport jaicore.search.structure.graphgenerator.SingleRootGenerator;\nimport jaicore.search.structure.graphgenerator.SingleSuccessorGenerator;\n\npublic class RandomCompletionGammaGraphGenerator<T> implements GammaGraphGenerator<T, Integer> {\n\n // TODO: Warum werden nur 1 bis 2 successors generiert\n // TODO: Kine random completion für goal nodes starten. Sondern da den evaluator nutzen (wieso macht RandomCompletionEvaluator das nicht??).\n\n private final GraphGenerator<T, String> graphGenerator;\n private final int samples;\n private final int seed;\n\n private final HashMap<GammaNode, GammaNode> alreadyGeneratedStates = new HashMap<>();\n private final HashMap<T, HashMap<T, List<Node<T, String>>>> computedPaths = new HashMap<>();\n\n private final RootGenerator<GammaNode<T,RStarK>> gammaRootGenerator;\n private final NodeGoalTester<T> gammaGoalTester;\n private final RandomCompletionBasedNodeEvaluator<T, Double> randomCompletionEvaluator;\n private final ISolutionEvaluator<T, Double> solutionEvaluator;\n\n /* Timeout stuff for Random Completions. */\n private int timeoutForComputationOfH = 1000;\n private TimeoutTimer.TimeoutSubmitter timeoutSubmitter;\n\n /**\n *\n * @param graphGenerator\n * @param solutionEvaluator for RandomCompletionGenerator\n * @param samples\n * @param seed\n */\n public RandomCompletionGammaGraphGenerator(SerializableGraphGenerator<T, String> graphGenerator, ISolutionEvaluator<T, Double> solutionEvaluator, int samples, int seed) {\n this.graphGenerator = graphGenerator;\n this.samples = samples;\n this.seed = seed;\n\n /**\n * Generate Gamma roots from root states and create GammaRootGenerators with these.\n */\n RootGenerator<T> rootGenerator = graphGenerator.getRootGenerator();\n\n if (rootGenerator instanceof MultipleRootGenerator) {\n // Create list from multiple roots.\n ArrayList<GammaNode<T,RStarK>> gammaRoots = new ArrayList<>();\n for (T root : ((MultipleRootGenerator<T>) rootGenerator).getRoots()) {\n GammaNode<T,RStarK> gammaRoot = new GammaNode<T, RStarK>(root);\n gammaRoots.add(gammaRoot);\n alreadyGeneratedStates.put(gammaRoot, gammaRoot);\n }\n // And return this list in the Gamma Root generator.\n gammaRootGenerator = new MultipleRootGenerator<GammaNode<T, RStarK>>() {\n @Override\n public Collection<GammaNode<T, RStarK>> getRoots() {\n return gammaRoots;\n }\n };\n } else {\n assert rootGenerator instanceof SingleRootGenerator : \"Only MultipleRootGenerator or SingleRootGenerators allowed.\";\n\n // Create Gamma root from single root.\n T root = ((SingleRootGenerator<T>) rootGenerator).getRoot();\n GammaNode<T,RStarK> gammaRoot = new GammaNode<>(root);\n alreadyGeneratedStates.put(gammaRoot, gammaRoot);\n // And return this root in the Gamma Root generator.\n gammaRootGenerator = new SingleRootGenerator<GammaNode<T, RStarK>>() {\n @Override\n public GammaNode<T, RStarK> getRoot() {\n return gammaRoot;\n }\n };\n }\n\n /**\n * Just take the goalTester (but only if its a NodeGoalTester).\n */\n GoalTester<T> goalTester = graphGenerator.getGoalTester();\n assert goalTester instanceof NodeGoalTester : \"RStar only supports NodeGoalTesters.\";\n gammaGoalTester = (NodeGoalTester)goalTester;\n\n this.solutionEvaluator = solutionEvaluator;\n randomCompletionEvaluator = new RandomCompletionBasedNodeEvaluator<>(new Random(seed), samples, solutionEvaluator);\n randomCompletionEvaluator.setGenerator(graphGenerator);\n }\n\n @Override\n public RootGenerator<GammaNode<T, RStarK>> getRootGenerator() {\n return gammaRootGenerator;\n }\n\n private void savePathComputation(T from, T to, List<Node<T, String>> path) {\n // Create new HashMap at first call for the 2from\" state.\n if (!computedPaths.containsKey(from)) {\n computedPaths.put(from, new HashMap<T, List<Node<T, String>>>());\n }\n computedPaths.get(from).put(to, path);\n }\n\n\n @Override\n public Collection<GammaNode<T, RStarK>> generateRandomSuccessors(GammaNode<T, RStarK> n, int K, Integer delta) throws IllegalArgumentException, InterruptedException {\n T s = n.getPoint();\n\n // The successors for this node have already been computed.\n if (computedPaths.containsKey(s)) {\n throw new IllegalArgumentException(\"Generate sucessors twice for the same node: \" + n);\n }\n // Never generate successors for a node goal.\n if (isGoal(n.getPoint())) {\n throw new IllegalArgumentException(\"The given node is a goal node. Can not generate successors for a goal node.\");\n }\n\n Collection<GammaNode<T,RStarK>> gammaSuccessors = new HashSet<>();\n\n\n\n Node<T, String> parent;\n T currentState;\n Node<T, String> currentNode;\n\n if (!isGoal(s)) {\n for (int k = 0; k < K; k++) {\n // Generate successor in depth delta.\n List<Node<T, String>> path = new ArrayList<>(K);\n parent = null;\n currentState = s;\n currentNode = new Node(parent, currentState);\n path.add(currentNode);\n for (int i = 0; i < delta; i++) {\n if (!gammaGoalTester.isGoal(currentState)) {\n\n if (graphGenerator.getSuccessorGenerator() instanceof SingleSuccessorGenerator) {\n int random = new Random().nextInt(Integer.MAX_VALUE);\n NodeExpansionDescription<T, String> succ = ((SingleSuccessorGenerator) graphGenerator.getSuccessorGenerator()).generateSuccessor(currentState, random);\n if (succ == null) {\n throw new IllegalStateException(\"SingleSucessorGenerator generated no successor for \" + currentState.toString());\n }\n currentState = succ.getTo();\n parent = currentNode;\n currentNode = new Node<>(parent, currentState);\n } else {\n List<NodeExpansionDescription<T, String>> succ = graphGenerator.getSuccessorGenerator().generateSuccessors(currentState);\n if (succ.size() == 0) {\n boolean goal = gammaGoalTester.isGoal(currentState);\n throw new IllegalStateException(\"SuccessorGenerator generated no successor for \" + currentState.toString());\n }\n int random = new Random().nextInt(succ.size());\n currentState = succ.get(random).getTo();\n parent = currentNode;\n currentNode = new Node<>(parent, currentState);\n }\n path.add(currentNode);\n }\n }\n // System.out.println(String.format(\"k=%d, Current node = %s, path=%s\", k, currentNode, path));\n // Save path in computed paths.\n savePathComputation(s, currentState, path);\n // Create gamma successor and add it, or the previously generate equal gamma node\n // to the list of successors.\n GammaNode<T, RStarK> gammaSucc = new GammaNode<>(currentState);\n if (alreadyGeneratedStates.containsKey(gammaSucc)) {\n // Already generated before. Take this gamma node instead of the newly generated.\n gammaSucc = alreadyGeneratedStates.get(gammaSucc);\n } else {\n alreadyGeneratedStates.put(gammaSucc, gammaSucc);\n }\n // TODO: Since this is a set, there will possible not K successors generated.\n\n gammaSuccessors.add(gammaSucc);\n }\n }else {\n gammaSuccessors = null;\n }\n // System.out.println(\"Generated successors \" + gammaSuccessors.size() + \"is goal = \" + isGoal(n.getPoint()));\n return gammaSuccessors;\n }\n\n @Override\n public PathAndCost computePath(GammaNode<T, RStarK> from, GammaNode<T, RStarK> to) {\n List<Node<T, String>> path = computedPaths.get(from.getPoint()).get(to.getPoint());\n return new PathAndCost(path, h(from, to));\n }\n\n\n private boolean isGoal(T n) {\n return ((NodeGoalTester)getGoalTester()).isGoal(n);\n }\n\n private double h(GammaNode<T, RStarK> n) {\n if (n.getAnnotation(\"h\") != null) {\n return (Double) n.getAnnotation(\"h\");\n } else {\n double h = Double.MAX_VALUE;\n if (isGoal(n.getPoint())) {\n try {\n h = solutionEvaluator.evaluateSolution(n.externalPath());\n } catch (Exception e) {\n e.printStackTrace();\n }\n } else {\n h = Double.MAX_VALUE;\n try {\n h = randomCompletionEvaluator.f(n);\n } catch (Throwable w) {\n System.err.println(\"Error while trying to compute random completion evaluation.\" + n + \"is goal = \" + isGoal(n.getPoint()));\n w.printStackTrace();\n }\n }\n // System.out.println(\"Evaluated node \" + n + \", h= \" + h);\n return h;\n }\n }\n\n @Override\n public double h(GammaNode<T, RStarK> n1, GammaNode<T, RStarK> n2){\n return h(n1)-h(n2);\n }\n\n @Override\n public double hToGoal(GammaNode<T, RStarK> from) {\n return h(from);\n }\n\n @Override\n public double hFromStart(GammaNode<T, RStarK> to) {\n\n // Calculate minimum h for all start states\n double h_start = Double.MAX_VALUE;\n\n if (gammaRootGenerator instanceof SingleRootGenerator) {\n h_start = h(((SingleRootGenerator<GammaNode<T,RStarK>>) gammaRootGenerator).getRoot());\n } else {\n assert gammaRootGenerator instanceof MultipleRootGenerator : \"Only MultipleRootGenerator or SingleRootGenerators allowed.\";\n for (GammaNode<T,RStarK> n : ((MultipleRootGenerator<GammaNode<T,RStarK>>) gammaRootGenerator).getRoots()) {\n if (h(n) < h_start) {\n h_start = h(n);\n }\n }\n }\n\n return h_start;\n }\n\n @Override\n public GoalTester<T> getGoalTester() {\n return graphGenerator.getGoalTester();\n }\n}\n" }, { "alpha_fraction": 0.6109721064567566, "alphanum_fraction": 0.620019257068634, "avg_line_length": 35.328670501708984, "blob_id": "5fad32bf0128905615450099914fafcc78abad80", "content_id": "fcb53c03291bc8389c016bd9e1648ad2de512e40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5195, "license_type": "no_license", "max_line_length": 134, "num_lines": 143, "path": "/JAICore/jaicore-search/test/jaicore/search/algorithms/standard/rstar/GridWorldGammaGraphGenerator.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.rstar;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Random;\n\nimport jaicore.search.algorithms.standard.bestfirst.nodeevaluation.INodeEvaluator;\nimport jaicore.search.core.interfaces.GraphGenerator;\nimport jaicore.search.model.travesaltree.Node;\nimport jaicore.search.model.travesaltree.NodeExpansionDescription;\nimport jaicore.search.model.travesaltree.NodeType;\nimport jaicore.search.structure.graphgenerator.GoalTester;\nimport jaicore.search.structure.graphgenerator.NodeGoalTester;\nimport jaicore.search.structure.graphgenerator.RootGenerator;\nimport jaicore.search.structure.graphgenerator.SingleRootGenerator;\nimport jaicore.search.structure.graphgenerator.SuccessorGenerator;\n\npublic class GridWorldGammaGraphGenerator implements GammaGraphGenerator<GridWorld, Integer> {\n\n GammaNode<GridWorld, RStarK> nstart;\n GammaNode<GridWorld, RStarK> ngoal;\n// GraphGenerator<GridWorld, Integer> gg;\n HashMap<GammaNode, GammaNode> alreadyGeneratedStates = new HashMap<>();\n\n public GridWorldGammaGraphGenerator() {\n nstart = new GammaNode<>(new GridWorld(0, 0));\n ngoal = new GammaNode<>(new GridWorld(15, 15));\n\n alreadyGeneratedStates.put(nstart, nstart);\n alreadyGeneratedStates.put(ngoal, ngoal);\n }\n\n @Override\n public RootGenerator<GammaNode<GridWorld, RStarK>> getRootGenerator() {\n return new SingleRootGenerator<GammaNode<GridWorld, RStarK>>() {\n @Override\n public GammaNode<GridWorld, RStarK> getRoot() {\n return nstart;\n }\n };\n }\n\n @Override\n public Collection<GammaNode<GridWorld, RStarK>> generateRandomSuccessors(GammaNode<GridWorld, RStarK> n, int K, Integer delta) {\n // Use hash set to assure that no state will be added twice to the successors.\n HashSet<GammaNode<GridWorld, RStarK>> succ = new HashSet<>();\n\n Random r = new Random();\n\n int posx = n.getPoint().getX();\n int posy = n.getPoint().getY();\n\n /**\n * Bounds for moving in x-direction and y-direction.\n * Assures that the state is always within [0,15]x[0,15].\n */\n int dx_min = posx < delta ? -posx : -delta;\n int dx_max = 15-posx < delta ? 15-posx : delta;\n\n int dy_min = posy < delta ? -posy : -delta;\n int dy_max = 15-posy < delta ? 15-posy : delta;\n\n for(int i = 0; i < K; i++) {\n int dx = r.nextInt(dx_max + 1 - dx_min) + dx_min;\n int dy = r.nextInt(dy_max + 1 - dy_min) + dy_min;\n\n // Regenerate successor if dx and dx are zero (force moving).\n while (dx == 0 && dy == 0) {\n dx = r.nextInt(dx_max + 1 - dx_min) + dx_min;\n dy = r.nextInt(dy_max + 1 - dy_min) + dy_min;\n }\n\n assert posx + dx >= 0 || posx + dx <= 15 || posy + dy >= 0 || posy + dy <= 15 :\n String.format(\"Calc wrong: dx=%d, dy=%d, posx=%d, posy=%d\", dx, dy, posx, posy);\n\n\n\n /**\n * If this state (x,y) has already been generated, use the reference of the\n * first generation of this state.\n * If its the goal state, dont add it twice.\n */\n GammaNode<GridWorld, RStarK> g = new GammaNode<>(new GridWorld(posx + dx, posy + dy));\n if (alreadyGeneratedStates.containsKey(g)) {\n succ.add(alreadyGeneratedStates.get(g));\n } else {\n alreadyGeneratedStates.put(g, g);\n succ.add(g);\n }\n }\n\n /**\n * If the goal state is within distance delta, add it to list of successors.\n */\n if ((15-posx <= delta) && (15-posy<=delta)) {\n succ.add(ngoal);\n }\n\n return succ;\n }\n\n @Override\n public PathAndCost computePath(GammaNode<GridWorld, RStarK> start, GammaNode<GridWorld, RStarK> end) throws InterruptedException {\n\n SimpleAStarGraphSearch<GridWorld, String> astar = new SimpleAStarGraphSearch<GridWorld, String>(\n new GridWorldBasicGraphGenerator(start.getPoint(), end.getPoint()),\n (n1, n2)->GridWorld.myGrid[n2.getPoint().getX()][n2.getPoint().getY()],\n new GridWorldHeuristic(end.getPoint()));\n\n PathAndCost pac = astar.solution();\n return pac;\n\n }\n\n @Override\n public double h(GammaNode<GridWorld, RStarK> n1, GammaNode<GridWorld, RStarK> n2) {\n return Math.abs(n1.getPoint().getX() - n2.getPoint().getX()) + Math.abs(n1.getPoint().getY() - n2.getPoint().getY());\n }\n\n @Override\n public double hFromStart(GammaNode<GridWorld, RStarK> to) {\n return h(nstart, to);\n }\n\n @Override\n public double hToGoal(GammaNode<GridWorld, RStarK> from) {\n return h(from, ngoal);\n }\n\n @Override\n public GoalTester<GridWorld> getGoalTester() {\n return new NodeGoalTester<GridWorld>() {\n @Override\n public boolean isGoal(GridWorld node) {\n return node.equals(ngoal.getPoint());\n }\n };\n }\n\n}\n" }, { "alpha_fraction": 0.7221171855926514, "alphanum_fraction": 0.7262129783630371, "avg_line_length": 33.266666412353516, "blob_id": "28baae9383406984bf6b4098e2f2970251d2b0c5", "content_id": "04b7cd85756eafc1a16b4181beb1bbe3ea77872f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3174, "license_type": "no_license", "max_line_length": 172, "num_lines": 90, "path": "/JAICore/jaicore-search/test/jaicore/search/testproblems/enhancedttsp/EnhancedTTSPNode.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.testproblems.enhancedttsp;\r\n\r\nimport it.unimi.dsi.fastutil.shorts.ShortList;\r\n\r\npublic class EnhancedTTSPNode {\r\n\tprivate final short curLocation;\r\n\tprivate final ShortList curTour;\r\n\tprivate final double time;\r\n\tprivate final double timeTraveledSinceLastShortBreak;\r\n\tprivate final double timeTraveledSinceLastLongBreak;\r\n\r\n\tpublic EnhancedTTSPNode(short curLocation, ShortList curTour, double time, double timeTraveledSinceLastShortBreak, double timeTraveledSinceLastLongBreak) {\r\n\t\tsuper();\r\n\t\tthis.curLocation = curLocation;\r\n\t\tthis.curTour = curTour;\r\n\t\tassert time >= 0 : \"Cannot create TTSP node with negative time\";\r\n\t\tassert timeTraveledSinceLastShortBreak >= 0 : \"Cannot create TTSP node with negative time since last short break\";\r\n\t\tassert timeTraveledSinceLastLongBreak >= 0 : \"Cannot create TTSP node with negative time since last long break\";\r\n\t\tthis.time = time;\r\n\t\tthis.timeTraveledSinceLastShortBreak = timeTraveledSinceLastShortBreak;\r\n\t\tthis.timeTraveledSinceLastLongBreak = timeTraveledSinceLastLongBreak;\r\n\t}\r\n\r\n\tpublic short getCurLocation() {\r\n\t\treturn curLocation;\r\n\t}\r\n\r\n\tpublic double getTime() {\r\n\t\treturn time;\r\n\t}\r\n\r\n\tpublic double getTimeTraveledSinceLastShortBreak() {\r\n\t\treturn timeTraveledSinceLastShortBreak;\r\n\t}\r\n\r\n\tpublic double getTimeTraveledSinceLastLongBreak() {\r\n\t\treturn timeTraveledSinceLastLongBreak;\r\n\t}\r\n\r\n\tpublic ShortList getCurTour() {\r\n\t\treturn curTour;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + curLocation;\r\n\t\tresult = prime * result + ((curTour == null) ? 0 : curTour.hashCode());\r\n\t\tlong temp;\r\n\t\ttemp = Double.doubleToLongBits(time);\r\n\t\tresult = prime * result + (int) (temp ^ (temp >>> 32));\r\n\t\ttemp = Double.doubleToLongBits(timeTraveledSinceLastLongBreak);\r\n\t\tresult = prime * result + (int) (temp ^ (temp >>> 32));\r\n\t\ttemp = Double.doubleToLongBits(timeTraveledSinceLastShortBreak);\r\n\t\tresult = prime * result + (int) (temp ^ (temp >>> 32));\r\n\t\treturn result;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean equals(Object obj) {\r\n\t\tif (this == obj)\r\n\t\t\treturn true;\r\n\t\tif (obj == null)\r\n\t\t\treturn false;\r\n\t\tif (getClass() != obj.getClass())\r\n\t\t\treturn false;\r\n\t\tEnhancedTTSPNode other = (EnhancedTTSPNode) obj;\r\n\t\tif (curLocation != other.curLocation)\r\n\t\t\treturn false;\r\n\t\tif (curTour == null) {\r\n\t\t\tif (other.curTour != null)\r\n\t\t\t\treturn false;\r\n\t\t} else if (!curTour.equals(other.curTour))\r\n\t\t\treturn false;\r\n\t\tif (Double.doubleToLongBits(time) != Double.doubleToLongBits(other.time))\r\n\t\t\treturn false;\r\n\t\tif (Double.doubleToLongBits(timeTraveledSinceLastLongBreak) != Double.doubleToLongBits(other.timeTraveledSinceLastLongBreak))\r\n\t\t\treturn false;\r\n\t\tif (Double.doubleToLongBits(timeTraveledSinceLastShortBreak) != Double.doubleToLongBits(other.timeTraveledSinceLastShortBreak))\r\n\t\t\treturn false;\r\n\t\treturn true;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\treturn \"EnhancedTTSPNode [curLocation=\" + curLocation + \", curTour=\" + curTour + \", time=\" + time + \", timeTraveledSinceLastShortBreak=\" + timeTraveledSinceLastShortBreak\r\n\t\t\t\t+ \", timeTraveledSinceLastLongBreak=\" + timeTraveledSinceLastLongBreak + \"]\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7199488282203674, "alphanum_fraction": 0.7225064039230347, "avg_line_length": 34.54545593261719, "blob_id": "e97f0f78324ac7e9dd1f92cb9048cd17b6192787", "content_id": "159cb01517e9bf965f6009aa12012d38a1790e19", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 782, "license_type": "no_license", "max_line_length": 118, "num_lines": 22, "path": "/JAICore/jaicore-planning/test/jaicore/planning/task/CEOCSTNFactoryTest.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.task;\n\nimport java.util.Arrays;\nimport java.util.Collection;\n\nimport org.junit.Test;\n\nimport jaicore.planning.model.task.ceocstn.CEOCSTNPlanningProblem;\nimport jaicore.planning.model.task.ceocstn.StandardProblemFactory;\n\npublic class CEOCSTNFactoryTest {\n\n\t@Test\n\tpublic void test() {\n\t\tCollection<String> init = Arrays.asList(new String[] {\"A\", \"B\", \"C\", \"D\"});\n\t\tCEOCSTNPlanningProblem problem = StandardProblemFactory.getNestedDichotomyCreationProblem(\"root\", init, true, 0, 0);\n\t\tSystem.out.println(\"Methods\\n---------------\");\n\t\tproblem.getDomain().getMethods().stream().forEach(m -> System.out.println(m));\n\t\tSystem.out.println(\"\\nOperations\\n---------------\");\n\t\tproblem.getDomain().getOperations().stream().forEach(o -> System.out.println(o));\n\t}\n}\n" }, { "alpha_fraction": 0.8657718300819397, "alphanum_fraction": 0.8657718300819397, "avg_line_length": 65.7272720336914, "blob_id": "e63665bf941e8846f652e46491ef0e59b20dbd62", "content_id": "9b516bb78315b54326473cc5de1cf09af6fa54e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1490, "license_type": "no_license", "max_line_length": 237, "num_lines": 22, "path": "/softwareconfiguration/hasco/src/hasco/variants/forwarddecomposition/HASCOViaFDAndBestFirstWithRandomCompletions.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package hasco.variants.forwarddecomposition;\r\n\r\nimport java.util.function.Predicate;\r\n\r\nimport hasco.core.RefinementConfiguredSoftwareConfigurationProblem;\r\nimport jaicore.planning.graphgenerators.task.tfd.TFDNode;\r\nimport jaicore.search.algorithms.standard.bestfirst.nodeevaluation.INodeEvaluator;\r\nimport jaicore.search.problemtransformers.GraphSearchProblemInputToGeneralEvaluatedTraversalTreeViaRDFS;\r\n\r\npublic class HASCOViaFDAndBestFirstWithRandomCompletions<V extends Comparable<V>> extends HASCOViaFDAndBestFirst<V> {\r\n\r\n\tpublic HASCOViaFDAndBestFirstWithRandomCompletions(RefinementConfiguredSoftwareConfigurationProblem<V> configurationProblem, int numSamples, int seed, int timeoutForSingleCompletionEvaluationInMS,\r\n\t\t\tint timeoutForNodeEvaluationInMS) {\r\n\t\tthis(configurationProblem, null, numSamples, seed, timeoutForSingleCompletionEvaluationInMS, timeoutForNodeEvaluationInMS, n -> null);\r\n\t}\r\n\r\n\tpublic HASCOViaFDAndBestFirstWithRandomCompletions(RefinementConfiguredSoftwareConfigurationProblem<V> configurationProblem, Predicate<TFDNode> prioritingPredicate, int numSamples, int seed, int timeoutForSingleCompletionEvaluationInMS,\r\n\t\t\tint timeoutForNodeEvaluationInMS, INodeEvaluator<TFDNode, V> preferredNodeEvaluator) {\r\n\t\tsuper(configurationProblem, new GraphSearchProblemInputToGeneralEvaluatedTraversalTreeViaRDFS<>(preferredNodeEvaluator, prioritingPredicate, seed, numSamples,\r\n\t\t\t\ttimeoutForSingleCompletionEvaluationInMS, timeoutForNodeEvaluationInMS));\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6697187423706055, "alphanum_fraction": 0.6716808080673218, "avg_line_length": 27.403846740722656, "blob_id": "b6a87505340c9a83120ae307620f8062dc7d6370", "content_id": "1e7cc7d62f58adbe9908d1d54b3dbd9c0a8f239a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1529, "license_type": "no_license", "max_line_length": 131, "num_lines": 52, "path": "/JAICore/jaicore-search/src/jaicore/search/model/probleminputs/NumberBasedAdditiveTraversalTree.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.model.probleminputs;\r\n\r\nimport java.util.Iterator;\r\nimport java.util.List;\r\n\r\nimport jaicore.search.algorithms.standard.bestfirst.nodeevaluation.INodeEvaluator;\r\nimport jaicore.search.core.interfaces.GraphGenerator;\r\nimport jaicore.search.model.travesaltree.Node;\r\n\r\npublic class NumberBasedAdditiveTraversalTree<N,A> extends GeneralEvaluatedTraversalTree<N, A, Double> {\r\n\r\n\tpublic interface EdgeCostComputer<N> {\r\n\t\tpublic double g(Node<N,?> from, Node<N,?> to);\r\n\t}\r\n\t\r\n\tprivate static class FComputer<N> implements INodeEvaluator<N,Double> {\r\n\r\n\t\tprivate final EdgeCostComputer<N> g;\r\n\t\tprivate final INodeEvaluator<N,Double> h;\r\n\r\n\t\tpublic FComputer(EdgeCostComputer<N> g, INodeEvaluator<N,Double> h) {\r\n\t\t\tsuper();\r\n\t\t\tthis.g = g;\r\n\t\t\tthis.h = h;\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic Double f(Node<N,?> node) throws Exception {\r\n\t\t\tList<?> path = node.path();\r\n\t\t\tint depth = path.size() - 1;\r\n\t\t\tdouble pathCost = 0;\r\n\t\t\tdouble heuristic = h.f(node);\r\n\t\t\tif (depth > 0) {\r\n\t\t\t\t@SuppressWarnings(\"unchecked\")\r\n\t\t\t\tIterator<Node<N,?>> it = (Iterator<Node<N, ?>>) path.iterator();\r\n\t\t\t\tNode<N,?> parent = it.next();\r\n\t\t\t\tNode<N,?> current;\r\n\t\t\t\twhile (it.hasNext()) {\r\n\t\t\t\t\tcurrent = it.next();\r\n\t\t\t\t\tpathCost += g.g(parent, current);\r\n\t\t\t\t\tparent = current;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn pathCost + heuristic;\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic NumberBasedAdditiveTraversalTree(GraphGenerator<N, A> graphGenerator, EdgeCostComputer<N> g, INodeEvaluator<N, Double> h) {\r\n\t\tsuper(graphGenerator, new FComputer<>(g, h));\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.7262569665908813, "alphanum_fraction": 0.7262569665908813, "avg_line_length": 16.047618865966797, "blob_id": "7a39f1e094b4192fe65dee466bcd27fb01c6aec5", "content_id": "c0bb23df3a3d7f2b4753d6deac0ee743761140bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 358, "license_type": "no_license", "max_line_length": 74, "num_lines": 21, "path": "/JAICore/jaicore-graphvisualizer/src/jaicore/graphvisualizer/gui/dataVisualizer/TooltipVisualizer.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.graphvisualizer.gui.dataVisualizer;\n\n/**\n * A Variation of the HTML-Visualizer with a different title and supplier.\n * \n * @author jkoepe\n *\n */\npublic class TooltipVisualizer extends HTMLVisualizer {\n\n\t@Override\n\tpublic String getSupplier() {\n\t\treturn \"TooltipSupplier\";\n\t}\n\n\t@Override\n\tpublic String getTitle() {\n\t\treturn \"Tooltips\";\n\t}\n\n}\n" }, { "alpha_fraction": 0.6329866051673889, "alphanum_fraction": 0.6329866051673889, "avg_line_length": 22.035715103149414, "blob_id": "7e73f201b198a5c01a7f953e8cb3035cf0db09bb", "content_id": "8388675ee841d2f038696029c52ec5be562bc841", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1346, "license_type": "no_license", "max_line_length": 76, "num_lines": 56, "path": "/JAICore/jaicore-graph/src/jaicore/graph/TreeNode.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.graph;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\n\r\npublic class TreeNode<T> {\r\n private final T value;\r\n private final TreeNode<T> parent;\r\n private final List<TreeNode<T>> children = new ArrayList<TreeNode<T>>();\r\n\r\n public TreeNode(T rootData) {\r\n this(rootData,null);\r\n }\r\n \r\n public TreeNode(T value, TreeNode<T> parent) {\r\n this.value = value;\r\n this.parent = parent;\r\n }\r\n \r\n public TreeNode<T> addChild(T child) {\r\n \tTreeNode<T> childNode = new TreeNode<>(child, this);\r\n \tchildren.add(childNode);\r\n \treturn childNode;\r\n }\r\n \r\n public void removeChild(T child) {\r\n \tchildren.removeIf(c -> c.value.equals(child));\r\n }\r\n\r\n\tpublic T getValue() {\r\n\t\treturn value;\r\n\t}\r\n\r\n\tpublic TreeNode<T> getParent() {\r\n\t\treturn parent;\r\n\t}\r\n\r\n\tpublic List<TreeNode<T>> getChildren() {\r\n\t\treturn children;\r\n\t}\r\n\t\r\n\tpublic TreeNode<T> getRootNode() {\r\n\t\treturn this.parent == null ? this : this.parent.getRootNode();\r\n\t}\r\n\t\r\n\tpublic List<T> getValuesOnPathFromRoot() {\r\n\t\tif (parent == null) {\r\n\t\t\tList<T> path = new ArrayList<>();\r\n\t\t\tpath.add(this.value);\r\n\t\t\treturn path;\r\n\t\t}\r\n\t\tList<T> valuesOnPathFromRootToParent = parent.getValuesOnPathFromRoot();\r\n\t\tvaluesOnPathFromRootToParent.add(this.value);\r\n\t\treturn valuesOnPathFromRootToParent;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.804444432258606, "alphanum_fraction": 0.8222222328186035, "avg_line_length": 30.14285659790039, "blob_id": "53c1033bc5bdf106b039f7cf1f65f175479b4700", "content_id": "3ee72e5d30a62a554e157fd0fba5173085d982a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 225, "license_type": "no_license", "max_line_length": 59, "num_lines": 7, "path": "/softwareconfiguration/mlplan/src/de/upb/crc901/mlplan/metamining/similaritymeasures/IRankMatrixSimilarityComputer.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package de.upb.crc901.mlplan.metamining.similaritymeasures;\r\n\r\nimport org.nd4j.linalg.api.ndarray.INDArray;\r\n\r\npublic interface IRankMatrixSimilarityComputer {\r\n\tpublic INDArray computeSimilarityOfRankMatrix(INDArray R);\r\n}\r\n" }, { "alpha_fraction": 0.7123696208000183, "alphanum_fraction": 0.7153502106666565, "avg_line_length": 21.964284896850586, "blob_id": "995de8d8b539d8feb1c652cb0240a394103827b3", "content_id": "0ac33ba1f176aca07b62d72e130782f015a6b3a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 671, "license_type": "no_license", "max_line_length": 108, "num_lines": 28, "path": "/JAICore/jaicore-search/src/jaicore/search/core/interfaces/EdgeCountingSolutionEvaluator.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.core.interfaces;\r\n\r\nimport java.util.List;\r\n\r\n/**\r\n * Uses Double to be compliant with algorithms that MUST work with double instead of Integer (such as AStar)\r\n * \r\n * @author fmohr\r\n *\r\n * @param <N>\r\n */\r\npublic class EdgeCountingSolutionEvaluator<N> implements ISolutionEvaluator<N, Double> {\r\n\r\n\t@Override\r\n\tpublic Double evaluateSolution(List<N> solutionPath) throws Exception {\r\n\t\treturn solutionPath.size() * 1.0;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean doesLastActionAffectScoreOfAnySubsequentSolution(List<N> partialSolutionPath) {\r\n\t\treturn true;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void cancel() {\r\n\t\t/* not necessary to explicitly cancel */\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.5506598353385925, "alphanum_fraction": 0.552449107170105, "avg_line_length": 23.565933227539062, "blob_id": "fc3c45d00629149c7d8739a5faf62afcfee4f5d5", "content_id": "db277a8b9504404320f8d744479d0006deb8fcdc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4471, "license_type": "no_license", "max_line_length": 98, "num_lines": 182, "path": "/JAICore/jaicore-basic/src/jaicore/basic/kvstore/Table.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.basic.kvstore;\n\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\n\npublic class Table<V> {\n\n private final List<String> columnIndex = new LinkedList<>();\n private final List<String> rowIndex = new LinkedList<>();\n\n private Map<String, Map<String, V>> tableData = new HashMap<>();\n\n public Table() {\n\n }\n\n public void addEntry(final String columnIndexValue, final String rowIndexValue, final V entry) {\n Map<String, V> selectedRow = this.tableData.get(rowIndexValue);\n if (selectedRow == null) {\n selectedRow = new HashMap<>();\n this.tableData.put(rowIndexValue, selectedRow);\n if (!this.rowIndex.contains(rowIndexValue)) {\n this.rowIndex.add(rowIndexValue);\n }\n }\n if (!this.columnIndex.contains(columnIndexValue)) {\n this.columnIndex.add(columnIndexValue);\n }\n selectedRow.put(columnIndexValue, entry);\n }\n\n public String toLaTeX() {\n StringBuilder sb = new StringBuilder();\n\n sb.append(\"\\\\begin{tabular}{\");\n for (int i = 0; i < this.columnIndex.size() + 1; i++) {\n sb.append(\"l\");\n }\n sb.append(\"}\");\n\n Collections.sort(this.columnIndex);\n for (String c : this.columnIndex) {\n sb.append(\"&\");\n // sb.append(\"\\\\rotatebox{90}{\");\n sb.append(c);\n // sb.append(\"}\");\n }\n sb.append(\"\\\\\\\\\\n\");\n\n for (String r : this.rowIndex) {\n sb.append(r);\n\n for (String c : this.columnIndex) {\n sb.append(\" & \");\n Map<String, V> selectRow = this.tableData.get(r);\n if (selectRow != null) {\n V entry = selectRow.get(c);\n if (entry != null) {\n sb.append(entry.toString().replaceAll(\"_\", \"\\\\_\"));\n }\n }\n }\n sb.append(\"\\\\\\\\\\n\");\n }\n\n sb.append(\"\\\\end{tabular}\");\n return sb.toString();\n }\n\n public String toLaTeX(final String missingEntry) {\n StringBuilder sb = new StringBuilder();\n\n sb.append(\"\\\\begin{tabular}{\");\n for (int i = 0; i < this.columnIndex.size() + 1; i++) {\n sb.append(\"l\");\n }\n sb.append(\"}\");\n\n Collections.sort(this.columnIndex);\n for (String c : this.columnIndex) {\n sb.append(\"&\");\n // sb.append(\"\\\\rotatebox{90}{\");\n sb.append(c);\n // sb.append(\"}\");\n }\n sb.append(\"\\\\\\\\\\n\");\n\n // Collections.sort(this.rowIndex);\n for (String r : this.rowIndex) {\n sb.append(r);\n\n for (String c : this.columnIndex) {\n sb.append(\" & \");\n Map<String, V> selectRow = this.tableData.get(r);\n if (selectRow != null) {\n V entry = selectRow.get(c);\n if (entry != null) {\n sb.append(entry.toString().replaceAll(\"_\", \"\\\\_\"));\n } else {\n sb.append(missingEntry);\n }\n }\n }\n sb.append(\"\\\\\\\\\\n\");\n }\n\n sb.append(\"\\\\end{tabular}\");\n return sb.toString();\n }\n\n public String toCSV(final String standardValue) {\n return this.toCSV(\"\\t\", standardValue);\n }\n\n public String toCSV(final String separator, final String standardValue) {\n StringBuilder sb = new StringBuilder();\n\n // Collections.sort(this.columnIndex);\n Collections.sort(this.rowIndex);\n\n boolean first = true;\n for (String c : this.columnIndex) {\n if (first) {\n first = false;\n } else {\n sb.append(separator);\n }\n sb.append(c);\n }\n sb.append(\"\\n\");\n for (String r : this.rowIndex) {\n // sb.append(r);\n\n first = true;\n\n for (String c : this.columnIndex) {\n if (first) {\n first = false;\n } else {\n sb.append(separator);\n }\n\n Map<String, V> selectRow = this.tableData.get(r);\n if (selectRow != null) {\n V entry = selectRow.get(c);\n if (entry != null) {\n sb.append(entry.toString());\n } else {\n sb.append(standardValue);\n }\n }\n }\n sb.append(\"\\n\");\n }\n return sb.toString();\n }\n\n public String getColumnsOfCSV() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"Columns\");\n for (String c : this.columnIndex) {\n sb.append(\"\\n\");\n sb.append(c);\n // sb.append(\"}\");\n }\n return sb.toString();\n }\n\n public String getRowsOfCSV() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"Rows\");\n for (String c : this.rowIndex) {\n sb.append(\"\\n\");\n sb.append(c);\n }\n return sb.toString();\n }\n\n}\n" }, { "alpha_fraction": 0.7973517775535583, "alphanum_fraction": 0.7973517775535583, "avg_line_length": 33.448978424072266, "blob_id": "b0ec9cee75c6996aa8eda5ffbcdc60569a317951", "content_id": "f7ab538189e4d47f4a9419603e04aa50e052f19c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1737, "license_type": "no_license", "max_line_length": 167, "num_lines": 49, "path": "/softwareconfiguration/hasco/src/hasco/core/SoftwareConfigurationProblem.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package hasco.core;\r\n\r\nimport java.io.File;\r\nimport java.io.IOException;\r\nimport java.util.Collection;\r\n\r\nimport hasco.model.Component;\r\nimport hasco.model.ComponentInstance;\r\nimport hasco.serialization.ComponentLoader;\r\nimport jaicore.basic.IObjectEvaluator;\r\n\r\npublic class SoftwareConfigurationProblem<V extends Comparable<V>> {\r\n\tprivate final Collection<Component> components;\r\n\tprivate final String requiredInterface;\r\n\tprivate final IObjectEvaluator<ComponentInstance, V> compositionEvaluator;\r\n\r\n\tpublic SoftwareConfigurationProblem(File configurationFile, String requiredInerface, IObjectEvaluator<ComponentInstance, V> compositionEvaluator) throws IOException {\r\n\t\tComponentLoader cl = new ComponentLoader();\r\n\t\tcl.loadComponents(configurationFile);\r\n\t\tthis.components = cl.getComponents();\r\n\t\tthis.requiredInterface = requiredInerface;\r\n\t\tthis.compositionEvaluator = compositionEvaluator;\r\n\t}\r\n\r\n\tpublic SoftwareConfigurationProblem(Collection<Component> components, String requiredInterface, IObjectEvaluator<ComponentInstance, V> compositionEvaluator) {\r\n\t\tsuper();\r\n\t\tthis.components = components;\r\n\t\tthis.requiredInterface = requiredInterface;\r\n\t\tthis.compositionEvaluator = compositionEvaluator;\r\n\t}\r\n\t\r\n\tpublic SoftwareConfigurationProblem(SoftwareConfigurationProblem<V> problem) {\r\n\t\tthis.components = problem.getComponents();\r\n\t\tthis.requiredInterface = problem.requiredInterface;\r\n\t\tthis.compositionEvaluator = problem.compositionEvaluator;\r\n\t}\r\n\r\n\tpublic Collection<Component> getComponents() {\r\n\t\treturn components;\r\n\t}\r\n\r\n\tpublic String getRequiredInterface() {\r\n\t\treturn requiredInterface;\r\n\t}\r\n\r\n\tpublic IObjectEvaluator<ComponentInstance, V> getCompositionEvaluator() {\r\n\t\treturn compositionEvaluator;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.8174387216567993, "alphanum_fraction": 0.8174387216567993, "avg_line_length": 31.363636016845703, "blob_id": "9c2fdece687eee17d760d0d0c8909c9f879a528c", "content_id": "0d19822b075290627ede75af568c2e0d60d664ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 367, "license_type": "no_license", "max_line_length": 121, "num_lines": 11, "path": "/softwareconfiguration/hasco/src/hasco/events/HASCOSolutionEvent.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package hasco.events;\r\n\r\nimport hasco.core.HASCOSolutionCandidate;\r\nimport jaicore.basic.algorithm.SolutionCandidateFoundEvent;\r\n\r\npublic class HASCOSolutionEvent<V extends Comparable<V>> extends SolutionCandidateFoundEvent<HASCOSolutionCandidate<V>> {\r\n\r\n\tpublic HASCOSolutionEvent(HASCOSolutionCandidate<V> solutionCandidate) {\r\n\t\tsuper(solutionCandidate);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7191903591156006, "alphanum_fraction": 0.7229272127151489, "avg_line_length": 39.97712326049805, "blob_id": "9876651370f55d8098dd03ec6069324d5ae2d42d", "content_id": "8a83efc20cbef4f7ee64cfa51d8bf5d99c9d36b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 12845, "license_type": "no_license", "max_line_length": 232, "num_lines": 306, "path": "/JAICore/jaicore-ml/src/jaicore/ml/experiments/MultiClassClassificationExperimentRunner.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.ml.experiments;\r\n\r\nimport java.io.BufferedReader;\r\nimport java.io.File;\r\nimport java.io.FileReader;\r\nimport java.io.IOException;\r\nimport java.lang.reflect.Method;\r\nimport java.nio.file.Files;\r\nimport java.nio.file.Path;\r\nimport java.util.ArrayList;\r\nimport java.util.Arrays;\r\nimport java.util.Collection;\r\nimport java.util.Collections;\r\nimport java.util.HashMap;\r\nimport java.util.List;\r\nimport java.util.Map;\r\nimport java.util.Random;\r\nimport java.util.concurrent.atomic.AtomicInteger;\r\nimport java.util.stream.Collectors;\r\nimport java.util.stream.Stream;\r\n\r\nimport org.apache.commons.lang3.reflect.MethodUtils;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.fasterxml.jackson.databind.ObjectMapper;\r\nimport com.fasterxml.jackson.databind.node.ArrayNode;\r\nimport com.google.common.collect.ContiguousSet;\r\nimport com.google.common.collect.DiscreteDomain;\r\nimport com.google.common.collect.Range;\r\n\r\nimport jaicore.logging.LoggerUtil;\r\nimport jaicore.ml.WekaUtil;\r\nimport jaicore.ml.measures.PMMulticlass;\r\nimport weka.classifiers.Classifier;\r\nimport weka.core.Instance;\r\nimport weka.core.Instances;\r\n\r\npublic abstract class MultiClassClassificationExperimentRunner {\r\n\r\n\tprivate static final Logger logger = LoggerFactory.getLogger(MultiClassClassificationExperimentRunner.class);\r\n\t\r\n\tprivate final File datasetFolder;\r\n\tprivate final List<File> availableDatasets;\r\n\tprivate final String[] classifiers;\r\n\tprivate final Map<String, String[]> setups;\r\n\tprivate final int numberOfSetups;\r\n\tprivate final int[] timeoutsInSeconds;\r\n\tprivate final int numberOfRunsPerExperiment;\r\n\tprivate final float trainingPortion;\r\n\tprivate final int numberOfCPUs;\r\n\tprivate final int memoryInMB;\r\n\tprivate final PMMulticlass performanceMeasure;\r\n\tprivate final IMultiClassClassificationExperimentDatabase database;\r\n\tprivate final int totalExperimentSize;\r\n\tprivate Collection<MLExperiment> experimentsConductedEarlier;\r\n\r\n\t@SuppressWarnings(\"serial\")\r\n\tclass ExperimentAlreadyConductedException extends Exception {\r\n\t\tpublic ExperimentAlreadyConductedException(String message) {\r\n\t\t\tsuper(message);\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic MultiClassClassificationExperimentRunner(File datasetFolder, String[] classifiers, Map<String, String[]> setups, int[] timeoutsInSeconds, int numberOfRunsPerExperiment,\r\n\t\t\tfloat trainingPortion, int numberOfCPUs, int memoryInMB, PMMulticlass performanceMeasure, IMultiClassClassificationExperimentDatabase logger) throws IOException {\r\n\t\tsuper();\r\n\t\tthis.datasetFolder = datasetFolder;\r\n\t\tthis.availableDatasets = getAvailableDatasets(datasetFolder);\r\n\t\tthis.classifiers = classifiers;\r\n\t\tthis.setups = setups;\r\n\t\tthis.timeoutsInSeconds = timeoutsInSeconds;\r\n\t\tthis.numberOfRunsPerExperiment = numberOfRunsPerExperiment;\r\n\t\tthis.trainingPortion = trainingPortion;\r\n\t\tthis.numberOfCPUs = numberOfCPUs;\r\n\t\tthis.memoryInMB = memoryInMB;\r\n\t\tthis.performanceMeasure = performanceMeasure;\r\n\t\tthis.database = logger;\r\n\r\n\t\tint tmpNumberOfSetups = 0;\r\n\t\tfor (String[] setupsOfClassifier : this.setups.values())\r\n\t\t\ttmpNumberOfSetups += setupsOfClassifier.length;\r\n\t\tnumberOfSetups = tmpNumberOfSetups;\r\n\r\n\t\ttotalExperimentSize = classifiers.length * availableDatasets.size() * numberOfSetups * numberOfRunsPerExperiment * timeoutsInSeconds.length;\r\n\t\t\r\n\t\t/* print information about the experiments */\r\n\t\tSystem.out.println(\"Available datasets: \");\r\n\t\tfinal AtomicInteger i = new AtomicInteger();\r\n\t\tavailableDatasets.stream().forEach(ds -> System.out.println(\"\\t\" + (i.getAndIncrement()) + \": \" + ds.getName()));\r\n\t\tSystem.out.println(\"Available algorithms: \");\r\n\t\ti.set(0);\r\n\t\tArrays.asList(classifiers).stream().forEach(c -> System.out.println(\"\\t\" + (i.getAndIncrement()) + \": \" + c));\r\n\t}\r\n\r\n\tprotected abstract Classifier getConfiguredClassifier(int seed, String algoName, String algoMode, int timeout, int numberOfCPUs, int memoryInMB,\r\n\t\t\tPMMulticlass performanceMeasure);\r\n\r\n\tpublic void runAll() throws Exception {\r\n\t\texperimentsConductedEarlier = database.getExperimentsForWhichARunExists();\r\n\t\tfor (int k = 0; k < totalExperimentSize; k++) {\r\n\t\t\ttry {\r\n\t\t\t\trunSpecific(k);\r\n\t\t\t} catch (ExperimentAlreadyConductedException e) {\r\n\t\t\t\tSystem.out.println(e.getMessage());\r\n\t\t\t} catch (Exception e) {\r\n\t\t\t\te.printStackTrace();\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void runAny() throws Exception {\r\n\t\texperimentsConductedEarlier = database.getExperimentsForWhichARunExists();\r\n\t\tList<Integer> indices = new ArrayList<>(ContiguousSet.create(Range.closed(0, totalExperimentSize - 1), DiscreteDomain.integers()).asList());\r\n\t\tCollections.shuffle(indices);\r\n\t\tfor (int index : indices){\r\n\t\t\ttry {\r\n\t\t\t\trunSpecific(index);\r\n\t\t\t\treturn;\r\n\t\t\t} catch (ExperimentAlreadyConductedException e) {\r\n\t\t\t\tSystem.out.println(e.getMessage());\r\n\t\t\t} catch (Exception e) {\r\n\t\t\t\te.printStackTrace();\r\n\t\t\t}\r\n\t\t}\r\n\t\twhile (true);\r\n\t}\r\n\r\n\tpublic void runSpecific(int k) throws Exception {\r\n\r\n\t\tint numberOfDatasets = availableDatasets.size();\r\n\t\tint numberOfSeeds = numberOfRunsPerExperiment;\r\n\t\tint numberOfTimeouts = timeoutsInSeconds.length;\r\n\t\tSystem.out.println(\"Number of runs (seeds) per dataset/algo-combination: \" + numberOfSeeds);\r\n\t\tint frameSizeForTimeout = totalExperimentSize / numberOfTimeouts;\r\n\t\tint frameSizeForSeed = frameSizeForTimeout / numberOfSeeds;\r\n\t\tint frameSizeForSetup = frameSizeForSeed / numberOfSetups;\r\n\t\tint frameSizeForDataset = frameSizeForSetup / numberOfDatasets;\r\n\t\tif (k >= totalExperimentSize)\r\n\t\t\tthrow new IllegalArgumentException(\"Only \" + totalExperimentSize + \" experiments defined.\");\r\n\r\n\t\t/* determine exact experiment */\r\n\t\tint timeoutId = (int) Math.floor(k / frameSizeForTimeout * 1f);\r\n\t\tint indexWithinTimeout = k % frameSizeForTimeout;\r\n\t\tint seedId = (int) Math.floor(indexWithinTimeout / frameSizeForSeed * 1f);\r\n\t\tint indexWithinSeed = indexWithinTimeout % frameSizeForSeed;\r\n\t\tint datasetId = (int) Math.floor(indexWithinSeed / frameSizeForDataset * 1f);\r\n\t\tint indexWithinDataset = indexWithinSeed % frameSizeForDataset;\r\n\t\tint algoAndSetupId = (int) Math.floor(indexWithinDataset / frameSizeForSetup * 1f);\r\n\t\t// int indexWithinSetup = indexWithinDataset % frameSizeForSetup;\r\n\r\n\t\tSystem.out.println(\"Running experiment \" + k + \"/\" + totalExperimentSize + \". The setup is: \" + timeoutId + \"/\" + seedId + \"/\" + datasetId + \"/\" + \"/\" + algoAndSetupId\r\n\t\t\t\t+ \"(timeout/seed/dataset/algo-setup-id)\");\r\n\t\trunExperiment(datasetId, timeoutId, seedId, algoAndSetupId);\r\n\t}\r\n\r\n\tprivate int getAlgoIdForAlgoSetupId(int algoSetupId) {\r\n\t\tint counter = 0;\r\n\t\tfor (int i = 0; i < classifiers.length; i++) {\r\n\t\t\tcounter += setups.get(classifiers[i]).length;\r\n\t\t\tif (algoSetupId < counter)\r\n\t\t\t\treturn i;\r\n\t\t}\r\n\t\treturn -1;\r\n\t}\r\n\r\n\tprivate int getSetupIdForAlgoSetupId(int algoSetupId) {\r\n\t\tint counter = 0;\r\n\t\tfor (int i = 0; i < classifiers.length; i++) {\r\n\t\t\tString[] setupsOfThisClassifier = setups.get(classifiers[i]);\r\n\t\t\tfor (int j = 0; j < setupsOfThisClassifier.length; j++) {\r\n\t\t\t\tif (counter == algoSetupId)\r\n\t\t\t\t\treturn j;\r\n\t\t\t\tcounter++;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn -1;\r\n\t}\r\n\r\n\tpublic void runExperiment(int datasetId, int timeoutId, int seedId, int algoAndSetupId) throws Exception {\r\n\r\n\t\t/* read dataset */\r\n\t\tString datasetName = availableDatasets.get(datasetId).getName();\r\n\t\tdatasetName = datasetName.substring(0, datasetName.lastIndexOf(\".\"));\r\n\r\n\t\t/* create experiment */\r\n\t\tint algoId = getAlgoIdForAlgoSetupId(algoAndSetupId);\r\n\t\tint setupId = getSetupIdForAlgoSetupId(algoAndSetupId);\r\n\t\tString algo = classifiers[algoId];\r\n\t\tString algoMode = setups.get(algo)[setupId];\r\n\t\tint timeoutInSeconds = timeoutsInSeconds[timeoutId];\r\n\t\tif (performanceMeasure != PMMulticlass.errorRate) {\r\n\t\t\tthrow new IllegalArgumentException(\"Currently the only supported performance measure is errorRate\");\r\n\t\t}\r\n\t\tMLExperiment exp = new MLExperiment(new File(datasetFolder + File.separator + availableDatasets.get(datasetId)).getAbsolutePath(), algo, algoMode, seedId, timeoutInSeconds, numberOfCPUs, memoryInMB, performanceMeasure.toString());\r\n\t\t\r\n\t\t/* conduct a first check whether this experiment already exists */\r\n\t\tif (experimentsConductedEarlier != null && experimentsConductedEarlier.contains(exp)) {\r\n\t\t\tthrow new ExperimentAlreadyConductedException(\"Experiment \" + exp + \" has already been conducted\");\r\n\t\t}\r\n\r\n\t\ttry {\r\n\t\t\t\r\n\t\t\t/* create actual classifier */\r\n\t\t\tSystem.out.println(\"Now configuring classifier ...\");\r\n\t\t\tClassifier c = getConfiguredClassifier(seedId, algo, algoMode, timeoutInSeconds, numberOfCPUs, memoryInMB, performanceMeasure);\r\n\t\t\t\r\n\t\t\t/* get all experiments conducted or in progress so far */\r\n\t\t\tCollection<MLExperiment> experiments = database.getExperimentsForWhichARunExists();\r\n\t\t\tif (experiments.contains(exp)) {\r\n\t\t\t\tthrow new ExperimentAlreadyConductedException(\"Experiment has already been conducted, but rather recently: \" + exp);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tint runId = database.createRunIfDoesNotExist(exp);\r\n\t\t\tif (runId < 0) {\r\n\t\t\t\tthrow new ExperimentAlreadyConductedException(\"Experiment has already been conducted, but quite recently: \" + exp);\r\n\t\t\t}\r\n\t\t\tSystem.out.println(\"The assigned runId for this experiment is \" + runId);\r\n\t\t\t\r\n\t\t\t/* create random object */\r\n\t\t\tRandom r = new Random(seedId);\r\n\r\n\t\t\t/* create actual dataset */\r\n\t\t\tInstances data = getKthInstances(datasetFolder, datasetId);\r\n\t\t\tdata.setClassIndex(data.numAttributes() - 1);\r\n\t\t\t\r\n\t\t\tCollection<Integer>[] overallSplitIndices = WekaUtil.getStratifiedSplitIndices(data, r, trainingPortion);\r\n\t\t\tList<Instances> overallSplit = WekaUtil.realizeSplit(data, overallSplitIndices);\r\n\t\t\tInstances internalData = overallSplit.get(0);\r\n\t\t\tInstances testData = overallSplit.get(1);\r\n\t\t\tObjectMapper om = new ObjectMapper();\r\n\t\t\tArrayNode an = om.createArrayNode();\r\n\t\t\toverallSplitIndices[0].stream().sorted().forEach(v -> an.add(v));\r\n\t\t\tSystem.out.println(\"Data were split into \" + internalData.size() + \"/\" + testData.size());\r\n\t\t\t\r\n\t\t\t/* update database information */\r\n\t\t\tMap<String,String> runUpdate = new HashMap<>();\r\n\t\t\trunUpdate.put(\"rows_for_training\", an.toString());\r\n\t\t\tdatabase.updateExperiment(exp, runUpdate);\r\n\t\t\tdatabase.associatedRunWithClassifier(runId, c);\r\n\t\t\tSystem.out.println(\"Classifier configured. Determining result files.\");\r\n\r\n\t\t\tSystem.out.println(\"Invoking \" + getExperimentDescription(datasetId, c, seedId) + \" with setup \" + algoMode + \" and timeout \" + timeoutsInSeconds[timeoutId] + \"s\");\r\n\t\t\tlong start = System.currentTimeMillis();\r\n\t\t\ttry {\r\n\t\t\t\tc.buildClassifier(internalData);\r\n\t\t\t\tlong end = System.currentTimeMillis();\r\n\t\t\t\tSystem.out.println(\"Search has finished. Runtime: \" + (end - start) / 1000f + \" s\");\r\n\r\n\t\t\t\t/* check performance of the pipeline */\r\n\t\t\t\tint mistakes = 0;\r\n\t\t\t\tMethod m = MethodUtils.getMatchingAccessibleMethod(c.getClass(), \"classifyInstances\", Instances.class);\r\n\t\t\t\tif (m != null) {\r\n\t\t\t\t\tdouble[] predictions = (double[]) m.invoke(c, testData);\r\n\t\t\t\t\tfor (int i = 0; i < predictions.length; i++) {\r\n\t\t\t\t\t\tif (predictions[i] != testData.get(i).classValue())\r\n\t\t\t\t\t\t\tmistakes ++;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tfor (Instance i : testData) {\r\n\t\t\t\t\t\tif (i.classValue() != c.classifyInstance(i))\r\n\t\t\t\t\t\t\tmistakes++;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tdouble error = mistakes * 10000f / testData.size();\r\n\t\t\t\tSystem.out.println(\"Sending error Rate \" + error + \" to logger.\");\r\n\t\t\t\tdatabase.addResultEntry(runId, error);\r\n\t\t\t} catch (Throwable e) {\r\n\t\t\t\tlogger.error(\"Experiment failed. Details:\\n{}\", LoggerUtil.getExceptionInfo(e));\r\n\t\t\t\tSystem.out.println(\"Sending error Rate -10000 to logger.\");\r\n\t\t\t\ttry {\r\n\t\t\t\t\tdatabase.addResultEntry(runId, -10000);\r\n\t\t\t\t} catch (Exception e1) {\r\n\t\t\t\t\tlogger.error(\"Could not write result to database. Details:\\n{}\", LoggerUtil.getExceptionInfo(e1));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\tlogger.error(\"Experiment failed. Details:\\n{}\", LoggerUtil.getExceptionInfo(e));\r\n\t\t}\r\n\t}\r\n\r\n\tpublic String getExperimentDescription(int datasetId, Classifier algorithm, int seed) {\r\n\t\treturn algorithm + \"-\" + availableDatasets.get(datasetId).getName() + \"-\" + seed;\r\n\t}\r\n\r\n\tpublic List<File> getAvailableDatasets(File folder) throws IOException {\r\n\t\tList<File> files = new ArrayList<>();\r\n\t\ttry (Stream<Path> paths = Files.walk(folder.toPath())) {\r\n\t\t\tpaths.filter(f -> f.getParent().toFile().equals(folder) && f.toFile().getAbsolutePath().endsWith(\".arff\")).forEach(f -> files.add(f.toFile()));\r\n\t\t}\r\n\t\treturn files.stream().sorted().collect(Collectors.toList());\r\n\t}\r\n\r\n\tpublic Instances getKthInstances(File folder, int k) throws IOException {\r\n\t\tFile f = getAvailableDatasets(folder).get(k);\r\n\t\tSystem.out.println(\"Selecting \" + f);\r\n\t\tInstances inst = new Instances(new BufferedReader(new FileReader(f)));\r\n\t\tinst.setRelationName((f.getAbsolutePath()).replace(File.separator, \"/\"));\r\n\t\treturn inst;\r\n\t}\r\n\r\n\tpublic IMultiClassClassificationExperimentDatabase getLogger() {\r\n\t\treturn database;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6438265442848206, "alphanum_fraction": 0.6537570357322693, "avg_line_length": 41.46762466430664, "blob_id": "1a353dd7e9f459ca7c19bc231f05e8ec81d97e65", "content_id": "c465a0a4b4363477226074172c85f7ece6beac02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 6042, "license_type": "no_license", "max_line_length": 165, "num_lines": 139, "path": "/softwareconfiguration/hasco/test/hasco/test/SimpleAutoMLTest.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "//package hasco.test;\r\n//\r\n//import java.io.BufferedReader;\r\n//import java.io.File;\r\n//import java.io.FileReader;\r\n//import java.util.ArrayList;\r\n//import java.util.HashMap;\r\n//import java.util.List;\r\n//import java.util.Map;\r\n//import java.util.Random;\r\n//\r\n//import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;\r\n//\r\n//import hasco.RefinementConfiguredSoftwareConfigurationProblem;\r\n//import hasco.SoftwareConfigurationProblem;\r\n//import hasco.core.HASCOFD;\r\n//import hasco.core.HASCOSolutionCandidate;\r\n//import hasco.model.Component;\r\n//import hasco.model.NumericParameterDomain;\r\n//import hasco.model.Parameter;\r\n//import hasco.model.ParameterRefinementConfiguration;\r\n//import hasco.variants.HASCOViaFD;\r\n//import hasco.variants.HASCOViaFDAndBestFirstWithRandomCompletions;\r\n//import jaicore.graphvisualizer.gui.VisualizationWindow;\r\n//import jaicore.ml.WekaUtil;\r\n//import jaicore.planning.EvaluatedSearchGraphBasedPlan;\r\n//import jaicore.planning.graphgenerators.task.tfd.TFDNode;\r\n//import jaicore.planning.graphgenerators.task.tfd.TFDTooltipGenerator;\r\n//import jaicore.search.model.travesaltree.Node;\r\n//import weka.classifiers.AbstractClassifier;\r\n//import weka.classifiers.Classifier;\r\n//import weka.classifiers.Evaluation;\r\n//import weka.core.Instances;\r\n//\r\n//public class SimpleAutoMLTest {\r\n//\r\n//// @Test\r\n// public void test() throws Exception {\r\n//\r\n// /* read instances */\r\n// Instances data = new Instances(new BufferedReader(new FileReader(new File(\"../datasets/classification/multi-class/segment.arff\"))));\r\n// data.setClassIndex(data.numAttributes() - 1);\r\n//\r\n// /* create algorithm */\r\n// List<Component> components = new ArrayList<>();\r\n// Map<Component, Map<Parameter, ParameterRefinementConfiguration>> paramConfigs = new HashMap<>();\r\n//\r\n// {\r\n// Component c = null;\r\n// Parameter p;\r\n// Map<Parameter, ParameterRefinementConfiguration> paramConfig;\r\n//\r\n// // c = new Component(\"weka.classifiers.meta.AdaBoostM1\");\r\n// // c.addProvidedInterface(\"classifier\");\r\n// // c.addRequiredInterface(\"baseclassifier\");\r\n// // p = new NumericParameter(\"p1\", true, 0, -10, 10);\r\n// // paramConfig = new HashMap<>();\r\n// // paramConfig.put(p, new ParameterRefinementConfiguration(2, 1));\r\n// // c.addParameter(p);\r\n// // p = new NumericParameter(\"p2\", false, 0, -10, 10);\r\n// // paramConfig.put(p, new ParameterRefinementConfiguration(2, 1));\r\n// // c.addParameter(p);\r\n// // paramConfigs.put(c, paramConfig);\r\n// // hasco.addComponent(c);\r\n//\r\n// // c = new Component(\"weka.classifiers.trees.RandomForest\");\r\n// // c.addProvidedInterface(\"classifier\");\r\n// // c.addProvidedInterface(\"baseclassifier\");\r\n// // p = new NumericParameter(\"I\", true, 50, 1, 1000);\r\n// // paramConfig = new HashMap<>();\r\n// // paramConfig.put(p, new ParameterRefinementConfiguration(4, 5));\r\n// // c.addParameter(p);\r\n// // p = new NumericParameter(\"P\", true, 0, 0, 100);\r\n// // paramConfig.put(p, new ParameterRefinementConfiguration(2, .05));\r\n// // c.addParameter(p);\r\n// // paramConfigs.put(c, paramConfig);\r\n// // hasco.addComponent(c);\r\n//\r\n// c = new Component(\"weka.classifiers.trees.RandomTree\");\r\n// c.addProvidedInterface(\"classifier\");\r\n// c.addProvidedInterface(\"baseclassifier\");\r\n// p = new Parameter(\"M\", new NumericParameterDomain(true, 1, 10), 1);\r\n// paramConfig = new HashMap<>();\r\n// paramConfig.put(p, new ParameterRefinementConfiguration(8, 1));\r\n// c.addParameter(p);\r\n// p = new Parameter(\"K\", new NumericParameterDomain(true, 0, 10), 0);\r\n// paramConfig.put(p, new ParameterRefinementConfiguration(2, 1));\r\n// c.addParameter(p);\r\n// paramConfigs.put(c, paramConfig);\r\n// components.add(c);\r\n// }\r\n// \r\n// components, paramConfigs, groundComponent -> {\r\n// Component component = groundComponent.getComponent();\r\n// Map<String, String> paramValues = groundComponent.getParameterValues();\r\n// String className = component.getName();\r\n// try {\r\n// List<String> params = new ArrayList<>();\r\n// for (Parameter p : component.getParameters()) {\r\n// if (paramValues.containsKey(p.getName())) {\r\n// params.add(\"-\" + p.getName());\r\n// params.add(paramValues.get(p.getName()));\r\n// }\r\n// }\r\n// String[] paramsAsArray = params.toArray(new String[] {});\r\n// return AbstractClassifier.forName(className, paramsAsArray);\r\n// } catch (Exception e) {\r\n// e.printStackTrace();\r\n// return null;\r\n// }\r\n// }, \"classifier\", c -> {\r\n//\r\n// System.out.print(\"Evaluating solution ... \");\r\n// DescriptiveStatistics stats = new DescriptiveStatistics();\r\n// for (int i = 0; i < 2; i++) {\r\n// List<Instances> split = WekaUtil.getStratifiedSplit(data, new Random(i), .7f);\r\n// c.buildClassifier(split.get(0));\r\n// Evaluation eval = new Evaluation(split.get(0));\r\n// eval.evaluateModel(c, split.get(1));\r\n// stats.addValue((100 - eval.pctCorrect()) / 100);\r\n// }\r\n// System.out.println(\"done\");\r\n// return stats.getMean();\r\n// }\r\n// SoftwareConfigurationProblem<Double> coreProblem = new SoftwareConfigurationProblem<>(components, requiredInterface, compositionEvaluator)\r\n// RefinementConfiguredSoftwareConfigurationProblem<Double> problem = new RefinementConfiguredSoftwareConfigurationProblem<>(coreProblem, paramRefinementConfig); \r\n// \r\n// HASCOViaFDAndBestFirstWithRandomCompletions<Double> hasco = new HASCOViaFDAndBestFirstWithRandomCompletions<>();\r\n//\r\n// new VisualizationWindow<Node<TFDNode, String>>(hasco).setTooltipGenerator(new TFDTooltipGenerator<>());\r\n// for (HASCOSolutionCandidate<EvaluatedSearchGraphBasedPlan, Classifier, Double> candidate : hasco) {\r\n// System.out.println(candidate);\r\n// }\r\n// System.out.println(\"Ready\");\r\n// while (true) {\r\n// ;\r\n// }\r\n// }\r\n//}\r\n" }, { "alpha_fraction": 0.6945917010307312, "alphanum_fraction": 0.6988335251808167, "avg_line_length": 28.419355392456055, "blob_id": "351719553e9d5d191a3f5d3277d14f11129dede7", "content_id": "28b69b0838a453d9ac9e95e7f8ad8c2cd33bbbef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3772, "license_type": "no_license", "max_line_length": 110, "num_lines": 124, "path": "/softwareconfiguration/mlplan/src/de/upb/crc901/mlplan/multiclass/wekamlplan/weka/model/SuvervisedFilterPreprocessor.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package de.upb.crc901.mlplan.multiclass.wekamlplan.weka.model;\r\n\r\nimport java.io.Serializable;\r\n\r\nimport de.upb.crc901.mlplan.multiclass.wekamlplan.sophisticated.FeaturePreprocessor;\r\nimport jaicore.ml.WekaUtil;\r\nimport weka.attributeSelection.ASEvaluation;\r\nimport weka.attributeSelection.ASSearch;\r\nimport weka.attributeSelection.AttributeSelection;\r\nimport weka.core.Attribute;\r\nimport weka.core.Instance;\r\nimport weka.core.Instances;\r\n\r\n@SuppressWarnings(\"serial\")\r\npublic class SuvervisedFilterPreprocessor implements Serializable, FeaturePreprocessor {\r\n\tprivate final ASSearch searcher;\r\n\tprivate final ASEvaluation evaluator;\r\n\tprivate final AttributeSelection selector;\r\n\tprivate boolean prepared;\r\n\r\n\tpublic SuvervisedFilterPreprocessor(ASSearch searcher, ASEvaluation evaluator) {\r\n\t\tsuper();\r\n\t\tthis.searcher = searcher;\r\n\t\tthis.evaluator = evaluator;\r\n\t\tthis.selector = new AttributeSelection();\r\n\t\tthis.selector.setSearch(searcher);\r\n\t\tthis.selector.setEvaluator(evaluator);\r\n\t}\r\n\t\r\n\tpublic SuvervisedFilterPreprocessor(ASSearch searcher, ASEvaluation evaluator, AttributeSelection selector) {\r\n\t\tsuper();\r\n\t\tthis.searcher = searcher;\r\n\t\tthis.evaluator = evaluator;\r\n\t\tthis.selector = selector;\r\n\t}\r\n\r\n\tpublic ASSearch getSearcher() {\r\n\t\treturn searcher;\r\n\t}\r\n\r\n\tpublic ASEvaluation getEvaluator() {\r\n\t\treturn evaluator;\r\n\t}\r\n\r\n\tpublic AttributeSelection getSelector() {\r\n\t\treturn selector;\r\n\t}\r\n\t\r\n\tpublic void prepare(Instances data) throws Exception {\r\n\t\tselector.SelectAttributes(data);\r\n\t\tprepared = true;\r\n\t}\r\n\t\r\n\tpublic Instance apply(Instance data) throws Exception {\r\n\t\tif (!prepared)\r\n\t\t\tthrow new IllegalStateException(\"Cannot apply preprocessor before it has been prepared!\");\r\n\t\tInstance inst = selector.reduceDimensionality(data);\r\n\t\tif (inst.dataset().classIndex() >= 0)\r\n\t\t\tinst = WekaUtil.removeClassAttribute(inst);\r\n\t\tfor (int i = 0; i < inst.dataset().numAttributes(); i++) {\r\n\t\t\tAttribute a = inst.dataset().attribute(i);\r\n\t\t\tinst.dataset().renameAttribute(a, this.getClass().getSimpleName() + \"_\" + a.name());\r\n\t\t}\r\n\t\treturn inst;\r\n\t}\r\n\t\r\n\tpublic Instances apply(Instances data) throws Exception {\r\n\t\tif (!prepared)\r\n\t\t\tthrow new IllegalStateException(\"Cannot apply preprocessor before it has been prepared!\");\r\n\t\tInstances inst = selector.reduceDimensionality(data);\r\n\t\tif (inst.classIndex() >= 0)\r\n\t\t\tinst = WekaUtil.removeClassAttribute(inst);\r\n\t\tfor (int i = 0; i < inst.numAttributes(); i++) {\r\n\t\t\tAttribute a = inst.attribute(i);\r\n\t\t\tinst.renameAttribute(a, this.getClass().getSimpleName() + \"_\" + a.name());\r\n\t\t}\r\n\t\treturn inst;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + ((evaluator == null) ? 0 : evaluator.hashCode());\r\n\t\tresult = prime * result + ((searcher == null) ? 0 : searcher.hashCode());\r\n\t\tresult = prime * result + ((selector == null) ? 0 : selector.hashCode());\r\n\t\treturn result;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean equals(Object obj) {\r\n\t\tif (this == obj)\r\n\t\t\treturn true;\r\n\t\tif (obj == null)\r\n\t\t\treturn false;\r\n\t\tif (getClass() != obj.getClass())\r\n\t\t\treturn false;\r\n\t\tSuvervisedFilterPreprocessor other = (SuvervisedFilterPreprocessor) obj;\r\n\t\tif (evaluator == null) {\r\n\t\t\tif (other.evaluator != null)\r\n\t\t\t\treturn false;\r\n\t\t} else if (!evaluator.equals(other.evaluator))\r\n\t\t\treturn false;\r\n\t\tif (searcher == null) {\r\n\t\t\tif (other.searcher != null)\r\n\t\t\t\treturn false;\r\n\t\t} else if (!searcher.equals(other.searcher))\r\n\t\t\treturn false;\r\n\t\tif (selector == null) {\r\n\t\t\tif (other.selector != null)\r\n\t\t\t\treturn false;\r\n\t\t} else if (!selector.equals(other.selector))\r\n\t\t\treturn false;\r\n\t\treturn true;\r\n\t}\r\n\r\n\tpublic boolean isPrepared() {\r\n\t\treturn prepared;\r\n\t}\r\n\r\n\tpublic void setPrepared(boolean prepared) {\r\n\t\tthis.prepared = prepared;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.546354353427887, "alphanum_fraction": 0.5628505349159241, "avg_line_length": 33.45454406738281, "blob_id": "d9ce784249275bde4e88767a16aaa3c296b10fa9", "content_id": "5a389b1c1b377ac969cc30eb67c6abbe87a0eb28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3031, "license_type": "no_license", "max_line_length": 118, "num_lines": 88, "path": "/JAICore/jaicore-services/src/jaicore/services/ComparableAttributeServiceGenerator.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.services;\nimport java.io.BufferedWriter;\nimport java.io.FileWriter;\nimport java.io.IOException;\n\npublic class ComparableAttributeServiceGenerator {\n\t\n\tpublic void create(int services, String outServices, String outRules) throws IOException {\n\t\t\n\t\t/* create services with predicates and rules */\n\t\tStringBuilder strRules = new StringBuilder();\n\t\tstrRules.append(\"EQ(x,y) -> EQ(y,x)\\n\");\n\t\tstrRules.append(\"NEQ(x,y) -> NEQ(y,x)\\n\");\n\t\tstrRules.append(\"EQ(x,y) & EQ(y,z) -> EQ(x,z)\\n\"); // transitivity of equality\n\t\tstrRules.append(\"LE(x,y) & LE(y,z) -> LE(x,z)\\n\"); // transitivity of <\n\t\tstrRules.append(\"LEQ(x,y) & LEQ(y,z) -> LEQ(x,z)\\n\"); // transitivity of <=\n\t\t\n\t\tStringBuilder strServices = new StringBuilder();\n\t\tfor (int i = 0; i < services; i++) {\n\t\t\tString inputs = \"\", outputs = \"\", precondition = \"\", effect = \"\";\n\t\t\tint numberOfInputs = (Math.random() > 0.5) ? 1 : 1;\n\t\t\tint numberOfOutputs = 1;\n\t\t\tfor (int j = 1; j <= numberOfInputs; j++) {\n\t\t\t\tif (inputs.length() != 0) {\n\t\t\t\t\tinputs += \", \";\n\t\t\t\t\tprecondition += \" & \";\n\t\t\t\t}\n\t\t\t\tinputs += \"i\" + j;\n\t\t\t\t//precondition += \"t\" + type + \"(i\" + j + \")\";\n\t\t\t}\n\t\t\tfor (int j = 1; j <= numberOfOutputs; j++) {\n\t\t\t\tif (outputs.length() != 0) {\n\t\t\t\t\toutputs += \", \";\n\t\t\t\t\t//effect += \" & \";\n\t\t\t\t}\n\t\t\t\toutputs += \"o\" + j;\n\t\t\t\t//effect += \"t\" + type + \"(o\" + j + \")\";\n\t\t\t}\n\t\t\t\n\t\t\t/* introduce three new predicates */\n\t\t\tString p1 = \"A\" + i; // postcondition\n\t\t\tString p2 = \"C\" + i; // comparison-predicate (CHEAPER,LARGER...)\n\t\t\t\n\t\t\tString[] comparators = {\"NEQ\", \"EQ\", \"LEQ\", \"LE\"};\n\t\t\t\n\t\t\t/* determine precondition of service */\n\t\t\tprecondition = \"T(i1)\";\n\t\t\t\n\t\t\t/* determine preconditions, and effects of service, and the rules */\n\t\t\tif (numberOfInputs == 1) {\n\t\t\t\teffect = \"T(o1) & \" + p1 + \"(i1,o1)\";\n\t\t\t\tfor (String b : comparators) {\n\t\t\t\t\t\n\t\t\t\t\t/* rule for filter 1 */\n\t\t\t\t\tstrRules.append(p1 + \"(x,y) & \" + b + \"(y,z) -> \" + p2 + b + \"(x,z)\\n\");\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t/* rule for selector */\n\t\t\t\tstrRules.append(p1 + \"(x1,y1) & \" + p1 + \"(x2,y2) & \" + \"LEQ(y1,y2) -> SM\" + i + \"(x1,x2)\\n\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\teffect = p1 + \"(i1,i2,o1)\";\n\t\t\t\t\n\t\t\t\tfor (String b : comparators) {\n\t\t\t\t\t\n\t\t\t\t\t/* rule for filter 1 */\n\t\t\t\t\tstrRules.append(p1 + \"(x,q,y) & \" + b + \"(y,z) -> \" + p2 + b + \"(x,q,z)\\n\");\n\t\t\t\t\t\n\t\t\t\t\t/* rule for selector */\n\t\t\t\t\tstrRules.append(p1 + \"(x1,q,y1) & \" + p1 + \"(x2,q,y2) & \" + b + \"(y1,y2) -> \" + p2 + b + \"(x1,x2,q)\\n\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tstrServices.append(\"serv\" + (i + 1) + \"; \" + inputs + \"; \" + outputs + \"; \" + precondition + \"; \" + effect + \"\\n\");\n\t\t}\n\t\t\n\t\t/* write services to file */\n\t\tFileWriter streamServiceFile = new FileWriter(outServices);\n\t\tBufferedWriter writerServiceFile = new BufferedWriter(streamServiceFile);\n\t\twriterServiceFile.write(strServices.toString());\n\t\twriterServiceFile.close();\n\t\t\n\t\t/* write rules to file */\n\t\tFileWriter streamRuleFile = new FileWriter(outRules);\n\t\tBufferedWriter writerRuleFile = new BufferedWriter(streamRuleFile);\n\t\twriterRuleFile.write(strRules.toString());\n\t\twriterRuleFile.close();\n\t}\n}" }, { "alpha_fraction": 0.774193525314331, "alphanum_fraction": 0.774193525314331, "avg_line_length": 12.285714149475098, "blob_id": "b650fbbfb1d5d188cd7e893e333284f240fea56d", "content_id": "612b4bc1de618de51aaed8b16eca3bc926c510fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 93, "license_type": "no_license", "max_line_length": 35, "num_lines": 7, "path": "/JAICore/jaicore-basic/src/jaicore/basic/chunks/ETaskElementValueType.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.basic.chunks;\n\npublic enum ETaskElementValueType {\n\n RANGE, ENUMERATION;\n\n}\n" }, { "alpha_fraction": 0.772417426109314, "alphanum_fraction": 0.772417426109314, "avg_line_length": 33.98113250732422, "blob_id": "30b4025ed85b02b92a4f616517df396a475a01e2", "content_id": "1d98d68c57f7e675f6ce3acdb1466ac741e182de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1907, "license_type": "no_license", "max_line_length": 197, "num_lines": 53, "path": "/softwareconfiguration/hasco/src/hasco/core/HASCOSolutionCandidate.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package hasco.core;\r\n\r\nimport hasco.model.ComponentInstance;\r\nimport jaicore.planning.EvaluatedPlan;\r\nimport jaicore.planning.EvaluatedSearchGraphBasedPlan;\r\nimport jaicore.planning.model.ceoc.CEOCAction;\r\n\r\n/**\r\n * This is a wrapper class only used for efficient processing of solutions. For example, to lookup the annotations of a solution, we do not need the possibly costly equals method of T but only this\r\n * class. For each solution, only one such object is created.\r\n * \r\n * @author fmohr\r\n *\r\n * @param <T>\r\n */\r\npublic class HASCOSolutionCandidate<V extends Comparable<V>> {\r\n\r\n\tprivate final ComponentInstance componentInstance;\r\n\tprivate final EvaluatedSearchGraphBasedPlan<CEOCAction, V, ?> planningSolution;\r\n\tprivate final int timeToEvaluateCandidate;\r\n\tprivate final long timeOfCreation = System.currentTimeMillis();\r\n\r\n\tpublic HASCOSolutionCandidate(ComponentInstance componentInstance, EvaluatedSearchGraphBasedPlan<CEOCAction, V, ?> planningSolution, int timeToEvaluateCandidate) {\r\n\t\tsuper();\r\n\t\tthis.componentInstance = componentInstance;\r\n\t\tthis.planningSolution = planningSolution;\r\n\t\tthis.timeToEvaluateCandidate = timeToEvaluateCandidate;\r\n\t\tif (planningSolution == null)\r\n\t\t\tthrow new IllegalArgumentException(\"HASCOSolutionCandidate cannot be created with a NULL planning solution.\");\r\n\t\tif (planningSolution.getPath() == null)\r\n\t\t\tthrow new IllegalArgumentException(\"HASCOSolutionCandidate cannot be created with a planning solution that has a NULL path object.\");\r\n\t}\r\n\r\n\tpublic ComponentInstance getComponentInstance() {\r\n\t\treturn componentInstance;\r\n\t}\r\n\r\n\tpublic EvaluatedPlan<CEOCAction, V> getPlanningSolution() {\r\n\t\treturn planningSolution;\r\n\t}\r\n\t\r\n\tpublic V getScore() {\r\n\t\treturn planningSolution.getScore();\r\n\t}\r\n\r\n\tpublic int getTimeToEvaluateCandidate() {\r\n\t\treturn timeToEvaluateCandidate;\r\n\t}\r\n\r\n\tpublic long getTimeOfCreation() {\r\n\t\treturn timeOfCreation;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.8219584822654724, "alphanum_fraction": 0.8219584822654724, "avg_line_length": 27.08333396911621, "blob_id": "b6ab02fe74e110a66d60f2404c6fb581321896ba", "content_id": "55ea9c64c8186317ade285ce4f148bcd83b27448", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 337, "license_type": "no_license", "max_line_length": 94, "num_lines": 12, "path": "/JAICore/jaicore-planning/src/jaicore/planning/model/strips/StripsPlanningProblem.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.model.strips;\n\nimport jaicore.logic.fol.structure.Monom;\nimport jaicore.planning.model.core.PlanningProblem;\n\npublic class StripsPlanningProblem extends PlanningProblem {\n\n\tpublic StripsPlanningProblem(StripsPlanningDomain domain, Monom initState, Monom goalState) {\n\t\tsuper(domain, initState, goalState);\n\t}\n\n}\n" }, { "alpha_fraction": 0.8292349576950073, "alphanum_fraction": 0.8292349576950073, "avg_line_length": 43.75, "blob_id": "a40828131f3ed73b48fd968e7809ca829f9f9534", "content_id": "9de134430c880519b0961a95e154c16ff45c8ec8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 732, "license_type": "no_license", "max_line_length": 154, "num_lines": 16, "path": "/JAICore/jaicore-search/test/jaicore/search/testproblems/nqueens/NQueensToGraphSearchProblemInputReducer.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.testproblems.nqueens;\r\n\r\nimport jaicore.basic.algorithm.AlgorithmProblemTransformer;\r\nimport jaicore.search.core.interfaces.GraphGenerator;\r\nimport jaicore.search.model.other.AgnosticPathEvaluator;\r\nimport jaicore.search.model.probleminputs.GraphSearchProblemInput;\r\n\r\npublic class NQueensToGraphSearchProblemInputReducer implements AlgorithmProblemTransformer<Integer, GraphSearchProblemInput<QueenNode, String, Double>> {\r\n\r\n\t@Override\r\n\tpublic GraphSearchProblemInput<QueenNode, String, Double> transform(Integer problem) {\r\n\t\tGraphGenerator<QueenNode, String> graphGenerator = new NQueenGenerator(problem);\r\n\t\treturn new GraphSearchProblemInput<>(graphGenerator, new AgnosticPathEvaluator<>());\r\n\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.739047646522522, "alphanum_fraction": 0.7428571581840515, "avg_line_length": 20.826086044311523, "blob_id": "720ae3c5639de12331d6fbf160fc869570772b9b", "content_id": "05ef990f950fd9bfe556fa18f5a5a47223bda7eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 525, "license_type": "no_license", "max_line_length": 95, "num_lines": 23, "path": "/JAICore/jaicore-search/src/jaicore/search/model/other/AgnosticPathEvaluator.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.model.other;\r\n\r\nimport java.util.List;\r\n\r\nimport jaicore.search.core.interfaces.ISolutionEvaluator;\r\n\r\npublic class AgnosticPathEvaluator<N> implements ISolutionEvaluator<N, Double> {\r\n\r\n\t@Override\r\n\tpublic Double evaluateSolution(List<N> solutionPath) throws Exception {\r\n\t\treturn 0.0;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean doesLastActionAffectScoreOfAnySubsequentSolution(List<N> partialSolutionPath) {\r\n\t\treturn true;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void cancel() {\r\n\t\t/* not necessary to cancel */\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.5899999737739563, "alphanum_fraction": 0.6200000047683716, "avg_line_length": 11.625, "blob_id": "f171660a20fb61928405b3b86e1c205902f06824", "content_id": "c8cc1aa09b45ccf64c22c40e84eeec7157fba376", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 100, "license_type": "no_license", "max_line_length": 59, "num_lines": 8, "path": "/softwareconfiguration/mlplan/src/de/upb/crc901/mlplan/metamining/similaritymeasures/package-info.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "/**\n * \n */\n/**\n * @author Helena Graf\n *\n */\npackage de.upb.crc901.mlplan.metamining.similaritymeasures;" }, { "alpha_fraction": 0.7973138093948364, "alphanum_fraction": 0.7973138093948364, "avg_line_length": 30.5, "blob_id": "d10596b31d84ca0f07a2d10dd65c7df31a97dba7", "content_id": "0430efe1f7449edcc1b0ea91ea5c453c80f01f68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 819, "license_type": "no_license", "max_line_length": 97, "num_lines": 26, "path": "/JAICore/jaicore-ml/src/jaicore/ml/experiments/IMultiClassClassificationExperimentDatabase.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.ml.experiments;\n\nimport java.util.Collection;\nimport java.util.Map;\n\nimport weka.classifiers.Classifier;\n\npublic interface IMultiClassClassificationExperimentDatabase {\n\t\n\tpublic Collection<MLExperiment> getExperimentsForWhichARunExists() throws Exception;\n\t\n\tpublic int createRunIfDoesNotExist(MLExperiment experiment) throws Exception;\n\t\n\tpublic void updateExperiment(MLExperiment experiment, Map<String,String> data) throws Exception;\n\t\n\t/**\n\t * This method tells the logger the classifier object that is used for the run.\n\t * Specific loggers may retrieve important information from the classifier. \n\t * \n\t * @param runId\n\t * @param c\n\t */\n\tpublic void associatedRunWithClassifier(int runId, Classifier c) throws Exception;\n\t\n\tpublic void addResultEntry(int runId, double score) throws Exception;\n}\n" }, { "alpha_fraction": 0.7383966445922852, "alphanum_fraction": 0.7383966445922852, "avg_line_length": 24.33333396911621, "blob_id": "c1f5b5326550921897f0ebcd5fc58bc126574863", "content_id": "a8b90b0ef8907cb755cf1256872fb2c0ff8c8b9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 237, "license_type": "no_license", "max_line_length": 85, "num_lines": 9, "path": "/JAICore/jaicore-graph/src/jaicore/graph/IGraphAlgorithmFactory.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.graph;\r\n\r\nimport jaicore.basic.algorithm.IAlgorithmFactory;\r\n\r\npublic interface IGraphAlgorithmFactory<I, O, N, A> extends IAlgorithmFactory<I, O> {\r\n\t\r\n\t@Override\r\n\tpublic IGraphAlgorithm<I, O, N, A> getAlgorithm();\r\n}\r\n" }, { "alpha_fraction": 0.6750915050506592, "alphanum_fraction": 0.6798157691955566, "avg_line_length": 32.149192810058594, "blob_id": "7ea2506e9fb5816e19d09857fd67d92d346fa167", "content_id": "7944ecf7c777c0c114fb8d53a9624f621dc93b9f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 8467, "license_type": "no_license", "max_line_length": 236, "num_lines": 248, "path": "/JAICore/jaicore-basic/src/jaicore/basic/SQLAdapter.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.basic;\r\n\r\nimport java.io.Serializable;\r\nimport java.sql.Connection;\r\nimport java.sql.DriverManager;\r\nimport java.sql.PreparedStatement;\r\nimport java.sql.ResultSet;\r\nimport java.sql.SQLException;\r\nimport java.sql.Statement;\r\nimport java.util.ArrayList;\r\nimport java.util.Arrays;\r\nimport java.util.HashMap;\r\nimport java.util.List;\r\nimport java.util.Map;\r\nimport java.util.Properties;\r\n\r\n/**\r\n * This is a simple util class for easy database access and query execution in sql. You need to make sure that the respective JDBC connector is in the class path. By default, the adapter uses the mysql driver, but any jdbc driver can be\r\n * used.\r\n *\r\n * @author fmohr\r\n *\r\n */\r\n@SuppressWarnings(\"serial\")\r\npublic class SQLAdapter implements Serializable, AutoCloseable {\r\n\tprivate final String driver, host, user, password, database;\r\n\tprivate final boolean ssl;\r\n\tprivate Connection connect;\r\n\tprivate long timestampOfLastAction = Long.MIN_VALUE;\r\n\tprivate final Properties connectionProperties;\r\n\r\n\tpublic SQLAdapter(final String host, final String user, final String password, final String database, final boolean ssl) {\r\n\t\tthis(\"mysql\", host, user, password, database, new Properties(), ssl);\r\n\t}\r\n\r\n\tpublic SQLAdapter(final String host, final String user, final String password, final String database) {\r\n\t\tthis(\"mysql\", host, user, password, database, new Properties());\r\n\t}\r\n\r\n\tpublic SQLAdapter(final String driver, final String host, final String user, final String password, final String database, final Properties connectionProperties) {\r\n\t\tthis(driver, host, user, password, database, connectionProperties, true);\r\n\t}\r\n\r\n\tpublic SQLAdapter(final String driver, final String host, final String user, final String password, final String database, final Properties connectionProperties, final boolean ssl) {\r\n\t\tsuper();\r\n\t\tthis.ssl = ssl;\r\n\t\tthis.driver = driver;\r\n\t\tthis.host = host;\r\n\t\tthis.user = user;\r\n\t\tthis.password = password;\r\n\t\tthis.database = database;\r\n\t\tthis.connectionProperties = connectionProperties;\r\n\r\n\t\tRuntime.getRuntime().addShutdownHook(new Thread(new Runnable() {\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\tSQLAdapter.this.close();\r\n\t\t\t}\r\n\t\t}));\r\n\t}\r\n\r\n\tprivate void connect() throws SQLException {\r\n\r\n\t\tint tries = 0;\r\n\t\tdo {\r\n\t\t\ttry {\r\n\t\t\t\tProperties connectionProps = new Properties(this.connectionProperties);\r\n\t\t\t\tconnectionProps.put(\"user\", this.user);\r\n\t\t\t\tconnectionProps.put(\"password\", this.password);\r\n\t\t\t\tString connectionString = \"jdbc:\" + this.driver + \"://\" + this.host + \"/\" + this.database + ((this.ssl) ? \"?verifyServerCertificate=false&requireSSL=true&useSSL=true\" : \"\");\r\n\t\t\t\tthis.connect = DriverManager.getConnection(connectionString, connectionProps);\r\n\t\t\t\treturn;\r\n\t\t\t} catch (SQLException e) {\r\n\t\t\t\ttries++;\r\n\t\t\t\tSystem.err.println(\"Connection to server \" + this.host + \" failed with JDBC driver \" + this.driver + \" (attempt \" + tries + \" of 3), waiting 3 seconds and trying again.\");\r\n\t\t\t\te.printStackTrace();\r\n\t\t\t\ttry {\r\n\t\t\t\t\tThread.sleep(3000);\r\n\t\t\t\t} catch (InterruptedException e1) {\r\n\t\t\t\t\te1.printStackTrace();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} while (tries < 3);\r\n\t\tSystem.err.println(\"Quitting execution\");\r\n\t\tSystem.exit(1);\r\n\t}\r\n\r\n\tpublic PreparedStatement getPreparedStatement(final String query) throws SQLException {\r\n\t\tthis.checkConnection();\r\n\t\treturn this.connect.prepareStatement(query);\r\n\t}\r\n\r\n\tpublic synchronized void checkConnection() throws SQLException {\r\n\t\tint renewAfterSeconds = 5 * 60;\r\n\t\tif (this.timestampOfLastAction + renewAfterSeconds * 1000 < System.currentTimeMillis()) {\r\n\t\t\tthis.close();\r\n\t\t\tthis.connect();\r\n\t\t}\r\n\t\tthis.timestampOfLastAction = System.currentTimeMillis();\r\n\t}\r\n\r\n\tpublic ResultSet getRowsOfTable(final String table) throws SQLException {\r\n\t\treturn this.getRowsOfTable(table, new HashMap<>());\r\n\t}\r\n\r\n\tpublic ResultSet getRowsOfTable(final String table, final Map<String, String> conditions) throws SQLException {\r\n\t\tStringBuilder conditionSB = new StringBuilder();\r\n\t\tList<String> values = new ArrayList<>();\r\n\t\tfor (String key : conditions.keySet()) {\r\n\t\t\tif (conditionSB.length() > 0) {\r\n\t\t\t\tconditionSB.append(\" AND \");\r\n\t\t\t} else {\r\n\t\t\t\tconditionSB.append(\" WHERE \");\r\n\t\t\t}\r\n\t\t\tconditionSB.append(key + \" = (?)\");\r\n\t\t\tvalues.add(conditions.get(key));\r\n\t\t}\r\n\t\treturn this.getResultsOfQuery(\"SELECT * FROM `\" + table + \"`\" + conditionSB.toString(), values);\r\n\t}\r\n\r\n\tpublic ResultSet getResultsOfQuery(final String query) throws SQLException {\r\n\t\treturn this.getResultsOfQuery(query, new ArrayList<>());\r\n\t}\r\n\r\n\tpublic ResultSet getResultsOfQuery(final String query, final String[] values) throws SQLException {\r\n\t\treturn this.getResultsOfQuery(query, Arrays.asList(values));\r\n\t}\r\n\r\n\tpublic ResultSet getResultsOfQuery(final String query, final List<String> values) throws SQLException {\r\n\t\tthis.checkConnection();\r\n\t\tPreparedStatement statement = this.connect.prepareStatement(query);\r\n\t\tfor (int i = 1; i <= values.size(); i++) {\r\n\t\t\tstatement.setString(i, values.get(i - 1));\r\n\t\t}\r\n\t\treturn statement.executeQuery();\r\n\t}\r\n\r\n\tpublic int insert(final String sql, final String[] values) throws SQLException {\r\n\t\treturn this.insert(sql, Arrays.asList(values));\r\n\t}\r\n\r\n\tpublic int insert(final String sql, final List<? extends Object> values) throws SQLException {\r\n\t\tthis.checkConnection();\r\n\t\tPreparedStatement stmt = this.connect.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);\r\n\t\tfor (int i = 1; i <= values.size(); i++) {\r\n\t\t\tthis.setValue(stmt, i, values.get(i - 1));\r\n\t\t}\r\n\t\tstmt.executeUpdate();\r\n\r\n\t\tResultSet rs = stmt.getGeneratedKeys();\r\n\t\trs.next();\r\n\t\treturn rs.getInt(1);\r\n\t}\r\n\r\n\tpublic int insert(final String table, final Map<String, ? extends Object> map) throws SQLException {\r\n\t\tStringBuilder sb1 = new StringBuilder();\r\n\t\tStringBuilder sb2 = new StringBuilder();\r\n\t\tList<Object> values = new ArrayList<>();\r\n\t\tfor (String key : map.keySet()) {\r\n\t\t\tif (map.get(key) == null) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tif (sb1.length() != 0) {\r\n\t\t\t\tsb1.append(\", \");\r\n\t\t\t\tsb2.append(\", \");\r\n\t\t\t}\r\n\t\t\tsb1.append(key);\r\n\t\t\tsb2.append(\"?\");\r\n\t\t\tvalues.add(map.get(key));\r\n\t\t}\r\n\r\n\t\tString statement = \"INSERT INTO \" + table + \" (\" + sb1.toString() + \") VALUES (\" + sb2.toString() + \")\";\r\n\t\treturn this.insert(statement, values);\r\n\t}\r\n\r\n\tpublic void update(final String sql, final String[] values) throws SQLException {\r\n\t\tthis.update(sql, Arrays.asList(values));\r\n\t}\r\n\r\n\tpublic void update(final String sql, final List<? extends Object> values) throws SQLException {\r\n\t\tthis.checkConnection();\r\n\t\tPreparedStatement stmt = this.connect.prepareStatement(sql);\r\n\t\tfor (int i = 1; i <= values.size(); i++) {\r\n\t\t\tstmt.setString(i, values.get(i - 1).toString());\r\n\t\t}\r\n\t\tstmt.executeUpdate();\r\n\t}\r\n\r\n\tpublic void update(final String table, final Map<String, ? extends Object> updateValues, final Map<String, ? extends Object> conditions) throws SQLException {\r\n\t\tthis.checkConnection();\r\n\t\tStringBuilder updateSB = new StringBuilder();\r\n\t\tList<Object> values = new ArrayList<>();\r\n\t\tfor (String key : updateValues.keySet()) {\r\n\t\t\tif (updateSB.length() > 0) {\r\n\t\t\t\tupdateSB.append(\", \");\r\n\t\t\t}\r\n\t\t\tupdateSB.append(key + \" = (?)\");\r\n\t\t\tvalues.add(updateValues.get(key));\r\n\t\t}\r\n\r\n\t\tStringBuilder conditionSB = new StringBuilder();\r\n\t\tfor (String key : conditions.keySet()) {\r\n\t\t\tif (conditionSB.length() > 0) {\r\n\t\t\t\tconditionSB.append(\" AND \");\r\n\t\t\t}\r\n\t\t\tconditionSB.append(key + \" = (?)\");\r\n\t\t\tvalues.add(conditions.get(key));\r\n\t\t}\r\n\r\n\t\tString sql = \"UPDATE \" + table + \" SET \" + updateSB.toString() + \" WHERE \" + conditionSB.toString();\r\n\t\tPreparedStatement stmt = this.connect.prepareStatement(sql);\r\n\t\tfor (int i = 1; i <= values.size(); i++) {\r\n\t\t\tthis.setValue(stmt, i, values.get(i - 1));\r\n\t\t}\r\n\t\tstmt.executeUpdate();\r\n\t}\r\n\r\n\tprivate void setValue(final PreparedStatement stmt, final int index, final Object val) throws SQLException {\r\n\t\tif (val instanceof Integer) {\r\n\t\t\tstmt.setInt(index, (Integer) val);\r\n\t\t} else if (val instanceof Number) {\r\n\t\t\tstmt.setDouble(index, (Double) val);\r\n\t\t} else if (val instanceof String) {\r\n\t\t\tstmt.setString(index, (String) val);\r\n\t\t} else {\r\n\t\t\tstmt.setObject(index, val);\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Close the connection. No more queries can be sent after having the access object closed\r\n\t */\r\n\t@Override\r\n\tpublic void close() {\r\n\t\ttry {\r\n\t\t\tif (this.connect != null) {\r\n\t\t\t\tthis.connect.close();\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t}\r\n\r\n\tpublic String getDriver() {\r\n\t\treturn this.driver;\r\n\t}\r\n}" }, { "alpha_fraction": 0.7028176784515381, "alphanum_fraction": 0.7028176784515381, "avg_line_length": 21.939023971557617, "blob_id": "86c34b956182481d4d2ca17d33f14ffa33ac707b", "content_id": "88a21049b86066b845c0880440212ea7e72df725", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1881, "license_type": "no_license", "max_line_length": 87, "num_lines": 82, "path": "/JAICore/jaicore-logic/src/jaicore/logic/fol/structure/TypeModule.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.logic.fol.structure;\n\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\n\npublic class TypeModule {\n\n\tprivate final Map<String, Type> typeMap = new HashMap<>();\n\t\n\tprivate final Map<String,ConstantParam> constants = new HashMap<>();\n\n\tpublic TypeModule() {}\n\t\n\tpublic TypeModule(Collection<Type> types) {\n\t\tfor (Type type : types) {\n\t\t\tthis.typeMap.put(type.getName(), type);\n\t\t}\n\t}\n\n\tpublic Type getType(String nameOfType) {\n\t\tif (nameOfType.trim().equals(\"\")) {\n\t\t\tthrow new IllegalArgumentException(\"Empty string is no valid name for a datatype.\");\n\t\t}\n\n\t\tType resultType = typeMap.get(nameOfType);\n\t\tif (resultType == null) {\n\t\t\tresultType = new Type(nameOfType);\n\t\t\tthis.typeMap.put(nameOfType, resultType);\n\t\t}\n\n\t\treturn resultType;\n\t}\n\n\tpublic int size() {\n\t\treturn this.typeMap.size();\n\t}\n\n\tpublic Collection<Type> getAllTypes() {\n\t\treturn this.typeMap.values();\n\t}\n\t\n\tpublic List<Type> getListOfAllTypes() {\n\t\tList<Type> result = new LinkedList<>();\n\t\tresult.addAll(this.typeMap.values());\n\t\treturn result;\n\t}\n\n\tpublic void merge(TypeModule typeModule) {\n\t\tfor (Type otherType : typeModule.getAllTypes()) {\n\t\t\tthis.getType(otherType.getName());\n\t\t}\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder sb = new StringBuilder();\n\n\t\tfor (Type type : this.typeMap.values()) {\n\t\t\tsb.append(type);\n\t\t\tsb.append(\"\\n\");\n\t\t}\n\n\t\treturn sb.toString();\n\t}\n\n\tpublic void setConstantType(String constant, Type type) {\n\t\tconstants.put(constant, new ConstantParam(constant, type));\n\t}\n\t\n\tpublic Type getConstantType(String constant) {\n\t\tif (!constants.containsKey(constant))\n\t\t\tthrow new IllegalArgumentException(\"Constant \" + constant + \" not found!\");\n\t\treturn constants.get(constant).getType();\n\t}\n\n\tpublic Collection<ConstantParam> getConstants() {\n\t\treturn constants.values();\n\t}\n}\n" }, { "alpha_fraction": 0.6790611743927002, "alphanum_fraction": 0.6834689378738403, "avg_line_length": 30.118406295776367, "blob_id": "efbb3c1281a62f4895fde45cf5ec9e4643823de5", "content_id": "f1a3366195c3b951026e241c54c07e62844b47da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 26544, "license_type": "no_license", "max_line_length": 197, "num_lines": 853, "path": "/JAICore/jaicore-basic/src/jaicore/basic/chunks/TaskChunk.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.basic.chunks;\n\nimport java.io.BufferedReader;\nimport java.io.BufferedWriter;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.io.Serializable;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\nimport org.apache.commons.math3.exception.NumberIsTooSmallException;\nimport org.apache.commons.math3.stat.descriptive.StatisticalSummaryValues;\nimport org.apache.commons.math3.stat.inference.MannWhitneyUTest;\nimport org.apache.commons.math3.stat.inference.TTest;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport jaicore.basic.FileUtil;\nimport jaicore.basic.ListHelper;\nimport jaicore.basic.Maps;\nimport jaicore.basic.StatisticsUtil;\nimport jaicore.basic.kvstore.IKVFilter;\nimport jaicore.basic.kvstore.SimpleKVStore;\nimport jaicore.basic.kvstore.SimpleKVStoreCollection;\n\npublic class TaskChunk<V extends Task> extends SimpleKVStore implements Iterable<V>, Serializable {\n\n\tprivate static final Logger LOGGER = LoggerFactory.getLogger(TaskChunk.class);\n\n\tpublic enum EGroupMethod {\n\t\tAVG, MIN, MAX, MAJORITY, MINORITY, LIST, ADD;\n\t}\n\n\t/**\n\t *\n\t */\n\tprivate static final long serialVersionUID = 608124601390225228L;\n\n\tprivate static final EGroupMethod STANDARD_GROUPING_HANDLER = EGroupMethod.LIST;\n\n\tprivate List<V> taskList = new LinkedList<>();\n\n\tpublic TaskChunk(final String taskChunkDescription) {\n\t\tthis.readFrom(taskChunkDescription);\n\t}\n\n\tpublic TaskChunk(final TaskChunk<V> other) {\n\t\tthis.getKeyValueMap().putAll(other.getKeyValueMap());\n\t\tthis.taskList.addAll(other.taskList);\n\t}\n\n\tpublic TaskChunk(final File file) {\n\t\tif (file.isDirectory()) {\n\t\t\tthis.setChunkID(file.getName());\n\t\t\tfor (File subFile : file.listFiles()) {\n\t\t\t\tif (subFile.isFile()) {\n\t\t\t\t\ttry (BufferedReader br = new BufferedReader(new FileReader(subFile))) {\n\t\t\t\t\t\tString line;\n\t\t\t\t\t\twhile ((line = br.readLine()) != null) {\n\t\t\t\t\t\t\tV task = this.convertLineToTask(line);\n\t\t\t\t\t\t\ttask.setChunk(this);\n\t\t\t\t\t\t\tthis.taskList.add(task);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\tLOGGER.error(\"An exception occurred while parsing the directory collecting the chunk: {}\", e);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.readFrom(FileUtil.readFileAsString(file));\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\tLOGGER.error(\"An exception occurred while reading the chunk from the given file: {}\", e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic TaskChunk(final Map<String, String> chunkMetaInformation) {\n\t\tsuper(chunkMetaInformation);\n\t\tthis.taskList = new LinkedList<>();\n\t}\n\n\tpublic TaskChunk(final Map<String, String> chunkMetaInformation, final List<V> taskList) {\n\t\tthis(chunkMetaInformation);\n\t\tthis.taskList.addAll(taskList);\n\t}\n\n\t@Override\n\tpublic Iterator<V> iterator() {\n\t\treturn this.taskList.iterator();\n\t}\n\n\tpublic synchronized void add(final V task) {\n\t\tthis.taskList.add(task);\n\t}\n\n\tpublic synchronized void addAll(final Collection<V> task) {\n\t\tthis.taskList.addAll(task);\n\t}\n\n\tpublic synchronized void addAll(final TaskChunk<V> otherChunk) {\n\t\tfor (V v : otherChunk) {\n\t\t\tthis.add(v);\n\t\t}\n\t}\n\n\tpublic Stream<V> stream() {\n\t\treturn this.taskList.stream();\n\t}\n\n\tpublic V remove(final int index) {\n\t\treturn this.taskList.remove(index);\n\t}\n\n\tpublic boolean remove(final V task) {\n\t\treturn this.taskList.remove(task);\n\t}\n\n\tpublic int size() {\n\t\treturn this.taskList.size();\n\t}\n\n\tpublic V get(final int index) {\n\t\treturn this.taskList.get(index);\n\t}\n\n\tpublic Collection<V> getAll() {\n\t\treturn this.taskList;\n\t}\n\n\tpublic void sort(final Comparator<V> comparator) {\n\t\tCollections.sort(this.taskList, comparator);\n\t}\n\n\t/** META data */\n\tprivate static final String FIELD_CHUNKID = \"chunkID\";\n\n\tpublic String getChunkID() {\n\t\treturn this.getValueAsString(FIELD_CHUNKID);\n\t}\n\n\tpublic void setChunkID(final String chunkID) {\n\t\tthis.store(FIELD_CHUNKID, chunkID);\n\t}\n\n\t/** (De-)Serialization handles */\n\tpublic void readFrom(final String chunkDescription) {\n\t\tString[] lines = chunkDescription.split(\"\\n\");\n\t\tif (lines.length < 1) {\n\t\t\tthrow new IllegalArgumentException(\"Invalid format of chunk description\");\n\t\t}\n\n\t\tboolean first = true;\n\t\tfor (String line : lines) {\n\t\t\tif (line.trim().equals(\"\") || line.trim().startsWith(\"#\")) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (first) {\n\t\t\t\t// first line in chunk description being no white line nor comment\n\t\t\t\t// such a line must carry all the meta information of the chunk!\n\t\t\t\tfirst = false;\n\t\t\t\tthis.readKVStoreFromDescription(line);\n\t\t\t} else {\n\t\t\t\tV task = this.convertLineToTask(line);\n\t\t\t\ttask.setChunk(this);\n\t\t\t\tthis.taskList.add(task);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic String getStringRepresentation() {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tsb.append(super.getStringRepresentation() + \"\\n\");\n\t\tfor (Task t : this.taskList) {\n\t\t\tsb.append(t.getStringRepresentation() + \"\\n\");\n\t\t}\n\t\treturn sb.toString();\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder sb = new StringBuilder();\n\n\t\tboolean first = true;\n\t\tfor (Entry<String, String> metaDataEntry : this.getAllKVEntries()) {\n\t\t\tif (first) {\n\t\t\t\tfirst = false;\n\t\t\t} else {\n\t\t\t\tsb.append(\";\");\n\t\t\t}\n\t\t\tsb.append(metaDataEntry.getKey() + \"=\" + metaDataEntry.getValue());\n\t\t}\n\t\tsb.append(\"\\n\");\n\n\t\tfor (Task task : this.taskList) {\n\t\t\tsb.append(task.toString() + \"\\n\");\n\t\t}\n\n\t\treturn sb.toString();\n\t}\n\n\t/**\n\t * Hook for Override in special instances of TaskChunk.\n\t *\n\t * @param line\n\t * @return\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic V convertLineToTask(final String line) {\n\t\treturn (V) new Task(line);\n\t}\n\n\tpublic V getTaskWithID(final String taskID) {\n\t\tfor (V task : this) {\n\t\t\tif (task.getTaskID().equals(taskID)) {\n\t\t\t\treturn task;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic void removeAny(final String value) {\n\t\tthis.removeAny(new String[] { value }, true);\n\t}\n\n\tpublic void removeAny(final String[] value, final boolean or) {\n\t\tList<Task> tasksToRemove = new LinkedList<>();\n\t\tfor (Task t : this.taskList) {\n\t\t\tif (or) {\n\t\t\t\tfor (String v : value) {\n\t\t\t\t\tif (t.getStringRepresentation().contains(v)) {\n\t\t\t\t\t\ttasksToRemove.add(t);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthrow new UnsupportedOperationException(\"Not yet implemented\");\n\t\t\t}\n\t\t}\n\n\t\tthis.taskList.removeAll(tasksToRemove);\n\t}\n\n\tpublic void removeAny(final Map<String, String> condition, final boolean or) {\n\t\tif (or) {\n\t\t\tthis.taskList.removeIf(t -> {\n\t\t\t\tfor (String key : condition.keySet()) {\n\t\t\t\t\tString val = t.getValueAsString(key);\n\t\t\t\t\tif (val == null && condition.get(key) == null || val != null && val.equals(condition.get(key))) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t});\n\t\t} else {\n\t\t\tthis.taskList.removeIf(t -> {\n\t\t\t\tfor (String key : condition.keySet()) {\n\t\t\t\t\tif (!t.getValueAsString(key).equals(condition.get(key))) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t});\n\t\t}\n\t}\n\n\tpublic void removeGroupsIfNotAtLeastWithSize(final int size) {\n\t\tMap<String, String> groupSizeCondition = new HashMap<>();\n\t\tfor (int i = 1; i < size; i++) {\n\t\t\tgroupSizeCondition.put(\"GROUP_SIZE\", \"\" + i);\n\t\t\tthis.removeAny(groupSizeCondition, true);\n\t\t}\n\t}\n\n\tpublic void removeGroupsIfNotAtLeastWithSizeButOne(final int size, final String[] groupingKeys) {\n\n\t\tMap<String, String> groupSizeCondition = new HashMap<>();\n\t\tfor (int i = 1; i < size; i++) {\n\t\t\tSystem.out.println(\"Remove any groups that dont have at least \" + (i + 1) + \" entries.\");\n\n\t\t\tint currentMinLength = i;\n\t\t\tTaskChunk<V> group = new TaskChunk<>(this.getStringRepresentation());\n\t\t\tgroup.renameAttribute(\"GROUP_SIZE\", \"size\");\n\t\t\tgroup = group.group(groupingKeys, new HashMap<>());\n\n\t\t\tfor (V t : group) {\n\t\t\t\tList<Integer> sizeList = t.getValueAsIntList(\"size\", \",\").stream().filter(x -> x > currentMinLength).collect(Collectors.toList());\n\t\t\t\tSystem.out.println(currentMinLength + \" \" + sizeList + \" \" + t.getValueAsIntList(\"size\", \",\"));\n\t\t\t\tif (sizeList.size() > 0) {\n\t\t\t\t\tfor (String groupingKey : groupingKeys) {\n\t\t\t\t\t\tgroupSizeCondition.put(groupingKey, t.getValueAsString(groupingKey));\n\t\t\t\t\t}\n\t\t\t\t\tgroupSizeCondition.put(\"GROUP_SIZE\", \"\" + i);\n\t\t\t\t\tSystem.out.println(groupSizeCondition);\n\t\t\t\t\tthis.removeAny(groupSizeCondition, false);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void renameAttribute(final String attributeName, final String replacement) {\n\t\tfor (V t : this) {\n\t\t\tt.renameAttribute(attributeName, replacement);\n\t\t}\n\t}\n\n\tpublic TaskChunk<V> group(final String[] groupingKeys, final Map<String, EGroupMethod> groupingHandler) {\n\t\tTaskChunk<Task> tempChunk = new TaskChunk<>(this.getKeyValueMap());\n\t\ttempChunk.setChunkID(this.getChunkID());\n\t\tMap<String, List<V>> groupedTasks = new HashMap<>();\n\n\t\tfor (V t : this) {\n\t\t\tStringBuilder sb = new StringBuilder();\n\t\t\tfor (String key : groupingKeys) {\n\t\t\t\tsb.append(t.getValueAsString(key) + \"#\");\n\t\t\t}\n\n\t\t\tList<V> groupedTaskList = groupedTasks.get(sb.toString());\n\t\t\tif (groupedTaskList == null) {\n\t\t\t\tgroupedTaskList = new LinkedList<>();\n\t\t\t\tgroupedTasks.put(sb.toString(), groupedTaskList);\n\t\t\t}\n\n\t\t\tgroupedTaskList.add(t);\n\t\t}\n\n\t\tfor (Entry<String, List<V>> groupedTaskEntry : groupedTasks.entrySet()) {\n\t\t\tList<V> groupedTaskList = groupedTaskEntry.getValue();\n\t\t\tTask groupedTask = groupedTaskList.get(0).clone();\n\t\t\tgroupedTask.store(\"GROUP_SIZE\", groupedTaskList.size() + \"\");\n\n\t\t\tMap<String, List<Object>> values = new HashMap<>();\n\n\t\t\tfor (V t : groupedTaskList) {\n\t\t\t\tfor (Entry<String, String> e : t.getAllKVEntries()) {\n\t\t\t\t\tboolean containedInGrouping = false;\n\t\t\t\t\tfor (String groupingKey : groupingKeys) {\n\t\t\t\t\t\tif (groupingKey.equals(e.getKey())) {\n\t\t\t\t\t\t\tcontainedInGrouping = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (containedInGrouping) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tObject value;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tvalue = Integer.parseInt(e.getValue());\n\n\t\t\t\t\t} catch (Exception noInt) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tvalue = Long.parseLong(e.getValue());\n\t\t\t\t\t\t} catch (Exception noLong) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tvalue = Double.parseDouble(e.getValue());\n\t\t\t\t\t\t\t} catch (Exception exception2) {\n\t\t\t\t\t\t\t\tvalue = e.getValue();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tList<Object> objectList = values.get(e.getKey());\n\t\t\t\t\tif (objectList == null) {\n\t\t\t\t\t\tobjectList = new LinkedList<>();\n\t\t\t\t\t\tvalues.put(e.getKey(), objectList);\n\t\t\t\t\t}\n\t\t\t\t\tobjectList.add(value);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (Entry<String, List<Object>> valueEntry : values.entrySet()) {\n\t\t\t\tEGroupMethod groupingMethod = groupingHandler.get(valueEntry.getKey());\n\t\t\t\tif (groupingMethod == null) {\n\t\t\t\t\tgroupingMethod = STANDARD_GROUPING_HANDLER;\n\t\t\t\t}\n\n\t\t\t\tString value = \"\";\n\t\t\t\tswitch (groupingMethod) {\n\t\t\t\tcase AVG: {\n\t\t\t\t\tList<Double> valueList = valueEntry.getValue().stream().map(x -> Double.valueOf(x.toString())).collect(Collectors.toList());\n\t\t\t\t\tgroupedTask.store(valueEntry.getKey() + \"_stdDev\", StatisticsUtil.standardDeviation(valueList) + \"\");\n\t\t\t\t\t// groupedTask.store(valueEntry.getKey() + \"_max\", StatisticsUtil.max(valueList) + \"\");\n\t\t\t\t\t// groupedTask.store(valueEntry.getKey() + \"_min\", StatisticsUtil.min(valueList) + \"\");\n\t\t\t\t\t// groupedTask.store(valueEntry.getKey() + \"_var\", StatisticsUtil.variance(valueList) + \"\");\n\t\t\t\t\t// groupedTask.store(valueEntry.getKey() + \"_sum\", StatisticsUtil.sum(valueList) + \"\");\n\t\t\t\t\tvalue = StatisticsUtil.mean(valueList) + \"\";\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase MIN: {\n\t\t\t\t\tList<Double> valueList = valueEntry.getValue().stream().map(x -> Double.valueOf(x.toString())).collect(Collectors.toList());\n\t\t\t\t\tvalue = StatisticsUtil.min(valueList) + \"\";\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase MAX: {\n\t\t\t\t\tList<Double> valueList = valueEntry.getValue().stream().map(x -> Double.valueOf(x.toString())).collect(Collectors.toList());\n\t\t\t\t\tvalue = StatisticsUtil.max(valueList) + \"\";\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase MINORITY: {\n\t\t\t\t\tMap<Object, Integer> counterMap = new HashMap<>();\n\t\t\t\t\tfor (Object v : valueEntry.getValue()) {\n\t\t\t\t\t\tMaps.increaseCounterInMap(counterMap, v);\n\t\t\t\t\t}\n\n\t\t\t\t\tObject minorityObject = null;\n\t\t\t\t\tfor (Object object : counterMap.keySet()) {\n\t\t\t\t\t\tif (minorityObject == null || counterMap.get(object) < counterMap.get(minorityObject)) {\n\t\t\t\t\t\t\tminorityObject = object;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tvalue = minorityObject + \"\";\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase MAJORITY: {\n\t\t\t\t\tMap<Object, Integer> counterMap = new HashMap<>();\n\t\t\t\t\tfor (Object v : valueEntry.getValue()) {\n\t\t\t\t\t\tMaps.increaseCounterInMap(counterMap, v);\n\t\t\t\t\t}\n\n\t\t\t\t\tObject minorityObject = null;\n\t\t\t\t\tfor (Object object : counterMap.keySet()) {\n\t\t\t\t\t\tif (minorityObject == null || counterMap.get(object) > counterMap.get(minorityObject)) {\n\t\t\t\t\t\t\tminorityObject = object;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tvalue = minorityObject + \"\";\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase ADD: {\n\t\t\t\t\tList<Double> valueList = valueEntry.getValue().stream().map(x -> Double.valueOf(x.toString())).collect(Collectors.toList());\n\t\t\t\t\tvalue = StatisticsUtil.sum(valueList) + \"\";\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\tcase LIST: {\n\t\t\t\t\tvalue = ListHelper.implode(valueEntry.getValue(), \",\");\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tgroupedTask.store(valueEntry.getKey(), value);\n\t\t\t}\n\t\t\ttempChunk.add(groupedTask);\n\t\t}\n\n\t\treturn new TaskChunk<>(tempChunk.getStringRepresentation());\n\t}\n\n\tpublic void implode(final String[] fieldKeys, final String separator, final String newFieldName) {\n\t\tfor (V t : this) {\n\t\t\tt.implode(fieldKeys, separator, newFieldName);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void project(final String[] keepKeys) {\n\t\tfor (V t : this) {\n\t\t\tt.project(keepKeys);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void projectRemove(final String[] removeKeys) {\n\t\tsuper.projectRemove(removeKeys);\n\n\t\tfor (V t : this) {\n\t\t\tt.projectRemove(removeKeys);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void applyFilter(final Map<String, IKVFilter> filterMap) {\n\t\tsuper.applyFilter(filterMap);\n\t\tfor (V t : this) {\n\t\t\tt.applyFilter(filterMap);\n\t\t}\n\t}\n\n\tpublic SimpleKVStoreCollection toKVStoreCollection() {\n\t\tSimpleKVStoreCollection collection = new SimpleKVStoreCollection();\n\t\tcollection.addAll(this.taskList);\n\t\treturn collection;\n\t}\n\n\tpublic TaskChunk<V> select(final Map<String, String> selection) {\n\t\tTaskChunk<V> chunk = new TaskChunk<>(this.getStringRepresentation());\n\t\tSet<V> selectedCollection = new HashSet<>();\n\n\t\tfor (V t : chunk) {\n\t\t\tif (!t.matches(selection)) {\n\t\t\t\tselectedCollection.add(t);\n\t\t\t}\n\t\t}\n\t\tchunk.taskList.removeAll(selectedCollection);\n\t\treturn chunk;\n\t}\n\n\tpublic void removeAll(final List<Task> tasksToRemove) {\n\t\tthis.taskList.removeAll(tasksToRemove);\n\t}\n\n\tpublic void removeAll(final TaskChunk<V> removeChunk) {\n\t\tthis.taskList.removeAll(removeChunk.taskList);\n\t}\n\n\tpublic void mergeTasks(final Task other, final Map<String, String> combineMap) {\n\t\tfor (Task t : this) {\n\n\t\t\tboolean equals = true;\n\t\t\tfor (Entry<String, String> combineEntry : combineMap.entrySet()) {\n\t\t\t\tif (!t.containsKey(combineEntry.getKey()) || !other.containsKey(combineEntry.getValue()) || !t.getValueAsString(combineEntry.getKey()).equals(other.getValueAsString(combineEntry.getValue()))) {\n\t\t\t\t\tequals = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!equals) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tt.getKeyValueMap().putAll(other.getKeyValueMap());\n\t\t}\n\t}\n\n\tpublic void mannWhitneyU(final String keyFieldName, final String comparatorFieldName, final String valueListFieldName, final String groundTruth) {\n\t\tMap<String, Task> groundTruthMap = new HashMap<>();\n\t\tMap<String, List<Task>> comparedWithMap = new HashMap<>();\n\n\t\tfor (Task t : this) {\n\t\t\tString key = t.getValueAsString(keyFieldName);\n\t\t\tString comparator = t.getValueAsString(comparatorFieldName);\n\n\t\t\tif (comparator.equals(groundTruth)) {\n\t\t\t\tgroundTruthMap.put(key, t);\n\t\t\t} else {\n\t\t\t\tList<Task> taskList = comparedWithMap.get(key);\n\t\t\t\tif (taskList == null) {\n\t\t\t\t\ttaskList = new LinkedList<>();\n\t\t\t\t\tcomparedWithMap.put(key, taskList);\n\t\t\t\t}\n\t\t\t\ttaskList.add(t);\n\t\t\t}\n\t\t}\n\n\t\tfor (Entry<String, Task> groundTruthEntry : groundTruthMap.entrySet()) {\n\t\t\tgroundTruthEntry.getValue().store(\"mwu\", \"\");\n\t\t\tList<Task> toCompareWithList = comparedWithMap.get(groundTruthEntry.getKey());\n\n\t\t\tif (toCompareWithList != null) {\n\t\t\t\tList<Double> groundTruthList = groundTruthEntry.getValue().getValueAsDoubleList(valueListFieldName, \",\");\n\t\t\t\tdouble gtMean = StatisticsUtil.mean(groundTruthList);\n\n\t\t\t\tfor (Task taskToCompareWith : toCompareWithList) {\n\t\t\t\t\tList<Double> compareWithValues = taskToCompareWith.getValueAsDoubleList(valueListFieldName, \",\");\n\n\t\t\t\t\tboolean sig = StatisticsUtil.mannWhitneyTwoSidedSignificance(groundTruthList, compareWithValues);\n\n\t\t\t\t\tif (groundTruthEntry.getKey().equals(\"dexter\")) {\n\t\t\t\t\t\tSystem.out.println(groundTruthEntry.getKey());\n\t\t\t\t\t\tSystem.out.println(groundTruthEntry.getValue());\n\t\t\t\t\t\t// System.out.println(toCompareWithList);\n\t\t\t\t\t\t// System.out.println(toCompareWithList.size());\n\t\t\t\t\t\tSystem.out.println(taskToCompareWith);\n\t\t\t\t\t\tSystem.out.println(sig);\n\n\t\t\t\t\t\tdouble[] valuesAArray = groundTruthList.stream().mapToDouble(x -> x).toArray();\n\t\t\t\t\t\tdouble[] valuesBArray = compareWithValues.stream().mapToDouble(x -> x).toArray();\n\t\t\t\t\t\tMannWhitneyUTest test = new MannWhitneyUTest();\n\t\t\t\t\t\tdouble p = test.mannWhitneyUTest(valuesAArray, valuesBArray);\n\t\t\t\t\t\tSystem.out.println(\"p-Value: \" + p);\n\t\t\t\t\t\tSystem.out.println(\"###\");\n\t\t\t\t\t}\n\n\t\t\t\t\tif (sig && gtMean < StatisticsUtil.mean(compareWithValues)) {\n\t\t\t\t\t\ttaskToCompareWith.store(\"mwu\", \"impr\");\n\t\t\t\t\t} else if (sig && gtMean > StatisticsUtil.mean(compareWithValues)) {\n\t\t\t\t\t\ttaskToCompareWith.store(\"mwu\", \"deg\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttaskToCompareWith.store(\"mwu\", \"eq\");\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic void best(final String keyFieldName, final String comparatorFieldName, final String valueFieldName) {\n\t\tthis.best(keyFieldName, comparatorFieldName, valueFieldName, \"best\");\n\t}\n\n\tpublic void best(final String keyFieldName, final String comparatorFieldName, final String valueFieldName, final String outputFieldName) {\n\t\tMap<String, List<Task>> comparedWithMap = new HashMap<>();\n\n\t\tfor (Task t : this) {\n\t\t\tString key = t.getValueAsString(keyFieldName);\n\t\t\tList<Task> taskList = comparedWithMap.get(key);\n\t\t\tif (taskList == null) {\n\t\t\t\ttaskList = new LinkedList<>();\n\t\t\t\tcomparedWithMap.put(key, taskList);\n\t\t\t}\n\t\t\ttaskList.add(t);\n\t\t}\n\n\t\tfor (Entry<String, List<Task>> groundTruthEntry : comparedWithMap.entrySet()) {\n\t\t\tTask bestTask = null;\n\t\t\tfor (Task taskToCompareWith : groundTruthEntry.getValue()) {\n\t\t\t\tif (bestTask == null) {\n\t\t\t\t\tbestTask = taskToCompareWith;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tdouble meanBest = StatisticsUtil.mean(bestTask.getValueAsDoubleList(valueFieldName, \",\"));\n\t\t\t\tdouble meanToCompareWith = StatisticsUtil.mean(taskToCompareWith.getValueAsDoubleList(valueFieldName, \",\"));\n\n\t\t\t\tif (meanToCompareWith < meanBest) {\n\t\t\t\t\tbestTask = taskToCompareWith;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (Task t : comparedWithMap.get(groundTruthEntry.getKey())) {\n\t\t\t\tif (t.getValueAsString(valueFieldName).equals(bestTask.getValueAsString(valueFieldName))) {\n\t\t\t\t\tt.store(outputFieldName, \"true\");\n\t\t\t\t} else {\n\t\t\t\t\tt.store(outputFieldName, \"false\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic void singleBest(final String keyFieldName, final String comparatorFieldName, final String valueFieldName) {\n\t\tthis.singleBest(keyFieldName, comparatorFieldName, valueFieldName, \"best\");\n\t}\n\n\tpublic void singleBest(final String keyFieldName, final String comparatorFieldName, final String valueFieldName, final String outputFieldName) {\n\t\tthis.best(keyFieldName, comparatorFieldName, valueFieldName, outputFieldName);\n\t\tList<V> distinctTasks = new ArrayList<>();\n\t\tSet<String> consideredKeys = new HashSet<>();\n\t\tthis.taskList.forEach(t -> {\n\t\t\tString keyValue = t.getValueAsString(keyFieldName);\n\t\t\tif (!consideredKeys.contains(keyValue) && t.getValueAsBoolean(outputFieldName)) {\n\t\t\t\tconsideredKeys.add(keyValue);\n\t\t\t\tdistinctTasks.add(t);\n\t\t\t}\n\t\t});\n\t\tthis.taskList = distinctTasks;\n\t}\n\n\tpublic void best(final String keyFieldName, final String comparatorFieldName, final String valueFieldName, final Set<String> compareObjects) {\n\t\tMap<String, List<Task>> comparedWithMap = new HashMap<>();\n\n\t\tfor (Task t : this) {\n\t\t\tString key = t.getValueAsString(keyFieldName);\n\t\t\tString object = t.getValueAsString(comparatorFieldName);\n\n\t\t\tif (!compareObjects.contains(object)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tList<Task> taskList = comparedWithMap.get(key);\n\t\t\tif (taskList == null) {\n\t\t\t\ttaskList = new LinkedList<>();\n\t\t\t\tcomparedWithMap.put(key, taskList);\n\t\t\t}\n\t\t\ttaskList.add(t);\n\t\t}\n\n\t\tfor (Entry<String, List<Task>> groundTruthEntry : comparedWithMap.entrySet()) {\n\t\t\tTask bestTask = null;\n\t\t\tfor (Task taskToCompareWith : groundTruthEntry.getValue()) {\n\t\t\t\tif (bestTask == null) {\n\t\t\t\t\tbestTask = taskToCompareWith;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tdouble meanBest = bestTask.getValueAsDouble(valueFieldName);\n\t\t\t\tdouble meanToCompareWith = taskToCompareWith.getValueAsDouble(valueFieldName);\n\n\t\t\t\tif (meanToCompareWith < meanBest) {\n\t\t\t\t\tbestTask = taskToCompareWith;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (Task t : comparedWithMap.get(groundTruthEntry.getKey())) {\n\t\t\t\tif (t == bestTask) {\n\t\t\t\t\tt.store(\"best\", \"true\");\n\t\t\t\t} else {\n\t\t\t\t\tt.store(\"best\", \"false\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic void bestTTest(final String keyFN, final String idFN, final String valueListFN, final String sigOutputFN) {\n\t\tthis.best(keyFN, idFN, valueListFN, sigOutputFN + \"_best\");\n\t\tMap<String, Task> groundTruthMap = new HashMap<>();\n\t\tMap<String, List<Task>> comparedWithMap = new HashMap<>();\n\n\t\tfor (Task t : this) {\n\t\t\tString key = t.getValueAsString(keyFN);\n\t\t\tif (t.getValueAsBoolean(sigOutputFN + \"_best\")) {\n\t\t\t\tgroundTruthMap.put(key, t);\n\t\t\t} else {\n\t\t\t\tList<Task> taskList = comparedWithMap.get(key);\n\t\t\t\tif (taskList == null) {\n\t\t\t\t\ttaskList = new LinkedList<>();\n\t\t\t\t\tcomparedWithMap.put(key, taskList);\n\t\t\t\t}\n\t\t\t\ttaskList.add(t);\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(comparedWithMap);\n\t\tfor (Entry<String, Task> groundTruthEntry : groundTruthMap.entrySet()) {\n\t\t\tTask gtT = groundTruthEntry.getValue();\n\t\t\tgtT.store(sigOutputFN, \"\");\n\t\t\tList<Task> toCompareWithList = comparedWithMap.get(groundTruthEntry.getKey());\n\n\t\t\tif (toCompareWithList != null) {\n\t\t\t\tList<Double> valueDoubleList = gtT.getValueAsDoubleList(valueListFN, \",\");\n\t\t\t\tdouble mean1 = StatisticsUtil.mean(valueDoubleList);\n\t\t\t\tdouble variance1 = StatisticsUtil.variance(valueDoubleList);\n\t\t\t\tdouble max1 = StatisticsUtil.max(valueDoubleList);\n\t\t\t\tdouble min1 = StatisticsUtil.min(valueDoubleList);\n\t\t\t\tdouble sum1 = StatisticsUtil.sum(valueDoubleList);\n\n\t\t\t\tfor (Task taskToCompareWith : toCompareWithList) {\n\t\t\t\t\tList<Double> valueDoubleList2 = taskToCompareWith.getValueAsDoubleList(valueListFN, \",\");\n\t\t\t\t\tdouble mean2 = StatisticsUtil.mean(valueDoubleList2);\n\t\t\t\t\tdouble variance2 = StatisticsUtil.variance(valueDoubleList2);\n\t\t\t\t\tdouble max2 = StatisticsUtil.max(valueDoubleList2);\n\t\t\t\t\tdouble min2 = StatisticsUtil.min(valueDoubleList2);\n\t\t\t\t\tdouble sum2 = StatisticsUtil.sum(valueDoubleList2);\n\n\t\t\t\t\tTTest test = new TTest();\n\t\t\t\t\tStatisticalSummaryValues summaryGT = new StatisticalSummaryValues(mean1, variance1, 20, max1, min1, sum1);\n\t\t\t\t\tStatisticalSummaryValues summaryComp = new StatisticalSummaryValues(mean2, variance2, 20, max2, min2, sum2);\n\t\t\t\t\tboolean sig = test.tTest(summaryGT, summaryComp, 0.05);\n\n\t\t\t\t\tif (sig && mean1 < mean2) {\n\t\t\t\t\t\ttaskToCompareWith.store(sigOutputFN, \"impr\");\n\t\t\t\t\t} else if (sig && mean1 > mean2) {\n\t\t\t\t\t\ttaskToCompareWith.store(sigOutputFN, \"deg\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttaskToCompareWith.store(sigOutputFN, \"eq\");\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic void tTest(final String keyFN, final String idFN, final String valueListFN, final String comparator, final String sigOutputFN) {\n\t\tMap<String, Task> groundTruthMap = new HashMap<>();\n\t\tMap<String, List<Task>> comparedWithMap = new HashMap<>();\n\n\t\tfor (Task t : this) {\n\t\t\tString key = t.getValueAsString(keyFN);\n\t\t\tString compareTo = t.getValueAsString(idFN);\n\n\t\t\tif (compareTo.equals(comparator)) {\n\t\t\t\tgroundTruthMap.put(key, t);\n\t\t\t} else {\n\t\t\t\tList<Task> taskList = comparedWithMap.get(key);\n\t\t\t\tif (taskList == null) {\n\t\t\t\t\ttaskList = new LinkedList<>();\n\t\t\t\t\tcomparedWithMap.put(key, taskList);\n\t\t\t\t}\n\t\t\t\ttaskList.add(t);\n\t\t\t}\n\t\t}\n\n\t\tfor (Entry<String, Task> groundTruthEntry : groundTruthMap.entrySet()) {\n\t\t\tTask gtT = groundTruthEntry.getValue();\n\t\t\tgtT.store(sigOutputFN, \"\");\n\t\t\tList<Task> toCompareWithList = comparedWithMap.get(groundTruthEntry.getKey());\n\n\t\t\tif (toCompareWithList != null) {\n\t\t\t\tList<Double> valueList1 = gtT.getValueAsDoubleList(valueListFN, \",\");\n\t\t\t\tdouble mean1 = StatisticsUtil.mean(valueList1);\n\t\t\t\tdouble variance1 = StatisticsUtil.variance(valueList1);\n\t\t\t\tdouble max1 = StatisticsUtil.max(valueList1);\n\t\t\t\tdouble min1 = StatisticsUtil.min(valueList1);\n\t\t\t\tdouble sum1 = StatisticsUtil.sum(valueList1);\n\t\t\t\tint n1 = valueList1.size();\n\t\t\t\tString name1 = gtT.getValueAsString(idFN);\n\n\t\t\t\tfor (Task taskToCompareWith : toCompareWithList) {\n\t\t\t\t\tList<Double> valueList2 = taskToCompareWith.getValueAsDoubleList(valueListFN, \",\");\n\t\t\t\t\tdouble mean2 = StatisticsUtil.mean(valueList2);\n\t\t\t\t\tdouble variance2 = StatisticsUtil.variance(valueList2);\n\t\t\t\t\tint n2 = valueList2.size();\n\t\t\t\t\tdouble max2 = StatisticsUtil.max(valueList2);\n\t\t\t\t\tdouble min2 = StatisticsUtil.min(valueList2);\n\t\t\t\t\tdouble sum2 = StatisticsUtil.sum(valueList2);\n\t\t\t\t\tString name2 = taskToCompareWith.getValueAsString(idFN);\n\n\t\t\t\t\tboolean sig;\n\t\t\t\t\tTTest test = new TTest();\n\t\t\t\t\tStatisticalSummaryValues summaryGT = new StatisticalSummaryValues(mean1, variance1, n1, max1, min1, sum1);\n\t\t\t\t\tStatisticalSummaryValues summaryComp = new StatisticalSummaryValues(mean2, variance2, n2, max2, min2, sum2);\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsig = test.tTest(summaryGT, summaryComp, 0.05);\n\t\t\t\t\t} catch (NumberIsTooSmallException e) {\n\t\t\t\t\t\tSystem.out.println(\"Cannot apply ttest for dataset \" + groundTruthEntry.getKey() + \" and comparison of \" + name1 + \" and \" + name2);\n\t\t\t\t\t\tSystem.out.println(summaryGT);\n\t\t\t\t\t\tSystem.out.println(summaryComp);\n\t\t\t\t\t\tthrow e;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (sig && mean1 < mean2) {\n\t\t\t\t\t\ttaskToCompareWith.store(sigOutputFN, \"impr\");\n\t\t\t\t\t} else if (sig && mean1 > mean2) {\n\t\t\t\t\t\ttaskToCompareWith.store(sigOutputFN, \"deg\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttaskToCompareWith.store(sigOutputFN, \"eq\");\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void serializeTo(final File file) {\n\t\tthis.serializeTo(file, false);\n\t}\n\n\tpublic void serializeTo(final File file, final boolean append) {\n\t\ttry (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {\n\t\t\tbw.write(this.getStringRepresentation());\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n}\n" }, { "alpha_fraction": 0.656000018119812, "alphanum_fraction": 0.7400000095367432, "avg_line_length": 20.909090042114258, "blob_id": "5a55d789cf5285a10d6979cf7019a1e734148388", "content_id": "77f9cc6819f962ecc2e581fa6a415cad5994441e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 250, "license_type": "no_license", "max_line_length": 44, "num_lines": 11, "path": "/softwareconfiguration/mlplan/conf/automl/mlplan.properties", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "cpus = 8\r\nmemory = 8192\r\ntimeout = 5\r\nhasco.seed = 0\r\n\r\nhasco.random_completions.timeout_path = 2000\r\nhasco.random_completions.timeout_node = 6000\r\n\r\nhasco.blowup.selection = 1.3\r\nhasco.blowup.postprocess = 1.3\r\nhasco.selection.timeouttolerance = 0.2" }, { "alpha_fraction": 0.8075916171073914, "alphanum_fraction": 0.8075916171073914, "avg_line_length": 36.20000076293945, "blob_id": "d9010671a8edc7e27f2d5425b617451287de5e88", "content_id": "93337b7423e527e550f2005e693c041df772d271", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 764, "license_type": "no_license", "max_line_length": 147, "num_lines": 20, "path": "/JAICore/jaicore-search/test/jaicore/search/algorithms/standard/ORGraphSearchTester.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard;\r\n\r\nimport org.junit.Test;\r\n\r\nimport jaicore.basic.algorithm.GeneralAlgorithmTester;\r\nimport jaicore.search.core.interfaces.IGraphSearchFactory;\r\n\r\npublic abstract class ORGraphSearchTester<P, I, O, NSrc, ASrc, V extends Comparable<V>, NSearch, ASearch> extends GeneralAlgorithmTester<P, I, O> {\r\n\r\n\t@Test\r\n\tpublic abstract void testThatAnEventForEachPossibleSolutionIsEmittedInSimpleCall() throws Throwable;\r\n\r\n\t@Test\r\n\tpublic abstract void testThatAnEventForEachPossibleSolutionIsEmittedInParallelizedCall() throws Throwable;\r\n\r\n\t@Test\r\n\tpublic abstract void testThatIteratorReturnsEachPossibleSolution() throws Throwable;\r\n\t\r\n\tpublic abstract IGraphSearchFactory<I, O, NSrc,ASrc, V, NSearch,ASearch> getFactory();\r\n}\r\n" }, { "alpha_fraction": 0.7612819075584412, "alphanum_fraction": 0.7612819075584412, "avg_line_length": 36.29268264770508, "blob_id": "5b61bed1d145e494cc046659d6a1ad309c78a806", "content_id": "5f1c4f0f2eccf481fb3589602644e39b07f9fd03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1529, "license_type": "no_license", "max_line_length": 90, "num_lines": 41, "path": "/JAICore/jaicore-planning/src/jaicore/planning/model/conditional/CEAction.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.model.conditional;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport jaicore.logic.fol.structure.CNFFormula;\nimport jaicore.logic.fol.structure.ConstantParam;\nimport jaicore.logic.fol.structure.Monom;\nimport jaicore.logic.fol.structure.VariableParam;\nimport jaicore.planning.model.core.Action;\n\n@SuppressWarnings(\"serial\")\npublic class CEAction extends Action {\n\tpublic CEAction(CEOperation operation, Map<VariableParam, ConstantParam> grounding) {\n\t\tsuper(operation, grounding);\n\t}\n\n\tpublic Map<CNFFormula, Monom> getAddLists() {\n\t\tMap<CNFFormula, Monom> addLists = new HashMap<>();\n\t\tCEOperation operation = ((CEOperation)getOperation());\n\t\tMap<VariableParam, ConstantParam> grounding = getGrounding();\n\t\tfor (CNFFormula key : operation.getAddLists().keySet()) {\n\t\t\tCNFFormula condition = new CNFFormula(key, grounding);\n\t\t\tif (!condition.isObviouslyContradictory())\n\t\t\t\taddLists.put(condition, new Monom(operation.getAddLists().get(key), grounding));\n\t\t}\n\t\treturn addLists;\n\t}\n\n\tpublic Map<CNFFormula, Monom> getDeleteLists() {\n\t\tCEOperation operation = ((CEOperation)getOperation());\n\t\tMap<VariableParam, ConstantParam> grounding = getGrounding();\n\t\tMap<CNFFormula, Monom> deleteLists = new HashMap<>();\n\t\tfor (CNFFormula key : operation.getDeleteLists().keySet()) {\n\t\t\tCNFFormula condition = new CNFFormula(key, grounding);\n\t\t\tif (!condition.isObviouslyContradictory())\n\t\t\t\tdeleteLists.put(condition, new Monom(operation.getDeleteLists().get(key), grounding));\n\t\t}\n\t\treturn deleteLists;\n\t}\n}\n" }, { "alpha_fraction": 0.6142302751541138, "alphanum_fraction": 0.6499353051185608, "avg_line_length": 39.11701965332031, "blob_id": "39925cf0c5e574864e55be5b99242007129fc525", "content_id": "68de4647a97cdcd2b1d30d167510d4370e1923b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3865, "license_type": "no_license", "max_line_length": 162, "num_lines": 94, "path": "/JAICore/jaicore-search/test/jaicore/search/algorithms/standard/bestfirst/npuzzle/parentDiscarding/ParentDiscardingTest.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.bestfirst.npuzzle.parentDiscarding;\r\n//package jaicore.search.algorithms.standard.bestfirst.npuzzle.parentDiscarding;\r\n//\r\n//import static org.junit.Assert.assertEquals;\r\n//import static org.junit.Assert.assertNotNull;\r\n//\r\n//import java.util.List;\r\n//\r\n//import org.junit.Test;\r\n//\r\n//import jaicore.basic.PerformanceLogger;\r\n//import jaicore.basic.PerformanceLogger.PerformanceMeasure;\r\n//import jaicore.graphvisualizer.SimpleGraphVisualizationWindow;\r\n//import jaicore.search.algorithms.EvaluatedSearchAlgorithmSolution;\r\n//import jaicore.search.algorithms.standard.astar.AStar;\r\n//import jaicore.search.algorithms.standard.bestfirst.BestFirst.ParentDiscarding;\r\n//import jaicore.search.algorithms.standard.bestfirst.model.Node;\r\n//import jaicore.search.testproblems.npuzzle.parentDiscarding.PDPuzzleGenerator;\r\n//import jaicore.search.testproblems.npuzzle.parentDiscarding.PDPuzzleNode;\r\n//\r\n//public class ParentDiscardingTest {\r\n//\r\n//\t@Test\r\n//\tpublic void test() throws InterruptedException {\r\n//\r\n//\t\tint board[][] = { { 1, 1, 1 }, { 0, 1, 1 }, { 1, 1, 1 } };\r\n//\t\tint board2[][] = { { 0, 1 }, { 1, 1 } };\r\n//\r\n//\t\tPDPuzzleGenerator gen = new PDPuzzleGenerator(board, 0, 1);\r\n//\t\tPDPuzzleGenerator gen2 = new PDPuzzleGenerator(board2, 0, 0);\r\n//\r\n//\t\tAStar<PDPuzzleNode, String> search = new AStar<>(gen, (n1, n2) -> {\r\n//\t\t\tif (n2.getPoint().getBoard()[0][0] == 0 || n2.getPoint().getBoard()[0][1] == 0 || n2.getPoint().getBoard()[0][2] == 0 || n2.getPoint().getBoard()[1][2] == 0)\r\n//\t\t\t\treturn Double.MAX_VALUE;\r\n//\t\t\tif (n1.getPoint().getBoard()[0][0] == 0 || n1.getPoint().getBoard()[0][1] == 0 || n1.getPoint().getBoard()[0][2] == 0 || n1.getPoint().getBoard()[1][2] == 0)\r\n//\t\t\t\treturn Double.MAX_VALUE;\r\n//\t\t\tif (n2.getPoint().getBoard()[1][1] == 0 || n1.getPoint().getBoard()[1][1] == 0)\r\n//\t\t\t\treturn 3.0;\r\n//\t\t\tif (n2.getPoint().getBoard()[2][0] == 0)\r\n//\t\t\t\treturn 4.0;\r\n//\t\t\tif (n2.getPoint().getBoard()[2][0] == 0 && n1.getPoint().getBoard()[1][0] == 0)\r\n//\t\t\t\treturn Double.MAX_VALUE;\r\n//\t\t\tif (n2.getPoint().getBoard()[2][2] == 0)\r\n//\t\t\t\treturn 10;\r\n//\t\t\telse\r\n//\t\t\t\treturn 1.0;\r\n//\t\t}, n -> {\r\n//\t\t\treturn 0.0;\r\n//\t\t}, ParentDiscarding.OPEN);\r\n//\r\n//\t\tAStar<PDPuzzleNode, String> search2 = new AStar<>(gen2, (n1, n2) -> {\r\n//\t\t\tdouble g = 0.0;\r\n//\t\t\tif (n2.getPoint().getBoard()[0][1] == 0)\r\n//\t\t\t\treturn 3.0;\r\n//\t\t\tif (n1.getPoint().getBoard()[0][1] == 0)\r\n//\t\t\t\treturn 3.0;\r\n//\t\t\tif (n2.getPoint().getBoard()[1][1] == 0)\r\n//\t\t\t\treturn 1.0;\r\n//\t\t\telse\r\n//\t\t\t\treturn 4.0;\r\n//\t\t}, n -> {\r\n//\t\t\treturn 0.0;\r\n//\t\t}, ParentDiscarding.ALL);\r\n//\r\n//\t\tSimpleGraphVisualizationWindow<Node<PDPuzzleNode, Double>> win = new SimpleGraphVisualizationWindow<>(search);\r\n//\t\twin.getPanel().setTooltipGenerator(n -> n.getPoint().toString());\r\n//\t\twin.setTitle(\"Search\");\r\n//\r\n//\t\tSimpleGraphVisualizationWindow<Node<PDPuzzleNode, Double>> win2 = new SimpleGraphVisualizationWindow<>(search2);\r\n//\t\twin2.getPanel().setTooltipGenerator(n -> n.getPoint().toString());\r\n//\t\twin2.setTitle(\"Search2\");\r\n//\r\n//\t\t/*search for solution*/\r\n//\t\tPerformanceLogger.logStart(\"search\");\r\n//\r\n//\t\tEvaluatedSearchAlgorithmSolution<PDPuzzleNode, String, Double> solution1 = search.nextSolution();\r\n//\t\tEvaluatedSearchAlgorithmSolution<PDPuzzleNode, String, Double> solution2 = search2.nextSolution();\r\n//\t\tsolution2 = search2.nextSolution();\r\n//\r\n//\t\tPerformanceLogger.logEnd(\"search\");\r\n//\t\tassertNotNull(solution1.getNodes());\r\n//\t\tassertNotNull(solution2.getNodes());\r\n//\r\n//\t\tassertEquals(3.0, solution2.getNodes().size(), 0.0);\r\n//\r\n//\t\tassert solution1.getNodes().size() <= 31;\r\n//\t\tSystem.out.println(solution1.getNodes().size());\r\n//\t\tSystem.out.println(\"Generated \" + search2.getCreatedCounter() + \" nodes.\");\r\n//\t\tPerformanceLogger.printStatsAndClear(PerformanceMeasure.TIME);\r\n//\t\twhile (true)\r\n//\t\t\t;\r\n//\t}\r\n//\r\n//}\r\n" }, { "alpha_fraction": 0.7822580933570862, "alphanum_fraction": 0.788306474685669, "avg_line_length": 29, "blob_id": "687e0fb675bc20e76c97922680602702980b76c7", "content_id": "d2a719784de4dd8cd3036ff8e613e6a5febc6d89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 496, "license_type": "no_license", "max_line_length": 97, "num_lines": 16, "path": "/softwareconfiguration/mlplan/examples/de/upb/crc901/mlplan/examples/multiclass/weka/MLPlanWekaExperimenterConfig.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package de.upb.crc901.mlplan.examples.multiclass.weka;\r\n\r\nimport org.aeonbits.owner.Config.Sources;\r\n\r\nimport jaicore.ml.experiments.IMultiClassClassificationExperimentConfig;\r\n\r\n@Sources({ \"file:conf/mlplan-weka-eval.properties\" })\r\npublic interface MLPlanWekaExperimenterConfig extends IMultiClassClassificationExperimentConfig {\r\n\r\n\tpublic static final String DB_EVAL_TABLE = \"db.evalTable\";\r\n\r\n\t@Key(DB_EVAL_TABLE)\r\n\t@DefaultValue(\"evaluations_mls\")\r\n\tpublic String evaluationsTable();\r\n\r\n}\r\n" }, { "alpha_fraction": 0.6571879982948303, "alphanum_fraction": 0.6598209738731384, "avg_line_length": 24.01369857788086, "blob_id": "bca5352f9a555ff61f160e370032a9caac527f74", "content_id": "e0c5cb9c271a1278cd0b6db89cc4c6bbba9a0681", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1899, "license_type": "no_license", "max_line_length": 155, "num_lines": 73, "path": "/softwareconfiguration/hasco/src/hasco/model/Dependency.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package hasco.model;\r\n\r\nimport java.util.Collection;\r\n\r\nimport jaicore.basic.sets.SetUtil.Pair;\r\n\r\npublic class Dependency {\r\n\tprivate final Collection<Collection<Pair<Parameter, ParameterDomain>>> premise; // semantics are DNF (every entry is an AND-connected constraint)\r\n\tprivate final Collection<Pair<Parameter, ParameterDomain>> conclusion;\r\n\r\n\tpublic Dependency(final Collection<Collection<Pair<Parameter, ParameterDomain>>> premise, final Collection<Pair<Parameter, ParameterDomain>> conclusion) {\r\n\t\tsuper();\r\n\t\tthis.premise = premise;\r\n\t\tthis.conclusion = conclusion;\r\n\t}\r\n\r\n\tpublic Collection<Collection<Pair<Parameter, ParameterDomain>>> getPremise() {\r\n\t\treturn this.premise;\r\n\t}\r\n\r\n\tpublic Collection<Pair<Parameter, ParameterDomain>> getConclusion() {\r\n\t\treturn this.conclusion;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + ((this.conclusion == null) ? 0 : this.conclusion.hashCode());\r\n\t\tresult = prime * result + ((this.premise == null) ? 0 : this.premise.hashCode());\r\n\t\treturn result;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean equals(final Object obj) {\r\n\t\tif (this == obj) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tif (obj == null) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tif (this.getClass() != obj.getClass()) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tDependency other = (Dependency) obj;\r\n\t\tif (this.conclusion == null) {\r\n\t\t\tif (other.conclusion != null) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t} else if (!this.conclusion.equals(other.conclusion)) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tif (this.premise == null) {\r\n\t\t\tif (other.premise != null) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t} else if (!this.premise.equals(other.premise)) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\tStringBuilder sb = new StringBuilder();\r\n\r\n\t\tsb.append(this.premise);\r\n\t\tsb.append(\" => \");\r\n\t\tsb.append(this.conclusion);\r\n\r\n\t\treturn sb.toString();\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6744765639305115, "alphanum_fraction": 0.6824526190757751, "avg_line_length": 32.58620834350586, "blob_id": "45e28ff918c0a1c93956af156396cd7e11bc7bea", "content_id": "1b9456e6d4491dc68054084376b31de458dc891a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2006, "license_type": "no_license", "max_line_length": 109, "num_lines": 58, "path": "/JAICore/jaicore-ml/src/jaicore/ml/classification/multiclass/reduction/PipelineOptimizer.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.ml.classification.multiclass.reduction;\r\n\r\nimport java.io.BufferedReader;\r\nimport java.io.File;\r\nimport java.io.FileReader;\r\nimport java.util.List;\r\nimport java.util.Random;\r\n\r\nimport jaicore.basic.MathExt;\r\nimport jaicore.ml.WekaUtil;\r\nimport jaicore.ml.classification.multiclass.reduction.reducer.ReductionOptimizer;\r\nimport weka.classifiers.Classifier;\r\nimport weka.classifiers.rules.OneR;\r\nimport weka.core.Instance;\r\nimport weka.core.Instances;\r\n\r\npublic class PipelineOptimizer {\r\n\t\r\n\tpublic static void main(String[] args) throws Exception {\r\n\t\tFile folder = new File(\"../CrcTaskBasedConfigurator/testrsc/polychotomous/\");\r\n\t\tInstances inst = new Instances(new BufferedReader(new FileReader(folder + File.separator + \"vowel.arff\")));\r\n\t\tinst.setClassIndex(inst.numAttributes() -1);\r\n\t\t\r\n\t\tClassifier mcc = new OneR();\r\n//\t\tmcc.setClassifier(new IBk());\r\n\t\t\r\n\t\tString classifierName = \"weka.classifiers.trees.RandomForest\";\r\n\t\t\r\n\t\tfor (int i = 0; i < inst.classAttribute().numValues(); i++)\r\n\t\t\tSystem.out.println(i + \": \" + inst.classAttribute().value(i));\r\n\t\t\r\n\t\tfor (int j = 0; j < 1; j++) {\r\n\t\t\tRandom rand = new Random(j);\r\n\t\t\tList<Instances> split = WekaUtil.getStratifiedSplit(inst, rand, .6f);\r\n\t\t\t\r\n\t\t\tSystem.out.print(\"Running base learner ...\");\r\n//\t\t\tClassifier rf = AbstractClassifier.forName(classifierName, null);\r\n\t\t\tmcc.buildClassifier(split.get(0));\r\n\t\t\tSystem.out.println(\"done. Accuracy: \" + getAccuracy(mcc, split.get(1)) + \"%\");\r\n\t\t\t\r\n\t\t\tClassifier c = new ReductionOptimizer(rand);\r\n\t\t\t\r\n//\t\t\tSystem.out.print(\"Train ... \");\r\n\t\t\tc.buildClassifier(split.get(0));\r\n//\t\t\tSystem.out.println(\"done\");\r\n\t\t\tSystem.out.println(\"MOD: \" + getAccuracy(c, split.get(1)) + \"%\");\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate static double getAccuracy(Classifier c, Instances test) throws Exception {\r\n\t\tint mistakes = 0;\r\n\t\tfor (Instance i : test) {\r\n\t\t\tif (c.classifyInstance(i) != i.classValue())\r\n\t\t\t\tmistakes ++;\r\n\t\t}\r\n\t\treturn MathExt.round(100 * (1- mistakes * 1f / test.size()), 2);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7408679723739624, "alphanum_fraction": 0.7435804605484009, "avg_line_length": 48.272727966308594, "blob_id": "b5b977d9120847ac4f03564866ff826169a75326", "content_id": "074682df1d7c2cccdec3d18a3643fa890776c7c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5530, "license_type": "no_license", "max_line_length": 294, "num_lines": 110, "path": "/softwareconfiguration/hasco/src/hasco/core/isRefinementCompletedPredicate.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package hasco.core;\r\n\r\nimport java.util.Arrays;\r\nimport java.util.Collection;\r\nimport java.util.List;\r\nimport java.util.Map;\r\n\r\nimport org.apache.commons.lang3.NotImplementedException;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport hasco.model.CategoricalParameterDomain;\r\nimport hasco.model.Component;\r\nimport hasco.model.ComponentInstance;\r\nimport hasco.model.NumericParameterDomain;\r\nimport hasco.model.Parameter;\r\nimport hasco.model.ParameterRefinementConfiguration;\r\nimport jaicore.basic.sets.SetUtil;\r\nimport jaicore.logic.fol.structure.ConstantParam;\r\nimport jaicore.logic.fol.structure.Literal;\r\nimport jaicore.logic.fol.structure.Monom;\r\nimport jaicore.logic.fol.theories.EvaluablePredicate;\r\n\r\npublic class isRefinementCompletedPredicate implements EvaluablePredicate {\r\n\r\n\tprivate final Logger logger = LoggerFactory.getLogger(isRefinementCompletedPredicate.class);\r\n\tprivate final Collection<Component> components;\r\n\tprivate final Map<Component,Map<Parameter, ParameterRefinementConfiguration>> refinementConfiguration;\r\n//\tprivate final Map<ComponentInstance,Double> knownCompositionsAndTheirScore = new HashMap<>();\r\n\r\n\tpublic isRefinementCompletedPredicate(Collection<Component> components, Map<Component,Map<Parameter, ParameterRefinementConfiguration>> refinementConfiguration) {\r\n\t\tsuper();\r\n\t\tthis.components = components;\r\n\t\tthis.refinementConfiguration = refinementConfiguration;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic Collection<List<ConstantParam>> getParamsForPositiveEvaluation(Monom state, ConstantParam... partialGrounding) {\r\n\t\tthrow new NotImplementedException(\"This is not an oracable predicate!\");\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean isOracable() {\r\n\t\treturn false;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic Collection<List<ConstantParam>> getParamsForNegativeEvaluation(Monom state, ConstantParam... partialGrounding) {\r\n\t\tthrow new UnsupportedOperationException();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean test(Monom state, ConstantParam... params) {\r\n\t\t\r\n\t\t/* initialize routine */\r\n\t\tif (params.length != 2) {\r\n\t\t\tthrow new IllegalArgumentException(\"There should be exactly two parameters additional to the state but \" + params.length +\" were provided: \" + Arrays.toString(params) + \". This parameters refer to the component name that is being configured and the object itself.\");\r\n\t\t}\r\n\t\tif (params[0] == null)\r\n\t\t\tthrow new IllegalArgumentException(\"The component name must not be null.\");\r\n\t\tif (params[1] == null)\r\n\t\t\tthrow new IllegalArgumentException(\"The component instance reference must not be null.\");\r\n//\t\tfinal String componentName = params[0].getName();\r\n\t\tfinal String objectContainer = params[1].getName();\r\n\t\t\t\t\r\n\t\t/* determine current values for the params */\r\n\t\tComponentInstance groundComponent = Util.getGroundComponentsFromState(state, components, false).get(objectContainer);\r\n\t\tComponent component = groundComponent.getComponent();\r\n\t\tMap<String,String> componentParamContainers = Util.getParameterContainerMap(state, objectContainer);\r\n\t\tfor (Parameter param : component.getParameters()) {\r\n\t\t\tString containerOfParam = componentParamContainers.get(param.getName());\r\n\t\t\tString currentValueOfParam = groundComponent.getParameterValue(param);\r\n\t\t\tboolean variableHasBeenSet = state.contains(new Literal(\"overwritten('\" + containerOfParam + \"')\"));\r\n\t\t\tboolean variableHasBeenClosed = state.contains(new Literal(\"closed('\" + containerOfParam + \"')\"));\r\n\t\t\tassert variableHasBeenSet == groundComponent.getParametersThatHaveBeenSetExplicitly().contains(param);\r\n\t\t\tassert !variableHasBeenClosed || variableHasBeenSet : \"Parameter \" + param.getName() + \" of component \" + component.getName() + \" with default domain \" + param.getDefaultDomain() + \" has been closed but no value has been set.\";\r\n\t\t\t\r\n\t\t\tif (param.isNumeric()) {\r\n\t\t\t\tdouble min = 0;\r\n\t\t\t\tdouble max = 0;\r\n\t\t\t\tif (currentValueOfParam != null) { \r\n\t\t\t\t\tList<String> interval = SetUtil.unserializeList(currentValueOfParam);\r\n\t\t\t\t\tmin = Double.parseDouble(interval.get(0));\r\n\t\t\t\t\tmax = Double.parseDouble(interval.get(1));\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tmin = ((NumericParameterDomain)param.getDefaultDomain()).getMin();\r\n\t\t\t\t\tmax = ((NumericParameterDomain)param.getDefaultDomain()).getMax();\r\n\t\t\t\t}\r\n\t\t\t\tdouble length = max - min;\r\n\t\t\t\tif (length > refinementConfiguration.get(component).get(param).getIntervalLength()) {\r\n\t\t\t\t\tlogger.info(\"Test for isRefinementCompletedPredicate({},{}) is negative. Interval length of [{},{}] is {}. Required length to consider an interval atomic is {}\", params[0].getName(), objectContainer, min ,max, length, refinementConfiguration.get(component).get(param).getIntervalLength());\r\n\t\t\t\t\treturn false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse if (param.getDefaultDomain() instanceof CategoricalParameterDomain) { // categorical params can be refined iff the have not been set and closed before\r\n\t\t\t\tassert param.getDefaultValue() != null : \"Param \" + param.getName() + \" has no default value!\";\r\n\t\t\t\tif (!variableHasBeenSet && !variableHasBeenClosed) {\r\n\t\t\t\t\tlogger.info(\"Test for isRefinementCompletedPredicate({},{}) is negative\", params[0].getName(), objectContainer);\r\n\t\t\t\t\treturn false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t\tthrow new UnsupportedOperationException(\"Currently no support for testing parameters of type \" + param.getClass().getName());\r\n//\t\t\tSystem.out.println(\"\\t\" + param.getName() + \" (\" + componentParams.get(param.getName()) + \") is still refinable.\");\r\n\t\t}\r\n\t\tlogger.info(\"Test for isRefinementCompletedPredicate({},{}) is positive\", params[0].getName(), objectContainer);\r\n\t\treturn true;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6052631735801697, "alphanum_fraction": 0.6052631735801697, "avg_line_length": 11.666666984558105, "blob_id": "a68e549ffe408e985c9aeec4e949d77c76554800", "content_id": "7b4fea6b6b1af923110645a0c333febc28dd2a9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 38, "license_type": "no_license", "max_line_length": 16, "num_lines": 3, "path": "/softwareconfiguration/mlplan/readme.md", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "## ML-Plan\n### Installation\n### Usage\n" }, { "alpha_fraction": 0.7376237511634827, "alphanum_fraction": 0.7376237511634827, "avg_line_length": 23.25, "blob_id": "27dd50d28de80fb379eeecd7acc6371c5efa691a", "content_id": "cf87aa93c33b7f0fb640b48d7cdd91721ae89561", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 202, "license_type": "no_license", "max_line_length": 60, "num_lines": 8, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/mcts/IPolicy.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.mcts;\r\n\r\nimport java.util.Map;\r\n\r\npublic interface IPolicy<T,A,V extends Comparable<V>> {\r\n\t\r\n\tpublic A getAction(T node, Map<A,T> actionsWithSuccessors);\r\n}\r\n" }, { "alpha_fraction": 0.7162454724311829, "alphanum_fraction": 0.7169675230979919, "avg_line_length": 35.28845977783203, "blob_id": "5fabaf733768f28e4bf1741457a92c06df0c5599", "content_id": "6257c1333b2450ecb3d5151a04b0c7e95c7d4c8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 9695, "license_type": "no_license", "max_line_length": 271, "num_lines": 260, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/random/RandomSearch.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.random;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.Collection;\r\nimport java.util.HashSet;\r\nimport java.util.List;\r\nimport java.util.Random;\r\nimport java.util.Set;\r\nimport java.util.concurrent.TimeoutException;\r\nimport java.util.function.Predicate;\r\nimport java.util.stream.Collectors;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport jaicore.basic.algorithm.AlgorithmEvent;\r\nimport jaicore.basic.algorithm.AlgorithmExecutionCanceledException;\r\nimport jaicore.basic.algorithm.AlgorithmFinishedEvent;\r\nimport jaicore.basic.algorithm.AlgorithmInitializedEvent;\r\nimport jaicore.basic.algorithm.AlgorithmState;\r\nimport jaicore.basic.sets.SetUtil;\r\nimport jaicore.graph.LabeledGraph;\r\nimport jaicore.graphvisualizer.events.graphEvents.GraphInitializedEvent;\r\nimport jaicore.graphvisualizer.events.graphEvents.NodeReachedEvent;\r\nimport jaicore.graphvisualizer.events.graphEvents.NodeTypeSwitchEvent;\r\nimport jaicore.search.algorithms.standard.AbstractORGraphSearch;\r\nimport jaicore.search.algorithms.standard.bestfirst.events.GraphSearchSolutionCandidateFoundEvent;\r\nimport jaicore.search.model.other.SearchGraphPath;\r\nimport jaicore.search.model.probleminputs.GraphSearchInput;\r\nimport jaicore.search.model.travesaltree.NodeExpansionDescription;\r\nimport jaicore.search.structure.graphgenerator.NodeGoalTester;\r\nimport jaicore.search.structure.graphgenerator.SingleRootGenerator;\r\nimport jaicore.search.structure.graphgenerator.SuccessorGenerator;\r\n\r\n/**\r\n * This search randomly draws paths from the root. At every node, each successor is chosen with the same probability except if a priority predicate is defined. A priority predicate says whether or not a node lies on a path that has\r\n * priority. A node only has priority until all successors that have priority are exhausted.\r\n * \r\n * @author fmohr\r\n *\r\n * @param <N>\r\n * @param <A>\r\n */\r\npublic class RandomSearch<N, A> extends AbstractORGraphSearch<GraphSearchInput<N, A>, Object, N, A, Double, N, A> {\r\n\r\n\tprivate final Logger logger = LoggerFactory.getLogger(RandomSearch.class);\r\n\r\n\tprivate final N root;\r\n\tprivate final SuccessorGenerator<N, A> gen;\r\n\tprivate final NodeGoalTester<N> goalTester;\r\n\tprivate final LabeledGraph<N, A> exploredGraph = new LabeledGraph<>();\r\n\tprivate final Set<N> closed = new HashSet<>();\r\n\tprivate final Predicate<N> priorityPredicate;\r\n\tprivate final Set<N> prioritizedNodes = new HashSet<>();\r\n\tprivate final Set<N> exhausted = new HashSet<>();\r\n\tprivate final Random random;\r\n\r\n\tpublic RandomSearch(GraphSearchInput<N, A> problem, int seed) {\r\n\t\tthis(problem, new Random(seed));\r\n\t}\r\n\r\n\tpublic RandomSearch(GraphSearchInput<N, A> problem, Random random) {\r\n\t\tthis(problem, null, random);\r\n\t}\r\n\r\n\tpublic RandomSearch(GraphSearchInput<N, A> problem, Predicate<N> priorityPredicate, Random random) {\r\n\t\tsuper(problem);\r\n\t\tthis.root = ((SingleRootGenerator<N>) problem.getGraphGenerator().getRootGenerator()).getRoot();\r\n\t\tthis.gen = problem.getGraphGenerator().getSuccessorGenerator();\r\n\t\tthis.goalTester = (NodeGoalTester<N>) problem.getGraphGenerator().getGoalTester();\r\n\t\texploredGraph.addItem(root);\r\n\t\tthis.random = random;\r\n\t\tthis.priorityPredicate = priorityPredicate;\r\n\t}\r\n\r\n\tprivate void expandNode(N node) throws InterruptedException {\r\n\t\tassert !closed.contains(node) && !goalTester.isGoal(node);\r\n\t\tlogger.info(\"Expanding next node {}\", node);\r\n\t\tList<NodeExpansionDescription<N, A>> successors = gen.generateSuccessors(node); // could have been interrupted here\r\n\t\tlogger.info(\"Identified {} successor(s), which are now appended.\", successors.size());\r\n\t\tboolean atLeastOneSuccessorPrioritized = false;\r\n\t\tfor (NodeExpansionDescription<N, A> successor : successors) {\r\n\t\t\texploredGraph.addItem(successor.getTo());\r\n\t\t\tboolean isPrioritized = priorityPredicate != null && priorityPredicate.test(successor.getTo());\r\n\t\t\tif (isPrioritized) {\r\n\t\t\t\tatLeastOneSuccessorPrioritized = true;\r\n\t\t\t\tprioritizedNodes.add(successor.getTo());\r\n\t\t\t}\r\n\t\t\texploredGraph.addEdge(node, successor.getTo(), successor.getAction());\r\n\t\t\tboolean isGoalNode = goalTester.isGoal(successor.getTo());\r\n\t\t\tif (isGoalNode)\r\n\t\t\t\tlogger.info(\"Found goal node {}!\", successor);\r\n\t\t\tpostEvent(new NodeReachedEvent<>(successor.getFrom(), successor.getTo(), isGoalNode ? \"or_solution\" : (isPrioritized ? \"or_prioritized\" : \"or_open\")));\r\n\t\t}\r\n\t\tif (!successors.isEmpty() && prioritizedNodes.contains(node) && !atLeastOneSuccessorPrioritized) {\r\n\t\t\tprioritizedNodes.remove(node);\r\n\t\t\tupdateExhaustedAndPrioritizedState(node);\r\n\t\t}\r\n\t\tif (!prioritizedNodes.contains(node))\r\n\t\t\tpostEvent(new NodeTypeSwitchEvent<N>(node, \"or_closed\"));\r\n\t\tclosed.add(node);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic AlgorithmEvent nextWithException() throws Exception {\r\n\r\n\t\tswitch (getState()) {\r\n\t\tcase created: {\r\n\t\t\tactivateTimeoutTimer(\"RandomSearch-Timeouter\");\r\n\t\t\tswitchState(AlgorithmState.active);\r\n\t\t\tpostEvent(new GraphInitializedEvent<>(root));\r\n\t\t\tAlgorithmEvent event = new AlgorithmInitializedEvent();\r\n\t\t\tpostEvent(event);\r\n\t\t\treturn event;\r\n\t\t}\r\n\t\tcase active: {\r\n\r\n\t\t\t/* if the root is exhausted, cancel */\r\n\t\t\tSearchGraphPath<N, A> drawnPath = null;\r\n\t\t\ttry {\r\n\t\t\t\tdrawnPath = nextSolutionUnderNode(root);\r\n\t\t\t} catch (TimeoutException e) {\r\n\r\n\t\t\t}\r\n\t\t\tif (drawnPath == null) {\r\n\t\t\t\tshutdown();\r\n\t\t\t\tAlgorithmEvent event = new AlgorithmFinishedEvent();\r\n\t\t\t\tpostEvent(event);\r\n\t\t\t\treturn event;\r\n\t\t\t}\r\n\t\t\tAlgorithmEvent event = new GraphSearchSolutionCandidateFoundEvent<>(drawnPath);\r\n\t\t\tpostEvent(event);\r\n\t\t\treturn event;\r\n\t\t}\r\n\t\tdefault: {\r\n\t\t\tthrow new IllegalStateException(\"Cannot do anything in state \" + getState());\r\n\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tpublic boolean knowsNode(N node) {\r\n\t\treturn exploredGraph.getItems().contains(node);\r\n\t}\r\n\r\n\tpublic void appendPathToNode(List<N> nodes) throws InterruptedException {\r\n\t\tfor (N node : nodes) {\r\n\t\t\tif (!closed.contains(node)) {\r\n\t\t\t\texpandNode(node);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tpublic SearchGraphPath<N, A> nextSolutionUnderNode(N node) throws InterruptedException, AlgorithmExecutionCanceledException, TimeoutException {\r\n\r\n\t\tcheckTermination();\r\n\r\n\t\t/* if the root is exhausted, cancel */\r\n\t\tif (exhausted.contains(node)) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\t/* conduct a random walk from the root to a goal */\r\n\t\tList<N> path = new ArrayList<>();\r\n\t\tpath.add(node);\r\n\t\tN head = node;\r\n\t\twhile (!goalTester.isGoal(head)) {\r\n\r\n\t\t\tcheckTermination();\r\n\r\n\t\t\t/* expand node if this has not happened yet */\r\n\t\t\tif (!closed.contains(head)) {\r\n\t\t\t\texpandNode(head);\r\n\t\t\t}\r\n\r\n\t\t\t/* get unexhausted successors */\r\n\t\t\tList<N> successors = exploredGraph.getSuccessors(head).stream().filter(n -> !exhausted.contains(n)).collect(Collectors.toList());\r\n\r\n\t\t\t/* if we are in a dead end, mark the node as exhausted and remove the head again */\r\n\t\t\tif (successors.isEmpty()) {\r\n\t\t\t\texhausted.add(head);\r\n\t\t\t\tprioritizedNodes.remove(head); // remove prioritized node from list if it is in\r\n\t\t\t\tpath.remove(head);\r\n\t\t\t\tif (path.isEmpty())\r\n\t\t\t\t\treturn null;\r\n\t\t\t\thead = path.get(path.size() - 1);\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t\t/* if at least one of the successors is prioritized, choose one of those; otherwise choose one at random */\r\n\t\t\tassert SetUtil.intersection(exhausted, prioritizedNodes).isEmpty() : \"There are nodes that are both exhausted and prioritized, which must not be the case:\" + SetUtil.intersection(exhausted, prioritizedNodes).stream().map(n -> \"\\n\\t\" + n).collect(Collectors.joining());\r\n\t\t\tCollection<N> prioritizedSuccessors = SetUtil.intersection(successors, prioritizedNodes);\r\n\t\t\tif (!prioritizedSuccessors.isEmpty()) {\r\n\t\t\t\thead = prioritizedSuccessors.iterator().next();\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tint n = successors.size();\r\n\t\t\t\tassert n != 0 : \"Ended up in a situation where only exhausted nodes can be chosen.\";\r\n\t\t\t\tint k = random.nextInt(n);\r\n\t\t\t\thead = successors.get(k);\r\n\t\t\t\tfinal N tmpHead = head; // needed for stream in assertion\r\n\t\t\t\tassert !path.contains(head) : \"Going in circles ... \" + path.stream().map(pn -> \"\\n\\t[\" + (pn.equals(tmpHead) ? \"*\" : \" \") + \"]\" + pn.toString()).collect(Collectors.joining())\r\n\t\t\t\t\t\t+ \"\\n\\t[*]\" + head;\r\n\t\t\t}\r\n\t\t\tpath.add(head);\r\n\t\t}\r\n\r\n\t\t/* propagate exhausted state */\r\n\t\texhausted.add(head);\r\n\t\tprioritizedNodes.remove(head);\r\n\t\tupdateExhaustedAndPrioritizedState(head);\r\n\t\treturn new SearchGraphPath<>(path, null);\r\n\t}\r\n\t\r\n\tprivate void updateExhaustedAndPrioritizedState(N node) {\r\n\t\tN current = node;\r\n\t\tCollection<N> predecessors;\r\n\t\twhile (!(predecessors = exploredGraph.getPredecessors(current)).isEmpty()) {\r\n\t\t\tassert predecessors.size() == 1;\r\n\t\t\tcurrent = predecessors.iterator().next();\r\n\t\t\tboolean currentIsPrioritized = prioritizedNodes.contains(current);\r\n\t\t\tboolean allChildrenExhausted = true;\r\n\t\t\tboolean allPrioritizedChildrenExhausted = true;\r\n\t\t\tfor (N successor : exploredGraph.getSuccessors(current)) {\r\n\t\t\t\tif (!exhausted.contains(successor)) {\r\n\t\t\t\t\tallChildrenExhausted = false;\r\n\t\t\t\t\tif (currentIsPrioritized && prioritizedNodes.contains(successor)) {\r\n\t\t\t\t\t\tallPrioritizedChildrenExhausted = false;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t} else if (!currentIsPrioritized)\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (allChildrenExhausted)\r\n\t\t\t\texhausted.add(current);\r\n\t\t\tif (currentIsPrioritized && allPrioritizedChildrenExhausted) {\r\n\t\t\t\tint sizeBefore = prioritizedNodes.size();\r\n\t\t\t\tprioritizedNodes.remove(current);\r\n\t\t\t\tpostEvent(new NodeTypeSwitchEvent<N>(current, \"or_closed\"));\r\n\t\t\t\tint sizeAfter = prioritizedNodes.size();\r\n\t\t\t\tassert sizeAfter == sizeBefore - 1;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void setNumCPUs(int numberOfCPUs) {\r\n\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int getNumCPUs() {\r\n\t\treturn 1;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic Object getSolutionProvidedToCall() {\r\n\t\treturn null;\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.7743526697158813, "alphanum_fraction": 0.7891492247581482, "avg_line_length": 26.964284896850586, "blob_id": "e9537e819a9e7291d7d7f43052aad05e6c03ba64", "content_id": "89055d93670823f6559d53bd982d9317b2866fbd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 811, "license_type": "no_license", "max_line_length": 124, "num_lines": 28, "path": "/softwareconfiguration/hasco/src/hasco/variants/forwarddecomposition/twophase/TwoPhaseHASCOReport.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package hasco.variants.forwarddecomposition.twophase;\r\n\r\nimport hasco.core.HASCOSolutionCandidate;\r\n\r\npublic class TwoPhaseHASCOReport {\r\n\tprivate final int numSolutionsInPhase1;\r\n\tprivate final int durationPhase1;\r\n\tprivate final HASCOSolutionCandidate<Double> returnedSolution;\r\n\r\n\tpublic TwoPhaseHASCOReport(int numSolutionsInPhase1, int durationPhase1, HASCOSolutionCandidate<Double> returnedSolution) {\r\n\t\tsuper();\r\n\t\tthis.numSolutionsInPhase1 = numSolutionsInPhase1;\r\n\t\tthis.durationPhase1 = durationPhase1;\r\n\t\tthis.returnedSolution = returnedSolution;\r\n\t}\r\n\r\n\tpublic int getNumSolutionsInPhase1() {\r\n\t\treturn numSolutionsInPhase1;\r\n\t}\r\n\r\n\tpublic int getDurationPhase1() {\r\n\t\treturn durationPhase1;\r\n\t}\r\n\r\n\tpublic HASCOSolutionCandidate<Double> getReturnedSolution() {\r\n\t\treturn returnedSolution;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6474428772926331, "alphanum_fraction": 0.6474428772926331, "avg_line_length": 21.975000381469727, "blob_id": "84a49ca91dfa9d931b8225f8eda271e2a112a702", "content_id": "8001000fd5d73245573891ff3682030d9d14f5cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 919, "license_type": "no_license", "max_line_length": 101, "num_lines": 40, "path": "/JAICore/jaicore-basic/src/jaicore/basic/ListHelper.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.basic;\n\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class ListHelper {\n\n /**\n * Forbid to create an object of ListHelper as there are only static methods allowed here.\n */\n private ListHelper() {\n // intentionally do nothing\n }\n\n public static List<String> commaSeparatedStringToList(final String stringList) {\n List<String> values = new LinkedList<>();\n String[] split = stringList.split(\",\");\n for (String splitElement : split) {\n values.add(splitElement);\n }\n return values;\n }\n\n public static String implode(final Iterable<? extends Object> collection, final String separator) {\n StringBuilder sb = new StringBuilder();\n\n boolean first = true;\n for (Object o : collection) {\n if (first) {\n first = false;\n } else {\n sb.append(separator);\n }\n sb.append(o.toString());\n }\n\n return sb.toString();\n }\n\n}\n" }, { "alpha_fraction": 0.5230769515037537, "alphanum_fraction": 0.5538461804389954, "avg_line_length": 19.85714340209961, "blob_id": "ceb4a30ee01543f282743aa88e97254a5c5eb8f1", "content_id": "49546f410f2b640643fd8bff13e8649623f89357", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Gradle", "length_bytes": 455, "license_type": "no_license", "max_line_length": 77, "num_lines": 21, "path": "/JAICore/jaicore-basic/build.gradle", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "plugins {\n\tid \"com.github.hauner.jarTest\" version \"1.0.1\"\n}\n\r\nsourceSets {\r\n main {\r\n java {\r\n srcDir 'src'\r\n }\r\n }\r\n test {\r\n \tjava {\r\n \t\tsrcDir 'test'\r\n \t}\r\n }\r\n}\r\ndependencies {\n\tcompile group: 'org.apache.commons', name: 'commons-math3', version: '3.6.1'\r\n\tcompile group: 'org.aeonbits.owner', name: 'owner-java8', version:'1.0.6'\r\n compile group: 'com.google.guava', name: 'guava', version: '26.0-jre'\r\n}\r\n" }, { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 19, "blob_id": "6cd3bd5b3cdc4d9473f38d12170d7c0925ecb9ae", "content_id": "cb84b321aab60cad75bed0aab2124371dca69c69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 140, "license_type": "no_license", "max_line_length": 40, "num_lines": 7, "path": "/JAICore/jaicore-basic/src/jaicore/basic/ILoggingCustomizable.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.basic;\n\npublic interface ILoggingCustomizable {\n\tpublic void setLoggerName(String name);\n\n\tpublic String getLoggerName();\n}\n" }, { "alpha_fraction": 0.8109965920448303, "alphanum_fraction": 0.8109965920448303, "avg_line_length": 28.100000381469727, "blob_id": "452fc8ff898ea3e919e4625fa7e2d1cdf481bf86", "content_id": "680a1b551428d2dd4379a60a20f481a5fc901270", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 291, "license_type": "no_license", "max_line_length": 86, "num_lines": 10, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/gbf/GeneralBestFirstEvaluationOrSelector.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.gbf;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport jaicore.search.model.travesaltree.Node;\n\npublic interface GeneralBestFirstEvaluationOrSelector<T> {\n\tpublic List<Node<T,Integer>> getSuccessorRanking(Map<Node<T,Integer>,Integer> nodes);\n}\n" }, { "alpha_fraction": 0.707317054271698, "alphanum_fraction": 0.7099538445472717, "avg_line_length": 30.793413162231445, "blob_id": "58a46be4be58e2a26b17e174c55c015eed8d84a8", "content_id": "4663fc5e10a04ca3673f497b516c805775bf7ab4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 10619, "license_type": "no_license", "max_line_length": 148, "num_lines": 334, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/parallel/parallelexploration/distributed/FolderBasedDistributedSearchCommunicationLayer.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.parallel.parallelexploration.distributed;\n\nimport java.io.BufferedInputStream;\nimport java.io.BufferedOutputStream;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.StandardCopyOption;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.BlockingQueue;\nimport java.util.concurrent.LinkedBlockingQueue;\nimport java.util.concurrent.Semaphore;\nimport java.util.stream.Stream;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport jaicore.basic.FileUtil;\nimport jaicore.search.algorithms.parallel.parallelexploration.distributed.interfaces.DistributedSearchCommunicationLayer;\nimport jaicore.search.algorithms.parallel.parallelexploration.distributed.interfaces.SerializableGraphGenerator;\nimport jaicore.search.algorithms.parallel.parallelexploration.distributed.interfaces.SerializableNodeEvaluator;\nimport jaicore.search.algorithms.standard.bestfirst.nodeevaluation.INodeEvaluator;\nimport jaicore.search.model.travesaltree.Node;\n\npublic class FolderBasedDistributedSearchCommunicationLayer<T, A, V extends Comparable<V>> implements DistributedSearchCommunicationLayer<T, A, V> {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(FolderBasedDistributedSearchCommunicationLayer.class);\n\tprivate final Set<String> knownCoworkers = new HashSet<>();\n\tprivate final Path communicationFolder;\n\tprivate Map<String, Semaphore> registerTickets = new HashMap<>();\n\tprivate Map<String, BlockingQueue<Collection<Node<T, V>>>> jobQueues = new HashMap<>();\n\n\tprivate final Thread masterFolderObserver = new Thread() {\n\t\tpublic void run() {\n//\t\t\ttry {\n//\t\t\t\twhile (!Thread.interrupted()) {\n//\n//\t\t\t\t\tThread.sleep(500);\n//\t\t\t\t}\n//\t\t\t} catch (InterruptedException e) {\n//\t\t\t\tlogger.info(\"Shutting down folder listener.\");\n//\t\t\t}\n\t\t}\n\t};\n\t\n\tprivate final Thread coworkerFolderObserver = new Thread() {\n\t\tpublic void run() {\n\t\t\ttry {\n\t\t\t\twhile (!Thread.interrupted()) {\n\t\t\t\t\t\n\t\t\t\t\t/* detect whether a coworker has a new job request */\n\t\t\t\t\tfor (String coworker : knownCoworkers) {\n\t\t\t\t\t\treadCoworkersJob(coworker);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t/* check whether registering coworkers have been attached */\n\t\t\t\t\tfor (String registeringCoworker : registerTickets.keySet()) {\n\t\t\t\t\t\tif (isAttached(registeringCoworker)) {\n\t\t\t\t\t\t\tregisterTickets.get(registeringCoworker).release();\n\t\t\t\t\t\t\tregisterTickets.remove(registeringCoworker);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tThread.sleep(500);\n\t\t\t\t}\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\tlogger.info(\"Shutting down folder listener.\");\n\t\t\t}\n\t\t}\n\t};\n\t\n\tpublic FolderBasedDistributedSearchCommunicationLayer(Path communicationFolder, boolean isMaster) {\n\t\tsuper();\n\t\tthis.communicationFolder = communicationFolder;\n\t\tif (isMaster)\n\t\t\tmasterFolderObserver.start();\n\t\telse\n\t\t\tcoworkerFolderObserver.start();\n\t}\n\n\tpublic void init() {\n\n\t\t/* clean directory */\n\t\ttry (Stream<Path> paths = Files.walk(communicationFolder)) {\n\t\t\tpaths.forEach(filePath -> {\n\t\t\t\ttry {\n\t\t\t\t\tif (Files.isRegularFile(filePath) && !filePath.getFileName().toString().contains(\"register\")) {\n\t\t\t\t\t\tlogger.info(\"Deleting {}\", filePath.getFileName());\n\t\t\t\t\t\tFiles.delete(filePath);\n\t\t\t\t\t}\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t});\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t@Override\n\tpublic Collection<String> detectNewCoworkers() {\n\n\t\t/* check whether there are requests */\n\t\tCollection<String> newCoworkers = new ArrayList<>();\n\t\ttry (Stream<Path> paths = Files.walk(communicationFolder)) {\n\t\t\tpaths.forEach(filePath -> {\n\t\t\t\tif (Files.isRegularFile(filePath) && filePath.toFile().getName().startsWith(\"register-\")) {\n\n\t\t\t\t\t/* register coworker and remove it */\n\t\t\t\t\tString coworkerId = filePath.toFile().getName().substring(\"register-\".length());\n\t\t\t\t\tlogger.info(\"Recognized coworker {}\", coworkerId);\n\t\t\t\t\ttry {\n\t\t\t\t\t\tFiles.delete(filePath);\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t\tnewCoworkers.add(coworkerId);\n\t\t\t\t}\n\t\t\t});\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\t/* add coworkers */\n\t\tfor (String newCoworker : newCoworkers) {\n\t\t\tknownCoworkers.add(newCoworker);\n\t\t\tif (!jobQueues.containsKey(newCoworker))\n\t\t\t\tjobQueues.put(newCoworker, new LinkedBlockingQueue<>());\n\t\t}\n\n\t\treturn newCoworkers;\n\t}\n\n\t@Override\n\tpublic void detachCoworker(String coworker) {\n\t\tFile f = new File(communicationFolder.toAbsolutePath() + \"/attach-\" + coworker);\n\t\ttry {\n\t\t\tFiles.delete(f.toPath());\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t@Override\n\tpublic void createNewJobForCoworker(String coworkerId, Collection<Node<T, V>> nodesToBeSolved) {\n\t\tFile target = new File(communicationFolder.toFile().getAbsolutePath() + \"/job-\" + coworkerId);\n\t\tFile tmp = new File(target.getAbsolutePath() + \".tmp\");\n\t\tlogger.info(\"Writing job for {}: {}\", coworkerId, nodesToBeSolved);\n\t\ttry (ObjectOutputStream bw = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(tmp)))) {\n\t\t\tbw.writeObject(nodesToBeSolved);\n\t\t\tbw.close();\n\t\t\tFiles.move(tmp.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\t@Override\n\tpublic DistributedComputationResult<T, V> readResult(String coworker) {\n\t\tFile file = new File(communicationFolder.toFile().getAbsolutePath() + \"/results-\" + coworker);\n\t\tif (!file.exists())\n\t\t\treturn null;\n\t\tlogger.info(\"Found results from coworker \" + coworker);\n\t\tboolean success = false;\n\t\tint tries = 0;\n\t\tDistributedComputationResult<T, V> result = null;\n\t\twhile (!success && tries < 4) {\n\t\t\ttry {\n\t\t\t\ttries++;\n\n\t\t\t\t/* read results object */\n\t\t\t\tlogger.info(\"Reading file \" + file.getAbsolutePath() + \" ...\");\n\t\t\t\tObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));\n\t\t\t\tresult = (DistributedComputationResult<T, V>) in.readObject();\n\t\t\t\tin.close();\n\t\t\t\tlogger.info(\"done\");\n\t\t\t\tFiles.delete(file.toPath());\n\t\t\t\tsuccess = true;\n\t\t\t} catch (IOException | ClassNotFoundException e) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(100);\n\t\t\t\t} catch (Exception e1) {\n\t\t\t\t\te1.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!success)\n\t\t\tlogger.error(\"Failed to read and/or delete file \" + file.getName());\n\t\treturn result;\n\t}\n\n\t/** Coworker Stuff **/\n\tpublic void register(String coworker) throws InterruptedException {\n\t\ttry {\n\n\t\t\t/* detach coworker forst if it is attached */\n\t\t\tif (isAttached(coworker))\n\t\t\t\tdetachCoworker(coworker);\n\n\t\t\t/* create register semaphore */\n\t\t\tSemaphore s = new Semaphore(0);\n\t\t\tregisterTickets.put(coworker, s);\n\n\t\t\t/* now register */\n\t\t\tFile f = new File(communicationFolder.toAbsolutePath() + \"/register-\" + coworker);\n\t\t\tf.createNewFile();\n\n\t\t\t/* now wait for acceptance */\n\t\t\ts.acquire(1);\n\t\t\t\n\t\t\t/* if the coworker has been registered, add him to the pool of candidates */\n\t\t\tknownCoworkers.add(coworker);\n\t\t\t\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tpublic void unregister(String coworker) {\n\t\ttry {\n\t\t\tFile f = new File(communicationFolder.toAbsolutePath() + \"/register-\" + coworker);\n\t\t\tif (f.exists()) {\n\t\t\t\tlogger.info(\"Deleting {}\", f.getAbsolutePath());\n\t\t\t\tFiles.delete(f.toPath());\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tpublic Collection<Node<T, V>> nextJob(String coworker) throws InterruptedException {\n\t\tif (!jobQueues.containsKey(coworker))\n\t\t\tjobQueues.put(coworker, new LinkedBlockingQueue<>());\n\t\treturn jobQueues.get(coworker).take();\n\t}\n\n\t@Override\n\tpublic void reportResult(String coworker, DistributedComputationResult<T, V> result) {\n\t\tFile target = new File(communicationFolder.toFile().getAbsolutePath() + \"/results-\" + coworker);\n\t\tFile tmp = new File(target.getAbsolutePath() + \".tmp\");\n\t\ttry (ObjectOutputStream bw = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(tmp)))) {\n\t\t\tbw.writeObject(result);\n\t\t\tbw.close();\n\t\t\tFiles.move(tmp.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t}\n\n\t@Override\n\tpublic void attachCoworker(String coworker) {\n\t\ttry {\n\t\t\tFile f = new File(communicationFolder.toAbsolutePath() + \"/attach-\" + coworker);\n\t\t\tf.createNewFile();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean isAttached(String coworker) {\n\t\tFile f = new File(communicationFolder.toAbsolutePath() + \"/attach-\" + coworker);\n\t\treturn f.exists();\n\t}\n\n\t@Override\n\tpublic void setGraphGenerator(SerializableGraphGenerator<T, A> generator) throws Exception {\n\t\tFileUtil.serializeObject(generator, communicationFolder.toAbsolutePath() + \"/graphgen.ser\");\n\t}\n\n\t@Override\n\tpublic void setNodeEvaluator(SerializableNodeEvaluator<T, V> evaluator) throws Exception {\n\t\tFileUtil.serializeObject(evaluator, communicationFolder.toAbsolutePath() + \"/nodeeval.ser\");\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\t@Override\n\tpublic SerializableGraphGenerator<T, A> getGraphGenerator() throws Exception {\n\t\treturn (SerializableGraphGenerator<T, A>) FileUtil.unserializeObject(communicationFolder.toAbsolutePath() + \"/graphgen.ser\");\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\t@Override\n\tpublic INodeEvaluator<T, V> getNodeEvaluator() throws Exception {\n\t\treturn (INodeEvaluator<T, V>) FileUtil.unserializeObject(communicationFolder.toAbsolutePath() + \"/nodeeval.ser\");\n\t}\n\n\t@Override\n\tpublic void close() {\n\t\tmasterFolderObserver.interrupt();\n\t\tcoworkerFolderObserver.interrupt();\n\t}\n\n\tprivate void readCoworkersJob(String coworker) {\n\t\tFile f = new File(communicationFolder.toAbsolutePath() + \"/job-\" + coworker);\n\t\tif (!f.exists())\n\t\t\treturn;\n\t\tint tries = 0;\n\t\twhile (tries < 10) {\n\t\t\ttry (ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(f)))) {\n\t\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\t\tCollection<Node<T, V>> nodes = (Collection<Node<T, V>>) in.readObject();\n\t\t\t\tin.close();\n\t\t\t\tFiles.delete(f.toPath());\n\t\t\t\tjobQueues.get(coworker).add(nodes);\n\t\t\t\treturn;\n\t\t\t} catch (IOException e) {\n\t\t\t\ttry {\n\t\t\t\t\tlogger.error(\"Error reading file \" + f.toString() + \", waiting 500ms and retrying.\");\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t\ttries++;\n\t\t\t\t\tThread.sleep(500);\n\t\t\t\t} catch (InterruptedException e1) {\n\t\t\t\t\te1.printStackTrace();\n\t\t\t\t}\n\t\t\t} catch (ClassNotFoundException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\tlogger.info(\"Giving up reading the results of \" + coworker);\n\t}\n}\n" }, { "alpha_fraction": 0.6474654674530029, "alphanum_fraction": 0.671658992767334, "avg_line_length": 19.20930290222168, "blob_id": "27ea0f5bb9e2909280bd6a19b689f2162f12b76f", "content_id": "7a0484ae8cbffa528c8cdff01c84b80ce0299634", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 868, "license_type": "no_license", "max_line_length": 87, "num_lines": 43, "path": "/JAICore/jaicore-search/test/jaicore/search/algorithms/parallel/parallelexploration/distributed/clustertest/TestNode.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.parallel.parallelexploration.distributed.clustertest;\n\nimport java.io.Serializable;\n\nclass TestNode implements Serializable {\n\tprivate static final long serialVersionUID = 793618120417152627L;\n\tfinal int min, max;\n\n\tpublic TestNode(int min, int max) {\n\t\tsuper();\n\t\tthis.min = min;\n\t\tthis.max = max;\n\t}\n\n\tpublic String toString() {\n\t\treturn min + \"/\" + max;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + max;\n\t\tresult = prime * result + min;\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tTestNode other = (TestNode) obj;\n\t\tif (max != other.max)\n\t\t\treturn false;\n\t\tif (min != other.min)\n\t\t\treturn false;\n\t\treturn true;\n\t}\n}" }, { "alpha_fraction": 0.8023256063461304, "alphanum_fraction": 0.8023256063461304, "avg_line_length": 16.200000762939453, "blob_id": "2377868adf8448cba5cacd372a1b4aad4881016e", "content_id": "3bcd2c726295dd41bb33cf9d85c9ee79e6b3b263", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 86, "license_type": "no_license", "max_line_length": 48, "num_lines": 5, "path": "/JAICore/jaicore-search/src/jaicore/search/structure/graphgenerator/GoalTester.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.structure.graphgenerator;\n\npublic interface GoalTester<T> {\n\n}\n" }, { "alpha_fraction": 0.840266227722168, "alphanum_fraction": 0.840266227722168, "avg_line_length": 48.16666793823242, "blob_id": "86a8500041751e64d9e294e7d93f6e343b111fd8", "content_id": "5eb5f1c18db7ae432ff32dd3417b41e25bff5acd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1202, "license_type": "no_license", "max_line_length": 183, "num_lines": 24, "path": "/JAICore/jaicore-search/test/jaicore/search/algorithms/standard/mcts/MCTSEnhancedTTSPTester.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.mcts;\r\n\r\nimport jaicore.basic.algorithm.AlgorithmProblemTransformer;\r\nimport jaicore.search.core.interfaces.IGraphSearchFactory;\r\nimport jaicore.search.model.probleminputs.GraphSearchProblemInput;\r\nimport jaicore.search.model.travesaltree.Node;\r\nimport jaicore.search.testproblems.enhancedttsp.EnhancedTTSP;\r\nimport jaicore.search.testproblems.enhancedttsp.EnhancedTTSPNode;\r\nimport jaicore.search.testproblems.enhancedttsp.EnhancedTTSPTester;\r\nimport jaicore.search.testproblems.enhancedttsp.EnhancedTTSPToGraphSearchProblemInputReducer;\r\n\r\npublic class MCTSEnhancedTTSPTester extends EnhancedTTSPTester<GraphSearchProblemInput<EnhancedTTSPNode,String,Double>,Object,Node<EnhancedTTSPNode,Double>, String> {\r\n\r\n\t@Override\r\n\tpublic AlgorithmProblemTransformer<EnhancedTTSP, GraphSearchProblemInput<EnhancedTTSPNode, String, Double>> getProblemReducer() {\r\n\t\treturn new EnhancedTTSPToGraphSearchProblemInputReducer();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic IGraphSearchFactory<GraphSearchProblemInput<EnhancedTTSPNode, String, Double>, Object, EnhancedTTSPNode, String, Double, Node<EnhancedTTSPNode, Double>, String> getFactory() {\r\n\t\treturn new UCTFactory<>();\r\n\t}\r\n\t\r\n}" }, { "alpha_fraction": 0.7367616295814514, "alphanum_fraction": 0.7393423914909363, "avg_line_length": 37.77946853637695, "blob_id": "e944f368a5407700fee38ba329e930f966afc6d0", "content_id": "d870123ddbfa80e70b750a424c4b4ec697ffeaa4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 10462, "license_type": "no_license", "max_line_length": 199, "num_lines": 263, "path": "/JAICore/jaicore-basic/test/jaicore/basic/algorithm/GeneralAlgorithmTester.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.basic.algorithm;\r\n\r\nimport static org.junit.Assert.assertEquals;\r\nimport static org.junit.Assert.assertTrue;\r\n\r\nimport java.util.Timer;\r\nimport java.util.TimerTask;\r\nimport java.util.concurrent.ExecutionException;\r\nimport java.util.concurrent.FutureTask;\r\nimport java.util.concurrent.TimeUnit;\r\nimport java.util.concurrent.TimeoutException;\r\nimport java.util.concurrent.atomic.AtomicLong;\r\n\r\nimport org.junit.Test;\r\n\r\nimport com.google.common.eventbus.Subscribe;\r\n\r\n/**\r\n *\r\n * @param <P>\r\n * The class of the actual problem to be solved\r\n * @param <I>\r\n * The class of the algorithm input\r\n * @param <O>\r\n * The class of the algorithm output\r\n */\r\npublic abstract class GeneralAlgorithmTester<P, I, O> {\r\n\r\n\tprivate static final int INTERRUPTION_DELAY = 5000;\r\n\tprivate static final int INTERRUPTION_CLEANUP_TOLERANCE = 2000;\r\n\tprivate static final int THREAD_SHUTDOWN_TOLERANCE = 10000;\r\n\r\n\tpublic abstract AlgorithmProblemTransformer<P, I> getProblemReducer();\r\n\r\n\tpublic abstract IAlgorithmFactory<I, O> getFactory();\r\n\r\n\tpublic abstract I getSimpleProblemInputForGeneralTestPurposes() throws Exception;\r\n\r\n\tpublic abstract I getDifficultProblemInputForGeneralTestPurposes() throws Exception; // runtime at least 10 seconds\r\n\r\n\t@Test\r\n\tpublic void testStartAndFinishEventEmissionSequentially() throws Exception {\r\n\t\tint numberOfThreadsBefore = Thread.activeCount();\r\n\t\tIAlgorithmFactory<I, O> factory = getFactory();\r\n\t\tfactory.setProblemInput(getSimpleProblemInputForGeneralTestPurposes());\r\n\t\tIAlgorithm<I, O> algorithm = factory.getAlgorithm();\r\n\t\tCheckingEventListener listener = new CheckingEventListener();\r\n\t\talgorithm.registerListener(listener);\r\n\t\talgorithm.call();\r\n\t\tlistener.checkState();\r\n\t\twaitForThreadsToAssumeNumber(numberOfThreadsBefore);\r\n\t\tcheckNotInterrupted();\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testStartAndFinishEventEmissionProtocolParallelly() throws Exception {\r\n\t\tIAlgorithmFactory<I, O> factory = getFactory();\r\n\t\tfactory.setProblemInput(getSimpleProblemInputForGeneralTestPurposes());\r\n\t\tIAlgorithm<I, O> algorithm = factory.getAlgorithm();\r\n\t\talgorithm.setNumCPUs(Runtime.getRuntime().availableProcessors());\r\n\t\tCheckingEventListener listener = new CheckingEventListener();\r\n\t\talgorithm.registerListener(listener);\r\n\t\tint numberOfThreadsBefore = Thread.activeCount();\r\n\t\talgorithm.call();\r\n\t\tlistener.checkState();\r\n\t\twaitForThreadsToAssumeNumber(numberOfThreadsBefore);\r\n\t\tcheckNotInterrupted();\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testStartAndFinishEventEmissionByIteration() throws Exception {\r\n\t\tIAlgorithmFactory<I, O> factory = getFactory();\r\n\t\tfactory.setProblemInput(getSimpleProblemInputForGeneralTestPurposes());\r\n\t\tIAlgorithm<I, O> algorithm = factory.getAlgorithm();\r\n\t\tCheckingEventListener listener = new CheckingEventListener();\r\n\t\tint numberOfThreadsBefore = Thread.activeCount();\r\n\t\tfor (AlgorithmEvent e : algorithm) {\r\n\t\t\tlistener.receiveEvent(e);\r\n\t\t}\r\n\t\tlistener.checkState();\r\n\t\twaitForThreadsToAssumeNumber(numberOfThreadsBefore);\r\n\t\tcheckNotInterrupted();\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testInterrupt() throws Exception {\r\n\r\n\t\t/* set up algorithm */\r\n\t\tIAlgorithmFactory<I, O> factory = getFactory();\r\n\t\tfactory.setProblemInput(getDifficultProblemInputForGeneralTestPurposes());\r\n\t\tIAlgorithm<I, O> algorithm = factory.getAlgorithm();\r\n\t\talgorithm.setNumCPUs(Runtime.getRuntime().availableProcessors());\r\n\t\tFutureTask<O> task = new FutureTask<>(algorithm);\r\n\t\tint numberOfThreadsBefore = Thread.activeCount();\r\n\r\n\t\t/* set up timer for interruption */\r\n\t\tThread t = new Thread(task, \"InterruptTest Algorithm runner for \" + algorithm);\r\n\t\tAtomicLong interruptEvent = new AtomicLong();\r\n\t\tt.start();\r\n\t\tnew Timer(\"InterruptTest Timer\").schedule(new TimerTask() {\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\tSystem.out.println(\"Interrupting \" + t);\r\n\t\t\t\tt.interrupt();\r\n\t\t\t\tinterruptEvent.set(System.currentTimeMillis());\r\n\t\t\t}\r\n\t\t}, INTERRUPTION_DELAY);\r\n\r\n\t\t/* launch algorithm */\r\n\t\tboolean interruptedExceptionSeen = false;\r\n\t\tlong start = System.currentTimeMillis();\r\n\t\ttry {\r\n\t\t\ttask.get(INTERRUPTION_DELAY + INTERRUPTION_CLEANUP_TOLERANCE, TimeUnit.MILLISECONDS);\r\n\t\t} catch (ExecutionException e) {\r\n\t\t\tif (e.getCause() instanceof InterruptedException)\r\n\t\t\t\tinterruptedExceptionSeen = true;\r\n\t\t} catch (TimeoutException e) {\r\n\t\t}\r\n\t\tlong end = System.currentTimeMillis();\r\n\t\tint runtime = (int) (end - start);\r\n\t\tint timeNeededToRealizeInterrupt = (int) (end - interruptEvent.get());\r\n\t\tassertTrue(\"Runtime must be at least 5 seconds, actually should be at least 10 seconds.\", runtime >= INTERRUPTION_DELAY);\r\n\t\tassertTrue(\"The algorithm has not terminated within \" + INTERRUPTION_CLEANUP_TOLERANCE + \"ms after the interrupt.\", timeNeededToRealizeInterrupt <= INTERRUPTION_CLEANUP_TOLERANCE);\r\n\t\tassertTrue(\"The algorithm has not emitted an interrupted exception.\", interruptedExceptionSeen);\r\n\r\n\t\t/* now sending a cancel to make sure the algorithm structure is shutdown (this is because the interrupt only requires that the executing thread is returned but not that the algorithm is shutdown */\r\n\t\talgorithm.cancel();\r\n\t\twaitForThreadsToAssumeNumber(numberOfThreadsBefore);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testCancel() throws Exception {\r\n\r\n\t\t/* set up algorithm */\r\n\t\tIAlgorithmFactory<I, O> factory = getFactory();\r\n\t\tfactory.setProblemInput(getDifficultProblemInputForGeneralTestPurposes());\r\n\t\tIAlgorithm<I, O> algorithm = factory.getAlgorithm();\r\n\t\talgorithm.setNumCPUs(Runtime.getRuntime().availableProcessors());\r\n\t\tFutureTask<O> task = new FutureTask<>(algorithm);\r\n\t\tint numberOfThreadsBefore = Thread.activeCount();\r\n\r\n\t\t/* set up timer for interruption */\r\n\t\tAtomicLong cancelEvent = new AtomicLong();\r\n\t\tnew Timer(\"CancelTest Timer\").schedule(new TimerTask() {\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\talgorithm.cancel();\r\n\t\t\t\tcancelEvent.set(System.currentTimeMillis());\r\n\t\t\t}\r\n\t\t}, INTERRUPTION_DELAY);\r\n\r\n\t\t/* launch algorithm */\r\n\t\tlong start = System.currentTimeMillis();\r\n\t\tboolean cancellationExceptionSeen = false;\r\n\t\tThread t = new Thread(task, \"CancelTest Algorithm runner for \" + algorithm);\r\n\t\tt.start();\r\n\t\ttry {\r\n\t\t\ttask.get(INTERRUPTION_DELAY + INTERRUPTION_CLEANUP_TOLERANCE, TimeUnit.MILLISECONDS);\r\n\t\t} catch (ExecutionException e) {\r\n\t\t\tif (e.getCause() instanceof AlgorithmExecutionCanceledException) {\r\n\t\t\t\tcancellationExceptionSeen = true;\r\n\t\t\t}\r\n\t\t} catch (TimeoutException e) {\r\n\t\t}\r\n\t\tlong end = System.currentTimeMillis();\r\n\t\tint runtime = (int) (end - start);\r\n\t\tint timeNeededToRealizeCancel = (int) (end - cancelEvent.get());\r\n\t\tassertTrue(\"Runtime must be at least 5 seconds, actually should be at least 10 seconds.\", runtime >= INTERRUPTION_DELAY);\r\n\t\tassertTrue(\"The algorithm has not terminated within \" + INTERRUPTION_CLEANUP_TOLERANCE + \"ms after it has been canceled.\", timeNeededToRealizeCancel < INTERRUPTION_CLEANUP_TOLERANCE);\r\n\t\tassertTrue(\"The algorithm has not emitted an AlgorithmExecutionCanceledException.\", cancellationExceptionSeen);\r\n\t\twaitForThreadsToAssumeNumber(numberOfThreadsBefore);\r\n\t\tcheckNotInterrupted();\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testQuickTimeout() throws Exception {\r\n\r\n\t\t/* set up algorithm */\r\n\t\tIAlgorithmFactory<I, O> factory = getFactory();\r\n\t\tfactory.setProblemInput(getDifficultProblemInputForGeneralTestPurposes());\r\n\t\tIAlgorithm<I, O> algorithm = factory.getAlgorithm();\r\n\t\talgorithm.setNumCPUs(Runtime.getRuntime().availableProcessors());\r\n\t\tFutureTask<O> task = new FutureTask<>(algorithm);\r\n\t\talgorithm.setTimeout(INTERRUPTION_DELAY, TimeUnit.MILLISECONDS);\r\n\t\tint numberOfThreadsBefore = Thread.activeCount();\r\n\r\n\t\t/* launch algorithm */\r\n\t\tlong start = System.currentTimeMillis();\r\n\t\tThread t = new Thread(task, \"TimeoutTest Algorithm runner for \" + algorithm);\r\n\t\tt.start();\r\n\t\ttry {\r\n\t\t\ttask.get(INTERRUPTION_DELAY + INTERRUPTION_CLEANUP_TOLERANCE, TimeUnit.MILLISECONDS);\r\n\t\t} catch (TimeoutException e) {\r\n\t\t}\r\n\t\tlong end = System.currentTimeMillis();\r\n\t\tint runtime = (int) (end - start);\r\n\t\tassertTrue(\"Runtime must be at least 5 seconds, actually should be at least 10 seconds.\", runtime >= INTERRUPTION_DELAY);\r\n\t\tassertTrue(\"The algorithm has not terminated within \" + INTERRUPTION_CLEANUP_TOLERANCE + \" ms after the specified timeout.\", runtime < INTERRUPTION_DELAY + INTERRUPTION_CLEANUP_TOLERANCE);\r\n\t\twaitForThreadsToAssumeNumber(numberOfThreadsBefore);\r\n\t\tcheckNotInterrupted();\r\n\t}\r\n\r\n\tprivate void checkNotInterrupted() {\r\n\t\tassertTrue(\"Executing thread is interrupted, which must not be the case!\", !Thread.currentThread().isInterrupted());\r\n\t}\r\n\r\n\tprivate void waitForThreadsToAssumeNumber(int numberOfThreads) throws InterruptedException {\r\n\t\tint n = 10;\r\n\t\tint numberOfThreadsAfter = Thread.activeCount();\r\n\t\tfor (int i = 0; i < n && numberOfThreadsAfter > numberOfThreads; i++) {\r\n\t\t\tThread.sleep(THREAD_SHUTDOWN_TOLERANCE / n);\r\n\t\t\tnumberOfThreadsAfter = Thread.activeCount();\r\n\t\t}\r\n\t\tassertEquals(\"Number of threads has changed during execution\", numberOfThreads, numberOfThreadsAfter);\r\n\t}\r\n\r\n\tprivate class CheckingEventListener {\r\n\t\tboolean observedInit = false;\r\n\t\tboolean observedInitExactlyOnce = false;\r\n\t\tboolean observedInitBeforeFinish = false;\r\n\t\tboolean observedFinish = false;\r\n\t\tboolean observedFinishExactlyOnce = false;\r\n\r\n\t\tpublic void receiveEvent(AlgorithmEvent e) {\r\n\r\n\t\t\tif (e instanceof AlgorithmInitializedEvent)\r\n\t\t\t\treceiveEvent((AlgorithmInitializedEvent) e);\r\n\t\t\telse if (e instanceof AlgorithmFinishedEvent)\r\n\t\t\t\treceiveEvent((AlgorithmFinishedEvent) e);\r\n\r\n\t\t\t/* ignore other events */\r\n\t\t}\r\n\r\n\t\t@Subscribe\r\n\t\tpublic void receiveEvent(AlgorithmInitializedEvent e) {\r\n\t\t\tif (!observedInit) {\r\n\t\t\t\tobservedInit = true;\r\n\t\t\t\tobservedInitExactlyOnce = true;\r\n\t\t\t\tif (!observedFinish)\r\n\t\t\t\t\tobservedInitBeforeFinish = true;\r\n\t\t\t} else {\r\n\t\t\t\tobservedInitExactlyOnce = false;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t@Subscribe\r\n\t\tpublic void receiveEvent(AlgorithmFinishedEvent e) {\r\n\t\t\tif (!observedFinish) {\r\n\t\t\t\tobservedFinish = true;\r\n\t\t\t\tobservedFinishExactlyOnce = true;\r\n\t\t\t} else\r\n\t\t\t\tobservedFinishExactlyOnce = false;\r\n\t\t}\r\n\r\n\t\tvoid checkState() {\r\n\t\t\tassertTrue(\"No init event was observed\", observedInit);\r\n\t\t\tassertTrue(\"More than one init event was observed\", observedInitExactlyOnce);\r\n\t\t\tassertTrue(\"A finish event was observed prior to an init event\", observedInitBeforeFinish);\r\n\t\t\tassertTrue(\"No finish event was observed\", observedFinish);\r\n\t\t\tassertTrue(\"More than one finish event was observed\", observedFinishExactlyOnce);\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6596278548240662, "alphanum_fraction": 0.6614028811454773, "avg_line_length": 37.83571243286133, "blob_id": "b068861d1e787bfe2942bf7b503ac78199722063", "content_id": "df1299e433b0a951eae9876dcaae77617298d96e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 16338, "license_type": "no_license", "max_line_length": 199, "num_lines": 420, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/gbf/ANDORGraphSearch.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "//package jaicore.search.algorithms.standard.gbf;\r\n//\r\n//import java.util.Collection;\r\n//import java.util.HashMap;\r\n//import java.util.HashSet;\r\n//import java.util.LinkedList;\r\n//import java.util.Map;\r\n//import java.util.Queue;\r\n//import java.util.Set;\r\n//\r\n//import jaicore.basic.PerformanceLogger;\r\n//import jaicore.graph.Graph;\r\n//import jaicore.graph.IGraphAlgorithm;\r\n//import jaicore.graph.IGraphAlgorithmListener;\r\n//import jaicore.graph.LabeledGraph;\r\n//import jaicore.graphvisualizer.events.graphEvents.GraphInitializedEvent;\r\n//import jaicore.graphvisualizer.events.graphEvents.NodeReachedEvent;\r\n//import jaicore.graphvisualizer.events.graphEvents.NodeTypeSwitchEvent;\r\n//import jaicore.search.algorithms.BestFirstSolution;\r\n//import jaicore.search.algorithms.standard.bestfirst.model.AndNode;\r\n//import jaicore.search.algorithms.standard.bestfirst.model.GraphEventBus;\r\n//import jaicore.search.algorithms.standard.bestfirst.model.Node;\r\n//import jaicore.search.algorithms.standard.bestfirst.model.OrNode;\r\n//import jaicore.search.structure.graphgenerator.GoalTester;\r\n//import jaicore.search.structure.graphgenerator.NodeGoalTester;\r\n//import jaicore.search.structure.graphgenerator.SingleRootGenerator;\r\n//import jaicore.search.structure.graphgenerator.SuccessorGenerator;\r\n//import meka.core.A;\n//\n//public abstract class ANDORGraphSearch<T, A, V extends Comparable<V>> implements IGraphAlgorithm<T,A,IGraphAlgorithmListener<T, A>, GBFSolution<T, A, V>>> {\n//\n//\t/* meta vars for controlling the general behavior */\n//\tprivate int expandedCounter;\n//\tprivate boolean initialized = false;\n//\tprivate boolean interrupted = false;\n//\n//\t/* communication */\n//\tprivate final GraphEventBus<Node<T, V>> eventBus = new GraphEventBus<>();\n//\n//\t/* search related objects */\n//\tprotected final SingleRootGenerator<T> rootGenerator;\n//\tprotected final SuccessorGenerator<T, A> successorGenerator;\n//\tprotected final NodeGoalTester<T> goalTester;\n//\tprotected final Map<T, Node<T, V>> ext2int = new HashMap<>();\n//\tprivate Node<T, V> root;\n//\tprotected final LabeledGraph<Node<T, V>, A> traversalGraph = new LabeledGraph<>();\n//\tprotected final Set<Node<T, V>> solvedNodes = new HashSet<>();\n//\tprotected final Set<Node<T, V>> recursivelyExhaustedNodes = new HashSet<>();\n//\n//\t/* methods that need refinement */\n//\tabstract protected Node<T, V> initialize();\n//\n//\tabstract protected Graph<Node<T, V>> nextSolutionBase();\n//\n//\tabstract protected Node<T, V> nextNode(Graph<Node<T, V>> solutionBase);\n//\n//\tabstract protected Collection<Node<T, V>> expand(Node<T, V> expanded);\n//\n//\tabstract protected int getNumberOfOpenNodesInSolutionBase(Graph<Node<T, V>> solutionBase);\n//\n//\tpublic ANDORGraphSearch(SingleRootGenerator<T> rootGenerator, SuccessorGenerator<T, A> successorGenerator, GoalTester<T> goalTester) {\n//\t\tsuper();\n//\t\tthis.rootGenerator = rootGenerator;\n//\t\tthis.successorGenerator = successorGenerator;\n//\t\tthis.goalTester = (NodeGoalTester<T>)goalTester;\n//\t}\n//\n//\t/**\n//\t * Find the shortest path to a goal starting from <code>start</code>.\n//\t *\n//\t * @param start\n//\t * The initial node.\n//\t * @return A list of nodes from the initial point to a goal, <code>null</code> if a path doesn't exist.\n//\t */\n//\tpublic LabeledGraph<T, A> getSolution() {\n//\n//\t\t/* create initial node */\n//\t\tif (!initialized) {\n//\t\t\tinitialized = true;\n//\t\t\troot = initialize();\n//\t\t\tthis.eventBus.post(new GraphInitializedEvent<T>(root.getPoint()));\n//\t\t}\n//\n//\t\t/* run actual algorithm */\n//\t\tGraph<Node<T, V>> solutionBase = nextSolutionBase();\n//\t\tNode<T, V> nodeToExpandNext = nextNode(solutionBase);\n//\t\twhile (nodeToExpandNext != null && !interrupted && !Thread.interrupted()) {\n//\n//\t\t\tsimpleSolvedLabeling(root);\n//\t\t\tfor (Node<T, V> solvedNode : solvedNodes) {\n//\t\t\t\teventBus.post(new NodeTypeSwitchEvent<T>(solvedNode.getPoint(), (solvedNode instanceof AndNode ? \"and\" : \"or\") + \"_solution\"));\n//\t\t\t}\n//\n//\t\t\t/* now return a solution if we found one; this can actually be done before */\n//\t\t\tif (solvedNodes.contains(root)) {\n//\t\t\t\treturn getBestSolutionGraph();\n//\t\t\t}\n//\t\t\t\n//\t\t\t/* acquire next node to expand */\n//\t\t\texpandNode(nodeToExpandNext);\n//\n//\t\t\t/* jump to next one */\n//\t\t\tsolutionBase = nextSolutionBase();\n//\t\t\tnodeToExpandNext = nextNode(solutionBase);\n//\t\t}\n//\t\treturn null;\n//\t}\n//\n//\tprotected void expandNode(Node<T, V> nodeToExpand) {\n//\n//\t\t/* perform expand step */\n//\t\tT externalRepresentation = nodeToExpand.getPoint();\n//\t\teventBus.post(new NodeTypeSwitchEvent<T>(externalRepresentation, \"expanding\"));\n//\t\tSet<Node<T, V>> knownNodes = new HashSet<>(traversalGraph.getItems());\n//\t\tPerformanceLogger.logStart(\"successor node computation\");\n//\t\tCollection<Node<T, V>> insertedChildren = expand(nodeToExpand);\n//\t\tPerformanceLogger.logEnd(\"successor node computation\");\n//\t\tPerformanceLogger.logStart(\"successor node labeling\");\n//\t\tfor (Node<T, V> successor : insertedChildren) {\n//\t\t\tString state = knownNodes.contains(successor) ? \"closed\" : \"open\";\n//\t\t\teventBus.post(new NodeReachedEvent<T>(nodeToExpand.getPoint(), successor.getPoint(), (successor instanceof AndNode ? \"and\" : \"or\") + \"_\" + state));\n//\t\t\texhaustiveSolvedLabeling(successor);\n//\t\t}\n//\t\tPerformanceLogger.logEnd(\"successor node labeling\");\n//\n//\t\t/* if this was a dead end, then add the node to the exhausted ones (relevant for efficient solved labeling) */\n//\t\tif (insertedChildren.isEmpty()) {\n//\t\t\trecursivelyExhaustedNodes.add(nodeToExpand);\n//\t\t}\n//\n//\t\texpandedCounter++;\n//\t\tif (!solvedNodes.contains(nodeToExpand))\n//\t\t\teventBus.post(new NodeTypeSwitchEvent<T>(externalRepresentation, (nodeToExpand instanceof AndNode ? \"and\" : \"or\") + \"_closed\"));\n//\t}\n//\n//\t/**\n//\t * Check how many times a node was expanded.\n//\t *\n//\t * @return A counter of how many times a node was expanded.\n//\t */\n//\tpublic int getExpandedCounter() {\n//\t\treturn expandedCounter;\n//\t}\n//\n//\tpublic int getCreatedCounter() {\n//\t\treturn traversalGraph.getItems().size();\n//\t}\n//\n//\tpublic int getEdgesCounter() {\n//\t\tint numEdges = 0;\n//\t\tfor (Node<T, V> node : traversalGraph.getItems())\n//\t\t\tnumEdges += traversalGraph.getSuccessors(node).size();\n//\t\treturn numEdges;\n//\t}\n//\n//\tpublic void interrupt() {\n//\t\tthis.interrupted = true;\n//\t}\n//\n//\tprotected OrNode<T, V> getOrNode(Node<T, V> parent, T ext, A edgeLabel) {\n//\t\tif (!ext2int.containsKey(ext)) {\n//\t\t\tOrNode<T, V> n = new OrNode<>(null, ext);\n//\t\t\text2int.put(ext, n);\n//\t\t\ttraversalGraph.addItem(n);\n//\t\t}\n//\t\tOrNode<T, V> n = (OrNode<T, V>) ext2int.get(ext);\n//\t\tif (parent != null) {\n//\t\t\tif (edgeLabel == null)\n//\t\t\t\tthrow new IllegalArgumentException(\"Edge label must not be null!\");\n//\t\t\ttraversalGraph.addEdge(parent, n, edgeLabel);\n//\t\t}\n//\t\treturn n;\n//\t}\n//\n//\tprotected AndNode<T, V> getAndNode(Node<T, V> parent, T ext, A edgeLabel) {\n//\t\tif (!ext2int.containsKey(ext)) {\n//\t\t\tAndNode<T, V> n = new AndNode<>(null, ext);\n//\t\t\text2int.put(ext, n);\n//\t\t\ttraversalGraph.addItem(n);\n//\t\t}\n//\t\tAndNode<T, V> n = (AndNode<T, V>) ext2int.get(ext);\n//\t\tif (parent != null) {\n//\t\t\tif (edgeLabel == null)\n//\t\t\t\tthrow new IllegalArgumentException(\"Edge label must not be null!\");\n//\t\t\ttraversalGraph.addEdge(parent, n, edgeLabel);\n//\t\t}\n//\t\treturn n;\n//\t}\n//\n//\tpublic GraphEventBus<Node<T, V>> getEventBus() {\n//\t\treturn eventBus;\n//\t}\n//\n//\tprotected void bottom2topLabeling(Node<T, V> n) {\n//\t\tboolean solution = simpleSolvedLabeling(n);\n//\t\tif (solution) {\n//\t\t\tCollection<Node<T, V>> parents = traversalGraph.getPredecessors(n);\n//\t\t\tfor (Node<T, V> parent : parents) {\n//\t\t\t\tbottom2topLabeling(parent);\n//\t\t\t}\n//\t\t}\n//\t}\n//\n//\tprotected boolean simpleSolvedLabeling(Node<T, V> n) {\n//\n//\t\t/* if node is solved, announce this */\n//\t\tif (solvedNodes.contains(n)) {\n//\t\t\treturn true;\n//\t\t}\n//\n//\t\tCollection<Node<T, V>> successors = traversalGraph.getSuccessors(n);\n//\t\tif (successors.isEmpty()) {\n//\t\t\tif (goalTester.isGoal(n.getPoint())) {\n//\t\t\t\tsolvedNodes.add(n);\n//\t\t\t\treturn true;\n//\t\t\t}\n//\t\t\treturn false;\n//\t\t}\n//\n//\t\tfor (Node<T, V> successor : successors) {\n//\t\t\tif (simpleSolvedLabeling(successor)) {\n//\t\t\t\tif (n instanceof OrNode) {\n//\t\t\t\t\tsolvedNodes.add(n);\n//\t\t\t\t\treturn true;\n//\t\t\t\t}\n//\t\t\t} else if (n instanceof AndNode) {\n//\t\t\t\treturn false;\n//\t\t\t}\n//\t\t}\n//\n//\t\t/* if this is an or-node, it has not been solved; if it is an and-node, it has been solved */\n//\t\tif (n instanceof OrNode) {\n//\t\t\treturn false;\n//\t\t} else {\n//\t\t\tsolvedNodes.add(n);\n//\t\t\treturn true;\n//\t\t}\n//\t}\n//\n//\tprotected boolean exhaustiveSolvedLabeling(Node<T, V> n) {\n//\n//\t\t/* if node is solved, announce this */\n//\t\tif (solvedNodes.contains(n) && recursivelyExhaustedNodes.contains(n)) {\n//\t\t\treturn true;\n//\t\t}\n//\n//\t\t/* if there is no successor, return true if the node is a goal and false otherwise (node may not have been expanded yet) */\n//\t\tCollection<Node<T, V>> successors = traversalGraph.getSuccessors(n);\n//\t\tif (successors.isEmpty()) {\n//\t\t\tif (goalTester.isGoal(n.getPoint())) {\n//\t\t\t\tsolvedNodes.add(n);\n//\t\t\t\trecursivelyExhaustedNodes.add(n);\n//\t\t\t\treturn true;\n//\t\t\t}\n//\t\t\treturn false;\n//\t\t}\n//\n//\t\t/* compute solved state based on successors */\n//\t\tif (recursivelyExhaustedNodes.containsAll(successors)) {\n//\t\t\trecursivelyExhaustedNodes.add(n);\n//\t\t}\n//\t\tfor (Node<T, V> successor : successors) {\n//\t\t\tboolean solution = exhaustiveSolvedLabeling(successor);\n//\t\t\tif (solution) {\n//\t\t\t\tif (n instanceof OrNode) {\n//\t\t\t\t\tsolvedNodes.add(n);\n//\t\t\t\t}\n//\t\t\t} else if (n instanceof AndNode) {\n//\t\t\t\treturn false;\n//\t\t\t}\n//\t\t}\n//\t\tif (n instanceof OrNode) {\n//\t\t\treturn solvedNodes.contains(n);\n//\t\t}\n//\n//\t\t/* if this is an or-node, it has not been solved; if it is an and-node, it has been solved */\n//\t\tif (n instanceof OrNode) {\n//\t\t\treturn false;\n//\t\t} else {\n//\t\t\tsolvedNodes.add(n);\n//\t\t\treturn true;\n//\t\t}\n//\t}\n//\n//\tprotected LabeledGraph<T, A> getBestSolutionGraph() {\n//\t\tLabeledGraph<T,A> g = new LabeledGraph<>();\n//\t\tg.addItem(root.getPoint());\n//\t\tQueue<Node<T, V>> open = new LinkedList<>();\n//\t\topen.add(root);\n//\t\twhile (!open.isEmpty()) {\n//\t\t\tNode<T, V> next = open.poll();\n//\t\t\tfor (Node<T, V> succ : traversalGraph.getSuccessors(next)) {\n//\t\t\t\tif (next instanceof AndNode) {\n//\t\t\t\t\tg.addItem(succ.getPoint());\n//\t\t\t\t\tg.addEdge(next.getPoint(), succ.getPoint(), traversalGraph.getEdgeLabel(next, succ));\n//\t\t\t\t\topen.add(succ);\n//\t\t\t\t} else if (next instanceof OrNode) {\n//\t\t\t\t\tif (solvedNodes.contains(succ)) {\n//\t\t\t\t\t\tg.addItem(succ.getPoint());\n//\t\t\t\t\t\tg.addEdge(next.getPoint(), succ.getPoint(), traversalGraph.getEdgeLabel(next, succ));\n//\t\t\t\t\t\topen.add(succ);\n//\t\t\t\t\t\tbreak;\n//\t\t\t\t\t}\n//\t\t\t\t}\n//\t\t\t}\n//\t\t}\n//\t\treturn g;\n//\t}\n//\n//\tpublic LabeledGraph<T, A> getExternalTraversalGraph() {\n//\t\treturn getExternalGraph(traversalGraph);\n//\t}\n//\n//\tpublic LabeledGraph<T, A> getExternalGraph(LabeledGraph<Node<T, V>, A> internalGraph) {\n//\t\tLabeledGraph<T, A> graph = new LabeledGraph<>();\n//\t\tfor (Node<T, V> n : internalGraph.getItems()) {\n//\t\t\tgraph.addItem(n.getPoint());\n//\t\t}\n//\t\tfor (Node<T, V> n1 : internalGraph.getItems()) {\n//\t\t\tfor (Node<T, V> n2 : internalGraph.getSuccessors(n1)) {\n//\t\t\t\tgraph.addEdge(n1.getPoint(), n2.getPoint(), internalGraph.getEdgeLabel(n1, n2));\n//\t\t\t}\n//\t\t}\n//\t\treturn graph;\n//\t}\n//\n//\tpublic Graph<T> getExternalGraph(Graph<Node<T, V>> internalGraph) {\n//\t\tGraph<T> graph = new Graph<>();\n//\t\tfor (Node<T, V> n : internalGraph.getItems()) {\n//\t\t\tgraph.addItem(n.getPoint());\n//\t\t}\n//\t\tfor (Node<T, V> n1 : internalGraph.getItems()) {\n//\t\t\tfor (Node<T, V> n2 : internalGraph.getSuccessors(n1)) {\n//\t\t\t\tgraph.addEdge(n1.getPoint(), n2.getPoint());\n//\t\t\t}\n//\t\t}\n//\t\treturn graph;\n//\t}\n//\n//\t// protected Collection<LabeledGraph<Node<T, V>, A>> getAllSolutionGraphs(Node<T, V> node) {\n//\t// if (!solvedNodes.contains(node))\n//\t// return new ArrayList<>();\n//\t//\n//\t// if (completeSolutionGraphSets.containsKey(node)) {\n//\t// Collection<LabeledGraph<Node<T,V>,A>> solutions = completeSolutionGraphSets.get(node).stream().map(graph -> new LabeledGraph<Node<T,V>,A>(graph)).collect(Collectors.toList());\n//\t// assert !solutions.stream().filter(subgraph -> subgraph.getSources().size() != 1).findAny().isPresent() : \"at least one subgraph has multiple roots\";\n//\t// assert !solutions.stream().filter(subgraph -> subgraph.getSources().iterator().next() != node).findAny().isPresent() : \"at least one of the \" + solutions.size() + \" returned subgraphs has a\n//\t// root that is different from the given node\";\n//\t// return solutions;\n//\t// }\n//\t// Collection<LabeledGraph<Node<T, V>, A>> solutions = new ArrayList<>();\n//\t//\n//\t// /* for leaf nodes, insert a graph with only one node */\n//\t// if (traversalGraph.getSuccessors(node).isEmpty()) {\n//\t// LabeledGraph<Node<T, V>, A> graph = new LabeledGraph<>();\n//\t// graph.addItem(node);\n//\t// assert graph.getSources().size() == 1 : \"Returning a subgraph with \" + graph.getSources().size() + \" roots\";\n//\t// assert graph.getSources().iterator().next() == node : \"Returning subgraph whose root is not the given node.\";\n//\t// solutions.add(graph);\n//\t// }\n//\t//\n//\t// else if (node instanceof OrNode) {\n//\t// for (Node<T, V> successor : traversalGraph.getSuccessors(node)) {\n//\t// A edgeLabel = traversalGraph.getEdgeLabel(node, successor);\n//\t// if (edgeLabel == null) {\n//\t// System.err.println(\"The edge between \" + node + \" and \" + successor + \" has no label!\");\n//\t// }\n//\t// for (LabeledGraph<Node<T, V>, A> subgraph : getAllSolutionGraphs(successor)) {\n//\t// assert subgraph.getSources().iterator().next() == successor : \"The root of the subgraph is \" + subgraph.getSources().iterator().next() + \", but the successor should be \" + successor + \"!\";\n//\t// subgraph.addItem(node);\n//\t// subgraph.addEdge(node, successor, edgeLabel);\n//\t// assert subgraph.getSources().size() == 1 : \"Returning subgraph with \" + subgraph.getSources().size() + \" roots.\";\n//\t// assert subgraph.getSources().iterator().next() == node : \"Returning subgraph whose root is not the given node.\";\n//\t// solutions.add(subgraph);\n//\t// }\n//\t// }\n//\t// } else if (node instanceof AndNode) {\n//\t// List<Collection<LabeledGraph<Node<T, V>, A>>> subgraphsPerSuccessor = new ArrayList<>();\n//\t// for (Node<T, V> successor : traversalGraph.getSuccessors(node)) {\n//\t// Collection<LabeledGraph<Node<T, V>, A>> subgraphs = getAllSolutionGraphs(successor);\n//\t// assert !subgraphs.stream().filter(subgraph -> subgraph.getSources().size() != 1).findAny().isPresent() : \"at least one subgraph has multiple roots\";\n//\t// subgraphsPerSuccessor.add(subgraphs);\n//\t// }\n//\t// for (List<LabeledGraph<Node<T, V>, A>> tuple : SetUtil.cartesianProduct(subgraphsPerSuccessor)) {\n//\t// LabeledGraph<Node<T, V>, A> mergedGraph = new LabeledGraph<>();\n//\t// mergedGraph.addItem(node);\n//\t// for (LabeledGraph<Node<T, V>, A> subgraph : tuple) {\n//\t// mergedGraph.addGraph(subgraph);\n//\t// Node<T, V> root = subgraph.getSources().iterator().next();\n//\t// mergedGraph.addEdge(node, root, traversalGraph.getEdgeLabel(node, root));\n//\t// }\n//\t// assert mergedGraph.getSources().size() == 1 : \"Returning subgraph with \" + mergedGraph.getSources().size() + \" roots.\";\n//\t// assert mergedGraph.getSources().iterator().next() == node : \"Returning subgraph whose root is not the given node.\";\n//\t// solutions.add(mergedGraph);\n//\t// }\n//\t// }\n//\t//\n//\t// /* return the solutions */\n//\t// assert !solutions.stream().filter(subgraph -> subgraph.getSources().size() != 1).findAny().isPresent() : \"at least one of the \" + solutions.size() + \" returned subgraphs has multiple roots: \" +\n//\t// solutions.stream().filter(subgraph -> subgraph.getSources().size() != 1).findAny().get().getSources();\n//\t// assert !solutions.stream().filter(subgraph -> subgraph.getSources().iterator().next() != node).findAny().isPresent() : \"at least one of the \" + solutions.size() + \" returned subgraphs has a\n//\t// root that is different from the given node\";\n//\t// if (recursivelyExhaustedNodes.contains(node))\n//\t// completeSolutionGraphSets.put(node, solutions);\n//\t// return solutions;\n//\t// }\n//\n//\tpublic Collection<Node<T, V>> getPredecessors(Node<T, V> node) {\n//\t\treturn traversalGraph.getPredecessors(node);\n//\t}\n//\n//\tpublic Collection<Node<T, V>> getSuccessors(Node<T, V> node) {\n//\t\treturn traversalGraph.getSuccessors(node);\n//\t}\n//\n//\t@Override\n//\tpublic void registerListener(Object listener) {\n//\t\tthis.eventBus.register(listener);\n//\t}\n//}\n" }, { "alpha_fraction": 0.8247036933898926, "alphanum_fraction": 0.8247036933898926, "avg_line_length": 49.09375, "blob_id": "a2b20f2afc5710c224512dc31277eeb7831cadb6", "content_id": "3d52a26f1993beea4a0f00d0b3bec30b605ce810", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1603, "license_type": "no_license", "max_line_length": 145, "num_lines": 32, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/parallel/parallelexploration/distributed/interfaces/DistributedSearchCommunicationLayer.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.parallel.parallelexploration.distributed.interfaces;\n\nimport java.util.Collection;\n\nimport jaicore.search.algorithms.parallel.parallelexploration.distributed.DistributedComputationResult;\nimport jaicore.search.algorithms.standard.bestfirst.nodeevaluation.INodeEvaluator;\nimport jaicore.search.model.travesaltree.Node;\n\npublic interface DistributedSearchCommunicationLayer<T,A,V extends Comparable<V>> {\n\t\n\t/* infrastructural operations */\n\tpublic void close();\n\t\n\t/* master operations */\n\tpublic void init();\n\tpublic Collection<String> detectNewCoworkers();\n\tpublic void createNewJobForCoworker(String coworker, Collection<Node<T,V>> nodes);\n\tpublic void attachCoworker(String coworker);\n\tpublic void detachCoworker(String coworker);\n\tpublic DistributedComputationResult<T, V> readResult(String coworker);\n\tpublic void setGraphGenerator(SerializableGraphGenerator<T, A> generator) throws Exception;\n\tpublic void setNodeEvaluator(SerializableNodeEvaluator<T, V> evaluator) throws Exception;\n\t\n\t/* coworker operations */\n\tpublic void register(String coworker) throws InterruptedException; // registers the coworker on the bus and blocks him until it becomes attached\n\tpublic void unregister(String coworker);\n\tpublic boolean isAttached(String coworker);\n\tpublic Collection<Node<T,V>> nextJob(String coworker) throws InterruptedException;\n\tpublic SerializableGraphGenerator<T,A> getGraphGenerator() throws Exception;\n\tpublic INodeEvaluator<T,V> getNodeEvaluator() throws Exception;\n\tpublic void reportResult(String coworker, DistributedComputationResult<T, V> results);\n}\n" }, { "alpha_fraction": 0.7027277946472168, "alphanum_fraction": 0.7051401138305664, "avg_line_length": 32.681251525878906, "blob_id": "c7ca37098f0d47e1e165dabfdd82707101f401ba", "content_id": "96f06a11f6b433a8c0602c591101cc4518983381", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5389, "license_type": "no_license", "max_line_length": 129, "num_lines": 160, "path": "/JAICore/jaicore-planning/test/jaicore/planning/gui/FXGuiTester.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "//package jaicore.planning.gui;\n//\n//import java.util.Arrays;\n//import java.util.Collection;\n//import java.util.List;\n//\n//import org.junit.Test;\n//\n//import jaicore.graphvisualizer.gui.FXController;\n//import jaicore.graphvisualizer.gui.FXGui;\n//import jaicore.graphvisualizer.gui.Recorder;\n//import jaicore.planning.algorithms.forwarddecomposition.ForwardDecompositionHTNPlanner;\n//import jaicore.planning.graphgenerators.task.tfd.TFDNode;\n//import jaicore.planning.graphgenerators.task.tfd.TFDTooltipGenerator;\n//import jaicore.planning.model.task.ceocstn.CEOCSTNPlanningProblem;\n//import jaicore.planning.model.task.ceocstn.StandardProblemFactory;\n//import jaicore.search.algorithms.standard.bestfirst.BestFirst;\n//import jaicore.search.core.interfaces.GraphGenerator;\n//import jaicore.search.gui.dataSupplier.BestFSupplier;\n//import jaicore.search.gui.dataSupplier.TooltipSupplier;\n//import jaicore.search.model.travesaltree.Node;\n//import jaicore.search.testproblems.bestfirst.abstractVersioning.TestGraphGenerator;\n//import jaicore.search.testproblems.bestfirst.abstractVersioning.TestNode;\n//import jaicore.search.testproblems.nqueens.NQueenGenerator;\n//import jaicore.search.testproblems.nqueens.QueenNode;\n//import javafx.application.Application;\n//import javafx.stage.Stage;\n//\n//public class FXGuiTester extends Application {\n//\n//\tFXGui gui;\n//\n//\t@Test\n//\tpublic void test() {\n//\t\tlaunch();\n//\t}\n//\n//\t@Override\n//\tpublic void start(Stage stage) throws Exception {\n//\t\tgui = new FXGui();\n//\t\t// bestFirstTest();\n//\n//\t\t// tooltipTest();\n//\t\t//\n//\t\t// dataSupplierTest();\n//\t\t//\n//\t\tbestFTest();\n//\n//\t}\n//\n//\tprivate void bestFirstTest() throws InterruptedException {\n//\t\tGraphGenerator generator = new TestGraphGenerator();\n//\t\tBestFirst<TestNode, String, Double> bf = new BestFirst<>(generator, n -> (double) Math.round(Math.random() * 100));\n//\t\t// open(bf,\"BestFirst\");\n//\n//\t\tRecorder rec = new Recorder(bf);\n//\n//\t\tgui.open(rec, \"Recorder\");\n//\n//\t\t// TooltipSupplier supplier = new TooltipSupplier();\n//\t\t// supplier.setGenerator(n->{\n//\t\t// Node node =(Node) n;\n//\t\t// return String.valueOf(((Node) n).getInternalLabel());\n//\t\t// });\n//\n//\t\t// rec.addDataSupplier(supplier);\n//\n//\t\t// FXController controller = gui.getControllers().get(gui.getControllers().size()-1);\n//\t\t// if(controller != null)\n//\t\t// controller.registerSupplier(sup);\n//\n//\t\t// bf.registerListener(supplier);\n//\t\tbf.nextSolution();\n//\n//\t}\n//\n//\tprivate void tooltipTest() {\n//\n//\t\tCollection<String> init = Arrays.asList(new String[] { \"A\", \"B\", \"C\", \"D\" });\n//\t\tCEOCSTNPlanningProblem problem = StandardProblemFactory.getNestedDichotomyCreationProblem(\"root\", init, true, 0, 0);\n//\t\tForwardDecompositionHTNPlanner planner = new ForwardDecompositionHTNPlanner(problem, 1);\n//\t\tForwardDecompositionHTNPlanner.SolutionIterator plannerRun = planner.iterator();\n//\t\t// new VisualizationWindow<Node<TFDNode,Double>>(plannerRun.getSearch()).setTooltipGenerator(new TFDTooltipGenerator<>());\n//\n//\t\tRecorder<Node<TFDNode, Double>> recorder = new Recorder<>(plannerRun.getSearch());\n//\t\t// recorder.setTooltipGenerator(new TFDTooltipGenerator<>());\n//\t\tTooltipSupplier dataSupplier = new TooltipSupplier();\n//\t\tdataSupplier.setGenerator(new TFDTooltipGenerator());\n//\n//\t\tplannerRun.getSearch().registerListener(dataSupplier);\n//\t\t/* solve problem */\n//\t\tSystem.out.println(\"Starting search. Waiting for solutions:\");\n//\t\twhile (plannerRun.hasNext()) {\n//\t\t\tList<TFDNode> solution = (List<TFDNode>) plannerRun.next();\n//\t\t\tSystem.out.println(\"\\t\" + solution);\n//\t\t}\n//\t\tSystem.out.println(\"Algorithm has finished.\");\n//\n//\t\t// recorder.addNodeDataSupplier(dataSupplier);\n//\n//\t\tgui.open(recorder, \"TooltipTest\");\n//\t\tFXController controller = gui.getControllers().get(gui.getControllers().size() - 1);\n//\t\tif (controller != null)\n//\t\t\tcontroller.registerSupplier(dataSupplier);\n//\t}\n//\n//\tprivate void dataSupplierTest() throws InterruptedException {\n//\n//\t\tGraphGenerator<TestNode,String> generator = new TestGraphGenerator();\n//\t\tBestFirst<TestNode,String,Double> bf = new BestFirst<>(generator, n -> (double) Math.round(Math.random() * 100));\n//\t\t// open(bf,\"BestFirst\");\n//\n//\t\tRecorder rec = new Recorder(bf);\n//\n//\t\tgui.open(rec, \"Recorder\");\n//\n//\t\t// rec.setTooltipGenerator(n->{\n//\t\t// Node node = (Node) n;\n//\t\t// return String.valueOf(node.getInternalLabel());\n//\t\t// });\n//\n//\t\tTooltipSupplier dataSupplier = new TooltipSupplier();\n//\n//\t\tdataSupplier.setGenerator((n -> {\n//\t\t\tNode node = (Node) n;\n//\t\t\tComparable c = node.getInternalLabel();\n//\t\t\tString s = String.valueOf(c);\n//\t\t\treturn String.valueOf(s);\n//\t\t}));\n//\n//\t\trec.addDataSupplier(dataSupplier);\n//\n//\t\tbf.nextSolution();\n//\n//\t\tgui.open();\n//\n//\t}\n//\n//\tprivate void bestFTest() throws InterruptedException {\n//\t\tNQueenGenerator gen = new NQueenGenerator(8);\n//\t\tBestFirst<QueenNode, String, Double> search = new BestFirst<>(gen, n -> (double) n.getPoint().getNumberOfNotAttackedCells());\n//\n//\t\tRecorder rec = new Recorder(search);\n//\t\tgui.open(rec, \"Queens\");\n//\n//\t\tBestFSupplier dataSupplier = new BestFSupplier();\n//\n//\t\trec.registerListener(dataSupplier);\n//\n//\t\t// rec.addGraphDataSupplier(dataSupplier);\n//\n//\t\tFXController controller = gui.getControllers().get(gui.getControllers().size() - 1);\n//\t\tif (controller != null)\n//\t\t\tcontroller.registerSupplier(dataSupplier);\n//\n//\t\tsearch.nextSolution();\n//\n//\t}\n//\n//}\n" }, { "alpha_fraction": 0.7381889820098877, "alphanum_fraction": 0.7381889820098877, "avg_line_length": 29.75, "blob_id": "907c3b7c0f4f7b0e77f83a5a5f1f757adf5d290b", "content_id": "3690c687480b94bedd9db5edfcd729059dc7e13b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 508, "license_type": "no_license", "max_line_length": 93, "num_lines": 16, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/mcts/UCT.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.mcts;\r\n\r\nimport java.util.Random;\r\n\r\nimport jaicore.search.model.probleminputs.GraphSearchProblemInput;\r\n\r\npublic class UCT<T,A> extends MCTS<T,A,Double> {\r\n\r\n\tpublic UCT(GraphSearchProblemInput<T, A, Double> problem, boolean maximization, int seed) {\r\n\t\tsuper(problem, new UCBPolicy<>(maximization), new UniformRandomPolicy<>(new Random(seed)));\r\n\t}\r\n\t\r\n\tpublic UCT(GraphSearchProblemInput<T, A, Double> problem, int seed) {\r\n\t\tthis(problem, false, seed);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.691769540309906, "alphanum_fraction": 0.6975308656692505, "avg_line_length": 28.375, "blob_id": "3c395111aa1cbb1ca9be866f2d9b871ffab1984a", "content_id": "aaeae9fa7ece5c5c97693dd0bf77d286ea79be45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2430, "license_type": "no_license", "max_line_length": 173, "num_lines": 80, "path": "/JAICore/jaicore-planning/experiments/jaicore/planning/graphgenerators/pddl/PDDLGraphGeneratorTester.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.graphgenerators.pddl;\r\n\r\nimport static org.junit.Assert.assertNotNull;\r\nimport static org.junit.Assert.assertTrue;\r\nimport static org.junit.Assert.fail;\r\n\r\nimport java.io.File;\r\nimport java.io.IOException;\r\nimport java.util.List;\r\n\r\nimport javax.swing.JFileChooser;\r\n\r\nimport org.junit.Test;\r\n\r\nimport fr.uga.pddl4j.encoding.CodedProblem;\r\nimport fr.uga.pddl4j.planners.ProblemFactory;\r\nimport fr.uga.pddl4j.planners.hsp.HSP;\r\nimport fr.uga.pddl4j.util.Plan;\r\nimport fr.uga.pddl4j.util.SequentialPlan;\r\nimport jaicore.search.algorithms.standard.astar.AStar;\r\n\r\npublic class PDDLGraphGeneratorTester {\r\n\r\n\t@Test\r\n\tpublic void test() throws InterruptedException {\r\n\t\tFile domain = null;\r\n\t\tFile problem = null;\r\n\r\n\t\tJFileChooser chooser = new JFileChooser();\r\n\t\tchooser.setDialogTitle(\" Open a Domain-File\");\r\n\t\tchooser.showOpenDialog(null);\r\n\t\tdomain = chooser.getSelectedFile();\r\n\t\t// domain = new File(\"/home/jkoepe/git/pddl4j/pddl/blocksworld/domain.pddl\");\r\n\r\n\t\tchooser.setDialogTitle(\"Open a Problme-File\");\r\n\t\tchooser.showOpenDialog(null);\r\n\t\tproblem = chooser.getSelectedFile();\r\n\t\t// problem = new File(\"/home/jkoepe/git/pddl4j/pddl/blocksworld/p15.pddl\");\r\n\r\n\t\tif (domain.exists() && problem.exists()) {\r\n\t\t\tPDDLGraphGenerator gen = new PDDLGraphGenerator(domain, problem);\r\n\t\t\tgen.setNodeNumbering(true);\r\n\r\n\t\t\t// create a Astar-serch with the heuristic given pddl4j\r\n\t\t\tAStar<PDDLNode, String> search = new AStar<>(gen, (s1, s2) -> 1.0, state -> (double) gen.getHeuristic().estimate(state.getPoint().getNode(), gen.getProblem().getGoal()));\r\n\r\n\t\t\tif (gen.getProblem().isSolvable()) {\r\n\t\t\t\tList<PDDLNode> solution = search.nextSolution();\r\n\t\t\t\tassertNotNull(solution);\r\n\r\n\t\t\t\tPlan plan = gen.extractPlan(solution);\r\n\t\t\t\tassertNotNull(plan);\r\n\r\n\t\t\t\tplan.actions().stream().forEach(n -> System.out.println(n.getName()));\r\n\r\n\t\t\t\tProblemFactory factory = new ProblemFactory();\r\n\t\t\t\ttry {\r\n\t\t\t\t\tfactory.parse(domain, problem);\r\n\r\n\t\t\t\t\tCodedProblem enc = factory.encode();\r\n\r\n\t\t\t\t\tHSP hspComp = new HSP();\r\n\r\n\t\t\t\t\tSequentialPlan hspPlan = hspComp.search(enc);\r\n\r\n\t\t\t\t\t// assertNotNull(hspPlan);\r\n\r\n\t\t\t\t} catch (IOException e) {\r\n\t\t\t\t\tSystem.out.println(\"The comparrison with HSP did not work\");\r\n\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t}\r\n\t\t\t} else\r\n\t\t\t\tfail(\"problem not solvable\");\r\n\r\n\t\t} else\r\n\t\t\tSystem.out.println(\"Either the domain file was not found or the problem file\");\r\n\t\tassertTrue(true);\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.6749311089515686, "alphanum_fraction": 0.6804407835006714, "avg_line_length": 25.88888931274414, "blob_id": "9f5fcc763a35347e64883fed42441eac80e4306c", "content_id": "5c77ae1e81ff50ee3fcd62df4219d502d23244bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 726, "license_type": "no_license", "max_line_length": 92, "num_lines": 27, "path": "/JAICore/jaicore-basic/src/jaicore/basic/ValueUtil.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.basic;\n\npublic class ValueUtil {\n\n /**\n * Forbid to create an object of ListHelper as there are only static methods allowed here.\n */\n private ValueUtil() {\n // intentionally do nothing\n }\n\n public static String valueToString(final double value, final int decimals) {\n StringBuilder sb = new StringBuilder();\n sb.append(round(value, decimals));\n while (sb.toString().length() < decimals + 2) {\n sb.append(\"0\");\n }\n return sb.toString();\n }\n\n public static double round(final double valueToRound, final int decimals) {\n int multiplier = (int) Math.pow(10, decimals);\n double raisedValue = Math.round(valueToRound * multiplier);\n return raisedValue / multiplier;\n }\n\n}\n" }, { "alpha_fraction": 0.7903030514717102, "alphanum_fraction": 0.7903030514717102, "avg_line_length": 46.52941131591797, "blob_id": "5d4ccc9f5d7d57054d8c4b8bfe084d0fcefc56f5", "content_id": "312dbb70241383c0002c96570cf8abc9727d6f8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 825, "license_type": "no_license", "max_line_length": 138, "num_lines": 17, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/lds/BestFirstLimitedDiscrepancySearchFactory.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.lds;\r\n\r\nimport jaicore.search.core.interfaces.StandardORGraphSearchFactory;\r\nimport jaicore.search.model.other.EvaluatedSearchGraphPath;\r\nimport jaicore.search.model.probleminputs.NodeRecommendedTree;\r\nimport jaicore.search.model.travesaltree.Node;\r\n\r\npublic class BestFirstLimitedDiscrepancySearchFactory<T, A, V extends Comparable<V>>\r\n\t\textends StandardORGraphSearchFactory<NodeRecommendedTree<T, A>, EvaluatedSearchGraphPath<T, A, V>, T, A, V, Node<T, NodeOrderList>, A> {\r\n\r\n\t@Override\r\n\tpublic BestFirstLimitedDiscrepancySearch<T, A, V> getAlgorithm() {\r\n\t\tif (getProblemInput() == null)\r\n\t\t\tthrow new IllegalArgumentException(\"Cannot create algorithm; problem input has not been set yet\");\r\n\t\treturn new BestFirstLimitedDiscrepancySearch<T, A, V>(getProblemInput());\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6044880747795105, "alphanum_fraction": 0.6297335028648376, "avg_line_length": 26.423076629638672, "blob_id": "e5a3c383b88521294eb84297035a41f00d11fd08", "content_id": "ec93034a89bd02e218aeb6e6c6874075b5327806", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Gradle", "length_bytes": 713, "license_type": "no_license", "max_line_length": 69, "num_lines": 26, "path": "/JAICore/jaicore-ml/build.gradle", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "sourceSets {\n main {\n java {\n srcDir 'src'\n }\n }\n test {\n \tjava {\n \t\tsrcDir 'test'\n \t}\n }\n}\ndependencies {\n\tcompile project(\":JAICore:jaicore-basic\")\n\tcompile project(\":JAICore:jaicore-search\")\n\tcompile project(\":JAICore:jaicore-graphvisualizer\")\n\tcompile project(\":JAICore:jaicore-experiments\")\n\tcompile group: 'org.openml', name: 'apiconnector', version: '1.0.16'\n\tcompile group: 'de.upb.isys', name: 'omlwebapp', version: '0.0.1'\n\tcompile group: 'de.upb.isys', name: 'meka', version: '0.0.1'\n\tcompile ('de.upb.isys:interruptable-weka:0.0.7') {\n\t exclude group: 'log4j'\n exclude group: 'org.slf4j'\n\t}\n\tcompile group: 'black.ninia', name: 'jep', version: '3.8.2'\n}\n" }, { "alpha_fraction": 0.7772873044013977, "alphanum_fraction": 0.778892457485199, "avg_line_length": 36.19403076171875, "blob_id": "dc5f8ecbdeb2d1226cabf8ed892cd8ebbfd129b9", "content_id": "9e6ebd9ea3bce0a7655af9f4c26dccf09759aea2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2492, "license_type": "no_license", "max_line_length": 176, "num_lines": 67, "path": "/JAICore/jaicore-planning/src/jaicore/planning/model/task/ceocipstn/CEOCIPSTNPlanningProblem.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.model.task.ceocipstn;\n\nimport java.util.Map;\n\nimport jaicore.logic.fol.structure.CNFFormula;\nimport jaicore.logic.fol.structure.Monom;\nimport jaicore.logic.fol.theories.EvaluablePredicate;\nimport jaicore.planning.graphgenerators.task.ceociptfd.OracleTaskResolver;\nimport jaicore.planning.model.ceoc.CEOCAction;\nimport jaicore.planning.model.ceoc.CEOCOperation;\nimport jaicore.planning.model.task.ceocstn.CEOCSTNPlanningDomain;\nimport jaicore.planning.model.task.ceocstn.CEOCSTNPlanningProblem;\nimport jaicore.planning.model.task.stn.TaskNetwork;\n\n@SuppressWarnings(\"serial\")\npublic class CEOCIPSTNPlanningProblem<O extends CEOCOperation, M extends OCIPMethod, A extends CEOCAction> extends CEOCSTNPlanningProblem<O, M, A> {\n\tprivate final Map<String, EvaluablePredicate> evaluablePlanningPredicates;\n\tprivate final Map<String, OracleTaskResolver> oracleResolvers;\n\n\tpublic CEOCIPSTNPlanningProblem(CEOCSTNPlanningDomain<O, M> domain, CNFFormula knowledge, Monom init, TaskNetwork network, Map<String, EvaluablePredicate> evaluablePredicates,\n\t\t\tMap<String, OracleTaskResolver> oracleResolvers) {\n\t\tsuper(domain, knowledge, init, network);\n\t\tthis.evaluablePlanningPredicates = evaluablePredicates;\n\t\tthis.oracleResolvers = oracleResolvers;\n\t}\n\n\tpublic Map<String, EvaluablePredicate> getEvaluablePlanningPredicates() {\n\t\treturn evaluablePlanningPredicates;\n\t}\n\n\tpublic Map<String, OracleTaskResolver> getOracleResolvers() {\n\t\treturn oracleResolvers;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = super.hashCode();\n\t\tresult = prime * result + ((evaluablePlanningPredicates == null) ? 0 : evaluablePlanningPredicates.hashCode());\n\t\tresult = prime * result + ((oracleResolvers == null) ? 0 : oracleResolvers.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (!super.equals(obj))\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tCEOCIPSTNPlanningProblem<O,M,A> other = (CEOCIPSTNPlanningProblem<O,M,A>) obj;\n\t\tif (evaluablePlanningPredicates == null) {\n\t\t\tif (other.evaluablePlanningPredicates != null)\n\t\t\t\treturn false;\n\t\t} else if (!evaluablePlanningPredicates.equals(other.evaluablePlanningPredicates))\n\t\t\treturn false;\n\t\tif (oracleResolvers == null) {\n\t\t\tif (other.oracleResolvers != null)\n\t\t\t\treturn false;\n\t\t} else if (!oracleResolvers.equals(other.oracleResolvers))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n}\n" }, { "alpha_fraction": 0.8008474707603455, "alphanum_fraction": 0.8008474707603455, "avg_line_length": 28.5, "blob_id": "393968782527338a6fbb205b6f3d7e18dd492e7c", "content_id": "9fee3f0ac79406d56440ce36769ef88586485745", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 472, "license_type": "no_license", "max_line_length": 71, "num_lines": 16, "path": "/JAICore/jaicore-ml/src/jaicore/ml/interfaces/LabeledInstances.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.ml.interfaces;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic interface LabeledInstances<L> extends List<LabeledInstance<L>> {\n\t\n\tpublic int getNumberOfRows();\n\tpublic int getNumberOfColumns();\n\tpublic String toJson();\n\tpublic void addAllFromJson(String jsonString) throws IOException;\n\tpublic void addAllFromJson(File jsonFile) throws IOException;\n\tpublic ArrayList<L> getOccurringLabels();\n}\n" }, { "alpha_fraction": 0.7265538573265076, "alphanum_fraction": 0.7317028045654297, "avg_line_length": 38.2814826965332, "blob_id": "9d7d1e526c55e069129f386a2d78b0c88133499c", "content_id": "62ca7aa384b6cace7b54087e9110e6c642de376c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5438, "license_type": "no_license", "max_line_length": 165, "num_lines": 135, "path": "/JAICore/jaicore-search/test/jaicore/search/testproblems/nqueens/NQueenTester.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.testproblems.nqueens;\r\n\r\nimport static org.junit.Assert.assertEquals;\r\nimport static org.junit.Assert.assertNotNull;\r\nimport static org.junit.Assert.assertTrue;\r\n\r\nimport java.util.Iterator;\r\nimport java.util.concurrent.atomic.AtomicInteger;\r\n\r\nimport com.google.common.eventbus.Subscribe;\r\n\r\nimport jaicore.basic.algorithm.AlgorithmEvent;\r\nimport jaicore.basic.algorithm.AlgorithmFinishedEvent;\r\nimport jaicore.basic.algorithm.AlgorithmInitializedEvent;\r\nimport jaicore.basic.algorithm.SolutionCandidateFoundEvent;\r\nimport jaicore.graph.IGraphAlgorithmListener;\r\nimport jaicore.graphvisualizer.gui.VisualizationWindow;\r\nimport jaicore.search.algorithms.standard.ORGraphSearchTester;\r\nimport jaicore.search.algorithms.standard.bestfirst.events.GraphSearchSolutionCandidateFoundEvent;\r\nimport jaicore.search.core.interfaces.IGraphSearch;\r\nimport jaicore.search.core.interfaces.IGraphSearchFactory;\r\n\r\npublic abstract class NQueenTester<I, O, VSearch, ESearch> extends ORGraphSearchTester<Integer, I, O, QueenNode, String, Double, VSearch, ESearch>\r\n\t\timplements IGraphAlgorithmListener<VSearch, ESearch> {\r\n\r\n\tint[] numbersOfSolutions = { 2, 10, 4, 40, 92, 352, 724 };\r\n\r\n\tprivate AtomicInteger seenSolutions = new AtomicInteger(0);\r\n\tprivate boolean showGraphs = false;\r\n\r\n\tIGraphSearchFactory<I, O, QueenNode, String, Double, VSearch, ESearch> searchFactory = getFactory();\r\n\r\n\tprivate IGraphSearch<I, O, QueenNode, String, Double, VSearch, ESearch> getSearchProblemInput(int n) {\r\n\t\tsearchFactory.setProblemInput(n, getProblemReducer());\r\n\t\tIGraphSearch<I, O, QueenNode, String, Double, VSearch, ESearch> search = searchFactory.getAlgorithm();\r\n\t\treturn search;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void testThatIteratorReturnsEachPossibleSolution() {\r\n\t\tif (searchFactory == null)\r\n\t\t\tthrow new IllegalArgumentException(\"Search factory has not been set\");\r\n\t\tfor (int i = 0; i < numbersOfSolutions.length; i++) {\r\n\t\t\tint n = i + 4;\r\n\t\t\tSystem.out.print(\"Checking \" + n + \"-Queens Problem ... \");\r\n\t\t\tIGraphSearch<I, O, QueenNode, String, Double, VSearch, ESearch> search = getSearchProblemInput(n);\r\n\t\t\tassertNotNull(\"The factory has not returned any search object.\", search);\r\n\t\t\tif (showGraphs)\r\n\t\t\t\tnew VisualizationWindow<>(search);\r\n\t\t\tboolean initialized = false;\r\n\t\t\tboolean terminated = false;\r\n\t\t\tint solutions = 0;\r\n\t\t\tIterator<AlgorithmEvent> iterator = search.iterator();\r\n\t\t\tassertNotNull(\"The search algorithm does return NULL as an iterator for itself.\", iterator);\r\n\t\t\twhile (iterator.hasNext()) {\r\n\t\t\t\tAlgorithmEvent e = search.next();\r\n\t\t\t\tassertNotNull(\"The search iterator has returned NULL even though hasNext suggested that more event should come.\", e);\r\n\t\t\t\tif (!initialized) {\r\n\t\t\t\t\tassertTrue(e instanceof AlgorithmInitializedEvent);\r\n\t\t\t\t\tinitialized = true;\r\n\t\t\t\t} else if (e instanceof AlgorithmFinishedEvent) {\r\n\t\t\t\t\tterminated = true;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tassertTrue(!terminated);\r\n\t\t\t\t\tif (e instanceof SolutionCandidateFoundEvent)\r\n\t\t\t\t\t\tsolutions++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tassertEquals(\"Failed to solve \" + n + \"-queens problem. Only found \" + solutions + \"/\" + numbersOfSolutions[i] + \" solutions.\", numbersOfSolutions[i], solutions);\r\n\t\t\tSystem.out.println(\"done\");\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void testThatAnEventForEachPossibleSolutionIsEmittedInSimpleCall() throws Exception {\r\n\t\tif (searchFactory == null)\r\n\t\t\tthrow new IllegalArgumentException(\"Search factory has not been set\");\r\n\t\tfor (int i = 0; i < numbersOfSolutions.length; i++) {\r\n\t\t\tint n = i + 4;\r\n\t\t\tSystem.out.print(\"Checking \" + n + \"-Queens Problem ... \");\r\n\t\t\tIGraphSearch<I, O, QueenNode, String, Double, VSearch, ESearch> search = getSearchProblemInput(n);\r\n\t\t\tassertNotNull(\"The factory has not returned any search object.\", search);\r\n\t\t\tif (showGraphs)\r\n\t\t\t\tnew VisualizationWindow<>(search);\r\n\t\t\tsearch.registerListener(this);\r\n\t\t\tseenSolutions = new AtomicInteger(0);\r\n\t\t\tsearch.call();\r\n\t\t\tassertEquals(numbersOfSolutions[i], seenSolutions.get());\r\n\t\t\tSystem.out.println(\"done\");\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void testThatAnEventForEachPossibleSolutionIsEmittedInParallelizedCall() throws Exception {\r\n\t\tif (searchFactory == null)\r\n\t\t\tthrow new IllegalArgumentException(\"Search factory has not been set\");\r\n\t\tfor (int i = 0; i < numbersOfSolutions.length; i++) {\r\n\t\t\tint n = i + 4;\r\n\t\t\tSystem.out.print(\"Checking \" + n + \"-Queens Problem ... \");\r\n\t\t\tIGraphSearch<I, O, QueenNode, String, Double, VSearch, ESearch> search = getSearchProblemInput(n);\r\n\t\t\tassertNotNull(\"The factory has not returned any search object.\", search);\r\n\t\t\tif (showGraphs)\r\n\t\t\t\tnew VisualizationWindow<>(search);\r\n\t\t\tsearch.registerListener(this);\r\n\t\t\tsearch.setNumCPUs(Runtime.getRuntime().availableProcessors());\r\n\t\t\tseenSolutions = new AtomicInteger(0);\r\n\t\t\tsearch.call();\r\n\t\t\tassertEquals(numbersOfSolutions[i], seenSolutions.get());\r\n\t\t\tSystem.out.println(\"done\");\r\n\t\t}\r\n\t}\r\n\r\n\t@Subscribe\r\n\tpublic void registerSolution(GraphSearchSolutionCandidateFoundEvent<QueenNode, String> solution) {\r\n\t\tseenSolutions.incrementAndGet();\r\n\t}\r\n\r\n\tpublic boolean isShowGraphs() {\r\n\t\treturn showGraphs;\r\n\t}\r\n\r\n\tpublic void setShowGraphs(boolean showGraphs) {\r\n\t\tthis.showGraphs = showGraphs;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic I getSimpleProblemInputForGeneralTestPurposes() {\r\n\t\treturn getProblemReducer().transform(4);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic I getDifficultProblemInputForGeneralTestPurposes() {\r\n\t\treturn getProblemReducer().transform(100);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7771317958831787, "alphanum_fraction": 0.7848837375640869, "avg_line_length": 31.25, "blob_id": "c2c40d44cfdf5d42cc4bbb928b6777228d8a4429", "content_id": "92fcd74decb4bd12cb7068546706bf957115f8f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1548, "license_type": "no_license", "max_line_length": 84, "num_lines": 48, "path": "/softwareconfiguration/mlplan/test/de/upb/crc901/automl/metamining/pipelinecharacterizing/WEKAOntologyConnectorTest.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package de.upb.crc901.automl.metamining.pipelinecharacterizing;\n\nimport static org.junit.Assert.assertEquals;\n\nimport java.util.List;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.semanticweb.owlapi.model.OWLOntologyCreationException;\n\nimport de.upb.crc901.mlplan.metamining.pipelinecharacterizing.WEKAOntologyConnector;\n\npublic class WEKAOntologyConnectorTest {\n\t\n\tprivate WEKAOntologyConnector connector;\n\t\n\t@Before\n\tpublic void initializeOntologyConnector() throws OWLOntologyCreationException {\n\t\tconnector = new WEKAOntologyConnector();\n\t}\n\t\n\t@Test\n\tpublic void testGetAncestorsOfClassifiers() {\n\t\tconnector.getAvailableClassifiers().forEach(classifier -> {\n\t\t\tList<String> ancestors = connector.getAncestorsOfClassifier(classifier);\n\t\t\tassertEquals(ancestors.get(0), connector.getClassifierTopNode());\n\t\t\tassertEquals(ancestors.get(ancestors.size()-1), classifier);\n\t\t});\n\t}\n\t\n\t@Test\n\tpublic void testGetAncestorsOfEvaluators() {\n\t\tconnector.getAvailableEvaluators().forEach(evaluator -> {\n\t\t\tList<String> ancestors = connector.getAncestorsOfEvaluator(evaluator);\n\t\t\tassertEquals(ancestors.get(0), connector.getEvaluatorTopNode());\n\t\t\tassertEquals(ancestors.get(ancestors.size()-1), evaluator);\n\t\t});\n\t}\n\t\n\t@Test\n\tpublic void testGetAncestorsOfSearchers() {\n\t\tconnector.getAvailableSearchers().forEach(searcher -> {\n\t\t\tList<String> ancestors = connector.getAncestorsOfSearcher(searcher);\n\t\t\tassertEquals(ancestors.get(0), connector.getSearcherTopNode());\n\t\t\tassertEquals(ancestors.get(ancestors.size()-1), searcher);\n\t\t});\n\t}\n}\n" }, { "alpha_fraction": 0.6489221453666687, "alphanum_fraction": 0.6520017385482788, "avg_line_length": 33.515625, "blob_id": "035b5cbe23489c7084f53319102012142b03e021", "content_id": "54ad164dd71edb998575e6997fa1917eef8e7cfb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 6819, "license_type": "no_license", "max_line_length": 127, "num_lines": 192, "path": "/softwareconfiguration/mlplan/src/de/upb/crc901/mlplan/multiclasswithreduction/RPNDOracleTaskSolver.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "//package de.upb.crc901.mlplan.multiclasswithreduction;\r\n//\r\n//import java.util.ArrayList;\r\n//import java.util.Collection;\r\n//import java.util.HashMap;\r\n//import java.util.HashSet;\r\n//import java.util.List;\r\n//import java.util.Map;\r\n//import java.util.Random;\r\n//import java.util.Set;\r\n//\r\n//import org.slf4j.Logger;\r\n//import org.slf4j.LoggerFactory;\r\n//\r\n//import jaicore.basic.sets.SetUtil;\r\n//import jaicore.basic.sets.SetUtil.Pair;\r\n//import jaicore.logic.fol.structure.ConstantParam;\r\n//import jaicore.logic.fol.structure.Literal;\r\n//import jaicore.logic.fol.structure.Monom;\r\n//import jaicore.logic.fol.structure.VariableParam;\r\n//import jaicore.logic.fol.theories.set.SetTheoryUtil;\r\n//import jaicore.planning.graphgenerators.task.ceociptfd.OracleTaskResolver;\r\n//import jaicore.planning.model.ceoc.CEOCAction;\r\n//import jaicore.planning.model.ceoc.CEOCOperation;\r\n//import jaicore.planning.model.core.Action;\r\n//import jaicore.planning.model.core.Operation;\r\n//import jaicore.planning.model.task.ceocipstn.CEOCIPSTNPlanningProblem;\r\n//import weka.core.Instances;\r\n//\r\n//public class RPNDOracleTaskSolver implements OracleTaskResolver {\r\n//\r\n//\tprivate static final Logger logger = LoggerFactory.getLogger(RPNDOracleTaskSolver.class);\r\n//\tprivate final Random rand;\r\n//\tprivate final String classifierName;\r\n//\tprivate final Instances data;\r\n//\tprivate CEOCOperation configChildNodesOp;\r\n//\r\n//\tpublic RPNDOracleTaskSolver(Random rand, String classifierName, Instances data, CEOCIPSTNPlanningProblem problem) {\r\n//\t\tsuper();\r\n//\t\tthis.rand = rand;\r\n//\t\tthis.classifierName = classifierName;\r\n//\t\tthis.data = data;\r\n//\t\tfor (Operation op : problem.getDomain().getOperations()) {\r\n//\t\t\tif (op.getName().equals(\"configChildNodes\")) {\r\n//\t\t\t\tconfigChildNodesOp = (CEOCOperation) op;\r\n//\t\t\t\tbreak;\r\n//\t\t\t}\r\n//\t\t}\r\n//\t\tif (configChildNodesOp == null)\r\n//\t\t\tthrow new IllegalArgumentException(\"Domain has no operation with name \\\"configChildNodes\\\"\");\r\n//\t}\r\n//\r\n//\tprivate interface Splitter {\r\n//\t\tSplit split(Collection<String> set) throws Exception;\r\n//\t}\r\n//\r\n//\tclass Split extends Pair<Set<String>, Set<String>> {\r\n//\r\n//\t\tpublic Split(Set<String> x, Set<String> y) {\r\n//\t\t\tsuper(x, y);\r\n//\t\t}\r\n//\r\n//\t\t@Override\r\n//\t\tpublic String toString() {\r\n//\t\t\treturn \"Split [getX()=\" + getX() + \", getY()=\" + getY() + \"]\";\r\n//\t\t}\r\n//\t}\r\n//\r\n//\tprivate class RPNDSplitter implements Splitter {\r\n//\r\n//\t\tprivate final Instances data;\r\n//\r\n//\t\tpublic RPNDSplitter(Instances data) {\r\n//\t\t\tsuper();\r\n//\t\t\tthis.data = data;\r\n//\t\t}\r\n//\r\n//\t\t@Override\r\n//\t\tpublic Split split(Collection<String> set) throws Exception {\r\n//\t\t\tClassSplit<String> split = NestedDichotomyUtil.createGeneralRPNDBasedSplit(set, rand, classifierName, data);\r\n//\t\t\treturn new Split(new HashSet<>(split.getL()), new HashSet<>(split.getR()));\r\n//\t\t}\r\n//\t}\r\n//\r\n////\tprivate class RandomSplit implements Splitter {\r\n////\r\n////\t\t@Override\r\n////\t\tpublic Split split(Collection<String> setOrig) {\r\n////\t\t\tList<String> set = new ArrayList<>(setOrig);\r\n////\t\t\tCollections.shuffle(set, rand);\r\n////\t\t\tint offset = rand.nextInt(set.size() - 1);\r\n////\r\n////\t\t\t/* perform this specific split */\r\n////\t\t\tSet<String> c1 = new HashSet<>();\r\n////\t\t\tSet<String> c2 = new HashSet<>();\r\n////\t\t\tboolean offsetReached = false;\r\n////\t\t\tint i = 0;\r\n////\t\t\tfor (String b : set) {\r\n////\t\t\t\tif (!offsetReached)\r\n////\t\t\t\t\tc1.add(b);\r\n////\t\t\t\telse\r\n////\t\t\t\t\tc2.add(b);\r\n////\t\t\t\ti++;\r\n////\t\t\t\tif (i == offset)\r\n////\t\t\t\t\toffsetReached = true;\r\n////\t\t\t}\r\n////\r\n////\t\t\treturn new Split(c1, c2);\r\n////\t\t}\r\n////\t}\r\n//\r\n////\tprivate class GreedySplitter implements Splitter {\r\n////\r\n////\t\tprivate final Instances data;\r\n////\r\n////\t\tpublic GreedySplitter(Instances data) {\r\n////\t\t\tsuper();\r\n////\t\t\tthis.data = data;\r\n////\t\t}\r\n////\r\n////\t\t@Override\r\n////\t\tpublic Split split(Collection<String> set) {\r\n////\t\t\t// ClassSplit<String> split = NestedDichotomyUtil.createGreedySplit(set, rand, classifierName, data);\r\n////\t\t\t// return new Split(new HashSet<>(split.getL()), new HashSet<>(split.getR()));\r\n////\t\t\treturn null;\r\n////\t\t}\r\n////\t}\r\n//\r\n//\t@Override\r\n//\tpublic Collection<List<Action>> getSubSolutions(Monom state, Literal task) throws Exception {\r\n//\r\n//\t\t/* prepare template grounding for actions */\r\n//\t\tString nameOfParent = task.getConstantParams().get(0).getName();\r\n//\t\tString nameOfLC = task.getConstantParams().get(1).getName();\r\n//\t\tString nameOfRC = task.getConstantParams().get(2).getName();\r\n//\t\tMap<VariableParam, ConstantParam> groundingTemplate = new HashMap<>();\r\n//\t\tgroundingTemplate.put(new VariableParam(\"p\"), new ConstantParam(nameOfParent));\r\n//\t\tgroundingTemplate.put(new VariableParam(\"lc\"), new ConstantParam(nameOfLC));\r\n//\t\tgroundingTemplate.put(new VariableParam(\"rc\"), new ConstantParam(nameOfRC));\r\n//\r\n//\t\tList<String> set = new ArrayList<>(SetTheoryUtil.getObjectsInSet(state, nameOfParent));\r\n//\t\tlogger.info(\"Compute RPND split for {}\", set);\r\n//\r\n//\t\tif (set.size() <= 1) {\r\n//\t\t\t// throw new UnsupportedOperationException(\"Cannot create successor where rest problem consists of one or less classes.\");\r\n//\t\t\treturn new ArrayList<>();\r\n//\t\t}\r\n//\r\n//\t\t/* if no decision is to be made, return the single possible solution */\r\n//\t\tif (set.size() == 2) {\r\n//\r\n//\t\t\t/* determine subsolutions */\r\n//\t\t\tCollection<List<Action>> subsolutions = new ArrayList<>();\r\n//\t\t\tMap<VariableParam, ConstantParam> grounding = new HashMap<>(groundingTemplate);\r\n//\t\t\tgrounding.put(new VariableParam(\"ss\"), new ConstantParam(\"{\" + set.get(0) + \"}\"));\r\n//\t\t\tList<Action> subsolution = new ArrayList<>();\r\n//\t\t\tsubsolution.add(new CEOCAction(configChildNodesOp, grounding));\r\n//\t\t\tsubsolutions.add(subsolution);\r\n//\t\t\treturn subsolutions;\r\n//\t\t}\r\n//\r\n//\t\tList<Splitter> splitters = new ArrayList<>();\r\n//\t\t// int max = (int)Math.log(set.size());\r\n//\t\tint max = 1;\r\n//\t\tlogger.info(\"Make {} suggestions for {} classes\", max, set.size());\r\n//\t\tfor (int i = 0; i < max; i++) {\r\n//\t\t\tsplitters.add(new RPNDSplitter(data));\r\n//\t\t\t// splitters.add(new GreedySplitter(data));\r\n//\t\t}\r\n//\r\n//\t\t/* determine subsolutions */\r\n//\t\tCollection<List<Action>> subsolutions = new ArrayList<>();\r\n//\t\ttry {\r\n//\t\t\tfor (Splitter splitter : splitters) {\r\n//\t\t\t\tlogger.info(\"Compute next split\");\r\n//\t\t\t\tSplit split = splitter.split(set);\r\n//\t\t\t\tlogger.info(\"Split computed: {}\", split);\r\n//\t\t\t\tMap<VariableParam, ConstantParam> grounding = new HashMap<>(groundingTemplate);\r\n//\t\t\t\tgrounding.put(new VariableParam(\"ss\"), new ConstantParam(SetUtil.serializeAsSet(split.getX())));\r\n//\t\t\t\tList<Action> subsolution = new ArrayList<>();\r\n//\t\t\t\tsubsolution.add(new CEOCAction(configChildNodesOp, grounding));\r\n//\t\t\t\tsubsolutions.add(subsolution);\r\n//\t\t\t}\r\n//\t\t} catch (InterruptedException e) {\r\n//\r\n//\t\t}\r\n//\r\n//\t\tlogger.info(\"Ready with RPND computation\");\r\n//\t\treturn subsolutions;\r\n//\t}\r\n//\r\n//}\r\n" }, { "alpha_fraction": 0.6006249785423279, "alphanum_fraction": 0.6089583039283752, "avg_line_length": 21.748815536499023, "blob_id": "16d343b09541c48317b90f647ae56f3daad60a04", "content_id": "47b713381fe8e0de4336735f0a3880a293af5841", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4800, "license_type": "no_license", "max_line_length": 110, "num_lines": 211, "path": "/JAICore/jaicore-search/test/jaicore/search/testproblems/npuzzle/standard/NPuzzleNode.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.testproblems.npuzzle.standard;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Random;\n\n/**\n * A node for the normal n-Puzzleproblem.\n * Every node contains the current board configuration as an 2D-Array of integer.\n * The empty space is indicated by an Integer with value 0.\n * @author jkoepe\n */\npublic class NPuzzleNode {\n\t//board configuration and empty space\n\tprotected int [][] board;\n\tprotected int emptyX;\n\tprotected int emptyY;\n\tprotected int numberOfMoves;\n\t\n\t/**\n\t * Constructor for a NPuzzleNode which creates a NPuzzleNode with complete \n\t * randomly distributed numbers.\n\t * @param dim\n\t * \t\tThe dimension of the board.\n\t */\n\tpublic NPuzzleNode(int dim) {\n\t\tthis(dim, 0);\n\t}\n\t\n\t/**\n\t * Constructor for a NPuzzleNode which creates a NPuzzleNode.\n\t * The board configuration starts with the targetconfiguration and shuffels the tiles afterwards.\n\t * @param dim\n\t * \t\t\tThe dimension of the board.\n\t * @param perm\n\t * \t\t\tThe number of moves which should be made before starting the search.\n\t * \t\t\tThis number is hardcoded to at least 1.\n\t */\n\tpublic NPuzzleNode(int dim, int seed) {\n\t\tthis.board = new int[dim][dim];\n\t\tList<Integer> numbers = new ArrayList<>();\n\t\tfor (int i = 0 ; i < dim * dim; i++)\n\t\t\tnumbers.add(i);\n\t\tCollections.shuffle(numbers, new Random(seed));\n\t\tint c = 0;\n\t\tfor(int i = 0; i < dim; i++) {\n\t\t\tfor(int j = 0; j < dim; j++) {\n\t\t\t\tboard[i][j] = numbers.get(c++);\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(this);\n\t}\n\t\n\t/**\n\t * Constructor for a NPuzzleNode in which the board is already given.\n\t * @param board\n\t * \t\t\tThe board configuration for this node\n\t * @param emptyX\n\t * \t\t\tThe empty space on the x-axis.\n\t * @param emptyY\n\t * \t\t\tThe empty space on the y-axis.\n\t * \n\t * @param noMoves\n\t * \t\t\tThe number of already done moves.\n\t */\n\tpublic NPuzzleNode(int [][] board, int emptyX, int emptyY, int numberOfMoves) {\n\t\tthis.board = board;\n\t\tthis.emptyX = emptyX;\n\t\tthis.emptyY = emptyY;\n\t\tthis.numberOfMoves = numberOfMoves;\n\t}\n\n\t\n\tpublic int[][] getBoard() {\n\t\treturn board;\n\t}\n\n\tpublic int getEmptyX() {\n\t\treturn emptyX;\n\t}\n\n\tpublic int getEmptyY() {\n\t\treturn emptyY;\n\t}\n\t\n\tpublic int getNumberOfMoves() {\n\t\treturn this.numberOfMoves;\n\t}\n\t\n\t\n\t/**\n\t * Returns a graphical version of the board configuration. \n\t * Works best if there is no number with two or more digits.\n\t */\n\t@Override\n\tpublic String toString() {\n//\t\treturn \"NPuzzleNode [board=\" + Arrays.toString(board) + \", emptyX=\" + emptyX + \", emptyY=\" + emptyY + \"]\";\n\t\tString s = \"\";\n\t\t\n\t\tfor(int j = 0; j < board.length; j++) {\n\t\t\ts+= \"----\";\n\t\t}\n\t\ts+= \"\\n\";\n\t\t\n\t\tfor(int i = 0; i< board.length; i++) {\n\t\t\ts += \"| \";\n\t\t\tfor(int j = 0; j < board.length; j++) {\n\t\t\t\ts += board[i][j] + \" | \";\n\t\t\t}\n\t\t\ts += \"\\n\";\n\t\t\tfor(int j = 0; j < board.length; j++) {\n\t\t\t\ts+= \"----\";\n\t\t\t}\n\t\t\ts += \"\\n\";\n\t\t}\n\t\treturn s;\n\t}\n\t\n\t/**\n\t * Returns the number of wrongly placed tiles\n\t * @return\n\t * \t\tThe number of wrongly placed tiles.\n\t */\n\tpublic int getNumberOfWrongTiles() {\n\t\tint wrongTiles = 0;\n\t\tint x = 1;\n\t\tfor(int i = 0; i < board.length; i++) {\n\t\t\tfor(int j = 0; j < board.length; j++) {\n\t\t\t\tif(i == board.length -1 && j == board.length -1)\n\t\t\t\t\tx = 0;\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(x != board[i][j])\n\t\t\t\t\twrongTiles ++;\n\t\t\t\t\n\t\t\t\tx++;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn wrongTiles;\n\t}\n\n\t/**\n\t * Returns the steps which are minimal need to reach a goal state\n\t * @return\n\t * \tThe number of steps.\n\t */\n\tpublic double getDistance() {\n\t\tdouble d = 0.0;\n\t\tfor(int i = 0; i < board.length; i++) {\n\t\t\tfor(int j = 0; j < board.length; j++) {\n\t\t\t\tint tile = board[i][j];\n\t\t\t\tdouble x = (double)tile / board.length;\n\t\t\t\tdouble y = tile % board.length-1;\n\t\t\t\tif(x%1==0)\n\t\t\t\t\tx--;\n\t\t\t\tx =Math.floor(x);\n\t\t\t\tif (y < 0)\n\t\t\t\t\ty = board.length-1;\n\n\t\t\t\tif(tile == 0) {\n//\t\t\t\t\tx = board.length-1;\n//\t\t\t\t\ty = board.length-1;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tdouble h1 = Math.abs(i-x);\n\t\t\t\tdouble h2 = Math.abs(j-y);\n\t\t\t\tdouble d1 = h1+h2;\n\t\t\t\td+= d1;\n\t\t\t}\n\t\t}\n\t\treturn d;\n\t}\n\n\t/* (non-Javadoc)\n\t * @see java.lang.Object#hashCode()\n\t */\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + Arrays.deepHashCode(board);\n//\t\tresult = prime * result + Arrays.hashCode(board);\n\t\tresult = prime * result + emptyX;\n\t\tresult = prime * result + emptyY;\n\t\treturn result;\n\t}\n\n\t/* (non-Javadoc)\n\t * @see java.lang.Object#equals(java.lang.Object)\n\t */\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tNPuzzleNode other = (NPuzzleNode) obj;\n\t\tif (!Arrays.deepEquals(board, other.board))\n\t\t\treturn false;\n\t\tif (emptyX != other.emptyX)\n\t\t\treturn false;\n\t\tif (emptyY != other.emptyY)\n\t\t\treturn false;\n\t\treturn true;\n\t}\n}\n" }, { "alpha_fraction": 0.5972727537155151, "alphanum_fraction": 0.6081818342208862, "avg_line_length": 24, "blob_id": "f7d81de8eb409ba5499c9c7bb892529b9e3510af", "content_id": "9f8115ce9f8c42f15d936e324e697efe54ff6415", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1100, "license_type": "no_license", "max_line_length": 101, "num_lines": 44, "path": "/JAICore/jaicore-basic/src/jaicore/basic/chunks/TaskKeyComparator.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.basic.chunks;\n\nimport java.util.Comparator;\n\npublic class TaskKeyComparator implements Comparator<Task> {\n\n private final String[] sortKeys;\n\n public TaskKeyComparator(final String[] sortKeys) {\n this.sortKeys = sortKeys;\n }\n\n @Override\n public int compare(final Task arg0, final Task arg1) {\n for (String sortKey : this.sortKeys) {\n try {\n int compareInt = arg0.getValueAsInt(sortKey).compareTo(arg1.getValueAsInt(sortKey));\n if (compareInt == 0) {\n continue;\n }\n return compareInt;\n } catch (Exception e) {\n }\n try {\n int compareLong = arg0.getValueAsLong(sortKey).compareTo(arg1.getValueAsLong(sortKey));\n if (compareLong == 0) {\n continue;\n }\n return compareLong;\n } catch (Exception e) {\n }\n try {\n int compareString = arg0.getValueAsString(sortKey).compareTo(arg1.getValueAsString(sortKey));\n if (compareString == 0) {\n continue;\n }\n return compareString;\n } catch (Exception e) {\n }\n }\n return 0;\n }\n\n}\n" }, { "alpha_fraction": 0.6106979250907898, "alphanum_fraction": 0.6124141812324524, "avg_line_length": 27.655736923217773, "blob_id": "d13a0ad319705deb936bd6766f686a766ed33d02", "content_id": "ccd37393d80078551f86ecb5b2f821edcb92adc3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3496, "license_type": "no_license", "max_line_length": 87, "num_lines": 122, "path": "/JAICore/jaicore-search/src/jaicore/search/gui/dataSupplier/BestFSupplier.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.gui.dataSupplier;\n\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.google.common.eventbus.EventBus;\nimport com.google.common.eventbus.Subscribe;\n\nimport jaicore.graphvisualizer.events.controlEvents.ControlEvent;\nimport jaicore.graphvisualizer.events.controlEvents.StepEvent;\nimport jaicore.graphvisualizer.events.graphEvents.GraphInitializedEvent;\nimport jaicore.graphvisualizer.events.graphEvents.NodeReachedEvent;\nimport jaicore.graphvisualizer.events.graphEvents.NodeTypeSwitchEvent;\nimport jaicore.graphvisualizer.events.graphEvents.GraphEvent;\nimport jaicore.graphvisualizer.events.misc.XYEvent;\nimport jaicore.graphvisualizer.gui.dataSupplier.ISupplier;\nimport jaicore.search.model.travesaltree.Node;\nimport javafx.scene.chart.XYChart;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class BestFSupplier implements ISupplier {\n\n private EventBus databus;\n\n private List<Comparable> list;\n private int index;\n\n\n public BestFSupplier(){\n this.list = new ArrayList<>();\n this.databus = new EventBus();\n this.index = 0;\n }\n\n\n @Override\n public void registerListener(Object listener) {\n this.databus.register(listener);\n }\n\n// @Override\n// public String getVisualizerName() {\n// return \"XYGraphVisualizer\";\n// }\n//\n// @Override\n// public String getVisualizerTitle() {\n// return \"BestF\";\n// }\n\n @Subscribe\n public void receiveGraphEvent(GraphEvent event) {\n Node n;\n Comparable f;\n switch(event.getClass().getSimpleName()){\n\n case \"GraphInitializedEvent\":\n GraphInitializedEvent initializedEvent = (GraphInitializedEvent) event;\n n = (Node) initializedEvent.getRoot();\n list.add(n.getInternalLabel());\n break;\n\n case \"NodeTypeSwitchEvent\":\n NodeTypeSwitchEvent nodeTypeSwitchEvent = (NodeTypeSwitchEvent) event;\n n = (Node) nodeTypeSwitchEvent.getNode();\n f= list.get(list.size()-1);\n if(n.getInternalLabel().compareTo(f) <= 0)\n list.add( n.getInternalLabel());\n else\n list.add(f);\n\n break;\n\n case \"NodeReachedEvent\":\n NodeReachedEvent nodeReachedEvent = (NodeReachedEvent) event;\n n = (Node) nodeReachedEvent.getNode();\n f= list.get(list.size()-1);\n if(n.getInternalLabel().compareTo(f) <= 0)\n list.add(n.getInternalLabel());\n else\n list.add(f);\n break;\n\n default:\n System.out.println(\"not an allowed event\");\n break;\n }\n\n XYChart.Data data = new XYChart.Data(index, (double)list.get(index));\n this.databus.post(new XYEvent(data));\n index ++;\n\n }\n\n @Override\n public void receiveControlEvent(ControlEvent event) {\n\n }\n\n @Override\n public JsonNode getSerialization() {\n return null;\n }\n\n\n// @Subscribe\n// public void receiveStepEvent(StepEvent event){\n// if(!event.forward())\n// return;\n//\n// int steps = event.getSteps();\n// while(steps != 0 ){\n// XYChart.Data data = new XYChart.Data(index, (double)list.get(index));\n// this.databus.post(new XYEvent(data));\n// steps --;\n// index ++;\n// }\n//\n// }\n\n\n}\n" }, { "alpha_fraction": 0.7550542950630188, "alphanum_fraction": 0.755774199962616, "avg_line_length": 41.40885543823242, "blob_id": "878f90ad9c21c300f6592411e7921bc3397c15bb", "content_id": "e1fe9153cf8d67ad6d5ee7fb2699d9c7e609b971", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 16669, "license_type": "no_license", "max_line_length": 199, "num_lines": 384, "path": "/softwareconfiguration/hasco/src/hasco/core/HASCO.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package hasco.core;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.Collection;\r\nimport java.util.Iterator;\r\nimport java.util.List;\r\nimport java.util.Map;\r\nimport java.util.concurrent.TimeUnit;\r\nimport java.util.stream.Collectors;\r\n\r\nimport org.aeonbits.owner.ConfigCache;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.google.common.eventbus.EventBus;\r\n\r\nimport hasco.events.HASCOSearchInitializedEvent;\r\nimport hasco.events.HASCOSolutionEvent;\r\nimport hasco.model.Component;\r\nimport hasco.model.ComponentInstance;\r\nimport hasco.model.Parameter;\r\nimport hasco.model.ParameterRefinementConfiguration;\r\nimport hasco.optimizingfactory.SoftwareConfigurationAlgorithm;\r\nimport hasco.reduction.HASCOReduction;\r\nimport jaicore.basic.ILoggingCustomizable;\r\nimport jaicore.basic.algorithm.AlgorithmEvent;\r\nimport jaicore.basic.algorithm.AlgorithmFinishedEvent;\r\nimport jaicore.basic.algorithm.AlgorithmInitializedEvent;\r\nimport jaicore.basic.algorithm.AlgorithmProblemTransformer;\r\nimport jaicore.basic.algorithm.AlgorithmState;\r\nimport jaicore.basic.algorithm.IOptimizerResult;\r\nimport jaicore.graphvisualizer.gui.VisualizationWindow;\r\nimport jaicore.planning.EvaluatedSearchGraphBasedPlan;\r\nimport jaicore.planning.algorithms.forwarddecomposition.ForwardDecompositionReducer;\r\nimport jaicore.planning.graphgenerators.task.tfd.TFDTooltipGenerator;\r\nimport jaicore.planning.model.CostSensitiveHTNPlanningProblem;\r\nimport jaicore.planning.model.CostSensitivePlanningToSearchProblemTransformer;\r\nimport jaicore.planning.model.ceoc.CEOCAction;\r\nimport jaicore.planning.model.ceoc.CEOCOperation;\r\nimport jaicore.planning.model.core.Plan;\r\nimport jaicore.planning.model.task.ceocipstn.CEOCIPSTNPlanningProblem;\r\nimport jaicore.planning.model.task.ceocipstn.OCIPMethod;\r\nimport jaicore.search.algorithms.standard.bestfirst.BestFirst;\r\nimport jaicore.search.algorithms.standard.bestfirst.events.EvaluatedSearchSolutionCandidateFoundEvent;\r\nimport jaicore.search.core.interfaces.GraphGenerator;\r\nimport jaicore.search.core.interfaces.IGraphSearch;\r\nimport jaicore.search.core.interfaces.IGraphSearchFactory;\r\nimport jaicore.search.model.other.EvaluatedSearchGraphPath;\r\nimport jaicore.search.model.probleminputs.GraphSearchProblemInput;\r\nimport jaicore.search.model.travesaltree.NodeTooltipGenerator;\r\n\r\n/**\r\n * Hierarchically create an object of type T\r\n *\r\n * @author fmohr\r\n *\r\n * @param <T>\r\n */\r\npublic class HASCO<ISearch, N, A, V extends Comparable<V>> implements SoftwareConfigurationAlgorithm<RefinementConfiguredSoftwareConfigurationProblem<V>, HASCORunReport<V>, V>, ILoggingCustomizable {\r\n\r\n\t/* communication (event bus and logging) */\r\n\tprivate final EventBus eventBus = new EventBus(); // An EventBus for notifying listeners about the evaluation of solution nodes.\r\n\tprivate Logger logger = LoggerFactory.getLogger(HASCO.class); // Logger instance for controlled output\r\n\tprivate String loggerName; // Name for the logger to facilitate output level configuration.\r\n\r\n\t/* problem and algorithm setup */\r\n\tprivate final RefinementConfiguredSoftwareConfigurationProblem<V> configurationProblem;\r\n\tprivate final RefinementConfiguredSoftwareConfigurationProblem<V> refactoredConfigurationProblem;\r\n\tprivate final Collection<Component> components;\r\n\tprivate final IHASCOPlanningGraphGeneratorDeriver<N, A> planningGraphGeneratorDeriver;\r\n\tprivate final AlgorithmProblemTransformer<GraphSearchProblemInput<N, A, V>, ISearch> searchProblemTransformer;\r\n\tprivate HASCOConfig config = ConfigCache.getOrCreate(HASCOConfig.class);\r\n\tprivate final IGraphSearchFactory<ISearch, ?, N, A, V, ?, ?> searchFactory;\r\n\r\n\t/* Parameters for the search algorithm configuration */\r\n\t/** Factory for producing planners solving the HTN planning problem. */\r\n\t// private final IHASCOSearchSpaceUtilFactory<N, A, V> searchSpaceUtilFactory;\r\n\r\n\t/** Object evaluator for assessing the quality of plans. */\r\n\r\n\t/* working constants of the algorithms - these are effectively final but are not set at object creation time */\r\n\tprivate CostSensitiveHTNPlanningProblem<CEOCOperation, OCIPMethod, CEOCAction, CEOCIPSTNPlanningProblem<CEOCOperation, OCIPMethod, CEOCAction>, V> planningProblem;\r\n\tprivate GraphSearchProblemInput<N, A, V> searchProblem;\r\n\tprivate IGraphSearch<ISearch, ?, N, A, V, ?, ?> search;\r\n\tprivate final List<HASCOSolutionCandidate<V>> listOfAllRecognizedSolutions = new ArrayList<>();\r\n\r\n\t/* runtime variables of algorithm */\r\n\tprivate AlgorithmState state = AlgorithmState.created;\r\n\tprivate boolean searchCreatedAndInitialized = false;\r\n\tprivate final TimeRecordingEvaluationWrapper<V> timeGrabbingEvaluationWrapper;\r\n\tprivate HASCOSolutionCandidate<V> bestRecognizedSolution;\r\n\r\n\tpublic HASCO(RefinementConfiguredSoftwareConfigurationProblem<V> configurationProblem, IHASCOPlanningGraphGeneratorDeriver<N, A> planningGraphGeneratorDeriver,\r\n\t\t\tIGraphSearchFactory<ISearch, ?, N, A, V, ?, ?> searchFactory, AlgorithmProblemTransformer<GraphSearchProblemInput<N, A, V>, ISearch> searchProblemTransformer) {\r\n\t\tsuper();\r\n\t\tif (configurationProblem == null)\r\n\t\t\tthrow new IllegalArgumentException(\"Cannot work with configuration problem NULL\");\r\n\t\tthis.configurationProblem = configurationProblem;\r\n\t\tthis.planningGraphGeneratorDeriver = planningGraphGeneratorDeriver;\r\n\t\tthis.searchFactory = searchFactory;\r\n\t\tthis.searchProblemTransformer = searchProblemTransformer;\r\n\t\tthis.components = configurationProblem.getComponents();\r\n\t\tthis.timeGrabbingEvaluationWrapper = new TimeRecordingEvaluationWrapper<>(configurationProblem.getCompositionEvaluator());\r\n\t\tthis.refactoredConfigurationProblem = new RefinementConfiguredSoftwareConfigurationProblem<>(\r\n\t\t\t\tnew SoftwareConfigurationProblem<V>(components, configurationProblem.getRequiredInterface(), timeGrabbingEvaluationWrapper), configurationProblem.getParamRefinementConfig());\r\n\t}\r\n\r\n\t@Override\r\n\tpublic Iterator<AlgorithmEvent> iterator() {\r\n\t\treturn this;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean hasNext() {\r\n\t\treturn state != AlgorithmState.inactive;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic AlgorithmEvent next() {\r\n\t\ttry {\r\n\t\t\treturn nextWithException();\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new RuntimeException(e);\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic AlgorithmEvent nextWithException() throws Exception {\r\n\t\tswitch (state) {\r\n\t\tcase created: {\r\n\t\t\tthis.logger.info(\"Starting HASCO run.\");\r\n\r\n\t\t\t/* check whether there is a refinement config for each numeric parameter */\r\n\t\t\tMap<Component, Map<Parameter, ParameterRefinementConfiguration>> paramRefinementConfig = refactoredConfigurationProblem.getParamRefinementConfig();\r\n\t\t\tfor (Component c : this.components) {\r\n\t\t\t\tfor (Parameter p : c.getParameters()) {\r\n\t\t\t\t\tif (p.isNumeric() && (!paramRefinementConfig.containsKey(c) || !paramRefinementConfig.get(c).containsKey(p))) {\r\n\t\t\t\t\t\tthrow new IllegalArgumentException(\"No refinement config was delivered for numeric parameter \" + p.getName() + \" of component \" + c.getName());\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t/* derive search problem */\r\n\t\t\tlogger.debug(\"Deriving search problem\");\r\n\t\t\tplanningProblem = new HASCOReduction<V>().transform(refactoredConfigurationProblem);\r\n\t\t\tif (logger.isDebugEnabled()) {\r\n\t\t\t\tString operations = planningProblem.getCorePlanningProblem().getDomain().getOperations().stream().map(o -> \"\\n\\t\\t\" + o.getName() + \"(\" + o.getParams() + \")\\n\\t\\t\\tPre: \"\r\n\t\t\t\t\t\t+ o.getPrecondition() + \"\\n\\t\\t\\tAdd List: \" + o.getAddLists() + \"\\n\\t\\t\\tDelete List: \" + o.getDeleteLists()).collect(Collectors.joining());\r\n\t\t\t\tString methods = planningProblem\r\n\t\t\t\t\t\t.getCorePlanningProblem().getDomain().getMethods().stream().map(m -> \"\\n\\t\\t\" + m.getName() + \"(\" + m.getParameters() + \") for task \" + m.getTask() + \"\\n\\t\\t\\tPre: \"\r\n\t\t\t\t\t\t\t\t+ m.getPrecondition() + \"\\n\\t\\t\\tPre Eval: \" + m.getEvaluablePrecondition() + \"\\n\\t\\t\\tNetwork: \" + m.getNetwork().getLineBasedStringRepresentation())\r\n\t\t\t\t\t\t.collect(Collectors.joining());\r\n\t\t\t\tlogger.debug(\"Derived the following HTN planning problem:\\n\\tOperations:{}\\n\\tMethods:{}\", operations, methods);\r\n\t\t\t}\r\n\t\t\tsearchProblem = new CostSensitivePlanningToSearchProblemTransformer<CEOCOperation, OCIPMethod, CEOCAction, CEOCIPSTNPlanningProblem<CEOCOperation, OCIPMethod, CEOCAction>, V, N, A>(\r\n\t\t\t\t\tplanningGraphGeneratorDeriver).transform(planningProblem);\r\n\r\n\t\t\t/* communicate that algorithm has been initialized */\r\n\t\t\tlogger.debug(\"Emitting intialization event\");\r\n\t\t\tAlgorithmInitializedEvent initEvent = new AlgorithmInitializedEvent();\r\n\t\t\tthis.eventBus.post(initEvent);\r\n\t\t\tthis.state = AlgorithmState.active;\r\n\t\t\treturn initEvent;\r\n\t\t}\r\n\t\tcase active: {\r\n\r\n\t\t\t/* if the search itself has not been initialized, do this now */\r\n\t\t\tif (!searchCreatedAndInitialized) {\r\n\r\n\t\t\t\t/* create search algorithm, set its logger, and initialize visualization*/\r\n\t\t\t\tlogger.debug(\"Creating the search object\");\r\n\t\t\t\tsearchFactory.setProblemInput(searchProblem, searchProblemTransformer);\r\n\t\t\t\tsearch = searchFactory.getAlgorithm();\r\n\t\t\t\tsearch.setNumCPUs(config.cpus());\r\n\t\t\t\tsearch.setTimeout(config.timeout() * 1000, TimeUnit.MILLISECONDS);\r\n\t\t\t\tif (this.loggerName != null && this.loggerName.length() > 0 && search instanceof ILoggingCustomizable) {\r\n\t\t\t\t\tlogger.info(\"Setting logger name of {} to {}\", search, this.loggerName + \".search\");\r\n\t\t\t\t\t((ILoggingCustomizable) this.search).setLoggerName(this.loggerName + \".search\");\r\n\t\t\t\t}\r\n\t\t\t\tif (config.visualizationEnabled()) {\r\n\t\t\t\t\tlogger.info(\"Launching graph visualization\");\r\n\t\t\t\t\tVisualizationWindow<?, ?> window = new VisualizationWindow<>(search);\r\n\t\t\t\t\tif ((planningGraphGeneratorDeriver instanceof DefaultHASCOPlanningGraphGeneratorDeriver\r\n\t\t\t\t\t\t\t&& ((DefaultHASCOPlanningGraphGeneratorDeriver) planningGraphGeneratorDeriver).getWrappedDeriver() instanceof ForwardDecompositionReducer) && search instanceof BestFirst) {\r\n\t\t\t\t\t\twindow.setTooltipGenerator(new NodeTooltipGenerator<>(new TFDTooltipGenerator<>()));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/* now initialize the search */\r\n\t\t\t\tlogger.debug(\"Initializing the search\");\r\n\t\t\t\tboolean searchInitializationObserved = false;\r\n\t\t\t\twhile (search.hasNext() && !(searchInitializationObserved = (search.next() instanceof AlgorithmInitializedEvent)))\r\n\t\t\t\t\t;\r\n\t\t\t\tif (!searchInitializationObserved)\r\n\t\t\t\t\tthrow new IllegalStateException(\"The search underlying HASCO could not be initialized successully.\");\r\n\t\t\t\tHASCOSearchInitializedEvent event = new HASCOSearchInitializedEvent();\r\n\t\t\t\tthis.eventBus.post(event);\r\n\t\t\t\tsearchCreatedAndInitialized = true;\r\n\t\t\t\treturn event;\r\n\t\t\t}\r\n\r\n\t\t\t/* otherwise iterate over the search */\r\n\t\t\twhile (search.hasNext()) {\r\n\t\t\t\tAlgorithmEvent searchEvent = search.nextWithException();\r\n\r\n\t\t\t\t/* if the underlying search algorithm finished, we also finish */\r\n\t\t\t\tif (searchEvent instanceof AlgorithmFinishedEvent) {\r\n\t\t\t\t\treturn terminate();\r\n\t\t\t\t}\r\n\r\n\t\t\t\t/* otherwise, if a solution has been found, we announce this finding to our listeners and memorize if it is a new best candidate */\r\n\t\t\t\telse if (searchEvent instanceof EvaluatedSearchSolutionCandidateFoundEvent) {\r\n\t\t\t\t\tlogger.info(\"Received new solution from search, communicating this solution to the HASCO listeners.\");\r\n\t\t\t\t\t@SuppressWarnings(\"unchecked\")\r\n\t\t\t\t\tEvaluatedSearchSolutionCandidateFoundEvent<N, A, V> solutionEvent = (EvaluatedSearchSolutionCandidateFoundEvent<N, A, V>) searchEvent;\r\n\t\t\t\t\tEvaluatedSearchGraphPath<N, A, V> searchPath = solutionEvent.getSolutionCandidate();\r\n\t\t\t\t\tPlan<CEOCAction> plan = planningGraphGeneratorDeriver.getPlan(searchPath.getNodes());\r\n\t\t\t\t\tComponentInstance objectInstance = Util.getSolutionCompositionForPlan(components, planningProblem.getCorePlanningProblem().getInit(), plan, true);\r\n\t\t\t\t\tV score = timeGrabbingEvaluationWrapper.hasEvaluationForComponentInstance(objectInstance) ? solutionEvent.getSolutionCandidate().getScore()\r\n\t\t\t\t\t\t\t: timeGrabbingEvaluationWrapper.evaluate(objectInstance);\r\n\t\t\t\t\tEvaluatedSearchGraphBasedPlan<CEOCAction, V, N> evaluatedPlan = new EvaluatedSearchGraphBasedPlan<>(plan, score, searchPath);\r\n\t\t\t\t\tHASCOSolutionCandidate<V> solution = new HASCOSolutionCandidate<>(objectInstance, evaluatedPlan,\r\n\t\t\t\t\t\t\ttimeGrabbingEvaluationWrapper.getEvaluationTimeForComponentInstance(objectInstance));\r\n\t\t\t\t\tif (bestRecognizedSolution == null || score.compareTo(bestRecognizedSolution.getScore()) < 0)\r\n\t\t\t\t\t\tbestRecognizedSolution = solution;\r\n\t\t\t\t\tlistOfAllRecognizedSolutions.add(solution);\r\n\t\t\t\t\tHASCOSolutionEvent<V> hascoSolutionEvent = new HASCOSolutionEvent<>(solution);\r\n\t\t\t\t\tthis.eventBus.post(hascoSolutionEvent);\r\n\t\t\t\t\treturn hascoSolutionEvent;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn terminate();\r\n\t\t}\r\n\t\tdefault:\r\n\t\t\tthrow new IllegalStateException(\"HASCO cannot do anything in state \" + state);\r\n\t\t}\r\n\r\n\t}\r\n\r\n\tprivate AlgorithmFinishedEvent terminate() {\r\n\t\tthis.state = AlgorithmState.inactive;\r\n\t\tAlgorithmFinishedEvent finishedEvent = new AlgorithmFinishedEvent();\r\n\t\tthis.eventBus.post(finishedEvent);\r\n\t\treturn finishedEvent;\r\n\t}\r\n\r\n\tprotected void afterSearch() {\r\n\t}\r\n\r\n\t/**\r\n\t * @return The config object defining the properties.\r\n\t */\r\n\tpublic HASCOConfig getConfig() {\r\n\t\treturn config;\r\n\t}\r\n\r\n\tpublic void setConfig(HASCOConfig config) {\r\n\t\tthis.config = config;\r\n\t}\r\n\r\n\t/**\r\n\t * Set the number of CPUs to be used by HASCO.\r\n\t *\r\n\t * @param numberOfCPUs\r\n\t * The number of cpus to be used.\r\n\t */\r\n\t@Override\r\n\tpublic void setNumCPUs(final int numberOfCPUs) {\r\n\t\tthis.getConfig().setProperty(HASCOConfig.K_CPUS, numberOfCPUs + \"\");\r\n\t}\r\n\r\n\tpublic void registerListenerForSolutionEvaluations(final Object listener) {\r\n\t\tthis.eventBus.register(listener);\r\n\t}\r\n\r\n\tpublic GraphGenerator<N, A> getGraphGenerator() {\r\n\t\treturn searchProblem.getGraphGenerator();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String getLoggerName() {\r\n\t\treturn this.loggerName;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void setLoggerName(final String name) {\r\n\t\tthis.logger.info(\"Switching logger from {} to {}\", this.logger.getName(), name);\r\n\t\tthis.loggerName = name;\r\n\t\tthis.logger = LoggerFactory.getLogger(name);\r\n\t\tthis.logger.info(\"Activated logger {} with name {}\", name, this.logger.getName());\r\n\t}\r\n\r\n\t/**\r\n\t * @return The timeout for gathering solutions.\r\n\t */\r\n\tpublic int getTimeout() {\r\n\t\treturn this.getConfig().timeout();\r\n\t}\r\n\r\n\t/**\r\n\t * @param timeout\r\n\t * Timeout for gathering solutions.\r\n\t */\r\n\t@Override\r\n\tpublic void setTimeout(final int timeout, TimeUnit timeUnit) {\r\n\t\tif (timeUnit != TimeUnit.SECONDS && timeUnit != TimeUnit.MILLISECONDS)\r\n\t\t\tthrow new IllegalArgumentException(\"Currently only seconds are supported\");\r\n\t\tint newTimeout = timeout;\r\n\t\tif (timeUnit == TimeUnit.MILLISECONDS)\r\n\t\t\tnewTimeout /= 1000;\r\n\t\tthis.getConfig().setProperty(HASCOConfig.K_TIMEOUT, newTimeout + \"\");\r\n\t}\r\n\r\n\t/**\r\n\t * @return Returns the number of CPUs that is to be used by HASCO.\r\n\t */\r\n\tpublic int getNumCPUs() {\r\n\t\treturn this.getConfig().cpus();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic HASCORunReport<V> call() throws Exception {\r\n\t\twhile (hasNext())\r\n\t\t\tnextWithException();\r\n\t\treturn new HASCORunReport<>(listOfAllRecognizedSolutions);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic RefinementConfiguredSoftwareConfigurationProblem<V> getInput() {\r\n\t\treturn configurationProblem;\r\n\t}\r\n\r\n\tpublic RefinementConfiguredSoftwareConfigurationProblem<V> getRefactoredProblem() {\r\n\t\treturn refactoredConfigurationProblem;\r\n\t}\r\n\r\n\tpublic CostSensitiveHTNPlanningProblem<CEOCOperation, OCIPMethod, CEOCAction, CEOCIPSTNPlanningProblem<CEOCOperation, OCIPMethod, CEOCAction>, V> getPlanningProblem() {\r\n\t\treturn planningProblem;\r\n\t}\r\n\r\n\tpublic void setVisualization(boolean visualization) {\r\n\t\tthis.config.setProperty(HASCOConfig.K_VISUALIZE, String.valueOf(visualization));\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void cancel() {\r\n\t\tif (search != null)\r\n\t\t\tsearch.cancel();\r\n\t\tthis.terminate();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void registerListener(Object listener) {\r\n\t\teventBus.register(listener);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic TimeUnit getTimeoutUnit() {\r\n\t\treturn TimeUnit.SECONDS;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic IOptimizerResult<ComponentInstance, V> getOptimizationResult() {\r\n\t\treturn new IOptimizerResult<>(bestRecognizedSolution.getComponentInstance(), bestRecognizedSolution.getScore());\r\n\t}\r\n\r\n\tpublic IHASCOPlanningGraphGeneratorDeriver<N, A> getPlanningGraphGeneratorDeriver() {\r\n\t\treturn planningGraphGeneratorDeriver;\r\n\t}\r\n\r\n\tpublic AlgorithmProblemTransformer<GraphSearchProblemInput<N, A, V>, ISearch> getSearchProblemTransformer() {\r\n\t\treturn searchProblemTransformer;\r\n\t}\r\n\r\n\tpublic AlgorithmInitializedEvent init() {\r\n\t\tAlgorithmEvent e = null;\r\n\t\twhile (hasNext()) {\r\n\t\t\te = next();\r\n\t\t\tif (e instanceof AlgorithmInitializedEvent)\r\n\t\t\t\treturn (AlgorithmInitializedEvent) e;\r\n\t\t}\r\n\t\tthrow new IllegalStateException(\"Could not complete initialization\");\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7390872836112976, "alphanum_fraction": 0.7390872836112976, "avg_line_length": 30.516128540039062, "blob_id": "7f3628b896714020e0ab9d4f7cb4b178df9a5439", "content_id": "3a6d2a2ec92c84df009c5579e61ee204e1173e3d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1008, "license_type": "no_license", "max_line_length": 160, "num_lines": 31, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/mcts/MCTSFactory.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.mcts;\r\n\r\nimport jaicore.search.core.interfaces.StandardORGraphSearchFactory;\r\nimport jaicore.search.model.probleminputs.GraphSearchProblemInput;\r\nimport jaicore.search.model.travesaltree.Node;\r\n\r\npublic class MCTSFactory<N, A, V extends Comparable<V>> extends StandardORGraphSearchFactory<GraphSearchProblemInput<N, A, V>, Object, N, A, V, Node<N, V>, A> {\r\n\tprivate IPathUpdatablePolicy<N, A, V> treePolicy;\r\n\tprivate IPolicy<N, A, V> defaultPolicy;\r\n\r\n\tpublic IPathUpdatablePolicy<N, A, V> getTreePolicy() {\r\n\t\treturn treePolicy;\r\n\t}\r\n\r\n\tpublic void setTreePolicy(IPathUpdatablePolicy<N, A, V> treePolicy) {\r\n\t\tthis.treePolicy = treePolicy;\r\n\t}\r\n\r\n\tpublic IPolicy<N, A, V> getDefaultPolicy() {\r\n\t\treturn defaultPolicy;\r\n\t}\r\n\r\n\tpublic void setDefaultPolicy(IPolicy<N, A, V> defaultPolicy) {\r\n\t\tthis.defaultPolicy = defaultPolicy;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic MCTS<N, A, V> getAlgorithm() {\r\n\t\treturn new MCTS<>(getProblemInput(), treePolicy, defaultPolicy);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7806743383407593, "alphanum_fraction": 0.7841086387634277, "avg_line_length": 46.16541290283203, "blob_id": "0fc3fe64f188ef9406f85a79079293e0fce32f39", "content_id": "62c68b50050eb2ee2bcb33481e835e549430bfae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 6406, "license_type": "no_license", "max_line_length": 187, "num_lines": 133, "path": "/softwareconfiguration/hasco/test/hasco/test/HASCOTester.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package hasco.test;\r\n\r\nimport static org.junit.Assert.assertEquals;\r\nimport static org.junit.Assert.assertTrue;\r\n\r\nimport java.io.File;\r\nimport java.io.IOException;\r\nimport java.util.ArrayList;\r\nimport java.util.Collection;\r\nimport java.util.HashSet;\r\nimport java.util.List;\r\nimport java.util.Set;\r\nimport java.util.concurrent.TimeUnit;\r\n\r\nimport org.junit.Test;\r\n\r\nimport hasco.core.HASCO;\r\nimport hasco.core.HASCOFactory;\r\nimport hasco.core.HASCORunReport;\r\nimport hasco.core.HASCOSolutionCandidate;\r\nimport hasco.core.RefinementConfiguredSoftwareConfigurationProblem;\r\nimport hasco.events.HASCOSolutionEvent;\r\nimport hasco.model.ComponentInstance;\r\nimport hasco.serialization.CompositionSerializer;\r\nimport jaicore.basic.algorithm.AlgorithmEvent;\r\nimport jaicore.basic.algorithm.AlgorithmProblemTransformer;\r\nimport jaicore.basic.algorithm.GeneralAlgorithmTester;\r\nimport jaicore.basic.sets.SetUtil.Pair;\r\nimport jaicore.search.core.interfaces.GraphGenerator;\r\nimport jaicore.search.model.probleminputs.GraphSearchInput;\r\nimport jaicore.search.util.CycleDetectedResult;\r\nimport jaicore.search.util.DeadEndDetectedResult;\r\nimport jaicore.search.util.GraphSanityChecker;\r\nimport jaicore.search.util.SanityCheckResult;\r\n\r\npublic abstract class HASCOTester<ISearch, N, A>\r\n\t\textends GeneralAlgorithmTester<RefinementConfiguredSoftwareConfigurationProblem<Double>, RefinementConfiguredSoftwareConfigurationProblem<Double>, HASCORunReport<Double>> {\r\n\r\n\tprivate HASCO<ISearch, N, A, Double> getHASCOForProblem(RefinementConfiguredSoftwareConfigurationProblem<Double> problem) throws Exception {\r\n\t\tHASCOFactory<ISearch, N, A, Double> factory = getFactory();\r\n\t\tfactory.setProblemInput(problem);\r\n\t\tHASCO<ISearch, N, A, Double> hasco = factory.getAlgorithm();\r\n\t\thasco.setTimeout(86400, TimeUnit.SECONDS);\r\n\t\treturn hasco;\r\n\t}\r\n\r\n\tprivate HASCO<ISearch, N, A, Double> getHASCOForSimpleProblem() throws Exception {\r\n\t\treturn getHASCOForProblem(getSimpleProblemInputForGeneralTestPurposes());\r\n\t}\r\n\r\n\tprivate HASCO<ISearch, N, A, Double> getHASCOForDifficultProblem() throws Exception {\r\n\t\treturn getHASCOForProblem(getDifficultProblemInputForGeneralTestPurposes());\r\n\t}\r\n\r\n\tprivate HASCO<ISearch, N, A, Double> getHASCOForProblemWithDependencies() throws Exception {\r\n\t\treturn getHASCOForProblem(getDependencyProblemInput());\r\n\t}\r\n\r\n\tprivate Collection<Pair<HASCO<ISearch, N, A, Double>, Integer>> getAllHASCOObjectsWithExpectedNumberOfSolutionsForTheKnownProblems() throws Exception {\r\n\t\tCollection<Pair<HASCO<ISearch, N, A, Double>, Integer>> hascoObjects = new ArrayList<>();\r\n\t\thascoObjects.add(new Pair<>(getHASCOForSimpleProblem(), 6));\r\n\t\thascoObjects.add(new Pair<>(getHASCOForDifficultProblem(), -1));\r\n\t\thascoObjects.add(new Pair<>(getHASCOForProblemWithDependencies(), 12));\r\n\t\treturn hascoObjects;\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void sanityCheckOfSearchGraph() throws Exception {\r\n\t\tfor (Pair<HASCO<ISearch, N, A, Double>, Integer> pairOfHASCOAndNumOfSolutions : getAllHASCOObjectsWithExpectedNumberOfSolutionsForTheKnownProblems()) {\r\n\t\t\tHASCO<ISearch, N, A, Double> hasco = pairOfHASCOAndNumOfSolutions.getX();\r\n\t\t\thasco.init();\r\n\t\t\tGraphGenerator<N, A> gen = hasco.getGraphGenerator();\r\n\r\n\t\t\t/* check on dead end */\r\n\t\t\tGraphSanityChecker<N, A> deadEndDetector = new GraphSanityChecker<>(new GraphSearchInput<>(gen), 100000);\r\n\t\t\t// new VisualizationWindow<>(deadEndDetector).setTooltipGenerator(n -> TFD);\r\n\t\t\tSanityCheckResult sanity = deadEndDetector.call();\r\n\t\t\tassertTrue(\"HASCO graph has a dead end: \" + sanity, !(sanity instanceof DeadEndDetectedResult));\r\n\t\t\tassertTrue(\"HASCO graph has a cycle: \" + sanity, !(sanity instanceof CycleDetectedResult));\r\n\t\t}\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testThatAnEventForEachPossibleSolutionIsEmittedInSimpleCall() throws Exception {\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testThatAnEventForEachPossibleSolutionIsEmittedInParallelizedCall() throws Exception {\r\n\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testThatIteratorReturnsEachPossibleSolution() throws Exception {\r\n\t\tfor (Pair<HASCO<ISearch, N, A, Double>, Integer> pairOfHASCOAndExpectedNumberOfSolutions : getAllHASCOObjectsWithExpectedNumberOfSolutionsForTheKnownProblems()) {\r\n\t\t\tHASCO<ISearch, N, A, Double> hasco = pairOfHASCOAndExpectedNumberOfSolutions.getX();\r\n\t\t\tint numberOfExpectedSolutions = pairOfHASCOAndExpectedNumberOfSolutions.getY();\r\n\t\t\tif (numberOfExpectedSolutions < 0)\r\n\t\t\t\tcontinue;\r\n\t\t\tList<ComponentInstance> solutions = new ArrayList<>();\r\n\t\t\tfor (AlgorithmEvent e : hasco) {\r\n\t\t\t\tif (e instanceof HASCOSolutionEvent) {\r\n\t\t\t\t\tsolutions.add(((HASCOSolutionCandidate<Double>) ((HASCOSolutionEvent) e).getSolutionCandidate()).getComponentInstance());\r\n\t\t\t\t\tSystem.out.println(new CompositionSerializer().serializeComponentInstance(((HASCOSolutionCandidate<Double>) ((HASCOSolutionEvent) e).getSolutionCandidate()).getComponentInstance()));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tSet<Object> uniqueSolutions = new HashSet<>(solutions);\r\n\t\t\tassertEquals(\"Only found \" + uniqueSolutions.size() + \"/\" + numberOfExpectedSolutions + \" solutions\", numberOfExpectedSolutions, uniqueSolutions.size());\r\n\t\t\tassertEquals(\"All \" + numberOfExpectedSolutions + \" solutions were found, but \" + solutions.size() + \" solutions were returned in total, i.e. there are solutions returned twice\",\r\n\t\t\t\t\tnumberOfExpectedSolutions, solutions.size());\r\n\t\t}\r\n\t}\r\n\r\n\tpublic abstract HASCOFactory<ISearch, N, A, Double> getFactory();\r\n\r\n\t@Override\r\n\tpublic AlgorithmProblemTransformer<RefinementConfiguredSoftwareConfigurationProblem<Double>, RefinementConfiguredSoftwareConfigurationProblem<Double>> getProblemReducer() {\r\n\t\treturn p -> p;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic RefinementConfiguredSoftwareConfigurationProblem<Double> getSimpleProblemInputForGeneralTestPurposes() throws Exception {\r\n\t\treturn new RefinementConfiguredSoftwareConfigurationProblem<>(new File(\"testrsc/simpleproblem.json\"), \"IFace\", n -> 0.0);\r\n\t}\r\n\r\n\tpublic RefinementConfiguredSoftwareConfigurationProblem<Double> getDependencyProblemInput() throws Exception {\r\n\t\treturn new RefinementConfiguredSoftwareConfigurationProblem<>(new File(\"testrsc/problemwithdependencies.json\"), \"IFace\", n -> 0.0);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic RefinementConfiguredSoftwareConfigurationProblem<Double> getDifficultProblemInputForGeneralTestPurposes() throws IOException {\r\n\t\treturn new RefinementConfiguredSoftwareConfigurationProblem<>(new File(\"testrsc/difficultproblem.json\"), \"IFace\", n -> 0.0);\r\n\t};\r\n}\r\n" }, { "alpha_fraction": 0.7547169923782349, "alphanum_fraction": 0.7547169923782349, "avg_line_length": 27.617647171020508, "blob_id": "9093506271a6850964d298f727e61472e94fe7c4", "content_id": "16b42fc5117d2fd8a6776155b934a01ddd32bb1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1007, "license_type": "no_license", "max_line_length": 99, "num_lines": 34, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/bestfirst/events/SuccessorComputationCompletedEvent.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.bestfirst.events;\r\n\r\nimport java.util.List;\r\n\r\nimport jaicore.search.model.travesaltree.Node;\r\nimport jaicore.search.model.travesaltree.NodeExpansionDescription;\r\n\r\npublic class SuccessorComputationCompletedEvent<T, A> extends BestFirstEvent {\r\n\tprivate Node<T, ?> node;\r\n\tprivate List<NodeExpansionDescription<T, A>> successorDescriptions;\r\n\r\n\tpublic SuccessorComputationCompletedEvent(Node<T, ?> node,\r\n\t\t\tList<NodeExpansionDescription<T, A>> successorDescriptions) {\r\n\t\tsuper();\r\n\t\tthis.node = node;\r\n\t\tthis.successorDescriptions = successorDescriptions;\r\n\t}\r\n\r\n\tpublic Node<T, ?> getNode() {\r\n\t\treturn node;\r\n\t}\r\n\r\n\tpublic void setNode(Node<T, ?> node) {\r\n\t\tthis.node = node;\r\n\t}\r\n\r\n\tpublic List<NodeExpansionDescription<T, A>> getSuccessorDescriptions() {\r\n\t\treturn successorDescriptions;\r\n\t}\r\n\r\n\tpublic void setSuccessorDescriptions(List<NodeExpansionDescription<T, A>> successorDescriptions) {\r\n\t\tthis.successorDescriptions = successorDescriptions;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7316821217536926, "alphanum_fraction": 0.7316821217536926, "avg_line_length": 30.299999237060547, "blob_id": "cbeda780f5434be62449e4db46db06626984a747", "content_id": "d0c23b65e80d4a2978d422c25fed93a7c4e238d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 969, "license_type": "no_license", "max_line_length": 110, "num_lines": 30, "path": "/JAICore/jaicore-search/src/jaicore/search/model/probleminputs/GraphSearchProblemInput.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.model.probleminputs;\r\n\r\nimport jaicore.search.core.interfaces.GraphGenerator;\r\nimport jaicore.search.core.interfaces.ISolutionEvaluator;\r\n\r\n/**\r\n * In AILibs, a graph search problem always aims at identifying one or more paths from\r\n * a set of root nodes to a goal node. Usually, such paths are associated with a value\r\n * that qualifies them.\r\n * \r\n * This is the most general problem input one can have if there is no other knowledge.\r\n * \r\n * @author fmohr\r\n *\r\n * @param <N>\r\n * @param <A>\r\n * @param <V>\r\n */\r\npublic class GraphSearchProblemInput<N, A, V extends Comparable<V>> extends GraphSearchInput<N, A> {\r\n\tprivate final ISolutionEvaluator<N, V> pathEvaluator;\r\n\r\n\tpublic GraphSearchProblemInput(GraphGenerator<N, A> graphGenerator, ISolutionEvaluator<N, V> pathEvaluator) {\r\n\t\tsuper(graphGenerator);\r\n\t\tthis.pathEvaluator = pathEvaluator;\r\n\t}\r\n\r\n\tpublic ISolutionEvaluator<N, V> getPathEvaluator() {\r\n\t\treturn pathEvaluator;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6885400414466858, "alphanum_fraction": 0.6907378435134888, "avg_line_length": 25.991525650024414, "blob_id": "b7b24b5d34b4b61bc256e8007757f9000c9d1b66", "content_id": "db6aaad2b9f2b51e9089cded33985cc4be0cc40d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3185, "license_type": "no_license", "max_line_length": 150, "num_lines": 118, "path": "/JAICore/jaicore-ml/src/jaicore/ml/experiments/MLExperiment.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.ml.experiments;\n\npublic class MLExperiment {\n\tprivate final String dataset;\n\tprivate final String algorithm;\n\tprivate final String algorithmMode;\n\tprivate final int seed;\n\tprivate final int timeoutInSeconds;\n\tprivate final int cpus;\n\tprivate final int memoryInMB;\n\tprivate final String performanceMeasure;\n\n\tpublic MLExperiment(String dataset, String algorithm, String algorithmMode, int seed, int timeoutInSeconds, int cpus, int memoryInMB,\n\t\t\tString performanceMeasure) {\n\t\tsuper();\n\t\tthis.dataset = dataset;\n\t\tthis.algorithm = algorithm;\n\t\tthis.algorithmMode = algorithmMode;\n\t\tthis.seed = seed;\n\t\tthis.timeoutInSeconds = timeoutInSeconds;\n\t\tthis.cpus = cpus;\n\t\tthis.memoryInMB = memoryInMB;\n\t\tthis.performanceMeasure = performanceMeasure;\n\t}\n\n\tpublic String getDataset() {\n\t\treturn dataset;\n\t}\n\n\tpublic String getAlgorithm() {\n\t\treturn algorithm;\n\t}\n\n\tpublic String getAlgorithmMode() {\n\t\treturn algorithmMode;\n\t}\n\n\tpublic int getSeed() {\n\t\treturn seed;\n\t}\n\n\tpublic int getTimeoutInSeconds() {\n\t\treturn timeoutInSeconds;\n\t}\n\n\tpublic int getCpus() {\n\t\treturn cpus;\n\t}\n\n\tpublic int getMemoryInMB() {\n\t\treturn memoryInMB;\n\t}\n\n\tpublic String getPerformanceMeasure() {\n\t\treturn performanceMeasure;\n\t}\n\t\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((algorithm == null) ? 0 : algorithm.hashCode());\n\t\tresult = prime * result + ((algorithmMode == null) ? 0 : algorithmMode.hashCode());\n\t\tresult = prime * result + cpus;\n\t\tresult = prime * result + ((dataset == null) ? 0 : dataset.hashCode());\n\t\tresult = prime * result + memoryInMB;\n\t\tresult = prime * result + ((performanceMeasure == null) ? 0 : performanceMeasure.hashCode());\n\t\tresult = prime * result + seed;\n\t\tresult = prime * result + timeoutInSeconds;\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tMLExperiment other = (MLExperiment) obj;\n\t\tif (algorithm == null) {\n\t\t\tif (other.algorithm != null)\n\t\t\t\treturn false;\n\t\t} else if (!algorithm.equals(other.algorithm))\n\t\t\treturn false;\n\t\tif (algorithmMode == null) {\n\t\t\tif (other.algorithmMode != null)\n\t\t\t\treturn false;\n\t\t} else if (!algorithmMode.equals(other.algorithmMode))\n\t\t\treturn false;\n\t\tif (cpus != other.cpus)\n\t\t\treturn false;\n\t\tif (dataset == null) {\n\t\t\tif (other.dataset != null)\n\t\t\t\treturn false;\n\t\t} else if (!dataset.equals(other.dataset))\n\t\t\treturn false;\n\t\tif (memoryInMB != other.memoryInMB)\n\t\t\treturn false;\n\t\tif (performanceMeasure == null) {\n\t\t\tif (other.performanceMeasure != null)\n\t\t\t\treturn false;\n\t\t} else if (!performanceMeasure.equals(other.performanceMeasure))\n\t\t\treturn false;\n\t\tif (seed != other.seed)\n\t\t\treturn false;\n\t\tif (timeoutInSeconds != other.timeoutInSeconds)\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Experiment [dataset=\" + dataset + \", algorithm=\" + algorithm + \", algorithmMode=\" + algorithmMode + \", seed=\" + seed\n\t\t\t\t+ \", timeoutInSeconds=\" + timeoutInSeconds + \", cpus=\" + cpus + \", memoryInMB=\" + memoryInMB + \", performanceMeasure=\" + performanceMeasure + \"]\";\n\t}\n}\n" }, { "alpha_fraction": 0.805031418800354, "alphanum_fraction": 0.805031418800354, "avg_line_length": 25.5, "blob_id": "f63048d15d4783072ecf85ca987280450e6736be", "content_id": "c5d032d1fe7a03fd094f99303352d66a221d0a0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 159, "license_type": "no_license", "max_line_length": 51, "num_lines": 6, "path": "/JAICore/jaicore-planning/src/jaicore/planning/model/core/SolutionPathConverter.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.model.core;\nimport java.util.List;\n\npublic interface SolutionPathConverter<T> {\n\tpublic T convertPathToSolution(List<Action> path);\n}\n" }, { "alpha_fraction": 0.8176291584968567, "alphanum_fraction": 0.8176291584968567, "avg_line_length": 26.41666603088379, "blob_id": "45a72541092199e9bc37c30a6828ec12fc1d775c", "content_id": "a3b64160f60eededa6361a29334b3d4b7d7e0765", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 329, "license_type": "no_license", "max_line_length": 90, "num_lines": 12, "path": "/JAICore/jaicore-planning/src/jaicore/planning/model/ceoc/CEOCPlanningProblem.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.model.ceoc;\n\nimport jaicore.logic.fol.structure.Monom;\nimport jaicore.planning.model.core.PlanningProblem;\n\npublic class CEOCPlanningProblem extends PlanningProblem {\n\n\tpublic CEOCPlanningProblem(CEOCPlanningDomain domain, Monom initState, Monom goalState) {\n\t\tsuper(domain, initState, goalState);\n\t}\n\n}\n" }, { "alpha_fraction": 0.7392309904098511, "alphanum_fraction": 0.7435675263404846, "avg_line_length": 37.43333435058594, "blob_id": "83c0a2635f08d63f33fedecdddf0def822fa0649", "content_id": "f30678f2d86c2b9e1c97dc6c9bd6900a01f74071", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3459, "license_type": "no_license", "max_line_length": 280, "num_lines": 90, "path": "/JAICore/jaicore-ml/src/jaicore/ml/experiments/MySQLExperimentDatabaseHandle.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.ml.experiments;\n\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport jaicore.basic.SQLAdapter;\nimport weka.classifiers.Classifier;\n\n@SuppressWarnings(\"serial\")\npublic class MySQLExperimentDatabaseHandle extends SQLAdapter implements IMultiClassClassificationExperimentDatabase {\n\t\n\tprivate Map<Integer,Classifier> run2classifier = new HashMap<>();\n\tprivate Map<Classifier,Integer> classifier2run = new HashMap<>();\n\n\tpublic MySQLExperimentDatabaseHandle(String host, String user, String password, String database) {\n\t\tsuper(host, user, password, database);\n\t}\n\t\n\tprotected void beforeCreateRun(MLExperiment e) {}\n\tprotected void afterCreateRun(MLExperiment e, int jobId) {}\n\t\n\t@Override\n\tpublic int createRunIfDoesNotExist(MLExperiment e) {\n\t\ttry {\n\t\t\tString[] values = { InetAddress.getLocalHost().toString(), e.getDataset(), e.getAlgorithm(), e.getAlgorithmMode(), String.valueOf(e.getSeed()), String.valueOf(e.getTimeoutInSeconds()), String.valueOf(e.getCpus()), String.valueOf(e.getMemoryInMB()), e.getPerformanceMeasure() };\n\t\t\tbeforeCreateRun(e);\n\t\t\tint id = insert(\"INSERT INTO `runs` (machine, dataset, algorithm, algorithmmode, seed, timeout, CPUs, memoryInMB, performancemeasure) VALUES (?,?,?,?,?,?,?,?,?)\", values);\n\t\t\tafterCreateRun(e, id);\n\t\t\treturn id;\n\t\t} catch (SQLException | UnknownHostException exc) {\n\t\t\tif (!exc.getMessage().startsWith(\"Duplicate entry\"))\n\t\t\t\texc.printStackTrace();\n\t\t\treturn -1;\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void associatedRunWithClassifier(int runId, Classifier c) {\n\t\trun2classifier.put(runId, c);\n\t\tclassifier2run.put(c, runId);\n\t}\n\t\n\tpublic int getRunIdOfClassifier(Classifier c) {\n\t\treturn classifier2run.get(c);\n\t}\n\t\n\tpublic Classifier getClassifierOfRun(int jobId) {\n\t\treturn run2classifier.get(jobId);\n\t}\n\t\n\n\t@Override\n\tpublic Collection<MLExperiment> getExperimentsForWhichARunExists() throws Exception {\n\t\tResultSet rs = getResultsOfQuery(\"SELECT dataset, algorithm, algorithmmode, seed, timeout, cpus, memoryinmb, performancemeasure FROM `runs`\");\n\t\tCollection<MLExperiment> list = new ArrayList<>();\n\t\twhile (rs.next()) {\n\t\t\tlist.add(new MLExperiment(rs.getString(1), rs.getString(2), rs.getString(3), rs.getInt(4), rs.getInt(5), rs.getInt(6), rs.getInt(7), rs.getString(8)));\n\t\t}\n\t\treturn list;\n\t}\n\t\n\t@Override\n\tpublic void updateExperiment(MLExperiment e, Map<String, String> data) throws Exception {\n\t\tMap<String,String> whereClause = new HashMap<>();\n\t\twhereClause.put(\"dataset\", e.getDataset());\n\t\twhereClause.put(\"algorithm\", e.getAlgorithm());\n\t\twhereClause.put(\"algorithmmode\", e.getAlgorithmMode());\n\t\twhereClause.put(\"seed\", String.valueOf(e.getSeed()));\n\t\twhereClause.put(\"timeout\", String.valueOf(e.getTimeoutInSeconds()));\n\t\twhereClause.put(\"cpus\", String.valueOf(e.getCpus()));\n\t\twhereClause.put(\"memoryinmb\", String.valueOf(e.getMemoryInMB()));\n\t\twhereClause.put(\"performancemeasure\", String.valueOf(e.getPerformanceMeasure()));\n\t\tupdate(\"runs\", data, whereClause);\n\t}\n\n\t@Override\n\tpublic void addResultEntry(int runId, double score) throws Exception {\n\t\tMap<String,String> whereClause = new HashMap<>();\n\t\twhereClause.put(\"run_id\", String.valueOf(runId));\n\t\tMap<String,String> data = new HashMap<>();\n\t\tdata.put(\"errorRate\", String.valueOf(score));\n\t\tupdate(\"runs\", data, whereClause);\n\t}\n}\n" }, { "alpha_fraction": 0.7602403163909912, "alphanum_fraction": 0.762424886226654, "avg_line_length": 30.568965911865234, "blob_id": "1d3d512b79e4849fbdd6b08ba1b7148ad20d1ce0", "content_id": "8268fb19aee20538ee19840446830221288faede", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1831, "license_type": "no_license", "max_line_length": 108, "num_lines": 58, "path": "/JAICore/jaicore-ml/src/jaicore/ml/multilabel/evaluators/MultilabelEvaluator.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.ml.multilabel.evaluators;\n\nimport java.io.Serializable;\nimport java.util.List;\nimport java.util.Random;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport jaicore.ml.WekaUtil;\nimport jaicore.ml.evaluation.BasicMLEvaluator;\nimport meka.classifiers.multilabel.MultiLabelClassifier;\nimport weka.classifiers.Classifier;\nimport weka.core.Instances;\n\n@SuppressWarnings(\"serial\")\npublic abstract class MultilabelEvaluator implements BasicMLEvaluator, Serializable {\n\t\n\tprivate final static Logger logger = LoggerFactory.getLogger(MultilabelEvaluator.class);\n\t\n\tprivate final Random rand;\n\tprivate boolean canceled;\n\n\tpublic MultilabelEvaluator(Random r) {\n\t\tsuper();\n\t\tthis.rand = r;\n\t}\n\n\tpublic double getErrorRateForRandomSplit(Classifier c, Instances data, double splitSize) throws Exception {\n\t\tList<Instances> split = WekaUtil.realizeSplit(data, WekaUtil.getArbitrarySplit(data, rand, splitSize));\n\t\tInstances train = split.get(0);\n\t\tInstances test = split.get(1);\n\t\tlogger.info(\"Split data set with {} items into {}/{}\", data.size(), train.size(), test.size());\n\t\treturn getErrorRateForSplit(c, train, test);\n\t}\n\t\n\tpublic double getErrorRateForSplit(Classifier c, Instances train, Instances test) throws Exception {\n\t\tMultiLabelClassifier cCopy = (MultiLabelClassifier)WekaUtil.cloneClassifier(c);\n\t\tcCopy.buildClassifier(train);\n\t\tif (test.isEmpty()) {\n\t\t\tlogger.error(\"Test fold is empty! Size of training set: {}\", train.size());\n\t\t}\n\t\telse\n\t\t\tlogger.info(\"Split size is {}/{}\", train.size(), test.size());\n\t\tdouble error = loss(cCopy, test);\n\t\treturn error;\n\t}\n\t\n\tpublic abstract double loss(MultiLabelClassifier builtClassifier, Instances test) throws Exception;\n\n\tpublic boolean isCanceled() {\n\t\treturn canceled;\n\t}\n\n\tpublic void setCanceled(boolean canceled) {\n\t\tthis.canceled = canceled;\n\t}\n}\n" }, { "alpha_fraction": 0.6742698550224304, "alphanum_fraction": 0.6760801076889038, "avg_line_length": 37.846153259277344, "blob_id": "a1e80fcfa1974705cf58ea9a1b68905a2a9fbc31", "content_id": "1ea0303dbf592ceef8872656cc59845f9ee5fc56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 8286, "license_type": "no_license", "max_line_length": 173, "num_lines": 208, "path": "/JAICore/jaicore-search/src/jaicore/search/algorithms/standard/gbf/GeneralBestFirst.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "//package jaicore.search.algorithms.standard.gbf;\r\n//\r\n//import java.util.ArrayList;\r\n//import java.util.Collection;\r\n//import java.util.HashMap;\r\n//import java.util.LinkedList;\r\n//import java.util.List;\r\n//import java.util.Map;\r\n//import java.util.Queue;\r\n//import java.util.concurrent.atomic.AtomicInteger;\r\n//import java.util.stream.Collectors;\r\n//\r\n//import jaicore.basic.sets.SetUtil;\r\n//import jaicore.graph.Graph;\r\n//import jaicore.search.algorithms.standard.bestfirst.model.AndNode;\r\n//import jaicore.search.algorithms.standard.bestfirst.model.GraphGenerator;\r\n//import jaicore.search.algorithms.standard.bestfirst.model.Node;\r\n//import jaicore.search.algorithms.standard.bestfirst.model.NodeExpansionDescription;\r\n//import jaicore.search.algorithms.standard.bestfirst.model.NodeType;\r\n//import jaicore.search.algorithms.standard.bestfirst.model.OrNode;\r\n//import jaicore.search.algorithms.standard.bestfirst.nodeevaluation.INodeEvaluator;\r\n//import jaicore.search.structure.graphgenerator.SingleRootGenerator;\r\n//\r\n///**\r\n// * A* algorithm implementation using the method design pattern.\r\n// *\r\n// * @author Felix Mohr\r\n// */\r\n//public class GeneralBestFirst<T, A> extends ANDORGraphSearch<T, A, Integer> {\r\n//\r\n//\tprivate Node<T, Integer> root;\r\n//\tprivate final Queue<Node<T, Integer>> open = new LinkedList<>();\r\n//\r\n//\tprivate final GeneralBestFirstEvaluationOrSelector<T> orAggregator;\r\n//\tprivate final GeneralBestFirstEvaluationAggregation<T> andAggregator;\r\n//\tprivate final INodeEvaluator<T, Integer> nodeEvaluator;\r\n//\tprivate final Map<Node<T, Integer>, Integer> bestValues = new HashMap<>();\r\n//\tprivate final Map<Node<T, Integer>, List<Node<T, Integer>>> bestOrSuccessors = new HashMap<>();\r\n//\r\n//\t/* solution stats */\r\n//\r\n//\tpublic GeneralBestFirst(GraphGenerator<T, A> graphGenerator, GeneralBestFirstEvaluationOrSelector<T> orAggregator, GeneralBestFirstEvaluationAggregation<T> andAggregator,\r\n//\t\t\tINodeEvaluator<T, Integer> nodeEvaluator) {\r\n//\t\tsuper((SingleRootGenerator<T>)graphGenerator.getRootGenerator(), graphGenerator.getSuccessorGenerator(), graphGenerator.getGoalTester());\r\n//\t\tthis.orAggregator = orAggregator;\r\n//\t\tthis.andAggregator = andAggregator;\r\n//\t\tthis.nodeEvaluator = nodeEvaluator;\r\n//\t}\r\n//\r\n//\t@Override\r\n//\tprotected Node<T, Integer> initialize() {\r\n//\t\troot = getOrNode(null, rootGenerator.getRoot(), null);\r\n//\t\topen.add(root);\r\n//\t\ttry {\r\n//\t\t\tbestValues.put(root, nodeEvaluator.f(root));\r\n//\t\t} catch (Throwable e) {\r\n//\t\t\te.printStackTrace();\r\n//\t\t}\r\n//\t\treturn root;\r\n//\t}\r\n//\r\n//\t@Override\r\n//\tprotected Graph<Node<T, Integer>> nextSolutionBase() {\r\n//\t\treturn getSolutionBase(0);\r\n//\t}\r\n//\r\n//\tprotected Graph<Node<T, Integer>> getSolutionBase(int index) {\r\n//\t\treturn getSolutionBaseUnderNode(root, new AtomicInteger(0));\r\n//\t}\r\n//\r\n//\tprotected Graph<Node<T, Integer>> getSolutionBaseUnderNode(Node<T, Integer> node, AtomicInteger index) {\r\n//\r\n//\t\t/* if we reached the bottom, return a graph of size 1 */\r\n//\t\tGraph<Node<T, Integer>> base = new Graph<>();\r\n//\t\tbase.addItem(node);\r\n//\t\tif (traversalGraph.getSuccessors(node).isEmpty()) {\r\n//\t\t\treturn base;\r\n//\t\t}\r\n//\r\n//\t\tif (node instanceof OrNode) {\r\n//\t\t\tif (bestOrSuccessors.containsKey(node)) {\r\n//\t\t\t\tList<Node<T, Integer>> successorRanking = bestOrSuccessors.get(node);\r\n//\t\t\t\tfor (int i = 0; i < successorRanking.size(); i++) {\r\n//\t\t\t\t\tGraph<Node<T, Integer>> subgraph = getSolutionBaseUnderNode(successorRanking.get(i), index);\r\n//\t\t\t\t\tif (subgraph.isEmpty()) {\r\n//\t\t\t\t\t\tthrow new IllegalStateException(\"Subgraph \" + subgraph + \" is empty\");\r\n//\t\t\t\t\t}\r\n//\t\t\t\t\tboolean isSolved = solvedNodes.contains(subgraph.getRoot());\r\n//\t\t\t\t\tboolean hasOpenNodes = !SetUtil.intersection(subgraph.getSinks(), open).isEmpty();\r\n//\t\t\t\t\tif (isSolved && index.get() > 0) {\r\n//\t\t\t\t\t\tindex.decrementAndGet();\r\n//\t\t\t\t\t} else if (isSolved || hasOpenNodes) {\r\n//\t\t\t\t\t\tbase.addGraph(subgraph);\r\n//\t\t\t\t\t\tNode<T, Integer> rootOfSubgraph = subgraph.getRoot();\r\n//\t\t\t\t\t\tbase.addEdge(node, rootOfSubgraph);\r\n//\t\t\t\t\t\tbreak;\r\n//\t\t\t\t\t}\r\n//\t\t\t\t}\r\n//\t\t\t} else {\r\n//\t\t\t\tthrow new IllegalStateException(\"I don't know anything about the quality of successors of an internal OR-Node\");\r\n//\t\t\t}\r\n//\t\t} else if (node instanceof AndNode) {\r\n//\t\t\tfor (Node<T, Integer> successor : traversalGraph.getSuccessors(node)) {\r\n//\t\t\t\tGraph<Node<T, Integer>> subgraph = getSolutionBaseUnderNode(successor, index);\r\n//\t\t\t\tNode<T, Integer> rootOfSubgraph = subgraph.getRoot();\r\n//\t\t\t\tbase.addGraph(subgraph);\r\n//\t\t\t\tbase.addEdge(node, rootOfSubgraph);\r\n//\t\t\t}\r\n//\t\t}\r\n//\t\treturn base;\r\n//\t}\r\n//\r\n//\t@Override\r\n//\tprotected Node<T, Integer> nextNode(Graph<Node<T, Integer>> solutionBase) {\r\n//\t\tCollection<Node<T, Integer>> candidates = SetUtil.intersection(solutionBase.getSinks(), open);\r\n//\t\tif (candidates.isEmpty()) {\r\n//\t\t\tassert !open.isEmpty() : \"no open node in solution base \" + solutionBase + \" but there are still nodes on open!\";\r\n//\t\t\treturn null;\r\n//\t\t}\r\n//\t\tNode<T, Integer> n = candidates.iterator().next();\r\n//\t\topen.remove(n);\r\n//\t\treturn n;\r\n//\t}\r\n//\r\n//\t@Override\r\n//\tprotected Collection<Node<T, Integer>> expand(Node<T, Integer> expanded) {\r\n//\t\tCollection<NodeExpansionDescription<T, A>> successorNodes = successorGenerator.generateSuccessors(expanded.getPoint());\r\n//\t\tCollection<Node<T, Integer>> successors = new ArrayList<>();\r\n//\t\tMap<Node<T, Integer>, Integer> newSuccessorsAndTheirScores = new HashMap<>();\r\n//\t\tfor (NodeExpansionDescription<T, A> successorDescription : successorNodes) {\r\n//\r\n//\t\t\t/* no reopening of nodes we already know */\r\n//\t\t\tT successor = successorDescription.getTo();\r\n//\t\t\tboolean isKnown = ext2int.containsKey(successor);\r\n//\t\t\tNode<T, Integer> node = null;\r\n//\t\t\tNodeType type = successorDescription.getTypeOfToNode();\r\n//\t\t\tif (type == NodeType.AND)\r\n//\t\t\t\tnode = getAndNode(expanded, successor, successorDescription.getAction());\r\n//\t\t\tif (type == NodeType.OR)\r\n//\t\t\t\tnode = getOrNode(expanded, successor, successorDescription.getAction());\r\n//\t\t\tif (!isKnown) {\r\n//\t\t\t\tint val;\r\n//\t\t\t\ttry {\r\n//\t\t\t\t\tval = nodeEvaluator.f(node);\r\n//\t\t\t\t\tnewSuccessorsAndTheirScores.put(node, val);\r\n//\t\t\t\t} catch (Throwable e) {\r\n//\t\t\t\t\te.printStackTrace();\r\n//\t\t\t\t}\r\n//\t\t\t} else\r\n//\t\t\t\tsuccessors.add(node);\r\n//\t\t}\r\n//\r\n//\t\t/* add nodes to open */\r\n//\t\tfor (Node<T, Integer> node : newSuccessorsAndTheirScores.keySet().stream().sorted((n1, n2) -> newSuccessorsAndTheirScores.get(n1) - newSuccessorsAndTheirScores.get(n2))\r\n//\t\t\t\t.collect(Collectors.toList())) {\r\n//\t\t\tbestValues.put(node, newSuccessorsAndTheirScores.get(node));\r\n//\t\t\tif (!goalTester.isGoal(node.getPoint())) {\r\n//\t\t\t\topen.add(node);\r\n//\t\t\t}\r\n//\t\t\tsuccessors.add(node);\r\n//\t\t}\r\n//\r\n//\t\t/* selective cost update of node and its parents */\r\n//\t\tbottom2topCostUpdate(expanded);\r\n//\t\treturn successors;\r\n//\t}\r\n//\r\n//\t@Override\r\n//\tprotected int getNumberOfOpenNodesInSolutionBase(Graph<Node<T, Integer>> solutionBase) {\r\n//\t\treturn SetUtil.intersection(solutionBase.getSinks(), open).size();\r\n//\t}\r\n//\r\n//\tprotected void bottom2topCostUpdate(Node<T, Integer> n) {\r\n//\t\tMap<Node<T, Integer>, Integer> successorValues = new HashMap<>();\r\n//\t\tfor (Node<T, Integer> s : traversalGraph.getSuccessors(n)) {\r\n//\t\t\tif (!bestValues.containsKey(s))\r\n//\t\t\t\tthrow new IllegalStateException(\"No best value known for \" + s);\r\n//\t\t\tsuccessorValues.put(s, bestValues.get(s));\r\n//\t\t}\r\n//\r\n//\t\t/* compute aggregation and update best successor of or-nodes */\r\n//\t\tint newValue = Integer.MAX_VALUE;\r\n//\t\tif (!successorValues.isEmpty()) {\r\n//\t\t\tif (n instanceof OrNode) {\r\n//\t\t\t\tList<Node<T, Integer>> successorRanking = orAggregator.getSuccessorRanking(successorValues);\r\n//\t\t\t\tnewValue = bestValues.get(successorRanking.get(0));\r\n//\t\t\t\tbestOrSuccessors.put(n, successorRanking);\r\n//\t\t\t} else {\r\n//\t\t\t\tnewValue = andAggregator.aggregate(successorValues);\r\n//\t\t\t}\r\n//\t\t}\r\n//\r\n//\t\t/* propagate this update to parents */\r\n//\t\tbestValues.put(n, newValue);\r\n//\t\tCollection<Node<T, Integer>> parents = traversalGraph.getPredecessors(n);\r\n//\t\tfor (Node<T, Integer> parent : parents) {\r\n//\t\t\tbottom2topCostUpdate(parent);\r\n//\t\t}\r\n//\t}\r\n//\r\n//\tpublic Integer getBestValue(Node<T, Integer> node) {\r\n//\t\treturn bestValues.get(node);\r\n//\t}\r\n//\r\n//\tpublic Integer getBestValue(T node) {\r\n//\t\treturn getBestValue(ext2int.get(node));\r\n//\t}\r\n//}" }, { "alpha_fraction": 0.7421383857727051, "alphanum_fraction": 0.7421383857727051, "avg_line_length": 18.875, "blob_id": "d0189a76b7e58b81fc86101e72db6564883f34e5", "content_id": "0bab474156f312a03be4c510f9941ec3eccd1497", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 159, "license_type": "no_license", "max_line_length": 91, "num_lines": 8, "path": "/JAICore/jaicore-processes/src/jaicore/processes/OS.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.processes;\n\n/**\n * Enum for operating systems that should be distinguished on the level of process analysis\n */\npublic enum OS {\n\tWIN, LINUX\n}\n" }, { "alpha_fraction": 0.835488498210907, "alphanum_fraction": 0.835488498210907, "avg_line_length": 58.60869598388672, "blob_id": "cb69428fba15f0c32e63aaa478d1568e9a00f09b", "content_id": "0627a9a56c80631cf67d9876ca6f7c82b371f862", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1392, "license_type": "no_license", "max_line_length": 240, "num_lines": 23, "path": "/JAICore/jaicore-search/test/jaicore/search/algorithms/standard/bestfirst/BestFirstEnhancedTTSPTester.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.search.algorithms.standard.bestfirst;\r\n\r\nimport jaicore.basic.algorithm.AlgorithmProblemTransformer;\r\nimport jaicore.search.core.interfaces.IGraphSearchFactory;\r\nimport jaicore.search.model.other.EvaluatedSearchGraphPath;\r\nimport jaicore.search.model.probleminputs.GeneralEvaluatedTraversalTree;\r\nimport jaicore.search.model.travesaltree.Node;\r\nimport jaicore.search.testproblems.enhancedttsp.EnhancedTTSP;\r\nimport jaicore.search.testproblems.enhancedttsp.EnhancedTTSPNode;\r\nimport jaicore.search.testproblems.enhancedttsp.EnhancedTTSPTester;\r\n\r\npublic class BestFirstEnhancedTTSPTester extends EnhancedTTSPTester<GeneralEvaluatedTraversalTree<EnhancedTTSPNode, String, Double>, EvaluatedSearchGraphPath<EnhancedTTSPNode, String, Double>, Node<EnhancedTTSPNode,Double>, String> {\r\n\t\r\n\t@Override\r\n\tpublic IGraphSearchFactory<GeneralEvaluatedTraversalTree<EnhancedTTSPNode, String, Double>, EvaluatedSearchGraphPath<EnhancedTTSPNode, String, Double>, EnhancedTTSPNode, String, Double, Node<EnhancedTTSPNode,Double>, String> getFactory() {\r\n\t\treturn new BestFirstFactory<>();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic AlgorithmProblemTransformer<EnhancedTTSP, GeneralEvaluatedTraversalTree<EnhancedTTSPNode, String, Double>> getProblemReducer() {\r\n\t\treturn a -> new GeneralEvaluatedTraversalTree<>(a.getGraphGenerator(), n -> a.getSolutionEvaluator().evaluateSolution(n.externalPath()));\r\n\t}\r\n}" }, { "alpha_fraction": 0.6565027236938477, "alphanum_fraction": 0.6771841645240784, "avg_line_length": 61.338844299316406, "blob_id": "431db9ab33fecd9520b222368df8c77856d31a4d", "content_id": "b3a23e7cf7302e461ad6bdfd4c96ef32e6c1767c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 7543, "license_type": "no_license", "max_line_length": 327, "num_lines": 121, "path": "/JAICore/jaicore-planning/src/jaicore/planning/model/task/stn/StandardProblemFactory.java", "repo_name": "fmohr/AILibs", "src_encoding": "UTF-8", "text": "package jaicore.planning.model.task.stn;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Map;\n\nimport jaicore.logic.fol.structure.CNFFormula;\nimport jaicore.logic.fol.structure.Literal;\nimport jaicore.logic.fol.structure.LiteralParam;\nimport jaicore.logic.fol.structure.Monom;\nimport jaicore.logic.fol.structure.VariableParam;\nimport jaicore.planning.model.ceoc.CEOCAction;\nimport jaicore.planning.model.ceoc.CEOCOperation;\nimport jaicore.planning.model.conditional.CEOperation;\nimport jaicore.planning.model.core.Action;\nimport jaicore.planning.model.core.Operation;\nimport jaicore.planning.model.strips.StripsPlanningDomain;\nimport jaicore.planning.model.task.ceocstn.CEOCSTNPlanningProblem;\nimport jaicore.planning.model.task.ceocstn.OCMethod;\n\npublic class StandardProblemFactory {\n\n\tpublic static STNPlanningProblem<Operation, Method, Action> getDockworkerProblem() {\n\n\t\t/* retrieve STRIPS operations of the planning problem */\n\t\tStripsPlanningDomain dwrStripsDomain = (StripsPlanningDomain) jaicore.planning.model.strips.StandardProblemFactory.getDockworkerProblem().getDomain();\n\n\t\t/* define non-primitive STN task literals for the domain */\n\t\tLiteral taskMoveTopmostContainer = new Literal(\"move-topmost-container(p1,p2)\");\n\t\tLiteral taskMoveStack = new Literal(\"move-stack(p,q)\");\n//\t\tLiteral taskMoveAllStacks = new Literal(\"move-all-stacks()\");\n\n\t\t/* define STN methods for the domain */\n\t\tList<Method> methods = new ArrayList<>();\n\t\tMonom p1 = new Monom(\"top(c,p1) & on(c,x1) & attached(p1,l1) & belong(k,l1) & attached(p2,l2) & top(x2,p2)\");\n\t\tmethods.add(new Method(\"take-and-put\", Arrays.asList(new VariableParam[] { new VariableParam(\"k\"), new VariableParam(\"c\"), new VariableParam(\"p1\"), new VariableParam(\"p2\"), new VariableParam(\"l1\"), new VariableParam(\"l2\"), new VariableParam(\"x1\"), new VariableParam(\"x2\") }), taskMoveTopmostContainer, p1,\n\t\t\t\tnew TaskNetwork(\"take(k,l1,c,x1,p1) -> put(k,l2,c,x2,p2)\"), false));\n\t\tmethods.add(new Method(\"recursive-move\", Arrays.asList(new VariableParam[] { new VariableParam(\"c\"), new VariableParam(\"p\"), new VariableParam(\"q\"), new VariableParam(\"x\") }), taskMoveStack, new Monom(\"top(c,p) & on(c,x)\"),\n\t\t\t\tnew TaskNetwork(\"move-topmost-container(p,q) -> move-stack(p,q)\"), false));\n\t\tmethods.add(new Method(\"do-nothing\", Arrays.asList(new VariableParam[] { new VariableParam(\"p\") }), taskMoveStack, new Monom(\"top('pallet',p)\"),\n\t\t\t\tnew TaskNetwork(), false));\n\n\t\t/* create STN domain */\n\t\tSTNPlanningDomain<Operation, Method> domain = new STNPlanningDomain<>(dwrStripsDomain.getOperations(), methods);\n\n\t\t/* define init situation, w.r.t. example in Ghallab, Nau, Traverso; p. 230 */\n\t\tMonom init = new Monom(\"\"\n\t\t\t\t+ \"attached('p1a','l1') & attached('p1b','l1') & attached('p1c','l1') & belong('crane1','l1') & empty('crane1') & in('c11','p1a') & in('c12','p1a') & top('c11','p1a') & top('pallet','p1b') & top('pallet','p1c') & on('c11','c12') & on('c12','pallet') &\"\n\t\t\t\t+ \"attached('p2a','l2') & attached('p2b','l2') & attached('p2c','l2') & belong('crane2','l2') & empty('crane2') & in('c21','p2a') & in('c22','p2a') & in('c23','p2a') & top('c21','p2a') & top('pallet','p2b') & top('pallet','p2c') & on('c21','c22') & on('c22','c23') & on('c23','pallet') &\"\n\t\t\t\t+ \"attached('p3a','l3') & attached('p3b','l3') & attached('p3c','l3') & belong('crane3','l3') & empty('crane3') & in('c31','p3a') & in('c32','p3a') & in('c33','p3a') & in('c34','p3a') & top('c31','p3a') & top('pallet','p3b') & top('pallet','p3c') & on('c31','c32') & on('c32','c33') & on('c33', 'c34') & on('c34','pallet')\"\n\t\t\t\t);\n\t\tTaskNetwork network = new TaskNetwork(\"move-stack('p1a', 'p1c') -> move-stack('p1c','p1b') -> move-stack('p2a','p2c') -> move-stack('p2c','p2b') -> move-stack('p3a','p3c') -> move-stack('p3c','p3b')\");\n\t\treturn new STNPlanningProblem<>(domain, null, init, network);\n\t}\n\n\tpublic static STNPlanningProblem<CEOCOperation, OCMethod, CEOCAction> getNestedDichotomyCreationProblem(String rootClusterName, List<String> classes) {\n\t\tCEOCSTNPlanningProblem<CEOCOperation, OCMethod, CEOCAction> problem = jaicore.planning.model.task.ceocstn.StandardProblemFactory.getNestedDichotomyCreationProblem(rootClusterName, classes, true, 1, 1);\n\t\t\n\t\tList<CEOperation> operations = new ArrayList<>();\n\t\tfor (CEOCOperation op : problem.getDomain().getOperations()) {\n\t\t\tMonom precondition = op.getPrecondition();\n\t\t\tMap<CNFFormula,Monom> addLists = op.getAddLists();\n\t\t\tMap<CNFFormula,Monom> deleteLists = op.getDeleteLists();\n\t\t\tList<VariableParam> parameters = new ArrayList<>(op.getParams());\n\t\t\tif (!op.getOutputs().isEmpty()) {\n\t\t\t\tfor (VariableParam out : op.getOutputs()) {\n\t\t\t\t\tprecondition.addAll(new Monom(\"cluster(\" + out.getName() + \") & !inuse(\" + out.getName() + \")\"));\n\t\t\t\t\taddLists.get(new CNFFormula()).add(new Literal(\"inuse(\" + out.getName() + \")\"));\n\t\t\t\t}\n\t\t\t\tparameters.add(new VariableParam(\"next\"));\n\t\t\t\taddLists.get(new CNFFormula()).add(new Literal(\"active(next)\"));\n\t\t\t\tdeleteLists.put(new CNFFormula(), new Monom(\"active(\" + op.getOutputs().get(0).getName() + \")\"));\n\t\t\t\tprecondition.addAll(new Monom(\"active(\" + op.getOutputs().get(0).getName() + \") & succ(\" + op.getOutputs().get(0).getName() + \", \" + op.getOutputs().get(1).getName() + \") & succ(\" + op.getOutputs().get(1).getName() + \", next)\"));\n\t\t\t}\n\t\t\toperations.add(new CEOperation(op.getName(), parameters, precondition, addLists, deleteLists));\n\t\t}\n\t\tList<Method> methods = new ArrayList<>();\n\t\tfor (OCMethod method : problem.getDomain().getMethods()) {\n\t\t\tList<VariableParam> parameters = new ArrayList<>(method.getParameters());\n\t\t\tMonom precondition = method.getPrecondition();\n\t\t\tTaskNetwork nw = method.getNetwork();\n\t\t\tif (!method.getOutputs().isEmpty()) {\n\t\t\t\tfor (VariableParam out : method.getOutputs()) {\n\t\t\t\t\tprecondition.addAll(new Monom(\"cluster(\" + out.getName() + \") & !inuse(\" + out.getName() + \")\"));\n\t\t\t\t}\n\t\t\t\tparameters.add(new VariableParam(\"next\"));\n\t\t\t\tList<Literal> tasks = new ArrayList<>(nw.getItems()); \n\t\t\t\tfor (Literal task : tasks) {\n\t\t\t\t\tif (task.getPropertyName().endsWith(\"initChildClusters\")) {\n\t\t\t\t\t\tList<LiteralParam> taskParams = new ArrayList<>(task.getParameters());\n\t\t\t\t\t\ttaskParams.add(new VariableParam(\"next\"));\n\t\t\t\t\t\tCollection<Literal> succ = nw.getSuccessors(task);\n\t\t\t\t\t\tCollection<Literal> pred = nw.getPredecessors(task);\n\t\t\t\t\t\tnw.removeItem(task);\n\t\t\t\t\t\tLiteral newTask = new Literal(task.getPropertyName(), taskParams);\n\t\t\t\t\t\tnw.addItem(newTask);\n\t\t\t\t\t\tfor (Literal l : succ)\n\t\t\t\t\t\t\tnw.addEdge(newTask, l);\n\t\t\t\t\t\tfor (Literal l : pred)\n\t\t\t\t\t\t\tnw.addEdge(l, newTask);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tprecondition.addAll(new Monom(\"active(\" + method.getOutputs().get(0).getName() + \") & succ(\" + method.getOutputs().get(0).getName() + \", \" + method.getOutputs().get(1).getName() + \") & succ(\" + method.getOutputs().get(1).getName() + \", next)\"));\n\t\t\t}\n\t\t\tSystem.out.println(precondition);\n\t\t\tmethods.add(new Method(method.getName(), parameters, method.getTask(), precondition, nw, method.isLonely()));\n\t\t}\n\t\t\n\t\tSTNPlanningDomain domain = new STNPlanningDomain(operations, methods);\n\t\tMonom init = problem.getInit();\n\t\tinit.add(new Literal(\"inuse('root')\"));\n\t\tfor (int i = 0; i < 2 * classes.size(); i++) {\n\t\t\tinit.addAll(i == 0 ? new Monom(\"cluster('c0') & active('c1')\") : new Monom(\"cluster('c\" + i + \"') & succ('c\" + (i-1) + \"','c\" + i + \"')\"));\n\t\t}\n\t\tSystem.out.println(init);\n\t\tSTNPlanningProblem newProblem = new STNPlanningProblem(domain, null, init, problem.getNetwork());\n\t\treturn newProblem;\n\t}\n}\n" } ]
285
staRRy-chen/dataScience
https://github.com/staRRy-chen/dataScience
6d508492afb33134c88ab45f46a53e1855eeeb3a
446dc50f0d905b2f6692208bfc08e2df60308d19
5e683aa00c108f5bdfeb06aaf155c20c290c06a9
refs/heads/master
2022-11-24T07:18:24.512130
2020-07-24T05:33:11
2020-07-24T05:33:11
280,848,250
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.53407222032547, "alphanum_fraction": 0.5483032464981079, "avg_line_length": 26.99616813659668, "blob_id": "eda2c522554efe12f20ee1f87367825f2019afef", "content_id": "869d3506f2293ebd5d8fa8e6d8b697bcd610d4aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7640, "license_type": "no_license", "max_line_length": 196, "num_lines": 261, "path": "/analyze.py", "repo_name": "staRRy-chen/dataScience", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport json\nimport os\nimport zipfile\nimport xlwt\nimport pandas as pd\nimport openpyxl\nimport copy\n\nos.chdir('F:/venv/')\nfile_chdir = os.getcwd()\nfile_tem = []\ndic_list = []\ndic = {}\ndic_singleQue = []\nfile_comp = []\nquestionData = []\nallData = []\ncases = []\ninputs = []\ntempInput = ''\noutputs = []\ntempOutput = ''\ncodeNumbers = []\ncurrentQue = ''\ncode = ''\nid = ''\ntype = ''\nscore = 0\nqueName = ''\ncount = 0\nfaceCaseCount = 0\nfaceTime = 0\ntemp={}\ntestcases = '.mooctest/testCases.json'\nanswer = '.mooctest/answer.py'\ncodename = 'main.py'\nsingleSubmit = 'C:/Users/starry/Desktop/singleSubmit.xlsx'\nsingleQue = 'C:/Users/starry/Desktop/singleQue.xlsx'\nquePath = 'C:/Users/starry/Desktop/que.xlsx'\n\n\ndef export_excel(export, filepath):\n # 将字典列表转换为DataFrame\n pf = pd.DataFrame(list(export))\n # 指定字段顺序\n #order = ['id', 'type', 'queName', 'count', 'faceTime','allCases', 'faceCases', 'originScore', 'realScore',]\n #pf = pf[order]\n columns_map = {\n 'id': '用户id',\n 'type': '类型',\n 'queName': '题目',\n 'count': '提交次数',\n 'faceTime':'面向用例提交次数',\n 'allCases': '总用例个数',\n 'faceCases': '面向用例个数',\n 'originScore': '原分数',\n 'realScore': '实际分数',\n 'people':'答题人数',\n 'allCount':'总提交次数',\n 'allFace':'总面向用例提交次数',\n 'allOrigin':'总原始分',\n 'aveOrigin':'原始平均分',\n 'allReal':'总真实分',\n 'aveReal':'真实平均分'\n }\n pf.rename(columns=columns_map, inplace=True)\n # 指定生成的Excel表格名称\n file_path = pd.ExcelWriter(filepath)\n # 替换空单元格\n pf.fillna(' ', inplace=True)\n # 输出\n pf.to_excel(file_path, encoding='utf-8', index=False)\n # 保存表格\n file_path.save()\n\n\ndef getTargetNumbers(s, t):\n numbers = []\n s = str(s)\n i = 0\n l = len(s)\n while i < l:\n num = ''\n symbol = s[i]\n while '0' <= symbol <= '9': # symbol.isdigit()\n num += symbol\n i += 1\n if i < l:\n symbol = s[i]\n else:\n break\n i += 1\n if num != '':\n numbers.append(int(num))\n if t == 'i':\n inputs.append(numbers)\n elif t == 'o':\n outputs.append(numbers)\n else:\n return numbers\n return\n\n\ndef judgeFaceCases(code, case):\n len1 = len(code)\n len2 = len(case)\n if len2 == 1 and case[0] <= 3:\n return 0\n if len1 < len2: return 0\n for i in range(0, len1 - len2 + 1):\n if code[i:i + len2] == case:\n return 1\n return 0\n\n\nfor root, dirs, files in os.walk(file_chdir):\n for file in files:\n file_tem.append(file)\n data = os.path.splitext(file)[0].split(',')\n file_tem.append(data[0])\n file_tem.append(data[1])\n file_tem.append(data[2]) # score\n file_tem.append(data[3])\n file_comp.append(file_tem)\n file_tem = []\nfile_comp.sort(key=lambda x: (x[1], x[2], x[4], x[3]))\nprint(\"success\")\nprint(str(file_comp[0][0]))\n\nfor file in file_comp:\n if '.' not in file[3]:\n continue\n if '.zip' not in str(file[0]):\n continue\n if file[1] != id:\n id = int(file[1])\n if file[2] != type:\n type = file[2]\n if str(file[4]).split('_')[0] != queName:\n queName = str(file[4]).split('_')[0]\n count = 0\n score = 0\n if file[3] != score:\n score = file[3]\n if str(file[4]).split('_')[0] == queName:\n count += 1\n questionData.append(id)\n questionData.append(type)\n questionData.append(queName)\n questionData.append(score)\n questionData.append(count)\n questionData.append(file[0])\n allData.append(questionData)\n questionData = []\nprint('success')\nfor data in allData:\n #print(data[4], data[5])\n if '.zip' not in str(data[5]):\n continue\n try:\n read_hey = zipfile.ZipFile(data[5])\n zipname = read_hey.namelist()[0]\n if '.zip' in zipname:\n fp = read_hey.open(zipname)\n read_code = zipfile.ZipFile(fp)\n code = read_code.open(codename).read() # 获取当前提交代码\n if data[4] == 1:\n if len(dic_list) != 0:\n temp = copy.deepcopy(dic_list[-1])\n temp['faceTime'] = faceTime\n faceTime = 0\n dic_singleQue.append(temp)\n f = read_code.open(testcases)\n cases = json.load(f)\n except:\"zipfile.BadZipFile: File is not a zip file\"\n\n\n for i in range(0, len(cases)):\n tempInput = ''.join(cases[i]['input'])\n tempOutput = ''.join(cases[i]['output'])\n getTargetNumbers(tempInput, 'i')\n getTargetNumbers(tempOutput, 'o')\n\n '''print(\"测试用例输入:\",end='')\n print(inputs)\n print(\"测试用例输出:\",end='')\n print(outputs)\n codeNumbers=getTargetNumbers(code,'c')\n print(\"code中出现的所有数字:\",end='')\n print(codeNumbers)'''\n for k in range(0, len(inputs)):\n faceCaseCount += max(judgeFaceCases(codeNumbers, outputs[k]), judgeFaceCases(codeNumbers, inputs[k]))\n inputs = []\n outputs = []\n if faceCaseCount > 0:\n faceTime += 1\n '''print(data[0],end=' ')\n print(data[1], end=' ')\n print(data[2], end=' ')\n print(data[3], end=' ')'''\n '''if data[4]==0:\n print(\"题目包\",end='')\n else:\n print(\"第%d次提交\" %(data[4]),end=' ')\n print(\"本题共%d个测试用例\" %(len(cases)),end=' ')\n print(\"本次提交中面向用例个数为:%d\" %(faceCaseCount),end=' ')'''\n realScore = float(data[3]) - faceCaseCount / len(cases) * 100\n if realScore < 0:\n realScore = 0\n '''print(cases)\n print(code)'''\n dic = {'id': data[0], 'type': data[1], 'queName': data[2], 'count': data[4],'faceTime':'', 'allCases': len(cases),\n 'faceCases': faceCaseCount, 'originScore': data[3], 'realScore': realScore}\n dic_list.append(dic)\n dic = {}\n faceCaseCount = 0\ntemp=copy.deepcopy(dic_list[-1])\ntemp['faceTime']=faceTime\nfaceTime=0\ndic_singleQue.append(temp)\nfor x in dic_list:\n del x['faceTime']\nprint('success')\nif __name__ == '__main__':\n export_excel(dic_list,singleSubmit)\n export_excel(dic_singleQue,singleQue)\n dic_singleQue.sort(key=lambda x: (x['type'], x['queName']))\n queName=''\n type=''\n allOrigin=0\n allReal=0\n allCount=0\n allFace=0\n count=0\n dic_Que=[]\n for que in dic_singleQue:\n del que['id']\n if queName!=que['queName']:\n if allCount!=0:\n dic={'type':type,'queName':queName,'people':count,'allCount':allCount,'allFace':allFace,'allOrigin':allOrigin,'aveOrigin':allOrigin/count,'allReal':allReal,'aveReal':allReal/count}\n dic_Que.append(dic)\n queName=que['queName']\n allOrigin=0\n allReal=0\n allCount=0\n allFace=0\n count=0\n dic={}\n if type!=que['type']:\n type=que['type']\n allOrigin+=float(que['originScore'])\n allReal+=float(que['realScore'])\n allCount+=int(que['count'])\n allFace+=int(que['faceTime'])\n count+=1\n dic = {'type': type, 'queName': queName, 'people':count,'allCount': allCount, 'allFace': allFace, 'allOrigin': allOrigin,\n 'aveOrigin': allOrigin / count, 'allReal': allReal, 'aveReal': allReal / count}\n dic_Que.append(dic)\n export_excel(dic_Que,quePath)\n\n" }, { "alpha_fraction": 0.5604705810546875, "alphanum_fraction": 0.5778823494911194, "avg_line_length": 26.243589401245117, "blob_id": "dd3dc9bfc8fd9ca550ccb810502338f4836fc031", "content_id": "261a740b89fef442e610da9c295ecec2b1b4a9f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2227, "license_type": "no_license", "max_line_length": 63, "num_lines": 78, "path": "/read.py", "repo_name": "staRRy-chen/dataScience", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport json\nimport os\nimport zipfile\nos.chdir('F:/test/')\nfile_chdir=os.getcwd()\nfile_tem = []\nfile_comp = []\nquestionData=[]\nallData=[]\ncases=[]\ncurrentQue=''\ncode=''\nid=0\ntype=''\nscore=0\nqueName=''\ncount=-1\ntestcases='.mooctest/testCases.json'\nanswer='.mooctest/answer.py'\ncodename='main.py'\nfor root,dirs,files in os.walk(file_chdir):\n for file in files:\n file_tem.append(file)\n data = os.path.splitext(file)[0].split(',')\n file_tem.append(int(data[0]))\n file_tem.append(data[1])\n file_tem.append(float(data[2]))\n file_tem.append(data[3])\n file_comp.append(file_tem)\n file_tem = []\nfile_comp.sort(key=lambda x: (x[1], x[2],x[4],x[3]))\n\n\nfor file in file_comp:\n if file[1]!=id:\n id=int(file[1])\n if file[2]!=type:\n type=file[2]\n if str(file[4]).split('_')[0]!=queName:\n queName=str(file[4]).split('_')[0]\n count=-1\n score=0\n if file[3]!=score:\n score=file[3]\n if str(file[4]).split('_')[0] == queName:\n count+=1\n questionData.append(id)\n questionData.append(type)\n questionData.append(queName)\n questionData.append(score)\n questionData.append(count)\n questionData.append(file[0])\n allData.append(questionData)\n questionData=[]\n\nfor data in allData:\n read_hey = zipfile.ZipFile(data[5])\n if data[4]==0:#如果count=0,代表题目包,从题目包中获取测试用例\n if testcases in read_hey.namelist():\n '''with open(testcases, 'r', encoding='utf8')as fp:\n json_data = json.load(fp)\n print(json_data)'''\n fp=read_hey.open(testcases)\n cases = json.load(fp)\n currentQue=data[2]#更新当前题目\n else:\n zipname=read_hey.namelist()[0]\n if '.zip' in zipname:\n fp=read_hey.open(zipname)\n read_code=zipfile.ZipFile(fp)\n code=read_code.open(codename).read()#获取当前提交代码\n if data[2]!=currentQue:#检验题目与测试用例当前题目是否一致\n f=read_code.open(testcases)\n cases=json.load(f)\n print(code)\n print(cases)\n" } ]
2
danbatiste/ClusterMail
https://github.com/danbatiste/ClusterMail
477d3d2d502cb923a0c355b644bc5def9c0e0641
c53d7fe6bcf2d5fdf36a9a236cfb0a7ded81462c
a167da2efc24314bb9983c238e5b758699d563cc
refs/heads/master
2020-12-30T23:10:31.345149
2017-02-01T05:11:40
2017-02-01T05:11:40
80,589,927
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5454956889152527, "alphanum_fraction": 0.5493435859680176, "avg_line_length": 32.26356506347656, "blob_id": "c7c0686bc1ba2a9d84d81a31da4687ec26793938", "content_id": "8f79c4664442874ad748460b41cbb5eeab07ade3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4418, "license_type": "no_license", "max_line_length": 172, "num_lines": 129, "path": "/ClusterMail.py", "repo_name": "danbatiste/ClusterMail", "src_encoding": "UTF-8", "text": "from __future__ import print_function\r\nfrom email.mime.text import MIMEText\r\nimport smtplib\r\nimport sys\r\nimport copy\r\nimport itertools\r\n\r\n#print(\"List of common SMTP Servers & Ports: https://www.arclab.com/en/kb/email/list-of-smtp-and-pop3-servers-mailserver-list.html\\n\") #implant a list in the readme.md file\r\n#CMM stands for \"ClusterMail Macro\"\r\n\r\ndef strip(line):\r\n if line[~0] == '\\n':\r\n return line[:~0]\r\n return line\r\n\r\ndef filter_spaces(string):\r\n return ''.join(list(filter(lambda c: not c == ' ', string)))\r\n\r\ndef remove_empty(str_list):\r\n return list(filter(lambda x: not x == '', str_list))\r\n\r\ndef parse_CMM(file_path):\r\n #Parsed CMM\r\n parsed = { \"vars\" : { \"n\" : 1 } }\r\n\r\n #Parses CMM\r\n with open(file_path, 'r') as file:\r\n for line in file:\r\n\r\n words = line.split(' ')\r\n\r\n #Variable assignment\r\n if \":=\" in line:\r\n eq = line.split(\":=\")\r\n var = ''.join(filter_spaces(eq[0]))\r\n\r\n if not len(remove_empty(eq[0].split(' '))) == 1:\r\n print(\"Error: Variables must not contain spaces\")\r\n print(\"-> \\\"{}\\\"\\n\".format(strip(line)))\r\n\r\n\r\n value = ''.join(remove_empty(list(itertools.dropwhile(lambda c: c in (' ','\\n') , eq[1:]))))\r\n try:\r\n #Removes possible space or spaces after assignment operator\r\n parsed[\"vars\"].update( {var : eval(value)} )\r\n except:\r\n parsed[\"vars\"].update( {var : value} )\r\n continue\r\n\r\n #Stores the body of the email, but does not parse the body\r\n if line[:5] == \"BEGIN\":\r\n ln = file.read()\r\n parsed.update( {\"BODY\" : \"\"} )\r\n while not ln == '':\r\n parsed[\"BODY\"] += ln\r\n ln = file.read()\r\n\r\n #Seperates Emails(str) into a list of emails, or gives error if no recipients are listed.\r\n try:\r\n parsed[\"vars\"][\"Emails\"] = remove_empty(strip(parsed[\"vars\"][\"Emails\"]).split(' '))\r\n except:\r\n print(\"Error: No recipients listed.\")\r\n\r\n #Returns the parsed CMM with message body left unparsed\r\n return parsed\r\n\r\n#Returns text(str) with variables swapped for their respective values in kwargs(dict).\r\ndef parse_text(text, kwargs):\r\n return text.format(**kwargs)\r\n\r\n#Outputs a preview of the body of an email produced by a CMM to STDOUT\r\ndef preview(file_path):\r\n parsed = parse_CMM(file_path)\r\n parsed[\"vars\"].update( {\"Email\" : \"[email protected]\"} )\r\n print(parse_text(parsed[\"BODY\"], parsed[\"vars\"]))\r\n\r\n\r\ndef main():\r\n #Prompts the user for required arguments if insuffucient arguments are given from the command line\r\n if not len(sys.argv[5:]):\r\n file_path = get_input(\"Enter path to the email macro: \")\r\n server = get_input(\"SMTP Server (Outgoing): \")\r\n port = get_input(\"Port (Outgoing) :\")\r\n email = get_input(\"Sender Email: \")\r\n password = get_input(\"Sender Password: \")\r\n else:\r\n _, file_path, server, port, email, password = sys.argv\r\n\r\n #Parses the user's CMM\r\n parsed = parse_CMM(file_path)\r\n\r\n smtp_server = smtplib.SMTP(server,port)\r\n\r\n #Puts connection to SMTP server in TLS mode\r\n smtp_server.starttls()\r\n s.login(email, password)\r\n\r\n #Sends the email(s) to the recipient(s)\r\n m = 0\r\n for recipient in parsed[\"vars\"][\"Emails\"]:\r\n\r\n #Creates deep copy of parsed CMM\r\n parsed_mut = copy.deepcopy(parsed)\r\n parsed_mut[\"vars\"].update({ \"Email\" : recipient })\r\n\r\n for i in range(parsed[\"vars\"][\"n\"]):\r\n i, m = i + 1, m + 1\r\n parsed_mut[\"vars\"].update({ \"n\" : i + 1})\r\n\r\n #Parses the body text, creates an instance of MIMEText to email, and then appends Subject, To, and From.\r\n body = parse_text(parsed[\"BODY\"], parsed_mut[\"vars\"])\r\n msg = MIMEText(body)\r\n msg[\"Subject\"] = parsed_mut[\"vars\"][\"Subject\"]\r\n msg[\"From\"] = parsed_mut[\"vars\"][\"From\"]\r\n msg[\"To\"] = parsed_mut[\"vars\"][\"To\"]\r\n\r\n #Sends the email\r\n s.sendmail(email, recipient, msg.as_string())\r\n print(\"{}. Mail sent to {}\".format(m, recipient))\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n get_input = input\r\n\r\n if sys.version_info[:2] <= (2, 7):\r\n get_input = raw_input\r\n\r\n main()" }, { "alpha_fraction": 0.7475950717926025, "alphanum_fraction": 0.7544663548469543, "avg_line_length": 45.446807861328125, "blob_id": "d2ec3bcfa1de3a0fb4cd3e2eeaee0d28b7bc616d", "content_id": "ed8f0328f1c0b636121c4d0f169c3f1d4cf8399a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2183, "license_type": "no_license", "max_line_length": 292, "num_lines": 47, "path": "/README.md", "repo_name": "danbatiste/ClusterMail", "src_encoding": "UTF-8", "text": "# ClusterMail\nEmail spammer with domain-specific language for the purpose of creating custom macros.\nCompatible with Python versions 2.x and 3.x.\n\n# Getting Started\n#### Installation\n`git clone https://github.com/danbatiste/ClusterMail`\n\n#### Usage\nClusterMail can be run from the command line as follows.\n\n`python ClusterMail.py CMM_path SMTP_server SMTP_port email password`\n\nIt can also be run directly, and if so will prompt the user to enter the above arguments.\n\n# Writing CMMs\nCMM is short for ClusterMail Macro.\n\n#### Assigning Variables\n`:=` is the assignment operator. It assigns a variable on the left to a Python expression on the right. If the expression is syntactically incorrect, the variable will be assigned its string representation. For example, in the third and fourth lines of `demo.cmm` we have\n```\nFrom := Test sender\nn := 100\n```\n`Test sender` is syntactically incorrect in Python, therefore `From` is assigned its string representation, `\"Test sender\"`.\n`100` is a syntactically correct expression, and so `n` is assigned the integer value of `100`.\n\n#### BEGIN Statement\n`BEGIN` begins the body of the email to be sent. The body of the email is composed of all lines following `BEGIN`.\n\n#### Calling Variables\n`{}` denotes a variable. When the email is composed, `{From}` will be substituted with the value of `From`, that being `\"Test sender\"`.\n\n#### Special Variables\n`Emails`, rather than being assigned to a string, will be converted to a list of emails to send to. This variable is meant to be assigned but not called.\n\n`Subject` is the subject of the email.\n\n`From` is the sender of the email.\n\n`n` is the number of emails to be sent. This variable, when called, will evaluate to the current email number. `n` will increment from 1, and once it is greater than its original value it will reset back to 1 and move on to the next recipient. This mechanism is similar to that of a for loop.\n\n`Email` is meant only to be called and not to be assigned. When called it will evaluate to the current recipient.\n\n\n# Credits\nClusterMail is a collaboration between [@0xCoto](https://github.com/0xCoto) and [@danbatiste](https://github.com/danbatiste).\n" } ]
2
amozie/quantdigger
https://github.com/amozie/quantdigger
4a700e200b05956291d4d90ffb854359888eebce
af3e722242ed575193b7c4702f112dd0d1f36410
c3848167772b113df6bddd1fd4e2bee7db9812f8
refs/heads/master
2021-08-30T14:22:40.227638
2017-12-18T09:24:31
2017-12-18T09:24:31
103,090,411
0
0
null
2017-09-11T04:39:16
2017-09-11T04:39:18
2017-12-17T15:44:24
Python
[ { "alpha_fraction": 0.5234899520874023, "alphanum_fraction": 0.5570470094680786, "avg_line_length": 20.285715103149414, "blob_id": "d803e974a51c3a8879b935587b3cb0b6fa5aadee", "content_id": "4ad6e9c7ae83a8cd88aebe1edbb53e852c5b9db3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 745, "license_type": "no_license", "max_line_length": 50, "num_lines": 35, "path": "/quantdigger/config.py", "repo_name": "amozie/quantdigger", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nsettings = {\n 'source': 'csv',\n #'source': 'mongodb',\n 'data_path': './data',\n 'stock_commission': 3 / 10000.0,\n 'future_commission': 1 / 10000.0,\n 'tick_test': False,\n}\n\n\nclass ConfigLog(object):\n log_level = 'INFO'\n log_to_file = True\n log_to_console = True\n log_path = './log'\n\nclass ConfigColor:\n bar_up_color = 'gray'\n bar_down_color = 'k'\n bar_width = 1\n bar_line_color = 'k'\n bar_alpha = 0.5\n vol_up_color = 'gray'\n vol_down_color = 'k'\n vol_width = 1\n vol_alpha = 0.5\n trading_up_color = 'pink'\n trading_down_color = 'skyblue'\n trading_width = 2\n trading_alpha = 0.7\n plot_line_alpha = 1\n\n__all__ = ['settings', 'ConfigLog', 'ConfigColor']\n" } ]
1
blockspacer/alia
https://github.com/blockspacer/alia
835e8c1d5fe906e146342df3fad1d9fbd515dbdf
e75512b15a74668f0266a04b2e2aa762ba6d7d92
dd9c96e9c3d2c321af9fbb10cc3ad635aa78b930
refs/heads/master
2022-02-20T18:50:07.524203
2018-11-26T15:37:33
2018-11-26T15:37:33
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7197682857513428, "alphanum_fraction": 0.720492422580719, "avg_line_length": 31.880952835083008, "blob_id": "9dab3027f49877e084dde61daa305ca81a251941", "content_id": "1d31de4cc5ab60621950d96cfed9d0c719606d0c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1381, "license_type": "permissive", "max_line_length": 67, "num_lines": 42, "path": "/unit_tests/context.cpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#include <alia/context.hpp>\n#include <alia/events.hpp>\n\n#include <catch2/catch.hpp>\n\nusing namespace alia;\n\nstruct other_traversal_tag\n{\n};\nstruct other_traversal\n{\n};\n\nTEST_CASE(\"component_storage\", \"[context]\")\n{\n component_storage storage;\n\n REQUIRE(!has_component<data_traversal_tag>(storage));\n data_traversal data;\n add_component<data_traversal_tag>(storage, &data);\n REQUIRE(has_component<data_traversal_tag>(storage));\n REQUIRE(get_component<data_traversal_tag>(storage) == &data);\n remove_component<data_traversal_tag>(storage);\n REQUIRE(!has_component<data_traversal_tag>(storage));\n\n REQUIRE(!has_component<event_traversal_tag>(storage));\n event_traversal event;\n add_component<event_traversal_tag>(storage, &event);\n REQUIRE(has_component<event_traversal_tag>(storage));\n REQUIRE(get_component<event_traversal_tag>(storage) == &event);\n remove_component<event_traversal_tag>(storage);\n REQUIRE(!has_component<event_traversal_tag>(storage));\n\n REQUIRE(!has_component<other_traversal_tag>(storage));\n other_traversal other;\n add_component<other_traversal_tag>(storage, &other);\n REQUIRE(has_component<other_traversal_tag>(storage));\n REQUIRE(get_component<other_traversal_tag>(storage) == &other);\n remove_component<other_traversal_tag>(storage);\n REQUIRE(!has_component<other_traversal_tag>(storage));\n}\n" }, { "alpha_fraction": 0.6649457812309265, "alphanum_fraction": 0.6649457812309265, "avg_line_length": 24.15584373474121, "blob_id": "1bdf0dc627b368de6e218753415478d4495d3894", "content_id": "8e8196fe848bf2d760b8dd2cebcddbc959579028", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1937, "license_type": "permissive", "max_line_length": 79, "num_lines": 77, "path": "/src/alia/signals/utilities.hpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#ifndef ALIA_SIGNALS_UTILITIES_HPP\n#define ALIA_SIGNALS_UTILITIES_HPP\n\n#include <alia/signals/core.hpp>\n\n// This file defines various utilities for working with signals.\n// (These are mostly meant to be used internally.)\n\nnamespace alia {\n\n// regular_signal is a partial implementation of the signal interface for\n// cases where the value ID of the signal is simply the value itself.\ntemplate<class Derived, class Value, class Direction>\nstruct regular_signal : signal<Derived, Value, Direction>\n{\n id_interface const&\n value_id() const\n {\n if (this->is_readable())\n {\n id_ = make_id_by_reference(this->read());\n return id_;\n }\n return no_id;\n }\n\n private:\n mutable simple_id_by_reference<Value> id_;\n};\n\n// lazy_reader is used to create signals that lazily generate their values.\n// It provides storage for the computed value and ensures that it's only\n// computed once.\ntemplate<class Value>\nstruct lazy_reader\n{\n lazy_reader() : already_generated_(false)\n {\n }\n template<class Generator>\n Value const&\n read(Generator const& generator) const\n {\n if (!already_generated_)\n {\n value_ = generator();\n already_generated_ = true;\n }\n return value_;\n }\n\n private:\n mutable bool already_generated_;\n mutable Value value_;\n};\n\n// is_true(x), where x is a boolean signal, returns true iff x is readable and\n// its value is true.\ntemplate<class Signal>\nstd::enable_if_t<is_readable_signal_type<Signal>::value, bool>\nis_true(Signal const& x)\n{\n return signal_is_readable(x) && read_signal(x);\n}\n\n// is_false(x), where x is a boolean signal, returns true iff x is readable and\n// its value is false.\ntemplate<class Signal>\nstd::enable_if_t<is_readable_signal_type<Signal>::value, bool>\nis_false(Signal const& x)\n{\n return signal_is_readable(x) && !read_signal(x);\n}\n\n} // namespace alia\n\n#endif\n" }, { "alpha_fraction": 0.6885902285575867, "alphanum_fraction": 0.6891621351242065, "avg_line_length": 27.6639347076416, "blob_id": "6d52b71b3a9d88ef19a97b576ee50bf93c2b7177", "content_id": "3115b1e335cb19b527c6a96b9e6b7518bf1546d2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10491, "license_type": "permissive", "max_line_length": 80, "num_lines": 366, "path": "/src/alia/signals/core.hpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#ifndef ALIA_SIGNALS_CORE_HPP\n#define ALIA_SIGNALS_CORE_HPP\n\n#include <alia/common.hpp>\n#include <alia/id.hpp>\n\n// This file defines the core types and functions of the signals module.\n\nnamespace alia {\n\n// Signals are passed by const reference into UI functions.\n// They're typically created directly at the call site as function arguments\n// and are only valid for the life of the function call.\n// Signals wrappers are templated and store copies of the actual wrapped\n// accessor, which allows them to be easily composed at the call site,\n// without requiring any memory allocation.\n\n// direction tags\nstruct read_only_signal\n{\n};\nstruct write_only_signal\n{\n};\nstruct bidirectional_signal\n{\n};\n\n// signal_direction_is_compatible<Expected,Actual>::value yields a compile-time\n// boolean indicating whether or not a signal with :Actual direction can be used\n// in a context expecting :Expected direction.\n// In the general case, the signals are not compatible.\ntemplate<class Expected, class Actual>\nstruct signal_direction_is_compatible : std::false_type\n{\n};\n// If the directions are the same, this is trivially true.\ntemplate<class Same>\nstruct signal_direction_is_compatible<Same, Same> : std::true_type\n{\n};\n// A bidirectional signal can work as anything.\ntemplate<class Expected>\nstruct signal_direction_is_compatible<Expected, bidirectional_signal>\n : std::true_type\n{\n};\n// Resolve ambiguity.\ntemplate<>\nstruct signal_direction_is_compatible<\n bidirectional_signal,\n bidirectional_signal> : std::true_type\n{\n};\n\n// signal_direction_intersection<A,B>::type, where A and B are signal\n// directions, yields a direction that only has the capabilities that are common\n// to both A and B.\ntemplate<class A, class B>\nstruct signal_direction_intersection\n{\n};\n// If the directions are the same, this is trivial.\ntemplate<class Same>\nstruct signal_direction_intersection<Same, Same>\n{\n typedef Same type;\n};\n// A bidirectional signal has both capabilities.\ntemplate<class A>\nstruct signal_direction_intersection<A, bidirectional_signal>\n{\n typedef A type;\n};\ntemplate<class B>\nstruct signal_direction_intersection<bidirectional_signal, B>\n{\n typedef B type;\n};\n// Resolve ambiguity.\ntemplate<>\nstruct signal_direction_intersection<bidirectional_signal, bidirectional_signal>\n{\n typedef bidirectional_signal type;\n};\n\n// signal_direction_union<A,B>::type, where A and B are signal directions,\n// yields a direction that has the union of the capabilities of A and B.\ntemplate<class A, class B>\nstruct signal_direction_union;\n// If the directions are the same, this is trivial.\ntemplate<class Same>\nstruct signal_direction_union<Same, Same>\n{\n typedef Same type;\n};\ntemplate<class A, class B>\nstruct signal_direction_union\n{\n // All other combinations yield bidirectional signals.\n typedef bidirectional_signal type;\n};\n\n// untyped_signal_base defines functionality common to all signals, irrespective\n// of the type of the value that the signal carries.\nstruct untyped_signal_base\n{\n // Can the signal currently be read from?\n virtual bool\n is_readable() const = 0;\n\n // A signal must supply an ID that uniquely identifies its value.\n // The ID is required to be valid if is_readable() returns true.\n // (It may be valid even if is_readable() returns false, which would mean\n // that the signal can identify its value but doesn't know it yet.)\n // The returned ID reference is only valid as long as the signal itself is\n // valid.\n virtual id_interface const&\n value_id() const = 0;\n\n // Can the signal currently be written to?\n virtual bool\n is_writable() const = 0;\n};\n\ntemplate<class Value>\nstruct signal_interface : untyped_signal_base\n{\n typedef Value value_type;\n\n // Read the signal's value. The reference returned here is only guaranteed\n // to be valid as long as the accessor itself is valid.\n virtual Value const&\n read() const = 0;\n\n // Write the signal's value.\n virtual void\n write(Value const& value) const = 0;\n};\n\ntemplate<class Derived, class Value, class Direction>\nstruct signal_base : signal_interface<Value>\n{\n typedef Direction direction_tag;\n\n template<class Index>\n auto operator[](Index const& index) const;\n};\n\ntemplate<class Derived, class Value, class Direction>\nstruct signal : signal_base<Derived, Value, Direction>\n{\n};\n\ntemplate<class Derived, class Value>\nstruct signal<Derived, Value, read_only_signal>\n : signal_base<Derived, Value, read_only_signal>\n{\n // These must be defined to satisfy the interface requirements, but they\n // obviously won't be used on a read-only signal.\n // LCOV_EXCL_START\n bool\n is_writable() const\n {\n return false;\n }\n void\n write(Value const& value) const\n {\n }\n // LCOV_EXCL_STOP\n};\n\ntemplate<class Derived, class Value>\nstruct signal<Derived, Value, write_only_signal>\n : signal_base<Derived, Value, write_only_signal>\n{\n // These must be defined to satisfy the interface requirements, but they\n // obviously won't be used on a write-only signal.\n // LCOV_EXCL_START\n id_interface const&\n value_id() const\n {\n return no_id;\n }\n bool\n is_readable() const\n {\n return false;\n }\n Value const&\n read() const\n {\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wnull-dereference\"\n#endif\n return *(Value const*) nullptr;\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n }\n // LCOV_EXCL_STOP\n};\n\n// signal_ref is a reference to a signal that acts as a signal itself.\ntemplate<class Value, class Direction>\nstruct signal_ref : signal<signal_ref<Value, Direction>, Value, Direction>\n{\n // Construct from any signal with compatible direction.\n template<class OtherSignal, class OtherDirection>\n signal_ref(\n signal<OtherSignal, Value, OtherDirection> const& signal,\n std::enable_if_t<\n signal_direction_is_compatible<Direction, OtherDirection>::value,\n int> = 0)\n : ref_(&signal)\n {\n }\n // Construct from another signal_ref. - This is meant to prevent unnecessary\n // layers of indirection.\n signal_ref(signal_ref<Value, Direction> const& other) : ref_(other.ref_)\n {\n }\n\n // implementation of signal_interface...\n\n bool\n is_readable() const\n {\n return ref_->is_readable();\n }\n Value const&\n read() const\n {\n return ref_->read();\n }\n id_interface const&\n value_id() const\n {\n return ref_->value_id();\n }\n bool\n is_writable() const\n {\n return ref_->is_writable();\n }\n void\n write(Value const& value) const\n {\n ref_->write(value);\n }\n\n private:\n signal_interface<Value> const* ref_;\n};\n\n// input<Value> denotes a reference to a readable signal carrying values of\n// type :Value.\ntemplate<class Value>\nusing input = signal_ref<Value, read_only_signal>;\n\n// output<Value> denotes a reference to a writable signal carrying values of\n// type :Value.\ntemplate<class Value>\nusing output = signal_ref<Value, write_only_signal>;\n\n// bidirectional<Value> denotes a reference to a bidirectional signal carrying\n// values of type :Value.\ntemplate<class Value>\nusing bidirectional = signal_ref<Value, bidirectional_signal>;\n\n// is_signal_type<T>::value yields a compile-time boolean indicating whether or\n// not T is an alia signal type.\ntemplate<class T>\nstruct is_signal_type : std::is_base_of<untyped_signal_base, T>\n{\n};\n\n// signal_can_read<Signal>::value yields a compile-time boolean indicating\n// whether or not the given signal type supports reading.\ntemplate<class Signal>\nstruct signal_can_read : signal_direction_is_compatible<\n read_only_signal,\n typename Signal::direction_tag>\n{\n};\n\n// is_readable_signal_type<T>::value yields a compile-time boolean indicating\n// whether or not T is an alia signal that supports reading.\ntemplate<class T>\nstruct is_readable_signal_type : std::conditional_t<\n is_signal_type<T>::value,\n signal_can_read<T>,\n std::false_type>\n{\n};\n\n// Is :signal currently readable?\n// Unlike calling signal.is_readable() directly, this will generate a\n// compile-time error if the signal's type doesn't support reading.\ntemplate<class Signal>\nstd::enable_if_t<signal_can_read<Signal>::value, bool>\nsignal_is_readable(Signal const& signal)\n{\n return signal.is_readable();\n}\n\n// Read a signal's value.\n// Unlike calling signal.read() directly, this will generate a compile-time\n// error if the signal's type doesn't support reading and a run-time error if\n// the signal isn't currently readable.\ntemplate<class Signal>\nstd::enable_if_t<\n signal_can_read<Signal>::value,\n typename Signal::value_type const&>\nread_signal(Signal const& signal)\n{\n assert(signal.is_readable());\n return signal.read();\n}\n\n// signal_can_write<Signal>::value yields a compile-time boolean indicating\n// whether or not the given signal type supports writing.\ntemplate<class Signal>\nstruct signal_can_write : signal_direction_is_compatible<\n write_only_signal,\n typename Signal::direction_tag>\n{\n};\n\n// is_writable_signal_type<T>::value yields a compile-time boolean indicating\n// whether or not T is an alia signal that supports writing.\ntemplate<class T>\nstruct is_writable_signal_type : std::conditional_t<\n is_signal_type<T>::value,\n signal_can_write<T>,\n std::false_type>\n{\n};\n\n// Is :signal currently writable?\n// Unlike calling signal.is_writable() directly, this will generate a\n// compile-time error if the signal's type doesn't support writing.\ntemplate<class Signal>\nstd::enable_if_t<signal_can_write<Signal>::value, bool>\nsignal_is_writable(Signal const& signal)\n{\n return signal.is_writable();\n}\n\n// Write a signal's value.\n// Unlike calling signal.write() directly, this will generate a compile-time\n// error if the signal's type doesn't support writing and a run-time error if\n// the signal isn't currently writable.\ntemplate<class Signal, class Value>\nstd::enable_if_t<signal_can_write<Signal>::value>\nwrite_signal(Signal const& signal, Value const& value)\n{\n assert(signal.is_writable());\n signal.write(value);\n}\n\n} // namespace alia\n\n#endif\n" }, { "alpha_fraction": 0.6303630471229553, "alphanum_fraction": 0.6303630471229553, "avg_line_length": 20.64285659790039, "blob_id": "edcc61a37663f803ad6d455644a150d4d5a6eee0", "content_id": "b477da92012437b66d68f59b9dcd27a99f7fcde5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 303, "license_type": "permissive", "max_line_length": 94, "num_lines": 14, "path": "/docs/in-depth/loops-and-conditionals.rst", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "Loops & Conditionals\n====================\n\nPreferred\n---------\n\n.. todo: alia_if/else (with signals), alia_switch/alia_case, for_each\n\n.. todo: Mention ALIA_STRICT_CONDITIONALS.\n\nCompatibility\n-------------\n\n.. todo: alia_for, alia_while, alia_if/else (with booleans), alia_switch (with regular values)\n" }, { "alpha_fraction": 0.7152907848358154, "alphanum_fraction": 0.7213883399963379, "avg_line_length": 40.80392074584961, "blob_id": "24d9f42c64970a33a14107887e7aa5cd78973013", "content_id": "c577068f70c98223ca0167858c943a647ea86ab0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 2132, "license_type": "permissive", "max_line_length": 332, "num_lines": 51, "path": "/README.rst", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "alia\n====\n\n.. image:: https://img.shields.io/travis/tmadden/alia.svg?style=flat&logo=travis\n :target: https://travis-ci.org/tmadden/alia\n\n.. image:: https://img.shields.io/appveyor/ci/tmadden/alia/master.svg?style=flat&logo=appveyor\n :target: https://ci.appveyor.com/project/tmadden/alia/branch/master\n\n.. image:: https://img.shields.io/codecov/c/github/tmadden/alia/master.svg?style=flat\n :target: https://codecov.io/gh/tmadden/alia\n\n|\n\n**WARNING**: This project is in an unstable, pre-release state. There are missing links, missing documentation pages, missing features, and APIs that may change in the future. That said, what's there now should work well, so if you're interested in playing around with it, I welcome any feedback or contributions!\n\nalia (pronounced uh-LEE-uh) is a modern C++ library for developing reactive applications. It provides a core of generic facilities for reactive programming (data flow modeling, event processing, etc.) as well as interfaces to some existing C++ libraries, allowing those libraries to be used reactively from within alia applications.\n\nThe full documentation for alia can be found here.\n\nBelow is a simple tip calculator written in alia using the asm-dom wrapper. To try it out and see more examples, click here.\n\n.. todo: Add links to documentation and examples.\n\n.. code-block:: C++\n\n\t// Get the state we need.\n\tauto bill = get_state<double>(ctx); // defaults to uninitialized\n\tauto tip_percentage = get_state(ctx, value(20.)); // defaults to 20%\n\n\t// Show some controls for manipulating our state.\n\tdo_input(ctx, bill);\n\tdo_input(ctx, tip_percentage);\n\n\t// Do some reactive calculations.\n\tauto tip = bill * tip_percentage / value(100.);\n\tauto total = bill + tip;\n\n\t// Show the results.\n\tdo_text(ctx, format(ctx, \"tip: %.2f\", tip);\n\tdo_text(ctx, format(ctx, \"total: %.2f\", total);\n\n\t// Allow the user to split the bill.\n\tauto n_people = get_state(ctx, value(1.));\n\tdo_input(ctx, n_people);\n\talia_if (n_people > 1)\n\t{\n\t\tdo_text(ctx, format(ctx, \"tip per person: %.2f\", tip / n_people);\n\t\tdo_text(ctx, format(ctx, \"total per person: %.2f\", total / n_people);\n\t}\n\talia_end\n" }, { "alpha_fraction": 0.6220522522926331, "alphanum_fraction": 0.6220522522926331, "avg_line_length": 39.75324630737305, "blob_id": "6fe94a651576cec05ffcb72367019e0a1358de43", "content_id": "216dac43c22d1be01762b4312b5d5037eed24a4a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 3138, "license_type": "permissive", "max_line_length": 364, "num_lines": 77, "path": "/docs/state-management.rst", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "State Management\n================\n\nAssociating State\n-----------------\n\nImagine that we want to modify the contact UI from the last section so that it has two modes: viewing and editing. Contacts are read-only in viewing mode, but the editing UI has the same editing controls as before. We could do that like this... ::\n\n struct contact\n {\n contact() : editing(false) {}\n bool editing;\n std::string name;\n std::string phone;\n };\n\n void do_contact_ui(context& ctx, contact& c)\n {\n alia_if (c.editing)\n {\n do_text_control(ctx, inout(&c.name));\n do_text_control(ctx, inout(&c.phone));\n if (do_button(ctx, \"OK\"))\n c.editing = false;\n }\n alia_else\n {\n do_text(ctx, c.name);\n do_text(ctx, c.phone);\n if (do_link(ctx, \"edit\"))\n c.editing = true;\n }\n alia_end\n \n do_separator(ctx);\n }\n\nThe above code behaves as desired, but now we've introduced UI-specific state into our contact structure. Ideally, we'd like our model data to be independent of any UI considerations, so we'd like to store the \"editing\" flag somewhere UI-specific. Fortunately, alia has a facility for this called get_state. ::\n\n struct contact\n {\n std::string name;\n std::string phone;\n };\n\n void do_contact_ui(context& ctx, contact& c)\n {\n state_accessor<bool> editing = get_state(ctx, false);\n \n alia_if (get(editing))\n {\n do_text_control(ctx, inout(&c.name));\n do_text_control(ctx, inout(&c.phone));\n if (do_button(ctx, \"OK\"))\n set(editing, false);\n }\n alia_else\n {\n do_text(ctx, c.name);\n do_text(ctx, c.phone);\n if (do_link(ctx, \"edit\"))\n set(editing, true);\n }\n alia_end\n \n do_separator(ctx);\n }\n\nget_state retrieves persistent state that's associated with the part of the UI that's currently being specified. It's a templated function, so it can retrieve any type of state. The state persists as long as the part of the UI that it's associated with.\nget_state comes in two forms. In the form used above, the second argument is the default value of the state. When the state is created, it's initialized with that value. The second form is used as follows. ::\n\n state_accessor<bool> editing;\n if (get_state(ctx, &editing))\n set(editing, false);\n\nWith this form, the first time get_state is called for a particular piece of UI, it returns true, indicating that the state it retrieved was just created (default constructed). The calling function can use this to initialize the state.\nUsing get_state, you can associate arbitrary UI-specific state with the portion of the UI that needs it, without anyone outside the function ever knowing. In fact, all along, some of the widgets we've been using have been calling get_state without us knowing. For example, this is how the text controls are able to track their cursor position, text selection, etc.\n" }, { "alpha_fraction": 0.4285714328289032, "alphanum_fraction": 0.4285714328289032, "avg_line_length": 12.800000190734863, "blob_id": "2ea220c8a7767260ee146db36ac40f8a17908a30", "content_id": "87e0ff66035441d4817010488c1c641ee1109c57", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 70, "license_type": "permissive", "max_line_length": 18, "num_lines": 5, "path": "/docs/in-depth/best-practices.rst", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "Best Practices\n==============\n\nState Minimization\n------------------\n\n" }, { "alpha_fraction": 0.594936728477478, "alphanum_fraction": 0.6017526984214783, "avg_line_length": 19.13725471496582, "blob_id": "14dda67df80515dbaf10d42fc05f5cc1535fa894", "content_id": "904e2c5fa0e045902ecb95d0a1753e182649bfed", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2054, "license_type": "permissive", "max_line_length": 70, "num_lines": 102, "path": "/unit_tests/signals/utilities.cpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#include <alia/signals/utilities.hpp>\n\n#include <catch2/catch.hpp>\n\n#include <alia/signals/basic.hpp>\n\nusing namespace alia;\n\nstruct unreadable_regular_signal\n : regular_signal<unreadable_regular_signal, int, read_only_signal>\n{\n bool\n is_readable() const\n {\n return false;\n }\n int const&\n read() const\n {\n static int value = 17;\n return value;\n }\n};\n\nTEST_CASE(\"unreadable regular_signal\", \"[signals]\")\n{\n unreadable_regular_signal s;\n\n typedef decltype(s) signal_t;\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(!signal_can_write<signal_t>::value);\n\n REQUIRE(!signal_is_readable(s));\n REQUIRE(s.value_id() == no_id);\n}\n\nstruct normal_regular_signal\n : regular_signal<normal_regular_signal, int, bidirectional_signal>\n{\n bool\n is_readable() const\n {\n return true;\n }\n int const&\n read() const\n {\n static int value = 17;\n return value;\n }\n bool\n is_writable() const\n {\n return false;\n }\n void\n write(int const& value) const\n {\n }\n};\n\nTEST_CASE(\"normal regular_signal\", \"[signals]\")\n{\n normal_regular_signal s;\n\n typedef decltype(s) signal_t;\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(signal_can_write<signal_t>::value);\n\n REQUIRE(signal_is_readable(s));\n REQUIRE(s.value_id() == make_id_by_reference(s.read()));\n REQUIRE(!signal_is_writable(s));\n}\n\nTEST_CASE(\"lazy_reader\", \"[signals]\")\n{\n int n = 0;\n\n auto generator = [&]() {\n ++n;\n return 12;\n };\n\n lazy_reader<int> reader;\n\n REQUIRE(reader.read(generator) == 12);\n REQUIRE(n == 1);\n // Check that it is caching and not re-invoking the generator.\n REQUIRE(reader.read(generator) == 12);\n REQUIRE(n == 1);\n}\n\nTEST_CASE(\"is_true/false\", \"[signals]\")\n{\n REQUIRE(is_true(value(true)));\n REQUIRE(!is_true(value(false)));\n REQUIRE(!is_true(empty<bool>()));\n\n REQUIRE(is_false(value(false)));\n REQUIRE(!is_false(value(true)));\n REQUIRE(!is_false(empty<bool>()));\n}\n" }, { "alpha_fraction": 0.7257583141326904, "alphanum_fraction": 0.7257583141326904, "avg_line_length": 34.91071319580078, "blob_id": "afe44c2b88105e8f46d7b2451be813e6f0ee8769", "content_id": "cc18d40f87c5b8fafc3c47d96f5cc9726f553703", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 4022, "license_type": "permissive", "max_line_length": 459, "num_lines": 112, "path": "/docs/in-depth/signals.rst", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "Signals\n=======\n\nIn alia, signals are values that vary over time. In other words, alia signals are like those from signal processing (and *not* like IPC signals, which are equivalent to events in alia).\n\n.. todo:: Add some example code and point out the signals.\n\nIf you think of an alia application as defining a dataflow graph where the inputs are application state and the outputs go into a back end (e.g., are displayed on the screen), then the edges of this graph (where the values live) are all signals.\n\n\n\nDirectionality\n--------------\n\nIn general, signal values can be read (i.e., polled) and new values can be written to signals, but not all signals support both operations.\n\n.. todo:: Add an example of, say, adding two signals and point out how writing to the sum doesn't make sense.\n\nSignals carry a compile-time property that indicates the direction(s) in which values can flow: read-only, write-only or bidirectional. Similarly, when a function takes a signal as a parameter, the function signature will specify the requirements of the signal:\n\n* **input**: The function may try to read the signal.\n* **output**: The function may try to write to the signal.\n* **bidirectional**: The function may try to read from or write to the signal.\n\n.. todo:: Add an example function declaration.\n\nWhen calling a function, the signals that you provide must meet those requirements. (e.g., If a function expects an input signal but you try to pass a signal that only supports writing, a compile-time error will be generated.)\n\n.. todo:: Add a link to an advanced section about bypassing these checks.\n\nAvailability\n------------\n\nEven when a signal supports reading, it might not always have a value. There are any number of reasons why this might be the case:\n\n* The signal is a user input and has no value until the user enters one.\n* The signal represents some remote data that is still being retrieved.\n* The signal is the result of some computationally intensive calculation that hasn't completed yet.\n\nBefore trying to read from a signal, you should check that it is actually readable using ``signal_is_readable``.\n\nSimilarly, a signal that supports writing isn't necessarily *always* writable. (e.g., Some data may require the user to explicitly unlock it, or it may be unwritable during certain sync operations.) Use ``signal_is_writable`` to check if a signal is writable before trying to write a value to it.\n\nValue Identity\n--------------\n\n.. caution:: This is advanced stuff.\n\nJust like regular values in C++, a signal value can be arbitrarily large. For example, a signal could carry a block of text or an image. Since alia uses polling to detect changes in signals, this can be prohibitively expensive for large signal values. (If we were using alia to display a large image, we wouldn't want alia to compare every pixel of the image every frame to make sure that the image we're providing is still the same one that's on the screen.)\n\nTo address this concern, any signal with a readable value must also provide a *value identity*.\n\nThere is one simple rule governing value identitiies:\n\n*If a signal's value changes, it's value identity must also change.*\n\n(Note that the converse is not true. A signal's value identity can change without a change in value.)\n\nIt is common for a single's value identity to be the value itself.\n\nConstructing Signals\n--------------------\n\n``value``\n\n``direct``\n\n``empty``\n\nLambdas\n^^^^^^^\n\n``lambda_input(is_readable, read)``\n\n``lambda_input(is_readable, read, generate_id)``\n\n``lambda_bidirectional(is_readable, read, is_writable, write)``\n\n``lambda_bidirectional(is_readable, read, is_writable, write, generate_id)``\n\nTransforming & Composing Signals\n--------------------------------\n\nOperators\n^^^^^^^^^\n\nCasts\n^^^^^\n\n``signal_cast<Value>(signal)``\n\nFunction Application\n^^^^^^^^^^^^^^^^^^^^\n\nMaps\n^^^^\n\nOther Adaptors\n^^^^^^^^^^^^^^\n\nCreating Custom Signals\n-----------------------\n\nExpected Interface\n^^^^^^^^^^^^^^^^^^\n\nUtilities\n^^^^^^^^^\n\nregular_signal\n\nlazy_reader\n" }, { "alpha_fraction": 0.7515923380851746, "alphanum_fraction": 0.7515923380851746, "avg_line_length": 14.699999809265137, "blob_id": "d79f8a7eb346b260496bfff69dfd703e196a9d96", "content_id": "41ded209d8ab7aa70ad8879bacc9542b31469a2e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 157, "license_type": "permissive", "max_line_length": 37, "num_lines": 10, "path": "/src/alia/signals/higher_order.hpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#ifndef ALIA_SIGNALS_HIGHER_ORDER_HPP\n#define ALIA_SIGNALS_HIGHER_ORDER_HPP\n\n#include <alia/signals/core.hpp>\n\nnamespace alia {\n\n} // namespace alia\n\n#endif\n" }, { "alpha_fraction": 0.6732576489448547, "alphanum_fraction": 0.6748238205909729, "avg_line_length": 33.98630142211914, "blob_id": "ecb9a3c5f2c7fb796255d58d33b529ec618651b8", "content_id": "bdf8f108bbb33c6b0301dafcf8227bbce9296f68", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5108, "license_type": "permissive", "max_line_length": 80, "num_lines": 146, "path": "/unit_tests/signals/core.cpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#include <alia/signals/core.hpp>\n\n#include <catch2/catch.hpp>\n\n#include <alia/signals/basic.hpp>\n\nusing namespace alia;\n\nTEST_CASE(\"signal_direction_is_compatible\", \"[signals]\")\n{\n#define TEST_COMPATIBILITY(Expected, Actual, result) \\\n REQUIRE( \\\n (signal_direction_is_compatible<Expected, Actual>::value) == (result))\n\n TEST_COMPATIBILITY(read_only_signal, read_only_signal, true);\n TEST_COMPATIBILITY(read_only_signal, write_only_signal, false);\n TEST_COMPATIBILITY(read_only_signal, bidirectional_signal, true);\n TEST_COMPATIBILITY(write_only_signal, read_only_signal, false);\n TEST_COMPATIBILITY(write_only_signal, write_only_signal, true);\n TEST_COMPATIBILITY(write_only_signal, bidirectional_signal, true);\n TEST_COMPATIBILITY(bidirectional_signal, read_only_signal, false);\n TEST_COMPATIBILITY(bidirectional_signal, write_only_signal, false);\n TEST_COMPATIBILITY(bidirectional_signal, bidirectional_signal, true);\n}\n\nTEST_CASE(\"signal_direction_intersection\", \"[signals]\")\n{\n#define TEST_INTERSECTION(A, B, Result) \\\n REQUIRE((std::is_same<signal_direction_intersection<A, B>::type, Result>:: \\\n value))\n\n TEST_INTERSECTION(read_only_signal, read_only_signal, read_only_signal);\n TEST_INTERSECTION(read_only_signal, bidirectional_signal, read_only_signal);\n TEST_INTERSECTION(write_only_signal, write_only_signal, write_only_signal);\n TEST_INTERSECTION(\n write_only_signal, bidirectional_signal, write_only_signal);\n TEST_INTERSECTION(bidirectional_signal, read_only_signal, read_only_signal);\n TEST_INTERSECTION(\n bidirectional_signal, write_only_signal, write_only_signal);\n TEST_INTERSECTION(\n bidirectional_signal, bidirectional_signal, bidirectional_signal);\n}\n\nTEST_CASE(\"signal_direction_union\", \"[signals]\")\n{\n#define TEST_UNION(A, B, Result) \\\n REQUIRE((std::is_same<signal_direction_union<A, B>::type, Result>::value))\n\n TEST_UNION(read_only_signal, read_only_signal, read_only_signal);\n TEST_UNION(read_only_signal, write_only_signal, bidirectional_signal);\n TEST_UNION(read_only_signal, bidirectional_signal, bidirectional_signal);\n TEST_UNION(write_only_signal, write_only_signal, write_only_signal);\n TEST_UNION(write_only_signal, read_only_signal, bidirectional_signal);\n TEST_UNION(write_only_signal, bidirectional_signal, bidirectional_signal);\n TEST_UNION(bidirectional_signal, read_only_signal, bidirectional_signal);\n TEST_UNION(bidirectional_signal, write_only_signal, bidirectional_signal);\n TEST_UNION(\n bidirectional_signal, bidirectional_signal, bidirectional_signal);\n}\n\nTEST_CASE(\"is_signal_type\", \"[signals]\")\n{\n REQUIRE(is_signal_type<input<int>>::value);\n REQUIRE(is_signal_type<output<int>>::value);\n REQUIRE(is_signal_type<bidirectional<int>>::value);\n REQUIRE(!is_signal_type<int>::value);\n REQUIRE(!is_signal_type<std::string>::value);\n}\n\nTEST_CASE(\"signal_can_read\", \"[signals]\")\n{\n REQUIRE(signal_can_read<input<int>>::value);\n REQUIRE(!signal_can_read<output<int>>::value);\n REQUIRE(signal_can_read<bidirectional<int>>::value);\n}\n\nTEST_CASE(\"is_readable_signal_type\", \"[signals]\")\n{\n REQUIRE(is_readable_signal_type<input<int>>::value);\n REQUIRE(!is_readable_signal_type<output<int>>::value);\n REQUIRE(is_readable_signal_type<bidirectional<int>>::value);\n REQUIRE(!is_readable_signal_type<int>::value);\n REQUIRE(!is_readable_signal_type<std::string>::value);\n}\n\nTEST_CASE(\"signal_can_write\", \"[signals]\")\n{\n REQUIRE(!signal_can_write<input<int>>::value);\n REQUIRE(signal_can_write<output<int>>::value);\n REQUIRE(signal_can_write<bidirectional<int>>::value);\n}\n\nTEST_CASE(\"is_writable_signal_type\", \"[signals]\")\n{\n REQUIRE(!is_writable_signal_type<input<int>>::value);\n REQUIRE(is_writable_signal_type<output<int>>::value);\n REQUIRE(is_writable_signal_type<bidirectional<int>>::value);\n REQUIRE(!is_writable_signal_type<int>::value);\n REQUIRE(!is_writable_signal_type<std::string>::value);\n}\n\nTEST_CASE(\"signal_ref\", \"[signals]\")\n{\n int x = 1;\n auto y = direct(x);\n signal_ref<int, bidirectional_signal> s = y;\n\n typedef decltype(s) signal_t;\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(signal_can_write<signal_t>::value);\n\n REQUIRE(signal_is_readable(s));\n REQUIRE(s.value_id() == y.value_id());\n REQUIRE(read_signal(s) == 1);\n REQUIRE(signal_is_writable(s));\n write_signal(s, 0);\n REQUIRE(x == 0);\n REQUIRE(read_signal(s) == 0);\n}\n\nstatic void\nf_input(alia::input<int> x)\n{\n}\n\nstatic void\nf_output(alia::output<int> x)\n{\n}\n\nstatic void\nf_bidirectional(alia::bidirectional<int> x)\n{\n}\n\nTEST_CASE(\"signal parameter passing\", \"[signals]\")\n{\n auto read_only = value(0);\n int x = 0;\n auto bidirectional = direct(x);\n\n f_input(read_only);\n f_input(bidirectional);\n f_output(bidirectional);\n f_bidirectional(bidirectional);\n}\n" }, { "alpha_fraction": 0.5882048010826111, "alphanum_fraction": 0.5956416726112366, "avg_line_length": 22.600000381469727, "blob_id": "e4384761d3348f6bce31c901666f9a3dfea4821f", "content_id": "5665968b5e42526e1ca6feb5b22261499b690eee", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5782, "license_type": "permissive", "max_line_length": 80, "num_lines": 245, "path": "/src/alia/signals/application.hpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#ifndef ALIA_SIGNALS_APPLICATION_HPP\n#define ALIA_SIGNALS_APPLICATION_HPP\n\n#include <alia/context.hpp>\n#include <alia/signals/utilities.hpp>\n\nnamespace alia {\n\n// lazy_apply(f, args...), where :args are all signals, yields a signal\n// to the result of lazily applying the function :f to the values of :args.\n\n// Note that doing this in true variadic fashion is a little insane, so I'm\n// just doing the two overloads I need for now...\n\ntemplate<class Result, class Function, class Arg>\nstruct lazy_apply1_signal : signal<\n lazy_apply1_signal<Result, Function, Arg>,\n Result,\n read_only_signal>\n{\n lazy_apply1_signal(Function const& f, Arg const& arg) : f_(f), arg_(arg)\n {\n }\n id_interface const&\n value_id() const\n {\n return arg_.value_id();\n }\n bool\n is_readable() const\n {\n return arg_.is_readable();\n }\n Result const&\n read() const\n {\n return lazy_reader_.read([&] { return f_(arg_.read()); });\n }\n\n private:\n Function f_;\n Arg arg_;\n lazy_reader<Result> lazy_reader_;\n};\ntemplate<class Function, class Arg>\nauto\nlazy_apply(Function const& f, Arg const& arg)\n{\n return lazy_apply1_signal<decltype(f(read_signal(arg))), Function, Arg>(\n f, arg);\n}\n\ntemplate<class Result, class Function, class Arg0, class Arg1>\nstruct lazy_apply2_signal\n : signal<\n lazy_apply2_signal<Result, Function, Arg0, Arg1>,\n Result,\n read_only_signal>\n{\n lazy_apply2_signal(Function const& f, Arg0 const& arg0, Arg1 const& arg1)\n : f_(f), arg0_(arg0), arg1_(arg1)\n {\n }\n id_interface const&\n value_id() const\n {\n id_ = combine_ids(ref(arg0_.value_id()), ref(arg1_.value_id()));\n return id_;\n }\n bool\n is_readable() const\n {\n return arg0_.is_readable() && arg1_.is_readable();\n }\n Result const&\n read() const\n {\n return lazy_reader_.read(\n [&]() { return f_(arg0_.read(), arg1_.read()); });\n }\n\n private:\n Function f_;\n Arg0 arg0_;\n Arg1 arg1_;\n mutable id_pair<id_ref, id_ref> id_;\n lazy_reader<Result> lazy_reader_;\n};\ntemplate<class Function, class Arg0, class Arg1>\nauto\nlazy_apply(Function const& f, Arg0 const& arg0, Arg1 const& arg1)\n{\n return lazy_apply2_signal<\n decltype(f(read_signal(arg0), read_signal(arg1))),\n Function,\n Arg0,\n Arg1>(f, arg0, arg1);\n}\n\ntemplate<class Function>\nauto\nlazy_lift(Function const& f)\n{\n return [=](auto&&... args) { return lazy_apply(f, args...); };\n}\n\n// apply(ctx, f, args...), where :args are all signals, yields a signal to the\n// result of applying the function :f to the values of :args. Unlike lazy_apply,\n// this is eager and caches and the result.\n\nenum class apply_status\n{\n UNCOMPUTED,\n READY,\n FAILED\n};\n\ntemplate<class Value>\nstruct apply_result_data\n{\n int result_version = 0;\n Value result;\n apply_status status = apply_status::UNCOMPUTED;\n};\n\ntemplate<class Value>\nvoid\nreset(apply_result_data<Value>& data)\n{\n if (data.status != apply_status::UNCOMPUTED)\n {\n ++data.result_version;\n data.status = apply_status::UNCOMPUTED;\n }\n}\n\ntemplate<class Value>\nstruct apply_signal : signal<apply_signal<Value>, Value, read_only_signal>\n{\n apply_signal(apply_result_data<Value>& data) : data_(&data)\n {\n }\n id_interface const&\n value_id() const\n {\n id_ = make_id(data_->result_version);\n return id_;\n }\n bool\n is_readable() const\n {\n return data_->status == apply_status::READY;\n }\n Value const&\n read() const\n {\n return data_->result;\n }\n\n private:\n apply_result_data<Value>* data_;\n mutable simple_id<int> id_;\n};\n\ntemplate<class Value>\napply_signal<Value>\nmake_apply_signal(apply_result_data<Value>& data)\n{\n return apply_signal<Value>(data);\n}\n\ntemplate<class Result>\nvoid\nprocess_apply_args(\n context ctx, apply_result_data<Result>& data, bool& args_ready)\n{\n}\ntemplate<class Result, class Arg, class... Rest>\nvoid\nprocess_apply_args(\n context ctx,\n apply_result_data<Result>& data,\n bool& args_ready,\n Arg const& arg,\n Rest const&... rest)\n{\n captured_id* cached_id;\n get_cached_data(ctx, &cached_id);\n if (!signal_is_readable(arg))\n {\n reset(data);\n args_ready = false;\n }\n else if (!cached_id->matches(arg.value_id()))\n {\n reset(data);\n cached_id->capture(arg.value_id());\n }\n process_apply_args(ctx, data, args_ready, rest...);\n}\n\ntemplate<class Function, class... Args>\nauto\napply(context ctx, Function const& f, Args const&... args)\n{\n apply_result_data<decltype(f(read_signal(args)...))>* data_ptr;\n get_cached_data(ctx, &data_ptr);\n auto& data = *data_ptr;\n if (is_refresh_pass(ctx))\n {\n bool args_ready = true;\n process_apply_args(ctx, data, args_ready, args...);\n if (data.status == apply_status::UNCOMPUTED && args_ready)\n {\n try\n {\n data.result = f(read_signal(args)...);\n data.status = apply_status::READY;\n }\n catch (...)\n {\n data.status = apply_status::FAILED;\n }\n }\n }\n return make_apply_signal(data);\n}\n\ntemplate<class Function>\nauto\nlift(context ctx, Function const& f)\n{\n return [=](auto&&... args) { return apply(ctx, f, args...); };\n}\n\n// alia_method(m) wraps a method name in a lambda so that it can be passed as a\n// function object.\n#define ALIA_METHOD(m) [](auto&& x, auto&&... args) { return x.m(args...); }\n#ifdef ALIA_LOWERCASE_MACROS\n#define alia_method(m) ALIA_METHOD(m)\n#endif\n\n} // namespace alia\n\n#endif\n" }, { "alpha_fraction": 0.5885492563247681, "alphanum_fraction": 0.5958272814750671, "avg_line_length": 25.423076629638672, "blob_id": "30f68e180c0b282d19b47fdd13375f0eed575e65", "content_id": "54b15f810f9cd5473333b0a4dd0e9cd7429fd8da", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2061, "license_type": "permissive", "max_line_length": 71, "num_lines": 78, "path": "/unit_tests/signals/lambdas.cpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#include <alia/signals/lambdas.hpp>\n\n#include <catch2/catch.hpp>\n\nusing namespace alia;\n\nTEST_CASE(\"lambda input signal\", \"[signals]\")\n{\n auto s = lambda_input(always_readable, []() { return 1; });\n\n typedef decltype(s) signal_t;\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(!signal_can_write<signal_t>::value);\n\n REQUIRE(signal_is_readable(s));\n REQUIRE(read_signal(s) == 1);\n}\n\nTEST_CASE(\"lambda input signal with ID\", \"[signals]\")\n{\n auto s = lambda_input(\n always_readable, []() { return 1; }, []() { return unit_id; });\n\n typedef decltype(s) signal_t;\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(!signal_can_write<signal_t>::value);\n\n REQUIRE(signal_is_readable(s));\n REQUIRE(read_signal(s) == 1);\n REQUIRE(s.value_id() == unit_id);\n}\n\nTEST_CASE(\"lambda bidirectional signal\", \"[signals]\")\n{\n int x = 1;\n\n auto s = lambda_bidirectional(\n always_readable,\n [&x]() { return x; },\n always_writable,\n [&x](int v) { x = v; });\n\n typedef decltype(s) signal_t;\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(signal_can_write<signal_t>::value);\n\n REQUIRE(signal_is_readable(s));\n REQUIRE(read_signal(s) == 1);\n REQUIRE(signal_is_writable(s));\n captured_id original_id = s.value_id();\n write_signal(s, 0);\n REQUIRE(read_signal(s) == 0);\n REQUIRE(!original_id.matches(s.value_id()));\n}\n\nTEST_CASE(\"lambda bidirectional signal with ID\", \"[signals]\")\n{\n int x = 1;\n\n auto s = lambda_bidirectional(\n always_readable,\n [&x]() { return x; },\n always_writable,\n [&x](int v) { x = v; },\n [&x]() { return make_id(x); });\n\n typedef decltype(s) signal_t;\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(signal_can_write<signal_t>::value);\n\n REQUIRE(signal_is_readable(s));\n REQUIRE(read_signal(s) == 1);\n REQUIRE(s.value_id() == make_id(1));\n REQUIRE(signal_is_writable(s));\n write_signal(s, 0);\n REQUIRE(read_signal(s) == 0);\n REQUIRE(s.value_id() == make_id(0));\n}\n" }, { "alpha_fraction": 0.5095223784446716, "alphanum_fraction": 0.5152660012245178, "avg_line_length": 26.11475372314453, "blob_id": "580dd2c86f603c10c0c8c0c0da023ed38457f408", "content_id": "68a77efb9d731447150729590fe49121bf9692f1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6616, "license_type": "permissive", "max_line_length": 75, "num_lines": 244, "path": "/unit_tests/signals/adaptors.cpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#include <alia/signals/adaptors.hpp>\n\n#include <type_traits>\n\n#include <alia/signals/basic.hpp>\n#include <alia/signals/lambdas.hpp>\n\n#include <catch2/catch.hpp>\n\nusing namespace alia;\n\nTEST_CASE(\"fake_readability\", \"[signals]\")\n{\n {\n auto s = fake_readability(\n lambda_input([&]() { return true; }, [&]() { return 0; }));\n\n typedef decltype(s) signal_t;\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(!signal_can_write<signal_t>::value);\n\n REQUIRE(!signal_is_readable(s));\n }\n\n {\n int x = 0;\n\n auto s = fake_readability(lambda_bidirectional(\n [&]() { return true; },\n [&]() { return x; },\n [&]() { return true; },\n [&](int v) { x = v; }));\n\n typedef decltype(s) signal_t;\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(signal_can_write<signal_t>::value);\n\n REQUIRE(s.value_id() == no_id);\n REQUIRE(!signal_is_readable(s));\n REQUIRE(signal_is_writable(s));\n write_signal(s, 1);\n REQUIRE(x == 1);\n }\n}\n\nTEST_CASE(\"fake_writability\", \"[signals]\")\n{\n {\n auto s = fake_writability(\n lambda_input([&]() { return true; }, [&]() { return 0; }));\n\n typedef decltype(s) signal_t;\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(signal_can_write<signal_t>::value);\n\n REQUIRE(signal_is_readable(s));\n REQUIRE(!signal_is_writable(s));\n }\n\n {\n auto s = fake_writability(lambda_bidirectional(\n [&]() { return true; },\n [&]() { return 0; },\n [&]() { return true; },\n [&](int x) {}));\n\n typedef decltype(s) signal_t;\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(signal_can_write<signal_t>::value);\n\n REQUIRE(signal_is_readable(s));\n REQUIRE(read_signal(s) == 0);\n int x = 0;\n REQUIRE(s.value_id() == make_id_by_reference(x));\n REQUIRE(!signal_is_writable(s));\n }\n}\n\nTEST_CASE(\"signal_cast\", \"[signals]\")\n{\n int x = 1;\n auto s = signal_cast<double>(direct(x));\n\n typedef decltype(s) signal_t;\n REQUIRE((std::is_same<signal_t::value_type, double>::value));\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(signal_can_write<signal_t>::value);\n\n REQUIRE(signal_is_readable(s));\n REQUIRE(read_signal(s) == 1.0);\n REQUIRE(signal_is_writable(s));\n write_signal(s, 0.0);\n REQUIRE(x == 0);\n}\n\nTEST_CASE(\"is_readable\", \"[signals]\")\n{\n bool readable = false;\n int x = 1;\n\n {\n auto s = is_readable(\n lambda_input([&]() { return readable; }, [&]() { return x; }));\n\n typedef decltype(s) signal_t;\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(!signal_can_write<signal_t>::value);\n\n REQUIRE(signal_is_readable(s));\n REQUIRE(read_signal(s) == false);\n }\n\n readable = true;\n\n {\n // Recreate the signal to circumvent internal caching.\n auto s = is_readable(\n lambda_input([&]() { return readable; }, [&]() { return x; }));\n\n REQUIRE(signal_is_readable(s));\n REQUIRE(read_signal(s) == true);\n }\n}\n\nTEST_CASE(\"is_writable\", \"[signals]\")\n{\n bool writable = false;\n int x = 1;\n\n {\n auto s = is_writable(lambda_bidirectional(\n always_readable,\n [&]() { return x; },\n [&]() { return writable; },\n [&](int v) { x = v; }));\n\n typedef decltype(s) signal_t;\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(!signal_can_write<signal_t>::value);\n\n REQUIRE(signal_is_readable(s));\n REQUIRE(read_signal(s) == false);\n }\n\n writable = true;\n\n {\n // Recreate the signal to circumvent internal caching.\n auto s = is_writable(lambda_bidirectional(\n always_readable,\n [&]() { return x; },\n [&]() { return writable; },\n [&](int v) { x = v; }));\n\n REQUIRE(signal_is_readable(s));\n REQUIRE(read_signal(s) == true);\n }\n}\n\nTEST_CASE(\"add_fallback\", \"[signals]\")\n{\n int p = 1;\n int f = 0;\n auto make_fallback = [&](bool primary_readable,\n bool primary_writable,\n bool fallback_readable) {\n return add_fallback(\n lambda_bidirectional(\n [=]() { return primary_readable; },\n [=]() { return p; },\n [=]() { return primary_writable; },\n [&p](int x) { p = x; }),\n lambda_bidirectional(\n [=]() { return fallback_readable; },\n [=]() { return f; },\n always_writable,\n [&f](int x) { f = x; }));\n };\n\n {\n typedef decltype(make_fallback(true, true, true)) signal_t;\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(signal_can_write<signal_t>::value);\n }\n\n {\n typedef decltype(add_fallback(value(0), value(1))) signal_t;\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(!signal_can_write<signal_t>::value);\n }\n\n {\n p = 1;\n auto s = make_fallback(true, true, true);\n REQUIRE(signal_is_readable(s));\n REQUIRE(read_signal(s) == 1);\n REQUIRE(signal_is_writable(s));\n write_signal(s, 2);\n REQUIRE(p == 2);\n REQUIRE(f == 0);\n }\n\n {\n p = 1;\n auto s = make_fallback(false, true, true);\n REQUIRE(signal_is_readable(s));\n REQUIRE(read_signal(s) == 0);\n REQUIRE(signal_is_writable(s));\n write_signal(s, 2);\n REQUIRE(p == 2);\n REQUIRE(f == 0);\n }\n\n {\n p = 1;\n auto s = make_fallback(false, true, false);\n REQUIRE(!signal_is_readable(s));\n REQUIRE(signal_is_writable(s));\n write_signal(s, 2);\n REQUIRE(p == 2);\n REQUIRE(f == 0);\n }\n\n {\n p = 1;\n auto s = make_fallback(true, false, false);\n REQUIRE(signal_is_readable(s));\n REQUIRE(read_signal(s) == 1);\n REQUIRE(!signal_is_writable(s));\n }\n\n {\n // Check that the overall signal produces a different value ID when\n // using the primary vs the fallback, even when the two component\n // signals have the same value ID.\n p = 0;\n auto s = make_fallback(true, false, false);\n auto t = make_fallback(false, false, true);\n REQUIRE(signal_is_readable(s));\n REQUIRE(signal_is_readable(t));\n REQUIRE(read_signal(s) == read_signal(t));\n REQUIRE(s.value_id() != t.value_id());\n }\n}\n" }, { "alpha_fraction": 0.6639209389686584, "alphanum_fraction": 0.6672158241271973, "avg_line_length": 54.181819915771484, "blob_id": "27f250bbcbf5d5678e0427a6119f01d48b66e37d", "content_id": "e832f3127f0314a1ea5c42a0aec5c97e590f3693", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 5463, "license_type": "permissive", "max_line_length": 559, "num_lines": 99, "path": "/docs/the-basics/what-is-alia.rst", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "What is alia?\n=============\n\nThe motivation for alia is perhaps best illustrated with an example. Imagine that we are implementing a simple map application that has to display points of interest to the user. This could be implemented very simply as follows. ::\n\n void draw_map(cairo_t* cr)\n {\n // ...\n for (auto const& poi : points_of_interest)\n {\n // Draw a circle at the POI's location in the POI's color.\n cairo_set_source_rgba (cr, poi.r, poi.g, poi.b, 0.6);\n cairo_set_line_width (cr, 6.0);\n cairo_arc (cr, poi.x, poi.y, 10.0, 0, 2 * pi);\n cairo_fill (cr);\n }\n }\n\nWe'll simply call this function whenever we need to draw (or redraw) our map, and our job is done!\n\nAnd of course, we can easily refactor this. ::\n\n void draw_poi(cairo_t* cr, point_of_interest const& poi)\n {\n // Draw a circle at the POI's location in the POI's color.\n cairo_set_source_rgba (cr, poi.r, poi.g, poi.b, 0.6);\n cairo_set_line_width (cr, 6.0);\n cairo_arc (cr, poi.x, poi.y, 10.0, 0, 2 * pi);\n cairo_fill (cr);\n }\n\n void draw_map(cairo_t* cr)\n {\n // ...\n for (auto const& poi : points_of_interest)\n {\n draw_poi(cr, poi);\n }\n }\n\nWhen our application behavior can be implemented as simple function calls, this type of refactoring is easy, and it makes other types of behavior straightforward as well. ::\n\n void draw_map(cairo_t* cr)\n {\n // ...\n for (auto const& poi : points_of_interest)\n {\n // Do some filtering.\n if (poi_matches_user_interests(poi))\n draw_poi(cr, poi);\n }\n // Dynamically add some other points that aren't in the list.\n if (location_tracking_enabled())\n draw_poi(cr, get_user_location());\n draw_poi(cr, get_user_home());\n }\n\nAn important feature of this code is that calling ``draw_poi`` essentially says \"This POI is part of our map right now.\" This allows us to use familiar C++ control flow mechanisms like ``if`` and ``for`` to analyze our application state and decide which POIs to include. Our map display automatically updates according to that logic whenever the application state changes.\n\nIn other words, this simple implementation of a map display is *reactive*!\n\nNow imagine that we want the user to be able to interact with our POIs. We need to detect when the user has clicked on a POI and open a popup with information about that POI and some options for interacting with it. Suddenly, we need a richer interface to a POI than ``draw_poi`` provides, along with some hidden state behind that interface.\n\nThis of course screams \"POIs are objects!\" And while an object is clearly a good fit for these new requirements, introducing a list of such objects to our application unfortunately breaks the reactive property that we had before. For example, we can no longer use a simple ``if`` statement to decide if the user's location should be part of the map. Instead, we'll need to detect when location tracking has been enabled or disabled and add/remove the corresponding object accordingly. This is much more cumbersome and error-prone code than what we had before.\n\nThis is where alia fits in. alia is designed to allow our new interactive application to be written like this:\n\n::\n\n void do_map(app_context ctx)\n {\n // ...\n\n alia::for_each(ctx, points_of_interest,\n [&](auto poi)\n {\n alia_if (poi_matches_user_interests(poi))\n {\n do_poi(ctx, poi);\n }\n alia_end\n });\n\n alia_if (location_tracking_enabled())\n {\n do_poi(ctx, get_user_location());\n }\n alia_end\n\n do_poi(ctx, get_user_home());\n }\n\nWe've replaced ``draw_map`` with ``do_map``. Whereas ``draw_map`` was only concerned with drawing, ``do_map`` is capable of handling mouse events as well. Essentially, it defines what POIs are on the map and routes events to them (via the ``ctx`` parameter).\n\nSomewhere inside ``do_poi``, you'd find code that detects what event is being processed and either draws the POI or does some mouse logic. Importantly, each call to ``do_poi`` can also store arbitrary data within ``ctx``, which allows it to maintain state about the user interaction or manage its own widgets. All of this is invisible to ``do_map``. (Except that ``do_map`` must be written with special forms of ``if`` and ``for``, which allow alia's data magic to work.)\n\nEffectively, each call to ``do_poi`` has the capabilities of a normal C++ object: it can respond to multiple types of events, and it can maintain arbitrary internal state. However, unlike normal C++ objects, we don't have to explicitly create and destroy calls to ``do_poi``. Whatever calls are encountered during a call to ``do_map`` uniquely specify the set of POIs that are present in the map. ``do_map`` is *reactive*!\n\nSo, alia is a library that allows you to write C++ application code reactively, even when your application's functionality requires the power of objects, and even when you want to utilize one or more libraries with an object-oriented interface. The core of alia supplies the mechanics to make the above style of programming possible, and it's intended to make the development of bindings to other libraries fairly straightforward.\n" }, { "alpha_fraction": 0.7486355900764465, "alphanum_fraction": 0.7508396506309509, "avg_line_length": 35.09090805053711, "blob_id": "d4ae187bd088831e285db98d6816cf7047061ba0", "content_id": "827ee272b9a047fb4761d565b51c4b6d6d0ad19e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 9528, "license_type": "permissive", "max_line_length": 428, "num_lines": 264, "path": "/docs/developer/goals-and-rationales.rst", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "Goals and Rationales\n====================\n\nSignals\n-------\n\nThe goals of the signals component are as follows.\n\n* Unify the interface to C-style data structures and OOP-style classes (whose data members may be protected behind accessor functions).\n* Provide standard mechanisms for transforming a back end's view of model state or applying constraints to its manipulations of that state.\n* Provide mechanisms for efficiently detecting changes in signal values. (e.g., It should be possible to poll a signal carrying a large body of text and detect if it has changed since the last poll without examining the entire text.)\n* The 'direction' of signals (i.e., input/output/bidirectional) should be explicitly denoted in both the capabilities that a signal implementation provides and the requirements of a function that accepts a signal as a parameter.\n* A function that expects an input signal should be able to accept a bidirectional signal without requiring the function to do any template shenanigans. (More specifically, a function that accepts a signal should only have to declare the required direction and the value type of the signal. If both of those are concrete, the function shouldn't need to use templates to accept that signal.)\n* Allow signal wrappers to be agnostic of the signal's direction. (e.g., If I want to implement a wrapper that presents a view of a signal where the value is 10x as large, I should have to define what that means for reading and writing the signal, but I shouldn't have to write three different versions in order to preserve the direction of the wrapped signal.)\n* Ensure that the passing of signal values across functions is as efficient and lazy as possible. (i.e., Avoid unnecessary memory allocations and computations of unused values.)\n\nIMGUI-Style vs Reactive-Style\n-----------------------------\n\nHow do we strike a balance between supporting IMGUI style and reactive style?\n\nIMGUI Style\n:::::::::::\n\nThe application iterates over the entire UI each frame/pass, (re)calculating everything that's relevant to the current snapshot and rendering/emitting it.\n\nReactive Style\n::::::::::::::\n\nThe application builds a dataflow / object graph with individual callbacks that are invoked when needed to propogate changes.\n\nResolution\n::::::::::\n\nJust like in alia v2, events don't need to traverse the full content/object graph. Instead, they can be routed to specific nodes. This behavior depends on the event itself.\n\nSubgraphs can also skip the refresh event with proper support from the adaptor libraries.\n\nFunctions can be explicitly 'invoked', which handles skipping/routing.\n\n\n\nTerminology\n-----------\n\nThere needs to be consistent terminology (which is ideally independent of user interfaces) for referring to whatever is actually getting generated by the controller.\n\nOptions\n:::::::\n\n* 'nodes'\n* 'content'\n* 'objects'\n\n* 'specify'\n* 'emit'\n* 'generate'\n* 'do'\n\nResolution\n::::::::::\n\n'content graph', 'content node', 'nodes in the content graph', 'content graph traversal', etc.\n\n'do'/'emit'?\n\nValidation\n----------\n\nWhat facilities should alia provide for doing input validation?\n\nResolution\n::::::::::\n\nIt should (obviously) not provide anything specific to display of error mssages.\n\nThe validation_error is probably worth keeping. For now, that's probably all that's worth deciding.\n\n\n\nSignals and Requests\n--------------------\n\nThe background request system in alia/cradle v2 seems to conflate multiple concerns:\n\n- Some signal values should be computed in the background.\n- Some signal values are accessed from multiple places within the UI and should be shared across those places.\n- Some signal values are worth caching in memory or on disk.\n\nCan these be addressed independently? How?\n\nBackground Execution\n::::::::::::::::::::\n\nAll this really implies is that a function should be executed in a separate thread from the controller.\n\n::\n x = alia::async(ctx, fib, value(43));\n\nJust like ``std::async``, this returns immediately, but x doesn't yield a value until fib() returns.\n\nalia::async(ctx, f, args) does the following:\n\n- Grab some local data.\n- Check if its stored key matches the merged key for :args.\n\t- If not:\n\t\t- Tell the old job (if any) to cancel and discard it.\n\t\t- Reset to the new key and discard the output value (if any).\n- Check if it has the output value.\n\t- If not:\n\t\t- Check if it already has a job disptached.\n\t\t\t- If not:\n\t\t\t\t- Check if all the args are gettable.\n\t\t\t\t\t- If so:\n\t\t\t\t\t\t- Dispatch a job to run the function.\n\t\t\t\t\t\t\t- This should include a wrapper to handle cancellation.\n\t\t\t\t\t\t\t https://stackoverflow.com/questions/12086622/is-there-a-way-to-cancel-detach-a-future-in-c11\n\t\t\t\t\t\t\t- Some indirection should be provided to allow different dispatchers (std::async, thread pooler, etc.)\n\t\t\t\t\t\t\t https://github.com/vit-vit/CTPL\n\t \t- Check if the job has produced a value (and if so, grab it).\n\nShared Access\n:::::::::::::\n\nThe main issue here is that the ID used to identify the signal value would need to be globally unique, whereas normal signal values only have to be unique for the location in the data graph at which they're used.\n\nThis can actually just be treated as a separate concern. A library like CRADLE can be implemented entirely separate from alia and interfaces to it through something like the above async function.\n\nCaching\n:::::::\n\nThis is basically the same story as shared access.\n\nResolution\n::::::::::\n\nImplement the async function described above and forget about shared access and caching for now.\n\n\n\nState Persistence\n-----------------\n\nIs there a generic mechanism by which 'magic'/local state could be persisted at a higher/global level (e.g., as part of a YAML data structure)?\n\nNotes\n:::::\n\nThe main requirement that this imposes is the ability to construct a path to arbitrary state (e.g., 'cart/items/0/product_id'). This is also useful for debugging tools.\n\nResolution\n::::::::::\n\n...\n\n\n\nRefresh Passes\n--------------\n\nThe Issue\n:::::::::\n\nShould alia v3 follow v2's convention of assuming that state doesn't change except on refresh passes?\n\nAdvantages\n::::::::::\n\nDepending on the interface, this could cause the interface to behave as if it is lagged w.r.t. the state. (It's possible that a widget will want to handle events before all properties can be set.)\n\nDisadvantages\n:::::::::::::\n\nThis causes issues for newbies and could impose burdensome constraints in some use cases. It also might adversely affect performance in cases where the app ends up having to issue refresh passes just to pick up changes (since those are global, whereas it was only trying to issue a targeted event).\n\nResolution\n::::::::::\n\nKeep the assumption. Maybe add an option to send refresh passes before every event.\n\n\nDebugging\n---------\n\nWhat tools should alia provide for debugging? How should these work? What requirements do they impose on the application?\n\nResolution\n::::::::::\n\nIt seems pretty reasonable that an alia app should be able to provide signal values and event logs via a local REST or websockets API.\n\nA GUI / web interface could be layered on top of this API.\n\nMore insight could be gained by parsing the C++ files:\n\nhttps://github.com/foonathan/cppast\n\nThis imposes some constraints on the types used for events and signals (e.g., streamability), but this would be an optional feature and features like those used in Boost.Exception could be used to stream various types as possible.\n\n\n\n# ORGANIZATION\n\n* The Issue\n\nHow is the project structured? Are library 'adaptors' part of the same repository/project as the core? If not, how do we guarantee that everything works together? If so, how do we avoid the project's scope getting out of control?\n\n* Resolution\n\nStart out with everything as a single repository/project and worry about this later.\n\n\n\n# DISTRIBUTION\n\n* The Issue\n\nHow does the typical developer get and use alia? (Assuming the developer isn't using a package manager.)\n\n* Resolution\n\nUsage is through header files. The core only requires C++11. Other components are split up based on which libraries they connect to (e.g., <alia/qt.hpp> provides an adaptor for Qt support). Optional libraries are enable with #defines. All of these are header-only and the implementation is only defined when ALIA_IMPLEMENTATION is #define'd. In all cases, the developer is responsible for making third-party libraries available.\n\nThese header files are built from multiple source files and distributed via GitHub releases.\n\n\n\n# CULLING\n\n* The Issue\n\nShould we support having the controller cull the scene directly? (The alternative is having the controller specify the entire scene and culling downstream.)\n\n* Pros\n\n- Should improve performance.\n\n* Cons\n\n- Might complicate interfaces.\n\n* Resolution\n\nFor now, this isn't explicitly addressed. Culling in general is possible, and the mechanisms should exist for individual adaptors to do it.\n\n\n\n# PIPELINING\n\n* The Issue\n\nShould the controller be able to reactively process its own output?\n\n* Pros\n\n- This would allow some interesting staged processing of content (e.g., transition effects).\n\n* Cons\n\n- This could add some overhead compared with just creating objects directly.\n\n* Resolution\n\nThis is left up to the designer of the library adaptor that is receiving the objects. Ultimately, the controller 'emits' something, and the adpator provides an API for doing so. The API can be in whatever form the designer likes, and can include methods to insert filters/preprocessors. (This is a simple matter of providing a level of indirection.)\n" }, { "alpha_fraction": 0.6654182076454163, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 17.627906799316406, "blob_id": "4ffd6f591bcc8f34d88609e598b66d6cdcee39e5", "content_id": "4d38e5899ca0e2778107d2fae64dc8a4e2213d12", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 801, "license_type": "permissive", "max_line_length": 68, "num_lines": 43, "path": "/compilation_tests/invalid_component_access.cpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#include <alia/component_collection.hpp>\n\n#include <boost/any.hpp>\n\nusing namespace alia;\n\nstruct foo_tag\n{\n};\nstruct foo\n{\n bool b = false;\n};\nstruct bar_tag\n{\n};\nstruct bar\n{\n int i = 0;\n};\n\nusing storage_type = generic_component_storage<boost::any>;\nusing cc_empty = empty_component_collection<storage_type>;\n\nvoid\nf()\n{\n storage_type storage_empty;\n cc_empty mc_empty(&storage_empty);\n\n storage_type storage_b;\n auto mc_b = add_component<bar_tag>(&storage_b, mc_empty, bar());\n\n storage_type storage_fb;\n auto mc_fb = add_component<foo_tag>(&storage_fb, mc_b, foo());\n\n storage_type storage_f;\n auto mc_f = remove_component<bar_tag>(&storage_f, mc_fb);\n get_component<foo_tag>(mc_f);\n#ifdef ALIA_TEST_COMPILATION_FAILURE\n get_component<bar_tag>(mc_f);\n#endif\n}\n" }, { "alpha_fraction": 0.674452543258667, "alphanum_fraction": 0.6802919507026672, "avg_line_length": 15.707317352294922, "blob_id": "4e9eaab66494a8d815c408e0481bcce27d588413", "content_id": "50f71fc4ec8fd3bbf47af451b4350681a98b8262", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 685, "license_type": "permissive", "max_line_length": 35, "num_lines": 41, "path": "/docs/index.rst", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "alia\n====\n\n.. toctree::\n :maxdepth: 2\n :hidden:\n :caption: The Basics\n\n the-basics/what-is-alia\n the-basics/getting-started\n the-basics/introductory-examples\n the-basics/signals\n the-basics/control-flow\n\n.. toctree::\n :maxdepth: 2\n :hidden:\n :caption: In-Depth Guides\n\n in-depth/signals\n in-depth/loops-and-conditionals\n in-depth/events\n in-depth/configuration\n in-depth/best-practices\n\n.. toctree::\n :maxdepth: 2\n :hidden:\n :caption: Developer Guides\n\n developer/building-and-testing\n developer/goals-and-rationales\n\n.. toctree::\n :maxdepth: 2\n :hidden:\n :caption: Outdated Tutorial\n\n introduction\n state-management\n control-flow\n" }, { "alpha_fraction": 0.706209123134613, "alphanum_fraction": 0.7067028880119324, "avg_line_length": 50.272151947021484, "blob_id": "58a0c75e9eadb5826698769b7838665208f138eb", "content_id": "a95bedfa62ea332b1320bfe58cd0ecb4b66754cd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 8101, "license_type": "permissive", "max_line_length": 606, "num_lines": 158, "path": "/docs/introduction.rst", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "Introduction\n============\n\nalia is an IMGUI library, a GUI library with an immediate mode API. In traditional (retained mode) GUI libraries, the library stores a hierarchy of widget objects that represent the current on-screen GUI. The structure of the GUI remains static unless the application explicitly alters the hierarchy of objects by adding new objects, removing old objects, or updating existing objects. Manually managing widget objects like this is a burden on the application programmer, and it often discourages the creation of highly dynamic UIs.\n\nIMGUI is designed for dynamic UIs. There is no implicit assumption that the UI remains static from frame to frame. Instead of supplying a static description of the UI, the application supplies the library with a function that dynamically defines the UI. Whenever the UI needs to be updated, the library calls this function to produce a fresh UI specification. The function can take into account dynamic application state to produce different UIs as the state changes.\n\nAnother way of saying this is that alia is a reactive GUI library.\n\nThis section is designed to introduce you to alia's way of thinking. The following examples will guide you through how some familiar UI concepts look in immediate mode. Note that the examples in this section are intentionally simple and unrealistic. More realistic examples will be presented in later sections.\n\nHello World\n-----------\n\nThe following is a UI function that produces a simple UI with a single string of text. ::\n\n void do_ui(context& ctx)\n {\n do_text(ctx, \"hello, world!\");\n }\n\nThere is no state associated with this UI, so the function produces the same UI every time it's called (i.e., this UI is entirely static). For cases like this, there isn't much difference between the IMGUI approach and the traditional approach, but it's important to remember that the call to do_text() isn't creating a text widget. Instead, it's specifying, each frame, that there is a text widget in the UI with the value \"hello, world!\".\n\nEvent Handling\n--------------\n\nA common first example in GUI libraries is a button that changes the value of a text display, so let's see how that looks in alia... ::\n\n std::string text = \"push the button!\";\n \n void do_ui(context& ctx)\n {\n do_text(ctx, text);\n if (do_button(ctx, \"push me\"))\n text = \"thanks!\";\n }\n\nThe do_button function returns true when it's pressed, which allows you to write the event handler in the same place that you specify the widget. In alia, all code related to a widget is typically localized to one single block, not spread out over creation functions, updates, callbacks, etc. Another benefit of this approach is that the event handler has access to the stack frame of the UI specification function, which is important in more complex UIs.\n\nAlso notice that the text display doesn't have some internal label property that we change. In an IMGUI, widgets don't store their values internally. Instead, their values are passed into them each frame by the UI function. This allows their values to change in a programmatic way. In this case, the text widget always displays the current value of the variable 'text', which changes when the button is pressed.\n\nControls\n--------\n\n::\n\n bool checked = false;\n \n void do_ui(context& ctx)\n {\n do_check_box(ctx, inout(&checked), \"check me\");\n do_text(ctx, checked ? \"thanks\" : \"please\");\n }\n\nA check box is an example of a control, a widget that manipulates a value (a boolean in this case). Like the text display, the check box doesn't have an internal value to manipulate. Instead, the UI function provides it with a reference to one. In this way, the check box can directly manipulate variables in the application. As before, we can change the value of 'checked' from within the application and the results will be immediately reflected in the UI. Similarly, we can use the value of 'checked' as a conditional in the specification of other parts of the UI, like the text display in this example.\n\nThe ``inout(&checked)`` syntax specifies that the check box will read its value from the variable ``checked`` and also write back any changes to that same variable. There are other ways of getting values in and out of controls in alia that will be explained later, but for now we'll focus on this simple method.\n\nSynchronized Control\n--------------------\n\nBecause controls manipulate variables in the application, synchronizing multiple controls is trivial in an IMGUI system. The following example shows a slider and a text control that both manipulate the same variable. Changing one changes the other.\n\n::\n\n int n;\n\n void do_ui(context& ctx)\n {\n do_slider(ctx, inout(&n), 0, 100);\n do_text_control(ctx, inout(&n));\n }\n\nComputed Values\n---------------\n\nSimilarly, it's trivial to display values that are computed dynamically from user inputs. For example, the following UI features two numeric inputs and a text display that shows their sum. ::\n\n int x, y;\n \n void do_ui(context& ctx)\n {\n do_text_control(ctx, inout(&x));\n do_text_control(ctx, inout(&y));\n do_text(ctx, x + y);\n }\n\nConditional Widgets\n-------------------\n\nThe true power of IMGUI really shows in GUIs where parts of the UI are added or removed depending on the state of the program. The following UI has a check box and a text display that's only present when the box is checked. ::\n\n bool checked = false;\n\n void do_ui(context& ctx)\n {\n do_check_box(ctx, inout(&checked), \"show text\");\n alia_if (checked)\n {\n do_text(ctx, \"hello\");\n }\n alia_end\n }\n\nThe ``alia_if`` macro behaves exactly like a normal if statement, but it does some magic behind the scenes to make alia's data management work. This is discussed in more detail in the Control Flow section.\n\nWidget Lists\n------------\n\nYou can even use loops to specify repeating sections of UI. This is especially useful when you have a list in your application and you want to provide a UI for each item in the list. ::\n\n struct contact\n {\n std::string name;\n std::string phone;\n };\n\n std::list<contact> contacts;\n\n void do_ui(context& ctx)\n {\n alia_for(std::list<contact>::iterator i = contacts.begin();\n i != contacts.end(); ++i)\n {\n do_text_control(ctx, inout(&i->name));\n do_text_control(ctx, inout(&i->phone));\n do_separator(ctx);\n }\n alia_end\n if (do_button(ctx, \"add contact\"))\n contacts.push_back(contact());\n }\n\nComposition and Abstraction\n---------------------------\n\nAs you've seen, alia widgets are functions, and even the entire application UI is represented as a function. It should come as no surprise that arbitrary subsections of the UI can also be represented as functions. The correspondence between functions and UI components means we can use the natural composition and abstraction mechanisms of functions to build up and break down the structure of the UI. As a simple example, the do_ui() function from the last example could be refactored as follows. ::\n\n void do_contact_ui(context& ctx, contact& c)\n {\n do_text_control(ctx, inout(&c.name));\n do_text_control(ctx, inout(&c.phone));\n do_separator(ctx);\n }\n\n void do_ui(context& ctx)\n {\n alia_for (std::list<contact>::iterator i = contacts.begin();\n i != contacts.end(); ++i)\n {\n do_contact_ui(ctx, *i);\n }\n alia_end\n if (do_button(ctx, \"add contact\"))\n contacts.push_back(contact());\n }\n\nThe advantage of using functions rather than objects to represent UI components is that we don't need to create and destroy object instances. Instead, we just call the functions for whichever UI components we want for that frame. Of course, objects have associated state, and you might be thinking we've lost that by using functions instead, but as you'll see the the next section, that's not the case.\n" }, { "alpha_fraction": 0.6650717854499817, "alphanum_fraction": 0.6746411323547363, "avg_line_length": 12.0625, "blob_id": "dba56f9ba3d10a6efa8110c0902ca6f3717807f5", "content_id": "c5a754f5b546d6f807d801be307d3abf27357a76", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 209, "license_type": "permissive", "max_line_length": 36, "num_lines": 16, "path": "/compilation_tests/strict_conditionals.cpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#ifdef ALIA_TEST_COMPILATION_FAILURE\n#define ALIA_STRICT_CONDITIONALS\n#endif\n\n#include <alia/data_graph.hpp>\n\nusing namespace alia;\n\nvoid\nf(data_traversal& ctx)\n{\n ALIA_IF(1 > 0)\n {\n }\n ALIA_END\n}\n" }, { "alpha_fraction": 0.5415306687355042, "alphanum_fraction": 0.5544069409370422, "avg_line_length": 25.509614944458008, "blob_id": "45407937f3f838db8d6ba9624f3f6770ea59b2bd", "content_id": "ca5ffc8fe7b6aa995f2b569bf84fde938ec0a4db", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5514, "license_type": "permissive", "max_line_length": 77, "num_lines": 208, "path": "/unit_tests/signals/application.cpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#define ALIA_LOWERCASE_MACROS\n\n#include <alia/signals/application.hpp>\n\n#include <catch2/catch.hpp>\n\n#include <alia/signals/basic.hpp>\n\nusing namespace alia;\n\nTEST_CASE(\"lazy_apply\", \"[signals]\")\n{\n auto s1 = lazy_apply([](int i) { return 2 * i; }, value(1));\n\n typedef decltype(s1) signal_t1;\n REQUIRE(signal_can_read<signal_t1>::value);\n REQUIRE(!signal_can_write<signal_t1>::value);\n\n REQUIRE(signal_is_readable(s1));\n REQUIRE(read_signal(s1) == 2);\n\n auto s2\n = lazy_apply([](int i, int j) { return i + j; }, value(1), value(6));\n\n typedef decltype(s2) signal_t2;\n REQUIRE(signal_can_read<signal_t2>::value);\n REQUIRE(!signal_can_write<signal_t2>::value);\n\n REQUIRE(signal_is_readable(s2));\n REQUIRE(read_signal(s2) == 7);\n REQUIRE(s1.value_id() != s2.value_id());\n\n // Create some similar signals to make sure that they produce different\n // value IDs.\n auto s3\n = lazy_apply([](int i, int j) { return i + j; }, value(2), value(6));\n auto s4\n = lazy_apply([](int i, int j) { return i + j; }, value(1), value(0));\n REQUIRE(s2.value_id() != s3.value_id());\n REQUIRE(s2.value_id() != s4.value_id());\n REQUIRE(s3.value_id() != s4.value_id());\n}\n\nTEST_CASE(\"lazy_lift\", \"[signals]\")\n{\n auto s = lazy_lift([](int i) { return 2 * i; })(value(1));\n\n typedef decltype(s) signal_t;\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(!signal_can_write<signal_t>::value);\n\n REQUIRE(signal_is_readable(s));\n REQUIRE(read_signal(s) == 2);\n}\n\ntemplate<class Controller>\nvoid\ndo_traversal(\n data_graph& graph, Controller const& controller, bool refresh = true)\n{\n data_traversal traversal;\n scoped_data_traversal sdt(graph, traversal);\n if (!refresh)\n disable_gc(traversal);\n\n component_storage storage;\n add_component<data_traversal_tag>(storage, &traversal);\n\n context ctx(&storage);\n controller(ctx);\n}\n\nTEST_CASE(\"simple apply\", \"[signals]\")\n{\n int f_call_count = 0;\n auto f = [&](int x, int y) {\n ++f_call_count;\n return x * 2 + y;\n };\n\n captured_id signal_id;\n\n data_graph graph;\n auto make_controller = [&](int x, int y) {\n return [=, &signal_id](context ctx) {\n auto s = apply(ctx, f, value(x), value(y));\n\n typedef decltype(s) signal_t;\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(!signal_can_write<signal_t>::value);\n\n REQUIRE(signal_is_readable(s));\n REQUIRE(read_signal(s) == x * 2 + y);\n\n signal_id.capture(s.value_id());\n };\n };\n\n do_traversal(graph, make_controller(1, 2));\n REQUIRE(f_call_count == 1);\n captured_id last_id = signal_id;\n\n do_traversal(graph, make_controller(1, 2));\n REQUIRE(f_call_count == 1);\n REQUIRE(last_id == signal_id);\n last_id = signal_id;\n\n do_traversal(graph, make_controller(2, 2));\n REQUIRE(f_call_count == 2);\n REQUIRE(last_id != signal_id);\n last_id = signal_id;\n\n do_traversal(graph, make_controller(2, 2));\n REQUIRE(f_call_count == 2);\n REQUIRE(last_id == signal_id);\n last_id = signal_id;\n\n do_traversal(graph, make_controller(2, 3));\n REQUIRE(f_call_count == 3);\n REQUIRE(last_id != signal_id);\n}\n\nTEST_CASE(\"unready apply\", \"[signals]\")\n{\n int f_call_count = 0;\n auto f = [&](int x, int y) {\n ++f_call_count;\n return x * 2 + y;\n };\n\n {\n data_graph graph;\n auto make_controller = [=](auto x, auto y) {\n return [=](context ctx) {\n auto s = apply(ctx, f, x, y);\n\n typedef decltype(s) signal_t;\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(!signal_can_write<signal_t>::value);\n\n REQUIRE(!signal_is_readable(s));\n };\n };\n\n do_traversal(graph, make_controller(empty<int>(), value(2)));\n REQUIRE(f_call_count == 0);\n\n do_traversal(graph, make_controller(value(1), empty<int>()));\n REQUIRE(f_call_count == 0);\n }\n}\n\nTEST_CASE(\"failed apply\", \"[signals]\")\n{\n auto f = [&](int x, int y) -> int { throw \"failed\"; };\n\n {\n data_graph graph;\n auto make_controller = [=](auto x, auto y) {\n return [=](context ctx) {\n auto s = apply(ctx, f, x, y);\n\n typedef decltype(s) signal_t;\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(!signal_can_write<signal_t>::value);\n\n REQUIRE(!signal_is_readable(s));\n };\n };\n\n do_traversal(graph, make_controller(value(1), value(2)));\n }\n}\n\nTEST_CASE(\"lift\", \"[signals]\")\n{\n int f_call_count = 0;\n auto f = [&](int x) {\n ++f_call_count;\n return x + 1;\n };\n\n {\n data_graph graph;\n auto controller = [=](context ctx) {\n auto f_lifted = lift(ctx, f);\n auto s = f_lifted(value(0));\n\n typedef decltype(s) signal_t;\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(!signal_can_write<signal_t>::value);\n\n REQUIRE(signal_is_readable(s));\n REQUIRE(read_signal(s) == 1);\n };\n\n do_traversal(graph, controller);\n REQUIRE(f_call_count == 1);\n }\n}\n\nTEST_CASE(\"alia_method\", \"[signals]\")\n{\n auto v = value(\"test text\");\n REQUIRE(read_signal(lazy_apply(ALIA_METHOD(length), v)) == 9);\n REQUIRE(\n read_signal(lazy_apply(alia_method(substr), v, value(5))) == \"text\");\n}\n" }, { "alpha_fraction": 0.7346437573432922, "alphanum_fraction": 0.7493857741355896, "avg_line_length": 36, "blob_id": "3c3a5f844042e5e4e412001171105a9d7887277a", "content_id": "2e5a7c0b9bd0c59b8acf0d73ebeb1516b45868e2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 407, "license_type": "permissive", "max_line_length": 103, "num_lines": 11, "path": "/scripts/set-up-system.sh", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# Set up a fresh Ubuntu installation so that it can build alia.\n# This should be run with sudo.\necho \"Setting up system...\"\nset -x -e\napt-get update -qy\napt-get install -y software-properties-common\nadd-apt-repository -y ppa:ubuntu-toolchain-r/test\napt-get update -qy\napt-get install -y --upgrade --allow-unauthenticated g++-5 gcc-5 lcov cmake git curl clang-4.0 llvm-4.0\npip install virtualenv\n" }, { "alpha_fraction": 0.6914318203926086, "alphanum_fraction": 0.6931397914886475, "avg_line_length": 23.56643295288086, "blob_id": "64822c8d1196b03bcbdbe42f0fb1cd6e96b64302", "content_id": "817283d7bba04b59e4c07b28cfe42588ef8eceaa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3513, "license_type": "permissive", "max_line_length": 80, "num_lines": 143, "path": "/src/alia/events.hpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#ifndef ALIA_EVENTS_HPP\n#define ALIA_EVENTS_HPP\n\n#include <alia/context.hpp>\n#include <alia/data_graph.hpp>\n\n// This file implements utilities for routing events through an alia content\n// traversal function.\n//\n// In alia, the application defines the contents of the scene dynamically by\n// iterating through the current objects in the scene and calling a\n// library-provided function to specify the existence of each of them.\n//\n// This traversal function serves as a way to dispatch and handle events.\n// However, in cases where the event only needs to go to a single object in the\n// scene, the overhead of having the traversal function visit every other object\n// can be problematic. The overhead can be reduced by having the traversal\n// function skip over subregions of the scene when they're not relevant to the\n// event.\n//\n// This file provides a system for defining a hierarchy of such subregions in\n// the scene, identifying which subregion an event is targeted at, and culling\n// out irrelevant subregions.\n\nnamespace alia {\n\nstruct system;\nstruct routing_region;\n\ntypedef std::shared_ptr<routing_region> routing_region_ptr;\n\nstruct routing_region\n{\n routing_region_ptr parent;\n};\n\nstruct event_routing_path\n{\n routing_region* node;\n event_routing_path* rest;\n};\n\nstruct event_traversal\n{\n routing_region_ptr* active_region;\n bool targeted;\n event_routing_path* path_to_target;\n std::type_info const* event_type;\n void* event;\n};\n\ninline routing_region_ptr\nget_active_routing_region(context ctx)\n{\n event_traversal& traversal = get_event_traversal(ctx);\n return traversal.active_region ? *traversal.active_region\n : routing_region_ptr();\n}\n\n// Set up the event traversal so that it will route the control flow to the\n// given target. (And also invoke the traversal.)\n// :target can be null, in which case no (further) routing will be done.\nvoid\nroute_event(system& sys, event_traversal& traversal, routing_region* target);\n\ntemplate<class Event>\nvoid\ndispatch_targeted_event(\n system& sys, Event& event, routing_region_ptr const& target)\n{\n event_traversal traversal;\n traversal.active_region = 0;\n traversal.targeted = true;\n traversal.path_to_target = 0;\n traversal.event_type = &typeid(Event);\n traversal.event = &event;\n route_event(sys, traversal, target.get());\n}\n\ntemplate<class Event>\nvoid\ndispatch_event(system& sys, Event& event)\n{\n event_traversal traversal;\n traversal.active_region = 0;\n traversal.targeted = false;\n traversal.path_to_target = 0;\n traversal.event_type = &typeid(Event);\n traversal.event = &event;\n route_event(sys, traversal, 0);\n}\n\nstruct scoped_routing_region\n{\n scoped_routing_region() : traversal_(0)\n {\n }\n scoped_routing_region(context ctx)\n {\n begin(ctx);\n }\n ~scoped_routing_region()\n {\n end();\n }\n\n void\n begin(context ctx);\n\n void\n end();\n\n bool\n is_relevant() const\n {\n return is_relevant_;\n }\n\n private:\n event_traversal* traversal_;\n routing_region_ptr* parent_;\n bool is_relevant_;\n};\n\nbool\ndetect_event(context ctx, std::type_info const& type);\n\ntemplate<class Event>\nbool\ndetect_event(context ctx, Event** event)\n{\n event_traversal& traversal = get_event_traversal(ctx);\n if (*traversal.event_type == typeid(Event))\n {\n *event = reinterpret_cast<Event*>(traversal.event);\n return true;\n }\n return false;\n}\n\n} // namespace alia\n\n#endif\n" }, { "alpha_fraction": 0.7083333134651184, "alphanum_fraction": 0.7083333134651184, "avg_line_length": 12.894737243652344, "blob_id": "b1971d86413431b5119d350bf0e17384d03c6b07", "content_id": "30fac638983ccf7668f8a8cbffe2575d0f90fecc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 264, "license_type": "permissive", "max_line_length": 44, "num_lines": 19, "path": "/src/alia/system.hpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#ifndef ALIA_SYSTEM_HPP\n#define ALIA_SYSTEM_HPP\n\n#include <functional>\n\n#include <alia/context.hpp>\n#include <alia/data_graph.hpp>\n\nnamespace alia {\n\nstruct system\n{\n data_graph data;\n std::function<void(context)> controller;\n};\n\n} // namespace alia\n\n#endif\n" }, { "alpha_fraction": 0.6249285340309143, "alphanum_fraction": 0.6249285340309143, "avg_line_length": 18.0108699798584, "blob_id": "b4278073dc2ff0ee625a5616660003ffcdc767bc", "content_id": "e2b4d78fa82be263ac45385537846990f2621485", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3498, "license_type": "permissive", "max_line_length": 78, "num_lines": 184, "path": "/src/alia/signals/basic.hpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#ifndef ALIA_SIGNALS_BASIC_HPP\n#define ALIA_SIGNALS_BASIC_HPP\n\n#include <alia/signals/core.hpp>\n#include <alia/signals/utilities.hpp>\n\n// This file defines various utilities for constructing basic signals.\n\nnamespace alia {\n\n// empty<Value>() gives a signal that never has a value.\ntemplate<class Value>\nstruct empty_signal : signal<empty_signal<Value>, Value, bidirectional_signal>\n{\n empty_signal()\n {\n }\n id_interface const&\n value_id() const\n {\n return no_id;\n }\n bool\n is_readable() const\n {\n return false;\n }\n // Since this is never readable, read() should never be called.\n // LCOV_EXCL_START\n Value const&\n read() const\n {\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wnull-dereference\"\n#endif\n return *(Value const*) nullptr;\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n }\n // LCOV_EXCL_STOP\n bool\n is_writable() const\n {\n return false;\n }\n // Since this is never writable, write() should never be called.\n // LCOV_EXCL_START\n void\n write(Value const& value) const\n {\n }\n // LCOV_EXCL_STOP\n};\ntemplate<class Value>\nempty_signal<Value>\nempty()\n{\n return empty_signal<Value>();\n}\n\n// value(v) creates a read-only signal that carries the value v.\ntemplate<class Value>\nstruct value_signal\n : regular_signal<value_signal<Value>, Value, read_only_signal>\n{\n explicit value_signal(Value const& v) : v_(v)\n {\n }\n bool\n is_readable() const\n {\n return true;\n }\n Value const&\n read() const\n {\n return v_;\n }\n\n private:\n Value v_;\n};\ntemplate<class Value>\nvalue_signal<Value>\nvalue(Value const& v)\n{\n return value_signal<Value>(v);\n}\n\n// This is a special overload of value() for C-style string literals.\nstruct string_literal_signal\n : signal<string_literal_signal, std::string, read_only_signal>\n{\n string_literal_signal(char const* x) : text_(x)\n {\n }\n id_interface const&\n value_id() const\n {\n return unit_id;\n }\n bool\n is_readable() const\n {\n return true;\n }\n std::string const&\n read() const\n {\n return lazy_reader_.read([&] { return std::string(text_); });\n }\n\n private:\n char const* text_;\n lazy_reader<std::string> lazy_reader_;\n};\ninline string_literal_signal\nvalue(char const* text)\n{\n return string_literal_signal(text);\n}\n\n// literal operators\nnamespace literals {\ninline value_signal<unsigned long long int>\noperator\"\" _a(unsigned long long int n)\n{\n return value(n);\n}\ninline value_signal<long double> operator\"\" _a(long double n)\n{\n return value(n);\n}\ninline string_literal_signal operator\"\" _a(char const* s, size_t n)\n{\n return string_literal_signal(s);\n}\n} // namespace literals\n\n// direct(x) creates a bidirectional signal that directly exposes the value of\n// x.\ntemplate<class Value>\nstruct direct_signal\n : regular_signal<direct_signal<Value>, Value, bidirectional_signal>\n{\n explicit direct_signal(Value* v) : v_(v)\n {\n }\n bool\n is_readable() const\n {\n return true;\n }\n Value const&\n read() const\n {\n return *v_;\n }\n bool\n is_writable() const\n {\n return true;\n }\n void\n write(Value const& value) const\n {\n *v_ = value;\n }\n\n private:\n Value* v_;\n};\ntemplate<class Value>\ndirect_signal<Value>\ndirect(Value& x)\n{\n return direct_signal<Value>(&x);\n}\n\n} // namespace alia\n\n#endif\n" }, { "alpha_fraction": 0.725978672504425, "alphanum_fraction": 0.725978672504425, "avg_line_length": 20.615385055541992, "blob_id": "4be9b0625d72618a1959ea4f0567f6975aa567bc", "content_id": "5a06ebfe54c1590fa27db363e10a864639ad099d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 281, "license_type": "permissive", "max_line_length": 79, "num_lines": 13, "path": "/compilation_tests/read_write_intersection.cpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#include <alia/signals.hpp>\n\nusing namespace alia;\n\nvoid\nf()\n{\n signal_direction_intersection<read_only_signal, bidirectional_signal>::\n type();\n#ifdef ALIA_TEST_COMPILATION_FAILURE\n signal_direction_intersection<read_only_signal, write_only_signal>::type();\n#endif\n}\n" }, { "alpha_fraction": 0.5838926434516907, "alphanum_fraction": 0.5838926434516907, "avg_line_length": 13.190476417541504, "blob_id": "378ed864b813f72d1d611af0e36b0ee1cddd3fc5", "content_id": "4c9d082e226b3e9d4e22e99428338f001b391532", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 298, "license_type": "permissive", "max_line_length": 81, "num_lines": 21, "path": "/docs/the-basics/signals.rst", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "Signals\n=======\n\nIntroduction\n------------\n\n.. todo: Introduce signals. Explain how they're different from normal C++ values.\n\n.. todo: Point out signals from introductory examples.\n\nConstructors\n------------\n\nOperators\n---------\n\nApplying Functions\n------------------\n\nAs Parameters\n-------------\n" }, { "alpha_fraction": 0.7394891381263733, "alphanum_fraction": 0.7397872805595398, "avg_line_length": 33.633392333984375, "blob_id": "756d9de4d127d4c3efc333b9479a3b05693bacb2", "content_id": "f6279f93cf919766424d2470c1b0a844a03ed660", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 20122, "license_type": "permissive", "max_line_length": 80, "num_lines": 581, "path": "/src/alia/component_collection.hpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#ifndef ALIA_COMPONENT_COLLECTION_HPP\n#define ALIA_COMPONENT_COLLECTION_HPP\n\n#include <alia/common.hpp>\n\n#include <type_traits>\n#include <typeindex>\n#include <unordered_map>\n\n// This file provides a means for defining arbitrary collections of components\n// which constitute the context in which an application operates. The set of\n// components required for an application obviously varies across applications\n// (and even across modules within a complex application). The goal here is to\n// allow applications to freely mix together components from multiple sources\n// (which may not know about one another).\n//\n// Some additional design considerations follow. Note that these refer to\n// contexts rather than component collections, since that is the primary\n// motivating example of a component collection.\n//\n// 1. An application should be able to easily define its own components and mix\n// those into its context. This includes application-level state. If there is\n// state that is essentially global to the application (e.g., the active user),\n// application code should be able to retrieve this from the application\n// context. Similarly, a component of the application may decide to extend\n// the application's context with state that is specific to that component\n// (but ubiquitous within it).\n//\n// 2. Functions that take contexts as arguments should be able to define the set\n// of components that they require as part of the type signature of the context.\n// Any caller whose context includes a superset of those components should be\n// able to call the function with an implicit conversion of the context\n// parameter. This should all be possible without needing to define functions as\n// templates (otherwise alia-based applications would end up being entirely\n// header-based) and with minimal (ideally zero) runtime overhead in converting\n// the caller's context to the type expected by the function.\n//\n// 3. Retrieving frames/capabilities from a context should require minimal\n// (ideally zero) runtime overhead.\n//\n// 4. Static type checking of context conversions/retrievals should be\n// possible but optional. Developers should not have to pay these compile-time\n// costs unless it's desired. It should be possible to use a mixed workflow\n// where these checks are replaced by runtime checks for iterative development\n// but enabled for CI/release builds.\n//\n// In order to satisfy #4, this file looks for a #define called\n// ALIA_DYNAMIC_COMPONENT_CHECKING. If this is set, code related to statically\n// checking components is omitted and dynamic checks are substituted where\n// appropriate. Note that when ALIA_DYNAMIC_COMPONENT_CHECKING is NOT set,\n// ALIA_STATIC_COMPONENT_CHECKING is set and static checks are included.\n//\n// The statically typed component_collection object is a simple wrapper around\n// the dynamically typed storage object. It adds a compile-time type list\n// indicating what's actually supposed to be in the collection. This allows\n// collections to be converted to other collection types without any run-time\n// overhead. This does imply some run-time overhead for retrieving components\n// from the collection, but that can be mitigated by providing zero-cost\n// retrieval for select (core) components. This also implies that the collection\n// object must be passed by value (or const& - though there's no real point in\n// that) whereas passing by reference would be more obvious, but that seems\n// unavoidable given the requirements.\n\n#ifndef ALIA_DYNAMIC_COMPONENT_CHECKING\n#define ALIA_STATIC_COMPONENT_CHECKING\n#endif\n\nnamespace alia {\n\ntemplate<class Components, class Storage>\nstruct component_collection;\n\n#ifdef ALIA_STATIC_COMPONENT_CHECKING\n\nnamespace detail {\n\n// A component has a tag type and a data type associated with it. The tag\n// type is used only at compile time to identify the component while the data\n// type actually stores any run-time data associated with the component.\ntemplate<class Tag, class Data>\nstruct component\n{\n typedef Tag tag;\n typedef Data data_type;\n};\n\n// component_list<Components...> defines a simple compile-time list of\n// components. This is held by a component_collection to provide compile-time\n// tracking of its contents.\ntemplate<class... Components>\nstruct component_list\n{\n};\n\n// component_list_contains_tag<Tag,Components>::value yields a compile-time\n// boolean indicating whether or not :Components contains a component with a\n// tag matching :Tag.\ntemplate<class List, class Tag>\nstruct component_list_contains_tag\n{\n};\n// base case (list is empty, so :Tag not found)\ntemplate<class Tag>\nstruct component_list_contains_tag<component_list<>, Tag> : std::false_type\n{\n};\n// case where tag matches\ntemplate<class Tag, class Data, class... Rest>\nstruct component_list_contains_tag<\n component_list<component<Tag, Data>, Rest...>,\n Tag> : std::true_type\n{\n};\n// non-matching (recursive) case\ntemplate<class Tag, class OtherTag, class Data, class... Rest>\nstruct component_list_contains_tag<\n component_list<component<OtherTag, Data>, Rest...>,\n Tag> : component_list_contains_tag<component_list<Rest...>, Tag>\n{\n};\n\n// component_collection_contains_tag<Collection,Tag>::value yields a\n// compile-time boolean indicating whether or not :Collection contains an entry\n// with a tag matching :Tag.\ntemplate<class Collection, class Tag>\nstruct component_collection_contains_tag\n{\n};\ntemplate<class Components, class Storage, class Tag>\nstruct component_collection_contains_tag<\n component_collection<Components, Storage>,\n Tag> : component_list_contains_tag<Components, Tag>\n{\n};\n\n// list_contains_component<List,Component>::value yields a compile-time\n// boolean indicating whether or not :Component appears in the component_list\n// :List.\ntemplate<class List, class Component>\nstruct list_contains_component\n{\n};\n// base case (list is empty, so :Component not found)\ntemplate<class Component>\nstruct list_contains_component<component_list<>, Component> : std::false_type\n{\n};\n// case where component matches\ntemplate<class Component, class... Rest>\nstruct list_contains_component<component_list<Component, Rest...>, Component>\n : std::true_type\n{\n};\n// non-matching (recursive) case\ntemplate<class Component, class OtherComponent, class... Rest>\nstruct list_contains_component<\n component_list<OtherComponent, Rest...>,\n Component> : list_contains_component<component_list<Rest...>, Component>\n{\n};\n\n// collection_contains_component<Collection,Component>::value yields a\n// compile-time boolean indicating whether or not :Collection contains\n// :Component.\ntemplate<class Collection, class Component>\nstruct collection_contains_component\n{\n};\ntemplate<class Components, class Storage, class Component>\nstruct collection_contains_component<\n component_collection<Components, Storage>,\n Component> : list_contains_component<Components, Component>\n{\n};\n\n// add_component_to_list<List,Component>::type yields the list that results\n// from adding :Component to the head of :List.\n// Note that this doesn't perform any checks for duplicate tags.\ntemplate<class List, class Component>\nstruct add_component_to_list\n{\n};\ntemplate<class Component, class... Components>\nstruct add_component_to_list<component_list<Components...>, Component>\n{\n typedef component_list<Component, Components...> type;\n};\n\n// remove_component_from_list<List,Tag>::type yields the list that results from\n// removing the component matching :Tag from :List.\n// Note that removing a component that's not actually in the list is not\n// considered an error.\ntemplate<class List, class Tag>\nstruct remove_component_from_list\n{\n};\n// base case (list is empty)\ntemplate<class Tag>\nstruct remove_component_from_list<component_list<>, Tag>\n{\n typedef component_list<> type;\n};\n// case where component matches\ntemplate<class Tag, class Data, class... Rest>\nstruct remove_component_from_list<\n component_list<component<Tag, Data>, Rest...>,\n Tag> : remove_component_from_list<component_list<Rest...>, Tag>\n{\n};\n// non-matching case\ntemplate<class Tag, class OtherTag, class Data, class... Rest>\nstruct remove_component_from_list<\n component_list<component<OtherTag, Data>, Rest...>,\n Tag>\n : add_component_to_list<\n typename remove_component_from_list<component_list<Rest...>, Tag>::\n type,\n component<OtherTag, Data>>\n{\n};\n\n// collection_contains_all_components<Collection,Components...>::value yields a\n// compile-time boolean indicating whether or not :Collection contains all\n// components in :Components.\ntemplate<class Collection, class... Components>\nstruct collection_contains_all_components\n{\n};\n// base case (list is empty)\ntemplate<class Collection>\nstruct collection_contains_all_components<Collection> : std::true_type\n{\n};\n// recursive case\ntemplate<class Collection, class Component, class... Rest>\nstruct collection_contains_all_components<Collection, Component, Rest...>\n : std::conditional_t<\n collection_contains_component<Collection, Component>::value,\n collection_contains_all_components<Collection, Rest...>,\n std::false_type>\n{\n};\n\n// merge_component_lists<A,B>::type yields a list of components that includes\n// all components from :A and :B (with no duplicates).\ntemplate<class A, class B>\nstruct merge_component_lists\n{\n};\n// base case (:A is empty)\ntemplate<class B>\nstruct merge_component_lists<component_list<>, B>\n{\n typedef B type;\n};\n// recursive case\ntemplate<class B, class AHead, class... ARest>\nstruct merge_component_lists<component_list<AHead, ARest...>, B>\n : add_component_to_list<\n // Ensure that :AHead isn't duplicated. (This may be a noop.)\n typename remove_component_from_list<\n typename merge_component_lists<component_list<ARest...>, B>::type,\n typename AHead::tag>::type,\n AHead>\n{\n};\n\n// component_collection_is_convertible<From,To>::value yields a\n// compile-time boolean indicating whether or not the type :From can be\n// converted to the type :To (both must be component_collections).\n// The requirements for this are that a) the storage types are the same and b)\n// :From has a superset of the components of :To.\ntemplate<class From, class To>\nstruct component_collection_is_convertible\n{\n};\n// case where storage types differ\ntemplate<\n class FromComponents,\n class FromStorage,\n class ToComponents,\n class ToStorage>\nstruct component_collection_is_convertible<\n component_collection<FromComponents, FromStorage>,\n component_collection<ToComponents, ToStorage>> : std::false_type\n{\n};\n// case where storage types are the same, so components must be checked\ntemplate<class Storage, class FromComponents, class... ToComponents>\nstruct component_collection_is_convertible<\n component_collection<FromComponents, Storage>,\n component_collection<component_list<ToComponents...>, Storage>>\n : collection_contains_all_components<\n component_collection<FromComponents, Storage>,\n ToComponents...>\n{\n};\n\n} // namespace detail\n\ntemplate<class Components, class Storage>\nstruct component_collection\n{\n typedef Components components;\n typedef Storage storage_type;\n\n component_collection(Storage* storage) : storage(storage)\n {\n }\n\n // copy constructor (from convertible collections)\n template<class Other>\n component_collection(\n Other other,\n std::enable_if_t<detail::component_collection_is_convertible<\n Other,\n component_collection>::value>* = 0)\n : storage(other.storage)\n {\n }\n\n // assignment operator (from convertible collections)\n template<class Other>\n std::enable_if_t<\n detail::component_collection_is_convertible<\n Other,\n component_collection>::value,\n component_collection&>\n operator=(Other other)\n {\n storage = other.storage;\n return *this;\n }\n\n Storage* storage;\n};\n\n// empty_component_collection<Storage> yields a component collection with\n// no components and :Storage as its storage type.\ntemplate<class Storage>\nusing empty_component_collection\n = component_collection<detail::component_list<>, Storage>;\n\n// add_component_type<Collection,Tag,Data>::type gives the type that results\n// from extending :Collection with the component defined by :Tag and :Data.\ntemplate<class Collection, class Tag, class Data>\nstruct add_component_type\n{\n};\ntemplate<class Tag, class Data, class Storage, class... Components>\nstruct add_component_type<\n component_collection<detail::component_list<Components...>, Storage>,\n Tag,\n Data>\n{\n static_assert(\n !detail::component_list_contains_tag<\n detail::component_list<Components...>,\n Tag>::value,\n \"duplicate component tag\");\n typedef component_collection<\n detail::component_list<detail::component<Tag, Data>, Components...>,\n Storage>\n type;\n};\ntemplate<class Collection, class Tag, class Data>\nusing add_component_type_t =\n typename add_component_type<Collection, Tag, Data>::type;\n\n// remove_component_type<Collection,Tag,Data>::type yields the type that results\n// from removing the component associated with :Tag from :Collection.\ntemplate<class Collection, class Tag>\nstruct remove_component_type\n{\n};\ntemplate<class Tag, class Storage, class Components>\nstruct remove_component_type<component_collection<Components, Storage>, Tag>\n{\n static_assert(\n detail::component_list_contains_tag<Components, Tag>::value,\n \"attempting to remove a component tag that doesn't exist\");\n typedef component_collection<\n typename detail::remove_component_from_list<Components, Tag>::type,\n Storage>\n type;\n};\ntemplate<class Collection, class Tag>\nusing remove_component_type_t =\n typename remove_component_type<Collection, Tag>::type;\n\n// merge_components<A,B>::type yields a component collection type that contains\n// all the components from :A and :B (but no duplicates).\n// Note that the resulting component collection inherits the storage type of :A.\ntemplate<class A, class B>\nstruct merge_components\n{\n typedef component_collection<\n typename detail::merge_component_lists<\n typename A::components,\n typename B::components>::type,\n typename A::storage_type>\n type;\n};\ntemplate<class A, class B>\nusing merge_components_t = typename merge_components<A, B>::type;\n\n#endif\n\n#ifdef ALIA_DYNAMIC_COMPONENT_CHECKING\n\nstruct dynamic_component_list\n{\n};\n\ntemplate<class Components, class Storage>\nstruct component_collection\n{\n typedef Components components;\n typedef Storage storage_type;\n\n component_collection(Storage* storage) : storage(storage)\n {\n }\n\n Storage* storage;\n};\n\n// empty_component_collection<Storage> yields a component collection with\n// no components and :Storage as its storage type.\ntemplate<class Storage>\nusing empty_component_collection\n = component_collection<dynamic_component_list, Storage>;\n\n// add_component_type<Collection,Tag,Data>::type gives the type that results\n// from extending :Collection with the component defined by :Tag and :Data.\ntemplate<class Collection, class Tag, class Data>\nstruct add_component_type\n{\n typedef Collection type;\n};\ntemplate<class Collection, class Tag, class Data>\nusing add_component_type_t =\n typename add_component_type<Collection, Tag, Data>::type;\n\n// remove_component_type<Collection,Tag,Data>::type yields the type that results\n// from removing the component associated with :Tag from :Collection.\ntemplate<class Collection, class Tag>\nstruct remove_component_type\n{\n typedef Collection type;\n};\ntemplate<class Collection, class Tag>\nusing remove_component_type_t =\n typename remove_component_type<Collection, Tag>::type;\n\n// merge_components<A,B>::type yields a component collection type that contains\n// all the components from :A and :B (but no duplicates).\n// Note that the resulting component collection inherits the storage type of :A.\ntemplate<class A, class B>\nstruct merge_components\n{\n typedef A type;\n};\ntemplate<class A, class B>\nusing merge_components_t = typename merge_components<A, B>::type;\n\n#endif\n\n// Extend a collection by adding a new component.\n// :Tag is the tag of the component.\n// :data is the data associated with the new component.\n// :new_storage is a pointer to the storage object to use for the extended\n// collection. It must outlive the returned collection. (Its contents before\n// calling this function don't matter.)\ntemplate<class Tag, class Data, class Collection>\nadd_component_type_t<Collection, Tag, Data>\nadd_component(\n typename Collection::storage_type* new_storage,\n Collection collection,\n Data data)\n{\n // Copy over existing components.\n *new_storage = *collection.storage;\n // Add the new data to the storage object.\n add_component<Tag>(*new_storage, data);\n // Create a collection to reference the new storage object.\n return add_component_type_t<Collection, Tag, Data>(new_storage);\n}\n\n// Remove a component from a collection.\n// :Tag is the tag of the component.\n// :new_storage is a pointer to the storage object to use for the new\n// collection. It must outlive the returned collection. (Its contents before\n// calling this function don't matter.)\n// Note that this function is allowed to reuse the storage object from the\n// input collection, so that is also required to outlive the returned\n// collection.\ntemplate<class Tag, class Collection>\nremove_component_type_t<Collection, Tag>\nremove_component(\n typename Collection::storage_type* new_storage, Collection collection)\n{\n#ifdef ALIA_STATIC_COMPONENT_CHECKING\n // Since we're using static checking, it doesn't matter if the runtime\n // storage includes an extra component. Static checks will prevent its use.\n return remove_component_type_t<Collection, Tag>(collection.storage);\n#else\n // Copy over existing components.\n *new_storage = *collection.storage;\n // Remove the component from the storage object.\n remove_component<Tag>(*new_storage);\n // Create a collection to reference the new storage object.\n return remove_component_type_t<Collection, Tag>(new_storage);\n#endif\n}\n\n// Get a reference to the data associated with a component in a collection.\n// :Tag identifies the component.\n// If static checking is enabled, this generates a compile-time error if :Tag\n// isn't contained in :collection.\ntemplate<class Tag, class Collection>\nauto\nget_component(Collection collection)\n{\n#ifdef ALIA_STATIC_COMPONENT_CHECKING\n static_assert(\n detail::component_collection_contains_tag<Collection, Tag>::value,\n \"component not found in collection\");\n#endif\n return get_component<Tag>(*collection.storage);\n}\n\n// generic_component_storage is one possible implementation of the underlying\n// container for storing components and their associated data.\n// :Data is the type used to store component data.\ntemplate<class Data>\nstruct generic_component_storage\n{\n std::unordered_map<std::type_index, Data> components;\n};\n\n// The following functions constitute the interface expected of storage objects.\n\n// Does the storage object have a component with the given tag?\ntemplate<class Tag, class Data>\nbool\nhas_component(generic_component_storage<Data>& storage)\n{\n return storage.components.find(std::type_index(typeid(Tag)))\n != storage.components.end();\n}\n\n// Add a component.\ntemplate<class Tag, class StorageData, class ComponentData>\nvoid\nadd_component(\n generic_component_storage<StorageData>& storage, ComponentData&& data)\n{\n storage.components[std::type_index(typeid(Tag))]\n = std::forward<ComponentData&&>(data);\n}\n\n// Remove a component.\ntemplate<class Tag, class Data>\nvoid\nremove_component(generic_component_storage<Data>& storage)\n{\n storage.components.erase(std::type_index(typeid(Tag)));\n}\n\n// Get the data for a component.\ntemplate<class Tag, class Data>\nData&\nget_component(generic_component_storage<Data>& storage)\n{\n return storage.components.at(std::type_index(typeid(Tag)));\n}\n\n} // namespace alia\n\n#endif\n" }, { "alpha_fraction": 0.5769127607345581, "alphanum_fraction": 0.5774496793746948, "avg_line_length": 24.34013557434082, "blob_id": "fde08c3783d8e844dd4a5ddc4a174b17d94e1743", "content_id": "3fc635940999234a1f8caadcbb72c5bbfaed5023", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3725, "license_type": "permissive", "max_line_length": 80, "num_lines": 147, "path": "/src/alia/signals/numeric.hpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#ifndef ALIA_SIGNALS_NUMERIC_HPP\n#define ALIA_SIGNALS_NUMERIC_HPP\n\n#include <alia/signals/application.hpp>\n#include <alia/signals/utilities.hpp>\n\n#include <cmath>\n\n// This file defines some numerical adaptors for signals.\n\nnamespace alia {\n\n// scale(n, factor) creates a new signal that presents a scaled view of :n,\n// where :n and :factor are both numeric signals.\ntemplate<class N, class Factor>\nstruct scaled_signal : regular_signal<\n scaled_signal<N, Factor>,\n typename N::value_type,\n typename N::direction_tag>\n{\n scaled_signal(N n, Factor scale_factor) : n_(n), scale_factor_(scale_factor)\n {\n }\n bool\n is_readable() const\n {\n return n_.is_readable() && scale_factor_.is_readable();\n }\n typename N::value_type const&\n read() const\n {\n return lazy_reader_.read(\n [&] { return n_.read() * scale_factor_.read(); });\n }\n bool\n is_writable() const\n {\n return n_.is_writable() && scale_factor_.is_readable();\n }\n void\n write(typename N::value_type const& value) const\n {\n n_.write(value / scale_factor_.read());\n }\n\n private:\n N n_;\n Factor scale_factor_;\n lazy_reader<typename N::value_type> lazy_reader_;\n};\ntemplate<class N, class Factor>\nscaled_signal<N, Factor>\nscale(N const& n, Factor const& scale_factor)\n{\n return scaled_signal<N, Factor>(n, scale_factor);\n}\n\n// offset(n, offset) presents an offset view of :n.\ntemplate<class N, class Offset>\nstruct offset_signal : regular_signal<\n offset_signal<N, Offset>,\n typename N::value_type,\n typename N::direction_tag>\n{\n offset_signal(N n, Offset offset) : n_(n), offset_(offset)\n {\n }\n bool\n is_readable() const\n {\n return n_.is_readable() && offset_.is_readable();\n }\n typename N::value_type const&\n read() const\n {\n return lazy_reader_.read([&] { return n_.read() + offset_.read(); });\n }\n bool\n is_writable() const\n {\n return n_.is_writable() && offset_.is_readable();\n }\n void\n write(typename N::value_type const& value) const\n {\n n_.write(value - offset_.read());\n }\n\n private:\n N n_;\n Offset offset_;\n lazy_reader<typename N::value_type> lazy_reader_;\n};\ntemplate<class N, class Offset>\noffset_signal<N, Offset>\noffset(N const& n, Offset const& offset)\n{\n return offset_signal<N, Offset>(n, offset);\n}\n\n// round_signal_writes(n, step) yields a wrapper which rounds any writes to\n// :n so that values are always a multiple of :step.\ntemplate<class N, class Step>\nstruct rounding_signal_wrapper : regular_signal<\n rounding_signal_wrapper<N, Step>,\n typename N::value_type,\n typename N::direction_tag>\n{\n rounding_signal_wrapper(N n, Step step) : n_(n), step_(step)\n {\n }\n bool\n is_readable() const\n {\n return n_.is_readable();\n }\n typename N::value_type const&\n read() const\n {\n return n_.read();\n }\n bool\n is_writable() const\n {\n return n_.is_writable() && step_.is_readable();\n }\n void\n write(typename N::value_type const& value) const\n {\n typename N::value_type step = step_.read();\n n_.write(std::floor(value / step + typename N::value_type(0.5)) * step);\n }\n\n private:\n N n_;\n Step step_;\n};\ntemplate<class N, class Step>\nrounding_signal_wrapper<N, Step>\nround_signal_writes(N const& n, Step const& step)\n{\n return rounding_signal_wrapper<N, Step>(n, step);\n}\n\n} // namespace alia\n\n#endif\n" }, { "alpha_fraction": 0.6687552332878113, "alphanum_fraction": 0.6712614893913269, "avg_line_length": 26.204545974731445, "blob_id": "048314e3d8ebbd8140b16d3c6035c38f1c59cf80", "content_id": "c53d69c845f9bafa17a5052dae59887a5c9d8fc1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2394, "license_type": "permissive", "max_line_length": 80, "num_lines": 88, "path": "/unit_tests/dynamic_component_collections.cpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#define ALIA_DYNAMIC_COMPONENT_CHECKING\n\n#include <alia/component_collection.hpp>\n\n#include <catch2/catch.hpp>\n\n#include <boost/any.hpp>\n\nusing namespace alia;\n\n// This shouldn't have been defiend.\n#ifdef ALIA_STATIC_COMPONENT_CHECKING\n#error ALIA_STATIC_COMPONENT_CHECKING defined\n#endif\n\n// Define some arbitrary tag and data types.\nstruct foo_tag\n{\n};\nstruct foo\n{\n bool b = false;\n};\nstruct bar_tag\n{\n};\nstruct bar\n{\n int i = 0;\n bar()\n {\n }\n bar(int i) : i(i)\n {\n }\n};\nstruct zap_tag\n{\n};\nstruct zap\n{\n double d = 0;\n};\n\n// Define some arbitrary component collection types.\nusing storage_type = generic_component_storage<boost::any>;\nusing cc_empty = empty_component_collection<storage_type>;\nusing cc_b = add_component_type_t<cc_empty, bar_tag, bar>;\nusing cc_fb = add_component_type_t<cc_b, foo_tag, foo>;\nusing cc_z = add_component_type_t<cc_empty, zap_tag, zap>;\nusing cc_bz = add_component_type_t<cc_z, bar_tag, bar>;\nusing cc_fbz = add_component_type_t<cc_bz, foo_tag, foo>;\nusing cc_fz = remove_component_type_t<cc_fbz, bar_tag>;\nusing cc_f = add_component_type_t<cc_empty, foo_tag, foo>;\nusing cc_fzb = merge_components_t<cc_fz, cc_bz>;\n\nTEST_CASE(\"dynamic component_collection conversions\", \"[component_collections]\")\n{\n storage_type storage;\n cc_fb mc_fb(&storage);\n REQUIRE(mc_fb.storage == &storage);\n cc_b mc_b(mc_fb);\n REQUIRE(mc_b.storage == &storage);\n}\n\nTEST_CASE(\"dynamic component access\", \"[component_collections]\")\n{\n storage_type storage_empty;\n cc_empty mc_empty(&storage_empty);\n REQUIRE(!has_component<bar_tag>(storage_empty));\n\n storage_type storage_b;\n cc_b mc_b = add_component<bar_tag>(&storage_b, mc_empty, bar(1));\n REQUIRE(has_component<bar_tag>(storage_b));\n REQUIRE(boost::any_cast<bar>(get_component<bar_tag>(mc_b)).i == 1);\n REQUIRE(!has_component<foo_tag>(storage_b));\n REQUIRE_THROWS(get_component<foo_tag>(mc_b));\n\n storage_type storage_fb;\n cc_fb mc_fb = add_component<foo_tag>(&storage_fb, mc_b, foo());\n REQUIRE(boost::any_cast<bar>(get_component<bar_tag>(mc_fb)).i == 1);\n REQUIRE(boost::any_cast<foo>(get_component<foo_tag>(mc_fb)).b == false);\n\n storage_type storage_f;\n cc_f mc_f = remove_component<bar_tag>(&storage_f, mc_fb);\n REQUIRE(boost::any_cast<foo>(get_component<foo_tag>(mc_f)).b == false);\n REQUIRE_THROWS(get_component<bar_tag>(mc_f));\n}\n" }, { "alpha_fraction": 0.5926480889320374, "alphanum_fraction": 0.60408616065979, "avg_line_length": 29.919511795043945, "blob_id": "e87598d1ef8a1eb48233b892c0c829eca64fa694", "content_id": "9fac0ccc1dc809b7f4ab896b68c792683c6ea65c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 12677, "license_type": "permissive", "max_line_length": 80, "num_lines": 410, "path": "/unit_tests/signals/operators.cpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#define ALIA_LOWERCASE_MACROS\n\n#include <alia/signals/operators.hpp>\n\n#include <map>\n\n#include <catch2/catch.hpp>\n\n#include <alia/signals/basic.hpp>\n#include <alia/signals/lambdas.hpp>\n#include <alia/signals/utilities.hpp>\n\nusing namespace alia;\n\nTEST_CASE(\"basic signal operators\", \"[signals]\")\n{\n REQUIRE(is_true(value(2) == value(2)));\n REQUIRE(is_false(value(6) == value(2)));\n REQUIRE(is_true(value(6) != value(2)));\n REQUIRE(is_false(value(2) != value(2)));\n REQUIRE(is_true(value(6) > value(2)));\n REQUIRE(is_false(value(6) < value(2)));\n REQUIRE(is_true(value(6) >= value(2)));\n REQUIRE(is_true(value(2) >= value(2)));\n REQUIRE(is_false(value(2) >= value(6)));\n REQUIRE(is_true(value(2) < value(6)));\n REQUIRE(is_false(value(6) < value(2)));\n REQUIRE(is_true(value(2) <= value(6)));\n REQUIRE(is_true(value(2) <= value(2)));\n REQUIRE(is_false(value(6) <= value(2)));\n\n REQUIRE(is_true(value(6) + value(2) == value(8)));\n REQUIRE(is_true(value(6) - value(2) == value(4)));\n REQUIRE(is_true(value(6) * value(2) == value(12)));\n REQUIRE(is_true(value(6) / value(2) == value(3)));\n REQUIRE(is_true(value(6) % value(2) == value(0)));\n REQUIRE(is_true((value(6) ^ value(2)) == value(4)));\n REQUIRE(is_true((value(6) & value(2)) == value(2)));\n REQUIRE(is_true((value(6) | value(2)) == value(6)));\n REQUIRE(is_true(value(6) << value(2) == value(24)));\n REQUIRE(is_true(value(6) >> value(2) == value(1)));\n\n REQUIRE(is_true(-value(2) == value(-2)));\n REQUIRE(is_false(!(value(2) == value(2))));\n}\n\nTEST_CASE(\"signal &&\", \"[signals]\")\n{\n REQUIRE(is_true(value(true) && value(true)));\n REQUIRE(is_false(value(true) && value(false)));\n REQUIRE(is_false(value(false) && value(true)));\n REQUIRE(is_false(value(false) && value(false)));\n\n // Check that unreadable signals are treated properly.\n REQUIRE(!signal_is_readable(empty<bool>() && empty<bool>()));\n REQUIRE(!signal_is_readable(value(true) && empty<bool>()));\n REQUIRE(!signal_is_readable(empty<bool>() && value(true)));\n REQUIRE(is_false(value(false) && empty<bool>()));\n REQUIRE(is_false(empty<bool>() && value(false)));\n\n // Check that && short-circuits.\n int access_count = 0;\n auto access_counting_signal = lambda_input(always_readable, [&]() {\n ++access_count;\n return true;\n });\n REQUIRE(is_false(value(false) && access_counting_signal));\n REQUIRE(access_count == 0);\n\n // Check that its value ID behaves reasonably.\n REQUIRE(\n (value(true) && value(false)).value_id()\n != (value(true) && value(true)).value_id());\n}\n\nTEST_CASE(\"signal ||\", \"[signals]\")\n{\n REQUIRE(is_true(value(true) || value(true)));\n REQUIRE(is_true(value(true) || value(false)));\n REQUIRE(is_true(value(false) || value(true)));\n REQUIRE(is_false(value(false) || value(false)));\n\n // Check that unreadable signals are treated properly.\n REQUIRE(!signal_is_readable(empty<bool>() || empty<bool>()));\n REQUIRE(!signal_is_readable(value(false) || empty<bool>()));\n REQUIRE(!signal_is_readable(empty<bool>() || value(false)));\n REQUIRE(is_true(value(true) || empty<bool>()));\n REQUIRE(is_true(empty<bool>() || value(true)));\n\n // Check that || short-circuits.\n int access_count = 0;\n auto access_counting_signal = lambda_input(always_readable, [&]() {\n ++access_count;\n return false;\n });\n REQUIRE(is_true(value(true) || access_counting_signal));\n REQUIRE(access_count == 0);\n\n // Check that its value ID behaves reasonably.\n REQUIRE(\n (value(false) || value(false)).value_id()\n != (value(true) || value(false)).value_id());\n}\n\nTEST_CASE(\"signal select\", \"[signals]\")\n{\n bool condition = false;\n auto s = conditional(direct(condition), value(1), value(2));\n\n typedef decltype(s) signal_t;\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(!signal_can_write<signal_t>::value);\n\n REQUIRE(signal_is_readable(s));\n REQUIRE(read_signal(s) == 2);\n captured_id original_id = s.value_id();\n condition = true;\n REQUIRE(signal_is_readable(s));\n REQUIRE(read_signal(s) == 1);\n REQUIRE(original_id.get() != s.value_id());\n}\n\nTEST_CASE(\"select with different directions\", \"[signals]\")\n{\n bool condition = false;\n auto s = conditional(direct(condition), empty<int>(), value(2));\n\n typedef decltype(s) signal_t;\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(!signal_can_write<signal_t>::value);\n\n REQUIRE(signal_is_readable(s));\n REQUIRE(read_signal(s) == 2);\n condition = true;\n REQUIRE(!signal_is_readable(s));\n}\n\nTEST_CASE(\"select value ID\", \"[signals]\")\n{\n // Test that conditional's ID changes when the condition changes, even if\n // both of its input signals are producing the same value ID.\n\n bool condition = false;\n auto s = conditional(direct(condition), value(2), value(2));\n\n captured_id original_id = s.value_id();\n condition = true;\n REQUIRE(original_id.get() != s.value_id());\n}\n\nTEST_CASE(\"select with unreadable condition\", \"[signals]\")\n{\n int x = 0, y = 1;\n auto s = conditional(empty<bool>(), direct(x), direct(y));\n REQUIRE(!signal_is_readable(s));\n REQUIRE(s.value_id() == no_id);\n REQUIRE(!signal_is_writable(s));\n}\n\nTEST_CASE(\"writable select\", \"[signals]\")\n{\n bool condition = false;\n int x = 1;\n int y = 2;\n auto s = conditional(direct(condition), direct(x), direct(y));\n\n typedef decltype(s) signal_t;\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(signal_can_write<signal_t>::value);\n\n REQUIRE(signal_is_readable(s));\n REQUIRE(read_signal(s) == 2);\n condition = true;\n REQUIRE(read_signal(s) == 1);\n write_signal(s, 4);\n REQUIRE(x == 4);\n REQUIRE(y == 2);\n REQUIRE(read_signal(s) == 4);\n condition = false;\n write_signal(s, 3);\n REQUIRE(x == 4);\n REQUIRE(y == 3);\n REQUIRE(read_signal(s) == 3);\n}\n\nTEST_CASE(\"field signal\", \"[signals]\")\n{\n struct foo\n {\n int x;\n double y;\n };\n foo f = {2, 1.5};\n auto f_signal = lambda_bidirectional(\n always_readable,\n [&]() { return f; },\n always_writable,\n [&](foo const& v) { f = v; },\n [&]() { return combine_ids(make_id(f.x), make_id(f.y)); });\n auto x_signal = f_signal->*&foo::x;\n\n typedef decltype(x_signal) x_signal_t;\n REQUIRE((std::is_same<x_signal_t::value_type, int>::value));\n REQUIRE(signal_can_read<x_signal_t>::value);\n REQUIRE(signal_can_write<x_signal_t>::value);\n\n REQUIRE(signal_is_readable(x_signal));\n REQUIRE(read_signal(x_signal) == 2);\n REQUIRE(signal_is_writable(x_signal));\n write_signal(x_signal, 1);\n REQUIRE(f.x == 1);\n\n auto y_signal = alia_field(f_signal, y);\n\n typedef decltype(y_signal) y_signal_t;\n REQUIRE((std::is_same<y_signal_t::value_type, double>::value));\n REQUIRE(signal_can_read<y_signal_t>::value);\n REQUIRE(signal_can_write<y_signal_t>::value);\n\n REQUIRE(y_signal.value_id() != x_signal.value_id());\n REQUIRE(signal_is_readable(y_signal));\n REQUIRE(read_signal(y_signal) == 1.5);\n REQUIRE(signal_is_writable(y_signal));\n captured_id original_y_id = y_signal.value_id();\n write_signal(y_signal, 0.5);\n REQUIRE(y_signal.value_id() != original_y_id.get());\n REQUIRE(f.y == 0.5);\n}\n\nstruct my_array\n{\n int x[3] = {1, 2, 3};\n int& operator[](int i)\n {\n return x[i];\n }\n int const& operator[](int i) const\n {\n return x[i];\n }\n};\n\nstruct my_const_array\n{\n int x[3] = {1, 2, 3};\n int operator[](int i) const\n {\n return x[i];\n }\n};\n\n// Test some of the helper metafunctions for subscript signals.\nTEST_CASE(\"subscript metafunctions\", \"[signals]\")\n{\n REQUIRE(has_at_indexer<std::vector<int>, int>::value);\n REQUIRE(has_at_indexer<std::map<int, int>, int>::value);\n REQUIRE(has_at_indexer<std::vector<bool>, int>::value);\n REQUIRE(!has_at_indexer<my_array, int>::value);\n REQUIRE(!has_at_indexer<my_const_array, int>::value);\n\n REQUIRE((std::is_same<\n subscript_result_type<std::vector<float>, int>::type,\n float>::value));\n REQUIRE((std::is_same<\n subscript_result_type<std::map<int, float>, int>::type,\n float>::value));\n REQUIRE((std::is_same<\n subscript_result_type<std::vector<bool>, int>::type,\n bool>::value));\n REQUIRE(\n (std::is_same<subscript_result_type<my_array, int>::type, int>::value));\n REQUIRE(\n (std::is_same<subscript_result_type<my_const_array, int>::type, int>::\n value));\n\n REQUIRE(const_subscript_returns_reference<std::vector<int>, int>::value);\n REQUIRE(const_subscript_returns_reference<std::map<int, int>, int>::value);\n REQUIRE(!const_subscript_returns_reference<std::vector<bool>, int>::value);\n REQUIRE(const_subscript_returns_reference<my_array, int>::value);\n REQUIRE(!const_subscript_returns_reference<my_const_array, int>::value);\n}\n\nTEST_CASE(\"vector subscript\", \"[signals]\")\n{\n using namespace alia;\n\n auto c = std::vector<int>{2, 0, 3};\n auto c_signal = direct(c);\n auto s = c_signal[value(1)];\n\n typedef decltype(s) signal_t;\n REQUIRE((std::is_same<signal_t::value_type, int>::value));\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(signal_can_write<signal_t>::value);\n\n REQUIRE(signal_is_readable(s));\n REQUIRE(read_signal(s) == 0);\n REQUIRE(signal_is_writable(s));\n captured_id original_id = s.value_id();\n write_signal(s, 1);\n REQUIRE(c == std::vector<int>({2, 1, 3}));\n\n // Check that changes in the container and the index both cause changes\n // in the value ID.\n REQUIRE(!original_id.matches(s.value_id()));\n auto t = c_signal[value(0)];\n REQUIRE(t.value_id() != s.value_id());\n}\n\nTEST_CASE(\"read-only subscript\", \"[signals]\")\n{\n using namespace alia;\n\n auto c = std::vector<int>{2, 0, 3};\n auto c_signal = value(c);\n auto s = c_signal[value(1)];\n\n typedef decltype(s) signal_t;\n REQUIRE((std::is_same<signal_t::value_type, int>::value));\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(!signal_can_write<signal_t>::value);\n\n REQUIRE(signal_is_readable(s));\n REQUIRE(read_signal(s) == 0);\n}\n\nTEST_CASE(\"vector<bool> subscript\", \"[signals]\")\n{\n using namespace alia;\n\n auto c = std::vector<bool>{true, false, false};\n auto c_signal = direct(c);\n auto s = c_signal[value(1)];\n\n typedef decltype(s) signal_t;\n REQUIRE((std::is_same<signal_t::value_type, bool>::value));\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(signal_can_write<signal_t>::value);\n\n REQUIRE(signal_is_readable(s));\n REQUIRE(read_signal(s) == false);\n REQUIRE(signal_is_writable(s));\n write_signal(s, true);\n REQUIRE(c == std::vector<bool>({true, true, false}));\n}\n\nTEST_CASE(\"map subscript\", \"[signals]\")\n{\n using namespace alia;\n\n auto c = std::map<int, int>{{2, 1}, {0, 3}};\n auto c_signal = direct(c);\n auto s = c_signal[value(2)];\n\n typedef decltype(s) signal_t;\n REQUIRE((std::is_same<signal_t::value_type, int>::value));\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(signal_can_write<signal_t>::value);\n\n REQUIRE(signal_is_readable(s));\n REQUIRE(read_signal(s) == 1);\n REQUIRE(signal_is_writable(s));\n write_signal(s, 7);\n REQUIRE(c == std::map<int, int>{{2, 7}, {0, 3}});\n}\n\nTEST_CASE(\"custom ref subscript\", \"[signals]\")\n{\n my_array c;\n auto c_signal = lambda_bidirectional(\n always_readable,\n [&]() { return c; },\n always_writable,\n [&](my_array const& v) { c = v; },\n [&]() {\n return unit_id; // doesn't really matter\n });\n auto s = c_signal[value(2)];\n\n typedef decltype(s) signal_t;\n REQUIRE((std::is_same<signal_t::value_type, int>::value));\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(signal_can_write<signal_t>::value);\n\n REQUIRE(signal_is_readable(s));\n REQUIRE(read_signal(s) == 3);\n REQUIRE(signal_is_writable(s));\n write_signal(s, 4);\n REQUIRE(c[2] == 4);\n}\n\nTEST_CASE(\"custom by-value subscript\", \"[signals]\")\n{\n my_const_array c;\n auto c_signal = lambda_input(\n always_readable,\n [&]() { return c; },\n [&]() {\n return unit_id; // doesn't really matter\n });\n auto s = c_signal[value(2)];\n\n typedef decltype(s) signal_t;\n REQUIRE((std::is_same<signal_t::value_type, int>::value));\n REQUIRE(signal_can_read<signal_t>::value);\n REQUIRE(!signal_can_write<signal_t>::value);\n\n REQUIRE(signal_is_readable(s));\n REQUIRE(read_signal(s) == 3);\n}\n" }, { "alpha_fraction": 0.6667567491531372, "alphanum_fraction": 0.6672970652580261, "avg_line_length": 22.957929611206055, "blob_id": "79959c910f2c97f3452f01b53089a5c17135afbd", "content_id": "0f668f1f18e65bb973b1a69b21c2452abe73e115", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7403, "license_type": "permissive", "max_line_length": 80, "num_lines": 309, "path": "/src/alia/actions.hpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#ifndef ALIA_ACTIONS_HPP\n#define ALIA_ACTIONS_HPP\n\n#include <alia/signals/core.hpp>\n#include <alia/signals/operators.hpp>\n\n// This file defines the alia action interface, some common implementations of\n// it, and some utilities for working with it.\n//\n// An action is essentially a response to an event that's dispatched by alia.\n// When specifying a component element that can generate events, the application\n// supplies the action that should be performed when the corresponding event is\n// generated. Using this style allows event handling to be written in a safer\n// and more reactive manner.\n//\n// Actions are very similar to signals in the way that they are used in an\n// application. Like signals, they're typically created directly at the call\n// site as function arguments and are only valid for the life of the function\n// call.\n\nnamespace alia {\n\n// untyped_action_interface defines functionality common to all actions,\n// irrespective of the type of arguments that the action takes.\nstruct untyped_action_interface\n{\n // Is this action ready to be performed?\n virtual bool\n is_ready() const = 0;\n};\n\ntemplate<class... Args>\nstruct action_interface : untyped_action_interface\n{\n // Perform this action.\n virtual void\n perform(Args... args) const = 0;\n};\n\n// is_action_type<T>::value yields a compile-time boolean indicating whether or\n// not T is an alia action type.\ntemplate<class T>\nstruct is_action_type : std::is_base_of<untyped_action_interface, T>\n{\n};\n\n// Perform an action.\ntemplate<class... Args>\nvoid\nperform_action(action_interface<Args...> const& action, Args... args)\n{\n assert(action.is_ready());\n action.perform(args...);\n}\n\n// action_ref is a reference to an action that implements the action interface\n// itself.\ntemplate<class... Args>\nstruct action_ref : action_interface<Args...>\n{\n // Construct from a reference to another action.\n action_ref(action_interface<Args...> const& ref) : action_(&ref)\n {\n }\n // Construct from another action_ref. - This is meant to prevent unnecessary\n // layers of indirection.\n action_ref(action_ref<Args...> const& other) : action_(other.action_)\n {\n }\n\n bool\n is_ready() const\n {\n return action_->is_ready();\n }\n\n void\n perform(Args... args) const\n {\n action_->perform(args...);\n }\n\n private:\n action_interface<Args...> const* action_;\n};\n\ntemplate<class... Args>\nusing action = action_ref<Args...>;\n\n// comma operator\n//\n// Using the comma operator between two signals creates a combined action that\n// performs the two actions in sequence.\n\ntemplate<class First, class Second, class... Args>\nstruct action_pair : First::action_interface\n{\n action_pair()\n {\n }\n\n action_pair(First const& first, Second const& second)\n : first_(first), second_(second)\n {\n }\n\n bool\n is_ready() const\n {\n return first_.is_ready() && second_.is_ready();\n }\n\n void\n perform(Args... args) const\n {\n first_.perform(args...);\n second_.perform(args...);\n }\n\n private:\n First first_;\n Second second_;\n};\n\ntemplate<\n class First,\n class Second,\n std::enable_if_t<\n is_action_type<First>::value && is_action_type<Second>::value,\n int> = 0>\nauto\noperator,(First const& first, Second const& second)\n{\n return action_pair<First, Second>(first, second);\n}\n\n// operator <<=\n//\n// sink <<= source, where :sink and :source are both signals, creates an action\n// that will set the value of :sink to the value held in :source. In order for\n// the action to be considered ready, :source must be readable and :sink must be\n// writable.\n\ntemplate<class Sink, class Source>\nstruct copy_action : action_interface<>\n{\n copy_action(Sink const& sink, Source const& source)\n : sink_(sink), source_(source)\n {\n }\n\n bool\n is_ready() const\n {\n return source_.is_readable() && sink_.is_writable();\n }\n\n void\n perform() const\n {\n sink_.write(source_.read());\n }\n\n private:\n Sink sink_;\n Source source_;\n};\n\ntemplate<\n class Sink,\n class Source,\n std::enable_if_t<\n is_writable_signal_type<Sink>::value\n && is_readable_signal_type<Source>::value,\n int> = 0>\nauto\noperator<<=(Sink const& sink, Source const& source)\n{\n return copy_action<Sink, Source>(sink, source);\n}\n\n// make_toggle_action(flag), where :flag is a signal to a boolean, creates an\n// action that will toggle the value of :flag between true and false.\n//\n// Note that this could also be used with other value types as long as the !\n// operator provides a reasonable \"toggle\" function.\n//\ntemplate<class Flag>\nauto\nmake_toggle_action(Flag const& flag)\n{\n return flag <<= !flag;\n}\n\n// make_push_back_action(collection, item), where both :collection and :item are\n// signals, creates an action that will push the value of :item onto the back\n// of :collection.\n\ntemplate<class Collection, class Item>\nstruct push_back_action : action_interface<>\n{\n push_back_action(Collection const& collection, Item const& item)\n : collection_(collection), item_(item)\n {\n }\n\n bool\n is_ready() const\n {\n return collection_.is_readable() && collection_.is_writable()\n && item_.is_readable();\n }\n\n void\n perform() const\n {\n auto new_collection = collection_.read();\n new_collection.push_back(item_.read());\n collection_.write(new_collection);\n }\n\n private:\n Collection collection_;\n Item item_;\n};\n\ntemplate<class Collection, class Item>\nauto\nmake_push_back_action(Collection const& collection, Item const& item)\n{\n return push_back_action<Collection, Item>(collection, item);\n}\n\n// lambda_action(is_ready, perform) creates an action whose behavior is defined\n// by two function objects.\n//\n// :is_ready takes no parameters and simply returns true or false to show if the\n// action is ready to be performed.\n//\n// :perform can take any number/type of arguments and this defines the signature\n// of the action.\n\ntemplate<class Function>\nstruct call_operator_action_signature\n{\n};\n\ntemplate<class T, class R, class... Args>\nstruct call_operator_action_signature<R (T::*)(Args...) const>\n{\n typedef action_interface<Args...> type;\n};\n\ntemplate<class Lambda>\nstruct lambda_action_signature\n : call_operator_action_signature<decltype(&Lambda::operator())>\n{\n};\n\ntemplate<class IsReady, class Perform, class Interface>\nstruct lambda_action_object;\n\ntemplate<class IsReady, class Perform, class... Args>\nstruct lambda_action_object<IsReady, Perform, action_interface<Args...>>\n : action_interface<Args...>\n{\n lambda_action_object(IsReady is_ready, Perform perform)\n : is_ready_(is_ready), perform_(perform)\n {\n }\n\n bool\n is_ready() const\n {\n return is_ready_();\n }\n\n void\n perform(Args... args) const\n {\n perform_(args...);\n }\n\n private:\n IsReady is_ready_;\n Perform perform_;\n};\n\ntemplate<class IsReady, class Perform>\nauto\nlambda_action(IsReady is_ready, Perform perform)\n{\n return lambda_action_object<\n IsReady,\n Perform,\n typename lambda_action_signature<Perform>::type>(is_ready, perform);\n}\n\n// This is just a clear and concise way of indicating that a lambda action is\n// always ready.\ninline bool\nalways_ready()\n{\n return true;\n}\n\n} // namespace alia\n\n#endif\n" }, { "alpha_fraction": 0.4047619104385376, "alphanum_fraction": 0.4047619104385376, "avg_line_length": 9.5, "blob_id": "550296c9491186445321f7074251ecc992cda21b", "content_id": "7965b439df397b8522393c00837dccd12f3fa2e8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 84, "license_type": "permissive", "max_line_length": 20, "num_lines": 8, "path": "/docs/the-basics/control-flow.rst", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "Control Flow\n============\n\nLoops & Conditionals\n--------------------\n\nEvents\n------\n" }, { "alpha_fraction": 0.5836182236671448, "alphanum_fraction": 0.5836182236671448, "avg_line_length": 23.63157844543457, "blob_id": "492c5e57005089bd114a4da330b42792a5132e9c", "content_id": "c81c217ddb62b839d024b68b5eda018424a709d1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7020, "license_type": "permissive", "max_line_length": 80, "num_lines": 285, "path": "/src/alia/signals/lambdas.hpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#ifndef ALIA_SIGNALS_LAMBDAS_HPP\n#define ALIA_SIGNALS_LAMBDAS_HPP\n\n#include <alia/signals/core.hpp>\n#include <alia/signals/utilities.hpp>\n\n// This file defines utilities for constructing custom signals via lambda\n// functions.\n\nnamespace alia {\n\n// lambda_input(is_readable, read) creates a read-only signal whose value is\n// determined by calling :is_readable and :read.\ntemplate<class Value, class IsReadable, class Read>\nstruct lambda_input_signal : regular_signal<\n lambda_input_signal<Value, IsReadable, Read>,\n Value,\n read_only_signal>\n{\n lambda_input_signal(IsReadable is_readable, Read read)\n : is_readable_(is_readable), read_(read)\n {\n }\n bool\n is_readable() const\n {\n return is_readable_();\n }\n Value const&\n read() const\n {\n value_ = read_();\n return value_;\n }\n\n private:\n IsReadable is_readable_;\n Read read_;\n mutable decltype(read_()) value_;\n};\ntemplate<class IsReadable, class Read>\nauto\nlambda_input(IsReadable is_readable, Read read)\n{\n return lambda_input_signal<\n std::decay_t<decltype(read())>,\n IsReadable,\n Read>(is_readable, read);\n}\n\n// lambda_input(is_readable, read, generate_id) creates a read-only signal whose\n// value is determined by calling :is_readable and :read and whose ID is\n// determined by calling :generate_id.\ntemplate<class Value, class IsReadable, class Read, class GenerateId>\nstruct lambda_input_signal_with_id\n : signal<\n lambda_input_signal_with_id<Value, IsReadable, Read, GenerateId>,\n Value,\n read_only_signal>\n{\n lambda_input_signal_with_id(\n IsReadable is_readable, Read read, GenerateId generate_id)\n : is_readable_(is_readable), read_(read), generate_id_(generate_id)\n {\n }\n id_interface const&\n value_id() const\n {\n id_ = generate_id_();\n return id_;\n }\n bool\n is_readable() const\n {\n return is_readable_();\n }\n Value const&\n read() const\n {\n value_ = read_();\n return value_;\n }\n\n private:\n IsReadable is_readable_;\n Read read_;\n mutable decltype(read_()) value_;\n GenerateId generate_id_;\n mutable decltype(generate_id_()) id_;\n};\ntemplate<class IsReadable, class Read, class GenerateId>\nauto\nlambda_input(IsReadable is_readable, Read read, GenerateId generate_id)\n{\n return lambda_input_signal_with_id<\n std::decay_t<decltype(read())>,\n IsReadable,\n Read,\n GenerateId>(is_readable, read, generate_id);\n}\n\n// lambda_bidirectional(is_readable, read, is_writable, write, generate_id)\n// creates a bidirectional signal whose value is read by calling :is_readable\n// and :read and written by calling :is_writable and :write. Its ID is\n// determined by calling :generate_id.\ntemplate<\n class Value,\n class IsReadable,\n class Read,\n class IsWritable,\n class Write>\nstruct lambda_bidirectional_signal : regular_signal<\n lambda_bidirectional_signal<\n Value,\n IsReadable,\n Read,\n IsWritable,\n Write>,\n Value,\n bidirectional_signal>\n{\n lambda_bidirectional_signal(\n IsReadable is_readable, Read read, IsWritable is_writable, Write write)\n : is_readable_(is_readable),\n read_(read),\n is_writable_(is_writable),\n write_(write)\n {\n }\n bool\n is_readable() const\n {\n return is_readable_();\n }\n Value const&\n read() const\n {\n value_ = read_();\n return value_;\n }\n bool\n is_writable() const\n {\n return is_writable_();\n }\n void\n write(Value const& value) const\n {\n write_(value);\n }\n\n private:\n IsReadable is_readable_;\n Read read_;\n mutable decltype(read_()) value_;\n IsWritable is_writable_;\n Write write_;\n};\ntemplate<class IsReadable, class Read, class IsWritable, class Write>\nauto\nlambda_bidirectional(\n IsReadable is_readable, Read read, IsWritable is_writable, Write write)\n{\n return lambda_bidirectional_signal<\n std::decay_t<decltype(read())>,\n IsReadable,\n Read,\n IsWritable,\n Write>(is_readable, read, is_writable, write);\n}\n\n// lambda_bidirectional(is_readable, read, is_writable, write) creates a\n// bidirectional signal whose value is read by calling :is_readable and :read\n// and written by calling :is_writable and :write.\ntemplate<\n class Value,\n class IsReadable,\n class Read,\n class IsWritable,\n class Write,\n class GenerateId>\nstruct lambda_bidirectional_signal_with_id\n : signal<\n lambda_bidirectional_signal_with_id<\n Value,\n IsReadable,\n Read,\n IsWritable,\n Write,\n GenerateId>,\n Value,\n bidirectional_signal>\n{\n lambda_bidirectional_signal_with_id(\n IsReadable is_readable,\n Read read,\n IsWritable is_writable,\n Write write,\n GenerateId generate_id)\n : is_readable_(is_readable),\n read_(read),\n is_writable_(is_writable),\n write_(write),\n generate_id_(generate_id)\n {\n }\n id_interface const&\n value_id() const\n {\n id_ = generate_id_();\n return id_;\n }\n bool\n is_readable() const\n {\n return is_readable_();\n }\n Value const&\n read() const\n {\n value_ = read_();\n return value_;\n }\n bool\n is_writable() const\n {\n return is_writable_();\n }\n void\n write(Value const& value) const\n {\n write_(value);\n }\n\n private:\n IsReadable is_readable_;\n Read read_;\n mutable decltype(read_()) value_;\n IsWritable is_writable_;\n Write write_;\n GenerateId generate_id_;\n mutable decltype(generate_id_()) id_;\n};\ntemplate<\n class IsReadable,\n class Read,\n class IsWritable,\n class Write,\n class GenerateId>\nauto\nlambda_bidirectional(\n IsReadable is_readable,\n Read read,\n IsWritable is_writable,\n Write write,\n GenerateId generate_id)\n{\n return lambda_bidirectional_signal_with_id<\n std::decay_t<decltype(read())>,\n IsReadable,\n Read,\n IsWritable,\n Write,\n GenerateId>(is_readable, read, is_writable, write, generate_id);\n}\n\n// This is just a clear and concise way of indicating that a lambda signal is\n// always readable.\ninline bool\nalways_readable()\n{\n return true;\n}\n\n// This is just a clear and concise way of indicating that a lambda signal is\n// always writable.\ninline bool\nalways_writable()\n{\n return true;\n}\n\n} // namespace alia\n\n#endif\n" }, { "alpha_fraction": 0.7269503474235535, "alphanum_fraction": 0.7269503474235535, "avg_line_length": 20.69230842590332, "blob_id": "0a08f0a4e7023fa2c03e7b28af1fa23af3409508", "content_id": "3b72e11af56f8004eafb74de868119278bbd5bbd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 282, "license_type": "permissive", "max_line_length": 79, "num_lines": 13, "path": "/compilation_tests/write_read_intersection.cpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#include <alia/signals.hpp>\n\nusing namespace alia;\n\nvoid\nf()\n{\n signal_direction_intersection<write_only_signal, bidirectional_signal>::\n type();\n#ifdef ALIA_TEST_COMPILATION_FAILURE\n signal_direction_intersection<write_only_signal, read_only_signal>::type();\n#endif\n}\n" }, { "alpha_fraction": 0.7048348784446716, "alphanum_fraction": 0.709367573261261, "avg_line_length": 40.36606979370117, "blob_id": "9355f0a10fec61be27a7f2d624ec3e08a84c72f0", "content_id": "e22f97b2aff597465504a91ed5cf981e18f3f0e3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 9266, "license_type": "permissive", "max_line_length": 170, "num_lines": 224, "path": "/CMakeLists.txt", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8.12)\n\nset(CMAKE_CXX_STANDARD 14)\n\nenable_testing()\n\n# Set up fips.\nget_filename_component(FIPS_ROOT_DIR \"../fips\" ABSOLUTE)\ninclude(\"${FIPS_ROOT_DIR}/cmake/fips.cmake\")\nset(FIPS_EXCEPTIONS ON)\nset(FIPS_RTTI ON)\nfips_setup()\nfips_project(alia)\n\n# Run Conan to install external C++ libraries.\n# Conan and fips disagree on various build options, so we need to override\n# some of Conan's defaults.\nset(CONAN_OPTIONS)\nif(FIPS_MSVC)\n if(CMAKE_BUILD_TYPE STREQUAL \"Debug\")\n set(CONAN_OPTIONS\n -s compiler=Visual\\ Studio -s build_type=Debug -s compiler.runtime=MTd)\n else()\n set(CONAN_OPTIONS\n -s compiler=Visual\\ Studio -s build_type=Release -s compiler.runtime=MT)\n endif()\nelseif(FIPS_GCC)\n if(CMAKE_BUILD_TYPE STREQUAL \"Debug\")\n set(CONAN_OPTIONS\n -s compiler=gcc -s compiler.libcxx=libstdc++11 -s build_type=Debug -o Boost:fPIC=True)\n else()\n set(CONAN_OPTIONS\n -s compiler=gcc -s compiler.libcxx=libstdc++11 -s build_type=Release -o Boost:fPIC=True)\n endif()\nelseif(FIPS_CLANG)\n string(REGEX REPLACE \"([0-9]+\\\\.[0-9]+).*\" \"\\\\1\" CLANG_MAJOR_MINOR_VERSION ${CMAKE_CXX_COMPILER_VERSION})\n if (CMAKE_BUILD_TYPE STREQUAL \"Debug\")\n set(CONAN_OPTIONS\n -s compiler=clang -s compiler.version=${CLANG_MAJOR_MINOR_VERSION} -s compiler.libcxx=libstdc++11 -s build_type=Debug -o Boost:fPIC=True)\n else()\n set(CONAN_OPTIONS\n -s compiler=clang -s compiler.version=${CLANG_MAJOR_MINOR_VERSION} -s compiler.libcxx=libstdc++11 -s build_type=Release -o Boost:fPIC=True)\n endif()\nendif()\nexecute_process(\n COMMAND conan install ${PROJECT_SOURCE_DIR} ${CONAN_OPTIONS} -e CONAN_IMPORT_PATH=${FIPS_PROJECT_DEPLOY_DIR} --build missing\n WORKING_DIRECTORY ${PROJECT_BINARY_DIR}\n RESULT_VARIABLE CONAN_RESULT)\nif(NOT ${CONAN_RESULT} EQUAL 0)\n message(FATAL_ERROR \"Conan failed.\")\nendif()\n\n# And now set up CMake to use those libraries.\n# Note that Conan seems to insert flags that don't make sense and cause warnings.\nset(ORIGINAL_CXX_FLAGS \"${CMAKE_CXX_FLAGS}\")\ninclude(${PROJECT_BINARY_DIR}/conanbuildinfo.cmake)\nconan_basic_setup()\nset(CMAKE_CXX_FLAGS \"${ORIGINAL_CXX_FLAGS}\")\n\n# Register Conan's include directories with fips.\nfips_include_directories(${CONAN_INCLUDE_DIRS}\n \"$<$<CONFIG:Release>:${CONAN_INCLUDE_DIRS_RELEASE}>\"\n \"$<$<CONFIG:Debug>:${CONAN_INCLUDE_DIRS_DEBUG}>\")\n# And remember the libs that it wants to link against.\nset(EXTERNAL_LIBS ${CONAN_LIBS})\n\n# If we're running on AppVeyor, we omit Boost from Conan and just use the one\n# that AppVeyor supplies. (This saves a lot of time and frustration.)\nif(DEFINED ENV{APPVEYOR})\n find_package(Boost REQUIRED COMPONENTS program_options)\n fips_include_directories(${Boost_INCLUDE_DIRS})\n list(APPEND EXTERNAL_LIBS ${Boost_LIBRARIES})\nendif()\n\nfips_include_directories(${PROJECT_SOURCE_DIR}/src)\n\n# MACRO - Add the given linker options on anything that gets linked.\nmacro(add_link_options )\n string(REPLACE \";\" \" \" OPTIONS \"${ARGV}\")\n set(CMAKE_MODULE_LINKER_FLAGS \"${CMAKE_MODULE_LINKER_FLAGS} ${OPTIONS}\")\n set(CMAKE_EXE_LINKER_FLAGS \"${CMAKE_EXE_LINKER_FLAGS} ${OPTIONS}\")\n set(CMAKE_STATIC_LINKER_FLAGS \"${CMAKE_STATIC_LINKER_FLAGS} ${OPTIONS}\")\n set(CMAKE_SHARED_LINKER_FLAGS \"${CMAKE_SHARED_LINKER_FLAGS} ${OPTIONS}\")\nendmacro()\n\n# MACRO - Add the given linker options for executables.\nmacro(add_exe_link_options )\n string(REPLACE \";\" \" \" OPTIONS \"${ARGV}\")\n set(CMAKE_EXE_LINKER_FLAGS \"${CMAKE_EXE_LINKER_FLAGS} ${OPTIONS}\")\nendmacro()\n\n# Enable a high level of compiler warnings and treat them as errors.\nif(FIPS_GCC)\n add_compile_options(-Wall -Werror)\n # Disable warnings that are too strict.\n # Warnings about suggested parentheses occur naturally when using Catch.\n add_compile_options(-Wno-parentheses)\n # unused function parameters\n add_compile_options(-Wno-unused-function)\nelseif(FIPS_MSVC)\n # First strip out the old warning level.\n string(REPLACE \"/W3\" \"\" CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS})\n add_compile_options(/W4 /WX)\n # Disable warnings that are too strict.\n # \"unreferenced formal parameter\"\n add_compile_options(/wd4100)\n # \"declaration hides previous local declaration\"\n add_compile_options(/wd4456)\n # \"unreferenced local function has been removed\"\n add_compile_options(/wd4505)\n # warnings about functions that are potentially insecure\n add_definitions(/D_CRT_SECURE_NO_WARNINGS)\n # Also suppress linker warnings about missing .pdb files that seem to inevitably creep in.\n add_link_options(/ignore:4099)\nelseif(FIPS_CLANG)\n add_compile_options(-Wall -Werror)\n add_compile_options(-Wno-logical-op-parentheses)\nendif()\n\n# Enable \"big objects\" for Visual C++ and try to speed up builds.\nif(FIPS_MSVC)\n add_compile_options(/bigobj)\n add_exe_link_options(/Debug:FASTLINK)\nendif()\n\n# Set build options for instrumenting test coverage.\nif(FIPS_CLANG AND CMAKE_BUILD_TYPE STREQUAL \"Debug\")\n message(STATUS \"Enabling gcov support\")\n add_compile_options(-DLLVM_USE_LINKER=gold -fprofile-instr-generate -fcoverage-mapping)\n add_exe_link_options(-fprofile-instr-generate -fcoverage-mapping)\nendif()\n\n# Add the alia library.\nfips_begin_lib(alia)\n fips_src(src/alia)\n fips_dir(.)\nfips_end_lib()\ntarget_link_libraries(alia ${EXTERNAL_LIBS})\n\n# Add the unit test runner.\nfips_begin_app(unit_test_runner cmdline)\n fips_deps(alia)\n fips_src(unit_tests)\nfips_end_app()\n\n# Add tests that are supposed to cause compilation errors.\n# Specifically, find all .cpp files in the compilation_tests/ directory and\n# generate test cases that try to compile them once with\n# ALIA_TEST_COMPILATION_FAILURE #defined and once without it. The files are\n# expected to compile successfully without the #define but generate a\n# compilation error when the #define is provided.\nfile(GLOB_RECURSE COMPILATION_TEST_FILES \"compilation_tests/*.cpp\")\nset(COMPILATION_TEST_SCRIPT\n \"${PROJECT_BINARY_DIR}/invoke_compilation_tests.cmake\")\nfile(WRITE ${COMPILATION_TEST_SCRIPT} \"\")\nget_target_property(COMPILE_DEFS unit_test_runner COMPILE_DEFINITIONS)\nforeach(TEST_FILE ${COMPILATION_TEST_FILES})\n get_filename_component(TEST_NAME ${TEST_FILE} NAME_WE)\n\n # We implement these tests by creating libraries that are built from the\n # source file in question. Then we create actual CMake test cases that try\n # to build those targets.\n\n # This is the \"control\" case (which omits the error and should build).\n fips_begin_lib(${TEST_NAME}_control)\n fips_deps(alia)\n fips_files(${TEST_FILE})\n fips_end_lib()\n set_target_properties(${TEST_NAME}_control PROPERTIES EXCLUDE_FROM_ALL 1 EXCLUDE_FROM_DEFAULT_BUILD 1)\n add_test(NAME ${TEST_NAME}_control\n COMMAND ${CMAKE_COMMAND} --build . --target ${TEST_NAME}_control\n WORKING_DIRECTORY ${PROJECT_BINARY_DIR})\n\n # This is the actual failure case.\n fips_begin_lib(${TEST_NAME})\n fips_deps(alia)\n fips_files(${TEST_FILE})\n fips_end_lib()\n target_compile_definitions(\n ${TEST_NAME} PRIVATE ALIA_TEST_COMPILATION_FAILURE)\n set_target_properties(${TEST_NAME} PROPERTIES EXCLUDE_FROM_ALL 1 EXCLUDE_FROM_DEFAULT_BUILD 1)\n add_test(NAME ${TEST_NAME}\n COMMAND ${CMAKE_COMMAND} --build . --target ${TEST_NAME}\n WORKING_DIRECTORY ${PROJECT_BINARY_DIR})\n set_tests_properties(${TEST_NAME} PROPERTIES WILL_FAIL TRUE)\nendforeach()\n\n# Add a target for running the unit tests.\nadd_custom_target(\n unit_tests\n # Create a fresh 'unit-testing' directory within the build dir and run the\n # tests with that. (Some of them perform file I/O.)\n COMMAND ${CMAKE_COMMAND} -E remove_directory unit-testing\n COMMAND ${CMAKE_COMMAND} -E make_directory unit-testing\n COMMAND ${CMAKE_COMMAND} -E chdir unit-testing ${CMAKE_COMMAND} -E env ALIA_DEPLOY_DIR=${FIPS_PROJECT_DEPLOY_DIR} ${FIPS_PROJECT_DEPLOY_DIR}/unit_test_runner\n WORKING_DIRECTORY ${PROJECT_BINARY_DIR}\n DEPENDS unit_test_runner)\n\n# On Linux debug builds, the proper CMake test associated with the unit tests\n# includes test coverage reporting.\nif(FIPS_CLANG AND CMAKE_BUILD_TYPE STREQUAL \"Debug\")\n add_custom_target(\n unit_test_coverage\n COMMAND ${CMAKE_COMMAND} --build . --target unit_tests\n COMMAND llvm-profdata-${CLANG_MAJOR_MINOR_VERSION} merge -sparse unit-testing/default.profraw -o default.profdata\n COMMAND llvm-cov-${CLANG_MAJOR_MINOR_VERSION} show -instr-profile=default.profdata ${FIPS_PROJECT_DEPLOY_DIR}/unit_test_runner >${PROJECT_SOURCE_DIR}/coverage.txt\n WORKING_DIRECTORY ${PROJECT_BINARY_DIR})\n add_test(\n NAME unit_test_coverage\n COMMAND ${CMAKE_COMMAND} --build . --target unit_test_coverage\n WORKING_DIRECTORY ${PROJECT_BINARY_DIR})\nelse()\n add_test(\n NAME unit_tests\n COMMAND ${CMAKE_COMMAND} --build . --target unit_tests\n WORKING_DIRECTORY ${PROJECT_BINARY_DIR})\nendif()\n\n# CMake doesn't seem to generate a test target in some cases (which I haven't\n# quite figured out), so generate a custom one.\nadd_custom_target(\n ctest\n COMMAND ctest -C ${CMAKE_BUILD_TYPE}\n WORKING_DIRECTORY ${PROJECT_BINARY_DIR})\n" }, { "alpha_fraction": 0.7100663781166077, "alphanum_fraction": 0.7108792662620544, "avg_line_length": 44.00609588623047, "blob_id": "61cb9c6d3746a51d3d9363fa5e780d4006068761", "content_id": "966d9e1de009771cfdb7710197f3f57eb5862f5f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7381, "license_type": "permissive", "max_line_length": 80, "num_lines": 164, "path": "/unit_tests/static_component_collections.cpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#include <alia/component_collection.hpp>\n\n#include <catch2/catch.hpp>\n\n#include <boost/any.hpp>\n\nusing namespace alia;\n\n// component_collection.hpp is supposed to define this by default.\n#ifndef ALIA_STATIC_COMPONENT_CHECKING\n#error ALIA_STATIC_COMPONENT_CHECKING not defined\n#endif\n\n// Define some arbitrary tag and data types.\nstruct foo_tag\n{\n};\nstruct foo\n{\n bool b = false;\n};\nstruct bar_tag\n{\n};\nstruct bar\n{\n int i = 0;\n bar()\n {\n }\n bar(int i) : i(i)\n {\n }\n};\nstruct zap_tag\n{\n};\nstruct zap\n{\n double d = 0;\n};\n\n// Test the underlying mechanics of adding and removing components from lists.\nnamespace list_tests {\nusing namespace detail;\nusing list_empty = component_list<>;\nstatic_assert(!component_list_contains_tag<list_empty, foo_tag>::value, \"\");\nusing list_b = add_component_to_list<list_empty, component<bar_tag, bar>>::type;\nstatic_assert(!component_list_contains_tag<list_b, foo_tag>::value, \"\");\nstatic_assert(component_list_contains_tag<list_b, bar_tag>::value, \"\");\nusing list_fb = add_component_to_list<list_b, component<foo_tag, foo>>::type;\nstatic_assert(component_list_contains_tag<list_fb, foo_tag>::value, \"\");\nstatic_assert(component_list_contains_tag<list_fb, bar_tag>::value, \"\");\nusing list_f = remove_component_from_list<list_fb, bar_tag>::type;\nstatic_assert(component_list_contains_tag<list_f, foo_tag>::value, \"\");\nstatic_assert(!component_list_contains_tag<list_f, bar_tag>::value, \"\");\nusing list_zfb = add_component_to_list<list_fb, component<zap_tag, zap>>::type;\nstatic_assert(component_list_contains_tag<list_zfb, foo_tag>::value, \"\");\nstatic_assert(component_list_contains_tag<list_zfb, bar_tag>::value, \"\");\nstatic_assert(component_list_contains_tag<list_zfb, zap_tag>::value, \"\");\nusing list_zb = remove_component_from_list<list_zfb, foo_tag>::type;\nstatic_assert(!component_list_contains_tag<list_zb, foo_tag>::value, \"\");\nstatic_assert(component_list_contains_tag<list_zb, bar_tag>::value, \"\");\nstatic_assert(component_list_contains_tag<list_zb, zap_tag>::value, \"\");\nusing list_z = remove_component_from_list<list_zb, bar_tag>::type;\nstatic_assert(!component_list_contains_tag<list_z, foo_tag>::value, \"\");\nstatic_assert(!component_list_contains_tag<list_z, bar_tag>::value, \"\");\nstatic_assert(component_list_contains_tag<list_z, zap_tag>::value, \"\");\nusing list_fbz = merge_component_lists<list_fb, list_zb>::type;\nstatic_assert(component_list_contains_tag<list_fbz, foo_tag>::value, \"\");\nstatic_assert(component_list_contains_tag<list_fbz, bar_tag>::value, \"\");\nstatic_assert(component_list_contains_tag<list_fbz, zap_tag>::value, \"\");\nusing list_bf = merge_component_lists<list_b, list_f>::type;\nstatic_assert(component_list_contains_tag<list_bf, foo_tag>::value, \"\");\nstatic_assert(component_list_contains_tag<list_bf, bar_tag>::value, \"\");\nstatic_assert(!component_list_contains_tag<list_bf, zap_tag>::value, \"\");\nusing list_b_ = merge_component_lists<list_b, list_b>::type;\nstatic_assert(!component_list_contains_tag<list_b_, foo_tag>::value, \"\");\nstatic_assert(component_list_contains_tag<list_b_, bar_tag>::value, \"\");\nstatic_assert(!component_list_contains_tag<list_b_, zap_tag>::value, \"\");\nusing list_f_ = merge_component_lists<list_f, list_empty>::type;\nstatic_assert(component_list_contains_tag<list_f_, foo_tag>::value, \"\");\nstatic_assert(!component_list_contains_tag<list_f_, bar_tag>::value, \"\");\nstatic_assert(!component_list_contains_tag<list_f_, zap_tag>::value, \"\");\nusing list_z_ = merge_component_lists<list_empty, list_z>::type;\nstatic_assert(!component_list_contains_tag<list_z_, foo_tag>::value, \"\");\nstatic_assert(!component_list_contains_tag<list_z_, bar_tag>::value, \"\");\nstatic_assert(component_list_contains_tag<list_z_, zap_tag>::value, \"\");\n} // namespace list_tests\n\n// Define some arbitrary component collection types.\nusing storage_type = generic_component_storage<boost::any>;\nusing cc_empty = empty_component_collection<storage_type>;\nusing cc_b = add_component_type_t<cc_empty, bar_tag, bar>;\nusing cc_fb = add_component_type_t<cc_b, foo_tag, foo>;\nusing cc_z = add_component_type_t<cc_empty, zap_tag, zap>;\nusing cc_bz = add_component_type_t<cc_z, bar_tag, bar>;\nusing cc_fbz = add_component_type_t<cc_bz, foo_tag, foo>;\nusing cc_fz = remove_component_type_t<cc_fbz, bar_tag>;\nusing cc_f = add_component_type_t<cc_empty, foo_tag, foo>;\nusing cc_fzb = merge_components_t<cc_fz, cc_bz>;\n\n// Test the underlying type functions on component collections.\nnamespace cc_type_tests {\nusing namespace detail;\n// detail::component_collection_contains_tag tests\nstatic_assert(component_collection_contains_tag<cc_fb, foo_tag>::value, \"\");\nstatic_assert(component_collection_contains_tag<cc_fb, bar_tag>::value, \"\");\nstatic_assert(!component_collection_contains_tag<cc_fb, foo>::value, \"\");\nstatic_assert(!component_collection_contains_tag<cc_fb, zap_tag>::value, \"\");\n// detail::collection_contains_component tests\nstatic_assert(\n collection_contains_component<cc_fb, component<foo_tag, foo>>::value, \"\");\nstatic_assert(\n collection_contains_component<cc_fb, component<bar_tag, bar>>::value, \"\");\nstatic_assert(\n !collection_contains_component<cc_fb, component<zap_tag, zap>>::value, \"\");\nstatic_assert(\n collection_contains_component<cc_fz, component<foo_tag, foo>>::value, \"\");\nstatic_assert(\n !collection_contains_component<cc_fz, component<bar_tag, bar>>::value, \"\");\nstatic_assert(\n collection_contains_component<cc_fz, component<zap_tag, zap>>::value, \"\");\n// detail::component_collection_is_convertible tests\nstatic_assert(component_collection_is_convertible<cc_fb, cc_fb>::value, \"\");\nstatic_assert(component_collection_is_convertible<cc_b, cc_b>::value, \"\");\nstatic_assert(component_collection_is_convertible<cc_fbz, cc_fbz>::value, \"\");\nstatic_assert(component_collection_is_convertible<cc_fb, cc_b>::value, \"\");\nstatic_assert(!component_collection_is_convertible<cc_b, cc_fb>::value, \"\");\nstatic_assert(component_collection_is_convertible<cc_fbz, cc_fb>::value, \"\");\nstatic_assert(!component_collection_is_convertible<cc_fb, cc_fbz>::value, \"\");\nstatic_assert(component_collection_is_convertible<cc_fbz, cc_b>::value, \"\");\nstatic_assert(!component_collection_is_convertible<cc_b, cc_fbz>::value, \"\");\nstatic_assert(component_collection_is_convertible<cc_fzb, cc_fz>::value, \"\");\nstatic_assert(component_collection_is_convertible<cc_fzb, cc_bz>::value, \"\");\n} // namespace cc_type_tests\n\nTEST_CASE(\"static component_collection conversions\", \"[component_collections]\")\n{\n storage_type storage;\n cc_fb mc_fb(&storage);\n REQUIRE(mc_fb.storage == &storage);\n cc_b mc_b(mc_fb);\n REQUIRE(mc_b.storage == &storage);\n}\n\nTEST_CASE(\"static component access\", \"[component_collections]\")\n{\n storage_type storage_empty;\n cc_empty mc_empty(&storage_empty);\n\n storage_type storage_b;\n cc_b mc_b = add_component<bar_tag>(&storage_b, mc_empty, bar(1));\n REQUIRE(boost::any_cast<bar>(get_component<bar_tag>(mc_b)).i == 1);\n\n storage_type storage_fb;\n cc_fb mc_fb = add_component<foo_tag>(&storage_fb, mc_b, foo());\n REQUIRE(boost::any_cast<bar>(get_component<bar_tag>(mc_fb)).i == 1);\n REQUIRE(boost::any_cast<foo>(get_component<foo_tag>(mc_fb)).b == false);\n\n storage_type storage_f;\n cc_f mc_f = remove_component<bar_tag>(&storage_f, mc_fb);\n REQUIRE(boost::any_cast<foo>(get_component<foo_tag>(mc_f)).b == false);\n}\n" }, { "alpha_fraction": 0.43478259444236755, "alphanum_fraction": 0.43478259444236755, "avg_line_length": 21, "blob_id": "4256b1131f9553b111be6b7c7a32f72088c7e627", "content_id": "8a51c3310b6e74cd695d8b986ea0b185d5911aa2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 46, "license_type": "permissive", "max_line_length": 21, "num_lines": 2, "path": "/docs/the-basics/introductory-examples.rst", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "Introductory Examples\n=====================\n\n\n" }, { "alpha_fraction": 0.761904776096344, "alphanum_fraction": 0.761904776096344, "avg_line_length": 17, "blob_id": "316d97055b2f3f9ecae0b0f9c2f1012a4593c6b1", "content_id": "d22610c095ef8e09a386aa9bc65a0fed85c7112a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 126, "license_type": "permissive", "max_line_length": 33, "num_lines": 7, "path": "/src/alia/signals.hpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#ifndef ALIA_SIGNALS_HPP\n#define ALIA_SIGNALS_HPP\n\n#include <alia/signals/basic.hpp>\n#include <alia/signals/core.hpp>\n\n#endif\n" }, { "alpha_fraction": 0.5967296957969666, "alphanum_fraction": 0.5968595147132874, "avg_line_length": 30.10292625427246, "blob_id": "9508f0a03b8d36d7e51fe507d21c3a305a41e741", "content_id": "607a8649a519031609f39080549e54d103871b1d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 30823, "license_type": "permissive", "max_line_length": 80, "num_lines": 991, "path": "/src/alia/data_graph.hpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#ifndef ALIA_DATA_GRAPH_HPP\n#define ALIA_DATA_GRAPH_HPP\n\n#include <alia/common.hpp>\n#include <alia/id.hpp>\n#include <alia/signals.hpp>\n#include <cassert>\n\n// This file defines the data retrieval library used for associating mutable\n// state and cached data with alia content graphs. It is designed so that each\n// node emitted by an application is associated with a unique instance of data,\n// even if there is no specific external identifier for that node.\n//\n// More generally, if you replace \"node\" with \"subexpression evaluation\" in the\n// previous sentence, it can be used to associate data with particular points in\n// the evaluation of any function. This can be useful in situations where you\n// need to evaluate a particular function many times with slightly different\n// inputs and you want to reuse the work that was done in earlier evaluations\n// without a lot of manual bookkeeping.\n//\n// To understand what's going on here, imagine the evaluation of a function on\n// a simple in-order, single-threaded processor. We can represent all possible\n// execution flows using a single DAG where each node represents the execution\n// of a particular instruction by the processor and edges represent the\n// transition to the next instruction. Nodes with multiple edges leaving them\n// represent the execution of branch instructions, while nodes with multiple\n// edges coming in are points where multiple branches merge back into a single\n// flow.\n//\n// Since the graph is a DAG, loops are represented by unrolling them.\n// Similarly, function calls are represented by inlining the callee's graph\n// into the caller's graph (with appropriate argument substitutions).\n// Note that both of these features make the graph potentially infinite.\n// Furthermore, if calls to function pointers are involved, parts of the graph\n// may be entirely unknown.\n//\n// Thus, for an arbitrary function, we cannot construct its graph a priori.\n// However, we CAN observe a particular evaluation of the function and\n// construct its path through the graph. We can also observe multiple\n// evaluations and construct the portion of the DAG that these executions\n// cover. In other words, if we're only interested in portions of the graph\n// that are reached by actual evaluations of the function, we can lazily\n// construct them by simply observing those evaluations.\n//\n// And that is essentially what this library does. In order to use it, you\n// must annotate the control flow in your function, and it uses these\n// annotations to trace each evaluation's flow through the graph, constructing\n// unexplored regions as they're encountered. The graph is used to store data\n// that is made available to your function as it executes.\n//\n// One problem with all this is that sometimes a subexpression evaluation\n// (content node) is associated with a particular piece of input data and the\n// evaluation of that input data is not fixed within the graph (e.g., it's in a\n// list of items where you can remove or shuffle items). In cases like this, we\n// allow the application to attach an explicit name to the subgraph\n// representing the evaluation of that expression, and we ensure that that\n// subgraph is always used where that name is encountered.\n\nnamespace alia {\n\n// It's worth noting here that the storage of the graph is slightly different\n// from what's described above. In reality, the only nodes the library knows\n// about are the annotated branch nodes and ones where you request data.\n// Other nodes are irrelevant, and the library never knows about them.\n// Furthermore, not all edges need to be stored explicitly.\n\n// A data node is a node in the graph that represents the retrieval of data,\n// and thus it stores the data associated with that retrieval.\n// Data nodes are stored as linked lists, held by data_blocks.\n//\n// Note that a data node is capable of storing any type of data.\n// data_node is a base class for all data nodes.\n// typed_data_node<T> represents data nodes that store values of type T.\n//\nstruct data_node : noncopyable\n{\n data_node() : next(0)\n {\n }\n virtual ~data_node()\n {\n }\n data_node* next;\n};\ntemplate<class T>\nstruct typed_data_node : data_node\n{\n T value;\n};\n\nstruct named_block_ref_node;\n\n// A data_block represents a block of execution. During a single evaluation,\n// either all nodes in the block are executed or all nodes are bypassed, and, if\n// executed, they are always executed in the same order. (It's conceptually\n// similar to a 'basic block' except that other nodes may be executed in between\n// nodes in a data_block.)\nstruct data_block : noncopyable\n{\n // the list of nodes in this block\n data_node* nodes = nullptr;\n\n // a flag to track if the block's cache is clear\n bool cache_clear = true;\n\n // list of named blocks referenced from this data block - The references\n // maintain shared ownership of the named blocks. The order of the\n // references indicates the order in which the block references appeared in\n // the last pass. When the content graph is stable and this order is\n // constant, we can find the blocks with a very small, constant cost.\n named_block_ref_node* named_blocks = nullptr;\n\n ~data_block();\n};\n\n// Clear all data from a data block.\n// Note that this recursively processes child blocks.\nvoid\nclear_data_block(data_block& block);\n\nstruct naming_map_node;\n\n// data_graph stores the data graph associated with a function.\nstruct data_graph : noncopyable\n{\n data_block root_block;\n\n naming_map_node* map_list = nullptr;\n\n // This list stores unused references to named blocks. When named block\n // references disappear from a traversal, it's possible that they've done\n // so only because the traversal was interrupted by an exception.\n // Therefore, they're kept here temporarily to keep the named blocks alive\n // until a complete traversal can establish new references to the named\n // blocks. They're cleaned up when someone calls gc_named_data(graph)\n // following a complete traversal.\n named_block_ref_node* unused_named_block_refs = nullptr;\n};\n\nstruct naming_map;\n\n// data_traversal stores the state associated with a single traversal of a\n// data_graph.\nstruct data_traversal\n{\n data_graph* graph;\n naming_map* active_map;\n data_block* active_block;\n named_block_ref_node* predicted_named_block;\n named_block_ref_node* used_named_blocks;\n named_block_ref_node** named_block_next_ptr;\n data_node** next_data_ptr;\n bool gc_enabled;\n bool cache_clearing_enabled;\n};\n\n// The utilities here operate on data_traversals. However, the data_graph\n// library is intended to be used in scenarios where the data_traversal object\n// is part of a larger context. Thus, any utilities here that are intended to be\n// used directly by the application developer are designed to accept a generic\n// context parameter. The only requirement on that paramater is that it defines\n// the function get_data_traversal(ctx), which returns a reference to a\n// data_traversal.\n\n// If using this library directly, the data_traversal itself can serve as the\n// context.\ninline data_traversal&\nget_data_traversal(data_traversal& ctx)\n{\n return ctx;\n}\n\n// A scoped_data_block activates the associated data_block at the beginning\n// of its scope and deactivates it at the end. It's useful anytime there is a\n// branch in the code and you need to activate the block associated with the\n// taken branch while that branch is active.\n// Note that the macros defined below make heavy use of this and reduce the\n// need for applications to use it directly.\nstruct scoped_data_block : noncopyable\n{\n scoped_data_block() : traversal_(0)\n {\n }\n\n template<class Context>\n scoped_data_block(Context& ctx, data_block& block)\n {\n begin(ctx, block);\n }\n\n ~scoped_data_block()\n {\n end();\n }\n\n template<class Context>\n void\n begin(Context& ctx, data_block& block)\n {\n begin(get_data_traversal(ctx), block);\n }\n\n void\n begin(data_traversal& traversal, data_block& block);\n\n void\n end();\n\n private:\n data_traversal* traversal_;\n // old state\n data_block* old_active_block_;\n named_block_ref_node* old_predicted_named_block_;\n named_block_ref_node* old_used_named_blocks_;\n named_block_ref_node** old_named_block_next_ptr_;\n data_node** old_next_data_ptr_;\n};\n\n// A named_block is like a scoped_data_block, but instead of supplying a\n// data_block directly, you provide an ID, and it finds the block associated\n// with that ID and activates it.\n//\n// This is the mechanism for dealing with dynamically ordered data.\n// named_blocks are free to move around within the graph as long as they\n// maintain the same IDs.\n//\n// A naming_context provides a context for IDs. IDs used within one naming\n// context can be reused within another without conflict.\n//\n// named_blocks are automatically garbage collected when the library detects\n// that they've disappeared from the graph. The logic for this is fairly\n// sophisticated, and it generally won't mistakingly collect named_blocks in\n// inactive regions of the graph. However, it still may not always do what you\n// want.\n// In those cases, you can specify the manual_delete flag. This will prevent\n// the library from collecting the block. It can be deleted manually by calling\n// delete_named_data(ctx, id). If that never happens, it will be deleted when\n// its context is destroyed.\n\n// The flag is specified via its own structure to make it very obvious at the\n// call site.\nstruct manual_delete\n{\n explicit manual_delete(bool value) : value(value)\n {\n }\n bool value;\n};\n\nstruct named_block : noncopyable\n{\n named_block()\n {\n }\n\n template<class Context>\n named_block(\n Context& ctx,\n id_interface const& id,\n manual_delete manual = manual_delete(false))\n {\n begin(ctx, id, manual);\n }\n\n template<class Context>\n void\n begin(\n Context& ctx,\n id_interface const& id,\n manual_delete manual = manual_delete(false))\n {\n begin(get_data_traversal(ctx), get_naming_map(ctx), id, manual);\n }\n\n void\n begin(\n data_traversal& traversal,\n naming_map& map,\n id_interface const& id,\n manual_delete manual);\n\n void\n end();\n\n private:\n scoped_data_block scoped_data_block_;\n};\n\nstruct naming_context : noncopyable\n{\n naming_context()\n {\n }\n\n template<class Context>\n naming_context(Context& ctx)\n {\n begin(ctx);\n }\n\n ~naming_context()\n {\n end();\n }\n\n template<class Context>\n void\n begin(Context& ctx)\n {\n begin(get_data_traversal(ctx));\n }\n\n void\n begin(data_traversal& traversal);\n\n void\n end()\n {\n }\n\n data_traversal&\n traversal()\n {\n return *traversal_;\n }\n naming_map&\n map()\n {\n return *map_;\n }\n\n private:\n data_traversal* traversal_;\n naming_map* map_;\n};\ninline data_traversal&\nget_data_traversal(naming_context& ctx)\n{\n return ctx.traversal();\n}\ninline naming_map&\nget_naming_map(naming_context& ctx)\n{\n return ctx.map();\n}\n\n// retrieve_naming_map gets a data_map from a data_traveral and registers it\n// with the underlying graph. It can be used to retrieve additional naming maps\n// from a data graph, in case you want to manage them yourself.\nnaming_map*\nretrieve_naming_map(data_traversal& traversal);\n\n// delete_named_block(ctx, id) deletes the data associated with a particular\n// named block, as identified by the given ID.\n\nvoid\ndelete_named_block(data_graph& graph, id_interface const& id);\n\ntemplate<class Context>\nvoid\ndelete_named_block(Context& ctx, id_interface const& id)\n{\n delete_named_block(*get_data_traversal(ctx).graph, id);\n}\n\n// This is a macro that, given a context, an uninitialized named_block, and an\n// ID, combines the ID with another ID which is unique to that location in the\n// code (but not the graph), and then initializes the named_block with the\n// combined ID.\n// This is not as generally useful as naming_context, but it can be used to\n// identify the combinaion of a function and its argument.\n#define ALIA_BEGIN_LOCATION_SPECIFIC_NAMED_BLOCK(ctx, named_block, id) \\\n { \\\n static int _alia_dummy_static; \\\n named_block.begin(ctx, combine_ids(make_id(&_alia_dummy_static), id)); \\\n }\n\n// disable_gc(traversal) disables the garbage collector for a data traversal.\n// It's used when you don't intend to visit the entire active part of the graph\n// and thus don't want the garbage collector to collect the unvisited parts.\n// It should be invoked before actually beginning a traversal.\n// When using this, if you visit named blocks, you must visit all blocks in a\n// data_block in the same order that they were last visited with the garbage\n// collector enabled. However, you don't have to finish the entire sequence.\n// If you violate this rule, you'll get a named_block_out_of_order exception.\nstruct named_block_out_of_order : exception\n{\n named_block_out_of_order()\n : exception(\"named block order must remain constant with GC disabled\")\n {\n }\n};\nvoid\ndisable_gc(data_traversal& traversal);\n\n// scoped_cache_clearing_disabler will prevent the library from clearing the\n// cache of inactive blocks within its scope.\nstruct scoped_cache_clearing_disabler\n{\n scoped_cache_clearing_disabler() : traversal_(0)\n {\n }\n template<class Context>\n scoped_cache_clearing_disabler(Context& ctx)\n {\n begin(ctx);\n }\n ~scoped_cache_clearing_disabler()\n {\n end();\n }\n template<class Context>\n void\n begin(Context& ctx)\n {\n begin(get_data_traversal(ctx));\n }\n void\n begin(data_traversal& traversal);\n void\n end();\n\n private:\n data_traversal* traversal_;\n bool old_cache_clearing_state_;\n};\n\n// get_data(traversal, &ptr) represents a data node in the data graph.\n// The call retrieves data from the graph at the current point in the\n// traversal, assigns its address to *ptr, and advances the traversal to the\n// next node.\n// The return value is true if the data at the node was just constructed and\n// false if it already existed.\n//\n// Note that get_data should normally not be used directly by the application.\n\ntemplate<class Context, class T>\nbool\nget_data(Context& ctx, T** ptr)\n{\n data_traversal& traversal = get_data_traversal(ctx);\n data_node* node = *traversal.next_data_ptr;\n if (node)\n {\n if (!dynamic_cast<typed_data_node<T>*>(node))\n assert(dynamic_cast<typed_data_node<T>*>(node));\n typed_data_node<T>* typed_node = static_cast<typed_data_node<T>*>(node);\n traversal.next_data_ptr = &node->next;\n *ptr = &typed_node->value;\n return false;\n }\n else\n {\n typed_data_node<T>* new_node = new typed_data_node<T>;\n *traversal.next_data_ptr = new_node;\n traversal.next_data_ptr = &new_node->next;\n *ptr = &new_node->value;\n return true;\n }\n}\n\n// get_cached_data(ctx, &ptr) is identical to get_data(ctx, &ptr), but the\n// data stored in the node is understood to be a cached value of data that's\n// generated by the application. The system assumes that the data can be\n// regenerated if it's lost.\n\nstruct cached_data\n{\n virtual ~cached_data()\n {\n }\n};\n\ntemplate<class T>\nstruct typed_cached_data : cached_data\n{\n T value;\n};\n\nstruct cached_data_holder\n{\n cached_data_holder() : data(0)\n {\n }\n ~cached_data_holder()\n {\n delete data;\n }\n cached_data* data;\n};\n\ntemplate<class Context, class T>\nbool\nget_cached_data(Context& ctx, T** ptr)\n{\n cached_data_holder* holder;\n get_data(ctx, &holder);\n if (holder->data)\n {\n assert(dynamic_cast<typed_cached_data<T>*>(holder->data));\n typed_cached_data<T>* data\n = static_cast<typed_cached_data<T>*>(holder->data);\n *ptr = &data->value;\n return false;\n }\n typed_cached_data<T>* data = new typed_cached_data<T>;\n holder->data = data;\n *ptr = &data->value;\n return true;\n}\n\n// Clear all cached data stored within a data block.\n// Note that this recursively processes child blocks.\nvoid\nclear_cached_data(data_block& block);\n\n// get_keyed_data(ctx, key, &signal) is a utility for retrieving cached data\n// from a data graph.\n// It stores not only the data but also a key that identifies the data.\n// The key is presented at each retrieval, and if it changes, the associated\n// data is invalidated and must be recomputed.\n\n// The return value is true iff the data needs to be recomputed.\n\ntemplate<class Data>\nstruct keyed_data\n{\n captured_id key;\n bool is_valid;\n Data value;\n keyed_data() : is_valid(false)\n {\n }\n};\n\ntemplate<class Data>\nbool\nis_valid(keyed_data<Data> const& data)\n{\n return data.is_valid;\n}\n\ntemplate<class Data>\nvoid\ninvalidate(keyed_data<Data>& data)\n{\n data.is_valid = false;\n data.key.clear();\n}\n\ntemplate<class Data>\nvoid\nmark_valid(keyed_data<Data>& data)\n{\n data.is_valid = true;\n}\n\ntemplate<class Data>\nbool\nrefresh_keyed_data(keyed_data<Data>& data, id_interface const& key)\n{\n if (!data.key.matches(key))\n {\n data.is_valid = false;\n data.key.capture(key);\n return true;\n }\n return false;\n}\n\ntemplate<class Data>\nvoid\nset(keyed_data<Data>& data, Data const& value)\n{\n data.value = value;\n mark_valid(data);\n}\n\ntemplate<class Data>\nData const&\nget(keyed_data<Data> const& data)\n{\n assert(is_valid(data));\n return data.value;\n}\n\ntemplate<class Data>\nstruct keyed_data_signal\n : signal<keyed_data_signal<Data>, Data, bidirectional_signal>\n{\n keyed_data_signal()\n {\n }\n keyed_data_signal(keyed_data<Data>* data) : data_(data)\n {\n }\n bool\n is_readable() const\n {\n return data_->is_valid;\n }\n Data const&\n read() const\n {\n return data_->value;\n }\n id_interface const&\n value_id() const\n {\n return data_->key.is_initialized() ? data_->key.get() : no_id;\n }\n bool\n is_writable() const\n {\n return true;\n }\n void\n write(Data const& value) const\n {\n alia::set(*data_, value);\n }\n\n private:\n keyed_data<Data>* data_;\n};\n\ntemplate<class Data>\nkeyed_data_signal<Data>\nmake_signal(keyed_data<Data>* data)\n{\n return keyed_data_signal<Data>(data);\n}\n\ntemplate<class Context, class Data>\nbool\nget_keyed_data(\n Context& ctx, id_interface const& key, keyed_data_signal<Data>* signal)\n{\n keyed_data<Data>* ptr;\n get_cached_data(ctx, &ptr);\n refresh_keyed_data(*ptr, key);\n *signal = make_signal(ptr);\n return !is_valid(*ptr);\n};\n\n// This is another form of get_keyed_data where there's no signal to guard\n// access to the retrieved data. Thus, it's up to the caller to track whether\n// or not the data is properly initialized.\n\ntemplate<class Data>\nstruct raw_keyed_data\n{\n captured_id key;\n Data data;\n};\n\ntemplate<class Context, class Data>\nbool\nget_keyed_data(Context& ctx, id_interface const& key, Data** data)\n{\n raw_keyed_data<Data>* ptr;\n bool is_new = false;\n if (get_cached_data(ctx, &ptr))\n {\n ptr->key.capture(key);\n is_new = true;\n }\n else if (!ptr->key.matches(key))\n {\n ptr->key.capture(key);\n ptr->data = Data();\n is_new = true;\n }\n *data = &ptr->data;\n return is_new;\n};\n\n// scoped_data_traversal can be used to manage a traversal of a graph.\n// begin(graph, traversal) will initialize traversal to act as a traversal of\n// graph.\nstruct scoped_data_traversal\n{\n scoped_data_traversal()\n {\n }\n\n scoped_data_traversal(data_graph& graph, data_traversal& traversal)\n {\n begin(graph, traversal);\n }\n\n ~scoped_data_traversal()\n {\n end();\n }\n\n void\n begin(data_graph& graph, data_traversal& traversal);\n\n void\n end();\n\n private:\n scoped_data_block root_block_;\n naming_context root_map_;\n};\n\n// The following are utilities that are used to implement the control flow\n// macros. They shouldn't be used directly by applications.\n\nstruct if_block : noncopyable\n{\n if_block(data_traversal& traversal, bool condition);\n\n private:\n scoped_data_block scoped_data_block_;\n};\n\nstruct pass_dependent_if_block : noncopyable\n{\n pass_dependent_if_block(data_traversal& traversal, bool condition);\n\n private:\n scoped_data_block scoped_data_block_;\n};\n\nstruct switch_block : noncopyable\n{\n template<class Context>\n switch_block(Context& ctx)\n {\n nc_.begin(ctx);\n }\n template<class Id>\n void\n activate_case(Id id)\n {\n active_case_.end();\n active_case_.begin(nc_, make_id(id), manual_delete(true));\n }\n\n private:\n naming_context nc_;\n named_block active_case_;\n};\n\nstruct loop_block : noncopyable\n{\n loop_block(data_traversal& traversal);\n ~loop_block();\n data_block&\n block() const\n {\n return *block_;\n }\n data_traversal&\n traversal() const\n {\n return *traversal_;\n }\n void\n next();\n\n private:\n data_traversal* traversal_;\n data_block* block_;\n};\n\n// The following are macros used to annotate control flow.\n// They are used exactly like their C equivalents, but all require an alia_end\n// after the end of their scope.\n// Also note that all come in two forms. One form ends in an underscore and\n// takes the context as its first argument. The other form has no trailing\n// underscore and assumes that the context is a variable named 'ctx'.\n\n// is_readable(x), where x is a readable signal type, calls signal_is_readable.\ntemplate<class T>\nstd::enable_if_t<is_readable_signal_type<T>::value, bool>\nis_readable(T const& x)\n{\n return signal_is_readable(x);\n}\n\n// read(x), where x is a readable signal type, calls read_signal.\ntemplate<class T>\nstd::enable_if_t<is_readable_signal_type<T>::value, typename T::value_type>\nread(T const& x)\n{\n return read_signal(x);\n}\n\n// ALIA_STRICT_CONDITIONALS disables the definitions that allow non-signals to\n// be used in if/else/switch macros.\n#ifndef ALIA_STRICT_CONDITIONALS\n\n// is_true(x) evaluates x in a boolean context.\ntemplate<class T>\nstd::enable_if_t<!is_signal_type<T>::value, bool>\nis_true(T x)\n{\n return x ? true : false;\n}\n\n// is_false(x) evaluates x in a boolean context and inverts it.\ntemplate<class T>\nstd::enable_if_t<!is_signal_type<T>::value, bool>\nis_false(T x)\n{\n return x ? false : true;\n}\n\n// is_readable(x), where x is NOT a signal type, always returns true.\ntemplate<class T>\nstd::enable_if_t<!is_signal_type<T>::value, bool>\nis_readable(T const& x)\n{\n return true;\n}\n\n// read(x), where x is NOT a signal type, simply returns x.\ntemplate<class T>\nstd::enable_if_t<!is_signal_type<T>::value, T const&>\nread(T const& x)\n{\n return x;\n}\n\n#endif\n\n// if, else_if, else\n\n#define ALIA_IF_(ctx, condition) \\\n { \\\n bool _alia_else_condition ALIA_UNUSED; \\\n { \\\n auto const& _alia_condition_value = (condition); \\\n bool _alia_if_condition = ::alia::is_true(_alia_condition_value); \\\n _alia_else_condition = ::alia::is_false(_alia_condition_value); \\\n ::alia::if_block _alia_if_block( \\\n get_data_traversal(ctx), _alia_if_condition); \\\n if (_alia_if_condition) \\\n {\n\n#define ALIA_IF(condition) ALIA_IF_(ctx, condition)\n\n#define ALIA_ELSE_IF_(ctx, condition) \\\n } \\\n } \\\n { \\\n auto const& _alia_condition_value = (condition); \\\n bool _alia_else_if_condition \\\n = _alia_else_condition && ::alia::is_true(_alia_condition_value); \\\n _alia_else_condition \\\n = _alia_else_condition && ::alia::is_false(_alia_condition_value); \\\n ::alia::if_block _alia_if_block( \\\n get_data_traversal(ctx), _alia_else_if_condition); \\\n if (_alia_else_if_condition) \\\n {\n\n#define ALIA_ELSE_IF(condition) ALIA_ELSE_IF_(ctx, condition)\n\n#define ALIA_ELSE_(ctx) \\\n } \\\n } \\\n { \\\n ::alia::if_block _alia_if_block( \\\n get_data_traversal(ctx), _alia_else_condition); \\\n if (_alia_else_condition) \\\n {\n\n#define ALIA_ELSE ALIA_ELSE_(ctx)\n\n#ifdef ALIA_LOWERCASE_MACROS\n#define alia_if_(ctx, condition) ALIA_IF_(ctx, condition)\n#define alia_if(condition) ALIA_IF(condition)\n#define alia_else_if_(ctx, condition) ALIA_ELSE_IF_(ctx, condition)\n#define alia_else_if(condition) ALIA_ELSE_IF(condition)\n#define alia_else_(ctx) ALIA_ELSE(ctx)\n#define alia_else ALIA_ELSE\n#endif\n\n// pass_dependent_if - This is used for tests that involve conditions that\n// change from one pass to another. It does not clear out cached data within\n// the block if it's skipped.\n\n#define ALIA_PASS_DEPENDENT_IF_(ctx, condition) \\\n { \\\n { \\\n bool _alia_condition = ::alia::is_true(condition); \\\n ::alia::pass_dependent_if_block _alia_if_block( \\\n get_data_traversal(ctx), _alia_condition); \\\n if (_alia_condition) \\\n {\n\n#define ALIA_PASS_DEPENDENT_IF(condition) \\\n ALIA_PASS_DEPENDENT_IF_(ctx, condition)\n\n#ifdef ALIA_LOWERCASE_MACROS\n#define alia_pass_dependent_if_(ctx, condition) \\\n ALIA_PASS_DEPENDENT_IF_(ctx, condition)\n#define alia_pass_dependent_if(condition) ALIA_PASS_DEPENDENT_IF(condition)\n#endif\n\n// switch\n\n#define ALIA_SWITCH_(ctx, x) \\\n { \\\n ::alia::switch_block _alia_switch_block(ctx); \\\n if (::alia::is_readable(x)) \\\n { \\\n switch (::alia::read(x)) \\\n {\n\n#define ALIA_SWITCH(x) ALIA_SWITCH_(ctx, x)\n\n#define ALIA_CONCATENATE_HELPER(a, b) a##b\n#define ALIA_CONCATENATE(a, b) ALIA_CONCATENATE_HELPER(a, b)\n\n#define ALIA_CASE(c) \\\n case c: \\\n _alia_switch_block.activate_case(c); \\\n goto ALIA_CONCATENATE(_alia_dummy_label_, __LINE__); \\\n ALIA_CONCATENATE(_alia_dummy_label_, __LINE__)\n\n#define ALIA_DEFAULT \\\n default: \\\n _alia_switch_block.activate_case(\"_alia_default_case\"); \\\n goto ALIA_CONCATENATE(_alia_dummy_label_, __LINE__); \\\n ALIA_CONCATENATE(_alia_dummy_label_, __LINE__)\n\n#ifdef ALIA_LOWERCASE_MACROS\n#define alia_switch_(ctx, x) ALIA_SWITCH_(ctx, x)\n#define alia_switch(x) ALIA_SWITCH(x)\n#define alia_case(c) ALIA_CASE(c)\n#define alia_default ALIA_DEFAULT\n#endif\n\n// for\n\n#define ALIA_FOR_(ctx, x) \\\n { \\\n { \\\n ::alia::loop_block _alia_looper(get_data_traversal(ctx)); \\\n for (x) \\\n { \\\n ::alia::scoped_data_block _alia_scope; \\\n _alia_scope.begin( \\\n _alia_looper.traversal(), _alia_looper.block()); \\\n _alia_looper.next();\n\n#define ALIA_FOR(x) ALIA_FOR_(ctx, x)\n\n#ifdef ALIA_LOWERCASE_MACROS\n#define alia_for_(ctx, x) ALIA_FOR_(ctx, x)\n#define alia_for(x) ALIA_FOR(x)\n#endif\n\n// while\n\n#define ALIA_WHILE_(ctx, x) \\\n { \\\n { \\\n ::alia::loop_block _alia_looper(get_data_traversal(ctx)); \\\n while (x) \\\n { \\\n ::alia::scoped_data_block _alia_scope; \\\n _alia_scope.begin( \\\n _alia_looper.traversal(), _alia_looper.block()); \\\n _alia_looper.next();\n\n#define ALIA_WHILE(x) ALIA_WHILE_(ctx, x)\n\n#ifdef ALIA_LOWERCASE_MACROS\n#define alia_while_(ctx, x) ALIA_WHILE_(ctx, x)\n#define alia_while(x) ALIA_WHILE(x)\n#endif\n\n// end\n\n#define ALIA_END \\\n } \\\n } \\\n }\n\n#ifdef ALIA_LOWERCASE_MACROS\n#define alia_end ALIA_END\n#endif\n\n} // namespace alia\n\n#endif\n" }, { "alpha_fraction": 0.6775362491607666, "alphanum_fraction": 0.6811594367027283, "avg_line_length": 11, "blob_id": "d73a17bf19db482792fd7fee132aff46a6377c6e", "content_id": "6ae73ef87384b45ceff9f8c599d44ca834d84fd9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 276, "license_type": "permissive", "max_line_length": 37, "num_lines": 23, "path": "/compilation_tests/invalid_signal_argument.cpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#include <alia/signals.hpp>\n\nusing namespace alia;\n\nvoid\nf_input(input<int> x)\n{\n}\n\nvoid\nf_bidirectional(bidirectional<int> x)\n{\n}\n\nvoid\nf()\n{\n auto read_only = value(0);\n f_input(read_only);\n#ifdef ALIA_TEST_COMPILATION_FAILURE\n f_bidirectional(read_only);\n#endif\n}\n" }, { "alpha_fraction": 0.7278735637664795, "alphanum_fraction": 0.7278735637664795, "avg_line_length": 68.5999984741211, "blob_id": "fde9a5fa636a10dce38c26faa967431546320723", "content_id": "af65d36354fb16d4ee66f0458d767c3d63df335d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 3480, "license_type": "permissive", "max_line_length": 461, "num_lines": 50, "path": "/docs/control-flow.rst", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "Control Flow\n============\n\nControl Flow Macros\n-------------------\n\nIn order for its data management facilities to function properly, alia needs to know about any place where you have widgets inside if statements or loops. You mark these places by using alia macros in place of the normal control flow keywords. We've already seen a few of these, but the complete list is here.\n\n- ``alia_if``\n- ``alia_else_if``\n- ``alia_else``\n- ``alia_switch``\n- ``alia_case``\n- ``alia_for``\n- ``alia_while``\n\nAll control blocks must be terminated with ``alia_end``. (As you've already seen, an ``if/else_if/else`` block only needs one ``alia_end`` to terminate the entire block.)\n\nNote that you must not use ``goto`` in your UI code because it circumvents these mechanisms. You should also avoid using ``return`` in the middle of a function, as this will skip over part of the function without alia knowing. ``break`` and ``continue``, however, are OK.\n\nAlso note that when we check the return value of ``do_button``, we use a normal if statement. This is because that if statement represents an event handlers, not a conditional block of widgets.\n\nContext Naming\n--------------\n\nAll of the above macros assume that your UI context variable is named 'ctx'. If that's not the case, each has a corresponding form with an underscore appended to the end of the name where you can manually specify the name of the context variable. For example, ::\n\n alia_if_ (my_context, editing)\n {\n // ...\n }\n alia_end\n\nLoops with Item Reordering\n--------------------------\n\nYou may be wondering why we can add items to our contact list but not remove them. It's because removing them would confuse the alia_for macro. alia_for and alia_while associate state with the widgets in the loop body based on iteration count (the first iteration always gets the same data, the second iteration always gets the same data, etc.). When iterating over a list, reordering items in the list will cause them to end up associated with the wrong state.\n\nIn cases like this, you have to provide alia with a way to identify items in the list that will remain constant even as the items move around. If list items always remain at the same address (this is the case with STL lists), then you can simply use the address of an item as its ID. In other cases, you can use any info that's unique to an item (e.g., you might have assigned a numeric ID). Here's how our contact list loop looks using IDs. ::\n\n naming_context nc(ctx);\n for (std::list<contact>::iterator i = contacts.begin(); i != contacts.end(); ++i)\n {\n named_block nb(ctx, make_id(&*i)); // using contact address as block ID\n do_contact_ui(ctx, *i);\n }\n\nCreating a named_block at the top of a scope creates a new data context for the scope. All widgets invoked inside that scope (or in any function called in that scope) will get their data from the block associated with the named_block's ID. Note that since the named_block is already taking care of the data management for the loop body, we can use a normal for loop.\n\nThe first line in the example defines a new naming context for the loop. A ``naming_context`` provides a context for ``named_block`` IDs. IDs used within one naming context can be reused within another without conflict. Since we only have one loop in this example, this isn't strictly necessary. However, in a real application, where you might have other loops over the same data, this is a good habit.\n" }, { "alpha_fraction": 0.498305082321167, "alphanum_fraction": 0.5092278718948364, "avg_line_length": 20.585365295410156, "blob_id": "f8223d58c784425c72649c768ef009636838d3cd", "content_id": "60b00efabd6f620310ff3dd7b89934a6b3ed1ac4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2655, "license_type": "permissive", "max_line_length": 76, "num_lines": 123, "path": "/unit_tests/actions.cpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#include <alia/actions.hpp>\n\n#include <catch2/catch.hpp>\n\nusing namespace alia;\n\nTEST_CASE(\"copy actions\", \"[actions]\")\n{\n int x = 1;\n REQUIRE(!(empty<int>() <<= empty<int>()).is_ready());\n REQUIRE(!(direct(x) <<= empty<int>()).is_ready());\n REQUIRE(!(empty<int>() <<= direct(x)).is_ready());\n auto a = direct(x) <<= value(2);\n REQUIRE(a.is_ready());\n REQUIRE(x == 1);\n perform_action(a);\n REQUIRE(x == 2);\n}\n\nTEST_CASE(\"sequenced actions\", \"[actions]\")\n{\n int x = 1, y = 2;\n auto a = empty<int>() <<= empty<int>();\n auto b = direct(x) <<= value(2);\n auto c = direct(y) <<= value(3);\n REQUIRE(!(a, b).is_ready());\n REQUIRE((b, c).is_ready());\n perform_action((b, c));\n REQUIRE(x == 2);\n REQUIRE(y == 3);\n}\n\nTEST_CASE(\"action_ref\", \"[actions]\")\n{\n int x = 1;\n auto a = empty<int>() <<= empty<int>();\n auto b = direct(x) <<= value(2);\n\n action_ref<> r = b;\n REQUIRE(r.is_ready());\n perform_action(r);\n REQUIRE(x == 2);\n\n x = 1;\n\n action_ref<> s = r;\n REQUIRE(s.is_ready());\n perform_action(s);\n REQUIRE(x == 2);\n\n s = a;\n REQUIRE(!s.is_ready());\n}\n\nstatic void\nf(action<> a)\n{\n REQUIRE(!a.is_ready());\n}\n\nTEST_CASE(\"action parameter passing\", \"[actions]\")\n{\n auto a = empty<int>() <<= empty<int>();\n f(a);\n}\n\nTEST_CASE(\"toggle action\", \"[actions]\")\n{\n bool x = false;\n {\n auto a = make_toggle_action(direct(x));\n REQUIRE(a.is_ready());\n perform_action(a);\n REQUIRE(x);\n }\n {\n auto a = make_toggle_action(direct(x));\n REQUIRE(a.is_ready());\n perform_action(a);\n REQUIRE(!x);\n }\n\n {\n auto a = make_toggle_action(empty<bool>());\n REQUIRE(!a.is_ready());\n }\n}\n\nTEST_CASE(\"push_back action\", \"[actions]\")\n{\n auto x = std::vector<int>{1, 2};\n {\n auto a = make_push_back_action(direct(x), value(3));\n REQUIRE(a.is_ready());\n perform_action(a);\n REQUIRE(x == std::vector<int>{1, 2, 3});\n }\n\n {\n auto a = make_push_back_action(direct(x), empty<int>());\n REQUIRE(!a.is_ready());\n }\n {\n auto a = make_push_back_action(empty<std::vector<int>>(), value(3));\n REQUIRE(!a.is_ready());\n }\n}\n\nTEST_CASE(\"lambda actions\", \"[actions]\")\n{\n int x = 0;\n auto a = lambda_action(always_ready, [&](int y, int z) { x = y + z; });\n perform_action(a, 1, 2);\n REQUIRE(x == 3);\n\n bool ready = false;\n auto b = lambda_action([&]() { return ready; }, [&](int y) { x += y; });\n REQUIRE(!b.is_ready());\n ready = true;\n REQUIRE(b.is_ready());\n perform_action(b, 1);\n REQUIRE(x == 4);\n}\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6720430254936218, "avg_line_length": 13.307692527770996, "blob_id": "b9e1a5ae8e7fcd2ca2ff85f75a84e61679374f19", "content_id": "f786ea0e9aee0569b303a2a70f1215e1c5f2931a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 186, "license_type": "permissive", "max_line_length": 36, "num_lines": 13, "path": "/compilation_tests/invalid_signal_access.cpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#include <alia/signals.hpp>\n\nusing namespace alia;\n\nvoid\nf()\n{\n auto s = value(0);\n signal_is_readable(s);\n#ifdef ALIA_TEST_COMPILATION_FAILURE\n signal_is_writable(s);\n#endif\n}\n" }, { "alpha_fraction": 0.4540680944919586, "alphanum_fraction": 0.4647676646709442, "avg_line_length": 28.866779327392578, "blob_id": "ef0144530a76cb2eb976e1abb0703a53a93f635e", "content_id": "6a4a58e7b3b38218d7a2ac3ef8f68be0fe794d11", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 35422, "license_type": "permissive", "max_line_length": 80, "num_lines": 1186, "path": "/unit_tests/data_graph.cpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#define ALIA_LOWERCASE_MACROS\n#include <alia/data_graph.hpp>\n\n#include <sstream>\n\n#include <boost/lexical_cast.hpp>\n\n#include <catch2/catch.hpp>\n\nusing namespace alia;\n\n// The following define a small framework for testing data traversal mechanics.\n// The idea is that we execute various traversals over test data graphs\n// (generally multiple times over each graph) and log various events (allocating\n// new nodes, destroying old ones, and visiting existing nodes). We can then\n// check that the log matches expectations.\n\nstatic std::stringstream log_;\n\n// Clear the log.\n// It's best to do this explicitly at the beginning of each test in case the\n// previous one failed and left the log in a bad state.\nstatic void\nclear_log()\n{\n log_.str(std::string());\n}\n\n// Check that the log contains the expected contents and clear it.\nstatic void\ncheck_log(std::string const& expected_contents)\n{\n REQUIRE(log_.str() == expected_contents);\n clear_log();\n}\n\nstruct int_object\n{\n int_object() : n(-1)\n {\n }\n int_object(int n) : n(n)\n {\n }\n ~int_object()\n {\n log_ << \"destructing int;\";\n }\n int n;\n};\n\ntemplate<class Context>\nvoid\ndo_int(Context& ctx, int n)\n{\n int_object* obj;\n if (get_data(ctx, &obj))\n {\n REQUIRE(obj->n == -1);\n obj->n = n;\n log_ << \"initializing int: \" << n << \";\";\n }\n else\n {\n REQUIRE(obj->n == n);\n log_ << \"visiting int: \" << n << \";\";\n }\n}\n\ntemplate<class Context>\nvoid\ndo_cached_int(Context& ctx, int n)\n{\n int_object* obj;\n if (get_cached_data(ctx, &obj))\n {\n REQUIRE(obj->n == -1);\n obj->n = n;\n log_ << \"initializing cached int: \" << n << \";\";\n }\n else\n {\n REQUIRE(obj->n == n);\n log_ << \"visiting cached int: \" << n << \";\";\n }\n}\n\ntemplate<class Context>\nvoid\ndo_keyed_int(Context& ctx, int n)\n{\n keyed_data_signal<int_object> obj;\n if (get_keyed_data(ctx, make_id(n), &obj))\n {\n REQUIRE(!obj.is_readable());\n write_signal(obj, int_object(n * 2));\n log_ << \"initializing keyed int: \" << n << \";\";\n }\n else\n {\n REQUIRE(read_signal(obj).n == n * 2);\n REQUIRE(obj.value_id() == make_id(n));\n log_ << \"visiting keyed int: \" << n << \";\";\n }\n}\n\ntemplate<class Controller>\nvoid\ndo_traversal(\n data_graph& graph, Controller const& controller, bool with_gc = true)\n{\n data_traversal ctx;\n scoped_data_traversal sdt(graph, ctx);\n if (!with_gc)\n disable_gc(ctx);\n controller(ctx);\n}\n\n// This is used to test that the utilities work with a custom context (rather\n// than invoking them directly on a data_traversal).\nstruct custom_context\n{\n custom_context(data_traversal& traversal) : traversal(traversal)\n {\n }\n\n data_traversal& traversal;\n};\nstatic data_traversal&\nget_data_traversal(custom_context& ctx)\n{\n return ctx.traversal;\n}\n\nTEST_CASE(\"basic data traversal\", \"[data_graph]\")\n{\n clear_log();\n {\n data_graph graph;\n auto controller = [](data_traversal& ctx) { do_int(ctx, 0); };\n do_traversal(graph, controller);\n check_log(\"initializing int: 0;\");\n do_traversal(graph, controller);\n check_log(\"visiting int: 0;\");\n }\n check_log(\"destructing int;\");\n}\n\nTEST_CASE(\"basic alia_if\", \"[data_graph]\")\n{\n clear_log();\n {\n data_graph graph;\n auto make_controller = [](auto condition) {\n return [=](data_traversal& ctx) {\n ALIA_IF(condition)\n {\n do_int(ctx, 0);\n }\n ALIA_END\n do_int(ctx, 1);\n };\n };\n do_traversal(graph, make_controller(value(false)));\n check_log(\"initializing int: 1;\");\n do_traversal(graph, make_controller(value(true)));\n check_log(\n \"initializing int: 0;\"\n \"visiting int: 1;\");\n do_traversal(graph, make_controller(value(false)));\n check_log(\"visiting int: 1;\");\n do_traversal(graph, make_controller(empty<bool>()));\n check_log(\"visiting int: 1;\");\n }\n check_log(\n \"destructing int;\"\n \"destructing int;\");\n}\n\nTEST_CASE(\"alia_if/alia_else\", \"[data_graph]\")\n{\n clear_log();\n {\n data_graph graph;\n auto make_controller = [](auto condition) {\n return [=](custom_context ctx) {\n ALIA_IF(condition)\n {\n do_int(ctx, 0);\n }\n ALIA_ELSE\n {\n do_int(ctx, 1);\n }\n ALIA_END\n do_int(ctx, 2);\n };\n };\n do_traversal(graph, make_controller(value(false)));\n check_log(\n \"initializing int: 1;\"\n \"initializing int: 2;\");\n do_traversal(graph, make_controller(value(true)));\n check_log(\n \"initializing int: 0;\"\n \"visiting int: 2;\");\n do_traversal(graph, make_controller(value(false)));\n check_log(\n \"visiting int: 1;\"\n \"visiting int: 2;\");\n do_traversal(graph, make_controller(empty<bool>()));\n check_log(\"visiting int: 2;\");\n }\n check_log(\n \"destructing int;\"\n \"destructing int;\"\n \"destructing int;\");\n}\n\nTEST_CASE(\"non-signal alia_if/alia_else\", \"[data_graph]\")\n{\n clear_log();\n {\n data_graph graph;\n auto make_controller = [](auto condition) {\n return [=](custom_context ctx) {\n ALIA_IF(condition)\n {\n do_int(ctx, 0);\n }\n ALIA_ELSE\n {\n do_int(ctx, 1);\n }\n ALIA_END\n do_int(ctx, 2);\n };\n };\n do_traversal(graph, make_controller(false));\n check_log(\n \"initializing int: 1;\"\n \"initializing int: 2;\");\n do_traversal(graph, make_controller(true));\n check_log(\n \"initializing int: 0;\"\n \"visiting int: 2;\");\n do_traversal(graph, make_controller(false));\n check_log(\n \"visiting int: 1;\"\n \"visiting int: 2;\");\n }\n check_log(\n \"destructing int;\"\n \"destructing int;\"\n \"destructing int;\");\n}\n\nTEST_CASE(\"alia_if/alia_else caching\", \"[data_graph]\")\n{\n clear_log();\n {\n data_graph graph;\n auto make_controller = [](auto condition) {\n return [=](custom_context ctx) {\n ALIA_IF(condition)\n {\n ; // This somehow stops ClangFormat from doing weird stuff\n // with this block;\n ALIA_IF(value(true))\n {\n // This is nested inside an additional level of data\n // blocks, so it triggers a different case in the cache\n // clearing code.\n do_cached_int(ctx, 0);\n }\n ALIA_END\n }\n ALIA_ELSE\n {\n do_cached_int(ctx, 1);\n }\n ALIA_END\n do_int(ctx, 2);\n };\n };\n // Cached data isn't retained inside inactive parts of the traversal, so\n // our cached ints will get destructed and recreated from one traversal\n // to another.\n do_traversal(graph, make_controller(value(false)));\n check_log(\n \"initializing cached int: 1;\"\n \"initializing int: 2;\");\n do_traversal(graph, make_controller(value(true)));\n check_log(\n \"initializing cached int: 0;\"\n \"destructing int;\"\n \"visiting int: 2;\");\n do_traversal(graph, make_controller(value(false)));\n check_log(\n \"destructing int;\"\n \"initializing cached int: 1;\"\n \"visiting int: 2;\");\n do_traversal(graph, make_controller(empty<bool>()));\n check_log(\n \"destructing int;\"\n \"visiting int: 2;\");\n do_traversal(graph, make_controller(value(true)));\n check_log(\n \"initializing cached int: 0;\"\n \"visiting int: 2;\");\n }\n check_log(\n \"destructing int;\"\n \"destructing int;\");\n}\n\nTEST_CASE(\"alia_if/alia_else_if/alia_else\", \"[data_graph]\")\n{\n clear_log();\n {\n data_graph graph;\n auto make_controller = [](auto condition1, auto condition2) {\n return [=](custom_context ctx) {\n alia_if(condition1)\n {\n do_int(ctx, 0);\n }\n alia_else_if(condition2)\n {\n do_int(ctx, 1);\n }\n alia_else\n {\n do_int(ctx, 2);\n }\n alia_end; // The ';' helps ClangFormat.\n\n do_int(ctx, 3);\n };\n };\n do_traversal(graph, make_controller(value(false), value(true)));\n check_log(\n \"initializing int: 1;\"\n \"initializing int: 3;\");\n do_traversal(graph, make_controller(value(true), value(false)));\n check_log(\n \"initializing int: 0;\"\n \"visiting int: 3;\");\n do_traversal(graph, make_controller(value(true), value(true)));\n check_log(\n \"visiting int: 0;\"\n \"visiting int: 3;\");\n do_traversal(graph, make_controller(value(false), value(false)));\n check_log(\n \"initializing int: 2;\"\n \"visiting int: 3;\");\n do_traversal(graph, make_controller(empty<bool>(), value(false)));\n check_log(\"visiting int: 3;\");\n do_traversal(graph, make_controller(empty<bool>(), empty<bool>()));\n check_log(\"visiting int: 3;\");\n do_traversal(graph, make_controller(value(false), empty<bool>()));\n check_log(\"visiting int: 3;\");\n do_traversal(graph, make_controller(value(false), value(true)));\n check_log(\n \"visiting int: 1;\"\n \"visiting int: 3;\");\n }\n check_log(\n \"destructing int;\"\n \"destructing int;\"\n \"destructing int;\"\n \"destructing int;\");\n}\n\nTEST_CASE(\"alia_pass_dependent_if\", \"[data_graph]\")\n{\n clear_log();\n {\n data_graph graph;\n auto make_controller = [](auto condition) {\n return [=](data_traversal& ctx) {\n alia_pass_dependent_if(condition)\n {\n do_cached_int(ctx, 0);\n }\n alia_end;\n do_int(ctx, 1);\n };\n };\n do_traversal(graph, make_controller(value(false)));\n check_log(\"initializing int: 1;\");\n do_traversal(graph, make_controller(value(true)));\n check_log(\n \"initializing cached int: 0;\"\n \"visiting int: 1;\");\n do_traversal(graph, make_controller(value(false)));\n check_log(\"visiting int: 1;\");\n do_traversal(graph, make_controller(empty<bool>()));\n check_log(\"visiting int: 1;\");\n do_traversal(graph, make_controller(value(true)));\n check_log(\n \"visiting cached int: 0;\"\n \"visiting int: 1;\");\n }\n check_log(\n \"destructing int;\"\n \"destructing int;\");\n}\n\nTEST_CASE(\"alia_switch\", \"[data_graph]\")\n{\n clear_log();\n {\n data_graph graph;\n auto make_controller = [](auto n) {\n return [=](custom_context ctx) {\n // clang-format off\n ALIA_SWITCH(n)\n {\n ALIA_CASE(0):\n do_int(ctx, 0);\n break;\n ALIA_CASE(1):\n do_int(ctx, 1);\n ALIA_CASE(2):\n ALIA_CASE(3):\n do_int(ctx, 2);\n do_cached_int(ctx, 3);\n break;\n ALIA_DEFAULT:\n do_int(ctx, 4);\n }\n ALIA_END\n do_int(ctx, -2);\n // clang-format on\n };\n };\n do_traversal(graph, make_controller(value(0)));\n check_log(\n \"initializing int: 0;\"\n \"initializing int: -2;\");\n do_traversal(graph, make_controller(value(2)));\n check_log(\n \"initializing int: 2;\"\n \"initializing cached int: 3;\"\n \"visiting int: -2;\");\n do_traversal(graph, make_controller(value(1)));\n check_log(\n \"initializing int: 1;\"\n \"visiting int: 2;\"\n \"visiting cached int: 3;\"\n \"visiting int: -2;\");\n do_traversal(graph, make_controller(value(17)));\n check_log(\n \"initializing int: 4;\"\n \"visiting int: -2;\"\n \"destructing int;\");\n do_traversal(graph, make_controller(value(1)));\n check_log(\n \"visiting int: 1;\"\n \"visiting int: 2;\"\n \"initializing cached int: 3;\"\n \"visiting int: -2;\");\n do_traversal(graph, make_controller(value(2)));\n check_log(\n \"visiting int: 2;\"\n \"visiting cached int: 3;\"\n \"visiting int: -2;\");\n }\n check_log(\n \"destructing int;\"\n \"destructing int;\"\n \"destructing int;\"\n \"destructing int;\"\n \"destructing int;\"\n \"destructing int;\");\n}\n\nTEST_CASE(\"non-signal alia_switch\", \"[data_graph]\")\n{\n clear_log();\n {\n data_graph graph;\n auto make_controller = [](auto n) {\n return [=](custom_context ctx) {\n // clang-format off\n alia_switch(n)\n {\n alia_case(0):\n do_int(ctx, 0);\n break;\n alia_case(1):\n do_int(ctx, 1);\n alia_case(2):\n alia_case(3):\n do_int(ctx, 2);\n do_cached_int(ctx, 3);\n break;\n alia_default:\n do_int(ctx, 4);\n }\n alia_end\n do_int(ctx, -2);\n // clang-format on\n };\n };\n do_traversal(graph, make_controller(0));\n check_log(\n \"initializing int: 0;\"\n \"initializing int: -2;\");\n do_traversal(graph, make_controller(2));\n check_log(\n \"initializing int: 2;\"\n \"initializing cached int: 3;\"\n \"visiting int: -2;\");\n do_traversal(graph, make_controller(1));\n check_log(\n \"initializing int: 1;\"\n \"visiting int: 2;\"\n \"visiting cached int: 3;\"\n \"visiting int: -2;\");\n do_traversal(graph, make_controller(17));\n check_log(\n \"initializing int: 4;\"\n \"visiting int: -2;\"\n \"destructing int;\");\n do_traversal(graph, make_controller(1));\n check_log(\n \"visiting int: 1;\"\n \"visiting int: 2;\"\n \"initializing cached int: 3;\"\n \"visiting int: -2;\");\n do_traversal(graph, make_controller(2));\n check_log(\n \"visiting int: 2;\"\n \"visiting cached int: 3;\"\n \"visiting int: -2;\");\n }\n check_log(\n \"destructing int;\"\n \"destructing int;\"\n \"destructing int;\"\n \"destructing int;\"\n \"destructing int;\"\n \"destructing int;\");\n}\n\nTEST_CASE(\"alia_for\", \"[data_graph]\")\n{\n clear_log();\n {\n data_graph graph;\n auto make_controller = [](int n) {\n return [=](custom_context ctx) {\n ALIA_FOR(int i = 1; i <= n; ++i)\n {\n do_int(ctx, i);\n }\n ALIA_END\n do_int(ctx, 0);\n };\n };\n do_traversal(graph, make_controller(2));\n check_log(\n \"initializing int: 1;\"\n \"initializing int: 2;\"\n \"initializing int: 0;\");\n do_traversal(graph, make_controller(1));\n check_log(\n \"visiting int: 1;\"\n \"destructing int;\"\n \"visiting int: 0;\");\n do_traversal(graph, make_controller(4));\n check_log(\n \"visiting int: 1;\"\n \"initializing int: 2;\"\n \"initializing int: 3;\"\n \"initializing int: 4;\"\n \"visiting int: 0;\");\n do_traversal(graph, make_controller(0));\n check_log(\n \"destructing int;\"\n \"destructing int;\"\n \"destructing int;\"\n \"destructing int;\"\n \"visiting int: 0;\");\n do_traversal(graph, make_controller(3));\n check_log(\n \"initializing int: 1;\"\n \"initializing int: 2;\"\n \"initializing int: 3;\"\n \"visiting int: 0;\");\n }\n check_log(\n \"destructing int;\"\n \"destructing int;\"\n \"destructing int;\"\n \"destructing int;\");\n}\n\nTEST_CASE(\"alia_while\", \"[data_graph]\")\n{\n clear_log();\n {\n data_graph graph;\n auto make_controller = [](int n) {\n return [=](custom_context ctx) {\n int i = 1;\n alia_while(i <= n)\n {\n do_int(ctx, i);\n ++i;\n }\n alia_end;\n do_int(ctx, 0);\n };\n };\n do_traversal(graph, make_controller(2));\n check_log(\n \"initializing int: 1;\"\n \"initializing int: 2;\"\n \"initializing int: 0;\");\n do_traversal(graph, make_controller(1));\n check_log(\n \"visiting int: 1;\"\n \"destructing int;\"\n \"visiting int: 0;\");\n do_traversal(graph, make_controller(4));\n check_log(\n \"visiting int: 1;\"\n \"initializing int: 2;\"\n \"initializing int: 3;\"\n \"initializing int: 4;\"\n \"visiting int: 0;\");\n do_traversal(graph, make_controller(0));\n check_log(\n \"destructing int;\"\n \"destructing int;\"\n \"destructing int;\"\n \"destructing int;\"\n \"visiting int: 0;\");\n do_traversal(graph, make_controller(3));\n check_log(\n \"initializing int: 1;\"\n \"initializing int: 2;\"\n \"initializing int: 3;\"\n \"visiting int: 0;\");\n }\n check_log(\n \"destructing int;\"\n \"destructing int;\"\n \"destructing int;\"\n \"destructing int;\");\n}\n\nTEST_CASE(\"simple named blocks\", \"[data_graph]\")\n{\n clear_log();\n {\n data_graph graph;\n auto make_controller = [](std::vector<int> indices) {\n return [=](data_traversal& ctx) {\n naming_context nc(ctx);\n for (auto i : indices)\n {\n named_block nb(nc, make_id(i));\n do_int(ctx, i);\n }\n do_int(ctx, 0);\n };\n };\n do_traversal(graph, make_controller({1}));\n check_log(\n \"initializing int: 1;\"\n \"initializing int: 0;\");\n do_traversal(graph, make_controller({2}));\n check_log(\n \"initializing int: 2;\"\n \"visiting int: 0;\"\n \"destructing int;\");\n do_traversal(graph, make_controller({1, 2}));\n check_log(\n \"initializing int: 1;\"\n \"visiting int: 2;\"\n \"visiting int: 0;\");\n do_traversal(graph, make_controller({2, 3}));\n check_log(\n \"visiting int: 2;\"\n \"initializing int: 3;\"\n \"visiting int: 0;\"\n \"destructing int;\");\n do_traversal(graph, make_controller({2, 1, 3}));\n check_log(\n \"visiting int: 2;\"\n \"initializing int: 1;\"\n \"visiting int: 3;\"\n \"visiting int: 0;\");\n }\n check_log(\n \"destructing int;\"\n \"destructing int;\"\n \"destructing int;\"\n \"destructing int;\");\n}\n\nTEST_CASE(\"mobile named blocks\", \"[data_graph]\")\n{\n clear_log();\n {\n data_graph graph;\n auto make_controller = [](std::vector<int> indices, int divider) {\n return [=](data_traversal& ctx) {\n naming_context nc(ctx);\n ALIA_FOR(auto i : indices)\n {\n ;\n ALIA_IF(i < divider)\n {\n named_block nb(nc, make_id(i));\n do_int(ctx, i);\n }\n ALIA_END\n }\n ALIA_END\n alia_for(auto i : indices)\n {\n ;\n alia_if(i >= divider)\n {\n named_block nb(nc, make_id(i));\n do_int(ctx, i);\n }\n alia_end\n }\n alia_end\n };\n };\n do_traversal(graph, make_controller({3, 2, 1}, 2));\n check_log(\n \"initializing int: 1;\"\n \"initializing int: 3;\"\n \"initializing int: 2;\");\n do_traversal(graph, make_controller({3, 2, 1}, 3));\n check_log(\n \"visiting int: 2;\"\n \"visiting int: 1;\"\n \"visiting int: 3;\");\n do_traversal(graph, make_controller({3, 1}, 3));\n check_log(\n \"visiting int: 1;\"\n \"visiting int: 3;\");\n }\n check_log(\n \"destructing int;\"\n \"destructing int;\"\n \"destructing int;\");\n}\n\nTEST_CASE(\"multiple naming contexts\", \"[data_graph]\")\n{\n clear_log();\n {\n data_graph graph;\n auto make_controller = [](std::vector<int> indices) {\n return [=](custom_context ctx) {\n {\n naming_context nc(ctx);\n for (auto i : indices)\n {\n named_block nb(nc, make_id(i));\n do_int(ctx, i);\n }\n }\n // Do the same thing again with the same names but with all the\n // do_int values doubled. This would cause conflicts if they\n // didn't have separate data from the ones above.\n {\n naming_context nc(ctx);\n for (auto i : indices)\n {\n named_block nb(nc, make_id(i));\n do_int(ctx, i * 2);\n }\n }\n do_int(ctx, 0);\n };\n };\n do_traversal(graph, make_controller({1}));\n check_log(\n \"initializing int: 1;\"\n \"initializing int: 2;\"\n \"initializing int: 0;\");\n do_traversal(graph, make_controller({2}));\n check_log(\n \"initializing int: 2;\"\n \"initializing int: 4;\"\n \"visiting int: 0;\"\n \"destructing int;\"\n \"destructing int;\");\n do_traversal(graph, make_controller({1, 2}));\n check_log(\n \"initializing int: 1;\"\n \"visiting int: 2;\"\n \"initializing int: 2;\"\n \"visiting int: 4;\"\n \"visiting int: 0;\");\n do_traversal(graph, make_controller({2, 3}));\n check_log(\n \"visiting int: 2;\"\n \"initializing int: 3;\"\n \"visiting int: 4;\"\n \"initializing int: 6;\"\n \"visiting int: 0;\"\n \"destructing int;\"\n \"destructing int;\");\n }\n check_log(\n \"destructing int;\"\n \"destructing int;\"\n \"destructing int;\"\n \"destructing int;\"\n \"destructing int;\");\n}\n\nTEST_CASE(\"unexecuted named blocks\", \"[data_graph]\")\n{\n // Test that named blocks aren't GC'd if they're in unexecuted blocks.\n clear_log();\n {\n data_graph graph;\n auto make_controller = [](auto condition, std::vector<int> indices) {\n return [=](custom_context ctx) {\n ALIA_IF(condition)\n {\n naming_context nc(ctx);\n for (auto i : indices)\n {\n named_block nb(nc, make_id(i));\n do_int(ctx, i);\n }\n }\n ALIA_END\n do_int(ctx, 0);\n };\n };\n do_traversal(graph, make_controller(value(true), {1}));\n check_log(\n \"initializing int: 1;\"\n \"initializing int: 0;\");\n do_traversal(graph, make_controller(value(false), {1}));\n check_log(\"visiting int: 0;\");\n do_traversal(graph, make_controller(value(true), {2, 1}));\n check_log(\n \"initializing int: 2;\"\n \"visiting int: 1;\"\n \"visiting int: 0;\");\n }\n check_log(\n \"destructing int;\"\n \"destructing int;\"\n \"destructing int;\");\n}\n\nTEST_CASE(\"GC disabling\", \"[data_graph]\")\n{\n clear_log();\n {\n data_graph graph;\n auto make_controller = [](std::vector<int> indices) {\n return [=](custom_context ctx) {\n {\n naming_context nc(ctx);\n for (auto i : indices)\n {\n named_block nb(nc, make_id(i));\n do_int(ctx, i);\n }\n }\n do_int(ctx, 0);\n };\n };\n // These traversals are fine because they have GC enabled.\n do_traversal(graph, make_controller({1, 2}), true);\n check_log(\n \"initializing int: 1;\"\n \"initializing int: 2;\"\n \"initializing int: 0;\");\n do_traversal(graph, make_controller({2, 1}), true);\n check_log(\n \"visiting int: 2;\"\n \"visiting int: 1;\"\n \"visiting int: 0;\");\n // This traversal is fine because it maintains the previous order.\n do_traversal(graph, make_controller({2, 1}), false);\n check_log(\n \"visiting int: 2;\"\n \"visiting int: 1;\"\n \"visiting int: 0;\");\n // This traversal is an error because it tries to change the order\n // with GC disabled.\n REQUIRE_THROWS_AS(\n do_traversal(graph, make_controller({1, 2}), false),\n named_block_out_of_order);\n }\n check_log(\n \"destructing int;\"\n \"destructing int;\"\n \"destructing int;\");\n}\n\nTEST_CASE(\"manual deletion\", \"[data_graph]\")\n{\n clear_log();\n {\n data_graph graph;\n auto make_controller = [](std::vector<int> indices) {\n return [=](custom_context ctx) {\n naming_context nc(ctx);\n for (auto i : indices)\n {\n // Odd indices will require manual deletion.\n named_block nb(nc, make_id(i), manual_delete((i & 1) != 0));\n do_int(ctx, i);\n }\n do_int(ctx, 0);\n };\n };\n do_traversal(graph, make_controller({1}));\n check_log(\n \"initializing int: 1;\"\n \"initializing int: 0;\");\n // Test that manual_delete blocks aren't GC'd when they're not seen.\n do_traversal(graph, make_controller({2, 3}));\n check_log(\n \"initializing int: 2;\"\n \"initializing int: 3;\"\n \"visiting int: 0;\");\n // Test that normal blocks are still GC'd.\n do_traversal(graph, make_controller({1}));\n check_log(\n \"visiting int: 1;\"\n \"visiting int: 0;\"\n \"destructing int;\");\n // Test that normal blocks are still GC'd.\n do_traversal(graph, make_controller({3, 1}));\n check_log(\n \"visiting int: 3;\"\n \"visiting int: 1;\"\n \"visiting int: 0;\");\n // Test that normal blocks are still GC'd.\n do_traversal(graph, make_controller({1}));\n check_log(\n \"visiting int: 1;\"\n \"visiting int: 0;\");\n // Test manual deletion.\n delete_named_block(graph, make_id(3));\n check_log(\"destructing int;\");\n // Test that manual deletion has no effect on blocks that are still\n // active.\n delete_named_block(graph, make_id(1));\n check_log(\"\");\n do_traversal(graph, make_controller({1}));\n check_log(\n \"visiting int: 1;\"\n \"visiting int: 0;\");\n }\n check_log(\n \"destructing int;\"\n \"destructing int;\");\n}\n\nTEST_CASE(\"named block caching\", \"[data_graph]\")\n{\n clear_log();\n {\n data_graph graph;\n auto make_controller = [](auto condition, std::vector<int> indices) {\n return [=](custom_context ctx) {\n ALIA_IF(condition)\n {\n naming_context nc(ctx);\n for (auto i : indices)\n {\n named_block nb(nc, make_id(i));\n ALIA_IF(value(true))\n {\n do_cached_int(ctx, i);\n }\n ALIA_END\n }\n }\n ALIA_END\n };\n };\n do_traversal(graph, make_controller(value(true), {2, 1}));\n check_log(\n \"initializing cached int: 2;\"\n \"initializing cached int: 1;\");\n do_traversal(graph, make_controller(value(true), {2, 1}));\n check_log(\n \"visiting cached int: 2;\"\n \"visiting cached int: 1;\");\n do_traversal(graph, make_controller(value(true), {1}));\n check_log(\n \"visiting cached int: 1;\"\n \"destructing int;\");\n do_traversal(graph, make_controller(value(true), {2, 1}));\n check_log(\n \"initializing cached int: 2;\"\n \"visiting cached int: 1;\");\n do_traversal(graph, make_controller(value(false), {2, 1}));\n check_log(\n \"destructing int;\"\n \"destructing int;\");\n do_traversal(graph, make_controller(value(true), {2, 1}));\n check_log(\n \"initializing cached int: 2;\"\n \"initializing cached int: 1;\");\n do_traversal(graph, make_controller(value(false), {}));\n check_log(\n \"destructing int;\"\n \"destructing int;\");\n do_traversal(graph, make_controller(value(true), {2, 1}));\n check_log(\n \"initializing cached int: 2;\"\n \"initializing cached int: 1;\");\n }\n check_log(\n \"destructing int;\"\n \"destructing int;\");\n}\n\nTEST_CASE(\"scoped_cache_clearing_disabler\", \"[data_graph]\")\n{\n clear_log();\n {\n data_graph graph;\n auto make_controller = [](auto condition) {\n return [=](custom_context ctx) {\n {\n scoped_cache_clearing_disabler disabler(ctx);\n ALIA_IF(condition)\n {\n do_cached_int(ctx, 0);\n }\n ALIA_ELSE\n {\n do_cached_int(ctx, 1);\n }\n ALIA_END\n }\n ALIA_IF(condition)\n {\n do_cached_int(ctx, 2);\n }\n ALIA_END\n };\n };\n // Since we are disabling cache clearing for the first block, the 0 and\n // 1 will persist even when their blocks go inactive.\n do_traversal(graph, make_controller(value(false)));\n check_log(\"initializing cached int: 1;\");\n do_traversal(graph, make_controller(value(true)));\n check_log(\n \"initializing cached int: 0;\"\n \"initializing cached int: 2;\");\n do_traversal(graph, make_controller(value(false)));\n check_log(\n \"visiting cached int: 1;\"\n \"destructing int;\");\n do_traversal(graph, make_controller(empty<bool>()));\n check_log(\"\");\n do_traversal(graph, make_controller(value(true)));\n check_log(\n \"visiting cached int: 0;\"\n \"initializing cached int: 2;\");\n do_traversal(graph, make_controller(value(false)));\n check_log(\n \"visiting cached int: 1;\"\n \"destructing int;\");\n }\n check_log(\n \"destructing int;\"\n \"destructing int;\");\n}\n\nTEST_CASE(\"keyed_data\", \"[data_graph]\")\n{\n keyed_data<int> i;\n REQUIRE(!is_valid(i));\n\n set(i, 2);\n REQUIRE(is_valid(i));\n REQUIRE(get(i) == 2);\n\n invalidate(i);\n REQUIRE(!is_valid(i));\n\n mark_valid(i);\n REQUIRE(is_valid(i));\n REQUIRE(get(i) == 2);\n\n refresh_keyed_data(i, make_id(0));\n REQUIRE(!is_valid(i));\n\n set(i, 1);\n REQUIRE(is_valid(i));\n REQUIRE(get(i) == 1);\n\n refresh_keyed_data(i, make_id(0));\n REQUIRE(is_valid(i));\n\n refresh_keyed_data(i, make_id(1));\n REQUIRE(!is_valid(i));\n}\n\nTEST_CASE(\"signal-based get_keyed_data\", \"[data_graph]\")\n{\n clear_log();\n {\n data_graph graph;\n auto make_controller = [](int i) {\n return [=](custom_context ctx) {\n do_keyed_int(ctx, i);\n do_keyed_int(ctx, 0);\n };\n };\n do_traversal(graph, make_controller(1));\n check_log(\n // A destruction happens during every initialization.\n \"destructing int;\"\n \"initializing keyed int: 1;\"\n \"destructing int;\"\n \"initializing keyed int: 0;\");\n do_traversal(graph, make_controller(1));\n check_log(\n \"visiting keyed int: 1;\"\n \"visiting keyed int: 0;\");\n do_traversal(graph, make_controller(2));\n check_log(\n \"destructing int;\"\n \"initializing keyed int: 2;\"\n \"visiting keyed int: 0;\");\n do_traversal(graph, make_controller(2));\n check_log(\n \"visiting keyed int: 2;\"\n \"visiting keyed int: 0;\");\n }\n check_log(\n \"destructing int;\"\n \"destructing int;\");\n}\n\nTEST_CASE(\"low-level get_keyed_data\", \"[data_graph]\")\n{\n clear_log();\n {\n data_graph graph;\n auto make_controller = [](int i) {\n return [=](custom_context ctx) {\n int_object* x;\n if (get_keyed_data(ctx, make_id(i), &x))\n {\n x->n = i;\n log_ << \"initializing keyed int: \" << i << \";\";\n }\n else\n {\n REQUIRE(x->n == i);\n log_ << \"visiting keyed int: \" << i << \";\";\n }\n };\n };\n do_traversal(graph, make_controller(1));\n check_log(\"initializing keyed int: 1;\");\n do_traversal(graph, make_controller(1));\n check_log(\"visiting keyed int: 1;\");\n do_traversal(graph, make_controller(2));\n check_log(\n \"destructing int;\"\n \"initializing keyed int: 2;\");\n do_traversal(graph, make_controller(2));\n check_log(\"visiting keyed int: 2;\");\n }\n check_log(\"destructing int;\");\n}\n" }, { "alpha_fraction": 0.49267226457595825, "alphanum_fraction": 0.4982849955558777, "avg_line_length": 22.40876007080078, "blob_id": "2d0442a6cfeb38cbc06446acfe108a4d74840023", "content_id": "6e78cca02a034abdc3dd6aaeaea54f2efa61427e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3207, "license_type": "permissive", "max_line_length": 70, "num_lines": 137, "path": "/unit_tests/events.cpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#include <alia/events.hpp>\n#include <alia/system.hpp>\n#include <sstream>\n\n#include <catch2/catch.hpp>\n\nusing namespace alia;\n\nstruct ostream_event\n{\n std::ostream* stream;\n};\n\nvoid\ndo_ostream_text(context& ctx, std::string const& text)\n{\n ostream_event* oe;\n if (detect_event(ctx, &oe))\n {\n *oe->stream << text << \";\";\n }\n}\n\nstruct find_label_event\n{\n routing_region_ptr region;\n std::string name;\n};\n\nvoid\ndo_label(context& ctx, std::string const& name)\n{\n do_ostream_text(ctx, name);\n\n find_label_event* fle;\n if (detect_event(ctx, &fle))\n {\n if (fle->name == name)\n fle->region = get_active_routing_region(ctx);\n }\n}\n\nstruct traversal_function\n{\n int n;\n traversal_function(int n) : n(n)\n {\n }\n void\n operator()(context ctx)\n {\n do_ostream_text(ctx, \"\");\n\n REQUIRE(!get_active_routing_region(ctx));\n\n scoped_routing_region srr(ctx);\n ALIA_IF(srr.is_relevant())\n {\n do_label(ctx, \"root\");\n\n ALIA_IF(n != 0)\n {\n scoped_routing_region srr(ctx);\n ALIA_IF(srr.is_relevant())\n {\n do_label(ctx, \"nonzero\");\n\n {\n scoped_routing_region srr(ctx);\n ALIA_IF(srr.is_relevant())\n {\n do_label(ctx, \"deep\");\n }\n ALIA_END\n }\n }\n ALIA_END\n }\n ALIA_END\n\n ALIA_IF(n & 1)\n {\n scoped_routing_region srr(ctx);\n ALIA_IF(srr.is_relevant())\n {\n do_label(ctx, \"odd\");\n }\n ALIA_END\n }\n ALIA_END\n }\n ALIA_END\n }\n};\n\nvoid\ncheck_traversal_path(\n int n, std::string const& label, std::string const& expected_path)\n{\n alia::system sys;\n sys.controller = traversal_function(n);\n routing_region_ptr target;\n {\n find_label_event fle;\n fle.name = label;\n dispatch_event(sys, fle);\n target = fle.region;\n }\n {\n ostream_event oe;\n std::ostringstream s;\n oe.stream = &s;\n dispatch_targeted_event(sys, oe, target);\n REQUIRE(s.str() == expected_path);\n }\n}\n\nTEST_CASE(\"targeted_event_dispatch\", \"[targeted_event_dispatch]\")\n{\n check_traversal_path(0, \"absent\", \";\");\n check_traversal_path(0, \"root\", \";root;\");\n check_traversal_path(0, \"nonzero\", \";\");\n check_traversal_path(0, \"odd\", \";\");\n check_traversal_path(0, \"deep\", \";\");\n\n check_traversal_path(1, \"absent\", \";\");\n check_traversal_path(1, \"root\", \";root;\");\n check_traversal_path(1, \"nonzero\", \";root;nonzero;\");\n check_traversal_path(1, \"odd\", \";root;odd;\");\n check_traversal_path(1, \"deep\", \";root;nonzero;deep;\");\n\n check_traversal_path(2, \"absent\", \";\");\n check_traversal_path(2, \"root\", \";root;\");\n check_traversal_path(2, \"nonzero\", \";root;nonzero;\");\n check_traversal_path(2, \"odd\", \";\");\n check_traversal_path(2, \"deep\", \";root;nonzero;deep;\");\n}\n" }, { "alpha_fraction": 0.6088435649871826, "alphanum_fraction": 0.6088435649871826, "avg_line_length": 24.34482765197754, "blob_id": "db10ff1fb9aaa6e4db298088305d0e7f7696dfcb", "content_id": "58310763073b4b66de03705571ddf0f78dac48fc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7350, "license_type": "permissive", "max_line_length": 80, "num_lines": 290, "path": "/src/alia/signals/adaptors.hpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#ifndef ALIA_SIGNALS_ADAPTORS_HPP\n#define ALIA_SIGNALS_ADAPTORS_HPP\n\n#include <alia/signals/utilities.hpp>\n\nnamespace alia {\n\n// fake_readability(s), where :s is a signal, yields a wrapper for :s that\n// pretends to have read capabilities. It will never actually be readable, but\n// it will type-check as a readable signal.\ntemplate<class Wrapped>\nstruct readability_faker : signal<\n readability_faker<Wrapped>,\n typename Wrapped::value_type,\n typename signal_direction_union<\n read_only_signal,\n typename Wrapped::direction_tag>::type>\n{\n readability_faker(Wrapped wrapped) : wrapped_(wrapped)\n {\n }\n id_interface const&\n value_id() const\n {\n return no_id;\n }\n bool\n is_readable() const\n {\n return false;\n }\n // Since this is only faking readability, read() should never be called.\n // LCOV_EXCL_START\n typename Wrapped::value_type const&\n read() const\n {\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wnull-dereference\"\n#endif\n return *(typename Wrapped::value_type const*) nullptr;\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n }\n // LCOV_EXCL_STOP\n bool\n is_writable() const\n {\n return wrapped_.is_writable();\n }\n void\n write(typename Wrapped::value_type const& value) const\n {\n return wrapped_.write(value);\n }\n\n private:\n Wrapped wrapped_;\n};\ntemplate<class Wrapped>\nreadability_faker<Wrapped>\nfake_readability(Wrapped const& wrapped)\n{\n return readability_faker<Wrapped>(wrapped);\n}\n\n// fake_writability(s), where :s is a signal, yields a wrapper for :s that\n// pretends to have write capabilities. It will never actually be writable, but\n// it will type-check as a writable signal.\ntemplate<class Wrapped>\nstruct writability_faker : signal<\n writability_faker<Wrapped>,\n typename Wrapped::value_type,\n typename signal_direction_union<\n write_only_signal,\n typename Wrapped::direction_tag>::type>\n{\n writability_faker(Wrapped wrapped) : wrapped_(wrapped)\n {\n }\n id_interface const&\n value_id() const\n {\n return wrapped_.value_id();\n }\n bool\n is_readable() const\n {\n return wrapped_.is_readable();\n }\n typename Wrapped::value_type const&\n read() const\n {\n return wrapped_.read();\n }\n bool\n is_writable() const\n {\n return false;\n }\n // Since this is only faking writability, write() should never be called.\n // LCOV_EXCL_START\n void\n write(typename Wrapped::value_type const& value) const\n {\n }\n // LCOV_EXCL_STOP\n\n private:\n Wrapped wrapped_;\n};\ntemplate<class Wrapped>\nwritability_faker<Wrapped>\nfake_writability(Wrapped const& wrapped)\n{\n return writability_faker<Wrapped>(wrapped);\n}\n\n// signal_cast<Value>(x), where :x is a signal, yields a proxy for :x with\n// the value type :Value. The proxy will apply static_casts to convert its\n// own values to and from :x's value type.\ntemplate<class Wrapped, class To>\nstruct signal_caster : regular_signal<\n signal_caster<Wrapped, To>,\n To,\n typename Wrapped::direction_tag>\n{\n signal_caster(Wrapped wrapped) : wrapped_(wrapped)\n {\n }\n bool\n is_readable() const\n {\n return wrapped_.is_readable();\n }\n To const&\n read() const\n {\n return lazy_reader_.read(\n [&] { return static_cast<To>(wrapped_.read()); });\n }\n bool\n is_writable() const\n {\n return wrapped_.is_writable();\n }\n void\n write(To const& value) const\n {\n return wrapped_.write(static_cast<typename Wrapped::value_type>(value));\n }\n\n private:\n Wrapped wrapped_;\n lazy_reader<To> lazy_reader_;\n};\ntemplate<class To, class Wrapped>\nsignal_caster<Wrapped, To>\nsignal_cast(Wrapped const& wrapped)\n{\n return signal_caster<Wrapped, To>(wrapped);\n}\n\n// is_readable(x) yields a signal to a boolean which indicates whether or\n// not x is readable. (The returned signal is always readable itself.)\ntemplate<class Wrapped>\nstruct readability_signal\n : regular_signal<readability_signal<Wrapped>, bool, read_only_signal>\n{\n readability_signal(Wrapped const& wrapped) : wrapped_(wrapped)\n {\n }\n bool\n is_readable() const\n {\n return true;\n }\n bool const&\n read() const\n {\n value_ = wrapped_.is_readable();\n return value_;\n }\n\n private:\n Wrapped wrapped_;\n mutable bool value_;\n};\ntemplate<class Wrapped>\nauto\nis_readable(Wrapped const& wrapped)\n{\n return readability_signal<Wrapped>(wrapped);\n}\n\n// is_writable(x) yields a signal to a boolean which indicates whether or\n// not x is writable. (The returned signal is always readable.)\ntemplate<class Wrapped>\nstruct writability_signal\n : regular_signal<writability_signal<Wrapped>, bool, read_only_signal>\n{\n writability_signal(Wrapped const& wrapped) : wrapped_(wrapped)\n {\n }\n bool\n is_readable() const\n {\n return true;\n }\n bool const&\n read() const\n {\n value_ = wrapped_.is_writable();\n return value_;\n }\n\n private:\n Wrapped wrapped_;\n mutable bool value_;\n};\ntemplate<class Wrapped>\nauto\nis_writable(Wrapped const& wrapped)\n{\n return writability_signal<Wrapped>(wrapped);\n}\n\n// add_fallback(primary, fallback), where :primary and :fallback are both\n// signals, yields another signal whose value is that of :primary if it's\n// readable and that of :fallback otherwise.\n// All writes go directly to :primary.\ntemplate<class Primary, class Fallback>\nstruct fallback_signal : signal<\n fallback_signal<Primary, Fallback>,\n typename Primary::value_type,\n typename Primary::direction_tag>\n{\n fallback_signal()\n {\n }\n fallback_signal(Primary primary, Fallback fallback)\n : primary_(primary), fallback_(fallback)\n {\n }\n bool\n is_readable() const\n {\n return primary_.is_readable() || fallback_.is_readable();\n }\n typename Primary::value_type const&\n read() const\n {\n return primary_.is_readable() ? primary_.read() : fallback_.read();\n }\n id_interface const&\n value_id() const\n {\n id_ = combine_ids(\n make_id(primary_.is_readable()),\n primary_.is_readable() ? ref(primary_.value_id())\n : ref(fallback_.value_id()));\n return id_;\n }\n bool\n is_writable() const\n {\n return primary_.is_writable();\n }\n void\n write(typename Primary::value_type const& value) const\n {\n primary_.write(value);\n }\n\n private:\n mutable id_pair<simple_id<bool>, id_ref> id_;\n Primary primary_;\n Fallback fallback_;\n};\ntemplate<class Primary, class Fallback>\nfallback_signal<Primary, Fallback>\nadd_fallback(Primary const& primary, Fallback const& fallback)\n{\n return fallback_signal<Primary, Fallback>(primary, fallback);\n}\n\n} // namespace alia\n\n#endif\n" }, { "alpha_fraction": 0.49626585841178894, "alphanum_fraction": 0.5003734230995178, "avg_line_length": 32.474998474121094, "blob_id": "2ff008335e59987b2831e4e5310028cc5228599d", "content_id": "ca759a24a29802123968ce11e2d8f35c1dc1be01", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2678, "license_type": "permissive", "max_line_length": 84, "num_lines": 80, "path": "/scripts/generate-distributables.py", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "from pathlib import Path\nimport re\n\ndef generate_single_header(single_header_path, source_dir, module):\n with open(single_header_path, 'w') as output:\n with open('LICENSE.txt') as f:\n lines = f.readlines()\n for line in lines:\n output.write('// ' + line)\n\n output.write('\\n')\n\n output.write('#ifndef ALIA_' + module.upper() + '_HPP\\n')\n output.write('#define ALIA_' + module.upper() + '_HPP\\n')\n\n header_states = {}\n\n def add_header_file(path):\n if path in header_states:\n if header_states[path] == 'done':\n return\n else:\n raise Exception(path + ': cyclical #includes detected')\n else:\n header_states[path] = 'processing'\n\n with open(path) as f:\n lines = f.readlines()\n\n # Check that the last (non-empty) line is an #endif and remove it.\n # (This is the end of the include guard, but we can't recognize it based\n # solely on its content.)\n while lines[-1].strip() == \"\":\n del lines[-1]\n if lines[-1].strip() != \"#endif\":\n raise Exception(path + ': header files must end with #endif')\n del lines[-1]\n\n for line in lines:\n # Recursively process #include'd files so that they're inlined.\n include = re.match(r'^\\s*#include <(alia/[a-z0-9/_\\.]+)>', line)\n if include:\n add_header_file('src/' + include.group(1))\n continue\n\n # Strip out include guards.\n if re.match(r'^\\s*#(ifndef|define) ALIA_[A-Z0-9_]+_HPP', line):\n continue\n\n output.write(line)\n\n header_states[path] = 'done'\n\n def add_source_file(path):\n with open(path) as f:\n lines = f.readlines()\n\n for line in lines:\n # All internal headers should've already been included.\n include = re.match(r'^\\s*#include <(alia/[a-z0-9/_\\.]+)>', line)\n if include:\n continue\n\n output.write(line)\n\n header_paths = Path(source_dir).glob('**/*.hpp')\n for path in header_paths:\n add_header_file(str(path))\n\n output.write('#ifdef ALIA_IMPLEMENTATION\\n')\n\n source_paths = Path(source_dir).glob('**/*.cpp')\n for path in source_paths:\n add_source_file(str(path))\n\n output.write('#endif\\n')\n\n output.write('#endif\\n')\n\ngenerate_single_header('alia.hpp', 'src/alia', 'core')\n" }, { "alpha_fraction": 0.6689283847808838, "alphanum_fraction": 0.6703322529792786, "avg_line_length": 18.695852279663086, "blob_id": "70d92df9f9ee3bf23126ff91c68467f5e1fb33d0", "content_id": "1c4d0b68ce68a419bad34dffc3816584cd315821", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4274, "license_type": "permissive", "max_line_length": 78, "num_lines": 217, "path": "/src/alia/context.hpp", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "#ifndef ALIA_CONTEXT_HPP\n#define ALIA_CONTEXT_HPP\n\n#include <alia/component_collection.hpp>\n#include <alia/data_graph.hpp>\n\nnamespace alia {\n\nstruct data_traversal_tag\n{\n};\nstruct data_traversal;\n\nstruct event_traversal_tag\n{\n};\nstruct event_traversal;\n\nstruct any_pointer\n{\n any_pointer()\n {\n }\n\n template<class T>\n any_pointer(T* ptr) : ptr(ptr)\n {\n }\n\n template<class T>\n operator T*()\n {\n return reinterpret_cast<T*>(ptr);\n }\n\n void* ptr;\n};\n\ntemplate<class T>\nbool\noperator==(any_pointer p, T* other)\n{\n return reinterpret_cast<T*>(p.ptr) == other;\n}\ntemplate<class T>\nbool\noperator==(T* other, any_pointer p)\n{\n return other == reinterpret_cast<T*>(p.ptr);\n}\ntemplate<class T>\nbool\noperator!=(any_pointer p, T* other)\n{\n return reinterpret_cast<T*>(p.ptr) != other;\n}\ntemplate<class T>\nbool\noperator!=(T* other, any_pointer p)\n{\n return other != reinterpret_cast<T*>(p.ptr);\n}\n\n// The structure we use to store components. It provides direct storage of the\n// commonly-used components in the core of alia.\nstruct component_storage\n{\n data_traversal* data = 0;\n event_traversal* event = 0;\n // generic storage for other components\n generic_component_storage<any_pointer> other;\n};\n\n// All component access is done through the following 'manipulator' structure.\n// Specializations can be defined for tags that have direct storage.\n\ntemplate<class Tag>\nstruct component_manipulator\n{\n static bool\n has(component_storage& storage)\n {\n return has_component<Tag>(storage.other);\n }\n static void\n add(component_storage& storage, any_pointer data)\n {\n add_component<Tag>(storage.other, data);\n }\n static void\n remove(component_storage& storage)\n {\n remove_component<Tag>(storage.other);\n }\n static any_pointer\n get(component_storage& storage)\n {\n return get_component<Tag>(storage.other);\n }\n};\n\ntemplate<>\nstruct component_manipulator<data_traversal_tag>\n{\n static bool\n has(component_storage& storage)\n {\n return storage.data != 0;\n }\n static void\n add(component_storage& storage, data_traversal* data)\n {\n storage.data = data;\n }\n static void\n remove(component_storage& storage)\n {\n storage.data = 0;\n }\n static data_traversal*\n get(component_storage& storage)\n {\n return storage.data;\n }\n};\n\ntemplate<>\nstruct component_manipulator<event_traversal_tag>\n{\n static bool\n has(component_storage& storage)\n {\n return storage.event != 0;\n }\n static void\n add(component_storage& storage, event_traversal* event)\n {\n storage.event = event;\n }\n static void\n remove(component_storage& storage)\n {\n storage.event = 0;\n }\n static event_traversal*\n get(component_storage& storage)\n {\n return storage.event;\n }\n};\n\n// The following is the implementation of the interface expected of component\n// storage objects. It simply forwards the requests along to the appropriate\n// manipulator.\n\ntemplate<class Tag>\nbool\nhas_component(component_storage& storage)\n{\n return component_manipulator<Tag>::has(storage);\n}\n\ntemplate<class Tag, class Data>\nvoid\nadd_component(component_storage& storage, Data&& data)\n{\n component_manipulator<Tag>::add(storage, std::forward<Data&&>(data));\n}\n\ntemplate<class Tag>\nvoid\nremove_component(component_storage& storage)\n{\n component_manipulator<Tag>::remove(storage);\n}\n\ntemplate<class Tag>\nauto\nget_component(component_storage& storage)\n{\n return component_manipulator<Tag>::get(storage);\n}\n\n// Finally, the typedef for the context...\n\ntypedef add_component_type_t<\n add_component_type_t<\n empty_component_collection<component_storage>,\n event_traversal_tag,\n event_traversal*>,\n data_traversal_tag,\n data_traversal*>\n context;\n\n// And some convenience functions...\n\ninline data_traversal&\nget_data_traversal(context& ctx)\n{\n return *get_component<data_traversal_tag>(ctx);\n}\n\ninline bool\nis_refresh_pass(context& ctx)\n{\n return get_data_traversal(ctx).gc_enabled;\n}\n\ninline event_traversal&\nget_event_traversal(context& ctx)\n{\n return *get_component<event_traversal_tag>(ctx);\n}\n\n} // namespace alia\n\n#endif\n" }, { "alpha_fraction": 0.5744966268539429, "alphanum_fraction": 0.581879198551178, "avg_line_length": 37.20512771606445, "blob_id": "d9ab648302876e87a6c44f482af79078c8d3b913", "content_id": "7f292f9fdc01978d2db0cdcbb1e0d35236be7d50", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1490, "license_type": "permissive", "max_line_length": 78, "num_lines": 39, "path": "/conanfile.py", "repo_name": "blockspacer/alia", "src_encoding": "UTF-8", "text": "from conans import ConanFile, CMake\nimport os\n\n\nclass CradleConan(ConanFile):\n settings = \"os\", \"compiler\", \"build_type\", \"arch\"\n requires = \\\n \"catch2/2.3.0@bincrafters/stable\", \\\n \"FakeIt/2.0.4@gasuketsu/stable\"\n generators = \"cmake\"\n default_options = \\\n \"FakeIt:integration=catch\", \\\n \"*:shared=False\"\n if \"APPVEYOR\" not in os.environ:\n # AppVeyor provides Boost directly (and seems to have trouble building\n # it through Conan), so omit Boost if we're running on AppVeyor.\n requires = requires + (\"boost/1.68.0@conan/stable\", )\n default_options = default_options + \\\n (\"boost:without_atomic=True\",\n \"boost:without_chrono=True\",\n \"boost:without_container=True\",\n \"boost:without_context=True\",\n \"boost:without_coroutine=True\",\n \"boost:without_graph=True\",\n \"boost:without_graph_parallel=True\",\n \"boost:without_log=True\",\n \"boost:without_math=True\",\n \"boost:without_mpi=True\",\n \"boost:without_serialization=True\",\n \"boost:without_signals=True\",\n \"boost:without_test=True\",\n \"boost:without_timer=True\",\n \"boost:without_type_erasure=True\",\n \"boost:without_wave=True\")\n\n def imports(self):\n dest = os.getenv(\"CONAN_IMPORT_PATH\", \"bin\")\n self.copy(\"*.dll\", dst=dest, src=\"bin\")\n self.copy(\"*.dylib*\", dst=dest, src=\"lib\")\n" } ]
50
hugoabreu1002/PRF
https://github.com/hugoabreu1002/PRF
1785946452ba405eab31f7ea721794775adbaa32
94fb8f8643e98e3a29469c0a1ea2bf2088a6f61c
0c78993ec99f74cc51b34468dd0bf3538af157a2
refs/heads/master
2021-01-07T11:47:29.455819
2020-02-27T11:12:00
2020-02-27T11:12:00
241,681,683
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5089011788368225, "alphanum_fraction": 0.519336998462677, "avg_line_length": 38.41935348510742, "blob_id": "79c2c845209465bd3513bcf8e0827afded5dfd61", "content_id": "2f74b64ff3d3c9a224e9728a8aa10cac8dbfdfc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4890, "license_type": "no_license", "max_line_length": 130, "num_lines": 124, "path": "/gen_pad.py", "repo_name": "hugoabreu1002/PRF", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport matplotlib.pyplot as plt\nimport datetime as dt\nimport numpy as np\nfrom tqdm import tqdm\nimport sys\n\ndef padding_for_year(df, v_year=2019, days_to_pad=366):\n \n map_weekday = {0:'segunda',1:'terça',2:'quarta',3:'quinta',4:'sexta',5:'sábado',6:'domingo'}\n\n df.sort_values(by='data')\n periodos = df.periodo.unique()\n data_min = dt.datetime(v_year,1,1)\n\n df_year_padded = pd.DataFrame(columns=df.columns)\n\n zero_padding_dict = {}\n for c in df.columns:\n zero_padding_dict[c] = [0]\n\n zero_padding_dict['ano'] = [v_year]\n\n dfy = df[(df.ano == v_year)]\n\n for br_selected in tqdm(dfy.br.unique()):\n \n zero_padding_dict['br'] = br_selected\n dfb = dfy[(dfy.br==br_selected)]\n\n for kmb in tqdm(dfb.km_bins.unique()):\n\n zero_padding_dict['km_bins'] = [kmb]\n zero_padding_dict['tracado_via'] = [dfb[(dfb.km_bins == kmb)].tracado_via.mode().values[0]]\n zero_padding_dict['tipo_pista'] = [dfb[(dfb.km_bins == kmb)].tipo_pista.mode().values[0]]\n zero_padding_dict['tracado_via'] = [dfb[(dfb.km_bins == kmb)].tracado_via.mode().values[0]]\n zero_padding_dict['uso_solo'] = [dfb[(dfb.km_bins == kmb)].uso_solo.mode().values[0]]\n \n data = data_min\n for day in range(1, days_to_pad):\n zero_padding_dict['data'] = data\n month = data.month\n dia = data.day\n\n dfmd = dfb[(dfb.month_number == month) & (dfb.dia == dia)]\n\n try:\n last_meteo = dfmd.condicao_meteorologica.mode().values[0]\n except:\n last_meteo = 'ignorada'\n\n zero_padding_dict['month_number'] = [month]\n zero_padding_dict['dia'] = [dia]\n zero_padding_dict['dia_semana'] = map_weekday[data.weekday()]\n\n try:\n zero_padding_dict['feriado'] = dfmd.feriado.mode().values[0]\n except:\n zero_padding_dict['feriado'] = 'not-feriado'\n\n for p in periodos:\n df_to_append = dfmd[(dfmd.km_bins == kmb) & (dfmd.periodo == p)].copy()\n\n if len(df_to_append) == 1:\n df_year_padded = df_year_padded.append(df_to_append, ignore_index=True)\n last_meteo = df_to_append.condicao_meteorologica.values[0]\n \n elif len(df_to_append) > 1:\n to_sum_cols = ['mortos', 'feridos_leves', 'feridos_graves','ilesos', 'ignorados', 'feridos', 'veiculos']\n all_other_cols = list(set(dfmd.columns) - set(to_sum_cols))\n\n dict_to_append_squished = {}\n\n for sc in to_sum_cols:\n dict_to_append_squished[sc] = [df_to_append[sc].sum()]\n\n for aoc in all_other_cols:\n dict_to_append_squished[aoc] = [df_to_append[aoc].mode().values[0]]\n\n df_year_padded = df_year_padded.append(pd.DataFrame.from_dict(dict_to_append_squished), ignore_index=True)\n\n else: \n zero_padding_dict['periodo'] = [p]\n zero_padding_dict['condicao_meteorologica'] = [last_meteo]\n df_year_padded = df_year_padded.append(pd.DataFrame.from_dict(zero_padding_dict), ignore_index=True)\n \n data = data_min + dt.timedelta(days=day)\n \n return df_year_padded\n\nif __name__ == \"__main__\":\n\n df = pd.read_csv('data/partial_pedataset.csv')\n\n clima_replace = {\n 'sol': 'tempo_claro',\n 'céu_claro': 'tempo_claro',\n 'ignorado': 'ignorado',\n 'chuva': 'tempo_adverso',\n 'nublado': 'tempo_adverso',\n 'nevoeiro_neblina': 'tempo_adverso'\n }\n\n for d in clima_replace:\n df.condicao_meteorologica.replace(to_replace=d,\n value=clima_replace[d],\n inplace=True)\n\n df.drop(['mes'], axis=1, inplace=True)\n df['dia'] = [int(str(d)[8:10]) for d in pd.to_datetime(df['timestamp'])]\n df['data'] = pd.to_datetime(df.timestamp, yearfirst=True, errors='ignore')\n df.drop([\n 'timestamp', 'municipio', 'tipo_acidente', 'classificacao_acidente', 'fase_dia',\n 'sentido_via', 'pessoas', 'label','causa_acidente','uf'],axis=1, inplace=True)\n\n df = df[((df['br']==104) | (df['br']==232) & (df['km']>=102)& (df['km']<=213))]\n\n df_year = df[df.ano==int(sys.argv[1])]\n\n print(df_year.head())\n\n df_year_new = padding_for_year(df_year, v_year=int(sys.argv[1]), days_to_pad=int(sys.argv[2]))\n\n df_year_new.to_excel('df_'+str(sys.argv[1])[-2:]+'_pad_'+str(sys.argv[2])+'.xlsx',index=None)" }, { "alpha_fraction": 0.7191489338874817, "alphanum_fraction": 0.7390071153640747, "avg_line_length": 77.33333587646484, "blob_id": "6077a6659053e88d3481b02237a672cd9a8c1b87", "content_id": "beab572ab7c1b6e2f3e58886a0a21498975d0295", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 710, "license_type": "no_license", "max_line_length": 159, "num_lines": 9, "path": "/descriptions/scripts_description.md", "repo_name": "hugoabreu1002/PRF", "src_encoding": "UTF-8", "text": "1. Baixe a pasta [data](https://drive.google.com/file/d/1tkH4g0LdXCOmddav0k9Zp09PucXEjgpJ/view) e salve no diretório do projeto.\n2. Para gerar a base limpa: execute [cleaning_calls](../cleaning_calls.py) para generar \"data/cleanedf.csv\"\n * Depende do pacote [defs](../defs.py) \n3. Para gerar a base pre-processada: execute [preposs_calls](../preposs_calls.py) para gerar \"data/partial_pedataset.csv\"\n * Depende do pacote [defs](../defs.py)\n4. [PRF_viz](PRF_viz.ipynb) é utilizado para o binder\n * [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/leonardoluzserrano/ProjetoPRF/binder-preview?urlpath=%2Fapps%2FPRF_viz.ipynb)\n \nOutros notebooks são para prototipação.\n" }, { "alpha_fraction": 0.5584470629692078, "alphanum_fraction": 0.5611197352409363, "avg_line_length": 38.49444580078125, "blob_id": "f493dc02a32d0d1a1552cf0566d8ede2bdf74779", "content_id": "6f88c0c2d34e78464a4816427ac6b571e1920663", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7109, "license_type": "no_license", "max_line_length": 151, "num_lines": 180, "path": "/dash/comp.py", "repo_name": "hugoabreu1002/PRF", "src_encoding": "UTF-8", "text": "from ipywidgets import widgets\nimport math\n\nclass Component(object):\n\n def __init__(self, feature, label, comparison_type=None, update_based_on=None):\n self.feature = feature\n self.label = label\n self.comparison_type = comparison_type\n self.update_based_on = update_based_on\n\n def create_component(self, dataframe):\n raise NotImplementedError(\"The method hasn't been implemented yet.\")\n\n def callback(self, change):\n raise NotImplementedError(\"The method hasn't been implemented yet.\")\n\n def _set_callback(self):\n raise NotImplementedError(\"The method hasn't been implemented yet.\")\n\n def _remove_callback(self):\n raise NotImplementedError(\"The method hasn't been implemented yet.\")\n\n def reset_options(self):\n self._remove_callback()\n self._reset_options()\n self._set_callback()\n\n def _reset_options(self):\n raise NotImplementedError(\"The method hasn't been implemented yet.\")\n\n def update_options(self, dataframe):\n self._remove_callback()\n self._update_options(dataframe)\n self._set_callback()\n\n def _update_options(self, dataframe):\n raise NotImplementedError(\"The method hasn't been implemented yet.\")\n\n def query_string(self):\n if self.comparison_type == 'equals':\n return self._equals()\n elif self.comparison_type == 'interval':\n return self._interval()\n else:\n return None\n\n def _equals(self):\n raise NotImplementedError(\"The method hasn't been implemented yet.\")\n \n def _interval(self):\n raise NotImplementedError(\"The method hasn't been implemented yet.\")\n\nclass FeatureBoxComponent(Component):\n\n def __init__(self, feature, label, comparison_type='equals', update_based_on=None, any_option='Todos', empty_options=False, options_sort_key=None):\n Component.__init__(self, feature, label, comparison_type, update_based_on)\n self.component = None\n self.handler = None\n self.any_option = any_option\n self.empty_options = empty_options\n self.initial_options = None\n self.options_sort_key = options_sort_key\n\n def _create_options(self, dataframe):\n unique_values = dataframe[self.feature].unique()\n unique_values = sorted(unique_values, key=self.options_sort_key)\n return [self.any_option, *unique_values] \n \n def create_component(self, dataframe):\n if not self.empty_options:\n self.initial_options = self._create_options(dataframe)\n else:\n self.initial_options = [self.any_option]\n\n options = self.initial_options.copy()\n self.component = widgets.Dropdown(description=self.label, value=options[0], options=options)\n self._set_callback()\n \n def callback(self, change):\n self.handler(self.feature, change)\n \n def _set_callback(self):\n self.component.observe(self.callback, names='value')\n \n def _remove_callback(self):\n self.component.unobserve(self.callback, names='value')\n \n def _set_component_options(self, options, value):\n self.component.options = options\n self.component.value = options[0]\n \n def _reset_options(self):\n options = self.initial_options.copy()\n self._set_component_options(options, options[0])\n \n def _update_options(self, dataframe):\n options = self._create_options(dataframe)\n self._set_component_options(options, options[0])\n \n def _equals(self):\n if self.component.value == self.any_option:\n return None\n return '{} == \"{}\"'.format(self.feature, self.component.value)\n\nclass RankSliderComponent(Component):\n\n def __init__(self, feature, label, slider_range=(0,15), comparison_type=None, update_based_on=None):\n Component.__init__(self, feature, label, comparison_type, update_based_on)\n self.slider_range = slider_range\n self.component = None\n self.handler = None\n \n def create_component(self, dataframe):\n self.component = widgets.IntSlider(value=0,\n min=self.slider_range[0],\n max=self.slider_range[1],\n step=1,\n description=self.label,\n continuous_update=True,\n orientation='vertical',\n readout=True,\n readout_format='d'\n )\n self.component.observe(self.callback, names='value')\n \n def callback(self, change):\n self.handler(self.feature, change)\n\nclass IntervalSliderComponent(Component):\n\n def __init__(self, feature, label, slider_range=(0,15), comparison_type='interval', update_based_on=None):\n Component.__init__(self, feature, label, comparison_type, update_based_on)\n self.slider_range = slider_range\n self.component = None\n self.handler = None\n \n def create_component(self, dataframe):\n self.component = widgets.IntRangeSlider(value=self.slider_range,\n min=self.slider_range[0], \n max=self.slider_range[1],\n step=1,\n description=self.label,\n disabled=False,\n continuous_update=True,\n orientation='vertical',\n readout=True,\n readout_format='d'\n )\n self._set_callback()\n \n def _update_options(self, dataframe):\n try:\n min_value = math.floor(dataframe[self.feature].min())\n max_value = math.ceil(dataframe[self.feature].max())\n if min_value > self.component.max:\n self.component.max = max_value\n self.component.min = min_value\n else:\n self.component.min = min_value\n self.component.max = max_value\n \n self.component.value = (self.component.min, self.component.max)\n self.component.disabled = False\n except Exception:\n self.component.disabled = True\n \n def callback(self, change):\n self.handler(self.feature, change)\n\n def _set_callback(self):\n self.component.observe(self.callback, names='value')\n \n def _remove_callback(self):\n self.component.unobserve(self.callback, names='value')\n\n def _interval(self):\n if self.component.disabled:\n return None\n return '{} <= {} < {}'.format(self.component.value[0], self.feature, self.component.value[1])\n" }, { "alpha_fraction": 0.5342649817466736, "alphanum_fraction": 0.5493146777153015, "avg_line_length": 40.33333206176758, "blob_id": "ca7971660a1bc1726f449adb766eb981f586ea78", "content_id": "8092c002d717de48a9e1d193296bd370214c72ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3721, "license_type": "no_license", "max_line_length": 116, "num_lines": 90, "path": "/dash/plot.py", "repo_name": "hugoabreu1002/PRF", "src_encoding": "UTF-8", "text": "import plotly.graph_objects as go\nimport plotly.express as px\n\nclass Plot(object):\n\n def __init__(self, title, layout=None):\n self.title = title\n self.layout = layout\n\n def _create_plot(self, dataframe):\n raise NotImplementedError(\"The method hasn't been implemented yet.\")\n\n def update_plot(self, dataframe):\n raise NotImplementedError(\"The method hasn't been implemented yet.\")\n\nclass MapPlot(Plot):\n\n def __init__(self, title, lat_col, lon_col, z_col, hovertext_cols, layout=None):\n Plot.__init__(self, title, layout)\n self.lat_col = lat_col\n self.lon_col = lon_col\n self.z_col = z_col\n self.hovertext_cols = hovertext_cols\n\nclass ScatterMapPlot(MapPlot):\n\n def __init__(self, title, lat_col, lon_col, z_col, hovertext_cols, layout=None, colorscale='plasma'):\n MapPlot.__init__(self, title, lat_col, lon_col, z_col, hovertext_cols, layout)\n self.figure = None\n self.colorscale = colorscale\n\n def _create_plot(self, dataframe):\n \n plot_parameters = dict(data_frame = dataframe, \n lat=self.lat_col, lon=self.lon_col,\n color_continuous_scale=self.colorscale,\n # range_color=[0,1],\n zoom=6, height=700,\n title=self.title,\n size=self.z_col,\n color=self.z_col,\n hover_data=self.hovertext_cols)\n \n# if self.z_col[-8:] != 'relativo':\n# print(self.z_col)\n# plot_parameters.pop('range_color')\n \n plot = px.scatter_mapbox(**plot_parameters)\n \n plot.update_layout(mapbox_style=\"open-street-map\")\n self.figure = go.FigureWidget(plot)\n\n def update_plot(self, dataframe):\n \n with self.figure.batch_update():\n self.figure.data[0].lat = dataframe[self.lat_col].values\n self.figure.data[0].lon = dataframe[self.lon_col].values\n self.figure.data[0].marker.size = dataframe[self.z_col] if dataframe[self.z_col].values.size != 0 else 0\n self.figure.data[0].marker.color = dataframe[self.z_col]\n self.figure.data[0].customdata = dataframe[self.hovertext_cols].values\n\nclass DensityMapPlot(MapPlot):\n\n def __init__(self, title, lat_col, lon_col, z_col, hovertext_cols, layout=None):\n MapPlot.__init__(self, title, lat_col, lon_col, z_col, hovertext_cols, layout)\n self.figure = None\n\n def _create_plot(self, dataframe):\n mapbox = go.Densitymapbox(lat=dataframe[self.lat_col], \n lon=dataframe[self.lon_col], \n z=dataframe[self.z_col], radius=10,\n #ids=df['id'], \n text=dataframe[self.hovertext_cols], hoverinfo='all'\n )\n \n layout = {'title': self.title,\n 'mapbox_style': 'open-street-map',\n 'height': 700,\n 'mapbox_zoom': 6,\n 'mapbox_center': {'lat': -8.435386868049687, 'lon': -36.95741641661875}\n }\n \n self.figure = go.FigureWidget(go.Figure(mapbox, layout=layout))\n\n def update_plot(self, dataframe):\n with self.figure.batch_update():\n self.figure.data[0].lat = dataframe[self.lat_col].values\n self.figure.data[0].lon = dataframe[self.lon_col].values\n self.figure.data[0].z = dataframe[self.z_col].values\n self.figure.data[0].customdata = dataframe[self.hovertext_cols].values\n\n" }, { "alpha_fraction": 0.6893125772476196, "alphanum_fraction": 0.704081654548645, "avg_line_length": 37, "blob_id": "5284fe07c34f61d103108336ff1bd197fdea8f85", "content_id": "b62aa9fe3ac8e8e52269cefadd3dbe797f44c6b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3729, "license_type": "no_license", "max_line_length": 283, "num_lines": 98, "path": "/descriptions/data_dict.md", "repo_name": "hugoabreu1002/PRF", "src_encoding": "UTF-8", "text": "# Info\n\n## Datasets\n\n> The data groups information about accident occurences in Brazilian roads from 2007 to 2019. Every year is provided as a separate dataset. Begining in the year 2017 new columns reporting geocoordinates and operational information have been added.\n\n## Data dictionary\n\n> - **id**:\nint, identifies the accidents.\n\n> - **data_inversa**: string, accident date.\n\n> - **dia_semana**: string, day of the week.\n\n> - **horario**: string, accident time. In the 24hr format hh:mm:ss.\n\n> - **uf**: string, state.\n\n> - **br**: int, road identification.\n\n> - **km**: float, road KM on which the accident took place.\n\n> - **municipio**: string, city name.\n\n> - **causa_acidente**: string, presumable cause of accident.\n\n> - **tipo_acidente**: string, type of accident.\n\n> - **classificacao_acidente**: string, rating of accident gravity based if casualities or injured were reported. Can assume 4 values 'Sem Vítimas', 'Com Vítimas Feridas', 'Com Vítimas Fatais' or 'Ignorado'. 'Ignorado' is used for occurences in which victims states weren't reported.\n\n> - **fase_dia**: string, stage of the day the accident occured. Can assume the values: 'Pleno dia', 'Plena noite', 'Amanhecer' or 'Anoitecer'.\n\n> - **sentido_via**: string, way of the road considering the collision point. Can be 'Crescente' or 'Decrescente'.\n\n> - **condicao_metereologica**: string, description of wheater condition at the time of accident.\n\n> - **tipo_pista**: string, road type based on the number of lanes. Can assume the values: 'Dupla', 'Simples' or 'Múltipla'.\n\n> - **tracado_via**: string, description of road layout.\n\n> - **uso_solo**: string, description of the local of the accident.\n\n> - **ano**: int, year the accident occured. This column is present untill 2015.\n\n> - **pessoas**: int, number of people involved in the accident.\n\n> - **mortos**: int, number of casualties.\n\n> - **feridos_leves**: int, number of slightly injured.\n\n> - **feridos_graves**: int, number of seriously injured.\n\n> - **ilesos**: int, number of uninjured people.\n\n> - **ignorados**: int, number of involved people which health states weren't reported.\n\n> - **feridos**: int, total number of injured people. Sum of 'feridos_leves' and 'feridos_graves'.\n\n> - **veiculos**: int, number of vehicles involved in the accident.\n\n### Features added to 2017 dataset onwards\n\n> - **latitude**: float, latitude coordinate.\n\n> - **longitude**: float, longitude coordinate.\n\n> - **regional/delegacia/uop**: string, PRF operational information.\n\n## Missing values\n\n> - Missing values appear in the form of a **'(null)'** string in the raw datasets.\n\n## Issues\n\n> - **id**: Values are unique in the same year and can repeat between different years.\n\n> - **data_inversa**: Variable name suggests it comes in a year first format, however the format is not consistent across years. It can appear in year first or day first formats and use '/' or '-' as separators.\n\n> - **dia_semana**: Names are capitalized till 2016. From 2017 onwards names aren't capitalized and the suffix '-feira' is added.\n\n> - **km**: Starting 2016 a comma is used as decimal point.\n\n> - **classificacao_acidente**: Missing values which can be infered from some numeric columns.\n\n> - **condicao_metereologica**: Column name typo.\n\n> - **uso_solo**: Till 2016 can assume values 'Urbano' or 'Rural'. From 2017 onwards: 'Sim' for 'Urbano' or 'Não' for 'Rural'.\n\n> - **ano**: This column is dropped after 2015.\n\n> - **pessoas**: Some rows have inconsistent values for this column.\n\n> - **latitude/longitude**: Present in datasets starting in 2017. In 2019 values have a comma for decimal point.\n\n> - **string columns**: Minor differences in values occur due to whitespaces, capitalization or typos\n\n---\n" }, { "alpha_fraction": 0.6551724076271057, "alphanum_fraction": 0.7586206793785095, "avg_line_length": 8.666666984558105, "blob_id": "fc0005b317dc2ccbe3c8c724209171ce1f5b12ae", "content_id": "b7781613c80b07b4aaeff6de16882244075b4566", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 29, "license_type": "no_license", "max_line_length": 13, "num_lines": 3, "path": "/binder/requirements.txt", "repo_name": "hugoabreu1002/PRF", "src_encoding": "UTF-8", "text": "pandas\nplotly==4.3.0\nappmode\n" }, { "alpha_fraction": 0.5538057684898376, "alphanum_fraction": 0.5577427744865417, "avg_line_length": 32.77777862548828, "blob_id": "a853496f0027e64a73025d47d61542d366e3a467", "content_id": "aa8b62afd846172990f135276ec958e6b85c81d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1528, "license_type": "no_license", "max_line_length": 113, "num_lines": 45, "path": "/dash/helpers.py", "repo_name": "hugoabreu1002/PRF", "src_encoding": "UTF-8", "text": "# Funções Helper para update dos DataFrames\n\n\n# Para atualizar o número de acidentes nos trechos filtrados\ndef update_acidentes_trecho(df):\n df.loc[:, \"acidentes_trecho\"] = df[\"trecho\"].replace( dict(df[\"trecho\"].value_counts()) )\n \n \n# Para atualizar o número de mortes nos trechos filtrados\ndef update_mortes_trecho(df):\n dicionario = {trecho:df[df[\"trecho\"] == trecho][\"mortos_original\"].sum() for trecho in df[\"trecho\"].unique()}\n \n df.loc[:, \"mortos_trecho\"] = df[\"trecho\"].replace(dicionario)\n\n \ndef update_relativo(df, col):\n col_relativo = col[:-7] + \"_relativo\"\n \n df.loc[:, col_relativo] = (df[col]/df[col].max()) if (df[col].max() != 0) else 0\n \n \ndef rank_order(col):\n \n mortos_acidentes = ['mortos_trecho', 'acidentes_trecho']\n \n dicionario = {'mortos_trecho': mortos_acidentes,\n 'acidentes_trecho': mortos_acidentes[::-1],\n 'mortos_relativo': mortos_acidentes, \n 'acidentes_relativo': mortos_acidentes[::-1]}\n \n return dicionario[col]\n \n\n \n \n# def update_mortes_trecho(df):\n \n# helperdf = df[[\"trecho\", \"mortos_original\"]].copy()\n \n# mortos_update = helperdf.groupby(\"trecho\").sum()\n \n# df[\"mortos_trecho\"] = helperdf.merge(mortos_update, \n# on = \"trecho\", \n# suffixes= ('', '__trecho_update')\n# )[\"mortos_original__trecho_update\"].fillna(value= 0) \n" }, { "alpha_fraction": 0.5500129461288452, "alphanum_fraction": 0.5544068217277527, "avg_line_length": 37.30693054199219, "blob_id": "6f4f477c26af54da17c55ca8f14db8b176436754", "content_id": "a30640f9698c958de7db9baac858a1cc8d3620be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3869, "license_type": "no_license", "max_line_length": 109, "num_lines": 101, "path": "/dash/dash.py", "repo_name": "hugoabreu1002/PRF", "src_encoding": "UTF-8", "text": "from ipywidgets import widgets\nimport pandas as pd\n\nfrom dash.helpers import *\n\nclass Dashboard(object):\n\n def __init__(self, dataframe, mapbox):\n self.dataframe = dataframe\n self.mapbox = mapbox\n self.boxes = []\n self.rank_slider = None\n self.output = None\n self.range_slider = None\n \n def add_box(self, box):\n self.boxes.append(box)\n\n def update(self, col, change):\n conditions = []\n for box in self.boxes:\n if box.update_based_on == col:\n box.update_options(self.dataframe[self.dataframe[col] == change.new])\n\n if box.query_string() != None:\n conditions.append(box.query_string())\n \n if self.range_slider:\n if self.range_slider.update_based_on == col:\n self.range_slider.update_options(self.dataframe[self.dataframe[col] == change.new])\n \n if self.range_slider.query_string() != None:\n conditions.append(self.range_slider.query_string())\n\n try:\n query_template = (len(conditions)-1)*'{} & ' + '{}'\n query_string = query_template.format(*conditions)\n temp_df = self.dataframe.query(query_string)\n \n # Contar num de acidentes nos trechos de acordo com a base filtrada\n update_acidentes_trecho(temp_df)\n \n # Contar num de mortes nos trechos de acordo com a base filtrada\n update_mortes_trecho(temp_df)\n \n # Atualizando fracoes de acidentes/mortos relativos ao valor maximo\n update_relativo(temp_df, \"acidentes_trecho\")\n update_relativo(temp_df, \"mortos_trecho\")\n \n except:\n temp_df = self.dataframe\n \n temp_df = temp_df.drop_duplicates(subset='trecho', keep='first')\n \n if self.rank_slider:\n rank = self.rank_slider.component.value\n if rank != 0:\n temp_df = temp_df.sort_values(by=self.mapbox.z_col, axis=0, ascending=False).head(rank)\n self.output.clear_output(wait=True)\n with self.output:\n display(temp_df[self.mapbox.hovertext_cols]\n .sort_values( rank_order(self.mapbox.z_col) , ascending = False)\n .iloc[:, ::-1]\n .set_index(pd.Index(list(map(lambda x : x + 1 ,\n range(len(temp_df[self.mapbox.hovertext_cols])))))))\n\n else:\n self.output.clear_output(wait=False)\n\n self.mapbox.update_plot(temp_df)\n \n def _set_up(self):\n self.mapbox._create_plot(self.dataframe.drop_duplicates(subset='trecho', keep='first'))\n\n self.output = widgets.Output(layout={'border': '1px solid black'})\n\n for box in self.boxes:\n box.create_component(self.dataframe)\n box.handler = self.update\n \n c1 = widgets.HBox(children=[box.component for box in self.boxes])\n \n \n if (self.rank_slider != None) & (self.range_slider != None):\n self.rank_slider.create_component(None)\n self.rank_slider.handler = self.update\n \n self.range_slider.create_component(None)\n self.range_slider.handler = self.update\n self.range_slider.component.disabled = True\n\n c2 = widgets.VBox(children=[c1, self.mapbox.figure, self.output])\n c3 = widgets.VBox(children=[self.rank_slider.component, self.range_slider.component])\n c4 = widgets.HBox(children=[c3, c2])\n return c4\n \n c2 = widgets.VBox(children=[c1, self.mapbox.figure])\n return widgets.HBox(children=[self.output, c2])\n\n def dash(self):\n return self._set_up()\n" }, { "alpha_fraction": 0.4422788619995117, "alphanum_fraction": 0.622188925743103, "avg_line_length": 36.11111068725586, "blob_id": "654091d5a7c9e6226424caf5e3211132da924865", "content_id": "7d5fca4a140a67e80bfab6d3368609b08938dc42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 667, "license_type": "no_license", "max_line_length": 69, "num_lines": 18, "path": "/padding_concat.py", "repo_name": "hugoabreu1002/PRF", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport sys\n\nif __name__ == \"__main__\":\n\n df_19_pad = pd.read_excel('df_19_pad.xlsx')\n df_18_pad = pd.read_excel('df_18_pad.xlsx')\n df_17_pad = pd.read_excel('df_17_pad.xlsx')\n df_16_pad = pd.read_excel('df_16_pad.xlsx')\n\n df_19_18_17_16_pad = df_19_pad.copy()\n df_19_18_17_16_pad = df_19_18_17_16_pad.append(df_18_pad)\n df_19_18_17_16_pad.reset_index(inplace=True)\n df_19_18_17_16_pad = df_19_18_17_16_pad.append(df_17_pad)\n df_19_18_17_16_pad = df_19_18_17_16_pad.append(df_16_pad)\n\n df_19_18_17_16_pad.to_excel('df_19_18_17_16_pad.xlsx',index=None)\n df_19_18_17_16_pad.to_csv('df_19_18_17_16_pad.csv',index=None)" }, { "alpha_fraction": 0.5850746035575867, "alphanum_fraction": 0.6805970072746277, "avg_line_length": 37.17142868041992, "blob_id": "3fd3a29ea4a2a3f2a723ddb46c7a4addac76bdc6", "content_id": "135247c0a763e229f92a71252b228c5904f16359", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1365, "license_type": "no_license", "max_line_length": 95, "num_lines": 35, "path": "/descriptions/feriados_municipais.md", "repo_name": "hugoabreu1002/PRF", "src_encoding": "UTF-8", "text": "\n\n## Feriados Recife\n 10/04/2020 ( sexta-feira ) - Sexta-feira Santa ( Feriado municipal )\n 24/06/2020 ( quarta-feira ) - São João ( Feriado municipal )\n 16/07/2020 ( quinta-feira ) - Nossa Senhora do Carmo ( Feriado municipal )\n 08/12/2020 ( terça-feira ) - Nossa Senhora da Conceição ( Feriado municipal )\n\n\n## Feriados Caruaru\n\n 10/04/2020 ( sexta-feira ) - Sexta-feira da Paixão ( Feriado municipal )\n 18/05/2020 ( segunda-feira ) - Emancipação de Caruaru ( Feriado municipal )\n 29/06/2020 ( segunda-feira ) - São Pedro ( Feriado municipal )\n 15/09/2020 ( terça-feira ) - Nossa Senhora das Dores ( Feriado municipal )\n\n\n## Feriados Cabo\n\n 13/06/2020 ( sábado ) - Santo Antônio ( Feriado municipal )\n 09/07/2020 ( quinta-feira ) - Emancipação de Cabo de Santo Agostinho ( Feriado municipal )\n 31/10/2020 ( sábado ) - Reforma Protestante e Ação de Graças ( Feriado municipal )\n\n\n## Feriados Jaboatao\n\n\n 10/04/2020 ( sexta-feira ) - Sexta-feira Santa ( Feriado municipal )\n 04/05/2020 ( segunda-feira ) - Aniversário do Jaboatão dos Guararapes ( Feriado municipal )\n 24/06/2020 ( quarta-feira ) - São João\n\n\n# Feriados Petrolina \n\n\n 15/08/2020 ( sábado ) - Nossa Senhora Rainha dos Anjos ( Feriado municipal )\n 21/09/2020 ( segunda-feira ) - Emancipação de Petrolina ( Feriado municipal )\n\n\n" } ]
10
threepipes/contest-notifier
https://github.com/threepipes/contest-notifier
6a81b79e37d320c3aa91ec71a66cd7c5ab8c95f8
8e34121be4aebd2d97b816f0358a00e81d997899
050712aeff6a5222312d495178f1fae5049f17c1
refs/heads/master
2020-06-26T17:10:48.780386
2019-07-30T17:20:10
2019-07-30T17:20:10
199,695,984
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7101648449897766, "alphanum_fraction": 0.7129120826721191, "avg_line_length": 21.75, "blob_id": "d77d17bebd0ea1dde969de3c4ef4e34db8f393d4", "content_id": "3460fe00ebd722e5586c70fe26a82e7143a6a626", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 728, "license_type": "no_license", "max_line_length": 65, "num_lines": 32, "path": "/notifier.py", "repo_name": "threepipes/contest-notifier", "src_encoding": "UTF-8", "text": "from pyquery import PyQuery as pq\nimport requests as req\nimport time\nimport json\nimport os\nimport argparse\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"id\", help=\"contest id\")\nargs = parser.parse_args()\n\n\ncontst_number = args.id\nurl = f'https://codeforces.com/contest/{contst_number}/standings'\nwebhook_url = os.getenv('SLACK_WEBHOOK', '')\n\n\ndef check_testing_status():\n status = pq(url)('span.contest-status')\n status_text = pq(status).text().strip()\n print(status_text)\n return status_text == 'Final standings'\n\n\nwhile not check_testing_status():\n time.sleep(60)\n\nresponse = req.post(webhook_url, json.dumps({\n 'text': f'Finish contest {contest_number} system testing.'\n}))\nprint(response.text)\n" }, { "alpha_fraction": 0.6535947918891907, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 9.928571701049805, "blob_id": "d5e77b940cbb569200f4e94745ef7ce815c564b5", "content_id": "38eb33e1041617898706d3bb0d28750aa3c9f445", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 167, "license_type": "no_license", "max_line_length": 43, "num_lines": 14, "path": "/README.md", "repo_name": "threepipes/contest-notifier", "src_encoding": "UTF-8", "text": "# 環境構築\n\n- python3.7\n\n```\npip install -r requirements.txt\nexport SLACK_WEBHOOK=<incoming_webhook_url>\n```\n\n# 使い方\n\n```\npython notifier.py <contest_id>\n```\n" } ]
2
knackofabhinav/number-guessing-game
https://github.com/knackofabhinav/number-guessing-game
5b52d5131078563b70bce3f4e93debb1d4dba4be
aed3f38ddc6a9272523149403cf9cebca175a436
b6921b6862b5007c21176f64937e13e34daf4bc2
refs/heads/main
2023-01-13T03:49:10.059173
2020-11-21T10:36:29
2020-11-21T10:36:29
314,787,303
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5555555820465088, "alphanum_fraction": 0.5714285969734192, "avg_line_length": 18.384614944458008, "blob_id": "3fa61b298278fb1c093eecb47560f73762b9a126", "content_id": "55f9b34991c3e9d00de86d2e77ef64772e5bcaea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 252, "license_type": "no_license", "max_line_length": 37, "num_lines": 13, "path": "/test.py", "repo_name": "knackofabhinav/number-guessing-game", "src_encoding": "UTF-8", "text": "import unittest\nimport main\n\nclass TestGame(unittest.TestCase):\n def test_input(self):\n guess = 5\n answer = 5\n result = main.run_guess(5, 5)\n self.assertTrue(result)\n \n\nif __name__ == '__main__':\n unittest.main()\n" } ]
1
vmfilatova/Influx
https://github.com/vmfilatova/Influx
5431044ce17dc232a27639b06ae82e9db474b4e3
14bcd1af7ebd73906d67f32f48f10457e8504326
a27f2a9c30a5c9e4fe090313ea9832e528367069
refs/heads/main
2023-08-12T02:51:20.422789
2021-10-13T15:11:51
2021-10-13T15:11:51
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5849652290344238, "alphanum_fraction": 0.5855969786643982, "avg_line_length": 27.799999237060547, "blob_id": "de5882efdb26a3db604f0e4a2c51fc3eb7412910", "content_id": "b6a759c6ef8c2f255d900db2c3e7943f87f25d3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1614, "license_type": "no_license", "max_line_length": 93, "num_lines": 55, "path": "/writeinflux.py", "repo_name": "vmfilatova/Influx", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport json\nimport os\n\nfrom influxdb import InfluxDBClient\n\n\nclass WriteInflux:\n\n def __init__(self, data):\n \"\"\"Constructor\"\"\"\n self.data = data\n ROOT_DIR = os.path.dirname(os.path.abspath(__file__))\n\n with open(ROOT_DIR+'/config.json') as f:\n data_config = json.load(f)\n\n config_influx = data_config.get('influx')\n self.config_influx = config_influx\n self.database = config_influx['database']\n if self.connect_influx():\n client = self.connect_influx()\n self.check_db(client)\n self.export_to_influxdb(client)\n\n def connect_influx(self):\n host = self.config_influx['host']\n port = self.config_influx['port']\n username = self.config_influx['username']\n password = self.config_influx['password']\n\n client = InfluxDBClient(host=host, port=port, username=username, password=password)\n try:\n client.ping()\n except Exception as e:\n print(e)\n return False\n return client\n\n def check_db(self, client):\n database_name = self.database\n if not ({'name': database_name} in client.get_list_database()):\n client.create_database(database_name)\n client.switch_database(database_name)\n\n def export_to_influxdb(self, client):\n \"\"\"\n Запись в базу данных временных рядов\n :param polling_time_value:\n :return:\n \"\"\"\n json_body = self.data\n print(json_body)\n client.write_points(json_body)" }, { "alpha_fraction": 0.49408283829689026, "alphanum_fraction": 0.5325443744659424, "avg_line_length": 14.095237731933594, "blob_id": "1e75bcb01cac292c389b3cd980c7635d96f0a5cb", "content_id": "3e01f1572549ed00e2bb23e91fc7f6ae57289965", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 338, "license_type": "no_license", "max_line_length": 45, "num_lines": 21, "path": "/getinfluxtime.py", "repo_name": "vmfilatova/Influx", "src_encoding": "UTF-8", "text": "import time\r\n\r\nfrom writeinflux import WriteInflux\r\n\r\n\r\ndef get_influx_time(t):\r\n return int(t * 1000000000)\r\n\r\n\r\nmeasurement = \"cluster\"\r\ndata = [\r\n {\r\n \"measurement\": measurement,\r\n \"time\": get_influx_time(time.time()),\r\n \"fields\": {\r\n \"pressure\": \"0.64\"\r\n }\r\n }\r\n]\r\n\r\nWriteInflux(data)\r\n" } ]
2
OniiChanKawaii/color_shahmat_cell
https://github.com/OniiChanKawaii/color_shahmat_cell
4f6dde7f856335f02bb25425534ca11c3bb9ac7f
005b275c2f08dfaaadb62a69893b26be0ce38594
aa4d20c64587e83a6f79c77eb61425a2f82f3a30
refs/heads/master
2022-12-24T07:09:48.882190
2020-09-12T17:49:35
2020-09-12T17:49:35
294,996,023
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5846724510192871, "alphanum_fraction": 0.6001235842704773, "avg_line_length": 40.487178802490234, "blob_id": "022907870f571a903cae4eab50c6986e67c9e7c1", "content_id": "aae982f36ef6e8b61ab23003c69781dc82b9c3c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2221, "license_type": "no_license", "max_line_length": 101, "num_lines": 39, "path": "/cell_color.py", "repo_name": "OniiChanKawaii/color_shahmat_cell", "src_encoding": "UTF-8", "text": "from random import randint # импортировал рандом, чтоб чтоб приводить примеры ввода\n\n\n#генераторы списка шахматных координат\nvertical = [chr(ord(\"1\") + i) for i in range(8)]\ngorizontal = [chr(ord(\"A\") + i) for i in range(8)]\n#------------------------------------#\n\n#-----------бесконечный цикл который будет запрашивать входные данные от пользователя----------#\nwhile True:\n coordin=list(input('введите координаты шахматной доски: '\n '\\n Пример: '+str( vertical[randint(0,7)]) + str(gorizontal[randint(0,7)])))\n\n coordin[1] = coordin[1].upper() # буква всегда будет приведена в верхнем регистре\n\n\n#-----------каждую координату x,y делят по модулю, чтоб узнать, имеется ли остаток-------------#\n\n if coordin[0] in vertical and coordin[1] in gorizontal:\n \n if int((coordin[0])) % 2 == 0 and int(gorizontal.index(coordin[1]) + 1) % 2 == 0:\n print(\"Black\")\n\n elif int((coordin[0])) % 2 == 1 and int(gorizontal.index(coordin[1]) + 1) % 2 == 1:\n print(\"координаты:\", coordin, \"цвет координат: ~Black~ \", )\n\n else:\n print(\"координаты:\", coordin, \"цвет координат: ~White~ \")\n#----------------------------------------------------------------------------------------------#\n else:\n print(\"Введите сначала цифру координат, затем букву\")\n\n\n# пользователь вводит координаты шахматной клетки которой хочет узнать её цвет.\n\n# из входных данных получается цвет клетки.\n\n# если число и буква координаты вместе чётные или не чётные тогда получается координата чёрного цвета\n# в ином случае координата введёному пользователя белого цвета.\n" } ]
1
alexandermfisher/cs50_artificial_intelligence
https://github.com/alexandermfisher/cs50_artificial_intelligence
cc01849270ffac396ff2e567dd56935bc3068c95
5e8bc855d91313d11296096335087b42726936d8
bf9952fc2749fb2d02ff0b807c550e1ba39cc4c7
refs/heads/master
2023-03-17T07:28:11.662309
2021-03-18T15:32:58
2021-03-18T15:32:58
331,311,458
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7886179089546204, "alphanum_fraction": 0.8048780560493469, "avg_line_length": 29.625, "blob_id": "7e167c1816047458789f15c69d11a3a7bdf2b7f9", "content_id": "894a35cb1077e7047a052406f770e430391cdc1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 246, "license_type": "no_license", "max_line_length": 135, "num_lines": 8, "path": "/README.md", "repo_name": "alexandermfisher/cs50_artificial_intelligence", "src_encoding": "UTF-8", "text": "# cs50_artificial_intelligence\n\nThis is a repository containing all of the worked solutions I have completed for Harvards CS50 Introduction to Artificial Intelligence.\n\nFill in this later\n\n- Search: Includes tic-tac-toe, and degrees\n- Knowledge \n" }, { "alpha_fraction": 0.6380106210708618, "alphanum_fraction": 0.641086995601654, "avg_line_length": 34.246986389160156, "blob_id": "1af06d93a942ad736aa9cef8e029d8f0d0a6ac5d", "content_id": "ae3dc7de65b1ac48bdfe9cbb4eacff69ab433ab3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5851, "license_type": "no_license", "max_line_length": 130, "num_lines": 166, "path": "/06 - Language/questions/questions.py", "repo_name": "alexandermfisher/cs50_artificial_intelligence", "src_encoding": "UTF-8", "text": "import nltk\nimport sys\nfrom nltk.tokenize import word_tokenize\nimport os\nimport string\nimport math\n\nFILE_MATCHES = 1\nSENTENCE_MATCHES = 1\n\n\n\ndef main():\n\n # Check command-line arguments\n if len(sys.argv) != 2:\n sys.exit(\"Usage: python questions.py corpus\")\n\n # Calculate IDF values across files\n files = load_files(sys.argv[1])\n file_words = {\n filename: tokenize(files[filename])\n for filename in files\n }\n file_idfs = compute_idfs(file_words)\n \n\n # Prompt user for query\n query = set(tokenize(input(\"Query: \")))\n\n # Determine top file matches according to TF-IDF\n filenames = top_files(query, file_words, file_idfs, n=FILE_MATCHES)\n\n # Extract sentences from top files\n sentences = dict()\n for filename in filenames:\n for passage in files[filename].split(\"\\n\"):\n for sentence in nltk.sent_tokenize(passage):\n tokens = tokenize(sentence)\n if tokens:\n sentences[sentence] = tokens\n\n # Compute IDF values across sentences\n idfs = compute_idfs(sentences)\n\n # Determine top sentence matches\n matches = top_sentences(query, sentences, idfs, n=SENTENCE_MATCHES)\n for match in matches:\n print(match)\n\n\ndef load_files(directory):\n \"\"\"\n Given a directory name, return a dictionary mapping the filename of each\n `.txt` file inside that directory to the file's contents as a string.\n \"\"\"\n # initialise dictionay to be returned\n files_dictionary = dict()\n \n # read in file names into a list:\n file_names = [file_name for file_name in os.listdir(directory) if file_name.endswith('.txt')]\n \n # read file_name and file contents into dictinoary:\n for file_name in file_names:\n with open(os.path.join(directory, file_name), 'r', encoding='UTF-8') as file:\n files_dictionary[file_name] = file.read()\n \n return files_dictionary\n\n\ndef tokenize(document):\n \"\"\"\n Given a document (represented as a string), return a list of all of the\n words in that document, in order.\n\n Process document by coverting all words to lowercase, and removing any\n punctuation or English stopwords.\n \"\"\"\n # tokenize document and remove stops words and punctuation.\n document_tokens = word_tokenize(document.lower())\n \n formatted_tokens = list()\n for token in document_tokens:\n # check to see word isn't a stop word\n if token not in nltk.corpus.stopwords.words(\"english\"):\n # removing any char in token that is punctuation\n formatted_token = token\n for char in token:\n if char in string.punctuation:\n formatted_token = formatted_token.replace(char, \"\")\n \n # if formatted_token is not empty string append to formatted_tokens\n if formatted_token != (\"\" or \"/n\"): \n formatted_tokens.append(formatted_token)\n\n \n return formatted_tokens\n\n\ndef compute_idfs(documents):\n \"\"\"\n Given a dictionary of `documents` that maps names of documents to a list\n of words, return a dictionary that maps words to their IDF values.\n\n Any word that appears in at least one of the documents should be in the\n resulting dictionary.\n \"\"\"\n num_docs = len(documents)\n idf_values_dict = dict()\n seen_words = set()\n\n # read in all words looping over each document\n # and store count in a dict.\n for document in documents:\n for word in documents[document]:\n # add unseen words to dict for counting and add 1 to count.\n if word not in seen_words:\n seen_words.add(word)\n idf_values_dict[word] = 1\n else:\n idf_values_dict[word] += 1\n # create dict that maps word to idf value for all seen words.\n return {word: math.log(num_docs)/count for word, count in idf_values_dict.items()}\n\n\ndef top_files(query, files, idfs, n):\n \"\"\"\n Given a `query` (a set of words), `files` (a dictionary mapping names of\n files to a list of their words), and `idfs` (a dictionary mapping words\n to their IDF values), return a list of the filenames of the the `n` top\n files that match the query, ranked according to tf-idf.\n \"\"\"\n # calculate the sum of tf-idf values (corresponding to each word in query) for each document.\n document_scores = dict()\n for file_name, file_words in files.items():\n document_scores[file_name] = 0\n for word in query:\n if word in file_words:\n document_scores[file_name] += idfs[word] * file_words.count(word)\n \n # rank the documents in descending order and return top n files from ranked list \n ranked_files = list(dict(sorted(document_scores.items(), key=lambda item: item[1], reverse=True)).keys())\n return ranked_files[:n]\n \n\ndef top_sentences(query, sentences, idfs, n):\n \"\"\"\n Given a `query` (a set of words), `sentences` (a dictionary mapping\n sentences to a list of their words), and `idfs` (a dictionary mapping words\n to their IDF values), return a list of the `n` top sentences that match\n the query, ranked according to idf. If there are ties, preference should\n be given to sentences that have a higher query term density.\n \"\"\"\n sentence_scores = dict()\n for sentence, sentences_words in sentences.items():\n sentence_scores[sentence] = [0,0]\n for word in query:\n if word in sentences_words:\n sentence_scores[sentence][0] += idfs[word]\n sentence_scores[sentence][1] += sentences_words.count(word) / len(sentences_words)\n\n ranked_sentences = list(dict(sorted(sentence_scores.items(), key=lambda item: (item[1][0], item[1][1]), reverse=True)).keys())\n return ranked_sentences[:n]\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.5237191915512085, "alphanum_fraction": 0.5394415855407715, "avg_line_length": 22.056249618530273, "blob_id": "b854bba4b3d4745c9943125b87252e9352b4ae4d", "content_id": "0d631f1490a1fe2224394f8cabcab65beaa154b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3689, "license_type": "no_license", "max_line_length": 82, "num_lines": 160, "path": "/00 - Search/tictactoe/tictactoe.py", "repo_name": "alexandermfisher/cs50_artificial_intelligence", "src_encoding": "UTF-8", "text": "\"\"\"\nTic Tac Toe Player\n\"\"\"\n\nimport math\nfrom copy import deepcopy\n\nX = \"X\"\nO = \"O\"\nEMPTY = None\n\n\ndef initial_state():\n \"\"\"\n Returns starting state of the board.\n \"\"\"\n return [[EMPTY, EMPTY, EMPTY],\n [EMPTY, EMPTY, EMPTY],\n [EMPTY, EMPTY, EMPTY]]\n\n\ndef player(board):\n \"\"\"\n Returns player who has the next turn on a board.\n \"\"\"\n\n ### Counts the amount of turns each player has taken.\n X_count = 0\n O_count = 0\n for i in board:\n for j in i:\n if j == \"X\":\n X_count += 1\n elif j == \"O\":\n O_count += 1\n\n if terminal(board):\n return None\n elif X_count == O_count:\n return \"X\"\n else:\n return \"O\"\n\n\ndef actions(board):\n \"\"\"\n Returns set of all possible actions (i, j) available on the board.\n \"\"\"\n possible_moves = set()\n for i in range(3):\n for j in range(3):\n if board[i][j] == EMPTY:\n possible_moves.add((i,j))\n\n return possible_moves\n\n\ndef result(board, action):\n \"\"\"\n Returns the board that results from making move (i, j) on the board.\n \"\"\"\n updated_board = deepcopy(board)\n try:\n if action not in actions(board):\n raise ValueError\n else:\n updated_board[action[0]][action[1]] = player(board)\n\n except ValueError:\n print(\"Invalid action. Only EMPTY spaces are valid places to make a move\")\n\n return updated_board\n\n\ndef winner(board):\n \"\"\"\n Returns the winner of the game, if there is one.\n \"\"\"\n\n ### check for horizontal wins\n for row in board:\n if all(col == row[0] for col in row): return row[0]\n ### check for vertical and diagonal wins\n if board[0][0] == board[1][0] == board[2][0]: return board[0][0]\n elif board[0][1] == board[1][1] == board[2][1]: return board[0][1]\n elif board[0][2] == board[1][2] == board[2][2]: return board[0][2]\n elif board[0][0] == board[1][1] == board[2][2]: return board[0][0]\n elif board[0][2] == board[1][1] == board[2][0]: return board[0][2]\n else: return None\n\n\ndef terminal(board):\n \"\"\"\n Returns True if game is over, False otherwise.\n \"\"\"\n ### check to see if there is a winner\n if winner(board) != None: return True\n\n ### check to see if board is full\n for i in board:\n for j in i:\n if j == EMPTY:\n return False\n\n return True\n\n\ndef utility(board):\n \"\"\"\n Returns 1 if X has won the game, -1 if O has won, 0 otherwise.\n \"\"\"\n who_won = winner(board)\n if who_won == \"X\": return 1\n elif who_won == \"O\": return -1\n else: return 0\n\n\ndef minimax(board):\n \"\"\"\n Returns the optimal action for the current player on the board.\n \"\"\"\n if board == initial_state():\n return (0,0)\n\n if player(board) == \"X\":\n v = -math.inf\n move = None\n for action in actions(board):\n min_val = min_value(result(board, action))\n if min_val > v:\n v = min_val\n move = action\n else:\n v = math.inf\n move = None\n for action in actions(board):\n max_val = max_value(result(board, action))\n if max_val < v:\n v = max_val\n move = action\n\n return move\n\n\ndef max_value(board):\n if terminal(board):\n return utility(board)\n v = -math.inf\n for action in actions(board):\n v = max(v,min_value(result(board,action)))\n return v\n\n\ndef min_value(board):\n if terminal(board):\n return utility(board)\n v = math.inf\n for action in actions(board):\n v = min(v,max_value(result(board,action)))\n return v\n" }, { "alpha_fraction": 0.6334139704704285, "alphanum_fraction": 0.6424828767776489, "avg_line_length": 33.69929885864258, "blob_id": "729b635fac9e7344f701c1fe32a1130aefd911c3", "content_id": "17802e9c2a7e9d702cfb72bb85b8c1d2e7ae0192", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4962, "license_type": "no_license", "max_line_length": 124, "num_lines": 143, "path": "/02 - Uncertainty/pagerank/pagerank.py", "repo_name": "alexandermfisher/cs50_artificial_intelligence", "src_encoding": "UTF-8", "text": "import os\nimport random\nimport re\nimport sys\n\nDAMPING = 0.85\nSAMPLES = 10000\n\n\ndef main():\n if len(sys.argv) != 2:\n sys.exit(\"Usage: python pagerank.py corpus\")\n corpus = crawl(sys.argv[1])\n ranks = sample_pagerank(corpus, DAMPING, SAMPLES)\n print(f\"PageRank Results from Sampling (n = {SAMPLES})\")\n for page in sorted(ranks):\n print(f\" {page}: {ranks[page]:.4f}\")\n ranks = iterate_pagerank(corpus, DAMPING)\n print(f\"PageRank Results from Iteration\")\n for page in sorted(ranks):\n print(f\" {page}: {ranks[page]:.4f}\")\n\n\ndef crawl(directory):\n \"\"\"\n Parse a directory of HTML pages and check for links to other pages.\n Return a dictionary where each key is a page, and values are\n a list of all other pages in the corpus that are linked to by the page.\n \"\"\"\n pages = dict()\n\n # Extract all links from HTML files\n for filename in os.listdir(directory):\n if not filename.endswith(\".html\"):\n continue\n with open(os.path.join(directory, filename)) as f:\n contents = f.read()\n links = re.findall(r\"<a\\s+(?:[^>]*?)href=\\\"([^\\\"]*)\\\"\", contents)\n pages[filename] = set(links) - {filename}\n\n # Only include links to other pages in the corpus\n for filename in pages:\n pages[filename] = set(link for link in pages[filename] if link in pages)\n\n return pages\n\n\ndef transition_model(corpus, page, damping_factor):\n \"\"\"\n Return a probability distribution over which page to visit next,\n given a current page.\n\n With probability `damping_factor`, choose a link at random\n linked to by `page`. With probability `1 - damping_factor`, choose\n a link at random chosen from all pages in the corpus.\n \"\"\"\n if corpus[page]:\n distribution_dict = dict(zip(corpus.keys(), [(1 - damping_factor) / len(corpus)] * len(corpus)))\n for link in corpus[page]:\n distribution_dict[link] += damping_factor / len(corpus[page])\n return distribution_dict\n else:\n distribution_dict = dict(zip(corpus.keys(), [1 / len(corpus)] * len(corpus)))\n return distribution_dict\n\n\ndef sample_pagerank(corpus, damping_factor, n):\n \"\"\"\n Return PageRank values for each page by sampling `n` pages\n according to transition model, starting with a page at random.\n\n Return a dictionary where keys are page names, and values are\n their estimated PageRank value (a value between 0 and 1). All\n PageRank values should sum to 1.\n \"\"\"\n\n # initialise page ranks dict. I.e. All keys start off on count of 0.\n page_ranks = dict(zip(corpus.keys(),[0]*len(corpus)))\n\n # initialise iterative process by selecting a random page to begin on and addding 1 to count for that page.\n # then complete remaining samples. \n current_page = random.choice(list(corpus.keys()))\n page_ranks[current_page] += 1 \n count = 1\n while count != n:\n distribution = transition_model(corpus,current_page,damping_factor)\n current_page = random.choices(list(distribution.keys()),list(distribution.values()))[0]\n page_ranks[current_page] += 1\n count += 1\n \n # normalise page_rank values by dividing by n.\n for key in page_ranks:\n page_ranks[key] /= n \n\n return page_ranks\n\n\ndef iterate_pagerank(corpus, damping_factor):\n \"\"\"\n Return PageRank values for each page by iteratively updating\n PageRank values until convergence.\n\n Return a dictionary where keys are page names, and values are\n their estimated PageRank value (a value between 0 and 1). All\n PageRank values should sum to 1.\n \"\"\"\n page_ranks = dict(zip(corpus.keys(), [1/len(corpus)] * len(corpus)))\n differences = dict(zip(corpus.keys(), [100] * len(corpus)))\n\n # if a page (in coprus) contains no links then add a link to every page in corpus. \n for page in corpus:\n if len(corpus[page]) == 0:\n corpus[page] = corpus.keys()\n\n # loop through updating page ranks according to formula until difference below 0.001 (error tolerance).\n error_tol = 0.0001\n keep_in_loop = True\n while keep_in_loop:\n for page in page_ranks:\n updated_page_rank = ((1-damping_factor)/len(corpus)) + (damping_factor * to_page_prob(page, corpus, page_ranks))\n differences[page] = abs(page_ranks[page] - updated_page_rank)\n page_ranks[page] = updated_page_rank\n\n if all(difference < error_tol for difference in differences.values()):\n keep_in_loop = False\n \n return page_ranks\n\ndef to_page_prob(page_p,corpus,page_ranks):\n \"\"\" Returns probability of getting to page_p from \n all other links. I.e. the second part of the PageRank Fomula.\n \"\"\"\n probability = 0\n for page_i in page_ranks:\n if page_p in corpus[page_i]:\n probability += page_ranks[page_i]/len(corpus[page_i])\n return probability\n \n\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.5631287693977356, "alphanum_fraction": 0.5682427883148193, "avg_line_length": 34.08235168457031, "blob_id": "e38fec0a8e17078c5e29d5c2bbd6e1db604a1af7", "content_id": "7f707dd34afc377bba651dc89e271f6919a708f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11932, "license_type": "no_license", "max_line_length": 145, "num_lines": 340, "path": "/01 - Knowledge/minesweeper/minesweeper.py", "repo_name": "alexandermfisher/cs50_artificial_intelligence", "src_encoding": "UTF-8", "text": "import itertools\nimport random\n\n\nclass Minesweeper():\n \"\"\"\n Minesweeper game representation\n \"\"\"\n\n def __init__(self, height=8, width=8, mines=8):\n\n # Set initial width, height, and number of mines\n self.height = height\n self.width = width\n self.mines = set()\n\n # Initialize an empty field with no mines\n self.board = []\n for i in range(self.height):\n row = []\n for j in range(self.width):\n row.append(False)\n self.board.append(row)\n\n # Add mines randomly\n while len(self.mines) != mines:\n i = random.randrange(height)\n j = random.randrange(width)\n if not self.board[i][j]:\n self.mines.add((i, j))\n self.board[i][j] = True\n\n # At first, player has found no mines\n self.mines_found = set()\n\n def print(self):\n \"\"\"\n Prints a text-based representation\n of where mines are located.\n \"\"\"\n for i in range(self.height):\n print(\"--\" * self.width + \"-\")\n for j in range(self.width):\n if self.board[i][j]:\n print(\"|X\", end=\"\")\n else:\n print(\"| \", end=\"\")\n print(\"|\")\n print(\"--\" * self.width + \"-\")\n\n def is_mine(self, cell):\n i, j = cell\n return self.board[i][j]\n\n def nearby_mines(self, cell):\n \"\"\"\n Returns the number of mines that are\n within one row and column of a given cell,\n not including the cell itself.\n \"\"\"\n\n # Keep count of nearby mines\n count = 0\n\n # Loop over all cells within one row and column\n for i in range(cell[0] - 1, cell[0] + 2):\n for j in range(cell[1] - 1, cell[1] + 2):\n\n # Ignore the cell itself\n if (i, j) == cell:\n continue\n\n # Update count if cell in bounds and is mine\n if 0 <= i < self.height and 0 <= j < self.width:\n if self.board[i][j]:\n count += 1\n\n return count\n\n def won(self):\n \"\"\"\n Checks if all mines have been flagged.\n \"\"\"\n return self.mines_found == self.mines\n\n\nclass Sentence():\n \"\"\"\n Logical statement about a Minesweeper game\n A sentence consists of a set of board cells,\n and a count of the number of those cells which are mines.\n \"\"\"\n\n def __init__(self, cells, count):\n self.cells = set(cells)\n self.count = count\n\n def __eq__(self, other):\n return self.cells == other.cells and self.count == other.count\n\n def __str__(self):\n return f\"{self.cells} = {self.count}\"\n\n def known_mines(self):\n \"\"\"\n Returns the set of all cells in self.cells known to be mines.\n \"\"\"\n ### Any time the number of cells is equal to the count, we know that all of that sentence’s cells must be mines.\n if len(self.cells) == self.count:\n return self.cells\n else:\n return set()\n\n def known_safes(self):\n \"\"\"\n Returns the set of all cells in self.cells known to be safe.\n \"\"\"\n ### Any time the count is equal to 0, we know that all of that sentence’s cells must be safe.\n if self.count == 0:\n return self.cells\n else:\n return set()\n\n def mark_mine(self, cell):\n \"\"\"\n Updates internal knowledge representation given the fact that\n a cell is known to be a mine.\n \"\"\"\n if cell in self.cells:\n self.cells.remove(cell)\n self.count -= 1\n\n def mark_safe(self, cell):\n \"\"\"\n Updates internal knowledge representation given the fact that\n a cell is known to be safe.\n \"\"\"\n if cell in self.cells:\n self.cells.remove(cell)\n\n def is_subset(self, other_sentence):\n ## tests to see if it is a subset of other sentence.\n ## returns true if yes it is or false if no it is not.\n if self.cells != other_sentence.cells and self.cells.issubset(other_sentence.cells):\n return True\n else:\n return False\n\n def infer_new_sentance(self, other_sentence):\n ### where self.cells is a subset of other_sentence.cells a new sentence is made\n different_cells = other_sentence.cells.difference(self.cells)\n different_count = other_sentence.count - self.count\n new_sentence = Sentence(different_cells, different_count)\n\n return new_sentence\n\n\nclass MinesweeperAI():\n \"\"\"\n Minesweeper game player\n \"\"\"\n\n def __init__(self, height=8, width=8):\n\n # Set initial height and width\n self.height = height\n self.width = width\n\n # Keep track of which cells have been clicked on\n self.moves_made = set()\n\n # Keep track of cells known to be safe or mines\n self.mines = set()\n self.safes = set()\n\n # List of sentences about the game known to be true\n self.knowledge = []\n\n def mark_mine(self, cell):\n \"\"\"\n Marks a cell as a mine, and updates all knowledge\n to mark that cell as a mine as well.\n \"\"\"\n self.mines.add(cell)\n for sentence in self.knowledge:\n sentence.mark_mine(cell)\n\n def mark_safe(self, cell):\n \"\"\"\n Marks a cell as safe, and updates all knowledge\n to mark that cell as safe as well.\n \"\"\"\n self.safes.add(cell)\n for sentence in self.knowledge:\n sentence.mark_safe(cell)\n\n def add_knowledge(self, cell, count):\n \"\"\"\n Called when the Minesweeper board tells us, for a given\n safe cell, how many neighboring cells have mines in them.\n\n This function should:\n 1) mark the cell as a move that has been made\n 2) mark the cell as safe\n 3) add a new sentence to the AI's knowledge base\n based on the value of `cell` and `count`\n 4) mark any additional cells as safe or as mines\n if it can be concluded based on the AI's knowledge base\n 5) add any new sentences to the AI's knowledge base\n if they can be inferred from existing knowledge\n \"\"\"\n ## form new sentance and add to knowledge base\n neibouring_cells = set()\n for i in range(max(0, cell[0]-1), min(cell[0] + 2, self.height)):\n for j in range(max(0, cell[1]-1), min(cell[1] + 2, self.width)):\n # Add the cell clicked on to moves made and safe set sets\n if (i, j) == cell:\n self.moves_made.add(cell)\n self.mark_safe(cell)\n else:\n neibouring_cells.add((i,j))\n\n new_sentence = Sentence(neibouring_cells, count)\n ## marks mines and safes for new sentance.\n for mine in self.mines:\n new_sentence.mark_mine(mine)\n for safe in self.safes:\n new_sentence.mark_safe(safe)\n\n ## add new sentence to knowledge base.\n self.knowledge.append(new_sentence)\n\n \"\"\"\n update knowledge base in any inferneces can be made.\n while any one of the three inference moves can generate new knowledge or ascribe a\n cell as a mine or safe this loop will continue (i.e. until no more inferences can be\n made and all new knowledge genereated by the new sentence/cell has been accounted for.)\n \"\"\"\n while self.inference_1() or self.inference_2() or self.inference_3():\n\n # find any subsetting possibilities and update knowledge base.\n for sentence_1 in self.knowledge.copy():\n for sentence_2 in self.knowledge.copy():\n if sentence_1.is_subset(sentence_2):\n new_sentence = sentence_1.infer_new_sentance(sentence_2)\n self.knowledge.append(new_sentence)\n self.knowledge.remove(sentence_2)\n\n # find any known mines or safes sentences and update mines and safes set\n for sentence in self.knowledge:\n for cell in sentence.known_safes().copy():\n self.mark_safe(cell)\n for cell in sentence.known_mines().copy():\n self.mark_mine(cell)\n\n # remove all empty sets in knowledge\n for sentence in self.knowledge:\n if sentence.cells == set():\n self.knowledge.remove(sentence)\n\n \"\"\"\n These three infernce functions loop over all sentences in knowledge and retrun\n a list of sentences that result from the relevant inferneces rules. If any of the\n three lists is not empty a infernece can be made and the subsequent knowledge can be added to knowledge bank.\n They are used in for the while loops condition to check if any inferneces can be made.\n I.e. While inferneces can be made they will be made and knowledge will be updated.\n \"\"\"\n\n def inference_1(self):\n \"\"\"\n Returns a list of new sentences, that can be formed by sub set infernece rule.\n That is to say if a sentence.cells is a subset of another sentance.cells, then the\n differnce will be found and the count will be calculated and a new sentance will\n be added to a list that will be returned.\n\n knowledge must be a list of Sentences()\n \"\"\"\n new_sentences = []\n for sentence_1 in self.knowledge:\n for sentence_2 in self.knowledge:\n if sentence_1.is_subset(sentence_2):\n new_sentence = sentence_1.infer_new_sentance(sentence_2)\n new_sentences.append(new_sentence)\n return new_sentences\n\n def inference_2(self):\n \"\"\"\n Returns a list of sentances where there are known safes. I.e where sentance.count = 0 and all cells are therefore safe.\n \"\"\"\n safe_sentences = []\n for sentence in self.knowledge:\n if sentence.known_safes() != set():\n safe_sentences.append(sentence)\n return safe_sentences\n\n def inference_3(self):\n \"\"\"\n Returns a list of sentences where there are known mines. I.e. where length of set is equal to count, and all cells are therefore a mine.\n \"\"\"\n mine_sentences = []\n for sentence in self.knowledge:\n if sentence.known_mines() != set():\n mine_sentences.append(sentence)\n return mine_sentences\n\n def make_safe_move(self):\n \"\"\"\n Returns a safe cell to choose on the Minesweeper board.\n The move must be known to be safe, and not already a move\n that has been made.\n\n This function may use the knowledge in self.mines, self.safes\n and self.moves_made, but should not modify any of those values.\n \"\"\"\n for move in self.safes:\n if move not in self.moves_made and move not in self.mines:\n return move\n return None\n\n def make_random_move(self):\n \"\"\"\n Returns a move to make on the Minesweeper board.\n Should choose randomly among cells that:\n 1) have not already been chosen, and\n 2) are not known to be mines\n \"\"\"\n possible_moves = []\n for i in range(0, self.height):\n for j in range(0, self.width):\n move = (i, j)\n if move not in self.moves_made and move not in self.mines:\n possible_moves.append(move)\n\n ### if available move, randomly pick one and return move, else return None as no move available.\n if possible_moves:\n random_index = random.randint(0,len(possible_moves)-1)\n random_move = possible_moves[random_index]\n return random_move\n else:\n return None\n" } ]
5
jecs580/ApiRest-Productos
https://github.com/jecs580/ApiRest-Productos
422689a8eb9066bea49fd31f951551b5673eeaaf
9db54128e6aa614bfce014b725cd44d05c0c8d6e
174703b4cf3072f93f6f7e28ae0f46536404ab50
refs/heads/master
2023-05-13T02:27:32.416649
2020-04-11T01:11:00
2020-04-11T01:11:00
253,339,309
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5079365372657776, "alphanum_fraction": 0.5767195820808411, "avg_line_length": 8.947368621826172, "blob_id": "81fa634dfddc840a30452b0416bde076c87412e8", "content_id": "8cf3dc88377025ecf2dbf21f8c20effabed2adda", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 189, "license_type": "no_license", "max_line_length": 28, "num_lines": 19, "path": "/product.py", "repo_name": "jecs580/ApiRest-Productos", "src_encoding": "UTF-8", "text": "\"\"\"Modelo para Productos.\"\"\"\n\nproducts = [\n{\n'name':'laptop',\n'price':8000,\n'cantidad':4\n},\n{\n'name':'mouse',\n'price':40,\n'cantidad':10\n},\n{\n'name':'monitor',\n'price':400,\n'cantidad':3\n}\n]\n" }, { "alpha_fraction": 0.6454545259475708, "alphanum_fraction": 0.7363636493682861, "avg_line_length": 12.875, "blob_id": "2cc18108b65e192da3cbc5db9d5c07d6ef5b0eaa", "content_id": "90ef702b57f252b45c1c974a149f6e94b177fba5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 110, "license_type": "no_license", "max_line_length": 25, "num_lines": 8, "path": "/requirements.txt", "repo_name": "jecs580/ApiRest-Productos", "src_encoding": "UTF-8", "text": "# Flask\nFlask==1.1.1\n\n# Flask SQLAlchemy\nFlask-SQLAlchemy==2.4.1\n\n# Flask MashMallow\nflask-marshmallow==0.11.0" }, { "alpha_fraction": 0.6735904812812805, "alphanum_fraction": 0.6771513223648071, "avg_line_length": 32.70000076293945, "blob_id": "47e5d5d6666b42439af3065279a384c257c2a3fa", "content_id": "4f85e64620ef883a2a5af96223cbf4f388126a6b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3370, "license_type": "no_license", "max_line_length": 164, "num_lines": 100, "path": "/app.py", "repo_name": "jecs580/ApiRest-Productos", "src_encoding": "UTF-8", "text": "\"\"\"Controller\"\"\"\n\n# Flask\nfrom flask import Flask, jsonify, request\n\n# Flask SQLAlchemy\nfrom flask_sqlalchemy import SQLAlchemy\n\n# Flask MarshMallow\nfrom flask_marshmallow import Marshmallow\n\napp = Flask(__name__) # Creamos una instancia de Flask.\napp.config['SQLALCHEMY_DATABASE_URI']= 'sqlite:///database/products.db'\ndb=SQLAlchemy(app)\nma = Marshmallow(app)\n\nclass Product(db.Model):\n \"\"\"Modelo de Clase para la tabla Product\"\"\"\n id=db.Column(db.Integer,primary_key=True)\n name=db.Column(db.String(20))\n price=db.Column(db.Integer)\n cantidad=db.Column(db.Integer)\n\n def __init__(self,name,price,cantidad):\n self.name=name\n self.price=price\n self.cantidad=cantidad\ndb.create_all()\nclass ProductSchema(ma.Schema):\n class Meta:\n fields =('id','name','price','cantidad')\n\nproductSchema=ProductSchema()\nproductsSchema=ProductSchema(many=True)\n\[email protected]('/ping')\ndef ping():\n \"\"\"Ruta de Prueba\"\"\"\n return jsonify({\n 'mensaje':'pong'\n }) # Serializamos la salida a Json\n\[email protected]('/products', methods=['GET'])\ndef getProducts():\n \"\"\"Listar Productos\"\"\"\n products = Product.query.all()\n result = productsSchema.dump(products)\n return jsonify(result)\n\[email protected]('/products/<string:product_name>')\ndef retrieveProduct(product_name):\n \"\"\"Recupera un Producto por su nombre\"\"\"\n product=Product.query.filter_by(name=product_name).first()\n \"\"\"Si queremos buscar un producto por su id podemos usar el metodo get\n que esta especificamente hecho para eso\n product=Product.query.get(id=product_id)\n \"\"\"\n if(product):\n result = productSchema.dump(product)\n return jsonify(result)\n return jsonify({'mensaje':'producto no encontrado'})\n\[email protected]('/products',methods=['POST'])\ndef createProduct():\n name = request.json['name']\n price = request.json.get('price',0) # Otra forma de obtener los datos. En caso que no contenga el dato colocamos el valor vacio o cualquiera valor por defecto.\n cantidad = int(request.json.get('cantidad',0))\n product = Product(name=name, price=price, cantidad=cantidad)\n db.session.add(product)\n db.session.commit()\n return productSchema.jsonify(product)\n\[email protected]('/products/<string:name>', methods=['PUT'])\ndef updateProduct(name):\n product=Product.query.filter_by(name=name).first()\n if(product):\n aux=productSchema.dump(product)\n product.name = request.json['name']\n product.price = request.json.get('price',aux['price'])\n product.cantidad = request.json.get('cantidad',aux['cantidad'])\n db.session.commit()\n result = productSchema.dump(product)\n return jsonify({\n 'mensaje':'Producto actualizado exitosamente',\n 'product':result\n })\n return jsonify({'mensaje':'producto no encontrado'})\n\[email protected]('/products/<string:name>', methods=['DELETE'])\ndef deleteProduct(name):\n product=Product.query.filter_by(name=name).first()\n if(product):\n result=productSchema.dump(product)\n Product.query.filter_by(name=name).delete()\n db.session.commit()\n return jsonify({'mensaje':'Producto eliminado exitosamente','product':result})\n return jsonify({'mensaje':'producto no encotrado'})\n \nif __name__ == \"__main__\":\n app.run(debug=True, port= 4000) # Por defecto se ejecuta en el puerto 5000\n" } ]
3
MUSTMIIZ11/chameleon
https://github.com/MUSTMIIZ11/chameleon
7837de0bd906c3cc48475f6ce7e182a5e19fea02
d6958fa09d9525f932995aad8e29a708f6cc5a8a
f106510bdd756b9047d69efe2202f1f474f9dd9a
refs/heads/main
2023-06-02T10:18:39.591680
2021-06-12T06:11:01
2021-06-12T06:11:01
356,900,624
0
2
null
null
null
null
null
[ { "alpha_fraction": 0.5805320143699646, "alphanum_fraction": 0.5822858810424805, "avg_line_length": 37.875, "blob_id": "022297053b0d5659d8e4a2f10ff73b348f8e2213", "content_id": "7d21cb882e830e9eaeaf3a0086c7adb97d67a5d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3437, "license_type": "no_license", "max_line_length": 112, "num_lines": 88, "path": "/signup/views.py", "repo_name": "MUSTMIIZ11/chameleon", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\n\n# Create your views here.\nfrom django.shortcuts import render\nfrom django.contrib import auth\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth.backends import ModelBackend\nfrom django.db.models import Q\nfrom .models import User\nfrom django.http import HttpResponseRedirect\nfrom django.contrib import redirects\n\n# def index(request):\n# return render(request, 'login.html')\n\nfrom django.views.generic.base import View\n\n\n# class CustomBackend(ModelBackend):\n# def authenticate(self, username=None, password=None, **kwargs):\n# print(\"<<< start authenticate >>>\")\n# try:\n# user = User.objects.get(Q(username=username) | Q(email=username))\n# if user.check_password(password):\n# return user\n# except Exception as e:\n# return None\n#\n# def user_login(self, request):\n# print(\"get in user login\")\n# if request.method == 'POST':\n# print(\"get user name and password\")\n# user_name = request.POST.get('username', \"\")\n# pass_word = request.POST.get('password', \"\")\n# print(user_name)\n# print(pass_word)\n# user = authenticate(username=user_name, password=pass_word)\n# if user is not None:\n# login(request, user)\n# return render(request, \"tool.html\")\n# else:\n# return render(request, 'login.html', {\"msg\": \"用户名或密码错误!\"})\n# elif request.method == 'GET':\n# return render(request, 'login.html', {})\n\n\ndef simple_login(request):\n if request.method == 'POST':\n user_name = request.POST.get('username', \"\")\n pass_word = request.POST.get('password', \"\")\n usr = User.objects.get(username=user_name)\n if usr.password == pass_word:\n # request.session['is_login'] = True\n # request.session['user_id'] = usr.id\n # request.session['user_name'] = usr.username\n # return render(request, 'index.html', {\"msg\": \"You have successfully login!\"})\n ret = HttpResponseRedirect('/welcome/')\n ret.set_cookie('is_login', True)\n ret.set_cookie('user_id', usr.id)\n ret.set_cookie('user_name', usr.username)\n return ret\n else:\n return render(request, 'login.html', {\"msg\": \"Invalid user or password!\"})\n return render(request, 'login.html')\n\n\ndef signup(request):\n if request.method == 'POST':\n user_name = request.POST.get('username', \"\")\n pass_word1 = request.POST.get('password1', \"\")\n pass_word2 = request.POST.get('password2', \"\")\n try:\n usr = User.objects.get(username=user_name)\n except Exception as e:\n usr = None\n\n if usr is not None:\n return render(request, 'register.html', {\"msg\": \"The user name already exist!\"})\n else:\n if pass_word1 == pass_word2:\n # create new users\n print(\"create new user\")\n new_user = User.objects.create(username=user_name, password=pass_word1)\n new_user.save()\n return render(request, 'index.html')\n else:\n return render(request, 'register.html', {\"msg\": \"Two password not the same, Please try again.\"})\n return render(request, 'register.html')\n" }, { "alpha_fraction": 0.8016529083251953, "alphanum_fraction": 0.8016529083251953, "avg_line_length": 23.399999618530273, "blob_id": "f646f604ed29273c59372dbad95f4705efcce645", "content_id": "8791f89daec655f7970612195a786fa413e3cbab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 121, "license_type": "no_license", "max_line_length": 32, "num_lines": 5, "path": "/signup/admin.py", "repo_name": "MUSTMIIZ11/chameleon", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom signup.models import User\n\n# Register your models here.\nadmin.site.register([User])" }, { "alpha_fraction": 0.7164429426193237, "alphanum_fraction": 0.7567114233970642, "avg_line_length": 44.846153259277344, "blob_id": "f64fef57762b41a129800d92c838eb8f10e7b324", "content_id": "f704a16ce4e83b36c83c6da7dafa480be3bd2208", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 596, "license_type": "no_license", "max_line_length": 131, "num_lines": 13, "path": "/Dockerfile", "repo_name": "MUSTMIIZ11/chameleon", "src_encoding": "UTF-8", "text": "# syntax=docker/dockerfile:1\nFROM python:3.7-alpine\nRUN pip config set global.index-url http://mirrors.aliyun.com/pypi/simple && pip config set install.trusted-host mirrors.aliyun.com\nRUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories && apk add --no-cache jpeg-dev zlib-dev\nRUN apk add --no-cache --virtual .build-deps build-base linux-headers \\\n && pip install Pillow\nWORKDIR \"/code\"\nCOPY requirements /code/\nRUN pip install -r requirements\nCOPY . /code/\nENV DJANGO_ENV=devlopment\nENV DJANGO_HOST=\"159.75.82.228:9090\"\nCMD python manage.py runserver 0.0.0.0:9090\n" }, { "alpha_fraction": 0.6386138796806335, "alphanum_fraction": 0.6386138796806335, "avg_line_length": 21.55555534362793, "blob_id": "b00b684a30806ef7433b37f3a4ec9da045a02cdf", "content_id": "bb333b29b1eb5d051f7d0330810ca19931cafd70", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 202, "license_type": "no_license", "max_line_length": 46, "num_lines": 9, "path": "/tools/urls.py", "repo_name": "MUSTMIIZ11/chameleon", "src_encoding": "UTF-8", "text": "from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('save', views.save_map, name='save'),\n path('check', views.check, name='check'),\n]" }, { "alpha_fraction": 0.8032786846160889, "alphanum_fraction": 0.8032786846160889, "avg_line_length": 23.600000381469727, "blob_id": "df82eb7b37ad8f7c9199d78186c05f35286bae76", "content_id": "55c4b36623a2f7676930299629c621428222a63e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 122, "license_type": "no_license", "max_line_length": 32, "num_lines": 5, "path": "/community/admin.py", "repo_name": "MUSTMIIZ11/chameleon", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom community.models import Map\n# Register your models here.\n\nadmin.site.register([Map])" }, { "alpha_fraction": 0.6896551847457886, "alphanum_fraction": 0.6896551847457886, "avg_line_length": 21.66666603088379, "blob_id": "993d05eba6571458e7340f6c97f97808bb12900c", "content_id": "8c752a658e3bc25e9ad5b606ba53ac4180bc2b39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 203, "license_type": "no_license", "max_line_length": 51, "num_lines": 9, "path": "/signup/urls.py", "repo_name": "MUSTMIIZ11/chameleon", "src_encoding": "UTF-8", "text": "from django.urls import path\n\n# from .views import CustomBackend\nfrom . import views\n\nurlpatterns = [\n path('', views.simple_login, name='login'),\n path('register/', views.signup, name='signup'),\n]" }, { "alpha_fraction": 0.6346828937530518, "alphanum_fraction": 0.6576176285743713, "avg_line_length": 26.384614944458008, "blob_id": "fd2fbda7efac369372d583608f32e9869678fa44", "content_id": "4f06308fea9f7988229724edb50a8453872af248", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4879, "license_type": "no_license", "max_line_length": 153, "num_lines": 156, "path": "/README.md", "repo_name": "MUSTMIIZ11/chameleon", "src_encoding": "UTF-8", "text": "# Chameleon: Course Project of MIIZ11 Software Engineering \n\n### Owner: Lulin Deng, Kan Ni, Zhiyao Xie \n![example workflow](https://github.com/MUSTMIIZ11/chameleon/actions/workflows/main.yml/badge.svg)\n[![codecov](https://codecov.io/gh/MUSTMIIZ11/chameleon/branch/main/graph/badge.svg?token=9X73F77MZF)](https://codecov.io/gh/MUSTMIIZ11/chameleon)\n***\nIt is a website of create your own character graph in books. Currently under active development...\n\n### !!! Notice to the developers !!! : \nPlease commit changes to your own branch, and pull request.\n\nDo not directly commit to the main branch.\n\nTODO LIST:\n\n### Welcome page \n\nButton\n\n- [x] Logo: 主页上的logo跳转主页(index.html)\n\n- [x] community: 主页community主页跳转到community.html\n\n- [x] tools: tools按钮跳转login.html\n\n- [ ] bookshelf: 跳转顺序:bookshelf.html->login.html->bookshelf.html\n\n- [x] get start: 跳转顺序:login.html —> community.html \n\n\n### Login page\n\nButton\n\n- [x] Sign in:数据库记录三条登陆信息\n\n- [x] Sign up:注册\n\n\n### Community page\n\nButton\n\n- [x] Logo: 跳转到index.html\n\n- [x] community: 跳转到community.html\n\n- [x] tools: 跳转顺序:login.html —> tools.thml\n\n- [ ] bookshelf: 跳转顺序login.html —> bookshelf.html \n\n\n### Tools page\n\n- [ ] upload botton: 点击upload,作品发布到社区\n\n- [x] save: 点击save,存到本地\n\n- [ ] share:点击share,生成二维码,扫码可以下载到手机(方便pre的时候show一下\n\n### Bookshelf page\n\n- [ ] 时间不够这个page就删了吧要不... wait for version 2.0\n\n### How to develop 进行本地开发\n```shell\n# 1.安装项目依赖\n# cd到chameleon项目下\npython -m pip install -r requirements\n# 运行服务\n# export DJANGO_ENV=devlopment 设置了环境变量,通过该环境变量,我们的配置使用了远程mysql数据库\nexport DJANGO_ENV=devlopment && python manage.py runserver 8080\n\n# export DJANGO_ENV=\"\" 将DJANGO_ENV置空,通过该环境变量,配置使用本地sqlite\nexport DJANGO_ENV=\"\" && python manage.py runserver 8080\n\n# 如果有新的app创建,并且要更新数据库,这时候需要执行下面的命令\npython manage.py migrate\n\n# 进行单元测试 Unit test command\nexport DJANGO_ENV=\"test\" && python ./manage.py test\nexport DJANGO_ENV=\"test\" && python ./manage.py test tools\n\n# Converage test command\nexport DJANGO_ENV=\"test\" && coverage run --source='.' manage.py test&& coverage xml\n# 本地查看coverage报告的命令\ncoverage report -m\n```\n\n### Useful commands \n```shell\npython manage.py startapp xxx # 创建一个app 名字叫\"xxx\"\n\n\n# 创建tools app,会在项目根目录下面创建tools目录\npython manage.py startapp tools\n\n# 如果有新的app创建,并且要更新数据库,这时候需要执行下面的命令\npython manage.py migrate\n\n管理员界面:http://127.0.0.1:8080/admin/ 账号admin 密码admin\n\nProject Online Address: http://159.75.82.228:9090/\nJENKINS: http://159.75.82.228:8080/job/chameleon/\n\n# docker commands\n# docker run --name mysql -v mysql-volume:/var/lib/mysql -e MYSQL_DATABASE=chameleon_db_dev -e MYSQL_ROOT_PASSWORD=chameleon -p 3306:3306 -d mysql\n# sudo docker run --name \"$RUN_NAME\" -v /home/ubuntu/img/img:/code/chameleon/static/map_img -p 9090:9090 -d\"$CONTAINER\"\n\n```\n\n\n### Database Design\n\n#### User\n\n| Attribute | Type | KEY | Whether can be NULL | Comments |\n| ---------- | ------------ | ---- | -------- | -------- |\n| id | int | PRIMARY KEY | No | Auto increase primary key |\n| username | char(128) | | No | user name |\n| password | varchar(255) | | No | password set by user |\n| createtime | datetime | | Yes | account create time |\n\n\n#### Map\n\n| Attribute | Type | KEY | Whether can be NULL | Comments |\n| ---------- | ------------ | ---- | -------- | -------- |\n| id |int | PRI | No | Auto increase key |\n| map_name | char(128) | | No | map name |\n| map_url | text | | No | map url |\n| user_id | int | | Yes | user id(indicate which user create this map) | \n| like | int | | No | The likes this map get |\n| createtime | datetime | | Yes | Creation time |\n\n### TroubleShooting\n```shell\n遇到数据库表冲突的问题解决方案:\nmysql -uroot -p -h 159.75.82.228\n#password: chameleon\nDELETE FROM django_migrations WHERE app = 'community'\nDROP table communicy;\npython manage.py makemigrations\npython manage.py migrate;\n```\n\n\n### Project Workflow\n\n\nNew Branch(Feature/BugFix/Main) -> Code Review(Pull Requests) -> Continuous Integration(Github Actions) -> Continuous Deployment(Github webook + Jenkins)\n\n![Workflow](materials/Workflow.png)\n\n### Load Test\nhttps://github.com/nikan1996/Webenchmark is similar to Apache Benchmark , use it to make a test\n\n" }, { "alpha_fraction": 0.6785714030265808, "alphanum_fraction": 0.6989796161651611, "avg_line_length": 23.5, "blob_id": "78ffb3f37d8a9cc0d7bf7c85028bd13f1aca0c24", "content_id": "228f1727f0567e22849d4741088a6739a032adc5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 410, "license_type": "no_license", "max_line_length": 120, "num_lines": 16, "path": "/deploy.sh", "repo_name": "MUSTMIIZ11/chameleon", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# 容器名称\nCONTAINER=\"chameleon\"\nIMAGE=\"$CONTAINER\":latest\n# 创建新镜像\ndocker build -t $IMAGE . && \\\n# delete running images\n\nRUN_NAME=\"$CONTAINER\"\"service\"\nif docker ps -a | grep -w $RUN_NAME\nthen\n docker rm -f $RUN_NAME\nfi\n# run new images\nsudo docker run --name \"$RUN_NAME\" -v /home/ubuntu/img/img:/code/chameleon/static/map_img -p 9090:9090 -d \"$CONTAINER\"\necho \"Run successfully\"\n" }, { "alpha_fraction": 0.499332457780838, "alphanum_fraction": 0.5064530372619629, "avg_line_length": 37.72413635253906, "blob_id": "b2e12cf989ae2cadb8e5149491888ab21b7295a2", "content_id": "f259359ea7b0e26b4ab82dff3f91d4bdbf739879", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 2247, "license_type": "no_license", "max_line_length": 125, "num_lines": 58, "path": "/templates/login.html", "repo_name": "MUSTMIIZ11/chameleon", "src_encoding": "UTF-8", "text": "\n{% extends \"base.html\" %}\n\n{% block title %}Login Page{% endblock %}\n\n{% block content %}\n<section id=\"services\" class=\"section-bg\">\n <div class=\"container\">\n\n <header class=\"section-header center-block\">\n <h3 class=\"section-title\">Welcome back!</h3>\n <p>Sign in your account to keep design</p>\n </header>\n\n {% if msg %}\n <div class=\"alert alert-warning\">{{ msg }}</div>\n {% endif %}\n\n <div class=\"row clearfix\">\n </div>\n <div class=\"row\">\n <div class=\"col-md-4 column\">\n </div>\n <div class=\"col-md-5 column center-block\">\n <form class=\"form-horizontal\" role=\"form\" method=\"POST\">\n <div class=\"form-group form-group-lg\">\n <label class=\"col-sm-2 control-label\" for=\"exampleInputEmail1\">User/Email</label>\n <div class=\"col-sm-10\">\n {% csrf_token %}\n{# <input type=\"email\" class=\"form-control\" placeholder=\"Email Address\" id=\"exampleInputEmail1\" />#}\n <input type=\"text\" name='username' class=\"form-control\" placeholder=\"User name\" id=\"username\" />\n </div>\n </div>\n <div class=\"form-group form-group-lg\">\n <label class=\"col-sm-2 control-label\" for=\"exampleInputPassword1\">Password</label>\n <div class=\"col-sm-10\">\n {% csrf_token %}\n <input type=\"password\" name='password' class=\"form-control\" placeholder=\"Password\" id=\"password\" />\n </div>\n </div>\n <div class=\"col-sm-10\">\n <div class=\"checkbox\">\n <button class=\"btn btn-large btn-info\" style=\"float:right\" type=\"submit\">Sign in</button>\n{# <button class=\"btn btn-large btn-link\" style=\"float:right\" type=\"button\">Forget password?</button>#}\n <button class=\"btn btn-large btn-info\" style=\"float:left\"><a href=\"/login/register/\">Sign Up</a></button>\n </div>\n </div>\n\n </form>\n </div>\n <div class=\"col-md-3 column\">\n </div>\n\n </div>\n\n\n </div>\n </section>\n{% endblock %}\n" }, { "alpha_fraction": 0.6703910827636719, "alphanum_fraction": 0.6871508359909058, "avg_line_length": 26.538461685180664, "blob_id": "2abc86206a2b30b6187197344be30591ddec3e31", "content_id": "dbb30351e4530533f5eb061e0eb2492330c73fb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 358, "license_type": "no_license", "max_line_length": 49, "num_lines": 13, "path": "/community/models.py", "repo_name": "MUSTMIIZ11/chameleon", "src_encoding": "UTF-8", "text": "from django.db import models\n\n\n# Create your models here.\nclass Map(models.Model):\n map_name = models.CharField(max_length=50)\n map_url = models.TextField(max_length=100)\n user_id = models.IntegerField()\n like = models.IntegerField(default=0)\n create_time = models.DateField(auto_now=True)\n\n def __str__(self):\n return self.map_name\n" }, { "alpha_fraction": 0.5641928315162659, "alphanum_fraction": 0.5704225301742554, "avg_line_length": 35.19607925415039, "blob_id": "d8eb0e0a9255f60e06b8a1b0f8c96eb97a19d751", "content_id": "1056c6a124778f4114dcd7431893c583b4dd6264", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3850, "license_type": "no_license", "max_line_length": 108, "num_lines": 102, "path": "/community/views.py", "repo_name": "MUSTMIIZ11/chameleon", "src_encoding": "UTF-8", "text": "import base64\nimport os\nimport sys\nfrom io import BytesIO\n\nimport qrcode\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\n\nfrom chameleon.settings import MAP_DIR, BASE_DIR\nfrom .models import Map\nfrom signup.models import User\nimport qrcode\nfrom chameleon import settings\n\n\ndef index(request):\n # sort the map data based on the 'like' attribute.\n # Select 9 map which have most likes.\n ordered_map = Map.objects.order_by('-like').all()\n # display_map_list = dict()\n # for i in range(9):\n # display_map_list['map' + str(i)] = ordered_map[i].map_url\n # # display_map_list['map' + str(i) + 'user'] = User.objects.get(id=ordered_map[i].user_id).username\n display_map_dict = dict()\n display_map_dict['map_user_all'] = list()\n map_class = [0, 1, 2]\n print(display_map_dict)\n for i, map in enumerate(ordered_map):\n temp = dict()\n\n if '.svg' in map.map_url:\n try:\n map_dir = os.path.join(BASE_DIR, 'static/')\n filename = os.path.join(map_dir, map.map_url)\n # # 为了兼容win系统\n # if sys.platform.startswith('win'):\n # filename=filename.replace('/','\\\\')\n # print(filename)\n with open(filename, 'rb') as f:\n map_data = f.read()\n map_data = base64.b64encode(map_data)\n temp['map_src'] = 'data:image/svg+xml;base64,' + map_data.decode()\n except:\n continue\n temp['map'] = ordered_map[i].map_url\n try:\n temp['map_user'] = User.objects.get(id=ordered_map[i].user_id).username\n except:\n temp['map_user'] = 'unknown'\n tmp = i % 3\n temp['map_count'] = map_class[tmp]\n display_map_dict['map_user_all'].append(temp)\n # print(display_map_dict)\n return render(request, 'community.html', display_map_dict)\n\n\nfrom django.utils.http import urlencode\n\n\ndef download(request):\n count = 0\n if request.method == \"GET\":\n img_url = request.GET.get('url')\n count += 1\n print(\"count:\", count)\n print('img_url:', img_url)\n data = {\"img_url\": img_url}\n if '.svg' in img_url:\n map_dir = os.path.join(BASE_DIR, 'static/')\n filename = os.path.join(map_dir, img_url)\n # # 为了兼容win系统\n # if sys.platform.startswith('win'):\n # filename=filename.replace('/','\\\\')\n # print(filename)\n with open(filename, 'rb') as f:\n map_data = f.read()\n map_data = base64.b64encode(map_data)\n map_src = 'data:image/svg+xml;base64,' + map_data.decode()\n data = {\"img_url\": img_url, 'map_src': map_src}\n\n return render(request, 'download.html',data)\n\n\n# def update_img_url(request):\n# if request.method == \"GET\":\n# img_url = request.GET.get('url')\n# print(\"img_url:\", img_url)\n# return HttpResponse(request, {\"img_url\": img_url})\n\ndef makeqrcode(request, data):\n url = \"http://\" + settings.URL + '/' + \"community/download?url=\" + data\n # url = os.path.join(settings.BASE_DIR, \"static/img/portfolio/card3.jpg\")\n img = qrcode.make(url) # 传入网址计算出二维码图片字节数据\n buf = BytesIO() # 创建一个BytesIO临时保存生成图片数据\n img.save(buf) # 将图片字节数据放到BytesIO临时保存\n image_stream = buf.getvalue() # 在BytesIO临时保存拿出数据\n # imagepath = os.path.join(settings.BASE_DIR, \"static/img/{}\".format(\"qrcode\")) # 图片路径\n # with open(imagepath, 'rb') as f:\n # image_data = f.read()\n response = HttpResponse(image_stream, content_type=\"image/jpg\") # 将二维码数据返回到页面\n return response\n" }, { "alpha_fraction": 0.6032681465148926, "alphanum_fraction": 0.6123760938644409, "avg_line_length": 32.936363220214844, "blob_id": "b8b3ba70631ae4ffe4f41cae9a836f834e1d6ecf", "content_id": "f5180c52ff85c926213b92e81c3a906dd45412a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3733, "license_type": "no_license", "max_line_length": 152, "num_lines": 110, "path": "/tools/tests.py", "repo_name": "MUSTMIIZ11/chameleon", "src_encoding": "UTF-8", "text": "import binascii\nimport unittest\nfrom unittest.mock import patch, mock_open\n\nfrom django.http import HttpResponse\nfrom django.test import Client\n# Create your tests here.\nfrom django.test import TestCase\n\nfrom community.models import Map\nfrom signup.models import User\n\n\nclass MapTestCase(TestCase):\n \"\"\"\n Test Map Case\n \"\"\"\n def setUp(self):\n self.user = User.objects.create(username='nick', password='123')\n\n # test map is created\n def test_map_create(self):\n Map.objects.create(map_name='map', map_url='', user_id=self.user.id)\n maps = Map.objects.filter(user_id=self.user.id)\n self.assertEqual(len(maps), 1)\n\n # test map __str__ function is called and equal to map name\n def test_map_str(self):\n map = Map.objects.create(map_name='map', map_url='', user_id=self.user.id)\n self.assertEqual(str(map), map.map_name)\n\n # test map model fields limit length\n def test_map_field_maxlength(self):\n map = Map.objects.create(map_name='map', map_url='', user_id=self.user.id)\n max_length = map._meta.get_field('map_name').max_length\n self.assertEqual(max_length, 50)\n max_length = map._meta.get_field('map_url').max_length\n self.assertEqual(max_length, 100)\n\n # skip this test because local environment we test with sqlite3, sqlite3 does not have the limitation of field length, but mysql have the limitation\n @unittest.skip(\"sqlite does not require the field length of char field\")\n def test_map_create_failed_with_exceeded_field(self):\n map_name = ['x' for i in range(100)]\n print(map_name)\n map = Map.objects.create(map_name=map_name, map_url='', user_id=self.user.id)\n self.assertEqual(map.map_name, map_name)\n # self.assertRaises()\n\n def tearDown(self) -> None:\n self.user.delete()\n\n\nclass ToolsViewsTestCase(TestCase):\n \"\"\"\n Test Tools\n \"\"\"\n def setUp(self) -> None:\n pass\n\n def tearDown(self) -> None:\n pass\n\n \"\"\"\n Test the tool/ router is correctly triggered.\n \"\"\"\n def test_index(self):\n c = Client()\n response = c.get('/tool/')\n self.assertEqual(response.status_code, 200)\n \"\"\"\n I mock the render and return a string instead, I only want to test the router is triggered correctly.\n \"\"\"\n @patch('tools.views.render')\n def test_mock_index(self, mock_render):\n c = Client()\n mock_render.return_value = HttpResponse('tools_html')\n response = c.get('/tool/')\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.content, b'tools_html')\n\n \"\"\"\n Mock the open function because I do not want to produce new files and modify files in test.\n \"\"\"\n @patch('builtins.open', new_callable=mock_open())\n def test_save_map(self, mock_open_):\n c = Client()\n response = c.post('/tool/save', {\n 'map_data': 'PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPCFET0NUWVBFIHN2ZyBQVUJMSUMgIi0vL1czQy8vRFREIFNWRyAxLjEvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkIj4KPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB2ZXJzaW9uPSIxLjEiIHdpZHRoPSIxMjFweCIgaGVpZ2h0PSI2MXB4IiB2aWV3Qm94PSItMC41IC0wLjUgMTIxIDYxIiBjb250ZW50PSImbHQ7bXhmaWxlIGV0YWc9JnF1b3Q7VGdBR2JKbGNJaGw3a1JuRGFxSDQmcXVvdDsgYWdlbnQ9JnF1b3Q7TW96aWxsYS81LjAgKE1hY2ludG9zaDsgSW50ZWwgTWFjIE9TIFggMTBfMTRfNikgQXBwbGVXZWJLaXQvNTM3LjM2IChLSFRNTCwgbGlrZSBHZWNrbykgQ2hyb21lLzgwLjAuMzk4Ny4xMDYgU2FmYXJpLzUzNy4zNiZxdW90OyBtb2RpZmllZD0mcXVvdDsyMDIwLTAyLTE5VDEyOjQ0OjI3LjY1OVomcXVvdDsgaG9zdD0mcXVvdDt0ZXN0LmRyYXcuaW8mcXVvdDsgdmVyc2lvbj0mcXVvdDtARFJBV0lPLVZFUlNJT05AJnF1b3Q7Jmd0OyZsdDtkaWFncmFtIGlkPSZxdW90O3JVdXh2bWFtZE5aMXpyTFhPbF82JnF1b3Q7IG5hbWU9JnF1b3Q7UGFnZS0xJnF1b3Q7Jmd0O2xaUExic0l3RUVXL0prc2t4Nll0V3dvcGZhaWxLcXFRMkpsNGNGdzVHZVFZU1ByMVRZaWRCeXphcmpJK21VZm1YaWRnczdSWUdMNVBYbEdBRGlnUlJjRG1BYVVocGF4NjFLUnN5VjFEcEZIQ3NRNnMxRGM0U0J3OUtBSDVJTkVpYXF2MlF4aGpsa0ZzQjR3Ymc2ZGgyZzcxY09xZVM3Z0NxNWpyYTdwV3dpWU5uZHlRamorQ2tvbWZIQkwzSnVVKzJZRTg0UUpQUGNTaWdNME1vbTJpdEppQnJ0WHp1cnlGNy9NeFpSK2piRU5pU2FmUlJxcFIwK3poUHlYdENnWXkrOWZXbnptWTVmYXJscFFTemJlVnIrZktsZVhHTmczOTBPeXdIZHVuWTFnc1g5YlBiSWU0THFlamJzUDJJM05iZWxVTkhqSUJkVDBKMkwzVVBNOWQzS3BVSDVvNVJ6QVdpZ3M3ZnRrbDdJMWZBS1pnVFZuVnVTN01lK0p1NWNRZFQ1M0RvVTlKZXU3ZU9zYmRwWkp0NTA2NEtuQWIrMk5QU284NjE4L3B2WitIUlQ4PSZsdDsvZGlhZ3JhbSZndDsmbHQ7L214ZmlsZSZndDsiIHN0eWxlPSJiYWNrZ3JvdW5kLWNvbG9yOiByZ2IoMjU1LCAyNTUsIDI1NSk7Ij48ZGVmcy8+PGc+PHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEyMCIgaGVpZ2h0PSI2MCIgZmlsbD0iI2ZmZmZmZiIgc3Ryb2tlPSIjMDAwMDAwIiBwb2ludGVyLWV2ZW50cz0iYWxsIi8+PGcgZmlsbD0iIzAwMDAwMCIgZm9udC1mYW1pbHk9IkhlbHZldGljYSIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZm9udC1zaXplPSIxMnB4Ij48dGV4dCB4PSI1OS41IiB5PSIzNC41Ij5TdGFydDwvdGV4dD48L2c+PC9nPjwvc3ZnPg==',\n 'map_name': 'test_map_name',\n 'user_id': '2'\n })\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.json()['status'], 'ok')\n self.assertEqual(response.json()['user_id'], 2)\n self.assertEqual(response.json()['map_url'], 'map_img/' + 'test_map_name' + '.svg'\n )\n\n \"\"\"\n If a request to \"/tool/save\" carries non-base64 data in it's body, raise corresponding error here.\n \"\"\"\n def test_save_map_with_non_base64_img_data(self):\n c = Client()\n with self.assertRaises(binascii.Error) as e:\n response = c.post('/tool/save', {\n 'map_data': 'P',\n 'map_name': 'test_map_name',\n 'user_id': '2'\n })\n" }, { "alpha_fraction": 0.45249998569488525, "alphanum_fraction": 0.5425000190734863, "avg_line_length": 25.733333587646484, "blob_id": "c649fbb158ace3bfd51a135084feb138df5c9644", "content_id": "e48310656fcc895cf16eaa615fc5bc6b2eae707c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 400, "license_type": "no_license", "max_line_length": 70, "num_lines": 15, "path": "/chameleon/settings_dev.py", "repo_name": "MUSTMIIZ11/chameleon", "src_encoding": "UTF-8", "text": "import os\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n# URL = \"159.75.82.228:9090\"\nURL = os.environ.get('DJANGO_HOST') or \"127.0.0.1:8080\"\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'chameleon_db_dev',\n 'USER': 'root',\n 'PASSWORD': 'chameleon',\n 'HOST': '159.75.82.228',\n 'PORT': '3306',\n }\n}" }, { "alpha_fraction": 0.5998959541320801, "alphanum_fraction": 0.6056191325187683, "avg_line_length": 28.121212005615234, "blob_id": "36510e870255174a79d32887980b8180b8427daa", "content_id": "25d947c242727516546b5c4981f890b0cded73f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1972, "license_type": "no_license", "max_line_length": 85, "num_lines": 66, "path": "/tools/views.py", "repo_name": "MUSTMIIZ11/chameleon", "src_encoding": "UTF-8", "text": "# Create your views here.\nfrom django.http import HttpResponse, JsonResponse\nfrom django.shortcuts import render\nimport base64\n\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom community.models import Map\nfrom chameleon.settings import BASE_DIR\nimport os\n\n\ndef index(request):\n return render(request, 'tool.html')\n\n\n@csrf_exempt\ndef check(request):\n user_id = request.POST['user_id']\n print(f\"the user id {user_id}\")\n # if user_id == -1:\n # return\n return JsonResponse({\n \"user_id\": user_id\n })\n # if user_id != -1:\n # print(\"testtttt\")\n # return render(request, 'login.html')\n # else:\n # print(\"toollllllll\")\n # # Not login\n # return render(request, 'tool.html')\n\n\n@csrf_exempt\ndef save_map(request):\n # Save map from diagrams.net\n # map格式 mapId-userId-mapName\n imgstring = request.POST['map_data']\n map_name = request.POST['map_name']\n user_id = request.POST['user_id']\n try:\n user_id = int(user_id)\n except:\n user_id = -1\n imgdata = base64.b64decode(imgstring)\n # filename = str(user_id) + '-' + map_name\n # filename 1. 创建数据库里map_url('map_img/xxx.jpg') 2. 图片存储路径,跟前面路径一样,存jpg。\n map_dir = os.path.join(BASE_DIR, 'static/')\n filename = 'map_img/' + map_name + '.svg'\n jpg = os.path.join(map_dir, 'map_img/' + map_name + '.jpg')\n map = Map.objects.create(map_name=map_name, user_id=user_id, map_url=filename)\n # map_dir = os.path.join(BASE_DIR, 'image_map')\n # if not os.path.exists(map_dir):\n # os.makedirs(map_dir)\n # with open(os.path.join(map_dir, str(map.id)+\"-\"+filename) + '.svg', 'wb') as f:\n with open(os.path.join(map_dir, filename), 'wb') as f:\n f.write(imgdata)\n\n return JsonResponse({\n 'status': 'ok',\n 'map_id': map.id,\n 'map_name': map.map_name,\n 'map_url': map.map_url,\n 'user_id': map.user_id\n })\n" }, { "alpha_fraction": 0.7004716992378235, "alphanum_fraction": 0.7004716992378235, "avg_line_length": 25.5625, "blob_id": "8ca0ae9e26a58cbd2d19f40e4c5ac0591f1a6df6", "content_id": "eb667ad8e19ab4d371cd6235c54b1be9c43db507", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 424, "license_type": "no_license", "max_line_length": 71, "num_lines": 16, "path": "/welcome/views.py", "repo_name": "MUSTMIIZ11/chameleon", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\n\n# Create your views here.\nfrom django.http import HttpResponse\n\n# def index(request):\n# return HttpResponse(\"Hello world, you are at poll index\")\n\n# def index(request):\n# context = dict()\n# context['hello'] = 'Hello World! You are now in the welcome app!'\n# return render(request, 'navigation.html', context)\n\n\ndef index(request):\n return render(request, 'index.html')" } ]
15
logambigaik/flaskpostgres
https://github.com/logambigaik/flaskpostgres
1da78e4280a1e6717aa4555860a78ffa2cf14009
2c1453a1ffb38c27966c297a209377420952424a
94027bf94f27457d8c7e4be76bcaa74835bbf653
refs/heads/main
2023-02-06T15:08:07.649369
2020-12-24T20:26:31
2020-12-24T20:26:31
324,230,835
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.6631664037704468, "alphanum_fraction": 0.6696284413337708, "avg_line_length": 28.83132553100586, "blob_id": "496e2fef0cafa8458710da7978f4840f50c2702e", "content_id": "933736fb61f89a2d4539b8067de44b7ae66d7ff8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2476, "license_type": "no_license", "max_line_length": 125, "num_lines": 83, "path": "/application.py", "repo_name": "logambigaik/flaskpostgres", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template,request\nfrom flask import jsonify\nfrom models import *\n\napp=Flask(__name__)\napp.config[\"SQLALCHEMY_DATABASE_URI\"]=\"postgresql+psycopg2://postgres:19821983@localhost:5432/postgres\"\napp.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"]=False\ndb.init_app(app)\n\n\n'''@app.route(\"/home\")\n\ndef index():\n flights=Airlines.query.all()\n return render_template(\"index.html\",flights=flights)\n\n'''\[email protected](\"/book\",methods=[\"POST\"])\ndef book():\n \"\"\" Book a Flight \"\"\"\n #Get form information\n\n name=request.form.get(\"name\")\n\n try:\n flight_id = int(request.form.get(\"flight_id\"))\n except Error:\n return render_template(\"error.html\",message='Invalid Flight number')\n\n #Make sure the flight exists\n flight=Airlines.query.get(flight_id)\n if flight is None:\n return render_template(\"error.html\",message='No such flight exists')\n\n #Add passenger.\n passenger=Customers(name=name,flight_id=flight_id)\n db.session.add(passenger)\n db.session.commit()\n return render_template(\"success.html\")\n\[email protected](\"/\")\ndef flights():\n \"\"\" List all the flights \"\"\"\n flights=Airlines.query.all()\n return render_template(\"flights.html\",flights=flights)\n\[email protected](\"/flights/<int:flight_id>\")\n\ndef flight(flight_id):\n \"\"\" List details about a single flight \"\"\"\n\n #Make sure flight exists\n flight=Airlines.query.get(flight_id)\n\n if flight is None:\n return render_template(\"error.html\",message=\"No such flight exist\")\n\n #Get all passenger\n passengers=flight.passenger #Not required sql for selecting the passenger from tableinstead refering the class relation\n return render_template(\"flight.html\",flight=flight,passengers=passengers)\n\[email protected](\"/api/flights/<int:flight_id>\")\n\ndef flight_api(flight_id):\n \"\"\" List details about a single flight \"\"\"\n\n #Make sure flight exists\n flight=Airlines.query.get(flight_id)\n\n if flight is None:\n return jsonify({\"error\":\"Invalid flight_id\"}),422\n\n #Get all passenger\n passengers=flight.passenger #Not required sql for selecting the passenger from tableinstead refering the class relation\n names=[]\n for passenger in passengers:\n names.append(passenger.name)\n return jsonify({\n \"origin\" : flight.origin,\n \"destination\" : flight.destination,\n \"duration\" : flight.duration,\n \"passengers\" : names\n })\n" }, { "alpha_fraction": 0.7124682068824768, "alphanum_fraction": 0.7124682068824768, "avg_line_length": 31.75, "blob_id": "fba5fc12a392a52bb31cb02009ccc2226e373a55", "content_id": "a1a4793d926dab4e7dca3cab3ecb4e84ba31a1fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 786, "license_type": "no_license", "max_line_length": 88, "num_lines": 24, "path": "/models.py", "repo_name": "logambigaik/flaskpostgres", "src_encoding": "UTF-8", "text": "import os\nfrom flask import Flask\nfrom flask_sqlalchemy import *\n\ndb=SQLAlchemy()\n\nclass Airlines(db.Model):\n __tablename__=\"airline\"\n id=db.Column(db.Integer,primary_key=True)\n origin=db.Column(db.String,nullable=False)\n destination=db.Column(db.String,nullable=False)\n duration=db.Column(db.Integer,nullable=False)\n passenger=db.relationship(\"Customers\",backref=\"airlines\",lazy=True) #Class relation\n\n def add_customer(self,name):\n p=Customers(name=name,flight_id=self.id)\n db.session.add(p)\n db.session.commit()\n\nclass Customers(db.Model):\n __tablename__=\"customer\"\n id=db.Column(db.Integer,primary_key=True)\n name=db.Column(db.String,nullable=False)\n flight_id =db.Column(db.Integer,db.ForeignKey(\"airline.id\"),nullable=False)\n" } ]
2
pfaion/pybeautymaps
https://github.com/pfaion/pybeautymaps
fb0c19419b625489801c140a58275755247a11b0
295d7db5a0df7cd1b0fc817fdd7fecc38644071a
10573a7fe8e0138c37c49a6ff51583728a27c06d
refs/heads/master
2020-05-02T11:31:48.787424
2019-08-25T06:11:45
2019-08-25T06:11:45
177,931,540
2
1
MIT
2019-03-27T06:25:28
2019-08-18T13:04:01
2019-08-18T13:54:30
Python
[ { "alpha_fraction": 0.6334841847419739, "alphanum_fraction": 0.686274528503418, "avg_line_length": 32.150001525878906, "blob_id": "d38cf984c07da0bd790f6f4a93c022f2ce7eb388", "content_id": "f81d61abf36874b1f8295314463ff1a05facfd2d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 663, "license_type": "permissive", "max_line_length": 55, "num_lines": 20, "path": "/tests/test_utils.py", "repo_name": "pfaion/pybeautymaps", "src_encoding": "UTF-8", "text": "import pytest\n\nfrom pybeautymaps import utils\n\nVALID_LATLON = (37.030347, -93.473126)\nVALID_SIZE = 1.2\n\ndef test_bbox_from_centered_raise_negative_size():\n with pytest.raises(ValueError):\n utils.bbox_from_centered(VALID_LATLON, -1)\n \ndef test_bbox_from_centered_raise_wrong_latlon():\n with pytest.raises(ValueError):\n utils.bbox_from_centered((-100, 0), VALID_SIZE)\n with pytest.raises(ValueError):\n utils.bbox_from_centered((100, 0), VALID_SIZE)\n with pytest.raises(ValueError):\n utils.bbox_from_centered((0, -200), VALID_SIZE)\n with pytest.raises(ValueError):\n utils.bbox_from_centered((0, 200), VALID_SIZE)\n" }, { "alpha_fraction": 0.630946159362793, "alphanum_fraction": 0.6366962790489197, "avg_line_length": 30.883333206176758, "blob_id": "301b2b52ee9ec4444e1812dfb3b4d2cf0b98456f", "content_id": "f9a3ae4d6d97c8ef585cc7b39f9fd12296d9039c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1913, "license_type": "permissive", "max_line_length": 73, "num_lines": 60, "path": "/setup.py", "repo_name": "pfaion/pybeautymaps", "src_encoding": "UTF-8", "text": "from os import path\nfrom setuptools import setup, find_packages\n\nthis_directory = path.abspath(path.dirname(__file__))\nwith open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:\n long_description = f.read()\n\ninstall_requires = [\n 'numpy',\n 'overpy',\n 'pycairo',\n 'pyproj',\n]\n\nsetup_requires = [\n 'pytest-runner',\n]\n\ntests_require = [\n 'pytest',\n # coverage 5.* has SQLite output and is not compatible with coveralls\n # pytest-cov will automatically install coverage 5.* though!\n 'coverage==4.*',\n 'pytest-cov',\n]\n\nsetup(\n name=\"pybeautymaps\",\n version=\"0\",\n author=\"Patrick Faion\",\n description=\"Beautiful images of street maps made with python.\",\n long_description=long_description,\n long_description_content_type='text/markdown',\n keywords=\"art beautiful maps street-maps openstreetmaps\",\n urls=\"https://github.com/pfaion/pybeautymaps\",\n packages=find_packages(),\n install_requires=install_requires,\n setup_requires=setup_requires,\n tests_require=tests_require,\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Developers',\n 'Intended Audience :: Education',\n 'Intended Audience :: End Users/Desktop',\n 'Intended Audience :: Information Technology',\n 'Intended Audience :: Other Audience',\n 'Intended Audience :: Science/Research',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3 :: Only',\n 'Topic :: Artistic Software',\n 'Topic :: Multimedia :: Graphics',\n 'Topic :: Scientific/Engineering :: Visualization',\n ],\n)\n" }, { "alpha_fraction": 0.875, "alphanum_fraction": 0.875, "avg_line_length": 32, "blob_id": "c62798a5fc4fc520524b80627233fe00894a4e94", "content_id": "6128f2e469ea1bfa2f4c369cc5d91548adb2ea7d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 32, "license_type": "permissive", "max_line_length": 32, "num_lines": 1, "path": "/pybeautymaps/__init__.py", "repo_name": "pfaion/pybeautymaps", "src_encoding": "UTF-8", "text": "from .beautymap import Beautymap" }, { "alpha_fraction": 0.6090342402458191, "alphanum_fraction": 0.6487538814544678, "avg_line_length": 29.571428298950195, "blob_id": "fbdc2ac008f9d948422e5236ee6f7296f9e52340", "content_id": "ad98e7f6d7f693e17338fc6cd6c3c4a3fe2e8ee6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1284, "license_type": "permissive", "max_line_length": 79, "num_lines": 42, "path": "/pybeautymaps/utils.py", "repo_name": "pfaion/pybeautymaps", "src_encoding": "UTF-8", "text": "import math\n\nimport numpy as np\nfrom pyproj import Proj\n\n\ndef is_valid_latitude(lat):\n return -90 <= lat <= 90\n\n\ndef is_valid_longitude(lon):\n return -180 <= lon <= 180\n\n\ndef bbox_from_centered(center_latlon, width):\n if width <= 0:\n raise ValueError(f'Bounding box width must be positive! Is: {width}')\n\n lat, lon = center_latlon\n if not is_valid_latitude(lat):\n raise ValueError(f'Latitude needs to be in [-90, 90]! Is: {lat}')\n if not is_valid_longitude(lon):\n raise ValueError(f'Longitude needs to be in [-180, 180]! Is: {lon}')\n\n # quick and dirty conversion of cathographic to geodetic distances\n # see: https://gis.stackexchange.com/a/2964\n # TODO: use pyproj for this as well!\n delta_lat = width / 111.111\n delta_lon = abs(width / (111.111 * math.cos(lat)))\n bbox = (lat - delta_lat, lon - delta_lon, lat + delta_lat, lon + delta_lon)\n return bbox\n\n\ndef carthographic_from_geodetic(*latlons):\n # EPSG.3857 projection https://epsg.io/3857\n # Pseudo-Mercator as used by Google Maps and Open Street Maps\n proj = Proj(3857)\n return [\n # projector works with separate arrays of longs and lats (!)\n np.vstack(proj(coordinates[:, 1], coordinates[:, 0])).T\n for coordinates in latlons\n ]\n" }, { "alpha_fraction": 0.61654132604599, "alphanum_fraction": 0.61654132604599, "avg_line_length": 10.083333015441895, "blob_id": "c62df9fe74b41f50186a82c89631d4278e3db778", "content_id": "597148a0baf2a31e408f84a381a880818f388458", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 133, "license_type": "permissive", "max_line_length": 22, "num_lines": 12, "path": "/examples/tests/test_examples.py", "repo_name": "pfaion/pybeautymaps", "src_encoding": "UTF-8", "text": "from examples import (\n manhattan,\n paris,\n)\n\n\ndef test_manhattan():\n manhattan.main()\n\n\ndef test_paris():\n paris.main()\n" }, { "alpha_fraction": 0.48813268542289734, "alphanum_fraction": 0.5050042867660522, "avg_line_length": 29.408695220947266, "blob_id": "e54a2a3c07ab87f833c23e020c64cd32a5bba779", "content_id": "fd88fd2553f1eda6515a53131d63a80def78166f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3497, "license_type": "permissive", "max_line_length": 88, "num_lines": 115, "path": "/pybeautymaps/beautymap.py", "repo_name": "pfaion/pybeautymaps", "src_encoding": "UTF-8", "text": "import cairo\nimport numpy as np\nimport overpy\n\nfrom . import utils\n\n\nclass Beautymap:\n\n @classmethod\n def square_centered(cls, center_latlon, width):\n bbox = utils.bbox_from_centered(center_latlon, width)\n return cls(bbox)\n\n def __init__(self, bbox):\n self.bbox = bbox\n bbox_data = np.array(self.bbox).reshape((2, 2))\n self.carthographic_bbox = utils.carthographic_from_geodetic(bbox_data)[0]\n\n self.road_types = {\n 'motorway',\n 'trunk',\n 'primary',\n 'secondary',\n 'tertiary',\n 'residential',\n 'living_street',\n }\n\n self.raw_overpass_data = self.get_overpass_data()\n\n self.road_data = [\n way.tags.get('highway', '')\n for way in self.raw_overpass_data\n ]\n\n self.geodetic_data = [\n np.array([(node.lat, node.lon) for node in way.nodes], dtype=float)\n for way in self.raw_overpass_data\n ]\n\n self.carthographic_data = utils.carthographic_from_geodetic(*self.geodetic_data)\n\n def get_overpass_data(self):\n self.overpass_ql_query = f\"\"\"\n (\n way\n // filter road types with OR regex\n [\"highway\"~\"^{'|'.join(self.road_types)}$\"]\n {str(self.bbox)};\n >;\n );\n out;\n \"\"\"\n return overpy.Overpass().query(self.overpass_ql_query).ways\n\n def render_square_png(self, filename, size, padding, line_widths=dict()):\n coord_min = self.carthographic_bbox[0, :]\n coord_max = self.carthographic_bbox[1, :]\n coord_range = coord_max - coord_min\n\n px_per_coord = (size - 2 * padding) / coord_range.min()\n\n # offsets for non-square shaped bounding boxes\n offset = (coord_range - coord_range.min()) / 2\n\n with cairo.ImageSurface(cairo.FORMAT_ARGB32, size, size) as surface:\n ctx = cairo.Context(surface)\n ctx.scale(1, 1)\n\n # white background\n ctx.rectangle(0, 0, size, size)\n ctx.set_source_rgb(1, 1, 1)\n ctx.fill()\n\n ctx.set_source_rgb(0, 0, 0)\n ctx.set_line_cap(cairo.LINE_CAP_ROUND)\n for way, road_type in zip(self.carthographic_data, self.road_data):\n ctx.set_line_width(line_widths.get(road_type, 1))\n way_zeroed = (way - coord_min - offset) * px_per_coord + padding\n way_zeroed = np.rint(way_zeroed).astype(int)\n x, y = way_zeroed[0, :]\n ctx.move_to(x, size - y)\n for x, y in way_zeroed[1:]:\n ctx.line_to(x, size - y)\n ctx.stroke()\n\n # padding\n ctx.set_source_rgb(1, 1, 1)\n padding_rects = [\n (0, 0, size, padding),\n (0, 0, padding, size),\n (size - padding, 0, padding, size),\n (0, size - padding, size, padding),\n ]\n for rect in padding_rects:\n ctx.rectangle(*rect)\n ctx.fill()\n\n surface.write_to_png(filename)\n\n\nif __name__ == \"__main__\":\n m = Beautymap.square_centered((40.757667, -73.983715), 8.0)\n m.render_square_png(\n filename='test.png',\n size=2000,\n padding=50,\n line_widths={\n 'trunk': 5,\n 'primary': 4,\n 'secondary': 3,\n 'tertiary': 2,\n }\n )\n" }, { "alpha_fraction": 0.5967413187026978, "alphanum_fraction": 0.6537678241729736, "avg_line_length": 23.549999237060547, "blob_id": "f17223cc09f65fb1b8d127e8fded52ba9f52f8f8", "content_id": "371f3f00223bc4211ef4af8b23c21ca98fa2dd66", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 491, "license_type": "permissive", "max_line_length": 87, "num_lines": 20, "path": "/tests/test_beautymap.py", "repo_name": "pfaion/pybeautymaps", "src_encoding": "UTF-8", "text": "from pathlib import Path\n\nimport pybeautymaps as pbm\n\n\ndef test_beautymap_general_workflow(tmp_path):\n file_path: Path = tmp_path / 'test.png'\n\n assert not file_path.exists()\n\n line_widths = dict(\n trunk=5,\n primary=4,\n secondary=3,\n tertiary=2,\n )\n m = pbm.Beautymap.square_centered(center_latlon=(37.030347, -93.473126), width=1.2)\n m.render_square_png(file_path, size=1000, padding=50, line_widths=line_widths)\n\n assert file_path.exists()\n" }, { "alpha_fraction": 0.42892158031463623, "alphanum_fraction": 0.4950980246067047, "avg_line_length": 19.399999618530273, "blob_id": "3336694cf3c30f0aeb9ee7c79332c240889aa579", "content_id": "4faf2889f08693d226fcddb7e940221e4cc1c3f5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 408, "license_type": "permissive", "max_line_length": 81, "num_lines": 20, "path": "/examples/paris.py", "repo_name": "pfaion/pybeautymaps", "src_encoding": "UTF-8", "text": "from pybeautymaps import Beautymap\n\n\ndef main():\n m = Beautymap.square_centered(center_latlon=(48.873768, 2.295046), width=4.0)\n m.render_square_png(\n filename='paris.png',\n size=2000,\n padding=50,\n line_widths={\n 'trunk': 5,\n 'primary': 4,\n 'secondary': 3,\n 'tertiary': 2,\n }\n )\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.7407407164573669, "alphanum_fraction": 0.7654321193695068, "avg_line_length": 15.199999809265137, "blob_id": "beaeb29173c132422677e0c9409de90dbef6da48", "content_id": "ffd0d3b6ac2aaacaa73a1d02b19b66d259fb37a8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 81, "license_type": "permissive", "max_line_length": 25, "num_lines": 5, "path": "/pylama.ini", "repo_name": "pfaion/pybeautymaps", "src_encoding": "UTF-8", "text": "[pylint:TYPECHECK]\ngenerated-members=cairo.*\n\n[pycodestyle]\nmax_line_length = 88\n" }, { "alpha_fraction": 0.6098360419273376, "alphanum_fraction": 0.6295081973075867, "avg_line_length": 42.57143020629883, "blob_id": "47057fb65019ca8cdbb6650e946a5e4fe2c203fa", "content_id": "2c03dd982c96ef55cd8da9eece0d8bdcb27f1ef4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 305, "license_type": "permissive", "max_line_length": 189, "num_lines": 7, "path": "/examples/README.md", "repo_name": "pfaion/pybeautymaps", "src_encoding": "UTF-8", "text": "# Example Gallery\n\nClick on the images to view it large, click on the title to view the code.\n\n| | |\n| --- | --- |\n| [<img src=\"manhattan.png\" width=\"450px\"> ](manhattan.png) <br /> [Manhattan](manhattan.py) | [<img src=\"paris.png\" width=\"450px\"> ](paris.png) <br /> [Paris (Arc de Triomphe)](paris.py) |\n" }, { "alpha_fraction": 0.43236714601516724, "alphanum_fraction": 0.5, "avg_line_length": 19.700000762939453, "blob_id": "1fe547b0fd4462ae3534d3e63ea4544732cc3661", "content_id": "97d6da6662fc7e63bc814929a235d213df037d85", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 414, "license_type": "permissive", "max_line_length": 83, "num_lines": 20, "path": "/examples/manhattan.py", "repo_name": "pfaion/pybeautymaps", "src_encoding": "UTF-8", "text": "from pybeautymaps import Beautymap\n\n\ndef main():\n m = Beautymap.square_centered(center_latlon=(40.757667, -73.983715), width=8.0)\n m.render_square_png(\n filename='manhattan.png',\n size=2000,\n padding=50,\n line_widths={\n 'trunk': 5,\n 'primary': 4,\n 'secondary': 3,\n 'tertiary': 2,\n }\n )\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.6708394885063171, "alphanum_fraction": 0.6914580464363098, "avg_line_length": 23.690908432006836, "blob_id": "f7e14523a1c36b42a0d2f317316fa10cba5a1b97", "content_id": "28010b593f43a3ccce1d07e1b689c0856c92ec1d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1358, "license_type": "permissive", "max_line_length": 165, "num_lines": 55, "path": "/README.md", "repo_name": "pfaion/pybeautymaps", "src_encoding": "UTF-8", "text": "# pybeautymaps\n\n\n[![Travis Build](https://travis-ci.org/pfaion/pybeautymaps.svg?branch=master)](https://travis-ci.org/pfaion/pybeautymaps)\n[![Coveralls Coverage](https://coveralls.io/repos/github/pfaion/pybeautymaps/badge.svg?branch=master)](https://coveralls.io/github/pfaion/pybeautymaps?branch=master)\n\nThis is a library for creating beautyful map images with python.\n\n![Example Image](examples/manhattan.png)\n\n\n## Installation\n\n```bash\npip install git+https://github.com/pfaion/pybeautymaps\n```\n\n\n## Quick-Start\n\nTake a look at the [examples](examples) folder for different renderings.\n\n```python\nfrom pybeautymaps import Beautymap\n\nm = Beautymap.square_centered(\n center_latlon=(40.757667, -73.983715),\n width=8.0\n)\n\nm.render_square_png(\n filename='manhattan.png',\n size=2000,\n padding=50,\n line_widths={\n 'trunk': 5,\n 'primary': 4,\n 'secondary': 3,\n 'tertiary': 2,\n }\n)\n```\n\n## TODO\nA brief list of what additional features are planned:\n\n- [ ] Add option to show rivers\n- [ ] Add option to use custom colors\n- [ ] Add more rendering shapes (rectangular, circular, ...)\n- [ ] Add more output formats (jpg, pdf, svg, ...)\n- [ ] Add debugging support via iPython\n\n - [ ] Return image as iPython image\n - [ ] Plot different road types in different colors\n - [ ] Cache data for every road type separately\n" } ]
12
xiahouwenyu/xiahowenyu-s-newpage
https://github.com/xiahouwenyu/xiahowenyu-s-newpage
d8a346df6b6aa12eae6799159c9db90e252cc8bd
bb4642e5cd996a6dc26b02f2cdb736da1bc7eb28
2f21919fd61da124de5bfb48a95508435c5dc040
refs/heads/master
2022-10-04T01:34:48.313591
2022-05-26T10:42:48
2022-05-26T10:42:48
270,645,758
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.652399480342865, "alphanum_fraction": 0.661478579044342, "avg_line_length": 29.8799991607666, "blob_id": "6c0de00f49f72b5f684080ed87d2b32bb8f1c0eb", "content_id": "11e90c99730fb3382352aed608292d2b1ee2b37f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 771, "license_type": "no_license", "max_line_length": 88, "num_lines": 25, "path": "/web_project/views.py", "repo_name": "xiahouwenyu/xiahowenyu-s-newpage", "src_encoding": "UTF-8", "text": "from django.http import HttpResponse\nfrom django.shortcuts import render\nfrom django.template.loader import get_template\nfrom django.template import Context\nimport datetime\n\ndef hello(request):\n now = datetime.datetime.now()\n html = \"<html><body>Hello world.It is now %s.</body></html>\" %now\n return HttpResponse(html)\n\ndef runoob(request):\n a = [\"1\", \"2\", \"3\"]\n return render(request, 'runoob.html', {'a': a})\n\ndef main(request):\n now = datetime.datetime.now()\n bb = get_template('mod.html')\n htt = bb.render(\n {'person_name':\"shenhuafei\", 'company':'Ynnan University', 'ship_date':now, \n 'item_list':[1,2,3], 'ordered_warranty':'1'})\n return HttpResponse(htt)\n\ndef kong(request):\n return render(request, 'index.html')" } ]
1
samy-3687/ProductJoin
https://github.com/samy-3687/ProductJoin
c0b5bc04f7bfde0eade5184ba28fc0d70366e8a5
ad517f1f28a0070520978df5caafe606672bd1e3
2734ee1b07511c4bac2926300982c89f7fd90290
refs/heads/main
2023-03-21T02:33:49.372369
2021-03-11T10:45:18
2021-03-11T10:45:18
346,663,577
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8181818127632141, "alphanum_fraction": 0.8181818127632141, "avg_line_length": 63.57143020629883, "blob_id": "0eb68573f2a11c18e54cd1a3c9a3c84a0769c286", "content_id": "9edd08957d7b3638d95bb65c15e3231e70589258", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 451, "license_type": "no_license", "max_line_length": 221, "num_lines": 7, "path": "/RESTJoinTables/views.py", "repo_name": "samy-3687/ProductJoin", "src_encoding": "UTF-8", "text": "from RESTJoinTables.serializers import JoinTableSerialize\nfrom RESTJoinTables.models import JoinTablesmodel\nfrom rest_framework import viewsets\n\nclass JoinTableApi(viewsets.ModelViewSet):\n queryset = JoinTablesmodel.objects.raw('SELECT PdInf.prd_name, PdInf.prd_cat, PdInf.prd_price, PdInf.prd_id, PdDet.prd_desc FROM Product_info PdInf LEFT OUTER JOIN Product_detail PdDet ON PdInf.prd_id = PdDet.prd_id')\n serializer_class = JoinTableSerialize" }, { "alpha_fraction": 0.764976978302002, "alphanum_fraction": 0.764976978302002, "avg_line_length": 30.14285659790039, "blob_id": "77f20352323f3723e8e36cc6ff2a78ed26fdf4a8", "content_id": "238eaa29d21009d82e9f84dfd270a9b6c874ab66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 217, "license_type": "no_license", "max_line_length": 54, "num_lines": 7, "path": "/RESTJoinTables/serializers.py", "repo_name": "samy-3687/ProductJoin", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\nfrom RESTJoinTables.models import JoinTablesmodel\n\nclass JoinTableSerialize(serializers.ModelSerializer):\n class Meta:\n model= JoinTablesmodel\n fields= '__all__'" }, { "alpha_fraction": 0.6907894611358643, "alphanum_fraction": 0.7138158082962036, "avg_line_length": 37.125, "blob_id": "64bba6ae4a9e27e874a9b18baadd0119ac019b35", "content_id": "7e345f86a103af25c6ac02b77b5af78d11814d53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 304, "license_type": "no_license", "max_line_length": 52, "num_lines": 8, "path": "/RESTJoinTables/models.py", "repo_name": "samy-3687/ProductJoin", "src_encoding": "UTF-8", "text": "from django.db import models\n\nclass JoinTablesmodel(models.Model):\n prd_name = models.CharField(max_length = 50)\n prd_cat = models.CharField(max_length = 50)\n prd_price = models.IntegerField()\n prd_id = models.IntegerField(primary_key = True)\n prd_desc = models.CharField(max_length = 500)" } ]
3
wpan1/FacebookMessengerGraphs
https://github.com/wpan1/FacebookMessengerGraphs
9e8f075316f136b7b38cfd8d695703807bdc3b3f
974943b09c5dd9efe947fd71990f72c0f886d2fd
4f6e170012cec337ad62d05af2404f9b31d9c7fe
refs/heads/master
2020-04-12T14:10:39.687722
2018-12-20T07:57:33
2018-12-20T07:57:33
162,544,689
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6833060383796692, "alphanum_fraction": 0.6910802125930786, "avg_line_length": 28.936708450317383, "blob_id": "a83c290e6a71e78a6b3f12ce8dd44ca264d5c359", "content_id": "57aa2919df5332b7b080fa4b4d86958fcad85ff7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2444, "license_type": "no_license", "max_line_length": 85, "num_lines": 79, "path": "/scraper.py", "repo_name": "wpan1/FacebookMessengerGraphs", "src_encoding": "UTF-8", "text": "import json\r\nfrom collections import defaultdict\r\nimport datetime\r\nimport matplotlib.pyplot as plt\r\nimport operator\r\n\r\nsenderName = \"Birry William Pan\"\r\nrecieverName = \"Jessica Tran\"\r\n\r\nmessageDateDic = defaultdict(int)\r\nmessageDateDicSender = defaultdict(int)\r\nmessageDateDicReciever = defaultdict(int)\r\n\r\nmessageMonthDic = defaultdict(int)\r\nmessageMonthDicSender = defaultdict(int)\r\nmessageMonthDicReciever = defaultdict(int)\r\n\r\nmessageCountSender = 0\r\nmessageCountReciever = 0\r\n\r\nwith open('message.json') as data_file:\r\n messages = json.load(data_file)\r\n for msg in messages[\"messages\"]:\r\n # For text messages\r\n if msg[\"type\"] == \"Generic\":\r\n time = datetime.datetime.fromtimestamp(float(msg[\"timestamp_ms\"])/1000.0)\r\n messageDateDic[time.date()] += 1\r\n messageMonthDic[time.month] += 1\r\n if msg[\"sender_name\"] == senderName:\r\n messageCountSender += 1\r\n messageDateDicSender[time.date()] += 1\r\n messageMonthDicSender[time.month] += 1\r\n else:\r\n messageCountReciever += 1\r\n messageDateDicReciever[time.date()] += 1\r\n messageMonthDicReciever[time.month] += 1\r\n\r\nsortedMessageDateData = sorted(messageDateDic.items())\r\n\r\nsortedMessageMonthData = sorted(messageMonthDic.items())\r\n\r\nsortedMessageDateSenderData = sorted(messageDateDicSender.items())\r\nsortedMessageDateRecieverData = sorted(messageDateDicReciever.items())\r\n\r\nsortedMessageMonthSenderData = sorted(messageMonthDicSender.items())\r\nsortedMessageMonthRecieverData = sorted(messageMonthDicReciever.items())\r\n\r\n# Statistics\r\nprint(\"Total Messages sent by sender: \" + str(messageCountSender))\r\nprint(\"Total Messages sent by reciever: \" + str(messageCountReciever))\r\n\r\n# Plot monthly data\r\nplt.figure(1)\r\nx, y = zip(*sortedMessageMonthData)\r\nplt.plot(x, y)\r\n\r\n# Plot monthly data per person\r\nplt.figure(2)\r\nx, y = zip(*sortedMessageMonthSenderData)\r\nplt.plot(x, y, label=\"Sender\")\r\nx, y = zip(*sortedMessageMonthRecieverData)\r\nplt.plot(x, y)\r\nplt.plot(x, y, label=\"Reciever\")\r\nplt.legend(loc='upper right')\r\n\r\n# Plot daily data\r\nplt.figure(3)\r\nx, y = zip(*sortedMessageDateData)\r\nplt.plot(x, y)\r\n\r\n# Plot daily data per person\r\nplt.figure(4)\r\nx, y = zip(*sortedMessageDateSenderData)\r\nplt.plot(x, y, label=\"Sender\")\r\nx, y = zip(*sortedMessageDateRecieverData)\r\nplt.plot(x, y, label=\"Reciever\")\r\nplt.legend(loc='upper right')\r\n\r\nplt.show()\r\n" }, { "alpha_fraction": 0.7197580933570862, "alphanum_fraction": 0.7540322542190552, "avg_line_length": 18.076923370361328, "blob_id": "81cd9b538fa746892d4a716260c0bf336e4f4d29", "content_id": "45b18700c225d65637643a5de70a34a25441ca97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 496, "license_type": "no_license", "max_line_length": 68, "num_lines": 26, "path": "/README.md", "repo_name": "wpan1/FacebookMessengerGraphs", "src_encoding": "UTF-8", "text": "# FacebookMessengerGraphs\nPlots graphs between two participants\n- Monthly data\n- Monthly data per person\n- Daily data\n- Daily data per person\n\n## Install\n### Python 3+\nwww.google.com\n### MatplotLib\n```\npip install matplotlib\n```\n\n## Use\n- Download Facebook Messenger data from facebook\nhttps://www.facebook.com/help/1701730696756992?helpref=hc_global_nav\n\n- Nativate to messages/inbox/[thread]\n\n- Copy message.json to scraper.py directory\n\n- Install MatplotLib library\n\n- ```python scraper.py```\n" } ]
2
algorithmiaio/nautilus
https://github.com/algorithmiaio/nautilus
11c2bf7bb98364bb3176b4a8d63f6302623230ba
f135c4aa76a1e33ff9eff9b8a6422baf1c351697
8465392bf9088aa3b53e80fac80bc24248bdbcda
refs/heads/master
2021-03-22T01:07:05.908461
2017-12-16T00:47:21
2017-12-16T00:47:21
114,187,303
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6511042714118958, "alphanum_fraction": 0.6583729386329651, "avg_line_length": 41.58333206176758, "blob_id": "cbea7447cbf8eecf0f0efe29fc61650425ac6ef4", "content_id": "97954df581e34069e817a6d134322afee254bb4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3577, "license_type": "no_license", "max_line_length": 119, "num_lines": 84, "path": "/dataset.py", "repo_name": "algorithmiaio/nautilus", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# Author: A. Besir Kurtulmus\nfrom Algorithmia import client\nimport pandas as pd\n\nclass Dataset(object):\n '''\n Dataset should be formatted as a pandas DataFrame.\n '''\n def __init__(self, data_world_api_key=None):\n self.data_world_api_key = data_world_api_key\n self.data_set = None\n def get_dataset(self):\n # Override method after inheritance\n return self.data_set\n\nclass SentimentDataset(Dataset):\n def __init__(self, data_world_api_key=None):\n super().__init__(data_world_api_key)\n self.positive_sentiment = None\n self.neutral_sentiment = None\n self.negative_sentiment = None\n self.compound_sentiment = None\n\n def get_positive_sentiment():\n # Override method after inheritance\n return self.positive_sentiment\n\n def get_neutral_sentiment():\n # Override method after inheritance\n return self.neutral_sentiment\n\n def get_negative_sentiment():\n # Override method after inheritance\n return self.negative_sentiment\n\nclass AppleComputersTwitterSentiment(SentimentDataset):\n def __init__(self, data_world_api_key=None):\n super().__init__(data_world_api_key)\n self.data_world_api_key = data_world_api_key\n self.data_set = pd.read_csv('https://query.data.world/s/0cUqqvqhsPW532T5HZqFYuWuqWp2mS', encoding='ISO-8859-1')\n self.init_lambda_functions()\n self.remove_missing_sentiment()\n self.calculate_compound_sentiment()\n self.positive_sentiment = self.get_positive_sentiment()\n self.neutral_sentiment = self.get_neutral_sentiment()\n self.negative_sentiment = self.get_negative_sentiment()\n self.compound_sentiment = self.get_compound_sentiment()\n\n def init_lambda_functions(self):\n self.lambda_positive_compound_sentiment_confidence = lambda x: x[\"sentiment:confidence\"]\n self.lambda_neutral_compound_sentiment_confidence = lambda x: 0\n self.lambda_negative_compound_sentiment_confidence = lambda x: -1*x[\"sentiment:confidence\"]\n\n def remove_missing_sentiment(self):\n # Remove any tweet that does not contain information about sentiment\n self.data_set = self.data_set[\n (self.data_set[\"sentiment\"] == \"1\") |\n (self.data_set[\"sentiment\"] == \"3\") |\n (self.data_set[\"sentiment\"] == \"5\")\n ]\n\n def calculate_compound_sentiment(self):\n self.data_set.loc[(self.data_set[\"sentiment\"] == \"5\"), \"sentiment:compound_confidence\"] = \\\n self.data_set.apply(self.lambda_positive_compound_sentiment_confidence, axis=1)\n self.data_set.loc[(self.data_set[\"sentiment\"] == \"3\"), \"sentiment:compound_confidence\"] = \\\n self.data_set.apply(self.lambda_neutral_compound_sentiment_confidence, axis=1)\n self.data_set.loc[(self.data_set[\"sentiment\"] == \"1\"), \"sentiment:compound_confidence\"] = \\\n self.data_set.apply(self.lambda_negative_compound_sentiment_confidence, axis=1)\n\n def get_positive_sentiment(self):\n return self.data_set[(self.data_set[\"sentiment\"] == \"5\")][[\"text\", \"sentiment:confidence\"]]\n\n def get_neutral_sentiment(self):\n return self.data_set[(self.data_set[\"sentiment\"] == \"3\")][[\"text\", \"sentiment:confidence\"]]\n\n def get_negative_sentiment(self):\n return self.data_set[(self.data_set[\"sentiment\"] == \"1\")][[\"text\", \"sentiment:confidence\"]]\n\n def get_compound_sentiment(self):\n return self.data_set[[\"text\", \"sentiment:compound_confidence\"]]\n\n def get_dataset(self):\n return self.data_set\n" }, { "alpha_fraction": 0.7571428418159485, "alphanum_fraction": 0.7607142925262451, "avg_line_length": 34, "blob_id": "913f33ac1a1eda034def6e35db6430114ac78045", "content_id": "ed82aa4094e315b8423034200c036164333f198e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 280, "license_type": "no_license", "max_line_length": 68, "num_lines": 8, "path": "/tests/test_competition.py", "repo_name": "algorithmiaio/nautilus", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# Author: A. Besir Kurtulmus\n\n# Comparing sentiment analysis algorithms unit-test\n# Dataset from: http://ai.stanford.edu/~amaas/data/sentiment/\n\n# To run this test, run the following in the project root directory:\n# python -m pytest tests/test_sentiment_competition.py\n" }, { "alpha_fraction": 0.7070707082748413, "alphanum_fraction": 0.7410101294517517, "avg_line_length": 44.83333206176758, "blob_id": "0e118948e6f22af4883ff08f841bc2c57ec530ea", "content_id": "1c9dbce5406620aef269e4a721f874aa18bf6e75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2475, "license_type": "no_license", "max_line_length": 90, "num_lines": 54, "path": "/tests/test_sentiment_algorithmia.py", "repo_name": "algorithmiaio/nautilus", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# Author: A. Besir Kurtulmus\n\n# Comparing sentiment analysis algorithms unit-test\n# Dataset from: http://ai.stanford.edu/~amaas/data/sentiment/\n\n# To run this test, run the following in the project root directory:\n# python -m pytest tests/test_sentiment_algorithmia.py --algorithmia_api_key=simXXXXXXXXXX\nfrom algo import AlgorithmiaAlgorithm\nfrom glue import AlgorithmiaNlpSentimentAnalysis, AlgorithmiaNlpSocialSentimentAnalysis, \\\n AlgorithmiaMtmanSentimentAnalysis\n\ndef test_define_algorithmia_algorithms1(algorithmia_api_key):\n algo1_name = \"nlp/SentimentAnalysis/1.0.4\"\n algo1_type = \"classification\"\n algo1_glue = AlgorithmiaNlpSentimentAnalysis()\n algo1_input = \"I like trains.\"\n algo1_expected_output = 0.3612\n sentiment_algo1 = AlgorithmiaAlgorithm(api_key=algorithmia_api_key,\n algo_name=algo1_name, algo_type=algo1_type, glue=algo1_glue)\n sentiment_algo1.call(algo1_input)\n\n assert sentiment_algo1.result[\"compound\"] == algo1_expected_output\n\ndef test_define_algorithmia_algorithms2(algorithmia_api_key):\n algo1_name = \"nlp/SocialSentimentAnalysis/0.1.4\"\n algo1_type = \"classification\"\n algo1_glue = AlgorithmiaNlpSocialSentimentAnalysis()\n algo1_input = \"I like trains.\"\n algo1_expected_output = {}\n algo1_expected_output[\"positive\"] = 0.714\n algo1_expected_output[\"neutral\"] = 0.286\n algo1_expected_output[\"negative\"] = 0.0\n algo1_expected_output[\"compound\"] = 0.3612\n sentiment_algo1 = AlgorithmiaAlgorithm(api_key=algorithmia_api_key,\n algo_name=algo1_name, algo_type=algo1_type, glue=algo1_glue)\n sentiment_algo1.call(algo1_input)\n\n assert sentiment_algo1.result[\"positive\"] == algo1_expected_output[\"positive\"]\n assert sentiment_algo1.result[\"neutral\"] == algo1_expected_output[\"neutral\"]\n assert sentiment_algo1.result[\"negative\"] == algo1_expected_output[\"negative\"]\n assert sentiment_algo1.result[\"compound\"] == algo1_expected_output[\"compound\"]\n\ndef test_define_algorithmia_algorithms2(algorithmia_api_key):\n algo1_name = \"mtman/SentimentAnalysis/0.1.1\"\n algo1_type = \"classification\"\n algo1_glue = AlgorithmiaMtmanSentimentAnalysis()\n algo1_input = \"I like trains.\"\n algo1_expected_output = 0.0\n sentiment_algo1 = AlgorithmiaAlgorithm(api_key=algorithmia_api_key,\n algo_name=algo1_name, algo_type=algo1_type, glue=algo1_glue)\n sentiment_algo1.call(algo1_input)\n\n assert sentiment_algo1.result[\"compound\"] == algo1_expected_output\n" }, { "alpha_fraction": 0.7269503474235535, "alphanum_fraction": 0.7269503474235535, "avg_line_length": 30.33333396911621, "blob_id": "3a8022dda97f96a0d0a2d5aefb2cf7438eba6de1", "content_id": "9209997998f80afd6bb0d33c4c67f76d6e76bc95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 282, "license_type": "no_license", "max_line_length": 73, "num_lines": 9, "path": "/conftest.py", "repo_name": "algorithmiaio/nautilus", "src_encoding": "UTF-8", "text": "import pytest\n\ndef pytest_addoption(parser):\n parser.addoption(\"--algorithmia_api_key\", action=\"store\", default=\"\",\n help=\"algorithmia_api_key: simXXXXXXXXXX\")\n\[email protected]\ndef algorithmia_api_key(request):\n return request.config.getoption(\"--algorithmia_api_key\")\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6833333373069763, "avg_line_length": 14, "blob_id": "1d7b62ed6ec94a234f10c64070afbeb0466ae06c", "content_id": "93cac3e9d9ffab05fe378d913092c6e89bbd6d85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 60, "license_type": "no_license", "max_line_length": 22, "num_lines": 4, "path": "/metrics.py", "repo_name": "algorithmiaio/nautilus", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# Author: A. Besir Kurtulmus\n\nimport numpy as np\n" }, { "alpha_fraction": 0.5047619342803955, "alphanum_fraction": 0.6952381134033203, "avg_line_length": 16.5, "blob_id": "11cb0298f10a810cbee684e16e975e42ce0e321c", "content_id": "f5099135638f57b34d650a39a2cba7653fb50ea4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 105, "license_type": "no_license", "max_line_length": 27, "num_lines": 6, "path": "/requirements.txt", "repo_name": "algorithmiaio/nautilus", "src_encoding": "UTF-8", "text": "numpy==1.13.3\nseaborn==0.8.1\nalgorithmia==1.0.8\npandas==0.21.1\ndatadotworld[pandas]==1.4.2\npytest==3.3.1\n" }, { "alpha_fraction": 0.5734870433807373, "alphanum_fraction": 0.5763688683509827, "avg_line_length": 22.133333206176758, "blob_id": "71dc905695616146518b3cd2bfc54a8290c505d2", "content_id": "92ab8ad47893543d535a50ddc65f49c63c084156", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 347, "license_type": "no_license", "max_line_length": 67, "num_lines": 15, "path": "/algo_type.py", "repo_name": "algorithmiaio/nautilus", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# Author: A. Besir Kurtulmus\n\nclass AlgoTypes(object):\n def __init__(self):\n self.types = [\"classification\", \"regression\", \"multilabel\"]\n\n def valid_type(self, algo_type):\n if algo_type in self.types:\n return True\n else:\n return False\n\n def get_types(self):\n return self.types\n" }, { "alpha_fraction": 0.625, "alphanum_fraction": 0.6499999761581421, "avg_line_length": 19, "blob_id": "c78cba562cf3148aa9b37923e15ea44452766ec5", "content_id": "bdb26b17ab458b5cee23636c4e6d7d01b6401f5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 40, "license_type": "no_license", "max_line_length": 22, "num_lines": 2, "path": "/visualize.py", "repo_name": "algorithmiaio/nautilus", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# Author: A. Besir Kurtulmus\n" }, { "alpha_fraction": 0.624907910823822, "alphanum_fraction": 0.6256448030471802, "avg_line_length": 32.09756088256836, "blob_id": "389d0e6e8bc00ad74f2fabc17636e2a5a7c06a6f", "content_id": "1277c37f10e2f6d40e2f48f4884690178e07f2b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1357, "license_type": "no_license", "max_line_length": 72, "num_lines": 41, "path": "/algo.py", "repo_name": "algorithmiaio/nautilus", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# Author: A. Besir Kurtulmus\nfrom Algorithmia import client\nfrom algo_type import AlgoTypes\n\nclass Algorithm(object):\n '''\n Algorithm is defined as an API endpoint that has a certain function.\n Does not only refer to an Algorithmia algorithm.\n '''\n def __init__(self, api_key, algo_name, algo_type, glue):\n self.types = AlgoTypes()\n self.type = algo_type\n if not self.types.valid_type(self.type):\n raise Exception(\"Algorithm is not a valid type.\")\n if isinstance(glue, type(None)):\n raise Exception(\"Please provide a glue for your algorithm.\")\n self.glue = glue\n self.client = None\n self.algo = None\n self.metadata = None\n self.result = None\n\n def call(self, input):\n return self.result\n\nclass AlgorithmiaAlgorithm(Algorithm):\n '''\n An Algorithmia algorithm.\n '''\n def __init__(self, api_key, algo_name, algo_type, glue):\n super().__init__(api_key, algo_name, algo_type, glue)\n self.client = client(api_key)\n self.algo = self.client.algo(algo_name)\n\n def call(self, user_input):\n algo_input = self.glue.process_input(user_input)\n res = self.algo.pipe(algo_input)\n self.metadata = res.metadata\n self.result = self.glue.process_output(res.result)\n return self.result\n" }, { "alpha_fraction": 0.7192192077636719, "alphanum_fraction": 0.7312312126159668, "avg_line_length": 17, "blob_id": "b1af91ef1a7ace4813b608a533928552c6fec0c6", "content_id": "b1240fe55c4e01fc4ecce4acbc71be86db23e61b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 666, "license_type": "no_license", "max_line_length": 174, "num_lines": 37, "path": "/README.md", "repo_name": "algorithmiaio/nautilus", "src_encoding": "UTF-8", "text": "# nautilus\n\n## 1. Introduction\n\nLorem whatever ipsum.\n\n## 2. Features\n\nLook at the cool features this library has!\n\n## 3. Installation\n\nHow to install dis.\n\n## 4. Getting Started\n\nHow do I use this? eli5\n\n## 5. Development\n\nHow can I contribute?\n\n## 6. Testing\n\nBefore testing, make sure that you have everything installed in the `requirements.txt` dependency file. We recommend using `virtualenv` to keep everything clean and isolated.\n\nSome tests require parameters to run. For example, you need API keys for testing certain API's work.\n\nTo start a test, run the following:\n\n```\npython -m pytest tests/<test_name>.py\n```\n\n## 7. Credits\n\nHumblebrag a little here..\n" }, { "alpha_fraction": 0.6947368383407593, "alphanum_fraction": 0.699999988079071, "avg_line_length": 20.11111068725586, "blob_id": "65a53ddae4b1c5c6be3fbc859ed5b36ec734bab2", "content_id": "6291f6f6a46fbccaa2b13f34553322136745418a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 190, "license_type": "no_license", "max_line_length": 57, "num_lines": 9, "path": "/nau.py", "repo_name": "algorithmiaio/nautilus", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# Author: A. Besir Kurtulmus\n# Collects metrics data for getting algorithm performance\n\nfrom metrics import *\n\nclass Competition(object):\n def __init__(self):\n continue\n" }, { "alpha_fraction": 0.7124902009963989, "alphanum_fraction": 0.7399842739105225, "avg_line_length": 35.371429443359375, "blob_id": "413933833edae496f7e79a1bcac80ad481ce3f0d", "content_id": "cd371a0c8970c1968fcfe18021a7c2906f46107d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1273, "license_type": "no_license", "max_line_length": 82, "num_lines": 35, "path": "/tests/test_sentiment_dataset.py", "repo_name": "algorithmiaio/nautilus", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# Author: A. Besir Kurtulmus\n\n# Comparing sentiment analysis algorithms unit-test\n# Dataset from: http://ai.stanford.edu/~amaas/data/sentiment/\n\n# To run this test, run the following in the project root directory:\n# python -m pytest tests/test_sentiment_dataset.py\nfrom dataset import AppleComputersTwitterSentiment\n\nds = AppleComputersTwitterSentiment()\n\ndef test_dataset_downloaded():\n assert not isinstance(ds, type(None))\n\ndef test_verify_positive_sentiment_values():\n # There should only be 423 positive tweets\n assert len(ds.get_positive_sentiment()) == 423\n\ndef test_verify_neutral_sentiment_values():\n # There should only be 2162 neutral tweets\n assert len(ds.get_neutral_sentiment()) == 2162\n\ndef test_verify_negative_sentiment_values():\n # There should only be 1219 negative tweets\n assert len(ds.get_negative_sentiment()) == 1219\n\ndef test_verify_compound_sentiment_values():\n # There should be 3804 compound tweets\n assert len(ds.get_compound_sentiment()) == 3804\n\ndef test_verify_compound_scores():\n # Make sure that compound scores are between -1 and 1\n assert min(ds.get_compound_sentiment()[\"sentiment:compound_confidence\"]) >= -1\n assert max(ds.get_compound_sentiment()[\"sentiment:compound_confidence\"]) <= 1\n" }, { "alpha_fraction": 0.622636616230011, "alphanum_fraction": 0.624449610710144, "avg_line_length": 34.099998474121094, "blob_id": "6f8c43d1155d4260b1d6a6a408453c8525be7449", "content_id": "7ab4956e3a01da0a1c970372fd58defe86c785c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3861, "license_type": "no_license", "max_line_length": 76, "num_lines": 110, "path": "/glue.py", "repo_name": "algorithmiaio/nautilus", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# Author: A. Besir Kurtulmus\nfrom algo_type import AlgoTypes\n\nclass Glue(object):\n '''\n Glue is an I/O adaptor for algorithms. It creates a common standard for\n interacting with algorithms in metrics.\n\n Currently 3 types of glues are supported: classification, regression and\n multilabel.\n '''\n def __init__(self, algo_type):\n self.input_structure = None\n self.output_structure = None\n self.types = AlgoTypes()\n self.type = algo_type\n if not self.types.valid_type(self.type):\n raise Exception(\"Algorithm is not a valid type.\")\n\n def process_input(self, user_input):\n # This takes the user input, and casts it into the algo input.\n # override this method\n algo_input = user_input\n return algo_input\n\n def process_output(self, algo_output):\n # This takes the algo output, and casts it into the user output.\n # override this method\n user_output = algo_output\n return user_output\n\nclass SentimentAnalysisGlue(Glue):\n '''\n Glue object for sentiment analysis.\n\n Returns sentiment object with positive, neutral, negative and compound\n float values.\n '''\n def __init__(self):\n super().__init__(\"classification\")\n self.sentiment = {}\n self.sentiment[\"positive\"] = None\n self.sentiment[\"neutral\"] = None\n self.sentiment[\"negative\"] = None\n self.sentiment[\"compound\"] = None\n\nclass AlgorithmiaNlpSentimentAnalysis(SentimentAnalysisGlue):\n def __init__(self):\n super().__init__()\n self.input_structure = {}\n self.output_structure = {}\n self.input_structure[\"document\"] = str\n self.output_structure[\"sentiment\"] = float\n self.output_structure[\"document\"] = str\n\n def process_input(self, user_input):\n algo_input = {}\n if not isinstance(user_input, str):\n raise Exception(\"Input must be a string.\")\n algo_input[\"document\"] = user_input\n return algo_input\n\n def process_output(self, algo_output):\n user_output = {}\n self.sentiment[\"compound\"] = algo_output[0][\"sentiment\"]\n return self.sentiment\n\nclass AlgorithmiaNlpSocialSentimentAnalysis(SentimentAnalysisGlue):\n def __init__(self):\n super().__init__()\n self.input_structure = {}\n self.output_structure = {}\n self.input_structure[\"sentence\"] = str\n self.output_structure[\"sentiment\"] = {}\n self.output_structure[\"sentiment\"][\"positive\"] = float\n self.output_structure[\"sentiment\"][\"neutral\"] = float\n self.output_structure[\"sentiment\"][\"negative\"] = float\n self.output_structure[\"sentiment\"][\"compound\"] = float\n self.output_structure[\"sentence\"] = str\n\n def process_input(self, user_input):\n algo_input = {}\n if not isinstance(user_input, str):\n raise Exception(\"Input must be a string.\")\n algo_input[\"sentence\"] = user_input\n return algo_input\n\n def process_output(self, algo_output):\n user_output = {}\n self.sentiment[\"positive\"] = algo_output[0][\"positive\"]\n self.sentiment[\"neutral\"] = algo_output[0][\"neutral\"]\n self.sentiment[\"negative\"] = algo_output[0][\"negative\"]\n self.sentiment[\"compound\"] = algo_output[0][\"compound\"]\n return self.sentiment\n\nclass AlgorithmiaMtmanSentimentAnalysis(SentimentAnalysisGlue):\n def __init__(self):\n super().__init__()\n self.input_structure = str\n self.output_structure = float\n\n def process_input(self, user_input):\n if not isinstance(user_input, str):\n raise Exception(\"Input must be a string.\")\n return user_input\n\n def process_output(self, algo_output):\n self.sentiment[\"compound\"] = float(algo_output)\n return self.sentiment\n" } ]
13
matthewmckenna/assigner
https://github.com/matthewmckenna/assigner
b19bb6404c30bc8824f2a80bd5d8a2e30c693eab
bb86e2579a3e1fae8d0cbc6222d2526d148e6f11
a6c6652fbe33c6c3b66b4d910b0bd0e3ff4c6c46
refs/heads/master
2020-03-27T00:31:50.203373
2018-08-21T23:40:10
2018-08-21T23:40:10
145,630,693
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6624952554702759, "alphanum_fraction": 0.6636329293251038, "avg_line_length": 36.67142868041992, "blob_id": "e8027c7960565798ab92350a610bac62ff9652c4", "content_id": "f945a8d31fd7abe91e3825c9080bb8f8c73fc793", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2637, "license_type": "no_license", "max_line_length": 94, "num_lines": 70, "path": "/assigner.py", "repo_name": "matthewmckenna/assigner", "src_encoding": "UTF-8", "text": "#!/usr/env/bin python\n\"\"\"randomly assign choices to names\"\"\"\nimport argparse\nfrom collections import defaultdict\nimport pprint\nimport random\nfrom typing import DefaultDict, List\n\n\ndef main(args: argparse.Namespace) -> None:\n \"\"\"main entry point\"\"\"\n # dict mapping from a `name` to a list of `choices`\n d: DefaultDict[str, List[str]] = defaultdict(list)\n\n # cannot use `if args.seed` because a seed of `0` is valid, but \"falsy\"!\n if args.seed is not None:\n random.seed(args.seed)\n\n # creates lists from `names` and possible `choices`\n with open(args.names, 'rt') as f, open(args.choices, 'rt') as f2:\n names = [name.strip() for name in f]\n choices = [choice.strip() for choice in f2]\n\n # if there are more choices than names, at least one name\n # will have more than one choice\n num_extra_choices = len(choices) - len(names)\n\n # shuffle the names\n # could also use: random.sample(names, k=len(names))\n random.shuffle(names)\n\n # shuffle the order of the choices\n # `len(randomised_choices)` will be < `len(choices)` if\n # `len(names)` != `len(choices)`\n # in these cases, it will be `min(len(choices), len(names))`\n randomised_choices = random.sample(choices, k=min(len(choices), len(names)))\n\n for name, choice in zip(names, randomised_choices):\n d[name].append(choice)\n\n if len(names) > len(choices):\n names_without_choices = set(names) - d.keys()\n print(f'There are more names ({len(names)}) than choices ({len(choices)})!')\n print(f'The following names were not assigned choices: {names_without_choices}')\n\n # `remaining_choices` will be an empty set (and therefore \"falsy\") if\n # `len(names)` == `len(choices)`\n remaining_choices = set(choices) - set(randomised_choices)\n\n if remaining_choices:\n # `additional_choices` contains names of those who get\n # an additional choice, as num_names > num_choices\n additional_choices = random.sample(names, k=num_extra_choices)\n\n for name, choice in zip(additional_choices, remaining_choices):\n d[name].append(choice)\n\n pprint.pprint(dict(d))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description='carry out random draws',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n )\n parser.add_argument('names', help='filename containing names of individuals in the draw')\n parser.add_argument('choices', help='filename containing choices')\n parser.add_argument('-s', '--seed', help='random seed for reproducible results', type=int)\n args = parser.parse_args()\n main(args)\n" }, { "alpha_fraction": 0.6840958595275879, "alphanum_fraction": 0.6897603273391724, "avg_line_length": 23.157894134521484, "blob_id": "1c932a1a552d8365697bb6386674cc06ab2c862e", "content_id": "f6aa6d188d69b43769cce3475574c246ef835fd9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2297, "license_type": "no_license", "max_line_length": 164, "num_lines": 95, "path": "/README.md", "repo_name": "matthewmckenna/assigner", "src_encoding": "UTF-8", "text": "# Assigner\n\nA simple application that reads a list of names and choices, and randomly assigns choices to the names.\n\nThis application was created as a quick way to carry out a draw for the 2018 World Cup.\n\n## Usage\n\n```\nusage: assigner.py [-h] [-s SEED] names choices\n```\n\nTo run the application, two filenames must be provided—the first should contain the names, and the second should contain the choices to be assigned.\n\nPositional arguments | Description\n:------------------- | :----------\n`names` | filename containing names of individuals in the draw\n`choices` | filename containing choices\n\nOptionally, you can set the seed with `-s` or `--seed` in order to obtain reproducible results.\n\nOptional arguments | Description\n:----------------- | :----------\n`-s, --seed` | random seed for reproducible results (default: None)\n\nThis application handles cases where the number of choices is greater than the number of names, and where the number of names is greater than the number of choices.\n\nSome simplistic examples are shown below.\n\n## Examples\n\n### Equal number of names and choices\n\nIn this scenario, each name in `names.txt` is assigned exactly one (1) choice from `choices.txt`.\n\n```\n$ cat names.txt\nalice\nbob\neve\n\n$ cat choices.txt\nrock\npaper\nscissors\n\n$ python3 assigner.py names.txt choices.txt\n{'alice': ['paper'], 'bob': ['scissors'], 'eve': ['rock']}\n```\n\n### More choices than names\n\nIn this scenario, *at least one (1)* name in `names.txt` will have two (2) or more choices from `choices.txt`.\n\nIn the example below, `bob` is assigned both `paper` and `scissors`.\n\n```\n$ cat names.txt\nalice\nbob\neve\n\n$ cat choices.txt\nrock\npaper\nscissors\nlizard\n\n$ python3 assigner.py names.txt choices.txt\n{'alice': ['rock'], 'bob': ['paper', 'scissors'], 'eve': ['lizard']}\n```\n\n### More names than choices\n\nIn this scenario, *at least one (1)* name in `names.txt` will not be assigned any choice from `choices.txt`.\n\nIn the example below, `alice` is not assigned any choices.\n\n```\n$ cat names.txt\nalice\nbob\neve\nmike\n\n$ cat choices.txt\nrock\npaper\nscissors\n\n$ python3 assigner.py names.txt choices.txt\nThere are more names (4) than choices (3)!\nThe following names were not assigned choices: {'alice'}\n{'bob': ['paper'], 'eve': ['scissors'], 'mike': ['rock']}\n```\n" } ]
2
rexjohannes98/pc-shrotter-discord.py
https://github.com/rexjohannes98/pc-shrotter-discord.py
4176a51767def54475ba1537e9fed9728a02e0de
30f7d2ab334a3ae85f39738aa8950ffd04d12f57
f4a2bad1fb1ed59f43ee879a8345c98ee4cfe278
refs/heads/master
2020-08-21T04:55:30.720144
2019-10-18T20:15:02
2019-10-18T20:15:02
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7516778707504272, "alphanum_fraction": 0.7634228467941284, "avg_line_length": 34.05882263183594, "blob_id": "f37a834987fcddf37f769cd29b09b613ecf1964a", "content_id": "020cfe191ea02bbda065804e96aabe1ec41b6b1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 597, "license_type": "no_license", "max_line_length": 140, "num_lines": 17, "path": "/README.md", "repo_name": "rexjohannes98/pc-shrotter-discord.py", "src_encoding": "UTF-8", "text": "# PC-Shrotter\nDamit du deinen PC gut zerstören kannst!\n\nNeedent: Linux\n\nHow to use!\n\nFirst up install python (apt install python3)\nNext step install pip (apt install python3-pip)\nThen install discord.py (pip3 install discord.py)\nAnd run: \"git clone https://github.com/rexjohannes/pc-shrotter-discord.py.git\"\n\nOr in one: apt install python3 python3-pip && pip3 install discord.py && git clone https://github.com/rexjohannes/pc-shrotter-discord.py.git\n\nNow Replace \"Token\" at the End of the Code with your Bot Token.\nNow Invite the Bot!\nAnd run the bot with \"cd (folderofbot)\" and \"python3 bot.py\"\n" }, { "alpha_fraction": 0.6824480295181274, "alphanum_fraction": 0.6824480295181274, "avg_line_length": 23.742856979370117, "blob_id": "74b411a4d0d198dcd563039ad392f76385c94e1e", "content_id": "c2ef540bc7dae35ddc693a359c87fe8df7a542c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 867, "license_type": "no_license", "max_line_length": 85, "num_lines": 35, "path": "/bot.py", "repo_name": "rexjohannes98/pc-shrotter-discord.py", "src_encoding": "UTF-8", "text": "import discord\nimport asyncio\nimport os\nfrom discord.ext import commands\n\nbot = commands.Bot(command_prefix='!')\n\[email protected]\nasync def on_ready():\n await bot.change_presence(activity=discord.Game(\"PC zerstören!\"))\n print('Logged in as')\n print(bot.user.name)\n print(bot.user.id)\n print(discord.utils.oauth_url(bot.user.id))\n\n \[email protected]\nasync def on_command_error(ctx, error):\n if isinstance(error, commands.MissingRequiredArgument):\n await ctx.send(\"Missing Argument!\")\n \nbot.remove_command('help')\n\[email protected]()\nasync def help(ctx):\n await ctx.send(\"Commands: \\nhelp - View this message. \\ncmd - Run a CMD on the PC\")\n \[email protected]()\[email protected]_owner()\nasync def cmd(ctx, *, cmd:str):\n returned_value = os.system(cmd)\n await ctx.send(\"Erfolgreich\")\n print(f\"{ctx.author} has executed {cmd}\")\n \nbot.run('TOKEN')\n" } ]
2
RakhithJK/mapbox-navigation-native-ios
https://github.com/RakhithJK/mapbox-navigation-native-ios
b52bc93a0e48787d44556adb6b10e2fdb2a01aac
85587f411f682879563c68cb6ce8392d3cab2491
c74ba576e3a2d7125e2a730e87912a6c58ef9824
refs/heads/main
2023-06-25T12:17:33.473568
2021-07-22T07:59:03
2021-07-22T07:59:03
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7054478526115417, "alphanum_fraction": 0.7220683097839355, "avg_line_length": 23.066667556762695, "blob_id": "544922f15480a565e76b22937fe33c9ebb7bfce5", "content_id": "c3f9bc11cd3659289670ecaf2629d004acdeaa57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1083, "license_type": "no_license", "max_line_length": 170, "num_lines": 45, "path": "/README.md", "repo_name": "RakhithJK/mapbox-navigation-native-ios", "src_encoding": "UTF-8", "text": "# mapbox-navigation-native-ios\n\n### Prerequisites\n\nBefore you can download the [Mapbox Navigation Native](https://github.com/mapbox/mapbox-navigation-native) for iOS, you need to create a token with `DOWNLOAD:READ` scope.\nGo to https://account.mapbox.com and click \"Create token\"\n\n##### SPM, CocoaPods and Carthage\nInsert or append the following to `~/.netrc`\n\n```bash\nmachine api.mapbox.com\n login mapbox\n password <TOKEN WITH DOWNLOAD:READ SCOPE>\n```\n\n## Integration\n\n##### Swift Package Manager\n\n###### Using SPM Package\n\n```swift\n.package(url: \"[email protected]:mapbox/mapbox-navigation-native-ios.git\", from: \"59.0.0\"),\n```\n\n##### CocoaPods\n\n```ruby\npod 'MapboxNavigationNative', '59.0.0'\n```\n\n##### Carthage\n\nAdd the following code to your Cartfile.\n\n```bash\nbinary \"https://api.mapbox.com/downloads/v2/carthage/mobile-navigation-native/MapboxNavigationNative.json\" == 59.0.0\nbinary \"https://api.mapbox.com/downloads/v2/carthage/mapbox-common/MapboxCommon-ios.json\" == 16.1.0\n```\n\nThen run the following command in the Terminal.\n```bash\ncarthage update --platform ios --use-netrc\n```\n" }, { "alpha_fraction": 0.6263736486434937, "alphanum_fraction": 0.7032967209815979, "avg_line_length": 17.200000762939453, "blob_id": "f827ea5da972f777a34f6691a4753502f514f136", "content_id": "78aec4e5467817a0ae2be5048b35cd77153c2a77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 91, "license_type": "no_license", "max_line_length": 40, "num_lines": 5, "path": "/Tests/CocoaPods/Podfile", "repo_name": "RakhithJK/mapbox-navigation-native-ios", "src_encoding": "UTF-8", "text": "platform :ios, '11.0'\n\ntarget 'PodInstall' do\n pod 'MapboxNavigationNative', '59.0.0'\nend\n" }, { "alpha_fraction": 0.6489361524581909, "alphanum_fraction": 0.6691489219665527, "avg_line_length": 32.57143020629883, "blob_id": "0482a774655e092e1828277e84ca80f6ae3bb941", "content_id": "d600e07a0805adff5af6db71d27234034030eb7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 940, "license_type": "no_license", "max_line_length": 138, "num_lines": 28, "path": "/scripts/release.sh", "repo_name": "RakhithJK/mapbox-navigation-native-ios", "src_encoding": "UTF-8", "text": "#!/bin/bash\nset -euo pipefail\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\nVERSION=$1\nMAPBOX_COMMON_VERSION=$2\n\nXCFRAMEWORK_ZIP=$(mktemp).zip\n\n# artifact can be not available immediately, so here we try to wait for it's availability\n# 10 minutes\nTIMEOUT=600\nINTERVAL=30\nTIME=0\nURL=\"https://api.mapbox.com/downloads/v2/mobile-navigation-native/releases/ios/packages/${VERSION}/MapboxNavigationNative.xcframework.zip\"\nwhile [[ \"$(curl -s -w ''%{http_code}'' --netrc ${URL} --output $XCFRAMEWORK_ZIP)\" != \"200\" ]]; do \n >&2 echo \"Artifact is not available yet. Waiting ${INTERVAL} seconds...\"\n sleep ${INTERVAL}\n TIME=$((TIME+${INTERVAL}))\n if [[ \"$TIME\" -gt \"$TIMEOUT\" ]]; then\n >&2 echo \"Timeout...\"\n exit 1\n fi\ndone\n\nCHECKSUM=$(swift package compute-checksum ${XCFRAMEWORK_ZIP})\npython3 ${DIR}/change_version.py --version ${VERSION} --common-version ${MAPBOX_COMMON_VERSION} --checksum ${CHECKSUM}\n" }, { "alpha_fraction": 0.6322188377380371, "alphanum_fraction": 0.6352583765983582, "avg_line_length": 22.428571701049805, "blob_id": "173486be35ff1762d3a0759b19daaacdb4d1537e", "content_id": "468f842903669c34411893f90025f918d8883b75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 329, "license_type": "no_license", "max_line_length": 55, "num_lines": 14, "path": "/Tests/test.sh", "repo_name": "RakhithJK/mapbox-navigation-native-ios", "src_encoding": "UTF-8", "text": "#!/usr/bin/env sh\nset -euo pipefail\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nROOT_DIR=\"${DIR}/..\"\n\necho \"Testing SPM...\"\n${ROOT_DIR}/Tests/test_spm.sh >/dev/null\n\necho \"Testing Carthage...\"\n${ROOT_DIR}/Tests/test_carthage.sh >/dev/null\n\necho \"Testing CocoaPods...\"\n${ROOT_DIR}/Tests/test_cocoapods.sh >/dev/null\n\n" }, { "alpha_fraction": 0.697586715221405, "alphanum_fraction": 0.7058823704719543, "avg_line_length": 36.88571548461914, "blob_id": "da626ca7eb50abd435930cdada2cbc65090f3850", "content_id": "9e7a5a3f92a1fad09b7525a14feb932cab019dda", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1326, "license_type": "no_license", "max_line_length": 138, "num_lines": 35, "path": "/Tests/test_spm.sh", "repo_name": "RakhithJK/mapbox-navigation-native-ios", "src_encoding": "UTF-8", "text": "#!/usr/bin/env sh\nset -euo pipefail\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nROOT_DIR=\"${DIR}/..\"\npushd \"${ROOT_DIR}/Tests/SPM\"\n\nfunction find_pattern {\n FILE=$1\n PATTERN=$2\n MATCH=$(python -c \"import re; import sys; print(re.findall('$PATTERN', open(sys.argv[1]).read())[0])\" $FILE)\n echo $MATCH\n}\n\n# test that we have correct checksum in Package.swift\nVERSION=$(find_pattern $ROOT_DIR/Package.swift \"let version = \\\"(.+)\\\"\")\nACTUAL_CHECKSUM=$(find_pattern $ROOT_DIR/Package.swift \"let checksum = \\\"(.+)\\\"\")\necho \"Current version in Package.swift: ${VERSION}\"\necho \"Current checksum in Package.swift: ${ACTUAL_CHECKSUM}\"\n\nURL=\"https://api.mapbox.com/downloads/v2/mobile-navigation-native/releases/ios/packages/${VERSION}/MapboxNavigationNative.xcframework.zip\"\nXCFRAMEWORK_ZIP=$(mktemp).zip\ncurl -s --retry 3 --netrc ${URL} --output ${XCFRAMEWORK_ZIP}\nEXPECTED_CHECKSUM=$(swift package compute-checksum ${XCFRAMEWORK_ZIP})\n\nif [[ \"$ACTUAL_CHECKSUM\" != \"$EXPECTED_CHECKSUM\" ]]; then\n >&2 echo \"Actual cheksum is ${ACTUAL_CHECKSUM} and expected checksum is ${EXPECTED_CHECKSUM}. SPM checksum test failed.\"\n exit 1\nfi\n\n# try to build test project\nxcodegen generate\nxcodebuild -project SPMTest.xcodeproj -scheme SPMTest -destination 'platform=iOS Simulator,name=iPhone 11,OS=latest' build\n\npopd\n" }, { "alpha_fraction": 0.6302900910377502, "alphanum_fraction": 0.6312410831451416, "avg_line_length": 37.94444274902344, "blob_id": "015218dbf287d58780c175b826c95cf2a63226cc", "content_id": "f60daf9cfe64437803542f00de58d0f49e449294", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4206, "license_type": "no_license", "max_line_length": 139, "num_lines": 108, "path": "/scripts/change_version.py", "repo_name": "RakhithJK/mapbox-navigation-native-ios", "src_encoding": "UTF-8", "text": "import argparse\nimport os\nimport re\n\nROOT = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')\nREADME = os.path.join(ROOT, 'README.md')\nPACKAGE_SWIFT = os.path.join(ROOT, 'Package.swift')\nTEST_CARTFILE = os.path.join(ROOT, 'Tests/Carthage/Cartfile')\nTEST_PODFILE = os.path.join(ROOT, 'Tests/CocoaPods/Podfile')\nTEST_SPM_PROJECT = os.path.join(ROOT, 'Tests/SPM/project.yml')\n\ndef change_cocoapods(podfile_contents, version):\n podfile_contents = re.sub(\n r\"pod 'MapboxNavigationNative', '.+'\", \n f\"pod 'MapboxNavigationNative', '{version}'\", \n podfile_contents)\n return podfile_contents\n\ndef change_carthage(cartfile_contents, version, common_version):\n cartfile_contents = re.sub(\n re.escape('binary \"https://api.mapbox.com/downloads/v2/carthage/mobile-navigation-native/MapboxNavigationNative.json\" == ') + '.+',\n f'binary \"https://api.mapbox.com/downloads/v2/carthage/mobile-navigation-native/MapboxNavigationNative.json\" == {version}',\n cartfile_contents\n )\n cartfile_contents = re.sub(\n re.escape('binary \"https://api.mapbox.com/downloads/v2/carthage/mapbox-common/MapboxCommon-ios.json\" == ') + '.+',\n f'binary \"https://api.mapbox.com/downloads/v2/carthage/mapbox-common/MapboxCommon-ios.json\" == {common_version}',\n cartfile_contents\n )\n return cartfile_contents\n\ndef change_readme(version, common_version):\n with open(README, 'r') as f:\n readme = f.read()\n readme = re.sub(\n r'\\.package\\(url: \"git@github\\.com:mapbox\\/mapbox-navigation-native-ios\\.git\", from: \".+\"\\),', \n f'.package(url: \"[email protected]:mapbox/mapbox-navigation-native-ios.git\", from: \"{version}\"),', \n readme)\n readme = change_cocoapods(readme, version=version)\n readme = change_carthage(readme, version=version, common_version=common_version)\n\n with open(README, 'w') as f:\n f.write(readme)\n\ndef change_package_swift(version, common_version, checksum):\n with open(PACKAGE_SWIFT, 'r') as f:\n package_swift = f.read()\n package_swift = re.sub(\n r'let version = \".+\"', \n f'let version = \"{version}\"', \n package_swift)\n package_swift = re.sub(\n r'let mapboxCommonVersion = Version\\(\".+\"\\)', \n f'let mapboxCommonVersion = Version(\"{common_version}\")', \n package_swift)\n package_swift = re.sub(\n r'let checksum = \".+\"', \n f'let checksum = \"{checksum}\"', \n package_swift)\n with open(PACKAGE_SWIFT, 'w') as f:\n f.write(package_swift)\n\ndef change_test_cartfile(version, common_version):\n with open(TEST_CARTFILE, 'r') as f:\n cartfile = f.read()\n cartfile = change_carthage(cartfile, version=version, common_version=common_version)\n\n with open(TEST_CARTFILE, 'w') as f:\n f.write(cartfile)\n\ndef change_test_podfile(version):\n with open(TEST_PODFILE, 'r') as f:\n podfile = f.read()\n podfile = change_cocoapods(podfile, version=version)\n\n with open(TEST_PODFILE, 'w') as f:\n f.write(podfile)\n\n\ndef change_test_spm_project(version, common_version):\n with open(TEST_SPM_PROJECT, 'r') as f:\n spm_project = f.read()\n spm_project = re.sub(\n r'MapboxNavigationNative:\\n.+from: .+', \n f'MapboxNavigationNative:\\n from: {version}', \n spm_project)\n spm_project = re.sub(\n r'MapboxCommon:\\n.+from: .+', \n f'MapboxCommon:\\n from: {common_version}', \n spm_project)\n\n with open(TEST_SPM_PROJECT, 'w') as f:\n f.write(spm_project)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--version', required=True)\n parser.add_argument('--common-version', required=True)\n parser.add_argument('--checksum', required=True)\n \n args = parser.parse_args()\n\n change_readme(args.version, args.common_version)\n change_package_swift(args.version, args.common_version, args.checksum)\n change_test_cartfile(args.version, args.common_version)\n change_test_podfile(args.version)\n change_test_spm_project(args.version, args.common_version)\n" } ]
6
lwqqq/UmiGo
https://github.com/lwqqq/UmiGo
fb0066a8509bc27c99ee36887ce6b36245dee4cf
03dbda60e7e982644421c32b7e77fe898b7d3224
9486b2418958055e468eacf6d39d903134d64185
refs/heads/main
2023-05-28T23:49:51.736408
2021-05-27T16:04:02
2021-05-27T16:04:02
328,365,488
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5071675777435303, "alphanum_fraction": 0.5724171996116638, "avg_line_length": 46.046512603759766, "blob_id": "69ea4bca445e9f093491fa6dbc214e5aa4148406", "content_id": "d123568e9fce064a599b891472931994b9e72615", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2033, "license_type": "no_license", "max_line_length": 148, "num_lines": 43, "path": "/data/download.py", "repo_name": "lwqqq/UmiGo", "src_encoding": "UTF-8", "text": "import requests\nfrom bs4 import BeautifulSoup\nimport re\n\nstartIndex = 94680\nendIndex = 94700\ndownloadPath = \"./sgf_record/\"\n\nbaseURL = 'http://www.go4go.net/go/games/record_request/'\ndownloadURL = 'http://www.go4go.net/sgf/__go4go_'\nbaseHeaders = {\"Cookie\": \"cookie-agreed-version=1.0.0; cookie-agreed=2; _ga=GA1.2.1891912329.1611233853; \"\n \"SESS44934a1e03ff8275732bdbfdcebdc556=c4G30SkeeJoTmu1zxicFHLh9DHb_XM-DcpmBhy32W98; has_js=1; \"\n \"_gid=GA1.2.598795055.1611366601; _gat=1\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"Accept\": \"*/*\",\n \"Accept-Encoding\": \"gzip, deflate, br\",\n \"Connection\": \"keep-alive\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4356.6 Safari/537.36\"\n }\n\n\nfor index in range(startIndex, endIndex + 1):\n print(\"正在尝试:\" + baseURL + str(index), end=\"\")\n response = requests.get(baseURL + str(index), headers=baseHeaders)\n if response.status_code != 200:\n print(\" FAILED\")\n continue\n htmlDoc = response.text\n soup = BeautifulSoup(htmlDoc, \"html.parser\")\n info = soup.find('textarea', 'form-textarea')\n if info is not None:\n dtInfo = re.search(r'(DT\\[)(.*)(])', info.text).group(2).replace('-', \"\")\n pbInfo = re.search(r'(PB\\[)(.*)(]B)', info.text).group(2).replace(\" \", \"-\")\n pwInfo = re.search(r'(PW\\[)(.*)(]W)', info.text).group(2).replace(\" \", \"-\")\n data = {\"op\": \"Download\", \"g\": index}\n response = requests.post(downloadURL + dtInfo + \"_\" + pbInfo + \"_\" + pwInfo + \".sgf\", data=data, headers=baseHeaders, timeout = 3000)\n if response.status_code != 200:\n print(\" FAILED\")\n continue\n open(downloadPath + \"_go4go_\" + dtInfo + \"_\" + pbInfo + \"_\" + pwInfo + \".sgf\", \"wb\").write(b\"(\" + response.content)\n print(\" OK\")\n else:\n print(\" FAILED\")\n" }, { "alpha_fraction": 0.5329403877258301, "alphanum_fraction": 0.545076310634613, "avg_line_length": 30.69230842590332, "blob_id": "f7749da98c854c7f645248c098432c10313f0615", "content_id": "5089f3c128a639307b70e37afaac10d4f6064695", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2884, "license_type": "no_license", "max_line_length": 82, "num_lines": 91, "path": "/sgf2train.py", "repo_name": "lwqqq/UmiGo", "src_encoding": "UTF-8", "text": "import os\nimport numpy as np\nfrom GoRule.gosgf import Sgf_game\nfrom GoRule.goboard import GameState, Move\nfrom GoRule.gotypes import Point\nfrom GoRule.utils import print_board\nfrom GoRule.encoder.oneplane import OnePlaneEncoder\nfrom GoRule.encoder.base import get_encoder_by_name\n\n\ndef get_sgf(path):\n return [os.path.join(path, f) for f in os.listdir(path) if f.endswith('.sgf')]\n\n\ndef encode(game_state):\n board_matrix = np.zeros((19, 19, 1))\n next_player = game_state.next_player\n for r in range(19):\n for c in range(19):\n p = Point(row=r + 1, col=c + 1)\n go_string = game_state.board.get_go_string(p)\n if go_string is None:\n continue\n if go_string.color == next_player:\n board_matrix[r, c, 0] = 1\n else:\n board_matrix[r, c, 0] = -1\n return board_matrix\n\n\ndef get_total_samples():\n total_sample = 0\n for index in sgf_path:\n f = open(index)\n sgf_content = f.read()\n f.close()\n sgf_game = Sgf_game.from_string(sgf_content)\n num_moves = 0\n first_move = False\n for item in sgf_game.main_sequence_iter():\n color, move_tuple = item.get_move()\n if color is not None and move_tuple is not None:\n if first_move:\n num_moves += 1\n else:\n first_move = True\n total_sample += num_moves\n return total_sample\n\n\ndef get_train():\n counter = 0\n for index in sgf_path:\n f = open(index)\n sgf_content = f.read()\n f.close()\n sgf_game = Sgf_game.from_string(sgf_content)\n game_state = GameState.new_game(19)\n\n first_move = False\n for item in sgf_game.main_sequence_iter():\n color, move_tuple = item.get_move()\n point = Point\n if color is not None:\n if move_tuple is not None:\n row, col = move_tuple\n point = Point(row + 1, col + 1)\n move = Move.play(point)\n else:\n move = Move.pass_turn()\n if first_move and point is not None:\n features[counter] = encode(game_state)\n labels[counter] = (point.row - 1) * 19 + (point.col - 1)\n counter += 1\n game_state = game_state.apply_move(move)\n first_move = True\n\n\nif __name__ == '__main__':\n sgf_path = get_sgf('./data/sgf_record')\n total_samples = get_total_samples()\n print(total_samples)\n features = np.zeros((total_samples, 19, 19, 1))\n labels = np.zeros((total_samples, 1))\n get_train()\n feature_file_base = './data/features'\n label_file_base = './data/labels'\n np.save(feature_file_base, features)\n np.save(label_file_base, labels)\n\n # print(features[1])\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.75, "avg_line_length": 20, "blob_id": "0ccaed5058f1b50b11e07b79d1e56989d4f8db52", "content_id": "e4350d83414d28cd519d7d0de0d0cc7a83f0ffd4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 20, "license_type": "no_license", "max_line_length": 20, "num_lines": 1, "path": "/GoRule/agent/__init__.py", "repo_name": "lwqqq/UmiGo", "src_encoding": "UTF-8", "text": "from .naive import *" }, { "alpha_fraction": 0.658707857131958, "alphanum_fraction": 0.6769663095474243, "avg_line_length": 28.625, "blob_id": "69cc783800439a334d4b8bf6c63a617015e170ea", "content_id": "a3f47f54120a15dba69de512e22cf4b75f73779a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 736, "license_type": "no_license", "max_line_length": 63, "num_lines": 24, "path": "/show_sgf.py", "repo_name": "lwqqq/UmiGo", "src_encoding": "UTF-8", "text": "from GoRule.gosgf import Sgf_game\nfrom GoRule.goboard import GameState, Move\nfrom GoRule.gotypes import Point\nfrom GoRule.utils import print_board\nimport time\n\n\nf = open(\"./data/sgf_record/20200316_Gao-Yun_Zhang-Kaixin.sgf\")\nsgf_content = f.read()\nf.close()\nsgf_game = Sgf_game.from_string(sgf_content)\n\ngame_state = GameState.new_game(19)\n\nfor item in sgf_game.main_sequence_iter():\n color, move_tuple = item.get_move()\n if color is not None and move_tuple is not None:\n row, col = move_tuple\n point = Point(row + 1, col + 1)\n move = Move.play(point)\n # 将读出的落子应用到棋盘上\n game_state = game_state.apply_move(move)\n time.sleep(1)\n print_board(game_state.board)\n\n" } ]
4
yutxie/text-classification-CS420-baselines
https://github.com/yutxie/text-classification-CS420-baselines
c209a8f7236f0d985326752b5fa24fb46ce544ba
949543399d4d94e4ba2e5c0b850be6ce1bf55cf5
470ac89df7967364ba5edb67edb02d02e0c4e51d
refs/heads/master
2020-04-26T17:03:22.624665
2019-03-28T05:14:10
2019-03-28T05:14:10
173,700,327
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6232166290283203, "alphanum_fraction": 0.6316472291946411, "avg_line_length": 31.82978630065918, "blob_id": "326a8950144bb7a4a89ef41ac07b7208d5e2a599", "content_id": "fff75ba3e1ab801eac96bef9528a73a0418d0eb2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1542, "license_type": "no_license", "max_line_length": 85, "num_lines": 47, "path": "/utils.py", "repo_name": "yutxie/text-classification-CS420-baselines", "src_encoding": "UTF-8", "text": "import os\nimport codecs\nimport logging as log\n\nfrom collections import defaultdict\n\nimport jieba\nimport torch\n\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\n\ndef sent_tokenize(sent, se=False):\n SOS_TOK, EOS_TOK = '<SOS>', '<EOS>'\n if isinstance(sent, str):\n # sent = jieba.lcut(sent)\n sent = [sent[i] for i in range(len(sent))]\n elif isinstance(sent, list):\n assert isinstance(sent[0], str), \"Invalid sentence found!\"\n if se: sent = [SOS_TOK] + sent + [EOS_TOK]\n return sent\n\ndef calc_tfidf_matrix(corpus, max_features, stop_words='english'):\n corpus = [' '.join(sent) for sent in corpus]\n vectorizer = CountVectorizer(\n # max_df= .999,\n # min_df = .001,\n max_features=max_features\n )\n transformer = TfidfTransformer()\n tfidf = transformer.fit_transform(\n vectorizer.fit_transform(corpus)\n )\n word_list = vectorizer.get_feature_names()\n log.info(\"Finished building a word list of size %i\" % len(word_list))\n return tfidf, word_list\n\ndef load_word_vector(data_dir, d_feature):\n word2idx = {}\n vectors = []\n with open(os.path.join(data_dir, 'sgns.weibo.word'), 'r', encoding='utf-8') as f:\n vocab_size, dim = map(int, f.readline().strip().split(' '))\n assert dim == d_feature\n for idx in range(vocab_size):\n line = f.readline().strip().split(' ')\n word2idx[line[0]] = idx\n vectors.append(torch.tensor(list(map(float, line[1:]))))\n return word2idx, vectors" }, { "alpha_fraction": 0.5516537427902222, "alphanum_fraction": 0.5549203753471375, "avg_line_length": 31.236841201782227, "blob_id": "db30d465faedcfa3dd95355c75be87de03b67c8e", "content_id": "fd5379fb670e22d44474951fd720effbed425d0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2449, "license_type": "no_license", "max_line_length": 106, "num_lines": 76, "path": "/train.py", "repo_name": "yutxie/text-classification-CS420-baselines", "src_encoding": "UTF-8", "text": "import os\nimport itertools\nimport logging as log\n\nimport torch\nimport torch.nn.functional as F\n\nfrom torchtext.data import Iterator, BucketIterator\nfrom torch.utils.data import DataLoader\nfrom tensorboardX import SummaryWriter\n\nfrom metrics import Metrics\nfrom evaluate import evaluate\n\n\ndef train(args, model, task):\n\n metrics = Metrics()\n writer = None #SummaryWriter(os.path.join(args.run_dir, 'tensorboard'))\n optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=args.lr)\n log.info('Start to train')\n\n n_passes = 0\n epoch = 0\n for epoch in range(args.n_epochs):\n # while True:\n data_iter = Iterator(\n # data_loader = DataLoader(\n task.train_set,\n args.batch_size,\n # collate_fn=task.collate_fn,\n device=args.device,\n shuffle=True,\n )\n\n for batch in data_iter:\n # for batch in data_loader:\n texts, targs = batch.text, batch.targ\n inputs = texts if args.model != 'MLP' else None\n # texts, targs = batch\n # inputs, targs = batch\n # targs = targs.to(args.device)\n\n model.train()\n optimizer.zero_grad()\n if args.model == 'Seq2Seq':\n _, _, loss = model(inputs)\n else:\n preds = model(inputs)\n loss = F.cross_entropy(preds, targs)\n metrics.count(preds, targs)\n loss.backward()\n optimizer.step()\n\n n_passes += 1\n\n # log train\n if n_passes % args.log_every == 0:\n # report = metrics.report(reset=True)\n # report += [('loss', loss.item())]\n # writer.add_scalars('train', dict(report), n_passes)\n # log.info('Pass #%i train: %s' % (n_passes, str(report)))\n log.info('Epoch #%i Pass #%i train: %f' % (epoch, n_passes, loss.item()))\n\n # save model\n # if n_passes % args.save_every == 0:\n # torch.save(model.state_dict(), os.path.join(args.run_dir, 'params_%i.model' % n_passes))\n\n # evaluate\n if n_passes % args.eval_every == 0:\n evaluate(args, model, task, tensorboard_writer=writer, n_passes=n_passes)\n\n epoch += 1\n\n torch.save(model.state_dict(), os.path.join(args.run_dir, 'params_%i.model' % epoch))\n log.info('Finished training')" }, { "alpha_fraction": 0.5651392340660095, "alphanum_fraction": 0.5696316361427307, "avg_line_length": 26.850000381469727, "blob_id": "6fcf7a57101ac504b9be5a91c9bd2b05a1f25191", "content_id": "bd905d6d559cd025843b3a0e6b919ecf4fdf2f24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1113, "license_type": "no_license", "max_line_length": 78, "num_lines": 40, "path": "/seq2vec.py", "repo_name": "yutxie/text-classification-CS420-baselines", "src_encoding": "UTF-8", "text": "import os\nimport pickle\nimport itertools\nimport logging as log\n\nimport torch\nimport torch.nn.functional as F\n\nfrom torchtext.data import Iterator\nfrom torch.utils.data import DataLoader\n\n\ndef seq2vec(args, model, task):\n log.info('Starting to computing features')\n model.eval()\n\n for split in ['train', 'test']:\n dataset = task.train_set if split == 'train' else task.test_set\n data_iter = Iterator(\n dataset,\n args.batch_size,\n device=args.device,\n shuffle=False\n )\n\n feats_list = []\n for batch in data_iter:\n inputs, targs = batch.text, batch.targ\n if args.model == 'Seq2Seq':\n feats, _, _ = model(inputs)\n feats = feats[-1]\n else:\n feats = model.seq2vec(inputs)\n feats_list.append(feats)\n feats = torch.cat(feats_list, dim=0)\n feats = feats.detach().cpu().numpy()\n print('feats shape', feats.shape)\n\n with open(os.path.join(args.data_dir, 'feats_%s' % split), 'wb') as f:\n pickle.dump(feats, f)" }, { "alpha_fraction": 0.5713049173355103, "alphanum_fraction": 0.581584095954895, "avg_line_length": 43.22488021850586, "blob_id": "f2ed93cac0632216066c66b305574079d19cc8e5", "content_id": "ca6e1bd31d6a28dab1201057b767b3d1c4266e51", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9242, "license_type": "no_license", "max_line_length": 113, "num_lines": 209, "path": "/metrics.py", "repo_name": "yutxie/text-classification-CS420-baselines", "src_encoding": "UTF-8", "text": "import torch\n\n\nclass CategoricalAccuracy():\n \"\"\"\n https://github.com/allenai/allennlp/blob/master/allennlp/training/metrics/categorical_accuracy.py#L11-L103\n Categorical Top-K accuracy. Assumes integer labels, with\n each item to be classified having a single correct class.\n Tie break enables equal distribution of scores among the\n classes with same maximum predsicted scores.\n \"\"\"\n def __init__(self, top_k: int = 1, tie_break: bool = False) -> None:\n if top_k > 1 and tie_break:\n raise ValueError(\"Tie break in Categorical Accuracy \"\n \"can be done only for maximum (top_k = 1)\")\n if top_k <= 0:\n raise ValueError(\"top_k passed to Categorical Accuracy must be > 0\")\n self._top_k = top_k\n self._tie_break = tie_break\n self.correct_count = 0.\n self.total_count = 0.\n\n def __call__(self,\n predsictions: torch.Tensor,\n gold_labels: torch.Tensor,\n # mask: Optional[torch.Tensor] = None):\n mask=None):\n \"\"\"\n Parameters\n ----------\n predsictions : ``torch.Tensor``, required.\n A tensor of predsictions of shape (batch_size, ..., num_classes).\n gold_labels : ``torch.Tensor``, required.\n A tensor of integer class label of shape (batch_size, ...). It must be the same\n shape as the ``predsictions`` tensor without the ``num_classes`` dimension.\n mask: ``torch.Tensor``, optional (default = None).\n A masking tensor the same size as ``gold_labels``.\n \"\"\"\n # predsictions, gold_labels, mask = self.unwrap_to_tensors(predsictions, gold_labels, mask)\n\n # Some sanity checks.\n num_classes = predsictions.size(-1)\n if gold_labels.dim() != predsictions.dim() - 1:\n raise ValueError(\"gold_labels must have dimension == predsictions.size() - 1 but \"\n \"found tensor of shape: {}\".format(predsictions.size()))\n if (gold_labels >= num_classes).any():\n raise ValueError(\"A gold label passed to Categorical Accuracy contains an id >= {}, \"\n \"the number of classes.\".format(num_classes))\n\n predsictions = predsictions.view((-1, num_classes))\n gold_labels = gold_labels.view(-1).long()\n if not self._tie_break:\n # Top K indexes of the predsictions (or fewer, if there aren't K of them).\n # Special case topk == 1, because it's common and .max() is much faster than .topk().\n if self._top_k == 1:\n top_k = predsictions.max(-1)[1].unsqueeze(-1)\n else:\n top_k = predsictions.topk(min(self._top_k, predsictions.shape[-1]), -1)[1]\n\n # This is of shape (batch_size, ..., top_k).\n correct = top_k.eq(gold_labels.unsqueeze(-1)).float()\n else:\n # predsiction is correct if gold label falls on any of the max scores. distribute score by tie_counts\n max_predsictions = predsictions.max(-1)[0]\n max_predsictions_mask = predsictions.eq(max_predsictions.unsqueeze(-1))\n # max_predsictions_mask is (rows X num_classes) and gold_labels is (batch_size)\n # ith entry in gold_labels points to index (0-num_classes) for ith row in max_predsictions\n # For each row check if index pointed by gold_label is was 1 or not (among max scored classes)\n correct = max_predsictions_mask[torch.arange(gold_labels.numel()).long(), gold_labels].float()\n tie_counts = max_predsictions_mask.sum(-1)\n correct /= tie_counts.float()\n correct.unsqueeze_(-1)\n\n if mask is not None:\n correct *= mask.view(-1, 1).float()\n self.total_count += mask.sum()\n else:\n self.total_count += gold_labels.numel()\n self.correct_count += correct.sum()\n\n def get_metric(self, reset: bool = False):\n \"\"\"\n Returns\n -------\n The accumulated accuracy.\n \"\"\"\n if self.total_count > 1e-12:\n accuracy = float(self.correct_count) / float(self.total_count)\n else:\n accuracy = 0.0\n if reset:\n self.reset()\n return accuracy\n\n def reset(self):\n self.correct_count = 0.0\n self.total_count = 0.0\n\n\nclass F1Measure():\n \"\"\"\n https://github.com/allenai/allennlp/blob/master/allennlp/training/metrics/f1_measure.py#L10-L94\n Computes Precision, Recall and F1 with respect to a given ``positive_label``.\n For example, for a BIO tagging scheme, you would pass the classification index of\n the tag you are interested in, resulting in the Precision, Recall and F1 score being\n calculated for this tag only.\n \"\"\"\n def __init__(self, positive_label: int = 1) -> None:\n self._positive_label = positive_label\n self._true_positives = 0.0\n self._true_negatives = 0.0\n self._false_positives = 0.0\n self._false_negatives = 0.0\n\n def __call__(self,\n predsictions: torch.Tensor,\n gold_labels: torch.Tensor,\n # mask: Optional[torch.Tensor] = None):\n mask=None):\n \"\"\"\n Parameters\n ----------\n predsictions : ``torch.Tensor``, required.\n A tensor of predsictions of shape (batch_size, ..., num_classes).\n gold_labels : ``torch.Tensor``, required.\n A tensor of integer class label of shape (batch_size, ...). It must be the same\n shape as the ``predsictions`` tensor without the ``num_classes`` dimension.\n mask: ``torch.Tensor``, optional (default = None).\n A masking tensor the same size as ``gold_labels``.\n \"\"\"\n # predsictions, gold_labels, mask = self.unwrap_to_tensors(predsictions, gold_labels, mask)\n\n num_classes = predsictions.size(-1)\n if (gold_labels >= num_classes).any():\n raise ValueError(\"A gold label passed to F1Measure contains an id >= {}, \"\n \"the number of classes.\".format(num_classes))\n if mask is None:\n mask = torch.ones_like(gold_labels)\n mask = mask.float()\n gold_labels = gold_labels.float()\n positive_label_mask = gold_labels.eq(self._positive_label).float()\n negative_label_mask = 1.0 - positive_label_mask\n\n argmax_predsictions = predsictions.max(-1)[1].float().squeeze(-1)\n\n # True Negatives: correct non-positive predsictions.\n correct_null_predsictions = (argmax_predsictions !=\n self._positive_label).float() * negative_label_mask\n self._true_negatives += (correct_null_predsictions.float() * mask).sum()\n\n # True Positives: correct positively labeled predsictions.\n correct_non_null_predsictions = (argmax_predsictions ==\n self._positive_label).float() * positive_label_mask\n self._true_positives += (correct_non_null_predsictions * mask).sum()\n\n # False Negatives: incorrect negatively labeled predsictions.\n incorrect_null_predsictions = (argmax_predsictions !=\n self._positive_label).float() * positive_label_mask\n self._false_negatives += (incorrect_null_predsictions * mask).sum()\n\n # False Positives: incorrect positively labeled predsictions\n incorrect_non_null_predsictions = (argmax_predsictions ==\n self._positive_label).float() * negative_label_mask\n self._false_positives += (incorrect_non_null_predsictions * mask).sum()\n\n def get_metric(self, reset: bool = False):\n \"\"\"\n Returns\n -------\n A tuple of the following metrics based on the accumulated count statistics:\n precision : float\n recall : float\n f1-measure : float\n \"\"\"\n precision = float(self._true_positives) / float(self._true_positives + self._false_positives + 1e-13)\n recall = float(self._true_positives) / float(self._true_positives + self._false_negatives + 1e-13)\n f1_measure = 2. * ((precision * recall) / (precision + recall + 1e-13))\n if reset:\n self.reset()\n return precision, recall, f1_measure\n\n def reset(self):\n self._true_positives = 0.0\n self._true_negatives = 0.0\n self._false_positives = 0.0\n self._false_negatives = 0.0\n\n\nclass Metrics():\n\n def __init__(self):\n self.metrics = [CategoricalAccuracy(), F1Measure()]\n\n def count(self, preds, targs):\n for metric in self.metrics:\n metric(preds, targs)\n\n def report(self, reset=False):\n report = []\n for metric in self.metrics:\n _ = metric.get_metric(reset=False)\n if isinstance(metric, CategoricalAccuracy): report.append(('acc', _))\n elif isinstance(metric, F1Measure): report += [('rec', _[0]), ('pre', _[1]), ('f1', _[2])]\n else: raise NotImplementedError\n return report\n\n def reset(self):\n for metric in self.metrics:\n metric.reset()" }, { "alpha_fraction": 0.6038803458213806, "alphanum_fraction": 0.6103476285934448, "avg_line_length": 26.511110305786133, "blob_id": "6ee3b39bb99f1ac174c82065f53ee9c8835ef9b2", "content_id": "931368984b22fe68c8dc9b15d6467f28cbec455c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1237, "license_type": "no_license", "max_line_length": 76, "num_lines": 45, "path": "/evaluate.py", "repo_name": "yutxie/text-classification-CS420-baselines", "src_encoding": "UTF-8", "text": "import logging as log\n\nimport torch\n\nfrom torchtext.data import Iterator, BucketIterator\nfrom torch.utils.data import DataLoader\n\nfrom metrics import Metrics\n\n\ndef evaluate(args, model, task, tensorboard_writer=None, n_passes=-1):\n model.eval()\n\n metrics = Metrics()\n data_iter = Iterator(\n # data_loader = DataLoader(\n task.test_set,\n args.batch_size,\n # collate_fn=task.collate_fn,\n device=args.device,\n shuffle=False\n )\n\n preds_list = []\n for batch in data_iter:\n # for batch in data_loader:\n inputs, targs = batch.text, batch.targ\n # inputs, targs = batch\n # targs = targs.to(args.device)\n if args.model == 'Seq2Seq':\n hidden, pred, loss = model(inputs)\n else:\n preds = model(inputs)\n preds_list.append(preds)\n metrics.count(preds, targs)\n\n print(inputs[0:10], '\\n', pred[0:10])\n\n # report = metrics.report(reset=True)\n # log.info('Pass #%i evaluate: %s' % (n_passes, str(report)))\n log.info('Pass #%i evaluate: %f' % (n_passes, loss.item()))\n # if tensorboard_writer is not None:\n # tensorboard_writer.add_scalars('evaluate', dict(report), n_passes)\n\n return preds_list" }, { "alpha_fraction": 0.5120835900306702, "alphanum_fraction": 0.5186153054237366, "avg_line_length": 25.413793563842773, "blob_id": "c196f84ace15c80b61e01708530596d8273b78ed", "content_id": "ea6c1ddfa8ed40c22b8a474a6efe97663d7a1a94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1531, "license_type": "no_license", "max_line_length": 63, "num_lines": 58, "path": "/models/trans.py", "repo_name": "yutxie/text-classification-CS420-baselines", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.autograd as autograd\n\nimport logging as log\n\nfrom .modules import TransformerEncoder\n\nclass Transformer(nn.Module):\n\n def __init__(self, args, task):\n super().__init__()\n self.vocab = task.vocab\n\n self.embedding = nn.Embedding(\n len(self.vocab),\n args.d_feature,\n # _weight=self.vocab.vectors\n )\n self.trans = TransformerEncoder(\n dimension=args.d_feature,\n n_heads=4,\n hidden=args.d_hidden,\n num_layers=args.n_layers,\n dropout=args.dropout\n )\n self.output = nn.Linear(\n args.d_hidden * (args.n_layers + 1),\n task.n_classes\n )\n\n self.device = args.device\n self.to(self.device)\n\n def forward(self, x):\n '''\n inputs:\n x: batch_size x seq_len\n task_idx: int\n '''\n x = x.to(self.device)\n batch_size = x.shape[0]\n x = self.embedding(x)\n x = self.trans(x)\n x = [x[i][:,-1,:] for i in range(len(x))]\n x = torch.cat(x, dim=1)\n x = self.output(x) # batch_size x n_classes\n return torch.softmax(x, dim=1) # batch_size x n_classes\n\n def seq2vec(self, x):\n x = x.to(self.device)\n batch_size = x.shape[0]\n x = self.embedding(x)\n x = self.trans(x)\n x = [x[i][:,-1,:] for i in range(len(x))]\n x = torch.cat(x, dim=1)\n return x" }, { "alpha_fraction": 0.6203007698059082, "alphanum_fraction": 0.6842105388641357, "avg_line_length": 16.799999237060547, "blob_id": "1326c33463f1b0ef876473cb6ad3253127c1b4ee", "content_id": "300364544c13bb65f3327c0227d94a9b4a497def", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 266, "license_type": "no_license", "max_line_length": 96, "num_lines": 15, "path": "/README.md", "repo_name": "yutxie/text-classification-CS420-baselines", "src_encoding": "UTF-8", "text": "# text-classification-meituan\nCourse project for CS420\n\n\n## Usage\n\nMLP, tfidf feature\n```\npython main.py --model MLP --d_feature 10000 --d_hidden 500 --n_layers 2 --device 1 --n_epochs 2\n```\n\nBiLSTM, word vector\n```\npython main.py --model BiLSTM --d_feature 300 \n```" }, { "alpha_fraction": 0.5366346836090088, "alphanum_fraction": 0.5386558771133423, "avg_line_length": 34.98181915283203, "blob_id": "c065d2b6e7e9972eaa4cfae5290ece713f874bfc", "content_id": "166c9e5c4b77ba940d87cbb12953ca027fa0993a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3958, "license_type": "no_license", "max_line_length": 99, "num_lines": 110, "path": "/dataset.py", "repo_name": "yutxie/text-classification-CS420-baselines", "src_encoding": "UTF-8", "text": "import os\nimport itertools\nimport logging as log\n\nimport torch\nimport torch.utils.data as data\n\nfrom torchtext import data, datasets\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nfrom utils import sent_tokenize, calc_tfidf_matrix, load_word_vector\n\n\nclass SeqTask():\n\n def __init__(self, args):\n self.n_classes = 2\n\n text_field = data.Field(\n sequential=True,\n init_token='<SOS>',\n eos_token='<EOS>',\n lower=True,\n tokenize=sent_tokenize,\n pad_first=False,\n batch_first=True\n )\n targ_field = data.Field(\n sequential=False,\n use_vocab=False,\n is_target=True\n )\n\n self.train_set = data.TabularDataset(\n path=os.path.join(args.data_dir, 'train_shuffle.txt'),\n format='tsv',\n fields=[('targ', targ_field), ('text', text_field)])\n self.test_set = data.TabularDataset(\n path=os.path.join(args.data_dir, 'test_shuffle.txt'),\n format='tsv',\n fields=[('targ', targ_field), ('text', text_field)])\n text_field.build_vocab(self.train_set)\n self.vocab = text_field.vocab\n log.info('Finished building a vocab of size %i' % len(self.vocab))\n\n word2idx, vectors = load_word_vector(args.data_dir, args.d_feature)\n self.vocab.set_vectors(word2idx, vectors, dim=args.d_feature)\n\nclass NonSeqTask():\n\n def __init__(self, args):\n self.n_classes = 2\n\n # load data\n corpus = []\n # with open(os.path.join(args.data_dir, 'stop_words.txt'), 'r') as f:\n # stop_words = f.readlines()\n # stop_words = [line.strip() for line in stop_words]\n # stop_words = []\n for split in ['train', 'test']:\n file_name = split + '_shuffle.txt'\n with open(os.path.join(args.data_dir, file_name), 'r') as f:\n lines = f.readlines() # targ \\t text\n lines = [line.strip().split('\\t') for line in lines] # [[targ, text], ...]\n print('Finished loading file %s' % file_name)\n texts = [sent_tokenize(text) for targ, text in lines] # [[word0, word1], ...]\n # texts = [[word for word in sent if word not in stop_words] for sent in texts]\n targs = [int(targ) for targ, text in lines] # [targs]\n exec(split + '_texts = texts')\n exec(split + '_targs = targs')\n corpus += texts\n\n class Dataset(data.Dataset):\n def __init__(self, inputs, targs):\n self.inputs = inputs\n self.targs = targs\n\n def __len__(self):\n return self.inputs.shape[0]\n\n def __getitem__(self, index):\n if self.targs is None: return self.inputs[index], None\n else: return self.inputs[index], self.targs[index]\n\n # form dataset\n tfidf, word_list = calc_tfidf_matrix(corpus, args.d_feature, stop_words=None)\n args.d_feature = len(word_list)\n for split in ['train', 'test']:\n texts = eval(split + '_texts')\n targs = eval(split + '_targs')\n split_size = len(texts)\n inputs = tfidf[:split_size]\n tfidf = tfidf[split_size:]\n setattr(self, split + '_set', Dataset(inputs, targs))\n log.info('Finished building datasets')\n\n print(len(self.train_set), len(self.test_set))\n\n def collate_fn(self, batch):\n inputs, targs = [], []\n for x, y in batch:\n x = torch.tensor(x.toarray(), dtype=torch.float)\n if y is not None: y = torch.tensor(y, dtype=torch.long)\n inputs.append(x)\n targs.append(y)\n\n inputs = torch.cat(inputs)\n if targs[0] is not None: targs = torch.stack(targs)\n else: targs = None\n return inputs, targs\n" }, { "alpha_fraction": 0.5395577549934387, "alphanum_fraction": 0.5464373230934143, "avg_line_length": 29.83333396911621, "blob_id": "25811245d86d479749a0cc60fa3d6f289db47e0f", "content_id": "88d5c963aae13d1233617367b62f0e5ae47d3d53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2035, "license_type": "no_license", "max_line_length": 98, "num_lines": 66, "path": "/models/seq2seq.py", "repo_name": "yutxie/text-classification-CS420-baselines", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.autograd as autograd\n\nimport logging as log\n\nclass Seq2Seq(nn.Module):\n\n def __init__(self, args, task):\n super().__init__()\n self.vocab = task.vocab\n self.vocab_size = len(self.vocab)\n self.d_feature = args.d_feature\n\n self.embedding = nn.Embedding(\n self.vocab_size,\n args.d_feature,\n _weight=self.vocab.vectors\n )\n self.encoder = nn.GRU(\n args.d_feature,\n args.d_hidden,\n args.n_layers,\n batch_first=True,\n bidirectional=False\n )\n self.decoder = nn.GRU(\n args.d_feature,\n args.d_hidden,\n args.n_layers,\n batch_first=True,\n bidirectional=False\n )\n self.output2word = nn.Linear(\n args.d_hidden,\n self.vocab_size\n )\n\n self.device = args.device\n self.to(self.device)\n\n def forward(self, sents):\n '''\n Parameters\n ------------------\n sents: batch_size x seq_len\n '''\n sents = sents.to(self.device)\n batch_size = sents.shape[0]\n seq_len = sents.shape[1]\n \n # encoding\n embeded = self.embedding(sents) # batch_size x seq_len x d_feature\n _, hidden = self.encoder(embeded) # n_directions * n_layers x batch_size x d_hidden\n\n # decoding\n # embeded = self.embedding(sents[:,:-1])\n embeded = torch.zeros(batch_size, seq_len - 1, self.d_feature).to(self.device)\n output, _ = self.decoder(embeded, hidden) # batch_size x seq_len x n_directions * d_hidden\n pred = self.output2word(output) # batch_size x seq_len x vocab_size\n pred = F.softmax(pred, dim=-1).view(-1, self.vocab_size)\n loss = F.cross_entropy(pred, sents[:,1:].contiguous().view(-1), ignore_index=1)\n pred = pred.argmax(dim=-1).view(batch_size, -1)\n\n return hidden, pred, loss\n" }, { "alpha_fraction": 0.5836016535758972, "alphanum_fraction": 0.5908993482589722, "avg_line_length": 31.80281639099121, "blob_id": "61d5a9939a57b3c592ddc73c80af8317b1a8a4a2", "content_id": "6346c0c161438c5ad532cbaa14c87e78904dddf9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4659, "license_type": "no_license", "max_line_length": 102, "num_lines": 142, "path": "/models/modules.py", "repo_name": "yutxie/text-classification-CS420-baselines", "src_encoding": "UTF-8", "text": "import os\nimport math\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.init as init\nimport torch.nn.functional as F\n\n\nclass Linear(nn.Linear):\n\n def forward(self, x):\n size = x.size()\n return super().forward(\n x.contiguous().view(-1, size[-1])).view(*size[:-1], -1)\n\nclass Feedforward(nn.Module):\n\n def __init__(self, d_in, d_out, activation=None, bias=True, dropout=0.2):\n super().__init__()\n if activation is not None:\n self.activation = getattr(torch, activation)\n else:\n self.activation = lambda x: x\n self.linear = Linear(d_in, d_out, bias=bias)\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, x):\n return self.activation(self.linear(self.dropout(x)))\n\n# torch.matmul can't do (4, 3, 2) @ (4, 2) -> (4, 3)\ndef matmul(x, y):\n if x.dim() == y.dim():\n return x @ y\n if x.dim() == y.dim() - 1:\n return (x.unsqueeze(-2) @ y).squeeze(-2)\n return (x @ y.unsqueeze(-2)).squeeze(-2)\n\nclass Attention(nn.Module):\n\n def __init__(self, d_key, dropout_ratio, causal):\n super().__init__()\n self.scale = math.sqrt(d_key)\n self.dropout = nn.Dropout(dropout_ratio)\n self.causal = causal\n\n def forward(self, query, key, value, padding=None):\n dot_products = matmul(query, key.transpose(1, 2))\n if query.dim() == 3 and self.causal:\n tri = key.new_ones((key.size(1), key.size(1))).triu(1) * INF\n dot_products.sub_(tri.unsqueeze(0))\n if not padding is None:\n dot_products.masked_fill_(padding.unsqueeze(1).expand_as(dot_products), -INF)\n return matmul(self.dropout(F.softmax(dot_products / self.scale, dim=-1)), value)\n\n\nclass MultiHead(nn.Module):\n\n def __init__(self, d_key, d_value, n_heads, dropout_ratio, causal=False):\n super().__init__()\n self.attention = Attention(d_key, dropout_ratio, causal=causal)\n self.wq = Linear(d_key, d_key, bias=False)\n self.wk = Linear(d_key, d_key, bias=False)\n self.wv = Linear(d_value, d_value, bias=False)\n self.n_heads = n_heads\n\n def forward(self, query, key, value, padding=None):\n query, key, value = self.wq(query), self.wk(key), self.wv(value)\n query, key, value = (\n x.chunk(self.n_heads, -1) for x in (query, key, value))\n return torch.cat([self.attention(q, k, v, padding=padding)\n for q, k, v in zip(query, key, value)], -1)\n\nclass LinearReLU(nn.Module):\n\n def __init__(self, d_model, d_hidden):\n super().__init__()\n self.feedforward = Feedforward(d_model, d_hidden, activation='relu')\n self.linear = Linear(d_hidden, d_model)\n\n def forward(self, x, padding=None):\n return self.linear(self.feedforward(x))\n\n\nclass LayerNorm(nn.Module):\n\n def __init__(self, d_model, eps=1e-6):\n super().__init__()\n self.gamma = nn.Parameter(torch.ones(d_model))\n self.beta = nn.Parameter(torch.zeros(d_model))\n self.eps = eps\n\n def forward(self, x):\n mean = x.mean(-1, keepdim=True)\n std = x.std(-1, keepdim=True)\n return self.gamma * (x - mean) / (std + self.eps) + self.beta\n\n\nclass ResidualBlock(nn.Module):\n\n def __init__(self, layer, d_model, dropout_ratio):\n super().__init__()\n self.layer = layer\n self.dropout = nn.Dropout(dropout_ratio)\n self.layernorm = LayerNorm(d_model)\n\n def forward(self, *x, padding=None):\n return self.layernorm(x[0] + self.dropout(self.layer(*x, padding=padding)))\n\n\nclass TransformerEncoderLayer(nn.Module):\n\n def __init__(self, dimension, n_heads, hidden, dropout):\n super().__init__()\n self.selfattn = ResidualBlock(\n MultiHead(\n dimension, dimension, n_heads, dropout),\n dimension, dropout)\n self.feedforward = ResidualBlock(\n LinearReLU(dimension, hidden),\n dimension, dropout)\n\n def forward(self, x, padding=None):\n return self.feedforward(self.selfattn(x, x, x, padding=padding))\n\n\nclass TransformerEncoder(nn.Module):\n\n def __init__(self, dimension, n_heads, hidden, num_layers, dropout):\n super().__init__()\n self.layers = nn.ModuleList(\n [TransformerEncoderLayer(dimension, n_heads, hidden, dropout) for i in range(num_layers)])\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, x, padding=None):\n x = self.dropout(x)\n encoding = [x]\n for layer in self.layers:\n x = layer(x, padding=padding)\n encoding.append(x)\n return encoding\n\n" }, { "alpha_fraction": 0.560093343257904, "alphanum_fraction": 0.560093343257904, "avg_line_length": 30.77777862548828, "blob_id": "4954855eef54be7957406d667a8c838bbd3002a3", "content_id": "e8812b764514673d5364f54a2461f094535e3779", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 857, "license_type": "no_license", "max_line_length": 107, "num_lines": 27, "path": "/models/mlp.py", "repo_name": "yutxie/text-classification-CS420-baselines", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass MLP(nn.Module):\n\n def __init__(self, args, task):\n super().__init__()\n\n self.linears = nn.Sequential(\n nn.Linear(args.d_feature, args.d_hidden), nn.ReLU(), nn.Dropout(p=args.dropout), # input\n *[nn.Sequential(\n nn.Linear(args.d_hidden, args.d_hidden), nn.ReLU(), nn.Dropout(p=args.dropout) # hiddens\n ) for _ in range(args.n_layers)]\n )\n self.output = nn.Linear(args.d_hidden, task.n_classes)\n\n self.device = args.device\n self.to(self.device)\n\n def forward(self, x):\n x = x.to(self.device)\n\n x = self.linears(x) # batch_size x d_hidden\n x = self.output(x) # batch_size x n_classes\n return F.sigmoid(x) # batch_size x n_classes" }, { "alpha_fraction": 0.8037382960319519, "alphanum_fraction": 0.822429895401001, "avg_line_length": 26, "blob_id": "b75722be83a2db094b23e26aa75636428d0fd837", "content_id": "81f8115e605d3861d8f35dfb5dddabbde43d7e4c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 107, "license_type": "no_license", "max_line_length": 30, "num_lines": 4, "path": "/models/__init__.py", "repo_name": "yutxie/text-classification-CS420-baselines", "src_encoding": "UTF-8", "text": "from .mlp import MLP\nfrom .bilstm import BiLSTM\nfrom .seq2seq import Seq2Seq\nfrom .trans import Transformer" }, { "alpha_fraction": 0.5199005007743835, "alphanum_fraction": 0.5292288661003113, "avg_line_length": 28.796297073364258, "blob_id": "0c00a5607ff7e7005801183d82006ecd94d0b1f8", "content_id": "c56a50b7958b0809f90e0b7c40019a1b7db53d2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1608, "license_type": "no_license", "max_line_length": 106, "num_lines": 54, "path": "/models/bilstm.py", "repo_name": "yutxie/text-classification-CS420-baselines", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.autograd as autograd\n\nimport logging as log\n\nclass BiLSTM(nn.Module):\n\n def __init__(self, args, task):\n super().__init__()\n self.vocab = task.vocab\n\n self.embedding = nn.Embedding(\n len(self.vocab),\n args.d_feature,\n _weight=self.vocab.vectors\n )\n self.bilstm = nn.LSTM(\n args.d_feature,\n args.d_hidden,\n args.n_layers,\n batch_first=True,\n bidirectional=True\n )\n self.output = nn.Linear(\n args.d_hidden * args.n_layers * 2,\n task.n_classes\n )\n\n self.device = args.device\n self.to(self.device)\n\n def forward(self, x):\n '''\n inputs:\n x: batch_size x seq_len\n task_idx: int\n '''\n x = x.to(self.device)\n batch_size = x.shape[0]\n x = self.embedding(x)\n x, (h_n, c_n) = self.bilstm(x) # n_layers * 2 x batch_size x d_hidden\n h_n = h_n.transpose(0, 1).contiguous().view(batch_size, -1) # batch_size x d_hidden * n_layers * 2\n x = self.output(h_n) # batch_size x n_classes\n return torch.softmax(x, dim=1) # batch_size x n_classes\n\n def seq2vec(self, x):\n x = x.to(self.device)\n batch_size = x.shape[0]\n x = self.embedding(x)\n x, (h_n, c_n) = self.bilstm(x) # n_layers * 2 x batch_size x d_hidden\n h_n = h_n.transpose(0, 1).contiguous().view(batch_size, -1) # batch_size x d_hidden * n_layers * 2\n return h_n" }, { "alpha_fraction": 0.6168539524078369, "alphanum_fraction": 0.6303370594978333, "avg_line_length": 32.81012725830078, "blob_id": "2b8233e04f78440e3fd4bcad75ad038b10a69726", "content_id": "24d6a80d7015d799fb85a592a083feed2096517e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2670, "license_type": "no_license", "max_line_length": 110, "num_lines": 79, "path": "/main.py", "repo_name": "yutxie/text-classification-CS420-baselines", "src_encoding": "UTF-8", "text": "import os\nimport time\nimport argparse\nimport logging as log\n\nimport torch\n\nimport models\nimport dataset\n\nfrom train import train\nfrom evaluate import evaluate\nfrom seq2vec import seq2vec\n\nparser = argparse.ArgumentParser(description='Text Classification')\n\n# environment\nparser.add_argument('--device', type=int, default=3, help='gpu device id, -1 if cpu')\n# log\nparser.add_argument('--log_every', type=int, default=200, help='log train how many every passes')\nparser.add_argument('--eval_every', type=int, default=2000, help='evaluate how many every passes')\n# parser.add_argument('--save_every', type=int, default=1000, help='save model how many every passes')\n# train\nparser.add_argument('--n_epochs', type=int, default=1000, help='how many epochs')\nparser.add_argument('--batch_size', type=int, default=32, help='how many instances in a batch')\nparser.add_argument('--lr', type=float, default=1e-4, help='learning rate')\n# data\nparser.add_argument('--data_dir', type=str, default='data/')\nparser.add_argument('--run_dir', type=str, default='run/')\n# model\nparser.add_argument('--model', type=str, default='Seq2Seq')\nparser.add_argument('--d_feature', type=int, default=300)\nparser.add_argument('--d_hidden', type=int, default=300)\nparser.add_argument('--n_layers', type=int, default=1)\nparser.add_argument('--dropout', type=float, default=.5)\n\nargs = parser.parse_args()\n\n# make dirs\nos.makedirs(args.run_dir, exist_ok=True)\n\n# set log\nlog.basicConfig(\n format='%(asctime)s: %(message)s',\n datefmt='%m/%d %I:%M:%S %p', level=log.INFO)\nlog.getLogger().addHandler(log.FileHandler(os.path.join(args.run_dir, 'log.txt'), mode='w'))\nlog.info(str(vars(args)))\n\n# parse device\nargs.device = 'cpu' if args.device < 0 else 'cuda:%i' % args.device\nargs.device = torch.device(args.device)\n\n#########################################\n\nif __name__ == \"__main__\":\n\n # dataset\n Task = dataset.NonSeqTask \\\n if args.model == 'MLP' \\\n else dataset.SeqTask\n task = Task(args)\n\n # model\n Model = getattr(models, args.model)\n model = Model(args, task)\n model.load_state_dict(torch.load(os.path.join(args.run_dir, 'params_lang.model')))\n\n # train\n train(args, model, task)\n # preds = evaluate(args, model, task)\n # preds = torch.cat(preds)\n # preds = preds[:,1]\n\n seq2vec(args, model, task)\n\n # with open(os.path.join(args.run_dir, 'submission.csv'), 'w') as f:\n # f.write('id,pred\\n')\n # for idx in range(preds.shape[0]):\n # f.write('%i,%f\\n' % (idx, preds[idx]))" } ]
14
candytale55/divisable_by_ten
https://github.com/candytale55/divisable_by_ten
13ba18a4764b8608568a413ba56066626188f77c
68e09c0d580e7b8292cce4ede73b424b5143e0a9
e19591de6294395bdd1bda0b157b6b7b96d783ab
refs/heads/main
2023-02-04T05:15:36.709337
2020-12-16T12:29:01
2020-12-16T12:29:01
321,974,591
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7090069055557251, "alphanum_fraction": 0.7159353494644165, "avg_line_length": 15.615385055541992, "blob_id": "1076592ce5cff3729a385b3784a69efa00b6c9a9", "content_id": "cedf07d3fcfbc8371242acddcbaf2a4aaa5ac67e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 433, "license_type": "no_license", "max_line_length": 168, "num_lines": 26, "path": "/README.md", "repo_name": "candytale55/divisable_by_ten", "src_encoding": "UTF-8", "text": "# divisable_by_ten\n\n## General info\nCreate a function named divisible_by_ten() that takes a list of numbers named nums as a parameter. Return the count of how many numbers in the list are divisible by 10.\n\nThe goal is really just personal learning.\n\n## Technologies\n* Python 3\n\n## Setup\nna\n\n## Code Examples\nna\n\n## Features\n* for..in loop\n* range()\n* modulo %\n\nTo-do list:\n* Complicate things \n\n## Status\nProject is: _in progress_, \n" }, { "alpha_fraction": 0.6235954761505127, "alphanum_fraction": 0.6713483333587646, "avg_line_length": 26.384614944458008, "blob_id": "7697da8edf7086d8b1fad6a11c05b5a48d0562f1", "content_id": "9ffd41d641c1e400e835e0e091256c422535d116", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 356, "license_type": "no_license", "max_line_length": 101, "num_lines": 13, "path": "/divisable_by_ten.py", "repo_name": "candytale55/divisable_by_ten", "src_encoding": "UTF-8", "text": "# Create a function named divisible_by_ten() that takes a list of numbers named nums as a parameter. \n# Return the count of how many numbers in the list are divisible by 10.\n\n\ndef divisible_by_ten(nums):\n count = 0\n for i in range(len(nums)):\n if nums[i] % 10 ==0:\n count += 1\n return count\n\n# TESTS\nprint(divisible_by_ten([20, 25, 30, 35, 40]))\n" } ]
2
mixure/wow
https://github.com/mixure/wow
84dd08952add914869bd5760bc1623f99c88e735
c2bc25a3ab6127681661273bcebd5d19b61e7e40
1729fef95672ee417291e7157cdd98568d166e79
refs/heads/master
2021-01-18T16:43:18.275230
2020-09-15T00:52:46
2020-09-15T00:52:46
86,759,048
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.6350497007369995, "alphanum_fraction": 0.6350497007369995, "avg_line_length": 25.829267501831055, "blob_id": "3a426d03863d4339238f8aca1b69873f46335f35", "content_id": "420fe29e08cbfcfae59772c6fe6330716c6ac491", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1107, "license_type": "no_license", "max_line_length": 65, "num_lines": 41, "path": "/test_project/utilities/core.py", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "import unittest\nfrom selenium import webdriver\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.common.by import By\nfrom utilities.logger import logger\n\n\nfrom selenium.webdriver.chrome.options import Options\n\nurl='http://www.baidu.com'\n\n# def get_screenshot_as_file(func):\n# def wrapper(self):\n# try:\n# func(self)\n# except:\n# self.dr.get_screenshot_as_file('{}.png'.format(\n# func.__name__) )\n# return wrapper\n\nclass Core(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n Core.dr=webdriver.Firefox()\n # Core.imgs=[]\n\n #Chrome headless mode\n # chrome_options=Options()\n # chrome_options.add_argument('--headless')\n # Core.ff=webdriver.Chrome(chrome_options=chrome_options)\n\n Core.dr.get(url)\n\n @classmethod\n def tearDownClass(cls):\n Core.dr.quit()\n\nif __name__=='__main__':\n unittest.main()\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.4440629482269287, "alphanum_fraction": 0.4560801088809967, "avg_line_length": 46.876712799072266, "blob_id": "6f7db8ce0117dd2565ffa780e83e001aa34398a8", "content_id": "78a93d21d5605615b809401558061352a828e7d5", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4041, "license_type": "permissive", "max_line_length": 282, "num_lines": 73, "path": "/_docker/mysqlutf8/README.md", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "# mysql utf8 how to\n\n## 其他人都是不正确的\n使用mysql容器镜像可以很快速的运行mysql,免去了传统的虚拟机安装方式的繁琐配置。\n但是使用[官方的mysql镜像](https://hub.docker.com/_/mysql/),你会遇到中文乱码的问题,原因是官方镜像的字符集默认值不是utf8。\n这时候你去google,会找到一些文章,如[这个哥们的](https://github.com/dnhsoft/docker-mysql-utf8),但是你按照他的做法,还是会乱码,这时候你进入mysql查看字符集,发现是这样的:\n```\nshow variables like \"%character%\";\n\n+--------------------------+----------------------------------+\n| Variable_name | Value |\n+--------------------------+----------------------------------+\n| character_set_client | utf8 |\n| character_set_connection | utf8 |\n| character_set_database | latin1 |\n| character_set_filesystem | binary |\n| character_set_results | utf8 |\n| character_set_server | latin1 |\n| character_set_system | utf8 |\n| character_sets_dir | /usr/local/mysqlarsets/ |\n+--------------------------+----------------------------------+\n8 rows in set (0.00 sec)\n```\n\n## 这里才是正确的\n好吧,我费了不少力气,才找到正确方法。\n\n首先查看官方镜像说明,有关于utf8设置的参数:\n```\nMany configuration options can be passed as flags to mysqld. This will give you the flexibility to customize the container without needing a cnf file. For example, if you want to change the default encoding and collation for all tables to use UTF-8 (utf8mb4) just run the following:\n $ docker run --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci\n```\n如果只是设置这两个参数是不够的,你会得到这样的配置:\n```\nmysql> show variables like \"%character%\";\n+--------------------------+----------------------------------+\n| Variable_name | Value |\n+--------------------------+----------------------------------+\n| character_set_client | latin1 |\n| character_set_connection | latin1 |\n| character_set_database | utf8 |\n| character_set_filesystem | binary |\n| character_set_results | latin1 |\n| character_set_server | utf8 |\n| character_set_system | utf8 |\n| character_sets_dir | /usr/local/mysql/share/charsets/ |\n+--------------------------+----------------------------------+\n8 rows in set (0.00 sec)\n```\n你会发现上面那个哥们的与官方的这个指导取并集,就是正确的结果了,所以方法就很简单了。查看dockerfile。\n正确的配置:\n```\nmysql> show variables like \"%character%\";\n+--------------------------+----------------------------------+\n| Variable_name | Value |\n+--------------------------+----------------------------------+\n| character_set_client | utf8 |\n| character_set_connection | utf8 |\n| character_set_database | utf8 |\n| character_set_filesystem | binary |\n| character_set_results | utf8 |\n| character_set_server | utf8 |\n| character_set_system | utf8 |\n| character_sets_dir | /usr/local/mysql/share/charsets/ |\n+--------------------------+----------------------------------+\n8 rows in set (0.01 sec)\n```\n\n---\ndockerfile\n* 添加root远程登陆授权;\n* -e MYSQL_ROOT_PASSWORD环境变量 \n* fork from https://github.com/ibusybox/mysqlutf8\n" }, { "alpha_fraction": 0.6143141388893127, "alphanum_fraction": 0.628230631351471, "avg_line_length": 17.629629135131836, "blob_id": "db4b517871d77927049838e2f54ac1a3c47d7310", "content_id": "fbfe9360013ea92d50c3473f73813e52ff46067b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 503, "license_type": "no_license", "max_line_length": 57, "num_lines": 27, "path": "/nginx", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "#! /bin/bash\n# chkconfig: 3 85 15\n\nDAEMON=/usr/local/nginx/sbin/nginx\ncase \"$1\" in\n\tstart)\n\t\techo \"Starting nginx daemon...\"\n\t\t$DAEMON &&echo \"SUCCESS\"\n\t\t;;\n\tstop)\n\t\techo \"Stoppint nginx daemon...\"\n\t\t$DAEMON -s quit && echo \"SUCCESS\"\n\t\t;;\n\treload)\n\t\techo \"Reloading nginx daemon...\"\n\t\t$DAEMON -s reload && echo \"SUCCESS\"\n\t\t;;\n\trestart)\n\t\techo \"Restarting nginx daemon...\"\n\t\t$DAEMON -s quit\n\t\t$DAEMON && echo \"SUCCESS\"\n\t\t;;\n\t*)\n\t\techo \"Usage: service nginx {start|stop|restart|reload}\"\n\t\texit 2\n\t;;\nesac\n" }, { "alpha_fraction": 0.7764900922775269, "alphanum_fraction": 0.7913907170295715, "avg_line_length": 32.55555725097656, "blob_id": "eadfb1f41ca1330dfb784c88f24c2d65f99dd4b0", "content_id": "014a1f84c771993a50043892474f85da725dd307", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 604, "license_type": "no_license", "max_line_length": 70, "num_lines": 18, "path": "/test_project/utilities/logger.py", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "import logging\nfrom logging.handlers import RotatingFileHandler\nfrom config import config\n\nlog_dir=config.Path.log_dir\n\nlogger=logging.getLogger()\nlogger.setLevel(logging.DEBUG)\nfile_handler=RotatingFileHandler('%s/log' %log_dir,maxBytes=1024*1024,\n backupCount=3)\nfile_handler.setFormatter(logging.Formatter(\"%(asctime)s %(msg)s\"))\nfile_handler.setLevel(logging.DEBUG)\nlogger.addHandler(file_handler)\n\nconsole_handler=logging.StreamHandler()\nconsole_handler.setFormatter(logging.Formatter(\"%(asctime)s %(msg)s\"))\nconsole_handler.setLevel(logging.DEBUG)\nlogger.addHandler(console_handler)\n" }, { "alpha_fraction": 0.47959184646606445, "alphanum_fraction": 0.4897959232330322, "avg_line_length": 24.789474487304688, "blob_id": "c0ebdceb9205d2da3666e2a5eadc4326ea99ba28", "content_id": "5fa4f24953582169e1222643d38c7431701843fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1052, "license_type": "no_license", "max_line_length": 65, "num_lines": 38, "path": "/lemur/lemur/wipeFruit.py", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n# coding=utf-8\n\n\n\"\"\"数据判断,生成monkey shell\"\"\"\n\n\nclass WipeFruit:\n def check_fruit(self,cache):\n if not cache['count'][1]:\n return '执行次数必填'\n return 0\n\n def then_eat_it(self,cache):\n echo=self.check_fruit(cache)\n if echo:\n return echo\n\n shell=list(['adb','shell','monkey'])\n sum=0\n for name,(option,value,description) in cache.iteritems():\n if 'ig' in name:\n shell.append(option if value else '')\n elif option and value:\n shell.extend([option,value])\n elif value:\n shell.append(value)\n\n try:\n if option and 'pct' in option and value:\n sum+=int(value)\n except:\n return '你一定输入了个不能转成整数的东西,在%s那.' %description\n else:\n if sum>100:\n return '事件总数大于100%'\n return ' '.join(shell)\n pass\n" }, { "alpha_fraction": 0.7009502649307251, "alphanum_fraction": 0.705422043800354, "avg_line_length": 26.90625, "blob_id": "3a346760ca3733c0051cf63c297a15738bb32689", "content_id": "cfe380dc53f4d924df920d9477f8567b5e126b47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1853, "license_type": "no_license", "max_line_length": 87, "num_lines": 64, "path": "/test_project/run_test.py", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "# coding=utf-8\n\nimport unittest\nimport os\nfrom config import config\nfrom utilities.logger import logger\n\nimport time,sys\n# http://tungwaiyip.info/software/HTMLTestRunner.html\nif sys.version_info.major==3:\n # HTMLTestRunner3 是在HTMLTestRunner 上修改的\n import utilities.HTMLTestRunner3 as HTMLTestRunner\nelse:\n import utilities.HTMLTestRunner as HTMLTestRunner\n\n #支持截图,2/3都可以\n # https://github.com/GoverSky/HTMLTestRunner_cn\nimport utilities.HTMLTestRunner_cn as HTMLTestRunner\n\n # https://github.com/findyou/HTMLTestRunnerCN/tree/dev\nimport utilities.HTMLTestRunnerCN as HTMLTestRunner\n\ndef test_unit():\n test_unit=unittest.TestSuite()\n test_dir=config.Path.test_cases_dir\n discover=unittest.defaultTestLoader.discover(\n test_dir,\n pattern='test*.py',\n # top_level_dir=None\n )\n\n for test_suite in discover:\n for test_case in test_suite:\n test_unit.addTests(test_case)\n return test_unit\n\ndef run(test_unit):\n runner=unittest.TextTestRunner()\n runner.run(test_unit)\n\ndef run_with_report(test_unit):\n report_file=config.Path.report_file\n fp=open(report_file,'wb')\n runner=HTMLTestRunner.HTMLTestRunner(\n stream=fp,\n title=\"title\",\n description=u'执行情况')\n runner.run(test_unit)\n fp.close()\n\ndef run_with_BeautifulReport(test_unit):\n # python3 使用BeautifulReport,report路径写在BeautifulReport里面\n from utilities.BeautifulReport import BeautifulReport\n result = BeautifulReport(test_unit)\n result.report(filename='report.html', description='测试deafult报告', log_path='report')\n\ndef send_mail():\n import mail1\n\nif __name__=='__main__':\n test_unit=test_unit()\n # run(test_unit)\n run_with_report(test_unit)\n # run_with_BeautifulReport(test_unit)\n\n\n\n" }, { "alpha_fraction": 0.4992314875125885, "alphanum_fraction": 0.5069167017936707, "avg_line_length": 27.53508758544922, "blob_id": "3bd89d1d00fd44e6c0432601e8ae1d71126a3cc1", "content_id": "ef30d2831a6ef794123a218edc84354eb783ab1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3375, "license_type": "no_license", "max_line_length": 73, "num_lines": 114, "path": "/lemur/lemur/lemur.py", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n# coding=utf-8\n\n\nimport Tkinter as tk\nfrom collections import OrderedDict\n\nfrom Madagascar import Madagascar\nfrom wipeFruit import WipeFruit\nfrom makeTool import render_and_dump\n\n\nclass Lemur:\n def __init__(self,master):\n self.wf=WipeFruit()\n self.Mad=Madagascar()\n\n self.master=master\n self.master.title('lemur')\n\n self.cache=self.Mad.load()\n self.run()\n\n def run(self):\n index=1\n for name,(option,value,description) in self.cache.iteritems():\n if 'ig' in name:\n setattr(self,name+'V',tk.IntVar())\n setattr(self,name,\n tk.Checkbutton(self.master,\n text=description,\n variable=getattr(self,name+'V')\n )\n )\n getattr(self,name).grid(row=index,column=0)\n if value==1:\n getattr(self,name).select()\n else:\n getattr(self,name).deselect()\n else:\n tk.Label(self.master,text=description).grid(row=index)\n setattr(self,name,tk.Entry(self.master))\n getattr(self,name).grid(row=index, column=1)\n getattr(self,name).insert(0,value)\n index+=1\n\n index+=1\n #输出结果文本框\n self.text=tk.Text(self.master, width=50,heigh=3,fg='BLUE')\n self.text.grid(row=index,column=0,columnspan=4)\n\n #生成monkey shell按钮\n index+=1\n adb_shell=tk.Button(self.master,\n text='生成 adb monkey',\n command=\n lambda :self.show_msg(self.grab_adb_shell()))\n adb_shell.grid(row=index,column=0)\n\n #保存配置信息按钮\n save_config=tk.Button(self.master,\n text='保存配置',\n command=self.save_config)\n save_config.grid(row=index,column=1)\n\n #生成脚本按钮\n index+=1\n generate_shell=tk.Button(self.master,\n text='生成 shell 脚本',\n command=self.generate_shell)\n generate_shell.grid(row=index,column=0)\n\n def update_cache(self):\n for name in self.cache:\n self.cache[name][1]=getattr(self,\n name+'V' if 'ig' in name else name).get()\n\n #生成monkey shell\n def grab_adb_shell(self):\n self.update_cache()\n return self.wf.then_eat_it(self.cache)\n\n #保存配置事件\n def save_config(self):\n self.update_cache()\n echo=self.grab_adb_shell()\n if 'adb' in echo:\n self.Mad.dump(self.cache)\n self.show_msg('配置已保存')\n else:\n self.show_msg(echo)\n\n #生成脚本事件\n def generate_shell(self):\n echo=self.grab_adb_shell()\n if 'adb' in echo:\n self.show_msg(render_and_dump(echo[10:]))\n else:\n self.show_msg(echo)\n\n #文本框显示事件\n def show_msg(self,content):\n self.text.delete('1.0',tk.END)\n self.text.insert('1.0',content)\n\n\ndef main():\n root=tk.Tk()\n monkey=Lemur(root)\n root.mainloop()\n\n\nif __name__=='__main__':\n main()\n" }, { "alpha_fraction": 0.6587926745414734, "alphanum_fraction": 0.6587926745414734, "avg_line_length": 21.294116973876953, "blob_id": "a18179a3f1f6f0fb74c9ab0d4c56b4d1ce01665b", "content_id": "b749f0aac601d6599e1631de412c6542f8f70ff7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 381, "license_type": "no_license", "max_line_length": 63, "num_lines": 17, "path": "/test_project/config/config.py", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "import os\nimport time\n\nclass Path:\n project_dir='/Users/yeap/local/personal/tools/test_project'\n\n test_cases_dir=os.path.join(project_dir,'test_cases')\n\n report_dir=os.path.join(project_dir,'report')\n\n report_file=os.path.join(report_dir,'{}.html'.format(\n time.strftime('%Y-%m-%d_%H:%M')))\n\n log_dir=os.path.join(project_dir,'report')\n\nclass Log:\n pass\n\n\n" }, { "alpha_fraction": 0.6231883764266968, "alphanum_fraction": 0.6343366503715515, "avg_line_length": 25.41176414489746, "blob_id": "f9235c91235f56140f8bd1f408a0e069bd4eb213", "content_id": "f77613ccadc67537b5f80702784ed0b8a8519c57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 905, "license_type": "no_license", "max_line_length": 56, "num_lines": 34, "path": "/phone/phone.sh", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "#! /usr/bash\n# coding=utf-8\n\nhead='adb shell'\n\nfor body in ro.build.version.release\\\n ro.build.version.sdk\\\n ro.product.manufacturer\\\n ro.product.name\\\n ro.product.cpu.abilist\\\n dalvik.vm.heapstartsize\\\n dalvik.vm.heapgrowthlimit\\\n dalvik.vm.heapsize;do\n echo ${body##*.}: `$head getprop $body`\ndone\n\necho battery `$head dumpsys battery|grep level`\n\n#package='com.android.browser'\nif [ $package ];then\n\n echo cupinfo: `$head dumpsys cpuinfo|grep $package`\n echo `$head dumpsys meminfo|grep $package`\n pid=`$head ps|grep $package|awk -F ' ' '{print $2}'`\n echo pid $pid\nfi\n\n# http://blog.csdn.net/subaohao/article/details/38730309\n# adb shell am start -n xxx/xxx \n\n# cpu dumpsys cpuinfo ; /proc/stat ;top\n# men dumpsys meminfo 包名; 整体/proc/meminfo\n# battery dumpsys battery\n# /proc/${pid}/net/dev" }, { "alpha_fraction": 0.5738434195518494, "alphanum_fraction": 0.5943060517311096, "avg_line_length": 20.20754623413086, "blob_id": "c1df63a2e7f626e26c43e0db53ff708d3c5e9cbe", "content_id": "c453a1c197c26efc7dba312e8f829e88e448d11d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1158, "license_type": "no_license", "max_line_length": 70, "num_lines": 53, "path": "/获取天气发送短信.rb", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "# Download the twilio-ruby library from twilio.com/docs/libraries/ruby\nrequire 'twilio-ruby'\nrequire 'open-uri'\n\naccount_sid = ''\nauth_token = ''\nclient = Twilio::REST::Client.new(account_sid, auth_token)\n\nfrom = '' # Your Twilio number\nto = '+' # Your mobile phone number\n\nurl='http://e.weather.com.cn/mweather15d/101010100.shtml'\n\nr='''\n<div class=\"list-left\">\n<p class=\"week\">(.+)</p>\n<p class=\"date\">(.+)</p>\n</div>\n<div class=\"list-right\">\n<p>\n<i class=\"svnicon housr_icons d01\"></i>\n<span class=\"weatherWord\">(.+)</span>\n<span class=\"d-temp\">(.+)</span>\n</p>\n<p>\n<i class=\"svnicon housr_icons n01\"></i>\n<span class=\"weatherWord\">(.+)</span>\n<span class=\"n-temp\">(.+)</span>\n</p>\n</div>\n<div class=\"list-right-wind\">\n<p class=\"windD wefther-fx\">\n<img class=.+ src=.+ alt=\"\">\n<br>\n<img class=.+ src=.+ alt=\"\">\n</p><p class=\"windS\">\n<span>(.+)</span><br>\n<span>(.+)</span>\n</p>\n'''\n\nopen(url).read=~ Regexp.new(r)\nmsg= \"#{$1}(#{$2}):#{$3},#{$4},#{$7}/#{$5},#{$6},#{$8}\"\n\n[\n to # 这是xxx的手机号; 其他接受方也要到twilio做登记...\n].each do |receiver|\n client.messages.create(\n from: from,\n to: receiver,\n body: \"#{msg}\" \n )\nend\n" }, { "alpha_fraction": 0.5136518478393555, "alphanum_fraction": 0.5358361601829529, "avg_line_length": 19.928571701049805, "blob_id": "dc7a8e7c22b4a4835510bec3bb4578fbfbbf8599", "content_id": "a66108730d6c8948e6e80bb1fa8bbfc7fe5be64f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1258, "license_type": "no_license", "max_line_length": 64, "num_lines": 56, "path": "/test_project/test_cases/test2.py", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "# coding:utf-8\n\nimport unittest\nfrom selenium import webdriver\nimport time\nfrom utilities.logger import logger\n\n# class Testaa(unittest.TestCase):\n# u'''测试用例a的集合'''\n# @classmethod\n# def setUpClass(cls):\n# cls.driver = webdriver.Firefox()\n\n# def setUp(self):\n# self.driver.get(\"https://www.cnblogs.com/yoyoketang/\")\n\n\n# def test_01(self):\n# u'''用例1:用例1的操作步骤'''\n# t = self.driver.title\n# print(t)\n# self.assertIn(\"悠悠\", t)\n\n\n# def test_02(self):\n# u'''用例2:用例2的操作步骤'''\n# t = self.driver.title\n# print(t)\n# self.assertIn(\"悠悠\", t)\n\n# def test_03(self):\n# u'''用例3:用例3的操作步骤'''\n# t = self.driver.title\n# print(t)\n# self.assertIn(\"悠悠\", t)\n\n# @classmethod\n# def tearDownClass(cls):\n# cls.driver.quit()\n\nclass Test(unittest.TestCase):\n def test01(self):\n '''01'''\n self.assertTrue(True)\n logger.debug('in test2.py')\n\n def test02(self):\n '''02'''\n self.assertTrue(True)\n\n def test03(self):\n '''03'''\n self.assertTrue(True)\n\nif __name__ == \"__main__\":\n unittest.main()\n" }, { "alpha_fraction": 0.6192660331726074, "alphanum_fraction": 0.6284403800964355, "avg_line_length": 15.769230842590332, "blob_id": "5f41ac64848efdf92d4dcd1a6ff2c2568c73a968", "content_id": "dd58b8ea16c4d910b607fc6b1570cb01fe7abb7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 218, "license_type": "no_license", "max_line_length": 38, "num_lines": 13, "path": "/find_rb.rb", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "#! /usr/bin/env ruby\n# coding=utf-8\n\nreg=Regexp.new ARGV[0]\n$:.each do |path|\n begin\n Dir.foreach(path) do |file|\n puts path if reg.match file\n end\n rescue\n puts \"exception occure in #{path}\"\n end\nend\n" }, { "alpha_fraction": 0.6315789222717285, "alphanum_fraction": 0.7218044996261597, "avg_line_length": 37, "blob_id": "a4e99b56fefb6ca9e0b717825c1eaf569cd43c19", "content_id": "d2764617de289c9b7dd80349c59bc20f8f999072", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 280, "license_type": "no_license", "max_line_length": 83, "num_lines": 7, "path": "/grant_root_remote_visit_mysql.sh", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "docker run -d -p 3307:3306 --name mysql -e MYSQL_ROOT_PASSWORD=123456 mysql:5.6\nsleep 10 # 这个延时实在是...\ndocker exec -i mysql mysql -uroot -p123456<<EOF\nGRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '123456' WITH GRANT OPTION;\nflush privileges;\nexit\nEOF\n" }, { "alpha_fraction": 0.6043689250946045, "alphanum_fraction": 0.6043689250946045, "avg_line_length": 19.600000381469727, "blob_id": "9c4e847a50eed60f8a1aa9687b9a09d5649240df", "content_id": "dd906cf4bbdbc037047c4c614505688e78398ee3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 412, "license_type": "no_license", "max_line_length": 74, "num_lines": 20, "path": "/rakefile.rb", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "require 'find'\ndir=Dir.pwd\n\ndef source_files dir,sfs\n Dir.glob(File.join(dir,'*')) do |f|\n source_files(f,sfs) if File.directory?(f)\n sfs<< File.join(dir,'*.java') if not sfs.include?(f) and f=~/.java$/\n end\n sfs\nend\n\nnamespace :admin do\n desc \"Compile java source files\"\n task :compile do\n sfs=source_files dir,[]\n sfs=sfs.join \" \"\n %x<javac -d . #{sfs}>\n puts 'done'\n end\nend\n" }, { "alpha_fraction": 0.7314049601554871, "alphanum_fraction": 0.7520661354064941, "avg_line_length": 47.400001525878906, "blob_id": "6c55a61e32bd74b74f2ca2f6a2fef644c69d1bb9", "content_id": "c7ee068a7862bf26849881680eb70614e4c81e37", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 242, "license_type": "permissive", "max_line_length": 83, "num_lines": 5, "path": "/_docker/mysqlutf8/Dockerfile", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "from mysql:5.6\nCOPY my.cnf /etc/mysql/conf.d/mysqlutf8.cnf\nCOPY ./grant_root_remote_visit.sql /docker-entrypoint-initdb.d\nENV MYSQL_ROOT_PASSWORD 123qwe \nCMD [\"mysqld\", \"--character-set-server=utf8\", \"--collation-server=utf8_unicode_ci\"]\n" }, { "alpha_fraction": 0.7150465846061707, "alphanum_fraction": 0.73235684633255, "avg_line_length": 24.03333282470703, "blob_id": "bae24e8d5788e335eebba0870977d6c7a635e2d6", "content_id": "e7666cd58bb98a26fc79bb8c1fd33681f5241789", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 751, "license_type": "no_license", "max_line_length": 71, "num_lines": 30, "path": "/_docker/noevim配置代码自动补全/install.sh", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "#! /usr/bin/sh\n\n#\nyum -y install git\n\n# python3\nyum install epel-release -y\nyum install https://centos7.iuscommunity.org/ius-release.rpm -y\nyum install python36u -y\nln -s /bin/python3.6 /bin/python3\n\n# pip3\nyum install -y epel-release\nyum -y install python36-pip\npip3 install pynvim\npip3 install -U pip3\n\n# vim-plug\ncurl -fLo ~/.local/share/nvim/site/autoload/plug.vim --create-dirs \\\n https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim\n\n# noevim\nmkdir /usr/local/nvim\ncd /usr/local/nvim\nmv /tmp/nvim.appimage .\n./nvim.appimage --appimage-extract\nln -s ./squashfs-root/usr/bin/nvim /usr/local/nvim/nvim\necho 'export PATH=$PATH:/usr/local/nvim'>>/root/.bashrc\n./nvim -c PlugInstall -c q -c q\n./nvim -c UpdateRemotePlugins -c q -c q\n" }, { "alpha_fraction": 0.6315789222717285, "alphanum_fraction": 0.6349745392799377, "avg_line_length": 20.814815521240234, "blob_id": "fb5f3be65519dee782dfb65afc5bf56b087c3998", "content_id": "5150fe87995d745d25038a74ee641d8c5a7ecd1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1268, "license_type": "no_license", "max_line_length": 92, "num_lines": 54, "path": "/lemur/lemur/makeTool.py", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n# coding=utf-8\n\n\"\"\"获取设备信息,生成shell\"\"\"\n\n\nimport os\nimport commands\nfrom string import Template\nfrom string import maketrans\n\n\ntemplate=Template('''#! /usr/bin/env bash\n\nmonkey_shell='${monkey_shell}'\n\nfor serial_number in ${serial_numbers}\ndo\n echo \"执行 $serial_number 设备\"\n\n adb -s $serial_number shell $$monkey_shell>>$serial_number.$(date \"+%Y.%m.%d.%H.%M\").log\n \ndone\n\necho \"日志记录在 $PWD\"\n''')\n\n#获取设备serial_number\ndef serial_numbers():\n devices_info=commands.getoutput('adb devices')\n if 'not' in devices_info:\n return 'adb未安装或未找到'\n\n device_info= [device_info.split('\\t')[0] \n for device_info in devices_info.split('\\n')[1:-1]\n ]\n return device_info if len(device_info) else '未插接手机/模拟器'\n\n\n#根据模版生成shell\ndef render_and_dump(monkey_shell):\n echo=serial_numbers()\n if isinstance(echo,str):\n return echo\n\n\n table=maketrans(\",\",' ')\n shell=template.safe_substitute(monkey_shell=monkey_shell,\n serial_numbers=str(echo).translate(table,\"[]'\"))\n\n with open(os.path.sep.join([os.path.expanduser('~'),'lemur.sh']),\n 'w') as f:\n f.write(shell)\n return '~/lemur.sh 已生成'\n" }, { "alpha_fraction": 0.5392156839370728, "alphanum_fraction": 0.7254902124404907, "avg_line_length": 19.399999618530273, "blob_id": "5c98be23441f241e9e3cd3127c4b71bf9ef823aa", "content_id": "246c94f431b0f44446c97aea33160188d13e42fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 102, "license_type": "no_license", "max_line_length": 43, "num_lines": 5, "path": "/phone/unlock.sh", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "#! /usr/bash\n# coding=utf-8\n\nadb shell input keyevent 82\nadb shell input swipe 360 1233 360 540 500 " }, { "alpha_fraction": 0.39742955565452576, "alphanum_fraction": 0.4003954529762268, "avg_line_length": 28.75, "blob_id": "e1a3485bdfa4c0a61080e0bf81b856be0cec0550", "content_id": "5bf45ce359fb6aec54f2fa868dd5aac9a8d3f1c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2177, "license_type": "no_license", "max_line_length": 70, "num_lines": 68, "path": "/lemur/lemur/Madagascar.py", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n# coding=utf-8\n\n\n\"\"\"保存配置信息\"\"\"\n\n\nimport os.path\nimport pickle\nfrom collections import OrderedDict\n\n\nclass Madagascar:\n def __init__(self):\n self.path=os.path.sep.join((os.path.expanduser('~'),'.lemur'))\n\n def dump(self,cache):\n \n with open(self.path,'w') as f:\n pickle.dump(cache,f)\n\n def load(self):\n if not os.path.exists(self.path):\n return OrderedDict([\n ('package_name',\n ['-p','','测试包名 -p com.xxx']),\n ('ig_crashes',\n ['--ignore-crashes',1,'忽略程序崩溃 --ignore-crashes']),\n ('touch',\n ['--pct-touch','','触摸事件 --pct-touch (%)']),\n ('motion',\n ['--pct-motion','','手势事件 --pct-motion (%)']),\n ('pinch',\n ['--pct-pinchzoom','','缩放事件:--pct-pinchzoom (%)']),\n ('trackball',\n ['--pct-trackball','','轨迹球事件:--pct-trackball (%)']),\n ('screen',\n ['--pct-rotation','','屏幕事件:--pct-rotation (%)']),\n ('nav',\n ['--pct-nav','','导航事件:--pct-nav (%)']),\n ('major',\n ['--pct-majornav','','主要事件:--pct-majornav (%)']),\n ('system',\n ['--pct-syskeys','','系统事件:--pct-syskeys (%)']),\n ('app',\n ['--pct-appswitch','','切屏事件:--pct-appswitch (%)']),\n ('keyboard',\n ['--pct-flip','','键盘事件:--pct-flip (%)']),\n ('anyevents',\n ['--pct-anyevent','','其他事件:--pct-anyevent (%)']),\n ('delay',\n ['--throttle','','延时 --throttle (ms)']),\n ('seed',\n ['-s','','随机种子 -s']),\n ('log_level',\n [None,'','日志级别 -v -v -v']),\n ('count',\n [None,'1000','执行次数 (必填)']),\n ])\n\n with open(self.path) as f:\n return pickle.load(f)\n\nif __name__=='__main__':\n m=Madagascar()\n m.dump({'key':'value'})\n print m.load()\n pass\n" }, { "alpha_fraction": 0.6803278923034668, "alphanum_fraction": 0.7158470153808594, "avg_line_length": 14.8695650100708, "blob_id": "c83ce7cde9d88fc06305ccafdcaed989444b0d3c", "content_id": "046a7e5c48732f922de421c587151c8f1399b898", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 525, "license_type": "no_license", "max_line_length": 124, "num_lines": 23, "path": "/lemur/README.md", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "# lemur\n\nlemur是android monkey的GUI程序,依赖于tk\n\n\n\n\n\n<img src=\"https://github.com/mixure/tools/blob/master/lemur/lemur.png\" width = \"300\" height = \"600\" alt=\"图片名称\" align=left />\n\n安装:\n\n- 1.python2 setup.py install 后,在命令行执行lemur\n- 2.或 直接执行python2 lemur/lemur.py\n\n\n\n使用:\n\n- 1.根据当前的输入生成 monkey shell\n- 2.保存配置,记录在~/.lemur\n  保存配置后再次启动程序,从 ~/.lemur读取\n- 3.根据当前插接的安卓设备和选项信息生成shell\n\n" }, { "alpha_fraction": 0.5696202516555786, "alphanum_fraction": 0.6139240264892578, "avg_line_length": 20.066667556762695, "blob_id": "3d6bbea37884c91245ad94dfae285a9e453fe031", "content_id": "5febb3c91fcf20e933bb1707093a1819f8a33101", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 364, "license_type": "no_license", "max_line_length": 62, "num_lines": 15, "path": "/包装BaiduPCS-Go查看和下载.rb", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "#! /usr/bin/env ruby\n# coding=utf-8\n\ndir=File.join '.','BaiduPCS-Go'\n\ncase ARGV[0]\nwhen %{ls}\n `#{dir} config set -appid=266719`\n `#{dir} #{ARGV.join \" \"}`.display\nwhen %{d},%{download}\n `#{dir} config set -appid=265486`\n \"运行 #{dir} #{ARGV.join ' '} 进行下载;\\n直接调不显示下载进度,忍不了\\n\".display\nelse\n \"不要用我\\n\".display\nend\n" }, { "alpha_fraction": 0.5222222208976746, "alphanum_fraction": 0.5333333611488342, "avg_line_length": 13.210526466369629, "blob_id": "4c2f9b3ed53b5e543e26c747938646e495e8c489", "content_id": "a922e6f12a6d8bc73e7e3a619c7c3d0500a1a686", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 270, "license_type": "no_license", "max_line_length": 42, "num_lines": 19, "path": "/lemur/setup.py", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n# coding=utf-8\n\n\nfrom setuptools import setup,find_packages\n\n\nsetup(\n name='lemur',\n version='0.1',\n packages=find_packages(),\n entry_points={\n 'console_scripts':[\n 'lemur=lemur:main'\n\n ]\n }\n\n)\n" }, { "alpha_fraction": 0.5452856421470642, "alphanum_fraction": 0.5856943726539612, "avg_line_length": 28.49315071105957, "blob_id": "b077183cf6826dec9a8382d603a75fbcf0011983", "content_id": "ad6c5363c7c6569aa8b2c0ce4b027602c09b4f74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2347, "license_type": "no_license", "max_line_length": 96, "num_lines": 73, "path": "/search404page.py", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python3\n# coding=utf-8\n\nimport time\nfrom urllib.parse import urljoin\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\nfrom logzero import logger\n\ndomain=\"https://www.9douyu.com\"\n# domain='http://app.qyer.com/guide/'\ntitle404=\"404错误页面\"\npage_size404=1308\ndr=webdriver.Safari()\ndr.get('https://www.9douyu.com/login')\ndr.find_element('id','username').send_keys('')\ndr.find_element('id','password').send_keys('')\ndr.find_element('id','v4-input-btn').click()\n\ndef scrap_url(url,orginal_url):\n status_code=200\n try:\n now=time.time()\n dr.get(url)\n\n #根据title判断/或者404页面文件都比较小\n if title404 in dr.title: status_code=404\n # if len(dr.page_source)<=page_size404: status_code=404\n t='%.2f' %(time.time()-now)\n html=dr.page_source\n soup=BeautifulSoup(html,'html.parser')\n except Exception as e:\n dr.get_screenshot_as_base64('f{orginal_url}_to_{url}')\n finally:\n if status_code==200:\n mod=\"32m\"\n elif status_code==404:\n mod=\"31m\"\n logger.debug(f'\\033[1;33;37m{url}, 从{orginal_url}获取该链接\\033[0m \\033[0;34m {t}s \\033[0m '\n f'\\033[0;{mod}{status_code}\\033[0m')\n\n more_seeds=[]\n #有些网站的站内的超链接不是href参数提供的,需要继续在if修改\n # 有些还有外链,都是在这处理....\n if status_code==200: # 有些网站404页面有本站链接,比如宜信\n for a in soup.find_all(href=True):\n if a['href'].startswith('/'):\n more_seeds.append((urljoin(domain,a['href']),url))\n \"\"\"\n for a in soup.find_all('a'): #非<a href=xxx>处理\n for k,v in a.attrs.items():\n if v[0]=='/':\n logzero(v)\n \"\"\"\n return more_seeds\n\ndef main(domain):\n seeds=[(domain,\"用户输入\")]\n old_urls=[]\n while seeds:\n seed,*seeds=seeds\n url,orginal_url=seed\n if 'tmail' in url :continue\n if 'qyer-release-android' in url:continue\n if 'apple-store' in url:continue\n if url in old_urls:\n logger.debug(f'{url}, 从{orginal_url}获取该链接,不进行重复访问 ')\n else:\n old_urls.append(url)\n seeds.extend(scrap_url(*seed))\n\nmain(domain)\ndr.quit()\n" }, { "alpha_fraction": 0.6534296274185181, "alphanum_fraction": 0.6696751117706299, "avg_line_length": 14.30555534362793, "blob_id": "b43ef7281c071e4c7cfe2874c4aef5199327daca", "content_id": "49c3d92a2f738e12cac636aa83f273ec61bbd336", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 724, "license_type": "no_license", "max_line_length": 70, "num_lines": 36, "path": "/README.md", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "\n**lemur**: android的monkey GUI工具\n\n**phone**: \n\n- phone.sh 获取 android 设备信息\n- takeashot.sh 截屏脚本\n- unlock.sh    解锁屏脚本\n\n\n**find_rb.rb**: 根据部分方法名在$:中查找方法\n\n**unlink_pyc.py**: 删除特定后缀文件\n\n**test_project**: unittest 测试\n\n**search404page.py** : 404页面查找\n\n\n\n\n\n![imag](https://github.com/mixure/tools/blob/master/search404page.jpg)\n\n**rakefile.rb** : 编译java\n\n**Se_screenshot.py** : 装饰器完成Se截图\n\n**vimrc_mac** : mac下的vim配置\n\n**nginx**: /etc/init.d/nginx\n\n**grant_root_remote_visit_mysql.sh** : shell授权root远程登陆mysql 容器\n\n**获取明日天气发送短信.rb**\n\n**_docker/noevim配置代码自动补全**\n\n\n" }, { "alpha_fraction": 0.5483425259590149, "alphanum_fraction": 0.5690608024597168, "avg_line_length": 25.77777862548828, "blob_id": "80f4cec9ceae4dda0bc7df7501e9bbd8873e4f53", "content_id": "6919b15a1df4c7899cf341dd4e758d2cd6d22282", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1526, "license_type": "no_license", "max_line_length": 86, "num_lines": 54, "path": "/test_project/test_cases/test1_baidu.py", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "# coding=utf-8\n\nfrom utilities.core import *\n\n\nclass Baidu(Core):\n def test1_title(self):\n \"\"\"检查title\"\"\"\n e=EC.title_is('百度一下,你就知道')\n self.assertTrue(e(self.dr))\n\n def test2_news(self):\n \"\"\"检查news\"\"\"\n e=EC.visibility_of_element_located(('name','tj_trnews'))\n self.assertTrue(e(self.dr))\n\n def test3_hao123(self):\n \"\"\"检查hao123\"\"\"\n e=EC.text_to_be_present_in_element(('name','tj_trhao123'),'hao123')\n self.assertTrue(e(self.dr))\n\n def test4_value(self):\n \"\"\"检查8对应元素的value中 \"\"\"\n e=EC.text_to_be_present_in_element_value(('xpath',\n '//input[@name=\"f\"]'),'8')\n self.assertTrue(e(self.dr))\n\n\n\n def test6(self):\n \"\"\"使用WebDriverWait\"\"\"\n self.assertTrue(False)\n e=self.dr.find_element_by_link_text('设置')\n ActionChains(self.dr).move_to_element(e).perform()\n\n # e=WebDriverWait(self.dr,10,0.5).until(\n # EC.presence_of_element_located(('link text','搜索历史'))\n # )\n # e.click()\n\n WebDriverWait(self.dr,10,0.5).until(\n lambda driver:driver.find_element_by_link_text(\"搜索历史\").is_displayed())\n self.dr.find_element_by_link_text('搜索历史').click()\n\n\n\nif __name__=='__main__':\n # suite=unittest.TestSuite()\n # suite.addTest(Baidu('test2'))\n # suite.addTest(Baidu('test1'))\n\n # runner=unittest.TextTestRunner()\n # runner.run(suite)\n unittest.main()\n\n\n" }, { "alpha_fraction": 0.6200466156005859, "alphanum_fraction": 0.6247086524963379, "avg_line_length": 24.235294342041016, "blob_id": "045259691c6217e93f220008c14bc8f19156fc33", "content_id": "c8b93cd6f6bedc76c926c83242a79a2c9f2a1303", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 429, "license_type": "no_license", "max_line_length": 62, "num_lines": 17, "path": "/unlink_pyc.py", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "# /usr/bin/env python\n# coding=utf-8\n\nimport os,shutil\nfrom logzero import logger\n\npath=os.path.dirname(\n os.path.abspath(__file__))\nexts=['.pyo','.pyc','.log','.html']\n\n\nfor dirname,subdirs,files in os.walk(path):\n for file in files:\n if os.path.splitext(file)[1] in exts or 'log' in file:\n path=os.path.join(dirname,file)\n logger.debug(path)\n os.unlink(os.path.join(dirname,file))\n" }, { "alpha_fraction": 0.7169811129570007, "alphanum_fraction": 0.7169811129570007, "avg_line_length": 52, "blob_id": "dabf76d299e46a2ca0acc1e848b9bb64b7eeff65", "content_id": "563eddad1b309959554a2be29748fb2901443341", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 106, "license_type": "permissive", "max_line_length": 87, "num_lines": 2, "path": "/_docker/mysqlutf8/grant_root_remote_visit.sql", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '123qwe' WITH GRANT OPTION;\nflush privileges;\n" }, { "alpha_fraction": 0.6868131756782532, "alphanum_fraction": 0.6868131756782532, "avg_line_length": 25, "blob_id": "636e9029db9c776e0fedcdffc5fba76834c90fa7", "content_id": "0100bdbfded8827623a4b581c0742e77de9e5ced", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 182, "license_type": "no_license", "max_line_length": 52, "num_lines": 7, "path": "/phone/takeashot.sh", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "#! /usr/bin/env bash\n\nfile_name=$(date +%Y%m%d_%H:%M)\n\nadb shell screencap -p /sdcard/screen.png\nadb pull /sdcard/screen.png ${HOME}/${file_name}.png\nadb shell rm /sdcard/screen.png\n" }, { "alpha_fraction": 0.6842655539512634, "alphanum_fraction": 0.7208572626113892, "avg_line_length": 28.430768966674805, "blob_id": "ea30db8e2fee86ccc2d4e93c13f81d47f625bd92", "content_id": "7ebd5c79fa5e63c639f3118ee17ca9c31754f7ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1961, "license_type": "no_license", "max_line_length": 130, "num_lines": 65, "path": "/init_aliyun_centos.sh", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "#! /bin/bash\n#\n\n#\necho \"LC_ALL=en_US.UTF-8\nLANG=en_US.UTF-8\">>/etc/environment\n\n# set alias\nfile_name=~/.bashrc\nsed -i '$a alias ls=\"ls -F\"' $file_name\nsed -i '$a alias h=history' $file_name\n\n# set vim\nsed -i '$a alias vi=vim' $file_name\ncurl -o ~/.vimrc https://raw.githubusercontent.com/mixure/tools/master/vimrc_aliyun_centos\nyum -y install git\ngit clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim\n\n# set docker\ncurl -o /etc/yum.repos.d/docker-ce.repo https://mirrors.ustc.edu.cn/docker-ce/linux/centos/docker-ce.repo\nyum -y install docker-ce\nsystemctl daemon-reload && systemctl restart docker\n\n# jdk\njdk=$(ls|grep jdk)\ntar -xvf $jdk\njdk=`ls|grep jdk.*[0-9]$`\nmv $jdk /usr/local/\nsed -i \"\\$a export JAVA_HOME=/usr/local/$jdk\" /etc/profile\t \nsed -i '$a export PATH=$PATH:$JAVA_HOME/bin' /etc/profile\nln -s /usr/local/$jdk/bin/java /usr/bin/java\n\n# jenkins\njenkins=$(ls|grep jenkins)\nrpm -ivh $jenkins --nosignature\nsed -i 's/JENKINS_USER=\"jenkins\"/JENKINS_USER=\"root\"/g' /etc/sysconfig/jenkins\nsystemctl start jenkins\n/sbin/chkconfig jenkins on\n\n# python\nyum -y install ncurses ncurses-devel \nyum -y install openssl openssl-devel\npython=`ls|grep Python`\ntar -xvf $python\npython=`ls|grep Python.*[0-9]$`\ncd $python\n./configure --prefix=/usr/local/${python}\nsed -i '205s/#//g;210,212s/#//g' Modules/Setup\nmake && make install\nsed -i '$a export PATH=$PATH:'\"/usr/local/$python/bin\" /etc/profile\ncd -\nrm -rf $python\n\n# rvm\ngpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB\n\\curl -sSL https://get.rvm.io | bash -s stable\necho 'export PATH=$PATH:/usr/local/rvm/bin'>>/etc/profile\n\n# mldonkey\nmldonkey=`ls|grep mldonkey`\nmv $mldonkey /usr/local/\ncd /usr/local/$mldonkey\n./configure # 编译过程中需要手动输入y\ngmake\ncp /usr/local/$mldonkey/mlnet /usr/bin/mlnet # mlnet启动后, 生成 ~/.mldonkey/download.ini 中修改allow_ip 可外网访问\n" }, { "alpha_fraction": 0.6715686321258545, "alphanum_fraction": 0.7034313678741455, "avg_line_length": 26.200000762939453, "blob_id": "48358cf137167655116b82db662059f83ecb0e24", "content_id": "a5927d37353bbe583c6b727cc50d4ae791727e48", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 428, "license_type": "permissive", "max_line_length": 84, "num_lines": 15, "path": "/test_project/utilities/BeautifulReport/sample/sample.py", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "\"\"\"\n@Version: 1.0\n@Project: BeautyReport\n@Author: Raymond\n@Data: 2017/11/17 下午3:48\n@File: sample.py\n@License: MIT\n\"\"\"\nimport unittest\nfrom BeautifulReport import BeautifulReport\n\nif __name__ == '__main__':\n test_suite = unittest.defaultTestLoader.discover('../tests', pattern='test*.py')\n result = BeautifulReport(test_suite)\n result.report(filename='测试报告', description='测试deafult报告', log_path='.')\n" }, { "alpha_fraction": 0.5249999761581421, "alphanum_fraction": 0.5649999976158142, "avg_line_length": 15, "blob_id": "9993173ee236f7b263539212e93b36ac6544d05f", "content_id": "57bb6d8b35c3013f87c19d35ff53a65fac0c142f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 400, "license_type": "no_license", "max_line_length": 46, "num_lines": 25, "path": "/test_project/test_cases/test.py", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "# coding=utf-8\n\nimport unittest\nimport paramunittest\n\n\[email protected](\n (1,1,2),\n (-1,1,0),\n (0,0,0),\n # (('name','tj_trhao123'),'hao123'),\n)\n\nclass Test(unittest.TestCase):\n\n def setParameters(self,a,b,c):\n self.a=a\n self.b=b\n self.c=c\n\n def test(self):\n self.assertEqual(self.a+self.b,self.c)\n\nif __name__=='__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.5871388912200928, "alphanum_fraction": 0.5973904728889465, "avg_line_length": 28, "blob_id": "41b75053f280fd39cdc00ace388a0a66ff300cbb", "content_id": "90353c23220b67b6f4e5905c94f4b842f3512fdf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1141, "license_type": "no_license", "max_line_length": 68, "num_lines": 37, "path": "/car.py", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n# coding=utf-8\n\n\"\"\"\n压缩文件夹,上传到远程机器后解压;\n远程机器文件夹压缩,取到本机解压;\n\"\"\"\nimport sys,os\nfrom fabric import Connection\nimport send2trash\n\nremote_machince=''\npasswd=''\ndir_name='gaslight'\ndes_dir='/root/local/'\n\nprint('{}, okey?'.format(sys.argv[1]))\ninput()\n\nc=Connection(remote_machince,connect_kwargs={'password':passwd})\nif sys.argv[1]=='push':\n os.system('tar -czvf {0}.tar.gz {0}'.format(dir_name))\n with c.cd(des_dir):\n c.put('/Users/yeah/local/{}.tar.gz'.format(dir_name),\n des_dir)\n c.run('tar -xzvf {}.tar.gz'.format(dir_name))\n c.run('rm -f {}.tar.gz'.format(dir_name))\n os.system('rm -f {}.tar.gz'.format(dir_name))\nif sys.argv[1]=='pull':\n with c.cd(des_dir):\n c.run('tar -czvf {0}.tar.gz {0}'.format(dir_name))\n c.get('{}{}.tar.gz'.format(des_dir,dir_name),\n '{}/local/{}.tar.gz'.format(os.path.expanduser('~'),\n dir_name))\n send2trash.send2trash(dir_name)\n os.system('tar -xzvf {}.tar.gz'.format(dir_name))\n os.system('rm -f {}.tar.gz'.format(dir_name))\n" }, { "alpha_fraction": 0.6098484992980957, "alphanum_fraction": 0.6136363744735718, "avg_line_length": 27.285715103149414, "blob_id": "d0877bb5c3579991abfdaf4540c980fab431cf01", "content_id": "01768a3b89e7589daba1661e555f6cca8b1a9d4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 826, "license_type": "no_license", "max_line_length": 87, "num_lines": 28, "path": "/test_project/run_all.py", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python3\n# coding=utf-8\nimport unittest\nfrom utilities.BeautifulReport import BeautifulReport\nfrom utilities.logger import logger\nimport os\nfrom tomorrow import threads\nfrom config import config\n\n\ndef add_case(case_path=config.Path.test_cases_dir, rule=\"test*.py\"):\n '''加载所有的测试用例'''\n discover = unittest.defaultTestLoader.discover(case_path,\n pattern=rule,\n top_level_dir=None)\n return discover\n\n@threads(3)\ndef run(test_suit):\n result = BeautifulReport(test_suit)\n result.report(filename='report.html', description='测试deafult报告', log_path='report')\n\nif __name__ == \"__main__\":\n # 用例集合\n cases = add_case()\n for i in cases:\n print(i)\n run(i)\n" }, { "alpha_fraction": 0.5396145582199097, "alphanum_fraction": 0.6070663928985596, "avg_line_length": 22.350000381469727, "blob_id": "bb1bc249a3ef64c9770143229cca50fe144392b1", "content_id": "af225a99af0e41fc1692007b69999dd8957e769d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 984, "license_type": "no_license", "max_line_length": 93, "num_lines": 40, "path": "/server酱向微信推送天气预报.rb", "repo_name": "mixure/wow", "src_encoding": "UTF-8", "text": "require 'rest-client'\n\nurl='http://e.weather.com.cn/mweather15d/101010100.shtml'\n\nr='''\n<div class=\"list-left\">\n<p class=\"week\">(.+)</p>\n<p class=\"date\">(.+)</p>\n</div>\n<div class=\"list-right\">\n<p>\n<i class=\"svnicon housr_icons d01\"></i>\n<span class=\"weatherWord\">(.+)</span>\n<span class=\"d-temp\">(.+)</span>\n</p>\n<p>\n<i class=\"svnicon housr_icons n01\"></i>\n<span class=\"weatherWord\">(.+)</span>\n<span class=\"n-temp\">(.+)</span>\n</p>\n</div>\n<div class=\"list-right-wind\">\n<p class=\"windD wefther-fx\">\n<img class=.+ src=.+ alt=\"\">\n<br>\n<img class=.+ src=.+ alt=\"\">\n</p><p class=\"windS\">\n<span>(.+)</span><br>\n<span>(.+)</span>\n</p>\n'''\n\nr=RestClient.get(url).scan(Regexp.new(r))[1]\nmsg= \"#{r[0]},(#{r[1]})#{r[3]}#{r[4]},#{r[7]},#{r[5]},#{r[6]},#{r[8]}\" # 如何插入中文\n\nserver_jian=\"https://sc.ftqq.com/SCU50181T6253d66a03616f402091464e460e01365cc6533cbe0f5.send\"\nRestClient.post server_jian,{text:'明日天气',desp:msg}\nputs msg\n\n# 在微信上会去掉一些字符,如逗号\n" } ]
34
smantinc/pyaml
https://github.com/smantinc/pyaml
cefd4a25768cbb39df6615a891a20f78ac01a918
18139cf342b1226a0a1855fe6842fa40631842f2
10aab692721ad0fa96b2349958ca563d20357711
refs/heads/master
2021-01-10T22:08:49.652081
2015-07-08T08:46:39
2015-07-08T08:46:39
31,347,721
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5720171928405762, "alphanum_fraction": 0.5825220942497253, "avg_line_length": 34.2795524597168, "blob_id": "fdbb907fdb6aff2f87bc1c10bcd604d1cdf45303", "content_id": "2fe00ca7170798c8991f7d9ae4b543cca81849bb", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22085, "license_type": "permissive", "max_line_length": 136, "num_lines": 626, "path": "/libaml/aml.py", "repo_name": "smantinc/pyaml", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport ctypes\nimport struct\nimport pkgutil\n\nfrom .utils.decorator import Struct\n\n\nclass ByteArrayBuffer:\n def __init__(self):\n self._buffers = []\n\n @property\n def size(self):\n return sum([i.size for i in self._buffers])\n\n def append(self, data):\n class ByBytes:\n def __init__(self, bytesbuf):\n self._bytesbuf = bytesbuf\n\n @property\n def size(self):\n return len(self._bytesbuf)\n\n def tobytes(self):\n return self._bytesbuf\n\n self._buffers.append(ByBytes(data) if type(data) is bytes else data)\n\n def tobytes(self):\n return b''.join([i.tobytes() for i in self._buffers])\n\n\nclass ResTypes:\n RES_NULL_TYPE = 0x0000\n RES_STRING_POOL_TYPE = 0x0001\n RES_TABLE_TYPE = 0x0002\n RES_XML_TYPE = 0x0003\n RES_XML_FIRST_CHUNK_TYPE = 0x0100\n RES_XML_START_NAMESPACE_TYPE = 0x0100\n RES_XML_END_NAMESPACE_TYPE = 0x0101\n RES_XML_START_ELEMENT_TYPE = 0x0102\n RES_XML_END_ELEMENT_TYPE = 0x0103\n RES_XML_CDATA_TYPE = 0x0104\n RES_XML_LAST_CHUNK_TYPE = 0x017f\n RES_XML_RESOURCE_MAP_TYPE = 0x0180\n RES_TABLE_PACKAGE_TYPE = 0x0200\n RES_TABLE_TYPE_TYPE = 0x0201\n RES_TABLE_TYPE_SPEC_TYPE = 0x0202\n\n\ndef parsestruct(buf, structformat):\n size = struct.calcsize(structformat)\n return struct.unpack(structformat, buf[:size])\n\n\nclass ResXMLElement:\n def __init__(self, node, stringpool, namespace, name):\n self._node = node\n self._stringpool = stringpool\n self._namespace = namespace\n self._name = name\n\n def tobytes(self):\n ns = 0xffffffff if not self._namespace else self._stringpool.getstringref(self._namespace)\n n = self._stringpool.getstringref(self._name)\n return struct.pack('II', ns, n)\n\n @property\n def node(self):\n return self._node\n\n @property\n def nodename(self):\n return self._name\n\n @property\n def size(self):\n return 8\n\n\n@Struct('I', ['ref'])\nclass ResourceRef(object):\n def __init__(self, stringpool, value=None):\n self._stringpool = stringpool\n self._value = value\n self._ref = AML.NONE_NAMESPACE_REF\n\n @property\n def value(self):\n return self._value\n\n @property\n def ref(self):\n return AML.NONE_NAMESPACE_REF if self._value is None else self._stringpool.getstringref(self._value)\n\n @ref.setter\n def ref(self, ref):\n if ref != AML.NONE_NAMESPACE_REF:\n self._value = self._stringpool.originalstrings[ref]\n self._ref = ref\n\n def tobytes(self):\n return struct.pack('I', self.ref)\n\n\nclass ResChunk:\n @staticmethod\n def parse(buf):\n header, nul = ResChunk.Header.parse(buf, buffer=buf)\n return header, buf[:header.chunkSize]\n\n @Struct('HHI', ['type', 'headerSize', 'chunkSize'])\n class Header:\n def __init__(self, buffer=None):\n self._buf = buffer\n\n def tobytesbybuf(self):\n return self._buf[:self.headerSize]\n\n def getbody(self):\n return self._buf[self.headerSize:self.chunkSize]\n\n def getnextchunkbuf(self):\n return self._buf[self.chunkSize:]\n\n def dump(self):\n print('type = 0x%04x headerSize = %d size = %d' % (self.type, self.headerSize, self.chunkSize))\n\n\n@Struct([ResourceRef, ResourceRef, 'HHHHHH'], ['ns', 'name', 'attributeStart', 'attributeSize',\n 'attributeCount', 'idIndex', 'classIndex', 'styleIndex'])\nclass ResXMLTree_attrExt:\n pass\n\n\n@Struct('HBBI', ['size', 'res0', 'dataType', 'data'])\nclass Res_value(object):\n # Contains no data.\n TYPE_NULL = 0x00\n # The 'data' holds a ResTable_ref, a reference to another resource\n # table entry.\n TYPE_REFERENCE = 0x01\n # The 'data' holds an attribute resource identifier.\n TYPE_ATTRIBUTE = 0x02\n # The 'data' holds an index into the containing resource table's\n # global value string pool.\n TYPE_STRING = 0x03\n # The 'data' holds a single-precision floating point number.\n TYPE_FLOAT = 0x04\n # The 'data' holds a complex number encoding a dimension value,\n # such as \"100in\".\n TYPE_DIMENSION = 0x05\n # The 'data' holds a complex number encoding a fraction of a\n # container.\n TYPE_FRACTION = 0x06\n\n # Beginning of integer flavors...\n TYPE_FIRST_INT = 0x10\n\n # The 'data' is a raw integer value of the form n..n.\n TYPE_INT_DEC = 0x10\n # The 'data' is a raw integer value of the form 0xn..n.\n TYPE_INT_HEX = 0x11\n # The 'data' is either 0 or 1, for input \"false\" or \"true\" respectively.\n TYPE_INT_BOOLEAN = 0x12\n\n # Beginning of color integer flavors...\n TYPE_FIRST_COLOR_INT = 0x1c\n\n # The 'data' is a raw integer value of the form #aarrggbb.\n TYPE_INT_COLOR_ARGB8 = 0x1c\n # The 'data' is a raw integer value of the form #rrggbb.\n TYPE_INT_COLOR_RGB8 = 0x1d\n # The 'data' is a raw integer value of the form #argb.\n TYPE_INT_COLOR_ARGB4 = 0x1e\n # The 'data' is a raw integer value of the form #rgb.\n TYPE_INT_COLOR_RGB4 = 0x1f\n\n # ...end of integer flavors.\n TYPE_LAST_COLOR_INT = 0x1f\n\n # ...end of integer flavors.\n TYPE_LAST_INT = 0x1f\n\n def __init__(self, stringpool, value=None):\n self._data = 0\n self._stringpool = stringpool\n self._value = value\n\n @property\n def data(self):\n if self.dataType == Res_value.TYPE_STRING and self._value:\n return self._stringpool.getstringref(self._value)\n return self._data\n\n @data.setter\n def data(self, val):\n self._data = val\n if self.dataType == Res_value.TYPE_STRING and val != AML.NONE_NAMESPACE_REF:\n self._value = self._stringpool.originalstrings[val]\n\n @property\n def value(self):\n if self.dataType == Res_value.TYPE_INT_DEC:\n return str(ctypes.c_int32(self._data).value)\n elif self.dataType == Res_value.TYPE_STRING:\n return self._stringpool.getstringbyref(self._data)\n elif self.dataType == Res_value.TYPE_INT_BOOLEAN:\n return 'true' if self._data else 'false'\n return '@%08x' % self._data\n\n\n@Struct('II', ['lineNumber', 'comment'])\nclass ResXMLTree_node:\n pass\n\n\n@Struct([ResourceRef, ResourceRef, 'I', Res_value], ['ns', 'name', 'rawValue', 'typedValue'])\nclass ResXMLTree_attribute:\n def __init__(self, aml=None):\n self._aml = aml\n\n @property\n def namespace(self):\n return self.ns.value\n\n @property\n def attributename(self):\n return self.name.value\n\n def __str__(self):\n if self.namespace:\n return '%s:%s' % (self._aml.namespaces[self.namespace], self.attributename)\n return self.attributename\n\n @staticmethod\n def make(ns, stringpool, name, value):\n if type(value) == str:\n resval = Res_value.create(8, 0, Res_value.TYPE_STRING, AML.NONE_NAMESPACE_REF, stringpool=stringpool, value=value)\n elif type(value) == bool:\n valueref = 0xffffffff if value else 0\n resval = Res_value.create(8, 0, Res_value.TYPE_INT_BOOLEAN, valueref, stringpool=stringpool)\n elif type(value) == int:\n resval = Res_value.create(8, 0, Res_value.TYPE_INT_DEC, value, stringpool=stringpool)\n else:\n print('Other data types aren\\'t supported, sorry')\n raise NotImplementedError()\n return ResXMLTree_attribute.create(ns, name, 0xffffffff, resval)\n\n def tobytes(self):\n if self.typedValue.dataType == Res_value.TYPE_STRING:\n self.rawValue = self.typedValue.data\n return self._tobytes()\n\n\n@Struct([ResChunk.Header, ResXMLTree_node, ResXMLTree_attrExt], ['header', 'node', 'attrExt'])\nclass ResXMLTree:\n def __init__(self, aml):\n self._attributes = []\n self._aml = aml\n\n @property\n def attributes(self):\n return self._attributes\n\n def tobytes(self):\n self.header.chunkSize = self.size\n self.attrExt.attributeCount = len(self._attributes)\n return self._tobytes() + b''.join([i.tobytes() for i in self._attributes])\n\n @property\n def nodename(self):\n return self.attrExt.name.value\n\n @property\n def size(self):\n return ResXMLTree._size + sum([i.size for i in self._attributes])\n\n\nclass AML:\n ANDROID_NAMESPACE = 'http://schemas.android.com/apk/res/android'\n NONE_NAMESPACE_REF = 0xffffffff\n\n class StringList:\n def __init__(self, strings):\n self._strings = strings\n self._stringmapping = dict((j, i) for i, j in enumerate(strings))\n\n def getstringref(self, s):\n return self._stringmapping[s]\n\n def __contains__(self, item):\n return item in self._stringmapping\n\n def __getitem__(self, item):\n return self._strings[item]\n\n def __len__(self):\n return len(self._strings)\n\n class Chunk:\n def __init__(self, header):\n self._bytebuffer = ByteArrayBuffer()\n self._header = header\n\n @property\n def size(self):\n return self._bytebuffer.size\n\n @property\n def body(self):\n return self._header.getbody()\n\n def append(self, data):\n self._bytebuffer.append(data)\n\n def tobytes(self):\n self._header.chunkSize = self.size + self._header.headerSize\n return b''.join([self._header.tobytes(),\n self._header.tobytesbybuf()[ResChunk.Header.size:],\n self._bytebuffer.tobytes()])\n\n class ResourceMapChunk:\n ATTRS = eval(pkgutil.get_data('libaml', 'android-attrs.json'))\n def __init__(self, header, strings):\n self._header = header\n idlen = int((header.chunkSize - header.headerSize) / 4)\n ids = parsestruct(header.getbody(), str(idlen) + 'I')\n self._attrs = [(strings[i], j) for i, j in enumerate(ids)]\n self._attrset = set([i for i, j in self._attrs])\n\n @property\n def attrs(self):\n return self._attrs\n\n @property\n def attrnames(self):\n return [i for i, j in self._attrs]\n\n def __contains__(self, attrname):\n return attrname in self._attrset\n\n def append(self, attrname):\n if attrname not in AML.ResourceMapChunk.ATTRS:\n print(\"Couldn't find R.attr.%s value\" % attrname)\n raise NotImplementedError()\n self._attrs.append((attrname, AML.ResourceMapChunk.ATTRS[attrname]))\n\n @property\n def size(self):\n return self._header.headerSize + len(self._attrs) * 4\n\n def tobytes(self):\n self._header.chunkSize = self.size\n resources = [i[1] for i in self._attrs]\n return self._header.tobytes() + struct.pack(str(len(resources)) + 'I', *resources)\n\n class StringPoolChunk(object):\n # If set, the string index is sorted by the string values (based\n # on strcmp16()).\n SORTED_FLAG = 1 << 0\n # String pool is encoded in UTF-8\n UTF8_FLAG = 1 << 8\n\n class _UTF16StringList:\n def __init__(self, aml):\n self._aml = aml\n\n def loadstrings(self, buf):\n strings = []\n indices = {}\n for i in range(self._aml.stringCount):\n stringlen = parsestruct(buf, 'H')[0]\n s = buf[2:2 + stringlen * 2].decode('utf-16')\n buf = buf[(stringlen + 1) * 2 + 2:]\n strings.append(s)\n indices[s] = i\n return strings, indices\n\n @property\n def size(self):\n return sum([len(i) * 2 + 4 for i in self._aml.strings])\n\n class _UTF8StringList:\n def __init__(self, aml):\n self._aml = aml\n\n def loadstrings(self, buf):\n strings = []\n indices = {}\n for i in range(self._aml.stringCount):\n stringlen = parsestruct(buf, 'H')[0] & 0xff\n s = buf[2:2 + stringlen].decode('utf-8')\n buf = buf[(stringlen + 1) + 2:]\n strings.append(s)\n indices[s] = i\n return strings, indices\n\n @property\n def size(self):\n return sum([len(i) + 3 for i in self._aml.strings])\n\n def __init__(self, buf):\n self._resourcemap = None\n self._header, self._body = ResChunk.Header.parse(buf, buffer=buf)\n self.stringCount, self.styleCount, self.flags, self.stringsStart, self.stylesStart = parsestruct(buf[8:], '5I')\n self._stringlist = self._UTF8StringList(self) if self.flags & AML.StringPoolChunk.UTF8_FLAG else self._UTF16StringList(self)\n self._strings, self._indices = self._stringlist.loadstrings(buf[self.stringsStart:])\n self._originalstrings = list(self._strings)\n\n @property\n def originalstrings(self):\n return self._originalstrings\n\n @property\n def size(self):\n size = self.stringslen()\n return size + (4 - size % 4) % 4\n\n @property\n def attrs(self):\n return [] if self._resourcemap is None else self._resourcemap.attrnames\n\n @property\n def strings(self):\n return list(self._strings if self._resourcemap is None else self._resourcemap.attrnames + self._strings)\n\n @property\n def resourcemap(self):\n return self._resourcemap\n\n @resourcemap.setter\n def resourcemap(self, resourcemap):\n attrlen = len(resourcemap.attrs)\n self._strings = self.strings[attrlen:]\n self._resourcemap = resourcemap\n\n def getstringref(self, s):\n return self._indices[s]\n\n def getstringbyref(self, ref):\n attrslen = len(self.attrs)\n return self.attrs[ref] if ref < attrslen else self._strings[ref - attrslen]\n\n def stringslen(self):\n return sum([len(i) * 2 + 4 for i in self.strings]) + self.stringCount * 4 + self._header.headerSize\n\n def _append(self, s):\n self.stringCount += 1\n self.stringsStart = self.stringCount * 4 + self._header.headerSize\n\n def _rebuildindices(self):\n self._indices = dict((j, i) for i, j in enumerate(self.strings))\n\n def setattribute(self, name, value):\n if name not in self._resourcemap:\n self._resourcemap.append(name)\n self._append(name)\n if type(value) is str:\n self.ensure(value)\n self._rebuildindices()\n\n def ensure(self, s):\n if s not in self._indices:\n self._strings.append(s)\n self._append(s)\n self._indices[s] = len(self.attrs) + len(self._strings) - 1\n\n def tobytes(self):\n bos = ByteArrayBuffer()\n bos.append(self._header)\n self.stringCount = (0 if self._resourcemap is None else len(self._resourcemap.attrs)) + len(self._strings)\n self.stringsStart = self.stringCount * 4 + self._header.headerSize\n bos.append(struct.pack('5I', self.stringCount, self.styleCount, self.flags,\n self.stringsStart, self.stylesStart))\n\n class OffsetCalculator:\n def __init__(self):\n self._offset = 0\n\n def offset(self, s):\n l = len(s) * 2 + 4\n o = self._offset\n self._offset += l\n return o\n\n calculator = OffsetCalculator()\n strings = self.strings\n stringmaps = [calculator.offset(i) for i in strings]\n bos.append(struct.pack(str(self.stringCount) + 'I', *stringmaps))\n for i in strings:\n bos.append(struct.pack(str(len(i) + 2) + 'H', *([len(i)] + [ord(j) for j in i] + [0])))\n self._header.chunkSize = self.size\n stringslen = self.stringslen()\n bos.append(b'\\x00' * (self._header.chunkSize - stringslen))\n return bos.tobytes()\n\n class InsertedPlaceHolder:\n def __init__(self, aml, node):\n self._aml = aml\n self._node = node\n self._bytebuffer = ByteArrayBuffer()\n\n def append(self, data):\n self._bytebuffer.append(data)\n\n @property\n def size(self):\n return self._bytebuffer.size\n\n def tobytes(self):\n return self._bytebuffer.tobytes()\n\n def writexmlstartelement(self, name, attrs, linenumber=0):\n stringpool = self._aml.stringpool\n self._aml.stringpool.ensure(name)\n attrExt = ResXMLTree_attrExt.create(ResourceRef.create(AML.NONE_NAMESPACE_REF, stringpool=stringpool),\n ResourceRef.create(stringpool=stringpool, value=name),\n 20, 20, len(attrs), 0, 0, 0)\n element = ResXMLTree.create(ResChunk.Header.create(ResTypes.RES_XML_START_ELEMENT_TYPE, 16, 0),\n ResXMLTree_node.create(linenumber or self._node.lineNumber, 0xffffffff),\n attrExt, aml=self)\n androidns = ResourceRef(stringpool=stringpool, value=AML.ANDROID_NAMESPACE)\n for k, v in attrs.items():\n stringpool.setattribute(k, v)\n attr = ResXMLTree_attribute.make(androidns, stringpool,\n ResourceRef.create(stringpool=stringpool, value=k), v)\n element.attributes.append(attr)\n self._bytebuffer.append(element)\n return element\n\n def writexmlendelement(self, name, linenumber=0):\n self._bytebuffer.append(ResChunk.Header.create(ResTypes.RES_XML_END_ELEMENT_TYPE, 16, 24))\n self._bytebuffer.append(ResXMLTree_node.create(linenumber or self._node.lineNumber, 0xffffffff))\n self._bytebuffer.append(struct.pack('I', 0xffffffff))\n self._bytebuffer.append(ResourceRef(self._aml.stringpool, name))\n\n @Struct([ResourceRef, ResourceRef], ['_name', '_namespace'])\n class XMLNamespace:\n @property\n def name(self):\n return self._name.value\n\n @property\n def namespace(self):\n return self._namespace.value\n\n def __init__(self, buffer):\n self._namespaces = {}\n self._stringpool = None\n self._strings = None\n self._header, self._body = ResChunk.Header.parse(buffer, buffer=buffer)\n self._rootchunk = AML.Chunk(self._header)\n self._bufptr = self._rootchunk.body\n self._firstchunk = True\n\n @property\n def stringpool(self):\n return self._stringpool\n\n @property\n def strings(self):\n return self._strings\n\n @property\n def namespaces(self):\n return self._namespaces\n\n def hasnext(self):\n return self._firstchunk or len(self._bufptr) > 0\n\n def next(self):\n if self._firstchunk:\n self._firstchunk = False\n return self._header, self._body\n self._header, chunk = ResChunk.parse(self._bufptr)\n self._body = self._header.getbody()\n if self._header.type == ResTypes.RES_STRING_POOL_TYPE:\n self._stringpool = AML.StringPoolChunk(self._bufptr)\n self._strings = AML.StringList(self._stringpool.strings)\n self._rootchunk.append(self._stringpool)\n elif self._header.type == ResTypes.RES_XML_START_NAMESPACE_TYPE:\n self._body, nul = AML.XMLNamespace.parse(self._header.getbody(), stringpool=self._stringpool)\n self._namespaces[self._body.namespace] = self._body.name\n self._rootchunk.append(self._header.tobytesbybuf())\n self._rootchunk.append(self._body)\n elif self._header.type == ResTypes.RES_XML_START_ELEMENT_TYPE:\n self._body, nul = ResXMLTree.parse(self._bufptr, aml=self, stringpool=self._stringpool)\n self._rootchunk.append(self._body)\n buf = self._header.getbody()[self._body.attrExt.attributeStart:]\n for i in range(self._body.attrExt.attributeCount):\n attribute, p = ResXMLTree_attribute.parse(buf, stringpool=self._stringpool, aml=self)\n self._body.attributes.append(attribute)\n buf = buf[self._body.attrExt.attributeSize:]\n elif self._header.type == ResTypes.RES_XML_END_ELEMENT_TYPE:\n node, nul = ResXMLTree_node.parse(self._bufptr[8:])\n ns, name = parsestruct(self._header.getbody(), 'II')\n self._body = ResXMLElement(node, self._stringpool, None, self._strings[name])\n self._rootchunk.append(self._header.tobytesbybuf())\n self._rootchunk.append(self._body)\n elif self._header.type == ResTypes.RES_XML_END_NAMESPACE_TYPE:\n self._body, nul = AML.XMLNamespace.parse(self._header.getbody(), stringpool=self._stringpool)\n self._rootchunk.append(self._header.tobytesbybuf())\n self._rootchunk.append(self._body)\n elif self._header.type == ResTypes.RES_XML_RESOURCE_MAP_TYPE:\n self._stringpool.resourcemap = AML.ResourceMapChunk(self._header, self._strings)\n self._rootchunk.append(self._stringpool.resourcemap)\n else:\n self._rootchunk.append(chunk)\n self._bufptr = self._header.getnextchunkbuf()\n return self._header, self._body\n\n def insert(self):\n try:\n inserted = AML.InsertedPlaceHolder(self, self._body.node)\n except AttributeError:\n raise AssertionError('Cannot insert after none xml node types!')\n self._rootchunk.append(inserted)\n return inserted\n\n def tobytes(self):\n return self._rootchunk.tobytes()\n" }, { "alpha_fraction": 0.5678749084472656, "alphanum_fraction": 0.574982225894928, "avg_line_length": 29.586956024169922, "blob_id": "299ce8946f2a2359964e584ec7da0af758c9e599", "content_id": "5b934a83a7099c9d471ff71841c2955b38d4ddd9", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1407, "license_type": "permissive", "max_line_length": 156, "num_lines": 46, "path": "/examples/parse.py", "repo_name": "smantinc/pyaml", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport getopt\n\nfrom libaml.aml import AML\nfrom libaml.aml import ResTypes\n\n\nINDENT_BLOCK = ' '\n\n\"\"\"\nThis example demonstrates the basic usage of libaml.\nIt parses Android binary xml and prints it to the stdout.\n\"\"\"\n\nif __name__ == '__main__':\n opts, args = getopt.getopt(sys.argv[1:], 'i:')\n params = dict([(i.lstrip('-'), j) for i, j in opts])\n\n if 'i' not in params:\n print('Usage:\\n%s -i android-binary-xml.xml' % sys.argv[0])\n sys.exit(0)\n\n infile = params['i']\n\n with open(infile, 'rb') as fp:\n buf = fp.read()\n\n aml = AML(buf)\n namespaces = []\n indent = 0\n while aml.hasnext():\n header, body = aml.next()\n if header.type == ResTypes.RES_XML_START_ELEMENT_TYPE:\n print(INDENT_BLOCK * indent + '<%s%s>' % (body.nodename, ''.join(namespaces + [' %s=\"%s\"' % (i, i.typedValue.value) for i in body.attributes])))\n namespaces = []\n indent += 1\n elif header.type == ResTypes.RES_XML_END_ELEMENT_TYPE:\n indent -= 1\n print(INDENT_BLOCK * indent + '</%s>' % body.nodename)\n elif header.type == ResTypes.RES_XML_START_NAMESPACE_TYPE:\n namespaces.append(' xmlns:%s=\"%s\"' % (body.name, body.namespace))\n elif header.type == ResTypes.RES_XML_TYPE:\n print('<?xml version=\"1.0\" encoding=\"utf-8\"?>')\n" }, { "alpha_fraction": 0.5857275128364563, "alphanum_fraction": 0.5903614163398743, "avg_line_length": 25.975000381469727, "blob_id": "e21b9dd5b8e9d6fe532b218a7165b14b78f312e1", "content_id": "3d65caba7e9fd81effa154eb9a45665fc551eec5", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1079, "license_type": "permissive", "max_line_length": 94, "num_lines": 40, "path": "/examples/increase_version_code.py", "repo_name": "smantinc/pyaml", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport getopt\n\nfrom libaml.aml import AML\nfrom libaml.aml import ResTypes\n\n\n\"\"\"\nThis example demonstrates the how to modify binary XML using libaml.\nIt parses AndroidManifest.xml and increases version code by one.\n\"\"\"\n\nif __name__ == '__main__':\n opts, args = getopt.getopt(sys.argv[1:], 'i:o:')\n params = dict([(i.lstrip('-'), j) for i, j in opts])\n\n if 'i' not in params:\n print('Usage:\\n%s -i AndroidManifest.xml [-o outfile.xml]' % sys.argv[0])\n sys.exit(0)\n\n infile = params['i']\n outfile = params['o'] if 'o' in params else infile\n\n with open(infile, 'rb') as fp:\n buf = fp.read()\n\n aml = AML(buf)\n while aml.hasnext():\n header, body = aml.next()\n if header.type == ResTypes.RES_XML_START_ELEMENT_TYPE and body.nodename == 'manifest':\n for i in body.attributes:\n if str(i) == 'android:versionCode':\n i.typedValue.data += 1\n\n with open(outfile, 'wb') as fp:\n fp.write(aml.tobytes())\n print('Done.')\n" }, { "alpha_fraction": 0.5274753570556641, "alphanum_fraction": 0.5339553952217102, "avg_line_length": 31.70339012145996, "blob_id": "f79fdb57d30c0b8461fb0f03933d5c4f7defc7fd", "content_id": "41b605ffefcbc75fc4d2db81a98cbede310ae3e3", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3858, "license_type": "permissive", "max_line_length": 109, "num_lines": 118, "path": "/libaml/utils/decorator.py", "repo_name": "smantinc/pyaml", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport inspect\nimport struct\n\nclass Struct:\n def __init__(self, signature, fieldnames):\n self._signature = signature\n self._fieldnames = fieldnames\n self._structs = Struct.initstructs(signature, fieldnames)\n self._structsize = Struct.calculatesize(signature)\n\n @staticmethod\n def initstructs(signature, fieldnames):\n nameoffset = 0\n\n class BySignature:\n def __init__(self, names, signature):\n self._signature = signature\n self._names = names\n self._size = struct.calcsize(signature)\n\n def parse(self, _buf, *args, **kwargs):\n return zip(self._names, struct.unpack(self._signature, _buf[:self._size])), _buf[self._size:]\n\n def tobytes(self, obj):\n return struct.pack(self._signature, *[getattr(obj, i) for i in self._names])\n\n class ByStruct:\n def __init__(self, name, st):\n self._name = name\n self._struct = st\n\n def parse(self, _buf, *args, **kwargs):\n obj, nextbuf = self._struct.parse(_buf, *args, **kwargs)\n return [(self._name, obj)], nextbuf\n\n def tobytes(self, obj):\n st = getattr(obj, self._name)\n return st.tobytes()\n\n structs = []\n if type(signature) is str:\n structs.append(BySignature(fieldnames, signature))\n else:\n for sig in signature:\n if type(sig) is str:\n names = fieldnames[nameoffset:nameoffset+len(sig)]\n nameoffset += len(names)\n structs.append(BySignature(names, sig))\n else:\n name = fieldnames[nameoffset]\n nameoffset += 1\n structs.append(ByStruct(name, sig))\n return structs\n\n @staticmethod\n def calculatesize(signature):\n return sum([struct.calcsize(i) if type(i) is str else i.size for i in signature])\n\n @staticmethod\n def override(cls, name, attr):\n if hasattr(cls, name):\n setattr(cls, '_' + name, attr)\n else:\n setattr(cls, name, attr)\n\n def __call__(self, cls):\n def getinitargs(kwargs):\n return dict([(k, v) for k, v in kwargs.items() if k in cls._INIT_KWARGS])\n\n def create(*args, **kwargs):\n s = cls(**getinitargs(kwargs))\n for i, j in enumerate(args):\n setattr(s, self._fieldnames[i], j)\n return s\n\n def tobytes(s):\n bos = [i.tobytes(s) for i in self._structs]\n return b''.join(bos)\n\n def parse(buf, *args, **kwargs):\n obj = cls(*args, **getinitargs(kwargs))\n for i in self._structs:\n items, buf = i.parse(buf, *args, **kwargs)\n for k, v in items:\n setattr(obj, k, v)\n return obj, buf\n\n try:\n cls._INIT_KWARGS = set(inspect.getargspec(cls.__init__)[0][1:])\n except (TypeError, AttributeError):\n cls._INIT_KWARGS = set([])\n Struct.override(cls, 'tobytes', tobytes)\n Struct.override(cls, 'create', staticmethod(create))\n Struct.override(cls, 'parse', staticmethod(parse))\n Struct.override(cls, 'size', self._structsize)\n return cls\n\n\n@Struct('HHI', ['type', 'headerSize', 'size'])\nclass MyStruct:\n pass\n\n\n@Struct(['II', MyStruct, 'HHL'], ['id', 'name', 'typedValue', 's1', 's2', 's3'])\nclass MyAnotherStruct:\n pass\n\nif __name__ == '__main__':\n s1 = MyStruct.create(10, 20, 30)\n buf = s1.tobytes()\n s1, p = MyStruct.parse(buf)\n ss = MyAnotherStruct.create(1, 2, s1, 3, 4, 5)\n buf = ss.tobytes()\n ss1, p = MyAnotherStruct.parse(buf)\n print(str(ss1))" }, { "alpha_fraction": 0.7857142686843872, "alphanum_fraction": 0.7857142686843872, "avg_line_length": 44.5, "blob_id": "0f24d2d568850ed17b2e8f1f1924015637007aca", "content_id": "7f4d6c55fdd4462c24b414ecef3843ed3cdf6488", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 182, "license_type": "permissive", "max_line_length": 138, "num_lines": 4, "path": "/README.md", "repo_name": "smantinc/pyaml", "src_encoding": "UTF-8", "text": "# pyaml\nPython Android Binary XML Library\n\npyaml is a Python Library used to parse and modify contents of Android Binary XML, a.k.a. AML, such as AndroidManifest.xml layout.xml etc.\n" } ]
5
turbinetamer/lab_app
https://github.com/turbinetamer/lab_app
f902e8006e59a5f350a6316d1cb6ba57ff4ac9fa
9b0de845e603ea8ad78258b7881a1c8a608726e4
0425bc560a185d3fd535f4a5dd40e20cd55e2e98
refs/heads/master
2021-01-12T05:46:53.877419
2017-01-03T17:13:42
2017-01-03T17:13:42
77,194,972
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6412615180015564, "alphanum_fraction": 0.655497133731842, "avg_line_length": 32.847328186035156, "blob_id": "4022e472e2de36cb3e0a2a20f63e38054ea4ea56", "content_id": "ddafa57162138c686c15adaed5700112c84a06ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4566, "license_type": "no_license", "max_line_length": 143, "num_lines": 131, "path": "/lab_app.py", "repo_name": "turbinetamer/lab_app", "src_encoding": "UTF-8", "text": "from flask import Flask, request, render_template\r\nimport time\r\nimport datetime\r\n\r\n\r\napp = Flask(__name__)\r\napp.debug = True # Make this False if you are no longer debugging\r\n\r\[email protected](\"/\")\r\ndef hello():\r\n return \"Hello World!-from lab_app.py\"\r\n\r\[email protected](\"/lab_temp\")\r\ndef lab_temp():\r\n\t#import sys\r\n\t#import Adafruit_DHT\r\n\t#humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302, 17)\r\n\t#if humidity is not None and temperature is not None:\r\n\t#\treturn render_template(\"lab_temp.html\",temp=temperature,hum=humidity)\r\n\t#else:\r\n\t#\treturn render_template(\"no_sensor.html\")\r\n\timport time, logging, math\r\n\timport Adafruit_GPIO as GPIO\r\n\timport Adafruit_GPIO.SPI as SPI\r\n\timport Adafruit_MAX31855.MAX31855 as MAX31855\r\n\t\r\n\tSPI_PORT = 0\r\n\tSPI_DEVICE = 0\r\n\tsensor = MAX31855.MAX31855(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=5000000))\r\n\t\r\n\ttemp = sensor.readTempC()\r\n\tinternal = sensor.readInternalC()\r\n\tprint temp,internal\r\n\t\r\n\tif temp is not None and internal is not None:\r\n\t\treturn render_template(\"lab_temp.html\", d_temp=temp, d_int=internal)\r\n\t\t#return \"We Have Data!\"\r\n\t\t#return 'Temp=%0.1f Internal=%0.1f'%(temp,internal)\r\n\telse:\r\n\t\t#return render_template(\"no_sensor.html\")\r\n\t\treturn \"Sorry, No Data\"\r\n\t\t\r\n\r\[email protected](\"/lab_env_db\", methods=['GET']) \r\ndef lab_env_db():\r\n\ttemperatures, humidities, from_date_str, to_date_str = get_records()\r\n\t\r\n\t#return \r\n\t#return \"lab_env_db from %s to %s items=%d last row %s \" % (from_date_str, to_date_str, len(temperatures), temperatures[len(temperatures)-1])\r\n\t#return render_template(\"lab_env_db.html\",temp=temperatures,hum=humidities)\r\n\treturn render_template(\"lab_env_db.html\",temp \t= temperatures, \r\n\t\t\t\t\t\t\t\t\t\t\t hum= humidities,\r\n\t\t\t\t\t\t\t\t\t\t\t from_date = from_date_str,\r\n\t\t\t\t\t\t\t\t\t\t\t to_date = to_date_str,\r\n\t\t\t\t\t\t\t\t\t\t\t temp_items = len(temperatures),\r\n\t\t\t\t\t\t\t\t\t\t\t hum_items = len(humidities))\r\n\r\ndef get_records():\r\n\tfrom_date_str \t= request.args.get('from',time.strftime(\"%Y-%m-%d 00:00\")) #Get the from date value from the URL\r\n\tto_date_str \t= request.args.get('to',time.strftime(\"%Y-%m-%d %H:%M\")) #Get the to date value from the URL\r\n\trange_h_form\t= request.args.get('range_h',''); #This will return a string, if field range_h exists in the request\r\n\r\n\trange_h_int \t= \"nan\" #initialise this variable with not a number\r\n\tdlist = {\"from_date_str\":from_date_str,\r\n\t\t\t\t\"to_date_str\":to_date_str,\r\n\t\t\t\t\"range_h_form\":range_h_form}\r\n\t\t\t\t\r\n\tfor key in dlist:\r\n\t\tprint(key,dlist[key])\r\n\t\r\n\ttry: \r\n\t\trange_h_int\t= int(range_h_form)\r\n\texcept:\r\n\t\tprint \"range_h_form still not a number, too bad\"\r\n\r\n\tif not validate_date(from_date_str):\t\t\t# Validate date before sending it to the DB\r\n\t\tfrom_date_str \t= time.strftime(\"%Y-%m-%d 00:00\")\r\n\tif not validate_date(to_date_str):\r\n\t\tto_date_str \t= time.strftime(\"%Y-%m-%d %H:%M\")\t\t# Validate date before sending it to the DB\r\n\r\n\t\t# If range_h is defined, we don't need the from and to times\r\n\tif isinstance(range_h_int,int):\t\r\n\t\ttime_now\t\t= datetime.datetime.now()\r\n\t\ttime_from \t\t= time_now - datetime.timedelta(hours = range_h_int)\r\n\t\ttime_to \t\t= time_now\r\n\t\tfrom_date_str = time_from.strftime(\"%Y-%m-%d %H:%M\")\r\n\t\tto_date_str\t = time_to.strftime(\"%Y-%m-%d %H:%M\")\r\n\r\n\tfor key in dlist:\r\n\t\tprint(key,dlist[key])\r\n\t\r\n\timport sqlite3\r\n\tconn=sqlite3.connect('/var/www/lab_app/lab_app.db')\r\n\tcurs=conn.cursor()\r\n\tt_cmd = \"SELECT * FROM temperatures WHERE rDateTime BETWEEN ? AND ?\", (from_date_str, to_date_str)\r\n\tprint(\"t_cmd \",t_cmd)\r\n\tcurs.execute(\"SELECT * FROM temperatures WHERE rDateTime BETWEEN ? AND ?\", (from_date_str, to_date_str))\r\n\ttemperatures \t= curs.fetchall()\r\n\tok_temps=[]\t\t\t\t\t\t\t# validate database records\r\n\tfor row in temperatures:\r\n\t\tif row[2] == None:\r\n\t\t\tprint(row)\t\t\t\t\t# log error records\r\n\t\telse:\r\n\t\t\tok_temps.append(row)\r\n\ttemperatures = ok_temps\r\n\t\r\n\tc_cmd = \"SELECT * FROM humidities WHERE rDateTime BETWEEN ? AND ?\", (from_date_str, to_date_str)\r\n\tprint(\"c_cmd \",c_cmd)\r\n\tcurs.execute(\"SELECT * FROM humidities WHERE rDateTime BETWEEN ? AND ?\", (from_date_str, to_date_str))\r\n\thumidities \t\t= curs.fetchall()\r\n\tok_humids=[]\t\t\t\t\t\t\t# validate database records\r\n\tfor row in humidities:\r\n\t\tif row[2] == None:\r\n\t\t\tprint(row)\t\t\t\t\t# log error records\r\n\t\telse:\r\n\t\t\tok_humids.append(row)\r\n\thumidities = ok_humids\r\n\t\r\n\tconn.close()\r\n\treturn [temperatures, humidities, from_date_str, to_date_str]\r\n\r\ndef validate_date(d):\r\n\ttry:\r\n\t\tdatetime.datetime.strptime(d, '%Y-%m-%d %H:%M')\r\n\t\treturn True\r\n\texcept ValueError:\r\n\t\treturn False\r\n\r\nif __name__ == \"__main__\":\r\n#\tprint \"Starting __main__\"\r\n\tapp.run(host='0.0.0.0', port=8080)\r\n\t" }, { "alpha_fraction": 0.6758349537849426, "alphanum_fraction": 0.683693528175354, "avg_line_length": 18.440000534057617, "blob_id": "c9617eaefe865b81e9b9fb23fc56d8472151fed3", "content_id": "0dc6f7c6e0cb10580322519682cf93cfb25f6a66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 509, "license_type": "no_license", "max_line_length": 82, "num_lines": 25, "path": "/lab_app_uwsgi.ini", "repo_name": "turbinetamer/lab_app", "src_encoding": "UTF-8", "text": "#Full path: /var/www/lab_app/lab_app_uwsgi.ini\r\n\r\n[uwsgi]\r\n#application's base folder\r\nbase = /var/www/lab_app\r\n\r\n#python module to import\r\n#app = hello\r\napp = lab_app\r\nmodule = %(app)\r\n\r\nhome = %(base)/venv\r\npythonpath = %(base)\r\n\r\n#socket file's location\r\nsocket = /var/www/lab_app/%n.sock\r\n\r\n#permissions for the socket file\r\nchmod-socket = 666\r\n\r\n#the variable that holds a flask application inside the module imported at line #6\r\ncallable = app\r\n\r\n#location of log files\r\nlogto = /var/log/uwsgi/%n.log" }, { "alpha_fraction": 0.6648841500282288, "alphanum_fraction": 0.7023172974586487, "avg_line_length": 26.43037986755371, "blob_id": "12fd26a051184c5d80ca56e9873fce86c39ef590", "content_id": "7a88f8ce7c99f70022e49c404cac157e7235107a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2244, "license_type": "no_license", "max_line_length": 101, "num_lines": 79, "path": "/env_log.py", "repo_name": "turbinetamer/lab_app", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n\r\n'''\r\nFILE NAME\r\nenv_log.py\r\n1. WHAT IT DOES\r\nTakes a reading from a DHT sensor and records the values in an SQLite3 database using a Raspberry Pi.\r\n \r\n2. REQUIRES\r\n* Any Raspberry Pi\r\n* A DHT sensor\r\n* A 10kOhm resistor\r\n* Jumper wires\r\n3. ORIGINAL WORK\r\nRaspberry Full stack 2015, Peter Dalmaris\r\n4. HARDWARE\r\nD17: Data pin for sensor\r\n5. SOFTWARE\r\nCommand line terminal\r\nSimple text editor\r\nLibraries:\r\nimport sqlite3\r\nimport sys\r\nimport Adafruit_DHT\r\n6. WARNING!\r\nNone\r\n7. CREATED \r\n8. TYPICAL OUTPUT\r\nNo text output. Two new records are inserted in the database when the script is executed\r\n // 9. COMMENTS\r\n--\r\n // 10. END\r\n'''\r\n\r\n\r\n\r\nimport sqlite3\r\nimport sys\r\n#import Adafruit_DHT\r\n\r\ndef log_values(sensor_id, temp, hum):\r\n\tconn=sqlite3.connect('/var/www/lab_app/lab_app.db') #It is important to provide an\r\n\t\t\t\t\t\t\t #absolute path to the database\r\n\t\t\t\t\t\t\t #file, otherwise Cron won't be\r\n\t\t\t\t\t\t\t #able to find it!\r\n\tcurs=conn.cursor()\r\n\tcurs.execute(\"\"\"INSERT INTO temperatures values(datetime(CURRENT_TIMESTAMP, 'localtime'),\r\n (?), (?))\"\"\", (sensor_id,temp))\r\n\tcurs.execute(\"\"\"INSERT INTO humidities values(datetime(CURRENT_TIMESTAMP, 'localtime'),\r\n (?), (?))\"\"\", (sensor_id,hum))\r\n\tconn.commit()\r\n\tconn.close()\r\n\r\n#humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302, 17)\r\n# If you don't have a sensor but still wish to run this program, comment out all the \r\n# sensor related lines, and uncomment the following lines (these will produce random\r\n# numbers for the temperature and humidity variables):\r\n# import random\r\n# humidity = random.randint(1,100)\r\n# temperature = random.randint(10,30)\r\n\r\n# use the MAX38155 Themocouple to read db values\r\n# use the internal temperature in then place of the humidity\r\nimport time, logging, math\r\nimport Adafruit_GPIO as GPIO\r\nimport Adafruit_GPIO.SPI as SPI\r\nimport Adafruit_MAX31855.MAX31855 as MAX31855\r\n\r\nSPI_PORT = 0\r\nSPI_DEVICE = 0\r\nsensor = MAX31855.MAX31855(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=5000000))\r\n\r\ntemperature = sensor.readTempC()\r\nhumidity = sensor.readInternalC()\r\n\r\nif humidity is not None and temperature is not None:\r\n\tlog_values(\"1\", temperature, humidity)\t\r\nelse:\r\n\tlog_values(\"1\", -999, -999)" } ]
3
gong-qi/gong_qi
https://github.com/gong-qi/gong_qi
26ce4c122266aa224428bb9b2542130396984343
fa53253e2d54df43657e7832f115669c1457f047
2d1cd1c0b2cd7cb4bcb016ff66ac2d7a66bc7181
refs/heads/master
2022-06-20T06:19:03.483234
2020-05-13T07:34:07
2020-05-13T07:34:07
263,548,041
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.31578946113586426, "alphanum_fraction": 0.31578946113586426, "avg_line_length": 8, "blob_id": "e1d1ef15ae38102cb600323bc50c9a9df0525743", "content_id": "25bfd5be53f02b3581f98c11fae4b1a2bd6792ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 27, "license_type": "no_license", "max_line_length": 8, "num_lines": 2, "path": "/register.py", "repo_name": "gong-qi/gong_qi", "src_encoding": "UTF-8", "text": "a = '宫七'\nb = '小艾'\n\n" } ]
1
HassanHaji90/CNN-based-NCMRA-dealiasing
https://github.com/HassanHaji90/CNN-based-NCMRA-dealiasing
06d396a4ab286bb180678052b983870cca7882dc
2d692296d2dace5371e8fe95e5514a5bb858c487
6738b8538f131311b1eee1e94324459dee36f7da
refs/heads/master
2020-05-19T22:15:46.029667
2019-05-06T17:42:55
2019-05-06T17:42:55
185,243,529
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7222222089767456, "alphanum_fraction": 0.7222222089767456, "avg_line_length": 16.5, "blob_id": "27cb92341a0527701d0e2c1fa1c5353bbe9f5785", "content_id": "03ed10f61254458204bca638460072efdfe0ff66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 36, "license_type": "no_license", "max_line_length": 22, "num_lines": 2, "path": "/Code_sub.py", "repo_name": "HassanHaji90/CNN-based-NCMRA-dealiasing", "src_encoding": "UTF-8", "text": "\n## importing functions\n# Hi Daming\n" } ]
1
shira19-meet/meet2017y1lab3
https://github.com/shira19-meet/meet2017y1lab3
3f2acc37a3fd6724304c7f3ec51979432e169d0c
556749230f540463ea7a714221836e140d5614f2
c2d1e7de220a499be06e06eda50e5b9d65c109b1
refs/heads/master
2020-12-02T11:34:34.701444
2017-07-25T13:48:48
2017-07-25T13:48:48
96,653,924
0
0
null
2017-07-09T01:27:00
2017-06-26T05:28:19
2017-07-02T22:37:34
null
[ { "alpha_fraction": 0.48124998807907104, "alphanum_fraction": 0.5062500238418579, "avg_line_length": 21.85714340209961, "blob_id": "71b6251fb66e4f515c9d276d54976e56947ae740", "content_id": "b3121a7be62d539746c96c07af7f3c79569c17a1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 160, "license_type": "permissive", "max_line_length": 48, "num_lines": 7, "path": "/randomname.py", "repo_name": "shira19-meet/meet2017y1lab3", "src_encoding": "UTF-8", "text": "\"Don't\" + \"forget\" + \"to\" + \"conserve\" + \"water\"\n'Don't' + ' forget' + 'to' + ' conserve ' +\n'water'\n\"the\"*3\n'the' + 3\n\"the\"*3 + \"beautiful\" + \"Earth\"\n2*\"True\"\n" }, { "alpha_fraction": 0.7346938848495483, "alphanum_fraction": 0.7346938848495483, "avg_line_length": 23.5, "blob_id": "2c449a9dff489c986148c6b3a866cab35f49d09f", "content_id": "3fea158706fdb5010426741e31d91492f613e808", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 49, "license_type": "permissive", "max_line_length": 34, "num_lines": 2, "path": "/Ages.py", "repo_name": "shira19-meet/meet2017y1lab3", "src_encoding": "UTF-8", "text": "someone=input (\"what is you age?\")\nprint(someone\n" }, { "alpha_fraction": 0.5894736647605896, "alphanum_fraction": 0.5894736647605896, "avg_line_length": 22.75, "blob_id": "56c1d41667c06081330457e46bc1724c9a8d3681", "content_id": "d07ae32a21bd867032a12533d816749dd17c3467", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 119, "license_type": "permissive", "max_line_length": 31, "num_lines": 4, "path": "/HelloWorld.py", "repo_name": "shira19-meet/meet2017y1lab3", "src_encoding": "UTF-8", "text": "print (\"hello world\")\nprint (\"shalom olam\")\nprint (\"नमस्ते दुनिया\")\nprint (\"hi, my name is shira.\")\n" }, { "alpha_fraction": 0.5936073064804077, "alphanum_fraction": 0.5936073064804077, "avg_line_length": 26.25, "blob_id": "1fcb5dd8d126a685bc0b94a7b817f59075fafe5a", "content_id": "805bb6762fa20fe6216331a7960a22e00e4c8011", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 219, "license_type": "permissive", "max_line_length": 43, "num_lines": 8, "path": "/specialCharacters.py", "repo_name": "shira19-meet/meet2017y1lab3", "src_encoding": "UTF-8", "text": "print (\"\\\"hi!\\\" \")\nprint (\"\\'hello!\\'\")\nprint (\" \\\\ its\\\\fun\\\\\")\nprint (\"first \\n second\")\nprint (\"no tab \\t tab\")\nprint (\"instructor alex asks,\")\nprint (\"\\\"what are you learning today?\\\" \")\nprint (\"the student reply'\n\n" } ]
4
jeremyblalock/precede
https://github.com/jeremyblalock/precede
79cff48d11071f2e57d294e4822347be75267e13
429cc0aaafa4a782a64cdec51469eb18cdc50f63
a52d8de6f4c68274e83d6acbdcfc5d7b22ccd24f
refs/heads/master
2021-01-19T03:13:57.207571
2012-07-19T18:22:28
2012-07-19T18:22:28
5,106,887
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7153284549713135, "alphanum_fraction": 0.7226277589797974, "avg_line_length": 21.5, "blob_id": "7e7ec58eb407cabb2ec517c81e98e6d1a7bf4b54", "content_id": "a409fb59a5f8b45a1edeacb79c1649fd736e2237", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 137, "license_type": "no_license", "max_line_length": 43, "num_lines": 6, "path": "/tests/unittest.py", "repo_name": "jeremyblalock/precede", "src_encoding": "UTF-8", "text": "import os, sys, unittest\n\n# Hack to allow test class to access module\nsys.path.insert(0, os.path.abspath('..'))\n\nimport datastore.core\n\n\n" }, { "alpha_fraction": 0.7346938848495483, "alphanum_fraction": 0.7346938848495483, "avg_line_length": 18.600000381469727, "blob_id": "e942dfb66abbc1fa74be95325b715ee5ce8ab687", "content_id": "9723ed2a0d136e616fb1f5b289a25e797a609e63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 98, "license_type": "no_license", "max_line_length": 31, "num_lines": 5, "path": "/datastore/core.py", "repo_name": "jeremyblalock/precede", "src_encoding": "UTF-8", "text": "from datastore import Datastore\n\ndef initdb(filename):\n db = datastore(filename)\n return db\n" }, { "alpha_fraction": 0.5412311553955078, "alphanum_fraction": 0.5412311553955078, "avg_line_length": 38.1363639831543, "blob_id": "13d8f04efe0ac748fda2f8ac6b423b53f5f2c465", "content_id": "5cacf99fe1c591843690be6f986dca59e011d04e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 861, "license_type": "no_license", "max_line_length": 99, "num_lines": 22, "path": "/datastore/datastore.py", "repo_name": "jeremyblalock/precede", "src_encoding": "UTF-8", "text": "import os\n\nclass Datastore(object):\n def __init__(self, filename):\n if not os.isdir(filename) and not os.path.exists:\n try:\n os.mkdir(os.path.expanduser(filename))\n except:\n raise Exception(\"Could not create directory '%s'\" % os.path.expanduser('filename'))\n try:\n datafile = open('%s/data' % filename, 'w')\n indexfile = open('%s/index' % filename, 'w')\n except:\n raise Exception(\"Could not create database files\")\n\n elif os.path.exists:\n raise Exception('Specified filename is not a directory')\n try:\n self.datafile = open('%s/data' % filename, 'r+')\n self.index = open('%s/index' % filename, 'r+')\n except:\n raise Exception('Database files appear to be corrupted')\n" }, { "alpha_fraction": 0.7817745804786682, "alphanum_fraction": 0.7961630821228027, "avg_line_length": 58.57143020629883, "blob_id": "5be992be4f61bb6de7f8e97be276529c93f41d1b", "content_id": "fe36fe97669cb33f3ebd1f1e590cd459dc8a2b46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 417, "license_type": "no_license", "max_line_length": 234, "num_lines": 7, "path": "/README.md", "repo_name": "jeremyblalock/precede", "src_encoding": "UTF-8", "text": "Precede\n=======\nProject started by Jeremy Blalock, July 19th 2012.\n## Mission\nMission: Make open, intelligent analytics and statistical prediction available to the public.\n## Implementation\nA python library consisting of functions to parse, regress, link, and analyze data of any format. Includes built-in protocols for working with text-based and other qualitative data sources, as well as traditional quantitative sources.\n" } ]
4
spolichnowski/motion-detector-openCV
https://github.com/spolichnowski/motion-detector-openCV
6396bfb28bdfcbc86ff2ef2be56771682b64a7d8
9bdf782ee46f6b40e0d5c5feadfc592078baebe2
b801a601780d9be86a150ce06ee7c514db534059
refs/heads/main
2023-02-18T09:06:04.649295
2021-01-16T15:34:41
2021-01-16T15:34:41
330,189,497
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7238627076148987, "alphanum_fraction": 0.7398244142532349, "avg_line_length": 23.096153259277344, "blob_id": "d3f7399843853cc194e2f0529b9ac171df00cc22", "content_id": "3d333bf6a624036c007fccc044f8596935b1402c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1253, "license_type": "no_license", "max_line_length": 161, "num_lines": 52, "path": "/README.md", "repo_name": "spolichnowski/motion-detector-openCV", "src_encoding": "UTF-8", "text": "## Motion detector\n\n> Motion detector created with internet camera and a few lines of Python code. App is using openCV for video capture and detection.\n\n## Technologies\n\nProject is created with:\n\n- Python version: 3.6.6\n- Numpy version: 1.19.5\n- Opencv-contrib-python version: 4.4.0.44\n- Opencv-python version: 4.3.0.36\n\n## Setup\n\n### To run this project:\n\nFirst of all make sure that you have Python version 3.6.6 installed on your machine.\nPrepare virtual environment, for example with:\n\n- pyenv (https://github.com/pyenv/pyenv-virtualenv)\n- conda (https://docs.conda.io/projects/conda/en/latest/user-guide/concepts/environments.html)\n- venv (https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/)\n\nAfter creating and running your virtual environment make sure that your 'pip' package installer is working. Check its version for a test and if needed update it:\n\n```\n$ pip --version\n$ pip install --upgrade pip\n```\n\nNow time to install all the requirements like:\n\n```\n$ cd ../'project folder'\n$ pip install -r requirements.txt\n```\n\nIf all the requirements has been installed time to run our application!\n\n```\n$ python main.py\n```\n\n## Status\n\nProject is: _in progress_\n\n## Contact\n\nInstagram: @code.with.stan\nEmail: [email protected]\n" }, { "alpha_fraction": 0.5999106168746948, "alphanum_fraction": 0.6164506077766418, "avg_line_length": 28.8266658782959, "blob_id": "50473c01fce10dd471883b0fcd0b3738a9cf433e", "content_id": "ea979ff7c6a7c69116ffc4f824fe3c7e62cb59c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2237, "license_type": "no_license", "max_line_length": 80, "num_lines": 75, "path": "/main.py", "repo_name": "spolichnowski/motion-detector-openCV", "src_encoding": "UTF-8", "text": "from cv2 import cv2 as cv \nimport time\nimport os\n\n# Displays (and reads) given worning on the screen of your laptop (only mac os) \ndef notify(title, text):\n os.system(\"\"\"\n osascript -e 'display notification \"{}\" with title \"{}\"'\n \"\"\".format(text, title))\n os.system('say \"Intruder is coming!\"')\n\n\n# Defines a video capture object, creates empty variable static_bg \n# that will be later used to detect changes in the video \nvid = cv.VideoCapture(0) \nstatic_bg = None\n\n# First pick of my camera was always dark so I added 5 second pause\ntime.sleep(5)\n\nwhile(True): \n motion = 0 \n # Capture the video frame \n # by frame \n ret, frame = vid.read() \n \n # Flips frame horizontally, converts it to grayscale\n # and adds Gaussian to reduce noise and details\n flip = cv.flip(frame, 1)\n gray_frame = cv.cvtColor(flip, cv.COLOR_BGR2GRAY)\n gray_img = cv.GaussianBlur(gray_frame, (21,21), 0)\n \n # Assigns starting background to our static_bg\n if static_bg is None:\n static_bg = gray_img\n continue\n \n # Calculates the difference to distinguish new objects on the frame\n difference = cv.absdiff(static_bg,gray_img)\n \n \n # Adds thresholding, noises removal \n threshold = cv.threshold(difference, 70, 255, cv.THRESH_BINARY)[1]\n thresh = cv.dilate(threshold, None, iterations = 2)\n \n \n cnts,_ = cv.findContours(thresh.copy(), \n cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) \n \n for contour in cnts: \n if cv.contourArea(contour) < 10000:\n continue\n motion = 1\n \n (x, y, w, h) = cv.boundingRect(contour) \n # making green rectangle arround the moving object \n cv.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3)\n \n # Uncomment to display the frame\n cv.imshow('Thresh', thresh) \n \n # If there is motion sends alert \n if motion == 1:\n time.sleep(1)\n notify(\"Alert\", \"Detected unknown movement.\")\n time.sleep(4)\n \n # Press 'q' to quit or 'ctrl c'\n if cv.waitKey(1) & 0xFF == ord('q'): \n break\n \n# After the loop release the cap object, \n# destroys all the windows\nvid.release() \ncv.destroyAllWindows() " }, { "alpha_fraction": 0.5142857432365417, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 22.33333396911621, "blob_id": "2829ce1d8dfd99fc08eb1ad76ba3806e673d95f1", "content_id": "f28d6544f0945bd9056d0fa6b8f4701f39aeeb3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 70, "license_type": "no_license", "max_line_length": 31, "num_lines": 3, "path": "/requirements.txt", "repo_name": "spolichnowski/motion-detector-openCV", "src_encoding": "UTF-8", "text": "numpy==1.19.5\nopencv-contrib-python==4.4.0.44\nopencv-python==4.3.0.36\n" } ]
3
Cauverypraba/data-structure
https://github.com/Cauverypraba/data-structure
8d503f1c86756321f50c41bd2962a77cea243ac7
a0e64fa371a85b243bdac6c031ccc2aa95b68f05
1c7100a53d1301587ef81bb5cfdda8240e45a262
refs/heads/main
2023-05-26T03:21:09.787097
2023-05-20T06:34:20
2023-05-20T06:34:20
332,737,526
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4933803975582123, "alphanum_fraction": 0.499558687210083, "avg_line_length": 21.459999084472656, "blob_id": "b209cbcd550b511910e984bb57c6ab5343243241", "content_id": "b62d5d12f68ad73656c26b3362bce79c2f2b3fcc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1133, "license_type": "no_license", "max_line_length": 55, "num_lines": 50, "path": "/Queue.py", "repo_name": "Cauverypraba/data-structure", "src_encoding": "UTF-8", "text": "'''Implementation of Queue using Singly Linked List '''\nclass Node():\n def __init__(self, value):\n self.value = value\n self.next = None\n\nclass Queue():\n def __init__(self):\n self.head = None\n self.tail = None\n \n def isEmpty(self):\n return self.head == None\n\n def enqueue(self, value):\n node = Node(value)\n if self.tail == None:\n self.head = self.tail = node\n print('inside')\n self.tail.next = node\n self.tail = node\n\n def dequeue(self):\n if self.isEmpty():\n return\n temp = self.head\n self.head = temp.next\n \n def printQueue(self):\n temp = self.head\n # print(temp.value)\n queue = [] \n while(temp):\n # print(temp.value)\n queue.append(temp.value)\n temp = temp.next\n # print(temp.value)\n print(\"Queue:\",queue)\n\nif __name__== '__main__':\n q = Queue()\n q.enqueue(10)\n q.enqueue(8)\n q.enqueue(28)\n q.enqueue(32)\n q.dequeue()\n q.dequeue()\n q.dequeue()\n q.dequeue()\n q.printQueue() \n\n\n" }, { "alpha_fraction": 0.5437940955162048, "alphanum_fraction": 0.5520963072776794, "avg_line_length": 29.112499237060547, "blob_id": "6ec54ac40cc4764a82b435ac7e8f8201293a9a5d", "content_id": "520cc6ded5f0f80e9f82f5008fd4fbbf382a4752", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2409, "license_type": "no_license", "max_line_length": 80, "num_lines": 80, "path": "/dynamic_array.py", "repo_name": "Cauverypraba/data-structure", "src_encoding": "UTF-8", "text": "class Dynamic():\n \"\"\" Dynamic Array implementation \"\"\"\n def __init__(self):\n self.capacity = 1\n self.dynamic_array = [0] * self.capacity\n self.substitute_array = []\n self.array_length = 0\n \n def len(self):\n \"\"\"\n Method to get the length of array \n returns: int\n \"\"\"\n return self.array_length\n \n def getItem(self, element):\n \"\"\"\n Method to get particular item from an array\n param: element: int\n returns: int\n \"\"\"\n if not 0 <= element <self.array_length:\n return IndexError('Element is out of bound')\n return self.dynamic_array[element] \n \n def append(self, element):\n \"\"\"\n Method to add element at last of an array, \n if length is greater than capacity calls resize() to increase the length\n param: element: int\n returns: list\n \"\"\"\n if self.array_length == self.capacity: \n self.resize(2 * self.capacity)\n self.dynamic_array[self.array_length] = element\n self.array_length += 1\n return self.dynamic_array \n \n def insertAt(self, index, element):\n \"\"\"\n Method to insert element at particular index\n params: index, element: int, int\n returns: list\n \"\"\"\n if self.array_length == self.capacity: \n self.resize(2 * self.capacity)\n self.dynamic_array[index] = element\n self.array_length += 1\n return self.dynamic_array\n\n def remove(self, index):\n \"\"\"\n Method to remove element in an array\n param: index: int\n returns: array\n \"\"\"\n if self.array_length > self.capacity:\n print(\"Only elements within the range can be deleted\")\n self.dynamic_array.pop(index)\n return self.dynamic_array \n\n def resize(self, new_cap):\n \"\"\"\n Method to increase the size of array \n \"\"\"\n self.substitute_array = [0] * new_cap\n for iter in range(self.array_length): \n self.substitute_array[iter] = self.dynamic_array[iter] \n \n self.dynamic_array = self.substitute_array\n self.capacity = new_cap\n \nif __name__ == '__main__': \n obj = Dynamic()\n obj.append(13)\n obj.append(22)\n obj.append(6)\n obj.append(18)\n obj.insertAt(7,20)\n obj.remove(7)\n" }, { "alpha_fraction": 0.5267326831817627, "alphanum_fraction": 0.5333333611488342, "avg_line_length": 23.8360652923584, "blob_id": "bf3e9cd22b3831ed35b8af849caf4a71082f7d86", "content_id": "a177548a115faef46d49167bf1e311aabdabcc2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1515, "license_type": "no_license", "max_line_length": 63, "num_lines": 61, "path": "/Stack.py", "repo_name": "Cauverypraba/data-structure", "src_encoding": "UTF-8", "text": "'''Implementing a Stack using Singly Linked List.'''\nclass Node():\n def __init__(self, value):\n self.value = value\n self.next = None\n \nclass Stack():\n def __init__(self):\n self.head = Node(\"head\")\n self.size = 0\n\n # To get the size of stack\n def getSize(self):\n return self.size\n\n # To check whether the stack is empty\n def isEmpty(self):\n return self.size == 0 \n \n # To get top value from the stack\n def peek(self):\n if self.isEmpty():\n raise Exception(\"Cannot peek from a empty stack..\")\n print(\"Peek element: \", self.head.next.value)\n\n # To insert value into stack\n def push(self, value):\n node = Node(value)\n node.next = self.head.next\n self.head.next = node\n self.size += 1 \n \n # To remove value from stack\n def pop(self):\n if self.isEmpty():\n raise Exception(\"Cannot pop from a empty stack..\")\n temp = self.head.next\n self.head.next = temp.next\n temp = None\n self.size -= 1 \n\n def printStack(self):\n temp = self.head.next\n stack = [] \n while(temp):\n stack.append(temp.value)\n temp = temp.next\n print(\"Stack: \",stack) \n\nif __name__ == \"__main__\":\n stack = Stack()\n stack.push(1)\n stack.push(2)\n stack.push(3)\n stack.push(4)\n stack.push(5)\n stack.push(6)\n stack.peek()\n stack.pop()\n stack.pop()\n stack.printStack()\n" }, { "alpha_fraction": 0.5850388407707214, "alphanum_fraction": 0.5913902521133423, "avg_line_length": 24.513513565063477, "blob_id": "ee7e53c826311f549beec242bfd5def8c3b409e2", "content_id": "f8f96c54c5e06d2aa180f59a5dbd3ffcce743477", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2834, "license_type": "no_license", "max_line_length": 78, "num_lines": 111, "path": "/binary_search_tree.py", "repo_name": "Cauverypraba/data-structure", "src_encoding": "UTF-8", "text": "class Node:\n def __init__(self, key):\n self.left = None\n self.right = None\n self.val = key\n\ndef search(root, key):\n if root is None or root.val == key:\n return root\n else:\n if key > root.val:\n return search(root.right, key)\n return search(root.left, key)\n\n# Function to do inorder traversal of BST.\ndef inorder(root):\n if root:\n inorder(root.left)\n print(root.val)\n inorder(root.right)\n\n# Function to do preorder traversal of BST.\ndef preorder(root):\n if root:\n print(root.val)\n preorder(root.left)\n preorder(root.right)\n\n# Function to do postorder traversal of BST.\ndef postorder(root):\n if root:\n postorder(root.left)\n postorder(root.right)\n print(root.val)\n\n# Function to insert a new node in BST.\ndef insertElement(root, key):\n if root is None:\n return Node(key)\n else: \n if root.val == key:\n return root \n elif root.val < key:\n root.right = insertElement(root.right, key)\n else:\n root.left = insertElement(root.left, key) \n return root\n\n# This function returns the min key value of a node, \n# instead of searching an entire tree.\ndef minValueNode(node):\n curr = node\n while curr.left is not None:\n curr = node.left\n return curr \n\n# Function that removes a node from Binary Search Tree and returns a new root.\ndef deleteNode(root, key):\n if root is None:\n return root \n if key < root.val:\n root.left = deleteNode(root.left, key)\n elif key > root.val:\n root.right = deleteNode(root.right, key)\n # If key is same as root's key, then this is the node\n # to be deleted \n else:\n # Node with only one child or no child\n if root.left == None:\n temp = root.right\n root = None\n return temp\n elif root.right == None:\n temp = root.left\n root = None\n return temp\n\n # Node with two children:\n # Get the inorder successor\n # (smallest in the right subtree) \n temp = minValueNode(root.right)\n \n # Copy the inorder successor's\n # content to this node\n root.val = temp.val \n \n # Delete the inorder successor\n root.right = deleteNode(root.right, key) \n return root \n \n\nr = Node(50)\nr = insertElement(r, 30)\nr = insertElement(r, 20)\nr = insertElement(r, 40)\nr = insertElement(r, 70)\nr = insertElement(r, 60)\nr = insertElement(r, 80)\n\nprint('Inorder Traversal of BST')\ninorder(r)\nprint('Preorder Traversal of BST')\npreorder(r)\nprint('Postorder Traversal of BST')\npostorder(r)\n\nprint(\"\\nDelete 20\")\nr = deleteNode(r, 20)\n\nprint(\"Inorder traversal of the modified tree\")\ninorder(r)\n\n\n" }, { "alpha_fraction": 0.5805084705352783, "alphanum_fraction": 0.597842812538147, "avg_line_length": 19.927419662475586, "blob_id": "d4ff573d037112da666614bc6362985d792fbb56", "content_id": "e7df76c469ed2cd6d8dc8cafc475d0f890e58447", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2596, "license_type": "no_license", "max_line_length": 82, "num_lines": 124, "path": "/priority_queue.py", "repo_name": "Cauverypraba/data-structure", "src_encoding": "UTF-8", "text": "'''Implementing Priority Queue using Binary Heap'''\narray = [0]*50\nsize = -1\n\n# Function to return parent of a given element\ndef parent(i):\n return (i - 1) // 2\n\n# Function to return leftside element\ndef leftChild(i):\n return ((2 * i) + 1)\n\n# Function to return rightside element\ndef rightChild(i):\n return ((2 * i) + 2) \n\n# Function to shiftUp the heap priority\ndef shiftUp(i):\n while (i > 0 and array[parent(i)] < array[i]) :\n # Swap parent and current node\n swap(parent(i), i)\n # Update i to parent of i\n i = parent(i)\n\n# Function to shiftDown the heap priority\ndef shiftDown(i):\n maxIndex = i\n l = leftChild(i)\n if l <= size and array[l] > array[maxIndex]:\n maxIndex = l\n \n r = rightChild(i)\n if r <= size and array[r] > array[maxIndex]:\n maxIndex = r\n \n # If i is not same as maxIndex\n if i != maxIndex:\n swap(i, maxIndex)\n shiftDown(maxIndex)\n\n# Function to insert element into heap with priority\ndef insert(p):\n global size\n size += 1\n array[size] = p\n shiftUp(size)\n\n# Function to extract maximum element\ndef poll():\n global size\n root = array[0]\n array[0] = array[size]\n size = size - 1 \n print('shiftdown')\n shiftDown(0)\n # return root \n\n\n#Function to get maximum element\ndef getMax():\n print(array[0])\n\n#Function to get minimum element\ndef getMin():\n print(array[size])\n\n# Function to change priority of an element\ndef changePriority(i, p):\n old_p = array[i]\n array[i] = p\n if old_p < p:\n shiftUp(i)\n else:\n shiftDown(i) \n \n# Function to remove elements from a heap\ndef remove(i):\n global size\n array.remove(i)\n size = size - 1\n shiftUp(i)\n # poll()\n return array\n \n\n# Function to swap elements\ndef swap(i, j) : \n temp = array[i]\n array[i] = array[j]\n array[j] = temp\n\ninsert(45)\ninsert(20)\ninsert(14)\ninsert(12)\ninsert(31)\ninsert(7)\ninsert(11)\ninsert(13)\ninsert(7)\nprint('Priority Queue after inserting elements: ',array)\npoll()\nprint(\"Priority Queue after polling highest priority element: \", end = ' ')\nj = 0\nprint('size',size)\nwhile (j <= size) :\n print(array[j], end = \" \")\n j += 1 \nprint() \ngetMax()\ngetMin()\nchangePriority(2, 49)\nprint(\"Priority Queue after changing the priority for a given element: \", end=' ')\nk = 0\nwhile (k <= size) :\n print(array[k], end = \" \")\n k += 1\nprint() \nremove(11)\nprint(\"Priority Queue after removing an element: \", end=' ')\nl = 0\nwhile (l <= size) :\n print(array[l], end = \" \")\n l += 1\n\n" }, { "alpha_fraction": 0.5492676496505737, "alphanum_fraction": 0.5529294013977051, "avg_line_length": 28.165048599243164, "blob_id": "6958f796debb5b11505e8d4b6b07f80e5b73ff4b", "content_id": "ab59de6b7e7bbc9845f26067f74347ef46681e40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3004, "license_type": "no_license", "max_line_length": 73, "num_lines": 103, "path": "/Doubly_Linked_List.py", "repo_name": "Cauverypraba/data-structure", "src_encoding": "UTF-8", "text": "class Node():\n # Initialises a node object with data and its address\n def __init__(self, next = None, prev = None, data = None):\n self.data = data\n self.next = next\n self.prev = prev\n\n# Class to perform doubly linked list functions using node object\nclass Doubly_List():\n # Function to initialise head\n def __init__(self, head):\n self.head = None\n\n # Function to insert data at beginning of the list\n def push(self, new_data):\n # nodes = []\n new_node = Node(data = new_data)\n\n # Point next of new_node as head\n new_node.next = self.head\n new_node.prev = None\n\n # Change prev of head node as newnode\n if self.head is not None:\n self.head.prev = new_node\n\n # Make new_node as head \n self.head = new_node\n\n # Function to insert a new node at a particular position\n def insertAt(self, prev_node, new_data):\n # Check if the given prev_node exists \n if prev_node is None: \n print(\"The given previous node must be in LinkedList.\")\n return\n # Create new node & put in the data \n new_node = Node(data = new_data) \n\n # Make next of new Node as next of prev_node \n new_node.next = prev_node.next\n\n # Make next of prev_node as new_node \n prev_node.next = new_node\n\n # Make prev node as previous of new node\n new_node.prev = prev_node\n\n # Change previous of new_node's next node \n if new_node.next is not None:\n new_node.next.prev = new_node \n \n #Function to insert element at the end of a list\n def append(self, new_data):\n new_node = Node(data = new_data)\n node = self.head\n if self.head == None:\n self.head = new_node\n return\n while(node.next):\n # print('inside', node.data)\n node = node.next\n node.next = new_node\n new_node.prev = node \n \n # Function to delete a node\n def deleteNode(self,key):\n temp = self.head\n # check key to be deleted is a head node\n if temp is not None:\n if temp.data == key:\n self.head = temp.next\n temp = None\n # Traverse list until key matches the data in list \n while temp is not None:\n if temp.data == key:\n break\n prev = temp\n temp = temp.next\n if temp == None:\n return\n prev.next = temp.next\n temp = None \n\n # Function to print the list\n def printList(self, node):\n nodes = []\n while(node):\n nodes.append(node.data)\n # print(node.data)\n node = node.next\n nodes.append(\"None\")\n print(nodes) \n\nobj = Doubly_List(7)\nobj.push(5)\nobj.push(16)\nobj.push(8)\nobj.append(19)\nobj.deleteNode(8)\nobj.push(27)\nobj.insertAt(obj.head.next, 4)\nobj.printList(obj.head)\n# print(obj.head.next.data)\n" }, { "alpha_fraction": 0.5181422233581543, "alphanum_fraction": 0.5261248350143433, "avg_line_length": 23.872726440429688, "blob_id": "0c3ed7c904f89cb875030c7b5aab526d812546c8", "content_id": "ca71001385555f4a86632e0b38529a2a8b40ec05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1378, "license_type": "no_license", "max_line_length": 63, "num_lines": 55, "path": "/Stack2.py", "repo_name": "Cauverypraba/data-structure", "src_encoding": "UTF-8", "text": "class Stack2():\n class Node():\n def __init__(self, value, next):\n self.value = value\n self.next = None\n def __init__(self):\n self.head = None\n self.size = 0\n\n # To get the size of stack\n def getSize(self):\n return self.size\n\n # To check whether the stack is empty\n def isEmpty(self):\n return self.size == 0\n \n # To get top value from the stack\n def peek(self):\n if self.isEmpty():\n raise Exception(\"Cannot peek from a empty stack..\")\n print(\"Peek element: \",self.head.value)\n\n # To insert value into stack\n def push(self, value):\n self.head = self.Node(value, self.head)\n self.size += 1 \n \n # To remove value from stack\n def pop(self, key):\n if self.isEmpty():\n raise Exception(\"Cannot pop from a empty stack..\")\n result = self.head.value\n self.head = self.head.next\n print(result) \n\n def printStack(self):\n temp = self.head\n # print(temp.value)\n stack = [] \n while(temp):\n print(temp.value)\n stack.append(temp.value)\n temp = temp.next\n # print(temp.value)\n print(\"Stack: \",stack[::-1]) \n \nst = Stack2()\nst.push(1)\nst.push(2)\nst.push(3)\nst.push(4)\nst.peek()\nst.pop(4)\nst.printStack() " }, { "alpha_fraction": 0.5302547812461853, "alphanum_fraction": 0.5338375568389893, "avg_line_length": 28.552940368652344, "blob_id": "4f070a4e3201ddac71d8635e006ffcdbd98e6604", "content_id": "b4369335f5dc5f25fc3fa410a2af026723ab3018", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2512, "license_type": "no_license", "max_line_length": 73, "num_lines": 85, "path": "/singly_inked_list.py", "repo_name": "Cauverypraba/data-structure", "src_encoding": "UTF-8", "text": "class Node():\n def __init__(self, data):\n self.data = data\n self.next = None\n \nclass Linked_List():\n def __init__(self):\n self.head = None\n\n # Function to insert new data at the beginning\n def push(self, new_data):\n new_node = Node(new_data)\n # Point next of new_node as head\n new_node.next = self.head\n # Make new_node as head \n self.head = new_node\n\n # Function to insert a new node after a given previous node\n def insertAt(self, prev_node, new_data):\n # Check if the given prev_node exists \n if prev_node is None: \n print(\"The given previous node must in LinkedList.\")\n return\n # Create new node & put in the data \n new_node = Node(new_data) \n # Make next of new Node as next of prev_node \n new_node.next = prev_node.next\n # Make next of prev_node as new_node \n prev_node.next = new_node \n\n # To insert new node at the end\n def append(self, new_data): \n # Create a new node and put in the data then set next as None \n new_node = Node(new_data) \n # If the Linked List is empty, then make the new node as head \n if self.head is None: \n self.head = new_node \n return\n # Else traverse till the last node \n last = self.head \n while (last.next): \n last = last.next\n # Change the next of last node \n last.next = new_node \n\n # Function to delete a node\n def deleteNode(self,key):\n temp = self.head\n # check key to be deleted is a head node\n if temp is not None:\n if temp.data == key:\n self.head = temp.next\n temp = None\n # Traverse list until key matches the data in list \n while temp is not None:\n if temp.data == key:\n break\n prev = temp\n temp = temp.next\n if temp == None:\n print('inside')\n return\n prev.next = temp.next\n temp = None \n \n def printList(self): \n temp = self.head\n nodes = []\n while (temp): \n nodes.append(temp.data)\n print (temp.data) \n print(nodes)\n temp = temp.next\n nodes.append('None')\n print(nodes) \n\nli = Linked_List()\nli.push(5)\nli.push(9)\nli.push(2)\nli.insertAt(li.head.next,7)\nli.append(12)\nli.deleteNode(7)\nli.append(10)\nli.printList()\n" } ]
8
dawsonc/attack-estimation
https://github.com/dawsonc/attack-estimation
70fc9a8318ee983ee2811697a05849de6b85c21b
66421345a819f4cd9f394fe021a959515df54f9e
a62c4edf242d5e111d868b4e67ec518f5b931851
refs/heads/master
2020-08-02T14:17:57.139112
2019-11-15T19:26:00
2019-11-15T19:26:00
211,385,563
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6829268336296082, "alphanum_fraction": 0.8048780560493469, "avg_line_length": 19.5, "blob_id": "9db252fc30db743ee93f51e29bf5c27787812df4", "content_id": "2973cc40319cb4bae893e69f83d42c017608b058", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 41, "license_type": "no_license", "max_line_length": 20, "num_lines": 2, "path": "/README.md", "repo_name": "dawsonc/attack-estimation", "src_encoding": "UTF-8", "text": "# attack-estimation\n16.413 Final Project\n" }, { "alpha_fraction": 0.6268796920776367, "alphanum_fraction": 0.6306390762329102, "avg_line_length": 44.14545440673828, "blob_id": "5d8da70bb791b7a81dd9f426f57806008975ede7", "content_id": "498cba0b8ddc83b423d51e6bd36d27d9a292b735", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7448, "license_type": "no_license", "max_line_length": 138, "num_lines": 165, "path": "/bayes_net.py", "repo_name": "dawsonc/attack-estimation", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport networkx as nx\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pydot # Install graphviz in anaconda prompt!!!\n\n\n\ndef almost_equal(val1, val2, epsilon=0.0001):\n return abs(val1 - val2) < epsilon\n\n\"\"\"\nDefines a BayesNode object for tracking marginal or conditional probability distributions.\n\"\"\"\n\nclass BayesNode:\n def __init__(self, var_name):\n self.name = var_name\n # Maps from (parent, val) tuples to map from value to probability.\n # Parents are BayesNodes themselves.\n # E.g. set((A, True), (B, 9)) -> {1: 0.2, 2: 0.7, 3: 0.1}\n self.parents = []\n self.conditional_distribution = {}\n self.marginal_distribution = {}\n self.domain = set()\n \n # Defines the marginal distribution for a node, so there's no conditioning allowed. Explicitly\n # sets the domain as well.\n def set_marginal_distribution(self, distribution):\n assert not self.conditional_distribution, \"Can't set distribution if already have conditional dist.\"\n self.marginal_distribution = distribution\n self.domain = distribution.keys()\n \n # Defines part of the conditional distribution for a node. Only defines the distribution over the domain\n # for a particular setting of the parent values. I assume that the distribution explicitly mentions all\n # variables in the domain - a future feature could infer that values should be zero if left out.\n def add_entry(self, parent_vals, distribution):\n assert not self.marginal_distribution, \"Can't set conditional if already have marginal distribution \" + self.marginal_distribution\n # The distribution being passed in had better be proper.\n assert almost_equal(sum(distribution.values()), 1), \"Improper distribution passed in \" + str(distribution)\n # Convert the parent vals into a set because order doesn't matter; use frozenset to make hashable.\n conditioning_event = frozenset(parent_vals)\n assert conditioning_event not in self.conditional_distribution.keys(), \"Already have event for \" + str(conditioning_event)\n if self.domain:\n assert distribution.keys() == self.domain, \"Mismatched domains.\"\n else: # Haven't set domain yet, so do so now.\n self.domain = distribution.keys()\n self.parents = [parent_node for parent_node, val in parent_vals]\n # Check the parent domains as well.\n for parent_node, val in parent_vals:\n assert val in parent_node.domain, \"Couldn't find \" + str(val) + \" in parent node \" + str(parent_node) + \" domain.\"\n self.conditional_distribution[conditioning_event] = distribution\n \n def get_prob_value(self, val, parent_vals=None):\n if parent_vals is None:\n assert not self.parents, \"Cannot ask for probability without giving parent values\"\n if not self.parents:\n return self.marginal_distribution.get(val)\n # Turn the parent assignments into a set.\n conditioning_event = frozenset(parent_vals)\n return self.conditional_distribution.get(conditioning_event).get(val)\n \n def draw_sample(self, parent_vals=None):\n if parent_vals is None:\n assert not self.parents, \"Cannot ask for a sample without giving parent values\"\n relevant_distribution = None\n if not self.parents:\n relevant_distribution = self.marginal_distribution\n else: # Same idea as for marginal, but with the conditional distribution.\n conditioning_event = frozenset(parent_vals)\n relevant_distribution = self.conditional_distribution.get(conditioning_event)\n relevant_values = [entry[0] for entry in sorted(relevant_distribution.items())]\n relevant_probabilities = [entry[1] for entry in sorted(relevant_distribution.items())] \n return np.random.choice(relevant_values, p=relevant_probabilities)\n \n def __str__(self):\n return self.name\n \n \n\n\"\"\"\nDefines a BayesNet object. Just a holder for a bunch of nodes.\n\"\"\"\n\nclass BayesNet:\n def __init__(self, nodes):\n self.nodes = nodes\n # Helper lookup map that goes from a variable name to the node itself (with the distribution info)\n self.name_to_nodes = {}\n for node in nodes:\n self.name_to_nodes[node.name] = node\n # Helper map goes from a node to its children\n self.node_to_children = {}\n for node in nodes:\n self.node_to_children[node] = [] # Initialize empty\n for node in nodes:\n for parent_node in node.parents:\n self.node_to_children[parent_node].append(node)\n\n # This would also be a great place to do sanity checks on the distributions themselves fully specifying\n # the distributions and summing to 1.\n # Could also come up with some sort of topographical ordering (and check that there are no loops)\n \n def get_node(self, name):\n assert name in self.name_to_nodes.keys(), \"Could not find node named \" + name\n return self.name_to_nodes.get(name)\n \n # Given assignments for all the variables, return the probability of that assignment\n def calc_joint(self, var_assignments):\n assert len(var_assignments) == len(self.nodes)\n running_prob = 1.0\n for var, value in var_assignments:\n # Loop up the corresponding probability, which means I also need to check parents and their values.\n if not var.parents:\n marginal_prob = var.get_prob_value(value)\n running_prob = running_prob * marginal_prob\n continue\n # Must look up parents and their values.\n parent_assignments = []\n for possible_var, possible_val in var_assignments:\n if possible_var in var.parents:\n parent_assignments.append((possible_var, possible_val))\n fetched_prob = var.get_prob_value(value, parent_assignments)\n running_prob = running_prob * fetched_prob\n return running_prob\n \n def get_topological_ordering(self):\n ordered = []\n while len(ordered) < len(self.nodes):\n for node in self.nodes:\n if node in ordered:\n continue\n parents_already_added = True\n for parent in node.parents:\n if parent not in ordered:\n parents_already_added = False\n break\n if parents_already_added:\n ordered.append(node)\n return ordered\n \n def get_children(self, node):\n return self.node_to_children.get(node)\n\n def draw_net(self):\n # Use graphviz layout and dot.\n nxg = nx.DiGraph()\n edges = []\n for node in self.nodes:\n if node.parents:\n edges.extend([(parent, node) for parent in node.parents])\n nxg.add_edges_from(edges)\n \n # Define the node labels\n node_labels = {}\n for node in self.nodes:\n node_labels[node] = node.name\n \n # Define some layout.\n pos = nx.nx_pydot.graphviz_layout(nxg, prog='dot')\n nx.draw_networkx_nodes(nxg, pos)\n nx.draw_networkx_edges(nxg, pos, edges)\n nx.draw_networkx_labels(nxg, pos, node_labels, font_size=16)\n plt.axis('off')\n plt.show()" } ]
2
MADRobotNO/Simple_NEAT_v0.2
https://github.com/MADRobotNO/Simple_NEAT_v0.2
f8e638445720327db300aa0ea1bd693861c424e0
2822a7382399a2e1f3d7c66412c8f922597ed429
7b8af06a71a807c711ab9fa0409a8f0aec996c87
refs/heads/master
2023-04-16T06:30:20.275501
2021-04-07T19:55:57
2021-04-07T19:55:57
353,122,348
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4275861978530884, "alphanum_fraction": 0.517241358757019, "avg_line_length": 25.363636016845703, "blob_id": "741015a16e864037bf2a1ee409b52638495ec5a9", "content_id": "dc31b1b95d69f9508201ea6634e61dfb07a6939d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 290, "license_type": "no_license", "max_line_length": 68, "num_lines": 11, "path": "/RandomData.py", "repo_name": "MADRobotNO/Simple_NEAT_v0.2", "src_encoding": "UTF-8", "text": "import random\n\n\nclass Xor:\n def __init__(self):\n self.data = [[0.0, 1.0], [1.0, 0.0], [1.0, 1.0], [0.0, 0.0]]\n self.targets = [[1.0], [1.0], [0.0], [0.0]]\n\n def getRandomXorData(self):\n random_number = random.randint(0, 4)\n return self.data[random_number]\n" }, { "alpha_fraction": 0.5689548254013062, "alphanum_fraction": 0.5800865888595581, "avg_line_length": 31.34000015258789, "blob_id": "43629f43912f71c5cf4e0d4000726482eac23329", "content_id": "0ae647865748cf09fa0e29d9e8f81770ae8e4a5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1617, "license_type": "no_license", "max_line_length": 121, "num_lines": 50, "path": "/Node.py", "repo_name": "MADRobotNO/Simple_NEAT_v0.2", "src_encoding": "UTF-8", "text": "import numpy as np\n\n\nclass Node:\n\n INPUT_NODE = \"input\"\n HIDDEN_NODE = \"hidden\"\n OUTPUT_NODE = \"output\"\n\n node_types = [INPUT_NODE, HIDDEN_NODE, OUTPUT_NODE]\n\n TANH_ACTIVATION_FUNCTION = 1\n SIGMOID_ACTIVATION_FUNCTION = 2\n\n def __init__(self, node_id, layer_type, layer_id, activation_function):\n self.node_id = node_id\n self.node_type = layer_type\n self.layer_id = layer_id\n self.input_data = 0.0\n self.output = 0.0\n self.bias = None\n self.activation_function = activation_function\n self.generate_random_bias()\n\n def adjust_bias(self):\n if self.node_type == self.INPUT_NODE:\n self.bias = 0.0\n else:\n self.bias += np.random.uniform(-0.1, 0.1)\n\n def generate_random_bias(self):\n if self.node_type == self.INPUT_NODE:\n self.bias = 0.0\n else:\n self.bias = np.random.uniform(-1, 1)\n\n def calculate_output(self):\n self.input_data = self.input_data + self.bias\n self.output = self.activate(self.input_data)\n return self.output\n\n def activate(self, value):\n if self.activation_function == self.TANH_ACTIVATION_FUNCTION:\n return np.tanh(value)\n elif self.activation_function == self.SIGMOID_ACTIVATION_FUNCTION:\n return 1 / (1 + np.exp(-value))\n\n def __str__(self):\n return \"Node id: \" + str(self.node_id) + \", node type: \" + self.node_type + \", layer id: \" + str(self.layer_id) \\\n + \", bias: \" + str(self.bias) + \", input: \" + str(self.input_data) + \", output: \" + str(self.output)\n" }, { "alpha_fraction": 0.6369889378547668, "alphanum_fraction": 0.6377531290054321, "avg_line_length": 47.46296310424805, "blob_id": "0352190a92389d39da140e69385a97dc1651a360", "content_id": "ff8d6ae1d3b4cb3490185c04179036038f78017e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5234, "license_type": "no_license", "max_line_length": 198, "num_lines": 108, "path": "/Layer.py", "repo_name": "MADRobotNO/Simple_NEAT_v0.2", "src_encoding": "UTF-8", "text": "from Node import Node\nfrom Connection import Connection\nimport numpy as np\n\n\nclass Layer:\n\n INPUT_LAYER = \"input\"\n HIDDEN_LAYER = \"hidden\"\n OUTPUT_LAYER = \"output\"\n\n INPUT_LAYER_ID = 0\n OUTPUT_LAYER_ID = 1\n\n def __init__(self, layer_id, layer_type, number_of_nodes, list_of_all_nodes, list_of_all_connections, list_of_all_layers, list_of_innovations, activation_function=Node.TANH_ACTIVATION_FUNCTION):\n self.layer_id = layer_id\n self.layer_type = layer_type\n self.number_of_nodes = number_of_nodes\n self.activation_function = activation_function\n self.list_of_layer_nodes = []\n self.list_of_layer_connections = []\n\n self.initialize_layer(list_of_all_nodes, list_of_all_connections, list_of_all_layers, list_of_innovations)\n\n def initialize_layer(self, list_of_all_nodes, list_of_all_connections, list_of_all_layers, list_of_innovations):\n self.initialize_nodes(list_of_all_nodes)\n\n if self.layer_type != self.INPUT_LAYER:\n self.initialize_connections(list_of_all_connections, list_of_all_layers, list_of_innovations)\n\n def initialize_nodes(self, list_of_all_nodes):\n for i in range(self.number_of_nodes):\n node = Node(len(list_of_all_nodes), self.layer_type, self.layer_id, self.activation_function)\n list_of_all_nodes.append(node)\n self.list_of_layer_nodes.append(node)\n\n def initialize_connections(self, list_of_all_connections, list_of_all_layers, list_of_innovations):\n # layer nearest to input layer, connecting to input\n for input_node in list_of_all_layers[self.INPUT_LAYER_ID].list_of_layer_nodes:\n for current_node in self.list_of_layer_nodes:\n innovation_id = self.get_innovation_id(list_of_innovations, input_node.node_id, current_node.node_id)\n connection = Connection(len(list_of_all_connections), input_node.node_id, current_node.node_id, innovation_id)\n list_of_all_connections.append(connection)\n self.list_of_layer_connections.append(connection)\n\n def get_innovation_id(self, list_of_innovations, from_node_id, to_node_id):\n new_connection = (from_node_id, to_node_id)\n for index, innovation in enumerate(list_of_innovations):\n if innovation == new_connection or reversed(innovation) == new_connection:\n return index\n list_of_innovations.append(new_connection)\n return list_of_innovations.index(new_connection)\n\n def generate_new_weights(self):\n for connection in self.list_of_layer_connections:\n connection.generate_random_weight()\n\n def generate_new_biases(self):\n for node in self.list_of_layer_nodes:\n node.generate_random_bias()\n\n def add_connection(self, from_node, to_node, innovation_id, list_of_all_connections):\n new_connection = Connection(len(list_of_all_connections), from_node.node_id, to_node.node_id, innovation_id)\n self.list_of_layer_connections.append(new_connection)\n list_of_all_connections.append(new_connection)\n return new_connection\n\n def add_new_node(self, input_layer, list_of_innovations, list_of_all_nodes, list_of_all_connections):\n node = Node(len(list_of_all_nodes), self.layer_type, self.layer_id, self.activation_function)\n for from_node in input_layer.list_of_layer_nodes:\n innovation_id = self.get_innovation_id(list_of_innovations, from_node.node_id, node.node_id)\n self.add_connection(from_node, node, innovation_id, list_of_all_connections)\n self.list_of_layer_nodes.append(node)\n list_of_all_nodes.append(node)\n return node\n\n def mutate(self, mutation_rate):\n for node in self.list_of_layer_nodes:\n # x % chance to adjust bias\n if np.random.random() < mutation_rate:\n node.adjust_bias()\n # x % chance to change bias\n elif np.random.random() < mutation_rate:\n node.generate_random_bias()\n for connection in self.list_of_layer_connections:\n # x % chance to adjust weight\n if np.random.random() < mutation_rate:\n connection.adjust_weight()\n # x % chance to change weight\n elif np.random.random() < mutation_rate:\n connection.generate_random_weight()\n\n def __str__(self):\n return_string = \"Layer id: \" + str(self.layer_id) + \", layer type: \" + self.layer_type + \", number of connections: \" \\\n + str(len(self.list_of_layer_connections)) + \", number of nodes: \" + str(len(self.list_of_layer_nodes)) + \"\\n\"\n return_string += \"Nodes:\\n\"\n if len(self.list_of_layer_nodes) > 0:\n for node in self.list_of_layer_nodes:\n return_string += node.__str__() + \"\\n\"\n else:\n return_string += \"No nodes in layer!\\n\"\n return_string += \"Connections:\\n\"\n if len(self.list_of_layer_connections) > 0:\n for connection in self.list_of_layer_connections:\n return_string += connection.__str__() + \"\\n\"\n else:\n return_string += \"No connections!\\n\"\n return return_string\n" }, { "alpha_fraction": 0.5797438621520996, "alphanum_fraction": 0.5867287516593933, "avg_line_length": 34.79166793823242, "blob_id": "c92e9de455481842836b3ac2ef6d9568e400adc7", "content_id": "90f80bb1bf1087e420d79ab29bbd8da783763392", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 859, "license_type": "no_license", "max_line_length": 110, "num_lines": 24, "path": "/Connection.py", "repo_name": "MADRobotNO/Simple_NEAT_v0.2", "src_encoding": "UTF-8", "text": "from Node import Node\nimport numpy as np\n\n\nclass Connection:\n def __init__(self, connection_id, from_node, to_node, innovation_id):\n self.connection_id = connection_id\n self.innovation_id = innovation_id\n self.from_node = from_node\n self.to_node = to_node\n self.enabled = True\n self.weight = None\n self.generate_random_weight()\n\n def adjust_weight(self):\n self.weight += np.random.uniform(-0.1, 0.1)\n\n def generate_random_weight(self):\n self.weight = np.random.uniform(-1, 1)\n\n def __str__(self):\n return \"Connection id: \" + str(self.connection_id) + \", innovation id: \" + str(self.innovation_id) + \\\n \", from node: \" + str(self.from_node) + \", to node: \" + str(self.to_node) + \", enabled: \" + \\\n str(self.enabled) + \", weight: \" + str(self.weight)\n" }, { "alpha_fraction": 0.6026616096496582, "alphanum_fraction": 0.605830192565918, "avg_line_length": 54.22999954223633, "blob_id": "5e39d3d6f2f9ba7d0b313533759de50472fb2b5a", "content_id": "4826c37473d525af2c31ecd1ceecc978222e54c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11046, "license_type": "no_license", "max_line_length": 236, "num_lines": 200, "path": "/Model.py", "repo_name": "MADRobotNO/Simple_NEAT_v0.2", "src_encoding": "UTF-8", "text": "from Connection import Connection\nfrom Layer import Layer\nimport numpy as np\nfrom Node import Node\n\nclass Model:\n\n def __init__(self, model_id, number_of_inputs, number_of_outputs, mutation_rate, list_of_innovations):\n self.model_id = model_id\n self.outputs = []\n self.score = 0.0\n self.number_of_inputs = number_of_inputs\n self.number_of_outputs = number_of_outputs\n self.mutation_rate = mutation_rate\n self.list_of_all_nodes = []\n self.list_of_all_layers = []\n self.list_of_all_connections = []\n self.list_of_all_hidden_layers = []\n self.input_layer = None\n self.output_layer = None\n\n self.initialize_model(list_of_innovations)\n\n def initialize_model(self, list_of_innovations):\n input_layer = Layer(len(self.list_of_all_layers), Layer.INPUT_LAYER, self.number_of_inputs, self.list_of_all_nodes, self.list_of_all_connections, self.list_of_all_layers, list_of_innovations)\n self.list_of_all_layers.append(input_layer)\n self.input_layer = input_layer\n output_layer = Layer(len(self.list_of_all_layers), Layer.OUTPUT_LAYER, self.number_of_outputs, self.list_of_all_nodes, self.list_of_all_connections, self.list_of_all_layers, list_of_innovations, Node.SIGMOID_ACTIVATION_FUNCTION)\n self.list_of_all_layers.append(output_layer)\n self.output_layer = output_layer\n\n def regenerate_random_weights_bias(self):\n for layer in self.list_of_all_layers:\n layer.generate_new_weights()\n layer.generate_new_biases()\n\n def mutate(self, list_of_innovations, parent_model=None, parent_model_two=None):\n random_number = np.random.random()\n # x percent chance to mutate structure\n if random_number < self.mutation_rate:\n # print(\"Mutating structure on model\", self.model_id)\n self.mutate_structure(list_of_innovations)\n else:\n # print(\"Mutating weights on model\", self.model_id)\n for layer in self.list_of_all_layers:\n # each element of model has x percent chance to mutate\n layer.mutate(self.mutation_rate)\n\n def mutate_structure(self, list_of_innovations):\n nodes_connection_ratio = 0.7\n random_number = np.random.random()\n\n # create new connection or disable old\n if random_number <= nodes_connection_ratio:\n # print(\"Adding new connection\")\n node_one = self.list_of_all_nodes[np.random.randint(0, len(self.list_of_all_nodes))]\n # first selected node cannot be an output node\n while node_one.node_type is Node.OUTPUT_NODE:\n node_one = self.list_of_all_nodes[np.random.randint(0, len(self.list_of_all_nodes))]\n node_two = self.list_of_all_nodes[np.random.randint(0, len(self.list_of_all_nodes))]\n # print(\"Node one selected:\", node_one)\n # print(\"Node two selected:\", node_two)\n # second selected node has to be:\n # 1. in lower layer to prevent reverse connections (exception: connection between input and output layers)\n # 2. different than first node\n # 3. of type hidden to prevent connection in the same layer for input/output layers\n # 4. other than input node as there can be only output connections from input layer\n while (node_two.layer_id > node_one.layer_id) \\\n or (node_two.node_id == node_one.node_id) \\\n or ((node_two.layer_id == node_one.layer_id) and (node_two.node_type is not Node.HIDDEN_NODE)) \\\n or (node_two.node_type is Node.INPUT_NODE):\n if node_two.layer_id > node_one.layer_id and (node_one.node_type == Node.INPUT_NODE\n and node_two.node_type == Node.OUTPUT_NODE):\n # print(\"Exception node one is input node two is output and node 2 layer is greater than node one\")\n break\n if (node_one.node_type is Node.INPUT_NODE) and (node_two.node_type is not Node.INPUT_NODE):\n # print(\"Exception node one is input node two is other than input\")\n break\n # print(\"generate again node two\")\n # print(\"Node one selected:\", node_one)\n node_two = self.list_of_all_nodes[np.random.randint(0, len(self.list_of_all_nodes))]\n # print(\"Node selected for check\", node_two)\n # print(\"Connection from:\", node_one, \", to:\", node_two)\n existing_connection_found = False\n for connection in self.list_of_all_layers[node_two.layer_id].list_of_layer_connections:\n if connection.from_node == node_one.node_id and connection.to_node == node_two.node_id:\n # print(\"Existing connection found, mutating connection\", connection, \"to\", (not connection.enabled))\n if connection.enabled is True:\n connection.enabled = False\n else:\n connection.enabled = True\n existing_connection_found = True\n break\n\n if not existing_connection_found:\n # new connection\n innovation_id = self.get_innovation_id(node_one, node_two, list_of_innovations)\n self.list_of_all_layers[node_two.layer_id].add_connection(node_one, node_two, innovation_id, self.list_of_all_connections)\n\n # create new node\n else:\n if len(self.list_of_all_hidden_layers) == 0:\n self.create_new_hidden_layer_with_node(list_of_innovations)\n else:\n # select random hidden layer or create a new one to add node\n random_number = np.random.random()\n if random_number > 0.3:\n # print(\"Adding new node to existing layer\")\n hidden_layer = self.list_of_all_hidden_layers[np.random.randint(0, len(self.list_of_all_hidden_layers))]\n # print(\"Hidden layer:\", hidden_layer)\n previous_layer = self.list_of_all_layers[hidden_layer.layer_id-1]\n node = hidden_layer.add_new_node(self.input_layer, list_of_innovations, self.list_of_all_nodes, self.list_of_all_connections)\n # print(\"New node:\", node)\n to_node = previous_layer.list_of_layer_nodes[np.random.randint(0, len(previous_layer.list_of_layer_nodes))]\n previous_layer.add_connection(node, to_node, self.get_innovation_id(node, to_node, list_of_innovations), self.list_of_all_connections)\n else:\n # new hidden layer\n # print(\"Creating new hidden layer with new node\")\n self.create_new_hidden_layer_with_node(list_of_innovations)\n\n def create_new_hidden_layer_with_node(self, list_of_innovations):\n # create hidden layer with one new node\n # print(\"Adding new layer and new node\")\n hidden_layer = Layer(len(self.list_of_all_layers), Layer.HIDDEN_LAYER, 1, self.list_of_all_nodes,\n self.list_of_all_connections, self.list_of_all_layers, list_of_innovations)\n self.list_of_all_layers.append(hidden_layer)\n self.list_of_all_hidden_layers.append(hidden_layer)\n node = hidden_layer.list_of_layer_nodes[len(hidden_layer.list_of_layer_nodes) - 1]\n from_connections = hidden_layer.list_of_layer_connections\n # connect node to next layer\n previous_layer = self.list_of_all_layers[hidden_layer.layer_id - 1]\n to_node = previous_layer.list_of_layer_nodes[np.random.randint(0, len(previous_layer.list_of_layer_nodes))]\n previous_layer_connections = previous_layer.list_of_layer_connections\n previous_layer.add_connection(node, to_node, self.get_innovation_id(node, to_node, list_of_innovations), self.list_of_all_connections)\n\n # disable old connection\n for connection in previous_layer_connections:\n for from_connection in from_connections:\n if from_connection.from_node == connection.from_node and connection.to_node == to_node.node_id:\n connection.enabled = False\n\n def get_innovation_id(self, node_from, node_to, list_of_innovations):\n new_connection = (node_from.node_id, node_to.node_id)\n if new_connection in list_of_innovations:\n return list_of_innovations.index(new_connection)\n list_of_innovations.append(new_connection)\n return len(list_of_innovations)\n\n def get_node_by_id(self, node_id):\n for node in self.list_of_all_nodes:\n if node_id == node.node_id:\n return node\n return None\n\n def feed_forward(self, input_data):\n self.outputs = []\n # input layer\n for input_index, input_node in enumerate(self.input_layer.list_of_layer_nodes):\n input_node.output = input_data[input_index]\n # hidden layers\n for hidden_layer in reversed(self.list_of_all_hidden_layers):\n for node in hidden_layer.list_of_layer_nodes:\n node.input_data = 0.0\n for hidden_conn_index, connection in enumerate(hidden_layer.list_of_layer_connections):\n if connection.to_node == node.node_id and connection.enabled:\n input_node = self.get_node_by_id(connection.from_node)\n node.input_data += input_node.output * connection.weight\n node.calculate_output()\n\n # output layer\n for node in self.output_layer.list_of_layer_nodes:\n node.input_data = 0.0\n for output_conn_index, output_connection in enumerate(self.output_layer.list_of_layer_connections):\n if output_connection.to_node == node.node_id and output_connection.enabled:\n input_node = self.get_node_by_id(output_connection.from_node)\n node.input_data += input_node.output * output_connection.weight\n node.calculate_output()\n self.outputs.append(node.output)\n return self.outputs\n\n def fit(self, input_data, target):\n outputs = self.feed_forward(input_data)\n for output_index, output in enumerate(outputs):\n if output > 0.5:\n temp_output = 1.0\n else:\n temp_output = 0.0\n self.reward(output, temp_output, target[output_index])\n\n def reward(self, output, temp_output, target):\n if temp_output == target:\n # reward\n self.score += abs((2 * output) - 1)\n\n def __str__(self):\n return_string = \"Model id: \" + str(self.model_id) + \", number of layers: \" + str(len(self.list_of_all_layers)) \\\n + \", score: \" + str(self.score) + \"\\nLayers:\\n\"\n for layer in self.list_of_all_layers:\n return_string += layer.__str__() + \"\\n\"\n return return_string\n" }, { "alpha_fraction": 0.6752136945724487, "alphanum_fraction": 0.7094017267227173, "avg_line_length": 22.399999618530273, "blob_id": "fdc55e50173975f09d60d2a749209c3b0ad83ff1", "content_id": "7dae8637ca2bf4123eb3199831d188f720ee7893", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 234, "license_type": "no_license", "max_line_length": 42, "num_lines": 10, "path": "/example.py", "repo_name": "MADRobotNO/Simple_NEAT_v0.2", "src_encoding": "UTF-8", "text": "from NEAT import Neat\nfrom RandomData import Xor\n\nxor = Xor()\nneat = Neat(2, 1, 10, 0.4)\nfor model in neat.list_of_all_models:\n model.mutate(neat.list_of_innovations)\n# print(neat)\nneat.fit(xor.data, xor.targets, 50)\nprint(\"done\")\n" }, { "alpha_fraction": 0.6085817217826843, "alphanum_fraction": 0.6128398180007935, "avg_line_length": 39.7066650390625, "blob_id": "81976fc3e36c717fccd8ab6aa079e9e66a493a9b", "content_id": "1bd25691f6736219cc0a9b767ef6ae633f5b6cfb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3053, "license_type": "no_license", "max_line_length": 118, "num_lines": 75, "path": "/NEAT.py", "repo_name": "MADRobotNO/Simple_NEAT_v0.2", "src_encoding": "UTF-8", "text": "from Model import Model\nimport numpy as np\nimport copy\n\n\nclass Neat:\n\n def __init__(self, number_of_inputs=2, number_of_outputs=1, number_of_models=1, mutation_rate=0.1):\n self.list_of_innovations = []\n self.list_of_all_models = []\n self.mutation_rate = mutation_rate\n self.number_of_inputs = number_of_inputs\n self.number_of_outputs = number_of_outputs\n self.number_of_models = number_of_models\n\n parent_model = self.initialize_model()\n self.generate_population(parent_model)\n\n def generate_population(self, parent_model, parent_model_two=None):\n for i in range(len(self.list_of_all_models), self.number_of_models):\n model = self.model_from_parent_structure(parent_model)\n model.mutate(self.list_of_innovations, parent_model, parent_model_two)\n self.list_of_all_models.append(model)\n\n def model_from_parent_structure(self, parent_model):\n model = copy.deepcopy(parent_model)\n model.model_id = len(self.list_of_all_models)\n model.outputs = None\n model.score = 0.0\n model.regenerate_random_weights_bias()\n return model\n\n def initialize_model(self):\n model = Model(len(self.list_of_all_models), self.number_of_inputs, self.number_of_outputs, self.mutation_rate,\n self.list_of_innovations)\n self.list_of_all_models.append(model)\n return model\n\n def fit(self, input_data, target_data, number_of_generations):\n for generation in range(1, number_of_generations+1):\n print(\"Generation:\", generation)\n # for each data row ...\n for index, input_row in enumerate(input_data):\n # ... train each model\n for model in self.list_of_all_models:\n model.fit(input_row, target_data[index])\n\n best_models = self.get_best_and_second_best_model()\n print(\"\\nBest model:\")\n print(best_models.get('first'))\n print(\"Second best:\")\n print(best_models.get('second'))\n\n def get_best_and_second_best_model(self):\n current_highest = 0.0\n current_second_highest = 0.0\n current_first_model = None\n current_second_model = None\n for model in self.list_of_all_models:\n if model.score > current_highest:\n current_second_highest = current_highest\n current_second_model = current_first_model\n current_highest = model.score\n current_first_model = model\n elif model.score > current_second_highest:\n current_second_highest = model.score\n current_second_model = model\n return {\"first\": current_first_model, \"second\": current_second_model}\n\n def __str__(self):\n return_string = \"Current NEAT state:\\n\"\n for model in self.list_of_all_models:\n return_string += model.__str__() + \"\\n\"\n return_string += \"List of innovations:\\n\" + str(self.list_of_innovations)\n return return_string\n" } ]
7
mdm16c/01-Knapsack
https://github.com/mdm16c/01-Knapsack
c8545d3f8288c0538be27d7fa4176dc7f6be2dd8
8572b73424930aa6b03be99a558a027d97ed0e0c
568ce39685fb626b201af8cbf76785524293af1e
refs/heads/main
2023-03-02T21:59:36.666897
2021-02-07T22:55:31
2021-02-07T22:55:31
335,684,563
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7594936490058899, "alphanum_fraction": 0.8101266026496887, "avg_line_length": 38.5, "blob_id": "b82a053650313b6034eb04f2a3dc2404c247fe50", "content_id": "6743dbb8d7c3e74c53999865e3e5ac918885ccd7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 79, "license_type": "permissive", "max_line_length": 64, "num_lines": 2, "path": "/README.md", "repo_name": "mdm16c/01-Knapsack", "src_encoding": "UTF-8", "text": "# 01-Knapsack\n Different algorithms to solve the 01 knapsack problem in Python\n" }, { "alpha_fraction": 0.691527247428894, "alphanum_fraction": 0.7050806283950806, "avg_line_length": 29.363218307495117, "blob_id": "3102bb5495a3be0e1d6a1997be9b76e1d41e60f9", "content_id": "3af52add536ee4beb5b7f547b54dd2c894f2c299", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13207, "license_type": "permissive", "max_line_length": 171, "num_lines": 435, "path": "/knapsack.py", "repo_name": "mdm16c/01-Knapsack", "src_encoding": "UTF-8", "text": "# Matthew McCracken\n# python knapsack.py -f tests/test1.txt -r\n\nimport sys\nimport math\nimport time\nimport random\n\n# knapsack class to store data about the bag and potential items\nclass knapsack:\n\tmaxWeight = 0.0\n\tallItems = []\n\texWeights = []\n\texValues = []\n\texItems = []\n\tnumberOfItems = 0\n\tpickedItems = []\n\n# function to read from the file and populate a knapsack object\ndef createKnapsack(filename):\n\n\t# open file\n\tf = open(filename, \"r\")\n\n\t# instantiate new knapsack object\n\tnewKnapsack = knapsack()\n\n\t# get max weight and # of items\n\tline = f.readline()\n\tline = line.rstrip('\\n')\n\tline = line.rstrip(' ')\n\ttempList = line.split(',')\n\tnewKnapsack.numberOfItems = tempList[0]\n\tnewKnapsack.maxWeight = tempList[1]\n\n\t# get all possible items and put it into a list + manipulate the data\n\tline = f.readline()\n\twhile (line != ''):\n\t\t# remove the endline character\n\t\tline = line.rstrip('\\n')\n\t\tline = line.rstrip(' ')\n\n\t\t# check if exhaustive search is being used because I am going to implement it differently\n\t\tif exhaustiveSearchWithPruningMethod or exhaustiveSearchWithoutPruningMethod:\n\t\t\ttempList = line.split(',')\n\t\t\tnewKnapsack.exItems.append(tempList[0])\n\t\t\tnewKnapsack.exWeights.append(int(tempList[1]))\n\t\t\tnewKnapsack.exValues.append(int(tempList[2]))\n\n\t\t# any method except for exhaustive search goes here as they work the same way\n\t\telse:\n\t\t\t# split the list into different elements based on the commas locations\n\t\t\tnewKnapsack.allItems.append(line.split(','))\n\n\t\t\t# convert weight and value to ints\n\t\t\tnewKnapsack.allItems[-1][1] = int(newKnapsack.allItems[-1][1])\n\t\t\tnewKnapsack.allItems[-1][2] = int(newKnapsack.allItems[-1][2])\n\n\t\t\t# append the value:weight ratio onto the end of each nested list\n\t\t\tnewKnapsack.allItems[-1].append(newKnapsack.allItems[-1][2] / newKnapsack.allItems[-1][1])\n\n\t\t\t# convert the nested list into a nested tuple\n\t\t\tnewKnapsack.allItems[-1] = tuple(newKnapsack.allItems[-1])\n\n\t\t# read the next line\n\t\tline = f.readline()\n\n\t# close file and return knapsack object\n\tf.close()\n\treturn newKnapsack\n\n# sort the list by its value:weight ratio\ndef sortByRatio(ks):\n\tks.allItems.sort(key=lambda x:x[3], reverse=True)\n\treturn ks\n\n# sort the list by its value\ndef sortByValue(ks):\n\tks.allItems.sort(key=lambda x:x[2], reverse=True)\n\treturn ks\n\n# sort the list by its weight\ndef sortByWeight(ks):\n\tks.allItems.sort(key=lambda x:x[1], reverse=False)\n\treturn ks\n\n# pick which items go in the bag based on how they were sorted\ndef pickItems(ks):\n\n\t# declare function variables\n\tcurrentWeight = 0.0\n\ttotalValue = 0.0\n\ttotalItems = 0\n\n\t# iterate through all items and take each until the bag is full\n\tfor i in ks.allItems:\n\n\t\t# check to make sure the new item is not too heavy\n\t\tif i[1] <= int(ks.maxWeight) - currentWeight:\n\n\t\t\t# add the item to list and add its weight to the total\n\t\t\tks.pickedItems.append(i)\n\t\t\tcurrentWeight += i[1]\n\t\t\ttotalValue += i[2]\n\t\t\ttotalItems += 1\n\n\t# output value\n\treturn totalValue, currentWeight, totalItems\n\ndef greedyHillClimbing(ks):\n\n\t# hold max value for comparing\n\tmaxValue = 0\n\n\t# temporary lists to decide which greedy approach is best\n\tweightItems = []\n\tvalueItems = []\n\tratioItems = []\n\n\t# greedy by weight approach\n\tsortByWeight(ks)\n\tweightMax = pickItems(ks)[0]\n\tweightItems = ks.pickedItems\n\tks.pickedItems = []\n\n\t# greedy by value approach\n\tsortByValue(ks)\n\tvalueMax = pickItems(ks)[0]\n\tvalueItems = ks.pickedItems\n\tks.pickedItems = []\n\n\t# greedy by ratio approach\n\tsortByRatio(ks)\n\tratioMax = pickItems(ks)[0]\n\tratioItems = ks.pickedItems\n\tks.pickedItems = []\n\n\t# if ratio max is the highest value save value and items picked\n\tif ratioMax >= weightMax and ratioMax >= valueMax:\n\t\tmaxValue = ratioMax\n\t\tks.pickedItems = ratioItems\n\n\t# if value max is the highest value save value and items picked\n\telif valueMax >= ratioMax and valueMax >= weightMax:\n\t\tmaxValue = valueMax\n\t\tks.pickedItems = valueItems\n\n\t# weight max must be the highest value so save value and items picked\n\telse:\n\t\tmaxValue = weightMax\n\t\tks.pickedItems = ratioItems\n\n\t# begin hill climbing\n\n\t# go through some amount of the list testing values\n\titerations = math.ceil(int(ks.numberOfItems)*5)\n\n\t# iterate through items in list\n\tfor i in range(len(ks.pickedItems)):\n\n\t\t# repeat random testing until reaching iterations\n\t\tfor j in range(iterations):\n\n\t\t\t# cap time if needed\n\t\t\tif time.time() > hcTimeout:\n\t\t\t\tsys.exit(filename + \" Reached max time\")\n\n\t\t\t# get random index of all items to test in place of i\n\t\t\ttestIndex = random.randint(0,int(ks.numberOfItems)-1)\n\n\t\t\t# if the random value selected is already in the list it cannot be added\n\t\t\tif ks.allItems[testIndex] in ks.pickedItems:\n\t\t\t\tcontinue\n\n\t\t\t# if the weight becomes greater than the max possible weight it cannot be used\n\t\t\tif int(ks.maxWeight) - int(ks.pickedItems[i][1]) + int(ks.allItems[testIndex][1]) <= int(ks.maxWeight):\n\n\t\t\t\t# if new max value is greater than old and it made it through previous checks, switch old values with new ones\n\t\t\t\tif maxValue - int(ks.pickedItems[i][2]) + int(ks.allItems[testIndex][2]) > maxValue:\n\t\t\t\t\tmaxValue = maxValue - int(ks.pickedItems[i][2]) + int(ks.allItems[testIndex][2])\n\t\t\t\t\tks.pickedItems[i] = ks.allItems[testIndex]\n\t\t\t\t\tbreak\n\n\t\t\t# if the weight is too much, check a combination of 2 random new items\n\n\t\t\t# generate 2nd random index to try\n\t\t\ttestIndex2 = random.randint(0,int(ks.numberOfItems)-1)\n\n\t\t\t# check to make sure we are not at the end of i, test indeices are different, and the new value does not already exist\n\t\t\tif i < len(ks.pickedItems)-1 and testIndex != testIndex2 and ks.allItems[testIndex2] not in ks.pickedItems:\n\n\t\t\t\t# make sure it not above the max weight\n\t\t\t\tif int(ks.maxWeight) - int(ks.pickedItems[i][1]) - int(ks.pickedItems[i+1][1]) + int(ks.allItems[testIndex][1]) + int(ks.allItems[testIndex2][1]) <= int(ks.maxWeight):\n\t\t\t\t\t\n\t\t\t\t\t# see if we found a better value between the 2 random values and update variables if so\n\t\t\t\t\tif maxValue - int(ks.pickedItems[i][2]) - int(ks.pickedItems[i+1][2]) + int(ks.allItems[testIndex][2]) + int(ks.allItems[testIndex2][2]) > maxValue:\n\t\t\t\t\t\tmaxValue = maxValue - int(ks.pickedItems[i][2]) - int(ks.pickedItems[i+1][2]) + int(ks.allItems[testIndex][2]) + int(ks.allItems[testIndex2][2])\n\t\t\t\t\t\tks.pickedItems[i] = ks.allItems[testIndex]\n\t\t\t\t\t\tks.pickedItems[i+1] = ks.allItems[testIndex2]\n\n\t# get current weight and total items\n\tcurrentWeight = 0\n\ttotalItems = 0\n\tfor i in ks.pickedItems:\n\t\tcurrentWeight += int(i[1])\n\t\ttotalItems += 1\n\n\t# return the max value found\n\treturn maxValue, currentWeight, totalItems\n\ndef getExhaustiveBagStats(ks):\n\n\t# convert values in lists to ints\n\tfor i in range(int(ks.numberOfItems)):\n\t\tks.exWeights[i] = int(ks.exWeights[i])\n\t\tks.exValues[i] = int(ks.exValues[i])\n\n\t# initialize table\n\ttempList = [[0 for i in range(int(ks.maxWeight)+1)] for j in range(int(ks.numberOfItems)+1)]\n\t\t\t\n\t# Create Table\n\tfor i in range(int(ks.numberOfItems)+1):\n\t\tfor j in range(int(ks.maxWeight)+1):\n\n\t\t\t# initialize table\n\t\t\tif i == 0 or j == 0:\n\t\t\t\ttempList[i][j] = 0\n\n\t\t\t# check if weight is possible\n\t\t\telif ks.exWeights[i-1] <= j:\n\n\t\t\t\t# get values for 2 different possibilities\n\t\t\t\ta = ks.exValues[i-1] + tempList[i-1][j-ks.exWeights[i-1]]\n\t\t\t\tb = tempList[i-1][j]\n\n\t\t\t\t# compare them and save the greater one\n\t\t\t\tif a >= b:\n\t\t\t\t\ttempList[i][j] = a\n\t\t\t\telse:\n\t\t\t\t\ttempList[i][j] = b\n\n\t\t\t# otherwise, keep old value\n\t\t\telse:\n\t\t\t\ttempList[i][j] = tempList[i-1][j]\n\n\t# save answer\n\ttotalValue = tempList[int(ks.numberOfItems)][int(ks.maxWeight)]\n\ttotalValueCopy = totalValue\n\ttotalWeight = 0\n\ttotalItems = 0\n\t\n\t# loop through bag\n\tfor i in range(int(ks.numberOfItems), 0, -1):\n\n\t\t# if we reach the end\n\t\tif totalValue <= 0:\n\t\t\tbreak\n\n\t\t# rejected item\n\t\tif tempList[i-1][int(ks.maxWeight)] == totalValue:\n\t\t\tcontinue\n\n\t\t# otherwise it was accepted\n\t\telse:\n\n\t\t\t# This item is included.\n\t\t\ttotalItems += 1\n\t\t\ttotalWeight += ks.exWeights[i-1]\n\t\t\t\n\t\t\t# subtract value from total\n\t\t\tks.maxWeight = int(ks.maxWeight) - ks.exWeights[i-1]\n\t\t\ttotalValue = totalValue - ks.exValues[i-1]\n\n\t# return resulting bag stats\n\treturn totalValueCopy, totalWeight, totalItems\n\ndef exhaustiveSearchWithPruning(maxWeight, weightsList, valuesList, totalItems):\n\n\tif time.time() > timeout:\n\t\twith open(\"ep.csv\", \"a\") as myfile:\n\t\t\tmyfile.write(filename[filename.index('\\\\')+1:])\n\t\t\tmyfile.write(\",\")\n\t\t\tmyfile.write(\"Exhaustive With Pruning\")\n\t\t\tmyfile.write(\",undef,undef,undef,MAX\\n\")\n\t\tsys.exit(filename + \" Reached max time\")\n\n\t# base case: if we run out of items to try or run out of bag space return 0\n\tif maxWeight == 0 or totalItems == 0:\n\t\treturn 0\n\n\t# if last item in list (i.e. item about to be checked) has a weight greater than max\n\t# remove item from pool, mostly for edge case use\n\tif (weightsList[totalItems-1] > maxWeight):\n\t\treturn exhaustiveSearchWithPruning(maxWeight, weightsList, valuesList, totalItems-1)\n\n\t# otherwise, continue down tree of possibilities and take the max of each option on the way back up\n\telse:\n\t\ta = valuesList[totalItems-1] + exhaustiveSearchWithPruning(maxWeight - weightsList[totalItems-1], weightsList, valuesList, totalItems-1)\n\t\tb = exhaustiveSearchWithPruning(maxWeight, weightsList, valuesList, totalItems-1)\n\t\tif a >= b:\n\t\t\treturn a\n\t\telse:\n\t\t\treturn b\n\ndef exhaustiveSearchWithoutPruning(ks):\n\n\t# get power set\n\tks.allItems = getPowerSet(ks.exItems)\n\n\t# declare variables to hold max values\n\tmaxValue = 0.0\n\n\t# declare variables to hold testing values\n\tcurrentWeight = 0.0\n\tcurrentValue = 0.0\n\n\t# iterate through power set\n\tfor i in ks.allItems:\n\t\tfor j in i:\n\n\t\t\tif time.time() > timeout:\n\t\t\t\tsys.exit(filename + \" Reached max time\")\n\n\t\t\t# keep track of testing variables in case they are better than max values\n\t\t\tmyIndex = ks.exItems.index(j)\n\t\t\tcurrentWeight += ks.exWeights[myIndex]\n\t\t\tcurrentValue += ks.exValues[myIndex]\n\n\t\t# test to see if the new values are better than the older ones and save them if they are\n\t\tif currentWeight <= int(ks.maxWeight) and currentValue > maxValue:\n\t\t\tmaxValue = currentValue\n\n\t\t# reset values of testing variables for next iteration\n\t\tcurrentValue = 0.0\n\t\tcurrentWeight = 0.0\n\n\t# return maximum value found\n\treturn maxValue\n\n# function to get a power set given a list of items\ndef getPowerSet(myList):\n\n\t# gets list length\n\tsize = len(myList)\n\n\t# temporary list to copy values into\n\ttempList = []\n\n\t# go through list getting every possible subset\n\tfor i in range(1 << size):\n\t\tif time.time() > timeout:\n\t\t\tsys.exit(filename + \" Reached max time\")\n\n\t\ttempList.append([myList[j] for j in range(size) if (i & (1 << j))])\n\n\t# return the templist that now contains all subsets\n\treturn tempList\n\n# user input variables\nfilename = \"\"\nexhaustiveSearchWithPruningMethod = False\nexhaustiveSearchWithoutPruningMethod = False\nweightSort = False\nvalueSort = False\nratioSort = False\nhillClimbing = False\n\n# get user input for method of solving and test filename\nn = len(sys.argv)\nfor i in range(1, n):\n if sys.argv[i] == \"-f\":\n \tfilename = sys.argv[i+1]\n elif sys.argv[i] == \"-e\":\n \texhaustiveSearchWithoutPruningMethod = True\n elif sys.argv[i] == \"-ep\":\n \texhaustiveSearchWithPruningMethod = True\n elif sys.argv[i] == \"-w\":\n \tweightSort = True\n elif sys.argv[i] == \"-v\":\n \tvalueSort = True\n elif sys.argv[i] == \"-r\":\n \tratioSort = True\n elif sys.argv[i] == \"-h\":\n \thillClimbing = True\n\n# make sure user passed in all required data\nif filename == \"\":\n\tsys.exit(\"pass in the name of a file (-f <filename>)\")\nelif not exhaustiveSearchWithPruningMethod and not exhaustiveSearchWithoutPruningMethod and not weightSort and not valueSort and not ratioSort and not hillClimbing:\n\tsys.exit(\"specify a method of solving (-e, -ep, -w, -v, -r, -h)\")\n\n# create the knapsack object from the file\nks = createKnapsack(filename)\n\n# start the timer after reading from file and sanitizing input\nstart_time = time.time()\n\ntimeout = time.time() + 60*20\nhcTimeout = time.time() + 60*5\n\n# pick a solution method and output the resulting value\nif weightSort:\n\tsortByWeight(ks)\n\tres = pickItems(ks)\n\ttimeCopy = round((time.time()-start_time) * 1000)\n\tprint(filename, int(res[1]), int(res[0]), int(res[2]), timeCopy, sep=',')\n\nelif valueSort:\n\tsortByValue(ks)\n\tres = pickItems(ks)\n\ttimeCopy = round((time.time()-start_time) * 1000)\n\tprint(filename, int(res[1]), int(res[0]), int(res[2]), timeCopy, sep=',')\n\nelif ratioSort:\n\tsortByRatio(ks)\n\tres = pickItems(ks)\n\ttimeCopy = round((time.time()-start_time) * 1000)\n\tprint(filename, int(res[1]), int(res[0]), int(res[2]), timeCopy, sep=',')\n\nelif exhaustiveSearchWithPruningMethod:\n\ttv = exhaustiveSearchWithPruning(int(ks.maxWeight), ks.exWeights, ks.exValues, int(ks.numberOfItems))\n\ttimeCopy = round((time.time()-start_time) * 1000)\n\tres = getExhaustiveBagStats(ks)\n\tprint(filename, int(res[1]), int(tv), int(res[2]), timeCopy, sep=',')\n\nelif exhaustiveSearchWithoutPruningMethod:\n\ttv = exhaustiveSearchWithoutPruning(ks)\n\ttimeCopy = round((time.time()-start_time) * 1000)\n\tres = getExhaustiveBagStats(ks)\n\tprint(filename, int(res[1]), int(tv), int(res[2]), timeCopy, sep=',')\n\nelif hillClimbing:\n\tres = greedyHillClimbing(ks)\n\ttimeCopy = round((time.time()-start_time) * 1000)\n\tprint(filename, int(res[1]), int(res[0]), int(res[2]), timeCopy, sep=',')" } ]
2
Rain1213/Hope
https://github.com/Rain1213/Hope
e11b81d5cb13536272ab20538590e33b596155ac
c80a1ad2fe2ab2db0ccdbcf92f17764dc2420487
ca760ec840dbfa4878931486c5f5db6c57bfd676
refs/heads/master
2023-01-24T10:10:48.604584
2020-12-08T17:50:15
2020-12-08T17:50:15
313,112,139
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7405920624732971, "alphanum_fraction": 0.7521324753761292, "avg_line_length": 65.43333435058594, "blob_id": "80632622eee3a4bbd5e1a271fe2f97941ce873dd", "content_id": "eccd8aaea812a3575cf2185160dea01cc7678a6b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3986, "license_type": "no_license", "max_line_length": 429, "num_lines": 60, "path": "/README.md", "repo_name": "Rain1213/Hope", "src_encoding": "UTF-8", "text": "# **HOPE**\n\nHope has been a 48 hour journey into building a lost and found application that works across the entire world. Submitted to ***Oxford Hacks 2020***, the aim is to make reporting lost items as easy as possible for the users so that they are obliged to report it.\n\nSimilarly it would be as easy as finding it; as it is to report it. Due to the project's grand ambitions and limiing time constraint, the lost portion of the project did remain incomplete; but given an opportunity to work on it again, would try my best to complete it.\n<br/><br/>\n\n## **LANGUAGES USED**\n- **Android Studio:** Primarily Android Studio has been used to create the application. Taking Images to report lost items as well as searching for them would be done using this app.\n- **Python:** Python was used to automatically identify the lost items from their images so not 1 word has to be entered from the users side.\n- **Firebase:** Firebase realtime database to store all lost item info and Firebase Storage to store the images of lost items taken by the user.\n<br/><br/>\n\n## **SOFTWARE DESIGN**\n\n### **MAIN PAGE**\n\nThe main page is where you are presented with an option of 'lost' or 'found'. As a person who has a recently lost an item, you would have to press the 'lost' button.\nIf you in case find an unattended item that appears to have been lost press the 'found' button and report the item to us.\n\n<img align=\"center\" alt=\"MainPage\" width=\"25%\" src=\"https://github.com/Rain1213/Hope/blob/master/screenshots/mainPg.JPG?raw=true\" />\n<br/><br/>\n\n### **FOUND PAGE**\n\nWhen you click on 'Found', you will be taken to the found main page. To keep things as simple as possible, all the finder has to do is take a picture of the found item. If the person wants to go an extra step and return the item to the police station, she/he could check the 'return to the police station' check box so that the lost person is,if he finds the item through the app, can take it easy that his item is in safe hands.\n\nWhat remains is to submit the info and its done. SIMPLE!!\n\n<img align=\"center\" alt=\"FoundPage\" width=\"25%\" src=\"https://github.com/Rain1213/Hope/blob/master/screenshots/lostPg.JPG?raw=true\" />\n\n<img align=\"center\" alt=\"AfterFoundPage\" width=\"25%\" src=\"https://github.com/Rain1213/Hope/blob/master/screenshots/afterLostPg.JPG?raw=true\" />\n<br/><br/>\n\n\n## **BACKEND**\n\n### **FIREBASE STORAGE**\nTo store the image I needed it to store it over the internet so that its url can be accessed in the future. I made use of firebase storage for this.\n\n<img align=\"center\" alt=\"FirebaseStorage\" width=\"100%\" src=\"https://github.com/Rain1213/Hope/blob/master/screenshots/FirebaseStorage.jpg?raw=true\" />\n\n<br/><br/>\n\n### **FIREBASE REALTIME DATABASE**\n\nI needed a database to store the the location details along with object details in realtime. Best way was to make of firebase realtime database for this. Intially the details of \"type\" remains empty. This is the field which recognizes and classifies the image.\n\n<img align=\"center\" alt=\"FirebaseStorage\" width=\"100%\" src=\"https://github.com/Rain1213/Hope/blob/master/screenshots/FirebaseDatabase.jpg?raw=true\" />\n\n<br/><br/>\n\n\n### **OBJECT IDENTIFICATION**\n Remember the finder has not written a single word as to what the item she/he found is. Therefore to segregate items into groups of items like \"wallets\", \"bagpacks\", \"smartphones\" etc. I made it so that the image stored in the Firebase Storage has to go through a python script to identify what the object is.\n The flow of data is as follows:\n\n The python scripts check if the \"type\" value of any child in firebase database is empty. If yes, it gets the value from the url, which contains the camera taken image of a found item. The script identifies what the object is and returns the value and fills the \"type\" column in the realtime database.\n\n <img align=\"center\" alt=\"FirebaseStorage\" width=\"100%\" src=\"https://github.com/Rain1213/Hope/blob/master/screenshots/ObjectRecognition.jpg?raw=true\" />\n" }, { "alpha_fraction": 0.6243094205856323, "alphanum_fraction": 0.6243094205856323, "avg_line_length": 20.611940383911133, "blob_id": "f529346bc1d4f0db644d1a71f773743a5c867357", "content_id": "549604134a5325c3a36584e414618c03a0b53a21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1448, "license_type": "no_license", "max_line_length": 128, "num_lines": 67, "path": "/app/src/main/java/com/example/lostandfoundoxford/FoundItemModel.java", "repo_name": "Rain1213/Hope", "src_encoding": "UTF-8", "text": "package com.example.lostandfoundoxford;\n\npublic class FoundItemModel {\n String uuid;\n String type;\n String imgUrl;\n Double latitude;\n Double longitude;\n Boolean policeProtected;\n\n public FoundItemModel(String uuid, String type, String imgUrl, Double latitude, Double longitude, Boolean policeProtected) {\n this.uuid = uuid;\n this.type = type;\n this.imgUrl = imgUrl;\n this.latitude = latitude;\n this.longitude = longitude;\n this.policeProtected = policeProtected;\n }\n\n public String getUuid() {\n return uuid;\n }\n\n public void setUuid(String uuid) {\n this.uuid = uuid;\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public String getImgUrl() {\n return imgUrl;\n }\n\n public void setImgUrl(String imgUrl) {\n this.imgUrl = imgUrl;\n }\n\n public Double getLatitude() {\n return latitude;\n }\n\n public void setLatitude(Double latitude) {\n this.latitude = latitude;\n }\n\n public Double getLongitude() {\n return longitude;\n }\n\n public void setLongitude(Double longitude) {\n this.longitude = longitude;\n }\n\n public Boolean getPoliceProtected() {\n return policeProtected;\n }\n\n public void setPoliceProtected(Boolean policeProtected) {\n this.policeProtected = policeProtected;\n }\n}\n" }, { "alpha_fraction": 0.7478882670402527, "alphanum_fraction": 0.7511370778083801, "avg_line_length": 29.780000686645508, "blob_id": "33efe1f958c59853e4be97f8fadd879b97761cdb", "content_id": "8479a09f67ceed780a414b0ae172c04153738e8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1539, "license_type": "no_license", "max_line_length": 89, "num_lines": 50, "path": "/app/src/main/java/com/example/lostandfoundoxford/MapActivity.java", "repo_name": "Rain1213/Hope", "src_encoding": "UTF-8", "text": "package com.example.lostandfoundoxford;\n\nimport android.Manifest;\nimport android.content.Context;\nimport android.content.pm.PackageManager;\nimport android.location.Location;\nimport android.location.LocationManager;\nimport android.os.Bundle;\n\nimport androidx.annotation.Nullable;\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.core.app.ActivityCompat;\n\nimport com.google.android.gms.maps.CameraUpdate;\nimport com.google.android.gms.maps.CameraUpdateFactory;\nimport com.google.android.gms.maps.GoogleMap;\nimport com.google.android.gms.maps.OnMapReadyCallback;\nimport com.google.android.gms.maps.SupportMapFragment;\nimport com.google.android.gms.maps.model.LatLng;\nimport com.google.android.gms.maps.model.MarkerOptions;\n\npublic class MapActivity extends AppCompatActivity implements OnMapReadyCallback {\n\n private GoogleMap mMap;\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.map_activity);\n\n SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()\n .findFragmentById(R.id.map);\n mapFragment.getMapAsync(this);\n\n }\n\n @Override\n public void onMapReady(GoogleMap googleMap) {\n mMap = googleMap;\n LatLng sydney = new LatLng(-34, 151);\n mMap.addMarker(new MarkerOptions()\n .position(sydney)\n .title(\"Marker in Sydney\"));\n mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));\n\n\n\n\n }\n}\n" }, { "alpha_fraction": 0.6170903444290161, "alphanum_fraction": 0.6473769545555115, "avg_line_length": 31.618181228637695, "blob_id": "9c8d00ae1193717a1720237f9ff6fd414c5729f2", "content_id": "6618db967fda75ac04bd5779e2218bfe5d60437e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1849, "license_type": "no_license", "max_line_length": 128, "num_lines": 55, "path": "/Python Code/ObjectRecognition.py", "repo_name": "Rain1213/Hope", "src_encoding": "UTF-8", "text": "from imageai.Detection import ObjectDetection\r\nimport os\r\nfrom firebase import Firebase\r\nimport requests\r\nimport time\r\n\r\nconfig = {\r\n \"apiKey\": \"AIzaSyCzphhFlPG78RzXO5lGpzyzMt2ahq0xngI\",\r\n \"authDomain\": \"lostandfound-1adc1.firebaseapp.com\",\r\n \"databaseURL\": \"https://lostandfound-1adc1.firebaseio.com\",\r\n \"projectId\": \"lostandfound-1adc1\",\r\n \"storageBucket\": \"lostandfound-1adc1.appspot.com\",\r\n \"messagingSenderId\": \"744472946418\",\r\n \"appId\": \"1:744472946418:web:8df69d71ec0511a5bdd26b\"\r\n}\r\n\r\nimg_names = []\r\nfirebase = Firebase(config)\r\nstorage = firebase.storage()\r\ndb = firebase.database()\r\nproject = \"FoundItemData\"\r\nnames = db.child(project).get()\r\nfor name in names.each():\r\n entries = project + \"/\" + str(name.key())\r\n values = db.child(entries).get()\r\n for value in values.each():\r\n if str(value.key()) == \"imgUrl\":\r\n img_names.append(value.val())\r\n\r\ncounter = int(0)\r\nfor image in img_names:\r\n img_data = requests.get(image).content\r\n with open(\"image\"+str(counter)+\".jpg\", 'wb') as handler:\r\n handler.write(img_data)\r\n time.sleep(1)\r\n counter += 1\r\n\r\nexecution_path = os.getcwd()\r\n\r\ndetector = ObjectDetection()\r\ndetector.setModelTypeAsRetinaNet()\r\ndetector.setModelPath(os.path.join(execution_path, \"resnet50_coco_best_v2.0.1.h5\"))\r\ndetector.loadModel()\r\n\r\ncounter = 0\r\nproject = \"FoundItemData\"\r\nnames = db.child(project).get()\r\nfor name in names.each():\r\n detections = detector.detectObjectsFromImage(input_image=os.path.join(execution_path, \"image\"+str(counter)+\".jpg\"),\r\n output_image_path=os.path.join(execution_path, \"imagenew\"+str(counter)+\".jpg\"))\r\n entries = project + \"/\" + str(name.key())\r\n db.child(entries).get()\r\n counter += 1\r\n for eachObject in detections:\r\n db.child(entries).update({\"type\": eachObject[\"name\"]})\r\n" } ]
4
busisd/BongoCat
https://github.com/busisd/BongoCat
2edbc224a54b30d800399b517a0a6809cab13e88
8bf17630ec38825f1fb5c9c95b6910e98828bb97
e639c99909e133cbe37e75d3aee96762e9472680
refs/heads/master
2020-03-30T02:39:12.163504
2019-05-29T23:10:54
2019-05-29T23:10:54
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7553191781044006, "alphanum_fraction": 0.7553191781044006, "avg_line_length": 36.400001525878906, "blob_id": "14f5759ceb8903cf55d0f998ccecfcd183480ed6", "content_id": "bbc3608ea0f391238ac0837d74d0a7f524dc4ece", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 376, "license_type": "no_license", "max_line_length": 83, "num_lines": 10, "path": "/README.md", "repo_name": "busisd/BongoCat", "src_encoding": "UTF-8", "text": "# BongoCat\nA program where you can control Bongo Cat to play along to music! \n\nUses the pygame module\n\nControls:\n - Left/right arrow: Play left/right bongo\n - Space: Toggle light mode (lower bongo dims the lights, upper bongo raises them!)\n - D: Toggle disco mode (background color changes randomly)\n - R: Toggle rainbow mode (Background color changes in a smooth rainbow!)\n \n" }, { "alpha_fraction": 0.6801367402076721, "alphanum_fraction": 0.7046758532524109, "avg_line_length": 32.71193313598633, "blob_id": "6ae1753999259a2c1910ffd39aa21ecd15289f8c", "content_id": "3cfff8e9bfc564d2475e61b7b5d835de95ca8ca5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8191, "license_type": "no_license", "max_line_length": 118, "num_lines": 243, "path": "/BongoCat.py", "repo_name": "busisd/BongoCat", "src_encoding": "UTF-8", "text": "#Coded by Daniel Busis\n#Inspired by (and art taken from) https://bongo.cat\n#Bongo sounds from https://www.freesound.org\n#Music from: https://www.bensound.com\n\nimport pygame\nimport random\n\nclass BongoCatGameController():\n\tdef __init__(self):\n\t\tself.CAT_NONE_DOWN_FILE = \"./images/BongoCatBothUp.png\"\n\t\tself.CAT_LEFT_DOWN_FILE = \"./images/BongoCatLeftDown.png\"\n\t\tself.CAT_RIGHT_DOWN_FILE = \"./images/BongoCatRightDown.png\"\n\t\tself.CAT_BOTH_DOWN_FILE = \"./images/BongoCatBothDown.png\"\n\t\tself.CAT_NONE_DOWN_IMAGE = pygame.image.load(self.CAT_NONE_DOWN_FILE)\n\t\tself.CAT_LEFT_DOWN_IMAGE = pygame.image.load(self.CAT_LEFT_DOWN_FILE)\n\t\tself.CAT_RIGHT_DOWN_IMAGE = pygame.image.load(self.CAT_RIGHT_DOWN_FILE)\n\t\tself.CAT_BOTH_DOWN_IMAGE = pygame.image.load(self.CAT_BOTH_DOWN_FILE)\n\n\t\tself.BULB_FILE = \"./images/bulb.png\"\n\t\tself.DISCO_FILE = \"./images/disco.png\"\n\t\tself.RAINBOW_FILE = \"./images/rainbow.png\"\n\t\tself.BULB_IMAGE = pygame.image.load(self.BULB_FILE)\n\t\tself.DISCO_IMAGE = pygame.image.load(self.DISCO_FILE)\n\t\tself.RAINBOW_IMAGE = pygame.image.load(self.RAINBOW_FILE)\n\t\t\n\t\tself.BONGO_SOUND_LOW_FILE = \"sounds/low_bongo.wav\"\n\t\tself.BONGO_SOUND_HIGH_FILE = \"sounds/high_bongo.wav\"\n\t\tself.BONGO_SOUND_LOW = pygame.mixer.Sound(self.BONGO_SOUND_LOW_FILE)\n\t\tself.BONGO_SOUND_HIGH = pygame.mixer.Sound(self.BONGO_SOUND_HIGH_FILE)\n\t\t\n\t\tself.MUSIC_POP_FILE = \"music/bensound-creativeminds.mp3\"\n\t\tself.MUSIC_JAZZ_FILE = \"music/bensound-jazzyfrenchy.mp3\"\n\t\tself.MUSIC_TECH_FILE = \"music/bensound-summer.mp3\"\n\t\tself.MUSIC_JINGLE_FILE = \"music/bensound-ukulele.mp3\"\n\t\tself.cur_song = -1\n\t\tself.song_list = [self.MUSIC_POP_FILE, self.MUSIC_JAZZ_FILE, self.MUSIC_TECH_FILE, self.MUSIC_JINGLE_FILE]\n\t\tself.SONG_VOLUME = .45\n\t\t\n\t\tself.left_down = False\n\t\tself.right_down = False\n\t\t\n\t\tself.bg_color = pygame.Color(255,255,255)\n\t\tself.lightswitch_mode = False\n\t\tself.disco_mode = False\n\t\t\n\t\tself.screen = None\n\t\tself.game_clock = None\n\t\t\n\t\tself.rainbow = RainbowControl()\n\t\tself.rainbow_mode = False\n\t\t\n\t\tself.font = pygame.font.SysFont(None, 36)\n\t\tself.font_color = pygame.Color(188,188,188)\n\t\tself.text_render = None\n\t\tself.song_name_list = [\"None\", \"Pop\", \"Jazzy\", \"Techno\", \"Jingle\"]\n\t\tself._update_text_render()\n\t\t\n\tdef _update_text_render(self):\n\t\tself.text_render = self.font.render(\"Current track: \"+self.song_name_list[self.cur_song+1], True, self.font_color)\n\t\t\nclass RainbowControl():\n\tdef __init__(self):\n\t\tself.color_percents = [1.0,1.0,1.0]\n\t\tself.frames_per_shift = 60\n\t\tself.cur_frames = 0\n\t\tself.color_goals = None\n\t\tself.color_steps = None\n\t\tself._choose_new_color_goals()\n\t\t\n\tdef get_color(self):\n\t\treturn pygame.Color(int(self.color_percents[0]*255),int(self.color_percents[1]*255),int(self.color_percents[2]*255))\n\t\tprint(self.color_percents)\n\t\t\n\tdef shift_rainbow(self):\n\t\tself.cur_frames+=1\n\t\tfor i in range(0,3):\n\t\t\tself.color_percents[i] += self.color_steps[i]\n\t\t\tif self.color_percents[i] < 0:\n\t\t\t\tself.color_percents[i] = 0\n\t\t\n\t\tif self.cur_frames >= self.frames_per_shift:\n\t\t\tself.cur_frames=0\n\t\t\tself._choose_new_color_goals()\n\t\t\n\tdef _choose_new_color_goals(self):\n\t\tself.color_goals = [random.random(), random.random(), random.random()]\n\t\tself.color_steps = [(1.0/self.frames_per_shift)*(self.color_goals[i] - self.color_percents[i]) for i in range(0,3)]\n\t\t\ndef main():\n\tpygame.mixer.pre_init(44100, -16, 2, 2048)\n\tpygame.mixer.init()\n\tpygame.font.init()\n\tpygame.init()\t\n\t\n\tgame_control = BongoCatGameController()\n\tpygame.display.set_caption(\"BONGO CAT\")\n\tgame_control.screen = pygame.display.set_mode((800,450))\n\t\n\tgame_control.game_clock = pygame.time.Clock()\n\t\n\trunning = True\n\twhile(running):\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\trunning = False\n\t\t\t\t\n\t\t\tif event.type == pygame.MOUSEBUTTONDOWN:\n\t\t\t\tif event.button==1:\n\t\t\t\t\t_left_bongo_down(game_control)\n\t\t\t\tif event.button==3:\n\t\t\t\t\t_right_bongo_down(game_control)\n\t\t\tif event.type == pygame.MOUSEBUTTONUP:\n\t\t\t\tif event.button==1:\n\t\t\t\t\t_left_bongo_up(game_control)\n\t\t\t\tif event.button==3:\n\t\t\t\t\t_right_bongo_up(game_control)\n\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\tif event.key==32:\n\t\t\t\t\tgame_control.lightswitch_mode = not game_control.lightswitch_mode\n\t\t\t\tif event.key==100:\n\t\t\t\t\tgame_control.disco_mode = not game_control.disco_mode\n\t\t\t\tif event.key==114:\n\t\t\t\t\tgame_control.rainbow_mode = not game_control.rainbow_mode\n\t\t\t\tif event.key==119:\n\t\t\t\t\t_return_to_white(game_control)\n\t\t\t\tif event.key==276:\n\t\t\t\t\t_left_bongo_down(game_control)\n\t\t\t\tif event.key==275:\n\t\t\t\t\t_right_bongo_down(game_control)\n\t\t\t\tif event.key==273:\n\t\t\t\t\t_toggle_song(game_control, 1)\n\t\t\t\tif event.key==274:\n\t\t\t\t\t_toggle_song(game_control, -1)\n\t\t\tif event.type == pygame.KEYUP:\n\t\t\t\tif event.key==276:\n\t\t\t\t\t_left_bongo_up(game_control)\n\t\t\t\tif event.key==275:\n\t\t\t\t\t_right_bongo_up(game_control)\n\t\tif game_control.disco_mode:\n\t\t\t_randomize_colors(game_control)\n\t\tif game_control.rainbow_mode:\n\t\t\tgame_control.rainbow.shift_rainbow()\n\t\t\tgame_control.bg_color = game_control.rainbow.get_color()\n\t\t\t\n\t\t_update_screen(game_control)\n\t\tgame_control.game_clock.tick(60)\n\tpygame.quit()\n\ndef _left_bongo_down(game_control):\n\tgame_control.left_down = True\n\tgame_control.BONGO_SOUND_LOW.play()\n\tif game_control.lightswitch_mode:\n\t\t_brighten_bg(game_control, -15)\n\ndef _right_bongo_down(game_control):\n\tgame_control.right_down = True\n\tgame_control.BONGO_SOUND_HIGH.play()\n\tif game_control.lightswitch_mode:\n\t\t_brighten_bg(game_control, 15)\n\ndef _left_bongo_up(game_control):\n\tgame_control.left_down = False\n\ndef _right_bongo_up(game_control):\n\tgame_control.right_down = False\n\t\t\ndef _brighten_bg(game_control, brighten_amount):\n\tnew_colors = []\n\tfor color in [game_control.bg_color.r, game_control.bg_color.g, game_control.bg_color.b]:\n\t\tif color + brighten_amount <= 255 and color + brighten_amount >= 0:\n\t\t\tcolor += brighten_amount\n\t\telif brighten_amount>0:\n\t\t\tcolor = 255\n\t\telse:\n\t\t\tcolor = 0\n\t\tnew_colors.append(color)\n\n\tgame_control.bg_color.r = new_colors[0]\n\tgame_control.bg_color.g = new_colors[1]\n\tgame_control.bg_color.b = new_colors[2]\n\ndef _randomize_colors(game_control):\n\tnew_colors = []\n\tfor color in [game_control.bg_color.r, game_control.bg_color.g, game_control.bg_color.b]:\n\t\tchange_amount = random.randrange(-4,5)\n\t\tif color + change_amount <= 255 and color + change_amount >= 0:\n\t\t\tcolor += change_amount\n\t\telif change_amount>0:\n\t\t\tcolor = 255\n\t\telse:\n\t\t\tcolor = 0\n\t\tnew_colors.append(color)\n\n\tgame_control.bg_color.r = new_colors[0]\n\tgame_control.bg_color.g = new_colors[1]\n\tgame_control.bg_color.b = new_colors[2]\n\ndef _return_to_white(game_control):\n\tgame_control.bg_color= pygame.Color(255,255,255)\n\t\ndef _update_screen(game_control):\n\tgame_control.screen.fill(game_control.bg_color)\n\tbackground_image = _choose_cat_image(game_control)\n\tgame_control.screen.blit(background_image, (0,0))\n\tif game_control.rainbow_mode:\n\t\tgame_control.screen.blit(game_control.RAINBOW_IMAGE, (20,450-64-20))\t\t\n\telse:\n\t\tif game_control.lightswitch_mode:\n\t\t\tgame_control.screen.blit(game_control.BULB_IMAGE, (20,450-64-20))\n\t\tif game_control.disco_mode:\n\t\t\tgame_control.screen.blit(game_control.DISCO_IMAGE, (20+64,450-64-20))\n\t_display_soundtrack(game_control)\n\tpygame.display.update()\n\t\ndef _display_soundtrack(game_control):\n\tgame_control.screen.blit(game_control.text_render, (800 - 300, 450 - 24 - 20))\n\t\ndef _choose_cat_image(game_control):\n\tif game_control.left_down and game_control.right_down:\n\t\treturn game_control.CAT_BOTH_DOWN_IMAGE\n\telif game_control.left_down:\n\t\treturn game_control.CAT_LEFT_DOWN_IMAGE\n\telif game_control.right_down:\n\t\treturn game_control.CAT_RIGHT_DOWN_IMAGE\n\telse:\n\t\treturn game_control.CAT_NONE_DOWN_IMAGE\n\ndef _toggle_song(game_control, toggle_direction):\n\tpygame.mixer.music.stop()\n\tgame_control.cur_song += toggle_direction\n\tif game_control.cur_song >= len(game_control.song_list):\n\t\tgame_control.cur_song -= len(game_control.song_list) + 1\n\tif game_control.cur_song < -1:\n\t\tgame_control.cur_song = len(game_control.song_list) - 1\n\tif not game_control.cur_song == -1:\n\t\tpygame.mixer.music.load(game_control.song_list[game_control.cur_song])\n\t\tpygame.mixer.music.set_volume(game_control.SONG_VOLUME)\n\t\tpygame.mixer.music.play()\n\tgame_control._update_text_render()\n\t\t\nif __name__==\"__main__\":\n\tmain()" } ]
2
sKryptonite/ozodlik
https://github.com/sKryptonite/ozodlik
ba3f8fa5a91ac0b0079cc6ccda0a7fcab4bd2367
9d6528a499718c9d381a752953877700f7629af6
b7e9e6d3e1356cdb71ca7e45321333f650ac281a
refs/heads/master
2022-12-14T05:16:35.694255
2020-08-25T14:22:00
2020-08-25T14:22:00
278,443,337
0
1
null
2020-07-09T18:39:10
2020-07-21T11:24:51
2020-08-11T06:27:24
Python
[ { "alpha_fraction": 0.5512943267822266, "alphanum_fraction": 0.5551294088363647, "avg_line_length": 31.645160675048828, "blob_id": "261591c27920547c9b8799af96c8b7d0d250b0e2", "content_id": "b507486d505dfb50e21e1e3626b223515cd8f681", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1043, "license_type": "no_license", "max_line_length": 81, "num_lines": 31, "path": "/ozodlikorg/ozodlikorg/spiders/02_polygraph.py", "repo_name": "sKryptonite/ozodlik", "src_encoding": "UTF-8", "text": "import scrapy\r\nfrom ..items import OzodlikorgItem\r\n\r\nclass OzodlikSpider(scrapy.Spider):\r\n name = 'polygraph'\r\n def __init__(self, *a, **kw):\r\n super(OzodlikSpider, self).__init__(*a, **kw)\r\n self.name2 = kw.get('name2')\r\n self.start_urls = ['https://www.polygraph.info/s?k=%s' % self.name2]\r\n\r\n def parse(self, response):\r\n\r\n items = OzodlikorgItem()\r\n\r\n all_div = response.css('.fui-grid__inner')\r\n\r\n for media in all_div:\r\n title = media.css('.media-block__title--size-3::text').extract()\r\n content = media.css('.perex--mb::text').extract()\r\n author = media.css('.links__item-link::text').extract()\r\n\r\n items['title'] = title\r\n items['content'] = content\r\n items['author'] = author\r\n\r\n yield items\r\n\r\n next_page = response.css('li.pagination__item--next a::attr(href)').get()\r\n print(next_page)\r\n if next_page is not None:\r\n yield response.follow(next_page, callback=self.parse)\r\n" }, { "alpha_fraction": 0.5714285969734192, "alphanum_fraction": 0.5797101259231567, "avg_line_length": 28.3125, "blob_id": "db659702531629c34a8a29b50396e4929aa0dbbb", "content_id": "efd1bf05beae127197d35d1205a51bbc1fe8df60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 483, "license_type": "no_license", "max_line_length": 79, "num_lines": 16, "path": "/ozodlikorg/ozodlikorg/__init__.py", "repo_name": "sKryptonite/ozodlik", "src_encoding": "UTF-8", "text": "# This package will contain the spiders of your Scrapy project\r\n#\r\n# Please refer to the documentation for information on how to create and manage\r\n# your spiders.\r\n\r\n\r\n# class OzodlikSpider(scrapy.Spider):\r\n# name = 'rferl'\r\n# name2 = input(\"Search for: \")\r\n# start_urls = [\r\n# 'https://www.rferl.org/s?k=%s' % name2\r\n# ]\r\n#\r\n# def __init__(self, *a, **kw):\r\n# super(OzodlikSpider, self).__init__(*a, **kw)\r\n# self.name2 = kw.get('name2')" }, { "alpha_fraction": 0.5122950673103333, "alphanum_fraction": 0.522648811340332, "avg_line_length": 42.57692337036133, "blob_id": "da86e3cbcfcef2d74f9ff064a778facec06e8e20", "content_id": "deaa84d834921692f81041b62ea648ddfa7c18d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4636, "license_type": "no_license", "max_line_length": 81, "num_lines": 104, "path": "/ozodlikorg/ozodlikorg/spiders/ozodlik_spider.py", "repo_name": "sKryptonite/ozodlik", "src_encoding": "UTF-8", "text": "import scrapy\r\nfrom ..items import OzodlikorgItem\r\n\r\nclass OzodlikSpider(scrapy.Spider):\r\n name = 'ozodlik'\r\n # name2 = input(\"Search for: \")\r\n name2 = ''\r\n start_urls = [\r\n 'https://www.rferl.org/s?k=%s' % name2,\r\n 'https://www.polygraph.info/s?k=%s' % name2,\r\n 'https://pressroom.rferl.org/s?k=%s' % name2,\r\n 'https://www.currenttime.tv/s?k=%s' % name2,\r\n # 'https://www.currenttime.tv/tv',\r\n 'https://en.currenttime.tv/s?k=%s' % name2,\r\n 'https: // www.svaboda.org/s?k=%s' % name2,\r\n # 'https: // www.svaboda.org / radio',\r\n 'https://www.radiosvoboda.org/s?k=%s' % name2,\r\n # 'https: // www.radiosvoboda.org / radio',\r\n 'https://ktat.krymr.com/s?k=%s' % name2,\r\n 'https://ua.krymr.com/s?k=%s' % name2,\r\n # 'https: // ua.krymr.com / radio',\r\n 'https://ru.krymr.com/s?k=%s' % name2,\r\n # 'https: // ru.krymr.com / radio',\r\n 'https://moldova.europalibera.org/s?k=%s' % name2,\r\n # 'https: // moldova.europalibera.org / radio',\r\n 'https://romania.europalibera.org/s?k=%s' % name2,\r\n 'https://www.svobodnaevropa.bg/s?k=%s' % name2,\r\n 'https://www.slobodnaevropa.org/s?k=%s' % name2,\r\n # 'https: // www.slobodnaevropa.org / radio',\r\n 'https://www.slobodnaevropa.mk/s?k=%s' % name2,\r\n # 'https: // www.slobodnaevropa.mk / radio',\r\n 'https://www.evropaelire.org/s?k=%s' % name2,\r\n # 'https: // www.evropaelire.org / radio',\r\n 'https://www.svoboda.org/s?k=%s' % name2,\r\n # 'https: // www.svoboda.org / radio',\r\n # 'https: // www.svoboda.org / tv',\r\n 'https://www.severreal.org/s?k=%s' % name2,\r\n 'https://www.sibreal.org/s?k=%s' % name2,\r\n 'https://www.factograph.info/s?k=%s' % name2,\r\n 'https://www.azatliq.org/s?k=%s' % name2,\r\n 'https://www.idelreal.org/s?k=%s' % name2,\r\n 'https://www.kavkazr.com/s?k=%s' % name2,\r\n 'https://www.radiomarsho.com/s?k=%s' % name2,\r\n 'https://www.azatutyun.am/s?k=%s' % name2,\r\n # 'https: // www.azatutyun.am / radio',\r\n 'https://rus.azatutyun.am/s?k=%s' % name2,\r\n 'https://www.azadliq.org/s?k=%s' % name2,\r\n # 'https: // www.azadliq.org / radio',\r\n 'https://www.radiotavisupleba.ge/s?k=%s' % name2,\r\n # 'https: // www.radiotavisupleba.ge / radio',\r\n 'https://www.ekhokavkaza.com/s?k=%s' % name2,\r\n # 'https: // www.ekhokavkaza.com / radio',\r\n 'https://www.radiofarda.com/s?k=%s' % name2,\r\n # 'https: // www.radiofarda.com / radio',\r\n # 'https: // www.radiofarda.com / tv',\r\n 'https://en.radiofarda.com/s?k=%s' % name2,\r\n 'https://www.azattyq.org/s?k=%s' % name2,\r\n 'https://rus.azattyq.org/s?k=%s' % name2,\r\n 'https://www.azattyk.org/s?k=%s' % name2,\r\n # 'https: // www.azattyk.org / radio',\r\n # 'https: // www.azattyk.org / tv',\r\n 'https://rus.azattyk.org/s?k=%s' % name2,\r\n # 'https: // rus.azattyk.org / radio',\r\n 'https://www.ozodi.org/s?k=%s' % name2,\r\n # 'https: // www.ozodi.org / radio',\r\n # 'https: // www.ozodi.org / tv',\r\n 'https://rus.ozodi.org/s?k=%s' % name2,\r\n 'https://www.azathabar.com/s?k=%s' % name2,\r\n # 'https: // www.azathabar.com / radio',\r\n 'https://rus.azathabar.com/s?k=%s' % name2,\r\n 'https://www.ozodlik.org/s?k=%s' % name2,\r\n # 'https: // www.ozodlik.org / radio',\r\n 'https://rus.ozodlik.org/s?k=%s' % name2,\r\n 'https://pa.azadiradio.com/s?k=%s' % name2,\r\n # 'https: // pa.azadiradio.com / radio',\r\n 'https://da.azadiradio.com/s?k=%s' % name2,\r\n # 'https: // da.azadiradio.com / radio',\r\n 'https://gandhara.rferl.org/s?k=%s' % name2,\r\n 'https://www.mashaalradio.com/s?k=%s' % name2,\r\n # 'https: // www.mashaalradio.com / radio',\r\n\r\n ]\r\n\r\n def parse(self, response):\r\n\r\n items = OzodlikorgItem()\r\n\r\n all_div = response.css('.fui-grid__inner')\r\n\r\n for media in all_div:\r\n title = media.css('.media-block__title--size-3::text').extract()\r\n content = media.css('.perex--mb::text').extract()\r\n author = media.css('.links__item-link::text').extract()\r\n\r\n items['title'] = title\r\n items['content'] = content\r\n items['author'] = author\r\n\r\n yield items\r\n\r\n next_page = response.css('li.pagination__item--next a::attr(href)').get()\r\n print(next_page)\r\n if next_page is not None:\r\n yield response.follow(next_page, callback=self.parse)\r\n" }, { "alpha_fraction": 0.5880829095840454, "alphanum_fraction": 0.5939119458198547, "avg_line_length": 30.510204315185547, "blob_id": "a0e6eb4beb9eeb3a66ecaf58adebdc390354c48a", "content_id": "441b3e68f3c47a508baf1056d453bf086e179f91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3088, "license_type": "no_license", "max_line_length": 119, "num_lines": 98, "path": "/ozodlikorg/ozodlikorg/Unitest/unitest.py", "repo_name": "sKryptonite/ozodlik", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport unittest\nimport requests\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), '../..'))\nsys.path.insert(0, BASE_DIR + '/spiders')\n\nfrom ozodlik_spider1 import OzodlikSpider\nfrom scrapy.crawler import CrawlerProcess\nfrom scrapy.http import Request, TextResponse, Response, HtmlResponse\n\n\n\nclass OzodlikTestCase(unittest.TestCase):\n\n def setUp(self):\n \"\"\"Set up for test\"\"\"\n print(\"Set up for [\" + str(self.shortDescription()) + \"]\")\n self.spider = OzodlikSpider()\n self.testfile = open('features_ozodlik_1.html', errors='ignore')\n self.testdata = self.testfile.read()\n\n def tearDown(self):\n \"\"\"Tear down for test\"\"\"\n print(\"Tear down for [\" + str(self.shortDescription()) + \"]\")\n print(\"\")\n self.testfile.close()\n\n def test_upper(self):\n \"\"\"Uppercase operation test\"\"\"\n self.assertEqual('foo'.upper(), 'FOO')\n\n def test_isupper(self):\n \"\"\"Uppercase assertTrue/assertFalse test\"\"\"\n self.assertTrue('FOO'.isupper())\n self.assertFalse('Foo'.isupper())\n\n def test_split(self):\n \"\"\"Split operation test\"\"\"\n s = 'hello world'\n self.assertEqual(s.split(), ['hello', 'world'])\n # check that s.split fails when the separator is not a string\n with self.assertRaises(TypeError):\n s.split(2)\n\n def _test_item_results(self, results, expected_length):\n count = 0\n for item in results:\n if not self.assertIsNotNone(item['title']):\n count += 1\n self.assertEqual(count, expected_length)\n\n def fake_response(self, file_name=None):\n request = Request(url='http://www.example.com')\n return HtmlResponse(\n url='http://www.example.com',\n request=request,\n body=self.testdata,\n encoding='utf-8'\n )\n\n def online_response(self, url=None):\n request = Request(url=url)\n return HtmlResponse(\n url=url,\n request=request,\n body=requests.get(url).text,\n encoding='utf-8'\n )\n\n def test_file_parse(self):\n \"\"\"Parse fake response test\"\"\"\n print(\"id: \" + self.id())\n results = self.spider.parse(self.fake_response(file_name='features_ozodlik_1.html'))\n self._test_item_results(results, 10)\n\n def test_requests_parse(self):\n \"\"\"Parse requests test\"\"\"\n print(\"id: \" + self.id())\n results = self.spider.parse(self.online_response(url='https://www.rferl.org/s?k=USA&tab=all&pi=1&r=any&pp=10'))\n self._test_item_results(results, 10)\n\n def str_par(self):\n return 'This is a monkey function'\n\n def test_monkey(self):\n \"\"\"Monkey patching\"\"\"\n print(\"id: \" + self.id())\n self.spider.parse = self.str_par\n results = self.spider.parse()\n self.assertEqual(results, 'This is a monkey')\n\n\nif __name__ == '__main__':\n unittest.main()\n" } ]
4
jQwotos/anime_scrapers
https://github.com/jQwotos/anime_scrapers
578bb1404d2f3a47d35cc10e83e2ba3b7d4a2287
f16d2085a956f43e48ab8bf0d3c3d7ad3d8b1d01
cb9276dee26bf600756f20e2bb256b43e70648ec
refs/heads/master
2020-12-03T06:40:15.239364
2018-01-29T22:15:09
2018-01-29T22:15:09
95,715,678
20
9
null
2017-06-28T22:07:32
2017-07-16T00:12:40
2017-10-11T19:33:37
Python
[ { "alpha_fraction": 0.6839103102684021, "alphanum_fraction": 0.684893786907196, "avg_line_length": 23.44230842590332, "blob_id": "6d97d4480c23546ef370c3416be8da802714f5a9", "content_id": "143d6ab1961cdfbb3fbeb609fa1cd57845eda256", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5084, "license_type": "no_license", "max_line_length": 221, "num_lines": 208, "path": "/README.md", "repo_name": "jQwotos/anime_scrapers", "src_encoding": "UTF-8", "text": "# anime-scrapers\n\nAnime scrapers is a collection of scrapers that have been all unified.\n\n## Table of Contents\n- [Installation](#installation)\n - [Mac / OSX](#mac-osx)\n - [General Installation](#general-installation)\n- [Usage](#usage)\n - [Functions](#functions)\n - [Handlers](#handlers)\n - [Scraper Handler](#scraper_handler)\n - [Download Handler](#download_handler)\n - [Info Handler](#info_handler)\n - [Individual Scraper Functions](#individual-scraper-functions)\n- [Contributing](#contributing)\n - [URL Handling (matching_urls)](#url-handling-matching_urls)\n - [Adding a Scraper](#adding-a-scraper)\n - [Adding a Downloader](#adding-a-downloader)\n - [Adding an Info Collector](#adding-an-information-collector)\n- [Credits](#credits)\n\n## Installation\n\n### Mac (OSX)\n- Install [Brew](https://brew.sh/)\n- Install python3\n - `brew install python3`\n- Continue to general installation\n\n### General Installation\n- Clone repository\n - `git clone https://github.com/jQwotos/anime_scrapers`\n- Nav into repo\n - `cd anime_scrapers`\n- Install required python packages\n - `pip install -r requirements.txt`\n\n## Usage\n\nanime_scrapers is the backend that is to be used by other applications. You can however use it directly if you want by using the python shell, but it's better to use an application.\n\n### Functions\n\n#### Handlers\n\nHandlers are all classes, however each of them also have premade variables so you don't need to create a new object each time.\n\nFor example `scraper_handler.py` has\n\n`class ScraperHandler():`\n\nand\n\n`var scraper_handler`\n\n##### scraper_handler\n- `search(query, limited_modules[])`\n - Searches all scraper modules (or specified ones)\n- `resolve(link)`\n - Finds matching function in module and returns proper response\n\n##### download_handler\n- `resolve(link)`\n - Takes in a download data (typically gotten from a scraper_handler resolve)\n ```\n {\n 'epNum': 'name of file',\n 'sources': [\n 'link': 'link',\n 'type': 'typically mp4 or iframe',\n ]\n }\n ```\n\n##### info_handler\n\nFor information gathering, use the `info_handler.py`. The functions are -\n\n```\n# strict is a boolean, which if True, searches for exact query only.\nsearch(query, strict):\n return [\n {\n 'id': 'id of the show (int)',\n 'titles': 'Other names of the show (str)',\n }\n ]\n```\n\n```\ngetDetailedInfo(id):\n return [\n {\n 'id': 'return the id from the parameter (int)',\n 'other-show-stuff': 'Other info related to show.\n \t\t\t See anidb.py in info_collectors for example',\n ...\n }\n ]\n```\n\n#### Individual Scraper Functions\n\n```\nscrape_all_show_sources(link):\n return {\n 'episodes': [\n {\n 'epNumber', 'number as a string',\n 'sources', sourceType\n }\n ],\n 'title': 'title of the show',\n 'status': 'status of the show',\n 'host': 'host such as gogoanime',\n 'released': 'year released as a string',\n }\n```\n\n```\nsearch(query):\n return [\n {\n 'link': 'link to the show',\n 'title': 'title of the show',\n 'language': 'sub or dub',\n },\n ]\n```\n\n```\n_scrape_video_sources(link):\n return {\n 'epNum': 'episode number as a string',\n 'sources': sourceType\n }\n```\n\nSourceTypes are in the following format.\n```\n[\n {\n 'link': 'link to the mp4 or iframe embed',\n 'type': 'mp4 or iframe',\n }\n]\n```\n\n## Contributing\n\nWant to add a downloader or scraper or info collector?\nEach module must have\n- URL Handeling / a matching_urls variable that looks like this.\n\n### URL Handling (matching_urls)\nMost functions will go through functions until there is a matching url schema. Each scraper contains the following variable which is used by the handler in order to identify the correct module to use when resolving links.\n```\nmatching_urls = [\n {\n 'urls': ['regex match expression'],\n 'function': function that should be called,\n },\n]\n```\n\n### Adding a Scraper\nScrapers handle search queries, scraping episodes from hosts and scraping sources from those episodes.\n\nRefer to [Functions](#Functions) for data formatting\n\nScrapers should have a couple of functions\n- `search`\n- `scrape_all_show_sources`\n - scrapes all show details and episodes along with their direct sources\n\nOptionally there can also be\n- `_scrape_episode_source`\n - scrapes a single episode's source\n\n\nScrapers should be put into the `scrapers` folder\n\n### Adding a downloader\nDownloaders are what extract the direct link the the video file or download the file based off a filename.\n\nDownloaders need these functions.\n- `download(link, filename)`\n - returns True when download is successful or false if failed.\n\nDownloaders should be put into the `downloaders` folder\n\n### Adding an information collector\nInformation collectors collect various information about a particular anime series/movie.\n\nThey need these functions, which are mentioned in details above.\n- search\n- getDetailedInfo\n\nInfo collectors should also have the following variables\n- matching_urls\n\n- Put them in the `info_collectors` folder\n\n## Credits\n- jQwotos\n- FadedCoder\n- DxCx (NineAnimeUrlExtender)\n" }, { "alpha_fraction": 0.6031106114387512, "alphanum_fraction": 0.606566846370697, "avg_line_length": 32.38461685180664, "blob_id": "08b00af57fc8bfafd968793966477a4fbde3a87c", "content_id": "14f9e4121a2ed45fbf0eb1c7d7054252d0459306", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3472, "license_type": "no_license", "max_line_length": 79, "num_lines": 104, "path": "/info_collectors/anidb.py", "repo_name": "jQwotos/anime_scrapers", "src_encoding": "UTF-8", "text": "import requests\nimport os\nfrom bs4 import BeautifulSoup\nfrom difflib import SequenceMatcher\nimport sys\n\n# Constants\nBASE_URL = \"http://api.anidb.net:9001/httpapi?request=anime\"\nBASE_PATH = os.path.dirname(os.path.realpath(__file__))\nSEARCH_FILE = os.path.join(BASE_PATH, \"anime-titles.xml\")\nIMAGE_URL = \"http://img7.anidb.net/pics/anime/\"\nCLIENT = \"fadedanimefinder\"\nCLIENT_VERSION = 1\nMIN_SIMILARITY_RATIO = 0.5\n\nsys.path.append(BASE_PATH)\nfrom _init_anidb import download_list\n\n\ndef _similar(original_txt, matched_txt):\n return SequenceMatcher(None, original_txt, matched_txt).ratio()\n\n\ndef search(query, strict=False):\n '''\n Search for a particular anime among the DB.\n In this module, `strict` is a dummy parameter, and does not do anything.\n Returns a list which contains a dict, containing the show ID and different\n names. Use that ID to get detailed info via getDetailedInfo(ID).\n '''\n download_list.get_file()\n\n with open(SEARCH_FILE, \"rb\") as f:\n search_contents = f.read()\n result_page = BeautifulSoup(search_contents, \"xml\").animetitles\n\n results = list()\n ratio_list = list()\n for anime in result_page.findAll(\"anime\"):\n highest_ratio = 0\n for title in anime.findAll(\"title\"):\n ratio = _similar(query, title.string)\n if ratio > MIN_SIMILARITY_RATIO:\n if ratio > highest_ratio:\n highest_ratio = ratio\n if not highest_ratio:\n continue\n ratio_list.append(highest_ratio)\n id = int(anime['aid'])\n titles = [title.string for title in\n anime.findAll(\"title\", attrs={\"type\": [\"main\", \"official\"]})]\n results.append({\"id\": id, \"titles\": titles})\n return [x for (y, x) in\n sorted(list(zip(ratio_list, results)),\n key=lambda pair: pair[0], reverse=True)]\n\n\ndef getDetailedInfo(id):\n '''\n Gets a detailed info from the ID provided. A dict is returned with\n the following keys. The type of the value is also mentioned.\n\n id: int, type: str, start_date: str, end_date: str, other_names: str,\n creators: [{str: str}], permanent_rating: float, image_url: str,\n description: str, recommendations: [{str: str}]\n '''\n request = requests.get(BASE_URL, params={\n \"request\": \"anime\",\n \"aid\": str(id),\n \"protover\": \"1\",\n \"client\": CLIENT,\n \"clientver\": str(CLIENT_VERSION)\n })\n request.raise_for_status()\n result_page = BeautifulSoup(request.text, \"xml\")\n\n results = {\n \"id\": id,\n \"type\": result_page.find(\"type\").string,\n \"episode_count\": result_page.find(\"episodecount\").string,\n \"start_date\": result_page.find(\"startdate\").string,\n \"end_date\": result_page.find(\"enddate\").string,\n \"other_names\": [title.string for title in\n result_page.find(\"titles\").findAll(\"title\")],\n \"creators\": [{name['type']: name.string}\n for name in result_page.find(\"creators\").findAll(\"name\")],\n \"permanent_rating\": float(result_page.find(\"ratings\")\n .find(\"permanent\").string),\n \"image_url\": IMAGE_URL + result_page.find(\"picture\").string,\n \"description\": result_page.find(\"description\").string\n }\n return results\n\n\nmatching_urls = [\n {\n 'urls': [],\n 'function': search,\n },\n {\n 'urls': [],\n 'function': getDetailedInfo,\n },\n]\n" }, { "alpha_fraction": 0.5028790831565857, "alphanum_fraction": 0.5047984719276428, "avg_line_length": 32.9782600402832, "blob_id": "9cf65d46a2e35d522d7e5f8755b4a733c62754c7", "content_id": "9587cf01af622fa6d855099cf81559182edb466c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1563, "license_type": "no_license", "max_line_length": 89, "num_lines": 46, "path": "/download_handler.py", "repo_name": "jQwotos/anime_scrapers", "src_encoding": "UTF-8", "text": "import logging\n\nfrom .templates.module_search import ModuleSearch\n\n\nclass DownloadHandler(ModuleSearch):\n # Deals with resolving downloading of files\n def __init__(self):\n self._get_modules('downloaders')\n\n def single_download(self, link, abs_path):\n \"\"\"\n Download a single episode.\n 'link' is the full link of it (get it with scraper_handler).\n 'abs_path' is full path + filename of downloaded file, example -\n \"/home/User/MyDownloadedEpisode.mp4\"\n \"\"\"\n for module in self.modules:\n if self._try_match_module(link, module):\n if module.download(link, abs_path):\n return True\n return False\n return False\n\n def resolve(self, data):\n logging.info(\n \"Trying to resolve '%s'\"\n % (data['epNum'])\n )\n for module in self.modules:\n for source in data['sources']:\n logging.info(\n \"Trying to resolve '%s' source.\"\n % (source['link'])\n )\n if self._try_match_module(source['link'], module):\n logging.info(\n \"Found a matching module for '%s'.\"\n % (source,)\n )\n # PEP8 Too long\n fileName = \"%s.mp4\" % (data['epNum'],) if 'epNum' in data else source\n if module.download(source['link'], fileName):\n break\n\ndownload_handler = DownloadHandler()\n" }, { "alpha_fraction": 0.5348837375640869, "alphanum_fraction": 0.5388704538345337, "avg_line_length": 28.509803771972656, "blob_id": "09141f94d2243c3f34d4a318af3e0bdd041ea949", "content_id": "816e2cfdd791a2ea221364574a702ef0cb8e493b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1505, "license_type": "no_license", "max_line_length": 63, "num_lines": 51, "path": "/info_collectors/_init_anidb.py", "repo_name": "jQwotos/anime_scrapers", "src_encoding": "UTF-8", "text": "from datetime import date\nimport requests\nimport os\n\n\nBASE_PATH = os.path.dirname(os.path.realpath(__file__))\nINFO_FILE = os.path.join(BASE_PATH, \"last_download.txt\")\nDOWNLOAD_URL = \"http://anidb.net/api/anime-titles.xml.gz\"\nDOWNLOAD_FILE = os.path.join(BASE_PATH, \"anime-titles.xml\")\n\n\nclass DownloadList:\n\n def __init__(self):\n self.need_download = self.need_to_download()\n\n def need_to_download(self):\n try:\n with open(INFO_FILE, \"r\") as f:\n data = f.readline()\n if len(data) > 0:\n last_download = date.fromordinal(int(data))\n time_delta = date.today() - last_download\n if time_delta.days > 7:\n return True\n else:\n return False\n else:\n return True\n except FileNotFoundError:\n return True\n return False\n\n def write_today_ordinal(self):\n with open(INFO_FILE, \"w\") as f:\n f.write(str(date.today().toordinal()) + \"\\n\")\n\n def download_list(self):\n request = requests.get(DOWNLOAD_URL, stream=True)\n with open(DOWNLOAD_FILE, \"wb\") as f:\n for chunk in request.iter_content(chunk_size=1024):\n if chunk:\n f.write(chunk)\n\n def get_file(self):\n if self.need_to_download():\n self.write_today_ordinal()\n self.download_list()\n\n\ndownload_list = DownloadList()\n" }, { "alpha_fraction": 0.8163265585899353, "alphanum_fraction": 0.8571428656578064, "avg_line_length": 6, "blob_id": "ac91f7db9a66d0954ac74fc38ef3ade75849ae91", "content_id": "67bf4ad4fd0c6e9ccb06c2ec2128cd493527c4c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 49, "license_type": "no_license", "max_line_length": 8, "num_lines": 7, "path": "/requirements.txt", "repo_name": "jQwotos/anime_scrapers", "src_encoding": "UTF-8", "text": "bs4\ncfscrape\nrequests\nfurl\nhtml5lib\nlxml\ndemjson\n" }, { "alpha_fraction": 0.5684547424316406, "alphanum_fraction": 0.5713904500007629, "avg_line_length": 24.664382934570312, "blob_id": "7f748c6bd67b3fbd94f7de2aa8c846fcf6b0e7b1", "content_id": "5fa8b4cf5951344ca06e659c83f72e660bafca68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3747, "license_type": "no_license", "max_line_length": 79, "num_lines": 146, "path": "/scrapers/anime9.py", "repo_name": "jQwotos/anime_scrapers", "src_encoding": "UTF-8", "text": "import logging\n\nimport requests\n\nfrom bs4 import BeautifulSoup as bs\n\nsite_name = \"9anime.is\"\n\nBASE_URL = 'https://9anime.is'\nSEARCH_URL = '%s/search' % (BASE_URL,)\nINFO_API_URL = \"%s/ajax/episode/info\" % (BASE_URL,)\n\n\ndef _parse_search_single(data):\n img = data.find(\"img\")\n nameAnchor = data.find(\"a\", {\"class\": \"name\"})\n lang = data.find('div', {'class': 'lang'})\n lang = lang.text if lang is not None else 'sub'\n\n return {\n 'title': nameAnchor.text,\n 'link': nameAnchor['href'],\n 'language': lang.lower(),\n 'host': site_name,\n 'poster': img['src']\n }\n\n\ndef _parse_search_multi(data):\n return [\n _parse_search_single(x)\n for x in data.findAll(\"div\", {\"class\": \"item\"})\n ]\n\n\ndef search(query):\n params = {\n 'keyword': query,\n }\n data = bs(requests.get(SEARCH_URL, params=params).content)\n\n return _parse_search_multi(data)\n\n\ndef _scrape_episode_source(data):\n return {\n 'link': data['file'],\n 'type': data['type'],\n 'quality': data['label'],\n }\n\n\ndef _scrape_episode_sources(data):\n request = requests.get(data['grabber'], params=data['params']).json()\n return [_scrape_episode_source(x) for x in request['data']]\n\n\ndef _scrape_episode_info(id):\n logging.debug(\"'%s' is performing a info grab for '%s'\" % (site_name, id,))\n params = {'id': id}\n data = requests.get(INFO_API_URL, params=params)\n if data.status_code == 200:\n data = data.json()\n if data.get('target') == '' or data.get('type') == 'direct':\n return _scrape_episode_sources(data)\n else:\n return {\n 'link': data.get('target'),\n 'type': data.get('type'),\n }\n\n\ndef _parse_server_single_episode(data):\n anchor = data.find(\"a\")\n id = anchor['data-id']\n output = {\n 'data-id': id,\n 'epNum': anchor.text,\n 'sources': _scrape_episode_info(id),\n }\n return output if output['sources'] is not None else None\n\n\ndef _parse_server_episodes(data):\n episodes = data.findAll(\"li\")\n sources = [_parse_server_single_episode(x) for x in episodes]\n if len(sources) > 0:\n return list(filter(None, sources))\n\n\ndef _scrape_all_servers(data):\n servers = data.findAll(\"ul\", {\"class\": \"episodes range active\"})\n sourcedServers = [_parse_server_episodes(x) for x in servers]\n return list(filter(None, sourcedServers))\n\n\ndef format_combine_multi(unformatedOutput):\n output = []\n for ep in unformatedOutput:\n output.append({\n 'epNum': str(int(ep)), # remove leading 0s\n 'sources': unformatedOutput[ep]\n })\n return output\n\n\ndef combine_multi(servers):\n unformatedOutput = {}\n print(servers)\n for server in servers:\n for ep in server:\n if ep['epNum'] not in unformatedOutput:\n unformatedOutput[ep['epNum']] = [ep['sources']]\n else:\n unformatedOutput[ep['epNum']] += [ep['sources']]\n\n return format_combine_multi(unformatedOutput)\n\n\ndef _scrape_title(data):\n return data.find('h1', {'class': 'title'}).text\n\n\ndef scrape_all_show_sources(link):\n logging.info(\n \"A request for '%s' was made under %s scraper.\" %\n (link, site_name)\n )\n data = bs(requests.get(link).content, 'html.parser')\n body = data.find('body')\n servers = _scrape_all_servers(data)\n return {\n 'episodes': combine_multi(servers),\n 'title': _scrape_title(data),\n 'host': site_name,\n }\n\nmatching_urls = [\n {\n 'urls': [\n r'https://9anime.to/watch/(.*).(.*)',\n r'https://9anime.is/watch/(.*).(.*)'\n ],\n 'function': scrape_all_show_sources,\n },\n]\n" }, { "alpha_fraction": 0.6199095249176025, "alphanum_fraction": 0.6199095249176025, "avg_line_length": 21.86206817626953, "blob_id": "0488d3b157e2618a598f1c23f891f1ea8ece03e9", "content_id": "3b7f26538d3f67dc74663eaf7699e0296ac6ec3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 663, "license_type": "no_license", "max_line_length": 61, "num_lines": 29, "path": "/info_handler.py", "repo_name": "jQwotos/anime_scrapers", "src_encoding": "UTF-8", "text": "import glob\n\nfrom .templates.module_search import ModuleSearch\n\n\nclass InfoHandler(ModuleSearch):\n\n def __init__(self):\n self._get_modules('info_collectors')\n\n def _search_module(self, query, strict, module):\n return module.search(query, strict)\n\n def search(self, query, strict=False):\n return [\n self._search_module(query, strict, x)\n for x in self.modules\n ]\n\n def _details_module(self, id, module):\n return module.getDetailedInfo(id)\n\n def getDetailedInfo(self, id):\n return [\n self._details_module(id, x) for x in self.modules\n ]\n\n\ninfo_handler = InfoHandler()\n" }, { "alpha_fraction": 0.732824444770813, "alphanum_fraction": 0.732824444770813, "avg_line_length": 31.75, "blob_id": "42479bf82daa05076f90950d7587b026d1f73911", "content_id": "72f307f03d4ca38980cdcf35788f0202eb8f7f34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 131, "license_type": "no_license", "max_line_length": 41, "num_lines": 4, "path": "/test.py", "repo_name": "jQwotos/anime_scrapers", "src_encoding": "UTF-8", "text": "import os\nfileLocation = os.path.realpath(__file__)\ndirectory = os.path.dirname(fileLocation)\nprint(os.path.join(directory, \"..\"))\n" }, { "alpha_fraction": 0.5739078521728516, "alphanum_fraction": 0.576301634311676, "avg_line_length": 31.764705657958984, "blob_id": "a411da6348ee8e2de25e902beff2000cddd58cbe", "content_id": "18658077970a5523534fa938cfe3a719386bb667", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1671, "license_type": "no_license", "max_line_length": 79, "num_lines": 51, "path": "/templates/module_search.py", "repo_name": "jQwotos/anime_scrapers", "src_encoding": "UTF-8", "text": "import glob\nimport imp\nimport logging\nimport os\nimport re\n\n\nclass ModuleSearch(object):\n def _load_single_module(self, f):\n return imp.load_source(f[:-3], f)\n\n def _load_modules(self):\n return [self._load_single_module(x) for x in self.modules]\n\n def _try_match_url(self, link, matchingURL):\n return True if re.match(matchingURL, link) is not None else False\n\n def _try_match_module_section(self, link, section):\n urls = section['urls']\n matches = [\n section['function'] for x in urls\n if self._try_match_url(link, x) is not False\n ]\n return True if len(matches) > 0 else False\n\n def _try_match_module(self, link, module):\n sections = module.matching_urls\n return [x['function'] for x in sections\n if self._try_match_module_section(link, x) is not False]\n\n def __is_underscore(self, f):\n if f[f.rfind('/') + 1] == \"_\":\n return True\n return False\n\n def _get_modules(self, location):\n fileLocation = os.path.realpath(__file__)\n directory = os.path.dirname(fileLocation)\n self.module_location = os.path.join(directory, '..', location)\n self.modules = glob.glob(\"%s/*.py\" % (self.module_location))\n self.modules = [\n module for module in self.modules\n if not self.__is_underscore(module)\n ]\n '''\n for i in range(len(self.modules)): # Delete modules beginning with '_'\n module = self.modules[i]\n if module[module.rfind(\"/\") + 1] == \"_\":\n del self.modules[i]\n '''\n self.modules = self._load_modules()\n" } ]
9
rdc2732/fmm_graph
https://github.com/rdc2732/fmm_graph
19d7b0e2a1f82b8cfb39283800543584f3328cd6
4c1e66f3cbb10ad27fd020218edb2ff29b6ee6fd
c8d47208a42636f3c8e46809d71bb99992b68778
refs/heads/master
2020-03-28T17:43:15.811302
2018-12-21T14:29:59
2018-12-21T14:29:59
148,816,159
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6333281993865967, "alphanum_fraction": 0.6397610902786255, "avg_line_length": 29.358139038085938, "blob_id": "5817b2f151bcbde343472691cb2d65667cc28884", "content_id": "3df5ae98309b9d8210e9fb944988ade5b16a306b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6529, "license_type": "no_license", "max_line_length": 108, "num_lines": 215, "path": "/fmm_graph.py", "repo_name": "rdc2732/fmm_graph", "src_encoding": "UTF-8", "text": "# fmm_graph.py\n# This program will loop through a CSV file exported from the DOORS FMM module. Each line of the file\n# contains a FMM keyword. Many of the keywords are dependent upon other keywords. This program will\n# parse the file and extract all keywords, and build a directed graph that shows all dependencies.\n#\n# The program will output a .gfz file to allow Graphiz to build a directed graph of the signals and modules.\n# Sqlite will be used to store the keywords, and then queried to create the data sets for the .gfx.\n#\n# Parsing the FMM.csv file:\n# - Column headings (import columns marked with *):\n# FM Selection GUI tab\n# Function\n# Selectable Options\n# FM Selection*\n# FM Selection Dependencies*\n# Rule Type\n# Selection Min\n# Selection Max\n\nimport re\nimport csv\nimport glob\nimport sqlite3\nimport subprocess\n\n# Define files\nsqldbfile = 'FMM.db'\ncsvfile = 'FMM.csv'\ndotfile = 'FMM.gfz'\ndotfile2 = 'FMM2.gfz'\noutfolder = './temp/'\n\n\n# Set up sqlite database\n# Keyword data will be organized in parent/child relationships.\n# - a keyword may be the child of (dependent on - depon) zero or more other keywords\n# - a keyword may be the parent of (dependency to - depto) zero or more other keywords\n# - depon refers to the dependency in FMM keywork, aka parent role\n# - depto refers to the keyword itself, aka child role\ncon = sqlite3.connect(sqldbfile)\ncur = con.cursor()\ncur.execute(\"DROP TABLE IF EXISTS Keywords\")\ncur.execute(\"DROP TABLE IF EXISTS KeyDepends\")\ncur.execute(\"CREATE TABLE Keywords (key_id INTEGER PRIMARY KEY, keyword TEXT, UNIQUE (keyword))\")\ncur.execute(\"CREATE TABLE KeyDepends (depon INTEGER, depto INTEGER, \\\n FOREIGN KEY (depon) REFERENCES Keywords(key_id), \\\n FOREIGN KEY (depto) REFERENCES Keywords(key_id))\")\n\n\n# Add new keyword to table if not exists. Return keyword ID\ndef addKeyword(keyWord):\n cur.execute('INSERT OR IGNORE INTO Keywords (keyword) VALUES (?)', (keyWord,))\n cur.execute('SELECT key_id FROM Keywords WHERE keyword = ?', (keyWord,))\n keyWordID = cur.fetchone()[0]\n return keyWordID\n\n\n# Add new keyword / dependency record\ndef addDependency(parent_id, child_id):\n cur.execute('INSERT OR IGNORE INTO KeyDepends (depon, depto) VALUES (?, ?)', (parent_id, child_id,))\n return\n\n\ndef find_all_paths(graph, start, path=[], level=0, skip = [0]):\n if not start in graph:\n return []\n path = path + [start]\n paths = [path]\n for node in graph[start]:\n level += 1\n if node not in skip:\n paths = paths + find_all_paths(graph, node, path, level)\n else:\n print('skipping node:', node)\n # Add a new keyWord to show items skipped\n skipped_name = keyWords[node] + \" skipped...\"\n keyWords[999] = skipped_name\n paths = paths + [[start, node],[node, 999]]\n return(paths)\n\n\n# CSV records; rec[0] = FM Keyword; rec[1] = list of FM Dependencies\nwith open(csvfile) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n line_count = 0\n for row in csv_reader:\n if line_count > 0:\n keyword_id = addKeyword(row[3])\n dependency_list = row[4].split(';')\n while '' in dependency_list: # Remove unfortunate trailing '' elements\n dependency_list.remove('')\n for dependency in dependency_list:\n dependency_id = addKeyword(dependency)\n addDependency(dependency_id, keyword_id)\n line_count += 1\n print(f'Processed {line_count} lines.')\n\n# Commit database\ncon.commit()\n\n\ngraph = {}\nkeyWords = {}\n\n# Get the list of all id's from the keywords table\nsql_query2 = \\\n \"\"\"\n select \n key_id, keyword from keywords\n ;\"\"\"\n\n\n# Make dictionary of key_id and keywords\ncur.execute(sql_query2)\nfor row in cur:\n keyWords[row[0]] = row[1]\n\n\n# Get this list of dependent ids for a given id\nsql_query3 = \\\n \"\"\"\n select\n depto\n from\n keydepends \n where\n depon = ?\n order by\n depon\n ;\"\"\"\n\n# Build out graph based on list of keys\nfor key in keyWords.keys():\n graph[key] = []\n cur.execute(sql_query3, (key,))\n for result in cur.fetchall():\n graph[key].append(result[0])\n\n\nsql_query4 = \\\n \"\"\"\n select key_id from keywords where key_id not in (select depto from keydepends) order by keyword;\n \"\"\"\n\n\ncur.execute(sql_query4)\ntop_nodes = []\ngfz_file_number = 0;\n\nfor result in cur.fetchall():\n top_nodes.append(result[0])\n\npdflist = []\nbookmarks = 'bookmark.txt'\nbookmarkFile = open(bookmarks, 'w')\n\nfor node in top_nodes:\n gfz_file_number += 1\n node_pairs = []\n\n dotfile = \"FMM_\" + str(gfz_file_number) + \".gfz\"\n pdffile = \"FMM_\" + str(gfz_file_number) + \".pdf\"\n\n node_name = keyWords[node]\n graph_title = '\"' + node_name + '\"'\n\n pathlist = find_all_paths(graph, node, [], 0, [])\n\n for path in pathlist:\n for n in range(len(path) - 1):\n node_pair = (path[n], path[n+1])\n if node_pair not in node_pairs:\n node_pairs.append(node_pair)\n\n # Make graphiz dot file from data\n myFile = open(dotfile, 'w')\n myFile.write('digraph ' + graph_title + ' {\\n')\n myFile.write('node [style=filled];\\n')\n myFile.write('size = \"8,10\";\\n')\n myFile.write('rankdir = LR;\\n')\n myFile.write('labelloc = \"t\";\\n')\n myFile.write(f'label = {graph_title};\\n')\n\n for node_pair in node_pairs:\n depon = keyWords[node_pair[0]]\n depto = keyWords[node_pair[1]]\n myFile.write(f' \\\"{depon}\\\" -> \\\"{depto}\\\" ;\\n')\n\n myFile.write(\"}\\n\")\n myFile.close()\n\n # Convert this newly minted gfz file to pdf\n subprocess.run(f'dot -Tpdf {dotfile} -o {pdffile}')\n pdflist.append(pdffile)\n\n # Make pdf table of contents file dot file from data\n bookmarkFile.write('BookmarkBegin\\n')\n bookmarkFile.write(f'BookmarkTitle: {node_name}\\n')\n bookmarkFile.write('BookmarkLevel: 1\\n')\n bookmarkFile.write(f'BookmarkPageNumber: {gfz_file_number}\\n')\n\nbookmarkFile.close()\npdffiles = ' '.join(pdflist)\n\nsubprocess.run(f'pdftk {pdffiles} cat output fmm_total.pdf')\nsubprocess.run(f'pdftk fmm_total.pdf update_info {bookmarks} output fmm_total_final.pdf')\n\n# Close database\ncon.close()\n\n# error check does not quite work to see if subnodes are subnodes of other nodes\n# for node in top_nodes:\n# print(\"node = \", keyWords[node])\n# for subnode in graph[node]:\n# print(\"\\tsubnode = \", keyWords[subnode])\n\n\n" }, { "alpha_fraction": 0.6158878207206726, "alphanum_fraction": 0.6214953064918518, "avg_line_length": 35.86206817626953, "blob_id": "f692ea13d616bc717d145848c20645a78088572d", "content_id": "38c17a69ae7aba47383f93e9f162d6b9d914b737", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1070, "license_type": "no_license", "max_line_length": 104, "num_lines": 29, "path": "/fmm_flat.py", "repo_name": "rdc2732/fmm_graph", "src_encoding": "UTF-8", "text": "# fmm_flat.py\n# This program will convert the FMM.csv file which has multiple dependencies on one line, to a different\n# format with one keyword/dependency per row. This will lend the data to be more easily analyzed with\n# Excel and pivot tables.\n\nimport re\nimport csv\nimport glob\n\n# Define files\ncsvfile = 'FMM.csv'\ncsvout = 'FMM-out.csv'\n\n# CSV records; rec[0] = FM Keyword; rec[1] = list of FM Dependencies\nwith open(csvfile) as csv_file:\n with open(csvout, 'w', newline='') as csv_out:\n csv_reader = csv.reader(csv_file, delimiter=',')\n csv_writer = csv.writer(csv_out, delimiter=',')\n line_count = 0\n for row in csv_reader:\n dependency_list = row[4].split(';')\n while '' in dependency_list: # Remove unfortunate trailing '' elements\n dependency_list.remove('')\n for dependency in dependency_list:\n new_row = row\n row[4] = dependency\n csv_writer.writerow(new_row)\n line_count += 1\n print(f'Processed {line_count} lines.')\n\n" }, { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 24, "blob_id": "347e726dec85468796cee62172f57ecb6a1aa33b", "content_id": "7115c88d84bb4754d4d1673af1e1d3278d3fe644", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 50, "license_type": "no_license", "max_line_length": 37, "num_lines": 2, "path": "/README.md", "repo_name": "rdc2732/fmm_graph", "src_encoding": "UTF-8", "text": "# fmm_graph\nCreate directed graph of FMM Keywords\n" }, { "alpha_fraction": 0.6617646813392639, "alphanum_fraction": 0.7009803652763367, "avg_line_length": 14.692307472229004, "blob_id": "aefc4c3fa321835918805591ae05582ba3e634b9", "content_id": "1caf8c2bf19e9f54db94490999028d0e708553c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 204, "license_type": "no_license", "max_line_length": 27, "num_lines": 13, "path": "/query.sql", "repo_name": "rdc2732/fmm_graph", "src_encoding": "UTF-8", "text": "select \n\tk1.keyword as Dependency, \n\tk2.keyword as Dependent \nfrom \n\tKeywords as k1,\n\tKeywords as K2,\n\tKeyDepends as d\nwhere\n\tk1.key_id = d.depon and\n\tk2.key_id = d.depto\norder by\n\tk1.key_id, k2.key_id\n;\n" } ]
4
khdc-me/ws-kevinharper-v1
https://github.com/khdc-me/ws-kevinharper-v1
90f885c0d99eac0dab8bc9dfed90df0b74caaa48
1237f2be490cb0513e82219d9d2eeffab061f747
bf2a7b197a15c56fe92fdc8467140d438751e2b9
refs/heads/master
2020-03-26T13:01:06.865718
2019-07-04T03:02:51
2019-07-04T03:02:51
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6890756487846375, "alphanum_fraction": 0.6890756487846375, "avg_line_length": 20, "blob_id": "f9f312da3cf57639424a1370a96654e6f0dc87f0", "content_id": "ee3772e24a3e450c3559b17daddde4f3972a4fc2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 357, "license_type": "no_license", "max_line_length": 50, "num_lines": 17, "path": "/website/pages/views.py", "repo_name": "khdc-me/ws-kevinharper-v1", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\n\n# Create your views here.\ndef home(request):\n return render(request, 'home.html', {})\n\n\ndef experience(request):\n return render(request, 'experience.html', {})\n\n\ndef my_portal(request):\n return render(request, 'my-portal.html', {})\n\n\ndef my_projects(request):\n return render(request, 'my-projects.html', {})\n" }, { "alpha_fraction": 0.6598639488220215, "alphanum_fraction": 0.6598639488220215, "avg_line_length": 28.399999618530273, "blob_id": "f444176b7bd976d3653ae441008a586fdd4e39e0", "content_id": "2de5c79ab590b52bfe2117f35c3b0e3b08bcc7fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 294, "license_type": "no_license", "max_line_length": 64, "num_lines": 10, "path": "/website/pages/urls.py", "repo_name": "khdc-me/ws-kevinharper-v1", "src_encoding": "UTF-8", "text": "from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.home, name='home'),\n path('experience/', views.experience, name='experience'),\n path('my-portal/', views.my_portal, name='my-portal'),\n path('my-projects/', views.my_projects, name='my-projects'),\n]\n" }, { "alpha_fraction": 0.7607260942459106, "alphanum_fraction": 0.7607260942459106, "avg_line_length": 39.400001525878906, "blob_id": "e64053b4d69e3b1da603b68c626454dd7d4e4319", "content_id": "e43952a21d0aee5a60dffa341b80c046e6cd5dbb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 606, "license_type": "no_license", "max_line_length": 170, "num_lines": 15, "path": "/README.md", "repo_name": "khdc-me/ws-kevinharper-v1", "src_encoding": "UTF-8", "text": "# ws-kevinharper\nCode repo for [kevinharper.com](https://kevinharper.com).\n\n## Project Build\n* Simple site to highlight skills and work history\n* Pages: main pg, experience pg, links pg (used almost like bookmarks)\n* Pages above work without JS\n* Sections: Blog, Git\n* Django Web Framework\n* Docker & Docker Compose for containerization, CI, & CD\n\n## Contribute\nThis project is a personal project and largely closed to pull requests.\n\nIf you do, however, find an error with code, security, or spelling/grammar, please let me know by [creating a new issue](https://github.com/khdc-me/ws-kevinharper/issues)\n" }, { "alpha_fraction": 0.4609375, "alphanum_fraction": 0.515625, "avg_line_length": 11.800000190734863, "blob_id": "52bfabbab2560c103112b889a8e03858d9a10222", "content_id": "2396314604ba0f54905786fef73581c4002ef7e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 128, "license_type": "no_license", "max_line_length": 23, "num_lines": 10, "path": "/config/settings/settings_prod.py", "repo_name": "khdc-me/ws-kevinharper-v1", "src_encoding": "UTF-8", "text": "from ._base import *\n\nALLOWED_HOSTS = [\n 'localhost',\n '127.0.0.1',\n '[::1]',\n '.kevinharper.com',\n]\n\nDEBUG = False\n" } ]
4