content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
matriz = []
valor = []
# ou matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for x in range(0, 3):
for y in range(0, 3):
valor.append(int(input(f'Digite um valor para [{x}, {y}]: ')))
matriz.append(valor[:])
valor.clear()
print('-='*30)
for x in range(0, 3):
for y in range(0, 3):
print(f'[{mat... | matriz = []
valor = []
for x in range(0, 3):
for y in range(0, 3):
valor.append(int(input(f'Digite um valor para [{x}, {y}]: ')))
matriz.append(valor[:])
valor.clear()
print('-=' * 30)
for x in range(0, 3):
for y in range(0, 3):
print(f'[{matriz[x][y]:^6}]', end='')
print() |
class GameExited(BaseException):
pass
class PlayerDied(BaseException):
pass
| class Gameexited(BaseException):
pass
class Playerdied(BaseException):
pass |
'''
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
'''
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
... | """
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
"""
class Listnode:
def __init__(self, x):
self.val = x
self.next = None
def print_self... |
in_file = open("watch-history.html", "r")
vids = 0
line = in_file.readline()
while line != "":
if "https://www.youtube.com/watch" in line:
break
line = in_file.readline()
in_file.close()
refs = line.split("href")
outstring = ""
for i in range(1, len(refs)):
link = refs[i][2:45]
outstring += link + "\n"
vids+... | in_file = open('watch-history.html', 'r')
vids = 0
line = in_file.readline()
while line != '':
if 'https://www.youtube.com/watch' in line:
break
line = in_file.readline()
in_file.close()
refs = line.split('href')
outstring = ''
for i in range(1, len(refs)):
link = refs[i][2:45]
outstring += link... |
#
# @lc app=leetcode.cn id=51 lang=python3
#
# [51] n-queens
#
None
# @lc code=end | None |
#! /usr/bin/env python3
# Copyright(c) 2019 Intel Corporation.
# License: MIT See LICENSE file in root directory.
# Get class color map for road segmentation #
classes_color_map = [
(150, 150, 150),
(58, 55, 169),
(211, 51, 17),
(157, 80, 44),
(23, 95, 189),
(210, 133, 34),
(76, 226, 202),... | classes_color_map = [(150, 150, 150), (58, 55, 169), (211, 51, 17), (157, 80, 44), (23, 95, 189), (210, 133, 34), (76, 226, 202), (101, 138, 127), (223, 91, 182), (80, 128, 113), (235, 155, 55), (44, 151, 243), (159, 80, 170), (239, 208, 44), (128, 50, 51), (82, 141, 193), (9, 107, 10), (223, 90, 142), (50, 248, 83), (... |
# 33. Search in Rotated Sorted Array solution improvised per
# https://leetcode.com/problems/search-in-rotated-sorted-array/discuss/14425/Concise-O(log-N)-Binary-search-solution
def binarysearch(array,target,pivotindex):
low=0
high=len(array)-1
result=-1
while low<=high:
mid=(low+high)//2
... | def binarysearch(array, target, pivotindex):
low = 0
high = len(array) - 1
result = -1
while low <= high:
mid = (low + high) // 2
realmid = (mid + pivotindex) % len(array)
if array[realmid] == target:
return realmid
elif array[realmid] > target:
hi... |
#Julian Conneely 23/03/18
#using len (list)
#print the first element of the list, if it contains even number of elements.
list = [1, 2, 3, 4]
if len(list) % 2 == 0:
print(list[0]) | list = [1, 2, 3, 4]
if len(list) % 2 == 0:
print(list[0]) |
class Transaction:
def __init__(self, first_name, last_name, username, email, address, address2, country, postal, payment_method, cc_name, cc_number, cc_expiration, cc_cvv, ):
self.__first_name = first_name
self.__last_name = last_name
self.__username = username
self.__email = email
... | class Transaction:
def __init__(self, first_name, last_name, username, email, address, address2, country, postal, payment_method, cc_name, cc_number, cc_expiration, cc_cvv):
self.__first_name = first_name
self.__last_name = last_name
self.__username = username
self.__email = email
... |
#
# PySNMP MIB module CISCO-TCP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-TCP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:57:36 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_size_constraint, constraints_intersection, single_value_constraint, value_range_constraint) ... |
# maybe worked with network_x
def get_maxx_maxy_non_pythonic(self, node_dict, nodes):
maxx = -999999
maxy = -999999
for node, i in enumerate(nodes):
# certainly a more pythonic way exists
x = node_dict[i][0]
if x > maxx:
maxx = x
y = node_dict[i][1]
if y >... | def get_maxx_maxy_non_pythonic(self, node_dict, nodes):
maxx = -999999
maxy = -999999
for (node, i) in enumerate(nodes):
x = node_dict[i][0]
if x > maxx:
maxx = x
y = node_dict[i][1]
if y > maxy:
maxy = y
return (maxx, maxy) |
x = [1, 2]
print (x)
print (x[0])
x[0] = 33
print (x)
my_list = [101, 20, 10, 50, 60]
for item in my_list:
print(item)
my_list = ["Spoon", "Fork", "Knife"]
for item in my_list:
print(item)
my_list.append ("Ladle")
for item in my_list:
print(item)
print (my_list[3])
# Copy of the array to sum
my_list ... | x = [1, 2]
print(x)
print(x[0])
x[0] = 33
print(x)
my_list = [101, 20, 10, 50, 60]
for item in my_list:
print(item)
my_list = ['Spoon', 'Fork', 'Knife']
for item in my_list:
print(item)
my_list.append('Ladle')
for item in my_list:
print(item)
print(my_list[3])
my_list = [5, 76, 8, 5, 3, 3, 56, 5, 23]
list_t... |
# Do not edit this file directly.
# It was auto-generated by: code/programs/reflexivity/reflexive_refresh
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def halley():
http_archive(
name="halley" ,
build_file="//bazel/deps/halley:build.BUILD" ,
sha256="f4ff28208cb144e... | load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
def halley():
http_archive(name='halley', build_file='//bazel/deps/halley:build.BUILD', sha256='f4ff28208cb144e60ac2233dfbcf495ea3c7627e9accb74804511191b31aff99', strip_prefix='halley-cd90859ed700b65bbab0f4473c7e2ce9ee4cd65f', urls=['https://gith... |
def solution(arr):
answer = [arr[0]]
for num in arr:
if answer[len(answer)-1] != num:
answer.append(num)
return answer | def solution(arr):
answer = [arr[0]]
for num in arr:
if answer[len(answer) - 1] != num:
answer.append(num)
return answer |
# Copyright (c) 2013, Jeff Terrace
# All rights reserved.
"""Module for connecting to and controlling the Logitech Harmony Link"""
| """Module for connecting to and controlling the Logitech Harmony Link""" |
'''
Provides the minimal behaviors for a Cell.
@author: Quinn Liu (quinnliu@vt.edu)
@author: Michael Cogswell (cogswell@vt.edu)
@version: July 22, 2013
'''
class Cell(object):
def __init__(self, isActive=None, wasActive=None):
self.isActive = False # biologically equivalent to
# generating 1 or more spikes
s... | """
Provides the minimal behaviors for a Cell.
@author: Quinn Liu (quinnliu@vt.edu)
@author: Michael Cogswell (cogswell@vt.edu)
@version: July 22, 2013
"""
class Cell(object):
def __init__(self, isActive=None, wasActive=None):
self.isActive = False
self.wasActive = False |
#!/usr/bin/env python
DESCRIPTION = "FNV1a hash (64-bit)"
TYPE = 'unsigned_long'
TEST_1 = 14074705352429455374
def hash(data):
val = 0xcbf29ce484222325
for c in data:
val = (0x100000001b3 * (c ^ val)) & 0xffffffffffffffff
return val
| description = 'FNV1a hash (64-bit)'
type = 'unsigned_long'
test_1 = 14074705352429455374
def hash(data):
val = 14695981039346656037
for c in data:
val = 1099511628211 * (c ^ val) & 18446744073709551615
return val |
def text_box(self, str):
box = TextMobject(str).scale(0.3)
box.add(SurroundingRectangle(box, stroke_color = DARK_GREY))
return box
| def text_box(self, str):
box = text_mobject(str).scale(0.3)
box.add(surrounding_rectangle(box, stroke_color=DARK_GREY))
return box |
class ManagerInterface(object):
def __init__(self):
self._state = {}
@property
def state(self):
return self._state
def _get_state_data(self, obj):
raise NotImplementedError
def subscribe(self, obj):
key, value = self._get_state_data(obj)
self._subscribe(key... | class Managerinterface(object):
def __init__(self):
self._state = {}
@property
def state(self):
return self._state
def _get_state_data(self, obj):
raise NotImplementedError
def subscribe(self, obj):
(key, value) = self._get_state_data(obj)
self._subscribe(... |
class Node(object):
def __init__(self, value):
self.val = value
self.left = None
self.right = None
def validateBST(node, min, max):
if not node:
return True
if node.val < min or node.val > max:
return False
return validateBST(node.left, min, node.val) and valida... | class Node(object):
def __init__(self, value):
self.val = value
self.left = None
self.right = None
def validate_bst(node, min, max):
if not node:
return True
if node.val < min or node.val > max:
return False
return validate_bst(node.left, min, node.val) and vali... |
"""
4. Task
Your provided code section should find a meaning of a word from a dictionary containing
key/value pairs of word: value.
line.
"""
input_word = input('Enter a word(Passed/Failed/Other) = ')
dictionary = {'Passed':'You have practiced at home.', 'Failed': 'You was not serious.',
'Other': 'Write your own meanin... | """
4. Task
Your provided code section should find a meaning of a word from a dictionary containing
key/value pairs of word: value.
line.
"""
input_word = input('Enter a word(Passed/Failed/Other) = ')
dictionary = {'Passed': 'You have practiced at home.', 'Failed': 'You was not serious.', 'Other': 'Write your own meani... |
name = 'Zed A. Shaw'
age = 35 # years
height = 74 # inches
weight = 180 # lbs
eyes = 'Blue'
teeth = 'White'
hair = 'Brown'
height_cm = 74 * 2.54 # height in centimeters
weight_kg = 180 * 0.45359237 # weight in kilograms
print(f"Let's talk about {name}.")
print(f"He's {height_cm} centimeters tall.")
p... | name = 'Zed A. Shaw'
age = 35
height = 74
weight = 180
eyes = 'Blue'
teeth = 'White'
hair = 'Brown'
height_cm = 74 * 2.54
weight_kg = 180 * 0.45359237
print(f"Let's talk about {name}.")
print(f"He's {height_cm} centimeters tall.")
print(f"He's {height} inches tall.")
print(f"He's {weight_kg} kilograms heavy.")
print(f"... |
class Stack:
def __init__(self):
self.stack = []
self.max_stack = []
def push(self, val):
self.stack.append(val)
if not self.max_stack or val > self.stack[self.max_stack[-1]]:
self.max_stack.append(len(self.stack) - 1)
def pop(self):
if not self.stack:
... | class Stack:
def __init__(self):
self.stack = []
self.max_stack = []
def push(self, val):
self.stack.append(val)
if not self.max_stack or val > self.stack[self.max_stack[-1]]:
self.max_stack.append(len(self.stack) - 1)
def pop(self):
if not self.stack:
... |
key_dict = {"k_kp_minus": 269,
"k_2": 50,
"k_pageup": 280,
"k_capslock": 301,
"k_rmeta": 309,
"k_hash": 35,
"k_space": 32,
"k_caret": 94,
"k_end": 279,
"k_leftbracket": 91,
"k_euro": 321,
"k_6": 54,
"k_semicolon": 59,
"k_9": 57,
"k_pagedown": 281,
... | key_dict = {'k_kp_minus': 269, 'k_2': 50, 'k_pageup': 280, 'k_capslock': 301, 'k_rmeta': 309, 'k_hash': 35, 'k_space': 32, 'k_caret': 94, 'k_end': 279, 'k_leftbracket': 91, 'k_euro': 321, 'k_6': 54, 'k_semicolon': 59, 'k_9': 57, 'k_pagedown': 281, 'k_lmeta': 310, 'k_print': 316, 'k_help': 315, 'k_3': 51, 'k_left': 276,... |
# https://leetcode.com/problems/valid-parentheses/
class Solution:
def isValid(self, s: str) -> bool:
# This question will be solved using a stack.
# The idea is: a valid push to the stack consists of a left paren (of any type).
# We will process the string one e... | class Solution:
def is_valid(self, s: str) -> bool:
stack = []
mirror = {'(': ')', '{': '}', '[': ']', ')': '(', '}': '{', ']': '['}
for i in s:
if i == '(' or i == '{' or i == '[':
stack.append(i)
elif i == ')' or '}' or ']':
if stack... |
_base_ = "./FlowNet512_1.5AugCosyAAEGray_AdamW_ClipGrad_AvgMaxMin_Pbr_01_ape.py"
OUTPUT_DIR = "output/deepim/lmPbrSO/FlowNet512_1.5AugCosyAAEGray_AdamW_ClipGrad_AvgMaxMin_lmPbr_SO/lamp"
DATASETS = dict(TRAIN=("lm_pbr_lamp_train",), TEST=("lm_real_lamp_test",))
# rl3
# objects lamp Avg(1)
# ad_2 0.96 0.96
# ad... | _base_ = './FlowNet512_1.5AugCosyAAEGray_AdamW_ClipGrad_AvgMaxMin_Pbr_01_ape.py'
output_dir = 'output/deepim/lmPbrSO/FlowNet512_1.5AugCosyAAEGray_AdamW_ClipGrad_AvgMaxMin_lmPbr_SO/lamp'
datasets = dict(TRAIN=('lm_pbr_lamp_train',), TEST=('lm_real_lamp_test',)) |
str_1 = "HelloWorld"
str_2 = "Hello World"
str_3 = "one\ntwo\rthree\r\nfour\vfive\x0bsix\fseven\x0ceight\x1cnine\x1dten\x1eeleven\x85twelve\u2028thirteen\u2029"
print("str_1 : ")
print(str_1.splitlines())
print(str_1.splitlines(keepends = True))
print("str_2 : ")
print(str_2.splitlines())
print(str_2.splitlines(kee... | str_1 = 'HelloWorld'
str_2 = 'Hello World'
str_3 = 'one\ntwo\rthree\r\nfour\x0bfive\x0bsix\x0cseven\x0ceight\x1cnine\x1dten\x1eeleven\x85twelve\u2028thirteen\u2029'
print('str_1 : ')
print(str_1.splitlines())
print(str_1.splitlines(keepends=True))
print('str_2 : ')
print(str_2.splitlines())
print(str_2.splitlines(keepe... |
def isPrime(numb):
dil = 2
while dil * dil <= numb and numb % dil != 0:
dil += 1
return dil * dil > numb
def generator(number):
res, first, second = [2], 2, 1
while len(res) < number:
# first, second = second, first + second
LucasNumber = first + second
first = secon... | def is_prime(numb):
dil = 2
while dil * dil <= numb and numb % dil != 0:
dil += 1
return dil * dil > numb
def generator(number):
(res, first, second) = ([2], 2, 1)
while len(res) < number:
lucas_number = first + second
first = second
second = LucasNumber
if i... |
pkgname = "firmware-ipw2200"
pkgver = "3.1"
pkgrel = 0
pkgdesc = "Firmware for the Intel PRO/Wireless 2200BG wifi cards"
maintainer = "q66 <q66@chimera-linux.org>"
license = "custom:ipw2200"
url = "http://ipw2200.sourceforge.net"
source = f"http://firmware.openbsd.org/firmware-dist/ipw2200-fw-{pkgver}.tgz"
sha256 = "c6... | pkgname = 'firmware-ipw2200'
pkgver = '3.1'
pkgrel = 0
pkgdesc = 'Firmware for the Intel PRO/Wireless 2200BG wifi cards'
maintainer = 'q66 <q66@chimera-linux.org>'
license = 'custom:ipw2200'
url = 'http://ipw2200.sourceforge.net'
source = f'http://firmware.openbsd.org/firmware-dist/ipw2200-fw-{pkgver}.tgz'
sha256 = 'c6... |
def search(ordered_list, term):
ordered_list_size = len(ordered_list)
for i in range(ordered_list_size):
if term == ordered_list[i]:
return i
elif ordered_list[i] > term:
return None
return None
scores = [2, 3, 4, 6, 7]
search_term = 5
position = search(scores, ... | def search(ordered_list, term):
ordered_list_size = len(ordered_list)
for i in range(ordered_list_size):
if term == ordered_list[i]:
return i
elif ordered_list[i] > term:
return None
return None
scores = [2, 3, 4, 6, 7]
search_term = 5
position = search(scores, search... |
"""
Represents a TicTacToe Board
"""
def _pretty_print_item(item):
if item is not None:
return item
return "-"
class Board:
"""
A TicTacToe Board
"""
def __init__(self, win_condition, valid_move, max_moves: int, width: int, height: int, depth: int = 1):
self.width = width
... | """
Represents a TicTacToe Board
"""
def _pretty_print_item(item):
if item is not None:
return item
return '-'
class Board:
"""
A TicTacToe Board
"""
def __init__(self, win_condition, valid_move, max_moves: int, width: int, height: int, depth: int=1):
self.width = width
... |
# In hr.py
class PayrollSystem:
def calculate_payroll(self, employees):
print('Calculating Payroll')
print('===================')
for employee in employees:
print(f'Payroll for: {employee.id} - {employee.name}')
print(f'- Check amount: {employee.calculate_payroll()}'... | class Payrollsystem:
def calculate_payroll(self, employees):
print('Calculating Payroll')
print('===================')
for employee in employees:
print(f'Payroll for: {employee.id} - {employee.name}')
print(f'- Check amount: {employee.calculate_payroll()}')
... |
#
# PySNMP MIB module PPP-IP-NCP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PPP-IP-NCP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:32:57 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_union, single_value_constraint, value_range_constraint, constraints_intersection) ... |
# Color palettes
palettes = {}
palettes['palette_0'] = ["rgba(134, 149, 184, 0.5)", "rgba(184, 179, 134, 0.5)",
"rgba(184, 134, 134, 0.5)", "rgba(134, 184, 132, 0.5)",
"rgba(140, 134, 184, 0.5)", "rgba(184, 134, 176, 0.5)"]
palettes['Tableau10'] = ["#4e79a7", "#f28e2... | palettes = {}
palettes['palette_0'] = ['rgba(134, 149, 184, 0.5)', 'rgba(184, 179, 134, 0.5)', 'rgba(184, 134, 134, 0.5)', 'rgba(134, 184, 132, 0.5)', 'rgba(140, 134, 184, 0.5)', 'rgba(184, 134, 176, 0.5)']
palettes['Tableau10'] = ['#4e79a7', '#f28e2c', '#e15759', '#76b7b2', '#59a14f', '#edc949', '#af7aa1', '#ff9da7', ... |
class stack:
def __init__(self):
self.stack = []
def push(self, obj):
self.stack.append(obj)
def pull(self):
if len(self.stack) > 0:
return self.stack.pop()
return None
def top(self):
if len(self.stack) > 0:
return self.stack[-1]
... | class Stack:
def __init__(self):
self.stack = []
def push(self, obj):
self.stack.append(obj)
def pull(self):
if len(self.stack) > 0:
return self.stack.pop()
return None
def top(self):
if len(self.stack) > 0:
return self.stack[-1]
... |
""" Lowest Common Ancestor in Binary Tree
"""
class Node:
""" Node contains actual data and address to left and right node """
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def lowest_common_ancestor(root, a, b):
""" lowest common ancestor in BST "... | """ Lowest Common Ancestor in Binary Tree
"""
class Node:
""" Node contains actual data and address to left and right node """
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def lowest_common_ancestor(root, a, b):
""" lowest common ancestor in BST ""... |
def pop_row(df, limit):
_filter = df['hour']!=limit
df = df[_filter]
return df.reset_index(drop=True)
def get_by_hour(df, hour):
tmp = df['hour']==hour
return df[tmp]
| def pop_row(df, limit):
_filter = df['hour'] != limit
df = df[_filter]
return df.reset_index(drop=True)
def get_by_hour(df, hour):
tmp = df['hour'] == hour
return df[tmp] |
class HEX2HSL:
def __init__(self,RGB):
self.RGB = RGB
self.R = int((self.RGB[1:3]),16)
self.G = int((self.RGB[3:5]),16)
self.B = int((self.RGB[5:7]),16)
self.H = 0;
self.S = 0;
self.L = 0;
R = (self.R/255)
G = (self.G/255)
B = (self.B/... | class Hex2Hsl:
def __init__(self, RGB):
self.RGB = RGB
self.R = int(self.RGB[1:3], 16)
self.G = int(self.RGB[3:5], 16)
self.B = int(self.RGB[5:7], 16)
self.H = 0
self.S = 0
self.L = 0
r = self.R / 255
g = self.G / 255
b = self.B / 255
... |
class SparkConf:
vals: dict = {}
def set(self, key: str, val: str):
self.vals[key] = val
def get(self, key: str):
if key not in self.vals:
raise Exception(f"Conf value not found for {key}")
return self.vals[key]
class SparkSessionMock:
def __init__(self):
... | class Sparkconf:
vals: dict = {}
def set(self, key: str, val: str):
self.vals[key] = val
def get(self, key: str):
if key not in self.vals:
raise exception(f'Conf value not found for {key}')
return self.vals[key]
class Sparksessionmock:
def __init__(self):
... |
print ("This is Han")
print ("This is Bin")
for x in range(10):
print (x)
print (x)
| print('This is Han')
print('This is Bin')
for x in range(10):
print(x)
print(x) |
x=int(input("enter an integer:"))
y=float(input("enter an fload number:"))
z=input("enter another number:")
def main(x,y,z):
if x>y and x>z:
print ("bigest number: ",x)
elif y>x and y>z:
print ("bigest: ", y)
elif z>x and z>y:
print ("bigest: ",z)
else:
p... | x = int(input('enter an integer:'))
y = float(input('enter an fload number:'))
z = input('enter another number:')
def main(x, y, z):
if x > y and x > z:
print('bigest number: ', x)
elif y > x and y > z:
print('bigest: ', y)
elif z > x and z > y:
print('bigest: ', z)
else:
... |
def aumentar(valor, taxa):
return valor + (valor * (taxa/100))
def diminuir(valor, taxa):
return valor - (valor * (taxa / 100))
def dobro(valor):
return valor * 2
def metade(valor):
return valor / 2 | def aumentar(valor, taxa):
return valor + valor * (taxa / 100)
def diminuir(valor, taxa):
return valor - valor * (taxa / 100)
def dobro(valor):
return valor * 2
def metade(valor):
return valor / 2 |
class TaxonomyTreeNode:
def __init__(self, taxId, parent, name, rank):
self.taxId = taxId
self.name = name
self.rank = rank
self.parent = parent
self.children = []
def addChild(self, child):
self.children.append(child)
def setChildren(self, children):
... | class Taxonomytreenode:
def __init__(self, taxId, parent, name, rank):
self.taxId = taxId
self.name = name
self.rank = rank
self.parent = parent
self.children = []
def add_child(self, child):
self.children.append(child)
def set_children(self, children):
... |
# Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd
# number of characters then it should replace the missing second character of the final pair with an underscore ('_').
#
# Examples:
#
# solution('abc') # should return ['ab', 'c_']
# solution('abcdef') # sh... | def solution(s):
output_list = []
temp_str = ''
counter = 0
for x in s:
if counter < 2:
temp_str = temp_str + x
counter += 1
if counter == 2:
counter = 0
output_list.append(temp_str)
temp_str = ''
if temp_str != '':
... |
'''
This is the main entry point for the clubadmin package as a whole and provides
the launching pad for the sub-packages that may be installed.
'''
| """
This is the main entry point for the clubadmin package as a whole and provides
the launching pad for the sub-packages that may be installed.
""" |
"""contains custom scrapy pipelines."""
class TypePipeline(object):
"""This class renames _type field."""
def process_item(self, item, spider):
"""implements https://doc.scrapy.org/en/latest/topics/item-pipeline.html#process_item"""
if item['_type']:
item['schema'] = item.pop('_t... | """contains custom scrapy pipelines."""
class Typepipeline(object):
"""This class renames _type field."""
def process_item(self, item, spider):
"""implements https://doc.scrapy.org/en/latest/topics/item-pipeline.html#process_item"""
if item['_type']:
item['schema'] = item.pop('_typ... |
def test_locals():
d1 = locals()
d2 = locals()
assert d1 is d2 | def test_locals():
d1 = locals()
d2 = locals()
assert d1 is d2 |
"""
Day 4: Binomial Distribution II
A manufacturer of metal pistons finds that, on average 12% of the pistons they
manufacture are rejected because they are incorrectly sized. What is the probability
that a batch of 10 pistons will contain:
1. no more than 2 rejects?
2. At least 2 rejects?
b(x,n,p) = (n p)... | """
Day 4: Binomial Distribution II
A manufacturer of metal pistons finds that, on average 12% of the pistons they
manufacture are rejected because they are incorrectly sized. What is the probability
that a batch of 10 pistons will contain:
1. no more than 2 rejects?
2. At least 2 rejects?
b(x,n,p) = (n p).p^x . q^(... |
def eq(a, b):
return a == b
def le(a, b):
return a <= b
def lt(a, b):
return a < b
def ge(a, b):
return a >= b
def gt(a, b):
return a > b
def itemgetter(*items):
if len(items) == 1:
item = items[0]
def g(obj):
return obj[item]
else:
def g(obj):
return tuple(obj[item] for ... | def eq(a, b):
return a == b
def le(a, b):
return a <= b
def lt(a, b):
return a < b
def ge(a, b):
return a >= b
def gt(a, b):
return a > b
def itemgetter(*items):
if len(items) == 1:
item = items[0]
def g(obj):
return obj[item]
else:
def g(obj):
... |
#
# PySNMP MIB module ZYXEL-MAC-AUTHENTICATION-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-MAC-AUTHENTICATION-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:50:44 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python vers... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, value_range_constraint, value_size_constraint, constraints_intersection) ... |
def one_moov(right, left, up):
if up == None:
pass
else:
return up
if right == None:
pass
else:
return right
if left == None:
pass
else:
return left
def get_nb_moov(right, left, up):
nb_moov = 3
if right == None:
nb_moov -= 1
if left == None:
nb_moov -= 1
if up == None... | def one_moov(right, left, up):
if up == None:
pass
else:
return up
if right == None:
pass
else:
return right
if left == None:
pass
else:
return left
def get_nb_moov(right, left, up):
nb_moov = 3
if right == None:
nb_moov -= 1
i... |
N = int(input())
li = list(map(int, input().split()))
# N = 6
# li = [5, 2, 4, 6, 1, 3]
for i in range(1, N):
print(*li)
v = li[i]
for j in reversed(range(0, i)):
if li[j] > v:
li[j + 1] = li[j]
li[j] = v
else:
break
print(*li)
| n = int(input())
li = list(map(int, input().split()))
for i in range(1, N):
print(*li)
v = li[i]
for j in reversed(range(0, i)):
if li[j] > v:
li[j + 1] = li[j]
li[j] = v
else:
break
print(*li) |
def readable_timedelta(days):
# insert your docstring here
"""Returns a string of the number of week(s) and day(s) in the given days.
Args:
days (int): number of days to convert
"""
weeks = days // 7
remainder = days % 7
return "{} week(s) and {} day(s)".format(weeks, remainder)
| def readable_timedelta(days):
"""Returns a string of the number of week(s) and day(s) in the given days.
Args:
days (int): number of days to convert
"""
weeks = days // 7
remainder = days % 7
return '{} week(s) and {} day(s)'.format(weeks, remainder) |
data = { "nouns" :
#['nouns'][0]
{"example" :
#['nouns'][0][0]
["plural form",
#['nouns'][0][1]
["tags"],
#['nouns'][0][2]
["synonyms"],
#['nouns'][0][3]
"usage ranking"],
"cat" :
["ca... | data = {'nouns': {'example': ['plural form', ['tags'], ['synonyms'], 'usage ranking'], 'cat': ['cats', ['pet', 'animal', 'feline', 'meow', 'paws', 'fur'][0], 5]}, 'verbs': {'example': ['is irregular', ['ed equivalent', 'ing equivalent'], 'is participle', ['tags'], ['synonyms'], 'usage ranking'], 'walk': [False, ['walke... |
def balance():
i01.setHeadSpeed(0.95,0.95)
i01.setArmSpeed("left",1.0,0.85,0.95,0.95)
i01.setArmSpeed("right",0.65,0.85,0.65,0.85)
i01.setHandSpeed("left",0.85,0.85,0.85,0.85,0.85,0.85)
i01.setHandSpeed("right",0.85,0.85,0.85,0.85,0.85,0.85)
i01.setTorsoSpeed(0.95,0.85,1.0)
i01.moveHead(79,1... | def balance():
i01.setHeadSpeed(0.95, 0.95)
i01.setArmSpeed('left', 1.0, 0.85, 0.95, 0.95)
i01.setArmSpeed('right', 0.65, 0.85, 0.65, 0.85)
i01.setHandSpeed('left', 0.85, 0.85, 0.85, 0.85, 0.85, 0.85)
i01.setHandSpeed('right', 0.85, 0.85, 0.85, 0.85, 0.85, 0.85)
i01.setTorsoSpeed(0.95, 0.85, 1.0... |
"""Day 1 Part Two.
Now, given the same instructions, find the position of the first character that
causes him to enter the basement (floor -1). The first character in the
instructions has position 1, the second character has position 2, and so on.
For example:
) causes him to enter the basement at character posi... | """Day 1 Part Two.
Now, given the same instructions, find the position of the first character that
causes him to enter the basement (floor -1). The first character in the
instructions has position 1, the second character has position 2, and so on.
For example:
) causes him to enter the basement at character posi... |
def openfile_returnlist(csvfilename):
with open(csvfilename) as f:
x=[]
for line in f:
# last character is a \n
x.append(line[:-1].split("\t"))
return x
if __name__ == "__main__":
mylist = openfile_returnlist("data/brands_filtered.txt")
print(mylist[0:2])
| def openfile_returnlist(csvfilename):
with open(csvfilename) as f:
x = []
for line in f:
x.append(line[:-1].split('\t'))
return x
if __name__ == '__main__':
mylist = openfile_returnlist('data/brands_filtered.txt')
print(mylist[0:2]) |
sigfox_hexa = 0x21134464D0A00500C01C8C01
lenght = 96
bin_host, bin_network = '', ''
def bin_format(sigfox_hexa, lenght):
return f'{sigfox_hexa:0>{lenght}b}'
# def bin_protocol('sigfox_bin'):
# for i in range(96):
# if i <= 3:
# bin_host = bin_host + sigfox_bin[i]
# elif i <= 7:
# ... | sigfox_hexa = 10236297895305328786010835969
lenght = 96
(bin_host, bin_network) = ('', '')
def bin_format(sigfox_hexa, lenght):
return f'{sigfox_hexa:0>{lenght}b}'
if __name__ == '__main__':
sigfox_bin = bin_format(sigfox_hexa, lenght)
bin_host = sigfox_bin[0:4]
bin_network = sigfox_bin[4:8]
bin_en... |
def main():
X = int(input())
if X<40:
print(40-X)
elif X<70:
print(70-X)
elif X<90:
print(90-X)
else:
print("expert")
if __name__ == '__main__':
main()
| def main():
x = int(input())
if X < 40:
print(40 - X)
elif X < 70:
print(70 - X)
elif X < 90:
print(90 - X)
else:
print('expert')
if __name__ == '__main__':
main() |
# solution to a kata on codewars
# https://www.codewars.com/kata/exes-and-ohs/python
# idea is to determine whether there is an
# equal number of "x" and "o" in a string
# (count the total of both upper and lower case)
def xo(s):
return s.lower().count('x') == s.lower().count('o')
| def xo(s):
return s.lower().count('x') == s.lower().count('o') |
student_grades = {
'Joe': [90, 95, 87, 99],
'Sally': [97, 92, 90, 100],
'Mark': [80, 83, 72, 89]
}
student_grades_avg = {}
def calc_avg(scores):
avg = sum(scores) / len(scores)
return avg
for student, scores in student_grades.items():
student_grades_avg[student] = calc_avg(scores)
prin... | student_grades = {'Joe': [90, 95, 87, 99], 'Sally': [97, 92, 90, 100], 'Mark': [80, 83, 72, 89]}
student_grades_avg = {}
def calc_avg(scores):
avg = sum(scores) / len(scores)
return avg
for (student, scores) in student_grades.items():
student_grades_avg[student] = calc_avg(scores)
print(student_grades_avg) |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def convertBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
# Input:... | class Solution(object):
def convert_bst(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
self.sum = 0
def dfs(root):
if not root:
return
dfs(root.right)
root.val += self.sum
self.sum = root.va... |
class Position:
def __init__(self, x, y):
self.x = int(x)
self.y = int(y)
def move(self, x, y):
self.x += x
self.y += y
def __str__(self):
return "X: " + str(self.x) + ", Y: " + str(self.y)
def count_trees_for_movement_pattern(field, step_x, step_y):
... | class Position:
def __init__(self, x, y):
self.x = int(x)
self.y = int(y)
def move(self, x, y):
self.x += x
self.y += y
def __str__(self):
return 'X: ' + str(self.x) + ', Y: ' + str(self.y)
def count_trees_for_movement_pattern(field, step_x, step_y):
base_leng... |
'''
We can also store a number of objects inside a list or a dictionary.
The below example, we have a list of mobile objects and we are iterating over the list and printing the values
'''
class Mobile:
def __init__(self, brand, price):
self.brand = brand
self.price = price
mob1=Mobile("Apple", 10... | """
We can also store a number of objects inside a list or a dictionary.
The below example, we have a list of mobile objects and we are iterating over the list and printing the values
"""
class Mobile:
def __init__(self, brand, price):
self.brand = brand
self.price = price
mob1 = mobile('Apple', ... |
# Copyright (C) 2018 DataArt
#
# 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, ... | class Notification(object):
device_id_key = 'deviceId'
id_key = 'id'
notification_key = 'notification'
parameters_key = 'parameters'
timestamp_key = 'timestamp'
def __init__(self, notification):
self._raw_data = notification
self._device_id = notification[self.DEVICE_ID_KEY]
... |
def Miladi_to_Shamsi(y, m, d):
g_d_m = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
if (m > 2):
y2 = y + 1
else:
y2 = y
days = 355666 + (365 * y) + ((y2 + 3) // 4) - ((y2 + 99) //
100) + ((y2 + 399) // 400) + d + g_d_m[m - 1... | def miladi_to__shamsi(y, m, d):
g_d_m = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
if m > 2:
y2 = y + 1
else:
y2 = y
days = 355666 + 365 * y + (y2 + 3) // 4 - (y2 + 99) // 100 + (y2 + 399) // 400 + d + g_d_m[m - 1]
jalali_year = -1595 + 33 * (days // 12053)
days %= 1... |
X = int(input())
if X%2 == 0: X += 1
for k in range(X,X+12,2):
print(k)
| x = int(input())
if X % 2 == 0:
x += 1
for k in range(X, X + 12, 2):
print(k) |
# Time: O(n)
# Space: O(1)
class Solution(object):
def minSwaps(self, s):
"""
:type s: str
:rtype: int
"""
def cost(s, x):
diff = 0
for c in s:
diff += int(c) != x
x ^= 1
return diff//2
ones ... | class Solution(object):
def min_swaps(self, s):
"""
:type s: str
:rtype: int
"""
def cost(s, x):
diff = 0
for c in s:
diff += int(c) != x
x ^= 1
return diff // 2
ones = s.count('1')
zeros = ... |
def tag(name, *content, cls=None, **attrs):
"""Generate one or more HTML tags, from Fluent Python, page 155"""
if cls is not None:
attrs['class'] = cls
if attrs:
attr_str = ''.join(f' {attr}="{value}"'
for attr, value
in sorted(attrs.item... | def tag(name, *content, cls=None, **attrs):
"""Generate one or more HTML tags, from Fluent Python, page 155"""
if cls is not None:
attrs['class'] = cls
if attrs:
attr_str = ''.join((f' {attr}="{value}"' for (attr, value) in sorted(attrs.items())))
else:
attr_str = ''
if conte... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
ret =... | class Solution(object):
def add_two_numbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
ret = None
c = 0
while True:
if l1 is not None and l2 is not None:
(c, s) = divmod(l1.val + l2.val + ... |
# Rename settings_sample.py to settings.py
# Generate jss_credentials with:
# printf "username:password" | iconv -t ISO-8859-1 | base64 -i -
jss_server = "YOUR_JAMF_PRO_URL"
jss_credential = "YOUR_CREDENTIALS"
attributes = {
"extension_attributes": [
{
"id": 32, # Extenss... | jss_server = 'YOUR_JAMF_PRO_URL'
jss_credential = 'YOUR_CREDENTIALS'
attributes = {'extension_attributes': [{'id': 32, 'name': 'shared_computer'}, {'id': 11, 'name': 'Whetever...'}]} |
class Person:
def __init__(self):
self.fname = 'Alex'
self.lname = 'Prodan'
self.age = 25
def __repr__(self):
return f'Person(fname={self.fname}, lname={self.lname}, age={self.age})'
def __str__(self):
return f'{self.fname} {self.lname} {self.age}'
def __byte... | class Person:
def __init__(self):
self.fname = 'Alex'
self.lname = 'Prodan'
self.age = 25
def __repr__(self):
return f'Person(fname={self.fname}, lname={self.lname}, age={self.age})'
def __str__(self):
return f'{self.fname} {self.lname} {self.age}'
def __bytes... |
test = {
'name': 'lab1_p2a',
'suites': [
{
'cases': [
{
'code': r"""
>>> # It looks like your variable is not named correctly.
>>> # Remember, we want a boolian variable that starts with somenum_
>>> 'somenum_bool' in vars()
True
"""
... | test = {'name': 'lab1_p2a', 'suites': [{'cases': [{'code': "\n >>> # It looks like your variable is not named correctly.\n >>> # Remember, we want a boolian variable that starts with somenum_\n >>> 'somenum_bool' in vars()\n True\n "}, {'code': '\n >>> # The variabl... |
# Task 1
class StatePool:
def __init__(self):
self.__states = {}
def get_instance(self, cls):
if cls not in self.__states:
self.__states[cls] = cls()
return self.__states[cls]
# Task 2
class HeroState:
__state_pool = StatePool()
@classmethod
def get_instance... | class Statepool:
def __init__(self):
self.__states = {}
def get_instance(self, cls):
if cls not in self.__states:
self.__states[cls] = cls()
return self.__states[cls]
class Herostate:
__state_pool = state_pool()
@classmethod
def get_instance(cls):
retu... |
for _ in range(int(input())):
a=input()
r=input()
for i in a:
if ord('A') <= ord(i) <= ord('Z'):
print(r[ord(i)-ord('A')],end="")
else:
print(i,end="")
print() | for _ in range(int(input())):
a = input()
r = input()
for i in a:
if ord('A') <= ord(i) <= ord('Z'):
print(r[ord(i) - ord('A')], end='')
else:
print(i, end='')
print() |
"""Dummy class that does not have MotionDetection class."""
class motiondetection:
"""Dummy class that does not have MotionDetection class."""
pass
| """Dummy class that does not have MotionDetection class."""
class Motiondetection:
"""Dummy class that does not have MotionDetection class."""
pass |
#
# PySNMP MIB module CISCO-VOICE-DIAL-CONTROL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VOICE-DIAL-CONTROL-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:03:03 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python vers... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, single_value_constraint, value_size_constraint, value_range_constraint) ... |
"""
entradas
venta1->float->v1
venta2->float->v2
venta3->float->v3
sueldobase->float->SB
salidas
comision->float->c
sueldototal->float->sueldototal
"""
#entradas
v1=float(input("digite la venta 1 " ))
v2=float(input("digite la venta 2 " ))
v3=float(input("digite la venta 3 " ))
sueldobase=float(input("digite el sueldo... | """
entradas
venta1->float->v1
venta2->float->v2
venta3->float->v3
sueldobase->float->SB
salidas
comision->float->c
sueldototal->float->sueldototal
"""
v1 = float(input('digite la venta 1 '))
v2 = float(input('digite la venta 2 '))
v3 = float(input('digite la venta 3 '))
sueldobase = float(input('digite el sueldo base... |
#
# PySNMP MIB module SIAE-RABR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file://./sm_rabr.mib
# Produced by pysmi-0.3.2 at Fri Jul 19 08:41:38 2019
# On host 0e190c6811ee platform Linux version 4.9.125-linuxkit by user root
# Using Python version 3.7.3 (default, Apr 3 2019, 05:39:12)
#
OctetString, ObjectIdenti... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_intersection, value_range_constraint, value_size_constraint, constraints_union) ... |
url = "bytebank.com/cambio?quantidade=100&moedaOrigem=real&moedaDestino=dolar"
indice_interrogacao = url.find('?')
url_base = url[:indice_interrogacao]
url_parametros = url[indice_interrogacao+1:]
parametro_busca = 'quantidade'
indice_parametro = url_parametros.find(parametro_busca)
indice_valor = indice_parametro + ... | url = 'bytebank.com/cambio?quantidade=100&moedaOrigem=real&moedaDestino=dolar'
indice_interrogacao = url.find('?')
url_base = url[:indice_interrogacao]
url_parametros = url[indice_interrogacao + 1:]
parametro_busca = 'quantidade'
indice_parametro = url_parametros.find(parametro_busca)
indice_valor = indice_parametro + ... |
# # 1
# # 1 2
# # 1 2 3
n = int(input("Enter value of n:"))
for i in range(0, n):
for j in range(0, i+1):
print(j+1, end=" ")
print()
# # 1
# # 2 2
# # 3 3 3
n = int(input("Enter value of n:"))
for i in range(1, n+1):
print((str(i)+' ')*i)
# # WAP print prime numbers fromm 2 to 50.
c = 0
for i i... | n = int(input('Enter value of n:'))
for i in range(0, n):
for j in range(0, i + 1):
print(j + 1, end=' ')
print()
n = int(input('Enter value of n:'))
for i in range(1, n + 1):
print((str(i) + ' ') * i)
c = 0
for i in range(2, 51):
c = 2
for j in range(2, i):
if i % j == 0 and c < 3:
... |
# Copyright (c) 2018, Lehrstuhl fuer Angewandte Mechanik, Technische
# Universitaet Muenchen.
#
# Distributed under BSD-3-Clause License. See LICENSE-File for more information
#
"""
Module contains eigensolvers
"""
| """
Module contains eigensolvers
""" |
# see https://www.codewars.com/kata/5a262cfb8f27f217f700000b/solutions/python
def solve(a,b):
r1 = "".join(x for x in a if x not in b)
r2 = "".join(x for x in b if x not in a)
return r1+r2
print(solve("xyab","xzca") == "ybzc")
print(solve("xyabb","xzca") == "ybbzc")
print(solve("abcd","xyz") == "abcdxyz")... | def solve(a, b):
r1 = ''.join((x for x in a if x not in b))
r2 = ''.join((x for x in b if x not in a))
return r1 + r2
print(solve('xyab', 'xzca') == 'ybzc')
print(solve('xyabb', 'xzca') == 'ybbzc')
print(solve('abcd', 'xyz') == 'abcdxyz')
print(solve('xxx', 'xzca') == 'zca') |
def maximo(x, y, z):
if x > y and x > z:
return x
if y > x and y > z:
return y
else:
return z | def maximo(x, y, z):
if x > y and x > z:
return x
if y > x and y > z:
return y
else:
return z |
#!/usr/bin/env python3
toomer_bio = """
Nathan Pinchback Tomer, who adopted the name Jean Tomer early
in his literary career, was born in Washington, D.C. in 1894.
Jean is the son of Nathan Tomer was a mixed-race freedman,
born into slavery in 1839 in Chatham County, North Carolina.
Jean Tomer is most well known for ... | toomer_bio = '\nNathan Pinchback Tomer, who adopted the name Jean Tomer early\nin his literary career, was born in Washington, D.C. in 1894.\nJean is the son of Nathan Tomer was a mixed-race freedman,\nborn into slavery in 1839 in Chatham County, North Carolina.\nJean Tomer is most well known for his first book Cane,\n... |
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print("Encountered a start tag:", tag)
def handle_endtag(self, tag):
print("Encountered an end tag :", tag)
def handle_data(self, data):
print("Encountered some data :", data)
| class Myhtmlparser(HTMLParser):
def handle_starttag(self, tag, attrs):
print('Encountered a start tag:', tag)
def handle_endtag(self, tag):
print('Encountered an end tag :', tag)
def handle_data(self, data):
print('Encountered some data :', data) |
def raw_to_libsvm(ofile, store, full_first_header=False):
"""Write a raw store to libsvm format
:param ofile: file like object to write to
:param store: the raw store
:param full_first_header: Write the full first line regardless of sparseness
"""
for idx,data in enumerate(store):
... | def raw_to_libsvm(ofile, store, full_first_header=False):
"""Write a raw store to libsvm format
:param ofile: file like object to write to
:param store: the raw store
:param full_first_header: Write the full first line regardless of sparseness
"""
for (idx, data) in enumerate(store):
... |
#py_function_1.py
# Globals namespace
STAR = "Sirius" # Polaris
Favorites = [ ]
X = 100
def setStar(name):
"Local namespace"
#remove comment to map to global namespace
#global STAR
STAR = name
Favorites.append(name)
print("STAR: ", STAR)
setStar("Polaris")
print("STAR: ", STAR) | star = 'Sirius'
favorites = []
x = 100
def set_star(name):
"""Local namespace"""
star = name
Favorites.append(name)
print('STAR: ', STAR)
set_star('Polaris')
print('STAR: ', STAR) |
# tests transition from small to large int representation by addition
# 31-bit overflow
i = 0x3fffffff
print(i + i)
print(-i + -i)
# 63-bit overflow
i = 0x3fffffffffffffff
print(i + i)
print(-i + -i)
| i = 1073741823
print(i + i)
print(-i + -i)
i = 4611686018427387903
print(i + i)
print(-i + -i) |
#!/usr/bin/env python3
class Noisy:
'''
Makes noise when you get or set attributes
'''
def __getattribute__(self, name):
'''
Always called on attribute reads. Overidding this method properly is
difficult so you should usually define __getattr__ if you want to handle
... | class Noisy:
"""
Makes noise when you get or set attributes
"""
def __getattribute__(self, name):
"""
Always called on attribute reads. Overidding this method properly is
difficult so you should usually define __getattr__ if you want to handle
missing attributes in s... |
def resolve():
'''
code here
'''
N = int(input())
D, X = [int(item) for item in input().split()]
As = [int(input()) for _ in range(N)]
cnt = 0
for i in range(N):
day = 1
while day <= D:
day +=As[i]
cnt +=1
print(cnt+X)
if __name__ == "__ma... | def resolve():
"""
code here
"""
n = int(input())
(d, x) = [int(item) for item in input().split()]
as = [int(input()) for _ in range(N)]
cnt = 0
for i in range(N):
day = 1
while day <= D:
day += As[i]
cnt += 1
print(cnt + X)
if __name__ == '__m... |
class Solution:
def maxArea(self, height: List[int]) -> int:
maxx = 0
l = 0
r = len(height)-1
while l<r:
maxx = max(maxx,min(height[l],height[r])*(r-l))
if height[l]<height[r]:l+=1
else:r-=1
return maxx
| class Solution:
def max_area(self, height: List[int]) -> int:
maxx = 0
l = 0
r = len(height) - 1
while l < r:
maxx = max(maxx, min(height[l], height[r]) * (r - l))
if height[l] < height[r]:
l += 1
else:
r -= 1
... |
# /usr/bin/env python3
# encoding: utf-8\
class ListNode(object):
def __init__(self, item):
self.val = item
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
'''
:param l1:
:param l2:
:return:listNode
'''
result = ListNode(0)
... | class Listnode(object):
def __init__(self, item):
self.val = item
self.next = None
class Solution:
def add_two_numbers(self, l1, l2):
"""
:param l1:
:param l2:
:return:listNode
"""
result = list_node(0)
cur = result
carry = 0
... |
class PlantContent:
def add_column(self, in_column_name: str, in_column_type: str):
if in_column_name not in self.columns:
self.columns[in_column_name] = in_column_type
def add_foreign_key(self, in_foreign_key_name: str, in_foreign_key_entity: str):
if in_foreign_key_name not in se... | class Plantcontent:
def add_column(self, in_column_name: str, in_column_type: str):
if in_column_name not in self.columns:
self.columns[in_column_name] = in_column_type
def add_foreign_key(self, in_foreign_key_name: str, in_foreign_key_entity: str):
if in_foreign_key_name not in se... |
number_of_students = int(input())
all_students = {}
all_students_high_score = {}
# adding all students + grades in dictionary
for current_student in range(number_of_students):
student = input()
grade = float(input())
all_students.setdefault(student, []).append(grade)
# calculating average grade
for k, v ... | number_of_students = int(input())
all_students = {}
all_students_high_score = {}
for current_student in range(number_of_students):
student = input()
grade = float(input())
all_students.setdefault(student, []).append(grade)
for (k, v) in all_students.items():
all_students[k] = sum(v) / len(v)
if all_... |
# -*- coding: utf-8 -*-
__all__ = (
"Config",
)
class Config(object):
DEBUG = True
TEMPLATES_AUTO_RELOAD = True
| __all__ = ('Config',)
class Config(object):
debug = True
templates_auto_reload = True |
MALE_WORDS = ['he', 'him', 'his']
FEMALE_WORDS = ['she', 'her']
min_length = 10
def preprocess(text): return text.lower().split(' ')
def predict(text):
m = 0
f = 0
preprocessed = preprocess(text)
for word in MALE_WORDS:
if word.lower() in preprocessed:
m += 1
for wor... | male_words = ['he', 'him', 'his']
female_words = ['she', 'her']
min_length = 10
def preprocess(text):
return text.lower().split(' ')
def predict(text):
m = 0
f = 0
preprocessed = preprocess(text)
for word in MALE_WORDS:
if word.lower() in preprocessed:
m += 1
for word in FE... |
class Solution:
def isInterleave(self, s1, s2, s3):
l1 = len(s1)
l2 = len(s2)
l3 = len(s3)
if l1 == l2 == l3 == 0:
return True
if l1 == 0:
return s2 == s3
if l2 == 0:
return s1 == s3
if l1 + l2 != l3:
return F... | class Solution:
def is_interleave(self, s1, s2, s3):
l1 = len(s1)
l2 = len(s2)
l3 = len(s3)
if l1 == l2 == l3 == 0:
return True
if l1 == 0:
return s2 == s3
if l2 == 0:
return s1 == s3
if l1 + l2 != l3:
return Fa... |
the_count = [1,2,3,4,5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print(f"This is count {number}")
# same as above
for fruit in fruits:
print(f"A fruid of type: {fruit}")
# ... | the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
for number in the_count:
print(f'This is count {number}')
for fruit in fruits:
print(f'A fruid of type: {fruit}')
for i in change:
print(f'I got {i}')
elements = list(range(0, 6... |
#!/usr/bin/python3
BOT_OAUTH = ''
CLIENT_ID = ''
CLIENT_SECRET = ''
CHANNEL = 'botdev' | bot_oauth = ''
client_id = ''
client_secret = ''
channel = 'botdev' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.