content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
ENV = 'testing'
DEBUG = True
TESTING = True
SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/flask_example_test'
SQLALCHEMY_TRACK_MODIFICATIONS = False
ERROR_404_HELP = False
| env = 'testing'
debug = True
testing = True
sqlalchemy_database_uri = 'postgresql://localhost/flask_example_test'
sqlalchemy_track_modifications = False
error_404_help = False |
# Copyright (C) 2018 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | load('//tools/build/rules:cc.bzl', 'cc_stripped_binary')
def _symbol_exports(name, exports):
native.genrule(name=name + '_syms', srcs=[exports], outs=[name + '_syms.S'], cmd='cat $< | awk \'{print ".global",$$0}\' > $@')
native.genrule(name=name + '_ldscript', srcs=[exports], outs=[name + '.ldscript'], cmd='('... |
class TwythonError(Exception):
@property
def msg(self) -> str: ...
class TwythonRateLimitError(TwythonError):
@property
def retry_after(self) -> int: ...
class TwythonAuthError(TwythonError): ... | class Twythonerror(Exception):
@property
def msg(self) -> str:
...
class Twythonratelimiterror(TwythonError):
@property
def retry_after(self) -> int:
...
class Twythonautherror(TwythonError):
... |
try:
sc = input("Enter your score between 0.0 and 1.0: ")
#sc = 0.85
score = float(sc)
except:
if score > 1.0 or score < 0.0:
print("Error, input should be between 0.0 and 1.0")
quit()
if score >= 0.9:
print('A')
elif score >= 0.8:
print('B')
elif score >= 0.7:
print('C')
elif s... | try:
sc = input('Enter your score between 0.0 and 1.0: ')
score = float(sc)
except:
if score > 1.0 or score < 0.0:
print('Error, input should be between 0.0 and 1.0')
quit()
if score >= 0.9:
print('A')
elif score >= 0.8:
print('B')
elif score >= 0.7:
print('C')
elif score < 0.6:
... |
passw = input()
def Is_Valid(password):
valid_length = False
two_digits = False
only = True
digit = 0
let_dig = 0
if len(password) >= 6 and len(password) <= 10:
valid_length = True
else:
print('Password must be between 6 and 10 characters')
for i in password:
if ... | passw = input()
def is__valid(password):
valid_length = False
two_digits = False
only = True
digit = 0
let_dig = 0
if len(password) >= 6 and len(password) <= 10:
valid_length = True
else:
print('Password must be between 6 and 10 characters')
for i in password:
if... |
# Algebraic-only implementation of two's complement in pure Python
#
# Written by: Patrizia Favaron
def raw_to_compl2(iRaw, iNumBits):
# Establish minimum and maximum possible raw values
iMinRaw = 0
iMaxRaw = 2**iNumBits - 1
# Clip value arithmetically
if iRaw < iMinRaw:
iRaw = iMinRaw
if iRaw > iMaxRaw:
... | def raw_to_compl2(iRaw, iNumBits):
i_min_raw = 0
i_max_raw = 2 ** iNumBits - 1
if iRaw < iMinRaw:
i_raw = iMinRaw
if iRaw > iMaxRaw:
i_raw = iMaxRaw
i_max_value = 2 ** (iNumBits - 1) - 1
if iRaw <= iMaxValue:
i_value = iRaw
else:
i_value = iRaw - 2 ** iNumBits... |
with open('./input.txt') as input:
hits = {}
for line in input:
(x1, y1), (x2, y2) = [ map(int, point.split(',')) for point in line.strip().split(' -> ')]
if x1 == x2:
for y in range(min(y1, y2), max(y1, y2) + 1):
if (x1, y) in hits:
hits[... | with open('./input.txt') as input:
hits = {}
for line in input:
((x1, y1), (x2, y2)) = [map(int, point.split(',')) for point in line.strip().split(' -> ')]
if x1 == x2:
for y in range(min(y1, y2), max(y1, y2) + 1):
if (x1, y) in hits:
hits[x1, y] +... |
def get_cat_vars_dict(df, categorical_cols, feature_names, target_name):
cat_vars_dict = {}
for col in [ col for col in categorical_cols if col != target_name]:
cat_vars_dict[feature_names.index(col)] = len(df[col].unique())
return cat_vars_dict | def get_cat_vars_dict(df, categorical_cols, feature_names, target_name):
cat_vars_dict = {}
for col in [col for col in categorical_cols if col != target_name]:
cat_vars_dict[feature_names.index(col)] = len(df[col].unique())
return cat_vars_dict |
class RestApi(object):
def __init__(self, app):
self.app = app
self.frefix_url = self.app.config.get("API_URL_PREFIX") or ""
self.views = []
def register_api(self, bleuprint, view, endpoint, url):
view_func = view.as_view(endpoint)
links = {}
# detail_url = "{}<... | class Restapi(object):
def __init__(self, app):
self.app = app
self.frefix_url = self.app.config.get('API_URL_PREFIX') or ''
self.views = []
def register_api(self, bleuprint, view, endpoint, url):
view_func = view.as_view(endpoint)
links = {}
links['self'] = url... |
class Kanji():
def __init__(self):
self.kanji = None
self.strokes = 0
self.pronunciation = None
self.definition = ""
self.kanji_shinjitai = None
self.strokes_shinjitai = 0
def __unicode__(self):
if self.kanji_shinjitai:
ks = " (%s)" % self.ka... | class Kanji:
def __init__(self):
self.kanji = None
self.strokes = 0
self.pronunciation = None
self.definition = ''
self.kanji_shinjitai = None
self.strokes_shinjitai = 0
def __unicode__(self):
if self.kanji_shinjitai:
ks = ' (%s)' % self.kanj... |
def p_error( p ):
print
print( "SYNTAX ERROR %s" % str( p ) )
print
raise Exception | def p_error(p):
print
print('SYNTAX ERROR %s' % str(p))
print
raise Exception |
numeros = []
par = []
impar = []
while True:
n = (int(input('Digite um numero: ')))
numeros.append(n)
if n % 2 == 0:
par.append(n)
else:
impar.append(n)
resp = str(input('Deseja continuar [S/N]: ')).strip().upper()[0]
while resp not in 'SN':
resp = str(input('Tente novam... | numeros = []
par = []
impar = []
while True:
n = int(input('Digite um numero: '))
numeros.append(n)
if n % 2 == 0:
par.append(n)
else:
impar.append(n)
resp = str(input('Deseja continuar [S/N]: ')).strip().upper()[0]
while resp not in 'SN':
resp = str(input('Tente novament... |
def get_label_dict(dataset_name):
label_dict = None
if dataset_name == 'PASCAL':
label_dict = {
'back_ground': 0,
'aeroplane': 1,
'bicycle': 2,
'bird': 3,
'boat': 4,
'bottle': 5,
'bus': 6,
'car': 7,
... | def get_label_dict(dataset_name):
label_dict = None
if dataset_name == 'PASCAL':
label_dict = {'back_ground': 0, 'aeroplane': 1, 'bicycle': 2, 'bird': 3, 'boat': 4, 'bottle': 5, 'bus': 6, 'car': 7, 'cat': 8, 'chair': 9, 'cow': 10, 'diningtable': 11, 'dog': 12, 'horse': 13, 'motorbike': 14, 'person': 15,... |
start = 0
end = 1781
instance = 0
for i in range(150):
f = open(f"ec2files/ec2file{i}.py", "w")
f.write(f"from scraper import * \ns = Scraper(start={start}, end={end}, max_iter=30, scraper_instance={instance}) \ns.scrape_letterboxd()")
start = end + 1
end = start + 1781
instance += 1
f.close()... | start = 0
end = 1781
instance = 0
for i in range(150):
f = open(f'ec2files/ec2file{i}.py', 'w')
f.write(f'from scraper import * \ns = Scraper(start={start}, end={end}, max_iter=30, scraper_instance={instance}) \ns.scrape_letterboxd()')
start = end + 1
end = start + 1781
instance += 1
f.close() |
class Config(object):
SECRET_KEY = "aaaaaaa"
debug = False
class Production(Config):
debug = True
CSRF_ENABLED = False
SQLALCHEMY_DATABASE_URI = "mysql://username:password@127.0.0.1/DBname"
migration_directory = "migrations"
| class Config(object):
secret_key = 'aaaaaaa'
debug = False
class Production(Config):
debug = True
csrf_enabled = False
sqlalchemy_database_uri = 'mysql://username:password@127.0.0.1/DBname'
migration_directory = 'migrations' |
# This program creates an object of the pet class
# and asks the user to enter the name, type, and age of pet.
# The program retrieves the pet's name, type, and age and
# displays the data.
class Pet:
def __init__(self, name, animal_type, age):
# Gets the pets name
self.__name = name
... | class Pet:
def __init__(self, name, animal_type, age):
self.__name = name
self.__animal_type = animal_type
self.__age = age
def set_name(self, name):
self.__name = name
def set_type(self, animal_type):
self.__animal_type = animal_type
def set_age(self, age):
... |
#
# PySNMP MIB module SCSPATMARP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SCSPATMARP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:01:23 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, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, constraints_intersection, value_size_constraint, single_value_constraint) ... |
# coding=utf-8
__author__ = 'lxn3032'
class ControllerBase(object):
def __init__(self, period, ValueType=float):
self.ValueType = ValueType
self.T = period
self.error_1 = ValueType(0)
self.error_2 = ValueType(0)
self.current_value = ValueType(0)
self.target_value = ... | __author__ = 'lxn3032'
class Controllerbase(object):
def __init__(self, period, ValueType=float):
self.ValueType = ValueType
self.T = period
self.error_1 = value_type(0)
self.error_2 = value_type(0)
self.current_value = value_type(0)
self.target_value = value_type(0... |
{
"cells": [
{
"cell_type": "code",
"execution_count": 20,
"id": "informative-england",
"metadata": {},
"outputs": [],
"source": [
"### This is the interworkings and mathematics behind the equity models\n",
"\n",
"### Gordon (Constant) Growth Model module ###\n",
"def Gordongrowth(d... | {'cells': [{'cell_type': 'code', 'execution_count': 20, 'id': 'informative-england', 'metadata': {}, 'outputs': [], 'source': ['### This is the interworkings and mathematics behind the equity models\n', '\n', '### Gordon (Constant) Growth Model module ###\n', 'def Gordongrowth(dividend, costofequity, growthrate):\n', '... |
class SYCSException(Exception):
pass
class CredentialsException(SYCSException):
def __init__(self):
super(SYCSException, self).__init__('username or password not provided.')
class InvalidCredentialsException(SYCSException):
def __init__(self):
super(SYCSException, self).__init__('wrong u... | class Sycsexception(Exception):
pass
class Credentialsexception(SYCSException):
def __init__(self):
super(SYCSException, self).__init__('username or password not provided.')
class Invalidcredentialsexception(SYCSException):
def __init__(self):
super(SYCSException, self).__init__('wrong u... |
def solution(A, B, s):
A.sort()
B.sort()
i = len(A) - 1
j = len(B) - 1
while 0 <= j <= len(B) - 1 and i:
pass
| def solution(A, B, s):
A.sort()
B.sort()
i = len(A) - 1
j = len(B) - 1
while 0 <= j <= len(B) - 1 and i:
pass |
a = int(input())
for i in range(1, a+1):
if a % i == 0:
print(i)
| a = int(input())
for i in range(1, a + 1):
if a % i == 0:
print(i) |
class When_we_have_a_test:
@classmethod
def examples(cls):
yield 1
yield 3
def when_things_happen(self):
pass
def it_should_do_this_test(self, arg):
assert arg < 3
| class When_We_Have_A_Test:
@classmethod
def examples(cls):
yield 1
yield 3
def when_things_happen(self):
pass
def it_should_do_this_test(self, arg):
assert arg < 3 |
class Solution:
def validTree(self, n: int, edges: list[list[int]]) -> bool:
if not n:
return True
adj = {i: [] for i in range(n)}
for n1, n2 in edges:
adj[n1].append(n2)
adj[n2].append(n1)
visit = set()
def dfs(i, prev):
if ... | class Solution:
def valid_tree(self, n: int, edges: list[list[int]]) -> bool:
if not n:
return True
adj = {i: [] for i in range(n)}
for (n1, n2) in edges:
adj[n1].append(n2)
adj[n2].append(n1)
visit = set()
def dfs(i, prev):
i... |
def get_accounts_for_path(client, path):
ou = client.convert_path_to_ou(path)
response = client.list_children_nested(ParentId=ou, ChildType="ACCOUNT")
return ",".join([r.get("Id") for r in response])
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apa... | def get_accounts_for_path(client, path):
ou = client.convert_path_to_ou(path)
response = client.list_children_nested(ParentId=ou, ChildType='ACCOUNT')
return ','.join([r.get('Id') for r in response])
macros = {'get_accounts_for_path': get_accounts_for_path} |
# Busiest Time in The Mall
def find_busiest_period(data):
peak_time = peak_vis = cur_vis = i = 0
while i < len(data):
time, v, enter = data[i]
cur_vis += v if enter else -v
if i == len(data)-1 or time != data[i+1][0]:
if cur_vis > peak_vis:
peak_vis = cur_vis
peak_time = ti... | def find_busiest_period(data):
peak_time = peak_vis = cur_vis = i = 0
while i < len(data):
(time, v, enter) = data[i]
cur_vis += v if enter else -v
if i == len(data) - 1 or time != data[i + 1][0]:
if cur_vis > peak_vis:
peak_vis = cur_vis
peak_... |
def test__delete__401_when_no_auth_headers(client):
r = client.delete('/themes/1')
assert r.status_code == 401, r.get_json()
def test__delete__401_when_incorrect_auth(client, faker):
r = client.delete('/themes/1', headers={
'Authentication': 'some_incorrect_token'})
assert r.status_code == 4... | def test__delete__401_when_no_auth_headers(client):
r = client.delete('/themes/1')
assert r.status_code == 401, r.get_json()
def test__delete__401_when_incorrect_auth(client, faker):
r = client.delete('/themes/1', headers={'Authentication': 'some_incorrect_token'})
assert r.status_code == 401, r.get_js... |
# Python 3.8.3
with open("input.txt", "r") as f:
puzzle_input = [int(i) for i in f.read().split()]
def fuel_needed(mass):
fuel = mass // 3 - 2
return fuel + fuel_needed(fuel) if fuel > 0 else 0
sum = 0
for mass in puzzle_input:
sum += fuel_needed(mass)
print(sum)
| with open('input.txt', 'r') as f:
puzzle_input = [int(i) for i in f.read().split()]
def fuel_needed(mass):
fuel = mass // 3 - 2
return fuel + fuel_needed(fuel) if fuel > 0 else 0
sum = 0
for mass in puzzle_input:
sum += fuel_needed(mass)
print(sum) |
# Date: 2020/11/12
# Author: Luis Marquez
# Description:
# This is a simple program in which the binary search will be implemented to calculate a square root result
#
#BINARY_SEARCH(): This function realize a binary search
def binary_search():
#objective: The number in which the root will be cal... | def binary_search():
objective = int(input(f'\nType a number: '))
print(f'\n')
epsilon = 0.01
low = 0.0
high = max(1.0, objective)
answer = (high + low) / 2
while abs(answer ** 2 - objective) >= epsilon:
print(f'Low={round(low, 2)} \t high={round(high, 2)} \t Answer={round(answer, 2)... |
class Config(object):
DESCRIPTION = 'Mock generator for c code'
VERSION = '0.5'
AUTHOR = 'Freddy Hurkmans'
LICENSE = 'BSD 3-Clause'
# set defaults for parameters
verbose = False
max_nr_function_calls = '25'
charstar_is_input_string = False
UNITY_INCLUDE = '#include "unity.h"'
#... | class Config(object):
description = 'Mock generator for c code'
version = '0.5'
author = 'Freddy Hurkmans'
license = 'BSD 3-Clause'
verbose = False
max_nr_function_calls = '25'
charstar_is_input_string = False
unity_include = '#include "unity.h"'
custom_includes = []
ctype_to_uni... |
left_eye_connection = [
# Left eye.
(263, 249),
(249, 390),
(390, 373),
(373, 374),
(374, 380),
(380, 381),
(381, 382),
(382, 362),
(263, 466),
(466, 388),
(388, 387),
(387, 386),
(386, 385),
(385, 384),
(384, 398),
(398, 362)
]
left_eyebrow_connection... | left_eye_connection = [(263, 249), (249, 390), (390, 373), (373, 374), (374, 380), (380, 381), (381, 382), (382, 362), (263, 466), (466, 388), (388, 387), (387, 386), (386, 385), (385, 384), (384, 398), (398, 362)]
left_eyebrow_connection = [(276, 283), (283, 282), (282, 295), (295, 285), (300, 293), (293, 334), (334, ... |
# --------------------------------------------------------
# GA3C for Dragon
# Copyright(c) 2017 SeetaTech
# Written by Ting Pan
# --------------------------------------------------------
class Config(object):
#########################################################################
# Game configuration
... | class Config(object):
atari_game = 'PongDeterministic-v0'
play_mode = False
train_models = True
load_checkpoint = False
load_episode = 32000
agents = 32
predictors = 2
trainers = 2
device = 'gpu:0'
dynamic_settings = True
dynamic_settings_step_wait = 20
dynamic_settings_i... |
INPUT_BUCKET = 'input-image-files'
OUTPUT_BUCKET = 'output-image-files'
INPUT_QUEUE = 'https://sqs.us-east-1.amazonaws.com/378107157540/Request-Queue'
OUTPUT_QUEUE = 'https://sqs.us-east-1.amazonaws.com/378107157540/Response-Queue'
| input_bucket = 'input-image-files'
output_bucket = 'output-image-files'
input_queue = 'https://sqs.us-east-1.amazonaws.com/378107157540/Request-Queue'
output_queue = 'https://sqs.us-east-1.amazonaws.com/378107157540/Response-Queue' |
f='11'
for i in range(5):
c=1
s=''
for j in range(len(f)-1):
if f[j]==f[j+1]:
c+=1
else:
s=(str(c)+(f[j]))
s=str(c)+(f[j])
f=str(s)
print(f)
| f = '11'
for i in range(5):
c = 1
s = ''
for j in range(len(f) - 1):
if f[j] == f[j + 1]:
c += 1
else:
s = str(c) + f[j]
s = str(c) + f[j]
f = str(s)
print(f) |
a=input("ENTER THE NUMBER\n")
if a[0]==a[1] or a[0]==a[2] or a[0]==a[3] or a[0]==a[4] or a[1]==a[2] or a[1]==a[3] or a[1]==a[4] or a[2]==a[3] or a[2]==a[4]:
print("THE ENTERED NUMBER IS NOT A UNIQUE NUMBER")
else:
print(a,"IS AN UNIQUE NUMBER")
| a = input('ENTER THE NUMBER\n')
if a[0] == a[1] or a[0] == a[2] or a[0] == a[3] or (a[0] == a[4]) or (a[1] == a[2]) or (a[1] == a[3]) or (a[1] == a[4]) or (a[2] == a[3]) or (a[2] == a[4]):
print('THE ENTERED NUMBER IS NOT A UNIQUE NUMBER')
else:
print(a, 'IS AN UNIQUE NUMBER') |
# The goal of this exercise is to get hands-on experience working with
# list comprehensions, and other comprehensions. Write a complementary
# function to each of the below, which accomplishes the same logic in
# a one-liner (using list/set/dict comprehensions).
# Exercise 1
# Adds 5 to each element
def add_five(nu... | def add_five(numbers):
out = []
for num in numbers:
out.append(num + 5)
return out
def add_five_one_liner(numbers):
pass
def drop_small(numbers):
out = []
for num in numbers:
if not num < 4:
out.append(num)
return out
def drop_small_one_liner(numbers):
pass... |
n = len(x)
if n % 2:
median_ = sorted(x)[round(0.5*(n-1))]
else:
x_ord, index = sorted(x), round(0.5 * n)
median_ = 0.5 * (x_ord[index-1] + x_ord[index])
median_ | n = len(x)
if n % 2:
median_ = sorted(x)[round(0.5 * (n - 1))]
else:
(x_ord, index) = (sorted(x), round(0.5 * n))
median_ = 0.5 * (x_ord[index - 1] + x_ord[index])
median_ |
def agreeanswer():
i01.disableRobotRandom(30)
i01.setHandSpeed("left", 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)
i01.setHandSpeed("right", 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)
i01.setArmSpeed("left", 1.0, 1.0, 1.0, 1.0)
i01.setArmSpeed("right", 1.0, 1.0, 1.0, 1.0)
i01.setHeadSpeed(1.0, 0.90)
i01.setTorsoSpeed(1.0, 1.0, 1.0)... | def agreeanswer():
i01.disableRobotRandom(30)
i01.setHandSpeed('left', 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)
i01.setHandSpeed('right', 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)
i01.setArmSpeed('left', 1.0, 1.0, 1.0, 1.0)
i01.setArmSpeed('right', 1.0, 1.0, 1.0, 1.0)
i01.setHeadSpeed(1.0, 0.9)
i01.setTorsoSpeed(1... |
database_path = "{projects}/brewmaster/server/data/"
heater_port = 12
port_number = 5000
stirrer_port = 13
temp_sensor_path = "/sys/bus/w1/devices/{your_sensor_id}/w1_slave"
use_fake = True
| database_path = '{projects}/brewmaster/server/data/'
heater_port = 12
port_number = 5000
stirrer_port = 13
temp_sensor_path = '/sys/bus/w1/devices/{your_sensor_id}/w1_slave'
use_fake = True |
# def favcolors(mameet,qj,mustafa):
# print(mameet, qj,mustafa)
# favcolors(qj='green',mameet='black',mustafa='blue')
# # ,,
def favcolors(**kwargs):
print(kwargs)
for key,val in kwargs.items():
print('Favourite color of',key,'is',val)
# favcolors(qj='green',mameet='black',mustafa='blue',fatima='... | def favcolors(**kwargs):
print(kwargs)
for (key, val) in kwargs.items():
print('Favourite color of', key, 'is', val)
def favcolors2(num1, *args, qj, **kwargs):
print('num1:', num1)
print('args:', args)
print('def arguments:', qj)
print('kwargs:', kwargs)
favcolors2(10, 20, 'aaaa', qj='g... |
# This file is distributed under the same license as the Django package.
#
# The *_FORMAT strings use the Django date format syntax,
# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
# Formatting for date objects.
DATE_FORMAT = 'N j, Y'
# Formatting for time objects.
TIME_FORMAT = 'P'
# Formatti... | date_format = 'N j, Y'
time_format = 'P'
datetime_format = 'N j, Y, P'
year_month_format = 'F Y'
month_day_format = 'F j'
short_date_format = 'm/d/Y'
short_datetime_format = 'm/d/Y P'
first_day_of_week = 0
date_input_formats = ['%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', '%b %d %Y', '%b %d, %Y', '%d %b %Y', '%d %b, %Y', '%B %d... |
number_of_rooms = int(input())
free_chairs = 0
insufficiency = False
for i in range(1, number_of_rooms + 1):
list_of_chairs_and_people = input().split()
chairs = len(list_of_chairs_and_people[0])
needed_ones = int(list_of_chairs_and_people[1])
if chairs >= needed_ones:
free_chairs += cha... | number_of_rooms = int(input())
free_chairs = 0
insufficiency = False
for i in range(1, number_of_rooms + 1):
list_of_chairs_and_people = input().split()
chairs = len(list_of_chairs_and_people[0])
needed_ones = int(list_of_chairs_and_people[1])
if chairs >= needed_ones:
free_chairs += chairs - ne... |
def funcion():
return 5
def generador():
yield 1,2,3,4,5,6,7,8,9
print(generador())
print(generador())
print(generador())
| def funcion():
return 5
def generador():
yield (1, 2, 3, 4, 5, 6, 7, 8, 9)
print(generador())
print(generador())
print(generador()) |
# vim: set ts=8 sts=4 sw=4 tw=99 et:
#
# This file is part of AMBuild.
#
# AMBuild is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ... | class Basegenerator(object):
def __init__(self, cm):
self.cm = cm
@property
def backend(self):
raise exception('Must be implemented!')
def add_symlink(self, context, source, output_path):
raise exception('Must be implemented!')
def add_folder(self, context, folder):
... |
# Copyright 2020 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | def one_level_function():
return 0
def multiline_args_tuple(a, b, c):
return 0
def nested_if_statements():
if True:
if True:
return 0
def nested_for_statements():
for x in range(1):
for y in range(1):
return 0
def nested_with_statements():
with open(__file... |
class BusInPOZ:
def __init__(self, intersection, check_in_bus_info, check_in_phase, check_in_phasetime, check_in_time, last_check_in):
self.intersection_of_interest = intersection
self.bus_id = check_in_bus_info.idVeh
self.check_in_time = check_in_time
self.check_in_phase = chec... | class Businpoz:
def __init__(self, intersection, check_in_bus_info, check_in_phase, check_in_phasetime, check_in_time, last_check_in):
self.intersection_of_interest = intersection
self.bus_id = check_in_bus_info.idVeh
self.check_in_time = check_in_time
self.check_in_phase = check_in... |
# -*- coding: utf-8 -*-
__version__ = '0.5.0.dev0'
PROJECT_NAME = "gx-tool-db"
PROJECT_OWNER = PROJECT_USERAME = "galaxyproject"
PROJECT_AUTHOR = 'Galaxy Project and Community'
PROJECT_EMAIL = 'jmchilton@gmail.com'
PROJECT_URL = "https://github.com/galaxyproject/gx-tool-db"
RAW_CONTENT_URL = "https://raw.github.com... | __version__ = '0.5.0.dev0'
project_name = 'gx-tool-db'
project_owner = project_userame = 'galaxyproject'
project_author = 'Galaxy Project and Community'
project_email = 'jmchilton@gmail.com'
project_url = 'https://github.com/galaxyproject/gx-tool-db'
raw_content_url = 'https://raw.github.com/%s/%s/main/' % (PROJECT_USE... |
class Vertex:
def __init__(self, x=None, y=None):
self.pos = [x, y]
self.x = x
self.y = y
self.data = None
def __str__(self):
return f"{self.pos}"
def __repr__(self):
return f"{self.pos}"
def __hash__(self):
return hash(''.join([str(x) for x... | class Vertex:
def __init__(self, x=None, y=None):
self.pos = [x, y]
self.x = x
self.y = y
self.data = None
def __str__(self):
return f'{self.pos}'
def __repr__(self):
return f'{self.pos}'
def __hash__(self):
return hash(''.join([str(x) for x in... |
#$Header: /nfs/slac/g/glast/ground/cvs/GlastRelease-scons/xmlBase/xmlBaseLib.py,v 1.4 2009/01/23 00:21:04 ecephas Exp $
def generate(env, **kw):
if not kw.get('depsOnly',0):
env.Tool('addLibrary', library = ['xmlBase'], package = 'xmlBase')
if env['PLATFORM']=='win32' and env.get('CONTAINERNAME','')... | def generate(env, **kw):
if not kw.get('depsOnly', 0):
env.Tool('addLibrary', library=['xmlBase'], package='xmlBase')
if env['PLATFORM'] == 'win32' and env.get('CONTAINERNAME', '') == 'GlastRelease':
env.Tool('findPkgPath', package='xmlBase')
env.Tool('facilitiesLib')
env.Tool('a... |
# Python program to print the first non-repeating character
NO_OF_CHARS = 256
# Returns an array of size 256 containg count
# of characters in the passed char array
def getCharCountArray(string):
count = [0] * NO_OF_CHARS
for i in string:
count[ord(i)] += 1
return count
# The function returns in... | no_of_chars = 256
def get_char_count_array(string):
count = [0] * NO_OF_CHARS
for i in string:
count[ord(i)] += 1
return count
def first_non_repeating(string):
count = get_char_count_array(string)
index = -1
k = 0
for i in string:
if count[ord(i)] == 1:
index = ... |
class Solution:
def reverse(self, x: int) -> int:
if x < 0 and x >= (-2**31):
# x_str = str(x)
# x_str_rev = '-'
# access from the 2nd last element excluding "-" sign
x_str_rev = '-' + str(x)[len(str(x)):0:-1]
if int(x_str_rev) < (-2**31):
... | class Solution:
def reverse(self, x: int) -> int:
if x < 0 and x >= -2 ** 31:
x_str_rev = '-' + str(x)[len(str(x)):0:-1]
if int(x_str_rev) < -2 ** 31:
return_value = 0
else:
return_value = int(x_str_rev)
elif x >= 0 and x <= 2 ** 3... |
# This problem was asked by Palantir.
# Given a number represented by a list of digits, find the next greater permutation of a
# number, in terms of lexicographic ordering. If there is not greater permutation possible,
# return the permutation with the lowest value/ordering.
# For example, the list [1,2,3] should retur... | def next_perm(arr):
n = len(arr)
i = n - 1
while i > 0:
(arr[i], arr[i - 1]) = (arr[i - 1], arr[i])
if arr[i - 1] > arr[i]:
return arr
i -= 1
return sorted(arr)
print(next_perm([1, 4, 3, 2])) |
def length_of_longest_substring(s):
dici = {}
max_s_rep = repeticao_na_fila = 0
for i, value in enumerate(s):
if value in dici:
num_repetidos = dici[value] + 1
if num_repetidos > repeticao_na_fila:
repeticao_na_fila = num_repetidos
num_repeticoes = i +... | def length_of_longest_substring(s):
dici = {}
max_s_rep = repeticao_na_fila = 0
for (i, value) in enumerate(s):
if value in dici:
num_repetidos = dici[value] + 1
if num_repetidos > repeticao_na_fila:
repeticao_na_fila = num_repetidos
num_repeticoes = i... |
#!/usr/bin/python3
f = open("/home/bccue/Cores-SweRV/testbench/asm/hello_world.s", "r")
g = open("/home/bccue/Cores-SweRV/testbench/asm/hello_world_c.c", "w")
for data in f:
data = data.strip("\n")
if (data == "") or ("//" in data):
continue
#New text to print to terminal
if (".ascii" in data):
print("__as... | f = open('/home/bccue/Cores-SweRV/testbench/asm/hello_world.s', 'r')
g = open('/home/bccue/Cores-SweRV/testbench/asm/hello_world_c.c', 'w')
for data in f:
data = data.strip('\n')
if data == '' or '//' in data:
continue
if '.ascii' in data:
print('__asm (".ascii \\"===========================... |
#!/usr/bin/python
# ex:set fileencoding=utf-8:
default_app_config = 'mosquitto.apps.Config'
| default_app_config = 'mosquitto.apps.Config' |
#Loading one line from file and starting a dictionary
for line in open('rosalind_ini6.txt', 'r').readlines():
contents = line.split()
dictionary = dict()
#Checking if a word from line is in dictionary, then sum the occurrences
for i in range(0, len(contents), 1):
if (contents[i] not in dictionary):
... | for line in open('rosalind_ini6.txt', 'r').readlines():
contents = line.split()
dictionary = dict()
for i in range(0, len(contents), 1):
if contents[i] not in dictionary:
dictionary[contents[i]] = 1
else:
dictionary[contents[i]] += 1
for (key, value) in dictionary.items():
print(key, val... |
# Python file
# Save this with extension .py
# Made By Arnav Naik
# A beginner's guide to Python
print("Welcome To The Trivia!!")
# Scoring
total_q = 4
print("Total Questions: ", total_q)
def question_1():
global score
score = int(0)
# Question1
question1 = str(input("1. What's the bes... | print('Welcome To The Trivia!!')
total_q = 4
print('Total Questions: ', total_q)
def question_1():
global score
score = int(0)
question1 = str(input("1. What's the best programming language? "))
ans1u = 'python'
ans1 = 'Python'
if question1 == ans1u or question1 == ans1:
question_1()
print('Correct!!')... |
class Solution:
def toLowerCase(self, str: str) -> str:
res = []
for i in range(len(str)):
if 65 <= ord(str[i]) <= 92:
res.append(chr(ord(str[i]) + 32))
else:
res.append(str[i])
return "".join(res)
def toLowerCase2(self, str: str) ... | class Solution:
def to_lower_case(self, str: str) -> str:
res = []
for i in range(len(str)):
if 65 <= ord(str[i]) <= 92:
res.append(chr(ord(str[i]) + 32))
else:
res.append(str[i])
return ''.join(res)
def to_lower_case2(self, str: ... |
# --------------
# Code starts here
# Create the lists
class_1 = ['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio' ]
class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes']
# Concatenate both the strings
new_class = (class_1 + class_2)
print (new_class)
# Append the list
new_class.append('Peter... | class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio']
class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes']
new_class = class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
new_class.remove('Carla Gentry')
print(new_class)
mathematics = {'Geoffrey Hinton... |
#!/usr/bin/env python3
# Created by Tiago Minuzzi, 2020.
# Files
in_fasta = "teste.fasta"
in_ids = "ids.txt"
out_fasta = "res_fas.fa"
# Empty dictionary to store sequences
fas_dict = {}
# Read reference fasta file
with open(in_fasta, "r") as fasta:
fasta=fasta.readlines()
for linha in fasta:
linha = linha.strip()
... | in_fasta = 'teste.fasta'
in_ids = 'ids.txt'
out_fasta = 'res_fas.fa'
fas_dict = {}
with open(in_fasta, 'r') as fasta:
fasta = fasta.readlines()
for linha in fasta:
linha = linha.strip()
if linha.startswith('>'):
kl = linha[1:]
fas_dict[kl] = ''
else:
f... |
class State:
def __init__(self, goal, task, visual, ):
self.goal = None
self.task = None
self.visual = None
self.features = None | class State:
def __init__(self, goal, task, visual):
self.goal = None
self.task = None
self.visual = None
self.features = None |
for i in range(1, 10):
print(i, end=', ')
print()
for i in range(0, 10, 2):
print(i, ' ', end='')
print()
for i in range(10, 1, -2):
print(i, ' ', end='')
| for i in range(1, 10):
print(i, end=', ')
print()
for i in range(0, 10, 2):
print(i, ' ', end='')
print()
for i in range(10, 1, -2):
print(i, ' ', end='') |
# Copyright 2017-2019 Sergej Schumilo, Cornelius Aschermann, Tim Blazytko
# Copyright 2019-2020 Intel Corporation
#
# SPDX-License-Identifier: AGPL-3.0-or-later
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[0;33m'
FAIL = '\033[91m'
ENDC = '\033[0m'
CLRSCR = ... | header = '\x1b[95m'
okblue = '\x1b[94m'
okgreen = '\x1b[92m'
warning = '\x1b[0;33m'
fail = '\x1b[91m'
endc = '\x1b[0m'
clrscr = '\x1b[1;1H'
realclrscr = '\x1b[2J'
bold = '\x1b[1m'
flush_line = '\r\x1b[K'
def move_cursor_up(num):
return '\x1b[' + str(num) + 'A'
def move_cursor_down(num):
return '\x1b[' + str(n... |
# Longest Increasing Subsequence
# We have discussed Overlapping Subproblems and Optimal Substructure properties.
# Let us discuss Longest Increasing Subsequence (LIS) problem as an example
# problem that can be solved using Dynamic Programming.
# The Longest Increasing Subsequence (LIS) problem is to find the length... | def longest_increasing_sequence(list1):
n = len(list1)
list2 = [1 for i in range(n)]
for i in range(1, n):
for j in range(i):
if list1[i] > list1[j] and list2[i] < list2[j] + 1:
list2[i] = list2[j] + 1
return max(list2)
print(longest_increasing_sequence([50, 3, 10, 7,... |
##Ejercicio 2
# el siguiente codigo busca la raiz entera de un numero dado usando BS
# Busqueda Binaria
# Entrada:
# 16 (si se desea encontrar de un numero
# mayor 20 incrementar el tamanio del array)
# Salida:
# Does not exist
#or
# "The element was found " +48
#
# El ejercicio incluye el ordenamiento del arra... | def binary_search(list, n):
baja = 0
alta = len(list) - 1
while baja <= alta:
middle = (alta + baja) // 2
middle_element = list[middle]
cuadrado = middle_element * middle_element
if cuadrado == n:
return middle
if cuadrado < n:
baja = middle + ... |
number = input("Type a number: ")
try:
number = float(number)
print("The number is: ", number)
except:
print("Invalid number") | number = input('Type a number: ')
try:
number = float(number)
print('The number is: ', number)
except:
print('Invalid number') |
def show_banner(value: str, times: int):
print(value * times)
def validate_loan_eligibility(has_income: bool, credit_report: bool, payment_default: bool) -> str:
if(has_income and (credit_report and (not payment_default))):
return "Eligible for loan"
else:
return "Not Eligible for loan"
... | def show_banner(value: str, times: int):
print(value * times)
def validate_loan_eligibility(has_income: bool, credit_report: bool, payment_default: bool) -> str:
if has_income and (credit_report and (not payment_default)):
return 'Eligible for loan'
else:
return 'Not Eligible for loan'
def... |
#!/usr/bin/env python3
shifted_serial = '''
0000000000400d00 db 0x96 ; '.'
0000000000400d01 db 0x9e ; '.'
0000000000400d02 db 0x86 ; '.'
0000000000400d03 db 0xb0 ; '.'
0000000000400d04 db 0xb4 ; '.'
0000000000400d05 db 0x8c ; '.'
0000000000400d06 db 0x5a ;... | shifted_serial = "\n0000000000400d00 db 0x96 ; '.'\n0000000000400d01 db 0x9e ; '.'\n0000000000400d02 db 0x86 ; '.'\n0000000000400d03 db 0xb0 ; '.'\n0000000000400d04 db 0xb4 ; '.'\n0000000000400d05 db 0x8c ; '.'\n0000000000400d06 db 0x5a ; 'Z'\n0000000000400... |
class Node:
hostname = None
username = None
key_file = None
def __init__(self, hostname, username, key_file):
self.hostname = hostname
self.username = username
self.key_file = key_file
def __repr__(self):
return self.__str__()
def __str__(self):
return ... | class Node:
hostname = None
username = None
key_file = None
def __init__(self, hostname, username, key_file):
self.hostname = hostname
self.username = username
self.key_file = key_file
def __repr__(self):
return self.__str__()
def __str__(self):
return ... |
def sub(s):
# print(s)
a = list(map(int, s.split('-')))
print(a)
return a[0]*2 - sum(a)
def main():
s = input()
add = s.split('+')
print(add)
print(sum(map(sub, add)))
if __name__ == "__main__":
print(main()) | def sub(s):
a = list(map(int, s.split('-')))
print(a)
return a[0] * 2 - sum(a)
def main():
s = input()
add = s.split('+')
print(add)
print(sum(map(sub, add)))
if __name__ == '__main__':
print(main()) |
# File system, where one can create and edit files protected with Login system. You can call it Personal Diary.
def menu():
print("***Menu***")
inp = input("Welcome user... \nWant to Login(lgn) or Register(reg) (lgn/reg)? ")
if inp == 'lgn':
loginAcct()
elif inp == 'reg':
regA... | def menu():
print('***Menu***')
inp = input('Welcome user... \nWant to Login(lgn) or Register(reg) (lgn/reg)? ')
if inp == 'lgn':
login_acct()
elif inp == 'reg':
reg_acct()
else:
print('\nInvalid choice...')
menu()
def reg_acct():
print('\n*** Registration ***\nP... |
m3 = range(0,1000,3)
m5 = range(0,1000,5)
m15 = range(0,1000,15)
answer = sum(m3)+sum(m5)-sum(m15)
print (answer)
| m3 = range(0, 1000, 3)
m5 = range(0, 1000, 5)
m15 = range(0, 1000, 15)
answer = sum(m3) + sum(m5) - sum(m15)
print(answer) |
__all__=["layer",
"fflayers",
"convnet"
"model",
"optimize"
"cost",
"train",
"util",
"nnfuns",
"dataset"] | __all__ = ['layer', 'fflayers', 'convnetmodel', 'optimizecost', 'train', 'util', 'nnfuns', 'dataset'] |
[
[
0.20155604,
0.13307383,
0.12784087,
float("NaN"),
0.06557849,
0.07970277,
float("NaN"),
0.05212981,
],
[
0.24451376,
0.14168013,
0.12661545,
float("NaN"),
0.10445491,
0.10288933,
float... | [[0.20155604, 0.13307383, 0.12784087, float('NaN'), 0.06557849, 0.07970277, float('NaN'), 0.05212981], [0.24451376, 0.14168013, 0.12661545, float('NaN'), 0.10445491, 0.10288933, float('NaN'), 0.07330904], [0.23630201, 0.15291979, 0.13264396, float('NaN'), 0.10157328, 0.09673594, float('NaN'), 0.07012212], [0.20088469, ... |
def compares_expressions(exp1, exp2) -> bool:
def compile_exp(exp):
return exp.compile(compile_kwargs={"literal_binds": True})
return str(compile_exp(exp1)) == str(compile_exp(exp2))
| def compares_expressions(exp1, exp2) -> bool:
def compile_exp(exp):
return exp.compile(compile_kwargs={'literal_binds': True})
return str(compile_exp(exp1)) == str(compile_exp(exp2)) |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isMirror(self,t1,t2):
if not t1 and not t2:
return True
elif not t1 or not... | class Solution:
def is_mirror(self, t1, t2):
if not t1 and (not t2):
return True
elif not t1 or not t2:
return False
return t1.val == t2.val and self.isMirror(t1.left, t2.rigt) and self.isMirror(t1.right, t2.left)
def is_symmetric(self, root: TreeNode) -> bool:
... |
class BaseParagraphElement(object):
def __init__(self, element: dict, document):
self._element = element
self._document = document
@property
def start_index(self) -> int:
return self._element.get("startIndex")
@property
def end_index(self) -> int:
return self._eleme... | class Baseparagraphelement(object):
def __init__(self, element: dict, document):
self._element = element
self._document = document
@property
def start_index(self) -> int:
return self._element.get('startIndex')
@property
def end_index(self) -> int:
return self._elem... |
#Bottle deposits
x = float(input('Enter the number of containers holding 1 litre or less: '))
y = float(input('Enter the number of containers holding more than 1 litre: '))
refund = float((x*.10)+(y*.25))
print('The refund received will be $',refund) | x = float(input('Enter the number of containers holding 1 litre or less: '))
y = float(input('Enter the number of containers holding more than 1 litre: '))
refund = float(x * 0.1 + y * 0.25)
print('The refund received will be $', refund) |
__SEPARATOR = '/'
__LAYER_TEMPLATE = '...../...../..?../...../.....'
__INNER_BORDER = set([(1,2), (3,2), (2,1), (2,3)])
def calculateBiodiversityRating(layout):
layoutString = layout.replace(__SEPARATOR, '')
biodiveristyRating = 0
for i in range(0, len(layoutString)):
if layoutString[i] == '#':
... | __separator = '/'
__layer_template = '...../...../..?../...../.....'
__inner_border = set([(1, 2), (3, 2), (2, 1), (2, 3)])
def calculate_biodiversity_rating(layout):
layout_string = layout.replace(__SEPARATOR, '')
biodiveristy_rating = 0
for i in range(0, len(layoutString)):
if layoutString[i] == ... |
{
"targets": [
{
"target_name": "aacencoder",
"sources": [ "aacencoder.cc" ],
"include_dirs": [
],
"libraries": [
"-lfaac"
]
}
]
}
| {'targets': [{'target_name': 'aacencoder', 'sources': ['aacencoder.cc'], 'include_dirs': [], 'libraries': ['-lfaac']}]} |
def main():
my_tuple = (4, 4, 3, 2, 5, 7, 8, 8, 8, 7)
evens = tuple([ item for item in my_tuple if item & 1 == 0 ])
odds = tuple([ item for item in my_tuple if item & 1 == 1 ])
print("Evens :", evens);
print("Odds :", odds);
if __name__ == '__main__':
main()
| def main():
my_tuple = (4, 4, 3, 2, 5, 7, 8, 8, 8, 7)
evens = tuple([item for item in my_tuple if item & 1 == 0])
odds = tuple([item for item in my_tuple if item & 1 == 1])
print('Evens :', evens)
print('Odds :', odds)
if __name__ == '__main__':
main() |
# http://codeforces.com/problemset/problem/263/A
matrix = [list(map(int, input().split())) for i in range(5)]
# x = [x for x in matrix if 1 in x][0]
# print(x.index(1))
row_counter = 0
for i in range(5):
if sum(matrix[i]) > 0:
break
row_counter += 1
col_counter = 0
for i in range(5):
if matrix[r... | matrix = [list(map(int, input().split())) for i in range(5)]
row_counter = 0
for i in range(5):
if sum(matrix[i]) > 0:
break
row_counter += 1
col_counter = 0
for i in range(5):
if matrix[row_counter][i] == 1:
break
col_counter += 1
row = abs(row_counter - 2)
col = abs(col_counter - 2)
pr... |
N = int(input())
K = int(input())
M = int(input())
def mul(m1, m2):
m = [[0,0],[0,0]]
for i in range(0,2):
for j in range(0,2):
for k in range(0,2):
m[i][j] = m[i][j]+m1[i][k]*m2[k][j]
m[i][j] = m[i][j] % M
return m
def mpow(m, p):
res = [[... | n = int(input())
k = int(input())
m = int(input())
def mul(m1, m2):
m = [[0, 0], [0, 0]]
for i in range(0, 2):
for j in range(0, 2):
for k in range(0, 2):
m[i][j] = m[i][j] + m1[i][k] * m2[k][j]
m[i][j] = m[i][j] % M
return m
def mpow(m, p):
res = [[1, 0... |
# options
NO = 0
YES = 1
def translate_option(options):
option_list = []
for option in options:
option_list.append((option[0], option[1]))
return option_list
yes_no_options = translate_option([("No", NO), ("Yes", YES)])
| no = 0
yes = 1
def translate_option(options):
option_list = []
for option in options:
option_list.append((option[0], option[1]))
return option_list
yes_no_options = translate_option([('No', NO), ('Yes', YES)]) |
# Default url patters for the engine.
urlpatterns = []
| urlpatterns = [] |
#
# @lc app=leetcode id=15 lang=python3
#
# [15] 3Sum
#
# O(n^2) time | O(n) space
class Solution:
def threeSum(self, array, k=0):
array.sort()
ans = []
for i in range(len(array) - 1):
left = i + 1
right = len(array) - 1
if i > 0 and array[i] == array[... | class Solution:
def three_sum(self, array, k=0):
array.sort()
ans = []
for i in range(len(array) - 1):
left = i + 1
right = len(array) - 1
if i > 0 and array[i] == array[i - 1]:
continue
while left < right:
pote... |
# Copyright (c) 2015-2022 Adam Karpierz
# Licensed under the MIT License
# https://opensource.org/licenses/MIT
__import__("pkg_about").about("jtypes.pyjava")
__copyright__ = f"Copyright (c) 2015-2022 {__author__}" # noqa
| __import__('pkg_about').about('jtypes.pyjava')
__copyright__ = f'Copyright (c) 2015-2022 {__author__}' |
INVALID_VALUE = -1
## @brief Captures an intraday best quote,i.e. the bid/ask prices/sizes
class Quote( object ):
def __init__( self, bid_price, bid_size, ask_price, ask_size ):
self.bid_price = bid_price
self.bid_size = bid_size
self.ask_price = ask_price
self.ask_size = ask_size
... | invalid_value = -1
class Quote(object):
def __init__(self, bid_price, bid_size, ask_price, ask_size):
self.bid_price = bid_price
self.bid_size = bid_size
self.ask_price = ask_price
self.ask_size = ask_size
def initialize(self):
self.bid_price = INVALID_VALUE
se... |
##python program to print a pattern
n=int(input("No of rows\n"))
for i in range(0,n):
for j in range (0,i+1):
print("*", end="")
print()
| n = int(input('No of rows\n'))
for i in range(0, n):
for j in range(0, i + 1):
print('*', end='')
print() |
# DomirScire
A1=[1,4,9]
A2=[9,9,9]
def plus_one(A):
A[-1] += 1
for i in reversed(range(1, len(A))):
if A[i] != 10:
break
A[i]=0
A[i-1] += 1
if A[0] == 10:
A[0]=1
A.append(0)
return A
if __name__ == "__main__":
print(plus_one(A1))
print(plus... | a1 = [1, 4, 9]
a2 = [9, 9, 9]
def plus_one(A):
A[-1] += 1
for i in reversed(range(1, len(A))):
if A[i] != 10:
break
A[i] = 0
A[i - 1] += 1
if A[0] == 10:
A[0] = 1
A.append(0)
return A
if __name__ == '__main__':
print(plus_one(A1))
print(plus_o... |
def main():
a = int(input("first number: "))
b = int(input("second number: "))
c = int(input("third number: "))
if a == b or b == c or c == a:
message = "\ngood bye"
else:
if a > b:
if a > c:
largest_number = a
else:
largest_nu... | def main():
a = int(input('first number: '))
b = int(input('second number: '))
c = int(input('third number: '))
if a == b or b == c or c == a:
message = '\ngood bye'
else:
if a > b:
if a > c:
largest_number = a
else:
largest_num... |
BLACK = 1
WHITE = -1
EMPTY = 0
symbols = {BLACK: 'X', WHITE: 'O', EMPTY: '.'}
| black = 1
white = -1
empty = 0
symbols = {BLACK: 'X', WHITE: 'O', EMPTY: '.'} |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
##
# Copyright 2018 FIWARE Foundation, e.V.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apach... | class Filterdata:
@staticmethod
def filter(data):
result = list(map(lambda x: FilterData.__filter__(x), data))
return result
@staticmethod
def __filter__(data):
result = dict()
result['key'] = data['key']
result['comments'] = list(map(lambda x: FilterData.__get_... |
#!/usr/bin/env python3
# create list
proto = ["ssh", "http", "https"]
# print entire list
print(proto)
# print second list item
print(proto[1])
# line add d, n, s
proto.extend("dns")
print(proto)
| proto = ['ssh', 'http', 'https']
print(proto)
print(proto[1])
proto.extend('dns')
print(proto) |
print("Welcome to Hangman")
name=input("What's your name?")
print("Hi "+name)
print("_ _ _ _ _")
firstletter=input("What's your first letter?")
if firstletter==("a"):
print("a _ _ _ _")
secondletter=input("What's your second letter?")
if firstletter==("a"):
if secondletter==("p"):
print(... | print('Welcome to Hangman')
name = input("What's your name?")
print('Hi ' + name)
print('_ _ _ _ _')
firstletter = input("What's your first letter?")
if firstletter == 'a':
print('a _ _ _ _')
secondletter = input("What's your second letter?")
if firstletter == 'a':
if secondletter == 'p':
print('app... |
#
# PySNMP MIB module DLINK-3100-IpRouter (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DLINK-3100-IpRouter
# Produced by pysmi-0.3.4 at Mon Apr 29 18:33:36 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_size_constraint, constraints_intersection, single_value_constraint, value_range_constraint) ... |
class Solution:
def firstUniqChar(self, s: str) -> int:
# warm-up
# check the xor
count = [0]*26
a = ord('a')
for achar in s:
position = ord(achar) - a
count[position] += 1
for i in range(len(s)):
position = ord(s[i]) - a
... | class Solution:
def first_uniq_char(self, s: str) -> int:
count = [0] * 26
a = ord('a')
for achar in s:
position = ord(achar) - a
count[position] += 1
for i in range(len(s)):
position = ord(s[i]) - a
if count[position] == 1:
... |
def get_amble(idx, lines):
return lines[idx-25:idx]
def get_pair(idx, lines):
amble = get_amble(idx, lines)
for i in amble:
for j in amble:
if i > lines[idx] or j > lines[idx]:
continue
if i == j:
continue
if i + j == lines[idx]:
... | def get_amble(idx, lines):
return lines[idx - 25:idx]
def get_pair(idx, lines):
amble = get_amble(idx, lines)
for i in amble:
for j in amble:
if i > lines[idx] or j > lines[idx]:
continue
if i == j:
continue
if i + j == lines[idx]:... |
arr=[0]*101
input();N=[*map(int,input().split())]
ans=0
for i in N:
if arr[i]==0: arr[i]=1
else: ans+=1
print(ans) | arr = [0] * 101
input()
n = [*map(int, input().split())]
ans = 0
for i in N:
if arr[i] == 0:
arr[i] = 1
else:
ans += 1
print(ans) |
def twos_difference(lst):
slst = sorted(lst)
pairs = []
for i in range(len(slst)):
for j in range(1, len(slst)):
if slst[j] - slst[i] == 2:
pairs.append((slst[i], slst[j]))
return pairs | def twos_difference(lst):
slst = sorted(lst)
pairs = []
for i in range(len(slst)):
for j in range(1, len(slst)):
if slst[j] - slst[i] == 2:
pairs.append((slst[i], slst[j]))
return pairs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.