content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Copyright (c) 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Classes in this package define additional actions that need to be taken to run a
test under some kind of runtime error detection tool.
The interface ... | """
Classes in this package define additional actions that need to be taken to run a
test under some kind of runtime error detection tool.
The interface is intended to be used as follows.
1. For tests that simply run a native process (i.e. no activity is spawned):
Call tool.CopyFiles(presentation.device).
Prepend te... |
'''
Created on Dec 12, 2014
@author: MP
'''
| """
Created on Dec 12, 2014
@author: MP
""" |
def get_data(fold=0):
return (MImageItemList.from_df(df, path=TRAIN+"/train", cols='image_id')
.split_by_idx(df.index[df.split == fold].tolist())
.label_from_df(cols=['prim_gleason','secon_gleason'])
.transform(get_transforms(flip_vert=True,max_rotate=15),size=sz,padding_mode='zeros')
.datab... | def get_data(fold=0):
return MImageItemList.from_df(df, path=TRAIN + '/train', cols='image_id').split_by_idx(df.index[df.split == fold].tolist()).label_from_df(cols=['prim_gleason', 'secon_gleason']).transform(get_transforms(flip_vert=True, max_rotate=15), size=sz, padding_mode='zeros').databunch(bs=bs, num_workers... |
legend = [
("Analog", "analog"),
("I2C", "i2c"),
("GPIO", "gpio"),
("Touch", "touch"),
("PWM", "pwm"),
("Power", "pwr"),
("Ground", "gnd"),
]
# Pinlabels
left_header = [
[
("0", "gpio"),
("A0", "analog"),
("MISO", "comms"),
],
[
("1", "gpio"),
... | legend = [('Analog', 'analog'), ('I2C', 'i2c'), ('GPIO', 'gpio'), ('Touch', 'touch'), ('PWM', 'pwm'), ('Power', 'pwr'), ('Ground', 'gnd')]
left_header = [[('0', 'gpio'), ('A0', 'analog'), ('MISO', 'comms')], [('1', 'gpio'), ('MOSI', 'comms', {'body': {'x': 92}})], [('2', 'gpio'), ('A1', 'analog'), ('SCLK', 'comms')], [... |
# Ctrl+K+C to comment a line, Ctrl+K+U to uncomment a line
first_name = input("What is your first name? ")
last_name = input("What is your last name? ")
print(first_name + last_name)
print("Hello " + first_name.capitalize() + " " + last_name.capitalize())
print()
sentence = "The dog is named Daisy"
print(sentence.uppe... | first_name = input('What is your first name? ')
last_name = input('What is your last name? ')
print(first_name + last_name)
print('Hello ' + first_name.capitalize() + ' ' + last_name.capitalize())
print()
sentence = 'The dog is named Daisy'
print(sentence.upper())
print(sentence.lower())
print(sentence.capitalize())
pr... |
class BingoBoardPlace:
def __init__(self, number: int):
self.number = number
self.selected: bool = False
class BingoBoard:
# 5x5 grid
# data must include rows and columns -> [ [0, 0, 0], [0, 0, 0], [0, 0, 0] ]
def __init__(self, data: []):
self.data = []
self.chosen_num... | class Bingoboardplace:
def __init__(self, number: int):
self.number = number
self.selected: bool = False
class Bingoboard:
def __init__(self, data: []):
self.data = []
self.chosen_numbers = []
self.result = -1
self.bingo_width = 0
for row in data:
... |
velocidadkms = 0
velocidadms = 0
distancia = float(input("ingrese la distancia recorrida en km"))
tiempo = float(input("ingrese el tiempo transcurrido en h"))
velocidadkms= distancia/tiempo
print("La velocidad en km/h es: ", velocidadkms)
velocidadms = (velocidadkms)*10/36
print("La velocidad en m/s es: ", velocidadms)... | velocidadkms = 0
velocidadms = 0
distancia = float(input('ingrese la distancia recorrida en km'))
tiempo = float(input('ingrese el tiempo transcurrido en h'))
velocidadkms = distancia / tiempo
print('La velocidad en km/h es: ', velocidadkms)
velocidadms = velocidadkms * 10 / 36
print('La velocidad en m/s es: ', velocid... |
def decode(cipher, rails):
cipher_len = len(cipher)
rail = [['\n' for i in range(len(cipher)) ] for j in range(rails)]
is_going_down = False
row, col = 0,0
for i in range(len(cipher)):
if row == 0:
is_going_down = True
elif row == rails -1:
is_going_d... | def decode(cipher, rails):
cipher_len = len(cipher)
rail = [['\n' for i in range(len(cipher))] for j in range(rails)]
is_going_down = False
(row, col) = (0, 0)
for i in range(len(cipher)):
if row == 0:
is_going_down = True
elif row == rails - 1:
is_going_down ... |
#!/usr/bin/env python3
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
a = list(ransomNote)
b = list(magazine)
try:
for i in a:
b.remove(i)
return True
except:
return False | class Solution:
def can_construct(self, ransomNote: str, magazine: str) -> bool:
a = list(ransomNote)
b = list(magazine)
try:
for i in a:
b.remove(i)
return True
except:
return False |
#!/usr/bin/python3
#------------------------------------------------------------------------------
# First Solution
#------------------------------------------------------------------------------
class Solution:
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
... | class Solution:
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
water = 0
water_differences1 = [0] * len(height)
trapped1 = []
curr = 0
beg = 0
for i in range(len(height)):
if height[i] >= curr:
... |
__author__ = 'raymond'
class TradingDataRowParser:
def __init__(self, spacing):
self.spacing = spacing
def split_by_ticker_symbol(self, row):
for ticker_start_index in range(0, len(row), self.spacing):
yield row[ticker_start_index:ticker_start_index + self.spacing], ticker_start_index
| __author__ = 'raymond'
class Tradingdatarowparser:
def __init__(self, spacing):
self.spacing = spacing
def split_by_ticker_symbol(self, row):
for ticker_start_index in range(0, len(row), self.spacing):
yield (row[ticker_start_index:ticker_start_index + self.spacing], ticker_start_... |
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2020 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the full list of names)
#
# Released under t... | """HOLE Analysis --- :mod:`MDAnalysis.analysis.hole2.templates`
=====================================================================================
:Author: Lily Wang
:Year: 2020
:Copyright: GNU Public License v3
.. versionadded:: 1.0
Templates used in :mod:`MDAnalysis.analysis.hole2.hole`
"""
exe_err = 'HOLE bina... |
"""
419. Roman to Integer
https://www.lintcode.com/problem/roman-to-integer/description
"""
class Solution:
"""
@param s: Roman representation
@return: an integer
"""
def romanToInt(self, s):
# write your code here
CHAR_TO_DIGIT = {
"I": 1,
"V": 5,
... | """
419. Roman to Integer
https://www.lintcode.com/problem/roman-to-integer/description
"""
class Solution:
"""
@param s: Roman representation
@return: an integer
"""
def roman_to_int(self, s):
char_to_digit = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
result... |
def check(num1, num2, num3):
total = num1 + num2 + num3
for i in range(2, total):
if total % i == 0 : return False
return True
def solution(nums):
answer = 0
for i in range(0, len(nums) - 2):
for j in range(i+1, len(nums) - 1):
for k in range(j+1, len(nums)):
... | def check(num1, num2, num3):
total = num1 + num2 + num3
for i in range(2, total):
if total % i == 0:
return False
return True
def solution(nums):
answer = 0
for i in range(0, len(nums) - 2):
for j in range(i + 1, len(nums) - 1):
for k in range(j + 1, len(nums... |
# -*- coding: utf-8 -*-
__version__ = '0.5.3'
__project__ = 'diamond-patterns'
__author__ = 'Ian Dennis Miller'
__email__ = 'iandennismiller@gmail.com'
__url__ = 'https://diamond-patterns.readthedocs.io/'
__repo__ = 'https://github.com/iandennismiller/diamond-patterns/'
__copyright__ = '2019 Ian Dennis Miller'
| __version__ = '0.5.3'
__project__ = 'diamond-patterns'
__author__ = 'Ian Dennis Miller'
__email__ = 'iandennismiller@gmail.com'
__url__ = 'https://diamond-patterns.readthedocs.io/'
__repo__ = 'https://github.com/iandennismiller/diamond-patterns/'
__copyright__ = '2019 Ian Dennis Miller' |
def data():
return """<?xml version='1.0' encoding='UTF-8'?>
<TrainingCenterDatabase xmlns:ns2="http://www.garmin.com/xmlschemas/UserProfile/v2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ns4="http://www.garmin.com/xmlschemas/ProfileExtension/v1"
xmlns:ns... | def data():
return '<?xml version=\'1.0\' encoding=\'UTF-8\'?>\n <TrainingCenterDatabase xmlns:ns2="http://www.garmin.com/xmlschemas/UserProfile/v2"\n xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\n xmlns:ns4="http://www.garmin.com/xmlschemas/ProfileExtension/v1"\n xm... |
"""https://open.kattis.com/problems/baconeggsandspam"""
def solveDay(orders: dict) -> str:
ans = []
for k in sorted(orders.keys()):
res = str(k) + " "
res += " ".join(sorted(orders[k]))
ans.append(res)
return "\n" + "\n".join(ans) + "\n"
if __name__ == '__main__':
ans = ""
... | """https://open.kattis.com/problems/baconeggsandspam"""
def solve_day(orders: dict) -> str:
ans = []
for k in sorted(orders.keys()):
res = str(k) + ' '
res += ' '.join(sorted(orders[k]))
ans.append(res)
return '\n' + '\n'.join(ans) + '\n'
if __name__ == '__main__':
ans = ''
... |
class AisiklError(Exception):
'''The base class for AIS, REST-related exceptions.'''
def __init__(self, *args, **kwargs):
super().__init__(*args)
for key, value in kwargs.items():
setattr(self, key, value)
class AISParseError(AisiklError):
'''We couldn't parse or properly pro... | class Aisiklerror(Exception):
"""The base class for AIS, REST-related exceptions."""
def __init__(self, *args, **kwargs):
super().__init__(*args)
for (key, value) in kwargs.items():
setattr(self, key, value)
class Aisparseerror(AisiklError):
"""We couldn't parse or properly pro... |
class factorial:
def find_fact(self,n):
res = 1
if n < 0:
return -1
elif n == 0:
return 1
else:
for i in range(1,n+1):
res = res*i
return res
| class Factorial:
def find_fact(self, n):
res = 1
if n < 0:
return -1
elif n == 0:
return 1
else:
for i in range(1, n + 1):
res = res * i
return res |
def Gray2Binary(n):
m = 0
while n:
m ^= n
n >>= 1
return m
print(Gray2Binary(4)) | def gray2_binary(n):
m = 0
while n:
m ^= n
n >>= 1
return m
print(gray2_binary(4)) |
class Entitlement_Manager:
@staticmethod
def fetch_entitlements(client,entitlement_type):
conversions = {
"skin_level": "e7c63390-eda7-46e0-bb7a-a6abdacd2433",
"skin_chroma": "3ad1b2b2-acdb-4524-852f-954a76ddae0a",
"agent": "01bb38e1-da47-4e6a-9b3d-945fe4655707",
... | class Entitlement_Manager:
@staticmethod
def fetch_entitlements(client, entitlement_type):
conversions = {'skin_level': 'e7c63390-eda7-46e0-bb7a-a6abdacd2433', 'skin_chroma': '3ad1b2b2-acdb-4524-852f-954a76ddae0a', 'agent': '01bb38e1-da47-4e6a-9b3d-945fe4655707', 'contract_definition': 'f85cb6f7-33e5-4... |
# Flask settings
DEBUG = False
# Flask-restplus settings
RESTPLUS_MASK_SWAGGER = False
# Application settings
# API metadata
API_TITLE = 'Model Asset Exchange Server'
API_DESC = 'An API for serving models'
API_VERSION = '0.1'
# default model
MODELNAME = 'ssrnet_3_3_3_64_1.0_1.0.h5'
DEFAULT_MODEL_PATH = 'assets/{}'.... | debug = False
restplus_mask_swagger = False
api_title = 'Model Asset Exchange Server'
api_desc = 'An API for serving models'
api_version = '0.1'
modelname = 'ssrnet_3_3_3_64_1.0_1.0.h5'
default_model_path = 'assets/{}'.format(MODELNAME)
model_license = 'MIT'
model_meta_data = {'id': 'ssrnet', 'name': 'SSR-Net Facial Ag... |
# find the ceil and floor value of a no. in a sorted array
n = int(input())
a = []
for i in range(n):
a.append(int(input()))
d = int(input())
l = 0
h = n-1
ceil = 0
floor = 0
while(l<=h):
mid = (l+h)//2
if a[mid]<d:
l = mid+1
ceil=a[mid]
elif a[mid]>d:
h = mid-1
floor=a[... | n = int(input())
a = []
for i in range(n):
a.append(int(input()))
d = int(input())
l = 0
h = n - 1
ceil = 0
floor = 0
while l <= h:
mid = (l + h) // 2
if a[mid] < d:
l = mid + 1
ceil = a[mid]
elif a[mid] > d:
h = mid - 1
floor = a[mid]
else:
ceil = floor = a[m... |
_base_ = ['./masktrack_rcnn_r50_fpn_12e_youtubevis2019.py']
model = dict(
detector=dict(
backbone=dict(
type='ResNeXt',
depth=101,
groups=64,
base_width=4,
init_cfg=dict(
type='Pretrained',
checkpoint='open-mmlab://r... | _base_ = ['./masktrack_rcnn_r50_fpn_12e_youtubevis2019.py']
model = dict(detector=dict(backbone=dict(type='ResNeXt', depth=101, groups=64, base_width=4, init_cfg=dict(type='Pretrained', checkpoint='open-mmlab://resnext101_64x4d')), init_cfg=dict(type='Pretrained', checkpoint='https://download.openmmlab.com/mmdetection/... |
LOG_FILE = '/var/lib/pgadmin/pgadmin.log'
SQLITE_PATH = '/var/lib/pgadmin/pgadmin.db'
SESSION_DB_PATH = '/var/lib/pgadmin/sessions'
STORAGE_DIR = '/var/lib/pgadmin/storage'
SERVER_MODE = True
ALLOW_SAVE_PASSWORD = True | log_file = '/var/lib/pgadmin/pgadmin.log'
sqlite_path = '/var/lib/pgadmin/pgadmin.db'
session_db_path = '/var/lib/pgadmin/sessions'
storage_dir = '/var/lib/pgadmin/storage'
server_mode = True
allow_save_password = True |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
# This turns on e.g. the filename-based detection of which
# platforms to include source files on (e.g. files ending in
# _mac... | {'variables': {'chromium_code': 1}, 'targets': [{'target_name': 'user_service_lib', 'type': 'static_library', 'include_dirs': ['../..'], 'sources': ['user_id_map.cc', 'user_id_map.h', 'user_service.cc', 'user_service.h', 'user_shell_client.cc', 'user_shell_client.h'], 'dependencies': ['user_app_manifest', 'user_service... |
# Converts an RGB color value to HSL. Conversion formula
# adapted from http://en.wikipedia.org/wiki/HSL_color_space.
# Assumes r, g, and b are contained in the set [0, 255] and
# returns h, s, and l in the set [0.0, 1.0].
#
# @param {number} r The red color value
# @param {number} g The green color v... | def rgb_to_hsl(r, g, b):
r = r / 255.0
g = g / 255.0
b = b / 255.0
_max = max(r, g, b)
_min = min(r, g, b)
h = 0
s = 0
l = (_max + _min) / 2
if _max == _min:
h = s = 0
else:
d = _max - _min
s = d / (2 - _max - _min) if l > 0.5 else d / (_max + _min)
... |
'''
def candies(n, arr):
count = 0
for i in range(n):
even = True
sum_even = 0
sum_odd = 0
for j in range(n):
if i == j:
continue
if even:
sum_even += arr[j]
even = False
else:
s... | """
def candies(n, arr):
count = 0
for i in range(n):
even = True
sum_even = 0
sum_odd = 0
for j in range(n):
if i == j:
continue
if even:
sum_even += arr[j]
even = False
else:
su... |
class Queue:
#Constructor
def __init__(self):
self.queue = list()
self.maxSize = 8
self.head = 0
self.tail = 0
#Adding elements
def enqueue(self,data):
#Checking if the queue is full
if self.size() >= self.maxSize:
return ("Queue Full")
... | class Queue:
def __init__(self):
self.queue = list()
self.maxSize = 8
self.head = 0
self.tail = 0
def enqueue(self, data):
if self.size() >= self.maxSize:
return 'Queue Full'
self.queue.append(data)
self.tail += 1
return True
def... |
class Defaults(object):
window_size = 7
filter_nums = [100, 100, 100]
filter_sizes = [3, 4, 5]
hidden_sizes = [1200]
hidden_activation = 'relu'
max_vocab_size = 1000000
optimizer = 'adam'
learning_rate = 1e-4
epochs = 20
iobes = True # Map tags to IOBES on input
max_tokens... | class Defaults(object):
window_size = 7
filter_nums = [100, 100, 100]
filter_sizes = [3, 4, 5]
hidden_sizes = [1200]
hidden_activation = 'relu'
max_vocab_size = 1000000
optimizer = 'adam'
learning_rate = 0.0001
epochs = 20
iobes = True
max_tokens = None
encoding = 'utf-8'... |
def average_weight(file_name):
min_value=45
max_value=125
average=0
count_number=0
with open(file_name,"r") as FILE:
list1=list(FILE.read().split())
for i in list1:
i=int(i)
if(min_value<=i<=max_value):
average+=i
count_number+=1
if... | def average_weight(file_name):
min_value = 45
max_value = 125
average = 0
count_number = 0
with open(file_name, 'r') as file:
list1 = list(FILE.read().split())
for i in list1:
i = int(i)
if min_value <= i <= max_value:
average += i
count_number += ... |
#Python program to illustrate
# combining else with while
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
else:
print("In Else Block")
| count = 0
while count < 3:
count = count + 1
print('Hello Geek')
else:
print('In Else Block') |
DEFAULT_IMAGETYPES = {'jpg', 'png', 'apng', 'bmp', 'jpeg', 'gif', 'svg', 'webp'}
ZIP_TYPES = {'zip', 'cbz'}
RAR_TYPES = {'rar', 'cbr'}
_7Z_TYPES = {'7z', 'cb7'}
ASSETS = {
'styles.css',
'scripts.js',
'zenscroll.js',
'menu.svg',
'menu-light.svg',
'scroll.svg',
'scroll-light.svg',
'roboto-... | default_imagetypes = {'jpg', 'png', 'apng', 'bmp', 'jpeg', 'gif', 'svg', 'webp'}
zip_types = {'zip', 'cbz'}
rar_types = {'rar', 'cbr'}
_7_z_types = {'7z', 'cb7'}
assets = {'styles.css', 'scripts.js', 'zenscroll.js', 'menu.svg', 'menu-light.svg', 'scroll.svg', 'scroll-light.svg', 'roboto-bold.woff2', 'roboto-regular.wof... |
# Create a function taking a positive integer as its parameter and returning a string containing the Roman Numeral representation of that integer.
# Modern Roman numerals are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero. In Roman numerals 199... | def solution(n):
if n == 0:
return ''
my_dict = {1000: 'M', 900: 'CM', 500: 'D', 400: 'CD', 100: 'C', 90: 'XC', 50: 'L', 40: 'XL', 10: 'X', 9: 'IX', 5: 'V', 4: 'IV', 1: 'I'}
for i in [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]:
if n - i >= 0:
return my_dict.get(i) + ''... |
def greet_user():
"""Display a simple greeting!"""
print("Hello!")
greet_user()
def greet_user(username):
print("Hello, " + username + "!")
greet_user('Jamey')
def make_pizza(topping='bacon'):
#"""Make a single-topping pizza."""
print("Have a " + topping + " pizza!")
make_pizza()
make_pizza('pepperon... | def greet_user():
"""Display a simple greeting!"""
print('Hello!')
greet_user()
def greet_user(username):
print('Hello, ' + username + '!')
greet_user('Jamey')
def make_pizza(topping='bacon'):
print('Have a ' + topping + ' pizza!')
make_pizza()
make_pizza('pepperoni')
end1 = 'c'
end2 = 'e'
end3 = 'd'
... |
a=0
b=1
n=10
print(1)
for i in range(n):
c=a+b
a=b
b=c
print(c)
| a = 0
b = 1
n = 10
print(1)
for i in range(n):
c = a + b
a = b
b = c
print(c) |
# Advent of Code 2015
#
# From https://adventofcode.com/2015/day/5
#
VOWELS = set('aeiou')
PAIRS = {x * 2 for x in 'abcdefghijklmnopqrstuvwxyz'}
NAUGHTY = {'ab', 'cd', 'pq', 'xy'}
def part1_check(string_):
if sum(string_.count(v) for v in VOWELS) >= 3:
pairs = set(string_[i:i + 2] for i in range(len(stri... | vowels = set('aeiou')
pairs = {x * 2 for x in 'abcdefghijklmnopqrstuvwxyz'}
naughty = {'ab', 'cd', 'pq', 'xy'}
def part1_check(string_):
if sum((string_.count(v) for v in VOWELS)) >= 3:
pairs = set((string_[i:i + 2] for i in range(len(string_) - 1)))
if not pairs.intersection(NAUGHTY) and pairs.int... |
BORDOR_LEFT = "CURSOR_REACH_LEFT"
BORDOR_RIGHT = "CURSOR_REACH_RIGHT"
BORDOR_TOP = "CURSOR_REACH_TOP"
BORDOR_BOTTOM = "CURSOR_REACH_BOTTOM"
| bordor_left = 'CURSOR_REACH_LEFT'
bordor_right = 'CURSOR_REACH_RIGHT'
bordor_top = 'CURSOR_REACH_TOP'
bordor_bottom = 'CURSOR_REACH_BOTTOM' |
#
# @lc app=leetcode id=226 lang=python3
#
# [226] Invert Binary Tree
#
# https://leetcode.com/problems/invert-binary-tree/description/
#
# algorithms
# Easy (66.70%)
# Likes: 4930
# Dislikes: 72
# Total Accepted: 670.1K
# Total Submissions: 997K
# Testcase Example: '[4,2,7,1,3,6,9]'
#
# Given the root of a bina... | class Solution:
def invert_tree(self, root: TreeNode) -> TreeNode:
if not root:
return root
left = self.invertTree(root.left)
right = self.invertTree(root.right)
root.right = left
root.left = right
return root |
number=int(input('What is your number? '))
prime=True
for fac in range(2, number):
if int(number)%fac==0 and not number==2:
prime=False
if prime==True and not number<2:
print('The number is prime.')
else:
print('The number is not prime.') | number = int(input('What is your number? '))
prime = True
for fac in range(2, number):
if int(number) % fac == 0 and (not number == 2):
prime = False
if prime == True and (not number < 2):
print('The number is prime.')
else:
print('The number is not prime.') |
class Process:
"""
Parent for all cellular processes.
"""
def __init__(self, name, model):
self.name = name
self.model = model
def update(self):
"""
Has to be implemented by child class.
"""
pass
| class Process:
"""
Parent for all cellular processes.
"""
def __init__(self, name, model):
self.name = name
self.model = model
def update(self):
"""
Has to be implemented by child class.
"""
pass |
# Source : https://leetcode.com/problems/check-if-numbers-are-ascending-in-a-sentence/
# Author : foxfromworld
# Date : 30/11/2021
# First attempt
class Solution:
def areNumbersAscending(self, s: str) -> bool:
curr = 0
for token in s.split(' '):
if token.isdigit():
#if toke... | class Solution:
def are_numbers_ascending(self, s: str) -> bool:
curr = 0
for token in s.split(' '):
if token.isdigit():
token = int(token)
if token > curr:
curr = token
else:
return False
re... |
class SquareRoot:
@staticmethod
def square_root(a):
c = pow(a, 0.5)
return c | class Squareroot:
@staticmethod
def square_root(a):
c = pow(a, 0.5)
return c |
# HS08TEST
amt,bal=map(float,input().split())
if(int(amt)%5==0):
if(amt<=(bal-0.5)): print("{:.2f}".format(bal-0.5-amt))
else: print("{:.2f}".format(bal))
else: print("{:.2f}".format(bal)) | (amt, bal) = map(float, input().split())
if int(amt) % 5 == 0:
if amt <= bal - 0.5:
print('{:.2f}'.format(bal - 0.5 - amt))
else:
print('{:.2f}'.format(bal))
else:
print('{:.2f}'.format(bal)) |
class DatabaseObject:
def __init__(self):
self.mongodb_id = None
@classmethod
def from_database_object(cls, database_obj):
"""
Returns the database object directly from a MongoDB data object.
"""
obj = cls()
for key, value in database_obj.items():
... | class Databaseobject:
def __init__(self):
self.mongodb_id = None
@classmethod
def from_database_object(cls, database_obj):
"""
Returns the database object directly from a MongoDB data object.
"""
obj = cls()
for (key, value) in database_obj.items():
... |
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class MultiFaceError(Error):
"""Exception raised for more than one face in the input file.
"""
def __init__(self, filename):
self.filename = filename
class NoDirError(Error):
def __init__(self, dirName):
... | class Error(Exception):
"""Base class for exceptions in this module."""
pass
class Multifaceerror(Error):
"""Exception raised for more than one face in the input file.
"""
def __init__(self, filename):
self.filename = filename
class Nodirerror(Error):
def __init__(self, dirName):
... |
class UrlManager:
def __init__(self):
self.pending_urls = set()
self.crawled_urls = set()
def has_pending_url(self):
return len(self.pending_urls) != 0
def add_url(self, url):
if url is None or len(url) == 0:
return
if url in self.crawled_urls:
... | class Urlmanager:
def __init__(self):
self.pending_urls = set()
self.crawled_urls = set()
def has_pending_url(self):
return len(self.pending_urls) != 0
def add_url(self, url):
if url is None or len(url) == 0:
return
if url in self.crawled_urls:
... |
def explore_next_node(self, node):
# maybe there are no paths to discover
if not self.unknownPaths: # and not self.unseenNodes
print("Every node discovered. Exploring finished.")
return None
# creat graphToSearch
graphList = {}
for key, value in self.pa... | def explore_next_node(self, node):
if not self.unknownPaths:
print('Every node discovered. Exploring finished.')
return None
graph_list = {}
for (key, value) in self.paths.items():
for targets in value.values():
if key in graphList and targets[2] > 0:
grap... |
# let the library to know how many jobs it has to allocate
GRID_SEARCH_CV_PARAMS = {
"n_jobs" : 4,
"cv" : 10
}
VERBOSE = True
VERBOSITY = 1
POS_NEG_DATASET_DIR = "./data/Positve_negative_sentences/"
HAM_SPAM_DATASET_DIR = "./data/Ham_Spam_comments/"
TRAINING_DIR= "Training/"
TEST_DIR = "Test/"
| grid_search_cv_params = {'n_jobs': 4, 'cv': 10}
verbose = True
verbosity = 1
pos_neg_dataset_dir = './data/Positve_negative_sentences/'
ham_spam_dataset_dir = './data/Ham_Spam_comments/'
training_dir = 'Training/'
test_dir = 'Test/' |
first_name = input()
second_name = input()
delimiter = input()
print(f"{first_name}{delimiter}{second_name}") | first_name = input()
second_name = input()
delimiter = input()
print(f'{first_name}{delimiter}{second_name}') |
# encoding:utf-8
save_problem_schema = {
'type': 'object',
'properties': {
'title': {'type': 'string'},
'content': {'type': 'string'},
'time_limit': {'type': 'integer'},
'memory_limit': {'type': 'integer'},
'difficulty' : {'type': 'string'},
'case_list': {'type':... | save_problem_schema = {'type': 'object', 'properties': {'title': {'type': 'string'}, 'content': {'type': 'string'}, 'time_limit': {'type': 'integer'}, 'memory_limit': {'type': 'integer'}, 'difficulty': {'type': 'string'}, 'case_list': {'type': 'array'}, 'answer_list': {'type': 'array'}}, 'required': ['title', 'content'... |
def main(grains):
return {
'states': ['vim'],
'pillars': {}
}
| def main(grains):
return {'states': ['vim'], 'pillars': {}} |
"""
Cardinal numbers
"""
class Aleph(object):
"""
Transfinite cardinal number Aleph(k).
The cardinality of the set of all integers is Aleph(0). Aleph(0)
is bigger than any natural numbers (cardinality of finite sets).
Alephs are ordered as Aleph(0) < Aleph(1) < ...
"""
def __init__(self, ... | """
Cardinal numbers
"""
class Aleph(object):
"""
Transfinite cardinal number Aleph(k).
The cardinality of the set of all integers is Aleph(0). Aleph(0)
is bigger than any natural numbers (cardinality of finite sets).
Alephs are ordered as Aleph(0) < Aleph(1) < ...
"""
def __init__(self,... |
class A:
def __init__(self):
self.x = 1
def _foo(self):
print(self.x)
a = A()
a._foo()
print(a.x) | class A:
def __init__(self):
self.x = 1
def _foo(self):
print(self.x)
a = a()
a._foo()
print(a.x) |
# for data acquisition:
numberOfChannels = 8
samplingRate = 500.0
# for preprocessing:
lowBandPassFreq = 2.0
highBandPassFreq = 100.0
lowBandStopFreq = 49
highBandStopFreq = 51
# for feature calculation:
windowSize = 0.15 # in s -> 150ms = 0.15s
samplesPerWindow = int(windowSize / (1. / samplingRate))
windowShift = ... | number_of_channels = 8
sampling_rate = 500.0
low_band_pass_freq = 2.0
high_band_pass_freq = 100.0
low_band_stop_freq = 49
high_band_stop_freq = 51
window_size = 0.15
samples_per_window = int(windowSize / (1.0 / samplingRate))
window_shift = int(samplesPerWindow / 2)
data_sample_correction = 1e-06
virtual_midi_cable = '... |
# a module
# define the function
def showState(state):
if(state == True):
print("On")
else:
print("Off")
| def show_state(state):
if state == True:
print('On')
else:
print('Off') |
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 26 13:19:04 2020
@author: Pedro
"""
#"""
#exercise 1
for a in range(2,11,2):
print(a)
print("Goodbye!")
#"""
#"""
#exercise 2
print("Hello!")
for b in range(10,1,-2):
print(b)
#"""
#"""
#exercise 3
end = 6
result = 0
for c in... | """
Created on Sun Jan 26 13:19:04 2020
@author: Pedro
"""
for a in range(2, 11, 2):
print(a)
print('Goodbye!')
print('Hello!')
for b in range(10, 1, -2):
print(b)
end = 6
result = 0
for c in range(0, end + 1):
result += c
print(result) |
def findDecision(obj): #obj[0]: Coupon, obj[1]: Education, obj[2]: Occupation, obj[3]: Restaurant20to50, obj[4]: Distance
# {"feature": "Coupon", "instances": 8147, "metric_value": 0.4722, "depth": 1}
if obj[0]>1:
# {"feature": "Distance", "instances": 5903, "metric_value": 0.4599, "depth": 2}
if obj[4]<=2:
# ... | def find_decision(obj):
if obj[0] > 1:
if obj[4] <= 2:
if obj[3] <= 1.0:
if obj[2] > 0:
if obj[1] <= 3:
return 'True'
elif obj[1] > 3:
return 'True'
else:
... |
# Shallow Copy
meta.append(arr)
# Deep Copy
meta.append(arr[:])
| meta.append(arr)
meta.append(arr[:]) |
def solve(data):
result = 0
for lines in data:
dimensions = list(map(int, lines.split('x')))
l = dimensions[0]
w = dimensions[1]
h = dimensions[2]
dimensions[0] = l * w
dimensions[1] = w * h
dimensions[2] = h * l
smallest_side = min(dimensions... | def solve(data):
result = 0
for lines in data:
dimensions = list(map(int, lines.split('x')))
l = dimensions[0]
w = dimensions[1]
h = dimensions[2]
dimensions[0] = l * w
dimensions[1] = w * h
dimensions[2] = h * l
smallest_side = min(dimensions)
... |
person_schema = {
"fname": {'type': 'string'},
"lname": {'type': 'string'},
"person_id": {'type': 'number'},
"timestamp": {'type': 'string'}
} | person_schema = {'fname': {'type': 'string'}, 'lname': {'type': 'string'}, 'person_id': {'type': 'number'}, 'timestamp': {'type': 'string'}} |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
self.res = float('-inf')
def dfs(root):
if not root:
... | class Solution:
def max_path_sum(self, root: TreeNode) -> int:
self.res = float('-inf')
def dfs(root):
if not root:
return 0
left = max(0, dfs(root.left))
right = max(0, dfs(root.right))
val = root.val + left + right
self.... |
class Solution:
def reverse(self, x: int) -> int:
if x >= 2 ** 31 - 1 or x <= -2 ** 31:
return 0
else:
strg = str(x)
if x >= 0:
revst = strg[::-1]
else:
temp = strg[1:]
temp2 = temp[::-1]
... | class Solution:
def reverse(self, x: int) -> int:
if x >= 2 ** 31 - 1 or x <= -2 ** 31:
return 0
else:
strg = str(x)
if x >= 0:
revst = strg[::-1]
else:
temp = strg[1:]
temp2 = temp[::-1]
... |
def dx(ux, u, nx, dx, order):
# summation-by-parts finite difference operators for first derivatives du/dx
m = nx-1
# second order accurate case
if order==2:
# calculate partial derivatives on the boundaries:[0, m] with one-sided difference operators
ux[0, :] = (u[1, :] - u[0,... | def dx(ux, u, nx, dx, order):
m = nx - 1
if order == 2:
ux[0, :] = (u[1, :] - u[0, :]) / dx
ux[m, :] = (u[m, :] - u[m - 1, :]) / dx
for j in range(1, m):
ux[j, :] = (u[j + 1, :] - u[j - 1, :]) / (2.0 * dx)
if order == 4:
ux[0, :] = -24.0 / 17 * u[0, :] + 59.0 / 34... |
set_example={"ATGCT","ATAGTATA","ATGCT"} #set will remove the duplicate members
print(set_example)
set_example={"YC1","YC2","YC3","YC3"}
print(set_example)
t_cell_epitopes={"LPVLQV","FGDSVE","VEKGVLPQLEQ","ARTAPH","EIPVA"}
b_cell_epitopes={"ARTAPH","IQYG","EIPVA"}
#all the available epitopes
#union operation
all_e... | set_example = {'ATGCT', 'ATAGTATA', 'ATGCT'}
print(set_example)
set_example = {'YC1', 'YC2', 'YC3', 'YC3'}
print(set_example)
t_cell_epitopes = {'LPVLQV', 'FGDSVE', 'VEKGVLPQLEQ', 'ARTAPH', 'EIPVA'}
b_cell_epitopes = {'ARTAPH', 'IQYG', 'EIPVA'}
all_epitopes = t_cell_epitopes | b_cell_epitopes
print(all_epitopes)
common... |
'''
Compute number of permutations containing specified number of descents
Status: Accepted
'''
def memoize(user_function):
"""Memoization decorator for user function of 1+ parameters"""
class Memodict(dict):
"""Memoization performs user function call on dict miss"""
def __getitem__(self, *k... | """
Compute number of permutations containing specified number of descents
Status: Accepted
"""
def memoize(user_function):
"""Memoization decorator for user function of 1+ parameters"""
class Memodict(dict):
"""Memoization performs user function call on dict miss"""
def __getitem__(self, *k... |
MOCK_ENTRIES = [{
"symbol": "GE",
"companyName": "General Electric Company",
"exchange": "New York Stock Exchange",
"industry": "Industrial Products",
"website": "http://www.ge.com",
"description":
"General Electric Co is a digital industrial company. It operates"
" in various se... | mock_entries = [{'symbol': 'GE', 'companyName': 'General Electric Company', 'exchange': 'New York Stock Exchange', 'industry': 'Industrial Products', 'website': 'http://www.ge.com', 'description': 'General Electric Co is a digital industrial company. It operates in various segments, including power and water, oil and g... |
#from swagger_server.models.configurations import Configurations
#from swagger_server.models.configuration import Configuration
class GuardAgentSecurityContext(object):
class __GuardAgentSecurityContext:
def __init__(self):
# self._time_between_probes=Configuration("time_between_probes", "int", "Tim... | class Guardagentsecuritycontext(object):
class __Guardagentsecuritycontext:
def __init__(self):
pass
def to_dict(self):
return self.configurations.to_dict()
def to_str(self):
return self.configurations.to_str()
def time_between_probes(self, tb... |
s = str(__import__('sys').stdin.readline().strip()).replace("()","0")
res = 0
sticker = 0
for x in s:
if x == "(":
sticker += 1
elif x == "0":
res += sticker
else:
sticker -= 1
res += 1
print(res)
| s = str(__import__('sys').stdin.readline().strip()).replace('()', '0')
res = 0
sticker = 0
for x in s:
if x == '(':
sticker += 1
elif x == '0':
res += sticker
else:
sticker -= 1
res += 1
print(res) |
#
# PySNMP MIB module VMWARE-VA-AGENTCAP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/VMWARE-VA-AGENTCAP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:35:03 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_size_constraint, single_value_constraint, constraints_intersection, value_range_constraint) ... |
'''
1. True y
2. False y
3. False y
4. True y
5. True y
6. False n
7. False y
8. True y
9. False y
10. False y
11. True y
12. False y
13. True y
14. False y
15. False y
16. True n
17. True y
18. True y
19. False y
20. False y
'''
| """
1. True y
2. False y
3. False y
4. True y
5. True y
6. False n
7. False y
8. True y
9. False y
10. False y
11. True y
12. False y
13. True y
14. False y
15. False y
16. True n
17. True y
18. True y
19. False y
20. False y
""" |
#
# Copyright (c) 2009-2020 Tom Keffer <tkeffer@gmail.com>
#
# See the file LICENSE.txt for your rights.
#
"""A very small wview schema."""
# =============================================================================
# This is a very severely restricted schema that includes only the basics. It
# is useful for... | """A very small wview schema."""
table = [('dateTime', 'INTEGER NOT NULL UNIQUE PRIMARY KEY'), ('usUnits', 'INTEGER NOT NULL'), ('interval', 'INTEGER NOT NULL'), ('altimeter', 'REAL'), ('barometer', 'REAL'), ('dewpoint', 'REAL'), ('ET', 'REAL'), ('heatindex', 'REAL'), ('inHumidity', 'REAL'), ('inTemp', 'REAL'), ('outHu... |
def palm_pilot(general, dev, msg) :
code = 13
prio = 800
prio += adjust_prio(general, dev, msg)
keys=list();
keys.append('Bottom of Cesar Chavez (LHS)')
keys.append('South Hall entrance 1')
if ( disallowed(general, dev) or not contains(dev, keys) ) : return (0, 0, 0, '', '')
if ( dev['Bottom of Cesar Chavez ... | def palm_pilot(general, dev, msg):
code = 13
prio = 800
prio += adjust_prio(general, dev, msg)
keys = list()
keys.append('Bottom of Cesar Chavez (LHS)')
keys.append('South Hall entrance 1')
if disallowed(general, dev) or not contains(dev, keys):
return (0, 0, 0, '', '')
if dev['B... |
{
"targets": [
{
"target_name": "addon",
"sources": [ "src/logql.cc" ],
"libraries": [ "<!(pwd)/logql.so" ]
}
]
}
| {'targets': [{'target_name': 'addon', 'sources': ['src/logql.cc'], 'libraries': ['<!(pwd)/logql.so']}]} |
def Articles():
articles = [
{
'id': 1,
'title': 'Article One',
'body': 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut... | def articles():
articles = [{'id': 1, 'title': 'Article One', 'body': 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute ir... |
def removeDuplicates(s: str) -> str:
i = 0
while i < len(s)-1:
if s[i] == s[i+1]:
s = s[i+2:] if s==0 else s[:i]+s[i+2:]
i = 0 if i==0 else i-1
else:
i+=1
return s
print(removeDuplicates("gnyogdbncigrwnjjtqtyregqyhkinjxgzmkpxskloxjcensflhhxlpfkrcmuctrr... | def remove_duplicates(s: str) -> str:
i = 0
while i < len(s) - 1:
if s[i] == s[i + 1]:
s = s[i + 2:] if s == 0 else s[:i] + s[i + 2:]
i = 0 if i == 0 else i - 1
else:
i += 1
return s
print(remove_duplicates('gnyogdbncigrwnjjtqtyregqyhkinjxgzmkpxskloxjcensf... |
#!/usr/local/bin/python3
def resultado_f1(**kwargs):
for posicao, piloto in kwargs.items():
print(f'{posicao} -> {piloto}')
if __name__ == '__main__':
resultado_f1(primeiro='Hamilton', segundo='Massa')
podium = {'primeiro': 'Hamilton', 'segundo': 'Massa'}
resultado_f1(**podium)
| def resultado_f1(**kwargs):
for (posicao, piloto) in kwargs.items():
print(f'{posicao} -> {piloto}')
if __name__ == '__main__':
resultado_f1(primeiro='Hamilton', segundo='Massa')
podium = {'primeiro': 'Hamilton', 'segundo': 'Massa'}
resultado_f1(**podium) |
"""
sspanel.urls
This module contains static URLs (and one incomplete URL)
"""
USER_LOGIN_URL = "https://www.survivalservers.com/sspanel/includes/ajax/validate_login.php"
SUBUSER_LOGIN_URL = "https://www.survivalservers.com/sspanel/includes/ajax/validate_subuser_login.php"
LOGOUT_URL = "https://www.survivalservers.co... | """
sspanel.urls
This module contains static URLs (and one incomplete URL)
"""
user_login_url = 'https://www.survivalservers.com/sspanel/includes/ajax/validate_login.php'
subuser_login_url = 'https://www.survivalservers.com/sspanel/includes/ajax/validate_subuser_login.php'
logout_url = 'https://www.survivalservers.com... |
#Write a class complex to represent complex numbers,
#along with overloaded operators + and * which adds and multiplies them.
#Formula --> (a+bi)(c+di) = (ac-bd) + (ad+bc)i
class Complex:
def __init__(self, r, i):
self.real = r
self.imaginary = i
def __add__(self, c):
return Complex(s... | class Complex:
def __init__(self, r, i):
self.real = r
self.imaginary = i
def __add__(self, c):
return complex(self.real + c.real, self.imaginary + c.imaginary)
def __mul__(self, c):
mul_real = self.real * c.real - self.imaginary * c.imaginary
mul_img = self.real *... |
guess = None
value = 5
trial = 5
print("WELCOME TO OUR GUESS GAME")
while trial > 0:
print('Your remaining trial is {}'.format(trial))
guess = int(input('enter a number: '))
if guess == value:
print('You win')
break
else:
trial = trial-1
else:
print('You loss')
| guess = None
value = 5
trial = 5
print('WELCOME TO OUR GUESS GAME')
while trial > 0:
print('Your remaining trial is {}'.format(trial))
guess = int(input('enter a number: '))
if guess == value:
print('You win')
break
else:
trial = trial - 1
else:
print('You loss') |
class IllegalArgumentException(Exception):
pass
class LinkedList:
class _Node:
def __init__(self, val=None, next_node=None):
self.val = val
self.next = next_node
# def __str__(self):
# return str(self.val)
# def __repr__(self):
# return... | class Illegalargumentexception(Exception):
pass
class Linkedlist:
class _Node:
def __init__(self, val=None, next_node=None):
self.val = val
self.next = next_node
def __init__(self):
self._dummy_head = self._Node()
self._size = 0
def get_size(self):
... |
line_num = 0
total = 0
visited = {}
with open("day8.txt") as f:
data = f.readlines()
def nop(num):
global line_num
line_num += 1
def jmp(num):
global line_num
line_num += num
def acc(num):
global total
global line_num
total += num
line_num += 1
cmds ... | line_num = 0
total = 0
visited = {}
with open('day8.txt') as f:
data = f.readlines()
def nop(num):
global line_num
line_num += 1
def jmp(num):
global line_num
line_num += num
def acc(num):
global total
global line_num
total += num
line_num += 1
cmds = {'nop': nop, 'jmp': jmp, 'acc... |
# Divyanshu Lohani: https://github.com/DivyanshuLohani
def pypart(n):
for i in range(0, n):
for j in range(0, i+1):
# printing stars
print("* ",end="")
# ending line after each row
print("\r")
n = 5
pypart(n) | def pypart(n):
for i in range(0, n):
for j in range(0, i + 1):
print('* ', end='')
print('\r')
n = 5
pypart(n) |
built_modules = list(name for name in
"Core;Gui;Widgets;PrintSupport;Sql;Network;Test;Concurrent;Xml;Help;OpenGL;OpenGLFunctions;OpenGLWidgets;Qml;Quick;QuickControls2;QuickWidgets;Svg;SvgWidgets;UiTools"
.split(";"))
shiboken_library_soversion = str(6.0)
pyside_library_soversion = str(6.0)
version = "6.0.0"
... | built_modules = list((name for name in 'Core;Gui;Widgets;PrintSupport;Sql;Network;Test;Concurrent;Xml;Help;OpenGL;OpenGLFunctions;OpenGLWidgets;Qml;Quick;QuickControls2;QuickWidgets;Svg;SvgWidgets;UiTools'.split(';')))
shiboken_library_soversion = str(6.0)
pyside_library_soversion = str(6.0)
version = '6.0.0'
version_i... |
'''
Pattern
Enter number of rows: 5
5
54
543
5432
54321
'''
print('Pattern: ')
number_rows=int(input('Enter number of rows: '))
for row in range(number_rows,0,-1):
for column in range(number_rows,row-1,-1):
if column < 10:
print(f'0{column}',end=' ')
else:
print(column,end=' ')
print()
| """
Pattern
Enter number of rows: 5
5
54
543
5432
54321
"""
print('Pattern: ')
number_rows = int(input('Enter number of rows: '))
for row in range(number_rows, 0, -1):
for column in range(number_rows, row - 1, -1):
if column < 10:
print(f'0{column}', end=' ')
else:
print(colu... |
# MIT License
# (C) Copyright 2021 Hewlett Packard Enterprise Development LP.
#
# statsRetention : Stats retention
def get_all_stats_retention(self) -> dict:
"""Get all statistics retention configuration
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpo... | def get_all_stats_retention(self) -> dict:
"""Get all statistics retention configuration
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - statsRetention
- GET
- /gms/stats/retention
:return: Returns dictionary of s... |
line = input().split()
n = int(line[0])
m = int(line[1])
ans = min(n,m)
if(ans%2==0):
print("Malvika")
else:
print("Akshat")
| line = input().split()
n = int(line[0])
m = int(line[1])
ans = min(n, m)
if ans % 2 == 0:
print('Malvika')
else:
print('Akshat') |
data = open("day15.txt").read().replace("\n", "").split(",")
data = [int(x) for x in data]
def find_last_number(data, stop):
previous = data[-1]
turn = len(data)
last_spoken = {value: key + 1 for key, value in enumerate(data[:-1])}
while turn < stop:
new_number = turn - \
last_spok... | data = open('day15.txt').read().replace('\n', '').split(',')
data = [int(x) for x in data]
def find_last_number(data, stop):
previous = data[-1]
turn = len(data)
last_spoken = {value: key + 1 for (key, value) in enumerate(data[:-1])}
while turn < stop:
new_number = turn - last_spoken[previous] ... |
class BasePagination(object):
"""
Class that make queryset paginated
"""
model = None
def __init__(self, cursor, items_per_page, model):
"""
:param cursor: field that would be direction for pagination
:param items_per_page: items per each page
:param model: model cla... | class Basepagination(object):
"""
Class that make queryset paginated
"""
model = None
def __init__(self, cursor, items_per_page, model):
"""
:param cursor: field that would be direction for pagination
:param items_per_page: items per each page
:param model: model cla... |
# Approach 2 - Left-to-Right Pass Improved
values = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000,
"IV": 4,
"IX": 9,
"XL": 40,
"XC": 90,
"CD": 400,
"CM": 900
}
class Solution:
def romanToInt(self, s: str) -> int:
total = 0
i ... | values = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000, 'IV': 4, 'IX': 9, 'XL': 40, 'XC': 90, 'CD': 400, 'CM': 900}
class Solution:
def roman_to_int(self, s: str) -> int:
total = 0
i = 0
while i < len(s):
if i < len(s) - 1 and s[i:i + 2] in values:
... |
class TreeNode:
def __init__(self, data):
self._data = data
self._children = []
def __repr__(self, level=0):
res = "\t" * level + repr(self._data) + "\n"
for child in self._children:
res += child.__repr__(level + 1)
return res
class BSTNode:
def __init_... | class Treenode:
def __init__(self, data):
self._data = data
self._children = []
def __repr__(self, level=0):
res = '\t' * level + repr(self._data) + '\n'
for child in self._children:
res += child.__repr__(level + 1)
return res
class Bstnode:
def __init... |
#
# PySNMP MIB module CTRON-SSR-TRAP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CTRON-SSR-TRAP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:31:35 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, constraints_intersection, single_value_constraint, constraints_union) ... |
remote = ("example.com", 80)
page = "/response"
auth = ""
reqthreads = 4
| remote = ('example.com', 80)
page = '/response'
auth = ''
reqthreads = 4 |
class Queue:
def __init__(self):
self.__items = []
def enqueue(self, item):
self.__items.append(item)
def dequeue(self):
if not self.length():
raise QueueEmptyException()
item = self.__items[0]
self.__items = self.__items[1:]
return item
def... | class Queue:
def __init__(self):
self.__items = []
def enqueue(self, item):
self.__items.append(item)
def dequeue(self):
if not self.length():
raise queue_empty_exception()
item = self.__items[0]
self.__items = self.__items[1:]
return item
... |
"""Aula 06: Linux - MariaDB Server + MySQL Workbench
[comandos]
sudo apt-get update
sudo apt-get install mariadb-server
sudo mysql -u root
USE mysql;
UPDATE user SET plugin='' WHERE User='root';
FLUSH PRIVILEGES;
exit
sudo apt-get install mysql-workbench
"""
| """Aula 06: Linux - MariaDB Server + MySQL Workbench
[comandos]
sudo apt-get update
sudo apt-get install mariadb-server
sudo mysql -u root
USE mysql;
UPDATE user SET plugin='' WHERE User='root';
FLUSH PRIVILEGES;
exit
sudo apt-get install mysql-workbench
""" |
def solve(data, part_two=False):
max_found = -1
seat_ids = []
for l in data:
row_max = 127
row_min = 0
seat_max = 7
seat_min = 0
for c in l:
if c == 'F':
row_max = ((row_max-row_min) // 2) + row_min
elif c == 'B':
... | def solve(data, part_two=False):
max_found = -1
seat_ids = []
for l in data:
row_max = 127
row_min = 0
seat_max = 7
seat_min = 0
for c in l:
if c == 'F':
row_max = (row_max - row_min) // 2 + row_min
elif c == 'B':
... |
# !/usr/bin/env python3
# Author: C.K
# Email: theck17@163.com
# DateTime:2021-12-04 09:48:17
# Description:
class Solution:
def longestWord(self, words: List[str]) -> str:
valid = set([""])
for word in sorted(words, key=lambda x: len(x)):
if word[:-1] in valid:
v... | class Solution:
def longest_word(self, words: List[str]) -> str:
valid = set([''])
for word in sorted(words, key=lambda x: len(x)):
if word[:-1] in valid:
valid.add(word)
return max(sorted(valid), key=lambda x: len(x))
if __name__ == '__main__':
pass |
class Bipartite(object):
def __init__(self, graph):
self.is_bipartite = True
self.color = [False for _ in range(graph.v)]
self.marked = [False for _ in range(graph.v)]
self.edge_to = [0 for _ in range(graph.v)]
self.odd_length_cycle = []
for v in range(graph.v):
... | class Bipartite(object):
def __init__(self, graph):
self.is_bipartite = True
self.color = [False for _ in range(graph.v)]
self.marked = [False for _ in range(graph.v)]
self.edge_to = [0 for _ in range(graph.v)]
self.odd_length_cycle = []
for v in range(graph.v):
... |
# The objective is to find the summation of the odd elements in the array
# Define a simple array
sample =[12,33,54,89,776,3]
# Get length of the array
l= len(sample)
s=0
# Looping on the array up to max length to sum up the odd elements
for i in range(l):
if (i%2!=0):
s = s + int(sample[i])
#print the sum... | sample = [12, 33, 54, 89, 776, 3]
l = len(sample)
s = 0
for i in range(l):
if i % 2 != 0:
s = s + int(sample[i])
print(s) |
"""
Module: 'os' on M5 FlowUI v1.4.0-beta
"""
# MCU: (sysname='esp32', nodename='esp32', release='1.11.0', version='v1.11-284-g5d8e1c867 on 2019-08-30', machine='ESP32 module with ESP32')
# Stubber: 1.3.1
SDMODE_1LINE = 2
SDMODE_4LINE = 3
SDMODE_SPI = 1
def chdir():
pass
def dupterm():
pass
def dupterm_notify... | """
Module: 'os' on M5 FlowUI v1.4.0-beta
"""
sdmode_1_line = 2
sdmode_4_line = 3
sdmode_spi = 1
def chdir():
pass
def dupterm():
pass
def dupterm_notify():
pass
def getcwd():
pass
def getdrive():
pass
def ilistdir():
pass
def listdir():
pass
def mkdir():
pass
def mountsd():
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.