content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Global settings
def init():
global target_api_url
target_api_url = ""
global target_instance_url
target_instance_url = ""
global source_api_url
source_api_url = ""
global source_instance_url
source_instance_url = ""
global sourcetoken
sourcetoken = ""
global targ... | def init():
global target_api_url
target_api_url = ''
global target_instance_url
target_instance_url = ''
global source_api_url
source_api_url = ''
global source_instance_url
source_instance_url = ''
global sourcetoken
sourcetoken = ''
global targettoken
targettoken = ''
... |
c.ServerProxy.servers = {
'code-server': {
'command': [
'code-server',
'--auth=none',
'--disable-telemetry',
'--bind-addr=localhost:{port}'
],
'timeout': 20,
'launcher_entry': {
'title': 'VS Code'
}
}
}
| c.ServerProxy.servers = {'code-server': {'command': ['code-server', '--auth=none', '--disable-telemetry', '--bind-addr=localhost:{port}'], 'timeout': 20, 'launcher_entry': {'title': 'VS Code'}}} |
#!/usr/bin/env python
#####################################
# Installation module for CrackMapExec
#####################################
# AUTHOR OF MODULE NAME
AUTHOR="David Kennedy (ReL1K), updated by Russ Swift (0xsalt)"
# DESCRIPTION OF THE MODULE
DESCRIPTION="This module will install/update CrackMapExec - pentes... | author = 'David Kennedy (ReL1K), updated by Russ Swift (0xsalt)'
description = 'This module will install/update CrackMapExec - pentesters AD tool'
install_type = 'GIT'
repository_location = ''
install_location = ''
debian = 'python3.7'
fedora = 'git'
after_commands = 'cd {INSTALL_LOCATION},rm -rf crackmapexec,git clone... |
'''
calculate the similarity of the given question of problem1.4
'''
def calculate(X, Y):
similarity = 0
for x, y in enumerate(X, Y):
similarity += abs(x - y)
return similarity / len(X)
| """
calculate the similarity of the given question of problem1.4
"""
def calculate(X, Y):
similarity = 0
for (x, y) in enumerate(X, Y):
similarity += abs(x - y)
return similarity / len(X) |
# Lecture 2.6, slide 4
x = int(raw_input('Enter an integer: '))
if (x % 2 == 0):
if (x % 3 == 0):
print ('Divisible by 2 and 3.')
else:
print ('Divisible by 2 but not 3.')
elif (x % 3 == 0):
print ('Divisible by 3 but not 2.') | x = int(raw_input('Enter an integer: '))
if x % 2 == 0:
if x % 3 == 0:
print('Divisible by 2 and 3.')
else:
print('Divisible by 2 but not 3.')
elif x % 3 == 0:
print('Divisible by 3 but not 2.') |
# -*- coding: utf-8 -*-
"""Top-level package for elm-fluent."""
__author__ = """Luke Plant"""
__email__ = "L.Plant.98@cantab.net"
__version__ = "0.6.0"
| """Top-level package for elm-fluent."""
__author__ = 'Luke Plant'
__email__ = 'L.Plant.98@cantab.net'
__version__ = '0.6.0' |
infty = 10**20
def floyd_warshall(w):
N = len(w)
R = [weights[:] for weights in w]
E = [[None]*N for _ in range(N)]
for i in range(N):
for j in range(N):
if R[i][j] is None:
R[i][j] = +infty
for j in range(N):
for i in set(range(N)) - {j}:
f... | infty = 10 ** 20
def floyd_warshall(w):
n = len(w)
r = [weights[:] for weights in w]
e = [[None] * N for _ in range(N)]
for i in range(N):
for j in range(N):
if R[i][j] is None:
R[i][j] = +infty
for j in range(N):
for i in set(range(N)) - {j}:
... |
#!/usr/bin/env python3
with open("gamelist.txt", "r") as f:
for l in f:
l = l.replace("\n", "")
l = l.split("/", 1)[0]
print(l)
| with open('gamelist.txt', 'r') as f:
for l in f:
l = l.replace('\n', '')
l = l.split('/', 1)[0]
print(l) |
class SystemTopics:
newCrownstoneFound = "newCrownstoneFound"
stateUpdate = "stateUpdate" # used to propagate verified state messages through the system
uartNewPackage = 'uartNewPackage' # Sent when a UART packet is received. Data is a UartWrapperPacket.
uartNewMe... | class Systemtopics:
new_crownstone_found = 'newCrownstoneFound'
state_update = 'stateUpdate'
uart_new_package = 'uartNewPackage'
uart_new_message = 'uartNewMessage'
uart_write_data = 'uartWriteData'
uart_write_error = 'uartWriteError'
uart_write_success = 'uartWriteSuccess'
result_packet... |
a = list(map(int, input().split()))
b = list(map(int, input().split()))
print(max((sum(a) - min(a)), (sum(b) - min(b))))
| a = list(map(int, input().split()))
b = list(map(int, input().split()))
print(max(sum(a) - min(a), sum(b) - min(b))) |
class Solution:
def find(self, m, n, visited, ans, s, i, j):
if i == n-1 and j == n-1:
ans.append(s)
return
visited[i][j] = 1
# Go Down and marking the path as visited
if i < n-1 and visited[i+1][j] == 0 and m[i+1][j] == 1:
visited[i+1][j] = 1
... | class Solution:
def find(self, m, n, visited, ans, s, i, j):
if i == n - 1 and j == n - 1:
ans.append(s)
return
visited[i][j] = 1
if i < n - 1 and visited[i + 1][j] == 0 and (m[i + 1][j] == 1):
visited[i + 1][j] = 1
self.find(m, n, visited, an... |
# Copyright 2018 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | """Implementation of macOS test rules."""
load('@build_bazel_rules_apple//apple/internal/testing:apple_test_rule_support.bzl', 'apple_test_rule_support')
load('@build_bazel_rules_apple//apple/internal/testing:apple_test_bundle_support.bzl', 'apple_test_bundle_support')
load('@build_bazel_rules_apple//apple/internal:app... |
class Settings():
"""A class to store all settings for the game."""
def __init__(self):
super().__init__()
# General settings
self.application_name = "SpaceInvaderv2"
self.font = "arial"
# Screen dimensions
self.HEIGHT = 600
self.WIDTH = 600
... | class Settings:
"""A class to store all settings for the game."""
def __init__(self):
super().__init__()
self.application_name = 'SpaceInvaderv2'
self.font = 'arial'
self.HEIGHT = 600
self.WIDTH = 600
self.colors = colors()
self.FPS = 60
self.powe... |
print("---Pallendrome check---")
inputStr = input("Enter string ")
revserStr = inputStr[::-1]
if inputStr == revserStr :
print (inputStr, "is a pallendrome!")
else :
print (inputStr, "is not a pallendrome!")
| print('---Pallendrome check---')
input_str = input('Enter string ')
revser_str = inputStr[::-1]
if inputStr == revserStr:
print(inputStr, 'is a pallendrome!')
else:
print(inputStr, 'is not a pallendrome!') |
class Interactions(object):
ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
def __init__(self):
self.mode = None
@staticmethod
def interact_with_sut():
return "foo"
| class Interactions(object):
robot_library_scope = 'TEST SUITE'
def __init__(self):
self.mode = None
@staticmethod
def interact_with_sut():
return 'foo' |
class Photo:
path = ""
caption = ""
def __init__(self, path, caption=""):
self.path = path
self.caption = caption
def set_caption(self, caption):
self.caption = caption
def get_caption(self):
return self.caption
def __repr__(self) -> str:
return "Photo... | class Photo:
path = ''
caption = ''
def __init__(self, path, caption=''):
self.path = path
self.caption = caption
def set_caption(self, caption):
self.caption = caption
def get_caption(self):
return self.caption
def __repr__(self) -> str:
return "Photo... |
# The idea is to construct the prefix sum arrays (four of them) containing the numbers of
# each nucleotide up to jth position
# Then, the difference between the pre- and post-sums for positions p and q are the numbers of
# nucleotides in the region.
# For these four differences, add the minimum impact factor
def sol... | def solution(S, P, Q):
impacts = {'A': 1, 'C': 2, 'G': 3, 'T': 4}
sums = [[0] * len(S), [0] * len(S), [0] * len(S), [0] * len(S)]
for i in range(0, len(S)):
if S[i] == 'A':
sums[0][i] += 1
if S[i] == 'C':
sums[1][i] += 1
if S[i] == 'G':
sums[2][i] ... |
# -*- coding: utf-8 -*-
class Solution:
def isValid(self, s: str) -> bool:
if len(s) % 2 == 1:
return False
pairs = {
')': '(',
']': '[',
'}': '{',
}
stack = []
for ch in s:
if ch in pairs:
if not s... | class Solution:
def is_valid(self, s: str) -> bool:
if len(s) % 2 == 1:
return False
pairs = {')': '(', ']': '[', '}': '{'}
stack = []
for ch in s:
if ch in pairs:
if not stack or stack[-1] != pairs[ch]:
return False
... |
#!/usr/bin/env python3
"""
The default options for the faceswap Unbalanced Model plugin.
Defaults files should be named <plugin_name>_defaults.py
Any items placed into this file will automatically get added to the relevant config .ini files
within the faceswap/config folder.
The following variable... | """
The default options for the faceswap Unbalanced Model plugin.
Defaults files should be named <plugin_name>_defaults.py
Any items placed into this file will automatically get added to the relevant config .ini files
within the faceswap/config folder.
The following variables should be defined:
... |
_base_ = [
# '../_base_/models/cd_vit.py',
# '../_base_/datasets/two_input.py',
# '../_base_/default_runtime.py',
# '../_base_/schedules/schedule_40k.py'
]
# model settings
# model settings
norm_cfg = dict(type='SyncBN', requires_grad=True)
model = dict(
type='EncoderDecoder',
# pretrained=''... | _base_ = []
norm_cfg = dict(type='SyncBN', requires_grad=True)
model = dict(type='EncoderDecoder', backbone=dict(type='SiameseEfficientNet', name='tf_efficientnetv2_b1', fusion='diff', pretrained=True), decode_head=dict(type='UPerHead', in_channels=[16, 32, 48, 96, 112, 192], in_index=[0, 1, 2, 3, 4, 5], pool_scales=(1... |
# Cloud Automation Services SDK for Python
# Copyright (c) 2019 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
class Network(object):
def __init__(self, network):
pass
@staticmethod
def list(session):
uri = f'/iaas/api/networks'
j = session._request(f'{ses... | class Network(object):
def __init__(self, network):
pass
@staticmethod
def list(session):
uri = f'/iaas/api/networks'
j = session._request(f'{session.baseurl}{uri}')
return j['content']
@classmethod
def describe(cls, session, id):
uri = f'/iaas/api/networks... |
# -*- coding: utf-8 -*-
"""Mixins to be implemented by user."""
class RateMixin:
"""User defined mixin class for Rate."""
def __init__(
self,
*,
base_ActivityEdge=None,
base_ObjectNode=None,
base_Parameter=None,
rate=None,
**kwargs,
):
super... | """Mixins to be implemented by user."""
class Ratemixin:
"""User defined mixin class for Rate."""
def __init__(self, *, base_ActivityEdge=None, base_ObjectNode=None, base_Parameter=None, rate=None, **kwargs):
super().__init__()
class Controloperatormixin:
"""User defined mixin class for ControlOp... |
async def handleRequest(request):
visitor_ip = request.headers.js_get('CF-Connecting-IP')
console.log(visitor_ip)
r = await fetch("https://api.ip.sb/geoip/" + visitor_ip)
d = await r.json()
d['time'] = Date.now()
return __new__(Response(JSON.stringify(d), {
'headers' : { 'content-type' :... | async def handleRequest(request):
visitor_ip = request.headers.js_get('CF-Connecting-IP')
console.log(visitor_ip)
r = await fetch('https://api.ip.sb/geoip/' + visitor_ip)
d = await r.json()
d['time'] = Date.now()
return __new__(response(JSON.stringify(d), {'headers': {'content-type': 'text/plain... |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | controller_reconnect_timeout = 10
def start_policy(policy, topology, timeout):
policy.start(topology)
policy.wait(timeout)
if len(policy.exceptions) > 0:
raise policy.exceptions[0]
def get_port_mac_and_ip(port, force_addr_pairs=False):
port_lport = port.port.get_logical_port()
allowed_addr... |
__author__ = """OceanProtocol"""
__version__ = '0.5.5'
# Copyright 2018 Ocean Protocol Foundation
# SPDX-License-Identifier: Apache-2.0
| __author__ = 'OceanProtocol'
__version__ = '0.5.5' |
def generate_from_bytes_mod_order_test_vector(modulus):
def gen_vector(number):
byte_arr = convert_int_to_byte_vec(number)
# s = str(number % modulus)
# return "(" + byte_arr + ", \"" + s + "\"),"
return byte_arr + ","
data = ["vec!["]
small_values_to_test = [0, 1, 255, 256... | def generate_from_bytes_mod_order_test_vector(modulus):
def gen_vector(number):
byte_arr = convert_int_to_byte_vec(number)
return byte_arr + ','
data = ['vec![']
small_values_to_test = [0, 1, 255, 256, 256 * 256 + 255]
modulus_bits = int((len(bin(modulus)[2:]) + 7) / 8) * 8
values_t... |
class Stack:
def __init__(self):
# Stack dynamic array implementation
self.stack = []
self.length = 0
def push(self, item):
self.stack.append(item)
self.length += 1
def pop(self):
if self.isEmpty():
return None
self.length -= 1
re... | class Stack:
def __init__(self):
self.stack = []
self.length = 0
def push(self, item):
self.stack.append(item)
self.length += 1
def pop(self):
if self.isEmpty():
return None
self.length -= 1
return self.stack.pop()
def peek(self):
... |
class Movie: #Created a class w/properties of a Movie
def __init__(self,movieName,rating,yearReleased): #initializes the properties and creates the template used for Instances
self.movieName=movieName
self.rating=rating
self.yearReleased=yearReleased
def __str__(self): #used to print all... | class Movie:
def __init__(self, movieName, rating, yearReleased):
self.movieName = movieName
self.rating = rating
self.yearReleased = yearReleased
def __str__(self):
new_print = f'Movie info: {self.movieName}, {self.rating}, {self.yearReleased}'
return newPrint
class P... |
boilerplate_ = '''import PySimpleGUI as sg
layout = [[]]
window = sg.Window('App', layout)
while True:
event, values = window.read()
if event in (None, 'Exit'): break
if event == '':
pass
# ~TARGET
window.close()
''' | boilerplate_ = "import PySimpleGUI as sg\n\nlayout = [[]]\nwindow = sg.Window('App', layout)\n\nwhile True:\n\tevent, values = window.read()\n\tif event in (None, 'Exit'): break\n\n\tif event == '':\n\t\tpass\n\n# ~TARGET\n\nwindow.close()\n" |
# EXERCISE 1:
# Step 1: Join items from list `["Answer","to","life","the","universe","and","everything","is","42"]` with space.
# Step 2: Append it with . at the end of line.
print(" ".join(["Answer","to","life","the","universe","and","everything","is","42"])+'.')
# EXERCISE 2:
#Find how many occurances of "... | print(' '.join(['Answer', 'to', 'life', 'the', 'universe', 'and', 'everything', 'is', '42']) + '.')
print('Answer to life the universe and everything is 42.'.casefold().count('a'))
print('Answer to life the universe and everything is 42.'[-3:])
print('\nExercise 1:')
x = [1, 'test', 3]
print(x)
del x[1]
print(x)
print(... |
class Kid:
def __init__(self, name="", age=-1):
self.name = name
self.age = age
class Family:
def __init__(self):
self.parents = []
self.kids = []
def add_kid(self, kid):
self.kids.append(kid)
| class Kid:
def __init__(self, name='', age=-1):
self.name = name
self.age = age
class Family:
def __init__(self):
self.parents = []
self.kids = []
def add_kid(self, kid):
self.kids.append(kid) |
# Message class to pydantic class converter
def get_type(typ) -> str:
if typ == str:
return "str"
elif typ == int:
return "int"
elif typ == dict:
return "dict"
elif typ == any:
return "any"
else:
return typ.__name__
def convert(cls):
res = []
res.a... | def get_type(typ) -> str:
if typ == str:
return 'str'
elif typ == int:
return 'int'
elif typ == dict:
return 'dict'
elif typ == any:
return 'any'
else:
return typ.__name__
def convert(cls):
res = []
res.append('class {}(BaseModel):'.format(cls.__name_... |
#!/usr/bin/env python
"""Exceptions for the distributed data servers."""
class DataServerError(Exception):
"""Raised when some error condition happens in a data server."""
pass
| """Exceptions for the distributed data servers."""
class Dataservererror(Exception):
"""Raised when some error condition happens in a data server."""
pass |
'''PART1'''
#open file
seq_file = open("/Users/modia/Downloads/Homo_sapiens_sequence.fa","r")
#make/initialize three lists to capture the sequence of the cDNA, 3'UTR, and 5'UTR
cdna = ""
utr3 = ""
utr5 = ""
#read first line and do nothing with it because its just the name
seq_file.readline()
#initialize string to... | """PART1"""
seq_file = open('/Users/modia/Downloads/Homo_sapiens_sequence.fa', 'r')
cdna = ''
utr3 = ''
utr5 = ''
seq_file.readline()
seq_string = ''
count = 0
for lines in seq_file.readlines():
lines = lines.strip()
if lines[0] != '>':
seq_string = seq_string + lines
elif count == 0:
cdna =... |
data = [ 1, 2, 3, 4, 5, 6, 7, 8]
events = []
for num in data:
if not num % 2:
events.append(num)
print(events)
events2 = [num for num in data if not num % 2]
print(events2)
data = [ 1, 'one', 2, 'two', 3, 'three', 4, 'four']
words = []
for num in data:
if isinstance(num, str):
words.append(nu... | data = [1, 2, 3, 4, 5, 6, 7, 8]
events = []
for num in data:
if not num % 2:
events.append(num)
print(events)
events2 = [num for num in data if not num % 2]
print(events2)
data = [1, 'one', 2, 'two', 3, 'three', 4, 'four']
words = []
for num in data:
if isinstance(num, str):
words.append(num)
pr... |
class Plugin(object):
__key__ = None
__priority__ = 0
_client = None
# TODO should this be changed to support both client and database updater plugins?
def initialize(self, client):
self._client = client
@property
def available(self):
return True
| class Plugin(object):
__key__ = None
__priority__ = 0
_client = None
def initialize(self, client):
self._client = client
@property
def available(self):
return True |
a,b,c=map(int,input().split())
if a+b+c>=100: print("OK")
elif a==min(a,b,c): print("Soongsil")
elif b==min(a,b,c): print("Korea")
else: print("Hanyang") | (a, b, c) = map(int, input().split())
if a + b + c >= 100:
print('OK')
elif a == min(a, b, c):
print('Soongsil')
elif b == min(a, b, c):
print('Korea')
else:
print('Hanyang') |
def main():
print("Implement {{ cookiecutter.package_name }}'s main function!")
if __name__ == "__main__":
main()
| def main():
print("Implement {{ cookiecutter.package_name }}'s main function!")
if __name__ == '__main__':
main() |
# -*- coding: utf-8 -*-
nStr = input().split()
nMap = map(int, nStr)
nLst = list(nMap)
if nLst[0] + nLst[1] > nLst[2] and nLst[0] + nLst[2] > nLst[1] and nLst[1] + nLst[2] > nLst[0]:
if nLst[0] != nLst[1] and nLst[0] != nLst[2] and nLst[1] != nLst[2]:
print("Valido-Escaleno")
if (nLst[0] == nLst[1]... | n_str = input().split()
n_map = map(int, nStr)
n_lst = list(nMap)
if nLst[0] + nLst[1] > nLst[2] and nLst[0] + nLst[2] > nLst[1] and (nLst[1] + nLst[2] > nLst[0]):
if nLst[0] != nLst[1] and nLst[0] != nLst[2] and (nLst[1] != nLst[2]):
print('Valido-Escaleno')
if nLst[0] == nLst[1] and nLst[0] != nLst[2]... |
def domultiplication():
a=2
b=5
print(a*b)#this is code for multiplication
domultiplication()
| def domultiplication():
a = 2
b = 5
print(a * b)
domultiplication() |
MUSE_NB_EEG_CHANNELS = 5
MUSE_SAMPLING_EEG_RATE = 256
LSL_EEG_CHUNK = 12
MUSE_NB_PPG_CHANNELS = 3
MUSE_SAMPLING_PPG_RATE = 64
LSL_PPG_CHUNK = 6
MUSE_NB_ACC_CHANNELS = 3
MUSE_SAMPLING_ACC_RATE = 52
LSL_ACC_CHUNK = 1
MUSE_NB_GYRO_CHANNELS = 3
MUSE_SAMPLING_GYRO_RATE = 52
LSL_GYRO_CHUNK = 1
MUSE_GATT_ATTR_STREAM_TOGGL... | muse_nb_eeg_channels = 5
muse_sampling_eeg_rate = 256
lsl_eeg_chunk = 12
muse_nb_ppg_channels = 3
muse_sampling_ppg_rate = 64
lsl_ppg_chunk = 6
muse_nb_acc_channels = 3
muse_sampling_acc_rate = 52
lsl_acc_chunk = 1
muse_nb_gyro_channels = 3
muse_sampling_gyro_rate = 52
lsl_gyro_chunk = 1
muse_gatt_attr_stream_toggle = ... |
class Node:
def __init__(self, state):
self.state = state
self.wins = 0.0
self.visits = 0.0
self.ressq = 0.0
self.parent = None
self.children = []
self.sputc = 0.0
self.isTerminal = False
def SetWeight(self, weight):
self.weight = weig... | class Node:
def __init__(self, state):
self.state = state
self.wins = 0.0
self.visits = 0.0
self.ressq = 0.0
self.parent = None
self.children = []
self.sputc = 0.0
self.isTerminal = False
def set_weight(self, weight):
self.weight = weight... |
#!/usr/bin/env python3
print('Hello World!')
| print('Hello World!') |
#!/usr/bin/python3
"""
Define a Rectangle class that inherits from BaseGeometry
"""
BaseGeometry = __import__('7-base_geometry').BaseGeometry
class Rectangle(BaseGeometry):
"""
Class that defines a rectangle
"""
def __init__(self, width, height):
"""
Initialize the Rectangle
... | """
Define a Rectangle class that inherits from BaseGeometry
"""
base_geometry = __import__('7-base_geometry').BaseGeometry
class Rectangle(BaseGeometry):
"""
Class that defines a rectangle
"""
def __init__(self, width, height):
"""
Initialize the Rectangle
Args:
w... |
n = int(input())
under200 = 0
bt200to399 = 0
bt400to599 = 0
bt600to799 = 0
more800 = 0
for i in range(1, n+1):
num = int(input())
if num<200:
under200+=1
elif 200<=num<=399:
bt200to399+=1
elif 400<=num<=599:
bt400to599+=1
elif 600<=num<=799:
bt600to799+=1
else:
... | n = int(input())
under200 = 0
bt200to399 = 0
bt400to599 = 0
bt600to799 = 0
more800 = 0
for i in range(1, n + 1):
num = int(input())
if num < 200:
under200 += 1
elif 200 <= num <= 399:
bt200to399 += 1
elif 400 <= num <= 599:
bt400to599 += 1
elif 600 <= num <= 799:
bt60... |
# Init
f1 = 0
f2 = 0
f3 = 0
f4 = 0
# Input
n1 = int(input("Enter First Number: "))
n2 = int(input("Enter Second Number: "))
n3 = int(input("Enter Third Number: "))
n4 = int(input("Enter Fourth Number: "))
# Process
if n1 > n2 and n1 > n3 and n1 > n4:
f4 = n1
if n2 > n3 and n2 > n4:
f3 = n2
... | f1 = 0
f2 = 0
f3 = 0
f4 = 0
n1 = int(input('Enter First Number: '))
n2 = int(input('Enter Second Number: '))
n3 = int(input('Enter Third Number: '))
n4 = int(input('Enter Fourth Number: '))
if n1 > n2 and n1 > n3 and (n1 > n4):
f4 = n1
if n2 > n3 and n2 > n4:
f3 = n2
if n3 > n4:
f2 =... |
# coding: utf-8
#
# Copyright 2014 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | """Configuration for JavaScript library dependencies."""
__author__ = 'Sean Lip'
dependencies_to_angular_modules_dict = {'codemirror': ['ui.codemirror'], 'google_maps': ['ui.map'], 'guppy': [], 'logic_proof': [], 'math_expressions': [], 'midijs': [], 'pencilcode': [], 'skulpt': []} |
#
# File: scripts/thread_handler.nut
# Author: Astrofra
#
def GenericThreadWait(s):
# _timeout = g_clock
#
# while ((g_clock - _timeout) < FixedSecToTick(Sec(s)))
# suspend()
pass
def RawClockThreadWait(s):
# local _timeout = 0.0
#
# while (_timeout < Sec(s)):
# _timeout += g_raw_dt_frame
# suspend()
... | def generic_thread_wait(s):
pass
def raw_clock_thread_wait(s):
pass
class Threadhandler:
def __init__(self, scene=None):
self.thread_list = []
self.current_scene = scene
def update(self):
self.HandleThreadList()
def create_thread(self, _thread_name):
pass
de... |
#class SeaDocument:
#"Sea document"
#def Info(self):
#return "Sea document"
# Get the Parameter Group of this module
ParGrp = App.ParamGet("System parameter:Modules").GetGroup("Sea") | par_grp = App.ParamGet('System parameter:Modules').GetGroup('Sea') |
'''
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iterati... | """
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1
/ 2 2
/ \\ / 3 4 4 3
But the following is not:
1
/ 2 2
\\ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
... |
py# phonebook_dict = {
# 'Alice' : '703-493-1834',
# 'Bob' : '857-384-1234',
# 'Elizabeth' : '484-584-2923'
# }
# print(phonebook_dict['Alice'])
# phonebook_dict['Kareem'] = '938-489-1234'
# phonebook_dict.pop('Alice')
# ramit = {
# 'name': 'Ramit',
# 'email': 'ramit@gmail.com',
# 'interests': ['movie... | py
def is_letter(string):
if len(string) > 1:
raise type_error('Get case excpeted a string of 1.')
elif ord(string.lower()) >= 97 and ord(string.lower()) <= 122:
return True
else:
return False
def letter_summary(input):
counting_dict = {}
for i in range(len(input)):
... |
print('hello world')
class C(object):
abc = 42
def __init__(self):
self.oar = 100
def f(a, b, c):
i = 42
l = [2,3,4]
d = {'abc':'fob'}
o = C()
print('in f')
f(2, [3,4,5], {'x':42})
| print('hello world')
class C(object):
abc = 42
def __init__(self):
self.oar = 100
def f(a, b, c):
i = 42
l = [2, 3, 4]
d = {'abc': 'fob'}
o = c()
print('in f')
f(2, [3, 4, 5], {'x': 42}) |
def myplot(nc_file, variable):
"""
nc_file application/netcdf
variable string
"""
# plot variable of nc_file
return plot.png
| def myplot(nc_file, variable):
"""
nc_file application/netcdf
variable string
"""
return plot.png |
"""
Write a Python program to compute the radius and the central coordinates (x,y) of a circle which is constructed
by three given points on the plane surface.
"""
print("Input the three coordinates of the circle: ")
x1, y1, x2, y2, x3, y3, = map(float, input().split())
c = (x1-x2)**2 + (y1-y2)**2
a = (x2-x3)**2 + (y2... | """
Write a Python program to compute the radius and the central coordinates (x,y) of a circle which is constructed
by three given points on the plane surface.
"""
print('Input the three coordinates of the circle: ')
(x1, y1, x2, y2, x3, y3) = map(float, input().split())
c = (x1 - x2) ** 2 + (y1 - y2) ** 2
a = (x2 - x... |
cache_transformers = True
log_transformations = True
drop_bad_extractor_results = True
progress_bar = True
parallelize = False
n_jobs = None
default_converters = {
'AudioStim->TextStim': ('IBMSpeechAPIConverter', 'WitTranscriptionConverter'),
'ImageStim->TextStim': ('GoogleVisionAPITextConverter', 'TesseractCon... | cache_transformers = True
log_transformations = True
drop_bad_extractor_results = True
progress_bar = True
parallelize = False
n_jobs = None
default_converters = {'AudioStim->TextStim': ('IBMSpeechAPIConverter', 'WitTranscriptionConverter'), 'ImageStim->TextStim': ('GoogleVisionAPITextConverter', 'TesseractConverter')} |
if __name__ == '__main__':
start_list = ... # 0-9
print("start: ", start_list)
sorted_list = ...
print("sorted: ", sorted_list)
squared_list = ...
print("squared: ", squared_list)
only_bigger_than_5 = ...
print("bigger 5: ", only_bigger_than_5)
combined_list = [
s... | if __name__ == '__main__':
start_list = ...
print('start: ', start_list)
sorted_list = ...
print('sorted: ', sorted_list)
squared_list = ...
print('squared: ', squared_list)
only_bigger_than_5 = ...
print('bigger 5: ', only_bigger_than_5)
combined_list = [start_list, sorted_list, squ... |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Weather, obj[2]: Temperature, obj[3]: Time, obj[4]: Coupon, obj[5]: Coupon_validity, obj[6]: Gender, obj[7]: Age, obj[8]: Maritalstatus, obj[9]: Children, obj[10]: Education, obj[11]: Occupation, obj[12]: Income, obj[13]: Bar, obj[14]: Coffeehouse, obj[15]: Restaurantl... | def find_decision(obj):
if obj[12] > 2:
if obj[16] <= 1.0:
if obj[8] > 0:
if obj[3] <= 3:
return 'True'
elif obj[3] > 3:
return 'False'
else:
return 'False'
elif obj[8] <= 0:
... |
# -*- coding: utf-8 -*-
#Inheritence
#is-a relationship
#manager is-a employee
#car is-a vehicle
#rectangle is-a shape
class Shape:
def __init__(self, xcor, ycor):
self.x = xcor
self.y = ycor
def __str__(self):
return 'x: ' + str(self.x) + ' y: ' + str(self.y) + ... | class Shape:
def __init__(self, xcor, ycor):
self.x = xcor
self.y = ycor
def __str__(self):
return 'x: ' + str(self.x) + ' y: ' + str(self.y) + '\n'
def move(self, x, y):
self.x += x
self.y += y
class Rectangle(Shape):
def __init__(self, xcor, ycor, wth, ht):... |
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return 'P({:.2f}, {:.2f})'.format(self.x, self.y) | class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return 'P({:.2f}, {:.2f})'.format(self.x, self.y) |
"""
File: file_lines.py
Prompts the user for a file name, then reads
the file and outputs the number of lines.
After this, the user can enter a line number, and
the program returns what is on that particular line
"""
input_filename = 'Enter a file name: '
f = open(input_filename, 'r')
lines = f.read().splitlines()
... | """
File: file_lines.py
Prompts the user for a file name, then reads
the file and outputs the number of lines.
After this, the user can enter a line number, and
the program returns what is on that particular line
"""
input_filename = 'Enter a file name: '
f = open(input_filename, 'r')
lines = f.read().splitlines()
pr... |
#
# PySNMP MIB module NTNTECH-NMS-TRAPS-V1-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NTNTECH-NMS-TRAPS-V1-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:25:29 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_intersection, constraints_union, value_range_constraint, value_size_constraint) ... |
config = {
"--acoustic-scale":[0.1,float],
"--allow-partial":["false",str],
"--beam":[13,int],
"--beam-delta":[0.5,float],
"--delta":[0.000976562,float],
"--determinize-lattice":["true",str],
"--hash-ratio":[2,int],
"--latti... | config = {'--acoustic-scale': [0.1, float], '--allow-partial': ['false', str], '--beam': [13, int], '--beam-delta': [0.5, float], '--delta': [0.000976562, float], '--determinize-lattice': ['true', str], '--hash-ratio': [2, int], '--lattice-beam': [8, int], '--max-active': [7000, int], '--max-mem': [50000000, int], '--m... |
tape5 = """\
-1
-1
-1
CUT 5 {CUT_OFF} -1
RDA FIND CROSS SECTION LIBRARY IDENTIFIER NUMBERS IN YOUR LIBRARY FILE
LIB 0 1 2 3 {NLB1} {NLB2} {NLB3} 9 3 0 3 0
OPTL 8 8 8 8 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8
OPTA 8 8 8 8 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8
OPTF 8 8 8 8 7 8 8 8... | tape5 = ' -1\n -1\n -1\n CUT 5 {CUT_OFF} -1\n RDA FIND CROSS SECTION LIBRARY IDENTIFIER NUMBERS IN YOUR LIBRARY FILE\n LIB 0 1 2 3 {NLB1} {NLB2} {NLB3} 9 3 0 3 0\n OPTL 8 8 8 8 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8\n OPTA 8 8 8 8 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8\n OPTF 8 8 8 8 7 8... |
"""
Usecases with Python 3 syntax in the signatures. This is a separate module
in order to avoid syntax errors with Python 2.
"""
class TestClass1(object):
def __init__(self, x, y, z=1, *, a=5):
self.x = x
self.y = y
self.z = z
self.a = a
class TestClass2(object):
def __init_... | """
Usecases with Python 3 syntax in the signatures. This is a separate module
in order to avoid syntax errors with Python 2.
"""
class Testclass1(object):
def __init__(self, x, y, z=1, *, a=5):
self.x = x
self.y = y
self.z = z
self.a = a
class Testclass2(object):
def __init_... |
#
# This file is part of SNMP simulator Control Plane software.
#
# Copyright (c) 2019-2020, Ilya Etingof <etingof@gmail.com>
# License: http://snmplabs.com/snmpsim/license.html
#
# SNMP Agent Simulator: REST API management server
#
class DefaultConfig(object):
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory'
SQ... | class Defaultconfig(object):
sqlalchemy_database_uri = 'sqlite:///:memory'
sqlalchemy_echo = False
debug = False
snmpsim_mgmt_listen_ip = '127.0.0.1'
snmpsim_mgmt_listen_port = 5000
snmpsim_mgmt_ssl_cert = None
snmpsim_mgmt_ssl_key = None
snmpsim_mgmt_dataroot = '/usr/share/snmpsim/data'... |
expected_output = {
"total_num_of_entries": {
"arp_table_entries": 100409,
"dynamic_arp_entries": 100204,
"incomplete_arp_entries": 0,
"interface_arp_entries": 205,
"static_arp_entries": 0,
"alias_arp_entries": 0,
"simple_application_arp_entries": 0,
},
... | expected_output = {'total_num_of_entries': {'arp_table_entries': 100409, 'dynamic_arp_entries': 100204, 'incomplete_arp_entries': 0, 'interface_arp_entries': 205, 'static_arp_entries': 0, 'alias_arp_entries': 0, 'simple_application_arp_entries': 0}, 'interface_entries': {'GigabitEthernet0': 4, 'TenGigabitEthernet0/2/0'... |
#
# PySNMP MIB module RAQMON-RDS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RAQMON-RDS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:52:13 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... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, value_size_constraint, value_range_constraint, constraints_intersection) ... |
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param: he... | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param: hea... |
class Runner:
def __init__(self, installer):
self.installer = installer
installer.set_runner(self)
pass
def process(self):
return True
def key_event(self, keys):
return True
| class Runner:
def __init__(self, installer):
self.installer = installer
installer.set_runner(self)
pass
def process(self):
return True
def key_event(self, keys):
return True |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param A : head node of linked list
# @return the first node in the cycle in the linked list
def detectCycle(self, root):
if root is None... | class Solution:
def detect_cycle(self, root):
if root is None:
return None
slow = root
fast = root.next
while fast and slow != fast:
slow = slow.next
fast = fast.next
if fast:
fast = fast.next
if fast == None:
... |
S = input()
N = len(S)
dp = [[0] * 2 for _ in range(N + 1)]
if N == 1:
print(1)
exit()
if S[0] == S[1]:
dp[0][0] = 0
dp[1][1] = 1
dp[0][1] = 1
dp[1][0] = 1
else:
dp[0][0] = 0
dp[0][1] = 1
dp[1][0] = 1
dp[1][1] = 2
for i in range(2, N):
if S[i - 1] != S[i]:
dp[i][1]... | s = input()
n = len(S)
dp = [[0] * 2 for _ in range(N + 1)]
if N == 1:
print(1)
exit()
if S[0] == S[1]:
dp[0][0] = 0
dp[1][1] = 1
dp[0][1] = 1
dp[1][0] = 1
else:
dp[0][0] = 0
dp[0][1] = 1
dp[1][0] = 1
dp[1][1] = 2
for i in range(2, N):
if S[i - 1] != S[i]:
dp[i][1] = ... |
birdsnap_classnames = [
"Coopers Hawk", "Northern Goshawk", "Sharp shinned Hawk", "Golden Eagle", "White tailed Hawk", "Zone tailed Hawk",
"Red tailed Hawk", "Rough legged Hawk", "Red shouldered Hawk", "Broad winged Hawk", "Ferruginous Hawk",
"Swainsons Hawk", "Common Black Hawk", "Northern Harrier", "Swall... | birdsnap_classnames = ['Coopers Hawk', 'Northern Goshawk', 'Sharp shinned Hawk', 'Golden Eagle', 'White tailed Hawk', 'Zone tailed Hawk', 'Red tailed Hawk', 'Rough legged Hawk', 'Red shouldered Hawk', 'Broad winged Hawk', 'Ferruginous Hawk', 'Swainsons Hawk', 'Common Black Hawk', 'Northern Harrier', 'Swallow tailed Kit... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Pieter Huycke
email: pieter.huycke@ugent.be
GitHub: phuycke
"""
#%%
s1 = "concord"
s2 = "souix city"
s3 = "HONOLULU"
s4 = "TopHat"
print(s1.capitalize())
print(s2.swapcase())
print(s2.upper())
print(s3.lower())
print(s4.title()) | """
@author: Pieter Huycke
email: pieter.huycke@ugent.be
GitHub: phuycke
"""
s1 = 'concord'
s2 = 'souix city'
s3 = 'HONOLULU'
s4 = 'TopHat'
print(s1.capitalize())
print(s2.swapcase())
print(s2.upper())
print(s3.lower())
print(s4.title()) |
def format_title(title, row_len, sep):
rem = row_len - len(title) # How many spaces available?
left = (rem//2) * sep
right = (rem-len(left)) * sep
return '{}{}{}'.format(left, title, right)
def get_widest_cols(data):
# Get number of columns and rows
num_rows = len(data)
num_cols = len(dat... | def format_title(title, row_len, sep):
rem = row_len - len(title)
left = rem // 2 * sep
right = (rem - len(left)) * sep
return '{}{}{}'.format(left, title, right)
def get_widest_cols(data):
num_rows = len(data)
num_cols = len(data[0])
widest_cols = []
for col in range(num_cols):
... |
class Node:
"""
Node object for a linked list class
"""
def __init__(self, val):
self.val = val
self.next = None
def set_next(self, next_):
self.next = next_
def get_next(self):
return self.next
def get_val(self):
return self.val
def set_val(s... | class Node:
"""
Node object for a linked list class
"""
def __init__(self, val):
self.val = val
self.next = None
def set_next(self, next_):
self.next = next_
def get_next(self):
return self.next
def get_val(self):
return self.val
def set_val(s... |
# =============================================================================
# Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/
# FileName: 10106.py
# Description: UVa Online Judge - 10106
# =============================================================================
while True:... | while True:
try:
a = int(input())
b = int(input())
except EOFError:
break
print(a * b) |
## FROM GEEKS4GEEKS
def K(V, W, C, n):
# base case
if n == 0 or C == 0:
return 0
# if any item in the weights arr > capacity it cannot be included so we skip the index with n-1
if W[n-1] > C:
return K(V, W, C, n-1)
else:
return max(V[n-1] + K(V, W, C-W[n-1], n-1), # ca... | def k(V, W, C, n):
if n == 0 or C == 0:
return 0
if W[n - 1] > C:
return k(V, W, C, n - 1)
else:
return max(V[n - 1] + k(V, W, C - W[n - 1], n - 1), k(V, W, C, n - 1)) |
"""Monkey patch H11 to ensure that it sends headers the way the SkyQ box wants them to be."""
def write_headers_titlecase(headers, write):
"""Monkey-patch h11 header handling.
See https://github.com/python-hyper/h11/issues/31 for the details. Essentially SkyQ box is
not RFC compliant as regards case-insen... | """Monkey patch H11 to ensure that it sends headers the way the SkyQ box wants them to be."""
def write_headers_titlecase(headers, write):
"""Monkey-patch h11 header handling.
See https://github.com/python-hyper/h11/issues/31 for the details. Essentially SkyQ box is
not RFC compliant as regards case-insen... |
class ApplicationInfo:
def __init__(self, application_id = None, application_instance_id = None, application_domain_name = None,
application_class_name = None, application_name = None, application_version = None,
application_stage = None, application_runtime = None,
application_runtime... | class Applicationinfo:
def __init__(self, application_id=None, application_instance_id=None, application_domain_name=None, application_class_name=None, application_name=None, application_version=None, application_stage=None, application_runtime=None, application_runtime_version=None, application_tags=None):
... |
'''
This program calculates the factorial of a number.
It is an example program for the Pylint poster.
The function name doesn't follow the snake case.
'''
def computeFactorial(num):#pylint: disable=invalid-name
'''Returns the factorial of a number.'''
if num == 1:
return 1
return num*computeFactori... | """
This program calculates the factorial of a number.
It is an example program for the Pylint poster.
The function name doesn't follow the snake case.
"""
def compute_factorial(num):
"""Returns the factorial of a number."""
if num == 1:
return 1
return num * compute_factorial(num - 1)
print(comput... |
"""This problem was asked by Microsoft.
Given an array of numbers, find the length of the longest increasing subsequence in the array.
The subsequence does not necessarily have to be contiguous.
For example, given the array [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15],
the longest increasing subsequence has... | """This problem was asked by Microsoft.
Given an array of numbers, find the length of the longest increasing subsequence in the array.
The subsequence does not necessarily have to be contiguous.
For example, given the array [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15],
the longest increasing subsequence has... |
print('Hello World')
sauce = 'tomato'
order_description = """
Blah blah blah
"""
if sauce.startswith('toma'):
print("It's probably tomato..")
else:
print("Not tomato")
print(order_description)
| print('Hello World')
sauce = 'tomato'
order_description = '\nBlah blah blah\n'
if sauce.startswith('toma'):
print("It's probably tomato..")
else:
print('Not tomato')
print(order_description) |
"""
Functions for popular string operations.
The purpose of this module is to allow students to work with strings without having to
understand method calls. We do not provide all string methods as functions -- just the
most popular ones.
The functions that would normally return lists return tuples. That is because,... | """
Functions for popular string operations.
The purpose of this module is to allow students to work with strings without having to
understand method calls. We do not provide all string methods as functions -- just the
most popular ones.
The functions that would normally return lists return tuples. That is because,... |
# Time: O(n)
# Space: O(h), h is height of binary tree
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
# @param root, a tree node
# @param sum, an integer
# @return a boolean
def hasPathSum... | class Treenode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def has_path_sum(self, root, sum):
if root is None:
return False
if root.left is None and root.right is None and (root.val == sum):
... |
class Day():
def __init__(self, data_path):
with open(data_path, "r") as file:
for line in file:
self.instructions = line.strip()
def part1(self):
floor = 0
for char in self.instructions:
if char == '(':
floor += 1
elif... | class Day:
def __init__(self, data_path):
with open(data_path, 'r') as file:
for line in file:
self.instructions = line.strip()
def part1(self):
floor = 0
for char in self.instructions:
if char == '(':
floor += 1
elif ... |
# OpenWeatherMap API Key
weather_api_key = "d3bc8c276acb9f0ad7660e4353716e90"
# Google API Key
g_key = "AIzaSyDibsDuYSaDy7VFjswzeuRETk5kiCuRBhs"
| weather_api_key = 'd3bc8c276acb9f0ad7660e4353716e90'
g_key = 'AIzaSyDibsDuYSaDy7VFjswzeuRETk5kiCuRBhs' |
'''
Created on 31 Mar 2017
@author: Federico Cerutti <federico.cerutti@acm.org>
'''
def isfloat(value):
try:
float(value)
return True
except ValueError:
return False
def isint(value):
try:
int(value)
return True
except ValueError:
return False | """
Created on 31 Mar 2017
@author: Federico Cerutti <federico.cerutti@acm.org>
"""
def isfloat(value):
try:
float(value)
return True
except ValueError:
return False
def isint(value):
try:
int(value)
return True
except ValueError:
return False |
"""This module contains API-related exceptions."""
class APIError(Exception):
"""An exception denoting generic API errors.
This error is raised when the API returns invalid
response data, like invalid JSON.
"""
pass
class EmptyResponseError(APIError):
"""An exception denoting an empty API ... | """This module contains API-related exceptions."""
class Apierror(Exception):
"""An exception denoting generic API errors.
This error is raised when the API returns invalid
response data, like invalid JSON.
"""
pass
class Emptyresponseerror(APIError):
"""An exception denoting an empty API res... |
# Custom Functions:
def list_print(subject, dest=None):
for dia in subject:
if dest is not None:
print(dia, file=dest)
else:
print(dia)
# Creating the data to be saved.
man = []
other = []
try:
data = open('sketch.txt')
for line in data:
try:
... | def list_print(subject, dest=None):
for dia in subject:
if dest is not None:
print(dia, file=dest)
else:
print(dia)
man = []
other = []
try:
data = open('sketch.txt')
for line in data:
try:
(role, dialog) = line.split(':', 1)
dialog = d... |
def bmi_calculator(height, weight):
return (weight/(height**2)) * 702
# Write 4 unit tests and check that at least 2 of them are testing edge cases
# There are many different tests that could have been written for this question.
# Here are a few examples.
assert bmi_calculator(1, 1) == 702.0, 'Input arguments g... | def bmi_calculator(height, weight):
return weight / height ** 2 * 702
assert bmi_calculator(1, 1) == 702.0, 'Input arguments giving incorrect output'
assert bmi_calculator(100, 10000) == 702.0, 'Input arguments giving incorrect output'
assert bmi_calculator(1, 0) == 0, 'Input arguments giving incorrect output'
asse... |
# Source and destination file names.
test_source = "dangerous.txt"
test_destination = "dangerous.html"
# Keyword parameters passed to publish_file.
reader_name = "standalone"
parser_name = "rst"
writer_name = "html"
# Settings
settings_overrides['file_insertion_enabled'] = False
settings_overrides['raw_enabled'] = Fa... | test_source = 'dangerous.txt'
test_destination = 'dangerous.html'
reader_name = 'standalone'
parser_name = 'rst'
writer_name = 'html'
settings_overrides['file_insertion_enabled'] = False
settings_overrides['raw_enabled'] = False
settings_overrides['stylesheet_path'] = 'functional/input/data/html4css1.css' |
class Bank1Account(object):
tax = 1.0
def __init__(self, number):
self.number = number
self.__total = 0
def deposit(self, value):
self.__total += value
def withdraw(self, value):
self.__total -= value
# self.__total -= 1
self.__total -= type(self).tax
... | class Bank1Account(object):
tax = 1.0
def __init__(self, number):
self.number = number
self.__total = 0
def deposit(self, value):
self.__total += value
def withdraw(self, value):
self.__total -= value
self.__total -= type(self).tax
def get_total(self):
... |
#!/usr/bin/python3
""" Module of a inherited class Rectangle"""
BaseGeometry = __import__('7-base_geometry').BaseGeometry
class Rectangle(BaseGeometry):
""" Class inherited form BaseGeometry """
def __init__(self, width, height):
""" Initializes a new object Rectangle """
super().integer_valid... | """ Module of a inherited class Rectangle"""
base_geometry = __import__('7-base_geometry').BaseGeometry
class Rectangle(BaseGeometry):
""" Class inherited form BaseGeometry """
def __init__(self, width, height):
""" Initializes a new object Rectangle """
super().integer_validator('width', widt... |
"""matplotlib rc params for APS journals
Gives a dictionary with the proper sizes for APS journals.
Modified from:
- M.V. DePalatis, 2010-09-01. Licensed under the GNU GPL v3
- http://www.scipy.org/Cookbook/Matplotlib/LaTeX_Examples
Examples
--------
>>> import pylab
>>> from pylab import arange, pi, sin, co... | """matplotlib rc params for APS journals
Gives a dictionary with the proper sizes for APS journals.
Modified from:
- M.V. DePalatis, 2010-09-01. Licensed under the GNU GPL v3
- http://www.scipy.org/Cookbook/Matplotlib/LaTeX_Examples
Examples
--------
>>> import pylab
>>> from pylab import arange, pi, sin, co... |
# Copyright (c) IBM Corporation and Others. All Rights Reserved.
# very loosely based on icu.gyp from Chromium:
# Copyright (c) 2012 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.
{
'variables': {
'icu_src_derb': [... | {'variables': {'icu_src_derb': ['<(icu_path)/source/tools/genrb/derb.c', '<(icu_path)/source/tools/genrb/derb.cpp']}, 'includes': ['../../icu_config.gypi'], 'targets': [{'target_name': 'icu_uconfig_target', 'type': 'none', 'toolsets': ['target'], 'direct_dependent_settings': {'defines': []}}, {'target_name': 'icu_uconf... |
len,m=map(int,input().split())
tree=[0 for i in range(len+1)]
for i in range(m):
l,r=map(int,input().split())
tree[l]+=1
tree[r]-=1
sum=0
flag=0
for i in tree:
if i==0 and flag==0:
sum+=1
else:
flag+=i
print(sum) | (len, m) = map(int, input().split())
tree = [0 for i in range(len + 1)]
for i in range(m):
(l, r) = map(int, input().split())
tree[l] += 1
tree[r] -= 1
sum = 0
flag = 0
for i in tree:
if i == 0 and flag == 0:
sum += 1
else:
flag += i
print(sum) |
#!/usr/bin/env python
'''Provides an Extruder base class for the RepRap.
All extruders extend this class, and can therefore be chosen by the
user at runtime.
Copyright 2011 Joseph Lewis <joehms22@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Pub... | """Provides an Extruder base class for the RepRap.
All extruders extend this class, and can therefore be chosen by the
user at runtime.
Copyright 2011 Joseph Lewis <joehms22@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as publish... |
class ApiSidebar():
def __init__(self, hass, cfg):
self.hass = hass
@property
def panel(self):
return self.hass.data.get("frontend_panels", {})
def remove(self, _path):
if _path in self.panel:
self.hass.components.frontend.async_remove_panel(_path)
def add(se... | class Apisidebar:
def __init__(self, hass, cfg):
self.hass = hass
@property
def panel(self):
return self.hass.data.get('frontend_panels', {})
def remove(self, _path):
if _path in self.panel:
self.hass.components.frontend.async_remove_panel(_path)
def add(self,... |
nomes = ['CARLOS', 'JOAO', 'PEDRO']
idades = ['30', '25', '22']
rows = len(nomes)
for i in range(rows):
print(nomes[i] + ":" + idades[i])
#https://pt.stackoverflow.com/q/414318/101
| nomes = ['CARLOS', 'JOAO', 'PEDRO']
idades = ['30', '25', '22']
rows = len(nomes)
for i in range(rows):
print(nomes[i] + ':' + idades[i]) |
while 1:
user_number = int(input("Entersitive number: "))
if user_number > 0:
break
print("Do somet7hing with number!")
| while 1:
user_number = int(input('Entersitive number: '))
if user_number > 0:
break
print('Do somet7hing with number!') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.