content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
version_info = (20, 0, 4, "custom")
__version__ = ".".join([str(v) for v in version_info])
SERVER = "gunicorn"
SERVER_SOFTWARE = "%s/%s" % (SERVER, __version__)
| version_info = (20, 0, 4, 'custom')
__version__ = '.'.join([str(v) for v in version_info])
server = 'gunicorn'
server_software = '%s/%s' % (SERVER, __version__) |
'''
03 - Creating histograms
Histograms show the full distribution of a variable. In this exercise, we will
display the distribution of weights of medalists in gymnastics and in rowing in
the 2016 Olympic games for a comparison between them.
You will have two DataFrames to use. The first is called mens_rowing and includes
information about the medalists in the men's rowing events. The other is called
mens_gymnastics and includes information about medalists in all of the Gymnastics
events.
Instructions:
- Use the ax.hist method to add a histogram of the "Weight" column from the mens_rowing
DataFrame.
- Use ax.hist to add a histogram of "Weight" for the mens_gymnastics DataFrame.
- Set the x-axis label to "Weight (kg)" and the y-axis label to "# of observations".
'''
fig, ax = plt.subplots()
# Plot a histogram of "Weight" for mens_rowing
ax.hist(mens_rowing['Weight'])
# Compare to histogram of "Weight" for mens_gymnastics
ax.hist(mens_gymnastics['Weight'])
# Set the x-axis label to "Weight (kg)"
ax.set_xlabel('Weight (kg)')
# Set the y-axis label to "# of observations"
ax.set_ylabel('# of observations')
plt.show()
| """
03 - Creating histograms
Histograms show the full distribution of a variable. In this exercise, we will
display the distribution of weights of medalists in gymnastics and in rowing in
the 2016 Olympic games for a comparison between them.
You will have two DataFrames to use. The first is called mens_rowing and includes
information about the medalists in the men's rowing events. The other is called
mens_gymnastics and includes information about medalists in all of the Gymnastics
events.
Instructions:
- Use the ax.hist method to add a histogram of the "Weight" column from the mens_rowing
DataFrame.
- Use ax.hist to add a histogram of "Weight" for the mens_gymnastics DataFrame.
- Set the x-axis label to "Weight (kg)" and the y-axis label to "# of observations".
"""
(fig, ax) = plt.subplots()
ax.hist(mens_rowing['Weight'])
ax.hist(mens_gymnastics['Weight'])
ax.set_xlabel('Weight (kg)')
ax.set_ylabel('# of observations')
plt.show() |
"""camera_settings.py
Note: Currently not used. Proof of concept to show how to change camera settings
in one file and have them applied to a camera from a different script.
"""
def apply_settings(camera):
"""Changes the settings of a camera."""
camera.clear_mode = 0
camera.exp_mode = "Internal Trigger"
camera.readout_port = 0
camera.speed_table_index = 0
camera.gain = 1
| """camera_settings.py
Note: Currently not used. Proof of concept to show how to change camera settings
in one file and have them applied to a camera from a different script.
"""
def apply_settings(camera):
"""Changes the settings of a camera."""
camera.clear_mode = 0
camera.exp_mode = 'Internal Trigger'
camera.readout_port = 0
camera.speed_table_index = 0
camera.gain = 1 |
# model settings
norm_cfg = dict(type='SyncBN', requires_grad=True)
model = dict(
type='EncoderDecoder',
pretrained=None,
backbone=dict(
type='MixVisionTransformer',
in_channels=3,
embed_dims=32,
num_stages=4,
num_layers=[2, 2, 2, 2],
num_heads=[1, 2, 5, 8],
patch_sizes=[7, 3, 3, 3],
sr_ratios=[8, 4, 2, 1],
out_indices=(0, 1, 2, 3),
mlp_ratio=4,
qkv_bias=True,
drop_rate=0.0,
attn_drop_rate=0.0,
drop_path_rate=0.1),
decode_head=dict(
type='SegformerHead',
in_channels=[32, 64, 160, 256],
in_index=[0, 1, 2, 3],
channels=256,
dropout_ratio=0.1,
num_classes=3,
norm_cfg=norm_cfg,
align_corners=False,
loss_decode=dict(
type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)),
# model training and testing settings
train_cfg=dict(),
test_cfg=dict(mode='whole'))
| norm_cfg = dict(type='SyncBN', requires_grad=True)
model = dict(type='EncoderDecoder', pretrained=None, backbone=dict(type='MixVisionTransformer', in_channels=3, embed_dims=32, num_stages=4, num_layers=[2, 2, 2, 2], num_heads=[1, 2, 5, 8], patch_sizes=[7, 3, 3, 3], sr_ratios=[8, 4, 2, 1], out_indices=(0, 1, 2, 3), mlp_ratio=4, qkv_bias=True, drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.1), decode_head=dict(type='SegformerHead', in_channels=[32, 64, 160, 256], in_index=[0, 1, 2, 3], channels=256, dropout_ratio=0.1, num_classes=3, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict(type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), train_cfg=dict(), test_cfg=dict(mode='whole')) |
# how to create a function
def greet():
print("Hello")
print("welcome, Edgar")
greet() # prints
greet() # prints(2)
greet() # prints(3)
# arguments and parameters
def greet(name): # name is a parameter
print('hello')
print('welcome, ', name)
greet('Edgar') # Edgar is the argument
# return
def greet(name):
if name == 'Edgar':
return
else:
print('hello')
print('welcome, ', name)
greet('Edgar')
# return values
def greet(name):
if name == 'Jose':
return 'Go away'
return "hello ", name, "Welcome to my app"
returned = greet('Edgar')
print(returned) | def greet():
print('Hello')
print('welcome, Edgar')
greet()
greet()
greet()
def greet(name):
print('hello')
print('welcome, ', name)
greet('Edgar')
def greet(name):
if name == 'Edgar':
return
else:
print('hello')
print('welcome, ', name)
greet('Edgar')
def greet(name):
if name == 'Jose':
return 'Go away'
return ('hello ', name, 'Welcome to my app')
returned = greet('Edgar')
print(returned) |
#! /usr/bin/env python3
"""
constants.py - Contains all constants used by the device manager
Author:
- Nidesh Chitrakar (nideshchitrakar@bennington.edu)
- Hoanh An (hoanhan@bennington.edu)
Date: 12/07/2017
"""
number_of_rows = 3 # total number rows of Index Servers
number_of_links = 5 # number of links to be sent to Crawler
number_of_chunks = 5 # number of chunks to be sent to Index Builder
number_of_comps = 10 # number of components managed by each watchdog | """
constants.py - Contains all constants used by the device manager
Author:
- Nidesh Chitrakar (nideshchitrakar@bennington.edu)
- Hoanh An (hoanhan@bennington.edu)
Date: 12/07/2017
"""
number_of_rows = 3
number_of_links = 5
number_of_chunks = 5
number_of_comps = 10 |
def convert_date_string_to_period(timestamp) -> int:
try:
month = int(timestamp.month)
except AttributeError:
return -1
else:
return month
| def convert_date_string_to_period(timestamp) -> int:
try:
month = int(timestamp.month)
except AttributeError:
return -1
else:
return month |
exe = "tester.exe"
toolchain = "msvc"
# optional
link_pool_depth = 1
# optional
builddir = {
"gnu" : "build"
, "msvc" : "build"
, "clang" : "build"
}
includes = {
"gnu" : [ "-I." ]
, "msvc" : [ "/I." ]
, "clang" : [ "-I." ]
}
defines = {
"gnu" : [ "-DEXAMPLE=1" ]
, "msvc" : [ "/DEXAMPLE=1" ]
, "clang" : [ "-DEXAMPLE=1" ]
}
cflags = {
"gnu" : [ "-O2", "-g" ]
, "msvc" : [ "/O2" ]
, "clang" : [ "-O2", "-g" ]
}
cxxflags = {
"gnu" : [ "-O2", "-g" ]
, "msvc" : [ "/O2", "/W4", "/EHsc"]
, "clang" : [ "-O2", "-g", "-fsanitize=address" ]
}
ldflags = {
"gnu" : [ ]
, "msvc" : [ ]
, "clang" : [ "-fsanitize=address" ]
}
# optionsl
cxx_files = [ "tester.cc" ]
c_files = [ ]
# You can register your own toolchain through register_toolchain function
def register_toolchain(ninja):
pass
| exe = 'tester.exe'
toolchain = 'msvc'
link_pool_depth = 1
builddir = {'gnu': 'build', 'msvc': 'build', 'clang': 'build'}
includes = {'gnu': ['-I.'], 'msvc': ['/I.'], 'clang': ['-I.']}
defines = {'gnu': ['-DEXAMPLE=1'], 'msvc': ['/DEXAMPLE=1'], 'clang': ['-DEXAMPLE=1']}
cflags = {'gnu': ['-O2', '-g'], 'msvc': ['/O2'], 'clang': ['-O2', '-g']}
cxxflags = {'gnu': ['-O2', '-g'], 'msvc': ['/O2', '/W4', '/EHsc'], 'clang': ['-O2', '-g', '-fsanitize=address']}
ldflags = {'gnu': [], 'msvc': [], 'clang': ['-fsanitize=address']}
cxx_files = ['tester.cc']
c_files = []
def register_toolchain(ninja):
pass |
# Problem: https://www.hackerrank.com/challenges/alphabet-rangoli/problem
def print_rangoli(size):
alorder = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
alorder = ''.join([i.lower() for i in alorder])
string, width , side_l, side_str = alorder[:size], (size-1)*4+1, [], ''
# top half
for i in range(size-1):
print((side_str + '-' + string[size-1-i] + '-' + side_str[::-1]).center(width,'-'))
side_l.append(string[size-1-i])
side_str = '-'.join(side_l)
# middle
if size == 1:
print(string[0])
else: print(side_str+'-'+string[0]+'-'+side_str[::-1])
# lower half
for i in range(size-1):
center_str = side_l.pop()
side_str = '-'.join(side_l)
print((side_str + '-' + center_str + '-' + side_str[::-1]).center(width,'-'))
n = int(input("Enter alphabet rangoli's size: "))
print_rangoli(n) | def print_rangoli(size):
alorder = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
alorder = ''.join([i.lower() for i in alorder])
(string, width, side_l, side_str) = (alorder[:size], (size - 1) * 4 + 1, [], '')
for i in range(size - 1):
print((side_str + '-' + string[size - 1 - i] + '-' + side_str[::-1]).center(width, '-'))
side_l.append(string[size - 1 - i])
side_str = '-'.join(side_l)
if size == 1:
print(string[0])
else:
print(side_str + '-' + string[0] + '-' + side_str[::-1])
for i in range(size - 1):
center_str = side_l.pop()
side_str = '-'.join(side_l)
print((side_str + '-' + center_str + '-' + side_str[::-1]).center(width, '-'))
n = int(input("Enter alphabet rangoli's size: "))
print_rangoli(n) |
# Cooling Settings
cool_circuit = \
{'label': 'Activate Cooling:', 'value': True, 'sticky': ['NW', 'NWE'],
'sim_name': ['stack', 'cool_flow'], 'type': 'CheckButtonSet',
'specifier': 'checklist_activate_cooling',
'command': {'function': 'set_status',
'args': [[[1, 0], [1, 1], [1, 2],
[2, 0], [2, 1], [2, 2],
[3, 0], [3, 1], [3, 2],
[4, 0], [4, 1], [4, 2],
[5, 0], [5, 1], [5, 2],
[6, 0], [6, 1], [6, 2],
[7, 0], [7, 1], [7, 2],
[8, 0], [8, 1], [8, 2]]]}}
# 'args2': [1, 2, 3, 4, 5, 6, 7]}}
cool_channel_length = \
{'label': 'Coolant Channel Length:', 'value': 0.4,
'sim_name': ['coolant_channel', 'length'], 'specifier': 'disabled_cooling',
'dtype': 'float', 'dimensions': 'm', 'type': 'EntrySet'}
cool_channel_height = \
{'label': 'Coolant Channel Height:', 'value': 1e-3,
'sim_name': ['coolant_channel', 'height'], 'specifier': 'disabled_cooling',
'dtype': 'float', 'dimensions': 'm', 'type': 'EntrySet'}
cool_channel_width = \
{'label': 'Coolant Channel Width:', 'value': 1e-3,
'sim_name': ['coolant_channel', 'width'], 'specifier': 'disabled_cooling',
'dtype': 'float', 'dimensions': 'm', 'type': 'EntrySet'}
cool_channel_number = \
{'label': 'Coolant Channel Number:', 'value': 2,
'sim_name': ['temperature_system', 'cool_ch_numb'],
'specifier': 'disabled_cooling', 'type': 'EntrySet'}
cool_channel_bends = \
{'label': 'Number of Coolant Channel Bends:', 'value': 0,
'sim_name': ['coolant_channel', 'bend_number'],
'specifier': 'disabled_cooling', 'type': 'EntrySet'}
cool_bend_pressure_loss_coefficient = \
{'label': 'Pressure Loss Coefficient for Coolant Channel Bend:',
'sim_name': ['coolant_channel', 'bend_friction_factor'],
'specifier': 'disabled_cooling', 'value': 0.5, 'dimensions': '-',
'type': 'EntrySet'}
cool_flow_end_cells = \
{'label': 'Activate Cooling Flow at End Plates:', 'value': False,
'sim_name': ['temperature_system', 'cool_ch_bc'],
'specifier': 'disabled_cooling',
'sticky': ['NW', 'NWE'], 'type': 'CheckButtonSet'}
channel_flow_direction = \
{'label': 'Channel Flow Direction (1 or -1):', 'value': 1,
'sim_name': ['coolant_channel', 'flow_direction'],
'specifier': 'disabled_cooling', 'dtype': 'int', 'type': 'EntrySet',
'sticky': ['NW', 'NWE']}
cool_frame_dict = \
{'title': 'Cooling Settings', 'show_title': False, 'font': 'Arial 10 bold',
'sticky': 'WEN', 'size_label': 'xl', 'size_unit': 's',
'widget_dicts': [cool_circuit, cool_channel_number,
cool_channel_length, cool_channel_height,
cool_channel_width, cool_channel_bends,
cool_bend_pressure_loss_coefficient,
channel_flow_direction,
cool_flow_end_cells],
# 'highlightbackground': 'grey', 'highlightthickness': 1
}
tab_dict = {'title': 'Cooling', 'show_title': False,
'sub_frame_dicts': [cool_frame_dict]}
# geometry_frame_dict = \
# {'title': 'Geometry', 'show_title': False, 'font': 'Arial 10 bold',
# 'sub_frame_dicts': [cool_frame_dict, manifold_frame_dict,
# cell_frame_dict],
# 'highlightbackground': 'grey', 'highlightthickness': 1}
# main_frame_dicts = [geometry_frame_dict, simulation_frame_dict]
| cool_circuit = {'label': 'Activate Cooling:', 'value': True, 'sticky': ['NW', 'NWE'], 'sim_name': ['stack', 'cool_flow'], 'type': 'CheckButtonSet', 'specifier': 'checklist_activate_cooling', 'command': {'function': 'set_status', 'args': [[[1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2], [3, 0], [3, 1], [3, 2], [4, 0], [4, 1], [4, 2], [5, 0], [5, 1], [5, 2], [6, 0], [6, 1], [6, 2], [7, 0], [7, 1], [7, 2], [8, 0], [8, 1], [8, 2]]]}}
cool_channel_length = {'label': 'Coolant Channel Length:', 'value': 0.4, 'sim_name': ['coolant_channel', 'length'], 'specifier': 'disabled_cooling', 'dtype': 'float', 'dimensions': 'm', 'type': 'EntrySet'}
cool_channel_height = {'label': 'Coolant Channel Height:', 'value': 0.001, 'sim_name': ['coolant_channel', 'height'], 'specifier': 'disabled_cooling', 'dtype': 'float', 'dimensions': 'm', 'type': 'EntrySet'}
cool_channel_width = {'label': 'Coolant Channel Width:', 'value': 0.001, 'sim_name': ['coolant_channel', 'width'], 'specifier': 'disabled_cooling', 'dtype': 'float', 'dimensions': 'm', 'type': 'EntrySet'}
cool_channel_number = {'label': 'Coolant Channel Number:', 'value': 2, 'sim_name': ['temperature_system', 'cool_ch_numb'], 'specifier': 'disabled_cooling', 'type': 'EntrySet'}
cool_channel_bends = {'label': 'Number of Coolant Channel Bends:', 'value': 0, 'sim_name': ['coolant_channel', 'bend_number'], 'specifier': 'disabled_cooling', 'type': 'EntrySet'}
cool_bend_pressure_loss_coefficient = {'label': 'Pressure Loss Coefficient for Coolant Channel Bend:', 'sim_name': ['coolant_channel', 'bend_friction_factor'], 'specifier': 'disabled_cooling', 'value': 0.5, 'dimensions': '-', 'type': 'EntrySet'}
cool_flow_end_cells = {'label': 'Activate Cooling Flow at End Plates:', 'value': False, 'sim_name': ['temperature_system', 'cool_ch_bc'], 'specifier': 'disabled_cooling', 'sticky': ['NW', 'NWE'], 'type': 'CheckButtonSet'}
channel_flow_direction = {'label': 'Channel Flow Direction (1 or -1):', 'value': 1, 'sim_name': ['coolant_channel', 'flow_direction'], 'specifier': 'disabled_cooling', 'dtype': 'int', 'type': 'EntrySet', 'sticky': ['NW', 'NWE']}
cool_frame_dict = {'title': 'Cooling Settings', 'show_title': False, 'font': 'Arial 10 bold', 'sticky': 'WEN', 'size_label': 'xl', 'size_unit': 's', 'widget_dicts': [cool_circuit, cool_channel_number, cool_channel_length, cool_channel_height, cool_channel_width, cool_channel_bends, cool_bend_pressure_loss_coefficient, channel_flow_direction, cool_flow_end_cells]}
tab_dict = {'title': 'Cooling', 'show_title': False, 'sub_frame_dicts': [cool_frame_dict]} |
class Solution:
# @param {integer} n
# @param {integer} k
# @return {string}
def getPermutation(self, n, k):
nums = [i+1 for i in xrange(n)]
facts = [0 for i in xrange(n)]
facts[0] = 1
for i in range(1,n):
facts[i] = i*facts[i-1]
k = k-1
res = []
for i in range(n,0,-1):
idx = k/facts[i-1]
k = k%facts[i-1]
res.append(nums[idx])
nums.pop(idx)
return ''.join([str(i) for i in res]) | class Solution:
def get_permutation(self, n, k):
nums = [i + 1 for i in xrange(n)]
facts = [0 for i in xrange(n)]
facts[0] = 1
for i in range(1, n):
facts[i] = i * facts[i - 1]
k = k - 1
res = []
for i in range(n, 0, -1):
idx = k / facts[i - 1]
k = k % facts[i - 1]
res.append(nums[idx])
nums.pop(idx)
return ''.join([str(i) for i in res]) |
# Python 3 compatibility (no longer includes `basestring`):
try:
basestring
except NameError:
basestring = str
class Item(object):
'''Common logic shared across all kinds of objects.'''
class UnknownAttributeError(ValueError):
def __init__(self, attributes):
super(Item.UnknownAttributeError, self).__init__(
"Unknown attributes: {0}".format(attributes))
COMMON_ATTRIBUTES = ('name', 'namespace', 'labels')
def __init__(self, config, info):
self._config = config
for attr in self.COMMON_ATTRIBUTES:
val = info.get(attr)
if not val and 'metadata' in info:
val = info['metadata'].get(attr)
if val:
setattr(self, attr, val)
def __repr__(self):
return '<{0}: {1}>'.format(
self.__class__.__name__,
' '.join('{0}={1}'.format(a, v) for a, v in self._simple_attrvals)
)
def attrvals(self, attributes):
unknown = set(attributes) - set(self.ATTRIBUTES)
if unknown:
raise self.UnknownAttributeError(unknown)
return ((a, getattr(self, a)) for a in attributes)
@property
def _simple_attrvals(self):
for attr in self.COMMON_ATTRIBUTES:
av = self._attrval_if_simple(attr)
if av:
yield av
for attr in self.PRIMARY_ATTRIBUTES:
if attr not in self.COMMON_ATTRIBUTES:
av = self._attrval_if_simple(attr)
if av:
yield av
def _attrval_if_simple(self, attr):
if hasattr(self, attr):
if not self._property(attr):
val = getattr(self, attr)
if self._simple(val):
return (attr, val)
@staticmethod
def _simple(val):
return isinstance(val, (basestring, int, float, None.__class__))
def _property(self, attr):
return isinstance(getattr(type(self), attr, None), property)
| try:
basestring
except NameError:
basestring = str
class Item(object):
"""Common logic shared across all kinds of objects."""
class Unknownattributeerror(ValueError):
def __init__(self, attributes):
super(Item.UnknownAttributeError, self).__init__('Unknown attributes: {0}'.format(attributes))
common_attributes = ('name', 'namespace', 'labels')
def __init__(self, config, info):
self._config = config
for attr in self.COMMON_ATTRIBUTES:
val = info.get(attr)
if not val and 'metadata' in info:
val = info['metadata'].get(attr)
if val:
setattr(self, attr, val)
def __repr__(self):
return '<{0}: {1}>'.format(self.__class__.__name__, ' '.join(('{0}={1}'.format(a, v) for (a, v) in self._simple_attrvals)))
def attrvals(self, attributes):
unknown = set(attributes) - set(self.ATTRIBUTES)
if unknown:
raise self.UnknownAttributeError(unknown)
return ((a, getattr(self, a)) for a in attributes)
@property
def _simple_attrvals(self):
for attr in self.COMMON_ATTRIBUTES:
av = self._attrval_if_simple(attr)
if av:
yield av
for attr in self.PRIMARY_ATTRIBUTES:
if attr not in self.COMMON_ATTRIBUTES:
av = self._attrval_if_simple(attr)
if av:
yield av
def _attrval_if_simple(self, attr):
if hasattr(self, attr):
if not self._property(attr):
val = getattr(self, attr)
if self._simple(val):
return (attr, val)
@staticmethod
def _simple(val):
return isinstance(val, (basestring, int, float, None.__class__))
def _property(self, attr):
return isinstance(getattr(type(self), attr, None), property) |
word = input().lower()
ans = []
vowels = ('a', 'i', 'u', 'e', 'o', 'y')
filtered_word = word
for i in word:
if i in vowels:
filtered_word = filtered_word.replace(i, "")
for i in filtered_word:
ans.append('.')
ans.append(i)
print(''.join(ans)) | word = input().lower()
ans = []
vowels = ('a', 'i', 'u', 'e', 'o', 'y')
filtered_word = word
for i in word:
if i in vowels:
filtered_word = filtered_word.replace(i, '')
for i in filtered_word:
ans.append('.')
ans.append(i)
print(''.join(ans)) |
def ft_map(function_to_apply, list_of_inputs):
return [function_to_apply(x) for x in list_of_inputs]
c = [0,1,2,3,4,5]
def add1(t):
return t+1
print(list(map(lambda x: x+1,c)))
print(ft_map(lambda x: x+1,c)) | def ft_map(function_to_apply, list_of_inputs):
return [function_to_apply(x) for x in list_of_inputs]
c = [0, 1, 2, 3, 4, 5]
def add1(t):
return t + 1
print(list(map(lambda x: x + 1, c)))
print(ft_map(lambda x: x + 1, c)) |
#!/bin/python2.7
#CLASS PARA VERIFICAR OS GRUPOS DE CONFLITO
class ScdGrupoConflito(object):
def __init__(self):
self.in_port = False
self.ip_src = False
self.ip_dst = False
self.dl_src = False
self.dl_dst = False
self.tp_src = False
self.tp_dst = False
self.dl_type = False
self.solucao = str("")
#CLASS PARA VERIFICAR SE OS CAMPOS SAO WILDCARDS
class ScdWildcards(object):
def __init__(self):
self.in_port = False
self.ip_src = False
self.ip_dst = False
self.dl_src = False
self.dl_dst = False
self.tp_src = False
self.tp_dst = False
self.dl_type = False
#CLASS PARA CONTAR O TOTAL DE WILDCARDS
class ScdWildcardsTotal(object):
def __init__(self):
self.in_port = 0
self.ip = 0
self.dl = 0
self.tp = 0
class ScdRegraGenerica(object):
def __init__(self):
self.in_port = False
self.ip = False
self.dl = False
self.tp = False
class ScdSugestao(object):
def __init__(self):
self.sugestao_resolucao = None
self.nivel_conflito = 0
#QUANTO AO NIVEL, DEFINIDO COMO
# 0 - Nenhum
# 1 - Medio
# 2 - Alto
def analise_Conflito(pscd_rule_1, pscd_rule_2):
# Inicia a verificacao das rules
##DECLARACAO DAS VARIAVEIS UTILIZADAS NA FUNCTION
grp_conflito = ScdGrupoConflito()
wildcards_rule_1 = ScdWildcards()
wildcards_rule_2 = ScdWildcards()
wildcards_total_1 = ScdWildcardsTotal()
wildcards_total_2 = ScdWildcardsTotal()
regra_generica = ScdRegraGenerica()
sugestao = ScdSugestao()
#print "Iniciando verificacao de Conflitos"
#print "################################################"
#PRIMEIRO VERIFICA SE SAO DO MESMA SWITCH
if pscd_rule_1.switch == pscd_rule_2.switch:
#VERIFICA SE SAO DA MESMA PORTA DE ENTRADA E DO MESMO TIPO (DL_TYPE)
if pscd_rule_1.dl_type != pscd_rule_2.dl_type:
#print "REGRAS NAO SAO DO MESMO DL_TYPE"
return sugestao
else:
#print "REGRAS SAO DO MESMO DL_TYPE"
grp_conflito.dl_type = True
#print "------------------------------------"
#print "----> VERIFICA IN_PORT - GRUPO 1"
#print "------------------------------------"
#SE UMA DAS IN_PORT FOR WILDCARD OU AS DUAS FOREM IGUAIS, PROSSEGUE
if (((pscd_rule_1.in_port == None) and (pscd_rule_2.in_port == None)) or (pscd_rule_1.in_port == pscd_rule_2.in_port)):
if (pscd_rule_1.in_port == None):
#print "IN_PORT 1 EH WILDCARD"
grp_conflito.in_port = True
if (pscd_rule_2.in_port == None):
#print "IN_PORT 2 EH WILDCARD"
grp_conflito.in_port = True
if (pscd_rule_1.in_port == pscd_rule_2.in_port):
#print "IN_PORT IGUAIS"
grp_conflito.in_port = True
#print ("Conflito Grupo 1: %s" %grp_conflito.in_port)
####FIM GRUPO 1
## Verifica IP_SRC e IP_DST - GRUPO 2
###################################
#print "------------------------------------"
#print "----> GRUPO 2 - VERIFICA IP SRC/DST"
#print "------------------------------------"
##IP_SRC
if pscd_rule_1.nw_src == pscd_rule_2.nw_src:
#print "GRUPO 2 - IP_SRC iguais"
grp_conflito.ip_src = True
if pscd_rule_1.nw_src == None and pscd_rule_2.nw_src == None:
#print "GRUPO 2 - IP_SRC 1 e 2 Wildcards"
wildcards_rule_1.ip_src = True
wildcards_rule_2.ip_src = True
else:
if pscd_rule_1.nw_src == None:
#print "GRUPO 2 - IP_SRC 1 Wildcard"
grp_conflito.ip_src = True
wildcards_rule_1.ip_src = True
if pscd_rule_2.nw_src == None:
#print "GRUPO 2 - IP_SRC 2 Wildcard"
grp_conflito.ip_src = True
wildcards_rule_2.ip_src = True
elif pscd_rule_1.nw_src is not None and pscd_rule_2.nw_src is not None:
mask = 0
if pscd_rule_1.nw_src[0] == pscd_rule_2.nw_src[0]:
if pscd_rule_1.nw_src[1] == pscd_rule_2.nw_src[1]:
if pscd_rule_1.nw_src[2] == pscd_rule_2.nw_src[2]:
if pscd_rule_1.nw_src[3] == pscd_rule_2.nw_src[3]:
mask = 1
else:
if pscd_rule_1.nw_src[3] == 0: mask = 1
elif pscd_rule_2.nw_src[3] == 0: mask = 1
else:
if pscd_rule_1.nw_src[2] == 0 and pscd_rule_1.nw_src[3] == 0: mask = 1
elif pscd_rule_2.nw_src[2] == 0 and pscd_rule_2.nw_src[3] == 0: mask = 1
else:
if pscd_rule_1.nw_src[1] == 0 and pscd_rule_1.nw_src[2] == 0 and pscd_rule_1.nw_src[3] == 0: mask = 1
elif pscd_rule_2.nw_src[1] == 0 and pscd_rule_2.nw_src[2] == 0 and pscd_rule_2.nw_src[3] == 0: mask = 1
else:
if pscd_rule_1.nw_src[0] == 0 and pscd_rule_1.nw_src[1] == 0 and pscd_rule_1.nw_src[2] == 0 and pscd_rule_1.nw_src[3] == 0: mask = 1
elif pscd_rule_2.nw_src[0] == 0 and pscd_rule_2.nw_src[1] == 0 and pscd_rule_2.nw_src[2] == 0 and pscd_rule_2.nw_src[3] == 0: mask = 1
if mask > 0: grp_conflito.ip_src = True
#print ("Net_Mask SRC: %s" % mask)
##IP_DST
if pscd_rule_1.nw_dst == pscd_rule_2.nw_dst:
#print "GRUPO 2 - IP_DST iguais"
grp_conflito.ip_dst = True
if pscd_rule_1.nw_dst == None and pscd_rule_2.nw_dst == None:
#print "GRUPO 2 - IP_DST 1 e 2 Wildcards"
wildcards_rule_1.ip_dst = True
wildcards_rule_2.ip_dst = True
else:
if pscd_rule_1.nw_dst == None:
#print "GRUPO 2 - IP_DST 1 Wildcard"
grp_conflito.ip_dst = True
wildcards_rule_1.ip_dst = True
if pscd_rule_2.nw_dst == None:
#print "GRUPO 2 - IP_DST 2 Wildcard"
grp_conflito.ip_dst = True
wildcards_rule_2.ip_dst = True
elif pscd_rule_1.nw_dst is not None and pscd_rule_2.nw_dst is not None:
mask = 0
if pscd_rule_1.nw_dst[0] == pscd_rule_2.nw_dst[0]:
if pscd_rule_1.nw_dst[1] == pscd_rule_2.nw_dst[1]:
if pscd_rule_1.nw_dst[2] == pscd_rule_2.nw_dst[2]:
if pscd_rule_1.nw_dst[3] == pscd_rule_2.nw_dst[3]:
mask = 1
else:
if pscd_rule_1.nw_dst[3] == 0: mask = 1
elif pscd_rule_2.nw_dst[3] == 0: mask = 1
else:
if pscd_rule_1.nw_dst[2] == 0 and pscd_rule_1.nw_dst[3] == 0: mask = 1
elif pscd_rule_2.nw_dst[2] == 0 and pscd_rule_2.nw_dst[3] == 0: mask = 1
else:
if pscd_rule_1.nw_dst[1] == 0 and pscd_rule_1.nw_dst[2] == 0 and pscd_rule_1.nw_dst[3] == 0: mask = 1
elif pscd_rule_2.nw_dst[1] == 0 and pscd_rule_2.nw_dst[2] == 0 and pscd_rule_2.nw_dst[3] == 0: mask = 1
else:
if pscd_rule_1.nw_dst[0] == 0 and pscd_rule_1.nw_dst[1] == 0 and pscd_rule_1.nw_dst[2] == 0 and pscd_rule_1.nw_dst[3] == 0: mask = 1
elif pscd_rule_2.nw_dst[0] == 0 and pscd_rule_2.nw_dst[1] == 0 and pscd_rule_2.nw_dst[2] == 0 and pscd_rule_2.nw_dst[3] == 0: mask = 1
if mask > 0: grp_conflito.ip_dst = True
#print ("Net_Mask dst: %s" % mask)
######FIM GRUPO 2
#Verifica MAC_SRC e MAC_DST - GRUPO 3
#####################################
#print "------------------------------------"
#print "----> GRUPO 3 - VERIFICA MAC SRC/DST"
#print "------------------------------------"
#ANALISA OS DOIS MAC
if pscd_rule_1.dl_src != None and pscd_rule_2.dl_src != None and pscd_rule_1.dl_dst != None and pscd_rule_2.dl_dst != None:
if pscd_rule_1.dl_src == pscd_rule_2.dl_src and pscd_rule_1.dl_dst != pscd_rule_2.dl_dst:
grp_conflito.dl_dst = False
grp_conflito.dl_src = False
if pscd_rule_1.dl_src != pscd_rule_2.dl_src and pscd_rule_1.dl_dst == pscd_rule_2.dl_dst:
grp_conflito.dl_dst = False
grp_conflito.dl_src = False
else:
# MAC SRC
if pscd_rule_1.dl_src == pscd_rule_2.dl_src:
#print "GRUPO 3 - DL_SRC iguais"
grp_conflito.dl_src = True
if pscd_rule_1.dl_src == None: wildcards_rule_1.dl_src = True
if pscd_rule_2.dl_src == None: wildcards_rule_2.dl_src = True
else:
if pscd_rule_1.dl_src == None:
#print "GRUPO 3 - DL_SRC 1 Wildcard"
grp_conflito.dl_src = True
wildcards_rule_1.dl_src = True
else:
if pscd_rule_2.dl_src == None:
#print "GRUPO 3 - DL_SRC 2 Wildcard"
grp_conflito.dl_src = True
wildcards_rule_2.dl_src = True
# MAC DST
if pscd_rule_1.dl_dst == pscd_rule_2.dl_dst:
#print "GRUPO 3 - DL_DST iguais"
grp_conflito.dl_dst = True
if pscd_rule_1.dl_dst == None: wildcards_rule_1.dl_dst = True
if pscd_rule_2.dl_dst == None: wildcards_rule_2.dl_dst = True
else:
if pscd_rule_1.dl_dst == None:
#print "GRUPO 3 - DL_DST 1 Wildcard"
grp_conflito.dl_dst = True
wildcards_rule_1.dl_dst = True
else:
if pscd_rule_2.dl_dst == None:
#print "GRUPO 3 - DL_DST 2 Wildcard"
grp_conflito.dl_dst = True
wildcards_rule_2.dl_dst = True
#print ("Conflito Grupo 3: MAC_SRC: %s MAC_DST: %s" % (grp_conflito.dl_src, grp_conflito.dl_dst))
####FIM GRUPO 3
# Verifica TP_SRC e TP_DST - GRUPO 4
#print "------------------------------------"
#print "----> GRUPO 4 - VERIFICA PORTA TCP/UDP SRC/DST"
#print "------------------------------------"
#PRIMEIRO, VERIFICAMOS SE O PROTOCOLO EH IP/TCP/UDP/SCTP, VIDE COMENTARIO NO SCRIPT COLETOR
#ANALISA SOMENTE UMA DAS REGRAS, POIS AS DUAS JA PASSARAM PELO TESTE DE IGUALDADE
if (pscd_rule_1.dl_type =="ip" or pscd_rule_1.dl_type =="tcp" or pscd_rule_1.dl_type =="udp" or pscd_rule_1.dl_type =="sctp"):
# PORTA TCP/UDP SRC
if pscd_rule_1.tp_src == pscd_rule_2.tp_src:
#print "GRUPO 4 - TP_SRC iguais"
grp_conflito.tp_src = True
else:
if pscd_rule_1.tp_src == None:
#print "GRUPO 4 - TP_SRC 1 Wildcard"
grp_conflito.tp_src = True
wildcards_rule_1.tp_src = True
else:
if pscd_rule_2.tp_src == None:
#print "GRUPO 4 - TP_SRC 2 Wildcard"
grp_conflito.tp_src = True
wildcards_rule_2.tp_src = True
# PORTA TCP/UDP DST
if pscd_rule_1.tp_dst == pscd_rule_2.tp_dst:
#print "GRUPO 4 - TP_DST iguais"
grp_conflito.tp_dst = True
else:
if pscd_rule_1.tp_dst == None:
#print "GRUPO 4 - TP_DST 1 Wildcard"
grp_conflito.tp_dst = True
wildcards_rule_2.tp_dst = True
else:
if pscd_rule_2.tp_dst == None:
#print "GRUPO 4 - TP_DST 2 Wildcard"
grp_conflito.tp_dst = True
wildcards_rule_2.tp_dst = True
#print ("Conflito Grupo 4: TP_SRC: %s TP_DST: %s" % (grp_conflito.tp_dst, grp_conflito.tp_dst))
#print ("----------------------------")
#print ("RESULTADO DAS ANALISES:")
#print ("----------------------------")
#print ("Grupo Conflitos: %s" % grp_conflito.__dict__)
#print ("Wildcards Regra 1: %s" % wildcards_rule_1.__dict__)
#print ("Wildcards Regra 2: %s" % wildcards_rule_2.__dict__)
#print ("----------------------------")
#print ("----------------------------")
##Conta os WildCards
#REGRA 1
if wildcards_rule_1.in_port == True: wildcards_total_1.in_port += 1
if wildcards_rule_1.dl_src == True: wildcards_total_1.dl += 1
if wildcards_rule_1.dl_dst == True: wildcards_total_1.dl += 1
if wildcards_rule_1.ip_dst == True: wildcards_total_1.ip += 1
if wildcards_rule_1.ip_src == True: wildcards_total_1.ip += 1
if wildcards_rule_1.tp_dst == True: wildcards_total_1.tp += 1
if wildcards_rule_1.tp_src == True: wildcards_total_1.tp += 1
#REGRA 2
if wildcards_rule_2.in_port == True: wildcards_total_2.in_port += 1
if wildcards_rule_2.dl_src == True: wildcards_total_2.dl += 1
if wildcards_rule_2.dl_dst == True: wildcards_total_2.dl += 1
if wildcards_rule_2.ip_dst == True: wildcards_total_2.ip += 1
if wildcards_rule_2.ip_src == True: wildcards_total_2.ip += 1
if wildcards_rule_2.tp_dst == True: wildcards_total_2.tp += 1
if wildcards_rule_2.tp_src == True: wildcards_total_2.tp += 1
#Compara as regras para ver se a regra 1 eh a mais generica
if wildcards_total_1.in_port > wildcards_total_2.in_port: regra_generica.in_port = True
if wildcards_total_1.ip > wildcards_total_2.ip: regra_generica.ip = True
if wildcards_total_1.dl > wildcards_total_2.dl: regra_generica.dl = True
if wildcards_total_1.tp > wildcards_total_2.tp: regra_generica.tp = True
generica_count = 0
if regra_generica.in_port==True: generica_count += 1
if regra_generica.ip==True: generica_count += 1
if regra_generica.tp==True: generica_count += 1
if regra_generica.dl==True: generica_count += 1
#if generica_count >= 3: print ("Regra 1 eh a mais Generica: %s" %generica_count)
#elif generica_count == 2: print ("Regras Genericas: %s" %generica_count)
#else: print ("Regra 2 eh a mais Generica: %s" %generica_count)
####### FAZ A DECISAO FINAL PARA VER SE AS REGRAS CONFLITAM
grupo_2 = 0
grupo_3 = 0
grupo_4 = 0
if grp_conflito.ip_src == True: grupo_2 += 1
if grp_conflito.ip_dst == True: grupo_2 += 1
if grp_conflito.dl_src == True: grupo_3 += 1
if grp_conflito.dl_dst == True: grupo_3 += 1
if grp_conflito.tp_src == True: grupo_4 += 1
if grp_conflito.tp_dst == True: grupo_4 += 1
#Conflita Totalmente
if (grupo_2 == 2) and (grupo_3 == 2) and (grupo_4 == 2):
#print "Conflitam em IP, MAC e TCP"
#COMO CONFLITA COM TUDO, VERIFICAR A PRIORIDADE E A QUANTIDADE DE WILDCARDS
if (pscd_rule_1.priority > pscd_rule_2.priority) and (generica_count >= 3):
sugestao.sugestao_resolucao = ("Voce pode alterar a prioridade da Regra. Ela eh a mais generica e sobreescreve a Regra %s!"%pscd_rule_2.flow_id)
elif (pscd_rule_1.priority > pscd_rule_2.priority) and (generica_count == 2):
sugestao.sugestao_resolucao = "Voce pode alterar a prioridade da Regra. As duas regras sao genericas!"
elif generica_count < 2:
sugestao.sugestao_resolucao = "Possuem caracteristicas de IP, MAC E TCP muito semelhantes. Confira estes campos!"
sugestao.nivel_conflito = 2
#Conflitos Parciais
elif (grupo_2 == 1) and (grupo_3 == 2) and (grupo_4 == 2):
#print "Conflitam em IP/Parcialmente, MAC e TCP"
#Analisa IP para ver qual eh wildcard
if wildcards_rule_1.ip_src == True and (pscd_rule_1.priority > pscd_rule_2.priority):
sugestao.sugestao_resolucao = "Verifique o IP de Origem da Regra. Estah bem generico"
sugestao.nivel_conflito = 2
elif wildcards_rule_2.ip_src == True and (pscd_rule_1.priority > pscd_rule_2.priority):
sugestao.sugestao_resolucao = ("Verifique o IP de Origem da Regra %s. Estah bem generico"%pscd_rule_2.flow_id)
sugestao.nivel_conflito = 2
elif wildcards_rule_1.ip_dst == True and (pscd_rule_1.priority > pscd_rule_2.priority):
sugestao.sugestao_resolucao = "Verifique o IP de Destino da Regra. Estah bem generico"
sugestao.nivel_conflito = 2
elif wildcards_rule_2.ip_dst == True and (pscd_rule_1.priority > pscd_rule_2.priority):
sugestao.sugestao_resolucao = ("Verifique o IP de Destino da Regra %s. Estah bem generico"%pscd_rule_2.flow_id)
sugestao.nivel_conflito = 2
else:
sugestao.sugestao_resolucao = "Verifique o IP das Regras. Grande probabilidade de conflito em MAC e Portas TCP"
sugestao.nivel_conflito = 2
##COMPARA QUANDO FOR UMA REGRA TCP
elif (pscd_rule_1.dl_type =="ip" or pscd_rule_1.dl_type =="tcp" or pscd_rule_1.dl_type =="udp" or pscd_rule_1.dl_type =="sctp") and (grupo_2==2) and (grupo_4==2):
sugestao.sugestao_resolucao = "Regra TCP. Os Campos IP e Portas TCP/UDP estao bem genericos."
sugestao.nivel_conflito = 2
elif (pscd_rule_1.dl_type =="ip" or pscd_rule_1.dl_type =="tcp" or pscd_rule_1.dl_type =="udp" or pscd_rule_1.dl_type =="sctp") and (grupo_2==1) and (grupo_4==2):
sugestao.sugestao_resolucao = "Regra TCP. As Portas TCP/UDP estao bem genericos. Confira tambem os Campos IP, podem vir a conflitar."
sugestao.nivel_conflito = 2
elif (pscd_rule_1.dl_type =="ip" or pscd_rule_1.dl_type =="tcp" or pscd_rule_1.dl_type =="udp" or pscd_rule_1.dl_type =="sctp") and (grupo_2==2) and (grupo_4==1):
sugestao.sugestao_resolucao = "Regra TCP. Os Campos IP estao bem generico. Confira tambem as Portas TCP/UDP, podem vir a conflitar."
sugestao.nivel_conflito = 2
elif (grupo_2 == 1) and (grupo_3 == 1) and (pscd_rule_1.dl_type =="arp" or pscd_rule_1.dl_type =="rarp" or pscd_rule_1.dl_type =="icmp"):
sugestao.sugestao_resolucao = ("Em regras %s, voce pode verificar os campos IP e MAC. Algum deles estah bem generico."%pscd_rule_1.dl_type)
sugestao.nivel_conflito = 1
elif (grupo_2 == 2) and (grupo_3 == 2) and (pscd_rule_1.dl_type =="arp" or pscd_rule_1.dl_type =="rarp" or pscd_rule_1.dl_type =="icmp"):
sugestao.sugestao_resolucao = ("Em regras %s, voce pode verificar os campos IP e MAC que estao bem genericos."%pscd_rule_1.dl_type)
sugestao.nivel_conflito = 2
elif (grupo_2 == 1) and (grupo_3 == 2) and (pscd_rule_1.dl_type =="arp" or pscd_rule_1.dl_type =="rarp" or pscd_rule_1.dl_type =="icmp"):
sugestao.sugestao_resolucao = ("Em regras %s, voce pode verificar os campos MAC que estao bem genericos."%pscd_rule_1.dl_type)
sugestao.nivel_conflito = 2
#elif (grupo_2 == 2) and (grupo_3 == 0) and (pscd_rule_1.dl_type =="arp" or pscd_rule_1.dl_type =="rarp" or pscd_rule_1.dl_type =="icmp"):
# sugestao.sugestao_resolucao = ("Em regras %s, voce pode verificar os campos IP que estao bem genericos."%pscd_rule_1.dl_type)
# sugestao.nivel_conflito = 2
elif (grupo_2 == 2) and (grupo_3 == 1) and (grupo_4 == 2):
#print "Conflitam em IP, MAC/Parcialmente e TCP"
sugestao.sugestao_resolucao = "Verifique os campos de IP e Portas TCP/UDP das Regras. Estao bem Genericos"
sugestao.nivel_conflito = 2
elif (grupo_2 == 2) and (grupo_3 == 2) and (grupo_4 == 1):
#print "Conflitam em IP, MAC e TCP/Parcialmente"
sugestao.sugestao_resolucao = "Verifique os campos de IP e MAC das Regras. Estao bem Genericos"
sugestao.nivel_conflito = 2
elif (grupo_2 == 2) and (grupo_3 == 1) and (grupo_4 == 1):
#print "Conflitam em IP, MAC/Parcialmente e TCP/Parcialmente"
sugestao.sugestao_resolucao = "Verifique os campos de IP das Regras. Estao bem Genericos. Os campos de Porta TCP/UDP e MAC tambem podem vir a conflitar!"
sugestao.nivel_conflito = 1
elif (grupo_2 == 1) and (grupo_3 == 2) and (grupo_4 == 1):
#print "Conflitam em IP/Parcialmente, MAC e TCP/Parcialmente"
sugestao.sugestao_resolucao = "Verifique os campos de MAC das Regras. Estao bem Genericos. Os campos de IP e Porta TCP/UDP tambem podem vir a conflitar!"
sugestao.nivel_conflito = 1
elif (grupo_2 == 1) and (grupo_3 == 1) and (grupo_4 == 2):
#print "Conflitam em IP/Parcialmente, MAC/Parcialmente e TCP"
sugestao.sugestao_resolucao = "Verifique os campos de Portas TCP/UDP das Regras. Estao bem Genericos. Os campos de IP e MAC tambem podem vir a conflitar!"
sugestao.nivel_conflito = 1
return sugestao
#SE NAO, ASSUME QUE NAO EH CONFLITO
else:
#print "IN_PORT DIFERENTES, NAO EH CONLITO"
return sugestao
else:
return sugestao | class Scdgrupoconflito(object):
def __init__(self):
self.in_port = False
self.ip_src = False
self.ip_dst = False
self.dl_src = False
self.dl_dst = False
self.tp_src = False
self.tp_dst = False
self.dl_type = False
self.solucao = str('')
class Scdwildcards(object):
def __init__(self):
self.in_port = False
self.ip_src = False
self.ip_dst = False
self.dl_src = False
self.dl_dst = False
self.tp_src = False
self.tp_dst = False
self.dl_type = False
class Scdwildcardstotal(object):
def __init__(self):
self.in_port = 0
self.ip = 0
self.dl = 0
self.tp = 0
class Scdregragenerica(object):
def __init__(self):
self.in_port = False
self.ip = False
self.dl = False
self.tp = False
class Scdsugestao(object):
def __init__(self):
self.sugestao_resolucao = None
self.nivel_conflito = 0
def analise__conflito(pscd_rule_1, pscd_rule_2):
grp_conflito = scd_grupo_conflito()
wildcards_rule_1 = scd_wildcards()
wildcards_rule_2 = scd_wildcards()
wildcards_total_1 = scd_wildcards_total()
wildcards_total_2 = scd_wildcards_total()
regra_generica = scd_regra_generica()
sugestao = scd_sugestao()
if pscd_rule_1.switch == pscd_rule_2.switch:
if pscd_rule_1.dl_type != pscd_rule_2.dl_type:
return sugestao
else:
grp_conflito.dl_type = True
if pscd_rule_1.in_port == None and pscd_rule_2.in_port == None or pscd_rule_1.in_port == pscd_rule_2.in_port:
if pscd_rule_1.in_port == None:
grp_conflito.in_port = True
if pscd_rule_2.in_port == None:
grp_conflito.in_port = True
if pscd_rule_1.in_port == pscd_rule_2.in_port:
grp_conflito.in_port = True
if pscd_rule_1.nw_src == pscd_rule_2.nw_src:
grp_conflito.ip_src = True
if pscd_rule_1.nw_src == None and pscd_rule_2.nw_src == None:
wildcards_rule_1.ip_src = True
wildcards_rule_2.ip_src = True
else:
if pscd_rule_1.nw_src == None:
grp_conflito.ip_src = True
wildcards_rule_1.ip_src = True
if pscd_rule_2.nw_src == None:
grp_conflito.ip_src = True
wildcards_rule_2.ip_src = True
elif pscd_rule_1.nw_src is not None and pscd_rule_2.nw_src is not None:
mask = 0
if pscd_rule_1.nw_src[0] == pscd_rule_2.nw_src[0]:
if pscd_rule_1.nw_src[1] == pscd_rule_2.nw_src[1]:
if pscd_rule_1.nw_src[2] == pscd_rule_2.nw_src[2]:
if pscd_rule_1.nw_src[3] == pscd_rule_2.nw_src[3]:
mask = 1
elif pscd_rule_1.nw_src[3] == 0:
mask = 1
elif pscd_rule_2.nw_src[3] == 0:
mask = 1
elif pscd_rule_1.nw_src[2] == 0 and pscd_rule_1.nw_src[3] == 0:
mask = 1
elif pscd_rule_2.nw_src[2] == 0 and pscd_rule_2.nw_src[3] == 0:
mask = 1
elif pscd_rule_1.nw_src[1] == 0 and pscd_rule_1.nw_src[2] == 0 and (pscd_rule_1.nw_src[3] == 0):
mask = 1
elif pscd_rule_2.nw_src[1] == 0 and pscd_rule_2.nw_src[2] == 0 and (pscd_rule_2.nw_src[3] == 0):
mask = 1
elif pscd_rule_1.nw_src[0] == 0 and pscd_rule_1.nw_src[1] == 0 and (pscd_rule_1.nw_src[2] == 0) and (pscd_rule_1.nw_src[3] == 0):
mask = 1
elif pscd_rule_2.nw_src[0] == 0 and pscd_rule_2.nw_src[1] == 0 and (pscd_rule_2.nw_src[2] == 0) and (pscd_rule_2.nw_src[3] == 0):
mask = 1
if mask > 0:
grp_conflito.ip_src = True
if pscd_rule_1.nw_dst == pscd_rule_2.nw_dst:
grp_conflito.ip_dst = True
if pscd_rule_1.nw_dst == None and pscd_rule_2.nw_dst == None:
wildcards_rule_1.ip_dst = True
wildcards_rule_2.ip_dst = True
else:
if pscd_rule_1.nw_dst == None:
grp_conflito.ip_dst = True
wildcards_rule_1.ip_dst = True
if pscd_rule_2.nw_dst == None:
grp_conflito.ip_dst = True
wildcards_rule_2.ip_dst = True
elif pscd_rule_1.nw_dst is not None and pscd_rule_2.nw_dst is not None:
mask = 0
if pscd_rule_1.nw_dst[0] == pscd_rule_2.nw_dst[0]:
if pscd_rule_1.nw_dst[1] == pscd_rule_2.nw_dst[1]:
if pscd_rule_1.nw_dst[2] == pscd_rule_2.nw_dst[2]:
if pscd_rule_1.nw_dst[3] == pscd_rule_2.nw_dst[3]:
mask = 1
elif pscd_rule_1.nw_dst[3] == 0:
mask = 1
elif pscd_rule_2.nw_dst[3] == 0:
mask = 1
elif pscd_rule_1.nw_dst[2] == 0 and pscd_rule_1.nw_dst[3] == 0:
mask = 1
elif pscd_rule_2.nw_dst[2] == 0 and pscd_rule_2.nw_dst[3] == 0:
mask = 1
elif pscd_rule_1.nw_dst[1] == 0 and pscd_rule_1.nw_dst[2] == 0 and (pscd_rule_1.nw_dst[3] == 0):
mask = 1
elif pscd_rule_2.nw_dst[1] == 0 and pscd_rule_2.nw_dst[2] == 0 and (pscd_rule_2.nw_dst[3] == 0):
mask = 1
elif pscd_rule_1.nw_dst[0] == 0 and pscd_rule_1.nw_dst[1] == 0 and (pscd_rule_1.nw_dst[2] == 0) and (pscd_rule_1.nw_dst[3] == 0):
mask = 1
elif pscd_rule_2.nw_dst[0] == 0 and pscd_rule_2.nw_dst[1] == 0 and (pscd_rule_2.nw_dst[2] == 0) and (pscd_rule_2.nw_dst[3] == 0):
mask = 1
if mask > 0:
grp_conflito.ip_dst = True
if pscd_rule_1.dl_src != None and pscd_rule_2.dl_src != None and (pscd_rule_1.dl_dst != None) and (pscd_rule_2.dl_dst != None):
if pscd_rule_1.dl_src == pscd_rule_2.dl_src and pscd_rule_1.dl_dst != pscd_rule_2.dl_dst:
grp_conflito.dl_dst = False
grp_conflito.dl_src = False
if pscd_rule_1.dl_src != pscd_rule_2.dl_src and pscd_rule_1.dl_dst == pscd_rule_2.dl_dst:
grp_conflito.dl_dst = False
grp_conflito.dl_src = False
else:
if pscd_rule_1.dl_src == pscd_rule_2.dl_src:
grp_conflito.dl_src = True
if pscd_rule_1.dl_src == None:
wildcards_rule_1.dl_src = True
if pscd_rule_2.dl_src == None:
wildcards_rule_2.dl_src = True
elif pscd_rule_1.dl_src == None:
grp_conflito.dl_src = True
wildcards_rule_1.dl_src = True
elif pscd_rule_2.dl_src == None:
grp_conflito.dl_src = True
wildcards_rule_2.dl_src = True
if pscd_rule_1.dl_dst == pscd_rule_2.dl_dst:
grp_conflito.dl_dst = True
if pscd_rule_1.dl_dst == None:
wildcards_rule_1.dl_dst = True
if pscd_rule_2.dl_dst == None:
wildcards_rule_2.dl_dst = True
elif pscd_rule_1.dl_dst == None:
grp_conflito.dl_dst = True
wildcards_rule_1.dl_dst = True
elif pscd_rule_2.dl_dst == None:
grp_conflito.dl_dst = True
wildcards_rule_2.dl_dst = True
if pscd_rule_1.dl_type == 'ip' or pscd_rule_1.dl_type == 'tcp' or pscd_rule_1.dl_type == 'udp' or (pscd_rule_1.dl_type == 'sctp'):
if pscd_rule_1.tp_src == pscd_rule_2.tp_src:
grp_conflito.tp_src = True
elif pscd_rule_1.tp_src == None:
grp_conflito.tp_src = True
wildcards_rule_1.tp_src = True
elif pscd_rule_2.tp_src == None:
grp_conflito.tp_src = True
wildcards_rule_2.tp_src = True
if pscd_rule_1.tp_dst == pscd_rule_2.tp_dst:
grp_conflito.tp_dst = True
elif pscd_rule_1.tp_dst == None:
grp_conflito.tp_dst = True
wildcards_rule_2.tp_dst = True
elif pscd_rule_2.tp_dst == None:
grp_conflito.tp_dst = True
wildcards_rule_2.tp_dst = True
if wildcards_rule_1.in_port == True:
wildcards_total_1.in_port += 1
if wildcards_rule_1.dl_src == True:
wildcards_total_1.dl += 1
if wildcards_rule_1.dl_dst == True:
wildcards_total_1.dl += 1
if wildcards_rule_1.ip_dst == True:
wildcards_total_1.ip += 1
if wildcards_rule_1.ip_src == True:
wildcards_total_1.ip += 1
if wildcards_rule_1.tp_dst == True:
wildcards_total_1.tp += 1
if wildcards_rule_1.tp_src == True:
wildcards_total_1.tp += 1
if wildcards_rule_2.in_port == True:
wildcards_total_2.in_port += 1
if wildcards_rule_2.dl_src == True:
wildcards_total_2.dl += 1
if wildcards_rule_2.dl_dst == True:
wildcards_total_2.dl += 1
if wildcards_rule_2.ip_dst == True:
wildcards_total_2.ip += 1
if wildcards_rule_2.ip_src == True:
wildcards_total_2.ip += 1
if wildcards_rule_2.tp_dst == True:
wildcards_total_2.tp += 1
if wildcards_rule_2.tp_src == True:
wildcards_total_2.tp += 1
if wildcards_total_1.in_port > wildcards_total_2.in_port:
regra_generica.in_port = True
if wildcards_total_1.ip > wildcards_total_2.ip:
regra_generica.ip = True
if wildcards_total_1.dl > wildcards_total_2.dl:
regra_generica.dl = True
if wildcards_total_1.tp > wildcards_total_2.tp:
regra_generica.tp = True
generica_count = 0
if regra_generica.in_port == True:
generica_count += 1
if regra_generica.ip == True:
generica_count += 1
if regra_generica.tp == True:
generica_count += 1
if regra_generica.dl == True:
generica_count += 1
grupo_2 = 0
grupo_3 = 0
grupo_4 = 0
if grp_conflito.ip_src == True:
grupo_2 += 1
if grp_conflito.ip_dst == True:
grupo_2 += 1
if grp_conflito.dl_src == True:
grupo_3 += 1
if grp_conflito.dl_dst == True:
grupo_3 += 1
if grp_conflito.tp_src == True:
grupo_4 += 1
if grp_conflito.tp_dst == True:
grupo_4 += 1
if grupo_2 == 2 and grupo_3 == 2 and (grupo_4 == 2):
if pscd_rule_1.priority > pscd_rule_2.priority and generica_count >= 3:
sugestao.sugestao_resolucao = 'Voce pode alterar a prioridade da Regra. Ela eh a mais generica e sobreescreve a Regra %s!' % pscd_rule_2.flow_id
elif pscd_rule_1.priority > pscd_rule_2.priority and generica_count == 2:
sugestao.sugestao_resolucao = 'Voce pode alterar a prioridade da Regra. As duas regras sao genericas!'
elif generica_count < 2:
sugestao.sugestao_resolucao = 'Possuem caracteristicas de IP, MAC E TCP muito semelhantes. Confira estes campos!'
sugestao.nivel_conflito = 2
elif grupo_2 == 1 and grupo_3 == 2 and (grupo_4 == 2):
if wildcards_rule_1.ip_src == True and pscd_rule_1.priority > pscd_rule_2.priority:
sugestao.sugestao_resolucao = 'Verifique o IP de Origem da Regra. Estah bem generico'
sugestao.nivel_conflito = 2
elif wildcards_rule_2.ip_src == True and pscd_rule_1.priority > pscd_rule_2.priority:
sugestao.sugestao_resolucao = 'Verifique o IP de Origem da Regra %s. Estah bem generico' % pscd_rule_2.flow_id
sugestao.nivel_conflito = 2
elif wildcards_rule_1.ip_dst == True and pscd_rule_1.priority > pscd_rule_2.priority:
sugestao.sugestao_resolucao = 'Verifique o IP de Destino da Regra. Estah bem generico'
sugestao.nivel_conflito = 2
elif wildcards_rule_2.ip_dst == True and pscd_rule_1.priority > pscd_rule_2.priority:
sugestao.sugestao_resolucao = 'Verifique o IP de Destino da Regra %s. Estah bem generico' % pscd_rule_2.flow_id
sugestao.nivel_conflito = 2
else:
sugestao.sugestao_resolucao = 'Verifique o IP das Regras. Grande probabilidade de conflito em MAC e Portas TCP'
sugestao.nivel_conflito = 2
elif (pscd_rule_1.dl_type == 'ip' or pscd_rule_1.dl_type == 'tcp' or pscd_rule_1.dl_type == 'udp' or (pscd_rule_1.dl_type == 'sctp')) and grupo_2 == 2 and (grupo_4 == 2):
sugestao.sugestao_resolucao = 'Regra TCP. Os Campos IP e Portas TCP/UDP estao bem genericos.'
sugestao.nivel_conflito = 2
elif (pscd_rule_1.dl_type == 'ip' or pscd_rule_1.dl_type == 'tcp' or pscd_rule_1.dl_type == 'udp' or (pscd_rule_1.dl_type == 'sctp')) and grupo_2 == 1 and (grupo_4 == 2):
sugestao.sugestao_resolucao = 'Regra TCP. As Portas TCP/UDP estao bem genericos. Confira tambem os Campos IP, podem vir a conflitar.'
sugestao.nivel_conflito = 2
elif (pscd_rule_1.dl_type == 'ip' or pscd_rule_1.dl_type == 'tcp' or pscd_rule_1.dl_type == 'udp' or (pscd_rule_1.dl_type == 'sctp')) and grupo_2 == 2 and (grupo_4 == 1):
sugestao.sugestao_resolucao = 'Regra TCP. Os Campos IP estao bem generico. Confira tambem as Portas TCP/UDP, podem vir a conflitar.'
sugestao.nivel_conflito = 2
elif grupo_2 == 1 and grupo_3 == 1 and (pscd_rule_1.dl_type == 'arp' or pscd_rule_1.dl_type == 'rarp' or pscd_rule_1.dl_type == 'icmp'):
sugestao.sugestao_resolucao = 'Em regras %s, voce pode verificar os campos IP e MAC. Algum deles estah bem generico.' % pscd_rule_1.dl_type
sugestao.nivel_conflito = 1
elif grupo_2 == 2 and grupo_3 == 2 and (pscd_rule_1.dl_type == 'arp' or pscd_rule_1.dl_type == 'rarp' or pscd_rule_1.dl_type == 'icmp'):
sugestao.sugestao_resolucao = 'Em regras %s, voce pode verificar os campos IP e MAC que estao bem genericos.' % pscd_rule_1.dl_type
sugestao.nivel_conflito = 2
elif grupo_2 == 1 and grupo_3 == 2 and (pscd_rule_1.dl_type == 'arp' or pscd_rule_1.dl_type == 'rarp' or pscd_rule_1.dl_type == 'icmp'):
sugestao.sugestao_resolucao = 'Em regras %s, voce pode verificar os campos MAC que estao bem genericos.' % pscd_rule_1.dl_type
sugestao.nivel_conflito = 2
elif grupo_2 == 2 and grupo_3 == 1 and (grupo_4 == 2):
sugestao.sugestao_resolucao = 'Verifique os campos de IP e Portas TCP/UDP das Regras. Estao bem Genericos'
sugestao.nivel_conflito = 2
elif grupo_2 == 2 and grupo_3 == 2 and (grupo_4 == 1):
sugestao.sugestao_resolucao = 'Verifique os campos de IP e MAC das Regras. Estao bem Genericos'
sugestao.nivel_conflito = 2
elif grupo_2 == 2 and grupo_3 == 1 and (grupo_4 == 1):
sugestao.sugestao_resolucao = 'Verifique os campos de IP das Regras. Estao bem Genericos. Os campos de Porta TCP/UDP e MAC tambem podem vir a conflitar!'
sugestao.nivel_conflito = 1
elif grupo_2 == 1 and grupo_3 == 2 and (grupo_4 == 1):
sugestao.sugestao_resolucao = 'Verifique os campos de MAC das Regras. Estao bem Genericos. Os campos de IP e Porta TCP/UDP tambem podem vir a conflitar!'
sugestao.nivel_conflito = 1
elif grupo_2 == 1 and grupo_3 == 1 and (grupo_4 == 2):
sugestao.sugestao_resolucao = 'Verifique os campos de Portas TCP/UDP das Regras. Estao bem Genericos. Os campos de IP e MAC tambem podem vir a conflitar!'
sugestao.nivel_conflito = 1
return sugestao
else:
return sugestao
else:
return sugestao |
def get_slice_length(path):
for i in range(len(path)):
if path[i].isalpha():
return i
return -1
| def get_slice_length(path):
for i in range(len(path)):
if path[i].isalpha():
return i
return -1 |
entrada = int(input())
#resultado = entrada % 2
#comp = 10 % 2
i = 1
while i <= entrada:
if i % 2 != 0:
print(i)
i+= 1
| entrada = int(input())
i = 1
while i <= entrada:
if i % 2 != 0:
print(i)
i += 1 |
"""
# Supported expressions examples
Test for `handsdown.ast_parser.analyzers.expression_analyzer.ExpressionAnalyzer` test.
"""
# string example
STRING = "string"
# bytes example
BSTRING = b"string"
# r-string example
RSTRING = r"str\ing"
# joined string example
JOINED_STRING = "part1" "part2"
# f-string example
FSTRING = f"start{STRING}end"
# slice example
SLICE = STRING[1:4:-1]
# set example
SET = {1, 2, 3}
# list example
LIST = [1, 2, 3]
# tuple example
TUPLE = (1, 2, 3)
# dict example
DICT = (1, 2, 3)
# dict comprehension example
DICT_COMP = {k: 1 for k in range(3) if k > -10}
# list comprehension example
LIST_COMP = [k + 1 for k in range(3)]
# set comprehension example
SET_COMP = {k + 1 for k in range(3)}
# generator expression example
GEN_EXPR = (k + 1 for k in range(3))
# if expression example
IF_EXPR = 5 if STRING else 6
# await example
AWAIT = await STRING
| """
# Supported expressions examples
Test for `handsdown.ast_parser.analyzers.expression_analyzer.ExpressionAnalyzer` test.
"""
string = 'string'
bstring = b'string'
rstring = 'str\\ing'
joined_string = 'part1part2'
fstring = f'start{STRING}end'
slice = STRING[1:4:-1]
set = {1, 2, 3}
list = [1, 2, 3]
tuple = (1, 2, 3)
dict = (1, 2, 3)
dict_comp = {k: 1 for k in range(3) if k > -10}
list_comp = [k + 1 for k in range(3)]
set_comp = {k + 1 for k in range(3)}
gen_expr = (k + 1 for k in range(3))
if_expr = 5 if STRING else 6
await = await STRING |
class ModaError(Exception):
pass
class ModaTimeoutError(ModaError):
pass
class ModaCannotInteractError(ModaError):
pass | class Modaerror(Exception):
pass
class Modatimeouterror(ModaError):
pass
class Modacannotinteracterror(ModaError):
pass |
def bubblesort(a_list: list) -> list:
"""
The Bubble sort algorithm is the most naive one that we can create. The idea around this algorithm
is comparing each two elements on the list and swapping them in case one is bigger than the other.
If any swap is executed, we need to rerun it, since these swapped elements might need to be swapped
again.
.. example::
original list: [3, 5, 1, 4, 2]
1st round: [3, 1, 4, 2, 5]
2nd round: [1, 3, 2, 4, 5]
3rd round: [1, 2, 3, 4, 5]
.. best case::
O(N)
If the list is already sorted, we pass it once and since no swap will happen, we return it as is.
.. worst case::
O(N^2)
If the list is inverted (e.g. [4, 3, 2, 1]) we need to pass the N elements N times.
original list: [4, 3, 2, 1]
1st round: [3, 2, 1, 4]
2nd round: [2, 1, 3, 4]
3rd round: [1, 2, 3, 4]
So we can see that its the number of elements (N) times the number of swaps (N-1). N^2-1 rounds.
:param a_list: a list with numbers.
:return: a list with the elements sorted (asc -> desc).
"""
updated = False
for i in range(0, len(a_list) - 1):
if a_list[i] > a_list[i + 1]:
a_list[i + 1], a_list[i] = a_list[i], a_list[i + 1]
updated = True
return a_list if not updated else bubblesort(a_list)
| def bubblesort(a_list: list) -> list:
"""
The Bubble sort algorithm is the most naive one that we can create. The idea around this algorithm
is comparing each two elements on the list and swapping them in case one is bigger than the other.
If any swap is executed, we need to rerun it, since these swapped elements might need to be swapped
again.
.. example::
original list: [3, 5, 1, 4, 2]
1st round: [3, 1, 4, 2, 5]
2nd round: [1, 3, 2, 4, 5]
3rd round: [1, 2, 3, 4, 5]
.. best case::
O(N)
If the list is already sorted, we pass it once and since no swap will happen, we return it as is.
.. worst case::
O(N^2)
If the list is inverted (e.g. [4, 3, 2, 1]) we need to pass the N elements N times.
original list: [4, 3, 2, 1]
1st round: [3, 2, 1, 4]
2nd round: [2, 1, 3, 4]
3rd round: [1, 2, 3, 4]
So we can see that its the number of elements (N) times the number of swaps (N-1). N^2-1 rounds.
:param a_list: a list with numbers.
:return: a list with the elements sorted (asc -> desc).
"""
updated = False
for i in range(0, len(a_list) - 1):
if a_list[i] > a_list[i + 1]:
(a_list[i + 1], a_list[i]) = (a_list[i], a_list[i + 1])
updated = True
return a_list if not updated else bubblesort(a_list) |
def recurse(a,i):
if i == len(a)-1:
print(a[i])
return
else:
recurse(a,i+1)
print(a[i])
recurse([1,2,3,4,5],0) | def recurse(a, i):
if i == len(a) - 1:
print(a[i])
return
else:
recurse(a, i + 1)
print(a[i])
recurse([1, 2, 3, 4, 5], 0) |
# https://www.hackerrank.com/challenges/30-running-time-and-complexity/problem
# Trial division
def is_prime(n):
if n < 2:
return False
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True
if __name__ == '__main__':
n, nums = int(input()), []
for i in range(n):
nums.append(int(input()))
# nums = [5, 97, 98, 3]
# nums = [1000000000, 1000000001, 1000000002, 1000000003, 1000000004, 1000000005, 1000000006, 1000000007, 1000000008,
# 1000000009]
# nums = [1000000006]
for num in nums:
print('Prime' if is_prime(num) else 'Not prime')
| def is_prime(n):
if n < 2:
return False
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True
if __name__ == '__main__':
(n, nums) = (int(input()), [])
for i in range(n):
nums.append(int(input()))
for num in nums:
print('Prime' if is_prime(num) else 'Not prime') |
class Citation:
"""Basic citation class"""
def __init__(self, data: dict):
self.data = data
@property
def data_(self):
return self.data
def __str__(self):
return str(self.data)
def __repr(self):
return str(self.data)
| class Citation:
"""Basic citation class"""
def __init__(self, data: dict):
self.data = data
@property
def data_(self):
return self.data
def __str__(self):
return str(self.data)
def __repr(self):
return str(self.data) |
def encode1(Loan_Status):
"""
This function encodes a loan status to either 1 or 0.
"""
if Loan_Status == 'Y':
return 1
else:
return 0
def encode2(Gender):
"""
This function encodes a loan status to either 1 or 0.
"""
if Gender == 'Male':
return 1
else:
return 0
def encode3(Married):
"""
This function encodes a loan status to either 1 or 0.
"""
if Married == 'Yes':
return 1
else:
return 0
def encode4(Education):
"""
This function encodes a loan status to either 1 or 0.
"""
if Education == 'Graduate':
return 1
else:
return 0
def encode5(Self_Employed):
"""
This function encodes a loan status to either 1 or 0.
"""
if Self_Employed == 'Yes':
return 1
else:
return 0
def encode6(Property_Area):
"""
This function encodes a loan status to either 1 or 0.
"""
if Property_Area == 'Urban':
return 1
elif Property_Area == 'Rural':
return 0
else:
return 2
def encode7(Dependents):
"""
This function encodes a loan status to either 1 or 0.
"""
if Dependents == '0':
return 0
elif Dependents == '1':
return 1
elif Dependents == '2':
return 2
else:
return 3
| def encode1(Loan_Status):
"""
This function encodes a loan status to either 1 or 0.
"""
if Loan_Status == 'Y':
return 1
else:
return 0
def encode2(Gender):
"""
This function encodes a loan status to either 1 or 0.
"""
if Gender == 'Male':
return 1
else:
return 0
def encode3(Married):
"""
This function encodes a loan status to either 1 or 0.
"""
if Married == 'Yes':
return 1
else:
return 0
def encode4(Education):
"""
This function encodes a loan status to either 1 or 0.
"""
if Education == 'Graduate':
return 1
else:
return 0
def encode5(Self_Employed):
"""
This function encodes a loan status to either 1 or 0.
"""
if Self_Employed == 'Yes':
return 1
else:
return 0
def encode6(Property_Area):
"""
This function encodes a loan status to either 1 or 0.
"""
if Property_Area == 'Urban':
return 1
elif Property_Area == 'Rural':
return 0
else:
return 2
def encode7(Dependents):
"""
This function encodes a loan status to either 1 or 0.
"""
if Dependents == '0':
return 0
elif Dependents == '1':
return 1
elif Dependents == '2':
return 2
else:
return 3 |
bulan_pembelian = ('Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember')
pertengahan_tahun = bulan_pembelian[4:8]
print(pertengahan_tahun)
awal_tahun = bulan_pembelian[:5]
print(awal_tahun)
akhir_tahun = bulan_pembelian[8:]
print(akhir_tahun)
print(bulan_pembelian[-4:-1]) | bulan_pembelian = ('Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember')
pertengahan_tahun = bulan_pembelian[4:8]
print(pertengahan_tahun)
awal_tahun = bulan_pembelian[:5]
print(awal_tahun)
akhir_tahun = bulan_pembelian[8:]
print(akhir_tahun)
print(bulan_pembelian[-4:-1]) |
def test_one(app):
response = app.get('/api/services', status=200)
response.json.should.be.is_instance(list)
def test_two(app):
response = app.get('/api/services/1', status=200)
response.json.should.be.equal({'id': 9, 'name': 'Voice', 'slug': 'SERVICE_VOICE'})
| def test_one(app):
response = app.get('/api/services', status=200)
response.json.should.be.is_instance(list)
def test_two(app):
response = app.get('/api/services/1', status=200)
response.json.should.be.equal({'id': 9, 'name': 'Voice', 'slug': 'SERVICE_VOICE'}) |
def str_to_int(value, default=int(0)):
stripped_value = value.strip()
try:
return int(stripped_value)
except ValueError:
return default
def str_to_float(value, default=float(0)):
stripped_value = value.strip()
try:
return float(stripped_value)
except ValueError:
return default
| def str_to_int(value, default=int(0)):
stripped_value = value.strip()
try:
return int(stripped_value)
except ValueError:
return default
def str_to_float(value, default=float(0)):
stripped_value = value.strip()
try:
return float(stripped_value)
except ValueError:
return default |
k=1
suma=(k**2+1)/k
cont=0
while cont<1000:
cont+=suma
print(k)
k+=1
suma=(k**2+1)/k
| k = 1
suma = (k ** 2 + 1) / k
cont = 0
while cont < 1000:
cont += suma
print(k)
k += 1
suma = (k ** 2 + 1) / k |
# Copyright 2017-2021 object_database Authors
#
# 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.
class SortWrapper:
def __init__(self, x):
self.x = x
def __lt__(self, other):
try:
if type(self.x) in (int, float) and type(other.x) in (int, float):
return self.x < other.x
if type(self.x) is type(other.x): # noqa: E721
return self.x < other.x
else:
return str(type(self.x)) < str(type(other.x))
except Exception:
try:
return str(self.x) < str(self.other)
except Exception:
return False
def __eq__(self, other):
try:
if type(self.x) is type(other.x): # noqa: E721
return self.x == other.x
else:
return str(type(self.x)) == str(type(other.x))
except Exception:
try:
return str(self.x) == str(self.other)
except Exception:
return True
| class Sortwrapper:
def __init__(self, x):
self.x = x
def __lt__(self, other):
try:
if type(self.x) in (int, float) and type(other.x) in (int, float):
return self.x < other.x
if type(self.x) is type(other.x):
return self.x < other.x
else:
return str(type(self.x)) < str(type(other.x))
except Exception:
try:
return str(self.x) < str(self.other)
except Exception:
return False
def __eq__(self, other):
try:
if type(self.x) is type(other.x):
return self.x == other.x
else:
return str(type(self.x)) == str(type(other.x))
except Exception:
try:
return str(self.x) == str(self.other)
except Exception:
return True |
class JSException(Exception):
"""Base exception for javascript engine wrapper."""
pass
class ArgumentError(JSException):
pass
class JSFunctionNotExists(JSException):
pass
class JSRuntimeException(JSException):
"""Javascript runtime exception with a stacktrace."""
def __init__(self, msg, traceback):
self.msg = msg
self.traceback = traceback
super().__init__()
class JSConversionException(JSException):
"""Exception on converting a javascript type to/from python type."""
pass
| class Jsexception(Exception):
"""Base exception for javascript engine wrapper."""
pass
class Argumenterror(JSException):
pass
class Jsfunctionnotexists(JSException):
pass
class Jsruntimeexception(JSException):
"""Javascript runtime exception with a stacktrace."""
def __init__(self, msg, traceback):
self.msg = msg
self.traceback = traceback
super().__init__()
class Jsconversionexception(JSException):
"""Exception on converting a javascript type to/from python type."""
pass |
# encoding=utf8
# coding=UTF-8
#pastaArquivoCsv = "/home/00937325465/familiai/acompanhaig/arquivos/csv/"
#pastaArquivoCsvProc = "/home/00937325465/familiai/acompanhaig/arquivos/csv/processados/"
#pastaArquivoZip = "/home/00937325465/familiai/acompanhaig/arquivos/zip/"
#pastaArquivoZipProc = "/home/00937325465/familiai/acompanhaig/arquivos/zip/processados/"
#pastaArquivosHTML = "/home/00937325465/familiai/acompanhaig/html/"
#templateBasico = "/home/00937325465/familiai/acompanhaig/templates/template_basico.html"
pastaArquivoCsv = "/home/ubuntu/workspace/public/python/input/csv/"
pastaArquivoCsvProc = "/home/ubuntu/workspace/public/python/input/csv/processados/"
pastaArquivoZip = "/home/ubuntu/workspace/public/python/input/zip/"
pastaArquivoZipProc = "/home/ubuntu/workspace/public/python/input/zip/processados/"
pastaArquivosHTML = "/home/ubuntu/workspace/public/python/output/html/"
templateBasico = "/home/ubuntu/workspace/public/python/input/templates/template_basico.html"
sep = "|"
sepNmArq = "_"
txDepto = "DERCE"
txLotacao = "LOTACAO"
tagLotacao = "<<lotacao>>"
| pasta_arquivo_csv = '/home/ubuntu/workspace/public/python/input/csv/'
pasta_arquivo_csv_proc = '/home/ubuntu/workspace/public/python/input/csv/processados/'
pasta_arquivo_zip = '/home/ubuntu/workspace/public/python/input/zip/'
pasta_arquivo_zip_proc = '/home/ubuntu/workspace/public/python/input/zip/processados/'
pasta_arquivos_html = '/home/ubuntu/workspace/public/python/output/html/'
template_basico = '/home/ubuntu/workspace/public/python/input/templates/template_basico.html'
sep = '|'
sep_nm_arq = '_'
tx_depto = 'DERCE'
tx_lotacao = 'LOTACAO'
tag_lotacao = '<<lotacao>>' |
class Innovation:
def __init__(self, innov, new_conn, fr=None, to=None, node_id=None):
"""Innovation details
Args:
innov (int): Innovation ID of the Innovation
new_conn (bool): Is the new Innovation a innovation of a connection or a node
fr (int, optional): Node ID of the input node. Defaults to None.
to (int, optional): Node ID of the output node. Defaults to None.
node_id (int, optional): ID of the node if it isn't a new_conn. Defaults to None.
"""
self.innov = innov
self.new_conn = new_conn
self.fr = fr
self.to = to
self.node_id = node_id
class InnovTable:
"""Innovation Table of the whole NEAT algorithm. It is a static class
Contains:
history (List[Innovation]): List of all the innovations occured
innov (int): The next innovation ID
node_id (int): The next node ID
"""
history = []
innov = 0
node_id = 0
@staticmethod
def set_node_id(node_id):
"""Sets the node_id if it is greater than InnovTable.node_id
Args:
node_id (int): The node ID
"""
InnovTable.node_id = max(InnovTable.node_id, node_id)
@staticmethod
def _create_innov(fr, to, new_conn):
"""Create a new innovation
Args:
fr (int): Node ID of the input node
to (int): Node ID of the output node
new_conn (bool): Is it a new connection. Other option is a node
Returns:
Innovation: The new innovation
"""
if new_conn:
innovation = Innovation(InnovTable.innov, new_conn, fr, to)
else:
innovation = Innovation(InnovTable.innov, new_conn, fr, to, node_id=InnovTable.node_id)
InnovTable.node_id += 1
InnovTable.history.append(innovation)
InnovTable.innov += 1
return innovation
@staticmethod
def get_innov(fr, to, new_conn=True):
"""Gets a innovation with given args. Returns the innovation if present or else creates a new innovation
Args:
fr (int): Node ID of the input node
to (int): Node ID of the output node
new_conn (bool, optional): Does the innovation contain a new connection or node. Defaults to True.
Returns:
Innovation: The innovation
"""
for innovation in InnovTable.history:
if innovation.new_conn == new_conn and innovation.fr == fr and innovation.to == to:
return innovation
return InnovTable._create_innov(fr, to, new_conn) | class Innovation:
def __init__(self, innov, new_conn, fr=None, to=None, node_id=None):
"""Innovation details
Args:
innov (int): Innovation ID of the Innovation
new_conn (bool): Is the new Innovation a innovation of a connection or a node
fr (int, optional): Node ID of the input node. Defaults to None.
to (int, optional): Node ID of the output node. Defaults to None.
node_id (int, optional): ID of the node if it isn't a new_conn. Defaults to None.
"""
self.innov = innov
self.new_conn = new_conn
self.fr = fr
self.to = to
self.node_id = node_id
class Innovtable:
"""Innovation Table of the whole NEAT algorithm. It is a static class
Contains:
history (List[Innovation]): List of all the innovations occured
innov (int): The next innovation ID
node_id (int): The next node ID
"""
history = []
innov = 0
node_id = 0
@staticmethod
def set_node_id(node_id):
"""Sets the node_id if it is greater than InnovTable.node_id
Args:
node_id (int): The node ID
"""
InnovTable.node_id = max(InnovTable.node_id, node_id)
@staticmethod
def _create_innov(fr, to, new_conn):
"""Create a new innovation
Args:
fr (int): Node ID of the input node
to (int): Node ID of the output node
new_conn (bool): Is it a new connection. Other option is a node
Returns:
Innovation: The new innovation
"""
if new_conn:
innovation = innovation(InnovTable.innov, new_conn, fr, to)
else:
innovation = innovation(InnovTable.innov, new_conn, fr, to, node_id=InnovTable.node_id)
InnovTable.node_id += 1
InnovTable.history.append(innovation)
InnovTable.innov += 1
return innovation
@staticmethod
def get_innov(fr, to, new_conn=True):
"""Gets a innovation with given args. Returns the innovation if present or else creates a new innovation
Args:
fr (int): Node ID of the input node
to (int): Node ID of the output node
new_conn (bool, optional): Does the innovation contain a new connection or node. Defaults to True.
Returns:
Innovation: The innovation
"""
for innovation in InnovTable.history:
if innovation.new_conn == new_conn and innovation.fr == fr and (innovation.to == to):
return innovation
return InnovTable._create_innov(fr, to, new_conn) |
def slices(number, n):
initial, res = 0, []
if n > len(number) or n == 0:
raise ValueError("Desired slices greater than number length")
elif n == len(number):
return [[int(x) for x in number]]
elif n == 1:
return [[int(x)] for x in number]
else:
while n <= len(number):
res.append([int(x) for x in number[initial:n]])
initial += 1
n += 1
return res
| def slices(number, n):
(initial, res) = (0, [])
if n > len(number) or n == 0:
raise value_error('Desired slices greater than number length')
elif n == len(number):
return [[int(x) for x in number]]
elif n == 1:
return [[int(x)] for x in number]
else:
while n <= len(number):
res.append([int(x) for x in number[initial:n]])
initial += 1
n += 1
return res |
#
# PySNMP MIB module HUAWEI-LswSMON-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-LswSMON-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:34:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint")
huaweiDatacomm, huaweiMgmt = mibBuilder.importSymbols("HUAWEI-3COM-OID-MIB", "huaweiDatacomm", "huaweiMgmt")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Unsigned32, Counter64, Counter32, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, ObjectIdentity, iso, Gauge32, MibIdentifier, Bits, IpAddress, TimeTicks, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "Unsigned32", "Counter64", "Counter32", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "ObjectIdentity", "iso", "Gauge32", "MibIdentifier", "Bits", "IpAddress", "TimeTicks", "Integer32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
hwSmonExtend = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26))
smonExtendObject = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1))
hwdot1qVlanStatNumber = MibScalar((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hwdot1qVlanStatNumber.setStatus('mandatory')
hwdot1qVlanStatStatusTable = MibTable((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1, 2), )
if mibBuilder.loadTexts: hwdot1qVlanStatStatusTable.setStatus('mandatory')
hwdot1qVlanStatStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1, 2, 1), ).setIndexNames((0, "HUAWEI-LswSMON-MIB", "hwdot1qVlanStatEnableIndex"))
if mibBuilder.loadTexts: hwdot1qVlanStatStatusEntry.setStatus('mandatory')
hwdot1qVlanStatEnableIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1, 2, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hwdot1qVlanStatEnableIndex.setStatus('mandatory')
hwdot1qVlanStatEnableStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hwdot1qVlanStatEnableStatus.setStatus('mandatory')
mibBuilder.exportSymbols("HUAWEI-LswSMON-MIB", hwdot1qVlanStatEnableIndex=hwdot1qVlanStatEnableIndex, smonExtendObject=smonExtendObject, hwdot1qVlanStatNumber=hwdot1qVlanStatNumber, hwdot1qVlanStatStatusTable=hwdot1qVlanStatStatusTable, hwSmonExtend=hwSmonExtend, hwdot1qVlanStatEnableStatus=hwdot1qVlanStatEnableStatus, hwdot1qVlanStatStatusEntry=hwdot1qVlanStatStatusEntry)
| (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, constraints_union, value_range_constraint, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'SingleValueConstraint', 'ConstraintsUnion', 'ValueRangeConstraint', 'ValueSizeConstraint')
(huawei_datacomm, huawei_mgmt) = mibBuilder.importSymbols('HUAWEI-3COM-OID-MIB', 'huaweiDatacomm', 'huaweiMgmt')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(unsigned32, counter64, counter32, module_identity, mib_scalar, mib_table, mib_table_row, mib_table_column, notification_type, object_identity, iso, gauge32, mib_identifier, bits, ip_address, time_ticks, integer32) = mibBuilder.importSymbols('SNMPv2-SMI', 'Unsigned32', 'Counter64', 'Counter32', 'ModuleIdentity', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'NotificationType', 'ObjectIdentity', 'iso', 'Gauge32', 'MibIdentifier', 'Bits', 'IpAddress', 'TimeTicks', 'Integer32')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
hw_smon_extend = mib_identifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26))
smon_extend_object = mib_identifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1))
hwdot1q_vlan_stat_number = mib_scalar((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hwdot1qVlanStatNumber.setStatus('mandatory')
hwdot1q_vlan_stat_status_table = mib_table((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1, 2))
if mibBuilder.loadTexts:
hwdot1qVlanStatStatusTable.setStatus('mandatory')
hwdot1q_vlan_stat_status_entry = mib_table_row((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1, 2, 1)).setIndexNames((0, 'HUAWEI-LswSMON-MIB', 'hwdot1qVlanStatEnableIndex'))
if mibBuilder.loadTexts:
hwdot1qVlanStatStatusEntry.setStatus('mandatory')
hwdot1q_vlan_stat_enable_index = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1, 2, 1, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hwdot1qVlanStatEnableIndex.setStatus('mandatory')
hwdot1q_vlan_stat_enable_status = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1, 2, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hwdot1qVlanStatEnableStatus.setStatus('mandatory')
mibBuilder.exportSymbols('HUAWEI-LswSMON-MIB', hwdot1qVlanStatEnableIndex=hwdot1qVlanStatEnableIndex, smonExtendObject=smonExtendObject, hwdot1qVlanStatNumber=hwdot1qVlanStatNumber, hwdot1qVlanStatStatusTable=hwdot1qVlanStatStatusTable, hwSmonExtend=hwSmonExtend, hwdot1qVlanStatEnableStatus=hwdot1qVlanStatEnableStatus, hwdot1qVlanStatStatusEntry=hwdot1qVlanStatStatusEntry) |
"""
Copyright 2015, Rob Shakir (rjs@jive.com, rjs@rob.sh)
This project has been supported by:
* Jive Communcations, Inc.
* BT plc.
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.
"""
class PybindBase(object):
__slots__ = ()
def elements(self):
return self._pyangbind_elements
def __str__(self):
return str(self.elements())
def get(self, filter=False):
def error():
return NameError, "element does not exist"
d = {}
# for each YANG element within this container.
for element_name in self._pyangbind_elements:
element = getattr(self, element_name, error)
if hasattr(element, "yang_name"):
# retrieve the YANG name method
yang_name = getattr(element, "yang_name", error)
element_id = yang_name()
else:
element_id = element_name
if hasattr(element, "get"):
# this is a YANG container that has its own
# get method
d[element_id] = element.get(filter=filter)
if filter is True:
# if the element hadn't changed but we were
# filtering unchanged elements, remove it
# from the dictionary
if isinstance(d[element_id], dict):
for entry in d[element_id].keys():
changed, present = False, False
if hasattr(d[element_id][entry], "_changed"):
if d[element_id][entry]._changed():
changed = True
else:
changed = None
if hasattr(d[element_id][entry], "_present"):
if not d[element_id][entry]._present() is True:
present = True
else:
present = None
if present is False and changed is False:
del d[element_id][entry]
if len(d[element_id]) == 0:
if element._presence and element._present():
pass
else:
del d[element_id]
elif isinstance(d[element_id], list):
for list_entry in d[element_id]:
if hasattr(list_entry, "_changed"):
if not list_entry._changed():
d[element_id].remove(list_entry)
if len(d[element_id]) == 0:
del d[element_id]
else:
# this is an attribute that does not have get()
# method
if filter is False and not element._changed() and not element._present() is True:
if element._default is not False and element._default:
d[element_id] = element._default
else:
d[element_id] = element
elif element._changed() or element._present() is True:
d[element_id] = element
else:
# changed = False, and filter = True
pass
return d
def __getitem__(self, k):
def error():
raise KeyError("Key %s does not exist" % k)
element = getattr(self, k, error)
return element()
def __iter__(self):
for elem in self._pyangbind_elements:
yield (elem, getattr(self, elem))
| """
Copyright 2015, Rob Shakir (rjs@jive.com, rjs@rob.sh)
This project has been supported by:
* Jive Communcations, Inc.
* BT plc.
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.
"""
class Pybindbase(object):
__slots__ = ()
def elements(self):
return self._pyangbind_elements
def __str__(self):
return str(self.elements())
def get(self, filter=False):
def error():
return (NameError, 'element does not exist')
d = {}
for element_name in self._pyangbind_elements:
element = getattr(self, element_name, error)
if hasattr(element, 'yang_name'):
yang_name = getattr(element, 'yang_name', error)
element_id = yang_name()
else:
element_id = element_name
if hasattr(element, 'get'):
d[element_id] = element.get(filter=filter)
if filter is True:
if isinstance(d[element_id], dict):
for entry in d[element_id].keys():
(changed, present) = (False, False)
if hasattr(d[element_id][entry], '_changed'):
if d[element_id][entry]._changed():
changed = True
else:
changed = None
if hasattr(d[element_id][entry], '_present'):
if not d[element_id][entry]._present() is True:
present = True
else:
present = None
if present is False and changed is False:
del d[element_id][entry]
if len(d[element_id]) == 0:
if element._presence and element._present():
pass
else:
del d[element_id]
elif isinstance(d[element_id], list):
for list_entry in d[element_id]:
if hasattr(list_entry, '_changed'):
if not list_entry._changed():
d[element_id].remove(list_entry)
if len(d[element_id]) == 0:
del d[element_id]
elif filter is False and (not element._changed()) and (not element._present() is True):
if element._default is not False and element._default:
d[element_id] = element._default
else:
d[element_id] = element
elif element._changed() or element._present() is True:
d[element_id] = element
else:
pass
return d
def __getitem__(self, k):
def error():
raise key_error('Key %s does not exist' % k)
element = getattr(self, k, error)
return element()
def __iter__(self):
for elem in self._pyangbind_elements:
yield (elem, getattr(self, elem)) |
INPUTS = [
['Select', False],
['Signal Only', ''],
['Probe', 'motion.probe-input'],
['Digital In 0', 'motion.digital-in-00'],
['Digital In 1', 'motion.digital-in-01'],
['Digital In 2', 'motion.digital-in-02'],
['Digital In 3', 'motion.digital-in-03'],
]
OUTPUTS = [
['Select', False],
['Signal Only', ''],
['Coolant Flood', 'iocontrol.0.coolant-flood'],
['Coolant Mist', 'iocontrol.0.coolant-mist'],
['Spindle On', 'spindle.0.on'],
['Spindle CW', 'spindle.0.forward'],
['Spindle CCW', 'spindle.0.reverse'],
['Spindle Brake', 'spindle.0.brake'],
['E-Stop Out', 'iocontrol.0.user-enable-out'],
['Digital Out 0', 'motion.digital-out-00'],
['Digital Out 1', 'motion.digital-out-01'],
['Digital Out 2', 'motion.digital-out-02'],
['Digital Out 3', 'motion.digital-out-03'],
]
AIN = [
['Select', False],
['Analog In 0', 'motion.analog-in-00'],
['Analog In 1', 'motion.analog-in-01'],
['Analog In 2', 'motion.analog-in-02'],
['Analog In 3', 'motion.analog-in-03'],
]
def build(parent):
sscards = {
'Select':'No Card Selected',
'7i64':'24 Outputs, 24 Inputs',
'7i69':'48 Digital I/O Bits',
'7i70':'48 Inputs',
'7i71':'48 Sourcing Outputs',
'7i72':'48 Sinking Outputs',
'7i73':'Pendant Card',
'7i84':'32 Inputs 16 Outputs',
'7i87':'8 Analog Inputs'
}
sspage = {
'Select':0,
'7i64':1,
'7i69':2,
'7i70':3,
'7i71':4,
'7i72':5,
'7i73':6,
'7i84':7,
'7i87':8
}
parent.smartSerialInfoLbl.setText(sscards[parent.ssCardCB.currentText()])
parent.smartSerialSW.setCurrentIndex(sspage[parent.ssCardCB.currentText()])
pins7i64 = {}
pins7i69 = {}
pins7i70 = {}
pins7i71 = {}
pins7i72 = {}
pins7i73 = {}
pins7i84 = {}
pins7i87 = {}
def buildCB(parent):
for i in range(16):
for item in INPUTS:
getattr(parent, 'ss7i73in_' + str(i)).addItem(item[0], item[1])
for i in range(2):
for item in OUTPUTS:
getattr(parent, 'ss7i73out_' + str(i)).addItem(item[0], item[1])
# 7i87 Combo Boxes
for i in range(8):
for item in AIN:
getattr(parent, 'ss7i87in_' + str(i)).addItem(item[0], item[1])
def ss7i73setup(parent):
if parent.ss7i97lcdCB.currentData() == 'w7d': # no LCD
parent.ss7i97w7Lbl.setText('W7 Down')
lcd = False
elif parent.ss7i97lcdCB.currentData() == 'w7u': # LCD
parent.ss7i97w7Lbl.setText('W7 Up')
lcd = True
if parent.ss7i73_keypadCB.currentData()[0] == 'w5d':
if parent.ss7i73_keypadCB.currentData()[1] == 'w6d': # no keypad
parent.ss7i73w5Lbl.setText('W5 Down')
parent.ss7i73w6Lbl.setText('W6 Down')
keypad = False
elif parent.ss7i73_keypadCB.currentData()[1] == 'w6u': # 4x8 keypad
parent.ss7i73w5Lbl.setText('W5 Down')
parent.ss7i73w6Lbl.setText('W6 Up')
keypad = True
keys = '4x8'
elif parent.ss7i73_keypadCB.currentData()[0] == 'w5u': # 8x8 keypad
parent.ss7i73w5Lbl.setText('W5 Up')
parent.ss7i73w6Lbl.setText('W6 Down')
keypad = True
keys = '8x8'
# No LCD No Keypad
if not lcd and not keypad:
for i in range(8):
getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Out {i+10}')
for item in OUTPUTS:
getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1])
for i in range(8,16):
getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'In {i+8}')
for item in INPUTS:
getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1])
for i in range(8):
getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i+2}')
for item in OUTPUTS:
getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1])
for i in range(8,12):
getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i+10}')
for item in OUTPUTS:
getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1])
# LCD No Keypad
if lcd and not keypad:
for i in range(8):
getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Out {i+6}')
for item in OUTPUTS:
getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1])
for i in range(8,16):
getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'In {i+8}')
for item in INPUTS:
getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1])
for i in range(5):
getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i+2}')
for item in OUTPUTS:
getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1])
for i in range(4,12):
getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'LCD {i}')
getattr(parent, 'ss7i73lcd_' + str(i)).clear()
# LCD 4x8 Keypad
if lcd and keypad and keys == '4x8':
for i in range(4):
getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Out {i+6}')
for item in OUTPUTS:
getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1])
for i in range(4,16):
getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Key {i}')
getattr(parent, 'ss7i73key_' + str(i)).clear()
for i in range(5):
getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i+2}')
for item in OUTPUTS:
getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1])
for i in range(4,12):
getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'LCD {i}')
getattr(parent, 'ss7i73lcd_' + str(i)).clear()
# LCD 8x8 Keypad
if lcd and keypad and keys == '8x8':
for i in range(16):
getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Key {i}')
getattr(parent, 'ss7i73key_' + str(i)).clear()
for i in range(5):
getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i+2}')
for item in OUTPUTS:
getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1])
for i in range(4,12):
getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'LCD {i}')
getattr(parent, 'ss7i73lcd_' + str(i)).clear()
# No LCD 4x8 Keypad
if not lcd and keypad and keys == '4x8':
for i in range(4):
getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Out {i+10}')
for item in OUTPUTS:
getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1])
for i in range(4,16):
getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Key {i}')
getattr(parent, 'ss7i73key_' + str(i)).clear()
for i in range(8):
getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i+2}')
for item in OUTPUTS:
getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1])
for i in range(8,12):
getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i+6}')
for item in OUTPUTS:
getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1])
# No LCD 8x8 Keypad
if not lcd and keypad and keys == '8x8':
for i in range(16):
getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Key {i}')
getattr(parent, 'ss7i73key_' + str(i)).clear()
for i in range(12):
getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i+2}')
for item in OUTPUTS:
getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1])
| inputs = [['Select', False], ['Signal Only', ''], ['Probe', 'motion.probe-input'], ['Digital In 0', 'motion.digital-in-00'], ['Digital In 1', 'motion.digital-in-01'], ['Digital In 2', 'motion.digital-in-02'], ['Digital In 3', 'motion.digital-in-03']]
outputs = [['Select', False], ['Signal Only', ''], ['Coolant Flood', 'iocontrol.0.coolant-flood'], ['Coolant Mist', 'iocontrol.0.coolant-mist'], ['Spindle On', 'spindle.0.on'], ['Spindle CW', 'spindle.0.forward'], ['Spindle CCW', 'spindle.0.reverse'], ['Spindle Brake', 'spindle.0.brake'], ['E-Stop Out', 'iocontrol.0.user-enable-out'], ['Digital Out 0', 'motion.digital-out-00'], ['Digital Out 1', 'motion.digital-out-01'], ['Digital Out 2', 'motion.digital-out-02'], ['Digital Out 3', 'motion.digital-out-03']]
ain = [['Select', False], ['Analog In 0', 'motion.analog-in-00'], ['Analog In 1', 'motion.analog-in-01'], ['Analog In 2', 'motion.analog-in-02'], ['Analog In 3', 'motion.analog-in-03']]
def build(parent):
sscards = {'Select': 'No Card Selected', '7i64': '24 Outputs, 24 Inputs', '7i69': '48 Digital I/O Bits', '7i70': '48 Inputs', '7i71': '48 Sourcing Outputs', '7i72': '48 Sinking Outputs', '7i73': 'Pendant Card', '7i84': '32 Inputs 16 Outputs', '7i87': '8 Analog Inputs'}
sspage = {'Select': 0, '7i64': 1, '7i69': 2, '7i70': 3, '7i71': 4, '7i72': 5, '7i73': 6, '7i84': 7, '7i87': 8}
parent.smartSerialInfoLbl.setText(sscards[parent.ssCardCB.currentText()])
parent.smartSerialSW.setCurrentIndex(sspage[parent.ssCardCB.currentText()])
pins7i64 = {}
pins7i69 = {}
pins7i70 = {}
pins7i71 = {}
pins7i72 = {}
pins7i73 = {}
pins7i84 = {}
pins7i87 = {}
def build_cb(parent):
for i in range(16):
for item in INPUTS:
getattr(parent, 'ss7i73in_' + str(i)).addItem(item[0], item[1])
for i in range(2):
for item in OUTPUTS:
getattr(parent, 'ss7i73out_' + str(i)).addItem(item[0], item[1])
for i in range(8):
for item in AIN:
getattr(parent, 'ss7i87in_' + str(i)).addItem(item[0], item[1])
def ss7i73setup(parent):
if parent.ss7i97lcdCB.currentData() == 'w7d':
parent.ss7i97w7Lbl.setText('W7 Down')
lcd = False
elif parent.ss7i97lcdCB.currentData() == 'w7u':
parent.ss7i97w7Lbl.setText('W7 Up')
lcd = True
if parent.ss7i73_keypadCB.currentData()[0] == 'w5d':
if parent.ss7i73_keypadCB.currentData()[1] == 'w6d':
parent.ss7i73w5Lbl.setText('W5 Down')
parent.ss7i73w6Lbl.setText('W6 Down')
keypad = False
elif parent.ss7i73_keypadCB.currentData()[1] == 'w6u':
parent.ss7i73w5Lbl.setText('W5 Down')
parent.ss7i73w6Lbl.setText('W6 Up')
keypad = True
keys = '4x8'
elif parent.ss7i73_keypadCB.currentData()[0] == 'w5u':
parent.ss7i73w5Lbl.setText('W5 Up')
parent.ss7i73w6Lbl.setText('W6 Down')
keypad = True
keys = '8x8'
if not lcd and (not keypad):
for i in range(8):
getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Out {i + 10}')
for item in OUTPUTS:
getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1])
for i in range(8, 16):
getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'In {i + 8}')
for item in INPUTS:
getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1])
for i in range(8):
getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i + 2}')
for item in OUTPUTS:
getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1])
for i in range(8, 12):
getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i + 10}')
for item in OUTPUTS:
getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1])
if lcd and (not keypad):
for i in range(8):
getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Out {i + 6}')
for item in OUTPUTS:
getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1])
for i in range(8, 16):
getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'In {i + 8}')
for item in INPUTS:
getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1])
for i in range(5):
getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i + 2}')
for item in OUTPUTS:
getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1])
for i in range(4, 12):
getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'LCD {i}')
getattr(parent, 'ss7i73lcd_' + str(i)).clear()
if lcd and keypad and (keys == '4x8'):
for i in range(4):
getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Out {i + 6}')
for item in OUTPUTS:
getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1])
for i in range(4, 16):
getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Key {i}')
getattr(parent, 'ss7i73key_' + str(i)).clear()
for i in range(5):
getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i + 2}')
for item in OUTPUTS:
getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1])
for i in range(4, 12):
getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'LCD {i}')
getattr(parent, 'ss7i73lcd_' + str(i)).clear()
if lcd and keypad and (keys == '8x8'):
for i in range(16):
getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Key {i}')
getattr(parent, 'ss7i73key_' + str(i)).clear()
for i in range(5):
getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i + 2}')
for item in OUTPUTS:
getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1])
for i in range(4, 12):
getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'LCD {i}')
getattr(parent, 'ss7i73lcd_' + str(i)).clear()
if not lcd and keypad and (keys == '4x8'):
for i in range(4):
getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Out {i + 10}')
for item in OUTPUTS:
getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1])
for i in range(4, 16):
getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Key {i}')
getattr(parent, 'ss7i73key_' + str(i)).clear()
for i in range(8):
getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i + 2}')
for item in OUTPUTS:
getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1])
for i in range(8, 12):
getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i + 6}')
for item in OUTPUTS:
getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1])
if not lcd and keypad and (keys == '8x8'):
for i in range(16):
getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Key {i}')
getattr(parent, 'ss7i73key_' + str(i)).clear()
for i in range(12):
getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i + 2}')
for item in OUTPUTS:
getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1]) |
n=int(input())
d=2
i = 0
while n>d :
if n%d==0 :
i+=1
print ("divisible by",d, "and count",i)
else:
print ("not divisible by this number",d)
d+=1
| n = int(input())
d = 2
i = 0
while n > d:
if n % d == 0:
i += 1
print('divisible by', d, 'and count', i)
else:
print('not divisible by this number', d)
d += 1 |
# -*- encoding: utf-8 -*-
EPILOG = 'Docker Hub in your terminal'
DESCRIPTION = 'Access docker hub from your terminal'
HELPMSGS = {
'method': 'The api method to query {%(choices)s}',
'orgname': 'Your orgname',
'reponame': 'The name of repository',
'username': 'The Docker Hub username',
'format': 'You can dispaly results in %(choices)s formats',
'page': 'The page of result to fetch',
'all_pages': 'Fetch all pages',
'status': 'To query for only builds with specified status',
'login': 'Authenticate with Docker Hub',
'config': 'Manage configuration values',
'action': 'Action to perform on an api method',
}
VALID_METHODS = ['repos', 'tags', 'builds', 'users', 'queue', 'version',
'login', 'config']
VALID_ACTIONS = ['set', 'get']
VALID_CONFIG_NAMES = ['orgname']
NO_TIP_METHODS = ['login', 'version', 'config']
NO_TIP_FORMATS = ['json']
VALID_DISPLAY_FORMATS = ['table', 'json']
DOCKER_AUTH_FILE = '~/.docker/config.json'
CONFIG_FILE = '~/.docker-hub/config.json'
DOCKER_HUB_API_ENDPOINT = 'https://hub.docker.com/v2/'
PER_PAGE = 15
SECURE_CONFIG_KEYS = ['auth_token']
BUILD_STATUS = {
-4: 'canceled',
-2: 'exception',
-1: 'error',
0: 'pending',
1: 'claimed',
2: 'started',
3: 'cloned',
4: 'readme',
5: 'dockerfile',
6: 'built',
7: 'bundled',
8: 'uploaded',
9: 'pushed',
10: 'done'
}
TIPS = [
'You are not authenticated with Docker Hub. Hence only public \
resources will be fetched. Try authenticating using `docker login` or \
`docker-hub login` command to see more.'
]
| epilog = 'Docker Hub in your terminal'
description = 'Access docker hub from your terminal'
helpmsgs = {'method': 'The api method to query {%(choices)s}', 'orgname': 'Your orgname', 'reponame': 'The name of repository', 'username': 'The Docker Hub username', 'format': 'You can dispaly results in %(choices)s formats', 'page': 'The page of result to fetch', 'all_pages': 'Fetch all pages', 'status': 'To query for only builds with specified status', 'login': 'Authenticate with Docker Hub', 'config': 'Manage configuration values', 'action': 'Action to perform on an api method'}
valid_methods = ['repos', 'tags', 'builds', 'users', 'queue', 'version', 'login', 'config']
valid_actions = ['set', 'get']
valid_config_names = ['orgname']
no_tip_methods = ['login', 'version', 'config']
no_tip_formats = ['json']
valid_display_formats = ['table', 'json']
docker_auth_file = '~/.docker/config.json'
config_file = '~/.docker-hub/config.json'
docker_hub_api_endpoint = 'https://hub.docker.com/v2/'
per_page = 15
secure_config_keys = ['auth_token']
build_status = {-4: 'canceled', -2: 'exception', -1: 'error', 0: 'pending', 1: 'claimed', 2: 'started', 3: 'cloned', 4: 'readme', 5: 'dockerfile', 6: 'built', 7: 'bundled', 8: 'uploaded', 9: 'pushed', 10: 'done'}
tips = ['You are not authenticated with Docker Hub. Hence only public resources will be fetched. Try authenticating using `docker login` or `docker-hub login` command to see more.'] |
adj = [[False for i in range(10)] for j in range(10)]
result = [0]
def findthepath(S, v):
result[0] = v
for i in range(1, len(S)):
if (adj[v][ord(S[i]) - ord('A')] or
adj[ord(S[i]) - ord('A')][v]):
v = ord(S[i]) - ord('A')
elif (adj[v][ord(S[i]) - ord('A') + 5] or
adj[ord(S[i]) - ord('A') + 5][v]):
v = ord(S[i]) - ord('A') + 5
else:
return False
result.append(v)
return True
adj[0][1] = adj[1][2] = adj[2][3] = \
adj[3][4] = adj[4][0] = adj[0][5] = \
adj[1][6] = adj[2][7] = adj[3][8] = \
adj[4][9] = adj[5][7] = adj[7][9] = \
adj[9][6] = adj[6][8] = adj[8][5] = True
S = "ABB"
S = list(S)
if (findthepath(S, ord(S[0]) - ord('A')) or
findthepath(S, ord(S[0]) - ord('A') + 5)):
print(*result, sep="")
else:
print("-1") | adj = [[False for i in range(10)] for j in range(10)]
result = [0]
def findthepath(S, v):
result[0] = v
for i in range(1, len(S)):
if adj[v][ord(S[i]) - ord('A')] or adj[ord(S[i]) - ord('A')][v]:
v = ord(S[i]) - ord('A')
elif adj[v][ord(S[i]) - ord('A') + 5] or adj[ord(S[i]) - ord('A') + 5][v]:
v = ord(S[i]) - ord('A') + 5
else:
return False
result.append(v)
return True
adj[0][1] = adj[1][2] = adj[2][3] = adj[3][4] = adj[4][0] = adj[0][5] = adj[1][6] = adj[2][7] = adj[3][8] = adj[4][9] = adj[5][7] = adj[7][9] = adj[9][6] = adj[6][8] = adj[8][5] = True
s = 'ABB'
s = list(S)
if findthepath(S, ord(S[0]) - ord('A')) or findthepath(S, ord(S[0]) - ord('A') + 5):
print(*result, sep='')
else:
print('-1') |
# Create a program that reads a positive integer N as input and prints on the console a rhombus with size n:
def generate_pyramid(size: int, inverted: bool = False) -> list:
steps = [i for i in range(1, size + 1)]
if inverted:
steps.reverse()
return [' ' * (size - i) + '* ' * i for i in steps]
def generate_rhombus(size: int) -> list:
retval = generate_pyramid(size)
retval.extend(generate_pyramid(size, True)[1:])
return retval
n = int(input())
output = generate_rhombus(n)
print(*output, sep='\n')
| def generate_pyramid(size: int, inverted: bool=False) -> list:
steps = [i for i in range(1, size + 1)]
if inverted:
steps.reverse()
return [' ' * (size - i) + '* ' * i for i in steps]
def generate_rhombus(size: int) -> list:
retval = generate_pyramid(size)
retval.extend(generate_pyramid(size, True)[1:])
return retval
n = int(input())
output = generate_rhombus(n)
print(*output, sep='\n') |
# Copyright 2021 Denis Gavrilyuk. 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.
class RecoveryImageIsMissing(Exception):
"""Raised when a client passed an image id for recovery but the image associated with
the id wasn't found in the database. """
| class Recoveryimageismissing(Exception):
"""Raised when a client passed an image id for recovery but the image associated with
the id wasn't found in the database. """ |
#!/usr/bin/env python3
# ~*~ coding: utf-8 ~*~
# Write a program that has a user guess your name, but they only get 3
# chances to do so until the program quits.
print("Try to guess my name!")
count = 1
name = "guileherme"
guess = input("What is my name? ")
while count < 3 and guess.lower() != name: # . lower allows things like Guileherme to still match.
print("You are wrong!")
guess = input("What is my name? ")
count = count + 1
if guess.lower() != name:
print("You are wrong!") # this message isn't printed in the third chance, so we print it now
print("You ran out of chances.")
else:
print("Yes! My name is", name + "!")
| print('Try to guess my name!')
count = 1
name = 'guileherme'
guess = input('What is my name? ')
while count < 3 and guess.lower() != name:
print('You are wrong!')
guess = input('What is my name? ')
count = count + 1
if guess.lower() != name:
print('You are wrong!')
print('You ran out of chances.')
else:
print('Yes! My name is', name + '!') |
def minimumDistances(a):
min_distance = -1
length = len(a)
for number in range(0, length-1):
for another_number in range(number+1, length):
if a[number] == a[another_number]:
distance = another_number - number
if min_distance == -1:
min_distance = distance
elif min_distance > distance:
min_distance = distance
return min_distance
| def minimum_distances(a):
min_distance = -1
length = len(a)
for number in range(0, length - 1):
for another_number in range(number + 1, length):
if a[number] == a[another_number]:
distance = another_number - number
if min_distance == -1:
min_distance = distance
elif min_distance > distance:
min_distance = distance
return min_distance |
class Parser:
""" Parse string matrix and covert each entry to double value, skipping nan values"""
def parse(self, matrix):
result = []
for row in range(0, len(matrix)):
result.append([])
rowLength = len(matrix[row])
for col in range(0, rowLength):
value = matrix[row][col];
if value !='nan':
value = float(value)
result[row].append(value)
return result
| class Parser:
""" Parse string matrix and covert each entry to double value, skipping nan values"""
def parse(self, matrix):
result = []
for row in range(0, len(matrix)):
result.append([])
row_length = len(matrix[row])
for col in range(0, rowLength):
value = matrix[row][col]
if value != 'nan':
value = float(value)
result[row].append(value)
return result |
# -*- coding: utf-8 -*-
#
# ax_spines.py
#
# Copyright 2017 Sebastian Spreizer
# The MIT License
def set_default(ax):
set_visible(ax, ['bottom', 'left'])
def set_visible(ax, sides):
all_sides = ax.spines.keys()
for side in all_sides:
ax.spines[side].set_visible(side in sides)
def set_invisible(ax, sides):
all_sides = ax.spines.keys()
for side in all_sides:
ax.spines[side].set_visible(side not in sides)
| def set_default(ax):
set_visible(ax, ['bottom', 'left'])
def set_visible(ax, sides):
all_sides = ax.spines.keys()
for side in all_sides:
ax.spines[side].set_visible(side in sides)
def set_invisible(ax, sides):
all_sides = ax.spines.keys()
for side in all_sides:
ax.spines[side].set_visible(side not in sides) |
""" Pre-generation tasks.
This is executed before the project has been generated.
"""
def main() -> int:
""" Validate parameters.
"""
status = 0
if not "{{ cookiecutter.plugin_name }}":
print("ERROR: plugin_name cannot be blank")
status = 1
if not "{{ cookiecutter.author_name }}":
print("ERROR: author_name cannot be blank")
status = 1
return status
# Make the script executable.
if __name__ == "__main__":
raise SystemExit(main())
| """ Pre-generation tasks.
This is executed before the project has been generated.
"""
def main() -> int:
""" Validate parameters.
"""
status = 0
if not '{{ cookiecutter.plugin_name }}':
print('ERROR: plugin_name cannot be blank')
status = 1
if not '{{ cookiecutter.author_name }}':
print('ERROR: author_name cannot be blank')
status = 1
return status
if __name__ == '__main__':
raise system_exit(main()) |
'''
https://www.codingame.com/training/easy/create-the-longest-sequence-of-1s
'''
b = input()
count = 0
buf = "0"
zeros = []
ones = []
for i in range(len(b)):
if b[i] == buf:
count += 1
else:
if buf == "0":
zeros.append(count)
else:
ones.append(count)
count = 1
buf = b[i]
if buf == "0":
zeros.append(count)
else:
ones.append(count)
max_ones = 1
for i in range(len(ones)):
left = 1
this_zero = zeros[i]
# Left dead-end (no flip)
if this_zero == 0:
left = ones[i]
# Left bridge (good flip)
elif this_zero == 1:
left = ones[i] + 1 if i == 0 else ones[i] + 1 + ones[i-1]
# Left addition (poor flip)
elif this_zero > 1:
left = ones[i] + 1
if left > max_ones:
max_ones = left
right = 1
if i < len(zeros) - 1:
next_zero = zeros[i+1]
# Right dead-end (no flip)
if zeros[i] == 0:
right = ones[i]
# Right bridge (good flip)
elif zeros[i] == 1:
right = ones[i] + 1 if i == 0 else ones[i] + 1 + ones[i-1]
# Right addition (poor flip)
elif zeros[i] > 1:
right = ones[i] + 1
if right > max_ones:
max_ones = right
print(max_ones)
| """
https://www.codingame.com/training/easy/create-the-longest-sequence-of-1s
"""
b = input()
count = 0
buf = '0'
zeros = []
ones = []
for i in range(len(b)):
if b[i] == buf:
count += 1
else:
if buf == '0':
zeros.append(count)
else:
ones.append(count)
count = 1
buf = b[i]
if buf == '0':
zeros.append(count)
else:
ones.append(count)
max_ones = 1
for i in range(len(ones)):
left = 1
this_zero = zeros[i]
if this_zero == 0:
left = ones[i]
elif this_zero == 1:
left = ones[i] + 1 if i == 0 else ones[i] + 1 + ones[i - 1]
elif this_zero > 1:
left = ones[i] + 1
if left > max_ones:
max_ones = left
right = 1
if i < len(zeros) - 1:
next_zero = zeros[i + 1]
if zeros[i] == 0:
right = ones[i]
elif zeros[i] == 1:
right = ones[i] + 1 if i == 0 else ones[i] + 1 + ones[i - 1]
elif zeros[i] > 1:
right = ones[i] + 1
if right > max_ones:
max_ones = right
print(max_ones) |
#This program calculates how many tiles you
#need when tiling a floor (in m2)
length = float(input("Enter room length:"))
width = float(input("Enter room width:"))
area = length * width
needed = area * 1.05
print("You need", needed, "tiles in squared metres") | length = float(input('Enter room length:'))
width = float(input('Enter room width:'))
area = length * width
needed = area * 1.05
print('You need', needed, 'tiles in squared metres') |
#
# PySNMP MIB module ZYXEL-CLUSTER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-CLUSTER-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:49:17 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ValueSizeConstraint, ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
iso, Counter32, Unsigned32, Counter64, Gauge32, Integer32, Bits, MibIdentifier, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, TimeTicks, NotificationType, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "Counter32", "Unsigned32", "Counter64", "Gauge32", "Integer32", "Bits", "MibIdentifier", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "TimeTicks", "NotificationType", "ModuleIdentity")
MacAddress, DisplayString, TextualConvention, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "MacAddress", "DisplayString", "TextualConvention", "RowStatus")
esMgmt, = mibBuilder.importSymbols("ZYXEL-ES-SMI", "esMgmt")
zyxelCluster = ModuleIdentity((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14))
if mibBuilder.loadTexts: zyxelCluster.setLastUpdated('201207010000Z')
if mibBuilder.loadTexts: zyxelCluster.setOrganization('Enterprise Solution ZyXEL')
if mibBuilder.loadTexts: zyxelCluster.setContactInfo('')
if mibBuilder.loadTexts: zyxelCluster.setDescription('The subtree for cluster')
zyxelClusterSetup = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1))
zyxelClusterStatus = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2))
zyxelClusterManager = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1))
zyClusterManagerMaxNumberOfManagers = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyClusterManagerMaxNumberOfManagers.setStatus('current')
if mibBuilder.loadTexts: zyClusterManagerMaxNumberOfManagers.setDescription('The maximum number of cluster managers that can be created.')
zyxelClusterManagerTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 2), )
if mibBuilder.loadTexts: zyxelClusterManagerTable.setStatus('current')
if mibBuilder.loadTexts: zyxelClusterManagerTable.setDescription('The table contains cluster manager configuration.')
zyxelClusterManagerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 2, 1), ).setIndexNames((0, "ZYXEL-CLUSTER-MIB", "zyClusterManagerVid"))
if mibBuilder.loadTexts: zyxelClusterManagerEntry.setStatus('current')
if mibBuilder.loadTexts: zyxelClusterManagerEntry.setDescription('An entry contains cluster manager configuration. ')
zyClusterManagerVid = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 2, 1, 1), Integer32())
if mibBuilder.loadTexts: zyClusterManagerVid.setStatus('current')
if mibBuilder.loadTexts: zyClusterManagerVid.setDescription('This is the VLAN ID and is only applicable if the switch is set to 802.1Q VLAN. All switches must be directly connected and in the same VLAN group to belong to the same cluster.')
zyClusterManagerName = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 2, 1, 2), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zyClusterManagerName.setStatus('current')
if mibBuilder.loadTexts: zyClusterManagerName.setDescription('Type a name to identify the cluster manager.')
zyClusterManagerRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 2, 1, 3), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: zyClusterManagerRowStatus.setStatus('current')
if mibBuilder.loadTexts: zyClusterManagerRowStatus.setDescription('This object allows cluster manager entries to be created and deleted from cluster manager table.')
zyxelClusterMembers = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2))
zyClusterMemberMaxNumberOfMembers = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyClusterMemberMaxNumberOfMembers.setStatus('current')
if mibBuilder.loadTexts: zyClusterMemberMaxNumberOfMembers.setDescription('The maximum number of cluster members that can be created.')
zyxelClusterMemberTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2), )
if mibBuilder.loadTexts: zyxelClusterMemberTable.setStatus('current')
if mibBuilder.loadTexts: zyxelClusterMemberTable.setDescription('The table contains cluster member configuration.')
zyxelClusterMemberEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1), ).setIndexNames((0, "ZYXEL-CLUSTER-MIB", "zyClusterMemberMacAddress"))
if mibBuilder.loadTexts: zyxelClusterMemberEntry.setStatus('current')
if mibBuilder.loadTexts: zyxelClusterMemberEntry.setDescription('An entry contains cluster member configuration.')
zyClusterMemberMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1, 1), MacAddress())
if mibBuilder.loadTexts: zyClusterMemberMacAddress.setStatus('current')
if mibBuilder.loadTexts: zyClusterMemberMacAddress.setDescription("This is the cluster member switch's hardware MAC address.")
zyClusterMemberName = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyClusterMemberName.setStatus('current')
if mibBuilder.loadTexts: zyClusterMemberName.setDescription("This is the cluster member switch's system name.")
zyClusterMemberModel = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1, 3), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyClusterMemberModel.setStatus('current')
if mibBuilder.loadTexts: zyClusterMemberModel.setDescription("This is the cluster member switch's model name.")
zyClusterMemberPassword = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1, 4), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zyClusterMemberPassword.setStatus('current')
if mibBuilder.loadTexts: zyClusterMemberPassword.setDescription("Each cluster member's password is its administration password.")
zyClusterMemberRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1, 5), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: zyClusterMemberRowStatus.setStatus('current')
if mibBuilder.loadTexts: zyClusterMemberRowStatus.setDescription('This object allows cluster member entries to be created and deleted from cluster member table.')
zyxelClusterCandidate = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1))
zyxelClusterCandidateTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1, 1), )
if mibBuilder.loadTexts: zyxelClusterCandidateTable.setStatus('current')
if mibBuilder.loadTexts: zyxelClusterCandidateTable.setDescription('The table contains cluster candidate information.')
zyxelClusterCandidateEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1, 1, 1), ).setIndexNames((0, "ZYXEL-CLUSTER-MIB", "zyClusterCandidateMacAddress"))
if mibBuilder.loadTexts: zyxelClusterCandidateEntry.setStatus('current')
if mibBuilder.loadTexts: zyxelClusterCandidateEntry.setDescription('An entry contains cluster candidate information.')
zyClusterCandidateMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1, 1, 1, 1), MacAddress())
if mibBuilder.loadTexts: zyClusterCandidateMacAddress.setStatus('current')
if mibBuilder.loadTexts: zyClusterCandidateMacAddress.setDescription("This is the cluster candidate switch's hardware MAC address.")
zyClusterCandidateName = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1, 1, 1, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyClusterCandidateName.setStatus('current')
if mibBuilder.loadTexts: zyClusterCandidateName.setDescription("This is the cluster candidate switch's system name.")
zyClusterCandidateModel = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1, 1, 1, 3), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyClusterCandidateModel.setStatus('current')
if mibBuilder.loadTexts: zyClusterCandidateModel.setDescription("This is the cluster candidate switch's model name.")
zyClusterRole = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("none", 0), ("manager", 1), ("member", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyClusterRole.setStatus('current')
if mibBuilder.loadTexts: zyClusterRole.setDescription('The role of this switch within the cluster.')
zyClusterInfoManager = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 3), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyClusterInfoManager.setStatus('current')
if mibBuilder.loadTexts: zyClusterInfoManager.setDescription("The cluster manager switch's hardware MAC address.")
zyxelClusterInfoMemberTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4), )
if mibBuilder.loadTexts: zyxelClusterInfoMemberTable.setStatus('current')
if mibBuilder.loadTexts: zyxelClusterInfoMemberTable.setDescription('The table contains cluster member information.')
zyxelClusterInfoMemberEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4, 1), ).setIndexNames((0, "ZYXEL-CLUSTER-MIB", "zyClusterInfoMemberMacAddress"))
if mibBuilder.loadTexts: zyxelClusterInfoMemberEntry.setStatus('current')
if mibBuilder.loadTexts: zyxelClusterInfoMemberEntry.setDescription('An entry contains cluster member information.')
zyClusterInfoMemberMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4, 1, 1), MacAddress())
if mibBuilder.loadTexts: zyClusterInfoMemberMacAddress.setStatus('current')
if mibBuilder.loadTexts: zyClusterInfoMemberMacAddress.setDescription("This is the cluster member switch's hardware MAC address.")
zyClusterInfoMemberName = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4, 1, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyClusterInfoMemberName.setStatus('current')
if mibBuilder.loadTexts: zyClusterInfoMemberName.setDescription("This is the cluster member switch's system name.")
zyClusterInfoMemberModel = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4, 1, 3), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyClusterInfoMemberModel.setStatus('current')
if mibBuilder.loadTexts: zyClusterInfoMemberModel.setDescription("This is the cluster member switch's model name.")
zyClusterInfoMemberStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("error", 0), ("online", 1), ("offline", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyClusterInfoMemberStatus.setStatus('current')
if mibBuilder.loadTexts: zyClusterInfoMemberStatus.setDescription('There are three types in cluster status. Online(the cluster member switch is accessible), Error (for example, the cluster member switch password was changed or the switch was set as the manager and so left the member list, etc.), Offline (the switch is disconnected - Offline shows approximately 1.5 minutes after the link between cluster member and manager goes down).')
mibBuilder.exportSymbols("ZYXEL-CLUSTER-MIB", zyClusterCandidateModel=zyClusterCandidateModel, zyxelClusterManager=zyxelClusterManager, zyxelClusterCandidateEntry=zyxelClusterCandidateEntry, zyxelClusterMembers=zyxelClusterMembers, zyxelCluster=zyxelCluster, zyClusterInfoManager=zyClusterInfoManager, zyClusterInfoMemberModel=zyClusterInfoMemberModel, zyxelClusterSetup=zyxelClusterSetup, zyxelClusterInfoMemberTable=zyxelClusterInfoMemberTable, zyClusterMemberName=zyClusterMemberName, zyClusterCandidateName=zyClusterCandidateName, zyxelClusterStatus=zyxelClusterStatus, zyClusterManagerRowStatus=zyClusterManagerRowStatus, zyxelClusterManagerEntry=zyxelClusterManagerEntry, zyClusterManagerVid=zyClusterManagerVid, zyClusterInfoMemberMacAddress=zyClusterInfoMemberMacAddress, zyxelClusterManagerTable=zyxelClusterManagerTable, zyxelClusterInfoMemberEntry=zyxelClusterInfoMemberEntry, zyxelClusterMemberEntry=zyxelClusterMemberEntry, zyClusterInfoMemberStatus=zyClusterInfoMemberStatus, zyClusterRole=zyClusterRole, zyClusterMemberRowStatus=zyClusterMemberRowStatus, zyxelClusterCandidateTable=zyxelClusterCandidateTable, zyClusterMemberMaxNumberOfMembers=zyClusterMemberMaxNumberOfMembers, zyxelClusterMemberTable=zyxelClusterMemberTable, zyClusterInfoMemberName=zyClusterInfoMemberName, zyClusterManagerName=zyClusterManagerName, zyClusterMemberModel=zyClusterMemberModel, zyClusterMemberMacAddress=zyClusterMemberMacAddress, zyClusterCandidateMacAddress=zyClusterCandidateMacAddress, PYSNMP_MODULE_ID=zyxelCluster, zyClusterMemberPassword=zyClusterMemberPassword, zyxelClusterCandidate=zyxelClusterCandidate, zyClusterManagerMaxNumberOfManagers=zyClusterManagerMaxNumberOfManagers)
| (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, value_range_constraint, single_value_constraint, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ValueSizeConstraint', 'ValueRangeConstraint', 'SingleValueConstraint', 'ConstraintsUnion')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(iso, counter32, unsigned32, counter64, gauge32, integer32, bits, mib_identifier, object_identity, mib_scalar, mib_table, mib_table_row, mib_table_column, ip_address, time_ticks, notification_type, module_identity) = mibBuilder.importSymbols('SNMPv2-SMI', 'iso', 'Counter32', 'Unsigned32', 'Counter64', 'Gauge32', 'Integer32', 'Bits', 'MibIdentifier', 'ObjectIdentity', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'IpAddress', 'TimeTicks', 'NotificationType', 'ModuleIdentity')
(mac_address, display_string, textual_convention, row_status) = mibBuilder.importSymbols('SNMPv2-TC', 'MacAddress', 'DisplayString', 'TextualConvention', 'RowStatus')
(es_mgmt,) = mibBuilder.importSymbols('ZYXEL-ES-SMI', 'esMgmt')
zyxel_cluster = module_identity((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14))
if mibBuilder.loadTexts:
zyxelCluster.setLastUpdated('201207010000Z')
if mibBuilder.loadTexts:
zyxelCluster.setOrganization('Enterprise Solution ZyXEL')
if mibBuilder.loadTexts:
zyxelCluster.setContactInfo('')
if mibBuilder.loadTexts:
zyxelCluster.setDescription('The subtree for cluster')
zyxel_cluster_setup = mib_identifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1))
zyxel_cluster_status = mib_identifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2))
zyxel_cluster_manager = mib_identifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1))
zy_cluster_manager_max_number_of_managers = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
zyClusterManagerMaxNumberOfManagers.setStatus('current')
if mibBuilder.loadTexts:
zyClusterManagerMaxNumberOfManagers.setDescription('The maximum number of cluster managers that can be created.')
zyxel_cluster_manager_table = mib_table((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 2))
if mibBuilder.loadTexts:
zyxelClusterManagerTable.setStatus('current')
if mibBuilder.loadTexts:
zyxelClusterManagerTable.setDescription('The table contains cluster manager configuration.')
zyxel_cluster_manager_entry = mib_table_row((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 2, 1)).setIndexNames((0, 'ZYXEL-CLUSTER-MIB', 'zyClusterManagerVid'))
if mibBuilder.loadTexts:
zyxelClusterManagerEntry.setStatus('current')
if mibBuilder.loadTexts:
zyxelClusterManagerEntry.setDescription('An entry contains cluster manager configuration. ')
zy_cluster_manager_vid = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 2, 1, 1), integer32())
if mibBuilder.loadTexts:
zyClusterManagerVid.setStatus('current')
if mibBuilder.loadTexts:
zyClusterManagerVid.setDescription('This is the VLAN ID and is only applicable if the switch is set to 802.1Q VLAN. All switches must be directly connected and in the same VLAN group to belong to the same cluster.')
zy_cluster_manager_name = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 2, 1, 2), display_string()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
zyClusterManagerName.setStatus('current')
if mibBuilder.loadTexts:
zyClusterManagerName.setDescription('Type a name to identify the cluster manager.')
zy_cluster_manager_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 2, 1, 3), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
zyClusterManagerRowStatus.setStatus('current')
if mibBuilder.loadTexts:
zyClusterManagerRowStatus.setDescription('This object allows cluster manager entries to be created and deleted from cluster manager table.')
zyxel_cluster_members = mib_identifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2))
zy_cluster_member_max_number_of_members = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
zyClusterMemberMaxNumberOfMembers.setStatus('current')
if mibBuilder.loadTexts:
zyClusterMemberMaxNumberOfMembers.setDescription('The maximum number of cluster members that can be created.')
zyxel_cluster_member_table = mib_table((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2))
if mibBuilder.loadTexts:
zyxelClusterMemberTable.setStatus('current')
if mibBuilder.loadTexts:
zyxelClusterMemberTable.setDescription('The table contains cluster member configuration.')
zyxel_cluster_member_entry = mib_table_row((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1)).setIndexNames((0, 'ZYXEL-CLUSTER-MIB', 'zyClusterMemberMacAddress'))
if mibBuilder.loadTexts:
zyxelClusterMemberEntry.setStatus('current')
if mibBuilder.loadTexts:
zyxelClusterMemberEntry.setDescription('An entry contains cluster member configuration.')
zy_cluster_member_mac_address = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1, 1), mac_address())
if mibBuilder.loadTexts:
zyClusterMemberMacAddress.setStatus('current')
if mibBuilder.loadTexts:
zyClusterMemberMacAddress.setDescription("This is the cluster member switch's hardware MAC address.")
zy_cluster_member_name = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1, 2), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
zyClusterMemberName.setStatus('current')
if mibBuilder.loadTexts:
zyClusterMemberName.setDescription("This is the cluster member switch's system name.")
zy_cluster_member_model = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1, 3), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
zyClusterMemberModel.setStatus('current')
if mibBuilder.loadTexts:
zyClusterMemberModel.setDescription("This is the cluster member switch's model name.")
zy_cluster_member_password = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1, 4), display_string()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
zyClusterMemberPassword.setStatus('current')
if mibBuilder.loadTexts:
zyClusterMemberPassword.setDescription("Each cluster member's password is its administration password.")
zy_cluster_member_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1, 5), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
zyClusterMemberRowStatus.setStatus('current')
if mibBuilder.loadTexts:
zyClusterMemberRowStatus.setDescription('This object allows cluster member entries to be created and deleted from cluster member table.')
zyxel_cluster_candidate = mib_identifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1))
zyxel_cluster_candidate_table = mib_table((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1, 1))
if mibBuilder.loadTexts:
zyxelClusterCandidateTable.setStatus('current')
if mibBuilder.loadTexts:
zyxelClusterCandidateTable.setDescription('The table contains cluster candidate information.')
zyxel_cluster_candidate_entry = mib_table_row((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1, 1, 1)).setIndexNames((0, 'ZYXEL-CLUSTER-MIB', 'zyClusterCandidateMacAddress'))
if mibBuilder.loadTexts:
zyxelClusterCandidateEntry.setStatus('current')
if mibBuilder.loadTexts:
zyxelClusterCandidateEntry.setDescription('An entry contains cluster candidate information.')
zy_cluster_candidate_mac_address = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1, 1, 1, 1), mac_address())
if mibBuilder.loadTexts:
zyClusterCandidateMacAddress.setStatus('current')
if mibBuilder.loadTexts:
zyClusterCandidateMacAddress.setDescription("This is the cluster candidate switch's hardware MAC address.")
zy_cluster_candidate_name = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1, 1, 1, 2), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
zyClusterCandidateName.setStatus('current')
if mibBuilder.loadTexts:
zyClusterCandidateName.setDescription("This is the cluster candidate switch's system name.")
zy_cluster_candidate_model = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1, 1, 1, 3), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
zyClusterCandidateModel.setStatus('current')
if mibBuilder.loadTexts:
zyClusterCandidateModel.setDescription("This is the cluster candidate switch's model name.")
zy_cluster_role = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2))).clone(namedValues=named_values(('none', 0), ('manager', 1), ('member', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
zyClusterRole.setStatus('current')
if mibBuilder.loadTexts:
zyClusterRole.setDescription('The role of this switch within the cluster.')
zy_cluster_info_manager = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 3), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
zyClusterInfoManager.setStatus('current')
if mibBuilder.loadTexts:
zyClusterInfoManager.setDescription("The cluster manager switch's hardware MAC address.")
zyxel_cluster_info_member_table = mib_table((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4))
if mibBuilder.loadTexts:
zyxelClusterInfoMemberTable.setStatus('current')
if mibBuilder.loadTexts:
zyxelClusterInfoMemberTable.setDescription('The table contains cluster member information.')
zyxel_cluster_info_member_entry = mib_table_row((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4, 1)).setIndexNames((0, 'ZYXEL-CLUSTER-MIB', 'zyClusterInfoMemberMacAddress'))
if mibBuilder.loadTexts:
zyxelClusterInfoMemberEntry.setStatus('current')
if mibBuilder.loadTexts:
zyxelClusterInfoMemberEntry.setDescription('An entry contains cluster member information.')
zy_cluster_info_member_mac_address = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4, 1, 1), mac_address())
if mibBuilder.loadTexts:
zyClusterInfoMemberMacAddress.setStatus('current')
if mibBuilder.loadTexts:
zyClusterInfoMemberMacAddress.setDescription("This is the cluster member switch's hardware MAC address.")
zy_cluster_info_member_name = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4, 1, 2), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
zyClusterInfoMemberName.setStatus('current')
if mibBuilder.loadTexts:
zyClusterInfoMemberName.setDescription("This is the cluster member switch's system name.")
zy_cluster_info_member_model = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4, 1, 3), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
zyClusterInfoMemberModel.setStatus('current')
if mibBuilder.loadTexts:
zyClusterInfoMemberModel.setDescription("This is the cluster member switch's model name.")
zy_cluster_info_member_status = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2))).clone(namedValues=named_values(('error', 0), ('online', 1), ('offline', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
zyClusterInfoMemberStatus.setStatus('current')
if mibBuilder.loadTexts:
zyClusterInfoMemberStatus.setDescription('There are three types in cluster status. Online(the cluster member switch is accessible), Error (for example, the cluster member switch password was changed or the switch was set as the manager and so left the member list, etc.), Offline (the switch is disconnected - Offline shows approximately 1.5 minutes after the link between cluster member and manager goes down).')
mibBuilder.exportSymbols('ZYXEL-CLUSTER-MIB', zyClusterCandidateModel=zyClusterCandidateModel, zyxelClusterManager=zyxelClusterManager, zyxelClusterCandidateEntry=zyxelClusterCandidateEntry, zyxelClusterMembers=zyxelClusterMembers, zyxelCluster=zyxelCluster, zyClusterInfoManager=zyClusterInfoManager, zyClusterInfoMemberModel=zyClusterInfoMemberModel, zyxelClusterSetup=zyxelClusterSetup, zyxelClusterInfoMemberTable=zyxelClusterInfoMemberTable, zyClusterMemberName=zyClusterMemberName, zyClusterCandidateName=zyClusterCandidateName, zyxelClusterStatus=zyxelClusterStatus, zyClusterManagerRowStatus=zyClusterManagerRowStatus, zyxelClusterManagerEntry=zyxelClusterManagerEntry, zyClusterManagerVid=zyClusterManagerVid, zyClusterInfoMemberMacAddress=zyClusterInfoMemberMacAddress, zyxelClusterManagerTable=zyxelClusterManagerTable, zyxelClusterInfoMemberEntry=zyxelClusterInfoMemberEntry, zyxelClusterMemberEntry=zyxelClusterMemberEntry, zyClusterInfoMemberStatus=zyClusterInfoMemberStatus, zyClusterRole=zyClusterRole, zyClusterMemberRowStatus=zyClusterMemberRowStatus, zyxelClusterCandidateTable=zyxelClusterCandidateTable, zyClusterMemberMaxNumberOfMembers=zyClusterMemberMaxNumberOfMembers, zyxelClusterMemberTable=zyxelClusterMemberTable, zyClusterInfoMemberName=zyClusterInfoMemberName, zyClusterManagerName=zyClusterManagerName, zyClusterMemberModel=zyClusterMemberModel, zyClusterMemberMacAddress=zyClusterMemberMacAddress, zyClusterCandidateMacAddress=zyClusterCandidateMacAddress, PYSNMP_MODULE_ID=zyxelCluster, zyClusterMemberPassword=zyClusterMemberPassword, zyxelClusterCandidate=zyxelClusterCandidate, zyClusterManagerMaxNumberOfManagers=zyClusterManagerMaxNumberOfManagers) |
# import math
# def squareRoot(a):
# return round(math.sqrt(float(a)),9)
def squareRoot(a):
return round(float(a)**(1/2),8) | def square_root(a):
return round(float(a) ** (1 / 2), 8) |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
if not head:
return None
dummyHead = currentNode = ListNode()
dummyHead.next = head
while currentNode.next:
if currentNode.next.val == val:
currentNode.next = currentNode.next.next
else:
currentNode = currentNode.next
return dummyHead.next
| class Solution:
def remove_elements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
if not head:
return None
dummy_head = current_node = list_node()
dummyHead.next = head
while currentNode.next:
if currentNode.next.val == val:
currentNode.next = currentNode.next.next
else:
current_node = currentNode.next
return dummyHead.next |
alist = [10, 20, 23, 26, 27, 35, 38, 41, 46, 49, 54, 56, 64, 70, 81, 87, 88, 90, 92, 96, 98]
temp = None
def binary_search(left: int, right: int, key: int) -> int:
global temp
if len(alist) == 1:
if alist[left] == key:
return alist[left]
else:
return 0
else:
mid = (left + right) // 2
print("mid ", mid)
if mid == temp or mid > len(alist) - 1: # Condition for preventing the deep recursion.
return 0
else:
temp = mid
if alist[mid] == key:
return alist[mid]
elif key < alist[mid]:
return binary_search(left, mid - 1, key)
else:
return binary_search(mid + 1, right, key)
"""
This segment for dynamic of the program
"""
# while True:
# a = input("Enter the element of the list = ")
# if a == "":
# break
# else:
# alist.append(int(a))
alist.sort()
print(alist)
print(len(alist))
search_key = int(input("Enter the number you want to search = "))
result = binary_search(0, len(alist), search_key)
print(result)
| alist = [10, 20, 23, 26, 27, 35, 38, 41, 46, 49, 54, 56, 64, 70, 81, 87, 88, 90, 92, 96, 98]
temp = None
def binary_search(left: int, right: int, key: int) -> int:
global temp
if len(alist) == 1:
if alist[left] == key:
return alist[left]
else:
return 0
else:
mid = (left + right) // 2
print('mid ', mid)
if mid == temp or mid > len(alist) - 1:
return 0
else:
temp = mid
if alist[mid] == key:
return alist[mid]
elif key < alist[mid]:
return binary_search(left, mid - 1, key)
else:
return binary_search(mid + 1, right, key)
' \nThis segment for dynamic of the program\n'
alist.sort()
print(alist)
print(len(alist))
search_key = int(input('Enter the number you want to search = '))
result = binary_search(0, len(alist), search_key)
print(result) |
class HTTPError(Exception):
"""Http Error Exception"""
pass
| class Httperror(Exception):
"""Http Error Exception"""
pass |
# 2021 April 16. Surrendered entirely.
# 2-d dp.
# text1 = "abcba", text2 = "abcbcba"
# At any two positions i, j in t1 and t2, if 1) t1[i] == t2[j]
# then the length of common subsequence count should increment by 1 and
# we then check from t1[i+1] and t2[j+1]. If 2) t1[i] != t2[j], then we
# should keep on finding common susbequence of t1[i], t2[j+1] and t1[i+1]
# and t2[j], whichever includes a bigger common subsequence. So in the
# example, checking from the left to the right, "abcb" is common (logic 1)
# at work). Then we are left with "a" vs. "cba", "a","c" don't match, so
# dp of "a","c" refers to "","c" (0) and "a","b", which in turn refers
# to "", "b"(0) and "a", "a". Since "a","a" is a match, dp of it is 1
# plus that of "", "", which is 0. So the boundary of common subseq
# length all 0, propagates the value back to the topleft corner
# dp[0][0] that we want, through some route that is determined by the
# matchings in the two texts. But algo won't know which route it takes
# beforehand, so solving the entire matrix, from bottom right to top left
# , would be necessary.
# dp a b c b a ""
# a 1 0
# b 1 0
# c 1 0
# b 1 0
# c *,1 0
# b *,1 0
# a 1 0
# "" 0 0 0 0 0 0
# * represents not knowing the value first, have to check right and
# downward. This checking keeps going until it reaches the bottom.
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
# One additional row and col to store bounary conditions.
# 0, 1, ..., len(text1) - 1, for each char in text1, then len(text1) for boundary 0.
ROWS, COLS = len(text1) + 1, len(text2) + 1
dp = [[0 for _ in range(COLS)] for _ in range(ROWS)]
for row in range(ROWS - 2, -1, -1):
for col in range(COLS - 2, -1, -1):
if text1[row] == text2[col]:
dp[row][col] = 1 + dp[row+1][col+1]
else:
dp[row][col] = max(dp[row+1][col], dp[row][col+1])
return dp[0][0]
if __name__ == "__main__":
print(Solution().longestCommonSubsequence("papmretkborsrurgtina", "nsnupotstmnkfcfavaxgl")) | class Solution:
def longest_common_subsequence(self, text1: str, text2: str) -> int:
(rows, cols) = (len(text1) + 1, len(text2) + 1)
dp = [[0 for _ in range(COLS)] for _ in range(ROWS)]
for row in range(ROWS - 2, -1, -1):
for col in range(COLS - 2, -1, -1):
if text1[row] == text2[col]:
dp[row][col] = 1 + dp[row + 1][col + 1]
else:
dp[row][col] = max(dp[row + 1][col], dp[row][col + 1])
return dp[0][0]
if __name__ == '__main__':
print(solution().longestCommonSubsequence('papmretkborsrurgtina', 'nsnupotstmnkfcfavaxgl')) |
class PxLoadBar(object):
"""
Visualizes system load in a horizontal bar.
Inputs are:
* System load
* Number of physical cores
* Number of logical cores
* How many columns wide the horizontal bar should be
The output is a horizontal bar string.
Load below the number of physical cores is visualized in green.
Load between the number of physical cores and logical cores is visualized in
yellow.
Load above of the number of logical cores is visualized in red.
As long as load is below the number of physical cores, it will use only the
first half of the output string.
Load up to twice the number of physical cores will go up to the end of the
string.
"""
def __init__(self, physical=None, logical=None):
if physical is None or physical < 1:
raise ValueError("Physical must be a positive integer, was: %r" % (physical,))
if logical is None or logical < physical:
raise ValueError("Logical must be >= physical, was: %r (vs %r)" % (logical, physical))
self._physical = physical
self._logical = logical
CSI = b"\x1b["
self.normal = CSI + b"m"
self.inverse = CSI + b"0;7m"
self.red = CSI + b"27;1;37;41m"
self.yellow = CSI + b"27;1;37;43m"
self.green = CSI + b"27;1;37;42m"
def _get_colored_bytes(self, load=None, columns=None, text=""):
"Yields pairs, with each pair containing a color and a byte"
maxlength = columns - 2 # Leave room for a starting and an ending space
if len(text) > maxlength:
text = text[0:(maxlength - 1)]
text = text + ' ' * (maxlength - len(text))
text = " " + text + " "
assert len(text) == columns
max_value = self._physical
if load > max_value:
max_value = 1.0 * load
UNUSED = 1000 * max_value
if load < self._physical:
yellow_start = UNUSED
red_start = UNUSED
inverse_start = load
normal_start = self._physical
else:
yellow_start = self._physical
red_start = self._logical
inverse_start = UNUSED
normal_start = load
# Scale the values to the number of columns
yellow_start = yellow_start * columns / max_value - 0.5
red_start = red_start * columns / max_value - 0.5
inverse_start = inverse_start * columns / max_value - 0.5
normal_start = normal_start * columns / max_value - 0.5
for i in range(columns):
# We always start out green
color = self.green
if i >= yellow_start:
color = self.yellow
if i >= red_start:
color = self.red
if i >= inverse_start:
color = self.inverse
if i >= normal_start:
color = self.normal
yield (color, text[i].encode('utf-8'))
def get_bar(self, load=None, columns=None, text=""):
if load is None:
raise ValueError("Missing required parameter load=")
if columns is None:
raise ValueError("Missing required parameter columns=")
return_me = b''
color = self.normal
for color_and_byte in self._get_colored_bytes(load=load, columns=columns, text=text):
if color_and_byte[0] != color:
return_me += color_and_byte[0]
color = color_and_byte[0]
return_me += color_and_byte[1]
if color != self.normal:
return_me += self.normal
return return_me
| class Pxloadbar(object):
"""
Visualizes system load in a horizontal bar.
Inputs are:
* System load
* Number of physical cores
* Number of logical cores
* How many columns wide the horizontal bar should be
The output is a horizontal bar string.
Load below the number of physical cores is visualized in green.
Load between the number of physical cores and logical cores is visualized in
yellow.
Load above of the number of logical cores is visualized in red.
As long as load is below the number of physical cores, it will use only the
first half of the output string.
Load up to twice the number of physical cores will go up to the end of the
string.
"""
def __init__(self, physical=None, logical=None):
if physical is None or physical < 1:
raise value_error('Physical must be a positive integer, was: %r' % (physical,))
if logical is None or logical < physical:
raise value_error('Logical must be >= physical, was: %r (vs %r)' % (logical, physical))
self._physical = physical
self._logical = logical
csi = b'\x1b['
self.normal = CSI + b'm'
self.inverse = CSI + b'0;7m'
self.red = CSI + b'27;1;37;41m'
self.yellow = CSI + b'27;1;37;43m'
self.green = CSI + b'27;1;37;42m'
def _get_colored_bytes(self, load=None, columns=None, text=''):
"""Yields pairs, with each pair containing a color and a byte"""
maxlength = columns - 2
if len(text) > maxlength:
text = text[0:maxlength - 1]
text = text + ' ' * (maxlength - len(text))
text = ' ' + text + ' '
assert len(text) == columns
max_value = self._physical
if load > max_value:
max_value = 1.0 * load
unused = 1000 * max_value
if load < self._physical:
yellow_start = UNUSED
red_start = UNUSED
inverse_start = load
normal_start = self._physical
else:
yellow_start = self._physical
red_start = self._logical
inverse_start = UNUSED
normal_start = load
yellow_start = yellow_start * columns / max_value - 0.5
red_start = red_start * columns / max_value - 0.5
inverse_start = inverse_start * columns / max_value - 0.5
normal_start = normal_start * columns / max_value - 0.5
for i in range(columns):
color = self.green
if i >= yellow_start:
color = self.yellow
if i >= red_start:
color = self.red
if i >= inverse_start:
color = self.inverse
if i >= normal_start:
color = self.normal
yield (color, text[i].encode('utf-8'))
def get_bar(self, load=None, columns=None, text=''):
if load is None:
raise value_error('Missing required parameter load=')
if columns is None:
raise value_error('Missing required parameter columns=')
return_me = b''
color = self.normal
for color_and_byte in self._get_colored_bytes(load=load, columns=columns, text=text):
if color_and_byte[0] != color:
return_me += color_and_byte[0]
color = color_and_byte[0]
return_me += color_and_byte[1]
if color != self.normal:
return_me += self.normal
return return_me |
"""
FizzBuzz is a classical interview question.
We will implement a modified version of it, however, you can also find the original version on the web if you are interested.
Write a program that takes a number from the user.
If this number is negative, print an error message
if this number is a multiple of 3, print 'Fizz'
if this number is a multiple of 5, print 'Buzz'
if this number is a multiple of 15, print 'FizzBuzz'
otherwise, print the number itself.
You can assume user will enter a valid integer value.
Examples:
Please enter a number: 25
Buzz
Please enter a number: -5
You entered a negative number!
Please enter a number: 2
2
Please enter a number: 36
Fizz
Please enter a number: 3330
FizzBuzz
"""
number = int(input('Enter a number: '))
if number < 0:
print('You entered a negative number!')
elif number % 15 == 0:
print('FizzBuzz')
elif number % 3 == 0:
print('Fizz')
elif number % 5 == 0:
print('Buzz')
else:
print(number)
| """
FizzBuzz is a classical interview question.
We will implement a modified version of it, however, you can also find the original version on the web if you are interested.
Write a program that takes a number from the user.
If this number is negative, print an error message
if this number is a multiple of 3, print 'Fizz'
if this number is a multiple of 5, print 'Buzz'
if this number is a multiple of 15, print 'FizzBuzz'
otherwise, print the number itself.
You can assume user will enter a valid integer value.
Examples:
Please enter a number: 25
Buzz
Please enter a number: -5
You entered a negative number!
Please enter a number: 2
2
Please enter a number: 36
Fizz
Please enter a number: 3330
FizzBuzz
"""
number = int(input('Enter a number: '))
if number < 0:
print('You entered a negative number!')
elif number % 15 == 0:
print('FizzBuzz')
elif number % 3 == 0:
print('Fizz')
elif number % 5 == 0:
print('Buzz')
else:
print(number) |
class BaseSensor():
def __init__(self):
self.null_value = 0
self.sensor = None
self.measurements = []
self.upper_reasonable_bound = 200
self.lower_reasonable_bound = 0
def setup(self):
self.sensor = None
def read(self):
return None
def average(self, measurements):
if len(measurements) != 0:
return sum(measurements)/len(measurements)
else:
return self.null_value
def rolling_average(self, measurement, measurements, size):
if measurement == None:
return None
if self.lower_reasonable_bound < measurement < self.upper_reasonable_bound:
if len(measurements) >= size:
measurements.pop(0)
measurements.append(measurement)
return self.average(measurements)
def mapNum(self, val, old_max, old_min, new_max, new_min):
try:
old_range = float(old_max - old_min)
new_range = float(new_max - new_min)
new_value = float(((val - old_min) * new_range) / old_range) + new_min
return new_value
except Exception:
return val
| class Basesensor:
def __init__(self):
self.null_value = 0
self.sensor = None
self.measurements = []
self.upper_reasonable_bound = 200
self.lower_reasonable_bound = 0
def setup(self):
self.sensor = None
def read(self):
return None
def average(self, measurements):
if len(measurements) != 0:
return sum(measurements) / len(measurements)
else:
return self.null_value
def rolling_average(self, measurement, measurements, size):
if measurement == None:
return None
if self.lower_reasonable_bound < measurement < self.upper_reasonable_bound:
if len(measurements) >= size:
measurements.pop(0)
measurements.append(measurement)
return self.average(measurements)
def map_num(self, val, old_max, old_min, new_max, new_min):
try:
old_range = float(old_max - old_min)
new_range = float(new_max - new_min)
new_value = float((val - old_min) * new_range / old_range) + new_min
return new_value
except Exception:
return val |
def time_in_range(data, bg_range=(4.0, 7.0)):
# data[0] is the time values - assume they are equally spaced, so we can ignore
values = data[1]
return 100.0 * sum([bg_range[0] <= v <= bg_range[1] for v in values]) / len(values)
def mean(data):
values = data[1]
return float(sum(values)) / len(values)
def estimated_hba1c(data):
# from https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2742903/
return hba1c_ngsp_to_ifcc((mean(data) + 2.59) / 1.59)
def hba1c_ngsp_to_ifcc(ngsp):
# from http://www.ngsp.org/ifccngsp.asp
return 10.93 * ngsp - 23.50
| def time_in_range(data, bg_range=(4.0, 7.0)):
values = data[1]
return 100.0 * sum([bg_range[0] <= v <= bg_range[1] for v in values]) / len(values)
def mean(data):
values = data[1]
return float(sum(values)) / len(values)
def estimated_hba1c(data):
return hba1c_ngsp_to_ifcc((mean(data) + 2.59) / 1.59)
def hba1c_ngsp_to_ifcc(ngsp):
return 10.93 * ngsp - 23.5 |
def maior_primo(x) -> object:
for maior in reversed(range(1,x+1)):
if all(maior%n!=0 for n in range(2,maior)):
return maior
| def maior_primo(x) -> object:
for maior in reversed(range(1, x + 1)):
if all((maior % n != 0 for n in range(2, maior))):
return maior |
USER_CREATED = "user_created"
USER_ADDED = "user_added_to_request"
USER_REMOVED = "user_removed_from_request"
USER_PERM_CHANGED = "user_permissions_changed"
USER_STATUS_CHANGED = "user_status_changed" # user, admin, super
USER_INFO_EDITED = "user_information_edited"
REQUESTER_INFO_EDITED = "requester_information_edited"
REQ_CREATED = "request_created"
AGENCY_REQ_CREATED = "agency_submitted_request"
REQ_ACKNOWLEDGED = "request_acknowledged"
REQ_DENIED = "request_denied"
REQ_STATUS_CHANGED = "request_status_changed"
REQ_EXTENDED = "request_extended"
REQ_CLOSED = "request_closed"
REQ_REOPENED = "request_reopened"
REQ_TITLE_EDITED = "request_title_edited"
REQ_AGENCY_REQ_SUM_EDITED = "request_agency_request_summary_edited"
REQ_TITLE_PRIVACY_EDITED = "request_title_privacy_edited"
REQ_AGENCY_REQ_SUM_PRIVACY_EDITED = "request_agency_request_summary_privacy_edited"
REQ_AGENCY_REQ_SUM_DATE_SET = "request_agency_request_summary_date_set"
REQ_POINT_OF_CONTACT_ADDED = "request_point_of_contact_added"
REQ_POINT_OF_CONTACT_REMOVED = "request_point_of_contact_removed"
EMAIL_NOTIFICATION_SENT = "email_notification_sent"
FILE_ADDED = "file_added"
FILE_EDITED = "file_edited"
FILE_PRIVACY_EDITED = "file_privacy_edited"
FILE_REPLACED = "file_replaced"
FILE_REMOVED = "file_removed"
LINK_ADDED = "link_added"
LINK_EDITED = "link_edited"
LINK_PRIVACY_EDITED = "link_privacy_edited"
LINK_REMOVED = "link_removed"
INSTRUCTIONS_ADDED = "instructions_added"
INSTRUCTIONS_EDITED = "instructions_edited"
INSTRUCTIONS_PRIVACY_EDITED = "instructions_privacy_edited"
INSTRUCTIONS_REMOVED = "instructions_removed"
NOTE_ADDED = "note_added"
NOTE_EDITED = "note_edited"
NOTE_PRIVACY_EDITED = "note_privacy_edited"
NOTE_REMOVED = "note_removed"
AGENCY_ACTIVATED = "agency_activated"
AGENCY_DEACTIVATED = "agency_deactivated"
AGENCY_USER_ACTIVATED = "agency_user_activated"
AGENCY_USER_DEACTIVATED = "agency_user_deactivated"
CONTACT_EMAIL_SENT = "contact_email_sent"
USER_LOGIN = "user_logged_in"
USER_AUTHORIZED = "user_authorized"
USER_LOGGED_OUT = "user_logged_out"
USER_MADE_AGENCY_ADMIN = "user_made_agency_admin"
USER_MADE_AGENCY_USER = "user_made_agency_user"
USER_PROFILE_UPDATED = "user_profile_updated"
ACKNOWLEDGMENT_LETTER_CREATED = 'acknowledgment_letter_created'
DENIAL_LETTER_CREATED = 'denial_letter_created'
CLOSING_LETTER_CREATED = 'closing_letter_created'
EXTENSION_LETTER_CREATED = 'extension_letter_created'
ENVELOPE_CREATED = 'envelope_created'
RESPONSE_LETTER_CREATED = 'response_letter_created'
REOPENING_LETTER_CREATED = 'reopening_letter_created'
FOR_REQUEST_HISTORY = [
USER_ADDED,
USER_REMOVED,
USER_PERM_CHANGED,
REQUESTER_INFO_EDITED,
REQ_CREATED,
AGENCY_REQ_CREATED,
REQ_STATUS_CHANGED,
REQ_ACKNOWLEDGED,
REQ_EXTENDED,
REQ_CLOSED,
REQ_REOPENED,
REQ_TITLE_EDITED,
REQ_AGENCY_REQ_SUM_EDITED,
REQ_TITLE_PRIVACY_EDITED,
REQ_AGENCY_REQ_SUM_PRIVACY_EDITED,
FILE_ADDED,
FILE_EDITED,
FILE_REMOVED,
LINK_ADDED,
LINK_EDITED,
LINK_REMOVED,
INSTRUCTIONS_ADDED,
INSTRUCTIONS_EDITED,
INSTRUCTIONS_REMOVED,
NOTE_ADDED,
NOTE_EDITED,
NOTE_REMOVED,
ENVELOPE_CREATED,
RESPONSE_LETTER_CREATED
]
RESPONSE_ADDED_TYPES = [
FILE_ADDED,
LINK_ADDED,
INSTRUCTIONS_ADDED,
NOTE_ADDED,
]
RESPONSE_EDITED_TYPES = [
FILE_EDITED,
FILE_REPLACED,
FILE_PRIVACY_EDITED,
LINK_EDITED,
LINK_PRIVACY_EDITED,
INSTRUCTIONS_EDITED,
INSTRUCTIONS_PRIVACY_EDITED,
NOTE_ADDED,
NOTE_PRIVACY_EDITED
]
RESPONSE_REMOVED_TYPES = [
FILE_REMOVED,
LINK_REMOVED,
INSTRUCTIONS_REMOVED,
NOTE_REMOVED
]
SYSTEM_TYPES = [
AGENCY_ACTIVATED,
AGENCY_DEACTIVATED,
AGENCY_USER_ACTIVATED,
AGENCY_USER_DEACTIVATED,
CONTACT_EMAIL_SENT,
USER_LOGIN,
USER_AUTHORIZED,
USER_LOGGED_OUT,
USER_MADE_AGENCY_ADMIN,
USER_MADE_AGENCY_USER,
USER_PROFILE_UPDATED
]
| user_created = 'user_created'
user_added = 'user_added_to_request'
user_removed = 'user_removed_from_request'
user_perm_changed = 'user_permissions_changed'
user_status_changed = 'user_status_changed'
user_info_edited = 'user_information_edited'
requester_info_edited = 'requester_information_edited'
req_created = 'request_created'
agency_req_created = 'agency_submitted_request'
req_acknowledged = 'request_acknowledged'
req_denied = 'request_denied'
req_status_changed = 'request_status_changed'
req_extended = 'request_extended'
req_closed = 'request_closed'
req_reopened = 'request_reopened'
req_title_edited = 'request_title_edited'
req_agency_req_sum_edited = 'request_agency_request_summary_edited'
req_title_privacy_edited = 'request_title_privacy_edited'
req_agency_req_sum_privacy_edited = 'request_agency_request_summary_privacy_edited'
req_agency_req_sum_date_set = 'request_agency_request_summary_date_set'
req_point_of_contact_added = 'request_point_of_contact_added'
req_point_of_contact_removed = 'request_point_of_contact_removed'
email_notification_sent = 'email_notification_sent'
file_added = 'file_added'
file_edited = 'file_edited'
file_privacy_edited = 'file_privacy_edited'
file_replaced = 'file_replaced'
file_removed = 'file_removed'
link_added = 'link_added'
link_edited = 'link_edited'
link_privacy_edited = 'link_privacy_edited'
link_removed = 'link_removed'
instructions_added = 'instructions_added'
instructions_edited = 'instructions_edited'
instructions_privacy_edited = 'instructions_privacy_edited'
instructions_removed = 'instructions_removed'
note_added = 'note_added'
note_edited = 'note_edited'
note_privacy_edited = 'note_privacy_edited'
note_removed = 'note_removed'
agency_activated = 'agency_activated'
agency_deactivated = 'agency_deactivated'
agency_user_activated = 'agency_user_activated'
agency_user_deactivated = 'agency_user_deactivated'
contact_email_sent = 'contact_email_sent'
user_login = 'user_logged_in'
user_authorized = 'user_authorized'
user_logged_out = 'user_logged_out'
user_made_agency_admin = 'user_made_agency_admin'
user_made_agency_user = 'user_made_agency_user'
user_profile_updated = 'user_profile_updated'
acknowledgment_letter_created = 'acknowledgment_letter_created'
denial_letter_created = 'denial_letter_created'
closing_letter_created = 'closing_letter_created'
extension_letter_created = 'extension_letter_created'
envelope_created = 'envelope_created'
response_letter_created = 'response_letter_created'
reopening_letter_created = 'reopening_letter_created'
for_request_history = [USER_ADDED, USER_REMOVED, USER_PERM_CHANGED, REQUESTER_INFO_EDITED, REQ_CREATED, AGENCY_REQ_CREATED, REQ_STATUS_CHANGED, REQ_ACKNOWLEDGED, REQ_EXTENDED, REQ_CLOSED, REQ_REOPENED, REQ_TITLE_EDITED, REQ_AGENCY_REQ_SUM_EDITED, REQ_TITLE_PRIVACY_EDITED, REQ_AGENCY_REQ_SUM_PRIVACY_EDITED, FILE_ADDED, FILE_EDITED, FILE_REMOVED, LINK_ADDED, LINK_EDITED, LINK_REMOVED, INSTRUCTIONS_ADDED, INSTRUCTIONS_EDITED, INSTRUCTIONS_REMOVED, NOTE_ADDED, NOTE_EDITED, NOTE_REMOVED, ENVELOPE_CREATED, RESPONSE_LETTER_CREATED]
response_added_types = [FILE_ADDED, LINK_ADDED, INSTRUCTIONS_ADDED, NOTE_ADDED]
response_edited_types = [FILE_EDITED, FILE_REPLACED, FILE_PRIVACY_EDITED, LINK_EDITED, LINK_PRIVACY_EDITED, INSTRUCTIONS_EDITED, INSTRUCTIONS_PRIVACY_EDITED, NOTE_ADDED, NOTE_PRIVACY_EDITED]
response_removed_types = [FILE_REMOVED, LINK_REMOVED, INSTRUCTIONS_REMOVED, NOTE_REMOVED]
system_types = [AGENCY_ACTIVATED, AGENCY_DEACTIVATED, AGENCY_USER_ACTIVATED, AGENCY_USER_DEACTIVATED, CONTACT_EMAIL_SENT, USER_LOGIN, USER_AUTHORIZED, USER_LOGGED_OUT, USER_MADE_AGENCY_ADMIN, USER_MADE_AGENCY_USER, USER_PROFILE_UPDATED] |
# Find the sum of the numbers 8, 9, 10
# Var declarations
num1 = 8
num2 = 9
num3 = 10
# Code
sum = num1 + num2 + num3
# Result
print(sum) | num1 = 8
num2 = 9
num3 = 10
sum = num1 + num2 + num3
print(sum) |
# Write your make_spoonerism function here:
def make_spoonerism(word1, word2):
a = word1[0]
b = word2[0]
c = word1[0].replace(a,b) + word1[1:]
d = word2[0].replace(b,a) + word2[1:]
e = c + ' ' + d
return e
# Uncomment these function calls to test your function:
print(make_spoonerism("Codecademy", "Learn"))
# should print Lodecademy Cearn
print(make_spoonerism("Hello", "world!"))
# should print wello Horld!
print(make_spoonerism("a", "b"))
# should print b a
# OR
# OR
# # Write your make_spoonerism function here:
# def make_spoonerism(word1, word2):
# return word2[0]+word1[1:]+" "+word1[0]+word2[1:]
# # Uncomment these function calls to test your tip function:
# print(make_spoonerism("Codecademy", "Learn"))
# # should print Lodecademy Cearn
# print(make_spoonerism("Hello", "world!"))
# # should print wello Horld!
# print(make_spoonerism("a", "b"))
# # should print b a
| def make_spoonerism(word1, word2):
a = word1[0]
b = word2[0]
c = word1[0].replace(a, b) + word1[1:]
d = word2[0].replace(b, a) + word2[1:]
e = c + ' ' + d
return e
print(make_spoonerism('Codecademy', 'Learn'))
print(make_spoonerism('Hello', 'world!'))
print(make_spoonerism('a', 'b')) |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"trace_log": "01_convert_time_log.ipynb",
"format_value": "01_convert_time_log.ipynb",
"strip_extra_EnmacClientTime_elements": "01_convert_time_log.ipynb",
"unix_time_milliseconds": "01_convert_time_log.ipynb",
"parse_dt": "01_convert_time_log.ipynb",
"parse_dt_to_milliseconds": "01_convert_time_log.ipynb",
"parse_httpd_dt": "01_convert_time_log.ipynb",
"parse_httpd_dt_to_milliseconds": "01_convert_time_log.ipynb",
"match_last2digits": "01_convert_time_log.ipynb",
"parse_timing_log": "01_convert_time_log.ipynb",
"parse_log_line": "01_convert_time_log.ipynb",
"parse_log_line_to_dict": "01_convert_time_log.ipynb",
"parse_httpd_log": "01_convert_time_log.ipynb",
"log_re": "01_convert_time_log.ipynb",
"request_re": "01_convert_time_log.ipynb",
"parse_httpd_log_file": "01_convert_time_log.ipynb",
"parse_timing_log_file": "01_convert_time_log.ipynb"}
modules = ["convert_time_log.py"]
doc_url = "https://3ideas.github.io/cronos/"
git_url = "https://github.com/3ideas/cronos/tree/master/"
def custom_doc_links(name): return None
| __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'trace_log': '01_convert_time_log.ipynb', 'format_value': '01_convert_time_log.ipynb', 'strip_extra_EnmacClientTime_elements': '01_convert_time_log.ipynb', 'unix_time_milliseconds': '01_convert_time_log.ipynb', 'parse_dt': '01_convert_time_log.ipynb', 'parse_dt_to_milliseconds': '01_convert_time_log.ipynb', 'parse_httpd_dt': '01_convert_time_log.ipynb', 'parse_httpd_dt_to_milliseconds': '01_convert_time_log.ipynb', 'match_last2digits': '01_convert_time_log.ipynb', 'parse_timing_log': '01_convert_time_log.ipynb', 'parse_log_line': '01_convert_time_log.ipynb', 'parse_log_line_to_dict': '01_convert_time_log.ipynb', 'parse_httpd_log': '01_convert_time_log.ipynb', 'log_re': '01_convert_time_log.ipynb', 'request_re': '01_convert_time_log.ipynb', 'parse_httpd_log_file': '01_convert_time_log.ipynb', 'parse_timing_log_file': '01_convert_time_log.ipynb'}
modules = ['convert_time_log.py']
doc_url = 'https://3ideas.github.io/cronos/'
git_url = 'https://github.com/3ideas/cronos/tree/master/'
def custom_doc_links(name):
return None |
#Planetary database
#Source for planetary data, and some of the data on
#the moons, is http://nssdc.gsfc.nasa.gov/planetary/factsheet/
class Planet:
'''
A Planet object contains basic planetary data.
If P is a Planet object, the data are:
P.name = Name of the planet
P.a = Mean radius of planet (m)
P.g = Surface gravitational acceleration (m/s**2)
P.L = Annual mean solar constant (current) (W/m**2)
P.albedo Bond albedo (fraction)
P.rsm = Semi-major axis of orbit about Sun (m)
P.year = Sidereal length of year (s)
P.eccentricity = Eccentricity (unitless)
P.day = Mean tropical length of day (s)
P.obliquity = Obliquity to orbit (degrees)
P.Lequinox = Longitude of equinox (degrees)
P.Tsbar = Mean surface temperature (K)
P.Tsmax = Maximum surface temperature (K)
For gas giants, "surface" quantities are given at the 1 bar level
'''
#__repr__ object prints out a help string when help is
#invoked on the planet object or the planet name is typed
def __repr__(self):
line1 =\
'This planet object contains information on %s\n'%self.name
line2 = 'Type \"help(Planet)\" for more information\n'
return line1+line2
def __init__(self):
self.name = None #Name of the planet
self.a = None #Mean radius of planet
self.g = None #Surface gravitational acceleration
self.L = None #Annual mean solar constant (current)
self.albedo = None #Bond albedo
self.rsm = None #Semi-major axis
self.year = None #Sidereal length of year
self.eccentricity = None # Eccentricity
self.day = None #Mean tropical length of day
self.obliquity = None #Obliquity to orbit
self.Lequinox = None #Longitude of equinox
self.Tsbar = None #Mean surface temperature
self.Tsmax = None #Maximum surface temperature
#----------------------------------------------------
Mercury = Planet()
Mercury.name = 'Mercury' #Name of the planet
Mercury.a = 2.4397e6 #Mean radius of planet
Mercury.g = 3.70 #Surface gravitational acceleration
Mercury.albedo = .119 #Bond albedo
Mercury.L = 9126.6 #Annual mean solar constant (current)
#
Mercury.rsm = 57.91e9 #Semi-major axis
Mercury.year = 87.969*24.*3600. #Sidereal length of year
Mercury.eccentricity = .2056 # Eccentricity
Mercury.day = 4222.6*3600. #Mean tropical length of day
Mercury.obliquity = .01 #Obliquity to orbit (deg)
Mercury.Lequinox = None #Longitude of equinox (deg)
#
Mercury.Tsbar = 440. #Mean surface temperature
Mercury.Tsmax = 725. #Maximum surface temperature
#----------------------------------------------------
Venus = Planet()
Venus.name = 'Venus' #Name of the planet
Venus.a = 6.0518e6 #Mean radius of planet
Venus.g = 8.87 #Surface gravitational acceleration
Venus.albedo = .750 #Bond albedo
Venus.L = 2613.9 #Annual mean solar constant (current)
#
Venus.rsm = 108.21e9 #Semi-major axis
Venus.year = 224.701*24.*3600. #Sidereal length of year
Venus.eccentricity = .0067 # Eccentricity
Venus.day = 2802.*3600. #Mean tropical length of day
Venus.obliquity = 177.36 #Obliquity to orbit (deg)
Venus.Lequinox = None #Longitude of equinox (deg)
#
Venus.Tsbar = 737. #Mean surface temperature
Venus.Tsmax = 737. #Maximum surface temperature
#----------------------------------------------------
Earth = Planet()
Earth.name = 'Earth' #Name of the planet
Earth.a = 6.371e6 #Mean radius of planet
Earth.g = 9.798 #Surface gravitational acceleration
Earth.albedo = .306 #Bond albedo
Earth.L = 1367.6 #Annual mean solar constant (current)
#
Earth.rsm = 149.60e9 #Semi-major axis
Earth.year = 365.256*24.*3600. #Sidereal length of year
Earth.eccentricity = .0167 # Eccentricity
Earth.day = 24.000*3600. #Mean tropical length of day
Earth.obliquity = 23.45 #Obliquity to orbit (deg)
Earth.Lequinox = None #Longitude of equinox (deg)
#
Earth.Tsbar = 288. #Mean surface temperature
Earth.Tsmax = None #Maximum surface temperature
#----------------------------------------------------
Mars = Planet()
Mars.name = 'Mars' #Name of the planet
Mars.a = 3.390e6 #Mean radius of planet
Mars.g = 3.71 #Surface gravitational acceleration
Mars.albedo = .250 #Bond albedo
Mars.L = 589.2 #Annual mean solar constant (current)
#
Mars.rsm = 227.92e9 #Semi-major axis
Mars.year = 686.98*24.*3600. #Sidereal length of year
Mars.eccentricity = .0935 # Eccentricity
Mars.day = 24.6597*3600. #Mean tropical length of day
Mars.obliquity = 25.19 #Obliquity to orbit (deg)
Mars.Lequinox = None #Longitude of equinox (deg)
#
Mars.Tsbar = 210. #Mean surface temperature
Mars.Tsmax = 295. #Maximum surface temperature
#----------------------------------------------------
Jupiter = Planet()
Jupiter.name = 'Jupiter' #Name of the planet
Jupiter.a = 69.911e6 #Mean radius of planet
Jupiter.g = 24.79 #Surface gravitational acceleration
Jupiter.albedo = .343 #Bond albedo
Jupiter.L = 50.5 #Annual mean solar constant (current)
#
Jupiter.rsm = 778.57e9 #Semi-major axis
Jupiter.year = 4332.*24.*3600. #Sidereal length of year
Jupiter.eccentricity = .0489 # Eccentricity
Jupiter.day = 9.9259*3600. #Mean tropical length of day
Jupiter.obliquity = 3.13 #Obliquity to orbit (deg)
Jupiter.Lequinox = None #Longitude of equinox (deg)
#
Jupiter.Tsbar = 165. #Mean surface temperature
Jupiter.Tsmax = None #Maximum surface temperature
#----------------------------------------------------
Saturn = Planet()
Saturn.name = 'Saturn' #Name of the planet
Saturn.a = 58.232e6 #Mean radius of planet
Saturn.g = 10.44 #Surface gravitational acceleration
Saturn.albedo = .342 #Bond albedo
Saturn.L = 14.90 #Annual mean solar constant (current)
#
Saturn.rsm = 1433.e9 #Semi-major axis
Saturn.year = 10759.*24.*3600. #Sidereal length of year
Saturn.eccentricity = .0565 # Eccentricity
Saturn.day = 10.656*3600. #Mean tropical length of day
Saturn.obliquity = 26.73 #Obliquity to orbit (deg)
Saturn.Lequinox = None #Longitude of equinox (deg)
#
Saturn.Tsbar = 134. #Mean surface temperature
Saturn.Tsmax = None #Maximum surface temperature
#----------------------------------------------------
Uranus = Planet()
Uranus.name = 'Uranus' #Name of the planet
Uranus.a = 25.362e6 #Mean radius of planet
Uranus.g = 8.87 #Surface gravitational acceleration
Uranus.albedo = .300 #Bond albedo
Uranus.L = 3.71 #Annual mean solar constant (current)
#
Uranus.rsm = 2872.46e9 #Semi-major axis
Uranus.year = 30685.4*24.*3600. #Sidereal length of year
Uranus.eccentricity = .0457 # Eccentricity
Uranus.day = 17.24*3600. #Mean tropical length of day
Uranus.obliquity = 97.77 #Obliquity to orbit (deg)
Uranus.Lequinox = None #Longitude of equinox (deg)
#
Uranus.Tsbar = 76. #Mean surface temperature
Uranus.Tsmax = None #Maximum surface temperature
#----------------------------------------------------
Neptune = Planet()
Neptune.name = 'Neptune' #Name of the planet
Neptune.a = 26.624e6 #Mean radius of planet
Neptune.g = 11.15 #Surface gravitational acceleration
Neptune.albedo = .290 #Bond albedo
Neptune.L = 1.51 #Annual mean solar constant (current)
#
Neptune.rsm = 4495.06e9 #Semi-major axis
Neptune.year = 60189.0*24.*3600. #Sidereal length of year
Neptune.eccentricity = .0113 # Eccentricity
Neptune.day = 16.11*3600. #Mean tropical length of day
Neptune.obliquity = 28.32 #Obliquity to orbit (deg)
Neptune.Lequinox = None #Longitude of equinox (deg)
#
Neptune.Tsbar = 72. #Mean surface temperature
Neptune.Tsmax = None #Maximum surface temperature
#----------------------------------------------------
Pluto = Planet()
Pluto.name = 'Pluto' #Name of the planet
Pluto.a = 1.195e6 #Mean radius of planet
Pluto.g = .58 #Surface gravitational acceleration
Pluto.albedo = .5 #Bond albedo
Pluto.L = .89 #Annual mean solar constant (current)
#
Pluto.rsm = 5906.e9 #Semi-major axis
Pluto.year = 90465.*24.*3600. #Sidereal length of year
Pluto.eccentricity = .2488 # Eccentricity
Pluto.day = 153.2820*3600. #Mean tropical length of day
Pluto.obliquity = 122.53 #Obliquity to orbit (deg)
Pluto.Lequinox = None #Longitude of equinox (deg)
#
Pluto.Tsbar = 50. #Mean surface temperature
Pluto.Tsmax = None #Maximum surface temperature
#Selected moons
#----------------------------------------------------
Moon = Planet()
Moon.name = 'Moon' #Name of the planet
Moon.a = 1.737e6 #Mean radius of planet
Moon.g = 1.62 #Surface gravitational acceleration
Moon.albedo = .11 #Bond albedo
Moon.L = 1367.6 #Annual mean solar constant (current)
#
Moon.rsm = Earth.rsm #Semi-major axis
Moon.year = Earth.year #Sidereal length of year
Moon.eccentricity = None # Eccentricity
Moon.day = 28.*24.*3600. #Mean tropical length of day (approx)
Moon.obliquity = None #Obliquity to orbit (deg)
Moon.Lequinox = None #Longitude of equinox (deg)
#
Moon.Tsbar = None #Mean surface temperature
Moon.Tsmax = 400. #Maximum surface temperature
Moon.Tsmin = 100. #Minimum surface temperature
Titan = Planet()
Titan.name = 'Titan' #Name of the planet
Titan.a = 2.575e6 #Mean radius of planet
Titan.g = 1.35 #Surface gravitational acceleration
Titan.L = Saturn.L #Annual mean solar constant (current)
Titan.albedo = .21 #Bond albedo (Not yet updated from Cassini)
#
Titan.rsm = None #Semi-major axis
Titan.year = Saturn.year #Sidereal length of year
Titan.eccentricity = Saturn.eccentricity # Eccentricity ABOUT SUN
Titan.day = 15.9452*24.*3600. #Mean tropical length of day
Titan.obliquity = Saturn.obliquity #Obliquity to plane of Ecliptic
#(Titan's rotation axis approx parallel
# to Saturn's
Titan.Lequinox = Saturn.Lequinox #Longitude of equinox
#
Titan.Tsbar = 95. #Mean surface temperature
Titan.Tsmax = None #Maximum surface temperature
Europa = Planet()
Europa.name = 'Europa' #Name of the planet
Europa.a = 1.560e6 #Mean radius of planet
Europa.g = 1.31 #Surface gravitational acceleration
Europa.L = Jupiter.L #Annual mean solar constant (current)
Europa.albedo = .67 #Bond albedo
#
Europa.rsm = Jupiter.rsm #Semi-major axis
Europa.year = Jupiter.year #Sidereal length of year
Europa.eccentricity = Jupiter.eccentricity # Eccentricity
Europa.day = 3.551*24.*3600. #Mean tropical length of day
Europa.obliquity = Jupiter.obliquity #Obliquity to plane of ecliptic
Europa.Lequinox = None #Longitude of equinox
#
Europa.Tsbar = 103. #Mean surface temperature
Europa.Tsmax = 125. #Maximum surface temperature
Triton = Planet()
Triton.name = 'Triton' #Name of the planet
Triton.a = 2.7068e6/2. #Mean radius of planet
Triton.g = .78 #Surface gravitational acceleration
Triton.L = Neptune.L #Annual mean solar constant (current)
Triton.albedo = .76 #Bond albedo
#
Triton.rsm = Neptune.rsm #Semi-major axis
Triton.year = Neptune.year #Sidereal length of year
Triton.eccentricity = Neptune.eccentricity # Eccentricity about Sun
Triton.day = 5.877*24.*3600. #Mean tropical length of day
#Triton's rotation is retrograde
Triton.obliquity = 156. #Obliquity to ecliptic **ToDo: Check this.
#Note: Seasons are influenced by the inclination
#of Triton's orbit? (About 20 degrees to
#Neptune's equator
Triton.Lequinox = None #Longitude of equinox
#
Triton.Tsbar = 34.5 #Mean surface temperature
#This is probably a computed blackbody
#temperature, rather than an observation
Triton.Tsmax = None #Maximum surface temperature
| class Planet:
"""
A Planet object contains basic planetary data.
If P is a Planet object, the data are:
P.name = Name of the planet
P.a = Mean radius of planet (m)
P.g = Surface gravitational acceleration (m/s**2)
P.L = Annual mean solar constant (current) (W/m**2)
P.albedo Bond albedo (fraction)
P.rsm = Semi-major axis of orbit about Sun (m)
P.year = Sidereal length of year (s)
P.eccentricity = Eccentricity (unitless)
P.day = Mean tropical length of day (s)
P.obliquity = Obliquity to orbit (degrees)
P.Lequinox = Longitude of equinox (degrees)
P.Tsbar = Mean surface temperature (K)
P.Tsmax = Maximum surface temperature (K)
For gas giants, "surface" quantities are given at the 1 bar level
"""
def __repr__(self):
line1 = 'This planet object contains information on %s\n' % self.name
line2 = 'Type "help(Planet)" for more information\n'
return line1 + line2
def __init__(self):
self.name = None
self.a = None
self.g = None
self.L = None
self.albedo = None
self.rsm = None
self.year = None
self.eccentricity = None
self.day = None
self.obliquity = None
self.Lequinox = None
self.Tsbar = None
self.Tsmax = None
mercury = planet()
Mercury.name = 'Mercury'
Mercury.a = 2439700.0
Mercury.g = 3.7
Mercury.albedo = 0.119
Mercury.L = 9126.6
Mercury.rsm = 57910000000.0
Mercury.year = 87.969 * 24.0 * 3600.0
Mercury.eccentricity = 0.2056
Mercury.day = 4222.6 * 3600.0
Mercury.obliquity = 0.01
Mercury.Lequinox = None
Mercury.Tsbar = 440.0
Mercury.Tsmax = 725.0
venus = planet()
Venus.name = 'Venus'
Venus.a = 6051800.0
Venus.g = 8.87
Venus.albedo = 0.75
Venus.L = 2613.9
Venus.rsm = 108210000000.0
Venus.year = 224.701 * 24.0 * 3600.0
Venus.eccentricity = 0.0067
Venus.day = 2802.0 * 3600.0
Venus.obliquity = 177.36
Venus.Lequinox = None
Venus.Tsbar = 737.0
Venus.Tsmax = 737.0
earth = planet()
Earth.name = 'Earth'
Earth.a = 6371000.0
Earth.g = 9.798
Earth.albedo = 0.306
Earth.L = 1367.6
Earth.rsm = 149600000000.0
Earth.year = 365.256 * 24.0 * 3600.0
Earth.eccentricity = 0.0167
Earth.day = 24.0 * 3600.0
Earth.obliquity = 23.45
Earth.Lequinox = None
Earth.Tsbar = 288.0
Earth.Tsmax = None
mars = planet()
Mars.name = 'Mars'
Mars.a = 3390000.0
Mars.g = 3.71
Mars.albedo = 0.25
Mars.L = 589.2
Mars.rsm = 227920000000.0
Mars.year = 686.98 * 24.0 * 3600.0
Mars.eccentricity = 0.0935
Mars.day = 24.6597 * 3600.0
Mars.obliquity = 25.19
Mars.Lequinox = None
Mars.Tsbar = 210.0
Mars.Tsmax = 295.0
jupiter = planet()
Jupiter.name = 'Jupiter'
Jupiter.a = 69911000.0
Jupiter.g = 24.79
Jupiter.albedo = 0.343
Jupiter.L = 50.5
Jupiter.rsm = 778570000000.0
Jupiter.year = 4332.0 * 24.0 * 3600.0
Jupiter.eccentricity = 0.0489
Jupiter.day = 9.9259 * 3600.0
Jupiter.obliquity = 3.13
Jupiter.Lequinox = None
Jupiter.Tsbar = 165.0
Jupiter.Tsmax = None
saturn = planet()
Saturn.name = 'Saturn'
Saturn.a = 58232000.0
Saturn.g = 10.44
Saturn.albedo = 0.342
Saturn.L = 14.9
Saturn.rsm = 1433000000000.0
Saturn.year = 10759.0 * 24.0 * 3600.0
Saturn.eccentricity = 0.0565
Saturn.day = 10.656 * 3600.0
Saturn.obliquity = 26.73
Saturn.Lequinox = None
Saturn.Tsbar = 134.0
Saturn.Tsmax = None
uranus = planet()
Uranus.name = 'Uranus'
Uranus.a = 25362000.0
Uranus.g = 8.87
Uranus.albedo = 0.3
Uranus.L = 3.71
Uranus.rsm = 2872460000000.0
Uranus.year = 30685.4 * 24.0 * 3600.0
Uranus.eccentricity = 0.0457
Uranus.day = 17.24 * 3600.0
Uranus.obliquity = 97.77
Uranus.Lequinox = None
Uranus.Tsbar = 76.0
Uranus.Tsmax = None
neptune = planet()
Neptune.name = 'Neptune'
Neptune.a = 26624000.0
Neptune.g = 11.15
Neptune.albedo = 0.29
Neptune.L = 1.51
Neptune.rsm = 4495060000000.0
Neptune.year = 60189.0 * 24.0 * 3600.0
Neptune.eccentricity = 0.0113
Neptune.day = 16.11 * 3600.0
Neptune.obliquity = 28.32
Neptune.Lequinox = None
Neptune.Tsbar = 72.0
Neptune.Tsmax = None
pluto = planet()
Pluto.name = 'Pluto'
Pluto.a = 1195000.0
Pluto.g = 0.58
Pluto.albedo = 0.5
Pluto.L = 0.89
Pluto.rsm = 5906000000000.0
Pluto.year = 90465.0 * 24.0 * 3600.0
Pluto.eccentricity = 0.2488
Pluto.day = 153.282 * 3600.0
Pluto.obliquity = 122.53
Pluto.Lequinox = None
Pluto.Tsbar = 50.0
Pluto.Tsmax = None
moon = planet()
Moon.name = 'Moon'
Moon.a = 1737000.0
Moon.g = 1.62
Moon.albedo = 0.11
Moon.L = 1367.6
Moon.rsm = Earth.rsm
Moon.year = Earth.year
Moon.eccentricity = None
Moon.day = 28.0 * 24.0 * 3600.0
Moon.obliquity = None
Moon.Lequinox = None
Moon.Tsbar = None
Moon.Tsmax = 400.0
Moon.Tsmin = 100.0
titan = planet()
Titan.name = 'Titan'
Titan.a = 2575000.0
Titan.g = 1.35
Titan.L = Saturn.L
Titan.albedo = 0.21
Titan.rsm = None
Titan.year = Saturn.year
Titan.eccentricity = Saturn.eccentricity
Titan.day = 15.9452 * 24.0 * 3600.0
Titan.obliquity = Saturn.obliquity
Titan.Lequinox = Saturn.Lequinox
Titan.Tsbar = 95.0
Titan.Tsmax = None
europa = planet()
Europa.name = 'Europa'
Europa.a = 1560000.0
Europa.g = 1.31
Europa.L = Jupiter.L
Europa.albedo = 0.67
Europa.rsm = Jupiter.rsm
Europa.year = Jupiter.year
Europa.eccentricity = Jupiter.eccentricity
Europa.day = 3.551 * 24.0 * 3600.0
Europa.obliquity = Jupiter.obliquity
Europa.Lequinox = None
Europa.Tsbar = 103.0
Europa.Tsmax = 125.0
triton = planet()
Triton.name = 'Triton'
Triton.a = 2706800.0 / 2.0
Triton.g = 0.78
Triton.L = Neptune.L
Triton.albedo = 0.76
Triton.rsm = Neptune.rsm
Triton.year = Neptune.year
Triton.eccentricity = Neptune.eccentricity
Triton.day = 5.877 * 24.0 * 3600.0
Triton.obliquity = 156.0
Triton.Lequinox = None
Triton.Tsbar = 34.5
Triton.Tsmax = None |
palavras = {}
arquivo = open('words.txt', 'r')
for p in arquivo.readlines():
palavra = p.split(' ')
for l in palavra:
try:
palavras[l] += 1
except:
palavras[l] = 1
arquivo.close()
print(palavras)
| palavras = {}
arquivo = open('words.txt', 'r')
for p in arquivo.readlines():
palavra = p.split(' ')
for l in palavra:
try:
palavras[l] += 1
except:
palavras[l] = 1
arquivo.close()
print(palavras) |
def getKey(dictionary, svalue):
for key, value in dictionary.items():
if value == svalue:
return key
# def hasKey(dictionary, key):
# if key in dictionary:
# return True
# return False
| def get_key(dictionary, svalue):
for (key, value) in dictionary.items():
if value == svalue:
return key |
# https://www.codewars.com/kata/529872bdd0f550a06b00026e/
'''
Instructions :
Complete the greatestProduct method so that it'll find the greatest product of five consecutive digits in the given string of digits.
For example:
greatestProduct("123834539327238239583") // should return 3240
The input string always has more than five digits.
Adapted from Project Euler.
'''
def product(n):
p = 1
for i in n:
p *= int(i)
return p
def greatest_product(n):
res = []
mul = 1
digit = 5
while len(n)>= digit:
res.append(product(n[:digit]))
n = n[1:]
print(res)
print(n)
return(max(res))
| """
Instructions :
Complete the greatestProduct method so that it'll find the greatest product of five consecutive digits in the given string of digits.
For example:
greatestProduct("123834539327238239583") // should return 3240
The input string always has more than five digits.
Adapted from Project Euler.
"""
def product(n):
p = 1
for i in n:
p *= int(i)
return p
def greatest_product(n):
res = []
mul = 1
digit = 5
while len(n) >= digit:
res.append(product(n[:digit]))
n = n[1:]
print(res)
print(n)
return max(res) |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
def drop_view_if_exists(cr, viewname):
cr.execute("DROP view IF EXISTS %s CASCADE" % (viewname,))
cr.commit()
def escape_psql(to_escape):
return to_escape.replace('\\', r'\\').replace('%', '\%').replace('_', '\_')
def pg_varchar(size=0):
""" Returns the VARCHAR declaration for the provided size:
* If no size (or an empty or negative size is provided) return an
'infinite' VARCHAR
* Otherwise return a VARCHAR(n)
:type int size: varchar size, optional
:rtype: str
"""
if size:
if not isinstance(size, int):
raise ValueError("VARCHAR parameter should be an int, got %s" % type(size))
if size > 0:
return 'VARCHAR(%d)' % size
return 'VARCHAR'
def reverse_order(order):
""" Reverse an ORDER BY clause """
items = []
for item in order.split(','):
item = item.lower().split()
direction = 'asc' if item[1:] == ['desc'] else 'desc'
items.append('%s %s' % (item[0], direction))
return ', '.join(items)
| def drop_view_if_exists(cr, viewname):
cr.execute('DROP view IF EXISTS %s CASCADE' % (viewname,))
cr.commit()
def escape_psql(to_escape):
return to_escape.replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_')
def pg_varchar(size=0):
""" Returns the VARCHAR declaration for the provided size:
* If no size (or an empty or negative size is provided) return an
'infinite' VARCHAR
* Otherwise return a VARCHAR(n)
:type int size: varchar size, optional
:rtype: str
"""
if size:
if not isinstance(size, int):
raise value_error('VARCHAR parameter should be an int, got %s' % type(size))
if size > 0:
return 'VARCHAR(%d)' % size
return 'VARCHAR'
def reverse_order(order):
""" Reverse an ORDER BY clause """
items = []
for item in order.split(','):
item = item.lower().split()
direction = 'asc' if item[1:] == ['desc'] else 'desc'
items.append('%s %s' % (item[0], direction))
return ', '.join(items) |
"""
You are given three inputs, all of which are instances of a class that have an
"ancestor" property pointing to their youngest ancestor. The first input is the
top ancestor in an ancestral tree(i.e. the only instance that has no ancestor),
and the other two inputs are descendants in the ancestral tree. Write a
functions that returns the youngest common ancestor to the two descendants.
for input Node A, Node E, Node I from this ancestral
A
/ \
B C
/ \ / \
D EF G
/ \
H I
Returns node B
"""
def get_youngest_common_ancestor(top_ancestor, descendant_one, descendant_two):
pass
| """
You are given three inputs, all of which are instances of a class that have an
"ancestor" property pointing to their youngest ancestor. The first input is the
top ancestor in an ancestral tree(i.e. the only instance that has no ancestor),
and the other two inputs are descendants in the ancestral tree. Write a
functions that returns the youngest common ancestor to the two descendants.
for input Node A, Node E, Node I from this ancestral
A
/ B C
/ \\ / D EF G
/ H I
Returns node B
"""
def get_youngest_common_ancestor(top_ancestor, descendant_one, descendant_two):
pass |
@auth.route('/login', methods=['GET', 'POST']) # define login page path
def login(): # define login page fucntion
if request.method=='GET': # if the request is a GET we return the login page
return render_template('login.html')
else: # if the request is POST the we check if the user exist
# and with te right password
email = request.form.get('email')
password = request.form.get('password')
remember = True if request.form.get('remember') else False
user = User.query.filter_by(email=email).first()
# check if the user actually exists
# take the user-supplied password, hash it, and compare it
# to the hashed password in the database
if not user:
flash('Please sign up before!')
return redirect(url_for('auth.signup'))
elif not check_password_hash(user.password, password):
flash('Please check your login details and try again.')
return redirect(url_for('auth.login')) # if the user
#doesn't exist or password is wrong, reload the page
# if the above check passes, then we know the user has the
# right credentials
login_user(user, remember=remember)
return redirect(url_for('main.profile')) | @auth.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'GET':
return render_template('login.html')
else:
email = request.form.get('email')
password = request.form.get('password')
remember = True if request.form.get('remember') else False
user = User.query.filter_by(email=email).first()
if not user:
flash('Please sign up before!')
return redirect(url_for('auth.signup'))
elif not check_password_hash(user.password, password):
flash('Please check your login details and try again.')
return redirect(url_for('auth.login'))
login_user(user, remember=remember)
return redirect(url_for('main.profile')) |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"get_norm_stats": "00_utils.ipynb",
"draw_rect": "00_utils.ipynb",
"convert_cords": "00_utils.ipynb",
"resize": "00_utils.ipynb",
"noise": "00_utils.ipynb",
"get_prompt_points": "00_utils.ipynb",
"yolo_to_coco": "00_utils.ipynb",
"PTBDataset": "01_data.ipynb",
"PTBTransform": "01_data.ipynb",
"PTBImage": "01_data.ipynb",
"ConversionDataset": "01_data.ipynb",
"EfficientLoc": "02_model.ipynb",
"CIoU": "02_model.ipynb"}
modules = ["utils.py",
"data.py",
"model.py",
"fastai.py",
"None.py"]
doc_url = "https://BavarianToolbox.github.io/point_to_box/"
git_url = "https://github.com/BavarianToolbox/point_to_box/tree/master/"
def custom_doc_links(name): return None
| __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'get_norm_stats': '00_utils.ipynb', 'draw_rect': '00_utils.ipynb', 'convert_cords': '00_utils.ipynb', 'resize': '00_utils.ipynb', 'noise': '00_utils.ipynb', 'get_prompt_points': '00_utils.ipynb', 'yolo_to_coco': '00_utils.ipynb', 'PTBDataset': '01_data.ipynb', 'PTBTransform': '01_data.ipynb', 'PTBImage': '01_data.ipynb', 'ConversionDataset': '01_data.ipynb', 'EfficientLoc': '02_model.ipynb', 'CIoU': '02_model.ipynb'}
modules = ['utils.py', 'data.py', 'model.py', 'fastai.py', 'None.py']
doc_url = 'https://BavarianToolbox.github.io/point_to_box/'
git_url = 'https://github.com/BavarianToolbox/point_to_box/tree/master/'
def custom_doc_links(name):
return None |
class OutcomeInfo:
'''Details for individual outcomes of a Market.'''
def __init__(self, id, volume, price, description):
self._id = id
self._volume = volume
self._price = price
self._description = description
@property
def id(self):
'''Market Outcome ID
Returns int
'''
return self._id
@property
def volume(self):
'''Trading volume for this Outcome.
Returns decimal.Decimal
'''
return self._volume
@property
def price(self):
'''Last price at which the outcome was traded. If no trades have taken place
in the Market, this value is set to the Market midpoint. If there is no
volume on this Outcome, but there is volume on another Outcome in the
Market, price is set to 0 for Yes/No Markets and Categorical Markets.
Returns decimal.Decimal
'''
return self._price
@property
def description(self):
'''Description for the Outcome.
Returns str
'''
return self._description
| class Outcomeinfo:
"""Details for individual outcomes of a Market."""
def __init__(self, id, volume, price, description):
self._id = id
self._volume = volume
self._price = price
self._description = description
@property
def id(self):
"""Market Outcome ID
Returns int
"""
return self._id
@property
def volume(self):
"""Trading volume for this Outcome.
Returns decimal.Decimal
"""
return self._volume
@property
def price(self):
"""Last price at which the outcome was traded. If no trades have taken place
in the Market, this value is set to the Market midpoint. If there is no
volume on this Outcome, but there is volume on another Outcome in the
Market, price is set to 0 for Yes/No Markets and Categorical Markets.
Returns decimal.Decimal
"""
return self._price
@property
def description(self):
"""Description for the Outcome.
Returns str
"""
return self._description |
'''
@author: Jakob Prange (jakpra)
@copyright: Copyright 2020, Jakob Prange
@license: Apache 2.0
'''
LETTERS = '_YZWVUTS'
def index_category(category, nargs, result_index=0, arg_index=1, self_index=0):
attr_str = ''.join((f'[{a}]' for a in category.attr - {'conj'})) + ('[conj]' if 'conj' in category.attr else '')
if category.result is None:
result_str = ''
else:
if category.result.equals(category.arg, ignore_attr=True):
if len(category.arg.attr) == 0 or (category.arg.attr == category.result.attr):
result_index = arg_index
result_str, result_index, arg_index, self_index = index_category(category.result, nargs-1, result_index, arg_index, result_index)
# if category.result.has_children():
# result_str = f'({result_str})'
if category.arg is None:
arg_str = ''
else:
arg_str, result_index, arg_index, self_index = index_category(category.arg, -1, arg_index, arg_index+1, arg_index)
# if category.arg.has_children():
# arg_str = f'({arg_str})'
if not category.has_children():
cat_str = f'{category.root}{attr_str}{{{LETTERS[self_index]}}}'
elif nargs < 0:
cat_str = f'({result_str}{category.root}{arg_str}){attr_str}{{{LETTERS[self_index]}}}'
else:
cat_str = f'({result_str}{category.root}{arg_str}<{nargs}>){attr_str}{{{LETTERS[self_index]}}}'
return cat_str, result_index, arg_index, self_index
def make_rule(category):
result = str(category)
nargs = category.nargs()
indexed, _, _, _ = index_category(category, nargs)
result += f'\n {nargs} {indexed}'
cat = category
for n in range(nargs):
result += f'\n {n+1} ignore'
cat = cat.result
return result
| """
@author: Jakob Prange (jakpra)
@copyright: Copyright 2020, Jakob Prange
@license: Apache 2.0
"""
letters = '_YZWVUTS'
def index_category(category, nargs, result_index=0, arg_index=1, self_index=0):
attr_str = ''.join((f'[{a}]' for a in category.attr - {'conj'})) + ('[conj]' if 'conj' in category.attr else '')
if category.result is None:
result_str = ''
else:
if category.result.equals(category.arg, ignore_attr=True):
if len(category.arg.attr) == 0 or category.arg.attr == category.result.attr:
result_index = arg_index
(result_str, result_index, arg_index, self_index) = index_category(category.result, nargs - 1, result_index, arg_index, result_index)
if category.arg is None:
arg_str = ''
else:
(arg_str, result_index, arg_index, self_index) = index_category(category.arg, -1, arg_index, arg_index + 1, arg_index)
if not category.has_children():
cat_str = f'{category.root}{attr_str}{{{LETTERS[self_index]}}}'
elif nargs < 0:
cat_str = f'({result_str}{category.root}{arg_str}){attr_str}{{{LETTERS[self_index]}}}'
else:
cat_str = f'({result_str}{category.root}{arg_str}<{nargs}>){attr_str}{{{LETTERS[self_index]}}}'
return (cat_str, result_index, arg_index, self_index)
def make_rule(category):
result = str(category)
nargs = category.nargs()
(indexed, _, _, _) = index_category(category, nargs)
result += f'\n {nargs} {indexed}'
cat = category
for n in range(nargs):
result += f'\n {n + 1} ignore'
cat = cat.result
return result |
# One Gold Star
# Question 1-star: Stirling and Bell Numbers
# The number of ways of splitting n items in k non-empty sets is called
# the Stirling number, S(n,k), of the second kind. For example, the group
# of people Dave, Sarah, Peter and Andy could be split into two groups in
# the following ways.
# 1. Dave, Sarah, Peter Andy
# 2. Dave, Sarah, Andy Peter
# 3. Dave, Andy, Peter Sarah
# 4. Sarah, Andy, Peter Dave
# 5. Dave, Sarah Andy, Peter
# 6. Dave, Andy Sarah, Peter
# 7. Dave, Peter Andy, Sarah
# so S(4,2) = 7
# If instead we split the group into one group, we have just one way to
# do it.
# 1. Dave, Sarah, Peter, Andy
# so S(4,1) = 1
# or into four groups, there is just one way to do it as well
# 1. Dave Sarah Peter Andy
# so S(4,4) = 1
# If we try to split into more groups than we have people, there are no
# ways to do it.
# The formula for calculating the Stirling numbers is
# S(n, k) = k*S(n-1, k) + S(n-1, k-1)
# Furthermore, the Bell number B(n) is the number of ways of splitting n
# into any number of parts, that is,
# B(n) is the sum of S(n,k) for k =1,2, ... , n.
# Write two procedures, stirling and bell. The first procedure, stirling
# takes as its inputs two positive integers of which the first is the
# number of items and the second is the number of sets into which those
# items will be split. The second procedure, bell, takes as input a
# positive integer n and returns the Bell number B(n).
def stirling(n_items, k_sets):
"""
Takes as its inputs two positive integers of which the first is the
number of items and the second is the number of sets into which those
items will be split. Returns total number of k_sets created from
n_items.
"""
if n_items < k_sets:
return 0
if k_sets == 1 or k_sets == n_items:
return 1
return k_sets * stirling(n_items-1, k_sets) + stirling(n_items-1, k_sets-1)
def bell(n_items):
"""
Returns the total number of k_sets of stirling numbers
for k_sets = 1, 2, ... , n.
"""
return sum([stirling(n_items, k) for k in range(1, n_items+1)])
print(stirling(1, 1))
# 1
print(stirling(2, 1))
# 1
print(stirling(2, 2))
# 1
print(stirling(2, 3))
# 0
print(stirling(3, 1))
# 1
print(stirling(3, 2))
# 3
print(stirling(3, 3))
# 1
print(stirling(4, 1))
# 1
print(stirling(4, 2))
# 7
print(stirling(4, 3))
# 6
print(stirling(4, 4))
# 1
print(stirling(5, 1))
# 1
print(stirling(5, 2))
# 15
print(stirling(5, 3))
# 25
print(stirling(5, 4))
# 10
print(stirling(5, 5))
# 1
print(stirling(20, 15))
# 452329200
print("***********")
print(bell(1))
# 1
print(bell(2))
# 2
print(bell(3))
# 5
print(bell(4))
# 15
print(bell(5))
# 52
print(bell(15))
# 1382958545
| def stirling(n_items, k_sets):
"""
Takes as its inputs two positive integers of which the first is the
number of items and the second is the number of sets into which those
items will be split. Returns total number of k_sets created from
n_items.
"""
if n_items < k_sets:
return 0
if k_sets == 1 or k_sets == n_items:
return 1
return k_sets * stirling(n_items - 1, k_sets) + stirling(n_items - 1, k_sets - 1)
def bell(n_items):
"""
Returns the total number of k_sets of stirling numbers
for k_sets = 1, 2, ... , n.
"""
return sum([stirling(n_items, k) for k in range(1, n_items + 1)])
print(stirling(1, 1))
print(stirling(2, 1))
print(stirling(2, 2))
print(stirling(2, 3))
print(stirling(3, 1))
print(stirling(3, 2))
print(stirling(3, 3))
print(stirling(4, 1))
print(stirling(4, 2))
print(stirling(4, 3))
print(stirling(4, 4))
print(stirling(5, 1))
print(stirling(5, 2))
print(stirling(5, 3))
print(stirling(5, 4))
print(stirling(5, 5))
print(stirling(20, 15))
print('***********')
print(bell(1))
print(bell(2))
print(bell(3))
print(bell(4))
print(bell(5))
print(bell(15)) |
def cpu_bound(n):
return sum(i * i for i in range(n))
if __name__ == "__main__":
n = int(input())
res = cpu_bound(n)
print(res) | def cpu_bound(n):
return sum((i * i for i in range(n)))
if __name__ == '__main__':
n = int(input())
res = cpu_bound(n)
print(res) |
# Implement a queue using two stacks. Recall that a queue is a FIFO
# (first-in, first-out) data structure with the following methods: enqueue,
# which inserts an element into the queue, and dequeue, which removes it.
class Queue:
def __init__(self):
self.ins = []
self.out = []
def enqueue(self, value):
self.ins.append(value)
def dequeue(self):
if not self.out:
while self.ins:
self.out.append(self.ins.pop())
return self.out.pop()
if __name__ == '__main__':
q = Queue()
for i in range(5):
q.enqueue(i)
for _ in range(3):
print(q.dequeue())
for i in range(5, 10):
q.enqueue(i)
for _ in range(7):
print(q.dequeue())
| class Queue:
def __init__(self):
self.ins = []
self.out = []
def enqueue(self, value):
self.ins.append(value)
def dequeue(self):
if not self.out:
while self.ins:
self.out.append(self.ins.pop())
return self.out.pop()
if __name__ == '__main__':
q = queue()
for i in range(5):
q.enqueue(i)
for _ in range(3):
print(q.dequeue())
for i in range(5, 10):
q.enqueue(i)
for _ in range(7):
print(q.dequeue()) |
MOCK_DATA = [
{
"symbol": "sy1",
"companyName": "cn1",
"exchange": "ex1",
"industry": "in1",
"website": "ws1",
"description": "dc1",
"CEO": "ceo1",
"issueType": "is1",
"sector": "sc1",
},
{
"symbol": "sy2",
"companyName": "cn2",
"exchange": "ex2",
"industry": "in2",
"website": "ws2",
"description": "dc2",
"CEO": "ceo2",
"issueType": "is2",
"sector": "sc2",
},
{
"symbol": "sy3",
"companyName": "cn3",
"exchange": "ex3",
"industry": "in3",
"website": "ws3",
"description": "dc3",
"CEO": "ceo3",
"issueType": "is3",
"sector": "sc3",
},
{
"symbol": "sy4",
"companyName": "cn4",
"exchange": "ex4",
"industry": "in4",
"website": "ws4",
"description": "dc4",
"CEO": "ceo4",
"issueType": "is4",
"sector": "sc4",
},
{
"symbol": "sy5",
"companyName": "cn5",
"exchange": "ex5",
"industry": "in5",
"website": "ws5",
"description": "dc5",
"CEO": "ceo5",
"issueType": "is5",
"sector": "sc5",
},
{
"symbol": "sy6",
"companyName": "cn6",
"exchange": "ex6",
"industry": "in6",
"website": "ws6",
"description": "dc6",
"CEO": "ceo6",
"issueType": "is6",
"sector": "sc6",
},
{
"symbol": "sy7",
"companyName": "cn7",
"exchange": "ex7",
"industry": "in7",
"website": "ws7",
"description": "dc7",
"CEO": "ceo7",
"issueType": "is7",
"sector": "sc7",
},
{
"symbol": "sy8",
"companyName": "cn8",
"exchange": "ex8",
"industry": "in8",
"website": "ws8",
"description": "dc8",
"CEO": "ceo8",
"issueType": "is8",
"sector": "sc8",
},
{
"symbol": "sy9",
"companyName": "cn9",
"exchange": "ex9",
"industry": "in9",
"website": "ws9",
"description": "dc9",
"CEO": "ceo9",
"issueType": "is9",
"sector": "sc9",
},
{
"symbol": "sy",
"companyName": "cn",
"exchange": "ex",
"industry": "in",
"website": "ws",
"description": "dc",
"CEO": "ceo",
"issueType": "is",
"sector": "sc",
}
]
| mock_data = [{'symbol': 'sy1', 'companyName': 'cn1', 'exchange': 'ex1', 'industry': 'in1', 'website': 'ws1', 'description': 'dc1', 'CEO': 'ceo1', 'issueType': 'is1', 'sector': 'sc1'}, {'symbol': 'sy2', 'companyName': 'cn2', 'exchange': 'ex2', 'industry': 'in2', 'website': 'ws2', 'description': 'dc2', 'CEO': 'ceo2', 'issueType': 'is2', 'sector': 'sc2'}, {'symbol': 'sy3', 'companyName': 'cn3', 'exchange': 'ex3', 'industry': 'in3', 'website': 'ws3', 'description': 'dc3', 'CEO': 'ceo3', 'issueType': 'is3', 'sector': 'sc3'}, {'symbol': 'sy4', 'companyName': 'cn4', 'exchange': 'ex4', 'industry': 'in4', 'website': 'ws4', 'description': 'dc4', 'CEO': 'ceo4', 'issueType': 'is4', 'sector': 'sc4'}, {'symbol': 'sy5', 'companyName': 'cn5', 'exchange': 'ex5', 'industry': 'in5', 'website': 'ws5', 'description': 'dc5', 'CEO': 'ceo5', 'issueType': 'is5', 'sector': 'sc5'}, {'symbol': 'sy6', 'companyName': 'cn6', 'exchange': 'ex6', 'industry': 'in6', 'website': 'ws6', 'description': 'dc6', 'CEO': 'ceo6', 'issueType': 'is6', 'sector': 'sc6'}, {'symbol': 'sy7', 'companyName': 'cn7', 'exchange': 'ex7', 'industry': 'in7', 'website': 'ws7', 'description': 'dc7', 'CEO': 'ceo7', 'issueType': 'is7', 'sector': 'sc7'}, {'symbol': 'sy8', 'companyName': 'cn8', 'exchange': 'ex8', 'industry': 'in8', 'website': 'ws8', 'description': 'dc8', 'CEO': 'ceo8', 'issueType': 'is8', 'sector': 'sc8'}, {'symbol': 'sy9', 'companyName': 'cn9', 'exchange': 'ex9', 'industry': 'in9', 'website': 'ws9', 'description': 'dc9', 'CEO': 'ceo9', 'issueType': 'is9', 'sector': 'sc9'}, {'symbol': 'sy', 'companyName': 'cn', 'exchange': 'ex', 'industry': 'in', 'website': 'ws', 'description': 'dc', 'CEO': 'ceo', 'issueType': 'is', 'sector': 'sc'}] |
# Only used for PyTorch open source BUCK build
# @lint-ignore-every BUCKRESTRICTEDSYNTAX
def is_arvr_mode():
if read_config("pt", "is_oss", "0") == "0":
fail("This file is for open source pytorch build. Do not use it in fbsource!")
return False
| def is_arvr_mode():
if read_config('pt', 'is_oss', '0') == '0':
fail('This file is for open source pytorch build. Do not use it in fbsource!')
return False |
# a = "crazy_python"
# print(id(a))
# print(id("crazy" + "_" + "python"))
"""
output:
41899952
41899952
"""
a = 'crazy'
b = 'crazy'
c = 'crazy!!'
d = 'crazy!!'
e, f = "crazy!", "crazy!"
print (a is b)
print(c is d)
print(e is f)
"""
output:
True
True
True
"""
array_1 = [1,2,3,4]
print(id(array_1))
g1 = (x for x in array_1)
array_1 = [1,2,3,4,5]
print(id(array_1))
"""
output:
41768200
41767048
""" | """
output:
41899952
41899952
"""
a = 'crazy'
b = 'crazy'
c = 'crazy!!'
d = 'crazy!!'
(e, f) = ('crazy!', 'crazy!')
print(a is b)
print(c is d)
print(e is f)
'\noutput:\nTrue\nTrue\nTrue\n'
array_1 = [1, 2, 3, 4]
print(id(array_1))
g1 = (x for x in array_1)
array_1 = [1, 2, 3, 4, 5]
print(id(array_1))
'\noutput:\n41768200\n41767048\n' |
class ValueParsingOptions(object,IDisposable):
"""
Options for parsing strings into numbers with units.
ValueParsingOptions()
"""
def Dispose(self):
""" Dispose(self: ValueParsingOptions) """
pass
def GetFormatOptions(self):
"""
GetFormatOptions(self: ValueParsingOptions) -> FormatOptions
Gets the FormatOptions to optionally override the default settings in the Units
class.
Returns: A copy of the FormatOptions.
"""
pass
def ReleaseUnmanagedResources(self,*args):
""" ReleaseUnmanagedResources(self: ValueParsingOptions,disposing: bool) """
pass
def SetFormatOptions(self,formatOptions):
"""
SetFormatOptions(self: ValueParsingOptions,formatOptions: FormatOptions)
Sets the FormatOptions to optionally override the default settings in the Units
class.
formatOptions: The FormatOptions.
"""
pass
def __enter__(self,*args):
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self,*args):
""" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __repr__(self,*args):
""" __repr__(self: object) -> str """
pass
AllowedValues=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""The allowable range of values to be parsed.
Get: AllowedValues(self: ValueParsingOptions) -> AllowedValues
Set: AllowedValues(self: ValueParsingOptions)=value
"""
IsValidObject=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Specifies whether the .NET object represents a valid Revit entity.
Get: IsValidObject(self: ValueParsingOptions) -> bool
"""
| class Valueparsingoptions(object, IDisposable):
"""
Options for parsing strings into numbers with units.
ValueParsingOptions()
"""
def dispose(self):
""" Dispose(self: ValueParsingOptions) """
pass
def get_format_options(self):
"""
GetFormatOptions(self: ValueParsingOptions) -> FormatOptions
Gets the FormatOptions to optionally override the default settings in the Units
class.
Returns: A copy of the FormatOptions.
"""
pass
def release_unmanaged_resources(self, *args):
""" ReleaseUnmanagedResources(self: ValueParsingOptions,disposing: bool) """
pass
def set_format_options(self, formatOptions):
"""
SetFormatOptions(self: ValueParsingOptions,formatOptions: FormatOptions)
Sets the FormatOptions to optionally override the default settings in the Units
class.
formatOptions: The FormatOptions.
"""
pass
def __enter__(self, *args):
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self, *args):
""" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __repr__(self, *args):
""" __repr__(self: object) -> str """
pass
allowed_values = property(lambda self: object(), lambda self, v: None, lambda self: None)
'The allowable range of values to be parsed.\n\n\n\nGet: AllowedValues(self: ValueParsingOptions) -> AllowedValues\n\n\n\nSet: AllowedValues(self: ValueParsingOptions)=value\n\n'
is_valid_object = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Specifies whether the .NET object represents a valid Revit entity.\n\n\n\nGet: IsValidObject(self: ValueParsingOptions) -> bool\n\n\n\n' |
"""Below Python Programme demonstrate lstrip
functions in a string"""
#Example:
random_string = ' this is good '
# Leading whitepsace are removed
print(random_string.lstrip())
# Argument doesn't contain space
# No characters are removed.
print(random_string.lstrip('sti'))
print(random_string.lstrip('s ti'))
| """Below Python Programme demonstrate lstrip
functions in a string"""
random_string = ' this is good '
print(random_string.lstrip())
print(random_string.lstrip('sti'))
print(random_string.lstrip('s ti')) |
# Diffusion 2D
nx = 20 # number of elements
ny = nx
# number of nodes
mx = nx + 1
my = ny + 1
# initial values
iv = {}
for j in range(int(0.2*my), int(0.3*my)):
for i in range(int(0.5*mx), int(0.8*mx)):
index = j*mx + i
iv[index] = 1.0
print("iv: ",iv)
config = {
"solverStructureDiagramFile": "solver_structure.txt", # output file of a diagram that shows data connection between solvers
"logFormat": "csv", # "csv" or "json", format of the lines in the log file, csv gives smaller files
"scenarioName": "diffusion", # scenario name to find the run in the log file
"mappingsBetweenMeshesLogFile": "", # a log file about mappings between meshes, here we do not want that because there are no mappings
"Heun" : {
"initialValues": iv,
"timeStepWidth": 1e-3,
"endTime": 1.0,
"timeStepOutputInterval": 100,
"checkForNanInf": False,
"inputMeshIsGlobal": True,
"nAdditionalFieldVariables": 0,
"additionalSlotNames": [],
"dirichletBoundaryConditions": {},
"dirichletOutputFilename": None, # filename for a vtp file that contains the Dirichlet boundary condition nodes and their values, set to None to disable
"FiniteElementMethod" : {
"nElements": [nx, ny],
"physicalExtent": [4.0,4.0],
"inputMeshIsGlobal": True,
"prefactor": 0.1,
# solver parameters
"solverType": "gmres",
"preconditionerType": "none",
"relativeTolerance": 1e-15, # relative tolerance of the residual normal, respective to the initial residual norm, linear solver
"absoluteTolerance": 1e-10, # 1e-10 absolute tolerance of the residual
"maxIterations": 10000,
"dumpFilename": "",
"dumpFormat": "ascii", # ascii, default or matlab
"slotName": "",
},
"OutputWriter" : [
{"format": "Paraview", "outputInterval": 10, "filename": "out/filename", "binary": "false", "fixedFormat": False, "onlyNodalValues": True, "combineFiles": True, "fileNumbering": "incremental"},
{"format": "PythonFile", "outputInterval": 10, "filename": "out/out_diffusion2d", "binary": True, "onlyNodalValues": True, "combineFiles": True, "fileNumbering": "incremental"}
]
},
}
| nx = 20
ny = nx
mx = nx + 1
my = ny + 1
iv = {}
for j in range(int(0.2 * my), int(0.3 * my)):
for i in range(int(0.5 * mx), int(0.8 * mx)):
index = j * mx + i
iv[index] = 1.0
print('iv: ', iv)
config = {'solverStructureDiagramFile': 'solver_structure.txt', 'logFormat': 'csv', 'scenarioName': 'diffusion', 'mappingsBetweenMeshesLogFile': '', 'Heun': {'initialValues': iv, 'timeStepWidth': 0.001, 'endTime': 1.0, 'timeStepOutputInterval': 100, 'checkForNanInf': False, 'inputMeshIsGlobal': True, 'nAdditionalFieldVariables': 0, 'additionalSlotNames': [], 'dirichletBoundaryConditions': {}, 'dirichletOutputFilename': None, 'FiniteElementMethod': {'nElements': [nx, ny], 'physicalExtent': [4.0, 4.0], 'inputMeshIsGlobal': True, 'prefactor': 0.1, 'solverType': 'gmres', 'preconditionerType': 'none', 'relativeTolerance': 1e-15, 'absoluteTolerance': 1e-10, 'maxIterations': 10000, 'dumpFilename': '', 'dumpFormat': 'ascii', 'slotName': ''}, 'OutputWriter': [{'format': 'Paraview', 'outputInterval': 10, 'filename': 'out/filename', 'binary': 'false', 'fixedFormat': False, 'onlyNodalValues': True, 'combineFiles': True, 'fileNumbering': 'incremental'}, {'format': 'PythonFile', 'outputInterval': 10, 'filename': 'out/out_diffusion2d', 'binary': True, 'onlyNodalValues': True, 'combineFiles': True, 'fileNumbering': 'incremental'}]}} |
__title__ = 'lightwood'
__package_name__ = 'mindsdb'
__version__ = '0.14.1'
__description__ = "Lightwood's goal is to make it very simple for developers to use the power of artificial neural networks in their projects."
__email__ = "jorge@mindsdb.com"
__author__ = 'MindsDB Inc'
__github__ = 'https://github.com/mindsdb/lightwood'
__pypi__ = 'https://pypi.org/project/lightwood'
__license__ = 'MIT'
__copyright__ = 'Copyright 2019- mindsdb'
| __title__ = 'lightwood'
__package_name__ = 'mindsdb'
__version__ = '0.14.1'
__description__ = "Lightwood's goal is to make it very simple for developers to use the power of artificial neural networks in their projects."
__email__ = 'jorge@mindsdb.com'
__author__ = 'MindsDB Inc'
__github__ = 'https://github.com/mindsdb/lightwood'
__pypi__ = 'https://pypi.org/project/lightwood'
__license__ = 'MIT'
__copyright__ = 'Copyright 2019- mindsdb' |
# Problem: input: an unsorted array A[lo..hi]; | output: the (left) median of the given array
# Source: SCU COEN279 DAA HW3 Q3
# Author: Shreyas Padhye
# Algorithm: Decrease-Conquer
class solution():
def left_median(self, A):
if len(A) == 1 or len(A) == 2:
return A[0]
else:
median = self.left_median(A[:-1])
if len(A[:-1]) % 2 == 0:
if median > A[-1]:
return median
else:
med_neighbour = A.index(median) + 1
if A[-1] < A[med_neighbour]:
temp = A[-1]
A[-1] = A[med_neighbour]
A[med_neighbour] = temp
return A[med_neighbour]
elif median < A[-1]:
return median
else:
med_neighbour = A.index(median) - 1
if A[-1] > A[med_neighbour]:
temp = A[-1]
A[-1] = A[med_neighbour]
A[med_neighbour] = temp
return A[med_neighbour]
t = solution()
# t.left_median([0, 1, 3, 5]) #1
# t.left_median([0, 1, 3, 5, 2]) #2
# t.left_median([0, 1, 3, 5]) #1
t.left_median([0, 1, 3, 5]) #1
t.left_median([5, 1, 3, 8, 2]) #5
t.left_median([7, 0, 1, 12, 1, 45, 2]) #7
t.left_median([7, 0, 1, 12, 45, 2, 11, 8, 101, 14]) #correct: 8, mine: 12
# t.left_median([7, 0, 1, 12, 1, 45, 2, 11, 8, 101, 14]) #correct: 8, mine: 1
| class Solution:
def left_median(self, A):
if len(A) == 1 or len(A) == 2:
return A[0]
else:
median = self.left_median(A[:-1])
if len(A[:-1]) % 2 == 0:
if median > A[-1]:
return median
else:
med_neighbour = A.index(median) + 1
if A[-1] < A[med_neighbour]:
temp = A[-1]
A[-1] = A[med_neighbour]
A[med_neighbour] = temp
return A[med_neighbour]
elif median < A[-1]:
return median
else:
med_neighbour = A.index(median) - 1
if A[-1] > A[med_neighbour]:
temp = A[-1]
A[-1] = A[med_neighbour]
A[med_neighbour] = temp
return A[med_neighbour]
t = solution()
t.left_median([0, 1, 3, 5])
t.left_median([5, 1, 3, 8, 2])
t.left_median([7, 0, 1, 12, 1, 45, 2])
t.left_median([7, 0, 1, 12, 45, 2, 11, 8, 101, 14]) |
"""
This module provide all the functions or classes which help pre-processing data.
For example, splitting paragraph into sentences
"""
| """
This module provide all the functions or classes which help pre-processing data.
For example, splitting paragraph into sentences
""" |
"""
Defines CPU Options for use in the CPU target
"""
class FastMathOptions(object):
"""
Options for controlling fast math optimization.
"""
def __init__(self, value):
# https://releases.llvm.org/7.0.0/docs/LangRef.html#fast-math-flags
valid_flags = {
'fast',
'nnan', 'ninf', 'nsz', 'arcp',
'contract', 'afn', 'reassoc',
}
if isinstance(value, FastMathOptions):
self.flags = value.flags.copy()
elif value is True:
self.flags = {'fast'}
elif value is False:
self.flags = set()
elif isinstance(value, set):
invalid = value - valid_flags
if invalid:
raise ValueError("Unrecognized fastmath flags: %s" % invalid)
self.flags = value
elif isinstance(value, dict):
invalid = set(value.keys()) - valid_flags
if invalid:
raise ValueError("Unrecognized fastmath flags: %s" % invalid)
self.flags = {v for v, enable in value.items() if enable}
else:
msg = "Expected fastmath option(s) to be either a bool, dict or set"
raise ValueError(msg)
def __bool__(self):
return bool(self.flags)
__nonzero__ = __bool__
def __repr__(self):
return f"FastMathOptions({self.flags})"
def __eq__(self, other):
if type(other) is type(self):
return self.flags == other.flags
return NotImplemented
class ParallelOptions(object):
"""
Options for controlling auto parallelization.
"""
__slots__ = ("enabled", "comprehension", "reduction", "inplace_binop",
"setitem", "numpy", "stencil", "fusion", "prange")
def __init__(self, value):
if isinstance(value, bool):
self.enabled = value
self.comprehension = value
self.reduction = value
self.inplace_binop = value
self.setitem = value
self.numpy = value
self.stencil = value
self.fusion = value
self.prange = value
elif isinstance(value, dict):
self.enabled = True
self.comprehension = value.pop('comprehension', True)
self.reduction = value.pop('reduction', True)
self.inplace_binop = value.pop('inplace_binop', True)
self.setitem = value.pop('setitem', True)
self.numpy = value.pop('numpy', True)
self.stencil = value.pop('stencil', True)
self.fusion = value.pop('fusion', True)
self.prange = value.pop('prange', True)
if value:
msg = "Unrecognized parallel options: %s" % value.keys()
raise NameError(msg)
elif isinstance(value, ParallelOptions):
self.enabled = value.enabled
self.comprehension = value.comprehension
self.reduction = value.reduction
self.inplace_binop = value.inplace_binop
self.setitem = value.setitem
self.numpy = value.numpy
self.stencil = value.stencil
self.fusion = value.fusion
self.prange = value.prange
else:
msg = "Expect parallel option to be either a bool or a dict"
raise ValueError(msg)
def _get_values(self):
"""Get values as dictionary.
"""
return {k: getattr(self, k) for k in self.__slots__}
def __eq__(self, other):
if type(other) is type(self):
return self._get_values() == other._get_values()
return NotImplemented
class InlineOptions(object):
"""
Options for controlling inlining
"""
def __init__(self, value):
ok = False
if isinstance(value, str):
if value in ('always', 'never'):
ok = True
else:
ok = hasattr(value, '__call__')
if ok:
self._inline = value
else:
msg = ("kwarg 'inline' must be one of the strings 'always' or "
"'never', or it can be a callable that returns True/False. "
"Found value %s" % value)
raise ValueError(msg)
@property
def is_never_inline(self):
"""
True if never inline
"""
return self._inline == 'never'
@property
def is_always_inline(self):
"""
True if always inline
"""
return self._inline == 'always'
@property
def has_cost_model(self):
"""
True if a cost model is provided
"""
return not (self.is_always_inline or self.is_never_inline)
@property
def value(self):
"""
The raw value
"""
return self._inline
def __eq__(self, other):
if type(other) is type(self):
return self.value == other.value
return NotImplemented
| """
Defines CPU Options for use in the CPU target
"""
class Fastmathoptions(object):
"""
Options for controlling fast math optimization.
"""
def __init__(self, value):
valid_flags = {'fast', 'nnan', 'ninf', 'nsz', 'arcp', 'contract', 'afn', 'reassoc'}
if isinstance(value, FastMathOptions):
self.flags = value.flags.copy()
elif value is True:
self.flags = {'fast'}
elif value is False:
self.flags = set()
elif isinstance(value, set):
invalid = value - valid_flags
if invalid:
raise value_error('Unrecognized fastmath flags: %s' % invalid)
self.flags = value
elif isinstance(value, dict):
invalid = set(value.keys()) - valid_flags
if invalid:
raise value_error('Unrecognized fastmath flags: %s' % invalid)
self.flags = {v for (v, enable) in value.items() if enable}
else:
msg = 'Expected fastmath option(s) to be either a bool, dict or set'
raise value_error(msg)
def __bool__(self):
return bool(self.flags)
__nonzero__ = __bool__
def __repr__(self):
return f'FastMathOptions({self.flags})'
def __eq__(self, other):
if type(other) is type(self):
return self.flags == other.flags
return NotImplemented
class Paralleloptions(object):
"""
Options for controlling auto parallelization.
"""
__slots__ = ('enabled', 'comprehension', 'reduction', 'inplace_binop', 'setitem', 'numpy', 'stencil', 'fusion', 'prange')
def __init__(self, value):
if isinstance(value, bool):
self.enabled = value
self.comprehension = value
self.reduction = value
self.inplace_binop = value
self.setitem = value
self.numpy = value
self.stencil = value
self.fusion = value
self.prange = value
elif isinstance(value, dict):
self.enabled = True
self.comprehension = value.pop('comprehension', True)
self.reduction = value.pop('reduction', True)
self.inplace_binop = value.pop('inplace_binop', True)
self.setitem = value.pop('setitem', True)
self.numpy = value.pop('numpy', True)
self.stencil = value.pop('stencil', True)
self.fusion = value.pop('fusion', True)
self.prange = value.pop('prange', True)
if value:
msg = 'Unrecognized parallel options: %s' % value.keys()
raise name_error(msg)
elif isinstance(value, ParallelOptions):
self.enabled = value.enabled
self.comprehension = value.comprehension
self.reduction = value.reduction
self.inplace_binop = value.inplace_binop
self.setitem = value.setitem
self.numpy = value.numpy
self.stencil = value.stencil
self.fusion = value.fusion
self.prange = value.prange
else:
msg = 'Expect parallel option to be either a bool or a dict'
raise value_error(msg)
def _get_values(self):
"""Get values as dictionary.
"""
return {k: getattr(self, k) for k in self.__slots__}
def __eq__(self, other):
if type(other) is type(self):
return self._get_values() == other._get_values()
return NotImplemented
class Inlineoptions(object):
"""
Options for controlling inlining
"""
def __init__(self, value):
ok = False
if isinstance(value, str):
if value in ('always', 'never'):
ok = True
else:
ok = hasattr(value, '__call__')
if ok:
self._inline = value
else:
msg = "kwarg 'inline' must be one of the strings 'always' or 'never', or it can be a callable that returns True/False. Found value %s" % value
raise value_error(msg)
@property
def is_never_inline(self):
"""
True if never inline
"""
return self._inline == 'never'
@property
def is_always_inline(self):
"""
True if always inline
"""
return self._inline == 'always'
@property
def has_cost_model(self):
"""
True if a cost model is provided
"""
return not (self.is_always_inline or self.is_never_inline)
@property
def value(self):
"""
The raw value
"""
return self._inline
def __eq__(self, other):
if type(other) is type(self):
return self.value == other.value
return NotImplemented |
def get_belief(sent):
if '<|belief|>' in sent:
tmp = sent.strip(' ').split('<|belief|>')[-1].split('<|action|>')[0]
else:
return []
tmp = tmp.strip(' .,')
tmp = tmp.replace('<|endofbelief|>', '')
tmp = tmp.replace('<|endoftext|>', '')
belief = tmp.split(',')
new_belief = []
for bs in belief:
bs = bs.strip(' .,')
if bs not in new_belief:
new_belief.append(bs)
return new_belief
def get_belief_dbsearch(sent):
if '<|belief|>' in sent:
tmp = sent.strip(' ').split('<|belief|>')[-1].split('<|endofbelief|>')[0]
else:
return []
tmp = tmp.strip(' .,')
tmp = tmp.replace('<|endofbelief|>', '')
tmp = tmp.replace('<|endoftext|>', '')
belief = tmp.split(',')
new_belief = []
for bs in belief:
bs = bs.strip(' .,')
if bs not in new_belief:
new_belief.append(bs)
return new_belief
def get_belief_openaigpt(sent):
if '< | belief | >' in sent:
tmp = sent.strip(' ').split('< | belief | >')[-1].split('< | action | >')[0]
else:
return []
tmp = tmp.strip(' .,')
tmp = tmp.replace('< | endofbelief | >', '')
tmp = tmp.replace('< | endoftext | >', '')
belief = tmp.split(',')
new_belief = []
for bs in belief:
bs = bs.strip(' .,')
if bs not in new_belief:
new_belief.append(bs)
return new_belief
def get_response(sent, tokenizer):
if '<|response|>' in sent:
tmp = sent.split('<|belief|>')[-1].split('<|action|>')[-1].split('<|response|>')[-1]
else:
return ''
tmp = tmp.strip(' .,')
tmp = tmp.replace('<|endofresponse|>', '')
tmp = tmp.replace('<|endoftext|>', '')
tokens = tokenizer.encode(tmp)
new_tokens = []
for tok in tokens:
if tok in tokenizer.encode(tokenizer._eos_token):
continue
new_tokens.append(tok)
response = tokenizer.decode(new_tokens).strip(' ,.')
return response
def get_response_openaigpt(sent, tokenizer):
if '< | response | >' in sent:
tmp = sent.split('< | belief | >')[-1].split('< | action | >')[-1].split('< | response | >')[-1]
else:
return ''
tmp = tmp.strip(' .,')
tmp = tmp.replace('< | endofresponse | >', '')
tmp = tmp.replace('< | endoftext | >', '')
tokens = tokenizer.encode(tmp)
new_tokens = []
for tok in tokens:
if tok in tokenizer.encode(tokenizer._eos_token):
continue
new_tokens.append(tok)
response = tokenizer.decode(new_tokens).strip(' ,.')
response = response.replace('[ ', '[')
response = response.replace(' ]', ']')
response = response.replace(' _ ', '_')
response = response.replace('i d', 'id')
return response
def get_action(sent):
if '<|action|>' not in sent:
return []
elif '<|belief|>' in sent:
tmp = sent.split('<|belief|>')[-1].split('<|response|>')[0].split('<|action|>')[-1].strip()
elif '<|action|>' in sent:
tmp = sent.split('<|response|>')[0].split('<|action|>')[-1].strip()
else:
return []
tmp = tmp.strip(' .,')
tmp = tmp.replace('<|endofaction|>', '')
tmp = tmp.replace('<|endoftext|>', '')
action = tmp.split(',')
new_action = []
for act in action:
if act == '':
continue
act = act.strip(' .,')
if act not in new_action:
new_action.append(act)
return new_action
def get_action_openaigpt(sent):
if '< | belief | >' in sent:
tmp = sent.split('< | belief | >')[-1].split('< | response | >')[0].split('< | action | >')[-1].strip()
elif '< | action | >' in sent:
tmp = sent.split('< | response | >')[0].split('< | action | >')[-1].strip()
else:
return []
tmp = tmp.strip(' .,')
tmp = tmp.replace('< | endofaction | >', '')
tmp = tmp.replace('< | endoftext | >', '')
action = tmp.split(',')
new_action = []
for act in action:
if act == '':
continue
act = act.strip(' .,')
if act not in new_action:
act = act.replace('i d', 'id')
new_action.append(act)
return new_action
def get_db_dynamically(predicted_text, goal, multiwoz_db):
gen_belief = get_belief_dbsearch(predicted_text)
belief_domain = {}
belief_book_domain = {}
for bs in gen_belief:
if bs in ['', ' ']:
continue
bs_domain = bs.split()[0]
if 'book' in bs:
bs_slot = bs.split()[2]
bs_val = ' '.join(bs.split()[3:])
if bs_domain not in belief_book_domain:
belief_book_domain[bs_domain] = {}
belief_book_domain[bs_domain][bs_slot] = bs_val
else:
bs_slot = bs.split()[1]
bs_val = ' '.join(bs.split()[2:])
if bs_domain not in belief_domain:
belief_domain[bs_domain] = {}
belief_book_domain[bs_domain] = {}
belief_domain[bs_domain][bs_slot] = bs_val
db_text_tmp = []
for dom in belief_domain:
if dom not in ['restaurant', 'hotel', 'attraction', 'train']:
continue
domain_match = len(multiwoz_db.queryResultVenues(dom, belief_domain[dom], real_belief=True))
if dom != 'train':
if domain_match >= 5:
domain_match_text = '>=5'
else:
domain_match_text = '={}'.format(domain_match)
elif dom == 'train':
if domain_match == 0:
domain_match_text = '=0'
elif domain_match == 2:
domain_match_text = '<3'
elif domain_match == 5:
domain_match_text = '<6'
elif domain_match == 10:
domain_match_text = '<11'
elif domain_match == 40:
domain_match_text = '<41'
else:
domain_match_text = '>40'
if 'fail_book' in goal[dom]:
for item in goal[dom]['fail_book'].items():
if item in belief_book_domain[dom].items():
domain_book_text = 'not available'
break
else:
domain_book_text = 'available'
else:
if domain_match == 0:
domain_book_text = 'not available'
else:
domain_book_text = 'available'
db_text_tmp.append('{} match{} booking={}'.format(dom, domain_match_text, domain_book_text))
db_text = ' <|dbsearch|> {} <|endofdbsearch|>'.format(' , '.join(db_text_tmp))
return db_text
| def get_belief(sent):
if '<|belief|>' in sent:
tmp = sent.strip(' ').split('<|belief|>')[-1].split('<|action|>')[0]
else:
return []
tmp = tmp.strip(' .,')
tmp = tmp.replace('<|endofbelief|>', '')
tmp = tmp.replace('<|endoftext|>', '')
belief = tmp.split(',')
new_belief = []
for bs in belief:
bs = bs.strip(' .,')
if bs not in new_belief:
new_belief.append(bs)
return new_belief
def get_belief_dbsearch(sent):
if '<|belief|>' in sent:
tmp = sent.strip(' ').split('<|belief|>')[-1].split('<|endofbelief|>')[0]
else:
return []
tmp = tmp.strip(' .,')
tmp = tmp.replace('<|endofbelief|>', '')
tmp = tmp.replace('<|endoftext|>', '')
belief = tmp.split(',')
new_belief = []
for bs in belief:
bs = bs.strip(' .,')
if bs not in new_belief:
new_belief.append(bs)
return new_belief
def get_belief_openaigpt(sent):
if '< | belief | >' in sent:
tmp = sent.strip(' ').split('< | belief | >')[-1].split('< | action | >')[0]
else:
return []
tmp = tmp.strip(' .,')
tmp = tmp.replace('< | endofbelief | >', '')
tmp = tmp.replace('< | endoftext | >', '')
belief = tmp.split(',')
new_belief = []
for bs in belief:
bs = bs.strip(' .,')
if bs not in new_belief:
new_belief.append(bs)
return new_belief
def get_response(sent, tokenizer):
if '<|response|>' in sent:
tmp = sent.split('<|belief|>')[-1].split('<|action|>')[-1].split('<|response|>')[-1]
else:
return ''
tmp = tmp.strip(' .,')
tmp = tmp.replace('<|endofresponse|>', '')
tmp = tmp.replace('<|endoftext|>', '')
tokens = tokenizer.encode(tmp)
new_tokens = []
for tok in tokens:
if tok in tokenizer.encode(tokenizer._eos_token):
continue
new_tokens.append(tok)
response = tokenizer.decode(new_tokens).strip(' ,.')
return response
def get_response_openaigpt(sent, tokenizer):
if '< | response | >' in sent:
tmp = sent.split('< | belief | >')[-1].split('< | action | >')[-1].split('< | response | >')[-1]
else:
return ''
tmp = tmp.strip(' .,')
tmp = tmp.replace('< | endofresponse | >', '')
tmp = tmp.replace('< | endoftext | >', '')
tokens = tokenizer.encode(tmp)
new_tokens = []
for tok in tokens:
if tok in tokenizer.encode(tokenizer._eos_token):
continue
new_tokens.append(tok)
response = tokenizer.decode(new_tokens).strip(' ,.')
response = response.replace('[ ', '[')
response = response.replace(' ]', ']')
response = response.replace(' _ ', '_')
response = response.replace('i d', 'id')
return response
def get_action(sent):
if '<|action|>' not in sent:
return []
elif '<|belief|>' in sent:
tmp = sent.split('<|belief|>')[-1].split('<|response|>')[0].split('<|action|>')[-1].strip()
elif '<|action|>' in sent:
tmp = sent.split('<|response|>')[0].split('<|action|>')[-1].strip()
else:
return []
tmp = tmp.strip(' .,')
tmp = tmp.replace('<|endofaction|>', '')
tmp = tmp.replace('<|endoftext|>', '')
action = tmp.split(',')
new_action = []
for act in action:
if act == '':
continue
act = act.strip(' .,')
if act not in new_action:
new_action.append(act)
return new_action
def get_action_openaigpt(sent):
if '< | belief | >' in sent:
tmp = sent.split('< | belief | >')[-1].split('< | response | >')[0].split('< | action | >')[-1].strip()
elif '< | action | >' in sent:
tmp = sent.split('< | response | >')[0].split('< | action | >')[-1].strip()
else:
return []
tmp = tmp.strip(' .,')
tmp = tmp.replace('< | endofaction | >', '')
tmp = tmp.replace('< | endoftext | >', '')
action = tmp.split(',')
new_action = []
for act in action:
if act == '':
continue
act = act.strip(' .,')
if act not in new_action:
act = act.replace('i d', 'id')
new_action.append(act)
return new_action
def get_db_dynamically(predicted_text, goal, multiwoz_db):
gen_belief = get_belief_dbsearch(predicted_text)
belief_domain = {}
belief_book_domain = {}
for bs in gen_belief:
if bs in ['', ' ']:
continue
bs_domain = bs.split()[0]
if 'book' in bs:
bs_slot = bs.split()[2]
bs_val = ' '.join(bs.split()[3:])
if bs_domain not in belief_book_domain:
belief_book_domain[bs_domain] = {}
belief_book_domain[bs_domain][bs_slot] = bs_val
else:
bs_slot = bs.split()[1]
bs_val = ' '.join(bs.split()[2:])
if bs_domain not in belief_domain:
belief_domain[bs_domain] = {}
belief_book_domain[bs_domain] = {}
belief_domain[bs_domain][bs_slot] = bs_val
db_text_tmp = []
for dom in belief_domain:
if dom not in ['restaurant', 'hotel', 'attraction', 'train']:
continue
domain_match = len(multiwoz_db.queryResultVenues(dom, belief_domain[dom], real_belief=True))
if dom != 'train':
if domain_match >= 5:
domain_match_text = '>=5'
else:
domain_match_text = '={}'.format(domain_match)
elif dom == 'train':
if domain_match == 0:
domain_match_text = '=0'
elif domain_match == 2:
domain_match_text = '<3'
elif domain_match == 5:
domain_match_text = '<6'
elif domain_match == 10:
domain_match_text = '<11'
elif domain_match == 40:
domain_match_text = '<41'
else:
domain_match_text = '>40'
if 'fail_book' in goal[dom]:
for item in goal[dom]['fail_book'].items():
if item in belief_book_domain[dom].items():
domain_book_text = 'not available'
break
else:
domain_book_text = 'available'
elif domain_match == 0:
domain_book_text = 'not available'
else:
domain_book_text = 'available'
db_text_tmp.append('{} match{} booking={}'.format(dom, domain_match_text, domain_book_text))
db_text = ' <|dbsearch|> {} <|endofdbsearch|>'.format(' , '.join(db_text_tmp))
return db_text |
'''
Created on 2016-01-13
@author: Wu Wenxiang (wuwenxiang.sh@gmail.com)
'''
DEBUG = False | """
Created on 2016-01-13
@author: Wu Wenxiang (wuwenxiang.sh@gmail.com)
"""
debug = False |
description = 'Helmholtz field coil'
group = 'optional'
includes = ['alias_B']
tango_base = 'tango://phys.kws1.frm2:10000/kws1/'
devices = dict(
I_helmholtz = device('nicos.devices.entangle.PowerSupply',
description = 'Current in coils',
tangodevice = tango_base + 'gesupply/ps2',
unit = 'A',
fmtstr = '%.2f',
),
B_helmholtz = device('nicos.devices.generic.CalibratedMagnet',
currentsource = 'I_helmholtz',
description = 'Magnet field',
unit = 'T',
fmtstr = '%.5f',
calibration = (
0.0032507550, # slope 0.003255221(old)
0,
0,
0,
0
)
),
)
alias_config = {
'B': {'B_helmholtz': 100},
}
extended = dict(
representative = 'B_helmholtz',
)
| description = 'Helmholtz field coil'
group = 'optional'
includes = ['alias_B']
tango_base = 'tango://phys.kws1.frm2:10000/kws1/'
devices = dict(I_helmholtz=device('nicos.devices.entangle.PowerSupply', description='Current in coils', tangodevice=tango_base + 'gesupply/ps2', unit='A', fmtstr='%.2f'), B_helmholtz=device('nicos.devices.generic.CalibratedMagnet', currentsource='I_helmholtz', description='Magnet field', unit='T', fmtstr='%.5f', calibration=(0.003250755, 0, 0, 0, 0)))
alias_config = {'B': {'B_helmholtz': 100}}
extended = dict(representative='B_helmholtz') |
# Test checked
class SymbolTable(object):
def __init__(self):
self._symbols = \
{ \
'SP':0, 'LCL':1, 'ARG':2, 'THIS':3, 'THAT':4, \
'R0':0, 'R1':1, 'R2':2, 'R3':3, 'R4':4, 'R5':5, 'R6':6, 'R7':7, \
'R8':8, 'R9':9, 'R10':10, 'R11':11, 'R12':12, 'R13':13, 'R14':14, \
'R15':15, 'SCREEN':0x4000, 'KBD':0x6000 \
}
def add_entry(self, symbol, address):
self._symbols[symbol] = address
def contains(self, symbol):
return symbol in self._symbols
def get_address(self, symbol):
return self._symbols[symbol]
| class Symboltable(object):
def __init__(self):
self._symbols = {'SP': 0, 'LCL': 1, 'ARG': 2, 'THIS': 3, 'THAT': 4, 'R0': 0, 'R1': 1, 'R2': 2, 'R3': 3, 'R4': 4, 'R5': 5, 'R6': 6, 'R7': 7, 'R8': 8, 'R9': 9, 'R10': 10, 'R11': 11, 'R12': 12, 'R13': 13, 'R14': 14, 'R15': 15, 'SCREEN': 16384, 'KBD': 24576}
def add_entry(self, symbol, address):
self._symbols[symbol] = address
def contains(self, symbol):
return symbol in self._symbols
def get_address(self, symbol):
return self._symbols[symbol] |
''' This the demonstration of range function in python'''
class Range:
"""A class that mimic's the built-in range class"""
def __init__(self, start, stop=None, step=1):
"""Initialize a Range instance
Semantic is similar to built-in range class
"""
if step == 0:
raise ValueError('step cannot be 0')
if stop == None:
stop, start = start, 0 # special case of range(n)
#calculate the effective lenght once
self._length = max(0, (stop -start + step -1)//step)
# need knowledge to start and step(but not stop) to support __getitem__
self._start = start
self._step = step
def __len__(self):
"""Return number of entries in the range"""
return self._length
def __getitem__(self, k):
"""Return entry at index k(using standar interpreation if negative)"""
if k < 0:
k += len(self) #attempt to convert negative index; depends on __len__
if not 0 <= k < self._length:
raise IndexError('index out of range')
return self._start + k*self._step
#------------------------------------------------------------------------------------------
def test():
r = Range(8, 140, 5)
print(r)
print(len(r))
print(r[25])
print(r[-1])
if __name__ == "__main__":
test() | """ This the demonstration of range function in python"""
class Range:
"""A class that mimic's the built-in range class"""
def __init__(self, start, stop=None, step=1):
"""Initialize a Range instance
Semantic is similar to built-in range class
"""
if step == 0:
raise value_error('step cannot be 0')
if stop == None:
(stop, start) = (start, 0)
self._length = max(0, (stop - start + step - 1) // step)
self._start = start
self._step = step
def __len__(self):
"""Return number of entries in the range"""
return self._length
def __getitem__(self, k):
"""Return entry at index k(using standar interpreation if negative)"""
if k < 0:
k += len(self)
if not 0 <= k < self._length:
raise index_error('index out of range')
return self._start + k * self._step
def test():
r = range(8, 140, 5)
print(r)
print(len(r))
print(r[25])
print(r[-1])
if __name__ == '__main__':
test() |
# File: question3.py
# Author: David Lechner
# Date: 11/19/2019
'''Ask some questions about goats'''
# REVIEW: We write `NUM_GOATS` in all caps because it is a constant. We set it
# once at the begining of the program and don't change after that.
NUM_GOATS = 10 # This is how many goats I have
# REVIEW: The input() function gives us a string, but we need a number, so we
# use int() to convert what the user types in to an integer.
# TRY IT: What happens if the user types in a letter instead of a nubmer? What
# about a number with a decimal point?
answer = int(input('How many goats do you see?'))
# LEARN: We can use inequality operators to compare numbers
if answer < NUM_GOATS:
print('Some of your goats are missing!')
if answer == NUM_GOATS:
print('All of the goats are there.')
if answer > NUM_GOATS:
print('You have extra goats!')
| """Ask some questions about goats"""
num_goats = 10
answer = int(input('How many goats do you see?'))
if answer < NUM_GOATS:
print('Some of your goats are missing!')
if answer == NUM_GOATS:
print('All of the goats are there.')
if answer > NUM_GOATS:
print('You have extra goats!') |
# lec6.4-removeDups.py
# edX MITx 6.00.1x
# Introduction to Computer Science and Programming Using Python
# Lecture 6, video 4
# Demonstrates performing operations on lists
# Demonstrates how changing a list while iterating over it creates
# unintended problems
def removeDups(L1, L2):
for e1 in L1:
if e1 in L2:
# Note: we are iterating over L1, but just removed one of
# its elements
L1.remove(e1)
# L1 is now [2,3,4] so when it loops through again the next
# element is 3. As a result the 2 is skipped and not removed
# as intended
L1 = [1,2,3,4]
L2 = [1,2,5,6]
removeDups(L1, L2)
print(L1)
# Better way to perform operations on list by creating a copy of L1
# then iterating over that as it will not change
def removeDupsBetter(L1, L2):
# Make a copy of L1 and put into L1Start
L1Start = L1[:]
for e1 in L1Start:
if e1 in L2:
L1.remove(e1)
L1 = [1,2,3,4]
L2 = [1,2,5,6]
removeDupsBetter(L1, L2)
print(L1)
| def remove_dups(L1, L2):
for e1 in L1:
if e1 in L2:
L1.remove(e1)
l1 = [1, 2, 3, 4]
l2 = [1, 2, 5, 6]
remove_dups(L1, L2)
print(L1)
def remove_dups_better(L1, L2):
l1_start = L1[:]
for e1 in L1Start:
if e1 in L2:
L1.remove(e1)
l1 = [1, 2, 3, 4]
l2 = [1, 2, 5, 6]
remove_dups_better(L1, L2)
print(L1) |
def compareTriplets(a, b):
result = []
aliceScore =0
bobScore = 0
for Alice, Bob in zip(a, b):
if Alice > Bob:
aliceScore +=1
continue
if Bob > Alice:
bobScore +=1
continue
if Alice == Bob:
continue
result.append(aliceScore)
result.append(bobScore)
return result
if __name__ == '__main__':
a = list(map(int, input('::: ').strip().split()))
b = list(map(int, input('::: ').strip().split()))
print(compareTriplets(a, b)) | def compare_triplets(a, b):
result = []
alice_score = 0
bob_score = 0
for (alice, bob) in zip(a, b):
if Alice > Bob:
alice_score += 1
continue
if Bob > Alice:
bob_score += 1
continue
if Alice == Bob:
continue
result.append(aliceScore)
result.append(bobScore)
return result
if __name__ == '__main__':
a = list(map(int, input('::: ').strip().split()))
b = list(map(int, input('::: ').strip().split()))
print(compare_triplets(a, b)) |
#file extension
'''n = input("enter file name with extension:")
f_ext = n.split('.')
x = f_ext[-1]
print(x)
#sum
n = input("enter one number:")
temp = n
temp1 = temp+temp
temp2 = temp+temp+temp
val = int(n)+int(temp1)+int(temp2)
print(val)
#Multiline comment
print("a string that you \"don\'t\" have to escape \n This \n is a ....... multi-line \n here doc string -------->")
#4
n = int(input("enter num"))
dif = n - 19
if(dif>0):
print("value is ", 2 * dif)
else:
print(dif)
#5
n = input("Enter string: ")
if(n[0:2] == "Is"):
print("String is ", n)
else:
n = "Is" + n
print("String",n)
#9
import math
n = int(input("enter value:"))
x= hex(n)
print("hexa decimal value is", x)
#10
import math
n = int(input("enter value:"))
x= bin(n)
print("hexa decimal value is", x)
#7
import math
n = input("enter character:")
x= ord(n)
print("ASCII value is", x)
#6
sec=int(input("enter the number of seconds:"))
if(sec >= 86400):
m = sec/60
h = m/60
d = h/24
print("Time in Minutes is ", m,"mins")
print("Time in Hours is ", h,"hrs")
print("Days is", d,"days")
else:
print("Seconds can\'t redable")
#8
x = int(input("enter first num:"))
y = int(input("enter second num:"))
f1 = float(x)
f2 = float(y)
if(x>y):
print("largest integer value",x)
else:
print("largest integer value",y)
if(f1>f2):
print("largest float value",f1)
else:
print("largest float value",f2)'''
| """n = input("enter file name with extension:")
f_ext = n.split('.')
x = f_ext[-1]
print(x)
#sum
n = input("enter one number:")
temp = n
temp1 = temp+temp
temp2 = temp+temp+temp
val = int(n)+int(temp1)+int(temp2)
print(val)
#Multiline comment
print("a string that you "don't" have to escape
This
is a ....... multi-line
here doc string -------->")
#4
n = int(input("enter num"))
dif = n - 19
if(dif>0):
print("value is ", 2 * dif)
else:
print(dif)
#5
n = input("Enter string: ")
if(n[0:2] == "Is"):
print("String is ", n)
else:
n = "Is" + n
print("String",n)
#9
import math
n = int(input("enter value:"))
x= hex(n)
print("hexa decimal value is", x)
#10
import math
n = int(input("enter value:"))
x= bin(n)
print("hexa decimal value is", x)
#7
import math
n = input("enter character:")
x= ord(n)
print("ASCII value is", x)
#6
sec=int(input("enter the number of seconds:"))
if(sec >= 86400):
m = sec/60
h = m/60
d = h/24
print("Time in Minutes is ", m,"mins")
print("Time in Hours is ", h,"hrs")
print("Days is", d,"days")
else:
print("Seconds can't redable")
#8
x = int(input("enter first num:"))
y = int(input("enter second num:"))
f1 = float(x)
f2 = float(y)
if(x>y):
print("largest integer value",x)
else:
print("largest integer value",y)
if(f1>f2):
print("largest float value",f1)
else:
print("largest float value",f2)""" |
# Python - Object Oriented Programming
# In here we will use special methods, also called as Magic methods.
# Double underscore is called as dunder. We have seen dunder __init__ fuction
# we will see __repr__ and __str__ in here.
# we can also have custom dunder that we can create for performing certain
# tasks as functions.
class Employee:
raise_amt = 1.04
def __init__(self, firstName, lastName, pay):
self.firstName = firstName
self.lastName = lastName
self.pay = pay
self.email = f"{firstName}.{lastName}@Company.com"
def fullname(self):
return f"{self.firstName} {self.lastName}"
def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)
# __repr__ is a special method used to represent a class's objects as a string
def __repr__(self):
return f"Employee('{self.firstName}', '{self.lastName}', {self.pay})"
# The __str__ method should be defined in a way that is easy to read
# and outputs all the members of the class.
def __str__(self):
return f"{self.fullname()} - {self.email}"
# we can control the result of a sum of two objects by modifying or defying
# the __add__ method. Takes first object as Self and second as other.
def __add__(self, other):
return self.pay + other.pay
# __len__ as a method you can customize for any object
def __len__(self):
return len(self.fullname())
employee_1 = Employee("Tom", "Hanks", 50000)
employee_2 = Employee("Ricky", "Martin", 60000)
# Now when we print an object we get a string output
print(employee_1)
print(str(employee_1))
# The output is string representation of object.
print(repr(employee_1))
print(employee_1.__repr__())
print(employee_1.__str__())
# Returns combined pay of employee_1 and employee_2
print(employee_1 + employee_2)
# Returns length of full name
print(len(employee_1))
| class Employee:
raise_amt = 1.04
def __init__(self, firstName, lastName, pay):
self.firstName = firstName
self.lastName = lastName
self.pay = pay
self.email = f'{firstName}.{lastName}@Company.com'
def fullname(self):
return f'{self.firstName} {self.lastName}'
def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)
def __repr__(self):
return f"Employee('{self.firstName}', '{self.lastName}', {self.pay})"
def __str__(self):
return f'{self.fullname()} - {self.email}'
def __add__(self, other):
return self.pay + other.pay
def __len__(self):
return len(self.fullname())
employee_1 = employee('Tom', 'Hanks', 50000)
employee_2 = employee('Ricky', 'Martin', 60000)
print(employee_1)
print(str(employee_1))
print(repr(employee_1))
print(employee_1.__repr__())
print(employee_1.__str__())
print(employee_1 + employee_2)
print(len(employee_1)) |
# File: okta_consts.py
#
# Copyright (c) 2018-2022 Splunk Inc.
#
# 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.
OKTA_BASE_URL = "base_url"
OKTA_API_TOKEN = "api_key"
OKTA_PAGINATED_ACTIONS_LIST = [
'list_users', 'list_user_groups', 'list_providers', 'list_roles']
OKTA_RESET_PASSWORD_SUCC = "Successfully created one-time token for user to reset password"
OKTA_LIMIT_INVALID_MSG_ERR = "Please provide a valid positive integer value for 'limit' action parameter"
OKTA_LIMIT_NON_ZERO_POSITIVE_MSG_ERR = "Please provide a valid non-zero positive integer value for 'limit' action parameter"
OKTA_PAGINATION_MSG_ERR = "Error occurred while fetching paginated response for action: {action_name}. Error Details: {error_detail}"
OKTA_DISABLE_USER_SUCC = "Successfully disabled the user"
OKTA_ALREADY_DISABLED_USER_ERR = "User is already disabled"
OKTA_ENABLE_USER_SUCC = "Successfully enabled the user"
OKTA_ALREADY_ENABLED_USER_ERR = "User is already enabled"
OKTA_SET_PASSWORD_SUCC = "Successfully set user password"
OKTA_ASSIGN_ROLE_SUCC = "Successfully assigned role to user"
OKTA_ALREADY_ASSIGN_ROLE_ERR = "Role is already assigned to user"
OKTA_UNASSIGN_ROLE_SUCC = "Successfully unassigned role to user"
OKTA_ALREADY_UNASSIGN_ROLE_ERR = "Role is not assigned to user"
OKTA_ALREADY_ADDED_GROUP_ERR = "Group already added to organization"
OKTA_ADDED_GROUP_SUCCESS_MSG = "Group has been added successfully"
OKTA_GET_GROUP_SUCC = "Successfully retrieved group"
OKTA_GET_USER_SUCC = "Successfully retrieved user"
OKTA_TEST_CONNECTIVITY_FAILED = "Test Connectivity Failed"
OKTA_TEST_CONNECTIVITY_PASSED = "Test Connectivity Passed"
OKTA_INVALID_USER_MSG = "Please provide a valid user_id"
OKTA_CLEAR_USER_SESSIONS_SUCC = "Successfully cleared user sessions"
OKTA_SEND_PUSH_NOTIFICATION_ERR_MSG = "Please configure factor_type '{factor_type}' for the user '{user_id}'"
# DO NOT MODIFY!
# A fixed field used by Okta to the integration
OKTA_APP_USER_AGENT_BASE = "SplunkPhantom/"
UNEXPECTED_RESPONSE_MSG = "Unexpected response received"
# Constants relating to '_get_error_message_from_exception'
ERR_CODE_MSG = "Error code unavailable"
ERR_MSG_UNAVAILABLE = "Error message unavailable. Please check the asset configuration and|or action parameters"
PARSE_ERR_MSG = "Unable to parse the error message. Please check the asset configuration and|or action parameters"
TYPE_ERR_MSG = "Error occurred while connecting to the Okta Server. Please check the asset configuration and|or the action parameters"
# Constants relating to value_list check
FACTOR_TYPE_VALUE_LIST = ["push", "sms (not yet implemented)", "token:software:totp (not yet implemented)"]
RECEIVE_TYPE_VALUE_LIST = ["Email", "UI"]
IDENTITY_PROVIDERS_TYPE_VALUE_LIST = ["SAML2", "FACEBOOK", "GOOGLE", "LINKEDIN", "MICROSOFT"]
ROLE_TYPE_VALUE_LIST = [
"SUPER_ADMIN", "ORG_ADMIN", "API_ACCESS_MANAGEMENT_ADMIN", "APP_ADMIN", "USER_ADMIN", "MOBILE_ADMIN", "READ_ONLY_ADMIN",
"HELP_DESK_ADMIN", "GROUP_MEMBERSHIP_ADMIN", "REPORT_ADMIN"]
VALUE_LIST_VALIDATION_MSG = "Please provide valid input from {} in '{}' action parameter"
| okta_base_url = 'base_url'
okta_api_token = 'api_key'
okta_paginated_actions_list = ['list_users', 'list_user_groups', 'list_providers', 'list_roles']
okta_reset_password_succ = 'Successfully created one-time token for user to reset password'
okta_limit_invalid_msg_err = "Please provide a valid positive integer value for 'limit' action parameter"
okta_limit_non_zero_positive_msg_err = "Please provide a valid non-zero positive integer value for 'limit' action parameter"
okta_pagination_msg_err = 'Error occurred while fetching paginated response for action: {action_name}. Error Details: {error_detail}'
okta_disable_user_succ = 'Successfully disabled the user'
okta_already_disabled_user_err = 'User is already disabled'
okta_enable_user_succ = 'Successfully enabled the user'
okta_already_enabled_user_err = 'User is already enabled'
okta_set_password_succ = 'Successfully set user password'
okta_assign_role_succ = 'Successfully assigned role to user'
okta_already_assign_role_err = 'Role is already assigned to user'
okta_unassign_role_succ = 'Successfully unassigned role to user'
okta_already_unassign_role_err = 'Role is not assigned to user'
okta_already_added_group_err = 'Group already added to organization'
okta_added_group_success_msg = 'Group has been added successfully'
okta_get_group_succ = 'Successfully retrieved group'
okta_get_user_succ = 'Successfully retrieved user'
okta_test_connectivity_failed = 'Test Connectivity Failed'
okta_test_connectivity_passed = 'Test Connectivity Passed'
okta_invalid_user_msg = 'Please provide a valid user_id'
okta_clear_user_sessions_succ = 'Successfully cleared user sessions'
okta_send_push_notification_err_msg = "Please configure factor_type '{factor_type}' for the user '{user_id}'"
okta_app_user_agent_base = 'SplunkPhantom/'
unexpected_response_msg = 'Unexpected response received'
err_code_msg = 'Error code unavailable'
err_msg_unavailable = 'Error message unavailable. Please check the asset configuration and|or action parameters'
parse_err_msg = 'Unable to parse the error message. Please check the asset configuration and|or action parameters'
type_err_msg = 'Error occurred while connecting to the Okta Server. Please check the asset configuration and|or the action parameters'
factor_type_value_list = ['push', 'sms (not yet implemented)', 'token:software:totp (not yet implemented)']
receive_type_value_list = ['Email', 'UI']
identity_providers_type_value_list = ['SAML2', 'FACEBOOK', 'GOOGLE', 'LINKEDIN', 'MICROSOFT']
role_type_value_list = ['SUPER_ADMIN', 'ORG_ADMIN', 'API_ACCESS_MANAGEMENT_ADMIN', 'APP_ADMIN', 'USER_ADMIN', 'MOBILE_ADMIN', 'READ_ONLY_ADMIN', 'HELP_DESK_ADMIN', 'GROUP_MEMBERSHIP_ADMIN', 'REPORT_ADMIN']
value_list_validation_msg = "Please provide valid input from {} in '{}' action parameter" |
#
"""
Array addition
Have the function ArrayAddition(arr) take the array of numbers stored in arr and return the string true if any combination of numbers in the array (excluding the largest number) can be added up to equal the largest number in the array, otherwise return the string false. For example: if arr contains [4, 6, 23, 10, 1, 3] the output should return true because 4 + 6 + 10 + 3 = 23. The array will not be empty, will not contain all the same elements, and may contain negative numbers.
"""
#%%
# Solution seen from the internet but I fully understood it, https://www.geeksforgeeks.org/subset-sum-problem-dp-25/
#array = [ 4, 6, 23, 10, 1, 3]#True
#array = [ -1, -2, -1]#False
array = [3,5,-1,8,12]#True
def searchSum(arr, sumV, ind, maxV):
if sumV == maxV:
return True
elif sumV > maxV or ind >= len(arr):
#no point of continuing with this stack
return None
sumLinearly = searchSum(arr, sumV + arr[ind], ind + 1, maxV)
skipPoisition = searchSum(arr, sumV, ind + 1, maxV)
return sumLinearly or skipPoisition
def findingSuminArr(arr):
arr.sort()
maxV = arr.pop(-1)
arrLen = len(arr)
doesExist = searchSum(arr, 0, 0, maxV)
if doesExist == False or doesExist == None:
return False
return True
print(findingSuminArr(array))
# %%
| """
Array addition
Have the function ArrayAddition(arr) take the array of numbers stored in arr and return the string true if any combination of numbers in the array (excluding the largest number) can be added up to equal the largest number in the array, otherwise return the string false. For example: if arr contains [4, 6, 23, 10, 1, 3] the output should return true because 4 + 6 + 10 + 3 = 23. The array will not be empty, will not contain all the same elements, and may contain negative numbers.
"""
array = [3, 5, -1, 8, 12]
def search_sum(arr, sumV, ind, maxV):
if sumV == maxV:
return True
elif sumV > maxV or ind >= len(arr):
return None
sum_linearly = search_sum(arr, sumV + arr[ind], ind + 1, maxV)
skip_poisition = search_sum(arr, sumV, ind + 1, maxV)
return sumLinearly or skipPoisition
def finding_sumin_arr(arr):
arr.sort()
max_v = arr.pop(-1)
arr_len = len(arr)
does_exist = search_sum(arr, 0, 0, maxV)
if doesExist == False or doesExist == None:
return False
return True
print(finding_sumin_arr(array)) |
"""
1. Make a table value -> [index].
2. Make an empty set of the tuples (i, j, k)
3. For-loop through array. Pick two random elements. Test set for a third that completes the triplet (N^2)
4. Confirm i != j !=k, add to ret set. convert ret set to list and return it.
"""
class Solution:
def threeSum(self, nums): # len(nums) < 3000, so O(n^2) may be possible.
# Return all triples s.t. nums[i] + nums[j] + nums[k] = 0 and i,j,k are all distinct
valueToIndex = {}
for ind, number in enumerate(nums):
if number in valueToIndex:
valueToIndex[number].append(ind)
else:
valueToIndex[number] = [ind]
retSet = set()
for iV in valueToIndex:
for jV in valueToIndex:
if iV != jV:
lookingFor = -(iV + jV)
if lookingFor in valueToIndex:
for k in valueToIndex[lookingFor]:
if i != j and i != k and j != k:
numbers = [nums[i], nums[j], nums[k]]
numbers.sort()
retSet.add(tuple(numbers))
return [list(tup) for tup in retSet]
soln = Solution()
print(soln.threeSum([-1, 0, 1, 2, -1, -4])) | """
1. Make a table value -> [index].
2. Make an empty set of the tuples (i, j, k)
3. For-loop through array. Pick two random elements. Test set for a third that completes the triplet (N^2)
4. Confirm i != j !=k, add to ret set. convert ret set to list and return it.
"""
class Solution:
def three_sum(self, nums):
value_to_index = {}
for (ind, number) in enumerate(nums):
if number in valueToIndex:
valueToIndex[number].append(ind)
else:
valueToIndex[number] = [ind]
ret_set = set()
for i_v in valueToIndex:
for j_v in valueToIndex:
if iV != jV:
looking_for = -(iV + jV)
if lookingFor in valueToIndex:
for k in valueToIndex[lookingFor]:
if i != j and i != k and (j != k):
numbers = [nums[i], nums[j], nums[k]]
numbers.sort()
retSet.add(tuple(numbers))
return [list(tup) for tup in retSet]
soln = solution()
print(soln.threeSum([-1, 0, 1, 2, -1, -4])) |
class Node:
def __init__(self, dataval = None):
self.dataval = dataval
self.next = None
self.prev = None
def __str__(self):
return str(self.dataval)
class MyList:
def __init__(self):
self.first = None
self.last = None
def add(self, dataval):
if (self.first == None):
self.first = Node(dataval)
self.last = self.first
else:
temp = Node(dataval)
temp.next = self.first
self.first = temp
def index(self, item):
index = 0
while index < self.length():
if self.get(index).dataval == item:
return index
index += 1
return -1
def remove(self, item):
index = self.index(item)
if self.last == self.first:
self.last = None
self.first = None
elif index == 0:
temp = self.first.next
self.first.next = None
self.first = temp
elif index > 0:
oneBefore = self.get(index - 1)
temp = oneBefore.next
if self.last == temp:
self.last = oneBefore
oneBefore.next = temp.next
temp.next = None
def append(self, dataval):
if (self.first == None):
self.first = Node(dataval)
self.last = self.first
else:
newItem = Node(dataval)
self.last.next = newItem
newItem.prev = self.last
self.last = newItem
newItem.next = None
def get(self, index):
current = 0
if index >= self.length() and index < 0:
return None
item = self.first
while (current < index):
item = item.next
current += 1
return item
def __len__(self):
return self.length()
def isEmpty(self):
return self.first == None
def length(self):
result = 0
if (self.first == None):
return result
item = self.first
result += 1
while (item.next != None):
item = item.next
result += 1
return result
def pop(self):
last = self.last
self.remove(self.last.dataval)
return last
def __str__(self):
if (self.first == None):
return "empty"
result = str(self.first.__str__())
item = self.first
while (item.next != None):
item = item.next
result = str(result) + str(",") + str(item.__str__())
return result
| class Node:
def __init__(self, dataval=None):
self.dataval = dataval
self.next = None
self.prev = None
def __str__(self):
return str(self.dataval)
class Mylist:
def __init__(self):
self.first = None
self.last = None
def add(self, dataval):
if self.first == None:
self.first = node(dataval)
self.last = self.first
else:
temp = node(dataval)
temp.next = self.first
self.first = temp
def index(self, item):
index = 0
while index < self.length():
if self.get(index).dataval == item:
return index
index += 1
return -1
def remove(self, item):
index = self.index(item)
if self.last == self.first:
self.last = None
self.first = None
elif index == 0:
temp = self.first.next
self.first.next = None
self.first = temp
elif index > 0:
one_before = self.get(index - 1)
temp = oneBefore.next
if self.last == temp:
self.last = oneBefore
oneBefore.next = temp.next
temp.next = None
def append(self, dataval):
if self.first == None:
self.first = node(dataval)
self.last = self.first
else:
new_item = node(dataval)
self.last.next = newItem
newItem.prev = self.last
self.last = newItem
newItem.next = None
def get(self, index):
current = 0
if index >= self.length() and index < 0:
return None
item = self.first
while current < index:
item = item.next
current += 1
return item
def __len__(self):
return self.length()
def is_empty(self):
return self.first == None
def length(self):
result = 0
if self.first == None:
return result
item = self.first
result += 1
while item.next != None:
item = item.next
result += 1
return result
def pop(self):
last = self.last
self.remove(self.last.dataval)
return last
def __str__(self):
if self.first == None:
return 'empty'
result = str(self.first.__str__())
item = self.first
while item.next != None:
item = item.next
result = str(result) + str(',') + str(item.__str__())
return result |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.