content stringlengths 7 1.05M |
|---|
"""
Solver functions for Sudoku
"""
def print_sudoku(sudoku):
for i in range(len(sudoku)):
line = ""
if i == 3 or i == 6:
print("---------------------")
for j in range(len(sudoku[i])):
if j == 3 or j == 6:
line += "| "
line += str(sudoku[... |
def sum(matriz):
sumValue = 0;
if len(matriz) > 0 and matriz[-1] <= 1000:
for item in matriz:
sumValue += item
return sumValue
print(sum([1, 2, 3]));
|
# https://www.acmicpc.net/problem/11091
input = __import__('sys').stdin.readline
N = int(input())
for _ in range(N):
chars = [0 for _ in range(26)]
line = input().rstrip()
for char in line:
if 97 <= ord(char) < 123:
chars[ord(char) - 97] += 1
elif 65 <= ord(char) < 91:
... |
def http(request):
"""Responds to any HTTP request.
Args:
request (flask.Request): HTTP request object.
Returns:
The response text or any set of values that can be turned into a
Response object using
`make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_respon... |
attendees = ["Ken", "Alena", "Treasure"]
attendees.append("Ashley")
attendees.extend(["James", "Guil"])
optional_attendees = ["Ben J.", "Dave"]
potential_attendees = attendees + optional_attendees
print("There are", len(potential_attendees), "attendees currently")
|
## https://leetcode.com/problems/dota2-senate/
## go through the rounds of voting, where a vote is to ban another
## senator or, if all senators of the other party are banned, delcare
## victory.
## the optimal play for each senator is to ban the first member of
## the opposition party after them. fastest way to ha... |
# init exercise 2 solution
# Using an approach similar to what was used in the Iris example
# we can identify appropriate boundaries for our meshgrid by
# referencing the actual wine data
x_1_wine = X_wine_train[predictors[0]]
x_2_wine = X_wine_train[predictors[1]]
x_1_min_wine, x_1_max_wine = x_1_wine.min() - 0.2, ... |
# addinterest1.py
def addInterest(balance, rate):
newBalance = balance * (1+rate)
balance = newBalance
def test():
amount = 1000
rate = 0.05
addInterest(amount, rate)
print(amount)
test()
|
print ("How many students' test scores do you want to arrange?")
a = input()
if a == "2":
print ("Enter first student's name")
name1 = input()
print ("Enter his/her score")
score1 = input()
print ("Enter second student's name")
name2 = input()
print ("Enter his/her score")
scor... |
def murmur3_32(data, seed=0):
"""MurmurHash3 was written by Austin Appleby, and is placed in the
public domain. The author hereby disclaims copyright to this source
code."""
c1 = 0xCC9E2D51
c2 = 0x1B873593
length = len(data)
h1 = seed
roundedEnd = length & 0xFFFFFFFC # round down to 4... |
# .-. . .-. .-. . . .-. .-.
# `-. | | | | | | `-. |
# `-' `--`-' `-' `-' `-' '
__title__ = 'slocust'
__version__ = '0.18.5.17.1'
__description__ = 'Generate serveral Locust nodes on single server.'
__license__ = 'MIT'
__url__ = 'http://ityoung.gitee.io'
__author__ = 'Shin Yeung'
__author_email__ = 'ityoung@foxma... |
def add(x, y):
return x+y
def product(z, y):
return z*y
|
class Base:
def __secret(self):
print("秘密です")
def public(self):
self.__secret()
class Derived(Base):
def __secret(self):
print("参照されません")
if __name__ == "__main__":
print("Baseクラスの属性:", dir(Base))
print("Derivedクラスの属性:", dir(Derived))
print("Base.public() の結果:")
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 18 12:00:00 2020
@author: divyanshvinayak
"""
for _ in range(int(input())):
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
A.sort()
B.sort()
S = 0
for I in range(N... |
# Project Euler Problem 21
# Created on: 2012-06-18
# Created by: William McDonald
# Returns a list of all primes under n using a sieve technique
def primes(n):
# 0 prime, 1 not.
primeSieve = ['0'] * (n / 2 - 1)
primeList = [2]
for i in range(3, n, 2):
if primeSieve[(i - 3) / 2] == '0... |
maior = 0
menor = 0
for i in range(1, 6): # Verifica qual o peso mais pesada e qual o mais leve, em um grupo de 5 pesos
peso = float(input(f'Digite o {i}° peso: '))
if i == 1: # Se for a primeira vez no loop, o menor e o maior recebem o mesmo peso
menor = peso
maior = peso
else:
i... |
#
# PySNMP MIB module ALTEON-TRAP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALTEON-TRAP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:21:08 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
#!/usr/bin/env python -*- coding: utf-8 -*-
def per_section(it):
""" Read a file and yield sections using empty line as delimiter """
section = []
for line in it:
if line.strip():
section.append(line)
else:
yield ''.join(section)
section = []
# yield any remaining lines as a section t... |
class InfluxDBClientError(Exception):
"""Raised when an error occurs in the request."""
def __init__(self, content, code=None):
"""Initialize the InfluxDBClientError handler."""
if isinstance(content, type(b'')):
content = content.decode('UTF-8', 'replace')
if code is not N... |
class Solution:
def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool:
d = defaultdict(set)
for a in allowed:
d[a[:2]].add(a[2])
return self._dfs(bottom, d, 0, "")
def _dfs(self, bottom, d, p, nxt):
if len(bottom) == 1:
return True
... |
for i in range(10):
print(i)
print("YY")
|
'''
The MIT License (MIT)
Copyright (c) 2016 WavyCloud
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, p... |
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... |
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/86563872
# https://blog.csdn.net/danspace1/article/details/88737508
# IDEA :
# TOTAL MOVES = abs(coins left need) + abs(coins right need)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
... |
#
# PySNMP MIB module UX25-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/UX25-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:30:16 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:23:1... |
"""
Device Message Queue defined in Thorlabs Kinesis v1.14.10
The device message queue allows the internal events raised by the device to be
monitored by the DLLs owner.
The device raises many different events, usually associated with a change of state.
These messages are temporarily stored in the DLL and can be a... |
class Solution(object):
def powerOfTwoBitManipulation(self, n):
"""
Time - O(1)
Space - O(1)
:type n: integer
:rtype: integer
"""
if n < 1:
return False
while n % 2 == 0:
n >>= 1
return n == 1
def powerOfTwoBitManip... |
if __name__ == '__main__':
# with open("input/12.test") as f:
with open("input/12.txt") as f:
lines = f.read().split("\n")
pots = lines[0].split(":")[1].strip()
rules = dict()
for line in lines[2:]:
[k, v] = line.split("=>")
k = k.strip()
v = v.strip()
rule... |
expected_output = {
"ACL_TEST": {
"aces": {
"80": {
"actions": {"forwarding": "deny", "logging": "log-none"},
"matches": {
"l3": {
"ipv4": {
"source_network": {
... |
# %%
#######################################
def dict_creation_demo():
print(
"We can convert a list of tuples into Dictionary Items: dict( [('key1','val1'), ('key2', 'val2')] "
)
was_tuple = dict([("key1", "val1"), ("key2", "val2")])
print(f"This was a list of Tuples: {was_tuple}\n")
print(... |
# Faça um programa que leia 3 números e mostre qual é o maior e qual é o menor.
num1 = int(input('Digite o primeiro número: '))
num2 = int(input('Digite o segundo número: '))
num3 = int(input('Digite o terceiro número: '))
maior = num1
if num2 > num1 and num2 > num3:
maior = num2
elif num3 > num1 and num3 > num2:... |
def gcd(a,b):
assert a>= a and b >= 0 and a + b > 0
while a > 0 and b > 0:
if a >= b:
a = a % b
else:
b = b % a
return max(a,b)
def egcd(a, b):
x,y, u,v = 0,1, 1,0
while a != 0:
q, r = b//a, b%a
m, n = x-u*q, y-v*q
b,a, x,y, u,v ... |
asSignedInt = lambda s: -int(0x7fffffff&int(s)) if bool(0x80000000&int(s)) else int(0x7fffffff&int(s)) # TODO: swig'ged HIPS I/O unsigned int -> PyInt_AsLong vice PyLong_AsInt; OverflowError: long int too large to convert to int
ZERO_STATUS = 0x00000000
def SeparatePathFromPVDL(pathToPVDL,normalizeStrs=False):
# n... |
# coding=utf-8
"""
最小差
描述:给定两个整数数组(第一个是数组 A,第二个是数组 B),
在数组 A 中取 A[i],数组 B 中取 B[j],
A[i] 和 B[j]两者的差越小越好(|A[i] - B[j]|), 返回最小差。
思路: 合并为一个列表,然后前后比较取最小值
这样的有点在于,升序排列,两两比较 避开指针大和小的比较
"""
class Solution:
"""
@param A: An integer array
@param B: An integer array
@return: Their smallest difference.
"""... |
df12.interaction(['A','B'], pairwise=False, max_factors=3, min_occurrence=1)
# A_B
# -------
# foo_one
# bar_one
# foo_two
# other
# foo_two
# other
# foo_one
# other
#
# [8 rows x 1 column] |
# Created by Egor Kostan.
# GitHub: https://github.com/ikostan
# LinkedIn: https://www.linkedin.com/in/egor-kostan/
def encrypt_this(text: str) -> str:
"""
Encrypts each word in the message using the following rules:
* The first letter needs to be converted to its ASCII code.
* The second letter ... |
# Copyright 2021 The Cross-Media Measurement Authors
#
# 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 ... |
# import cv2
def text2binary(string):
"""
Converts text to binary string.
>>> text = 'Hello'
>>> binary_text = text2binary(text)
>>> print(binary_text)
'10010001100101110110011011001101111'
"""
# creates a list of binary representation of each character
# and joins the list to crea... |
def read(text_path):
texts = []
with open(text_path) as f:
for line in f.readlines():
texts.append(line.strip())
return texts
def corpus_perplexity(corpus_path, model):
texts = read(corpus_path)
N = sum(len(x.split()) for x in texts)
corpus_perp = 1
for text in texts:
... |
################################################
# result postprocessing utils
def divide_list_chunks(list, size_list):
assert(sum(size_list) >= len(list))
if sum(size_list) < len(list):
size_list.append(len(list) - sum(size_list))
for j in range(len(size_list)):
cur_id = sum(size_list[0:j... |
"""Constants for the Sure Petcare component."""
DOMAIN = "petcare"
DEFAULT_DEVICE_CLASS = "lock"
# sure petcare api
SURE_API_TIMEOUT = 60
# flap
BATTERY_ICON = "mdi:battery"
SURE_BATT_VOLTAGE_FULL = 1.6 # voltage
SURE_BATT_VOLTAGE_LOW = 1.25 # voltage
SURE_BATT_VOLTAGE_DIFF = SURE_BATT_VOLTAGE_FULL - SURE_BATT_VOL... |
class Board:
width = 3
height = 3
# Board Index
# 0 | 1 | 2
# 3 | 4 | 5
# 6 | 7 | 8
def __init__(self):
"""Instantiates a board object."""
# None is empty, 1 is player 1, 2 is player 2.
self._board = [None] * (self.width * self.height)
def _check_if_board_is_e... |
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
par = ter = maior = 0
for l in range(0, 3):
for c in range(0, 3):
matriz[l][c] = int(input(f'Digite o valor para [{l}, {c}]: '))
if c == 2:
ter += matriz[l][c]
if l == 1 and c == 0:
maior = matriz[l][c]
elif l == 1:
... |
class Hash:
def __init__(self):
self.m = 5 # cantidad de posiciones iniciales
self.min = 20 # porcentaje minimo a ocupar
self.max = 80 # porcentaje maximo a ocupar
self.n = 0
self.h = []
self.init()
def division(self, k):
return int(k % ... |
with open("English dictionary.txt", "r") as input_file, open("English dictionary.out", "w") as output_file:
row_id = 2
for line in input_file:
line = line.strip()
output_file.write("%d,%s\n" % (row_id, line.split(",")[1]))
row_id += 1
|
def test_cat1():
assert True
def test_cat2():
assert True
def test_cat3():
assert True
def test_cat4():
assert True
def test_cat5():
assert True
def test_cat6():
assert True
def test_cat7():
assert True
def test_cat8():
assert True
|
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
"""
This module provides implementation for GlobalRoutePlannerDAO
"""
class GlobalRoutePlannerDAO(object):
"""
This class is the data access layer for fetching data
from the carla server i... |
# print("Hello")
# print("Hello")
# print("Hello")
# i = 1 # so caller iterator, or index if you will
# while i < 5: # while loops are for indeterminate time
# print("Hello No.", i)
# print(f"Hello Number {i}")
# i += 1 # i = i + 1 # we will have a infinite loop without i += 1, there is no i++
#
# print... |
load("//ocaml:providers.bzl",
"OcamlNsResolverProvider",
"PpxNsArchiveProvider")
load(":options.bzl", "options", "options_ns_archive", "options_ns_opts")
load(":impl_ns_archive.bzl", "impl_ns_archive")
load("//ocaml/_transitions:ns_transitions.bzl", "nsarchive_in_transition")
OCAML_FILETYPES = [
".ml"... |
# coding=utf-8
class Card:
# card-colors
KARO = 0
HERZ = 1
PIK = 2
KREUZ = 3
# card-names
ZWEI = 2
DREI = 3
VIER = 4
FUENF = 5
SECHS = 6
SIEBEN = 7
ACHT = 8
NEUN = 9
ZEHN = 10
BUBE = 11
DAME = 12
KOENIG = 13
ASS = 14
def __init__(self, c... |
print(' ====== Exercício 13 ====== ')
# Solicitando ao usuário que insira o valor do salario que deve receber aumento.
salario = float(input('Qual é o salário do funcionário? R$'))
# Calculando o a soma do salario inserido com mais 15% de aumento.
novo = salario + (salario * 15/100)
# Exibindo o resultado ao usuário.
p... |
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/xtark/ros_ws/devel/include;/home/xtark/ros_ws/src/third_packages/ar_track_alvar/ar_track_alvar/include".split(';') if "/home/xtark/ros_ws/devel/include;/home/xtark/ros_ws/src/third_packages/ar_tr... |
def maxfun(l, *arr):
maxn = 0
maxsum = 0
for k, i in enumerate(arr):
s = 0
for t in l:
s += i(t)
if s >= maxsum:
maxn = k
maxsum = s
return arr[maxn]
|
class EngineParams(object):
def __init__(self, **kwargs):
# Iterates over provided arguments and sets the provided arguments as class properties
for key, value in kwargs.items():
setattr(self, key, value)
|
colours = {}
# Regular
colours["Black"]="\033[0;30m"
colours["Red"]="\033[0;31m"
colours["Green"]="\033[0;32m"
colours["Yellow"]="\033[0;33m"
colours["Blue"]="\033[0;34m"
colours["Purple"]="\033[0;35m"
colours["Cyan"]="\033[0;36m"
colours["White"]="\033[0;37m"
#Bold
colours["BBlack"]="\033[1;30m"
colours["BRed"]="\033[... |
class A(object):
x:int = 1
def foo():
print(1)
print(A)
print(foo()) #ok
print(foo) #error |
# The path to the Webdriver (for Chrome/Chromium)
CHROMEDRIVER_PATH = 'C:\\WebDriver\\bin\\chromedriver.exe'
# Tell the browser to ignore invalid/insecure https connections
BROWSER_INSECURE_CERTS = True
# The URL pointing to the Franka Control Webinterface (Desk)
DESK_URL = 'robot.franka.de'
# Expect a login page wh... |
def print_division(a,b):
try:
result = a / b
print(f"result: {result}")
except: # It catches ALL errors
print("error occurred")
print_division(10,5)
print_division(10,0)
print_division(10,2)
str_line = input("please enter two numbers to divide:")
a = int(str_line.split(" ")[0])
b = int(str_line.split(" "... |
class ConnectionError(Exception):
"""Failed to connect to the broker."""
pass
|
t = int(input())
while t:
arr = []
S = input().split()
if(len(S)==1):
print(S[0].capitalize())
else:
for i in range(len(S)):
arr.append(S[i].capitalize())
for i in range(len(S)-1):
print(arr[i][0]+'.',end=' ')
print(S[len(S)-1].capitalize())
... |
# -*- coding: utf-8 -*-
"""
uniq is a Python API client library for Cisco's Application Policy Infrastructure Controller
Enterprise Module (APIC-EM) Northbound APIs.
*** Description ***
The APIC-EM Northbound Interface is the only API that you will need to control your network
programmatically. The API is function r... |
class Image_SVG():
def Stmp(self):
return
|
def crack(value,g,mod):
for i in range(mod):
if ((g**i) % mod == value):
return i
# print("X = ", crack(57, 13, 59))
# print("Y = ", crack(44,13,59))
# print("Alice computes", (44**20)%59)
# print("Bob computes", (57**47)%59)
def find_num(target):
for i in range(target):
for j in range(target):
... |
#Função que recebe varios parâmetros e mostra qual o maior valor entre eles
def maior(*num):
if len(num) > 0:
maior = num[0]
print(f'Analisando os valores: ', end='')
for i in num:
print(f'{i}, ', end='')
if i >= maior:
maior = i
print(f'fora... |
__version__ = '1.0.3.5'
if __name__ == '__main__':
print(__version__)
# ******************************************************************************
# MIT License
#
# Copyright (c) 2020 Jianlin Shi
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated ... |
#tests if passed-in number is a prime number
def is_prime(num):
if num < 2:
return False
for i in range(2, num):
if num % i == 0:
return False
return True
#takes in a number and returns a list of prime numbers for zero to the number
def generate_prime_numbers(number):
primes = []
try:
isinstance(number,... |
# time O(nlogn)
# space O(1)
def minimumWaitingTime(queries):
queries.sort()
total = 0
prev_sum = 0
for i in queries[:-1]:
prev_sum += i
total += prev_sum
return total
# time O(nlogn)
# space O(1)
def minimumWaitingTime(queries):
queries.sort()
total = 0
f... |
for _ in range(int(input())):
n, m, k = map(int, input().split())
req = 0
req = 1*(m-1) + m*(n-1)
if req == k:
print("YES")
else:
print("NO") |
#/*********************************************************\
# * File: 44ScriptOOP.py *
# *
# * Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/)
# *
# * This file is part of PixelLight.
# *
# * Permission is hereby granted, free of charge, to any person obtain... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 23 14:39:19 2019
@author: aksha
"""
annual_salary = int(input('Enter your annual salary: '))
annual_salary1 = annual_salary
total_cost = 1000000
semi_annual_raise = 0.07
current_savings = 0.0
low = 0
high = 10000
guess = 5000
numberofsteps = 0
while abs(cur... |
orig = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
num = int(input())
for i in range(num):
alpha = list(orig)
key = input()
cipher = input()
tl = list(key)
letters = []
newAlpha = []
for l in tl:
if l not in letters:
letters.append(l)
alpha.remove(l)
length = len(letters... |
def get_inplane(inplanes, idx):
if isinstance(inplanes, list):
return inplanes[idx]
else:
return inplanes
|
def linearsearch(_list, _v):
if len(_list) == 0:
return False
for i, item in enumerate(_list):
if item == _v:
return i
return False
|
images = [
"https://demo.com/imgs/1.jpg",
"https://demo.com/imgs/2.jpg",
"https://demo.com/imgs/3.jpg",
]
|
"""Constants for the Livebox component."""
DOMAIN = "livebox"
COORDINATOR = "coordinator"
UNSUB_LISTENER = "unsubscribe_listener"
LIVEBOX_ID = "id"
LIVEBOX_API = "api"
COMPONENTS = ["sensor", "binary_sensor", "device_tracker", "switch"]
TEMPLATE_SENSOR = "Orange Livebox"
DEFAULT_USERNAME = "admin"
DEFAULT_HOST = "192... |
INITIAL_CAROUSEL_DATA = [
{
"title": "New Feature",
"description": "Explore",
"graphic": "/images/homepage/map-explorer.png",
"url": "/explore"
},
{
"title": "Data Visualization",
"description": "Yemen - WFP mVAM, Food Security Monitoring",
"graphic": ... |
"optimize with in-place list operations"
class error(Exception): pass # when imported: local exception
class Stack:
def __init__(self, start=[]): # self is the instance object
self.stack = [] # start is any sequence: stack...
for x in start: s... |
'''
A Simple nested if
'''
# Can you eat chicken?
a = input("Are you veg or non veg?\n")
day = input("Which day is today?\n")
if(a == "nonveg"):
if(day == "sunday"):
print("You can eat chicken")
else:
print("It is not sunday! You cannot eat chicken..")
else:
print("you are vegitarian! you cannot eat ch... |
__author__ = "Rob MacKinnon <rome@villagertech.com>"
__package__ = "DOMObjects"
__name__ = "DOMObjects.flags"
__license__ = "MIT"
DEBUG = 0
FLAG_READ = 2**0
FLAG_WRITE = 2**1
FLAG_NAMESPACE = 2**2
FLAG_RESERVED_8 = 2**3
FLAG_RESERVED_16 = 2**4
FLAG_RESERVED_32 = 2**5
FLAG_RESERVED_64 = 2**6
FLAG_RESERVED_128 = 2**7
... |
languages = {}
banned = []
results = {}
data = input().split("-")
while "exam finished" not in data:
if "banned" in data:
banned.append(data[0])
data = input().split("-")
continue
name = data[0]
language = data[1]
points = int(data[2])
current_points = 0
if language i... |
nome = str(input('Digite seu nome: ')).strip()
print('Olá {} vou te mostrar algumas informações sobre seu nome'.format(nome))
print('Tudo maiuscula:', nome.upper())
print('Tudo minuscula:', nome.lower())
print('Quantidade de letras:', len(nome) -nome.count(' '))
#print('Seu primeiro nome tem {} letras:'.format(nome.fin... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""test_pycmake
----------------------------------
Tests for `pycmake` module.
"""
|
"""
This package contains implementation of the individual components of
the topic coherence pipeline.
"""
|
# -*- coding: utf-8 -*-
{
'name': "se_openeducat_se_idr",
'summary': """
se_openeducat_se_idr
""",
'description': """
Openeducat SE IDR
""",
'author': "Alejandro",
'category': 'Uncategorized',
'version': '0.1',
'depends': ['base','openeducat_core','openeducat_... |
'''
Generic functions for files
'''
class FileOps:
def open(self, name):
'''
Open the file and return a string
'''
with open(name, 'rb') as f:
return f.read()
|
'''
Caesar Cypher, by Jackson Urquhart - 19 February 2022 @ 22:47
'''
in_str = str(input("\nEnter phrase: \n")) # Gets in_string from user
key = int(input("\nEnter key: \n")) # Gets key from user
keep_upper = str(input("\nMaintain case? y/n\n")) # Determines whether user wants to maintiain case values
def encrypt(in_... |
#
# PySNMP MIB module ETHER-WIS (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ETHER-WIS
# Produced by pysmi-0.3.4 at Wed May 1 13:06:45 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:23... |
print("hello world")
#prin("how are you")
def fa():
return fb()
def fb():
return fc()
def fc():
return 1
def suma(a, b):
return a + b
|
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 6 17:02:15 2019
@author: Administrator
"""
class Solution:
def setZeroes(self, matrix: list) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
d = {}
d['R'] = []
d['C'] = []
for r, val in... |
#
# PySNMP MIB module Nortel-Magellan-Passport-BaseRoutingMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-BaseRoutingMIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:16:59 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwan... |
def denumerate(enum_list):
try:
nums = dict(enum_list)
maximum = max(nums) + 1
result = ''.join(nums[a] for a in xrange(maximum))
if result.isalnum() and len(result) == maximum:
return result
except (KeyError, TypeError, ValueError):
pass
return False
|
lines = open('input.txt', 'r').readlines()
timestamp = int(lines[0].strip())
buses = lines[1].strip().split(',')
m, x = [], []
for i, bus in enumerate(buses):
if bus == 'x':
continue
bus = int(bus)
m.append(bus)
x.append((bus - i) % bus)
def extended_euclidean(a, b):
if a == 0:
return b, 0, 1
else:
g, y,... |
print('olá mário')
n1=int(input('digite um valor '))
n2=int(input('digite o segundo número '))
s=n1+n2
print('a soma entre {} e {:.2f} \n vale {}'.format(n1,n2,s),end=' >>> ')
# (end='')tambem continua a linha porém com espaço.
print('olá') |
"""Dependency specific initialization."""
def deps(repo_mapping = {}):
pass
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
def is_whitespaces_str(s):
return True if len(s.strip(" \t\n\r\f\v")) == 0 else False |
command = '/usr/bin/gunicorn'
pythonpath = '/usr/share/webapps/netbox'
bind = '127.0.0.1:8001'
workers = 3
user = 'netbox'
|
# Copyright (c) lobsterpy development team
# Distributed under the terms of a BSD 3-Clause "New" or "Revised" License
"""
This package provides the modules for analyzing Lobster files
"""
|
# This one's a bit different, representing an unusual (and honestly,
# not recommended) strategy for tracking users that sign up for a service.
class User:
# An (intentionally shared) collection storing users who sign up for some hypothetical service.
# There's only one set of members, so it lives at the class... |
def is_knight_removed(matrix: list, row: int, col: int):
if row not in range(rows) or col not in range(rows):
return False
return matrix[row][col] == "K"
def affected_knights(matrix: list, row: int, col: int):
result = 0
if is_knight_removed(matrix, row - 2, col + 1):
result += 1
i... |
# Fibonacci
"""
Using Recursion
"""
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(5))
"""
Using Dynamic Programming
"""
def fibonacci2(n):
# Taking 1st two fibonacci nubers as 0 and 1
FibArray = [0, 1]
while len(FibArray) < n + 1:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.