content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
'''
Mysql Table Create Queries
'''
tables = [
# master_config Table
'''
CREATE TABLE IF NOT EXISTS master_config (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
author VARCHAR(20) NOT NULL,
PRIMARY KEY(id)
);
''',
'''
CREATE TABLE IF NOT EXISTS user (
id VARCHAR(200) NOT NULL,
... | """
Mysql Table Create Queries
"""
tables = ['\n CREATE TABLE IF NOT EXISTS master_config (\n id INT UNSIGNED NOT NULL AUTO_INCREMENT,\n author VARCHAR(20) NOT NULL,\n PRIMARY KEY(id)\n );\n', '\n CREATE TABLE IF NOT EXISTS user (\n id VARCHAR(200) NOT NULL,\n pw VARCHAR(200)... |
x,y = map(int,input().split())
if x+y < 10:
print(x+y)
else:
print("error") | (x, y) = map(int, input().split())
if x + y < 10:
print(x + y)
else:
print('error') |
class Address(object):
ADDRESS_UTIM = 0
ADDRESS_UHOST = 1
ADDRESS_DEVICE = 2
ADDRESS_PLATFORM = 3
| class Address(object):
address_utim = 0
address_uhost = 1
address_device = 2
address_platform = 3 |
s = "a quick {0} brown fox {2} jumped over {1} the lazy dog";
x = 100;
y = 200;
z = 300;
t = s.format(x,y,z);
print(t); | s = 'a quick {0} brown fox {2} jumped over {1} the lazy dog'
x = 100
y = 200
z = 300
t = s.format(x, y, z)
print(t) |
def uncollapse(s):
for n in ['zero','one','two','three','four','five','six','seven','eight','nine']:
s=s.replace(n,n+' ')
return s[:-1]
def G(s):
for n in ['zero','one','two','three','four','five','six','seven','eight','nine']:
s=s.replace(n,n+' ')
return s[:-1]
| def uncollapse(s):
for n in ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']:
s = s.replace(n, n + ' ')
return s[:-1]
def g(s):
for n in ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']:
s = s.replace(n, n + ' ')
return s[:... |
"""This file defines the unified tensor framework interface required by DGL
unit testing, other than the ones used in the framework itself.
"""
###############################################################################
# Tensor, data type and context interfaces
def cuda():
"""Context object for CUDA."""
... | """This file defines the unified tensor framework interface required by DGL
unit testing, other than the ones used in the framework itself.
"""
def cuda():
"""Context object for CUDA."""
pass
def is_cuda_available():
"""Check whether CUDA is available."""
pass
def array_equal(a, b):
"""Check whet... |
# based on https://nlp.stanford.edu/software/dependencies_manual.pdf
DEPENDENCY_DEFINITONS = {
'acomp': 'adjectival_complement',
'advcl': 'adverbial_clause_modifier',
'advmod': 'adverb_modifier',
'agent': 'agent',
'amod': 'adjectival_modifier',
'appos': 'appositional_modifier',
'aux': 'auxiliary',
'auxpass': 'p... | dependency_definitons = {'acomp': 'adjectival_complement', 'advcl': 'adverbial_clause_modifier', 'advmod': 'adverb_modifier', 'agent': 'agent', 'amod': 'adjectival_modifier', 'appos': 'appositional_modifier', 'aux': 'auxiliary', 'auxpass': 'passive_auxiliary', 'cc': 'coordination', 'ccomp': 'clausal_complement', 'conj'... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
retu... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sum_of_left_leaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
sum = 0
if ... |
"""The functional module implements various functional needed
for reinforcement learning calculations.
Exposed functions:
* :py:func:`loss.entropy`
* :py:func:`loss.policy_gradient`
* :py:func:`vtrace.from_logits`
"""
| """The functional module implements various functional needed
for reinforcement learning calculations.
Exposed functions:
* :py:func:`loss.entropy`
* :py:func:`loss.policy_gradient`
* :py:func:`vtrace.from_logits`
""" |
class GH_GrasshopperLibraryInfo(GH_AssemblyInfo):
""" GH_GrasshopperLibraryInfo() """
AuthorContact=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: AuthorContact(self: GH_GrasshopperLibraryInfo) -> str
"""
AuthorName=property(lambda self: object(),lambda self,v: None,lambd... | class Gh_Grasshopperlibraryinfo(GH_AssemblyInfo):
""" GH_GrasshopperLibraryInfo() """
author_contact = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Get: AuthorContact(self: GH_GrasshopperLibraryInfo) -> str\n\n\n\n'
author_name = property(lambda self: object(), lambda self, ... |
class Solution:
def reverse(self, x: int) -> int:
s = ''
if x < 0:
s += '-'
x *= -1
else:
s += '0'
while x > 0:
tmp = x % 10
s += str(tmp)
x = x // 10
res = int(s)
if res > 2**31 - 1 or res < - 2*... | class Solution:
def reverse(self, x: int) -> int:
s = ''
if x < 0:
s += '-'
x *= -1
else:
s += '0'
while x > 0:
tmp = x % 10
s += str(tmp)
x = x // 10
res = int(s)
if res > 2 ** 31 - 1 or res < -... |
#!/usr/bin/env python
# encoding: utf-8
"""
surrounded_regions.py
Created by Shengwei on 2014-07-15.
"""
# https://oj.leetcode.com/problems/surrounded-regions/
# tags: hard, matrix, bfs
"""
Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.
A region is captured by flipping all 'O's into... | """
surrounded_regions.py
Created by Shengwei on 2014-07-15.
"""
"\nGiven a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.\n\nA region is captured by flipping all 'O's into 'X's in that surrounded region.\n\nFor example,\nX X X X\nX O O X\nX X O X\nX O X X\nAfter running your function, the boa... |
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param headA: the first list
@param headB: the second list
@return: a ListNode
"""
def getIntersectionNode(self, headA, headB):
... | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param headA: the first list
@param headB: the second list
@return: a ListNode
"""
def get_intersection_node(self, headA, headB):
... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
result = ListNode(0)
curr = result
carry = 0
while l1 or l2... | class Solution:
def add_two_numbers(self, l1: ListNode, l2: ListNode) -> ListNode:
result = list_node(0)
curr = result
carry = 0
while l1 or l2:
x = l1.val if l1 else 0
y = l2.val if l2 else 0
value = carry + x + y
carry = value // 10
... |
string = "PATTERN"
strlen = len(string)
for x in range(0, strlen):
print(string[0:strlen-x]) | string = 'PATTERN'
strlen = len(string)
for x in range(0, strlen):
print(string[0:strlen - x]) |
#Donal Maher
# Check if one number divides by another
def sleep_in(weekday, vacation):
if (weekday and vacation == False):
return False
else:
return True
result = sleep_in(False, False)
print("The result is {} ".format(result)) | def sleep_in(weekday, vacation):
if weekday and vacation == False:
return False
else:
return True
result = sleep_in(False, False)
print('The result is {} '.format(result)) |
def calc(n1 ,op ,n2):
result = 0
if op == '+':
result = n1 + n2
elif op == '-':
result = n1 - n2
elif op == '*':
result = n1 * n2
elif op == '/':
result = n1 / n2
else:
result = 0
return result
num1 = input('Input num1...')
num2 = input('Input num2...... | def calc(n1, op, n2):
result = 0
if op == '+':
result = n1 + n2
elif op == '-':
result = n1 - n2
elif op == '*':
result = n1 * n2
elif op == '/':
result = n1 / n2
else:
result = 0
return result
num1 = input('Input num1...')
num2 = input('Input num2...'... |
n = int(input())
L = list(map(int,input().split()))
ans = 1
c = L[0]
cnt = 1
for i in L[1:]:
if c <= i:
cnt+=1
c = i
ans = max(ans,cnt)
else:
cnt = 1
c = i
c = L[0]
cnt = 1
for i in L[1:]:
if c >= i:
cnt+=1
c = i
ans = max(ans,cnt)
else:
... | n = int(input())
l = list(map(int, input().split()))
ans = 1
c = L[0]
cnt = 1
for i in L[1:]:
if c <= i:
cnt += 1
c = i
ans = max(ans, cnt)
else:
cnt = 1
c = i
c = L[0]
cnt = 1
for i in L[1:]:
if c >= i:
cnt += 1
c = i
ans = max(ans, cnt)
e... |
# -*- coding: utf-8 -*-
class Config(object):
def __init__(self, bucket, root):
self.bucket = bucket
self.root = root
| class Config(object):
def __init__(self, bucket, root):
self.bucket = bucket
self.root = root |
def find_best_investment(arr):
if len(arr) < 2:
return None, None
current_min = arr[0]
current_max_profit = -float("inf")
result = (None, None)
for item in arr[1:]:
current_profit = item - current_min
if current_profit > current_max_profit:
current_max_profit = ... | def find_best_investment(arr):
if len(arr) < 2:
return (None, None)
current_min = arr[0]
current_max_profit = -float('inf')
result = (None, None)
for item in arr[1:]:
current_profit = item - current_min
if current_profit > current_max_profit:
current_max_profit = ... |
def returnValues(z):
results = [(x, y)
for x in range(z)
for y in range(z)
if x + y == 5
if x > y]
return results
print(returnValues(10)) | def return_values(z):
results = [(x, y) for x in range(z) for y in range(z) if x + y == 5 if x > y]
return results
print(return_values(10)) |
# This file is used on sr restored train set (which includes dev segments) tagged with their segment headers
# It splits the set into the dev and train sets using the header information
dev_path = 'dev/text' # stores dev segment information
restored_sr = 'train/text_restored_by_inference_version2_with_tim... | dev_path = 'dev/text'
restored_sr = 'train/text_restored_by_inference_version2_with_timing'
save_dev = open('../../data/sr_restored_split_by_inference_version2/dev', 'a')
save_train = open('../../data/sr_restored_split_by_inference_version2/train', 'a')
def convert_word(text):
t = text.strip()
if t == '':
... |
"""FrequencyEstimator.py
Estimate frequencies of items in a data stream.
D. Eppstein, Feb 2016."""
class FrequencyEstimator:
"""Estimate frequencies of a stream of items to a specified accuracy
(e.g. accuracy=0.1 means within 10% of actual frequency)
using only O(1/accuracy) bytes of memory."""
def _... | """FrequencyEstimator.py
Estimate frequencies of items in a data stream.
D. Eppstein, Feb 2016."""
class Frequencyestimator:
"""Estimate frequencies of a stream of items to a specified accuracy
(e.g. accuracy=0.1 means within 10% of actual frequency)
using only O(1/accuracy) bytes of memory."""
def __... |
async with pyryver.Ryver("organization_name", "username", "password") as ryver:
await ryver.load_chats()
a_user = ryver.get_user(username="tylertian123")
a_forum = ryver.get_groupchat(display_name="Off-Topic")
| async with pyryver.Ryver('organization_name', 'username', 'password') as ryver:
await ryver.load_chats()
a_user = ryver.get_user(username='tylertian123')
a_forum = ryver.get_groupchat(display_name='Off-Topic') |
# tests require to import from Faiss module
# so thus require PYTHONPATH
# the other option would be installing via requirements
# but that would always be a different version
# only required for CI. DO NOT add real tests here, but in top-level integration
def test_dummy():
pass
| def test_dummy():
pass |
numbers = [int(n) for n in input().split(", ")]
count_of_beggars = int(input())
collected = []
index = 0
for i in range(count_of_beggars):
current_list = []
for index in range(0, len(numbers) + 1, count_of_beggars):
index += i
if index < len(numbers):
current_list.append(numbers[i... | numbers = [int(n) for n in input().split(', ')]
count_of_beggars = int(input())
collected = []
index = 0
for i in range(count_of_beggars):
current_list = []
for index in range(0, len(numbers) + 1, count_of_beggars):
index += i
if index < len(numbers):
current_list.append(numbers[inde... |
# list comprehension is an elegant way to creats list based on exesting list
# We can use this one liner comprehensioner for dictnory ans sets also.
#l1 = [3,5,6,7,8,90,12,34,67,0]
'''
# For addind even in l2
l2 =[]
for item in l1:
if item%2 == 0:
l2.append(item)
print(l2)
'''
'''
# Shortcut to write the s... | """
# For addind even in l2
l2 =[]
for item in l1:
if item%2 == 0:
l2.append(item)
print(l2)
"""
'\n# Shortcut to write the same:\nl2 = [item for item in l1 if item < 8]\nl3 = [item for item in l1 if item%2 ==0] # creating a list for \nprint(l2)\nprint(l3)\n'
l4 = ['am', 'em', 'fcgh', 'em', 'em']
l5 = ['a... |
'''
Created on Apr 11, 2017
tutorial:
https://www.youtube.com/watch?v=nefopNkZmB4&list=PL6gx4Cwl9DGAcbMi1sH6oAMk4JHw91mC_&index=3
modules:
https://www.youtube.com/watch?v=sKYiQLRe254
@author: halil
'''
class BayesianFilter(object):
'''
classdocs
'''
def __init__(self):
'''
Constru... | """
Created on Apr 11, 2017
tutorial:
https://www.youtube.com/watch?v=nefopNkZmB4&list=PL6gx4Cwl9DGAcbMi1sH6oAMk4JHw91mC_&index=3
modules:
https://www.youtube.com/watch?v=sKYiQLRe254
@author: halil
"""
class Bayesianfilter(object):
"""
classdocs
"""
def __init__(self):
"""
Construc... |
"""
This is one solution to the cash machine challenge.
It will be good to re run this when they start to do OOP and see how subtly different the code
is.
I have got around the local scope of the subroutines by declaring thst I will be using the global
variables at the start of the subroutines. This is not the only wa... | """
This is one solution to the cash machine challenge.
It will be good to re run this when they start to do OOP and see how subtly different the code
is.
I have got around the local scope of the subroutines by declaring thst I will be using the global
variables at the start of the subroutines. This is not the only wa... |
"""Simplest possible f-string with one string variable."""
name = "Peter"
print(f"Hello {name}")
| """Simplest possible f-string with one string variable."""
name = 'Peter'
print(f'Hello {name}') |
rules = {}
appearances = {}
original = input()
input()
while True:
try:
l, r = input().split(" -> ")
except:
break
rules[l] = r
appearances[l] = 0
for i in range(len(original)-1):
a = original[i]
b = original[i+1]
appearances[a+b] += 1
def polymerization(d):
new = {x... | rules = {}
appearances = {}
original = input()
input()
while True:
try:
(l, r) = input().split(' -> ')
except:
break
rules[l] = r
appearances[l] = 0
for i in range(len(original) - 1):
a = original[i]
b = original[i + 1]
appearances[a + b] += 1
def polymerization(d):
new ... |
class AccountManagement:
"""
All Account requests allow managing the authenticated user's account or are in some way
connected to account management.
"""
def __init__(self, resolve):
self.resolve = resolve
def get_account_information(self):
"""
Returns the account detai... | class Accountmanagement:
"""
All Account requests allow managing the authenticated user's account or are in some way
connected to account management.
"""
def __init__(self, resolve):
self.resolve = resolve
def get_account_information(self):
"""
Returns the account detai... |
n, m = map(int, input().split())
res = []
for _ in range(m):
res.append(int(input()))
res.sort()
price, ans = 0,0
for i in range(m):
result = min(m-i, n)
if ans < res[i] * result:
price = res[i]
ans = res[i] * result
print(price, ans) | (n, m) = map(int, input().split())
res = []
for _ in range(m):
res.append(int(input()))
res.sort()
(price, ans) = (0, 0)
for i in range(m):
result = min(m - i, n)
if ans < res[i] * result:
price = res[i]
ans = res[i] * result
print(price, ans) |
__version__ = "0.3.1"
__logo__ = [
" _ _",
"| | _____ | |__ _ __ __ _",
"| |/ / _ \\| '_ \\| '__/ _` |",
"| < (_) | |_) | | | (_| |",
"|_|\\_\\___/|_.__/|_| \\__,_|",
" "
]
| __version__ = '0.3.1'
__logo__ = [' _ _', '| | _____ | |__ _ __ __ _', "| |/ / _ \\| '_ \\| '__/ _` |", '| < (_) | |_) | | | (_| |', '|_|\\_\\___/|_.__/|_| \\__,_|', ' '] |
def _RELIC__word_list_prep():
file = open('stopwords.txt')
new_file = open('stopwords_new.txt', 'w')
for line in file:
if line.strip():
new_file.write(line)
file.close()
new_file.close()
| def _relic__word_list_prep():
file = open('stopwords.txt')
new_file = open('stopwords_new.txt', 'w')
for line in file:
if line.strip():
new_file.write(line)
file.close()
new_file.close() |
# There are a total of n courses you have to take, labeled from 0 to n - 1.
# Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
# Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish al... | class Solution(object):
def can_finish(self, numCourses, prerequisites):
"""
O(V+E)
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: bool
"""
zero_indegree = []
indegree = {}
outdegree = {}
for (i, j) in prerequisites... |
"""
Web server settings
"""
# 433 MHz Outlet Codes -----------------------------------------------------------------------------
rfcodes = {'1': {'on': '21811', 'off': '21820'},
'2': {'on': '21955', 'off': '21964'},
'3': {'on': '22275', 'off': '22284'},
'4': {'on': '23811', 'off': '2382... | """
Web server settings
"""
rfcodes = {'1': {'on': '21811', 'off': '21820'}, '2': {'on': '21955', 'off': '21964'}, '3': {'on': '22275', 'off': '22284'}, '4': {'on': '23811', 'off': '23820'}, '5': {'on': '29955', 'off': '29964'}, '6': {'on': '10000', 'off': '10010'}, '7': {'on': '11000', 'off': '11010'}, '8': {'on': '12... |
# acutal is the list of actual labels, pred is the list of predicted labels.
# sensitive is the column of sensitive attribute, target_group is s in S = s
# positive_pred is the favorable result in prediction task. e.g. get approved for a loan
def calibration_pos(actual,pred,sensitive,target_group,positive_pred):
to... | def calibration_pos(actual, pred, sensitive, target_group, positive_pred):
tot_pred_pos = 0
act_pos = 0
for (act, pred_val, sens) in zip(actual, pred, sensitive):
if sens != target_group:
continue
elif pred_val == positive_pred:
tot_pred_pos += 1
if act ==... |
# Problem Link: https://www.hackerrank.com/contests/projecteuler/challenges/euler013/problem
sum = 0
for _ in range(int(input())):
sum += int(input())
print(str(sum)[:10])
| sum = 0
for _ in range(int(input())):
sum += int(input())
print(str(sum)[:10]) |
# -*- coding: utf-8 -*-
#
# -- General configuration -------------------------------------
source_suffix = ".rst"
master_doc = "index"
project = u"Sphinx theme for dynamic html presentation style"
copyright = u"2012-2021, Sphinx-users.jp"
version = "0.5.0"
# -- Options for HTML output ------------------------------... | source_suffix = '.rst'
master_doc = 'index'
project = u'Sphinx theme for dynamic html presentation style'
copyright = u'2012-2021, Sphinx-users.jp'
version = '0.5.0'
extensions = ['sphinxjp.themes.impressjs']
html_theme = 'impressjs'
html_use_index = False |
"""Custom mail app exceptions"""
class MultiEmailValidationError(Exception):
"""
General exception for failures while validating multiple emails
"""
def __init__(self, invalid_emails, msg=None):
"""
Args:
invalid_emails (set of str): All email addresses that failed validat... | """Custom mail app exceptions"""
class Multiemailvalidationerror(Exception):
"""
General exception for failures while validating multiple emails
"""
def __init__(self, invalid_emails, msg=None):
"""
Args:
invalid_emails (set of str): All email addresses that failed validati... |
operators = {
'+': (lambda a, b: a + b),
'-': (lambda a, b: a - b),
'*': (lambda a, b: a * b),
'/': (lambda a, b: a / b),
'**': (lambda a, b: a ** b),
'^': (lambda a, b: a ** b)
}
priorities = {
'+': 1,
'-': 1,
'*': 2,
'/': 2,
'**': 3,
'^': 3
}
op_chars = {char for o... | operators = {'+': lambda a, b: a + b, '-': lambda a, b: a - b, '*': lambda a, b: a * b, '/': lambda a, b: a / b, '**': lambda a, b: a ** b, '^': lambda a, b: a ** b}
priorities = {'+': 1, '-': 1, '*': 2, '/': 2, '**': 3, '^': 3}
op_chars = {char for op in operators for char in op}
def evaluate(expression):
infix =... |
states = ["Washington", "Oregon", "California"]
for x in states:
print(x)
print("Washington" in states)
print("Tennessee" in states)
print("Washington" not in states)
states2 = ["Arizona", "Ohio", "Louisiana"]
best_states = states + states2
print(best_states)
print(best_states[1:3])
print(best_states[:2])
print(... | states = ['Washington', 'Oregon', 'California']
for x in states:
print(x)
print('Washington' in states)
print('Tennessee' in states)
print('Washington' not in states)
states2 = ['Arizona', 'Ohio', 'Louisiana']
best_states = states + states2
print(best_states)
print(best_states[1:3])
print(best_states[:2])
print(bes... |
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
##
# Calculates and display a restaurant bill with tax and tips
# @author: rafael magalhaes
# Tax Rate in percent
TAX = 8/100
# Tip percentage
TIP = 18/100
# Getting the meal value
print("Welcome to grand total restaurant app.")
meal_value = float(input("How much was ... | tax = 8 / 100
tip = 18 / 100
print('Welcome to grand total restaurant app.')
meal_value = float(input('How much was the ordered total meal: '))
tax_value = meal_value * TAX
tip_value = meal_value * TIP
grand_total = meal_value + tax_value + tip_value
print('\n\nGreat Meal! Your meal and total amount is:\n')
print('${:1... |
# Topics
topics = {
# Letter A
"Amor post mortem" : ["Love beyond death.", "The nature of love is eternal, a bond that goes beyond physical death."]
, "Amor bonus" : ["Good love.", "The nature of love is good."]
, "Amor ferus" : ["Fiery love.", "A negative nature of the physical love, reference to passionate, rough ... | topics = {'Amor post mortem': ['Love beyond death.', 'The nature of love is eternal, a bond that goes beyond physical death.'], 'Amor bonus': ['Good love.', 'The nature of love is good.'], 'Amor ferus': ['Fiery love.', 'A negative nature of the physical love, reference to passionate, rough sex.'], 'Amor mixtus': ['Mix ... |
def xfail(fun, excp):
flag = False
try:
fun()
except excp:
flag = True
assert flag
| def xfail(fun, excp):
flag = False
try:
fun()
except excp:
flag = True
assert flag |
def reverse_words(text): # 7 kyu
reverse = []
words = text.split(' ')
for word in words:
reverse.append(word[::-1])
return ' '.join(reverse)
t = "This is an example!"
print(reverse_words(t)) | def reverse_words(text):
reverse = []
words = text.split(' ')
for word in words:
reverse.append(word[::-1])
return ' '.join(reverse)
t = 'This is an example!'
print(reverse_words(t)) |
with open('p11_grid.txt', 'r') as file:
lines = file.readlines()
n = []
for line in lines:
a = line.split(' ')
b = []
for i in a:
b.append(int(i))
n.append(b)
N = 0
for i in range(20):
for j in range(20):
horizontal, vertical, diag1, diag2 = 0, 0,... | with open('p11_grid.txt', 'r') as file:
lines = file.readlines()
n = []
for line in lines:
a = line.split(' ')
b = []
for i in a:
b.append(int(i))
n.append(b)
n = 0
for i in range(20):
for j in range(20):
(horizontal, vertical, diag1, diag2) = (0, 0, 0, 0)
if j < 17:
... |
class BST:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
class TreeInfo:
def __init__(self, numberOfNodesVisited, latestVisitedNodeValue):
self.numberOfNodesVisited = numberOfNodesVisited
self.latestVisitedNodeValue = latestVi... | class Bst:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
class Treeinfo:
def __init__(self, numberOfNodesVisited, latestVisitedNodeValue):
self.numberOfNodesVisited = numberOfNodesVisited
self.latestVisitedNode... |
class ObjectA:
"""first type of object to be matched when running the gale-shapley algorithm"""
def __init__(self, name: str):
self.name = name
def __repr__(self):
return self.name
class ObjectB:
"""second type of object to be matched when running the gale-shapley algorithm"""
d... | class Objecta:
"""first type of object to be matched when running the gale-shapley algorithm"""
def __init__(self, name: str):
self.name = name
def __repr__(self):
return self.name
class Objectb:
"""second type of object to be matched when running the gale-shapley algorithm"""
de... |
class Solution:
def mostCommonWord(self, paragraph, banned):
"""
:type paragraph: str
:type banned: List[str]
:rtype: str
"""
return collections.Counter(word for word in re.sub("[!?',;.]", " ", paragraph).lower().split() if word not in banned).most_common(1)[0][0] | class Solution:
def most_common_word(self, paragraph, banned):
"""
:type paragraph: str
:type banned: List[str]
:rtype: str
"""
return collections.Counter((word for word in re.sub("[!?',;.]", ' ', paragraph).lower().split() if word not in banned)).most_common(1)[0][0... |
def compute(data):
lines = data.split('\n')
pairs = {
'(':')',
'[':']',
'{':'}',
'<':'>',
}
p1_scores = {
')':3,
']':57,
'}':1197,
'>':25137,
}
p2_scores = {
')':1,
']':2,
'}':3,
'>':4,
}
... | def compute(data):
lines = data.split('\n')
pairs = {'(': ')', '[': ']', '{': '}', '<': '>'}
p1_scores = {')': 3, ']': 57, '}': 1197, '>': 25137}
p2_scores = {')': 1, ']': 2, '}': 3, '>': 4}
p1_score = 0
p2_score = []
for l in lines:
stack = []
corrupt = False
for c i... |
n = int(input())
count = 0
a_prev, b_prev = -1, 0
for _ in range(n):
a, b = map(int, input().split())
start = max(a_prev, b_prev)
end = min(a, b)
if end >= start:
count += end - start + 1
if a_prev == b_prev:
count -= 1
a_prev, b_prev = a, b
print(count)
| n = int(input())
count = 0
(a_prev, b_prev) = (-1, 0)
for _ in range(n):
(a, b) = map(int, input().split())
start = max(a_prev, b_prev)
end = min(a, b)
if end >= start:
count += end - start + 1
if a_prev == b_prev:
count -= 1
(a_prev, b_prev) = (a, b)
print(count) |
# Copyright 2021 by Saithalavi M, saithalavi@gmail.com
# All rights reserved.
# This file is part of the Nessaid readline Framework, nessaid_readline python package
# and is released under the "MIT License Agreement". Please see the LICENSE
# file included as part of this package.
#
# common
CR = "\x0d"
LF = "\x0a"
BA... | cr = '\r'
lf = '\n'
backspace = '\x7f'
space = ' '
tab = '\t'
esc = '\x1b'
insert = '\x1b[2~'
delete = '\x1b[3~'
page_up = '\x1b[5~'
page_down = '\x1b[6~'
home = '\x1b[H'
end = '\x1b[F'
up = '\x1b[A'
down = '\x1b[B'
left = '\x1b[D'
right = '\x1b[C'
ctrl_a = '\x01'
ctrl_b = '\x02'
ctrl_c = '\x03'
ctrl_d = '\x04'
ctrl_e ... |
"""
Given a binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.
For example:
Given the below binary tree,
1
/ \
2 3
... | """
Given a binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.
For example:
Given the below binary tree,
1
/ 2 3
Re... |
"""Ext macros."""
load("@b//:lib2.bzl", "bar")
foo = bar
| """Ext macros."""
load('@b//:lib2.bzl', 'bar')
foo = bar |
# The contents of this file is free and unencumbered software released into the
# public domain. For more information, please refer to <http://unlicense.org/>
manga_query = '''
query ($id: Int,$search: String) {
Page (perPage: 10) {
media (id: $id, type: MANGA,search: $search) {
id
title {
... | manga_query = '\nquery ($id: Int,$search: String) {\n Page (perPage: 10) {\n media (id: $id, type: MANGA,search: $search) {\n id\n title {\n romaji\n english\n native\n }\n description (asHtml: false)\n startDate{\n year\n }\n ... |
# this code will accept an input string and check if it is a plandrome
# it will then return true if it is a plaindrome and false if it is not
def reverse(str1):
if(len(str1) == 0):
return str1
else:
return reverse(str1[1:]) + str1[0]
string = input("Please enter your own String : ")
# chec... | def reverse(str1):
if len(str1) == 0:
return str1
else:
return reverse(str1[1:]) + str1[0]
string = input('Please enter your own String : ')
str1 = reverse(string)
print('String in reverse Order : ', str1)
if string == str1:
print('This is a Palindrome String')
else:
print('This is Not ... |
ticket_dict1 = {
"pagination": {
"object_count": 2,
"continuation": None,
"page_count": 1,
"page_size": 50,
"has_more_items": False,
"page_number": 1
},
"ticket_classes": [
{
"actual_cost": None,
"actual_fee": {
... | ticket_dict1 = {'pagination': {'object_count': 2, 'continuation': None, 'page_count': 1, 'page_size': 50, 'has_more_items': False, 'page_number': 1}, 'ticket_classes': [{'actual_cost': None, 'actual_fee': {'display': '$7.72', 'currency': 'USD', 'value': 772, 'major_value': '7.72'}, 'cost': {'display': '$100.00', 'curre... |
# sorting
n=7
print(n)
arr=[5,1,1,2,10,2,1]
arr.sort()
for i in arr:
print(i,end=' ')
| n = 7
print(n)
arr = [5, 1, 1, 2, 10, 2, 1]
arr.sort()
for i in arr:
print(i, end=' ') |
n = int(input())
for _ in range(n):
(d, m) = map(int, input().split(' '))
days = list(map(int, input().split(' ')))
day_of_week = 0
friday_13s = 0
for month in range(m):
for day in range(1, days[month] + 1):
if day_of_week == 5 and day == 13:
friday_13s += 1
... | n = int(input())
for _ in range(n):
(d, m) = map(int, input().split(' '))
days = list(map(int, input().split(' ')))
day_of_week = 0
friday_13s = 0
for month in range(m):
for day in range(1, days[month] + 1):
if day_of_week == 5 and day == 13:
friday_13s += 1
... |
class Solution(object):
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
letters = list(s)
start, end = 0, len(letters) - 1
while start < end:
while start < end and let... | class Solution(object):
def reverse_vowels(self, s):
"""
:type s: str
:rtype: str
"""
vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
letters = list(s)
(start, end) = (0, len(letters) - 1)
while start < end:
while start < end a... |
f = open("13.txt", "r")
sum = 0
while (1):
num = 0
line = f.readline()
if line:
line = line.strip('\n')
for i in range(0, len(line)):
num = num * 10 + int(line[i])
sum += num
else:
break
ans = str(sum)
for i in range(0, 10):
print(ans[i], end = '') | f = open('13.txt', 'r')
sum = 0
while 1:
num = 0
line = f.readline()
if line:
line = line.strip('\n')
for i in range(0, len(line)):
num = num * 10 + int(line[i])
sum += num
else:
break
ans = str(sum)
for i in range(0, 10):
print(ans[i], end='') |
def from_file(input, output, fasta, fai):
"""
Args:
input - A 23andme data file,
output - Output VCF file,
fasta - An uncompressed reference genome GRCh37 fasta file
fai - The fasta index for for the reference
"""
args = {
'input': input,
'ou... | def from_file(input, output, fasta, fai):
"""
Args:
input - A 23andme data file,
output - Output VCF file,
fasta - An uncompressed reference genome GRCh37 fasta file
fai - The fasta index for for the reference
"""
args = {'input': input, 'output': output, 'fasta': fasta,... |
#!/usr/bin/env python3
def string_to_max_list(s):
"""Given an input string, convert it to a descendant list of numbers
from the length of the string down to 0"""
out_list = list(range(len(s) - 1, -1, -1))
return out_list
def string_to_min_list(s):
out_list = list(range(len(s)))
out... | def string_to_max_list(s):
"""Given an input string, convert it to a descendant list of numbers
from the length of the string down to 0"""
out_list = list(range(len(s) - 1, -1, -1))
return out_list
def string_to_min_list(s):
out_list = list(range(len(s)))
(out_list[0], out_list[1]) = (out_list[... |
def getNewAddress():
pass
def pushRawP2PKHTxn():
pass
def pushRawP2SHTxn():
pass
def pushRawBareP2WPKHTxn():
pass
def pushRawBareP2WSHTxn():
pass
def pushRawP2SH_P2WPKHTxn():
pass
def pushRawP2SH_P2WSHTxn():
pass
def getSignedTxn():
pass
| def get_new_address():
pass
def push_raw_p2_pkh_txn():
pass
def push_raw_p2_sh_txn():
pass
def push_raw_bare_p2_wpkh_txn():
pass
def push_raw_bare_p2_wsh_txn():
pass
def push_raw_p2_sh_p2_wpkh_txn():
pass
def push_raw_p2_sh_p2_wsh_txn():
pass
def get_signed_txn():
pass |
def nextPermutation(nums: list[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
def reverse(nums, left, right):
while left < right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
if not nums:
... | def next_permutation(nums: list[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
def reverse(nums, left, right):
while left < right:
(nums[left], nums[right]) = (nums[right], nums[left])
left += 1
right -= 1
if not nums:
... |
"""
Mercedes Me APIs
Author: G. Ravera
For more details about this component, please refer to the documentation at
https://github.com/xraver/mercedes_me_api/
"""
# Software Name & Version
NAME = "Mercedes Me API"
DOMAIN = "mercedesmeapi"
VERSION = "0.8"
# Software Parameters
TOKEN_FILE = ".mercedesme_token"
CREDENTIA... | """
Mercedes Me APIs
Author: G. Ravera
For more details about this component, please refer to the documentation at
https://github.com/xraver/mercedes_me_api/
"""
name = 'Mercedes Me API'
domain = 'mercedesmeapi'
version = '0.8'
token_file = '.mercedesme_token'
credentials_file = '.mercedesme_credentials'
resources_fi... |
# -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-29 15:17
albert_models_google = {
'albert_base_zh': 'https://storage.googleapis.com/albert_models/albert_base_zh.tar.gz',
'albert_large_zh': 'https://storage.googleapis.com/albert_models/albert_large_zh.tar.gz',
'albert_xlarge_zh': 'https://storage.go... | albert_models_google = {'albert_base_zh': 'https://storage.googleapis.com/albert_models/albert_base_zh.tar.gz', 'albert_large_zh': 'https://storage.googleapis.com/albert_models/albert_large_zh.tar.gz', 'albert_xlarge_zh': 'https://storage.googleapis.com/albert_models/albert_xlarge_zh.tar.gz', 'albert_xxlarge_zh': 'http... |
class Solution(object):
def getMoneyAmount(self, n):
"""
:type n: int
:rtype: int
"""
cache = [[0] * (n + 1) for _ in xrange(n + 1)]
def dc(cache, start, end):
if start >= end:
return 0
if cache[start][end] != 0:
... | class Solution(object):
def get_money_amount(self, n):
"""
:type n: int
:rtype: int
"""
cache = [[0] * (n + 1) for _ in xrange(n + 1)]
def dc(cache, start, end):
if start >= end:
return 0
if cache[start][end] != 0:
... |
AWR_CONFIGS = {
"Ant-v2":
{
"actor_net_layers": [128, 64],
"actor_stepsize": 0.00005,
"actor_momentum": 0.9,
"actor_init_output_scale": 0.01,
"actor_batch_size": 256,
"actor_steps": 1000,
"action_std": 0.2,
"critic_net_layers": [128, 64],
... | awr_configs = {'Ant-v2': {'actor_net_layers': [128, 64], 'actor_stepsize': 5e-05, 'actor_momentum': 0.9, 'actor_init_output_scale': 0.01, 'actor_batch_size': 256, 'actor_steps': 1000, 'action_std': 0.2, 'critic_net_layers': [128, 64], 'critic_stepsize': 0.01, 'critic_momentum': 0.9, 'critic_batch_size': 256, 'critic_st... |
"""
Custom exceptions for runpandas
"""
class InvalidFileError(Exception):
def __init__(self, msg):
message = "It doesn't like a valid %s file!" % (msg)
super().__init__(message)
class RequiredColumnError(Exception):
def __init__(self, column, cls=None):
if cls is None:
... | """
Custom exceptions for runpandas
"""
class Invalidfileerror(Exception):
def __init__(self, msg):
message = "It doesn't like a valid %s file!" % msg
super().__init__(message)
class Requiredcolumnerror(Exception):
def __init__(self, column, cls=None):
if cls is None:
me... |
class MonoMacPackage (Package):
def __init__ (self):
self.pkgconfig_version = '1.0'
self.maccore_tag = '0b71453'
self.maccore_source_dir_name = 'mono-maccore-0b71453'
self.monomac_tag = 'ae428c7'
self.monomac_source_dir_name = 'mono-monomac-ae428c7'
Package.__init__ (self, 'monomac', self.monomac_tag)
... | class Monomacpackage(Package):
def __init__(self):
self.pkgconfig_version = '1.0'
self.maccore_tag = '0b71453'
self.maccore_source_dir_name = 'mono-maccore-0b71453'
self.monomac_tag = 'ae428c7'
self.monomac_source_dir_name = 'mono-monomac-ae428c7'
Package.__init__(se... |
# flake8: noqa
# Disable all security
c.NotebookApp.token = ""
c.NotebookApp.password = ""
c.NotebookApp.open_browser = True
c.NotebookApp.ip = "localhost"
| c.NotebookApp.token = ''
c.NotebookApp.password = ''
c.NotebookApp.open_browser = True
c.NotebookApp.ip = 'localhost' |
"""STATES"""
ON = "ON"
OFF = "OFF"
| """STATES"""
on = 'ON'
off = 'OFF' |
"""Message type identifiers for Connections."""
MESSAGE_FAMILY = "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/credential-issuance/0.1"
CREDENTIAL_OFFER = f"{MESSAGE_FAMILY}/credential-offer"
CREDENTIAL_REQUEST = f"{MESSAGE_FAMILY}/credential-request"
CREDENTIAL_ISSUE = f"{MESSAGE_FAMILY}/credential-issue"
MESSAGE_TYPES = {
... | """Message type identifiers for Connections."""
message_family = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/credential-issuance/0.1'
credential_offer = f'{MESSAGE_FAMILY}/credential-offer'
credential_request = f'{MESSAGE_FAMILY}/credential-request'
credential_issue = f'{MESSAGE_FAMILY}/credential-issue'
message_types = {CRED... |
# -*- coding: utf-8 -*-
def comp_mass_magnets(self):
"""Compute the mass of the hole magnets
Parameters
----------
self : HoleM50
A HoleM50 object
Returns
-------
Mmag: float
mass of the 2 Magnets [kg]
"""
M = 0
# magnet_0 and magnet_1 can have different mat... | def comp_mass_magnets(self):
"""Compute the mass of the hole magnets
Parameters
----------
self : HoleM50
A HoleM50 object
Returns
-------
Mmag: float
mass of the 2 Magnets [kg]
"""
m = 0
if self.magnet_0:
m += self.H3 * self.W4 * self.magnet_0.Lmag * s... |
A, B = map(int, input().split())
if A > 8 or B > 8:
print(":(")
else:
print("Yay!") | (a, b) = map(int, input().split())
if A > 8 or B > 8:
print(':(')
else:
print('Yay!') |
class PointObject(RhinoObject):
# no doc
def DuplicatePointGeometry(self):
""" DuplicatePointGeometry(self: PointObject) -> Point """
pass
PointGeometry = property(
lambda self: object(), lambda self, v: None, lambda self: None
)
"""Get: PointGeometry(self: PointObj... | class Pointobject(RhinoObject):
def duplicate_point_geometry(self):
""" DuplicatePointGeometry(self: PointObject) -> Point """
pass
point_geometry = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Get: PointGeometry(self: PointObject) -> Point\n\n\n\n' |
# Copyright 2021 Jake Arkinstall
#
# Work based on efforts copyrighted 2018 The Bazel 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
#
# http://www.apache.org/licenses/LICENSE-2... | load('//toolchain/internal:common.bzl', _python='python')
_circle_builds = {'141': struct(version='141', url='https://www.circle-lang.org/linux/build_141.tgz', sha256='90228ff369fb478bd4c0f86092725a22ec775924bdfff201cd4529ed9a969848'), '142': struct(version='142', url='https://www.circle-lang.org/linux/build_142.tgz', ... |
def add(matA,matB):
dimA = []
dimB = []
# find dimensions of arrA
a = matA
b = matB
while type(a) == list:
dimA.append(len(a))
a = a[0]
# find dimensions of arrB
while type(b) == list:
dimB.append(len(b))
b = b[0]
#is it possible to add them
if dim... | def add(matA, matB):
dim_a = []
dim_b = []
a = matA
b = matB
while type(a) == list:
dimA.append(len(a))
a = a[0]
while type(b) == list:
dimB.append(len(b))
b = b[0]
if dimA != dimB:
raise exception('dimension mismath {} != {}'.format(dimA, dimB))
n... |
# This file contains code that can be used later which cannot fit in right now.
'''This is the function to run 'map'. This is paused so that PyCUDA can support dynamic parallelism.
if stmt.count('map') > 0:
self.kernel_final.append(kernel+"}")
start = stmt.index('map') + 2
declar = self.device_py[self.devi... | """This is the function to run 'map'. This is paused so that PyCUDA can support dynamic parallelism.
if stmt.count('map') > 0:
self.kernel_final.append(kernel+"}")
start = stmt.index('map') + 2
declar = self.device_py[self.device_func_name.index(stmt[start])]
print declar, stmt
caller = stmt[start+1:-... |
"""
Code implementing standard data types.
Can depend on core and calc, and no other Sauronlab packages.
"""
| """
Code implementing standard data types.
Can depend on core and calc, and no other Sauronlab packages.
""" |
class Solution(object):
def calculateMinimumHP(self, dungeon):
"""
:type dungeon: List[List[int]]
:rtype: int
"""
if not dungeon:
return 0
N = len(dungeon)
M = len(dungeon[0])
matrix = []
for i in range(N):
row = [0] * M... | class Solution(object):
def calculate_minimum_hp(self, dungeon):
"""
:type dungeon: List[List[int]]
:rtype: int
"""
if not dungeon:
return 0
n = len(dungeon)
m = len(dungeon[0])
matrix = []
for i in range(N):
row = [0] ... |
# Copyright 2017 Rice University
#
# 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 applicable law or agreed to in writin... | class Retreversemapper:
def __init__(self, vocab):
self.vocab = vocab
self.ret_type = []
self.num_data = 0
return
def add_data(self, ret_type):
self.ret_type.extend(ret_type)
self.num_data += len(ret_type)
def get_element(self, id):
return self.ret_... |
names = []
children = []
with open("day7.txt") as f:
for line in f.readlines():
data = line.split('->')
names.append(data[0].split(" ")[0])
if len(data) == 2:
[x.strip() for x in data[1].split(',')]
children.append([x.strip() for x in data[1].split(',')])
children = [... | names = []
children = []
with open('day7.txt') as f:
for line in f.readlines():
data = line.split('->')
names.append(data[0].split(' ')[0])
if len(data) == 2:
[x.strip() for x in data[1].split(',')]
children.append([x.strip() for x in data[1].split(',')])
children = [... |
# Implementation of EA
def gcd(p, q):
while q != 0:
(p, q) = (q, p % q)
return p
# Implementation of the EEA
def extgcd(r0, r1):
u, v, s, t = 1, 0, 0, 1
# Swap arguments if r1 is smaller
if r1 < r0:
temp = r1
r1 = r0
r0 = temp
# While Loop to cumpute params
w... | def gcd(p, q):
while q != 0:
(p, q) = (q, p % q)
return p
def extgcd(r0, r1):
(u, v, s, t) = (1, 0, 0, 1)
if r1 < r0:
temp = r1
r1 = r0
r0 = temp
while r1 != 0:
q = r0 // r1
(r0, r1) = (r1, r0 - q * r1)
(u, s) = (s, u - q * s)
(v, t) =... |
year=int(input("Enter any year to check for leap year: "))
if year%4==0:
if year%100==0:
if year%400==0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0}... | year = int(input('Enter any year to check for leap year: '))
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print('{0} is a leap year'.format(year))
else:
print('{0} is not a leap year'.format(year))
else:
print('{0} is a leap year'.format(year))
else:
... |
s = input().strip()
while(s != '0'):
tam = len(s)
i = 1
anagrama = 1
while(i <= tam):
anagrama = anagrama * i
i = i + 1
print(anagrama)
s = input().strip() | s = input().strip()
while s != '0':
tam = len(s)
i = 1
anagrama = 1
while i <= tam:
anagrama = anagrama * i
i = i + 1
print(anagrama)
s = input().strip() |
#
# @lc app=leetcode.cn id=1587 lang=python3
#
# [1587] parallel-courses-ii
#
None
# @lc code=end | None |
class Solution:
def findComplement(self, num: int) -> int:
num = bin(num)[2:]
ans = ''
for i in num:
if i == "1":
ans += '0'
else:
ans += '1'
ans = int(ans, 2)
return ans | class Solution:
def find_complement(self, num: int) -> int:
num = bin(num)[2:]
ans = ''
for i in num:
if i == '1':
ans += '0'
else:
ans += '1'
ans = int(ans, 2)
return ans |
#
# PySNMP MIB module AT-PIM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AT-PIM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:30:27 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, 09:... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, value_range_constraint, constraints_intersection, constraints_union) ... |
def create_phone_number(n):
return (f'({n[0]}{n[1]}{n[2]}) {n[3]}{n[4]}{n[5]}-{n[6]}{n[7]}{n[8]}{n[9]}')
# Best Practices
def create_phone_number(n):
print ("({}{}{}) {}{}{}-{}{}{}{}".format(*n))
| def create_phone_number(n):
return f'({n[0]}{n[1]}{n[2]}) {n[3]}{n[4]}{n[5]}-{n[6]}{n[7]}{n[8]}{n[9]}'
def create_phone_number(n):
print('({}{}{}) {}{}{}-{}{}{}{}'.format(*n)) |
class Class:
def __init__(self, name):
self.name = name
self.fields = []
def __str__(self):
lines = ['class %s:' % self.name]
if not self.fields:
lines.append(' pass')
else:
lines.append(' def __init__(self):')
for f in self.fields:
... | class Class:
def __init__(self, name):
self.name = name
self.fields = []
def __str__(self):
lines = ['class %s:' % self.name]
if not self.fields:
lines.append(' pass')
else:
lines.append(' def __init__(self):')
for f in self.fields:... |
class LCS:
def __init__(self,str1,str2):
self.str1=str1
self.str2=str2
self.m=len(str1)
self.n=len(str2)
self.dp = [[0 for x in range(self.n + 1)] for x in range(self.m + 1)]
def lcs_length(self):
for i in range(self.m):
for j in range(self... | class Lcs:
def __init__(self, str1, str2):
self.str1 = str1
self.str2 = str2
self.m = len(str1)
self.n = len(str2)
self.dp = [[0 for x in range(self.n + 1)] for x in range(self.m + 1)]
def lcs_length(self):
for i in range(self.m):
for j in range(self... |
# Copyright (c) 2014 Eventbrite, Inc. All rights reserved.
# See "LICENSE" file for license.
"""These functions should be made available via cs2mako in the Mako context"""
def include(clearsilver_name):
"""loads clearsilver file and returns a rendered mako file"""
pass
# need to put whatever ported clearsil... | """These functions should be made available via cs2mako in the Mako context"""
def include(clearsilver_name):
"""loads clearsilver file and returns a rendered mako file"""
pass |
################################################################################
##
## This library is free software; you can redistribute it and/or
## modify it under the terms of the GNU Lesser General Public
## License as published by the Free Software Foundation; either
## version 2.1 of the License, or (at your op... | class Stream:
def __init__(self):
self.lines = []
def write(self, line):
self.lines.append(line)
class Bufferasfile:
def __init__(self, lines):
self.lines = lines
def readlines(self):
return self.lines |
parties = []
class Political():
@staticmethod
def exists(name):
"""
Checks if a party with the same name exists
Returns a boolean
"""
for party in parties:
if party["name"] == name:
return True
return False
def create_political_... | parties = []
class Political:
@staticmethod
def exists(name):
"""
Checks if a party with the same name exists
Returns a boolean
"""
for party in parties:
if party['name'] == name:
return True
return False
def create_political_par... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 16 11:05:36 2021
@author: Olli Nevalainen (Finnish Meteorological Institute)
"""
| """
Created on Tue Mar 16 11:05:36 2021
@author: Olli Nevalainen (Finnish Meteorological Institute)
""" |
# Copyright (c) 2019 The Bazel Utils Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
load("//:conditions.bzl", "if_windows")
load("//:warnings.bzl", "default_warnings")
#################################################################... | load('//:conditions.bzl', 'if_windows')
load('//:warnings.bzl', 'default_warnings')
def safest_code_copts():
return select({'@com_chokobole_bazel_utils//:windows': ['/W4'], '@com_chokobole_bazel_utils//:clang_or_clang_cl': ['-Wextra'], '//conditions:default': ['-Wall', '-Werror']}) + default_warnings()
def safer_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.