content stringlengths 7 1.05M |
|---|
#!/usr/bin/env python
'''
Seed_match.py:
Check seed matching between miRNA and TargetRNA
<Rules>
WC => Watson-Crick match
GU => G:U Wobble
-------------------------------
seed_length = 8
-------------------------------
8mer: p1-p8 WC match
8mer-1A: p1=A, p2-p8 WC match
7mer-m8: p2-p8 WC match
7mer-m1: p1... |
# python3
def prefix_function(string):
'''prefixs[i] is the length of the longest border of the prefix string[0:i]'''
len_str = len(string)
prefixs = [None for _ in range(len_str)]
prefixs[0] = 0
border = 0
for index in range(1, len_str):
# decrease border size
while borde... |
'''8.5 Open the file mbox-short.txt and read it line by line.
When you find a line that starts with 'From ' like the following line:
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
You will parse the From line using split() and print out the second word in the line
(i.e. the entire address of the person wh... |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 27 12:37:17 2021
@author: Easin
"""
in1 = input()
in1 = int(in1)
for elements in range(in1):
in2 = input()
in2 = int(in2)
a = input().split()
list1 = []
for elem in range(len(a)):
list1.append(int(a[elem]))
list1.sort... |
# -*- coding: utf-8 -*-
pytest_plugins = [
"fixtures.fixtures_app",
"fixtures.fixtures_db",
"fixtures.fixtures_auth",
]
|
_base_ = 'retinanet_pvtv2-b0_fpn_1x_coco.py'
model = dict(
backbone=dict(
embed_dims=64,
num_layers=[3, 6, 40, 3],
mlp_ratios=(4, 4, 4, 4),
init_cfg=dict(checkpoint='https://github.com/whai362/PVT/'
'releases/download/v2/pvt_v2_b5.pth')),
neck=dict(in_channe... |
#!/usr/bin/env python
"""
https://leetcode.com/problems/roman-to-integer/description/
Created on 2018-11-07
@author: 'Jiezhi.G@gmail.com'
Reference:
"""
romanDict = dict([('I', 1), ('V', 5), ('X', 10), ('L', 50), ('C', 100), ('D', 500), ('M', 1000)])
class Solution:
def romanToInt(self, s):
"""
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
def get_max_gain(node):
... |
"""
============
readthestuff
============
Yet another Google Reader alternative built on top of Python.
"""
|
def main():
x = raw_input("What's your name? ")
a = int(raw_input("Inform an integer: "))
b = float(raw_input("Inform a float: "))
print("Your name is %s") % (x)
print("Integer number: %i") % (a)
print("Float number: %.2f") % (b)
main() |
class Solution(object):
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
# import os
# return os.path.abspath(path)
stack = []
for p in path.split("/"):
if(p == ".."):
if stack:
stack.pop... |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Weather, obj[2]: Time, obj[3]: Coupon, obj[4]: Coupon_validity, obj[5]: Gender, obj[6]: Age, obj[7]: Maritalstatus, obj[8]: Children, obj[9]: Education, obj[10]: Occupation, obj[11]: Income, obj[12]: Bar, obj[13]: Coffeehouse, obj[14]: Restaurant20to50, obj[15]: Direct... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Assembly Parser
Author: n-vizion / info@stackevolve.com
"""
# todo - change from lists to set for speed and performance
class ParseAsm:
def __init__(self, asm_file):
self.asm_file = asm_file
# return code
self.r_code = ""
self.start = 0
self.asm = ""
se... |
class PenguinTiles:
def minMoves(self, tiles):
rc, cc = len(tiles), len(tiles[0])
for i, r in enumerate(tiles):
for j, c in enumerate(r):
if c == '.':
return (rc-1 != i) + (cc-1 != j)
return 0
|
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
... |
num1=7
num2=9
#add two numbers
sum=float(num1) + float(num2)
#display the sum
print('the sum of {0} and {1} is {2}'.format(num1, num2, sum))
print ("hello")
print ("hi")
print (1+2+4-8-7+9+93-8)
number1=98
number2=76
#add two numbers
sum=float(number1) + (number2)
#display the sum
print ('sum of {0} and... |
'''
Given arc, kui index, data dictionary, slots
Runs PRIP algorithm and returns slots.
'''
def PRIP(data_dict, kui_idx, arc, slot_sizes):
print(slot_sizes)
s_type = 0
item_placed = 0
slot_type_arr = []
CAS = []
num_slots = len(slot_sizes)
total_slots = 0
slots = []
for i in range(... |
class VectorHashTestEnum:
DATA_IN = 'Msg'
DATA_LEN = 'Len'
EXP = 'Exp' |
s = input("digite um valor em segundos: ")
h = int(int(s)/3600)
m = int((int(s)%3600)/60)
s = int((int(s)%3600)%60)
print (str(h)+":"+str(m)+":"+str(s))
|
def count_inversions(ints):
"""
count inversions with mergesort
"""
# base case
n = len(ints)
if n == 1:
return 0, ints
# count left and right half recursively
nums_l, sort_l = count_inversions(ints[:n//2])
nums_r, sort_r = count_inversions(ints[n//2:])
# mersort and coun... |
class Pin:
def __init__(self, node, pin_type, channel, bit):
self.node = node
self.pin_type = pin_type
self.channel = channel
self.bit = bit
async def read(self):
if self.pin_type == 'input':
channel_state = await self.node.inputs[self.channel].read()
... |
disk = {}
disk['SR4'] = {'name': 'SR4',
'label': 'SR 4',
'distance': 134.8,
'incl': 22.0,
'PA': 18.0,
'dx': -0.060,
'dy': -0.509,
'rgap': [0.079],
'wg... |
'''
script que faz a conversão de metros para as demais distancias
'''
distancia = float(input('digite a distancia em metros: '))
km = distancia / 1000
hm = distancia / 100
dam = distancia / 10
dm = distancia * 10
cm = distancia * 100
mm = distancia * 1000
print(f'a medida de {distancia:.1f}m corresponde a')
print(f... |
def solve(n, arr):
ret: list[int] = [0] * 100
for i in range(0, n):
ret[arr[i]] += 1
return ret
if __name__ == "__main__":
n = int(input().strip())
arr = list(map(int, input().rstrip().split()))
result = solve(n, arr)
print(" ".join(map(str, result))) |
# 6. Write a simple function (area_circle) that returns the area
# of a circle of a given radius.
def area_circle(r):
''' Calculate the area of a circle given the radius
r = radius (in some unstated unit of measurement)
'''
return 3.1415926536 * (r ** 2)
def main():
print('Test case')
p... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def distanceK(self, root, target, K):
"""
:type root: TreeNode
:type target: TreeNode
:type K: int
... |
# Classes and methods whitelist
core = {'': ['absdiff', 'add', 'addWeighted', 'bitwise_and', 'bitwise_not', 'bitwise_or', 'bitwise_xor', 'cartToPolar',\
'compare', 'convertScaleAbs', 'copyMakeBorder', 'countNonZero', 'determinant', 'dft', 'divide', 'eigen', \
'exp', 'flip', 'getOptimalDFTSize'... |
# Time: O(m * n)
# Space: O(m + n)
class Solution(object):
# @return an integer
def uniquePaths(self, m, n):
if m < n:
return self.uniquePaths(n, m)
ways = [1] * n
for i in xrange(1, m):
for j in xrange(1, n):
ways[j] += ways[j - 1]
ret... |
# This program uses a loop to display a
# table of numbers and their squares.
print('This program displays a list of numbers')
print('(starting at 1) and their squares.')
end = int(input('How high should I go? '))
print()
print('Number\tSquare')
print('--------------')
for number in range(1, end + 1):
square = n... |
#coding: utf-8
''' mbinary
#######################################################################
# File : fastPow.py
# Author: mbinary
# Mail: zhuheqin1@gmail.com
# Blog: https://mbinary.xyz
# Github: https://github.com/mbinary
# Created Time: 2018-12-17 21:39
# Description: fast power
##############################... |
class Iterator(object):
"""Base class of all dataset iterators.
Iterator iterates over the dataset, yielding a minibatch at each
iteration. Minibatch is a list of examples. Each implementation should
implement an iterator protocol (e.g., the :meth:`__next__` method).
Note that, even if the iterat... |
def domain_name(url):
for i in ['www.', '//']:
if i in url:
return url.split(i)[1][:url.split(i)[1].find('.')]
return url[:url.find('.')]
|
# -*- coding: utf-8 -*-
__author__ = 'R. M. Parrondo'
__email__ = 'aroy@alum.mit.edu'
__version__ = '0.1.0'
|
def init_app(app):
app.config["SECRET_KEY"] = "passW0rd01"
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///foodelivery.db"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["FLASK_ADMIN_SWATCH"] = "cerulean"
app.config["DEBUG_TB_INTERCEPT_REDIRECTS"] = False
if app.debug:
... |
class Solution:
def integerBreak(self, n):
"""
:type n: int
:rtype: int
"""
if n == 2:
return 1
elif n == 3:
return 2
elif n%3 == 0:
return pow(3,n//3)
elif n%3 == 1:
return pow(3,n//3 -1)*4
elif ... |
# # 可变对象
# a = [1,2,3]
# print('修改前:', a , id(a))
# # 通过索引修改列表
# a[0] = 10
# print('修改后:', a , id(a))
# # 为变量重新赋值
# a = [4,5,6]
# print('修改后:', a , id(a))
a = [1, 2, 3]
b = a
# b[0] = 10
b = [10, 2, 3]
# print("a",a,id(a))
# print("b",b,id(b))
# == != is is not
# == != 比较的是对象的值是否相等
# is is ... |
# Case1 : 반복문 내에 조건에 해당하는 값 출력하기
print("==================Case1==================")
# 입력 받은 n개만큼 0 ~ 9 사이의 짝수 출력하기
# n 회 동안 짝수의 총합 출력하기
n = int(input())
def even_sum():
sum = 0
for i in range(n):
print(f'i : {i}')
for j in range(9):
if j % 2 == 0:
print(j)
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 28 13:33:54 2019
Programa que permite contar
las vocales dentro de una palabra
@author: Luis Cobian
"""
palabra = input("Una palabra: ")
palabra = palabra.lower();
a = palabra.count("a");
e = palabra.count("e");
i = palabra.count("i");
o = palabra.count("o");
u = palabr... |
N, K = map(int, input().split())
tmp, answer = N, 1
while True:
tmp = tmp // K
if tmp == 0:
break
answer += 1
print(answer) |
# Create a tuple named zoo that contains your favorite animals.
zoo = ("Armadillo", "Turtle", "Hedgehog", "Tree Frog")
# Find one of your animals using the .index(value) method on the tuple.
print(zoo.index("Hedgehog"))
# Determine if an animal is in your tuple by using for value in tuple.
if "Koala" in zoo:
pri... |
"""
文件写方法 示例
"""
# 打开一个文件
file = open("file.txt",'w')
# 追加方式打开
# file = open("file.txt",'a')
# 写入内容
# file.write("hello,死鬼\n")
# n = file.write("哎呀,干啥\n")
# print("写入 %d 字节"%n)
# 将列表写入文件
data = [
"先帝创业未半\n",
"而中道崩殂\n"
]
file.writelines(data)
# 关闭
file.close() |
"""
@author: Deniz Altinbuken, Emin Gun Sirer
@note: Example jobmanager
@copyright: See LICENSE
"""
class JobManager():
def __init__(self):
self.jobs = []
def schedule(self, job):
self.jobs.append(job)
def deschedule(self, job):
self.jobs.remove(job)
def update(self, job, key,... |
# (C) Datadog, Inc. 2019-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
NODE_METRICS_MAP = {
'go_gc_duration_seconds': 'go.gc.duration.seconds',
'go_goroutines': 'go.goroutines',
'go_info': 'go.info',
'go_memstats_alloc_bytes': 'go.memstats.alloc.bytes',
'g... |
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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 ... |
SECRET_KEY = "12345"
DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}}
INSTALLED_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"wagtail.users",
"wagtail.admin",
"wagtail.images",
"wagtail.core",
"tests.my_app",
]
AUTH_PASSWORD_VALIDATOR... |
"""
This unit test checks that we get a RepyArgumentError
when providing bad arguments to listenforconnection.
"""
#pragma repy
def tryit(ip,port):
try:
listenforconnection(ip,port)
log("Bad combination worked! IP:"+str(ip)+" Port: "+str(port),'\n')
except:
pass
# Try some bad combos
tryit(None, None)... |
f = open("sample.txt", mode="r", encoding="utf-8")
f2 = open("sample3.txt", mode="w", encoding="utf-8")
f2.write(f.read())
f2 = open("sample3.txt", mode="r", encoding="utf-8")
print("Reading contents present inside sample3.txt:")
print(f2.read()) |
"""This class implements a very thin layer to store metadata in a string."""
class SequenceString(str):
def __new__(self, value, metadata=None):
return str.__new__(self, value)
def __init__(self, value, metadata=None):
self.metadata = metadata or {}
@staticmethod
def from_record(reco... |
# Created by MechAviv
# ID :: [865090003]
# Unknown : Unknown
sm.curNodeEventEnd(True)
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(True, False, False, False)
sm.setStandAloneMode(True)
sm.hideUser(True)
sm.createFieldTextEffect("#fn나눔고딕 ExtraBold##fs26#That Evening", 100, 2500, 4, 0, 0, 1, 4, 0, 0, 0)
sm.send... |
"""
Contains methods for generating new input_0.py files
This will help us do more "generations" of reactions
"""
# I couldn't find a way to access these from the reaction model itself
# TODO: Access these from the models, instead of providing it explicitly
temperature = 800
pressure = 1.0
def clean_prev(current_fil... |
###############################################################################
# Copyright Maciej Patro (maciej.patro@gmail.com)
# MIT License
###############################################################################
def input_data(parser):
parser.add_argument('input',
type=str,
... |
gray = {}
gray[100] = "#f8f9fa"
gray[200] = "#ecf0f1"
gray[300] = "#dee2e6"
gray[400] = "#ced4da"
gray[500] = "#b4bcc2"
gray[600] = "#95a5a6"
gray[700] = "#7b8a8b"
gray[800] = "#343a40"
gray[900] = "#212529"
blue = "#3d91f2"
indigo = "#6610f2"
purple = "#6f42c1"
pink = "#e83e8c"
red = "#e74c3c"
orange = "#fd7e14"
yell... |
''' Provides helpers for working with bits and bytes. '''
# Provides a quick list of JDEC JEP106 designer IDs.
JDEC_JEP106 = {
571: 'ARM (0x23B)'
}
def to_bit_list(entries, width=8, bitflip=False):
''' Convert interger list to a list of bits. '''
result = []
# TODO: Do this without string formatting... |
# =========================================================================
#
# Copyright COS 397
#
# 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/license... |
# 最长回文串
# https://leetcode-cn.com/problems/longest-palindromic-substring/
class Solution:
def longestPalindrome(self, s: str) -> str:
length = len(s)
rl = rr = 0
for i in range(length):
left = right = i
while left > 0 and s[left - 1] == s[i]:
left -= 1... |
"""
This is a simple config file holding an array of packages for each subtype that exists
"""
# packages required for everything
GENERAL_PACKAGES=["git"]
# packages required to build the repository
REPO_PACKAGES=["python-sphinx", "rust", "pacman-contrib", "i3lock-color-git", "dkms", "xorg-xset", "unzip", "asciidoc",... |
class Container:
def __init__(self, container_id):
self.container_id = container_id
|
# Defaults
peaks_QC, cut_spikes_QC, cut_spikes_holding_QC, cut_spikes_baselined_QC, parameters_QC = spikesQC(
file_name, peaks, peaks_properties,
cut_spikes, cut_spikes_holding, cut_spikes_baselined,
filter_by = ['p', 'wh', 'pw', 'ph', 'pb', 'lb', 'rb'],
QC_p_min = float('-inf'), QC_p_max = float('inf')... |
i, j = ( 3, 9 )
print(i, j)
for i, j in[(1, 2), (3, 4), (5, 6)]:
print(i, j)
|
"""Serveradmin - adminapi
Copyright (c) 2021 InnoGames GmbH
"""
VERSION = (4, 3, 0)
|
persn1 = "Taufiq"
persn2 = "Naufal"
persons = ["Taufiq", "Naufal", "Syamsul", "Yessy", "Ervan"]
persons[0] # accessing data
persons[0] = "Dedy" # changing list data
# insert data berdasarkan index, lalu memberikan isi data untuk index tersebut
persons.insert(2,"Tohari")
print(persons)
# menambahkan data pada list... |
"""
问题: 把n个骰子扔在地上,所有的骰子朝上一面的点数之和为s。输入n,打印出
s的所有可能的值出现的概率
"""
class Probability:
def __init__(self):
self.max_value = 6
def get_probability(self, n):
if n < 1:
return
probalities = [0 for _ in range(self.max_value*n-n+1)]
self.process(n, probalities)
total... |
# Copyright 2018 Databricks, Inc.
VERSION = '1.7.1.dev0'
|
principle = 5000
interest_rate = 0.035
# interest = principle * interest_rate
# principle = principle + interest #this is equivalent to below
for i in range(5):
principle += principle * interest_rate
print(f'Principle: ${principle:0.2f}')
# principle *= 1 + interest_rate #equivalent but less readable
x = 8
# str... |
#primeiro e último nome de uma pessoa.
#Faça um programa que leia o nome completo de uma pessoa , mostrando em Seguida o primeiro e o último nome separadamente.
n=str(input('\033[7;30;44mDigite seu nome completo:\033[m'))
nome=n.split()
print('\033[1;36m muito prozer em te conhecer!')
print('Seu primeiro nome é {}'.for... |
for _ in range(3):
record = list(map(int, input().split()))
opening = 3600 * record[0] + 60 * record[1] + record[2]
closing = 3600 * record[3] + 60 * record[4] + record[5]
office_hour = closing - opening
print(office_hour // 3600, office_hour % 3600 // 60, office_hour % 60)
|
class ApiError(Exception):
"""
Follows the RFC 7807 standard https://tools.ietf.org/html/rfc7807
Example Usage:
{
"type": "https://example.com/probs/out-of-credit",
"title": "You do not have enough credit.",
"detail": "Your current balance is 30, but that costs 50.",
... |
"""
Copyright (c) 2015 Michael Bright and Bamboo HR LLC
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... |
def _check_test_type(tt: str):
if tt == "two-tailed" or tt == "left-tailed" or tt == "right-tailed":
pass
else:
raise AttributeError(
"Test type should be whether 'two-tailed' or 'left-tailed' or 'right-tailed'"
)
def _check_others(*args):
for cl in args:
if cl ... |
# This file is part of the Python aiocoap library project.
#
# Copyright (c) 2012-2014 Maciej Wasilak <http://sixpinetrees.blogspot.com/>,
# 2013-2014 Christian Amsüss <c.amsuess@energyharvesting.at>
#
# aiocoap is free software, this file is published under the MIT license as
# described in the accompany... |
# There are so many different approaches and so many different ways to implement each. I find it hard to decide, so here are several: -)
# In all of them, I check one of these tree characterizations:
# Has n - 1 edges and is acyclic.
# Has n - 1 edges and is connected.
# Solution 1 ... Union - Find
# The test cases ... |
def solver_function(L1: list, L2: list, C1: list, C2: list,
C_max: int) -> QuantumCircuit:
# the number of qubits representing answers
index_qubits = len(L1)
# the maximum possible total cost
max_c = sum([max(l0, l1) for l0, l1 in zip(C1, C2)])
min_c = sum([min(l0, l1) for l0, ... |
# Crie um programa que leia um numero inteiro e mostre na tela se é par ou impar
num = int(input('Digite um numero: '))
div = num % 2
if div == 0:
print('Este numero é par!!')
else:
print('Este Numero é Impar!!')
|
# tables.py
class MortalityTable:
"""mortalitytable is a matrix, by age and duration."""
def __init__(self, csv_filename, name, select_period, pc_of_base=1):
self.filename = csv_filename
self.name = name
self.select_period = select_period
self.pc_of_base = pc_of_base... |
try:
# Write normal code here. This block must include
# code that falls into two groups:
# 1. Code that may cause an exception to be raised
# 2. Code that depends on the results from the code
# in the first group
pass
except ZeroDivisionError as zero_div_err:
# Code that the computer execut... |
num , need = map(int, input().split())
arr = list(map(int, input().split()))
#sys.stdin.readline().strip()
i = 0
j = 0
check = 0;
sum = 0
while i <= len(arr):
if(i != len(arr)):
if sum < need:
sum += arr[i]
i += 1
elif sum > need:
sum -= arr[j]
... |
"""
Pieces
"""
EMPTY = (0, 0, 0)
GARBAGE = (150, 150, 150)
Z_PIECE = (0, 20, 255)
S_PIECE = (10, 255, 100)
O_PIECE = (20, 255, 255)
T_PIECE = (255, 0, 127)
J_PIECE = (255, 100, 0)
L_PIECE = (30, 160, 220)
I_PIECE = (220, 220, 0)
UNKNOWN = (255, 255, 255)
|
n = int(input())
for i in range(n):
vet = list(map(float, input().split()))
pa = int(vet[0])
pb = int(vet[1])
cresA = vet[2]/100
cresB = vet[3]/100
tempo = 0
while pa < pb:
pa += int(pa * cresA)
pb += int(pb * cresB)
tempo += 1
if tempo > 100 or pa > pb:
... |
class Repository:
def __init__(self, user, name):
self.user = user
self.name = name
@classmethod
def fromList(cls, repositories):
for user, name in repositories:
yield cls(user, name)
def __str__(self):
return "{}/{}".format(self.user, self.name)
|
i=input()
if "0000000" in i:
print("YES")
else:
print("NO") |
def for_Reverse_Left_faced_Right_Angled_Triangle():
""" pattern for : Reverse_Left_faced_Right_Angled_Triangle"""
for i in range(5):
for j in range(5):
if i<=j:
print('*',end=' ')
else:
print(' ',end=' ')
print()
def while_Reverse_... |
nfolds = 4
random_seed = 0
classifier_head_str = 'RandomForestClassifierHead(n_estimators=500, n_jobs=-1)'
feature_extractor_str = 'TFIDFFeatureExtractor(max_features=1000)'
work_dir = 'artifacts/base' |
# -*- coding: utf-8 -*-
"""
.. module:: composite.fields
:synopsis: Fields
.. moduleauthor:: NickolasFox <tarvitz@blacklibrary.ru>
.. sectionauthor:: NickolasFox <tarvitz@blacklibrary.ru>
"""
class BaseField(object):
"""
Base Field abstract class
"""
__slots__ = ['name', 'type', 'default']
de... |
# if文で処理を分岐できる。
if a == 1:
print('a is 1') # if文の式が真のときに実行される。
elif a == 2:
print('a is 2') # elif節の式が真のときに実行される(elif節は無くてもよい)。
else:
print('a is not 1 nor 2') # どの条件にも当てはまらなかったときに実行される(else節は無くてもよい)。
print('a is 1' if a == 1 else 'a is not 1') # 条件式で1行で書ける。可読性が下がるので多用しない。
|
LANDSCAPE = 'landscape'
PORTRAIT = 'portrait'
SQUARE = 'square'
PAD = 'pad'
CROP = 'crop'
RESIZE = 'resize'
|
def parse_rooms_from_db(data):
rooms = list()
for i in data:
tmp = i[4]
if tmp == None:
tmp = 0
rooms.append(Room(i[0], i[1], i[2], i[3], tmp, i[5]))
return rooms
class Room():
def __init__(self, id, name, desc, master, signed, lim_in_room):
self.id =... |
#!env/bin/python
"""Port of mailcheck.js
https://github.com/mailcheck/pymailcheck/
"""
DOMAIN_THRESHOLD = 2
SECOND_LEVEL_THRESHOLD = 2
TOP_LEVEL_THRESHOLD = 2
DOMAINS = frozenset([
"aim.com",
"aol.com",
"att.net",
"bellsouth.net",
"btinternet.com",
"charter.net",
"comcast.net",
"cox.ne... |
class Order:
def __init__(self, order_number, customer_id, lp_number, category, pickup_date, return_date, price, insurance, actual_return_date):
self.__order_number = order_number
self.__customer_id = customer_id
self.__lp_number = lp_number
self.__category = category
se... |
S=int(input('Enter the Size: '))
TSUM=int(input('Enter Target Sum: '))
a=[]
for i in range(S):
a.append(int(input('Enter the array ElementS: ')))
def Quadruple(a,TSUM):
a.sort()
for i in range(S-3):
for j in range(i+1,S-2):
k=TSUM-(a[i]+a[j])
l=j+1
h=S-1
... |
#!/usr/bin/env python3
"""
:author Wang Weiwei <email>weiwei02@vip.qq.com / weiwei.wang@100credit.com</email>
:sine 2017/8/11
:version 1.0
""" |
# Autogenerated by devscripts/update-version.py
__version__ = '2022.02.03'
RELEASE_GIT_HEAD = '28469edd7'
|
class Settings:
def __init__(self, public_key, private_key, mode):
self.api_key = public_key
self.secret_key = private_key
if mode == "test":
self.url = "https://bz-sandbox.opay-test.net/api/"
else:
self.url = "https://operapay.com/api/"
self.access... |
"""
根据列表中的数字,重复生成*.
list01 = [1, 2, 3, 4, 5, 4, 3, 2, 1]
效果:
*
**
***
****
*****
****
***
**
*
"""
list01 = [1, 2, 3, 4, 5, 4, 3, 2, 1]
for item in list01:
print(item*"*")
|
class Cell:
def __init__(self, num):
self.num = num
def __setattr__(self, attr, value):
if attr == "num":
self.__dict__[attr] = value
else:
print(f"Атрибут {attr} недопустим")
def __str__(self):
return str(self.num)
def __add__(self, other):
... |
{
"targets": [
{
"target_name": "pikchr",
"sources": ["pikchr.cc"],
'dependencies': ['libpikchr'],
'conditions': [
['OS=="linux"', {
'libraries': ["<(module_root_dir)/build/Release/pikchr.a"]
}],
['OS=="win"', {
'librari... |
'''
Utilities for the caps_options
(functions needed for defining caps-options easily)
Created on Jul 25, 2011
@author: shai
'''
# Key types for supporting caps lock behaviors
EIGHT_LEVEL = 'EIGHT_LEVEL'
SIX_LEVEL = 'SIX_LEVEL'
FOUR_LEVEL = 'FOUR_LEVEL_ALPHABETIC'
CAPS_KEY_TYPES = frozenset([EIGHT_LEVEL, SIX_LEVEL,... |
class GalleryAction():
def __init__(self, icon, name, tooltip=None):
self._icon = icon
self._name = name
self._tooltip = tooltip
@property
def tooltip(self):
return self._tooltip
@tooltip.setter
def tooltip(self, value):
self._tooltip = value
@property
... |
'''
Exceptions from sqlstr
-------------------------
'''
class sqlstrException(Exception):
def __init__(self, message):
'''
Instanitates a custom sqlstrException
message -- string. Message describing the exception.
'''
Exception.__init__(self, message)
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
dp = [startFuel] + [0] * len(stations) # Initialize dp
for i, (loc, cap) in enumerate(stations): # Traversing the gas station
for t in range(i, -1, -1):
if dp[t] >=... |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Run `{dnf,yum} makecache` on each of the specified snapshots.
This is meant to be run on an image right after `install_rpm_repo_snapsho... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.