content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
dp1 = 1
dp2 = 2
dp_step = 0
if n <= 1:
return dp1
if n == 2:
return dp2
while n > 2:
dp_step = dp1 + dp2
dp1 = dp... | class Solution:
def climb_stairs(self, n):
"""
:type n: int
:rtype: int
"""
dp1 = 1
dp2 = 2
dp_step = 0
if n <= 1:
return dp1
if n == 2:
return dp2
while n > 2:
dp_step = dp1 + dp2
dp1 = ... |
numero = int(input('Digite um numero para ver sua tabuada: '))
print('---------------')
print('{} x 1 = {}'.format(numero, numero * 1))
print('{} x 2 = {}'.format(numero, numero * 2))
print('{} x 3 = {}'.format(numero, numero * 3))
print('{} x 4 = {}'.format(numero, numero * 4))
print('{} x 5 = {}'.format(numero,... | numero = int(input('Digite um numero para ver sua tabuada: '))
print('---------------')
print('{} x 1 = {}'.format(numero, numero * 1))
print('{} x 2 = {}'.format(numero, numero * 2))
print('{} x 3 = {}'.format(numero, numero * 3))
print('{} x 4 = {}'.format(numero, numero * 4))
print('{} x 5 = {}'.format(numero, ... |
'''
We want to make a row of bricks that is goal inches long. We have a number of
small bricks (1 inch each) and big bricks (5 inches each). Return True if it
is possible to make the goal by choosing from the given bricks. This is a
little harder than it looks and can be done without any loops.
'''
def make_bricks(sma... | """
We want to make a row of bricks that is goal inches long. We have a number of
small bricks (1 inch each) and big bricks (5 inches each). Return True if it
is possible to make the goal by choosing from the given bricks. This is a
little harder than it looks and can be done without any loops.
"""
def make_bricks(sma... |
def validacao_de_nota():
notas_validas = soma = 0
while True:
if notas_validas == 2:
break
nota = float(input())
if 0 <= nota <= 10:
soma += nota
notas_validas += 1
else:
print('nota invalida')
media = soma / 2
print(f'media... | def validacao_de_nota():
notas_validas = soma = 0
while True:
if notas_validas == 2:
break
nota = float(input())
if 0 <= nota <= 10:
soma += nota
notas_validas += 1
else:
print('nota invalida')
media = soma / 2
print(f'media... |
# -*- coding: utf-8 -*-
def main(names):
def get_format(is_angy):
return "{0}.My name is {1}" if is_angy else "{0}.{1} is my classmate"
for i, n in enumerate(names):
print(get_format(n == "Angy").format(i, n))
if __name__ == "__main__":
names = ("Bill", "Anne", "Angy", "Cony", "Daniel", ... | def main(names):
def get_format(is_angy):
return '{0}.My name is {1}' if is_angy else '{0}.{1} is my classmate'
for (i, n) in enumerate(names):
print(get_format(n == 'Angy').format(i, n))
if __name__ == '__main__':
names = ('Bill', 'Anne', 'Angy', 'Cony', 'Daniel', 'Occhan')
main(names) |
# # 6. write a function that takes an integer n and prints a square of n*n #
def quadrat(n):
sq=n*n
print(sq)
return sq
quadrat(10) | def quadrat(n):
sq = n * n
print(sq)
return sq
quadrat(10) |
'''test for having the file checked .
if we request the channels from the file and there are no channels
and when you call the channels from file .. you specify which file to call from .(which list)
if the stream is already there then you dont want it to add the stream
and notify the user that it already exists.... | """test for having the file checked .
if we request the channels from the file and there are no channels
and when you call the channels from file .. you specify which file to call from .(which list)
if the stream is already there then you dont want it to add the stream
and notify the user that it already exists.
... |
"""Errors used in pydexcom."""
class DexcomError(Exception):
"""Base class for all Dexcom errors."""
pass
class AccountError(DexcomError):
"""Errors involving Dexcom Share API credentials."""
pass
class SessionError(DexcomError):
"""Errors involving Dexcom Share API session."""
pass
c... | """Errors used in pydexcom."""
class Dexcomerror(Exception):
"""Base class for all Dexcom errors."""
pass
class Accounterror(DexcomError):
"""Errors involving Dexcom Share API credentials."""
pass
class Sessionerror(DexcomError):
"""Errors involving Dexcom Share API session."""
pass
class Ar... |
with open("day2.txt", "rt") as file:
data = file.readlines()
valid = 0
valid2 = 0
for entry in data:
parts = entry.split(' ')
limits = parts[0].split('-')
letter = parts[1].split(':')[0]
password = parts[2]
count = 0
for ch in password:
if ch ... | with open('day2.txt', 'rt') as file:
data = file.readlines()
valid = 0
valid2 = 0
for entry in data:
parts = entry.split(' ')
limits = parts[0].split('-')
letter = parts[1].split(':')[0]
password = parts[2]
count = 0
for ch in password:
if ch =... |
# SPDX-License-Identifier: BSD-2-Clause
"""osdk-manager exceptions.
Manage osdk and opm binary installation, and help to scaffold, release, and
version Operator SDK-based Kubernetes operators.
This file contains the custom exceptions utilized for the osdk_manager.
"""
class ContainerRuntimeException(Exception):
... | """osdk-manager exceptions.
Manage osdk and opm binary installation, and help to scaffold, release, and
version Operator SDK-based Kubernetes operators.
This file contains the custom exceptions utilized for the osdk_manager.
"""
class Containerruntimeexception(Exception):
"""Unable to identify a container runtim... |
TRAINING_FILE_ORIG = '../input/adult.csv'
TRAINING_FILE = '../input/adult_folds.csv'
| training_file_orig = '../input/adult.csv'
training_file = '../input/adult_folds.csv' |
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit script for devil.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for
details on the presubmit API built into depot_... | """Presubmit script for devil.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for
details on the presubmit API built into depot_tools.
"""
def __run_pylint(input_api, output_api):
return input_api.RunTests(input_api.canned_checks.RunPylint(input_api, output_api, pylintrc='pylintrc'))
... |
# -*- coding: utf-8 -*-
"""Top-level package for filter_classified_reads."""
__author__ = """Peter Kruczkiewicz"""
__email__ = 'peter.kruczkiewicz@gmail.com'
__version__ = '0.2.1'
| """Top-level package for filter_classified_reads."""
__author__ = 'Peter Kruczkiewicz'
__email__ = 'peter.kruczkiewicz@gmail.com'
__version__ = '0.2.1' |
"""Styles for the frontend."""
async def style():
"""Return styles."""
return """
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="... | """Styles for the frontend."""
async def style():
"""Return styles."""
return '\n <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">\n <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="sha384-o... |
open_brackets = ["[","{","("]
close_brackets = ["]","}",")"]
def validate_brackets(string):
stack = []
for i in string:
if i in open_brackets:
stack.append(i)
elif i in close_brackets:
pos = close_brackets.index(i)
if ((len(stack) > 0) and
(ope... | open_brackets = ['[', '{', '(']
close_brackets = [']', '}', ')']
def validate_brackets(string):
stack = []
for i in string:
if i in open_brackets:
stack.append(i)
elif i in close_brackets:
pos = close_brackets.index(i)
if len(stack) > 0 and open_brackets[pos]... |
def my_name(name):
# import ipdb;ipdb.set_trace()
return f"My name is: {name}"
if __name__ == "__main__":
my_name("bob")
| def my_name(name):
return f'My name is: {name}'
if __name__ == '__main__':
my_name('bob') |
'''
Created on 25 apr 2019
@author: Matteo
'''
CD_RETURN_IMMEDIATELY = 1
CD_ADD_AND_CONTINUE_WAITING = 2
CD_CONTINUE_WAITING = 0
CD_ABORT_AND_RETRY = 3
| """
Created on 25 apr 2019
@author: Matteo
"""
cd_return_immediately = 1
cd_add_and_continue_waiting = 2
cd_continue_waiting = 0
cd_abort_and_retry = 3 |
load("@fbcode_macros//build_defs/lib:cpp_common.bzl", "cpp_common")
load("@fbcode_macros//build_defs/lib:src_and_dep_helpers.bzl", "src_and_dep_helpers")
load("@fbcode_macros//build_defs/lib:string_macros.bzl", "string_macros")
load("@fbcode_macros//build_defs/lib:target_utils.bzl", "target_utils")
load("@fbcode_macros... | load('@fbcode_macros//build_defs/lib:cpp_common.bzl', 'cpp_common')
load('@fbcode_macros//build_defs/lib:src_and_dep_helpers.bzl', 'src_and_dep_helpers')
load('@fbcode_macros//build_defs/lib:string_macros.bzl', 'string_macros')
load('@fbcode_macros//build_defs/lib:target_utils.bzl', 'target_utils')
load('@fbcode_macros... |
##
# File: PdbxChemCompConstants.py
# Date: 21-Feb-2012 John Westbrook
#
# Update:
# 21-Feb-2012 jdw add to chemcomputil repository
# 1-Feb-2017 jdw unified with chem_ref_data
#
##
"""
A collection of chemical data and information.
"""
__docformat__ = "restructuredtext en"
__author__ = "John Westbrook"
__email__ =... | """
A collection of chemical data and information.
"""
__docformat__ = 'restructuredtext en'
__author__ = 'John Westbrook'
__email__ = 'john.westbrook@rcsb.org'
__license__ = 'Apache 2.0'
class Pdbxchemcompconstants(object):
periodic_table = ['H', 'HE', 'LI', 'BE', 'B', 'C', 'N', 'O', 'F', 'NE', 'NA', 'MG', 'AL',... |
class AverageMeter(object):
"""Stores the summation and counts the number to compute the average value.
"""
def __init__(self):
self._sum = 0
self._count = 0
@property
def avg(self):
return self._sum / self._count if self._count != 0 else 0
@property
def count(self)... | class Averagemeter(object):
"""Stores the summation and counts the number to compute the average value.
"""
def __init__(self):
self._sum = 0
self._count = 0
@property
def avg(self):
return self._sum / self._count if self._count != 0 else 0
@property
def count(self... |
r'''
.. _snippets-cli-tagging:
Command Line Interface: Tagging
===============================
This is the tested source code for the snippets used in :ref:`cli-tagging`. The
config file we're using in this example can be downloaded
:download:`here <../../examples/snippets/resources/datafs_mongo.yml>`.
Example 1
----... | """
.. _snippets-cli-tagging:
Command Line Interface: Tagging
===============================
This is the tested source code for the snippets used in :ref:`cli-tagging`. The
config file we're using in this example can be downloaded
:download:`here <../../examples/snippets/resources/datafs_mongo.yml>`.
Example 1
-----... |
class Funcionario:
def __init__(self, nome, salario):
self.nome=nome
self.salario=float(salario)
def aum_salario(self, pct):
self.salario += (self.salario*pct/100)
def get_salario(self):
return self.salario | class Funcionario:
def __init__(self, nome, salario):
self.nome = nome
self.salario = float(salario)
def aum_salario(self, pct):
self.salario += self.salario * pct / 100
def get_salario(self):
return self.salario |
class Node(object):
def __init__(self, val=None, children=None):
self.val = val
self.children = children
| class Node(object):
def __init__(self, val=None, children=None):
self.val = val
self.children = children |
num = int(input('digite um numero:'))
if num / 1 and num/ num:
print('esse numero primo')
else:
print('esse numerp nap e primo') | num = int(input('digite um numero:'))
if num / 1 and num / num:
print('esse numero primo')
else:
print('esse numerp nap e primo') |
'''
https://www.hackerrank.com/challenges/python-loops/problem
Task
====
The provided code stub reads and integer, , from STDIN. For all non-negative integers , print .
Example
=======
The list of non-negative integers that are less than is . Print the square of each number on a sep... | """
https://www.hackerrank.com/challenges/python-loops/problem
Task
====
The provided code stub reads and integer, , from STDIN. For all non-negative integers , print .
Example
=======
The list of non-negative integers that are less than is . Print the square of each number on a sep... |
# Time: O(m*n), m = len(word1), n = len(word2)
# Space: O(m*n)
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
"""
3 options for each char
if chars match don't need to do anything
subprobem(i,j) = subproblem(i-1,j-1)
else:
subproblem(i,j) = 1 + ... | class Solution:
def min_distance(self, word1: str, word2: str) -> int:
"""
3 options for each char
if chars match don't need to do anything
subprobem(i,j) = subproblem(i-1,j-1)
else:
subproblem(i,j) = 1 + min of(1,2,3)
1.Insertion: subproblem(word1[i], word2[... |
'''
Created on 24.07.2019
@author: LK
'''
# TODO: Inheritance of tmcl interface
class Landungsbruecke(object):
GP_VitalSignsErrorMask = 1
GP_DriversEnable = 2
GP_DebugMode = 3
GP_BoardAssignment = 4
GP_HWID = 5
GP_PinState = 6
| """
Created on 24.07.2019
@author: LK
"""
class Landungsbruecke(object):
gp__vital_signs_error_mask = 1
gp__drivers_enable = 2
gp__debug_mode = 3
gp__board_assignment = 4
gp_hwid = 5
gp__pin_state = 6 |
def strategy(history, memory):
if history.shape[1] % 3 == 2: # CC
return 0, None # D
else:
return 1, None # C | def strategy(history, memory):
if history.shape[1] % 3 == 2:
return (0, None)
else:
return (1, None) |
class PixivException(Exception):
pass
class DownloadException(PixivException):
pass
class APIException(PixivException):
pass
class LoginPasswordError(APIException):
pass
class LoginTokenError(APIException):
pass
| class Pixivexception(Exception):
pass
class Downloadexception(PixivException):
pass
class Apiexception(PixivException):
pass
class Loginpassworderror(APIException):
pass
class Logintokenerror(APIException):
pass |
def createMessageForArduino(flags, device_id, datasize, data):
# prepare data, datasize depends whether we are working on
# strings or not and therefor calculate it again
byteData, datasize = getBytesForData(data)
message = b'\xff'
message += bytes([flags])
message += bytes([int(device_id)])... | def create_message_for_arduino(flags, device_id, datasize, data):
(byte_data, datasize) = get_bytes_for_data(data)
message = b'\xff'
message += bytes([flags])
message += bytes([int(device_id)])
message += bytes([datasize])
if datasize > 0:
message += byteData
message += b'\xfe'
p... |
# Copyright 2020 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file acc... | class Sdkerror(Exception):
"""Base Error for Amazon Transcribe Streaming SDK"""
class Httpexception(SDKError):
"""Base error for HTTP related exceptions"""
class Serviceexception(SDKError):
"""Errors returned by the service"""
class Unknownserviceexception(ServiceException):
def __init__(self, statu... |
# -*- coding: utf-8 -*-
class ChainingHash(object):
""" Hash table implementation which resolves collisions by using chaining.
Attributes:
num_buckets: int, how large should the internal array be to store data.
data: list, a storage for hash data.
"""
def __init__(self, num_buckets):... | class Chaininghash(object):
""" Hash table implementation which resolves collisions by using chaining.
Attributes:
num_buckets: int, how large should the internal array be to store data.
data: list, a storage for hash data.
"""
def __init__(self, num_buckets):
""" Constructs h... |
def max_sublist_sum(arr):
max_ending_here = 0
max_so_far = 0
for x in arr:
max_ending_here = max_ending_here + x
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
"""
Max Sublist Sum
max-sublist-sum
Efficient equivalent to max(sum(arr[i:j]) for 0 <= i <= j <= len(arr)... | def max_sublist_sum(arr):
max_ending_here = 0
max_so_far = 0
for x in arr:
max_ending_here = max_ending_here + x
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
'\nMax Sublist Sum\nmax-sublist-sum\n\nEfficient equivalent to max(sum(arr[i:j]) for 0 <= i <= j <= len(arr))\n... |
# List is python's version of array, zero-based indexing
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
print(months[0])
print(months[2])
print(months[-1])
list_of_random_things = [1, 3.4, 'a string', True]
# watch for indexing error... | months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
print(months[0])
print(months[2])
print(months[-1])
list_of_random_things = [1, 3.4, 'a string', True]
list_of_random_things[len(list_of_random_things) - 1]
print(list_of_random_things[len... |
# --- Day 11: Seating System ---
# Your plane lands with plenty of time to spare. The final leg of your journey is a ferry that goes directly to the tropical island where you can finally start your vacation. As you reach the waiting area to board the ferry, you realize you're so early, nobody else has even arrived yet!... | def file_input():
f = open(inputFile, 'r')
with open(inputFile) as f:
read_data = f.read().split('\n')
f.close()
return read_data
def split_seats(data):
split_data = []
for row in data:
row_data = [seat for seat in row]
splitData.append(rowData)
return splitData
def... |
# WiFi credentials
wifi_ssid = "YourSSID"
wifi_password = "YourPassword"
# Ubidots credentials
ubidots_token = "YourToken"
| wifi_ssid = 'YourSSID'
wifi_password = 'YourPassword'
ubidots_token = 'YourToken' |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 28 20:38:28 2020
@author: Chetan Patil
"""
# server properties
KAFKA_SERVERS='server1:9092,server2:9092,server3:9092'
KAFKA_SERVERS_DEV='localhost:9092'
# transaction message properties
TRANSACTION_MESSAGE_MERCHANT_ID='merchant_id'
TRANSACTION_MES... | """
Created on Sun Jun 28 20:38:28 2020
@author: Chetan Patil
"""
kafka_servers = 'server1:9092,server2:9092,server3:9092'
kafka_servers_dev = 'localhost:9092'
transaction_message_merchant_id = 'merchant_id'
transaction_message_user_id = 'user_id'
transaction_message_transaction_timestamp = 'transaction_ts'
transactio... |
number_one = int(input())
number_two = int(input())
number_three = int(input())
for one in range(2, number_one + 1, 2):
for two in range(2, number_two + 1):
for three in range(2, number_three + 1, 2):
if two == 2 or two == 3 or two == 5 or two == 7:
print(f"{one} {two} {three}") | number_one = int(input())
number_two = int(input())
number_three = int(input())
for one in range(2, number_one + 1, 2):
for two in range(2, number_two + 1):
for three in range(2, number_three + 1, 2):
if two == 2 or two == 3 or two == 5 or (two == 7):
print(f'{one} {two} {three}'... |
"""
This program shows how changing an outside variable from within a function
makes another variable!
In this program, print_something has its own variable called z. It can no longer
access the outer variable called z.
"""
z = 6.5
def print_something():
z = "hi"
print(z * 3)
print_something()... | """
This program shows how changing an outside variable from within a function
makes another variable!
In this program, print_something has its own variable called z. It can no longer
access the outer variable called z.
"""
z = 6.5
def print_something():
z = 'hi'
print(z * 3)
print_something()
print(z * 3) |
#! /usr/bin/python
HOME_PATH = './'
CACHE_PATH = '/var/cache/obmc/'
FLASH_DOWNLOAD_PATH = "/tmp"
GPIO_BASE = 320
SYSTEM_NAME = "Garrison"
## System states
## state can change to next state in 2 ways:
## - a process emits a GotoSystemState signal with state name to goto
## - objects specified in EXIT_STATE_DEPE... | home_path = './'
cache_path = '/var/cache/obmc/'
flash_download_path = '/tmp'
gpio_base = 320
system_name = 'Garrison'
system_states = ['BASE_APPS', 'BMC_STARTING', 'BMC_READY', 'HOST_POWERING_ON', 'HOST_POWERED_ON', 'HOST_BOOTING', 'HOST_BOOTED', 'HOST_POWERED_OFF']
exit_state_depend = {'BASE_APPS': {'/org/openbmc/sen... |
def fahrenheit_to_celsius(temp_f):
"""Convert temperature in Fahrenheit to Celsius
"""
temp_c = (temp_f-32)*(5.0/9.0)
return temp_c
| def fahrenheit_to_celsius(temp_f):
"""Convert temperature in Fahrenheit to Celsius
"""
temp_c = (temp_f - 32) * (5.0 / 9.0)
return temp_c |
class Table(object):
"""docstring for Table"""
def __init__(self, arg):
self.arg = arg
| class Table(object):
"""docstring for Table"""
def __init__(self, arg):
self.arg = arg |
A,B,C,D = map(float,input().split())
A = (A*2+B*3+C*4+D*1)/10
print(f'Media: {A:.1f}')
if A>=7.0:
print("Aluno aprovado.")
elif A<5.0:
print("Aluno reprovado.")
elif A>=5.0 and A<7.0:
print("Aluno em exame.")
N = float(input())
print(f'Nota do exame: {N:.1f}')
N = (A+N)/2
if N>=5.0:
... | (a, b, c, d) = map(float, input().split())
a = (A * 2 + B * 3 + C * 4 + D * 1) / 10
print(f'Media: {A:.1f}')
if A >= 7.0:
print('Aluno aprovado.')
elif A < 5.0:
print('Aluno reprovado.')
elif A >= 5.0 and A < 7.0:
print('Aluno em exame.')
n = float(input())
print(f'Nota do exame: {N:.1f}')
n = (... |
# this file contains the ascii art for our equipment
# HELMET
#
#
# SHIELD ARMOR WEAPON
#
#
# OTHER ITEMS ......
equipment = {'sword':[ ' /\ ',
' || ',
' || ',
' || ',
... | equipment = {'sword': [' /\\ ', ' || ', ' || ', ' || ', ' || ', ' || ', ' || ', ' || ', ' || ', ' || ', ' || ', ' || ', ' || ', 'o==o', ' II ', ' II ', ' II ', ' ** '], 'shield': [' | `-._/\\_.-` |', ' | || |', ' | ___o()o___ |', ' | __((<>))__ |', ' | ___o()o___ |', ' | \\/ |', ' \\ o\\/o /', ' ... |
'''
Given a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right.
Note that elements beyond the length of the original array are not written.
Do the above modifications to the input array in place, do not return anything from your function.
Example 1:... | """
Given a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right.
Note that elements beyond the length of the original array are not written.
Do the above modifications to the input array in place, do not return anything from your function.
Example 1:... |
linha1 = input()
linha2 = input()
linha3 = input()
if(linha1 == 'vertebrado'):
if(linha2 == 'ave'):
if(linha3 == 'carnivoro'):
print('aguia')
else:
print('pomba')
else:
if(linha3 == 'onivoro'):
print('homem')
else:
print('vaca')
el... | linha1 = input()
linha2 = input()
linha3 = input()
if linha1 == 'vertebrado':
if linha2 == 'ave':
if linha3 == 'carnivoro':
print('aguia')
else:
print('pomba')
elif linha3 == 'onivoro':
print('homem')
else:
print('vaca')
elif linha2 == 'inseto':
if... |
# 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 isUnivalTree(self, root: TreeNode) -> bool:
if root:
self.k=root.val
sel... | class Solution:
def is_unival_tree(self, root: TreeNode) -> bool:
if root:
self.k = root.val
self.x = []
self.x.append(root.val)
else:
return True
def abc(root):
if root:
if root.left:
self.x.ap... |
def most_cash_prep(one_slot_size, start_p, wor_p, gap, lot_enhance):
"""
:param one_slot_size:
:param start_p:
:param wor_p:
:param gap: in percent, 0.05 means gap is 5% in strategy
:param lot_enhance: in percent, 0.3 means 1.3 in strategy
:return:
"""
grids = round(((start_p - wor_p... | def most_cash_prep(one_slot_size, start_p, wor_p, gap, lot_enhance):
"""
:param one_slot_size:
:param start_p:
:param wor_p:
:param gap: in percent, 0.05 means gap is 5% in strategy
:param lot_enhance: in percent, 0.3 means 1.3 in strategy
:return:
"""
grids = round((start_p - wor_p)... |
T = int(input())
for _ in range(T):
M, H = map(int, input().split())
B = M//H**2
if B<=18:
print(1)
elif B in range(19, 25):
print(2)
elif B in range(25, 30):
print(3)
else:
print(4) | t = int(input())
for _ in range(T):
(m, h) = map(int, input().split())
b = M // H ** 2
if B <= 18:
print(1)
elif B in range(19, 25):
print(2)
elif B in range(25, 30):
print(3)
else:
print(4) |
'''
URL: https://leetcode.com/problems/regular-expression-matching/description/
Time complexity: O(n*m)
Space complexity: O(n*m)
'''
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
is_match = [[False for j in range(len(... | """
URL: https://leetcode.com/problems/regular-expression-matching/description/
Time complexity: O(n*m)
Space complexity: O(n*m)
"""
class Solution(object):
def is_match(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
is_match = [[False for j in range(le... |
ls = open('logs.txt').readlines()
for line in ls:
g = line.strip()
g = "/d/c186/FarnettoApps/" + g
print("echo loading %s"%(g))
print("java -Dserverid=farnetto -cp $CP farnetto.log4jconverter.Loader file:/%s 2>&1 | grep ERROR"%(g))
| ls = open('logs.txt').readlines()
for line in ls:
g = line.strip()
g = '/d/c186/FarnettoApps/' + g
print('echo loading %s' % g)
print('java -Dserverid=farnetto -cp $CP farnetto.log4jconverter.Loader file:/%s 2>&1 | grep ERROR' % g) |
#Your function definition goes here
def valid_date(date_str):
if len(date_str) == 8:
for ch in date_str:
if ch == "/":
return False
if ch.isalpha():
return False
date_str.split(".")
day = int(date_str[:2])
month = int(date_str[3... | def valid_date(date_str):
if len(date_str) == 8:
for ch in date_str:
if ch == '/':
return False
if ch.isalpha():
return False
date_str.split('.')
day = int(date_str[:2])
month = int(date_str[3:5])
year = int(date_str[-2:... |
#Created with the Terminal ASCII Paint app by Michele Morelli - https://github.com/MicheleMorelli
def draw_house():
print(" "*64+"\n"+" "*64+"\n"+" "*5+"_"*33+" "*26+"\n"+" "*4+"|"+"/"*4+"|"+"#"*28+" "*26+"\n"+" "*4+"|"+"/"*4+"|"+"#"*28+" "*26+"\n"+" "*4+"|"+"/"*4+"|"+"#"*2+" "*2+"|"+"/"+"|"+"#"*2+" "*3+"|"+"/"+"|... | def draw_house():
print(' ' * 64 + '\n' + ' ' * 64 + '\n' + ' ' * 5 + '_' * 33 + ' ' * 26 + '\n' + ' ' * 4 + '|' + '/' * 4 + '|' + '#' * 28 + ' ' * 26 + '\n' + ' ' * 4 + '|' + '/' * 4 + '|' + '#' * 28 + ' ' * 26 + '\n' + ' ' * 4 + '|' + '/' * 4 + '|' + '#' * 2 + ' ' * 2 + '|' + '/' + '|' + '#' * 2 + ' ' * 3 + '|' +... |
"""
observer pattern in python
"""
class Subject:
"""
# Represents what is being 'observed'
"""
def __init__(self):
self._observers = (
[]
) # This where references to all the observers are being kept
# Note that this is a one-to-many relationship: there will be o... | """
observer pattern in python
"""
class Subject:
"""
# Represents what is being 'observed'
"""
def __init__(self):
self._observers = []
def attach(self, observer):
"""
# If the observer is not already in the observers list
# append the observer to the list
... |
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def set_width(self, width):
self.width = width
def set_height(self, height):
self.height = height
def get_area(self):
return self.height * self.width
def get_perim... | class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def set_width(self, width):
self.width = width
def set_height(self, height):
self.height = height
def get_area(self):
return self.height * self.width
def get_perim... |
def details():
name = input("What is your name? ")
age = input("What is your age? ")
username = input("What is your Reddit username? ")
with open("python_get_details_details.txt", "a+", encoding="utf-8") as file:
file.write(name + " " + age + " " + username + "\n")
print("Your name is ... | def details():
name = input('What is your name? ')
age = input('What is your age? ')
username = input('What is your Reddit username? ')
with open('python_get_details_details.txt', 'a+', encoding='utf-8') as file:
file.write(name + ' ' + age + ' ' + username + '\n')
print('Your name is ' + na... |
# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations
#########################################################################
## This is a sample controller
## - index is the default action of any application
## - user is required for authentication and authorization... | @auth.requires_login()
def index():
response.flash = t('Welcome!')
notes = [lambda project: a('Notes', _class='btn', _href=url('default', 'note', args=[project.id]))]
grid = SQLFORM.grid(db.project, create=False, links=notes, fields=[db.project.name, db.project.employee_name, db.project.company_name, db.pro... |
"""
rapidapi.livescore
~~~~~~~~~~~~~~~~~~
RapidAPI LiveScore API modules.
@author: z33k
""" | """
rapidapi.livescore
~~~~~~~~~~~~~~~~~~
RapidAPI LiveScore API modules.
@author: z33k
""" |
def solve(n):
notebook = {}
for _ in range(n):
student, grade = input().split(' ')
if student not in notebook:
notebook[student] = []
notebook[student] += [float(grade)]
for st, gr in notebook.items():
print(f"{st} ->", end=' ')
[print(f"{x:.2f}",... | def solve(n):
notebook = {}
for _ in range(n):
(student, grade) = input().split(' ')
if student not in notebook:
notebook[student] = []
notebook[student] += [float(grade)]
for (st, gr) in notebook.items():
print(f'{st} ->', end=' ')
[print(f'{x:.2f}', end=... |
"""
If the function can access the variables in the global scope.
So why do we need arguments? Explain with example.
"""
def greet(name):
return f'Hello, {name} Good morning!'
name1 = "Raj Nath Patel"
name2 = "Raj Kumar"
return_value = greet(name1) # Call function with return value
print(return_value)
return_v... | """
If the function can access the variables in the global scope.
So why do we need arguments? Explain with example.
"""
def greet(name):
return f'Hello, {name} Good morning!'
name1 = 'Raj Nath Patel'
name2 = 'Raj Kumar'
return_value = greet(name1)
print(return_value)
return_value = greet(name2)
print(return_value... |
class Element():
def __init__(self, identifier, name, symbol):
self.identifier = identifier
self.name = name
self.symbol = symbol
self.metabolites = []
def add_compound(self, compound):
if compound not in self.metabolites:
self.metabolites.append(compound)
... | class Element:
def __init__(self, identifier, name, symbol):
self.identifier = identifier
self.name = name
self.symbol = symbol
self.metabolites = []
def add_compound(self, compound):
if compound not in self.metabolites:
self.metabolites.append(compound)
... |
#Name Cases.
Personal_Name = "joey Tribionny"
print("Person's name in lower case: " + Personal_Name.lower())
print("Person's name in upper case: " + Personal_Name.upper())
print("Person's name in title case: " + Personal_Name.title())
| personal__name = 'joey Tribionny'
print("Person's name in lower case: " + Personal_Name.lower())
print("Person's name in upper case: " + Personal_Name.upper())
print("Person's name in title case: " + Personal_Name.title()) |
# 1) Function that takes a string as a paratmeter and returns true if str contains at least 3 g false otherwise.
# def threeg(stri):
# gsum = 0
# for letter in stri.upper():
# if letter == 'G':
# gsum += 1
# while gsum < 3:
# return False
# print(threeg('ggg')
def g_count(any_... | def g_count(any_str):
gnum = 0
for char in any_str.upper():
if char == 'G':
gnum += 1
if gnum >= 3:
return True
else:
return False
print(g_count('attggg')) |
# import pytest
class TestFormatHandler:
def test_read(self): # synced
assert True
def test_write(self): # synced
assert True
def test_append(self): # synced
assert True
def test_read_help(self): # synced
assert True
def test_write_help(self): # synced
... | class Testformathandler:
def test_read(self):
assert True
def test_write(self):
assert True
def test_append(self):
assert True
def test_read_help(self):
assert True
def test_write_help(self):
assert True
def test__ensure_format(self):
assert ... |
num = []
soma = 0
for i in range(11):
num.append(int(input()))
n = len(num)
for i in num:
soma = soma + i
media = soma / n
print(media)
| num = []
soma = 0
for i in range(11):
num.append(int(input()))
n = len(num)
for i in num:
soma = soma + i
media = soma / n
print(media) |
load("@bazel_skylib//lib:paths.bzl", "paths")
load("@bazel_tools//tools/build_defs/pkg:pkg.bzl", "pkg_tar")
def _pre_render_script_ops_impl(ctx):
output_filename = "{}.yaml".format(ctx.attr.name)
output_yaml = ctx.actions.declare_file(output_filename)
outputs = [output_yaml]
ctx.actions.run(
in... | load('@bazel_skylib//lib:paths.bzl', 'paths')
load('@bazel_tools//tools/build_defs/pkg:pkg.bzl', 'pkg_tar')
def _pre_render_script_ops_impl(ctx):
output_filename = '{}.yaml'.format(ctx.attr.name)
output_yaml = ctx.actions.declare_file(output_filename)
outputs = [output_yaml]
ctx.actions.run(inputs=[ctx... |
# # # # # a = 215
# # # # a = int(input("Input a"))
# # # a = 9000
# # # a = 3
# # #
# if True: # after : is the code block, must be indented
# print("True")
# print("This always runs because if statement is True")
# print("Still working in if block")
# # # if block has ended
# print("This runs no matter w... | a = 200
a = -95
a = 10
a = -100
if 2 < 3 < 8 < a:
print(f'2 < 3 < 8 < {a} is it a True statement? ', 2 < 3 < 8 < a)
else:
print(f'2 < 3 < 8 < {a} is it a True statement?', 2 < 3 < 8 < a) |
def test1():
l = []
for i in range(1000):
l = l + [i]
def test2():
l = []
for i in range(1000):
l.append(i)
def test3():
l = [i for i in range(1000)]
def test4():
l = list(range(1000))
| def test1():
l = []
for i in range(1000):
l = l + [i]
def test2():
l = []
for i in range(1000):
l.append(i)
def test3():
l = [i for i in range(1000)]
def test4():
l = list(range(1000)) |
print("Listing Primes")
prime_list = []
i = 0
while i < 10000:
if i % 1000 == 0:
print("Processed %d primes" % i)
i += 1
prime = True
for n in range(i):
if n != 0 and n!= 1 and n!= i:
if i % n == 0: prime = False
if prime == True:
prime_list.append(i)
for i in r... | print('Listing Primes')
prime_list = []
i = 0
while i < 10000:
if i % 1000 == 0:
print('Processed %d primes' % i)
i += 1
prime = True
for n in range(i):
if n != 0 and n != 1 and (n != i):
if i % n == 0:
prime = False
if prime == True:
prime_list.ap... |
class Verb(object):
def __init__(self, verb, subject):
self.verb = verb
self.subject = subject
self.value = ""
def format(self, context):
subject = self.subject(context).value
if subject.player:
self.value = self.verb
else:
self.value = th... | class Verb(object):
def __init__(self, verb, subject):
self.verb = verb
self.subject = subject
self.value = ''
def format(self, context):
subject = self.subject(context).value
if subject.player:
self.value = self.verb
else:
self.value = t... |
""" Module with functionalities for blocking based on a dictionary of records,
where a blocking function must return a dictionary with block identifiers
as keys and values being sets or lists of record identifiers in that block.
"""
# =======================================================================... | """ Module with functionalities for blocking based on a dictionary of records,
where a blocking function must return a dictionary with block identifiers
as keys and values being sets or lists of record identifiers in that block.
"""
def no_blocking(rec_dict):
"""A function which does no blocking but simply... |
def is_valid(row, col, size):
return 0 <= row < size and 0 <= col < size
# returns True or False
def explode(row, col, size, matrix_in):
bomb = matrix[row][col]
for r in range(row - 1, row + 2):
for c in range(col - 1, col + 2):
if is_valid(r, c, size) and matrix_in[r][c] > 0:
... | def is_valid(row, col, size):
return 0 <= row < size and 0 <= col < size
def explode(row, col, size, matrix_in):
bomb = matrix[row][col]
for r in range(row - 1, row + 2):
for c in range(col - 1, col + 2):
if is_valid(r, c, size) and matrix_in[r][c] > 0:
matrix[r][c] -= b... |
# -*- coding: utf-8 -*-
""" Train models module. """
#from modules.models.pytorch.alex_net import AlexNet
#__all__ = ['AlexNet']
| """ Train models module. """ |
test_cases = int(input())
for i in range(test_cases):
text = input()
new_text = ''
for l in text:
if l.isalpha():
new_text += chr(ord(l) + 3)
else:
new_text += l
new_text = new_text[::-1]
half = int((len(new_text) / 2))
first_part = new_text[0:half]
... | test_cases = int(input())
for i in range(test_cases):
text = input()
new_text = ''
for l in text:
if l.isalpha():
new_text += chr(ord(l) + 3)
else:
new_text += l
new_text = new_text[::-1]
half = int(len(new_text) / 2)
first_part = new_text[0:half]
seco... |
# Ported from python 3.7 contextlib.py
class nullcontext(object):
"""Context manager that does no additional processing.
Used as a stand-in for a normal context manager, when a particular
block of code is only sometimes used with a normal context manager:
cm = optional_cm if condition else nullcontext()... | class Nullcontext(object):
"""Context manager that does no additional processing.
Used as a stand-in for a normal context manager, when a particular
block of code is only sometimes used with a normal context manager:
cm = optional_cm if condition else nullcontext()
with cm:
# Perform operati... |
name = "signalfx-azure-function-python"
version = "1.0.1"
user_agent = f"signalfx_azure_function/{version}"
| name = 'signalfx-azure-function-python'
version = '1.0.1'
user_agent = f'signalfx_azure_function/{version}' |
# Implement the singleton pattern with a twist. First, instead of storing one
# instance, store two instances. And in every even call of getInstance(), return
# the first instance and in every odd call of getInstance(), return the second
# instance.
class Singleton(type):
_instance = []
odd = True
... | class Singleton(type):
_instance = []
odd = True
def __call__(cls, *args, **kwargs):
if len(cls._instance) < 2:
instance = super(Singleton, cls).__call__(*args, **kwargs)
cls._instance.append(instance)
cls.odd = True if not cls.odd else False
return cls._inst... |
# Messages issued by the bot to the user
REMOVAL_MESSAGE = """
The message by {username} was deleted as it violated the channel's moral guidelines.
Multiple such violations may lead to a temporary or even a permanent ban
"""
PERSONAL_MESSAGE_AFTER_REMOVAL = """
We deleted your message because it was found to be toxic... | removal_message = "\nThe message by {username} was deleted as it violated the channel's moral guidelines.\nMultiple such violations may lead to a temporary or even a permanent ban\n"
personal_message_after_removal = '\nWe deleted your message because it was found to be toxic. Please refrain from using such messages in ... |
def _get_ratio(ratio):
if isinstance(ratio, str):
if ':' in ratio:
r_w, r_h = ratio.split(':')
try:
ratio = float(r_w) / float(r_h)
except:
raise
if not isinstance(ratio, float):
ratio = float(ratio)
return ratio
def center... | def _get_ratio(ratio):
if isinstance(ratio, str):
if ':' in ratio:
(r_w, r_h) = ratio.split(':')
try:
ratio = float(r_w) / float(r_h)
except:
raise
if not isinstance(ratio, float):
ratio = float(ratio)
return ratio
def cent... |
# Copyright (c) 2015, Sofiat Olaosebikan. All Rights Reserved
# This program 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.
#
# This ... | class Hopcroftkarp(object):
def __init__(self, graph):
"""
:param graph: an unweighted bipartite graph represented as a dictionary.
Vertices in the left and right vertex set must have different labelling
:return: a maximum matching of the given graph represented as a dictionary.
... |
class DefaultAlias(object):
''' unless explicitly assigned, this attribute aliases to another. '''
def __init__(self, name):
self.name = name
def __get__(self, inst, cls):
if inst is None:
# attribute accessed on class, return `self' descriptor
return self
ret... | class Defaultalias(object):
""" unless explicitly assigned, this attribute aliases to another. """
def __init__(self, name):
self.name = name
def __get__(self, inst, cls):
if inst is None:
return self
return getattr(inst, self.name)
class Alias(DefaultAlias):
""" t... |
f1 = open("unprocessed/Cit-HepTh-dates.csv", "w")
f2 = open("unprocessed/Cit-HepTh.csv", "w")
with open("unprocessed/Cit-HepTh-dates.txt", "r") as file:
c = 0
for line in file:
if not c == 0:
l = line.split()
nl = l[0] + "," + l[1] + '\n'
f1.write(nl)
... | f1 = open('unprocessed/Cit-HepTh-dates.csv', 'w')
f2 = open('unprocessed/Cit-HepTh.csv', 'w')
with open('unprocessed/Cit-HepTh-dates.txt', 'r') as file:
c = 0
for line in file:
if not c == 0:
l = line.split()
nl = l[0] + ',' + l[1] + '\n'
f1.write(nl)
else:
... |
def color_analysis(img):
# obtain the color palatte of the image
palatte = defaultdict(int)
for pixel in img.getdata():
palatte[pixel] += 1
# sort the colors present in the image
sorted_x = sorted(palatte.items(), key=operator.itemgetter(1), reverse = True)
light_shade, dark_shade, shad... | def color_analysis(img):
palatte = defaultdict(int)
for pixel in img.getdata():
palatte[pixel] += 1
sorted_x = sorted(palatte.items(), key=operator.itemgetter(1), reverse=True)
(light_shade, dark_shade, shade_count, pixel_limit) = (0, 0, 0, 25)
for (i, x) in enumerate(sorted_x[:pixel_limit])... |
#Write a program using while loops that asks the user for a positive integer 'n' and prints
#a triangle using numbers from 1 to 'n'.
number = int(input("Give me a number: "))
count = 0
for x in range(1, number+1):
count += 1
dibujar = str(x)
print (dibujar*count)
| number = int(input('Give me a number: '))
count = 0
for x in range(1, number + 1):
count += 1
dibujar = str(x)
print(dibujar * count) |
"""
factorial() is function factorial(number),
take the number parameter been passed and
return the factorial of it
"""
def factorial(number):
if number == 0:
return 1
else:
ans = number * factorial(number - 1)
return ans
| """
factorial() is function factorial(number),
take the number parameter been passed and
return the factorial of it
"""
def factorial(number):
if number == 0:
return 1
else:
ans = number * factorial(number - 1)
return ans |
class Solution:
def getFactors(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
ans = []
self.helper(n, [], n, ans)
return ans
def helper(self, n, factors, left, ans):
if left == 1:
if factors:
ans.append(fact... | class Solution:
def get_factors(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
ans = []
self.helper(n, [], n, ans)
return ans
def helper(self, n, factors, left, ans):
if left == 1:
if factors:
ans.append(factor... |
class Board(object):
def __init__(self, boards):
if len(boards) != 25:
raise Exception(f"Invalid board : {len(boards)}")
self.boards = boards
self.marked = [False] * 25
@staticmethod
def parse(lines):
boards = []
for line in lines:
boards.ext... | class Board(object):
def __init__(self, boards):
if len(boards) != 25:
raise exception(f'Invalid board : {len(boards)}')
self.boards = boards
self.marked = [False] * 25
@staticmethod
def parse(lines):
boards = []
for line in lines:
boards.ext... |
{
"format_version": "1.16.0",
"minecraft:entity": {
"description": {
"identifier": f"{namespace}:pig_{color}",
"is_spawnable": true,
"is_summonable": true,
"is_experimental": false
},
"components": {
"minecraft:type_family": {
"family": [
f"pig_{color}",
"pig",
"mob"
]
}... | {'format_version': '1.16.0', 'minecraft:entity': {'description': {'identifier': f'{namespace}:pig_{color}', 'is_spawnable': true, 'is_summonable': true, 'is_experimental': false}, 'components': {'minecraft:type_family': {'family': [f'pig_{color}', 'pig', 'mob']}, 'minecraft:breathable': {'total_supply': 15, 'suffocate_... |
"""
The :mod:`stan.proc_functions.merge` module is the proc merge function
"""
def merge(dt_left, dt_right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, suffixes=('_x', '_y'), copy=True):
return dt_left.merge(dt_right, how='inner', on=None, left_on=None, right... | """
The :mod:`stan.proc_functions.merge` module is the proc merge function
"""
def merge(dt_left, dt_right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, suffixes=('_x', '_y'), copy=True):
return dt_left.merge(dt_right, how='inner', on=None, left_on=None, right... |
"""
Constants
Author: Brady Volkmann
Date: 6/21/2019
Constants file for the Tektroniks TTR506 VNA
"""
# INITIALIZE CONSTANTS ======================================================
# configure acquisition parameters
startFreqSweep = '50 MHz'
stopFreqSweep = '6 GHz'
sweepDelay = '1s'
snpFilename = 'test.s1... | """
Constants
Author: Brady Volkmann
Date: 6/21/2019
Constants file for the Tektroniks TTR506 VNA
"""
start_freq_sweep = '50 MHz'
stop_freq_sweep = '6 GHz'
sweep_delay = '1s'
snp_filename = 'test.s1p'
s_param = 'S21' |
description = 'The outside temperature on the campus'
group = 'lowlevel'
devices = dict(
OutsideTemp = device('nicos.devices.entangle.Sensor',
description = 'Outdoor air temperature',
tangodevice = 'tango://ictrlfs.ictrl.frm2:10000/frm2/meteo/temp',
),
)
| description = 'The outside temperature on the campus'
group = 'lowlevel'
devices = dict(OutsideTemp=device('nicos.devices.entangle.Sensor', description='Outdoor air temperature', tangodevice='tango://ictrlfs.ictrl.frm2:10000/frm2/meteo/temp')) |
#This is just a demo server file to demonstrate the working of Telopy Backend
#This program consist the last line of Telopy
#import time
#import sys
#cursor = ['|','/','-','\\']
print('Telopy Server is Live ',end="")
#while True:
# for i in cursor:
# print(i+"\x08",end="")
# sys.stdout.flush()
# ... | print('Telopy Server is Live ', end='') |
class VersioningError(Exception):
pass
class ClassNotVersioned(VersioningError):
pass
class ImproperlyConfigured(VersioningError):
pass
| class Versioningerror(Exception):
pass
class Classnotversioned(VersioningError):
pass
class Improperlyconfigured(VersioningError):
pass |
def create_groups(items, n):
"""Splits items into n groups of equal size, although the last one may be shorter."""
# determine the size each group should be
try:
# this line could cause a ZeroDivisionError exception
size = len(items) // n
except ZeroDivisionError:
print('WARNING:... | def create_groups(items, n):
"""Splits items into n groups of equal size, although the last one may be shorter."""
try:
size = len(items) // n
except ZeroDivisionError:
print('WARNING: Returning empty list. Please use a nonzero number.')
return []
else:
groups = []
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@created: 22.01.20
@author: felix
"""
NORMALIZE = False
class EasyDict(dict):
def __init__(self, *args, **kwargs):
global NORMALIZE
NORMALIZE = kwargs.pop('normalize', False)
super(EasyDict, self).__init__(*args, **kwargs)
def __get... | """
@created: 22.01.20
@author: felix
"""
normalize = False
class Easydict(dict):
def __init__(self, *args, **kwargs):
global NORMALIZE
normalize = kwargs.pop('normalize', False)
super(EasyDict, self).__init__(*args, **kwargs)
def __getattr__(self, item):
if NORMALIZE and item... |
fig, axs = plt.subplots(1, 2, figsize=(20,5))
p1=boroughs4.plot(column='Controlled drugs',ax=axs[0],cmap='Blues',legend=True);
p2=boroughs4.plot(column='Stolen goods',ax=axs[1], cmap='Reds',legend=True);
axs[0].set_title('Controlled drugs', fontdict={'fontsize': '12', 'fontweight' : '5'});
axs[1].set_title('Stolen go... | (fig, axs) = plt.subplots(1, 2, figsize=(20, 5))
p1 = boroughs4.plot(column='Controlled drugs', ax=axs[0], cmap='Blues', legend=True)
p2 = boroughs4.plot(column='Stolen goods', ax=axs[1], cmap='Reds', legend=True)
axs[0].set_title('Controlled drugs', fontdict={'fontsize': '12', 'fontweight': '5'})
axs[1].set_title('Sto... |
class Reaction:
def __init__(self):
pass
def from_json(json):
reaction = Reaction()
reaction.reaction = json["reaction"].encode("unicode-escape")
reaction.actor = json["actor"]
return reaction
def list_from_json(json):
reactions = []
for child in json:
reactions.append(Reaction.from_json(child)... | class Reaction:
def __init__(self):
pass
def from_json(json):
reaction = reaction()
reaction.reaction = json['reaction'].encode('unicode-escape')
reaction.actor = json['actor']
return reaction
def list_from_json(json):
reactions = []
for child in js... |
class Triangulo():
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def semelhantes(self, triangulo):
a, b, c = triangulo.a, triangulo.b, triangulo.c
if ((a % self.a) == 0 ) and ((b % self.b) == 0) and ((c % self.c) == 0):
ret... | class Triangulo:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def semelhantes(self, triangulo):
(a, b, c) = (triangulo.a, triangulo.b, triangulo.c)
if a % self.a == 0 and b % self.b == 0 and (c % self.c == 0):
return True
elif a // s... |
age = input("Please enter your age: ")
if age.isdigit():
print(age)
age = int(input("Please enter your age: "))
while(True):
try:
age = int(input("Please enter your age: "))
except ValueError:
print("Sorry, I didn't understand that.")
continue
else:
break
raise Except... | age = input('Please enter your age: ')
if age.isdigit():
print(age)
age = int(input('Please enter your age: '))
while True:
try:
age = int(input('Please enter your age: '))
except ValueError:
print("Sorry, I didn't understand that.")
continue
else:
break
raise exception('... |
def fasttsq(M,psi,Y,y,m,c,o,plm):
#TODO
raise NotImplementedError
def fasttsq3d(M,psi,Y,y,m,c,o,plm):
#TODO
raise NotImplementedError
def fasttsqp(M,psi,Y,y,m,c,o,plm):
#TODO
raise NotImplementedError
def fastq(M,psi,Y,y,m,c,o,plm):
#TODO
raise NotImplementedError
def fastq3d(M,psi,Y... | def fasttsq(M, psi, Y, y, m, c, o, plm):
raise NotImplementedError
def fasttsq3d(M, psi, Y, y, m, c, o, plm):
raise NotImplementedError
def fasttsqp(M, psi, Y, y, m, c, o, plm):
raise NotImplementedError
def fastq(M, psi, Y, y, m, c, o, plm):
raise NotImplementedError
def fastq3d(M, psi, Y, y, m, c,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.