content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""Shared Memory for ShadMem program"""
class ShadBaseSharedMemory(Exception):
"""Base exception class for Shared Memory."""
pass
class ShadSharedMemory(ShadBaseSharedMemory):
"""Shared memory class"""
errno = None
def __init__(self,shrdmm=None,verbse=False):
self.sharedmemory = shrdmm
... | """Shared Memory for ShadMem program"""
class Shadbasesharedmemory(Exception):
"""Base exception class for Shared Memory."""
pass
class Shadsharedmemory(ShadBaseSharedMemory):
"""Shared memory class"""
errno = None
def __init__(self, shrdmm=None, verbse=False):
self.sharedmemory = shrdmm
... |
#!/usr/bin/env python
# coding: utf-8
# In[9]:
##############################################################################################################################
### Hassan Shahzad
### CS-D
### Artificial Intelligence Lab (Lab # 9)
### FAST-NUCES
### chhxnshah@gmai... | variables = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
constraints = [('A', 'B'), ('A', 'C'), ('B', 'C'), ('B', 'D'), ('B', 'E'), ('C', 'E'), ('C', 'F'), ('D', 'E'), ('E', 'F'), ('E', 'G'), ('F', 'G')]
domain_values = ['Monday', 'Tuesday', 'Wednesday']
def backtrack(assignment):
if len(assignment) == len(VARIABLES):
... |
clearText = pow(0x025051c6c4e82266e0b9e8a47266531a01d484b0dc7ee629fb5a0588f15bf50281f46cf08be71e067ac7166580f144a6bdcc83a90206681c2409404e92474b37de67d92fd2fa4bc4bd119372b6d50c0377758fc8e946d203a040e04d6bfe41dfb898cd4e36e582f16ad475915ac2c6586d874dd397e7ed1cb2d3f2003586c257, 89508186630638564513494386415865407147609702... | clear_text = pow(162476896597824412221838491544025994977362305261910926538496052420409924140550933429821701207357424524014097582331265916084704503513250153693909608961907792999825125123678359025556295112989730272506765528550349367618606269335047048224712459876653375502744041871339850956618923981561391666298788102929427... |
# File: awswaf_consts.py
#
# Copyright (c) 2019-2021 Splunk Inc.
#
# 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 appl... | awswaf_access_key = 'access_key_id'
awswaf_secret_key = 'access_key_secret'
awswaf_region = 'region'
awswaf_default_limit = 100
awswaf_insufficient_param = 'Insufficient parameters. Please provide either ip_set_name or ip_set_id'
awswaf_err_token = 'Error in connection while getting the token'
awswaf_err_create_ipset =... |
# Copyright 2019 Axis Communications AB.
#
# For a full list of individual contributors, please see the commit history.
#
# 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.apac... | follow_my_commit = '{\n sourceChangeCreated(search: "{\'data.gitIdentifier.commitId\': \'c9ea15d2d0d3bcfa2856416be4add5a5919764f4\'}") {\n edges {\n node {\n reverse {\n edges {\n node {\n ... on SourceChangeSubmitted {\n reverse {\n edges... |
#Printing Stars in 'F' Shape !
'''
* * * * *
*
*
* * * *
*
*
*
'''
for row in range(7):
for col in range(5):
if (col==0)or((row==0) and (col>0) or (row==3)and(col>0 and col<4)):
print('*',end=' ')
else:
print(end=' ')
print() | """
* * * * *
*
*
* * * *
*
*
*
"""
for row in range(7):
for col in range(5):
if col == 0 or (row == 0 and col > 0 or (row == 3 and (col > 0 and col < 4))):
print('*', end=' ')
else:
print(end=' ')
print() |
print("hello")
print('hello')
welcome_message = "Hello, welcome to Udacity!"
print(welcome_message)
# pet_halibut = "Why should I be tarred with the epithet "loony" merely because I have a pet halibut?""
# SyntaxError: invalid syntax
pet_halibut = 'Why should I be tarred with the epithet "loony" merely because I hav... | print('hello')
print('hello')
welcome_message = 'Hello, welcome to Udacity!'
print(welcome_message)
pet_halibut = 'Why should I be tarred with the epithet "loony" merely because I have a pet halibut?'
salesman = '"I think you\'re an encyclopedia salesman"'
this_string = "Simon's skateboard is in the garage."
print(this... |
# Hyperparameters to evaluate: For each, hyperparameter, provide a LIST of options to evaluate. A paramter grid will be generated so all combinations of these hyperparameters will be evaluated.
hyperparams = {"epochs": [200], \
"nonlinearity": ["relu"], \
"hidden_sizes_shared": [[500,10... | hyperparams = {'epochs': [200], 'nonlinearity': ['relu'], 'hidden_sizes_shared': [[500, 100]], 'hidden_sizes_separate': [[50, 10]], 'dropout': [0.1], 'k_reg': [1e-05, 0.001], 'learning_rate': [0.0001, 0.001], 'loss_weights': [[1, 1]], 'grad_clip_norm': [0.01, 0.1], 'batch_size': [20]}
specific_folder = 'origGE'
phenoty... |
# http://ipset.netfilter.org/iptables-extensions.man.html#lbBK
class Mark(object):
def __init__(self, raw):
self.value = 0
self.mask = 0xFFFFFFFF
self.invert = False
fields = raw.split()
for i in range(len(fields)):
if fields[i] == "--mark":
if f... | class Mark(object):
def __init__(self, raw):
self.value = 0
self.mask = 4294967295
self.invert = False
fields = raw.split()
for i in range(len(fields)):
if fields[i] == '--mark':
if fields[i - 1] == '!':
self.invert = True
... |
{
"targets": [
{
"includes": [
"auto.gypi"
],
"sources": [
"src/run.cpp"
],
"link_settings":{
"ldflags": [
"-L<(module_root_dir)/src/target/release -lbinarytrees",
"-Wl,-rpath=<(module_root_dir)/src/target/release"
]
}
}
... | {'targets': [{'includes': ['auto.gypi'], 'sources': ['src/run.cpp'], 'link_settings': {'ldflags': ['-L<(module_root_dir)/src/target/release -lbinarytrees', '-Wl,-rpath=<(module_root_dir)/src/target/release']}}], 'includes': ['auto-top.gypi']} |
for i in range(1,101):
print(i,end="")
divisores=[]
if i % 2 == 0:
divisores.append(2)
if i % 3 == 0:
divisores.append(3)
if i % 5 == 0:
divisores.append(5)
if len(divisores) == 0 :
divisores = ""
else :
divisores=" "+str(tuple(divisores)).replace(",)"... | for i in range(1, 101):
print(i, end='')
divisores = []
if i % 2 == 0:
divisores.append(2)
if i % 3 == 0:
divisores.append(3)
if i % 5 == 0:
divisores.append(5)
if len(divisores) == 0:
divisores = ''
else:
divisores = ' ' + str(tuple(divisores)).replac... |
#
# @lc app=leetcode id=1239 lang=python3
#
# [1239] Maximum Length of a Concatenated String with Unique Characters
#
# @lc code=start
class Solution:
def maxLength(self, arr: List[str]) -> int:
filtered = [set(str) for str in arr if len(str) == len(set(str))]
found = [set()]
for s1 in fil... | class Solution:
def max_length(self, arr: List[str]) -> int:
filtered = [set(str) for str in arr if len(str) == len(set(str))]
found = [set()]
for s1 in filtered:
for s2 in found:
if not s1 & s2:
found.append(s1 | s2)
return max([len(i... |
class Rat:
def __init__(self, game):
self.game = game
self.attack = 1
game.rat_enters.append(self.rat_enters)
game.notify_rat.append(self.notify_rat)
game.rat_dies.append(self.rat_dies)
self.game.rat_enters(self)
def __enter__(self):
return self
de... | class Rat:
def __init__(self, game):
self.game = game
self.attack = 1
game.rat_enters.append(self.rat_enters)
game.notify_rat.append(self.notify_rat)
game.rat_dies.append(self.rat_dies)
self.game.rat_enters(self)
def __enter__(self):
return self
def... |
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.queue=[]
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self.queue.append(x)
def pop(self) -> int:
"""
Removes... | class Myqueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.queue = []
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self.queue.append(x)
def pop(self) -> int:
"""
Remov... |
INDEX_INFO = {
"robust04": {
"description": "TREC Disks 4 & 5 (minus Congressional Records), used in the TREC 2004 Robust Track",
"urls": [
"https://www.dropbox.com/s/s91388puqbxh176/index-robust04-20191213.tar.gz?dl=1",
"https://git.uwaterloo.ca/jimmylin/anserini-indexes/raw... | index_info = {'robust04': {'description': 'TREC Disks 4 & 5 (minus Congressional Records), used in the TREC 2004 Robust Track', 'urls': ['https://www.dropbox.com/s/s91388puqbxh176/index-robust04-20191213.tar.gz?dl=1', 'https://git.uwaterloo.ca/jimmylin/anserini-indexes/raw/master/index-robust04-20191213.tar.gz'], 'md5'... |
def compress(image, b):
'''
Function to compress images
Parameters:
image, a 3d array representation of the image
like the one returned by plt.imread(image)
b, the number of bits used in each entry in the array
integer from 1 to 8
1 = maximum compression
... | def compress(image, b):
"""
Function to compress images
Parameters:
image, a 3d array representation of the image
like the one returned by plt.imread(image)
b, the number of bits used in each entry in the array
integer from 1 to 8
1 = maximum compression
... |
#OOPR-Assgn-5
#Start writing your code here
def check_type(type):
vehicle_type=['Two Wheeler', 'Four Wheeler']
if type not in vehicle_type:
return 0
return 1
class Vehicle:
def __init__(self):
self.__vehicle_cost=None
self.__vehicle_id=None
self.__vehicle_type=None
... | def check_type(type):
vehicle_type = ['Two Wheeler', 'Four Wheeler']
if type not in vehicle_type:
return 0
return 1
class Vehicle:
def __init__(self):
self.__vehicle_cost = None
self.__vehicle_id = None
self.__vehicle_type = None
self.__premium_amount = None
... |
friction = 0.02 # higher value = points slow down faster after force is applied
gravity = 0.05 # constant downard force on all points
bounce = 0.5 # multiple of inverse force applied to point when out of bounds
rigidity = 5 # accuracy; elasticity
class Rag:
def __init__(self, rag):
self.points = [p ... | friction = 0.02
gravity = 0.05
bounce = 0.5
rigidity = 5
class Rag:
def __init__(self, rag):
self.points = [p + p for p in rag['points']]
self.statics = [s for s in rag['statics']]
self.sticks = [s for s in rag['sticks']]
for s in self.sticks:
p0 = self.points[s[0]]
... |
# Programa 12
c = 7 + 5*1.2
b = c - 4
if (b > 9):
if (c == 10):
a = b + 3
elif (b == 6):
a = c*3
print(a - c)
elif (c >= 13):
a = b + 1
else:
a = c / 7
print(a**b)
if (a < b):
a = c - b
c = c - a | c = 7 + 5 * 1.2
b = c - 4
if b > 9:
if c == 10:
a = b + 3
elif b == 6:
a = c * 3
print(a - c)
elif c >= 13:
a = b + 1
else:
a = c / 7
print(a ** b)
if a < b:
a = c - b
c = c - a |
PACKAGE_NAME = 'chatbridge'
VERSION_PYPI = '2.0.0-a1'
SERVER_NAME = '#SERVER'
| package_name = 'chatbridge'
version_pypi = '2.0.0-a1'
server_name = '#SERVER' |
#
# Copyright 2016 Google Inc. All Rights Reserved.
#
# 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... | {'includes': ['../common.gypi'], 'variables': {'icu_src_dir': '<(root_dir)/third_party/icu/icu4c'}, 'targets': [{'target_name': 'ionicu', 'type': 'static_library', 'all_dependent_settings': {'include_dirs': ['<(icu_src_dir)/source/common'], 'defines': ['U_DISABLE_RENAMING']}, 'include_dirs': ['<(root_dir)/', '<(icu_src... |
# -- Configuration Version --
config_version = 1
# -- Solver configuration --
f_to_calculate = [16., 31.5, 63., 125., 250., 500., 1000., 2000., 4000., 8000.]
f_to_plot = [250., 1000., 4000.]
order = 1
absorbing_layer = True
# -- Results Files configuration --
should_delete_old_results = False
results_directory = '... | config_version = 1
f_to_calculate = [16.0, 31.5, 63.0, 125.0, 250.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0]
f_to_plot = [250.0, 1000.0, 4000.0]
order = 1
absorbing_layer = True
should_delete_old_results = False
results_directory = '../results/config{}'.format(config_version)
results_dir_with_absorbing_layer = '{}/with_... |
PLUGIN_AUTHOR_NAME = 'Your name'
PLUGIN_AUTHOR_EMAIL = 'your@email'
PLUGIN_AUTHOR_WEBSITE = 'https://yourwebsite'
HOOK_BEFORE_CREATE_PLUGIN = ''
HOOK_AFTER_CREATE_PLUGIN = ''
STORAGE_DIR = 'storage'
PERMISSIONS_TREE = {
'root': ['admin'],
'admin': ['execution'],
'execution': []
}
PROTOCOLS = [
]
PLUGINS... | plugin_author_name = 'Your name'
plugin_author_email = 'your@email'
plugin_author_website = 'https://yourwebsite'
hook_before_create_plugin = ''
hook_after_create_plugin = ''
storage_dir = 'storage'
permissions_tree = {'root': ['admin'], 'admin': ['execution'], 'execution': []}
protocols = []
plugins = ['bot', 'hello']... |
class Solution:
def isValid(self, s: str) -> bool:
dic = {'(': ')', '{': '}', '[': ']', '!': '!'}
stack = ['!']
for c in s:
if c in dic:
stack.append(c)
elif dic[stack.pop()] != c:
return False
return len(stack) == 1
| class Solution:
def is_valid(self, s: str) -> bool:
dic = {'(': ')', '{': '}', '[': ']', '!': '!'}
stack = ['!']
for c in s:
if c in dic:
stack.append(c)
elif dic[stack.pop()] != c:
return False
return len(stack) == 1 |
#
# 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, software
# ... | spool_template = '\nheat_template_version: 2015-04-30\ndescription: Template to test subnetpool Neutron resource\nresources:\n sub_pool:\n type: OS::Neutron::SubnetPool\n properties:\n name: the_sp\n prefixes:\n - 10.1.0.0/16\n address_scope: test\n default_quota: 2\n default_pref... |
print('Pick an operation')
operation=input()
print('enter your first number')
number_1 = int(input())
print('enter your second number')
number_2 = int(input())
if operation == '+':
print(number_1 + number_2)
else:
print(number_1 - number_2)
| print('Pick an operation')
operation = input()
print('enter your first number')
number_1 = int(input())
print('enter your second number')
number_2 = int(input())
if operation == '+':
print(number_1 + number_2)
else:
print(number_1 - number_2) |
class Solution:
def findSubstringInWraproundString(self, p: str) -> int:
dp = [0] * 26
curr = 1
expected_code = None
for i, c in enumerate(p):
char_code = ord(c) - ord('a')
if char_code == expected_code:
curr += 1
else:
... | class Solution:
def find_substring_in_wrapround_string(self, p: str) -> int:
dp = [0] * 26
curr = 1
expected_code = None
for (i, c) in enumerate(p):
char_code = ord(c) - ord('a')
if char_code == expected_code:
curr += 1
else:
... |
# link: https://leetcode.com/problems/friend-circles/
class Solution(object):
def findCircleNum(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
# first create a adjacancy list
nodes= len(M)
visited = [0]*nodes
result=0
for node in range... | class Solution(object):
def find_circle_num(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
nodes = len(M)
visited = [0] * nodes
result = 0
for node in range(nodes):
if visited[node] == 0:
self.dfs(M, node, visited)
... |
# File: symantecatp_view.py
#
# Copyright (c) 2017-2019 Splunk Inc.
#
# 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 a... | def get_ctx_result(result):
ctx_result = {}
param = result.get_param()
summary = result.get_summary()
data = result.get_data()
ctx_result['param'] = param
if summary:
ctx_result['summary'] = summary
if not data:
ctx_result['data'] = {}
return ctx_result
ctx_result... |
# import re
def replaceVogais(txt):
for i in 'aeiouAEIOU':
txt = txt.replace(i, '')
return txt
lista = []
for i in range(3):
palavra = input('Digite uma palavra:')
lista.append(palavra)
for index, palavra in enumerate(lista):
match index:
case 0:
lista[0] = lista[0... | def replace_vogais(txt):
for i in 'aeiouAEIOU':
txt = txt.replace(i, '')
return txt
lista = []
for i in range(3):
palavra = input('Digite uma palavra:')
lista.append(palavra)
for (index, palavra) in enumerate(lista):
match index:
case 0:
lista[0] = lista[0].upper()
... |
_DEFAULT_SAMPLE_RATE = 22050
SOUNDFONTS = {
"salamander": "../soundfonts/salamander/SalamanderGrandPiano.sf2",
"fluidR3": "../soundfonts/fluid/FluidR3_GM.sf2",
"musescore": "../soundfonts/musescore/musescore_general.sf3",
"rhodes": "../soundfonts/rhodes/RhodesEPsPlus_2.3.sf2"
} | _default_sample_rate = 22050
soundfonts = {'salamander': '../soundfonts/salamander/SalamanderGrandPiano.sf2', 'fluidR3': '../soundfonts/fluid/FluidR3_GM.sf2', 'musescore': '../soundfonts/musescore/musescore_general.sf3', 'rhodes': '../soundfonts/rhodes/RhodesEPsPlus_2.3.sf2'} |
"""
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any
positive integer, replace the number by the sum of the squares of its digits,
and repeat the process until the number equals 1 (where it will stay), or it
loops endlessly in a cycl... | """
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any
positive integer, replace the number by the sum of the squares of its digits,
and repeat the process until the number equals 1 (where it will stay), or it
loops endlessly in a cycl... |
n, k = [int(x) for x in input().split()]
nm = []
for g in range(n): nm.append(input())
print(sorted(nm)[k-1])
| (n, k) = [int(x) for x in input().split()]
nm = []
for g in range(n):
nm.append(input())
print(sorted(nm)[k - 1]) |
#!usr/bin/env python
# -*- coding: utf-8 -*-
# This function checks if the status code of a REST request is 200/201,
# signifying a successful request. If not, the program exits with a log message.
def checkStatusCode(status_code, URL):
# Status codes 200 and 201 represent a successful request, so the function
# s... | def check_status_code(status_code, URL):
if status_code == 200 or status_code == 201:
return
else:
print('Call to URL {0} failed with status code {1}'.format(URL, status_code))
print('Exiting')
exit(1) |
"""
Permutar los valores de estas dos tuplas:
tuple_one = (23, 34)
tuple_two = (34, 45)
Final:
tuple_one = (34, 45)
tuple_two = (23, 34)
"""
tuple_one = (23, 34)
tuple_two = (34, 45)
print("Inicio")
print(tuple_one, tuple_two)
tuple_one, tuple_two = tuple_two, tuple_one
print("Final")
print(tuple_one, tuple_two)
| """
Permutar los valores de estas dos tuplas:
tuple_one = (23, 34)
tuple_two = (34, 45)
Final:
tuple_one = (34, 45)
tuple_two = (23, 34)
"""
tuple_one = (23, 34)
tuple_two = (34, 45)
print('Inicio')
print(tuple_one, tuple_two)
(tuple_one, tuple_two) = (tuple_two, tuple_one)
print('Final')
print(tuple_one, tuple_two) |
class CompositionalRule(object):
def __and__(self, other):
return And(self, other)
def __invert__(self):
return Not(self)
def __or__(self, other):
return Or(self, other)
def __ne__(self, other):
return Not(self.__eq__(other))
def accepts(self, anObject):
r... | class Compositionalrule(object):
def __and__(self, other):
return and(self, other)
def __invert__(self):
return not(self)
def __or__(self, other):
return or(self, other)
def __ne__(self, other):
return not(self.__eq__(other))
def accepts(self, anObject):
... |
class Args(list):
def __init__(self, raw_args):
super().__init__()
self._raw_args = raw_args
def __setitem__(self, index, data):
self._raw_args[index] = data
def __getitem__(self, index):
return self._raw_args[index]
def __len__(self):
return len(self._raw_arg... | class Args(list):
def __init__(self, raw_args):
super().__init__()
self._raw_args = raw_args
def __setitem__(self, index, data):
self._raw_args[index] = data
def __getitem__(self, index):
return self._raw_args[index]
def __len__(self):
return len(self._raw_arg... |
class ParsingError(Exception):
"""
This exception gets raised when there is a parsing error during logical form processing. This
might happen because you're not handling the full set of possible logical forms, for instance,
and having this error provides a consistent way to catch those errors and log h... | class Parsingerror(Exception):
"""
This exception gets raised when there is a parsing error during logical form processing. This
might happen because you're not handling the full set of possible logical forms, for instance,
and having this error provides a consistent way to catch those errors and log h... |
# -*- coding: utf-8 -*-
"""
meraki
This file was automatically generated for meraki by APIMATIC v2.0 ( https://apimatic.io ).
"""
class V3PrivModeEnum(object):
"""Implementation of the 'V3PrivMode' enum.
The SNMP version 3 privacy mode. Can be either 'DES' or 'AES128'.
Attributes... | """
meraki
This file was automatically generated for meraki by APIMATIC v2.0 ( https://apimatic.io ).
"""
class V3Privmodeenum(object):
"""Implementation of the 'V3PrivMode' enum.
The SNMP version 3 privacy mode. Can be either 'DES' or 'AES128'.
Attributes:
DES: TODO: type description he... |
# Areas list
areas = [ "hallway", 14.35,
"kitchen", 15.0,
"living room", 19.0,
"bedroom", 12.5,
"bathroom", 8.75 ]
# Add garage and garden data
all_areas = areas + ["garage", 20.0,"garden", 17.0]
# Print out all_areas
print(all_areas) | areas = ['hallway', 14.35, 'kitchen', 15.0, 'living room', 19.0, 'bedroom', 12.5, 'bathroom', 8.75]
all_areas = areas + ['garage', 20.0, 'garden', 17.0]
print(all_areas) |
with open("input.txt", "r") as f:
lines = f.readlines()
isFirst = True
cValue = 0
counter = 0
for line in lines:
line = line.strip()
if isFirst:
isFirst = False
else:
if cValue < int(line) :
counter +=1
cValue = int(line)
... | with open('input.txt', 'r') as f:
lines = f.readlines()
is_first = True
c_value = 0
counter = 0
for line in lines:
line = line.strip()
if isFirst:
is_first = False
elif cValue < int(line):
counter += 1
c_value = int(line)
print('Total incre... |
# print(*input().split('WUB'))
# And I thought regex is going to beat me...
# Wait.... the checker doesn't care about double space......................
# Now I stand by my solution, even thought it would replace "WUBWWUBUWUBBWUB" with ""
def l(a):
for b in ['WUB',' ']:a=a.replace(b,' ')
return a
w=input()
while w!=... | def l(a):
for b in ['WUB', ' ']:
a = a.replace(b, ' ')
return a
w = input()
while w != l(w):
w = l(w)
print(w.strip()) |
class Location:
def __init__(self, x, y, value):
self.x = x
self.y = y
self.value = value
def intersection(node, x, y):
pass
class QuadTreeNode:
def __init__(self, top_left, top_right, bottom_left, bottom_right):
self.top_left = top_left
self.top_right = top_right... | class Location:
def __init__(self, x, y, value):
self.x = x
self.y = y
self.value = value
def intersection(node, x, y):
pass
class Quadtreenode:
def __init__(self, top_left, top_right, bottom_left, bottom_right):
self.top_left = top_left
self.top_right = top_right... |
# Copyright (c) 2010-2021 openpyxl
class IndexedList(list):
"""
List with optimised access by value
Based on Alex Martelli's recipe
http://code.activestate.com/recipes/52303-the-auxiliary-dictionary-idiom-for-sequences-with-/
"""
_dict = {}
def __init__(self, iterable=None):
sel... | class Indexedlist(list):
"""
List with optimised access by value
Based on Alex Martelli's recipe
http://code.activestate.com/recipes/52303-the-auxiliary-dictionary-idiom-for-sequences-with-/
"""
_dict = {}
def __init__(self, iterable=None):
self.clean = True
self._dict = {}... |
"""Custom report symbols for pass/fail/skip"""
names = "passed xpassed failed xfailed skipped error".split()
defaults = dict(zip(names, ".XFxsE"))
help = """
symbol to use in the report when a test has passed (default {passed})
symbol to use when a test is marked as an expected failure, but it doesn't fail (default {x... | """Custom report symbols for pass/fail/skip"""
names = 'passed xpassed failed xfailed skipped error'.split()
defaults = dict(zip(names, '.XFxsE'))
help = "\nsymbol to use in the report when a test has passed (default {passed})\nsymbol to use when a test is marked as an expected failure, but it doesn't fail (default {xp... |
# test basic complex number functionality
# convert bignum to complex on rhs
ans = 1j + (1 << 70)
print("%.5g %.5g" % (ans.real, ans.imag))
| ans = 1j + (1 << 70)
print('%.5g %.5g' % (ans.real, ans.imag)) |
with open("day8_input.txt") as f:
lines = map(str.strip, f.readlines())
count = 0
for signals, outputs in [(x.split(), y.split()) for x, y in [line.split("|") for line in lines]]:
count += sum(1 for output in outputs if len(output) in [2, 4, 3, 7])
print(f"{count=}")
| with open('day8_input.txt') as f:
lines = map(str.strip, f.readlines())
count = 0
for (signals, outputs) in [(x.split(), y.split()) for (x, y) in [line.split('|') for line in lines]]:
count += sum((1 for output in outputs if len(output) in [2, 4, 3, 7]))
print(f'count={count!r}') |
# -*-coding:utf-8-*-
# A password is considered strong if below conditions are all met:
# It has at least 6 characters and at most 20 characters.
# It must contain at least one lowercase letter, at least one uppercase letter, and at least one digit.
# It must NOT contain three repeating characters in a row ("...aaa..... | ___author = 'BONFY'
class Solution:
def strong_password_checker(self, s):
"""
:type s: str
:rtype: int
"""
missing_type = 3
if any((c.islower() for c in s)):
missing_type -= 1
if any((c.isupper() for c in s)):
missing_type -= 1
... |
print('Welcome to Number Guessing Mania - Game in Python')
while(True):
n = int(input('Enter a number :\n'))
if n == 18:
print('Yes you got it !!! \n')
break
elif n > 30:
print(f'Sorry, your entered number {n} is greater than expected.')
continue
elif n < ... | print('Welcome to Number Guessing Mania - Game in Python')
while True:
n = int(input('Enter a number :\n'))
if n == 18:
print('Yes you got it !!! \n')
break
elif n > 30:
print(f'Sorry, your entered number {n} is greater than expected.')
continue
elif n < 15:
prin... |
df = pd.DataFrame(
np.random.randint(1, 7, 6000),
columns = ['one'])
df['two'] = df['one'] + np.random.randint(1, 7, 6000)
ax = df.plot.hist(bins=12, alpha=0.5)
| df = pd.DataFrame(np.random.randint(1, 7, 6000), columns=['one'])
df['two'] = df['one'] + np.random.randint(1, 7, 6000)
ax = df.plot.hist(bins=12, alpha=0.5) |
_options = {
"cpp_std": "c++11",
"optimize": "3",
}
def set_option(name, value):
global _options
_options[name] = value
def get_option(name, default=None):
global _options
return _options.get(name, default)
| _options = {'cpp_std': 'c++11', 'optimize': '3'}
def set_option(name, value):
global _options
_options[name] = value
def get_option(name, default=None):
global _options
return _options.get(name, default) |
load(
"@bazel_tools//tools/build_defs/repo:http.bzl",
"http_archive",
"http_file",
)
load("@com_google_protobuf//:protobuf_deps.bzl", "protobuf_deps")
########################################
# bazel_toolchains_repositories
########################################
#
# This rule configures the following rep... | load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive', 'http_file')
load('@com_google_protobuf//:protobuf_deps.bzl', 'protobuf_deps')
load('@bazel_toolchains//repositories:repositories.bzl', bazel_toolchains_repositories='repositories')
def stage2():
bazel_toolchains_repositories()
protobuf_deps(... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
"""
Pre-order DFS
O(N) time and O(N) space
"""
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:t... | """
Pre-order DFS
O(N) time and O(N) space
"""
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
def rserialize(root, string):
""" a recursive helper function for the serialize() function."""
... |
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
result = ""
base = 26
digits = 1
while n > base:
n -= base
base = base * 26
digits += 1
n = n - 1
for i in range(... | class Solution(object):
def convert_to_title(self, n):
"""
:type n: int
:rtype: str
"""
result = ''
base = 26
digits = 1
while n > base:
n -= base
base = base * 26
digits += 1
n = n - 1
for i in rang... |
class Repeater:
def __init__(self, value):
if callable(value):
self._value = value
else:
self._value = lambda: value
def __iter__(self):
return self
def __next__(self):
return self._value()
| class Repeater:
def __init__(self, value):
if callable(value):
self._value = value
else:
self._value = lambda : value
def __iter__(self):
return self
def __next__(self):
return self._value() |
while True:
command = input(">")
if command == 'help':
print("1) start")
print("2) stop")
print("3) quiet")
elif command == 'start':
print("Car started....Ready to Go")
elif command == 'stop':
print("Car stopped")
elif command == 'quiet':
print("Car te... | while True:
command = input('>')
if command == 'help':
print('1) start')
print('2) stop')
print('3) quiet')
elif command == 'start':
print('Car started....Ready to Go')
elif command == 'stop':
print('Car stopped')
elif command == 'quiet':
print('Car te... |
def hcf(x, y):
divisor = 1
if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller + 1):
if (x % i == 0) and (y % i == 0):
divisor = i
return divisor
num1 = int(input('Enter the first number: '))
num2 = int(input("Enter the second number: "))
print(nu... | def hcf(x, y):
divisor = 1
if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller + 1):
if x % i == 0 and y % i == 0:
divisor = i
return divisor
num1 = int(input('Enter the first number: '))
num2 = int(input('Enter the second number: '))
print(num1, ' a... |
class DiscordanceReportResolution:
ONGOING = None
CONCORDANT = 'C'
CONTINUED_DISCORDANCE = 'D'
CHOICES = (
(CONCORDANT, 'Concordant'),
(CONTINUED_DISCORDANCE, 'Continued Discordance')
)
class ContinuedDiscordanceReason:
UNRESPONSIVE = 'U'
DIFFERENT_CURATION_METHODS = 'D'
... | class Discordancereportresolution:
ongoing = None
concordant = 'C'
continued_discordance = 'D'
choices = ((CONCORDANT, 'Concordant'), (CONTINUED_DISCORDANCE, 'Continued Discordance'))
class Continueddiscordancereason:
unresponsive = 'U'
different_curation_methods = 'D'
choices = ((UNRESPONS... |
if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
L = [[a,b,c] for a in range(x+1) for b in range(y+1) for c in range(z+1)]
L = list(filter(lambda x : sum(x) != n, L))
print(L)
| if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
l = [[a, b, c] for a in range(x + 1) for b in range(y + 1) for c in range(z + 1)]
l = list(filter(lambda x: sum(x) != n, L))
print(L) |
#Parameters
def say_hello(name, age):
print(f'Hello, I am {name} and I am {age} years old.')
#Default Parameters
def say_something(name='Andrei', age=20):
print(f'Hello, I am {name} and I am not {age} years old.')
say_something()
#Positional Arguments
say_hello('Elena', 14)
say_hello('John', 10)
#Keyword Ar... | def say_hello(name, age):
print(f'Hello, I am {name} and I am {age} years old.')
def say_something(name='Andrei', age=20):
print(f'Hello, I am {name} and I am not {age} years old.')
say_something()
say_hello('Elena', 14)
say_hello('John', 10)
say_hello(name='Peter', age=20)
say_hello(age=10, name='Ana') |
def find_numbers(lst, test):
numbers = []
for x in lst:
if test(x):
numbers.append(x)
return numbers
def is_even(n):
return n % 2 == 0
def is_big(n):
return n > 500
numbers = [2, 1, 3, 4, 1000, 10001, 1002, 100, -5, -101, -1]
print(find_numbers(numbers, is_big))
def negate(... | def find_numbers(lst, test):
numbers = []
for x in lst:
if test(x):
numbers.append(x)
return numbers
def is_even(n):
return n % 2 == 0
def is_big(n):
return n > 500
numbers = [2, 1, 3, 4, 1000, 10001, 1002, 100, -5, -101, -1]
print(find_numbers(numbers, is_big))
def negate(n):... |
'''import requests
# IDs of the datasets we want to query --> TODO: complete, maybe list in separate file?
datasets_interesting = ['S1084_80_2_409', 'S2060_83_4_435_ENG', 'S2140_87_1_459_ENG', 'S2212_91_3_490_ENG']
# Directory for output/RDF data
dir_processed_eb_rdf = 'data/processed_data/special_eb/metadata/'
def... | """import requests
# IDs of the datasets we want to query --> TODO: complete, maybe list in separate file?
datasets_interesting = ['S1084_80_2_409', 'S2060_83_4_435_ENG', 'S2140_87_1_459_ENG', 'S2212_91_3_490_ENG']
# Directory for output/RDF data
dir_processed_eb_rdf = 'data/processed_data/special_eb/metadata/'
def... |
N, T, *A = map(int, open(0).read().split())
t = 10 ** 9 + 1
d = {}
for a in A:
t = min(t, a)
d.setdefault(a - t, 0)
d[a - t] += 1
print(d[max(d)])
| (n, t, *a) = map(int, open(0).read().split())
t = 10 ** 9 + 1
d = {}
for a in A:
t = min(t, a)
d.setdefault(a - t, 0)
d[a - t] += 1
print(d[max(d)]) |
mondey_temparature = [9.1, 8.8, 7.6]
for temparature in mondey_temparature:
print(round(temparature))
for letter in "helllo":
print(letter) | mondey_temparature = [9.1, 8.8, 7.6]
for temparature in mondey_temparature:
print(round(temparature))
for letter in 'helllo':
print(letter) |
def checkdata(b):
clear_output()
display(button0)
print('Initial Data Condition:')
#checkdata = pd.read_excel('story_'+ story.value+'/story'+ story.value+'.xlsx', sheet_name='sample')
checkdata = pd.read_excel('story_0/story0'+'.xlsx', sheet_name='sample')
checkdata['FC_Start_Date'] = checkdata[... | def checkdata(b):
clear_output()
display(button0)
print('Initial Data Condition:')
checkdata = pd.read_excel('story_0/story0' + '.xlsx', sheet_name='sample')
checkdata['FC_Start_Date'] = checkdata['Arrival_Date'] + pd.to_timedelta(1, unit='D')
checkdata['demanddays'] = np.ceil(checkdata.Demand_Q... |
major = 1
minor = 3
build = 6
version = f"{major}.{minor}.{build}"
| major = 1
minor = 3
build = 6
version = f'{major}.{minor}.{build}' |
def sortPositions(positions):
sorted_positions = {}
for eachposition in positions:
chromosome=eachposition.split(".")[0]
start,end = eachposition.split(":")[-1].split("-")
start,end=int(start),int(end)
sorted_positions[chromosome] = [start,end]
sorted_positions_new={} ... | def sort_positions(positions):
sorted_positions = {}
for eachposition in positions:
chromosome = eachposition.split('.')[0]
(start, end) = eachposition.split(':')[-1].split('-')
(start, end) = (int(start), int(end))
sorted_positions[chromosome] = [start, end]
sorted_positions... |
"""Buffer module to store constants and settings."""
DISP_MSEC = 50 # Delay between display cycles
CAMERA_NUM = 1
GPIO_UV_LED = 32
GPIO_COLOR_LED = 18
COLOR_LED_NUM = 40
CAMERA_RESOLUTION = (3040, 3040)
DISPLAY_RESOLUTION = (480, 480)
RED_GAIN = 4575
BLUE_GAIN = 918
TEST_IMAGE_NAME = "testImag... | """Buffer module to store constants and settings."""
disp_msec = 50
camera_num = 1
gpio_uv_led = 32
gpio_color_led = 18
color_led_num = 40
camera_resolution = (3040, 3040)
display_resolution = (480, 480)
red_gain = 4575
blue_gain = 918
test_image_name = 'testImage.tiff'
settings = {} |
def array_advance(A):
furthest_reached = 0
i=0
lastIndex = len(A)-1
# If furthest reach still has range and we have not reached goal
while i <= furthest_reached and furthest_reached < lastIndex:
furthest_reached = max(furthest_reached, A[i]+i)
i += 1
return furthest_reached >= ... | def array_advance(A):
furthest_reached = 0
i = 0
last_index = len(A) - 1
while i <= furthest_reached and furthest_reached < lastIndex:
furthest_reached = max(furthest_reached, A[i] + i)
i += 1
return furthest_reached >= lastIndex
a = [3, 3, 1, 0, 2, 0, 1]
print(array_advance(A))
a = ... |
class ComputeRank(object):
def __init__(self, var_name):
self.var_name = var_name
def __call__(self, documents):
for i, document in enumerate(documents, 1):
document[self.var_name] = i
return documents
| class Computerank(object):
def __init__(self, var_name):
self.var_name = var_name
def __call__(self, documents):
for (i, document) in enumerate(documents, 1):
document[self.var_name] = i
return documents |
class Statistics:
"""
Represents the state of some players statistics.
Abstracts stat modifications (such as dealing damage).
"""
MAX_HP = 100.0
INITIAL_ARMOUR = 0.0
MAX_ARMOUR = 20.0
def __init__(self):
self.hp = self.MAX_HP
self.armour = self.INITIAL_ARMOUR
def de... | class Statistics:
"""
Represents the state of some players statistics.
Abstracts stat modifications (such as dealing damage).
"""
max_hp = 100.0
initial_armour = 0.0
max_armour = 20.0
def __init__(self):
self.hp = self.MAX_HP
self.armour = self.INITIAL_ARMOUR
def de... |
"""
URLify: Write a method to replace all spaces in a string with '%20: You may assume that the string
has sufficient space at the end to hold the additional characters, and that you are given the "true"
length of the string. (Note: If implementing in Java, please use a character array so that you can
perform this o... | """
URLify: Write a method to replace all spaces in a string with '%20: You may assume that the string
has sufficient space at the end to hold the additional characters, and that you are given the "true"
length of the string. (Note: If implementing in Java, please use a character array so that you can
perform this o... |
"""Module containing dummy code objects for testing the Squirrel program with.
"""
def dummyfunc(word: str):
"""I do things"""
print(f'Hello {word}!')
return 0
class DummyClass():
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def __str__(self):
ret... | """Module containing dummy code objects for testing the Squirrel program with.
"""
def dummyfunc(word: str):
"""I do things"""
print(f'Hello {word}!')
return 0
class Dummyclass:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def __str__(self):
retur... |
output = """
[DEFAULT]
# the DEFAULT section is where you create variables
# that can be used in later sections
control_network = 192.168.10
test_network = 192.168.20
[TEST]
output_folder = data_{t}
# The data files will be appended with .iperf
data_file = %(output_folder)s
# This is the number of times to repeat the ... | output = "\n[DEFAULT]\n# the DEFAULT section is where you create variables\n# that can be used in later sections\ncontrol_network = 192.168.10\ntest_network = 192.168.20\n\n[TEST]\noutput_folder = data_{t}\n# The data files will be appended with .iperf\ndata_file = %(output_folder)s\n# This is the number of times to re... |
# Description: Functions in Python
# Defining a function
# 1. The keyword def introduces a function definition, followed by a function name.
# 2. The body of the function MUST start at the next line, and MUST be indented.
# 3. The first statement of the function body can OPTIONALLY be a string literal to describe the ... | def fibonacci(n):
"""Print a Fibonacci series up to n."""
(a, b) = (0, 1)
while a < n:
print(a, ' ')
(a, b) = (b, a + b)
print()
fibonacci(20)
print(fibonacci(20))
recursive_function = fibonacci(20)
print(recursive_function)
recursive_function = fibonacci
print(recursive_function)
re... |
stocks = pd.read_csv('all_stocks_SP500.csv')
stocks = stocks.T
stocks.columns = stocks.iloc[0]
stocks = stocks[1:]
stocks['condition1'] = (stocks['price'] > stocks['200 MA']) & (stocks['price'] > stocks['150 MA'])
stocks['condition2'] = stocks['150 MA'] > stocks['200 MA']
#3 The 200-day moving average line is trending... | stocks = pd.read_csv('all_stocks_SP500.csv')
stocks = stocks.T
stocks.columns = stocks.iloc[0]
stocks = stocks[1:]
stocks['condition1'] = (stocks['price'] > stocks['200 MA']) & (stocks['price'] > stocks['150 MA'])
stocks['condition2'] = stocks['150 MA'] > stocks['200 MA']
stocks['condition3'] = stocks['200 MA'] > stock... |
"""PodmanPy Tests."""
# Do not auto-update these from version.py,
# as test code should be changed to reflect changes in Podman API versions
BASE_SOCK = "unix:///run/api.sock"
LIBPOD_URL = "http://%2Frun%2Fapi.sock/v3.2.1/libpod"
COMPATIBLE_URL = "http://%2Frun%2Fapi.sock/v1.40"
| """PodmanPy Tests."""
base_sock = 'unix:///run/api.sock'
libpod_url = 'http://%2Frun%2Fapi.sock/v3.2.1/libpod'
compatible_url = 'http://%2Frun%2Fapi.sock/v1.40' |
# pylint: disable=missing-docstring, unused-variable, pointless-statement, too-few-public-methods, useless-object-inheritance
class WrapperClass(object):
def method(self):
var = +4294967296
self.method.__code__.co_consts
| class Wrapperclass(object):
def method(self):
var = +4294967296
self.method.__code__.co_consts |
# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
# Version requirements for various tools. Checked by tooling (e.g. fusesoc),
# and inserted into the documentation.
#
# Entries are keyed by tool name. The value is either ... | __tool_requirements__ = {'edalize': '0.2.0', 'ninja': {'min_version': '1.8.2', 'as_needed': True}, 'verilator': {'min_version': '4.210', 'as_needed': True}, 'hugo_extended': {'min_version': '0.82.0', 'as_needed': True}, 'verible': {'min_version': 'v0.0-2135-gb534c1fe', 'as_needed': True}, 'vcs': {'min_version': '2020.1... |
# physical constants in cgs
# Fundamental constants taken from NIST's 2010 CODATA recommended values
c = 2.99792458e10 # speed of light
h = 6.62606957e-27 # Planck constant
hbar = 1.054571726e-27 #
G = 6.67428e-8 # Gravitational constant
e = 4.80320451e-10 # Electron charge
... | c = 29979245800.0
h = 6.62606957e-27
hbar = 1.054571726e-27
g = 6.67428e-08
e = 4.80320451e-10
me = 9.10938291e-28
mp = 1.672621777e-24
na = 6.02214129e+23
k = 1.3806488e-16
r = 83144621.45468952
sigma = 5.670373e-05
sigma_t = 6.652458734e-25
a = 7.565731356724124e-15
e_v = 1.602176487e-12
j = 10000000.0
n = 100000.0
a... |
#
# PySNMP MIB module NOKIA-ALCHEMYOS-HARDWARE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NOKIA-ALCHEMYOS-HARDWARE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:23:17 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python vers... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_range_constraint, constraints_intersection, constraints_union, value_size_constraint) ... |
# Input contains a number of pairs of parentheses, extract each group seperately
stack = []
pairs = []
s = "Outer (First inner (first nested group) group) parentheses (another group)"
for i, char in enumerate(s):
if char == "(":
stack.append(i)
elif char == ")":
pairs.append((stack.pop(), i))... | stack = []
pairs = []
s = 'Outer (First inner (first nested group) group) parentheses (another group)'
for (i, char) in enumerate(s):
if char == '(':
stack.append(i)
elif char == ')':
pairs.append((stack.pop(), i))
for pair in pairs:
print(s[pair[0]:pair[1] + 1])
def get_group(ii, s):
s... |
# TODO: Add import statements
# Assign the data to predictor and outcome variables
# TODO: Load the data
train_data = None
X = None
y = None
# Create polynomial features
# TODO: Create a PolynomialFeatures object, then fit and transform the
# predictor feature
poly_feat = None
X_poly = None
# Make and fit the polyno... | train_data = None
x = None
y = None
poly_feat = None
x_poly = None
poly_model = None |
#
# @lc app=leetcode id=53 lang=python
#
# [53] Maximum Subarray
#
# https://leetcode.com/problems/maximum-subarray/description/
#
# algorithms
# Easy (42.84%)
# Total Accepted: 471.5K
# Total Submissions: 1.1M
# Testcase Example: '[-2,1,-3,4,-1,2,1,-5,4]'
#
# Given an integer array nums, find the contiguous subarr... | '''
class Solution(object):
max_sum = 0
max_lst = []
sum_lst = []
visited = []
def solver(self, nums, head, tail, sum_res):
if head > tail or head >= len(nums):
return
if self.visited[head] != -1 and self.visited[tail] != -1:
return
if sum_res >= self.... |
DB_VALUE_PREPROCESSING = "Calls or returns the specified input value's attribute when saved to the database"
FIXED_KWARGS = "Fixed run method keyword arguments"
IS_CONFIGURATION = "Whether this definition represents a configuration of the analysis (rather than data input)"
MAX_PARALLEL = "Maximal number of parallel exe... | db_value_preprocessing = "Calls or returns the specified input value's attribute when saved to the database"
fixed_kwargs = 'Fixed run method keyword arguments'
is_configuration = 'Whether this definition represents a configuration of the analysis (rather than data input)'
max_parallel = 'Maximal number of parallel exe... |
# Title : Print Prime Number till the specified limit
# Author : Kiran raj R.
# Date : 16:10:2020
userInput = int(input("Enter the limit of the prime number : "))
def primeLimit(limit):
for num in range(2, limit):
for i in range(2, num):
if num % i == 0:
break
else... | user_input = int(input('Enter the limit of the prime number : '))
def prime_limit(limit):
for num in range(2, limit):
for i in range(2, num):
if num % i == 0:
break
else:
print(num)
prime_limit(userInput) |
built_modules = list(name for name in
"Core;Gui;Widgets;PrintSupport;Sql;Network;Test;Concurrent;WinExtras;Xml;XmlPatterns;Help;Multimedia;MultimediaWidgets;OpenGL;OpenGLFunctions;Positioning;Location;Qml;Quick;QuickControls2;QuickWidgets;RemoteObjects;Scxml;Script;ScriptTools;Sensors;SerialPort;TextToSpeech;Charts... | built_modules = list((name for name in 'Core;Gui;Widgets;PrintSupport;Sql;Network;Test;Concurrent;WinExtras;Xml;XmlPatterns;Help;Multimedia;MultimediaWidgets;OpenGL;OpenGLFunctions;Positioning;Location;Qml;Quick;QuickControls2;QuickWidgets;RemoteObjects;Scxml;Script;ScriptTools;Sensors;SerialPort;TextToSpeech;Charts;Sv... |
class DelegateFake(object):
""" DelegateFake() """
def EditMacro(self,FileName):
""" EditMacro(self: DelegateFake,FileName: str) -> int """
pass
def ExplodeBentPlate(self,partId):
""" ExplodeBentPlate(self: DelegateFake,partId: int) -> int """
pass
def ExportAddComponentAttributeToStack(self,pAttr):
""" E... | class Delegatefake(object):
""" DelegateFake() """
def edit_macro(self, FileName):
""" EditMacro(self: DelegateFake,FileName: str) -> int """
pass
def explode_bent_plate(self, partId):
""" ExplodeBentPlate(self: DelegateFake,partId: int) -> int """
pass
def export_add_... |
# Collaborators: none
#
# Write a program that asks for the user's name and another piece of information.Then prints a response using both of the inputs.
x= input("Your name: ")
print ("Hello there, " + x + "!")
y= input("How are you, " + x + "?: ")
print (y + " huh, okay thank you " + x + ", for letting me know!") | x = input('Your name: ')
print('Hello there, ' + x + '!')
y = input('How are you, ' + x + '?: ')
print(y + ' huh, okay thank you ' + x + ', for letting me know!') |
class Solution:
def isMonotonic(self, A):
"""
:type A: List[int]
:rtype: bool
"""
is_asc = True
is_desc = True
for i in range(1, len(A)):
if A[i-1] < A[i]:
is_asc = False
if A[i-1] > A[i]:
is_des... | class Solution:
def is_monotonic(self, A):
"""
:type A: List[int]
:rtype: bool
"""
is_asc = True
is_desc = True
for i in range(1, len(A)):
if A[i - 1] < A[i]:
is_asc = False
if A[i - 1] > A[i]:
is_desc =... |
#!/usr/bin/constants
""" Collection of physical constants
Main source: http://physics.nist.gov/cuu/Constants/index.html
"""
def AMU():
""" Atomic mass unit, kg """
return 1.660538782e-27
def AVOGADRO():
""" Avogadro constant, mol^-1 """
return 6.02214179e23
def BOLTZMANN():
""" Boltzmann constan... | """ Collection of physical constants
Main source: http://physics.nist.gov/cuu/Constants/index.html
"""
def amu():
""" Atomic mass unit, kg """
return 1.660538782e-27
def avogadro():
""" Avogadro constant, mol^-1 """
return 6.02214179e+23
def boltzmann():
""" Boltzmann constant, J K^-1 """
re... |
t = int(input())
for _ in range(t):
l = list(map(str, input().split()))
for i in range(len(l) - 1):
l[i] = l[i][0].upper() + "."
l[len(l) - 1] = l[len(l) - 1][0].upper() + l[len(l) - 1][1:].lower()
print(" ".join(l)) | t = int(input())
for _ in range(t):
l = list(map(str, input().split()))
for i in range(len(l) - 1):
l[i] = l[i][0].upper() + '.'
l[len(l) - 1] = l[len(l) - 1][0].upper() + l[len(l) - 1][1:].lower()
print(' '.join(l)) |
# Time complexity: ?
# Space Complexity: ?
def newman_conway(num):
""" Returns a list of the Newman Conway numbers for the given value.
Time Complexity: O(n^2)
Space Complexity: O(n)
"""
if num == 0:
raise ValueError("ValueError")
if num == 1:
return '1'
s='1 1'
... | def newman_conway(num):
""" Returns a list of the Newman Conway numbers for the given value.
Time Complexity: O(n^2)
Space Complexity: O(n)
"""
if num == 0:
raise value_error('ValueError')
if num == 1:
return '1'
s = '1 1'
arr = [0, 1, 1]
for num in range(3, n... |
num = 10
if num < 10:
print("number is less than 10")
elif num > 10:
print("number is greater than 10")
else:
print("the number is equal to 10")
| num = 10
if num < 10:
print('number is less than 10')
elif num > 10:
print('number is greater than 10')
else:
print('the number is equal to 10') |
"""Definition of chips."""
AM33XX = "AM33XX"
DRA74X = "DRA74X"
IMX6ULL = "IMX6ULL"
IMX8MX = "IMX8MX"
BCM2XXX = "BCM2XXX"
ESP8266 = "ESP8266"
EXYNOS5422 = "EXYNOS5422"
RYZEN_V1202B = "RYZEN_V1202B"
RYZEN_V1605B = "RYZEN_V1605B"
SAMD21 = "SAMD21"
SUN8I = "SUN8I"
S805 = "S805"
S905 = "S905"
S905X3 = "S905X3"
S922X = "S922... | """Definition of chips."""
am33_xx = 'AM33XX'
dra74_x = 'DRA74X'
imx6_ull = 'IMX6ULL'
imx8_mx = 'IMX8MX'
bcm2_xxx = 'BCM2XXX'
esp8266 = 'ESP8266'
exynos5422 = 'EXYNOS5422'
ryzen_v1202_b = 'RYZEN_V1202B'
ryzen_v1605_b = 'RYZEN_V1605B'
samd21 = 'SAMD21'
sun8_i = 'SUN8I'
s805 = 'S805'
s905 = 'S905'
s905_x3 = 'S905X3'
s922... |
class Action(object):
def __init__(self, actionroot):
self.name = actionroot.find('./name').text
argumentLists = None
if len(actionroot.findall('./argumentList/argument')) > 0:
argumentLists = actionroot.findall('./argumentList/argument')
else:
argumentLists ... | class Action(object):
def __init__(self, actionroot):
self.name = actionroot.find('./name').text
argument_lists = None
if len(actionroot.findall('./argumentList/argument')) > 0:
argument_lists = actionroot.findall('./argumentList/argument')
else:
argument_lis... |
description = 'detector setup'
group = 'lowlevel'
devices = dict(
monitor = device('nicos.devices.generic.VirtualCounter',
description = 'simulated monitor',
fmtstr = '%d',
type = 'monitor',
visibility = (),
),
timer = device('nicos.devices.generic.VirtualTimer',
de... | description = 'detector setup'
group = 'lowlevel'
devices = dict(monitor=device('nicos.devices.generic.VirtualCounter', description='simulated monitor', fmtstr='%d', type='monitor', visibility=()), timer=device('nicos.devices.generic.VirtualTimer', description='simulated timer', fmtstr='%.2f', visibility=()), image=dev... |
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
'''
T: O(n log k) and S: O(k)
result = []
for i in range(len(nums) - k + 1):
numsK = nums[i: i + k]
heapq._heapify_max(numsK)
result.append(numsK[0])
... | class Solution:
def max_sliding_window(self, nums: List[int], k: int) -> List[int]:
"""
T: O(n log k) and S: O(k)
result = []
for i in range(len(nums) - k + 1):
numsK = nums[i: i + k]
heapq._heapify_max(numsK)
result.append(numsK[0])
... |
# Marc's Cakewalk
# Developer: Murillo Grubler
# Link: https://www.hackerrank.com/challenges/marcs-cakewalk/problem
# Function O(n)
def must_walk(n, arr):
count = 0
for i in range(n):
count = count + (arr[i] * (2 ** i))
return count
n = int(input().strip())
calories = sorted(list(map(int, inpu... | def must_walk(n, arr):
count = 0
for i in range(n):
count = count + arr[i] * 2 ** i
return count
n = int(input().strip())
calories = sorted(list(map(int, input().strip().split(' '))), reverse=True)
print(must_walk(n, calories)) |
class LinkedListException(Exception):
pass
class Node(object):
def __init__(self, value, next_node, previous_node=None):
self.value = value
self.next_node = next_node
self.previous_node = previous_node
class _LinkedList(object):
def __init__(self):
self.last_nod... | class Linkedlistexception(Exception):
pass
class Node(object):
def __init__(self, value, next_node, previous_node=None):
self.value = value
self.next_node = next_node
self.previous_node = previous_node
class _Linkedlist(object):
def __init__(self):
self.last_node = None
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.