content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#!/usr/bin/env python3
'''a gcode scraper that performs common functions
for gcode editing purposes. gscrape is desiged to
enable more effecient writing of macros for machine
programmers who wish to automate code formatting'''
class gscrape():
def __init__(self):
self._comment_flags = dict()
def ad... | """a gcode scraper that performs common functions
for gcode editing purposes. gscrape is desiged to
enable more effecient writing of macros for machine
programmers who wish to automate code formatting"""
class Gscrape:
def __init__(self):
self._comment_flags = dict()
def add_comment_flag(self, name, ... |
#!/usr/bin/env python3
########################################################################
# #
# Program purpose: Gets all strobogrammatic numbers that are of #
# length 'n'. #
# ... | def gen_strobogrammatic(num):
"""
Compute various numbers of 'n'
:param num: Number
:return: List of string.
"""
result = helper(num=num, length=num)
return result
def helper(num, length):
if num == 0:
return ['']
if num == 1:
return ['1', '0', '8']
middles = hel... |
class FONT_MODULE:
""" font name too long can't remember """
def __init__(self, parent):
self.parent = parent
self.commands = {
"retro": self.retro,
"futurism": self.futurism,
"stream": self.stream,
"default": self.default,
}
self.add_self()
def retro(self, arg=None):
self.parent.font_set(... | class Font_Module:
""" font name too long can't remember """
def __init__(self, parent):
self.parent = parent
self.commands = {'retro': self.retro, 'futurism': self.futurism, 'stream': self.stream, 'default': self.default}
self.add_self()
def retro(self, arg=None):
self.par... |
# Find the element that appears once
# https://www.geeksforgeeks.org/find-the-element-that-appears-once/
# SGVP387500 | 14:47 26F19
# fun to find the element that appears once
def getSingle(arr, n):
print("getSingle()- start | 14:55 26F19")
ones = 0
twos = 0
for i in range(n):
twos = twos | (o... | def get_single(arr, n):
print('getSingle()- start | 14:55 26F19')
ones = 0
twos = 0
for i in range(n):
twos = twos | ones & arr[i]
ones = ones ^ arr[i]
common_bit_mask = ~(ones & twos)
ones &= common_bit_mask
twos &= common_bit_mask
return ones
def opposite_s... |
def can_build(platform):
# FIXME: Disabled temporary for gles3 implementation
return False
def configure(env):
pass
| def can_build(platform):
return False
def configure(env):
pass |
tupla = (2,5,9,12)
print(tupla)
segundo_elemento = tupla[1]
print(segundo_elemento)
tupla1 = (2,)
print(tupla1)
tupla_de_lista = tuple([2,5,8])
print(tupla_de_lista)
lista_de_tupla = list(tupla)
print(lista_de_tupla)
tupla_elemento_mutavel = (9,[2,5],12)
print(tupla_elemento_mutavel)
# erro - AttributeError: 'int... | tupla = (2, 5, 9, 12)
print(tupla)
segundo_elemento = tupla[1]
print(segundo_elemento)
tupla1 = (2,)
print(tupla1)
tupla_de_lista = tuple([2, 5, 8])
print(tupla_de_lista)
lista_de_tupla = list(tupla)
print(lista_de_tupla)
tupla_elemento_mutavel = (9, [2, 5], 12)
print(tupla_elemento_mutavel) |
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def set_width(self, new_width):
self.width = new_width
def set_height(self, new_height):
self.height = new_height
def get_area(self):
return self.width * self.height
... | class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def set_width(self, new_width):
self.width = new_width
def set_height(self, new_height):
self.height = new_height
def get_area(self):
return self.width * self.height
... |
class ClassForTesting:
def use_this_func(self, a):
return a
class ClassForTesting2(ClassForTesting):
def use_this_func(self, a):
b = a * 10
return b
class ClassForTesting3(ClassForTesting):
pass
class ClassForTesting4(ClassForTesting2):
def use_this_func(self, a):
b... | class Classfortesting:
def use_this_func(self, a):
return a
class Classfortesting2(ClassForTesting):
def use_this_func(self, a):
b = a * 10
return b
class Classfortesting3(ClassForTesting):
pass
class Classfortesting4(ClassForTesting2):
def use_this_func(self, a):
b... |
class ResourceMetadata (object):
def __init__(self, system_meta, science_meta):
self.__dict__.update(science_meta)
self.__dict__.update(system_meta)
@property
def url(self):
return self.resource_url
@property
def abstract(self):
return self.description
@prop... | class Resourcemetadata(object):
def __init__(self, system_meta, science_meta):
self.__dict__.update(science_meta)
self.__dict__.update(system_meta)
@property
def url(self):
return self.resource_url
@property
def abstract(self):
return self.description
@propert... |
# -*- coding: utf-8 -*-
__version__ = '0.2.0'
__doc__ = """
TERA : the Toxicological and Risk Assessment Knowledge Graph.
The set of APIs enables aggregation, integration and access of several data sources relevant to the toxicological and risk assessment domain.
"""
| __version__ = '0.2.0'
__doc__ = '\n TERA : the Toxicological and Risk Assessment Knowledge Graph. \n \n The set of APIs enables aggregation, integration and access of several data sources relevant to the toxicological and risk assessment domain. \n' |
x = 0
depth = 0
with open("data.txt", "r+") as f:
lines = f.readlines()
for line in lines:
commands = line.split(" ")
direction = commands[0]
val = int(commands[1])
match direction:
case "down":
depth += val
case "up":
... | x = 0
depth = 0
with open('data.txt', 'r+') as f:
lines = f.readlines()
for line in lines:
commands = line.split(' ')
direction = commands[0]
val = int(commands[1])
match direction:
case 'down':
depth += val
case 'up':
depth... |
#Sintaxis basica de una funcion
def mi_funcion():
print("Ejecucion de la funcion")
#Llamando la funcion
mi_funcion() | def mi_funcion():
print('Ejecucion de la funcion')
mi_funcion() |
class Solution:
# my solution
def heightChecker(self, heights: List[int]) -> int:
ordered = sorted(heights)
res = 0
for i, j in zip(ordered, heights):
if i != j:
res += 1
return res | class Solution:
def height_checker(self, heights: List[int]) -> int:
ordered = sorted(heights)
res = 0
for (i, j) in zip(ordered, heights):
if i != j:
res += 1
return res |
def early_stop(cost_window):
if len(cost_window) < 2:
return False
else:
curr = cost_window[0]
for idx, cost in enumerate(cost_window):
if curr < cost or idx == 0:
curr = cost
else:
return False
return True
def early_stop2... | def early_stop(cost_window):
if len(cost_window) < 2:
return False
else:
curr = cost_window[0]
for (idx, cost) in enumerate(cost_window):
if curr < cost or idx == 0:
curr = cost
else:
return False
return True
def early_stop... |
# 3.1
names = ['john', 'dirk', 'elon', 'rita', 'bob']
print(names[0])
print(names[1])
print(names[2])
print(names[3])
print(names[4])
# 3.2
print(f'Hello, {names[0].title()}')
print(f'Hello, {names[1].title()}')
print(f'Hello, {names[2].title()}')
print(f'Hello, {names[3].title()}')
print(f'Hello, {names[4].title()}')... | names = ['john', 'dirk', 'elon', 'rita', 'bob']
print(names[0])
print(names[1])
print(names[2])
print(names[3])
print(names[4])
print(f'Hello, {names[0].title()}')
print(f'Hello, {names[1].title()}')
print(f'Hello, {names[2].title()}')
print(f'Hello, {names[3].title()}')
print(f'Hello, {names[4].title()}')
vehicles = [... |
first = int(input('Write a initial term of an arithmetic progression:'))
difference = int(input('Write a common difference:'))
term = first
cont = 1
while cont <= 10:
print('{} -> '.format(term), end='')
term += difference
cont += 1
print('Many terms {}'.format(cont-1))
| first = int(input('Write a initial term of an arithmetic progression:'))
difference = int(input('Write a common difference:'))
term = first
cont = 1
while cont <= 10:
print('{} -> '.format(term), end='')
term += difference
cont += 1
print('Many terms {}'.format(cont - 1)) |
"""
Graph representation - 2 main forms:
--------------------
-> use an adjacency matrix & a dictionary
-> use an adjacency list
-> Adjacency list
-----------------
- Use a simple list can be used to present a graph. The indices of the list will represent the nodes/vertices in the
graph. At each index, the adjacent n... | """
Graph representation - 2 main forms:
--------------------
-> use an adjacency matrix & a dictionary
-> use an adjacency list
-> Adjacency list
-----------------
- Use a simple list can be used to present a graph. The indices of the list will represent the nodes/vertices in the
graph. At each index, the adjacent n... |
def kowsi():
global x
x="blue"
print("Color is "+x)
kowsi() | def kowsi():
global x
x = 'blue'
print('Color is ' + x)
kowsi() |
############################################################################
## MagicQ FX Constants
## July 22, 2016
## Austin Tyler
##
## Reference: MagicQ Manual - Chapter 31. ChamSys Remote Protocol Commands
## http://chamsys.co.uk
#####################################################################... | fx_1 = 14
fx_2 = 15
fx_3 = 34
fx_4 = 35
fx_5 = 36
fx_6 = 37
fx_7 = 38
fx_8 = 39 |
class Error(Exception):
"""Base class for other exceptions"""
pass
class LoginTimeoutError(Error):
"""Raised login to device times out"""
pass
class LoginCredentialsError(Error):
"""Raised when there is a problem with the user credentials"""
pass
| class Error(Exception):
"""Base class for other exceptions"""
pass
class Logintimeouterror(Error):
"""Raised login to device times out"""
pass
class Logincredentialserror(Error):
"""Raised when there is a problem with the user credentials"""
pass |
# 01-08-2021
# Emma Benjaminson
# Binary Tree Implementation (v1)
# Source: https://medium.com/swlh/making-data-trees-in-python-3a3ceb050cfd
class Tree():
def __init__(self, root):
self.root = root
self.children = []
def addNode(self, obj):
self.children.append(obj)
class Node():
... | class Tree:
def __init__(self, root):
self.root = root
self.children = []
def add_node(self, obj):
self.children.append(obj)
class Node:
def __init__(self, data):
self.data = data
self.children = []
def add_node(self, obj):
self.children.append(obj) |
#!/usr/bin/env python3
'''
Return True if every even index contains an even number and every odd index contains an odd number. Else return False
'''
def is_special_array(lst):
a = [i for i in lst[::2] if i % 2 == 1]
b = [i for i in lst[1::2] if i % 2 == 0]
return len(a) == len(b)
#Alternative Solutions
def is_spec... | """
Return True if every even index contains an even number and every odd index contains an odd number. Else return False
"""
def is_special_array(lst):
a = [i for i in lst[::2] if i % 2 == 1]
b = [i for i in lst[1::2] if i % 2 == 0]
return len(a) == len(b)
def is_special_array(lst):
return all((lst[... |
# -*- coding: utf-8 -*-
class NotFoundSchema(Exception):
""" When can't find schema raise exception """
pass
| class Notfoundschema(Exception):
""" When can't find schema raise exception """
pass |
def run(program):
program_counter = 0
while True:
op_code = program[program_counter]
if op_code == 1:
program[program[program_counter + 3]] = program[program[program_counter + 2]] + program[
program[program_counter + 1]]
elif op_code == 2:
program[... | def run(program):
program_counter = 0
while True:
op_code = program[program_counter]
if op_code == 1:
program[program[program_counter + 3]] = program[program[program_counter + 2]] + program[program[program_counter + 1]]
elif op_code == 2:
program[program[program_c... |
class Subkey:
def __init__(self, value, origin: str, output_matching: bool=False):
'''
Params
-------
value:
subkey value corresponding to a Vset module
origin: str
name of the origin Vset of this Subkey
output_matching: inherited from the Vse... | class Subkey:
def __init__(self, value, origin: str, output_matching: bool=False):
"""
Params
-------
value:
subkey value corresponding to a Vset module
origin: str
name of the origin Vset of this Subkey
output_matching: inherited from the Vse... |
# how count the number of items in a list
# define count function
def conteggio(numbers):
total = 0
for x in numbers: # rolling sum
if x < 20:
total += 1
return total
list_1 = [1, 3, 5, 7, 15, 23, 43, 56, 78]
conteggio(list_1)
| def conteggio(numbers):
total = 0
for x in numbers:
if x < 20:
total += 1
return total
list_1 = [1, 3, 5, 7, 15, 23, 43, 56, 78]
conteggio(list_1) |
#!/usr/bin/python
class Problem7:
'''
'''
def solution(self):
return 0
p = Problem7()
print(p.solution()) | class Problem7:
"""
"""
def solution(self):
return 0
p = problem7()
print(p.solution()) |
#!/bin/python3
if __name__ == '__main__':
n = int(input().strip())
if (n % 2) != 0 :
print("Weird")
elif ((n%2)==0) and n in range(6,21):
print("Weird")
elif ((n % 2) ==0) and n in range(2,5):
print("Not Weird")
elif ((n % 2) == 0) and n > 20:
print("Not Weird"... | if __name__ == '__main__':
n = int(input().strip())
if n % 2 != 0:
print('Weird')
elif n % 2 == 0 and n in range(6, 21):
print('Weird')
elif n % 2 == 0 and n in range(2, 5):
print('Not Weird')
elif n % 2 == 0 and n > 20:
print('Not Weird') |
def anagram_check(s1: str, s2: str):
s1 = s1.replace(' ', '').lower()
s2 = s2.replace(' ', '').lower()
if len(s1) != len(s2):
return False
cache = {}
for char in s1:
cache[char] = cache.get(char, 0) + 1
for char in s2:
if not cache.get(char):
return False
... | def anagram_check(s1: str, s2: str):
s1 = s1.replace(' ', '').lower()
s2 = s2.replace(' ', '').lower()
if len(s1) != len(s2):
return False
cache = {}
for char in s1:
cache[char] = cache.get(char, 0) + 1
for char in s2:
if not cache.get(char):
return False
... |
IN1 = 29
IN2 = 31
IN3 = 33
IN4 = 35
AvoidSensorfor = 40
AvoidSensorbac = 38 | in1 = 29
in2 = 31
in3 = 33
in4 = 35
avoid_sensorfor = 40
avoid_sensorbac = 38 |
"""In-order, pre-order, and post-order tree traversal."""
class Node(object):
def __init__(self, val):
self.left = None
self.right = None
self.value = val
def inOrder(root):
if not root:
return
out = []
l = inOrder(root.left)
if l:
out.extend(l)
out.append(root.value)
r = inOrder(r... | """In-order, pre-order, and post-order tree traversal."""
class Node(object):
def __init__(self, val):
self.left = None
self.right = None
self.value = val
def in_order(root):
if not root:
return
out = []
l = in_order(root.left)
if l:
out.extend(l)
out.a... |
# -*- coding: utf-8 -*-
xy = list(map(int, input().split()))
lh0 = list(map(int, input().split()))
lh1 = list(map(int, input().split()))
if lh0[1] + lh1[1] <= xy[1] and max(lh0[0], lh1[0]) <= xy[0]:
print("S")
elif lh0[0] + lh1[1] <= xy[1] and max(lh0[1], lh1[0]) <= xy[0]:
print("S")
elif lh0[1] + lh1[0] <=... | xy = list(map(int, input().split()))
lh0 = list(map(int, input().split()))
lh1 = list(map(int, input().split()))
if lh0[1] + lh1[1] <= xy[1] and max(lh0[0], lh1[0]) <= xy[0]:
print('S')
elif lh0[0] + lh1[1] <= xy[1] and max(lh0[1], lh1[0]) <= xy[0]:
print('S')
elif lh0[1] + lh1[0] <= xy[1] and max(lh0[0], lh1[1... |
class Purchase:
def __init__(self, product_name, cost):
self.product_name = product_name
self.cost = cost
def __add__(self, other):
name = f'{self.product_name}, {other.product_name}'
cost = self.cost + other.cost
return Purchase(name, cost)
def __repr__(self):
... | class Purchase:
def __init__(self, product_name, cost):
self.product_name = product_name
self.cost = cost
def __add__(self, other):
name = f'{self.product_name}, {other.product_name}'
cost = self.cost + other.cost
return purchase(name, cost)
def __repr__(self):
... |
HTTP_OK = 200
HTTP_PARTIAL = 206
| http_ok = 200
http_partial = 206 |
def get_part2_input():
with open('Day3_input_part2.txt','r') as input_file:
input = input_file.read().split("\n")
# There is a "\n" at the end that gives problems, we simply delete it
del input[-1]
return input
def solve_part1(input_file):
with open(input_file,'r') as input:
... | def get_part2_input():
with open('Day3_input_part2.txt', 'r') as input_file:
input = input_file.read().split('\n')
del input[-1]
return input
def solve_part1(input_file):
with open(input_file, 'r') as input:
bits = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: ... |
class CommandIODefinition:
"""Class which contains a set of inputs and outputs for a command,
based on the configuration.
"""
def __init__(self,
input_uris=None,
output_uris=None,
missing_input_messages=None):
if input_uris is None:
... | class Commandiodefinition:
"""Class which contains a set of inputs and outputs for a command,
based on the configuration.
"""
def __init__(self, input_uris=None, output_uris=None, missing_input_messages=None):
if input_uris is None:
input_uris = set([])
if output_uris is ... |
# Algorytmy Grafowe
# Piotr Faliszewski 2019
# Load graph in the DIMACS ascii format + weights
def loadCNFFormula( name ):
"""Load a CNF formula in the DIMACS ascii format from
the file "name" and return it as a list of clauses
Returns (V,F)
V -- highest variable number
F -- list of clauses"""
... | def load_cnf_formula(name):
"""Load a CNF formula in the DIMACS ascii format from
the file "name" and return it as a list of clauses
Returns (V,F)
V -- highest variable number
F -- list of clauses"""
v = 0
l = []
f = open(name, 'r')
lines = f.readlines()
for l in lines:
... |
clist = [
"\\c[uh0]", "\\c[uh1]", "\\c[uh2]", "\\c[uh3]", "\\c[uh4]", "\\c[uh5]", "\\c[uh6]", "\\c[uh7]", "\\c[uh8]",
"\\c[uh9]", "\\c[uh10]", "\\c[uh11]", "\\c[uh12]", "\\c[uh13]", "\\c[uh14]", "\\c[uh15]", "\\c[uh16]", "\\c[uh17]",
"\\c[uh18]", "\\c[uh19]", "\\c[uh20]", "\\c[uh21]", "\\c[uh22]", "\\c[uh23]", ... | clist = ['\\c[uh0]', '\\c[uh1]', '\\c[uh2]', '\\c[uh3]', '\\c[uh4]', '\\c[uh5]', '\\c[uh6]', '\\c[uh7]', '\\c[uh8]', '\\c[uh9]', '\\c[uh10]', '\\c[uh11]', '\\c[uh12]', '\\c[uh13]', '\\c[uh14]', '\\c[uh15]', '\\c[uh16]', '\\c[uh17]', '\\c[uh18]', '\\c[uh19]', '\\c[uh20]', '\\c[uh21]', '\\c[uh22]', '\\c[uh23]', '\\c[uh24... |
'''
.. module:: dsge
:platform: Linux
:synopsis: The dsge module is just a package which contains all of the modules required to do DSGE modelling, that is solving
them and then doing further work with the obtained solutions, such as simulating and generating IRFs.
.. moduleauthor:: Eric M. Scheffe... | """
.. module:: dsge
:platform: Linux
:synopsis: The dsge module is just a package which contains all of the modules required to do DSGE modelling, that is solving
them and then doing further work with the obtained solutions, such as simulating and generating IRFs.
.. moduleauthor:: Eric M. Scheffe... |
MEMCACHE_HOST="127.0.0.1"
MEMCACHE_PORT=11211
MONGO_HOST="localhost"
MONGO_PORT="27017"
MONGO_DB="taskqueue"
MONGO_LOG_COLLECTION="tasklog"
MONGO_TOMBSTONE_COLLECTION="tombstones"
BROKER_URL = "pyamqp://someuser:somepassword@somehost.somedomain.com:5672/somevhost"
CELERY_RESULT_BACKEND = "mongodb"
CELERY_MONGODB_BAC... | memcache_host = '127.0.0.1'
memcache_port = 11211
mongo_host = 'localhost'
mongo_port = '27017'
mongo_db = 'taskqueue'
mongo_log_collection = 'tasklog'
mongo_tombstone_collection = 'tombstones'
broker_url = 'pyamqp://someuser:somepassword@somehost.somedomain.com:5672/somevhost'
celery_result_backend = 'mongodb'
celery_... |
if __name__ == '__main__':
s = 'spam'
print(dir(s))
print(dir(str))
print(s + 'ni!')
print(s.__add__('ni!'))
print(help(s.replace))
print(help(str.replace))
| if __name__ == '__main__':
s = 'spam'
print(dir(s))
print(dir(str))
print(s + 'ni!')
print(s.__add__('ni!'))
print(help(s.replace))
print(help(str.replace)) |
overlapping = (
((1, 5), (2, 6)),
((5, 7), (3, 7)),
((-3, 6), (-7, -1)),
((2, 3), (2.5, 5.5))
)
overlapping_edge = (
((-6, -4), (-5.5, -4.5)),
((1, 9), (5, 6)),
((5, 6), (1, 9)),
((1, 5), (1, 5)),
((1, 1), (1, 1)),
((1, 1), (2, 1)),
((0, 4), (4, 8)),
((4, 6.1), (5.9, 8))... | overlapping = (((1, 5), (2, 6)), ((5, 7), (3, 7)), ((-3, 6), (-7, -1)), ((2, 3), (2.5, 5.5)))
overlapping_edge = (((-6, -4), (-5.5, -4.5)), ((1, 9), (5, 6)), ((5, 6), (1, 9)), ((1, 5), (1, 5)), ((1, 1), (1, 1)), ((1, 1), (2, 1)), ((0, 4), (4, 8)), ((4, 6.1), (5.9, 8)), ((5, 1), (2, 4)))
not_overlapping_edge = (((4, 5.9... |
"""Custom Exceptions."""
class NoDataFound(Exception):
"""Exception for when no data was found for request."""
class UnitsError(Exception):
"""Exception for bad Units."""
class TextProductException(Exception):
"""Exception for Text Parsing."""
class HWOException(Exception):
"""Exception for HWO ... | """Custom Exceptions."""
class Nodatafound(Exception):
"""Exception for when no data was found for request."""
class Unitserror(Exception):
"""Exception for bad Units."""
class Textproductexception(Exception):
"""Exception for Text Parsing."""
class Hwoexception(Exception):
"""Exception for HWO Pars... |
# https://leetcode.com/problems/keep-multiplying-found-values-by-two/
class Solution:
def findFinalValue(self, nums: List[int], original: int) -> int:
while True:
if original in nums:
original *= 2
else:
return original
| class Solution:
def find_final_value(self, nums: List[int], original: int) -> int:
while True:
if original in nums:
original *= 2
else:
return original |
print("Begin")
i=input('Enter fno:')
j=input('Enter sno:')
try:
x=int(i)
y=int(j)
z=x/y
print(z)
except:
print('Erroor occured')
print('End')
| print('Begin')
i = input('Enter fno:')
j = input('Enter sno:')
try:
x = int(i)
y = int(j)
z = x / y
print(z)
except:
print('Erroor occured')
print('End') |
dict = {'sape': '4139', 'guido': '666'}
for k, i in dict.items():
print(k,i)
| dict = {'sape': '4139', 'guido': '666'}
for (k, i) in dict.items():
print(k, i) |
class Solution:
def minCost(self, costs: List[List[int]]) -> int:
if not costs:
return 0
if len(costs) == 1:
return min(costs[0])
def dfs(costs, prev):
if not costs:
return 0
r = b = g = float("inf")
if prev != "red"... | class Solution:
def min_cost(self, costs: List[List[int]]) -> int:
if not costs:
return 0
if len(costs) == 1:
return min(costs[0])
def dfs(costs, prev):
if not costs:
return 0
r = b = g = float('inf')
if prev != 'r... |
ecoopgroup = {}
ecoopgroup['TWC'] = {}
ecoopgroup['TWC']['subgroup'] = ''
ecoopgroup['TWC']['organization'] = ''
ecoopgroup['TWC']['homepageURL'] = ''
ecoopgroup['TWC']['mbox'] = ''
ecoopgroup['TWC']['address'] = ''
ecoopgroup['TWC']['phone'] = ''
ecoopgroup['TWC']['name'] = 'TWC'
ecoopgroup['TWC']['members'] = '' | ecoopgroup = {}
ecoopgroup['TWC'] = {}
ecoopgroup['TWC']['subgroup'] = ''
ecoopgroup['TWC']['organization'] = ''
ecoopgroup['TWC']['homepageURL'] = ''
ecoopgroup['TWC']['mbox'] = ''
ecoopgroup['TWC']['address'] = ''
ecoopgroup['TWC']['phone'] = ''
ecoopgroup['TWC']['name'] = 'TWC'
ecoopgroup['TWC']['members'] = '' |
# Equality
print(2 == 2)
print(1 == 2)
print('hello' == 'bye')
print('Bye' == 'bye')
# Not Equality
print(3 != 3)
print(4 != 5)
# Greater than
print(1 > 3)
print(5 > 2)
# Less than
print(30 < 10)
print(5 < 7)
# Greater than or equal
print(3 >= 3)
print(4 >= 3)
print(1 >= 3)
# Less than or equal
print(3 <= 3)
print... | print(2 == 2)
print(1 == 2)
print('hello' == 'bye')
print('Bye' == 'bye')
print(3 != 3)
print(4 != 5)
print(1 > 3)
print(5 > 2)
print(30 < 10)
print(5 < 7)
print(3 >= 3)
print(4 >= 3)
print(1 >= 3)
print(3 <= 3)
print(4 <= 3)
print(1 <= 3) |
load("@bazel_skylib//lib:dicts.bzl", "dicts")
load("@build_bazel_rules_nodejs//:index.bzl", "yarn_install")
load("@rules_haskell//haskell:repositories.bzl", "rules_haskell_dependencies")
load("@rules_haskell//haskell:toolchain.bzl", "rules_haskell_toolchains")
load("@rules_haskell//haskell:cabal.bzl", "stack_snapshot")... | load('@bazel_skylib//lib:dicts.bzl', 'dicts')
load('@build_bazel_rules_nodejs//:index.bzl', 'yarn_install')
load('@rules_haskell//haskell:repositories.bzl', 'rules_haskell_dependencies')
load('@rules_haskell//haskell:toolchain.bzl', 'rules_haskell_toolchains')
load('@rules_haskell//haskell:cabal.bzl', 'stack_snapshot')... |
# Reading input file
f = open("inputs/day05.txt", "r")
lines = f.readlines()
def get_position(low, high, seat_code, lower_label):
if high - low == 2:
if len(seat_code) == 1:
if seat_code == lower_label:
return low
else:
return high - 1
else:
... | f = open('inputs/day05.txt', 'r')
lines = f.readlines()
def get_position(low, high, seat_code, lower_label):
if high - low == 2:
if len(seat_code) == 1:
if seat_code == lower_label:
return low
else:
return high - 1
else:
return 0
... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
def add_node(self,x):
if self.next is None:
self.next=ListNode(x)... | class Solution:
def remove_nth_from_end(self, head: ListNode, n: int) -> ListNode:
def add_node(self, x):
if self.next is None:
self.next = list_node(x)
else:
self.next.add_node(x)
ListNode.add_node = add_node
vals = [head.val]
... |
class OrderError(ValueError):
pass
class CompoundedError(ValueError):
pass | class Ordererror(ValueError):
pass
class Compoundederror(ValueError):
pass |
#%%
"""
- Beautiful Arrangement
- https://leetcode.com/problems/beautiful-arrangement/
- Medium
Suppose you have N integers from 1 to N. We define a beautiful arrangement as an array that is constructed by these N numbers successfully if one of the following is true for the ith position (1 <= i <= N) in this array:
T... | """
- Beautiful Arrangement
- https://leetcode.com/problems/beautiful-arrangement/
- Medium
Suppose you have N integers from 1 to N. We define a beautiful arrangement as an array that is constructed by these N numbers successfully if one of the following is true for the ith position (1 <= i <= N) in this array:
The n... |
"""
INPUTS AND EXPECTED OUTPUTS:-
9 => "1001"
60 => "0011_1100"
100 => "0110_0100"
63000 => "1111_0110_0001_1000"
"""
def get_binary(n):
s = bin(n)[2:]; # Getting binary string
strs = [];
while s:
l = len(s); # Finding lenght of binary string
if l > 4:
strs.insert(0, s[l-4:]);
s = s[:l... | """
INPUTS AND EXPECTED OUTPUTS:-
9 => "1001"
60 => "0011_1100"
100 => "0110_0100"
63000 => "1111_0110_0001_1000"
"""
def get_binary(n):
s = bin(n)[2:]
strs = []
while s:
l = len(s)
if l > 4:
strs.insert(0, s[l - 4:])
s = s[:l - 4]
else:
... |
class AmazonItem(object):
def __init__(self, title, price, picture_url, amazon_url):
self.title = title
self.price = price
self.picture_url = picture_url
self.amazon_url = amazon_url
| class Amazonitem(object):
def __init__(self, title, price, picture_url, amazon_url):
self.title = title
self.price = price
self.picture_url = picture_url
self.amazon_url = amazon_url |
"""Plugin commands."""
async def on_reverse(app, message, *args):
"""Reverse the string in argument and send it back."""
if not args:
await app.send_message(message.channel,
f"_Usage: {app.prefixize('reverse')} string_")
else:
await app.send_message(message.ch... | """Plugin commands."""
async def on_reverse(app, message, *args):
"""Reverse the string in argument and send it back."""
if not args:
await app.send_message(message.channel, f"_Usage: {app.prefixize('reverse')} string_")
else:
await app.send_message(message.channel, ' '.join(args)[::-1]) |
#Create a class pets from a class Animals and further create class Dog from Pets. Add a method bark to class Dog.
class Animals:
animalType = "Mammal"
class Pets:
color = "White"
class Dog:
@staticmethod
def bark():
print("Bark")
d = Dog()
d.bark() | class Animals:
animal_type = 'Mammal'
class Pets:
color = 'White'
class Dog:
@staticmethod
def bark():
print('Bark')
d = dog()
d.bark() |
def create_task_from_section_a5(task_type):
# Cell numbering: [[[0, 1, 2]]]
# Desired solution: [[[0, 1, whatever]]]
grid_sizes = [1, 1, 3] # 1D example represented in 3D for generality
rays = [[0, 1, 2]] # linear indices of grid cells are listed for each ray
gradient_step_size = 1. # implicitly specified via... | def create_task_from_section_a5(task_type):
grid_sizes = [1, 1, 3]
rays = [[0, 1, 2]]
gradient_step_size = 1.0
ray_costs_occ = [[-2.0, -3.0, -2.0]]
ray_costs_occ = [[val * gradient_step_size for val in costs] for costs in ray_costs_occ]
ray_costs_free = [0.0]
return {'grid_sizes': grid_sizes... |
# -*- coding: utf-8 -*-
# (c) Copyright IBM Corp. 2010, 2021. All Rights Reserved.
# pragma pylint: disable=unused-argument, no-self-use
"""
File contains constants used in the integration.
"""
# Page size to for paged results from Resilient.
INC_PAGE_SIZE = 500
# Name of Resilient incident close status template file ... | """
File contains constants used in the integration.
"""
inc_page_size = 500
close_incident_template = 'incident_close.json'
package = 'fn-aws-guardduty'
path_to_templates = 'fn_aws_guardduty/data/templates/'
custom_fields_map = {'Id': 'aws_guardduty_finding_id', 'Arn': 'aws_guardduty_finding_arn', 'Type': 'aws_guarddu... |
class Object:
## `A << B -> A[B.tag] = B` left/tag slot assignment
def __lshift__(self, that):
that = self.box(that)
return self.__setitem__(that.tag(), that)
## `A // B -> A.push(B)` stack-like push to end of vector
def __floordiv__(self, that):
that = self.box(that)
s... | class Object:
def __lshift__(self, that):
that = self.box(that)
return self.__setitem__(that.tag(), that)
def __floordiv__(self, that):
that = self.box(that)
self.nest.append(that)
return self |
class ValueRange:
name: str
min: float
max: float
value: float
def __init__(self, name, min, max):
self.name = name
self.min = min
self.max = max
def __set__(self, parent, value):
if value not in range(self.min, self.max):
err = f'{self.name} is not... | class Valuerange:
name: str
min: float
max: float
value: float
def __init__(self, name, min, max):
self.name = name
self.min = min
self.max = max
def __set__(self, parent, value):
if value not in range(self.min, self.max):
err = f'{self.name} is not ... |
# Medium
# https://leetcode.com/problems/jump-game-ii/
# Time Complexity: O(n)
# Space Complexity: O(1)
class Solution:
def jump(self, nums: List[int]) -> int:
'''
Approach:
1) For every element in the array, Find the index at which it can reach by
taking the longest jump (i.e ... | class Solution:
def jump(self, nums: List[int]) -> int:
"""
Approach:
1) For every element in the array, Find the index at which it can reach by
taking the longest jump (i.e curr_index + element). Store these in an
array.
[2, 4, 5, 1, 1, 1, 1, 1]
... |
#!/usr/bin/env python
def filter(new_values, values=[]):
for new_value in new_values:
if new_value > 0:
values.append(new_value)
return values
if __name__ == '__main__':
value_list = [
[1, -3, 5],
[13, 33, -15],
]
for values in value_list:
print(f'filter... | def filter(new_values, values=[]):
for new_value in new_values:
if new_value > 0:
values.append(new_value)
return values
if __name__ == '__main__':
value_list = [[1, -3, 5], [13, 33, -15]]
for values in value_list:
print(f'filtering {values}')
filtered_values = filter... |
N_SEGMENTS = 5
FEDERATED_AGGREGATOR_HOST = "http://cte_federated_aggregator:8080"
ETA = 1.5
REGISTRATION_ENABLE = True
ACTIVE_ENCRYPTION = True
DATASETS_DIR = "./dataset"
KEY_LENGTH = 1024
DB_ENGINE = 'sqlite:////app/db/data_owner.db'
| n_segments = 5
federated_aggregator_host = 'http://cte_federated_aggregator:8080'
eta = 1.5
registration_enable = True
active_encryption = True
datasets_dir = './dataset'
key_length = 1024
db_engine = 'sqlite:////app/db/data_owner.db' |
matrix = []
with open('input') as f:
for row in f:
row_matrix = [x for x in row.split()]
matrix.append(row_matrix)
# print(matrix)
counter = 0
abc_list = []
total = []
for row in matrix:
# Empty line
if not row:
total.append(len(abc_list))
# print(len(abc_list))
ab... | matrix = []
with open('input') as f:
for row in f:
row_matrix = [x for x in row.split()]
matrix.append(row_matrix)
counter = 0
abc_list = []
total = []
for row in matrix:
if not row:
total.append(len(abc_list))
abc_list = []
continue
for i in row:
for ch in i:... |
print ("Enter temperature value in Celcius:")
celcius = input()
fcelcius = float (celcius)
fahrenheit = (fcelcius * 9) / 5 + 32
print(fahrenheit,"deg F")
| print('Enter temperature value in Celcius:')
celcius = input()
fcelcius = float(celcius)
fahrenheit = fcelcius * 9 / 5 + 32
print(fahrenheit, 'deg F') |
#
# PySNMP MIB module RIPv2-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RIPv2-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:03:31 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, 09:23... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, single_value_constraint, value_size_constraint, value_range_constraint) ... |
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
diff = 0
for num in nums:
diff ^= num
diff &= -diff
res = [0, 0]
for num in nums:
if diff & num == 0:
... | class Solution(object):
def single_number(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
diff = 0
for num in nums:
diff ^= num
diff &= -diff
res = [0, 0]
for num in nums:
if diff & num == 0:
... |
# class MyAdaptorEditInline(object):
# @classmethod
# def can_edit(cls, adaptor_field):
# user = adaptor_field.request.user
# obj = adaptor_field.obj
# can_edit = False
# if user.is_anonymous():
# pass
# elif user.is_superuser:
# can_edit = True
#... | class Myadaptoreditinline(object):
@classmethod
def can_edit(cls, adaptor_field):
can_edit = True
return can_edit |
# TODO: Implement input interupts if needed
class PCF8574:
def __init__(self, i2c, address):
self._i2c = i2c
self._address = address
self._input = 0 # Buffers the result of read in memory
self._input_mask = 0 # Mask specifying which pins are set as input
self._output = 0 #... | class Pcf8574:
def __init__(self, i2c, address):
self._i2c = i2c
self._address = address
self._input = 0
self._input_mask = 0
self._output = 0
self._write()
def _read(self):
self._input = self._i2c.readfrom(self._address, 1)[0] & self._input_mask
de... |
options = {
1: "All",
2: "Arrays and Strings",
3: "Linked Lists",
4: "Stacks and Queues",
5: "Trees and Graphs",
6: "Bit Manipulation",
7: "Math and Logic",
8: "Recursion and Dynamic Programming",
9: "Sorting and Searching",
10: "System Design and Scalability",
11: "Object-Oriented Design",
12: "Testing",
... | options = {1: 'All', 2: 'Arrays and Strings', 3: 'Linked Lists', 4: 'Stacks and Queues', 5: 'Trees and Graphs', 6: 'Bit Manipulation', 7: 'Math and Logic', 8: 'Recursion and Dynamic Programming', 9: 'Sorting and Searching', 10: 'System Design and Scalability', 11: 'Object-Oriented Design', 12: 'Testing', 13: 'Databases... |
"""Tests for the HTTP REST API base."""
def test_access_index_url_returning_200_status_code(client):
"""
GIVEN a Flask application
WHEN the '/' URL is requested (GET)
THEN check the response is valid
"""
response = client.get('/')
assert response.status_code == 200
assert response.dat... | """Tests for the HTTP REST API base."""
def test_access_index_url_returning_200_status_code(client):
"""
GIVEN a Flask application
WHEN the '/' URL is requested (GET)
THEN check the response is valid
"""
response = client.get('/')
assert response.status_code == 200
assert response.data ... |
main_input = input()
robot_count = int(main_input.split(" ")[0])
max_height = int(main_input.split(" ")[1])
robot_height = 0
for specific_robot in range(robot_count):
robot_power = int(input())
if robot_power <= max_height and robot_power > robot_height:
robot_height = robot_power
print(robot_he... | main_input = input()
robot_count = int(main_input.split(' ')[0])
max_height = int(main_input.split(' ')[1])
robot_height = 0
for specific_robot in range(robot_count):
robot_power = int(input())
if robot_power <= max_height and robot_power > robot_height:
robot_height = robot_power
print(robot_height) |
"""Changes associated with version Honeybee schema version 1.43.2."""
UPDATED_CONSTRUCTS = ('OpaqueConstructionAbridged', 'WindowConstructionAbridged')
def version_1_43_2(model_dict):
"""Implement changes in a Model dict to make it compatible with version 1.43.2."""
if 'energy' in model_dict['properties']:
... | """Changes associated with version Honeybee schema version 1.43.2."""
updated_constructs = ('OpaqueConstructionAbridged', 'WindowConstructionAbridged')
def version_1_43_2(model_dict):
"""Implement changes in a Model dict to make it compatible with version 1.43.2."""
if 'energy' in model_dict['properties']:
... |
class ___concatenate_HELPER_KeyGenerator___:
""""""
def __init__(self, vectors):
self.vectors = vectors
self._check_repeated_ = True
self._IS_CT_ = False
self._IS_NC_ = False
self._CT_ = '>CT<'
self._NC_ = '>NC<'
def __call__(self, i):
""""""
... | class ___Concatenate_Helper_Keygenerator___:
""""""
def __init__(self, vectors):
self.vectors = vectors
self._check_repeated_ = True
self._IS_CT_ = False
self._IS_NC_ = False
self._CT_ = '>CT<'
self._NC_ = '>NC<'
def __call__(self, i):
""""""
... |
'''
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
Example:
Input: ... | """
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
Example:
Input: ... |
def fontgen(ctx, output, input):
"""create a new XML font file from a source font"""
raise NotImplementedError
| def fontgen(ctx, output, input):
"""create a new XML font file from a source font"""
raise NotImplementedError |
Y,X,d = [int(x) for x in input().split()]
arr = []
for _ in range(Y):
xs = [int(x) for x in input().split()]
arr.extend(xs)
arr.sort()
hi = max(arr)
for i in range(Y*X):
arr[i] -= hi
if all(map(lambda x: x % d == 0, arr)):
total = 0
med = arr[(Y*X) // 2]
# print(med)
for x in arr:
... | (y, x, d) = [int(x) for x in input().split()]
arr = []
for _ in range(Y):
xs = [int(x) for x in input().split()]
arr.extend(xs)
arr.sort()
hi = max(arr)
for i in range(Y * X):
arr[i] -= hi
if all(map(lambda x: x % d == 0, arr)):
total = 0
med = arr[Y * X // 2]
for x in arr:
rem = abs(med... |
#
# PySNMP MIB module REDSTONE-PPP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/REDSTONE-PPP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:55:45 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')
(value_size_constraint, single_value_constraint, value_range_constraint, constraints_intersection, constraints_union) ... |
my_stuff = {'apple': "I am apples!"}
print(my_stuff['apple'])
def apple():
print("i am apples")
tangerine = "Living reflection of a dream"
print(apple())
class MyStuff(object):
def __init__(self, var1):
self.tangerine = "And now a thousand years between"
self.tiger = var1
def apple(s... | my_stuff = {'apple': 'I am apples!'}
print(my_stuff['apple'])
def apple():
print('i am apples')
tangerine = 'Living reflection of a dream'
print(apple())
class Mystuff(object):
def __init__(self, var1):
self.tangerine = 'And now a thousand years between'
self.tiger = var1
def apple(self)... |
# self explanatory
sample = r'This is a example of a sentence containing multiple words'
def spinWords(sentence):
wordList = sentence.split()
counter = 0
longWords = {}
for word in wordList:
if len(word) >= 5:
flip = word[::-1]
longWords[counter] = word
co... | sample = 'This is a example of a sentence containing multiple words'
def spin_words(sentence):
word_list = sentence.split()
counter = 0
long_words = {}
for word in wordList:
if len(word) >= 5:
flip = word[::-1]
longWords[counter] = word
counter += 1
e... |
{
"cells": [
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "5d377b45d1af4c17ab25e85b0cc47c0e",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
... | {'cells': [{'cell_type': 'code', 'execution_count': 11, 'metadata': {}, 'outputs': [{'data': {'application/vnd.jupyter.widget-view+json': {'model_id': '5d377b45d1af4c17ab25e85b0cc47c0e', 'version_major': 2, 'version_minor': 0}, 'text/plain': ["Label(value='REAL TIME TRANSPORT ')"]}, 'metadata': {}, 'output_type': 'disp... |
# ----------------------------------------------------------------------------
# Name: pln.py (Planning.py)
# Purpose: This module contains variables for the construction
# of a planning dataset. This module is to be used in
# conjunction with create-Base-DataSet/main.py.
#... | pln_gdb_name = 'Planning.gdb'
'\nThe following information outlines the variable structure for each feature\nin order to be used correctly within main.py.\n\nNOTE: The * used in the information below is to indicate a user defined\nname.\n\nFeature variable structure:\n\n # Layer Name --------------------------------... |
items = ['One', 'Two', 'Three', 'Four','Five']
for item in items:
if item == 'Two':
continue # Completely skip 'Two'
print(item) # One # Three # Four # Five
for item in items:
if item == 'Two' or item == 'Four':
continue # Completely skip 'Two'
print(item) # One ... | items = ['One', 'Two', 'Three', 'Four', 'Five']
for item in items:
if item == 'Two':
continue
print(item)
for item in items:
if item == 'Two' or item == 'Four':
continue
print(item)
for item in items:
if item == 'Three':
break
print(item)
num = 0
while num <= 10:
num ... |
__debug_flag__ = {'enabled': False}
def is_debug_enabled():
r"""Returns :obj:`True`, if the debug mode is enabled."""
return __debug_flag__['enabled']
def set_debug_enabled(mode):
__debug_flag__['enabled'] = mode
class debug:
r"""Context-manager that enables the debug mode to help track down error... | __debug_flag__ = {'enabled': False}
def is_debug_enabled():
"""Returns :obj:`True`, if the debug mode is enabled."""
return __debug_flag__['enabled']
def set_debug_enabled(mode):
__debug_flag__['enabled'] = mode
class Debug:
"""Context-manager that enables the debug mode to help track down errors
... |
# Check if a tag needs to be removed
def check_remove(s):
# print(s)
l = s.split()
for j in range(len(l)):
l[j] = nltk.word_tokenize(l[j])
[(a,b)] = nltk.pos_tag(l[j])
l[j] = b
# print(l)
adj = l.count('JJ') + l.count('JJR') + l.count('JJS')
adv = l.count('RB') + l.count('RBR') + l.count('RBS')... | def check_remove(s):
l = s.split()
for j in range(len(l)):
l[j] = nltk.word_tokenize(l[j])
[(a, b)] = nltk.pos_tag(l[j])
l[j] = b
adj = l.count('JJ') + l.count('JJR') + l.count('JJS')
adv = l.count('RB') + l.count('RBR') + l.count('RBS')
adjv = adj + adv
non = l.count('NN... |
# Copyright 2018-2019 Google LLC.
# SPDX-License-Identifier: Apache-2.0
# Please keep deps in alphabetical order
THIRD_PARTY_ARTIFACTS = [
"com.google.guava:guava:28.1-jre",
"com.google.truth:truth:1.0",
]
| third_party_artifacts = ['com.google.guava:guava:28.1-jre', 'com.google.truth:truth:1.0'] |
"""
Created on Wed Jul 28 10:03:48 2021
Python Implementation
NPTEL
Getting Started with Competitive Programming
Week 1
Mod 1
Reversort
https://www.craft.do/s/AcEMNb4NLdHlQo/b/66FE59A3-D17C-45C9-9C2A-A1C4C76A99E9/Module_1._Reversort
by
https://rajkumargalaxy.github.io/profile
Submission successful at https://coding... | """
Created on Wed Jul 28 10:03:48 2021
Python Implementation
NPTEL
Getting Started with Competitive Programming
Week 1
Mod 1
Reversort
https://www.craft.do/s/AcEMNb4NLdHlQo/b/66FE59A3-D17C-45C9-9C2A-A1C4C76A99E9/Module_1._Reversort
by
https://rajkumargalaxy.github.io/profile
Submission successful at https://coding... |
def simple():
"""
A docstring.
"""
pass
| def simple():
"""
A docstring.
"""
pass |
#!/usr/bin/env python3
m = []
i = 1
while len(m) < 10001:
i += 1
not_prime = 0
for j in range(2, i):
if i%j == 0:
not_prime = 1
break
if not_prime == 0:
m.append(i)
print(len(m))
print(m[-1]) | m = []
i = 1
while len(m) < 10001:
i += 1
not_prime = 0
for j in range(2, i):
if i % j == 0:
not_prime = 1
break
if not_prime == 0:
m.append(i)
print(len(m))
print(m[-1]) |
def bubblesort(list):
# Swap the elements to arrange in order
for iter_num in range(len(list) - 1, 0, -1):
for idx in range(iter_num):
if list[idx] > list[idx + 1]:
temp = list[idx]
list[idx] = list[idx + 1]
list[idx + 1] = temp
list = [19, ... | def bubblesort(list):
for iter_num in range(len(list) - 1, 0, -1):
for idx in range(iter_num):
if list[idx] > list[idx + 1]:
temp = list[idx]
list[idx] = list[idx + 1]
list[idx + 1] = temp
list = [19, 2, 31, 45, 6, 11, 121, 27]
bubblesort(list)
pri... |
class Graph:
class Node:
def __init__(self, n=''):
self.name = n
self.edges = list()
def to_string(self):
strepr = self.name
strepr += ' [ '
strepr += ', '.join([e.name for e in self.edges])
strepr += ' ] '
return ... | class Graph:
class Node:
def __init__(self, n=''):
self.name = n
self.edges = list()
def to_string(self):
strepr = self.name
strepr += ' [ '
strepr += ', '.join([e.name for e in self.edges])
strepr += ' ] '
return... |
with open('data/captions.csv', 'r', encoding='utf8') as f1, open('data/Flickr30k/captions.txt', 'w') as f2:
f2.write('image,caption')
line = f1.readline()
while True:
line = f1.readline()
if not line:
break
image, caption = line.strip().split('| ')[::2]
capti... | with open('data/captions.csv', 'r', encoding='utf8') as f1, open('data/Flickr30k/captions.txt', 'w') as f2:
f2.write('image,caption')
line = f1.readline()
while True:
line = f1.readline()
if not line:
break
(image, caption) = line.strip().split('| ')[::2]
caption ... |
'''
Add together any number of matrices and provide a positional sum matrix.
Written for Python Morsels Exercise/Assignment #1 "add"
Functions:
add(*matrices: list[list[int|float]]) -> list[list[int|float]
- Returns a matrix (list of lists) of given matrix values added positionally.
'''
def add(*... | """
Add together any number of matrices and provide a positional sum matrix.
Written for Python Morsels Exercise/Assignment #1 "add"
Functions:
add(*matrices: list[list[int|float]]) -> list[list[int|float]
- Returns a matrix (list of lists) of given matrix values added positionally.
"""
def add(*matrices: l... |
#096_Funcao_que_calcula_area.py
def area(l, c):
print("-" * 30)
print(f"{'Controle de terreno':^30}")
print("-" * 30)
A = l * c
print(f"{l}m x {c}m = {A}m2")
print("-" * 30)
x = int(input("Largura: "))
y = int(input("Comprimento: "))
area(x, y)
| def area(l, c):
print('-' * 30)
print(f"{'Controle de terreno':^30}")
print('-' * 30)
a = l * c
print(f'{l}m x {c}m = {A}m2')
print('-' * 30)
x = int(input('Largura: '))
y = int(input('Comprimento: '))
area(x, y) |
def map_efo(trait_2_efo_dict, name_list):
"""
Function accepts a dict with mappings from clinvar trait names to tuples containing ontology
ids and labels, and a list with clinvar trait names for one trait. Returns the clinvar trait
name (in lowercase) that is earliest in the list and has a mapping in th... | def map_efo(trait_2_efo_dict, name_list):
"""
Function accepts a dict with mappings from clinvar trait names to tuples containing ontology
ids and labels, and a list with clinvar trait names for one trait. Returns the clinvar trait
name (in lowercase) that is earliest in the list and has a mapping in th... |
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
combinations = []
def combination(ans, openP, closeP):
if closeP == n:
combinations.append(ans)
return
if openP >... | class Solution(object):
def generate_parenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
combinations = []
def combination(ans, openP, closeP):
if closeP == n:
combinations.append(ans)
return
if openP ... |
"""
PASSENGERS
"""
numPassengers = 4249
passenger_arriving = (
(2, 15, 5, 3, 2, 0, 9, 9, 8, 5, 1, 0), # 0
(4, 9, 10, 3, 3, 0, 12, 10, 7, 10, 3, 0), # 1
(2, 6, 7, 2, 2, 0, 3, 17, 5, 7, 3, 0), # 2
(6, 13, 7, 7, 4, 0, 7, 14, 5, 7, 2, 0), # 3
(5, 12, 9, 3, 3, 0, 12, 10, 9, 9, 3, 0), # 4
(4, 13, 14, 5, 0, 0, 4... | """
PASSENGERS
"""
num_passengers = 4249
passenger_arriving = ((2, 15, 5, 3, 2, 0, 9, 9, 8, 5, 1, 0), (4, 9, 10, 3, 3, 0, 12, 10, 7, 10, 3, 0), (2, 6, 7, 2, 2, 0, 3, 17, 5, 7, 3, 0), (6, 13, 7, 7, 4, 0, 7, 14, 5, 7, 2, 0), (5, 12, 9, 3, 3, 0, 12, 10, 9, 9, 3, 0), (4, 13, 14, 5, 0, 0, 4, 7, 7, 4, 0, 0), (9, 12, 8, 4, 2,... |
#!/usr/bin/env python
# Copyright Contributors to the Open Shading Language project.
# SPDX-License-Identifier: BSD-3-Clause
# https://github.com/AcademySoftwareFoundation/OpenShadingLanguage
# We will take the liberty of assuming point, vector, and normal all take
# the identical code path
# compassign u index u f... | command += testshade('-t 1 -g 64 64 -od uint8 -o Cout out_compassign_u_index_u_float.tif test_compassign_u_index_u_float')
command += testshade('-t 1 -g 64 64 -od uint8 -o Cout out_compassign_u_index_v_float.tif test_compassign_u_index_v_float')
command += testshade('-t 1 -g 64 64 --vary_pdxdy -od uint8 -o Cout out_com... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.