content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# fo =open("/disk/lulu/TCGA11.txt","w")
with open(r"/disk/lulu/TCGA1.txt","r") as TCGA:
temp=[]
cancerlist=[]
cancer =[]
for line in TCGA:
list = line.strip().split("\t")
temp = list[0]
cancerlist.append(temp)
cancer = sorted(set(cancerlist))
print (cancer)
... | with open('/disk/lulu/TCGA1.txt', 'r') as tcga:
temp = []
cancerlist = []
cancer = []
for line in TCGA:
list = line.strip().split('\t')
temp = list[0]
cancerlist.append(temp)
cancer = sorted(set(cancerlist))
print(cancer)
tcg_alist = []
for item in cancer:
... |
# https://www.hackerrank.com/challenges/strange-code/problem?utm_campaign=challenge-recommendation&utm_medium=email&utm_source=24-hour-campaign
starting = 3
index = 1
# time and value seperated by 2 min
time,value = [],[]
for i in range(1,40+1):
time.append(index) # time
value.append(starting) # value
inde... | starting = 3
index = 1
(time, value) = ([], [])
for i in range(1, 40 + 1):
time.append(index)
value.append(starting)
index = starting + index
starting *= 2
cycle = list(zip(time, value))
t = 213921847123
f = 0
for i in range(len(time)):
if (t < time[i]) is True and (t > time[i]) is False:
f ... |
#
# PySNMP MIB module HPN-ICF-EPON-DEVICE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-EPON-DEVICE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:38:33 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, value_size_constraint, constraints_intersection, single_value_constraint) ... |
# comprehensive solution
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
# https://leetcode.com/problems/jewels-and-stones/discuss/527360/Several-Python-solution.-w-Explanation
jewel = set(J)
return sum( 1 for item in S if item in jewel )
def numJewelsInStones(s... | class Solution:
def num_jewels_in_stones(self, J: str, S: str) -> int:
jewel = set(J)
return sum((1 for item in S if item in jewel))
def num_jewels_in_stones(self, J: str, S: str) -> int:
return sum((S.count(jewel) for jewel in J))
def num_jewels_in_stones(self, J: str, S: str) ->... |
TIEMPO_POR_INSTRUCCION = 15
TIEMPO_AVISO_NO_MOVIMIENTO = 10
constante_cambio_area = 1000 # constante de cambio de area, entre mayor sea el numero, mayor es el area a detectar para cambio, es decir el equivalente a la velocidad de movimiento
valor_cambio = 200 # Constante incremental para cambio de estado [Lavandose_... | tiempo_por_instruccion = 15
tiempo_aviso_no_movimiento = 10
constante_cambio_area = 1000
valor_cambio = 200
status_movimiento = ('MOVE', 'NO_MOVE')
tiempo_volver_lavar_manos = 60 |
# -*- coding=utf-8 -*-
# library: jionlp
# author: dongrixinyu
# license: Apache License 2.0
# Email: dongrixinyu.89@163.com
# github: https://github.com/dongrixinyu/JioNLP
# description: Preprocessing tool for Chinese NLP
def bracket(regular_expression):
return ''.join([r'(', regular_expression, r')'])
def bra... | def bracket(regular_expression):
return ''.join(['(', regular_expression, ')'])
def bracket_absence(regular_expression):
return ''.join(['(', regular_expression, ')?'])
def absence(regular_expression):
return ''.join([regular_expression, '?'])
def start_end(regular_expression):
return ''.join(['^', r... |
t = int(input())
s = "abcdefghijklmnopqrstuvwxyz"
for _ in range(t):
total = 0
l = list(map(int, input().split()))
string = input()
lst = list(set(s) - set(string))
for i in lst:
total += l[ord(i) - ord('a')]
print(total) | t = int(input())
s = 'abcdefghijklmnopqrstuvwxyz'
for _ in range(t):
total = 0
l = list(map(int, input().split()))
string = input()
lst = list(set(s) - set(string))
for i in lst:
total += l[ord(i) - ord('a')]
print(total) |
# Fury Incarnate
medal = 1142554
if sm.canHold(medal):
sm.chatScript("You obtained the <Fury Incarnate> medal.")
sm.startQuest(parentID)
sm.completeQuest(parentID) | medal = 1142554
if sm.canHold(medal):
sm.chatScript('You obtained the <Fury Incarnate> medal.')
sm.startQuest(parentID)
sm.completeQuest(parentID) |
#
# PySNMP MIB module WHISP-SM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WHISP-SM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:36:30 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, value_range_constraint, single_value_constraint, value_size_constraint) ... |
#
# PySNMP MIB module NETSCREEN-SERVICE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NETSCREEN-SERVICE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:20:18 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_intersection, value_size_constraint, constraints_union, value_range_constraint) ... |
#
# PySNMP MIB module DT1-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DT1-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:39:59 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_intersection, constraints_union, single_value_constraint, value_range_constraint) ... |
print(''' _____
.-" .-. "-.
_/ '=(0.0)=' \_
/` .='|m|'=. `\
\________________ /
.--.__///`'-,__~\\\\~`
/ /6|__\// a (__)-\\\\
\ \/--`(( ._\ ,)))
/ \\ ))\ -==- (O)(
/ )\((((\ . /)))))
/ _.' / __(`~~~~`)__
//"\... | print(' _____\n .-" .-. "-.\n _/ \'=(0.0)=\' \\_\n /` .=\'|m|\'=. ` \\________________ /\n .--.__///`\'-,__~\\\\~`\n / /6|__\\// a (__)-\\\\\n \\ \\/--`(( ._\\ ,)))\n / \\ ))\\ -==- (O)(\n / )\\((((\\ . /)))))\n / _.\' / ... |
'''
Created on Dec 20, 2016
@author: bardya
'''
# HOG_herit = [0,1,2]
#
# hogset = set()
#
# for i in HOG_herit:
# fh = open("/share/project/bardya/Enterobacteriaceae/OMA_prot/HOGLevel_Gains/{}".format(i), 'r')
# hogset |= set([line.strip() for line in fh if line.strip()])
# fh.close()
#
# fh2 = ... | """
Created on Dec 20, 2016
@author: bardya
"""
hog_herit = [0]
hogset = set()
fh = open('/share/project/bardya/Enterobacteriaceae/OMA_prot/HOGLevel_Gains/{}'.format(HOG_herit[0]), 'r')
hogset |= set([line.strip() for line in fh if line.strip()])
fh.close()
lca_set = []
for i in hogset:
i_sample = i.replace('.fa',... |
class FModifierEnvelopeControlPoint:
frame = None
max = None
min = None
| class Fmodifierenvelopecontrolpoint:
frame = None
max = None
min = None |
self.description = "Try to upgrade two packages which would break deps"
lp1 = pmpkg("pkg1")
lp1.depends = ["pkg2=1.0"]
self.addpkg2db("local", lp1)
lp2 = pmpkg("pkg2", "1.0-1")
self.addpkg2db("local", lp2)
p1 = pmpkg("pkg1", "1.1-1")
p1.depends = ["pkg2=1.0-1"]
self.addpkg(p1)
p2 = pmpkg("pkg2", "1.1-1")
self.addpk... | self.description = 'Try to upgrade two packages which would break deps'
lp1 = pmpkg('pkg1')
lp1.depends = ['pkg2=1.0']
self.addpkg2db('local', lp1)
lp2 = pmpkg('pkg2', '1.0-1')
self.addpkg2db('local', lp2)
p1 = pmpkg('pkg1', '1.1-1')
p1.depends = ['pkg2=1.0-1']
self.addpkg(p1)
p2 = pmpkg('pkg2', '1.1-1')
self.addpkg(p2... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Solution:
def insert(self, head, data):
p = Node(data)
if head == None:
head = p
elif head.next == None:
head.next = p
else:
start = head
... | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Solution:
def insert(self, head, data):
p = node(data)
if head == None:
head = p
elif head.next == None:
head.next = p
else:
start = head
... |
__version__ = "1.1.0"
'''
1.1.0
- Base demo module with version info
''' | __version__ = '1.1.0'
'\n1.1.0\n - Base demo module with version info \n' |
#
# PySNMP MIB module CISCOSB-EVENTS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-EVENTS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:06:29 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, value_size_constraint, single_value_constraint, constraints_intersection) ... |
# https://leetcode.com/problems/lru-cache/
class Node:
def __init__(self, key, value, nxt=None, prev=None):
self.key = key
self.value = value
self.next = nxt
self.prev = prev
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.map = d... | class Node:
def __init__(self, key, value, nxt=None, prev=None):
self.key = key
self.value = value
self.next = nxt
self.prev = prev
class Lrucache:
def __init__(self, capacity: int):
self.capacity = capacity
self.map = dict()
self.linked_list_head = nod... |
#memocate.py: The Trivial Memory Allocator in Python
#Disclaimer: Use this at your own discretion. I am not responsible for anything that happens.
#Author: TD
#initialization
a = "a"
mode = input("(0) Intensive or (1) Safe: ")
#Storing string to memory until overflow.
#Concatenating Runtime: O(n)
if(mode):
print("Saf... | a = 'a'
mode = input('(0) Intensive or (1) Safe: ')
if mode:
print('Safe Mode O(n)')
while 1:
a = a + 'a'
else:
print('Intensive Mode O(n^2)')
while 1:
a = a + a |
#
# @lc app=leetcode id=1275 lang=python3
#
# [1275] Find Winner on a Tic Tac Toe Game
#
# @lc code=start
class Solution:
def tictactoe(self, moves: list[list[int]]) -> str:
rows, cols, hill, dale, mark = [0, 0, 0], [0, 0, 0], 0, 0, 1
for i, j in moves:
rows[i] += mark
cols[... | class Solution:
def tictactoe(self, moves: list[list[int]]) -> str:
(rows, cols, hill, dale, mark) = ([0, 0, 0], [0, 0, 0], 0, 0, 1)
for (i, j) in moves:
rows[i] += mark
cols[j] += mark
hill += mark * (i == 2 - j)
dale += mark * (i == j)
i... |
'''
File: imports.py
Project: src
File Created: Sunday, 28th February 2021 3:10:35 am
Author: Sparsh Dutta (sparsh.dtt@gmail.com)
-----
Last Modified: Sunday, 28th February 2021 3:10:35 am
Modified By: Sparsh Dutta (sparsh.dtt@gmail.com>)
-----
Copyright 2021 Sparsh Dutta
'''
| """
File: imports.py
Project: src
File Created: Sunday, 28th February 2021 3:10:35 am
Author: Sparsh Dutta (sparsh.dtt@gmail.com)
-----
Last Modified: Sunday, 28th February 2021 3:10:35 am
Modified By: Sparsh Dutta (sparsh.dtt@gmail.com>)
-----
Copyright 2021 Sparsh Dutta
""" |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def geometric_mid(*args):
if args:
ans = 1
for item in args:
ans *= item
return pow(ans, 1/len(args))
else:
return None
if __name__ == "__main__":
print(geometric_mid())
print(geometric_mid(5, ... | def geometric_mid(*args):
if args:
ans = 1
for item in args:
ans *= item
return pow(ans, 1 / len(args))
else:
return None
if __name__ == '__main__':
print(geometric_mid())
print(geometric_mid(5, 4, 2, 8, 9))
print(geometric_mid(3, 7, 4, 9, 4, 5)) |
# Compute mean of combined data set: combined_mean
combined_mean = np.mean(np.concatenate((bd_1975, bd_2012)))
# Shift the samples
bd_1975_shifted = bd_1975 - np.mean(bd_1975) + combined_mean
bd_2012_shifted = bd_2012 - np.mean(bd_2012) + combined_mean
# Get bootstrap replicates of shifted data sets
bs_replicates_197... | combined_mean = np.mean(np.concatenate((bd_1975, bd_2012)))
bd_1975_shifted = bd_1975 - np.mean(bd_1975) + combined_mean
bd_2012_shifted = bd_2012 - np.mean(bd_2012) + combined_mean
bs_replicates_1975 = draw_bs_reps(bd_1975_shifted, np.mean, 10000)
bs_replicates_2012 = draw_bs_reps(bd_2012_shifted, np.mean, 10000)
bs_d... |
__author__ = "Max Dippel, Michael Burkart and Matthias Urban"
__version__ = "0.0.1"
__license__ = "BSD"
CSConfig = dict()
# SchedulerStepLR
step_lr = dict()
step_lr['step_size'] = (1, 10)
step_lr['gamma'] = (0.001, 0.9)
CSConfig['step_lr'] = step_lr
# SchedulerExponentialLR
exponential_lr = dict()
exponential_lr['ga... | __author__ = 'Max Dippel, Michael Burkart and Matthias Urban'
__version__ = '0.0.1'
__license__ = 'BSD'
cs_config = dict()
step_lr = dict()
step_lr['step_size'] = (1, 10)
step_lr['gamma'] = (0.001, 0.9)
CSConfig['step_lr'] = step_lr
exponential_lr = dict()
exponential_lr['gamma'] = (0.8, 0.9999)
CSConfig['exponential_l... |
# [8 kyu] Double Char
#
# Author: Hsins
# Date: 2019/11/28
def two_sort(array):
word = sorted(array)[0]
return "".join(c + '***' for c in word)[0:-3]
| def two_sort(array):
word = sorted(array)[0]
return ''.join((c + '***' for c in word))[0:-3] |
def func(x,y):
if(y == 0):
return 0
else:
print(x,y)
return x + func(x,y-1)
func(10,10)
| def func(x, y):
if y == 0:
return 0
else:
print(x, y)
return x + func(x, y - 1)
func(10, 10) |
class Params:
# the most important parameter
random_seed = 224422
# system params
verbose = True
device = None # to be set on runtime
num_workers = 2
# dataset params
datasets_dir = 'datasets'
dataset = 'churches'
train_suffix = 'train'
valid_suffix = 'val'
flip = True... | class Params:
random_seed = 224422
verbose = True
device = None
num_workers = 2
datasets_dir = 'datasets'
dataset = 'churches'
train_suffix = 'train'
valid_suffix = 'val'
flip = True
normalize = True
image_size = (512, 1024)
input_left = True
in_channels = 3
out_c... |
#
# Example file for working with functions
#
# define a basic function
def func1():
print ("I am a function")
# function that takes arguments
def func2(arg1, arg2):
print (arg1, " ", arg2)
# function that returns a value
def cube(x):
return x*x*x
# function with default value for an argument
def power(num, x... | def func1():
print('I am a function')
def func2(arg1, arg2):
print(arg1, ' ', arg2)
def cube(x):
return x * x * x
def power(num, x=1):
result = 1
for i in range(x):
result = result * num
return result
def multi_add(*args):
result = 0
for x in args:
result = result + x... |
name = input("Enter lenght of name: ")
if len(name) < 3:
print("name must be at least 3 characters")
elif len(name) > 50:
print("name can be a maximum of 50 characters")
else:
print("name looks good!")
| name = input('Enter lenght of name: ')
if len(name) < 3:
print('name must be at least 3 characters')
elif len(name) > 50:
print('name can be a maximum of 50 characters')
else:
print('name looks good!') |
# File: Lists_inside_Dictionary_in_Python.py
# Description: Calculating the scores of sports team by using Lists inside Dictionary
# Environment: PyCharm and Anaconda environment
#
# MIT License
# Copyright (c) 2018 Valentyn N Sichkar
# github.com/sichkar-valentyn
# Reference to:
# [1] Valentyn N Sichkar. Lists... | n = int(input())
string = ''
d = {}
for i in range(n):
string = input().split(';')
if string[0] not in d:
d[string[0]] = [1, 0, 0, 0, 0]
else:
d[string[0]][0] += 1
if string[2] not in d:
d[string[2]] = [1, 0, 0, 0, 0]
else:
d[string[2]][0] += 1
if int(string[1]) >... |
my_list = [1, 2, 3, 4, 5, 6, 7, 8]
def filter_iter(list, pred):
filtered = []
for i in list:
if pred(i):
filtered.append(i)
return filtered
def filter_beautiful(list, pred):
return [x for x in list if pred(x)]
def even(x):
return x % 2 == 0
print(filter_iter(my_list, even))
print(filter_beautiful(my_lis... | my_list = [1, 2, 3, 4, 5, 6, 7, 8]
def filter_iter(list, pred):
filtered = []
for i in list:
if pred(i):
filtered.append(i)
return filtered
def filter_beautiful(list, pred):
return [x for x in list if pred(x)]
def even(x):
return x % 2 == 0
print(filter_iter(my_list, even))
pr... |
title=xpath("div[@class=BlogTitle]")
urls="http://my\\.oschina\\.net/flashsword/blog/\\d+"
result={"title":title,"urls":urls}
| title = xpath('div[@class=BlogTitle]')
urls = 'http://my\\.oschina\\.net/flashsword/blog/\\d+'
result = {'title': title, 'urls': urls} |
print("nihao,shijie")
print("lalalalal")
print("ninniiiinnij")
| print('nihao,shijie')
print('lalalalal')
print('ninniiiinnij') |
for _ in range(int(input())):
n=int(input())
nums=list(map(int, input().split()))
ini=10**5
for i in range(n):
if ini>nums[i]:
ini=nums[i]
res=i
print(res+1)
| for _ in range(int(input())):
n = int(input())
nums = list(map(int, input().split()))
ini = 10 ** 5
for i in range(n):
if ini > nums[i]:
ini = nums[i]
res = i
print(res + 1) |
#
# Copyright (C) 2018 SecurityCentral Contributors see LICENSE for license
#
'''
This base platform module exports platform dependant constants.
'''
class SecurityCentralPlatformBaseConstants(object):
pass
| """
This base platform module exports platform dependant constants.
"""
class Securitycentralplatformbaseconstants(object):
pass |
expected_output = {
'Et0/2:12': {
'type': 'BD_PORT',
'is_path_list': False,
'port': 'Et0/2:12'
},
'[IR]20012:2.2.2.2': {
'type':'VXLAN_REP',
'is_path_list': True,
'path_list': {
'id': 1191,
'path_count': 1,
'type': 'VXLAN_RE... | expected_output = {'Et0/2:12': {'type': 'BD_PORT', 'is_path_list': False, 'port': 'Et0/2:12'}, '[IR]20012:2.2.2.2': {'type': 'VXLAN_REP', 'is_path_list': True, 'path_list': {'id': 1191, 'path_count': 1, 'type': 'VXLAN_REP', 'description': '[IR]20012:2.2.2.2'}}, '[IR]20012:3.3.3.2': {'type': 'VXLAN_REP', 'is_path_list':... |
#!/usr/bin/env python
# -*- coding: utf-8; -*-
# Copyright (c) 2020, 2022 Oracle and/or its affiliates.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
class Timeseries:
def __init__(self, col_name, df, date_range=None, min=None, max=None):
self.co... | class Timeseries:
def __init__(self, col_name, df, date_range=None, min=None, max=None):
self.col_name = col_name
self.df = df
self.date_range = date_range
self.min = min
self.max = max
def plot(self, **kwargs):
pass |
nums = input('Please enter 5 numbers, separated by commas:\n')
nums1 = nums.split(',')
#print('You entered ' + nums1[0] + ', ' + nums1[1] + ', ' + nums1[2] + ', ' + nums1[3] + ', ' + nums1[4] + ', ' )
print('You entered ' + nums1[0] + ', ' + nums1[1] + ', ' + nums1[2] + ', ' + nums1[3] + ', ' + nums1[4] +'.')
nums1[... | nums = input('Please enter 5 numbers, separated by commas:\n')
nums1 = nums.split(',')
print('You entered ' + nums1[0] + ', ' + nums1[1] + ', ' + nums1[2] + ', ' + nums1[3] + ', ' + nums1[4] + '.')
nums1[0] = int(nums1[0])
nums1[1] = int(nums1[1])
nums1[2] = int(nums1[2])
nums1[3] = int(nums1[3])
nums1[4] = int(nums1[4... |
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | class Vmwaretagactions(object):
def __init__(self, session, url_base):
self.session = session
self.url_base = url_base
def make_url(self, endpoint):
return self.url_base + endpoint
def get(self, endpoint):
url = self.make_url(endpoint)
response = self.session.get(u... |
class Solution:
def countBits(self, n: int) -> list[int]:
res = []
for i in range(n + 1):
res.append(bin(i).count("1"))
return res
class Solution:
def countBits(self, n: int) -> list[int]:
res = [0] * (n + 1)
for x in range(1, n + 1):
res[x] = re... | class Solution:
def count_bits(self, n: int) -> list[int]:
res = []
for i in range(n + 1):
res.append(bin(i).count('1'))
return res
class Solution:
def count_bits(self, n: int) -> list[int]:
res = [0] * (n + 1)
for x in range(1, n + 1):
res[x] =... |
R1_info = {
'device_type': 'cisco_ios',
'ip': '192.168.1.1',
'username': 'user',
'password': 'pass',
}
R2_info = {
'device_type': 'cisco_ios',
'ip': '192.168.1.2',
'username': 'user',
'password': 'pass',
}
R3_info = {
'device_type': 'cisco_ios',
'ip': '1... | r1_info = {'device_type': 'cisco_ios', 'ip': '192.168.1.1', 'username': 'user', 'password': 'pass'}
r2_info = {'device_type': 'cisco_ios', 'ip': '192.168.1.2', 'username': 'user', 'password': 'pass'}
r3_info = {'device_type': 'cisco_ios', 'ip': '192.168.1.3', 'username': 'user', 'password': 'pass'}
r4_info = {'device_t... |
'''
Created on 10/02/2012
@author: Alumno
'''
def suma(x, y):
return x+y
def multiplica(x, y):
return x*y
def cuadrado(x):
return x*x | """
Created on 10/02/2012
@author: Alumno
"""
def suma(x, y):
return x + y
def multiplica(x, y):
return x * y
def cuadrado(x):
return x * x |
#!/usr/bin/env python3
#https://codeforces.com/problemset/problem/1029/B
n = int(input())
al = list(map(int,input().split()))
cnt = 1
mxc = 0
for i in range(n-1):
if al[i+1]-al[i] <= al[i]:
cnt += 1
else:
if cnt>mxc:
mxc = cnt
cnt = 1
print(max(mxc,cnt))
| n = int(input())
al = list(map(int, input().split()))
cnt = 1
mxc = 0
for i in range(n - 1):
if al[i + 1] - al[i] <= al[i]:
cnt += 1
else:
if cnt > mxc:
mxc = cnt
cnt = 1
print(max(mxc, cnt)) |
def solve_knapsack(profits, weights, capacity):
if profits is None \
or weights is None \
or len(profits) == 0 \
or len(profits) != len(weights):
return 0
return unbounded_knapsack(profits, weights, capacity, 0)
# We are trying to find the maximum profit
def unboun... | def solve_knapsack(profits, weights, capacity):
if profits is None or weights is None or len(profits) == 0 or (len(profits) != len(weights)):
return 0
return unbounded_knapsack(profits, weights, capacity, 0)
def unbounded_knapsack(profits, weights, capacity, curr_index):
n = len(profits)
if cap... |
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
paths = [[1] * n for _ in range(m)]
for row in range(1, m):
for col in range(1, n):
paths[row][col] = paths[row-1][col] + paths[row][col-1]
return paths[m-1][n-1] | class Solution:
def unique_paths(self, m: int, n: int) -> int:
paths = [[1] * n for _ in range(m)]
for row in range(1, m):
for col in range(1, n):
paths[row][col] = paths[row - 1][col] + paths[row][col - 1]
return paths[m - 1][n - 1] |
# The search the 2D array for the target element where array is sorted from
# left to right and top to bottom
def search_2D_array(arr,x):
row = 0
col = len(arr[0]) - 1
while row < len(arr) and col >= 0:
if arr[col][row] == x:
return True
elif arr[row][col] < x:
row... | def search_2_d_array(arr, x):
row = 0
col = len(arr[0]) - 1
while row < len(arr) and col >= 0:
if arr[col][row] == x:
return True
elif arr[row][col] < x:
row += 1
else:
col -= 1
return False
if __name__ == '__main__':
arr = [[10, 20, 30, 40... |
n, k = map(int, input().split())
a = list(map(int, input().split()))
fre = [0] * (10 ** 5 + 5)
unique = 0
j = 0
for i in range(n):
if fre[a[i]] == 0:
unique += 1
fre[a[i]] += 1
while unique == k:
fre[a[j]] -= 1
if fre[a[j]] == 0:
print(j + 1, i + 1)
... | (n, k) = map(int, input().split())
a = list(map(int, input().split()))
fre = [0] * (10 ** 5 + 5)
unique = 0
j = 0
for i in range(n):
if fre[a[i]] == 0:
unique += 1
fre[a[i]] += 1
while unique == k:
fre[a[j]] -= 1
if fre[a[j]] == 0:
print(j + 1, i + 1)
exit()
... |
n = int(input())
spaces = 2*(n-1)
for i in range(1, n+1):
print(" "*spaces, end="")
if i == 1:
print("1")
else:
for j in range(i, 2*i):
print(str(j) + " ", end="")
for j in range(2*i-2, i-1, -1 ):
print(str(j) + " ", end="")
print()
spaces -= 2 | n = int(input())
spaces = 2 * (n - 1)
for i in range(1, n + 1):
print(' ' * spaces, end='')
if i == 1:
print('1')
else:
for j in range(i, 2 * i):
print(str(j) + ' ', end='')
for j in range(2 * i - 2, i - 1, -1):
print(str(j) + ' ', end='')
print()
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2016-12-22 10:42:23
# @Author : Jan Yang
# @Software : Sublime Text
class Email:
def __init__(self):
pass
| class Email:
def __init__(self):
pass |
# Perulangan pada string
print('=====Perulangan Pada String=====')
teks = 'helloworld'
print('teks =',teks)
hitung = 0
for i in range(len(teks)):
if 'l' == teks[i]:
hitung = hitung + 1
print('jumlah l pada teks',teks,'adalah',hitung) | print('=====Perulangan Pada String=====')
teks = 'helloworld'
print('teks =', teks)
hitung = 0
for i in range(len(teks)):
if 'l' == teks[i]:
hitung = hitung + 1
print('jumlah l pada teks', teks, 'adalah', hitung) |
h, m = 100, 200
h_deg, m_deg = h//2, m//3
# In Python3, // rounds down to the nearest whole number
angle = abs(h_deg - m_deg)
if angle > 180:
angle = 360 - angle
print(int(angle))
| (h, m) = (100, 200)
(h_deg, m_deg) = (h // 2, m // 3)
angle = abs(h_deg - m_deg)
if angle > 180:
angle = 360 - angle
print(int(angle)) |
# Gregary C. Zweigle
# 2020
MAX_PIANO_NOTE = 88
# TODO - Should this move elsewhere?
class FileName:
def __init__(self):
self.note_number = 0
self.file_name_l = 'EMPTY_L'
self.file_name_r = 'EMPTY_R'
def initialize_file_name(self, record_start_note):
self.note_n... | max_piano_note = 88
class Filename:
def __init__(self):
self.note_number = 0
self.file_name_l = 'EMPTY_L'
self.file_name_r = 'EMPTY_R'
def initialize_file_name(self, record_start_note):
self.note_number = int(float(record_start_note))
self.file_name_l = 'noteL' + str(s... |
n = int(input())
s = list(map(int, input().split()))
c = [0] * 10010
res, count = 0, 0
for i in s:
c[i] += 1
if c[i] > count:
res = i
count = c[i]
elif c[i] == count:
res = min(res, i)
print(res)
| n = int(input())
s = list(map(int, input().split()))
c = [0] * 10010
(res, count) = (0, 0)
for i in s:
c[i] += 1
if c[i] > count:
res = i
count = c[i]
elif c[i] == count:
res = min(res, i)
print(res) |
class ApiError(Exception):
pass
class AuthorizationFailed(Exception):
pass
| class Apierror(Exception):
pass
class Authorizationfailed(Exception):
pass |
s = 'one two one two one'
print(s.replace('one', 'two').replace('two', 'one'))
# one one one one one
print(s.replace('one', 'X').replace('two', 'one').replace('X', 'two'))
# two one two one two
def swap_str(s_org, s1, s2, temp='*q@w-e~r^'):
return s_org.replace(s1, temp).replace(s2, s1).replace(temp, s2)
print(... | s = 'one two one two one'
print(s.replace('one', 'two').replace('two', 'one'))
print(s.replace('one', 'X').replace('two', 'one').replace('X', 'two'))
def swap_str(s_org, s1, s2, temp='*q@w-e~r^'):
return s_org.replace(s1, temp).replace(s2, s1).replace(temp, s2)
print(swap_str(s, 'one', 'two'))
print(s.replace('o',... |
# TODO: create functions for data sending
async def send_data(event, buttons):
pass
| async def send_data(event, buttons):
pass |
n = int(input())
s = set(map(int, input().split()))
for i in range(int(input())):
c = input().split()
if c[0] == "update":
s.update(set(map(int, input().split())))
elif c[0] == "intersection_update":
s.intersection_update(set(map(int, input().split())))
elif c[0] == "difference_update":... | n = int(input())
s = set(map(int, input().split()))
for i in range(int(input())):
c = input().split()
if c[0] == 'update':
s.update(set(map(int, input().split())))
elif c[0] == 'intersection_update':
s.intersection_update(set(map(int, input().split())))
elif c[0] == 'difference_update':
... |
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def right_view_util(root, max_level, level):
if not root:
return
if max_level[0] < level:
print(root.val)
max_level[0] = level
right_view_util(r... | class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def right_view_util(root, max_level, level):
if not root:
return
if max_level[0] < level:
print(root.val)
max_level[0] = level
right_view_util(root.right, max_level, l... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# # https://oj.leetcode.com/problems/symmetric-tree
# Given a binary tree, check whether it is a mirror of itself
# (ie, symmetric around its center).
# For example, this binary tree is symmetric:
# 1
# / \
# 2 2
# / \ / \
# 3 4 4 3
#
# But the following ... | class Solution(object):
def is_symmetric(self, root):
def is_sym(L, R):
if not L and (not R):
return True
if L and R and (L.val == R.val):
return is_sym(L.left, R.right) and is_sym(L.right, R.left)
return False
return is_sym(root,... |
# These regexes must not include line anchors ('^', '$'). Those will be added by the
# ValidateRegex library function and anybody else who needs them.
NAME_VALIDATION = r"(?P<name>[@\-\w\.]+)"
# This regex needs to exactly match the above, EXCEPT that the name should be "name2". So if the
# above regex changes, chang... | name_validation = '(?P<name>[@\\-\\w\\.]+)'
name2_validation = '(?P<name2>[@\\-\\w\\.]+)'
permission_validation = '(?P<name>(?:[a-z0-9]+[_\\-\\.])*[a-z0-9]+)'
permission_wildcard_validation = '(?P<name>(?:[a-z0-9]+[_\\-\\.])*[a-z0-9]+(?:\\.\\*)?)'
argument_validation = '(?P<argument>|\\*|[\\w=+/.:-]+\\*?)'
permission_g... |
def check(n):
sqlist = str(n**2)# list(map(int,str(n**2)))
l = len(sqlist)
if l%2 == 0: #if even
rsq = int(sqlist[l//2:])
lsq = int(sqlist[:l//2])
else:
rsq = int(sqlist[(l-1)//2:])
if l!= 1:
lsq = int(sqlist[:(l-1)//2])
else:
lsq = 0 #only lsq can have an empty list
if rsq + lsq == ... | def check(n):
sqlist = str(n ** 2)
l = len(sqlist)
if l % 2 == 0:
rsq = int(sqlist[l // 2:])
lsq = int(sqlist[:l // 2])
else:
rsq = int(sqlist[(l - 1) // 2:])
if l != 1:
lsq = int(sqlist[:(l - 1) // 2])
else:
lsq = 0
if rsq + lsq == n:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
AUTHOR = 'Ben Poile'
SITENAME = 'blog'
SITEURL = 'https://poiley.github.io'
# GITHUB_URL = 'https://github.com/poiley/poiley.github.io'
PATH = 'content'
OUTPUT_PATH = 'output'
STATIC_PATHS = ['articles', 'downloads']
ARTICLE_PATHS = ['articles',]
ARTICLE_URL = 'artic... | author = 'Ben Poile'
sitename = 'blog'
siteurl = 'https://poiley.github.io'
path = 'content'
output_path = 'output'
static_paths = ['articles', 'downloads']
article_paths = ['articles']
article_url = 'articles/{date:%Y}/{date:%m}/{slug}.html'
article_save_as = 'articles/{date:%Y}/{date:%m}/{slug}.html'
timezone = 'Amer... |
class SomethingAbstract:
property_a: str
property_b: str
property_c: Optional[str]
property_d: Optional[str]
def __init__(
self,
property_a: str,
property_b: str,
property_c: Optional[str] = None,
property_d: Optional[str] = None,
) -> None:
self... | class Somethingabstract:
property_a: str
property_b: str
property_c: Optional[str]
property_d: Optional[str]
def __init__(self, property_a: str, property_b: str, property_c: Optional[str]=None, property_d: Optional[str]=None) -> None:
self.property_a = property_a
self.property_b = p... |
text = open("subInfo.txt").read()
def findCount(sub):
count = 0
terms = open(sub).readlines()
terms = [t.strip().lower() for t in terms]
for t in terms:
if t in text:
count += 1
return count
subArr = []
subArr.append((findCount("biology_terms.txt"), "biology_ter... | text = open('subInfo.txt').read()
def find_count(sub):
count = 0
terms = open(sub).readlines()
terms = [t.strip().lower() for t in terms]
for t in terms:
if t in text:
count += 1
return count
sub_arr = []
subArr.append((find_count('biology_terms.txt'), 'biology_terms.txt'))
subA... |
class eAxes:
xAxis, yAxis, zAxis = range(3)
class eTurn:
learner, simulator = range(2)
class eEPA:
evaluation, potency, activity = range(3)
evaluationSelf, potencySelf, activitySelf,\
evaluationAction, potencyAction, activityAction,\
evaluationOther, potencyOther, activityOther = range(9)
... | class Eaxes:
(x_axis, y_axis, z_axis) = range(3)
class Eturn:
(learner, simulator) = range(2)
class Eepa:
(evaluation, potency, activity) = range(3)
(evaluation_self, potency_self, activity_self, evaluation_action, potency_action, activity_action, evaluation_other, potency_other, activity_other) = ran... |
cars=["Maruthi","Honda","TataIndica"]
x = cars[0]
print("x=\n",x)
cars[0]="Ford"
print("cars=\n",cars)
L = len(cars)
print("Length of cars=",L)
#Print each item in the car array
for y in cars:
print(y)
cars.append("BMW")
print("cars=\n",cars)
#Delete the second element of the cars array
cars.pop(1)
... | cars = ['Maruthi', 'Honda', 'TataIndica']
x = cars[0]
print('x=\n', x)
cars[0] = 'Ford'
print('cars=\n', cars)
l = len(cars)
print('Length of cars=', L)
for y in cars:
print(y)
cars.append('BMW')
print('cars=\n', cars)
cars.pop(1)
print('cars=\n', cars)
cars.remove('TataIndica')
print('cars=\n', cars) |
guests = ["Mark", "Kevin", "Mellisa"]
msg = "I'd like to invite you to have a dinner with us on 5/18. Thanks, Andrew"
print(f"Hi {guests[0]}, {msg}")
print(f"Hi {guests[1]}, {msg}")
print(f"Hi {guests[2]}, {msg}")
print(f"\nSorry, {guests[1]} can't make it.\n")
guests[1] = "Ace"
print(f"Hi {guests[0]}, {msg}")
print(... | guests = ['Mark', 'Kevin', 'Mellisa']
msg = "I'd like to invite you to have a dinner with us on 5/18. Thanks, Andrew"
print(f'Hi {guests[0]}, {msg}')
print(f'Hi {guests[1]}, {msg}')
print(f'Hi {guests[2]}, {msg}')
print(f"\nSorry, {guests[1]} can't make it.\n")
guests[1] = 'Ace'
print(f'Hi {guests[0]}, {msg}')
print(f'... |
# Problem Set 1a
# Name: Eloi Gil
# Time Spent: 1
#
balance = float(input('balance: '))
annualInterestRate = float(input('annual interest rate: '))
minMonthlyPaymentRate = float(input('minimum monthly payment rate: '))
month = 0.0
while month < 12.0:
month += 1.0
print('Month ' + str(month))
minMonthlyPay... | balance = float(input('balance: '))
annual_interest_rate = float(input('annual interest rate: '))
min_monthly_payment_rate = float(input('minimum monthly payment rate: '))
month = 0.0
while month < 12.0:
month += 1.0
print('Month ' + str(month))
min_monthly_payment = round(balance * minMonthlyPaymentRate, 2... |
s=0
for c in range(0,4):
n= int(input('Digite um valor: '))
s += n
print('Somatorio deu: {}' .format(s)) | s = 0
for c in range(0, 4):
n = int(input('Digite um valor: '))
s += n
print('Somatorio deu: {}'.format(s)) |
__title__ = 'DRF Exception Handler'
__version__ = '1.0.1'
__author__ = 'Thomas'
__license__ = 'MIT'
__copyright__ = 'Copyright 2021 Thomas'
# Version synonym
VERSION = __version__
| __title__ = 'DRF Exception Handler'
__version__ = '1.0.1'
__author__ = 'Thomas'
__license__ = 'MIT'
__copyright__ = 'Copyright 2021 Thomas'
version = __version__ |
{
"targets": [
{
"target_name": "boost-property_tree",
"type": "none",
"include_dirs": [
"1.57.0/property_tree-boost-1.57.0/include"
],
"all_dependent_settings": {
"include_dirs": [
"1.57.0/proper... | {'targets': [{'target_name': 'boost-property_tree', 'type': 'none', 'include_dirs': ['1.57.0/property_tree-boost-1.57.0/include'], 'all_dependent_settings': {'include_dirs': ['1.57.0/property_tree-boost-1.57.0/include']}, 'dependencies': ['../boost-config/boost-config.gyp:*', '../boost-serialization/boost-serialization... |
def between_markers(text,mark1,mark2):
'''
You are given a string and two markers (the initial one and final). You have to find a substring enclosed between these two markers. But there are a few important conditions.
This is a simplified version of the Between Markers mission.
The initial and final markers a... | def between_markers(text, mark1, mark2):
"""
You are given a string and two markers (the initial one and final). You have to find a substring enclosed between these two markers. But there are a few important conditions.
This is a simplified version of the Between Markers mission.
The initial and final markers... |
# Copyright (C) 2017 Tiancheng Zhao, Carnegie Mellon University
class KgCVAEConfig(object):
description= None
use_hcf = True # use dialog act in training (if turn off kgCVAE -> CVAE)
update_limit = 3000 # the number of mini-batch before evaluating the model
# how to encode utterance.
# bow: ... | class Kgcvaeconfig(object):
description = None
use_hcf = True
update_limit = 3000
sent_type = 'bi_rnn'
latent_size = 200
full_kl_step = 10000
dec_keep_prob = 1.0
cell_type = 'gru'
embed_size = 200
topic_embed_size = 30
da_embed_size = 30
cxt_cell_size = 600
sent_cell_... |
# Cast to int
x = int(100) # x will be 100
y = int(5.75) # y will be 5
z = int("32") # z will be 32
print(x)
print(y)
print(z)
print(type(x))
print(type(y))
print(type(z))
# cast to float
a = float(100) # x will be 100.0
b = float(5.75) # y will be 5.75
c = float("32") # z will be 32.0
d = float(... | x = int(100)
y = int(5.75)
z = int('32')
print(x)
print(y)
print(z)
print(type(x))
print(type(y))
print(type(z))
a = float(100)
b = float(5.75)
c = float('32')
d = float('32.5')
print(a)
print(b)
print(c)
print(d)
print(type(a))
print(type(b))
print(type(c))
print(type(d))
s1 = str('s1')
s2 = str(100)
s3 = str(5.75)
pr... |
class MetadataHolder():
def set_metadata(self, key, value):
self.client.api.call_function('set_metadata', {
'entity_type': self._data['type'],
'entity_id': self.id,
'key': key,
'value': value
})
def set_metadata_dict(self, metadata_dict):
... | class Metadataholder:
def set_metadata(self, key, value):
self.client.api.call_function('set_metadata', {'entity_type': self._data['type'], 'entity_id': self.id, 'key': key, 'value': value})
def set_metadata_dict(self, metadata_dict):
self.client.api.call_function('set_metadata_dict', {'entity... |
'''
Given an array of unique integers preorder, return true if it is the correct preorder traversal sequence of a binary search tree.
Example 1:
Input: preorder = [5,2,1,3,6]
Output: true
Example 2:
Input: preorder = [5,2,6,1,3]
Output: false
'''
# Convert to Inorder and check if sorted or not
# TC O(N) and Space O... | """
Given an array of unique integers preorder, return true if it is the correct preorder traversal sequence of a binary search tree.
Example 1:
Input: preorder = [5,2,1,3,6]
Output: true
Example 2:
Input: preorder = [5,2,6,1,3]
Output: false
"""
class Solution(object):
def to_inorder(self, preorder):
s... |
'''
You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], return true if and only if all the given nodes form exactly one valid binary tree.
If node i has no left child then leftChild[i] will equal -1, similarly for the right child.
Note that the nodes hav... | """
You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], return true if and only if all the given nodes form exactly one valid binary tree.
If node i has no left child then leftChild[i] will equal -1, similarly for the right child.
Note that the nodes hav... |
# Nesse exemplo retorna uma lista ordenada
lista = [1,5,3,2,7,50,9]
def bubbleSort(list):
for i in range(len(list)):
for j in range(0, len(list) - 1 - i):
if (list[j] > list[j+1]):
temp = list[j]
list[j] = list[j+1]
list[j+1] = temp
return l... | lista = [1, 5, 3, 2, 7, 50, 9]
def bubble_sort(list):
for i in range(len(list)):
for j in range(0, len(list) - 1 - i):
if list[j] > list[j + 1]:
temp = list[j]
list[j] = list[j + 1]
list[j + 1] = temp
return list
if __name__ == '__main__':
... |
# General settings
HOST = "irc.twitch.tv"
PORT = 6667
COOLDOWN = 10 #Global cooldown for commands (in seconds)
# Bot account settings
PASS = "oauth:abcabcabcabcabcabcacb1231231231"
IDENT = "bot_username"
# Channel owner settings
CHANNEL = "channel_owner_username" #The username of your Twitch account (lowerc... | host = 'irc.twitch.tv'
port = 6667
cooldown = 10
pass = 'oauth:abcabcabcabcabcabcacb1231231231'
ident = 'bot_username'
channel = 'channel_owner_username'
channelpass = 'oauth:abcabcbaacbacbabcbac123456789'
games = [['Sample Game', 'sg', 'Sample Platform', 'sp64'], ['Sample Game 2', 'sg2', 'Sample Platform', 'sp64']]
ca... |
__author__ = 'shukkkur'
'''
https://codeforces.com/problemset/problem/1399/A
A. Remove Smallest
Couldn't Solve it myself, answer borrowed.
'''
for _ in range(int(input())):
n = int(input())
a = set(map(int, input().split()))
print('YES' if max(a)-min(a) < len(a) else 'NO')
| __author__ = 'shukkkur'
"\nhttps://codeforces.com/problemset/problem/1399/A\nA. Remove Smallest\nCouldn't Solve it myself, answer borrowed.\n"
for _ in range(int(input())):
n = int(input())
a = set(map(int, input().split()))
print('YES' if max(a) - min(a) < len(a) else 'NO') |
N, *a = map(int, open(0).read().split())
i, j = 0, 0
c = 0
result = 0
while j < N:
if c <= N:
c += a[j]
j += 1
else:
c -= a[i]
i += 1
if c == N:
result += 1
while i < N:
c -= a[i]
i += 1
if c == N:
result += 1
print(result)
| (n, *a) = map(int, open(0).read().split())
(i, j) = (0, 0)
c = 0
result = 0
while j < N:
if c <= N:
c += a[j]
j += 1
else:
c -= a[i]
i += 1
if c == N:
result += 1
while i < N:
c -= a[i]
i += 1
if c == N:
result += 1
print(result) |
# test using cpu only
cpu = False
# type of network to be trained, can be bnn, full-bnn, qnn, full-qnn, tnn, full-tnn
network_type = 'full-qnn'
# bits can be None, 2, 4, 8 , whatever
bits=None
wbits = 4
abits = 4
# finetune an be false or true
finetune = False
architecture = 'RESNET'
# architecture = 'VGG'
dataset='C... | cpu = False
network_type = 'full-qnn'
bits = None
wbits = 4
abits = 4
finetune = False
architecture = 'RESNET'
dataset = 'CIFAR-10'
if dataset == 'CIFAR-10':
dim = 32
channels = 3
else:
dim = 28
channels = 1
classes = 10
data_augmentation = True
kernel_regularizer = 0.0
kernel_initializer = 'glorot_unif... |
# JIG code from Stand-up Maths video "Why don't Jigsaw Puzzles have the correct number of pieces?"
def low_factors(n):
# all the factors which are the lower half of each factor pair
lf = []
for i in range(1, int(n**0.5)+1):
if n % i == 0:
lf.append(i)
return lf
def jig(w,h,n,b=0):... | def low_factors(n):
lf = []
for i in range(1, int(n ** 0.5) + 1):
if n % i == 0:
lf.append(i)
return lf
def jig(w, h, n, b=0):
threshold = 0.1
penalty = 1.005
ratio = max(w, h) / min(w, h)
print('')
print(f'{w} by {h} is picture ratio {round(ratio, 4)}')
print(''... |
class Grandpa:
basketball = 1
class Dad(Grandpa):
dance = 1
def d(this):
return f"Yes I Dance {this.dance} no of times"
class Grandson(Dad):
dance = 6
def d(this):
return f"Yes I Dance AWESOMELY {this.dance} no of times"
jo = Grandpa()
bo = Dad()
po = Grandson()
# Everything... | class Grandpa:
basketball = 1
class Dad(Grandpa):
dance = 1
def d(this):
return f'Yes I Dance {this.dance} no of times'
class Grandson(Dad):
dance = 6
def d(this):
return f'Yes I Dance AWESOMELY {this.dance} no of times'
jo = grandpa()
bo = dad()
po = grandson()
print(po.basketba... |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Time, obj[2]: Coupon, obj[3]: Coupon_validity, obj[4]: Gender, obj[5]: Age, obj[6]: Children, obj[7]: Education, obj[8]: Occupation, obj[9]: Income, obj[10]: Bar, obj[11]: Coffeehouse, obj[12]: Restaurant20to50, obj[13]: Direction_same, obj[14]: Distance
# {"feature":... | def find_decision(obj):
if obj[13] <= 0:
if obj[0] <= 2:
if obj[2] <= 3:
if obj[10] <= 1.0:
if obj[7] <= 1:
return 'True'
elif obj[7] > 1:
if obj[4] <= 0:
return 'F... |
DOMAIN = "meross"
CONF_KEY = "key"
CONF_VALIDATE = "validate"
CONF_UUID = "uuid"
DEVICE_OFF = 0
DEVICE_ON = 1
LISTEN_TOPIC = '/appliance/{}/publish'
PUBLISH_TOPIC = '/appliance/{}/subscribe'
APP_METHOD_PUSH = "PUSH"
APP_METHOD_GET = "GET"
APP_METHOD_SET = "SET"
APP_SYS_CLOCK = "Appliance.System.Clock"
APP_SYS_ALL... | domain = 'meross'
conf_key = 'key'
conf_validate = 'validate'
conf_uuid = 'uuid'
device_off = 0
device_on = 1
listen_topic = '/appliance/{}/publish'
publish_topic = '/appliance/{}/subscribe'
app_method_push = 'PUSH'
app_method_get = 'GET'
app_method_set = 'SET'
app_sys_clock = 'Appliance.System.Clock'
app_sys_all = 'Ap... |
#!/usr/bin/env python3
def main():
print( getProd2() )
print( getProd3() )
def getProd2():
with open( "expenses.txt" ) as f:
expenses = [ int( i.rstrip("\n") ) for i in f.readlines() ]
n = len( expenses )
for i in range( n ):
for j in range( i + 1, n ):
if expenses[ i ] + expenses... | def main():
print(get_prod2())
print(get_prod3())
def get_prod2():
with open('expenses.txt') as f:
expenses = [int(i.rstrip('\n')) for i in f.readlines()]
n = len(expenses)
for i in range(n):
for j in range(i + 1, n):
if expenses[i] + expenses[j] == 2020:
... |
class LinkedListIterator:
def __init__(self, beginning):
self._current_cell = beginning
self._first = True
def __iter__(self):
return self
def __next__(self):
try:
getattr(self._current_cell, "value")
except AttributeError:
raise StopIteration()
else:
if self._first:
self._first = False
... | class Linkedlistiterator:
def __init__(self, beginning):
self._current_cell = beginning
self._first = True
def __iter__(self):
return self
def __next__(self):
try:
getattr(self._current_cell, 'value')
except AttributeError:
raise stop_iterat... |
'''https://practice.geeksforgeeks.org/problems/subarray-with-0-sum-1587115621/1
Subarray with 0 sum
Easy Accuracy: 49.91% Submissions: 74975 Points: 2
Given an array of positive and negative numbers. Find if there is a subarray (of size at-least one) with 0 sum.
Example 1:
Input:
5
4 2 -3 1 6
Output:
Yes
Explanat... | """https://practice.geeksforgeeks.org/problems/subarray-with-0-sum-1587115621/1
Subarray with 0 sum
Easy Accuracy: 49.91% Submissions: 74975 Points: 2
Given an array of positive and negative numbers. Find if there is a subarray (of size at-least one) with 0 sum.
Example 1:
Input:
5
4 2 -3 1 6
Output:
Yes
Explanat... |
all__ = ['jazPush', 'jazRvalue', 'jazLvalue', 'jazPop', 'jazAssign', 'jazCopy']
class jazPush:
def __init__(self):
self.command = "push"
def call(self, interpreter, arg):
interpreter.GetScope().stack.append(int(arg))
return None
class jazRvalue:
def __init__(self):
self.co... | all__ = ['jazPush', 'jazRvalue', 'jazLvalue', 'jazPop', 'jazAssign', 'jazCopy']
class Jazpush:
def __init__(self):
self.command = 'push'
def call(self, interpreter, arg):
interpreter.GetScope().stack.append(int(arg))
return None
class Jazrvalue:
def __init__(self):
self.... |
a = int(input())
length = 0
sum_of_sequence = 0
while a != 0:
sum_of_sequence += a
length += 1
a = int(input())
print(sum_of_sequence / length) | a = int(input())
length = 0
sum_of_sequence = 0
while a != 0:
sum_of_sequence += a
length += 1
a = int(input())
print(sum_of_sequence / length) |
def swap(i):
i = i.swapcase()
return i
if __name__ == "__main__":
s = input()
res = swap(s)
print(res)
| def swap(i):
i = i.swapcase()
return i
if __name__ == '__main__':
s = input()
res = swap(s)
print(res) |
class Cell(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __lt__(self, other):
if (self.x < other.x):
return True
elif (self.x > other.x):
return False
elif (self.x == other.x):
return (self.y < other.y)
... | class Cell(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __lt__(self, other):
if self.x < other.x:
return True
elif self.x > other.x:
return False
elif self.x == other.x:
return self.y < other.y |
#
# CAMP
#
# Copyright (C) 2017 -- 2019 SINTEF Digital
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the MIT license. See the LICENSE file for details.
#
class About:
PROGRAM = "CAMP"
VERSION = "0.7.0"
COMMIT_HASH = None
LICENSE = "MIT"
COPYRIG... | class About:
program = 'CAMP'
version = '0.7.0'
commit_hash = None
license = 'MIT'
copyright = 'Copyright (C) 2017 -- 2019 SINTEF Digital'
description = 'Amplify your configuration tests!'
@staticmethod
def full_version():
if About.COMMIT_HASH:
return '%s-git.%s' % (... |
# SIMPLE FORMULA
# __________________________________________________________________________________________
# VARIABLE
# - Localize language: ID
textOpen=(
'Solve it! #1',
'Diketahui W=((X+YxZ)/(XxY))^Z'
)
textInX='Nilai X:'
textInY='Nilai Y:'
textInZ='Nilai Z:'
textOut='Nilai W adalah'
# ____________________... | text_open = ('Solve it! #1', 'Diketahui W=((X+YxZ)/(XxY))^Z')
text_in_x = 'Nilai X:'
text_in_y = 'Nilai Y:'
text_in_z = 'Nilai Z:'
text_out = 'Nilai W adalah'
print(f'\n{textOpen[0]}\n\n{textOpen[1]}\n')
x = int(input(f'{textInX} '))
y = int(input(f'{textInY} '))
z = int(input(f'{textInZ} '))
w = ((x + y * z) / (x * y)... |
# I have used sieve of erato algorithm to solve this problem
def seive(Max):
primes = []
isprime = [False] * (Max)
maxN = Max
if maxN < 2:
return 0
if maxN >= 2:
isprime[0] = isprime[1] = True
for i in range(2, maxN):
if (isprime[i] is False):
for j in range... | def seive(Max):
primes = []
isprime = [False] * Max
max_n = Max
if maxN < 2:
return 0
if maxN >= 2:
isprime[0] = isprime[1] = True
for i in range(2, maxN):
if isprime[i] is False:
for j in range(i * i, maxN, i):
isprime[j] = True
for i in r... |
class Solution():
def isUnique(self, string: str):
'''Checks whether a given string has unique characters only
Inputs
------
string: str
string to be checked for unique chars
Assumptions
------------
Whitespace ' ' is a character
... | class Solution:
def is_unique(self, string: str):
"""Checks whether a given string has unique characters only
Inputs
------
string: str
string to be checked for unique chars
Assumptions
------------
Whitespace ' ' is a character
... |
class Page():
def __init__(self, parent, render):
self.__parent = parent
self.__render = render
def render(self):
return self.__render(self)
def parent(self):
return self.__parent
| class Page:
def __init__(self, parent, render):
self.__parent = parent
self.__render = render
def render(self):
return self.__render(self)
def parent(self):
return self.__parent |
# from astra import models
#
# class UserObject(models.Model):
# def
#
#
#
class MetaDemo(type):
pass
class Demo(metaclass=MetaDemo):
pass
d = Demo()
print(d.__class__.__metaclass__)
| class Metademo(type):
pass
class Demo(metaclass=MetaDemo):
pass
d = demo()
print(d.__class__.__metaclass__) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.