content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def merge_dicts(*dict_args):
"""
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
"""
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result
def rescale_bbox(height, width, bbox):
""... | def merge_dicts(*dict_args):
"""
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
"""
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result
def rescale_bbox(height, width, bbox):
"""... |
# Copyright Notice:
# Copyright 2016-2019 DMTF. All rights reserved.
# License: BSD 3-Clause License. For full text see link: https://github.com/DMTF/Redfish-Interface-Emulator/blob/master/LICENSE.md
# Redfish Emulator Role Service.
# Temporary version, to be removed when AccountService goes dynamic
class AccountSe... | class Accountservice(object):
def __init__(self):
self._accounts = {'Administrator': 'Password', 'User': 'Password'}
self._roles = {'Administrator': 'Admin', 'User': 'ReadOnlyUser'}
def check_priviledge_level(self, user, level):
if self._roles[user] == level:
return True
... |
# the highest score
student_scores = input("Input a list of student scores ").split()
for n in range(0, len(student_scores)):
student_scores[n] = int(student_scores[n])
print(student_scores)
# or you can use the max() function
# max = max(student_scores)
highest = student_scores[0]
for index in range(0, len(stude... | student_scores = input('Input a list of student scores ').split()
for n in range(0, len(student_scores)):
student_scores[n] = int(student_scores[n])
print(student_scores)
highest = student_scores[0]
for index in range(0, len(student_scores)):
if student_scores[index] > highest:
highest = student_scores[... |
"""Constants used by the OpenMediaVault integration."""
DOMAIN = "openmediavault"
DEFAULT_NAME = "OpenMediaVault"
DATA_CLIENT = "client"
ATTRIBUTION = "Data provided by OpenMediaVault integration"
DEFAULT_HOST = "10.0.0.1"
DEFAULT_USERNAME = "admin"
DEFAULT_PASSWORD = "openmediavault"
DEFAULT_DEVICE_NAME = "OMV"
DEF... | """Constants used by the OpenMediaVault integration."""
domain = 'openmediavault'
default_name = 'OpenMediaVault'
data_client = 'client'
attribution = 'Data provided by OpenMediaVault integration'
default_host = '10.0.0.1'
default_username = 'admin'
default_password = 'openmediavault'
default_device_name = 'OMV'
defaul... |
class Solution(object):
def singleNumber(self, nums):
diff = reduce(lambda x, y: x ^ y, nums, 0)
diff &= -diff
res = [0, 0]
for num in nums:
res[num & diff == 0] ^= num
return res | class Solution(object):
def single_number(self, nums):
diff = reduce(lambda x, y: x ^ y, nums, 0)
diff &= -diff
res = [0, 0]
for num in nums:
res[num & diff == 0] ^= num
return res |
def powerset_of_set(aset):
set_list = [x for x in aset]
final_set = set()
for catchnum in range(len(set_list)):
print(catchnum)
for index in range(catchnum, len(set_list)):
b = "{}".format(set_list[index:])
if b not in final_set:
final_set.add(b)
... | def powerset_of_set(aset):
set_list = [x for x in aset]
final_set = set()
for catchnum in range(len(set_list)):
print(catchnum)
for index in range(catchnum, len(set_list)):
b = '{}'.format(set_list[index:])
if b not in final_set:
final_set.add(b)
r... |
# Fungsi enkripsi
def encrypt(plain,password):
plainIntVector = []
for i in range(len(plain)):
plainIntVector.append(ord(plain[i]))
passwordIntVector = []
# inisiasi variabel baru untuk membuat setiap perubahan yang terjadi pada
# password akan menyebabkan avalanche effect
# variabel in... | def encrypt(plain, password):
plain_int_vector = []
for i in range(len(plain)):
plainIntVector.append(ord(plain[i]))
password_int_vector = []
added_value = pow(sum([ord(i) for i in password]), len(password), 256)
for i in range(len(password)):
passwordIntVector.append((ord(password[i... |
class solve_day(object):
with open('inputs/day08.txt', 'r') as f:
data = f.readlines()
data = [d.strip() for d in data]
def part1(self):
accumulator = 0
i = 0
index_tracker = []
index_visited = set()
index_tracker.append(i)
index_visited.add(i... | class Solve_Day(object):
with open('inputs/day08.txt', 'r') as f:
data = f.readlines()
data = [d.strip() for d in data]
def part1(self):
accumulator = 0
i = 0
index_tracker = []
index_visited = set()
index_tracker.append(i)
index_visited.add(i)
... |
class Marker(object):
def __init__(self):
self._body = None
def make(self):
raise NotImplementedError
def update(self, marker):
pass
def show(self):
if self._body is None:
self._body = self.make()
self.update(self._body)
def hide(self):
... | class Marker(object):
def __init__(self):
self._body = None
def make(self):
raise NotImplementedError
def update(self, marker):
pass
def show(self):
if self._body is None:
self._body = self.make()
self.update(self._body)
def hide(self):
... |
# Bubble Sort-values of a dictionary as a list
#Time Complexity = O(N)
def bubbleSort(k):
for i in range(1,len(k)):
for j in range(len(k)-i):
if k[j] > k[j+1]:
k[j],k[j+1] = k[j+1],k[j]
return k
dict = {"a":1, "c":3, "f":6, "e":5, "d":4, "b":2}
k = list(dict.values())
prin... | def bubble_sort(k):
for i in range(1, len(k)):
for j in range(len(k) - i):
if k[j] > k[j + 1]:
(k[j], k[j + 1]) = (k[j + 1], k[j])
return k
dict = {'a': 1, 'c': 3, 'f': 6, 'e': 5, 'd': 4, 'b': 2}
k = list(dict.values())
print(bubble_sort(k)) |
saisie_debut = input("le debut :")
debut = int(saisie_debut)
#si l'utilisateur saisit un chiffre impair
if debut % 2 != 0 :
debut += 1
saisie_fin = input("la fin :")
fin = int(saisie_fin)
indice = 1
for elem in range(debut, fin, 2):
print("element ", indice," = ", elem)
indice += 1
| saisie_debut = input('le debut :')
debut = int(saisie_debut)
if debut % 2 != 0:
debut += 1
saisie_fin = input('la fin :')
fin = int(saisie_fin)
indice = 1
for elem in range(debut, fin, 2):
print('element ', indice, ' = ', elem)
indice += 1 |
var = """A multi-line
docstring"""
var = """A multi-line
docstring
"""
| var = 'A multi-line\ndocstring'
var = 'A multi-line\ndocstring\n' |
# -*- coding: utf-8 -*-
"""Top-level package for Python Missing Data Strategies."""
__author__ = """Aris Tritas"""
__email__ = "a.tritas@gmail.com"
__version__ = "0.0.1"
imputation_strategies = ("mean", "median", "most_frequent", "infer", "fill")
| """Top-level package for Python Missing Data Strategies."""
__author__ = 'Aris Tritas'
__email__ = 'a.tritas@gmail.com'
__version__ = '0.0.1'
imputation_strategies = ('mean', 'median', 'most_frequent', 'infer', 'fill') |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 7 10:17:36 2020
@author: teja
"""
s = '12asdbkFWS(#@!qde'
cn = 0
ca = 0
cspl = 0
for i in range(len(s)):
if s[i].isalpha():
ca+=1
elif s[i].isnumeric():
cn+=1
else:
cspl+=1
print(str(cn) + " " + str(ca) + " " + str(cspl) + " ") | """
Created on Sat Mar 7 10:17:36 2020
@author: teja
"""
s = '12asdbkFWS(#@!qde'
cn = 0
ca = 0
cspl = 0
for i in range(len(s)):
if s[i].isalpha():
ca += 1
elif s[i].isnumeric():
cn += 1
else:
cspl += 1
print(str(cn) + ' ' + str(ca) + ' ' + str(cspl) + ' ') |
SMTP_SERVICE_BLOCK = 'smtp-service'
SMTP_HOST = 'smtp_host'
SMTP_PORT = 'smtp_port'
SMTP_USERNAME = 'smtp_username'
SMTP_PASSWORD = 'smtp_password'
SMTP_USE_TLS = 'smtp_use_tls'
SMTP_LEVEL = 'smtp_level'
SMTP_DEFAULT_VALUES = {
SMTP_HOST: '127.0.0.1',
SMTP_PORT: '25',
SMTP_USERNAME: None,
SMTP_PASSWORD... | smtp_service_block = 'smtp-service'
smtp_host = 'smtp_host'
smtp_port = 'smtp_port'
smtp_username = 'smtp_username'
smtp_password = 'smtp_password'
smtp_use_tls = 'smtp_use_tls'
smtp_level = 'smtp_level'
smtp_default_values = {SMTP_HOST: '127.0.0.1', SMTP_PORT: '25', SMTP_USERNAME: None, SMTP_PASSWORD: None, SMTP_USE_T... |
"""Constants for pyskyqremote."""
# SOAP/UPnP Constants
SKY_PLAY_URN = "urn:nds-com:serviceId:SkyPlay"
SKYCONTROL = "SkyControl"
SOAP_ACTION = '"urn:schemas-nds-com:service:SkyPlay:2#{0}"'
SOAP_CONTROL_BASE_URL = "http://{0}:49153{1}"
SOAP_DESCRIPTION_BASE_URL = "http://{0}:49153/description{1}.xml"
SOAP_PAYLOAD = """<... | """Constants for pyskyqremote."""
sky_play_urn = 'urn:nds-com:serviceId:SkyPlay'
skycontrol = 'SkyControl'
soap_action = '"urn:schemas-nds-com:service:SkyPlay:2#{0}"'
soap_control_base_url = 'http://{0}:49153{1}'
soap_description_base_url = 'http://{0}:49153/description{1}.xml'
soap_payload = '<s:Envelope xmlns:s=\'htt... |
'''
Little Jhool and psychic powers
Little Jhool always wanted to have some psychic powers so that he could showoff his skills, and magic to people and impress them. (Specially, his girlfriend Big Jhool!) But, in spite all his efforts, hardwork, dedication, Googling, watching youtube videos he couldn't garner any psyc... | """
Little Jhool and psychic powers
Little Jhool always wanted to have some psychic powers so that he could showoff his skills, and magic to people and impress them. (Specially, his girlfriend Big Jhool!) But, in spite all his efforts, hardwork, dedication, Googling, watching youtube videos he couldn't garner any psyc... |
"""
if elif else
"""
NUMBER = 17
value = int(input("input a value: "))
if value == NUMBER:
print("Winner!!!")
elif value > NUMBER:
print("your number is greater")
else:
print("your number is lower")
| """
if elif else
"""
number = 17
value = int(input('input a value: '))
if value == NUMBER:
print('Winner!!!')
elif value > NUMBER:
print('your number is greater')
else:
print('your number is lower') |
class ValidatedDictLike:
"""
This a dict with a `validate` method that may raise any exception.
The dict it validation on initialization and any time its contents
are changed. If a change is illegal, it is reverted an the exception
from `validate` is raised. Thus, it is impossible to put the dict
... | class Validateddictlike:
"""
This a dict with a `validate` method that may raise any exception.
The dict it validation on initialization and any time its contents
are changed. If a change is illegal, it is reverted an the exception
from `validate` is raised. Thus, it is impossible to put the dict
... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Defines constants for use in the performance testing framework."""
class DataTypes:
"""Data types"""
TABULAR = 'tabular'
IMAGE = 'image'
TEXT = 'text'
class Algorithms:
"""Algorithms"""
SVM = ... | """Defines constants for use in the performance testing framework."""
class Datatypes:
"""Data types"""
tabular = 'tabular'
image = 'image'
text = 'text'
class Algorithms:
"""Algorithms"""
svm = 'svm'
logistic = 'logistic'
deep = 'deep'
tree = 'tree'
ridge = 'ridge'
class Task... |
def test_logout(ui):
driver = ui.driver
driver.find_element_by_css_selector(".user-dropdown").click()
driver.find_element_by_css_selector(".logout-button").click()
assert driver.find_element_by_css_selector('.login-form')
def test_recorded_sessions_visible(ui_session):
assert ui_session is not Non... | def test_logout(ui):
driver = ui.driver
driver.find_element_by_css_selector('.user-dropdown').click()
driver.find_element_by_css_selector('.logout-button').click()
assert driver.find_element_by_css_selector('.login-form')
def test_recorded_sessions_visible(ui_session):
assert ui_session is not None |
"""
https://github.com/parzival-roethlein/prmaya
# DESCRIPTION
Manage objectSet members (add, remove, reorder, export, import)
# USAGE
import prmaya.scripts.prObjectSetUi.utils
prmaya.scripts.prObjectSetUi.utils.ui()
# TODO
- export / import members
- avoid unwanted maya behavior (clean solutions only possible with ... | """
https://github.com/parzival-roethlein/prmaya
# DESCRIPTION
Manage objectSet members (add, remove, reorder, export, import)
# USAGE
import prmaya.scripts.prObjectSetUi.utils
prmaya.scripts.prObjectSetUi.utils.ui()
# TODO
- export / import members
- avoid unwanted maya behavior (clean solutions only possible with ... |
def longest_palindromic_substring(s):
t = '^#'+'#'.join(s)+'#$'
n = len(t)
p = [0]*n
c = r = cm = rm = 0
for i in range (1, n-1):
p[i] = min(r-i, p[2*c-i]) if r > i else 0
while t[i-p[i]-1] == t[i+p[i]+1]: p[i] += 1
if p[i]+i > r: c, r = i, p[i]+i
... | def longest_palindromic_substring(s):
t = '^#' + '#'.join(s) + '#$'
n = len(t)
p = [0] * n
c = r = cm = rm = 0
for i in range(1, n - 1):
p[i] = min(r - i, p[2 * c - i]) if r > i else 0
while t[i - p[i] - 1] == t[i + p[i] + 1]:
p[i] += 1
if p[i] + i > r:
... |
# create a Blender service, we'll call it ... blender
blender = Runtime.start("blender","Blender")
# connect it to Blender - blender must be running the Blender.py
# or easier yet, start blender with the Blender.blend file
# select game mode then press p with cursor over the rendering screen
if not blender.connect():
... | blender = Runtime.start('blender', 'Blender')
if not blender.connect():
print('could not connect to blender - is it running and did you remember to run Blender.py')
else:
print('connected')
i01 = Runtime.start('i01', 'InMoov')
arduino = Runtime.start('i01.left', 'Arduino')
blender.attach(arduino)
neck = Runtime... |
class Candidate:
_inner_id = 0
def __init__(self, name=""):
self._id = Candidate._inner_id
self.name = name
Candidate._inner_id += 1
CandidateList.append(self)
@staticmethod
def reset_id():
Candidate._inner_id = 0
class CandidateList:
"""
CandidateList... | class Candidate:
_inner_id = 0
def __init__(self, name=''):
self._id = Candidate._inner_id
self.name = name
Candidate._inner_id += 1
CandidateList.append(self)
@staticmethod
def reset_id():
Candidate._inner_id = 0
class Candidatelist:
"""
CandidateList ... |
class CloudWatchEvent:
def __init__(self,
schedule_expression: str,
is_active: bool,
name: str =None):
self.name = name
self.schedule_expression = schedule_expression
self.is_active = is_active
| class Cloudwatchevent:
def __init__(self, schedule_expression: str, is_active: bool, name: str=None):
self.name = name
self.schedule_expression = schedule_expression
self.is_active = is_active |
# increasing paths in an array
def f1_3(array): # O(N^2)
if len(array) <= 1:
return
ans = []
start_idx, idx = 0, 1
prenum = array[start_idx]
while idx < len(array):
if array[idx] >= prenum:
for i in range(start_idx, idx):
ans.append(array[i:idx + 1])... | def f1_3(array):
if len(array) <= 1:
return
ans = []
(start_idx, idx) = (0, 1)
prenum = array[start_idx]
while idx < len(array):
if array[idx] >= prenum:
for i in range(start_idx, idx):
ans.append(array[i:idx + 1])
else:
start_idx = idx... |
class Movie(object):
def __init__(self):
self.title = ""
self.id = ""
self.plot = ""
self.year = ""
def __str__(self):
return str(self.__dict__)
| class Movie(object):
def __init__(self):
self.title = ''
self.id = ''
self.plot = ''
self.year = ''
def __str__(self):
return str(self.__dict__) |
'''2. Write a Python program that accepts six numbers as input and sorts them in descending order.
Input:
Input consists of six numbers n1, n2, n3, n4, n5, n6 (-100000 = n1, n2, n3, n4, n5, n6 = 100000). The six numbers are separated by a space.
Input six integers:
15 30 25 14 35 40
After sorting the said integers:
40 ... | """2. Write a Python program that accepts six numbers as input and sorts them in descending order.
Input:
Input consists of six numbers n1, n2, n3, n4, n5, n6 (-100000 = n1, n2, n3, n4, n5, n6 = 100000). The six numbers are separated by a space.
Input six integers:
15 30 25 14 35 40
After sorting the said integers:
40 ... |
def list_squared(m, n):
data=[[1, 1], [42, 2500], [246, 84100],[287, 84100],[728, 722500], [1434, 2856100], [1673, 2856100], [1880, 4884100],[4264, 24304900],[6237, 45024100], [9799, 96079204], [9855, 113635600]]
result=[]
index=0
while True:
if m<=data[index][0]<=n:
result.append(da... | def list_squared(m, n):
data = [[1, 1], [42, 2500], [246, 84100], [287, 84100], [728, 722500], [1434, 2856100], [1673, 2856100], [1880, 4884100], [4264, 24304900], [6237, 45024100], [9799, 96079204], [9855, 113635600]]
result = []
index = 0
while True:
if m <= data[index][0] <= n:
re... |
# Array, two pointers
class Solution:
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
if not height or len(height) < 3:
return 0
left_max = right_max = 0
ans = left = 0
right = len(height) - 1
while left < right:... | class Solution:
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
if not height or len(height) < 3:
return 0
left_max = right_max = 0
ans = left = 0
right = len(height) - 1
while left < right:
left_max... |
"""
Complete the function that accepts a string parameter,
and reverses each word in the string. All spaces in
the string should be retained.
Examples
"This is an example!" ==> "sihT si na !elpmaxe"
"double spaces" ==> "elbuod secaps"
"""
def reverse_words(text):
str_list = []
for word in text.split(' '):
... | """
Complete the function that accepts a string parameter,
and reverses each word in the string. All spaces in
the string should be retained.
Examples
"This is an example!" ==> "sihT si na !elpmaxe"
"double spaces" ==> "elbuod secaps"
"""
def reverse_words(text):
str_list = []
for word in text.split(' ... |
# Creating a program that uses the min() without using the min() function. Without knowing the user inputted values of num1 and num2, create a program that outputs the lower value without using the min()
num1 = int(input('Enter a value: '))
num2 = int(input('Enter a value: '))
if num1 <= num2:
print(num1)
else:
... | num1 = int(input('Enter a value: '))
num2 = int(input('Enter a value: '))
if num1 <= num2:
print(num1)
else:
print(num2) |
class NodeIndexer:
def __init__(self, walker):
self.walker = walker
self.__nodes = []
def __walk(self):
next_node = next(self.walker)
self.__nodes.append(next_node)
return next_node
def index(self, node):
result = self.__find_from_loaded(node)
if res... | class Nodeindexer:
def __init__(self, walker):
self.walker = walker
self.__nodes = []
def __walk(self):
next_node = next(self.walker)
self.__nodes.append(next_node)
return next_node
def index(self, node):
result = self.__find_from_loaded(node)
if re... |
def bfs(graph, start):
"""Visits all the nodes of a graph using BFS
Args:
graph (dict): Search space represented by a graph
start (str): Starting state
Returns:
explored (list): List of the explored nodes
"""
# list to keep track of all visited nodes
explored = []
... | def bfs(graph, start):
"""Visits all the nodes of a graph using BFS
Args:
graph (dict): Search space represented by a graph
start (str): Starting state
Returns:
explored (list): List of the explored nodes
"""
explored = []
queue = []
queue.append(start)
while le... |
for _ in range(int(input())):
n,k=map(int,input().split())
a=list(map(int,input().split()))
s=sum(a)
c=0
for i in range(n):
if(a[i]+k>s-a[i]):
#print([i])
c+=1
print(c) | for _ in range(int(input())):
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
s = sum(a)
c = 0
for i in range(n):
if a[i] + k > s - a[i]:
c += 1
print(c) |
class color(object):
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
RESET_ALL = '\033[0m' | class Color(object):
green = '\x1b[92m'
yellow = '\x1b[93m'
red = '\x1b[91m'
reset_all = '\x1b[0m' |
# -*- coding: utf-8 -*-
# Copyright (c) 2019-2020 shmilee
class RawLoader(object):
path = 'test/rawlodaer'
filenames = [
'g.out', 'eq.out', 's0.out', 's2.out', 's4.out',
'p/s0_t0.out', 'p/s0_t1.out', 'p/s0_t2.out',
'p/s2_t0.out', 'p/s2_t1.out', 'p/s2_t2.out',
]
class PckLoader(o... | class Rawloader(object):
path = 'test/rawlodaer'
filenames = ['g.out', 'eq.out', 's0.out', 's2.out', 's4.out', 'p/s0_t0.out', 'p/s0_t1.out', 'p/s0_t2.out', 'p/s2_t0.out', 'p/s2_t1.out', 'p/s2_t2.out']
class Pckloader(object):
path = 'test/pcklodaer'
datakeys = ['g/c', 'da/i-p-f', 'da/i-m-f', 'da/e-p-f'... |
def minTime(machines, goal):
# make a modest guess of what the days may be, and use it as a starting point
efficiency = [1.0/x for x in machines]
lower_bound = int(goal / sum(efficiency)) - 1
upper_bound = lower_bound + max(machines) + 1
while lower_bound < upper_bound -1:
days ... | def min_time(machines, goal):
efficiency = [1.0 / x for x in machines]
lower_bound = int(goal / sum(efficiency)) - 1
upper_bound = lower_bound + max(machines) + 1
while lower_bound < upper_bound - 1:
days = (lower_bound + upper_bound) // 2
produce = sum([days // x for x in machines])
... |
# write program reading an integer from standard input - a
# printing sum of all numbers indivisible by 3, smaller than a
# for example, for a=10, result = 1 + 2 + 4 + 5 + 7 + 8 = 27
a = int(input("pass a - "))
element = 1
result = 0
while element < a:
if element % 3 != 0 :
result = result + element
element = el... | a = int(input('pass a - '))
element = 1
result = 0
while element < a:
if element % 3 != 0:
result = result + element
element = element + 1
print('result = ' + str(result)) |
N, K = map(int, input().split())
if N % 2 == 0:
print(min(K + 1, N // 2))
else:
print(min(K + 1, N))
| (n, k) = map(int, input().split())
if N % 2 == 0:
print(min(K + 1, N // 2))
else:
print(min(K + 1, N)) |
def format_sexpr_flat(node):
if not isinstance(node, (list, tuple)):
return str(node)
else:
return '(' + ' '.join(format_sexpr_flat(x) for x in node) + ')'
def format_sexpr(node, indent_level=0, max_width=80):
if not isinstance(node, (list, tuple)):
return str(node)
if len(node)... | def format_sexpr_flat(node):
if not isinstance(node, (list, tuple)):
return str(node)
else:
return '(' + ' '.join((format_sexpr_flat(x) for x in node)) + ')'
def format_sexpr(node, indent_level=0, max_width=80):
if not isinstance(node, (list, tuple)):
return str(node)
if len(nod... |
#-*- coding:utf-8 -*-
class UnknownComponent:
def build(self, c):
pass
def start(self, c):
pass
def stop(self, c):
pass
def __str__(self):
return 'unknown' | class Unknowncomponent:
def build(self, c):
pass
def start(self, c):
pass
def stop(self, c):
pass
def __str__(self):
return 'unknown' |
class Rectangle:
def __init__(self, l, w):
# Aqui estamos llamando a los setters (ver abajo)
self.length = l
self.width = w
@property
def area(self):
return self._length*self._width
@property
def perimeter(self):
return self._length * 2 + se... | class Rectangle:
def __init__(self, l, w):
self.length = l
self.width = w
@property
def area(self):
return self._length * self._width
@property
def perimeter(self):
return self._length * 2 + self._width * 2
@property
def length(self):
return self._... |
# -*- encoding: utf-8 -*-
def differ(a,b):
return a-b
| def differ(a, b):
return a - b |
# -*- coding: UTF-8 -*-
VENDOR_GROUP = 1
CUSTOMER_GROUP = 2
RETAILER_GROUP = 3
SUPER_ADMIN = 4
| vendor_group = 1
customer_group = 2
retailer_group = 3
super_admin = 4 |
# -*- coding: utf-8 -*-
class BaseApiException(Exception):
status_code = None
message = None
detail = None
def to_dict(self):
_output = {
'code': self.status_code,
'message': self.message
}
if self.detail:
_output.update({'detail': self.deta... | class Baseapiexception(Exception):
status_code = None
message = None
detail = None
def to_dict(self):
_output = {'code': self.status_code, 'message': self.message}
if self.detail:
_output.update({'detail': self.detail})
return _output
class Objectalreadyexistexcepti... |
TEMPLATE = """
{name}
====
README
"""
def get_readme_template(name: str) -> str:
return TEMPLATE.format(name=name)
| template = '\n{name}\n====\n\nREADME\n'
def get_readme_template(name: str) -> str:
return TEMPLATE.format(name=name) |
# outer loop
for i in range (65,70):
# inner loop
for j in range(65,i+1):
print(chr(j),end="")
print()
| for i in range(65, 70):
for j in range(65, i + 1):
print(chr(j), end='')
print() |
# Copyright (C) [2015-2017] [Thomson Reuters LLC]
# Copyright (C) [2015-2017] [Panos Kittenis]
# 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... | """Constants and default settings for InfluxGraph"""
influxdb_aggregations = ['count', 'distinct', 'integral', 'mean', 'median', 'mode', 'spread', 'stddev', 'sum', 'bottom', 'first', 'last', 'max', 'min', 'percentile', 'sample', 'top']
default_aggregations = {'\\.min$': 'min', '\\.max$': 'max', '\\.last$': 'last', '\\.... |
# -*- coding: utf-8 -*-
""" server settings """
# The address which the server runs on.
# The server supports both INET4 and UNIX sockets.
# For INET sockets, set to (addr: str, port: int),
# For UNIX sockets, set to the path of the socket.
server_addr = '/tmp/gulag.sock'
# The max amount of concurrent
# connections ... | """ server settings """
server_addr = '/tmp/gulag.sock'
max_conns = 16
debug = False
server_build = True
mysql = {'db': 'gulag', 'host': 'localhost', 'password': 'supersecure', 'user': 'cmyui'}
osu_api_key = ''
' osu!direct '
mirror = True
external_mirror = 'https://osu.gatari.pw'
' customization '
menu_icon = ('https:... |
def print_table(table, max_char):
if table:
if len(table) > 0:
if len(table[0]) > 0:
#find length/height
col = len(table)
row = len(table[0])
maxlen = []
output = []
#find l... | def print_table(table, max_char):
if table:
if len(table) > 0:
if len(table[0]) > 0:
col = len(table)
row = len(table[0])
maxlen = []
output = []
for x in range(0, len(table[0])):
maxlen.append(0)... |
class Day1:
@staticmethod
def count(depths: str):
lines = depths.splitlines()
current_ine = 9999999
increased = 0
for line in lines:
int_line = int(line)
if current_ine < int_line:
increased += 1
current_ine = int_line
r... | class Day1:
@staticmethod
def count(depths: str):
lines = depths.splitlines()
current_ine = 9999999
increased = 0
for line in lines:
int_line = int(line)
if current_ine < int_line:
increased += 1
current_ine = int_line
... |
'''
Sample code to test PythonSyntaxHighlighter.
'''
# Comments:
# - Words like TODO, BUG, FIXME, HACK, NOTE, and XXX are highlighted.
# - Escapes like \n and \t are not.
# Integers:
i = 0_000_000 + 0o_000 + 0o123 + 0x1_2abc_CAFE + 0b_1011_0110 + 1_2_3_4_5
# Floats:
f = [3.14, 10., .001, 1e100, 3.14e-10, 0e0, 3.14_1... | """
Sample code to test PythonSyntaxHighlighter.
"""
i = 0 + 0 + 83 + 5011983102 + 182 + 12345
f = [3.14, 10.0, 0.001, 1e+100, 3.14e-10, 0.0, 3.141593, 0.007, 990000000000.0, 12345.67891]
im = 0.23j + 987600j + 0.5j
s1 = 'string'
s2 = 's'
s3 = 'nested "quote"'
s4 = 'nested """ triple quote'
s5 = "the ''' other way"
s6 ... |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
a,b,c=map(int,input().split())
print(0--(a*c)//b-c) | """
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
(a, b, c) = map(int, input().split())
print(0 - -(a * c) // b - c) |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"core_fn": "00_core.ipynb",
"Apple": "00a_apple.ipynb",
"core_text_fn": "10_text_core.ipynb",
"text_util_fn": "10a_text_utils.ipynb"}
modules = ["core.py",
"apple.py",
... | __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'core_fn': '00_core.ipynb', 'Apple': '00a_apple.ipynb', 'core_text_fn': '10_text_core.ipynb', 'text_util_fn': '10a_text_utils.ipynb'}
modules = ['core.py', 'apple.py', 'text/core.py', 'text/utils.py']
doc_url = 'https://pete88b.github.io/nbdev_demo/... |
def interlock(word1, word2, word3):
if (not word1) or (not word2) or (not word3):
return False
interlocked = ""
for i in range(len(min([word1, word2], key=len))):
interlocked += (word1[i] + word2[i])
if word3 == (interlocked + max([word1, word2], key=len)[len(min([word1, word2], key=l... | def interlock(word1, word2, word3):
if not word1 or not word2 or (not word3):
return False
interlocked = ''
for i in range(len(min([word1, word2], key=len))):
interlocked += word1[i] + word2[i]
if word3 == interlocked + max([word1, word2], key=len)[len(min([word1, word2], key=len)):]:
... |
# -*- coding: utf-8 -*-
class Solution:
def isMagicSquareCenteredHere(self, grid, i, j):
all_nine_numbers = sorted([
grid[i - 1][j - 1], grid[i - 1][j], grid[i - 1][j + 1],
grid[i][j - 1], grid[i][j], grid[i][j + 1],
grid[i + 1][j - 1], grid[i + 1][j], grid[i + 1][j + 1... | class Solution:
def is_magic_square_centered_here(self, grid, i, j):
all_nine_numbers = sorted([grid[i - 1][j - 1], grid[i - 1][j], grid[i - 1][j + 1], grid[i][j - 1], grid[i][j], grid[i][j + 1], grid[i + 1][j - 1], grid[i + 1][j], grid[i + 1][j + 1]]) == list(range(1, 10))
all_sums_equal = len(set... |
# Do not edit this file directly.
# It was auto-generated by: code/programs/reflexivity/reflexive_refresh
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def sfml():
http_archive(
name="sfml" ,
build_file="//bazel/deps/sfml:build.BUILD" ,
sha256="6b013624aa9a916da2d37... | load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
def sfml():
http_archive(name='sfml', build_file='//bazel/deps/sfml:build.BUILD', sha256='6b013624aa9a916da2d37180772031e963098494538f59a14f40e00db23c9077', strip_prefix='SFML-257e50beb886f1edebeebbde1903169da4eca39f', urls=['https://github.com/U... |
class Solution:
"""
@param s: a string
@param k: an integer
@return: all unique substring
"""
def uniqueSubstring(self, s, k):
records = set()
for i in range(len(s) - k + 1):
word = s[i: i + k]
records.add(word)
return sorted(records) | class Solution:
"""
@param s: a string
@param k: an integer
@return: all unique substring
"""
def unique_substring(self, s, k):
records = set()
for i in range(len(s) - k + 1):
word = s[i:i + k]
records.add(word)
return sorted(records) |
ADMIN = 1
USER = 0
ROLE = {
ADMIN: 'admin',
USER: 'user',
}
# Post status
PRIVATE = 1
PUBLIC = 0
STATUS = {
PRIVATE: 'Private',
PUBLIC: 'Public'
}
#User friend
ISFRIEND = 1
NOTISFRIEND = 0
STATUS = {
ISFRIEND: 'Is Friend',
NOTISFRIEND: 'Not is Friend'
}
PROCESSED = 1
NOPROCESSED = 0
STATUS = ... | admin = 1
user = 0
role = {ADMIN: 'admin', USER: 'user'}
private = 1
public = 0
status = {PRIVATE: 'Private', PUBLIC: 'Public'}
isfriend = 1
notisfriend = 0
status = {ISFRIEND: 'Is Friend', NOTISFRIEND: 'Not is Friend'}
processed = 1
noprocessed = 0
status = {PROCESSED: 'Processed', NOPROCESSED: 'No Processed'} |
class Solution:
def plusOne(self, digits: [int]) -> [int]:
if digits[-1] < 9:
digits[-1] += 1
return digits
temp = ''
for value in digits:
temp += str(value)
temp = str(int(temp) + 1)
result = []
for value in temp:
res... | class Solution:
def plus_one(self, digits: [int]) -> [int]:
if digits[-1] < 9:
digits[-1] += 1
return digits
temp = ''
for value in digits:
temp += str(value)
temp = str(int(temp) + 1)
result = []
for value in temp:
res... |
'''
Exceptions/codes
________________
Organized error codes for reporting errors and exceptions.
:copyright: (c) 2015 The Regents of the University of California.
:license: GNU GPL, see licenses/GNU GPLv3.txt for more details.
'''
CODES = {
"000": ("Cannot find file%(-s)s in row%(-s)s {0}."
... | """
Exceptions/codes
________________
Organized error codes for reporting errors and exceptions.
:copyright: (c) 2015 The Regents of the University of California.
:license: GNU GPL, see licenses/GNU GPLv3.txt for more details.
"""
codes = {'000': 'Cannot find file%(-s)s in row%(-s)s {0}. Deleting ... |
def add(num1:int,num2:int):
return num1 + num2
class InsufficientFunds(Exception):
pass
class BankAccount():
def __init__(self,starting_balance=0):
self.balance = starting_balance
def deposit(self,amount):
self.balance += amount
def withdraw(self,amount):
if amount > self... | def add(num1: int, num2: int):
return num1 + num2
class Insufficientfunds(Exception):
pass
class Bankaccount:
def __init__(self, starting_balance=0):
self.balance = starting_balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount >... |
{
"variables": {
"libwebm_root%": "",
},
"targets": [
{
"target_name": "audio",
"sources": [ "audio-napi.cc", "webvtt/vttreader.cc", "webvtt/webvttparser.cc", "webm_muxer.cc", "sample_muxer_metadata.cc" ],
"conditions": [
['OS=="mac"',
{
'defines': [
'__MACOSX_CORE_... | {'variables': {'libwebm_root%': ''}, 'targets': [{'target_name': 'audio', 'sources': ['audio-napi.cc', 'webvtt/vttreader.cc', 'webvtt/webvttparser.cc', 'webm_muxer.cc', 'sample_muxer_metadata.cc'], 'conditions': [['OS=="mac"', {'defines': ['__MACOSX_CORE__'], 'include_dirs': ['<(libwebm_root)'], 'link_settings': {'libr... |
# Copyright 2014 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': {
'errorprone_script_path': '<(PRODUCT_DIR)/bin.java/chromium_errorprone',
},
'targets': [
{
# GN: //third_party/errorpron... | {'variables': {'errorprone_script_path': '<(PRODUCT_DIR)/bin.java/chromium_errorprone'}, 'targets': [{'target_name': 'error_prone_annotation_jar', 'type': 'none', 'variables': {'jar_path': 'lib/error_prone_annotation-2.0.5.jar'}, 'includes': ['../../build/host_prebuilt_jar.gypi']}, {'target_name': 'error_prone_annotati... |
n=int(input())
i=0
x=0
while (i<n):
b=set(input())
if("+" in b):
x+=1
else:
x+=(-1)
i+=1
else:
print(x)
| n = int(input())
i = 0
x = 0
while i < n:
b = set(input())
if '+' in b:
x += 1
else:
x += -1
i += 1
else:
print(x) |
class InputError(Exception):
"""Exception raised for errors in the input.
Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""
def __init__(self, expression, options):
self.expression = expression
self.message = ... | class Inputerror(Exception):
"""Exception raised for errors in the input.
Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""
def __init__(self, expression, options):
self.expression = expression
self.message = ... |
n = int(input())
total_sum = 0
for x in range(1, n + 1):
ascii_code = input()
total_sum += ord(ascii_code)
print(f"The sum equals: {total_sum}") | n = int(input())
total_sum = 0
for x in range(1, n + 1):
ascii_code = input()
total_sum += ord(ascii_code)
print(f'The sum equals: {total_sum}') |
def soma(x1, y1):
res = x1 + y1
print('O resultado da soma e {}'.format(res))
x = int(input('Digite um valor!'))
y = int(input('Digite um outro valor!'))
soma(x, y)
| def soma(x1, y1):
res = x1 + y1
print('O resultado da soma e {}'.format(res))
x = int(input('Digite um valor!'))
y = int(input('Digite um outro valor!'))
soma(x, y) |
# double quote, backslash, and newlines are forbidden
ok_chars = " !#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~"
ok_chars = frozenset(ok_chars)
# these characters cannot use unicode escape codes due to the way Java escaping works
late_escape = {u'\u0009':r'\t', u'\u000a... | ok_chars = " !#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~"
ok_chars = frozenset(ok_chars)
late_escape = {u'\t': '\\t', u'\n': '\\n', u'\r': '\\r', u'"': '\\"', u'\\': '\\\\'}
def escape_string(u):
if set(u) <= ok_chars:
return u
escaped = []
for c in ... |
# OpenWeatherMap API Key
weather_api_key = "68524e14c88fa47aab3ac62f9461f6d5"
# Google API Key
g_key = "AIzaSyAMvlEJHc05Plk9V6VOFt-ezMHPgo6BZSo"
| weather_api_key = '68524e14c88fa47aab3ac62f9461f6d5'
g_key = 'AIzaSyAMvlEJHc05Plk9V6VOFt-ezMHPgo6BZSo' |
def fib(n):
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)
if __name__ == "__main__":
assert fib(3) == 2
assert fib(6) == 8
| def fib(n):
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)
if __name__ == '__main__':
assert fib(3) == 2
assert fib(6) == 8 |
# global variables for common header types
ETHER_DETECT = False
IPv4_DETECT = False
IPv6_DETECT = False
TCP_DETECT = False
UDP_DETECT = False
DEBUG = False
# Maximum possible headers within a packet, hyperparameter with default value as 10
MAX_PATH_LENGTH = 10
| ether_detect = False
i_pv4_detect = False
i_pv6_detect = False
tcp_detect = False
udp_detect = False
debug = False
max_path_length = 10 |
class Solution:
def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:
if not timeSeries:
return 0
ans = 0
start = timeSeries[0]
end = timeSeries[0] + duration
for t in timeSeries[1:]:
if t < end:
... | class Solution:
def find_poisoned_duration(self, timeSeries: List[int], duration: int) -> int:
if not timeSeries:
return 0
ans = 0
start = timeSeries[0]
end = timeSeries[0] + duration
for t in timeSeries[1:]:
if t < end:
end = t + dura... |
#!/usr/bin/python
# encoding: utf-8
"""
@author: xuk1
@license: (C) Copyright 2013-2017
@contact: kai.a.xu@intel.com
@file: test.py
@time: 8/15/2017 10:38
@desc:
"""
| """
@author: xuk1
@license: (C) Copyright 2013-2017
@contact: kai.a.xu@intel.com
@file: test.py
@time: 8/15/2017 10:38
@desc:
""" |
# This file is generated by ./Setup.py
class LocalConfig:
@staticmethod
def initialized():
pass
@staticmethod
def get_db_name():
return 'universe_db'
@staticmethod
def get_db_user():
return 'postgres'
@staticmethod
def get_db_host():
return '127.0.0.1'... | class Localconfig:
@staticmethod
def initialized():
pass
@staticmethod
def get_db_name():
return 'universe_db'
@staticmethod
def get_db_user():
return 'postgres'
@staticmethod
def get_db_host():
return '127.0.0.1'
@staticmethod
def get_db_port... |
top_three([2, 3, 5, 6, 8, 4, 2, 1])
# [8, 6, 5]
top_three([1, 2])
# [2, 1]
top_three(['cat', 'dog', 'python', 'cuttlefish'])
# ['python', 'dog', 'cuttlefish']
| top_three([2, 3, 5, 6, 8, 4, 2, 1])
top_three([1, 2])
top_three(['cat', 'dog', 'python', 'cuttlefish']) |
class GameEnd(Exception):
pass
class Tie(GameEnd):
pass
class Checkmated(GameEnd):
pass
class RunOutOfTime(GameEnd):
pass
class MoveError(Exception):
pass
class CheckAfterMove(MoveError):
pass
class SquareNotInValidMoves(MoveError):
pass
class TeamDoesntGotTurn(MoveError):
... | class Gameend(Exception):
pass
class Tie(GameEnd):
pass
class Checkmated(GameEnd):
pass
class Runoutoftime(GameEnd):
pass
class Moveerror(Exception):
pass
class Checkaftermove(MoveError):
pass
class Squarenotinvalidmoves(MoveError):
pass
class Teamdoesntgotturn(MoveError):
pass
c... |
interfaces = [None] * 26
interfaces[0] = "kitchen_a"
interfaces[1] = "kitchen_b"
interfaces[2] = "kitchen_c"
interfaces[3] = "kitchen_d"
interfaces[4] = "kitchen_e"
interfaces[5] = "kitchen_f"
interfaces[6] = "kitchen_g"
interfaces[7] = "kitchen_h"
interfaces[8] = "kitchen_i"
interfaces[9] = "kitchen_j"
interfaces[10] ... | interfaces = [None] * 26
interfaces[0] = 'kitchen_a'
interfaces[1] = 'kitchen_b'
interfaces[2] = 'kitchen_c'
interfaces[3] = 'kitchen_d'
interfaces[4] = 'kitchen_e'
interfaces[5] = 'kitchen_f'
interfaces[6] = 'kitchen_g'
interfaces[7] = 'kitchen_h'
interfaces[8] = 'kitchen_i'
interfaces[9] = 'kitchen_j'
interfaces[10] ... |
ROOT = ''
BASE_DIR = ROOT+''
WRITABLE_FOLDER = ROOT+'writable/'
DATABASES = {'default':
{
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/path/to/database',
}
}
ADMINS = (('name', 'name@example.com'))
#Influences which template and... | root = ''
base_dir = ROOT + ''
writable_folder = ROOT + 'writable/'
databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': '/path/to/database'}}
admins = ('name', 'name@example.com')
signbank_version_code = ''
url = ''
languages = (('en', 'English'),)
language_code = 'en'
separate_english_idgloss_fiel... |
#1. Basic - Print all integers from 0 to 150.
for x in range(151):
print(x)
#2. Multiples of Five - Print all the multiples of 5 from 5 to 1,000
for x in range(1001):
if (x % 5 == 0):
print(x)
"""3. Counting, the Dojo Way - Print integers 1 to 100. If divisible by 5, print "Coding" instead.
If divisi... | for x in range(151):
print(x)
for x in range(1001):
if x % 5 == 0:
print(x)
'3. Counting, the Dojo Way - Print integers 1 to 100. If divisible by 5, print "Coding" instead. \nIf divisible by 10, print "Coding Dojo".'
for x in range(1, 101):
if x % 10 == 0:
print('Coding Dojo')
elif x % 5... |
def merge_sort(lst):
# print("list=",lst)
n=len(lst)
if n>1:
mid=n//2
# print("mid=",mid)
left=lst[0:mid]
# print("left:",left)
right=lst[mid:]
# print("right:",right)
# print("-"*50)
merge_sort(left)
merge_sort(right)
Merge(left,right,lst)
return lst
def Merge(left,r... | def merge_sort(lst):
n = len(lst)
if n > 1:
mid = n // 2
left = lst[0:mid]
right = lst[mid:]
merge_sort(left)
merge_sort(right)
merge(left, right, lst)
return lst
def merge(left, right, lst):
i = 0
j = 0
k = 0
while i < len(left) and j < len(r... |
'''
Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.
Example 1:
Input: [1,4,3,2]
Output: 4
Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + m... | """
Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.
Example 1:
Input: [1,4,3,2]
Output: 4
Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + m... |
# O(n)
def find_in_sorted_matrix(matrix, val):
i = 0
j = len(matrix[0]) - 1
while ( i < len(matrix) and j >= 0 ):
if (matrix[i][j] == val ):
return (i,j)
if (matrix[i][j] > val ):
j -= 1
else:
i += 1
return None | def find_in_sorted_matrix(matrix, val):
i = 0
j = len(matrix[0]) - 1
while i < len(matrix) and j >= 0:
if matrix[i][j] == val:
return (i, j)
if matrix[i][j] > val:
j -= 1
else:
i += 1
return None |
# idea: the setup sounds complicated but actually reduces to a trivial problem. If the strings are not identical, the longer of the two strings can't be a subsequence of the other (or either one if they are the same length but not identical), and if they are identical, there is no uncommon subsequence
class Solution:
... | class Solution:
def find_lu_slength(self, a, b):
"""
:type a: str
:type b: str
:rtype: int
"""
return -1 if a == b else max(len(a), len(b)) |
"""
Exceptions thrown by pyxll_notebook.
"""
class KernelStartError(RuntimeError):
pass
class ExecuteRequestError(RuntimeError):
def __init__(self, evalue=None, traceback=None, **kwargs):
if evalue is None:
evalue = str(kwargs)
super().__init__(evalue)
class AuthenticationError... | """
Exceptions thrown by pyxll_notebook.
"""
class Kernelstarterror(RuntimeError):
pass
class Executerequesterror(RuntimeError):
def __init__(self, evalue=None, traceback=None, **kwargs):
if evalue is None:
evalue = str(kwargs)
super().__init__(evalue)
class Authenticationerror(R... |
flag = False
N = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9','0']
inp = raw_input("Input Rule:")
prod = inp[(inp.index("->")+2):]
print(prod)
for i in range(len(prod)):
if prod[i] == inp[0]:
flag = True
... | flag = False
n = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
inp = raw_input('Input Rule:')
prod = inp[inp.index('->') + 2:]
print(prod)
for i in range(len(prod)):
if prod[i] == i... |
response = natural_language_understanding.analyze(
url="https://en.wikipedia.org/wiki/SpaceX",
features=Features(
categories=CategoriesOptions(limit=4),
concepts=ConceptsOptions(limit=10)),
clean=False
).get_result()
| response = natural_language_understanding.analyze(url='https://en.wikipedia.org/wiki/SpaceX', features=features(categories=categories_options(limit=4), concepts=concepts_options(limit=10)), clean=False).get_result() |
#!/usr/bin/env python3
def f(h,l,p):
#print(h,p,l)
nc = len(l)
for i in range(nc):
l[i] -= p[1][i]
if l[i]<0: return ['NO']
v2s = [0]*(nc-1) #quota of small
v2b = [0]*(nc-1) #quota of big
for i in range(nc-1):
v2s[i] = l[i] #use all small left!
p[2][i... | def f(h, l, p):
nc = len(l)
for i in range(nc):
l[i] -= p[1][i]
if l[i] < 0:
return ['NO']
v2s = [0] * (nc - 1)
v2b = [0] * (nc - 1)
for i in range(nc - 1):
v2s[i] = l[i]
p[2][i] -= v2s[i]
if p[2][i] <= 0:
continue
v2b[i] = p[2]... |
"""
syntax.py: contains syntax for common languages
"""
syntax = {
"py": {
"keywords": ['False', 'await', 'else', 'import', 'pass',
'None', 'break', 'except', 'in', 'raise',
'True', 'class', 'finally', 'is', 'return',
'and', 'continue', 'for', ... | """
syntax.py: contains syntax for common languages
"""
syntax = {'py': {'keywords': ['False', 'await', 'else', 'import', 'pass', 'None', 'break', 'except', 'in', 'raise', 'True', 'class', 'finally', 'is', 'return', 'and', 'continue', 'for', 'lambda', 'try', 'as', 'def', 'from', 'nonlocal', 'while', 'assert', 'del', 'g... |
class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
a, b = 1, 1
for _ in range(n):
a, b = b, a + b
return a
| class Solution:
def climb_stairs(self, n):
"""
:type n: int
:rtype: int
"""
(a, b) = (1, 1)
for _ in range(n):
(a, b) = (b, a + b)
return a |
class PlayerHand:
# player's hand
def __init__(self):
self.__hand = []
def deal(self, card):
# receive a card
self.__hand.append(card)
def gethand(self):
return self.__hand
def burnhand(self):
self.__hand = []
| class Playerhand:
def __init__(self):
self.__hand = []
def deal(self, card):
self.__hand.append(card)
def gethand(self):
return self.__hand
def burnhand(self):
self.__hand = [] |
# -*- coding: utf-8 -*-
# @Author : jjxu
# @time: 2019/01/14 14:42
DEBUG = True
HOST = "0.0.0.0"
| debug = True
host = '0.0.0.0' |
input = "1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,1,6,19,2,19,6,23,1,23,5,27,1,9,27,31,1,31,10,35,2,35,9,39,1,5,39,43,2,43,9,47,1,5,47,51,2,51,13,55,1,55,10,59,1,59,10,63,2,9,63,67,1,67,5,71,2,13,71,75,1,75,10,79,1,79,6,83,2,13,83,87,1,87,6,91,1,6,91,95,1,10,95,99,2,99,6,103,1,103,5,107,2,6,107,111,1,10,111,115,1,115,5,119,2,... | input = '1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,1,6,19,2,19,6,23,1,23,5,27,1,9,27,31,1,31,10,35,2,35,9,39,1,5,39,43,2,43,9,47,1,5,47,51,2,51,13,55,1,55,10,59,1,59,10,63,2,9,63,67,1,67,5,71,2,13,71,75,1,75,10,79,1,79,6,83,2,13,83,87,1,87,6,91,1,6,91,95,1,10,95,99,2,99,6,103,1,103,5,107,2,6,107,111,1,10,111,115,1,115,5,119,2,... |
"""684. Redundant Connection"""
class Solution(object):
def findRedundantConnection(self, edges):
"""
:type edges: List[List[int]]
:rtype: List[int]
"""
# union find: 1. Union 2. Find
"""OOD"""
self.parent = [x for x in range(len(edges)+1)]
for x, y i... | """684. Redundant Connection"""
class Solution(object):
def find_redundant_connection(self, edges):
"""
:type edges: List[List[int]]
:rtype: List[int]
"""
'OOD'
self.parent = [x for x in range(len(edges) + 1)]
for (x, y) in edges:
if self.union(x... |
class Solution:
def maxSubArray(self, nums: list[int]) -> int:
maxItem, arraySum, maxSum = nums[0], 0, 0
for i in nums:
maxItem = max(maxItem, i)
if i >= 0:
arraySum += i
maxSum = max(arraySum, maxSum)
elif arraySum+i >= 0:
... | class Solution:
def max_sub_array(self, nums: list[int]) -> int:
(max_item, array_sum, max_sum) = (nums[0], 0, 0)
for i in nums:
max_item = max(maxItem, i)
if i >= 0:
array_sum += i
max_sum = max(arraySum, maxSum)
elif arraySum + i... |
# First Last _ custid _ username _ password _ rank
# change list of dictionaries into dictionary of dictionaries
def user_dict(user_l):
""" list(dict) -> dict """
id_user = {}
for u in user_l:
id_user[u['custID']] = u
return id_user
# change string to dictionary of info
def read_user(str):
... | def user_dict(user_l):
""" list(dict) -> dict """
id_user = {}
for u in user_l:
id_user[u['custID']] = u
return id_user
def read_user(str):
""" str -> dict """
pieces = str.split()
return {'first': pieces[0], 'last': pieces[1], 'username': pieces[5], 'custID': pieces[3], 'password':... |
#!/usr/bin/env python3
google_api_key=''
google_cx_id=''
| google_api_key = ''
google_cx_id = '' |
#
# PySNMP MIB module LANCOM-1711-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/LANCOM-1711-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:05:22 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, value_size_constraint, constraints_union, constraints_intersection) ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.