content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
'''
Reversed Queue
Write a function that takes a queue as an input and returns a reversed version of it.
'''
# Solution
class LinkedListNode:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.num_elements = 0
self.head = None
... | """
Reversed Queue
Write a function that takes a queue as an input and returns a reversed version of it.
"""
class Linkedlistnode:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.num_elements = 0
self.head = None
def push... |
class Solution:
def maximalSquare(self, matrix):
if not matrix:
return 0
row = [0] * len(matrix[0])
res = 0
for i in xrange(len(matrix)):
top_left = 0
for j in xrange(len(matrix[i])):
if matrix[i][j] == "0":
... | class Solution:
def maximal_square(self, matrix):
if not matrix:
return 0
row = [0] * len(matrix[0])
res = 0
for i in xrange(len(matrix)):
top_left = 0
for j in xrange(len(matrix[i])):
if matrix[i][j] == '0':
to... |
class Ring:
"""Parent class/interface for all rings to inherit from"""
def __init__(self, name, element_type, is_commutative=False):
self.name = name
self.element_type = element_type
self.is_commutative = is_commutative
# Stuff we need to implement in child classes
def one(self... | class Ring:
"""Parent class/interface for all rings to inherit from"""
def __init__(self, name, element_type, is_commutative=False):
self.name = name
self.element_type = element_type
self.is_commutative = is_commutative
def one(self):
raise NotImplementedError
def zero... |
optimizer = dict(type='Adam', lr=0.001)
optimizer_config = dict(grad_clip=None)
lr_config = dict(policy='poly', power=0.9)
total_epochs = 5000
checkpoint_config = dict(interval=10)
log_config = dict(interval=5, hooks=[dict(type='TextLoggerHook')])
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
r... | optimizer = dict(type='Adam', lr=0.001)
optimizer_config = dict(grad_clip=None)
lr_config = dict(policy='poly', power=0.9)
total_epochs = 5000
checkpoint_config = dict(interval=10)
log_config = dict(interval=5, hooks=[dict(type='TextLoggerHook')])
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
r... |
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Command-journalling persistence framework inspired by Prevayler.
This package is deprecated since Twisted 11.0.
Maintainer: Itamar Shtull-Trauring
"""
| """
Command-journalling persistence framework inspired by Prevayler.
This package is deprecated since Twisted 11.0.
Maintainer: Itamar Shtull-Trauring
""" |
# Simple game in python
print('Hi, welcome to the Tim quiz!')
print('Try to get as many questions correct as possible...')
totalQuestions = 4
score = 0
ans = input('1. What is the name of my youtube channel? ')
if ans.lower() == 'tech with tim':
print('Correct!')
score += 1
else:
print('In... | print('Hi, welcome to the Tim quiz!')
print('Try to get as many questions correct as possible...')
total_questions = 4
score = 0
ans = input('1. What is the name of my youtube channel? ')
if ans.lower() == 'tech with tim':
print('Correct!')
score += 1
else:
print('Incorrect')
ans = input('2. What is my age?... |
# add this file to your .gitignore file of the project
LOCAL_SETTINGS = dict(
media_root='/Users/user/projects/project/media',
path='/Users/user/projects/project',
virtualenv_path='/Users/user/virtualenvs/project',
)
| local_settings = dict(media_root='/Users/user/projects/project/media', path='/Users/user/projects/project', virtualenv_path='/Users/user/virtualenvs/project') |
# Copyright (c) 2022 {{cookiecutter.author_name}}
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
"""Version information for {{cookiecutter.project_name}}.
This file is imported by ``{{cookiecutter.package_name}}.__init__``, and parsed by
``setup.py``.
"""
# Note, that dev... | """Version information for {{cookiecutter.project_name}}.
This file is imported by ``{{cookiecutter.package_name}}.__init__``, and parsed by
``setup.py``.
"""
__version__ = '1.0.0.dev1' |
def tw(f,t,st):
for x in range(t):
f.write("\t")
nl = True
if st[-1] == "#":
nl = False
st = st[:-1]
f.write(st)
if nl:
f.write("\n")
def write_property_lua(f, tab, name, value, pref = ""):
tw(f, tab, '%s{ name = "%s",' % (pref, name))
tab = tab + 1
if (type(value)==str):
tw(f, tab, 'value = "%s... | def tw(f, t, st):
for x in range(t):
f.write('\t')
nl = True
if st[-1] == '#':
nl = False
st = st[:-1]
f.write(st)
if nl:
f.write('\n')
def write_property_lua(f, tab, name, value, pref=''):
tw(f, tab, '%s{ name = "%s",' % (pref, name))
tab = tab + 1
if ty... |
fileout = open("requests.sh", "w")
for i in range(1,57):
if i >= 10:
s = "0" + str(i)
else:
s = "00" + str(i)
fileout.write("curl -s -H 'Content-Type: application/json' -H " + '"Authorization: Bearer `gcloud auth print-access-token`"' + " https://speech.googleapis.com/v1/speech:recognize -d" + ''' "{'config': ... | fileout = open('requests.sh', 'w')
for i in range(1, 57):
if i >= 10:
s = '0' + str(i)
else:
s = '00' + str(i)
fileout.write("curl -s -H 'Content-Type: application/json' -H " + '"Authorization: Bearer `gcloud auth print-access-token`"' + ' https://speech.googleapis.com/v1/speech:recognize -d... |
def define_env(env):
"Definition of the module"
@env.macro
def feedback(title, section, slug):
email_address = f"{section}+{slug}@technotes.jakoubek.net"
md = "\n\n## Feedback / Kontakt\n\n"
md += f"Wenn Sie Fragen oder Anregungen zum Artikel *{title}* haben, senden Sie mir bitte ei... | def define_env(env):
"""Definition of the module"""
@env.macro
def feedback(title, section, slug):
email_address = f'{section}+{slug}@technotes.jakoubek.net'
md = '\n\n## Feedback / Kontakt\n\n'
md += f'Wenn Sie Fragen oder Anregungen zum Artikel *{title}* haben, senden Sie mir bitt... |
class Solution:
# # Greedy (Accepted), O(n) time, O(1) space
# def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
# plots = len(flowerbed)
# flowerbed.append(0)
# prev = planted = 0
# for i in range(plots):
# if flowerbed[i] == 0:
# if pr... | class Solution:
def can_place_flowers(self, A: List[int], N: int) -> bool:
for (i, x) in enumerate(A):
if not x and (i == 0 or A[i - 1] == 0) and (i == len(A) - 1 or A[i + 1] == 0):
n -= 1
A[i] = 1
return N <= 0 |
# PyZ3950_parsetab.py
# This file is automatically generated. Do not edit.
_lr_method = 'SLR'
_lr_signature = '\xfc\xb2\xa8\xb7\xd9\xe7\xad\xba"\xb2Ss\'\xcd\x08\x16'
_lr_action_items = {'QUOTEDVALUE':([18,12,14,0,26,],[1,1,1,1,1,]),'LOGOP':([3,5,20,4,6,27,19,24,25,13,22,1,],[-5,-8,-4,-14,14,14,14,-9,-6,-13,-7,-12,]... | _lr_method = 'SLR'
_lr_signature = 'ü²¨·Ùç\xadº"²Ss\'Í\x08\x16'
_lr_action_items = {'QUOTEDVALUE': ([18, 12, 14, 0, 26], [1, 1, 1, 1, 1]), 'LOGOP': ([3, 5, 20, 4, 6, 27, 19, 24, 25, 13, 22, 1], [-5, -8, -4, -14, 14, 14, 14, -9, -6, -13, -7, -12]), 'SET': ([12, 14, 0, 26], [10, 10, 10, 10]), 'WORD': ([12, 14, 0, 5, 18, ... |
#
# PySNMP MIB module RSPAN-MGMT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RSPAN-MGMT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:50:21 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... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, constraints_intersection, constraints_union, single_value_constraint) ... |
class Node:
def __init__(self, declaration_list):
self.declaration_list = declaration_list
def visit(self):
context = {"type": "program"}
return self.declaration_list.visit(context)
| class Node:
def __init__(self, declaration_list):
self.declaration_list = declaration_list
def visit(self):
context = {'type': 'program'}
return self.declaration_list.visit(context) |
"""
Problem Description
The program takes a list from the user and finds the cumulative
sum of a list where the ith element is the sum of the first i+1 elements from the original list.
Problem Solution
1. Declare an empty list and initialise to an empty list.
2. Consider a for loop to accept values for the list.... | """
Problem Description
The program takes a list from the user and finds the cumulative
sum of a list where the ith element is the sum of the first i+1 elements from the original list.
Problem Solution
1. Declare an empty list and initialise to an empty list.
2. Consider a for loop to accept values for the list.
3. Ta... |
"""Application deployment configuration parameters."""
PROTOCOL = 'http'
HOSTNAME = 'localhost'
PORT = 6040
| """Application deployment configuration parameters."""
protocol = 'http'
hostname = 'localhost'
port = 6040 |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 22 11:20:42 2021
@author: Keisha
"""
class Bird:
def intro(self):
print("There are man y types of birds.")
def flight(self):
print("Most of the birds can fly ut some caqnnot.")
class sparrow(Bird):
def flight(s... | """
Created on Tue Jun 22 11:20:42 2021
@author: Keisha
"""
class Bird:
def intro(self):
print('There are man y types of birds.')
def flight(self):
print('Most of the birds can fly ut some caqnnot.')
class Sparrow(Bird):
def flight(self):
print('Sparrows can fly.')
class Ostri... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def _diameterBTree(self,root):
if not root:
return 0
l = self._diameterBTree(root.left)
r = self._diameterBTree... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def _diameter_b_tree(self, root):
if not root:
return 0
l = self._diameterBTree(root.left)
r = self._diameterBTree(root.right)
self.ans = ... |
class Modification:
def __init__(self):
self.AAs=[]
self.mass=0.0
self.NL={}
self.DI={}
self.factor=1
self.name=""
self.ID=-1
def setAAs(self, newAAlist):
self.AAs=newAAlist
return True
def getAAs(self):
return self.AAs
d... | class Modification:
def __init__(self):
self.AAs = []
self.mass = 0.0
self.NL = {}
self.DI = {}
self.factor = 1
self.name = ''
self.ID = -1
def set_a_as(self, newAAlist):
self.AAs = newAAlist
return True
def get_a_as(self):
r... |
class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def append(self,newdata):
new_node=Node(newdata)
if self.head is None:
self.head=new_node
return
temp=se... | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def append(self, newdata):
new_node = node(newdata)
if self.head is None:
self.head = new_node
return
tem... |
"""
AS PYTHON DOESN'T HAVE CONSTANT DECLARATION, THE NEXT METHODS
RETURN THE VALUES WHO NEED CONSTANT BEHAVIOR.
"""
def VGL_SHAPE_NCHANNELS():
return 0
def VGL_SHAPE_WIDTH():
return 1
def VGL_SHAPE_HEIGHT():
return 2
def VGL_SHAPE_LENGTH():
return 3
def VGL_MAX_DIM():
return 10
def VGL_ARR_SHAPE_SIZE():
r... | """
AS PYTHON DOESN'T HAVE CONSTANT DECLARATION, THE NEXT METHODS
RETURN THE VALUES WHO NEED CONSTANT BEHAVIOR.
"""
def vgl_shape_nchannels():
return 0
def vgl_shape_width():
return 1
def vgl_shape_height():
return 2
def vgl_shape_length():
return 3
def vgl_max_dim():
return 10
def vgl_arr_s... |
def simplest_numbers_generator():
"""Simplest Number Generator, yielding only two values - 1 and 2.
Disclaimer: Use it just to trace how next and yield operators works.
This example is not useful in real world!
"""
num = 1
print("Yielding", num)
yield num
num +=1
print("Yielding", nu... | def simplest_numbers_generator():
"""Simplest Number Generator, yielding only two values - 1 and 2.
Disclaimer: Use it just to trace how next and yield operators works.
This example is not useful in real world!
"""
num = 1
print('Yielding', num)
yield num
num += 1
print('Y... |
""" --- What is wrong with this family? --- Simple
You have a list of family relationships between father and son.
Every element on this list has two elements. The first is the
father's name, the second is a son's name. All names in the family
are unique. Check if the family tree is correct. There are
no strangers in ... | """ --- What is wrong with this family? --- Simple
You have a list of family relationships between father and son.
Every element on this list has two elements. The first is the
father's name, the second is a son's name. All names in the family
are unique. Check if the family tree is correct. There are
no strangers in ... |
"""CSP (Constraint Satisfaction Problems) problems and solvers. (Chapter 6)."""
# CLASS FROM https://github.com/aimacode/aima-python/ slightly modified for performance (see tag @modified)
# the proof about performance can be found in the files original_results.txt and modified_results.txt
# @modified: removed unused i... | """CSP (Constraint Satisfaction Problems) problems and solvers. (Chapter 6)."""
class Csp:
"""This class describes finite-domain Constraint Satisfaction Problems.
A CSP is specified by the following inputs:
variables A list of variables; each is atomic (e.g. int or string).
domains A dict... |
class Error(Exception):
message = None
def __str__(self):
return repr(self.message)
class GSLZeroDivision(Error):
message = "GSL encountered zero division"
class GSLFailure(Error):
message = "GSL failed"
class GSLMemoryFailure(Error):
message = "GSL failed to allocate necessary memory"
... | class Error(Exception):
message = None
def __str__(self):
return repr(self.message)
class Gslzerodivision(Error):
message = 'GSL encountered zero division'
class Gslfailure(Error):
message = 'GSL failed'
class Gslmemoryfailure(Error):
message = 'GSL failed to allocate necessary memory'
... |
"""
Tema: Recursividad y Factoriales.
Curso: Pensamiento computacional.
Plataforma: Platzi.
Profesor: David Aroesti.
Alumno: @edinsonrequena.
"""
def factorial(n):
"""Calcula el factorial de n
n int > 0
returns n!
"""
print(n)
if n == 1:
return 1
return n * factorial(n ... | """
Tema: Recursividad y Factoriales.
Curso: Pensamiento computacional.
Plataforma: Platzi.
Profesor: David Aroesti.
Alumno: @edinsonrequena.
"""
def factorial(n):
"""Calcula el factorial de n
n int > 0
returns n!
"""
print(n)
if n == 1:
return 1
return n * factorial(n - ... |
# coding=utf-8
class TestTeamcityMessages:
def testPass(self):
pass
def testAssertEqual(self):
assert (True == True)
def testAssertEqualFails(self):
assert 1 == 2
def testAssertFalse(self):
assert False
def testException(self):
raise Exception("some exce... | class Testteamcitymessages:
def test_pass(self):
pass
def test_assert_equal(self):
assert True == True
def test_assert_equal_fails(self):
assert 1 == 2
def test_assert_false(self):
assert False
def test_exception(self):
raise exception('some exception') |
volatile = False
log_norm = False
# Maximal sequence length in training data
max_seq_len = 50
'''
Embedding layer
'''
# Size of word embedding of source word and target word
src_wemb_size = 512
trg_wemb_size = 512
'''
Encoder layer
'''
# Size of hidden units in encoder
enc_hid_size = 512
'''
Attention layer
'''
#... | volatile = False
log_norm = False
max_seq_len = 50
'\nEmbedding layer\n'
src_wemb_size = 512
trg_wemb_size = 512
'\nEncoder layer\n'
enc_hid_size = 512
'\nAttention layer\n'
align_size = 512
'\nDecoder layer\n'
dec_hid_size = 512
out_size = 512
drop_rate = 0.5
dir_model = 'wmodel'
dir_valid = 'wvalid'
dir_tests = 'wtes... |
# PROBLEM
#
# Now write a program that calculates the minimum fixed monthly payment needed
# in order to pay off a credit card balance within 12 months. By a fixed
# monthly payment, we mean a single number which does not change each month,
# but instead is a constant amount that will be paid each month.
#
# In this... | balance = 5000
annual_interest_rate = 0.18
def year_end_balance(balance, monthlyPayment):
"""
balance: outstanding balance on the credit card (int or float)
monthlyPayment: fixed monthly payment (int or float)
returns: ending balance on the credit card after 12 months (int or float)
"""
fo... |
##Hello World Example
#!/user/bin/env python3
print("Hello", "world!")
| print('Hello', 'world!') |
buttons = {
"brightness up": [9097, 4455, 635, 495, 629, 502, 632, 499, 636, 494, 630, 500, 603, 528, 627, 503, 632, 500, 603, 1628, 599, 1632, 606, 1625, 602, 1627, 600, 530, 604, 1626, 601, 1630, 628, 1603, 603, 529, 606, 525, 599, 532, 602, 530, 604, 528, 607, 524, 599, 532, 603, 528, 606, 1625, 610, 1622, 608, 1624... | buttons = {'brightness up': [9097, 4455, 635, 495, 629, 502, 632, 499, 636, 494, 630, 500, 603, 528, 627, 503, 632, 500, 603, 1628, 599, 1632, 606, 1625, 602, 1627, 600, 530, 604, 1626, 601, 1630, 628, 1603, 603, 529, 606, 525, 599, 532, 602, 530, 604, 528, 607, 524, 599, 532, 603, 528, 606, 1625, 610, 1622, 608, 1624,... |
# Haystack settings for running tests.
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = 'haystack_tests.db'
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'haystack',
'core',
]
ROOT_URLCONF = 'c... | database_engine = 'sqlite3'
database_name = 'haystack_tests.db'
installed_apps = ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'haystack', 'core']
root_urlconf = 'core.urls'
haystack_connections = {'default': {'ENGINE': 'core.tests.mock... |
def first_method():
"""First sibling package method."""
return 1
def second_method():
"""Second sibling package method."""
return 2
| def first_method():
"""First sibling package method."""
return 1
def second_method():
"""Second sibling package method."""
return 2 |
# Python program for implementation of MergeSort(Implement Divide and conquer)
# MergeSort(arr[], l, r)
# If r > l
# 1. Find the middle point to divide the array into two halves:
# middle m = l+ (r-l)/2
# 2. Call mergeSort for first half:
# Call mergeSort(arr, l, m)
# ... | def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
l = arr[:mid]
r = arr[mid:]
merge_sort(L)
merge_sort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
... |
# -*- coding: utf-8 -*-
"""Class to represent binary data as hexadecimal."""
class Hexdump(object):
"""Class that defines a hexadecimal representation formatter (hexdump)."""
@classmethod
def _FormatDataLine(cls, data, data_offset, data_size):
"""Formats binary data in a single line of hexadecimal represen... | """Class to represent binary data as hexadecimal."""
class Hexdump(object):
"""Class that defines a hexadecimal representation formatter (hexdump)."""
@classmethod
def __format_data_line(cls, data, data_offset, data_size):
"""Formats binary data in a single line of hexadecimal representation.
... |
class Component(object):
_env = None
_di = None
_args = None
_kwargs = None
def setDi(self, di):
self._di = di
def getDi(self):
return self._di
def getEnv(self):
return self._env
def setEnv(self, env):
self._env = env
def setAr... | class Component(object):
_env = None
_di = None
_args = None
_kwargs = None
def set_di(self, di):
self._di = di
def get_di(self):
return self._di
def get_env(self):
return self._env
def set_env(self, env):
self._env = env
def set_args(self, args):... |
with open('F:\\url.txt', 'r') as f:
list1 = f.readlines()
def remain720p(args):
return args.find('720P') > 0
list2 = filter(remain720p, list1)
with open('F:\\url2.txt', 'w') as f2:
for str2 in list2:
f2.writelines(str2) | with open('F:\\url.txt', 'r') as f:
list1 = f.readlines()
def remain720p(args):
return args.find('720P') > 0
list2 = filter(remain720p, list1)
with open('F:\\url2.txt', 'w') as f2:
for str2 in list2:
f2.writelines(str2) |
"""
This contains emperically derived constants from Hutto and Gilbert (2014)
"""
# (empirically derived mean sentiment intensity rating increase for booster words)
B_INCR = 0.293
B_DECR = -0.293
# (empirically derived mean sentiment intensity rating increase for using ALLCAPs to emphasize a word)
C_INCR = 0.733 # c... | """
This contains emperically derived constants from Hutto and Gilbert (2014)
"""
b_incr = 0.293
b_decr = -0.293
c_incr = 0.733
n_scalar = -0.74
before_but_scalar = 0.5
after_but_scalar = 1.5 |
def fib(i: int) -> int:
if i == 0 or i == 1:
return 1
return fib(i - 1) + fib(i - 2)
if __name__ == "__main__":
# Using a variable to workaround
# https://github.com/adsharma/py2many/issues/64
rv = fib(5)
print(rv)
| def fib(i: int) -> int:
if i == 0 or i == 1:
return 1
return fib(i - 1) + fib(i - 2)
if __name__ == '__main__':
rv = fib(5)
print(rv) |
"""Constants for the Shelly integration."""
COAP = "coap"
DATA_CONFIG_ENTRY = "config_entry"
DEVICE = "device"
DOMAIN = "shelly"
REST = "rest"
CONF_COAP_PORT = "coap_port"
DEFAULT_COAP_PORT = 5683
# Used in "_async_update_data" as timeout for polling data from devices.
POLLING_TIMEOUT_SEC = 18
# Refresh interval fo... | """Constants for the Shelly integration."""
coap = 'coap'
data_config_entry = 'config_entry'
device = 'device'
domain = 'shelly'
rest = 'rest'
conf_coap_port = 'coap_port'
default_coap_port = 5683
polling_timeout_sec = 18
rest_sensors_update_interval = 60
aioshelly_device_timeout_sec = 10
sleep_period_multiplier = 1.2
... |
"""Hass.io const variables."""
ATTR_DISCOVERY = 'discovery'
ATTR_ADDON = 'addon'
ATTR_NAME = 'name'
ATTR_SERVICE = 'service'
ATTR_CONFIG = 'config'
ATTR_UUID = 'uuid'
ATTR_USERNAME = 'username'
ATTR_PASSWORD = 'password'
X_HASSIO = 'X-HASSIO-KEY'
X_HASS_USER_ID = 'X-HASS-USER-ID'
X_HASS_IS_ADMIN = 'X-HASS-IS-ADMIN'
| """Hass.io const variables."""
attr_discovery = 'discovery'
attr_addon = 'addon'
attr_name = 'name'
attr_service = 'service'
attr_config = 'config'
attr_uuid = 'uuid'
attr_username = 'username'
attr_password = 'password'
x_hassio = 'X-HASSIO-KEY'
x_hass_user_id = 'X-HASS-USER-ID'
x_hass_is_admin = 'X-HASS-IS-ADMIN' |
#!/usr/bin/env python3
# coding=utf-8
# author: @netmanchris
# -*- coding: utf-8 -*-
"""
This module contains functions for authenticating to the Attelani Brid Air Purifier Device
API.
"""
class BridAuth:
"""
Object to hold the authentication data for the Brid API
Note currently, the Brid API requires no... | """
This module contains functions for authenticating to the Attelani Brid Air Purifier Device
API.
"""
class Bridauth:
"""
Object to hold the authentication data for the Brid API
Note currently, the Brid API requires no authentication. Auth object is created
to allow for caching of IP address of Brid... |
class Defaults(object):
window_size = 7
hidden_sizes = [300]
hidden_activation = 'relu'
max_vocab_size = 1000000
optimizer = 'sgd' # 'adam'
learning_rate = 0.1 # 1e-4
epochs = 20
iobes = True # Map tags to IOBES on input
max_tokens = None # Max dataset size in tokens
encodi... | class Defaults(object):
window_size = 7
hidden_sizes = [300]
hidden_activation = 'relu'
max_vocab_size = 1000000
optimizer = 'sgd'
learning_rate = 0.1
epochs = 20
iobes = True
max_tokens = None
encoding = 'utf-8'
output_drop_prob = 0.0
token_level_eval = False
verbosi... |
ATOM_COLORS = {
"C": "#c8c8c8",
"H": "#ffffff",
"N": "#8f8fff",
"S": "#ffc832",
"O": "#f00000",
"F": "#ffff00",
"P": "#ffa500",
"K": "#42f4ee",
"G": "#3f3f3f",
}
CHAIN_COLORS = {
"A": "#320000",
"B": "#8a2be2",
"C": "#ff4500",
"D": "#00bfff",
"E": "#ff00ff",
... | atom_colors = {'C': '#c8c8c8', 'H': '#ffffff', 'N': '#8f8fff', 'S': '#ffc832', 'O': '#f00000', 'F': '#ffff00', 'P': '#ffa500', 'K': '#42f4ee', 'G': '#3f3f3f'}
chain_colors = {'A': '#320000', 'B': '#8a2be2', 'C': '#ff4500', 'D': '#00bfff', 'E': '#ff00ff', 'F': '#ffff00', 'G': '#4682b4', 'H': '#ffb6c1', 'I': '#a52aaa', '... |
"""Ubuntu Laptop Monitoring - Django project to display laptop hardware status.
.. moduleauthor:: Alexander Dupuy <alex.dupuy@mac.com>
"""
| """Ubuntu Laptop Monitoring - Django project to display laptop hardware status.
.. moduleauthor:: Alexander Dupuy <alex.dupuy@mac.com>
""" |
class Config:
EPS = 1e-14
RPN_CLOBBER_POSITIVES = False
RPN_NEGATIVE_OVERLAP = 0.3
RPN_POSITIVE_OVERLAP = 0.7
RPN_FG_FRACTION = 0.5
RPN_BATCHSIZE = 300
RPN_BBOX_INSIDE_WEIGHTS = (1.0, 1.0, 1.0, 1.0)
RPN_POSITIVE_WEIGHT = -1.0
RPN_PRE_NMS_TOP_N = 12000
RPN_POST_NMS_TOP_N = 1000
... | class Config:
eps = 1e-14
rpn_clobber_positives = False
rpn_negative_overlap = 0.3
rpn_positive_overlap = 0.7
rpn_fg_fraction = 0.5
rpn_batchsize = 300
rpn_bbox_inside_weights = (1.0, 1.0, 1.0, 1.0)
rpn_positive_weight = -1.0
rpn_pre_nms_top_n = 12000
rpn_post_nms_top_n = 1000
... |
hps = {
"0351291110650853": {
"ott_len": 35,
"ott_percent": 129,
"ott_bw_up": 111,
"tps_qty_index": 65,
"max_risk_long": 85
},
"0561821341040643": {
"ott_len": 56,
"ott_percent": 182,
"ott_bw_up": 134,
"tps_qty_index": 104,
"max_risk_long": 64
},
"0351291110200403": {
"ott_len": 35,
"ott_pe... | hps = {'0351291110650853': {'ott_len': 35, 'ott_percent': 129, 'ott_bw_up': 111, 'tps_qty_index': 65, 'max_risk_long': 85}, '0561821341040643': {'ott_len': 56, 'ott_percent': 182, 'ott_bw_up': 134, 'tps_qty_index': 104, 'max_risk_long': 64}, '0351291110200403': {'ott_len': 35, 'ott_percent': 129, 'ott_bw_up': 111, 'tps... |
"""
A variety of examples to showcase useage of pix.
Note that some libraries or other thirdparty resources may be required to run
an example.
""" | """
A variety of examples to showcase useage of pix.
Note that some libraries or other thirdparty resources may be required to run
an example.
""" |
class Configuration(object):
def __init__(self, **kwargs):
for key, value in kwargs.items():
if isinstance(value, dict):
value = Configuration(**value)
setattr(self, key, value)
def to_dict(self):
rv = {}
for key, value in self.__dict__.items():
... | class Configuration(object):
def __init__(self, **kwargs):
for (key, value) in kwargs.items():
if isinstance(value, dict):
value = configuration(**value)
setattr(self, key, value)
def to_dict(self):
rv = {}
for (key, value) in self.__dict__.items... |
product = input()
day = input()
quantity = float(input())
price = 0
isError = False
if day == 'Saturday' or day == 'Sunday':
if product == 'banana':
price = 2.7
elif product == 'apple':
price = 1.25
elif product == 'orange':
price = 0.9
elif product == 'grapefruit':... | product = input()
day = input()
quantity = float(input())
price = 0
is_error = False
if day == 'Saturday' or day == 'Sunday':
if product == 'banana':
price = 2.7
elif product == 'apple':
price = 1.25
elif product == 'orange':
price = 0.9
elif product == 'grapefruit':
pric... |
# -*- coding: utf-8 -*-
class Precipitation(object):
def __init__(self, precipitation):
self.value = float(precipitation['value'])
try:
self.minValue = float(precipitation['minvalue'])
except KeyError:
self.minValue = None
try:
self.maxValue = fl... | class Precipitation(object):
def __init__(self, precipitation):
self.value = float(precipitation['value'])
try:
self.minValue = float(precipitation['minvalue'])
except KeyError:
self.minValue = None
try:
self.maxValue = float(precipitation['maxval... |
def run():
r.setpos(0,0,0)
| def run():
r.setpos(0, 0, 0) |
class Command:
TO_CN = 1
TO_EN = 2
JSON_FORMAT = 3
URL_ENCODE = 4
URL_DECODE = 5 | class Command:
to_cn = 1
to_en = 2
json_format = 3
url_encode = 4
url_decode = 5 |
# checking for armstrong number
a = input("Enter a number")
n = int(a)
S = 0
while n > 0:
d = n % 10
S = S + d * d * d
n = n / 10
if int(a) == S:
print("Armstrong Number")
else:
print("Not an Armstrong Number")
| a = input('Enter a number')
n = int(a)
s = 0
while n > 0:
d = n % 10
s = S + d * d * d
n = n / 10
if int(a) == S:
print('Armstrong Number')
else:
print('Not an Armstrong Number') |
class BuildEnvironmentError(Exception):
def __init__(self, msg, build_env):
self.msg = msg
self.build_env = build_env
def __str__(self):
return "{}({})".format(self.__class__.__name__, repr(self.msg))
class VariantDBConnectionError(BuildEnvironmentError):
def __init__(self, connec... | class Buildenvironmenterror(Exception):
def __init__(self, msg, build_env):
self.msg = msg
self.build_env = build_env
def __str__(self):
return '{}({})'.format(self.__class__.__name__, repr(self.msg))
class Variantdbconnectionerror(BuildEnvironmentError):
def __init__(self, conne... |
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param l1: the first list
@param l2: the second list
@return: the sum list of l1 and l2
"""
def addLists(self, l1, l2):
dumm... | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param l1: the first list
@param l2: the second list
@return: the sum list of l1 and l2
"""
def add_lists(self, l1, l2):
du... |
#Advanced string syntax
#Multiple ways to type strings
print('Hello')
print("That is Alice's cat")
#To use a single quote throughout your code
#put in a / before the quotation
print('Here is the example (\')')
print('Do you see how the quotation \' is shown?')
#Example of types of "Escape Characters"
# \' ... | print('Hello')
print("That is Alice's cat")
print("Here is the example (')")
print("Do you see how the quotation ' is shown?")
print("Hello there! \nHow are you? \n I'm fine.")
print("This is an example of use of the multi string.\n\nDear Alice,\nEve's cat has been arrested for catnapping, cat burglary, and extortion.\... |
class Queue:
def __init__(self):
self.queue = list()
def enqueue(self,data):
if data not in self.queue:
self.queue.insert(0,data)
return True
return False
def dequeue(self):
if len(self.queue)>0:
return self.queue.pop()
return ("Queue ... | class Queue:
def __init__(self):
self.queue = list()
def enqueue(self, data):
if data not in self.queue:
self.queue.insert(0, data)
return True
return False
def dequeue(self):
if len(self.queue) > 0:
return self.queue.pop()
retur... |
class Solution(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums) - 1
start, end = 1, n
while start + 1 < end:
mid = start + (end - start) / 2
count = 0
for num in nums... | class Solution(object):
def find_duplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums) - 1
(start, end) = (1, n)
while start + 1 < end:
mid = start + (end - start) / 2
count = 0
for num in nums:
... |
class TerminalSet:
NODE_TYPE = 'terminal'
@classmethod
def is_terminal_value(cls, node):
return node['node_type'] == cls.NODE_TYPE and node.has_key('value') and (node['type'] in ['int', 'float'])
@classmethod
def terminal_value(cls, value):
return {'node_type': cls.NODE_TYPE, 'name': str(value), 'va... | class Terminalset:
node_type = 'terminal'
@classmethod
def is_terminal_value(cls, node):
return node['node_type'] == cls.NODE_TYPE and node.has_key('value') and (node['type'] in ['int', 'float'])
@classmethod
def terminal_value(cls, value):
return {'node_type': cls.NODE_TYPE, 'name... |
"""
Parameters exchanged client <-> server and client <-> compensator
Copyright 2021 Reza NasiriGerdeh and Reihaneh TorkzadehMahani. 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 ... | """
Parameters exchanged client <-> server and client <-> compensator
Copyright 2021 Reza NasiriGerdeh and Reihaneh TorkzadehMahani. 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 ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2019 Idiap Research Institute, http://www.idiap.ch/
# Written by Bastian Schnell <bastian.schnell@idiap.ch>
#
class EmbeddingConfig(object):
def __init__(self, f_get_emb_index, num_embeddings, embedding_dim, name=None, **args):
assert calla... | class Embeddingconfig(object):
def __init__(self, f_get_emb_index, num_embeddings, embedding_dim, name=None, **args):
assert callable(f_get_emb_index), 'f_get_emb_index must be callable.'
self.f_get_emb_index = f_get_emb_index
self.num_embeddings = num_embeddings
self.embedding_dim ... |
y=int(input("Enter The year: "))
if(((y%2==0)or (y%400==0))and y%100!=0):
print("leap Year")
else:
print("Not Leap year")
| y = int(input('Enter The year: '))
if (y % 2 == 0 or y % 400 == 0) and y % 100 != 0:
print('leap Year')
else:
print('Not Leap year') |
class Notifier:
def __init(self):
pass
def notify(self, msg):
print(msg)
def message(self, msg):
print(msg)
def message2(self, msg2):
print(msg2) | class Notifier:
def __init(self):
pass
def notify(self, msg):
print(msg)
def message(self, msg):
print(msg)
def message2(self, msg2):
print(msg2) |
# -*- coding: utf-8 -*-
"""Version information for the bioregistry."""
__all__ = [
'VERSION',
]
VERSION = '0.1.4-dev'
| """Version information for the bioregistry."""
__all__ = ['VERSION']
version = '0.1.4-dev' |
class Solution:
def reverseWords(self, s: str) -> str:
list1 = s.split(' ')[::-1]
new_string = ""
for i in range(0,len(list1)):
if(list1[i]!=""):
if(len(new_string)>0):
new_string+=" "
new_string+=list1[i]
return new_str... | class Solution:
def reverse_words(self, s: str) -> str:
list1 = s.split(' ')[::-1]
new_string = ''
for i in range(0, len(list1)):
if list1[i] != '':
if len(new_string) > 0:
new_string += ' '
new_string += list1[i]
retur... |
# fig03_03.py
"""Using nested control statements to analyze examination results."""
# initialize variables
passes = 0 # number of passes
failures = 0 # number of failures
# process 10 students
for student in range(10):
# get one exam result
result = int(input('Enter result (1=pass, 2=fail): '))
if resu... | """Using nested control statements to analyze examination results."""
passes = 0
failures = 0
for student in range(10):
result = int(input('Enter result (1=pass, 2=fail): '))
if result == 1:
passes = passes + 1
else:
failures = failures + 1
print('Passed:', passes)
print('Failed:', failures)... |
def relay_states_registar_value(relay_states):
num = 0
n = 8
for relay_state in relay_states:
if relay_state:
num += 2**n
n += 1
return num
def relay_states_from_register_value(value):
relay_states = []
num = value
for i in range(11, 7, -1):
if... | def relay_states_registar_value(relay_states):
num = 0
n = 8
for relay_state in relay_states:
if relay_state:
num += 2 ** n
n += 1
return num
def relay_states_from_register_value(value):
relay_states = []
num = value
for i in range(11, 7, -1):
if num >= 2... |
"""User variables to use toolkit for Dynatrace"""
FULL_SET = {
"CLUSTER_NAME": {
"url":"URL GOES HERE (EVEN FOR SAAS)",
"tenant": {
"tenant1": "TENANT UUID GOES HERE",
"tenant2": "TENANT UUID GOES HERE"
},
"api_token": {
"tenant1": "API TOKEN GOES ... | """User variables to use toolkit for Dynatrace"""
full_set = {'CLUSTER_NAME': {'url': 'URL GOES HERE (EVEN FOR SAAS)', 'tenant': {'tenant1': 'TENANT UUID GOES HERE', 'tenant2': 'TENANT UUID GOES HERE'}, 'api_token': {'tenant1': 'API TOKEN GOES HERE', 'tenant2': 'API TOKEN GOES HERE'}, 'is_managed': True, 'cluster_token... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2012 Yahoo! Inc. All Rights Reserved.
# Copyright (C) 2012 New Dream Network, LLC (DreamHost) All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the Licens... | def partition(fullname):
"""
The name should be in dotted.path:ClassName syntax.
"""
if ':' not in fullname:
raise value_error('Invalid entry point specifier %r' % fullname)
(module_name, _, classname) = fullname.partition(':')
return (module_name, classname)
def import_entry_point(full... |
# for loop
# Iterating over a list
print("List Iteration")
l = ["Ankit", "Gupta"]
for i in l:
print(i)
# Iterating over a tuple (immutable)
print("\nTuple Iteration")
t = ("ankit", "gupta")
for i in t:
print(i)
# Iterating over a String
print("\nString Iteration")
s = "Ankit"
for i in s:
print(i... | print('List Iteration')
l = ['Ankit', 'Gupta']
for i in l:
print(i)
print('\nTuple Iteration')
t = ('ankit', 'gupta')
for i in t:
print(i)
print('\nString Iteration')
s = 'Ankit'
for i in s:
print(i)
print('\nDictionary Iteration')
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d:
print('% s % d' % (... |
with open('html_file.html','r') as rf:
with open('output.txt','w') as of:
for string in rf.readlines():
if "<a href=" in string :
of.write(string)
#Some Better Solution for video lecture no. 223 | with open('html_file.html', 'r') as rf:
with open('output.txt', 'w') as of:
for string in rf.readlines():
if '<a href=' in string:
of.write(string) |
#!/usr/bin/env python
input = input("Enter IP address: ")
octets = input.split(".")
first_octet = bin(int(octets[0]))
second_octet = bin(int(octets[1]))
third_octet = bin(int(octets[2]))
forth_octet = bin(int(octets[3]))
print("%-20s%-20s%-20s%-20s" % ("First Octet", "Second Octet",
"T... | input = input('Enter IP address: ')
octets = input.split('.')
first_octet = bin(int(octets[0]))
second_octet = bin(int(octets[1]))
third_octet = bin(int(octets[2]))
forth_octet = bin(int(octets[3]))
print('%-20s%-20s%-20s%-20s' % ('First Octet', 'Second Octet', 'Third Octet', 'Forth Octet'))
print('%-20s%-20s%-20s%-20s... |
class Region:
def __init__ (self, bbox, region_):
self.bbox = bbox # [xmin, ymin, xmax, ymax] float
self.region_ = region_ # (d_region)
| class Region:
def __init__(self, bbox, region_):
self.bbox = bbox
self.region_ = region_ |
# 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... | """Proxy file for referencing processor partials."""
load('@build_bazel_rules_apple//apple/internal/partials:app_assets_validation.bzl', _app_assets_validation_partial='app_assets_validation_partial')
load('@build_bazel_rules_apple//apple/internal/partials:apple_bundle_info.bzl', _apple_bundle_info_partial='apple_bundl... |
def metade(x):
s = x / 2
return s
def dobro(n):
return 2 * n
def aumentar(n, p):
return (n * (p / 100)) + n
| def metade(x):
s = x / 2
return s
def dobro(n):
return 2 * n
def aumentar(n, p):
return n * (p / 100) + n |
# -*- coding: utf-8 -*-
'''
Package containing network handshakes
'''
| """
Package containing network handshakes
""" |
def _merge(a, b):
members = set()
members.update(a.members if isinstance(a, TagSet) else {a})
members.update(b.members if isinstance(b, TagSet) else {b})
return TagSet(members)
class Tag:
def __init__(self, name):
self.name = name
__and__ = _merge
__rand__ = _merge
def __repr... | def _merge(a, b):
members = set()
members.update(a.members if isinstance(a, TagSet) else {a})
members.update(b.members if isinstance(b, TagSet) else {b})
return tag_set(members)
class Tag:
def __init__(self, name):
self.name = name
__and__ = _merge
__rand__ = _merge
def __repr... |
'''Unstamp Mail Submission Agent Server
This server receives outgoing mail from the email client, and gives it to the
Mail Transfer Agent to send.
'''
| """Unstamp Mail Submission Agent Server
This server receives outgoing mail from the email client, and gives it to the
Mail Transfer Agent to send.
""" |
# Copyright 2013 Locaweb.
# 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 appli... | class Formatter(object):
def host(self, host_id, name, address):
return {'id': host_id, 'name': name, 'address': address}
def storage(self, sr_id, name, sr_type, used_space, allocated_space, physical_size):
return {'id': sr_id, 'name': name, 'type': sr_type, 'used_space': int(used_space), 'all... |
class Settings:
def __init__(self):
# Rotors = Moveable wheels
self.rotors = {
"I": {"sequence": "ekmflgdqvzntowyhxuspaibrcj", "notches": ["r"]},
"II": {"sequence": "ajdksiruxblhwtmcqgznpyfvoe", "notches": ["f"]},
"III": {"sequence": "bdfhjlcprtxvznyeiwgakmusqo", ... | class Settings:
def __init__(self):
self.rotors = {'I': {'sequence': 'ekmflgdqvzntowyhxuspaibrcj', 'notches': ['r']}, 'II': {'sequence': 'ajdksiruxblhwtmcqgznpyfvoe', 'notches': ['f']}, 'III': {'sequence': 'bdfhjlcprtxvznyeiwgakmusqo', 'notches': ['w']}, 'IV': {'sequence': 'esovpzjayquirhxlnftgkdcmwb', 'no... |
# Copyright 2019 Nicole Borrelli
#
# 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... | vanilla_flags = {'garland_defeated': 1, 'bridge_to_be_rebuilt': 2, 'obtained_bridge': 3, 'obtained_lute': 4, 'obtained_ship': 5, 'obtained_crown': 6, 'obtained_crystal_eye': 7, 'obtained_jolt_tonic': 8, 'obtained_mystic_key': 9, 'obtained_nitro_powder': 10, 'obtained_canal': 11, 'vampire_defeated': 12, 'obtained_ruby':... |
#!/usr/bin/env python3
#encoding=utf-8
#-------------------------------------------------
# Usage: python3 4-getattribute_to_compute_attribute.py
# Description: attribute management 4 of 4
# Same, but with generic __getattribute__ all attribute interception
#----------------------------------------------... | class Powers(object):
def __init__(self, square, cube):
self._square = square
self._cube = cube
def __getattribute__(self, name):
if name == 'square':
return object.__getattribute__(self, '_square') ** 2
elif name == 'cube':
return object.__getattribute_... |
#!/usr/bin/python3
# files.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
def main():
f = open('lines.txt')
for line in f:
print(line, end = '')
if __name__ == "__main__": main()
| def main():
f = open('lines.txt')
for line in f:
print(line, end='')
if __name__ == '__main__':
main() |
"""Common functions."""
__all__ = ['rshift']
def rshift(integer: int, shift: int) -> int:
"""Logical right binary shift."""
if integer >= 0:
return integer >> shift
return (integer + 0x100000000) >> shift
| """Common functions."""
__all__ = ['rshift']
def rshift(integer: int, shift: int) -> int:
"""Logical right binary shift."""
if integer >= 0:
return integer >> shift
return integer + 4294967296 >> shift |
"""
lab 7
"""
# 3.1
i = -1
while i <6:
i = i+1
if i ==3 or i ==6:
continue
print(i)
# 3.2
i=1
result = 1
while i <=5:
#print(i)
result = result *i
i = i+1
print(result)
# 3.3
i = 1
result = 0
while i <=5:
result = result +i
i = i+1
print(result)
# 3.4
i = 3
result = 1
whi... | """
lab 7
"""
i = -1
while i < 6:
i = i + 1
if i == 3 or i == 6:
continue
print(i)
i = 1
result = 1
while i <= 5:
result = result * i
i = i + 1
print(result)
i = 1
result = 0
while i <= 5:
result = result + i
i = i + 1
print(result)
i = 3
result = 1
while i <= 8:
result = result ... |
"""582. Word Break II
"""
class Solution:
"""
@param: s: A string
@param: wordDict: A set of words.
@return: All possible sentences.
"""
def wordBreak(self, s, wordDict):
# write your code here
return self.dfs(0, s, wordDict, {})
def dfs(self, idx, s, dict, memo):
if... | """582. Word Break II
"""
class Solution:
"""
@param: s: A string
@param: wordDict: A set of words.
@return: All possible sentences.
"""
def word_break(self, s, wordDict):
return self.dfs(0, s, wordDict, {})
def dfs(self, idx, s, dict, memo):
if idx == len(s):
... |
#Extensions:
# I have Taken Example 5.9 and extended it to dictionary
#no users:
usernames = {
'aes':{
'password':'64545465',
'key' : '56'
},
'bes':{
'password':'64545465',
'key' : '56'
},
'ces':{
'password':'64546545',
'key' : '56'
},
'ad... | usernames = {'aes': {'password': '64545465', 'key': '56'}, 'bes': {'password': '64545465', 'key': '56'}, 'ces': {'password': '64546545', 'key': '56'}, 'admin': {'password': '64546465', 'key': '5'}}
if usernames != {}:
for (user, info) in usernames.items():
if user == 'admin':
print('Hello, admin... |
MACS_VERSION = "3.0.0a7"
MAX_PAIRNUM = 1000
MAX_LAMBDA = 100000
FESTEP = 20
BUFFER_SIZE = 100000 # np array will increase at step of 1 million items
READ_BUFFER_SIZE = 10000000 # 10M bytes for read buffer size
N_MP = 2 # Number of processers
| macs_version = '3.0.0a7'
max_pairnum = 1000
max_lambda = 100000
festep = 20
buffer_size = 100000
read_buffer_size = 10000000
n_mp = 2 |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 30 16:26:18 2018
Accelerator BPM
@author: xf18id
"""
bpm17_1x = EpicsSignalRO("SR:C17-BI{BPM:1}Pos:X-I", name="bpm17_1x")
bpm17_1y = EpicsSignalRO("SR:C17-BI{BPM:1}Pos:Y-I", name="bpm17_1y")
bpm17_2x = EpicsSignalRO("SR:C17-BI{BPM:2}Pos:X-I", name="bpm17_2x")
bpm17_2y =... | """
Created on Fri Mar 30 16:26:18 2018
Accelerator BPM
@author: xf18id
"""
bpm17_1x = epics_signal_ro('SR:C17-BI{BPM:1}Pos:X-I', name='bpm17_1x')
bpm17_1y = epics_signal_ro('SR:C17-BI{BPM:1}Pos:Y-I', name='bpm17_1y')
bpm17_2x = epics_signal_ro('SR:C17-BI{BPM:2}Pos:X-I', name='bpm17_2x')
bpm17_2y = epics_signal_ro('SR... |
# error if not grade for a student
# OPTION 2: change the policy
def get_stats(class_list):
new_stats = []
for item in class_list:
new_stats.append([item[0], item[1], avg(item[1])])
return new_stats
def avg(grades):
try:
return sum(grades)/len(grades)
except ZeroDivisionError:
... | def get_stats(class_list):
new_stats = []
for item in class_list:
new_stats.append([item[0], item[1], avg(item[1])])
return new_stats
def avg(grades):
try:
return sum(grades) / len(grades)
except ZeroDivisionError:
print('no grades data')
return 0.0
test_grades = [[[... |
class BaseHelper:
def __init__(self, device):
self.device = device
def params(self, locals_: dict):
params = locals_.copy()
params.pop('self')
return params
| class Basehelper:
def __init__(self, device):
self.device = device
def params(self, locals_: dict):
params = locals_.copy()
params.pop('self')
return params |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Watchdog(object):
KEEP_ALIVE = '\n'
DEVICE = '/dev/watchdog'
# STOP = 'V' in bleaglebone black not works
def __init__(self):
pass
def notify(self, device, msg):
'''
/dev/watchdog is opened and will reboot un... | class Watchdog(object):
keep_alive = '\n'
device = '/dev/watchdog'
def __init__(self):
pass
def notify(self, device, msg):
"""
/dev/watchdog is opened and will reboot unless the watchdog is pinged
within a certain time.
:param device str: path of watchd... |
def CheckBinarySearchTreeSequence(arr: iter):
"""
Checks if a binary search sequence can is feasible
:param arr: An array containing the binary search tree sequence
:type arr: iter
"""
invalidSequenceString = "sequence is invalid: %s %s %s."
searchVal = arr[-1]
minVal = min(arr) - 1
maxVal = max(ar... | def check_binary_search_tree_sequence(arr: iter):
"""
Checks if a binary search sequence can is feasible
:param arr: An array containing the binary search tree sequence
:type arr: iter
"""
invalid_sequence_string = 'sequence is invalid: %s %s %s.'
search_val = arr[-1]
min_val = min(arr) - 1
... |
"""Macros to simplify generating maven files.
"""
load("@google_bazel_common//tools/maven:pom_file.bzl", default_pom_file = "pom_file")
def pom_file(name, targets, artifact_name, artifact_id, packaging = None, **kwargs):
default_pom_file(
name = name,
targets = targets,
preferred_group_ids... | """Macros to simplify generating maven files.
"""
load('@google_bazel_common//tools/maven:pom_file.bzl', default_pom_file='pom_file')
def pom_file(name, targets, artifact_name, artifact_id, packaging=None, **kwargs):
default_pom_file(name=name, targets=targets, preferred_group_ids=['com.google.common.inject', 'com... |
class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
s_bcount, t_bcount = 0, 0
s_idx, t_idx = len(S) - 1, len(T) - 1
while s_idx >= 0 or t_idx >= 0:
while s_idx >= 0:
if S[s_idx] == '#':
s_bcount += 1
... | class Solution:
def backspace_compare(self, S: str, T: str) -> bool:
(s_bcount, t_bcount) = (0, 0)
(s_idx, t_idx) = (len(S) - 1, len(T) - 1)
while s_idx >= 0 or t_idx >= 0:
while s_idx >= 0:
if S[s_idx] == '#':
s_bcount += 1
... |
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
if endWord not in wordList:
return 0
result = 0
l = len(beginWord)
beginSet = {beginWord}
endSet = {endWord}
wordList = set(wordList)
... | class Solution:
def ladder_length(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
if endWord not in wordList:
return 0
result = 0
l = len(beginWord)
begin_set = {beginWord}
end_set = {endWord}
word_list = set(wordList)
while begin... |
# coding: utf8
# try something like
# coding: utf8
# try something like
def index():
rows = db((db.activity.type=='stand')&(db.activity.status=='accepted')).select()
if rows:
return dict(projects=rows)
else:
return plugin_flatpage()
| def index():
rows = db((db.activity.type == 'stand') & (db.activity.status == 'accepted')).select()
if rows:
return dict(projects=rows)
else:
return plugin_flatpage() |
#re-learning about class and objects.
class MyClass: #ini class, class adalah blueprint dari object
var = "blah" #variable ini adalah object didalan class
def function(self): #ini adalah fungsi didalam class
print("This is a message inside the class.")
myobjectx = MyClass() #myobjectx adalah variabl... | class Myclass:
var = 'blah'
def function(self):
print('This is a message inside the class.')
myobjectx = my_class()
myobjectx.var
print(myobjectx.var)
print('####\n')
myobjecty = my_class()
myobjectz = my_class()
myobjectz.var = 'zlah'
print(myobjectx.var)
print(myobjectz.var)
print('####\n')
myobjectx... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.