content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class VaderStreamsConstants(object):
__slots__ = []
BASE_URL = 'http://vapi.vaders.tv/'
CATEGORIES_JSON_FILE_NAME = 'categories.json'
CATEGORIES_PATH = 'epg/categories'
CHANNELS_JSON_FILE_NAME = 'channels.json'
CHANNELS_PATH = 'epg/channels'
DB_FILE_NAME = 'vaderstreams.db'
DEFAULT_EPG_... | class Vaderstreamsconstants(object):
__slots__ = []
base_url = 'http://vapi.vaders.tv/'
categories_json_file_name = 'categories.json'
categories_path = 'epg/categories'
channels_json_file_name = 'channels.json'
channels_path = 'epg/channels'
db_file_name = 'vaderstreams.db'
default_epg_s... |
class Vector:
def __init__(self, inputs: list):
self.inputs = inputs
def dot(self, weigths):
dot_product = 0
for index in range(len(self.inputs)):
dot_product = dot_product + (self.inputs[index] * weigths.inputs[index])
return dot_product | class Vector:
def __init__(self, inputs: list):
self.inputs = inputs
def dot(self, weigths):
dot_product = 0
for index in range(len(self.inputs)):
dot_product = dot_product + self.inputs[index] * weigths.inputs[index]
return dot_product |
dependency_matcher_patterns = {
"pattern_parameter_adverbial_clause": [
{"RIGHT_ID": "action_head", "RIGHT_ATTRS": {"POS": "VERB"}},
{
"LEFT_ID": "action_head",
"REL_OP": ">",
"RIGHT_ID": "condition_head",
"RIGHT_ATTRS": {"DEP": "advcl"},
},
... | dependency_matcher_patterns = {'pattern_parameter_adverbial_clause': [{'RIGHT_ID': 'action_head', 'RIGHT_ATTRS': {'POS': 'VERB'}}, {'LEFT_ID': 'action_head', 'REL_OP': '>', 'RIGHT_ID': 'condition_head', 'RIGHT_ATTRS': {'DEP': 'advcl'}}, {'LEFT_ID': 'condition_head', 'REL_OP': '>', 'RIGHT_ID': 'dependee_param', 'RIGHT_A... |
PAGE_ITEM_LIMIT = 10
RSS_ITEM_LIMIT = 10
OUTPUT_DIRECTORY = ""
| page_item_limit = 10
rss_item_limit = 10
output_directory = '' |
"""Provides a macro to import all TensorFlow Serving dependencies.
Some of the external dependencies need to be initialized. To do this, duplicate
the initialization code from TensorFlow Serving's WORKSPACE file.
"""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def tf_serving_workspace():
... | """Provides a macro to import all TensorFlow Serving dependencies.
Some of the external dependencies need to be initialized. To do this, duplicate
the initialization code from TensorFlow Serving's WORKSPACE file.
"""
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
def tf_serving_workspace():
... |
# %%
#######################################
def match_str_len_with_padding(
string1: str, string2: str, padding="#", align=("left", "center", "right")[1]
):
"""Returns a list containing the original longer string, and the smaller string with padding.
Examples:
>>> mystring = "Complex is better tha... | def match_str_len_with_padding(string1: str, string2: str, padding='#', align=('left', 'center', 'right')[1]):
"""Returns a list containing the original longer string, and the smaller string with padding.
Examples:
>>> mystring = "Complex is better than complicated."
>>> secondstring = " blah "... |
'''
EASY 203. Remove Linked List Elements
You are given a license key represented as a string S which consists only alphanumeric character and dashes.
The string is separated into N+1 groups by N dashes.
Given a number K, we would want to reformat the strings such that each group contains exactly K characters,
exce... | """
EASY 203. Remove Linked List Elements
You are given a license key represented as a string S which consists only alphanumeric character and dashes.
The string is separated into N+1 groups by N dashes.
Given a number K, we would want to reformat the strings such that each group contains exactly K characters,
exce... |
cities = [
'Vilnius',
'Kaunas',
'Klaipeda',
'Siauliai',
'Panevezys',
'Alytus',
'Dainava (Kaunas)',
'Eiguliai',
'Marijampole',
'Mazeikiai',
'Silainiai',
'Fabijoniskes',
'Jonava',
'Utena',
'Pasilaiciai',
'Kedainiai',
'Seskine',
'Lazdynai',
'Telsi... | cities = ['Vilnius', 'Kaunas', 'Klaipeda', 'Siauliai', 'Panevezys', 'Alytus', 'Dainava (Kaunas)', 'Eiguliai', 'Marijampole', 'Mazeikiai', 'Silainiai', 'Fabijoniskes', 'Jonava', 'Utena', 'Pasilaiciai', 'Kedainiai', 'Seskine', 'Lazdynai', 'Telsiai', 'Visaginas', 'Taurage', 'Justiniskes', 'Ukmerge', 'Aleksotas', 'Plunge',... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
result = []... | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
result = []
def dfs(root):
if root == None:
result.append('null')
return
result.append(str(root.val))
... |
def add_numbers(num1, num2):
return num1 + num2
def subtract_numbers(num1, num2):
return num1 - num2
def multiply_numbers(num1, num2):
return num1 * num2
def divide_numbers(num1, num2):
return num1 / num2
| def add_numbers(num1, num2):
return num1 + num2
def subtract_numbers(num1, num2):
return num1 - num2
def multiply_numbers(num1, num2):
return num1 * num2
def divide_numbers(num1, num2):
return num1 / num2 |
REQUEST_DELETE_CONTENT_RANGE = 'deleteContentRange'
REQUEST_DELETE_TABLE_ROW = 'deleteTableRow'
REQUEST_INSERT_TABLE = 'insertTable'
REQUEST_INSERT_TABLE_ROW = 'insertTableRow'
REQUEST_INSERT_TEXT = 'insertText'
REQUEST_MERGE_TABLE_CELLS = 'mergeTableCells'
REQUEST_UPDATE_TEXT_STYLE = 'updateTextStyle'
BODY = 'body'
... | request_delete_content_range = 'deleteContentRange'
request_delete_table_row = 'deleteTableRow'
request_insert_table = 'insertTable'
request_insert_table_row = 'insertTableRow'
request_insert_text = 'insertText'
request_merge_table_cells = 'mergeTableCells'
request_update_text_style = 'updateTextStyle'
body = 'body'
bo... |
sum = lambda a,b : a + b
print("suma: "+ str(sum(1,2)))
# Map lambdas
names = ["Christian", "yamile", "Anddy", "Lucero", "Evelyn"]
names = map(lambda name:name.upper(),names)
print(list(names))
def decrement_list (*vargs):
return list(map(lambda number: number - 1,vargs))
print(decrement_list(1,2,3))
#all
... | sum = lambda a, b: a + b
print('suma: ' + str(sum(1, 2)))
names = ['Christian', 'yamile', 'Anddy', 'Lucero', 'Evelyn']
names = map(lambda name: name.upper(), names)
print(list(names))
def decrement_list(*vargs):
return list(map(lambda number: number - 1, vargs))
print(decrement_list(1, 2, 3))
def is_all_strings(l... |
""" This file is create and managed by Tahir Iqbal
----------------------------------------------
It can be use only for education purpose
"""
# List Modification
mix_list = [1, 'Programmer', 5.0, True]
print(mix_list)
# Mutable : Because re-assign value
mix_list[0] = 2
print(mix_list)
# Adding item in li... | """ This file is create and managed by Tahir Iqbal
----------------------------------------------
It can be use only for education purpose
"""
mix_list = [1, 'Programmer', 5.0, True]
print(mix_list)
mix_list[0] = 2
print(mix_list)
mix_list.append('Python')
print(mix_list)
mix_list += ['Solo']
print(mix_list)... |
"""
ED Data imports exception types
"""
class FieldsValidationError(Exception):
"""
Exception type for validation errors related to
DataModel instances.
"""
pass
class UnexpectedQueryResult(Exception):
"""
Exception for unexpected database results.
"""
pass
class NoResultsError(Un... | """
ED Data imports exception types
"""
class Fieldsvalidationerror(Exception):
"""
Exception type for validation errors related to
DataModel instances.
"""
pass
class Unexpectedqueryresult(Exception):
"""
Exception for unexpected database results.
"""
pass
class Noresultserror(Un... |
def author_picture():
author_picture_list = [
"https://edu-test-1255999742.file.myqcloud.com/portrait/20190524/"
"2ca50ff2ca024a75a893b80257458104.jpg",
"https://edu-test-1255999742.file.myqcloud.com/portrait/20190524/"
"f3b24a5e1d534ba49b36f4ac36ce4f09.jpg",
"https://edu-tes... | def author_picture():
author_picture_list = ['https://edu-test-1255999742.file.myqcloud.com/portrait/20190524/2ca50ff2ca024a75a893b80257458104.jpg', 'https://edu-test-1255999742.file.myqcloud.com/portrait/20190524/f3b24a5e1d534ba49b36f4ac36ce4f09.jpg', 'https://edu-test-1255999742.file.myqcloud.com/portrait/2019052... |
# python3 theory/conditionals.py
def plus(a, b):
if type(a) is int or type(a) is float:
if type(b) is int or type(b) is float:
return a + b
else:
return None
else:
return None
print(plus(1, '10'))
def can_drink(age):
print(f"You are {age} years old.")
if age < 18:
print("You ca... | def plus(a, b):
if type(a) is int or type(a) is float:
if type(b) is int or type(b) is float:
return a + b
else:
return None
else:
return None
print(plus(1, '10'))
def can_drink(age):
print(f'You are {age} years old.')
if age < 18:
print("You can'... |
def os_return(distro):
if distro == 'rhel':
return_value = {
'distribution': 'centos',
'version': '7.5',
'dist_name': 'CentOS Linux',
'based_on': 'rhel'
}
elif distro == 'ubuntu':
return_value = {
'distribution': 'ec2',
... | def os_return(distro):
if distro == 'rhel':
return_value = {'distribution': 'centos', 'version': '7.5', 'dist_name': 'CentOS Linux', 'based_on': 'rhel'}
elif distro == 'ubuntu':
return_value = {'distribution': 'ec2', 'version': '16.04', 'dist_name': 'Ubuntu', 'based_on': 'debian'}
elif distr... |
"""Return list of values that are multiplies of x."""
def count_by(x, n):
"""Return a sequence of numbers counting by `x` `n` times."""
return [i * x for i in range(1, n + 1)]
| """Return list of values that are multiplies of x."""
def count_by(x, n):
"""Return a sequence of numbers counting by `x` `n` times."""
return [i * x for i in range(1, n + 1)] |
class NoGloveValueError(Exception):
"""
Raised if no value can be found in GloVe for a user's text.
"""
pass
| class Noglovevalueerror(Exception):
"""
Raised if no value can be found in GloVe for a user's text.
"""
pass |
class Config:
@staticmethod
def get(repo, config_key):
splitted_keys = config_key.split('.')
splitted_keys_in_byte = [key.encode() for key in splitted_keys]
if splitted_keys.__len__() > 2:
section = tuple(splitted_keys_in_byte[:-1])
arg = splitted_keys_in_byte[-1]
else:
se... | class Config:
@staticmethod
def get(repo, config_key):
splitted_keys = config_key.split('.')
splitted_keys_in_byte = [key.encode() for key in splitted_keys]
if splitted_keys.__len__() > 2:
section = tuple(splitted_keys_in_byte[:-1])
arg = splitted_keys_in_byte[-1... |
path = 'home/sample.mp4'
akhil = []
akhil = path.split(".")
video = akhil[0].split("/")
print(video[len(video)-1]) | path = 'home/sample.mp4'
akhil = []
akhil = path.split('.')
video = akhil[0].split('/')
print(video[len(video) - 1]) |
def converteHora(hora):
# Se a hora for 00:
if int(hora[:2]) == 0:
return f"12{hora[2:]} AM"
# Se for 12
if int(hora[:2]) == 12:
return f"12{hora[2:]} PM"
# Se for de tarde
if int(hora[:2]) > 12:
return f"0{int(hora[:2]) - 12 }{hora[2:]} PM"
return f"{hora} AM"
print(converteHora(... | def converte_hora(hora):
if int(hora[:2]) == 0:
return f'12{hora[2:]} AM'
if int(hora[:2]) == 12:
return f'12{hora[2:]} PM'
if int(hora[:2]) > 12:
return f'0{int(hora[:2]) - 12}{hora[2:]} PM'
return f'{hora} AM'
print(converte_hora('09:39')) |
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'includes': [
'../../build/common.gypi',
],
'targets': [
{
'target_name': 'libpng',
'type': '<(library)',
'dependencies... | {'includes': ['../../build/common.gypi'], 'targets': [{'target_name': 'libpng', 'type': '<(library)', 'dependencies': ['../zlib/zlib.gyp:zlib'], 'defines': ['CHROME_PNG_WRITE_SUPPORT', 'PNG_USER_CONFIG'], 'msvs_guid': 'C564F145-9172-42C3-BFCB-6014CA97DBCD', 'sources': ['png.c', 'png.h', 'pngconf.h', 'pngerror.c', 'pngg... |
#
# PySNMP MIB module HPN-ICF-FC-PSM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-FC-PSM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:38:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_size_constraint, single_value_constraint, constraints_intersection, value_range_constraint) ... |
print('=-'*25)
print(f'{"Sequencia de fibonacci": ^50}')
print('=-'*25, '\n')
termos = int(input('Quantos termos voce quer mostrar: '))
controle = 0
fibonacci = 0
n1 = 0
n2 = 1
print(n1, '->', n2, end=' -> ')
while controle != termos - 2:
controle += 1
fibonacci = n1 + n2
n1 = n2
n2 = fibonacci
p... | print('=-' * 25)
print(f"{'Sequencia de fibonacci': ^50}")
print('=-' * 25, '\n')
termos = int(input('Quantos termos voce quer mostrar: '))
controle = 0
fibonacci = 0
n1 = 0
n2 = 1
print(n1, '->', n2, end=' -> ')
while controle != termos - 2:
controle += 1
fibonacci = n1 + n2
n1 = n2
n2 = fibonacci
... |
def count_and_say(palavra):
dicionario = {}
palavra = palavra.replace(' ', '')
for letra in palavra:
if not letra in dicionario.keys():
dicionario[letra] = 1
else:
dicionario[letra] += 1
retorno = ''
for letra, quantidade in dicionario.items(... | def count_and_say(palavra):
dicionario = {}
palavra = palavra.replace(' ', '')
for letra in palavra:
if not letra in dicionario.keys():
dicionario[letra] = 1
else:
dicionario[letra] += 1
retorno = ''
for (letra, quantidade) in dicionario.items():
retor... |
# https://www.hackerrank.com/challenges/recursive-digit-sum
def super_digit(n, k):
def _compute(num):
num_str = str(num)
total = sum(map(int, num_str))
if len(str(total)) == 1:
return total
else:
return _compute(total)
# n, k = [int(x) for x in ra... | def super_digit(n, k):
def _compute(num):
num_str = str(num)
total = sum(map(int, num_str))
if len(str(total)) == 1:
return total
else:
return _compute(total)
concat = int(str(n) * k)
if len(str(concat)) == 1:
return concat
else:
r... |
# Copyright 2018 Google LLC
#
# 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 writing, ... | """Errors used by the Google Ads API library."""
class Googleadsexception(Exception):
"""Exception thrown in response to an API error from GoogleAds servers."""
def __init__(self, error, call, failure, request_id):
"""Initializer.
Args:
error: the grpc.RpcError raised by an rpc ca... |
def remove_char(str,n):
first_part = str[:n]
last_part = str[n+1:]
return first_part + last_part
def unify(E1, E2):
E1_Variable = E1[0].isupper()
E2_Variable = E2[0].isupper()
SUBSET = ""
if not E1_Variable and not E2_Variable or(len(E1) == 0 and len(E2) == 0):
if E1[0] == E2[0]:
... | def remove_char(str, n):
first_part = str[:n]
last_part = str[n + 1:]
return first_part + last_part
def unify(E1, E2):
e1__variable = E1[0].isupper()
e2__variable = E2[0].isupper()
subset = ''
if not E1_Variable and (not E2_Variable) or (len(E1) == 0 and len(E2) == 0):
if E1[0] == E... |
# Create a script that has:
#a function accept a list of grades (i.e. [99, 88, 77])
#and returns a grading report for that list.
# Data
# List of Integers
# blank_list = []
# grades = [99, 75, 89, 45, 68, 94, 87, 86, 80]
# Conditional logic
# A >= 90
# B < 90 and B >= 80
# C < 80 and C >= 70
# D < 70 and D >= 60
... | def scorer(scores):
class_scores = {'A': 0, 'B': 0, 'C': 0, 'D': 0, 'F': 0}
for grade in scores:
if grade >= 90:
print(f'{grade} is an A!')
print(str(grade) + ' is an A!')
class_scores['A'] += 1
elif grade >= 80:
print(f'{grade} is a B!')
... |
def titulo(txt):
print('-' * 35)
print(f'{txt:^35}')
print('-' * 35)
| def titulo(txt):
print('-' * 35)
print(f'{txt:^35}')
print('-' * 35) |
def make_shirt(size='Large', message='I love Python'):
print(f"The size of the shirt is {size} and the message is {message}")
make_shirt()
make_shirt('m')
make_shirt('xs', "I'm okay")
| def make_shirt(size='Large', message='I love Python'):
print(f'The size of the shirt is {size} and the message is {message}')
make_shirt()
make_shirt('m')
make_shirt('xs', "I'm okay") |
def fib(n):
'''Takes in a number n, and returns the nth fibonacci number, starting with: 1, 1, 2, 3, 5,...'''
if n<=1:
return n
else:
f = [0, 1]
for i in range(2,n+1):
f.append(f[i-1] + f[i-2])
return f[n]
| def fib(n):
"""Takes in a number n, and returns the nth fibonacci number, starting with: 1, 1, 2, 3, 5,..."""
if n <= 1:
return n
else:
f = [0, 1]
for i in range(2, n + 1):
f.append(f[i - 1] + f[i - 2])
return f[n] |
# Created by MechAviv
# Map ID :: 940011080
# Western Region of Pantheon : Heliseum Hideout
# [SET_DRESS_CHANGED] [00 00 ]
sm.curNodeEventEnd(True)
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(True, True, False, False)
sm.forcedInput(0)
sm.forcedInput(2)
sm.sendDelay(60)
sm.forcedInput(0)
sm.setSpeakerID(0)
... | sm.curNodeEventEnd(True)
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(True, True, False, False)
sm.forcedInput(0)
sm.forcedInput(2)
sm.sendDelay(60)
sm.forcedInput(0)
sm.setSpeakerID(0)
sm.removeEscapeButton()
sm.flipDialoguePlayerAsSpeaker()
sm.setSpeakerType(3)
sm.sendNext('What am I gonna do?! Maybe I can ju... |
class Solution:
# @param root, a tree link node
# @return nothing
def connect(self, root):
if not root or (not root.left and not root.right):
return root
strut = dict()
level_0 = [root]
lv = 0
strut[lv] = level_0
is_last_level = False
... | class Solution:
def connect(self, root):
if not root or (not root.left and (not root.right)):
return root
strut = dict()
level_0 = [root]
lv = 0
strut[lv] = level_0
is_last_level = False
while not is_last_level:
new_level = []
... |
class Solution:
def partition(self, s: str) -> List[List[str]]:
res=[]
self.helper(res,s,[])
return res
def helper(self,res,s,path):
if not s:
res.append(path)
return
for i in range(1,len(s)+1):
if self.check(s[:i])==True:
... | class Solution:
def partition(self, s: str) -> List[List[str]]:
res = []
self.helper(res, s, [])
return res
def helper(self, res, s, path):
if not s:
res.append(path)
return
for i in range(1, len(s) + 1):
if self.check(s[:i]) == True:... |
#entrada
nFuncionarios = int(input())
qEventos = int(input())
#processamento
mesas = []
for i in range(1, nFuncionarios + 1): #inserindo funcionarios nas mesas
mesas.append(i)
for i in range(0, qEventos):
entrada = str(input()).split()
eTipo = int(entrada[0])
a = int(entrada[1])
if eTipo == 1: #up... | n_funcionarios = int(input())
q_eventos = int(input())
mesas = []
for i in range(1, nFuncionarios + 1):
mesas.append(i)
for i in range(0, qEventos):
entrada = str(input()).split()
e_tipo = int(entrada[0])
a = int(entrada[1])
if eTipo == 1:
b = int(entrada[2])
aux = mesas.index(b)
... |
#58: Next Day
a=input("Enter the date:")
b=[1,3,5,7,8,10,12]
c=[4,6,9,11]
d=a.split('-')
year=int(d[0])
month=int(d[1])
date=int(d[2])
if year%400==0:
x=True
elif year%100==0:
x=False
elif year%4==0:
x=True
else:
x=False
if 1<=month<=12 and 1<=date<=31:
if month in b:
date+... | a = input('Enter the date:')
b = [1, 3, 5, 7, 8, 10, 12]
c = [4, 6, 9, 11]
d = a.split('-')
year = int(d[0])
month = int(d[1])
date = int(d[2])
if year % 400 == 0:
x = True
elif year % 100 == 0:
x = False
elif year % 4 == 0:
x = True
else:
x = False
if 1 <= month <= 12 and 1 <= date <= 31:
if month ... |
class Solution(object):
def checkSubarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
remainders = {0:-1}
subSum = 0
for i, ni in enumerate(nums):
subSum += ni
if k != 0:
subSum %= ... | class Solution(object):
def check_subarray_sum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
remainders = {0: -1}
sub_sum = 0
for (i, ni) in enumerate(nums):
sub_sum += ni
if k != 0:
su... |
def get_soundex(token):
temp=''
token=token.upper()
temp+=token[0]
dic={'BFPV':1,'CGJKQSXZ':2,'DT':3,'L':4,'MN':5,'R':6,'AEIOUYHW':''}
for char in token[1:]:
for key in dic.keys():
if char in key:
code=str(dic[key])
break
if... | def get_soundex(token):
temp = ''
token = token.upper()
temp += token[0]
dic = {'BFPV': 1, 'CGJKQSXZ': 2, 'DT': 3, 'L': 4, 'MN': 5, 'R': 6, 'AEIOUYHW': ''}
for char in token[1:]:
for key in dic.keys():
if char in key:
code = str(dic[key])
break
... |
# 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 minDepth(self, root: TreeNode) -> int:
def depth(node, x):
if node == None:
... | class Solution:
def min_depth(self, root: TreeNode) -> int:
def depth(node, x):
if node == None:
return x - 1
if node.left == None and node.right == None:
return x
l = 10 ** 5
r = 10 ** 5
if node.left != None:
... |
def longest_palin_substring(str1):
"""
dp[size][i] = dp[size-2][i+1] if str[i] == str[j]
else
dp[size][i] = False
where dp[size][i] = If substring of size `size` starting at index `i` is palindrome or not.
Answer = max of all (j-i+1) where dp[i][j] is True.
"""
str_len = len(str1)
is... | def longest_palin_substring(str1):
"""
dp[size][i] = dp[size-2][i+1] if str[i] == str[j]
else
dp[size][i] = False
where dp[size][i] = If substring of size `size` starting at index `i` is palindrome or not.
Answer = max of all (j-i+1) where dp[i][j] is True.
"""
str_len = len(str1)
is... |
#!/usr/bin/env python3
# Import data
with open('/home/agaspari/aoc2021/dec_8/dec8_input.txt') as f:
signal_list = f.read().split('\n')
unique_signals_one = {'c', 'f'}
unique_signals_four = {'b', 'c', 'd', 'f'}
unique_signals_seven = {'a', 'c', 'f'}
unique_signals_eight = {'a', 'b', 'c', 'd', 'e', 'f', 'g'}
uniqu... | with open('/home/agaspari/aoc2021/dec_8/dec8_input.txt') as f:
signal_list = f.read().split('\n')
unique_signals_one = {'c', 'f'}
unique_signals_four = {'b', 'c', 'd', 'f'}
unique_signals_seven = {'a', 'c', 'f'}
unique_signals_eight = {'a', 'b', 'c', 'd', 'e', 'f', 'g'}
unique_signals = [unique_signals_one, unique_... |
x = 1 + 2 * 3 - 3 ** 5 / 2
y = 3 ** 5 - 2
z = x / y
zz = x // y
z -= z
zz += zz
xx = -x
xx %= 10
if type(x) is int:
print(x and y)
| x = 1 + 2 * 3 - 3 ** 5 / 2
y = 3 ** 5 - 2
z = x / y
zz = x // y
z -= z
zz += zz
xx = -x
xx %= 10
if type(x) is int:
print(x and y) |
"""
bender_mc.utils
~~~~~~~~~~~~~~~
Utility tools for bender-mc.
"""
# :copyright: (c) 2020 by Nicholas Repole.
# :license: MIT - See LICENSE for more details.
def deformat_title(formatted_title):
return formatted_title.replace(
"__COLON__", ":").replace(
"__DOT__", ".").replace(
... | """
bender_mc.utils
~~~~~~~~~~~~~~~
Utility tools for bender-mc.
"""
def deformat_title(formatted_title):
return formatted_title.replace('__COLON__', ':').replace('__DOT__', '.').replace('__DASH__', '-').replace('__SPACE__', ' ').replace('__APOSTROPHE__', "'").replace('__UNDERSCORE__', '_') |
class Queue:
qu = []
size = 0
front = 0
rear = 0
def __init__(self, size):
self.size = size
def en_queue(self, data):
self.qu.append(data)
self.size = self.size + 1
self.rear = self.rear + 1
def de_queue(self):
temp = self.qu[self.front]
del... | class Queue:
qu = []
size = 0
front = 0
rear = 0
def __init__(self, size):
self.size = size
def en_queue(self, data):
self.qu.append(data)
self.size = self.size + 1
self.rear = self.rear + 1
def de_queue(self):
temp = self.qu[self.front]
del... |
class parser(object):
def __call__(self, line):
self.rank = 0
self.in_garbage = False # if False, then we're in garbage
self.ignore = False
self.points = []
self.garbage_count = 0
for char in line:
self._inc(char)
return self.points
... | class Parser(object):
def __call__(self, line):
self.rank = 0
self.in_garbage = False
self.ignore = False
self.points = []
self.garbage_count = 0
for char in line:
self._inc(char)
return self.points
def _inc(self, char):
if self.ignor... |
# -*- coding: utf-8 -*-
"""
>>> import os
>>> import json
>>> from samila import *
>>> from pytest import warns
>>> g = GenerativeImage(lambda x,y: 0, lambda x,y: 0)
>>> g.generate(step=0.1)
>>> result = g.save_data()
>>> g_ = GenerativeImage(data=open('data.json', 'r'))
>>> g_.data1 == g.data1
True
>>> g_.data2 == g.d... | """
>>> import os
>>> import json
>>> from samila import *
>>> from pytest import warns
>>> g = GenerativeImage(lambda x,y: 0, lambda x,y: 0)
>>> g.generate(step=0.1)
>>> result = g.save_data()
>>> g_ = GenerativeImage(data=open('data.json', 'r'))
>>> g_.data1 == g.data1
True
>>> g_.data2 == g.data2
True
>>> with open(... |
"""Various functions to help deal with exceptions.
Released under the MIT license (https://opensource.org/licenses/MIT).
"""
def raises(callable, args=(), kwargs={}):
"""Check if `callable(*args, **kwargs)` raises an exception.
Returns `True` if an exception is raised, else `False`.
Arguments:
- call... | """Various functions to help deal with exceptions.
Released under the MIT license (https://opensource.org/licenses/MIT).
"""
def raises(callable, args=(), kwargs={}):
"""Check if `callable(*args, **kwargs)` raises an exception.
Returns `True` if an exception is raised, else `False`.
Arguments:
- calla... |
"""
This demonstrates the use of object properties as a way to give the illusion of private members and
getters/setters per object oriented programming. Variables prefixed by underscore are a signal to other
programmers that they should be changing them directly, but there really isn't any enforcement. There are
still... | """
This demonstrates the use of object properties as a way to give the illusion of private members and
getters/setters per object oriented programming. Variables prefixed by underscore are a signal to other
programmers that they should be changing them directly, but there really isn't any enforcement. There are
still... |
class Text():
'''text to write to console'''
def __init__(self, text, fg='black', bg='white'):
self.text = text
self.fg = fg
self.bg = bg
class Value():
'''a value for the status bar'''
def __init__(self, name, text, row=0, fg='black', bg='white'):
self.name = name
... | class Text:
"""text to write to console"""
def __init__(self, text, fg='black', bg='white'):
self.text = text
self.fg = fg
self.bg = bg
class Value:
"""a value for the status bar"""
def __init__(self, name, text, row=0, fg='black', bg='white'):
self.name = name
... |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
n=int(input())
a=*map(int,input()),
a,b=sorted(a[:n]),sorted(a[n:])
d=[1,-1][a[0]>b[0]]
print('NYOE S'[all(d*x<d*y for x,y in zip(a,b))::2]) | """
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
n = int(input())
a = (*map(int, input()),)
(a, b) = (sorted(a[:n]), sorted(a[n:]))
d = [1, -1][a[0] > b[0]]
print('NYOE S'[all((d * x < d * y for (x, y) in zip(a, b)))::2]) |
# ***********************************************************************************
# * Copyright 2010 - 2016 Paulo A. Herrera. All rights reserved *
# * *
# * Redistribution and use in source and binary forms, with or... | """Simple class to generate a well-formed XML file."""
class Xmlwriter:
"""
xml writer class.
Parameters
----------
filepath : str
Path to the xml file.
addDeclaration : bool, optional
Whether to add the declaration.
The default is True.
"""
def __init__(self, ... |
"""django-solo helps working with singletons: things like global settings that you want to edit from the admin site.
"""
__version__ = '1.0.5'
| """django-solo helps working with singletons: things like global settings that you want to edit from the admin site.
"""
__version__ = '1.0.5' |
m = int(input())
n = int(input()) + 1
for i in range(m, n, ):
if (i % 17 == 0) or (i % 10 == 9) or (i % 3 == 0 and i % 5 == 0):
print(i)
| m = int(input())
n = int(input()) + 1
for i in range(m, n):
if i % 17 == 0 or i % 10 == 9 or (i % 3 == 0 and i % 5 == 0):
print(i) |
def print_formatted(number):
binlen = len(str(bin(number))) - 2
for i in range(1, number+1):
print("{0} {1} {2} {3}".format(str(i).rjust(binlen), str(oct(i))[1:].rjust(binlen), format(i, 'x').upper().rjust(binlen), bin(i)[2:].rjust(binlen)))
| def print_formatted(number):
binlen = len(str(bin(number))) - 2
for i in range(1, number + 1):
print('{0} {1} {2} {3}'.format(str(i).rjust(binlen), str(oct(i))[1:].rjust(binlen), format(i, 'x').upper().rjust(binlen), bin(i)[2:].rjust(binlen))) |
class RequestHandler:
def __init__ (self, logger):
self.logger = logger
def log (self, message, type = "info"):
self.logger.log ("%s - %s" % (self.request.uri, message), type)
def log_info (self, message, type='info'):
self.log (message, type)
def trace (self):
self.logger.trace (self.request.uri)
... | class Requesthandler:
def __init__(self, logger):
self.logger = logger
def log(self, message, type='info'):
self.logger.log('%s - %s' % (self.request.uri, message), type)
def log_info(self, message, type='info'):
self.log(message, type)
def trace(self):
self.logger.tr... |
#
# PySNMP MIB module HH3C-LOCAL-AAA-SERVER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-LOCAL-AAA-SERVER-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:15:00 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_intersection, single_value_constraint, constraints_union, value_range_constraint) ... |
__version__ = '1.0.1'
default_app_config = (
'django_selectel_storage.apps.'
'DjangoSelectelStorageAppConfig'
)
| __version__ = '1.0.1'
default_app_config = 'django_selectel_storage.apps.DjangoSelectelStorageAppConfig' |
class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
result = []
keyb = {'a': '2', 'b': '3', 'c': '3', 'd': '2', 'e': '1', 'f': '2', 'g': '2', 'h': '2', 'i': '1', 'j': '2', 'k': '2', 'l': '2', 'm': '3', 'n': '3', 'o': '1... | class Solution(object):
def find_words(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
result = []
keyb = {'a': '2', 'b': '3', 'c': '3', 'd': '2', 'e': '1', 'f': '2', 'g': '2', 'h': '2', 'i': '1', 'j': '2', 'k': '2', 'l': '2', 'm': '3', 'n': '3', 'o': ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2016 JiNong Inc.
#
"""
Reference
* http://stackoverflow.com/questions/36932/how-can-i-represent-an-enum-in-python
"""
def enum(*sequential, **named):
"""
a function to generate enum type
"""
enums = dict(zip(sequential, ran... | """
Reference
* http://stackoverflow.com/questions/36932/how-can-i-represent-an-enum-in-python
"""
def enum(*sequential, **named):
"""
a function to generate enum type
"""
enums = dict(zip(sequential, range(len(sequential))), **named)
reverse = dict(((value, key) for (key, value) in enums.iteritems... |
XMajor = [[15, 13.333333333333334, 26.666666666666668, 46.666666666666664, 13.333333333333334, 0.0, 0.0, 0.0],[13, 15.384615384615385, 38.46153846153846, 7.6923076923076925, 15.384615384615385, 15.384615384615385, 0.0, 7.6923076923076925],[4, 25.0, 0.0, 25.0, 50.0, 0.0, 0.0, 0.0],[10, 20.0, 30.0, 0.0, 0.0, 0.0, 20.0, 3... | x_major = [[15, 13.333333333333334, 26.666666666666668, 46.666666666666664, 13.333333333333334, 0.0, 0.0, 0.0], [13, 15.384615384615385, 38.46153846153846, 7.6923076923076925, 15.384615384615385, 15.384615384615385, 0.0, 7.6923076923076925], [4, 25.0, 0.0, 25.0, 50.0, 0.0, 0.0, 0.0], [10, 20.0, 30.0, 0.0, 0.0, 0.0, 20.... |
# Define Functions
# Function that handles all litre conversions
def litreconv():
print("you have selected Litres")
conversion = int(input("input Litres to convert: "))
print(str(conversion) + " Litres")
converted = 0.21997 * conversion
print(str(round(converted, 4)) + " UK Gallons")
converted... | def litreconv():
print('you have selected Litres')
conversion = int(input('input Litres to convert: '))
print(str(conversion) + ' Litres')
converted = 0.21997 * conversion
print(str(round(converted, 4)) + ' UK Gallons')
converted = conversion / 3.785
print(str(round(converted, 4)) + 'US Gall... |
dff = data
df_sk = dff.loc[(dff['scenario']=='ND_NO_SKAVICA')|(dff['scenario']=='ND_SKAVICA')]
df_sk['scenario'].replace({"ND_NO_SKAVICA":"No Skavica", "ND_SKAVICA":"With Skavica"}, inplace=True)
df_sk1 = df_sk.loc[(df_sk['country']=='Albania')&(df_sk['tech']!='AL-Import')]
df_sk1 = df_sk1.groupby(['country','tech','y... | dff = data
df_sk = dff.loc[(dff['scenario'] == 'ND_NO_SKAVICA') | (dff['scenario'] == 'ND_SKAVICA')]
df_sk['scenario'].replace({'ND_NO_SKAVICA': 'No Skavica', 'ND_SKAVICA': 'With Skavica'}, inplace=True)
df_sk1 = df_sk.loc[(df_sk['country'] == 'Albania') & (df_sk['tech'] != 'AL-Import')]
df_sk1 = df_sk1.groupby(['count... |
"""
Module: 'functools' on LEGO EV3 v1.0.0
"""
# MCU: sysname=ev3, nodename=ev3, release=('v1.0.0',), version=('0.0.0',), machine=ev3
# Stubber: 1.3.2
def partial():
pass
def reduce():
pass
def update_wrapper():
pass
def wraps():
pass
| """
Module: 'functools' on LEGO EV3 v1.0.0
"""
def partial():
pass
def reduce():
pass
def update_wrapper():
pass
def wraps():
pass |
# ASL ALPHABET, j,Z OMITTED
language = {
'letter_a' : [
"http://science.opposingviews.com/DM-Resize/photos.demandstudios.com/getty/article/81/210/78033946.jpg?w=600&h=600&keep_ratio=1",
"http://www.lifeprint.com/asl101/signjpegs/a/a.jpg",
"http://thumbs.dreamstime.com/x/letter-sign-language-587184.jpg",
"http:/... | language = {'letter_a': ['http://science.opposingviews.com/DM-Resize/photos.demandstudios.com/getty/article/81/210/78033946.jpg?w=600&h=600&keep_ratio=1', 'http://www.lifeprint.com/asl101/signjpegs/a/a.jpg', 'http://thumbs.dreamstime.com/x/letter-sign-language-587184.jpg', 'http://i.imgur.com/ei3jaNZ.jpg', 'http://imgu... |
#!/usr/bin/python3
'''Day 5 of the 2017 advent of code'''
def process_commands(cmds, program_counter):
"""helper for part 2"""
jmp_offset = cmds[program_counter]
if jmp_offset > 2:
cmds[program_counter] -= 1
else:
cmds[program_counter] += 1
return jmp_offset + program_counter
... | """Day 5 of the 2017 advent of code"""
def process_commands(cmds, program_counter):
"""helper for part 2"""
jmp_offset = cmds[program_counter]
if jmp_offset > 2:
cmds[program_counter] -= 1
else:
cmds[program_counter] += 1
return jmp_offset + program_counter
def part_one(rows):
... |
def get_access_by_username (cursor, username) :
try :
sql_statement = 'SELECT username,password,active FROM access WHERE username = %s'
cursor.execute(sql_statement,(username,))
data = cursor.fetchone()
except Exception as ex:
print('[ERROR] get_access_by_username : ' + ex.__str_... | def get_access_by_username(cursor, username):
try:
sql_statement = 'SELECT username,password,active FROM access WHERE username = %s'
cursor.execute(sql_statement, (username,))
data = cursor.fetchone()
except Exception as ex:
print('[ERROR] get_access_by_username : ' + ex.__str__(... |
"""
cmd.do('create ${1:t4l}, ${2:1lw9};')
"""
cmd.do('create t4l, 1lw9;')
# Description: Duplicate object.
# Source: placeHolder
| """
cmd.do('create ${1:t4l}, ${2:1lw9};')
"""
cmd.do('create t4l, 1lw9;') |
def misspelled(words):
misspelled_words = []
for keys, values in words.items():
if ''.join(values) != keys:
misspelled_words.append(keys)
return misspelled_words | def misspelled(words):
misspelled_words = []
for (keys, values) in words.items():
if ''.join(values) != keys:
misspelled_words.append(keys)
return misspelled_words |
#!/usr/bin/python
class VideoData(object):
percent_confidence_limit = 25
def __init__(self):
# Standard Data
self._video_id = None
self._title = None
self._description = None
self._published = None
# Metrics
self._date_start = None
self._date_... | class Videodata(object):
percent_confidence_limit = 25
def __init__(self):
self._video_id = None
self._title = None
self._description = None
self._published = None
self._date_start = None
self._date_end = None
self._views = None
self._monetizedPla... |
'''
Description: exercise: your age
Version: 1.0.0.20210113
Author: Arvin Zhao
Date: 2021-01-13 09:44:34
Last Editors: Arvin Zhao
LastEditTime: 2021-01-13 10:27:55
'''
def check_age(age: int) -> None:
'''
Check an age and print what he/she can do regarding the age.
Parameters
----------
age : his/... | """
Description: exercise: your age
Version: 1.0.0.20210113
Author: Arvin Zhao
Date: 2021-01-13 09:44:34
Last Editors: Arvin Zhao
LastEditTime: 2021-01-13 10:27:55
"""
def check_age(age: int) -> None:
"""
Check an age and print what he/she can do regarding the age.
Parameters
----------
age : his/... |
"""Top-level package for pycoview."""
__author__ = """John Gilling"""
__email__ = 'suddensleep@gmail.com'
__version__ = '0.1.0'
| """Top-level package for pycoview."""
__author__ = 'John Gilling'
__email__ = 'suddensleep@gmail.com'
__version__ = '0.1.0' |
#!/usr/bin/env python3
DOCTL = "/usr/local/bin/doctl"
PK_FILE = "/home/ndjuric/.ssh/id_rsa.pub"
SWARM_DIR = TAG = "swarm"
OVERLAY_NETWORK = "swarmnet"
DOCKER_REGISTRY = {
'master': 'private.docker.registry.example.com:5000/master',
'worker': 'private.docker.registry.example.com:5000/worker'
}
NFS_SERVER = '10.... | doctl = '/usr/local/bin/doctl'
pk_file = '/home/ndjuric/.ssh/id_rsa.pub'
swarm_dir = tag = 'swarm'
overlay_network = 'swarmnet'
docker_registry = {'master': 'private.docker.registry.example.com:5000/master', 'worker': 'private.docker.registry.example.com:5000/worker'}
nfs_server = '10.135.69.119'
' CALL_MAP is a list e... |
# Filename: BotGlobals.py
# Author: mfwass
# Date: January 8th, 2017
#
# The Legend of Pirates Online Software
# Copyright (c) The Legend of Pirates Online. All rights reserved.
#
# All use of this software is subject to the terms of the revised BSD
# license. You should have received a copy of this license along
# wi... | """
The BotGlobals class will serve as a central location
of all global values in the TLOPO Discord Bot project.
"""
app_description_upstream = 'Discord bot by TLOPO. <3 https://github.com/TheLegendofPiratesOnline/discord-bot'
app_description_fork = 'Dynasty of Persia fork. https://github.com/jamebus/discord-bot'
app_d... |
x = int(input('Enter a number: '))
index = 0
for i in range(1, int(x/2) +1):
if x % i == 0:
print(i)
index += 1
print(x)
print(f'There were {index + 1} divisors') | x = int(input('Enter a number: '))
index = 0
for i in range(1, int(x / 2) + 1):
if x % i == 0:
print(i)
index += 1
print(x)
print(f'There were {index + 1} divisors') |
# CALCULATING THE WORK ON AN OBJECT, GIVEN THE FORCE AND DISPLACEMENT OF THE OBJECT.
# creating a function to calculate the work.
def calc_work (force, displacement):
# arithmetic calculation to determine the work on an object.
work = force * displacement
work = round(work, 2)
# returning th... | def calc_work(force, displacement):
work = force * displacement
work = round(work, 2)
return work
force = int(input('Enter the amount of force in Newtons please:'))
displacement = int(input('Enter the amount of displacement in meters please:'))
print('The work on the object is:', calc_work(force, displaceme... |
class DiseaseError(Exception):
"Base class for disease module exceptions."
pass
class ParserError(DiseaseError): pass
| class Diseaseerror(Exception):
"""Base class for disease module exceptions."""
pass
class Parsererror(DiseaseError):
pass |
""" Stored values specific to a single test execution. """
test_file = None
browser = None
browser_definition = None
browsers = {}
data = None
secrets = None
description = None
settings = None
test_dirname = None
test_path = None
project_name = None
project_path = None
testdir = None
execution_reportdir = None
testfil... | """ Stored values specific to a single test execution. """
test_file = None
browser = None
browser_definition = None
browsers = {}
data = None
secrets = None
description = None
settings = None
test_dirname = None
test_path = None
project_name = None
project_path = None
testdir = None
execution_reportdir = None
testfile... |
class SaveCurrentUser():
def save_model(self, request, obj, form, change):
obj.current_user = request.user
super().save_model(request, obj, form, change)
class SaveCurrentUserAdmin():
def save_model(self, request, obj, form, change):
obj.current_user = request.user
super().sa... | class Savecurrentuser:
def save_model(self, request, obj, form, change):
obj.current_user = request.user
super().save_model(request, obj, form, change)
class Savecurrentuseradmin:
def save_model(self, request, obj, form, change):
obj.current_user = request.user
super().save_mo... |
# CSV related
ROW_MOST_RECENT_DAY = 1 # First row with data (i.e row 2)
ROW_FIRST_COMPLETE_DAY = 3 # First row with valid data for the 7-day total (i.e row 4)
COL_AREA_CODE = 0
COL_AREA_NAME = 1
COL_AREA_TYPE = 2
COL_DATE = 3
COL_TOTAL_DEATHS = 4
COL_HOSPITAL_CASES = 5
COL_NEW_CASES = 6
| row_most_recent_day = 1
row_first_complete_day = 3
col_area_code = 0
col_area_name = 1
col_area_type = 2
col_date = 3
col_total_deaths = 4
col_hospital_cases = 5
col_new_cases = 6 |
# Time: O(n)
# Space: O(h)
class Solution(object):
def widthOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def dfs(node, i, depth, leftmosts):
if not node:
return 0
if depth >= len(leftmosts):
... | class Solution(object):
def width_of_binary_tree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def dfs(node, i, depth, leftmosts):
if not node:
return 0
if depth >= len(leftmosts):
leftmosts.append(i)
... |
class House:
"""All houses have rooms, a type of roof, and may have a porch."""
def __init__(self):
self.__rooms = list()
self.__roof = None
self.__porch = False
def add_room(self, room):
self.__rooms.append(room)
def set_roof(self, roof):
self.__roof = roof
... | class House:
"""All houses have rooms, a type of roof, and may have a porch."""
def __init__(self):
self.__rooms = list()
self.__roof = None
self.__porch = False
def add_room(self, room):
self.__rooms.append(room)
def set_roof(self, roof):
self.__roof = roof
... |
DEFAULT_AUTOPILOT_CONFIG = {
'region_name': 'YOUR_REGION',
's3_bucket': 'YOUR_S3_BUCKET',
'role_arn': 'YOUR_ROLE_ARN',
}
| default_autopilot_config = {'region_name': 'YOUR_REGION', 's3_bucket': 'YOUR_S3_BUCKET', 'role_arn': 'YOUR_ROLE_ARN'} |
#
t = int(input("T:"))
list = []
for i in range(0,t):
k = input("A B :")
list.append(k)
print(list)
for z in range(0,len(list)):
q = str(list[z])
m = q.split(" ")
print(int(m[0])+int(m[1]))
| t = int(input('T:'))
list = []
for i in range(0, t):
k = input('A B :')
list.append(k)
print(list)
for z in range(0, len(list)):
q = str(list[z])
m = q.split(' ')
print(int(m[0]) + int(m[1])) |
class BianPlugin():
def ready(self):
return True
def run(self,core,*params):
if len(params) != 4:
raise Exception("missing params:"+str(params))
init = "from halo_bian.bian.exceptions import BianException\n\nfrom halo_bian.bian.bian import ActionTerms\n\nfrom botocore.exce... | class Bianplugin:
def ready(self):
return True
def run(self, core, *params):
if len(params) != 4:
raise exception('missing params:' + str(params))
init = 'from halo_bian.bian.exceptions import BianException\n\nfrom halo_bian.bian.bian import ActionTerms\n\nfrom botocore.exc... |
V,E=map(int,input().split())
edges=[set() for i in range(V)]
for i in range(E):
a,b=map(int,input().split())
edges[a-1].add(b-1)
edges[b-1].add(a-1)
for i in range(V):
print(len({n for v in edges[i] for n in edges[v] if not n in edges[i] and n!=i})) | (v, e) = map(int, input().split())
edges = [set() for i in range(V)]
for i in range(E):
(a, b) = map(int, input().split())
edges[a - 1].add(b - 1)
edges[b - 1].add(a - 1)
for i in range(V):
print(len({n for v in edges[i] for n in edges[v] if not n in edges[i] and n != i})) |
'''
Copyright (C) 2021 Sovrasov V. - All Rights Reserved
* You may use, distribute and modify this code under the
* terms of the MIT license.
* You should have received a copy of the MIT license with
* this file. If not visit https://opensource.org/licenses/MIT
'''
def flops_to_string(flops, units='GMac', precisi... | """
Copyright (C) 2021 Sovrasov V. - All Rights Reserved
* You may use, distribute and modify this code under the
* terms of the MIT license.
* You should have received a copy of the MIT license with
* this file. If not visit https://opensource.org/licenses/MIT
"""
def flops_to_string(flops, units='GMac', precisio... |
a=[12,9,1,3]
a1=[12,9,1,3]
s=[]
z=0
c=0
#expected a=[1,3,12,9]
for i in range(len(a)):
q=0
while(a1[i]>0):
z=a1[i]%10
q=q+z
a1[i]=a1[i]//10
s.append(q)
print(a)
s.sort()
print(s)
| a = [12, 9, 1, 3]
a1 = [12, 9, 1, 3]
s = []
z = 0
c = 0
for i in range(len(a)):
q = 0
while a1[i] > 0:
z = a1[i] % 10
q = q + z
a1[i] = a1[i] // 10
s.append(q)
print(a)
s.sort()
print(s) |
# host and port for client and tracker
HOST = '192.168.43.92'
PORT = 9992
# redis key prefixes
TRANSACTION_QUEUE_KEY = 'transactions.queue'
BLOCK_KEY_PREFIX = 'chain.block.'
PREV_HASH_KEY = 'prev_hash'
SEND_TRANSACTIONS_QUEUE_KEY = 'send.transactions.queue'
TRANSACTIONS_SIGNATURE = 'transactions.signature.'
# number ... | host = '192.168.43.92'
port = 9992
transaction_queue_key = 'transactions.queue'
block_key_prefix = 'chain.block.'
prev_hash_key = 'prev_hash'
send_transactions_queue_key = 'send.transactions.queue'
transactions_signature = 'transactions.signature.'
transactions_in_block = 1
gamer_bawa = 1024 |
# -*- coding: utf-8 -*-
description = 'Monitoring for DNS setup'
group = 'basic'
tango_base = 'tango://localhost:10000/test/'
devices = dict(
dns_main_voltages = device('nicos_mlz.emc.devices.janitza_online.VectorInput',
description = 'Voltage monitoring',
tangodevice = tango_base + 'janitza_dns/... | description = 'Monitoring for DNS setup'
group = 'basic'
tango_base = 'tango://localhost:10000/test/'
devices = dict(dns_main_voltages=device('nicos_mlz.emc.devices.janitza_online.VectorInput', description='Voltage monitoring', tangodevice=tango_base + 'janitza_dns/voltages'), dns_main_currents=device('nicos_mlz.emc.de... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Author: Nasy
@Date: Dec 31. 2016
@email: sy_n@me.com
@file: optlib/tools/color_print.py
@license: MIT
An Excited Python Script
"""
RESET_COLOR = "\033[0m"
COLOR_CODES = {
"blue": "\033[1;34m", # blue
"green": "\033[1;32m", # green
"yellow"... | """
@Author: Nasy
@Date: Dec 31. 2016
@email: sy_n@me.com
@file: optlib/tools/color_print.py
@license: MIT
An Excited Python Script
"""
reset_color = '\x1b[0m'
color_codes = {'blue': '\x1b[1;34m', 'green': '\x1b[1;32m', 'yellow': '\x1b[1;33m', 'red': '\x1b[1;31m', 'b_red': '\x1b[1;41m'} |
#
# PySNMP MIB module HPN-ICF-DHCPSNOOP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-DHCPSNOOP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:25:32 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, value_range_constraint, constraints_intersection, value_size_constraint) ... |
## HTML lists ##
CHECKBOX_TOGGLES = [
"accelerometer",
"gps",
"calls",
"texts",
"wifi",
"bluetooth",
"power_state",
"proximity",
"gyro",
"magnetometer",
"devicemotion",
"ambient_audio",
"reachability",
"allow_upload_over_cellular_data",
"use_anonymized_hashing... | checkbox_toggles = ['accelerometer', 'gps', 'calls', 'texts', 'wifi', 'bluetooth', 'power_state', 'proximity', 'gyro', 'magnetometer', 'devicemotion', 'ambient_audio', 'reachability', 'allow_upload_over_cellular_data', 'use_anonymized_hashing', 'use_gps_fuzzing', 'call_clinician_button_enabled', 'call_research_assistan... |
# Comments allow for programers to write reminders or create a better understanding of the code and program
city_name = "St. Potatosburg"
# The amount of people living in the city of St. Potatosburg:
city_pop = 340000 | city_name = 'St. Potatosburg'
city_pop = 340000 |
# Script to generate translation and rotation specializations of placed volumes,
rotation = [0x1B1, 0x18E, 0x076, 0x16A, 0x155, 0x0AD, 0x0DC, 0x0E3, 0x11B,
0x0A1, 0x10A, 0x046, 0x062, 0x054, 0x111, 0x200]
translation = ["translation::kGeneric", "translation::kIdentity"]
header_string = """\
/// @file Tran... | rotation = [433, 398, 118, 362, 341, 173, 220, 227, 283, 161, 266, 70, 98, 84, 273, 512]
translation = ['translation::kGeneric', 'translation::kIdentity']
header_string = '/// @file TransformationSpecializations.icc\n/// @author Script generated.\n\n#ifndef VECGEOM_NO_SPECIALIZATION\n'
specialization_string = ' if (tr... |
class Solution:
def dropNegatives(self, A):
j = 0
newlist = []
for i in range(len(A)):
if A[i] > 0:
newlist.append(A[i])
return newlist
def firstMissingPositive(self, nums: List[int]) -> int:
A = self.dropNegatives(nums)
if len(A)==0:
... | class Solution:
def drop_negatives(self, A):
j = 0
newlist = []
for i in range(len(A)):
if A[i] > 0:
newlist.append(A[i])
return newlist
def first_missing_positive(self, nums: List[int]) -> int:
a = self.dropNegatives(nums)
if len(A) ... |
def group_weekly(df, date_col):
weekly = df.copy()
weekly['week'] = weekly[date_col].dt.isocalendar().week
weekly['year'] = weekly[date_col].dt.isocalendar().year
weekly['year_week'] = weekly['year'].astype(str) + "-" + weekly['week'].astype(str)
weekly = weekly.groupby('year_week').sum()
weekly... | def group_weekly(df, date_col):
weekly = df.copy()
weekly['week'] = weekly[date_col].dt.isocalendar().week
weekly['year'] = weekly[date_col].dt.isocalendar().year
weekly['year_week'] = weekly['year'].astype(str) + '-' + weekly['week'].astype(str)
weekly = weekly.groupby('year_week').sum()
weekly... |
# coding:utf-8
workers = 4
threads = 4
bind = '0.0.0.0:5000'
worker_class = 'eventlet' # 'gevent'
worker_connections = 2000
pidfile = 'gunicorn.pid'
accesslog = './logs/gunicorn_acess.log'
errorlog = './logs/gunicorn_error.log'
loglevel = 'info'
reload = True
| workers = 4
threads = 4
bind = '0.0.0.0:5000'
worker_class = 'eventlet'
worker_connections = 2000
pidfile = 'gunicorn.pid'
accesslog = './logs/gunicorn_acess.log'
errorlog = './logs/gunicorn_error.log'
loglevel = 'info'
reload = True |
seed_csv = """
id,name,some_date
1,Easton,1981-05-20T06:46:51
2,Lillian,1978-09-03T18:10:33
3,Jeremiah,1982-03-11T03:59:51
4,Nolan,1976-05-06T20:21:35
""".lstrip()
model_sql = """
select * from {{ ref('seed') }}
"""
profile_yml = """
version: 2
models:
- name: materialization
columns:
- name: id
t... | seed_csv = '\nid,name,some_date\n1,Easton,1981-05-20T06:46:51\n2,Lillian,1978-09-03T18:10:33\n3,Jeremiah,1982-03-11T03:59:51\n4,Nolan,1976-05-06T20:21:35\n'.lstrip()
model_sql = "\nselect * from {{ ref('seed') }}\n"
profile_yml = '\nversion: 2\nmodels:\n - name: materialization\n columns:\n - name: id\n ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.