content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Config:
DIR = "arm_now/"
kernel = "kernel"
dtb = "dtb"
rootfs = "rootfs.ext2"
arch = "arch"
KERNEL = DIR + "kernel"
DTB = DIR + "dtb"
ROOTFS = DIR + "rootfs.ext2"
ARCH = DIR + "arch"
DOWNLOAD_CACHE_DIR = "/tmp/arm_now"
qemu_options = {
"aarch64": ["aarch64", "-M virt -cpu... | class Config:
dir = 'arm_now/'
kernel = 'kernel'
dtb = 'dtb'
rootfs = 'rootfs.ext2'
arch = 'arch'
kernel = DIR + 'kernel'
dtb = DIR + 'dtb'
rootfs = DIR + 'rootfs.ext2'
arch = DIR + 'arch'
download_cache_dir = '/tmp/arm_now'
qemu_options = {'aarch64': ['aarch64', "-M virt -cpu co... |
def Capital_letter(func): #This function receive another function
def Wrapper(text):
return func(text).upper()
return Wrapper
@Capital_letter
def message(name):
return f'{name}, you have received a message'
print(message('Yery')) | def capital_letter(func):
def wrapper(text):
return func(text).upper()
return Wrapper
@Capital_letter
def message(name):
return f'{name}, you have received a message'
print(message('Yery')) |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
class Encumbrance:
speed_multiplier = 1
to_hit_modifier = 0
@classmethod
def get_encumbrance_state(cls, w... | class Encumbrance:
speed_multiplier = 1
to_hit_modifier = 0
@classmethod
def get_encumbrance_state(cls, weight, capacity):
if weight <= capacity:
return Unencumbered
elif weight <= 1.5 * capacity:
return Burdened
elif weight <= 2 * capacity:
r... |
_base_ = [
'../_base_/models/r50_multihead.py',
'../_base_/datasets/imagenet_color_sz224_4xbs64.py',
'../_base_/default_runtime.py',
]
# model settings
model = dict(
backbone=dict(frozen_stages=4),
head=dict(num_classes=1000))
# optimizer
optimizer = dict(
type='SGD',
lr=0.01,
momentum... | _base_ = ['../_base_/models/r50_multihead.py', '../_base_/datasets/imagenet_color_sz224_4xbs64.py', '../_base_/default_runtime.py']
model = dict(backbone=dict(frozen_stages=4), head=dict(num_classes=1000))
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001, nesterov=True, paramwise_options={'(bn|ln... |
n = int(input())
if n == 2:
print(2)
else:
if n%2 == 0:
n -= 1
for i in range(n, 1, -2):
flag = True
size = int(pow(i,0.5))
for j in range(3, size+1):
if i % j == 0:
flag = False
break
if flag:
prin... | n = int(input())
if n == 2:
print(2)
else:
if n % 2 == 0:
n -= 1
for i in range(n, 1, -2):
flag = True
size = int(pow(i, 0.5))
for j in range(3, size + 1):
if i % j == 0:
flag = False
break
if flag:
print(i)
... |
# More conditional structures
"""- multi-way
if (...) :
...
elif (...) :
...
else :
..."""
"""- The try/except structures
try:
...
except:
...
(except only runs if try fails)"""
'''astr = 'Saul'
try:
print('123')
istr = int(astr)
print('456')
except:
ist... | """- multi-way
if (...) :
...
elif (...) :
...
else :
..."""
'- The try/except structures\n\ntry:\n ...\nexcept:\n ...\n\n(except only runs if try fails)'
"astr = 'Saul'\ntry:\n print('123')\n istr = int(astr)\n print('456')\nexcept:\n istr = -1\n print('using e... |
height = int(input())
for i in range(height,0,-1):
for j in range(i,height):
print(end=" ")
for j in range(1,i+1):
if(i%2 != 0):
c = chr(i+64)
print(c,end=" ")
else:
print(i,end=" ")
print()
# Sample Input :- 5
# Output :-
# E E E E E
... | height = int(input())
for i in range(height, 0, -1):
for j in range(i, height):
print(end=' ')
for j in range(1, i + 1):
if i % 2 != 0:
c = chr(i + 64)
print(c, end=' ')
else:
print(i, end=' ')
print() |
class PysetoError(Exception):
"""
Base class for all exceptions.
"""
pass
class NotSupportedError(PysetoError):
"""
An Exception occurred when the function is not supported for the key object.
"""
pass
class EncryptError(PysetoError):
"""
An Exception occurred when an encry... | class Pysetoerror(Exception):
"""
Base class for all exceptions.
"""
pass
class Notsupportederror(PysetoError):
"""
An Exception occurred when the function is not supported for the key object.
"""
pass
class Encrypterror(PysetoError):
"""
An Exception occurred when an encryptio... |
"""
Django integration for Salesforce using Heroku Connect.
Model classes inheriting from :class:`HerokuConnectModel<heroku_connect.models.HerokuConnectModel>`
can easily be registered with `Heroku Connect`_, which then keeps their tables
in the Heroku database in sync with Salesforce.
.. _`Heroku Connect`: https://d... | """
Django integration for Salesforce using Heroku Connect.
Model classes inheriting from :class:`HerokuConnectModel<heroku_connect.models.HerokuConnectModel>`
can easily be registered with `Heroku Connect`_, which then keeps their tables
in the Heroku database in sync with Salesforce.
.. _`Heroku Connect`: https://d... |
# ----------------------------------------------------------------------------
# CLASSES: nightly
#
# Test Case: moveoperators.py
#
# Tests: plots - Pseudocolor, Mesh, FilledBoundary
# operators - Erase, Isosurface, Reflect, Slice, Transform
#
# Defect ID: '1837
#
# Programmer: Brad Whitloc... | def init_annotation():
a = annotation_attributes()
turn_off_all_annotations(a)
a.axes2D.visible = 1
a.axes2D.xAxis.label.visible = 0
a.axes2D.yAxis.label.visible = 0
a.axes2D.xAxis.title.visible = 0
a.axes2D.yAxis.title.visible = 0
a.axes3D.bboxFlag = 1
set_annotation_attributes(a)
... |
gibber = input("What's the gibberish?: ")
direction = input("Left/Right?: ")
retry = int(input("How much do you want to try?: "))
charlist = "abcdefghijklmnopqrstuvwxyz "
dictionary = {}
index = 0
for e in charlist:
dictionary[e] = index
index += 1
jump = 1
if direction == "Right":
for cycle in range(retr... | gibber = input("What's the gibberish?: ")
direction = input('Left/Right?: ')
retry = int(input('How much do you want to try?: '))
charlist = 'abcdefghijklmnopqrstuvwxyz '
dictionary = {}
index = 0
for e in charlist:
dictionary[e] = index
index += 1
jump = 1
if direction == 'Right':
for cycle in range(retry)... |
def find(f, df, ddf, a, b, eps):
fa = f(a)
dfa = df(a)
ddfa = ddf(a)
fb = f(b)
dfb = df(b)
ddfb = ddf(b)
if not (
(fa * fb < 0) and
((dfa > 0 and dfb > 0) or (dfa < 0 and dfb < 0)) and
((ddfa > 0 and ddfb > 0) or (ddfa < 0 and ddfb < 0))
):
return
cu... | def find(f, df, ddf, a, b, eps):
fa = f(a)
dfa = df(a)
ddfa = ddf(a)
fb = f(b)
dfb = df(b)
ddfb = ddf(b)
if not (fa * fb < 0 and (dfa > 0 and dfb > 0 or (dfa < 0 and dfb < 0)) and (ddfa > 0 and ddfb > 0 or (ddfa < 0 and ddfb < 0))):
return
currx = a if fa * ddfa > 0 else b
pr... |
class Card:
# Game card.
def __init__(self, number, color, ability, wild):
# Number on the face of the card
self.number = number
# Which color is the thing
self.color = color
# Draw 2 / Reverse etc
self.ability = ability
# Wild card?
self.wild = wild
def __eq__(self, other):
return (self.num... | class Card:
def __init__(self, number, color, ability, wild):
self.number = number
self.color = color
self.ability = ability
self.wild = wild
def __eq__(self, other):
return self.number == other.number and self.color == other.color and (self.ability == other.ability) an... |
"""
This is simply a file to store all of the docstrings for the documentation for CBSim. I place it into a new file so that it doesn't cause clutter for the scripts
"""
def docs_physics():
""" \n Physics implementation in CBSim
===============================
General
-------
Following the 2005 paper by Fred Cur... | """
This is simply a file to store all of the docstrings for the documentation for CBSim. I place it into a new file so that it doesn't cause clutter for the scripts
"""
def docs_physics():
"""
Physics implementation in CBSim
===============================
General
-------
Following the 2005 paper by Fred Cu... |
#!/usr/bin/env python3
def get_input() -> list[str]:
with open('./input', 'r') as f:
return [v for v in [v.strip() for v in f.readlines()] if v]
def _get_input_raw() -> list[str]:
with open('./input', 'r') as f:
return [v.strip() for v in f.readlines()]
def get_input_by_chunks() -> list[lis... | def get_input() -> list[str]:
with open('./input', 'r') as f:
return [v for v in [v.strip() for v in f.readlines()] if v]
def _get_input_raw() -> list[str]:
with open('./input', 'r') as f:
return [v.strip() for v in f.readlines()]
def get_input_by_chunks() -> list[list[str]]:
raw_input = _... |
#Anagram Detection
#reads 2 strings
st1 = input("Enter a string: ")
st2 = input("Enter another string: ")
#check if their lengths are equal
if len(st1) == len(st2):
#create a list
n = len(st1)-1
list1 = list()
while n >= 0:
list1.append(st1[n])
n -= 1
m = len(st2)-1
list2 = list()
while m >= 0:... | st1 = input('Enter a string: ')
st2 = input('Enter another string: ')
if len(st1) == len(st2):
n = len(st1) - 1
list1 = list()
while n >= 0:
list1.append(st1[n])
n -= 1
m = len(st2) - 1
list2 = list()
while m >= 0:
list2.append(st2[m])
m -= 1
list1.sort()
... |
TURNS = {"R": -1j, "L": 1j}
instructions = tuple((inst[0], int(inst[1:])) for inst in open("input").read().strip().split(", "))
position, direction = (0 + 0j), (0 + 1j)
visited_locations = set()
first_twice_location = 0 + 0j
for turn, dist in instructions:
direction *= TURNS[turn]
for _ in range(dist):
... | turns = {'R': -1j, 'L': 1j}
instructions = tuple(((inst[0], int(inst[1:])) for inst in open('input').read().strip().split(', ')))
(position, direction) = (0 + 0j, 0 + 1j)
visited_locations = set()
first_twice_location = 0 + 0j
for (turn, dist) in instructions:
direction *= TURNS[turn]
for _ in range(dist):
... |
#!/usr/bin/env python3
# Define n
n = 5
# Store Outputs
sum = 0
facr = 1
# Loop
for i in range(1,n+1):
sum = sum + i
facr = facr * i
print(n,sum,facr)
| n = 5
sum = 0
facr = 1
for i in range(1, n + 1):
sum = sum + i
facr = facr * i
print(n, sum, facr) |
"""
'abba' & 'baab' == true
'abba' & 'bbaa' == true
'abba' & 'abbba' == false
'abba' & 'abca' == false
Write function:
anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) => ['aabb', 'bbaa']
anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']) => ['carer', 'racer']
anagrams('laser', ['lazing', 'lazy'... | """
'abba' & 'baab' == true
'abba' & 'bbaa' == true
'abba' & 'abbba' == false
'abba' & 'abca' == false
Write function:
anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) => ['aabb', 'bbaa']
anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']) => ['carer', 'racer']
anagrams('laser', ['lazing', 'lazy'... |
AppLayout(header=header_button,
left_sidebar=None,
center=center_button,
right_sidebar=None,
footer=footer_button)
| app_layout(header=header_button, left_sidebar=None, center=center_button, right_sidebar=None, footer=footer_button) |
class Result:
def __init__(self, result: bool, error = None, item = None, list = [], comment = None):
self.result = result
self.error = error
self.item = item
self.list = list
self.comment = comment
| class Result:
def __init__(self, result: bool, error=None, item=None, list=[], comment=None):
self.result = result
self.error = error
self.item = item
self.list = list
self.comment = comment |
# Copyright 2019 StreamSets Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... | batch = sdc.createBatch()
record = sdc.createRecord('bindings test')
record.value = {}
record.value['batchSize'] = sdc.batchSize
record.value['numThreads'] = sdc.numThreads
record.value['lastOffsets'] = sdc.lastOffsets
record.value['params'] = sdc.userParams
record.value['isStopped()'] = sdc.isStopped()
record.value['p... |
def select_outside(low, high, *values):
result = []
for v in values:
if (v < low) or (v > high):
result.append(v)
return result
print(select_outside(0, 1.0, 0.3, -0.2, -0.5, 0.4, 1.7))
| def select_outside(low, high, *values):
result = []
for v in values:
if v < low or v > high:
result.append(v)
return result
print(select_outside(0, 1.0, 0.3, -0.2, -0.5, 0.4, 1.7)) |
"""
Escriba un programa que simule un relog usando bucles while
-------------------- Algoritmo ------------------------
1) Crear tres variables de tipo entero que almacenen la hora, los minutos y los segundos e inicalizarlas en 0.
2) Crear un bucle while que recorra la variable hora 24 veces
3) Dentro del bucle que ... | """
Escriba un programa que simule un relog usando bucles while
-------------------- Algoritmo ------------------------
1) Crear tres variables de tipo entero que almacenen la hora, los minutos y los segundos e inicalizarlas en 0.
2) Crear un bucle while que recorra la variable hora 24 veces
3) Dentro del bucle que ... |
'''
Python tuple is a sequence,
which can store heterogeneous data
types such as integers, floats, strings,
lists, and dictionaries. Tuples are written
with round brackets and individual objects
within the tuple are separated by a comma.
The two biggest differences between a tuple
and a list are that a tup... | """
Python tuple is a sequence,
which can store heterogeneous data
types such as integers, floats, strings,
lists, and dictionaries. Tuples are written
with round brackets and individual objects
within the tuple are separated by a comma.
The two biggest differences between a tuple
and a list are that a tuple is im... |
'''Exceptions.
:copyright: 2021, Jeroen van der Heijden <jeroen@cesbit.com>
'''
class CompileError(Exception):
pass
class KeywordError(CompileError):
pass
class ReKeywordsChangedError(CompileError):
pass
class NameAssignedError(CompileError):
pass
class MissingRefError(CompileError):
pass... | """Exceptions.
:copyright: 2021, Jeroen van der Heijden <jeroen@cesbit.com>
"""
class Compileerror(Exception):
pass
class Keyworderror(CompileError):
pass
class Rekeywordschangederror(CompileError):
pass
class Nameassignederror(CompileError):
pass
class Missingreferror(CompileError):
pass
cla... |
""" According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton
devised by the British mathematician John Horton Conway in 1970."
Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its
eight neighbors (horizontal... | """ According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton
devised by the British mathematician John Horton Conway in 1970."
Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its
eight neighbors (horizontal... |
class sensorVariables:
def __init__(self):
self.elevation = None
self.vfov = None
self.north = None
self.roll = None
self.range = None
self.azimuth = None
self.model = None
self.fov = None
self.type = None
self.version = None
@cla... | class Sensorvariables:
def __init__(self):
self.elevation = None
self.vfov = None
self.north = None
self.roll = None
self.range = None
self.azimuth = None
self.model = None
self.fov = None
self.type = None
self.version = None
@cla... |
"""Holds the base class for the SCIM system"""
def _create_error_text(method: str, endpoint: str) -> str:
return f"The {method} method is not implemented for {endpoint}"
class SCIMSystem:
"""Represents a system behind the SCIM 2.0 interface.
Methods are named according to to RFC7644 section 3.2 and foll... | """Holds the base class for the SCIM system"""
def _create_error_text(method: str, endpoint: str) -> str:
return f'The {method} method is not implemented for {endpoint}'
class Scimsystem:
"""Represents a system behind the SCIM 2.0 interface.
Methods are named according to to RFC7644 section 3.2 and follow... |
class Handler:
"""
Base handler for client connections.
"""
def disconnect(self, code):
"""
The Consumer's connection was closed.
:param code:
:return:
"""
pass
def handle(self, content):
"""
Called when the handler should process som... | class Handler:
"""
Base handler for client connections.
"""
def disconnect(self, code):
"""
The Consumer's connection was closed.
:param code:
:return:
"""
pass
def handle(self, content):
"""
Called when the handler should process som... |
glossary = {
'and' : 'Logical and operator',
'or' : 'Logical or operator',
'False' : 'Boolean false value',
'True' : 'Boolean true value',
'for' : 'To create for loop',
}
print("and: " + glossary['and'] + "\n")
print("or: " + glossary['or'] + "\n")
print("False: " + glossary['False'] + "\n")
pr... | glossary = {'and': 'Logical and operator', 'or': 'Logical or operator', 'False': 'Boolean false value', 'True': 'Boolean true value', 'for': 'To create for loop'}
print('and: ' + glossary['and'] + '\n')
print('or: ' + glossary['or'] + '\n')
print('False: ' + glossary['False'] + '\n')
print('True: ' + glossary['True'] +... |
def test_add():
class Number:
def __add__(self, other):
return 4 + other
def __radd__(self, other):
return other + 4
a = Number()
assert 3 + a == 7
assert a + 3 == 7
| def test_add():
class Number:
def __add__(self, other):
return 4 + other
def __radd__(self, other):
return other + 4
a = number()
assert 3 + a == 7
assert a + 3 == 7 |
MinZoneNum = 0
MaxZoneNum = 999
UberZoneEntId = 0
LevelMgrEntId = 1000
EditMgrEntId = 1001
| min_zone_num = 0
max_zone_num = 999
uber_zone_ent_id = 0
level_mgr_ent_id = 1000
edit_mgr_ent_id = 1001 |
allwords=[]
for category in bag_of_words.keys():
for word in bag_of_words[category].keys():
if word not in allwords:
allwords.append(word)
freq_term_matrix=[]
for category in bag_of_words.keys():
new=[]
for column in range(0,len(allwords)):
if allwords[column] in bag_of_words[category].keys():
new.append(... | allwords = []
for category in bag_of_words.keys():
for word in bag_of_words[category].keys():
if word not in allwords:
allwords.append(word)
freq_term_matrix = []
for category in bag_of_words.keys():
new = []
for column in range(0, len(allwords)):
if allwords[column] in bag_of_wo... |
# Copyright (C) 2015-2021 Swift Navigation Inc.
# Contact: https://support.swiftnav.com
#
# This source is subject to the license found in the file 'LICENSE' which must
# be be distributed together with this source. All other rights reserved.
#
# THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIN... | class Nulllogger(object):
"""
NullLogger
The :class:`NullLogger` does not log records.
"""
def __call__(self, msg, **metadata):
pass
def __enter__(self):
return self
def flush(self):
pass
def read(self, s=None):
pass
def write(self, s=None):
... |
"""
Function:
In functions we can pass mutable and immutable parameters
Immutable parameter every time when we change its value
new object is created and old object is discarded
"""
def add(x):
x += 10
return x
x = 5
print("Value of x: ",x)
print("ID of x: ",id(x))
x = add(x)
print("Value of x: "... | """
Function:
In functions we can pass mutable and immutable parameters
Immutable parameter every time when we change its value
new object is created and old object is discarded
"""
def add(x):
x += 10
return x
x = 5
print('Value of x: ', x)
print('ID of x: ', id(x))
x = add(x)
print('Value of x: ', x)
print('... |
fh = open("Headlines", 'r')
Word = input("Type your Word Here:")
S = " "
count = 1
while S:
S = fh.readline()
L = S.split()
if Word in L:
print("Line Number:", count, ":", S)
count += 1
| fh = open('Headlines', 'r')
word = input('Type your Word Here:')
s = ' '
count = 1
while S:
s = fh.readline()
l = S.split()
if Word in L:
print('Line Number:', count, ':', S)
count += 1 |
string = "ugknbfddgicrmopn"
string = "aaa"
string = "jchzalrnumimnmhp"
string = "haegwjzuvuyypxyu"
string = "dvszwmarrgswjxmb"
def check_vowels(string):
vowels = 0
vowels += string.count("a")
vowels += string.count("e")
vowels += string.count("i")
vowels += string.count("o")
vowels += string.count("u")
r... | string = 'ugknbfddgicrmopn'
string = 'aaa'
string = 'jchzalrnumimnmhp'
string = 'haegwjzuvuyypxyu'
string = 'dvszwmarrgswjxmb'
def check_vowels(string):
vowels = 0
vowels += string.count('a')
vowels += string.count('e')
vowels += string.count('i')
vowels += string.count('o')
vowels += string.co... |
def lonely_integer(m):
answer = 0
for x in m:
answer = answer ^ x
return answer
a = int(input())
b = map(int, input().strip().split(" "))
print(lonely_integer(b))
| def lonely_integer(m):
answer = 0
for x in m:
answer = answer ^ x
return answer
a = int(input())
b = map(int, input().strip().split(' '))
print(lonely_integer(b)) |
# -*- coding: utf-8 -*-
"""
Module for testing the autodocsumm
Just a dummy module with some class definitions
"""
#: to test if the data is included
test_data = None
def test_func():
"""Test if function is contained in autosummary"""
pass
class Class_CallTest(object):
"""A class defining a __call__ ... | """
Module for testing the autodocsumm
Just a dummy module with some class definitions
"""
test_data = None
def test_func():
"""Test if function is contained in autosummary"""
pass
class Class_Calltest(object):
"""A class defining a __call__ method"""
def __get__(self, instance, owner):
retu... |
""" Given an integer array nums, you need to find one continuous subarray that if
you only sort this subarray in ascending order, then the whole array will be
sorted in ascending order. Return the shortest such subarray and output its
leftgth.
Example 1: Input: nums = [2,6,4,8,10,9,15] Output: 5
... | """ Given an integer array nums, you need to find one continuous subarray that if
you only sort this subarray in ascending order, then the whole array will be
sorted in ascending order. Return the shortest such subarray and output its
leftgth.
Example 1: Input: nums = [2,6,4,8,10,9,15] Output: 5
... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
def main():
age = 30
print(age)
print(30)
# Variable name snake case
friend_age = 23
print(friend_age)
PI = 3.14159
print(PI)
RADIANS_TO_DEGREES = 180/PI
print(RADIANS_TO_DEGREES)
if __name__ == "__main__":
main() | def main():
age = 30
print(age)
print(30)
friend_age = 23
print(friend_age)
pi = 3.14159
print(PI)
radians_to_degrees = 180 / PI
print(RADIANS_TO_DEGREES)
if __name__ == '__main__':
main() |
# -*- coding: utf-8 -*-
# Every time function slice return a new object
students = ['Tom', 'Mary', 'Ken', 'Billy', 'Mike']
# Get continuously subset of a range
slice1 = students[0:3]
print(slice1)
slice2 = students[:3]
print(slice2)
slice3 = students[-3:] # last three
print(slice3)
slice4 = students[2:4] # 3rd ... | students = ['Tom', 'Mary', 'Ken', 'Billy', 'Mike']
slice1 = students[0:3]
print(slice1)
slice2 = students[:3]
print(slice2)
slice3 = students[-3:]
print(slice3)
slice4 = students[2:4]
print(slice4)
slice5 = students[:]
print(slice5)
print(list(range(100)[0:20:2]))
print(list(range(100)[::5]))
print('abcde'[0:3]) |
class LogHolder():
def __init__(self, dirpath, name):
self.dirpath = dirpath
self.name = name
self.reset(suffix='train')
def write_to_file(self):
with open(self.dirpath + f'{self.name}-metrics-{self.suffix}.txt', 'a') as file:
for i in self.metric_holder:
file.write(str(i) + ' ')
with open(self.di... | class Logholder:
def __init__(self, dirpath, name):
self.dirpath = dirpath
self.name = name
self.reset(suffix='train')
def write_to_file(self):
with open(self.dirpath + f'{self.name}-metrics-{self.suffix}.txt', 'a') as file:
for i in self.metric_holder:
... |
# This program calculates the sum of a series
# of numbers entered by the user.
max = 5 # The maximum number
# Initialize an accumulator variable.
total = 0.0
# Explain what we are doing.
print('This program calculates the sum of')
print(max, 'numbers you will enter.')
# Get the numbers and accumulate them.
fo... | max = 5
total = 0.0
print('This program calculates the sum of')
print(max, 'numbers you will enter.')
for counter in range(max):
number = int(input('Enter a number: '))
total = total + number
print('The total is', total) |
class Solution:
def maximum69Number (self, num: int) -> int:
try:
numstr = list(str(num))
numstr[numstr.index('6')]='9'
return int("".join(numstr))
except:
return num | class Solution:
def maximum69_number(self, num: int) -> int:
try:
numstr = list(str(num))
numstr[numstr.index('6')] = '9'
return int(''.join(numstr))
except:
return num |
class CurvedUniverse():
def __init__(self, shape_or_k = 0):
self.shapes = {'o': -1, 'f': 0, 'c': 1}
self.set_shape_or_k(shape_or_k)
def set_shape_or_k(self, shape_or_k):
if type(shape_or_k) == str:
self.__dict__['shape'] = shape_or_k
self.__dict__['k'] = self.shapes[shape_or_k]
else:
self.__dict__['... | class Curveduniverse:
def __init__(self, shape_or_k=0):
self.shapes = {'o': -1, 'f': 0, 'c': 1}
self.set_shape_or_k(shape_or_k)
def set_shape_or_k(self, shape_or_k):
if type(shape_or_k) == str:
self.__dict__['shape'] = shape_or_k
self.__dict__['k'] = self.shapes... |
keep_going = "y"
while keep_going.startswith("y"):
a_name = input("Enter a name: ").strip()
with open("users.txt", "a") as file:
file.write(a_name + "; ")
keep_going = input("Insert another name? (y/n) ").strip() | keep_going = 'y'
while keep_going.startswith('y'):
a_name = input('Enter a name: ').strip()
with open('users.txt', 'a') as file:
file.write(a_name + '; ')
keep_going = input('Insert another name? (y/n) ').strip() |
# Conditional Statements in Python
# If-else statements
age = int(input("Input your age: "))
if age > 17:
print("You are an adult")
else:
print("You are a minor")
#If-elif-else statements
number = int(input("Input a number: "))
if number > 5:
print("Is greater than 5")
elif number == 5:
print("Is eq... | age = int(input('Input your age: '))
if age > 17:
print('You are an adult')
else:
print('You are a minor')
number = int(input('Input a number: '))
if number > 5:
print('Is greater than 5')
elif number == 5:
print('Is equal to 5')
else:
print('Is less than 5') |
# Your App secret key
SECRET_KEY = "TXxWqZHAILwElJF2bKR8"
DEFAULT_FEATURE_FLAGS: Dict[str, bool] = {
# Note that: RowLevelSecurityFilter is only given by default to the Admin role
# and the Admin Role does have the all_datasources security permission.
# But, if users create a specific role with access to R... | secret_key = 'TXxWqZHAILwElJF2bKR8'
default_feature_flags: Dict[str, bool] = {'ROW_LEVEL_SECURITY': True}
superset_webserver_port = 8088
favicons = [{'href': '/static/assets/images/favicon.png'}]
app_icon = '/static/assets/images/superset-logo-horiz.png'
app_icon_width = 126
babel_default_locale = 'en'
babel_default_fo... |
N, Q = tuple(map(int, input().split()))
LRT = [tuple(map(int, input().split())) for _ in range(Q)]
A = [0 for _ in range(N)]
for left, right, t in LRT:
for i in range(left - 1, right):
A[i] = t
print(*A, sep="\n")
| (n, q) = tuple(map(int, input().split()))
lrt = [tuple(map(int, input().split())) for _ in range(Q)]
a = [0 for _ in range(N)]
for (left, right, t) in LRT:
for i in range(left - 1, right):
A[i] = t
print(*A, sep='\n') |
"""
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
4 4 4 4 3 3 0
| |
[3,3,5,0,0,3,1,4]
| |
0 0 2 2 2 3 3 4
... | """
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
4 4 4 4 3 3 0
| |
[3,3,5,0,0,3,1,4]
| |
0 0 2 2 2 3 3 4
... |
# AUTHOR: Dharma Teja
# Python3 Concept:sum of digits in given number
# GITHUB: https://github.com/dharmateja03
number=int(input()) #enter input
l=list(str(number))
nums=list(map(int,l))
print(sum(nums))
| number = int(input())
l = list(str(number))
nums = list(map(int, l))
print(sum(nums)) |
class DataThing:
def __init__(self, _x):
self.y = int(input("Enter a Y Value: "))
self.x = _x
def __str__(self):
ret = "{} {}".format(self.x, self.y)
return ret
def createSome():
x = int(input("Enter a X Value: "))
ret = DataThing(x)
return ret
... | class Datathing:
def __init__(self, _x):
self.y = int(input('Enter a Y Value: '))
self.x = _x
def __str__(self):
ret = '{} {}'.format(self.x, self.y)
return ret
def create_some():
x = int(input('Enter a X Value: '))
ret = data_thing(x)
return ret
a = data_thi... |
class Graph():
def __init__(self, vertices):
self.V=vertices
self.graph=[[0 for col in range(vertices)] for row in range(vertices)]
def printSolution(self, dist):
print ("Vertex \tDistance from Source")
for node in range(self.V):
print (node, "\t\t\t", dist[node])
def minDistance(self, d... | class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for col in range(vertices)] for row in range(vertices)]
def print_solution(self, dist):
print('Vertex \tDistance from Source')
for node in range(self.V):
print(node, '\t\t\t', dist[node])
... |
"""
Problem Link: https://binarysearch.io/problems/Linked-list-delete-last-occurrence-of-value
"""
# class LLNode:
# def __init__(self, val, next=None):
# self.val = val
# self.next = next
class Solution:
def solve(self, node, target):
# Write your code here
latest = None
... | """
Problem Link: https://binarysearch.io/problems/Linked-list-delete-last-occurrence-of-value
"""
class Solution:
def solve(self, node, target):
latest = None
latest_prev = None
prev = None
if node.val == target:
prev = None
latest = node
current = ... |
#input_column: b,string,VARCHAR(100),100,None,None
#input_type: SET
#output_column: b,string,VARCHAR(100),100,None,None
#output_type: EMITS
#!/bin/bash
ls -l /tmp
| ls - l / tmp |
class BaseGenerator:
pass
class CharGenerator(BaseGenerator):
pass
| class Basegenerator:
pass
class Chargenerator(BaseGenerator):
pass |
# The self keyword is used when you want a method or
# attribute to be for a specific object. This means that,
# down below, each Tesla object can have different maxSpeed
# and colors from each other.
class Tesla:
def __init__(self, maxSpeed=120, color="red"):
self.maxSpeed = maxSpeed
self.color =... | class Tesla:
def __init__(self, maxSpeed=120, color='red'):
self.maxSpeed = maxSpeed
self.color = color
def change(self, c):
self.color = c
p1 = tesla(140, 'blue')
p2 = tesla(100, 'blue')
p1.change('green')
print(p1.color)
p2.change('yellow')
print(p2.color) |
### Author: Dag Wieers <dag@wieers.com>
class dstat_plugin(dstat):
"""
Top interrupt
Displays the name of the most frequent interrupt
"""
def __init__(self):
self.name = 'most frequent'
self.vars = ('interrupt',)
self.type = 's'
self.width = 20
self.scale = ... | class Dstat_Plugin(dstat):
"""
Top interrupt
Displays the name of the most frequent interrupt
"""
def __init__(self):
self.name = 'most frequent'
self.vars = ('interrupt',)
self.type = 's'
self.width = 20
self.scale = 0
self.intset1 = []
self... |
_DAGGER = """
java_library(
name = "dagger",
exports = [
":dagger-api",
"@maven//javax/inject:javax_inject",
],
exported_plugins = [":plugin"],
visibility = ["//visibility:public"],
)
raw_jvm_import(
name = "dagger-api",
jar = "@com_google_dagger_dagger//maven",
visibili... | _dagger = '\njava_library(\n name = "dagger",\n exports = [\n ":dagger-api",\n "@maven//javax/inject:javax_inject",\n ],\n exported_plugins = [":plugin"],\n visibility = ["//visibility:public"],\n)\n\nraw_jvm_import(\n name = "dagger-api",\n jar = "@com_google_dagger_dagger//maven",\n... |
algorithm = "fourier"
potential = {}
potential["potential"] = "x/4"
T = 8.5
dt = 0.01
eps = 0.1
f = 2.0
ngn = 4096
basis_size = 4
P = 1.0j
Q = 1.0
S = 0.0
parameters = [ (P, Q, S, 1.0, -2.0) ]
coefficients = [[(0, 1.0)]]
write_nth = 2
| algorithm = 'fourier'
potential = {}
potential['potential'] = 'x/4'
t = 8.5
dt = 0.01
eps = 0.1
f = 2.0
ngn = 4096
basis_size = 4
p = 1j
q = 1.0
s = 0.0
parameters = [(P, Q, S, 1.0, -2.0)]
coefficients = [[(0, 1.0)]]
write_nth = 2 |
"""
This file contains the rules on which this abstraction of Robot Challenge is based on.
"""
SIZE_OF_BOARD = 5
STARTING_POSITION = (0, 0)
STARTING_DIRECTION = "NORTH"
ROTATE_DIRECTIONS = [
"LEFT",
"RIGHT",
]
DIRECTIONS = [
"NORTH",
"EAST",
"SOUTH",
"WEST",
]
DIRECTION_STEP_MAPPING = {
... | """
This file contains the rules on which this abstraction of Robot Challenge is based on.
"""
size_of_board = 5
starting_position = (0, 0)
starting_direction = 'NORTH'
rotate_directions = ['LEFT', 'RIGHT']
directions = ['NORTH', 'EAST', 'SOUTH', 'WEST']
direction_step_mapping = {'NORTH': (0, 1), 'EAST': (1, 0), 'WEST'... |
class MessageKeyAttributes(object):
def __init__(self, remote_jid, from_me, id, participant):
self._remote_jid = remote_jid
self._from_me = from_me
self._id = id
self._participant = participant
def __str__(self):
attrs = []
if self.remote_jid is not None:
... | class Messagekeyattributes(object):
def __init__(self, remote_jid, from_me, id, participant):
self._remote_jid = remote_jid
self._from_me = from_me
self._id = id
self._participant = participant
def __str__(self):
attrs = []
if self.remote_jid is not None:
... |
amt_torch, ifo_light, amt_max, ifo_count, ifo_dgree = int(input()), [False for a in range(360)], 0, 0, 0
def fill_light(ifo_start, ifo_stop):
for each_spot in range(ifo_start, ifo_stop): ifo_light[each_spot] = True
for each_torch in range(amt_torch):
[ifo_start, ifo_stop] = [int(b) for b in input().split()... | (amt_torch, ifo_light, amt_max, ifo_count, ifo_dgree) = (int(input()), [False for a in range(360)], 0, 0, 0)
def fill_light(ifo_start, ifo_stop):
for each_spot in range(ifo_start, ifo_stop):
ifo_light[each_spot] = True
for each_torch in range(amt_torch):
[ifo_start, ifo_stop] = [int(b) for b in input()... |
#
# PySNMP MIB module PHIHONG-PoE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PHIHONG-PoE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:31:30 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_size_constraint, single_value_constraint, constraints_intersection, value_range_constraint) ... |
class InvalidRating(ValueError): pass
class AuthRequired(TypeError): pass
class CannotChangeVote(Exception): pass
class CannotDeleteVote(Exception): pass
class IPLimitReached(Exception): pass | class Invalidrating(ValueError):
pass
class Authrequired(TypeError):
pass
class Cannotchangevote(Exception):
pass
class Cannotdeletevote(Exception):
pass
class Iplimitreached(Exception):
pass |
'''
oneflux.util
For license information:
see LICENSE file or headers in oneflux.__init__.py
General utilities for oneflux
@author: Gilberto Pastorello
@contact: gzpastorello@lbl.gov
@date: 2017-01-31
'''
| """
oneflux.util
For license information:
see LICENSE file or headers in oneflux.__init__.py
General utilities for oneflux
@author: Gilberto Pastorello
@contact: gzpastorello@lbl.gov
@date: 2017-01-31
""" |
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if prices is None or len(prices) == 0:
return 0
low = prices[0]
res = 0
for i in range(1, len(prices)):
res = max(res, p... | class Solution(object):
def max_profit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if prices is None or len(prices) == 0:
return 0
low = prices[0]
res = 0
for i in range(1, len(prices)):
res = max(res, prices[i] ... |
class ParserException(Exception):
def __init__(self, message, filename=None, xml_exception=None, xml_element=None):
Exception.__init__(self, message)
self._message = message
self._filename = filename
self._xml_exception = xml_exception
self._xml_element = xml_element
@pr... | class Parserexception(Exception):
def __init__(self, message, filename=None, xml_exception=None, xml_element=None):
Exception.__init__(self, message)
self._message = message
self._filename = filename
self._xml_exception = xml_exception
self._xml_element = xml_element
@p... |
def main(filepath):
ranges = [(int(x),int(y)-1) for x,y in [tuple(x.split(':')) for x in open(filepath,'r').read().replace(' ','').split('\n')]]
delay = 0; caught = True
severity = sum(depth*(scan_range+1) for depth, scan_range in ranges if depth%(2*scan_range) == 0)
while caught:
delay += 1... | def main(filepath):
ranges = [(int(x), int(y) - 1) for (x, y) in [tuple(x.split(':')) for x in open(filepath, 'r').read().replace(' ', '').split('\n')]]
delay = 0
caught = True
severity = sum((depth * (scan_range + 1) for (depth, scan_range) in ranges if depth % (2 * scan_range) == 0))
while caught:... |
# https://www.coursera.org/learn/competitive-programming-core-skills/lecture/wSCUn/defining-solution-set
#input: n items with given weights w, w2, w3 and costs c1, c2 etc
# largest total cost of thetems whose total weights doesnt exceed W.
store= [] #defaultdict(int)
def nested_fors(n,firstfor,x):
global store... | store = []
def nested_fors(n, firstfor, x):
global store
w_total = 0
c_total = 0
n = 3
w = 5
w = [3, 2, 5]
c = [2, 3, 6]
if firstfor < n:
for x[firstfor] in ['0', '1']:
nested_fors(n, firstfor + 1, x)
else:
m = ''
if x[0] == '1':
w_tot... |
class TransmissionData(object,IDisposable):
"""
A class representing information on all external file references
in a document.
TransmissionData(other: TransmissionData)
"""
def Dispose(self):
""" Dispose(self: TransmissionData) """
pass
@staticmethod
def DocumentIsNotTransmitted(fileP... | class Transmissiondata(object, IDisposable):
"""
A class representing information on all external file references
in a document.
TransmissionData(other: TransmissionData)
"""
def dispose(self):
""" Dispose(self: TransmissionData) """
pass
@staticmethod
def document_is_not_t... |
def ScaleGlyph(glyph, scale, r):
glyph['advanceWidth'] = r(glyph['advanceWidth'] * scale)
if 'advanceHeight' in glyph:
glyph['advanceHeight'] = r(glyph['advanceHeight'] * scale)
glyph['verticalOrigin'] = r(glyph['verticalOrigin'] * scale)
rm = [ 'stemH', 'stemV', 'hintMasks', 'contourMasks', 'instructions' ... | def scale_glyph(glyph, scale, r):
glyph['advanceWidth'] = r(glyph['advanceWidth'] * scale)
if 'advanceHeight' in glyph:
glyph['advanceHeight'] = r(glyph['advanceHeight'] * scale)
glyph['verticalOrigin'] = r(glyph['verticalOrigin'] * scale)
rm = ['stemH', 'stemV', 'hintMasks', 'contourMasks',... |
test = {
'name': 'Recursion',
'points': 0,
'suites': [
{
'cases': [
{
'code': r"""
>>> def f(a, b):
... if a > b:
... return f(a - 3, 2 * b)
... elif a < b:
... return f(b // 2, a)
... else:
... | test = {'name': 'Recursion', 'points': 0, 'suites': [{'cases': [{'code': '\n >>> def f(a, b):\n ... if a > b:\n ... return f(a - 3, 2 * b)\n ... elif a < b:\n ... return f(b // 2, a)\n ... else:\n ... return b\n ... |
class Side:
BUY = 'BUY'
SELL = 'SELL'
class TimeInForce:
GTC = 'GTC' # Good Til Cancel (default value on BTSE)
IOC = 'IOC' # Immediate or Cancel
FIVEMIN = 'FIVEMIN' # 5 mins
HOUR = 'HOUR' # 1 hour
TWELVEHOUR = 'TWELVEHOUR' # 12 hours
DAY = 'DAY' # 1 day
WEEK = 'WEEK' # 1 wee... | class Side:
buy = 'BUY'
sell = 'SELL'
class Timeinforce:
gtc = 'GTC'
ioc = 'IOC'
fivemin = 'FIVEMIN'
hour = 'HOUR'
twelvehour = 'TWELVEHOUR'
day = 'DAY'
week = 'WEEK'
month = 'MONTH'
class Ordertype:
limit = 'LIMIT'
market = 'MARKET'
oco = 'OCO'
class Txtype:
l... |
"""
Profile ../profile-datasets-py/standard54lev_allgas_seaonly/001.py
file automaticaly created by prof_gen.py script
"""
self["ID"] = "../profile-datasets-py/standard54lev_allgas_seaonly/001.py"
self["Q"] = numpy.array([ 1.41160700e+00, 2.34372900e+00, 3.53382100e+00,
4.62808600e+00, 5.4... | """
Profile ../profile-datasets-py/standard54lev_allgas_seaonly/001.py
file automaticaly created by prof_gen.py script
"""
self['ID'] = '../profile-datasets-py/standard54lev_allgas_seaonly/001.py'
self['Q'] = numpy.array([1.411607, 2.343729, 3.533821, 4.628086, 5.437759, 5.97528, 5.999964, 5.999964, 5.92326... |
dadosPessoas = []
dadoTemporario = []
c = maiorPeso = menorPeso = 0
while True:
dadoTemporario.append(str(input('Nome: ')))
dadoTemporario.append(float(input('Peso(KG): ')))
dadosPessoas.append(dadoTemporario[:])
if c == 0: # Posso usar len(dadoTemporario) para fazer o contador
maiorPeso = dado... | dados_pessoas = []
dado_temporario = []
c = maior_peso = menor_peso = 0
while True:
dadoTemporario.append(str(input('Nome: ')))
dadoTemporario.append(float(input('Peso(KG): ')))
dadosPessoas.append(dadoTemporario[:])
if c == 0:
maior_peso = dadoTemporario[1]
menor_peso = dadoTemporario[1... |
string = input()
results = []
for i, char in enumerate(string):
if i != 0 and char.isupper():
results.append('_')
results.append(char.lower())
print("".join(results))
| string = input()
results = []
for (i, char) in enumerate(string):
if i != 0 and char.isupper():
results.append('_')
results.append(char.lower())
print(''.join(results)) |
#!/usr/bin/env python
# Copyright Contributors to the Open Shading Language project.
# SPDX-License-Identifier: BSD-3-Clause
# https://github.com/imageworks/OpenShadingLanguage
command = testshade("--groupoutputs -od half -o a a.exr -o b b.exr -o c c.exr -g 64 64 test")
outputs = [ "a.exr", "b.exr", "c.exr", "out.txt... | command = testshade('--groupoutputs -od half -o a a.exr -o b b.exr -o c c.exr -g 64 64 test')
outputs = ['a.exr', 'b.exr', 'c.exr', 'out.txt'] |
def AssignFare(c,a,d):
if d<500:
t_fare=(a*200)+(c*(200/2))
elif (d<1000) and (d>=500):
t_fare=(a*300)+(c*(300/2))
else:
t_fare=(a*500)+(c*(500/2))
return t_fare
child=int(input("enter the number of children: "))
adult=int(input("enter the number of adults: "))
distan... | def assign_fare(c, a, d):
if d < 500:
t_fare = a * 200 + c * (200 / 2)
elif d < 1000 and d >= 500:
t_fare = a * 300 + c * (300 / 2)
else:
t_fare = a * 500 + c * (500 / 2)
return t_fare
child = int(input('enter the number of children: '))
adult = int(input('enter the number of adu... |
def insertion_sort(array): #function to sort array using insertion sort
comparison=0
shift=0
for i in range(1,len(array)):
j=i-1
val=array[i]
while(j>=0 and val<array[j]):
shift+=1
comparison+=1
array[j+1]=array[j]
array[j]=val
... | def insertion_sort(array):
comparison = 0
shift = 0
for i in range(1, len(array)):
j = i - 1
val = array[i]
while j >= 0 and val < array[j]:
shift += 1
comparison += 1
array[j + 1] = array[j]
array[j] = val
j -= 1
co... |
# Some more if statements
banned_users = ['andrew','carolina','david']
user = 'marie'
if user not in banned_users:
print(user.title()+", you can post a response if you wish.")
car = 'subaru'
print("Is car == 'subaru'? I predict True")
print(car == 'subaru')
print("Is car == 'audi'? I predict false")
print(car == '... | banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
print(user.title() + ', you can post a response if you wish.')
car = 'subaru'
print("Is car == 'subaru'? I predict True")
print(car == 'subaru')
print("Is car == 'audi'? I predict false")
print(car == 'audi')
age = 20
if age ... |
def extract_pos(doc, pos, return_list = True, lower_case = True):
tokens = [t.text for t in doc if t.pos_ == pos]
if lower_case == True:
tokens = [t.lower() for t in tokens]
if return_list == False:
tokens = ', '.join(tokens)
return tokens
| def extract_pos(doc, pos, return_list=True, lower_case=True):
tokens = [t.text for t in doc if t.pos_ == pos]
if lower_case == True:
tokens = [t.lower() for t in tokens]
if return_list == False:
tokens = ', '.join(tokens)
return tokens |
class Solution:
def countBattleships(self, board):
"""
:type board: List[List[str]]
:rtype: int
"""
return sum(val == 'X' for i, row in enumerate(board) for j, val in enumerate(row) if (j == 0 or board[i][j - 1] == '.') and (i == 0 or board[i - 1][j] == '.')) | class Solution:
def count_battleships(self, board):
"""
:type board: List[List[str]]
:rtype: int
"""
return sum((val == 'X' for (i, row) in enumerate(board) for (j, val) in enumerate(row) if (j == 0 or board[i][j - 1] == '.') and (i == 0 or board[i - 1][j] == '.'))) |
class Queue:
def __init__(self):
self.items=[]
def enqueue(self,item):
self.items.append(item)
def dequeue(self):
return self.items.pop(0)
def is_empty(self):
if self.items==[]:
return True
return False
if __name__=="__main__":
q=Queue()
q.en... | class Queue:
def __init__(self):
self.items = []
def enqueue(self, item):
self.items.append(item)
def dequeue(self):
return self.items.pop(0)
def is_empty(self):
if self.items == []:
return True
return False
if __name__ == '__main__':
q = queue... |
class Point3f(
object,
IEquatable[Point3f],
IComparable[Point3f],
IComparable,
IEpsilonFComparable[Point3f],
):
"""
Represents the three coordinates of a point in three-dimensional space,
using System.Single-precision floating point numbers.
Point3f(x: Single,y: Single,z... | class Point3F(object, IEquatable[Point3f], IComparable[Point3f], IComparable, IEpsilonFComparable[Point3f]):
"""
Represents the three coordinates of a point in three-dimensional space,
using System.Single-precision floating point numbers.
Point3f(x: Single,y: Single,z: Single)
"""
def compare_to(se... |
#kaynak https://randomnerdtutorials.com/micropython-esp32-esp8266-access-point-ap/
def web_page():
html = """<html><head><meta name="viewport" content="width=device-width, initial-scale=1"></head>
<body><h1>Hello, World!</h1></body></html>"""
return html
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bi... | def web_page():
html = '<html><head><meta name="viewport" content="width=device-width, initial-scale=1"></head>\n <body><h1>Hello, World!</h1></body></html>'
return html
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)
while True:
(conn, addr) = s.accept()
print('Got a... |
async def execute(client, **kwargs):
print("Please wait...")
await client.logout()
print("Client sucsessfully logged out")
return 1
if __name__ == "__main__":
pass
| async def execute(client, **kwargs):
print('Please wait...')
await client.logout()
print('Client sucsessfully logged out')
return 1
if __name__ == '__main__':
pass |
"""
Localisation Settings to conduct Localisation by Clustering before CAE training and DA.
"""
class LoaderSetting():
def __init__(self, data, pickle, percentage, dim, domain, otherDomain):
self.DATA_FP = data
self.X_PICKLE = pickle
self.PERCENTAGE = percentage
self.DIM = dim
... | """
Localisation Settings to conduct Localisation by Clustering before CAE training and DA.
"""
class Loadersetting:
def __init__(self, data, pickle, percentage, dim, domain, otherDomain):
self.DATA_FP = data
self.X_PICKLE = pickle
self.PERCENTAGE = percentage
self.DIM = dim
... |
class Character:
"""Represents a single character"""
def __init__(self, char, was_guessed=False):
self.char = char
self.was_guessed = was_guessed
def get_char(self):
""" Returns the char data"""
return self.char
def show_char(self):
"""
Returns the char ... | class Character:
"""Represents a single character"""
def __init__(self, char, was_guessed=False):
self.char = char
self.was_guessed = was_guessed
def get_char(self):
""" Returns the char data"""
return self.char
def show_char(self):
"""
Returns the char... |
suffix = "ack"
praefixe = "JKLMNOPQ"
for praefix in praefixe:
if praefix == "O" or praefix == "Q":
print(praefix + "u" + suffix)
else:
print(praefix + suffix) | suffix = 'ack'
praefixe = 'JKLMNOPQ'
for praefix in praefixe:
if praefix == 'O' or praefix == 'Q':
print(praefix + 'u' + suffix)
else:
print(praefix + suffix) |
"""Constants for the Switcher integration."""
DOMAIN = "switcher_kis"
CONF_DEVICE_PASSWORD = "device_password"
CONF_PHONE_ID = "phone_id"
DATA_DEVICE = "device"
SIGNAL_SWITCHER_DEVICE_UPDATE = "switcher_device_update"
ATTR_AUTO_OFF_SET = "auto_off_set"
ATTR_ELECTRIC_CURRENT = "electric_current"
ATTR_REMAINING_TIME... | """Constants for the Switcher integration."""
domain = 'switcher_kis'
conf_device_password = 'device_password'
conf_phone_id = 'phone_id'
data_device = 'device'
signal_switcher_device_update = 'switcher_device_update'
attr_auto_off_set = 'auto_off_set'
attr_electric_current = 'electric_current'
attr_remaining_time = 'r... |
class UknownValueError(ValueError):
"""Raised when the provided value is unkown or is not
in a specified list or dictionary map
"""
def __init__(self, provided_value=None, known_values=None):
if provided_value and known_values:
if isinstance(known_values, list):
supe... | class Uknownvalueerror(ValueError):
"""Raised when the provided value is unkown or is not
in a specified list or dictionary map
"""
def __init__(self, provided_value=None, known_values=None):
if provided_value and known_values:
if isinstance(known_values, list):
sup... |
def fatorial(p1):
f = 1
indice = p1
while indice >= 1:
f *= indice
indice -= 1
return f
def dobro(p1):
return p1 * 2
def triplo(p1):
return p1 * 3
| def fatorial(p1):
f = 1
indice = p1
while indice >= 1:
f *= indice
indice -= 1
return f
def dobro(p1):
return p1 * 2
def triplo(p1):
return p1 * 3 |
# This program says hello world and asks for my name.
print('Hello, world!')
print('what is your name?') # ask for the name
my_Name = input()
print('It is nice to meet you, '+ my_Name)
print('The length of your name is:')
print(len(my_Name))
print(len(' '))
print('What is your age?') # ask for the age
my_Age = inpu... | print('Hello, world!')
print('what is your name?')
my__name = input()
print('It is nice to meet you, ' + my_Name)
print('The length of your name is:')
print(len(my_Name))
print(len(' '))
print('What is your age?')
my__age = input()
print('You will be ' + str(int(my_Age) + 1) + ' in a year') |
class Failsafe:
'''
Catches I/O errors.
'''
def __init__(self, func):
self.function = func
def __call__(self, *args):
try:
self.function(*args)
except IOError:
print('An I/O error was caught when opening file "{}"'.format(args[0]))
... | class Failsafe:
"""
Catches I/O errors.
"""
def __init__(self, func):
self.function = func
def __call__(self, *args):
try:
self.function(*args)
except IOError:
print('An I/O error was caught when opening file "{}"'.format(args[0]))
@Failsafe
def ris... |
# TIMEBOMB: report me
a = 1 # TIMEBOMB (jsmith): report me
# TIMEBOMB: do not report me (pragma). # no-check-fixmes
# TIMEBOMB(jsmith - 2020-04-25): report me
a = "TIMEBOMB" # do not report me (within a string)
a = "TIMEBOMB" # do not report me (within a string)
# TIMEBOMB - FEWTURE-BOOM: report me
| a = 1
a = 'TIMEBOMB'
a = 'TIMEBOMB' |
class Store:
# Here will be the instance stored.
__instance = None
@staticmethod
def getInstance():
""" Static access method. """
if Store.__instance == None:
Store()
return Store.__instance
def __init__(self):
""" Virtually private constructor. """
... | class Store:
__instance = None
@staticmethod
def get_instance():
""" Static access method. """
if Store.__instance == None:
store()
return Store.__instance
def __init__(self):
""" Virtually private constructor. """
if Store.__instance != None:
... |
class Node:
def __init__(self, x: int, next: "Node" = None, random: "Node" = None):
self.val = int(x)
self.next = next
self.random = random
class Solution:
def copyRandomList(self, head: "Node") -> "Node":
if not head:
return None
node = head
new_nod... | class Node:
def __init__(self, x: int, next: 'Node'=None, random: 'Node'=None):
self.val = int(x)
self.next = next
self.random = random
class Solution:
def copy_random_list(self, head: 'Node') -> 'Node':
if not head:
return None
node = head
new_node... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.