content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#
# PySNMP MIB module BAY-STACK-UNICAST-STORM-CONTROL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BAY-STACK-UNICAST-STORM-CONTROL-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:19:32 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Usi... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, single_value_constraint, constraints_union, constraints_intersection) ... |
"""
Computer Architecture - Day 4
"""
# === Stack frames === #
# Stack grows downward
# 701:
#
# 700: # return point 1 |
# 699: a = 2 | main()'s stack frame
# 698: b = ?? |
#
# 697: # return point 2 |
# 696: x = 2 |
# 695: y = 7 | mult2()'s stack ... | """
Computer Architecture - Day 4
"""
def count(n):
if n == 0:
return
print(n)
count(n - 1)
return
count(4) |
class SQLitePostProcessor:
"""Post processor classes are responsable for modifying the result after a query.
Post Processors are called after the connection calls the database in the
Query Builder but before the result is returned in that builder method.
We can use this oppurtunity to get things like ... | class Sqlitepostprocessor:
"""Post processor classes are responsable for modifying the result after a query.
Post Processors are called after the connection calls the database in the
Query Builder but before the result is returned in that builder method.
We can use this oppurtunity to get things like ... |
with open("../input/day10.txt") as f:
lines = [x.strip() for x in f.readlines()]
score_p1 = {
')': 3,
']': 57,
'}': 1197,
'>': 25137
}
score_p2 = {
')': 1,
']': 2,
'}': 3,
'>': 4
}
rev = {
')': '(',
'}': '{',
']': '[',
... | with open('../input/day10.txt') as f:
lines = [x.strip() for x in f.readlines()]
score_p1 = {')': 3, ']': 57, '}': 1197, '>': 25137}
score_p2 = {')': 1, ']': 2, '}': 3, '>': 4}
rev = {')': '(', '}': '{', ']': '[', '>': '<'}
rev_left = {y: x for (x, y) in rev.items()}
left = set(rev.values())
right = set(rev.keys())... |
def new_user(active=False, admin=False):
print(active)
print(admin)
config = {"active": False,
"admin": True}
new_user(config.get('active'),config.get('admin'))
new_user(**config)
| def new_user(active=False, admin=False):
print(active)
print(admin)
config = {'active': False, 'admin': True}
new_user(config.get('active'), config.get('admin'))
new_user(**config) |
"""
ID: groundsada
LANG: PYTHON3
TASK: dualpal
"""
fin = open ('dualpal.in', 'r')
fout = open ('dualpal.out', 'w')
def decToBase(num,base):
result = ""
x = num
while x > 1:
remainder = x % base
if remainder < 10:
result += str(remainder)
else:
result += chr(6... | """
ID: groundsada
LANG: PYTHON3
TASK: dualpal
"""
fin = open('dualpal.in', 'r')
fout = open('dualpal.out', 'w')
def dec_to_base(num, base):
result = ''
x = num
while x > 1:
remainder = x % base
if remainder < 10:
result += str(remainder)
else:
result += chr(... |
{
"cells": [
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['2018-11-22 06:46:14', '0']\n",
"['2018-11-22 06:52:11', '0']\n",
"['2018-11-22 06:52:27', '1']\n",
"['2018-11-22 06:5... | {'cells': [{'cell_type': 'code', 'execution_count': 8, 'metadata': {}, 'outputs': [{'name': 'stdout', 'output_type': 'stream', 'text': ["['2018-11-22 06:46:14', '0']\n", "['2018-11-22 06:52:11', '0']\n", "['2018-11-22 06:52:27', '1']\n", "['2018-11-22 06:53:01', '2']\n", "['2018-11-22 06:53:50', '2']\n", "['2018-11-22 ... |
__title__ = 'cihai'
__package_name__ = 'cihai'
__version__ = '0.12.0'
__description__ = 'Library for CJK (chinese, japanese, korean) language data.'
__author__ = 'Tony Narlock'
__email__ = 'tony@git-pull.com'
__github__ = 'https://github.com/cihai/cihai'
__docs__ = 'https://cihai.git-pull.com'
__tracker__ = 'https://gi... | __title__ = 'cihai'
__package_name__ = 'cihai'
__version__ = '0.12.0'
__description__ = 'Library for CJK (chinese, japanese, korean) language data.'
__author__ = 'Tony Narlock'
__email__ = 'tony@git-pull.com'
__github__ = 'https://github.com/cihai/cihai'
__docs__ = 'https://cihai.git-pull.com'
__tracker__ = 'https://gi... |
class Solution:
def detectCapitalUse(self, word: str) -> bool:
caps = False
low = False
first = False
for i, c in enumerate(word):
if i == 0:
if c.isupper():
first = True
else:
if c.isupper():
... | class Solution:
def detect_capital_use(self, word: str) -> bool:
caps = False
low = False
first = False
for (i, c) in enumerate(word):
if i == 0:
if c.isupper():
first = True
elif c.isupper():
caps = True
... |
#
# PySNMP MIB module HM2-NETOBJ-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HM2-NETOBJ-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:19:03 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, constraints_union, value_size_constraint, value_range_constraint) ... |
# The MIT License (MIT)
#
# Copyright (c) 2020-2022 Yury Gribov
#
# Use of this source code is governed by The MIT License (MIT)
# that can be found in the LICENSE.txt file.
"""Source file locations."""
class Location:
"""Location in file."""
def __init__(self, filename=None, lineno=None):
self.filename = ... | """Source file locations."""
class Location:
"""Location in file."""
def __init__(self, filename=None, lineno=None):
self.filename = filename
self.lineno = lineno
def prior(self):
"""Location of preceeding line."""
return location(self.filename, self.lineno - 1) if self el... |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 26 18:29:24 2017
@author: User
"""
def multVals(vals, multiplier):
newVals = []
for elements in vals:
newVals.append(elements*multiplier)
vals[:] = newVals # this is the way to change a global variable vals to the new values. If just vals i... | """
Created on Tue Dec 26 18:29:24 2017
@author: User
"""
def mult_vals(vals, multiplier):
new_vals = []
for elements in vals:
newVals.append(elements * multiplier)
vals[:] = newVals
vals = [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 44, 55, 222]
print(mult_vals(vals, 10))
print(vals) |
# -*- coding: utf-8 -*-
"""
Fallback to given artist name when no title/artist detected
"""
def fallback_artist(artist):
"""
Fallback method
"""
def fallback_a(title):
return [artist, title]
return fallback_a
| """
Fallback to given artist name when no title/artist detected
"""
def fallback_artist(artist):
"""
Fallback method
"""
def fallback_a(title):
return [artist, title]
return fallback_a |
numbers_to_word = {
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
}
a = int(input('Number: '))
if a in numbers_to_word.keys():
print(numbers_to_word[a])
else:
print('number too big')
| numbers_to_word = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine'}
a = int(input('Number: '))
if a in numbers_to_word.keys():
print(numbers_to_word[a])
else:
print('number too big') |
def repeat_it(string,n):
print( string)
if type(string) == str:
return string * n
print(string*n)
else:
return 'Not a string' | def repeat_it(string, n):
print(string)
if type(string) == str:
return string * n
print(string * n)
else:
return 'Not a string' |
class Utils:
@staticmethod
def parse_html(text):
tag_dict = {
"<b>": "**",
"</b>": "**",
"<i>": "_",
"</i>": "_"
}
if text[0] == ">":
text = "\\" + text
new_text = text.replace('*', '\*')
for i, j in tag_dict.ite... | class Utils:
@staticmethod
def parse_html(text):
tag_dict = {'<b>': '**', '</b>': '**', '<i>': '_', '</i>': '_'}
if text[0] == '>':
text = '\\' + text
new_text = text.replace('*', '\\*')
for (i, j) in tag_dict.items():
new_text = new_text.replace(i, j)
... |
"""
A factory pattern defines a interface for creating an
object, but defer object instantiation to run time.
"""
# abstract class (Interface)
class ShapeInterface:
def draw(self):
raise NotImplementedError()
# concrete classes
class Circle(ShapeInterface):
def draw(self):
print('Circle.dr... | """
A factory pattern defines a interface for creating an
object, but defer object instantiation to run time.
"""
class Shapeinterface:
def draw(self):
raise not_implemented_error()
class Circle(ShapeInterface):
def draw(self):
print('Circle.draw')
class Square(ShapeInterface):
def dr... |
Filenames = {
'CONF': 'scenario.json',
'SOLU': 'solution.json'
}
Ratings = {
'MIN': 0,
'MAX': 100,
}
| filenames = {'CONF': 'scenario.json', 'SOLU': 'solution.json'}
ratings = {'MIN': 0, 'MAX': 100} |
# Copyright 2014 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.
"""
Exception classes raised by AdbWrapper and DeviceUtils.
"""
class BaseError(Exception):
"""Base exception for all device and command errors."""
pass... | """
Exception classes raised by AdbWrapper and DeviceUtils.
"""
class Baseerror(Exception):
"""Base exception for all device and command errors."""
pass
class Commandfailederror(BaseError):
"""Exception for command failures."""
def __init__(self, msg, device=None):
super(CommandFailedError, s... |
class SelectionNotContinuousException(Exception):
pass
| class Selectionnotcontinuousexception(Exception):
pass |
load("//rules:common.bzl", "CljInfo")
def clojure_ns_impl(ctx):
runfiles = ctx.runfiles()
clj_srcs = []
java_deps = []
transitive_aot = list(ctx.attr.aot)
for dep in ctx.attr.srcs.keys() + ctx.attr.deps:
if DefaultInfo in dep:
runfiles = runfiles.merge(dep[DefaultInfo].default... | load('//rules:common.bzl', 'CljInfo')
def clojure_ns_impl(ctx):
runfiles = ctx.runfiles()
clj_srcs = []
java_deps = []
transitive_aot = list(ctx.attr.aot)
for dep in ctx.attr.srcs.keys() + ctx.attr.deps:
if DefaultInfo in dep:
runfiles = runfiles.merge(dep[DefaultInfo].default_r... |
def bdms(n,k):
if(n==0):
return 0
else:
# n not zero
if(n%2==0):
kick = n//2
n2 = kick
n1 = 0
else:
kick = (n//2) + 1
n2 = kick-1
n1 = 1
if(kick%k==0):
return kick
else:
while(kick%k != 0 and n2>0):
kick+=1
n2-=1
n1+=2
if(n2==0):
return -1
return kick
n,k=... | def bdms(n, k):
if n == 0:
return 0
else:
if n % 2 == 0:
kick = n // 2
n2 = kick
n1 = 0
else:
kick = n // 2 + 1
n2 = kick - 1
n1 = 1
if kick % k == 0:
return kick
else:
while k... |
reporting_jurisdiction = [
'AL',
'AK',
'AR',
'AZ',
'CA',
'CI',
'CO',
'MP',
'CT',
'DE',
'DC',
'FM',
'FL',
'GA',
'GU',
'HI',
'HO',
'ID',
'IL',
'IN',
'IA',
'KS',
'KY',
'LC',
'LA',
'ME',
'MD',
'MA',
'MI',
... | reporting_jurisdiction = ['AL', 'AK', 'AR', 'AZ', 'CA', 'CI', 'CO', 'MP', 'CT', 'DE', 'DC', 'FM', 'FL', 'GA', 'GU', 'HI', 'HO', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LC', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NZ', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'PH', 'PR', 'MH', ... |
#!/usr/bin/env python
# http://flask.pocoo.org/docs/config/#development-production
class Config(object):
SECRET_KEY = 'bzNsEap7HGJeOGzAxhNlQCtaRpccRZHgWaOncxAKpCJovJgJbN'
SITE_NAME = 'profiler'
MEMCACHED_SERVERS = ['localhost:11211']
SYS_ADMINS = ['foo@example.com']
class ProductionConfig(Config):
... | class Config(object):
secret_key = 'bzNsEap7HGJeOGzAxhNlQCtaRpccRZHgWaOncxAKpCJovJgJbN'
site_name = 'profiler'
memcached_servers = ['localhost:11211']
sys_admins = ['foo@example.com']
class Productionconfig(Config):
debug = False
class Developmentconfig(Config):
"""Use "if app.debug" anywhere ... |
# coding: utf-8
# Try POH
# author: Leonarodne @ NEETSDKASU
##############################################
def gs(*_): return input().strip()
def gi(*_): return int(gs())
def gss(*_): return gs().split()
def gis(*_): return list(map(int, gss()))
def nmapf(n,f): return list(map(f, range(n)))
def ngs(n): return nmapf... | def gs(*_):
return input().strip()
def gi(*_):
return int(gs())
def gss(*_):
return gs().split()
def gis(*_):
return list(map(int, gss()))
def nmapf(n, f):
return list(map(f, range(n)))
def ngs(n):
return nmapf(n, gs)
def ngi(n):
return nmapf(n, gi)
def ngss(n):
return nmapf(n, gs... |
class Point():
# each method has at least self argument
def getX(self):
return self.x
# Create instances of class Point
point1 = Point()
point2 = Point()
print(point1)
print(point2)
print(point1 is point2)
point1.x = 5
point2.x = 10
print(point1.getX())
print(point2.getX())
| class Point:
def get_x(self):
return self.x
point1 = point()
point2 = point()
print(point1)
print(point2)
print(point1 is point2)
point1.x = 5
point2.x = 10
print(point1.getX())
print(point2.getX()) |
"""
Ryan Kirkbride - Love coding weird noises to dance to:
https://www.youtube.com/watch?v=Qc_8Pm2t-84
How to:
- Run the statements line by line (alt+enter),
go to the next one whenever you feel like
- The "#### > run block <" blocks should be
executed atomically (ctrl+enter)
- If you want to fast-... | """
Ryan Kirkbride - Love coding weird noises to dance to:
https://www.youtube.com/watch?v=Qc_8Pm2t-84
How to:
- Run the statements line by line (alt+enter),
go to the next one whenever you feel like
- The "#### > run block <" blocks should be
executed atomically (ctrl+enter)
- If you want to fast-... |
# ham cho do dai day con dai nhat thoa man A[i] = A[i-1] + A[i-2]
def maxSubLens(A, N):
pass
N = int(input())
A = [int(item) for item in input().split()]
print(len(A)) | def max_sub_lens(A, N):
pass
n = int(input())
a = [int(item) for item in input().split()]
print(len(A)) |
def getTotalX(a, b):
limMax = min(b) #maximum limit
limMin = max(a) #minimum limit
sizeA = len(a)
sizeB = len(b)
nums = []
result = 0
aux = limMin
while (aux <= limMax):
for j in range(0,sizeA):
if (j == sizeA - 1) and (aux % a[j] == 0):
nums.append(aux)
break
if aux % a... | def get_total_x(a, b):
lim_max = min(b)
lim_min = max(a)
size_a = len(a)
size_b = len(b)
nums = []
result = 0
aux = limMin
while aux <= limMax:
for j in range(0, sizeA):
if j == sizeA - 1 and aux % a[j] == 0:
nums.append(aux)
break
... |
""" Custom exceptions for dealing with responses from the TAP server """
__all__ = ["TAPQueryException", "TAPUploadException"]
class TAPQueryException(Exception):
def __init__(self, response, message=None):
# Try parsing out an error message.
if message is None:
try:
... | """ Custom exceptions for dealing with responses from the TAP server """
__all__ = ['TAPQueryException', 'TAPUploadException']
class Tapqueryexception(Exception):
def __init__(self, response, message=None):
if message is None:
try:
message = response.text.split('<INFO name="QUE... |
opt = {
"optimizer": {
"type": "Adam",
"kwargs": {
"lr": 0.001,
},
},
"learning_rate_decay": {
"type": "",
"kwargs": {},
},
"gradient_clip": {
"type": "",
"kwargs": {},
},
"gradient_noise_scale": None,
"name": None,
}
| opt = {'optimizer': {'type': 'Adam', 'kwargs': {'lr': 0.001}}, 'learning_rate_decay': {'type': '', 'kwargs': {}}, 'gradient_clip': {'type': '', 'kwargs': {}}, 'gradient_noise_scale': None, 'name': None} |
class Protocol(object):
def __str__(self):
_str = '<================ Constants information ================>\n'
for name, value in self.__dict__.items():
print(name, value)
_str += '\t{}\t{}\n'.format(name, value)
return _str
def __len__(self):
raise No... | class Protocol(object):
def __str__(self):
_str = '<================ Constants information ================>\n'
for (name, value) in self.__dict__.items():
print(name, value)
_str += '\t{}\t{}\n'.format(name, value)
return _str
def __len__(self):
raise N... |
class FastTextModel(object):
def __init__(self, word_index, raw_word_vectors):
pass
def save_to_word2vec_format(self, word_vectors, output_path):
pass
| class Fasttextmodel(object):
def __init__(self, word_index, raw_word_vectors):
pass
def save_to_word2vec_format(self, word_vectors, output_path):
pass |
class PhoneDirectory:
def __init__(self, maxNumbers):
self.nums = set(range(maxNumbers))
def get(self):
return self.nums.pop() if self.nums else -1
def check(self, number):
return number in self.nums
def release(self, number):
self.nums.add(number) | class Phonedirectory:
def __init__(self, maxNumbers):
self.nums = set(range(maxNumbers))
def get(self):
return self.nums.pop() if self.nums else -1
def check(self, number):
return number in self.nums
def release(self, number):
self.nums.add(number) |
#!/usr/bin/env python
class TestMyModule:
'''
``Test`` prefix
'''
def test_f(self):
'''
``test_`` prefix
'''
pass
| class Testmymodule:
"""
``Test`` prefix
"""
def test_f(self):
"""
``test_`` prefix
"""
pass |
tests = (
'parse_token',
'variable_fields',
'template',
'loaders',
'filters',
'default_filters',
'blockextend',
'default_tags',
)
| tests = ('parse_token', 'variable_fields', 'template', 'loaders', 'filters', 'default_filters', 'blockextend', 'default_tags') |
standardRnaToProtein = {
'UUU':'F', 'UUC':'F', 'UCU':'S', 'UCC':'S',
'UAU':'Y', 'UAC':'Y', 'UGU':'C', 'UGC':'C',
'UUA':'L', 'UCA':'S', 'UAA':'*', 'UGA':'*',
'UUG':'L', 'UCG':'S', 'UAG':'*', 'UGG':'W',
'CUU':'L', 'CUC':'L', 'CCU':'P', 'CCC':'P',
'CAU':'H', ... | standard_rna_to_protein = {'UUU': 'F', 'UUC': 'F', 'UCU': 'S', 'UCC': 'S', 'UAU': 'Y', 'UAC': 'Y', 'UGU': 'C', 'UGC': 'C', 'UUA': 'L', 'UCA': 'S', 'UAA': '*', 'UGA': '*', 'UUG': 'L', 'UCG': 'S', 'UAG': '*', 'UGG': 'W', 'CUU': 'L', 'CUC': 'L', 'CCU': 'P', 'CCC': 'P', 'CAU': 'H', 'CAC': 'H', 'CGU': 'R', 'CGC': 'R', 'CUA'... |
class Field(object):
def __init__(self, default=None, null: bool = False):
self.default = default
self.null = null
self.section = None
self.name = None
self.value = None
self.meta = None
def __get__(self, instance, owner):
value = self.meta.connector.get... | class Field(object):
def __init__(self, default=None, null: bool=False):
self.default = default
self.null = null
self.section = None
self.name = None
self.value = None
self.meta = None
def __get__(self, instance, owner):
value = self.meta.connector.get_v... |
# simple_assignment.py
# THIS FILE IS AUTOMATICALLY GENERATED FROM comments.pil.
# DO NOT EDIT!
foo = 5
print(foo)
| foo = 5
print(foo) |
NEO4J_TEST_CONNECTION = """MATCH (n) RETURN count(n) as count"""
# create
NEO4J_CREATE_DOCUMENT_NODE_RETURN_ID = """
CYPHER 3.4
CREATE (node { }) RETURN ID(node) as ID"""
NEO4J_CREATE_NODE_SET_PART = "SET node.`{attr_name}` = {{`{attr_name}`}}"
NEO4J_CREATE_NODE_SET_PART_MERGE_ATTR = "SET node.`{attr_name}` = (CASE WH... | neo4_j_test_connection = 'MATCH (n) RETURN count(n) as count'
neo4_j_create_document_node_return_id = '\nCYPHER 3.4\nCREATE (node { }) RETURN ID(node) as ID'
neo4_j_create_node_set_part = 'SET node.`{attr_name}` = {{`{attr_name}`}}'
neo4_j_create_node_set_part_merge_attr = 'SET node.`{attr_name}` = (CASE WHEN not exist... |
# -*- coding: utf-8 -*-
""" Utilities for generating ring crossings.
"""
def generate_crossings(points, n_rings):
""" Generate a rings crossing dictionary from crossings points.
:param list points:
Points is a list of rings from 0 to N-1. Each list
specifies the LED number of eac... | """ Utilities for generating ring crossings.
"""
def generate_crossings(points, n_rings):
""" Generate a rings crossing dictionary from crossings points.
:param list points:
Points is a list of rings from 0 to N-1. Each list
specifies the LED number of each point on the ring that
... |
# GENERATED VERSION FILE
# TIME: Thu Aug 6 08:41:19 2020
__version__ = '0.7.rc1+82bf68a'
short_version = '0.7.rc1'
mmskl_home = r'/home/wing_mac/action_recognition/mmskeleton'
| __version__ = '0.7.rc1+82bf68a'
short_version = '0.7.rc1'
mmskl_home = '/home/wing_mac/action_recognition/mmskeleton' |
class SqlError(Exception):
def __init__(self, message="Salary != in (5000, 15000) range"):
self.message = message
super().__init__(self.message) | class Sqlerror(Exception):
def __init__(self, message='Salary != in (5000, 15000) range'):
self.message = message
super().__init__(self.message) |
# vat.py
price = 100 # GBP, no VAT
final_price1 = price * 1.2
final_price2 = price + price / 5.0
final_price3 = price * (100 + 20) / 100.0
final_price4 = price + price * 0.2
if __name__ == "__main__":
for var, value in sorted(vars().items()):
if 'price' in var:
print(var, value)
| price = 100
final_price1 = price * 1.2
final_price2 = price + price / 5.0
final_price3 = price * (100 + 20) / 100.0
final_price4 = price + price * 0.2
if __name__ == '__main__':
for (var, value) in sorted(vars().items()):
if 'price' in var:
print(var, value) |
class Solution:
def numberOfMatches(self, n: int) -> int:
count = 0
while n >= 2:
count += n // 2
print(count)
if n % 2:
n = n // 2 + 1
else:
n = n // 2
return count
| class Solution:
def number_of_matches(self, n: int) -> int:
count = 0
while n >= 2:
count += n // 2
print(count)
if n % 2:
n = n // 2 + 1
else:
n = n // 2
return count |
"""This module contains the set of Ostorlab exceptions."""
class OstorlabError(Exception):
"""Ostorlab base error that all the exceptions inherit from."""
| """This module contains the set of Ostorlab exceptions."""
class Ostorlaberror(Exception):
"""Ostorlab base error that all the exceptions inherit from.""" |
#!/usr/bin/env python
class HmiMessage(object):
def __init__(self):
pass
class CloseMessage(HmiMessage):
def __init__(self):
super(CloseMessage, self).__init__()
class HmiModbusMessage(HmiMessage):
def __init__(self, ip, mb_table):
super(HmiModbusMessage, self).__init__()
... | class Hmimessage(object):
def __init__(self):
pass
class Closemessage(HmiMessage):
def __init__(self):
super(CloseMessage, self).__init__()
class Hmimodbusmessage(HmiMessage):
def __init__(self, ip, mb_table):
super(HmiModbusMessage, self).__init__()
self.ip = ip
... |
N = int(input())
G = [int(x) for x in input().split()]
trueG = list(range(N))
for i in range(N):
for j in range(N):
G[j] = (G[j] + (-1 if j % 2 else 1)) % N
if G == trueG:
print('Yes')
break
else:
print('No')
| n = int(input())
g = [int(x) for x in input().split()]
true_g = list(range(N))
for i in range(N):
for j in range(N):
G[j] = (G[j] + (-1 if j % 2 else 1)) % N
if G == trueG:
print('Yes')
break
else:
print('No') |
class APIException(Exception):
def __init__(self):
self.message = '!200 response from api'
class OpenConvException(Exception):
def __init__(self):
self.message = 'Error while opening conv non 200 response'
class OpenConvServerException(Exception):
def __init__(self):
self.message... | class Apiexception(Exception):
def __init__(self):
self.message = '!200 response from api'
class Openconvexception(Exception):
def __init__(self):
self.message = 'Error while opening conv non 200 response'
class Openconvserverexception(Exception):
def __init__(self):
self.messag... |
n = list(map(int, input().split()))
if (n[1] % 2 == 0):
print("possible")
else:
print("impossible")
| n = list(map(int, input().split()))
if n[1] % 2 == 0:
print('possible')
else:
print('impossible') |
'''
In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.
Two nodes of a binary tree are cousins if they have the same depth, but have different parents.
We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree.
... | """
In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.
Two nodes of a binary tree are cousins if they have the same depth, but have different parents.
We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree.
... |
"""
Model parameters.
"""
sys_params = {
'food_growth_rate': [3],
'maximum_food_per_site': [10],
'reproduction_probability': [1.0],
'agent_lifespan': [35],
'reproduction_food_threshold': [6], # When the agents start reproducing
'hunger_threshold': [15], # When the agents start eating
'repro... | """
Model parameters.
"""
sys_params = {'food_growth_rate': [3], 'maximum_food_per_site': [10], 'reproduction_probability': [1.0], 'agent_lifespan': [35], 'reproduction_food_threshold': [6], 'hunger_threshold': [15], 'reproduction_food': [1]} |
# The arduino accepts commands in 1/10 millimeters
UNIT = 10
class Line:
def __init__(self, x1, y1, x2, y2):
self.x1 = float(x1)
self.y1 = float(y1)
self.x2 = float(x2)
self.y2 = float(y2)
def __eq__(self, other):
return isinstance(other, self.__class__) \
a... | unit = 10
class Line:
def __init__(self, x1, y1, x2, y2):
self.x1 = float(x1)
self.y1 = float(y1)
self.x2 = float(x2)
self.y2 = float(y2)
def __eq__(self, other):
return isinstance(other, self.__class__) and self.x1 == other.x1 and (self.y1 == other.y1) and (self.x2 ==... |
def check_and_apply(queue, rule):
r = rule[0].split()
l = len(r)
if len(queue) >= l:
t = queue[-l:]
if list(zip(*t)[0]) == r:
new_t = rule[1](list(zip(*t)[1]))
del queue[-l:]
queue.extend(new_t)
return True
return False
rules = []
# k, ... | def check_and_apply(queue, rule):
r = rule[0].split()
l = len(r)
if len(queue) >= l:
t = queue[-l:]
if list(zip(*t)[0]) == r:
new_t = rule[1](list(zip(*t)[1]))
del queue[-l:]
queue.extend(new_t)
return True
return False
rules = []
max_while... |
_base_ = [
'../_base_/models/faster_rcnn_r50_fpn.py',
'../_base_/datasets/coco_detection.py',
'../_base_/schedules/schedule_3x.py', '../_base_/default_runtime.py'
]
'''
model = dict(
neck=dict(
type='PAFPN',
in_channels=[256, 512, 1024, 2048],
out_channels=256,
num_outs... | _base_ = ['../_base_/models/faster_rcnn_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_3x.py', '../_base_/default_runtime.py']
"\nmodel = dict(\n neck=dict(\n type='PAFPN',\n in_channels=[256, 512, 1024, 2048],\n out_channels=256,\n num_outs=5),\n te... |
class Parser:
def parse(self, string):
"""
Returns a dictionary which has a structure like this:
- com
- arg1
- arg2
...
-argN
"""
parsedString = {}
strArr = string.split()
parsedString['com'] = strArr[0]
... | class Parser:
def parse(self, string):
"""
Returns a dictionary which has a structure like this:
- com
- arg1
- arg2
...
-argN
"""
parsed_string = {}
str_arr = string.split()
parsedString['com'] = strArr[0]
... |
"""
What? Simplest unit check (as opposed to integration checks)
Keep in mind that python sum function accepts any
iterables.
Reference: https://realpython.com/python-testing/
"""
def test_sum_list():
assert sum([1, 2, 3]) == 6, "Should be 6"
def test_sum_tuple():
assert sum((1, 2, 2)) == 5, "Should be 6"
... | """
What? Simplest unit check (as opposed to integration checks)
Keep in mind that python sum function accepts any
iterables.
Reference: https://realpython.com/python-testing/
"""
def test_sum_list():
assert sum([1, 2, 3]) == 6, 'Should be 6'
def test_sum_tuple():
assert sum((1, 2, 2)) == 5, 'Should be 6'
i... |
"""
EOS CLI syntax changes
"""
CLI_SYNTAX = {
# Default CLI syntax version
# We do trandlation from 4.23.0 syntax to pre-4.23.0 syntax
1: {
"aaa authorization serial-console": "aaa authorization console",
"area not-so-stubby lsa type-7 convert type-5": "area nssa translate type7 always",
... | """
EOS CLI syntax changes
"""
cli_syntax = {1: {'aaa authorization serial-console': 'aaa authorization console', 'area not-so-stubby lsa type-7 convert type-5': 'area nssa translate type7 always', 'arp aging timeout': 'arp timeout', 'bfd default': 'bfd all-interfaces', 'dynamic peer max': 'bgp listen limit', 'class-ma... |
# Copyright (c) 2016-2017 Dustin Doloff
# Licensed under Apache License v2.0
load(
"@bazel_toolbox//actions:actions.bzl",
"generate_templated_file",
)
load(
"@bazel_toolbox//labels:labels.bzl",
"executable_label",
)
def _generate_deploy_site_zip_s3_script(ctx):
ctx.actions.run(
mnemonic = ... | load('@bazel_toolbox//actions:actions.bzl', 'generate_templated_file')
load('@bazel_toolbox//labels:labels.bzl', 'executable_label')
def _generate_deploy_site_zip_s3_script(ctx):
ctx.actions.run(mnemonic='GeneratingS3DeployScript', arguments=['--bucket', ctx.attr.bucket, '--cache-durations', ctx.attr.cache_duratio... |
__all__ = ['__version__', '__author__', '__email__']
__version__ = '1.0.1'
__author__ = 'Axel Juraske'
__email__ = 'axel.juraske@short-report.de'
| __all__ = ['__version__', '__author__', '__email__']
__version__ = '1.0.1'
__author__ = 'Axel Juraske'
__email__ = 'axel.juraske@short-report.de' |
"""
#DEFUNCT TROPO TEST
response.view="generic.json"
def index():
return(
dict(
tropo=[{"say":{"value":"Welcome to the Biddrive dot com call center. Testing pronunciation. Hello Neal, Paul, Zaki, Barret, Rob, Christy, and Himel."}}]
)
)
def result():
return(
dict(
tropo=[{"hangup":{"value":"... | """
#DEFUNCT TROPO TEST
response.view="generic.json"
def index():
return(
dict(
tropo=[{"say":{"value":"Welcome to the Biddrive dot com call center. Testing pronunciation. Hello Neal, Paul, Zaki, Barret, Rob, Christy, and Himel."}}]
)
)
def result():
return(
dict(
tropo=[{"hangup":{"value":"Goodbye."}}]... |
CFNoQuitButton=256
CFPageButton=16
CFQuicktalker=4
CFQuitButton=32
CFReversed=64
CFSndOpenchat=128
CFSpeech=1
CFThought=2
CFTimeout=8
CCNormal = 0
CCNonPlayer = 1
CCSuit = 2
CCToonBuilding = 3
CCSuitBuilding = 4
CCHouseBuilding = 5
CCSpeedChat = 6
NAMETAG_COLORS = {
CCNormal: (
# Normal FG ... | cf_no_quit_button = 256
cf_page_button = 16
cf_quicktalker = 4
cf_quit_button = 32
cf_reversed = 64
cf_snd_openchat = 128
cf_speech = 1
cf_thought = 2
cf_timeout = 8
cc_normal = 0
cc_non_player = 1
cc_suit = 2
cc_toon_building = 3
cc_suit_building = 4
cc_house_building = 5
cc_speed_chat = 6
nametag_colors = {CCNormal: ... |
"""
File: largest_digit.py
Name:
----------------------------------
This file recursively prints the biggest digit in
5 different integers, 12345, 281, 6, -111, -9453
If your implementation is correct, you should see
5, 8, 6, 1, 9 on Console.
"""
def main():
print(find_largest_digit(12345)) # 5
print(find_larg... | """
File: largest_digit.py
Name:
----------------------------------
This file recursively prints the biggest digit in
5 different integers, 12345, 281, 6, -111, -9453
If your implementation is correct, you should see
5, 8, 6, 1, 9 on Console.
"""
def main():
print(find_largest_digit(12345))
print(find_largest_... |
def main():
n,k = map(int,input().split())
answer = [1 for _ in range(n)]
for _ in range(k):
d = int(input())
a = list(map(int,input().split()))
for i in range(d):
answer[a[i]-1] = 0
print(sum(answer))
if __name__ == "__main__":
main() | def main():
(n, k) = map(int, input().split())
answer = [1 for _ in range(n)]
for _ in range(k):
d = int(input())
a = list(map(int, input().split()))
for i in range(d):
answer[a[i] - 1] = 0
print(sum(answer))
if __name__ == '__main__':
main() |
# ex:ts=4:sw=4:sts=4:et
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
#
# Copyright (C) 2006 - 2007 Michael 'Mickey' Lauer
# Copyright (C) 2006 - 2007 Richard Purdie
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License versi... | class Bbuihelper:
def __init__(self):
self.needUpdate = False
self.running_tasks = {}
self.failed_tasks = []
def event_handler(self, event):
if isinstance(event, bb.build.TaskStarted):
self.running_tasks[event.pid] = {'title': '%s %s' % (event._package, event._task)... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param {ListNode} head
# @param {integer} val
# @return {ListNode}
def removeElements(self, head, val):
node = head
last = None
... | class Solution:
def remove_elements(self, head, val):
node = head
last = None
new_head = head
while node:
if node.val != val:
if last:
last.next = node
last = node
else:
last = no... |
'''https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
105. Construct Binary Tree from Preorder and Inorder Traversal
Medium
6751
171
Add to List
Share
Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inor... | """https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
105. Construct Binary Tree from Preorder and Inorder Traversal
Medium
6751
171
Add to List
Share
Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inor... |
template = {
'template_type': 'attachment',
'value': {
'attachment': {
'type': 'file',
'payload': {
'url': ''
}
}
}
}
class AttachmentTemplate:
def __init__(self, url='', type='file'):
self.template = template['value']
... | template = {'template_type': 'attachment', 'value': {'attachment': {'type': 'file', 'payload': {'url': ''}}}}
class Attachmenttemplate:
def __init__(self, url='', type='file'):
self.template = template['value']
self.url = url
self.type = type
def set_url(self, url=''):
self.ur... |
"""This problem was asked by Microsoft.
Given a string and a pattern, find the starting indices of all occurrences
of the pattern in the string. For example, given the string "abracadabra" and
the pattern "abr", you should return [0, 7].
""" | """This problem was asked by Microsoft.
Given a string and a pattern, find the starting indices of all occurrences
of the pattern in the string. For example, given the string "abracadabra" and
the pattern "abr", you should return [0, 7].
""" |
class _Regex:
def __init__(self, s: str):
self.s = s
def __eq__(self, x):
if self.s == None and x.s == None:
return True
if self.s == None:
return False
if x.s == None:
return False
return self.s == x.s
def __add__(self, x):
... | class _Regex:
def __init__(self, s: str):
self.s = s
def __eq__(self, x):
if self.s == None and x.s == None:
return True
if self.s == None:
return False
if x.s == None:
return False
return self.s == x.s
def __add__(self, x):
... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
__author__ = 'andyguo'
DAYU_DB_ROOT_FOLDER_NAME = '.!0x5f3759df_this_is_a_magic_number_used_for_telling_which_atom_is_the_root'
DAYU_DB_NAME = 'DAYU_DB_NAME'
DAYU_APP_NAME = 'DAYU_APP_NAME'
DAYU_CONFIG_STATIC_PATH = 'DAYU_CONFIG_STATIC_PATH'
| __author__ = 'andyguo'
dayu_db_root_folder_name = '.!0x5f3759df_this_is_a_magic_number_used_for_telling_which_atom_is_the_root'
dayu_db_name = 'DAYU_DB_NAME'
dayu_app_name = 'DAYU_APP_NAME'
dayu_config_static_path = 'DAYU_CONFIG_STATIC_PATH' |
a=10 #Normal initialization of object to variable a
def global_var():
global a #declaring that a variable as a global variable here to access or use that a here
a=a+1 # calculation
print(a)
global_var() #calling the function
"""
output become 11
"""
"""
Global variables for Nested functions
"""
def func_... | a = 10
def global_var():
global a
a = a + 1
print(a)
global_var()
'\noutput become 11\n'
'\nGlobal variables for Nested functions\n'
def func_out():
x = 10
def func_in():
global x
x = 20
print(x)
func_in()
'\noutput 20\nBecause here we already declare x=10 to func_out() so there is no nee... |
"""
`minion-ci` is a minimalist, decentralized, flexible Continuous Integration Server for hackers.
This module contains the exceptions specific to `minion` errors.
:copyright: (c) by Timo Furrer
:license: MIT, see LICENSE for details
"""
class MinionError(Exception):
"""Exception which is raised... | """
`minion-ci` is a minimalist, decentralized, flexible Continuous Integration Server for hackers.
This module contains the exceptions specific to `minion` errors.
:copyright: (c) by Timo Furrer
:license: MIT, see LICENSE for details
"""
class Minionerror(Exception):
"""Exception which is raised... |
def tag_bloco(conteudo, classe='sucesso', inline=False):
tag = 'span' if inline else 'div'
return f'<{tag} class="{classe}">{conteudo}</{tag}>'
def tag_lista(*itens):
lista = ''.join(f'<li>{item}</li>' for item in itens)
return f'<ul>{lista}</ul>'
if __name__ == '__main__':
print(tag_bloco('TEXT... | def tag_bloco(conteudo, classe='sucesso', inline=False):
tag = 'span' if inline else 'div'
return f'<{tag} class="{classe}">{conteudo}</{tag}>'
def tag_lista(*itens):
lista = ''.join((f'<li>{item}</li>' for item in itens))
return f'<ul>{lista}</ul>'
if __name__ == '__main__':
print(tag_bloco('TEXTO... |
# Errors from Identity Provider translates into these errors codes
# as an internal abstraction over OpenID Connect errors.
OIDC_ERROR_CODES = {
'E0': 'Unknown error from Identity Provider',
'E1': 'User interrupted',
'E3': 'User failed to verify SSN',
'E4': 'User declined terms',
# Happens if an... | oidc_error_codes = {'E0': 'Unknown error from Identity Provider', 'E1': 'User interrupted', 'E3': 'User failed to verify SSN', 'E4': 'User declined terms', 'E500': 'Internal Server Error', 'E501': 'Internal Server Error at Identity Provider', 'E502': 'Internal Server Error at Identity Provider', 'E505': 'Failed to comm... |
z=10
w=-10
while(z<50):
if (z>0 and w<0):
print(z**2, w**3)
z = z+10
w=w+10
# 100 -1000 | z = 10
w = -10
while z < 50:
if z > 0 and w < 0:
print(z ** 2, w ** 3)
z = z + 10
w = w + 10 |
"""
Krema part for Perms, Types, Intents etc...
"""
class ChannelTypes:
"""All Channel types in this class."""
GUILD_TEXT: int = 0 # a text channel within a server
DM: int = 1 # a direct message between users
GUILD_VOICE: int = 2 # a voice channel within a server
GROUP_DM: int = 3 # a direct ... | """
Krema part for Perms, Types, Intents etc...
"""
class Channeltypes:
"""All Channel types in this class."""
guild_text: int = 0
dm: int = 1
guild_voice: int = 2
group_dm: int = 3
guild_category: int = 4
guild_news: int = 5
guild_store: int = 6
guild_news_thread: int = 10
guil... |
def downheap(i, size):
while 2 * i <= size:
k = 2 * i
if k < size and a[k] < a[k + 1]:
k += 1
if a[i] >= a[k]:
break
a[i], a[k] = a[k], a[i]
i = k
def create_heap(a):
hsize = len(a) - 1
for i in reversed(range(1, hsize // 2 + 1)):
dow... | def downheap(i, size):
while 2 * i <= size:
k = 2 * i
if k < size and a[k] < a[k + 1]:
k += 1
if a[i] >= a[k]:
break
(a[i], a[k]) = (a[k], a[i])
i = k
def create_heap(a):
hsize = len(a) - 1
for i in reversed(range(1, hsize // 2 + 1)):
... |
x = int(input('Digite primeiro numero: '))
y = int(input('Digite segundo numero: '))
if x > y :
print('Primeiro numero e maior que o segundo!!!!')
elif x == y :
print('Os dois numeros sao iguais!!!!')
else:
print('Segundo numero e maior que o primeiro!!!!')
| x = int(input('Digite primeiro numero: '))
y = int(input('Digite segundo numero: '))
if x > y:
print('Primeiro numero e maior que o segundo!!!!')
elif x == y:
print('Os dois numeros sao iguais!!!!')
else:
print('Segundo numero e maior que o primeiro!!!!') |
#
# @lc app=leetcode id=47 lang=python3
#
# [47] Permutations II
#
# @lc code=start
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
if len(nums) == 1:
return [nums]
last_num = nums[-1]
pre_nums = nums[:-1]
permutations = []
pre_per... | class Solution:
def permute_unique(self, nums: List[int]) -> List[List[int]]:
if len(nums) == 1:
return [nums]
last_num = nums[-1]
pre_nums = nums[:-1]
permutations = []
pre_permutations = self.permuteUnique(pre_nums)
for p in pre_permutations:
... |
# Project Euler Problem 0001
# Multiples of 3 and 5
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
# NOTES:
# - natural numbers: -2, -1, 0, 1, 2, ...
# Answer: 233168
lower_... | lower_limit = 0
upper_limit = 1000
x = list(range(lower_limit, upper_limit, 1))
y = 0
for el in x:
if (el % 3 == 0) | (el % 5 == 0):
y += el
print(y) |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def insert(root, x):
if x < root.val:
if root.left is None:
root.left = TreeNode(x)
else:
insert(root.left, x)
elif x > root.val:
if root.ri... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def insert(root, x):
if x < root.val:
if root.left is None:
root.left = tree_node(x)
else:
insert(root.left, x)
elif x > root.val:
if root.right is... |
# -*- coding: utf-8 -*-
"""
mudicom.exceptions
~~~~~~~~~~~~~~~~~~
Module for package specific exceptions
"""
class InvalidDicom(IOError):
""" A DICOM file must have the correct tag to be validated as a
DICOM file. Read the DICOM standard for more information. """
pass
| """
mudicom.exceptions
~~~~~~~~~~~~~~~~~~
Module for package specific exceptions
"""
class Invaliddicom(IOError):
""" A DICOM file must have the correct tag to be validated as a
DICOM file. Read the DICOM standard for more information. """
pass |
###############################################################################
## Laboratorio de Engenharia de Computadores (LECOM) ##
## Departamento de Ciencia da Computacao (DCC) ##
## Universidade Federal de Minas Gerais (UFMG) ##
... | class Eventcode:
msg_recv = 0
msg_send = 2
node_call = 3
class Eventgenerator:
def create_call_event(time, addr):
return (time, EventCode.NODE_CALL, addr)
def create_send_event(time, msg):
return (time, EventCode.MSG_SEND, msg)
def create_recv_event(time, addr, msg):
... |
def getName():
return "html"
def output(state,information):
categories = information.listCategories()
selections = state.selected
toSave = ""
toSave += """
<html>
<head>
</head>
<body>
\n
"""
firstOne = True
for category in categories:
found = 0
for select... | def get_name():
return 'html'
def output(state, information):
categories = information.listCategories()
selections = state.selected
to_save = ''
to_save += '\n<html>\n <head>\n </head>\n <body>\n\n\n'
first_one = True
for category in categories:
found = 0
for select... |
"""
TLS Lite is a free python library that implements SSL v3, TLS v1, and
TLS v1.1. TLS Lite supports non-traditional authentication methods
such as SRP, shared keys, and cryptoIDs, in addition to X.509
certificates. TLS Lite is pure python, however it can access OpenSSL,
cryptlib, pycrypto, and GMPY for faster crypt... | """
TLS Lite is a free python library that implements SSL v3, TLS v1, and
TLS v1.1. TLS Lite supports non-traditional authentication methods
such as SRP, shared keys, and cryptoIDs, in addition to X.509
certificates. TLS Lite is pure python, however it can access OpenSSL,
cryptlib, pycrypto, and GMPY for faster crypt... |
class Solution:
def customSortString(self, order: str, str: str) -> str:
output = ""
strList = list(str)
for i in order:
cnt = strList.count(i)
strList = [c for c in strList if c != i]
output += i * cnt
return output + "".join(strList) | class Solution:
def custom_sort_string(self, order: str, str: str) -> str:
output = ''
str_list = list(str)
for i in order:
cnt = strList.count(i)
str_list = [c for c in strList if c != i]
output += i * cnt
return output + ''.join(strList) |
print("\n")
print("****************************************************")
print("|--------------------- PyPong ---------------------|")
print("| |")
print("| By WMouton | l33th |")
print("| Profession: Web Development & Linux Security ... | print('\n')
print('****************************************************')
print('|--------------------- PyPong ---------------------|')
print('| |')
print('| By WMouton | l33th |')
print('| Profession: Web Development & Linux Security |'... |
def pseudo_sort(st):
lowerCaseWords = []
pass | def pseudo_sort(st):
lower_case_words = []
pass |
class DataStore:
def __init__(self, data):
self.data = {
"image": data["image"],
"name": data["name"],
"id": data["image"]["full"].split(".")[0],
}
def setImageUrl(self, imageUrl):
self.imageUrl = imageUrl
@property
def image(self):
r... | class Datastore:
def __init__(self, data):
self.data = {'image': data['image'], 'name': data['name'], 'id': data['image']['full'].split('.')[0]}
def set_image_url(self, imageUrl):
self.imageUrl = imageUrl
@property
def image(self):
return self.imageUrl + self.data['image']['gr... |
class Distance:
kilometers = 0.0
minutes = 0.0
def __init__(self, kilometers, minutes):
self.kilometers = kilometers
self.minutes = minutes
def toJson(self):
return { "kilometers" : self.kilometers, "minutes" : self.minutes } | class Distance:
kilometers = 0.0
minutes = 0.0
def __init__(self, kilometers, minutes):
self.kilometers = kilometers
self.minutes = minutes
def to_json(self):
return {'kilometers': self.kilometers, 'minutes': self.minutes} |
# problem 8
# Project Euler
def productOfNumbers(string,start,LENGTH):
adjNumber = string[start:start+LENGTH]
product = 1
for n in adjNumber:
product *= int(n)
return product
def adjacentNumbers(string):
LENGTH = 13
currentMaxProduct = -1
currentMaxIndex = -1
for i,e in enumerate(string):
product = produc... | def product_of_numbers(string, start, LENGTH):
adj_number = string[start:start + LENGTH]
product = 1
for n in adjNumber:
product *= int(n)
return product
def adjacent_numbers(string):
length = 13
current_max_product = -1
current_max_index = -1
for (i, e) in enumerate(string):
... |
# coding=utf-8
"""
Created by jayvee on 2017/6/9.
https://github.com/JayveeHe
""" | """
Created by jayvee on 2017/6/9.
https://github.com/JayveeHe
""" |
name = input("Enter your name: ")
if name == "Arya Stark":
print("Valar Morghulis")
elif name == "Jon Snow":
print("You know nothing!")
else:
print("Carry On!") | name = input('Enter your name: ')
if name == 'Arya Stark':
print('Valar Morghulis')
elif name == 'Jon Snow':
print('You know nothing!')
else:
print('Carry On!') |
# Find the longest Palindromic Substring
# Asked in Amazon ,MakeMyTrip, Microsoft, Qualcomm, Visa
# Difficulty -> Medium
# Algorithm:
# We observe that a palindrome mirrors around its center. Therefore, a palindrome can be expanded from its center, and
# there are only 2n - 1 such centers. You might be asking why th... | def longest_palindrome(s: str) -> str:
if len(s) < 2:
return s
(start, end) = (0, 0)
for i in range(len(s)):
len1 = expand_from_center(s, i, i)
len2 = expand_from_center(s, i, i + 1)
l = max(len1, len2)
if l > end - start:
start = i - (l - 1) // 2
... |
expected_output = {
"process_id": {
65109: {
"router_id": "10.4.1.1",
"ospf_object": {
"Process ID (65109)": {
"ipfrr_enabled": "no",
"sr_enabled": "yes",
"ti_lfa_configured": "yes",
"ti_l... | expected_output = {'process_id': {65109: {'router_id': '10.4.1.1', 'ospf_object': {'Process ID (65109)': {'ipfrr_enabled': 'no', 'sr_enabled': 'yes', 'ti_lfa_configured': 'yes', 'ti_lfa_enabled': 'yes (inactive)'}, 'Area 8': {'ipfrr_enabled': 'yes', 'sr_enabled': 'yes', 'ti_lfa_configured': 'yes', 'ti_lfa_enabled': 'ye... |
#
# PySNMP MIB module NBS-VLAN-FWD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NBS-VLAN-FWD-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:17:48 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_intersection, value_size_constraint, constraints_union, value_range_constraint) ... |
class has_many:
def __init__(self, name, _class, primary_key=None, foreign_key=None):
self.name = name
self._class = _class
self.primary_key = primary_key
self.foreign_key = foreign_key
class belongs_to:
def __init__(self, name, _class, primary_key=None, foreign_key=None):
... | class Has_Many:
def __init__(self, name, _class, primary_key=None, foreign_key=None):
self.name = name
self._class = _class
self.primary_key = primary_key
self.foreign_key = foreign_key
class Belongs_To:
def __init__(self, name, _class, primary_key=None, foreign_key=None):
... |
'''
UBC Eye Movement Data Analysis Toolkit (EMDAT), Version 3
'''
| """
UBC Eye Movement Data Analysis Toolkit (EMDAT), Version 3
""" |
setup(
name='pyroll',
description='cli for simulating the rolling of dice',
author='Philip Z Nevill',
author_email='pznevill.dev@gmail.com',
version='0.1.0',
packages=find_packages(include=['pyroll', 'pyroll.*']),
)
| setup(name='pyroll', description='cli for simulating the rolling of dice', author='Philip Z Nevill', author_email='pznevill.dev@gmail.com', version='0.1.0', packages=find_packages(include=['pyroll', 'pyroll.*'])) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.