content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def __repr__(self):
return "{}".format(self.val)
class Solution(object):
# @param root, a tree node
# @return a boolean
# Time: N
... | class Treenode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def __repr__(self):
return '{}'.format(self.val)
class Solution(object):
def is_valid_bst(self, root):
output = []
self.inOrderTraversal(root, output)
fo... |
#https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/two-strings-4/
entry = int(input())
for i in range(entry):
string1, string2 = input().split()
for c in string1:
if c in string2:
string1 = string1.replace(c, '', 1)
string2 = stri... | entry = int(input())
for i in range(entry):
(string1, string2) = input().split()
for c in string1:
if c in string2:
string1 = string1.replace(c, '', 1)
string2 = string2.replace(c, '', 1)
if len(string1) + len(string2) > 1:
print('NO')
else:
print('YES') |
#a1q2c.py
#HUGHXIE
#input for color and time from light
color = input("What color is the light? (G/Y/R) :")
speed = float(input("Enter speed of car in m/s: "))
distance = float(input("Enter distance from light in meters: "))
time = (distance / speed)
#checks if color is red and time is greater than 2 or color is yell... | color = input('What color is the light? (G/Y/R) :')
speed = float(input('Enter speed of car in m/s: '))
distance = float(input('Enter distance from light in meters: '))
time = distance / speed
if color == 'R' and time <= 2 or (color == 'Y' and time <= 5) or color == 'G':
print('Go')
else:
print('Stop') |
def without_end(str):
if len(str) == 2:
return ''
else:
str = str[1:]
l = len(str) -1
str = str[:l]
return str
| def without_end(str):
if len(str) == 2:
return ''
else:
str = str[1:]
l = len(str) - 1
str = str[:l]
return str |
inFile = open("/etc/php5/fpm/pool.d/www.conf", "r", encoding = "utf-8")
string = inFile.read()
string = string.replace("pm.max_children = 5", "pm.max_children = 100")
inFile.close()
out = open("/etc/php5/fpm/pool.d/www.conf", "w", encoding = "utf-8")
out.write(string)
out.close()
| in_file = open('/etc/php5/fpm/pool.d/www.conf', 'r', encoding='utf-8')
string = inFile.read()
string = string.replace('pm.max_children = 5', 'pm.max_children = 100')
inFile.close()
out = open('/etc/php5/fpm/pool.d/www.conf', 'w', encoding='utf-8')
out.write(string)
out.close() |
"""
This file contains the implementation of functions
that are not represented as a single node in the
computational graph, but are
treated as a **compound** function.
Note
----
These functions should be replaced by a dedicated implementation in
* algopy.Function
* algopy.UTPM
so they are represented by a single n... | """
This file contains the implementation of functions
that are not represented as a single node in the
computational graph, but are
treated as a **compound** function.
Note
----
These functions should be replaced by a dedicated implementation in
* algopy.Function
* algopy.UTPM
so they are represented by a single n... |
class Calculator():
def __init__(self, number_1, number_2):
self.number_1 = number_1
self.number_2 = number_2
def add(self):
return self.number_1 + self.number_2
def subtract(self):
return self.number_1 - self.number_2
def multiply(self):
return self.number_1 ... | class Calculator:
def __init__(self, number_1, number_2):
self.number_1 = number_1
self.number_2 = number_2
def add(self):
return self.number_1 + self.number_2
def subtract(self):
return self.number_1 - self.number_2
def multiply(self):
return self.number_1 * ... |
# Copyright 2016-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
"""
Functions that handle co... | """
Functions that handle correcting 'visiblity' arguments
"""
load('@fbcode_macros//build_defs:visibility_exceptions.bzl', 'WHITELIST')
def get_visibility_for_base_path(visibility_attr, name_attr, base_path):
"""
Gets the default visibility for a given base_path.
If the base_path is an experimental path ... |
happy_nums = set()
happy_nums.add(1)
class Solution:
def sqrSum(self, n: int) -> int:
res = 0
for c in str(n):
res += int(c)**2
return res
def isHappy(self, n: int) -> bool:
global happy_nums
temp = set()
while True:
sqr = self.sqrSum(n... | happy_nums = set()
happy_nums.add(1)
class Solution:
def sqr_sum(self, n: int) -> int:
res = 0
for c in str(n):
res += int(c) ** 2
return res
def is_happy(self, n: int) -> bool:
global happy_nums
temp = set()
while True:
sqr = self.sqrSu... |
def swap(lst):
if len(lst) < 2:
return lst
first = lst[0]
last = lst[-1]
return [last] + lst[1:-1] + [first]
print(swap([12, 35, 9, 56, 24]))
print(swap([1, 2, 3]))
| def swap(lst):
if len(lst) < 2:
return lst
first = lst[0]
last = lst[-1]
return [last] + lst[1:-1] + [first]
print(swap([12, 35, 9, 56, 24]))
print(swap([1, 2, 3])) |
a, b, c = input().split(" ")
a = int(a)
b = int(b)
c = int(c)
if (c < a + b) and (b < c + a) and (a < b + c) and (0 < a,b,c < 10**5):
if((a != b and b == c) or ( a == c and a != b) or ( a == b and c != b)):
print("Valido-Isoceles")
if ((a**2 == b**2 + c**2) or (b**2 == a**2 + c**2) or (c**2 == b**2... | (a, b, c) = input().split(' ')
a = int(a)
b = int(b)
c = int(c)
if c < a + b and b < c + a and (a < b + c) and (0 < a, b, c < 10 ** 5):
if a != b and b == c or (a == c and a != b) or (a == b and c != b):
print('Valido-Isoceles')
if a ** 2 == b ** 2 + c ** 2 or b ** 2 == a ** 2 + c ** 2 or c ** 2 == ... |
def main():
f = [line.rstrip("\n") for line in open("Data.txt")]
coordinates = []
for line in f:
coordinate = [int(i) for i in line.split(", ")]
coordinates.append(coordinate)
count = 0
for i in range(400):
for j in range(400):
sum_ = 0
for coordinat... | def main():
f = [line.rstrip('\n') for line in open('Data.txt')]
coordinates = []
for line in f:
coordinate = [int(i) for i in line.split(', ')]
coordinates.append(coordinate)
count = 0
for i in range(400):
for j in range(400):
sum_ = 0
for coordinate ... |
class Solution:
def mostCommonWord(self, paragraph: str, banned) -> str:
helper = {}
tmp_word = ""
for i in paragraph:
if (ord('a') <= ord(i) <= ord('z') or ord('A') <= ord(i) <= ord('Z')) is False:
if len(tmp_word) > 0:
if helper.__contains__(... | class Solution:
def most_common_word(self, paragraph: str, banned) -> str:
helper = {}
tmp_word = ''
for i in paragraph:
if (ord('a') <= ord(i) <= ord('z') or ord('A') <= ord(i) <= ord('Z')) is False:
if len(tmp_word) > 0:
if helper.__contains... |
#!python
# -*- coding: utf-8 -*-
# @author: Kun
'''
Author: Kun
Date: 2021-09-30 00:48:14
LastEditTime: 2021-09-30 00:48:14
LastEditors: Kun
Description:
FilePath: /HomoglyphAttacksDetector/utils/__init__.py
'''
| """
Author: Kun
Date: 2021-09-30 00:48:14
LastEditTime: 2021-09-30 00:48:14
LastEditors: Kun
Description:
FilePath: /HomoglyphAttacksDetector/utils/__init__.py
""" |
{
'includes':[
'../common/common.gypi',
],
'targets': [
{
'target_name': 'tizen_network_bearer_selection',
'type': 'loadable_module',
'sources': [
'network_bearer_selection_api.js',
'network_bearer_selection_connection_mobile.cc',
'network_bearer_selection_connect... | {'includes': ['../common/common.gypi'], 'targets': [{'target_name': 'tizen_network_bearer_selection', 'type': 'loadable_module', 'sources': ['network_bearer_selection_api.js', 'network_bearer_selection_connection_mobile.cc', 'network_bearer_selection_connection_mobile.h', 'network_bearer_selection_context.cc', 'network... |
# Resolve the problem!!
PALINDROMES = [
'Acaso hubo buhos aca',
'A la catalana banal atacala',
'Amar da drama',
]
NOT_PALINDROMES = [
'Hola como estas',
'Platzi'
'Oscar',
]
def is_palindrome(palindrome):
"""
validates that the string palindrome is a
palindrome (it is a word or p... | palindromes = ['Acaso hubo buhos aca', 'A la catalana banal atacala', 'Amar da drama']
not_palindromes = ['Hola como estas', 'PlatziOscar']
def is_palindrome(palindrome):
"""
validates that the string palindrome is a
palindrome (it is a word or phrase that
read equal to right and back
param str ... |
def DEBUG(s):
#pass
print(s)
| def debug(s):
print(s) |
def print_n(s, n):
"""write a function that prints a string n times"""
while n > 0:
print(s)
n = n - 1
print_n('string', 3)
| def print_n(s, n):
"""write a function that prints a string n times"""
while n > 0:
print(s)
n = n - 1
print_n('string', 3) |
def add_to(subparsers):
parser = subparsers.add_parser(
"wifi",
help="Get and set WiFi configuration",
)
parser.add_children(__name__, __path__)
| def add_to(subparsers):
parser = subparsers.add_parser('wifi', help='Get and set WiFi configuration')
parser.add_children(__name__, __path__) |
'''
1. Write a Python program to print the following string in a specific format (see the output). Go to the editor
Sample String : "Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high,
Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are"
... | """
1. Write a Python program to print the following string in a specific format (see the output). Go to the editor
Sample String : "Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high,
Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are"
... |
'''
Fill in your credentials from Twitter
'''
consumer_key = ''
consumer_secret = ''
access_token_key = ''
access_token_secret = ''
account_name = "@"
kytten_name = "" #Screen Name without the "@"
| """
Fill in your credentials from Twitter
"""
consumer_key = ''
consumer_secret = ''
access_token_key = ''
access_token_secret = ''
account_name = '@'
kytten_name = '' |
"""Contain constants Ids and labels."""
# pylint: disable=R0903
class DataSourceType:
"""Data source type Ids."""
CLOUDERA_HIVE_ID = 1
CLOUDERA_IMPALA_ID = 2
MARIADB_ID = 3
MSSQL_ID = 4
MYSQL_ID = 5
ORACLE_ID = 6
POSTGRESQL_ID = 7
SQLITE_ID = 8
TERADATA_ID = 9
SNOWFLAKE_ID... | """Contain constants Ids and labels."""
class Datasourcetype:
"""Data source type Ids."""
cloudera_hive_id = 1
cloudera_impala_id = 2
mariadb_id = 3
mssql_id = 4
mysql_id = 5
oracle_id = 6
postgresql_id = 7
sqlite_id = 8
teradata_id = 9
snowflake_id = 10
hortonworks_hive... |
class Solution:
def longestRepeatingSubstring(self, S: str) -> int:
# dp[i][j] means the longest repeating string ends at i and j.
# (aka the target ends at i and the repeating one ends at j)
n = len(S) + 1
dp = [[0] * n for _ in range(n)]
result = 0
for i in range(1... | class Solution:
def longest_repeating_substring(self, S: str) -> int:
n = len(S) + 1
dp = [[0] * n for _ in range(n)]
result = 0
for i in range(1, n):
for j in range(i + 1, n):
if S[i - 1] == S[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
... |
emojis = \
{
29000000: "<:Unranked:601618883853680653>",
29000001: "<:BronzeLeagueIII:601611929311510528>",
29000002: "<:BronzeLeagueII:601611942850986014>",
29000003: "<:BronzeLeagueI:601611950228635648>",
29000004: "<:SilverLeagueIII:601611958067920906>",
29000005: ... | emojis = {29000000: '<:Unranked:601618883853680653>', 29000001: '<:BronzeLeagueIII:601611929311510528>', 29000002: '<:BronzeLeagueII:601611942850986014>', 29000003: '<:BronzeLeagueI:601611950228635648>', 29000004: '<:SilverLeagueIII:601611958067920906>', 29000005: '<:SilverLeagueII:601611965550428160>', 29000006: '<:Si... |
course = 'Python for Beginners'
#print the length of the string
print(len(course))
#print all in upper
print(course.upper())
#print all in lower
print(course.lower())
#Find index of the first instance of 'P'
print(course.find('P'))
#Find index of the first instance of 'o'
print(course.find('o'))
#Find index of th... | course = 'Python for Beginners'
print(len(course))
print(course.upper())
print(course.lower())
print(course.find('P'))
print(course.find('o'))
print(course.find('0'))
print(course.find('Beginners'))
print(course.replace('Beginners', 'Absolute Beginners'))
print('Python' in course)
print('python' in course) |
#4.2
list_with_integers = [26, 3, 22, 5.9, 1337, 988, 69.544]
for i in list_with_integers:
print(float(i)) | list_with_integers = [26, 3, 22, 5.9, 1337, 988, 69.544]
for i in list_with_integers:
print(float(i)) |
projectTwitterDataFile = open("project_twitter_data.csv","r")
resultingDataFile = open("resulting_data.csv","w")
punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@']
# lists of words to use
positive_words = []
with open("positive_words.txt") as pos_f:
for lin in pos_f:
if lin[0] != ';' and lin... | project_twitter_data_file = open('project_twitter_data.csv', 'r')
resulting_data_file = open('resulting_data.csv', 'w')
punctuation_chars = ["'", '"', ',', '.', '!', ':', ';', '#', '@']
positive_words = []
with open('positive_words.txt') as pos_f:
for lin in pos_f:
if lin[0] != ';' and lin[0] != '\n':
... |
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
if n == 0:
return 0
elif n == 1:
return nums[0]
elif n == 2:
return max(nums)
else:
a, b = nums... | class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
if n == 0:
return 0
elif n == 1:
return nums[0]
elif n == 2:
return max(nums)
else:
(a, b) = (... |
def sum_repeat_digits(offset):
l = []
for i, c in enumerate(digits):
index_to_check = int((i + offset) % len(digits))
if c == digits[index_to_check]:
l.append(int(c))
return sum(l)
def main():
with open('inputs/solution1.txt') as f:
digits = f.read().strip()
pri... | def sum_repeat_digits(offset):
l = []
for (i, c) in enumerate(digits):
index_to_check = int((i + offset) % len(digits))
if c == digits[index_to_check]:
l.append(int(c))
return sum(l)
def main():
with open('inputs/solution1.txt') as f:
digits = f.read().strip()
pr... |
employees = {
'Alice': 100000,
'Bob': 98000,
'Cena': 127000,
'Dwayne': 158000,
'Frank': 88000
}
# find the top earner (every one with salary greater than or equal to 1 lakh)
top_earners = []
for name,salary in employees.items():
if salary >= 100000:
top_earners.append((name,salary))
p... | employees = {'Alice': 100000, 'Bob': 98000, 'Cena': 127000, 'Dwayne': 158000, 'Frank': 88000}
top_earners = []
for (name, salary) in employees.items():
if salary >= 100000:
top_earners.append((name, salary))
print(top_earners)
top_earners = [(n, s) for (n, s) in employees.items() if s >= 100000]
print(top_e... |
VALID_AZURE_ENVIRONMENTS = [
'AzurePublicCloud',
'AzureUSGovernmentCloud',
'AzureChinaCloud',
'AzureGermanCloud',
]
| valid_azure_environments = ['AzurePublicCloud', 'AzureUSGovernmentCloud', 'AzureChinaCloud', 'AzureGermanCloud'] |
class Lane:
def __init__(self, position, objectType, player_id):
self.position = position
self.object = objectType
self.occupied_by_player_id = player_id
| class Lane:
def __init__(self, position, objectType, player_id):
self.position = position
self.object = objectType
self.occupied_by_player_id = player_id |
coordinates_E0E1E1 = ((123, 110),
(123, 112), (123, 113), (123, 114), (123, 115), (123, 116), (123, 117), (123, 118), (123, 119), (123, 120), (123, 122), (124, 110), (124, 122), (125, 110), (125, 112), (125, 113), (125, 114), (125, 115), (125, 116), (125, 117), (125, 118), (125, 119), (125, 120), (125, 122), (126, 10... | coordinates_e0_e1_e1 = ((123, 110), (123, 112), (123, 113), (123, 114), (123, 115), (123, 116), (123, 117), (123, 118), (123, 119), (123, 120), (123, 122), (124, 110), (124, 122), (125, 110), (125, 112), (125, 113), (125, 114), (125, 115), (125, 116), (125, 117), (125, 118), (125, 119), (125, 120), (125, 122), (126, 10... |
class Adam:
def __init__(self, lr=0.001, beta1=0.9, beta2=0.999):
self.lr = lr
self.beta1 = beta1
self.beta2 = beta2
self.iter = 0
self.m = None
self.v = None
def update(self, params, grads):
if self.m is None:
self.m, self.v = {}, {}... | class Adam:
def __init__(self, lr=0.001, beta1=0.9, beta2=0.999):
self.lr = lr
self.beta1 = beta1
self.beta2 = beta2
self.iter = 0
self.m = None
self.v = None
def update(self, params, grads):
if self.m is None:
(self.m, self.v) = ({}, {})
... |
#
# PySNMP MIB module HH3C-RCP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-RCP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:29:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, single_value_constraint, value_range_constraint, constraints_union) ... |
#Two words are blanagrams if they are anagrams but exactly one letter has been substituted for another.
#Given two words, check if they are blanagrams of each other.
def checkBlanagrams(word1, word2):
difference = 0
sortedWord1 = sorted(word1)
sortedWord2 = sorted(word2)
for a, b in zip(sortedWor... | def check_blanagrams(word1, word2):
difference = 0
sorted_word1 = sorted(word1)
sorted_word2 = sorted(word2)
for (a, b) in zip(sortedWord1, sortedWord2):
if sortedWord1 == sortedWord2:
return False
if a != b:
difference += 1
if difference > 1:
... |
arr = [1, 2]
brr = [3, 4]
print(arr + brr)
print([1] * 3)
| arr = [1, 2]
brr = [3, 4]
print(arr + brr)
print([1] * 3) |
def check_is_prime(n):
if n == 2 or n == 3:
return True
if n % 2 == 0 or n < 2:
return False
for i in range(3, int(n**0.5)+1, 2):
if n % i == 0:
return False
return True
| def check_is_prime(n):
if n == 2 or n == 3:
return True
if n % 2 == 0 or n < 2:
return False
for i in range(3, int(n ** 0.5) + 1, 2):
if n % i == 0:
return False
return True |
if __name__ == '__main__':
input = [x.strip().split('-') for x in open('input', 'r').readlines()]
map = {}
for path in input:
if path[0] not in map: map[path[0]] = list()
map[path[0]].append(path[1])
if path[1] not in map: map[path[1]] = list()
map[path[1]].append(path[0])
... | if __name__ == '__main__':
input = [x.strip().split('-') for x in open('input', 'r').readlines()]
map = {}
for path in input:
if path[0] not in map:
map[path[0]] = list()
map[path[0]].append(path[1])
if path[1] not in map:
map[path[1]] = list()
map[pat... |
class DH_Endpoint(object):
def __init__(self, public_key1, public_key2, private_key):
self.public_key1 = public_key1
self.public_key2 = public_key2
self.private_key = private_key
self.full_key = None
def generate_partial_key(self):
partial_key = self.public_key1**self.pri... | class Dh_Endpoint(object):
def __init__(self, public_key1, public_key2, private_key):
self.public_key1 = public_key1
self.public_key2 = public_key2
self.private_key = private_key
self.full_key = None
def generate_partial_key(self):
partial_key = self.public_key1 ** self... |
"""
bitToRealHelper.py is a helper class to convert a binary representation to a real numbered representation for the purpose of the assignment. In reality, it would be much simpler to program a GA that uses real values and an interpolation method during crossover.
@author Michael Allport 2021
"""
class BitToReal():
... | """
bitToRealHelper.py is a helper class to convert a binary representation to a real numbered representation for the purpose of the assignment. In reality, it would be much simpler to program a GA that uses real values and an interpolation method during crossover.
@author Michael Allport 2021
"""
class Bittoreal:
... |
def make_sectional_content(data : list) -> list:
sections = []
section = []
for item in data:
if item == "~~~":
sections.append(section)
section = []
continue
section.append(item)
return sections
def print_sectional_content(sect... | def make_sectional_content(data: list) -> list:
sections = []
section = []
for item in data:
if item == '~~~':
sections.append(section)
section = []
continue
section.append(item)
return sections
def print_sectional_content(sections: list) -> None:
... |
def test_find_or_create_invite(logged_rocket):
rid = 'GENERAL'
find_or_create_invite = logged_rocket.find_or_create_invite(rid=rid, days=7, max_uses=5).json()
assert find_or_create_invite.get('success')
assert find_or_create_invite.get('days') == 7
assert find_or_create_invite.get('maxUses') == 5
... | def test_find_or_create_invite(logged_rocket):
rid = 'GENERAL'
find_or_create_invite = logged_rocket.find_or_create_invite(rid=rid, days=7, max_uses=5).json()
assert find_or_create_invite.get('success')
assert find_or_create_invite.get('days') == 7
assert find_or_create_invite.get('maxUses') == 5
d... |
def check_best_ways(matrix: list, row: int, col: int):
direction_up = float('-inf')
position_direction_up = []
up_sum = 0
for r in range(row - 1, -1, -1):
if matrix[r][col] == "X":
break
up_sum += matrix[r][col]
direction_up = up_sum
position_direction_up.appe... | def check_best_ways(matrix: list, row: int, col: int):
direction_up = float('-inf')
position_direction_up = []
up_sum = 0
for r in range(row - 1, -1, -1):
if matrix[r][col] == 'X':
break
up_sum += matrix[r][col]
direction_up = up_sum
position_direction_up.appe... |
class Asset:
def __init__(self, type, nameplate, project):
self.type = type
self.nameplate = nameplate
self.project = project
B02 = Asset("Tracker","none", "Saltwood Solar")
print(B02.project)
| class Asset:
def __init__(self, type, nameplate, project):
self.type = type
self.nameplate = nameplate
self.project = project
b02 = asset('Tracker', 'none', 'Saltwood Solar')
print(B02.project) |
pokerNames = ('3','4','5','6','7','8','9','10','J','Q','K','A','2','B','R')
pokerValues = ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 100,200,300)
pokerDict = dict(zip(pokerNames, pokerValues))
def getCardValue(name):
return pokerDict[name]
if __name__ == '__main__':
print(getCardValue('3'))
... | poker_names = ('3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A', '2', 'B', 'R')
poker_values = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 100, 200, 300)
poker_dict = dict(zip(pokerNames, pokerValues))
def get_card_value(name):
return pokerDict[name]
if __name__ == '__main__':
print(get_card_value('3'))
... |
# Program to find if the numbers given can add
# up to a given target or not
"""
m = target, determines the height of the tree
n = array length, determines complexity
This has a O(n^m) time complexity and O(m)
space complexity when solving without memoization.
Memoized Solution:
Time = O(m*n)
Space = O(m)
"""
cache =... | """
m = target, determines the height of the tree
n = array length, determines complexity
This has a O(n^m) time complexity and O(m)
space complexity when solving without memoization.
Memoized Solution:
Time = O(m*n)
Space = O(m)
"""
cache = {}
def can_sum(target, numbers):
global cache
if target in cache:
... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without ... | """ To Use:
- subclass Observable for a thing that chagnes
- subclass Observer for the things that will use those changes
- Observers call Observable's #addObserver to register and #removeObserver to stop
- When the thing (the Observable) changes, #notifyObservers calls all the Observers
"""
class Observer:
def... |
""" Asked by: LinkedIn [Hard].
Given a string, return whether it represents a number. Here are the different kinds of numbers:
"10", a positive integer
"-10", a negative integer
"10.1", a positive real number
"-10.1", a negative real number
"1e5", a number in scientific notation
And here are examples of non-numbers:
... | """ Asked by: LinkedIn [Hard].
Given a string, return whether it represents a number. Here are the different kinds of numbers:
"10", a positive integer
"-10", a negative integer
"10.1", a positive real number
"-10.1", a negative real number
"1e5", a number in scientific notation
And here are examples of non-numbers:
... |
"""
Query PyPI from the command line
``qypi`` is a command-line client for querying & searching `PyPI
<https://pypi.org>`_ for Python package information and outputting JSON (with
some minor opinionated changes to the output data structures).
Run ``qypi --help`` or visit <https://github.com/jwodder/qypi> for more
inf... | """
Query PyPI from the command line
``qypi`` is a command-line client for querying & searching `PyPI
<https://pypi.org>`_ for Python package information and outputting JSON (with
some minor opinionated changes to the output data structures).
Run ``qypi --help`` or visit <https://github.com/jwodder/qypi> for more
inf... |
def parse_ner_dataset_file(f):
tokens = []
for i, l in enumerate(f):
l_split = l.split()
if len(l_split) == 0:
yield tokens
tokens.clear()
continue
if len(l_split) < 2:
continue # todo: fix this
else:
tokens.append({'te... | def parse_ner_dataset_file(f):
tokens = []
for (i, l) in enumerate(f):
l_split = l.split()
if len(l_split) == 0:
yield tokens
tokens.clear()
continue
if len(l_split) < 2:
continue
else:
tokens.append({'text': l_split[0],... |
config = {
"-varprune":[0,int],
"-recompute":[False,bool],
"-sort":[False,bool],
"-no-sos":[False,bool],
"-no-eos":[False,bool],
"-write":["./counts",str],
"-gtmin":[1,int],
"-gtmax":[5,int],
"-ndiscount":[Fals... | config = {'-varprune': [0, int], '-recompute': [False, bool], '-sort': [False, bool], '-no-sos': [False, bool], '-no-eos': [False, bool], '-write': ['./counts', str], '-gtmin': [1, int], '-gtmax': [5, int], '-ndiscount': [False, bool], '-wbdiscount': [False, bool], '-kndiscount': [True, bool], '-ukndiscount': [False, b... |
class Config:
# region bug configurations
PROJECT_ROOT_PATH = r"/Users/ori/pergit/defects/math_1_buggy"
BUG_PROJECT = 'math'
BUG_ID = 1
IGNORED_CLASS_LIST = ['FastCosineTransformerTest', 'FastSineTransformerTest', 'FastMathStrictComparisonTest',
'CorrelatedRandomVectorGener... | class Config:
project_root_path = '/Users/ori/pergit/defects/math_1_buggy'
bug_project = 'math'
bug_id = 1
ignored_class_list = ['FastCosineTransformerTest', 'FastSineTransformerTest', 'FastMathStrictComparisonTest', 'CorrelatedRandomVectorGeneratorTest', 'FastMathTestPerformance']
actual_faults_met... |
# hint: see np.diff()
inter_switch_intervals = np.diff(switch_times)
# plot inter-switch intervals
with plt.xkcd():
plot_interswitch_interval_histogram(inter_switch_intervals) | inter_switch_intervals = np.diff(switch_times)
with plt.xkcd():
plot_interswitch_interval_histogram(inter_switch_intervals) |
class Solution:
def minEatingSpeed(self, piles: List[int], H: int) -> int:
if len(piles)==0:
return 0
l,r = 1,pow(10,9)
while l<=r:
m = (l+r)>>1
sum = 0
for i in piles:
sum+=(... | class Solution:
def min_eating_speed(self, piles: List[int], H: int) -> int:
if len(piles) == 0:
return 0
(l, r) = (1, pow(10, 9))
while l <= r:
m = l + r >> 1
sum = 0
for i in piles:
sum += (i + m - 1) // m
if sum ... |
digits = [0,1,2,3,4,5,6,7,8,9]
print(digits[-1])
print(digits[-len(digits)])
print(digits[:3])
#stride mige chanta chanta beri
print((digits[0:9:2]))
#bayad az akhar be aval bzanim
print((digits[9:0:-1]))
goods = 'success,win,best_coder,elham'
print(goods)
l = goods.split(",")
#ye string ro migire o split mikone be li... | digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(digits[-1])
print(digits[-len(digits)])
print(digits[:3])
print(digits[0:9:2])
print(digits[9:0:-1])
goods = 'success,win,best_coder,elham'
print(goods)
l = goods.split(',')
print(l)
l = goods.split('win')
print(l)
goods = 'success,win,best_coder,elham'
l = goods.split(',')... |
class Holding(object):
def __init__(self, name, ticker, weight=100, sector=None, news=None, link=None):
self.name = name
self.ticker = ticker
self.weight = weight
self.sector = sector
self.news = news
self.link = link
def set_name(self, name):
self.name ... | class Holding(object):
def __init__(self, name, ticker, weight=100, sector=None, news=None, link=None):
self.name = name
self.ticker = ticker
self.weight = weight
self.sector = sector
self.news = news
self.link = link
def set_name(self, name):
self.name ... |
"""Top-level package for Nginx Log Analytics."""
__author__ = """Surya Sankar"""
__email__ = 'suryashankar.m@gmail.com'
__version__ = '0.1.0'
| """Top-level package for Nginx Log Analytics."""
__author__ = 'Surya Sankar'
__email__ = 'suryashankar.m@gmail.com'
__version__ = '0.1.0' |
class BulkOperationProgressInfo(object):
""" Contains percent complete progress information for the bulk operation."""
def __init__(self, percent_complete=0):
""" Initialize a new instance of this class.
:param percent_complete: (optional) Percent complete progress information for the bulk ope... | class Bulkoperationprogressinfo(object):
""" Contains percent complete progress information for the bulk operation."""
def __init__(self, percent_complete=0):
""" Initialize a new instance of this class.
:param percent_complete: (optional) Percent complete progress information for the bulk ope... |
# Question : https://www.careercup.com/question?id=5754648968298496
dishes = {"Pasta":["Tomato Sauce", "Onions", "Garlic"],
"Chicken Curry":["Chicken", "Curry Sauce"],
"Fried Rice":["Rice", "Onions", "Nuts"],
"Salad":["Spinach", "Nuts"],
"Sandwich":["Cheese", "Bread"],
... | dishes = {'Pasta': ['Tomato Sauce', 'Onions', 'Garlic'], 'Chicken Curry': ['Chicken', 'Curry Sauce'], 'Fried Rice': ['Rice', 'Onions', 'Nuts'], 'Salad': ['Spinach', 'Nuts'], 'Sandwich': ['Cheese', 'Bread'], 'Quesadilla': ['Chicken', 'Cheese']}
def group_by_ingredients(dishes):
ingredients = {}
for dish in dish... |
class Funcionario:
def __init__(self, nome, idade, salario):
self.nome = nome
self.idade = idade
self.__salario = salario # atributo privado
def set_salario(self, salario):
if salario > 0:
self.__salario = salario
else:
print("Valor invalido")
... | class Funcionario:
def __init__(self, nome, idade, salario):
self.nome = nome
self.idade = idade
self.__salario = salario
def set_salario(self, salario):
if salario > 0:
self.__salario = salario
else:
print('Valor invalido')
def get_salario(... |
# phone numbers for countries
phone_codes = {}
phone_codes["DE"] = 49
phone_codes["TR"] = 90
phone_codes["PK"] = 92
phone_codes["IN"] = 91
code = phone_codes["IN"]
print(code)
| phone_codes = {}
phone_codes['DE'] = 49
phone_codes['TR'] = 90
phone_codes['PK'] = 92
phone_codes['IN'] = 91
code = phone_codes['IN']
print(code) |
"""
Speech constants related to determining whether the user is in Boston or not.
"""
GENERIC_GEOLOCATION_PERMISSON_SPEECH = """
Boston Info would like to use your location.
To turn on location sharing, please go to your Alexa app and
follow the instructions. Alternatively, you can provide an address whe... | """
Speech constants related to determining whether the user is in Boston or not.
"""
generic_geolocation_permisson_speech = '\n Boston Info would like to use your location. \n To turn on location sharing, please go to your Alexa app and \n follow the instructions. Alternatively, you can provide an address whe... |
def hello():
return hw()
def hw():
cadena = "<h1>Prueba</h1>"
cadena += "<h2>Probando</h2>"
cadena += "<div>Hello World.</div>"
return cadena
| def hello():
return hw()
def hw():
cadena = '<h1>Prueba</h1>'
cadena += '<h2>Probando</h2>'
cadena += '<div>Hello World.</div>'
return cadena |
def test_object(store):
test_store_object(store)
test_events_object(store.events)
test_attendees_object(store.attendees)
test_attendees_object(store.waitings)
test_users_object(store.users)
def test_store_object(store):
assert store
assert store.events
assert store.attendees... | def test_object(store):
test_store_object(store)
test_events_object(store.events)
test_attendees_object(store.attendees)
test_attendees_object(store.waitings)
test_users_object(store.users)
def test_store_object(store):
assert store
assert store.events
assert store.attendees
assert ... |
#
# PySNMP MIB module BAS-PBRF-OSPF-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BAS-PBRF-OSPF-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:34:08 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_union, single_value_constraint, constraints_intersection, value_range_constraint) ... |
# Synthetic fault scarp parameters
fault_dip = 60
fault_slip = 10
fault_slip_rate = 2
fault_scarp_profile_length = 30
fault_scarp_exponential = True # True for simple
fault_scarp_steps = 1
fault_scarp_step_width = 5
final_time = fault_slip / fault_slip_rate
# Parameters for synthetic fault scarps and for calculating d... | fault_dip = 60
fault_slip = 10
fault_slip_rate = 2
fault_scarp_profile_length = 30
fault_scarp_exponential = True
fault_scarp_steps = 1
fault_scarp_step_width = 5
final_time = fault_slip / fault_slip_rate
diffusion_coefficient = 10
time_steps_between_plots = 20
change_in_distance = 1
calculation_final_time = 25 |
class Lit_detail:
def __init__(self, lit_name, lit_author):
self.title = lit_name
self.author = lit_author
def display(self):
return "Title:" + str(self.title) + " Author:" + str(self.author)
class Book(Lit_detail):
unique_count = 0
total_count = 0
... | class Lit_Detail:
def __init__(self, lit_name, lit_author):
self.title = lit_name
self.author = lit_author
def display(self):
return 'Title:' + str(self.title) + ' Author:' + str(self.author)
class Book(Lit_detail):
unique_count = 0
total_count = 0
def __init__(self, b... |
# my_string = input("Input as many values as you want separated by whitespace: ")
# my_list = my_string.split(" ")
# my_numbers = [int(element) for element in my_list]
# print(my_numbers, sum(my_numbers), min(my_numbers), max(my_numbers))
# one liner as above but maybe a bit too dense
my_nums = [int(t) for t in input(... | my_nums = [int(t) for t in input('Enter values separated by whitespace').split(' ')]
print(my_nums) |
with open('input18.txt') as f:
maths = f.read().split('\n')
ops = {
'*':[2, 'l', 2, lambda x, y : y * x],
'+':[3, 'l', 2, lambda x, y : y + x]
}
def solve(read):
stack = []
out = []
numstack = []
funcstack = []
last = ''
for t in read:
if t.isspace():
contin... | with open('input18.txt') as f:
maths = f.read().split('\n')
ops = {'*': [2, 'l', 2, lambda x, y: y * x], '+': [3, 'l', 2, lambda x, y: y + x]}
def solve(read):
stack = []
out = []
numstack = []
funcstack = []
last = ''
for t in read:
if t.isspace():
continue
if l... |
def check_prime(integer):
if integer == 1: return False
if integer == 2: return True
if integer % 2 == 0: return False
for i in range(3, int(integer**(1/2))+1, 2):
if integer % i == 0:
return False
else:
return True
num_primes = 0
n = 0
while num_... | def check_prime(integer):
if integer == 1:
return False
if integer == 2:
return True
if integer % 2 == 0:
return False
for i in range(3, int(integer ** (1 / 2)) + 1, 2):
if integer % i == 0:
return False
else:
return True
num_primes = 0
n = 0
while... |
n = int(input())
upper_sum , lower_sum = 0, 0
arr = []
for _ in range(n):
upper, lower = [int(x) for x in input().split()]
upper_sum += upper
lower_sum += lower
arr.append((upper, lower))
if (upper_sum % 2) == 0 and (lower_sum % 2) == 0:
print("0")
else:
msg = "-1"
for upper, lower in arr:
... | n = int(input())
(upper_sum, lower_sum) = (0, 0)
arr = []
for _ in range(n):
(upper, lower) = [int(x) for x in input().split()]
upper_sum += upper
lower_sum += lower
arr.append((upper, lower))
if upper_sum % 2 == 0 and lower_sum % 2 == 0:
print('0')
else:
msg = '-1'
for (upper, lower) in arr... |
class RaisesClass():
def func_with_raise(self) -> None:
"""
Raises:
RuntimeError: [description]
ValueError: [description]
IndexError: [description]
"""
if 2 == 3:
raise RuntimeError()
if 2 == 4:
raise ValueError()
... | class Raisesclass:
def func_with_raise(self) -> None:
"""
Raises:
RuntimeError: [description]
ValueError: [description]
IndexError: [description]
"""
if 2 == 3:
raise runtime_error()
if 2 == 4:
raise value_error()
... |
class Node:
"""
Basic node implementation with a single link.
"""
def __init__(self, val=None):
self.val = val
self.next = None
def __str__(self):
return str(self.val)
class Queue:
"""
Queue implementation using Linked List.
"""
def __init__(self):
... | class Node:
"""
Basic node implementation with a single link.
"""
def __init__(self, val=None):
self.val = val
self.next = None
def __str__(self):
return str(self.val)
class Queue:
"""
Queue implementation using Linked List.
"""
def __init__(self):
... |
#!/usr/bin/env python3
# encoding: utf-8
"""
@author: Medivh Xu
@file: __init__.py.py
@time: 2020-03-04 21:27
""" | """
@author: Medivh Xu
@file: __init__.py.py
@time: 2020-03-04 21:27
""" |
l_rate = 0.3
n_epoch = 100
loss = np.zeros(n_epoch)
beta = [0.0,0.0,0.0]
for epoch in range(n_epoch):
sum_error = 0
for row in train:
x = row[0:-1] # input features
y = row[-1] # output label
yhat = predict(row, beta)
error = y - yhat
sum_error += error**2
beta... | l_rate = 0.3
n_epoch = 100
loss = np.zeros(n_epoch)
beta = [0.0, 0.0, 0.0]
for epoch in range(n_epoch):
sum_error = 0
for row in train:
x = row[0:-1]
y = row[-1]
yhat = predict(row, beta)
error = y - yhat
sum_error += error ** 2
beta[0] += l_rate * error * yhat * ... |
def fetch_data1():
return "data1"
def fetch_data2():
return "data2"
def process_data1():
return fetch_data1().upper()
def process_data2():
return fetch_data2().upper()
def process_data3():
return process_data1() + "-" + process_data2()
def show_report1():
print(process_data3())
def show_re... | def fetch_data1():
return 'data1'
def fetch_data2():
return 'data2'
def process_data1():
return fetch_data1().upper()
def process_data2():
return fetch_data2().upper()
def process_data3():
return process_data1() + '-' + process_data2()
def show_report1():
print(process_data3())
def show_re... |
'''
@author: Kittl
'''
def exportStorageTypes(dpf, exportProfile, tables, colHeads):
# Get the index in the list of worksheets
if exportProfile is 2:
cmpStr = "StorageType"
elif exportProfile is 3:
cmpStr = ""
idxWs = [idx for idx,val in enumerate(tables[exportProfile-1]) if val == ... | """
@author: Kittl
"""
def export_storage_types(dpf, exportProfile, tables, colHeads):
if exportProfile is 2:
cmp_str = 'StorageType'
elif exportProfile is 3:
cmp_str = ''
idx_ws = [idx for (idx, val) in enumerate(tables[exportProfile - 1]) if val == cmpStr]
if not idxWs:
dpf.Pr... |
class MongoUsersUtils:
def __init__(self, mongo):
self.mongo = mongo
self.collection_name = "users"
def save(self, user):
return self.mongo.db[self.collection_name].insert(user)
| class Mongousersutils:
def __init__(self, mongo):
self.mongo = mongo
self.collection_name = 'users'
def save(self, user):
return self.mongo.db[self.collection_name].insert(user) |
# -*- coding: utf-8 -*-
"""This module contains settings for Animerger"""
archive_extensions = [".7z", ".zip", ".rar", ".tar"]
video_extensions = [".mkv", ".mp4", ".avi"]
audio_extensions = [".mka", ".aac", ".mp3", ".ac3"]
subtitles_extensions = [".srt", ".ass", ".ssa"]
fonts_extensions = [".ttf", ".otf"]
| """This module contains settings for Animerger"""
archive_extensions = ['.7z', '.zip', '.rar', '.tar']
video_extensions = ['.mkv', '.mp4', '.avi']
audio_extensions = ['.mka', '.aac', '.mp3', '.ac3']
subtitles_extensions = ['.srt', '.ass', '.ssa']
fonts_extensions = ['.ttf', '.otf'] |
def reverseBits(n: int) -> int:
bin_n = list(bin(n)[2:])
bin_n.reverse()
bin_n.extend(['0'] * (32 - len(bin_n)))
return int(''.join(bin_n), 2)
def reverseBits(n: int) -> int:
rtn = 0
for i in range(32):
rtn = (rtn << 1) | (n & 1)
n >>= 1
return rtn
def reverseBits(n: int)... | def reverse_bits(n: int) -> int:
bin_n = list(bin(n)[2:])
bin_n.reverse()
bin_n.extend(['0'] * (32 - len(bin_n)))
return int(''.join(bin_n), 2)
def reverse_bits(n: int) -> int:
rtn = 0
for i in range(32):
rtn = rtn << 1 | n & 1
n >>= 1
return rtn
def reverse_bits(n: int) ->... |
def unique_string_list(element_list, only_string=True):
"""
Parameters
----------
element_list :
only_string :
(Default value = True)
Returns
-------
"""
if element_list:
if isinstance(element_list, list):
element_list = set(element_list)
elif... | def unique_string_list(element_list, only_string=True):
"""
Parameters
----------
element_list :
only_string :
(Default value = True)
Returns
-------
"""
if element_list:
if isinstance(element_list, list):
element_list = set(element_list)
elif... |
input = """
% true negation of terms does not make sense.
%g(-a).
okay(a).
%f(1,-"zwei").
%:- not g(-a).
:- not okay(a).
%:- not f(1,-"zwei").
"""
output = """
% true negation of terms does not make sense.
%g(-a).
okay(a).
%f(1,-"zwei").
%:- not g(-a).
:- not okay(a).
%:- not f(1,-"zwei").
"""
| input = '\n% true negation of terms does not make sense.\n\n%g(-a).\nokay(a).\n%f(1,-"zwei").\n%:- not g(-a).\n:- not okay(a).\n%:- not f(1,-"zwei").\n'
output = '\n% true negation of terms does not make sense.\n\n%g(-a).\nokay(a).\n%f(1,-"zwei").\n%:- not g(-a).\n:- not okay(a).\n%:- not f(1,-"zwei").\n' |
# copy-pasted from https://github.com/toastdriven/pylev/blob/master/pylev.py
def recursive_levenshtein(string_1, string_2, len_1=None, len_2=None, offset_1=0, offset_2=0, memo=None) -> float:
"""
Calculates the Levenshtein distance between two strings.
Usage::
>>> recursive_levenshtein('kitten', 'si... | def recursive_levenshtein(string_1, string_2, len_1=None, len_2=None, offset_1=0, offset_2=0, memo=None) -> float:
"""
Calculates the Levenshtein distance between two strings.
Usage::
>>> recursive_levenshtein('kitten', 'sitting')
3
>>> recursive_levenshtein('kitten', 'kitten')
... |
class NoSolutionException(Exception):
"""
DESCRIPTION:
An exception to handle where there are no terms to choose when
performing inference. This exception is launched when there is
no solution.
"""
# Methods
def __init__(self):
"""
DESCRIPTION:
Constructor of th... | class Nosolutionexception(Exception):
"""
DESCRIPTION:
An exception to handle where there are no terms to choose when
performing inference. This exception is launched when there is
no solution.
"""
def __init__(self):
"""
DESCRIPTION:
Constructor of the class
... |
def get_upstream_conduits(node_id, con_df, in_col_name="InletNode", out_col_name="OutletNode"):
us_nodes = get_upstream_nodes(node_id, con_df, in_col_name, out_col_name)
us_cons = con_df[(con_df[in_col_name].isin(us_nodes)) | (con_df[out_col_name].isin(us_nodes))]
return us_cons.index
def get_upstream_nod... | def get_upstream_conduits(node_id, con_df, in_col_name='InletNode', out_col_name='OutletNode'):
us_nodes = get_upstream_nodes(node_id, con_df, in_col_name, out_col_name)
us_cons = con_df[con_df[in_col_name].isin(us_nodes) | con_df[out_col_name].isin(us_nodes)]
return us_cons.index
def get_upstream_nodes_on... |
#unlicense.org
#in case importing the numpy/scipy libraries should be avoided:
def zeros(item, quanity):
return [item] * quanity
def simple_matrix(item,quanity):
return [item] * quanity
| def zeros(item, quanity):
return [item] * quanity
def simple_matrix(item, quanity):
return [item] * quanity |
#!/usr/bin/env python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | task_type = 'classification'
column_names = ['age', 'workclass', 'fnlwgt', 'education', 'education_num', 'marital_status', 'occupation', 'relationship', 'race', 'gender', 'capital_gain', 'capital_loss', 'hours_per_week', 'native_country', 'income_bracket']
serving_column_names = ['age', 'workclass', 'education', 'educa... |
set_name(0x801379C4, "PreGameOnlyTestRoutine__Fv", SN_NOWARN)
set_name(0x80139A88, "DRLG_PlaceDoor__Fii", SN_NOWARN)
set_name(0x80139F5C, "DRLG_L1Shadows__Fv", SN_NOWARN)
set_name(0x8013A374, "DRLG_PlaceMiniSet__FPCUciiiiiii", SN_NOWARN)
set_name(0x8013A7E0, "DRLG_L1Floor__Fv", SN_NOWARN)
set_name(0x8013A8CC, "StoreBlo... | set_name(2148760004, 'PreGameOnlyTestRoutine__Fv', SN_NOWARN)
set_name(2148768392, 'DRLG_PlaceDoor__Fii', SN_NOWARN)
set_name(2148769628, 'DRLG_L1Shadows__Fv', SN_NOWARN)
set_name(2148770676, 'DRLG_PlaceMiniSet__FPCUciiiiiii', SN_NOWARN)
set_name(2148771808, 'DRLG_L1Floor__Fv', SN_NOWARN)
set_name(2148772044, 'StoreBlo... |
class ValidationException(Exception):
pass
class RepromptException(Exception):
pass
| class Validationexception(Exception):
pass
class Repromptexception(Exception):
pass |
m,n=map(int,input().split())
mat=[]
for i in range(m):
k=list(map(int,input().split()))
mat.append(k)
mat
count=mat[0][0]
i=0
j=0
while(True):
if (i==m-1 and j==n-1):
break
if (i<m-1 and j<n-1):
if (mat[i+1][j]>mat[i][j+1]):
count+=mat[i+1][j]
i+=1
else:
count+... | (m, n) = map(int, input().split())
mat = []
for i in range(m):
k = list(map(int, input().split()))
mat.append(k)
mat
count = mat[0][0]
i = 0
j = 0
while True:
if i == m - 1 and j == n - 1:
break
if i < m - 1 and j < n - 1:
if mat[i + 1][j] > mat[i][j + 1]:
count += mat[i + 1]... |
def parse_function_path_string(string):
"""
takes in the function string and splits it into the module path and function path.
:param string:
:return:
"""
list_ = string.split('.')
module_path = '.'.join(list_[:-1])
function_path = list_[-1]
return module_path, function_path
| def parse_function_path_string(string):
"""
takes in the function string and splits it into the module path and function path.
:param string:
:return:
"""
list_ = string.split('.')
module_path = '.'.join(list_[:-1])
function_path = list_[-1]
return (module_path, function_path) |
# Solution to part 2 of day 9 of AOC 2021, Smoke Basin
# https://adventofcode.com/2021/day/9
def search(search_x: int, search_y: int) -> int:
"""Starting at x, y... return the size of the basin found."""
if (search_x, search_y) not in floor:
return 0
if floor[search_x, search_y] == 9:
retu... | def search(search_x: int, search_y: int) -> int:
"""Starting at x, y... return the size of the basin found."""
if (search_x, search_y) not in floor:
return 0
if floor[search_x, search_y] == 9:
return 0
floor[search_x, search_y] = 9
size = 0
for (dx, dy) in [(-1, 0), (1, 0), (0, -... |
"""
The original version of the API.
.. deprecated:: 0.7.4
Use ``api.v2`` instead.
"""
| """
The original version of the API.
.. deprecated:: 0.7.4
Use ``api.v2`` instead.
""" |
input = """
f(1).
a(X) :- 1=2+x, f(X). %+(1,2,x), f(X).
"""
output = """
f(1).
a(X) :- 1=2+x, f(X). %+(1,2,x), f(X).
"""
| input = '\nf(1).\na(X) :- 1=2+x, f(X). %+(1,2,x), f(X).\n'
output = '\nf(1).\na(X) :- 1=2+x, f(X). %+(1,2,x), f(X).\n' |
def generate_LAMMPS_potential(data):
#potential_file = '# Potential file generated by aiida plugin (please check citation in the orignal file)\n'
potential_file = ''
for line in data['file_contents']:
potential_file += '{}'.format(line)
return potential_file
def get_input_potential_lines(da... | def generate_lammps_potential(data):
potential_file = ''
for line in data['file_contents']:
potential_file += '{}'.format(line)
return potential_file
def get_input_potential_lines(data, names=None, potential_filename='potential.pot'):
lammps_input_text = 'pair_style eam/{}\n'.format(data['... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"div2k_path": "00_datasets.ipynb",
"div2k_train_lr_path": "00_datasets.ipynb",
"div2k_train_lr_x2": "00_datasets.ipynb",
"div2k_train_lr_x3": "00_datasets.ipynb",
"div2k_tr... | __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'div2k_path': '00_datasets.ipynb', 'div2k_train_lr_path': '00_datasets.ipynb', 'div2k_train_lr_x2': '00_datasets.ipynb', 'div2k_train_lr_x3': '00_datasets.ipynb', 'div2k_train_lr_x4': '00_datasets.ipynb', 'div2k_train_hr': '00_datasets.ipynb', 'div2... |
""" Dummy module that just print out some messages"""
DATE = 12092019
def hello ( name ):
""" Say hello ."""
return " hello " + name
def ciao ( name ):
""" Say ciao ."""
return " Ciao " + name
def bye (nom ):
""" Say bye ."""
return " bye " + nom
| """ Dummy module that just print out some messages"""
date = 12092019
def hello(name):
""" Say hello ."""
return ' hello ' + name
def ciao(name):
""" Say ciao ."""
return ' Ciao ' + name
def bye(nom):
""" Say bye ."""
return ' bye ' + nom |
myStr = input("Enter a String: ")
Str = ""
for ind in range (2, len(myStr)):
if ind%2 == 0:
Str = Str + myStr[ind]
print (myStr[0] + Str)
| my_str = input('Enter a String: ')
str = ''
for ind in range(2, len(myStr)):
if ind % 2 == 0:
str = Str + myStr[ind]
print(myStr[0] + Str) |
# Copyright (c) 2013 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'shared',
'type': 'shared_library',
'sources': [ 'file.c' ],
},
{
'target_name': 's... | {'targets': [{'target_name': 'shared', 'type': 'shared_library', 'sources': ['file.c']}, {'target_name': 'shared_no_so_suffix', 'product_extension': 'so.0.1', 'type': 'shared_library', 'sources': ['file.c']}, {'target_name': 'static', 'type': 'static_library', 'sources': ['file.c']}, {'target_name': 'shared_executable'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.