content stringlengths 7 1.05M |
|---|
YEAR_IN_S = 31557600.
GEV_IN_KEV = 1.e6
C_KMSEC = 299792.458
NUCLEON_MASS = 0.938272 # Nucleon mass in GeV
P_MAGMOM = 2.793 # proton magnetic moment, PDG Live
N_MAGMOM = -1.913 # neutron magnetic moment, PDG Live
NUCLEAR_MASSES = {
'xenon': 122.298654871,
'germanium': 67.663731424,
'argon': 37.2113263068,... |
class FrameworkTextComposition(TextComposition):
""" Represents a composition during the text input events of a System.Windows.Controls.TextBox. """
def Complete(self):
"""
Complete(self: FrameworkTextComposition)
Finalizes the composition.
"""
pass
CompositionLength=property(lambda self: object(... |
def get_version(testbed: str):
path = [e for e in testbed.split(" ") if e.find("/") > -1][0]
full_name = path.split("/")[-1]
return full_name.replace(".jar", "")
def parse_engine_name(testbed: str):
return get_version(testbed).split("-")[0]
|
def predict(text, with_neu=True): # requires string input.
start_at = time.time()
x_test = pad_sequences(tokenizer.texts_to_sequences([text]), maxlen=seq_len)
score = model.predict([x_test])[0]
label = decode_sentiment(score, with_neu=with_neu)
score = float(score)
return {print(f"label: {label}... |
def get_session_attributes(previous_intent = "", previous_intent_attributes = "", requested_value = "", previous_requested_value = "", questions_urls = [], question_now_id = 0, question_name = "", answers_ids = [], answer_now_id = 0, comments_ids = [], comment_now_id = 0, complete_answer = [], complete_code = [], comp... |
# Definición de parámetros de configuración
PeriodoDePoleo = 30000 # Milisegundos entre cada poleo de mediciones
AlmacenamientoLocal = False # Define si los datos se alamacenarán localmente o no
Compresion = False # Define si los datos que se almacenarán localmente serán comprimidos
EnvioAlaNube = True # Define si los... |
def bag_of_words(text):
"""Returns bag-of-words representation of the input text.
Args:
text: A string containing the text.
Returns:
A dictionary of strings to integers.
"""
bag = {}
for word in text.lower().split():
bag[word] = bag.get(word, 0) + 1
return bag
|
STATS = [
{
"num_node_expansions": 0,
"search_time": 0.0929848,
"total_time": 0.206795,
"plan_length": 209,
"plan_cost": 209,
"objects_used": 145,
"objects_total": 253,
"neural_net_time": 0.09392738342285156,
"num_replanning_steps": 0,
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 17 10:43:46 2017
@author: ASUS
This code snippet finds the given spliced motif within the given DNA sequence
"""
#I put \n manually so that it fits to my solution
fasta_formatted_input = ">Rosalind_4080\nGTTACTGCCGAGTGCAAGCAACTTATTGCTGATTGGTCCGTGTAGGCTGTTAGCAGTTAGAATCTCT... |
"""
Files in nftfw - and a description of what they do
PackageIndex.txt this file
__init__.py amend the Python module lookup
Main nftfw application
----------------------
__main__.py Main application, deals with argument decode
and dispatch
config.py Class Config - supplies default... |
class Basededados:
def __init__(self):
self._dados = {}
def inserir_cliente(self,id , nome):
if 'clientes' not in self._dados: #Se o cliente não existir nos dados
self._dados['clientes'] = {id:nome} #o ID vai ser o nome
else:
self._dados['clientes'].update({id:n... |
# Copyright (c) 2020 Trail of Bits, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is di... |
# container.py - Creates META-INF/content.xml within the epub file
def create_container(epub_file):
epub_file.writestr('META-INF/container.xml', '''<?xml version="1.0"?>
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
<rootfiles>
<rootfile full-path="OEBPS/cont... |
APP_MIN_WIDTH = 1024
APP_MIN_HEIGHT = 800
APP_NAME = 'Fractals'
APP_FONT = 12
|
s = input()
ans = []
i=0
while i<len(s):
if s[i]=='.':
ans.append('0')
else:
if s[i+1]=='.':
ans.append('1')
else:
ans.append('2')
i=i+1
i+=1
for j in ans:
print(j,end='') |
def usersagein_Sec():
users_age = int(input("Enter user age in years"))
agein_sec = users_age *12 *365 * 24
print(f"Age in sec is {agein_sec}")
print("Welcome to function project 1 ")
usersagein_Sec()
# Never use same name in anywhere inside a function program. else going to get error.
friends ... |
def test_non_standard_default_desired_privilege_level(iosxe_conn):
# purpose of this test is to ensure that when a user sets a non-standard default desired priv
# level, that there is nothing in genericdriver/networkdriver that will prevent that from
# actually being set as the default desired priv level
... |
class Trader(object):
"""An entity buying and/or selling on the market."""
def __init__(self, name, funds=0, units=0):
self.name = name
self.funds = funds
self.units = units
def __repr__(self):
return "[Trader: name={}, funds={}, units={}]".format(self.name, self.funds, sel... |
fruits = {
"orange" :"a sweet,orange citrus fruit",
"apple" :"good for making cider",
"lemon" :"a sour,yellow citrus fruit",
"grape" :"a small, sweet fruit growing in bunches",
"lime" :"a sour,yellow citrus fruit",
}
def simple_operation():
print("T... |
# Mac address of authentication server
AUTH_SERVER_MAC = "b8:ae:ed:7a:05:3b"
# IP address of authentication server
AUTH_SERVER_IP = "192.168.1.42"
# Switch port authentication server is facing
AUTH_SERVER_PORT = 3
#CTL_REST_IP = "192.168.1.39"
CTL_REST_IP = "10.0.1.8"
CTL_REST_PORT = "8080"
CTL_MAC = "b8:27:eb:b0:1d... |
print('-=-=-=-= DESAFIO 64 -=-=-=-=')
print()
n = tot = soma = 0
print('Para sair, digite "999".')
while n != 999:
n = int(input('Digite um número: '))
if n != 999:
tot += 1
soma += n
print('Foram digitados {} valores e a soma entre eles vale {}.'.format(tot, soma))
# RESOLUÇÃO do PROF:
# n = i... |
running = True
# Global Options
SIZES = {'small': [7.58, 0], 'medium': [9.69, 1], 'large': [12.09, 2], 'jumbo': [17.99, 3], 'party': [20.29, 4]} # [Price, ID]
TOPPINGS = {'pepperoni': [0, False], 'bacon': [0, True], 'sausage': [0, False], 'mushroom': [1, False], 'black olive': [1, False], 'green pepper': [1, False]} #... |
#
# PySNMP MIB module EdgeSwitch-QOS-AUTOVOIP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EdgeSwitch-QOS-AUTOVOIP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:10:44 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... |
# #!/usr/bin/env python
# encoding: utf-8
#
# --------------------------------------------------------------------------------------------------------------------
# Name: amortization.py
# Version: 0.0.1
# Summary: Para que a dívida seja totalmente paga, o tomador deve quitar o montante inicial adicionado aos jur... |
def reverse(my_list):
if type(my_list) != list:
return f"{my_list} is not a list"
elif len(my_list) ==0:
return 'list should not be empty'
reversed_list = my_list[::-1]
return reversed_list
if __name__ == "__main__":
riddle_index = 0
|
"""
@author: David Lei
@since: 28/08/2016
@modified:
ReTRIEval tree = Trie
Tree data structure (reTRIEval tree)
- used to store collections of strings
- if 2 strings have a common prefix, will have a same ancestor in this tree
- idea for dictionaries, less space compared to hashtable
a.k.a digital tree, radix tree,... |
class _dafny:
def print(value):
if type(value) == bool:
print("true" if value else "false", end="")
elif type(value) == property:
print(value.fget(), end="")
else:
print(value, end="")
|
limit=int(input("enter the limit"))
no=int(input("enter the no"))
for i in range(1,limit+1,1):
multi=no*i
print(no,"*",i,"=",multi) |
"""Exceptions raised by `e2e.pom` at runtime."""
class PomError(Exception):
"""Base exception from which all `e2e.pom` errors inherit."""
class ElementNotUniqueErrror(PomError):
"""Raised when multiple DOM matches are found for a "unique" model."""
class ElementNotFoundErrror(PomError):
"""Raised when... |
months = {
'01':'janvier',
'02':'février',
'03':'mars',
'04':'avril',
'05':'mai',
'06':'juin',
'07':'juillet',
'08':'août',
'09':'septembre',
'10':'octobre',
'11':'novembre',
'12':'décembre'
}
def str_date_fr(date: str) -> str:
date = date.split('-')
if len(date)... |
class Arithmetic:
def __init__(self, command):
self.text = command
def operation(self):
return self.text.strip()
class MemoryAccess:
def __init__(self, command):
self.op, self.seg, self.idx = tuple(command.split())
def operation(self):
return self.op
def segmen... |
N = int(input())
pokemons = []
while (N != 0):
Name = input()
pokemons.append(Name)
N-= 1
print('Falta(m) {} pomekon(s).'.format(151 - len(set(pokemons))))
|
def count_salutes(hallway):
count=hallway.count("<")
total=0
for i in hallway:
count-=i=="<"
if i==">":
total+=count*2
return total
|
# Python - 3.6.0
Test.assert_equals(catch_sign_change([1, 3, 4, 5]), 0)
Test.assert_equals(catch_sign_change([1, -3, -4, 0, 5]), 2)
Test.assert_equals(catch_sign_change([]), 0)
Test.assert_equals(catch_sign_change([-47, 84, -30, -11, -5, 74, 77]), 3)
|
num = int(input('Digite um número para teste:'))
tot = 0
for c in range(1, num + 1):
if num % c == 0:
print('\033[1;33m', end='')
tot +=1
else:
print('\033[1;34m', end='')
print(f'{c}', end=' ')
print(f'\nO número {c} foi divisível {tot} vezes.')
if tot == 2:
print('E por isso e... |
{
'targets': [
{
'target_name': 'murmurhash3',
'sources': ['src/MurmurHash3.cpp', 'src/node_murmurhash3.cc'],
'cflags': ['-fexceptions'],
'cflags_cc': ['-fexceptions'],
'cflags!': ['-fno-exceptions'],
'cflags_cc!': ['-fno-exception'],
"include_dirs" : [
"<!(node... |
def create_desktop_file_KDE():
path="/usr/share/applications/klusta_process_manager.desktop"
text=["[Desktop Entry]",
"Version=0.1",
"Name=klusta_process_manager",
"Comment=GUI",
"Exec=klusta_process_manager",
"Icon=eyes",
"Terminal=False",
"Type=Application",
"Categories=Applications;... |
class BinarySearchTreeNode:
def __init__(self,data):
self.data=data
self.left=None
self.right=None
def add_child(self,data):
if data == self.data:
return
if data <self.data:
#add on the left side of the subtree
if self.left:
... |
# -*- coding: utf-8 -*-
# Scrapy settings for cosme project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'cosme'
SPIDER_MODULES = ['cosme.spiders']
NEWSPIDER_... |
# The Tribonacci sequence Tn is defined as follows:
# T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.
# Given n, return the value of Tn.
# Example 1:
# Input: n = 4
# Output: 4
# Explanation:
# T_3 = 0 + 1 + 1 = 2
# T_4 = 1 + 1 + 2 = 4
# Example 2:
# Input: n = 25
# Output: 1389537
# Constraints:
# ... |
# Time: O(n)
# Space: O(h), h is height of binary tree
# 129
# Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
#
# An example is the root-to-leaf path 1->2->3 which represents the number 123.
#
# Find the total sum of all root-to-leaf numbers.
#
# For example,
#
# ... |
"""
Georgia Institute of Technology - CS1301
HW04 - Strings, Indexing and Lists
"""
#########################################
"""
Function Name: findMax()
Parameters: a caption list of numbers (list), start index (int), stop index (int)
Returns: highest number (int)
"""
def findMax(theNumbersMason, theStart, theEnd):... |
"""
Midi pitch values:
A0 has value 21
C8 has value 108
"""
NAME_TO_VAL = {
"C": 0,
"D": 2,
"E": 4,
"F": 5,
"G": 7,
"A": 9,
"B": 11,
}
def name_to_val(name):
name = name.upper()
note = name[0]
mod = None
octave = None
offset = 12
if name[1] in ("#", "B"):
... |
task = int(input())
points = int(input())
course = input()
if task == 1:
if course == 'Basics':
points = points * 0.08 - (0.2 * (points * 0.08))
elif course == 'Fundamentals':
points = points * 0.11
elif course == 'Advanced':
points = points * 0.14 + (0.2 * (points * 0.14))
elif ta... |
# Given a number N, print the odd digits in the number(space seperated) or print -1 if there is no odd digit in the given number.
number = int(input(''))
array = list(str(number))
flag = 0
for digit in range(0, len(array)-1):
if(int(array[digit]) % 2 == 0):
print(' ', end='')
else:
print(array... |
"""A function to reverse a string.
By Ted Silbernagel
"""
def reverse_string(input_word: str) -> str:
return_word = ''
for _ in input_word:
return_word += input_word[-1:]
input_word = input_word[:-1]
return return_word
if __name__ == '__main__':
user_string = input('Please enter a word/string to r... |
"""
File: forestfire.py
----------------
This program highlights fires in an image by identifying
pixels who red intensity is more than INTENSITY_THRESHOLD times
the average of the red, green, and blue values at a pixel.
Those "sufficiently red" pixels are then highlighted in the
image and the rest of the image is turn... |
class Rectangle:
def __init__(self, width):
self.__width = width
@property
def width(self):
return self.__width
@width.setter
def width(self, w):
if w > 0:
self.__width = w
else:
raise ValueError
# Теперь работать с width и height можно так... |
t5_generation_config = {
"do_sample": True,
"num_beams": 2,
"repetition_penalty": 5.0,
"length_penalty": 1.0,
"num_return_sequences": 1,
}
GPT2_generation_config = {
"do_sample": True,
"num_beams": 2,
"repetition_penalty": 5.0,
"length_penalty": 1.0,
} |
# -*- coding: utf-8 -*-
"""
Created on Tue May 7 12:11:09 2019
@author: DiPu
"""
A1=int(input())
A2=int(input())
A3=int(input())
E1=int(input())
E2=int(input())
weighted_score=((A1+A2+A3)*0.1)+((E1+E2)*0.35 )
print("weightrd score is",weighted_score)
|
# Pyomniar
# Copyright 2011 Chris Kelly
# See LICENSE for details.
class OmniarError(Exception):
"""Omniar exception"""
def __init__(self, reason, response=None):
self.reason = unicode(reason)
self.response = response
def __str__(self):
return self.reason |
while True:
number = int(input('Enter a number: '))
while number != 1:
if number % 2 == 0:
number //= 2
else:
number = number * 3 + 1
print(number)
print()
|
# ------------------------------
# 276. Paint Fence
#
# Description:
# There is a fence with n posts, each post can be painted with one of the k colors.
# You have to paint all the posts such that no more than two adjacent fence posts have the same color.
#
# Return the total number of ways you can paint the fence.
#... |
def get_index_different_char(chars):
alphanumeric_count, not_alphanumeric_count = 0, 0
last_alphanumeric_idx, last_not_alphanumeric_idx = 0, 0
alphanumeric = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
for idx, char in enumerate(chars):
if str(char) in alphanumeric:
... |
#Conditional if
x = 22
y = 100
if y < x:
print("This is True, y is not greater than x!")
elif y == x:
print("This is True, y is greater than x!")
else:
print("Anything else!")
print("Completed")
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
models
----------------------------------
Models store record state during parsing and serialisation to other formats.
"""
class InventoryItem(object):
""" Inventory Item Model """
def __init__(self, id=None, price=None, description=None, cost=None, price_t... |
""""""
_TEST_TEMPLATE = """#!/bin/bash
# Unset TEST_SRCDIR since we're trying to test the non-test behavior
unset TEST_SRCDIR
# --- begin runfiles.bash initialization v2 ---
# Copy-pasted from the Bazel Bash runfiles library v2.
set -uo pipefail; f=bazel_tools/tools/bash/runfiles/runfiles.bash
source "${RUNFILES_DIR:-... |
#!/usr/bin/env python
# encoding: utf-8
"""
constants.py
Useful constants; the ones embedded in classes can be thought of as Enums.
Created by Niall Richard Murphy on 2011-05-25.
"""
_DNS_SEPARATOR = "." # What do we use to join hostname to domain name
_FIRST_ONE_ONLY = 0 # If we only want the first match back from... |
"""
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
... |
#import sys
#sys.stdin = open('rectangles.in', 'r')
#sys.stdout = open('rectangles.out', 'w')
n, m, k = map(int, input().split())
a = [[100000, 0, 100000, 0] for i in range(k)]
field = []
for i in range(n):
field.append(list(map(int, input().split())))
field.reverse()
for i in range(n):
for j in range(m):
... |
def _cc_injected_toolchain_header_library_impl(ctx):
hdrs = ctx.files.hdrs
transitive_cc_infos = [dep[CcInfo] for dep in ctx.attr.deps]
compilation_ctx = cc_common.create_compilation_context(headers = depset(hdrs))
info = cc_common.merge_cc_infos(
cc_infos = transitive_cc_infos + [CcInfo(compila... |
"""
Given two integers n and k, return all possible combinations of k numbers out
of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
"""
class Solution(object):
def combine(self, n, k):
"""
:type n: int
:type k: int
... |
#
# PySNMP MIB module TRAPEZE-NETWORKS-REGISTRATION-DEVICES-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRAPEZE-NETWORKS-REGISTRATION-DEVICES-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:27:22 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user da... |
# coding: utf-8
def base_reducer(suffler_results):
# Неплохо бы рекурсивную реализацию
n = len(suffler_results)
if n == 1:
return suffler_results
else:
A_raw = suffler_results[:n/2]
B_raw = suffler_results[n/2:]
A = base_reducer(A_raw)
B = base_reducer(B_raw)
... |
class Solution:
def searchMatrix(self, matrix, target):
i = 0
m = len(matrix)
while i < m and matrix[i][0] <= target:
i = i + 1
i = i - 1
return target in matrix[i]
if __name__ == '__main__':
matrix = [[1]]
target = 1
ans = Solution().searchMatrix(mat... |
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file")
def _download_binary(ctx):
ctx.download(
url = [
ctx.attr.uri,
],
output = ctx.attr.binary_name,
executable = True,
)
ctx.file(
"BUILD.bazel",
content = 'exports_files(glob(["*"]))'... |
# Basic type checking: no types necessary
x = 3
x + 'a'
def return_type() -> float:
return 'a'
return_type(9)
def argument_type(x: float):
return
argument_type()
|
def sudoku(board, rows, columns):
return helper(board, 0, 0, columns, rows)
def helper(board, r, c, rows, columns):
def inbound(r, c):
return (0 <= r < rows) and (0 <= c < columns)
# Out of bounds:
# We filled all blank cells and, thus, a valid solution
if not inbound(r, c):
return True
nr, nc = ... |
"""
Configuration file
"""
URL = 'localhost'
PORT = 1883
KEEPALIVE = 60
UDP_URL = 'localhost'
UDP_PORT = 1885
|
'''Print multiplication table of given number'''
n=int(input("Enter the no:"))
print("Multiplication table is:")
for i in range(1,11):
print(i*n) |
# CONVERT DB_DATA TO STRING FOR SELF-MESSAGE
def format_to_writeable_db_data(db_data: list) -> str:
writeable_data = ""
for user in db_data:
listed_mangoes = ""
for manga in user['mangoes']:
listed_mangoes += f"{manga}>(u*u)>"
writeable_data = f"{writeable_data}{user['name']... |
class SuperList(list):
def __len__(self):
return 1000
super_list1 = SuperList()
print((len(super_list1)))
super_list1.append(5)
print(super_list1[0])
print(issubclass(SuperList, list)) # true
print(issubclass(list, object)) |
vline = '│'
hline = '─'
tlcorner = '┌'
trcorner = '┐'
blcorner = '└'
brcorner = '┘'
cross = '┼'
tcross = '┬'
lcross = '├'
rcross = '┤'
bcross = '┴'
block = '█'
lblock = '▌'
rblock = '▐'
edge = hline * 4
tile_blank = ' ' * 4
tile_full = ' ' + block*2 + ' '
class Grid:
def __init__(self, x, y):
self.x =... |
def reverse(SA):
reverse = [0] * len(SA)
for i in range(len(SA)):
reverse[SA[i] - 1] = i + 1
return reverse
def prefix_doubling(text, n):
'''Computes suffix array using Karp-Miller-Rosenberg algorithm'''
text += '$'
mapping = {v: i + 1 for i, v in enumerate(sorted(set(text[1:])))}
R, k = [mapping[v] ... |
N, M = map(int, input().split())
case = [i for i in range(1, N+1)]
disk = []
for _ in range(M):
disk.append(int(input()))
now = 0
for d in disk:
if d == now:
continue
i = case.index(d)
tmp = case[i]
case[i] = now
now = tmp
for c in case:
print(c)
|
def maximum():
A = input('Enter the 1st number:')
B = input('Enter the 2nd number:')
if A > B:
print("%d The highest num than %d"%(A,B))
else:
print('The highest num is:' ,B)
print("Optised max",max(A,B))
def minimum():
A1 = input('Enter the 1st number:')
B1 = input('Enter ... |
position = list(input())
xPos = int(position[1])
yPos = int(ord(position[0])) - int(ord('a')) + 1
result = 0
# x 2칸 이동
if xPos + 2 > 0 and yPos - 1 > 0:
result += 1
if xPos + 2 > 0 and yPos + 1 > 0:
result += 1
if xPos - 2 > 0 and yPos - 1 > 0:
result += 1
if xPos - 2 > 0 and yPos + 1 > 0:
result += 1
# ... |
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
n = int(input())
shelters = [0] * (n + 1)
f... |
__author__ = 'varx'
class BaseRenderer(object):
"""
Base renderer that all renders should inherit from
"""
def can_render(self, path):
raise NotImplementedError()
def render(self, path):
raise NotImplementedError() |
# -*- coding: utf-8 -*-
# According to https://tools.ietf.org/html/rfc2616#section-7.1
_ENTITY_HEADERS = frozenset(
[
"allow",
"content-encoding",
"content-language",
"content-length",
"content-location",
"content-md5",
"content-range",
"content-type"... |
# 2020 @Cmlohr
MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"c... |
stores = []
command = input()
while command != 'END':
tokens = command.split('->')
store_name = tokens[1]
if tokens[0] == 'Add':
items = tokens[2].split(',')
if len([x for x in stores if x[0] == store_name]) > 0:
idx = stores.index([x for x in stores if x[0] == store_name... |
# This is a great place to put your bot's version number.
__version__ = "0.1.0"
# You'll want to change this.
GUILD_ID = 845688627265536010
|
#dictionary and for statements with values method
linguagens = {
'lea': 'python',
'sara': 'c',
'eddie': 'java',
'phil': 'python',
}
for linguagem in linguagens.values(): #values method shows us the values of a dictionary
print(linguagem.title()) |
class EmitterTypeError(Exception):
pass
class EmitterValidationError(Exception):
pass
|
class BSTNode():
def __init__(self, Key, Value=None):
self.key = Key
self.Value = Value
self.left = None
self.right = None
self.parent = None
@staticmethod
def remove_none(lst):
return [x for x in lst if x is not None]
def check_BSTNode(self):
if... |
LSM9DS1_MAG_ADDRESS = 0x1C #Would be 0x1E if SDO_M is HIGH
LSM9DS1_ACC_ADDRESS = 0x6A
LSM9DS1_GYR_ADDRESS = 0x6A #Would be 0x6B if SDO_AG is HIGH
#/////////////////////////////////////////
#// LSM9DS1 Accel/Gyro (XL/G) Registers //
#/////////////////////////////////////////
LSM9DS1_ACT_THS = 0x04
LSM9DS1_ACT... |
def handle(event, context):
"""handle a request to the function
Args:
event (dict): request params
context (dict): function call metadata
"""
return {
"message": "Hello From Python3 runtime on Serverless Framework and Scaleway Functions"
}
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 10 15:19:36 2020
@author: krishan
"""
class Book:
def __init__(self, pages):
self.pages = pages
def __add__(self, other):
total = self.pages + other.pages
b = Book(total)
return b
... |
"""
字符串抽取程序
抽取类型:
- 抽取单个,抽取全部
"""
"""
string_util 主要处理 比较短的文本,长文本的处理交给text_util
对字符串的一些常见的判断.
1. is_blank 为None或者strip以后为0
2. is_empty 为None或者长度为0
3. has?
4. 返回字符串特点
提取请求url中的中文内容.
"""
def is_blank(_str):
"""
判断是否为空(除去空格换行)
:param _str:
:return:
"""
return _str is None or len(_str.strip()... |
n = int(input('digite um numero: '))
n2 = int(input('digite um numero: '))
def soma ():
s = n + n2
print(soma)
|
# noinspection PyUnusedLocal
# skus = unicode string
def checkout(skus):
sd = dict()
for sku in skus:
if sku in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
if sku in sd:
sd[sku] += 1
else:
sd[sku] = 1
else:
return -1
na = sd.get('A', 0... |
def test_upgrade_atac_alignment_enrichment_quality_metric_1_2(
upgrader, atac_alignment_enrichment_quality_metric_1
):
value = upgrader.upgrade(
'atac_alignment_enrichment_quality_metric',
atac_alignment_enrichment_quality_metric_1,
current_version='1',
target_version='2',
)
... |
PREVIEW_CHOICES = [
('slider', 'Slider'),
('pre-order', 'Pre-order'),
('new', 'New'),
('offer', 'Offer'),
('hidden', 'Hidden'),
]
CATEGORY_CHOICES = [
('accesory', 'Accesory'),
('bottom', 'Bottoms'),
('hoodie', 'Hoodies'),
('outerwear', 'Outerwears'),
('sneaker', 'Sneakers'),
... |
# SPDX-License-Identifier: BSD-2-Clause
"""osdk-manager about details.
Manage osdk and opm binary installation, and help to scaffold, release, and
version Operator SDK-based Kubernetes operators.
This file contains some basic variables used for setup.
"""
__title__ = "osdk-manager"
__name__ = __title__
__summary__ ... |
print("Let's practice everything")
print('You\'d need to know \'bout escapes with \\ that do:')
print('\n newlines and \t tabs.')
poem="""
\tThe lovely world
with logic so firmly planted
cannnot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
""... |
class Estereo:
def __init__(self, marca) -> None:
self.marca = marca
self.estado = 'apagado'
|
list = [2, 4, 6, 8]
sum = 0
for num in list:
sum = sum + num
print("The sum is:", sum)
|
class RDBMSHost:
def __init__(self, host: str, port: int, db_name: str, db_schema: str, db_user: str, db_password: str):
self.host: str = host
self.port: int = port
self.db_name: str = db_name
self.db_schema: str = db_schema
self.db_user: str = db_user
self.db_passwor... |
grid = [input() for _ in range(323)]
width = len(grid[0])
height = len(grid)
trees = 0
i, j = 0, 0
while (i := i + 1) < height:
j = (j + 3) % width
if grid[i][j] == '#':
trees += 1
print(trees)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.