content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#
# PySNMP MIB module CISCO-ATM-SWITCH-CUG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ATM-SWITCH-CUG-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:33:30 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_size_constraint, constraints_union, value_range_constraint) ... |
__author__ = 'rramchandani'
class TimeOutException(Exception):
message = "There was a system timeout before operation could be able to complete."
class BuildError(Exception):
message = "Invalid Build ID"
class LoginError(Exception):
message = "It's mandatory be logged in; to execute this operation."
c... | __author__ = 'rramchandani'
class Timeoutexception(Exception):
message = 'There was a system timeout before operation could be able to complete.'
class Builderror(Exception):
message = 'Invalid Build ID'
class Loginerror(Exception):
message = "It's mandatory be logged in; to execute this operation."
cla... |
#Program to implement Round Robin
print("Round Robin Scheduling algorithm")
print("================================")
headers = ['Processes','Arrival Time','Burst Time','Completion Time','Waiting Time',
'Turn-Around Time']
out = []
quantum = int(input("Enter value for quantum := "))
N = int(input("Enter ... | print('Round Robin Scheduling algorithm')
print('================================')
headers = ['Processes', 'Arrival Time', 'Burst Time', 'Completion Time', 'Waiting Time', 'Turn-Around Time']
out = []
quantum = int(input('Enter value for quantum := '))
n = int(input('Enter number of processes := '))
bt = []
t = 0
for ... |
conjunto = set()
print(conjunto)
conjunto = {1,2,3}
conjunto.add(4)
conjunto.add(0)
conjunto.add('H')
conjunto.add('A')
conjunto.add('Z')
print(conjunto)
grupo = {'Hector', 'Juan', 'Mario'}
print('Hector' in grupo)
test = {'Hector', 'Hector', 'Hector'}
print(test)
# CASTEO
l = [1,2,3,3,2,1]
c = set(l)
print(c)
l ... | conjunto = set()
print(conjunto)
conjunto = {1, 2, 3}
conjunto.add(4)
conjunto.add(0)
conjunto.add('H')
conjunto.add('A')
conjunto.add('Z')
print(conjunto)
grupo = {'Hector', 'Juan', 'Mario'}
print('Hector' in grupo)
test = {'Hector', 'Hector', 'Hector'}
print(test)
l = [1, 2, 3, 3, 2, 1]
c = set(l)
print(c)
l = [1, 2,... |
"""
Contains mocks for testing purposes.
"""
mock_get = {
'/computes/local': '{"capabilities": {"node_types": ["cloud", "ethernet_hub", "ethernet_switch", "vpcs", "virtualbox", "dynamips", "frame_relay_switch", "atm_switch", "qemu", "vmware"], "platform": "darwin", "version": "2.0.3"}, "compute_id": "local", "conne... | """
Contains mocks for testing purposes.
"""
mock_get = {'/computes/local': '{"capabilities": {"node_types": ["cloud", "ethernet_hub", "ethernet_switch", "vpcs", "virtualbox", "dynamips", "frame_relay_switch", "atm_switch", "qemu", "vmware"], "platform": "darwin", "version": "2.0.3"}, "compute_id": "local", "connected"... |
def _mask_border_keypoints(image, keypoints, dist):
"""Removes keypoints that are within dist pixels from the image border."""
width = image.shape[0]
height = image.shape[1]
keypoints_filtering_mask = ((dist - 1 < keypoints[:, 0]) &
(keypoints[:, 0] < width - dist + 1)... | def _mask_border_keypoints(image, keypoints, dist):
"""Removes keypoints that are within dist pixels from the image border."""
width = image.shape[0]
height = image.shape[1]
keypoints_filtering_mask = (dist - 1 < keypoints[:, 0]) & (keypoints[:, 0] < width - dist + 1) & (dist - 1 < keypoints[:, 1]) & (k... |
class Solution:
"""
@param L: Given n pieces of wood with length L[i]
@param k: An integer
@return: The maximum length of the small pieces
"""
def woodCut(self, L, k):
# write your code here
if L is None or len(L) == 0:
return 0
... | class Solution:
"""
@param L: Given n pieces of wood with length L[i]
@param k: An integer
@return: The maximum length of the small pieces
"""
def wood_cut(self, L, k):
if L is None or len(L) == 0:
return 0
start = 0
end = max(L)
while... |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 1 20:59:20 2021
@author: remotelab
"""
q1 = d[2]+1j*d[3] # Complex phasor for Channel 1
q2 = d[4]+1j*d[5] # Complex phasor for Channel 2
q1r = q1*abs(q2)/q2 # q1 but with phase relative to that of q2
x = ( d[1] ) # ... | """
Created on Mon Mar 1 20:59:20 2021
@author: remotelab
"""
q1 = d[2] + 1j * d[3]
q2 = d[4] + 1j * d[5]
q1r = q1 * abs(q2) / q2
x = d[1]
y = (abs(q1r), angle(q1r))
xlabels = 'Frequency (Hz)'
ylabels = ('Magnitude', 'Relative Phase') |
class Token(object):
def __init__(self, token_type, value):
"""Initialize with token type and value"""
self.token_type = token_type
self.value = value
def __eq__(self, other):
return self.token_type == other.token_type and self.value == other.value
def __str__(self):
... | class Token(object):
def __init__(self, token_type, value):
"""Initialize with token type and value"""
self.token_type = token_type
self.value = value
def __eq__(self, other):
return self.token_type == other.token_type and self.value == other.value
def __str__(self):
... |
n = list()
def notas(notes,sit=False):
report = dict()
report['Total'] = len(notes)
report['Highest'] = max(notes)
report['Lowest'] = min(notes)
report['Avg'] = sum(notes)/len(notes)
return report
quant = int(input("How many notes do you want to register: "))
for c in range(0,quant):
n.ap... | n = list()
def notas(notes, sit=False):
report = dict()
report['Total'] = len(notes)
report['Highest'] = max(notes)
report['Lowest'] = min(notes)
report['Avg'] = sum(notes) / len(notes)
return report
quant = int(input('How many notes do you want to register: '))
for c in range(0, quant):
n.... |
# -*- coding: utf-8 -*-
class Solution:
def totalHammingDistance(self, nums):
result = 0
for digit in range(32):
partial = 0
for num in nums:
partial += (num >> digit) & 1
result += partial * (len(nums) - partial)
return result
if __n... | class Solution:
def total_hamming_distance(self, nums):
result = 0
for digit in range(32):
partial = 0
for num in nums:
partial += num >> digit & 1
result += partial * (len(nums) - partial)
return result
if __name__ == '__main__':
solu... |
"""
Write a program that accepts a year as input and outputs the century the year belongs in (e.g. 18th century's year
ranges are 1701 to 1800) and whether or not the year is a leap year. Pseudocode for leap year can be found
here[https://en.wikipedia.org/wiki/Leap_year#Algorithm].
Sample run:
Enter Year: 1996
Century... | """
Write a program that accepts a year as input and outputs the century the year belongs in (e.g. 18th century's year
ranges are 1701 to 1800) and whether or not the year is a leap year. Pseudocode for leap year can be found
here[https://en.wikipedia.org/wiki/Leap_year#Algorithm].
Sample run:
Enter Year: 1996
Century... |
# -*- coding: utf-8 -*-
# 0xCCCCCCCC
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def sorted_array_2_bst(nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if len(nums) == 0:
... | class Treenode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def sorted_array_2_bst(nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if len(nums) == 0:
return None
return gen_bst(nums, 0, len(nums))
def gen_bst(nums, l... |
# initialize objects that control robot components
left_motor = Motor(1)
right_motor = Motor(2)
gyro = Gyro()
# create a controller object and set its goal
controller = PID(0.2, 0.002, 0.015, time, gyro)
controller.set_goal(0) # the goal is 0 because we want to head straight
while True:
# get the contr... | left_motor = motor(1)
right_motor = motor(2)
gyro = gyro()
controller = pid(0.2, 0.002, 0.015, time, gyro)
controller.set_goal(0)
while True:
controller_value = controller.get_value()
arcade_drive(controller_value, 0, left_motor, right_motor) |
def ask(prompt):
'''Get a number from the user.'''
while True:
ans = input(prompt)
if ans.upper().startswith("Q"):
return "Q"
if ans.isdigit():
return int(ans)
print("Sorry, invalid response. Please try again.") | def ask(prompt):
"""Get a number from the user."""
while True:
ans = input(prompt)
if ans.upper().startswith('Q'):
return 'Q'
if ans.isdigit():
return int(ans)
print('Sorry, invalid response. Please try again.') |
word = input("Enter your string: ")
dic = {}
length = len(word)
count = 0
lcount = 2
while True:
for elm in range(count,length):
if lcount >length:
break
temp = word[count:lcount]
if len(temp)%2 == 0:
atemp = temp[0:(len(temp)//2)]
btemp = temp[(len(t... | word = input('Enter your string: ')
dic = {}
length = len(word)
count = 0
lcount = 2
while True:
for elm in range(count, length):
if lcount > length:
break
temp = word[count:lcount]
if len(temp) % 2 == 0:
atemp = temp[0:len(temp) // 2]
btemp = temp[len(tem... |
"""
a SQLAlchemy based implementation...so an engine string could be used.
Not fully implemented
"""
stype = 'SQLAlchemy'
renew = True
class Source(object):
def __init__(self, ses, **kwargs):
NotImplementedError("SQLAlchemy")
def getseries(self, ses, **kwargs):
NotImplementedError("SQLAlchem... | """
a SQLAlchemy based implementation...so an engine string could be used.
Not fully implemented
"""
stype = 'SQLAlchemy'
renew = True
class Source(object):
def __init__(self, ses, **kwargs):
not_implemented_error('SQLAlchemy')
def getseries(self, ses, **kwargs):
not_implemented_error('SQLAl... |
class Menu:
def __init__(self, rdoc, on_add=None):
self.rdoc = rdoc
self.element = rdoc.element('nav')
vn = '#' + self.element.varname
self.rule_menu = rdoc.stylesheet.rule(vn)
self.rule_item = rdoc.stylesheet.rule(vn + ' > li')
self.rule_item_hover = rdoc.stylesheet... | class Menu:
def __init__(self, rdoc, on_add=None):
self.rdoc = rdoc
self.element = rdoc.element('nav')
vn = '#' + self.element.varname
self.rule_menu = rdoc.stylesheet.rule(vn)
self.rule_item = rdoc.stylesheet.rule(vn + ' > li')
self.rule_item_hover = rdoc.stylesheet... |
word1 = 'ox'
word2 = 'owl'
word3 = 'cow'
word4 = 'sheep'
word5 = 'flies'
word6 = 'trots'
word7 = 'runs'
word8 = 'blue'
word9 = 'red'
word10 = 'yellow'
word9 = 'The ' + word9
passcode = word8
passcode = word9
passcode = passcode + ' f'
passcode = passcode + word1
passcode = passcode + ' '
passcode = pass... | word1 = 'ox'
word2 = 'owl'
word3 = 'cow'
word4 = 'sheep'
word5 = 'flies'
word6 = 'trots'
word7 = 'runs'
word8 = 'blue'
word9 = 'red'
word10 = 'yellow'
word9 = 'The ' + word9
passcode = word8
passcode = word9
passcode = passcode + ' f'
passcode = passcode + word1
passcode = passcode + ' '
passcode = passcode + word6
pri... |
class Solution(object):
def myAtoi(self, string):
"""
:type str: str
:rtype: int
"""
# round 0: handle special case, preprocess
if len(string)==0: return 0
string = string.strip()
# round 1: filtering
res = []
for (k,token) in enumerate... | class Solution(object):
def my_atoi(self, string):
"""
:type str: str
:rtype: int
"""
if len(string) == 0:
return 0
string = string.strip()
res = []
for (k, token) in enumerate(string):
if k == 0 and (token == '+' or token == '... |
sigma_s = 1
N_d = 32
N_c = 8
K = 50
P_FA = 0.05
SNR = 10
SNR_LOW = -20
SNR_UP = 6
SNR_STEP = 2
SNR_NOISE = 1
P_H1 = 0.2
NUM_STATISTICS = 1000
#NUM_STATISTICS = 100000
| sigma_s = 1
n_d = 32
n_c = 8
k = 50
p_fa = 0.05
snr = 10
snr_low = -20
snr_up = 6
snr_step = 2
snr_noise = 1
p_h1 = 0.2
num_statistics = 1000 |
#Open file and store data
data = []
with open('inputs\input5.txt') as f:
data = f.readlines()
data = [line.strip() for line in data]
#Define Functions with Binary Conversions
def splitRowCol(boardingPass):
return(boardingPass[0:7],boardingPass[7:])
def convToBinary(inputStr,convToZero=["F","L"],convToOne... | data = []
with open('inputs\\input5.txt') as f:
data = f.readlines()
data = [line.strip() for line in data]
def split_row_col(boardingPass):
return (boardingPass[0:7], boardingPass[7:])
def conv_to_binary(inputStr, convToZero=['F', 'L'], convToOne=['B', 'R']):
input_str = list(inputStr)
for char_i... |
doc+='''<head>\n <title>Privacy Policy</title>\n <meta charset="utf-8">\n <meta name="format-detection" content="telephone=no">\n <link rel="icon" href="images/favicon.ico" type="image/x-icon">\n <link rel="stylesheet" href="'''
try: doc+=str(data['base_url'])
except Exception as e: doc+=str(e)
doc+='''s... | doc += '<head>\n <title>Privacy Policy</title>\n <meta charset="utf-8">\n <meta name="format-detection" content="telephone=no">\n <link rel="icon" href="images/favicon.ico" type="image/x-icon">\n <link rel="stylesheet" href="'
try:
doc += str(data['base_url'])
except Exception as e:
doc += str(e)... |
class ViewModel:
def __init__(self):
self._is_valid = None
"""
should contain entries of form {'control_id': 'error message'}.
entries may contain the same value for 'control_id' if there are
muliple errors pertaining to that particular 'control_id'
"""
s... | class Viewmodel:
def __init__(self):
self._is_valid = None
"\n should contain entries of form {'control_id': 'error message'}.\n entries may contain the same value for 'control_id' if there are\n muliple errors pertaining to that particular 'control_id'\n "
s... |
class Core(object):
def foo(self):
pass
c = Core()
| class Core(object):
def foo(self):
pass
c = core() |
"""This is the player."""
class Player:
"""This is a player class."""
def __init__(self, name):
"""Initiate the player."""
self._name = name
self._score = 0
@property
def name(self):
"""Get player's name."""
return self._name
@property
def score(self)... | """This is the player."""
class Player:
"""This is a player class."""
def __init__(self, name):
"""Initiate the player."""
self._name = name
self._score = 0
@property
def name(self):
"""Get player's name."""
return self._name
@property
def score(self):... |
microcode = '''
def macroop VPADDD_XMM_XMM {
vaddi dest=xmm0, src1=xmm0v, src2=xmm0m, size=4, VL=16
};
def macroop VPADDD_XMM_M {
ldfp128 ufp1, seg, sib, "DISPLACEMENT + 0", dataSize=16
vaddi dest=xmm0, src1=xmm0v, src2=ufp1, size=4, VL=16
};
def macroop VPADDD_XMM_P {
rdip t7
ldfp128 ufp1, seg, r... | microcode = '\ndef macroop VPADDD_XMM_XMM {\n vaddi dest=xmm0, src1=xmm0v, src2=xmm0m, size=4, VL=16\n};\n\ndef macroop VPADDD_XMM_M {\n ldfp128 ufp1, seg, sib, "DISPLACEMENT + 0", dataSize=16\n vaddi dest=xmm0, src1=xmm0v, src2=ufp1, size=4, VL=16\n};\n\ndef macroop VPADDD_XMM_P {\n rdip t7\n ldfp128 uf... |
# -*- coding: utf-8 -*-
'''
@author: Andreas Peldszus
'''
folds = [
['micro_k009', 'micro_b050', 'micro_b055', 'micro_b041', 'micro_b036', 'micro_b007', 'micro_k021', 'micro_d08', 'micro_b033', 'micro_b060', 'micro_b034', 'micro_k003', 'micro_d15', 'micro_d20', 'micro_k012', 'micro_d13', 'micro_b010', 'micro_k029... | """
@author: Andreas Peldszus
"""
folds = [['micro_k009', 'micro_b050', 'micro_b055', 'micro_b041', 'micro_b036', 'micro_b007', 'micro_k021', 'micro_d08', 'micro_b033', 'micro_b060', 'micro_b034', 'micro_k003', 'micro_d15', 'micro_d20', 'micro_k012', 'micro_d13', 'micro_b010', 'micro_k029', 'micro_d14', 'micro_b024', '... |
load("@io_bazel_rules_sass//:defs.bzl", "sass_repositories")
def rules_web_dependencies():
sass_repositories()
| load('@io_bazel_rules_sass//:defs.bzl', 'sass_repositories')
def rules_web_dependencies():
sass_repositories() |
count = 0
inputNum = 1
prevInput = -1
while (inputNum > 0):
inputNum = int(input())
if inputNum == prevInput:
count += 1
prevInput = inputNum
print (f'{count}')
| count = 0
input_num = 1
prev_input = -1
while inputNum > 0:
input_num = int(input())
if inputNum == prevInput:
count += 1
prev_input = inputNum
print(f'{count}') |
def snail(h, a, b):
now_high = 0
d = 0
while now_high < h:
now_high += a
if now_high < h:
now_high -= b
d += 1
print(d)
snail(int(input()), int(input()), int(input()))
| def snail(h, a, b):
now_high = 0
d = 0
while now_high < h:
now_high += a
if now_high < h:
now_high -= b
d += 1
print(d)
snail(int(input()), int(input()), int(input())) |
"""
http://community.topcoder.com/stat?c=problem_statement&pm=1708
Single Round Match 144 Round 1 - Division II, Level One
"""
class Time:
def whatTime(self, seconds):
return ':'.join(map(str, [int(seconds / 3600), int(seconds % 3600 / 60), seconds % 60]))
| """
http://community.topcoder.com/stat?c=problem_statement&pm=1708
Single Round Match 144 Round 1 - Division II, Level One
"""
class Time:
def what_time(self, seconds):
return ':'.join(map(str, [int(seconds / 3600), int(seconds % 3600 / 60), seconds % 60])) |
"""
Just a placeholder
"""
class TestDummy:
"""
Dummy test
"""
@staticmethod
def test_do_nothing() -> None:
"""Do nothing"""
assert True
@staticmethod
def test_do_nothing2() -> None:
"""Do nothing"""
assert True
| """
Just a placeholder
"""
class Testdummy:
"""
Dummy test
"""
@staticmethod
def test_do_nothing() -> None:
"""Do nothing"""
assert True
@staticmethod
def test_do_nothing2() -> None:
"""Do nothing"""
assert True |
apiAttachAvailable = u'API tillg\xe4ngligt'
apiAttachNotAvailable = u'Inte tillg\xe4ngligt'
apiAttachPendingAuthorization = u'Godk\xe4nnande avvaktas'
apiAttachRefused = u'Nekades'
apiAttachSuccess = u'Det lyckades'
apiAttachUnknown = u'Ok\xe4nd'
budDeletedFriend = u'Borttagen fr\xe5n kontaktlistan'
budFriend = u'V\xe4... | api_attach_available = u'API tillgängligt'
api_attach_not_available = u'Inte tillgängligt'
api_attach_pending_authorization = u'Godkännande avvaktas'
api_attach_refused = u'Nekades'
api_attach_success = u'Det lyckades'
api_attach_unknown = u'Okänd'
bud_deleted_friend = u'Borttagen från kontaktlistan'
bud_friend = u'Vän... |
class Student:
def __init__(self, name, school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(self.marks) / len(self.marks)
@classmethod
def friend(cls, origin, friend_name, *args, **kwargs):
return cls(friend_name, origin... | class Student:
def __init__(self, name, school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(self.marks) / len(self.marks)
@classmethod
def friend(cls, origin, friend_name, *args, **kwargs):
return cls(friend_name, origin... |
def round_counter():
RCi = 0
RCi_list = []
# print(type(RCi))
l = 0
for l in range (48):
# print(type(RCi))
RCi = bin(RCi)[2:].zfill(6)
RCi_one_list = [int(d) for d in str((RCi))]
# print(RCi_one_list)
t = 1 + RCi_one_list[0] + RCi_one_list[1]
t = t % ... | def round_counter():
r_ci = 0
r_ci_list = []
l = 0
for l in range(48):
r_ci = bin(RCi)[2:].zfill(6)
r_ci_one_list = [int(d) for d in str(RCi)]
t = 1 + RCi_one_list[0] + RCi_one_list[1]
t = t % 2
RCi_one_list.append(RCi_one_list.pop(0))
RCi_one_list[5] = t
... |
# enter your file path
DATA_PATH = "./lab1/data"
# file names
IN_FILE = "input.txt"
OUT_FILE = "output.txt"
def main():
lines = []
# open input file
with open("{}/{}".format(DATA_PATH, IN_FILE), "r") as file:
# reach each line
for line in file:
# print removing newline
... | data_path = './lab1/data'
in_file = 'input.txt'
out_file = 'output.txt'
def main():
lines = []
with open('{}/{}'.format(DATA_PATH, IN_FILE), 'r') as file:
for line in file:
print(line.strip())
lines.append(line)
lines = lines[-1::-1]
with open('{}/{}'.format(DATA_PATH, O... |
#!/usr/bin/python
# Copyright 2017 Hewlett-Packard Enterprise Development Company, L.P.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.... | def integer(value):
return value
def object_name(value):
return (value,)
phy_drive_mib_output = {'SNMPv2-SMI::enterprises.232.3.2.5.1.1.1.2.0': {'cpqDaPhyDrvCntlrIndex': {object_name('2.0'): integer(2)}}, 'SNMPv2-SMI::enterprises.232.3.2.5.1.1.1.2.1': {'cpqDaPhyDrvCntlrIndex': {object_name('2.1'): integer(2)}}... |
# Simple account class with balance
class Account:
def __init__(self, name, balance):
self.name = name
self.balance = balance
print("Account is created for {}".format(self.name))
def deposit(self, amount):
if amount > 0:
self.balance += amount
def withdr... | class Account:
def __init__(self, name, balance):
self.name = name
self.balance = balance
print('Account is created for {}'.format(self.name))
def deposit(self, amount):
if amount > 0:
self.balance += amount
def withdraw(self, amount):
if 0 < amount < s... |
def isPrime(number):
prime = True
global code
for c in range(2, number):
if number % c == 0:
prime = False
if prime is True and len(str(number)) == 3:
code = number
code = counter = 0
while True:
isPrime(counter)
if counter == 1000:
break
counter += 1
pr... | def is_prime(number):
prime = True
global code
for c in range(2, number):
if number % c == 0:
prime = False
if prime is True and len(str(number)) == 3:
code = number
code = counter = 0
while True:
is_prime(counter)
if counter == 1000:
break
counter += 1
pr... |
"""
Trapping Rain Water
Given n non-negative integers representing an elevation map where the
width of each bar is 1, compute how much water it can trap after raining.
Example 1:
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,... | """
Trapping Rain Water
Given n non-negative integers representing an elevation map where the
width of each bar is 1, compute how much water it can trap after raining.
Example 1:
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'ole'
class Message:
irc = None
propagate = True
# IRC-protocol attributes
prefix = ""
command = []
content = ""
# IRC-command dependent attributes
cmd = [] # bot-command within message
nick = ""
channel = None
de... | __author__ = 'ole'
class Message:
irc = None
propagate = True
prefix = ''
command = []
content = ''
cmd = []
nick = ''
channel = None
def __init__(self, irc, message):
self.irc = irc
prefix_end = 0
if len(message) > 0 and message[0] == ':':
prefi... |
# Done by Carlos Amaral (2020/09/22)
# SCU 4.7 - Range Function with a For Loop
for i in range(1,10):
print(i, " squared is ", i**2)
| for i in range(1, 10):
print(i, ' squared is ', i ** 2) |
DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
}
INSTALLED_APPS = [
'tests.testapp',
]
ROOT_URLCONF = 'tests.urls'
| debug = True
databases = {'default': {'ENGINE': 'django.db.backends.sqlite3'}}
installed_apps = ['tests.testapp']
root_urlconf = 'tests.urls' |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "nebula"
class BeFilteredException(Exception):
def __init__(self, t):
self._t = t
@property
def type(self):
return self._t
| __author__ = 'nebula'
class Befilteredexception(Exception):
def __init__(self, t):
self._t = t
@property
def type(self):
return self._t |
"""
* Load and Display
*
* Images can be loaded and displayed to the screen at their actual size
* or any other size.
"""
def setup():
size(640, 360)
# The image file must be in the data folder of the current sketch
# to load successfully
global img
img = loadImage("moonwalk.jpg") # Loa... | """
* Load and Display
*
* Images can be loaded and displayed to the screen at their actual size
* or any other size.
"""
def setup():
size(640, 360)
global img
img = load_image('moonwalk.jpg')
no_loop()
def draw():
image(img, 0, 0)
image(img, 0, height / 2, img.width / 2, img.height /... |
def gcd_iter(u, v):
while v:
u, v = v, u % v
return abs(u)
| def gcd_iter(u, v):
while v:
(u, v) = (v, u % v)
return abs(u) |
# Silvio Dunst
# Variables can be of type function, and we can call those variables.
# This means that lists, tuples and dicts can have variables of type function in them,
# so we could have a dict that stores the letter of the menu and the function associated with that letter.
# We could access that function by that... | def fun1():
print('this is fun1')
def fun2():
print('this is fun2')
which_fun = fun1
which_fun()
which_fun = fun2
which_fun() |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 5 16:02:48 2018
@author: matteo
"""
| """
Created on Thu Apr 5 16:02:48 2018
@author: matteo
""" |
def isInterleave(s1: str, s2: str, s3: str) -> bool:
def dfs(i, j, k): # dfs with memo
if i == len(s1):
return s2[j:] == s3[k:]
if j == len(s2):
return s1[i:] == s3[k:]
if (i, j) in memo:
return memo[(i, j)]
res = F... | def is_interleave(s1: str, s2: str, s3: str) -> bool:
def dfs(i, j, k):
if i == len(s1):
return s2[j:] == s3[k:]
if j == len(s2):
return s1[i:] == s3[k:]
if (i, j) in memo:
return memo[i, j]
res = False
if s1[i] == s3[k] and dfs(i + 1, j, ... |
# S and T are strings composed of lowercase letters. In S, no letter occurs more
# than once.
# S was sorted in some custom order previously. We want to permute the characters
# of T so that they match the order that S was sorted. More specifically, if x
# occurs before y in S, then x should occur before y in the retu... | class Solution:
def custom_sort_string(self, S, T):
"""
:type S: str
:type T: str
:rtype: str
"""
return ''.join(sorted(T, key=S.find))
sol = solution().customSortString
print(sol('cba', 'abcd')) |
with open("inputs/6.txt") as f:
input = f.read()
groups = [group.split() for group in input.split('\n\n')]
total_answers = 0
for group in groups:
total_answers += len(set(''.join(group)))
print("Part 1 answer:", total_answers)
total_answers = 0
for group in groups:
sets = list(map(set, group))
total... | with open('inputs/6.txt') as f:
input = f.read()
groups = [group.split() for group in input.split('\n\n')]
total_answers = 0
for group in groups:
total_answers += len(set(''.join(group)))
print('Part 1 answer:', total_answers)
total_answers = 0
for group in groups:
sets = list(map(set, group))
total_ans... |
#disorder
def distinct_list(a):
return list(set(a))
| def distinct_list(a):
return list(set(a)) |
class CreditCard:
""" A consumer credit card."""
def __init__(self, customer, bank, acnt, limit):
"""Create a new credit card instance.
The initial balance is zero.
customer the name of the customer (e.g., 'John Bowman')
bank the name of the bank (e.g., 'Californi... | class Creditcard:
""" A consumer credit card."""
def __init__(self, customer, bank, acnt, limit):
"""Create a new credit card instance.
The initial balance is zero.
customer the name of the customer (e.g., 'John Bowman')
bank the name of the bank (e.g., 'California Savings... |
class SingleLinkedList(object):
"""
simple implimentation of a linked singly linked list
"""
def __init__(self):
"""
initializes a new node with none values
"""
self.next = None
self.data = None
def set_value(self,
value):
"""
... | class Singlelinkedlist(object):
"""
simple implimentation of a linked singly linked list
"""
def __init__(self):
"""
initializes a new node with none values
"""
self.next = None
self.data = None
def set_value(self, value):
"""
sets the data v... |
f = open('in_domain_dev.tsv', 'r').readlines()
g1 = open('val.src', 'w')
g2 = open('val.tgt', 'w')
for line in f:
line = line.split('\t')
_, label, _, text = line
g1.write('{}'.format(text))
g2.write('{}\n'.format(label))
| f = open('in_domain_dev.tsv', 'r').readlines()
g1 = open('val.src', 'w')
g2 = open('val.tgt', 'w')
for line in f:
line = line.split('\t')
(_, label, _, text) = line
g1.write('{}'.format(text))
g2.write('{}\n'.format(label)) |
matriz = [[0,0,0],[0,0,0],[0,0,0]]
for l in range(0,3):
for c in range(0,3):
matriz[l][c] = int(input(f'Digite os valores para [{l}, {c}]: '))
print('=-='*30)
for l in range(0,3):
for c in range(0,3):
print(f'[{matriz[l][c]: ^5}', end = '')
print() | matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for l in range(0, 3):
for c in range(0, 3):
matriz[l][c] = int(input(f'Digite os valores para [{l}, {c}]: '))
print('=-=' * 30)
for l in range(0, 3):
for c in range(0, 3):
print(f'[{matriz[l][c]: ^5}', end='')
print() |
def node_to_string(node, layer = 0):
message = '|' * layer + repr(node) + '\n'
for child in node.children:
message += node_to_string(child, layer + 1)
return message
| def node_to_string(node, layer=0):
message = '|' * layer + repr(node) + '\n'
for child in node.children:
message += node_to_string(child, layer + 1)
return message |
config = {
"host_server": "<host_address>",
'token_request':{
'client_id': '<client_id>',
'client_secret': '<client_secret>',
'Ocp-Apim-Subscription-Key': '<Ocp-Apim-Subscription-Key> For Access Token',
},
'ecom':{
'Content-Type': 'application/json',
'Ocp... | config = {'host_server': '<host_address>', 'token_request': {'client_id': '<client_id>', 'client_secret': '<client_secret>', 'Ocp-Apim-Subscription-Key': '<Ocp-Apim-Subscription-Key> For Access Token'}, 'ecom': {'Content-Type': 'application/json', 'Ocp-Apim-Subscription-Key': '<Ocp-Apim-Subscription-Key> For the eComme... |
def calc(n):
if n<12:
return n
if dp[n]:
return dp[n]
x=calc(n//2)+calc(n//3)+calc(n//4)
dp[n]=max(n,x)
return dp[n]
dp=[0 for i in range(1000000)]
n=int(input())
print(calc(n))
#==============================
def decode(s):
for i in range(2,len(s)+1):
prev=... | def calc(n):
if n < 12:
return n
if dp[n]:
return dp[n]
x = calc(n // 2) + calc(n // 3) + calc(n // 4)
dp[n] = max(n, x)
return dp[n]
dp = [0 for i in range(1000000)]
n = int(input())
print(calc(n))
def decode(s):
for i in range(2, len(s) + 1):
prev = int(s[i - 2])
... |
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
y = int(x)
r = 0
while x > 0:
r *= 10
r += x % 10
x //= 10
print(r)
if r == y:
return True
else:
... | class Solution(object):
def is_palindrome(self, x):
"""
:type x: int
:rtype: bool
"""
y = int(x)
r = 0
while x > 0:
r *= 10
r += x % 10
x //= 10
print(r)
if r == y:
return True
else:
... |
'''For a range of numbers starting at 2, determine whether the number is 'perfect', 'abundant' or 'deficient',
'''
topNum = input("What is the upper number for the range:")
topNum = int(topNum)
theNum=2
while theNum <= topNum:
# sum up the divisors
divisor = 1
sumOfDivisors = 0
while divisor < theNum:... | """For a range of numbers starting at 2, determine whether the number is 'perfect', 'abundant' or 'deficient',
"""
top_num = input('What is the upper number for the range:')
top_num = int(topNum)
the_num = 2
while theNum <= topNum:
divisor = 1
sum_of_divisors = 0
while divisor < theNum:
if theNum %... |
def div(n1,n2):
d = n1 // n2
r = n1 - n2 * d
print(r)
while True:
try:
num1 = float(input("Please enter the first number:"))
num2 = float(input("Please enter the second number:"))
except ValueError:
print("Please enter the number correctly.")
else:
div(num1,num2)
... | def div(n1, n2):
d = n1 // n2
r = n1 - n2 * d
print(r)
while True:
try:
num1 = float(input('Please enter the first number:'))
num2 = float(input('Please enter the second number:'))
except ValueError:
print('Please enter the number correctly.')
else:
div(num1, num2... |
#!/usr/bin/env python
# coding=utf-8
def concat(*args, sep = "/"):
return sep.join(args)
concat("earth","mars","venus")
concat("earth","mars","venus", sep=".")
| def concat(*args, sep='/'):
return sep.join(args)
concat('earth', 'mars', 'venus')
concat('earth', 'mars', 'venus', sep='.') |
class Television:
def __init__(self):
self.ligada = False
self.canal = 4
def power(self):
if self.ligada:
self.ligada = False
else:
self.ligada = True
def canal_up(self):
if self.ligada:
self.canal += 1
def canal_down(self):
... | class Television:
def __init__(self):
self.ligada = False
self.canal = 4
def power(self):
if self.ligada:
self.ligada = False
else:
self.ligada = True
def canal_up(self):
if self.ligada:
self.canal += 1
def canal_down(self):... |
"""
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may... | """
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may... |
input = """
% Input: specify parts of the rules ...
rule(r1). head(bird,r1).
rule(r2). head(swims,r1).
rule(r3). head(neg_flies,r3). pbl(peng,r3). nbl(flies,r3).
rule(r4). head(flies,r4). pbl(bird,r4). nbl(neg_flies,r4).
rule(r5). head(peng,r5). pbl(bird,r5). pbl(swims,r5). nbl(neg_peng,r5).
... | input = '\n% Input: specify parts of the rules ...\n\n\n rule(r1). head(bird,r1).\n\n rule(r2). head(swims,r1). \n\n rule(r3). head(neg_flies,r3). pbl(peng,r3). nbl(flies,r3).\n\n rule(r4). head(flies,r4). pbl(bird,r4). nbl(neg_flies,r4).\n\n rule(r5). head(peng,r5). pbl(bird,r5). pbl(swims,r5). nbl(neg_peng,r5).\n\n ... |
# Use words.txt as the file name
fname = input("Enter file name: ")
fh = open(fname)
for inp in fname:
print(inp.isUpper())
print('hello im the impostor, changes made by satyam raj')
print('ima a hacker, coz im doing this bullshit for hacktoberfest')
| fname = input('Enter file name: ')
fh = open(fname)
for inp in fname:
print(inp.isUpper())
print('hello im the impostor, changes made by satyam raj')
print('ima a hacker, coz im doing this bullshit for hacktoberfest') |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def dfs(self, node: TreeNode, sum: int) -> int:
res = 1 if node.val == sum else 0
if node.le... | class Solution:
def dfs(self, node: TreeNode, sum: int) -> int:
res = 1 if node.val == sum else 0
if node.left:
res += self.dfs(node.left, sum - node.val)
if node.right:
res += self.dfs(node.right, sum - node.val)
return res
def path_sum(self, root: Tree... |
def sssi(M, s):
L = []
for i in M[::-1]:
if s >= i:
s -= i
L.append(1)
else:
L.append(0)
if s == 0:
return L[::-1]
print("!!!!!")
| def sssi(M, s):
l = []
for i in M[::-1]:
if s >= i:
s -= i
L.append(1)
else:
L.append(0)
if s == 0:
return L[::-1]
print('!!!!!') |
"""Test Basic Addition"""
def test_basic_addition():
assert 1 + 1 == 2
def test_basic_addition_inverse():
assert 1 + 1 != 3
| """Test Basic Addition"""
def test_basic_addition():
assert 1 + 1 == 2
def test_basic_addition_inverse():
assert 1 + 1 != 3 |
class GrowingBlob:
"""
python is slow in accumulation of large data (str += segment).
Growing blob is an optimization for that
"""
def __init__(self):
self._blobs = []
self._length = 0
def append(self, blob):
self._blobs.append(blob)
self._length += len(blob)
... | class Growingblob:
"""
python is slow in accumulation of large data (str += segment).
Growing blob is an optimization for that
"""
def __init__(self):
self._blobs = []
self._length = 0
def append(self, blob):
self._blobs.append(blob)
self._length += len(blob)
... |
"""
For more details regarding inputs and output in form of complex dictionaries see the original source docs at:
%host%/docs/source/Core.html
for example:
`https://editor.webgme.org/docs/source/Core.html <https://editor.webgme.org/docs/source/Core.html>`_
"""
class Core(object):
"""
Class for... | """
For more details regarding inputs and output in form of complex dictionaries see the original source docs at:
%host%/docs/source/Core.html
for example:
`https://editor.webgme.org/docs/source/Core.html <https://editor.webgme.org/docs/source/Core.html>`_
"""
class Core(object):
"""
Class for querying and ... |
__title__ = 'consign'
__description__ = 'Python storage for humans.'
__url__ = 'https://requests.readthedocs.io'
__version__ = '0.2.2'
__author__ = 'Daniel Jadraque'
__author_email__ = 'jadraque@hey.com'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2021 Daniel Jadraque' | __title__ = 'consign'
__description__ = 'Python storage for humans.'
__url__ = 'https://requests.readthedocs.io'
__version__ = '0.2.2'
__author__ = 'Daniel Jadraque'
__author_email__ = 'jadraque@hey.com'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2021 Daniel Jadraque' |
nome = input("Digite seu nome: ")
nome = nome.strip().title()
print("No seu nome tem silva? {}".format("Silva" in nome))
print("O seu nome: {}".format(nome))
| nome = input('Digite seu nome: ')
nome = nome.strip().title()
print('No seu nome tem silva? {}'.format('Silva' in nome))
print('O seu nome: {}'.format(nome)) |
class Employee:
numEmployee = 0
def __init__(self, name, rate):
self.owed = 0
self.name = name
self.rate = rate
Employee.numEmployee += 1
def __repr__(self):
return "a custom object (%r)" % self.name
def __del__(self):
Employee.numEmployee -= 1
def... | class Employee:
num_employee = 0
def __init__(self, name, rate):
self.owed = 0
self.name = name
self.rate = rate
Employee.numEmployee += 1
def __repr__(self):
return 'a custom object (%r)' % self.name
def __del__(self):
Employee.numEmployee -= 1
de... |
def get_unique_iterable_objects_in_order(iterable):
unique_objects_in_order = []
for object_ in iterable:
if object_ not in unique_objects_in_order:
unique_objects_in_order.append(object_)
return unique_objects_in_order
| def get_unique_iterable_objects_in_order(iterable):
unique_objects_in_order = []
for object_ in iterable:
if object_ not in unique_objects_in_order:
unique_objects_in_order.append(object_)
return unique_objects_in_order |
# -*- mode: python ; coding: utf-8 -*-
block_cipher = None
a = Analysis(['D:\\temp\\main.py'],
pathex=['D:\\temp'],
binaries=[],
datas=[],
hiddenimports=[],
hookspath=[],
runtime_hooks=[],
excludes=[],
... | block_cipher = None
a = analysis(['D:\\temp\\main.py'], pathex=['D:\\temp'], binaries=[], datas=[], hiddenimports=[], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False)
pyz = pyz(a.pure, a.zipped_data, cipher=block_cipher)
exe ... |
test = {
'name': 'q1_1',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
>>> # Did you add Career Length column?;
>>> nfl.num_columns == 6
True
""",
'hidden': False,
'locked': False
},
{
'code': ... | test = {'name': 'q1_1', 'points': 1, 'suites': [{'cases': [{'code': '\n >>> # Did you add Career Length column?;\n >>> nfl.num_columns == 6\n True\n ', 'hidden': False, 'locked': False}, {'code': '\n >>> # Checking that the first 10 rows are correct;\n >>> nfl.take(... |
"""
Typcasting w. Strings
"""
# Convert these variables into strings and then back to their original data types. Print out each result as well as its data type. What do you notice about the last one?
five = 5
zero = 0
neg_8 = -8
T = True
F = False | """
Typcasting w. Strings
"""
five = 5
zero = 0
neg_8 = -8
t = True
f = False |
RAWDATA_DIR = '/staging/as/skchoudh/rna-seq-datasets/single/ornithorhynchus_anatinus/SRP007412'
OUT_DIR = '/staging/as/skchoudh/rna-seq-output/ornithorhynchus_anatinus/SRP007412'
CDNA_FA_GZ = '/home/cmb-panasas2/skchoudh/genomes/ornithorhynchus_anatinus/cdna/Ornithorhynchus_anatinus.OANA5.cdna.all.fa.gz'
CDNA_IDX ... | rawdata_dir = '/staging/as/skchoudh/rna-seq-datasets/single/ornithorhynchus_anatinus/SRP007412'
out_dir = '/staging/as/skchoudh/rna-seq-output/ornithorhynchus_anatinus/SRP007412'
cdna_fa_gz = '/home/cmb-panasas2/skchoudh/genomes/ornithorhynchus_anatinus/cdna/Ornithorhynchus_anatinus.OANA5.cdna.all.fa.gz'
cdna_idx = '/h... |
'''
Author : MiKueen
Level : Medium
Problem Statement : Find Minimum in Rotated Sorted Array
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
You may assume no duplicate exists in the array.
... | """
Author : MiKueen
Level : Medium
Problem Statement : Find Minimum in Rotated Sorted Array
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
You may assume no duplicate exists in the array.
... |
def say_hello(name):
print("Hello,", name)
user_name = input("What is your name? ")
say_hello(user_name)
| def say_hello(name):
print('Hello,', name)
user_name = input('What is your name? ')
say_hello(user_name) |
#xsv Libraries / dictionaries / variables or
# WHATEVER YOU FUCKING CALL THEM!
exampleVars = [
{
'Name': 'xH',
'Info': {
'Staff': ['Council'],
'Dev': ['Im Dynamic'],
'Office': ['Couch'],
'Role... | example_vars = [{'Name': 'xH', 'Info': {'Staff': ['Council'], 'Dev': ['Im Dynamic'], 'Office': ['Couch'], 'Role': []}}, {'Name': 'xsv', 'Info': {'Staff': ['Im Dynamic'], 'Dev': ['@Blynd'], 'Office': [], 'Role': ['Development Team']}}] |
def is_opcode(line):
return line.startswith('#define') and 'OPCODE' not in line
def get_filename_for_op(op):
return op.split("_")[0]
def get_function_name_for_op(op):
return "op_{}".format(op)
outfiles = {}
opfilenames = []
opmap = {}
ops = []
f = open("opcodes.h")
for line in f:
if is_opcode(line):
toke... | def is_opcode(line):
return line.startswith('#define') and 'OPCODE' not in line
def get_filename_for_op(op):
return op.split('_')[0]
def get_function_name_for_op(op):
return 'op_{}'.format(op)
outfiles = {}
opfilenames = []
opmap = {}
ops = []
f = open('opcodes.h')
for line in f:
if is_opcode(line):
... |
BATCH_SIZE = 128
EPOCHS = 120
LR = 0.001
NGRAM = 10
NUM_CLASS = 20
EMBEDDING_DIM = 100
CUDA = True
DEVICE = 3
DEBUG = False
# FILENAME = '../bsnn/data/tor_erase_tls2.traffic'
FILENAME = '../bsnn/data/20_header_payload_all.traffic'
# LABELS ={'facebook': 0, 'yahoomail': 1, 'Youtube': 2, 'itunes': 3, 'mysql': 4, 'fi... | batch_size = 128
epochs = 120
lr = 0.001
ngram = 10
num_class = 20
embedding_dim = 100
cuda = True
device = 3
debug = False
filename = '../bsnn/data/20_header_payload_all.traffic'
labels = {'reddit': 0, 'facebook': 1, 'NeteaseMusic': 2, 'twitter': 3, 'qqmail': 4, 'instagram': 5, 'weibo': 6, 'iqiyi': 7, 'imdb': 8, 'TED'... |
def inputGrades(nm):
grades = []
for i in range(0,nm,1):
grade = float(input('Enter your Grade: '))
grades.append(grade)
return grades
def printGrades(nm,x):
for i in range(0,nm,1):
print(x[i])
def avgGrades(nm,x):
Sum = 0
for i in range(0,nm,1):
Sum = Sum + x[i... | def input_grades(nm):
grades = []
for i in range(0, nm, 1):
grade = float(input('Enter your Grade: '))
grades.append(grade)
return grades
def print_grades(nm, x):
for i in range(0, nm, 1):
print(x[i])
def avg_grades(nm, x):
sum = 0
for i in range(0, nm, 1):
sum ... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Created by Ross on 2019/8/21
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
dp = [0] * len(nums)
if len(nums) == 0:
return 0
dp[0] = 1
for i in range(1, len(nums)):
maxval = 0
for j in ... | class Solution:
def length_of_lis(self, nums: List[int]) -> int:
dp = [0] * len(nums)
if len(nums) == 0:
return 0
dp[0] = 1
for i in range(1, len(nums)):
maxval = 0
for j in range(0, i):
if nums[j] < nums[i]:
ma... |
class TransformationTypeEnum():
__DOUBLE_SIGMOID = "double_sigmoid"
__SIGMOID = "sigmoid"
__REVERSE_SIGMOID = "reverse_sigmoid"
__RIGHT_STEP = "right_step"
__LEFT_STEP = "left_step"
__STEP = "step"
__CUSTOM_INTERPOLATION = "custom_interpolation"
__NO_TRANSFORMATION = "no_transformation"... | class Transformationtypeenum:
__double_sigmoid = 'double_sigmoid'
__sigmoid = 'sigmoid'
__reverse_sigmoid = 'reverse_sigmoid'
__right_step = 'right_step'
__left_step = 'left_step'
__step = 'step'
__custom_interpolation = 'custom_interpolation'
__no_transformation = 'no_transformation'
... |
__author__ = 'yinjun'
"""
@see http://blog.csdn.net/u011095253/article/details/9248073
@see http://www.jiuzhang.com/solutions/interleaving-string/
"""
class Solution:
"""
@params s1, s2, s3: Three strings as description.
@return: return True if s3 is formed by the interleaving of
s1 and s2 or ... | __author__ = 'yinjun'
'\n@see http://blog.csdn.net/u011095253/article/details/9248073\n@see http://www.jiuzhang.com/solutions/interleaving-string/\n'
class Solution:
"""
@params s1, s2, s3: Three strings as description.
@return: return True if s3 is formed by the interleaving of
s1 and s2 or F... |
a = True # Creates a variable set to true
while a: # While this variable is true, loop. Used to handle for 2+ word inputs
inp = input('Enter ONE word: ') # Takes the users input
test = inp.split() # Makes the users input a list of each word, to check how many words are there
if len(test) == 1: # If thi... | a = True
while a:
inp = input('Enter ONE word: ')
test = inp.split()
if len(test) == 1:
a = False
print(inp[::-1])
else:
print('Your input was either 2 words, or nothing at all. Please try again :)') |
def main(request, response):
type = request.GET.first("type", None)
is_revalidation = request.headers.get("If-Modified-Since", None)
content = "/* nothing to see here */"
response.add_required_headers = False
if is_revalidation is not None:
response.writer.write_status(304)
response.wr... | def main(request, response):
type = request.GET.first('type', None)
is_revalidation = request.headers.get('If-Modified-Since', None)
content = '/* nothing to see here */'
response.add_required_headers = False
if is_revalidation is not None:
response.writer.write_status(304)
response.... |
def calcula_soma(A: int, B: int):
if (not isinstance(A, int) or not isinstance(B, int)):
raise TypeError
return f'SOMA = {A + B}'
| def calcula_soma(A: int, B: int):
if not isinstance(A, int) or not isinstance(B, int):
raise TypeError
return f'SOMA = {A + B}' |
# Flask config reference: http://flask.pocoo.org/docs/1.0/config/
# Flask-Sqlalchemy config reference: http://flask-sqlalchemy.pocoo.org/2.3/config/
POSTGRES_ENV_VARS_DEV = {
'user': 'postgres',
'pwd': '1qaz2wsx',
'host': 'jblin',
'port': '5432',
'db': 'postgres',
}
POSTGRES_ENV_VARS_PRD = {
#... | postgres_env_vars_dev = {'user': 'postgres', 'pwd': '1qaz2wsx', 'host': 'jblin', 'port': '5432', 'db': 'postgres'}
postgres_env_vars_prd = {}
class Baseconfig(object):
debug = False
testing = False
secret_key = '12qwaszx'
jsonify_mimetype = 'application/json'
sqlalchemy_database_uri = 'postgresql:/... |
def sort_address_results(addresses, postcode):
'''
# Not to be used. Address Index API should sort for us.
If required address object should include the following fields:
paoStartNumber = address['nag']['pao']['paoStartNumber']
saoStartNumber = address['nag']['sao']['saoStartNumber']
street_num... | def sort_address_results(addresses, postcode):
"""
# Not to be used. Address Index API should sort for us.
If required address object should include the following fields:
paoStartNumber = address['nag']['pao']['paoStartNumber']
saoStartNumber = address['nag']['sao']['saoStartNumber']
street_num... |
#!/usr/bin/env python3
# https://codeforces.com/problemset/problem/851/A
n,k,t = list(map(int,input().split()))
print(min(t,n+k-t,k))
| (n, k, t) = list(map(int, input().split()))
print(min(t, n + k - t, k)) |
# Ch02-FlowControl-while_break_continue_statements.py
# This is an example for while, break, continue statements.
#
# https://automatetheboringstuff.com/chapter2/
# Flow Control Statements: Lesson 6 - while Loops, break, and continue
#
# I changed the original code slightly.
count = 0
while True:
print('What is y... | count = 0
while True:
print('What is your name?')
name = input()
if name != 'Joe':
if count > 2:
print('Hint: The name should be Joe.')
count = count + 1
continue
print('Hi, Joe. What is the password?')
password = input()
if password == 'swordfish':
br... |
#!/bin/python3
# Complete the solve function below.
def solve(s):
words = s.split(' ')
for i in range(len(words)):
words[i] = words[i].capitalize()
return ' '.join(words)
if __name__ == '__main__':
s = input()
result = solve(s)
print(result)
| def solve(s):
words = s.split(' ')
for i in range(len(words)):
words[i] = words[i].capitalize()
return ' '.join(words)
if __name__ == '__main__':
s = input()
result = solve(s)
print(result) |
# Assignment 6
# Author: Jignesh Chaudhary, Student Id: 197320
# a) Heapsort: Implement the heapsort algorithm from your textbook (Algorithm 7.5) but modify it so it ends after finding z largest keys
# in non-increasing order. You can hardcode the keys to be integer type. Implement test program to provide unsorted i... | class Heap:
"""This class take array as a input and find z number of largest key in non-increasing order
class has method call siftdown, makeheap, removekey and display"""
def __init__(self, array, z):
"""Constructur which create unsorted array from input and take int z to find z number of largest ... |
def main(str1, str2):
m = len(str1)
n = len(str2)
j = 0
i = 0
while j < m and i < n:
if str1[j] == str2[i]:
j = j+1
i = i + 1
return j == m
str2 = str(input())
N = int(input())
for i in range(N):
str1 = str(input())
if main(str1, str2):
print("... | def main(str1, str2):
m = len(str1)
n = len(str2)
j = 0
i = 0
while j < m and i < n:
if str1[j] == str2[i]:
j = j + 1
i = i + 1
return j == m
str2 = str(input())
n = int(input())
for i in range(N):
str1 = str(input())
if main(str1, str2):
print('POSITI... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.