content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
Root endpoints.
"""
def root() -> str:
"""
Root endpoint.
:return: project description
"""
return 'Sample RESTful API'
| """
Root endpoints.
"""
def root() -> str:
"""
Root endpoint.
:return: project description
"""
return 'Sample RESTful API' |
class LetterInput():
def __init__(self, letter):
self.__dict__['_x'] = []
self.__dict__['_d'] = None
self.__dict__['_letter'] = letter
self.getLetter()
def getLetter(self):
if self._letter == 'a':
self._x = [
0, 0, 0, 0, 0,
... | class Letterinput:
def __init__(self, letter):
self.__dict__['_x'] = []
self.__dict__['_d'] = None
self.__dict__['_letter'] = letter
self.getLetter()
def get_letter(self):
if self._letter == 'a':
self._x = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... |
x = 8
class C:
x = 7
def f():
return x
| x = 8
class C:
x = 7
def f():
return x |
# Obtaining the Width and Height of a Raster
# https://github.com/GeospatialPython/Learn/raw/master/SatImage.zip
rasterLyr = QgsRasterLayer("/qgis_data/rasters/satimage.tif", "Satellite Image")
rasterLyr.isValid()
# True
rasterLyr.width()
# 2592
rasterLyr.height()
# 2693 | raster_lyr = qgs_raster_layer('/qgis_data/rasters/satimage.tif', 'Satellite Image')
rasterLyr.isValid()
rasterLyr.width()
rasterLyr.height() |
def first(input):
res = ""
rem = input[::]
while '(' in rem:
start = rem.index('(')
end = rem.index(')')
chars, repetitions = list(map(int, rem[start+1:end].split('x')))
res += rem[:start]
res += rem[end+1:end+1+chars]*repetitions
rem = rem[end+chars+1:]
... | def first(input):
res = ''
rem = input[:]
while '(' in rem:
start = rem.index('(')
end = rem.index(')')
(chars, repetitions) = list(map(int, rem[start + 1:end].split('x')))
res += rem[:start]
res += rem[end + 1:end + 1 + chars] * repetitions
rem = rem[end + ch... |
strings = {
# ui strings
'nothing': 'None',
'mora': "Mora",
'xp': 'Character Exp',
'wep_xp': 'Weapon Exp',
'resin': 'Resin',
'location': "Location",
'item': 'Item',
'item_s': 'Item(s)',
'character_s': 'Character(s)',
'characters': 'Characters',
'inventory': 'Inventory',
'add': 'Add',
'character': 'Charact... | strings = {'nothing': 'None', 'mora': 'Mora', 'xp': 'Character Exp', 'wep_xp': 'Weapon Exp', 'resin': 'Resin', 'location': 'Location', 'item': 'Item', 'item_s': 'Item(s)', 'character_s': 'Character(s)', 'characters': 'Characters', 'inventory': 'Inventory', 'add': 'Add', 'character': 'Character', 'name': 'Name', 'level'... |
# 2-4 Name Cases
name = "henrik samuelsson"
print(name.lower())
print(name.upper())
print(name.title())
| name = 'henrik samuelsson'
print(name.lower())
print(name.upper())
print(name.title()) |
"""AXL definitions"""
WSDL_URLS = {
"RisPort70": "https://{fqdn}:8443/realtimeservice2/services/RISService70?wsdl",
"CDRonDemand": "https://{fqdn}:8443/realtimeservice2/services/CDRonDemandService?wsdl",
"PerfMon": "https://{fqdn}:8443/perfmonservice2/services/PerfmonService?wsdl",
"ControlCenterServi... | """AXL definitions"""
wsdl_urls = {'RisPort70': 'https://{fqdn}:8443/realtimeservice2/services/RISService70?wsdl', 'CDRonDemand': 'https://{fqdn}:8443/realtimeservice2/services/CDRonDemandService?wsdl', 'PerfMon': 'https://{fqdn}:8443/perfmonservice2/services/PerfmonService?wsdl', 'ControlCenterServices': 'https://{fqd... |
# get prime numbers
def get_primes():
prime1 = int(input('Please enter the first prime number:'))
prime2 = int(input('Please enter the second prime number:'))
return prime1, prime2
# check if each number is prime
def is_prime(i):
if i < 2:
return False
if i == 2:
return True
if... | def get_primes():
prime1 = int(input('Please enter the first prime number:'))
prime2 = int(input('Please enter the second prime number:'))
return (prime1, prime2)
def is_prime(i):
if i < 2:
return False
if i == 2:
return True
if i > 2:
for j in range(2, i):
i... |
# 2020.01.09
# Problem Statement:
# https://leetcode.com/problems/same-tree/
# 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 isSameTree(self, p: TreeNo... | class Solution:
def is_same_tree(self, p: TreeNode, q: TreeNode) -> bool:
if p is None:
return q is None
if q is None:
return p is None
self.answer = True
return self.isSameTreeHelper(p, q)
def is_same_tree_helper(self, p, q):
if p is None:
... |
@job(desc="job1's desc")
def job1():
pass
@job("test1")
def job2():
pass
| @job(desc="job1's desc")
def job1():
pass
@job('test1')
def job2():
pass |
class HTTPException(Exception):
"""
Exception which happens when HTTP status code is not 200 (OK).
"""
def __init__(self, code, url) -> None:
self.error = f"While requesting to {url}, request returned status {code}."
def __str__(self) -> str:
return self.error
class GeniusExcepti... | class Httpexception(Exception):
"""
Exception which happens when HTTP status code is not 200 (OK).
"""
def __init__(self, code, url) -> None:
self.error = f'While requesting to {url}, request returned status {code}.'
def __str__(self) -> str:
return self.error
class Geniusexceptio... |
class Tracker:
def __init__(self, con):
self.con = con
def get_tracking(self):
tracking = dict()
for notice in self.con.notices:
splits = notice.split()
if splits[1] == 'TRACK':
if splits[2] in tracking:
tracking[splits[2]].ap... | class Tracker:
def __init__(self, con):
self.con = con
def get_tracking(self):
tracking = dict()
for notice in self.con.notices:
splits = notice.split()
if splits[1] == 'TRACK':
if splits[2] in tracking:
tracking[splits[2]].ap... |
class PortainerNameView:
def __init__(
self, client, database="portainer2git", collection="portainer_name"
):
super().__init__()
self.__client = client
self.__db = self.__client[database]
self.__collection = self.__db[collection]
def name_exists(self, name: str) -> b... | class Portainernameview:
def __init__(self, client, database='portainer2git', collection='portainer_name'):
super().__init__()
self.__client = client
self.__db = self.__client[database]
self.__collection = self.__db[collection]
def name_exists(self, name: str) -> bool:
... |
dict1 = {"first_name": "frodo","last_name":"baggins"}
#x = dict1.pop("lst_name")
#print(x)
a = {"snack": "pasta","desert":"brownie","main":"rice"}
b = a.copy()
b["desert"]= "pudding"
print(a)
mytup = (10000,)
print(mytup*6)
subject = ("physics","chemistry","history","anthropology","archeology")
subjects = subject + ... | dict1 = {'first_name': 'frodo', 'last_name': 'baggins'}
a = {'snack': 'pasta', 'desert': 'brownie', 'main': 'rice'}
b = a.copy()
b['desert'] = 'pudding'
print(a)
mytup = (10000,)
print(mytup * 6)
subject = ('physics', 'chemistry', 'history', 'anthropology', 'archeology')
subjects = subject + subject
print(subjects) |
class Solution:
def findMaxAverage(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: float
"""
if len(nums) == 1: return nums[0]
max_ave = float('-inf')
for i in range(len(nums) - k + 1):
max_ave = max(max_ave, sum(nums[i:i + k... | class Solution:
def find_max_average(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: float
"""
if len(nums) == 1:
return nums[0]
max_ave = float('-inf')
for i in range(len(nums) - k + 1):
max_ave = max(max_ave, s... |
"""CSC110 Fall 2021: Term Test 2, Question 1 (Cryptography)
Module Description
==================
This module contains instructions for this question. There are THREE
parts of this question, labelled "Part (a)", "Part (b)", etc.
The comments in this file contain instructions on how to complete each part,
so please rea... | """CSC110 Fall 2021: Term Test 2, Question 1 (Cryptography)
Module Description
==================
This module contains instructions for this question. There are THREE
parts of this question, labelled "Part (a)", "Part (b)", etc.
The comments in this file contain instructions on how to complete each part,
so please rea... |
#! usr/bin/env python3
# Function arguments in python work in the same way as assignments - be careful with mutable objects
# When assigning a mutable to a var, we are actually assigning a reference to the mutable
# Function arguments work in the same way as assignments. Changes to mutable objects will be reflected ... | def main():
a = [5]
print(id(a))
b = a
print(id(b))
b[0] = 3
print(id(b))
x = 5
print(id(x))
y = x
print(id(y))
kitten(x)
print(f'in main: x is {x}')
dog('wofwof', 'woooof', 'woffff')
dog()
n = ('wofwof', 'woooof', 'woffff')
dog(n)
dog(*n)
cow(Buff... |
###################################
# File Name : multiple_of_ten.py
###################################
#!/usr/bin/python3
def multiple_of_ten():
square_root = 10
def square(x):
return square_root ** x
return square
def main():
print ("=== print result ===")
f = multiple_of_ten()
p... | def multiple_of_ten():
square_root = 10
def square(x):
return square_root ** x
return square
def main():
print('=== print result ===')
f = multiple_of_ten()
print(f(2))
print(f(3))
if __name__ == '__main__':
main() |
num1 = 10
num2 = 20
num3 = 454545
num3 = 12012
| num1 = 10
num2 = 20
num3 = 454545
num3 = 12012 |
# python3
def solve(r, c):
res = 0
q_r, q_c = r // 3, c // 3
r_r, r_c = r % 3, c % 3
res += q_r * q_c * 8
if r_c == 1:
res += q_r * 2
if r_c == 2:
res += q_r * 5
if r_r == 1:
res += q_c * 2
if r_r == 2:
res += q_c * 5
if r_r == 1 and r_c == 2:
... | def solve(r, c):
res = 0
(q_r, q_c) = (r // 3, c // 3)
(r_r, r_c) = (r % 3, c % 3)
res += q_r * q_c * 8
if r_c == 1:
res += q_r * 2
if r_c == 2:
res += q_r * 5
if r_r == 1:
res += q_c * 2
if r_r == 2:
res += q_c * 5
if r_r == 1 and r_c == 2:
re... |
def powertower(x, n):
''' Calculates the power tower x**x**x**x**x... where the exponentiation
is repeated n times.
'''
r = 1
for i in range(n):
r = r**x
return r | def powertower(x, n):
""" Calculates the power tower x**x**x**x**x... where the exponentiation
is repeated n times.
"""
r = 1
for i in range(n):
r = r ** x
return r |
class CircularBuffer:
def __init__(self, size):
self.buf = [None] * size
self.posW = 0
self.posR = 0
self.len = 0
def __len__(self):
return self.len
def _incR(self):
self.posR = (self.posR + 1) % len(self.buf)
def _incW(self):
self... | class Circularbuffer:
def __init__(self, size):
self.buf = [None] * size
self.posW = 0
self.posR = 0
self.len = 0
def __len__(self):
return self.len
def _inc_r(self):
self.posR = (self.posR + 1) % len(self.buf)
def _inc_w(self):
self.posW = (se... |
x = input("enter number:")
if(x>=10 and x<30):
print(x,"le bada surma eda layi firda")
elif(x>=30 and x<=40):
print(x,"bada stud")
else :
print(x,"chota bai oye")
| x = input('enter number:')
if x >= 10 and x < 30:
print(x, 'le bada surma eda layi firda')
elif x >= 30 and x <= 40:
print(x, 'bada stud')
else:
print(x, 'chota bai oye') |
"""
Config module.
"""
class Config:
"""
Class with constants for configuration.
"""
DEFAULT_DEBUGGING: bool = True
DEFAULT_DAYS_EXPIRATION: int = 60
| """
Config module.
"""
class Config:
"""
Class with constants for configuration.
"""
default_debugging: bool = True
default_days_expiration: int = 60 |
def predict_proba(arr):
return [
[[], 99.999],
]
| def predict_proba(arr):
return [[[], 99.999]] |
class Solution(object):
def countComponents(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: int
"""
g = {x: [] for x in range(n)}
for x, y in edges:
g[x].append(y)
g[y].append(x)
visited = [False] * n
... | class Solution(object):
def count_components(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: int
"""
g = {x: [] for x in range(n)}
for (x, y) in edges:
g[x].append(y)
g[y].append(x)
visited = [False] * n
... |
class TwitterData_Cleansing(TwitterData_Initialize.TwitterData_Initialize):
def __init__(self, previous):
self.processed_data = previous.processed_data
def cleanup(self, cleanuper):
t = self.processed_data
for cleanup_method in cleanuper.iterate():
if not self.is_tes... | class Twitterdata_Cleansing(TwitterData_Initialize.TwitterData_Initialize):
def __init__(self, previous):
self.processed_data = previous.processed_data
def cleanup(self, cleanuper):
t = self.processed_data
for cleanup_method in cleanuper.iterate():
if not self.is_testing:
... |
#!/usr/bin/python2.4
# encoding: utf-8
"""
score.py
THIS FILE SHOULD BE REMOVED ONCE THE DDG SCHEDULER HAS BEEN REWRITTEN.
Created by Shane O'Connor 2012.
Copyright (c) 2012 __UCSF__. All rights reserved.
"""
class ddgScore(object):
type = None
version = None
def __init__(self, data = {}):
self.data = data
... | """
score.py
THIS FILE SHOULD BE REMOVED ONCE THE DDG SCHEDULER HAS BEEN REWRITTEN.
Created by Shane O'Connor 2012.
Copyright (c) 2012 __UCSF__. All rights reserved.
"""
class Ddgscore(object):
type = None
version = None
def __init__(self, data={}):
self.data = data
def get_type(self):
... |
def enum():
with open("textSource", "r") as file:
text = file.read()
words = text.split()
formatedText = ""
for i, word in enumerate(words):
formatedText += str((i // 15) + 1) + ( " " * (10 - len(str((i // 15) + 1))) ) if i % 15 == 0 else ""
formatedText += ... | def enum():
with open('textSource', 'r') as file:
text = file.read()
words = text.split()
formated_text = ''
for (i, word) in enumerate(words):
formated_text += str(i // 15 + 1) + ' ' * (10 - len(str(i // 15 + 1))) if i % 15 == 0 else ''
formated_text += word ... |
"""!
# Trading folder
**This folder contains all the modules related to live trading**
""" | """!
# Trading folder
**This folder contains all the modules related to live trading**
""" |
class Submarine:
depth = 0
horizontal_pos = 0
def down(self, depth):
self.depth += depth
def up(self, depth):
self.depth -= depth
def forward(self, distance):
self.horizontal_pos += distance
def get_depth(self):
return self.depth
def get_horizontal_pos(se... | class Submarine:
depth = 0
horizontal_pos = 0
def down(self, depth):
self.depth += depth
def up(self, depth):
self.depth -= depth
def forward(self, distance):
self.horizontal_pos += distance
def get_depth(self):
return self.depth
def get_horizontal_pos(se... |
# PRAGMA TEST 4 *NOT READY TO GO YET
# Santiago Garcia Arango
def minCost(numProjects, projectId, bid):
# Vector of ids needed [0, 1, 2, 3, ..., N]
vector_of_ids = []
for i in range(numProjects):
vector_of_ids.append(i)
possibilities = []
for i in range(len(vector_of_ids)):
curren... | def min_cost(numProjects, projectId, bid):
vector_of_ids = []
for i in range(numProjects):
vector_of_ids.append(i)
possibilities = []
for i in range(len(vector_of_ids)):
current = []
for j in range(len(projectId)):
if projectId[j] == i:
current.append(... |
#1. Create a greeting for your program.
print("Welcome to the band name generator!")
#2. Ask the user for the city that they grew up in.
city = input("What city did you grow up in? \n")
#3. Ask the user for the name of a pet.
pet = input("What is the name of a pet?\n")
#4. Combine the name of their city and pet and sho... | print('Welcome to the band name generator!')
city = input('What city did you grow up in? \n')
pet = input('What is the name of a pet?\n')
print(f'The name of your band could be the {city} {pet}!') |
N = int(input())
answer = 10**9 + 1
for _ in range(N):
a, p, x = map(int, input().split())
if x - a > 0:
answer = min(answer, p)
if answer == 10**9 + 1:
print(-1)
else:
print(answer) | n = int(input())
answer = 10 ** 9 + 1
for _ in range(N):
(a, p, x) = map(int, input().split())
if x - a > 0:
answer = min(answer, p)
if answer == 10 ** 9 + 1:
print(-1)
else:
print(answer) |
score_sum = 0
#we open the file that we can read
file_names = open('p022_names.txt', 'r')
#we split it on ","
names = file_names.read().split(",")
#we removed the first and last sign (double " ")
for i in range(len(names)):
names[i] = names[i][1:-1]
#we sort all names into alphabetical order
names.sort()
for i in ... | score_sum = 0
file_names = open('p022_names.txt', 'r')
names = file_names.read().split(',')
for i in range(len(names)):
names[i] = names[i][1:-1]
names.sort()
for i in range(len(names)):
sum_letters = []
for j in names[i]:
sum_letters.append(ord(j) - 64)
score_sum += sum(sum_letters) * (i + 1)
p... |
#!/usr/bin/python
#coding:utf8
__author__ = ['markshao']
__version__ = "1.0.2"
def version_number():
return __version__
| __author__ = ['markshao']
__version__ = '1.0.2'
def version_number():
return __version__ |
"""
Discussion:
In a limiting case, when the time constant of the OU process is very long and the
input current is almost flat, we expect the firing rate to decrease and neuron
will spike more regularly. So as the OU process time constant increases, we expect
firing rate and CV_ISI to decrease, if all other parame... | """
Discussion:
In a limiting case, when the time constant of the OU process is very long and the
input current is almost flat, we expect the firing rate to decrease and neuron
will spike more regularly. So as the OU process time constant increases, we expect
firing rate and CV_ISI to decrease, if all other paramet... |
#!/usr/bin/env python3
with open('27_B.txt') as f:
triades = [sorted([int(y) for y in x.split()]) for x in f.readlines()[1:]]
k, min_diff, s = 109, 20000, 0
for triade in triades:
s += triade[2]
max_mid = triade[2] - triade[1]
max_min = triade[2] - triade[0]
if max_mid % k != 0:
min_diff = min(min_diff, max_mid... | with open('27_B.txt') as f:
triades = [sorted([int(y) for y in x.split()]) for x in f.readlines()[1:]]
(k, min_diff, s) = (109, 20000, 0)
for triade in triades:
s += triade[2]
max_mid = triade[2] - triade[1]
max_min = triade[2] - triade[0]
if max_mid % k != 0:
min_diff = min(min_diff, max_mi... |
# -*- coding: utf-8 -*-
SERVER_INDEX = 'serverIndex'
"""
OpenAPI has support for multiple servers (read as base URLs), but the OMS
doesn't. To account for this, a choice must be made when converting.
"""
| server_index = 'serverIndex'
"\nOpenAPI has support for multiple servers (read as base URLs), but the OMS\ndoesn't. To account for this, a choice must be made when converting.\n" |
#$Id: $
def generate(env, **kw):
if not kw.get('depsOnly',0):
env.Tool('addLibrary', library = ['pulsePhase'])
env.Tool('pulsarDbLib')
env.Tool('st_appLib')
env.Tool('st_facilitiesLib')
env.Tool('timeSystemLib')
env.Tool('tipLib')
def exists(env):
return 1
| def generate(env, **kw):
if not kw.get('depsOnly', 0):
env.Tool('addLibrary', library=['pulsePhase'])
env.Tool('pulsarDbLib')
env.Tool('st_appLib')
env.Tool('st_facilitiesLib')
env.Tool('timeSystemLib')
env.Tool('tipLib')
def exists(env):
return 1 |
class Solution:
def countAndSay(self, n: int) -> str:
def read(n):
if n == 1:
return '1'
else:
s = read(n - 1)
curr, cnt = s[0], 1
res = ''
for i in range(1, len(s)):
... | class Solution:
def count_and_say(self, n: int) -> str:
def read(n):
if n == 1:
return '1'
else:
s = read(n - 1)
(curr, cnt) = (s[0], 1)
res = ''
for i in range(1, len(s)):
if s[i] =... |
# %%
#######################################
def remove_falsey_values_in_array(lst: list):
"""Removes falsey values such as 0, '', False, None from the list.
Examples:
>>> list_with_falsey = [0, 1, False, 2, '', ' ', 3, 'a', 's', 34, None]\n
>>> remove_falsey_values_in_array(list_with_falsey)\... | def remove_falsey_values_in_array(lst: list):
"""Removes falsey values such as 0, '', False, None from the list.
Examples:
>>> list_with_falsey = [0, 1, False, 2, '', ' ', 3, 'a', 's', 34, None]
>>> remove_falsey_values_in_array(list_with_falsey)
[1, 2, ' ', 3, 'a', 's', 34]
... |
def partition(a, start=0, end=0):
pivot = a[end]
pi = start
for i in range(start, end):
if a[i] <= pivot:
a[i], a[pi] = a[pi], a[i]
pi += 1
a[pi], a[end] = a[end], a[pi]
return pi
def quicksort(a, start = 0, end = 0):
if start < end:
pi = pa... | def partition(a, start=0, end=0):
pivot = a[end]
pi = start
for i in range(start, end):
if a[i] <= pivot:
(a[i], a[pi]) = (a[pi], a[i])
pi += 1
(a[pi], a[end]) = (a[end], a[pi])
return pi
def quicksort(a, start=0, end=0):
if start < end:
pi = partition(a,... |
class Indicator_Image_Control(object):
""" Handle update logic for animations """
def update(self, indicator_image):
pass
class Image_Pause_Control(Indicator_Image_Control):
""" Handle pauses """
def __init__(self, frames):
self.frames = frames
self._current_frame = 0
de... | class Indicator_Image_Control(object):
""" Handle update logic for animations """
def update(self, indicator_image):
pass
class Image_Pause_Control(Indicator_Image_Control):
""" Handle pauses """
def __init__(self, frames):
self.frames = frames
self._current_frame = 0
def... |
# URI Online Judge 1688
N = int(input())
for n in range(N):
S = int(input())
soma = 0
for s in range(S):
if s%2 == 0: soma += 1
elif s%2 == 1: soma -= 1
print(soma)
| n = int(input())
for n in range(N):
s = int(input())
soma = 0
for s in range(S):
if s % 2 == 0:
soma += 1
elif s % 2 == 1:
soma -= 1
print(soma) |
#### Data ####
datapath = "COVID-19"
#### Database ####
db_host = "localhost"
db_port = "3306"
db_scheme = "bmbf_formular"
db_prefix = "bmbf_"
db_user = "root"
db_password = ""
#### DO NOT CHANGE ####
if __name__ == "__main__":
exit(1) | datapath = 'COVID-19'
db_host = 'localhost'
db_port = '3306'
db_scheme = 'bmbf_formular'
db_prefix = 'bmbf_'
db_user = 'root'
db_password = ''
if __name__ == '__main__':
exit(1) |
'''for i in range(1, 7):
print(i)
print('Fim')'''
'''for i in range(6, 0, -1):
print(i)
print('FIM')'''
for i in range(0, 7, 2):
print(i)
print('FIM')
| """for i in range(1, 7):
print(i)
print('Fim')"""
"for i in range(6, 0, -1):\n print(i)\nprint('FIM')"
for i in range(0, 7, 2):
print(i)
print('FIM') |
class Solution(object):
def uniquePathsWithObstacles(self, grid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
if not grid:
return 0
if grid[0][0] == 1:
return 0
dp = [[0] * len(grid[0]) for _ in range(0, len(grid))]
dp[0][0] = 1 if grid[0][0] == 0 else 0
for... | class Solution(object):
def unique_paths_with_obstacles(self, grid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
if not grid:
return 0
if grid[0][0] == 1:
return 0
dp = [[0] * len(grid[0]) for _ in range(0, len(grid))]
dp[0][0]... |
class CGXFormatter:
def __init__(self):
self.BASE_INDENT = 4
self.inside_string = False
self.total_indent = 0
self.new_line = True
self.nb_lines = 0
def read_lines(self):
self.nb_lines = int(input())
for _ in range(self.nb_lines):
line = input... | class Cgxformatter:
def __init__(self):
self.BASE_INDENT = 4
self.inside_string = False
self.total_indent = 0
self.new_line = True
self.nb_lines = 0
def read_lines(self):
self.nb_lines = int(input())
for _ in range(self.nb_lines):
line = inpu... |
"""
When make reliable means, we need to neglect best and worst value. For example, when making average score on athletes we need this option.
So, this algorithms, fix some percentage to neglect when making mean. For example, if you suggest 20%, it will neglect best 10% value, and
worst 10% value.
This algorithm gets ... | """
When make reliable means, we need to neglect best and worst value. For example, when making average score on athletes we need this option.
So, this algorithms, fix some percentage to neglect when making mean. For example, if you suggest 20%, it will neglect best 10% value, and
worst 10% value.
This algorithm gets ... |
def test_roles_dict():
"""
A dictionary of roles for use in testing the dynamic User class.
This dictionary represents the roles that will be in RaxKeystone.roles.
"""
return {
"admin": ["admin_role_1", "admin_role_2"],
"support": ["support_role_1"]
}
| def test_roles_dict():
"""
A dictionary of roles for use in testing the dynamic User class.
This dictionary represents the roles that will be in RaxKeystone.roles.
"""
return {'admin': ['admin_role_1', 'admin_role_2'], 'support': ['support_role_1']} |
#
# PySNMP MIB module RBTWS-EXTERNAL-SERVER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RBTWS-EXTERNAL-SERVER-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:45:13 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, value_range_constraint, value_size_constraint, single_value_constraint) ... |
n = 1e5
print(int(n))
st = "a"*int(n)
print(st)
| n = 100000.0
print(int(n))
st = 'a' * int(n)
print(st) |
class ModelUnknown(Exception):
pass
class AsyncMismatch(Exception):
pass
class InvalidInput(Exception):
pass
| class Modelunknown(Exception):
pass
class Asyncmismatch(Exception):
pass
class Invalidinput(Exception):
pass |
def plot(processes):
"""
Displays the given processes in a tabular format
Args:
processes (Array : :class:`src.utils.process.Process`): processed processes.
"""
print('| PID | BURST_TIME | ARRIVAL_TIME | PRIORITY || RESPONSE_TIME | WAITING_TIME | TURNAROUND_TIME | RETURN_TIME |')
for... | def plot(processes):
"""
Displays the given processes in a tabular format
Args:
processes (Array : :class:`src.utils.process.Process`): processed processes.
"""
print('| PID | BURST_TIME | ARRIVAL_TIME | PRIORITY || RESPONSE_TIME | WAITING_TIME | TURNAROUND_TIME | RETURN_TIME |')
for p... |
'''
Given a linked list of size N.
Reverse every k nodes (where k is an input to the function) in the linked list.
'''
class Node:
# initializing the Node
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Initializing the LinkedList
def __init... | """
Given a linked list of size N.
Reverse every k nodes (where k is an input to the function) in the linked list.
"""
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def insert_at_end(self, ... |
a = int(input())
while a != 0:
if a % 2 == 1:
a += 1
print(sum(range(a, a+10, 2)))
a = int(input())
| a = int(input())
while a != 0:
if a % 2 == 1:
a += 1
print(sum(range(a, a + 10, 2)))
a = int(input()) |
class dictlist(dict):
"""A python implementation of a dictionary mapping one key to a list of values.
Parameters
----------
See the ``update`` method.
Example
-------
>>> from dictlist import dictlist
>>> dl = dictlist()
>>> dl['A']='a'
>>> dl.update({'B':'b','C':'c'})
>>> ... | class Dictlist(dict):
"""A python implementation of a dictionary mapping one key to a list of values.
Parameters
----------
See the ``update`` method.
Example
-------
>>> from dictlist import dictlist
>>> dl = dictlist()
>>> dl['A']='a'
>>> dl.update({'B':'b','C':'c'})
>>> ... |
__author__ = 'student'
A = set('0123456789')
B = set('02468')
C = set('12345')
D = set('56789')
E = ((A - B)&(C - D)) | ((D-A)&(B-C))
print(E) | __author__ = 'student'
a = set('0123456789')
b = set('02468')
c = set('12345')
d = set('56789')
e = A - B & C - D | D - A & B - C
print(E) |
def improve_initiative():
return 4
def new_ac_selector(player):
def _get_ac_abil_mod(self):
if not self.wearing_heavy():
return max(map(
lambda x: player.get_abil_mod,
name.DEX, name.INT, name.CON))
else:
return max(map(
la... | def improve_initiative():
return 4
def new_ac_selector(player):
def _get_ac_abil_mod(self):
if not self.wearing_heavy():
return max(map(lambda x: player.get_abil_mod, name.DEX, name.INT, name.CON))
else:
return max(map(lambda x: player.get_abil_mod, name.DEX, name.INT))... |
# https://www.hackerrank.com/challenges/time-conversion/problem
def timeConversion(s):
hour = int(s[0:2])
if s[-2:] == "AM":
if s[0:2] == "12":
res = f"0{hour - 12}{s[2:8]}"
return res
else:
return s[0:8]
else:
if s[0:2] == "12":
... | def time_conversion(s):
hour = int(s[0:2])
if s[-2:] == 'AM':
if s[0:2] == '12':
res = f'0{hour - 12}{s[2:8]}'
return res
else:
return s[0:8]
elif s[0:2] == '12':
return s[0:8]
else:
res = f'{hour + 12}{s[2:8]}'
return res |
# Nomal method
numbers = [1, 2, 3, 4]
double_numbers = []
for number in numbers:
doubled = number * 2
double_numbers.append(doubled)
print(double_numbers)
# Using map in build function
def double(x):
return x * 2
doubled_list_functional = list(map(double, numbers))
print(doubled_list_functional) | numbers = [1, 2, 3, 4]
double_numbers = []
for number in numbers:
doubled = number * 2
double_numbers.append(doubled)
print(double_numbers)
def double(x):
return x * 2
doubled_list_functional = list(map(double, numbers))
print(doubled_list_functional) |
class MyType:
pass
MyType
MyType()
MyType == MyType() | class Mytype:
pass
MyType
my_type()
MyType == my_type() |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class CouchbaseRecoverJobParams(object):
"""Implementation of the 'CouchbaseRecoverJobParams' model.
Contains any additional couchbase environment specific params for the
recover job.
Attributes:
append_documents (bool): Whether to appen... | class Couchbaserecoverjobparams(object):
"""Implementation of the 'CouchbaseRecoverJobParams' model.
Contains any additional couchbase environment specific params for the
recover job.
Attributes:
append_documents (bool): Whether to append documents into the bucket
at the destinatio... |
#coding=utf-8
class LeagueListDTO:
def __init__(self, jsonData):
self.leagueId = jsonData["leagueId"] if "leagueId" in jsonData else None
self.tier = jsonData["tier"] if "tier" in jsonData else None
self.entries = []
if "entries" in jsonData:
for item in jsonData["entrie... | class Leaguelistdto:
def __init__(self, jsonData):
self.leagueId = jsonData['leagueId'] if 'leagueId' in jsonData else None
self.tier = jsonData['tier'] if 'tier' in jsonData else None
self.entries = []
if 'entries' in jsonData:
for item in jsonData['entries']:
... |
def parse(raw_instruction):
parsed = raw_instruction.split(' ')
return {
'operation': parsed[0],
'value': int(parsed[1][1:]) if parsed[1].startswith('+') else int(parsed[1]),
'executedCount': 0
}
def run(instructions):
for instruction in instructions:
instruction['execu... | def parse(raw_instruction):
parsed = raw_instruction.split(' ')
return {'operation': parsed[0], 'value': int(parsed[1][1:]) if parsed[1].startswith('+') else int(parsed[1]), 'executedCount': 0}
def run(instructions):
for instruction in instructions:
instruction['executedCount'] = 0
accumulator ... |
#!/usr/bin/env python3
EXIT_VALID = 0
EXIT_KEYBOARD = 1
EXIT_UNKNOWN = 2
EXIT_CLI = 64
EXIT_INPUT_FORMAT = 65
EXIT_INPUT_NOT_FOUND = 66
EXIT_SYSERR = 71
EXIT_CANT_OUTPUT = 73
# EXIT_IOERR = 74
class MyException(Exception):
def __init__(self, msg: str, ecode: int):
self.msg = msg
self.ecode = ec... | exit_valid = 0
exit_keyboard = 1
exit_unknown = 2
exit_cli = 64
exit_input_format = 65
exit_input_not_found = 66
exit_syserr = 71
exit_cant_output = 73
class Myexception(Exception):
def __init__(self, msg: str, ecode: int):
self.msg = msg
self.ecode = ecode
return
def __str__(self):
... |
class TypeValidationEventArgs(EventArgs):
"""
Provides data for the System.Windows.Forms.MaskedTextBox.TypeValidationCompleted event.
TypeValidationEventArgs(validatingType: Type,isValidInput: bool,returnValue: object,message: str)
"""
@staticmethod
def __new__(self, validatingType, isVali... | class Typevalidationeventargs(EventArgs):
"""
Provides data for the System.Windows.Forms.MaskedTextBox.TypeValidationCompleted event.
TypeValidationEventArgs(validatingType: Type,isValidInput: bool,returnValue: object,message: str)
"""
@staticmethod
def __new__(self, validatingType, isValidInput, re... |
# String
s = "I am a string."
print(type(s)) # Will say str
# Boolean
yes = True # Boolean True
print(type(yes))
no = False
print(type(no)) # Boolean false
print(" ")
# Lit -- ordered and changeable
alpha_list = ["a", "b", "c"] # List initialization
print(type(alpha_list)) ... | s = 'I am a string.'
print(type(s))
yes = True
print(type(yes))
no = False
print(type(no))
print(' ')
alpha_list = ['a', 'b', 'c']
print(type(alpha_list))
print(type(alpha_list[0]))
alpha_list.append('d')
print(alpha_list)
print(' ')
alpha_tuple = ('a', 'b', 'c')
print(type(alpha_tuple))
print(' ')
try:
alpha_tuple... |
# Copyright 2018- The Pixie Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_file')
def linux_headers():
http_file(name='timeconst_100', urls=['https://storage.googleapis.com/pixie-dev-public/timeconst_100.h'], sha256='082496c45ab93af811732da56000caf5ffc9e6734ff633a2b348291f160ceb7e', downloaded_file_path='timeconst_100.h')
htt... |
OPEN = 'Open'
IN_PROGRESS = 'In Progress'
DUE_SOON = 'Due Soon'
OVERDUE = 'Overdue'
CLOSED = 'Closed'
| open = 'Open'
in_progress = 'In Progress'
due_soon = 'Due Soon'
overdue = 'Overdue'
closed = 'Closed' |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Solution:
def display(self, head):
current = head
while current:
print(current.data, end=' ')
current = current.next
# Solution 1
def insert(self, head, data):
... | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Solution:
def display(self, head):
current = head
while current:
print(current.data, end=' ')
current = current.next
def insert(self, head, data):
if head == None... |
class ElementIntersectsFilter(ElementSlowFilter, IDisposable):
""" A base class for filters used to match elements which intersect with geometry. """
def Dispose(self):
""" Dispose(self: ElementFilter,A_0: bool) """
pass
@staticmethod
def IsCategorySupported(element):
... | class Elementintersectsfilter(ElementSlowFilter, IDisposable):
""" A base class for filters used to match elements which intersect with geometry. """
def dispose(self):
""" Dispose(self: ElementFilter,A_0: bool) """
pass
@staticmethod
def is_category_supported(element):
"""
I... |
class ApiCollection:
items = []
limit = 10
offset = 0
next_href = None
| class Apicollection:
items = []
limit = 10
offset = 0
next_href = None |
dataset_type = 'CocoDataset'
data_root = '../data/'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', with_bbox=True, with_mask=True),
dict(type='Resize', img_scale=[(480, 480), (... | dataset_type = 'CocoDataset'
data_root = '../data/'
img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True, with_mask=True), dict(type='Resize', img_scale=[(480, 480), (960, 960)], keep_r... |
class DataStructure:
def __init__(self, df, target_column, dataset_type_column='dataset_type'):
self.df = df.copy()
self.dataset_type_column = dataset_type_column
self.target_column = target_column
self.feature_columns = set(self.df.columns) - set([self.target_column, self.dataset_ty... | class Datastructure:
def __init__(self, df, target_column, dataset_type_column='dataset_type'):
self.df = df.copy()
self.dataset_type_column = dataset_type_column
self.target_column = target_column
self.feature_columns = set(self.df.columns) - set([self.target_column, self.dataset_t... |
"""This is gramatically correct, but it's still a SyntaxError"""
yield from [1, 2] # [yield-outside-function]
LAMBDA_WITH_YIELD = lambda: (yield from [1, 2])
| """This is gramatically correct, but it's still a SyntaxError"""
yield from [1, 2]
lambda_with_yield = lambda : (yield from [1, 2]) |
#! /usr/bin/env python3
## create a dictionary
switch = {'hostname': 'sw1', 'ip':'10.0.1.1', 'version': '1.2', 'vendor': 'cisco'}
## display parts of the dictionary
print(switch['hostname'])
print(switch['ip'])
## request a fake key
#print(switch['lynx'])
## request a fake key with .get() method
print("first key tes... | switch = {'hostname': 'sw1', 'ip': '10.0.1.1', 'version': '1.2', 'vendor': 'cisco'}
print(switch['hostname'])
print(switch['ip'])
print('first key test - ,get()')
print(switch.get('lynx'))
print(switch.get('lynx', 'THE KEY IS IN ANOTHER CASTLE!'))
print(switch.get('version'))
print('Fourth test - .Keys()')
print(switch... |
#
# Copyright (c) 2017 Joy Diamond. All rights reserved.
#
@gem('Topaz.Cache')
def gem():
require_gem('Topaz.Core')
require_gem('Topaz.CacheSupport')
require_gem('Topaz.GeneratedConjureQuadruple')
require_gem('Topaz.OldConjureQuadruple')
show = 0
#
# Specific instances
#
eig... | @gem('Topaz.Cache')
def gem():
require_gem('Topaz.Core')
require_gem('Topaz.CacheSupport')
require_gem('Topaz.GeneratedConjureQuadruple')
require_gem('Topaz.OldConjureQuadruple')
show = 0
eight = conjure_number('eight', 8)
five = conjure_number('five', 5)
four = conjure_number('four', 4)... |
simple_tenant_usage_data = \
[{
u'total_volume_gb_usage': 480.0,
u'total_memory_mb_usage': 393216.0,
u'total_vcpus_usage': 192.0,
u'start': u'2012-09-05 00:00:00',
u'tenant_id': u'e638ade19b0de826ee1391ee8e84dd7e',
u'stop': u'2012-09-06 00:00:00',
u'total_hours': 48.0,
u'total_local_gb_u... | simple_tenant_usage_data = [{u'total_volume_gb_usage': 480.0, u'total_memory_mb_usage': 393216.0, u'total_vcpus_usage': 192.0, u'start': u'2012-09-05 00:00:00', u'tenant_id': u'e638ade19b0de826ee1391ee8e84dd7e', u'stop': u'2012-09-06 00:00:00', u'total_hours': 48.0, u'total_local_gb_usage': 768.0, u'total_images_gb_usa... |
#
# PySNMP MIB module Nortel-MsCarrier-MscPassport-IpxMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-MsCarrier-MscPassport-IpxMIB
# Produced by pysmi-0.3.4 at Wed May 1 14:30:40 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Usi... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_range_constraint, value_size_constraint, single_value_constraint, constraints_union) ... |
#
# PySNMP MIB module RAQMON-RDS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RAQMON-RDS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:43:43 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, value_size_constraint, value_range_constraint, single_value_constraint) ... |
class Solution:
def subdomainVisits(self, cpdomains):
"""
:type cpdomains: List[str]
:rtype: List[str]
"""
domains = collections.Counter()
subDomains = collections.Counter()
# O(N)
for item in cpdomains:
count, domain = item.split(' ')
... | class Solution:
def subdomain_visits(self, cpdomains):
"""
:type cpdomains: List[str]
:rtype: List[str]
"""
domains = collections.Counter()
sub_domains = collections.Counter()
for item in cpdomains:
(count, domain) = item.split(' ')
su... |
# coding: utf-8
"""
Functional tests for the public app
"""
class TestPublicViews:
""" Test the public app views """
def test_index_returns_200(self, testapp):
""" Index page """
client = testapp.get('/')
assert client.status_code == 200
| """
Functional tests for the public app
"""
class Testpublicviews:
""" Test the public app views """
def test_index_returns_200(self, testapp):
""" Index page """
client = testapp.get('/')
assert client.status_code == 200 |
ORIG_W, ORIG_H = (800, 500)
RENDER_W, RENDER_H = ORIG_W, ORIG_H
def adjwidth (x):
return (RENDER_W * x) / ORIG_W
def adjheight (y):
return (RENDER_H * y) / ORIG_H
def adjpos (x, y):
return (adjwidth (x), adjheight (y))
def adjrect (a, b, c, d):
return (adjwidth (a), adjheight (b), adjwidth (c), adjw... | (orig_w, orig_h) = (800, 500)
(render_w, render_h) = (ORIG_W, ORIG_H)
def adjwidth(x):
return RENDER_W * x / ORIG_W
def adjheight(y):
return RENDER_H * y / ORIG_H
def adjpos(x, y):
return (adjwidth(x), adjheight(y))
def adjrect(a, b, c, d):
return (adjwidth(a), adjheight(b), adjwidth(c), adjwidth(d)... |
# -*- coding: utf-8 -*-
class KeyNotFound(Exception):
pass
class InvalidUrl(Exception):
pass
class InvalidAlias(Exception):
pass
class InvalidGatewayResponse(Exception):
pass
| class Keynotfound(Exception):
pass
class Invalidurl(Exception):
pass
class Invalidalias(Exception):
pass
class Invalidgatewayresponse(Exception):
pass |
class Queries:
GET_BOOKS_COUNT = 'SELECT COUNT(*) FROM moscow_books.book;'
GET_USER_HISTORY_BOOK_IDS = 'SELECT catalogueRecordID FROM moscow_books.books_issuance WHERE readerID=%s;'
GET_BOOK = 'SELECT recId AS id, aut AS author, title FROM moscow_books.book WHERE recId=%s;'
GET_BOOK_NEWCOMER = 'SELECT ... | class Queries:
get_books_count = 'SELECT COUNT(*) FROM moscow_books.book;'
get_user_history_book_ids = 'SELECT catalogueRecordID FROM moscow_books.books_issuance WHERE readerID=%s;'
get_book = 'SELECT recId AS id, aut AS author, title FROM moscow_books.book WHERE recId=%s;'
get_book_newcomer = 'SELECT r... |
def count_digits(n):
if(n == 0):
return n
if(n < 0):
n *= -1
if(n < 10):
return 1
return 1 + count_digits(n/10) | def count_digits(n):
if n == 0:
return n
if n < 0:
n *= -1
if n < 10:
return 1
return 1 + count_digits(n / 10) |
class Example:
'Common base class for all employee'
def printValue(self):
print(Example.__doc__)
print(Example.__name__)
print(Example.__dict__)
print(Example.__module__)
print(Example.__bases__)
example = Example()
example.printValue()
| class Example:
"""Common base class for all employee"""
def print_value(self):
print(Example.__doc__)
print(Example.__name__)
print(Example.__dict__)
print(Example.__module__)
print(Example.__bases__)
example = example()
example.printValue() |
default_excluded_paths = ['/health/', '/api/notify/']
def excluded_path(path, excluded_paths):
excl_paths = excluded_paths.split(',') + default_excluded_paths
return (
path and
any([p for p in excl_paths if path.startswith(p)]))
| default_excluded_paths = ['/health/', '/api/notify/']
def excluded_path(path, excluded_paths):
excl_paths = excluded_paths.split(',') + default_excluded_paths
return path and any([p for p in excl_paths if path.startswith(p)]) |
edad = 17
hambre = edad
dinero = 2000
helados_consumidos = 0
precio_helado = 100
while (hambre) < 85 and (dinero-precio_helado) > 0:
dinero = dinero - precio_helado
precio_helado = precio_helado + (precio_helado * 0.2)
helados_consumidos = helados_consumidos + 1
hambre = hambre + edad
if (hambre + ... | edad = 17
hambre = edad
dinero = 2000
helados_consumidos = 0
precio_helado = 100
while hambre < 85 and dinero - precio_helado > 0:
dinero = dinero - precio_helado
precio_helado = precio_helado + precio_helado * 0.2
helados_consumidos = helados_consumidos + 1
hambre = hambre + edad
if hambre + edad >... |
CONFIG_VERSION = 1
config = None
class Config:
def __init__(self, obj):
if 'CONFIG_VERSION' not in obj:
raise Exception("Configuration file must contain 'CONFIG_VERSION' field")
if obj['CONFIG_VERSION'] != CONFIG_VERSION:
raise Exception("Expected CONFIG_VERSION to be %s fo... | config_version = 1
config = None
class Config:
def __init__(self, obj):
if 'CONFIG_VERSION' not in obj:
raise exception("Configuration file must contain 'CONFIG_VERSION' field")
if obj['CONFIG_VERSION'] != CONFIG_VERSION:
raise exception('Expected CONFIG_VERSION to be %s fo... |
# Copyright 2016 Nidium Inc. All rights reserved.
# Use of this source code is governed by a MIT license
# that can be found in the LICENSE file.
{
'targets': [{
'target_name': 'generate-embed',
'type': 'none',
'actions': [
{
'action_name': 'Generating embed',
... | {'targets': [{'target_name': 'generate-embed', 'type': 'none', 'actions': [{'action_name': 'Generating embed', 'inputs': ['<(nidium_src_path)/Tools/dir2nvfs.cpp', '<(nidium_tools_path)dir2nvfs', '<!@(find <(nidium_embed_dir) -type f |sed \'s/.*/"&"/\')'], 'outputs': ['<(nidium_embed_bin)'], 'action': ['<@(nidium_tools_... |
class Board:
def __init__(self, boardInputFile):
# initialise board variables
self.sizeH, self.sizeV, self.nWallSquares, self.wallCoordinates, self.nBoxes, \
self.boxCoordinates, self.nstorLocations, self.storCoordinates, self.playerLoc = \
None, None, None, None, None, None, None, None, None
self.boardInpu... | class Board:
def __init__(self, boardInputFile):
(self.sizeH, self.sizeV, self.nWallSquares, self.wallCoordinates, self.nBoxes, self.boxCoordinates, self.nstorLocations, self.storCoordinates, self.playerLoc) = (None, None, None, None, None, None, None, None, None)
(self.boardInputFile, self.boardGr... |
def displayGrid(src):
state = src.copy()
state[state.index(-1)] = ' '
print(state[0], state[1], state[2])
print(state[3], state[4], state[5])
print(state[6], state[7], state[8])
print()
def gen(state, m, b):
temp = state.copy()
if m == 'u':
temp[b... | def display_grid(src):
state = src.copy()
state[state.index(-1)] = ' '
print(state[0], state[1], state[2])
print(state[3], state[4], state[5])
print(state[6], state[7], state[8])
print()
def gen(state, m, b):
temp = state.copy()
if m == 'u':
(temp[b - 3], temp[b]) = (temp[b], te... |
DATABASES = {
'default': {
'NAME' : ':memory:',
'ENGINE': 'django.db.backends.sqlite3',
'SUPPORTS_TRANSACTIONS' : 'False'
}
}
INSTALLED_APPS = ('django.contrib.auth',
'django.contrib.contenttypes',
'django_app',)
SECRET_KEY = "dmqsTestSecretKey"
| databases = {'default': {'NAME': ':memory:', 'ENGINE': 'django.db.backends.sqlite3', 'SUPPORTS_TRANSACTIONS': 'False'}}
installed_apps = ('django.contrib.auth', 'django.contrib.contenttypes', 'django_app')
secret_key = 'dmqsTestSecretKey' |
"""
Part 1
------
[1,1] => 2
[] => 0
[0] => 0
[1,1,1,0,1,1,0,1] => 3
[1,0,1,1,0,1,1,1] => 3
"""
def longestConsecutive(list):
""" assume list is a list """
if len(list) == 0:
return 0
longest = 0
currentlen = 0
for element in list:
if element == 1:
currentlen += 1
... | """
Part 1
------
[1,1] => 2
[] => 0
[0] => 0
[1,1,1,0,1,1,0,1] => 3
[1,0,1,1,0,1,1,1] => 3
"""
def longest_consecutive(list):
""" assume list is a list """
if len(list) == 0:
return 0
longest = 0
currentlen = 0
for element in list:
if element == 1:
currentlen += 1
... |
#!/usr/bin/env python3.8
def starred_return():
my_list = ["value2", "value3"]
return "value1", *my_list
def starred_yield():
my_list = ["value2", "value3"]
yield "value1", *my_list
# output
#!/usr/bin/env python3.8
def starred_return():
my_list = ["value2", "value3"]
return "value1", *... | def starred_return():
my_list = ['value2', 'value3']
return ('value1', *my_list)
def starred_yield():
my_list = ['value2', 'value3']
yield ('value1', *my_list)
def starred_return():
my_list = ['value2', 'value3']
return ('value1', *my_list)
def starred_yield():
my_list = ['value2', 'value... |
print("""Welcome! Are you completely new to programming?
about why and how to get started with Python. Fortunately
an experienced programmer in any programming language
(whatever it may be) can pick up Python very quickly.
Its also easy for beginners to use and learn, so jump in!""") | print('Welcome! Are you completely new to programming?\nabout why and how to get started with Python. Fortunately\nan experienced programmer in any programming language\n(whatever it may be) can pick up Python very quickly.\nIts also easy for beginners to use and learn, so jump in!') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.