content stringlengths 7 1.05M |
|---|
# -*- coding: UTF-8 -*-
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:123456@127.0.0.1:3306/vicuna'
# SQLALCHEMY_DATABASE_URI = 'sqlite:///instance/vicuna.sqlite'
SQLALCHEMY_TRACK_MODIFICATIONS = True
SQLALCHEMY_ECHO = True
# SQLALCHEMY_BINDS = {
# 'ga': 'mysql+pymysql://root:123456@127.0.0.1:3306/ga'
# }
DEBUG ... |
#!/usr/bin/env python3
#print("Welcome to python scripting.")
#print("This lecture is about printing special characters.")
#print("Welcome to python scripting.\nThis lecture is about special characters in print statement.")
#print("Hello""Inder")
#print('Hello Inder.\nHow are you?')
#print("Hello \bInder.")
#print("He... |
load("//private:tsc.bzl", _tsc = "tsc")
load("//private:typings.bzl", _typings = "typings")
load("//private:rollup_js_source_bundle.bzl", _rollup_js_source_bundle = "rollup_js_source_bundle")
load("//private:rollup_js_vendor_bundle.bzl", _rollup_js_vendor_bundle = "rollup_js_vendor_bundle")
load("//private:uglify_es.bz... |
class LinkedList:
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
def __init__(self):
self.head = None
def append(self, data):
new_node = self.Node(data)
if self.head is None:
self.head = new... |
"""
link: https://leetcode-cn.com/problems/license-key-formatting
problem: 格式化字符串,按K位分割
solution: 模拟
"""
class Solution:
def licenseKeyFormatting(self, S: str, K: int) -> str:
S = S.replace('-', '', -1).upper()
if not S:
return ""
n = len(S)
res = S[:len(S) % K]
... |
class SHA:
"""Represents a Git commit's SHA
It does not actually calculate an SHA. Instead, it simply increments a
counter. This makes sense because the SHA makes it into the artifact name
and therefore, the artifact's name tells the human "how old" it is. The
higher the SHA, the junger the a... |
# 両隣のラクダが被っている帽子に書かれた数のビットごとの排他的論理和が自身の被っている帽子に書かれた数と等しい
# ラクダの数を取得
# 例) 3
# int() : 入力された文字を数値に変換する
N = int(input())
# 帽子の番号を入力
# 例) 1 2 3
# split() : スペース区切りで入力された文字を配列に
# map(,) : 第一引数の関数を第二引数の各値を使って実行→今回であればすべての値をint型に変換する
# list() : 引数をリスト型に変換する
A = list(map(int,input().split()))
# 結果を確認するための変数
tp = 0
# 連続す... |
OPTIONAL_FIELDS = [
'tags', 'consumes', 'produces', 'schemes', 'security',
'deprecated', 'operationId', 'externalDocs'
]
OPTIONAL_OAS3_FIELDS = [
'components', 'servers'
]
DEFAULT_FIELDS = {"tags": [], "consumes": ['application/json'],
"produces": ['application/json'], "schemes": [],
... |
# Faça um programa que leia um número inteiro e diga se ele é ou não um número primo.
num = int(input('Digite um número para saber se é primo: '))
if num == 1:
print('\33[1:34mEsse número\33[m \33[1:33mNÃO\33[m \33[1:34mé primo!\33[m ')
elif num == 2 or num == 3 or num == 5 or num == 7:
print('\33[1:32mEsse n... |
def Num11047():
result = 0
parameter = [int(num) for num in input().split()]
N = parameter[0]
K = parameter[1]
moneyValues = sorted([int(input()) for i in range(N)], reverse=True)
for moneyValue in moneyValues:
if K % moneyValue == 0:
result += K // moneyValue
pr... |
# noinspection PyShadowingBuiltins,PyUnusedLocal
def sum(x, y):
try:
val_x = int(x)
val_y = int(y)
except ValueError:
raise
assert val_x >= 0 and val_x <= 100, "Value must be between 0 and 100"
assert val_y >= 0 and val_y <= 100, "Value must be between 0 and 100"
return (v... |
def number_of_friends():
n_friends = int(input("Enter the number of friends joining (including you): "))
return n_friends
def friend_names(n_friends: int):
names = []
for i in range(n_friends):
name = input(f"Enter the name of the friend number {i+1}: ")
names.append(name)
return n... |
a = int(input())
b = int(input())
if a > b:
for x in range(b+1,a):
if x % 5 == 2 or x % 5 == 3:
print(x)
if a < b:
for x in range(a+1,b):
if x % 5 == 2 or x % 5 == 3:
print(x)
if a == b:
print("0")
|
class AbstractRanker:
def __init__(self, num_features):
self.num_features = num_features
def update(self, gradient):
raise NotImplementedError("Derived class needs to implement "
"update.")
def assign_weights(self, weights):
raise NotImplementedErr... |
'''
06 - Run_n_times()
In the video exercise, I showed you an example of a decorator that takes
an argument: run_n_times(). The code for that decorator is repeated below
to remind you how it works. Practice different ways of applying the decorator
to the function print_sum(). Then I'll show you a funny prank... |
#for basic
a = 10
for i in range(a):
print("perulangan ke - "+str(i))
print('')
#for dengan data variable
print('#for dengan data')
barang = ['wireless', 'access point', 'wajan bolic']
for i in barang:
print(i)
|
'''
Created on Mar 14, 2018
@author: abelit
'''
class Animal:
def __init__(self, action):
self.action = action
def run(self):
print('I can go!')
class Cat(Animal):
def __init__(self,name):
self.name = name
self.action = ''
def cat_print(self):
... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 24 13:47:35 2017
@author: Javier
"""
molecular_weight = 58.44 # expressed in g/mol
molarity = 0.6
final_volume = 1000 # expressed in ml
conversion_factor = final_volume / 1000 # expressed in ml
needed_moles = molarity * conversion_factor
amount_needed = mol... |
q2 = dict()
count = 0
def checkQueen(x):
global count, q2, num
if (x == num):
count += 1
return
for i in range(num):
flag = True
for j in range(x):
if (i == q2[j] or abs(j - x) == abs(i - q2[j])):
flag = False
break
if (... |
# Dependency Injection
class DI(object):
def __init__(self):
self.container = {}
def get(self, dependency):
return self.container.get(dependency)
def set(self, dependency, value):
self.container[dependency] = value
def containers(self):
return self.container.keys()
|
class FileParser(object):
def __init__(self, file):
self.file = file
self.line = self.read_file()
def read_file(self):
with open(self.file) as file:
line = file.readlines()
return line
m = self.get_value(line[4])
print(m)
@staticmethod
def s... |
# RUN: test-output.sh %s
x = 1
print("Test Case 1")
if x == 1:
print("A")
print("D")
# OUTPUT-LABEL: Test Case 1
# OUTPUT-NEXT: A
# OUTPUT-NEXT: D
print("Test Case 2")
if x != 1:
print("A")
print("D")
# OUTPUT-LABEL: Test Case 2
# OUTPUT-NEXT: D
print("Test Case 3")
if x == 1:
print("A")
else:
... |
"""http and socket response messages in one place for re usability"""
auth_messages = {
"token_required": {
"status": "error",
"error": "token_not_found",
"message": "Ensure request headers contain a token",
},
"expired_token": {
'status': 'error',
'error': 'token_exp... |
def fun_decorator(some_funct):
def wrapper():
print("Here is the decorator, doing its thing")
for i in range(10):
print(i)
print("The decorator is done, returning to the originally scheduled function")
print(some_funct())
return wrapper
@fun_decorator
def a_funct():
... |
#This code is best for future use of this program
for i in range(1, 101):
fizz = 3
buzz = 5
fizzbuzz = fizz * buzz
if i % fizzbuzz == 0:
print("FizzBuzz")
continue
elif i % fizz == 0:
print("Fizz")
continue
elif i % buzz == 0:
print("Buzz")
co... |
# Задача 5. Грижи за кученце
# Ани намира кученце, за което ще се грижи, докато се намери някой да го осинови.
# То изяжда дневно определено количество храна. Да се напише програма, която проверява дали количеството храна,
# което е закупено за кученцето, ще е достатъчно докато кученцето бъде осиновено.
food_bought_kg... |
_base_ = [
'../_base_/models/retinanet_r50_fpn.py',
'../_base_/datasets/coco_detection.py',
'../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py'
]
pretrained = 'https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_tiny_patch4_window7_224.pth' # noqa
model = dict(
bac... |
def formatset(rs,fs):
for key,value in rs.items():
if value:
fs=fs.replace('%'+key+'%',value)
else:
fs=fs.replace('%'+key+'%','')
return fs
def myfilter(lines,args):
for line in lines:
line=line.decode('utf8')
match=args['regex'].match(line)
... |
#!/usr/bin/python
""" Functions for calculating distributions (pT, eta)"""
def ptdistr(particles, ptypelist, ptpoints, deltapt,
ypoint, deltay, dndptsums, pseudorap=False):
""" Calculate identified particle pT distribution.
Input:
particles -- List of ParticleData objects
ptypelist ... |
class Solution:
def removeDuplicates(self, nums: list[int]) -> int:
if nums == []:
return 0
res = 0
for i in range(1, len(nums)):
if nums[i] != nums[res]:
res += 1
nums[res] = nums[i]
return res + 1 |
real = float(input('Digite o quantos reais você tem: R$'))
dolar = real / 5.60
print('Com R${:.2f} você consegue comprar US${:.2f}. '.format(real, dolar))
|
_base_ = [
'../_base_/models/mocov3_vit-small-p16.py',
'../_base_/datasets/imagenet_mocov3.py',
'../_base_/schedules/adamw_coslr-300e_in1k.py',
'../_base_/default_runtime.py',
]
# dataset settings
img_norm_cfg = dict(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
# the difference between ResNet... |
reverse_num= 0
for i in range(10,1000):
for j in range(10,1000):
number= i*j
original_num= number
reverse_num= 0
while(number!=0):
r= number % 10
reverse_num = reverse_num *10 + r
number= number//10
if(original_num==reverse_num):
... |
MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
... |
# Christian Webber
# August 30th, 2013
# Assignment 1
# Intended for Windows
debugging = False # Turn on or off test-specific pass/fail output
subDebugging = False # Turn on or off sub-function output
# Debugging output printer
# Input:
# - s: the string to be outputted
# Returns:
# - N/A
def debug(*s):
if d... |
# Ex. 1
def partition(input_list, start, end, pivot_position):
pivot = input_list[pivot_position]
indexes = list(range(start, end + 1))
indexes.remove(pivot_position)
i = indexes[0]
for index in indexes:
if input_list[index] < pivot:
swap(input_list, index, i)
i = n... |
def sqrt(number: int) -> int:
if number in {0, 1}:
return number
low = 0
high = number // 2 + 1
_result = None
while high >= low:
mid = (low + high) // 2
sq = mid * mid
if sq == number:
return mid
elif sq < number:
low = mid + 1
... |
# Standard Class definition
class BrazilianNumber:
countryCode = 55
def __init__(self, area_code, number):
self.area_code = area_code
self.number = number
def __str__(self):
return f'+ {BrazilianNumber.countryCode} ({self.area_code}) {self.number}'
# Defining a Class with th... |
"""Things that deal with UDF results that do not depend on the rest of DAGs.
Clients should almost never have to deal with anything in this module or its
submodules.
"""
|
"""
This module contains stuff related to bandwidth scanners.
.. toctree::
:maxdepth: 2
bandwidth/file.rst
"""
# TODO: Write a better docstring
|
# This file is part of Moksha.
# Copyright (C) 2008-2010 Red Hat, Inc.
#
# 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 ... |
numbers = frozenset({0 , 1, 2, 3, 4, 5, 6, 7, 8, 9})
# numbers.add(20) AttributeError
print(numbers)
users = {1, 2, 3, 4, 5}
users.add(2)
users.add(6)
print(len(users))
|
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: Set[str]
:rtype: List[str]
"""
if not s:
return []
# dp[i] means first i letters can be formed by words in the dictionary
dp = [False] * (len(s)+1)
... |
#!/usr/bin/env python3
# "+", "-", "*", "/".
# Must contain at least 2 lower case and 2 upper case characters, 2 digits, and 2 special chars.
__author__ = "Mert Erol"
pwd = "aA00++"
def is_valid():
special = ["+", "-", "*", "/"]
upper = 0
lower = 0
digit = 0
spam = 0
specialdigit = 0
# You... |
class CameraPoolManager:
"""Pool class for containing all camera instances."""
def __init__(self):
self._instances = {}
def __repr__(self):
return '<{0} id={1}>: {2}'.format(self.__class__.__name__, id(self),
repr(self._instances))
def __str__... |
"""
Date Created: 2018-02-27
Date Modified: 2018-02-27
Version: 1
Contract Hash: 0a8b34b4097f0a472d5a31726d70ff807d37490d
Available on NEO TestNet: False
Available on CoZ TestNet: False
Available on MainNet: False
Example:
Test Invoke: ... |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class DatabaseStateEnum(object):
"""Implementation of the 'DatabaseState' enum.
Specifies the state of the Exchange database copy.
Specifies the state of Exchange Database Copy.
'kUnknown' indicates the status is not known.
'kMounted' indic... |
# -*- coding: utf-8 -*-
# Copyright (c) 2011-2020 Raphaël Barrois
# This code is distributed under the two-clause BSD license.
def load_tests(loader, standard_tests, pattern):
return standard_tests
|
def gkstn(N):
count = 0
for i in range(1,N+1):
arr = list(map(int,str(i)))
if i < 100:
count += 1
elif arr[0]-arr[1] == arr[1]-arr[2]:
count += 1
return count
N = int(input())
print(gkstn(N))
|
class Season():
def __init__(self):
print("FUCK YOU!")
|
# Дано предложение. Определить количество букв н, предшествующих первой запятой предложения.
# Рассмотреть два случая: известно, что запятые в предложении есть; запятых в предложении может не быть.
# -*- coding: utf-8 -*-
if __name__ == '__main__':
sentense = input("Введите предложение: ")
comma = int(... |
# Assign foobar which gives the output shown in the last example.
# Hint: Use the triple quote as the outermost quote
foobar = '''"No, thanks, Mom," I said, "I don't know how long it will take."'''
print(foobar)
|
'''
--- Day 1: No Time for a Taxicab ---
--- Part Two ---
Then, you notice the instructions continue on the back of the Recruiting Document. Easter Bunny HQ is actually at the first location you visit twice.
For example, if your instructions are R8, R4, R4, R8, the first location you visit twice is 4 blocks away, due... |
class Event(object) :
"""
Events sent from NodeJS parent process websocket.
Handled in the Strategy base class.
"""
FIND_SIGNAL = 'FIND_SIGNAL'
BUILD_ORDER = 'BUILD_ORDER'
EXECUTE_ORDER = 'EXECUTE_ORDER'
AUDIT_STRATEGY = 'AUDIT_STRATEGY'
STORE_FILL = 'STORE_FILL'
FINISHED_TRADIN... |
p_termo = int(input('Primeiro termo: '))
razao = int(input('Razão: '))
c = 10
while c > 0:
print(p_termo, end=' ')
p_termo += razao
c -= 1
if c == 0:
c = int(input('\nAcrescentar mais números na sequência: ')) |
dataset_type = 'RCTW17Dataset'
data_root = 'data/rctw_17/'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadOBBAnnotations', with_bbox=True,
with_label=True, with_poly_as_mask=True),
... |
ANTLR_JAR_PATH = 'antlr-3.5.2-complete-no-st3.jar'
def onrun_antlr(unit, *args):
unit.onpeerdir(['build/external_resources/antlr3'])
unit.on_run_java(['-jar', '$ANTLR3_RESOURCE_GLOBAL/' + ANTLR_JAR_PATH] + list(args))
|
''' auxiliar_functions
Series of tools for using in project development.
Created on 05/05/2019
@author: Carlos Cesar Brochine Junior
'''
def funcao_test(teste):
return teste
if __name__ == '__main__':
a = funcao_test('Hello World')
print(a) |
#!/usr/bin/python3
def explore(nodes, visited, path_list, node):
if node == 'start':
return path_list
if node != 'end' and node.islower() and node in visited:
return path_list
visits = visited + [node]
if node == 'end':
path_list.append(visits)
return path_list
next... |
'''
Crie um algorítmo que leia um núemo e mostre o seu dobro, triplo e raiz quadrada.
'''
print('===== Exercício 06 =====')
n1 = int(input('Digite um número: '))
print(f'O dobro de {n1} é {2*n1}, o triplo é {3*n1} e sua raiz quadrada é {pow(n1, (1/2))}')
print('O dobro de {} é {}, o triplo é {} e sua raiz quadrada é {... |
def query_custom_answers(question, answers, default=None):
"""Ask a question via raw_input() and return the chosen answer.
@param question {str} Printed on stdout before querying the user.
@param answers {list} A list of acceptable string answers. Particular
answers can include '&' before one o... |
if __name__ == '__main__':
a,b = int(input()),int(input())
div = divmod(a,b)
print(div[0])
print(div[1])
print(div) |
MORZE = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---",
".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]
class Solution:
def uniqueMorseRepresentations(self, words: List[str]) -> int:
return len(set([''.join... |
def fetch_audio_features(sp, username, songs_collection, audio_features_collection):
# Audio features fetching
cursor = songs_collection.find({'user_id': username})
for doc in cursor:
artist = doc['song_artist']
name = doc['song_name']
id = doc['spotify_id']
print("=> Checkin... |
"""https://open.kattis.com/problems/freefood"""
N = int(input())
days = []
for _ in range(N):
s, t = map(int, input().split())
for each in range(s, t+1):
if each not in days:
days.append(each)
print(len(days))
|
# Extract class or function along with its docstring
# Docstring will be captured in group 1 and group 0 contains the whole class or function along with its docstring.
DEF_WITH_DOCS_REGEX = r'((def|class).*((\s*->\s*.*)|):\n\s*"""(\n\s*.*?)*""")'
# Given a docstring, identity each part, i.e, parameters and return valu... |
"""
Dado 2 números inteiros ("a" e "b"), retorne true caso eles sejam "6" ou se sua
soma ou diferença absoluta resulte em 6.
"""
def love6(a, b):
return a == 6 or b == 6 or a+b == 6 or abs(a-b) == 6
print(love6(4, 2))
|
#!/usr/bin/python
"""
runs on the server, prints HTML to create a new page;
url=http://localhost/cgi-bin/tutor0.py
"""
print('Content-type: text/html\n')
print('<TITLE>CGI 101</TITLE>')
print('<H1>A First CGI Script</H1>')
print('<P>Hello, CGI World!</P>')
|
s=input();sl=len(s);l=0;r=0
for i in range(sl):
if s[i]==')':
if r==0:
l+=1
else:
r-=1
else:
r+=1
print(l+r)
|
class Caesar():
#CS50X Caesar task in python
def caesar_main(self):
key = int(input("Key (number) : ")) # get key number
caesar = input("Text : ") # get string
new_caesar = "" #converted string
for i in caesar: #loop in given string
if i.isalpha(): # if i is alpha (a-z)... |
# -*- coding: utf-8 -*-
# Converted from NotoSansSC-Regular.otf using:
# ../../../utils/font2bitmap.py -s '万事起头难。熟能生巧。冰冻三尺,非一日之寒。三个臭皮匠,胜过诸葛亮。今日事,今日毕。师父领进门,修行在个人。一口吃不成胖子。欲速则不达。百闻不如一见。不入虎穴,焉得虎子。' NotoSansSC-Regular.otf 30
MAP = (
'皮口胜亮难成巧冰寒闻匠焉父起一生领入诸在百,之修个吃日穴今师不得'
'门虎速葛事。冻达尺行头非过则熟三毕人臭子欲如能进见胖万'
)
BPP = 1
HEIG... |
"""
The Black shade analyser and comparison tool.
"""
__author__ = "Richard Si, et al."
__license__ = "MIT"
__version__ = "22.5.dev1"
|
def bubbleSort(arr):
# This is the bubble sort algorithm implementation.
ind = 0
while ind < len(arr):
x = 0
while x < len(arr):
if arr[x] > arr[ind]:
temp = arr[ind]
arr[ind] = arr[x]
arr[x] = temp
x+=1
ind+=1
... |
vet = list(map(int, input().split()))
a = vet[0]
ultimo_valor = len(vet) - 1
n = vet[ultimo_valor]
soma = 0
for i in range(0, n):
soma += a + i
print(soma)
|
def sieve_of_eratosthenes(num):
prime = [True] * (num + 1)
p = 2
while (p * p <= num):
# If prime[p] is not changed, then it is a prime
if (prime[p] is True):
# Update all multiples of p
for i in range(p * 2, num + 1, p):
prime[i] = False
... |
#Written by Kenneth Nero <https://github.com/KennethNero>
# Simple function to create an array of mathcing elements
# between two lists.
def intersection(ls1, ls2):
result = [v for v in ls1 if v in ls2]
return result
# Main function that operates on the command line to take
# in and send output.
def main():
... |
# -*- coding: utf-8 -*-
openings = [
{"name": "Alekhine Defense", "eco": "B02", "fen": "rnbqkb1r/pppppppp/5n2/8/4P3/8/PPPP1PPP/RNBQKBNR w KQkq", "moves": "1. e4 Nf6", "position": "rnbqkb1r/pppppppp/5n2/8/4P3/8/PPPP1PPP/RNBQKBNR"},
{"name": "Alekhine Defense, 2. e5 Nd5 3. d4", "eco": "B03", "fen": "rnbqkb1r/pppppppp/... |
def kaziZdravo():
print("Pozdrav svima!") #blok koji pripada funkciji
#kraj funkcije
kaziZdravo() #poziv funkcije
kaziZdravo() #opet poziv funkcije
|
ins_set={
0x00:[1,0,"exit"],
0x01:[3,2,"mov r{0},0x{1:0>2X}"],
0x11:[3,2,"mov r{0},r{1}"],
0x21:[3,2,"mov [r{0}],0x{1:0>2X}"],
0x31:[3,2,"mov [r{0}],r{1}"],
0x02:[2,1,"inc r{0}"],
0x03:[2,1,"push r{0}"],
0x04:[2,1,"pop r{0}"],
0x05:[2,1,"r{0} = getchar()"],
0x06:[2,1,"p... |
"""
2) :
Crie um programa que leia 6 valores inteiros e, em seguida, mostre na tela os valores lidos :
"""
n = []
for v in range(0, 6):
v = int(input("Digite valor: "))
n.append(v)
'\n'
for v in n:
print(v)
|
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
if s == "": return ""
if s == None: return None
maxFound = s[0]
maxLen = 1
s_len = len(s)
#odd length palindromes
for i i... |
class GreyForecast:
tag = ""
k = 0
original_value = 0.0
forecast_value = 0.0
error_rate = 0.0
average_error_rate = 0.0
|
# Use the file name mbox-short.txt as the file name
fname = input("Enter file name: ") # allow user to type the file name
try:
fh = open(fname)
except:
print("File does not exist")
quit() #when the file does not exist, then stop the programme
count = 0
total = 0
for line in fh:
if not line.startswith("X... |
def get_instance_name(x):
"""Gets the name of the instance"""
return x.__class__.__name__.lower()
def is_unique(xs):
"""Tests if all x in xs belong to the same instance"""
fn = get_instance_name
xs_set = {x for x in map(fn, xs)}
if len(xs_set) == 1:
return list(xs_set)[0]
return Fal... |
# create a bezier path
path = BezierPath()
# move to a point
path.moveTo((100, 100))
# line to a point
path.lineTo((100, 200))
path.lineTo((200, 200))
# close the path
path.closePath()
# loop over a range of 10
for i in range(10):
# set a random color with alpha value of .3
fill(random(), random(), random(), ... |
lanche = ['hamburguer', 'suco', 'pizza', 'pudim'] #lista
lanche[3] = 'picolé' #Substitui o indice 3 de lanche (pizza) por picolé
lanche.append('coockie') #add cookie no indice 4
lanche.insert(0, 'cachorro-quente') #insere cachorro-quente na posição 0 e 'empurra' o restante para frente
del lanche[3] # deleta indice 3 de... |
'''
Linear regression on appropriate Anscombe data
For practice, perform a linear regression on the data set from Anscombe's quartet that is most reasonably
interpreted with linear regression.
INSTRUCTIONS
100XP
-Compute the parameters for the slope and intercept using np.polyfit(). The Anscombe data are stored
in ... |
# pylint: disable=invalid-name, missing-class-docstring, too-few-public-methods
# flake8: noqa
""" Sample Submissions for test cases. """
class SampleSubmissions:
""" Static submissions for test cases - BASE and DATAPATH (which references BASE) """
class UNIT_TESTS:
STORAGE_VALID = "storage_connection... |
# from pandas import DataFrame
# from server.database import Database
# from server.sendmail import Smtp
# import mylibrary.genmail as gm
# smtp_data = ['CAS-HT02.systex.tw', '25', '2000089', 'Cdec76461110']
# mailserver = Smtp(smtp_data[0], int(smtp_data[1]), smtp_data[2], smtp_data[3])
# mail_msg = gm.gen_test_eml(... |
'''
Напишите программу подсчета букв ‘a’ в строке «abrakadabra»
Selfedu001133PyBeginCh03p02TASK01
'''
str = 'abrakadabra'
count = 0
for i in range(len(str)):
if str[i] == 'a':
count += 1
print(count)
|
"""
"""
CARDINALITY_SLOP = 1
def is_discrete(num_records: int, cardinality: int, p=0.15):
"""
Estimate whether a feature is discrete given the number of records
observed and the cardinality (number of unique values)
The default assumption is that features are not discrete.
Parameters
-------... |
{
"targets": [
{
"includes": [
"auto.gypi"
],
"sources": [
"../src/index.cc"
],
"cflags": [
"-Wall",
"-Wno-deprecated",
"-Wno-deprecated-declarations",
"-Wno-cast-function-type",
"-Wno-class-memaccess",
"-O2",
"-Ofast",
"-pthread"
]
}
],
"includes": [
... |
#!/usr/bin/env python
Pdir = "/root/ansible"
LOG_FILENAME = Pdir+'/ConfigGen.log'
LOGGER_NAME = 'ConfigGen'
CONFIG_DATA_FILE = '/root/input.json'
VAR_CONF_FILE = Pdir+'/vars/gen.yml'
PAYLOAD_LOC = Pdir+'/payload'
GEN_LOC = Pdir+'/payload'
|
# ARRAYS-DS HACKERRANK SOLUTION:
# creating a function to reverse the given array.
def reverseArray(arr):
# code to reverse the given array.
reversed_array = arr[::-1]
# returning the reversed array.
return reversed_array
# receiving input.
arr_count = int(input().strip())
arr = list(ma... |
class BaseResponse(object):
_allowedResponses = []
_http_responses = {}
def __init__(self, allowedResponses=None):
self.__allowedResponses = allowedResponses
for code in allowedResponses:
status_code = str(code)
self._http_responses[status_code] = self._def... |
with open("map.txt", 'r') as fd:
contents = fd.readlines()
mapping = {}
for line in contents:
row, col, name = line.strip().split("\t")
pos = (int(row), int(col))
if pos in mapping:
print("Collision!", pos)
mapping[pos] = name |
'''Crie um programa que mostre na tela todos os numeros pares que estao no intervalo de 1 a 50.'''
for c in range(1,50 +1,):
if c % 2 == 0:
print(c) |
# day one, advent 2020
def day_one():
# read input for day one, calculate and print answer
with open('advent/20201201.txt', 'r') as f:
data = f.read()
data = [int(i) for i in data.split()]
for i in data:
for j in data:
if i + j == 2020:
print(f"Day 1.1: i:... |
__author__ = 'petar@google.com (Petar Petrov)'
class GeneratedServiceType(type):
_DESCRIPTOR_KEY = 'DESCRIPTOR'
def __init__(cls, name, bases, dictionary):
if GeneratedServiceType._DESCRIPTOR_KEY not in dictionary:
return
descriptor = dictionary[GeneratedServiceType._DESCRIPTOR_KEY... |
def to_rna(dna):
rna = ''
dna_rna = {'G':'C', 'C':'G', 'T':'A', 'A':'U'}
for char in dna:
try:
rna = rna + dna_rna[char]
except:
return ""
return rna
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.