content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# A =[3, 1, 2, 4, 3]
# For this one, it is important to re-use previous calculations. For instance:
# (A[0] + A[1] + A[2]) = (A[0] + A[1]) + A[2]
def solution(A):
#
head = A[0]
tail = sum(A[1:])
min_dif = abs(head - tail)
# Important not to include the first and last element
for index in range(1... | def solution(A):
head = A[0]
tail = sum(A[1:])
min_dif = abs(head - tail)
for index in range(1, len(A) - 1):
head += A[index]
tail -= A[index]
if abs(head - tail) < min_dif:
min_dif = abs(head - tail)
return min_dif |
class Node:
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
return str(self.value)
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def __str__(self):
cur_head = self.head
out_string = "... | class Node:
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
return str(self.value)
class Linkedlist:
def __init__(self):
self.head = None
self.tail = None
def __str__(self):
cur_head = self.head
out_string = ... |
# Generated by rpcgen.py from /home/nickolai/proj/go-rpcgen/rfc1057/prot.x on Fri Dec 6 10:47:00 2019
FALSE = 0
TRUE = 1
AUTH_NONE = 0
AUTH_UNIX = 1
AUTH_SHORT = 2
AUTH_DES = 3
auth_flavor = {
0 : 'AUTH_NONE',
1 : 'AUTH_UNIX',
2 : 'AUTH_SHORT',
3 : 'AUTH_DES',
}
CALL = 0
REPLY = 1
msg_type = {
0 : ... | false = 0
true = 1
auth_none = 0
auth_unix = 1
auth_short = 2
auth_des = 3
auth_flavor = {0: 'AUTH_NONE', 1: 'AUTH_UNIX', 2: 'AUTH_SHORT', 3: 'AUTH_DES'}
call = 0
reply = 1
msg_type = {0: 'CALL', 1: 'REPLY'}
msg_accepted = 0
msg_denied = 1
reply_stat = {0: 'MSG_ACCEPTED', 1: 'MSG_DENIED'}
success = 0
prog_unavail = 1
p... |
# https://www.hackerrank.com/challenges/python-mutations/problem
def mutate_string(string, position, character):
string = list(string)
string[position] = character
return "".join(string)
| def mutate_string(string, position, character):
string = list(string)
string[position] = character
return ''.join(string) |
"""Exception classes."""
class FeatureError(Exception):
"""Raised when a feature is used incorrectly."""
| """Exception classes."""
class Featureerror(Exception):
"""Raised when a feature is used incorrectly.""" |
reg_list=[
# exmaple:
# ["ISR","uint64_t","MEM_MAPPED",["NS",1,"RES0_0",2]],
#distributor
["GICD_CTLR","uint32_t","MEM_MAPPED",[["EnableGrp0",1, "EnableGrp1NS",1, "EnableGrp1S",1, "RES0_0",1, "ARE_S",1, "ARE_NS",1, "DS",1, "E1NWF",1, "RES0_1",23, "RWP",1 ]] ],
#cpu-system-side
... | reg_list = [['GICD_CTLR', 'uint32_t', 'MEM_MAPPED', [['EnableGrp0', 1, 'EnableGrp1NS', 1, 'EnableGrp1S', 1, 'RES0_0', 1, 'ARE_S', 1, 'ARE_NS', 1, 'DS', 1, 'E1NWF', 1, 'RES0_1', 23, 'RWP', 1]]], ['ICC_BPR0_EL1', 'uint32_t', 'GCC_REPR', [['BinaryPoint', 3, 'RES0', 29]]], ['ICC_BPR1_EL1', 'uint32_t', 'GCC_REPR', [['Binary... |
def countsubarray(nums, k):
if k <= 1: return 0
prod = 1
ans = left = 0
for right, val in enumerate(nums):
prod *= val
while prod >= k:
prod /= nums[left]
left += 1
ans += right - left + 1
return ans
t = int(input())
for _ in range(t):
n,k = map(in... | def countsubarray(nums, k):
if k <= 1:
return 0
prod = 1
ans = left = 0
for (right, val) in enumerate(nums):
prod *= val
while prod >= k:
prod /= nums[left]
left += 1
ans += right - left + 1
return ans
t = int(input())
for _ in range(t):
(n... |
N, M = map(int, input().split())
set_list = []
for i in range(M):
x, y = map(int, input().split())
set_list.append({x, y})
max_num = 1
for i in range(2**N):
binary = format(i, 'b').zfill(N+2)[2:]
group = []
for j in range(N):
if binary[j] == '1':
group.append(j+1)
failed = Fa... | (n, m) = map(int, input().split())
set_list = []
for i in range(M):
(x, y) = map(int, input().split())
set_list.append({x, y})
max_num = 1
for i in range(2 ** N):
binary = format(i, 'b').zfill(N + 2)[2:]
group = []
for j in range(N):
if binary[j] == '1':
group.append(j + 1)
f... |
N = (int(input()))
i = 0
while i < N - 2:
i = i + 2
print(i)
| n = int(input())
i = 0
while i < N - 2:
i = i + 2
print(i) |
class Ability():
def __init__(self, name, value):
self.name=name
self.value=value
self.modifier=0
self.setModifier()
def setModifier(self):
if self.value>=10:
self.modifier=(self.value-10)//2
else:
self.modifier=(self.value-10)//2
class Defense():
def __init__(self, charlevel, abilitymodifier):
... | class Ability:
def __init__(self, name, value):
self.name = name
self.value = value
self.modifier = 0
self.setModifier()
def set_modifier(self):
if self.value >= 10:
self.modifier = (self.value - 10) // 2
else:
self.modifier = (self.value... |
print(2.0/2)
print(7.0//2)
print(-5//4)
print(8%3)
print(455643/17.43)
a=10
b=30
print(a/b)
a=4.445*10**8
b=5*10**6
c=(b*10)/100
d=b-c
print(d)
g=b+a
print(g)
f=(b*5)/100
e=b-f
print(e)
| print(2.0 / 2)
print(7.0 // 2)
print(-5 // 4)
print(8 % 3)
print(455643 / 17.43)
a = 10
b = 30
print(a / b)
a = 4.445 * 10 ** 8
b = 5 * 10 ** 6
c = b * 10 / 100
d = b - c
print(d)
g = b + a
print(g)
f = b * 5 / 100
e = b - f
print(e) |
def __binary_search(leafs, l, r, d):
result = 0
while l <= r:
mid = (l + r) // 2
if leafs[mid] < d:
l = mid + 1
result = mid + 1
else:
r = mid - 1
return result
def solution(leafs):
leafs.sort()
n = len(leafs)
answer = 0
for i in ... | def __binary_search(leafs, l, r, d):
result = 0
while l <= r:
mid = (l + r) // 2
if leafs[mid] < d:
l = mid + 1
result = mid + 1
else:
r = mid - 1
return result
def solution(leafs):
leafs.sort()
n = len(leafs)
answer = 0
for i in r... |
# Problem: https://www.hackerrank.com/challenges/python-string-split-and-join/problem
def split_and_join(line):
return "-".join(line.split(' '))
line = input()
result = split_and_join(line)
print(result) | def split_and_join(line):
return '-'.join(line.split(' '))
line = input()
result = split_and_join(line)
print(result) |
#
# If you prefer some of the entries are preloaded with values
# just complete the entries according using this keys as examples
#
#default = {
# 'hostname': 'replace_with_hostname',
# 'username': 'replace_with_user',
## 'password': 'replace_with_password',
# 'directory': 'replace_with_directory',
## 'p... | default = {} |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 22 09:26:32 2019
@author: Davide
"""
def f3(graph, startnode, endnode):
# Shortest paths from startnode
shortest_paths = {startnode: (None, 0)}
# Initial node
current_node = startnode
# Set of visited nodes, which we can forget of during o... | """
Created on Sun Dec 22 09:26:32 2019
@author: Davide
"""
def f3(graph, startnode, endnode):
shortest_paths = {startnode: (None, 0)}
current_node = startnode
visited_nodes = set()
while current_node != endnode:
visited_nodes.add(current_node)
destinations = list(graph[current_node])
... |
# -*- coding: utf-8 -*-
"""
Authored by: Fang Jiaan (fduodev@gmail.com)
""" | """
Authored by: Fang Jiaan (fduodev@gmail.com)
""" |
class FlowerCareException(Exception):
'''
Flower Care exception
'''
pass | class Flowercareexception(Exception):
"""
Flower Care exception
"""
pass |
# Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All contributing project au... | {'includes': ['../build/common.gypi'], 'targets': [{'target_name': 'rtc_media', 'type': 'static_library', 'dependencies': ['<(webrtc_root)/base/base.gyp:rtc_base_approved', '<(webrtc_root)/common.gyp:webrtc_common', '<(webrtc_root)/webrtc.gyp:webrtc', '<(webrtc_root)/voice_engine/voice_engine.gyp:voice_engine', '<(webr... |
class Symbol:
""" Represents a language symbol """
def __init__(self, conceptId, text):
""" Initialize the symbol with its concept id and the text """
self.conceptId = conceptId
self.text = text
def __unicode__(self):
""" Return the string representat... | class Symbol:
""" Represents a language symbol """
def __init__(self, conceptId, text):
""" Initialize the symbol with its concept id and the text """
self.conceptId = conceptId
self.text = text
def __unicode__(self):
""" Return the string representation of the Symbol """
... |
'''
Given a binary tree, return the postorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [3,2,1]
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.rig... | """
Given a binary tree, return the postorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
2
/
3
Output: [3,2,1]
"""
class Solution(object):
def postorder_traversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not ro... |
def asset_path(model, asset_name):
if not hasattr(model, '__tfi_asset_path__'):
return None
return model.__tfi_asset_path__(asset_name)
| def asset_path(model, asset_name):
if not hasattr(model, '__tfi_asset_path__'):
return None
return model.__tfi_asset_path__(asset_name) |
# IDLE (Python 3.8.0)
# YMDHMS (Years, Months, Days, Hours, Minutes, Seconds)
def WAF(FrO, O, ScO):
# WAF means Whole And Fraction.
# FrO means First Operand and is a value of a variable.
# O means Operator and is a string of an operator symbol.
# ScO means Second Operand and is a value of a variable.... | def waf(FrO, O, ScO):
if O == ' + ':
sum = FrO + ScO
whole = int(Sum)
fraction = Sum - Whole
return (Whole, Fraction)
elif O == ' - ':
remainder = FrO - ScO
whole = int(Remainder)
fraction = Remainder - Whole
return (Whole, Fraction)
elif O == ... |
class DirectedAdjacencyMatrix:
def __init__(self, n):
self.n = n
self.data = [[0] * n for i in range(n)]
def connect(self, i_from, i_to):
self.data[i_from][i_to] += 1
def disconnect(self, i_from, i_to):
self.data[i_from][i_to] = max(0, self.data[i_from][i_to] - 1)
def ... | class Directedadjacencymatrix:
def __init__(self, n):
self.n = n
self.data = [[0] * n for i in range(n)]
def connect(self, i_from, i_to):
self.data[i_from][i_to] += 1
def disconnect(self, i_from, i_to):
self.data[i_from][i_to] = max(0, self.data[i_from][i_to] - 1)
def... |
class TeachersParser:
def __init__(self, file,days_mapping):
self.file = file
self.days_mapping = days_mapping
def parse_teachers(self):
teachers = {}
for record in self.file:
name = record['osoba']
if name is not None and name != '':
fe... | class Teachersparser:
def __init__(self, file, days_mapping):
self.file = file
self.days_mapping = days_mapping
def parse_teachers(self):
teachers = {}
for record in self.file:
name = record['osoba']
if name is not None and name != '':
fe... |
class Material:
def __init__(self):
self.data = {}
self.data["mesh_color"] = [1.0, 1.0, 1.0, 1.0]
def assign_material(self, index, value):
self.data[index] = value
def get_material_data(self):
return self.data
def get_copy(self):
mat = Material()
... | class Material:
def __init__(self):
self.data = {}
self.data['mesh_color'] = [1.0, 1.0, 1.0, 1.0]
def assign_material(self, index, value):
self.data[index] = value
def get_material_data(self):
return self.data
def get_copy(self):
mat = material()
for n... |
# https://www.interviewbitcom/problems/grid-unique-paths/
# Grid Unique Path
# Input : A = 2, B = 2
# Output : 2
# 2 possible routes : (0, 0) -> (0, 1) -> (1, 1)
# OR : (0, 0) -> (1, 0) -> (1, 1)
class Solution:
# @param A : integer
# @param B : integer
# @return an integer
def uniqu... | class Solution:
def unique_paths(self, rows, cols):
if rows == 1 or cols == 1:
return 1
a = [[1] + [0] * (cols - 1)] * rows
a[0] = [1] * cols
for i in range(1, rows):
for j in range(1, cols):
a[i][j] = a[i - 1][j] + a[i][j - 1]
return ... |
# To Do: Figure out the base item classes for use in the scripting language
class Item():
# The Base Class for All Items
def __init__(self, name, description, value):
if type(name) != str:
raise TypeError("Name must be a string")
self.name = name
if type(descripti... | class Item:
def __init__(self, name, description, value):
if type(name) != str:
raise type_error('Name must be a string')
self.name = name
if type(description) != str:
raise type_error('Description must be a string')
self.description = description
if ... |
"""
Create custom expected conditions in here
See these links for more details:
https://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.support.expected_conditions
http://www.teachmeselenium.com/2018/04/07/python-selenium-waits-writing-own-custom-wait-conditions/
"""
class BrowserIsReady:
... | """
Create custom expected conditions in here
See these links for more details:
https://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.support.expected_conditions
http://www.teachmeselenium.com/2018/04/07/python-selenium-waits-writing-own-custom-wait-conditions/
"""
class Browserisready:
... |
X=1234567891.1234
X=int(X) #1234567890
X=str(X) #"1234567890"
X=X[4] #computer starts at 0
print(X)
| x = 1234567891.1234
x = int(X)
x = str(X)
x = X[4]
print(X) |
# -*- coding: utf-8 -*-
class GildedRose(object):
def __init__(self, items):
self.items = items
def update_quality(self):
for item in self.items:
item.update()
class Item:
def __init__(self, name, sell_in, quality):
self.name = name
self.sell_in = sell_in
... | class Gildedrose(object):
def __init__(self, items):
self.items = items
def update_quality(self):
for item in self.items:
item.update()
class Item:
def __init__(self, name, sell_in, quality):
self.name = name
self.sell_in = sell_in
self.quality = quali... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"Learner.one_batch": "00_core.ipynb",
"unrar": "00_core.ipynb",
"extract_frames": "00_core.ipynb",
"avi2frames": "00_core.ipynb",
"get_instances": "00_core.ipynb",
... | __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'Learner.one_batch': '00_core.ipynb', 'unrar': '00_core.ipynb', 'extract_frames': '00_core.ipynb', 'avi2frames': '00_core.ipynb', 'get_instances': '00_core.ipynb', 'Path.ls_sorted': '00_core.ipynb', 'ImageTuple': '00_core.ipynb', 'ImageTupleTfm': '0... |
LANGUAGES = None
BASE_URL = '/'
STATIC_URL = '/'
DEFAULT_PAGE = None
DEFAULT_LANGUAGE = None
LAYOUTS = {}
BUNDLES = {}
ORDERING = {}
PAGINATION = {}
PAGE_NAME = 'page%i'
| languages = None
base_url = '/'
static_url = '/'
default_page = None
default_language = None
layouts = {}
bundles = {}
ordering = {}
pagination = {}
page_name = 'page%i' |
limit = int(input("Enter upper limit:"))
c = 0
m = 2
while c < limit:
for n in range(1, m + 1):
a = m * m - n * n
b = 2 * m * n
c = m * m + n * n
if c > limit:
break
if a == 0 or b == 0 or c == 0:
break
print(a, b, c)
m = m + 1
| limit = int(input('Enter upper limit:'))
c = 0
m = 2
while c < limit:
for n in range(1, m + 1):
a = m * m - n * n
b = 2 * m * n
c = m * m + n * n
if c > limit:
break
if a == 0 or b == 0 or c == 0:
break
print(a, b, c)
m = m + 1 |
# Databricks notebook source
# MAGIC %md # 2_dp_skinny_record_unassembled: Make the Skinny Record Unassembled Table
# COMMAND ----------
# MAGIC %md
# MAGIC **Description** Gather together the records for each patient in primary and secondary care before they are assembled into a skinny record. This notebook is speci... | batch_id = 'bcaf6e02-a878-44e3-98d8-cc77f5ab2ef2'
def create_table(table_name: str, database_name: str='dars_nic_391419_j3w9t_collab', select_sql_script: str=None) -> None:
"""Will save to table from a global_temp view of the same name as the supplied table name (if no SQL script is supplied)
Otherwise, can supp... |
#-----Read data from 2008
flt2008=pd.read_csv('2008.csv')
print("shape of dataset : ", flt2008.shape)
print("Features in dataset : ", flt2008.columns)
print("No of features in dataset : ", flt2008.columns.shape)
# shape of dataset : s(7009728, 29)
# Features in dataset : Index(['Year', 'Month', 'DayofMonth', 'Da... | flt2008 = pd.read_csv('2008.csv')
print('shape of dataset : ', flt2008.shape)
print('Features in dataset : ', flt2008.columns)
print('No of features in dataset : ', flt2008.columns.shape)
flt2008 = flt2008[flt2008['Cancelled'] == 0]
flt2008.drop(['Cancelled', 'CancellationCode', 'CarrierDelay', 'WeatherDelay', 'NASDela... |
"""
cmec_global_vars.py
These are global variables used throughout CMEC driver.
"version" should be incremented with each new release.
"""
version = "1.1.5"
cmec_library_name = ".cmeclibrary"
cmec_config_dir = ".cmec"
cmec_toc_name = "contents.json"
cmec_settings_name = "settings.json"
cmec_settings_name_alt = "setting... | """
cmec_global_vars.py
These are global variables used throughout CMEC driver.
"version" should be incremented with each new release.
"""
version = '1.1.5'
cmec_library_name = '.cmeclibrary'
cmec_config_dir = '.cmec'
cmec_toc_name = 'contents.json'
cmec_settings_name = 'settings.json'
cmec_settings_name_alt = 'setting... |
# Version info
__version__ = '0.2.6'
__license__ = 'MIT'
# Project description(s)
__description__ = 'First order optimization tools'
# The project's main homepage.
__url__ = 'https://github.com/nirum/descent'
# Author details
__author__ = 'Niru Maheswaranathan'
__author_email__ = 'niru@fastmail.com'
| __version__ = '0.2.6'
__license__ = 'MIT'
__description__ = 'First order optimization tools'
__url__ = 'https://github.com/nirum/descent'
__author__ = 'Niru Maheswaranathan'
__author_email__ = 'niru@fastmail.com' |
def getID(i,j):
return ("%05d%05d")%(i,j)
def getIDL(i,j):
return ("%08d%08d")%(i,j)
def getIDFour(i,j,m,n):
return ("%05d%05d%05d%05d")%(i,j,m,n)
| def get_id(i, j):
return '%05d%05d' % (i, j)
def get_idl(i, j):
return '%08d%08d' % (i, j)
def get_id_four(i, j, m, n):
return '%05d%05d%05d%05d' % (i, j, m, n) |
def average_number(*args):
return sum(args, 0.0) / len(args)
average_number(6, 9, 10)
| def average_number(*args):
return sum(args, 0.0) / len(args)
average_number(6, 9, 10) |
#2
for row in range(10):
for col in range(10):
if (row==9 )or (col+row==9 and row!=0 and row!=2 and row!=1)or (row==2 and col==6)or (row==1 and col==6)or (row==0 and col==5)or (row==0 and col==4)or (row==0 and col==3)or (row==1 and col==2):
print("*",end=" ")
else:
pri... | for row in range(10):
for col in range(10):
if row == 9 or (col + row == 9 and row != 0 and (row != 2) and (row != 1)) or (row == 2 and col == 6) or (row == 1 and col == 6) or (row == 0 and col == 5) or (row == 0 and col == 4) or (row == 0 and col == 3) or (row == 1 and col == 2):
print('*', end... |
# Challenge 52, easy
# https://www.reddit.com/r/dailyprogrammer/comments/tmnfq/5142012_challenge_52_easy/
word_list = ['Shoe', 'Hat', "ZZTop", "Aa"]
def get_value(word):
new_letter_values = [ord(letter.upper()) - 64 for letter in word]
return sum(new_letter_values)
print(sorted(word_list, key = get_value))
| word_list = ['Shoe', 'Hat', 'ZZTop', 'Aa']
def get_value(word):
new_letter_values = [ord(letter.upper()) - 64 for letter in word]
return sum(new_letter_values)
print(sorted(word_list, key=get_value)) |
# 2020.09.18
# Problem Statement:
# https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
# do early return
if len(nums) <= 2: return len(nums)
# count counts for the occurance of the current element
... | class Solution:
def remove_duplicates(self, nums: List[int]) -> int:
if len(nums) <= 2:
return len(nums)
count = 1
index = 1
while True:
if index > len(nums) - 1:
break
if nums[index] == nums[index - 1]:
count = cou... |
"""
On a N * N grid, we place some 1 * 1 * 1 cubes. Each value v = grid[i][j] represents a tower of v cubes
placed on top of grid cell (i, j). Return the total surface area of the resulting shapes.
Example 1:
Input: [[2]]
Output: 10
Example 2:
Input: [[1,2],[3,4]]
Output: 34
Example 3:
Input:... | """
On a N * N grid, we place some 1 * 1 * 1 cubes. Each value v = grid[i][j] represents a tower of v cubes
placed on top of grid cell (i, j). Return the total surface area of the resulting shapes.
Example 1:
Input: [[2]]
Output: 10
Example 2:
Input: [[1,2],[3,4]]
Output: 34
Example 3:
Input:... |
#Input Format
n = int(input())
for i in range(1, 11):
#Output Format
print(str(n) + " x " + str(i) + " = " + str(n * i))
| n = int(input())
for i in range(1, 11):
print(str(n) + ' x ' + str(i) + ' = ' + str(n * i)) |
tipo=0
alcohol=0
gasolina=0
diesel=0
while True:
tipo=int(input(""))
if tipo==1:
alcohol=alcohol+1
elif tipo==2:
gasolina=gasolina+1
elif tipo==3:
diesel=diesel+1
elif tipo==4:
break
print("MUITO OBRIGADO")
print("Alcool: "+str(alcohol))
print("Gasolina: "+str(gasolin... | tipo = 0
alcohol = 0
gasolina = 0
diesel = 0
while True:
tipo = int(input(''))
if tipo == 1:
alcohol = alcohol + 1
elif tipo == 2:
gasolina = gasolina + 1
elif tipo == 3:
diesel = diesel + 1
elif tipo == 4:
break
print('MUITO OBRIGADO')
print('Alcool: ' + str(alcohol)... |
def write_ascii_triangle(triangle_doc, block, sidelength):
""" (File Open for writing, str, int) -> NoneType
Precondition: len(block) == 1
Write an ascii isosceles right triangle of character block that is
sidelength characters wide and high to triangle_doc. The right
angle should be in th... | def write_ascii_triangle(triangle_doc, block, sidelength):
""" (File Open for writing, str, int) -> NoneType
Precondition: len(block) == 1
Write an ascii isosceles right triangle of character block that is
sidelength characters wide and high to triangle_doc. The right
angle should be in th... |
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/apple/catkin_ws/src/hd_map/msg/element.msg;/home/apple/catkin_ws/src/hd_map/msg/elements.msg"
services_str = ""
pkg_name = "hd_map"
dependencies_str = "std_msgs;sensor_msgs"
langs = "gencpp;geneus;genlisp;gennodejs;genpy"
dep_include_paths_str =... | messages_str = '/home/apple/catkin_ws/src/hd_map/msg/element.msg;/home/apple/catkin_ws/src/hd_map/msg/elements.msg'
services_str = ''
pkg_name = 'hd_map'
dependencies_str = 'std_msgs;sensor_msgs'
langs = 'gencpp;geneus;genlisp;gennodejs;genpy'
dep_include_paths_str = 'hd_map;/home/apple/catkin_ws/src/hd_map/msg;std_msg... |
original = input().split()
new = [int(i) for i in original]
new.sort()
for i in new:
print(i)
print('')
for k in original:
print(k)
| original = input().split()
new = [int(i) for i in original]
new.sort()
for i in new:
print(i)
print('')
for k in original:
print(k) |
expected_output = {
"oper_state": {
"admin_enabled" : False,
"oper_up" : False }
} | expected_output = {'oper_state': {'admin_enabled': False, 'oper_up': False}} |
# https://leetcode.com/problems/paint-fence/
# ---------------------------------------------------
# Runtime Complexity: O(N)
# Space Complexity: O(1)
class Solution:
def numWays(self, n: int, k: int) -> int:
if n == 0:
return 0
if n == 1:
return k
same_color = k
... | class Solution:
def num_ways(self, n: int, k: int) -> int:
if n == 0:
return 0
if n == 1:
return k
same_color = k
diff_color = k * (k - 1)
for i in range(2, n):
tmp = diff_color
diff_color = (diff_color + same_color) * (k - 1)
... |
def main():
input_int = input("Choose a number(1): ")
input_int2 = input("Choose another number(2): ")
if represents_int(input_int) and represents_int(input_int2):
return print("Both values are ints. sum= %i" %(int(input_int) + int(input_int2)))
return print("One or more of the values is not a... | def main():
input_int = input('Choose a number(1): ')
input_int2 = input('Choose another number(2): ')
if represents_int(input_int) and represents_int(input_int2):
return print('Both values are ints. sum= %i' % (int(input_int) + int(input_int2)))
return print('One or more of the values is not an... |
"""
Data Access Layer
Responsible for database management, creating and updating the databse and retrieving values stored in it.
"""
| """
Data Access Layer
Responsible for database management, creating and updating the databse and retrieving values stored in it.
""" |
# Error classes for peripherals
#
# Luz micro-controller simulator
# Eli Bendersky (C) 2008-2010
#
class PeripheralError(Exception): pass
class PeripheralMemoryError(Exception): pass
class PeripheralMemoryAlignError(PeripheralMemoryError): pass
class PeripheralMemoryAccessError(PeripheralMemoryError): pass
| class Peripheralerror(Exception):
pass
class Peripheralmemoryerror(Exception):
pass
class Peripheralmemoryalignerror(PeripheralMemoryError):
pass
class Peripheralmemoryaccesserror(PeripheralMemoryError):
pass |
#!/usr/bin/env python3
code_0 = 0
code_1 = 1
code_a = "a"
code_b = "b"
l_b = {code_a}
l_c = {code_b: code_0}
if __name__ == "__main__":
assert "a" in l_b
# Dereferencing items in the dict fails on Rust.
# Dict compare 'in' does not work on Dart
# Print of sets and dicts fails on Rust
print("OK... | code_0 = 0
code_1 = 1
code_a = 'a'
code_b = 'b'
l_b = {code_a}
l_c = {code_b: code_0}
if __name__ == '__main__':
assert 'a' in l_b
print('OK') |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
@author: ??
@file: __init__.py.py
@time: 2018/8/23 10:18
@desc:
''' | """
@author: ??
@file: __init__.py.py
@time: 2018/8/23 10:18
@desc:
""" |
"""
1) For a<0, the solution decays in time.
For a>0, the solution grows in time.
For a=0, the solution stays at 1 (and is stable).
2) For small-ish dt, the solution still looks the same.
As dt gets bigger, the solution starts to look choppier and is no longer smooth,
but still has mostly the right trends.
For a = 0.... | """
1) For a<0, the solution decays in time.
For a>0, the solution grows in time.
For a=0, the solution stays at 1 (and is stable).
2) For small-ish dt, the solution still looks the same.
As dt gets bigger, the solution starts to look choppier and is no longer smooth,
but still has mostly the right trends.
For a = 0.1... |
def countdown(i):
if i < 1:
return 0
else:
print(i)
countdown(i - 1)
number = int(input())
countdown(number)
| def countdown(i):
if i < 1:
return 0
else:
print(i)
countdown(i - 1)
number = int(input())
countdown(number) |
class Solution:
def removeDuplicates(self, nums):
cur = 0
for i in range(len(nums)):
if nums[cur] != nums[i]:
cur += 1
nums[cur] = nums[i]
print(cur + 1)
return(cur + 1)
obj = Solution()
obj.removeDuplicates([1,1,2])
obj.removeDuplicates... | class Solution:
def remove_duplicates(self, nums):
cur = 0
for i in range(len(nums)):
if nums[cur] != nums[i]:
cur += 1
nums[cur] = nums[i]
print(cur + 1)
return cur + 1
obj = solution()
obj.removeDuplicates([1, 1, 2])
obj.removeDuplicates... |
#!/usr/bin/env python
def read_input(filename):
"""
>>> read_input('example')
[16, 1, 2, 0, 4, 2, 7, 1, 2, 14]
"""
with open(filename) as fd:
return [int(n) for n in fd.readline().strip().split(",")]
def fuelforpos(pos, crabs):
"""Meh
>>> crabs = read_input('example')
>>> fue... | def read_input(filename):
"""
>>> read_input('example')
[16, 1, 2, 0, 4, 2, 7, 1, 2, 14]
"""
with open(filename) as fd:
return [int(n) for n in fd.readline().strip().split(',')]
def fuelforpos(pos, crabs):
"""Meh
>>> crabs = read_input('example')
>>> fuelforpos(1, crabs)
41
... |
# from enum import IntEnum
class __Error__():
def __init__(self, code, msg):
self.code = code
self.msg = msg
def __str__(self):
return f'[{self.code}] {self.msg}'
class ExceptionApp(Exception):
def __init__(self, error, *args):
self.errCode = error.code
self.errMsg = error.msg.format(*args)... | class __Error__:
def __init__(self, code, msg):
self.code = code
self.msg = msg
def __str__(self):
return f'[{self.code}] {self.msg}'
class Exceptionapp(Exception):
def __init__(self, error, *args):
self.errCode = error.code
self.errMsg = error.msg.format(*args)
... |
#Program for Odd Even
a=int(input("Enter positive integer "))
if a%2==0:
print("The given number ",a,"is even")
else:
print("The given number ",a,"is odd")
| a = int(input('Enter positive integer '))
if a % 2 == 0:
print('The given number ', a, 'is even')
else:
print('The given number ', a, 'is odd') |
def printHam(self):
print('ham')
class myclass(object):
def __init__(self):
self.x = 5
TypeClass = type("TypeClass", (), {"x": 5, "printHam": printHam})
m = myclass()
t = TypeClass()
print(m.x, t.x)
print(m == t)
print(type(m))
t.printHam()
| def print_ham(self):
print('ham')
class Myclass(object):
def __init__(self):
self.x = 5
type_class = type('TypeClass', (), {'x': 5, 'printHam': printHam})
m = myclass()
t = type_class()
print(m.x, t.x)
print(m == t)
print(type(m))
t.printHam() |
'''
speed: 89.11%
memory: 21:02%
N = len(S), A = 1~26(size of diff alpabet)
ex) aab, N=3, A=2
time complexity: O(A * (N + logA))
space complexity: O(N)
'''
class Solution:
def reorganizeString(self, S: str) -> str:
n = len(S)
a= []
for c,x in sorted((S.count(x), x) for x in set(S)):... | """
speed: 89.11%
memory: 21:02%
N = len(S), A = 1~26(size of diff alpabet)
ex) aab, N=3, A=2
time complexity: O(A * (N + logA))
space complexity: O(N)
"""
class Solution:
def reorganize_string(self, S: str) -> str:
n = len(S)
a = []
for (c, x) in sorted(((S.count(x), x) for x in set(S))):... |
input = """
c num blocks = 1
c num vars = 150
c minblockids[0] = 1
c maxblockids[0] = 150
p cnf 150 667
-11 -87 28 0
-91 18 -5 0
-9 50 -72 0
-15 -93 -2 0
127 -81 39 0
-107 -49 25 0
132 42 -4 0
63 -103 42 0
95 85 -133 0
-57 -74 -15 0
-150 -76 71 0
7 -141 -104 0
107 -19 -150 0
-69 12 -122 0
72 87 -70 0
31 71 -79 0
42 -99... | input = '\nc num blocks = 1\nc num vars = 150\nc minblockids[0] = 1\nc maxblockids[0] = 150\np cnf 150 667\n-11 -87 28 0\n-91 18 -5 0\n-9 50 -72 0\n-15 -93 -2 0\n127 -81 39 0\n-107 -49 25 0\n132 42 -4 0\n63 -103 42 0\n95 85 -133 0\n-57 -74 -15 0\n-150 -76 71 0\n7 -141 -104 0\n107 -19 -150 0\n-69 12 -122 0\n72 87 -70 0\... |
def permutationIsAPalindrome(inString):
seenDict = {}
for character in inString:
if character not in seenDict:
seenDict[character] = 1
else:
del seenDict[character]
return len(seenDict.keys()) <= 1
def main():
testCaseList = []
testCaseList.append(["civic"... | def permutation_is_a_palindrome(inString):
seen_dict = {}
for character in inString:
if character not in seenDict:
seenDict[character] = 1
else:
del seenDict[character]
return len(seenDict.keys()) <= 1
def main():
test_case_list = []
testCaseList.append(['civ... |
a = 4
b = 5 # Operator (=) assigns the value to variable
print(a, "is of type", type(a))
print(a + b)
print(4 + 5)
print(a - a * b)
print(25 - 3 * 6)
print((20 - 3 * 7) / 2)
print(9 / 5)
c = b / a # division returns a floating point number
print(c, "is of type", type(c))
print(c) # No need to explicitly decl... | a = 4
b = 5
print(a, 'is of type', type(a))
print(a + b)
print(4 + 5)
print(a - a * b)
print(25 - 3 * 6)
print((20 - 3 * 7) / 2)
print(9 / 5)
c = b / a
print(c, 'is of type', type(c))
print(c)
a = 4
b = 5
d = b // a
print(d)
print(d, 'is of type', type(d))
print(-7 / 5)
print(7 / 5)
print(-7 // 5)
a = 7
b = 5
e = b ** ... |
ES_HOST = 'localhost:9200'
ES_INDEX = 'pending-go_bp'
ES_DOC_TYPE = 'geneset'
API_PREFIX = 'go_bp'
API_VERSION = ''
| es_host = 'localhost:9200'
es_index = 'pending-go_bp'
es_doc_type = 'geneset'
api_prefix = 'go_bp'
api_version = '' |
def load_pdf_document(session, inline, pdf_data):
"""Load a PDF document in the browser using pdf.js"""
session.url = inline("""
<!doctype html>
<script src="/_pdf_js/pdf.js"></script>
<canvas></canvas>
<script>
async function getText() {
pages = [];
let loadingTask = pdfjsLib.getDocument({data: atob("%s")}... | def load_pdf_document(session, inline, pdf_data):
"""Load a PDF document in the browser using pdf.js"""
session.url = inline('\n<!doctype html>\n<script src="/_pdf_js/pdf.js"></script>\n<canvas></canvas>\n<script>\nasync function getText() {\n pages = [];\n let loadingTask = pdfjsLib.getDocument({data: atob("... |
# Copyright 2020 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.
DEPS = [
'flutter/firebase',
'recipe_engine/path',
]
def RunSteps(api):
docs_path = api.path['start_dir'].join('flutter', 'dev', 'docs')
api.fi... | deps = ['flutter/firebase', 'recipe_engine/path']
def run_steps(api):
docs_path = api.path['start_dir'].join('flutter', 'dev', 'docs')
api.firebase.deploy_docs({}, {}, docs_path, 'myproject')
def gen_tests(api):
yield api.test('basic') |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# Diameter = 1+ max depth of left and max depth of right
# use DFS to recursively find left and right nodes
class Solution:
... | class Solution:
def diameter_of_binary_tree(self, root: TreeNode) -> int:
self.ans = 1
def depth(p):
if not p:
return 0
left = depth(p.left)
right = depth(p.right)
self.ans = max(self.ans, left + right + 1)
return max(left... |
"""Event handlers for the function editor window."""
##
# Copyright 2013 Chad Spratt
# 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... | """Event handlers for the function editor window."""
class Gui_Functioneditor(object):
def showfunceditor(self, _widget, _data=None):
"""Initialize and show the function editor window."""
selectedlibname = self.gui['calclibrarycomboentry'].get_active_text()
selection = self.gui['calcfuncti... |
"""Declare runtime dependencies
These are needed for local dev, and users must install them as well.
See https://docs.bazel.build/versions/main/skylark/deploying.html#dependencies
"""
load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archi... | """Declare runtime dependencies
These are needed for local dev, and users must install them as well.
See https://docs.bazel.build/versions/main/skylark/deploying.html#dependencies
"""
load('@bazel_tools//tools/build_defs/repo:git.bzl', 'git_repository')
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archiv... |
def extractLightNovelswithMisachan(item):
"""
'Light Novels with Misa-chan~'
"""
if item['title'].startswith("Protected:"):
return None
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
if item['title... | def extract_light_novelswith_misachan(item):
"""
'Light Novels with Misa-chan~'
"""
if item['title'].startswith('Protected:'):
return None
(vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
... |
"""
* Alpha Mask.
*
* Loads a "mask" for an image to specify the transparency
* in different parts of the image. The two images are blended
* together using the mask() method of PImage.
"""
def setup():
size(640, 360)
global img, imgMask
img = loadImage("moonwalk.jpg")
imgMask = loadImage("m... | """
* Alpha Mask.
*
* Loads a "mask" for an image to specify the transparency
* in different parts of the image. The two images are blended
* together using the mask() method of PImage.
"""
def setup():
size(640, 360)
global img, imgMask
img = load_image('moonwalk.jpg')
img_mask = load_image(... |
sieve = [True] * 110000
primes = []
for i in range(2, 110000):
if sieve[i] == True:
primes.append(i)
for j in range(2*i, 110000, i):
sieve[j] = False
while True:
n, p = map(int, input().split())
if n == -1 and p == -1: break
cnt = 0
for i in primes:
if n < i:
... | sieve = [True] * 110000
primes = []
for i in range(2, 110000):
if sieve[i] == True:
primes.append(i)
for j in range(2 * i, 110000, i):
sieve[j] = False
while True:
(n, p) = map(int, input().split())
if n == -1 and p == -1:
break
cnt = 0
for i in primes:
if... |
output = []
with open("iso3166_alpha2_codes.csv") as f:
for line in f:
output.append(line[0:2])
print(output) | output = []
with open('iso3166_alpha2_codes.csv') as f:
for line in f:
output.append(line[0:2])
print(output) |
def deduplicate(iterable):
"""
Yields deduplicated values, in original order.
The values of iterable must be hashable
"""
seen = set()
for val in iterable:
if val not in seen:
seen.add(val)
yield val
| def deduplicate(iterable):
"""
Yields deduplicated values, in original order.
The values of iterable must be hashable
"""
seen = set()
for val in iterable:
if val not in seen:
seen.add(val)
yield val |
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
x = 0
# counter = collections.Counter(operations)
# print(counter)
# for operation, count in counter.items():
# if operation == "X++" or operation == "++X":
# ... | class Solution:
def final_value_after_operations(self, operations: List[str]) -> int:
x = 0
for operation in operations:
if operation == 'X++' or operation == '++X':
x += 1
else:
x -= 1
return x |
#the array or the xo
"""
[[00,01,02],
[10,11,12],
[20,21,22]]
"""
def p_r_box(box):
"""Prints the xo box when called"""
#print(f"{box[0]}\n{box[1]}\n{box[2]}\n")
for i in range(3):
print('+-------'*3+'+')
print('| '*3+'|')
for j in range(3):
print('... | """
[[00,01,02],
[10,11,12],
[20,21,22]]
"""
def p_r_box(box):
"""Prints the xo box when called"""
for i in range(3):
print('+-------' * 3 + '+')
print('| ' * 3 + '|')
for j in range(3):
print('| ' + box[i][j] + ' ', end='')
print('|')
... |
"""Test ansys.mapdl.solution.Solution"""
def time_step_size(mapdl):
assert isinstance(mapdl.solution.time_step_size, float)
def test_n_cmls(mapdl):
assert isinstance(mapdl.solution.n_cmls, float)
def test_n_cmss(mapdl):
assert isinstance(mapdl.solution.n_cmss, float)
def test_n_eqit(mapdl):
asse... | """Test ansys.mapdl.solution.Solution"""
def time_step_size(mapdl):
assert isinstance(mapdl.solution.time_step_size, float)
def test_n_cmls(mapdl):
assert isinstance(mapdl.solution.n_cmls, float)
def test_n_cmss(mapdl):
assert isinstance(mapdl.solution.n_cmss, float)
def test_n_eqit(mapdl):
assert i... |
# https://leetcode.com/problems/nim-game/
#
# You are playing the following Nim Game with your friend:
# There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones.
# The one who removes the last stone will be the winner.
# You will take the first turn to remove the stones.
#
# Both... | class Solution(object):
def can_win_nim(self, n):
"""
:type n: int
:rtype: bool
"""
if n % 4:
return True
return False
if __name__ == '__main__':
s = solution()
s.canWinNim(1348820612) |
class Policy(object):
'''
Encapsulates a policy document for an S3 POST request.
http://docs.aws.amazon.com/AmazonS3/latest/dev/HTTPPOSTForms.html#HTTPPOSTConstructPolicy
expiration: The policy expiration date, a native datetime.datetime object
conditions: A list of PolicyCondition objects
... | class Policy(object):
"""
Encapsulates a policy document for an S3 POST request.
http://docs.aws.amazon.com/AmazonS3/latest/dev/HTTPPOSTForms.html#HTTPPOSTConstructPolicy
expiration: The policy expiration date, a native datetime.datetime object
conditions: A list of PolicyCondition objects
... |
GOOGLE_GEOCODE_KEY = 'key'
YELP_CONSUMER_KEY = 'key'
YELP_CONSUMER_SECRET = 'key'
YELP_TOKEN = 'key'
YELP_TOKEN_SECRET = 'key'
TMDB_KEY = 'key'
WA_KEY = 'key'
UL_KEY = 'key'
| google_geocode_key = 'key'
yelp_consumer_key = 'key'
yelp_consumer_secret = 'key'
yelp_token = 'key'
yelp_token_secret = 'key'
tmdb_key = 'key'
wa_key = 'key'
ul_key = 'key' |
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
n = len(s)
m = len(p)
res = []
if n < m:
return
s_ct = [0] * 26
p_ct = [0] * 26
for i in range(m):
p_ct[ord(p[i]) - ord('a')] += 1
s_ct[ord(s[i]) - ord('a... | class Solution:
def find_anagrams(self, s: str, p: str) -> List[int]:
n = len(s)
m = len(p)
res = []
if n < m:
return
s_ct = [0] * 26
p_ct = [0] * 26
for i in range(m):
p_ct[ord(p[i]) - ord('a')] += 1
s_ct[ord(s[i]) - ord('... |
#!/usr/bin/env python
def override_init():
return { 'init': 'systemd' }
| def override_init():
return {'init': 'systemd'} |
# -*- coding: utf-8 -*-
def get_context_and_entities(request):
return request['context'], request['entities']
def get_first_entity_value(entities, entity):
if entities is None or entity not in entities:
return None
value = entities[entity][0]['value']
if not value:
return None
return value['value'] if isinsta... | def get_context_and_entities(request):
return (request['context'], request['entities'])
def get_first_entity_value(entities, entity):
if entities is None or entity not in entities:
return None
value = entities[entity][0]['value']
if not value:
return None
return value['value'] if is... |
# insertion sort implementation
# author: D1N3SHh
# https://github.com/D1N3SHh/algorithms
def insertion_sort(A):
for j in range(1, len(A)):
key = A[j]
i = j - 1
while i >= 0 and A[i] > key:
A[i + 1] = A[i]
i -= 1
A[i + 1] = key
return A
def example_usa... | def insertion_sort(A):
for j in range(1, len(A)):
key = A[j]
i = j - 1
while i >= 0 and A[i] > key:
A[i + 1] = A[i]
i -= 1
A[i + 1] = key
return A
def example_usage():
a = [3, 7, 1, 8, 4, 6, 9, 2, 5]
print('Unsorted:\t', A)
print('Sorted:\t\t'... |
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
result = []
def dfs( need, curr, start ):
if need == 0:
result.append( list(curr) )
return
for idx, c i... | class Solution:
def combination_sum(self, candidates: List[int], target: int) -> List[List[int]]:
result = []
def dfs(need, curr, start):
if need == 0:
result.append(list(curr))
return
for (idx, c) in enumerate(candidates[start:]):
... |
class News:
def __init__(
self,
id: int or None,
headline: str or None,
url: str,
author: str,
image_url: str or None,
title: str or None,
external_id: str or None,
media: dict or None,
published_... | class News:
def __init__(self, id: int or None, headline: str or None, url: str, author: str, image_url: str or None, title: str or None, external_id: str or None, media: dict or None, published_at, updated_at):
self.id = id
self.headline = headline
self.image_url = image_url
self.t... |
doc = list(string.split(""))
blockl_list = ["Report Date", "Booking Status", "Printed By", "District", "UCR Code", "OBTN", "Court of Appearance", "Master Name", "Age", "Location of Arrest",
"Booking Name", "Alias", "Address", "Charges", "Booking#", "Incident#", "CR Number", "Booking Date", "Arrest Date", "... | doc = list(string.split(''))
blockl_list = ['Report Date', 'Booking Status', 'Printed By', 'District', 'UCR Code', 'OBTN', 'Court of Appearance', 'Master Name', 'Age', 'Location of Arrest', 'Booking Name', 'Alias', 'Address', 'Charges', 'Booking#', 'Incident#', 'CR Number', 'Booking Date', 'Arrest Date', 'RA Number', '... |
def read_file():
with open('animal-dataset.txt') as f:
mylist = [tuple(i.split(',')) for i in f.read().splitlines()]
print(mylist)
read_file()
| def read_file():
with open('animal-dataset.txt') as f:
mylist = [tuple(i.split(',')) for i in f.read().splitlines()]
print(mylist)
read_file() |
"""miscellaneous routines that might be useful sometime"""
class TrieNode(object):
"""
Our trie node implementation. Very basic. but does the job
from https://towardsdatascience.com/implementing-a-trie-data-structure-in-python-in-less-than-100-lines-of-code-a877ea23c1a1
"""
def __init__(self, cha... | """miscellaneous routines that might be useful sometime"""
class Trienode(object):
"""
Our trie node implementation. Very basic. but does the job
from https://towardsdatascience.com/implementing-a-trie-data-structure-in-python-in-less-than-100-lines-of-code-a877ea23c1a1
"""
def __init__(self, cha... |
class ZeroEdgeReduction:
"""Reduction that automatically contracts edges with weight 0"""
def __init__(self):
self.merged = []
self.enabled = True
def reduce(self, steiner, prev_cnt, curr_cnt):
track = 0
changed = True
while changed:
changed = False
... | class Zeroedgereduction:
"""Reduction that automatically contracts edges with weight 0"""
def __init__(self):
self.merged = []
self.enabled = True
def reduce(self, steiner, prev_cnt, curr_cnt):
track = 0
changed = True
while changed:
changed = False
... |
def indented(line: str, indent: int):
return ' ' * indent + line
def formatted(file: str):
lines = []
indent = 0
for line in file.split('\n'):
line = line.strip()
if line == '':
continue
if line.endswith('{'):
line = indented(line, indent)
in... | def indented(line: str, indent: int):
return ' ' * indent + line
def formatted(file: str):
lines = []
indent = 0
for line in file.split('\n'):
line = line.strip()
if line == '':
continue
if line.endswith('{'):
line = indented(line, indent)
ind... |
# https://leetcode.com/problems/add-strings/
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
max_len = max(len(num1), len(num2))
num1 = num1.zfill(max_len)
num2 = num2.zfill(max_len)
digits = list()
carry = 0
for idx in reversed(range(max_len)):
... | class Solution:
def add_strings(self, num1: str, num2: str) -> str:
max_len = max(len(num1), len(num2))
num1 = num1.zfill(max_len)
num2 = num2.zfill(max_len)
digits = list()
carry = 0
for idx in reversed(range(max_len)):
digit1 = int(num1[idx])
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Event:
def __init__(self, code, name=''):
self.code = code
self.name = name or code
def __str__(self):
return '{} : {}'.format(self.code, self.name)
class State:
def __init__(self, name, description=''):
... | class Event:
def __init__(self, code, name=''):
self.code = code
self.name = name or code
def __str__(self):
return '{} : {}'.format(self.code, self.name)
class State:
def __init__(self, name, description=''):
self.name = name
self.description = description or sel... |
# Generated from 'Menus.h'
def FOUR_CHAR_CODE(x): return x
noMark = 0
kMenuDrawMsg = 0
kMenuSizeMsg = 2
kMenuPopUpMsg = 3
kMenuCalcItemMsg = 5
kMenuThemeSavvyMsg = 7
mDrawMsg = 0
mSizeMsg = 2
mPopUpMsg = 3
mCalcItemMsg = 5
mChooseMsg = 1
mDrawItemMsg = 4
kMenuChooseMsg = 1
kMenuDrawItemMsg = 4
kThemeSavvyMenuResponse ... | def four_char_code(x):
return x
no_mark = 0
k_menu_draw_msg = 0
k_menu_size_msg = 2
k_menu_pop_up_msg = 3
k_menu_calc_item_msg = 5
k_menu_theme_savvy_msg = 7
m_draw_msg = 0
m_size_msg = 2
m_pop_up_msg = 3
m_calc_item_msg = 5
m_choose_msg = 1
m_draw_item_msg = 4
k_menu_choose_msg = 1
k_menu_draw_item_msg = 4
k_theme... |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 10 17:48:47 2018
@author: dhb-lx
"""
| """
Created on Fri Aug 10 17:48:47 2018
@author: dhb-lx
""" |
""" Implements a macro for constructing Docker images.
"""
load("@io_bazel_rules_docker//lang:image.bzl", "app_layer")
def container_image(name, binary, base, **kwargs):
"""Constructs a container image for the given binary.
Args:
name: Name of the target.
binary: The binary to embed in the im... | """ Implements a macro for constructing Docker images.
"""
load('@io_bazel_rules_docker//lang:image.bzl', 'app_layer')
def container_image(name, binary, base, **kwargs):
"""Constructs a container image for the given binary.
Args:
name: Name of the target.
binary: The binary to embed in the ima... |
# Copyright 2012 Google Inc. All Rights Reserved.
__author__ = 'benvanik@google.com (Ben Vanik)'
class InstanceInfo(object):
"""A debuggable application instance.
Each instance represents a single process that can be debugged. Some providers
may only have a single instance, where as others may have many (like ... | __author__ = 'benvanik@google.com (Ben Vanik)'
class Instanceinfo(object):
"""A debuggable application instance.
Each instance represents a single process that can be debugged. Some providers
may only have a single instance, where as others may have many (like a web
browser that may have one per tab).
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.