content stringlengths 7 1.05M |
|---|
"""
1. 引用计数
最简单直接的办法, 对每个对象维护一个引用计数, 起始为1.
缺点:
维护引用计数消耗资源
循环引用有内存泄漏
"""
class A:
def __init__(self, b):
self.a = 10
self.b = b
class B:
def __init__(self, a):
self.b = 10
self.a = a
|
"""Constants"""
DOMAIN = "grocy"
DOMAIN_DATA = "{}_data".format(DOMAIN)
DOMAIN_EVENT = "grocy_updated"
DOMAIN_SERVICE = "{}"
# Integration local data
DATA_GROCY = "grocy"
DATA_DATA = "data"
DATA_ENTITIES = "entities"
DATA_STORE_CONF = "store_conf"
# Domain events
EVENT_ADDED_TO_LIST='added_to_list'
EVENT_SUBTRACT_F... |
number_for_fibonacci = int(input("Enter Fibonacci number: "))
first_num = 0
second_num = 1
while second_num <= number_for_fibonacci:
print(second_num)
first_num, second_num = second_num, first_num + second_num
print("Fibonacci number") |
def collected_materials(key_materials_dict:dict, junk_materials_dict:dict, material:str, quantity:int):
if material=="shards" or material=="fragments" or material=="motes":
key_materials_dict[material]+=quantity
else:
if material not in junk_materials.keys():
junk_materials[material]... |
t_host = "localhost"
t_port = "5432"
t_dbname = "insert_db_name"
t_user = "insert_user"
t_pw = "insert_pw"
photo_request_data = {
"CAD6E": {
"id": 218,
"coords_x": -5.9357153,
"coords_y": 54.5974748,
"land_hash": "1530850C9A6F5FF56B66AC16301584EC"
},
"TES... |
def pad_in(string: str, space: int) -> str:
"""
>>> pad_in('abc', 0)
'abc'
>>> pad_in('abc', 2)
' abc'
"""
return "".join([" "] * space) + string
def without_ends(string: str) -> str:
"""
>>> without_ends('abc')
'b'
"""
return string[1:-1]
def without_first(string: ... |
def algorithm(K1,K2, B, weight_vec, datapoints, true_labels, lambda_lasso, penalty_func_name='norm1', calculate_score=False):
'''
Outer loop is gradient ascent algorithm, the variable 'new_weight_vec' here is the dual variable we are interested in
Inner loop is still our Nlasso algorithm
:para... |
#!/usr/bin/env python2
class RDHSSet:
def __init__(self, path):
with open(path, 'r') as f:
self.regions = [ tuple(line.strip().split()[:4]) for line in f ]
self.indexmap = { x: i for i, x in enumerate(self.regions) }
self.accessionIndexMap = { x[-1]: i for i, x in enumerate(sel... |
def getLeapYear(year):
while True:
if year%400==0:
return year
elif year%4==0 and year%100!=0:
return year
else:
year +=1
if __name__=='__main__':
leap_year_list = []
cur_year = int(input("Enter any year :"))
leap_year = getLeapYear(cur_year)
for i in range(15):
leap_year_list.append(leap_year)... |
for number in range(1, 101):
if number % 3 == 0 and number % 5 == 0:
print(f"{number} FizzBuzz")
elif number % 3 == 0:
print(f"{number} Fizz")
elif number % 5 == 0:
print(f"{number} Buzz")
else:
print(number)
|
{{notice}}
workers = 4
errorlog = "{{proj_root}}/run/log/gunicorn.error"
accesslog = "{{proj_root}}/run/log/gunicorn.access"
loglevel = "debug"
bind = ["127.0.0.1:9001"]
|
class Relevance(object):
'''Incooperation with result file and qrels file
Attributes:
qid, int, query id
judgement_docid_list: list of list, judged docids in TREC qrels
supervised_docid_list: list, top docids from unsupervised models, e.g. BM25, QL.
'''
def __init__(self, qid, judged_docid_... |
# -*- coding: utf-8 -*-
"""
@author: Ing. Víctor Fabián Castro Pérez
"""
def imprimealgo():
print ("Esta es la cadena que se imprime de la funcion MiFuncion\n")
|
astr = '\thello '
astr.strip() # 去除两端空白字符
astr.lstrip() # 去除左端空白字符
astr.rstrip() # 去除右端空白字符
'hello.tar.gz'.split('.')
hi = 'hello world'
hi.title()
hi.upper()
hi.lower()
hi.islower()
'hao123'.isdigit()
hi.isidentifier()
hi.center(50)
hi.center(50, '#')
hi.ljust(50)
hi.rjust(50)
hi.startswith('he')
hi.endswith('d')... |
#!/usr/bin/env python
# encoding: utf-8
"""
@author: Bocheng.Zhang
@license: Apache Licence
@contact: bocheng0000@gmail.com
@file: config.py
@time: 2019/11/6 10:35
"""
# [environment]
ela_url = "coreservices-mainchain-privnet.elastos.org"
did_url = "coreservices-didsidechain-privnet.elastos.org"
# faucet account
fa... |
def our_range(*args):
start = 0
end = 10
step = 1
if len(args) == 1:
end = args[0]
elif 2 <= len(args) <= 3:
start = args[0]
end = args[1]
if len(args) == 3:
step = args[2]
elif len(args) > 3:
raise SyntaxError
i = start
while i < end... |
##################################################
# 基本設定
# 変更した設定は次回起動時から適用されます
##################################################
# 接続するチャンネル
channel = "__Your_Channel__"
# Botのカラー 下の中から選択
# 'Red','Blue','Green','Firebrick','Coral','YellowGreen',
# 'OrengeRed','SeaGreen','GoldenRod','Chocolate','CadetBlue',
# 'Do... |
"""
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example:
board =
[
['A','B','C','E'],
['S','F... |
def part1(input_data):
numbers, boards = parse_input(input_data)
for number in numbers:
# Put number on all boards
for board in boards:
for row in board:
for i in range(len(row)):
if number == row[i]:
row[i] = "x"
... |
load("@bazel_skylib//lib:paths.bzl", "paths")
load(
"//caffe2/test:defs.bzl",
"define_tests",
)
def define_pipeline_tests():
test_files = native.glob(["**/test_*.py"])
TESTS = {}
for test_file in test_files:
test_file_name = paths.basename(test_file)
test_name = test_file_name.rep... |
# definitions.py
IbConfig = {
'telepotChatId': '572145851',
'googleServiceKeyFile' : 'GoogleCloudServiceKey.json',
'telepotToken' : '679545486:AAEbCBdedlJ1lxFXpN1a-J-6LfgFQ4cAp04',
'startMessage' : 'Hallo, ich bin unsere dolmetschende Eule. Stelle mich bitte auf deine Handflaeche und ich sage dir, was d... |
class Graph:
def __init__(self,nodes,edges):
self.graph=[]
for i in range(nodes+1):
self.graph.append([])
self.visited=[False]*(len(self.graph))
def addEdge(self,v1,v2):
self.graph[v1].append(v2)
def dfs(self,source):
self.visited[source]=True
print(source)
for i in self.graph[source]:
if not s... |
grupo = []
somai = 0
dados = {}
while True:
dados.clear()
dados['nome'] = str(input('Nome: ')).strip().capitalize()
while True:
dados['sexo'] = str(input('Sexo [M/F]: ')).upper().strip()[0]
if dados['sexo'] in 'MF':
break
print('Por favor digite apenas M ou F.')
dados... |
inp = list(map(float, input().split()))
inp.sort(reverse=True)
a, b, c = inp
if a >= b + c:
print('NAO FORMA TRIANGULO')
else:
if a ** 2 == b ** 2 + c ** 2:
print('TRIANGULO RETANGULO')
elif a ** 2 > b ** 2 + c ** 2:
print('TRIANGULO OBTUSANGULO')
else:
print('TRIANGULO ACUTAN... |
__all__ = ['CONFIG', 'get']
CONFIG = {
'model_save_dir': "./output/MicroExpression",
'num_classes': 7,
'total_images': 17245,
'epochs': 20,
'batch_size': 32,
'image_shape': [3, 224, 224],
'LEARNING_RATE': {
'params': {
'lr': 0.00375
}
},
'OPT... |
n=str(input("Enter the string"))
le=len(n)
dig=0
alp=0
for i in range(le):
if n[i].isdigit():
dig=dig+1
elif n[i].isalpha():
alp=alp+1
else:
continue
print("Letters count is : %d"%alp)
print("Digits count is : %d"%dig)
|
# Author: Will Killian
# https://www.github.com/willkill07
#
# Copyright 2021
# All Rights Reserved
class Lab:
_all = dict()
lab_id = 200
def min_id():
"""
Returns the maximum number for the lab IDs (always 200)
"""
return 200
def max_id():
"""
... |
# -*- coding: utf-8 -*-
class GeocoderException(Exception):
"""Base class for all the reverse geocoder module exceptions."""
class InitializationError(GeocoderException):
"""Catching this error will catch all initialization-related errors."""
class CsvReadError(InitializationError):
"""Could not open ... |
#Given a decimal number n, your task is to convert it
#to its binary equivalent using a recursive function.
#The binary number output must be of length 8 bits.
def binary(n):
if n == 0:
return 0
else:
return (n % 2 + 10*binary(int(n // 2)))
def convert_8_bit(n):
s = str(n)
while len(s... |
'''
Author: Shuailin Chen
Created Date: 2021-09-14
Last Modified: 2021-12-29
content:
'''
# optimizer
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0005)
optimizer_config = dict()
# learning policy
lr_config = dict(policy='poly', power=0.9, min_lr=1e-4, by_epoch=False)
# runtime settings
runner ... |
keys = {
"accept": 30,
"add": 107,
"apps": 93,
"attn": 246,
"back": 8,
"browser_back": 166,
"browser_forward": 167,
"cancel": 3,
"capital": 20,
"clear": 12,
"control": 17,
"convert": 28,
"crsel": 247,
"decimal": 110,
"delete": 46,
"divide":... |
N = int(input())
A = list(map(int, input().split()))
A.sort()
left, right = 0, 2*N-1
moist = A.count(0) // 2
while left < right and A[left] < 0 and A[right] > 0:
if abs(A[left]) == A[right]:
moist += 1
left += 1
right -= 1
elif abs(A[left]) > A[right]:
left += 1
else:
... |
def printSlope(equation):
xIndex = equation.find('x')
if xIndex == -1:
print(0)
elif xIndex == 2:
print(1)
else:
slopeString = equation[2:xIndex]
if slopeString == "-":
print(-1)
else:
print(slopeString)
printSlope("y=2x+5") #prints 2
prin... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
"""
__title__ = 'replace'
__author__ = 'JieYuan'
__mtime__ = '2019-05-06'
"""
def replace(s, dic):
return s.translate(str.maketrans(dic))
if __name__ == '__main__':
print(replace('abcd', {'a': '8', 'd': '88'}))
|
# Everytime you make changes in this file, you have to run Reco again (reco.pyw).
webhook_restricter_list=[
#(copy starts from here)
{
#1️⃣ Replace webhook Name
'webhookName':'Temp webhook', # Here you can enter the Webhook name, so you can identify easily in this file.
#2️⃣ Replace webhook URL... |
def profile_most_probable_kmer(text, k, profile):
highest_prob = -1
most_probable_kmer = ""
for i in range(len(text) - k + 1):
kmer = text[i : i+k]
prob = 1
for index, nucleotide in enumerate(kmer):
prob *= profile[nucleotide][index]
if prob > highest_prob:
... |
ROW_COUNT = 128
COLUMN_COUNT = 8
def solve(input):
return max(map(lambda i: BoardingPass(i).seat_id, input))
class BoardingPass:
def __init__(self, data, row_count=ROW_COUNT, column_count=COLUMN_COUNT):
self.row = self._search(
data = data[:7],
low_char='F',
high_char='B',
i=0,
... |
f = open('day3.txt', 'r')
data = f.readlines()
oneCount = 0
threeCount = 0
fiveCount = 0
sevenCount = 0
evenCount = 0
pos1 = 0
pos3 = 0
pos5 = 0
pos7 = 0
posEven = 0
even = True
for line in data:
line = line.replace("\n", '')
if line[pos1 % len(line)] == '#':
oneCount += 1
if line[pos3 % len(line)... |
def porrada(seq, passo):
atual = 0
while len(seq) > 1:
atual += passo - 1
while atual > len(seq) - 1:
atual -= len(seq)
seq.pop(atual)
return seq[0] + 1
quantidade_de_casos = int(input())
for c in range(quantidade_de_casos):
entrada = input().split()
n = list(ra... |
n = int(input())
arr = list(map(int, input().split(' ')))
arr.sort(reverse=True)
res = 0
for i in range(n):
res += arr[i]*2**i
print(res)
|
def run_example():
# Taką samą listę z numerami jak w poprzednim przykładzie możemy zapisać krócej za pomocą list comprehensions
# numbers = []
# for number in range(15):
# numbers.append(number)
numbers = [number for number in range(15)]
print(numbers)
# List comprehensions zawiera... |
class Solution:
def minInsertions(self, s: str) -> int:
right = count = 0
for c in s:
if c == '(':
if right & 1:
right -= 1
count += 1
right += 2
else:
right -= 1
if right ... |
# Given an array of integers, return indices of the two numbers such that they add up to a specific target.
# You may assume that each input would have exactly one solution, and you may not use the same element twice.
# Example:
# Given nums = [2, 7, 11, 15], target = 9,
# Because nums[0] + nums[1] = 2 + 7 = 9,
# re... |
S = input()
N = len(S)
A = [0]*(N+1)
B = [0]*(N+1)
for i in range(N):
if S[i] == '<':
A[i+1] = A[i]+1
else:
A[i+1] = 0
for i in range(N):
if S[N-i-1] == '>':
B[N-i-1] = B[N-i]+1
else:
B[N-i-1] = 0
ans = 0
for i in range(N+1):
ans += max(A[i], B[i])
print(ans)
|
# https://leetcode.com/problems/add-two-numbers/
# You are given two non-empty linked lists representing two non-negative integers.
# The digits are stored in reverse order and each of their nodes contain a single digit.
# Add the two numbers and return it as a linked list.
#
# You may assume the two numbers do not co... |
A = int(input())
B = int(input())
if B % A == 0 or A % B == 0:
print("São Múltiplos \n")
else:
print("Não são Múltiplos \n")
|
'''
Write a program that takes an integer argument and
retums all the primes between 1 and that integer.
For example, if the input is 18, you should return
[2, 3, 5, 7, 11, 13, 17].
'''
def generate_primes(n): # Time: O(n log log n) | Space: O(n)
primes = []
# is_prime[p] represents if p is prime or not.
... |
"""
gdcdatamodel.migrations.update_case_cache
--------------------
Functionality to fix stale case caches in _related_cases edge tables.
"""
def update_related_cases(driver, node_id):
"""Removes and re-adds the edge between the given node and it's parent
to cascade the new relationship to _related_cases thr... |
"""
Métodos mágicos são todos os métodos que utilizam o dunder __method__
"""
# Construtor (__init__)
class Livro:
def __init__(self, titulo, autor, paginas):
self.__titulo = titulo
self.__autor = autor
self.__pagina = paginas
def __repr__(self): #__repr__ É a representasão do objeto... |
n = int(input())
l = []
for i in range(0, n):
l.append(int(input()))
for orig_num in l:
count = 0
num = orig_num
while num != 0:
digit = num % 10
if digit == 0:
pass
elif orig_num % digit == 0:
count += 1
num = int(num / 10)
print (count) |
# Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre sua média.
n1 = int(input('Digite sua primeira nota:'))
n2 = int(input('Digite sua segunda nota:'))
media = float (n1+n2)/2
print('A média do aluno é {}'.format(media))
|
class Qseq(str):
def __init__(self, seq):
self.qkey = None
self.parent = None
self.parental_id = None
self.parental_class = None
self.name = None
self.item = None
def __getitem__(self, item):
value = s... |
rios = {
'nilo' : 'egito',
'rio grande' : 'brasil',
'rio parana' : 'brasil'
}
for key,value in rios.items():
print(' O rio ' + key.title() + ' corre pelo ' + value.title())
for key in rios.keys():
print(key.title())
for value in rios.values():
print(value.title())
|
# coding: utf-8
# In[ ]:
class Solution:
def searchRange(self, nums, target):
#算法思路:
#首先写下一个可以找到第一个出现的target的indice的binary search的方程
#在这个方程里,如果mid的大小大于或等于target,则hi变成现在的mid
#如果mid的大小小于了target了,则lo变为现在的mid+1
#可以注意的是,因为我们在一个sorted list nums寻找,当这个方程的target变为target+1后
#这个方程会返回在nums中最后一个的target的indice+1
def ... |
def hello(name):
"""Generate a friendly greeting.
Greeting is an important part of culture. This function takes a name and
generates a friendly greeting for it.
Parameters
----------
name : str
A name.
Returns
-------
str
A greeting.
"""
return 'Hello {na... |
vowels2 = set('aeiiiouuu')
word = input('Provide a word to search for vowels:').lower()
found = vowels2.intersection(set(word))
for v in found:
print(v) |
#!/usr/bin/env python2.7
"""
Read the file agents.raw and output agents.txt, a readable file
"""
if __name__=="__main__":
with open("agents.raw","r") as f:
with open("agents.txt","w") as out:
for line in f:
if(line[0] in '+|'):
out.write(line)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : metaclass_0.py
# @Author: yubo
# @Date : 2019/11/18
# @Desc :
class Meta(type):
"""
自定义元类
"""
def __new__(cls, name, bases, d):
"""
使用自定义元类,最终都是要调用 type 生成类实例
return super(Meta, cls).__new__(cls, name, bases, d)
... |
idades = [11, 43, 55, 41, 85, 43, 43, 5]
# Forma manual
for indice in range(len(idades)):
print(indice, "|", idades[indice])
print()
# Forma com tuplas usando enumerate
for tupla in enumerate(idades):
print(tupla)
print()
# Forma com desempacotamento de tuplas
for indice, idade in enumerate(idades):
pr... |
# -*- coding: utf-8 -*-
"""mul.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1fvc_bX8oobfbr_O2r1pCpgOd2CTckXe9
"""
def mul(num1, num2):
print('Result is: ', num1 * num2) |
class Solution:
def wordPattern(self, pattern: str, str: str) -> bool:
table = {}
mapped = set()
words = str.split()
if len(words) != len(pattern):
return False
for i, word in enumerate(words):
if word in table:
if table[wor... |
HOST = 'localhost'
PORT = 61613
VERSION = '1.2'
BROKER = 'activemq'
LOGIN, PASSCODE, VIRTUALHOST = {
'activemq': ('', '', ''),
'apollo': ('admin', 'password', 'mybroker'),
'rabbitmq': ('guest', 'guest', '/')
}[BROKER]
|
# python3.7
"""Configuration for testing StyleGAN on FF-HQ (1024) dataset.
All settings are particularly used for one replica (GPU), such as `batch_size`
and `num_workers`.
"""
runner_type = 'StyleGANRunner'
gan_type = 'stylegan'
resolution = 1024
batch_size = 16
data = dict(
num_workers=4,
# val=dict(root_d... |
def Num2581():
M = int(input())
N = int(input())
minPrimeNum = 0
sumPrimeNum = 0
primeNums = []
for dividend in range(M, N+1):
if dividend == 1:
continue
primeNums.append(dividend)
sumPrimeNum += dividend
for divisor in range(2, dividend):
... |
#takes a list of options as input which will be printed as a numerical list
#Also optionally takes messages as input to be printed after the options but before input request
#Ultimately the users choice is returned
def selector(options,*messages):
rego = 'y'
while rego.lower() == "y":
n=1
for x... |
"""A module to keep track of a relinearization key."""
class BFVRelinKey:
"""An instance of a relinearization key.
The relinearization key consists of a list of values, as specified
in Version 1 of the BFV paper, generated in key_generator.py.
Attributes:
base (int): Base used in relineariza... |
class Wrapping(object):
def __init__(self, klass, wrapped_klass, dependency_functions):
self._klass = klass
self._wrapped_klass = wrapped_klass
self._dependency_functions = dependency_functions
def wrap(self):
for dependency_method in self._dependency_functions:
se... |
"""
templates for urls
"""
URL = """router.register(r'%(path)s', %(model)sViewSet)
"""
VIEWSET_IMPORT = """from %(app)s.views import %(model)sViewSet
"""
URL_PATTERNS = """urlpatterns = [
path("", include(router.urls)),
]"""
SETUP = """from rest_framework import routers
from django.urls import include, path
r... |
# Desafio 005 - Faça um programa que leia um número inteiro e mostre na tela o seu sucessor e seu antecessor
inteiro = int(input('Digite um número inteiro: '))
antecessor = inteiro - 1
sucessor = inteiro + 1
print('O antecessor de {} é {}. \nO sucessor de {} é {}.'. format(inteiro, antecessor, inteiro, sucessor))
# a... |
def roman_number(num):
if num > 3999:
print("enter number less than 3999")
return
#take 2 list symbol and value symbol having roman of each integer in list value
value = [1000,900,500,400,100,90,50,40,10,9,5,4,1]
symbol = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]
ro... |
def radixSort(data):
if not data:
return []
max_num = max(data) # 获取当前数列中最大值
max_digit = len(str(abs(max_num))) # 获取最大的位数
dev = 1 # 第几位数,个位数为1,十位数为10···
mod = 10 # 求余数的除法
for i in range(max_digit):
radix_queue = [list() for k in range(mod * 2)]
for j in range(len(dat... |
AN_ESCAPED_NEWLINE = "\n"
AN_ESCAPED_TAB = "\t"
A_COMMA = ","
A_QUOTE = "'"
A_TAB = "\t"
DOUBLE_QUOTES = "\""
NEWLINE = "\n"
|
#!/usr/bin/env python3
#
# Copyright 2019 Google 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
class MyClass:
def __init__(self, name):
self.__name = name
def Show(self):
print(self.__name)
c1 = MyClass('c1')
c2 = MyClass('c2')
c3 = MyClass('c3')
c4 = MyClass('c4')
a = {x.Show() for x in {c1, c2, c3, c4} if x not in {c1, c2}}
|
SUB_GROUP = [
(0, "Нет подгруппы"),
(1, "Подгруппа 1"),
(2, "Подгруппа 2"),
(3, "Подгруппа 3"),
(4, "Подгруппа 4"),
(5, "Подгруппа 5"),
(6, "Подгруппа 6"),
(7, "Подгруппа 7"),
(8, "Подгруппа 8"),
(9, "Подгруппа 9"),
]
FORM_OF_EDUCATION = [
(0, "Очная"),
(1, "Заочая"),
... |
@metadata_reactor
def install_git(metadata):
return {
'apt': {
'packages': {
'git': {
'installed': True,
},
}
},
}
|
if __name__ == '__main__':
n,m = map(int,input().split())
l = map(int,input().split())
a = set(map(int,input().split()))
b = set(map(int,input().split()))
happy = 0
for i in l:
if i in a:
happy += 1
elif i in b:
happy -= 1
print(happy)
# print(sum([(i in a) - (i in b) for i in l])) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
############################
# File Name: upper_lower_convert.py
# Author: One Zero
# Mail: zeroonegit@gmail.com
# Created Time: 2015-12-28 01:10:28
############################
str = 'www.zeroonecloud.com'
print(str.upper()) # 把所有字符中的小写字母转换成大写字母
prin... |
#!/usr/bin/env python
"""Python-LCS Algorithm, Author: Matt Nichols
Copied from https://github.com/man1/Python-LCS/blob/master/lcs.py
Modified for running LCS inside P4SC merging algorithm
"""
### solve the longest common subsequence problem
# get the matrix of LCS lengths at each sub-step of the recursive pro... |
# // This is a generated file, modify: generate/templates/binding.gyp.
{
"targets": [{
"target_name": "nodegit",
"dependencies": [
"<(module_root_dir)/vendor/libgit2.gyp:libgit2"
],
"sources": [
"src/nodegit.cc",
"src/wrapper.cc",
"src/functions/copy.cc",
"src/attr.cc"... |
# Text for QML styles
chl_style = """
<!DOCTYPE qgis PUBLIC 'http://mrcc.com/qgis.dtd' 'SYSTEM'>
<qgis version="2.4.0-Chugiak" minimumScale="0" maximumScale="1e+08" hasScaleBasedVisibilityFlag="0">
<pipe>
<rasterrenderer opacity="1" alphaBand="0" classificationMax="1.44451" classificationMinMaxOrigin="Cumulative... |
a = 10
b = 20
c = 300000
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
if not root:
... |
class Solution:
def addBinary(self, a: str, b: str) -> str:
x=int(a,2)
y=int(b,2)
return bin(x+y)[2:]
|
#母音を変数に
vowel = 'aeiouAEIOU'
#標準入力
name = input()
#cname変数に母音じゃないものをjoinしていって出力
#'間に挿入する文字列'.join([連結したい文字列のリスト])
cname = ''.join(s for s in name if s not in vowel)
print(cname)
#複数行の入出力
input_line = int(input())
for i in range(input_line):
n = input()
print(n)
# 繰り返し出力
input_line = 'one two three four five'... |
# Copyright © 2020, United States Government, as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All rights reserved.
#
# The DELTA (Deep Earth Learning, Tools, and Analysis) platform is
# licensed under the Apache License, Version 2.0 (the "License");
# you may not use this f... |
for i in range(int(input())):
n = int(input())
s = input()
a,b = [-1 for j in range(26)],[1e5 for j in range(26)]
for j in range(n):
if(a[ord(s[j])-97]==-1):
a[ord(s[j])-97] = j
else:
if(j-a[ord(s[j])-97]<b[ord(s[j])-97]):
b[ord(s[j])-97] = j-a[ord... |
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
edits = [[x for x in range(len(word1) + 1)] for y in range(len(word2) + 1)]
for i in range(1, len(word2) + 1):
edits[i][0] = edits[i - 1][0] + 1
for i in range(1, len(word2) + 1):
for j in range(1, ... |
ENHANCED_PEER_MOBILIZATION = 'enhanced_peer_mobilization'
CHAMP_CAMEROON = 'champ_client_forms'
TARGET_XMLNS = 'http://openrosa.org/formdesigner/A79467FD-4CDE-47B6-8218-4394699A5C95'
PREVENTION_XMLNS = 'http://openrosa.org/formdesigner/DF2FBEEA-31DE-4537-9913-07D57591502C'
POST_TEST_XMLNS = 'http://openrosa.org/formd... |
def attack(state, attacking_moves_sequence):
new_state = state.__deepcopy__()
ATTACKING_TERRITORY_INDEX = 0
ENEMY_TERRITORY_INDEX = 1
for attacking_move in attacking_moves_sequence:
print("in attack attacking move",attacking_move)
print("new state map in attack", len(new_state.map))
... |
# You may need this if you really want to use a recursive solution!
# It raises the cap on how many recursions can happen. Use this at your own risk!
# sys.setrecursionlimit(100000)
def read_lines(filename):
try:
f = open(filename,"r")
lines = f.readlines()
f.close()
filter... |
class MultiFilterCNNModel(object):
def __init__(self, max_sequences, word_index, embed_dim, embedding_matrix, filter_sizes,
num_filters, dropout, learning_rate, beta_1, beta_2, epsilon, n_classes):
sequence_input = Input(shape=(max_sequences,), dtype='int32')
embedding_layer = Emb... |
#!usr/bin/python
# -*- coding: utf-8 -*-
class Database(object):
"""Database class holding information about node/label relationships, mappings from nodes to images and from images to status."""
def __init__(self, root_name="core"):
"""Constuctor for the Database class.
Args:
roo... |
norm_cfg = dict(type='BN', requires_grad=True)
model = dict(
type='EncoderDecoder',
pretrained='open-mmlab://resnet50_v1c',
backbone=dict(
type='ResNetV1c',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
dilations=(1, 1, 2, 4),
strides=(1, 2, 1, 1),
... |
class Solution:
def longestAwesome(self, s: str) -> int:
table = {0 : -1}
mask = maxLen = 0
for i, c in enumerate(s):
mask ^= (1 << int(c))
for j in range(10):
mask2 = mask ^ (1 << j)
if mask2 in table:
maxLen = max(... |
# This is what gets created by TextField.as_tensor with a SingleIdTokenIndexer
# and a TokenCharactersIndexer; see the code snippet above. This time we're using
# more intuitive names for the indexers and embedders.
token_tensor = {
'tokens': {'tokens': torch.LongTensor([[2, 4, 3, 5]])},
'token_characters': {'t... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
""" Image tags """
img_tag = '[Ваше_изображение]'
img_group_tag, img_group_closing_tag = '[Ряд_изображений]', '[/Ряд_изображений]'
group_img_tag = '[Рядовый_элемент]'
|
pessoas = [['João', 15],['Maria', 22], ['Messias', 35]]
print(pessoas[0][1])
print(pessoas[1][0])
print(pessoas[2][1])
print(pessoas)
print(pessoas[1])
#############################################################
teste = list()
teste.append('Leonardo')
teste.append(17)
galera = list()
galera.append(teste[... |
{
"targets": [
{
"target_name": "decompressor",
"sources": ["decompressor.cpp"]
},
{
"target_name": "pow_solver",
"sources": ["pow_solver.cpp"]
}
]
}
|
class C4FileIO():
red_wins = 0
blue_wins = 0
def __init__(self):
try:
f = open("c4wins.txt", "r")
lines = f.readlines()
f.close()
if type(lines) == list:
self.deserialize_file(lines)
except FileNotFoundError:
print(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.