content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def runModels(sproc,modelList,testPredictionPaths,CVPredictionPaths,trials,RMSEPaths,useRMSE):
subprocesses = []
for trial in range(0,trials):
# Setup utility arrays
testPredictionPaths.append([])
CVPredictionPaths.append([])
for model in modelList:
print("Running Model " + m... | def run_models(sproc, modelList, testPredictionPaths, CVPredictionPaths, trials, RMSEPaths, useRMSE):
subprocesses = []
for trial in range(0, trials):
testPredictionPaths.append([])
CVPredictionPaths.append([])
for model in modelList:
print('Running Model ' + model.tag)
model... |
"""
Manages the game colors
--
Author : DrLarck
Last update : 22/08/19 (DrLarck)
"""
game_color = {
"n" : 0xad5f25,
"r" : 0xdcdede,
"sr" : 0xfe871a,
"ssr" : 0xfcdc09,
"ur" : 0x0b68f3,
"lr" : 0xd90e82
} | """
Manages the game colors
--
Author : DrLarck
Last update : 22/08/19 (DrLarck)
"""
game_color = {'n': 11362085, 'r': 14474974, 'sr': 16680730, 'ssr': 16571401, 'ur': 747763, 'lr': 14225026} |
def faculty_evaluation_result(nev, rar, som, oft, voft, alw):
'''
Write code to calculate faculty evaluation rating according to assignment instructions
:param nev: Never
:param rar: Rarely
:param som: Sometimes
:param oft: Often
:param voft: Very Often
:param alw: Always
... | def faculty_evaluation_result(nev, rar, som, oft, voft, alw):
"""
Write code to calculate faculty evaluation rating according to assignment instructions
:param nev: Never
:param rar: Rarely
:param som: Sometimes
:param oft: Often
:param voft: Very Often
:param alw: Always
:return: r... |
"""
https://leetcode.com/problems/minimum-distance-between-bst-nodes/
Given a Binary Search Tree (BST) with the root node root, return the minimum difference between the values of any two different nodes in the tree.
Example :
Input: root = [4,2,6,1,3,null,null]
Output: 1
Explanation:
Note that root is a TreeNode obj... | """
https://leetcode.com/problems/minimum-distance-between-bst-nodes/
Given a Binary Search Tree (BST) with the root node root, return the minimum difference between the values of any two different nodes in the tree.
Example :
Input: root = [4,2,6,1,3,null,null]
Output: 1
Explanation:
Note that root is a TreeNode obj... |
# Variables which should not be accessed outside a class are called private variables.
# In Python you can easily create private variables by prefixing it with a double underscore ( __ )
# Whenever you create a private variable, python internally changes its name as _ClassName__variableName.
# For example, here __sala... | class Trainer:
def __init__(self):
self.name = None
self.__salary = 1000
def set_salary(self, salary):
self.__salary = salary
def get_salary(self):
return self.__salary
lion_trainer = trainer()
lion_trainer.name = 'Mark'
lion_trainer.set_salary(2000)
print("Lion's trainer ... |
class Solution:
def connect(self, root: 'Node') -> 'Node':
node = root
while node:
next_level = node.left
while node and node.left:
node.left.next = node.right
node.right.next = node.next and node.next.left
node = node.next
... | class Solution:
def connect(self, root: 'Node') -> 'Node':
node = root
while node:
next_level = node.left
while node and node.left:
node.left.next = node.right
node.right.next = node.next and node.next.left
node = node.next
... |
UNUSED_PRETRAINED_LAYERS = ['"fc_1.weight", '
'"fc_1.bias", '
'"fc_2.weight", '
'"fc_2.bias", '
'"fc_3.weight", '
'"fc_3.bias", '
'"fc_4.weight", '
... | unused_pretrained_layers = ['"fc_1.weight", "fc_1.bias", "fc_2.weight", "fc_2.bias", "fc_3.weight", "fc_3.bias", "fc_4.weight", "fc_4.bias", "bn_1.weight", "bn_1.bias", "bn_1.running_mean", "bn_1.running_var", "bn_1.num_batches_tracked", "bn_2.weight", "bn_2.bias", "bn_2.running_mean", "bn_2.running_var", "bn_2.num_bat... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
# def mergeKLists(self, lists):
# # Priority queue
# from Queue import PriorityQueue
# queue = PriorityQueue()
# for ... | class Solution(object):
def merge_k_lists(self, lists):
if lists is None:
return None
elif len(lists) == 0:
return None
return self.mergeK(lists, 0, len(lists) - 1)
def merge_k(self, lists, low, high):
if low == high:
return lists[low]
... |
def sum_two_smallest_numbers(numbers):
"""
Create a function that returns the sum of the two lowest positive
numbers given an array of minimum 4 positive integers.
No floats or non-positive integers will be passed.
"""
sum_numbers = 0
for i in range(2):
sum_numbers += numbers.pop(n... | def sum_two_smallest_numbers(numbers):
"""
Create a function that returns the sum of the two lowest positive
numbers given an array of minimum 4 positive integers.
No floats or non-positive integers will be passed.
"""
sum_numbers = 0
for i in range(2):
sum_numbers += numbers.pop(num... |
class Observer(object):
def __init__(self, **kwargs):
self._listeners = []
def add_listener(self, listener):
self._listeners.append(listener)
def _call_event(self, msg):
for listener in self._listeners:
listener(msg)
| class Observer(object):
def __init__(self, **kwargs):
self._listeners = []
def add_listener(self, listener):
self._listeners.append(listener)
def _call_event(self, msg):
for listener in self._listeners:
listener(msg) |
def mergeSort(arrInput):
if len(arrInput) > 1:
mid = len(arrInput) // 2 # midpoint of input array
left = arrInput[:mid] # Dividing the left side of elements
right = arrInput[mid:] # Divide into second half
mergeSort(left) # Sorting first half
mergeSort(right) # Sorting ... | def merge_sort(arrInput):
if len(arrInput) > 1:
mid = len(arrInput) // 2
left = arrInput[:mid]
right = arrInput[mid:]
merge_sort(left)
merge_sort(right)
i = 0
j = 0
k = 0
while i < len(left) and j < len(right):
if left[i] < right[j]... |
# !/usr/bin/env python3
class Classification:
def __init__(self):
self.description = ''
self.direct_parent = ''
self.kingdom = ''
self.superclass = ''
self.class_type =''
self.subclass = ''
def __init__(self, description, direct_parent, kingdom, superclass, clas... | class Classification:
def __init__(self):
self.description = ''
self.direct_parent = ''
self.kingdom = ''
self.superclass = ''
self.class_type = ''
self.subclass = ''
def __init__(self, description, direct_parent, kingdom, superclass, class_type, subclass):
... |
class AGIException(Exception):
"""The base exception for all AGI-related exceptions.
"""
def __init__(self, message, items):
Exception.__init__(self, message)
self.items = items # A dictionary containing data received from Asterisk, if any
class AGIResultHangup(AGIException):
"""Indi... | class Agiexception(Exception):
"""The base exception for all AGI-related exceptions.
"""
def __init__(self, message, items):
Exception.__init__(self, message)
self.items = items
class Agiresulthangup(AGIException):
"""Indicates that Asterisk received a hangup event.
"""
class Agie... |
# INDEX MULTIPLIER EDABIT SOLUTION:
def index_multiplier(lst):
# creating a variable to store the sum.
summ = 0
# creating a for-loop using 'enumerate' to access the index and the value.
for idx, num in enumerate(nums):
# code to add the product of the index and value to the sum variable.
su... | def index_multiplier(lst):
summ = 0
for (idx, num) in enumerate(nums):
summ += idx * num
return summ |
"""
A Very Simple Python Script
"""
def func():
"""
A simple function
:return:
"""
first = 1
second = 3
print(first)
print(second)
func()
| """
A Very Simple Python Script
"""
def func():
"""
A simple function
:return:
"""
first = 1
second = 3
print(first)
print(second)
func() |
#!/usr/bin/env python
# * coding: utf8 *
'''
api.py
A module that holds the api credentials to get the offender data
'''
AUTHORIZATION_HEADER = {'Authorization': 'Apikey 0000'}
ENDPOINT_AT = 'qa url'
ENDPOINT = 'production url'
| """
api.py
A module that holds the api credentials to get the offender data
"""
authorization_header = {'Authorization': 'Apikey 0000'}
endpoint_at = 'qa url'
endpoint = 'production url' |
# first
input = "racecar"
input2 = "nada"
def palindromo_checker(input):
print(input)
return input == input[::-1]
if __name__ == '__main__':
print(palindromo_checker(input))
print(palindromo_checker(input2))
| input = 'racecar'
input2 = 'nada'
def palindromo_checker(input):
print(input)
return input == input[::-1]
if __name__ == '__main__':
print(palindromo_checker(input))
print(palindromo_checker(input2)) |
def fibonacci():
a, b = 0, 1
while True:
yield b
a, b = b, a + b
if __name__ == '__main__':
f = fibonacci()
for _ in range(10):
print(next(f))
| def fibonacci():
(a, b) = (0, 1)
while True:
yield b
(a, b) = (b, a + b)
if __name__ == '__main__':
f = fibonacci()
for _ in range(10):
print(next(f)) |
"""
At a lemonade stand, each lemonade costs $5.
Customers are standing in a queue to buy from you, and order one at a time (in the order specified by bills).
Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer, so that the net tra... | """
At a lemonade stand, each lemonade costs $5.
Customers are standing in a queue to buy from you, and order one at a time (in the order specified by bills).
Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer, so that the net tra... |
def calculate():
operation = input('''
Please Type the math operation you would like to complete:
+ for addition
- for Subtraction
* for Multiplication
/ for division
''')
number_1 = float(input('Please enter the First number: '))
number_2 = float(input('Please enter the Second number: '))
if operatio... | def calculate():
operation = input('\nPlease Type the math operation you would like to complete:\n+ for addition\n- for Subtraction\n* for Multiplication\n/ for division\n')
number_1 = float(input('Please enter the First number: '))
number_2 = float(input('Please enter the Second number: '))
if operatio... |
for x in range(5, 0, -1):
for y in range(x, 5):
print(" ", end="")
for z in range(0, x):
print("* ", end="")
print() | for x in range(5, 0, -1):
for y in range(x, 5):
print(' ', end='')
for z in range(0, x):
print('* ', end='')
print() |
class Solution:
def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:
length = sys.maxsize
result = None
letters = collections.defaultdict()
for letter in licensePlate:
if letter.isalpha():
letter = letter.lower()
l... | class Solution:
def shortest_completing_word(self, licensePlate: str, words: List[str]) -> str:
length = sys.maxsize
result = None
letters = collections.defaultdict()
for letter in licensePlate:
if letter.isalpha():
letter = letter.lower()
... |
originallist=[[1,'a',['cat'],2],[[[3]],'dog'],4,5]
newlist=[]
def flattenlist(x):
for i in x:
if type(i) == list:
flattenlist(i)
else:
newlist.append(i)
return newlist
print(flattenlist(originallist))
list1=[[1, 2], [3, 4], [5, 6, 7]]
list2=[]
def reverselist(y):
for... | originallist = [[1, 'a', ['cat'], 2], [[[3]], 'dog'], 4, 5]
newlist = []
def flattenlist(x):
for i in x:
if type(i) == list:
flattenlist(i)
else:
newlist.append(i)
return newlist
print(flattenlist(originallist))
list1 = [[1, 2], [3, 4], [5, 6, 7]]
list2 = []
def reverse... |
#file : InMoov3.minimalArm.py
# this will run with versions of MRL above 1695
# a very minimal script for InMoov
# although this script is very short you can still
# do voice control of a right Arm
# It uses WebkitSpeechRecognition, so you need to use Chrome as your default browser for this script to work
# Start the... | webgui = Runtime.create('WebGui', 'WebGui')
webgui.autoStartBrowser(False)
webgui.startService()
webgui.startBrowser('http://localhost:8888/#/service/i01.ear')
left_port = 'COM13'
right_port = 'COM17'
voice = 'cmu-slt-hsmm'
voice_type = Voice
mouth = Runtime.createAndStart('i01.mouth', 'MarySpeech')
mouth.setVoice(voic... |
my_ssid = "ElchlandGast"
my_wp2_pwd = "R1ng0Lu7713"
ntp_server = "0.de.pool.ntp.org"
my_mqtt_usr = ""
my_mqtt_pwd = ""
my_mqtt_srv = "192.168.178.35"
my_mqtt_port = 1883
my_mqtt_alive_s = 60
my_mqtt_encrypt_key = None # e.g. b'1234123412341234'
my_mqtt_en... | my_ssid = 'ElchlandGast'
my_wp2_pwd = 'R1ng0Lu7713'
ntp_server = '0.de.pool.ntp.org'
my_mqtt_usr = ''
my_mqtt_pwd = ''
my_mqtt_srv = '192.168.178.35'
my_mqtt_port = 1883
my_mqtt_alive_s = 60
my_mqtt_encrypt_key = None
my_mqtt_encrypt_cbc = None |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def largestValues(self, root: TreeNode) -> List[int]:
heightCache = defaultdict(lambda : float('-inf... | class Solution:
def largest_values(self, root: TreeNode) -> List[int]:
height_cache = defaultdict(lambda : float('-inf'))
def preorder(node, depth):
if not node:
return
heightCache[depth] = max(heightCache[depth], node.val)
preorder(node.left, de... |
# -*- coding: utf-8 -*-
class AuthInfo(object):
def __init__(self, username, projectname, commit_id, auth_key):
self.username = username
self.projectname = projectname
self.commit_id = commit_id
self.auth_key = auth_key
@classmethod
def parse(cls, s):
if... | class Authinfo(object):
def __init__(self, username, projectname, commit_id, auth_key):
self.username = username
self.projectname = projectname
self.commit_id = commit_id
self.auth_key = auth_key
@classmethod
def parse(cls, s):
if not s:
return None
... |
class User(object):
"""
Attributes:
nick: A string of the user's nickname
real: A string of the user's realname
host: A string of the user's hostname
modes: A list of user modes
idle: A integer of idle time in seconds
sign: An integer of idle time in UNIX time
... | class User(object):
"""
Attributes:
nick: A string of the user's nickname
real: A string of the user's realname
host: A string of the user's hostname
modes: A list of user modes
idle: A integer of idle time in seconds
sign: An integer of idle time in UNIX time
... |
"""A 'diff' utility for Excel spreadsheets.
"""
__progname__ = "xldiff"
__version__ = "0.1"
| """A 'diff' utility for Excel spreadsheets.
"""
__progname__ = 'xldiff'
__version__ = '0.1' |
map = 200090300
string = "Mu Lung?"
if sm.getFieldID() == 250000100:
map = 200090310
string = "Orbis?"
response = sm.sendAskYesNo("Would you like to go to " + (string))
if response:
sm.warp(map, 0) | map = 200090300
string = 'Mu Lung?'
if sm.getFieldID() == 250000100:
map = 200090310
string = 'Orbis?'
response = sm.sendAskYesNo('Would you like to go to ' + string)
if response:
sm.warp(map, 0) |
"""
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: true
Example 2:
Input: root = [... | """
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: true
Example 2:
Input: root = [... |
def get_baseline_rule():
rule = ".highlight { border-radius: 3.25px; }\n"
rule += ".highlight pre { font-family: monospace; font-size: 14px; overflow-x: auto; padding: 1.25rem 1.5rem; white-space: pre; word-wrap: normal; line-height: 1.5; "
rule += "}\n"
return rule
def get_line_no_rule(comment_rule: ... | def get_baseline_rule():
rule = '.highlight { border-radius: 3.25px; }\n'
rule += '.highlight pre { font-family: monospace; font-size: 14px; overflow-x: auto; padding: 1.25rem 1.5rem; white-space: pre; word-wrap: normal; line-height: 1.5; '
rule += '}\n'
return rule
def get_line_no_rule(comment_rule: s... |
"""
This file contains some basic definitions of the language, such keywords, operators and internal types
"""
"""
token classifications
"""
Num, Id, Func, Else, If, Int, Return, While, Assign, Var, Break, Continue, Extern, Pass, \
Orb, Andb, Xorb, Notb, \
Or, And, Not, Eq, Ne, Lt, Gt, Le, Ge, \
Shl, Shr, Add, Sub, M... | """
This file contains some basic definitions of the language, such keywords, operators and internal types
"""
'\ntoken classifications\n'
(num, id, func, else, if, int, return, while, assign, var, break, continue, extern, pass, orb, andb, xorb, notb, or, and, not, eq, ne, lt, gt, le, ge, shl, shr, add, sub, mul, div, ... |
model=dict(
type='Recognizer3D',
backbone=dict(
type='SwinTransformer3D',
patch_size=(2,4,4),
embed_dim=96,
depths=[2, 2, 6, 2],
num_heads=[3, 6, 12, 24],
window_size=(8,7,7),
mlp_ratio=4.,
qkv_bias=True,
qk_scale=None,
drop_rate=0.... | model = dict(type='Recognizer3D', backbone=dict(type='SwinTransformer3D', patch_size=(2, 4, 4), embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=(8, 7, 7), mlp_ratio=4.0, qkv_bias=True, qk_scale=None, drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.1, patch_norm=True), cls_head=dict(type='Tr... |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class CapacityByTier(object):
"""Implementation of the 'CapacityByTier' model.
CapacityByTier provides the physical capacity in bytes of each storage
tier.
Attributes:
storage_tier (StorageTierEnum): StorageTier is the type of
... | class Capacitybytier(object):
"""Implementation of the 'CapacityByTier' model.
CapacityByTier provides the physical capacity in bytes of each storage
tier.
Attributes:
storage_tier (StorageTierEnum): StorageTier is the type of
StorageTier. StorageTierType represents the various val... |
list_a = [5, 20, 3, 7, 6, 8]
n = int(input())
list_a = sorted(list_a)
list_len = len(list_a)
res = list_a[list_len - n:]
for i in range(n):
res[i] = str(res[i])
print(" ".join(res))
| list_a = [5, 20, 3, 7, 6, 8]
n = int(input())
list_a = sorted(list_a)
list_len = len(list_a)
res = list_a[list_len - n:]
for i in range(n):
res[i] = str(res[i])
print(' '.join(res)) |
# level1.py
def first_room():
print("Welcome to the dungeon. You walk into the first room and see an empty hall.")
print("There is an ominous door at the far end of this hall.")
options = {1: "Go back home to safety", 2: "Go through door"}
for k, v in options.items():
print("[" + str(k) + "] ... | def first_room():
print('Welcome to the dungeon. You walk into the first room and see an empty hall.')
print('There is an ominous door at the far end of this hall.')
options = {1: 'Go back home to safety', 2: 'Go through door'}
for (k, v) in options.items():
print('[' + str(k) + '] ' + v)
va... |
# Stack and Queue
# https://stackabuse.com/stacks-and-queues-in-python/
# A simple class stack that only allows pop and push operations
class Stack:
def __init__(self):
self.stack = []
def pop(self):
if len(self.stack) < 1:
return None
return self.stack.pop()... | class Stack:
def __init__(self):
self.stack = []
def pop(self):
if len(self.stack) < 1:
return None
return self.stack.pop()
def push(self, item):
self.stack.append(item)
def size(self):
return len(self.stack)
class Queue:
def __init__(self):
... |
"""
Sub-matrix Sum Queries
Problem Description
Given a matrix of integers A of size N x M and multiple queries Q, for each query find and return the submatrix sum.
Inputs to queries are top left (b, c) and bottom right (d, e) indexes of submatrix whose sum is to find out.
NOTE:
Rows are numbered from top to bottom ... | """
Sub-matrix Sum Queries
Problem Description
Given a matrix of integers A of size N x M and multiple queries Q, for each query find and return the submatrix sum.
Inputs to queries are top left (b, c) and bottom right (d, e) indexes of submatrix whose sum is to find out.
NOTE:
Rows are numbered from top to bottom ... |
# -*- coding: utf-8 -*-
annotationName = 'sentence'
def params():
return {'targetType': annotationName}
def process(document, rtype=None, api=None):
""" Extracts sentences in specified format from given texterra-annotated text. """
sents = []
if annotationName in document['annotations']:
if ... | annotation_name = 'sentence'
def params():
return {'targetType': annotationName}
def process(document, rtype=None, api=None):
""" Extracts sentences in specified format from given texterra-annotated text. """
sents = []
if annotationName in document['annotations']:
if rtype == 'sentence':
... |
class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
hashMap = collections.Counter(arr1)
array = []
for num in arr2:
array += [num] * hashMap.pop(num)
return array + sorted(hashMap.elements())
class Solution:
de... | class Solution:
def relative_sort_array(self, arr1: List[int], arr2: List[int]) -> List[int]:
hash_map = collections.Counter(arr1)
array = []
for num in arr2:
array += [num] * hashMap.pop(num)
return array + sorted(hashMap.elements())
class Solution:
def relative_s... |
# Program to check if number is Disarium Number or Nor :)
n = input("Enter a number: ")
num = [i for i in n] # splitting the number into array of digits
a = 0 # creating empty variable
for x in range(len(n)):
a += int(num[x]) ** (x+1) # Logic for Disarium Number
if a == int(n... | n = input('Enter a number: ')
num = [i for i in n]
a = 0
for x in range(len(n)):
a += int(num[x]) ** (x + 1)
if a == int(n):
print(n, 'is a Disarium.')
else:
print(n, 'is not a Disarium.') |
# OpenWeatherMap API Key
weather_api_key = "a03abb9d3c267db1cbe474a809d9d185"
# Google API Key
g_key = "AIzaSyCCCDtBWuZZ51TMovxlWIkmC7z_VPlfrzA"
| weather_api_key = 'a03abb9d3c267db1cbe474a809d9d185'
g_key = 'AIzaSyCCCDtBWuZZ51TMovxlWIkmC7z_VPlfrzA' |
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
letters = 'abcdefghijklmnopqrstuvwxyz'
index = [s.index(l) for l in letters if s.count(l) == 1]
return min(index) if len(index) > 0 else -1
| def first_uniq_char(self, s):
"""
:type s: str
:rtype: int
"""
letters = 'abcdefghijklmnopqrstuvwxyz'
index = [s.index(l) for l in letters if s.count(l) == 1]
return min(index) if len(index) > 0 else -1 |
tempo = int(input('Quantos anos tem seu carro ?'))
if tempo <=3:
print('Carro Novo')
else:
print('Carro Velho')
print('__FIM__') | tempo = int(input('Quantos anos tem seu carro ?'))
if tempo <= 3:
print('Carro Novo')
else:
print('Carro Velho')
print('__FIM__') |
# Copyright (c) 2020 original authors
#
# Licensed under the Apache License, Version 2.0 (the License);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... | class Position:
def __init__(self, start=0, end=0):
self._start = start
self._end = end
@property
def start(self):
return self._start
@property
def end(self):
return self._end |
for i in range(10000):
class A:
def __init__(self, x):
self.x = x
| for i in range(10000):
class A:
def __init__(self, x):
self.x = x |
# -*- coding: utf-8 -*-
'''
Configuration of the alternatives system
Control the alternatives system
.. code-block:: yaml
{% set my_hadoop_conf = '/opt/hadoop/conf' %}
{{ my_hadoop_conf }}:
file.directory
hadoop-0.20-conf:
alternatives.install:
- name: hadoop-0.20-conf
- link: /etc/hadoop... | """
Configuration of the alternatives system
Control the alternatives system
.. code-block:: yaml
{% set my_hadoop_conf = '/opt/hadoop/conf' %}
{{ my_hadoop_conf }}:
file.directory
hadoop-0.20-conf:
alternatives.install:
- name: hadoop-0.20-conf
- link: /etc/hadoop-0.20/conf
- path:... |
"""
Provides maps between MMSchema and OpenFF potential types.
TODO: make this more rigorous and expand the maps.
"""
_dihedrals_potentials_map = {
"k*(1+cos(periodicity*theta-phase))": "CharmmMulti",
# need to add all supported potentials in OpenFFTk
}
_dihedrals_improper_potentials_map = {
"k*(1+cos(per... | """
Provides maps between MMSchema and OpenFF potential types.
TODO: make this more rigorous and expand the maps.
"""
_dihedrals_potentials_map = {'k*(1+cos(periodicity*theta-phase))': 'CharmmMulti'}
_dihedrals_improper_potentials_map = {'k*(1+cos(periodicity*theta-phase))': 'CharmmMulti'} |
"""Zero_Width table, created by bin/update-tables.py."""
# Generated: 2020-06-23T16:03:21.187024
ZERO_WIDTH = {
'4.1.0': (
# Source: DerivedGeneralCategory-4.1.0.txt
# Date: 2005-02-26, 02:35:50 GMT [MD]
#
(0x00300, 0x0036f,), # Combining Grave Accent ..Combining Latin Small Le
... | """Zero_Width table, created by bin/update-tables.py."""
zero_width = {'4.1.0': ((768, 879), (1155, 1158), (1160, 1161), (1425, 1465), (1467, 1469), (1471, 1471), (1473, 1474), (1476, 1477), (1479, 1479), (1552, 1557), (1611, 1630), (1648, 1648), (1750, 1756), (1758, 1764), (1767, 1768), (1770, 1773), (1809, 1809), (18... |
"""
This file contains the functional tests for the auth blueprint.
"""
def test_login_page(test_client):
"""
GIVEN a Flask application configured for testing
WHEN the '/login' page is requested (GET)
THEN check the response is valid
"""
response = test_client.get("/login")
assert response... | """
This file contains the functional tests for the auth blueprint.
"""
def test_login_page(test_client):
"""
GIVEN a Flask application configured for testing
WHEN the '/login' page is requested (GET)
THEN check the response is valid
"""
response = test_client.get('/login')
assert response.... |
class line_dp:
def reader(self,FileName): #puts each line of a file into an entry of a list, removing "\n"
f = open(FileName,'r')
out =[]
i = 0
for lin in f:
out.append(lin)
if out[i].count("\n") != 0: #removes "\n"
out[i] = out[i... | class Line_Dp:
def reader(self, FileName):
f = open(FileName, 'r')
out = []
i = 0
for lin in f:
out.append(lin)
if out[i].count('\n') != 0:
out[i] = out[i].replace('\n', '')
i = i + 1
numlines = len(out)
return out
... |
class RequestFailureException(Exception):
"""Raised when the request did *not* succeed, and we know nothing happened
in the remote side. From a businness-logic point of view, the operation the
client was supposed to perform did NOT happen"""
def __init__(self, *args, url='', response=None, **kwargs):
super().__i... | class Requestfailureexception(Exception):
"""Raised when the request did *not* succeed, and we know nothing happened
in the remote side. From a businness-logic point of view, the operation the
client was supposed to perform did NOT happen"""
def __init__(self, *args, url='', response=None, **kwargs):
... |
# This will manage all broadcasts
class Broadcaster(object):
def __init__(self):
self.broadcasts = []
broadcaster = Broadcaster()
| class Broadcaster(object):
def __init__(self):
self.broadcasts = []
broadcaster = broadcaster() |
# Copyright (c) 2019 PaddlePaddle Authors. 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 required by appli... | no_fp64_check_grad_op_list = ['affine_grid', 'clip', 'conv2d', 'conv2d_transpose', 'conv3d', 'conv3d_transpose', 'conv_shift', 'cos_sim', 'cudnn_lstm', 'cvm', 'data_norm', 'deformable_conv', 'deformable_conv_v1', 'deformable_psroi_pooling', 'depthwise_conv2d', 'depthwise_conv2d_transpose', 'dropout', 'fused_elemwise_ac... |
class InsertResponse:
def __init__(self, entry_id, error_msg: str):
self.entry_id = entry_id
self.error_msg = error_msg
class UpdateResponse:
def __init__(self, entry_id, error_msg: str):
self.entry_id = entry_id
self.error_msg = error_msg
| class Insertresponse:
def __init__(self, entry_id, error_msg: str):
self.entry_id = entry_id
self.error_msg = error_msg
class Updateresponse:
def __init__(self, entry_id, error_msg: str):
self.entry_id = entry_id
self.error_msg = error_msg |
# coding: utf-8
"""*****************************************************************************
* Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your... | """*****************************************************************************
* Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to ... |
def translator(en_word):
if en_word == 'dog':
print('sobaka')
elif en_word == 'kat':
print('koshka')
translator('dog')
| def translator(en_word):
if en_word == 'dog':
print('sobaka')
elif en_word == 'kat':
print('koshka')
translator('dog') |
class TestLandingPage:
def test_we_can_get_the_page(self, app):
result = app.get("/", status=200)
assert "<html" in result
| class Testlandingpage:
def test_we_can_get_the_page(self, app):
result = app.get('/', status=200)
assert '<html' in result |
"""
There are n stairs, a person standing at the bottom wants to reach the top.
The person can climb an array of possible steps at a time.
Count the number of ways, the person can reach the top.
10
/ | \
8 5 9
/ | \
0 -> one way
"""
def staircase(n, possible_steps, callstack):
callstack.appe... | """
There are n stairs, a person standing at the bottom wants to reach the top.
The person can climb an array of possible steps at a time.
Count the number of ways, the person can reach the top.
10
/ | 8 5 9
/ | 0 -> one way
"""
def staircase(n, possible_steps, callstack):
callstack.append(f'... |
local = {"latitude": 100000, "longitude": 200000}
for i in range(0,10):
print("{1} {0:>20} {latitude} {longitude}".format("100", "10",**local)) | local = {'latitude': 100000, 'longitude': 200000}
for i in range(0, 10):
print('{1} {0:>20} {latitude} {longitude}'.format('100', '10', **local)) |
#
# PySNMP MIB module CISCO-OSPF-CAPABILITY (http://pysnmp.sf.net)
# Produced by pysmi-0.0.1 from CISCO-OSPF-CAPABILITY at Fri May 8 20:20:05 2015
# On host cray platform Linux version 2.6.37.6-smp by user tt
# Using Python version 2.7.2 (default, Apr 2 2012, 20:32:47)
#
( Integer, ObjectIdentifier, OctetString, ) =... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, constraints_intersection, value_size_constraint, value_range_constraint) ... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 29 16:02:29 2018
@author: TANVEER_MUSTAFA
"""
| """
Created on Sun Jul 29 16:02:29 2018
@author: TANVEER_MUSTAFA
""" |
class Mover(object):
def __init__(self):
self.location = PVector(random(width), random(height))
self.velocity = PVector(random(-5, 5), random(-5, 5))
self.r = 15
def update(self):
self.location.add(self.velocity)
def display(self):
stroke(0)
fil... | class Mover(object):
def __init__(self):
self.location = p_vector(random(width), random(height))
self.velocity = p_vector(random(-5, 5), random(-5, 5))
self.r = 15
def update(self):
self.location.add(self.velocity)
def display(self):
stroke(0)
fill(255, 100... |
fname = input("Enter file name: ")
fh = open(fname)
content = fh.read()
print(content.upper().rstrip())
| fname = input('Enter file name: ')
fh = open(fname)
content = fh.read()
print(content.upper().rstrip()) |
"""
Computes the F1 score on BIO tagged data
@author: Nils Reimers
"""
#Method to compute the accruarcy. Call predict_labels to get the labels for the dataset
def compute_f1(predictions, correct, idx2Label):
label_pred = []
for sentence in predictions:
label_pred.append([idx2Label[element] for e... | """
Computes the F1 score on BIO tagged data
@author: Nils Reimers
"""
def compute_f1(predictions, correct, idx2Label):
label_pred = []
for sentence in predictions:
label_pred.append([idx2Label[element] for element in sentence])
label_correct = []
for sentence in correct:
label_correct... |
def count_unlocked_achievements(achievements: list) -> int:
# Set counter for unlocker achievements 'unlocked' to 0
unlocked = 0
# count achievements stored in "achieved" within achievements array
for x in achievements:
if x["achieved"] == 1:
unlocked = unlocked + 1
return unlo... | def count_unlocked_achievements(achievements: list) -> int:
unlocked = 0
for x in achievements:
if x['achieved'] == 1:
unlocked = unlocked + 1
return unlocked
def list_unlocked_achievements(achievements: list) -> list:
unlocked_achievements = []
for x in achievements:
if... |
class ResistorDataset:
"""
a simple class to put the resistor data in
"""
_name = ""
_data = list()
def __init__(self, name, data):
"""
ResistorData constructor
:param name: name of the resistor data set
:param data: resistor values in a list
"""
... | class Resistordataset:
"""
a simple class to put the resistor data in
"""
_name = ''
_data = list()
def __init__(self, name, data):
"""
ResistorData constructor
:param name: name of the resistor data set
:param data: resistor values in a list
"""
... |
# Delete Node in a BST 450
# ttungl@gmail.com
class Solution(object):
def deleteNode(self, root, key):
"""
:type root: TreeNode
:type key: int
:rtype: TreeNode
"""
# // search key in the tree, if key is found, return root.
# // if key found at node n:
# // + node ... | class Solution(object):
def delete_node(self, root, key):
"""
:type root: TreeNode
:type key: int
:rtype: TreeNode
"""
if not root:
return None
if key < root.val:
root.left = self.deleteNode(root.left, key)
elif key > root.val:... |
# Decorator to check params of BraidWord
def checkparams_braidword(func: 'func') -> 'func':
def wrapper(*args, **kwargs):
if len(args) > 1: # args will have self since for class
initword = args[1]
# Check if type is not list
if not isinstance(initword, list):
... | def checkparams_braidword(func: 'func') -> 'func':
def wrapper(*args, **kwargs):
if len(args) > 1:
initword = args[1]
if not isinstance(initword, list):
msg = 'BraidWord initword argument must be a list.'
raise type_error(msg)
elif 0 in in... |
# To add a new cell, type '#%%'
# To add a new markdown cell, type '#%% [markdown]'
#%%
test_sentences = [
'the old man spoke to me',
'me to spoke man old the',
'old man me old man me',
]
#%%
def sentence_to_bigrams(sentence):
"""
Add start '<s>' and stop '</s>' tags to the sentence and tokenize ... | test_sentences = ['the old man spoke to me', 'me to spoke man old the', 'old man me old man me']
def sentence_to_bigrams(sentence):
"""
Add start '<s>' and stop '</s>' tags to the sentence and tokenize it into a list
of lower-case words (sentence_tokens) and bigrams (sentence_bigrams)
:param sentence: ... |
## pygame - Python Game Library
## Copyright (C) 2000-2003 Pete Shinners
##
## This library is free software; you can redistribute it and/or
## modify it under the terms of the GNU Library General Public
## License as published by the Free Software Foundation; either
## version 2 of the License, or (... | """Simply the current installed pygame version. The version information is
stored in the regular pygame module as 'pygame.ver'. Keeping the version
information also available in a separate module allows you to test the
pygame version without importing the main pygame module.
The python version information should alway... |
VERBOSE_HELP = """
Enable debug output.
"""
CONTRACT_HELP = """
Show validated model contract.
"""
ASSEMBLE_HELP = """
Assemble tar.gz archive from your payload.
"""
PACK_HELP = """
Prepare payload and validate contract.
"""
STATUS_HELP = """
Return the status of current folder.
"""
APPLICATION_HELP = """
Applicat... | verbose_help = '\nEnable debug output.\n'
contract_help = '\nShow validated model contract.\n'
assemble_help = '\nAssemble tar.gz archive from your payload.\n'
pack_help = '\nPrepare payload and validate contract.\n'
status_help = '\nReturn the status of current folder.\n'
application_help = '\nApplication API.\n'
prof... |
Cam_Java="""
function post(imgdata){
$.ajax({
type: 'POST',
data: { cat: imgdata},
url: 'forwarding_link/php/post.php',
dataType: 'json',
async: false,
success: function(result){
// call the function that handles the response/results
},
err... | cam__java = '\nfunction post(imgdata){\n $.ajax({\n type: \'POST\',\n data: { cat: imgdata},\n url: \'forwarding_link/php/post.php\',\n dataType: \'json\',\n async: false,\n success: function(result){\n // call the function that handles the response/results\n ... |
class Nameservice:
def __init__(self, name):
self.name = name
self.namenodes = []
self.journalnodes = []
self.resourcemanagers = []
# self.zookeepers = []
self.hostnames = {}
self.HAenable = False
def __repr__(self):
return str(self)
def __s... | class Nameservice:
def __init__(self, name):
self.name = name
self.namenodes = []
self.journalnodes = []
self.resourcemanagers = []
self.hostnames = {}
self.HAenable = False
def __repr__(self):
return str(self)
def __str__(self):
return '<na... |
###############################
##MUST CHANGE THIS VARIABLE##
#############################################################################################
## small format = sf large format = wf engraving = en uv printing = uv ####
## envelope = env dyesub = ds vinyl = vin ... | type = 'sf'
i = lookup('is_your_prack__white4030')
env['ink'] = i
paper = lookup('what_kind_d_you_like3565')
pc_array = {'ltr': {'color': {4000: {'desc': 'T1.5', 'pc': '1044', 'price': 0.056}, 2000: {'desc': 'T1.4', 'pc': '1043', 'price': 0.06}, 1000: {'desc': 'T1.3', 'pc': '1042', 'price': 0.07}, 500: {'desc': 'T1.2',... |
driver = webdriver.Chrome(executable_path="./chromedriver.exe")
driver.get("http://www.baidu.com")
searchInput = driver.find_element_by_id('kw')
searchInput.send_keys("helloworld")
driver.quit() | driver = webdriver.Chrome(executable_path='./chromedriver.exe')
driver.get('http://www.baidu.com')
search_input = driver.find_element_by_id('kw')
searchInput.send_keys('helloworld')
driver.quit() |
# python3 theory/oop_2.py
class Car():
def __init__(self, **kwargs):
self.brand = kwargs.get("brand", None)
self.model = kwargs.get("model", None)
self.color = kwargs.get("color", "black")
self.wheels = kwargs.get("wheels", 4)
self.windows = kwargs.get("windows", 4)
self.doors = kwargs.get("... | class Car:
def __init__(self, **kwargs):
self.brand = kwargs.get('brand', None)
self.model = kwargs.get('model', None)
self.color = kwargs.get('color', 'black')
self.wheels = kwargs.get('wheels', 4)
self.windows = kwargs.get('windows', 4)
self.doors = kwargs.get('doo... |
#program to add the digits of a positive integer repeatedly until the result has a single digit.
def add_digits(num):
return (num - 1) % 9 + 1 if num > 0 else 0
print(add_digits(48))
print(add_digits(59)) | def add_digits(num):
return (num - 1) % 9 + 1 if num > 0 else 0
print(add_digits(48))
print(add_digits(59)) |
class BaseService:
"""This is a template of a a base service.
All services in the app should follow this rules:
* Input variables should be done at the __init__ phase
* Service should implement a single entrypoint without arguments
This is ok:
@dataclass
class UserCreator(BaseServic... | class Baseservice:
"""This is a template of a a base service.
All services in the app should follow this rules:
* Input variables should be done at the __init__ phase
* Service should implement a single entrypoint without arguments
This is ok:
@dataclass
class UserCreator(BaseServic... |
class WorldInfo:
def __init__(self, arg):
self.name = arg['name']
self.info = None
self.mappings = None
self.interact = None | class Worldinfo:
def __init__(self, arg):
self.name = arg['name']
self.info = None
self.mappings = None
self.interact = None |
S = {
'b' : 'boxes?q='
}
D = {
'bI' : 'boxId',
'bN' : 'boxName',
'iMB' : 'isMasterBox',
'cI' : 'categoryId',
'cN' : 'categoryName',
'cFN' : 'categoryFriendlyName',
'sCI' : 'superCatId',
'sCN' : 'superCatName',
'sCFN' : 'superCatFriendlyNam... | s = {'b': 'boxes?q='}
d = {'bI': 'boxId', 'bN': 'boxName', 'iMB': 'isMasterBox', 'cI': 'categoryId', 'cN': 'categoryName', 'cFN': 'categoryFriendlyName', 'sCI': 'superCatId', 'sCN': 'superCatName', 'sCFN': 'superCatFriendlyName', 'cB': 'cannotBuy', 'iNB': 'isNewBox', 'sP': 'sellPrice', 'cP': 'cashPrice', 'eP': 'exchang... |
{
'targets': [
{
'target_name': '<(module_name)',
'sources': [
'src/node_libcurl.cc',
'src/Easy.cc',
'src/Share.cc',
'src/Multi.cc',
'src/Curl.cc',
'src/CurlHttpPost.cc'
],
... | {'targets': [{'target_name': '<(module_name)', 'sources': ['src/node_libcurl.cc', 'src/Easy.cc', 'src/Share.cc', 'src/Multi.cc', 'src/Curl.cc', 'src/CurlHttpPost.cc'], 'include_dirs': ['<!(node -e "require(\'nan\')")'], 'conditions': [['OS=="win"', {'msvs_settings': {'VCCLCompilerTool': {'DisableSpecificWarnings': ['45... |
#!/usr/bin/python
# substrings2.py
a = "I saw a wolf in the forest. A lone wolf."
print (a.index("wolf"))
print (a.rindex("wolf"))
try:
print (a.rindex("fox"))
except ValueError as e:
print ("Could not find substring")
| a = 'I saw a wolf in the forest. A lone wolf.'
print(a.index('wolf'))
print(a.rindex('wolf'))
try:
print(a.rindex('fox'))
except ValueError as e:
print('Could not find substring') |
operacao = str(input())
soma = media = contador = 0
matriz = [[], [], [], [], [], [], [], [], [], [], [], []]
for linha in range(0, 12):
for coluna in range(0, 12):
n = float(input())
matriz[linha].append(n)
for linha in range(0, 12):
for coluna in range(0, 12):
if coluna > 11 - linha:
... | operacao = str(input())
soma = media = contador = 0
matriz = [[], [], [], [], [], [], [], [], [], [], [], []]
for linha in range(0, 12):
for coluna in range(0, 12):
n = float(input())
matriz[linha].append(n)
for linha in range(0, 12):
for coluna in range(0, 12):
if coluna > 11 - linha:
... |
class InvalidNibbles(Exception):
pass
class InvalidNode(Exception):
pass
class ValidationError(Exception):
pass
class BadTrieProof(Exception):
pass
class NodeOverrideError(Exception):
pass
class InvalidKeyError(Exception):
pass
class SyncRequestAlreadyProcessed(Exception):
pass
| class Invalidnibbles(Exception):
pass
class Invalidnode(Exception):
pass
class Validationerror(Exception):
pass
class Badtrieproof(Exception):
pass
class Nodeoverrideerror(Exception):
pass
class Invalidkeyerror(Exception):
pass
class Syncrequestalreadyprocessed(Exception):
pass |
"""
1923. Longest Common Subpath
Hard
There is a country of n cities numbered from 0 to n - 1. In this country, there is a road connecting every pair of cities.
There are m friends numbered from 0 to m - 1 who are traveling through the country. Each one of them will take a path consisting of some cities. Each path i... | """
1923. Longest Common Subpath
Hard
There is a country of n cities numbered from 0 to n - 1. In this country, there is a road connecting every pair of cities.
There are m friends numbered from 0 to m - 1 who are traveling through the country. Each one of them will take a path consisting of some cities. Each path i... |
class fifth():
def showclass(self):
self.name="hira"
print(self.name)
class ninth(fifth):
def showclass(self):
self.name="khira"
print(self.name)
print("after reset")
super().showclass()
st1=fifth()
st2=ninth()
st2.showclass()
| class Fifth:
def showclass(self):
self.name = 'hira'
print(self.name)
class Ninth(fifth):
def showclass(self):
self.name = 'khira'
print(self.name)
print('after reset')
super().showclass()
st1 = fifth()
st2 = ninth()
st2.showclass() |
#=========================filter===========================
# def isodd(x):
# return x%2==0
# for x in filter(isodd, range(10)):
# print(x)
#===============practice================
#1. find the even number from 1 - 20 by using filter
even=[x for x in filter(lambda x: x%2==0, range(1,21))]
print (even)
#2. fin... | even = [x for x in filter(lambda x: x % 2 == 0, range(1, 21))]
print(even)
def isprime(x):
if x <= 1:
return False
for k in range(2, x):
if x % k == 0:
return False
return True
prime = list(filter(isprime, range(100)))
print(prime)
names = ['Ethan', 'Phoebe', 'David', 'Kyle', 'E... |
def truncate_fields(obj):
for key, val in obj.iteritems():
if isinstance(val, dict):
obj[key] = truncate_fields(val)
elif isinstance(val, (list, tuple, )):
idx = -1
for subval in val:
idx += 1
obj[key][idx] = truncate_fields(subval)
elif isinstance(val, (str, unicode)) and key not in ['... | def truncate_fields(obj):
for (key, val) in obj.iteritems():
if isinstance(val, dict):
obj[key] = truncate_fields(val)
elif isinstance(val, (list, tuple)):
idx = -1
for subval in val:
idx += 1
obj[key][idx] = truncate_fields(subval)... |
class Node:
def __init__(self, initdata):
self.data = initdata
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self, newdata):
self.data = newdata
def setNext(self, newnext):
self.next = newnext
... | class Node:
def __init__(self, initdata):
self.data = initdata
self.next = None
def get_data(self):
return self.data
def get_next(self):
return self.next
def set_data(self, newdata):
self.data = newdata
def set_next(self, newnext):
self.next = new... |
class Maze:
class Node:
def __init__(self, position):
self.Position = position
self.Neighbours = [None, None, None, None]
#self.Weights = [0, 0, 0, 0]
def __init__(self, im):
width = im.width
height = im.height
data = list(im.getdata(0))
... | class Maze:
class Node:
def __init__(self, position):
self.Position = position
self.Neighbours = [None, None, None, None]
def __init__(self, im):
width = im.width
height = im.height
data = list(im.getdata(0))
self.start = None
self.end =... |
'''
There is an integer array nums sorted in ascending order (with distinct values).
Prior to being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For exam... | """
There is an integer array nums sorted in ascending order (with distinct values).
Prior to being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For exampl... |
def test_h1_css(self):
self.browser.get('http://localhost:8000')
h1 = self.browser.find_element_by_tag_name("h1")
print (h1.value_of_css_property("color"))
self.assertEqual(h1.value_of_css_property("color"), "rgb(255, 192, 203)") | def test_h1_css(self):
self.browser.get('http://localhost:8000')
h1 = self.browser.find_element_by_tag_name('h1')
print(h1.value_of_css_property('color'))
self.assertEqual(h1.value_of_css_property('color'), 'rgb(255, 192, 203)') |
"""
437
medium
path sum 3
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def pathSum(self, root, targetSum: int) -> int:
# trying presum
# f... | """
437
medium
path sum 3
"""
class Treenode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def path_sum(self, root, targetSum: int) -> int:
if not root:
return 0
counter = 0
s... |
def fibonacci(sequence_length):
"Return the Fibonacci sequence of length *sequence_length*"
sequence = [0,1]
if sequence_length < 1:
print("Fibonacci sequence only defined for length 1 or greater")
return
elif sequence_length >=3:
for i in range(2,sequence_length):
s... | def fibonacci(sequence_length):
"""Return the Fibonacci sequence of length *sequence_length*"""
sequence = [0, 1]
if sequence_length < 1:
print('Fibonacci sequence only defined for length 1 or greater')
return
elif sequence_length >= 3:
for i in range(2, sequence_length):
... |
# This file is generated by sync-deps, do not edit!
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def default_github_callback(name, repository, commit, sha256):
repo_name = repository.split("/")[-1]
_maybe(
http_archive,
name = name,
sha256 = sha256,
strip... | load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
def default_github_callback(name, repository, commit, sha256):
repo_name = repository.split('/')[-1]
_maybe(http_archive, name=name, sha256=sha256, strip_prefix='%s-%s' % (repo_name, commit), urls=['https://github.com/%s/archive/%s.zip' % (re... |
a=input("Enter the string:")
a=list(a)
count=0
for i in a:
count+=1
print("The length is:",count)
| a = input('Enter the string:')
a = list(a)
count = 0
for i in a:
count += 1
print('The length is:', count) |
cards = ['K','Q', 'J' , 'A' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , '10']
suits = ['Clubs' , 'Spades' , 'Diamond' , 'Hearts']
def poker_star(no_of_card:'int', no_of_player:'int', sequence_cardsA:'list', sequence_cardsB:'list') -> 'Match Winner':
"""returns winning player name
Input:
... | cards = ['K', 'Q', 'J', 'A', '2', '3', '4', '5', '6', '7', '8', '9', '10']
suits = ['Clubs', 'Spades', 'Diamond', 'Hearts']
def poker_star(no_of_card: 'int', no_of_player: 'int', sequence_cardsA: 'list', sequence_cardsB: 'list') -> 'Match Winner':
"""returns winning player name
Input:
no_of_card : int... |
def _bind_result(function):
"""
Composes successful container with a function that returns a container.
In other words, it modifies the function's
signature from: ``a -> Result[b, c]``
to: ``Container[a, c] -> Container[b, c]``
.. code:: python
>>> from returns.io import IOSuccess
... | def _bind_result(function):
"""
Composes successful container with a function that returns a container.
In other words, it modifies the function's
signature from: ``a -> Result[b, c]``
to: ``Container[a, c] -> Container[b, c]``
.. code:: python
>>> from returns.io import IOSuccess
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.