content
stringlengths 7
1.05M
|
|---|
def even_odd(*args):
if "even" in args:
return list(filter(lambda x: x % 2 == 0, [args[i] for i in range(len(args) - 1)]))
return list(filter(lambda x: x % 2 == 1, [args[i] for i in range(len(args) - 1)]))
# print(even_odd(1, 2, 3, 4, 5, 6, "even"))
# print(even_odd(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "odd"))
|
# swift_build_support/build_graph.py ----------------------------*- python -*-
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
# ----------------------------------------------------------------------------
#
# This is a simple implementation of an acyclic build graph. We require no
# cycles, so we just perform a reverse post order traversal to get a topological
# ordering. We check during the reverse post order traversal that we do not
# visit any node multiple times.
#
# Nodes are assumed to be a product's class.
#
# ----------------------------------------------------------------------------
def _get_po_ordered_nodes(root, invertedDepMap):
# Then setup our worklist/visited node set.
worklist = [root]
visitedNodes = set([])
# TODO: Can we unify po_ordered_nodes and visitedNodes in some way?
po_ordered_nodes = []
# Until we no longer have nodes to visit...
while not len(worklist) == 0:
# First grab the last element of the worklist. If we have already
# visited this node, just pop it and skip it.
#
# DISCUSSION: Consider the following build graph:
#
# A -> [C, B]
# B -> [C]
#
# In this case, we will most likely get the following worklist
# before actually processing anything:
#
# A, C, B, C
#
# In this case, we want to ignore the initial C pushed onto the
# worklist by visiting A since we will have visited C already due to
# the edge from B -> C.
node = worklist[-1]
if node in visitedNodes:
worklist.pop()
continue
# Then grab the dependents of our node.
deps = invertedDepMap.get(node, set([]))
assert(isinstance(deps, set))
# Then visit those and see if we have not visited any of them. Push
# any such nodes onto the worklist and continue. If we have already
# visited all of our dependents, then we can actually process this
# node.
foundDep = False
for d in deps:
if d not in visitedNodes:
foundDep = True
worklist.append(d)
if foundDep:
continue
# Now process the node by popping it off the worklist, adding it to
# the visited nodes set, and append it to the po_ordered_nodes in
# its final position.
worklist.pop()
visitedNodes.add(node)
po_ordered_nodes.append(node)
return po_ordered_nodes
class BuildDAG(object):
def __init__(self):
self.root = None
# A map from a node to a list of nodes that depend on the given node.
#
# NOTE: This is an inverted dependency map implying that the root will
# be a "final element" of the graph.
self.invertedDepMap = {}
def add_edge(self, pred, succ):
self.invertedDepMap.setdefault(pred, set([succ])) \
.add(succ)
def set_root(self, root):
# Assert that we always only have one root.
assert(self.root is None)
self.root = root
def produce_schedule(self):
# Grab the root and make sure it is not None
root = self.root
assert(root is not None)
# Then perform a post order traversal from root using our inverted
# dependency map to compute a list of our nodes in post order.
#
# NOTE: The index of each node in this list is the post order number of
# the node.
po_ordered_nodes = _get_po_ordered_nodes(root, self.invertedDepMap)
# Ok, we have our post order list. We want to provide our user a reverse
# post order, so we take our array and construct a dictionary of an
# enumeration of the list. This will give us a dictionary mapping our
# product names to their reverse post order number.
rpo_ordered_nodes = list(reversed(po_ordered_nodes))
node_to_rpot_map = dict((y, x) for x, y in enumerate(rpo_ordered_nodes))
# Now before we return our rpo_ordered_nodes and our node_to_rpot_map, lets
# verify that we didn't find any cycles. We can do this by traversing
# our dependency graph in reverse post order and making sure all
# dependencies of each node we visit has a later reverse post order
# number than the node we are checking.
for n, node in enumerate(rpo_ordered_nodes):
for dep in self.invertedDepMap.get(node, []):
if node_to_rpot_map[dep] < n:
print('n: {}. node: {}.'.format(n, node))
print('dep: {}.'.format(dep))
print('inverted dependency map: {}'.format(self.invertedDepMap))
print('rpo ordered nodes: {}'.format(rpo_ordered_nodes))
print('rpo node to rpo number map: {}'.format(node_to_rpot_map))
raise RuntimeError('Found cycle in build graph!')
return (rpo_ordered_nodes, node_to_rpot_map)
def produce_scheduled_build(input_product_classes):
"""For a given a subset input_input_product_classes of
all_input_product_classes, compute a topological ordering of the
input_input_product_classes + topological closures that respects the
dependency graph.
"""
dag = BuildDAG()
worklist = list(input_product_classes)
visited = set(input_product_classes)
# Construct the DAG.
while len(worklist) > 0:
entry = worklist.pop()
deps = entry.get_dependencies()
if len(deps) == 0:
dag.set_root(entry)
for d in deps:
dag.add_edge(d, entry)
if d not in visited:
worklist.append(d)
visited = visited.union(deps)
# Then produce the schedule.
schedule = dag.produce_schedule()
# Finally check that all of our input_product_classes are in the schedule.
if len(set(input_product_classes) - set(schedule[0])) != 0:
raise RuntimeError('Found disconnected graph?!')
return schedule
|
pkgname = "python-sphinxcontrib-serializinghtml"
pkgver = "1.1.5"
pkgrel = 0
build_style = "python_module"
hostmakedepends = ["python-setuptools"]
checkdepends = ["python-sphinx"]
depends = ["python"]
pkgdesc = "Sphinx extension which outputs serialized HTML document"
maintainer = "q66 <q66@chimera-linux.org>"
license = "BSD-2-Clause"
url = "http://sphinx-doc.org"
source = f"$(PYPI_SITE)/s/sphinxcontrib-serializinghtml/sphinxcontrib-serializinghtml-{pkgver}.tar.gz"
sha256 = "aa5f6de5dfdf809ef505c4895e51ef5c9eac17d0f287933eb49ec495280b6952"
# circular checkdepends
options = ["!check"]
def post_install(self):
self.install_license("LICENSE")
|
"""
MIT License
Copyright (c) 2019 Michael Schmidt
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
class BinarySearchTree:
""" A basic binary search tree """
class _node:
""" A basic node object for trees """
def __init__(self, data):
""" Create a node with no children and just a data element
:data: object() Which implements relational <, >, == """
self.left = None
self.right = None
self.data = data
self.height = 1
def pre_order(self):
""" pre-order traversal generator function """
if self.data is not None:
yield self.data
if self.left:
for data in self.left.pre_order():
yield data
if self.right:
for data in self.right.pre_order():
yield data
def in_order(self):
""" in-order traversal generator function """
if self.left:
for data in self.left.in_order():
yield data
if self.data is not None:
yield self.data
if self.right:
for data in self.right.in_order():
yield data
def post_order(self):
""" post-order traversal generator function """
if self.left:
for data in self.left.post_order():
yield data
if self.right:
for data in self.right.post_order():
yield data
if self.data:
yield self.data
def __init__(self, data):
""" construct the root of the tree """
self.root = self._node(data)
self.size = 1
def __iter__(self):
""" return an in-order interator to the tree """
return self.root.in_order()
def __len__(self):
""" return the size of the tree """
return self.size
def find(self, data) -> bool:
""" Search tree to check if `data` is in tree
:data: object() Which implements <, >, ==
:returns: bool True if found, otherwise False """
return self._find(self.root, data)
def insert(self, data):
""" Insert an element into the tree
:data: object() Which implements <, >, == """
self._insert(self.root, data)
self.size += 1
def delete(self, data):
""" Public Method to remove data
:data: object() Which implements <, >, == """
self.root = self._delete(self.root, data)
self.size -= 1
def pre_order(self):
""" Public method which returns a generator for pre-order traversal """
for data in self.root.pre_order():
yield data
def in_order(self):
""" Public method which returns a generator for in-order traversal """
for data in self.root.in_order():
yield data
def post_order(self):
""" Public method which returns a generator for post-order traversal """
for data in self.root.post_order():
yield data
def _find(self, node, data) -> bool:
""" Hidden method for recursive search
:node: _node() root node of subtree
:data: object() which implements <, >, == """
if node:
if data == node.data:
return True
if data < node.data:
return self._find(node.left, data)
return self._find(node.right, data)
return False
def _insert(self, node, data):
""" Hidden method for recursive insert
:node: _node() root node of subtree
:data: object() which implements <, >, == """
if node.data is not None:
if data < node.data:
if node.left is None:
node.left = self._node(data)
else:
self._insert(node.left, data)
elif data > node.data:
if node.right is None:
node.right = self._node(data)
else:
self._insert(node.right, data)
else:
node.data = data
def _delete(self, node, data):
""" Hidden method for recursive _delete
:node: _node() root node of subtree
:data: object() which implements <, >, == """
if node is None:
return node
if data < node.data:
node.left = self._delete(node.left, data)
elif data > node.data:
node.right = self._delete(node.right, data)
else:
if node.left is None:
temp = node.right
node = None
return temp
if node.right is None:
temp = node.left
node = None
return temp
temp = self._get_minvalue_node(node.right)
node.key = temp.key
node.right = self._delete(node.right, temp.key)
return node
def _get_minvalue_node(self, node):
if node is None or node.left is None:
return node
return self._get_minvalue_node(node.left)
def _get_height(self, subtree):
""" Hidden method which returns the nodes height in the tree
:subtree: _node() Root node of a subtree """
if not subtree:
return 0
return subtree.height
class AVLTree(BinarySearchTree):
""" A self-balancing AVL tree """
def __init__(self, data):
""" Construct the root node
:data: object() Which implements relational <, >, == """
super(AVLTree, self).__init__(data)
def insert(self, data):
""" Public method for inserting data
:data: object() Which implements relational <, >, == """
self.root = self._insert(self.root, data)
self.size += 1
def delete(self, data):
""" Public method for recursive delete
Removes element and balances the tree
:data: object Which implements relational <, >, == """
self.root = self._delete(self.root, data)
self.size -= 1
def _insert(self, node, data) -> BinarySearchTree._node:
""" Hidden method for recursive insert
:node: _node() A tree node
:data: object Which implements relational <, >, ==
:returns: _node() a node (ultimately the new root) """
if not node:
return self._node(data)
if data < node.data:
node.left = self._insert(node.left, data)
else:
node.right = self._insert(node.right, data)
node.height = 1 + max(self._get_height(node.left), self._get_height(node.right))
balance = self._get_balance(node)
if balance > 1 and data < node.left.data:
return self._rotate_right(node)
if balance < -1 and data > node.right.data:
return self._rotate_left(node)
if balance > 1 and data > node.left.data:
node.left = self._rotate_left(node.left)
return self._rotate_right(node)
if balance < -1 and data < node.right.data:
node.right = self._rotate_right(node.right)
return self._rotate_left(node)
return node
def _delete(self, node, data):
""" Hidden method for recursive delete
:node: _node() A tree node
:data: object Which implements relational <, >, == """
if not node:
return node
if data < node.data:
node.left = self._delete(node.left, data)
elif data > node.data:
node.right = self._delete(node.right, data)
else:
if node.left is None:
temp = node.right
node = None
return temp
if node.right is None:
temp = node.left
node = None
return temp
temp = self._get_minvalue_node(node.right)
node.data = temp.data
node.right = self._delete(node.right, temp.data)
if node is None:
return node
node.height = 1 + max(self._get_height(node.left), self._get_height(node.right))
balance = self._get_balance(node)
if balance > 1 and self._get_balance(node.left) >= 0:
return self._rotate_right(node)
if balance < -1 and self._get_balance(node.right) <= 0:
return self._rotate_left(node)
if balance > 1 and self._get_balance(node.left) < 0:
node.left = self._rotate_left(node.left)
return self._rotate_right(node)
if balance < -1 and self._get_balance(node.right) > 0:
node.right = self._rotate_right(node.right)
return self._rotate_left(node)
return node
def _rotate_left(self, subtree):
""" Hidden method for left rotations
:subtree: _node() Root node of a subtree """
new_root = subtree.right
left = new_root.left
new_root.left = subtree
subtree.right = left
subtree.height = 1 + max(self._get_height(subtree.left), self._get_height(subtree.right))
new_root.height = 1 + max(self._get_height(new_root.left), self._get_height(new_root.right))
return new_root
def _rotate_right(self, subtree):
""" Hidden method for right rotations
:subtree: _node() Root node of a subtree """
new_root = subtree.left
right = new_root.right
new_root.right = subtree
subtree.left = right
subtree.height = 1 + max(self._get_height(subtree.left), self._get_height(subtree.right))
new_root.height = 1 + max(self._get_height(new_root.left), self._get_height(new_root.right))
return new_root
def _get_balance(self, subtree):
""" Hidden method which determines the tree balance
:subtree: _node() Root node of a subtree """
if not subtree:
return 0
return self._get_height(subtree.left) - self._get_height(subtree.right)
|
class Solution:
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
stack = []
index_stack = []
if len(s) <= 1:
return 0
dp = [0] * len(s)
for i in range(len(s)):
if s[i] == '(':
dp[i] = 0
stack.append(s[i])
index_stack.append(i)
continue
if len(stack) == 0:
dp[i] = 0
else:
if i - 1 >= 0:
if s[i - 1] == ')':
dp[i] = 1 + dp[i - 1]
else:
dp[i] = 1
stack = stack[0:-1]
p = index_stack[-1]
if len(index_stack) > 1:
index_stack = index_stack[0:-1]
else:
index_stack = []
if p - 1 >= 0:
dp[i] = dp[i] + dp[p - 1]
# p += 2
return max(dp) * 2
if __name__ == '__main__':
S = Solution()
a = S.longestValidParentheses(")(((((()())()()))()(()))(")
print(a)
|
lis = [1, 2, 3, 4, 2, 6, 7, 8, 9]
without_duplicates = []
ok = True
for i in range(0,len(lis)):
if lis[i] in without_duplicates:
ok = False
break
else:
without_duplicates.append(lis[i])
if ok:
print("There are no duplicates")
else:
print("Things are not ok")
|
# model settings
model = dict(
type='CenterNet2',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
norm_eval=True,
style='pytorch',
init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50')),
neck=dict(
type='FPN',
in_channels=[256, 512, 1024, 2048],
out_channels=256,
start_level=1,
add_extra_convs='on_output', # use P5
num_outs=5,
relu_before_extra_convs=True),
rpn_head=dict(
type='CenterNet2Head',
num_classes=80,
in_channels=256,
stacked_convs=4,
feat_channels=256,
not_norm_reg=True,
dcn_on_last_conv=False,
strides=[8, 16, 32, 64, 128],
regress_ranges=((0, 64), (64, 128), (128, 256), (256, 512), (512,
1e8)),
loss_hm=dict(
type='BinaryFocalLoss',
alpha=0.25,
beta=4,
gamma=2,
weight=0.5,
sigmoid_clamp=1e-4,
ignore_high_fp=0.85),
loss_bbox=dict(type='GIoULoss', reduction='mean', loss_weight=1.0)),
roi_head=dict(
type='CascadeRoIHead',
num_stages=3,
stage_loss_weights=[1, 0.5, 0.25],
mult_proposal_score=True,
bbox_roi_extractor=dict(
type='SingleRoIExtractor',
roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0),
out_channels=256,
featmap_strides=[8, 16, 32, 64, 128],
finest_scale=112),
bbox_head=[
dict(
type='Shared2FCBBoxHead',
in_channels=256,
fc_out_channels=1024,
roi_feat_size=7,
num_classes=80,
bbox_coder=dict(
type='DeltaXYWHBBoxCoder',
target_means=[0., 0., 0., 0.],
target_stds=[0.1, 0.1, 0.2, 0.2]),
reg_class_agnostic=True,
loss_cls=dict(
type='CrossEntropyLoss',
use_sigmoid=False,
loss_weight=1.0),
loss_bbox=dict(type='SmoothL1Loss', beta=1.0,
loss_weight=1.0)),
dict(
type='Shared2FCBBoxHead',
in_channels=256,
fc_out_channels=1024,
roi_feat_size=7,
num_classes=80,
bbox_coder=dict(
type='DeltaXYWHBBoxCoder',
target_means=[0., 0., 0., 0.],
target_stds=[0.05, 0.05, 0.1, 0.1]),
reg_class_agnostic=True,
loss_cls=dict(
type='CrossEntropyLoss',
use_sigmoid=False,
loss_weight=1.0),
loss_bbox=dict(type='SmoothL1Loss', beta=1.0,
loss_weight=1.0)),
dict(
type='Shared2FCBBoxHead',
in_channels=256,
fc_out_channels=1024,
roi_feat_size=7,
num_classes=80,
mult_proposal_score=True,
bbox_coder=dict(
type='DeltaXYWHBBoxCoder',
target_means=[0., 0., 0., 0.],
target_stds=[0.033, 0.033, 0.067, 0.067]),
reg_class_agnostic=True,
loss_cls=dict(
type='CrossEntropyLoss',
use_sigmoid=False,
loss_weight=1.0),
loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0))
]),
# training and testing settings
train_cfg=dict(
rpn=dict(
nms_pre=4000,
score_thr=0.0001,
min_bbox_size=0,
nms=dict(type='nms', iou_threshold=0.9),
max_per_img=2000),
rcnn=[
dict(
assigner=dict(
type='MaxIoUAssigner',
pos_iou_thr=0.6,
neg_iou_thr=0.6,
min_pos_iou=0.6,
match_low_quality=False,
ignore_iof_thr=-1),
sampler=dict(
type='RandomSampler',
num=512,
pos_fraction=0.25,
neg_pos_ub=-1,
add_gt_as_proposals=True),
pos_weight=-1,
debug=False),
dict(
assigner=dict(
type='MaxIoUAssigner',
pos_iou_thr=0.7,
neg_iou_thr=0.7,
min_pos_iou=0.7,
match_low_quality=False,
ignore_iof_thr=-1),
sampler=dict(
type='RandomSampler',
num=512,
pos_fraction=0.25,
neg_pos_ub=-1,
add_gt_as_proposals=True),
pos_weight=-1,
debug=False),
dict(
assigner=dict(
type='MaxIoUAssigner',
pos_iou_thr=0.8,
neg_iou_thr=0.8,
min_pos_iou=0.8,
match_low_quality=False,
ignore_iof_thr=-1),
sampler=dict(
type='RandomSampler',
num=512,
pos_fraction=0.25,
neg_pos_ub=-1,
add_gt_as_proposals=True),
pos_weight=-1,
debug=False)
]),
test_cfg=dict(
rpn=dict(
nms_pre=1000,
score_thr=0.0001,
min_bbox_size=0,
nms=dict(type='nms', iou_threshold=0.9),
max_per_img=256),
rcnn=dict(
score_thr=0.05,
nms=dict(type='nms', iou_threshold=0.7),
max_per_img=100)))
# dataset settings
dataset_type = 'CocoDataset'
data_root = 'data/coco/'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', with_bbox=True),
dict(
type='Resize',
img_scale=[(1333, 640), (1333, 672), (1333, 704), (1333, 736),
(1333, 768), (1333, 800)],
multiscale_mode='value',
keep_ratio=True),
dict(type='RandomFlip', flip_ratio=0.5),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']),
]
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='MultiScaleFlipAug',
img_scale=(1333, 800),
flip=False,
transforms=[
dict(type='Resize', keep_ratio=True),
dict(type='RandomFlip'),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img']),
])
]
data = dict(
samples_per_gpu=2,
workers_per_gpu=2,
train=dict(
type=dataset_type,
ann_file=data_root + 'annotations/instances_train2017.json',
img_prefix=data_root + 'train2017/',
pipeline=train_pipeline),
val=dict(
type=dataset_type,
ann_file=data_root + 'annotations/instances_val2017.json',
img_prefix=data_root + 'val2017/',
pipeline=test_pipeline),
test=dict(
type=dataset_type,
ann_file=data_root + 'annotations/instances_val2017.json',
img_prefix=data_root + 'val2017/',
pipeline=test_pipeline))
evaluation = dict(interval=9000, metric='bbox')
# optimizer
optimizer = dict(type='SGD', lr=0.02 / 8, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2))
# learning policy
lr_config = dict(
policy='step', warmup='linear', warmup_iters=500, step=[60000, 80000])
runner = dict(type='IterBasedRunner', max_iters=90000)
# runtime
checkpoint_config = dict(interval=9000)
# yapf:disable
log_config = dict(
interval=100,
hooks=[
dict(type='TextLoggerHook'),
# dict(type='TensorboardLoggerHook')
])
# yapf:enable
custom_hooks = [dict(type='NumClassCheckHook')]
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
workflow = [('train', 1)]
work_dir = 'outputs/CN2R50FPN'
seed = 0
gpu_ids = range(1)
|
""" Constants file for Auth0's seed project
"""
ACCESS_TOKEN_KEY = 'access_token'
API_ID = 'API_ID'
APP_JSON_KEY = 'application/json'
AUTH0_CLIENT_ID = 'uL61M0bVYCd72QwsrvGioOHotcRlqw35'
AUTH0_CLIENT_SECRET = '3dtMdBV5P4jtohyJCtwk0P0HBoOk_hv_oHYzEkYtHCOWjFR59MBBphTPIYf6tucz'
# AUTH0_CALLBACK_URL = 'http://127.0.0.1:5000/callback'
AUTH0_CALLBACK_URL = 'https://sustainable-roi.herokuapp.com/callback'
AUTH0_DOMAIN = 'capextool.auth0.com'
AUTHORIZATION_CODE_KEY = 'authorization_code'
CLIENT_ID_KEY = 'uL61M0bVYCd72QwsrvGioOHotcRlqw35'
CLIENT_SECRET_KEY = '3dtMdBV5P4jtohyJCtwk0P0HBoOk_hv_oHYzEkYtHCOWjFR59MBBphTPIYf6tucz'
CODE_KEY = 'code'
CONTENT_TYPE_KEY = 'content-type'
GRANT_TYPE_KEY = 'grant_type'
PROFILE_KEY = 'profile'
# REDIRECT_URI_KEY = 'http://127.0.0.1:5000/callback'
REDIRECT_URI_KEY = 'https://sustainable-roi.herokuapp.com/callback'
SECRET_KEY = 'ThisIsTheSecretKey'
|
# Copyright 2014 0xc0170
#
# 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 IARDefinitions():
def get_mcu_definition(self, name):
""" If MCU found, returns its definition dic, error otherwise. """
try:
return self.mcu_def[name]
except KeyError:
raise RuntimeError(
"Mcu was not recognized for IAR. Please check mcu_def dictionary.")
# MCU definitions which are currently supported. Add a new one, define a name as it is
# in IAR, create an empty project for that MCU, open the project file (ewp) in any text
# editor, find out the values of SelectEditMenu, CoreOrChip and FPU if
# it's not disabled (=0)
mcu_def = {
'LPC1768': {
'OGChipSelectEditMenu': {
'state': 'LPC1768 NXP LPC1768',
},
'OGCoreOrChip': {
'state': 1,
}
},
'MKL25Z128xxx4': {
'OGChipSelectEditMenu': {
'state': 'MKL25Z128xxx4 Freescale MKL25Z128xxx4',
},
'OGCoreOrChip': {
'state': 1,
}
},
'STM32F401xB': {
'OGChipSelectEditMenu': {
'state': 'STM32F401xB ST STM32F401xB',
},
'OGCoreOrChip': {
'state': 1,
},
'FPU': {
'state': 5,
},
},
}
iar_settings = {
'Variant': {
'state': 0,
},
'GEndianMode': { # [General Options][Target] Endian mode
'state': 0,
},
'Input variant': {
'version': 0,
'state': 0,
},
'Output variant': {
'state': 1,
},
'GOutputBinary': { # [General Options][Output] Executable or library
'state': 0, # 1 - library, 0 - executable
},
'FPU': {
'version': 2,
'state': 0,
},
'GRuntimeLibSelect': { # [General Options] Use runtime library
'version': 0,
'state': 0, # 0 - none, 1 - normal, 2 - full, 3 - custom
},
'GRuntimeLibSelectSlave': {
'version': 0,
'state': 0,
},
'GeneralEnableMisra': { # [General Options] Enable Misra-C
'state': 0,
},
'GeneralMisraVerbose': { # [General Options] Misra verbose
'state': 0,
},
'OGChipSelectEditMenu': { # [General Options] Select MCU (be aware, tabs are needed in some cases)
'state': 0,
},
'GenLowLevelInterface': { # [General Options] Use semihosting
# [General Options] 0 - none, 1 - semihosting, 2 - IAR breakpoint
'state': 0,
},
'GEndianModeBE': {
'state': 0,
},
'OGBufferedTerminalOutput': { # [General Options] Buffered terminal output
'state': 0,
},
'GenStdoutInterface': { # [General Options] Stdout/err
'state': 0, # [General Options] 0 - semihosting, 1 - SWD
},
'GeneralMisraVer': {
'state': 0,
},
'GFPUCoreSlave': {
'state': 0,
},
'GBECoreSlave': {
'state': 0,
},
'OGUseCmsis': { # [General Options][Lib configuration] Use CMSIS Lib
'state': 0,
},
'OGUseCmsisDspLib': { # [General Options][Lib configuration] Use CMSIS DSP Lib, only valid if CMSIS Lib is selected
'state': 0,
},
'CCPreprocFile': {
'state': 0,
},
'CCPreprocComments': {
'state': 0,
},
'CCPreprocLine': {
'state': 0,
},
'CCListCFile': { # [C/C++ Compiler][Output] Output list file
'state': 0,
},
'CCListCMnemonics': {
'state': 0,
},
'CCListCMessages': {
'state': 0,
},
'CCListAssFile': { # [C/C++ Compiler][Output] Output assembler file
'state': 0,
},
'CCListAssSource': {
'state': 0,
},
'CCEnableRemarks': {
'state': [],
},
'CCDiagSuppress': {
'state': '',
},
'CCDiagRemark': {
'state': '',
},
'CCDiagWarning': {
'state': '',
},
'CCDiagError': {
'state': '',
},
'CCObjPrefix': { # Generate object files for C/C++
'state': 1,
},
'CCAllowList': { # [C/C++ Compiler] Enable transformations (Optimizations)
'version': 1,
# Each bit is for one optimization settings. For example second bit
# is for loop unrolling
'state': 1111111,
},
'CCDebugInfo': { # [C/C++ Compiler] Generate debug information
'state': 1,
},
'IEndianMode': {
'state': 1,
},
'IProcessor': {
'state': 1,
},
'IExtraOptionsCheck': {
'state': 0,
},
'IExtraOptions': {
'state': 0,
},
'CCLangConformance': { # [C/C++ Compiler] Language conformance
# 0 - standard with IAR extensions, 1 - standard, 2 - strict
'state': 0,
},
'CCSignedPlainChar': { # [C/C++ Compiler] Plain char
'state': 1, # 0 - signed, 1 - unsigned
},
'CCRequirePrototypes': { # [C/C++ Compiler] Require prototypes
'state': 0,
},
'CCMultibyteSupport': {
'state': 0,
},
'CCCompilerRuntimeInfo': {
'state': 0,
},
'CCDiagWarnAreErr': {
'state': 0,
},
'IFpuProcessor': {
'state': 0,
},
'OutputFile': {
'state': '',
},
'CCLibConfigHeader': {
'state': 0,
},
'PreInclude': {
'state': 0,
},
'CompilerMisraOverride': {
'state': 0,
},
'CCStdIncCheck': {
'state': 0,
},
'CCCodeSection': {
'state': '.text',
},
'IInterwork2': {
'state': 0,
},
'IProcessorMode2': {
'state': 0,
},
'IInterwork2': {
'state': 0,
},
'CCOptLevel': { # [C/C++ Compiler] Optimization level
'state': 0, # 0 - None, 1 - Low, 2 - Medium , 3 - High
},
'CCOptStrategy': { # [C/C++ Compiler] Valid only for Optimization level High
'version': 0,
'state': 0, # 0 - Balanced, 1 - Size, 2 - Speed
},
'CCOptLevelSlave': {
'state': 0,
},
'CompilerMisraRules98': {
'version': 0,
'state': 0,
},
'CompilerMisraRules04': {
'version': 0,
'state': 0,
},
'CCPosIndRopi': { # [C/C++ Compiler][Code] Code and read-only data
'state': 0,
},
'IccLang': { # [C/C++ Compiler] C/C++ Language selection
'state': 0, # 0 - C, 1- C++, 2 - Auto
},
'CCPosIndNoDynInit': { # [C/C++ Compiler][Code]
'state': 0,
},
'CCPosIndRwpi': { # [C/C++ Compiler][Code] Read write/data
'state': 0,
},
'IccCDialect': { # [C/C++ Compiler] C dialect
'state': 1, # 0 - C89, 1 - C90
},
'IccAllowVLA': { # [C/C++ Compiler] Allow VLA (valid only for C99)
'state': 0,
},
'IccCppDialect': { # [C/C++ Compiler] C++ dialect
'state': 0, # 0 - Embedded C++, 1 - Extended embedded, 2 - C++
},
'IccExceptions': { # [C/C++ Compiler] With exceptions (valid only for C++ dialect 2)
'state': 0,
},
'IccRTTI': { # [C/C++ Compiler] With RTTI (valid only for C++ dialect 2)
'state': 0,
},
'IccStaticDestr': {
'state': 1,
},
'IccCppInlineSemantics': { # [C/C++ Compiler] C++ inline semantic (valid only for C99)
'state': 0,
},
'IccCmsis': {
'state': 1,
},
'IccFloatSemantics': { # [C/C++ Compiler] Floating point semantic
'state': 0, # 0 - strict, 1 - relaxed
},
'AObjPrefix': { # Generate object files for assembly files
'state': 1,
},
'AEndian': {
'state': 0,
},
'ACaseSensitivity': {
'state': 0,
},
'MacroChars': {
'state': 0,
},
'AWarnEnable': {
'state': 0,
},
'AWarnWhat': {
'state': 0,
},
'AWarnOne': {
'state': 0,
},
'AWarnRange1': {
'state': 0,
},
'AWarnRange2': {
'state': 0,
},
'ADebug': { # [Assembler] Generate debug info
'state': 0,
},
'AltRegisterNames': {
'state': 0,
},
'ADefines': { # [Assembler] Preprocessor - Defines
'state': '',
},
'AList': {
'state': 0,
},
'AListHeader': {
'state': 0,
},
'AListing': {
'state': 0,
},
'Includes': {
'state': '',
},
'MacDefs': {
'state': 0,
},
'MacExps': {
'state': 0,
},
'MacExec': {
'state': 0,
},
'OnlyAssed': {
'state': 0,
},
'MultiLine': {
'state': 0,
},
'PageLengthCheck': {
'state': 0,
},
'PageLength': {
'state': 0,
},
'TabSpacing': {
'state': 0,
},
'AXRefDefines': {
'state': 0,
},
'AXRef': {
'state': 0,
},
'AXRefInternal': {
'state': 0,
},
'AXRefDual': {
'state': 0,
},
'AProcessor': {
'state': 0,
},
'AFpuProcessor': {
'state': 0,
},
'AOutputFile': {
'state': 0,
},
'AMultibyteSupport': {
'state': 0,
},
'ALimitErrorsCheck': {
'state': 0,
},
'ALimitErrorsEdit': {
'state': 100,
},
'AIgnoreStdInclude': {
'state': 0,
},
'AUserIncludes': {
'state': '',
},
'AExtraOptionsCheckV2': {
'state': 0,
},
'AExtraOptionsV2': {
'state': 0,
},
'OOCOutputFormat': {
'state': 0,
},
'OCOutputOverride': {
'state': 0,
},
'OOCCommandLineProducer': {
'state': 0,
},
'OOCObjCopyEnable': {
'state': 1,
},
'IlinkOutputFile': {
'state': 0,
},
'IlinkLibIOConfig': {
'state': 0,
},
'XLinkMisraHandler': {
'state': 0,
},
'IlinkInputFileSlave': {
'state': 0,
},
'IlinkDebugInfoEnable': {
'state': 0,
},
'IlinkKeepSymbols': {
'state': 0,
},
'IlinkRawBinaryFile': {
'state': 0,
},
'IlinkRawBinarySymbol': {
'state': 0,
},
'IlinkRawBinarySegment': {
'state': 0,
},
'IlinkRawBinaryAlign': {
'state': 0,
},
'IlinkDefines': {
'state': 0,
},
'IlinkConfigDefines': {
'state': 0,
},
'IlinkMapFile': {
'state': 0,
},
'IlinkLogFile': {
'state': 0,
},
'IlinkLogInitialization': {
'state': 0,
},
'IlinkLogModule': {
'state': 0,
},
'IlinkLogSection': {
'state': 0,
},
'IlinkLogVeneer': {
'state': 0,
},
'IlinkIcfOverride': {
'state': 0,
},
'IlinkEnableRemarks': {
'state': 0,
},
'IlinkSuppressDiags': {
'state': 0,
},
'IlinkTreatAsRem': {
'state': 0,
},
'IlinkTreatAsWarn': {
'state': 0,
},
'IlinkTreatAsErr': {
'state': 0,
},
'IlinkWarningsAreErrors': {
'state': 0,
},
'IlinkUseExtraOptions': {
'state': 0,
},
'IlinkExtraOptions': {
'state': 0,
},
'IlinkLowLevelInterfaceSlave': {
'state': 0,
},
'IlinkAutoLibEnable': {
'state': 0,
},
'IlinkProgramEntryLabelSelect': {
'state': 0,
},
'IlinkProgramEntryLabel': {
'state': 0,
},
}
|
class Escritor:
def __init__(self, nome):
self.nome = nome
self.ferramenta = None
class Caneta:
def __init__(self, marca):
self.marca = marca
self.escrevendo = False
def escrever(self, nome=None):
if nome == None:
self.escrevendo = True
print(f"Caneta da marca {self.marca} está escrevendo.. ")
return
else:
self.escrevendo = True
print(f"{nome} está escrevendo com a caneta da marca {self.marca}")
return
def parar_escrever(self):
if self.escrevendo:
self.escrevendo = False
print("Parando de escrever...")
return
else:
print('Caneta já não está escrevendo')
class Maquina:
@staticmethod
def escrever():
print('Escrevendo..')
escritor = Escritor('José')
caneta = Caneta('Bic')
maquina = Maquina()
caneta.escrever()
caneta.parar_escrever()
# atributos de classe X podem receber um objeto Y, sendo assim,
# o atributo pode obter os métodos da classe do objeto Y
escritor.ferramenta = maquina
escritor.ferramenta.escrever()
escritor.ferramenta = caneta
escritor.ferramenta.escrever(escritor.nome)
|
aux = 0
num = int(input("Ingrese un numero entero positivo: "))
opc = int(input("1- Sumatoria, 2-Factorial: "))
if opc == 1:
for x in range(0,num+1):
aux = aux + x
print (aux)
elif opc == 2:
if num == 0:
print("1")
elif num > 0:
aux = 1
for x in range(1,num+1):
aux = aux*x
print (aux)
elif num < 0:
print("Se deberia haber ingresado un numero valido")
|
#Give a single command that computes the sum from Exercise R-1.6,relying
#on Python's comprehension syntax and the built-in sum function
n = int(input('please input an positive integer:'))
result = sum(i**2 for i in range(1,n) if i&1!=0)
print(result)
|
#!/usr/bin/env python3
#https://codeforces.com/problemset/problem/189/A
#n分为a,b,c三个长度; 求最常分法.
#典型DP: 递归/记忆化搜索容易些? 或者用更适合py的构建?
#或许用bfs/BFS? 但和bfs相比,DP只需一层层记录,所以还是更像DP
n,a,b,c = list(map(int,input().split())) #<4000
ss = set([a,b,c])
ii = 0
while min(ss)<n:
l = list(ss)
ss = set([i+j for i in l for j in [a,b,c]])
ii += 1
print(ss)
print(ii)
|
# coding=utf-8
"""
Exceptions for AVWX package
"""
class AVWXError(Exception):
"""Base AVWX exception"""
class AVWXRequestFailedError(AVWXError):
"""Raised when request failed"""
class StationNotFound(AVWXError):
"""
Raised when a ICAO station isn't found
"""
def __init__(self, icao: str) -> None:
msg = f'ICAO station not found on AVWX server: "{icao}"; you might want to try another one.'
super(StationNotFound, self).__init__(msg)
|
# Aula 24 - Desempacotamento de listas em Python
lista = ['Luiz', 'João', 'Maria', 'Marcos', 'Julia']
n1, n2, n3, n4, n5 = lista # A quantidade variveis tem que ser igual ao quantidad de elementos
print(n2)
v1, *outraLista, ultimoLista = lista # O restante dos valores da lista vai para uma nova lista, precisa usar '*'
# ultimoLista colocar esse variável por último após '*' na lista faz com que o ultmo valor da lista vai para ela
print(v1)
print(outraLista)
print(ultimoLista)
*outraLista2, v1, v2 = lista # * gera uma lista, como coloquei variáveis apos ele, cada uma delas pegará os ultimos valores
print(outraLista2)
print(v1)
print(v2)
n1, n2, *_ = lista # *_ não está se preocupando com o resto da lista, somente deseja pegar os valores inciais
|
"""https://www.educative.io/courses/grokking-the-coding-interview/xl2g3vxrMq3
"""
def find_string_anagrams(input_str: str, pattern: str) -> list[str]:
"""Find all anagrams of a specified pattern in the given string.
Anagram is actually a Permutation of a string.
For example, “abc” has the following six anagrams:
abc
acb
bac
bca
cab
cba
Complexity:
N = len(input_str)
M = len(pattern)
Time: O(N+M)
Space: O(N+M)
O(M) (for HashMap if `pattern` has ALL DISTINCT CHARACTERS)
+ O(N) (for result list if M==1 & `input_str` contains ONLY that char)
Returns:
Anagrams of `pattern` in `input_str`.
Examples:
>>> find_string_anagrams("ppqp", "pq")
['pq', 'qp']
>>> find_string_anagrams("abbcabc", "abc")
['bca', 'cab', 'abc']
>>> find_string_anagrams("aaaa", "a")
['a', 'a', 'a', 'a']
>>> find_string_anagrams("`not pattern`", "")
[]
>>> find_string_anagrams("", "`not `input_str`")
[]
>>> find_string_anagrams("a", "`len(pattern) > len(input_str)`")
[]
"""
## EDGE CASES ##
if not pattern or not input_str or len(pattern) > len(input_str):
return []
"""ALGORITHM"""
get_curr_win_size = lambda: window_end - window_start + 1
## INITIALIZE VARS ##
window_start, num_fully_matched_chars = 0, 0
# DS's/res
anagrams = []
pattern_char_count = {}
for c in pattern:
pattern_char_count[c] = pattern_char_count.get(c, 0) + 1
## SLIDING ##
for window_end in range(len(input_str)):
left_char, right_char = input_str[window_start], input_str[window_end]
## EXPANSION ##
if right_char in pattern_char_count: # pragma: no branch
pattern_char_count[right_char] -= 1 # Decrement the character count
if pattern_char_count[right_char] == 0:
num_fully_matched_chars += 1 # Increment the matched count
## WINDOW MATCH ##
if num_fully_matched_chars == len(pattern_char_count): # Anagram!
window_substr = input_str[window_start : window_end + 1]
anagrams.append(window_substr)
## CONTRACTION ##
if get_curr_win_size() == len(pattern):
if left_char in pattern_char_count: # pragma: no branch
if pattern_char_count[left_char] == 0:
num_fully_matched_chars -= 1 # Decrement the matched count
pattern_char_count[left_char] += 1 # Re-increment the character count
window_start += 1
return anagrams
|
def twoSum(self, n: List[int], target: int) -> List[int]:
N = len(n)
l = 0
r = N-1
while l<r:
s = n[l] + n[r]
if s == target:
return [l+1,r+1]
elif s < target:
l += 1
else:
r -= 1
|
# Copyright (c) 2020 vesoft inc. All rights reserved.
#
# This source code is licensed under Apache 2.0 License,
# attached with Common Clause Condition 1.0, found in the LICENSES directory.
def __bytes2ul(b):
return int.from_bytes(b, byteorder='little', signed=False)
def mmh2(bstr, seed=0xc70f6907, signed=True):
MASK = 2 ** 64 - 1
size = len(bstr)
m = 0xc6a4a7935bd1e995
r = 47
h = seed ^ (size * m & MASK)
end = size & (0xfffffff8)
for pos in range(0, end, 8):
k = __bytes2ul(bstr[pos:pos+8])
k = k * m & MASK
k = k ^ (k >> r)
k = k * m & MASK;
h = h ^ k
h = h * m & MASK
left = size & 0x7
if left >= 7:
h = h ^ (bstr[end+6] << 48)
if left >= 6:
h = h ^ (bstr[end+5] << 40)
if left >= 5:
h = h ^ (bstr[end+4] << 32)
if left >= 4:
h = h ^ (bstr[end+3] << 24)
if left >= 3:
h = h ^ (bstr[end+2] << 16)
if left >= 2:
h = h ^ (bstr[end+1] << 8)
if left >= 1:
h = h ^ bstr[end+0]
h = h * m & MASK
h = h ^ (h >> r)
h = h * m & MASK
h = h ^ (h >> r)
if signed:
h = h | (-(h & 0x8000000000000000))
return h
if __name__ == '__main__':
assert mmh2(b'hello') == 2762169579135187400
assert mmh2(b'World') == -295471233978816215
assert mmh2(b'Hello World') == 2146989006636459346
assert mmh2(b'Hello Wo') == -821961639117166431
|
"""
author : Ali Emre SAVAS
Link : https://www.hackerrank.com/challenges/py-check-subset/problem
"""
if __name__ == "__main__":
for _ in range(int(input())):
numberOfA = int(input())
setA = set(map(int, input().split()))
numberOfA = int(input())
setB = set(map(int, input().split()))
print(setA.issubset(setB))
|
def init(n,m):
state_initial = [n] + [1] * m
state_current = state_initial
state_final = [n] * (m + 1)
return state_initial, state_current, state_final
def valid_transition(currentState, tower_i, tower_j):
k = 0
t = 0
if tower_i == tower_j: # same tower not allowed
return False
for i in range(1,len(currentState)):
if currentState[i]==tower_i:
k = i
if k == 0:
return False
for j in range(1,len(currentState)):
if currentState[j]==tower_j:
t = j
if k > 0 and k < t:
return False
return True
def transition(currentState, tower_i, tower_j):
if valid_transition(currentState, tower_i, tower_j):
for i in range(1, len(currentState)):
if currentState[i] == tower_i:
k = i
currentState[k] = tower_j
return currentState
def is_final_state(currentState, n, m):
if currentState == [n] * (m + 1):
return True
return False
|
class Vector:
'''Vector class modeling Vectors'''
def __init__(self,initialise_param):
'''constructor:-create list of num length'''
if isinstance(initialise_param,(Vector,list)):
self._coords=[i for i in initialise_param]
elif isinstance(initialise_param,(int)):
if initialise_param<=0:
raise ValueError("bhai mat kar bhai mat kar chutiye")
else:
self._coords=[0]*initialise_param
def __len__(self):
return len(self._coords)
def __getitem__(self,j):
return self._coords[j]
def __setitem__(self,at_index,val):
self._coords[at_index]=val
def __add__(self,vector):
if len(self)!=len(vector):
raise ValueError("dimension of the vector must be same")
result=Vector(len(self))
for j in range(0,len(self)):
print(j)
print(self[j],vector[j])
result[j]=self[j]+vector[j]
return result
def __eq__(self,vector):
return True if vector == self else False
def __ne__(self,vector):
return not self==vector
def __str__(self):
return "<"+str(self._coords)[1:-1]+">"
def __sub__(self,vec):
if len(self)!=len(vec):
raise ValueError("both must have same dimension")
return
subtracted_vec=Vector(len(self))
for i in range(0,len(vec)):
subtracted_vec[i]=self[i]-vec[i]
return subtracted_vec
def __neg__(self):
neg_vector=Vector(len(self))
for i in range(0,len(self)):
neg_vector[i]=-1*self[i]
return neg_vector
# adding functionality to add list+vector return vector
def __mul__(self,multby_vec):
num=multby_vec
if isinstance(num,(int,float)):
vec=Vector(len(self))
for i in range(0,len(self)):
vec[i]=num*(self[i])
return vec
elif isinstance(multby_vec,list):
if len(self)!=len(multby_vec):
raise ValueError("must be of same length")
else:
dot_product=0
for i in range(0,len(multby_vec)):
dot_product+=multby_vec[i]*self[i]
return dot_product
def __radd__(self,add_list):
if len(self)!= len(add_list):
raise ValueError("must be of same length for valid operation")
new_vec=Vector(len(self))
for i in range(0,len(self)):
new_vec[i]=self[i]+add_list[i]
return new_vec
if __name__ == "__main__":
v1=Vector(3)
v2=Vector(3)
v1[2]=1
v2[1]=34
v3=v1+v2
print(v3)
v4=v3-v1
print("v3 is",v3,"\n v1 is \n",v1,"so the result after subtartion is ",v4)
print("after negating the values",-v4)
##ading list to vector adding functionality
v5=[1,2,3]+v4
print('adding lit to the elements []1,2,3]',v5)
## adding test of multiply operators
v6=v5*[1,2,3]# act as a dot product
print('multipled vector is',v6)
v6=v5*2
print(v6)
#v6=2*v5
print(v6)
# adding test for overriden Counstructors
new_vec=Vector([34,12,344,5])
print(new_vec)
|
def createList():
fruitsList = ["apple", "banana", "cherry"]
print("Fruit List : ", fruitsList)
# Iterate the list of fruits
for i in fruitsList:
print("Value : ", i)
# Add to fruits list
fruitsList.append("kiwi")
fruitsList.append("Grape")
fruitsList.append("Orange")
print("After adding furits now list ...")
for fruit in fruitsList:
print("Now Fruit : ", fruit)
# Delete a fruits from List
if fruitsList.__contains__("Grape"):
fruitsList.remove("Grape")
print("Fuits : ", fruitsList)
# Update a fruit, instead of apple, use Green Apple
for fruit in fruitsList:
value = fruit
if value == "apple":
# Find the index of apple
index = fruitsList.index("apple")
print("Index of Apple : ", index)
# Now update apple with Green Apple
fruitsList[index] = "Green Apple"
# finally print the details of the fruit list
print("Show all the updated fruits ...")
for fruit in fruitsList:
print(fruit, end="\t")
print("\n")
# Insert at the beginning of List
fruitsList.insert(0, "Laxman Phal") # Insert at the top
print("Inserted fruits : ", fruitsList)
# Insert at the last
fruitsList.append("Figs") # Insert at the last
print("Inserted at the end : ", fruitsList)
# Get the index in list of fruits
print("All the fruits with their indexes")
for fruit in fruitsList:
fruitIndex = fruitsList.index(fruit)
print(fruit, "<---->", fruitIndex)
#Sort a list
fruitsList.sort();
print("Sorted in Ascending order : ",fruitsList)
print("-------- In descending order ------")
fruitsList.sort(reverse = True)
print("Sorted in Descending order : ", fruitsList)
if __name__ == "__main__":
createList()
|
# Crie um programa que leia dois números e mostre a soma entre eles.
num1 = int(input('Digite o primeiro valor: '))
num2 = int(input('Digite o segundo valor: '))
soma = num1 + num2
print('O resultado da soma entre {} e {} é: {}'.format(num1, num2, soma))
|
class SlopeGradient:
def __init__(self, rightSteps, downSteps):
self.rightSteps = rightSteps
self.downSteps = downSteps
|
S = input()
is_no = False
for s in S:
if S.count(s) != 2:
is_no = True
break
if is_no:
print("No")
else:
print("Yes")
|
class WeekSchedule():
def __init__(self, dates=[], codes=[]):
self.weeknum = 0
self.dates = dates
self.codes = codes
|
a=10
print(type(a))
a='Python'
print(type(a))
a=False
print(type(a))
|
''' Code for training and evaluating Self-Explaining Neural Networks.
Copyright (C) 2018 David Alvarez-Melis <dalvmel@mit.edu>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License,
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
'''
|
# 1. Реализовать класс «Дата», функция-конструктор которого должна принимать
# дату в виде строки формата «день-месяц-год». В рамках класса реализовать
# два метода. Первый, с декоратором @classmethod, должен извлекать число,
# месяц, год и преобразовывать их тип к типу «Число». Второй, с декоратором
# @staticmethod, должен проводить валидацию числа, месяца и года (например,
# месяц — от 1 до 12). Проверить работу полученной структуры на реальных данных.
class Date:
def __init__(self, date_as_string):
self.date_as_string = date_as_string
@classmethod
def extract_numbers(cls, date):
return [int(number) for number in date.date_as_string.split('-')]
@staticmethod
def Validate(day, month, year):
if day not in [1,31]:
raise ValueError(f'Ошибка! Некорректное значения дня "{day}".')
elif month not in [1,12]:
raise ValueError(f'Ошибка! Некорректное значения месяца "{month}".')
elif year < 0:
raise ValueError(f'Ошибка! Некорректное значения года "{year}".')
my_date = Date('31-12-2012')
my_date_values = Date.extract_numbers(my_date)
print(my_date_values)
print(Date.Validate(my_date_values[0], my_date_values[1], my_date_values[2]))
|
nume1 = "Gabinete_Cooler_master"
nume2 = "Geforce_RTX_2080TI"
nume3 = (input("Digite uma peça"))
nume4 = (input("Digite uma peça"))
Carrinho = [nume1,nume2,nume3,nume4]
print(Carrinho)
Remove = int(input("Oh não! os preços estão altos demais!, deseja remover o gabinete e a placa de video? 1- sim 2-não"))
if Remove is 1:
del Carrinho[0,1]
print(Carrinho)
if Remove is 2 :
print("Você é rico!")
print(Carrinho)
|
load("@io_bazel_rules_docker//container:container.bzl", "container_pull")
def image_deps():
container_pull(
name = "python3.7",
digest = "sha256:57c7d7161fdaa79b61f107b8a480c50657d64dca37295d67db2f675abe38b45a",
registry = "index.docker.io",
repository = "library/python",
tag = "3.7.8",
)
|
#!/usr/bin/python
ADMIN_SCHEMA_FOLDER = "admin/schemas/"
ADMIN_SCHEMA_CHAR_SEPARATOR = "_"
ADD_COIN_METHOD = "addcoin"
GET_COIN_METHOD = "getcoin"
REMOVE_COIN_METHOD = "removecoin"
UPDATE_COIN_METHOD = "updatecoin"
|
class HandledEventArgs(EventArgs):
"""
Provides data for events that can be handled completely in an event handler.
HandledEventArgs()
HandledEventArgs(defaultHandledValue: bool)
"""
@staticmethod
def __new__(self,defaultHandledValue=None):
"""
__new__(cls: type)
__new__(cls: type,defaultHandledValue: bool)
"""
pass
Handled=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value that indicates whether the event handler has completely handled the event or whether the system should continue its own processing.
Get: Handled(self: HandledEventArgs) -> bool
Set: Handled(self: HandledEventArgs)=value
"""
|
# Ler dois números inteiros e compare eles
# mostrando na tela a mensagem:
# - o primeiro valor é maior
# - o segundo valor é maior
# não existe valor maior, os dois são iguais
n1 = int(input('Digite o primeiro número: '))
n2 = int(input('Digite o segundo número: '))
if n1 > n2:
print('O primeiro número é maior')
elif n2 > n1:
print('O segundo número é maior')
else:
print('Ambos os números são iguais')
|
exp_name = 'glean_ffhq_16x'
scale = 16
# model settings
model = dict(
type='GLEAN',
generator=dict(
type='GLEANStyleGANv2',
in_size=64,
out_size=1024,
style_channels=512,
pretrained=dict(
ckpt_path='http://download.openmmlab.com/mmgen/stylegan2/'
'official_weights/stylegan2-ffhq-config-f-official_20210327'
'_171224-bce9310c.pth',
prefix='generator_ema')),
discriminator=dict(
type='StyleGAN2Discriminator',
in_size=1024,
pretrained=dict(
ckpt_path='http://download.openmmlab.com/mmgen/stylegan2/'
'official_weights/stylegan2-ffhq-config-f-official_20210327'
'_171224-bce9310c.pth',
prefix='discriminator')),
pixel_loss=dict(type='MSELoss', loss_weight=1.0, reduction='mean'),
perceptual_loss=dict(
type='PerceptualLoss',
layer_weights={'21': 1.0},
vgg_type='vgg16',
perceptual_weight=1e-2,
style_weight=0,
norm_img=False,
criterion='mse',
pretrained='torchvision://vgg16'),
gan_loss=dict(
type='GANLoss',
gan_type='vanilla',
loss_weight=1e-2,
real_label_val=1.0,
fake_label_val=0),
pretrained=None,
)
# model training and testing settings
train_cfg = None
test_cfg = dict(metrics=['PSNR'], crop_border=0)
# dataset settings
train_dataset_type = 'SRAnnotationDataset'
val_dataset_type = 'SRAnnotationDataset'
train_pipeline = [
dict(type='LoadImageFromFile', io_backend='disk', key='lq'),
dict(type='LoadImageFromFile', io_backend='disk', key='gt'),
dict(type='RescaleToZeroOne', keys=['lq', 'gt']),
dict(
type='Normalize',
keys=['lq', 'gt'],
mean=[0.5, 0.5, 0.5],
std=[0.5, 0.5, 0.5],
to_rgb=True),
dict(
type='Flip', keys=['lq', 'gt'], flip_ratio=0.5,
direction='horizontal'),
dict(type='ImageToTensor', keys=['lq', 'gt']),
dict(type='Collect', keys=['lq', 'gt'], meta_keys=['lq_path', 'gt_path'])
]
test_pipeline = [
dict(type='LoadImageFromFile', io_backend='disk', key='lq'),
dict(type='LoadImageFromFile', io_backend='disk', key='gt'),
dict(type='RescaleToZeroOne', keys=['lq', 'gt']),
dict(
type='Normalize',
keys=['lq', 'gt'],
mean=[0.5, 0.5, 0.5],
std=[0.5, 0.5, 0.5],
to_rgb=True),
dict(type='ImageToTensor', keys=['lq', 'gt']),
dict(type='Collect', keys=['lq', 'gt'], meta_keys=['lq_path', 'gt_path'])
]
data = dict(
workers_per_gpu=8,
train_dataloader=dict(samples_per_gpu=4, drop_last=True), # 2 gpus
val_dataloader=dict(samples_per_gpu=1),
test_dataloader=dict(samples_per_gpu=1),
train=dict(
type='RepeatDataset',
times=1000,
dataset=dict(
type=train_dataset_type,
lq_folder='data/FFHQ/BIx16_down',
gt_folder='data/FFHQ/GT',
ann_file='data/FFHQ/meta_info_FFHQ_GT.txt',
pipeline=train_pipeline,
scale=scale)),
val=dict(
type=val_dataset_type,
lq_folder='data/CelebA-HQ/BIx16_down',
gt_folder='data/CelebA-HQ/GT',
ann_file='data/CelebA-HQ/meta_info_CelebAHQ_val100_GT.txt',
pipeline=test_pipeline,
scale=scale),
test=dict(
type=val_dataset_type,
lq_folder='data/CelebA-HQ/BIx16_down',
gt_folder='data/CelebA-HQ/GT',
ann_file='data/CelebA-HQ/meta_info_CelebAHQ_val100_GT.txt',
pipeline=test_pipeline,
scale=scale))
# optimizer
optimizers = dict(
generator=dict(type='Adam', lr=1e-4, betas=(0.9, 0.99)),
discriminator=dict(type='Adam', lr=1e-4, betas=(0.9, 0.99)))
# learning policy
total_iters = 300000
lr_config = dict(
policy='CosineRestart',
by_epoch=False,
periods=[300000],
restart_weights=[1],
min_lr=1e-7)
checkpoint_config = dict(interval=5000, save_optimizer=True, by_epoch=False)
evaluation = dict(interval=5000, save_image=False, gpu_collect=True)
log_config = dict(
interval=100,
hooks=[
dict(type='TextLoggerHook', by_epoch=False),
# dict(type='TensorboardLoggerHook'),
])
visual_config = None
# runtime settings
dist_params = dict(backend='nccl')
log_level = 'INFO'
work_dir = f'./work_dirs/{exp_name}'
load_from = None
resume_from = None
workflow = [('train', 1)]
find_unused_parameters = True
|
#1 Create countries dictionary
countries = __________________
#2 Print out the capital of egypt
print(__________________)
|
# -*- coding:utf-8 -*-
__author__ = [
'wufang'
]
|
"""Farmer classes.
:author: Someone
:email: someone@pnnl.gov
License: BSD 2-Clause, see LICENSE and DISCLAIMER files
"""
class FarmerOne:
"""This is the first Farmer agent.
:param age: Age of farmer
:type age: int
CLASS ATTRIBUTES:
:param AGE_MIN: Minimum age of a farmer
:type AGE_MIN: int
:param AGE_MAX: Maximum age of a farmer
:type AGE_MAX" int
"""
# minimum and maximum of acceptable farmer ages
AGE_MIN = 0
AGE_MAX = 150
def __init__(self, age):
self._age = age
@property
def age(self):
"""Age of farmer must be between expected age."""
if self._age > FarmerOne.AGE_MAX:
raise ValueError(f"FarmerOne age '{self._age}' is greater than allowable age of '{FarmerOne.AGE_MAX}'")
elif self._age < FarmerOne.AGE_MIN:
raise ValueError(f"FarmerOne age '{self._age}' is less than allowable age of '{FarmerOne.AGE_MIN}'")
else:
return self._age
|
# ------------------------------------------------------------------------------
# Access to the CodeHawk Binary Analyzer Analysis Results
# Author: Henny Sipma
# ------------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2016-2020 Kestrel Technology LLC
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ------------------------------------------------------------------------------
"""X86 CPU Register data."""
class AsmRegisterBase(object):
def __init__(self,bd,index,tags,args):
self.bd = bd
self.index = index
self.tags = tags
self.args = args
def is_cpu_register(self): return False
def is_segment_register(self): return False
def is_double_register(self): return False
def is_floating_point_register(self): return False
def is_control_register(self): return False
def is_debug_register(self): return False
def is_mmx_register(self): return False
def is_xmm_register(self): return False
def get_key(self):
return (','.join(self.tags), ','.join([str(x) for x in self.args]))
# ------------------------------------------------------------------------------
# CPURegister
# ------------------------------------------------------------------------------
class CPURegister(AsmRegisterBase):
def __init__(self,bd,index,tags,args):
AsmRegisterBase.__init__(self,bd,index,tags,args)
def is_cpu_register(self): return True
def __str__(self): return self.tags[1]
# ------------------------------------------------------------------------------
# SegmentRegister
# ------------------------------------------------------------------------------
class SegmentRegister(AsmRegisterBase):
def __init__(self,bd,index,tags,args):
AsmRegisterBase.__init__(self,bd,index,tags,args)
def is_segment_register(self): return True
def __str__(self): return self.tags[1]
# ------------------------------------------------------------------------------
# DoubleRegister
# ------------------------------------------------------------------------------
class DoubleRegister(AsmRegisterBase):
def __init__(self,bd,index,tags,args):
AsmRegisterBase.__init__(self,bd,index,tags,args)
def is_double_register(self): return True
def __str__(self): return self.tags[1] + ':' + self.tags[2]
# ------------------------------------------------------------------------------
# FloatingPointRegister
# ------------------------------------------------------------------------------
class FloatingPointRegister(AsmRegisterBase):
def __init__(self,bd,index,tags,args):
AsmRegisterBase.__init__(self,bd,index,tags,args)
def is_floating_point_register(self): return True
def get_index(self): return self.args[0]
def __str__(self): return 'st(' + str(self.get_index()) + ')'
# ------------------------------------------------------------------------------
# ControlRegister
# ------------------------------------------------------------------------------
class ControlRegister(AsmRegisterBase):
def __init__(self,bd,index,tags,args):
AsmRegisterBase.__init__(self,bd,index,tags,args)
def is_control_register(self): return True
def get_index(self): return self.args[0]
def __str__(self): return 'CR' + str(self.get_index())
# ------------------------------------------------------------------------------
# DebugRegister
# ------------------------------------------------------------------------------
class DebugRegister(AsmRegisterBase):
def __init__(self,bd,index,tags,args):
AsmRegisterBase.__init__(self,bd,index,tags,args)
def is_debug_register(self): return True
def get_index(self): return self.args[0]
def __str__(self): return 'DR' + str(self.get_index())
# ------------------------------------------------------------------------------
# MmxRegister
# ------------------------------------------------------------------------------
class MmxRegister(AsmRegisterBase):
def __init__(self,bd,index,tags,args):
AsmRegisterBase.__init__(self,bd,index,tags,args)
def is_mmx_register(self): return True
def get_index(self): return self.args[0]
def __str__(self): return 'mm(' + str(self.get_index()) + ')'
# ------------------------------------------------------------------------------
# XmmRegister
# ------------------------------------------------------------------------------
class XmmRegister(AsmRegisterBase):
def __init__(self,bd,index,tags,args):
AsmRegisterBase.__init__(self,bd,index,tags,args)
def is_xmm_register(self): return True
def get_index(self): return self.args[0]
def __str__(self): return 'xmm(' + str(self.get_index()) + ')'
|
"""hxlm.core.urn
Author: 2021, Emerson Rocha (Etica.AI) <rocha@ieee.org>
License: Public Domain / BSD Zero Clause License
SPDX-License-Identifier: Unlicense OR 0BSD
"""
# __all__ = [
# 'get_entrypoint_type'
# ]
# from hxlm.core.io.util import ( # noqa
# get_entrypoint_type
# )
|
"""
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity
O(n).
For example,
S = "ADOBECODEBANC"
T = "ABC"
Minimum window is "BANC".
Note:
If there is no such window in S that covers all characters in T, return the emtpy string "".
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
"""
__author__ = 'Danyang'
class Solution:
def minWindow(self, S, T):
"""
Algorithm:
two pointers
Aggressively enclose the chars until find all T, and then shrink the window as far as possible
:param S: str
:param T: str
:return: str
"""
min_window = [0, 1<<32] # [start, end)
w_chars = [0 for _ in range(256)] # window
T_CHARS = [0 for _ in range(256)] # 256 ascii, static
for char in T:
T_CHARS[ord(char)] += 1 # remain static after construction
appeared_cnt = 0
start_ptr = 0
for end_ptr in xrange(len(S)):
# expand
val = S[end_ptr]
if T_CHARS[ord(val)]>0:
w_chars[ord(val)] += 1
if T_CHARS[ord(val)]>0 and w_chars[ord(val)]<=T_CHARS[ord(val)]:
appeared_cnt += 1 # when to decrease appeared_cnt?
# shrink
if appeared_cnt==len(T): # until find all
# while w_chars[ord(S[start_ptr])]>T_CHARS[ord(S[start_ptr])] or w_chars[ord(S[start_ptr])]<=0:
while w_chars[ord(S[start_ptr])]>T_CHARS[ord(S[start_ptr])] or T_CHARS[ord(S[start_ptr])]<=0:
w_chars[ord(S[start_ptr])] -= 1 # if negative, it doesn't matter
start_ptr += 1
# after shrinking, still valid window
if min_window[1]-min_window[0]>end_ptr-start_ptr+1:
min_window[0], min_window[1] = start_ptr, end_ptr+1
if min_window[1]==1<<32:
return ""
else:
return S[min_window[0]:min_window[1]]
if __name__=="__main__":
assert Solution().minWindow("ADOBECODEBANC", "ABC")=="BANC"
|
a = int(input())
b = int(input())
def rectangle_area(a, b):
return '{:.0f}'.format(a * b)
print(rectangle_area(a, b))
|
# -*- coding: utf-8 -*-
"""
KM3NeT Data Definitions v2.0.0-9-gbae3720
https://git.km3net.de/common/km3net-dataformat
"""
# daqdatatypes
data = dict(
DAQSUPERFRAME=101,
DAQSUMMARYFRAME=201,
DAQTIMESLICE=1001,
DAQTIMESLICEL0=1002,
DAQTIMESLICEL1=1003,
DAQTIMESLICEL2=1004,
DAQTIMESLICESN=1005,
DAQSUMMARYSLICE=2001,
DAQEVENT=10001,
)
|
class Solution:
def minSteps(self, n: int) -> int:
res, m = 0, 2
while n > 1:
while n % m == 0:
res += m
n //= m
m += 1
return res
|
# Example, do not modify!
print(5 / 8)
# Put code below here
5 / 8
print( 7 + 10 )
# Just testing division
print(5 / 8)
# Addition works too.
print(7 + 10)
# Addition and subtraction
print(5 + 5)
print(5 - 5)
# Multiplication and division
print(3 * 5)
print(10 / 2)
# Exponentiation
print(4 ** 2)
# Modulo
print(18 % 7)
# How much is your $100 worth after 7 years?
print( 100 * 1.1 ** 7 )
# Create a variable savings
savings = 100
# Print out savings
print( savings )
# Create a variable savings
savings = 100
# Create a variable factor
factor = 1.10
# Calculate result
result = savings * factor ** 7
# Print out result
print( result )
# Create a variable desc
desc = "compound interest"
# Create a variable profitable
profitable = True
# Several variables to experiment with
savings = 100
factor = 1.1
desc = "compound interest"
# Assign product of factor and savings to year1
year1 = savings * factor
# Print the type of year1
print( type( year1 ) )
# Assign sum of desc and desc to doubledesc
doubledesc = desc + desc
# Print out doubledesc
print( doubledesc )
# Definition of savings and result
savings = 100
result = 100 * 1.10 ** 7
# Fix the printout
print("I started with $" + str(savings) + " and now have $" + str(result) + ". Awesome!")
# Definition of pi_string
pi_string = "3.1415926"
# Convert pi_string into float: pi_float
pi_float = float(pi_string)
|
# -*- coding: utf-8 -*-
name = 'smsapi-client'
version = '2.3.0'
lib_info = '%s/%s' % (name, version)
|
f = open('day6.txt', 'r')
data = f.read()
groups = data.split('\n\n')
answer = 0
for group in groups:
people = group.split('\n')
group_set = set(people[0])
for person in people:
group_set = group_set & set(person)
answer += len(group_set)
print(answer)
|
#!/bin/python3
def day12(lines):
registers = {'a': 0, 'b': 0, 'c': 1, 'd': 0}
i = 0
k = 0
while i < len(lines):
if k > 0:
i += 1
k -= 1
continue
line = lines[i].strip('\n').split(' ')
print('[%d, %d, %d, %d], %s' % (registers['a'],
registers['b'],
registers['c'],
registers['d'], line))
try:
x = registers[line[1]]
except KeyError:
x = int(line[1])
if line[0] == 'cpy':
registers[line[2]] = registers.get(line[1], x)
elif line[0] == 'inc':
registers[line[1]] += 1
elif line[0] == 'dec':
registers[line[1]] -= 1
elif line[0] == 'jnz' and x != 0:
jump = int(line[2])
if jump < 0:
i = max(i + jump, 0)
continue
else:
k += jump
continue
i += 1
return registers['a']
with open('aoc_day_12_input.txt') as f:
r = f.readlines()
print(day12(r))
|
"""Used to make pytest functions available globally"""
# Copyright (c) 2020 zfit
#
#
# def pytest_generate_tests(metafunc):
# if metafunc.config.option.all_jit_levels:
#
# # We're going to duplicate these tests by parametrizing them,
# # which requires that each test has a fixture to accept the parameter.
# # We can add a new fixture like so:
# metafunc.fixturenames.append('tmp_ct')
#
# # Now we parametrize. This is what happens when we do e.g.,
# # @pytest.mark.parametrize('tmp_ct', range(count))
# # def test_foo(): pass
# metafunc.parametrize('tmp_ct', range(2))
|
km = int(input('Qual a quantidade de km percorridos?'))
dias = int(input('Por quantos dias você alugou o carro?'))
pago = (dias * 60) + (km * 0.15)
print(f'O total do seu aluguel tem valor de R${pago :.2f}.')
|
mutables_test_text_001 = '''
def function(
param,
):
pass
'''
mutables_test_text_002 = '''
def function(
param=0,
):
pass
'''
mutables_test_text_003 = '''
def function(
param={},
):
pass
'''
mutables_test_text_004 = '''
def function(
param=[],
):
pass
'''
mutables_test_text_005 = '''
def function(
param=tuple(),
):
pass
'''
mutables_test_text_006 = '''
def function(
param=list(),
):
pass
'''
mutables_test_text_007 = '''
def function(
param_one,
param_two,
):
pass
'''
mutables_test_text_008 = '''
def function(
param_one,
param_two=0,
):
pass
'''
mutables_test_text_009 = '''
def function(
param_one,
param_two={},
):
pass
'''
mutables_test_text_010 = '''
def function(
param_one,
param_two=[],
):
pass
'''
mutables_test_text_011 = '''
def function(
param_one,
param_two=list(),
):
pass
'''
mutables_test_text_012 = '''
def function(
param_one,
param_two=tuple(),
):
pass
'''
mutables_test_text_013 = '''
def function(
param_one,
param_two,
param_three,
):
pass
'''
mutables_test_text_014 = '''
def function(
param_one,
param_two,
param_three=0,
):
pass
'''
mutables_test_text_015 = '''
def function(
param_one,
param_two=0,
param_three={},
):
pass
'''
mutables_test_text_016 = '''
def function(
param_one,
param_two=[],
param_three={},
):
pass
'''
mutables_test_text_017 = '''
def function(
param_one={},
param_two=0,
param_three={},
):
pass
'''
mutables_test_text_018 = '''
def function(
param_one=0,
param_two=[],
param_three=0,
):
pass
'''
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Solution:
def merge(self, nums1, m: int, nums2, n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
for i in range(m):
nums1[-1-i] = nums1[m-1-i]
i = 0
j = 0
k = 0
while i < m and j < n:
if nums1[-m+i] < nums2[j]:
nums1[k] = nums1[-m+i]
i += 1
else:
nums1[k] = nums2[j]
j += 1
k += 1
while i < m:
nums1[k] = nums1[-m+i]
i += 1
k += 1
while j < n:
nums1[k] = nums2[j]
j += 1
k += 1
if __name__ == "__main__":
s = Solution()
nums1 = [1, 2, 3, 0, 0, 0]
m = 3
nums2 = [2, 5, 6]
n = 3
s.merge(nums1, m, nums2, n)
print(nums1)
|
#
# PySNMP MIB module CISCO-ENTITY-FRU-CONTROL-CAPABILITY (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ENTITY-FRU-CONTROL-CAPABILITY
# Produced by pysmi-0.3.4 at Wed May 1 11:57:00 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)
#
ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsIntersection")
ciscoAgentCapability, = mibBuilder.importSymbols("CISCO-SMI", "ciscoAgentCapability")
AgentCapabilities, ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "AgentCapabilities", "ModuleCompliance", "NotificationGroup")
Integer32, iso, Unsigned32, Bits, ObjectIdentity, Gauge32, ModuleIdentity, TimeTicks, NotificationType, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, MibIdentifier, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "iso", "Unsigned32", "Bits", "ObjectIdentity", "Gauge32", "ModuleIdentity", "TimeTicks", "NotificationType", "Counter32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "MibIdentifier", "IpAddress")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
ciscoEntityFruControlCapability = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 7, 264))
ciscoEntityFruControlCapability.setRevisions(('2011-09-25 00:00', '2009-12-14 00:00', '2009-07-30 00:00', '2009-03-25 00:00', '2009-03-11 00:00', '2008-10-28 00:00', '2008-03-24 00:00', '2007-09-06 00:00', '2007-08-31 00:00', '2007-07-19 00:00', '2006-06-21 00:00', '2006-04-19 00:00', '2006-03-16 00:00', '2006-01-31 00:00', '2005-07-12 00:00', '2005-03-09 00:00', '2004-09-15 00:00', '2004-01-15 00:00', '2003-09-15 00:00', '2002-03-20 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: ciscoEntityFruControlCapability.setRevisionsDescriptions(('Added capabilities ciscoEfcCapV15R0001SYPCat6K.', 'Added capability ciscoEfcCapV15R01TP39XXE', 'Added capabilities for ciscoEfcCapV12R04TP3925E, and ciscoEfcCapV12R04TP3945E', 'Added capabilities for ciscoEfcCapV12R04TP3845nv, ciscoEfcCapV12R04TP3825nv, ciscoEfcCapV12R04TP1941, ciscoEfcCapV12R04TP29XX, ciscoEfcCapV12R04TP3925 and ciscoEfcCapV12R04TP3945', 'The capability statement ciscoEfcCapIOSXRV3R08CRS1 has been added.', 'Added capabilities ciscoEfcCapV12R0233SXIPCat6K.', 'The capability statement ciscoEfcCapIOSXRV3R06CRS1 has been added.', 'Added capabilities ciscoEfcCapabilityV12R05TP32xx for 3200 platform.', 'Added capabilities ciscoEfcCapV12R0233SXHPCat6K.', 'Added capabilities ciscoEfcCapabilityV05R05PMGX8850 for MGX8850 platform.', '- Added capabilities ciscoEfcCapV12R05TP18xx and ciscoEfcCapV12R05TP2801 for IOS 12.4T on platforms 18xx and 2801.', '- Added Agent capabilities ciscoEfcCapACSWV03R000 for Cisco Application Control Engine (ACE).', '- Add VARIATIONs for notifications cefcModuleStatusChange, cefcPowerStatusChange, cefcFRUInserted and cefcFRURemoved in ciscoEfcCapabilityCatOSV08R0101, ciscoEfcCapabilityCatOSV08R0301 and ciscoEfcCapCatOSV08R0501.', '- Added ciscoEfcCapSanOSV21R1MDS9000 for SAN OS 2.1(1) on MDS 9000 series devices. - Added ciscoEfcCapSanOSV30R1MDS9000 for SAN OS 3.0(1) on MDS 9000 series devices.', '- Added ciscoEfcCapCatOSV08R0501.', '- Added capabilities ciscoEfcCapV12R04TP26XX ciscoEfcCapV12R04TP28XX, ciscoEfcCapV12R04TP3725, ciscoEfcCapV12R04TP3745, ciscoEfcCapV12R04TP3825, ciscoEfcCapV12R04TP3845, ciscoEfcCapV12R04TPIAD243X, ciscoEfcCapV12R04TPVG224 for IOS 12.4T on platforms 26xx, 28xx, 37xx, 38xx, IAD243x, VG224', '- Added ciscoEfcCapabilityV12R03P5XXX for IOS 12.3 on Access Server Platforms (AS5350, AS5400 and AS5850).', '- Added ciscoEfcCapV12RO217bSXACat6K. - Added ciscoEfcCapabilityCatOSV08R0301.', '- Added ciscoEfcCapabilityV12R0119ECat6K for IOS 12.1(19E) on Catalyst 6000/6500 and Cisco 7600 series devices. - Added ciscoEfcCapabilityV12RO217SXCat6K for IOS 12.2(17SX) on Catalyst 6000/6500 and Cisco 7600 series devices. - Added ciscoEfcCapabilityCatOSV08R0101 for Cisco CatOS 8.1(1).', 'Initial version of the MIB Module. - The ciscoEntityFruControlCapabilityV2R00 is for MGX8850 and BPX SES platform. - The ciscoEntityFRUControlCapabilityV12R00SGSR is for GSR platform.',))
if mibBuilder.loadTexts: ciscoEntityFruControlCapability.setLastUpdated('201109250000Z')
if mibBuilder.loadTexts: ciscoEntityFruControlCapability.setOrganization('Cisco Systems, Inc.')
if mibBuilder.loadTexts: ciscoEntityFruControlCapability.setContactInfo('Cisco Systems Customer Service Postal: 170 W Tasman Drive San Jose, CA 95134 USA Tel: +1 800 553-NETS E-mail: cs-snmp@cisco.com cs-lan-switch-snmp@cisco.com')
if mibBuilder.loadTexts: ciscoEntityFruControlCapability.setDescription('The Agent Capabilities for CISCO-ENTITY-FRU-CONTROL-MIB.')
ciscoEntityFruControlCapabilityV2R00 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 1))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEntityFruControlCapabilityV2R00 = ciscoEntityFruControlCapabilityV2R00.setProductRelease('MGX8850 Release 2.00,\n BPX SES Release 1.00')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEntityFruControlCapabilityV2R00 = ciscoEntityFruControlCapabilityV2R00.setStatus('current')
if mibBuilder.loadTexts: ciscoEntityFruControlCapabilityV2R00.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB Capabilities')
ciscoEntityFRUControlCapabilityV12R00SGSR = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 2))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEntityFRUControlCapabilityV12R00SGSR = ciscoEntityFRUControlCapabilityV12R00SGSR.setProductRelease('Cisco IOS 12.0S for GSR')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEntityFRUControlCapabilityV12R00SGSR = ciscoEntityFRUControlCapabilityV12R00SGSR.setStatus('current')
if mibBuilder.loadTexts: ciscoEntityFRUControlCapabilityV12R00SGSR.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities for GSR platform.')
ciscoEfcCapabilityV12R0119ECat6K = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 3))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapabilityV12R0119ECat6K = ciscoEfcCapabilityV12R0119ECat6K.setProductRelease('Cisco IOS 12.1(19E) on Catalyst 6000/6500\n and Cisco 7600 series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapabilityV12R0119ECat6K = ciscoEfcCapabilityV12R0119ECat6K.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapabilityV12R0119ECat6K.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities.')
ciscoEfcCapabilityV12RO217SXCat6K = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 4))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapabilityV12RO217SXCat6K = ciscoEfcCapabilityV12RO217SXCat6K.setProductRelease('Cisco IOS 12.2(17SX) on Catalyst 6000/6500\n and Cisco 7600 series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapabilityV12RO217SXCat6K = ciscoEfcCapabilityV12RO217SXCat6K.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapabilityV12RO217SXCat6K.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities.')
ciscoEfcCapabilityCatOSV08R0101 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 5))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapabilityCatOSV08R0101 = ciscoEfcCapabilityCatOSV08R0101.setProductRelease('Cisco CatOS 8.1(1).')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapabilityCatOSV08R0101 = ciscoEfcCapabilityCatOSV08R0101.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapabilityCatOSV08R0101.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities.')
ciscoEfcCapV12RO217bSXACat6K = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 6))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12RO217bSXACat6K = ciscoEfcCapV12RO217bSXACat6K.setProductRelease('Cisco IOS 12.2(17b)SXA on Catalyst 6000/6500\n and Cisco 7600 series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12RO217bSXACat6K = ciscoEfcCapV12RO217bSXACat6K.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapV12RO217bSXACat6K.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities.')
ciscoEfcCapabilityCatOSV08R0301 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 7))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapabilityCatOSV08R0301 = ciscoEfcCapabilityCatOSV08R0301.setProductRelease('Cisco CatOS 8.3(1) on Catalyst 6000/6500\n and Cisco 7600 series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapabilityCatOSV08R0301 = ciscoEfcCapabilityCatOSV08R0301.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapabilityCatOSV08R0301.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities.')
ciscoEfcCapabilityV12R03P5XXX = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 8))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapabilityV12R03P5XXX = ciscoEfcCapabilityV12R03P5XXX.setProductRelease('Cisco IOS 12.3 for Access Server Platforms\n AS5350, AS5400 and AS5850.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapabilityV12R03P5XXX = ciscoEfcCapabilityV12R03P5XXX.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapabilityV12R03P5XXX.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities.')
ciscoEfcCapV12R04TP3725 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 9))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TP3725 = ciscoEfcCapV12R04TP3725.setProductRelease('Cisco IOS 12.4T for c3725 Platform')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TP3725 = ciscoEfcCapV12R04TP3725.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapV12R04TP3725.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities.')
ciscoEfcCapV12R04TP3745 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 10))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TP3745 = ciscoEfcCapV12R04TP3745.setProductRelease('Cisco IOS 12.4T for c3745 Platforms')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TP3745 = ciscoEfcCapV12R04TP3745.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapV12R04TP3745.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities')
ciscoEfcCapV12R04TP26XX = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 11))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TP26XX = ciscoEfcCapV12R04TP26XX.setProductRelease('Cisco IOS 12.4T for c26xx XM Platforms')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TP26XX = ciscoEfcCapV12R04TP26XX.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapV12R04TP26XX.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities')
ciscoEfcCapV12R04TPIAD243X = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 12))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TPIAD243X = ciscoEfcCapV12R04TPIAD243X.setProductRelease('Cisco IOS 12.4T for IAD 243x Platforms')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TPIAD243X = ciscoEfcCapV12R04TPIAD243X.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapV12R04TPIAD243X.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities')
ciscoEfcCapV12R04TPVG224 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 13))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TPVG224 = ciscoEfcCapV12R04TPVG224.setProductRelease('Cisco IOS 12.4T for VG224 Platform')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TPVG224 = ciscoEfcCapV12R04TPVG224.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapV12R04TPVG224.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities')
ciscoEfcCapV12R04TP2691 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 14))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TP2691 = ciscoEfcCapV12R04TP2691.setProductRelease('Cisco IOS 12.4T for c2691 Platform')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TP2691 = ciscoEfcCapV12R04TP2691.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapV12R04TP2691.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities')
ciscoEfcCapV12R04TP28XX = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 15))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TP28XX = ciscoEfcCapV12R04TP28XX.setProductRelease('Cisco IOS 12.4T for c28xx Platforms')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TP28XX = ciscoEfcCapV12R04TP28XX.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapV12R04TP28XX.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities')
ciscoEfcCapV12R04TP3825 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 16))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TP3825 = ciscoEfcCapV12R04TP3825.setProductRelease('Cisco IOS 12.4T for c3825 Platforms')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TP3825 = ciscoEfcCapV12R04TP3825.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapV12R04TP3825.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities')
ciscoEfcCapV12R04TP3845 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 17))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TP3845 = ciscoEfcCapV12R04TP3845.setProductRelease('Cisco IOS 12.4T for c3845 Platform')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TP3845 = ciscoEfcCapV12R04TP3845.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapV12R04TP3845.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities')
ciscoEfcCapCatOSV08R0501 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 18))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapCatOSV08R0501 = ciscoEfcCapCatOSV08R0501.setProductRelease('Cisco CatOS 8.5(1) on Catalyst 6000/6500\n and Cisco 7600 series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapCatOSV08R0501 = ciscoEfcCapCatOSV08R0501.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapCatOSV08R0501.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities.')
ciscoEfcCapSanOSV21R1MDS9000 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 19))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapSanOSV21R1MDS9000 = ciscoEfcCapSanOSV21R1MDS9000.setProductRelease('Cisco SanOS 2.1(1) on Cisco MDS 9000 series\n devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapSanOSV21R1MDS9000 = ciscoEfcCapSanOSV21R1MDS9000.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapSanOSV21R1MDS9000.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities.')
ciscoEfcCapSanOSV30R1MDS9000 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 20))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapSanOSV30R1MDS9000 = ciscoEfcCapSanOSV30R1MDS9000.setProductRelease('Cisco SanOS 3.0(1) on Cisco MDS 9000 series\n devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapSanOSV30R1MDS9000 = ciscoEfcCapSanOSV30R1MDS9000.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapSanOSV30R1MDS9000.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities.')
ciscoEfcCapACSWV03R000 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 21))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapACSWV03R000 = ciscoEfcCapACSWV03R000.setProductRelease('ACSW (Application Control Software) 3.0')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapACSWV03R000 = ciscoEfcCapACSWV03R000.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapACSWV03R000.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities.')
ciscoEfcCapV12R05TP18xx = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 22))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R05TP18xx = ciscoEfcCapV12R05TP18xx.setProductRelease('Cisco IOS 12.5T for c18xx Platform')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R05TP18xx = ciscoEfcCapV12R05TP18xx.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapV12R05TP18xx.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities')
ciscoEfcCapV12R05TP2801 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 23))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R05TP2801 = ciscoEfcCapV12R05TP2801.setProductRelease('Cisco IOS 12.5T for c2801 Platform')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R05TP2801 = ciscoEfcCapV12R05TP2801.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapV12R05TP2801.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities')
ciscoEfcCapabilityV05R05PMGX8850 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 24))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapabilityV05R05PMGX8850 = ciscoEfcCapabilityV05R05PMGX8850.setProductRelease('MGX8850 Release 5.5')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapabilityV05R05PMGX8850 = ciscoEfcCapabilityV05R05PMGX8850.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapabilityV05R05PMGX8850.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB Capabilities for the following modules of MGX8850: AXSM-XG, MPSM-T3E3-155, MPSM-16-T1E1, PXM1E, PXM45, VXSM and VISM.')
ciscoEfcCapV12R0233SXHPCat6K = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 25))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R0233SXHPCat6K = ciscoEfcCapV12R0233SXHPCat6K.setProductRelease('Cisco IOS 12.2(33)SXH on Catalyst 6000/6500\n series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R0233SXHPCat6K = ciscoEfcCapV12R0233SXHPCat6K.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapV12R0233SXHPCat6K.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities.')
ciscoEfcCapabilityV12R05TP32xx = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 26))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapabilityV12R05TP32xx = ciscoEfcCapabilityV12R05TP32xx.setProductRelease('Cisco IOS 12.5T for Cisco 3200 series routers')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapabilityV12R05TP32xx = ciscoEfcCapabilityV12R05TP32xx.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapabilityV12R05TP32xx.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities for 3220, 3250 and 3270 routers.')
ciscoEfcCapIOSXRV3R06CRS1 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 27))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapIOSXRV3R06CRS1 = ciscoEfcCapIOSXRV3R06CRS1.setProductRelease('Cisco IOS-XR Release 3.6 for CRS-1.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapIOSXRV3R06CRS1 = ciscoEfcCapIOSXRV3R06CRS1.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapIOSXRV3R06CRS1.setDescription('Agent capabilities for IOS-XR Release 3.6 for CRS-1.')
ciscoEfcCapV12R0233SXIPCat6K = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 28))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R0233SXIPCat6K = ciscoEfcCapV12R0233SXIPCat6K.setProductRelease('Cisco IOS 12.2(33)SXI on Catalyst 6000/6500\n series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R0233SXIPCat6K = ciscoEfcCapV12R0233SXIPCat6K.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapV12R0233SXIPCat6K.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities.')
ciscoEfcCapIOSXRV3R08CRS1 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 29))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapIOSXRV3R08CRS1 = ciscoEfcCapIOSXRV3R08CRS1.setProductRelease('Cisco IOS-XR Release 3.8 for CRS-1.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapIOSXRV3R08CRS1 = ciscoEfcCapIOSXRV3R08CRS1.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapIOSXRV3R08CRS1.setDescription('Agent capabilities for IOS-XR Release 3.8 for CRS-1.')
ciscoEfcCapV12R04TP3845nv = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 30))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TP3845nv = ciscoEfcCapV12R04TP3845nv.setProductRelease('Cisco IOS 12.4(22)YB1 for c3845nv Platform')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TP3845nv = ciscoEfcCapV12R04TP3845nv.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapV12R04TP3845nv.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities')
ciscoEfcCapV12R04TP3825nv = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 31))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TP3825nv = ciscoEfcCapV12R04TP3825nv.setProductRelease('Cisco IOS 12.4(22)YB1 for c3825nv Platforms')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TP3825nv = ciscoEfcCapV12R04TP3825nv.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapV12R04TP3825nv.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities')
ciscoEfcCapV12R04TP1941 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 32))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TP1941 = ciscoEfcCapV12R04TP1941.setProductRelease('Cisco IOS 12.4T for c1941 Platform')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TP1941 = ciscoEfcCapV12R04TP1941.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapV12R04TP1941.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities')
ciscoEfcCapV12R04TP29XX = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 33))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TP29XX = ciscoEfcCapV12R04TP29XX.setProductRelease('Cisco IOS 12.4T for c29xx Platforms')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TP29XX = ciscoEfcCapV12R04TP29XX.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapV12R04TP29XX.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities')
ciscoEfcCapV12R04TP3925 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 34))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TP3925 = ciscoEfcCapV12R04TP3925.setProductRelease('Cisco IOS 12.4T for c3925 Platforms')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TP3925 = ciscoEfcCapV12R04TP3925.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapV12R04TP3925.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities')
ciscoEfcCapV12R04TP3945 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 35))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TP3945 = ciscoEfcCapV12R04TP3945.setProductRelease('Cisco IOS 12.4T for c3945 Platform')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV12R04TP3945 = ciscoEfcCapV12R04TP3945.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapV12R04TP3945.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities')
ciscoEfcCapV15R01TP39XXE = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 36))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV15R01TP39XXE = ciscoEfcCapV15R01TP39XXE.setProductRelease('Cisco IOS 15.1T for c3925SPE200/c3925SPE250\n c3945SPE200/c3945SPE250 Platforms')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV15R01TP39XXE = ciscoEfcCapV15R01TP39XXE.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapV15R01TP39XXE.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities')
ciscoEfcCapV15R0001SYPCat6K = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 264, 37))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV15R0001SYPCat6K = ciscoEfcCapV15R0001SYPCat6K.setProductRelease('Cisco IOS 15.0(1)SY on Catalyst 6000/6500 \n series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEfcCapV15R0001SYPCat6K = ciscoEfcCapV15R0001SYPCat6K.setStatus('current')
if mibBuilder.loadTexts: ciscoEfcCapV15R0001SYPCat6K.setDescription('CISCO-ENTITY-FRU-CONTROL-MIB capabilities.')
mibBuilder.exportSymbols("CISCO-ENTITY-FRU-CONTROL-CAPABILITY", ciscoEfcCapV12R04TP3745=ciscoEfcCapV12R04TP3745, ciscoEfcCapV12R04TP3925=ciscoEfcCapV12R04TP3925, ciscoEfcCapV12RO217bSXACat6K=ciscoEfcCapV12RO217bSXACat6K, ciscoEfcCapV12R04TPIAD243X=ciscoEfcCapV12R04TPIAD243X, ciscoEfcCapV12R05TP2801=ciscoEfcCapV12R05TP2801, ciscoEfcCapIOSXRV3R08CRS1=ciscoEfcCapIOSXRV3R08CRS1, PYSNMP_MODULE_ID=ciscoEntityFruControlCapability, ciscoEfcCapabilityV12R0119ECat6K=ciscoEfcCapabilityV12R0119ECat6K, ciscoEfcCapACSWV03R000=ciscoEfcCapACSWV03R000, ciscoEfcCapV12R04TP2691=ciscoEfcCapV12R04TP2691, ciscoEfcCapV12R04TP1941=ciscoEfcCapV12R04TP1941, ciscoEfcCapV12R04TP28XX=ciscoEfcCapV12R04TP28XX, ciscoEfcCapSanOSV21R1MDS9000=ciscoEfcCapSanOSV21R1MDS9000, ciscoEntityFruControlCapability=ciscoEntityFruControlCapability, ciscoEfcCapV15R0001SYPCat6K=ciscoEfcCapV15R0001SYPCat6K, ciscoEfcCapabilityCatOSV08R0101=ciscoEfcCapabilityCatOSV08R0101, ciscoEfcCapV12R04TPVG224=ciscoEfcCapV12R04TPVG224, ciscoEfcCapV12R04TP3845=ciscoEfcCapV12R04TP3845, ciscoEfcCapCatOSV08R0501=ciscoEfcCapCatOSV08R0501, ciscoEfcCapV12R04TP26XX=ciscoEfcCapV12R04TP26XX, ciscoEfcCapabilityV05R05PMGX8850=ciscoEfcCapabilityV05R05PMGX8850, ciscoEfcCapV12R04TP3725=ciscoEfcCapV12R04TP3725, ciscoEfcCapV12R04TP3825=ciscoEfcCapV12R04TP3825, ciscoEntityFRUControlCapabilityV12R00SGSR=ciscoEntityFRUControlCapabilityV12R00SGSR, ciscoEfcCapSanOSV30R1MDS9000=ciscoEfcCapSanOSV30R1MDS9000, ciscoEfcCapV12R0233SXHPCat6K=ciscoEfcCapV12R0233SXHPCat6K, ciscoEfcCapV15R01TP39XXE=ciscoEfcCapV15R01TP39XXE, ciscoEfcCapIOSXRV3R06CRS1=ciscoEfcCapIOSXRV3R06CRS1, ciscoEfcCapV12R05TP18xx=ciscoEfcCapV12R05TP18xx, ciscoEfcCapabilityV12RO217SXCat6K=ciscoEfcCapabilityV12RO217SXCat6K, ciscoEfcCapV12R04TP29XX=ciscoEfcCapV12R04TP29XX, ciscoEfcCapV12R04TP3945=ciscoEfcCapV12R04TP3945, ciscoEfcCapV12R0233SXIPCat6K=ciscoEfcCapV12R0233SXIPCat6K, ciscoEfcCapabilityV12R05TP32xx=ciscoEfcCapabilityV12R05TP32xx, ciscoEfcCapV12R04TP3825nv=ciscoEfcCapV12R04TP3825nv, ciscoEntityFruControlCapabilityV2R00=ciscoEntityFruControlCapabilityV2R00, ciscoEfcCapabilityV12R03P5XXX=ciscoEfcCapabilityV12R03P5XXX, ciscoEfcCapabilityCatOSV08R0301=ciscoEfcCapabilityCatOSV08R0301, ciscoEfcCapV12R04TP3845nv=ciscoEfcCapV12R04TP3845nv)
|
#!/usr/bin/env python
""" Imprimir matriz
Escreva uma função imprime_matriz(matriz),
que recebe uma matriz como parâmetro e imprime a matriz,
linha por linha.
Note que NÃO se deve imprimir espaços após o último elemento de cada linha!
Exemplos:
minha_matriz = [[1], [2], [3]]
imprime_matriz(minha_matriz)
* 1
* 2
* 3
minha_matriz = [[1, 2, 3], [4, 5, 6]]
imprime_matriz(minha_matriz)
* 1 2 3
* 4 5 6
"""
def imprime_matriz(minha_matriz):
line = len(minha_matriz)
colunm = len(minha_matriz[0])
for i in range(line):
for j in range(colunm):
if (j != (colunm-1)) :
print(minha_matriz[i][j],end=' ')
else :
print(minha_matriz[i][j])
if __name__ == "__main__":
minha_matriz = [[1, 2, 3],
[4, 5, 6]]
imprime_matriz(minha_matriz)
|
"""
Eventually we'll probably want to add some decent serialization support.
For now - this is a pass through. Patches accepted :)
"""
class Serializer(object):
def serialize(cls, obj):
return obj
def is_valid(self):
return True
|
"""
Implement a Queue by linked list. Support the following basic methods:
1.enqueue(item). Put a new item in the queue.
2.dequeue(). Move the first item out of the queue, return it.
Example 1:
Input:
enqueue(1)
enqueue(2)
enqueue(3)
dequeue() // return 1
enqueue(4)
dequeue() // return 2
Solution:
做一些必要的初始化,在 MyQueue 类的 __init__() 中维护一个链表,注意在链表长度为1时 dequeue 之后需要重置 tail (此时 tail == None)
"""
class Node:
def __init__(self, _val):
self.val = _val
self.next = None
class MyQueue:
def __init__(self):
self.head = Node(0)
self.tail = self.head
self.size = 0
"""
@param: item: An integer
@return: nothing
"""
def enqueue(self, item):
# write your code here
node = Node(item)
self.tail.next = node
self.tail = self.tail.next
self.size += 1
"""
@return: An integer
"""
def dequeue(self):
# write your code here
if self.size < 1:
return None
res = self.head.next.val
self.head.next = self.head.next.next
self.size -= 1
if self.size == 0:
self.tail = self.head # self.tail == None, need to reset
return res
|
name = "openimageio"
version = "2.0.0"
authors = [
"Larry Gritz"
]
description = \
"""
OpenImageIO is a library for reading and writing images, and a bunch of
related classes, utilities, and applications.
"""
private_build_requires = [
'cmake-3.2.2+',
"boost-1.55",
"gcc-4.8.2+",
"opencolorio-1.0.9",
"ilmbase-2.2",
'openexr-2.2',
'ptex'
]
requires = [
'qt-4.8+<5',
'python-2.7'
]
variants = [
["platform-linux", "arch-x86_64", "os-CentOS-7", "python-2.7"]
]
tools = [
"iconvert",
"idiff",
"igrep",
"iinfo",
"maketx",
"oiiotool"
]
uuid = "openimageio"
def commands():
env.PATH.append("{root}/bin")
env.LD_LIBRARY_PATH.append("{root}/lib")
env.PYTHONPATH.append("{root}/lib/python/site-packages")
if building:
env.CPATH.append('{root}/include')
env.LIBRARY_PATH.append('{root}/lib')
|
def finan():
i = 0
tot_renda = 0
print('Ok mas antes de financiar preciso de algumas informações')
pess_rend = int(input('Quantas pessoas possuem renda na sua casa?'))
while pess_rend > i: #tem que usar 'for' porque se não fica no looping infinito
rend_familia = int(input('Valor da renda do membro:'))
tot_renda = (tot_renda + rend_familia) #nesta linha enquanto esta dentro do while o programa vai somando a renda dos familiares
temp_serv = int(input('Quanto tempo de serviço você tem ?: '))
print('O total de renda familiar é R${:.2f}'.format(tot_renda))
print('Bem vindo ao financiamento online (cuidado com o que você coloca neste campo meu jovem)')
#no caso abaixo eu não sei trabalhar muito bem com booleanos mas vou tentar usar neste caso para o if
print('O que você pretende financiar?')
print('{1} - Imóveis {2} - Automóveis {3} - Nada vim aqui por engano')
escolha = int(input('Bora rapaz diga: '))
if (escolha == 1) or (escolha == 2):
val_fin = int(input('Digite o valor do Financiamento: '))
val_entrada = int(input('Digite o valor de entrada: '))
temp_fin = int(input('Digite o tempo de financiamento: '))
tot_fin = ((val_fin-val_entrada)* 1.8) #calculo juros do financiamento
val_par = (tot_fin/temp_fin) #calculo valor da parcela
rend = ((tot_renda*40)/100) #calculo porcentagem renda familiar
val_tot = (val_fin - val_entrada) #calculo falor do financiamento
if (tot_fin < rend) or (temp_serv <= 3):
print('Valor de financiamento não aprovado pelo sistema')
elif (tot_fin > rend) or (temp_serv > 3):
print('Parabéns o Banco Gringotes aprova o seu financiamento!')
else:
print('Algo no seu financiamento está errado')
else:
print('Obrigado por utilizar o Banco Gringotes')
|
"""
57 / 57 test cases passed.
Runtime: 104 ms
Memory Usage: 14.9 MB
"""
class Solution:
def largestTriangleArea(self, points: List[List[int]]) -> float:
def triangleArea(x1, y1, x2, y2, x3, y3):
return abs(x1 * y2 + x2 * y3 + x3 * y1 - x1 * y3 - x2 * y1 - x3 * y2) / 2
return max(triangleArea(x1, y1, x2, y2, x3, y3) for (x1, y1), (x2, y2), (x3, y3) in combinations(points, 3))
|
#
# @lc app=leetcode.cn id=1 lang=python3
#
# [1] 两数之和
#
# @lc code=start
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashmap = {}
for i, num in enumerate(nums):
if hashmap.get(target - num) is not None:
return [hashmap.get(target - num), i]
hashmap[num] = i
# @lc code=end
|
class User:
user_list = []
def __init__(self,f_name,l_name,password):
"""function that creates user object"""
self.f_name = f_name
self.l_name = l_name
self.password = password
def save_user(self):
"""function that saves users"""
User.user_list.append(self)
def delete_user(self):
"""function that deletes users"""
User.user_list.remove(self)
@classmethod
def display_user(self):
"""function that displays users"""
return User.user_list
@classmethod
def find_user_by_name(cls,name):
"""function that finds users by name"""
for user in cls.user_list:
if user.f_name == name:
return user
@classmethod
def user_exist(cls,f_name):
"""function that checks if users exists"""
for user in cls.user_list:
if user.f_name == f_name:
return True
return False
class Credentials:
def __init__ (self,user_name, credential_name , credential__password):
"""function that creates credentials"""
self.user_name = user_name
self.credential_name =credential_name
self.credential_password =credential__password
list_of_credentials = []
def save_credentials(self):
"""function that saves credentials"""
self.list_of_credentials.append(self)
def delete_credentials(self):
"""function that deletes credentials"""
Credentials.list_of_credentials.remove(self)
@classmethod
def find_by_name(cls, user_name):
"""Method that takes in a name and returns a credential that matches that particular name
Args:
name: account_name that has a password
Returns:
The account_name and it's corresponding PassWord
"""
for credential in cls.list_of_credentials:
if credential.user_name == user_name:
return credential
@classmethod
def credential_exists(cls,name):
"""function that checks if credentials exists"""
for credential in cls.list_of_credentials:
if credential.user_name == name:
return True
@classmethod
def display_all_credentials(cls):
"""function that displays Credentials"""
return cls.list_of_credentials
|
# validated: 2018-01-14 DV a68a0c3ebf0b libraries/driver/include/ctre/phoenix/MotorControl/Faults.h
__all__ = ['FaultsBase']
class FaultsBase:
fields = []
def __init__(self, bits = 0):
mask = 1
for field in self.fields:
setattr(self, field, bool(bits & mask))
mask <<= 1
def toBitfield(self):
retval = 0
mask = 1
for field in self.fields:
if getattr(self, field):
retval |= mask
mask <<= 1
return retval
def hasAnyFault(self):
return any([getattr(self, field) for field in self.fields])
def __str__(self):
return " ".join(["%s:%s" % (field, int(getattr(self,field))) for field in self.fields])
|
# Databricks notebook source
HLRIOWYITKFDP
GOQFOEKSZNF
BQRYZYCEYRHRVDKCQSN
BELVHHTEWWKFYTNTWJIIYUQTBHUMOCJNDBBIPBOVCDIKTUPVXZRIUC
AUVGECGGHDZPJPMFEZWDFYYDXYGEMHXRHYXXGEMXTCZOPGPGSRCIQNPHCUONPPCBOWTFOZEYCXCQKKUNDSXSBAKSMWIPUKICUWX
HDCWKJXOZHPPXWBBPLIGLXMBATYPTDTCAACKEEWURDREVIIUPRJXDFNDLSHBZEBMWQOMYFWARMGERQAXVLFREGTYUXPABORSDUP
XPSNALKIEEH
TNRJVKVUADXUMYRVMHWANRYEQXHWTJQWRWKSYUM
JZXPNGKLOBUHKSQBTCTPEDKMXFIBBGGHRJQHBBORPGAUUQJRVXCIPMMFYYLRYN
KGQOIYGOLOQKPGZJQOZBYIDIZHPVDGNQIBWMZKLFVEICEQCZJBCOJNRCFYZBKW
XUCXWMRZSJZGGPF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QOZJTUJEEANTNEINJZKE
FKEIGQOIZREFLTLFOIJNOWKXBNEOTAWXUOFJNOQDHWPLCHXCZOJJEXBVISOAWMKWNF
CFMEUOWFOIGOKVAUAAEFTREATXGHSXAHWDMLFJWGSDPCRPDLLDGTUEWDPWTOSIWAJBMRMIGCXPRKDDLQN
NYCZPLFBNFCEOQNMDERNLXFHVFPRBGB
NGFPWVKYWHFAZROCPCIQGOMKFRQVKCNRJCSBPLLDURZLLFVPVHDHLZGYCSNMFVOFDLR
# COMMAND ----------
UKZXZUEPDEPUJMJPKLZZHMJGNWHBVCMRHEDUSDBOBWVSTHIYFRKOIBKVORNRLGCUPKSXQLNRWJPRBRII
ASQHRUROYUSINQWRBDTXJUSOKOBZACFFAWDWEREVAUCLILARUWYHKULERWCTZAUJFQ
FWHFQOMZGEMRZZSCJAZJPTICZZUVORFEERPPQMBACIGCOMTRIWRIEKXVHBFBVDKZTINQNZAJKLBWVJMWO
LRDLGVNCRARLYWVJUQJVOFVESVFVDSP
ELJBIAZHUEZBFFJCEIUZEDYVVGUCSXSTDTSPUCWQHAYKOWBDKDKNXMTNACFLYZGKXBCUAQHKNXNJQZANGZUXRFPZVJZC
JVEUTEBRDFTQAOGHHARDX
OFNHZGSVOQPLGCMIVZKODBVBLQRZK
|
# 2次配列で格納して、学生(i)を基準に各チェックポイント(m)とのマンハッタン距離を見ていく
# dis_lstに格納し、一番小さかった数字が格納されている配列番号を取ってくる。その番号に+1をし各チェックポイントの番号として、表示する。
# https://note.nkmk.me/python-list-index/
n, m = map(int, input().split())
s_lst = [list(map(int, input().split())) for _ in range(n)]
c_lst = [list(map(int, input().split())) for _ in range(m)]
dis_lst = []
min_lst = []
for i in range(0, n):
for j in range(0, m):
dis = abs(s_lst[i][0] - c_lst[j][0]) + \
abs(s_lst[i][1] - c_lst[j][1])
dis_lst.append(dis)
min_lst.append(dis_lst.index(min(dis_lst)) + 1)
dis_lst = []
for i in range(n):
print(min_lst[i])
|
"""!
@brief Colors used by pyclustering library for visualization.
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2020
@copyright BSD-3-Clause
"""
class color:
"""!
@brief Consists titles of colors that are used by pyclustering for visualization.
"""
@staticmethod
def get_color(sequential_index):
"""!
@brief Returns color using round robin to avoid out of range exception.
@param[in] sequential_index (uint): Index that should be converted to valid color index.
@return (uint) Color from list color.TITLES.
"""
return color.TITLES[sequential_index % len(color.TITLES)]
## List of color titles that are used by pyclustering for visualization.
TITLES = [ 'red', 'blue', 'darkgreen', 'gold', 'violet',
'deepskyblue', 'darkgrey', 'lightsalmon', 'deeppink', 'yellow',
'black', 'mediumspringgreen', 'orange', 'darkviolet', 'darkblue',
'silver', 'lime', 'pink', 'brown', 'bisque',
'dimgray', 'firebrick', 'darksalmon', 'chartreuse', 'skyblue',
'purple', 'fuchsia', 'palegoldenrod', 'coral', 'hotpink',
'gray', 'tan', 'crimson', 'teal', 'olive']
|
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# Function to print the list
def printList(self):
node = self
output = ''
while node is not None:
output += str(node.val)
output += " "
node = node.next
print(output)
# Iterative Solution
@staticmethod
def reverseIteratively(head):
reverse = None
following = head.next
while head:
head.next = reverse
reverse = head
head = following
if following:
following = following.next
if __name__ == '__main__':
testHead = ListNode(4)
node1 = ListNode(3)
testHead.next = node1
node2 = ListNode(2)
node1.next = node2
node3 = ListNode(1)
node2.next = node3
testTail = ListNode(0)
node3.next = testTail
print("Initial list: ")
testHead.printList()
#4 3 2 1 0
testHead.reverseIteratively(testHead)
print("List after reversal: ")
testTail.printList()
#0 1 2 3 4
|
# My Script:
hrs=input('Enter Hours: ')
hrs=float(hrs)
rph=input('Enter your rate per hour: ')
rph=float(rph)
pay=hrs*rph
print('Pay:', pay)
|
#!/usr/bin/python
def twosum(list, target):
for i in list:
for j in list:
if i != j and i + j == target:
return True
return False
with open('xmas.txt') as fh:
lines = fh.readlines()
nums = [int(l.strip()) for l in lines]
idx = 25
while(True):
last25 = nums[idx-25:idx]
if twosum(last25, nums[idx]):
idx += 1
else:
break
targetsum = nums[idx]
wstart = 0
wend = 1
while(True):
cursum = sum(nums[wstart:wend+1])
if cursum < targetsum:
wend += 1
elif cursum > targetsum:
wstart += 1
else:
print("%d %d" % (wstart, wend))
window = nums[wstart:wend+1]
print(min(window) + max(window))
break
print(cursum)
|
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
if len(nums) <= 2:
return max(nums)
dp = [0] * len(nums)
dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])
for x in range(2, len(nums)):
dp[x] = max(dp[x - 1], nums[x] + dp[x - 2])
return dp[-1]
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
prevMax,currMax = 0, 0
for x in nums:
tmp = currMax
currMax = max(prevMax + x, currMax)
prevMax = tmp
return currMax
|
class Solution:
# Max to Min distance pair, O(n^2) time, O(1) space
def maxDistance(self, colors: List[int]) -> int:
for dist in range(len(colors)-1, 0, -1):
for i in range(len(colors)-dist):
if colors[i] != colors[i+dist]:
return dist
# Max dist from endpoints (Top Voted), O(n) time, O(1) space
def maxDistance(self, A: List[int]) -> int:
i, j = 0, len(A) - 1
while A[0] == A[j]:
j -= 1
while A[-1] == A[i]:
i += 1
return max(len(A) - 1 - i, j)
|
#Functions
def userFunction(): #Putting Function
print("Hello, User :)")
print("Have a nice day!")
#Calling Function
userFunction()
|
"""Define docstring substitutions.
Text to be replaced is specified as a key in the returned dictionary,
with the replacement text defined by the corresponding value.
Special docstring substitutions, as defined by a class's
`_docstring_special_substitutions` method, may be used in the
replacement text, and will be substituted as usual.
Replacement text may not contain other non-special substitutions.
Keys must be `str` or `re.Pattern` objects:
* If a key is a `str` then the corresponding value must be a string.
* If a key is a `re.Pattern` object then the corresponding value must
be a string or a callable, as accepted by the `re.Pattern.sub`
method.
.. versionaddedd:: (cfdm) 1.8.7.0
"""
_docstring_substitution_definitions = {
# ----------------------------------------------------------------
# General susbstitutions (not indent-dependent)
# ----------------------------------------------------------------
"{{repr}}": "",
# ----------------------------------------------------------------
# # Method description susbstitutions (2 levels of indentation)
# ----------------------------------------------------------------
# cached: optional
"{{cached: optional}}": """cached: optional
If any value other than `None` then return *cached*
without selecting any constructs.""",
# todict: `bool`, optional
"{{todict: `bool`, optional}}": """todict: `bool`, optional
If True then return a dictionary of constructs keyed
by their construct identifiers, instead of a
`Constructs` object. This is a faster option.""",
# ----------------------------------------------------------------
# # Method description susbstitutions (3 levels of indentation)
# ----------------------------------------------------------------
# axes int examples
"{{axes int examples}}": """Each axis is identified by its integer position in the
data. Negative integers counting from the last
position are allowed.
*Parameter example:*
``axes=0``
*Parameter example:*
``axes=-1``
*Parameter example:*
``axes=[1, -2]``""",
# default Exception
"{{default Exception}}": """If set to an `Exception` instance then it will be
raised instead.""",
# inplace: `bool`, optional (default True)
"{{inplace: `bool`, optional (default True)}}": """inplace: `bool`, optional:
If False then do not do the operation in-place and
return a new, modified `{{class}}` instance. By
default the operation is in-place and `None` is
returned.""",
# init properties
"{{init properties: `dict`, optional}}": """properties: `dict`, optional
Set descriptive properties. The dictionary keys are
property names, with corresponding values. Ignored if
the *source* parameter is set.
Properties may also be set after initialisation with
the `set_properties` and `set_property` methods.""",
# init data
"{{init data: data_like, optional}}": """data: data_like, optional
Set the data. Ignored if the *source* parameter is
set.
{{data_like}}
The data also may be set after initialisation with the
`set_data` method.""",
# init bounds
"{{init bounds: `Bounds`, optional}}": """bounds: `Bounds`, optional
Set the bounds array. Ignored if the *source*
parameter is set.
The bounds array may also be set after initialisation
with the `set_bounds` method.""",
# init geometry
"{{init geometry: `str`, optional}}": """geometry: `str`, optional
Set the geometry type. Ignored if the *source*
parameter is set.
The geometry type may also be set after initialisation
with the `set_geometry` method.
*Parameter example:*
``geometry='polygon'``""",
# init interior_ring
"{{init interior_ring: `InteriorRing`, optional}}": """interior_ring: `InteriorRing`, optional
Set the interior ring variable. Ignored if the
*source* parameter is set.
The interior ring variable may also be set after
initialisation with the `set_interior_ring` method.""",
# init copy
"{{init copy: `bool`, optional}}": """copy: `bool`, optional
If False then do not deep copy input parameters prior
to initialisation. By default arguments are deep
copied.""",
# init source
"{{init source}}": """Note that if *source* is a `{{class}}` instance then
``{{package}}.{{class}}(source=source)`` is equivalent
to ``source.copy()``.""",
# data_like
"{{data_like}}": """A data_like object is any object that can be converted
to a `Data` object, i.e. `numpy` array_like objects,
`Data` objects, and {{package}} instances that contain
`Data` objects.""",
}
|
num_of_lines = int(input())
def cold_compress(cum, rs):
N = len(cum)
# exit
if (rs == ""):
output_string = ""
for s in cum:
output_string += str(s) + " "
return output_string
# iteration
if (N >= 2 and cum[N-1] == rs[0]):
cnt = cum[N-2]
cnt += 1
cum[N-2] = cnt
return cold_compress(cum, rs[1:])
else:
cum.append(1)
cum.append(rs[0])
return cold_compress(cum, rs[1:])
for i in range(0, num_of_lines):
print(cold_compress([], input()))
|
# arr = [2, 3, -4, -9, -1, -7, 1, -5, -6]
arr = [0, 0, 0, 0]
def next_p(arr, l, x):
print("px0", x)
while x <= l - 1 and arr[x] < 0:
x += 1
print("px1", x)
print("px2", x)
return x
def next_n(arr, l, x):
print("nx0", x)
while x <= l - 1 and arr[x] >= 0:
x += 1
print("nx1", x)
print("nx2", x)
return x
l = len(arr)
n = next_n(arr, l, 0)
p = next_p(arr, l, 0)
res = []
i = 0
print("a0", i, n, p, l, arr)
while i < l and n < l and p < l:
pos = i % 2 == 0
print("pos", i, pos, n, p)
if pos:
res.append(arr[p])
p += 1
p = next_p(arr, l, p)
else:
res.append(arr[n])
n += 1
n = next_n(arr, l, n)
i += 1
print("a1", i, n, p, l, res)
while i < l and n < l:
if arr[n] < 0:
res.append(arr[n])
n += 1
while i < l and p < l:
if arr[p] >= 0:
res.append(arr[p])
p += 1
print("a2", res)
|
# -*- coding: utf-8 -*-
# OPENID URLS
URL_WELL_KNOWN = "realms/{realm-name}/.well-known/openid-configuration"
URL_TOKEN = "realms/{realm-name}/protocol/openid-connect/token"
URL_USERINFO = "realms/{realm-name}/protocol/openid-connect/userinfo"
URL_LOGOUT = "realms/{realm-name}/protocol/openid-connect/logout"
URL_CERTS = "realms/{realm-name}/protocol/openid-connect/certs"
URL_INTROSPECT = "realms/{realm-name}/protocol/openid-connect/token/introspect"
URL_ENTITLEMENT = "realms/{realm-name}/authz/entitlement/{resource-server-id}"
# ADMIN URLS
URL_ADMIN_USERS = "admin/realms/{realm-name}/users"
URL_ADMIN_USERS_COUNT = "admin/realms/{realm-name}/users/count"
URL_ADMIN_USER = "admin/realms/{realm-name}/users/{id}"
URL_ADMIN_USER_CONSENTS = "admin/realms/{realm-name}/users/{id}/consents"
URL_ADMIN_SEND_UPDATE_ACCOUNT = "admin/realms/{realm-name}/users/{id}/execute-actions-email"
URL_ADMIN_SEND_VERIFY_EMAIL = "admin/realms/{realm-name}/users/{id}/send-verify-email"
URL_ADMIN_RESET_PASSWORD = "admin/realms/{realm-name}/users/{id}/reset-password"
URL_ADMIN_GET_SESSIONS = "admin/realms/{realm-name}/users/{id}/sessions"
URL_ADMIN_USER_CLIENT_ROLES = "admin/realms/{realm-name}/users/{id}/role-mappings/clients/{client-id}"
URL_ADMIN_USER_GROUP = "admin/realms/{realm-name}/users/{id}/groups/{group-id}"
URL_ADMIN_SERVER_INFO = "admin/serverinfo"
URL_ADMIN_GROUPS = "admin/realms/{realm-name}/groups"
URL_ADMIN_GROUP = "admin/realms/{realm-name}/groups/{id}"
URL_ADMIN_GROUP_CHILD = "admin/realms/{realm-name}/groups/{id}/children"
URL_ADMIN_GROUP_PERMISSIONS = "admin/realms/{realm-name}/groups/{id}/management/permissions"
URL_ADMIN_CLIENTS = "admin/realms/{realm-name}/clients"
URL_ADMIN_CLIENT = "admin/realms/{realm-name}/clients/{id}"
URL_ADMIN_CLIENT_ROLES = "admin/realms/{realm-name}/clients/{id}/roles"
URL_ADMIN_CLIENT_ROLE = "admin/realms/{realm-name}/clients/{id}/roles/{role-name}"
URL_ADMIN_REALM_ROLES = "admin/realms/{realm-name}/roles"
URL_ADMIN_USER_STORAGE = "admin/realms/{realm-name}/user-storage/{id}/sync"
|
#DEFAULT ARGS
print('Default Args : ')
def sample(a, b = 0, c = 1) :
print(a, b, c)
sample(10)
sample(10, 20)
sample(10, 20, 30)
#VARIABLE NUMBER OF ARGS
print('VARIABLE NUMBER OF ARGS : ')
def add(a, b, *t) :
s = a + b
for x in t :
s = s + x
return s
print(add(1, 2, 3, 4))
#KEY - WORD ARGS
print('KEY - WORD ARGS : ')
def sample2(j, k, l) :
print(j, k, l)
sample2(j = 'hi', k = 1.5, l = 30)
# VARIABLE NUMBER OF KEY - WORD ARGS
print('VARIABLE NUMBER OF KEY - WORD ARGS : ')
def sample3(**d) :
print(d)
sample3(m = 'Monday')
sample3(m = 'Monday', b = 'Tuesday')
|
string = 'b a '
newstring = string[-1::-1]
length = 0
print(newstring)
for i in range(0, len(newstring)):
if newstring[i] == ' ':
if i == 0:
continue
if newstring[i-1] == ' ':
continue
break
length += 1
print(length)
|
NEPS_URL = 'https://neps.academy'
ENGLISH_BUTTON = '/html/body/div/div/div/div[2]/div/div/a/div[2]/div'
LOGIN_PAGE_BUTTON = '//*[@id="app"]/div/div/div/div[1]/div/header/div/div/div[3]/div/div/nav/ul/li[6]/button'
EMAIL_INPUT = '/html/body/div/div/div/div[3]/div/div/div/form/div[1]/div/div[1]/div/input'
PASSWORD_INPUT = '/html/body/div/div/div/div[3]/div/div/div/form/div[2]/div/div[1]/div[1]/input'
LOGIN_MODAL_BUTTON = '//*[@id="app"]/div[3]/div/div/div/form/div[3]/button'
|
class Account:
"""Store login information(username and password)."""
def __init__(self, username='', password=''):
"""Store username and password."""
self.username = username
self.password = password
|
class Car(object):
"""A car class"""
def __init__(self, model, make, color):
self.model = model
self.make = make
self.color = color
self.price = None
def get_price(self):
return self.price
def set_price(self, value):
self.price = value
availableCars = []
def main():
global availableCars
#Create a new car obj
carObj = Car("Maruti SX4", "2011", "Black")
carObj.set_price(950000) # Set price
# Add this to available cars
availableCars.append(carObj)
print('TEST SUCEEDED')
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@文件 :collection_utils.py
@说明 :
@时间 :2020/07/13 17:54:21
@作者 :Riven
@版本 :1.0.0
'''
def get_first_existing(dict, *keys, default=None):
for key in keys:
if key in dict:
return dict[key]
return default
def put_multivalue(some_dict, key, value):
"""
Puts a value in a dict. If key already exists, then value will be appended to existing value(s) as a list.
Behavior is described by the following cases:
- key not exists: just put value in dict
- key has a single value: new list is created for [old_value,new_value] and stored into dict
- key has multiple values: new_value is appended to the list
:param dict: where to put new element
:param key: co
:param value: new value to add
"""
if key not in some_dict:
some_dict[key] = value
elif isinstance(some_dict[key], list):
some_dict[key].appended(value)
else:
some_dict[key] = [some_dict[key], value]
def find_any(values, predicate):
for value in values:
if predicate(value):
return value
return None
|
"""
URL: https://leetcode.com/explore/learn/card/linked-list/219/classic-problems/1207/
Problem Statement:
------------------
Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.
Example 1:
Input: head = [1,2,6,3,4,5,6], val = 6
Output: [1,2,3,4,5]
Example 2:
Input: head = [], val = 1
Output: []
Example 3:
Input: head = [7,7,7,7], val = 7
Output: []
Constraints:
The number of nodes in the list is in the range [0, 104].
1 <= Node.val <= 50
0 <= val <= 50
"""
# 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: ListNode, val: int) -> ListNode:
"""Approach 1: Creating new ListNode"""
# if head is None:
# return head
# node = ListNode(-1)
# itt = node
# while head is not None:
# if head.val != val:
# itt.next = ListNode(head.val)
# itt = itt.next
# head = head.next
# return node.next
"""Approach 2: Updating existing Linked List"""
node = ListNode(-1)
node.next = head
head = node
while head and head.next:
if head.next.val == val:
head.next = head.next.next
else:
head = head.next
return node.next
head = ListNode(1)
head.next = ListNode(6)
# head.next.next = ListNode(3)
# head.next.next.next = ListNode(6)
# head.next.next.next.next = ListNode(5)
Solution().removeElements(head=head, val=6)
|
class Solution:
def __init__(self):
self.ret = []
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
# dp[i][j] means starting from [i for j ele can be slice
dp = [[0 for _ in range(len(s)+1)] for _ in range(len(s)+1)]
for j in range(1, len(s)+1):
for i in range(len(s)-j+1):
if s[i:i+j] in wordDict:
dp[i][j] = 1
else:
for k in range(i, i+j):
if dp[i][k] != 0 and dp[i+k][j-k] != 0:
dp[i][j] = 2
if dp[0][len(s)] == 0:
return self.ret
curr = []
self.dfs(s, curr, 0, dp)
return self.ret
def dfs(self, s, curr, start, dp):
if start == len(s):
self.ret.append(" ".join(curr))
return
for i in range(1, len(s)-start+1):
if dp[start][i] == 1:
curr.append(s[start:start+i])
self.dfs(s, curr, start+i, dp)
curr.pop()
sl = Solution()
s = "catsanddog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
print(sl.wordBreak(s, wordDict))
|
password = input()
alpha = False
upalpha = False
digit = False
for i in password:
if i.isspace():
print("NOPE")
break
if i.isdigit():
digit = True
if i.isalpha():
if i.isupper():
upalpha = True
if i.islower():
alpha = True
else:
if alpha and upalpha and digit:
print("OK")
else:
print("NOPE")
|
"""
Best Solution
Space : O(1)
Time : O(n log n)
"""
class Solution:
def smallestRangeII(self, A: List[int], K: int) -> int:
A.sort()
ans = A[-1] - A[0]
for x, y in zip(A, A[1:]):
ans = min(ans, max(A[-1]-K, x+K) - min(A[0]+K, y-K))
return ans
|
# como adicionar itens em dicionario + lista em um looping + formatação
estado = {} # {} = dicionário
brasil = [] # [] lista
for c in range (0,3):
estado['uf']= str(input('Unidade Federativa: '))
estado['Sigla']=str(input('Sigla do Estado: '))
brasil.append(estado.copy()) # quando temos esse misto de dicionário e lista temos que inserir o copy para o dicionário, não podemos fatiar igual lista
for e in brasil:
print(e)
estado = {} # {} = dicionário
brasil = [] # [] lista
for c in range (0,2):
estado['uf']= str(input('Unidade Federativa: '))
estado['Sigla']=str(input('Sigla do Estado: '))
brasil.append(estado.copy()) # quando temos esse misto de dicionário e lista temos que inserir o copy para o dicionário, não podemos fatiar igual lista
for e in brasil:
for k, v in e.items():
print(f'O campo {k} tem o valor {v}')
estado = {} # {} = dicionário
brasil = [] # [] lista
for c in range (0,2):
estado['uf']= str(input('Unidade Federativa: '))
estado['Sigla']=str(input('Sigla do Estado: '))
brasil.append(estado.copy()) # quando temos esse misto de dicionário e lista temos que inserir o copy para o dicionário, não podemos fatiar igual lista
for e in brasil:
for v in e.valeus():
print(v, end=' ')
print ( )
|
###########################
# 6.0002 Problem Set 1b: Space Change
# Name:
# Collaborators:
# Time:
# Author: charz, cdenise
#================================
# Part B: Golden Eggs
#================================
# Problem 1
# Method 1
# def dp_make_weight(egg_weights, target_weight, memo = {}):
# """
# Find number of eggs to bring back, using the smallest number of eggs. Assumes there is
# an infinite supply of eggs of each weight, and there is always a egg of value 1.
# Parameters:
# egg_weights - tuple of integers, available egg weights sorted from smallest to largest value (1 = d1 < d2 < ... < dk)
# target_weight - int, amount of weight we want to find eggs to fit
# memo - dictionary, OPTIONAL parameter for memoization (you may not need to use this parameter depending on your implementation)
# Returns: int, smallest number of eggs needed to make target weight
# """
# # TODO: Your code here
# # sorted tuple
# egg_weights = tuple(sorted(egg_weights, reverse=True))
# # initiate result of zero egg
# if egg_weights == () or target_weight == 0:
# result = 0
# # explore right branch if first item > target weight
# elif egg_weights[0] > target_weight:
# result = dp_make_weight(egg_weights[1:],target_weight, memo)
# # explore left branch if first item < target weight
# else:
# next_egg_to_consider = egg_weights[0]
# # explore right branch if take next egg
# n_eggs_next_taken = dp_make_weight(egg_weights[1:],
# target_weight%next_egg_to_consider,
# memo)
# n_eggs_next_taken += (target_weight//next_egg_to_consider)
# # explore left branch if not take any next egg
# n_eggs_next_not = dp_make_weight(egg_weights[1:], target_weight, memo)
# if target_weight%next_egg_to_consider >= 0:
# result = n_eggs_next_taken
# else:
# result = n_eggs_next_not
# return result
# Method 2 (dynamic programming)
# https://stackoverflow.com/questions/61642912
def dp_make_weight(egg_weights, target_weight, memo={}):
# base case target weight < 0
least_taken = float("inf")
# base case target weight == 0
if target_weight == 0:
return 0
# recall stored key in dict
elif target_weight in memo:
return memo[target_weight]
# recursive case
elif target_weight > 0:
for weight in egg_weights:
sub_result = dp_make_weight(egg_weights, target_weight - weight)
least_taken = min(least_taken, sub_result)
# add 1 for current egg taken
memo[target_weight] = least_taken + 1
print(memo)
return least_taken + 1
# EXAMPLE TESTING CODE, feel free to add more if you'd like
if __name__ == '__main__':
egg_weights = (1, 5, 10, 25)
n = 99
print("Egg weights = (1, 5, 10, 25)")
print("n = 99")
print("Expected ouput: 9 (3 * 25 + 2 * 10 + 4 * 1 = 99)")
print("Actual output:", dp_make_weight(egg_weights, n))
print()
|
def mensaje(): # Declaración de la función
print("Estamos aprendiendo Python.")
print("Estamos aprendiendo instrucciones básicas.")
print("Poco a poco iremos avanzando.")
mensaje() # Llamada a la función
print("Ejecutando código fuera de función")
mensaje()
|
"""Miscellaneous stuff for Coverage."""
def nice_pair(pair):
"""Make a nice string representation of a pair of numbers.
If the numbers are equal, just return the number, otherwise return the pair
with a dash between them, indicating the range.
"""
start, end = pair
if start == end:
return "%d" % start
else:
return "%d-%d" % (start, end)
def format_lines(statements, lines):
"""Nicely format a list of line numbers.
Format a list of line numbers for printing by coalescing groups of lines as
long as the lines represent consecutive statements. This will coalesce
even if there are gaps between statements.
For example, if `statements` is [1,2,3,4,5,10,11,12,13,14] and
`lines` is [1,2,5,10,11,13,14] then the result will be "1-2, 5-11, 13-14".
"""
pairs = []
i = 0
j = 0
start = None
while i < len(statements) and j < len(lines):
if statements[i] == lines[j]:
if start == None:
start = lines[j]
end = lines[j]
j += 1
elif start:
pairs.append((start, end))
start = None
i += 1
if start:
pairs.append((start, end))
ret = ', '.join(map(nice_pair, pairs))
return ret
def expensive(fn):
"""A decorator to cache the result of an expensive operation.
Only applies to methods with no arguments.
"""
attr = "_cache_" + fn.__name__
def _wrapped(self):
"""Inner fn that checks the cache."""
if not hasattr(self, attr):
setattr(self, attr, fn(self))
return getattr(self, attr)
return _wrapped
class CoverageException(Exception):
"""An exception specific to Coverage."""
pass
class NoSource(CoverageException):
"""Used to indicate we couldn't find the source for a module."""
pass
|
# Ideas
"""
server = dkeras.DataServer()
model1.link(model3)
model1.postprocess = lambda z: np.float16(z)
server = model1 + model2 + model3
server.add(camera1, dest=('m1', 'm2'))
server.add_address('192.168.1.42')
"""
|
#!/usr/bin/env python3
class IndexCreator:
def __init__(self):
self._index = 0
def generate(self):
r = self._index
self._index += 1
return r
def clear(self):
self._index = 0
if __name__ == "__main__":
i = IndexCreator()
print(i.generate(), i.generate(), i.generate(), i.generate())
i.clear()
print(i.generate(), i.generate(), i.generate(), i.generate())
|
#Drinklist by Danzibob Credits to him!
drink_list = [{
'name': 'Vesper',
'ingredients': {
'gin': 60,
'vodka': 15.0,
'vermouth': 7.5
},
},
{
'name': 'Bacardi',
'ingredients': {
'whiteRum': 45.0,
'lij': 20,
'grenadine': 10
},
},
{
'name': 'Kryptonite',
'ingredients': {
'vodka': 8.0,
'whiskey': 7.0,
'lej': 6.0,
'oj': 5.0,
'grenadine': 4.0,
'cj': 3.0,
'rum': 2.0,
'vermouth': 1.0
},
},
{
'name': 'Vodka',
'ingredients': {
'vodka': 10.0,
},
},
{
'name': 'Whiskey',
'ingredients': {
'whiskey': 10.0,
},
},
{
'name': 'Lemon Juice',
'ingredients': {
'lej': 10.0,
},
},
{
'name': 'Orange Juice',
'ingredients': {
'oj': 10.0,
},
},
{
'name': 'Grenadine',
'ingredients': {
'grenadine': 10.0,
},
},
{
'name': 'Cranberry Juice',
'ingredients': {
'cj': 10.0,
},
},
{
'name': 'Rum',
'ingredients': {
'rum': 10.0,
},
},
{
'name': 'Vermouth',
'ingredients': {
'vermouth': 10.0
},
},
{
'name': 'Negroni',
'ingredients': {
'gin': 30,
'campari': 30,
'vermouth': 30
},
},
{
'name': 'Rose',
'ingredients': {
'cherryBrandy': 20,
'vermouth': 40
},
},
{
'name': 'Old Fashioned',
'ingredients': {
'whiskey': 45.0
},
},
{
'name': 'Tuxedo',
'ingredients': {
'gin': 30,
'vermouth': 30
},
},
{
'name': 'Mojito',
'ingredients': {
'whiteRum': 40,
'lij': 30
},
},
{
'name': "Horse's Neck",
'ingredients': {
'brandy': 40,
'gingerAle': 120
},
},
{
'name': "Planter's Punch",
'ingredients': {
'darkRum': 45.0,
'oj': 35.0,
'pj': 35.0,
'lej': 20,
'grenadine': 10
},
},
{
'name': 'Sea Breeze',
'ingredients': {
'vodka': 40,
'cj': 120,
'gj': 30
},
},
{
'name': 'Pisco Sour',
'ingredients': {
'brandy': 45.0,
'lej': 30,
'grenadine': 20
},
},
{
'name': 'Long Island Iced Tea',
'ingredients': {
'tequila': 15.0,
'vodka': 15.0,
'whiteRum': 15.0,
'tripSec': 15.0,
'gin': 15.0,
'lej': 25.0,
'grenadine': 30.0
},
},
{
'name': 'Clover Club',
'ingredients': {
'gin': 45.0,
'grenadine': 15.0,
'lej': 15.0
},
},
{
'name': 'Angel Face',
'ingredients': {
'gin': 30,
'apricotBrandy': 30,
'appleBrandy': 30
},
},
{
'name': 'Mimosa',
'ingredients': {
'champagne': 75.0,
'oj': 75.0
},
},
{
'name': 'Whiskey Sour',
'ingredients': {
'whiskey': 45.0,
'lej': 30.0,
'grenadine': 15.0
},
},
{
'name': 'Screwdriver',
'ingredients': {
'vodka': 50,
'oj': 100
},
},
{
'name': 'Cuba Libre',
'ingredients': {
'whiteRum': 50,
'cola': 120,
'lij': 10
},
},
{
'name': 'Manhattan',
'ingredients': {
'whiskey': 50,
'vermouth': 20
},
},
{
'name': 'Porto Flip',
'ingredients': {
'brandy': 15.0,
'port': 45.0,
'eggYolk': 10
},
},
{
'name': 'Gin Fizz',
'ingredients': {
'gin': 45.0,
'lej': 30,
'grenadine': 10,
'soda': 80
},
},
{
'name': 'Espresso Martini',
'ingredients': {
'vodka': 50,
'coffeeLiqueur': 10
},
},
{
'name': 'Margarita',
'ingredients': {
'tequila': 35.0,
'tripSec': 20,
'lij': 15.0
},
},
{
'name': 'French 75',
'ingredients': {
'gin': 30,
'lej': 15.0,
'champagne': 60
},
},
{
'name': 'Yellow Bird',
'ingredients': {
'whiteRum': 30,
'galliano': 15.0,
'tripSec': 15.0,
'lij': 15.0
},
},
{
'name': 'Pina Colada',
'ingredients': {
'whiteRum': 30,
'pj': 90,
'coconutMilk': 30
},
},
{
'name': 'Aviation',
'ingredients': {
'gin': 45.0,
'cherryLiqueur': 15.0,
'lej': 15.0
},
},
{
'name': 'Bellini',
'ingredients': {
'prosecco': 100,
'peachPuree': 50
},
},
{
'name': 'Grasshopper',
'ingredients': {
'cremeCacao': 30,
'cream': 30
},
},
{
'name': 'Tequila Sunrise',
'ingredients': {
'tequila': 45.0,
'oj': 90,
'grenadine': 15.0
},
},
{
'name': 'Daiquiri',
'ingredients': {
'whiteRum': 45.0,
'lij': 25.0,
'grenadine': 15.0
},
},
{
'name': 'Rusty Nail',
'ingredients': {
'whiskey': 25.0
},
},
{
'name': 'B52',
'ingredients': {
'coffeeLiqueur': 20,
'baileys': 20,
'tripSec': 20
},
},
{
'name': 'Stinger',
'ingredients': {
'brandy': 50,
'cremeCacao': 20
},
},
{
'name': 'Golden Dream',
'ingredients': {
'galliano': 20,
'tripSec': 20,
'oj': 20,
'cream': 10
},
},
{
'name': 'God Mother',
'ingredients': {
'vodka': 35.0,
'amaretto': 35.0
},
},
{
'name': 'Spritz Veneziano',
'ingredients': {
'prosecco': 60,
'aperol': 40
},
},
{
'name': 'Bramble',
'ingredients': {
'gin': 40,
'lej': 15.0,
'grenadine': 10,
'blackberryLiqueur': 15.0
},
},
{
'name': 'Alexander',
'ingredients': {
'brandy': 30,
'cremeCacao': 30,
'cream': 30
},
},
{
'name': 'Lemon Drop Martini',
'ingredients': {
'vodka': 25.0,
'tripSec': 20,
'lej': 15.0
},
},
{
'name': 'French Martini',
'ingredients': {
'vodka': 45.0,
'raspberryLiqueur': 15.0,
'pj': 15.0
},
},
{
'name': 'Black Russian',
'ingredients': {
'vodka': 50,
'coffeeLiqueur': 20
},
},
{
'name': 'Bloody Mary',
'ingredients': {
'vodka': 45.0,
'tj': 90,
'lej': 15.0
},
},
{
'name': 'Mai-tai',
'ingredients': {
'whiteRum': 40,
'darkRum': 20,
'tripSec': 15.0,
'grenadine': 15.0,
'lij': 10
},
},
{
"name": "Madras",
"ingredients": {
"vodka": 45,
"cj": 90,
"oj": 30
}
},
{
"name": "Lemon Drop",
"ingredients": {
"vodka": 40,
"lej": 40,
"grenadine": 15
}
},
{
"name": "Gin Tonic",
"ingredients": {
"gin": 50,
"tonic": 160
}
},
{
"name": "Cape Cod",
"ingredients": {
"vodka": 35,
"cj": 135
}
},
{
"name": "Bourbon Squash",
"ingredients": {
"whisky": 45,
"oj": 50,
"lej": 30,
"grenadine": 20
}
}]
drink_options = [
{
"name": "Gin",
"value": "gin"
},
{
"name": "White Rum",
"value": "whiteRum"
},
{
"name": "Dark Rum",
"value": "darkRum"
},
{
"name": "Coconut Rum",
"value": "coconutRum"
},
{
"name": "Vodka",
"value": "vodka"
},
{
"name": "Tequila",
"value": "tequila"
},
{
"name": "Tonic Water",
"value": "tonic"
},
{
"name": "Coke",
"value": "coke"
},
{
"name": "Orange Juice",
"value": "oj"
},
{
"name": "Margarita Mix",
"value": "mmix"
},
{
"name": "Cranberry Juice",
"value": "cj"
},
{
"name": "Pineapple Juice",
"value": "pj"
},
{
"name": "Apple Juice",
"value": "aj"
},
{
"name": "Grapefruit Juice",
"value": "gj"
},
{
"name": "Tomato Juice",
"value": "tj"
},
{
"name": "Lime Juice",
"value": "lij"
},
{
"name": "Lemon Juice",
"value": "lej"
},
{
"name": "Whiskey",
"value": "whiskey"
},
{
"name": "Triple Sec",
"value": "tripSec"
},
{
"name": "Grenadine",
"value": "grenadine"
},
{
"name": "Vermouth",
"value": "vermouth"
},
{
"name": "Soda",
"value": "soda"
},
{
"name": "Peach Schnapps",
"value": "peachSchnapps"
},
{
"name": "Midori",
"value": "midori"
},
{
"name": "Presecco",
"value": "prosecco"
},
{
"name": "Cherry Brandy",
"value": "cherryBrandy"
},
{
"name": "Apple Brandy",
"value": "appleBrandy"
},
{
"name": "Apricot Brandy",
"value": "apricotBrandy"
},
{
"name": "Brandy (generic)",
"value": "brandy"
},
{
"name": "Champagne",
"value": "champagne"
},
{
"name": "Cola",
"value": "cola"
},
{
"name": "Port",
"value": "port"
},
{
"name": "Coconut Milk",
"value": "coconutMilk"
},
{
"name": "Creme de Cacao",
"value": "cremeCacao"
},
{
"name": "Grenadine",
"value": "grenadine"
}
]
# Check for ingredients that we don 't have a record for
if __name__ == "__main__":
found = []
drinks = [x["value"] for x in drink_options]
for D in drink_list:
for I in D["ingredients"]:
if I not in drinks and I not in found:
found.append(I)
print(I)
|
lista = [1, 13, 15, 7]
lista_animal = ['cachorro', 'gato', 'elefante', 'arara']
# Convertendo lista em tupla
tupla_animal = tuple(lista_animal)
print(lista_animal)
print(tupla_animal)
# Convertendo tupla em lista
tupla = (1, 13, 15, 7)
lista_numerica = list(tupla)
print(tupla)
print(lista_numerica)
# Daí dá para alterar
lista_numerica[0] = 80
print(lista_numerica)
|
'''
Thanks to "Primo" for the amazing code found in this .py.
'''
# legendre symbol (a|m)
# note: returns m-1 if a is a non-residue, instead of -1
def legendre(a, m):
return pow(a, (m-1) >> 1, m)
# strong probable prime
def is_sprp(n, b=2):
d = n-1
s = 0
while d & 1 == 0:
s += 1
d >>= 1
x = pow(b, d, n)
if x == 1 or x == n-1:
return True
for r in range(1, s):
x = (x * x) % n
if x == 1:
return False
elif x == n-1:
return True
return False
# lucas probable prime
# assumes D = 1 (mod 4), (D|n) = -1
def is_lucas_prp(n, D):
P = 1
Q = (1-D) >> 2
# n+1 = 2**r*s where s is odd
s = n+1
r = 0
while s&1 == 0:
r += 1
s >>= 1
# calculate the bit reversal of (odd) s
# e.g. 19 (10011) <=> 25 (11001)
t = 0
while s > 0:
if s & 1:
t += 1
s -= 1
else:
t <<= 1
s >>= 1
# use the same bit reversal process to calculate the sth Lucas number
# keep track of q = Q**n as we go
U = 0
V = 2
q = 1
# mod_inv(2, n)
inv_2 = (n+1) >> 1
while t > 0:
if t & 1 == 1:
# U, V of n+1
U, V = ((U + V) * inv_2) % n, ((D*U + V) * inv_2) % n
q = (q * Q) % n
t -= 1
else:
# U, V of n*2
U, V = (U * V) % n, (V * V - 2 * q) % n
q = (q * q) % n
t >>= 1
# double s until we have the 2**r*sth Lucas number
while r > 0:
U, V = (U * V)%n, (V * V - 2 * q)%n
q = (q * q)%n
r -= 1
# primality check
# if n is prime, n divides the n+1st Lucas number, given the assumptions
return U == 0
# primes less than 212
small_primes = set([
2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97,101,103,107,109,113,
127,131,137,139,149,151,157,163,167,173,
179,181,191,193,197,199,211])
# pre-calced sieve of eratosthenes for n = 2, 3, 5, 7
indices = [
1, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83,
89, 97,101,103,107,109,113,121,127,131,
137,139,143,149,151,157,163,167,169,173,
179,181,187,191,193,197,199,209]
# distances between sieve values
offsets = [
10, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6,
6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4,
2, 4, 8, 6, 4, 6, 2, 4, 6, 2, 6, 6,
4, 2, 4, 6, 2, 6, 4, 2, 4, 2,10, 2]
max_int = 2147483647
# an 'almost certain' primality check
def is_prime(n):
if n < 212:
return n in small_primes
for p in small_primes:
if n % p == 0:
return False
# if n is a 32-bit integer, perform full trial division
if n <= max_int:
i = 211
while i * i < n:
for o in offsets:
i += o
if n % i == 0:
return False
return True
# Baillie-PSW
# this is technically a probabalistic test, but there are no known pseudoprimes
if not is_sprp(n):
return False
a = 5
s = 2
while legendre(a, n) != n-1:
s = -s
a = s-a
return is_lucas_prp(n, a)
# next prime strictly larger than n
def next_prime(n):
if n < 2:
return 2
# first odd larger than n
n = (n + 1) | 1
if n < 212:
while True:
if n in small_primes:
return n
n += 2
# find our position in the sieve rotation via binary search
x = int(n % 210)
s = 0
e = 47
m = 24
while m != e:
if indices[m] < x:
s = m
m = (s + e + 1) >> 1
else:
e = m
m = (s + e) >> 1
i = int(n + (indices[m] - x))
# adjust offsets
offs = offsets[m:]+offsets[:m]
while True:
for o in offs:
if is_prime(i):
return i
i += o
|
a = "Hello World"
b = a[3]
c = a[-2]
d = a[5::]
e = a[:5]
print(b)
print(c)
print(d)
print(e)
|
class TagLoaderException(Exception):
pass
def str2int(s: str, default=0) -> int:
try:
return int(s)
except ValueError:
return default
def get_or_default(d, k, default=""):
if k in d:
return d[k]
else:
return default
def bytes2str(buffer: bytes) -> [str, bytes]:
# 末尾のNULL文字を削除する
while buffer[-1] == 0:
buffer = buffer[:-1]
for encoding in ["Shift-JIS", "UTF-8"]:
try:
return buffer.decode(encoding)
except UnicodeDecodeError:
pass
return buffer
|
overlapped_classes = ["Alarm clock",
"Backpack",
"Banana",
"Band Aid",
"Basket",
"Bath towel",
"Beer bottle",
"Bench",
"Bicycle",
"Binder (closed)",
"Bottle cap",
"Bread loaf",
"Broom",
"Bucket",
"Butcher's knife",
"Can opener",
"Candle",
"Cellphone",
"Chair",
"Clothes hamper",
"Combination lock",
"Computer mouse",
"Desk lamp",
"Dishrag or hand towel",
"Doormat",
"Dress",
"Dress shoe (men)",
"Drill",
"Drinking Cup",
"Drying rack for plates",
"Envelope",
"Fan",
"Coffee/French press",
"Frying pan",
"Hair dryer",
"Hammer",
"Helmet",
"Iron (for clothes)",
"Jeans",
"Keyboard",
"Ladle",
"Lampshade",
"Laptop (open)",
"Lemon",
"Letter opener",
"Lighter",
"Lipstick",
"Match",
"Measuring cup",
"Microwave",
"Mixing / Salad Bowl",
"Monitor",
"Mug",
"Nail (fastener)",
"Necklace",
"Orange",
"Padlock",
"Paintbrush",
"Paper towel",
"Pen",
"Pill bottle",
"Pillow",
"Pitcher",
"Plastic bag",
"Plate",
"Plunger",
"Pop can",
"Portable heater",
"Printer",
"Remote control",
"Ruler",
"Running shoe",
"Safety pin",
"Salt shaker",
"Sandal",
"Screw",
"Shovel",
"Skirt",
"Sleeping bag",
"Soap dispenser",
"Sock",
"Soup Bowl",
"Spatula",
"Speaker",
"Still Camera",
"Strainer",
"Stuffed animal",
"Suit jacket",
"Sunglasses",
"Sweater",
"Swimming trunks",
"T-shirt",
"TV",
"Teapot",
"Tennis racket",
"Tie",
"Toaster",
"Toilet paper roll",
"Trash bin",
"Tray",
"Umbrella",
"Vacuum cleaner",
"Vase",
"Wallet",
"Watch",
"Water bottle",
"Weight (exercise)",
"Weight scale",
"Wheel",
"Whistle",
"Wine bottle",
"Winter glove",
"Wok"]
|
indexes = range(5)
same_indexes = range(0, 5)
print("indexes are:")
for i in indexes:
print(i)
print("same_indexes are:")
for i in same_indexes:
print(i)
special_indexes = range(5, 9)
print("special_indexes are:")
for i in special_indexes:
print(i)
|
print('\nCalculate the midpoint of a line :')
x1 = float(input('The value of x (the first endpoint) '))
y1 = float(input('The value of y (the first endpoint) '))
x2 = float(input('The value of x (the first endpoint) '))
y2 = float(input('The value of y (the first endpoint) '))
x_m_point = (x1 + x2)/2
y_m_point = (y1 + y2)/2
print()
print("The midpoint of line is :")
print( "The midpoint's x value is: ",x_m_point)
print( "The midpoint's y value is: ",y_m_point)
print()
|
ts = [
# example tests
14,
16,
23,
# small numbers
5,
4,
3,
2,
1,
# random bit bigger numbers
10,
20,
31,
32,
33,
46,
# perfect squares
25,
36,
49,
# random incrementally larger numbers
73,
89,
106,
132,
182,
258,
299,
324, # perfect square
359, # prime
489,
512,
581,
713,
834,
952,
986,
996,
997, # largest prime in range
998,
999,
]
for i, n in enumerate(ts):
with open('T%02d.in' % i, 'w') as f:
f.write('%d\n' % n)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.