content stringlengths 7 1.05M |
|---|
_base_ = [
'../../_base_/models/resnet50.py',
'../../_base_/datasets/imagenet.py',
'../../_base_/schedules/sgd_steplr-100e.py',
'../../_base_/default_runtime.py',
]
# model settings
model = dict(backbone=dict(norm_cfg=dict(type='SyncBN')))
# dataset settings
data = dict(
imgs_per_gpu=64, # total ... |
def test_add_to_basket(browser):
link = 'http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/'
browser.get(link)
assert browser.find_element_by_class_name('btn-add-to-basket').is_displayed(), f'Basket button not found'
|
class TaskAnswer:
# list of tuple: (vertice_source, vertice_destination, moved_value)
_steps = []
def get_steps(self) -> list:
return self._steps
def add_step(self, source: int, destination: int, value: float):
step = (source, destination, value)
self._steps.append(step)
... |
class Solution:
def getDescentPeriods(self, prices: List[int]) -> int:
curr = result = 1
for i in range(1, len(prices)):
if prices[i] + 1 == prices[i-1]:
curr += 1
else:
curr = 1
result += curr
return result |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"from splinter import Browser\n",
"from bs4 import BeautifulSoup\n",
"from datetime import datetime \n",
"import os\n",
"import time\n",
"from urlli... |
# Implementar la función es_primo(), que devuelva un booleano en base a
# si numero es primo o no.
def es_primo(numero):
for i in range (2,numero):
if (numero % i) == 0:
return False
return True
assert(es_primo(7)== True)
assert(es_primo(6) == False)
|
'''
question-1
Code likho jo iss list mein se maximum dhund kar ke print kare.
numbers=[50, 40, 23, 70, 56, 12, 5, 10, 7]
Aapke program ka output 70 hona chaiye.
'''
#through max function
numbers=[50, 40, 23, 70, 56, 12, 5, 10, 7]
print (max(numbers))
#without useing max function
numbers=[50, 40, 23, 70, 56, 12, 5, 1... |
print("####################################################")
print("#FILENAME:\t\ta1p1.py\t\t\t #")
print("#ASSIGNMENT:\t\tHomework Assignment 1 Pt. 1#")
print("#COURSE/SECTION:\tCIS 3389.251\t\t #")
print("#DUE DATE:\t\tWednesday, 12.February 2020#")
print("####################################################\n\... |
#!/usr/bin/env python
# encoding: utf-8
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
dp = [0]*(num+1)
for i in xrange(num+1):
dp[i] = dp[i/2] if i%2 == 0 else dp[i/2]+1
return dp |
# 폰켓몬
def solution(nums):
half = len(nums)/2
nums = list(set(nums))
diff = len(nums)
if half >= diff:
return int(diff)
else:
return int(half)
# 테스트 1 〉 통과 (0.01ms, 10.2MB)
# 테스트 2 〉 통과 (0.01ms, 10.1MB)
# 테스트 3 〉 통과 (0.01ms, 10.2MB)
# 테스트 4 〉 통과 (0.01ms, 10.2MB)
# 테스트 5 〉 통과 (0.01ms, 10.... |
#!/usr/local/bin/python3
# Python Challenge - 1
# http://www.pythonchallenge.com/pc/def/map.html
# Keyword: ocr
def main():
'''
Hint:
K -> M
O -> Q
E -> G
Everybody thinks twice before solving this.
'''
cipher_text = ('g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcp'
... |
def check_next_num(inp, j):
for i in range(j, len(inp)):
elm = inp[i]
if len(inp) > i+1:
if inp[i+1] == (elm+1):
check_next_num(inp, i+1)
else:
if j == 0:
return i
return i
else:
return le... |
def rotate(str, d, mag):
if (d=="L"):
return str[mag:] + str[0:mag]
elif (d=="R"):
return str[len(str)-mag:] + str[0: len(str)-mag]
def checkAnagram(str1, str2):
if(sorted(str1)==sorted(str2)):
return True
else:
return False
def subString(s, n, ans):
for i in r... |
"""
You are asked to ensure that the first and last names of people begin with a capital letter in their passports. For example, alison heck should be capitalised correctly as Alison Heck.
Given a full name, your task is to capitalize the name appropriately.
Input Format
A single line of input containing the full na... |
number = int(input("Pick a number? "))
for i in range(5):
number = number + number
print(number)
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
# Author=====>>>Nipun Garg<<<=====
# Problem Statement - Given number of jobs and number of applicants
# And for each applicant given that wether each applicant is
# eligible to get the job or not in the form of matrix
# Return 1 if a person can get the job
def dfs(graph, applicant, visited, result,nApplicants,nJob... |
print('<=== Antecessor e Sucessor ===>')
n = int(input('Digite um número:'))
na = n-1
ns = n+1
print('O número que antecede {} é {}.'.format(n, na))
print('O número que sucede {} é {}.'.format(n, ns))
print('')
print('Melhorado')
print('O número que antecede {} é {}'.format(n, n-1))
print('O número que sucede {} é {}'... |
#026 - Primeira e última ocorrência de uma string
frase = str(input('Digite uma frase: ')).upper().strip()
print(f'A letra A aparece {frase.count("A")}')
print(f'A primeira letra A apareeceu na posicao {frase.find("A")+1}')
print(f'A ultima letra A aparece na posicao {frase.rfind("A")+1}')
|
# -*- coding: utf8 -*-
# @author: yinan
# @time: 18-7-4 下午5:52
# @filename: response.py
def return_message(data, msg, code):
return {
"code": code,
"data": data,
"msg": msg
}
|
# 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 tree2str(self, t: TreeNode) -> str:
if t is None:
return ""
... |
# get distinct characters and their count in a String
string = input("Enter String: ")
c = 0
for i in range(65, 91):
c = 0
for j in range(0, len(string)):
if(string[j] == chr(i)):
c += 1
if c > 0:
print("", chr(i), " is ", c, " times.")
c = 0
for i in range(97, 123):
c = 0... |
class SearchPath:
def __init__(self, path=None):
if path is None:
self._path = []
else:
self._path = path
def branch_off(self, label, p):
path = self._path + [(label, p)]
return SearchPath(path)
@property
def labels(self):
return [label f... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# SKR03
# =====
# Dieses Modul bietet Ihnen einen deutschen Kontenplan basierend auf dem SKR03.
# Gemäss der aktuellen Einstellungen ist die Firma nicht Umsatzsteuerpflichtig.
# Diese Grundeinstellung ist sehr einfach z... |
class Bot:
'''
state - state of the game
returns a move
'''
def move(self, state, symbol):
raise NotImplementedError('Abstractaaa')
def get_name(self):
raise NotImplementedError('Abstractaaa')
|
__author__ = 'shukkkur'
'''
https://codeforces.com/problemset/problem/581/A
A. Vasya the Hipster
'''
red, blue = map(int, input().split())
total = red + blue
a = min(red, blue)
total -= 2 * a
b = total // 2
print(a, b)
|
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def dnsmasq_dependencies():
http_archive(
name = "dnsmasq",
urls = ["http://www.thekelleys.org.uk/dnsmasq/dnsmasq-2.78.tar.xz"],
sha256 = "89949f438c74b0c7543f06689c319484bd126cc4b1f8c745c742ab397681252b",
build_fi... |
file = open("input")
lines = file.readlines()
pattern_len = len(lines[0])
def part1(lines, right, down):
count = 0
pattern_len = len(lines[0])
x = 0
y = 0
while y < len(lines) - down:
x += right
y += down
if lines[y][x % (pattern_len - 1)] == "#":
... |
"""
Expect Utility
--------------
Regardless of comment type, all tests in this file will be detected. We will
demonstrate that expect can handle several edge cases, accommodate regular
doctest formats, and detect inline tests.
>>> x = 4
>>> x
4
>>> 3+5 # comments
8
>>> 6+x # wrong!
5
>>> is_proper('()')
True
"""
... |
# input the length of array
n = int(input())
# input the elements of array
ar = [int(x) for x in input().strip().split(' ')]
c = [0]*100
for a in ar :
c[a] += 1
s = ''
# print the sorted list as a single line of space-separated elements
for x in range(0,100) :
for i in range(0,c[x]) :
s += ' ' + ... |
full_dict = {
'daterecieved': 'entry daterecieved',
'poploadslip' : 'entry poploadslip',
'count' : 'entry 1' ,
'tm9_ticket' : 'entry tm9_ticket',
'disposition_fmanum' : 'entry disposition_fmanum',
'owner' : 'entry ownerName',
'... |
"""smp_base/__init__.py
.. todo::
remove actinf tag from base learners
.. todo::
abstract class from andi / smp_control to check for api conformity?
.. todo::
for module in rlspy igmm kohonone otl ; do git submodule ...
"""
|
# HEAD
# Python Functions - *args
# DESCRIPTION
# Describes
# capturing all arguments as *args (tuple)
#
# RESOURCES
#
# Arguments (any number during invocation) can also be
# caught as a sequence of arguments - tuple using *args
# Order does matter for unnamed arguments list and makes for
# inde... |
class Luhn:
def __init__(self, card_num: str):
self._reversed_card_num = card_num.replace(' ', '')[::-1]
self._even_digits = self._reversed_card_num[1::2]
self._odd_digits = self._reversed_card_num[::2]
def valid(self) -> bool:
if str.isnumeric(self._reversed_card_num) and len(s... |
"""
Problem name: ThePalindrome
Class: SRM 428, Division II Level One
Description: https://community.topcoder.com/stat?c=problem_statement&pm=10182
"""
def solve(args):
""" Simply reverse the string and find a match. When the match is found,
continue it to the end. If the end is reached, then the match... |
"""Kata url: https://www.codewars.com/kata/51fc12de24a9d8cb0e000001."""
def valid_ISBN10(isbn: str) -> bool:
if len(isbn) != 10:
return False
if not isbn[:-1].isdigit():
return False
if not (isbn[-1].isdigit() or isbn[-1] == 'X'):
return False
return not sum(
int(x, ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 27 11:20:36 2019
@author: melzanaty
"""
####################################################
# Quiz: Check for Prime Numbers
####################################################
# '''
# Write code to check if the numbers provided in the list check_... |
# Copyright 2019-present, GraphQL Foundation
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
def title(s):
'''Capitalize the first character of s.'''
return s[0].capitalize() + s[1:]
def camel(s):
'''Lowercase the first charac... |
class Solution:
def binary_to_decimal(self, n):
return int(n, 2)
def grayCode(self, A):
num_till_now = [0, 1]
if A == 1:
return num_till_now
results = []
for i in range(1, A):
rev = num_till_now.copy()
rev.reverse()
num_ti... |
def include_in_html(content_to_include, input_includename, html_filepath):
with open(html_filepath, "r") as f:
line_list = f.readlines()
res = []
includename = None
initial_spaces = 0
for line in line_list:
line = line.strip("\n")
if line.strip(" ")[:14] == "<!-- #includ... |
# 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.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
class Simple(object):
def __init__(self, x):
self.x = x
self.y = 6
def get_x(self):
return self.x
class WithCollection(object):
def __init__(self):
self.l = list()
self.d = dict()
def get_l(self):
return self.l |
""" Once in the "ready" state, Huntsman has been initialized successfully and it is safe. The goal
of the ready state is to decide which of the following states to enter next:
- parking
- coarse_focusing
- scheduling
- twilight_flat_fielding
"""
def on_enter(event_data):
"""
"""
pocs = event_data.model
... |
s = open('input.txt','r').read()
s = [k for k in s.split("\n")]
aller = {}
count = {}
for line in s:
allergens = line.split("contains ")[1].split(", ")
allergens[-1] = allergens[-1][:-1]
ing = line.split(" (")[0].split(" ")
for i in ing:
count[i] = 1 if i not in count else count[i] + 1
fo... |
t = int(input())
for i in range(t):
n = input()
rev_n = int(n[::-1])
print(rev_n) |
courses={}
while True:
command=input()
if command!="end":
command=command.split(" : ")
doesCourseExist=False
for j in courses:
if j==command[0]:
doesCourseExist=True
break
if doesCourseExist==False:
courses[comm... |
#! /usr/bin/env python
# encoding: utf-8
class TimeOutError(Exception):
pass
class MaxRetryError(Exception):
pass
class GodError(Exception):
"""
custom exception msg class
"""
def __init__(self, msg="Intern Error", code=500):
self.msg = msg
self.code = code
def __str__... |
def main():
object_a_mass = float(input("Object A mass: "))
object_b_mass = float(input("Object B mass: "))
distance = float(input("Distance between both: "))
G = 6.67408 * (10**11)
print(G*(object_a_mass*object_b_mass)/ (distance ** 2))
if __name__ == '__main__':
main()
|
PB_PACKAGE = __package__
NODE_TAG = 'p_baker_node'
MATERIAL_TAG = 'p_baker_material'
MATERIAL_TAG_VERTEX = 'p_baker_material_vertex'
NODE_INPUTS = [
'Color',
'Subsurface',
'Subsurface Color',
'Metallic',
'Specular',
'Specular Tint',
'Roughness',
'Anisotropic',
'Anisotropic Rotation... |
def nrange(start, stop, step=1):
while start < stop:
yield start
start += step
@profile
def ncall():
for i in nrange(1,1000000):
pass
if __name__ == "__main__":
ncall()
|
string = "abcdefgabc"
string_list = []
for letter in string:
string_list.append(letter)
print(string_list)
string_list_no_duplicate = set(string_list)
string_list_no_duplicate = list(string_list_no_duplicate)
string_list_no_duplicate.sort()
print(string_list_no_duplicate)
for letters in string_list_no_duplicate... |
# Created by sarathkaul on 14/11/19
def remove_duplicates(sentence: str) -> str:
"""
Reomove duplicates from sentence
>>> remove_duplicates("Python is great and Java is also great")
'Java Python also and great is'
"""
sen_list = sentence.split(" ")
check = set()
for a_word in sen_list... |
def load(task_id, file_id, cmds):
global responses
code = reverse_upload(task_id, file_id)
name = cmds
if agent.get_Encryption_key() == "":
dynfs[name] = code
else:
dynfs[name] = encrypt_code(code)
response = {
'task_id': task_id,
"user_output": "Modul... |
for _ in range(int(input())):
n = int(input())
r = [int(i) for i in input().split()]
o = max(r)
if r.count(o)==len(r):
print(-1)
continue
kq = -1
for i in range(1,len(r)):
if r[i]==o and (r[i]>r[i-1]):
kq = i+1
for i in range(len(r)-1):
if r[i]==o and(r[i]>r[i+1]):
kq = i+1
print(kq)
|
"""
Give Steps to Sort a List
Given a shuffled list l, return a sequence of transpositions which sorts the list (as in sorted(l)).
A transposition is a pair of indices (i, j) representing that l[i] and l[j] be swapped.
Specifically, the output is a list of transpositions to be applied. Transpositions are applied as i... |
WIDTH = 128
HEIGHT = 128
# Must be more than ALIEN_SIZE, used to pad alien rows and columns
ALIEN_BLOCK_SIZE = 8
# Alien constants are global as their spacing is used to separate them
ALIENS_PER_ROW = int(WIDTH / ALIEN_BLOCK_SIZE) - 6
ALIEN_ROWS = int(HEIGHT / (2 * ALIEN_BLOCK_SIZE))
# How often to move the aliens i... |
fp = open('abcd.txt', 'r')
line_offset = []
offset = 0
for line in fp:
line_offset.append(offset)
offset += len(line)
print(line_offset)
for each in line_offset:
fp.seek(each)
print(fp.readline()[:-1])
|
# ----------------------------------------------------------------------------
# Copyright 2019-2022 Diligent Graphics 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.a... |
# Um programa que análisa o nome e faz alterações no mesmo #
nome = str(input('Digite seu nome: ')).strip()
print('Analiando seu nome...')
print(f'Seu nome em maiúsculas é {(nome.upper())}')
print(f'Seu nome em minúsculas é {(nome.lower())}')
print(f'Seu nome tem ao todo {(len(nome) - nome.count(" "))} letras')
# Os ... |
#
# PySNMP MIB module Cajun-ROOT (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Cajun-ROOT
# Produced by pysmi-0.3.4 at Mon Apr 29 17:08:17 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... |
# Add 5 to number
add5 = lambda n : n + 5
print(add5(2))
print(add5(7))
print()
# Square number
sqr = lambda n : n * n
print(sqr(2))
print(sqr(7))
print()
# Next integer
nextInt = lambda n : int(n) + 1
print(nextInt(2.7))
print(nextInt(7.2))
print()
# Previous integer of half
prevInt = lambda n : int(n // 2)
print(p... |
class Solution(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if not root:
return []
values = []
self.visit(root, values)
return values
def visit(self, root, values):
values.append(root.val)
for child in root.children:
self.visit(child, values)
|
small_train_path = "../data/small_dataset/train.conll" # 小数据集-训练集
small_dev_path = "../data/small_dataset/dev.conll" # 小数据集-验证集
big_train_path = "../data/big_dataset/train" # 大数据集-训练集
big_dev_path = "../data/big_dataset/dev" # 大数据集-验证集
big_test_path = "../data/big_dataset/test" # 大数据集-测试集
result_path = "../re... |
files = {
"server.py":"""#Import all your routes here
from {}.routes import router
from fastapi import FastAPI
app = FastAPI()
app.include_router(router)
""",
"settings.py": """#configuration for database""",
"test.py":"""#implement your test here""",
"models.py": """#implement your models here
from pydantic impor... |
state = '10011111011011001'
disk_length = 35651584
def mutate(a):
b = ''.join(['1' if x == '0' else '0' for x in reversed(a)])
return a + '0' + b
def checksum(a):
result = ''
i = 0
while i < len(a) - 1:
if a[i] == a[i+1]:
result += '1'
else:
result += '0'
... |
x = 1
while x < 10:
y = 1
while y < 10:
print("%4d" % (x*y), end="")
y += 1
print()
x += 1
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2011 Cisco Systems, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache... |
def saisie_liste():
cest_un_nombre=True
premier_nombre = input("Entrer un nombre : ")
somme=int(premier_nombre)
min=int(premier_nombre)
max=int(premier_nombre)
nombre_int = 0
n=0
moyenne = 0
while cest_un_nombre==True:
n += 1
nombre=input("Entrer un nombre : ")
... |
AF_INET = 2
AF_INET6 = 10
IPPROTO_IP = 0
IPPROTO_TCP = 6
IPPROTO_UDP = 17
IP_ADD_MEMBERSHIP = 3
SOCK_DGRAM = 2
SOCK_RAW = 3
SOCK_STREAM = 1
SOL_SOCKET = 4095
SO_REUSEADDR = 4
def getaddrinfo():
pass
def socket():
pass
|
fixed_rows = []
with open('runs/expert/baseline_pass_full_doc_rerank', 'r') as fi:
for line in fi:
line = line.strip().split()
if line:
fixed_score = -float(line[4])
line[4] = str(fixed_score)
fixed_rows.append('\t'.join(line))
with open('runs/expert/baseline_pass_full_doc_rerank', 'w') as fo:
for row ... |
def insertion_sort(l):
for i in range(1, len(l)):
j = i-1
key = l[i]
while (l[j] > key) and (j >= 0):
l[j+1] = l[j]
j -= 1
l[j+1] = key
numbers = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
insertion_sort(numbers)
print(numbers)
|
# Question: https://projecteuler.net/problem=120
# The coefficients of a^(odd) cancel out, so there might be a pattern ...
# n | X_n = (a-1)^n + (a+1)^n | mod a^2
#-----|----------------------------|--------
# 1 | 2a | 2a
# 2 | 2a^2 + 2 | 2
# 3 | 2... |
n = int(input().strip())
for i in range(0,n):
for y in range(0,n):
if(y<n-i-1):
print(' ', end='')
elif(y>=n-i-1 and y!=n-1):
print('#',end='')
else:
print('#')
|
def linha():
print()
print('=' * 80)
print()
linha()
while True:
num = int(input('Digite um número para ver sua tabuada [0 para sair]: '))
print()
if num == 0:
break
for c in range(1, 11):
print(f'{num} x {c:>2} = {num*c:>2}')
print()
linha()
|
class Node:
def __init__(self, value):
self.value = value
self.next = None
class Stack:
def __init__(self):
self.top = None
def push(self, value):
node = Node(value)
if self.top:
node.next = self.top
self.top = node
else:
... |
def scorify_library(library):
"""
The aim is to give the libraries a score, that will enable to order them later on
"""
NB = library[0]
BD = library[2]
SB = library_total_book_score(library)
DR = library[1]
library_scoring = (D - DR) * BD * (SB/NB)
return library_scoring
def libra... |
class Node:
def __init__(self, condition, body):
self.condition = condition
self.body = body
def visit(self, context):
rvalue = None
while self.condition.visit(context):
rvalue = self.body.visit(context)
return rvalue
|
""" Quiz: Enumerate
Use enumerate to modify the cast list so that each element contains the name followed by the character's corresponding height. For example, the first element of cast should change from "Barney Stinson" to "Barney Stinson 72".
"""
cast = [
"Barney Stinson",
"Robin Scherbatsky",
"Ted Mos... |
__all__ = [
'arch_blocks',
'get_mask',
'get_param_groups',
'logger',
'losses',
'lr_schedulers',
'optimizers_L1L2',
'tensorflow_logger',
] |
class Solution:
def solve(self, courses):
n = len(courses)
def helper(start):
visited[start] = 1
for v in courses[start]:
if visited[v]==1:
return True
elif visited[v]==0:
if helper(v):
... |
chipper = input('Input Message: ')
plain = ''
for alphabet in chipper:
temp = ord(alphabet)-1
plain += chr(temp)
print(plain)
|
"""
[2016-09-26] Challenge #285 [Easy] Cross Platform/Language Data Encoding part 1
https://www.reddit.com/r/dailyprogrammer/comments/54lu54/20160926_challenge_285_easy_cross/
We will make a binary byte oriented encoding of data that is self describing and extensible, and aims to solve the
following problems:
* porta... |
def dec1(def1):
def exec():
print("Executing now")
def1()
print("Executed")
return exec
@dec1
def who_is_sandy():
print("Sandy is good programmer")
#who_is_sandy = dec1(who_is_sandy) #Decorative function is dec1 another term is @dec1
who_is_sandy()
|
"""Aiohwenergy errors."""
class AiohwenergyException(Exception):
"""Base error for aiohwenergy."""
class RequestError(AiohwenergyException):
"""Unable to fulfill request.
Raised when host or API cannot be reached.
"""
class InvalidStateError(AiohwenergyException):
"""Raised when the device is... |
# container with most water
# https://leetcode.com/problems/container-with-most-water/
# the function maxArea -> take in a list of integers and return an integer
# 3 variables to keep track of the current max area, left and right pointers
# left pointer initialized to the first elements of the list
# right pointer init... |
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
Settings file for the TestRailImporter tool.
"""
TESTRAIL_STATUS_IDS = { # For more info see http://docs.gurock.c... |
print("------------------------------------")
print("********* Woorden switchen *********")
print("------------------------------------")
# Input temperatuur in Celsius
woord1 = input("Woord 1: ")
woord2 = input("Woord 2: ")
# Output
print()
print("Woord 1: " + woord1.upper())
print("Woord 2: " + woord2.upper())
prin... |
# Python 记录日志
flowFile = session.get()
if flowFile != None:
test = flowFile.getAttribute("greeting")
log.debug(test + ": Debug")
log.info(test + ": Info")
log.warn(test + ": Warn")
log.error(test + ": Error")
session.transfer(flowFile, REL_SUCCESS)
|
# * =======================
# *
# * Author: Matthew Moccaro
# * File: Network_Programming.py
# * Type: Python Source File
# *
# * Creation Date: 1/2/19
# *
# * Description: Python
# * source file for the
# * network programming
# * project.
# *
# * ======================
print("Network Programming For Python")
|
__author__ = 'mstipanov'
class ApiRequestErrorDetails(object):
messageId = ""
text = ""
variables = ""
additionalDescription = ""
def __init__(self, text=""):
self.text = text
def __str__(self):
return "ApiRequestErrorDetails: {" \
"messageId = \"" + str(self.m... |
"""
Aim: Given an undirected graph and an integer M. The task is to determine if
the graph can be colored with at most M colors such that no two adjacent
vertices of the graph are colored with the same color.
Intuition: We consider all the different combinations of the colors for the
given graph... |
# -*- coding: utf-8 -*-
# Jupyter Extension points
def _jupyter_nbextension_paths():
return [
dict(
section="notebook",
# the path is relative to the `my_fancy_module` directory
src="resources/nbextension",
# directory in the `nbextension/` namespace
... |
'''
Вероятно, вы помните задачу про школьницу Вику, которая в свой день рождения
принесла в школу N шоколадных конфет, чтобы отпраздновать вместе с одноклассниками.
За день до столь знаменательного праздника Вика пошла в магазин,
чтобы купить N конфет, однако обнаружила, что поштучно их купить нельзя.
Конфеты, которые ... |
class BatteryAndInverter:
name = "battery and inverter"
params = [
{
"key": "capacity_dc_kwh",
"label": "",
"units": "kwh",
"private": False,
"value": 4000,
"confidence": 0,
"notes": "",
"source": "FAKE"
... |
# Generate a mask for the upper triangle
mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(20, 18))
# Draw the heatmap with the mask and correct aspect ratio
sns.heatmap(corr, mask=mask, cmap="YlGnBu", vmax=.30, cente... |
# -*- coding: utf-8 -*-
#
# 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, softwa... |
# -*- coding: utf-8 -*-
# API - cs
# FileName: default.py
# Version: 1.0.0
# Create: 2018-10-24
# Modify: 2018-10-27
"""
Default settings and values
"""
"""global"""
BUCKET_NAME = 'BUCKET_NAME'
CODING = 'utf-8'
DOMAIN = 'DOMAIN'
INTERNAL_DOMAIN = 'oss-cn-beijing-internal.aliyuncs.com'
PREFIX = 'mosdb/... |
# Declaring the gotopt2 dependencies
load("@bazel_gazelle//:deps.bzl", "gazelle_dependencies", "go_repository")
load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
load("@bazel_bats//:deps.bzl", "bazel_bats_dependencies")
# Include this into any dependencies that want to compile gotopt2 from source.
... |
# -*- coding: utf-8 -*-
"""
Created on 2018/5/20
@author: susmote
"""
kv_dict = {}
with open('../right_code.txt') as f:
for value in f:
value = value.strip()
for i in value:
kv_dict.setdefault(i, 0)
kv_dict[i] += 1
print(kv_dict.keys())
print(len(kv_dict))
|
def leiaInt(msg=''):
while True:
try:
valor = int(input(msg))
except KeyboardInterrupt:
print(f"\033[31mO usuário preferiu não digitar esse número.\033[m")
return 0
except (ValueError, TypeError):
print(f"\033[31mERRO!Digite um número inteiro válido\033[m")
continue
else:
return valor
def l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.