content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
max_prime = 0
number = 600851475143
factor = 2
while number != 1:
if number % factor == 0:
number //= factor
max_prime = max(max_prime, factor)
else:
factor += 1
print("Max primer number is {}".format(max_prime))
| max_prime = 0
number = 600851475143
factor = 2
while number != 1:
if number % factor == 0:
number //= factor
max_prime = max(max_prime, factor)
else:
factor += 1
print('Max primer number is {}'.format(max_prime)) |
#
# PySNMP MIB module CRESCENDO-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CRESCENDO-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:28:15 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (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) ... |
num1 = 1
num2 = 2
num3 = 3333
num3 = 33
num4 = 444
| num1 = 1
num2 = 2
num3 = 3333
num3 = 33
num4 = 444 |
fin = open("TrainingData.csv")
x = open("x.csv", 'w')
Y = open("Y.csv", 'w')
xData = []
yData = []
# read in data
for dataSet in fin:
d = list(map(int,dataSet.strip().split(',')))
xData.append(d[0:3])
yData.append([d[-1]])
# write data
index = 0
for i in xData:
k = str(i[0])
for j in i[1:]:
... | fin = open('TrainingData.csv')
x = open('x.csv', 'w')
y = open('Y.csv', 'w')
x_data = []
y_data = []
for data_set in fin:
d = list(map(int, dataSet.strip().split(',')))
xData.append(d[0:3])
yData.append([d[-1]])
index = 0
for i in xData:
k = str(i[0])
for j in i[1:]:
k += ',' + str(j)
in... |
i = 4
d = 4.0
s = 'HackerRank '
i2 = int(input())
d2 = float(input())
s2 = input()
print(i + i2)
print(d + d2)
print(s + s2)
| i = 4
d = 4.0
s = 'HackerRank '
i2 = int(input())
d2 = float(input())
s2 = input()
print(i + i2)
print(d + d2)
print(s + s2) |
"""
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
OJ's undirected graph serialization:
Nodes are labeled uniquely.
We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.
As an example, consider the serialized graph {... | """
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
OJ's undirected graph serialization:
Nodes are labeled uniquely.
We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.
As an example, consider the serialized graph {... |
items = {
'ether': {
'name': 'ether',
'icon': 'Resources//pictures//ether.png'
},
'aiguille': {
'name': 'aiguille',
'icon': 'Resources//pictures//aiguille.png',
},
'tube': {
'name': 'tube',
'icon': 'Resources//pictures//tube.png'
}
}
| items = {'ether': {'name': 'ether', 'icon': 'Resources//pictures//ether.png'}, 'aiguille': {'name': 'aiguille', 'icon': 'Resources//pictures//aiguille.png'}, 'tube': {'name': 'tube', 'icon': 'Resources//pictures//tube.png'}} |
name = 'automake'
version = '1.15'
authors = [
'GNU'
]
description = \
'''
Automake
'''
build_requires = [
'autoconf-2.69'
]
variants = [
['platform-osx', 'arch-x86_64']
]
tools = [
]
def commands():
env.PATH.append('{root}/bin')
if building:
env.ACLOCAL_PATH = '{root}/s... | name = 'automake'
version = '1.15'
authors = ['GNU']
description = '\n Automake\n '
build_requires = ['autoconf-2.69']
variants = [['platform-osx', 'arch-x86_64']]
tools = []
def commands():
env.PATH.append('{root}/bin')
if building:
env.ACLOCAL_PATH = '{root}/share'
uuid = 'repository.automake' |
class Sources:
'''
news source class to define sources objects
'''
def __init__(self, id,name, description,url, category,language, country):
self.id = id
self.name = name
self.description = description
self.url = url
self.category = category
self.language ... | class Sources:
"""
news source class to define sources objects
"""
def __init__(self, id, name, description, url, category, language, country):
self.id = id
self.name = name
self.description = description
self.url = url
self.category = category
self.langu... |
expected_output = {
"interfaces": {
"Loopback1": {
"ipv4": {"192.168.111.2": {"ip": "192.168.111.2", "netmask": "255.255.255.0","primary": True}},
"ipv6": ["2001:db8:4:1::1/64", "2001:db8:400:1::2/112"],
"vrf": "VRF1",
},
},
}
| expected_output = {'interfaces': {'Loopback1': {'ipv4': {'192.168.111.2': {'ip': '192.168.111.2', 'netmask': '255.255.255.0', 'primary': True}}, 'ipv6': ['2001:db8:4:1::1/64', '2001:db8:400:1::2/112'], 'vrf': 'VRF1'}}} |
baum1 = False
baum2 = False
baum3 = False
baum4 = False
baum5 = False
i = 1
while i <= 4:
if kara.onLeaf():
if i == 1:
baum1 = True
kara.removeLeaf()
elif i == 2:
baum2 = True
kara.removeLeaf()
elif i == 3:
baum3 = True
... | baum1 = False
baum2 = False
baum3 = False
baum4 = False
baum5 = False
i = 1
while i <= 4:
if kara.onLeaf():
if i == 1:
baum1 = True
kara.removeLeaf()
elif i == 2:
baum2 = True
kara.removeLeaf()
elif i == 3:
baum3 = True
... |
games = ['AirRaid', 'Alien', 'Amidar', 'Assault', 'Asterix', 'Asteroids', 'Atlantis', 'BankHeist', 'BattleZone', 'BeamRider', 'Berzerk', 'Bowling', 'Boxing', 'Breakout', 'Carnival', 'Centipede', 'ChopperCommand', 'CrazyClimber', 'DemonAttack', 'DoubleDunk', 'ElevatorAction', 'Enduro', 'FishingDerby', 'Freeway', 'Frostb... | games = ['AirRaid', 'Alien', 'Amidar', 'Assault', 'Asterix', 'Asteroids', 'Atlantis', 'BankHeist', 'BattleZone', 'BeamRider', 'Berzerk', 'Bowling', 'Boxing', 'Breakout', 'Carnival', 'Centipede', 'ChopperCommand', 'CrazyClimber', 'DemonAttack', 'DoubleDunk', 'ElevatorAction', 'Enduro', 'FishingDerby', 'Freeway', 'Frostb... |
class Solution:
def nthMagicalNumber(self, n: int, a: int, b: int) -> int:
MOD = int(1e9+7)
if max(a,b)%min(a,b) == 0: return (min(a,b)*n) % MOD
ans = 0
gcd_ab = gcd(a,b)
for i in range(n//(a//gcd_ab + b//gcd_ab - 1)):
ans = (ans + (a*b)//gcd_ab) % MOD
... | class Solution:
def nth_magical_number(self, n: int, a: int, b: int) -> int:
mod = int(1000000000.0 + 7)
if max(a, b) % min(a, b) == 0:
return min(a, b) * n % MOD
ans = 0
gcd_ab = gcd(a, b)
for i in range(n // (a // gcd_ab + b // gcd_ab - 1)):
ans = (... |
class Solution:
def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:
wordSet = set(wordList)
if endWord not in wordList:
return []
# {"hit": ["hot"], "hot": ["dot", "lot"], ...}
graph: Dict[str, List[str]] = defaultdict(list)
# build graph from begin... | class Solution:
def find_ladders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:
word_set = set(wordList)
if endWord not in wordList:
return []
graph: Dict[str, List[str]] = defaultdict(list)
if not self._bfs(beginWord, endWord, wordSet, grap... |
#
# PySNMP MIB module Nortel-Magellan-Passport-TraceBaseMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-TraceBaseMIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:17:35 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
#... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, constraints_union, constraints_intersection, value_size_constraint) ... |
# Copyright (C) 2022 by the nbvalx authors
#
# This file is part of nbvalx.
#
# SPDX-License-Identifier: BSD-3-Clause
"""nbvalx documentation configuration."""
# Project information
project = "nbvalx"
copyright = "2022, the nbvalx authors"
author = "Francesco Ballarin (and contributors)"
# General configuration
exten... | """nbvalx documentation configuration."""
project = 'nbvalx'
copyright = '2022, the nbvalx authors'
author = 'Francesco Ballarin (and contributors)'
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.napoleon', 'sphinx.ext.viewcode']
autodoc_default_options = {'exclude-members': '__dict__,__init_... |
def test_test():
assert False
def test_2_test():
pass
| def test_test():
assert False
def test_2_test():
pass |
'''
https://leetcode.com/problems/palindromic-substrings/
647. Palindromic Substrings
Given a string s, return the number of palindromic substrings in it.
A string is a palindrome when it reads the same backward as forward.
A substring is a contiguous sequence of characters within the string.
''... | """
https://leetcode.com/problems/palindromic-substrings/
647. Palindromic Substrings
Given a string s, return the number of palindromic substrings in it.
A string is a palindrome when it reads the same backward as forward.
A substring is a contiguous sequence of characters within the string.
""... |
"""
Add Strings
Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.
You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.
Example 1:
... | """
Add Strings
Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.
You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.
Example 1:
... |
def add(a,b):
print("ADDING %d + %d" % (a, b))
return a+b
def subtract(a, b):
print("SUBTRACTING %d - %d" % (a, b))
return a-b
def multiply(a, b):
print("MULTIPLYING %d * %d" %(a, b))
return a*b
def divide(a,b):
print("DIVIDING %d / %d" %(a, b))
return a/b
print("Let't do some math w... | def add(a, b):
print('ADDING %d + %d' % (a, b))
return a + b
def subtract(a, b):
print('SUBTRACTING %d - %d' % (a, b))
return a - b
def multiply(a, b):
print('MULTIPLYING %d * %d' % (a, b))
return a * b
def divide(a, b):
print('DIVIDING %d / %d' % (a, b))
return a / b
print("Let't do ... |
def binary_search(haystack, needle):
if len(haystack) == 0:
return -1
l, r = 0, len(haystack) - 1
while l <= r:
mid = (l + r) // 2
if needle < haystack[mid]:
r = mid - 1
elif needle > haystack[mid]:
l = mid + 1
else:
return mid
... | def binary_search(haystack, needle):
if len(haystack) == 0:
return -1
(l, r) = (0, len(haystack) - 1)
while l <= r:
mid = (l + r) // 2
if needle < haystack[mid]:
r = mid - 1
elif needle > haystack[mid]:
l = mid + 1
else:
return mid
... |
class ExtractionError(Exception):
'''The exception that is raised when there is an error when extracting.'''
def extract_7z(path:str):
'''Extract a file using 7zip.
''' | class Extractionerror(Exception):
"""The exception that is raised when there is an error when extracting."""
def extract_7z(path: str):
"""Extract a file using 7zip.
""" |
def harness(p):
scenario = [
'Constructor 0',
'Constructor 1',
'Main function',
'Destructor 1',
'Destructor 0'
]
for expect in scenario:
line = p.readline().rstrip()
assert expect == line, f'Expected: {expect}, got: {line}'
| def harness(p):
scenario = ['Constructor 0', 'Constructor 1', 'Main function', 'Destructor 1', 'Destructor 0']
for expect in scenario:
line = p.readline().rstrip()
assert expect == line, f'Expected: {expect}, got: {line}' |
class Solution:
def longestSubstring(self, s: str, k: int) -> int:
c = Counter(s)
for i, v in c.items():
if v < k:
return max(self.longestSubstring(x, k) for x in s.split(i))
return len(s)
| class Solution:
def longest_substring(self, s: str, k: int) -> int:
c = counter(s)
for (i, v) in c.items():
if v < k:
return max((self.longestSubstring(x, k) for x in s.split(i)))
return len(s) |
class BotController(object):
def __init__(self,senderId,converter,processorFactory,messenger):
self.senderId = senderId
self.converter = converter
self.processorFactory = processorFactory
self.messenger = messenger
def parse(self,request):
seatnum = request["seatnum"]
... | class Botcontroller(object):
def __init__(self, senderId, converter, processorFactory, messenger):
self.senderId = senderId
self.converter = converter
self.processorFactory = processorFactory
self.messenger = messenger
def parse(self, request):
seatnum = request['seatnu... |
# Demo Python Operators
'''
Python Operators
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
* Arithmetic operators
* Assignment operators
* Comparison operators
* Logical operators
* Identity operators
* Membership operators
*... | """
Python Operators
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
* Arithmetic operators
* Assignment operators
* Comparison operators
* Logical operators
* Identity operators
* Membership operators
* Bitwise operators
"... |
# make a list to hold onto our items
shopping_list = []
def show_help():
# print out instructions on how to use the app
print("What should we pick up at the store?")
print("""
Enter 'DONE' to stop adding items.
Enter 'HELP' for this help.
Enter 'SHOW' to see your current list.
""")
def show_list():
... | shopping_list = []
def show_help():
print('What should we pick up at the store?')
print("\nEnter 'DONE' to stop adding items.\nEnter 'HELP' for this help.\nEnter 'SHOW' to see your current list.\n")
def show_list():
print("Here's your list:")
for item in shopping_list:
print(item)
def add_to_... |
def getFrequencies(loadFrequencies):
output = 0
for line in loadFrequencies():
operator = line[0]
num = int(line[1:])
if operator == "+":
output += num
else:
output -= num
return output
| def get_frequencies(loadFrequencies):
output = 0
for line in load_frequencies():
operator = line[0]
num = int(line[1:])
if operator == '+':
output += num
else:
output -= num
return output |
def base_gate_sequence_and_macros(model, basic_gates_macros: dict = None):
"""
Given a pyGSTi model generate a minimal generating set of gate sequences by taking a union of the fiducials and the germs.
If basic gates macros given, generate a macro for each gate sequence as well.
@param model: A pyGS... | def base_gate_sequence_and_macros(model, basic_gates_macros: dict=None):
"""
Given a pyGSTi model generate a minimal generating set of gate sequences by taking a union of the fiducials and the germs.
If basic gates macros given, generate a macro for each gate sequence as well.
@param model: A pyGSTi mod... |
"""
Instruction class
"""
# Standard Library Imports
# Third Party Imports
# Local Imports
class Instruction(object):
"""
The Instruction class represents a single instruction within a Gadget.
"""
register_families = [["rax", "eax", "ax", "al", "ah"], # 0
["rbx", "ebx", "... | """
Instruction class
"""
class Instruction(object):
"""
The Instruction class represents a single instruction within a Gadget.
"""
register_families = [['rax', 'eax', 'ax', 'al', 'ah'], ['rbx', 'ebx', 'bx', 'bl', 'bh'], ['rcx', 'ecx', 'cx', 'cl', 'ch'], ['rdx', 'edx', 'dx', 'dl', 'dh'], ['rsi', 'esi',... |
small_2018_dataset = r"data/original/raster/small_datasets/2018.tif"
small_2010_dataset = r"data/original/raster/small_datasets/2010.tif"
envelope_2018 = r"data/original/raster/real_datasets/2018/envelope_2018.img"
coberture_2018_binary = r"data/original/vectorial/reals/2018_cobertures/binary/2018_binary_cobertures.shp... | small_2018_dataset = 'data/original/raster/small_datasets/2018.tif'
small_2010_dataset = 'data/original/raster/small_datasets/2010.tif'
envelope_2018 = 'data/original/raster/real_datasets/2018/envelope_2018.img'
coberture_2018_binary = 'data/original/vectorial/reals/2018_cobertures/binary/2018_binary_cobertures.shp' |
# Copyright 2002 by Andrew Dalke. All rights reserved.
# Revisions 2007-2008 by Peter Cock.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
#
# Note that BioSQL (including the database schema and scr... | """Storing and retrieve biological sequences in a BioSQL relational database.
See:
- http://biopython.org/wiki/BioSQL
- http://www.biosql.org/
""" |
# https://www.hackerrank.com/challenges/grading/problem
def gradingStudents(grades):
# Write your code here
return [(g+2)//5*5 if (g >= 38) and (g%5>2) else g for g in grades]
| def grading_students(grades):
return [(g + 2) // 5 * 5 if g >= 38 and g % 5 > 2 else g for g in grades] |
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
inputHash, strStart, firstPsum, currHash, res = 0, 0, 0, 0, []
if len(s) < len(p):
return []
for subStr in p:
inputHash += hash(subStr)
for i in range(len(p)):
firstPsum += hash(... | class Solution:
def find_anagrams(self, s: str, p: str) -> List[int]:
(input_hash, str_start, first_psum, curr_hash, res) = (0, 0, 0, 0, [])
if len(s) < len(p):
return []
for sub_str in p:
input_hash += hash(subStr)
for i in range(len(p)):
first_p... |
# EG11-02 Stock Item class failed
class StockItem(object):
'''
Stock item for the fashion shop
'''
def __init__(self, stock_ref, price, color):
self.stock_ref = stock_ref
self.__price = price
self.__stock_level = 0
self.color = color
@property
def price(self)... | class Stockitem(object):
"""
Stock item for the fashion shop
"""
def __init__(self, stock_ref, price, color):
self.stock_ref = stock_ref
self.__price = price
self.__stock_level = 0
self.color = color
@property
def price(self):
return self.__price
@p... |
def int_hex(v):
v = hex(v)
v = v[2:]
return v
def main(v):
v = v.upper()
print(v)
main(int_hex(int(input()))) | def int_hex(v):
v = hex(v)
v = v[2:]
return v
def main(v):
v = v.upper()
print(v)
main(int_hex(int(input()))) |
"""Determines if a triangle is equilater based on three input side lengths."""
def main() -> None:
"""Takes user input of three side lengths and displays if triangle is equilateral or not."""
length_one: int = int(input('Enter the first side: '))
length_two: int = int(input('Enter the second side: '))... | """Determines if a triangle is equilater based on three input side lengths."""
def main() -> None:
"""Takes user input of three side lengths and displays if triangle is equilateral or not."""
length_one: int = int(input('Enter the first side: '))
length_two: int = int(input('Enter the second side: '))
... |
"""
Version and related info.
Created by: Martin Sicho
On: 5/7/20, 2:25 PM
"""
__all__ = [
"__version__",
"__devstatus__",
"__devversion__",
"get_release_info"
]
# https://setuptools.readthedocs.io/en/latest/setuptools.html#specifying-your-project-s-version
__version__ = "0.0.0"
__devstatus__ = "alph... | """
Version and related info.
Created by: Martin Sicho
On: 5/7/20, 2:25 PM
"""
__all__ = ['__version__', '__devstatus__', '__devversion__', 'get_release_info']
__version__ = '0.0.0'
__devstatus__ = 'alpha'
__devversion__ = '1'
assert __devstatus__ and __devversion__ or not (__devstatus__ or __devversion__)
def get_re... |
"""
* High switching cost means that you should be more certain that the other side
is better before committing to change sides. This means that beliefs must fall
below a threshold before acting. Conversely, a lower switching cost allows you
more flexibility to switch at less stringent thresholds. In the limit of _ze... | """
* High switching cost means that you should be more certain that the other side
is better before committing to change sides. This means that beliefs must fall
below a threshold before acting. Conversely, a lower switching cost allows you
more flexibility to switch at less stringent thresholds. In the limit of _zer... |
def union(p,q):
for e in q:
if e not in p:
p.append(e)
def crawl_web(seed):
tocrawl = [seed]
crawled = []
index = {}
graph = {}
while tocrawl:
page = tocrawl.pop()
if page not in crawled:
content = get_page(page)
add_page_to_index(index,page,content)
outlinks = get_all_links... | def union(p, q):
for e in q:
if e not in p:
p.append(e)
def crawl_web(seed):
tocrawl = [seed]
crawled = []
index = {}
graph = {}
while tocrawl:
page = tocrawl.pop()
if page not in crawled:
content = get_page(page)
add_page_to_index(ind... |
class ServiceTypes(object):
LOAD_BALANCER = 'LoadBalancer'
NODE_PORT = 'NodePort'
CLUSTER_IP = 'ClusterIP'
VALUES = [LOAD_BALANCER, NODE_PORT, CLUSTER_IP]
| class Servicetypes(object):
load_balancer = 'LoadBalancer'
node_port = 'NodePort'
cluster_ip = 'ClusterIP'
values = [LOAD_BALANCER, NODE_PORT, CLUSTER_IP] |
#! /usr/bin/env python
# -*- coding: utf-8 -*
"""
Decorators to help manage our custom classes.
"""
TABLE_LIST = []
def register(cls):
"""
A decorator to register new table configuration classes.
"""
TABLE_LIST.append(cls)
return cls
def downloader(func):
"""
A decorator to download data... | """
Decorators to help manage our custom classes.
"""
table_list = []
def register(cls):
"""
A decorator to register new table configuration classes.
"""
TABLE_LIST.append(cls)
return cls
def downloader(func):
"""
A decorator to download data inside a table configuration class.
"""
... |
def event_handler(source,evt):
if evt == lv.EVENT.CLICKED:
if source == btn1:
# treat "clicked" events only for btn1
print("Clicked")
elif evt == lv.EVENT.VALUE_CHANGED:
print("Toggled")
# create a simple button
btn1 = lv.btn(lv.scr_act(),None)
# attach the call... | def event_handler(source, evt):
if evt == lv.EVENT.CLICKED:
if source == btn1:
print('Clicked')
elif evt == lv.EVENT.VALUE_CHANGED:
print('Toggled')
btn1 = lv.btn(lv.scr_act(), None)
btn1.set_event_cb(event_handler)
btn1.align(None, lv.ALIGN.CENTER, 0, -40)
label = lv.label(b... |
"""
Assume that the error function is x^5 - 2x^3 - 2
To know the slope of any given x value, we take its derivative: 5x^4 - 6x^2
"""
current_x = 0.5 # Algorithm starts at x = 0.5
learning_rate = 0.01 # Step size multiplier
epoch = 50 # Number of times to train the function
# Compute the derivative of the error functi... | """
Assume that the error function is x^5 - 2x^3 - 2
To know the slope of any given x value, we take its derivative: 5x^4 - 6x^2
"""
current_x = 0.5
learning_rate = 0.01
epoch = 50
def slope(x):
return 5 * x ** 4 - 6 * x ** 2
for i in range(epoch):
previous_x = current_x
current_x += -learning_rate * slope... |
#!/usr/bin/env python3
UNKNOWN = -1
def read_val():
return int(input())
def read_row():
return list(map(int, input().split()))
def read_grid():
return [read_row() for _ in range(read_val())]
def make_blank_row(i):
return [UNKNOWN] * i
def make_blank_grid(n):
return [make_blank_row(i) for i in ... | unknown = -1
def read_val():
return int(input())
def read_row():
return list(map(int, input().split()))
def read_grid():
return [read_row() for _ in range(read_val())]
def make_blank_row(i):
return [UNKNOWN] * i
def make_blank_grid(n):
return [make_blank_row(i) for i in range(1, n + 1)]
def co... |
# Copyright 2019 The Bazel Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | """PostCSS runner binary rule.
Creates a nodejs_binary given our generated internal runner source. This file
can be substituted in your copies of these build rules, for example due to
differences in Node.js/Starlark build rules."""
load('@build_bazel_rules_nodejs//:index.bzl', 'nodejs_binary')
def postcss_runner_bin(... |
"""
swagger module -
A package defining the swagger features. This module creates the swagger
structure and defines the data to show when the swagger is activated.
It does not contain the html and css files used to create the page,
only the underlying structure. The html and css can be found at the sta... | """
swagger module -
A package defining the swagger features. This module creates the swagger
structure and defines the data to show when the swagger is activated.
It does not contain the html and css files used to create the page,
only the underlying structure. The html and css can be found at the sta... |
#
# DVR-Scan: Find & Export Motion Events in Video Footage
# --------------------------------------------------------------
# [ Site: https://github.com/Breakthrough/DVR-Scan/ ]
# [ Documentation: http://dvr-scan.readthedocs.org/ ]
#
# This file contains all code related to timecode formats, inter... | class Frametimecode(object):
""" Object for frame-based timecodes, using the video framerate
to compute back and forth between frame number and second/timecode formats.
The passed argument is declared valid if it meets one of three valid forms:
1) Standard timecode HH:MM:SS[.nnn]:
in stri... |
def get_alert_rules(session: object, logger):
'''
Accepts a tenant session object.
Gets all alert rules from a tenant
'''
logger.debug('API - Getting Alert Rules')
res = session.request("GET", "/v2/alert/rule")
data = res.json()
return data | def get_alert_rules(session: object, logger):
"""
Accepts a tenant session object.
Gets all alert rules from a tenant
"""
logger.debug('API - Getting Alert Rules')
res = session.request('GET', '/v2/alert/rule')
data = res.json()
return data |
'''
Base test
'''
def test_index(client):
assert client.get('/').status_code == 302
def test_registration(client):
assert client.post('/registration',
json={"email": "test4@gmail.com", "password": "12345", "name": "PyTest"}).status_code == 200
assert client.post('/registratio... | """
Base test
"""
def test_index(client):
assert client.get('/').status_code == 302
def test_registration(client):
assert client.post('/registration', json={'email': 'test4@gmail.com', 'password': '12345', 'name': 'PyTest'}).status_code == 200
assert client.post('/registration', json={'password': '123... |
sum = 0
for num in range (10):
add = int(input(""))
sum = sum + add
avg = sum / 10
print(avg)
| sum = 0
for num in range(10):
add = int(input(''))
sum = sum + add
avg = sum / 10
print(avg) |
class Employees(object):
_employees = {}
_headcount = 0
def add_employee(self, employee):
self._headcount += 1
self._employees[self._headcount] = employee
def get_employee(self, i):
return self._employees[i]
@property
def headcount(self):
return self._headcount... | class Employees(object):
_employees = {}
_headcount = 0
def add_employee(self, employee):
self._headcount += 1
self._employees[self._headcount] = employee
def get_employee(self, i):
return self._employees[i]
@property
def headcount(self):
return self._headcount |
sm.showFieldEffect("demonSlayer/whiteOut", 0)
sm.sendDelay(1950)
sm.completeQuestNoRewards(23203)
sm.deleteQuest(23203)
sm.curNodeEventEnd(True)
sm.warpInstanceIn(931050300, 0) | sm.showFieldEffect('demonSlayer/whiteOut', 0)
sm.sendDelay(1950)
sm.completeQuestNoRewards(23203)
sm.deleteQuest(23203)
sm.curNodeEventEnd(True)
sm.warpInstanceIn(931050300, 0) |
class Solution:
def leastInterval(self, tasks: List[str], n: int) -> int:
cnt = [0]*26
for i in tasks:
cnt[ord(i)-65] += 1
maxCnt = 0
for i in range(26):
maxCnt = max(maxCnt, cnt[i])
e = 0
for i in range(26):
... | class Solution:
def least_interval(self, tasks: List[str], n: int) -> int:
cnt = [0] * 26
for i in tasks:
cnt[ord(i) - 65] += 1
max_cnt = 0
for i in range(26):
max_cnt = max(maxCnt, cnt[i])
e = 0
for i in range(26):
if cnt[i] == ma... |
# flopy version file automatically created using...pre-commit.py
# created on...October 19, 2018 18:28:49
major = 3
minor = 2
micro = 10
build = 0
commit = 2892
__version__ = '{:d}.{:d}.{:d}'.format(major, minor, micro)
__build__ = '{:d}.{:d}.{:d}.{:d}'.format(major, minor, micro, build)
__git_commit__ = '{:d}'.forma... | major = 3
minor = 2
micro = 10
build = 0
commit = 2892
__version__ = '{:d}.{:d}.{:d}'.format(major, minor, micro)
__build__ = '{:d}.{:d}.{:d}.{:d}'.format(major, minor, micro, build)
__git_commit__ = '{:d}'.format(commit) |
def is_open():
try:
myfile = open("test.JPG", "r+") # or "a+", whatever you need
print("File is not open")
except IOError:
print("Could not open file!")
| def is_open():
try:
myfile = open('test.JPG', 'r+')
print('File is not open')
except IOError:
print('Could not open file!') |
def aumentar(n=0):
return n * 1.5
def diminuir(n=0):
return n * 0.5
def dobro(n=0):
return n * 2
def metade(n=0):
return n / 2
def moeda(n=0):
return f'R${n:.2f}'.replace('.', ',')
| def aumentar(n=0):
return n * 1.5
def diminuir(n=0):
return n * 0.5
def dobro(n=0):
return n * 2
def metade(n=0):
return n / 2
def moeda(n=0):
return f'R${n:.2f}'.replace('.', ',') |
class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
rows = len(image)
cols = len(image[0])
flag = False
if cols%2 != 0:
flag = True
for row in range(rows):
if flag:
image[row][cols//2] = 1 ^ image[ro... | class Solution:
def flip_and_invert_image(self, image: List[List[int]]) -> List[List[int]]:
rows = len(image)
cols = len(image[0])
flag = False
if cols % 2 != 0:
flag = True
for row in range(rows):
if flag:
image[row][cols // 2] = 1 ^ ... |
apic_ip_address = '192.168.1.100'
apic_admin_user = 'admin'
apic_admin_password = 'password'
template_file = 'template.xml'
template_params = '{"tnPrefix": "iPost-light","tnQuant": 10}'
| apic_ip_address = '192.168.1.100'
apic_admin_user = 'admin'
apic_admin_password = 'password'
template_file = 'template.xml'
template_params = '{"tnPrefix": "iPost-light","tnQuant": 10}' |
load("//:import_external.bzl", import_external = "safe_wix_scala_maven_import_external")
def dependencies():
import_external(
name = "aopalliance_aopalliance",
artifact = "aopalliance:aopalliance:1.0",
jar_sha256 = "0addec670fedcd3f113c5c8091d783280d23f75e3acb841b61a9cdb079376a08",
srcjar_sh... | load('//:import_external.bzl', import_external='safe_wix_scala_maven_import_external')
def dependencies():
import_external(name='aopalliance_aopalliance', artifact='aopalliance:aopalliance:1.0', jar_sha256='0addec670fedcd3f113c5c8091d783280d23f75e3acb841b61a9cdb079376a08', srcjar_sha256='e6ef91d439ada9045f419c7754... |
N,A,B,C,D=list(map(int,input().split()))
if N%A == 0:
M = B*(N//A)
else:
M = B*(N//A+1)
if N%C == 0:
M2 = D*(N//C)
else:
M2= D*(N//C+1)
print(min(M,M2)) | (n, a, b, c, d) = list(map(int, input().split()))
if N % A == 0:
m = B * (N // A)
else:
m = B * (N // A + 1)
if N % C == 0:
m2 = D * (N // C)
else:
m2 = D * (N // C + 1)
print(min(M, M2)) |
def millionaire():
answer_list = ['shekspir','pushkik','bunin','bulgakov']
true_answer = 'bulgakov'
print('Otvette na vopros: Kto napisal Master i Margarita?')
print('Varianty otvetov:',answer_list)
help = input('Nujny varianty podskazki?')
if help == 'da':
poll = input('U vas 3 podskazk... | def millionaire():
answer_list = ['shekspir', 'pushkik', 'bunin', 'bulgakov']
true_answer = 'bulgakov'
print('Otvette na vopros: Kto napisal Master i Margarita?')
print('Varianty otvetov:', answer_list)
help = input('Nujny varianty podskazki?')
if help == 'da':
poll = input('U vas 3 pods... |
#
# PySNMP MIB module VIDEOFRAME-SIGMON-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/VIDEOFRAME-SIGMON-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:27:17 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, constraints_union, value_size_constraint, value_range_constraint) ... |
# Created by MechAviv
# Kinesis Introduction
# Map ID :: 331001120
# Hideout :: Training Room 2
JAY = 1531001
sm.spawnMob(2700302, 705, 63, False)
sm.lockForIntro()
sm.forcedFlip(True)
sm.removeAdditionalEffect()
sm.setIntroBoxChat(JAY)
sm.sendNext("#face9#Okay, before we get to the real combat, let me capture a ba... | jay = 1531001
sm.spawnMob(2700302, 705, 63, False)
sm.lockForIntro()
sm.forcedFlip(True)
sm.removeAdditionalEffect()
sm.setIntroBoxChat(JAY)
sm.sendNext('#face9#Okay, before we get to the real combat, let me capture a baseline of your ablities. Destroy Training Robot A there so I can measure your basic power.')
sm.setQ... |
class Solution:
def maxProfit(self, prices: List[int]) -> int:
buy, max_profit = float('inf'), 0
for price in prices:
buy = min(buy, price)
max_profit = max(max_profit, price - buy)
return max_profit
| class Solution:
def max_profit(self, prices: List[int]) -> int:
(buy, max_profit) = (float('inf'), 0)
for price in prices:
buy = min(buy, price)
max_profit = max(max_profit, price - buy)
return max_profit |
def fib(n):
if n <= 1:
return n
else:
return(fib(n-1) + fib(n-2))
item = 3
if item <= 0:
print("Plese enter a +ve integer")
else:
for i in range(item+1):
print(fib(i))
| def fib(n):
if n <= 1:
return n
else:
return fib(n - 1) + fib(n - 2)
item = 3
if item <= 0:
print('Plese enter a +ve integer')
else:
for i in range(item + 1):
print(fib(i)) |
#
# Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved
# Copyright (C) 2018 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://w... | def test(input0, output0, input_data, beta, axis, output_data):
model = model().Operation('LOG_SOFTMAX', input0, beta, axis).To(output0)
example({input0: input_data, output0: output_data}, model=model).AddVariations('relaxed', 'float16')
test(input0=input('input0', 'TENSOR_FLOAT32', '{1, 1, 2, 4}'), output0=out... |
##
##
# File auto-generated by PythonFileGenerator
__all__ = [
'lock',
'message',
'notify',
'request'
]
| __all__ = ['lock', 'message', 'notify', 'request'] |
class Poll():
def __init__(self, id, title, options):
self.id = id
self.title = title
self.options = {op: [] for op in options}
print(self.options)
def vote(self, person, vote):
if vote in self.options:
if not(person in self.options[vote]):
s... | class Poll:
def __init__(self, id, title, options):
self.id = id
self.title = title
self.options = {op: [] for op in options}
print(self.options)
def vote(self, person, vote):
if vote in self.options:
if not person in self.options[vote]:
self... |
# Hook for http://pypi.python.org/pypi/h5py/
# Author: dhyams
# Date: 2011-10-14
# Ticket: #437
hiddenimports = ['_proxy','utils','defs']
| hiddenimports = ['_proxy', 'utils', 'defs'] |
def const(a, b):
def result():
return a
def zilch(b):
return b
return result()
| def const(a, b):
def result():
return a
def zilch(b):
return b
return result() |
#for Job class
#one week
NOTIFICATION_TIMEOUT = 604800
#two weeks
KILL_JOB_DEFAULT_TIMEOUT = 1209600
#Packet`s names policy
IGNORE_DUPLICATE_NAMES_POLICY = 0b001
WARN_DUPLICATE_NAMES_POLICY = 0b010
DENY_DUPLICATE_NAMES_POLICY = 0b100
DEFAULT_DUPLICATE_NAMES_POLICY = DENY_DUPLICATE_NAMES_POLICY
JOB_WATCHER_MAX_DELAY ... | notification_timeout = 604800
kill_job_default_timeout = 1209600
ignore_duplicate_names_policy = 1
warn_duplicate_names_policy = 2
deny_duplicate_names_policy = 4
default_duplicate_names_policy = DENY_DUPLICATE_NAMES_POLICY
job_watcher_max_delay = 2 |
""" Functions which preprocess an audio chunk to improve the accuracy of speech
recognition. """
def __maximize_volume(chunk):
return chunk - chunk.max_dBFS
def improve_accuracy(chunk):
""" Filter chunk through various functions to improve speech recognition """
return __maximize_volume(chunk)
| """ Functions which preprocess an audio chunk to improve the accuracy of speech
recognition. """
def __maximize_volume(chunk):
return chunk - chunk.max_dBFS
def improve_accuracy(chunk):
""" Filter chunk through various functions to improve speech recognition """
return __maximize_volume(chunk) |
file1 = open("paint.in", "r")
line1 = file1.readline()
line2 = file1.readline()
a, b = int(line1.split()[0]), int(line1.split()[1])
c, d = int(line2.split()[0]), int(line2.split()[1])
file1.close()
lst = [*range(1, max(a, b, c, d))]
lenlst = len(lst)
for thing in range(a, b):
if thing in lst:
lst.remov... | file1 = open('paint.in', 'r')
line1 = file1.readline()
line2 = file1.readline()
(a, b) = (int(line1.split()[0]), int(line1.split()[1]))
(c, d) = (int(line2.split()[0]), int(line2.split()[1]))
file1.close()
lst = [*range(1, max(a, b, c, d))]
lenlst = len(lst)
for thing in range(a, b):
if thing in lst:
lst.re... |
'''
Created on Mar 30, 2018
@author: Burkhard A. Meier
'''
def generator_function():
print('before yield')
yield 10 # yield makes it a generator
print('before second yield')
yield 20 # second yield
gen = generator_function() # s... | """
Created on Mar 30, 2018
@author: Burkhard A. Meier
"""
def generator_function():
print('before yield')
yield 10
print('before second yield')
yield 20
gen = generator_function()
print(next(gen))
print(next(gen))
print(next(gen)) |
# -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
class FileOrDirectoryPathFilter(object):
"""Implementation of the 'File or Directory Path Filter.' model.
Specifies filters to match files and directories on a Server.
Two kinds of filters are supported. a) prefix which always starts
with '/'. b... | class Fileordirectorypathfilter(object):
"""Implementation of the 'File or Directory Path Filter.' model.
Specifies filters to match files and directories on a Server.
Two kinds of filters are supported. a) prefix which always starts
with '/'. b) posix which always starts with '*' (cannot be "*" only).... |
"Exceptions raised by the coercion model"
###############################################################################
# Sage: Open Source Mathematical Software
# Copyright (C) 2009 Robert Bradshaw <robertwb@math.washington.edu>
# Distributed under the terms of the GNU General Public License (GPL)
# The f... | """Exceptions raised by the coercion model"""
class Coercionexception(TypeError):
"""
This is the baseclass of exceptions that the coercion model raises
when trying to discover coercions. We do not use standard Python
exceptions to avoid inadvertently catching and suppressing real errors.
Usually ... |
# https://leetcode.com/problems/combination-sum
class Solution:
def combinationSum(self, candidates, target):
output = set()
N = len(candidates)
def backtrack(cur_sum=0, cur_list=[]):
if cur_sum == target:
output.add(tuple(sorted(cur_list[:])))
if c... | class Solution:
def combination_sum(self, candidates, target):
output = set()
n = len(candidates)
def backtrack(cur_sum=0, cur_list=[]):
if cur_sum == target:
output.add(tuple(sorted(cur_list[:])))
if cur_sum < target:
for i in range(... |
# -*- coding: utf-8 -*-
"""
SQL Constants
"""
INSERT_GPKG_CONTENTS_SHORT = """
INSERT INTO gpkg_contents (
table_name, data_type, identifier, description, last_change, srs_id)
VALUES (?, ?, ?, ?, ?, ?)
"""
INSERT_GPKG_OGR_CONTENTS = """
INSERT INTO gpkg_ogr_contents (table_name, feature_count) ... | """
SQL Constants
"""
insert_gpkg_contents_short = '\n INSERT INTO gpkg_contents (\n table_name, data_type, identifier, description, last_change, srs_id) \n VALUES (?, ?, ?, ?, ?, ?)\n'
insert_gpkg_ogr_contents = '\n INSERT INTO gpkg_ogr_contents (table_name, feature_count) VALUES (?, ?)\n'
gpkg_ogr_con... |
class ScheduleMixin(object):
"""Add behavior of a document with a "Schedule" section.
This is use to filter document classes in signal handling.
"""
pass
| class Schedulemixin(object):
"""Add behavior of a document with a "Schedule" section.
This is use to filter document classes in signal handling.
"""
pass |
# -*- coding: utf-8 -*-
""" 03-2022
This sub package holds the screens in ANSI Art used by the game (AU), it
also holds the script to convert the ansi color code in evennia color tags,
and the original ANSI screen.
see README.md for more info.
""" | """ 03-2022
This sub package holds the screens in ANSI Art used by the game (AU), it
also holds the script to convert the ansi color code in evennia color tags,
and the original ANSI screen.
see README.md for more info.
""" |
# -*- coding: utf-8 -*-
"""Top-level package for dwglasso."""
__author__ = """Ryan J. Kinnear"""
__email__ = 'Ryan@Kinnear.ca'
__version__ = '0.1.0'
| """Top-level package for dwglasso."""
__author__ = 'Ryan J. Kinnear'
__email__ = 'Ryan@Kinnear.ca'
__version__ = '0.1.0' |
DEFAULT_SIZE = 128
identity = lambda x: x
regularProbe = lambda hashed, current, n: 7 * current + 1 if n > 0 else hashed
linearProbe = lambda hashed, current, n: hashed + n
quadraticProbe = lambda hashed, current, n: hashed + n * n
pythonProbe = lambda hashed, current, n: 5 * current + 1 + ((hashed >> n) & 0xF)
def re... | default_size = 128
identity = lambda x: x
regular_probe = lambda hashed, current, n: 7 * current + 1 if n > 0 else hashed
linear_probe = lambda hashed, current, n: hashed + n
quadratic_probe = lambda hashed, current, n: hashed + n * n
python_probe = lambda hashed, current, n: 5 * current + 1 + (hashed >> n & 15)
def r... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 20 16:39:21 2021
@author: bartelsaa
"""
# def save_wav_file(raw_audio, folder="data/spec_samples/", normalize=False, plot=False):
# for idx, flac in enumerate(raw_audio): #164157
# flac = matching[0]
# # print(flac)
# fi... | """
Created on Sat Nov 20 16:39:21 2021
@author: bartelsaa
""" |
def main():
t = raw_input()
[r, s, m, d, n] = [int(z) for z in t.split(' ')]
brands = [int(z) for z in raw_input().split(' ')]
S = []
for _ in range(s):
S.append([int(z) for z in raw_input().split(' ')][1:])
M = []
for _ in range(m):
M.append([int(z) for z in raw_input().split(' ')][1:])
D = []
for _ in ... | def main():
t = raw_input()
[r, s, m, d, n] = [int(z) for z in t.split(' ')]
brands = [int(z) for z in raw_input().split(' ')]
s = []
for _ in range(s):
S.append([int(z) for z in raw_input().split(' ')][1:])
m = []
for _ in range(m):
M.append([int(z) for z in raw_input().spli... |
# DP 2D
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
m = len(grid)
n = len(grid[0])
for i in range(1, n):
grid[0][i] += grid[0][i-1]
for i in range(1, m):
grid[i][0] += grid[i-1][0]
for i in range(1, m... | class Solution:
def min_path_sum(self, grid: List[List[int]]) -> int:
m = len(grid)
n = len(grid[0])
for i in range(1, n):
grid[0][i] += grid[0][i - 1]
for i in range(1, m):
grid[i][0] += grid[i - 1][0]
for i in range(1, m):
for j in range... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeKLists(self, lists):
k = len(lists)
vir_node = ListNode(0)
cur_node = vir_node
index = [i for i in range(k)]
while len(ind... | class Listnode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def merge_k_lists(self, lists):
k = len(lists)
vir_node = list_node(0)
cur_node = vir_node
index = [i for i in range(k)]
while len(index) > 0:
min_val = 1 <... |
class FromClass(object):
CLASS_FIELD = 42
def __init__(self):
self.instance_field = 100500
| class Fromclass(object):
class_field = 42
def __init__(self):
self.instance_field = 100500 |
#!/usr/local/bin/python3
def read_input():
with open("input/2018/day8-input.txt", "r") as file:
data = file.read()
return [int(x) for x in data.split(' ')]
def part1(data):
"""
>>> part1(read_input())
37439
"""
data = data.copy()
queue = [True]
metadata = 0
whi... | def read_input():
with open('input/2018/day8-input.txt', 'r') as file:
data = file.read()
return [int(x) for x in data.split(' ')]
def part1(data):
"""
>>> part1(read_input())
37439
"""
data = data.copy()
queue = [True]
metadata = 0
while data:
is_node = queu... |
def save_logs_train(path_to_history, details):
path_to_history = path_to_history + '/__hystoryTrain__.txt'
history = open(path_to_history, "a")
history.write(details + '\n')
history.close()
def save_logs_eval(path_to_history, details):
path_to_history = path_to_history + '/__hystoryEval__.txt'
... | def save_logs_train(path_to_history, details):
path_to_history = path_to_history + '/__hystoryTrain__.txt'
history = open(path_to_history, 'a')
history.write(details + '\n')
history.close()
def save_logs_eval(path_to_history, details):
path_to_history = path_to_history + '/__hystoryEval__.txt'
... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | def load_command_table(self, _):
with self.command_group('oracle') as g:
g.custom_command('cmd1', 'tester1')
g.custom_command('cmd2', 'tester2') |
# noinspection PyPep8Naming
class dotdict(dict):
"""
A convenient dot dict class::
a = dotdict({"argument": "value"})
print (a.argument)
Nested dot documentation is not supported.
"""
def __getattr__(self, attr):
return self.get(attr)
__setattr__ = dict.__setitem__
_... | class Dotdict(dict):
"""
A convenient dot dict class::
a = dotdict({"argument": "value"})
print (a.argument)
Nested dot documentation is not supported.
"""
def __getattr__(self, attr):
return self.get(attr)
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__ |
class Solution:
def bitwiseComplement(self, n: int) -> int:
if n == 0:
return 1
# XOR n (n1) with a n2 which is all 1
n1 = n
num_bits = 0
while n > 0:
num_bits += 1
n = n >> 1
n2 = pow(2, num_bits) - 1
retu... | class Solution:
def bitwise_complement(self, n: int) -> int:
if n == 0:
return 1
n1 = n
num_bits = 0
while n > 0:
num_bits += 1
n = n >> 1
n2 = pow(2, num_bits) - 1
return n1 ^ n2 |
a, b, c, d = input().split()
a = float(a)
b = float(b)
c = float(c)
d = float(d)
media = round((a * 2 + b * 3 + c * 4 + d * 1) / 10, 1)
print(f'Media = {media:.1f}')
if media >= 7:
print('Aluno aprovado.')
elif media >= 5 and media <= 6.9:
print('Aluno em exame.')
e = float(input())
print(f'Nota do exam... | (a, b, c, d) = input().split()
a = float(a)
b = float(b)
c = float(c)
d = float(d)
media = round((a * 2 + b * 3 + c * 4 + d * 1) / 10, 1)
print(f'Media = {media:.1f}')
if media >= 7:
print('Aluno aprovado.')
elif media >= 5 and media <= 6.9:
print('Aluno em exame.')
e = float(input())
print(f'Nota do ex... |
# Nombre de objetos y sus probabilidades
def name_to_file_path(list_of_names):
dictionary_to_return = {}
for name in list_of_names:
dictionary_to_return[name] = name
return dictionary_to_return
background_color = ["normal_1", "normal_2", "normal_3", "normal_4", "normal_5", "normal_6",
... | def name_to_file_path(list_of_names):
dictionary_to_return = {}
for name in list_of_names:
dictionary_to_return[name] = name
return dictionary_to_return
background_color = ['normal_1', 'normal_2', 'normal_3', 'normal_4', 'normal_5', 'normal_6', 'epic_dark_blue']
background_color_weights = [15, 11, 1... |
try:
UNICODE_EXISTS = bool(type(unicode))
except NameError:
unicode = str
| try:
unicode_exists = bool(type(unicode))
except NameError:
unicode = str |
# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
inas = [('ina219', 0x40, 'ap_arm', 1, 0.01, 'loc0', True),
('ina219', 0x41, 'ap_g3d', 1, 0.01, 'loc0', True),
('ina219', 0x42, 'ap_int... | inas = [('ina219', 64, 'ap_arm', 1, 0.01, 'loc0', True), ('ina219', 65, 'ap_g3d', 1, 0.01, 'loc0', True), ('ina219', 66, 'ap_int', 1, 0.1, 'loc0', True), ('ina219', 67, '1350_ldoin', 1.35, 0.1, 'loc0', True), ('ina219', 68, 'ap_mif', 1, 0.1, 'loc0', True), ('ina219', 69, 'ap_kfc', 1, 0.1, 'loc0', True), ('ina219', 70, ... |
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'empty_bundle',
'type': 'loadable_module',
'mac_bundle': 1,
},
{
'target_name': 'resource_bund... | {'targets': [{'target_name': 'empty_bundle', 'type': 'loadable_module', 'mac_bundle': 1}, {'target_name': 'resource_bundle', 'type': 'loadable_module', 'mac_bundle': 1, 'actions': [{'action_name': 'Add Resource', 'inputs': [], 'outputs': ['<(INTERMEDIATE_DIR)/app_manifest/foo.manifest'], 'action': ['touch', '<(INTERMED... |
def min_abs_diff(arr):
arr = sorted(arr)
min_diff = abs(arr[0] - arr[1])
for i in range(1, len(arr) - 1):
diff = abs(arr[i] - arr[i + 1])
if diff < min_diff:
min_diff = diff
return min_diff
| def min_abs_diff(arr):
arr = sorted(arr)
min_diff = abs(arr[0] - arr[1])
for i in range(1, len(arr) - 1):
diff = abs(arr[i] - arr[i + 1])
if diff < min_diff:
min_diff = diff
return min_diff |
class BaconCipher:
def __init__(self):
'''This is python implementation of Bacon Cipher'''
self.bacon_dict = {
'A': 'aaaaa', 'B': 'aaaab', 'C': 'aaaba',
'D': 'aaabb', 'E': 'aabaa', 'F': 'aabab',
'G': 'aabba', 'H': 'aabbb', 'I': 'abaaa',
'J': 'abaab', ... | class Baconcipher:
def __init__(self):
"""This is python implementation of Bacon Cipher"""
self.bacon_dict = {'A': 'aaaaa', 'B': 'aaaab', 'C': 'aaaba', 'D': 'aaabb', 'E': 'aabaa', 'F': 'aabab', 'G': 'aabba', 'H': 'aabbb', 'I': 'abaaa', 'J': 'abaab', 'K': 'ababa', 'L': 'ababb', 'M': 'abbaa', 'N': 'a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.