content stringlengths 7 1.05M |
|---|
'''Crie as classes necessárias para um sistema de gerenciamento de uma biblioteca. Os
bibliotecários deverão preencher o sistema com o título do livro, os autores, o ano, a editora, a
edição e o volume. A biblioteca também terá um sistema de pesquisa (outro software), portanto
será necessário conseguir acessar os atrib... |
"""
Given an n-ary tree, return the postorder traversal of its nodes' values. Nary-Tree input serialization
is represented in their level order traversal, each group of children is separated by the null value
(See examples).
Follow up: Recursive solution is trivial, could you do it iteratively?
Example 1:
htt... |
class TableViewUIUtils(object):
""" This utility class contains members that involve the Revit UI and operate on schedule views or MEP electrical panel schedules. """
@staticmethod
def TestCellAndPromptToEditTypeParameter(tableView,sectionType,row,column):
"""
TestCellAndPromptToEditTypeParameter(tableView:... |
# Q5. Write a program to implement OOPs concepts in python i.e. inheritance etc.
class Person:
def __init__(self, name, age, address): # constructor
self.name = name
self.age = age
self.address = address
def set_data(self, name, age, address):
self.name = name
self.age = age
self.address... |
# Aprimore o desafio anterior, mostrando no final:
# A) A soma de todos os valores pares digitados.
# B) A soma dos valores da terceira coluna.
# C) O maior valor da segunda linha.
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
somaPar = 0
somaCol = 0
for l in range(0, 3):
for c in range(0, 3):
matriz[l][c] = i... |
class PolarPoint():
def __init__(self, angle, radius):
self.angle = angle
self.radius = radius
|
def mu(i, lo=0, hi=None):
hi = hi or len(i.has)
return sum([i.x(i.has[j]) for j in range(lo, hi)]) / (hi - lo)
class Some(o):
"Collect some examples, not all."
hi = 256 # max number of items to collect
def __init__(i, pos=0, txt=" ", inits=[]):
i.pos, i.txt, i.n, i._all, i.sorted = pos, txt, 0, [], Fa... |
'''
Truth tables for logical expressions.
Define predicates and/2, or/2, nand/2, nor/2, xor/2, impl/2 and equ/2 (for logical equivalence) which succeed or fail according to the result of their respective operations; e.g. and(A,B) will succeed, if and only if both A and B succeed. Note that A and B can be Prolog goa... |
p=float(input('\033[32mqual o preço do produto ? R$\033[m'))
d=(p*5)/100
v=p-d
print('\033[34mO desconto em 5 porcento do produto será de \033[31mR${}\033[34m'.format(d))
print('O valor do produto com 5 porcento de desconto é de \033[31mR${}'.format(v)) |
'''
*000*000*
0*00*00*0
00*0*0*00
000***000
Utkarsh
'''
l=int(input())
b=int(input())
print("With for\n")
for i in range(1,b+1):
for j in range(1,l+1):
if j==(l+1)//2 or j==i or j==(l+1)-i:
print('*',end='')
else:
print('0',end='')
print()
i=1
j=1
print("\nWith while\n")... |
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: flat
class SeriesLengthOption(object):
Unlimited = 0
Three_Games = 1
Five_Games = 2
Seven_Games = 3
|
"""69. Sqrt(x)
https://leetcode.com/problems/sqrtx/
Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a
non-negative integer.
Since the return type is an integer, the decimal digits are truncated and
only the integer part of the result is returned.
Example 1:
Input: 4
... |
# coding: utf-8
__author__ = 'tack'
class Position(object):
'''
position
'''
def __init__(self, code, num, price, commission, date):
'''
Args:
code: stock code
price: cost price
commission: commission
num: num
date: date
... |
#08 - Crie um programa que leia nome, ano de nascimento e carteira de trabalho e cadastre-os (com idade) em um dicionário. Se por acaso a CTPS for diferente de 0, o dicionário receberá também o ano de contratação e o salário. Calcule e acrescente , além da idade, com quantos anos a pessoa vai se aposentar. Considere qu... |
with open("p022_names.txt","r") as names:
names = names.read().replace("\"","").split(",")
names.sort()
Sum = 0
length = len(names)
for position in range(length):
alphavalue=0
for j in names[position]:
alphavalue += (ord(j)-64)
Sum += (alphavalue * (position+1))
print(Sum) |
config = {
'population_size' : 100,
'mutation_probability' : .1,
'crossover_rate' : .9,
# maximum simulation runs before finishing
'max_runs' : 100,
# maximum timesteps per simulation
'max_timesteps' : 150,
# smoothness value of the line in [0, 1]
'line_smoothness' : .4,
# Bound ... |
expected_output = {
'mstp': {
'blocked-ports': {
'mst_instances': {
'0': {
'mst_id': '0',
'interfaces': {
'GigabitEthernet0/0/4/4': {
'name': 'GigabitEthe... |
class Solution:
def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
tup = [(ind, i) for ind, i in enumerate(nums)]
tup.sort(key=lambda x: x[1])
for i in range(len(tup)):
for j in range(i+1, len(tup)):
if abs(tup[i][1]-tup[j][1])>t:
... |
del_items(0x80139F2C)
SetType(0x80139F2C, "void PresOnlyTestRoutine__Fv()")
del_items(0x80139F54)
SetType(0x80139F54, "void FeInitBuffer__Fv()")
del_items(0x80139F7C)
SetType(0x80139F7C, "void FeAddEntry__Fii8TXT_JUSTUsP7FeTableP5CFont(int X, int Y, enum TXT_JUST Just, unsigned short Str, struct FeTable *MenuPtr, struc... |
# -*- coding: utf-8 -*-
# Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
# Duplicate values will overwrite existing values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
# String, int, boolean, and list dat... |
''' e. and use all methods '''
''' also try different exception like java file,array,string,numberformat '''
''' user define exception '''
try:
raise Exception('spam,','eggs')
except Exception as inst:
print("Type of instance : ",type(inst)) # the exception instance
print("Arguments of instance : ",inst.ar... |
def is_palindrome_number(number):
return number == int(str(number)[::-1])
def infinite_sequence():
num = 0
while True:
yield num
num += 1
for number in infinite_sequence():
if is_palindrome_number(number):
print(number)
def countdown_from(number):
print(f"Starting to co... |
TEST_ROOT_TABLES = {
"tenders": ["/tender"],
"awards": ["/awards"],
"contracts": ["/contracts"],
"planning": ["/planning"],
"parties": ["/parties"],
}
TEST_COMBINED_TABLES = {
"documents": [
"/planning/documents",
"/tender/documents",
"/awards/documents",
"/contra... |
"""Diagnose audio and other input data for ML pipelines
>>> print('hello')
hello
"""
|
def pattern_nineteen(steps):
''' Pattern nineteen
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24... |
n1 = float(input('qual a primeira nota? '))
n2 = float(input('qual a segunda nota? '))
soma = n1 + n2
media = (n1 + n2) / 2
print('a soma das notas foi {:.2f}, e a sua media foi de {:.2f}'.format(soma, media))
|
'''
02 - Creating dummy variables
As Andy discussed in the video, scikit-learn does not accept non-numerical features.
You saw in the previous exercise that the 'Region' feature contains very useful
information that can predict life expectancy.
For example: Sub-Saharan Africa has a lower life expectancy compar... |
# Given three colinear points p, q, r, the function checks if
# point q lies on line segment 'pr'
def onSegment(p, q, r):
if ( (q.position[0] <= max(p.position[0], r.position[0])) and (q.position[0] >= min(p.position[0], r.position[0])) and
(q.position[1] <= max(p.position[1], r.position[1])) and ... |
class SystemCallFault(Exception):
def __init__(self):
pass
def __str__(self):
return 'System not give expect response.'
class NecessaryLibraryNotFound(Exception):
def __init__(self,value = '?'):
self.value = value
def __str__(self):
return 'Necessary library \'%s\' n... |
string = "Character"
print(string[2])
# string[2] = 'A' not change it
# string.replace('a','A') we can replace it but it cannot change the our string variables.
new_string = string.replace('a','A')
print(new_string) |
## CvAltRoot
##
## Tells BUG where to locate its files when it cannot find them normally.
## This is common when using the /AltRoot Civ4 feature or sometimes on
## non-English operating systems and Windows Vista.
##
## HOW TO USE
##
## 1. Change the text in the quotes below to match the full path to the
## ... |
#######################################################################
# Copyright (C) 2017 Shangtong Zhang(zhangshangtong.cpp@gmail.com) #
# Permission given to modify the code as long as you keep this #
# declaration at the top #
################################... |
# question 1
A = 3
B = 3
C = (-5)
X = 8.8
Y = 3.5
Z = (-5.2)
print(A % C)
print(A * B / C)
print((A * C) % C)
print(X / Y)
print(X / (X + Y))
print(int(X) % int(Y))
# question 2
A = float(input("the number you want to round off:"))
print(round(A))
# question 3
A = float(input("length in CM:"))
B = float(input("length... |
# coding=utf-8
setThrowException(True)
class Nautilus:
REMOTE = 0
LOCAL = 1
_tab = None
_dirs = {}
def __init__(self):
self._dirs = {self.LOCAL: [], self.REMOTE: []}
self._startNautilus()
self._initWebdav()
sleep(1)
self._initLocal()
def _startNautilus(self):
... |
def policy_threshold(threshold, belief, loc):
"""
chooses whether to switch side based on whether the belief
on the current site drops below the threshold
Args:
threshold (float): the threshold of belief on the current site,
when the belief is lower than the threshold, switch si... |
print((2**64).to_bytes(9, "little",signed=False))
#signed shall be False by default
print((2**64).to_bytes(9, "little"))
# test min/max signed value
for i in [10]:
v = 2**(i*8 - 1) - 1
print(v)
vbytes = v.to_bytes(i, "little")
print(vbytes)
print(int.from_bytes(vbytes,"little"))
v = - (2**(i*8... |
'''Crie um programa onde o usuário possa digitar vários valores numéricos e cadastre-os em uma lista. Caso o número já
exista lá dentro, ele não será adicionado. No final, serão exibidos todos os valores únicos digitados, em ordem crescente.'''
lista = []
print('\033[1;33m-=\033[m' * 20)
while True:
n1 = int(input(... |
x = int(input('Podaj pierwsza liczbe calkowita: '))
y = int(input('Podaj druga liczbe calkowita: '))
print()
print(x%y)
print(y%x)
print()
print(x//y)
print(y//x) |
SEAL_CHECKER = 9300535
SEAL_OF_TIME_1 = 2159363
SEAL_OF_TIME_2 = 2159364
SEAL_OF_TIME_3 = 2159365
SEAL_OF_TIME_4 = 2159366
sm.giveSkill(20041222)
sm.setFuncKeyByScript(True, 20041222, 42)
sm.spawnMob(SEAL_CHECKER, 550, -298, False)
sm.spawnMob(SEAL_CHECKER, 107, -508, False)
sm.spawnMob(SEAL_CHECKER, -195, -508, Fals... |
"""testpackagepypi - test"""
__version__ = '0.1.0'
__author__ = 'Dominik Haitz <dominik.haitz at ...>'
__all__ = []
|
description = 'minimal NICOS startup setup'
group = 'lowlevel'
sysconfig = dict(
cache = 'tofhw.toftof.frm2:14869',
)
|
class BaseStrategy(object):
def get_next_move(self, board):
raise NotImplementedError
class MoveFirst(BaseStrategy):
pass
|
"""Code generated by gazelle. DO NOT EDIT."""
load("@bazel_gazelle//:deps.bzl", "go_repository")
def go_dependencies():
"""go_dependencies."""
go_repository(
name = "co_honnef_go_tools",
importpath = "honnef.co/go/tools",
sum = "h1:UoveltGrhghAA7ePc+e+QYDHXrBps2PqFZiHkGR/xK8=",
... |
"""
The `~certbot_dns_rrpproxy.dns_rrpproxy` plugin automates the process of
completing a ``dns-01`` challenge (`~acme.challenges.DNS01`) by creating, and
subsequently removing, TXT records using the RRPproxy API.
Named Arguments
---------------
======================================== =============================... |
print('\033[31mOlá, Mundo!')
print('\033[31;43mOlá, Mundo!')
print('\033[1;31;43mOlá, Mundo!')
print('\033[1;31;43mOlá, Mundo!\033[m')
print('\033[4;30;45mOlá, Mundo!\033[m')
print('\033[30mOlá, Mundo!\033[m')
print('\033[37mOlá, Mundo!\033[m')
print('\033[7;30mOlá, Mundo!\033[m')
print('\033[0;33;44mOlá, Mundo!\033[m'... |
VERSION = "1.0.0-beta.15"
LANGUAGE = "python"
PROJECT = "versionhelper"
_p = "versionhelper.libvh."
API = {_p + "version_helper" : {"arguments" : ("filename str", ),
"keywords" : {"directory" : "directory str",
"version" : "str",
... |
#Build a Bus/Air/Rail Booking System where the user can choose a source and destination from the list given and enter the information passenger wise, depending on the distance cost shall be computed.
#Bus,Rail and Air systems will have different fares for different classes.You should be able to think of the system as ... |
print(f'\033[33m{"—"*30:^30}\033[m')
print(f'\033[36m{"EXERCÍCIO Nº 52":^30}\033[m')
print(f'\033[33m{"—"*30:^30}\033[m')
n = int(input('Digite um número: '))
for x in range(2, n + 1):
if x == n:
print('Primo')
break
if n % x == 0:
print('não é primo')
break
|
'''
Author: Shuailin Chen
Created Date: 2021-08-17
Last Modified: 2021-08-17
content:
'''
_base_= [
'../_base_/models/bit_pos_s4_dd8.py',
'../_base_/datasets/s2looking.py',
'../_base_/default_runtime.py',
'../_base_/schedules/schedule_80k.py'
]
data = dict(
samples_per_gpu=8,
workers_per_g... |
#need prompt for pet type
#build pet dictionary
#give toys, feed pet, let game loop, while printing menu
pet = {"name":"", "type": "", "age": 0, "hunger": 0, "playfulness" : 0, "toys": []}
pettoys = {"cat": ["String", "Cardboard Box", "Scratching Post"], "dog": ["Frisbee","Tennis Ball", "Stick"], "fish": ["Underse... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def middleNode(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
val_list = [head.val]
node = head
... |
RAWDATA_DIR = '/staging/as/skchoudh/rna-seq-datasets/single/gallus_gallus/SRP007412'
OUT_DIR = '/staging/as/skchoudh/rna-seq-output/gallus_gallus/SRP007412'
CDNA_FA_GZ = '/home/cmb-panasas2/skchoudh/genomes/gallus_gallus/cdna/Gallus_gallus.Gallus_gallus-5.0.cdna.all.fa.gz'
CDNA_IDX = '/home/cmb-panasas2/skchoudh/g... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
TIME_WIND... |
def check_rewrite_data(data, data_path):
with open(data_path, 'w') as output_data:
first_is_name = False
need_line = False
seq_num = 0
for x in data:
x = x.strip()
if not x:
continue
if x[0] == '>':
x = ada... |
n, min_val, max_val = int(input('n=')), int(input('minimum=')), int(input('maximum='))
c = i = 0
while True:
i, sq = i+1, i**n
if sq in range(min_val, max_val+1): c += 1
if sq > max_val: break
print(f'{c} values raised to the power {n} lie in the range {min_val}, {max_val}')
|
_base_ = [
'../_base_/models/fpn_r50.py', '../_base_/datasets/FoodSeg103.py',
'../_base_/default_runtime.py', '../_base_/schedules/schedule_80k.py'
]
model = dict(pretrained='./pretrained_model/R50_ReLeM.pth',
backbone=dict(type='ResNet'),
decode_head=dict(num_classes=104))
optimizer... |
def me(**kwargs):
for key, value in kwargs.items():
print("{0}=={1}". format(key, value))
me(name="Rahim", ID=18)
me(name="Ariful", age=109)
me(age=10)
|
class Query:
"""
Class representing a single query to be executed on the database.
"""
def __init__(self):
self.__select = "*"
self.__from = None
self.__where = None
self.__group_by = None
self.__having = None
self.__order_by = None
self.__limit = ... |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Adekunle Oliver Adebajo\n",
"### 20120612016\n",
"### adekunle.adebajo@pau.edu.ng\n",
"### the following codes consist of class exercises involving problem solving"
]
},
{
"cell_type": "code",
"execution_co... |
#!/usr/bin/env python
# coding=utf-8
# author: zengyuetian
# 此代码仅供学习与交流,请勿用于商业用途。
# 小区信息的数据结构
class XiaoQu(object):
def __init__(self, district, area, name, price, on_sale):
self.district = district
self.area = area
self.price = price
self.name = name
self.on_sale = on_sale... |
def trapes_areal(sideEn=float, sideTo=float, høyde=float):
""" Returnerer arealet til et trapes """
return ( ( sideEn+sideTo ) * høyde ) / 2
def trapes(funksjon, start=float, slutt=float, antall=int):
'''
Returnerer arealet under grafen ved å
bruke trapeser. ( Numerisk
Integras... |
# Standard tuning of each string
GUITAR_STAFF: dict = {0: 'E', 1: 'A', 2: 'D', 3: 'G', 4: 'B', 5: 'E'}
UKULELE_STAFF: dict = {0: 'G', 1: 'C', 2: 'E', 3: 'A'}
# Number of strings
GUITAR_STRING = 6
UKULELE_STRING = 4
# MIDI metadata
TIME_SIGNATURE = 'time_signature'
NOTE_ON = 'note_on'
NOTE_OFF = 'note_off'
HALF_NOTE =... |
#divide 2 numbers
x = int(input("Enter first number :"))
y = int(input("Enter second number :"))
answer = int(x/y)
remainder = x % y
print("{} divided by {} is {} with a remainder of {}".format(x,y,answer,remainder))
|
def return_true():
return True
if __name__ == "__main__":
print("shipit") |
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: the root node
@param L: an integer
@param R: an integer
@return: the sum
"""
def rangeSumBST(self, root, L, R):
... |
'''
Crie um programa que leia vários números inteiros pelo teclado. No final da execução, mostre a média entre
todos os valores e qual foi o maior e o menor valores lidos. O programa deve perguntar ao usuário se ele
quer ou não continuar a digitar valores.
'''
continuar = 'S'
acumulador = 0
contador = 0
numero = 0
med... |
#!python3.6
#encoding: utf-8
# https://teratail.com/questions/52151
class Deco:
def __init__(self): self.value = 'value'
def deco(func):
def wrapper(self, *args, **kwargs):
print('----- start -----')
print('self.value =', self.value) # AttributeError: 'C' object has no attribute ... |
expected_output = {
"Mgmt-intf": {
"address_family": {
"ipv4 unicast": {
"flags": "0x0",
"table_id": "0x1",
"vrf_label": {"allocation_mode": "per-prefix"},
}
},
"cli_format": "New",
"flags": "0x1808",
"in... |
#MenuTitle: Control Characters
# -*- coding: utf-8 -*-
__doc__="""
Creates a new tab with selected glyphs between control characters.
"""
Font = Glyphs.font
tab = ''
# supports latin, greek and cyrillic
uppercase = ["A", "Aacute", "Abreve", "Abreveacute", "Abrevedotbelow", "Abrevegrave", "Abrevehookabove", "Abrevetil... |
#
# Collective Knowledge (indexing through ElasticSearch)
#
# See CK LICENSE.txt for licensing details
# See CK COPYRIGHT.txt for copyright details
#
# Developer: Grigori Fursin
#
cfg = {} # Will be updated by CK (meta description of this module)
work = {} # Will be updated by CK (temporal data)
ck = None # Will be... |
class Solution:
def longestDupSubstring(self, s: str) -> str:
kMod = int(1e9) + 7
bestStart = -1
l = 1
r = len(s)
def val(c: str) -> int:
return ord(c) - ord('a')
# k := length of hashed substring
def getStart(k: int) -> Optional[int]:
maxPow = pow(26, k - 1, kMod)
hash... |
# parsetab.py
# This file is automatically generated. Do not edit.
# pylint: disable=W,C,R
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = "rightASSIGNrightNOTnonassocLESSEQ<=left+-left*/rightISVOIDleft~left@left.ASSIGN CASE CLASS COMMENT ELSE ESAC FALSE FI ID IF IN INHERITS INT ISVOID LESSEQ LET LOOP NEW N... |
class Truss(Element,IDisposable):
""" Represents all kinds of Trusses. """
def AttachChord(self,attachToElement,location,forceRemoveSketch):
"""
AttachChord(self: Truss,attachToElement: Element,location: TrussChordLocation,forceRemoveSketch: bool)
Attach a truss's specific chord to a specified element,th... |
# This is a simple example script for FL
# It should represent a webshop, or at least part of it
cart = {}
def addToCart(product):
if(product not in cart.keys()):
cart[str(product)] = 1
else:
cart[str(product)] = cart[(str(product))] + 2 # bug -> should be 1
def removeFromCart(product):
... |
# 796. 旋转字符串
#
# 20200728
# huao
# 这个好像和前面某个题一样的...
# 遍历,判断一下就好了
class Solution:
def rotateString(self, A: str, B: str) -> bool:
if A == '' and B == '':
return True
lenA = len(A)
lenB = len(B)
if lenA != lenB:
return False
for i in range(lenA):
... |
# 547.朋友圈(Medium)
# 班上有 N 名学生。其中有些人是朋友,有些则不是。
# 他们的友谊具有是传递性。如果已知 A 是 B 的朋友,B 是 C 的朋友,
# 那么我们可以认为 A 也是 C 的朋友。所谓的朋友圈,是指所有朋友的集合。
# 给定一个 N * N 的矩阵 M,表示班级中学生之间的朋友关系。
# 如果M[i][j] = 1,表示已知第 i 个和 j 个学生互为朋友关系,否则为不知道。
# 你必须输出所有学生中的已知的朋友圈总数。
# 示例 1:
# 输入:
# [[1,1,0],
# [1,1,0],
# [0,0,1]]
# 输出: 2
# 说明:已知学生0和学生1互为朋友... |
#
# PySNMP MIB module EXTRAHOP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EXTRAHOP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:53: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,... |
# -*- encoding: utf-8 -*-
"""Common exceptions for the inventory manager.
"""
class ExistingMACAddress(Exception):
code = 409
message = u'A server with the MAC address %(address)s already exists.'
def __init__(self, address, message=None, **kwargs):
"""
:param address: The conflicting M... |
#necesitamos dividir nuestro data set
#necesitamos el punto pivotal
#recursivamente ordenar cada mitad de mi array
def partition(arr, low, high):#creamos la particion del array
i = (low-1) # i va a tomar el valor del indice mas bajo low-1
pivot = arr[high] #valor medio de los datos, que separa los datos altos ... |
# ==============================================================================
# ARSC (A Relatively Simple Computer) License
# ==============================================================================
#
# ARSC is distributed under the following BSD-style license:
#
# Copyright (c) 2016-2017 Dzanan Bajgoric
# A... |
def SymbolToFromAtomicNumber(ATOM):
atoms = [ [1,"H"],[2,"He"],[3,"Li"],[4,"Be"],[5,"B"],[6,"C"],[7,"N"],[8,"O"],[9,"F"],[10,"Ne"], \
[11,"Na"],[12,"Mg"],[13,"Al"],[14,"Si"],[15,"P"],[16,"S"],[17,"Cl"],[18,"Ar"],[19,"K"],[20,"Ca"], \
[21,"Sc"],[22,"Ti"],[23,"V"],[24,"Cr"],[25,"Mn"],[26,"Fe"],[27... |
#!/usr/bin/python3
list = ["Binwalk","bulk-extractor","Capstone","chntpw","Cuckoo",
"dc3dd","ddrescue","DFF","diStorm3","Dumpzilla","extundelete",
"Foremost","Galleta","Guymager","iPhone Backup Analyzer","p0f",
"pdf-parser","pdfid","pdgmail","peepdf","RegRipper","Volatility","Xplico"] |
def solution(items):
"""
map(int, input.split())
Получить массив сумм двух чисел через 1
>>> solution([1, 2, 3, 4, 7, 2, 1, 1])
[5, 9]
"""
return list(map(sum, zip(items[1::3], items[2::3])))
"""
slice, zip, map, list
""" |
""" DNS Record Types """
# https://en.wikipedia.org/wiki/List_of_DNS_record_types
DNS_RECORD_TYPES = {
1: "A",
28: "AAAA",
18: "AFSDB",
42: "APL",
257: "CAA",
60: "CDNSKEY",
59: "CDS",
37: "CERT",
5: "CNAME",
62: "CSYNC",
49: "DHCID",
32769: "DLV",
39: "DNAME",
4... |
#####################################################################################
# 整个基于双指针的算法的解题逻辑是,记录下历史上拥有最大重复字母且其余字母之和不大于k的区间
# 当然记录这个区间的方式只是记录了那个最大重复字母的数量,毕竟原题不需要我们提供两个端点
# 而且在找到答案要求的最大后,即便再往后移动,如果不能找到重复字母更大的区间,即maxnum不增加
# right - left + 1 - maxnum会一直大于k,left会一直伴随right同时加1,因此区间大小不变
# 最后根据题目要求,返回替换后的最长子串长... |
#
# PySNMP MIB module CISCOSB-STACK-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-STACK-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:23:37 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
def config_fgsm(targeted, adv_ys):
if targeted:
yname = 'y_target'
else:
yname = 'y'
fgsm_params = {yname: adv_ys,
'eps': 0.3,
'clip_min': 0.,
'clip_max': 1.}
return fgsm_params
def config_bim(targeted, adv_ys):
if ta... |
n = int(input())
for i in range(1,n+1):
if ((n % i) == 0):
print(i,end=" ")
|
_base_ = [
'../_base_/models/faster_rcnn_r50_fpn.py',
'../_base_/datasets/coco_detection.py',
'../_base_/schedules/schedule_2x.py', '../_base_/default_runtime.py'
]
# model setting
model = dict(
backbone=dict(
init_cfg=None
),
roi_head=dict(
bbox_head=dict(
num_class... |
# 24. Swap Nodes in Pairs
# Runtime: 24 ms, faster than 96.60% of Python3 online submissions for Swap Nodes in Pairs.
# Memory Usage: 14 MB, less than 92.32% of Python3 online submissions for Swap Nodes in Pairs.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# ... |
'''
Created on 11 Apr 2020
@author: dkr85djo
'''
class md:
MAXCARDS = 106
class MDColourSet:
def __init__(self, value, names, hexcolour=b'#000000'):
self.value = value
self.names = names
self.hexcolour = hexcolour
def size(self):
return len(self.na... |
class Stack:
Top = -1
def __init__(self,size):
self.stack = [0 for i in range(size)]
def push(self, value):
if (Stack.Top!=len(self.stack)-1):
Stack.Top += 1
self.stack[Stack.Top] = value
else:
print("Overflow: Stack is Full")
def pop(self):
if (Stack.Top == -1):
pri... |
BASIC_PLUGINS = [
{
"name": "kubejobs",
"source": "",
"component": "manager",
"plugin_source": "",
"module": "kubejobs"
},
{
"name": "kubejobs",
"source": "",
"component": "controller",
"p... |
a = (2, 5, 4)
b = (5, 8, 1, 2)
c = a + b
print(c)
print(len(c))
print(c.count(5))# Quantas vezes aparece o '5' dentro de 'c'
print(c.index(8)) #Em que posição está o valor '8'
pessoa = ('Gustavo', 39, 'M', 99.88)
print(pessoa)
del (pessoa) #Apaga a tupla 'pessoa'
print(pessoa)
|
""" TIMEFLIESBAR PROGRESS_BAR FUNCTION """
# Contact.
# ovgpcomms@outlook.com
# ---------------------------------------------------------------------------#
# Pass-trough variables.
tm: int
""" total_minutes from tfb_calculus. """
gm: int
""" gone_minutes from tfb_calculus. """
# Regular variables.
percent_decim... |
#!usr/bin/python
# -*- coding:utf8 -*-
"""
翻转字符数组 https://leetcode.com/problems/reverse-string/
s是一个字符串列表
1. s.reverse
"""
class Solution:
def reverseString(self, s):
"""
Do not return anything, modify s in-place instead.
"""
beg = 0
end = len(s) - 1
while beg < en... |
refTable = [{'desc': 'Freedom of Movement', 'templates': ['free'], 'weight': 1.0},
{'desc': 'Visa not Required', 'templates': ['yes', 'yes '], 'weight': 0.9},
{'desc': 'Visa on Arrival',
'templates': ['Optional', 'yes-no'],
'weight': 0.7},
{'desc': 'Electronic Visa', 'templates': ['yes2'], 'weight': 0.5},
{'des... |
class Solution:
def romanToInt(self, s: str) -> int:
romanNumberAsc = ['I', 'V', 'X', 'L', 'C', 'D', 'M'];
numberMapForRoman = [1, 5, 10, 50, 100, 500, 1000];
lenOfRomanNumber = len(s);
integer = 0;
# 从前往后遍历,如果当前字符大于或等于后面的字符,则累加,否则则减去当前字符
for i in range(lenOfRomanNu... |
# builtins stub used in boolean-related test cases.
class object:
def __init__(self) -> None: pass
class type: pass
class bool: pass
class int: pass
|
"""Information regarding crosstool-supported architectures."""
# Copyright 2017 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apach... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.