content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
game_board = {'7': ' ', '8': ' ', '9': ' ',
'4': ' ', '5': ' ', '6': ' ',
'1': ' ', '2': ' ', '3': ' '}
disp_board = {'1': '1', '2': '2', '3': '3',
'4': '4', '5': '5', '6': '6',
'7': '7', '8': '8', '9': '9'}
fill_board = []
# for i in the_board:
# fill_boar... | game_board = {'7': ' ', '8': ' ', '9': ' ', '4': ' ', '5': ' ', '6': ' ', '1': ' ', '2': ' ', '3': ' '}
disp_board = {'1': '1', '2': '2', '3': '3', '4': '4', '5': '5', '6': '6', '7': '7', '8': '8', '9': '9'}
fill_board = []
def print_board(board):
print(board['1'], ' |', board['2'], '|', board['3'])
print('-- ... |
if __name__ == '__main__':
print('hello.')
"""
The given program reads a list of single-word
first names and ages (ending with -1),
and outputs that list with the age incremented.
The program fails and throws an exception if
the second input on a line is a string rather
than ... | if __name__ == '__main__':
print('hello.')
'\n The given program reads a list of single-word\n first names and ages (ending with -1),\n and outputs that list with the age incremented.\n\n The program fails and throws an exception if\n the second input on a line is a string rather\n tha... |
# -*- coding: utf-8 -*-
DDD = int(input())
dic = { 61: "Brasilia", 71: "Salvador", 11: "Sao Paulo",
21: "Rio de Janeiro", 32: "Juiz de Fora", 19: "Campinas",
27: "Vitoria", 31: "Belo Horizonte" }
if (DDD in dic.keys()):
print(dic[DDD])
else:
print("DDD nao cadastrado") | ddd = int(input())
dic = {61: 'Brasilia', 71: 'Salvador', 11: 'Sao Paulo', 21: 'Rio de Janeiro', 32: 'Juiz de Fora', 19: 'Campinas', 27: 'Vitoria', 31: 'Belo Horizonte'}
if DDD in dic.keys():
print(dic[DDD])
else:
print('DDD nao cadastrado') |
class DBSCAN(object):
def __init__(self, eps=0, min_points=2):
self.eps = eps
self.min_points = min_points
self.noise = []
self.clusters = []
self.dp = []
self.near_neighbours = []
self.wp = set()
self.proto_cores = set()
self.points = []
... | class Dbscan(object):
def __init__(self, eps=0, min_points=2):
self.eps = eps
self.min_points = min_points
self.noise = []
self.clusters = []
self.dp = []
self.near_neighbours = []
self.wp = set()
self.proto_cores = set()
self.points = []
... |
config_structure = {
"default_user" : {
"profile": {
"description" : None, #string < 1000
"roster" : [], # List of champion dict
"roster_ss": [],
"alliance_ids": [], #list of dicts { alliance: 1234, tag: ABCDE}
"alliance_tag": None,
"... | config_structure = {'default_user': {'profile': {'description': None, 'roster': [], 'roster_ss': [], 'alliance_ids': [], 'alliance_tag': None, 'started': None, 'ingame': None, 'aq5_paths': [], 'aq6_paths': [], 'aq7_paths': [], 'aw': [], 'offense': None, 'defense': None, 'utility': None, 'collage': None}, 'settings': {'... |
class Solution:
def countLetters(self, S: str) -> int:
if len(S) == 1:
return 1
prev_char = S[0]
res = 1
flag = 1
for cur_char in S[1:]:
if cur_char == prev_char:
flag += 1
res += flag
else:
p... | class Solution:
def count_letters(self, S: str) -> int:
if len(S) == 1:
return 1
prev_char = S[0]
res = 1
flag = 1
for cur_char in S[1:]:
if cur_char == prev_char:
flag += 1
res += flag
else:
... |
i=10
for i in range(5):
print(i)
i = i+3
print(i)
'''output
0
3
1
4
2
5
3
6
4
7
''' | i = 10
for i in range(5):
print(i)
i = i + 3
print(i)
'output\n0\n3\n1\n4\n2\n5\n3\n6\n4\n7\n' |
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython
"""
for i in range(10, 0, -1):
print(i) | """AyudaEnPython: https://www.facebook.com/groups/ayudapython
"""
for i in range(10, 0, -1):
print(i) |
{
'includes': [ 'common.gypi' ],
'targets': [
{
'target_name': 'webserver',
'type': 'executable',
'sources': [
'webserver.cc',
],
'dependencies': [
'./deps/libuv/uv.gyp:libuv',
'./deps/http-parser/http_parser.gyp:http_parser'
],
},
{
'tar... | {'includes': ['common.gypi'], 'targets': [{'target_name': 'webserver', 'type': 'executable', 'sources': ['webserver.cc'], 'dependencies': ['./deps/libuv/uv.gyp:libuv', './deps/http-parser/http_parser.gyp:http_parser']}, {'target_name': 'webclient', 'type': 'executable', 'sources': ['webclient.cc'], 'dependencies': ['./... |
reveal_type(len("blub"))
def get_id(name: str):
return len(name)
reveal_type(get_id("blub"))
# limitations_inference.py:1: error: Revealed type is 'builtins.int'
# limitations_inference.py:7: error: Revealed type is 'Any'
| reveal_type(len('blub'))
def get_id(name: str):
return len(name)
reveal_type(get_id('blub')) |
MOCK_GOOD_COMMIT_1 = "\n".join([
"557fec0b69228ae803c81e38f80c3b1fb993d9cb|||<<<(((ooo+++ooo)))>>>|||Bob Dole|||<<<(((ooo+++ooo)))>>>|||bob@dole.com|||<<<(((ooo+++ooo)))>>>|||2015-05-20|||<<<(((ooo+++ooo)))>>>|||TIK-1111 - Some important change|||<<<(((ooo+++ooo)))>>>|||This change affects something really importan... | mock_good_commit_1 = '\n'.join(['557fec0b69228ae803c81e38f80c3b1fb993d9cb|||<<<(((ooo+++ooo)))>>>|||Bob Dole|||<<<(((ooo+++ooo)))>>>|||bob@dole.com|||<<<(((ooo+++ooo)))>>>|||2015-05-20|||<<<(((ooo+++ooo)))>>>|||TIK-1111 - Some important change|||<<<(((ooo+++ooo)))>>>|||This change affects something really important and... |
# -*- coding: utf-8 -*-
__version__ = '0.0.0'
__author__ = 'Mike Bland'
__license__ = "CC0-1.0"
| __version__ = '0.0.0'
__author__ = 'Mike Bland'
__license__ = 'CC0-1.0' |
class MockLogger:
@staticmethod
def info(content):
print(f"\nMockLogger: info - {content}")
@staticmethod
def debug(content):
print(f"\nMockLogger: debug - {content}")
def warn(self, content):
self.warning(content)
@staticmethod
def warning(content):
print(... | class Mocklogger:
@staticmethod
def info(content):
print(f'\nMockLogger: info - {content}')
@staticmethod
def debug(content):
print(f'\nMockLogger: debug - {content}')
def warn(self, content):
self.warning(content)
@staticmethod
def warning(content):
print... |
# simple python spark examples, as if they were typed into pyspark, not a full application
# load sales
sales=sc.textFile("sales_*.txt").map(lambda x:x.split('\t'))
#load stores and products
stores=sc.textFile("stores.txt").map(lambda x:x.split('\t'))
products=sc.textFile("products.txt").map(lambda x:x.split('\t'))
... | sales = sc.textFile('sales_*.txt').map(lambda x: x.split('\t'))
stores = sc.textFile('stores.txt').map(lambda x: x.split('\t'))
products = sc.textFile('products.txt').map(lambda x: x.split('\t'))
sales_by_day = sales.map(lambda x: (x[0], int(x[3]))).reduceByKey(lambda x, y: x + y)
sales_by_day.map(lambda l: '{0}\t{1}'.... |
class Student():
count=0
pycount=0
def __init__(self,USN,Name,Subject):
self.USN=USN
self.Name=Name
self.Subject=Subject
if self.Subject.lower()=="python":
Student.pycount+=1
Student.count+=1
listofstud=[]
n=int(input("Enter the number of students "))
for ... | class Student:
count = 0
pycount = 0
def __init__(self, USN, Name, Subject):
self.USN = USN
self.Name = Name
self.Subject = Subject
if self.Subject.lower() == 'python':
Student.pycount += 1
Student.count += 1
listofstud = []
n = int(input('Enter the numbe... |
# Reading input file
f = open("inputs/day02.txt", "r")
lines = f.readlines()
def part1():
valid_passwords = 0
for line in lines:
password = line.replace("\n", "").split(": ")
min_occurrence = int(password[0].split(" ")[0].split("-")[0])
max_occurrence = int(password[0].split(" ")[0].spl... | f = open('inputs/day02.txt', 'r')
lines = f.readlines()
def part1():
valid_passwords = 0
for line in lines:
password = line.replace('\n', '').split(': ')
min_occurrence = int(password[0].split(' ')[0].split('-')[0])
max_occurrence = int(password[0].split(' ')[0].split('-')[1])
l... |
__all__ = [
"category",
"event_log",
"org",
"user",
]
| __all__ = ['category', 'event_log', 'org', 'user'] |
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 28 20:54:59 2021
@author: eddy9111226
"""
year=int(input())
while (year!=-9999):
if (year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)):
print("yes")
else:
print("no")
year=int(input())
| """
Created on Sun Nov 28 20:54:59 2021
@author: eddy9111226
"""
year = int(input())
while year != -9999:
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
print('yes')
else:
print('no')
year = int(input()) |
def main():
infile = open("test_master.txt","r")
infileContent = infile.read();
infile.close()
testsRaw = infileContent.split("==========\n")
for testRaw in testsRaw:
testParts = testRaw.split("----------\n")
name = testParts[0].strip()
inSrc = testParts[1]
outSrc ... | def main():
infile = open('test_master.txt', 'r')
infile_content = infile.read()
infile.close()
tests_raw = infileContent.split('==========\n')
for test_raw in testsRaw:
test_parts = testRaw.split('----------\n')
name = testParts[0].strip()
in_src = testParts[1]
out_s... |
n=int(input())
if n%2==0:
print("I LOVE CBNU")
exit(0)
print("*"*n)
for i in range(n//2+1):
print(end=" "*(n//2-i))
if i==0: print("*")
else: print("*"+" "*(i*2-1)+"*") | n = int(input())
if n % 2 == 0:
print('I LOVE CBNU')
exit(0)
print('*' * n)
for i in range(n // 2 + 1):
print(end=' ' * (n // 2 - i))
if i == 0:
print('*')
else:
print('*' + ' ' * (i * 2 - 1) + '*') |
#!/usr/bin/env python3.7
rules = {}
with open('input.txt') as fd:
for line in fd:
words = line[:-1].split()
this_bag = words[0]+ " " + words[1]
rules[this_bag] = []
b = line[:-1].split('contain')
bags = b[1].split(',')
for bag in bags:
words = bag.split()... | rules = {}
with open('input.txt') as fd:
for line in fd:
words = line[:-1].split()
this_bag = words[0] + ' ' + words[1]
rules[this_bag] = []
b = line[:-1].split('contain')
bags = b[1].split(',')
for bag in bags:
words = bag.split()
count = 0
... |
# Copyright (C) 2005, Giovanni Bajo
# Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the... | hiddenimports = ['xml.dom.html.HTMLAnchorElement', 'xml.dom.html.HTMLAppletElement', 'xml.dom.html.HTMLAreaElement', 'xml.dom.html.HTMLBaseElement', 'xml.dom.html.HTMLBaseFontElement', 'xml.dom.html.HTMLBodyElement', 'xml.dom.html.HTMLBRElement', 'xml.dom.html.HTMLButtonElement', 'xml.dom.html.HTMLDirectoryElement', 'x... |
"""
Dictionaries. Unordered set of key value pairs separated by a comma & enclosed by {}.
Very useful for storing information in a specific format. They are mutable i.e. can be modified.
Dictionary specific procedures have to be used for doing this as they are not indexed by the position of the
element like lists. Th... | """
Dictionaries. Unordered set of key value pairs separated by a comma & enclosed by {}.
Very useful for storing information in a specific format. They are mutable i.e. can be modified.
Dictionary specific procedures have to be used for doing this as they are not indexed by the position of the
element like lists. Th... |
class Solution:
def mySqrt(self, x: int) -> int:
if x == 0 or x == 1:
return x
cur_min = x
left = 0
right = x // 2
res = 0
while left <= right:
mid = (left + right) // 2
cur_val = x - mid * mid
if cur_val >= 0 and cur_va... | class Solution:
def my_sqrt(self, x: int) -> int:
if x == 0 or x == 1:
return x
cur_min = x
left = 0
right = x // 2
res = 0
while left <= right:
mid = (left + right) // 2
cur_val = x - mid * mid
if cur_val >= 0 and cur_... |
"""
Sample ``conf.py``.
"""
master_doc = 'index'
extensions = [
'notfound.extension',
]
| """
Sample ``conf.py``.
"""
master_doc = 'index'
extensions = ['notfound.extension'] |
n=int(input())
l=list(map(int,input().split()))
count1=0
count2=0
for i in range(0,len(l)-1):
if l[i]<l[i+1]:
count1=count1+1
if(count1>count2):
count2=count1
else:
count1=0
print(count2+1)
| n = int(input())
l = list(map(int, input().split()))
count1 = 0
count2 = 0
for i in range(0, len(l) - 1):
if l[i] < l[i + 1]:
count1 = count1 + 1
if count1 > count2:
count2 = count1
else:
count1 = 0
print(count2 + 1) |
def ilen(n, mapa):
pole = [[1 for i in range(n)] for j in range(n)]
for obsz in mapa:
x = obsz[:2] [::-1]
y = obsz[2:4]
y = [y[1] - 1, y[0] - 1]
poziom = obsz[4]
wiersz = range(x[1], y[1] + 1)
wiersze = range(x[0], y[0] + 1)
for k in wiersze:
... | def ilen(n, mapa):
pole = [[1 for i in range(n)] for j in range(n)]
for obsz in mapa:
x = obsz[:2][::-1]
y = obsz[2:4]
y = [y[1] - 1, y[0] - 1]
poziom = obsz[4]
wiersz = range(x[1], y[1] + 1)
wiersze = range(x[0], y[0] + 1)
for k in wiersze:
fo... |
def gcd(A, B):
while A != 0:
B, A = A, B % A
return B
A, B = map(int, input().split())
if A >= B:
GCD = gcd(B, A)
else:
GCD = gcd(A, B)
result = A * B // GCD
print(result)
| def gcd(A, B):
while A != 0:
(b, a) = (A, B % A)
return B
(a, b) = map(int, input().split())
if A >= B:
gcd = gcd(B, A)
else:
gcd = gcd(A, B)
result = A * B // GCD
print(result) |
#!/bin/python3
# Print string
print("Strings and thigns")
print("hello world lmao")
print("""Hello this is a
multi line string""")
print("This is" + " concatination")
print('\n') #new line
# Maths
print("math time")
print(50 + 50)
print(50 - 50)
print(50 * 50)
print(50 / 50)
print(50 + 50 - 50 * 50 / 50) # PEMDAS... | print('Strings and thigns')
print('hello world lmao')
print('Hello this is a \nmulti line string')
print('This is' + ' concatination')
print('\n')
print('math time')
print(50 + 50)
print(50 - 50)
print(50 * 50)
print(50 / 50)
print(50 + 50 - 50 * 50 / 50)
print(50 ** 2)
print(50 % 6)
print(50 // 6)
print('\n')
print('F... |
class NoResponseContent(Exception):
"""
When the response is empty
"""
pass
class InvalidResponseRetry(Exception):
"""
When the response is invalid and we want to retry
"""
pass
class InvalidAMQPMessage(Exception):
def __repr__(self):
return 'The incoming AMQP message has... | class Noresponsecontent(Exception):
"""
When the response is empty
"""
pass
class Invalidresponseretry(Exception):
"""
When the response is invalid and we want to retry
"""
pass
class Invalidamqpmessage(Exception):
def __repr__(self):
return 'The incoming AMQP message has ... |
description = 'Basic setup for SPHERES containing sis detector, doppler, ' \
'sps selector and shutter'
group = 'basic'
includes = ['sis',
'doppler',
'cct6',
'sps',
'shutter',
'memograph',
'selector',
]
startupcode = 'S... | description = 'Basic setup for SPHERES containing sis detector, doppler, sps selector and shutter'
group = 'basic'
includes = ['sis', 'doppler', 'cct6', 'sps', 'shutter', 'memograph', 'selector']
startupcode = 'SetDetectors(sis)\nSetEnvironment(cct6_c_temperature, cct6_setpoint)' |
"""Code to handle preparing equation text for image transform."""
def escape_percentage(equation):
"""
Escape percentage symbols in equations.
Inputs:
equation: string containing equation
Returns string with percentage symbols escaped
"""
if '%' in equation:
equation = equati... | """Code to handle preparing equation text for image transform."""
def escape_percentage(equation):
"""
Escape percentage symbols in equations.
Inputs:
equation: string containing equation
Returns string with percentage symbols escaped
"""
if '%' in equation:
equation = equatio... |
"""*****************************************************************************
* Copyright (C) 2019 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to ... | """*****************************************************************************
* Copyright (C) 2019 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to ... |
def test_validate(client):
mimetype = "application/json"
headers = {
"Accept": mimetype
}
response = client.get(path="/validate",
query_string={"numbers": "100000000"
"020000000"
... | def test_validate(client):
mimetype = 'application/json'
headers = {'Accept': mimetype}
response = client.get(path='/validate', query_string={'numbers': '100000000020000000003000000000400000000050000000006000000000700000000080000000009'}, headers=headers)
assert response.status_code == 200
assert re... |
"""Module to hold sanity check functions."""
def luhn(account_string, _encoding):
"""Return bool if string passes Luhn test.
This is based on the algorithm example found on the wikipedia
article for luhn algorithm:
https[:]//en[dot]wikipedia[dot]org/wiki/Luhn_algorithm
:param account_string: Th... | """Module to hold sanity check functions."""
def luhn(account_string, _encoding):
"""Return bool if string passes Luhn test.
This is based on the algorithm example found on the wikipedia
article for luhn algorithm:
https[:]//en[dot]wikipedia[dot]org/wiki/Luhn_algorithm
:param account_string: The... |
def safe_open(*args, **kwargs):
file_handle = None
try:
file_handle = open(*args, **kwargs)
except IOError as exc:
yield None, exc # return for an exception
else:
try:
yield file_handle, None # return for success
# func(file_handle, None)
final... | def safe_open(*args, **kwargs):
file_handle = None
try:
file_handle = open(*args, **kwargs)
except IOError as exc:
yield (None, exc)
else:
try:
yield (file_handle, None)
finally:
print('clean things up')
if file_handle:
... |
"""Constants."""
CACHE_NAME = 'web_screen_scraper'
CACHE_TIMEOUT = 3600
| """Constants."""
cache_name = 'web_screen_scraper'
cache_timeout = 3600 |
def process_raw_input(s):
s = 'inputs/'+s
with open(s) as t:
return [line.strip().rstrip() for line in t.readlines()]
| def process_raw_input(s):
s = 'inputs/' + s
with open(s) as t:
return [line.strip().rstrip() for line in t.readlines()] |
REACTION_SUZUKI = "[*;$(c2aaaaa2),$(c2aaaa2):1]-!@[*;$(c2aaaaa2),$(c2aaaa2):2]>>[*:1][*].[*:2][*]"
SCAFFOLD_SUZUKI = 'Cc1ccc(cc1)c2cc(nn2c3ccc(cc3)S(=O)(=O)N)[*]'
DECORATION_SUZUKI = '[*]c1ncncc1'
TWO_DECORATIONS_SUZUKI = '[*]c1ncncc1|[*]c1ncncc1'
TWO_DECORATIONS_ONE_SUZUKI = '[*]c1ncncc1|[*]C'
SCAFFOLD_NO_SUZUKI = '[... | reaction_suzuki = '[*;$(c2aaaaa2),$(c2aaaa2):1]-!@[*;$(c2aaaaa2),$(c2aaaa2):2]>>[*:1][*].[*:2][*]'
scaffold_suzuki = 'Cc1ccc(cc1)c2cc(nn2c3ccc(cc3)S(=O)(=O)N)[*]'
decoration_suzuki = '[*]c1ncncc1'
two_decorations_suzuki = '[*]c1ncncc1|[*]c1ncncc1'
two_decorations_one_suzuki = '[*]c1ncncc1|[*]C'
scaffold_no_suzuki = '[*... |
class Solution(object):
mapping = {'2':'abc', '3': 'def', '4':'ghi',\
'5':'jkl', '6':'mno', '7': 'pqrs', '8':'tuv', '9':'wxyz'}
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
if len(digits) == 0:
return lis... | class Solution(object):
mapping = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
def letter_combinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
if len(digits) == 0:
return list()
... |
"""
UpBack: synchronize (both ways) two filesystem braches using
rclone, so that you can sync local and remote file systems
on Amazon Cloud Drive, Google Drive, Dropbox, etc...
"""
__version__ = "1.0.0-dev"
__author__ = "Davide Rossi"
__licence__ = "MIT"
| """
UpBack: synchronize (both ways) two filesystem braches using
rclone, so that you can sync local and remote file systems
on Amazon Cloud Drive, Google Drive, Dropbox, etc...
"""
__version__ = '1.0.0-dev'
__author__ = 'Davide Rossi'
__licence__ = 'MIT' |
#!/usr/bin/env python3.7
class StrategyTypes:
"""
Types of strategy available to solve a problem
"""
NULL = "null"
KNUTH = "knuth"
GENETIC = "genetic"
SWASZEK = "swaszek"
HYBRID = "hybrid"
| class Strategytypes:
"""
Types of strategy available to solve a problem
"""
null = 'null'
knuth = 'knuth'
genetic = 'genetic'
swaszek = 'swaszek'
hybrid = 'hybrid' |
def solution(max):
a = 0
b = 1
if max < 0:
print("Incorrect input")
elif max == 0:
return a
elif max == 1:
return b
else:
sum = 0
while a+b < max:
c = a + b
a = b
b = c
if b % 2 == 0:
... | def solution(max):
a = 0
b = 1
if max < 0:
print('Incorrect input')
elif max == 0:
return a
elif max == 1:
return b
else:
sum = 0
while a + b < max:
c = a + b
a = b
b = c
if b % 2 == 0:
sum +=... |
"""
This is only an example of the config file that would be used for database connections.
Fields listed as <> would have to be filled in manually.
"""
db_name = "<database_name>"
db_user = "<databse_username>"
db_password = "<database_password>"
db_host = "<database_host>"
db_port = "<database_port>"
| """
This is only an example of the config file that would be used for database connections.
Fields listed as <> would have to be filled in manually.
"""
db_name = '<database_name>'
db_user = '<databse_username>'
db_password = '<database_password>'
db_host = '<database_host>'
db_port = '<database_port>' |
"""
Author: Armon Dadgar
Description:
This test tries to initialize a VirtualNamespace and checks that it
behaves as expected.
"""
#pragma repy
# Small code snippet, safe
safe_code = "meaning_of_life = 42\n"
# Unsafe snippet
unsafe_code = "import sys\n"
# Try to make the safe virtual namespace
safe_virt = creat... | """
Author: Armon Dadgar
Description:
This test tries to initialize a VirtualNamespace and checks that it
behaves as expected.
"""
safe_code = 'meaning_of_life = 42\n'
unsafe_code = 'import sys\n'
safe_virt = createvirtualnamespace(safe_code, 'TEST VN')
try:
unsafe_virt = createvirtualnamespace(unsafe_code, 'TE... |
def CFS(data):
features = []
score = -1e-9
while True:
best_feature = None
for feature in range(data.features):
features.append(feature)
temp_score = calculate_corr(data[F])
if temp_score > score:
score = temp_score
best_feature = features
features.pop()
feature... | def cfs(data):
features = []
score = -1e-09
while True:
best_feature = None
for feature in range(data.features):
features.append(feature)
temp_score = calculate_corr(data[F])
if temp_score > score:
score = temp_score
best_fe... |
# O(n) time | O(d) - where n is the total number of elements in the array,
# including sub-elements and d is the greatest depth of arrays in the array
def productSum(array, multiplier=1):
# Write your code here.
sum = 0
for element in array:
if type(element) is list:
sum += productSum(element, multiplier + 1... | def product_sum(array, multiplier=1):
sum = 0
for element in array:
if type(element) is list:
sum += product_sum(element, multiplier + 1)
else:
sum += element
return sum * multiplier |
# "The cake is not a lie!" challenge
test_string = "abccbaabccba"
def solution(s):
s_len = len(s)
for pattern_len in range(1, s_len + 1):
pattern = s[:pattern_len]
pattern_count = s.count(pattern)
if pattern_count * pattern_len == s_len:
return pattern_count
if __name__... | test_string = 'abccbaabccba'
def solution(s):
s_len = len(s)
for pattern_len in range(1, s_len + 1):
pattern = s[:pattern_len]
pattern_count = s.count(pattern)
if pattern_count * pattern_len == s_len:
return pattern_count
if __name__ == '__main__':
print(solution(test_st... |
#!/bin/bash
with open("version.txt", "r+") as f:
version = f.read().split(".")
final_string = f"{version[0]}.{int(version[1])+1}.{version[2]}"
f.seek(0)
f.truncate() # truncate requires cursor at the beginning of the file
f.write(final_string)
| with open('version.txt', 'r+') as f:
version = f.read().split('.')
final_string = f'{version[0]}.{int(version[1]) + 1}.{version[2]}'
f.seek(0)
f.truncate()
f.write(final_string) |
conditions = {
'test_project_ids': ['*'],
'test_suite_ids': ['*'],
'test_names': ['login'],
}
def pre_test_run():
pass
| conditions = {'test_project_ids': ['*'], 'test_suite_ids': ['*'], 'test_names': ['login']}
def pre_test_run():
pass |
_debug = True
def SetDebug(val=True):
global _debug
_debug = val
class AtlasException(Exception):
def __init__(self, message):
super().__init__(message)
def AtlasAssert(cond, message):
if _debug and (not cond):
raise AtlasException(message) | _debug = True
def set_debug(val=True):
global _debug
_debug = val
class Atlasexception(Exception):
def __init__(self, message):
super().__init__(message)
def atlas_assert(cond, message):
if _debug and (not cond):
raise atlas_exception(message) |
# Protocol Constants
CMD_FIELD_LENGTH = 16 # Exact length of cmd field (in bytes)
LENGTH_FIELD_LENGTH = 4 # Exact length of length field (in bytes)
MAX_DATA_LENGTH = 10**LENGTH_FIELD_LENGTH-1 # Max size of data field according to protocol
MSG_HEADER_LENGTH = CMD_FIELD_LENGTH + 1 + LENGTH_FIELD_LENGTH + 1 # Ex... | cmd_field_length = 16
length_field_length = 4
max_data_length = 10 ** LENGTH_FIELD_LENGTH - 1
msg_header_length = CMD_FIELD_LENGTH + 1 + LENGTH_FIELD_LENGTH + 1
max_msg_length = MSG_HEADER_LENGTH + MAX_DATA_LENGTH
delimiter = '|'
data_delimiter = '#'
protocol_client = {'login_msg': 'LOGIN', 'logout_msg': 'LOGOUT', 'get... |
class Account:
def __init__(self, owner, amount=0):
self.owner = owner
self.amount = amount
self._transactions = []
def __add__(self, other):
account = Account(f'{self.owner}&{other.owner}', self.amount + other.amount)
account._transactions = self._transactions + other._... | class Account:
def __init__(self, owner, amount=0):
self.owner = owner
self.amount = amount
self._transactions = []
def __add__(self, other):
account = account(f'{self.owner}&{other.owner}', self.amount + other.amount)
account._transactions = self._transactions + other.... |
class ScreenType:
SSD1306 = 0
SSD1106 = 1
def __init__(self):
pass
class ConnectionType:
I2C = 0
SPI = 1
def __init__(self):
pass
class Screen:
screen_type = ""
connection_type = ""
bus = ""
screen = ""
# @timed_function
def __init__(self, screen_ty... | class Screentype:
ssd1306 = 0
ssd1106 = 1
def __init__(self):
pass
class Connectiontype:
i2_c = 0
spi = 1
def __init__(self):
pass
class Screen:
screen_type = ''
connection_type = ''
bus = ''
screen = ''
def __init__(self, screen_type, connection_type, bu... |
names_count = int(input())
names = {input() for _ in range(names_count)}
[print(x) for x in names]
| names_count = int(input())
names = {input() for _ in range(names_count)}
[print(x) for x in names] |
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = ""
services_str = "/home/ubuntu/catkin_ws/src/navigation/robot_pose_ekf/srv/GetStatus.srv"
pkg_name = "robot_pose_ekf"
dependencies_str = "std_msgs"
langs = "gencpp;genlisp;genpy"
dep_include_paths_str = "std_msgs;/opt/ros/indigo/share/std_msgs/cmake/.... | messages_str = ''
services_str = '/home/ubuntu/catkin_ws/src/navigation/robot_pose_ekf/srv/GetStatus.srv'
pkg_name = 'robot_pose_ekf'
dependencies_str = 'std_msgs'
langs = 'gencpp;genlisp;genpy'
dep_include_paths_str = 'std_msgs;/opt/ros/indigo/share/std_msgs/cmake/../msg'
python_executable = '/usr/bin/python'
package_... |
#
# PySNMP MIB module Nortel-Magellan-Passport-VoiceMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-VoiceMIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:19:22 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using P... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_size_constraint, value_range_constraint, constraints_intersection, single_value_constraint) ... |
""" default range of waypoints on the map (used for node name binary encoding in states) """
def get_pos_min_max():
# find boundaries of X and Y coordinates in the graph
ROW_MIN = 11
ROW_MAX = 14
COL_MIN = 0
COL_MAX = 11
# TBD for dynamic graphs
return (ROW_MIN, ROW_MAX), (COL_MIN, COL_MA... | """ default range of waypoints on the map (used for node name binary encoding in states) """
def get_pos_min_max():
row_min = 11
row_max = 14
col_min = 0
col_max = 11
return ((ROW_MIN, ROW_MAX), (COL_MIN, COL_MAX))
def get_pos_norms():
((row_min, row_max), (col_min, col_max)) = get_pos_min_max... |
SQLALCHEMY_DATABASE_URI = 'postgresql://shepard:shepard@localhost/sheparddb'
SECRET_KEY = 'fda890t43nlba8i9pr32jl'
MONGODB_SETTINGS = {
'db': 'sheparddb',
'host': '127.0.0.1',
'port': 27017
}
PORT = 9999
DEBUG_LOG_FILE = '/var/log/sheparddb/info.log'
WTF_CSRF_ENABLED = False... | sqlalchemy_database_uri = 'postgresql://shepard:shepard@localhost/sheparddb'
secret_key = 'fda890t43nlba8i9pr32jl'
mongodb_settings = {'db': 'sheparddb', 'host': '127.0.0.1', 'port': 27017}
port = 9999
debug_log_file = '/var/log/sheparddb/info.log'
wtf_csrf_enabled = False
sqlalchemy_track_modifications = True |
# For the drifters to work, you need to fill in your Twitter APP key.
# The probability values are hidden here. You can decide the values by youself.
# The values used in our paper can be found in the manuscript.
################# Access Keys #######################
mashape_key = ''
customer_API_key = ''
customer_API... | mashape_key = ''
customer_api_key = ''
customer_api_secret_key = ''
access_token = ''
access_token_secret = ''
twitter_app_auth = {'consumer_key': customer_API_key, 'consumer_secret': customer_API_secret_key, 'access_token': access_token, 'access_token_secret': access_token_secret}
conn_save_freq = 12
num_friends = 1
n... |
a,b,c = int(input()),input().split(),0
key = [b[i-a:i] for i in range(1, len(b)+1)if i%a==0 and b.count("0")!=a*a]
for i in range(a):
for j in range(a):
if len(key) > 1 and key[i][j] == key[j][i]:
c=c+1
if c == a*a:
print("yes",end="")
else:
print("no",end="")
... | (a, b, c) = (int(input()), input().split(), 0)
key = [b[i - a:i] for i in range(1, len(b) + 1) if i % a == 0 and b.count('0') != a * a]
for i in range(a):
for j in range(a):
if len(key) > 1 and key[i][j] == key[j][i]:
c = c + 1
if c == a * a:
print('yes', end='')
else:
print('no', end=''... |
class Solution:
#given a string
#return an integer
def romanToInt(self, s):
key = ['M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I']
val = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
res = 0
for i in range(len(key)):
while len(key[i]) <= len(s)... | class Solution:
def roman_to_int(self, s):
key = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']
val = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
res = 0
for i in range(len(key)):
while len(key[i]) <= len(s) and key[i] == s[:len(key[i]... |
"""exercism triangle module."""
def is_triangle(sides):
"""
Check to see if this is a triangle
:param sides: list[*int] - the length of the three sides of a triangle?
:return bool - whether it is a triangle or not
>>> is_triangle([1, 2, 3])
True
>>> is_triangle([0, 0, 0])
False
... | """exercism triangle module."""
def is_triangle(sides):
"""
Check to see if this is a triangle
:param sides: list[*int] - the length of the three sides of a triangle?
:return bool - whether it is a triangle or not
>>> is_triangle([1, 2, 3])
True
>>> is_triangle([0, 0, 0])
False
... |
# While loop will run until the specified condition is true
i = 1
while i < 5:
print(i)
i += 1
# Using break statement we can stop the flow of the loop
print()
i =1
while i < 5:
print (i)
if i == 3: # Our loop will stop executing from 3
break
i += 1
# Example 2
# Continue: this wl... | i = 1
while i < 5:
print(i)
i += 1
print()
i = 1
while i < 5:
print(i)
if i == 3:
break
i += 1
print('\nContinue Statement')
i = 0
while i < 5:
i += 1
if i == 3:
continue
print(i)
print()
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
print('\n... |
# from math import ceil, floor, trunc
# a=12.3456
# b=(a)
# # print(b)
# list=[1,2,3,4,5]
# # here we use the shallow copy method to both has the different memory address. using the "copy.copy".
# # list1=copy(list)
# help(copy.copy)
# print("list : ",id(list))
# print("list1 : ",id(list1))
def uppers(z):
for i... | def uppers(z):
for i in range(0, len(z)):
print('i : ', i)
if i % 2 == 0:
return z[i].upper()
else:
i = i + 1
txt = 'arfa is a good gril'
result = uppers(txt)
print(result) |
SEARCH_LOCATIONS = [
[-54.1962894, -69.223033],
[-51.7628454, -58.8519393],
[-48.263197, -70.2777205],
[-45.8935737, 168.8783417],
[-44.0028155, -68.519908],
[-42.8152797, 171.8666229],
[-42.1020234, 146.8177948],
[-39.1408438, -72.3870955],
[-38.7580781, 175.8217011],
[-38.73065... | search_locations = [[-54.1962894, -69.223033], [-51.7628454, -58.8519393], [-48.263197, -70.2777205], [-45.8935737, 168.8783417], [-44.0028155, -68.519908], [-42.8152797, 171.8666229], [-42.1020234, 146.8177948], [-39.1408438, -72.3870955], [-38.7580781, 175.8217011], [-38.7306509, -63.598033], [-37.4311589, 144.289902... |
SECRET_KEY = '*&GJD%KDjy'
DEBUG = True
ENV_CONF = {
'world_size': 12,
'capacity': 10,
'player1_home': (5,5),
'player2_home': (6,6),
'num_walls': 24,
'num_jobs': 24,
'value_range': (6,12),
'max_steps': 200
}
# REPLAY_DIR = "/replays"
REPLAY_DIR = "/Users/st491/LocalStore/tmp/competition3_repl... | secret_key = '*&GJD%KDjy'
debug = True
env_conf = {'world_size': 12, 'capacity': 10, 'player1_home': (5, 5), 'player2_home': (6, 6), 'num_walls': 24, 'num_jobs': 24, 'value_range': (6, 12), 'max_steps': 200}
replay_dir = '/Users/st491/LocalStore/tmp/competition3_replay'
timeout = 1.5
retry = 20 |
a=5
b=3
print(a+b)
c=input()
#d=input()
d=4
e=c*d
print(e) | a = 5
b = 3
print(a + b)
c = input()
d = 4
e = c * d
print(e) |
def cut_candy(arr):
size = len(arr)
memo = [0 for x in range(size+1)]
memo[0] = 0
for i in range(1, size+1):
max_profit = -float('inf')
for j in range(i):
max_profit = max(max_profit, arr[j] + memo[i-j-1])
memo[i] = max_profit
print(memo)
return memo[size]
... | def cut_candy(arr):
size = len(arr)
memo = [0 for x in range(size + 1)]
memo[0] = 0
for i in range(1, size + 1):
max_profit = -float('inf')
for j in range(i):
max_profit = max(max_profit, arr[j] + memo[i - j - 1])
memo[i] = max_profit
print(memo)
return memo[s... |
class ItemValue:
#Class to store items data
def __init__(self, wt, val, index):
self.wt = wt #Weight of item
self.val = val #Value of item
self.index = index #Index of item in list
self.cost = val / wt #Figure of merit
def __lt__(self, other)... | class Itemvalue:
def __init__(self, wt, val, index):
self.wt = wt
self.val = val
self.index = index
self.cost = val / wt
def __lt__(self, other):
return self.cost < other.cost
class Solution:
def get_max_knapsack(self, wt, val, capacity):
i_val = []
... |
fruit = {"orange": "a sweet, orange, citrus fruit",
"apple": "good for making cider",
"lemon": "a sour, yellow, citrus fruit",
"pear": "change me"}
# "apple": "The second one"} # reassigns the value of first 'apple' instead of printing a second 'apple' value
# # print(fruit)
... | fruit = {'orange': 'a sweet, orange, citrus fruit', 'apple': 'good for making cider', 'lemon': 'a sour, yellow, citrus fruit', 'pear': 'change me'}
print(fruit)
print(fruit.items())
print(tuple(fruit.items())) |
__version__ = '0.0.0'
API_ROOT = 'https://www.pythonanywhere.com/api/v0'
| __version__ = '0.0.0'
api_root = 'https://www.pythonanywhere.com/api/v0' |
def closeH5(h5File):
try:
h5File.close()
except:
pass
def closeAllH5Files(h5Files):
for h5File in h5Files:
closeH5(h5File)
def loadLabelsBlock(h5Dset, begin, end):
return h5Dset[begin[0]:end[0], begin[1]:end[1], begin[2]:end[2], 0]
def loadData(h5Dset, begin, end):
i... | def close_h5(h5File):
try:
h5File.close()
except:
pass
def close_all_h5_files(h5Files):
for h5_file in h5Files:
close_h5(h5File)
def load_labels_block(h5Dset, begin, end):
return h5Dset[begin[0]:end[0], begin[1]:end[1], begin[2]:end[2], 0]
def load_data(h5Dset, begin, end):
... |
original = 'Mary had a %s lamb.'
extra = 'little'
original % extra
'Mary had a little lamb.'
| original = 'Mary had a %s lamb.'
extra = 'little'
original % extra
'Mary had a little lamb.' |
# https://adventofcode.com/2021/day/5
test = "2021-05_sample.txt"
run = "2021-05_input.txt"
def part1(fname):
count = 0
points = {}
for line in open(fname):
a, _, b = line.rstrip().split(' ')
p1 = [int(x) for x in a.split(',')]
p2 = [int(x) for x in b.split(',')]
#print(f'\... | test = '2021-05_sample.txt'
run = '2021-05_input.txt'
def part1(fname):
count = 0
points = {}
for line in open(fname):
(a, _, b) = line.rstrip().split(' ')
p1 = [int(x) for x in a.split(',')]
p2 = [int(x) for x in b.split(',')]
if p1[0] == p2[0] or p1[1] == p2[1]:
... |
c=0;a=[];n=int(input())
for _ in range(n):
v,p=map(int,input().split())
a.append(v)
a.sort(reverse=True);k=a[4]
for i in range(5,n):
if k==a[i]: c+=1
else: break
print(c)
| c = 0
a = []
n = int(input())
for _ in range(n):
(v, p) = map(int, input().split())
a.append(v)
a.sort(reverse=True)
k = a[4]
for i in range(5, n):
if k == a[i]:
c += 1
else:
break
print(c) |
x=1
pos=0
while x<=6:
a=float(input())
if a>0:
pos=1+pos
x=x+1
print("%d valores positivos" % pos)
| x = 1
pos = 0
while x <= 6:
a = float(input())
if a > 0:
pos = 1 + pos
x = x + 1
print('%d valores positivos' % pos) |
class Node(object):
def __init__(self, item):
self.item = item
def __str__(self):
return str(self.item)
def __repr__(self):
return str(self)
def __getattr__(self, attr):
return getattr(self.item, attr)
| class Node(object):
def __init__(self, item):
self.item = item
def __str__(self):
return str(self.item)
def __repr__(self):
return str(self)
def __getattr__(self, attr):
return getattr(self.item, attr) |
class MRMSComposite(object):
"""
Class for the MRMSGrib object
"""
def __init__(self, validity_date, validity_time, major_axis, minor_axis, data_path, fname, shape, grid_lons=None, grid_lats=None):
"""
Initializes a new MRMSComposite object
Parameters
----------
... | class Mrmscomposite(object):
"""
Class for the MRMSGrib object
"""
def __init__(self, validity_date, validity_time, major_axis, minor_axis, data_path, fname, shape, grid_lons=None, grid_lats=None):
"""
Initializes a new MRMSComposite object
Parameters
----------
... |
class CountdownObject():
def __init__(self, list_nums, target):
self._list_nums = list_nums # e.g. [1,2,3,4]
self._target = target
self._permutations = [list_nums.copy()] # list of lists, all possible permutations of original list, e.g. [[1,5,7],[2,4,3]...], starts as original list of nums
self._solutions = [[... | class Countdownobject:
def __init__(self, list_nums, target):
self._list_nums = list_nums
self._target = target
self._permutations = [list_nums.copy()]
self._solutions = [[''] * len(list_nums)]
def get_permutations(self):
return self._permutations
def get_solutions... |
description = 'virtual POLI lifting counter'
group = 'lowlevel'
devices = dict(
liftingctr = device('nicos.devices.generic.VirtualMotor',
description = 'lifting counter axis',
pollinterval = 15,
maxage = 61,
fmtstr = '%.2f',
abslimits = (-4.2, 30),
precision = 0.01,... | description = 'virtual POLI lifting counter'
group = 'lowlevel'
devices = dict(liftingctr=device('nicos.devices.generic.VirtualMotor', description='lifting counter axis', pollinterval=15, maxage=61, fmtstr='%.2f', abslimits=(-4.2, 30), precision=0.01, unit='deg')) |
#
# PySNMP MIB module COLUBRIS-CONNECTION-LIMITING-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/COLUBRIS-CONNECTION-LIMITING-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:25:45 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pyt... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_range_constraint, constraints_union, value_size_constraint, constraints_intersection) ... |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 23 23:02:44 2017
@author: LI YUXIN
"""
'''
VGGNet Placeholder
'''
| """
Created on Sun Apr 23 23:02:44 2017
@author: LI YUXIN
"""
'\nVGGNet Placeholder\n' |
# Wrap the operations into one function, now named `calculate`,
# with a mandatory "operation" parameter.
def calculate(x: int, y: int = 1, operation: str = None) -> int:
"""Calculates the sum (or difference) of two numbers.
Parameters:
`x` : int
The first number
`y` : int, optional
T... | def calculate(x: int, y: int=1, operation: str=None) -> int:
"""Calculates the sum (or difference) of two numbers.
Parameters:
`x` : int
The first number
`y` : int, optional
The second number (default is `1`)
`operation`: str, optional
Pass "subtract" to perform subtraction ... |
def is_even(x):
result=x//2
if((x-result*2)==0):
return True
else:
return False | def is_even(x):
result = x // 2
if x - result * 2 == 0:
return True
else:
return False |
#!/usr/bin/python3
complex_delete = __import__('102-complex_delete').complex_delete
print_sorted_dictionary = \
__import__('6-print_sorted_dictionary').print_sorted_dictionary
a_dictionary = {'lang': "C", 'track': "Low", 'pref': "C", 'ids': [1, 2, 3]}
new_dict = complex_delete(a_dictionary, 'C')
print_sorted_dicti... | complex_delete = __import__('102-complex_delete').complex_delete
print_sorted_dictionary = __import__('6-print_sorted_dictionary').print_sorted_dictionary
a_dictionary = {'lang': 'C', 'track': 'Low', 'pref': 'C', 'ids': [1, 2, 3]}
new_dict = complex_delete(a_dictionary, 'C')
print_sorted_dictionary(a_dictionary)
print(... |
def changeValueA(actualDataFrame, changeValue):
predictedData = actualDataFrame.copy()
predictedData["y"] = [item*changeValue for item in actualDataFrame["x"]]
return predictedData
def changeValueB(actualDataFrame, changeValue):
predictedData = actualDataFrame.copy()
predictedData["y"] = [item+cha... | def change_value_a(actualDataFrame, changeValue):
predicted_data = actualDataFrame.copy()
predictedData['y'] = [item * changeValue for item in actualDataFrame['x']]
return predictedData
def change_value_b(actualDataFrame, changeValue):
predicted_data = actualDataFrame.copy()
predictedData['y'] = [i... |
# # # # # # # # Python Tuples (a,b)
# # # # # # # # Immutable - size is fixed
# # # # # # # # Use - passing data that does not need changing
# # # # # # # # Faster than list - less bookkeeping no worries about size change
# # # # # # # # "safer" than list
# # # # # # # # Can be key in dict unlike list
# # # # # # # # F... | my_tuple = ('Valdis', 'programmer', 45, 200.8, [10, 20, 30], True, None, ('also_tuple', 5, True), {'food': 'potatoes', 'drink': 'kefir'})
print(my_tuple)
simple_tuple = (10, 20, 30)
print(simple_tuple)
another_tuple = tuple([1, 'Valdis', True])
print(another_tuple)
print(type(my_tuple))
numbers_tuple = tuple(range(100,... |
# Copyright 2017 Balazs Nemeth
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | class Basewhentoapplyoptimization(object):
def __init__(self, opt_ready_states, opt_pending_states, logger):
"""
Return always true.
:param opt_ready_states: iterable
:param opt_pending_states: iterable
"""
super(BaseWhenToApplyOptimization, self).__init__()
self.opt_ready_... |
# v = dict.fromkeys(["k1","123","323"],123)
# print(v)
# dic = {'k1': 123, 456: 123, '999': 123}
# v = dic.pop()
# print(v,dic)
# del dic["999"]
# print(dic)
# dic = {'k1': 123, 123: 123, '999': 123}
# v = dic.setdefault("k2","123")
# print(v,dic)
# dic.update({"k3":"v3"})
# dic.update(k4="v4")
# for i in dic.keys():
... | dic = {'k1': 123, 123: 123, '999': 123}
for (i, v) in enumerate(dic.items(), 1):
print(i, v[0], v[1])
for (i, v) in enumerate(dic, 1):
print(i, v, dic[v]) |
crime_codes = {
'740': 'VANDALISM - FELONY ($400 & OVERALL CHURCH VANDALISMS) 0114',
'888': 'TRESPASSING',
'330': 'BURGLARY FROM VEHICLE',
'745': 'VANDALISM - MISDEAMEANOR ($399 OR UNDER)',
'510': 'VEHICLE - STOLEN',
'210': 'ROBBERY',
'901': 'VIOLATION OF RESTRAINING ORDER',
'626': 'INTI... | crime_codes = {'740': 'VANDALISM - FELONY ($400 & OVERALL CHURCH VANDALISMS) 0114', '888': 'TRESPASSING', '330': 'BURGLARY FROM VEHICLE', '745': 'VANDALISM - MISDEAMEANOR ($399 OR UNDER)', '510': 'VEHICLE - STOLEN', '210': 'ROBBERY', '901': 'VIOLATION OF RESTRAINING ORDER', '626': 'INTIMATE PARTNER - SIMPLE ASSAULT', '... |
def in_range(minim, maxim, num):
if minim > maxim:
aux = minim
minim = maxim
maxim = aux
return num in range(minim, maxim)
x = in_range(10, 14, 11)
print(x)
| def in_range(minim, maxim, num):
if minim > maxim:
aux = minim
minim = maxim
maxim = aux
return num in range(minim, maxim)
x = in_range(10, 14, 11)
print(x) |
# 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 __init__(self):
self.has_found = False
self.res = []
self.path = []
def DFS(self, n... | class Treenode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def __init__(self):
self.has_found = False
self.res = []
self.path = []
def dfs(self, node, tar):
if node is None:
... |
info = {0: {'bad_channels': [3],
'color': 'red',
'polygon': [(0.396535162031, -0.628663752105),
(0.396444292843, -0.631425958949),
(0.396352852158, -0.634185981605),
(0.396260837973, -0.63694380631),
(0.3961682483, -0.639699419259),
... | info = {0: {'bad_channels': [3], 'color': 'red', 'polygon': [(0.396535162031, -0.628663752105), (0.396444292843, -0.631425958949), (0.396352852158, -0.634185981605), (0.396260837973, -0.63694380631), (0.3961682483, -0.639699419259), (0.396075081167, -0.642452806602), (0.395981334623, -0.645203954444), (0.395887006733, ... |
n = int(input())
salary = int(input())
penalty = 0
for i in range(n):
browser_tab = input()
if browser_tab == 'Facebook':
penalty += 150
elif browser_tab == 'Instagram':
penalty += 100
elif browser_tab == 'Reddit':
penalty += 50
if salary - penalty <= 0:
print('You have los... | n = int(input())
salary = int(input())
penalty = 0
for i in range(n):
browser_tab = input()
if browser_tab == 'Facebook':
penalty += 150
elif browser_tab == 'Instagram':
penalty += 100
elif browser_tab == 'Reddit':
penalty += 50
if salary - penalty <= 0:
print('You have lost ... |
# Tabela verdade do operador not
x = True
y = False
print(not x)
print(not y)
# Tabela verdade do operador and (e)(apenas true e true da true)
x = True
y = False
print(x and y)
# Tabela verdade do operador or (ou) (apenas false ou false da false)(o resto da true)
x = True
y = False
print(x or y)
# exemplo 1 not
x = ... | x = True
y = False
print(not x)
print(not y)
x = True
y = False
print(x and y)
x = True
y = False
print(x or y)
x = 10
y = 1
res = not x > y
print(res)
x = 10
y = 1
z = 5.5
res = x > y and z == y
print(res)
x = 10
y = 1
z = 5.5
res = x > y or z == y
print(res)
x = 10
y = 1
z = 5.5
res = x > y or (not z == y and y != y ... |
def encrypt(y):
y = y ^ y >> 11
y = y ^ y << 7 & 2636928640
y = y ^ y << 15 & 4022730752
y = y ^ y >> 18
return y
flag = open("flag", 'rb').read().strip()
encrypted = list(map(encrypt, flag))
print(encrypted)
# 151130148, 189142078, 184947887, 184947887, 155324581, 4194515, 16908820, 16908806, 172234346, 1... | def encrypt(y):
y = y ^ y >> 11
y = y ^ y << 7 & 2636928640
y = y ^ y << 15 & 4022730752
y = y ^ y >> 18
return y
flag = open('flag', 'rb').read().strip()
encrypted = list(map(encrypt, flag))
print(encrypted) |
def parity_brute_force(x):
res = 0
while x > 0:
res ^= x & 0x1
x = x >> 1
return res
def parity_bit_shifting(x):
four_bit_parity_lookup_table = 0x6996 #= 0b0110100110010110
x ^= x >> 32
x ^= x >> 16
x ^= x >> 8
x ^= x >> 4
x &= 0xF
return (four_bit_parity_loo... | def parity_brute_force(x):
res = 0
while x > 0:
res ^= x & 1
x = x >> 1
return res
def parity_bit_shifting(x):
four_bit_parity_lookup_table = 27030
x ^= x >> 32
x ^= x >> 16
x ^= x >> 8
x ^= x >> 4
x &= 15
return four_bit_parity_lookup_table >> x & 1
if __name__ ... |
t=int(input())
while(t):
n,v1,v2=map(int,input().split())
if(2**0.5)/v1<2/v2:
print("Stairs")
else:
print("Elevator")
t=t-1
| t = int(input())
while t:
(n, v1, v2) = map(int, input().split())
if 2 ** 0.5 / v1 < 2 / v2:
print('Stairs')
else:
print('Elevator')
t = t - 1 |
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
abc_set = set()
max_length = 0
start_pos = 0
for i, c in enumerate(s):
while c in abc_set:
abc_set.discard(s[start_pos])
... | class Solution:
def length_of_longest_substring(self, s):
"""
:type s: str
:rtype: int
"""
abc_set = set()
max_length = 0
start_pos = 0
for (i, c) in enumerate(s):
while c in abc_set:
abc_set.discard(s[start_pos])
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.