content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def pytest_addoption(parser):
selenium_class_names = ("Android", "Chrome", "Firefox", "Ie", "Opera", "PhantomJS", "Remote", "Safari")
parser.addoption("--webdriver", action="store", choices=selenium_class_names,
default="PhantomJS",
help="Selenium WebDriver interface to use for running the test. Default: PhantomJS")
parser.addoption("--webdriver-options", action="store", default="{}",
help="Python dictionary of options to pass to the Selenium WebDriver class. Default: {}")
| def pytest_addoption(parser):
selenium_class_names = ('Android', 'Chrome', 'Firefox', 'Ie', 'Opera', 'PhantomJS', 'Remote', 'Safari')
parser.addoption('--webdriver', action='store', choices=selenium_class_names, default='PhantomJS', help='Selenium WebDriver interface to use for running the test. Default: PhantomJS')
parser.addoption('--webdriver-options', action='store', default='{}', help='Python dictionary of options to pass to the Selenium WebDriver class. Default: {}') |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Simone Persiani <iosonopersia@gmail.com>
#
# Permission to use, copy, modify, and/or distribute this software for any purpose
# with or without fee is hereby granted, provided that the above copyright notice
# and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
# OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
# DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
# SOFTWARE.
# REQUIRED DIRECTORIES
meta_csv_output_dir = '<path>/meta_folder/csv_output/' # INPUT DIR
citations_csv_dir = '<path>/converter_folder/citations/' # INPUT DIR
converter_citations_csv_output_dir = '<path>/citations_folder/csv_output/' # OUTPUT DIR
converter_citations_rdf_output_dir = '<path>/citations_folder/rdf_output/' # OUTPUT DIR
# TRIPLESTORE and OC_OCDM
base_iri = "https://w3id.org/oc/meta/"
triplestore_url = "http://localhost:9999/blazegraph/sparql"
query_timeout = 3 # seconds
context_path = "https://w3id.org/oc/corpus/context.json"
info_dir = "<path>/meta_folder/info_dir/"
dir_split_number = 10000 # This must be multiple of the following one
items_per_file = 1000
default_dir = "_"
resp_agent = "https://w3id.org/oc/meta/prov/pa/1"
supplier_prefix = ""
# OPTIONS
rdf_output_in_chunks = True
| meta_csv_output_dir = '<path>/meta_folder/csv_output/'
citations_csv_dir = '<path>/converter_folder/citations/'
converter_citations_csv_output_dir = '<path>/citations_folder/csv_output/'
converter_citations_rdf_output_dir = '<path>/citations_folder/rdf_output/'
base_iri = 'https://w3id.org/oc/meta/'
triplestore_url = 'http://localhost:9999/blazegraph/sparql'
query_timeout = 3
context_path = 'https://w3id.org/oc/corpus/context.json'
info_dir = '<path>/meta_folder/info_dir/'
dir_split_number = 10000
items_per_file = 1000
default_dir = '_'
resp_agent = 'https://w3id.org/oc/meta/prov/pa/1'
supplier_prefix = ''
rdf_output_in_chunks = True |
# Time: O(m * n)
# Space: O(min(m, n))
class Solution(object):
def longestCommonSubsequence(self, text1, text2):
"""
:type text1: str
:type text2: str
:rtype: int
"""
if len(text1) < len(text2):
return self.longestCommonSubsequence(text2, text1)
dp = [[0 for _ in range(len(text2)+1)] for _ in range(2)]
for i in range(1, len(text1)+1):
for j in range(1, len(text2)+1):
dp[i%2][j] = dp[(i-1)%2][j-1]+1 if text1[i-1] == text2[j-1] \
else max(dp[(i-1)%2][j], dp[i%2][j-1])
return dp[len(text1)%2][len(text2)]
| class Solution(object):
def longest_common_subsequence(self, text1, text2):
"""
:type text1: str
:type text2: str
:rtype: int
"""
if len(text1) < len(text2):
return self.longestCommonSubsequence(text2, text1)
dp = [[0 for _ in range(len(text2) + 1)] for _ in range(2)]
for i in range(1, len(text1) + 1):
for j in range(1, len(text2) + 1):
dp[i % 2][j] = dp[(i - 1) % 2][j - 1] + 1 if text1[i - 1] == text2[j - 1] else max(dp[(i - 1) % 2][j], dp[i % 2][j - 1])
return dp[len(text1) % 2][len(text2)] |
class FeatureGenerator():
"""
Base class for feature generators
"""
def fit(self, timeseries):
"""
Fit the feature generator
inputs:
timeseries: the timeseries (numpy array) (num_series x series_length)
"""
raise NotImplementedError('FeatureGenerator.fit() not implemented')
def transform(self, timeseries):
"""
Generate features
inputs:
timeseries: the timeseries (numpy array) (num_series x series_length)
"""
raise NotImplementedError('FeatureGenerator.transform() not implemented')
def fit_transform(self, timeseries):
self.fit(timeseries)
return self.transform(timeseries) | class Featuregenerator:
"""
Base class for feature generators
"""
def fit(self, timeseries):
"""
Fit the feature generator
inputs:
timeseries: the timeseries (numpy array) (num_series x series_length)
"""
raise not_implemented_error('FeatureGenerator.fit() not implemented')
def transform(self, timeseries):
"""
Generate features
inputs:
timeseries: the timeseries (numpy array) (num_series x series_length)
"""
raise not_implemented_error('FeatureGenerator.transform() not implemented')
def fit_transform(self, timeseries):
self.fit(timeseries)
return self.transform(timeseries) |
dpi = 400
dpcm = dpi / 2.54
INFTY = float('inf')
PAPER = {
'letter': {
'qr_left': (0.0, 0.882, 0.152, 1.0),
'qr_right': (0.848, 0.882, 1.0, 1.0),
'tick': (0.17, 0.88, 0.91, 1.0),
'uin': (0.49, 0.11, 0.964, 0.54)
}
}
| dpi = 400
dpcm = dpi / 2.54
infty = float('inf')
paper = {'letter': {'qr_left': (0.0, 0.882, 0.152, 1.0), 'qr_right': (0.848, 0.882, 1.0, 1.0), 'tick': (0.17, 0.88, 0.91, 1.0), 'uin': (0.49, 0.11, 0.964, 0.54)}} |
'''Soma Simples'''
A = int(input())
B = int(input())
def CalculaSomaSimples(a: int, b: int):
resultado = int(a+b)
return('SOMA = {}'.format(resultado))
print(CalculaSomaSimples(A,B))
| """Soma Simples"""
a = int(input())
b = int(input())
def calcula_soma_simples(a: int, b: int):
resultado = int(a + b)
return 'SOMA = {}'.format(resultado)
print(calcula_soma_simples(A, B)) |
pkgname = "libgpg-error"
pkgver = "1.43"
pkgrel = 0
build_style = "gnu_configure"
hostmakedepends = ["pkgconf"]
pkgdesc = "Library for error values used by GnuPG components"
maintainer = "q66 <q66@chimera-linux.org>"
license = "LGPL-2.1-or-later"
url = "https://www.gnupg.org"
source = f"{url}/ftp/gcrypt/{pkgname}/{pkgname}-{pkgver}.tar.bz2"
sha256 = "a9ab83ca7acc442a5bd846a75b920285ff79bdb4e3d34aa382be88ed2c3aebaf"
# needs qemu and patching
options = ["!cross"]
def post_install(self):
self.rm(self.destdir / "usr/share/common-lisp", recursive = True)
@subpackage("libgpg-error-devel")
def _devel(self):
return self.default_devel()
@subpackage("libgpg-error-progs")
def _progs(self):
return self.default_progs()
| pkgname = 'libgpg-error'
pkgver = '1.43'
pkgrel = 0
build_style = 'gnu_configure'
hostmakedepends = ['pkgconf']
pkgdesc = 'Library for error values used by GnuPG components'
maintainer = 'q66 <q66@chimera-linux.org>'
license = 'LGPL-2.1-or-later'
url = 'https://www.gnupg.org'
source = f'{url}/ftp/gcrypt/{pkgname}/{pkgname}-{pkgver}.tar.bz2'
sha256 = 'a9ab83ca7acc442a5bd846a75b920285ff79bdb4e3d34aa382be88ed2c3aebaf'
options = ['!cross']
def post_install(self):
self.rm(self.destdir / 'usr/share/common-lisp', recursive=True)
@subpackage('libgpg-error-devel')
def _devel(self):
return self.default_devel()
@subpackage('libgpg-error-progs')
def _progs(self):
return self.default_progs() |
class Person:
name = None
age = 0
gender = None
def __init__(self, n, a, g):
self.name = n
self.age = a
self.gender = g
def walk(self):
print('I am walking')
def eat(self):
print('I am eating :)')
def __str__(self): # string representation of the object
return 'name: {}\tage: {}\tgender: {}'.format(self.name, self.age, self.gender)
p1 = Person('Ahmed', 20, 'm')
p2 = Person('Attia', 25, 'm')
p1.walk()
p2.eat()
print(p1)
print(p2)
| class Person:
name = None
age = 0
gender = None
def __init__(self, n, a, g):
self.name = n
self.age = a
self.gender = g
def walk(self):
print('I am walking')
def eat(self):
print('I am eating :)')
def __str__(self):
return 'name: {}\tage: {}\tgender: {}'.format(self.name, self.age, self.gender)
p1 = person('Ahmed', 20, 'm')
p2 = person('Attia', 25, 'm')
p1.walk()
p2.eat()
print(p1)
print(p2) |
list=input().split()
re=[int(e) for e in input().split()]
new=[]
for i in re:
new.append(list[i])
for l in new:
print(l,end=" ")
| list = input().split()
re = [int(e) for e in input().split()]
new = []
for i in re:
new.append(list[i])
for l in new:
print(l, end=' ') |
shopping_list = []
def show_help():
print("Enter the items/amount for your shopping list")
print("Enter DONE once you have completed the list, Enter Help if you require assistance")
def add_to_list(item):
shopping_list.append(item)
print("Added! List has {} items.".format(len(shopping_list)))
def show_list():
print("Here is your list")
for item in shopping_list:
print(item)
show_help()
while True:
new_item = input("item>")
if new_item == 'DONE':
break
elif new_item == 'HELP':
show_help()
continue
elif new_item == 'SHOW':
show_list()
continue
else:
add_to_list(new_item)
continue
show_list() | shopping_list = []
def show_help():
print('Enter the items/amount for your shopping list')
print('Enter DONE once you have completed the list, Enter Help if you require assistance')
def add_to_list(item):
shopping_list.append(item)
print('Added! List has {} items.'.format(len(shopping_list)))
def show_list():
print('Here is your list')
for item in shopping_list:
print(item)
show_help()
while True:
new_item = input('item>')
if new_item == 'DONE':
break
elif new_item == 'HELP':
show_help()
continue
elif new_item == 'SHOW':
show_list()
continue
else:
add_to_list(new_item)
continue
show_list() |
# Copyright (c) Microsoft Corporation
# Licensed under the MIT License.
"""Defines the Constant strings related to Error Analysis."""
class ErrorAnalysisDashboardInterface(object):
"""Dictionary properties shared between python and javascript object."""
TREE_URL = "treeUrl"
MATRIX_URL = "matrixUrl"
ENABLE_PREDICT = 'enablePredict'
| """Defines the Constant strings related to Error Analysis."""
class Erroranalysisdashboardinterface(object):
"""Dictionary properties shared between python and javascript object."""
tree_url = 'treeUrl'
matrix_url = 'matrixUrl'
enable_predict = 'enablePredict' |
"""
LIST: MINIMUM AND MAXIMUM ITEMS
"""
__author__ = 'Sol Amour - amoursol@gmail.com'
__twitter__ = '@solamour'
__version__ = '1.0.0'
"""
SYNTAX: min(iterable[, key = x])
min = Return the smallest item in an iterable or the smallest of two or more arguments
iterable = An iterable element (Such as a list, tuple, dictionary)
[,key] = An optional 'key' argument to specificy how to find the minimum argument
"""
dataSingle = [ 1, 2, 3, 4, 5 ] # A data list of numbers
dataDouble = [["A", 11], ["B", 7], ["C", 9]] # A data list of lists (Paired alphabetic
# and numeric characters)
minimumItem = min(dataSingle) # Will return the lowest natural sort item of '1'
maximumItem = max(dataSingle) # Will return the highest natural sort item of '5'
minimumItemKey = min(dataDouble, key = lambda d : d[1] ) # Will return the middle pairing of
# '["B", 7]' as we use an anonymous function (Lambda) as our key that simple states we're parsing
# the 'minimum item' based off Index 1 (Our numbers)
maximumItemKey = max(dataDouble, key = lambda d : d[1] ) # Will return the first pairing of
# '["A", 11]' as we use an anonymous function (Lambda) as our key that simple states we're parsing
# the 'maximum item' based off Index 1 (Our numbers)
OUT = minimumItem,maximumItem,minimumItemKey,maximumItemKey
| """
LIST: MINIMUM AND MAXIMUM ITEMS
"""
__author__ = 'Sol Amour - amoursol@gmail.com'
__twitter__ = '@solamour'
__version__ = '1.0.0'
"\n\nSYNTAX: min(iterable[, key = x])\n\nmin = Return the smallest item in an iterable or the smallest of two or more arguments\niterable = An iterable element (Such as a list, tuple, dictionary)\n[,key] = An optional 'key' argument to specificy how to find the minimum argument\n\n"
data_single = [1, 2, 3, 4, 5]
data_double = [['A', 11], ['B', 7], ['C', 9]]
minimum_item = min(dataSingle)
maximum_item = max(dataSingle)
minimum_item_key = min(dataDouble, key=lambda d: d[1])
maximum_item_key = max(dataDouble, key=lambda d: d[1])
out = (minimumItem, maximumItem, minimumItemKey, maximumItemKey) |
GET_HOSTS = [
{
'device_id': '00000000000000000000000000000000',
'cid': '11111111111111111111111111111111',
'agent_load_flags': '0',
'agent_local_time': '2021-12-08T15:16:24.360Z',
'agent_version': '6.30.14406.0',
'bios_manufacturer': 'Amazon EC2',
'bios_version': '1.0',
'build_number': '11111',
'config_id_base': '11111111',
'config_id_build': '11111',
'config_id_platform': '1',
'cpu_signature': '111111',
'external_ip': '10.0.0.1',
'mac_address': '00-00-00-00-00-00',
'instance_id': 'i-01',
'service_provider': 'AWS_EC2',
'service_provider_account_id': '000000000000',
'hostname': 'test',
'first_seen': '2022-03-14T04:13:28Z',
'last_seen': '2022-03-15T07:42:07Z',
'local_ip': '10.0.0.1',
'machine_domain': 'example.com',
'major_version': '4',
'minor_version': '14',
'os_version': 'Amazon Linux 2',
'os_build': '241',
'ou': ['test'],
'platform_id': '3',
'platform_name': 'Linux',
'policies': [],
'reduced_functionality_mode': 'no',
'device_policies': {},
'groups': ['00000000000000000000000000000001'],
'group_hash': '0000000000000000000000000000000000000000000000000000000000000000',
'product_type': '3',
'product_type_desc': 'Server',
'provision_status': 'Provisioned',
'serial_number': '00000000-0000-0000-0000-000000000000',
'service_pack_major': '0',
'service_pack_minor': '0',
'pointer_size': '8',
'site_name': 'Default-First-Site-Name',
'status': 'normal',
'system_manufacturer': 'Amazon EC2',
'system_product_name': 't3.small',
'tags': ['SensorGroupingTags/test'],
'modified_timestamp': '2022-03-15T07:42:10Z',
'slow_changing_modified_timestamp': '2022-03-15T06:16:42Z',
'meta': {'version': '6433'},
'zone_group': 'us-east-1a',
'kernel_version': '4.14.241-184.433.amzn2.x86_64',
},
]
| get_hosts = [{'device_id': '00000000000000000000000000000000', 'cid': '11111111111111111111111111111111', 'agent_load_flags': '0', 'agent_local_time': '2021-12-08T15:16:24.360Z', 'agent_version': '6.30.14406.0', 'bios_manufacturer': 'Amazon EC2', 'bios_version': '1.0', 'build_number': '11111', 'config_id_base': '11111111', 'config_id_build': '11111', 'config_id_platform': '1', 'cpu_signature': '111111', 'external_ip': '10.0.0.1', 'mac_address': '00-00-00-00-00-00', 'instance_id': 'i-01', 'service_provider': 'AWS_EC2', 'service_provider_account_id': '000000000000', 'hostname': 'test', 'first_seen': '2022-03-14T04:13:28Z', 'last_seen': '2022-03-15T07:42:07Z', 'local_ip': '10.0.0.1', 'machine_domain': 'example.com', 'major_version': '4', 'minor_version': '14', 'os_version': 'Amazon Linux 2', 'os_build': '241', 'ou': ['test'], 'platform_id': '3', 'platform_name': 'Linux', 'policies': [], 'reduced_functionality_mode': 'no', 'device_policies': {}, 'groups': ['00000000000000000000000000000001'], 'group_hash': '0000000000000000000000000000000000000000000000000000000000000000', 'product_type': '3', 'product_type_desc': 'Server', 'provision_status': 'Provisioned', 'serial_number': '00000000-0000-0000-0000-000000000000', 'service_pack_major': '0', 'service_pack_minor': '0', 'pointer_size': '8', 'site_name': 'Default-First-Site-Name', 'status': 'normal', 'system_manufacturer': 'Amazon EC2', 'system_product_name': 't3.small', 'tags': ['SensorGroupingTags/test'], 'modified_timestamp': '2022-03-15T07:42:10Z', 'slow_changing_modified_timestamp': '2022-03-15T06:16:42Z', 'meta': {'version': '6433'}, 'zone_group': 'us-east-1a', 'kernel_version': '4.14.241-184.433.amzn2.x86_64'}] |
# *****************************************************************************
# Copyright (c) 2020, Intel Corporation All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# *****************************************************************************
def knn_python(
train,
train_labels,
test,
k,
classes_num,
train_size,
test_size,
predictions,
queue_neighbors_lst,
votes_to_classes_lst,
data_dim,
):
for i in range(test_size):
queue_neighbors = queue_neighbors_lst[i]
for j in range(k):
# dist = euclidean_dist(train[j], test[i])
x1 = train[j]
x2 = test[i]
distance = 0.0
for jj in range(data_dim):
diff = x1[jj] - x2[jj]
distance += diff * diff
dist = distance ** 0.5
queue_neighbors[j, 0] = dist
queue_neighbors[j, 1] = train_labels[j]
# sort_queue(queue_neighbors)
for j in range(len(queue_neighbors)):
# push_queue(queue_neighbors, queue_neighbors[i], i)
new_distance = queue_neighbors[j, 0]
new_neighbor_label = queue_neighbors[j, 1]
index = j
while index > 0 and new_distance < queue_neighbors[index - 1, 0]:
queue_neighbors[index, 0] = queue_neighbors[index - 1, 0]
queue_neighbors[index, 1] = queue_neighbors[index - 1, 1]
index = index - 1
queue_neighbors[index, 0] = new_distance
queue_neighbors[index, 1] = new_neighbor_label
for j in range(k, train_size):
# dist = euclidean_dist(train[j], test[i])
x1 = train[j]
x2 = test[i]
distance = 0.0
for jj in range(data_dim):
diff = x1[jj] - x2[jj]
distance += diff * diff
dist = distance ** 0.5
if dist < queue_neighbors[k - 1][0]:
# queue_neighbors[k - 1] = new_neighbor
queue_neighbors[k - 1][0] = dist
queue_neighbors[k - 1][1] = train_labels[j]
# push_queue(queue_neighbors, queue_neighbors[k - 1])
new_distance = queue_neighbors[k - 1, 0]
new_neighbor_label = queue_neighbors[k - 1, 1]
index = k - 1
while index > 0 and new_distance < queue_neighbors[index - 1, 0]:
queue_neighbors[index, 0] = queue_neighbors[index - 1, 0]
queue_neighbors[index, 1] = queue_neighbors[index - 1, 1]
index = index - 1
queue_neighbors[index, 0] = new_distance
queue_neighbors[index, 1] = new_neighbor_label
votes_to_classes = votes_to_classes_lst[i]
for j in range(len(queue_neighbors)):
votes_to_classes[int(queue_neighbors[j, 1])] += 1
max_ind = 0
max_value = 0
for j in range(classes_num):
if votes_to_classes[j] > max_value:
max_value = votes_to_classes[j]
max_ind = j
predictions[i] = max_ind
| def knn_python(train, train_labels, test, k, classes_num, train_size, test_size, predictions, queue_neighbors_lst, votes_to_classes_lst, data_dim):
for i in range(test_size):
queue_neighbors = queue_neighbors_lst[i]
for j in range(k):
x1 = train[j]
x2 = test[i]
distance = 0.0
for jj in range(data_dim):
diff = x1[jj] - x2[jj]
distance += diff * diff
dist = distance ** 0.5
queue_neighbors[j, 0] = dist
queue_neighbors[j, 1] = train_labels[j]
for j in range(len(queue_neighbors)):
new_distance = queue_neighbors[j, 0]
new_neighbor_label = queue_neighbors[j, 1]
index = j
while index > 0 and new_distance < queue_neighbors[index - 1, 0]:
queue_neighbors[index, 0] = queue_neighbors[index - 1, 0]
queue_neighbors[index, 1] = queue_neighbors[index - 1, 1]
index = index - 1
queue_neighbors[index, 0] = new_distance
queue_neighbors[index, 1] = new_neighbor_label
for j in range(k, train_size):
x1 = train[j]
x2 = test[i]
distance = 0.0
for jj in range(data_dim):
diff = x1[jj] - x2[jj]
distance += diff * diff
dist = distance ** 0.5
if dist < queue_neighbors[k - 1][0]:
queue_neighbors[k - 1][0] = dist
queue_neighbors[k - 1][1] = train_labels[j]
new_distance = queue_neighbors[k - 1, 0]
new_neighbor_label = queue_neighbors[k - 1, 1]
index = k - 1
while index > 0 and new_distance < queue_neighbors[index - 1, 0]:
queue_neighbors[index, 0] = queue_neighbors[index - 1, 0]
queue_neighbors[index, 1] = queue_neighbors[index - 1, 1]
index = index - 1
queue_neighbors[index, 0] = new_distance
queue_neighbors[index, 1] = new_neighbor_label
votes_to_classes = votes_to_classes_lst[i]
for j in range(len(queue_neighbors)):
votes_to_classes[int(queue_neighbors[j, 1])] += 1
max_ind = 0
max_value = 0
for j in range(classes_num):
if votes_to_classes[j] > max_value:
max_value = votes_to_classes[j]
max_ind = j
predictions[i] = max_ind |
class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
nc = len(grid)
nr = len(grid[0])
for x in range(1, nr):
grid[0][x] += grid[0][x-1]
for x in range(1, nc):
grid[x][0] += grid[x-1][0]
for y in range(1, nr):
grid[x][y] += min(grid[x - 1][y], grid[x][y - 1])
return grid[nc-1][nr-1]
| class Solution(object):
def min_path_sum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
nc = len(grid)
nr = len(grid[0])
for x in range(1, nr):
grid[0][x] += grid[0][x - 1]
for x in range(1, nc):
grid[x][0] += grid[x - 1][0]
for y in range(1, nr):
grid[x][y] += min(grid[x - 1][y], grid[x][y - 1])
return grid[nc - 1][nr - 1] |
class WordWithTag:
word = ""
tag = ""
separator = ''
def __init__(self, separator):
self.separator = separator
| class Wordwithtag:
word = ''
tag = ''
separator = ''
def __init__(self, separator):
self.separator = separator |
class NvramBatteryStatusEnum(basestring):
"""
ok|partially discharged|fully discharged|not present|near
eol|eol|unknown|over charged|fully charged
Possible values:
<ul>
<li> "battery_ok" ,
<li> "battery_partially_discharged" ,
<li> "battery_fully_discharged" ,
<li> "battery_not_present" ,
<li> "battery_near_end_of_life" ,
<li> "battery_at_end_of_life" ,
<li> "battery_unknown" ,
<li> "battery_over_charged" ,
<li> "battery_fully_charged"
</ul>
"""
@staticmethod
def get_api_name():
return "nvram-battery-status-enum"
| class Nvrambatterystatusenum(basestring):
"""
ok|partially discharged|fully discharged|not present|near
eol|eol|unknown|over charged|fully charged
Possible values:
<ul>
<li> "battery_ok" ,
<li> "battery_partially_discharged" ,
<li> "battery_fully_discharged" ,
<li> "battery_not_present" ,
<li> "battery_near_end_of_life" ,
<li> "battery_at_end_of_life" ,
<li> "battery_unknown" ,
<li> "battery_over_charged" ,
<li> "battery_fully_charged"
</ul>
"""
@staticmethod
def get_api_name():
return 'nvram-battery-status-enum' |
class Solution:
def minOperations(self, n: int) -> int:
num_ops = 0
for i in range(0, n // 2, 1):
num_ops += n - (2 * i + 1)
return num_ops | class Solution:
def min_operations(self, n: int) -> int:
num_ops = 0
for i in range(0, n // 2, 1):
num_ops += n - (2 * i + 1)
return num_ops |
input = """
3 2 2 3 1 0 4
2 5 2 0 1 2 3
1 1 2 1 5 4
2 6 2 0 2 2 3
1 1 2 0 6 4
1 4 0 0
3 3 7 8 9 1 0 10
2 11 3 0 1 7 8 9
1 1 2 1 11 10
2 12 3 0 2 7 8 9
1 1 2 0 12 10
1 10 0 0
1 13 1 0 9
1 14 1 0 8
1 15 1 0 7
1 16 1 0 9
1 17 1 0 7
1 18 1 1 17
1 19 2 0 14 13
1 20 3 0 14 18 15
1 1 2 1 20 2
1 1 2 1 19 3
0
16 i
3 e
20 s
13 f
9 a
14 g
17 l
8 b
18 p
2 d
19 r
15 h
7 c
0
B+
0
B-
1
0
1
"""
output = """
INCOHERENT
"""
| input = '\n3 2 2 3 1 0 4\n2 5 2 0 1 2 3\n1 1 2 1 5 4\n2 6 2 0 2 2 3\n1 1 2 0 6 4\n1 4 0 0\n3 3 7 8 9 1 0 10\n2 11 3 0 1 7 8 9\n1 1 2 1 11 10\n2 12 3 0 2 7 8 9\n1 1 2 0 12 10\n1 10 0 0\n1 13 1 0 9\n1 14 1 0 8\n1 15 1 0 7\n1 16 1 0 9\n1 17 1 0 7\n1 18 1 1 17\n1 19 2 0 14 13\n1 20 3 0 14 18 15\n1 1 2 1 20 2\n1 1 2 1 19 3\n0\n16 i\n3 e\n20 s\n13 f\n9 a\n14 g\n17 l\n8 b\n18 p\n2 d\n19 r\n15 h\n7 c\n0\nB+\n0\nB-\n1\n0\n1\n'
output = '\nINCOHERENT\n' |
'''
Largest Continuous Sum Problem
Given an array of integers (positive and negative) find the largest continous sum
'''
def large_cont_sum(arr):
#if array is all positive we return the result as summ of all numbers
#the negative numbers int he array will cause us to need to begin checkin sequences
## Check to see if array is Length 0
if len(arr) == 0:
return 0
max_sum = current_sum = arr[0] #equal to first element
for num in arr[1:]: #We check each number in array not including the first num arr[0]
current_sum = max(current_sum+num, num) #find out which one is larger: current sum + num or the num
max_sum = max(current_sum,max_sum) #we keep track of which one is larger
return max_sum
print(large_cont_sum([1,2,-1,3,4,10,10,-10,-1])) | """
Largest Continuous Sum Problem
Given an array of integers (positive and negative) find the largest continous sum
"""
def large_cont_sum(arr):
if len(arr) == 0:
return 0
max_sum = current_sum = arr[0]
for num in arr[1:]:
current_sum = max(current_sum + num, num)
max_sum = max(current_sum, max_sum)
return max_sum
print(large_cont_sum([1, 2, -1, 3, 4, 10, 10, -10, -1])) |
data = (
's', # 0x00
't', # 0x01
'u', # 0x02
'v', # 0x03
'w', # 0x04
'x', # 0x05
'y', # 0x06
'z', # 0x07
'A', # 0x08
'B', # 0x09
'C', # 0x0a
'D', # 0x0b
'E', # 0x0c
'F', # 0x0d
'G', # 0x0e
'H', # 0x0f
'I', # 0x10
'J', # 0x11
'K', # 0x12
'L', # 0x13
'M', # 0x14
'N', # 0x15
'O', # 0x16
'P', # 0x17
'Q', # 0x18
'R', # 0x19
'S', # 0x1a
'T', # 0x1b
'U', # 0x1c
'V', # 0x1d
'W', # 0x1e
'X', # 0x1f
'Y', # 0x20
'Z', # 0x21
'a', # 0x22
'b', # 0x23
'c', # 0x24
'd', # 0x25
'e', # 0x26
'f', # 0x27
'g', # 0x28
'h', # 0x29
'i', # 0x2a
'j', # 0x2b
'k', # 0x2c
'l', # 0x2d
'm', # 0x2e
'n', # 0x2f
'o', # 0x30
'p', # 0x31
'q', # 0x32
'r', # 0x33
's', # 0x34
't', # 0x35
'u', # 0x36
'v', # 0x37
'w', # 0x38
'x', # 0x39
'y', # 0x3a
'z', # 0x3b
'A', # 0x3c
'B', # 0x3d
'C', # 0x3e
'D', # 0x3f
'E', # 0x40
'F', # 0x41
'G', # 0x42
'H', # 0x43
'I', # 0x44
'J', # 0x45
'K', # 0x46
'L', # 0x47
'M', # 0x48
'N', # 0x49
'O', # 0x4a
'P', # 0x4b
'Q', # 0x4c
'R', # 0x4d
'S', # 0x4e
'T', # 0x4f
'U', # 0x50
'V', # 0x51
'W', # 0x52
'X', # 0x53
'Y', # 0x54
'Z', # 0x55
'a', # 0x56
'b', # 0x57
'c', # 0x58
'd', # 0x59
'e', # 0x5a
'f', # 0x5b
'g', # 0x5c
'h', # 0x5d
'i', # 0x5e
'j', # 0x5f
'k', # 0x60
'l', # 0x61
'm', # 0x62
'n', # 0x63
'o', # 0x64
'p', # 0x65
'q', # 0x66
'r', # 0x67
's', # 0x68
't', # 0x69
'u', # 0x6a
'v', # 0x6b
'w', # 0x6c
'x', # 0x6d
'y', # 0x6e
'z', # 0x6f
'A', # 0x70
'B', # 0x71
'C', # 0x72
'D', # 0x73
'E', # 0x74
'F', # 0x75
'G', # 0x76
'H', # 0x77
'I', # 0x78
'J', # 0x79
'K', # 0x7a
'L', # 0x7b
'M', # 0x7c
'N', # 0x7d
'O', # 0x7e
'P', # 0x7f
'Q', # 0x80
'R', # 0x81
'S', # 0x82
'T', # 0x83
'U', # 0x84
'V', # 0x85
'W', # 0x86
'X', # 0x87
'Y', # 0x88
'Z', # 0x89
'a', # 0x8a
'b', # 0x8b
'c', # 0x8c
'd', # 0x8d
'e', # 0x8e
'f', # 0x8f
'g', # 0x90
'h', # 0x91
'i', # 0x92
'j', # 0x93
'k', # 0x94
'l', # 0x95
'm', # 0x96
'n', # 0x97
'o', # 0x98
'p', # 0x99
'q', # 0x9a
'r', # 0x9b
's', # 0x9c
't', # 0x9d
'u', # 0x9e
'v', # 0x9f
'w', # 0xa0
'x', # 0xa1
'y', # 0xa2
'z', # 0xa3
'i', # 0xa4
'j', # 0xa5
'', # 0xa6
'', # 0xa7
'Alpha', # 0xa8
'Beta', # 0xa9
'Gamma', # 0xaa
'Delta', # 0xab
'Epsilon', # 0xac
'Zeta', # 0xad
'Eta', # 0xae
'Theta', # 0xaf
'Iota', # 0xb0
'Kappa', # 0xb1
'Lamda', # 0xb2
'Mu', # 0xb3
'Nu', # 0xb4
'Xi', # 0xb5
'Omicron', # 0xb6
'Pi', # 0xb7
'Rho', # 0xb8
'Theta', # 0xb9
'Sigma', # 0xba
'Tau', # 0xbb
'Upsilon', # 0xbc
'Phi', # 0xbd
'Chi', # 0xbe
'Psi', # 0xbf
'Omega', # 0xc0
'nabla', # 0xc1
'alpha', # 0xc2
'beta', # 0xc3
'gamma', # 0xc4
'delta', # 0xc5
'epsilon', # 0xc6
'zeta', # 0xc7
'eta', # 0xc8
'theta', # 0xc9
'iota', # 0xca
'kappa', # 0xcb
'lamda', # 0xcc
'mu', # 0xcd
'nu', # 0xce
'xi', # 0xcf
'omicron', # 0xd0
'pi', # 0xd1
'rho', # 0xd2
'sigma', # 0xd3
'sigma', # 0xd4
'tai', # 0xd5
'upsilon', # 0xd6
'phi', # 0xd7
'chi', # 0xd8
'psi', # 0xd9
'omega', # 0xda
'', # 0xdb
'', # 0xdc
'', # 0xdd
'', # 0xde
'', # 0xdf
'', # 0xe0
'', # 0xe1
'', # 0xe2
'', # 0xe3
'', # 0xe4
'', # 0xe5
'', # 0xe6
'', # 0xe7
'', # 0xe8
'', # 0xe9
'', # 0xea
'', # 0xeb
'', # 0xec
'', # 0xed
'', # 0xee
'', # 0xef
'', # 0xf0
'', # 0xf1
'', # 0xf2
'', # 0xf3
'', # 0xf4
'', # 0xf5
'', # 0xf6
'', # 0xf7
'', # 0xf8
'', # 0xf9
'', # 0xfa
'', # 0xfb
'', # 0xfc
'', # 0xfd
'', # 0xfe
'', # 0xff
)
| data = ('s', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'i', 'j', '', '', 'Alpha', 'Beta', 'Gamma', 'Delta', 'Epsilon', 'Zeta', 'Eta', 'Theta', 'Iota', 'Kappa', 'Lamda', 'Mu', 'Nu', 'Xi', 'Omicron', 'Pi', 'Rho', 'Theta', 'Sigma', 'Tau', 'Upsilon', 'Phi', 'Chi', 'Psi', 'Omega', 'nabla', 'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', 'eta', 'theta', 'iota', 'kappa', 'lamda', 'mu', 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma', 'sigma', 'tai', 'upsilon', 'phi', 'chi', 'psi', 'omega', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '') |
# -*- coding: utf-8 -*-
"""
"main concept of MongoDB is embed whenever possible"
Ref: http://stackoverflow.com/questions/4655610#comment5129510_4656431
"""
transcript = dict(
# The ensemble transcript id
transcript_id=str, # required=True
# The hgnc gene id
hgnc_id=int,
### Protein specific predictions ###
# The ensemble protein id
protein_id=str,
# The sift consequence prediction for this transcript
sift_prediction=str, # choices=CONSEQUENCE
# The polyphen consequence prediction for this transcript
polyphen_prediction=str, # choices=CONSEQUENCE
# The swiss protein id for the product
swiss_prot=str,
# The pfam id for the protein product
pfam_domain=str,
# The prosite id for the product
prosite_profile=str,
# The smart id for the product
smart_domain=str,
# The biotype annotation for the transcript
biotype=str,
# The functional annotations for the transcript
functional_annotations=list, # list(str(choices=SO_TERM_KEYS))
# The region annotations for the transcripts
region_annotations=list, # list(str(choices=FEATURE_TYPES))
# The exon number in the transcript e.g '2/7'
exon=str,
# The intron number in the transcript e.g '4/6'
intron=str,
# The strand of the transcript e.g '+'
strand=str,
# the CDNA change of the transcript e.g 'c.95T>C'
coding_sequence_name=str,
# The amino acid change on the transcript e.g. 'p.Phe32Ser'
protein_sequence_name=str,
# If the transcript is relevant
is_canonical=bool,
# The MANE select transcript
mane_transcript=str,
)
| """
"main concept of MongoDB is embed whenever possible"
Ref: http://stackoverflow.com/questions/4655610#comment5129510_4656431
"""
transcript = dict(transcript_id=str, hgnc_id=int, protein_id=str, sift_prediction=str, polyphen_prediction=str, swiss_prot=str, pfam_domain=str, prosite_profile=str, smart_domain=str, biotype=str, functional_annotations=list, region_annotations=list, exon=str, intron=str, strand=str, coding_sequence_name=str, protein_sequence_name=str, is_canonical=bool, mane_transcript=str) |
# MIT licensed
# Copyright (c) 2013-2020 lilydjwg <lilydjwg@gmail.com>, et al.
GEMS_URL = 'https://rubygems.org/api/v1/versions/%s.json'
async def get_version(name, conf, *, cache, **kwargs):
key = conf.get('gems', name)
data = await cache.get_json(GEMS_URL % key)
return data[0]['number']
| gems_url = 'https://rubygems.org/api/v1/versions/%s.json'
async def get_version(name, conf, *, cache, **kwargs):
key = conf.get('gems', name)
data = await cache.get_json(GEMS_URL % key)
return data[0]['number'] |
def msgme(*names):
for i in names:
print(i)
msgme("abc")
msgme("xyz",100)
msgme("apple","mango",1,2,3,7)
| def msgme(*names):
for i in names:
print(i)
msgme('abc')
msgme('xyz', 100)
msgme('apple', 'mango', 1, 2, 3, 7) |
class Dog:
species = 'caniche'
def __init__(self, name, age):
self.name = name
self.age = age
bambi = Dog("Bambi", 5)
mikey = Dog("Rufus", 6)
blacky = Dog("Fosca", 9)
coco = Dog("Coco", 13)
perla = Dog("Neska", 3)
print("{} is {} and {} is {}.". format(bambi.name, bambi.age, mikey.name, mikey.age))
if bambi.species == "caniche":
print("{0} is a {1}!".format(bambi.name, bambi.species))
def get_biggest_number (*argument):
max=0
for i in argument:
if (type(i) is int) == False:
return ("Error: Arguments must be integers")
if i>max:
max=i
return (max)
print('The biggest number among the given is: ' , get_biggest_number(1 , 4 , 5 , -4 , 6 , 123 , 0)) | class Dog:
species = 'caniche'
def __init__(self, name, age):
self.name = name
self.age = age
bambi = dog('Bambi', 5)
mikey = dog('Rufus', 6)
blacky = dog('Fosca', 9)
coco = dog('Coco', 13)
perla = dog('Neska', 3)
print('{} is {} and {} is {}.'.format(bambi.name, bambi.age, mikey.name, mikey.age))
if bambi.species == 'caniche':
print('{0} is a {1}!'.format(bambi.name, bambi.species))
def get_biggest_number(*argument):
max = 0
for i in argument:
if (type(i) is int) == False:
return 'Error: Arguments must be integers'
if i > max:
max = i
return max
print('The biggest number among the given is: ', get_biggest_number(1, 4, 5, -4, 6, 123, 0)) |
"""
[11/3/2012] Challenge #110 [Difficult] You can't handle the truth!
https://www.reddit.com/r/dailyprogrammer/comments/12k3xw/1132012_challenge_110_difficult_you_cant_handle/
**Description:**
[Truth Tables](http://en.wikipedia.org/wiki/Truth_table) are a simple table that demonstrates all possible results
given a Boolean algebra function. An example Boolean algebra function would be "A or B", where there are four possible
combinations, one of which is "A:false, B:false, Result: false"
Your goal is to write a Boolean algebra function truth-table generator for statements that are up to 4 variables
(always A, B, C, or D) and for only the following operators: [not](http://en.wikipedia.org/wiki/Logical_NOT),
[and](http://en.wikipedia.org/wiki/Logical_AND), [or](http://en.wikipedia.org/wiki/Logical_OR),
[nand](http://en.wikipedia.org/wiki/Logical_NAND), and [nor](http://en.wikipedia.org/wiki/Logical_NOR).
Note that you must maintain order of operator correctness, though evaluate left-to-right if there are ambiguous
statements.
**Formal Inputs & Outputs:**
*Input Description:*
String BoolFunction - A string of one or more variables (always A, B, C, or D) and keyboards (not, and, or, nand, nor).
This string is guaranteed to be valid
*Output Description:*
Your application must print all possible combinations of states for all variables, with the last variable being
"Result", which should the correct result if the given variables were set to the given values. An example row would be
"A:false, B:false, Result: false"
**Sample Inputs & Outputs:**
Given "A and B", your program should print the following:
A:false, B:false, Result: false
A:true, B:false, Result: false
A:false, B:true, Result: false
A:true, B:true, Result: true
**Notes:**
To help with cycling through all boolean combinations, realize that when counting from 0 to 3 in binary, you generate a
table of all combinations of 2 variables (00, 01, 10, 11). You can extrapolate this out to itterating through all table
rows for a given variable count. [Challenge
#105](http://www.reddit.com/r/dailyprogrammer/comments/11shtj/10202012_challenge_105_intermediate_boolean_logic/) has a
very similar premise to this challenge.
"""
def main():
pass
if __name__ == "__main__":
main()
| """
[11/3/2012] Challenge #110 [Difficult] You can't handle the truth!
https://www.reddit.com/r/dailyprogrammer/comments/12k3xw/1132012_challenge_110_difficult_you_cant_handle/
**Description:**
[Truth Tables](http://en.wikipedia.org/wiki/Truth_table) are a simple table that demonstrates all possible results
given a Boolean algebra function. An example Boolean algebra function would be "A or B", where there are four possible
combinations, one of which is "A:false, B:false, Result: false"
Your goal is to write a Boolean algebra function truth-table generator for statements that are up to 4 variables
(always A, B, C, or D) and for only the following operators: [not](http://en.wikipedia.org/wiki/Logical_NOT),
[and](http://en.wikipedia.org/wiki/Logical_AND), [or](http://en.wikipedia.org/wiki/Logical_OR),
[nand](http://en.wikipedia.org/wiki/Logical_NAND), and [nor](http://en.wikipedia.org/wiki/Logical_NOR).
Note that you must maintain order of operator correctness, though evaluate left-to-right if there are ambiguous
statements.
**Formal Inputs & Outputs:**
*Input Description:*
String BoolFunction - A string of one or more variables (always A, B, C, or D) and keyboards (not, and, or, nand, nor).
This string is guaranteed to be valid
*Output Description:*
Your application must print all possible combinations of states for all variables, with the last variable being
"Result", which should the correct result if the given variables were set to the given values. An example row would be
"A:false, B:false, Result: false"
**Sample Inputs & Outputs:**
Given "A and B", your program should print the following:
A:false, B:false, Result: false
A:true, B:false, Result: false
A:false, B:true, Result: false
A:true, B:true, Result: true
**Notes:**
To help with cycling through all boolean combinations, realize that when counting from 0 to 3 in binary, you generate a
table of all combinations of 2 variables (00, 01, 10, 11). You can extrapolate this out to itterating through all table
rows for a given variable count. [Challenge
#105](http://www.reddit.com/r/dailyprogrammer/comments/11shtj/10202012_challenge_105_intermediate_boolean_logic/) has a
very similar premise to this challenge.
"""
def main():
pass
if __name__ == '__main__':
main() |
def getBuiltinTargs():
return {
"1": {
"name": "1",
"ptype": "maven2",
"patterns": [".*"],
"defincpat": ["**"],
"defexcpat": []
},
"2": {
"name": "2",
"ptype": "maven1",
"patterns": [".*"],
"defincpat": ["**"],
"defexcpat": []
},
"3": {
"name": "3",
"ptype": "maven2",
"patterns": ["(?!.*-sources.*).*"],
"defincpat": ["**"],
"defexcpat": ["**/*-sources.*/**"]
},
"4": {
"name": "4",
"ptype": "maven2",
"patterns": [".*maven-metadata\.xml.*"],
"defincpat": ["**/*maven-metadata.xml*"],
"defexcpat": []
},
"any": {
"name": "any",
"ptype": "any",
"patterns": [".*"],
"defincpat": ["**"],
"defexcpat": []
},
"site": {
"name": "site",
"ptype": "site",
"patterns": [".*"],
"defincpat": ["**"],
"defexcpat": []
},
"npm": {
"name": "npm",
"ptype": "npm",
"patterns": [".*"],
"defincpat": ["**"],
"defexcpat": []
},
"nuget": {
"name": "nuget",
"ptype": "nuget",
"patterns": [".*"],
"defincpat": ["**"],
"defexcpat": []
},
"rubygems": {
"name": "rubygems",
"ptype": "rubygems",
"patterns": [".*"],
"defincpat": ["**"],
"defexcpat": []
}
}
def getBuiltinPrivs(targs):
return {
"All M1 Repositories": {
"name": "All M1 Repositories",
"target": targs["2"],
"repo": "*",
"builtin": True
},
"All M2 Repositories": {
"name": "All M2 Repositories",
"target": targs["1"],
"repo": "*",
"builtin": True
},
"All npm Repositories": {
"name": "All npm Repositories",
"target": targs["npm"],
"repo": "*",
"builtin": True
},
"All NuGet Repositories": {
"name": "All NuGet Repositories",
"target": targs["nuget"],
"repo": "*",
"builtin": True
},
"All Repositories": {
"name": "All Repositories",
"target": targs["any"],
"repo": "*",
"builtin": True
},
"All Rubygems Repositories": {
"name": "All Rubygems Repositories",
"target": targs["rubygems"],
"repo": "*",
"builtin": True
},
"All Site Repositories": {
"name": "All Site Repositories",
"target": targs["site"],
"repo": "*",
"builtin": True
}
}
def getBuiltinPrivmap(privs):
return {
"repository-all": {
"id": "repository-all",
"repo": "*",
"type": "view",
"needadmin": False
},
"T6": {
"id": "T6",
"method": "create",
"priv": privs["All M1 Repositories"],
"type": "target",
"needadmin": False
},
"T8": {
"id": "T8",
"method": "delete",
"priv": privs["All M1 Repositories"],
"type": "target",
"needadmin": False
},
"T2": {
"id": "T2",
"method": "read",
"priv": privs["All M1 Repositories"],
"type": "target",
"needadmin": False
},
"T4": {
"id": "T4",
"method": "update",
"priv": privs["All M1 Repositories"],
"type": "target",
"needadmin": False
},
"T5": {
"id": "T5",
"method": "create",
"priv": privs["All M2 Repositories"],
"type": "target",
"needadmin": False
},
"T7": {
"id": "T7",
"method": "delete",
"priv": privs["All M2 Repositories"],
"type": "target",
"needadmin": False
},
"T1": {
"id": "T1",
"method": "read",
"priv": privs["All M2 Repositories"],
"type": "target",
"needadmin": False
},
"T3": {
"id": "T3",
"method": "update",
"priv": privs["All M2 Repositories"],
"type": "target",
"needadmin": False
},
"npm-create": {
"id": "npm-create",
"method": "create",
"priv": privs["All npm Repositories"],
"type": "target",
"needadmin": False
},
"npm-delete": {
"id": "npm-delete",
"method": "delete",
"priv": privs["All npm Repositories"],
"type": "target",
"needadmin": False
},
"npm-read": {
"id": "npm-read",
"method": "read",
"priv": privs["All npm Repositories"],
"type": "target",
"needadmin": False
},
"npm-update": {
"id": "npm-update",
"method": "update",
"priv": privs["All npm Repositories"],
"type": "target",
"needadmin": False
},
"nuget-create": {
"id": "nuget-create",
"method": "create",
"priv": privs["All NuGet Repositories"],
"type": "target",
"needadmin": False
},
"nuget-delete": {
"id": "nuget-delete",
"method": "delete",
"priv": privs["All NuGet Repositories"],
"type": "target",
"needadmin": False
},
"nuget-read": {
"id": "nuget-read",
"method": "read",
"priv": privs["All NuGet Repositories"],
"type": "target",
"needadmin": False
},
"nuget-update": {
"id": "nuget-update",
"method": "update",
"priv": privs["All NuGet Repositories"],
"type": "target",
"needadmin": False
},
"T11": {
"id": "T11",
"method": "create",
"priv": privs["All Repositories"],
"type": "target",
"needadmin": False
},
"T12": {
"id": "T12",
"method": "delete",
"priv": privs["All Repositories"],
"type": "target",
"needadmin": False
},
"T9": {
"id": "T9",
"method": "read",
"priv": privs["All Repositories"],
"type": "target",
"needadmin": False
},
"T10": {
"id": "T10",
"method": "update",
"priv": privs["All Repositories"],
"type": "target",
"needadmin": False
},
"rubygems-create": {
"id": "rubygems-create",
"method": "create",
"priv": privs["All Rubygems Repositories"],
"type": "target",
"needadmin": False
},
"rubygems-delete": {
"id": "rubygems-delete",
"method": "delete",
"priv": privs["All Rubygems Repositories"],
"type": "target",
"needadmin": False
},
"rubygems-read": {
"id": "rubygems-read",
"method": "read",
"priv": privs["All Rubygems Repositories"],
"type": "target",
"needadmin": False
},
"rubygems-update": {
"id": "rubygems-update",
"method": "update",
"priv": privs["All Rubygems Repositories"],
"type": "target",
"needadmin": False
},
"site-create": {
"id": "site-create",
"method": "create",
"priv": privs["All Site Repositories"],
"type": "target",
"needadmin": False
},
"site-delete": {
"id": "site-delete",
"method": "delete",
"priv": privs["All Site Repositories"],
"type": "target",
"needadmin": False
},
"site-read": {
"id": "site-read",
"method": "read",
"priv": privs["All Site Repositories"],
"type": "target",
"needadmin": False
},
"site-update": {
"id": "site-update",
"method": "update",
"priv": privs["All Site Repositories"],
"type": "target",
"needadmin": False
},
"1000": {
"id": "1000",
"method": "*",
"permission": "nexus:*",
"type": "application",
"needadmin": True
},
"analytics-all": {
"id": "analytics-all",
"method": "*",
"permission": "nexus:analytics",
"type": "application",
"needadmin": False
},
"83": {
"id": "83",
"method": "*",
"permission": "apikey:access",
"type": "application",
"needadmin": False
},
"54": {
"id": "54",
"method": "read",
"permission": "nexus:artifact",
"type": "application",
"needadmin": False
},
"65": {
"id": "65",
"method": "create,read",
"permission": "nexus:artifact",
"type": "application",
"needadmin": False
},
"atlas-all": {
"id": "atlas-all",
"method": "*",
"permission": "nexus:atlas",
"type": "application",
"needadmin": False
},
"browse-remote-repo": {
"id": "browse-remote-repo",
"method": "read",
"permission": "nexus:browseremote",
"type": "application",
"needadmin": False
},
"capabilities-create-read": {
"id": "capabilities-create-read",
"method": "create,read",
"permission": "nexus:capabilities",
"type": "application",
"needadmin": False
},
"capabilities-delete-read": {
"id": "capabilities-delete-read",
"method": "delete,read",
"permission": "nexus:capabilities",
"type": "application",
"needadmin": False
},
"capabilities-read": {
"id": "capabilities-read",
"method": "read",
"permission": "nexus:capabilities",
"type": "application",
"needadmin": False
},
"capabilities-update-read": {
"id": "capabilities-update-read",
"method": "update,read",
"permission": "nexus:capabilities",
"type": "application",
"needadmin": False
},
"capability-types-read": {
"id": "capability-types-read",
"method": "read",
"permission": "nexus:capabilityTypes",
"type": "application",
"needadmin": False
},
"19": {
"id": "19",
"method": "read",
"permission": "nexus:identify",
"type": "application",
"needadmin": False
},
"21": {
"id": "21",
"method": "delete,read",
"permission": "nexus:cache",
"type": "application",
"needadmin": True
},
"43": {
"id": "43",
"method": "read",
"permission": "nexus:configuration",
"type": "application",
"needadmin": False
},
"nexus-healthcheck-read": {
"id": "nexus-healthcheck-read",
"method": "read",
"permission": "nexus:healthcheck",
"type": "application",
"needadmin": False
},
"nexus-healthcheck-update": {
"id": "nexus-healthcheck-update",
"method": "update",
"permission": "nexus:healthcheck",
"type": "application",
"needadmin": False
},
"nexus-healthcheck-summary-read": {
"id": "nexus-healthcheck-summary-read",
"method": "read",
"permission": "nexus:healthchecksummary",
"type": "application",
"needadmin": False
},
"ldap-conn-read": {
"id": "ldap-conn-read",
"method": "read",
"permission": "nexus:ldapconninfo",
"type": "application",
"needadmin": False
},
"ldap-conn-update": {
"id": "ldap-conn-update",
"method": "update",
"permission": "nexus:ldapconninfo",
"type": "application",
"needadmin": True
},
"ldap-test-auth-conf": {
"id": "ldap-test-auth-conf",
"method": "update",
"permission": "nexus:ldaptestauth",
"type": "application",
"needadmin": True
},
"ldap-test-user-group-conf": {
"id": "ldap-test-user-group-conf",
"method": "update",
"permission": "nexus:ldaptestuserconf",
"type": "application",
"needadmin": True
},
"ldap-user-group-conf-read": {
"id": "ldap-user-group-conf-read",
"method": "read",
"permission": "nexus:ldapusergroupconf",
"type": "application",
"needadmin": False
},
"ldap-user-group-conf-update": {
"id": "ldap-user-group-conf-update",
"method": "update",
"permission": "nexus:ldapusergroupconf",
"type": "application",
"needadmin": True
},
"ldap-user-role-map-create": {
"id": "ldap-user-role-map-create",
"method": "create",
"permission": "nexus:ldapuserrolemap",
"type": "application",
"needadmin": True
},
"ldap-user-role-map-delete": {
"id": "ldap-user-role-map-delete",
"method": "delete,read",
"permission": "nexus:ldapuserrolemap",
"type": "application",
"needadmin": True
},
"ldap-user-role-map-read": {
"id": "ldap-user-role-map-read",
"method": "read",
"permission": "nexus:ldapuserrolemap",
"type": "application",
"needadmin": False
},
"ldap-user-role-map-update": {
"id": "ldap-user-role-map-update",
"method": "update",
"permission": "nexus:ldapuserrolemap",
"type": "application",
"needadmin": True
},
"77": {
"id": "77",
"method": "read,update",
"permission": "nexus:logconfig",
"type": "application",
"needadmin": False
},
"2": {
"id": "2",
"method": "read",
"permission": "nexus:authentication",
"type": "application",
"needadmin": False
},
"42": {
"id": "42",
"method": "read",
"permission": "nexus:logs",
"type": "application",
"needadmin": False
},
"metrics-endpoints": {
"id": "metrics-endpoints",
"method": "*",
"permission": "nexus:metrics-endpoints",
"type": "application",
"needadmin": False
},
"66": {
"id": "66",
"method": "update,read",
"permission": "nexus:command",
"type": "application",
"needadmin": False
},
"plugin-infos-read": {
"id": "plugin-infos-read",
"method": "read",
"permission": "nexus:pluginconsoleplugininfos",
"type": "application",
"needadmin": False
},
"55": {
"id": "55",
"method": "read",
"permission": "nexus:repostatus",
"type": "application",
"needadmin": False
},
"73": {
"id": "73",
"method": "read",
"permission": "nexus:componentrealmtypes",
"type": "application",
"needadmin": False
},
"76": {
"id": "76",
"method": "delete,read",
"permission": "nexus:metadata",
"type": "application",
"needadmin": False
},
"20": {
"id": "20",
"method": "delete,read",
"permission": "nexus:attributes",
"type": "application",
"needadmin": False
},
"18": {
"id": "18",
"method": "delete,read",
"permission": "nexus:index",
"type": "application",
"needadmin": False
},
"5": {
"id": "5",
"method": "create,read",
"permission": "nexus:repositories",
"type": "application",
"needadmin": True
},
"8": {
"id": "8",
"method": "delete,read",
"permission": "nexus:repositories",
"type": "application",
"needadmin": True
},
"6": {
"id": "6",
"method": "read",
"permission": "nexus:repositories",
"type": "application",
"needadmin": False
},
"7": {
"id": "7",
"method": "update,read",
"permission": "nexus:repositories",
"type": "application",
"needadmin": True
},
"70": {
"id": "70",
"method": "read",
"permission": "nexus:componentscontentclasses",
"type": "application",
"needadmin": False
},
"13": {
"id": "13",
"method": "create,read",
"permission": "nexus:repogroups",
"type": "application",
"needadmin": True
},
"16": {
"id": "16",
"method": "delete,read",
"permission": "nexus:repogroups",
"type": "application",
"needadmin": True
},
"14": {
"id": "14",
"method": "read",
"permission": "nexus:repogroups",
"type": "application",
"needadmin": False
},
"15": {
"id": "15",
"method": "update,read",
"permission": "nexus:repogroups",
"type": "application",
"needadmin": True
},
"79": {
"id": "79",
"method": "create,read",
"permission": "nexus:repositorymirrors",
"type": "application",
"needadmin": False
},
"78": {
"id": "78",
"method": "read",
"permission": "nexus:repositorymirrors",
"type": "application",
"needadmin": False
},
"82": {
"id": "82",
"method": "read",
"permission": "nexus:repositorymirrorsstatus",
"type": "application",
"needadmin": False
},
"81": {
"id": "81",
"method": "read",
"permission": "nexus:repositorypredefinedmirrors",
"type": "application",
"needadmin": False
},
"22": {
"id": "22",
"method": "create,read",
"permission": "nexus:routes",
"type": "application",
"needadmin": False
},
"25": {
"id": "25",
"method": "delete,read",
"permission": "nexus:routes",
"type": "application",
"needadmin": False
},
"23": {
"id": "23",
"method": "read",
"permission": "nexus:routes",
"type": "application",
"needadmin": False
},
"24": {
"id": "24",
"method": "update,read",
"permission": "nexus:routes",
"type": "application",
"needadmin": False
},
"67": {
"id": "67",
"method": "read",
"permission": "nexus:repometa",
"type": "application",
"needadmin": False
},
"45": {
"id": "45",
"method": "create,read",
"permission": "nexus:targets",
"type": "application",
"needadmin": True
},
"48": {
"id": "48",
"method": "delete,read",
"permission": "nexus:targets",
"type": "application",
"needadmin": True
},
"46": {
"id": "46",
"method": "read",
"permission": "nexus:targets",
"type": "application",
"needadmin": False
},
"47": {
"id": "47",
"method": "update,read",
"permission": "nexus:targets",
"type": "application",
"needadmin": True
},
"9": {
"id": "9",
"method": "create,read",
"permission": "nexus:repotemplates",
"type": "application",
"needadmin": False
},
"12": {
"id": "12",
"method": "delete,read",
"permission": "nexus:repotemplates",
"type": "application",
"needadmin": False
},
"10": {
"id": "10",
"method": "read",
"permission": "nexus:repotemplates",
"type": "application",
"needadmin": False
},
"11": {
"id": "11",
"method": "update,read",
"permission": "nexus:repotemplates",
"type": "application",
"needadmin": False
},
"74": {
"id": "74",
"method": "read",
"permission": "nexus:componentsrepotypes",
"type": "application",
"needadmin": False
},
"44": {
"id": "44",
"method": "read",
"permission": "nexus:feeds",
"type": "application",
"needadmin": False
},
"69": {
"id": "69",
"method": "read",
"permission": "nexus:tasktypes",
"type": "application",
"needadmin": False
},
"71": {
"id": "71",
"method": "read",
"permission": "nexus:componentscheduletypes",
"type": "application",
"needadmin": False
},
"26": {
"id": "26",
"method": "create,read",
"permission": "nexus:tasks",
"type": "application",
"needadmin": True
},
"29": {
"id": "29",
"method": "delete,read",
"permission": "nexus:tasks",
"type": "application",
"needadmin": True
},
"27": {
"id": "27",
"method": "read",
"permission": "nexus:tasks",
"type": "application",
"needadmin": False
},
"68": {
"id": "68",
"method": "read,delete",
"permission": "nexus:tasksrun",
"type": "application",
"needadmin": True
},
"28": {
"id": "28",
"method": "update,read",
"permission": "nexus:tasks",
"type": "application",
"needadmin": True
},
"17": {
"id": "17",
"method": "read",
"permission": "nexus:index",
"type": "application",
"needadmin": False
},
"1001": {
"id": "1001",
"method": "*",
"permission": "security:*",
"type": "application",
"needadmin": True
},
"3": {
"id": "3",
"method": "read",
"permission": "nexus:settings",
"type": "application",
"needadmin": False
},
"4": {
"id": "4",
"method": "update,read",
"permission": "nexus:settings",
"type": "application",
"needadmin": True
},
"49": {
"id": "49",
"method": "update,read",
"permission": "nexus:status",
"type": "application",
"needadmin": True
},
"1": {
"id": "1",
"method": "read",
"permission": "nexus:status",
"type": "application",
"needadmin": False
},
"56": {
"id": "56",
"method": "update",
"permission": "nexus:repostatus",
"type": "application",
"needadmin": True
},
"64": {
"id": "64",
"method": "create,read",
"permission": "security:userschangepw",
"type": "application",
"needadmin": False
},
"57": {
"id": "57",
"method": "create,read",
"permission": "security:usersforgotpw",
"type": "application",
"needadmin": False
},
"58": {
"id": "58",
"method": "create,read",
"permission": "security:usersforgotid",
"type": "application",
"needadmin": False
},
"75": {
"id": "75",
"method": "read",
"permission": "security:componentsuserlocatortypes",
"type": "application",
"needadmin": False
},
"80": {
"id": "80",
"method": "read",
"permission": "security:privilegetypes",
"type": "application",
"needadmin": False
},
"30": {
"id": "30",
"method": "create,read",
"permission": "security:privileges",
"type": "application",
"needadmin": True
},
"33": {
"id": "33",
"method": "delete,read",
"permission": "security:privileges",
"type": "application",
"needadmin": True
},
"31": {
"id": "31",
"method": "read",
"permission": "security:privileges",
"type": "application",
"needadmin": False
},
"32": {
"id": "32",
"method": "update,read",
"permission": "security:privileges",
"type": "application",
"needadmin": True
},
"59": {
"id": "59",
"method": "delete,read",
"permission": "security:usersreset",
"type": "application",
"needadmin": True
},
"34": {
"id": "34",
"method": "create,read",
"permission": "security:roles",
"type": "application",
"needadmin": True
},
"37": {
"id": "37",
"method": "delete,read",
"permission": "security:roles",
"type": "application",
"needadmin": True
},
"35": {
"id": "35",
"method": "read",
"permission": "security:roles",
"type": "application",
"needadmin": False
},
"36": {
"id": "36",
"method": "update,read",
"permission": "security:roles",
"type": "application",
"needadmin": True
},
"72": {
"id": "72",
"method": "create,read",
"permission": "security:userssetpw",
"type": "application",
"needadmin": True
},
"38": {
"id": "38",
"method": "create,read",
"permission": "security:users",
"type": "application",
"needadmin": True
},
"41": {
"id": "41",
"method": "delete,read",
"permission": "security:users",
"type": "application",
"needadmin": True
},
"39": {
"id": "39",
"method": "read",
"permission": "security:users",
"type": "application",
"needadmin": False
},
"40": {
"id": "40",
"method": "update,read",
"permission": "security:users",
"type": "application",
"needadmin": True
},
"51": {
"id": "51",
"method": "delete,read",
"permission": "nexus:wastebasket",
"type": "application",
"needadmin": False
},
"50": {
"id": "50",
"method": "read",
"permission": "nexus:wastebasket",
"type": "application",
"needadmin": False
},
"wonderland-all": {
"id": "wonderland-all",
"method": "*",
"permission": "nexus:wonderland",
"type": "application",
"needadmin": False
},
"yum-alias-read": {
"id": "yum-alias-read",
"method": "read",
"permission": "nexus:yumAlias",
"type": "application",
"needadmin": False
},
"yum-alias-create-read": {
"id": "yum-alias-create-read",
"method": "create,update,read",
"permission": "nexus:yumAlias",
"type": "application",
"needadmin": False
},
"yum-repository-read": {
"id": "yum-repository-read",
"method": "read",
"permission": "nexus:yumVersionedRepositories",
"type": "application",
"needadmin": False
}
}
def getBuiltinRoles(privmap):
return {
"analytics": {
"groupName": "analytics",
"description": "Gives access to Analytics",
"privileges": [
privmap["analytics-all"]
],
"roles": [],
"admin": False,
"builtin": True
},
"atlas": {
"groupName": "atlas",
"description": "Gives access to Atlas support tools",
"privileges": [
privmap["atlas-all"]
],
"roles": [],
"admin": False,
"builtin": True
},
"metrics-endpoints": {
"groupName": "metrics-endpoints",
"description": "Allows access to metrics endpoints.",
"privileges": [
privmap["metrics-endpoints"]
],
"roles": [],
"admin": False,
"builtin": True
},
"nx-admin": {
"groupName": "nx-admin",
"description": "Administration role for Nexus",
"privileges": [
privmap["1001"],
privmap["1000"],
privmap["83"]
],
"roles": [],
"admin": True,
"builtin": True
},
"anonymous": {
"groupName": "anonymous",
"description": "Anonymous role for Nexus",
"privileges": [
privmap["1"],
privmap["57"],
privmap["58"],
privmap["70"],
privmap["74"],
privmap["54"]
],
"roles": [
"ui-healthcheck-read",
"ui-search",
"ui-repo-browser",
],
"admin": False,
"builtin": True
},
"nx-apikey-access": {
"groupName": "nx-apikey-access",
"description": "API-Key Access role for Nexus.",
"privileges": [
privmap["83"]
],
"roles": [],
"admin": False,
"builtin": True
},
"nx-deployment": {
"groupName": "nx-deployment",
"description": "Deployment role for Nexus",
"privileges": [
privmap["83"]
],
"roles": [
"ui-basic",
"anonymous",
],
"admin": False,
"builtin": True
},
"nx-developer": {
"groupName": "nx-developer",
"description": "Developer role for Nexus",
"privileges": [],
"roles": [
"ui-basic",
"nx-deployment",
],
"admin": False,
"builtin": True
},
"nexus-yum-admin": {
"groupName": "nexus-yum-admin",
"description": "Gives access to read versioned yum repositories and administrate version aliases",
"privileges": [
privmap["yum-repository-read"],
privmap["yum-alias-create-read"],
privmap["yum-alias-read"]
],
"roles": [],
"admin": False,
"builtin": True
},
"nexus-yum-user": {
"groupName": "nexus-yum-user",
"description": "Gives access to read versioned yum repositories",
"privileges": [
privmap["yum-repository-read"]
],
"roles": [],
"admin": False,
"builtin": True
},
"any-all-view": {
"groupName": "any-all-view",
"description": "Gives access to view ALL Repositories in Nexus.",
"privileges": [],
"roles": [],
"admin": False,
"builtin": True
},
"repo-all-full": {
"groupName": "repo-all-full",
"description": "Gives access to create/read/update/delete ALL content of ALL Maven1 and Maven2 repositories in Nexus.",
"privileges": [
privmap["T4"],
privmap["T5"],
privmap["T6"],
privmap["T7"],
privmap["T8"],
privmap["repository-all"],
privmap["T1"],
privmap["T2"],
privmap["T3"]
],
"roles": [],
"admin": False,
"builtin": True
},
"repo-all-read": {
"groupName": "repo-all-read",
"description": "Gives access to read ALL content of ALL Maven1 and Maven2 repositories in Nexus.",
"privileges": [
privmap["repository-all"],
privmap["T1"],
privmap["T2"]
],
"roles": [],
"admin": False,
"builtin": True
},
"maven1-all-view": {
"groupName": "maven1-all-view",
"description": "Gives access to view ALL Maven1 Repositories in Nexus.",
"privileges": [],
"roles": [],
"admin": False,
"builtin": True
},
"maven2-all-view": {
"groupName": "maven2-all-view",
"description": "Gives access to view ALL Maven2 Repositories in Nexus.",
"privileges": [],
"roles": [],
"admin": False,
"builtin": True
},
"npm-all-full": {
"groupName": "npm-all-full",
"description": "Gives access to create/read/update/delete ALL content of ALL npm Repositories in Nexus.",
"privileges": [
privmap["npm-read"],
privmap["npm-create"],
privmap["npm-delete"],
privmap["npm-update"]
],
"roles": [
"npm-all-view",
],
"admin": False,
"builtin": True
},
"npm-all-read": {
"groupName": "npm-all-read",
"description": "Gives access to read ALL content of ALL npm Repositories in Nexus.",
"privileges": [
privmap["npm-read"]
],
"roles": [
"npm-all-view",
],
"admin": False,
"builtin": True
},
"npm-all-view": {
"groupName": "npm-all-view",
"description": "Gives access to view ALL npm Repositories in Nexus.",
"privileges": [],
"roles": [],
"admin": False,
"builtin": True
},
"nuget-all-full": {
"groupName": "nuget-all-full",
"description": "Gives access to create/read/update/delete ALL content of ALL NuGet Repositories in Nexus.",
"privileges": [
privmap["nuget-read"],
privmap["nuget-create"],
privmap["nuget-delete"],
privmap["nuget-update"]
],
"roles": [
"nuget-all-view",
],
"admin": False,
"builtin": True
},
"nuget-all-read": {
"groupName": "nuget-all-read",
"description": "Gives access to read ALL content of ALL NuGet Repositories in Nexus.",
"privileges": [
privmap["nuget-read"]
],
"roles": [
"nuget-all-view",
],
"admin": False,
"builtin": True
},
"nuget-all-view": {
"groupName": "nuget-all-view",
"description": "Gives access to view ALL NuGet Repositories in Nexus.",
"privileges": [],
"roles": [],
"admin": False,
"builtin": True
},
"repository-any-full": {
"groupName": "repository-any-full",
"description": "Gives access to create/read/update/delete ALL content of ALL repositories in Nexus.",
"privileges": [
privmap["T10"],
privmap["T12"],
privmap["repository-all"],
privmap["T9"],
privmap["T11"]
],
"roles": [],
"admin": False,
"builtin": True
},
"repository-any-read": {
"groupName": "repository-any-read",
"description": "Gives access to read ALL content of ALL repositories in Nexus.",
"privileges": [
privmap["repository-all"],
privmap["T9"]
],
"roles": [],
"admin": False,
"builtin": True
},
"rubygems-all-full": {
"groupName": "rubygems-all-full",
"description": "Gives access to create/read/update/delete ALL content of ALL Rubygems Repositories in Nexus.",
"privileges": [
privmap["rubygems-create"],
privmap["rubygems-delete"],
privmap["rubygems-read"],
privmap["rubygems-update"]
],
"roles": [
"rubygems-all-view",
],
"admin": False,
"builtin": True
},
"rubygems-all-read": {
"groupName": "rubygems-all-read",
"description": "Gives access to read ALL content of ALL Rubygems Repositories in Nexus.",
"privileges": [
privmap["rubygems-read"]
],
"roles": [
"rubygems-all-view",
],
"admin": False,
"builtin": True
},
"rubygems-all-view": {
"groupName": "rubygems-all-view",
"description": "Gives access to view ALL Rubygems Repositories in Nexus.",
"privileges": [],
"roles": [],
"admin": False,
"builtin": True
},
"site-all-full": {
"groupName": "site-all-full",
"description": "Gives access to create/read/update/delete ALL content of ALL Site Repositories in Nexus.",
"privileges": [
privmap["site-create"],
privmap["site-update"],
privmap["site-delete"],
privmap["repository-all"],
privmap["site-read"]
],
"roles": [],
"admin": False,
"builtin": True
},
"site-all-read": {
"groupName": "site-all-read",
"description": "Gives access to read ALL content of ALL Site Repositories in Nexus.",
"privileges": [
privmap["repository-all"],
privmap["site-read"]
],
"roles": [],
"admin": False,
"builtin": True
},
"site-all-view": {
"groupName": "site-all-view",
"description": "Gives access to view ALL Site Repositories in Nexus.",
"privileges": [],
"roles": [],
"admin": False,
"builtin": True
},
"ui-basic": {
"groupName": "ui-basic",
"description": "Generic privileges for users in the Nexus UI",
"privileges": [
privmap["1"],
privmap["2"],
privmap["64"]
],
"roles": [],
"admin": False,
"builtin": True
},
"ui-capabilities-admin": {
"groupName": "ui-capabilities-admin",
"description": "Gives access to Capabilities Administration screen in Nexus UI",
"privileges": [
privmap["capabilities-read"],
privmap["capability-types-read"],
privmap["14"],
privmap["capabilities-update-read"],
privmap["6"],
privmap["capabilities-delete-read"],
privmap["capabilities-create-read"]
],
"roles": [],
"admin": False,
"builtin": True
},
"ui-group-admin": {
"groupName": "ui-group-admin",
"description": "Gives access to the Group Administration screen in Nexus UI",
"privileges": [
privmap["13"],
privmap["14"],
privmap["15"],
privmap["repository-all"],
privmap["16"],
privmap["6"]
],
"roles": [
"ui-repo-browser",
],
"admin": False,
"builtin": True
},
"ui-healthcheck-full": {
"groupName": "ui-healthcheck-full",
"description": "Gives access to view and enable/disable the health check for repositories, along with some additional artifact data",
"privileges": [
privmap["nexus-healthcheck-update"]
],
"roles": [
"ui-healthcheck-read",
],
"admin": False,
"builtin": True
},
"ui-healthcheck-read": {
"groupName": "ui-healthcheck-read",
"description": "Gives access to view the health check summary for repositories",
"privileges": [
privmap["nexus-healthcheck-summary-read"],
privmap["nexus-healthcheck-read"]
],
"roles": [],
"admin": False,
"builtin": True
},
"ui-ldap-admin": {
"groupName": "ui-ldap-admin",
"description": "Gives access to configure the LDAP server used for authentication.",
"privileges": [
privmap["ldap-conn-read"],
privmap["ldap-user-group-conf-update"],
privmap["ldap-user-role-map-create"],
privmap["ldap-conn-update"],
privmap["ldap-test-auth-conf"],
privmap["ldap-user-role-map-update"],
privmap["ldap-user-role-map-read"],
privmap["ldap-user-role-map-delete"],
privmap["ldap-user-group-conf-read"],
privmap["ldap-test-user-group-conf"]
],
"roles": [
"ui-server-admin",
],
"admin": False,
"builtin": True
},
"ui-logs-config-files": {
"groupName": "ui-logs-config-files",
"description": "Gives access to the Logs and Config Files screen in Nexus UI",
"privileges": [
privmap["42"],
privmap["43"]
],
"roles": [],
"admin": False,
"builtin": True
},
"ui-plugin-console": {
"groupName": "ui-plugin-console",
"description": "Gives access to the Plugin Console screen in Nexus UI.",
"privileges": [
privmap["plugin-infos-read"]
],
"roles": [],
"admin": False,
"builtin": True
},
"ui-privileges-admin": {
"groupName": "ui-privileges-admin",
"description": "Gives access to the Privilege Administration screen in Nexus UI",
"privileges": [
privmap["33"],
privmap["46"],
privmap["14"],
privmap["6"],
privmap["80"],
privmap["30"],
privmap["31"],
privmap["32"]
],
"roles": [],
"admin": False,
"builtin": True
},
"ui-repository-admin": {
"groupName": "ui-repository-admin",
"description": "Gives access to the Repository Administration screen in Nexus UI",
"privileges": [
privmap["78"],
privmap["79"],
privmap["repository-all"],
privmap["5"],
privmap["6"],
privmap["7"],
privmap["8"],
privmap["81"],
privmap["82"],
privmap["74"],
privmap["10"]
],
"roles": [
"ui-repo-browser",
],
"admin": False,
"builtin": True
},
"ui-repo-browser": {
"groupName": "ui-repo-browser",
"description": "Gives access to the Repository Browser screen in Nexus UI",
"privileges": [
privmap["55"],
privmap["14"],
privmap["6"],
privmap["browse-remote-repo"]
],
"roles": [],
"admin": False,
"builtin": True
},
"ui-repository-targets-admin": {
"groupName": "ui-repository-targets-admin",
"description": "Gives access to the Repository Target Administration screen in Nexus UI",
"privileges": [
privmap["45"],
privmap["46"],
privmap["47"],
privmap["48"],
privmap["70"],
privmap["74"]
],
"roles": [],
"admin": False,
"builtin": True
},
"ui-roles-admin": {
"groupName": "ui-roles-admin",
"description": "Gives access to the Role Administration screen in Nexus UI",
"privileges": [
privmap["34"],
privmap["35"],
privmap["36"],
privmap["37"],
privmap["31"]
],
"roles": [],
"admin": False,
"builtin": True
},
"ui-routing-admin": {
"groupName": "ui-routing-admin",
"description": "Gives access to the Routing Administration screen in Nexus UI",
"privileges": [
privmap["22"],
privmap["23"],
privmap["24"],
privmap["14"],
privmap["25"],
privmap["6"]
],
"roles": [],
"admin": False,
"builtin": True
},
"ui-scheduled-tasks-admin": {
"groupName": "ui-scheduled-tasks-admin",
"description": "Gives access to the Scheduled Task Administration screen in Nexus UI",
"privileges": [
privmap["68"],
privmap["14"],
privmap["69"],
privmap["26"],
privmap["27"],
privmap["6"],
privmap["28"],
privmap["29"],
privmap["71"]
],
"roles": [],
"admin": False,
"builtin": True
},
"ui-search": {
"groupName": "ui-search",
"description": "Gives access to the Search screen in Nexus UI",
"privileges": [
privmap["17"],
privmap["19"],
privmap["54"]
],
"roles": [],
"admin": False,
"builtin": True
},
"ui-server-admin": {
"groupName": "ui-server-admin",
"description": "Gives access to the Server Administration screen in Nexus UI",
"privileges": [
privmap["3"],
privmap["4"],
privmap["73"]
],
"roles": [],
"admin": False,
"builtin": True
},
"ui-system-feeds": {
"groupName": "ui-system-feeds",
"description": "Gives access to the System Feeds screen in Nexus UI",
"privileges": [
privmap["44"]
],
"roles": [],
"admin": False,
"builtin": True
},
"ui-users-admin": {
"groupName": "ui-users-admin",
"description": "Gives access to the User Administration screen in Nexus UI",
"privileges": [
privmap["35"],
privmap["38"],
privmap["39"],
privmap["72"],
privmap["40"],
privmap["41"],
privmap["75"]
],
"roles": [],
"admin": False,
"builtin": True
},
"wonderland": {
"groupName": "wonderland",
"description": "Gives access to Wonderland",
"privileges": [
privmap["wonderland-all"]
],
"roles": [],
"admin": False,
"builtin": True
}
}
| def get_builtin_targs():
return {'1': {'name': '1', 'ptype': 'maven2', 'patterns': ['.*'], 'defincpat': ['**'], 'defexcpat': []}, '2': {'name': '2', 'ptype': 'maven1', 'patterns': ['.*'], 'defincpat': ['**'], 'defexcpat': []}, '3': {'name': '3', 'ptype': 'maven2', 'patterns': ['(?!.*-sources.*).*'], 'defincpat': ['**'], 'defexcpat': ['**/*-sources.*/**']}, '4': {'name': '4', 'ptype': 'maven2', 'patterns': ['.*maven-metadata\\.xml.*'], 'defincpat': ['**/*maven-metadata.xml*'], 'defexcpat': []}, 'any': {'name': 'any', 'ptype': 'any', 'patterns': ['.*'], 'defincpat': ['**'], 'defexcpat': []}, 'site': {'name': 'site', 'ptype': 'site', 'patterns': ['.*'], 'defincpat': ['**'], 'defexcpat': []}, 'npm': {'name': 'npm', 'ptype': 'npm', 'patterns': ['.*'], 'defincpat': ['**'], 'defexcpat': []}, 'nuget': {'name': 'nuget', 'ptype': 'nuget', 'patterns': ['.*'], 'defincpat': ['**'], 'defexcpat': []}, 'rubygems': {'name': 'rubygems', 'ptype': 'rubygems', 'patterns': ['.*'], 'defincpat': ['**'], 'defexcpat': []}}
def get_builtin_privs(targs):
return {'All M1 Repositories': {'name': 'All M1 Repositories', 'target': targs['2'], 'repo': '*', 'builtin': True}, 'All M2 Repositories': {'name': 'All M2 Repositories', 'target': targs['1'], 'repo': '*', 'builtin': True}, 'All npm Repositories': {'name': 'All npm Repositories', 'target': targs['npm'], 'repo': '*', 'builtin': True}, 'All NuGet Repositories': {'name': 'All NuGet Repositories', 'target': targs['nuget'], 'repo': '*', 'builtin': True}, 'All Repositories': {'name': 'All Repositories', 'target': targs['any'], 'repo': '*', 'builtin': True}, 'All Rubygems Repositories': {'name': 'All Rubygems Repositories', 'target': targs['rubygems'], 'repo': '*', 'builtin': True}, 'All Site Repositories': {'name': 'All Site Repositories', 'target': targs['site'], 'repo': '*', 'builtin': True}}
def get_builtin_privmap(privs):
return {'repository-all': {'id': 'repository-all', 'repo': '*', 'type': 'view', 'needadmin': False}, 'T6': {'id': 'T6', 'method': 'create', 'priv': privs['All M1 Repositories'], 'type': 'target', 'needadmin': False}, 'T8': {'id': 'T8', 'method': 'delete', 'priv': privs['All M1 Repositories'], 'type': 'target', 'needadmin': False}, 'T2': {'id': 'T2', 'method': 'read', 'priv': privs['All M1 Repositories'], 'type': 'target', 'needadmin': False}, 'T4': {'id': 'T4', 'method': 'update', 'priv': privs['All M1 Repositories'], 'type': 'target', 'needadmin': False}, 'T5': {'id': 'T5', 'method': 'create', 'priv': privs['All M2 Repositories'], 'type': 'target', 'needadmin': False}, 'T7': {'id': 'T7', 'method': 'delete', 'priv': privs['All M2 Repositories'], 'type': 'target', 'needadmin': False}, 'T1': {'id': 'T1', 'method': 'read', 'priv': privs['All M2 Repositories'], 'type': 'target', 'needadmin': False}, 'T3': {'id': 'T3', 'method': 'update', 'priv': privs['All M2 Repositories'], 'type': 'target', 'needadmin': False}, 'npm-create': {'id': 'npm-create', 'method': 'create', 'priv': privs['All npm Repositories'], 'type': 'target', 'needadmin': False}, 'npm-delete': {'id': 'npm-delete', 'method': 'delete', 'priv': privs['All npm Repositories'], 'type': 'target', 'needadmin': False}, 'npm-read': {'id': 'npm-read', 'method': 'read', 'priv': privs['All npm Repositories'], 'type': 'target', 'needadmin': False}, 'npm-update': {'id': 'npm-update', 'method': 'update', 'priv': privs['All npm Repositories'], 'type': 'target', 'needadmin': False}, 'nuget-create': {'id': 'nuget-create', 'method': 'create', 'priv': privs['All NuGet Repositories'], 'type': 'target', 'needadmin': False}, 'nuget-delete': {'id': 'nuget-delete', 'method': 'delete', 'priv': privs['All NuGet Repositories'], 'type': 'target', 'needadmin': False}, 'nuget-read': {'id': 'nuget-read', 'method': 'read', 'priv': privs['All NuGet Repositories'], 'type': 'target', 'needadmin': False}, 'nuget-update': {'id': 'nuget-update', 'method': 'update', 'priv': privs['All NuGet Repositories'], 'type': 'target', 'needadmin': False}, 'T11': {'id': 'T11', 'method': 'create', 'priv': privs['All Repositories'], 'type': 'target', 'needadmin': False}, 'T12': {'id': 'T12', 'method': 'delete', 'priv': privs['All Repositories'], 'type': 'target', 'needadmin': False}, 'T9': {'id': 'T9', 'method': 'read', 'priv': privs['All Repositories'], 'type': 'target', 'needadmin': False}, 'T10': {'id': 'T10', 'method': 'update', 'priv': privs['All Repositories'], 'type': 'target', 'needadmin': False}, 'rubygems-create': {'id': 'rubygems-create', 'method': 'create', 'priv': privs['All Rubygems Repositories'], 'type': 'target', 'needadmin': False}, 'rubygems-delete': {'id': 'rubygems-delete', 'method': 'delete', 'priv': privs['All Rubygems Repositories'], 'type': 'target', 'needadmin': False}, 'rubygems-read': {'id': 'rubygems-read', 'method': 'read', 'priv': privs['All Rubygems Repositories'], 'type': 'target', 'needadmin': False}, 'rubygems-update': {'id': 'rubygems-update', 'method': 'update', 'priv': privs['All Rubygems Repositories'], 'type': 'target', 'needadmin': False}, 'site-create': {'id': 'site-create', 'method': 'create', 'priv': privs['All Site Repositories'], 'type': 'target', 'needadmin': False}, 'site-delete': {'id': 'site-delete', 'method': 'delete', 'priv': privs['All Site Repositories'], 'type': 'target', 'needadmin': False}, 'site-read': {'id': 'site-read', 'method': 'read', 'priv': privs['All Site Repositories'], 'type': 'target', 'needadmin': False}, 'site-update': {'id': 'site-update', 'method': 'update', 'priv': privs['All Site Repositories'], 'type': 'target', 'needadmin': False}, '1000': {'id': '1000', 'method': '*', 'permission': 'nexus:*', 'type': 'application', 'needadmin': True}, 'analytics-all': {'id': 'analytics-all', 'method': '*', 'permission': 'nexus:analytics', 'type': 'application', 'needadmin': False}, '83': {'id': '83', 'method': '*', 'permission': 'apikey:access', 'type': 'application', 'needadmin': False}, '54': {'id': '54', 'method': 'read', 'permission': 'nexus:artifact', 'type': 'application', 'needadmin': False}, '65': {'id': '65', 'method': 'create,read', 'permission': 'nexus:artifact', 'type': 'application', 'needadmin': False}, 'atlas-all': {'id': 'atlas-all', 'method': '*', 'permission': 'nexus:atlas', 'type': 'application', 'needadmin': False}, 'browse-remote-repo': {'id': 'browse-remote-repo', 'method': 'read', 'permission': 'nexus:browseremote', 'type': 'application', 'needadmin': False}, 'capabilities-create-read': {'id': 'capabilities-create-read', 'method': 'create,read', 'permission': 'nexus:capabilities', 'type': 'application', 'needadmin': False}, 'capabilities-delete-read': {'id': 'capabilities-delete-read', 'method': 'delete,read', 'permission': 'nexus:capabilities', 'type': 'application', 'needadmin': False}, 'capabilities-read': {'id': 'capabilities-read', 'method': 'read', 'permission': 'nexus:capabilities', 'type': 'application', 'needadmin': False}, 'capabilities-update-read': {'id': 'capabilities-update-read', 'method': 'update,read', 'permission': 'nexus:capabilities', 'type': 'application', 'needadmin': False}, 'capability-types-read': {'id': 'capability-types-read', 'method': 'read', 'permission': 'nexus:capabilityTypes', 'type': 'application', 'needadmin': False}, '19': {'id': '19', 'method': 'read', 'permission': 'nexus:identify', 'type': 'application', 'needadmin': False}, '21': {'id': '21', 'method': 'delete,read', 'permission': 'nexus:cache', 'type': 'application', 'needadmin': True}, '43': {'id': '43', 'method': 'read', 'permission': 'nexus:configuration', 'type': 'application', 'needadmin': False}, 'nexus-healthcheck-read': {'id': 'nexus-healthcheck-read', 'method': 'read', 'permission': 'nexus:healthcheck', 'type': 'application', 'needadmin': False}, 'nexus-healthcheck-update': {'id': 'nexus-healthcheck-update', 'method': 'update', 'permission': 'nexus:healthcheck', 'type': 'application', 'needadmin': False}, 'nexus-healthcheck-summary-read': {'id': 'nexus-healthcheck-summary-read', 'method': 'read', 'permission': 'nexus:healthchecksummary', 'type': 'application', 'needadmin': False}, 'ldap-conn-read': {'id': 'ldap-conn-read', 'method': 'read', 'permission': 'nexus:ldapconninfo', 'type': 'application', 'needadmin': False}, 'ldap-conn-update': {'id': 'ldap-conn-update', 'method': 'update', 'permission': 'nexus:ldapconninfo', 'type': 'application', 'needadmin': True}, 'ldap-test-auth-conf': {'id': 'ldap-test-auth-conf', 'method': 'update', 'permission': 'nexus:ldaptestauth', 'type': 'application', 'needadmin': True}, 'ldap-test-user-group-conf': {'id': 'ldap-test-user-group-conf', 'method': 'update', 'permission': 'nexus:ldaptestuserconf', 'type': 'application', 'needadmin': True}, 'ldap-user-group-conf-read': {'id': 'ldap-user-group-conf-read', 'method': 'read', 'permission': 'nexus:ldapusergroupconf', 'type': 'application', 'needadmin': False}, 'ldap-user-group-conf-update': {'id': 'ldap-user-group-conf-update', 'method': 'update', 'permission': 'nexus:ldapusergroupconf', 'type': 'application', 'needadmin': True}, 'ldap-user-role-map-create': {'id': 'ldap-user-role-map-create', 'method': 'create', 'permission': 'nexus:ldapuserrolemap', 'type': 'application', 'needadmin': True}, 'ldap-user-role-map-delete': {'id': 'ldap-user-role-map-delete', 'method': 'delete,read', 'permission': 'nexus:ldapuserrolemap', 'type': 'application', 'needadmin': True}, 'ldap-user-role-map-read': {'id': 'ldap-user-role-map-read', 'method': 'read', 'permission': 'nexus:ldapuserrolemap', 'type': 'application', 'needadmin': False}, 'ldap-user-role-map-update': {'id': 'ldap-user-role-map-update', 'method': 'update', 'permission': 'nexus:ldapuserrolemap', 'type': 'application', 'needadmin': True}, '77': {'id': '77', 'method': 'read,update', 'permission': 'nexus:logconfig', 'type': 'application', 'needadmin': False}, '2': {'id': '2', 'method': 'read', 'permission': 'nexus:authentication', 'type': 'application', 'needadmin': False}, '42': {'id': '42', 'method': 'read', 'permission': 'nexus:logs', 'type': 'application', 'needadmin': False}, 'metrics-endpoints': {'id': 'metrics-endpoints', 'method': '*', 'permission': 'nexus:metrics-endpoints', 'type': 'application', 'needadmin': False}, '66': {'id': '66', 'method': 'update,read', 'permission': 'nexus:command', 'type': 'application', 'needadmin': False}, 'plugin-infos-read': {'id': 'plugin-infos-read', 'method': 'read', 'permission': 'nexus:pluginconsoleplugininfos', 'type': 'application', 'needadmin': False}, '55': {'id': '55', 'method': 'read', 'permission': 'nexus:repostatus', 'type': 'application', 'needadmin': False}, '73': {'id': '73', 'method': 'read', 'permission': 'nexus:componentrealmtypes', 'type': 'application', 'needadmin': False}, '76': {'id': '76', 'method': 'delete,read', 'permission': 'nexus:metadata', 'type': 'application', 'needadmin': False}, '20': {'id': '20', 'method': 'delete,read', 'permission': 'nexus:attributes', 'type': 'application', 'needadmin': False}, '18': {'id': '18', 'method': 'delete,read', 'permission': 'nexus:index', 'type': 'application', 'needadmin': False}, '5': {'id': '5', 'method': 'create,read', 'permission': 'nexus:repositories', 'type': 'application', 'needadmin': True}, '8': {'id': '8', 'method': 'delete,read', 'permission': 'nexus:repositories', 'type': 'application', 'needadmin': True}, '6': {'id': '6', 'method': 'read', 'permission': 'nexus:repositories', 'type': 'application', 'needadmin': False}, '7': {'id': '7', 'method': 'update,read', 'permission': 'nexus:repositories', 'type': 'application', 'needadmin': True}, '70': {'id': '70', 'method': 'read', 'permission': 'nexus:componentscontentclasses', 'type': 'application', 'needadmin': False}, '13': {'id': '13', 'method': 'create,read', 'permission': 'nexus:repogroups', 'type': 'application', 'needadmin': True}, '16': {'id': '16', 'method': 'delete,read', 'permission': 'nexus:repogroups', 'type': 'application', 'needadmin': True}, '14': {'id': '14', 'method': 'read', 'permission': 'nexus:repogroups', 'type': 'application', 'needadmin': False}, '15': {'id': '15', 'method': 'update,read', 'permission': 'nexus:repogroups', 'type': 'application', 'needadmin': True}, '79': {'id': '79', 'method': 'create,read', 'permission': 'nexus:repositorymirrors', 'type': 'application', 'needadmin': False}, '78': {'id': '78', 'method': 'read', 'permission': 'nexus:repositorymirrors', 'type': 'application', 'needadmin': False}, '82': {'id': '82', 'method': 'read', 'permission': 'nexus:repositorymirrorsstatus', 'type': 'application', 'needadmin': False}, '81': {'id': '81', 'method': 'read', 'permission': 'nexus:repositorypredefinedmirrors', 'type': 'application', 'needadmin': False}, '22': {'id': '22', 'method': 'create,read', 'permission': 'nexus:routes', 'type': 'application', 'needadmin': False}, '25': {'id': '25', 'method': 'delete,read', 'permission': 'nexus:routes', 'type': 'application', 'needadmin': False}, '23': {'id': '23', 'method': 'read', 'permission': 'nexus:routes', 'type': 'application', 'needadmin': False}, '24': {'id': '24', 'method': 'update,read', 'permission': 'nexus:routes', 'type': 'application', 'needadmin': False}, '67': {'id': '67', 'method': 'read', 'permission': 'nexus:repometa', 'type': 'application', 'needadmin': False}, '45': {'id': '45', 'method': 'create,read', 'permission': 'nexus:targets', 'type': 'application', 'needadmin': True}, '48': {'id': '48', 'method': 'delete,read', 'permission': 'nexus:targets', 'type': 'application', 'needadmin': True}, '46': {'id': '46', 'method': 'read', 'permission': 'nexus:targets', 'type': 'application', 'needadmin': False}, '47': {'id': '47', 'method': 'update,read', 'permission': 'nexus:targets', 'type': 'application', 'needadmin': True}, '9': {'id': '9', 'method': 'create,read', 'permission': 'nexus:repotemplates', 'type': 'application', 'needadmin': False}, '12': {'id': '12', 'method': 'delete,read', 'permission': 'nexus:repotemplates', 'type': 'application', 'needadmin': False}, '10': {'id': '10', 'method': 'read', 'permission': 'nexus:repotemplates', 'type': 'application', 'needadmin': False}, '11': {'id': '11', 'method': 'update,read', 'permission': 'nexus:repotemplates', 'type': 'application', 'needadmin': False}, '74': {'id': '74', 'method': 'read', 'permission': 'nexus:componentsrepotypes', 'type': 'application', 'needadmin': False}, '44': {'id': '44', 'method': 'read', 'permission': 'nexus:feeds', 'type': 'application', 'needadmin': False}, '69': {'id': '69', 'method': 'read', 'permission': 'nexus:tasktypes', 'type': 'application', 'needadmin': False}, '71': {'id': '71', 'method': 'read', 'permission': 'nexus:componentscheduletypes', 'type': 'application', 'needadmin': False}, '26': {'id': '26', 'method': 'create,read', 'permission': 'nexus:tasks', 'type': 'application', 'needadmin': True}, '29': {'id': '29', 'method': 'delete,read', 'permission': 'nexus:tasks', 'type': 'application', 'needadmin': True}, '27': {'id': '27', 'method': 'read', 'permission': 'nexus:tasks', 'type': 'application', 'needadmin': False}, '68': {'id': '68', 'method': 'read,delete', 'permission': 'nexus:tasksrun', 'type': 'application', 'needadmin': True}, '28': {'id': '28', 'method': 'update,read', 'permission': 'nexus:tasks', 'type': 'application', 'needadmin': True}, '17': {'id': '17', 'method': 'read', 'permission': 'nexus:index', 'type': 'application', 'needadmin': False}, '1001': {'id': '1001', 'method': '*', 'permission': 'security:*', 'type': 'application', 'needadmin': True}, '3': {'id': '3', 'method': 'read', 'permission': 'nexus:settings', 'type': 'application', 'needadmin': False}, '4': {'id': '4', 'method': 'update,read', 'permission': 'nexus:settings', 'type': 'application', 'needadmin': True}, '49': {'id': '49', 'method': 'update,read', 'permission': 'nexus:status', 'type': 'application', 'needadmin': True}, '1': {'id': '1', 'method': 'read', 'permission': 'nexus:status', 'type': 'application', 'needadmin': False}, '56': {'id': '56', 'method': 'update', 'permission': 'nexus:repostatus', 'type': 'application', 'needadmin': True}, '64': {'id': '64', 'method': 'create,read', 'permission': 'security:userschangepw', 'type': 'application', 'needadmin': False}, '57': {'id': '57', 'method': 'create,read', 'permission': 'security:usersforgotpw', 'type': 'application', 'needadmin': False}, '58': {'id': '58', 'method': 'create,read', 'permission': 'security:usersforgotid', 'type': 'application', 'needadmin': False}, '75': {'id': '75', 'method': 'read', 'permission': 'security:componentsuserlocatortypes', 'type': 'application', 'needadmin': False}, '80': {'id': '80', 'method': 'read', 'permission': 'security:privilegetypes', 'type': 'application', 'needadmin': False}, '30': {'id': '30', 'method': 'create,read', 'permission': 'security:privileges', 'type': 'application', 'needadmin': True}, '33': {'id': '33', 'method': 'delete,read', 'permission': 'security:privileges', 'type': 'application', 'needadmin': True}, '31': {'id': '31', 'method': 'read', 'permission': 'security:privileges', 'type': 'application', 'needadmin': False}, '32': {'id': '32', 'method': 'update,read', 'permission': 'security:privileges', 'type': 'application', 'needadmin': True}, '59': {'id': '59', 'method': 'delete,read', 'permission': 'security:usersreset', 'type': 'application', 'needadmin': True}, '34': {'id': '34', 'method': 'create,read', 'permission': 'security:roles', 'type': 'application', 'needadmin': True}, '37': {'id': '37', 'method': 'delete,read', 'permission': 'security:roles', 'type': 'application', 'needadmin': True}, '35': {'id': '35', 'method': 'read', 'permission': 'security:roles', 'type': 'application', 'needadmin': False}, '36': {'id': '36', 'method': 'update,read', 'permission': 'security:roles', 'type': 'application', 'needadmin': True}, '72': {'id': '72', 'method': 'create,read', 'permission': 'security:userssetpw', 'type': 'application', 'needadmin': True}, '38': {'id': '38', 'method': 'create,read', 'permission': 'security:users', 'type': 'application', 'needadmin': True}, '41': {'id': '41', 'method': 'delete,read', 'permission': 'security:users', 'type': 'application', 'needadmin': True}, '39': {'id': '39', 'method': 'read', 'permission': 'security:users', 'type': 'application', 'needadmin': False}, '40': {'id': '40', 'method': 'update,read', 'permission': 'security:users', 'type': 'application', 'needadmin': True}, '51': {'id': '51', 'method': 'delete,read', 'permission': 'nexus:wastebasket', 'type': 'application', 'needadmin': False}, '50': {'id': '50', 'method': 'read', 'permission': 'nexus:wastebasket', 'type': 'application', 'needadmin': False}, 'wonderland-all': {'id': 'wonderland-all', 'method': '*', 'permission': 'nexus:wonderland', 'type': 'application', 'needadmin': False}, 'yum-alias-read': {'id': 'yum-alias-read', 'method': 'read', 'permission': 'nexus:yumAlias', 'type': 'application', 'needadmin': False}, 'yum-alias-create-read': {'id': 'yum-alias-create-read', 'method': 'create,update,read', 'permission': 'nexus:yumAlias', 'type': 'application', 'needadmin': False}, 'yum-repository-read': {'id': 'yum-repository-read', 'method': 'read', 'permission': 'nexus:yumVersionedRepositories', 'type': 'application', 'needadmin': False}}
def get_builtin_roles(privmap):
return {'analytics': {'groupName': 'analytics', 'description': 'Gives access to Analytics', 'privileges': [privmap['analytics-all']], 'roles': [], 'admin': False, 'builtin': True}, 'atlas': {'groupName': 'atlas', 'description': 'Gives access to Atlas support tools', 'privileges': [privmap['atlas-all']], 'roles': [], 'admin': False, 'builtin': True}, 'metrics-endpoints': {'groupName': 'metrics-endpoints', 'description': 'Allows access to metrics endpoints.', 'privileges': [privmap['metrics-endpoints']], 'roles': [], 'admin': False, 'builtin': True}, 'nx-admin': {'groupName': 'nx-admin', 'description': 'Administration role for Nexus', 'privileges': [privmap['1001'], privmap['1000'], privmap['83']], 'roles': [], 'admin': True, 'builtin': True}, 'anonymous': {'groupName': 'anonymous', 'description': 'Anonymous role for Nexus', 'privileges': [privmap['1'], privmap['57'], privmap['58'], privmap['70'], privmap['74'], privmap['54']], 'roles': ['ui-healthcheck-read', 'ui-search', 'ui-repo-browser'], 'admin': False, 'builtin': True}, 'nx-apikey-access': {'groupName': 'nx-apikey-access', 'description': 'API-Key Access role for Nexus.', 'privileges': [privmap['83']], 'roles': [], 'admin': False, 'builtin': True}, 'nx-deployment': {'groupName': 'nx-deployment', 'description': 'Deployment role for Nexus', 'privileges': [privmap['83']], 'roles': ['ui-basic', 'anonymous'], 'admin': False, 'builtin': True}, 'nx-developer': {'groupName': 'nx-developer', 'description': 'Developer role for Nexus', 'privileges': [], 'roles': ['ui-basic', 'nx-deployment'], 'admin': False, 'builtin': True}, 'nexus-yum-admin': {'groupName': 'nexus-yum-admin', 'description': 'Gives access to read versioned yum repositories and administrate version aliases', 'privileges': [privmap['yum-repository-read'], privmap['yum-alias-create-read'], privmap['yum-alias-read']], 'roles': [], 'admin': False, 'builtin': True}, 'nexus-yum-user': {'groupName': 'nexus-yum-user', 'description': 'Gives access to read versioned yum repositories', 'privileges': [privmap['yum-repository-read']], 'roles': [], 'admin': False, 'builtin': True}, 'any-all-view': {'groupName': 'any-all-view', 'description': 'Gives access to view ALL Repositories in Nexus.', 'privileges': [], 'roles': [], 'admin': False, 'builtin': True}, 'repo-all-full': {'groupName': 'repo-all-full', 'description': 'Gives access to create/read/update/delete ALL content of ALL Maven1 and Maven2 repositories in Nexus.', 'privileges': [privmap['T4'], privmap['T5'], privmap['T6'], privmap['T7'], privmap['T8'], privmap['repository-all'], privmap['T1'], privmap['T2'], privmap['T3']], 'roles': [], 'admin': False, 'builtin': True}, 'repo-all-read': {'groupName': 'repo-all-read', 'description': 'Gives access to read ALL content of ALL Maven1 and Maven2 repositories in Nexus.', 'privileges': [privmap['repository-all'], privmap['T1'], privmap['T2']], 'roles': [], 'admin': False, 'builtin': True}, 'maven1-all-view': {'groupName': 'maven1-all-view', 'description': 'Gives access to view ALL Maven1 Repositories in Nexus.', 'privileges': [], 'roles': [], 'admin': False, 'builtin': True}, 'maven2-all-view': {'groupName': 'maven2-all-view', 'description': 'Gives access to view ALL Maven2 Repositories in Nexus.', 'privileges': [], 'roles': [], 'admin': False, 'builtin': True}, 'npm-all-full': {'groupName': 'npm-all-full', 'description': 'Gives access to create/read/update/delete ALL content of ALL npm Repositories in Nexus.', 'privileges': [privmap['npm-read'], privmap['npm-create'], privmap['npm-delete'], privmap['npm-update']], 'roles': ['npm-all-view'], 'admin': False, 'builtin': True}, 'npm-all-read': {'groupName': 'npm-all-read', 'description': 'Gives access to read ALL content of ALL npm Repositories in Nexus.', 'privileges': [privmap['npm-read']], 'roles': ['npm-all-view'], 'admin': False, 'builtin': True}, 'npm-all-view': {'groupName': 'npm-all-view', 'description': 'Gives access to view ALL npm Repositories in Nexus.', 'privileges': [], 'roles': [], 'admin': False, 'builtin': True}, 'nuget-all-full': {'groupName': 'nuget-all-full', 'description': 'Gives access to create/read/update/delete ALL content of ALL NuGet Repositories in Nexus.', 'privileges': [privmap['nuget-read'], privmap['nuget-create'], privmap['nuget-delete'], privmap['nuget-update']], 'roles': ['nuget-all-view'], 'admin': False, 'builtin': True}, 'nuget-all-read': {'groupName': 'nuget-all-read', 'description': 'Gives access to read ALL content of ALL NuGet Repositories in Nexus.', 'privileges': [privmap['nuget-read']], 'roles': ['nuget-all-view'], 'admin': False, 'builtin': True}, 'nuget-all-view': {'groupName': 'nuget-all-view', 'description': 'Gives access to view ALL NuGet Repositories in Nexus.', 'privileges': [], 'roles': [], 'admin': False, 'builtin': True}, 'repository-any-full': {'groupName': 'repository-any-full', 'description': 'Gives access to create/read/update/delete ALL content of ALL repositories in Nexus.', 'privileges': [privmap['T10'], privmap['T12'], privmap['repository-all'], privmap['T9'], privmap['T11']], 'roles': [], 'admin': False, 'builtin': True}, 'repository-any-read': {'groupName': 'repository-any-read', 'description': 'Gives access to read ALL content of ALL repositories in Nexus.', 'privileges': [privmap['repository-all'], privmap['T9']], 'roles': [], 'admin': False, 'builtin': True}, 'rubygems-all-full': {'groupName': 'rubygems-all-full', 'description': 'Gives access to create/read/update/delete ALL content of ALL Rubygems Repositories in Nexus.', 'privileges': [privmap['rubygems-create'], privmap['rubygems-delete'], privmap['rubygems-read'], privmap['rubygems-update']], 'roles': ['rubygems-all-view'], 'admin': False, 'builtin': True}, 'rubygems-all-read': {'groupName': 'rubygems-all-read', 'description': 'Gives access to read ALL content of ALL Rubygems Repositories in Nexus.', 'privileges': [privmap['rubygems-read']], 'roles': ['rubygems-all-view'], 'admin': False, 'builtin': True}, 'rubygems-all-view': {'groupName': 'rubygems-all-view', 'description': 'Gives access to view ALL Rubygems Repositories in Nexus.', 'privileges': [], 'roles': [], 'admin': False, 'builtin': True}, 'site-all-full': {'groupName': 'site-all-full', 'description': 'Gives access to create/read/update/delete ALL content of ALL Site Repositories in Nexus.', 'privileges': [privmap['site-create'], privmap['site-update'], privmap['site-delete'], privmap['repository-all'], privmap['site-read']], 'roles': [], 'admin': False, 'builtin': True}, 'site-all-read': {'groupName': 'site-all-read', 'description': 'Gives access to read ALL content of ALL Site Repositories in Nexus.', 'privileges': [privmap['repository-all'], privmap['site-read']], 'roles': [], 'admin': False, 'builtin': True}, 'site-all-view': {'groupName': 'site-all-view', 'description': 'Gives access to view ALL Site Repositories in Nexus.', 'privileges': [], 'roles': [], 'admin': False, 'builtin': True}, 'ui-basic': {'groupName': 'ui-basic', 'description': 'Generic privileges for users in the Nexus UI', 'privileges': [privmap['1'], privmap['2'], privmap['64']], 'roles': [], 'admin': False, 'builtin': True}, 'ui-capabilities-admin': {'groupName': 'ui-capabilities-admin', 'description': 'Gives access to Capabilities Administration screen in Nexus UI', 'privileges': [privmap['capabilities-read'], privmap['capability-types-read'], privmap['14'], privmap['capabilities-update-read'], privmap['6'], privmap['capabilities-delete-read'], privmap['capabilities-create-read']], 'roles': [], 'admin': False, 'builtin': True}, 'ui-group-admin': {'groupName': 'ui-group-admin', 'description': 'Gives access to the Group Administration screen in Nexus UI', 'privileges': [privmap['13'], privmap['14'], privmap['15'], privmap['repository-all'], privmap['16'], privmap['6']], 'roles': ['ui-repo-browser'], 'admin': False, 'builtin': True}, 'ui-healthcheck-full': {'groupName': 'ui-healthcheck-full', 'description': 'Gives access to view and enable/disable the health check for repositories, along with some additional artifact data', 'privileges': [privmap['nexus-healthcheck-update']], 'roles': ['ui-healthcheck-read'], 'admin': False, 'builtin': True}, 'ui-healthcheck-read': {'groupName': 'ui-healthcheck-read', 'description': 'Gives access to view the health check summary for repositories', 'privileges': [privmap['nexus-healthcheck-summary-read'], privmap['nexus-healthcheck-read']], 'roles': [], 'admin': False, 'builtin': True}, 'ui-ldap-admin': {'groupName': 'ui-ldap-admin', 'description': 'Gives access to configure the LDAP server used for authentication.', 'privileges': [privmap['ldap-conn-read'], privmap['ldap-user-group-conf-update'], privmap['ldap-user-role-map-create'], privmap['ldap-conn-update'], privmap['ldap-test-auth-conf'], privmap['ldap-user-role-map-update'], privmap['ldap-user-role-map-read'], privmap['ldap-user-role-map-delete'], privmap['ldap-user-group-conf-read'], privmap['ldap-test-user-group-conf']], 'roles': ['ui-server-admin'], 'admin': False, 'builtin': True}, 'ui-logs-config-files': {'groupName': 'ui-logs-config-files', 'description': 'Gives access to the Logs and Config Files screen in Nexus UI', 'privileges': [privmap['42'], privmap['43']], 'roles': [], 'admin': False, 'builtin': True}, 'ui-plugin-console': {'groupName': 'ui-plugin-console', 'description': 'Gives access to the Plugin Console screen in Nexus UI.', 'privileges': [privmap['plugin-infos-read']], 'roles': [], 'admin': False, 'builtin': True}, 'ui-privileges-admin': {'groupName': 'ui-privileges-admin', 'description': 'Gives access to the Privilege Administration screen in Nexus UI', 'privileges': [privmap['33'], privmap['46'], privmap['14'], privmap['6'], privmap['80'], privmap['30'], privmap['31'], privmap['32']], 'roles': [], 'admin': False, 'builtin': True}, 'ui-repository-admin': {'groupName': 'ui-repository-admin', 'description': 'Gives access to the Repository Administration screen in Nexus UI', 'privileges': [privmap['78'], privmap['79'], privmap['repository-all'], privmap['5'], privmap['6'], privmap['7'], privmap['8'], privmap['81'], privmap['82'], privmap['74'], privmap['10']], 'roles': ['ui-repo-browser'], 'admin': False, 'builtin': True}, 'ui-repo-browser': {'groupName': 'ui-repo-browser', 'description': 'Gives access to the Repository Browser screen in Nexus UI', 'privileges': [privmap['55'], privmap['14'], privmap['6'], privmap['browse-remote-repo']], 'roles': [], 'admin': False, 'builtin': True}, 'ui-repository-targets-admin': {'groupName': 'ui-repository-targets-admin', 'description': 'Gives access to the Repository Target Administration screen in Nexus UI', 'privileges': [privmap['45'], privmap['46'], privmap['47'], privmap['48'], privmap['70'], privmap['74']], 'roles': [], 'admin': False, 'builtin': True}, 'ui-roles-admin': {'groupName': 'ui-roles-admin', 'description': 'Gives access to the Role Administration screen in Nexus UI', 'privileges': [privmap['34'], privmap['35'], privmap['36'], privmap['37'], privmap['31']], 'roles': [], 'admin': False, 'builtin': True}, 'ui-routing-admin': {'groupName': 'ui-routing-admin', 'description': 'Gives access to the Routing Administration screen in Nexus UI', 'privileges': [privmap['22'], privmap['23'], privmap['24'], privmap['14'], privmap['25'], privmap['6']], 'roles': [], 'admin': False, 'builtin': True}, 'ui-scheduled-tasks-admin': {'groupName': 'ui-scheduled-tasks-admin', 'description': 'Gives access to the Scheduled Task Administration screen in Nexus UI', 'privileges': [privmap['68'], privmap['14'], privmap['69'], privmap['26'], privmap['27'], privmap['6'], privmap['28'], privmap['29'], privmap['71']], 'roles': [], 'admin': False, 'builtin': True}, 'ui-search': {'groupName': 'ui-search', 'description': 'Gives access to the Search screen in Nexus UI', 'privileges': [privmap['17'], privmap['19'], privmap['54']], 'roles': [], 'admin': False, 'builtin': True}, 'ui-server-admin': {'groupName': 'ui-server-admin', 'description': 'Gives access to the Server Administration screen in Nexus UI', 'privileges': [privmap['3'], privmap['4'], privmap['73']], 'roles': [], 'admin': False, 'builtin': True}, 'ui-system-feeds': {'groupName': 'ui-system-feeds', 'description': 'Gives access to the System Feeds screen in Nexus UI', 'privileges': [privmap['44']], 'roles': [], 'admin': False, 'builtin': True}, 'ui-users-admin': {'groupName': 'ui-users-admin', 'description': 'Gives access to the User Administration screen in Nexus UI', 'privileges': [privmap['35'], privmap['38'], privmap['39'], privmap['72'], privmap['40'], privmap['41'], privmap['75']], 'roles': [], 'admin': False, 'builtin': True}, 'wonderland': {'groupName': 'wonderland', 'description': 'Gives access to Wonderland', 'privileges': [privmap['wonderland-all']], 'roles': [], 'admin': False, 'builtin': True}} |
def add(x,y):
"""add two numbers together"""
return x + y
| def add(x, y):
"""add two numbers together"""
return x + y |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 10 15:43:09 2017
@author: juherask
"""
DEBUG_VERBOSITY = 3
COST_EPSILON = 1e-10
CAPACITY_EPSILON = 1e-10
# how many seconds we give to a MIP solver
MAX_MIP_SOLVER_RUNTIME = 60*10 # 10m
MIP_SOLVER_THREADS = 1 # 0 is automatic (parallel computing)
BENCHMARKS_BASEPATH = r"C:\Users\juherask\Dissertation\Phases\Benchmarks"
LKH_EXE_PATH = r"C:\Users\juherask\Dissertation\Phases\Selection\solvers\lkh\lkh.exe"
LKH_EXACT_DISTANCES_PRECISION_DECIMALS = 1000.0 # of the form 0.123
ACOTSP_EXE_PATH = r"C:\Users\juherask\Dissertation\Phases\Selection\solvers\ACOTSP\acotsp.exe"
ACOTSP_EXACT_DISTANCES_PRECISION_DECIMALS = 1000.0 # of the form 0.123
| """
Created on Thu Aug 10 15:43:09 2017
@author: juherask
"""
debug_verbosity = 3
cost_epsilon = 1e-10
capacity_epsilon = 1e-10
max_mip_solver_runtime = 60 * 10
mip_solver_threads = 1
benchmarks_basepath = 'C:\\Users\\juherask\\Dissertation\\Phases\\Benchmarks'
lkh_exe_path = 'C:\\Users\\juherask\\Dissertation\\Phases\\Selection\\solvers\\lkh\\lkh.exe'
lkh_exact_distances_precision_decimals = 1000.0
acotsp_exe_path = 'C:\\Users\\juherask\\Dissertation\\Phases\\Selection\\solvers\\ACOTSP\\acotsp.exe'
acotsp_exact_distances_precision_decimals = 1000.0 |
EXT_STANDARD = 1
INT_STANDARD = 2
EXT_HQ = 3
INT_HQ = 4
EXT_HOUSE = 5
INT_HOUSE = 6
EXT_COGHQ = 7
INT_COGHQ = 8
EXT_KS = 9
INT_KS = 10
| ext_standard = 1
int_standard = 2
ext_hq = 3
int_hq = 4
ext_house = 5
int_house = 6
ext_coghq = 7
int_coghq = 8
ext_ks = 9
int_ks = 10 |
# Basics
""" Summary:
Dictionary are a list of Key and Value
{Key: Value}
You can create a key connected to its own definition
e.g.
{"Bug": "An error in a program that prevents the program from running as expected"}
You can also create more keys, separating each key /w a comma.
{
"Bug": "An error in a program that prevents the program from running as expected",
"Loop": The action of doing something over and over again."
}
"""
programming_dictionary = {
"Bug": "An error in a program that prevents the program from running as expected.",
"Function": "A piece of code that you can easily call over and over again.",
}
# adding a new item to dictionary
programming_dictionary["Item"] = "This is a new Value definition."
print(programming_dictionary)
# editing an item to dictionary
programming_dictionary["Bug"] = "This value has been edited."
print(programming_dictionary)
# example of retrive code - creating a loop through a dictionary
for key in programming_dictionary:
print(key)
print(programming_dictionary)
| """ Summary:
Dictionary are a list of Key and Value
{Key: Value}
You can create a key connected to its own definition
e.g.
{"Bug": "An error in a program that prevents the program from running as expected"}
You can also create more keys, separating each key /w a comma.
{
"Bug": "An error in a program that prevents the program from running as expected",
"Loop": The action of doing something over and over again."
}
"""
programming_dictionary = {'Bug': 'An error in a program that prevents the program from running as expected.', 'Function': 'A piece of code that you can easily call over and over again.'}
programming_dictionary['Item'] = 'This is a new Value definition.'
print(programming_dictionary)
programming_dictionary['Bug'] = 'This value has been edited.'
print(programming_dictionary)
for key in programming_dictionary:
print(key)
print(programming_dictionary) |
# Leo colorizer control file for dart mode.
# This file is in the public domain.
# Properties for dart mode.
properties = {
"commentEnd": "*/",
"commentStart": "/*",
"electricKeys": ":",
"indentCloseBrackets": "]}",
"indentNextLine": "\\s*(((if|while)\\s*\\(|else\\s*|else\\s+if\\s*\\(|for\\s*\\(.*\\))[^{;]*)",
"indentOpenBrackets": "{[",
"lineComment": "//",
"unalignedCloseBrackets": ")",
"unalignedOpenBrackets": "(",
"unindentThisLine": "^.*(default:\\s*|case.*:.*)$",
"wordBreakChars": ",+-=<>/?^&*",
}
dart_main_attributes_dict = {
# From python.py
"default": "null",
"digit_re": "",
"escape": "\\",
"highlight_digits": "true",
"ignore_case": "false",
"no_word_sep": "",
}
# Dictionary of attributes dictionaries for dart mode.
attributesDictDict = {
"dart_main": dart_main_attributes_dict,
}
# Keywords dict for dart_expression ruleset.
dart_main_keywords_dict = {
# keywords3 and keywords4.
"assertionerror": "keyword4",
"badnumberformatexception": "keyword4",
"bool": "keyword3",
"clock": "keyword4",
"closureargumentmismatchexception": "keyword4",
"collection": "keyword4",
"comparable": "keyword4",
"const": "keyword1",
"date": "keyword4",
"dispatcher": "keyword4",
"double": "keyword3",
"duration": "keyword4",
"emptyqueueexception": "keyword4",
"exception": "keyword4",
"expect": "keyword4",
"expectexception": "keyword4",
"fallthrougherror": "keyword4",
"false": "literal2",
"function": "keyword4",
"hashable": "keyword4",
"hashmap": "keyword4",
"hashset": "keyword4",
"illegalaccessexception": "keyword4",
"illegalargumentexception": "keyword4",
"illegaljsregexpexception": "keyword4",
"implements": "keyword1",
"indexoutofrangeexception": "keyword4",
"int": "keyword3",
"integerdivisionbyzeroexception": "keyword4",
"is": "keyword1",
"isolate": "keyword4",
"iterable": "keyword4",
"iterator": "keyword4",
"linkedhashmap": "keyword4",
"list": "keyword4",
"map": "keyword4",
"match": "keyword4",
"math": "keyword4",
"new": "keyword1",
"nomoreelementsexception": "keyword4",
"nosuchmethodexception": "keyword4",
"notimplementedexception": "keyword4",
"null": "literal2",
"nullpointerexception": "keyword4",
"num": "keyword3",
"object": "keyword4",
"objectnotclosureexception": "keyword4",
"outofmemoryexception": "keyword4",
"pattern": "keyword4",
"promise": "keyword4",
"proxy": "keyword4",
"queue": "keyword4",
"receiveport": "keyword4",
"regexp": "keyword4",
"sendport": "keyword4",
### "set": "keyword4",
"stackoverflowexception": "keyword4",
"stopwatch": "keyword4",
"string": "keyword4",
"stringbuffer": "keyword4",
"strings": "keyword4",
"super": "literal2",
"this": "literal2",
"timezone": "keyword4",
"true": "literal2",
"typeerror": "keyword4",
"unsupportedoperationexception": "keyword4",
"void": "keyword3",
"wrongargumentcountexception": "keyword4",
# keyword1
"abstract": "keyword1",
"assert": "keyword1",
"break": "keyword1",
"case": "keyword1",
"catch": "keyword1",
"class": "keyword1",
"continue": "keyword1",
"default": "keyword1",
"do": "keyword1",
"else": "keyword1",
"extends": "keyword1",
"factory": "keyword1",
"final": "keyword1",
"finally": "keyword1",
"for": "keyword1",
"get": "keyword1",
"if": "keyword1",
"import": "keyword1",
"in": "keyword1",
"interface": "keyword1",
"library": "keyword1",
"negate": "keyword1",
"operator": "keyword1",
"return": "keyword1",
"set": "keyword1",
"source": "keyword1",
"static": "keyword1",
"switch": "keyword1",
"throw": "keyword1",
"try": "keyword1",
"typedef": "keyword1",
"var": "keyword1",
"while": "keyword1",
}
# Dictionary of keywords dictionaries for dart mode.
keywordsDictDict = {
"dart_main": dart_main_keywords_dict,
}
# Rules for main ruleset.
def dart_rule2(colorer, s, i):
return colorer.match_span(s, i, kind="comment3", begin="/**", end="*/",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="",exclude_match=False,
no_escape=False, no_line_break=False, no_word_break=False)
def dart_rule3(colorer, s, i):
return colorer.match_span(s, i, kind="comment1", begin="/*", end="*/",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="",exclude_match=False,
no_escape=False, no_line_break=False, no_word_break=False)
def dart_rule4(colorer, s, i):
return colorer.match_span(s, i, kind="literal1", begin="@\"\"\"", end="\"\"\"",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="",exclude_match=False,
no_escape=False, no_line_break=False, no_word_break=False)
def dart_rule5(colorer, s, i):
return colorer.match_span(s, i, kind="literal1", begin="@'''", end="'''",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="",exclude_match=False,
no_escape=False, no_line_break=False, no_word_break=False)
def dart_rule6(colorer, s, i):
return colorer.match_span(s, i, kind="literal1", begin="@\"", end="\"",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="",exclude_match=False,
no_escape=False, no_line_break=True, no_word_break=False)
def dart_rule7(colorer, s, i):
return colorer.match_span(s, i, kind="literal1", begin="@'", end="'",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="",exclude_match=False,
no_escape=False, no_line_break=True, no_word_break=False)
def dart_rule8(colorer, s, i):
return colorer.match_span(s, i, kind="literal1", begin="\"\"\"", end="\"\"\"",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="dart::dart_literal1",exclude_match=False,
no_escape=False, no_line_break=False, no_word_break=False)
def dart_rule9(colorer, s, i):
return colorer.match_span(s, i, kind="literal1", begin="'''", end="'''",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="dart::dart_literal1",exclude_match=False,
no_escape=False, no_line_break=False, no_word_break=False)
def dart_rule10(colorer, s, i):
return colorer.match_span(s, i, kind="literal1", begin="\"", end="\"",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="dart::dart_literal1",exclude_match=False,
no_escape=False, no_line_break=True, no_word_break=False)
def dart_rule11(colorer, s, i):
return colorer.match_span(s, i, kind="literal1", begin="'", end="'",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="dart::dart_literal1",exclude_match=False,
no_escape=False, no_line_break=True, no_word_break=False)
def dart_rule12(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="=",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule13(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="!",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule14(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq=">=",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule15(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="<=",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule16(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="+",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule17(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="-",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule18(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="/",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule19(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="*",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule20(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq=">",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule21(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="<",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule22(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="%",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule23(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="&",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule24(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="|",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule25(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="^",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule26(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="<<",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule27(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq=">>>",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule28(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq=">>",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule29(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="~/",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule30(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq=".",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule31(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq=";",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule32(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="]",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule33(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="[",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule34(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="}",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule35(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="{",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
# def dart_rule36(colorer, s, i):
# return colorer.match_mark_previous(s, i, kind="function", pattern="(",
# at_line_start=False, at_whitespace_end=False, at_word_start=False, exclude_match=False)
def dart_rule37(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq=")",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule38(colorer, s, i):
return colorer.match_keywords(s, i)
# Rules formerly in expression ruleset.
def dart_rule39(colorer, s, i):
return colorer.match_seq(s, i, kind="comment2", seq="//-->",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule40(colorer, s, i):
return colorer.match_eol_span(s, i, kind="comment2", seq="//",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="", exclude_match=False)
def dart_rule41(colorer, s, i):
return colorer.match_eol_span(s, i, kind="keyword2", seq="#!",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="", exclude_match=False)
def dart_rule42(colorer, s, i):
return colorer.match_seq(s, i, kind="keyword2", seq="#library",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule43(colorer, s, i):
return colorer.match_seq(s, i, kind="keyword2", seq="#import",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule44(colorer, s, i):
return colorer.match_seq(s, i, kind="keyword2", seq="#source",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule45(colorer, s, i):
return colorer.match_seq(s, i, kind="keyword2", seq="#resource",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def dart_rule46(colorer, s, i):
return colorer.match_keywords(s, i)
# Rules dict for main ruleset.
rulesDict1 = {
"#": [dart_rule41,dart_rule42,dart_rule43,dart_rule44,dart_rule45,],
"@": [dart_rule4,dart_rule5,dart_rule6,dart_rule7,dart_rule38,], # Added.
"/": [dart_rule39,dart_rule40,
dart_rule2,dart_rule3,dart_rule18,], # Added.
"'": [dart_rule9,dart_rule11,], # Added.
'"': [dart_rule8,dart_rule10,], # Added.
# "@": [dart_rule46,],
# "0": [dart_rule46,],
# "1": [dart_rule46,],
# "2": [dart_rule46,],
# "3": [dart_rule46,],
# "4": [dart_rule46,],
# "5": [dart_rule46,],
# "6": [dart_rule46,],
# "7": [dart_rule46,],
# "8": [dart_rule46,],
# "9": [dart_rule46,],
"A": [dart_rule46,],
"B": [dart_rule46,],
"C": [dart_rule46,],
"D": [dart_rule46,],
"E": [dart_rule46,],
"F": [dart_rule46,],
"G": [dart_rule46,],
"H": [dart_rule46,],
"I": [dart_rule46,],
"J": [dart_rule46,],
"K": [dart_rule46,],
"L": [dart_rule46,],
"M": [dart_rule46,],
"N": [dart_rule46,],
"O": [dart_rule46,],
"P": [dart_rule46,],
"Q": [dart_rule46,],
"R": [dart_rule46,],
"S": [dart_rule46,],
"T": [dart_rule46,],
"U": [dart_rule46,],
"V": [dart_rule46,],
"W": [dart_rule46,],
"X": [dart_rule46,],
"Y": [dart_rule46,],
"Z": [dart_rule46,],
"a": [dart_rule46,],
"b": [dart_rule46,],
"c": [dart_rule46,],
"d": [dart_rule46,],
"e": [dart_rule46,],
"f": [dart_rule46,],
"g": [dart_rule46,],
"h": [dart_rule46,],
"i": [dart_rule46,],
"j": [dart_rule46,],
"k": [dart_rule46,],
"l": [dart_rule46,],
"m": [dart_rule46,],
"n": [dart_rule46,],
"o": [dart_rule46,],
"p": [dart_rule46,],
"q": [dart_rule46,],
"r": [dart_rule46,],
"s": [dart_rule46,],
"t": [dart_rule46,],
"u": [dart_rule46,],
"v": [dart_rule46,],
"w": [dart_rule46,],
"x": [dart_rule46,],
"y": [dart_rule46,],
"z": [dart_rule46,],
}
# x.rulesDictDict for dart mode.
rulesDictDict = {
"dart_main": rulesDict1,
}
# Import dict for dart mode.
importDict = {}
| properties = {'commentEnd': '*/', 'commentStart': '/*', 'electricKeys': ':', 'indentCloseBrackets': ']}', 'indentNextLine': '\\s*(((if|while)\\s*\\(|else\\s*|else\\s+if\\s*\\(|for\\s*\\(.*\\))[^{;]*)', 'indentOpenBrackets': '{[', 'lineComment': '//', 'unalignedCloseBrackets': ')', 'unalignedOpenBrackets': '(', 'unindentThisLine': '^.*(default:\\s*|case.*:.*)$', 'wordBreakChars': ',+-=<>/?^&*'}
dart_main_attributes_dict = {'default': 'null', 'digit_re': '', 'escape': '\\', 'highlight_digits': 'true', 'ignore_case': 'false', 'no_word_sep': ''}
attributes_dict_dict = {'dart_main': dart_main_attributes_dict}
dart_main_keywords_dict = {'assertionerror': 'keyword4', 'badnumberformatexception': 'keyword4', 'bool': 'keyword3', 'clock': 'keyword4', 'closureargumentmismatchexception': 'keyword4', 'collection': 'keyword4', 'comparable': 'keyword4', 'const': 'keyword1', 'date': 'keyword4', 'dispatcher': 'keyword4', 'double': 'keyword3', 'duration': 'keyword4', 'emptyqueueexception': 'keyword4', 'exception': 'keyword4', 'expect': 'keyword4', 'expectexception': 'keyword4', 'fallthrougherror': 'keyword4', 'false': 'literal2', 'function': 'keyword4', 'hashable': 'keyword4', 'hashmap': 'keyword4', 'hashset': 'keyword4', 'illegalaccessexception': 'keyword4', 'illegalargumentexception': 'keyword4', 'illegaljsregexpexception': 'keyword4', 'implements': 'keyword1', 'indexoutofrangeexception': 'keyword4', 'int': 'keyword3', 'integerdivisionbyzeroexception': 'keyword4', 'is': 'keyword1', 'isolate': 'keyword4', 'iterable': 'keyword4', 'iterator': 'keyword4', 'linkedhashmap': 'keyword4', 'list': 'keyword4', 'map': 'keyword4', 'match': 'keyword4', 'math': 'keyword4', 'new': 'keyword1', 'nomoreelementsexception': 'keyword4', 'nosuchmethodexception': 'keyword4', 'notimplementedexception': 'keyword4', 'null': 'literal2', 'nullpointerexception': 'keyword4', 'num': 'keyword3', 'object': 'keyword4', 'objectnotclosureexception': 'keyword4', 'outofmemoryexception': 'keyword4', 'pattern': 'keyword4', 'promise': 'keyword4', 'proxy': 'keyword4', 'queue': 'keyword4', 'receiveport': 'keyword4', 'regexp': 'keyword4', 'sendport': 'keyword4', 'stackoverflowexception': 'keyword4', 'stopwatch': 'keyword4', 'string': 'keyword4', 'stringbuffer': 'keyword4', 'strings': 'keyword4', 'super': 'literal2', 'this': 'literal2', 'timezone': 'keyword4', 'true': 'literal2', 'typeerror': 'keyword4', 'unsupportedoperationexception': 'keyword4', 'void': 'keyword3', 'wrongargumentcountexception': 'keyword4', 'abstract': 'keyword1', 'assert': 'keyword1', 'break': 'keyword1', 'case': 'keyword1', 'catch': 'keyword1', 'class': 'keyword1', 'continue': 'keyword1', 'default': 'keyword1', 'do': 'keyword1', 'else': 'keyword1', 'extends': 'keyword1', 'factory': 'keyword1', 'final': 'keyword1', 'finally': 'keyword1', 'for': 'keyword1', 'get': 'keyword1', 'if': 'keyword1', 'import': 'keyword1', 'in': 'keyword1', 'interface': 'keyword1', 'library': 'keyword1', 'negate': 'keyword1', 'operator': 'keyword1', 'return': 'keyword1', 'set': 'keyword1', 'source': 'keyword1', 'static': 'keyword1', 'switch': 'keyword1', 'throw': 'keyword1', 'try': 'keyword1', 'typedef': 'keyword1', 'var': 'keyword1', 'while': 'keyword1'}
keywords_dict_dict = {'dart_main': dart_main_keywords_dict}
def dart_rule2(colorer, s, i):
return colorer.match_span(s, i, kind='comment3', begin='/**', end='*/', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='', exclude_match=False, no_escape=False, no_line_break=False, no_word_break=False)
def dart_rule3(colorer, s, i):
return colorer.match_span(s, i, kind='comment1', begin='/*', end='*/', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='', exclude_match=False, no_escape=False, no_line_break=False, no_word_break=False)
def dart_rule4(colorer, s, i):
return colorer.match_span(s, i, kind='literal1', begin='@"""', end='"""', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='', exclude_match=False, no_escape=False, no_line_break=False, no_word_break=False)
def dart_rule5(colorer, s, i):
return colorer.match_span(s, i, kind='literal1', begin="@'''", end="'''", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='', exclude_match=False, no_escape=False, no_line_break=False, no_word_break=False)
def dart_rule6(colorer, s, i):
return colorer.match_span(s, i, kind='literal1', begin='@"', end='"', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='', exclude_match=False, no_escape=False, no_line_break=True, no_word_break=False)
def dart_rule7(colorer, s, i):
return colorer.match_span(s, i, kind='literal1', begin="@'", end="'", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='', exclude_match=False, no_escape=False, no_line_break=True, no_word_break=False)
def dart_rule8(colorer, s, i):
return colorer.match_span(s, i, kind='literal1', begin='"""', end='"""', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='dart::dart_literal1', exclude_match=False, no_escape=False, no_line_break=False, no_word_break=False)
def dart_rule9(colorer, s, i):
return colorer.match_span(s, i, kind='literal1', begin="'''", end="'''", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='dart::dart_literal1', exclude_match=False, no_escape=False, no_line_break=False, no_word_break=False)
def dart_rule10(colorer, s, i):
return colorer.match_span(s, i, kind='literal1', begin='"', end='"', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='dart::dart_literal1', exclude_match=False, no_escape=False, no_line_break=True, no_word_break=False)
def dart_rule11(colorer, s, i):
return colorer.match_span(s, i, kind='literal1', begin="'", end="'", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='dart::dart_literal1', exclude_match=False, no_escape=False, no_line_break=True, no_word_break=False)
def dart_rule12(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='=', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule13(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='!', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule14(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='>=', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule15(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='<=', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule16(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='+', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule17(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='-', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule18(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='/', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule19(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='*', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule20(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='>', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule21(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='<', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule22(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='%', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule23(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='&', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule24(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='|', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule25(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='^', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule26(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='<<', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule27(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='>>>', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule28(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='>>', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule29(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='~/', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule30(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='.', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule31(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq=';', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule32(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq=']', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule33(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='[', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule34(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='}', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule35(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq='{', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule37(colorer, s, i):
return colorer.match_seq(s, i, kind='operator', seq=')', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule38(colorer, s, i):
return colorer.match_keywords(s, i)
def dart_rule39(colorer, s, i):
return colorer.match_seq(s, i, kind='comment2', seq='//-->', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule40(colorer, s, i):
return colorer.match_eol_span(s, i, kind='comment2', seq='//', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='', exclude_match=False)
def dart_rule41(colorer, s, i):
return colorer.match_eol_span(s, i, kind='keyword2', seq='#!', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='', exclude_match=False)
def dart_rule42(colorer, s, i):
return colorer.match_seq(s, i, kind='keyword2', seq='#library', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule43(colorer, s, i):
return colorer.match_seq(s, i, kind='keyword2', seq='#import', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule44(colorer, s, i):
return colorer.match_seq(s, i, kind='keyword2', seq='#source', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule45(colorer, s, i):
return colorer.match_seq(s, i, kind='keyword2', seq='#resource', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='')
def dart_rule46(colorer, s, i):
return colorer.match_keywords(s, i)
rules_dict1 = {'#': [dart_rule41, dart_rule42, dart_rule43, dart_rule44, dart_rule45], '@': [dart_rule4, dart_rule5, dart_rule6, dart_rule7, dart_rule38], '/': [dart_rule39, dart_rule40, dart_rule2, dart_rule3, dart_rule18], "'": [dart_rule9, dart_rule11], '"': [dart_rule8, dart_rule10], 'A': [dart_rule46], 'B': [dart_rule46], 'C': [dart_rule46], 'D': [dart_rule46], 'E': [dart_rule46], 'F': [dart_rule46], 'G': [dart_rule46], 'H': [dart_rule46], 'I': [dart_rule46], 'J': [dart_rule46], 'K': [dart_rule46], 'L': [dart_rule46], 'M': [dart_rule46], 'N': [dart_rule46], 'O': [dart_rule46], 'P': [dart_rule46], 'Q': [dart_rule46], 'R': [dart_rule46], 'S': [dart_rule46], 'T': [dart_rule46], 'U': [dart_rule46], 'V': [dart_rule46], 'W': [dart_rule46], 'X': [dart_rule46], 'Y': [dart_rule46], 'Z': [dart_rule46], 'a': [dart_rule46], 'b': [dart_rule46], 'c': [dart_rule46], 'd': [dart_rule46], 'e': [dart_rule46], 'f': [dart_rule46], 'g': [dart_rule46], 'h': [dart_rule46], 'i': [dart_rule46], 'j': [dart_rule46], 'k': [dart_rule46], 'l': [dart_rule46], 'm': [dart_rule46], 'n': [dart_rule46], 'o': [dart_rule46], 'p': [dart_rule46], 'q': [dart_rule46], 'r': [dart_rule46], 's': [dart_rule46], 't': [dart_rule46], 'u': [dart_rule46], 'v': [dart_rule46], 'w': [dart_rule46], 'x': [dart_rule46], 'y': [dart_rule46], 'z': [dart_rule46]}
rules_dict_dict = {'dart_main': rulesDict1}
import_dict = {} |
ACCOUNT_ID = "1234567890"
def parameter_arn(region, parameter_name):
if parameter_name[0] == "/":
parameter_name = parameter_name[1:]
return "arn:aws:ssm:{0}:{1}:parameter/{2}".format(
region, ACCOUNT_ID, parameter_name
)
| account_id = '1234567890'
def parameter_arn(region, parameter_name):
if parameter_name[0] == '/':
parameter_name = parameter_name[1:]
return 'arn:aws:ssm:{0}:{1}:parameter/{2}'.format(region, ACCOUNT_ID, parameter_name) |
#!/bin/python
# Enter your code here. Read input from STDIN. Print output to STDOUT
N = int(raw_input())
n= N
w = 'Weird'
nw = 'Not Weird'
if n % 2 == 1:
print(w)
elif n % 2 == 0 and (n>=2 and n<5):
print(nw)
elif n % 2 == 0 and (n>=6 and n<=20):
print(w)
elif n % 2 == 0 and (n>20):
print(nw)
| n = int(raw_input())
n = N
w = 'Weird'
nw = 'Not Weird'
if n % 2 == 1:
print(w)
elif n % 2 == 0 and (n >= 2 and n < 5):
print(nw)
elif n % 2 == 0 and (n >= 6 and n <= 20):
print(w)
elif n % 2 == 0 and n > 20:
print(nw) |
# Sage version information for Python scripts
# This file is auto-generated by the sage-update-version script, do not edit!
version = '9.3.rc0'
date = '2021-03-23'
banner = 'SageMath version 9.3.rc0, Release Date: 2021-03-23'
| version = '9.3.rc0'
date = '2021-03-23'
banner = 'SageMath version 9.3.rc0, Release Date: 2021-03-23' |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __str__(self):
return str(self.val)
def print_list(head: ListNode):
cur = head
while cur is not None:
print(cur.val, end=' ')
cur = cur.next
if cur is not None:
print('->', end=' ')
print()
def build_list(values):
head = None
prev = None
for i, v in enumerate(values):
if i == 0:
head = ListNode(v)
prev = head
continue
cur = ListNode(v)
prev.next = cur
prev = cur
return head
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
cur = head
next_node = head.next
cur.next = next_node.next
next_node.next = cur
cur.next = Solution().swapPairs(cur.next)
return next_node
# tests
head = build_list([1, 2, 3, 4, 5])
print_list(head)
head = Solution().swapPairs(head)
print_list(head)
head = build_list([])
print_list(head)
head = Solution().swapPairs(head)
print_list(head)
head = build_list([1])
print_list(head)
head = Solution().swapPairs(head)
print_list(head)
| class Listnode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __str__(self):
return str(self.val)
def print_list(head: ListNode):
cur = head
while cur is not None:
print(cur.val, end=' ')
cur = cur.next
if cur is not None:
print('->', end=' ')
print()
def build_list(values):
head = None
prev = None
for (i, v) in enumerate(values):
if i == 0:
head = list_node(v)
prev = head
continue
cur = list_node(v)
prev.next = cur
prev = cur
return head
class Solution:
def swap_pairs(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
cur = head
next_node = head.next
cur.next = next_node.next
next_node.next = cur
cur.next = solution().swapPairs(cur.next)
return next_node
head = build_list([1, 2, 3, 4, 5])
print_list(head)
head = solution().swapPairs(head)
print_list(head)
head = build_list([])
print_list(head)
head = solution().swapPairs(head)
print_list(head)
head = build_list([1])
print_list(head)
head = solution().swapPairs(head)
print_list(head) |
REDFIN_TABLE_SCHEMA = {
'SCHEMA': {
'SALE_TYPE': 'VARCHAR(50)',
'SOLD_DATE': 'DATE',
'PROPERTY_TYPE': 'VARCHAR(50)',
'ADDRESS': 'VARCHAR(100) NOT NULL',
'CITY': 'VARCHAR(50) NOT NULL',
'STATE': 'VARCHAR(50) NOT NULL',
'ZIPCODE': 'BIGINT',
'PRICE': 'BIGINT',
'BEDS': 'BIGINT',
'BATHS': 'DOUBLE PRECISION',
'SQFT': 'BIGINT',
'LOT_SIZE': 'BIGINT',
'YEAR_BUILT': 'BIGINT',
'DAYS_ON_MARKET': 'BIGINT',
'DOLLAR_PER_SQFT': 'BIGINT',
'HOA_MONTHLY': 'BIGINT',
'STATUS': 'VARCHAR(50)',
'URL': 'VARCHAR(100)',
'MLS_NUM': 'VARCHAR(50)',
'LATITUDE': 'DOUBLE PRECISION',
'LONGITUDE': 'DOUBLE PRECISION'},
'PRIMARY_KEY': 'ADDRESS, CITY, STATE, ZIPCODE',
'POSITION': ['SALE_TYPE', 'SOLD_DATE', 'PROPERTY_TYPE', 'ADDRESS', 'CITY', 'STATE', 'ZIPCODE', 'PRICE', 'BEDS', 'BATHS', 'SQFT', 'LOT_SIZE', 'YEAR_BUILT', 'DAYS_ON_MARKET', 'DOLLAR_PER_SQFT', 'HOA_MONTHLY', 'STATUS', 'URL', 'MLS_NUM', 'LATITUDE', 'LONGITUDE']
}
| redfin_table_schema = {'SCHEMA': {'SALE_TYPE': 'VARCHAR(50)', 'SOLD_DATE': 'DATE', 'PROPERTY_TYPE': 'VARCHAR(50)', 'ADDRESS': 'VARCHAR(100) NOT NULL', 'CITY': 'VARCHAR(50) NOT NULL', 'STATE': 'VARCHAR(50) NOT NULL', 'ZIPCODE': 'BIGINT', 'PRICE': 'BIGINT', 'BEDS': 'BIGINT', 'BATHS': 'DOUBLE PRECISION', 'SQFT': 'BIGINT', 'LOT_SIZE': 'BIGINT', 'YEAR_BUILT': 'BIGINT', 'DAYS_ON_MARKET': 'BIGINT', 'DOLLAR_PER_SQFT': 'BIGINT', 'HOA_MONTHLY': 'BIGINT', 'STATUS': 'VARCHAR(50)', 'URL': 'VARCHAR(100)', 'MLS_NUM': 'VARCHAR(50)', 'LATITUDE': 'DOUBLE PRECISION', 'LONGITUDE': 'DOUBLE PRECISION'}, 'PRIMARY_KEY': 'ADDRESS, CITY, STATE, ZIPCODE', 'POSITION': ['SALE_TYPE', 'SOLD_DATE', 'PROPERTY_TYPE', 'ADDRESS', 'CITY', 'STATE', 'ZIPCODE', 'PRICE', 'BEDS', 'BATHS', 'SQFT', 'LOT_SIZE', 'YEAR_BUILT', 'DAYS_ON_MARKET', 'DOLLAR_PER_SQFT', 'HOA_MONTHLY', 'STATUS', 'URL', 'MLS_NUM', 'LATITUDE', 'LONGITUDE']} |
message = 'My name is ' 'Tom'
print(message)
| message = 'My name is Tom'
print(message) |
list1 = ["apple", "banana", "cherry"]
list2 = list1.copy()
print(list2)
list3 = list(list1)
print(list3)
list4 = list('T am a list')
print(list4)
# join 2 lists
list5 = list1 + list4
print(list5)
for x in list4:
list1.append(x)
print(list1)
list2.extend(list4)
print(list2)
# list constructor
list7 = list(("apple", "banana", "cherry")) # note the double round-brackets
print(list7)
print(list4.count(' '))
# reverse list
list7.reverse()
print(list7)
# sort list
cars = ['Ford', 'BMW', 'Volvo', 'Kia', 'Hyundai', 'Toyota', 'Honda', 'Mazda', 'Mitsubishi', 'Nissan']
cars.sort()
print(cars)
cars.sort(key=lambda e: len(e), reverse=True)
print(cars)
| list1 = ['apple', 'banana', 'cherry']
list2 = list1.copy()
print(list2)
list3 = list(list1)
print(list3)
list4 = list('T am a list')
print(list4)
list5 = list1 + list4
print(list5)
for x in list4:
list1.append(x)
print(list1)
list2.extend(list4)
print(list2)
list7 = list(('apple', 'banana', 'cherry'))
print(list7)
print(list4.count(' '))
list7.reverse()
print(list7)
cars = ['Ford', 'BMW', 'Volvo', 'Kia', 'Hyundai', 'Toyota', 'Honda', 'Mazda', 'Mitsubishi', 'Nissan']
cars.sort()
print(cars)
cars.sort(key=lambda e: len(e), reverse=True)
print(cars) |
"""
URLify: Write a method to replace all spaces in a string with '%20'. You may assume that the string
has sufficient space at the end to hold the additional characters, and that you are given the "true"
length of the string. (Note: If implementing in Java, please use a character array so that you can
perform this operation in place.)
EXAMPLE
Input: "Mr 3ohn Smith"
Output: "Mr%203ohn%20Smith"
"""
def urlify(usr_str):
return str(usr_str).replace(' ', '%20')
# inp_str = input("Enter String \n")
print(urlify(input("Enter String \n")))
| """
URLify: Write a method to replace all spaces in a string with '%20'. You may assume that the string
has sufficient space at the end to hold the additional characters, and that you are given the "true"
length of the string. (Note: If implementing in Java, please use a character array so that you can
perform this operation in place.)
EXAMPLE
Input: "Mr 3ohn Smith"
Output: "Mr%203ohn%20Smith"
"""
def urlify(usr_str):
return str(usr_str).replace(' ', '%20')
print(urlify(input('Enter String \n'))) |
r"""
``scanInfo`` --- Scan information
====================================
.. code-block:: python
import gempython.vfatqc.utils.scanInfo
Documentation
-------------
"""
#default values for the algorithm to update the trim values in the iterative trimmer
sigmaOffsetDefault=0
highNoiseCutDefault=63
highTrimCutoffDefault=50
highTrimWeightDefault=1.5
| """
``scanInfo`` --- Scan information
====================================
.. code-block:: python
import gempython.vfatqc.utils.scanInfo
Documentation
-------------
"""
sigma_offset_default = 0
high_noise_cut_default = 63
high_trim_cutoff_default = 50
high_trim_weight_default = 1.5 |
class SessionStorage:
"""Class to save data into session section organized by section_id."""
def __init__(self, session):
self.session = session
def set(self, section_id, key, value):
"""Set data to session section."""
session_part = self.session.get(section_id, {})
session_part[key] = value
self.session[section_id] = session_part
def get(self, section_id, key, default=None):
"""Get data from session section."""
session_part = self.session.get(section_id, {})
return session_part.get(key, default)
def clear(self, section_id):
"""Clear session section."""
try:
del self.session[section_id]
self.session.modified = True
except KeyError:
pass # It is ok, value is already cleared.
| class Sessionstorage:
"""Class to save data into session section organized by section_id."""
def __init__(self, session):
self.session = session
def set(self, section_id, key, value):
"""Set data to session section."""
session_part = self.session.get(section_id, {})
session_part[key] = value
self.session[section_id] = session_part
def get(self, section_id, key, default=None):
"""Get data from session section."""
session_part = self.session.get(section_id, {})
return session_part.get(key, default)
def clear(self, section_id):
"""Clear session section."""
try:
del self.session[section_id]
self.session.modified = True
except KeyError:
pass |
_MODELS = dict()
def register(fn):
global _MODELS
_MODELS[fn.__name__] = fn
return fn
def get_model(args=None):
if args.model is None:
return _MODELS
return _MODELS[args.model](args.num_classes)
| _models = dict()
def register(fn):
global _MODELS
_MODELS[fn.__name__] = fn
return fn
def get_model(args=None):
if args.model is None:
return _MODELS
return _MODELS[args.model](args.num_classes) |
Izhikevich = Neuron(
parameters= {
'a': Array(value=0.02, dtype=np.float32),
'b': Array(value=0.2),
'c': Value(value=-65.),
'd': Value(value=-2.),
'VT': Value(value=30.),
},
equations = {
'v': Array(eq="dv/dt = 0.04 * v^2 + 5.0 * v + 140.0 - u + I + ge - gi", value=0.0, method='midpoint'),
'u': Array(
eq="du/dt = a * (b * v - u)",
value=0.0,
method='midpoint',
min=0.0,
max=100.,
),
'ge': Array(eq=None, value=0.0, during_refractory=False),
'gi': Array(eq="tau*dgi/dt=-gi", during_refractory=False),
},
update= ['v', 'u'],
update2 = ['v', 'u', 'ge', 'gi'],
spike = "v > VT",
reset = ["v = c", "u += d"],
refractory = None, # the default, or 5.0, or "tau_ref",
name = "Izhikevich",
description = """
Some text describing what the neuron does,
equations that can be parsed for the report, etc.
"""
)
default_spiking_synapse = Synapse(
psp = "w",
operator = "sum" # optional
)
STDP = Synapse(
parameters = {
'tau_plus': Value(value=20.),
'tau_minus': Array(value=20.), # one per post neuron
'tau': Matrix(value = 10.0) # one per synapse
},
equations = {
'x': Matrix(eq="tau_plus * dx/dt = -x", method="event-driven"),
'y': Matrix(eq="tau_minus * dy/dt = -y", method="event-driven"),
},
transmit = "w",
on_pre = [
"x +=1 ",
"w +=y ",
],
on_post = [
"y +=1",
"w -=x",
],
name = "STDP",
description= """
Spike timing dependent plasticity
"""
)
# Create the network
net = Network(dt=0.1)
# Add a population
pop = net.add(10, Izhikevich)
print(pop.a)
pop.a = np.linspace(1.0, 10.0, pop.size)
print(pop.a)
# Connect the population with itself
proj = net.connect(pre=pop, post=pop, target=pop.ge, synapse=default_spiking_synapse)
proj.fill(w=1.0, d=5.0) # default is a single weight for the whole population, not learnable
proj.fill(w=1.0, d=5.0, connector=Dense(self_connection=False), format='lil')
proj.fill(w=Uniform(0.0, 1.0), d=5.0, connector=Sparse(p=0.1))
proj.fill(w=1.0, d=5.0, connector=One2One())
proj.fill(w=np.ones((pop.size, pop.size)), d=0.0)
# Monitor
net.monitor([pop.v, proj.w])
# Compile the network
net.compile(backend='openmp') # single, openmp, mpi, cuda, etc
# Simulate
net.simulate(1000, monitor=True)
# Retrieve the simulated data
data = net.recorded() | izhikevich = neuron(parameters={'a': array(value=0.02, dtype=np.float32), 'b': array(value=0.2), 'c': value(value=-65.0), 'd': value(value=-2.0), 'VT': value(value=30.0)}, equations={'v': array(eq='dv/dt = 0.04 * v^2 + 5.0 * v + 140.0 - u + I + ge - gi', value=0.0, method='midpoint'), 'u': array(eq='du/dt = a * (b * v - u)', value=0.0, method='midpoint', min=0.0, max=100.0), 'ge': array(eq=None, value=0.0, during_refractory=False), 'gi': array(eq='tau*dgi/dt=-gi', during_refractory=False)}, update=['v', 'u'], update2=['v', 'u', 'ge', 'gi'], spike='v > VT', reset=['v = c', 'u += d'], refractory=None, name='Izhikevich', description='\n Some text describing what the neuron does, \n equations that can be parsed for the report, etc.\n ')
default_spiking_synapse = synapse(psp='w', operator='sum')
stdp = synapse(parameters={'tau_plus': value(value=20.0), 'tau_minus': array(value=20.0), 'tau': matrix(value=10.0)}, equations={'x': matrix(eq='tau_plus * dx/dt = -x', method='event-driven'), 'y': matrix(eq='tau_minus * dy/dt = -y', method='event-driven')}, transmit='w', on_pre=['x +=1 ', 'w +=y '], on_post=['y +=1', 'w -=x'], name='STDP', description='\n Spike timing dependent plasticity\n ')
net = network(dt=0.1)
pop = net.add(10, Izhikevich)
print(pop.a)
pop.a = np.linspace(1.0, 10.0, pop.size)
print(pop.a)
proj = net.connect(pre=pop, post=pop, target=pop.ge, synapse=default_spiking_synapse)
proj.fill(w=1.0, d=5.0)
proj.fill(w=1.0, d=5.0, connector=dense(self_connection=False), format='lil')
proj.fill(w=uniform(0.0, 1.0), d=5.0, connector=sparse(p=0.1))
proj.fill(w=1.0, d=5.0, connector=one2_one())
proj.fill(w=np.ones((pop.size, pop.size)), d=0.0)
net.monitor([pop.v, proj.w])
net.compile(backend='openmp')
net.simulate(1000, monitor=True)
data = net.recorded() |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Gammapy integration and system tests.
This package can be used for tests that involved several
Gammapy sub-packages, or that don't fit anywhere else.
"""
| """Gammapy integration and system tests.
This package can be used for tests that involved several
Gammapy sub-packages, or that don't fit anywhere else.
""" |
# class SVNRepo:
# @classmethod
# def isBadVersion(cls, id)
# # Run unit tests to check whether verison `id` is a bad version
# # return true if unit tests passed else false.
# You can use SVNRepo.isBadVersion(10) to check whether version 10 is a
# bad version.
class Solution:
"""
@param n: An integer
@return: An integer which is the first bad version.
"""
def findFirstBadVersion(self, n):
# write your code here
start, end = 1, n
while start + 1 < end:
mid = start + (end - start) // 2
if SVNRepo.isBadVersion(mid):
end = mid
else:
start = mid
if SVNRepo.isBadVersion(start):
return start
return end
| class Solution:
"""
@param n: An integer
@return: An integer which is the first bad version.
"""
def find_first_bad_version(self, n):
(start, end) = (1, n)
while start + 1 < end:
mid = start + (end - start) // 2
if SVNRepo.isBadVersion(mid):
end = mid
else:
start = mid
if SVNRepo.isBadVersion(start):
return start
return end |
#Lists Challenge 9: Basketball Roster Program
print("Welcome to the Basketball Roster Program")
#Get user input and define our roster
roster = []
player = input("\nWho is your point guard: ").title()
roster.append(player)
player = input("Who is your shooting guard: ").title()
roster.append(player)
player = input("Who is your small forward: ").title()
roster.append(player)
player = input("Who is your power forward: ").title()
roster.append(player)
player = input("Who is your center: ").title()
roster.append(player)
#Display roster
print("\n\tYour starting 5 for the upcoming basketball season")
print("\t\tPoint Guard:\t\t" + roster[0])
print("\t\tShooting Guard:\t\t" + roster[1])
print("\t\tSmall Forward:\t\t" + roster[2])
print("\t\tPower Forward:\t\t" + roster[3])
print("\t\tCenter:\t\t\t" + roster[4])
#Remove an injured player
injured_player = roster.pop(2)
print("\nOh no, " + injured_player + " is injured.")
roster_length = len(roster)
print("Your roster only has " + str(roster_length) + " players.")
#Add a new player
added_player = input("Who will take " + injured_player + "'s spot: ").title()
roster.insert(2, added_player)
#Display roster
print("\n\tYour starting 5 for the upcoming basketball season")
print("\t\tPoint Guard:\t\t" + roster[0])
print("\t\tShooting Guard:\t\t" + roster[1])
print("\t\tSmall Forward:\t\t" + roster[2])
print("\t\tPower Forward:\t\t" + roster[3])
print("\t\tCenter:\t\t\t" + roster[4])
print("\nGood luck " + roster[2] + " you will do great!")
roster_length = len(roster)
print("Your roster now has " + str(roster_length) + " players.")
| print('Welcome to the Basketball Roster Program')
roster = []
player = input('\nWho is your point guard: ').title()
roster.append(player)
player = input('Who is your shooting guard: ').title()
roster.append(player)
player = input('Who is your small forward: ').title()
roster.append(player)
player = input('Who is your power forward: ').title()
roster.append(player)
player = input('Who is your center: ').title()
roster.append(player)
print('\n\tYour starting 5 for the upcoming basketball season')
print('\t\tPoint Guard:\t\t' + roster[0])
print('\t\tShooting Guard:\t\t' + roster[1])
print('\t\tSmall Forward:\t\t' + roster[2])
print('\t\tPower Forward:\t\t' + roster[3])
print('\t\tCenter:\t\t\t' + roster[4])
injured_player = roster.pop(2)
print('\nOh no, ' + injured_player + ' is injured.')
roster_length = len(roster)
print('Your roster only has ' + str(roster_length) + ' players.')
added_player = input('Who will take ' + injured_player + "'s spot: ").title()
roster.insert(2, added_player)
print('\n\tYour starting 5 for the upcoming basketball season')
print('\t\tPoint Guard:\t\t' + roster[0])
print('\t\tShooting Guard:\t\t' + roster[1])
print('\t\tSmall Forward:\t\t' + roster[2])
print('\t\tPower Forward:\t\t' + roster[3])
print('\t\tCenter:\t\t\t' + roster[4])
print('\nGood luck ' + roster[2] + ' you will do great!')
roster_length = len(roster)
print('Your roster now has ' + str(roster_length) + ' players.') |
# Helper merge sort function
def mergeSort(arr):
# Clone the array for the merge later
arrClone = arr.clone()
mergeSortAux(arr, arrClone, 0, len(arr) - 1)
# Actual merge sort
def mergeSortAux(arr, arrClone, low, high):
if low < high:
mid = (low + high) / 2
# Sort left
mergeSortAux(arr, arrClone, low, mid)
# Sort right
mergeSortAux(arr, arrClone, mid + 1, high)
# Merge
merge(arr, arrClone, low, mid, high)
# Merge definition that sorts two sub arrays
def merge(arr, arrClone, low, mid, high):
i = low
j = mid + 1
# Copy the clone array parts over
for k in range(low, high):
arrClone[k] = arr[k]
for k in range(low, high):
if i > mid:
arr[k] = arrClone[j]
j += 1
elif j > high:
arr[k] = arrClone[i]
i += 1
elif arrClone[i] > arrClone[j]:
arr[k] = arrClone[j]
j += 1
else:
arr[k] = arrClone[i]
i += 1 | def merge_sort(arr):
arr_clone = arr.clone()
merge_sort_aux(arr, arrClone, 0, len(arr) - 1)
def merge_sort_aux(arr, arrClone, low, high):
if low < high:
mid = (low + high) / 2
merge_sort_aux(arr, arrClone, low, mid)
merge_sort_aux(arr, arrClone, mid + 1, high)
merge(arr, arrClone, low, mid, high)
def merge(arr, arrClone, low, mid, high):
i = low
j = mid + 1
for k in range(low, high):
arrClone[k] = arr[k]
for k in range(low, high):
if i > mid:
arr[k] = arrClone[j]
j += 1
elif j > high:
arr[k] = arrClone[i]
i += 1
elif arrClone[i] > arrClone[j]:
arr[k] = arrClone[j]
j += 1
else:
arr[k] = arrClone[i]
i += 1 |
"""
Exceptions
"""
class SubFrameError(Exception):
"""General error."""
pass
| """
Exceptions
"""
class Subframeerror(Exception):
"""General error."""
pass |
# You can comment by putting # in front of a text.
#First off we will start off with the humble while loop.
#Now notice the syntax: first we declare our variable,
#while condition is followed with a colon,
#in order to concenate a string with a number
#we must turn it into a string as well.
#Finally don't forget the incremental counter which will allow us
#to actually exit the file!!!!
n = 0
while n <= 5:
print ("While is now " + str(n))
n = n+1
#Now we will move on to the for loop.
#range will give us a collection of numbers. For now, the old fella
#will explain the real things later on.
#range syntax: range(start, stop, step)
for n in range(5):
print (n)
mySum = 1
for i in range(1, 12, 1):
print("i is now " + str(i))
if i == 11:
print("Oh snap we are now over 11!")
break
#Note that it will always stop one step before the stop value in the range.
#Also check this little loop out.
varA = 200
varB = 100
if type(varA) == str or type(varB) == str:
print("string involved")
elif varA > varB:
print("bigger")
elif varA == varB:
print("equal")
else:
print("smaller")
#Checkin types, elif statements, elses... What else do you need?
#This little snippet is a pretty cool one.
#You can find the sum of X and all the numbers before X.
#As seen on MIT6.001X Week 1.2 question 3 in while loops!
n = 0
X = 10
while X > 0:
n += X
X -= 1
print (n)
#Now how do the same in a for loop??
n = 0
X = 10
for i in range(X, 0, -1):
n += i
print (n)
#Wew so hard!
| n = 0
while n <= 5:
print('While is now ' + str(n))
n = n + 1
for n in range(5):
print(n)
my_sum = 1
for i in range(1, 12, 1):
print('i is now ' + str(i))
if i == 11:
print('Oh snap we are now over 11!')
break
var_a = 200
var_b = 100
if type(varA) == str or type(varB) == str:
print('string involved')
elif varA > varB:
print('bigger')
elif varA == varB:
print('equal')
else:
print('smaller')
n = 0
x = 10
while X > 0:
n += X
x -= 1
print(n)
n = 0
x = 10
for i in range(X, 0, -1):
n += i
print(n) |
class DailySchedule:
def __init__(self, day_number: int, day_off: bool = False):
self.day_number = day_number
self.day_off = day_off
self.lessons: list[tuple[str, str, str]] = [] | class Dailyschedule:
def __init__(self, day_number: int, day_off: bool=False):
self.day_number = day_number
self.day_off = day_off
self.lessons: list[tuple[str, str, str]] = [] |
class SpaceSequenceEditor:
display_channel = None
display_mode = None
draw_overexposed = None
grease_pencil = None
overlay_type = None
preview_channels = None
proxy_render_size = None
show_backdrop = None
show_frame_indicator = None
show_frames = None
show_grease_pencil = None
show_metadata = None
show_safe_areas = None
show_safe_center = None
show_seconds = None
show_separate_color = None
show_strip_offset = None
use_marker_sync = None
view_type = None
waveform_draw_type = None
def draw_handler_add(self):
pass
def draw_handler_remove(self):
pass
| class Spacesequenceeditor:
display_channel = None
display_mode = None
draw_overexposed = None
grease_pencil = None
overlay_type = None
preview_channels = None
proxy_render_size = None
show_backdrop = None
show_frame_indicator = None
show_frames = None
show_grease_pencil = None
show_metadata = None
show_safe_areas = None
show_safe_center = None
show_seconds = None
show_separate_color = None
show_strip_offset = None
use_marker_sync = None
view_type = None
waveform_draw_type = None
def draw_handler_add(self):
pass
def draw_handler_remove(self):
pass |
# Write for loops that iterate over the elements of a list without the use of the range
# function for the following tasks.
# c. Counting how many elements in a list are negative.
list = [ -5, 10, 15, -20, -2, 0, -8, 94 ]
numNegativeElements = 0
for item in list:
if item < 0:
numNegativeElements += 1
print("Number of negative elements:", numNegativeElements) | list = [-5, 10, 15, -20, -2, 0, -8, 94]
num_negative_elements = 0
for item in list:
if item < 0:
num_negative_elements += 1
print('Number of negative elements:', numNegativeElements) |
# Letter Phone
# https://www.interviewbit.com/problems/letter-phone/
#
# Given a digit string, return all possible letter combinations that the number could represent.
#
# A mapping of digit to letters (just like on the telephone buttons) is given below.
#
# The digit 0 maps to 0 itself.
# The digit 1 maps to 1 itself.
#
# Input: Digit string "23"
# Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
#
# Make sure the returned strings are lexicographically sorted.
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class Solution:
MAP = {
'0': '0',
'1': '1',
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz',
}
def _letterCombinations(self, i, A, sub):
if(i == len(A) - 1):
return [sub + char for char in Solution.MAP[A[i]]]
res = list()
for char in Solution.MAP[A[i]]:
res.extend(self._letterCombinations(i + 1, A, sub + char))
return res
# @param A : string
# @return a list of strings
def letterCombinations(self, A):
return self._letterCombinations(0, A, '')
| class Solution:
map = {'0': '0', '1': '1', '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
def _letter_combinations(self, i, A, sub):
if i == len(A) - 1:
return [sub + char for char in Solution.MAP[A[i]]]
res = list()
for char in Solution.MAP[A[i]]:
res.extend(self._letterCombinations(i + 1, A, sub + char))
return res
def letter_combinations(self, A):
return self._letterCombinations(0, A, '') |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def test_install_extension(lib):
lib.cmd('extension install hello')
lib.cmd('hello')
def test_install_extension_with_github_syntax(lib):
lib.cmd('extension install clk-project/hello')
lib.cmd('hello')
def test_update_extension(lib):
lib.cmd('extension install hello')
lib.cmd('extension update hello')
lib.cmd('hello --update-extension')
def test_copy_extension(lib):
lib.cmd('extension create someext')
lib.cmd('parameter --global-someext set echo test')
assert lib.cmd('echo') == 'test'
lib.cmd('extension disable someext')
assert lib.cmd('echo') == ''
lib.cmd('extension copy someext someext2')
assert lib.cmd('echo') == 'test'
lib.cmd('extension disable someext2')
assert lib.cmd('echo') == ''
def test_move_extension(lib):
lib.cmd('extension create someext')
lib.cmd('parameter --global-someext set echo test')
assert lib.cmd('echo') == 'test'
lib.cmd('extension disable someext')
assert lib.cmd('echo') == ''
lib.cmd('extension rename someext someext2')
assert lib.cmd('echo') == 'test'
lib.cmd('extension disable someext2')
assert lib.cmd('echo') == ''
lib.cmd('extension enable someext')
assert lib.cmd('echo') == ''
| def test_install_extension(lib):
lib.cmd('extension install hello')
lib.cmd('hello')
def test_install_extension_with_github_syntax(lib):
lib.cmd('extension install clk-project/hello')
lib.cmd('hello')
def test_update_extension(lib):
lib.cmd('extension install hello')
lib.cmd('extension update hello')
lib.cmd('hello --update-extension')
def test_copy_extension(lib):
lib.cmd('extension create someext')
lib.cmd('parameter --global-someext set echo test')
assert lib.cmd('echo') == 'test'
lib.cmd('extension disable someext')
assert lib.cmd('echo') == ''
lib.cmd('extension copy someext someext2')
assert lib.cmd('echo') == 'test'
lib.cmd('extension disable someext2')
assert lib.cmd('echo') == ''
def test_move_extension(lib):
lib.cmd('extension create someext')
lib.cmd('parameter --global-someext set echo test')
assert lib.cmd('echo') == 'test'
lib.cmd('extension disable someext')
assert lib.cmd('echo') == ''
lib.cmd('extension rename someext someext2')
assert lib.cmd('echo') == 'test'
lib.cmd('extension disable someext2')
assert lib.cmd('echo') == ''
lib.cmd('extension enable someext')
assert lib.cmd('echo') == '' |
"""
Module contains class coordinates
Class coordinates represent a pair of coordinates of a single cell on a 10x10 board
"""
class Coordinates:
"""
Represents coordinates of a single cell
Represents coordinates of a single cell with x and y coordinates where x abs is a top row in range a-j and y abs
is leftmost columnt 1-10
"""
def __init__(self, x:str, y:int):
"""
Constructor of the class coordinates
:param x: a string of a single letter in range a-b
:param y: an integer in range [1-10]
"""
if all([y>0, y<11]) and x in ['a','b','c','d','e','f','g','h','i','j']:
self.x = x
self.y = y
else:
raise Exception('invalid coordinates values')
def match(self, coordinates) -> bool:
"""
check if one object has the same coordinates as another
:param coordinates:
:return: True or False
"""
if coordinates.x == self.x and coordinates.y == self.y:
return True
return False
def next_y(self):
"""
next y coordinate
:return: next y value
"""
if self.y<10:
return self.y+1
else:
return None
# raise Exception('can not go beyond the limit')
def prev_y(self):
"""
perv y coordinate
:return: prev y value
"""
if self.y > 1:
return self.y - 1
else:
return None
# raise Exception('can not go beyond the limit')
def next_x(self):
"""
next x coordinate
:return: next x value
"""
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
index = letters.index(self.x)
if index < 9:
return letters[index + 1]
else:
return None
# raise Exception('can not go beyond the limit')
def prev_x(self):
"""
prev x coordinate
:return: prev x value
"""
letters = ['a','b','c','d','e','f','g','h','i','j']
index = letters.index(self.x)
if index > 0 :
return letters[index-1]
else:
return None
# raise Exception('can not go beyond the limit')
| """
Module contains class coordinates
Class coordinates represent a pair of coordinates of a single cell on a 10x10 board
"""
class Coordinates:
"""
Represents coordinates of a single cell
Represents coordinates of a single cell with x and y coordinates where x abs is a top row in range a-j and y abs
is leftmost columnt 1-10
"""
def __init__(self, x: str, y: int):
"""
Constructor of the class coordinates
:param x: a string of a single letter in range a-b
:param y: an integer in range [1-10]
"""
if all([y > 0, y < 11]) and x in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']:
self.x = x
self.y = y
else:
raise exception('invalid coordinates values')
def match(self, coordinates) -> bool:
"""
check if one object has the same coordinates as another
:param coordinates:
:return: True or False
"""
if coordinates.x == self.x and coordinates.y == self.y:
return True
return False
def next_y(self):
"""
next y coordinate
:return: next y value
"""
if self.y < 10:
return self.y + 1
else:
return None
def prev_y(self):
"""
perv y coordinate
:return: prev y value
"""
if self.y > 1:
return self.y - 1
else:
return None
def next_x(self):
"""
next x coordinate
:return: next x value
"""
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
index = letters.index(self.x)
if index < 9:
return letters[index + 1]
else:
return None
def prev_x(self):
"""
prev x coordinate
:return: prev x value
"""
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
index = letters.index(self.x)
if index > 0:
return letters[index - 1]
else:
return None |
'''
ref: https://www.datacamp.com/community/tutorials/decorators-python
'''
def uppercase_decorator(function):
def wrapper():
func = function()
make_uppercase = func.upper()
return make_uppercase
return wrapper
def say_hi():
return 'hi there'
decorate = uppercase_decorator(say_hi)
decorate()
print(decorate())
print('----------------------------------------------------------------------------')
print('----------------------------------------------------------------------------')
'''
Here is the decorator annotated as @uppercase_decorator
'''
@uppercase_decorator
def say_hello():
return 'hello there'
print(say_hello())
print('----------------------------------------------------------------------------')
print('----------------------------------------------------------------------------')
'''
Applying Multiple Decorators to a Single Function
'''
def split_string(function):
def wrapper():
func = function()
splitted_string = func.split()
return splitted_string
return wrapper
'''
Application of decorators is from the bottom up.
Had we interchanged the order, we'd have seen an error since lists don't have an upper attribute.
The sentence has first been converted to uppercase and then split into a list.
'''
@split_string # second applied
@uppercase_decorator # first applied
def say_hello():
return 'hello there'
print(say_hello())
print('----------------------------------------------------------------------------')
print('----------------------------------------------------------------------------')
'''
Function defination with parameters
'''
def decorator_with_arguments(function):
def wrapper_accepting_arguments(arg1, arg2):
print("Parameters passed to the function are: {0}, {1}".format(arg1,arg2))
function(arg1, arg2)
return wrapper_accepting_arguments
@decorator_with_arguments
def cities(city_one, city_two):
print("Cities I love are {0} and {1}".format(city_one, city_two))
cities("Duluth", "Leesburg")
print('----------------------------------------------------------------------------')
print('----------------------------------------------------------------------------')
def a_decorator_passing_arguments(function_to_decorate):
def a_wrapper_accepting_arguments(*args,**kwargs):
print('The positional arguments are', args)
print('The keyword arguments are', kwargs)
function_to_decorate(*args, *kwargs)
return a_wrapper_accepting_arguments
@a_decorator_passing_arguments
def function_with_positional_keyword_arguments(param1, param2, service="glue", region='us-east-1'):
print("This has both keyword and arguments")
print(f'param1: {param1} param2: {param2} service: {service} region: {region}')
function_with_positional_keyword_arguments('first-parameter', 'second-parameter')
print('----------------------------------------------------------------------------')
print('----------------------------------------------------------------------------')
function_with_positional_keyword_arguments('first-parameter', 'second-parameter', 's3', 'us-east-2')
| """
ref: https://www.datacamp.com/community/tutorials/decorators-python
"""
def uppercase_decorator(function):
def wrapper():
func = function()
make_uppercase = func.upper()
return make_uppercase
return wrapper
def say_hi():
return 'hi there'
decorate = uppercase_decorator(say_hi)
decorate()
print(decorate())
print('----------------------------------------------------------------------------')
print('----------------------------------------------------------------------------')
'\nHere is the decorator annotated as @uppercase_decorator\n'
@uppercase_decorator
def say_hello():
return 'hello there'
print(say_hello())
print('----------------------------------------------------------------------------')
print('----------------------------------------------------------------------------')
'\nApplying Multiple Decorators to a Single Function\n'
def split_string(function):
def wrapper():
func = function()
splitted_string = func.split()
return splitted_string
return wrapper
"\nApplication of decorators is from the bottom up. \nHad we interchanged the order, we'd have seen an error since lists don't have an upper attribute.\nThe sentence has first been converted to uppercase and then split into a list.\n"
@split_string
@uppercase_decorator
def say_hello():
return 'hello there'
print(say_hello())
print('----------------------------------------------------------------------------')
print('----------------------------------------------------------------------------')
'\n Function defination with parameters\n'
def decorator_with_arguments(function):
def wrapper_accepting_arguments(arg1, arg2):
print('Parameters passed to the function are: {0}, {1}'.format(arg1, arg2))
function(arg1, arg2)
return wrapper_accepting_arguments
@decorator_with_arguments
def cities(city_one, city_two):
print('Cities I love are {0} and {1}'.format(city_one, city_two))
cities('Duluth', 'Leesburg')
print('----------------------------------------------------------------------------')
print('----------------------------------------------------------------------------')
def a_decorator_passing_arguments(function_to_decorate):
def a_wrapper_accepting_arguments(*args, **kwargs):
print('The positional arguments are', args)
print('The keyword arguments are', kwargs)
function_to_decorate(*args, *kwargs)
return a_wrapper_accepting_arguments
@a_decorator_passing_arguments
def function_with_positional_keyword_arguments(param1, param2, service='glue', region='us-east-1'):
print('This has both keyword and arguments')
print(f'param1: {param1} param2: {param2} service: {service} region: {region}')
function_with_positional_keyword_arguments('first-parameter', 'second-parameter')
print('----------------------------------------------------------------------------')
print('----------------------------------------------------------------------------')
function_with_positional_keyword_arguments('first-parameter', 'second-parameter', 's3', 'us-east-2') |
# Copyright Google Inc. All Rights Reserved.
#
# Use of this source code is governed by an MIT-style license that can be
# found in the LICENSE file at https://angular.io/license
"""Test utility to extract the "flat_module_metadata" from transitive Angular deps.
"""
def _extract_flat_module_index(ctx):
return [DefaultInfo(files = depset(transitive = [
dep.angular.flat_module_metadata
for dep in ctx.attr.deps
if hasattr(dep, "angular")
]))]
extract_flat_module_index = rule(
implementation = _extract_flat_module_index,
attrs = {
"deps": attr.label_list(),
},
)
| """Test utility to extract the "flat_module_metadata" from transitive Angular deps.
"""
def _extract_flat_module_index(ctx):
return [default_info(files=depset(transitive=[dep.angular.flat_module_metadata for dep in ctx.attr.deps if hasattr(dep, 'angular')]))]
extract_flat_module_index = rule(implementation=_extract_flat_module_index, attrs={'deps': attr.label_list()}) |
MAX_CHAR_GROUP_NAME = 30
MAX_CHAR_CONTEXT_NAME = 30
MAX_CHAR_DEVICE_NAME = 30
MAX_DEVICES = 10
MAX_GROUPS = 10
MAX_CONTEXTS = 10
MAX_ACTIONS = 10
MAX_TRIGGERS = 10
# in seconds
INTERVAL_PUB_GROUP_DATA = 120
INTERVAL_ONLINE = 60
STATE_NO_CONNECTION = 1
STATE_CONNECTED_INTERNET = 2
STATE_CONNECTED_NO_INTERNET = 3 | max_char_group_name = 30
max_char_context_name = 30
max_char_device_name = 30
max_devices = 10
max_groups = 10
max_contexts = 10
max_actions = 10
max_triggers = 10
interval_pub_group_data = 120
interval_online = 60
state_no_connection = 1
state_connected_internet = 2
state_connected_no_internet = 3 |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 25 19:44:16 2020
@author: Ravi
"""
#Topological Sorting using recursive DFS
# {1: [3], 2: [3], 4: [0, 1], 5: [0, 2]}
# topological order = [3,1,2,1,0,4,5]
# 1->3
# 2->3
# 4->0->1
class Graph:
def __init__(self,edges):
self.explored = set()
self.edges = edges
self.graph_dict = {1: [2],
2: [3, 4],
3: [11, 8],
4: [5, 7],
5: [6],
6: [7],
7: [5],
8: [7, 9, 10],
9: [6, 10],
10: [11],
11: [8]}# {1: [3], 2: [3], 4: [0, 1], 5: [0, 2]}
self.order = []
# for start,end in self.edges:
# if start not in self.graph_dict:
# self.graph_dict[start] = [end]
# else:
# self.graph_dict[start].append(end)
# print(self.graph_dict)
self.nodes = list(self.graph_dict.keys())
def topological_ordering(self):
for i in self.nodes:
if i not in self.explored:
self.order.append(i)
self.dfs_helper(i)
def dfs_helper(self,start):
if start not in self.explored:
self.explored.add(start)
if start in self.graph_dict:
for edg in self.graph_dict[start]:
if edg not in self.explored:
self.order.append(edg) #this sould be commented out for reverse
self.dfs_helper(edg)
# self.order.append(start) {computes reverse topsort}
def print(self):
print(self.order)
if __name__ == '__main__':
routes =[
(5, 2),
(5, 0),
(4, 0),
(4, 1),
(2, 3),
(3, 1)
# (1,None)
]
routes2 = [
('a','c'),
('a','b'),
('b','e'),
('c','e'),
('c','d'),
('d','f'),
('e','f')
]
graph = Graph(routes)
graph.topological_ordering()
graph.print()
# graph.Topological_ordering()
| """
Created on Fri Sep 25 19:44:16 2020
@author: Ravi
"""
class Graph:
def __init__(self, edges):
self.explored = set()
self.edges = edges
self.graph_dict = {1: [2], 2: [3, 4], 3: [11, 8], 4: [5, 7], 5: [6], 6: [7], 7: [5], 8: [7, 9, 10], 9: [6, 10], 10: [11], 11: [8]}
self.order = []
self.nodes = list(self.graph_dict.keys())
def topological_ordering(self):
for i in self.nodes:
if i not in self.explored:
self.order.append(i)
self.dfs_helper(i)
def dfs_helper(self, start):
if start not in self.explored:
self.explored.add(start)
if start in self.graph_dict:
for edg in self.graph_dict[start]:
if edg not in self.explored:
self.order.append(edg)
self.dfs_helper(edg)
def print(self):
print(self.order)
if __name__ == '__main__':
routes = [(5, 2), (5, 0), (4, 0), (4, 1), (2, 3), (3, 1)]
routes2 = [('a', 'c'), ('a', 'b'), ('b', 'e'), ('c', 'e'), ('c', 'd'), ('d', 'f'), ('e', 'f')]
graph = graph(routes)
graph.topological_ordering()
graph.print() |
def login(client, username, password):
payload = dict(username=username, password=password)
return client.post('/login', data=payload, follow_redirects=True)
def logout(client):
return client.get('/logout', follow_redirects=True)
| def login(client, username, password):
payload = dict(username=username, password=password)
return client.post('/login', data=payload, follow_redirects=True)
def logout(client):
return client.get('/logout', follow_redirects=True) |
largest_number=None
smallest_number=None
while True:
order=input('Enter a number: ')
if order=='done':
break
try:
number=int(order)
except Exception as e:
print("Invalid Input")
continue
if largest_number is None:
largest_number=number
if smallest_number is None:
smallest_number=number
if largest_number<number:
largest_number=number
if smallest_number>number:
smallest_number=number
print(largest_number)
print(smallest_number) | largest_number = None
smallest_number = None
while True:
order = input('Enter a number: ')
if order == 'done':
break
try:
number = int(order)
except Exception as e:
print('Invalid Input')
continue
if largest_number is None:
largest_number = number
if smallest_number is None:
smallest_number = number
if largest_number < number:
largest_number = number
if smallest_number > number:
smallest_number = number
print(largest_number)
print(smallest_number) |
# XXXXXXXXXXX
class Node:
def __init__(self, value, prev_item=None, next_item=None):
self.value = value
self.prev_item = prev_item
self.next_item = next_item
class Queue():
def __init__(self, max_size):
self.max_size = max_size
self.size = 0
self.head = None
self.last = None
def push_back(self, x):
node = Node(value=x)
if self.max_size != self.size:
if self.size == 0:
self.head = node
self.last = node
else:
node.prev_item = self.last
self.last.next_item = node
self.last = node
self.size += 1
else:
print('error')
def push_front(self, x):
node = Node(value=x)
if self.max_size != self.size:
if self.size == 0:
self.head = node
self.last = node
else:
node.next_item = self.head
self.head.prev_item = node
self.head = node
self.size += 1
else:
print('error')
def pop_back(self):
if self.size == 0:
print('error')
else:
x = self.last
self.last = self.last.prev_item
self.size -= 1
print(x.value)
def pop_front(self):
if self.size == 0:
print('error')
else:
x = self.head
self.head = self.head.next_item
self.size -= 1
print(x.value)
def get_size(self):
print(self.size)
def run():
num_com = int(input())
max_size = int(input())
q = Queue(max_size)
for _ in range(num_com):
command = input().split()
if command[0] == 'push_back':
q.push_back(command[1])
if command[0] == 'push_front':
q.push_front(command[1])
if command[0] == 'pop_back':
q.pop_back()
if command[0] == 'pop_front':
q.pop_front()
if __name__ == '__main__':
run() | class Node:
def __init__(self, value, prev_item=None, next_item=None):
self.value = value
self.prev_item = prev_item
self.next_item = next_item
class Queue:
def __init__(self, max_size):
self.max_size = max_size
self.size = 0
self.head = None
self.last = None
def push_back(self, x):
node = node(value=x)
if self.max_size != self.size:
if self.size == 0:
self.head = node
self.last = node
else:
node.prev_item = self.last
self.last.next_item = node
self.last = node
self.size += 1
else:
print('error')
def push_front(self, x):
node = node(value=x)
if self.max_size != self.size:
if self.size == 0:
self.head = node
self.last = node
else:
node.next_item = self.head
self.head.prev_item = node
self.head = node
self.size += 1
else:
print('error')
def pop_back(self):
if self.size == 0:
print('error')
else:
x = self.last
self.last = self.last.prev_item
self.size -= 1
print(x.value)
def pop_front(self):
if self.size == 0:
print('error')
else:
x = self.head
self.head = self.head.next_item
self.size -= 1
print(x.value)
def get_size(self):
print(self.size)
def run():
num_com = int(input())
max_size = int(input())
q = queue(max_size)
for _ in range(num_com):
command = input().split()
if command[0] == 'push_back':
q.push_back(command[1])
if command[0] == 'push_front':
q.push_front(command[1])
if command[0] == 'pop_back':
q.pop_back()
if command[0] == 'pop_front':
q.pop_front()
if __name__ == '__main__':
run() |
#!/usr/bin/python3.6
# created by cicek on 12.10.2018 15:09
digits = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
d_list = list(digits)
i, res = 0, 1
product_array = []
while ((i+12) < len(d_list)):
for x in range(0, 13):
res *= int(d_list[i+x])
product_array.append(res)
res = 1
i += 1
product_array.sort()
print(product_array[-1])
| digits = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450'
d_list = list(digits)
(i, res) = (0, 1)
product_array = []
while i + 12 < len(d_list):
for x in range(0, 13):
res *= int(d_list[i + x])
product_array.append(res)
res = 1
i += 1
product_array.sort()
print(product_array[-1]) |
user_schema = {
"type": "object",
"properties": {
"name": {"type": "string"}
},
"required": ["name"],
"additionalProperties": False
}
get_users_query_params_schema = {
"type": ["object", "null"],
"properties": {
"page": {"type": "string"}
},
"additionalProperties": False
}
| user_schema = {'type': 'object', 'properties': {'name': {'type': 'string'}}, 'required': ['name'], 'additionalProperties': False}
get_users_query_params_schema = {'type': ['object', 'null'], 'properties': {'page': {'type': 'string'}}, 'additionalProperties': False} |
## ===============================================================================
## Authors: AFRL/RQQA
## Organization: Air Force Research Laboratory, Aerospace Systems Directorate, Power and Control Division
##
## Copyright (c) 2017 Government of the United State of America, as represented by
## the Secretary of the Air Force. No copyright is claimed in the United States under
## Title 17, U.S. Code. All Other Rights Reserved.
## ===============================================================================
## This file was auto-created by LmcpGen. Modifications will be overwritten.
class LoiterDirection:
VehicleDefault = 0
CounterClockwise = 1
Clockwise = 2
def get_LoiterDirection_str(str):
"""
Returns a numerical value from a string
"""
if str == "VehicleDefault": return LoiterDirection.VehicleDefault
if str == "CounterClockwise": return LoiterDirection.CounterClockwise
if str == "Clockwise": return LoiterDirection.Clockwise
def get_LoiterDirection_int(val):
"""
Returns a string representation from an int
"""
if val == LoiterDirection.VehicleDefault: return "VehicleDefault"
if val == LoiterDirection.CounterClockwise: return "CounterClockwise"
if val == LoiterDirection.Clockwise: return "Clockwise"
return LoiterDirection.VehicleDefault
| class Loiterdirection:
vehicle_default = 0
counter_clockwise = 1
clockwise = 2
def get__loiter_direction_str(str):
"""
Returns a numerical value from a string
"""
if str == 'VehicleDefault':
return LoiterDirection.VehicleDefault
if str == 'CounterClockwise':
return LoiterDirection.CounterClockwise
if str == 'Clockwise':
return LoiterDirection.Clockwise
def get__loiter_direction_int(val):
"""
Returns a string representation from an int
"""
if val == LoiterDirection.VehicleDefault:
return 'VehicleDefault'
if val == LoiterDirection.CounterClockwise:
return 'CounterClockwise'
if val == LoiterDirection.Clockwise:
return 'Clockwise'
return LoiterDirection.VehicleDefault |
#!/usr/bin/env python
class HostType:
GPCHECK_HOSTTYPE_UNDEFINED = 0
GPCHECK_HOSTTYPE_APPLIANCE = 1
GPCHECK_HOSTTYPE_GENERIC_LINUX = 2
def hosttype_str(type):
if type == HostType.GPCHECK_HOSTTYPE_APPLIANCE:
return "GPDB Appliance"
elif type == HostType.GPCHECK_HOSTTYPE_GENERIC_LINUX:
return "Generic Linux Cluster"
else:
return "Undetected Platform"
class sysctl:
def __init__(self):
self.variables = dict() # dictionary of values
self.errormsg = None
class omreport:
def __init__(self):
self.biossetup = dict() # key value pairs
self.biossetup_errormsg = None
self.bootorder = list() # list of Devices in order of boot
self.bootorder_errormsg = None
self.remoteaccess = dict() # key value pairs
self.remoteaccess_errormsg = None
self.vdisks = list() # list of dicts, 1 for each virtual disk
self.vdisks_errormsg = None
self.controller = dict() # key value pairs
self.controller_errormsg = None
self.omversion = None
self.omversion_errormsg = None
self.bios = dict() # key value pairs
self.bios_errormsg = None
self.alerts = list() # list of alerts... each alert is a dictionary of key value pairs
self.alerts_errormsg = None
class chkconfig:
def __init__(self):
self.services = dict() # hash of services, each entry is hash of run levels and boolean value
self.xinetd = dict() # hash of services, value is boolean
self.errormsg = None
class grubconf:
def __init__(self):
self.serial_declaration = False
self.terminal_declaration = False
self.ttyS1_declaration = False
self.errormsg = None
def __str__(self):
return "serial_declaration(%s) terminal_declaration(%s) ttyS1_declaration(%s)" % (self.serial_declaration, self.terminal_declaration, self.ttyS1_declaration)
class inittab:
def __init__(self):
self.s1 = False
self.defaultRunLevel = None
self.errormsg = None
def __str__(self):
return "s1_declaration(%s) default_run_level(%s)" % (self.s1, self.defaultRunLevel)
class uname:
def __init__(self):
self.output = None
self.errormsg = None
def __str__(self):
return self.output
class connectemc:
def __init__(self):
self.output = None
self.errormsg = None
def __str__(self):
return self.output
class securetty:
def __init__(self):
self.errormsg = None
self.data = set()
class bcu:
def __init__(self):
self.firmware = None
self.biosversion = None
self.errormsg = None
def __str__(self):
return "firmware_version=%s|biosversion=%s" % (self.firmware, self.biosversion)
class ioschedulers:
def __init__(self):
self.devices = dict() # key is device name value is scheduler name
self.errormsg = ''
class blockdev:
def __init__(self):
self.ra = dict() # key is device name value is getra value
self.errormsg = ''
class rclocal:
def __init__(self):
self.isexecutable = False # check that /etc/rc.d/rc.local is executable permissions
def __str__(self):
return "executable(%s)" % self.isexecutable
class limitsconf_entry:
def __init__(self, domain, type, item, value):
self.domain = domain
self.type = type
self.item = item
self.value = value
def __str__(self):
return "%s %s %s %s" % (self.domain, self.type, self.item, self.value)
class limitsconf:
def __init__(self):
self.lines = list()
self.errormsg = None
def __str__(self):
output = ""
for line in self.lines:
output = "%s\n%s" % (output, line)
return output
class GpMount:
def __init__(self):
self.partition = None
self.dir= None
self.type = None
self.options = set() # mount options
def __str__(self):
optionstring = ''
first = True
for k in self.options:
if not first:
optionstring = "%s," % optionstring
thisoption = k
optionstring = "%s%s" % (optionstring, thisoption)
first = False
return "%s on %s type %s (%s)" % (self.partition, self.dir, self.type, optionstring)
class ntp:
def __init__(self):
self.running = False
self.hosts = set()
self.currentime = None
self.errormsg = None
def __str__(self):
return "(running %s) (time %f) (peers: %s)" % (self.running, self.currenttime, self.hosts)
class mounts:
def __init__(self):
self.entries = dict() # dictionary key=partition value=mount object
self.errormsg = None
def __str__(self):
output = ''
for k in self.entries.keys():
output = "%s\n%s" % (output, self.entries[k].__str__())
return output
class GenericLinuxOutputData:
def __init__(self):
self.mounts = None
self.uname = None
self.blockdev = None
self.ioschedulers = None
self.sysctl = None
self.limitsconf = None
self.ntp = None
def __str__(self):
grc = "============= SYSCTL=========================\n"
gre = "============= SYSCTL ERRORMSG================\n"
output = "%s%s\n%s%s" % (grc, self.sysctl.variables.__str__(), gre, self.sysctl.errormsg)
grc = "============= LIMITS=========================\n"
gre = "============= LIMITS ERRORMSG================\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.limitsconf.__str__(), gre, self.limitsconf.errormsg)
mnt = "============= MOUNT==========================\n"
mte = "============= MOUNT ERRORMSG=================\n"
output = "%s\n%s%s\n%s%s" % (output, mnt, self.mounts.__str__(), mte, self.mounts.errormsg)
grc = "============= UNAME==========================\n"
gre = "============= UNAME ERRORMSG=================\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.uname.__str__(), gre, self.uname.errormsg)
grc = "============= IO SCHEDULERS==================\n"
gre = "============= IO SCHEDULERS ERRORMSG========\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.ioschedulers.devices.__str__(), gre, self.ioschedulers.errormsg)
grc = "============= BLOCKDEV RA ====================\n"
gre = "============= BLOCKDEV RA ERRORMSG============\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.blockdev.ra.__str__(), gre, self.blockdev.errormsg)
grc = "============= NTPD ===========================\n"
gre = "============= NTPD ERRORMSG===================\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.ntp.__str__(), gre, self.ntp.errormsg)
return output
class ApplianceOutputData:
def __init__(self):
self.chkconfig = None
self.omreport = None
self.grubconf = None
self.mounts = None
self.inittab = None
self.uname = None
self.securetty = None
self.bcu = None
self.blockdev = None
self.rclocal = None
self.ioschedulers = None
self.sysctl = None
self.limitsconf = None
self.connectemc = None
self.ntp = None
def __str__(self):
ser = "=============SERVICES=======================\n"
xin = "=============XINETD =======================\n"
err = "=============CHKCONFIG ERRORMSG=============\n"
output = "%s%s\n%s%s\n%s%s" % (ser, self.chkconfig.services.__str__(), xin, self.chkconfig.xinetd.__str__(), err, self.chkconfig.errormsg)
omr = "=============OMREPORT VERSION ==============\n"
ome = "=============OMREPORT VERSION ERRORMSG======\n"
output = "%s\n%s%s\n%s%s" % (output, omr, self.omreport.omversion, ome, self.omreport.omversion_errormsg)
omr = "=============OMREPORT BIOS==================\n"
ome = "=============OMREPORT BIOS ERRORMSG=========\n"
output = "%s\n%s%s\n%s%s" % (output, omr, self.omreport.bios.__str__(), ome,self.omreport.bios_errormsg)
omr = "=============OMREPORT BIOSSETUP=============\n"
ome = "=============OMREPORT BIOSSETUP ERRORMSG====\n"
output = "%s\n%s%s\n%s%s" % (output, omr, self.omreport.biossetup.__str__(), ome,self.omreport.biossetup_errormsg)
omr = "=============OMREPORT CONTROLLER============\n"
ome = "=============OMREPORT CONTROLLER ERRORMSG===\n"
output = "%s\n%s%s\n%s%s" % (output, omr, self.omreport.controller.__str__(), ome,self.omreport.controller_errormsg)
boo = "=============OMREPORT BOOTORDER=============\n"
boe = "=============OMREPORT BOOTORDER ERRORMSG====\n"
output = "%s\n%s%s\n%s%s" % (output, boo, self.omreport.bootorder.__str__(), boe, self.omreport.bootorder_errormsg)
omr = "=============OMREPORT REMOTEACCESS==========\n"
ome = "=============OMREPORT REMOTEACCESS ERRORMSG=\n"
output = "%s\n%s%s\n%s%s" % (output, omr, self.omreport.remoteaccess.__str__(), ome,self.omreport.remoteaccess_errormsg)
omr = "=============OMREPORT ALERTS==========\n"
ome = "=============OMREPORT ALERTS ERRORMSG=\n"
output = "%s\n%s%s\n%s%s" % (output, omr, self.omreport.alerts.__str__(), ome,self.omreport.alerts_errormsg)
omr = "=============OMREPORT VIRTUAL DISKS=========\n"
ome = "=============OMREPORT VIRTUAL DISKS ERRORMSG\n"
output = "%s\n%s%s\n%s%s" % (output, omr, self.omreport.vdisks.__str__(), ome,self.omreport.vdisks_errormsg)
grc = "============= GRUB.CONF======================\n"
gre = "============= GRUB.CONF ERRORMSG=============\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.grubconf.__str__(), gre, self.grubconf.errormsg)
grc = "============= SYSCTL=========================\n"
gre = "============= SYSCTL ERRORMSG================\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.sysctl.variables.__str__(), gre, self.sysctl.errormsg)
grc = "============= LIMITS=========================\n"
gre = "============= LIMITS ERRORMSG================\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.limitsconf.__str__(), gre, self.limitsconf.errormsg)
mnt = "============= MOUNT==========================\n"
mte = "============= MOUNT ERRORMSG=================\n"
output = "%s\n%s%s\n%s%s" % (output, mnt, self.mounts.__str__(), mte, self.mounts.errormsg)
grc = "============= INITTAB========================\n"
gre = "============= INITTAB ERRORMSG===============\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.inittab.__str__(), gre, self.inittab.errormsg)
grc = "============= UNAME==========================\n"
gre = "============= UNAME ERRORMSG=================\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.uname.__str__(), gre, self.uname.errormsg)
grc = "============= CONNECTEMC=====================\n"
gre = "============= CONNECtEMC ERRORMSG============\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.connectemc.__str__(), gre, self.connectemc.errormsg)
grc = "============= SECURETTY======================\n"
gre = "============= SECURETTY ERRORMSG=============\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.securetty.data.__str__(), gre, self.securetty.errormsg)
grc = "============= IO SCHEDULERS==================\n"
gre = "============= IO SCHEDULERS ERRORMSG========\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.ioschedulers.devices.__str__(), gre, self.ioschedulers.errormsg)
grc = "============= BLOCKDEV RA ====================\n"
gre = "============= BLOCKDEV RA ERRORMSG============\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.blockdev.ra.__str__(), gre, self.blockdev.errormsg)
grc = "============= BCU CNA ========================\n"
gre = "============= BCU CNA ERRORMSG================\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.bcu.__str__(), gre, self.bcu.errormsg)
grc = "============= /etc/rc.d/rc.local =============\n"
output = "%s\n%s%s" % (output, grc, self.rclocal.__str__())
grc = "============= NTPD ===========================\n"
gre = "============= NTPD ERRORMSG===================\n"
output = "%s\n%s%s\n%s%s" % (output, grc, self.ntp.__str__(), gre, self.ntp.errormsg)
return output
| class Hosttype:
gpcheck_hosttype_undefined = 0
gpcheck_hosttype_appliance = 1
gpcheck_hosttype_generic_linux = 2
def hosttype_str(type):
if type == HostType.GPCHECK_HOSTTYPE_APPLIANCE:
return 'GPDB Appliance'
elif type == HostType.GPCHECK_HOSTTYPE_GENERIC_LINUX:
return 'Generic Linux Cluster'
else:
return 'Undetected Platform'
class Sysctl:
def __init__(self):
self.variables = dict()
self.errormsg = None
class Omreport:
def __init__(self):
self.biossetup = dict()
self.biossetup_errormsg = None
self.bootorder = list()
self.bootorder_errormsg = None
self.remoteaccess = dict()
self.remoteaccess_errormsg = None
self.vdisks = list()
self.vdisks_errormsg = None
self.controller = dict()
self.controller_errormsg = None
self.omversion = None
self.omversion_errormsg = None
self.bios = dict()
self.bios_errormsg = None
self.alerts = list()
self.alerts_errormsg = None
class Chkconfig:
def __init__(self):
self.services = dict()
self.xinetd = dict()
self.errormsg = None
class Grubconf:
def __init__(self):
self.serial_declaration = False
self.terminal_declaration = False
self.ttyS1_declaration = False
self.errormsg = None
def __str__(self):
return 'serial_declaration(%s) terminal_declaration(%s) ttyS1_declaration(%s)' % (self.serial_declaration, self.terminal_declaration, self.ttyS1_declaration)
class Inittab:
def __init__(self):
self.s1 = False
self.defaultRunLevel = None
self.errormsg = None
def __str__(self):
return 's1_declaration(%s) default_run_level(%s)' % (self.s1, self.defaultRunLevel)
class Uname:
def __init__(self):
self.output = None
self.errormsg = None
def __str__(self):
return self.output
class Connectemc:
def __init__(self):
self.output = None
self.errormsg = None
def __str__(self):
return self.output
class Securetty:
def __init__(self):
self.errormsg = None
self.data = set()
class Bcu:
def __init__(self):
self.firmware = None
self.biosversion = None
self.errormsg = None
def __str__(self):
return 'firmware_version=%s|biosversion=%s' % (self.firmware, self.biosversion)
class Ioschedulers:
def __init__(self):
self.devices = dict()
self.errormsg = ''
class Blockdev:
def __init__(self):
self.ra = dict()
self.errormsg = ''
class Rclocal:
def __init__(self):
self.isexecutable = False
def __str__(self):
return 'executable(%s)' % self.isexecutable
class Limitsconf_Entry:
def __init__(self, domain, type, item, value):
self.domain = domain
self.type = type
self.item = item
self.value = value
def __str__(self):
return '%s %s %s %s' % (self.domain, self.type, self.item, self.value)
class Limitsconf:
def __init__(self):
self.lines = list()
self.errormsg = None
def __str__(self):
output = ''
for line in self.lines:
output = '%s\n%s' % (output, line)
return output
class Gpmount:
def __init__(self):
self.partition = None
self.dir = None
self.type = None
self.options = set()
def __str__(self):
optionstring = ''
first = True
for k in self.options:
if not first:
optionstring = '%s,' % optionstring
thisoption = k
optionstring = '%s%s' % (optionstring, thisoption)
first = False
return '%s on %s type %s (%s)' % (self.partition, self.dir, self.type, optionstring)
class Ntp:
def __init__(self):
self.running = False
self.hosts = set()
self.currentime = None
self.errormsg = None
def __str__(self):
return '(running %s) (time %f) (peers: %s)' % (self.running, self.currenttime, self.hosts)
class Mounts:
def __init__(self):
self.entries = dict()
self.errormsg = None
def __str__(self):
output = ''
for k in self.entries.keys():
output = '%s\n%s' % (output, self.entries[k].__str__())
return output
class Genericlinuxoutputdata:
def __init__(self):
self.mounts = None
self.uname = None
self.blockdev = None
self.ioschedulers = None
self.sysctl = None
self.limitsconf = None
self.ntp = None
def __str__(self):
grc = '============= SYSCTL=========================\n'
gre = '============= SYSCTL ERRORMSG================\n'
output = '%s%s\n%s%s' % (grc, self.sysctl.variables.__str__(), gre, self.sysctl.errormsg)
grc = '============= LIMITS=========================\n'
gre = '============= LIMITS ERRORMSG================\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.limitsconf.__str__(), gre, self.limitsconf.errormsg)
mnt = '============= MOUNT==========================\n'
mte = '============= MOUNT ERRORMSG=================\n'
output = '%s\n%s%s\n%s%s' % (output, mnt, self.mounts.__str__(), mte, self.mounts.errormsg)
grc = '============= UNAME==========================\n'
gre = '============= UNAME ERRORMSG=================\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.uname.__str__(), gre, self.uname.errormsg)
grc = '============= IO SCHEDULERS==================\n'
gre = '============= IO SCHEDULERS ERRORMSG========\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.ioschedulers.devices.__str__(), gre, self.ioschedulers.errormsg)
grc = '============= BLOCKDEV RA ====================\n'
gre = '============= BLOCKDEV RA ERRORMSG============\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.blockdev.ra.__str__(), gre, self.blockdev.errormsg)
grc = '============= NTPD ===========================\n'
gre = '============= NTPD ERRORMSG===================\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.ntp.__str__(), gre, self.ntp.errormsg)
return output
class Applianceoutputdata:
def __init__(self):
self.chkconfig = None
self.omreport = None
self.grubconf = None
self.mounts = None
self.inittab = None
self.uname = None
self.securetty = None
self.bcu = None
self.blockdev = None
self.rclocal = None
self.ioschedulers = None
self.sysctl = None
self.limitsconf = None
self.connectemc = None
self.ntp = None
def __str__(self):
ser = '=============SERVICES=======================\n'
xin = '=============XINETD =======================\n'
err = '=============CHKCONFIG ERRORMSG=============\n'
output = '%s%s\n%s%s\n%s%s' % (ser, self.chkconfig.services.__str__(), xin, self.chkconfig.xinetd.__str__(), err, self.chkconfig.errormsg)
omr = '=============OMREPORT VERSION ==============\n'
ome = '=============OMREPORT VERSION ERRORMSG======\n'
output = '%s\n%s%s\n%s%s' % (output, omr, self.omreport.omversion, ome, self.omreport.omversion_errormsg)
omr = '=============OMREPORT BIOS==================\n'
ome = '=============OMREPORT BIOS ERRORMSG=========\n'
output = '%s\n%s%s\n%s%s' % (output, omr, self.omreport.bios.__str__(), ome, self.omreport.bios_errormsg)
omr = '=============OMREPORT BIOSSETUP=============\n'
ome = '=============OMREPORT BIOSSETUP ERRORMSG====\n'
output = '%s\n%s%s\n%s%s' % (output, omr, self.omreport.biossetup.__str__(), ome, self.omreport.biossetup_errormsg)
omr = '=============OMREPORT CONTROLLER============\n'
ome = '=============OMREPORT CONTROLLER ERRORMSG===\n'
output = '%s\n%s%s\n%s%s' % (output, omr, self.omreport.controller.__str__(), ome, self.omreport.controller_errormsg)
boo = '=============OMREPORT BOOTORDER=============\n'
boe = '=============OMREPORT BOOTORDER ERRORMSG====\n'
output = '%s\n%s%s\n%s%s' % (output, boo, self.omreport.bootorder.__str__(), boe, self.omreport.bootorder_errormsg)
omr = '=============OMREPORT REMOTEACCESS==========\n'
ome = '=============OMREPORT REMOTEACCESS ERRORMSG=\n'
output = '%s\n%s%s\n%s%s' % (output, omr, self.omreport.remoteaccess.__str__(), ome, self.omreport.remoteaccess_errormsg)
omr = '=============OMREPORT ALERTS==========\n'
ome = '=============OMREPORT ALERTS ERRORMSG=\n'
output = '%s\n%s%s\n%s%s' % (output, omr, self.omreport.alerts.__str__(), ome, self.omreport.alerts_errormsg)
omr = '=============OMREPORT VIRTUAL DISKS=========\n'
ome = '=============OMREPORT VIRTUAL DISKS ERRORMSG\n'
output = '%s\n%s%s\n%s%s' % (output, omr, self.omreport.vdisks.__str__(), ome, self.omreport.vdisks_errormsg)
grc = '============= GRUB.CONF======================\n'
gre = '============= GRUB.CONF ERRORMSG=============\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.grubconf.__str__(), gre, self.grubconf.errormsg)
grc = '============= SYSCTL=========================\n'
gre = '============= SYSCTL ERRORMSG================\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.sysctl.variables.__str__(), gre, self.sysctl.errormsg)
grc = '============= LIMITS=========================\n'
gre = '============= LIMITS ERRORMSG================\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.limitsconf.__str__(), gre, self.limitsconf.errormsg)
mnt = '============= MOUNT==========================\n'
mte = '============= MOUNT ERRORMSG=================\n'
output = '%s\n%s%s\n%s%s' % (output, mnt, self.mounts.__str__(), mte, self.mounts.errormsg)
grc = '============= INITTAB========================\n'
gre = '============= INITTAB ERRORMSG===============\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.inittab.__str__(), gre, self.inittab.errormsg)
grc = '============= UNAME==========================\n'
gre = '============= UNAME ERRORMSG=================\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.uname.__str__(), gre, self.uname.errormsg)
grc = '============= CONNECTEMC=====================\n'
gre = '============= CONNECtEMC ERRORMSG============\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.connectemc.__str__(), gre, self.connectemc.errormsg)
grc = '============= SECURETTY======================\n'
gre = '============= SECURETTY ERRORMSG=============\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.securetty.data.__str__(), gre, self.securetty.errormsg)
grc = '============= IO SCHEDULERS==================\n'
gre = '============= IO SCHEDULERS ERRORMSG========\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.ioschedulers.devices.__str__(), gre, self.ioschedulers.errormsg)
grc = '============= BLOCKDEV RA ====================\n'
gre = '============= BLOCKDEV RA ERRORMSG============\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.blockdev.ra.__str__(), gre, self.blockdev.errormsg)
grc = '============= BCU CNA ========================\n'
gre = '============= BCU CNA ERRORMSG================\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.bcu.__str__(), gre, self.bcu.errormsg)
grc = '============= /etc/rc.d/rc.local =============\n'
output = '%s\n%s%s' % (output, grc, self.rclocal.__str__())
grc = '============= NTPD ===========================\n'
gre = '============= NTPD ERRORMSG===================\n'
output = '%s\n%s%s\n%s%s' % (output, grc, self.ntp.__str__(), gre, self.ntp.errormsg)
return output |
true = True
false = False
abi = [
{
"inputs": [],
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"stateMutability": "payable",
"type": "fallback"
},
{
"inputs": [],
"name": "client_cancellation",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "client_delete_random_index",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "i",
"type": "uint256"
}
],
"name": "client_download_MSRI",
"outputs": [
{
"internalType": "bytes",
"name": "",
"type": "bytes"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "i",
"type": "uint256"
}
],
"name": "client_download_encrypted_keys",
"outputs": [
{
"internalType": "bytes",
"name": "",
"type": "bytes"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "client_generate_random_index",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "client_get_RIAlength",
"outputs": [
{
"internalType": "uint8",
"name": "",
"type": "uint8"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "client_get_current_RIA_length",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "client_get_update_period",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "bytes",
"name": "str",
"type": "bytes"
}
],
"name": "client_register",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "client_registration_check",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address payable",
"name": "addr",
"type": "address"
}
],
"name": "contract_transfer_to_relay",
"outputs": [],
"stateMutability": "payable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "Addr",
"type": "address"
}
],
"name": "getClientFlag",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "addr",
"type": "address"
}
],
"name": "getRIA",
"outputs": [
{
"internalType": "uint16[]",
"name": "",
"type": "uint16[]"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint16",
"name": "i",
"type": "uint16"
}
],
"name": "getRelayFlag",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "getclientNum",
"outputs": [
{
"internalType": "uint24",
"name": "",
"type": "uint24"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint16",
"name": "i",
"type": "uint16"
}
],
"name": "getinfo",
"outputs": [
{
"internalType": "bytes",
"name": "",
"type": "bytes"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "getrelayIndex",
"outputs": [
{
"internalType": "uint16",
"name": "",
"type": "uint16"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "Addr",
"type": "address"
},
{
"internalType": "bool",
"name": "flag",
"type": "bool"
}
],
"name": "modifyClientFlag",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint16",
"name": "i",
"type": "uint16"
},
{
"internalType": "bool",
"name": "flag",
"type": "bool"
}
],
"name": "modifyRelayFlag",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "relay_cancellation",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "i",
"type": "uint256"
}
],
"name": "relay_download_clients_public_keys",
"outputs": [
{
"internalType": "bytes",
"name": "",
"type": "bytes"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "relay_get_clientlist_length",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "relay_get_upload_period",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "relay_register",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "relay_registration_check",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "bytes",
"name": "info",
"type": "bytes"
},
{
"internalType": "uint256",
"name": "num",
"type": "uint256"
},
{
"internalType": "bytes[]",
"name": "keys",
"type": "bytes[]"
}
],
"name": "relay_upload_SRI_and_keys",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "i",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "num",
"type": "uint256"
},
{
"internalType": "bytes[]",
"name": "keys",
"type": "bytes[]"
}
],
"name": "relay_upload_keys",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint8",
"name": "num",
"type": "uint8"
}
],
"name": "setRIAlength",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "period",
"type": "uint256"
}
],
"name": "setRIAperiod",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "period",
"type": "uint256"
}
],
"name": "setSRIperiod",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"stateMutability": "payable",
"type": "receive"
}
] | true = True
false = False
abi = [{'inputs': [], 'stateMutability': 'nonpayable', 'type': 'constructor'}, {'stateMutability': 'payable', 'type': 'fallback'}, {'inputs': [], 'name': 'client_cancellation', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function'}, {'inputs': [], 'name': 'client_delete_random_index', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function'}, {'inputs': [{'internalType': 'uint256', 'name': 'i', 'type': 'uint256'}], 'name': 'client_download_MSRI', 'outputs': [{'internalType': 'bytes', 'name': '', 'type': 'bytes'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [{'internalType': 'uint256', 'name': 'i', 'type': 'uint256'}], 'name': 'client_download_encrypted_keys', 'outputs': [{'internalType': 'bytes', 'name': '', 'type': 'bytes'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [], 'name': 'client_generate_random_index', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function'}, {'inputs': [], 'name': 'client_get_RIAlength', 'outputs': [{'internalType': 'uint8', 'name': '', 'type': 'uint8'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [], 'name': 'client_get_current_RIA_length', 'outputs': [{'internalType': 'uint256', 'name': '', 'type': 'uint256'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [], 'name': 'client_get_update_period', 'outputs': [{'internalType': 'uint256', 'name': '', 'type': 'uint256'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [{'internalType': 'bytes', 'name': 'str', 'type': 'bytes'}], 'name': 'client_register', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function'}, {'inputs': [], 'name': 'client_registration_check', 'outputs': [{'internalType': 'uint256', 'name': '', 'type': 'uint256'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [{'internalType': 'address payable', 'name': 'addr', 'type': 'address'}], 'name': 'contract_transfer_to_relay', 'outputs': [], 'stateMutability': 'payable', 'type': 'function'}, {'inputs': [{'internalType': 'address', 'name': 'Addr', 'type': 'address'}], 'name': 'getClientFlag', 'outputs': [{'internalType': 'bool', 'name': '', 'type': 'bool'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [{'internalType': 'address', 'name': 'addr', 'type': 'address'}], 'name': 'getRIA', 'outputs': [{'internalType': 'uint16[]', 'name': '', 'type': 'uint16[]'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [{'internalType': 'uint16', 'name': 'i', 'type': 'uint16'}], 'name': 'getRelayFlag', 'outputs': [{'internalType': 'bool', 'name': '', 'type': 'bool'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [], 'name': 'getclientNum', 'outputs': [{'internalType': 'uint24', 'name': '', 'type': 'uint24'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [{'internalType': 'uint16', 'name': 'i', 'type': 'uint16'}], 'name': 'getinfo', 'outputs': [{'internalType': 'bytes', 'name': '', 'type': 'bytes'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [], 'name': 'getrelayIndex', 'outputs': [{'internalType': 'uint16', 'name': '', 'type': 'uint16'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [{'internalType': 'address', 'name': 'Addr', 'type': 'address'}, {'internalType': 'bool', 'name': 'flag', 'type': 'bool'}], 'name': 'modifyClientFlag', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function'}, {'inputs': [{'internalType': 'uint16', 'name': 'i', 'type': 'uint16'}, {'internalType': 'bool', 'name': 'flag', 'type': 'bool'}], 'name': 'modifyRelayFlag', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function'}, {'inputs': [], 'name': 'relay_cancellation', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function'}, {'inputs': [{'internalType': 'uint256', 'name': 'i', 'type': 'uint256'}], 'name': 'relay_download_clients_public_keys', 'outputs': [{'internalType': 'bytes', 'name': '', 'type': 'bytes'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [], 'name': 'relay_get_clientlist_length', 'outputs': [{'internalType': 'uint256', 'name': '', 'type': 'uint256'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [], 'name': 'relay_get_upload_period', 'outputs': [{'internalType': 'uint256', 'name': '', 'type': 'uint256'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [], 'name': 'relay_register', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function'}, {'inputs': [], 'name': 'relay_registration_check', 'outputs': [{'internalType': 'uint256', 'name': '', 'type': 'uint256'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [{'internalType': 'bytes', 'name': 'info', 'type': 'bytes'}, {'internalType': 'uint256', 'name': 'num', 'type': 'uint256'}, {'internalType': 'bytes[]', 'name': 'keys', 'type': 'bytes[]'}], 'name': 'relay_upload_SRI_and_keys', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function'}, {'inputs': [{'internalType': 'uint256', 'name': 'i', 'type': 'uint256'}, {'internalType': 'uint256', 'name': 'num', 'type': 'uint256'}, {'internalType': 'bytes[]', 'name': 'keys', 'type': 'bytes[]'}], 'name': 'relay_upload_keys', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function'}, {'inputs': [{'internalType': 'uint8', 'name': 'num', 'type': 'uint8'}], 'name': 'setRIAlength', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function'}, {'inputs': [{'internalType': 'uint256', 'name': 'period', 'type': 'uint256'}], 'name': 'setRIAperiod', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function'}, {'inputs': [{'internalType': 'uint256', 'name': 'period', 'type': 'uint256'}], 'name': 'setSRIperiod', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function'}, {'stateMutability': 'payable', 'type': 'receive'}] |
# Copyright 2020 The FedLearner Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# coding: utf-8
# TODO THIS FILE SHOULD BE MERGED WITH fedlearner.common.common
# TODO MIND THE SUBTLE DIFFERENCES DUE TO ES COMPATIBILITY WHEN MERGING
# YYYY-MM-DD'T'hh:mm:ss.SSSSSSZ
_es_datetime_format = 'strict_date_optional_time'
RAW_DATA_MAPPINGS = {
'dynamic': True,
'dynamic_templates': [
{
'strings': {
'match_mapping_type': 'string',
'mapping': {
'type': 'keyword'
}
}
}
],
'properties': {
'partition': {
'type': 'short'
},
'application_id': {
'ignore_above': 128,
'type': 'keyword'
},
'event_time': {
'format': _es_datetime_format,
'type': 'date'
},
'process_time': {
'format': _es_datetime_format,
'type': 'date'
}
}
}
DATA_JOIN_MAPPINGS = {
'dynamic': True,
# for dynamically adding string fields, use keyword to reduce space
'dynamic_templates': [
{
'strings': {
'match_mapping_type': 'string',
'mapping': {
'type': 'keyword'
}
}
}
],
'properties': {
'partition': {
'type': 'short'
},
'joined': {
'type': 'byte'
},
'label': {
'ignore_above': 32,
'type': 'keyword'
},
'type': {
'ignore_above': 32,
'type': 'keyword'
},
'has_click_id': {
'type': 'boolean'
},
'has_example_id': {
'type': 'boolean'
},
'application_id': {
'ignore_above': 128,
'type': 'keyword'
},
'process_time': {
'format': _es_datetime_format,
'type': 'date'
},
'event_time': {
'format': _es_datetime_format,
'type': 'date'
}
}
}
METRICS_MAPPINGS = {
'dynamic': True,
'dynamic_templates': [
{
'strings': {
'match_mapping_type': 'string',
'mapping': {
'type': 'keyword'
}
}
}
],
'properties': {
'name': {
'type': 'keyword'
},
'value': {
'type': 'float'
},
'date_time': {
'format': _es_datetime_format,
'type': 'date'
},
'tags': {
'properties': {
'partition': {
'type': 'short'
},
'application_id': {
'ignore_above': 128,
'type': 'keyword'
},
'data_source_name': {
'ignore_above': 128,
'type': 'keyword'
},
'joiner_name': {
'ignore_above': 32,
'type': 'keyword'
},
'role': {
'ignore_above': 32,
'type': 'keyword'
},
'event_time': {
'type': 'date',
'format': _es_datetime_format
}
}
}
}
}
ALIAS_NAME = {'metrics': 'metrics_v2',
'raw_data': 'raw_data',
'data_join': 'data_join'}
INDEX_MAP = {'metrics': METRICS_MAPPINGS,
'raw_data': RAW_DATA_MAPPINGS,
'data_join': DATA_JOIN_MAPPINGS}
def get_es_template(index_type, shards):
assert index_type in ALIAS_NAME
alias_name = ALIAS_NAME[index_type]
template = {'index_patterns': ['{}-*'.format(alias_name)],
'settings': {
'index': {
'lifecycle': {
'name': 'fedlearner_{}_ilm'.format(index_type),
'rollover_alias': alias_name
},
'codec': 'best_compression',
'routing': {
'allocation': {
'total_shards_per_node': '1'
}
},
'refresh_interval': '60s',
'number_of_shards': str(shards),
'number_of_replicas': '1',
}
},
'mappings': INDEX_MAP[index_type]}
return template
| _es_datetime_format = 'strict_date_optional_time'
raw_data_mappings = {'dynamic': True, 'dynamic_templates': [{'strings': {'match_mapping_type': 'string', 'mapping': {'type': 'keyword'}}}], 'properties': {'partition': {'type': 'short'}, 'application_id': {'ignore_above': 128, 'type': 'keyword'}, 'event_time': {'format': _es_datetime_format, 'type': 'date'}, 'process_time': {'format': _es_datetime_format, 'type': 'date'}}}
data_join_mappings = {'dynamic': True, 'dynamic_templates': [{'strings': {'match_mapping_type': 'string', 'mapping': {'type': 'keyword'}}}], 'properties': {'partition': {'type': 'short'}, 'joined': {'type': 'byte'}, 'label': {'ignore_above': 32, 'type': 'keyword'}, 'type': {'ignore_above': 32, 'type': 'keyword'}, 'has_click_id': {'type': 'boolean'}, 'has_example_id': {'type': 'boolean'}, 'application_id': {'ignore_above': 128, 'type': 'keyword'}, 'process_time': {'format': _es_datetime_format, 'type': 'date'}, 'event_time': {'format': _es_datetime_format, 'type': 'date'}}}
metrics_mappings = {'dynamic': True, 'dynamic_templates': [{'strings': {'match_mapping_type': 'string', 'mapping': {'type': 'keyword'}}}], 'properties': {'name': {'type': 'keyword'}, 'value': {'type': 'float'}, 'date_time': {'format': _es_datetime_format, 'type': 'date'}, 'tags': {'properties': {'partition': {'type': 'short'}, 'application_id': {'ignore_above': 128, 'type': 'keyword'}, 'data_source_name': {'ignore_above': 128, 'type': 'keyword'}, 'joiner_name': {'ignore_above': 32, 'type': 'keyword'}, 'role': {'ignore_above': 32, 'type': 'keyword'}, 'event_time': {'type': 'date', 'format': _es_datetime_format}}}}}
alias_name = {'metrics': 'metrics_v2', 'raw_data': 'raw_data', 'data_join': 'data_join'}
index_map = {'metrics': METRICS_MAPPINGS, 'raw_data': RAW_DATA_MAPPINGS, 'data_join': DATA_JOIN_MAPPINGS}
def get_es_template(index_type, shards):
assert index_type in ALIAS_NAME
alias_name = ALIAS_NAME[index_type]
template = {'index_patterns': ['{}-*'.format(alias_name)], 'settings': {'index': {'lifecycle': {'name': 'fedlearner_{}_ilm'.format(index_type), 'rollover_alias': alias_name}, 'codec': 'best_compression', 'routing': {'allocation': {'total_shards_per_node': '1'}}, 'refresh_interval': '60s', 'number_of_shards': str(shards), 'number_of_replicas': '1'}}, 'mappings': INDEX_MAP[index_type]}
return template |
my_list = list(range(1, 11))
print(my_list)
def maxInList(aList): # non-recursion method
max_number = aList[0]
for i in range(1, len(aList)):
if max_number < aList[i]:
max_number = aList[i]
return max_number
def minInList(aList): # non-recursion method
min_number = aList[0]
for i in range(1, len(aList)):
if min_number > aList[i]:
min_number = aList[i]
return min_number
print(maxInList(my_list))
print(minInList(my_list))
| my_list = list(range(1, 11))
print(my_list)
def max_in_list(aList):
max_number = aList[0]
for i in range(1, len(aList)):
if max_number < aList[i]:
max_number = aList[i]
return max_number
def min_in_list(aList):
min_number = aList[0]
for i in range(1, len(aList)):
if min_number > aList[i]:
min_number = aList[i]
return min_number
print(max_in_list(my_list))
print(min_in_list(my_list)) |
#!/usr/bin/env python
#
# Copyright (c) 2018 10X Genomics, Inc. All rights reserved.
#
MATRIX_MEM_GB_MULTIPLIER = 2 # TODO reduce this once we're confident about the actual memory bounds
NUM_MATRIX_ENTRIES_PER_MEM_GB = 50e6
# Empirical obs: with new CountMatrix setup, take ~ 50 bytes/bc
NUM_MATRIX_BARCODES_PER_MEM_GB = 2000000
MIN_MEM_GB = 3
MIN_MEM_GB_NOWHITELIST = 64
GZIP_SUFFIX = '.gz'
LZ4_SUFFIX = '.lz4'
H5_COMPRESSION_LEVEL = 1
H5_FILETYPE_KEY = 'filetype'
H5_FEATURE_REF_ATTR = 'features'
H5_BCS_ATTR = 'barcodes'
H5_MATRIX_DATA_ATTR = 'data'
H5_MATRIX_INDICES_ATTR = 'indices'
H5_MATRIX_INDPTR_ATTR = 'indptr'
H5_MATRIX_SHAPE_ATTR = 'shape'
H5_MATRIX_ATTRS = {H5_MATRIX_DATA_ATTR: 'int32', H5_MATRIX_INDICES_ATTR: 'int64', H5_MATRIX_INDPTR_ATTR: 'int64', H5_MATRIX_SHAPE_ATTR: 'int32'}
H5_CHEMISTRY_DESC_KEY = 'chemistry_description'
H5_LIBRARY_ID_MAPPING_KEY = 'library_ids'
H5_ORIG_GEM_GROUP_MAPPING_KEY = 'original_gem_groups'
H5_METADATA_ATTRS = [H5_LIBRARY_ID_MAPPING_KEY, H5_ORIG_GEM_GROUP_MAPPING_KEY, H5_CHEMISTRY_DESC_KEY]
| matrix_mem_gb_multiplier = 2
num_matrix_entries_per_mem_gb = 50000000.0
num_matrix_barcodes_per_mem_gb = 2000000
min_mem_gb = 3
min_mem_gb_nowhitelist = 64
gzip_suffix = '.gz'
lz4_suffix = '.lz4'
h5_compression_level = 1
h5_filetype_key = 'filetype'
h5_feature_ref_attr = 'features'
h5_bcs_attr = 'barcodes'
h5_matrix_data_attr = 'data'
h5_matrix_indices_attr = 'indices'
h5_matrix_indptr_attr = 'indptr'
h5_matrix_shape_attr = 'shape'
h5_matrix_attrs = {H5_MATRIX_DATA_ATTR: 'int32', H5_MATRIX_INDICES_ATTR: 'int64', H5_MATRIX_INDPTR_ATTR: 'int64', H5_MATRIX_SHAPE_ATTR: 'int32'}
h5_chemistry_desc_key = 'chemistry_description'
h5_library_id_mapping_key = 'library_ids'
h5_orig_gem_group_mapping_key = 'original_gem_groups'
h5_metadata_attrs = [H5_LIBRARY_ID_MAPPING_KEY, H5_ORIG_GEM_GROUP_MAPPING_KEY, H5_CHEMISTRY_DESC_KEY] |
# 8. Write a program that swaps the values of three variables x,y, and z, so that x gets the value
# of y, y gets the value of z, and z gets the value of x.
x, y, z = 5, 10, 15
x, y, z = y, z, x # The power of Python ;)
# print(x, y, z) : 10 15 5
| (x, y, z) = (5, 10, 15)
(x, y, z) = (y, z, x) |
vts = list()
vts.append(0)
vtx = list()
total = 0
def dfs(cur, visited:list):
global vtx, total
if cache[cur] != -1:
total += cache[cur]
return
if not vtx[cur]:
if cur == tg + 3:
total += 1
return
visited = visited.copy()
visited.append(cur)
for i in vtx[cur]:
if not i in visited:
dfs(i, visited)
while True:
try:
vts.append(int(input()))
except EOFError:
break
tg = max(vts)
vts.append(tg + 3)
vts.sort()
vtx = [0]*(tg + 4)
cache = [-1]*(tg + 4)
cnt = len(vts) - 1
for i in range(cnt):
vtx[vts[i]] = list()
vtx[vts[i]].append(vts[i + 1])
if i + 2 <= cnt and vts[i + 2] - vts[i] <= 3: vtx[vts[i]].append(vts[i+2])
if i + 3 <= cnt and vts[i + 3] - vts[i] <= 3: vtx[vts[i]].append(vts[i+3])
for i in range(cnt + 1):
if vtx[cnt - i] == 0: continue
total = 0
dfs(cnt - i, list())
cache[cnt - i] = total
print(total) | vts = list()
vts.append(0)
vtx = list()
total = 0
def dfs(cur, visited: list):
global vtx, total
if cache[cur] != -1:
total += cache[cur]
return
if not vtx[cur]:
if cur == tg + 3:
total += 1
return
visited = visited.copy()
visited.append(cur)
for i in vtx[cur]:
if not i in visited:
dfs(i, visited)
while True:
try:
vts.append(int(input()))
except EOFError:
break
tg = max(vts)
vts.append(tg + 3)
vts.sort()
vtx = [0] * (tg + 4)
cache = [-1] * (tg + 4)
cnt = len(vts) - 1
for i in range(cnt):
vtx[vts[i]] = list()
vtx[vts[i]].append(vts[i + 1])
if i + 2 <= cnt and vts[i + 2] - vts[i] <= 3:
vtx[vts[i]].append(vts[i + 2])
if i + 3 <= cnt and vts[i + 3] - vts[i] <= 3:
vtx[vts[i]].append(vts[i + 3])
for i in range(cnt + 1):
if vtx[cnt - i] == 0:
continue
total = 0
dfs(cnt - i, list())
cache[cnt - i] = total
print(total) |
#!/usr/bin/env prey
async def main():
await x("ls -a")
cd("..")
a = await x("ls")
await asyncio.sleep(2)
| async def main():
await x('ls -a')
cd('..')
a = await x('ls')
await asyncio.sleep(2) |
"""Default configuration
Use env var to override
"""
DEBUG = True
SECRET_KEY = "changeme"
SQLALCHEMY_DATABASE_URI = "sqlite:////tmp/microbiome_api.db"
SQLALCHEMY_TRACK_MODIFICATIONS = False
| """Default configuration
Use env var to override
"""
debug = True
secret_key = 'changeme'
sqlalchemy_database_uri = 'sqlite:////tmp/microbiome_api.db'
sqlalchemy_track_modifications = False |
class Solution:
def halvesAreAlike(self, s: str) -> bool:
num_vowels=0
num_vowels1=0
split = -( ( -len(s) )//2 )
p1, p2 = s[:split], s[split:]
for char in p1:
if char in "aeiouAEIOU":
num_vowels = num_vowels+1
for char in p2:
if char in "aeiouAEIOU":
num_vowels1 = num_vowels1+1
return num_vowels== num_vowels1
| class Solution:
def halves_are_alike(self, s: str) -> bool:
num_vowels = 0
num_vowels1 = 0
split = -(-len(s) // 2)
(p1, p2) = (s[:split], s[split:])
for char in p1:
if char in 'aeiouAEIOU':
num_vowels = num_vowels + 1
for char in p2:
if char in 'aeiouAEIOU':
num_vowels1 = num_vowels1 + 1
return num_vowels == num_vowels1 |
class BaseValidationError(ValueError):
pass
class LogInFileNotParsedError(BaseValidationError):
pass
| class Basevalidationerror(ValueError):
pass
class Loginfilenotparsederror(BaseValidationError):
pass |
# -*- coding: utf-8 -*-
class TransitionType(object):
def __init__(self, utc_offset, is_dst, abbrev):
self.utc_offset = utc_offset
self.is_dst = is_dst
self.abbrev = abbrev
def __repr__(self):
return '<TransitionType [{}, {}, {}]>'.format(
self.utc_offset,
self.is_dst,
self.abbrev
)
| class Transitiontype(object):
def __init__(self, utc_offset, is_dst, abbrev):
self.utc_offset = utc_offset
self.is_dst = is_dst
self.abbrev = abbrev
def __repr__(self):
return '<TransitionType [{}, {}, {}]>'.format(self.utc_offset, self.is_dst, self.abbrev) |
class SingleLinkedListNode(object):
def __init__(self, value, nxt):
self.value = value
self.next = nxt
def __repr__(self):
nval = self.next and self.next.value or None
return f"[{self.value}:{repr(nval)}]"
class SingleLinkedList(object):
def __init__(self):
self.begin = None
self.end = None
def push(self, obj):
"""Appends a new value on the end of the list."""
node = SingleLinkedListNode(obj, None)
if self.begin == None:
# nothing net
self.begin = node
self.end = self.begin
else:
self.end.next = node
self.end = node
assert self.begin != self.end
assert self.end.next == None
def pop(self):
"""Removes the last item and returns it."""
if self.end == None:
return None
elif self.end == self.begin:
node = self.begin
self.end = self.begin = None
return node.value
else:
node = self.begin
while node.next != self.end:
node = node.next
assert self.end != node
self.end = node
return node.next.value
def shift(self, obj):
"""Another name for push."""
def unshift(self):
"""Removes the first item and returns it."""
def remove(self, obj):
"""Finds a matching item and removes it from the list."""
def first(self):
"""Returns a *reference* to the first item, does not remove."""
def last(self):
"""Returns a reference to the last item, does not remove."""
def count(self):
"""Counts the number of elements in the list."""
node = self.begin
count = 0
while node:
count += 1
node = node.next
return count
def get(self, index):
"""Get the value at index."""
def dump(self, mark):
"""Debugging function that dumps the contents of the list."""
| class Singlelinkedlistnode(object):
def __init__(self, value, nxt):
self.value = value
self.next = nxt
def __repr__(self):
nval = self.next and self.next.value or None
return f'[{self.value}:{repr(nval)}]'
class Singlelinkedlist(object):
def __init__(self):
self.begin = None
self.end = None
def push(self, obj):
"""Appends a new value on the end of the list."""
node = single_linked_list_node(obj, None)
if self.begin == None:
self.begin = node
self.end = self.begin
else:
self.end.next = node
self.end = node
assert self.begin != self.end
assert self.end.next == None
def pop(self):
"""Removes the last item and returns it."""
if self.end == None:
return None
elif self.end == self.begin:
node = self.begin
self.end = self.begin = None
return node.value
else:
node = self.begin
while node.next != self.end:
node = node.next
assert self.end != node
self.end = node
return node.next.value
def shift(self, obj):
"""Another name for push."""
def unshift(self):
"""Removes the first item and returns it."""
def remove(self, obj):
"""Finds a matching item and removes it from the list."""
def first(self):
"""Returns a *reference* to the first item, does not remove."""
def last(self):
"""Returns a reference to the last item, does not remove."""
def count(self):
"""Counts the number of elements in the list."""
node = self.begin
count = 0
while node:
count += 1
node = node.next
return count
def get(self, index):
"""Get the value at index."""
def dump(self, mark):
"""Debugging function that dumps the contents of the list.""" |
"""
0997. Find the Town Judge
In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge.
If the town judge exists, then:
The town judge trusts nobody.
Everybody (except for the town judge) trusts the town judge.
There is exactly one person that satisfies properties 1 and 2.
You are given trust, an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b.
If the town judge exists and can be identified, return the label of the town judge. Otherwise, return -1.
Example 1:
Input: N = 2, trust = [[1,2]]
Output: 2
Example 2:
Input: N = 3, trust = [[1,3],[2,3]]
Output: 3
Example 3:
Input: N = 3, trust = [[1,3],[2,3],[3,1]]
Output: -1
Example 4:
Input: N = 3, trust = [[1,2],[2,3]]
Output: -1
Example 5:
Input: N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]]
Output: 3
Constraints:
1 <= N <= 1000
0 <= trust.length <= 10^4
trust[i].length == 2
trust[i] are all different
trust[i][0] != trust[i][1]
1 <= trust[i][0], trust[i][1] <= N
"""
class Solution:
def findJudge(self, N: int, trust: List[List[int]]) -> int:
trusted = [0] * N
for a, b in trust:
trusted[a - 1] -= 1
trusted[b - 1] += 1
for i in range(N):
if trusted[i] == N - 1:
return i + 1
return -1 | """
0997. Find the Town Judge
In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge.
If the town judge exists, then:
The town judge trusts nobody.
Everybody (except for the town judge) trusts the town judge.
There is exactly one person that satisfies properties 1 and 2.
You are given trust, an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b.
If the town judge exists and can be identified, return the label of the town judge. Otherwise, return -1.
Example 1:
Input: N = 2, trust = [[1,2]]
Output: 2
Example 2:
Input: N = 3, trust = [[1,3],[2,3]]
Output: 3
Example 3:
Input: N = 3, trust = [[1,3],[2,3],[3,1]]
Output: -1
Example 4:
Input: N = 3, trust = [[1,2],[2,3]]
Output: -1
Example 5:
Input: N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]]
Output: 3
Constraints:
1 <= N <= 1000
0 <= trust.length <= 10^4
trust[i].length == 2
trust[i] are all different
trust[i][0] != trust[i][1]
1 <= trust[i][0], trust[i][1] <= N
"""
class Solution:
def find_judge(self, N: int, trust: List[List[int]]) -> int:
trusted = [0] * N
for (a, b) in trust:
trusted[a - 1] -= 1
trusted[b - 1] += 1
for i in range(N):
if trusted[i] == N - 1:
return i + 1
return -1 |
class Solution:
def findLonelyPixel(self, picture: List[List[str]]) -> int:
"""Array.
Running time: O(m * n) where m and n are the size of picture.
"""
m, n = len(picture), len(picture[0])
row, col = [0] * m , [0] * n
for i in range(m):
for j in range(n):
if picture[i][j] == 'B':
row[i] += 1
col[j] += 1
res = 0
for i in range(m):
for j in range(n):
if picture[i][j] == 'B' and row[i] == col[j] == 1:
res += 1
return res
| class Solution:
def find_lonely_pixel(self, picture: List[List[str]]) -> int:
"""Array.
Running time: O(m * n) where m and n are the size of picture.
"""
(m, n) = (len(picture), len(picture[0]))
(row, col) = ([0] * m, [0] * n)
for i in range(m):
for j in range(n):
if picture[i][j] == 'B':
row[i] += 1
col[j] += 1
res = 0
for i in range(m):
for j in range(n):
if picture[i][j] == 'B' and row[i] == col[j] == 1:
res += 1
return res |
#!/usr/bin/env python
# coding: utf-8
# In given array find the duplicate odd number .
#
# Note: There is only one duplicate odd number
#
# <b> Ex [1,4,6,3,1] should return 1 </b>
# In[3]:
def dup_odd_num(num):
count=0
for i in range(len(num)):
if num[i] % 2 != 0:
count+=1
if count > 1: return num[i]
return False
print(dup_odd_num([1,3,2,3]))
# In[ ]:
def dup_odd_num(num):
count=0
dic={}
for i in range(len(num)):
if num[i] % 2 != 0:
dic[0]=count
dic[1]=num[i]
count+=1
return dic[1]
# In[28]:
print(dup_odd_num([3,4,6,8,]))
| def dup_odd_num(num):
count = 0
for i in range(len(num)):
if num[i] % 2 != 0:
count += 1
if count > 1:
return num[i]
return False
print(dup_odd_num([1, 3, 2, 3]))
def dup_odd_num(num):
count = 0
dic = {}
for i in range(len(num)):
if num[i] % 2 != 0:
dic[0] = count
dic[1] = num[i]
count += 1
return dic[1]
print(dup_odd_num([3, 4, 6, 8])) |
# -*- coding: utf-8 -*-
class OcelotError(Exception):
"""Base for custom ocelot errors"""
pass
class ZeroProduction(OcelotError):
"""Reference production exchange has amount of zero"""
pass
class IdenticalVariables(OcelotError):
"""The same variable name is used twice"""
pass
class InvalidMultioutputDataset(OcelotError):
pass
class OutputDirectoryError(OcelotError):
pass
class ParameterizationError(OcelotError):
pass
class UnsupportedDistribution(OcelotError):
"""Manipulation of this uncertainty type is not supported"""
pass
class InvalidExchange(OcelotError):
"""This exchange in invalid in the given system model"""
pass
class MultipleGlobalDatasets(OcelotError):
"""Multiple global datasets for the same activity name and reference product are not allowed"""
pass
class UnparsableFormula(OcelotError):
"""Formula contains elements that can't be parsed"""
pass
class InvalidMarketExchange(Exception):
"""Markets aren't allowed to consume their own reference product"""
pass
class InvalidMarket(Exception):
"""Markets can only have one reference product"""
pass
class UnresolvableActivityLink(OcelotError):
"""Activity link can't be uniquely resolved to an exchange"""
pass
class MissingMandatoryProperty(Exception):
"""Exchange is missing a mandatory property"""
pass
class OverlappingActivities(OcelotError):
"""Markets overlap, preventing correct linking"""
pass
class IdenticalDatasets(OcelotError):
"""Multiple datasets with the same identifying attributes were found"""
pass
class OverlappingMarkets(OcelotError):
"""Markets overlap, preventing correct linking"""
pass
class InvalidTransformationFunction(OcelotError):
"""Metadata could not be retrieved for this function"""
pass
class MissingSupplier(OcelotError):
"""Input from global or RoW market is needed, but this market doesn't exist"""
pass
class MissingAlternativeProducer(OcelotError):
"""Alternative producer for byproduct not found"""
pass
class MarketGroupError(OcelotError):
"""Error with market group definition or suppliers"""
pass
| class Oceloterror(Exception):
"""Base for custom ocelot errors"""
pass
class Zeroproduction(OcelotError):
"""Reference production exchange has amount of zero"""
pass
class Identicalvariables(OcelotError):
"""The same variable name is used twice"""
pass
class Invalidmultioutputdataset(OcelotError):
pass
class Outputdirectoryerror(OcelotError):
pass
class Parameterizationerror(OcelotError):
pass
class Unsupporteddistribution(OcelotError):
"""Manipulation of this uncertainty type is not supported"""
pass
class Invalidexchange(OcelotError):
"""This exchange in invalid in the given system model"""
pass
class Multipleglobaldatasets(OcelotError):
"""Multiple global datasets for the same activity name and reference product are not allowed"""
pass
class Unparsableformula(OcelotError):
"""Formula contains elements that can't be parsed"""
pass
class Invalidmarketexchange(Exception):
"""Markets aren't allowed to consume their own reference product"""
pass
class Invalidmarket(Exception):
"""Markets can only have one reference product"""
pass
class Unresolvableactivitylink(OcelotError):
"""Activity link can't be uniquely resolved to an exchange"""
pass
class Missingmandatoryproperty(Exception):
"""Exchange is missing a mandatory property"""
pass
class Overlappingactivities(OcelotError):
"""Markets overlap, preventing correct linking"""
pass
class Identicaldatasets(OcelotError):
"""Multiple datasets with the same identifying attributes were found"""
pass
class Overlappingmarkets(OcelotError):
"""Markets overlap, preventing correct linking"""
pass
class Invalidtransformationfunction(OcelotError):
"""Metadata could not be retrieved for this function"""
pass
class Missingsupplier(OcelotError):
"""Input from global or RoW market is needed, but this market doesn't exist"""
pass
class Missingalternativeproducer(OcelotError):
"""Alternative producer for byproduct not found"""
pass
class Marketgrouperror(OcelotError):
"""Error with market group definition or suppliers"""
pass |
# -*- coding: utf-8 -*-
# *******************************************************
# Copyright (c) VMware, Inc. 2020-2021. All Rights Reserved.
# SPDX-License-Identifier: MIT
# *******************************************************
# *
# * DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT
# * WARRANTIES OR CONDITIONS OF ANY KIND, WHETHER ORAL OR WRITTEN,
# * EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY DISCLAIMS ANY IMPLIED
# * WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY,
# * NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
"""Engine fixtures for testing"""
IOCS_1 = [{
"id": "j39sbv7",
"match_type": "equality",
"values": ["127.0.0.1"],
"severity": 1,
},
{
"id": "kfsd982m",
"match_type": "equality",
"values": ["127.0.0.2"],
"severity": 1,
},
{
"id": "slkf038",
"match_type": "equality",
"values": ["app.exe"],
"severity": 10,
},
{
"id": "0kdl4uf9",
"match_type": "regex",
"values": [".*google.*"],
"severity": 3,
}]
IOCS_2 = [{
"id": "s9dlk2m1",
"match_type": "query",
"values": ["netconn_ipv4:127.0.0.1"],
"severity": 2,
}]
IOCS_3 = [{
"id": "jsoq301n",
"match_type": "equality",
"values": ["127.0.0.1"],
"severity": 1,
},
{
"id": "ci2js01l",
"match_type": "equality",
"values": ["127.0.0.2"],
"severity": 1,
},
{
"id": "d83nsmc4",
"match_type": "equality",
"values": ["app.exe"],
"severity": 10,
},
{
"id": "cj01nsbds",
"match_type": "equality",
"values": ["127.0.0.3"],
"severity": 1,
},
{
"id": "feh48sk1",
"match_type": "equality",
"values": ["127.0.0.4"],
"severity": 1,
},
{
"id": "d02kfn63",
"match_type": "equality",
"values": ["bad.exe"],
"severity": 10,
},
{
"id": "cje828jc",
"match_type": "regex",
"values": [".*google.*"],
"severity": 3,
},
{
"id": "s9dlk2m1",
"match_type": "query",
"values": ["netconn_ipv4:127.0.0.1"],
"severity": 2,
}]
IOC_HASH = [{
"id": "j39sbv7",
"match_type": "equality",
"values": ["405f03534be8b45185695f68deb47d4daf04dcd6df9d351ca6831d3721b1efc4"],
"severity": 1,
}]
IOCS_INVALID = [{
"id": "s9dlk2m1",
"match_type": "query",
"values": ["netconn_ipv4:127.0.0.1"],
"severity": -10,
}]
UNFINISHED_STATE = {
"file_size": 2000000,
"file_name": "blort.exe",
"os_type": "WINDOWS",
"engine_name": "!!REPLACE!!",
"time_sent": "2020-01-15T12:00:00"
}
FINISHED_STATE = {
"file_size": 2000000,
"file_name": "foobar.exe",
"os_type": "WINDOWS",
"engine_name": "!!REPLACE!!",
"time_sent": "2020-01-14T12:00:00",
"time_returned": "2020-01-14T12:05:00"
}
MESSAGE_VALID = {
"iocs": IOCS_1,
"engine_name": "TEST_ENGINE",
"binary_hash": "0995f71c34f613207bc39ed4fcc1bbbee396a543fa1739656f7ddf70419309fc",
"success": True
}
MESSAGE_VALID_1 = {
"iocs": IOCS_2,
"engine_name": "TEST_ENGINE",
"binary_hash": "0995f71c34f613207bc39ed4fcc1bbbee396a543fa1739656f7ddf70419309fc",
"success": True
}
MESSAGE_VALID_2 = {
"iocs": IOCS_3,
"engine_name": "TEST_ENGINE",
"binary_hash": "0995f71c34f613207bc39ed4fcc1bbbee396a543fa1739656f7ddf70419309fc",
"success": True
}
ENGINE_FAILURE = {
"iocs": [],
"engine_name": "TEST_ENGINE",
"binary_hash": "0995f71c34f613207bc39ed4fcc1bbbee396a543fa1739656f7ddf70419309fc",
"success": False
}
MESSAGE_INVALID = {
"INVALID": "Bad schema",
"binary_hash": "0995f71c34f613207bc39ed4fcc1bbbee396a543fa1739656f7ddf70419309fc"
}
| """Engine fixtures for testing"""
iocs_1 = [{'id': 'j39sbv7', 'match_type': 'equality', 'values': ['127.0.0.1'], 'severity': 1}, {'id': 'kfsd982m', 'match_type': 'equality', 'values': ['127.0.0.2'], 'severity': 1}, {'id': 'slkf038', 'match_type': 'equality', 'values': ['app.exe'], 'severity': 10}, {'id': '0kdl4uf9', 'match_type': 'regex', 'values': ['.*google.*'], 'severity': 3}]
iocs_2 = [{'id': 's9dlk2m1', 'match_type': 'query', 'values': ['netconn_ipv4:127.0.0.1'], 'severity': 2}]
iocs_3 = [{'id': 'jsoq301n', 'match_type': 'equality', 'values': ['127.0.0.1'], 'severity': 1}, {'id': 'ci2js01l', 'match_type': 'equality', 'values': ['127.0.0.2'], 'severity': 1}, {'id': 'd83nsmc4', 'match_type': 'equality', 'values': ['app.exe'], 'severity': 10}, {'id': 'cj01nsbds', 'match_type': 'equality', 'values': ['127.0.0.3'], 'severity': 1}, {'id': 'feh48sk1', 'match_type': 'equality', 'values': ['127.0.0.4'], 'severity': 1}, {'id': 'd02kfn63', 'match_type': 'equality', 'values': ['bad.exe'], 'severity': 10}, {'id': 'cje828jc', 'match_type': 'regex', 'values': ['.*google.*'], 'severity': 3}, {'id': 's9dlk2m1', 'match_type': 'query', 'values': ['netconn_ipv4:127.0.0.1'], 'severity': 2}]
ioc_hash = [{'id': 'j39sbv7', 'match_type': 'equality', 'values': ['405f03534be8b45185695f68deb47d4daf04dcd6df9d351ca6831d3721b1efc4'], 'severity': 1}]
iocs_invalid = [{'id': 's9dlk2m1', 'match_type': 'query', 'values': ['netconn_ipv4:127.0.0.1'], 'severity': -10}]
unfinished_state = {'file_size': 2000000, 'file_name': 'blort.exe', 'os_type': 'WINDOWS', 'engine_name': '!!REPLACE!!', 'time_sent': '2020-01-15T12:00:00'}
finished_state = {'file_size': 2000000, 'file_name': 'foobar.exe', 'os_type': 'WINDOWS', 'engine_name': '!!REPLACE!!', 'time_sent': '2020-01-14T12:00:00', 'time_returned': '2020-01-14T12:05:00'}
message_valid = {'iocs': IOCS_1, 'engine_name': 'TEST_ENGINE', 'binary_hash': '0995f71c34f613207bc39ed4fcc1bbbee396a543fa1739656f7ddf70419309fc', 'success': True}
message_valid_1 = {'iocs': IOCS_2, 'engine_name': 'TEST_ENGINE', 'binary_hash': '0995f71c34f613207bc39ed4fcc1bbbee396a543fa1739656f7ddf70419309fc', 'success': True}
message_valid_2 = {'iocs': IOCS_3, 'engine_name': 'TEST_ENGINE', 'binary_hash': '0995f71c34f613207bc39ed4fcc1bbbee396a543fa1739656f7ddf70419309fc', 'success': True}
engine_failure = {'iocs': [], 'engine_name': 'TEST_ENGINE', 'binary_hash': '0995f71c34f613207bc39ed4fcc1bbbee396a543fa1739656f7ddf70419309fc', 'success': False}
message_invalid = {'INVALID': 'Bad schema', 'binary_hash': '0995f71c34f613207bc39ed4fcc1bbbee396a543fa1739656f7ddf70419309fc'} |
a = int(input())
b = int(input())
count = 0
x = 0
a1 = str(a)
b1 = str(b)
if len(a1) == len(b1):
for i in a1:
for j in b1[x::]:
if i != j:
count += 1
x += 1
break
print(count)
| a = int(input())
b = int(input())
count = 0
x = 0
a1 = str(a)
b1 = str(b)
if len(a1) == len(b1):
for i in a1:
for j in b1[x:]:
if i != j:
count += 1
x += 1
break
print(count) |
valores =[]
valores_quadrado =[]
for i in range(10):
valores.append(int(input("Digite um numero inteiro: ")))
for i in valores:
valores_quadrado.append(i**2)
print("Valores da lista ao quadrado: ",valores_quadrado)
print("Soma dos quadrados: ",sum(valores_quadrado)) | valores = []
valores_quadrado = []
for i in range(10):
valores.append(int(input('Digite um numero inteiro: ')))
for i in valores:
valores_quadrado.append(i ** 2)
print('Valores da lista ao quadrado: ', valores_quadrado)
print('Soma dos quadrados: ', sum(valores_quadrado)) |
def str_seems_like_json(txt):
for c in txt:
if c not in "\r\n\t ":
return c == '{'
return False
def bytes_seems_like_json(binary):
for b in binary:
if b not in [13, 10, 9, 32]:
return b == 123
return False
| def str_seems_like_json(txt):
for c in txt:
if c not in '\r\n\t ':
return c == '{'
return False
def bytes_seems_like_json(binary):
for b in binary:
if b not in [13, 10, 9, 32]:
return b == 123
return False |
DEFAULT_SESSION_DURATION = 43200 # 12 hours
SANDBOX_SESSION_DURATION = 60 * 60 # 1 hour
BASTION_PROFILE_ENV_NAME = 'FIGGY_AWS_PROFILE'
AWS_REGIONS = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'af-south-1', 'ap-east-1', 'ap-east-2',
'ap-northeast-3', 'ap-northeast-2', 'ap-northeast-1', 'ap-southeast-1', 'ap-southeast-2',
'ca-central-1', 'cn-north-1', 'cn-northwest-1', 'eu-central-1', 'eu-west-1', 'eu-west-2',
'eu-west-3', 'eu-north-1', 'me-south-1', 'sa-east-1', 'us-gov-east-1', 'us-gov-west-1']
AWS_CFG_ACCESS_KEY_ID = 'aws_access_key_id'
AWS_CFG_SECRET_KEY = 'aws_secret_access_key'
AWS_CFG_TOKEN = 'aws_session_token'
AWS_CFG_REGION = 'region'
AWS_CFG_OUTPUT = 'output'
RESTRICTED_ENV_VARS = ['AWS_ACCESS_KEY_ID', 'AWS_DEFAULT_REGION', 'AWS_PROFILE', 'AWS_SECRET_ACCESS_KEY', 'AWS_SESSION_TOKEN'] | default_session_duration = 43200
sandbox_session_duration = 60 * 60
bastion_profile_env_name = 'FIGGY_AWS_PROFILE'
aws_regions = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'af-south-1', 'ap-east-1', 'ap-east-2', 'ap-northeast-3', 'ap-northeast-2', 'ap-northeast-1', 'ap-southeast-1', 'ap-southeast-2', 'ca-central-1', 'cn-north-1', 'cn-northwest-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1', 'me-south-1', 'sa-east-1', 'us-gov-east-1', 'us-gov-west-1']
aws_cfg_access_key_id = 'aws_access_key_id'
aws_cfg_secret_key = 'aws_secret_access_key'
aws_cfg_token = 'aws_session_token'
aws_cfg_region = 'region'
aws_cfg_output = 'output'
restricted_env_vars = ['AWS_ACCESS_KEY_ID', 'AWS_DEFAULT_REGION', 'AWS_PROFILE', 'AWS_SECRET_ACCESS_KEY', 'AWS_SESSION_TOKEN'] |
#
# SOFTWARE HISTORY
#
# Date Ticket# Engineer Description
# ------------ ---------- ----------- --------------------------
# Sep 16, 2016 pmoyer Generated
class GetStationsRequest(object):
def __init__(self):
self.pluginName = None
def getPluginName(self):
return self.pluginName
def setPluginName(self, pluginName):
self.pluginName = pluginName
| class Getstationsrequest(object):
def __init__(self):
self.pluginName = None
def get_plugin_name(self):
return self.pluginName
def set_plugin_name(self, pluginName):
self.pluginName = pluginName |
def compute():
ans = sum(1 for i in range(10000) if is_lychrel(i))
return str(ans)
def is_lychrel(n):
for i in range(50):
n += int(str(n)[ : : -1])
if str(n) == str(n)[ : : -1]:
return False
return True
if __name__ == "__main__":
print(compute())
| def compute():
ans = sum((1 for i in range(10000) if is_lychrel(i)))
return str(ans)
def is_lychrel(n):
for i in range(50):
n += int(str(n)[::-1])
if str(n) == str(n)[::-1]:
return False
return True
if __name__ == '__main__':
print(compute()) |
# lecture 3.6, slide 2
# bisection search for square root
x = 12345
epsilon = 0.01
numGuesses = 0
low = 0.0
high = x
ans = (high + low)/2.0
while abs(ans**2 - x) >= epsilon:
print('low = ' + str(low) + ' high = ' + str(high) + ' ans = ' + str(ans))
numGuesses += 1
if ans**2 < x:
low = ans
else:
high = ans
ans = (high + low)/2.0
print('numGuesses = ' + str(numGuesses))
print(str(ans) + ' is close to square root of ' + str(x))
| x = 12345
epsilon = 0.01
num_guesses = 0
low = 0.0
high = x
ans = (high + low) / 2.0
while abs(ans ** 2 - x) >= epsilon:
print('low = ' + str(low) + ' high = ' + str(high) + ' ans = ' + str(ans))
num_guesses += 1
if ans ** 2 < x:
low = ans
else:
high = ans
ans = (high + low) / 2.0
print('numGuesses = ' + str(numGuesses))
print(str(ans) + ' is close to square root of ' + str(x)) |
"""Implementation of Kotlin JS rules."""
load("@io_bazel_rules_kotlin//kotlin/internal:defs.bzl", "KtJsInfo")
def kt_js_import_impl(ctx):
"""Implementation for kt_js_import.
Args:
ctx: rule context
Returns:
Providers for the build rule.
"""
if len(ctx.files.jars) != 1:
fail("a single jar should be supplied, multiple jars not supported")
jar_file = ctx.files.jars[0]
args = ctx.actions.args()
args.add("--jar", jar_file)
args.add("--out_pattern", "\\.js$")
args.add("--out", ctx.outputs.js)
args.add("--aux_pattern", "\\.js\\.map$")
args.add("--aux", ctx.outputs.js_map)
tools, _, input_manifest = ctx.resolve_command(tools = [ctx.attr._importer])
ctx.actions.run(
inputs = [jar_file],
tools = tools,
executable = ctx.executable._importer,
outputs = [
ctx.outputs.js,
ctx.outputs.js_map,
],
arguments = [args],
input_manifests = input_manifest,
)
return [
DefaultInfo(
files = depset([ctx.outputs.js, ctx.outputs.js_map]),
),
KtJsInfo(
js = ctx.outputs.js,
js_map = ctx.outputs.js_map,
jar = jar_file,
srcjar = ctx.files.srcjar[0],
),
]
| """Implementation of Kotlin JS rules."""
load('@io_bazel_rules_kotlin//kotlin/internal:defs.bzl', 'KtJsInfo')
def kt_js_import_impl(ctx):
"""Implementation for kt_js_import.
Args:
ctx: rule context
Returns:
Providers for the build rule.
"""
if len(ctx.files.jars) != 1:
fail('a single jar should be supplied, multiple jars not supported')
jar_file = ctx.files.jars[0]
args = ctx.actions.args()
args.add('--jar', jar_file)
args.add('--out_pattern', '\\.js$')
args.add('--out', ctx.outputs.js)
args.add('--aux_pattern', '\\.js\\.map$')
args.add('--aux', ctx.outputs.js_map)
(tools, _, input_manifest) = ctx.resolve_command(tools=[ctx.attr._importer])
ctx.actions.run(inputs=[jar_file], tools=tools, executable=ctx.executable._importer, outputs=[ctx.outputs.js, ctx.outputs.js_map], arguments=[args], input_manifests=input_manifest)
return [default_info(files=depset([ctx.outputs.js, ctx.outputs.js_map])), kt_js_info(js=ctx.outputs.js, js_map=ctx.outputs.js_map, jar=jar_file, srcjar=ctx.files.srcjar[0])] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Question 010
Source : http://www.pythonchallenge.com/pc/return/bull.html
what are you looking at ?
len(a[30]) = ?
a = [1, 11, 21, 1211, 111221]
Solution : http://villemin.gerard.free.fr/Puzzle/SeqComme.htm
"""
a = ["1"]
for i in range(31):
# init value
value = ""
# init temporary variable
last_char = ""
number_count = 0
chars = list(a[i])
last_char = chars[0]
# read all chars
for char in chars:
if last_char != char:
value += str(number_count) + last_char
last_char = char
number_count = 0
number_count += 1
value += str(number_count) + last_char
a.append(value)
print(a)
print(len(a[30]))
# 5808
| """Question 010
Source : http://www.pythonchallenge.com/pc/return/bull.html
what are you looking at ?
len(a[30]) = ?
a = [1, 11, 21, 1211, 111221]
Solution : http://villemin.gerard.free.fr/Puzzle/SeqComme.htm
"""
a = ['1']
for i in range(31):
value = ''
last_char = ''
number_count = 0
chars = list(a[i])
last_char = chars[0]
for char in chars:
if last_char != char:
value += str(number_count) + last_char
last_char = char
number_count = 0
number_count += 1
value += str(number_count) + last_char
a.append(value)
print(a)
print(len(a[30])) |
#!/usr/bin/env python3
# imports go here
#
# Free Coding session for 2015-03-02
# Written by Matt Warren
#
class SimpleClass:
def main(self):
return "HI"
def main2(self):
return "HELLO AGAIN"
if __name__ == '__main__':
sc = SimpleClass()
assert(sc.main.__name__ == 'main')
fn = getattr(sc, 'main')
assert(fn() == 'HI')
fn = getattr(sc, 'main', sc.main2)
assert(fn() == 'HI')
fn = getattr(sc, 'main3', sc.main2)
assert(fn() == 'HELLO AGAIN')
setattr(sc, 'main3', fn)
fn = getattr(sc, 'main3', sc.main2)
assert(fn() == 'HELLO AGAIN')
assert(sc.main3() == 'HELLO AGAIN')
| class Simpleclass:
def main(self):
return 'HI'
def main2(self):
return 'HELLO AGAIN'
if __name__ == '__main__':
sc = simple_class()
assert sc.main.__name__ == 'main'
fn = getattr(sc, 'main')
assert fn() == 'HI'
fn = getattr(sc, 'main', sc.main2)
assert fn() == 'HI'
fn = getattr(sc, 'main3', sc.main2)
assert fn() == 'HELLO AGAIN'
setattr(sc, 'main3', fn)
fn = getattr(sc, 'main3', sc.main2)
assert fn() == 'HELLO AGAIN'
assert sc.main3() == 'HELLO AGAIN' |
r =int(input("enter the row:"))
for i in range(1, r+1):
for j in range(1, i+1):
print("*", end = " ")
print("\n")
x = r
for j in range(1, r):
for i in range(1, x):
print("*", end = " ")
x = x - 1
print("\n")
| r = int(input('enter the row:'))
for i in range(1, r + 1):
for j in range(1, i + 1):
print('*', end=' ')
print('\n')
x = r
for j in range(1, r):
for i in range(1, x):
print('*', end=' ')
x = x - 1
print('\n') |
app.config.from_envvar('FLASKR_SETTINGS', silent=True)
def connect_db():
"""Connects to the specific database."""
rv = sqlite3.connect(app.config['DATABASE'])
rv.row_factory = sqlite3.Row
return rv | app.config.from_envvar('FLASKR_SETTINGS', silent=True)
def connect_db():
"""Connects to the specific database."""
rv = sqlite3.connect(app.config['DATABASE'])
rv.row_factory = sqlite3.Row
return rv |
# -*- coding: utf-8 -*-
"""
Project: EverydayWechat-Github
Creator: DoubleThunder
Create time: 2019-07-12 19:09
Introduction:
"""
| """
Project: EverydayWechat-Github
Creator: DoubleThunder
Create time: 2019-07-12 19:09
Introduction:
""" |
SERVIDOR_DESTINO = "BIGSQL"
YAML_SCOOP_IMPORT = "sqoop-import"
YAML_SCOOP_EXPORT = "sqoop-export"
YAML_BIGSQL_EXEC = "bigsql-import"
YAML_HDFS_IMPORT = "hdfs-import"
YAML_HDFS_EXPORT = "hdfs-export"
YAML_PYTHON_SCRIPT = "python-script"
YAML_ORIGEM = "origem"
YAML_DESTINO = "destino"
YAML_TABLE = "tabela"
YAML_QUERY = "consulta"
YAML_SCRIPT_FINAL = "script_final"
YAML_SPLITBY = "chave"
YAML_TIPO_TABELA = "tipo_tabela"
YAML_QUANDO_EXISTIR = "se_existir"
YAML_ACAO_SUBSTITUIR = "substituir"
YAML_ACAO_IGNORAR = "ignorar"
YAML_ACAO_INCREMENTAR = "incrementar"
YAML_ACAO_ERRO = "erro"
YAML_ACAO_CARREGAR = "carregar"
YAML_REMOVER_TABELA_GERADA = "remover_tabela_gerada"
YAML_SERVIDORES_TRANSACIONAIS = "servidores"
YAML_SCHEMA = "schema"
YAML_LISTA_ARQUIVOS = "arquivos"
YAML_LISTA_TABELAS = "tabelas"
YAML_ARQUIVO_SCRIPT = "nome_arquivo_script"
YAML_ARQUIVO_SAIDA = "nome_arquivo_saida"
YAML_SCRIPT_PRE = "script_pre_processamento"
YAML_SCRIPT_POS = "script_pos_processamento"
YAML_ARQUIVO_ENTRADA = "nome_arquivo_entrada"
YAML_ESTRUTURA = "estrutura"
YAML_ARQUIVO_ESTRUTURA = "nome_arquivo_estrutura"
YAML_CONVERSAO_AUTOMATICA = "converter_tipos_na_stage"
YAML_FORMATO_TABELA = "nome_tabela"
YAML_FORMATO_SEQUENCIA = "sequencia"
YAML_CONFIG = "configuracao"
YAML_DIR_LOGS = "diretorio_logs"
YAML_DIR_SCRIPTS = "diretorio_scripts"
YAML_DIR_SAIDA = "diretorio_saida"
YAML_DIR_ENTRADA = "diretorio_entrada"
YAML_DIR_ESTRUTURA = "diretorio_estrutura"
YAML_DIR_BACKUP = "diretorio_backup"
YAML_CONTINUA_ERRO = "continuar_em_erro"
YAML_TABELA_CONTROLE = "tabela_controle"
YAML_TABELA_CONTROLE_SQOOP = "sqoop.tabela_controle"
YAML_TABELA_CONTROLE_BIGSQL = "bigsql.tabela_controle"
YAML_WEB_HDFS_HOST = "webhdfs_host"
YAML_HDFS_TEMP_DIR = "hdfs_temp_dir"
YAML_EXECUTA_EM_ERRO = "executar_em_erro"
YAML_MAIL_TO = "reportar"
YAML_SEP_COLUNA = "delimitador_coluna"
YAML_SEP_LINHA = "delimitador_linha"
YAML_CABECALHO = "cabecalho_primeira_linha"
YAML_TIPO_ARQUIVO = "tipo_arquivo"
#YAML_QUOTATION = "delimitador_texto"
| servidor_destino = 'BIGSQL'
yaml_scoop_import = 'sqoop-import'
yaml_scoop_export = 'sqoop-export'
yaml_bigsql_exec = 'bigsql-import'
yaml_hdfs_import = 'hdfs-import'
yaml_hdfs_export = 'hdfs-export'
yaml_python_script = 'python-script'
yaml_origem = 'origem'
yaml_destino = 'destino'
yaml_table = 'tabela'
yaml_query = 'consulta'
yaml_script_final = 'script_final'
yaml_splitby = 'chave'
yaml_tipo_tabela = 'tipo_tabela'
yaml_quando_existir = 'se_existir'
yaml_acao_substituir = 'substituir'
yaml_acao_ignorar = 'ignorar'
yaml_acao_incrementar = 'incrementar'
yaml_acao_erro = 'erro'
yaml_acao_carregar = 'carregar'
yaml_remover_tabela_gerada = 'remover_tabela_gerada'
yaml_servidores_transacionais = 'servidores'
yaml_schema = 'schema'
yaml_lista_arquivos = 'arquivos'
yaml_lista_tabelas = 'tabelas'
yaml_arquivo_script = 'nome_arquivo_script'
yaml_arquivo_saida = 'nome_arquivo_saida'
yaml_script_pre = 'script_pre_processamento'
yaml_script_pos = 'script_pos_processamento'
yaml_arquivo_entrada = 'nome_arquivo_entrada'
yaml_estrutura = 'estrutura'
yaml_arquivo_estrutura = 'nome_arquivo_estrutura'
yaml_conversao_automatica = 'converter_tipos_na_stage'
yaml_formato_tabela = 'nome_tabela'
yaml_formato_sequencia = 'sequencia'
yaml_config = 'configuracao'
yaml_dir_logs = 'diretorio_logs'
yaml_dir_scripts = 'diretorio_scripts'
yaml_dir_saida = 'diretorio_saida'
yaml_dir_entrada = 'diretorio_entrada'
yaml_dir_estrutura = 'diretorio_estrutura'
yaml_dir_backup = 'diretorio_backup'
yaml_continua_erro = 'continuar_em_erro'
yaml_tabela_controle = 'tabela_controle'
yaml_tabela_controle_sqoop = 'sqoop.tabela_controle'
yaml_tabela_controle_bigsql = 'bigsql.tabela_controle'
yaml_web_hdfs_host = 'webhdfs_host'
yaml_hdfs_temp_dir = 'hdfs_temp_dir'
yaml_executa_em_erro = 'executar_em_erro'
yaml_mail_to = 'reportar'
yaml_sep_coluna = 'delimitador_coluna'
yaml_sep_linha = 'delimitador_linha'
yaml_cabecalho = 'cabecalho_primeira_linha'
yaml_tipo_arquivo = 'tipo_arquivo' |
"""1423. Maximum Points You Can Obtain from Cards"""
class Solution(object):
def maxScore(self, cardPoints, k):
"""
:type cardPoints: List[int]
:type k: int
:rtype: int
"""
points = res = sum(cardPoints[:k])
c = cardPoints[::-1]
for i in range(k):
points += c[i] - cardPoints[k-i-1]
res = max(res, points)
return res
| """1423. Maximum Points You Can Obtain from Cards"""
class Solution(object):
def max_score(self, cardPoints, k):
"""
:type cardPoints: List[int]
:type k: int
:rtype: int
"""
points = res = sum(cardPoints[:k])
c = cardPoints[::-1]
for i in range(k):
points += c[i] - cardPoints[k - i - 1]
res = max(res, points)
return res |
{
# Ports for the left-side motors
"leftMotorPorts": [0, 1],
# Ports for the right-side motors
"rightMotorPorts": [2, 3],
# NOTE: Inversions of the slaves (i.e. any motor *after* the first on
# each side of the drive) are *with respect to their master*. This is
# different from the other poject types!
# Inversions for the left-side motors
"leftMotorsInverted": [False, False],
# Inversions for the right side motors
"rightMotorsInverted": [False, False],
# If your robot has only one encoder, remove all of the right encoder fields
# Encoder pulses-per-revolution (*NOT* cycles per revolution!)
# This value should be the pulses per revolution *of the wheels*, and so
# should take into account gearing between the encoder and the wheels
"encoderPPR": 512,
# Whether the left encoder is inverted
"leftEncoderInverted": False,
# Whether the right encoder is inverted:
"rightEncoderInverted": False,
# The total gear reduction between the motor and the wheels, expressed as
# a fraction [motor turns]/[wheel turns]
"gearing": 1,
# Wheel diameter (in units of your choice - will dictate units of analysis)
"wheelDiameter": 0.333,
# Your gyro type (one of "NavX", "Pigeon", "ADXRS450", "AnalogGyro", or "None")
"gyroType": "None",
# Whatever you put into the constructor of your gyro
# Could be:
# "SPI.Port.kMXP" (MXP SPI port for NavX or ADXRS450),
# "I2C.Port.kOnboard" (Onboard I2C port for NavX)
# "0" (Pigeon CAN ID or AnalogGyro channel),
# "new TalonSRX(3)" (Pigeon on a Talon SRX),
# "" (NavX using default SPI, ADXRS450 using onboard CS0, or no gyro)
"gyroPort": "",
}
| {'leftMotorPorts': [0, 1], 'rightMotorPorts': [2, 3], 'leftMotorsInverted': [False, False], 'rightMotorsInverted': [False, False], 'encoderPPR': 512, 'leftEncoderInverted': False, 'rightEncoderInverted': False, 'gearing': 1, 'wheelDiameter': 0.333, 'gyroType': 'None', 'gyroPort': ''} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.