content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
__author__ = "Manuel Escriche <mev@tid.es>"
class BacklogIssuesModel:
def __init__(self):
self.__entryTypes = ('Epic', 'Feature', 'Story', 'Bug', 'WorkItem')
self.longTermTypes = ('Epic',)
self.midTermTypes = ('Feature',)
self.shortTermTypes = ('Story','Bug','WorkItem')
@proper... | __author__ = 'Manuel Escriche <mev@tid.es>'
class Backlogissuesmodel:
def __init__(self):
self.__entryTypes = ('Epic', 'Feature', 'Story', 'Bug', 'WorkItem')
self.longTermTypes = ('Epic',)
self.midTermTypes = ('Feature',)
self.shortTermTypes = ('Story', 'Bug', 'WorkItem')
@pro... |
# Gitlab-UI: Settings -> General
# https://python-gitlab.readthedocs.io/en/stable/gl_objects/projects.html
# https://docs.gitlab.com/ce/api/projects.html#edit-project
def configure_project_general_settings(project):
print("Configuring general project settings:", project.name)
# Set whether merge requests can only ... | def configure_project_general_settings(project):
print('Configuring general project settings:', project.name)
project.only_allow_merge_if_pipeline_succeeds = True
project.allow_merge_on_skipped_pipeline = False
project.only_allow_merge_if_all_discussions_are_resolved = True
project.merge_method = 'f... |
# Birthday Chocolate
# Given an array of integers, find the number of subarrays of length k having sum s.
#
# https://www.hackerrank.com/challenges/the-birthday-bar/problem
#
def solve(n, s, d, m):
# Complete this function
return sum(1 for i in range(len(s) - m + 1) if sum(s[i:i + m]) == d)
n = int(input()... | def solve(n, s, d, m):
return sum((1 for i in range(len(s) - m + 1) if sum(s[i:i + m]) == d))
n = int(input().strip())
s = list(map(int, input().strip().split(' ')))
(d, m) = input().strip().split(' ')
(d, m) = [int(d), int(m)]
result = solve(n, s, d, m)
print(result) |
# Test changing propagated properties
def test_public_propagation_from_project(data_builder, as_admin):
"""
Tests:
- 'public' is a propagated property
"""
project = data_builder.create_project()
session = data_builder.create_session()
acquisition = data_builder.create_acquisition()
p... | def test_public_propagation_from_project(data_builder, as_admin):
"""
Tests:
- 'public' is a propagated property
"""
project = data_builder.create_project()
session = data_builder.create_session()
acquisition = data_builder.create_acquisition()
payload = {'public': False}
r = as_ad... |
logFile = open("log.log", "r")
#print("score time")
#line = logFile.readline()
#line = "line"
i = 0
for line in logFile:
i += 1
if (i % 1 != 0): # Rendering all points takes time in LaTeX, skip some
continue
words = line.split()
score = words[0]
time = words[2].replace("s", "")
minutes... | log_file = open('log.log', 'r')
i = 0
for line in logFile:
i += 1
if i % 1 != 0:
continue
words = line.split()
score = words[0]
time = words[2].replace('s', '')
minutes = int(time) / 60.0
print(score + ' ' + i + '')
logFile.close() |
{
"variables": {
"gypkg_deps": [
# Place for `gypkg` dependencies
"git://github.com/libuv/libuv@^1.7.0 => uv.gyp:libuv",
],
},
"targets": [ {
"target_name": "latetyper",
"type": "executable",
"dependencies": [
"<!@(gypkg deps <(gypkg_deps))",
# Place for local depende... | {'variables': {'gypkg_deps': ['git://github.com/libuv/libuv@^1.7.0 => uv.gyp:libuv']}, 'targets': [{'target_name': 'latetyper', 'type': 'executable', 'dependencies': ['<!@(gypkg deps <(gypkg_deps))'], 'direct_dependent_settings': {'include_dirs': ['include']}, 'include_dirs': ['.'], 'sources': ['src/main.c'], 'librarie... |
grid = []
for r in range(20):
row = [int(x) for x in input().split(' ')]
grid.append(row)
mx = 0
for i in range(20):
for j in range(17):
prod = grid[i][j] * grid[i][j+1] * grid[i][j+2] * grid[i][j+3]
if prod > mx:
mx = prod
prod = grid[j][i] * grid[j+1][i] * grid[j+2][i]... | grid = []
for r in range(20):
row = [int(x) for x in input().split(' ')]
grid.append(row)
mx = 0
for i in range(20):
for j in range(17):
prod = grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3]
if prod > mx:
mx = prod
prod = grid[j][i] * grid[j + 1][i] * grid[... |
"""
Immutable data structures.
The classes in this module have the prefix 'immutable' to avoid confusion
with the built-in ``frozenset``, which does not have any modification methods,
even pure ones.
"""
class immutabledict(dict):
"""
An immutable version of ``dict``.
Mutating syntax (``del d[k]``, ``d[... | """
Immutable data structures.
The classes in this module have the prefix 'immutable' to avoid confusion
with the built-in ``frozenset``, which does not have any modification methods,
even pure ones.
"""
class Immutabledict(dict):
"""
An immutable version of ``dict``.
Mutating syntax (``del d[k]``, ``d[k... |
def problem4_1(wordlist):
print(wordlist)
wordlist.sort(key=str.lower)
print(wordlist)
#firstline = ["Happy", "families", "are", "all", "alike;", "every", \
# "unhappy", "family", "is", "unhappy", "in", "its", "own", \
# "way.", "Leo Tolstoy", "Anna Karenina"]
#problem4_1(firstline)
| def problem4_1(wordlist):
print(wordlist)
wordlist.sort(key=str.lower)
print(wordlist) |
# 1346. Check If N and Its Double Exist
# Runtime: 40 ms, faster than 98.82% of Python3 online submissions for Check If N and Its Double Exist.
# Memory Usage: 14.4 MB, less than 9.05% of Python3 online submissions for Check If N and Its Double Exist.
class Solution:
def checkIfExist(self, arr: list[int]) -> bo... | class Solution:
def check_if_exist(self, arr: list[int]) -> bool:
prev = set()
for (i, n) in enumerate(arr):
if n * 2 in prev or n * 0.5 in prev:
return True
if n not in prev:
prev.add(n)
return False |
class Subject:
def __init__(self):
self.observers = []
def attach(self, observer):
if observer not in self.observers:
self.observers.append(observer)
def detach(self, observer):
try:
self.observers.remove(observer)
except Exception as e:
... | class Subject:
def __init__(self):
self.observers = []
def attach(self, observer):
if observer not in self.observers:
self.observers.append(observer)
def detach(self, observer):
try:
self.observers.remove(observer)
except Exception as e:
... |
class PropertyCheckResult:
def __init__(self, name: str):
self.name = name
def __str__(self):
return self.name
def __repr__(self):
return f"PropertyCheckResult({self.name})"
def __invert__(self):
if self == UNSAT:
return SAT
if self == SAT:
... | class Propertycheckresult:
def __init__(self, name: str):
self.name = name
def __str__(self):
return self.name
def __repr__(self):
return f'PropertyCheckResult({self.name})'
def __invert__(self):
if self == UNSAT:
return SAT
if self == SAT:
... |
d=dict(one=1,two=2,three=3)
print(d)
'''for k in d:
print(k,d[k])
for k in sorted(d.keys()): #isme key ki help se d[k] nikaalre h
print(k,d[k])
for k,v in sorted(d.items()): #k and v(value) dono ek hi baar lene h to without dictionary help
print(k,v)
for v in sorted(d.values()):
print(v)... | d = dict(one=1, two=2, three=3)
print(d)
'for k in d:\n print(k,d[k])\nfor k in sorted(d.keys()): #isme key ki help se d[k] nikaalre h\n print(k,d[k])\nfor k,v in sorted(d.items()): #k and v(value) dono ek hi baar lene h to without dictionary help\n print(k,v)\nfor v in sorted(d.values()):\n ... |
#
# Copyright (c) 2017 Amit Green. All rights reserved.
#
@gem('Gem.ErrorNumber')
def gem():
require_gem('Gem.Import')
PythonErrorNumber = import_module('errno')
export(
'ERROR_NO_ACCESS', PythonErrorNumber.EACCES,
'ERROR_NO_ENTRY', PythonErrorNumber.ENOENT,
)
| @gem('Gem.ErrorNumber')
def gem():
require_gem('Gem.Import')
python_error_number = import_module('errno')
export('ERROR_NO_ACCESS', PythonErrorNumber.EACCES, 'ERROR_NO_ENTRY', PythonErrorNumber.ENOENT) |
class colors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
WHITE = '\033[1;97m'
def banner():
version = "0.6.0"
githublink = "https://github.com/f0lg0/Oncogene"
... | class Colors:
header = '\x1b[95m'
okblue = '\x1b[94m'
okgreen = '\x1b[92m'
warning = '\x1b[93m'
fail = '\x1b[91m'
endc = '\x1b[0m'
bold = '\x1b[1m'
underline = '\x1b[4m'
white = '\x1b[1;97m'
def banner():
version = '0.6.0'
githublink = 'https://github.com/f0lg0/Oncogene'
... |
cube = []
for value in range(1, 11):
cube_value = value**3
cube.append(cube_value)
print(cube)
| cube = []
for value in range(1, 11):
cube_value = value ** 3
cube.append(cube_value)
print(cube) |
# We create an arr dp which hold max val till that point. At each i, max_val = max(dp[i-2] + nums[i], dp[i-1])
class Solution:
def rob(self, nums: List[int]) -> int:
if not nums:
return 0
if len(nums)<2:
return max(nums)
dp = [0]*len(nums)
... | class Solution:
def rob(self, nums: List[int]) -> int:
if not nums:
return 0
if len(nums) < 2:
return max(nums)
dp = [0] * len(nums)
dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])
for i in range(2, len(nums)):
dp[i] = max(dp[i - 2] ... |
def to_pascal_case(string):
return ''.join([w.title() for w in string.split('_')])
| def to_pascal_case(string):
return ''.join([w.title() for w in string.split('_')]) |
print('''
*******************************************************************************
| | | |
_________|________________.=""_;=.______________|_____________________|_______
| | ,-"_,="" `"=.| |
|_______________... | print('\n*******************************************************************************\n | | | |\n _________|________________.=""_;=.______________|_____________________|_______\n| | ,-"_,="" `"=.| |\n|____________... |
"""
**********************************************************************************
Name: constants
Purpose: Holds common constants used throughout the application
**********************************************************************************
"""
#------------------------------------
# HTTP Response codes
#-... | """
**********************************************************************************
Name: constants
Purpose: Holds common constants used throughout the application
**********************************************************************************
"""
http_methods_get = 'GET'
http_methods_post = 'POST'
http_methods... |
# Approach 3 - Two Pointers
# Time: O(n^2)
# Space: O(1)
class Solution:
def threeSumSmaller(self, nums: List[int], target: int) -> int:
nums.sort()
total = 0
for i in range(len(nums)-1):
total += self.twoSumSmaller(nums, i + 1, target - nums[i])
r... | class Solution:
def three_sum_smaller(self, nums: List[int], target: int) -> int:
nums.sort()
total = 0
for i in range(len(nums) - 1):
total += self.twoSumSmaller(nums, i + 1, target - nums[i])
return total
def two_sum_smaller(self, nums, start_index, target):
... |
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
print(alien_0['color'])
print(alien_0['points'])
new_points = alien_0['points']
print("You just earned " + str(new_points) + " points!")
| alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
print(alien_0['color'])
print(alien_0['points'])
new_points = alien_0['points']
print('You just earned ' + str(new_points) + ' points!') |
A = int(input())
B = int(input())
C = int(input())
X = int(input())
count = 0
for a in range(A+1):
for b in range(B+1):
for c in range(C+1):
if 500*a + 100*b + 50*c == X:
count +=1
print(count)
| a = int(input())
b = int(input())
c = int(input())
x = int(input())
count = 0
for a in range(A + 1):
for b in range(B + 1):
for c in range(C + 1):
if 500 * a + 100 * b + 50 * c == X:
count += 1
print(count) |
def test_model_piecewise(classifier, filename, batch_size):
"""
same as test_model but reads input file line by line
Predict class labels of given data using the model learned.
INPUTS:
classifier_trained: object of MLP, the model learned by function "train_model".
filename: file locat... | def test_model_piecewise(classifier, filename, batch_size):
"""
same as test_model but reads input file line by line
Predict class labels of given data using the model learned.
INPUTS:
classifier_trained: object of MLP, the model learned by function "train_model".
filename: file locat... |
class Solution(object):
def reverse(self,s):
return s[::-1]
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
strs = s.split(' ')
strs = map(self.reverse, strs)
return ' '.join(strs) | class Solution(object):
def reverse(self, s):
return s[::-1]
def reverse_words(self, s):
"""
:type s: str
:rtype: str
"""
strs = s.split(' ')
strs = map(self.reverse, strs)
return ' '.join(strs) |
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
head = 0
temp = ""
tail = len(s) - 1
while head < tail:
temp = s[head]
s[head] = s[tail]
s[tail] = tem... | class Solution:
def reverse_string(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
head = 0
temp = ''
tail = len(s) - 1
while head < tail:
temp = s[head]
s[head] = s[tail]
s[tail] = t... |
"""
Interface with Pleiades
"""
class Pleiades:
def __init__(self):
return
| """
Interface with Pleiades
"""
class Pleiades:
def __init__(self):
return |
a, b, c = map(int, input().split())
numbers = [a, b, c]
numbers.sort()
print(" ".join(str(number) for number in numbers))
| (a, b, c) = map(int, input().split())
numbers = [a, b, c]
numbers.sort()
print(' '.join((str(number) for number in numbers))) |
def binarySearch(ar, n, key):
lb = 0
ub = n
while lb <= ub:
mid = int((lb + ub) / 2)
if ar[mid] == key:
return mid
if ar[mid] > key:
ub = mid - 1
else:
lb = mid + 1
print('!!Value Not Found!!')
return -1
# Test Code
ar = [1, 4, 6... | def binary_search(ar, n, key):
lb = 0
ub = n
while lb <= ub:
mid = int((lb + ub) / 2)
if ar[mid] == key:
return mid
if ar[mid] > key:
ub = mid - 1
else:
lb = mid + 1
print('!!Value Not Found!!')
return -1
ar = [1, 4, 6, 8, 10, 12]
n... |
#MAIN PROGRAM STARTS HERE:
num = int(input('Enter the number of rows and columns for the square: '))
for x in range(num, 0, -1):
for y in range(num, 0, -1):
print ('%d ' % (y), end='')
print() | num = int(input('Enter the number of rows and columns for the square: '))
for x in range(num, 0, -1):
for y in range(num, 0, -1):
print('%d ' % y, end='')
print() |
def validBraces(string):
while len(string) !=0:
if '{}' in string or '[]' in string or '()' in string:
string = string.replace('{}','').replace('()','').replace('[]','')
else:
return False
return True | def valid_braces(string):
while len(string) != 0:
if '{}' in string or '[]' in string or '()' in string:
string = string.replace('{}', '').replace('()', '').replace('[]', '')
else:
return False
return True |
"""
Tools to work with the webhooks data files.
A copy of those data files is expected at the `openedx_webhooks.info.DATA_FILES_URL_BASE` location.
"""
| """
Tools to work with the webhooks data files.
A copy of those data files is expected at the `openedx_webhooks.info.DATA_FILES_URL_BASE` location.
""" |
def resolve():
'''
code here
'''
N, M = [int(item) for item in input().split()]
As = [[int(item) for item in input().split()] for _ in range(N)]
memo = [0 for _ in range(M+1)]
for k, *items in As:
for item in items:
memo[item] += 1
res = 0
for item in memo:
... | def resolve():
"""
code here
"""
(n, m) = [int(item) for item in input().split()]
as = [[int(item) for item in input().split()] for _ in range(N)]
memo = [0 for _ in range(M + 1)]
for (k, *items) in As:
for item in items:
memo[item] += 1
res = 0
for item in memo:
... |
noc_config = [
["c", "c"],
["c", "c"],
["n", "v"],
#["c", "n"],
]
| noc_config = [['c', 'c'], ['c', 'c'], ['n', 'v']] |
class Thing:
def __init__(self, primary_noun, countable=True):
self.primary_noun = primary_noun
self.countable = countable
class Container(Thing):
def __init__(self, primary_noun, countable=True, preposition="on"):
super().__init__(primary_noun, countable)
self.preposition = pre... | class Thing:
def __init__(self, primary_noun, countable=True):
self.primary_noun = primary_noun
self.countable = countable
class Container(Thing):
def __init__(self, primary_noun, countable=True, preposition='on'):
super().__init__(primary_noun, countable)
self.preposition = p... |
# loops over all collection data, converts to true if collection - false if not part of collection
def collection_to_boolean(data_frame):
# Data should be available as str (see Kaggle Webpage)
data_frame.belongs_to_collection = data_frame.belongs_to_collection.astype(str)
# Looping over Data to convert to... | def collection_to_boolean(data_frame):
data_frame.belongs_to_collection = data_frame.belongs_to_collection.astype(str)
data_frame['belongs_to_collection'] = (data_frame['belongs_to_collection'] != 'nan').astype(int)
data_frame.belongs_to_collection = data_frame.belongs_to_collection.astype(bool)
return ... |
"""Modulo node."""
class Node:
"""Gerencia items da fila."""
def __init__(self, data):
self.data = data
self.next = None | """Modulo node."""
class Node:
"""Gerencia items da fila."""
def __init__(self, data):
self.data = data
self.next = None |
#var 1
div1 = [num for num in range(1, 11) if num % 2 != 0 and num % 3 != 0]
print(f"Not divisible by 2 and 3: {div1}")
div2 = [num for num in range(1, 11) if num % 2 == 0]
print(f"Divisible by 2: {div2}")
div3 = [num for num in range (1, 11) if num % 3 == 0]
print(f"Divisible by 3: {div3}")
input()
#var 2
for num i... | div1 = [num for num in range(1, 11) if num % 2 != 0 and num % 3 != 0]
print(f'Not divisible by 2 and 3: {div1}')
div2 = [num for num in range(1, 11) if num % 2 == 0]
print(f'Divisible by 2: {div2}')
div3 = [num for num in range(1, 11) if num % 3 == 0]
print(f'Divisible by 3: {div3}')
input()
for num in range(1, 11):
... |
"""complex-valued trig functions adapted from SciPy's cython code:
https://github.com/scipy/scipy/blob/master/scipy/special/_trig.pxd
Note: The CUDA Math library defines the real-valued cospi, sinpi
"""
csinpi_definition = """
#include <cupy/math_constants.h>
// Compute sin(pi*z) for complex arguments
__device__ ... | """complex-valued trig functions adapted from SciPy's cython code:
https://github.com/scipy/scipy/blob/master/scipy/special/_trig.pxd
Note: The CUDA Math library defines the real-valued cospi, sinpi
"""
csinpi_definition = '\n\n#include <cupy/math_constants.h>\n\n// Compute sin(pi*z) for complex arguments\n\n__device... |
pkgname = "traceroute"
pkgver = "2.1.0"
pkgrel = 0
build_style = "makefile"
make_cmd = "gmake"
make_build_args = ["prefix=/usr"]
make_install_args = ["prefix=/usr"]
hostmakedepends = ["gmake"]
makedepends = ["linux-headers"]
pkgdesc = "Traces the route taken by packets over an IPv4/IPv6 network"
maintainer = "q66 <q66@... | pkgname = 'traceroute'
pkgver = '2.1.0'
pkgrel = 0
build_style = 'makefile'
make_cmd = 'gmake'
make_build_args = ['prefix=/usr']
make_install_args = ['prefix=/usr']
hostmakedepends = ['gmake']
makedepends = ['linux-headers']
pkgdesc = 'Traces the route taken by packets over an IPv4/IPv6 network'
maintainer = 'q66 <q66@... |
a=int(input("enter the element"))
b=int(input("enter the element"))
c=int(input("enter the element"))
n1=[]
n2=[]
n3=[]
n1.append(a)
n2.append(b)
n3.append(c)
if n1>n2 and n1>n3:
print(n1,"maximum")
elif n2>n1 and n2>n3:
print(n2,"maximum")
else:
print(n3,"maximum") | a = int(input('enter the element'))
b = int(input('enter the element'))
c = int(input('enter the element'))
n1 = []
n2 = []
n3 = []
n1.append(a)
n2.append(b)
n3.append(c)
if n1 > n2 and n1 > n3:
print(n1, 'maximum')
elif n2 > n1 and n2 > n3:
print(n2, 'maximum')
else:
print(n3, 'maximum') |
{
'name': 'test installation of data module',
'description': 'Test data module (see test_data_module) installation',
'version': '0.0.1',
'category': 'Hidden/Tests',
'sequence': 10,
}
| {'name': 'test installation of data module', 'description': 'Test data module (see test_data_module) installation', 'version': '0.0.1', 'category': 'Hidden/Tests', 'sequence': 10} |
"""Functionality for computing the error between exact and approximate values."""
def absolute_error(x0, x):
"""
Compute absolute error between a value `x` and its expected value `x0`.
:param x0: Expected value.
:param x: Actual value.
:return: Absolute error between the actual and expected value... | """Functionality for computing the error between exact and approximate values."""
def absolute_error(x0, x):
"""
Compute absolute error between a value `x` and its expected value `x0`.
:param x0: Expected value.
:param x: Actual value.
:return: Absolute error between the actual and expected value.... |
class Solution:
@staticmethod
def longest_palindromic(self, s: str) -> str:
# Instead of taking the left and right edges of the string
# We will start in the middle of the string
# Making base function to help us in the method and pass in 'l' and 'r' parameters
def baseFun ... | class Solution:
@staticmethod
def longest_palindromic(self, s: str) -> str:
def base_fun(l, r):
while l >= 0 and r < len(s) and (s[l] == s[r]):
l -= 1
r += 1
return s[l + 1:r]
res = ''
for i in range(len(s)):
test = ba... |
# model settings
norm_cfg = dict(type='GN', num_groups=32, requires_grad=True)
model = dict(
type='CFADetector',
pretrained='torchvision://resnet50',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dic... | norm_cfg = dict(type='GN', num_groups=32, requires_grad=True)
model = dict(type='CFADetector', pretrained='torchvision://resnet50', backbone=dict(type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), style='pytorch'), neck=dict(type='FPN', in_cha... |
# -*- coding: utf-8 -*-
class BaseContext:
headers = {}
def __init__(self, **kwargs):
self.headers = {}
def on_auth(self):
pass
def update_authkey(self, authkey):
pass
def set_authkey(self, authkey):
self.headers["X-Authorization-Update"] = "Bearer {0}".format(a... | class Basecontext:
headers = {}
def __init__(self, **kwargs):
self.headers = {}
def on_auth(self):
pass
def update_authkey(self, authkey):
pass
def set_authkey(self, authkey):
self.headers['X-Authorization-Update'] = 'Bearer {0}'.format(authkey) |
class BaseDeDados:
def __init__(self):#init eh o mais proximo de um construtor e vamos adicionar ao dicionario o banco de dados
self.dados = {}
def inserir_cliente(self, id, nome):
if 'clientes' not in self.dados:#se a informacao nao tiver na base de dados
self.dados['clientes'] = {... | class Basededados:
def __init__(self):
self.dados = {}
def inserir_cliente(self, id, nome):
if 'clientes' not in self.dados:
self.dados['clientes'] = {id: nome}
else:
self.dados['clientes'].update({id: nome})
def lista_clientes(self):
for (id, nome)... |
def langInit(jsonDir,json):
fop=open(jsonDir,'r')
lang=fop.read()
fop.close()
lang=json.loads(lang)
#print(lang)
return lang
| def lang_init(jsonDir, json):
fop = open(jsonDir, 'r')
lang = fop.read()
fop.close()
lang = json.loads(lang)
return lang |
class Solution:
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
def dfs(idx, csum):
record.append(None)
for i in range(idx, len(candidates)):
record[-1... | class Solution:
def combination_sum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
def dfs(idx, csum):
record.append(None)
for i in range(idx, len(candidates)):
record[... |
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
row, col = len(board), len(board[0])
def dfs(i, j):
nonlocal row, col, board
if i < 0 or i >= row or j < 0 or j >= ... | class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
(row, col) = (len(board), len(board[0]))
def dfs(i, j):
nonlocal row, col, board
if i < 0 or i >= row or j < 0 or (j >= co... |
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | """General interface of an RL agent.
The classes implements this class need to support the following interfaces:
1. random_action(observation), given an observation return a random action.
2. action(observation), given an observation return an action from the policy.
3. train(global_step), improves the agents internal... |
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 02 05:35:25 2014
@author: perez
"""
##
# MongoDB config
config_mongoURI = 'mongodb://localhost:27017/'
config_db_name = 'test_database'
##
# Meteo API config
config_openWeatherMapAPIKey = '53c2d72826f2215d60c154f657ddb923'
| """
Created on Sat Aug 02 05:35:25 2014
@author: perez
"""
config_mongo_uri = 'mongodb://localhost:27017/'
config_db_name = 'test_database'
config_open_weather_map_api_key = '53c2d72826f2215d60c154f657ddb923' |
# closure Example
def counter(n):
def next():
nonlocal n
r = n
n -= 1
# print(next.__globals__)
print(type(next.__globals__))
for val in next.__globals__:
print(type(val), val)
return r
return next
next = counter(10)
print(next())
# print(... | def counter(n):
def next():
nonlocal n
r = n
n -= 1
print(type(next.__globals__))
for val in next.__globals__:
print(type(val), val)
return r
return next
next = counter(10)
print(next())
print(next())
print(next())
print(next())
print(next()) |
#
# PySNMP MIB module IF-CAP-STACK-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IF-CAP-STACK-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:53:07 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, value_range_constraint, single_value_constraint, value_size_constraint) ... |
#
# PySNMP MIB module Nortel-MsCarrier-MscPassport-TrunksMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-MsCarrier-MscPassport-TrunksMIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:19:50 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, constraints_union, value_range_constraint, single_value_constraint) ... |
class Solution:
def findLatestStep(self, arr: List[int], m: int) -> int:
n = len(arr)
parent, size, result, bitsArray, count = [x for x in range(n)], [1] * n, -1, [0] * n, Counter()
def find(x):
if parent[x] == x:
return x
else:
... | class Solution:
def find_latest_step(self, arr: List[int], m: int) -> int:
n = len(arr)
(parent, size, result, bits_array, count) = ([x for x in range(n)], [1] * n, -1, [0] * n, counter())
def find(x):
if parent[x] == x:
return x
else:
... |
def ask_name():
name = input("Write your name: ")
return name
def go_through(name):
for i in name:
print(i)
print("\n")
def go_Through_(name):
for i in name:
print(i.upper())
print("\n")
def run():
n = ask_name()
go_through(n)
go_Through_(n)
if __name__ =... | def ask_name():
name = input('Write your name: ')
return name
def go_through(name):
for i in name:
print(i)
print('\n')
def go__through_(name):
for i in name:
print(i.upper())
print('\n')
def run():
n = ask_name()
go_through(n)
go__through_(n)
if __name__ == '__mai... |
class Solution(object):
def findLUSlength(self, strs):
"""
:type strs: List[str]
:rtype: int
"""
| class Solution(object):
def find_lu_slength(self, strs):
"""
:type strs: List[str]
:rtype: int
""" |
def generate_exclusion_list(hls_input_file,exclusion_list_file):
file_lines = []
with open(hls_input_file,'r') as input_file:
file_lines = input_file.readlines()
r_list = []
with open(hls_input_file,'w') as clean_code:
for i,x in enumerate(file_lines):
if "@" in x:
... | def generate_exclusion_list(hls_input_file, exclusion_list_file):
file_lines = []
with open(hls_input_file, 'r') as input_file:
file_lines = input_file.readlines()
r_list = []
with open(hls_input_file, 'w') as clean_code:
for (i, x) in enumerate(file_lines):
if '@' in x:
... |
# Easy
# https://leetcode.com/problems/same-tree/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# Time Complexity: O(N)
# Space Complexity: O(tree height)
class Solutio... | class Solution:
def is_same_tree(self, p: TreeNode, q: TreeNode) -> bool:
return self.helper(p, q)
def helper(self, node1, node2):
if node1 and (not node2) or (node2 and (not node1)):
return False
elif node1 and node2:
if not self.helper(node1.left, node2.left):... |
# -*- coding: utf-8 -*-
"""
Auto-generated file 2022-04-22 09:25:28 UTC
Resource: https://github.com/google/libphonenumber v8.12.47
"""
PATTERNS = {
"info": "libphonenumber v8.12.47",
"data": {
"AC": {
"code": "247",
"pattern": "((6[2-467][\\d]{3}))",
"mobile": "((4... | """
Auto-generated file 2022-04-22 09:25:28 UTC
Resource: https://github.com/google/libphonenumber v8.12.47
"""
patterns = {'info': 'libphonenumber v8.12.47', 'data': {'AC': {'code': '247', 'pattern': '((6[2-467][\\d]{3}))', 'mobile': '((4[\\d]{4}))'}, 'AD': {'code': '376', 'pattern': '(([78][\\d]{5}))', 'mobile': '((6... |
stack = []
def isEmpty(stack):
if stack == []:
return True
else:
return False
def push(stack):
item = int(input("enter value"))
stack.append(item)
top = len(stack)-1
def pop(stack):
if isEmpty(stack):
print("underflow")
else:
item=stack.pop()... | stack = []
def is_empty(stack):
if stack == []:
return True
else:
return False
def push(stack):
item = int(input('enter value'))
stack.append(item)
top = len(stack) - 1
def pop(stack):
if is_empty(stack):
print('underflow')
else:
item = stack.pop()
... |
class PyVEXError(Exception):
pass
class SkipStatementsError(PyVEXError):
pass
#
# Exceptions and notifications that post-processors can raise
#
class LiftingException(Exception):
pass
class NeedStatementsNotification(LiftingException):
"""
A post-processor may raise a NeedStatementsNotifica... | class Pyvexerror(Exception):
pass
class Skipstatementserror(PyVEXError):
pass
class Liftingexception(Exception):
pass
class Needstatementsnotification(LiftingException):
"""
A post-processor may raise a NeedStatementsNotification if it needs to work with statements, but the current IRSB
is ge... |
#coding: latin1
#< full
class CYKParser:
def __init__(self, P: "IList<(str, str) or (str)>", S: "str",
createMap: "IList<(str, str), int -> IMap<int, int, str>"=lambda P, n: dict()):
self.P, self.S = P, S
self.createMap = createMap
def accepts(self, x: "str") -> "boo... | class Cykparser:
def __init__(self, P: 'IList<(str, str) or (str)>', S: 'str', createMap: 'IList<(str, str), int -> IMap<int, int, str>'=lambda P, n: dict()):
(self.P, self.S) = (P, S)
self.createMap = createMap
def accepts(self, x: 'str') -> 'bool':
n = len(x)
pi = self.create... |
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
z = 0
for i in range(1, len(nums)):
if nums[i] != 0 and nums[z] == 0:
nums[i], nums[z] = nums[z], nums[i]
if nums[z] != 0:
z += 1
| class Solution:
def move_zeroes(self, nums: List[int]) -> None:
z = 0
for i in range(1, len(nums)):
if nums[i] != 0 and nums[z] == 0:
(nums[i], nums[z]) = (nums[z], nums[i])
if nums[z] != 0:
z += 1 |
# problem 18
# Project Euler
__author__ = 'Libao Jin'
__date__ = 'July 17, 2015'
string = '''
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39... | __author__ = 'Libao Jin'
__date__ = 'July 17, 2015'
string = '\n75\n95 64\n17 47 82\n18 35 87 10\n20 04 82 47 65\n19 01 23 75 03 34\n88 02 77 73 07 63 67\n99 65 04 28 06 16 70 92\n41 41 26 56 83 40 80 70 33\n41 48 72 33 47 32 37 16 94 29\n53 71 44 65 25 43 91 52 97 51 14\n70 11 33 28 77 73 17 78 39 68 17 57\n91 71 52 3... |
class MockCache(object):
"""
Simple cache to use for mocking Memcached
"""
def __init__(self):
super(MockCache, self).__init__()
self._cache = {}
def set(self, k, v):
self._cache[k] = v
return True
def get(self, k, default=None):
return self._cache.get(k... | class Mockcache(object):
"""
Simple cache to use for mocking Memcached
"""
def __init__(self):
super(MockCache, self).__init__()
self._cache = {}
def set(self, k, v):
self._cache[k] = v
return True
def get(self, k, default=None):
return self._cache.get(... |
# File: T (Python 2.4)
SKY_OFF = 0
SKY_LAST = 1
SKY_DAWN = 2
SKY_DAY = 3
SKY_DUSK = 4
SKY_NIGHT = 5
SKY_STARS = 6
SKY_HALLOWEEN = 7
SKY_SWAMP = 8
SKY_INVASION = 9
SKY_OVERCAST = 10
SKY_OVERCASTNIGHT = 11
SKY_CODES = {
SKY_OFF: 'SKY_OFF',
SKY_LAST: 'SKY_LAST',
SKY_DAWN: 'SKY_DAWN',
SKY_DAY: 'SKY_DAY',
... | sky_off = 0
sky_last = 1
sky_dawn = 2
sky_day = 3
sky_dusk = 4
sky_night = 5
sky_stars = 6
sky_halloween = 7
sky_swamp = 8
sky_invasion = 9
sky_overcast = 10
sky_overcastnight = 11
sky_codes = {SKY_OFF: 'SKY_OFF', SKY_LAST: 'SKY_LAST', SKY_DAWN: 'SKY_DAWN', SKY_DAY: 'SKY_DAY', SKY_DUSK: 'SKY_DUSK', SKY_NIGHT: 'SKY_NIGH... |
def main():
with open('triangles.txt') as f:
lines = f.read().splitlines()
counts = 0
for line in lines:
points = line.split(',')
points = [int(point) for point in points]
A = points[:2]
B = points[2:4]
C = points[4:]
P = (0, 0)
if area(A, B, ... | def main():
with open('triangles.txt') as f:
lines = f.read().splitlines()
counts = 0
for line in lines:
points = line.split(',')
points = [int(point) for point in points]
a = points[:2]
b = points[2:4]
c = points[4:]
p = (0, 0)
if area(A, B, C... |
# SinglyLinkedListNode:
# int data
# SinglyLinkedListNode next
#
#
def findMergeNode(head1, head2):
# the data on the linked list nodes might not be unique
# we can't rely on just checking the data in each node
# as with any node-based data structure, each node is a unique
# region in memory ... | def find_merge_node(head1, head2):
curr = head1
s = set()
while curr:
s.add(curr)
curr = curr.next
curr = head2
while curr:
if curr in s:
return curr.data
curr = curr.next |
test = {
'name': '',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
>>> # Make sure your column labels are correct
>>> estimates.labels == ('min estimate', 'mean-based estimate')
True
""",
'hidden': False,
'locked': Fal... | test = {'name': '', 'points': 1, 'suites': [{'cases': [{'code': "\n >>> # Make sure your column labels are correct\n >>> estimates.labels == ('min estimate', 'mean-based estimate')\n True\n\n ", 'hidden': False, 'locked': False}, {'code': "\n >>> abs(14 - np.mean(estimates.c... |
layers = {
"title": "DEA Water Observations",
"abstract": "Digital Earth Australia (DEA) Water Observations from Space (WOfS)",
"layers": [
{
"include": "ows_refactored.inland_water.wofs.individual.ows_c3_wo_cfg.layer",
"type": "python",
},
{
"inc... | layers = {'title': 'DEA Water Observations', 'abstract': 'Digital Earth Australia (DEA) Water Observations from Space (WOfS)', 'layers': [{'include': 'ows_refactored.inland_water.wofs.individual.ows_c3_wo_cfg.layer', 'type': 'python'}, {'include': 'ows_refactored.inland_water.wofs.individual.ows_s2_wo_cfg.layer', 'type... |
class FunnyRect():
def setCenter(self, x,y):
self.cx = x
self.cy = y
def setSize(self, a):
self.a = a
def render(self):
rect(self.cx, self.cy, self.a, self.a)
def colors(self,b):
fill(b)
funnyRect = FunnyRect()
funnyRect1 = FunnyRect()
counter = 0
d... | class Funnyrect:
def set_center(self, x, y):
self.cx = x
self.cy = y
def set_size(self, a):
self.a = a
def render(self):
rect(self.cx, self.cy, self.a, self.a)
def colors(self, b):
fill(b)
funny_rect = funny_rect()
funny_rect1 = funny_rect()
counter = 0
def s... |
class MyCustomClass:
prop1 = 1
prop2 = "a"
prop3 = {1, 2, 3}
def test_snapshot_custom_class(snapshot):
assert MyCustomClass() == snapshot
class MyCustomReprClass(MyCustomClass):
def __repr__(self):
state = "\n".join(
f" {a}={repr(getattr(self, a))},"
for a in sor... | class Mycustomclass:
prop1 = 1
prop2 = 'a'
prop3 = {1, 2, 3}
def test_snapshot_custom_class(snapshot):
assert my_custom_class() == snapshot
class Mycustomreprclass(MyCustomClass):
def __repr__(self):
state = '\n'.join((f' {a}={repr(getattr(self, a))},' for a in sorted(dir(self)) if not a... |
ll = []
print(ll) # immutable operation
ll.append(1) # mutable operation
ll.insert(0, -1) # mutable operation
print(ll[0]) # immutable operation
print(ll) # immutable operation
ll.pop() # mutable operation
print(ll) # immutable operation
ll[0] = -111 # mutable operation
print(ll) # immutable operation
tt ... | ll = []
print(ll)
ll.append(1)
ll.insert(0, -1)
print(ll[0])
print(ll)
ll.pop()
print(ll)
ll[0] = -111
print(ll)
tt = (1, 2, 3, 4)
tt2 = (1, 2, 3, 4)
print(tt)
print(tt[0])
tt = (1, 2, 3)
print([1])
print((1,))
print(())
n = 15
print(list(range(n)))
print(tuple(range(n)))
print(tuple(ll)) |
#
# @lc app=leetcode.cn id=1195 lang=python3
#
# [1195] distribute-candies-to-people
#
None
# @lc code=end | None |
# Design Snake Game
class SnakeGame(object):
def __init__(self, width, height, food):
"""
Initialize your data structure here.
@param width - screen width
@param height - screen height
@param food - A list of food positions
E.g food = [[1,1], [1,0]] means the first f... | class Snakegame(object):
def __init__(self, width, height, food):
"""
Initialize your data structure here.
@param width - screen width
@param height - screen height
@param food - A list of food positions
E.g food = [[1,1], [1,0]] means the first food is positioned at... |
class Lagrange():
def lagrange(self, points, x):
result = {
'error': False,
'errorMessage': None,
'functionOutput': None,
'terms': None,
'polynomial': None,
'resultMessage': None,
'solutionFailed': False
}
n ... | class Lagrange:
def lagrange(self, points, x):
result = {'error': False, 'errorMessage': None, 'functionOutput': None, 'terms': None, 'polynomial': None, 'resultMessage': None, 'solutionFailed': False}
n = len(points)
l_values = list()
p_values = list()
res = 0
for i... |
device_str = " r3-L-n7, cisco, catalyst 2960, ios , extra stupid stuff " #string
# NON LIST COMPREHENSION WAY
device = list() #we are crating a empty list [0,1,2,3,4]
for item in device_str.split(","): #item 0, ittem 1, item 2 etc...
device.append(item.strip()) #remove begining and ending spaces for every item... | device_str = ' r3-L-n7, cisco, catalyst 2960, ios , extra stupid stuff '
device = list()
for item in device_str.split(','):
device.append(item.strip())
print('\ndevice using for loop:\n\t\t', device)
device = [item.strip() for item in device_str.split(',')]
print('\ndevice using list comprehension:\n\t\t', device)... |
def process_scope(dom, json_dict):
scope_sections = dom.xpath("scope")
if len(scope_sections) > 0:
json_dict["scope"] = []
for book in scope_sections[0].xpath("bookScope"):
if book.text:
json_dict["scope"].append(book.text)
| def process_scope(dom, json_dict):
scope_sections = dom.xpath('scope')
if len(scope_sections) > 0:
json_dict['scope'] = []
for book in scope_sections[0].xpath('bookScope'):
if book.text:
json_dict['scope'].append(book.text) |
#sets 2 variables a and b as age one and age 2. One is enterd it will swap the ages to b,a
def swap(age1, age2):
a = age1
b = age2
if a <= b:
return a, b
else:
return b, a
def swapfunction():
input1 = input("first age")
input2 = input("second age")
a, b = swap(input1, input2)... | def swap(age1, age2):
a = age1
b = age2
if a <= b:
return (a, b)
else:
return (b, a)
def swapfunction():
input1 = input('first age')
input2 = input('second age')
(a, b) = swap(input1, input2)
print(a, b)
if __name__ == '__main__':
swapfunction() |
#
# @lc app=leetcode id=322 lang=python3
#
# [322] Coin Change
#
# https://leetcode.com/problems/coin-change/description/
#
# algorithms
# Medium (27.95%)
# Total Accepted: 261.6K
# Total Submissions: 810K
# Testcase Example: '[1,2,5]\n11'
#
# You are given coins of different denominations and a total amount of mon... | class Solution(object):
def coin_change(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
table = [float('inf') for _ in range(amount + 1)]
table[0] = 0
for i in range(1, amount + 1):
for coin in coins:
... |
BASE_URLS = [
"www.journals.elsevier.com/aasri-procedia/",
"www.elsevier.com/journals/abstract-bulletin-of-paper-science-and-technology/1523-388x",
"www.journals.elsevier.com/academic-pediatrics/",
"www.journals.elsevier.com/academic-radiology/",
"www.journals.elsevier.com/accident-analysis-and-prevention/",
"www.elsev... | base_urls = ['www.journals.elsevier.com/aasri-procedia/', 'www.elsevier.com/journals/abstract-bulletin-of-paper-science-and-technology/1523-388x', 'www.journals.elsevier.com/academic-pediatrics/', 'www.journals.elsevier.com/academic-radiology/', 'www.journals.elsevier.com/accident-analysis-and-prevention/', 'www.elsevi... |
# Expected Payment's direction
class DirectionTypes:
CREDIT = 'credit'
DEBIT = 'debit'
# PaymentOrders
class PaymentOrderTypes:
ACH = 'ach'
WIRE = 'wire'
CHECk = 'check'
BOOK = 'book'
rtp = 'rtp'
# account types
class AccountTypes:
CHECKING = 'checking'
SAVINGS = 'savings'
OTHE... | class Directiontypes:
credit = 'credit'
debit = 'debit'
class Paymentordertypes:
ach = 'ach'
wire = 'wire'
che_ck = 'check'
book = 'book'
rtp = 'rtp'
class Accounttypes:
checking = 'checking'
savings = 'savings'
other = 'other'
class Accountnumbertype:
iban = 'iban'
cl... |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
class FICDataVault:
def __init__(self):
# Common Data
self.uid = int() # Used to find the object.
... | class Ficdatavault:
def __init__(self):
self.uid = int()
self.repos_container = dict()
self.commit_type = None
self.commit_number = None
self.commit_sha = None
self.commit_url = None
self.commit_author = None
self.commit_author_email = None
se... |
#
# PySNMP MIB module IANA-RTPROTO-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IANA-RTPROTO-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:02:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_range_constraint, single_value_constraint, constraints_union, value_size_constraint) ... |
expected_output = {
"vrf": {
"default": {
"address_family": {
"ipv4": {
"routes": {
"0.0.0.0/0": {
"candidate_default": True,
"active": True,
"route": "... | expected_output = {'vrf': {'default': {'address_family': {'ipv4': {'routes': {'0.0.0.0/0': {'candidate_default': True, 'active': True, 'route': '0.0.0.0/0', 'source_protocol_codes': 'S', 'source_protocol': 'static', 'metric': 0, 'route_preference': 1, 'next_hop': {'next_hop_list': {1: {'index': 1, 'next_hop': '192.2.0.... |
class PyLarkError(Exception):
def __init__(self, scope: str, func: str, code: int, msg: str):
super().__init__(
f"pylark error, scope={scope}, func={func}, code={code}, msg={msg}"
)
self.scope = scope
self.func = func
self.code = code
self.msg = msg
| class Pylarkerror(Exception):
def __init__(self, scope: str, func: str, code: int, msg: str):
super().__init__(f'pylark error, scope={scope}, func={func}, code={code}, msg={msg}')
self.scope = scope
self.func = func
self.code = code
self.msg = msg |
#!/usr/bin/env python
""" Problem 7
10001st prime
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10,001st prime number?
Answer = 104743
"""
def main():
upper_limit = 10001
counter = 1
prime_list = []
prime_list.append(2)
while ... | """ Problem 7
10001st prime
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10,001st prime number?
Answer = 104743
"""
def main():
upper_limit = 10001
counter = 1
prime_list = []
prime_list.append(2)
while len(prime_list) < upper_l... |
budget = float(input())
needed_funds = 0
product = input()
counter = 0
total_price = 0
is_budget_over = False
while product != 'Stop':
counter += 1
product_price = float(input())
if counter % 3 == 0:
product_price = product_price / 2
if budget < product_price:
is_budget_over = True
... | budget = float(input())
needed_funds = 0
product = input()
counter = 0
total_price = 0
is_budget_over = False
while product != 'Stop':
counter += 1
product_price = float(input())
if counter % 3 == 0:
product_price = product_price / 2
if budget < product_price:
is_budget_over = True
... |
def perfect_number(num):
sum_divisors = 0
for i in range(1, num):
if i > 0:
if num % i == 0:
sum_divisors += i
if sum_divisors == num:
return 'We have a perfect number!'
else:
return 'It\'s not so perfect.'
number = int(input())
print(perfect_number(n... | def perfect_number(num):
sum_divisors = 0
for i in range(1, num):
if i > 0:
if num % i == 0:
sum_divisors += i
if sum_divisors == num:
return 'We have a perfect number!'
else:
return "It's not so perfect."
number = int(input())
print(perfect_number(num... |
class Solution:
def defangIPaddr(self, address: str) -> str:
return "[.]".join((address.split(".")))
slu = Solution()
print(slu.defangIPaddr("1.1.1.1")) | class Solution:
def defang_i_paddr(self, address: str) -> str:
return '[.]'.join(address.split('.'))
slu = solution()
print(slu.defangIPaddr('1.1.1.1')) |
# ----------------------------------------------
# Convert a temperature in Fahrenheit to Celsius
# ----------------------------------------------
Fahrenheit = 85.2
Celsius = (Fahrenheit - 32) * 5.0 / 9.0
print("Temperature:", Fahrenheit, "Fahrenheit = ", Celsius, " Celsius")
| fahrenheit = 85.2
celsius = (Fahrenheit - 32) * 5.0 / 9.0
print('Temperature:', Fahrenheit, 'Fahrenheit = ', Celsius, ' Celsius') |
#
# @lc app=leetcode.cn id=1410 lang=python3
#
# [1410] traffic-light-controlled-intersection
#
None
# @lc code=end | None |
num_tries = 0
def binarysearch(numlist, target):
global num_tries
if len(numlist) == 0:
print("The target is not in this list.")
else:
midpoint_index = len(numlist) // 2
if numlist[midpoint_index] == target:
num_tries += 1
print("The target", target, "was fou... | num_tries = 0
def binarysearch(numlist, target):
global num_tries
if len(numlist) == 0:
print('The target is not in this list.')
else:
midpoint_index = len(numlist) // 2
if numlist[midpoint_index] == target:
num_tries += 1
print('The target', target, 'was fou... |
load("@bazel_skylib//lib:paths.bzl", "paths")
load("//ocaml:providers.bzl",
"CompilationModeSettingProvider",)
load("//ocaml/_functions:utils.bzl",
"get_opamroot",
"get_sdkpath",
)
load(":impl_common.bzl", "tmpdir")
########## RULE: OCAML_INTERFACE ################
def _ocaml_lex_impl(ctx):
debu... | load('@bazel_skylib//lib:paths.bzl', 'paths')
load('//ocaml:providers.bzl', 'CompilationModeSettingProvider')
load('//ocaml/_functions:utils.bzl', 'get_opamroot', 'get_sdkpath')
load(':impl_common.bzl', 'tmpdir')
def _ocaml_lex_impl(ctx):
debug = False
if debug:
print('OCAML LEX TARGET: %s' % ctx.label... |
#: E711:7
if res == None:
pass
#: E711:7
if res != None:
pass
#: E711:8
if None == res:
pass
#: E711:8
if None != res:
pass
#: E711:10
if res[1] == None:
pass
#: E711:10
if res[1] != None:
pass
#: E711:8
if None != res[1]:
pass
#: E711:8
if None == res[1]:
pass
#
#: E712:7
if res == Tru... | if res == None:
pass
if res != None:
pass
if None == res:
pass
if None != res:
pass
if res[1] == None:
pass
if res[1] != None:
pass
if None != res[1]:
pass
if None == res[1]:
pass
if res == True:
pass
if res != False:
pass
if True != res:
pass
if False == res:
pass
if res... |
"""
These are intended to be helpful references that will take up a lot of
space if included in the main modules, so I'm breaking them out into
a separate module...maybe some utility functions will be in order at some point,
such as figuring out which attributes all elements have in common, etc.
https://developer.intu... | """
These are intended to be helpful references that will take up a lot of
space if included in the main modules, so I'm breaking them out into
a separate module...maybe some utility functions will be in order at some point,
such as figuring out which attributes all elements have in common, etc.
https://developer.intu... |
# Data cfg
dataset_type = 'MarvelDatasetBBox'
background_type = 'ImageNetDataset'
# data_root = 'your_data_path/imagenet/train' # data path
base_scale = (256, 256)
fore_scale = (128, 255)
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=False)
preprocess_pipeline = dict(
... | dataset_type = 'MarvelDatasetBBox'
background_type = 'ImageNetDataset'
base_scale = (256, 256)
fore_scale = (128, 255)
img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=False)
preprocess_pipeline = dict(type='CopyAndPasteNew', feed_bytes=False, base_scale=base_scale, ratio=(0.5, 2.... |
#
# PySNMP MIB module RFC1286-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RFC1286-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:48:48 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 0... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_range_constraint, constraints_union, constraints_intersection, value_size_constraint) ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.