content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#this program demonstrates the addition of the two numbers
n1 = float (input ('enter the first number: '))
n2 = float (input ('enter the second number: '))
add = n1 +n2
print('the sum is: ',add)
| n1 = float(input('enter the first number: '))
n2 = float(input('enter the second number: '))
add = n1 + n2
print('the sum is: ', add) |
# Demo Python Dictionaries - Dictionary
'''
Removing Items
There are several methods to remove items from a dictionary.
'''
# The pop() method removes the item with the specified key name:
thisdict = {
"brand": "TOYOTA",
"model": "LAND CRUISER",
"year": 2020,
"color": "red"
}
print(thisdict)
thisdi... | """
Removing Items
There are several methods to remove items from a dictionary.
"""
thisdict = {'brand': 'TOYOTA', 'model': 'LAND CRUISER', 'year': 2020, 'color': 'red'}
print(thisdict)
thisdict.pop('model')
print(thisdict) |
#******************************#
# Project: Tuples practice
#
# Version: 1.0
# Author: Bruce Stull
# Date: December 22, 2021
#******************************#
# Do we need parentheses to wrap around the tuple? No error when compiled.
cat = 'fuzzy', 'furry', 'purry'
# Define tuple over multiple lines. '\'... | cat = ('fuzzy', 'furry', 'purry')
dog = ('bad', 'barky', 'bitey')
print(dog) |
class Example:
def __init__(self):
self.item1 = None
def item2(self):
return "instance variable item1 is %s" % (self.item1)
| class Example:
def __init__(self):
self.item1 = None
def item2(self):
return 'instance variable item1 is %s' % self.item1 |
count = 0
with open('data/Plagiarism.txt','r') as fin:
for line in fin:
count = count + int(line.split(';')[1])
print(count)
count2 = 0
with open('data/Plagiarism.txt','r') as fin, open('data/PlagiarismCumulative.txt','w+') as fout:
for line in fin:
count2 = count2 + int(line.split(';')[1])
... | count = 0
with open('data/Plagiarism.txt', 'r') as fin:
for line in fin:
count = count + int(line.split(';')[1])
print(count)
count2 = 0
with open('data/Plagiarism.txt', 'r') as fin, open('data/PlagiarismCumulative.txt', 'w+') as fout:
for line in fin:
count2 = count2 + int(line.split(';')[1])
... |
n = int(input())
for outer in range(1 , (n + 1)):
for inner in range(1, (n+1)):
if outer * inner == n:
print(str(outer)+" times "+str(inner)+" equals "+str(n))
| n = int(input())
for outer in range(1, n + 1):
for inner in range(1, n + 1):
if outer * inner == n:
print(str(outer) + ' times ' + str(inner) + ' equals ' + str(n)) |
#page starts with right side by 1
#backside page count
# https://www.hackerrank.com/challenges/drawing-book/problem?h_r=internal-search
n = 5
p = 4
#pages = [[i,i+1] for i in range(n+1)][::2] #experi
book = list(range(n+1))
book.append(0)
#print(book)
pages = []
elem = []
for i in range(n//2+1):
for j in rang... | n = 5
p = 4
book = list(range(n + 1))
book.append(0)
pages = []
elem = []
for i in range(n // 2 + 1):
for j in range(2):
elem.append(book.pop(0))
pages.append(elem)
elem = []
print(pages)
def st(b, p):
start = 0
for i in b:
if p in i:
return start
start += 1
def... |
class Status:
def __init__(self, level, name):
self.level = level
self.name = name
def __eq__(self, other):
return hasattr(other, "level") and self.level == other.level
def __ge__(self, other):
return self.level >= other.level
def __gt__(self, other):
return se... | class Status:
def __init__(self, level, name):
self.level = level
self.name = name
def __eq__(self, other):
return hasattr(other, 'level') and self.level == other.level
def __ge__(self, other):
return self.level >= other.level
def __gt__(self, other):
return s... |
def extractWwwPacificnovelsCom(item):
'''
Parser for 'www.pacificnovels.com'
'''
if any([tmp.lower().endswith(" (patreon)") for tmp in item['tags'] if tmp]):
return None
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
retu... | def extract_www_pacificnovels_com(item):
"""
Parser for 'www.pacificnovels.com'
"""
if any([tmp.lower().endswith(' (patreon)') for tmp in item['tags'] if tmp]):
return None
(vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(item['title'])
if not (chp or vol) or 'preview' in item[... |
# -*- coding: utf-8 -*-
# Author: Tom Bresee <tbresee@umich.edu>
#
# License: BSD 3 clause
__version__ = "1.1.dev1"
| __version__ = '1.1.dev1' |
simple = (5, 6)
two = ((5, 6), (6, 5))
three = (((5, 6), (5, 4)), ((6, 7), (6, 5)))
print(simple)
print(simple[0])
print()
print(two)
print(two[0])
print(two[0][0])
print()
print(three)
print(three[0])
print(three[0][0])
print(three[0][0][0]) | simple = (5, 6)
two = ((5, 6), (6, 5))
three = (((5, 6), (5, 4)), ((6, 7), (6, 5)))
print(simple)
print(simple[0])
print()
print(two)
print(two[0])
print(two[0][0])
print()
print(three)
print(three[0])
print(three[0][0])
print(three[0][0][0]) |
def foo():
'''
>>> def ok():
... pass
>>> def _ok():
... pass
>>> def ok_ok_ok_ok():
... pass
>>> def _somehow_good():
... pass
>>> def go_od_():
... pass
>>> def _go_od_():
... pass
>>> d... | def foo():
"""
>>> def ok():
... pass
>>> def _ok():
... pass
>>> def ok_ok_ok_ok():
... pass
>>> def _somehow_good():
... pass
>>> def go_od_():
... pass
>>> def _go_od_():
... pass
>>> d... |
class Patient:
def __init__(self, id, attr, value):
self.id = str(id)
self.attr = str(attr)
self.val = str(value)
class TemporalPatient:
def __init__(self, time_index, xvar):
self.time_index = time_index
self.xvar = xvar
# class TemporalPatient:
# def __init__(sel... | class Patient:
def __init__(self, id, attr, value):
self.id = str(id)
self.attr = str(attr)
self.val = str(value)
class Temporalpatient:
def __init__(self, time_index, xvar):
self.time_index = time_index
self.xvar = xvar
class Temporalpatientlist:
def __init__(se... |
class Solution:
def findDisappearedNumbers(self, nums: [int]) -> [int]:
arr = [0] * (len(nums) + 1)
for i in nums:
arr[i] = 1
result = []
for i in range(1, len(arr)):
if arr[i] == 0:
result.append(i)
return result
if __name__ == "__ma... | class Solution:
def find_disappeared_numbers(self, nums: [int]) -> [int]:
arr = [0] * (len(nums) + 1)
for i in nums:
arr[i] = 1
result = []
for i in range(1, len(arr)):
if arr[i] == 0:
result.append(i)
return result
if __name__ == '__m... |
class Solution:
def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
d1={}
ans=0
for i in range(len(A)):
for j in range(len(B)):
if -(A[i]+ B[j]) not in d1:
d1[-(A[i]+B[j])]=1
else:
... | class Solution:
def four_sum_count(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
d1 = {}
ans = 0
for i in range(len(A)):
for j in range(len(B)):
if -(A[i] + B[j]) not in d1:
d1[-(A[i] + B[j])] = 1
else:
... |
#!/usr/bin/env python3
#!/usr/local/bin/python3.7
#!/usr/bin/env python3
#!/usr/bin/python3
for i1 in range(256):
str2 = "%s %d 0x%x '%c'" % (str(i1), i1, i1, i1)
print(("str2 = %s" % str2))
#for i1 in range(32, 127):
# c1 = chr(i1)
# print "%d %s" % (i1, c1)
| for i1 in range(256):
str2 = "%s %d 0x%x '%c'" % (str(i1), i1, i1, i1)
print('str2 = %s' % str2) |
{
'variables': {
'platform': '<(OS)',
},
'conditions': [
# Replace gyp platform with node platform, blech
['platform == "mac"', {'variables': {'platform': 'darwin'}}],
['platform == "win"', {'variables': {'platform': 'win32'}}],
],
'targets': [
{
'target_name': 'glfw',
'defines... | {'variables': {'platform': '<(OS)'}, 'conditions': [['platform == "mac"', {'variables': {'platform': 'darwin'}}], ['platform == "win"', {'variables': {'platform': 'win32'}}]], 'targets': [{'target_name': 'glfw', 'defines': ['VERSION=0.3.1'], 'sources': ['src/atb.cc', 'src/glfw.cc'], 'include_dirs': ['<!(node -e "requir... |
count = 0
fhand = open(input('Enter the file name to look in: '))
for ln in fhand:
if ln.startswith('From '):
words = ln.split()
print(words[1])
count = count + 1
print('There were',count,'lines in the file with From as the first word')
| count = 0
fhand = open(input('Enter the file name to look in: '))
for ln in fhand:
if ln.startswith('From '):
words = ln.split()
print(words[1])
count = count + 1
print('There were', count, 'lines in the file with From as the first word') |
class Solution:
def minAvailableDuration(self, slots1: List[List[int]], slots2: List[List[int]], duration: int) -> List[int]:
i1 = 0; i2 = 0
L1 = len(slots1); L2 = len(slots2)
slots1.sort(); slots2.sort()
while i1 < L1 and i2 < L2:
slot1 = slots1[i1]; slot2 = slots2[i2]
... | class Solution:
def min_available_duration(self, slots1: List[List[int]], slots2: List[List[int]], duration: int) -> List[int]:
i1 = 0
i2 = 0
l1 = len(slots1)
l2 = len(slots2)
slots1.sort()
slots2.sort()
while i1 < L1 and i2 < L2:
slot1 = slots1[i... |
#Useful general functions
def default_scheduler(lr_scheduler):
return {'scheduler':lr_scheduler, 'monitor':'val_checkpoint_on'}
def default_scheduler2(lr_scheduler):
return {'scheduler':lr_scheduler, 'monitor':'asdfhakjsdhfjkahsdjfk'} | def default_scheduler(lr_scheduler):
return {'scheduler': lr_scheduler, 'monitor': 'val_checkpoint_on'}
def default_scheduler2(lr_scheduler):
return {'scheduler': lr_scheduler, 'monitor': 'asdfhakjsdhfjkahsdjfk'} |
class Property(object):
def __init__(self,
name,
type_,
access,
description,
gtype,
min_,
max_,
default
):
self.name = name
self.type = type_
self.access = access
self.description = description
self.gty... | class Property(object):
def __init__(self, name, type_, access, description, gtype, min_, max_, default):
self.name = name
self.type = type_
self.access = access
self.description = description
self.gtype = gtype
self.min = min_
self.max = max_
self.de... |
# Define critical settings and/or override defaults specified in
# settings.py. Copy this file to settings_local.py in the same
# directory as settings.py and edit. Any settings defined here
# will override those defined in settings.py
# Set this to point to your compiled checkout of caffe
caffevis_caffe_root =... | caffevis_caffe_root = '/path/to/caffe'
caffevis_deploy_prototxt = '%DVT_ROOT%/models/squeezenet/deploy.prototxt'
caffevis_network_weights = '%DVT_ROOT%/models/squeezenet/squeezenet_v1.0.caffemodel'
caffevis_data_mean = (104, 117, 123)
caffevis_labels = '%DVT_ROOT%/models/squeezenet/ilsvrc_2012_labels.txt'
caffevis_jpgv... |
class Expression:
def to_cypher(self, *args, **kwargs):
raise NotImplementedError()
def get_instances(self):
return []
| class Expression:
def to_cypher(self, *args, **kwargs):
raise not_implemented_error()
def get_instances(self):
return [] |
# Copyright 2015 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
inas = [(0x40, 'ina_v5a', 5.0, 0.002, 'rem', True),
(0x41, 'ina_v3p3a', 3.3, 0.002, 'rem', True),
(0x42, 'ina_vcc0_cpu', ... | inas = [(64, 'ina_v5a', 5.0, 0.002, 'rem', True), (65, 'ina_v3p3a', 3.3, 0.002, 'rem', True), (66, 'ina_vcc0_cpu', 7.5, 0.002, 'rem', True), (67, 'ina_vddq', 7.5, 0.002, 'rem', True), (68, 'ina_vbata', 7.5, 0.002, 'rem', True), (69, 'ina_vgg', 7.5, 0.002, 'rem', True), (70, 'ina_vnn', 7.5, 0.002, 'rem', True), (71, 'in... |
num = 10
num1 = 20
num2 = 30
num3 = 40
num4 = 50
num5 = 60
| num = 10
num1 = 20
num2 = 30
num3 = 40
num4 = 50
num5 = 60 |
class FunctionRegistry:
def __init__(self):
self.functions = {}
def __iter__(self):
return iter(self.functions.items())
def register(self, function):
name = function.__name__[9:]
self.functions[name] = function
return function
def __call__(self, function):
... | class Functionregistry:
def __init__(self):
self.functions = {}
def __iter__(self):
return iter(self.functions.items())
def register(self, function):
name = function.__name__[9:]
self.functions[name] = function
return function
def __call__(self, function):
... |
daily_goal = int(input())
result = 0
price = 0
command = input()
while command != 'closed' or result != daily_goal:
current_command = command
if current_command == 'haircut mens':
price = 15
result += price
elif current_command == 'haircut ladies':
price = 20
resul... | daily_goal = int(input())
result = 0
price = 0
command = input()
while command != 'closed' or result != daily_goal:
current_command = command
if current_command == 'haircut mens':
price = 15
result += price
elif current_command == 'haircut ladies':
price = 20
result += price
... |
season = str(input())
km_month = float(input())
summer = False
winter = False
spring_autumn = False
small = False
average = False
huge = False
if (season == "Spring") or (season == "Autumn"):
spring_autumn = True
if season == "Summer":
summer = True
if season == "Winter":
winter = True
if km_month <= 5000... | season = str(input())
km_month = float(input())
summer = False
winter = False
spring_autumn = False
small = False
average = False
huge = False
if season == 'Spring' or season == 'Autumn':
spring_autumn = True
if season == 'Summer':
summer = True
if season == 'Winter':
winter = True
if km_month <= 5000:
... |
def foo():
print("foo line 1")
print("foo line 2")
print("foo line 3")
def fum():
print("fum line 1")
print("fum line 2")
print("fum line 3")
def bar():
print("bar line 1")
fum()
foo()
print("bar line 4")
def go():
bar()
go() | def foo():
print('foo line 1')
print('foo line 2')
print('foo line 3')
def fum():
print('fum line 1')
print('fum line 2')
print('fum line 3')
def bar():
print('bar line 1')
fum()
foo()
print('bar line 4')
def go():
bar()
go() |
file = open("energiaConsumoDataCenter.csv", "r")
total = 0
for linea in file:
data = linea.strip().split(";")
total += float(data[1])
print(total) | file = open('energiaConsumoDataCenter.csv', 'r')
total = 0
for linea in file:
data = linea.strip().split(';')
total += float(data[1])
print(total) |
# Program : Check whether the number is palindrome or not.
# Input : number = 565
# Output : True
# Explanation : 565 and its reverse are the same, so 565 is a palindrome.
# Language : Python3
# O(n) time | O(1) space
def palindrome_or_not(number):
# Copy the number into a temporary variable.
temp = number
... | def palindrome_or_not(number):
temp = number
reverse = 0
while number > 0:
last_digit = number % 10
reverse = reverse * 10 + last_digit
number = number // 10
if reverse == temp:
return True
else:
return False
if __name__ == '__main__':
number = 565
ans... |
class Solution:
# @param m, an integer
# @param n, an integer
# @return an integer
def rangeBitwiseAnd(self, m, n):
cnt = 0
while m != n:
m >>= 1
n >>= 1
cnt += 1
return m << cnt
| class Solution:
def range_bitwise_and(self, m, n):
cnt = 0
while m != n:
m >>= 1
n >>= 1
cnt += 1
return m << cnt |
class MinHeap:
def __init__(self):
self.data = [None]
def swap(self,a,b):
self.data[a], self.data[b] = self.data[b], self.data[a]
def insert(self,value):
self.data.append(value)
idx = len(self.data)-1
while idx > 1 and self.data[idx] < self.data[idx//2]:
s... | class Minheap:
def __init__(self):
self.data = [None]
def swap(self, a, b):
(self.data[a], self.data[b]) = (self.data[b], self.data[a])
def insert(self, value):
self.data.append(value)
idx = len(self.data) - 1
while idx > 1 and self.data[idx] < self.data[idx // 2]:... |
# 1.2 Palindrome Tester
def is_palindrome(input_string):
if not input_string:
return True
a_list = []
reversed_string = ''
for c in input_string:
a_list.append(c)
while a_list:
reversed_string += str(a_list.pop())
result = input_string == reversed_string
return ... | def is_palindrome(input_string):
if not input_string:
return True
a_list = []
reversed_string = ''
for c in input_string:
a_list.append(c)
while a_list:
reversed_string += str(a_list.pop())
result = input_string == reversed_string
return result |
# Copyright (c) 2012-2018 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the COPYING file.
project = u'qiBuild'
version = '3.11.18'
release = version
sys.path.insert(0, os.path.abspath('../tools'))
# for autodoc
sys.path.insert(0, os.path.abs... | project = u'qiBuild'
version = '3.11.18'
release = version
sys.path.insert(0, os.path.abspath('../tools'))
sys.path.insert(0, os.path.abspath('../../python'))
extensions.append('cmakedomain')
extensions.append('sphinx.ext.autodoc')
extensions.append('sphinxcontrib.spelling')
templates_path = ['../source/_templates']
ht... |
# Author: btjanaka (Bryon Tjanaka)
# Problem: (Kattis) arithmetic
# Title: Arithmetic
# Link: https://open.kattis.com/problems/arithmetic
# Idea: Convert base 8 to base 16.
# Difficulty: easy
# Tags: math, implementation
print(hex(int(input().strip(), base=8))[2:].upper())
| print(hex(int(input().strip(), base=8))[2:].upper()) |
class queue:
def __init__(self):
self.queue = []
def enqueue(self, obj):
self.queue.append(obj)
def dequeue(self):
if len(self.queue) > 0:
return self.queue.pop(0)
return None
def rear(self):
return self.queue[-1]
def front(self):
if le... | class Queue:
def __init__(self):
self.queue = []
def enqueue(self, obj):
self.queue.append(obj)
def dequeue(self):
if len(self.queue) > 0:
return self.queue.pop(0)
return None
def rear(self):
return self.queue[-1]
def front(self):
if l... |
#
# PySNMP MIB module A3COM-SWITCHING-SYSTEMS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-SWITCHING-SYSTEMS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:53:36 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_union, single_value_constraint, constraints_intersection, value_range_constraint) ... |
lists = ['1', '2', '3']
print(lists[3])
| lists = ['1', '2', '3']
print(lists[3]) |
class LogicGate:
def __init__(self,n):
self.label = n
self.output = None
def getLabel(self):
return self.label
def getOutput(self):
self.output = self.performGateLogic()
return self.output
| class Logicgate:
def __init__(self, n):
self.label = n
self.output = None
def get_label(self):
return self.label
def get_output(self):
self.output = self.performGateLogic()
return self.output |
#--------------------------------------------------------------
# By Miles R. Porter
# Painted Harmony Group, Inc
# June 13, 2017
# Please See LICENSE.txt
#--------------------------------------------------------------
class LineParser():
def __init__(self, Name, SearchCode, Start_Field, End_Field, Scale, Off... | class Lineparser:
def __init__(self, Name, SearchCode, Start_Field, End_Field, Scale, Offset):
self.name = Name
self.searchCode = SearchCode
self.start_field = Start_Field
self.end_field = End_Field
self.scale = Scale
self.offset = Offset
def parse(self, data):
... |
class DataStore:
store = {}
@classmethod
def add_item(cls, key, value):
cls.store[key] = value
@classmethod
def remove_item(cls, key):
del cls.store[key]
@classmethod
def reset(cls):
cls.store = {} | class Datastore:
store = {}
@classmethod
def add_item(cls, key, value):
cls.store[key] = value
@classmethod
def remove_item(cls, key):
del cls.store[key]
@classmethod
def reset(cls):
cls.store = {} |
#!/usr/bin/python3
def IsPrime(n):
for x in range(2, n // 2 + 1):
if not n % x:
return False
return True
def PrimesTo(n):
for x in range(2, n):
if IsPrime(x):
print(x)
PrimesTo(50)
| def is_prime(n):
for x in range(2, n // 2 + 1):
if not n % x:
return False
return True
def primes_to(n):
for x in range(2, n):
if is_prime(x):
print(x)
primes_to(50) |
with open("inp23.txt") as file:
data = file.read()
instructions = []
for line in data.splitlines():
if "jio" in line or "jie" in line:
rest, offset = line.split(", ")
cmd, reg = rest.split(" ")
instructions.append((cmd, reg, offset))
else:
cmd, x = line.split(" ")
... | with open('inp23.txt') as file:
data = file.read()
instructions = []
for line in data.splitlines():
if 'jio' in line or 'jie' in line:
(rest, offset) = line.split(', ')
(cmd, reg) = rest.split(' ')
instructions.append((cmd, reg, offset))
else:
(cmd, x) = line.split(' ')
... |
class FinishPipe:
def __init__(self, f):
self.f = f
def next(self, window, values, num, done):
apply(self.f, values)
| class Finishpipe:
def __init__(self, f):
self.f = f
def next(self, window, values, num, done):
apply(self.f, values) |
class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
fS = []
for index,char in enumerate(S):
if char == '#':
if fS:fS.pop()
else:
fS.append(char)
fT = []
for index,char in enumerate(T):
if char == '#' ... | class Solution:
def backspace_compare(self, S: str, T: str) -> bool:
f_s = []
for (index, char) in enumerate(S):
if char == '#':
if fS:
fS.pop()
else:
fS.append(char)
f_t = []
for (index, char) in enumerate(... |
def count_documents(cursor, spec=None):
return cursor.collection.count_documents(spec or {})
def test_qop_and_1(monty_find, mongo_find):
docs = [
{"a": 8, "b": 4}
]
spec = {"$and": [{"a": {"$gt": 6}}, {"b": {"$lt": 5}}]}
monty_c = monty_find(docs, spec)
mongo_c = mongo_find(docs, sp... | def count_documents(cursor, spec=None):
return cursor.collection.count_documents(spec or {})
def test_qop_and_1(monty_find, mongo_find):
docs = [{'a': 8, 'b': 4}]
spec = {'$and': [{'a': {'$gt': 6}}, {'b': {'$lt': 5}}]}
monty_c = monty_find(docs, spec)
mongo_c = mongo_find(docs, spec)
assert cou... |
#!/usr/bin/env python
a = 'www.baidu.com'
print(a.split('.'))
b = '{} is my love'.format('Python')
print(b)
list = ['peter', 'lilei', 'wangwu', 'xiaoming']
print(list[2:])
| a = 'www.baidu.com'
print(a.split('.'))
b = '{} is my love'.format('Python')
print(b)
list = ['peter', 'lilei', 'wangwu', 'xiaoming']
print(list[2:]) |
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
prev = float('-inf')
for i in range(len(nums)):
if nums[i] > prev:
if i == len(nums)-1:
return i
elif nums[i]>nums[i + 1]:
return i
... | class Solution:
def find_peak_element(self, nums: List[int]) -> int:
prev = float('-inf')
for i in range(len(nums)):
if nums[i] > prev:
if i == len(nums) - 1:
return i
elif nums[i] > nums[i + 1]:
return i
... |
class Employee:
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname
# self.email = f"{fname}.{lname}@sandy.com"
def explain(self):
return f"This employee is {self.fname} {self.lname}"
@property
def email(self):
if self.fname == None or self.ln... | class Employee:
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname
def explain(self):
return f'This employee is {self.fname} {self.lname}'
@property
def email(self):
if self.fname == None or self.lname == None:
return 'Emain is not set'... |
print('===== DESAFIO 009 =====')
n = int(input('digite um valor: '))
print('===== SUA TABUADA ======')
print('+')
print(f'{n} + 1 = {n+1}')
print(f'{n} + 2 = {n+2}')
print(f'{n} + 3 = {n+3}')
print(f'{n} + 4 = {n+4}')
print(f'{n} + 5 = {n+5}')
print(f'{n} + 6 = {n+6}')
print(f'{n} + 7 = {n+7}')
print(f'{n} + 8 = {n+8}'... | print('===== DESAFIO 009 =====')
n = int(input('digite um valor: '))
print('===== SUA TABUADA ======')
print('+')
print(f'{n} + 1 = {n + 1}')
print(f'{n} + 2 = {n + 2}')
print(f'{n} + 3 = {n + 3}')
print(f'{n} + 4 = {n + 4}')
print(f'{n} + 5 = {n + 5}')
print(f'{n} + 6 = {n + 6}')
print(f'{n} + 7 = {n + 7}')
print(f'{n... |
A = int(input())
B = int(input())
C = int(input())
num = A*B*C
for i in range(0, 10):
print(str(num).count(str(i))) | a = int(input())
b = int(input())
c = int(input())
num = A * B * C
for i in range(0, 10):
print(str(num).count(str(i))) |
UPPER_TOR = "upper_tor"
LOWER_TOR = "lower_tor"
TOGGLE = "toggle"
RANDOM = "random"
NIC = "nic"
DROP = "drop"
OUTPUT = "output"
FLAP_COUNTER = "flap_counter"
CLEAR_FLAP_COUNTER = "clear_flap_counter"
MUX_SIM_ALLOWED_DISRUPTION_SEC = 5
CONFIG_RELOAD_ALLOWED_DISRUPTION_SEC = 120
PHYSICAL_CABLE_ALLOWED_DISRUPTION_SEC ... | upper_tor = 'upper_tor'
lower_tor = 'lower_tor'
toggle = 'toggle'
random = 'random'
nic = 'nic'
drop = 'drop'
output = 'output'
flap_counter = 'flap_counter'
clear_flap_counter = 'clear_flap_counter'
mux_sim_allowed_disruption_sec = 5
config_reload_allowed_disruption_sec = 120
physical_cable_allowed_disruption_sec = 1 |
# -------------------------------------------------------------------------------
# Copyright IBM Corp. 2018
#
# 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/licens... | class Basedatahandler(object):
def __init__(self, options, entity):
self.options = options
self.entity = entity
self.isStreaming = False
def add_numerical_column(self):
raise not_implemented_error()
def count(self):
raise not_implemented_error()
def get_field_... |
#
# PySNMP MIB module ALCATEL-IND1-PORT-MAPPING (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALCATEL-IND1-PORT-MAPPING
# Produced by pysmi-0.3.4 at Wed May 1 11:18:59 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.... | (softent_ind1_port_mapping,) = mibBuilder.importSymbols('ALCATEL-IND1-BASE', 'softentIND1PortMapping')
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_con... |
def isMonotonic(array):
is_increasing = True
is_decreasing = True
for i in range(1, len(array)):
if array[i] < array[i - 1]:
is_increasing = False
elif array[i] > array[i - 1]:
is_decreasing = False
return is_increasing or is_decreasing
| def is_monotonic(array):
is_increasing = True
is_decreasing = True
for i in range(1, len(array)):
if array[i] < array[i - 1]:
is_increasing = False
elif array[i] > array[i - 1]:
is_decreasing = False
return is_increasing or is_decreasing |
DEFAULT_CONNECTION = 'default'
DEFAULT_SERVER = 'default'
# Examples helper descriptions
GENERATE_DATA_DESC = "generates data for running IBM FL examples"
NUM_PARTIES_DESC = "the number of parties to split the data into"
DATASET_DESC = "which data set to use"
PATH_DESC = "directory to save the data"
PER_PARTY = "the n... | default_connection = 'default'
default_server = 'default'
generate_data_desc = 'generates data for running IBM FL examples'
num_parties_desc = 'the number of parties to split the data into'
dataset_desc = 'which data set to use'
path_desc = 'directory to save the data'
per_party = 'the number of data points per party'
... |
expected_output = {
"nodes": {
1: {
"ospf_router_id": "10.19.198.239",
"area_id": 8,
"domain_id": 0,
"asn": 65109,
"prefix_sid": {
"prefix": "10.19.198.239",
"label": 16073,
"label_type": "regular",
... | expected_output = {'nodes': {1: {'ospf_router_id': '10.19.198.239', 'area_id': 8, 'domain_id': 0, 'asn': 65109, 'prefix_sid': {'prefix': '10.19.198.239', 'label': 16073, 'label_type': 'regular', 'domain_id': 0, 'flags': 'N , E'}, 'links': {0: {'local_address': '10.19.198.26', 'remote_address': '10.19.198.25', 'local_no... |
matrix = [['X00','X01','X02'],['X10','X11','X12'],['X20','X21','X22']]
agg = []
for j in range(0, len(matrix)):
mat = []
for i in matrix:
mat = mat + [i[j]]
agg.append(mat)
print (matrix)
print(agg) | matrix = [['X00', 'X01', 'X02'], ['X10', 'X11', 'X12'], ['X20', 'X21', 'X22']]
agg = []
for j in range(0, len(matrix)):
mat = []
for i in matrix:
mat = mat + [i[j]]
agg.append(mat)
print(matrix)
print(agg) |
class Foo(int, x=42):
pass
# EXPECTED:
[
...,
LOAD_NAME('int'),
LOAD_CONST(42),
LOAD_CONST(('x',)),
CALL_FUNCTION_KW(4),
...
]
| class Foo(int, x=42):
pass
[..., load_name('int'), load_const(42), load_const(('x',)), call_function_kw(4), ...] |
extensions = ['sphinx.ext.doctest']
project = 'test project for doctest'
master_doc = 'doctest.txt'
source_suffix = '.txt'
| extensions = ['sphinx.ext.doctest']
project = 'test project for doctest'
master_doc = 'doctest.txt'
source_suffix = '.txt' |
#!/bin/python3
# Task
# Write a Person class with an instance variable, , and a constructor that takes an integer, , as a parameter. The constructor must assign to after confirming the argument passed as is not negative; if a negative argument is passed as , the constructor should set to and print Age is not valid... | class Person:
def __init__(self, initialAge):
if initialAge < 0:
print('Age is not valid, setting age to 0.')
self.age = 0
else:
self.age = initialAge
def am_i_old(self):
if self.age < 0:
print('Age is not valid, setting age to 0.')
... |
time = ['flamengo','atletico','cruzeiro','botafogo']
time[0],time[-1] = time[-1],time[0]
print(time) | time = ['flamengo', 'atletico', 'cruzeiro', 'botafogo']
(time[0], time[-1]) = (time[-1], time[0])
print(time) |
class Config:
NEO4J_DATA = {
'uri': 'bolt://localhost:7687',
'login': 'neo4j',
'password': 'kinix951'
}
| class Config:
neo4_j_data = {'uri': 'bolt://localhost:7687', 'login': 'neo4j', 'password': 'kinix951'} |
iris={'setosa\n': 0, 'versicolor\n': 1, 'virginica\n': 2}
def deal(infilename,outfilename):
infile = open(infilename)
lines = infile.readlines()
out = []
for line in lines:
line = line.split(' ')
val = line[-1]
line = line[:-1]
val = iris[val]
line.insert(0,val)
... | iris = {'setosa\n': 0, 'versicolor\n': 1, 'virginica\n': 2}
def deal(infilename, outfilename):
infile = open(infilename)
lines = infile.readlines()
out = []
for line in lines:
line = line.split(' ')
val = line[-1]
line = line[:-1]
val = iris[val]
line.insert(0, v... |
def dowrong():
return 1/0
def main():
try:
dowrong()
except:
print("oops")
finally:
print("program finished")
if __name__ == "__main__":
main() | def dowrong():
return 1 / 0
def main():
try:
dowrong()
except:
print('oops')
finally:
print('program finished')
if __name__ == '__main__':
main() |
#Input two numbers and display the larger / smaller number.
def min_max():
a=int(input('enter first number: '))
b=int(input('enter second number: '))
if a>b:
print('larger number is: ',a)
print('smaller number is: ',b)
else:
print('larger number is: ',b)
pr... | def min_max():
a = int(input('enter first number: '))
b = int(input('enter second number: '))
if a > b:
print('larger number is: ', a)
print('smaller number is: ', b)
else:
print('larger number is: ', b)
print('smaller number is: ', a)
min_max() |
#the program tests whether a given word is a palindrome.
def isPalidrome(string):
left_pos = 0
right_pos =len(string) - 1
while right_pos >= left_pos:
if not string[left_pos] == string[right_pos]:
return False
left_pos += 1
right_pos -=1
return True
name = st... | def is_palidrome(string):
left_pos = 0
right_pos = len(string) - 1
while right_pos >= left_pos:
if not string[left_pos] == string[right_pos]:
return False
left_pos += 1
right_pos -= 1
return True
name = str(input('Enter a name: '))
print(is_palidrome(name)) |
PASSWORD = "UtOF3tbWJaHSCImY"
def check(selenium_obj, host):
current_host = f"http://gallery.{host}/"
selenium_obj.get(current_host)
selenium_obj.add_cookie({'name': 'token', 'value': PASSWORD, 'path': '/'})
| password = 'UtOF3tbWJaHSCImY'
def check(selenium_obj, host):
current_host = f'http://gallery.{host}/'
selenium_obj.get(current_host)
selenium_obj.add_cookie({'name': 'token', 'value': PASSWORD, 'path': '/'}) |
materials = pd.read_excel('/Users/michael/projects/materials/data/materials.xlsx')
bom = pd.read_csv('/Users/michael/Desktop/tangers/bom.txt')
bom = bom.drop('UM_Multiplier', axis=1)
bom = bom.groupby('Part Number', as_index=False).sum()
materials = materials.merge(bom, how='right').fillna(0)
dates = list(materials.col... | materials = pd.read_excel('/Users/michael/projects/materials/data/materials.xlsx')
bom = pd.read_csv('/Users/michael/Desktop/tangers/bom.txt')
bom = bom.drop('UM_Multiplier', axis=1)
bom = bom.groupby('Part Number', as_index=False).sum()
materials = materials.merge(bom, how='right').fillna(0)
dates = list(materials.col... |
admin = True
username = 'test'
# ldap_host = 'dc.main.local'
# ldap_user = 'CN=phonebook_user,CN=Users,DC=main,DC=local'
# ldap_password = ''
# ldap_base = 'CN=Users,DC=main,DC=local'
conf_domain = 'MAIN'
font = 'HelvRu'
copyright = 'Phonebook Company Ltd.'
org_vcard = 'Phonebook Company'
# use lowercase for login!
ad... | admin = True
username = 'test'
conf_domain = 'MAIN'
font = 'HelvRu'
copyright = 'Phonebook Company Ltd.'
org_vcard = 'Phonebook Company'
admin_users = ['administrator']
secret_key = 'testtesttest'
header_content = 'Phonebook Company Ltd.'
header_content1 = 'Switzerland | E-mail: test@test.ch' |
def stage(ctx):
return {
"parent": "root",
"triggers": {
"repo": {
"url": "https://github.com/gohugoio/hugo.git",
"branch": "master",
"interval": "3d"
}
},
"parameters": [],
"configs": [],
"jobs":... | def stage(ctx):
return {'parent': 'root', 'triggers': {'repo': {'url': 'https://github.com/gohugoio/hugo.git', 'branch': 'master', 'interval': '3d'}}, 'parameters': [], 'configs': [], 'jobs': [{'name': 'do all', 'timeout': 2500, 'steps': [{'tool': 'git', 'checkout': 'https://github.com/gohugoio/hugo.git'}, {'tool':... |
# Generated by h2py from lmaccess.h
# Included from lmcons.h
CNLEN = 15
LM20_CNLEN = 15
DNLEN = CNLEN
LM20_DNLEN = LM20_CNLEN
UNCLEN = CNLEN + 2
LM20_UNCLEN = LM20_CNLEN + 2
NNLEN = 80
LM20_NNLEN = 12
RMLEN = UNCLEN + 1 + NNLEN
LM20_RMLEN = LM20_UNCLEN + 1 + LM20_NNLEN
SNLEN = 80
LM20_SNLEN = 15
STXTLEN = 256
LM20_STX... | cnlen = 15
lm20_cnlen = 15
dnlen = CNLEN
lm20_dnlen = LM20_CNLEN
unclen = CNLEN + 2
lm20_unclen = LM20_CNLEN + 2
nnlen = 80
lm20_nnlen = 12
rmlen = UNCLEN + 1 + NNLEN
lm20_rmlen = LM20_UNCLEN + 1 + LM20_NNLEN
snlen = 80
lm20_snlen = 15
stxtlen = 256
lm20_stxtlen = 63
pathlen = 256
lm20_pathlen = 256
devlen = 80
lm20_de... |
#!/usr/bin/env prey
async def main():
await x(
[
# be sure to reset styles or everything after it will still be styled
f"echo {colorama.Fore.RED} this is red{colorama.Style.RESET_ALL}",
f"echo this is normal",
f'echo {colorama.Back.LIGHTBLACK_EX}{colorama.Fo... | async def main():
await x([f'echo {colorama.Fore.RED} this is red{colorama.Style.RESET_ALL}', f'echo this is normal', f'echo {colorama.Back.LIGHTBLACK_EX}{colorama.Fore.YELLOW}this has a "light black" background and yellow text{colorama.Style.RESET_ALL}']) |
#new code, the if statement was missing another '='
#by adding "==" we are checking if the result is equal to 0
#if we used "=" we are saying that its 0!
number = int(input("Which number do you want to check? "))
if number % 2 == 0:
print("This is an even number.")
else:
print("This is an odd number.")
#old code,... | number = int(input('Which number do you want to check? '))
if number % 2 == 0:
print('This is an even number.')
else:
print('This is an odd number.') |
class HorizontalSegment:
def __init__(self, x1, x2, y):
self.left = x1
self.right = x2
self.y = y
class VerticalSegment:
def __init__(self, y1, y2, x):
self.top = y1
self.bottom = y2
self.x = x
def findMaxRowAndCol(set):
maxRow = float("-inf")
maxCol =... | class Horizontalsegment:
def __init__(self, x1, x2, y):
self.left = x1
self.right = x2
self.y = y
class Verticalsegment:
def __init__(self, y1, y2, x):
self.top = y1
self.bottom = y2
self.x = x
def find_max_row_and_col(set):
max_row = float('-inf')
max... |
TIMEOUT = 10
TEAMCITY_API = "app/rest"
TEAMCITY_API_VERSION = "latest"
TEAMCITY_BASIC_AUTH = "httpAuth"
TEAMCITY_GUEST_AUTH = "guestAuth"
TEAMCITY_SERVER_INFO_API = "server"
TEAMCITY_PLUGINS_API = "{0}/plugins".format(TEAMCITY_SERVER_INFO_API)
| timeout = 10
teamcity_api = 'app/rest'
teamcity_api_version = 'latest'
teamcity_basic_auth = 'httpAuth'
teamcity_guest_auth = 'guestAuth'
teamcity_server_info_api = 'server'
teamcity_plugins_api = '{0}/plugins'.format(TEAMCITY_SERVER_INFO_API) |
###########################
# Project Euler Problem 17
# Number letter counts
#
# Code by Kevin Marciniak
###########################
def num_to_word(num):
if len(num) == 3:
if num[1] == "0" and num[2] == "0":
return num_to_word(num[0]) + "hundred"
else:
return num_to_word(num[0]) + "hundredand" + num_to_w... | def num_to_word(num):
if len(num) == 3:
if num[1] == '0' and num[2] == '0':
return num_to_word(num[0]) + 'hundred'
else:
return num_to_word(num[0]) + 'hundredand' + num_to_word(num[1:])
if len(num) == 2:
if num[0] == '9':
return 'ninety' + num_to_word(... |
palavras = ('APRENDER','PROGRAMAR','LINGUAGEM','PYTHON','CURSO',
'GRATIS','ESTUDAR','PRATICAR','TRABALHAR','MERCADO',
'PROGRAMADOR','FUTURO','NOTEBOOK','MOUSE','TOUCH')
for pos in palavras:
print (f'\nNa palavra {pos} temos ', end='')
for letra in pos:
if letra in 'AEIOU':
... | palavras = ('APRENDER', 'PROGRAMAR', 'LINGUAGEM', 'PYTHON', 'CURSO', 'GRATIS', 'ESTUDAR', 'PRATICAR', 'TRABALHAR', 'MERCADO', 'PROGRAMADOR', 'FUTURO', 'NOTEBOOK', 'MOUSE', 'TOUCH')
for pos in palavras:
print(f'\nNa palavra {pos} temos ', end='')
for letra in pos:
if letra in 'AEIOU':
print(f... |
soma = cont = 0
while True:
n = int(input('Digire um valor. (para sair digite 999)'))
if n == 999:
break;
else:
soma += n
cont += 1
print(f'a soma dos {cont} numeros foi {soma}') | soma = cont = 0
while True:
n = int(input('Digire um valor. (para sair digite 999)'))
if n == 999:
break
else:
soma += n
cont += 1
print(f'a soma dos {cont} numeros foi {soma}') |
parser = mlprogram.datasets.django.Parser(
split_value=mlprogram.datasets.django.SplitValue(),
)
extract_reference = mlprogram.datasets.django.TokenizeQuery()
is_subtype = mlprogram.languages.python.IsSubtype()
dataset = mlprogram.datasets.django.download()
metrics = {
"accuracy": mlprogram.metrics.use_environm... | parser = mlprogram.datasets.django.Parser(split_value=mlprogram.datasets.django.SplitValue())
extract_reference = mlprogram.datasets.django.TokenizeQuery()
is_subtype = mlprogram.languages.python.IsSubtype()
dataset = mlprogram.datasets.django.download()
metrics = {'accuracy': mlprogram.metrics.use_environment(metric=m... |
PARAMETER_TYPES = [(1, 'query'), (2, 'user')]
TRANSFORMATION_TYPES = [(1, 'Transpose'), (2, 'Split'), (3, 'Merge')]
COLUMN_TYPES = [(1, 'dimension'), (2, 'metric')]
SQL_WRITE_BLACKLIST = [
# Data Definition
'CREATE', 'ALTER', 'RENAME', 'DROP', 'TRUNCATE',
# Data Manipulation
'INSERT', 'UPDATE', 'REPLACE... | parameter_types = [(1, 'query'), (2, 'user')]
transformation_types = [(1, 'Transpose'), (2, 'Split'), (3, 'Merge')]
column_types = [(1, 'dimension'), (2, 'metric')]
sql_write_blacklist = ['CREATE', 'ALTER', 'RENAME', 'DROP', 'TRUNCATE', 'INSERT', 'UPDATE', 'REPLACE', 'DELETE']
swagger_json_template = {'swagger': '2.0',... |
#ACL
def is_prime(n):
assert(0<=n<=4294967296)
if n in [2,7,61]:
return True
if n<=1 or n%2==0:
return False
d=n-1
while d%2==0:
d//=2
for a in [2,7,61]:
t=d
y=pow(a,t,n)
while t!=n-1 and y not in [1,n-1]:
y=y*y%n
t<<=1
if y!=n-1 and t%2==0:
return False
retur... | def is_prime(n):
assert 0 <= n <= 4294967296
if n in [2, 7, 61]:
return True
if n <= 1 or n % 2 == 0:
return False
d = n - 1
while d % 2 == 0:
d //= 2
for a in [2, 7, 61]:
t = d
y = pow(a, t, n)
while t != n - 1 and y not in [1, n - 1]:
... |
def takeData(data):
dataProvided = data["code"]
return dataProvided | def take_data(data):
data_provided = data['code']
return dataProvided |
# If modifying these scopes, delete the file token.json.
SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'
CSV_MIME_TYPE = 'text/csv'
XLSX_MIME_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
| scopes = 'https://www.googleapis.com/auth/gmail.readonly'
csv_mime_type = 'text/csv'
xlsx_mime_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' |
model = dict(
type='Recognizer3D',
backbone=dict(
type='ResNet3d',
pretrained2d=True,
pretrained='torchvision://resnet50',
depth=50,
conv1_kernel=(5, 7, 7),
conv1_stride_t=2,
pool1_stride_t=2,
conv_cfg=dict(type='Conv3d'),
norm_eval=False,
... | model = dict(type='Recognizer3D', backbone=dict(type='ResNet3d', pretrained2d=True, pretrained='torchvision://resnet50', depth=50, conv1_kernel=(5, 7, 7), conv1_stride_t=2, pool1_stride_t=2, conv_cfg=dict(type='Conv3d'), norm_eval=False, inflate=((1, 1, 1), (1, 0, 1, 0), (1, 0, 1, 0, 1, 0), (0, 1, 0)), zero_init_residu... |
def calcular_precio_producto(coste_producto):
'''
(float)-> float
#casos de prueba
>>> calcular_precio_producto(200)
300.0
>>> calcular_precio_producto(300)
450.0
>>> calcular_precio_producto(600)
900.0
:param coste_producto:
:return:
'''
# procesos //
cos... | def calcular_precio_producto(coste_producto):
"""
(float)-> float
#casos de prueba
>>> calcular_precio_producto(200)
300.0
>>> calcular_precio_producto(300)
450.0
>>> calcular_precio_producto(600)
900.0
:param coste_producto:
:return:
"""
coste_producto_comision... |
class EventTrackingServiceException(Exception):
def __init__(self, message, data=None):
super(EventTrackingServiceException, self).__init__(message)
self.data = data
self.message = message
def __str__(self):
return '<EventTrackingServiceException: {}, data={}>'.format(self.messa... | class Eventtrackingserviceexception(Exception):
def __init__(self, message, data=None):
super(EventTrackingServiceException, self).__init__(message)
self.data = data
self.message = message
def __str__(self):
return '<EventTrackingServiceException: {}, data={}>'.format(self.mess... |
# -*- coding: utf-8 -*-
class Credit(object):
def __init__(self, credit):
self.url = credit['link']['url']
self.text = credit['link']['text']
def __str__(self):
return '\tUrl: {0} \n\tText: {1}'.format(self.url, self.text) | class Credit(object):
def __init__(self, credit):
self.url = credit['link']['url']
self.text = credit['link']['text']
def __str__(self):
return '\tUrl: {0} \n\tText: {1}'.format(self.url, self.text) |
i = 0
k = 1
def setup ():
size(500, 500)
smooth()
strokeWeight(30)
background(0)
def draw ():
global i,k
stroke(i, 20)
line(mouseX -50,mouseY -50, 100+mouseX -50, 100+mouseY -50)
line(100+mouseX -50,mouseY -50, mouseX -50, 100+mouseY -50)
i +=k
if(i == 255):
k=-1
... | i = 0
k = 1
def setup():
size(500, 500)
smooth()
stroke_weight(30)
background(0)
def draw():
global i, k
stroke(i, 20)
line(mouseX - 50, mouseY - 50, 100 + mouseX - 50, 100 + mouseY - 50)
line(100 + mouseX - 50, mouseY - 50, mouseX - 50, 100 + mouseY - 50)
i += k
if i == 255:
... |
def bubble_sort (List):
print("Current values are: ",List)
countswaps=0
for i in range(0,len(List)-1):
for j in range(0,len(List)-1):
if List[i] > List[j+1]:
List[j],List[j+1]=List[j+1],List[j]
countswaps +=1
print("swap",countswaps,"is: ",... | def bubble_sort(List):
print('Current values are: ', List)
countswaps = 0
for i in range(0, len(List) - 1):
for j in range(0, len(List) - 1):
if List[i] > List[j + 1]:
(List[j], List[j + 1]) = (List[j + 1], List[j])
countswaps += 1
print('s... |
a = 15 * 3
b = 15 / 3
c = 15 // 2
d = 15 ** 2
print(type(a), a)
print(type(b), b)
print(type(c), b)
print(type(d), d)
| a = 15 * 3
b = 15 / 3
c = 15 // 2
d = 15 ** 2
print(type(a), a)
print(type(b), b)
print(type(c), b)
print(type(d), d) |
#4. Write a Python program to get the smallest number from a list.
def smallest_num_list(list):
min = list[0]
for a in list:
if a < min:
min = a
return min
print(smallest_num_list([1,2,-8,0,-1232])) | def smallest_num_list(list):
min = list[0]
for a in list:
if a < min:
min = a
return min
print(smallest_num_list([1, 2, -8, 0, -1232])) |
class Point:
def __init__(self, xVal, yVal):
self.xVal_ = xVal
self.yVal_ = yVal
| class Point:
def __init__(self, xVal, yVal):
self.xVal_ = xVal
self.yVal_ = yVal |
WIDTH = 600
HEIGHT = 600
# Colours
WHITE = (255,255,255)
BLACK = (0,0,0)
LIGHTBLUE = (96, 216, 232)
LOCKEDCELLCOLOUR = (189,189,189)
INCORRECTCELLCOLOUR = (195,121,121)
# Boards
testBoard1 = [[0 for x in range(9)] for x in range(9)]
testBoard2 = [[0,6,0,2,0,0,8,3,1],
[0,0,0,0,8,4,0,0,0],
[... | width = 600
height = 600
white = (255, 255, 255)
black = (0, 0, 0)
lightblue = (96, 216, 232)
lockedcellcolour = (189, 189, 189)
incorrectcellcolour = (195, 121, 121)
test_board1 = [[0 for x in range(9)] for x in range(9)]
test_board2 = [[0, 6, 0, 2, 0, 0, 8, 3, 1], [0, 0, 0, 0, 8, 4, 0, 0, 0], [0, 0, 7, 6, 0, 3, 0, 4,... |
rat_1 = [1,2,3,4,5,6,7,8,9,10]
rat_2 = [11,12,13,14,15,16,17,18,19,20]
if rat_1[0] > rat_2[0]:
print("Rat 1 weighed more than rat 2 on day 1.")
else:
print("Rat 1 weighed less than rat 2 on day 1.")
if (rat_1[0] > rat_2[0]) and (rat_1[9] > rat_2[9]):
print("Rat 1 remained heavier than Rat 2.")
elif (rat_1... | rat_1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
rat_2 = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
if rat_1[0] > rat_2[0]:
print('Rat 1 weighed more than rat 2 on day 1.')
else:
print('Rat 1 weighed less than rat 2 on day 1.')
if rat_1[0] > rat_2[0] and rat_1[9] > rat_2[9]:
print('Rat 1 remained heavier than Rat 2.')... |
{'networks':
[
{u'provider:physical_network': None,
u'port_security_enabled': True,
u'provider:network_type': u'vxlan',
u'id': u'956df7c4-25d9-4564-8b81-843462ae707a',
u'router:external': False,
u'availability_zone_hints': [],
u'availability_zones': [u'nova'],
u'ipv4_address_scope': None,
... | {'networks': [{u'provider:physical_network': None, u'port_security_enabled': True, u'provider:network_type': u'vxlan', u'id': u'956df7c4-25d9-4564-8b81-843462ae707a', u'router:external': False, u'availability_zone_hints': [], u'availability_zones': [u'nova'], u'ipv4_address_scope': None, u'shared': False, u'project_id'... |
# Collections Dictionary practice (basics)
# Create a dictionary about Alex
alex = {'Age' : 32 , 'Married' : 'Yes' ,'Kids' : 3}
print("(1) - This is Alex's dictionary : " +str(alex))
# Extract values of the dictionary into variables
age = alex['Age']
marriage_status = alex['Married']
number_of_kids = alex['Kids']
pr... | alex = {'Age': 32, 'Married': 'Yes', 'Kids': 3}
print("(1) - This is Alex's dictionary : " + str(alex))
age = alex['Age']
marriage_status = alex['Married']
number_of_kids = alex['Kids']
print("(2) - Print of 'age' value " + str(age))
print("(2) - Print of 'marriage_status' value : " + marriage_status)
print("(2) - Prin... |
#!/usr/bin/env python
# coding=utf-8
RECORD_BASE_DIR = '/home/vision/data/vision/'
source_db_host = '192.168.100.151'
source_db_port = '1433'
source_db_database = 'QADB'
source_db_user = 'read'
source_db_pwd = 'read'
# rl_db_host = '10.15.97.128'
# rl_db_port = '3306'
# rl_db_database = 'vision'
# rl_db_user = 'root'... | record_base_dir = '/home/vision/data/vision/'
source_db_host = '192.168.100.151'
source_db_port = '1433'
source_db_database = 'QADB'
source_db_user = 'read'
source_db_pwd = 'read'
rl_db_host = '39.98.3.182'
rl_db_port = '3306'
rl_db_database = 'vision'
rl_db_user = 'factor_edit'
rl_db_pwd = 'factor_edit_2019'
pre_db_ho... |
def lcm(a, b):
if b > a:
a, b = b, a
if a % b == 0:
return a
mul = 2
while a * mul % b != 0:
mul += 1
return a * mul
while True:
c = int(input('Enter the first number(0 to exit): '))
d = int(input("Enter the second number(0 to exit): "))
if c == 0 or d == 0:
... | def lcm(a, b):
if b > a:
(a, b) = (b, a)
if a % b == 0:
return a
mul = 2
while a * mul % b != 0:
mul += 1
return a * mul
while True:
c = int(input('Enter the first number(0 to exit): '))
d = int(input('Enter the second number(0 to exit): '))
if c == 0 or d == 0:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.