content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
|---|---|
"""Directives and roles for documenting traitlets config options.
::
.. configtrait:: Application.log_datefmt
Description goes here.
Cross reference like this: :configtrait:`Application.log_datefmt`.
"""
def setup(app):
app.add_object_type('configtrait', 'configtrait', objname='Config option')
metadata = {'parallel_read_safe': True, 'parallel_write_safe': True}
return metadata
|
"""Directives and roles for documenting traitlets config options.
::
.. configtrait:: Application.log_datefmt
Description goes here.
Cross reference like this: :configtrait:`Application.log_datefmt`.
"""
def setup(app):
app.add_object_type('configtrait', 'configtrait', objname='Config option')
metadata = {'parallel_read_safe': True, 'parallel_write_safe': True}
return metadata
|
"""
Implementation of a vertex, as used in graphs
"""
################################################################################
# #
# Undirected #
# #
################################################################################
class UndirectedVertex(object):
def __init__(self, val=None, attrs=None):
self._val = val or id(self)
self._attrs = attrs or {}
self._edges = set()
self._has_self_edge = False
def __repr__(self):
display = (self.val, id(self))
return "Vertex(val=%s, id=%s)" % display
def __str__(self):
return "V(%s)" % self.val
def __contains__(self, e):
return e in self._edges
@property
def val(self):
return self._val
@property
def attrs(self):
return self._attrs
@property
def edges(self):
return iter(self._edges)
@property
def has_self_edge(self):
return self._has_self_edge
@property
def neighbors(self):
""" Iterator over vertices adjacent to this vertex """
return iter(set(v for e in self._edges for v in e.vertices
if v != self) |
(set([self]) if self._has_self_edge else set()))
@property
def degree(self):
""" Number of neighbors this vertex has (+1 if it has a self edge) """
return sum(1 for _ in self._edges) + (1 if self._has_self_edge else 0)
def add_edge(self, e):
""" Adds an edge to this vertex """
if self not in e.vertices:
raise ValueError(str(self) + " is not part of " + str(e) + ".")
if e in self:
raise ValueError(str(self) + " already has " + str(e) + ".")
self._edges.add(e)
if e.is_self_edge:
self._has_self_edge = True
def remove_edge(self, e):
""" Removes an edge from this vertex """
self._edges.discard(e)
if e.is_self_edge:
self._has_self_edge = False
def get(self, attr):
""" Get an attribute """
return self._attrs.get(attr)
def set(self, attr, value):
""" Set an attribute """
self._attrs[attr] = value
def has_attr(self, attr):
""" Check if an attribute exists """
return attr in self._attrs
def del_attr(self, attr):
""" Delete an attribute """
del self._attrs[attr]
################################################################################
# #
# Directed #
# #
################################################################################
class DirectedVertex(object):
def __init__(self, val=None, attrs=None):
self._val = val or id(self)
self._attrs = attrs or {}
self._edges = set()
def __repr__(self):
display = (self.val, id(self))
return "Vertex(val=%s, id=%s)" % display
def __str__(self):
return "V(%s)" % self.val
def __contains__(self, e):
return e in self._edges
@property
def val(self):
return self._val
@property
def attrs(self):
return self._attrs
@property
def edges(self):
return iter(self._edges)
@property
def outs(self):
""" Iterator over vertices into which this vertex has an edge """
return iter(set(e.v_to for e in self._edges if e.v_from == self))
@property
def ins(self):
""" Iterator over vertices which have an edge into this vertex """
return iter(set(e.v_from for e in self._edges if e.v_to == self))
@property
def out_degree(self):
""" Number of vertices into which this vertex has an edge """
return sum(1 for e in self._edges if e.v_from == self)
@property
def in_degree(self):
""" Number of vertices which have an edge into this vertex """
return sum(1 for e in self._edges if e.v_to == self)
@property
def degree(self):
""" Sum of out degree and in degree """
return self.out_degree + self.in_degree
def add_edge(self, e):
""" Adds an edge to this vertex """
if self != e.v_from and self != e.v_to:
raise ValueError(str(self) + " is not part of " + str(e) + ".")
if e in self:
raise ValueError(str(self) + " already has " + str(e) + ".")
self._edges.add(e)
def remove_edge(self, e):
""" Removes an edge from this vertex """
self._edges.discard(e)
def get(self, attr):
""" Get an attribute """
return self._attrs.get(attr)
def set(self, attr, value):
""" Set an attribute """
self._attrs[attr] = value
def has_attr(self, attr):
""" Check if an attribute exists """
return attr in self._attrs
def del_attr(self, attr):
""" Delete an attribute """
del self._attrs[attr]
|
"""
Implementation of a vertex, as used in graphs
"""
class Undirectedvertex(object):
def __init__(self, val=None, attrs=None):
self._val = val or id(self)
self._attrs = attrs or {}
self._edges = set()
self._has_self_edge = False
def __repr__(self):
display = (self.val, id(self))
return 'Vertex(val=%s, id=%s)' % display
def __str__(self):
return 'V(%s)' % self.val
def __contains__(self, e):
return e in self._edges
@property
def val(self):
return self._val
@property
def attrs(self):
return self._attrs
@property
def edges(self):
return iter(self._edges)
@property
def has_self_edge(self):
return self._has_self_edge
@property
def neighbors(self):
""" Iterator over vertices adjacent to this vertex """
return iter(set((v for e in self._edges for v in e.vertices if v != self)) | (set([self]) if self._has_self_edge else set()))
@property
def degree(self):
""" Number of neighbors this vertex has (+1 if it has a self edge) """
return sum((1 for _ in self._edges)) + (1 if self._has_self_edge else 0)
def add_edge(self, e):
""" Adds an edge to this vertex """
if self not in e.vertices:
raise value_error(str(self) + ' is not part of ' + str(e) + '.')
if e in self:
raise value_error(str(self) + ' already has ' + str(e) + '.')
self._edges.add(e)
if e.is_self_edge:
self._has_self_edge = True
def remove_edge(self, e):
""" Removes an edge from this vertex """
self._edges.discard(e)
if e.is_self_edge:
self._has_self_edge = False
def get(self, attr):
""" Get an attribute """
return self._attrs.get(attr)
def set(self, attr, value):
""" Set an attribute """
self._attrs[attr] = value
def has_attr(self, attr):
""" Check if an attribute exists """
return attr in self._attrs
def del_attr(self, attr):
""" Delete an attribute """
del self._attrs[attr]
class Directedvertex(object):
def __init__(self, val=None, attrs=None):
self._val = val or id(self)
self._attrs = attrs or {}
self._edges = set()
def __repr__(self):
display = (self.val, id(self))
return 'Vertex(val=%s, id=%s)' % display
def __str__(self):
return 'V(%s)' % self.val
def __contains__(self, e):
return e in self._edges
@property
def val(self):
return self._val
@property
def attrs(self):
return self._attrs
@property
def edges(self):
return iter(self._edges)
@property
def outs(self):
""" Iterator over vertices into which this vertex has an edge """
return iter(set((e.v_to for e in self._edges if e.v_from == self)))
@property
def ins(self):
""" Iterator over vertices which have an edge into this vertex """
return iter(set((e.v_from for e in self._edges if e.v_to == self)))
@property
def out_degree(self):
""" Number of vertices into which this vertex has an edge """
return sum((1 for e in self._edges if e.v_from == self))
@property
def in_degree(self):
""" Number of vertices which have an edge into this vertex """
return sum((1 for e in self._edges if e.v_to == self))
@property
def degree(self):
""" Sum of out degree and in degree """
return self.out_degree + self.in_degree
def add_edge(self, e):
""" Adds an edge to this vertex """
if self != e.v_from and self != e.v_to:
raise value_error(str(self) + ' is not part of ' + str(e) + '.')
if e in self:
raise value_error(str(self) + ' already has ' + str(e) + '.')
self._edges.add(e)
def remove_edge(self, e):
""" Removes an edge from this vertex """
self._edges.discard(e)
def get(self, attr):
""" Get an attribute """
return self._attrs.get(attr)
def set(self, attr, value):
""" Set an attribute """
self._attrs[attr] = value
def has_attr(self, attr):
""" Check if an attribute exists """
return attr in self._attrs
def del_attr(self, attr):
""" Delete an attribute """
del self._attrs[attr]
|
def aumentar(preco,taxa):
res = preco * (1 + taxa)
return res
def diminuir(preco,taxa):
res = preco * (1 - taxa)
return res
def dobro(preco):
res = preco * 2
return res
def metade(preco):
res = preco/2
return res
|
def aumentar(preco, taxa):
res = preco * (1 + taxa)
return res
def diminuir(preco, taxa):
res = preco * (1 - taxa)
return res
def dobro(preco):
res = preco * 2
return res
def metade(preco):
res = preco / 2
return res
|
"""All Lena exceptions are subclasses of :exc:`LenaException`
and corresponding Python exceptions (if they exist).
"""
# pylint: disable=missing-docstring
# Most Exceptions here are familiar to Python programmers
# and are self-explanatory.
class LenaException(Exception):
"""Base class for all Lena exceptions."""
pass
class LenaAttributeError(LenaException, AttributeError):
pass
class LenaEnvironmentError(LenaException, EnvironmentError):
"""The base class for exceptions
that can occur outside the Python system,
like IOError or OSError.
"""
class LenaIndexError(LenaException, IndexError):
pass
class LenaKeyError(LenaException, KeyError):
pass
class LenaNotImplementedError(LenaException, NotImplementedError):
pass
class LenaRuntimeError(LenaException, RuntimeError):
"""Raised when an error does not belong to other categories."""
pass
class LenaStopFill(LenaException):
"""Signal that no more fill is accepted.
Analogous to StopIteration, but control flow is reversed.
"""
pass
class LenaTypeError(LenaException, TypeError):
pass
class LenaValueError(LenaException, ValueError):
pass
class LenaZeroDivisionError(LenaException, ZeroDivisionError):
# raised when, for example, mean can't be calculated
pass
|
"""All Lena exceptions are subclasses of :exc:`LenaException`
and corresponding Python exceptions (if they exist).
"""
class Lenaexception(Exception):
"""Base class for all Lena exceptions."""
pass
class Lenaattributeerror(LenaException, AttributeError):
pass
class Lenaenvironmenterror(LenaException, EnvironmentError):
"""The base class for exceptions
that can occur outside the Python system,
like IOError or OSError.
"""
class Lenaindexerror(LenaException, IndexError):
pass
class Lenakeyerror(LenaException, KeyError):
pass
class Lenanotimplementederror(LenaException, NotImplementedError):
pass
class Lenaruntimeerror(LenaException, RuntimeError):
"""Raised when an error does not belong to other categories."""
pass
class Lenastopfill(LenaException):
"""Signal that no more fill is accepted.
Analogous to StopIteration, but control flow is reversed.
"""
pass
class Lenatypeerror(LenaException, TypeError):
pass
class Lenavalueerror(LenaException, ValueError):
pass
class Lenazerodivisionerror(LenaException, ZeroDivisionError):
pass
|
def ps(uid='-1',det='default',suffix='default',shift=.5,logplot='off',figure_number=999):
'''
function to determine statistic on line profile (assumes either peak or erf-profile)\n
calling sequence: uid='-1',det='default',suffix='default',shift=.5)\n
det='default' -> get detector from metadata, otherwise: specify, e.g. det='eiger4m_single'\n
suffix='default' -> _stats1_total / _sum_all, otherwise: specify, e.g. suffix='_stats2_total'\n
shift: scale for peak presence (0.5 -> peak has to be taller factor 2 above background)\n
figure_number: default=999 -> specify figure number for plot
'''
#import datetime
#import time
#import numpy as np
#from PIL import Image
#from databroker import db, get_fields, get_images, get_table
#from matplotlib import pyplot as pltfrom
#from lmfit import Model
#from lmfit import minimize, Parameters, Parameter, report_fit
#from scipy.special import erf
# get the scan information:
if uid == '-1':
uid=-1
if det == 'default':
if db[uid].start.detectors[0] == 'elm' and suffix=='default':
intensity_field='elm_sum_all'
elif db[uid].start.detectors[0] == 'elm':
intensity_field='elm'+suffix
elif suffix == 'default':
intensity_field= db[uid].start.detectors[0]+'_stats1_total'
else:
intensity_field= db[uid].start.detectors[0]+suffix
else:
if det=='elm' and suffix == 'default':
intensity_field='elm_sum_all'
elif det=='elm':
intensity_field = 'elm'+suffix
elif suffix == 'default':
intensity_field=det+'_stats1_total'
else:
intensity_field=det+suffix
field = db[uid].start.motors[0]
#field='dcm_b';intensity_field='elm_sum_all'
[x,y,t]=get_data(uid,field=field, intensity_field=intensity_field, det=None, debug=False) #need to re-write way to get data
x=np.array(x)
y=np.array(y)
x = np.nan_to_num(x)
y = np.nan_to_num(y)
PEAK=x[np.argmax(y)]
PEAK_y=np.max(y)
COM=np.sum(x * y) / np.sum(y)
### from Maksim: assume this is a peak profile:
def is_positive(num):
return True if num > 0 else False
# Normalize values first:
ym = (y - np.min(y)) / (np.max(y) - np.min(y)) - shift # roots are at Y=0
positive = is_positive(ym[0])
list_of_roots = []
for i in range(len(y)):
current_positive = is_positive(ym[i])
if current_positive != positive:
list_of_roots.append(x[i - 1] + (x[i] - x[i - 1]) / (abs(ym[i]) + abs(ym[i - 1])) * abs(ym[i - 1]))
positive = not positive
if len(list_of_roots) >= 2:
FWHM=abs(list_of_roots[-1] - list_of_roots[0])
CEN=list_of_roots[0]+0.5*(list_of_roots[1]-list_of_roots[0])
ps.fwhm=FWHM
ps.cen=CEN
#return {
# 'fwhm': abs(list_of_roots[-1] - list_of_roots[0]),
# 'x_range': list_of_roots,
#}
else: # ok, maybe it's a step function..
print('no peak...trying step function...')
ym = ym + shift
def err_func(x, x0, k=2, A=1, base=0 ): #### erf fit from Yugang
return base - A * erf(k*(x-x0))
mod = Model( err_func )
### estimate starting values:
x0=np.mean(x)
#k=0.1*(np.max(x)-np.min(x))
pars = mod.make_params( x0=x0, k=2, A = 1., base = 0. )
result = mod.fit(ym, pars, x = x )
CEN=result.best_values['x0']
FWHM = result.best_values['k']
ps.cen = CEN
ps.fwhm = FWHM
### re-plot results:
if logplot=='on':
plt.close(figure_number)
plt.figure(figure_number)
plt.semilogy([PEAK,PEAK],[np.min(y),np.max(y)],'k--',label='PEAK')
#plt.hold(True)
plt.semilogy([CEN,CEN],[np.min(y),np.max(y)],'r-.',label='CEN')
plt.semilogy([COM,COM],[np.min(y),np.max(y)],'g.-.',label='COM')
plt.semilogy(x,y,'bo-')
plt.xlabel(field);plt.ylabel(intensity_field)
plt.legend()
plt.title('uid: '+str(uid)+' @ '+str(t)+'\nPEAK: '+str(PEAK_y)[:8]+' @ '+str(PEAK)[:8]+' COM @ '+str(COM)[:8]+ '\n FWHM: '+str(FWHM)[:8]+' @ CEN: '+str(CEN)[:8],size=9)
plt.show()
else:
plt.close(figure_number)
plt.figure(figure_number)
plt.plot([PEAK,PEAK],[np.min(y),np.max(y)],'k--',label='PEAK')
#plt.hold(True)
plt.plot([CEN,CEN],[np.min(y),np.max(y)],'r-.',label='CEN')
plt.plot([COM,COM],[np.min(y),np.max(y)],'g.-.',label='COM')
plt.plot(x,y,'bo-')
plt.xlabel(field);plt.ylabel(intensity_field)
plt.legend()
plt.title('uid: '+str(uid)+' @ '+str(t)+'\nPEAK: '+str(PEAK_y)[:8]+' @ '+str(PEAK)[:8]+' COM @ '+str(COM)[:8]+ '\n FWHM: '+str(FWHM)[:8]+' @ CEN: '+str(CEN)[:8],size=9)
plt.show()
### assign values of interest as function attributes:
ps.peak=PEAK
ps.com=COM
|
def ps(uid='-1', det='default', suffix='default', shift=0.5, logplot='off', figure_number=999):
"""
function to determine statistic on line profile (assumes either peak or erf-profile)
calling sequence: uid='-1',det='default',suffix='default',shift=.5)
det='default' -> get detector from metadata, otherwise: specify, e.g. det='eiger4m_single'
suffix='default' -> _stats1_total / _sum_all, otherwise: specify, e.g. suffix='_stats2_total'
shift: scale for peak presence (0.5 -> peak has to be taller factor 2 above background)
figure_number: default=999 -> specify figure number for plot
"""
if uid == '-1':
uid = -1
if det == 'default':
if db[uid].start.detectors[0] == 'elm' and suffix == 'default':
intensity_field = 'elm_sum_all'
elif db[uid].start.detectors[0] == 'elm':
intensity_field = 'elm' + suffix
elif suffix == 'default':
intensity_field = db[uid].start.detectors[0] + '_stats1_total'
else:
intensity_field = db[uid].start.detectors[0] + suffix
elif det == 'elm' and suffix == 'default':
intensity_field = 'elm_sum_all'
elif det == 'elm':
intensity_field = 'elm' + suffix
elif suffix == 'default':
intensity_field = det + '_stats1_total'
else:
intensity_field = det + suffix
field = db[uid].start.motors[0]
[x, y, t] = get_data(uid, field=field, intensity_field=intensity_field, det=None, debug=False)
x = np.array(x)
y = np.array(y)
x = np.nan_to_num(x)
y = np.nan_to_num(y)
peak = x[np.argmax(y)]
peak_y = np.max(y)
com = np.sum(x * y) / np.sum(y)
def is_positive(num):
return True if num > 0 else False
ym = (y - np.min(y)) / (np.max(y) - np.min(y)) - shift
positive = is_positive(ym[0])
list_of_roots = []
for i in range(len(y)):
current_positive = is_positive(ym[i])
if current_positive != positive:
list_of_roots.append(x[i - 1] + (x[i] - x[i - 1]) / (abs(ym[i]) + abs(ym[i - 1])) * abs(ym[i - 1]))
positive = not positive
if len(list_of_roots) >= 2:
fwhm = abs(list_of_roots[-1] - list_of_roots[0])
cen = list_of_roots[0] + 0.5 * (list_of_roots[1] - list_of_roots[0])
ps.fwhm = FWHM
ps.cen = CEN
else:
print('no peak...trying step function...')
ym = ym + shift
def err_func(x, x0, k=2, A=1, base=0):
return base - A * erf(k * (x - x0))
mod = model(err_func)
x0 = np.mean(x)
pars = mod.make_params(x0=x0, k=2, A=1.0, base=0.0)
result = mod.fit(ym, pars, x=x)
cen = result.best_values['x0']
fwhm = result.best_values['k']
ps.cen = CEN
ps.fwhm = FWHM
if logplot == 'on':
plt.close(figure_number)
plt.figure(figure_number)
plt.semilogy([PEAK, PEAK], [np.min(y), np.max(y)], 'k--', label='PEAK')
plt.semilogy([CEN, CEN], [np.min(y), np.max(y)], 'r-.', label='CEN')
plt.semilogy([COM, COM], [np.min(y), np.max(y)], 'g.-.', label='COM')
plt.semilogy(x, y, 'bo-')
plt.xlabel(field)
plt.ylabel(intensity_field)
plt.legend()
plt.title('uid: ' + str(uid) + ' @ ' + str(t) + '\nPEAK: ' + str(PEAK_y)[:8] + ' @ ' + str(PEAK)[:8] + ' COM @ ' + str(COM)[:8] + '\n FWHM: ' + str(FWHM)[:8] + ' @ CEN: ' + str(CEN)[:8], size=9)
plt.show()
else:
plt.close(figure_number)
plt.figure(figure_number)
plt.plot([PEAK, PEAK], [np.min(y), np.max(y)], 'k--', label='PEAK')
plt.plot([CEN, CEN], [np.min(y), np.max(y)], 'r-.', label='CEN')
plt.plot([COM, COM], [np.min(y), np.max(y)], 'g.-.', label='COM')
plt.plot(x, y, 'bo-')
plt.xlabel(field)
plt.ylabel(intensity_field)
plt.legend()
plt.title('uid: ' + str(uid) + ' @ ' + str(t) + '\nPEAK: ' + str(PEAK_y)[:8] + ' @ ' + str(PEAK)[:8] + ' COM @ ' + str(COM)[:8] + '\n FWHM: ' + str(FWHM)[:8] + ' @ CEN: ' + str(CEN)[:8], size=9)
plt.show()
ps.peak = PEAK
ps.com = COM
|
"""
Question 38 :
Define a function which can generated a list where the values
are square of numbers between 1 and 20 (both included). Then the
function need to print the last 5 elements in the list.
Hints : Use ** operator to get power of a number. Use range()
for loop. Use list.append() to add values into a list. Use
[n1:n2] to slice a list.
"""
# Solution :
num = int(input("Enter a number : "))
def print_value():
l = list()
for i in range(1, num + 1):
l.append(i**2)
print(l[-5:])
print_value()
"""
Output :
Enter a number : 20
[256, 289, 324, 361, 400]
Process finished with exit code 0
"""
|
"""
Question 38 :
Define a function which can generated a list where the values
are square of numbers between 1 and 20 (both included). Then the
function need to print the last 5 elements in the list.
Hints : Use ** operator to get power of a number. Use range()
for loop. Use list.append() to add values into a list. Use
[n1:n2] to slice a list.
"""
num = int(input('Enter a number : '))
def print_value():
l = list()
for i in range(1, num + 1):
l.append(i ** 2)
print(l[-5:])
print_value()
'\nOutput : \n Enter a number : 20\n [256, 289, 324, 361, 400]\n \n Process finished with exit code 0\n\n'
|
# Copyright (c) Ville de Montreal. All rights reserved.
# Licensed under the MIT license.
# See LICENSE file in the project root for full license information.
CITYSCAPE_LABELS = [
('unlabeled', 0, 0, 0, 0),
('ego vehicle', 1, 0, 0, 0),
('rectification border', 2, 0, 0, 0),
('out of roi', 3, 0, 0, 0),
('static', 4, 0, 0, 0),
('dynamic', 5, 111, 74, 0),
('ground', 6, 81, 0, 81),
('road', 7, 128, 64, 128),
('sidewalk', 8, 244, 35, 232),
('parking', 9, 250, 170, 160),
('rail track', 10, 230, 150, 140),
('building', 11, 70, 70, 70),
('wall', 12, 102, 102, 156),
('fence', 13, 190, 153, 153),
('guard rail', 14, 180, 165, 180),
('bridge', 15, 150, 100, 100),
('tunnel', 16, 150, 120, 90),
('pole', 17, 153, 153, 153),
('polegroup', 18, 153, 153, 153),
('traffic light', 19, 250, 170, 30),
('traffic sign', 20, 220, 220, 0),
('vegetation', 21, 107, 142, 35),
('terrain', 22, 152, 251, 152),
('sky', 23, 70, 130, 180),
('person', 24, 220, 20, 60),
('rider', 25, 255, 0, 0),
('car', 26, 0, 0, 142),
('truck', 27, 0, 0, 70),
('bus', 28, 0, 60, 100),
('caravan', 29, 0, 0, 90),
('trailer', 30, 0, 0, 110),
('train', 31, 0, 80, 100),
('motorcycle', 32, 0, 0, 230),
('bicycle', 33, 119, 11, 32),
('license plate', 34, 0, 0, 142)]
CARLA_LABELS = [
('void', 0, 0, 0, 0),
('building', 1, 70, 70, 70),
('fence', 2, 190, 153, 153),
('other', 3, 250, 170, 160),
('pedestrian', 4, 220, 20, 60),
('pole', 5, 153, 153, 153),
('road line', 6, 157, 234, 50),
('road', 7, 128, 64, 128),
('sidewalk', 8, 244, 35, 232),
('vegetation', 9, 107, 142, 35),
('car', 10, 0, 0, 142),
('wall', 11, 102, 102, 156),
('traffic sign', 12, 220, 220, 0)]
CGMU_LABELS = [
('void', 0, 0, 0, 0),
('pole', 1, 255, 189, 176),
('traffic sign', 2, 255, 181, 0),
('vehicle', 3, 247, 93, 195),
('vegetation', 4, 83, 145, 11),
('median strip', 5, 255, 236, 0),
('building', 6, 123, 0, 255),
('private', 7, 255, 0, 0),
('sidewalk', 8, 0, 205, 255),
('road', 9, 14, 0, 255),
('pedestrian', 10, 0, 255, 4),
('structure', 11, 134, 69, 15),
('construction', 12, 255, 99, 0)]
|
cityscape_labels = [('unlabeled', 0, 0, 0, 0), ('ego vehicle', 1, 0, 0, 0), ('rectification border', 2, 0, 0, 0), ('out of roi', 3, 0, 0, 0), ('static', 4, 0, 0, 0), ('dynamic', 5, 111, 74, 0), ('ground', 6, 81, 0, 81), ('road', 7, 128, 64, 128), ('sidewalk', 8, 244, 35, 232), ('parking', 9, 250, 170, 160), ('rail track', 10, 230, 150, 140), ('building', 11, 70, 70, 70), ('wall', 12, 102, 102, 156), ('fence', 13, 190, 153, 153), ('guard rail', 14, 180, 165, 180), ('bridge', 15, 150, 100, 100), ('tunnel', 16, 150, 120, 90), ('pole', 17, 153, 153, 153), ('polegroup', 18, 153, 153, 153), ('traffic light', 19, 250, 170, 30), ('traffic sign', 20, 220, 220, 0), ('vegetation', 21, 107, 142, 35), ('terrain', 22, 152, 251, 152), ('sky', 23, 70, 130, 180), ('person', 24, 220, 20, 60), ('rider', 25, 255, 0, 0), ('car', 26, 0, 0, 142), ('truck', 27, 0, 0, 70), ('bus', 28, 0, 60, 100), ('caravan', 29, 0, 0, 90), ('trailer', 30, 0, 0, 110), ('train', 31, 0, 80, 100), ('motorcycle', 32, 0, 0, 230), ('bicycle', 33, 119, 11, 32), ('license plate', 34, 0, 0, 142)]
carla_labels = [('void', 0, 0, 0, 0), ('building', 1, 70, 70, 70), ('fence', 2, 190, 153, 153), ('other', 3, 250, 170, 160), ('pedestrian', 4, 220, 20, 60), ('pole', 5, 153, 153, 153), ('road line', 6, 157, 234, 50), ('road', 7, 128, 64, 128), ('sidewalk', 8, 244, 35, 232), ('vegetation', 9, 107, 142, 35), ('car', 10, 0, 0, 142), ('wall', 11, 102, 102, 156), ('traffic sign', 12, 220, 220, 0)]
cgmu_labels = [('void', 0, 0, 0, 0), ('pole', 1, 255, 189, 176), ('traffic sign', 2, 255, 181, 0), ('vehicle', 3, 247, 93, 195), ('vegetation', 4, 83, 145, 11), ('median strip', 5, 255, 236, 0), ('building', 6, 123, 0, 255), ('private', 7, 255, 0, 0), ('sidewalk', 8, 0, 205, 255), ('road', 9, 14, 0, 255), ('pedestrian', 10, 0, 255, 4), ('structure', 11, 134, 69, 15), ('construction', 12, 255, 99, 0)]
|
email = input()
while True:
commands = input().split()
command = commands[0]
if command == "Complete":
break
if command == "Make":
case = commands[1]
if case == "Upper":
email = email.upper()
elif case == "Lower":
email = email.lower()
print(email)
elif command == "GetDomain":
count = int(commands[1])
print(email[-count:])
elif command == "GetUsername":
if "@" not in email:
print(f"The email {email} doesn't contain the @ symbol.")
else:
splitted_email = email.split("@")
print(f"{splitted_email[0]}")
elif command == "Replace":
char = commands[1]
email = email.replace(char, "-")
print(email)
elif command == "Encrypt":
for s in email:
print(ord(s), end=" ")
|
email = input()
while True:
commands = input().split()
command = commands[0]
if command == 'Complete':
break
if command == 'Make':
case = commands[1]
if case == 'Upper':
email = email.upper()
elif case == 'Lower':
email = email.lower()
print(email)
elif command == 'GetDomain':
count = int(commands[1])
print(email[-count:])
elif command == 'GetUsername':
if '@' not in email:
print(f"The email {email} doesn't contain the @ symbol.")
else:
splitted_email = email.split('@')
print(f'{splitted_email[0]}')
elif command == 'Replace':
char = commands[1]
email = email.replace(char, '-')
print(email)
elif command == 'Encrypt':
for s in email:
print(ord(s), end=' ')
|
#tuples are immutable like strings
eggs = ('hello', 42, 0.5)
eggs[0]
'hello'
eggs[1:3]
(42, 0.5)
print(len(eggs))
type(('hello',)) #class 'tuple'
type(('hello')) #class 'str'
#Converting Types with the list() and tuple() Functions
tuple(['cat', 'dog', 5]) #('cat', 'dog', 5)
list(('cat', 'dog', 5)) #['cat', 'dog', 5]
list('hello') #['h', 'e', 'l', 'l', 'o']
|
eggs = ('hello', 42, 0.5)
eggs[0]
'hello'
eggs[1:3]
(42, 0.5)
print(len(eggs))
type(('hello',))
type('hello')
tuple(['cat', 'dog', 5])
list(('cat', 'dog', 5))
list('hello')
|
#!/usr/bin/python
class Problem7:
'''
10001st prime
Problem 7
104743
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
'''
def solution(self):
primes = []
nextPrime = 2
for i in range(10001):
print('%d, %d' % (i, nextPrime))
nextPrime = self.getNextPrime(primes)
return nextPrime
def getNextPrime(self, primes):
if (len(primes) == 0):
primes.append(2)
return 2
if (len(primes) == 1):
primes.append(3)
return 3
findNewPrime = False
nextPrime = primes[-1] + 2
while not findNewPrime:
findNewPrime = True
for i in primes:
if not nextPrime % i:
findNewPrime = False
break
if (findNewPrime):
primes.append(nextPrime)
break
nextPrime += 2
return nextPrime
p = Problem7()
print(p.solution())
|
class Problem7:
"""
10001st prime
Problem 7
104743
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
"""
def solution(self):
primes = []
next_prime = 2
for i in range(10001):
print('%d, %d' % (i, nextPrime))
next_prime = self.getNextPrime(primes)
return nextPrime
def get_next_prime(self, primes):
if len(primes) == 0:
primes.append(2)
return 2
if len(primes) == 1:
primes.append(3)
return 3
find_new_prime = False
next_prime = primes[-1] + 2
while not findNewPrime:
find_new_prime = True
for i in primes:
if not nextPrime % i:
find_new_prime = False
break
if findNewPrime:
primes.append(nextPrime)
break
next_prime += 2
return nextPrime
p = problem7()
print(p.solution())
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Contains all abstract class definitions """
__author__ = 'San Kilkis'
class AttrDict(dict):
""" Nested Attribute Dictionary
A class to convert a nested Dictionary into an object with key-values
accessibly using attribute notation (AttrDict.attribute) in addition to
key notation (Dict["key"]). This class recursively sets Dicts to objects,
allowing you to recurse down nested dicts (like: AttrDict.attr.attr)
"""
def __init__(self, mapping):
super(AttrDict, self).__init__() # Initializes the dictionary object w/ mapping
for key, value in mapping.items():
self.__setitem__(key, value)
def __setitem__(self, key, value):
if isinstance(value, dict): # If passed dictionary mapping is a dictionary instead of key, value recurse
value = AttrDict(value)
super(AttrDict, self).__setitem__(key, value)
def __getattr__(self, item):
try:
return self.__getitem__(item)
except KeyError:
raise AttributeError(item)
__setattr__ = __setitem__
|
""" Contains all abstract class definitions """
__author__ = 'San Kilkis'
class Attrdict(dict):
""" Nested Attribute Dictionary
A class to convert a nested Dictionary into an object with key-values
accessibly using attribute notation (AttrDict.attribute) in addition to
key notation (Dict["key"]). This class recursively sets Dicts to objects,
allowing you to recurse down nested dicts (like: AttrDict.attr.attr)
"""
def __init__(self, mapping):
super(AttrDict, self).__init__()
for (key, value) in mapping.items():
self.__setitem__(key, value)
def __setitem__(self, key, value):
if isinstance(value, dict):
value = attr_dict(value)
super(AttrDict, self).__setitem__(key, value)
def __getattr__(self, item):
try:
return self.__getitem__(item)
except KeyError:
raise attribute_error(item)
__setattr__ = __setitem__
|
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 14 13:29:10 2020
@author: Ham
"""
def locate(ar, target):
lft = 0
rgt = len(ar) - 1
while lft <= rgt:
mid = (lft + rgt) // 2
if ar[mid] == target:
return mid
if target < ar[mid]:
rgt = mid - 1
else:
lft = mid + 1
return -1
#for i,e in enumerate(ar):
# if e == target:
# return i
return -1
ar = range(11, 34)
print('locate([],', 20, 'found at', locate(ar, 20))
print('locate([],', 10, 'found at', locate(ar, 10))
print('locate([],', 50, 'found at', locate(ar, 50))
print('locate([],', 11, 'found at', locate(ar, 11))
print('locate([],', 33, 'found at', locate(ar, 33))
print('locate([],', 21, 'found at', locate(ar, 21))
print('locate([],', 22, 'found at', locate(ar, 22))
print('locate([],', 23, 'found at', locate(ar, 23))
print('locate([],', 24, 'found at', locate(ar, 24))
|
"""
Created on Mon Dec 14 13:29:10 2020
@author: Ham
"""
def locate(ar, target):
lft = 0
rgt = len(ar) - 1
while lft <= rgt:
mid = (lft + rgt) // 2
if ar[mid] == target:
return mid
if target < ar[mid]:
rgt = mid - 1
else:
lft = mid + 1
return -1
return -1
ar = range(11, 34)
print('locate([],', 20, 'found at', locate(ar, 20))
print('locate([],', 10, 'found at', locate(ar, 10))
print('locate([],', 50, 'found at', locate(ar, 50))
print('locate([],', 11, 'found at', locate(ar, 11))
print('locate([],', 33, 'found at', locate(ar, 33))
print('locate([],', 21, 'found at', locate(ar, 21))
print('locate([],', 22, 'found at', locate(ar, 22))
print('locate([],', 23, 'found at', locate(ar, 23))
print('locate([],', 24, 'found at', locate(ar, 24))
|
class_ds = \
"""A One-Group Light Water Reactor Fuel Cycle Component. This is a daughter
class of Reactor1G and a granddaughter of FCComp.
Parameters
----------
lib : str, optional
The path the the LWR HDF5 data library. This value is set to
Reactor1G.libfile and used by Reactor1G.loadlib().
rp : ReactorParameters, optional
The physical reactor parameter data to initialize this LWR instance with.
If this argument is not provided, default values are taken.
n : str, optional
The name of this LWR instance.
"""
desc = {
'docstrings': {
'class': class_ds,
'attrs': {},
'methods': {},
},
'attrs': {},
'extra': {},
}
mod = {'LightWaterReactor1G': desc,
'docstring': "Python wrapper for LWR1G.",}
desc['docstrings']['methods']['calc_params'] = \
"""Along with its own parameter set to track, the LWR model implements its own
function to set these parameters. This function is equivalent to the following::
self.params_prior_calc["BUd"] = 0.0
self.params_after_calc["BUd"] = self.BUd
self.params_prior_calc["U"] = self.mat_feed_u.mass
self.params_after_calc["U"] = self.mat_prod_u.mass
self.params_prior_calc["TRU"] = self.mat_feed_tru.mass
self.params_after_calc["TRU"] = self.mat_prod_tru.mass
self.params_prior_calc["ACT"] = self.mat_feed_act.mass
self.params_after_calc["ACT"] = self.mat_prod_act.mass
self.params_prior_calc["LAN"] = self.mat_feed_lan.mass
self.params_after_calc["LAN"] = self.mat_prod_lan.mass
self.params_prior_calc["FP"] = 1.0 - self.mat_feed_act.mass - self.mat_feed_lan.mass
"""
|
class_ds = 'A One-Group Light Water Reactor Fuel Cycle Component. This is a daughter \nclass of Reactor1G and a granddaughter of FCComp.\n\nParameters\n----------\nlib : str, optional\n The path the the LWR HDF5 data library. This value is set to \n Reactor1G.libfile and used by Reactor1G.loadlib().\nrp : ReactorParameters, optional\n The physical reactor parameter data to initialize this LWR instance with. \n If this argument is not provided, default values are taken.\nn : str, optional\n The name of this LWR instance.\n\n'
desc = {'docstrings': {'class': class_ds, 'attrs': {}, 'methods': {}}, 'attrs': {}, 'extra': {}}
mod = {'LightWaterReactor1G': desc, 'docstring': 'Python wrapper for LWR1G.'}
desc['docstrings']['methods']['calc_params'] = 'Along with its own parameter set to track, the LWR model implements its own \nfunction to set these parameters. This function is equivalent to the following::\n\n self.params_prior_calc["BUd"] = 0.0\n self.params_after_calc["BUd"] = self.BUd\n\n self.params_prior_calc["U"] = self.mat_feed_u.mass\n self.params_after_calc["U"] = self.mat_prod_u.mass\n\n self.params_prior_calc["TRU"] = self.mat_feed_tru.mass\n self.params_after_calc["TRU"] = self.mat_prod_tru.mass\n\n self.params_prior_calc["ACT"] = self.mat_feed_act.mass\n self.params_after_calc["ACT"] = self.mat_prod_act.mass\n\n self.params_prior_calc["LAN"] = self.mat_feed_lan.mass\n self.params_after_calc["LAN"] = self.mat_prod_lan.mass\n\n self.params_prior_calc["FP"] = 1.0 - self.mat_feed_act.mass - self.mat_feed_lan.mass\n\n'
|
class Solution:
# Top Down DP (Accepted), O(n^2) time, O(1) space
def minimumTotal(self, triangle: List[List[int]]) -> int:
for i in range(1, len(triangle)):
row = triangle[i]
row[0] += triangle[i-1][0]
row[-1] += triangle[i-1][-1]
for j in range(1, len(row)-1):
row[j] += min(triangle[i-1][j], triangle[i-1][j-1])
return min(triangle[-1])
# Bottom Up DP (Top Voted), O(n^2) time, O(1) space
def minimumTotal(self, triangle: List[List[int]]) -> int:
if not triangle:
return
for i in range(len(triangle)-2, -1, -1):
for j in range(len(triangle[i])):
triangle[i][j] += min(triangle[i+1][j], triangle[i+1][j+1])
return triangle[0][0]
|
class Solution:
def minimum_total(self, triangle: List[List[int]]) -> int:
for i in range(1, len(triangle)):
row = triangle[i]
row[0] += triangle[i - 1][0]
row[-1] += triangle[i - 1][-1]
for j in range(1, len(row) - 1):
row[j] += min(triangle[i - 1][j], triangle[i - 1][j - 1])
return min(triangle[-1])
def minimum_total(self, triangle: List[List[int]]) -> int:
if not triangle:
return
for i in range(len(triangle) - 2, -1, -1):
for j in range(len(triangle[i])):
triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1])
return triangle[0][0]
|
#! /usr/bin/env python
#Asking for input until a list of 10 integers given
while True:
num = input("Enter a list of 10 integers separated by a ',' : ").split(',')
l = len(num)
try:
for i in range(l):
num[i] = int(num[i])
p = (l==10)
if p:
break
except:
continue
#Finding prime numbers
prime_num = []
for x in num:
if x > 1:
for i in range(2,((x//2)+1)):
if x % i == 0:
break
else:
prime_num.append(x)
elif x == 1: #Number 1 is not considered as prime
continue
else: #For any negative numbers or 0
continue
if len(prime_num) > 0:
print(f'Prime numbers from the given list are : {prime_num}')
else:
print("There were no prime numbers in the given list")
print("\nEnd")
|
while True:
num = input("Enter a list of 10 integers separated by a ',' : ").split(',')
l = len(num)
try:
for i in range(l):
num[i] = int(num[i])
p = l == 10
if p:
break
except:
continue
prime_num = []
for x in num:
if x > 1:
for i in range(2, x // 2 + 1):
if x % i == 0:
break
else:
prime_num.append(x)
elif x == 1:
continue
else:
continue
if len(prime_num) > 0:
print(f'Prime numbers from the given list are : {prime_num}')
else:
print('There were no prime numbers in the given list')
print('\nEnd')
|
#!/usr/bin/env python3
# Lists
# Create a list
list_1 = [] # Creates an empty list using parantheses
list_2 = list() # Creates an empty list using the list() builtin
# Lists can accomodate different/multiple data types
list_2 = [1, 2, 3]
list_3 = ["a", "b", "c"]
list_4 = ["a", "hello", 1, "5"]
# Lists can accomodate other lists
list_5 = [[1, 2, 3], [5, 6, 1]]
# Combine a list with an existing list
list_6 = list_5.__add__(list_4) # Or list_5 + list_4
print(list_6)
print(dir())
# Create a copy of a list
#
# 1. Use `=`
# This is an exact copy, which means any change in one goes in the other
# The new list name is just a reference to the same memory address
list_copy_1 = list_4
print(id(list_copy_1))
print(id(list_4))
list_copy_1 is list_4
#
# 2. Add the elements, rather than assigning the list directly
list_copy_2 = list_4[:]
print(id(list_copy_1))
print(id(list_4))
list_copy_1 is list_4
|
list_1 = []
list_2 = list()
list_2 = [1, 2, 3]
list_3 = ['a', 'b', 'c']
list_4 = ['a', 'hello', 1, '5']
list_5 = [[1, 2, 3], [5, 6, 1]]
list_6 = list_5.__add__(list_4)
print(list_6)
print(dir())
list_copy_1 = list_4
print(id(list_copy_1))
print(id(list_4))
list_copy_1 is list_4
list_copy_2 = list_4[:]
print(id(list_copy_1))
print(id(list_4))
list_copy_1 is list_4
|
class File:
def __init__(self, name: str, mode: str):
self.file = open(name, mode)
def write(self, line: str):
self.file.write(line + "\n")
def write_dict(self, dict):
for key, val in dict.items():
self.write(f"{key}: {val}")
def close(self):
self.file.close()
|
class File:
def __init__(self, name: str, mode: str):
self.file = open(name, mode)
def write(self, line: str):
self.file.write(line + '\n')
def write_dict(self, dict):
for (key, val) in dict.items():
self.write(f'{key}: {val}')
def close(self):
self.file.close()
|
"""
There are n people, each of them has a unique ID from 0 to n - 1 and each
person of them belongs to exactly one group.
Given an integer array groupSizes which indicated that the person with
ID = i belongs to a group of groupSize[i] persons.
Return an array of the groups where ans[j] contains the IDs of the jth
group. Each ID should belong to exactly one group and each ID should be
present in your answer. Also if a person with ID = i belongs to group j in
your answer, then ans[j].length == groupSize[i] should be true.
If there is multiple answers, return any of them. It is guaranteed that
there will be at least one valid solution for the given input.
Example:
Input: groupSizes = [3,3,3,3,3,1,3]
Output: [[5],[0,1,2],[3,4,6]]
Explanation:
Other possible solutions are [[2,1,6],[5],[0,4,3]]
and [[5],[0,6,2],[4,3,1]].
Example:
Input: groupSizes = [2,1,3,3,3,2]
Output: [[1],[0,5],[2,3,4]]
Constraints:
- groupSizes.length == n
- 1 <= n <= 500
- 1 <= groupSizes[i] <= n
"""
#Difficulty: Medium
#102 / 102 test cases passed.
#Runtime: 72 ms
#Memory Usage: 13.7 MB
#Runtime: 72 ms, faster than 97.63% of Python3 online submissions for Group the People Given the Group Size They Belong To.
#Memory Usage: 13.7 MB, less than 96.74% of Python3 online submissions for Group the People Given the Group Size They Belong To.
class Solution:
def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
groups = {}
result = []
for i, n in enumerate(groupSizes):
if n not in groups:
groups[n] = []
groups[n].append(i)
for i in groups.keys():
while groups[i]:
result.append(groups[i][:i])
groups[i] = groups[i][i:]
return result
|
"""
There are n people, each of them has a unique ID from 0 to n - 1 and each
person of them belongs to exactly one group.
Given an integer array groupSizes which indicated that the person with
ID = i belongs to a group of groupSize[i] persons.
Return an array of the groups where ans[j] contains the IDs of the jth
group. Each ID should belong to exactly one group and each ID should be
present in your answer. Also if a person with ID = i belongs to group j in
your answer, then ans[j].length == groupSize[i] should be true.
If there is multiple answers, return any of them. It is guaranteed that
there will be at least one valid solution for the given input.
Example:
Input: groupSizes = [3,3,3,3,3,1,3]
Output: [[5],[0,1,2],[3,4,6]]
Explanation:
Other possible solutions are [[2,1,6],[5],[0,4,3]]
and [[5],[0,6,2],[4,3,1]].
Example:
Input: groupSizes = [2,1,3,3,3,2]
Output: [[1],[0,5],[2,3,4]]
Constraints:
- groupSizes.length == n
- 1 <= n <= 500
- 1 <= groupSizes[i] <= n
"""
class Solution:
def group_the_people(self, groupSizes: List[int]) -> List[List[int]]:
groups = {}
result = []
for (i, n) in enumerate(groupSizes):
if n not in groups:
groups[n] = []
groups[n].append(i)
for i in groups.keys():
while groups[i]:
result.append(groups[i][:i])
groups[i] = groups[i][i:]
return result
|
query_set = [
"SELECT subscriber.s_id, subscriber.sub_nbr, \
subscriber.bit_1, subscriber.bit_2, subscriber.bit_3, subscriber.bit_4, subscriber.bit_5, subscriber.bit_6, subscriber.bit_7, \
subscriber.bit_8, subscriber.bit_9, subscriber.bit_10, \
subscriber.hex_1, subscriber.hex_2, subscriber.hex_3, subscriber.hex_4, subscriber.hex_5, subscriber.hex_6, subscriber.hex_7, \
subscriber.hex_8, subscriber.hex_9, subscriber.hex_10, \
subscriber.byte2_1, subscriber.byte2_2, subscriber.byte2_3, subscriber.byte2_4, subscriber.byte2_5, \
subscriber.byte2_6, subscriber.byte2_7, subscriber.byte2_8, subscriber.byte2_9, subscriber.byte2_10, \
subscriber.msc_location, subscriber.vlr_location \
FROM subscriber \
WHERE subscriber.s_id = <non_uniform_rand_int_subscriber_size>; ",35, # was 35
"SELECT call_forwarding.numberx \
FROM special_facility, call_forwarding \
WHERE \
(special_facility.s_id = <non_uniform_rand_int_subscriber_size> \
AND special_facility.sf_type = <rand_int_1_4> \
AND special_facility.is_active = 1) \
AND (call_forwarding.s_id = special_facility.s_id \
AND call_forwarding.sf_type = special_facility.sf_type) \
AND (call_forwarding.start_time <= <rand_0_8_16> \
AND call_forwarding.end_time >= <rand_1_to_24>);",10, # was 10
"SELECT access_info.data1, access_info.data2, access_info.data3, access_info.data4 \
FROM access_info \
WHERE access_info.s_id = <non_uniform_rand_int_subscriber_size> \
AND access_info.ai_type = <rand_int_1_4>;",35, # was 35
"UPDATE subscriber, special_facility \
SET subscriber.bit_1 = <bit_rand>, special_facility.data_a = <rand_int_1_255> \
WHERE subscriber.s_id = <non_uniform_rand_int_subscriber_size> \
AND special_facility.s_id = <non_uniform_rand_int_subscriber_size> \
AND special_facility.sf_type = <rand_int_1_4>;", 2, # Was 2
"UPDATE subscriber \
SET subscriber.vlr_location = <rand_int_1_big> \
WHERE subscriber.sub_nbr = '<non_uniform_rand_int_subscriber_size_string>';",14, # Was 14
"INSERT INTO call_forwarding (call_forwarding.s_id, call_forwarding.sf_type, call_forwarding.start_time, call_forwarding.end_time, call_forwarding.numberx) \
SELECT subscriber.s_id, special_facility.sf_type ,<rand_0_8_16>,<rand_1_to_24>, <non_uniform_rand_int_subscriber_size> \
FROM subscriber \
LEFT OUTER JOIN special_facility ON subscriber.s_id = special_facility.s_id \
WHERE subscriber.sub_nbr = '<non_uniform_rand_int_subscriber_size_string>' \
ORDER BY RAND() LIMIT 1;",2, # Was 2, but self-conflicting was an issue.
"DELETE call_forwarding FROM call_forwarding \
INNER JOIN subscriber ON subscriber.s_id = call_forwarding.s_id \
WHERE call_forwarding.sf_type = <rand_int_1_4> \
AND call_forwarding.start_time = <rand_0_8_16> \
AND subscriber.sub_nbr = '<non_uniform_rand_int_subscriber_size_string>';",2, # Was 2
]
|
query_set = ['SELECT subscriber.s_id, subscriber.sub_nbr, subscriber.bit_1, subscriber.bit_2, subscriber.bit_3, subscriber.bit_4, subscriber.bit_5, subscriber.bit_6, subscriber.bit_7, subscriber.bit_8, subscriber.bit_9, subscriber.bit_10, subscriber.hex_1, subscriber.hex_2, subscriber.hex_3, subscriber.hex_4, subscriber.hex_5, subscriber.hex_6, subscriber.hex_7, subscriber.hex_8, subscriber.hex_9, subscriber.hex_10, subscriber.byte2_1, subscriber.byte2_2, subscriber.byte2_3, subscriber.byte2_4, subscriber.byte2_5, subscriber.byte2_6, subscriber.byte2_7, subscriber.byte2_8, subscriber.byte2_9, subscriber.byte2_10, subscriber.msc_location, subscriber.vlr_location FROM subscriber WHERE subscriber.s_id = <non_uniform_rand_int_subscriber_size>; ', 35, 'SELECT call_forwarding.numberx FROM special_facility, call_forwarding WHERE (special_facility.s_id = <non_uniform_rand_int_subscriber_size> AND special_facility.sf_type = <rand_int_1_4> AND special_facility.is_active = 1) AND (call_forwarding.s_id = special_facility.s_id AND call_forwarding.sf_type = special_facility.sf_type) AND (call_forwarding.start_time <= <rand_0_8_16> AND call_forwarding.end_time >= <rand_1_to_24>);', 10, 'SELECT access_info.data1, access_info.data2, access_info.data3, access_info.data4 FROM access_info WHERE access_info.s_id = <non_uniform_rand_int_subscriber_size> AND access_info.ai_type = <rand_int_1_4>;', 35, 'UPDATE subscriber, special_facility SET subscriber.bit_1 = <bit_rand>, special_facility.data_a = <rand_int_1_255> WHERE subscriber.s_id = <non_uniform_rand_int_subscriber_size> AND special_facility.s_id = <non_uniform_rand_int_subscriber_size> AND special_facility.sf_type = <rand_int_1_4>;', 2, "UPDATE subscriber SET subscriber.vlr_location = <rand_int_1_big> WHERE subscriber.sub_nbr = '<non_uniform_rand_int_subscriber_size_string>';", 14, "INSERT INTO call_forwarding (call_forwarding.s_id, call_forwarding.sf_type, call_forwarding.start_time, call_forwarding.end_time, call_forwarding.numberx) SELECT subscriber.s_id, special_facility.sf_type ,<rand_0_8_16>,<rand_1_to_24>, <non_uniform_rand_int_subscriber_size> FROM subscriber LEFT OUTER JOIN special_facility ON subscriber.s_id = special_facility.s_id WHERE subscriber.sub_nbr = '<non_uniform_rand_int_subscriber_size_string>' ORDER BY RAND() LIMIT 1;", 2, "DELETE call_forwarding FROM call_forwarding INNER JOIN subscriber ON subscriber.s_id = call_forwarding.s_id WHERE call_forwarding.sf_type = <rand_int_1_4> AND call_forwarding.start_time = <rand_0_8_16> AND subscriber.sub_nbr = '<non_uniform_rand_int_subscriber_size_string>';", 2]
|
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: Set[str]
:rtype: bool
"""
## DP
dp = [False for _ in range(len(s) + 1)]
dp[0] = True
for j in range(1, len(s) + 1):
for i in range(0, j):
if dp[i] and s[i:j] in wordDict:
dp[j] = True
break
return dp[-1]
## recursive solution with memory
self.record=set([])
if not wordDict:
return False
self.r=list(set([len(x) for x in wordDict]))
return self.helper(s, wordDict)
def helper(self, s, wordDict):
if not s:
return True
if s in self.record:
return False
if not wordDict:
return False
# return minLength, maxLength
for i in self.r:
if s[:i] in wordDict:
# if s[:i] in wordDict:
if self.helper(s[i:], wordDict):
return True
self.record.add(s)
return False
|
class Solution(object):
def word_break(self, s, wordDict):
"""
:type s: str
:type wordDict: Set[str]
:rtype: bool
"""
dp = [False for _ in range(len(s) + 1)]
dp[0] = True
for j in range(1, len(s) + 1):
for i in range(0, j):
if dp[i] and s[i:j] in wordDict:
dp[j] = True
break
return dp[-1]
self.record = set([])
if not wordDict:
return False
self.r = list(set([len(x) for x in wordDict]))
return self.helper(s, wordDict)
def helper(self, s, wordDict):
if not s:
return True
if s in self.record:
return False
if not wordDict:
return False
for i in self.r:
if s[:i] in wordDict:
if self.helper(s[i:], wordDict):
return True
self.record.add(s)
return False
|
## https://leetcode.com/problems/find-all-duplicates-in-an-array/
## pretty simple solution -- use a set to keep track of the numbers
## that have already appeared (because lookup time is O(1) given
## the implementation in python via a hash table). Gives me an O(N)
## runtime
## runetime is 79th percentile; memory is 19th percentile
class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
already_appeared = set([])
twice = []
while len(nums):
n = nums.pop()
if n in already_appeared:
twice.append(n)
else:
already_appeared.add(n)
return twice
|
class Solution:
def find_duplicates(self, nums: List[int]) -> List[int]:
already_appeared = set([])
twice = []
while len(nums):
n = nums.pop()
if n in already_appeared:
twice.append(n)
else:
already_appeared.add(n)
return twice
|
world_cities = ['Dubai', 'New Orleans', 'Santorini', 'Gaza', 'Seoul']
print('***********')
print(world_cities)
print('***********')
print(sorted(world_cities))
print('***********')
print(world_cities)
print('***********')
print(sorted(world_cities, reverse=True))
print('***********')
print(world_cities)
print('***********')
world_cities.reverse()
print('***********')
print(world_cities)
world_cities.reverse()
print('***********')
print(world_cities)
print('***********')
world_cities.sort()
print(world_cities)
|
world_cities = ['Dubai', 'New Orleans', 'Santorini', 'Gaza', 'Seoul']
print('***********')
print(world_cities)
print('***********')
print(sorted(world_cities))
print('***********')
print(world_cities)
print('***********')
print(sorted(world_cities, reverse=True))
print('***********')
print(world_cities)
print('***********')
world_cities.reverse()
print('***********')
print(world_cities)
world_cities.reverse()
print('***********')
print(world_cities)
print('***********')
world_cities.sort()
print(world_cities)
|
# Given a non-negative integer num, return the number of steps to reduce it to zero.
# If the current number is even, you have to divide it by 2,
# otherwise, you have to subtract 1 from it.
def count_steps(num):
steps = 0
while num != 0:
if num % 2 == 1:
num -= 1
else:
num /= 2
steps += 1
return steps
|
def count_steps(num):
steps = 0
while num != 0:
if num % 2 == 1:
num -= 1
else:
num /= 2
steps += 1
return steps
|
# https://leetcode.com/problems/is-subsequence/
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
if len(s) == 0:
return True
sIndex = 0
for tIndex, tChar in enumerate(t):
if s[sIndex] == tChar:
sIndex += 1
if sIndex == len(s):
return True
return False
|
class Solution:
def is_subsequence(self, s: str, t: str) -> bool:
if len(s) == 0:
return True
s_index = 0
for (t_index, t_char) in enumerate(t):
if s[sIndex] == tChar:
s_index += 1
if sIndex == len(s):
return True
return False
|
#
# PySNMP MIB module H3C-FTM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/H3C-FTM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:09:18 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint")
h3cCommon, = mibBuilder.importSymbols("HUAWEI-3COM-OID-MIB", "h3cCommon")
ObjectGroup, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance")
MibIdentifier, Gauge32, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, ModuleIdentity, Counter64, iso, ObjectIdentity, Unsigned32, IpAddress, TimeTicks, Counter32, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "Gauge32", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "ModuleIdentity", "Counter64", "iso", "ObjectIdentity", "Unsigned32", "IpAddress", "TimeTicks", "Counter32", "Integer32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
h3cFtmManMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1))
if mibBuilder.loadTexts: h3cFtmManMIB.setLastUpdated('200401131055Z')
if mibBuilder.loadTexts: h3cFtmManMIB.setOrganization('HUAWEI-3COM TECHNOLOGIES.')
h3cFtm = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1))
h3cFtmManMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1))
h3cFtmUnitTable = MibTable((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1), )
if mibBuilder.loadTexts: h3cFtmUnitTable.setStatus('current')
h3cFtmUnitEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1), ).setIndexNames((0, "H3C-FTM-MIB", "h3cFtmIndex"))
if mibBuilder.loadTexts: h3cFtmUnitEntry.setStatus('current')
h3cFtmIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1, 1), Integer32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: h3cFtmIndex.setStatus('current')
h3cFtmUnitID = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1, 2), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: h3cFtmUnitID.setStatus('current')
h3cFtmUnitName = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1, 3), OctetString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: h3cFtmUnitName.setStatus('current')
h3cFtmUnitRole = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("master", 0), ("slave", 1)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: h3cFtmUnitRole.setStatus('current')
h3cFtmNumberMode = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("automatic", 0), ("manual", 1)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: h3cFtmNumberMode.setStatus('current')
h3cFtmAuthMode = MibScalar((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("ftm-none", 0), ("ftm-simple", 1), ("ftm-md5", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: h3cFtmAuthMode.setStatus('current')
h3cFtmAuthValue = MibScalar((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 3), OctetString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: h3cFtmAuthValue.setStatus('current')
h3cFtmFabricVlanID = MibScalar((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 4094))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: h3cFtmFabricVlanID.setStatus('current')
h3cFtmFabricType = MibScalar((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("outofStack", 1), ("line", 2), ("ring", 3), ("mesh", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: h3cFtmFabricType.setStatus('current')
h3cFtmManMIBNotification = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 3))
h3cFtmUnitIDChange = NotificationType((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 3, 1)).setObjects(("H3C-FTM-MIB", "h3cFtmIndex"), ("H3C-FTM-MIB", "h3cFtmUnitID"))
if mibBuilder.loadTexts: h3cFtmUnitIDChange.setStatus('current')
h3cFtmUnitNameChange = NotificationType((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 3, 2)).setObjects(("H3C-FTM-MIB", "h3cFtmIndex"), ("H3C-FTM-MIB", "h3cFtmUnitName"))
if mibBuilder.loadTexts: h3cFtmUnitNameChange.setStatus('current')
h3cFtmManMIBComformance = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2))
h3cFtmMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2, 1))
h3cFtmMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2, 1, 1)).setObjects(("H3C-FTM-MIB", "h3cFtmConfigGroup"), ("H3C-FTM-MIB", "h3cFtmNotificationGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
h3cFtmMIBCompliance = h3cFtmMIBCompliance.setStatus('current')
h3cFtmMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2, 2))
h3cFtmConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2, 2, 1)).setObjects(("H3C-FTM-MIB", "h3cFtmUnitID"), ("H3C-FTM-MIB", "h3cFtmUnitName"), ("H3C-FTM-MIB", "h3cFtmAuthMode"), ("H3C-FTM-MIB", "h3cFtmAuthValue"), ("H3C-FTM-MIB", "h3cFtmFabricVlanID"), ("H3C-FTM-MIB", "h3cFtmFabricType"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
h3cFtmConfigGroup = h3cFtmConfigGroup.setStatus('current')
h3cFtmNotificationGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2, 2, 2)).setObjects(("H3C-FTM-MIB", "h3cFtmUnitIDChange"), ("H3C-FTM-MIB", "h3cFtmUnitNameChange"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
h3cFtmNotificationGroup = h3cFtmNotificationGroup.setStatus('current')
mibBuilder.exportSymbols("H3C-FTM-MIB", h3cFtmUnitID=h3cFtmUnitID, h3cFtmManMIBObjects=h3cFtmManMIBObjects, h3cFtmManMIBNotification=h3cFtmManMIBNotification, h3cFtmFabricVlanID=h3cFtmFabricVlanID, h3cFtmNotificationGroup=h3cFtmNotificationGroup, h3cFtmNumberMode=h3cFtmNumberMode, h3cFtm=h3cFtm, h3cFtmManMIBComformance=h3cFtmManMIBComformance, h3cFtmUnitRole=h3cFtmUnitRole, h3cFtmUnitEntry=h3cFtmUnitEntry, h3cFtmManMIB=h3cFtmManMIB, h3cFtmMIBCompliances=h3cFtmMIBCompliances, h3cFtmMIBCompliance=h3cFtmMIBCompliance, h3cFtmFabricType=h3cFtmFabricType, h3cFtmAuthMode=h3cFtmAuthMode, h3cFtmAuthValue=h3cFtmAuthValue, h3cFtmUnitName=h3cFtmUnitName, PYSNMP_MODULE_ID=h3cFtmManMIB, h3cFtmConfigGroup=h3cFtmConfigGroup, h3cFtmIndex=h3cFtmIndex, h3cFtmMIBGroups=h3cFtmMIBGroups, h3cFtmUnitIDChange=h3cFtmUnitIDChange, h3cFtmUnitTable=h3cFtmUnitTable, h3cFtmUnitNameChange=h3cFtmUnitNameChange)
|
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, single_value_constraint, value_range_constraint, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ConstraintsUnion', 'SingleValueConstraint', 'ValueRangeConstraint', 'ValueSizeConstraint')
(h3c_common,) = mibBuilder.importSymbols('HUAWEI-3COM-OID-MIB', 'h3cCommon')
(object_group, notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'ObjectGroup', 'NotificationGroup', 'ModuleCompliance')
(mib_identifier, gauge32, bits, mib_scalar, mib_table, mib_table_row, mib_table_column, notification_type, module_identity, counter64, iso, object_identity, unsigned32, ip_address, time_ticks, counter32, integer32) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibIdentifier', 'Gauge32', 'Bits', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'NotificationType', 'ModuleIdentity', 'Counter64', 'iso', 'ObjectIdentity', 'Unsigned32', 'IpAddress', 'TimeTicks', 'Counter32', 'Integer32')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
h3c_ftm_man_mib = module_identity((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1))
if mibBuilder.loadTexts:
h3cFtmManMIB.setLastUpdated('200401131055Z')
if mibBuilder.loadTexts:
h3cFtmManMIB.setOrganization('HUAWEI-3COM TECHNOLOGIES.')
h3c_ftm = mib_identifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1))
h3c_ftm_man_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1))
h3c_ftm_unit_table = mib_table((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1))
if mibBuilder.loadTexts:
h3cFtmUnitTable.setStatus('current')
h3c_ftm_unit_entry = mib_table_row((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1)).setIndexNames((0, 'H3C-FTM-MIB', 'h3cFtmIndex'))
if mibBuilder.loadTexts:
h3cFtmUnitEntry.setStatus('current')
h3c_ftm_index = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1, 1), integer32()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
h3cFtmIndex.setStatus('current')
h3c_ftm_unit_id = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1, 2), integer32()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
h3cFtmUnitID.setStatus('current')
h3c_ftm_unit_name = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1, 3), octet_string()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
h3cFtmUnitName.setStatus('current')
h3c_ftm_unit_role = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('master', 0), ('slave', 1)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
h3cFtmUnitRole.setStatus('current')
h3c_ftm_number_mode = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('automatic', 0), ('manual', 1)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
h3cFtmNumberMode.setStatus('current')
h3c_ftm_auth_mode = mib_scalar((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2))).clone(namedValues=named_values(('ftm-none', 0), ('ftm-simple', 1), ('ftm-md5', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
h3cFtmAuthMode.setStatus('current')
h3c_ftm_auth_value = mib_scalar((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 3), octet_string()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
h3cFtmAuthValue.setStatus('current')
h3c_ftm_fabric_vlan_id = mib_scalar((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 4), integer32().subtype(subtypeSpec=value_range_constraint(2, 4094))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
h3cFtmFabricVlanID.setStatus('current')
h3c_ftm_fabric_type = mib_scalar((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('outofStack', 1), ('line', 2), ('ring', 3), ('mesh', 4)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
h3cFtmFabricType.setStatus('current')
h3c_ftm_man_mib_notification = mib_identifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 3))
h3c_ftm_unit_id_change = notification_type((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 3, 1)).setObjects(('H3C-FTM-MIB', 'h3cFtmIndex'), ('H3C-FTM-MIB', 'h3cFtmUnitID'))
if mibBuilder.loadTexts:
h3cFtmUnitIDChange.setStatus('current')
h3c_ftm_unit_name_change = notification_type((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 3, 2)).setObjects(('H3C-FTM-MIB', 'h3cFtmIndex'), ('H3C-FTM-MIB', 'h3cFtmUnitName'))
if mibBuilder.loadTexts:
h3cFtmUnitNameChange.setStatus('current')
h3c_ftm_man_mib_comformance = mib_identifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2))
h3c_ftm_mib_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2, 1))
h3c_ftm_mib_compliance = module_compliance((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2, 1, 1)).setObjects(('H3C-FTM-MIB', 'h3cFtmConfigGroup'), ('H3C-FTM-MIB', 'h3cFtmNotificationGroup'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
h3c_ftm_mib_compliance = h3cFtmMIBCompliance.setStatus('current')
h3c_ftm_mib_groups = mib_identifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2, 2))
h3c_ftm_config_group = object_group((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2, 2, 1)).setObjects(('H3C-FTM-MIB', 'h3cFtmUnitID'), ('H3C-FTM-MIB', 'h3cFtmUnitName'), ('H3C-FTM-MIB', 'h3cFtmAuthMode'), ('H3C-FTM-MIB', 'h3cFtmAuthValue'), ('H3C-FTM-MIB', 'h3cFtmFabricVlanID'), ('H3C-FTM-MIB', 'h3cFtmFabricType'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
h3c_ftm_config_group = h3cFtmConfigGroup.setStatus('current')
h3c_ftm_notification_group = notification_group((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2, 2, 2)).setObjects(('H3C-FTM-MIB', 'h3cFtmUnitIDChange'), ('H3C-FTM-MIB', 'h3cFtmUnitNameChange'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
h3c_ftm_notification_group = h3cFtmNotificationGroup.setStatus('current')
mibBuilder.exportSymbols('H3C-FTM-MIB', h3cFtmUnitID=h3cFtmUnitID, h3cFtmManMIBObjects=h3cFtmManMIBObjects, h3cFtmManMIBNotification=h3cFtmManMIBNotification, h3cFtmFabricVlanID=h3cFtmFabricVlanID, h3cFtmNotificationGroup=h3cFtmNotificationGroup, h3cFtmNumberMode=h3cFtmNumberMode, h3cFtm=h3cFtm, h3cFtmManMIBComformance=h3cFtmManMIBComformance, h3cFtmUnitRole=h3cFtmUnitRole, h3cFtmUnitEntry=h3cFtmUnitEntry, h3cFtmManMIB=h3cFtmManMIB, h3cFtmMIBCompliances=h3cFtmMIBCompliances, h3cFtmMIBCompliance=h3cFtmMIBCompliance, h3cFtmFabricType=h3cFtmFabricType, h3cFtmAuthMode=h3cFtmAuthMode, h3cFtmAuthValue=h3cFtmAuthValue, h3cFtmUnitName=h3cFtmUnitName, PYSNMP_MODULE_ID=h3cFtmManMIB, h3cFtmConfigGroup=h3cFtmConfigGroup, h3cFtmIndex=h3cFtmIndex, h3cFtmMIBGroups=h3cFtmMIBGroups, h3cFtmUnitIDChange=h3cFtmUnitIDChange, h3cFtmUnitTable=h3cFtmUnitTable, h3cFtmUnitNameChange=h3cFtmUnitNameChange)
|
# Row-by-column representation of the board
BOARD_SIZE = 6, 7
# Define size of each cell in the GUI of the game
CELL_SIZE = 100
# Define radius of dot
RADIUS = (CELL_SIZE // 2) - 5
# Define size of GUI screen
GUI_SIZE = (BOARD_SIZE[0] + 1) * CELL_SIZE, (BOARD_SIZE[1]) * CELL_SIZE
# Define various colors used on the GUI of the game
RED = 255, 0, 0
BLUE = 0, 0, 255
BLACK = 0, 0, 0
WHITE = 255, 255, 255
YELLOW = 255, 255, 0
# Define various players in the Game
HUMAN_PLAYER = 0
Q_ROBOT = 1
RANDOM_ROBOT = 2
MINI_MAX_ROBOT = 3
# Define various rewards
REWARD_WIN = 1
REWARD_LOSS = -1
REWARD_DRAW = 0.2
REWARD_NOTHING = 0
# Define various modes of the game
GAME_NAME = 'CONNECT-4'
GAME_MODES = {0: '2 Players', 1: 'vs Computer'}
# Define various modes of learning
LEARNING_MODES = {'random_agent': 0, 'trained_agent': 1, 'minimax_agent': 2}
NO_TOKEN = 0
# Define location of memory file
MEM_LOCATION = 'memory/memory.npy'
# Define variable to store no. of iterations to train the game robot
ITERATIONS = 100
# Define depth of mini-max player
MINI_MAX_DEPTH = 5
|
board_size = (6, 7)
cell_size = 100
radius = CELL_SIZE // 2 - 5
gui_size = ((BOARD_SIZE[0] + 1) * CELL_SIZE, BOARD_SIZE[1] * CELL_SIZE)
red = (255, 0, 0)
blue = (0, 0, 255)
black = (0, 0, 0)
white = (255, 255, 255)
yellow = (255, 255, 0)
human_player = 0
q_robot = 1
random_robot = 2
mini_max_robot = 3
reward_win = 1
reward_loss = -1
reward_draw = 0.2
reward_nothing = 0
game_name = 'CONNECT-4'
game_modes = {0: '2 Players', 1: 'vs Computer'}
learning_modes = {'random_agent': 0, 'trained_agent': 1, 'minimax_agent': 2}
no_token = 0
mem_location = 'memory/memory.npy'
iterations = 100
mini_max_depth = 5
|
'''This tnsertion sort algorithm
which is shown in most websites
and books, is slower than another
insertion sort algorithm.'''
def insertion_sort_slow(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
#insertionSort(arr)
#for i in range(len(arr)):
# print ("% d" % arr[i])
|
"""This tnsertion sort algorithm
which is shown in most websites
and books, is slower than another
insertion sort algorithm."""
def insertion_sort_slow(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
|
"""class krypton_patch:
def __init__(self, driver) -> None:
self.driver = driver
self.js = driver.driver.execute_script
driver.driver.execute_script("javascript/index.js") #patch 0.1
def FakeReply(self, korban, pesan, chat_id, MsgId, teks):
return self.js(f"return await FakeReply(\"{chat_id}\", \"{MsgId}\", \"{pesan}\", \"{korban}\", \"{teks}\")")
def hidetag(self, chat_id, body, msg):
return self.js(f"return await HideTagged(\"{chat_id}\", \"{body}\", \"{msg}\")")"""
|
"""class krypton_patch:
def __init__(self, driver) -> None:
self.driver = driver
self.js = driver.driver.execute_script
driver.driver.execute_script("javascript/index.js") #patch 0.1
def FakeReply(self, korban, pesan, chat_id, MsgId, teks):
return self.js(f"return await FakeReply("{chat_id}", "{MsgId}", "{pesan}", "{korban}", "{teks}")")
def hidetag(self, chat_id, body, msg):
return self.js(f"return await HideTagged("{chat_id}", "{body}", "{msg}")")"""
|
# Solution for the problem "Cats and a mouse"
# https://www.hackerrank.com/challenges/cats-and-a-mouse/problem
# Number of test cases
numQueries = int(input())
# Running the queries
for queryIndex in range(0, numQueries):
# Locations of Cat A, Cat B and mouse
locCatA, locCatB, locMouse = map(int, input().strip().split(' '))
# Distance between Cat A and mouse
distCatA = abs(locCatA - locMouse)
# Distance between Cat B and mouse
distCatB = abs(locCatB - locMouse)
# Mouse escapes if both distances are equal
if distCatA == distCatB:
print("Mouse C")
# Cat A is nearer
elif distCatA < distCatB:
print("Cat A")
# Cat B is nearer
else:
print("Cat B")
|
num_queries = int(input())
for query_index in range(0, numQueries):
(loc_cat_a, loc_cat_b, loc_mouse) = map(int, input().strip().split(' '))
dist_cat_a = abs(locCatA - locMouse)
dist_cat_b = abs(locCatB - locMouse)
if distCatA == distCatB:
print('Mouse C')
elif distCatA < distCatB:
print('Cat A')
else:
print('Cat B')
|
"""
DESCRIPTION:
Write a code to extract each digit from an integer, in the reverse order
EXAMPLE
Input:
n = 1234
Output:
"4 3 2 1"
"""
def main(n: int) -> str:
ret_val: str = ""
# Enter the code below
return ret_val
|
"""
DESCRIPTION:
Write a code to extract each digit from an integer, in the reverse order
EXAMPLE
Input:
n = 1234
Output:
"4 3 2 1"
"""
def main(n: int) -> str:
ret_val: str = ''
return ret_val
|
# configuration for building the network
y_dim = 6
tr_dim = 7
ir_dim = 10
latent_dim = 128
z_dim = 128
batch_size = 128
lr = 0.0002
beta1 = 0.5
# configuration for the supervisor
logdir = "./log"
sampledir = "./example"
max_steps = 30000
sample_every_n_steps = 100
summary_every_n_steps = 1
save_model_secs = 120
checkpoint_basename = "layout"
checkpoint_dir = "./checkpoints"
filenamequeue = "./dataset/layout_1205.tfrecords"
min_after_dequeue = 5000
num_threads = 4
|
y_dim = 6
tr_dim = 7
ir_dim = 10
latent_dim = 128
z_dim = 128
batch_size = 128
lr = 0.0002
beta1 = 0.5
logdir = './log'
sampledir = './example'
max_steps = 30000
sample_every_n_steps = 100
summary_every_n_steps = 1
save_model_secs = 120
checkpoint_basename = 'layout'
checkpoint_dir = './checkpoints'
filenamequeue = './dataset/layout_1205.tfrecords'
min_after_dequeue = 5000
num_threads = 4
|
N = int(input())
s = [input() for _ in range(N)]
for y in range(N):
for x in range(N):
print(s[N - 1 - x][y], end='')
print('')
|
n = int(input())
s = [input() for _ in range(N)]
for y in range(N):
for x in range(N):
print(s[N - 1 - x][y], end='')
print('')
|
class Message(object):
"""`Message` stores the SMS text and the originating phone number.
"""
def __init__(self, from_number, text, provider=None, *args, **kwargs):
self.from_number = from_number
self.text = text
self._provider = provider
def reply(self, text):
self._provider.send(self.from_number, text)
def __repr__(self):
return '[{} - {}]'.format(self.from_number, self.text)
|
class Message(object):
"""`Message` stores the SMS text and the originating phone number.
"""
def __init__(self, from_number, text, provider=None, *args, **kwargs):
self.from_number = from_number
self.text = text
self._provider = provider
def reply(self, text):
self._provider.send(self.from_number, text)
def __repr__(self):
return '[{} - {}]'.format(self.from_number, self.text)
|
S = input()
def check_even(stri):
if len(stri) % 2 !=0:
return False
else:
half = int(len(stri)/2)
if stri[:half] == stri[half:]:
return True
else:
return False
for i in range(len(S)):
if check_even(S[:-(i+1)]):
print(len(S)-(i+1))
exit()
|
s = input()
def check_even(stri):
if len(stri) % 2 != 0:
return False
else:
half = int(len(stri) / 2)
if stri[:half] == stri[half:]:
return True
else:
return False
for i in range(len(S)):
if check_even(S[:-(i + 1)]):
print(len(S) - (i + 1))
exit()
|
N = int(input("Cuantos digitos quiere ingresar? "))
lista = []
lista2 = []
for i in range(N):
lista.append(int(input("Digite un numero: ")))
print("Su lista es: ", lista)
for i in range(N):
lista2.append(1*(lista[i]+1))
print("La segunda lista es: ", lista2)
|
n = int(input('Cuantos digitos quiere ingresar? '))
lista = []
lista2 = []
for i in range(N):
lista.append(int(input('Digite un numero: ')))
print('Su lista es: ', lista)
for i in range(N):
lista2.append(1 * (lista[i] + 1))
print('La segunda lista es: ', lista2)
|
# @dependency 001-main/002-createrepository.py
frontend.json(
"repositories",
expect={ "repositories": [critic_json] })
frontend.json(
"repositories/1",
expect=critic_json)
frontend.json(
"repositories",
params={ "name": "critic" },
expect=critic_json)
frontend.json(
"repositories/4711",
expect={ "error": { "title": "No such resource",
"message": "Resource not found: Invalid repository id: 4711" }},
expected_http_status=404)
frontend.json(
"repositories/critic",
expect={ "error": { "title": "Invalid API request",
"message": "Invalid numeric id: 'critic'" }},
expected_http_status=400)
frontend.json(
"repositories",
params={ "name": "nosuchrepository" },
expect={ "error": { "title": "No such resource",
"message": "Resource not found: Invalid repository name: 'nosuchrepository'" }},
expected_http_status=404)
frontend.json(
"repositories",
params={ "filter": "interesting" },
expect={ "error": { "title": "Invalid API request",
"message": "Invalid repository filter parameter: 'interesting'" }},
expected_http_status=400)
|
frontend.json('repositories', expect={'repositories': [critic_json]})
frontend.json('repositories/1', expect=critic_json)
frontend.json('repositories', params={'name': 'critic'}, expect=critic_json)
frontend.json('repositories/4711', expect={'error': {'title': 'No such resource', 'message': 'Resource not found: Invalid repository id: 4711'}}, expected_http_status=404)
frontend.json('repositories/critic', expect={'error': {'title': 'Invalid API request', 'message': "Invalid numeric id: 'critic'"}}, expected_http_status=400)
frontend.json('repositories', params={'name': 'nosuchrepository'}, expect={'error': {'title': 'No such resource', 'message': "Resource not found: Invalid repository name: 'nosuchrepository'"}}, expected_http_status=404)
frontend.json('repositories', params={'filter': 'interesting'}, expect={'error': {'title': 'Invalid API request', 'message': "Invalid repository filter parameter: 'interesting'"}}, expected_http_status=400)
|
#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
# Copyright (C) 2020 Daniel Rodriguez
# Use of this source code is governed by the MIT License
###############################################################################
__all__ = [
'SEED_AVG', 'SEED_LAST', 'SEED_SUM', 'SEED_NONE', 'SEED_ZERO',
'SEED_ZFILL',
'_INCPERIOD', '_DECPERIOD', '_MINIDX',
'_SERIES', '_MPSERIES',
'_SETVAL', '_MPSETVAL',
]
SEED_AVG = 0
SEED_LAST = 1
SEED_SUM = 2
SEED_NONE = 4
SEED_ZERO = 5
SEED_ZFILL = 6
def _INCPERIOD(x, p=1):
'''
Forces an increase `p` in the minperiod of object `x`.
Example: `ta-lib` calculates `+DM` a period of 1 too early, but calculates
the depending `+DI` from the right starting point. Increasing the period,
without changing the underlying already calculated `+DM` values, allows the
`+DI` values to be right
'''
x._minperiod += p
def _DECPERIOD(x, p=1):
'''
Forces an increase `p` in the minperiod of object `x`.
Example: `ta-lib` calculates `obv` already when the period is `1`,
discarding the needed "close" to "previous close" comparison. The only way
to take this into account is to decrease the delivery period of the
comparison by 1 to start the calculation before (and using a fixed
criterion as to what to do in the absence of a valid close to close
comparison)
'''
x._minperiod -= p
def _MINIDX(x, p=0):
'''
Delivers the index to an array which corresponds to `_minperiod` offset by
`p`. This allow direct manipulation of single values in arrays like in the
`obv` scenario in which a seed value is needed for the 1st delivered value
(in `ta-lib` mode) because no `close` to `previous close` comparison is
possible.
'''
return x._minperiod - 1 + p
def _SERIES(x):
'''Macro like function which makes clear that one is retrieving the actual
underlying series and not something a wrapped version'''
return x._series
def _MPSERIES(x):
'''Macro like function which makes clear that one is retrieving the actual
underlying series, sliced starting at the MINPERIOD of the series'''
return x._series[x._minperiod - 1:]
def _SETVAL(x, idx, val):
'''Macro like function which makes clear that one is setting a value in the
underlying series'''
x._series[idx] = val
def _MPSETVAL(x, idx, val):
'''Macro like function which makes clear that one is setting a value in the
underlying series'''
x._series[x._minperiod - 1 + idx] = val
|
__all__ = ['SEED_AVG', 'SEED_LAST', 'SEED_SUM', 'SEED_NONE', 'SEED_ZERO', 'SEED_ZFILL', '_INCPERIOD', '_DECPERIOD', '_MINIDX', '_SERIES', '_MPSERIES', '_SETVAL', '_MPSETVAL']
seed_avg = 0
seed_last = 1
seed_sum = 2
seed_none = 4
seed_zero = 5
seed_zfill = 6
def _incperiod(x, p=1):
"""
Forces an increase `p` in the minperiod of object `x`.
Example: `ta-lib` calculates `+DM` a period of 1 too early, but calculates
the depending `+DI` from the right starting point. Increasing the period,
without changing the underlying already calculated `+DM` values, allows the
`+DI` values to be right
"""
x._minperiod += p
def _decperiod(x, p=1):
"""
Forces an increase `p` in the minperiod of object `x`.
Example: `ta-lib` calculates `obv` already when the period is `1`,
discarding the needed "close" to "previous close" comparison. The only way
to take this into account is to decrease the delivery period of the
comparison by 1 to start the calculation before (and using a fixed
criterion as to what to do in the absence of a valid close to close
comparison)
"""
x._minperiod -= p
def _minidx(x, p=0):
"""
Delivers the index to an array which corresponds to `_minperiod` offset by
`p`. This allow direct manipulation of single values in arrays like in the
`obv` scenario in which a seed value is needed for the 1st delivered value
(in `ta-lib` mode) because no `close` to `previous close` comparison is
possible.
"""
return x._minperiod - 1 + p
def _series(x):
"""Macro like function which makes clear that one is retrieving the actual
underlying series and not something a wrapped version"""
return x._series
def _mpseries(x):
"""Macro like function which makes clear that one is retrieving the actual
underlying series, sliced starting at the MINPERIOD of the series"""
return x._series[x._minperiod - 1:]
def _setval(x, idx, val):
"""Macro like function which makes clear that one is setting a value in the
underlying series"""
x._series[idx] = val
def _mpsetval(x, idx, val):
"""Macro like function which makes clear that one is setting a value in the
underlying series"""
x._series[x._minperiod - 1 + idx] = val
|
##Patterns: E0103
def test():
while True:
break
##Err: E0103
break
for letter in 'Python':
if letter == 'h':
continue
##Err: E0103
continue
|
def test():
while True:
break
break
for letter in 'Python':
if letter == 'h':
continue
continue
|
def checkio(f, g):
def call(function, *args, **kwargs):
try: return function(*args, **kwargs)
except Exception: return None
def h(*args, **kwargs):
value_f, value_g = call(f, *args, **kwargs), call(g, *args, **kwargs)
status = ""
if (value_f is None and value_g is None): status = "both_error"
elif (value_f is None): status = "f_error"
elif (value_g is None): status = "g_error"
elif (value_f == value_g): status = "same"
else: status = "different"
if (value_f is None and value_g is None): return (None, status)
elif (value_f is None): return (value_g, status)
else: return (value_f, status)
return h
if __name__ == "__main__":
#These "asserts" using only for self-checking and not necessary for auto-testing
# (x+y)(x-y)/(x-y)
assert checkio(lambda x,y:x+y,
lambda x,y:(x**2-y**2)/(x-y))\
(1,3)==(4,"same"), "Function: x+y, first"
assert checkio(lambda x,y:x+y,
lambda x,y:(x**2-y**2)/(x-y))\
(1,2)==(3,"same"), "Function: x+y, second"
assert checkio(lambda x,y:x+y,
lambda x,y:(x**2-y**2)/(x-y))\
(1,1.01)==(2.01,"different"), "x+y, third"
assert checkio(lambda x,y:x+y,
lambda x,y:(x**2-y**2)/(x-y))\
(1,1)==(2,"g_error"), "x+y, fourth"
# Remove odds from list
f = lambda nums:[x for x in nums if ~x%2]
def g(nums):
for i in range(len(nums)):
if nums[i]%2==1:
nums.pop(i)
return nums
assert checkio(f,g)([2,4,6,8]) == ([2,4,6,8],"same"), "evens, first"
assert checkio(f,g)([2,3,4,6,8]) == ([2,4,6,8],"g_error"), "evens, second"
# Fizz Buzz
assert checkio(lambda n:("Fizz "*(1-n%3) + "Buzz "*(1-n%5))[:-1] or str(n),
lambda n:("Fizz"*(n%3==0) + " " + "Buzz"*(n%5==0)).strip())\
(6)==("Fizz","same"), "fizz buzz, first"
assert checkio(lambda n:("Fizz "*(1-n%3) + "Buzz "*(1-n%5))[:-1] or str(n),
lambda n:("Fizz"*(n%3==0) + " " + "Buzz"*(n%5==0)).strip())\
(30)==("Fizz Buzz","same"), "fizz buzz, second"
assert checkio(lambda n:("Fizz "*(1-n%3) + "Buzz "*(1-n%5))[:-1] or str(n),
lambda n:("Fizz"*(n%3==0) + " " + "Buzz"*(n%5==0)).strip())\
(7)==("7","different"), "fizz buzz, third"
|
def checkio(f, g):
def call(function, *args, **kwargs):
try:
return function(*args, **kwargs)
except Exception:
return None
def h(*args, **kwargs):
(value_f, value_g) = (call(f, *args, **kwargs), call(g, *args, **kwargs))
status = ''
if value_f is None and value_g is None:
status = 'both_error'
elif value_f is None:
status = 'f_error'
elif value_g is None:
status = 'g_error'
elif value_f == value_g:
status = 'same'
else:
status = 'different'
if value_f is None and value_g is None:
return (None, status)
elif value_f is None:
return (value_g, status)
else:
return (value_f, status)
return h
if __name__ == '__main__':
assert checkio(lambda x, y: x + y, lambda x, y: (x ** 2 - y ** 2) / (x - y))(1, 3) == (4, 'same'), 'Function: x+y, first'
assert checkio(lambda x, y: x + y, lambda x, y: (x ** 2 - y ** 2) / (x - y))(1, 2) == (3, 'same'), 'Function: x+y, second'
assert checkio(lambda x, y: x + y, lambda x, y: (x ** 2 - y ** 2) / (x - y))(1, 1.01) == (2.01, 'different'), 'x+y, third'
assert checkio(lambda x, y: x + y, lambda x, y: (x ** 2 - y ** 2) / (x - y))(1, 1) == (2, 'g_error'), 'x+y, fourth'
f = lambda nums: [x for x in nums if ~x % 2]
def g(nums):
for i in range(len(nums)):
if nums[i] % 2 == 1:
nums.pop(i)
return nums
assert checkio(f, g)([2, 4, 6, 8]) == ([2, 4, 6, 8], 'same'), 'evens, first'
assert checkio(f, g)([2, 3, 4, 6, 8]) == ([2, 4, 6, 8], 'g_error'), 'evens, second'
assert checkio(lambda n: ('Fizz ' * (1 - n % 3) + 'Buzz ' * (1 - n % 5))[:-1] or str(n), lambda n: ('Fizz' * (n % 3 == 0) + ' ' + 'Buzz' * (n % 5 == 0)).strip())(6) == ('Fizz', 'same'), 'fizz buzz, first'
assert checkio(lambda n: ('Fizz ' * (1 - n % 3) + 'Buzz ' * (1 - n % 5))[:-1] or str(n), lambda n: ('Fizz' * (n % 3 == 0) + ' ' + 'Buzz' * (n % 5 == 0)).strip())(30) == ('Fizz Buzz', 'same'), 'fizz buzz, second'
assert checkio(lambda n: ('Fizz ' * (1 - n % 3) + 'Buzz ' * (1 - n % 5))[:-1] or str(n), lambda n: ('Fizz' * (n % 3 == 0) + ' ' + 'Buzz' * (n % 5 == 0)).strip())(7) == ('7', 'different'), 'fizz buzz, third'
|
# --------------
# Code starts here
class_1 = ['Geoffrey Hinton' , 'Andrew Ng' , 'Sebastian Raschka' , 'Yoshua Bengio']
class_2 = ['Hilary Mason' , 'Carla Gentry' , 'Corinna Cortes']
new_class = class_1+class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
new_class.remove('Carla Gentry')
print(new_class)
# Code ends here
# --------------
# Code starts here
courses = {'Math':65, 'English':70, 'History':80, 'French': 70, 'Science':60}
total = sum(courses.values())
print(total)
percentage = total/500*100
print(percentage)
# Code ends here
# --------------
# Code starts here
mathematics = {'Geoffrey Hinton': 78, 'Andrew Ng': 95, 'Sebastian Raschka': 65,
'Yoshua Benjio': 50, 'Hilary Mason': 70, 'Corinna Cortes': 60, 'Peter Warden': 75}
topper = max(mathematics,key = mathematics.get)
print(topper)
# Code ends here
# --------------
# Given string
topper = 'andrew ng'
# Code starts here
print('-'*20)
first_name = topper.split()[0]
last_name = topper.split()[1]
full_name = f'{last_name} {first_name}'
print(full_name)
certificate_name = full_name.upper()
print(certificate_name)
# Code ends here
|
class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio']
class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes']
new_class = class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
new_class.remove('Carla Gentry')
print(new_class)
courses = {'Math': 65, 'English': 70, 'History': 80, 'French': 70, 'Science': 60}
total = sum(courses.values())
print(total)
percentage = total / 500 * 100
print(percentage)
mathematics = {'Geoffrey Hinton': 78, 'Andrew Ng': 95, 'Sebastian Raschka': 65, 'Yoshua Benjio': 50, 'Hilary Mason': 70, 'Corinna Cortes': 60, 'Peter Warden': 75}
topper = max(mathematics, key=mathematics.get)
print(topper)
topper = 'andrew ng'
print('-' * 20)
first_name = topper.split()[0]
last_name = topper.split()[1]
full_name = f'{last_name} {first_name}'
print(full_name)
certificate_name = full_name.upper()
print(certificate_name)
|
N = int(input())
a,b = 1,1
print(0,end=' ')
for i in range(1,N-1):
if i != N:
print(a,end=' ')
a,b = b,a+b
print(a,end='\n')
|
n = int(input())
(a, b) = (1, 1)
print(0, end=' ')
for i in range(1, N - 1):
if i != N:
print(a, end=' ')
(a, b) = (b, a + b)
print(a, end='\n')
|
# This is a dummy file to allow the automatic loading of modules without error on none.
def setup(robot_config):
return
def say(*args):
return
def mute():
return
def unmute():
return
def volume(level):
return
|
def setup(robot_config):
return
def say(*args):
return
def mute():
return
def unmute():
return
def volume(level):
return
|
class FeeValidator:
def __init__(self, specifier) -> None:
super().__init__()
self.specifier = specifier
def validate(self, fee):
failed=False
try:
if fee != 0 and not 1 <= fee <= 100:
failed=True
except TypeError:
failed=True
if failed:
raise Exception("Fee for {} cannot be {}. Valid values are 0, [1-100]".format(self.specifier, fee))
|
class Feevalidator:
def __init__(self, specifier) -> None:
super().__init__()
self.specifier = specifier
def validate(self, fee):
failed = False
try:
if fee != 0 and (not 1 <= fee <= 100):
failed = True
except TypeError:
failed = True
if failed:
raise exception('Fee for {} cannot be {}. Valid values are 0, [1-100]'.format(self.specifier, fee))
|
#!/usr/bin/env python3
"""
Get information on the inferface.
"""
help(gdb)
help(gdb.command)
help(gdb.events)
help(gdb.function)
|
"""
Get information on the inferface.
"""
help(gdb)
help(gdb.command)
help(gdb.events)
help(gdb.function)
|
INSERT_ONE_BY_BYTE = "insert_one_by_byte"
INSERT_ONE_BY_PATH = "insert_one_by_path"
INSERT_MANY_BY_BYTE = "insert_many_by_byte"
INSERT_MANY_BY_DIR = "insert_many_by_dir"
INSERT_MANY_BY_PATHS = "insert_many_by_paths"
DELETE_ONE_BY_ID = "delete_one_by_id"
DELETE_MANY_BY_IDS = "delete_many_by_ids"
DELETE_ALL = "delete_all"
UPDATE_ONE_BY_ID = "update_one_by_id"
UPDATE_MANY_BY_IDS = "update_many_by_ids"
RETRIEVE_ONE = "retrieve_one"
RETRIEVE_MANY = "retrieve_many"
QUERY_NEAREST_BY_CONTENT = "query_nearest_by_content"
QUERY_NEAREST_BY_STYLE = "query_nearest_by_style"
QUERY_FARTHEST_BY_CONTENT = "query_farthest_by_content"
QUERY_FARTHEST_BY_STYLE = "query_farthest_by_style"
QUERY_BY_TAG_ALL = "query_by_tag_all"
QUERY_BY_TAG_PARTIAL = "query_by_tag_partial"
QUERY_RANGE_BY_CONTENT = "query_range_by_content"
QUERY_RANGE_BY_STYLE = "query_range_by_style"
BROWSE_BY_RANDOM = "browse_by_random"
BROWSE_BY_CLUSTER = "browse_by_cluster"
|
insert_one_by_byte = 'insert_one_by_byte'
insert_one_by_path = 'insert_one_by_path'
insert_many_by_byte = 'insert_many_by_byte'
insert_many_by_dir = 'insert_many_by_dir'
insert_many_by_paths = 'insert_many_by_paths'
delete_one_by_id = 'delete_one_by_id'
delete_many_by_ids = 'delete_many_by_ids'
delete_all = 'delete_all'
update_one_by_id = 'update_one_by_id'
update_many_by_ids = 'update_many_by_ids'
retrieve_one = 'retrieve_one'
retrieve_many = 'retrieve_many'
query_nearest_by_content = 'query_nearest_by_content'
query_nearest_by_style = 'query_nearest_by_style'
query_farthest_by_content = 'query_farthest_by_content'
query_farthest_by_style = 'query_farthest_by_style'
query_by_tag_all = 'query_by_tag_all'
query_by_tag_partial = 'query_by_tag_partial'
query_range_by_content = 'query_range_by_content'
query_range_by_style = 'query_range_by_style'
browse_by_random = 'browse_by_random'
browse_by_cluster = 'browse_by_cluster'
|
lista = []
lista_par = []
lista_impar = []
while True:
n = (int(input('Digite os numeros: ')))
lista.append(n)
if n % 2 == 0:
lista_par.append(n)
else:
lista_impar.append(n)
res = str(input('Quer continuar [S/N] : '))
if res in 'Nn':
break
print(f'O numeros da lista fora : {lista}')
print(f'O numeros pares foram : {lista_par}')
print(f'O numeros impares foram : {lista_impar}')
|
lista = []
lista_par = []
lista_impar = []
while True:
n = int(input('Digite os numeros: '))
lista.append(n)
if n % 2 == 0:
lista_par.append(n)
else:
lista_impar.append(n)
res = str(input('Quer continuar [S/N] : '))
if res in 'Nn':
break
print(f'O numeros da lista fora : {lista}')
print(f'O numeros pares foram : {lista_par}')
print(f'O numeros impares foram : {lista_impar}')
|
input = """
1 2 0 0
1 3 0 0
1 4 0 0
1 5 0 0
1 6 0 0
1 7 0 0
1 8 0 0
1 9 0 0
1 10 0 0
1 11 0 0
1 12 0 0
1 13 0 0
1 14 0 0
1 15 0 0
1 16 0 0
1 17 0 0
1 18 1 1 19
1 20 1 1 21
1 22 1 1 23
1 24 1 1 25
1 26 1 1 27
1 28 1 1 29
1 19 1 1 18
1 21 1 1 20
1 23 1 1 22
1 25 1 1 24
1 27 1 1 26
1 29 1 1 28
1 1 1 1 18
2 30 2 0 2 22 20
1 1 1 1 30
2 31 3 0 1 28 26 24
1 32 1 1 31
1 1 1 1 32
2 33 3 0 2 24 20 18
2 34 3 0 3 24 20 18
1 35 2 1 34 33
1 1 1 1 35
2 36 1 0 1 26
1 37 1 1 36
1 1 1 1 37
2 38 2 0 1 28 22
2 39 2 0 2 28 22
1 40 2 1 39 38
1 1 1 1 40
1 1 2 0 20 19
1 1 2 0 22 19
1 1 2 0 24 21
1 1 2 0 24 23
1 1 2 0 26 21
1 1 2 0 26 23
1 1 2 0 28 21
1 1 2 0 28 23
1 1 2 0 20 23
1 1 2 0 22 21
1 1 2 0 24 27
1 1 2 0 24 29
1 1 2 0 26 25
1 1 2 0 26 29
1 1 2 0 28 25
1 1 2 0 28 27
0
2 xsucc(1,2)
3 xsucc(2,3)
18 filled(3,3)
20 filled(3,2)
22 filled(1,2)
24 filled(3,1)
26 filled(2,1)
28 filled(1,1)
4 ysucc(1,2)
5 ysucc(2,3)
19 unfilled(3,3)
21 unfilled(3,2)
23 unfilled(1,2)
25 unfilled(3,1)
27 unfilled(2,1)
29 unfilled(1,1)
12 xvalue(1,0)
13 xvalue(2,2)
14 xvalue(3,1)
6 bottle(1,1,1)
7 bottle(1,2,1)
8 bottle(1,3,1)
9 bottle(1,1,2)
10 bottle(1,3,2)
11 bottle(1,3,3)
15 yvalue(1,1)
16 yvalue(2,0)
17 yvalue(3,2)
0
B+
0
B-
1
0
1
"""
output = """
{xsucc(1,2), xsucc(2,3), ysucc(1,2), ysucc(2,3), bottle(1,1,1), bottle(1,2,1), bottle(1,3,1), bottle(1,1,2), bottle(1,3,2), bottle(1,3,3), xvalue(1,0), xvalue(2,2), xvalue(3,1), yvalue(1,1), yvalue(2,0), yvalue(3,2), filled(3,3), filled(3,2), filled(1,2), unfilled(3,1), unfilled(2,1), unfilled(1,1)}
"""
|
input = '\n1 2 0 0\n1 3 0 0\n1 4 0 0\n1 5 0 0\n1 6 0 0\n1 7 0 0\n1 8 0 0\n1 9 0 0\n1 10 0 0\n1 11 0 0\n1 12 0 0\n1 13 0 0\n1 14 0 0\n1 15 0 0\n1 16 0 0\n1 17 0 0\n1 18 1 1 19\n1 20 1 1 21\n1 22 1 1 23\n1 24 1 1 25\n1 26 1 1 27\n1 28 1 1 29\n1 19 1 1 18\n1 21 1 1 20\n1 23 1 1 22\n1 25 1 1 24\n1 27 1 1 26\n1 29 1 1 28\n1 1 1 1 18\n2 30 2 0 2 22 20\n1 1 1 1 30\n2 31 3 0 1 28 26 24\n1 32 1 1 31\n1 1 1 1 32\n2 33 3 0 2 24 20 18\n2 34 3 0 3 24 20 18\n1 35 2 1 34 33\n1 1 1 1 35\n2 36 1 0 1 26\n1 37 1 1 36\n1 1 1 1 37\n2 38 2 0 1 28 22\n2 39 2 0 2 28 22\n1 40 2 1 39 38\n1 1 1 1 40\n1 1 2 0 20 19\n1 1 2 0 22 19\n1 1 2 0 24 21\n1 1 2 0 24 23\n1 1 2 0 26 21\n1 1 2 0 26 23\n1 1 2 0 28 21\n1 1 2 0 28 23\n1 1 2 0 20 23\n1 1 2 0 22 21\n1 1 2 0 24 27\n1 1 2 0 24 29\n1 1 2 0 26 25\n1 1 2 0 26 29\n1 1 2 0 28 25\n1 1 2 0 28 27\n0\n2 xsucc(1,2)\n3 xsucc(2,3)\n18 filled(3,3)\n20 filled(3,2)\n22 filled(1,2)\n24 filled(3,1)\n26 filled(2,1)\n28 filled(1,1)\n4 ysucc(1,2)\n5 ysucc(2,3)\n19 unfilled(3,3)\n21 unfilled(3,2)\n23 unfilled(1,2)\n25 unfilled(3,1)\n27 unfilled(2,1)\n29 unfilled(1,1)\n12 xvalue(1,0)\n13 xvalue(2,2)\n14 xvalue(3,1)\n6 bottle(1,1,1)\n7 bottle(1,2,1)\n8 bottle(1,3,1)\n9 bottle(1,1,2)\n10 bottle(1,3,2)\n11 bottle(1,3,3)\n15 yvalue(1,1)\n16 yvalue(2,0)\n17 yvalue(3,2)\n0\nB+\n0\nB-\n1\n0\n1\n'
output = '\n{xsucc(1,2), xsucc(2,3), ysucc(1,2), ysucc(2,3), bottle(1,1,1), bottle(1,2,1), bottle(1,3,1), bottle(1,1,2), bottle(1,3,2), bottle(1,3,3), xvalue(1,0), xvalue(2,2), xvalue(3,1), yvalue(1,1), yvalue(2,0), yvalue(3,2), filled(3,3), filled(3,2), filled(1,2), unfilled(3,1), unfilled(2,1), unfilled(1,1)}\n'
|
test = [11.0, "Alice has a cat", 12, 4, "5"]
print("len(test) = " + str(len(test)))
print("test[1] = " + str(test[1]))
print("test[3:6] = " + str(test[3:6]))
print("test[1:6:2] = " + str(test[1:6:2]))
print("test[:6] = " + str(test[:6]))
print("test[-2] = " + str(test[-2]))
test.append(121)
test2 = test + [1, 2, 3]
print("len(test2) = " + str(len(test2)))
test2[0] = "Lodz"
test2[6] = 77
print(test2)
|
test = [11.0, 'Alice has a cat', 12, 4, '5']
print('len(test) = ' + str(len(test)))
print('test[1] = ' + str(test[1]))
print('test[3:6] = ' + str(test[3:6]))
print('test[1:6:2] = ' + str(test[1:6:2]))
print('test[:6] = ' + str(test[:6]))
print('test[-2] = ' + str(test[-2]))
test.append(121)
test2 = test + [1, 2, 3]
print('len(test2) = ' + str(len(test2)))
test2[0] = 'Lodz'
test2[6] = 77
print(test2)
|
class dotStringProperty_t(object):
# no doc
aName=None
aValueString=None
FatherId=None
ValueStringIteration=None
|
class Dotstringproperty_T(object):
a_name = None
a_value_string = None
father_id = None
value_string_iteration = None
|
#!/usr/bin/env python
# encoding: utf-8
# The MIT License
#
# Copyright (c) 2011 Wyss Institute at Harvard University
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# http://www.opensource.org/licenses/mit-license.php
class Modifier(object):
"""
Modifiers do affect an applied sequence and do not store a sequence
themselves. They cause a base changed to another sequence.
Modifiers DO NOT affect the length of a strand
"""
def __init__(self, idx):
if self.__class__ == Modifier:
e = "Modifier should be subclassed."
raise NotImplementedError(e)
self._mType = None
self._lowIdx = idx
self._highIdx = self._lowIdx
self._privateSequence = None
# end def
def length(self):
"""
This is the length of a sequence that is immutable by the strand
"""
return self._highIdx - self._lowIdx + 1
def modifierType(self):
return self._mtype
# end class
|
class Modifier(object):
"""
Modifiers do affect an applied sequence and do not store a sequence
themselves. They cause a base changed to another sequence.
Modifiers DO NOT affect the length of a strand
"""
def __init__(self, idx):
if self.__class__ == Modifier:
e = 'Modifier should be subclassed.'
raise not_implemented_error(e)
self._mType = None
self._lowIdx = idx
self._highIdx = self._lowIdx
self._privateSequence = None
def length(self):
"""
This is the length of a sequence that is immutable by the strand
"""
return self._highIdx - self._lowIdx + 1
def modifier_type(self):
return self._mtype
|
# pylint: disable=missing-function-docstring, missing-module-docstring/
@toto # pylint: disable=undefined-variable
def f():
pass
|
@toto
def f():
pass
|
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
class Solution:
"""
@param root: An object of TreeNode, denote the root of the binary tree.
This method will be invoked first, you should design your own algorithm
to serialize a binary tree which denote by a root node to a string which
can be easily deserialized by your own "deserialize" method later.
"""
def serialize(self, root):
result = []
self.serializeHelper(root,result)
return ",".join(result)
def serializeHelper(self,root,result) :
if root is None :
result.append('$')
return
result.append(str(root.val))
self.serializeHelper(root.left,result)
self.serializeHelper(root.right,result)
"""
@param data: A string serialized by your serialize method.
This method will be invoked second, the argument data is what exactly
you serialized at method "serialize", that means the data is not given by
system, it's given by your own serialize method. So the format of data is
designed by yourself, and deserialize it here as you serialize it in
"serialize" method.
"""
def deserialize(self, data):
self.index = 0
return self.deserializeHelper(data.split(','))
def deserializeHelper(self,data):
if self.index == len(data) :
return None
if data[self.index] == '$' :
self.index += 1
return None
root = TreeNode(data[self.index])
self.index += 1
root.left = self.deserializeHelper(data)
root.right = self.deserializeHelper(data)
return root
|
class Treenode:
def __init__(self, val):
self.val = val
(self.left, self.right) = (None, None)
class Solution:
"""
@param root: An object of TreeNode, denote the root of the binary tree.
This method will be invoked first, you should design your own algorithm
to serialize a binary tree which denote by a root node to a string which
can be easily deserialized by your own "deserialize" method later.
"""
def serialize(self, root):
result = []
self.serializeHelper(root, result)
return ','.join(result)
def serialize_helper(self, root, result):
if root is None:
result.append('$')
return
result.append(str(root.val))
self.serializeHelper(root.left, result)
self.serializeHelper(root.right, result)
'\n @param data: A string serialized by your serialize method.\n This method will be invoked second, the argument data is what exactly\n you serialized at method "serialize", that means the data is not given by\n system, it\'s given by your own serialize method. So the format of data is\n designed by yourself, and deserialize it here as you serialize it in \n "serialize" method.\n '
def deserialize(self, data):
self.index = 0
return self.deserializeHelper(data.split(','))
def deserialize_helper(self, data):
if self.index == len(data):
return None
if data[self.index] == '$':
self.index += 1
return None
root = tree_node(data[self.index])
self.index += 1
root.left = self.deserializeHelper(data)
root.right = self.deserializeHelper(data)
return root
|
x = 50
def func(x):
print('x is',x)
x = 2
print('Changed local x to',x)
func(x)
print('x is still',x)
|
x = 50
def func(x):
print('x is', x)
x = 2
print('Changed local x to', x)
func(x)
print('x is still', x)
|
"""Adapters for twisted.vfs.
This package provides adapters to hook up systems SFTP and FTP to the
IFileSystemLeaf and IFileSystemDirectory interfaces of VFS.
"""
|
"""Adapters for twisted.vfs.
This package provides adapters to hook up systems SFTP and FTP to the
IFileSystemLeaf and IFileSystemDirectory interfaces of VFS.
"""
|
class WebEncoderException(Exception):
pass
class InvalidEncodingErrors(WebEncoderException):
"""Exception raised for errors in the input value of encoding_errors attribute of WebEncoder class.
Args:
message: explanation of the error
"""
def __init__(self, message=None):
self.message = (
message
or "Invalid encoding_errors value. It should be 'strict', 'ignore', 'replace' or 'xmlcharrefreplace'."
)
super().__init__(self.message)
class InvalidStringType(WebEncoderException):
"""Exception raised for errors in the input value of _string into _string_to_bytes method of WebEncoder class.
Args:
message: explanation of the error
"""
def __init__(self, message=None):
self.message = message or "The _string need to be str type."
super().__init__(self.message)
class InvalidBytesType(WebEncoderException):
"""Exception raised for errors in the input value of _bytes into methods of WebEncoder class.
Args:
message: explanation of the error
"""
def __init__(self, message=None):
self.message = message or "The _bytes need to be bytes type."
super().__init__(self.message)
class InvalidDataType(WebEncoderException):
"""Exception raised for errors in the input value of data into encode method of WebEncoder class.
Args:
message: explanation of the error
"""
def __init__(self, message=None):
self.message = message or "The data need to be str type."
super().__init__(self.message)
class InvalidEncodedDataType(WebEncoderException):
"""Exception raised for errors in the input value of encoded_data into decode method of WebEncoder class.
Args:
message: explanation of the error
"""
def __init__(self, message=None):
self.message = message or "The encoded_data need to be str type."
super().__init__(self.message)
class DataDecodeError(WebEncoderException):
"""Exception raised for data decoding error in _bytes_to_string of WebEncoder class.
Args:
message: explanation of the error
"""
def __init__(self, message=None):
self.message = message or "Could not decode the message."
super().__init__(self.message)
class CannotBeCompressed(WebEncoderException):
"""Exception raised for errors in the _compress_data method of WebEncoder class.
Args:
message: explanation of the error
"""
def __init__(self, message=None):
self.message = message or "The data cannot be compressed."
super().__init__(self.message)
class CannotBeDecompressed(WebEncoderException):
"""Exception raised for errors in the _decompress_data method of WebEncoder class.
Args:
message: explanation of the error
"""
def __init__(self, message=None):
self.message = message or "The data cannot be decompressed."
super().__init__(self.message)
|
class Webencoderexception(Exception):
pass
class Invalidencodingerrors(WebEncoderException):
"""Exception raised for errors in the input value of encoding_errors attribute of WebEncoder class.
Args:
message: explanation of the error
"""
def __init__(self, message=None):
self.message = message or "Invalid encoding_errors value. It should be 'strict', 'ignore', 'replace' or 'xmlcharrefreplace'."
super().__init__(self.message)
class Invalidstringtype(WebEncoderException):
"""Exception raised for errors in the input value of _string into _string_to_bytes method of WebEncoder class.
Args:
message: explanation of the error
"""
def __init__(self, message=None):
self.message = message or 'The _string need to be str type.'
super().__init__(self.message)
class Invalidbytestype(WebEncoderException):
"""Exception raised for errors in the input value of _bytes into methods of WebEncoder class.
Args:
message: explanation of the error
"""
def __init__(self, message=None):
self.message = message or 'The _bytes need to be bytes type.'
super().__init__(self.message)
class Invaliddatatype(WebEncoderException):
"""Exception raised for errors in the input value of data into encode method of WebEncoder class.
Args:
message: explanation of the error
"""
def __init__(self, message=None):
self.message = message or 'The data need to be str type.'
super().__init__(self.message)
class Invalidencodeddatatype(WebEncoderException):
"""Exception raised for errors in the input value of encoded_data into decode method of WebEncoder class.
Args:
message: explanation of the error
"""
def __init__(self, message=None):
self.message = message or 'The encoded_data need to be str type.'
super().__init__(self.message)
class Datadecodeerror(WebEncoderException):
"""Exception raised for data decoding error in _bytes_to_string of WebEncoder class.
Args:
message: explanation of the error
"""
def __init__(self, message=None):
self.message = message or 'Could not decode the message.'
super().__init__(self.message)
class Cannotbecompressed(WebEncoderException):
"""Exception raised for errors in the _compress_data method of WebEncoder class.
Args:
message: explanation of the error
"""
def __init__(self, message=None):
self.message = message or 'The data cannot be compressed.'
super().__init__(self.message)
class Cannotbedecompressed(WebEncoderException):
"""Exception raised for errors in the _decompress_data method of WebEncoder class.
Args:
message: explanation of the error
"""
def __init__(self, message=None):
self.message = message or 'The data cannot be decompressed.'
super().__init__(self.message)
|
class Node():
def __init__(self, value="", frequency=0.0):
self.frequency = frequency
self.value = value
self.children = {}
self.stop = False
def __getitem__(self, key):
if key in self.children:
return self.children[key]
return None
def __setitem__(self, key, value):
self.children[key] = value
def __contains__(self, key):
return key in self.children
def __str__(self):
return self.value
def __iter__(self):
for key in sorted(self.children.keys()):
yield key
def __delitem__(self, key):
del self.children[key]
class Trie:
def __init__(self):
self.root = Node()
def add_word(self, word, frequency):
word = word.lower()
current_node = self.root
for letter in word:
if letter not in current_node:
current_node[letter] = Node(letter)
current_node = current_node[letter]
current_node.stop = True
current_node.frequency = frequency
@staticmethod
def get_possible_matches(node, words_list, path):
if node.stop:
words_list.append((path + node.value, node.frequency))
for letter in node.children:
Trie.get_possible_matches(node.children[letter], words_list, path + node.value)
def match_suffix(self, word):
current_node = self.root
for letter in word.lower():
if letter in current_node:
current_node = current_node[letter]
# word += current_node.value
else:
return False
possible_words = []
self.get_possible_matches(current_node, possible_words, word[:-1])
return possible_words
def contains(self, word):
current_node = self.root
path = ""
for letter in word.lower():
if letter not in current_node:
return False
else:
path += letter
current_node = current_node[letter]
if current_node.stop:
return True
return False
def __contains__(self, key):
return self.contains(key)
@staticmethod
def _print(node, path=""):
if node.stop:
print(path + node.value, node.frequency)
for letter in node.children:
Trie._print(node.children[letter], path + node.value)
def print_content(self):
for letter in self.root.children:
self._print(self.root[letter])
if __name__ == "__main__":
t = Trie()
t.add_word("kaka")
t.add_word("kakan")
t.add_word("kakor")
t.print_content()
print("---------------")
print(t.contains("kaka"))
|
class Node:
def __init__(self, value='', frequency=0.0):
self.frequency = frequency
self.value = value
self.children = {}
self.stop = False
def __getitem__(self, key):
if key in self.children:
return self.children[key]
return None
def __setitem__(self, key, value):
self.children[key] = value
def __contains__(self, key):
return key in self.children
def __str__(self):
return self.value
def __iter__(self):
for key in sorted(self.children.keys()):
yield key
def __delitem__(self, key):
del self.children[key]
class Trie:
def __init__(self):
self.root = node()
def add_word(self, word, frequency):
word = word.lower()
current_node = self.root
for letter in word:
if letter not in current_node:
current_node[letter] = node(letter)
current_node = current_node[letter]
current_node.stop = True
current_node.frequency = frequency
@staticmethod
def get_possible_matches(node, words_list, path):
if node.stop:
words_list.append((path + node.value, node.frequency))
for letter in node.children:
Trie.get_possible_matches(node.children[letter], words_list, path + node.value)
def match_suffix(self, word):
current_node = self.root
for letter in word.lower():
if letter in current_node:
current_node = current_node[letter]
else:
return False
possible_words = []
self.get_possible_matches(current_node, possible_words, word[:-1])
return possible_words
def contains(self, word):
current_node = self.root
path = ''
for letter in word.lower():
if letter not in current_node:
return False
else:
path += letter
current_node = current_node[letter]
if current_node.stop:
return True
return False
def __contains__(self, key):
return self.contains(key)
@staticmethod
def _print(node, path=''):
if node.stop:
print(path + node.value, node.frequency)
for letter in node.children:
Trie._print(node.children[letter], path + node.value)
def print_content(self):
for letter in self.root.children:
self._print(self.root[letter])
if __name__ == '__main__':
t = trie()
t.add_word('kaka')
t.add_word('kakan')
t.add_word('kakor')
t.print_content()
print('---------------')
print(t.contains('kaka'))
|
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"PairwiseDistance": "00_distance.ipynb",
"pairwise_dist_gram": "00_distance.ipynb",
"stackoverflow_pairwise_distance": "00_distance.ipynb",
"PairwiseDistance.stackoverflow_pairwise_distance": "00_distance.ipynb",
"torch_pairwise_distance": "00_distance.ipynb",
"PairwiseDistance.torch_pairwise_distance": "00_distance.ipynb",
"measure_execution_time": "00_distance.ipynb",
"get_time_stats": "00_distance.ipynb",
"DistanceMatrixIndexMapper": "00_distance.ipynb",
"Hull": "00_distance.ipynb",
"to_2dpositions": "00_distance.ipynb",
"Hull.to_2dpositions": "00_distance.ipynb",
"plot_atoms_and_hull": "00_distance.ipynb"}
modules = ["distance.py"]
doc_url = "https://eschmidt42.github.io/md/"
git_url = "https://github.com/eschmidt42/md/tree/master/"
def custom_doc_links(name): return None
|
__all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'PairwiseDistance': '00_distance.ipynb', 'pairwise_dist_gram': '00_distance.ipynb', 'stackoverflow_pairwise_distance': '00_distance.ipynb', 'PairwiseDistance.stackoverflow_pairwise_distance': '00_distance.ipynb', 'torch_pairwise_distance': '00_distance.ipynb', 'PairwiseDistance.torch_pairwise_distance': '00_distance.ipynb', 'measure_execution_time': '00_distance.ipynb', 'get_time_stats': '00_distance.ipynb', 'DistanceMatrixIndexMapper': '00_distance.ipynb', 'Hull': '00_distance.ipynb', 'to_2dpositions': '00_distance.ipynb', 'Hull.to_2dpositions': '00_distance.ipynb', 'plot_atoms_and_hull': '00_distance.ipynb'}
modules = ['distance.py']
doc_url = 'https://eschmidt42.github.io/md/'
git_url = 'https://github.com/eschmidt42/md/tree/master/'
def custom_doc_links(name):
return None
|
class AppUserProfile:
types = {
'username': str,
'password': str
}
def __init__(self):
self.username = None # str
self.password = None # str
|
class Appuserprofile:
types = {'username': str, 'password': str}
def __init__(self):
self.username = None
self.password = None
|
"""Hydra Library Tools & Applications.
"""
__all__ = (
"app", "hy", "log", "rpc", "test", "util"
)
VERSION = "2.6.5"
|
"""Hydra Library Tools & Applications.
"""
__all__ = ('app', 'hy', 'log', 'rpc', 'test', 'util')
version = '2.6.5'
|
class Container:
def __init__(self, container=None):
if container == None or type(container) != dict:
self._container = dict()
else:
self._container = container
def __iter__(self):
return iter(self._container.items())
def addObject(self, name, object_:object):
self._container[name] = object_
def hasObject(self, name):
return self._container.get(name) is not None
def getObject(self, name) -> object:
return self._container.get(name)
def delete(self, name) -> object:
return self._container.pop(name)
def clearAll(self):
self._container.clear()
|
class Container:
def __init__(self, container=None):
if container == None or type(container) != dict:
self._container = dict()
else:
self._container = container
def __iter__(self):
return iter(self._container.items())
def add_object(self, name, object_: object):
self._container[name] = object_
def has_object(self, name):
return self._container.get(name) is not None
def get_object(self, name) -> object:
return self._container.get(name)
def delete(self, name) -> object:
return self._container.pop(name)
def clear_all(self):
self._container.clear()
|
# Numeral System Converter
"""
TODO
1. Convert from any system to decimal
"""
def binary_to_decimal(bin_string:str) -> int:
bin_string = str(bin_string).strip()
if not bin_string:
raise ValueError("Empty string was passed to the function")
is_negative = bin_string[0] == "-"
if is_negative:
bin_string = bin_string[1:]
if not all(char in "01" for char in bin_string):
raise ValueError("Non-binary value was passed to the function")
decimal_number = 0
for char in bin_string:
decimal_number = 2 * decimal_number + int(char)
return -decimal_number if is_negative else decimal_number
def to_dec(num:int) -> int:
pass
def main():
print(binary_to_decimal(2))
pass
if __name__ == "__main__":
main()
|
"""
TODO
1. Convert from any system to decimal
"""
def binary_to_decimal(bin_string: str) -> int:
bin_string = str(bin_string).strip()
if not bin_string:
raise value_error('Empty string was passed to the function')
is_negative = bin_string[0] == '-'
if is_negative:
bin_string = bin_string[1:]
if not all((char in '01' for char in bin_string)):
raise value_error('Non-binary value was passed to the function')
decimal_number = 0
for char in bin_string:
decimal_number = 2 * decimal_number + int(char)
return -decimal_number if is_negative else decimal_number
def to_dec(num: int) -> int:
pass
def main():
print(binary_to_decimal(2))
pass
if __name__ == '__main__':
main()
|
class AcousticParam(object):
def __init__(
self,
sampling_rate: int = 24000,
pad_second: float = 0,
threshold_db: float = None,
frame_period: int = 5,
order: int = 8,
alpha: float = 0.466,
f0_floor: float = 71,
f0_ceil: float = 800,
fft_length: int = 1024,
dtype: str = 'float32',
) -> None:
self.sampling_rate = sampling_rate
self.pad_second = pad_second
self.threshold_db = threshold_db
self.frame_period = frame_period
self.order = order
self.alpha = alpha
self.f0_floor = f0_floor
self.f0_ceil = f0_ceil
self.fft_length = fft_length
self.dtype = dtype
def _asdict(self):
return self.__dict__
|
class Acousticparam(object):
def __init__(self, sampling_rate: int=24000, pad_second: float=0, threshold_db: float=None, frame_period: int=5, order: int=8, alpha: float=0.466, f0_floor: float=71, f0_ceil: float=800, fft_length: int=1024, dtype: str='float32') -> None:
self.sampling_rate = sampling_rate
self.pad_second = pad_second
self.threshold_db = threshold_db
self.frame_period = frame_period
self.order = order
self.alpha = alpha
self.f0_floor = f0_floor
self.f0_ceil = f0_ceil
self.fft_length = fft_length
self.dtype = dtype
def _asdict(self):
return self.__dict__
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 11 12:52:32 2018
@author: cyril-kubu
"""
|
"""
Created on Tue Sep 11 12:52:32 2018
@author: cyril-kubu
"""
|
def print_vars(obj):
"""
Prints all non-private attributes variables (does not start with '_' and not method)
:param obj:
:return:
"""
for attr in dir(obj):
if attr[0] is "_" or callable(getattr(obj,attr)):
continue
print(attr, ":", getattr(obj, attr))
def print_methods(obj):
"""
Prints all non-private attributes methods (does not start with '_' and not method)
:param obj:
:return:
"""
for attr in dir(obj):
if attr[0] is "_" or not callable(getattr(obj,attr)):
continue
print(attr, ":", getattr(obj, attr))
def print_attr(obj):
"""
Prints all non-private attributes
:param obj:
:return:
"""
for attr in dir(obj):
if attr[0] is "_":
continue
print(attr, ":", getattr(obj, attr))
|
def print_vars(obj):
"""
Prints all non-private attributes variables (does not start with '_' and not method)
:param obj:
:return:
"""
for attr in dir(obj):
if attr[0] is '_' or callable(getattr(obj, attr)):
continue
print(attr, ':', getattr(obj, attr))
def print_methods(obj):
"""
Prints all non-private attributes methods (does not start with '_' and not method)
:param obj:
:return:
"""
for attr in dir(obj):
if attr[0] is '_' or not callable(getattr(obj, attr)):
continue
print(attr, ':', getattr(obj, attr))
def print_attr(obj):
"""
Prints all non-private attributes
:param obj:
:return:
"""
for attr in dir(obj):
if attr[0] is '_':
continue
print(attr, ':', getattr(obj, attr))
|
"""
Class for storing method parameters.
"""
class JavaMethodParameter:
def __init__(self, identifier, parameter_type):
self.__identifier = identifier
self.__type = parameter_type
@property
def identifier(self):
return self.__identifier
@property
def parameter_type(self):
return self.__type
|
"""
Class for storing method parameters.
"""
class Javamethodparameter:
def __init__(self, identifier, parameter_type):
self.__identifier = identifier
self.__type = parameter_type
@property
def identifier(self):
return self.__identifier
@property
def parameter_type(self):
return self.__type
|
def get_headers(text):
list_a = text.split("\n")[1:]
list_headers = []
for i in list_a:
if not i:
break
list_headers.append(i.split(": "))
return dict(list_headers)
|
def get_headers(text):
list_a = text.split('\n')[1:]
list_headers = []
for i in list_a:
if not i:
break
list_headers.append(i.split(': '))
return dict(list_headers)
|
#WAP to find, a given number is prime or not
num = int(input("enter number"))
if num>1:
#check for factors
for i in range(2,num):
if(num / i) == 0:
print(num," is not prime number")
break
else:
print(num," is not a prime number")
|
num = int(input('enter number'))
if num > 1:
for i in range(2, num):
if num / i == 0:
print(num, ' is not prime number')
break
else:
print(num, ' is not a prime number')
|
# Description: Print the B-factors of a residue.
# Source: placeHolder
"""
cmd.do('remove element h; iterate resi ${1: 1:13}, print(resi, name,b);')
"""
cmd.do('remove element h; iterate resi 1:13, print(resi, name,b);')
|
"""
cmd.do('remove element h; iterate resi ${1: 1:13}, print(resi, name,b);')
"""
cmd.do('remove element h; iterate resi 1:13, print(resi, name,b);')
|
def Scenario_Generation():
# first restricting the data to April 2020 when we are predicting six weeks out from april 2020
popularity_germany = np.load("./popularity_germany.npy")
popularity_germany = np.copy(popularity_germany[:,0:63,:]) # april 20th is the 63rd index in the popularity number
#
one = np.multiply(np.ones((16,42,6)),popularity_germany[:,62:63,:])
popularity_germany = np.append(popularity_germany,one,axis=1)
# bus movement is kept as 0 after march 18
# we keep the flight data same as what was observed on april 20th
# there has been no change in the trucj movement pattern (sp we keep as a weekly pattern)
# the data contains placeholder for 158 countries (so that we can capture the movement from all the countries)
bus_movement = np.load("./bus_movement.npy")
truck_movement = np.load("./truck_movement.npy")
flight_movement = np.load("./flight_movement.npy")
car_movement = np.load("./car_movement.npy")
train_movement = np.load("./train_movement.npy")
bus_move = bus_movement[:,0:63,:]
truck_move = truck_movement[:,0:63,:]
flight_move = flight_movement[:,0:63,:]
static_car_move = car_movement[:,0:63,:]
static_train_move = train_movement[:,0:63,:]
one = np.multiply(np.ones((16,42,158)),bus_move[:,62:63,:])
bus_move = np.append(bus_move,one,axis=1)
one = np.multiply(np.ones((16,42,158)),truck_move[:,62:63,:])
truck_move = np.append(truck_move,one,axis=1)
one = np.multiply(np.ones((16,42,158)),flight_move[:,62:63,:])
flight_move = np.append(flight_move,one,axis=1)
one = np.multiply(np.ones((16,42,158)),static_car_move[:,62:63,:])
static_car_move = np.append(static_car_move,one,axis=1)
one = np.multiply(np.ones((16,42,158)),static_train_move[:,62:63,:])
static_train_move = np.append(static_train_move,one,axis=1)
for t in range(63,63+42):
truck_move[:,t,:] = truck_move[:,t-7,:]
popularity_o = np.copy(popularity_germany)
policy_o = pd.read_csv("./policy.csv")
policy_o_life = pd.read_csv("./policy_lift.csv")
cols = ['Border Closure', 'Initial business closure',
'Educational facilities closed', 'Non-essential services closed',
'Stay at home order', 'contact restriction',
'retails closed','trend','tmax','frustration']
policy = pd.read_csv("./policy.csv")
policy_lift = pd.read_csv("./policy_lift.csv")
popularity = np.load("./popularity_germany.npy")
weather = pd.read_csv("./weather_predict.csv")
trend = pd.read_csv("./trend_predict.csv") # cumulative trend numbers
PTV = pd.read_csv("./PTV_predict.csv")
# there are 9 scenarios
# in first scenario, no change in policy and all policies remain in place
# in the next 7 scenarios, we switch off (relax) one of the policy if it was implemented in that respective state
# in the last scenario, we relax all the policies (however, we do not show this in paper as it lead to a very sharp rise)
# each of these 9 scenarios is tested twice - one when for april 21, 2020 and once for april 28, 2020
for pp in range(9):
popularity = np.copy(popularity_o)
car_movement = np.copy(static_car_move)
train_movement = np.copy(static_train_move)
for w in range(2):
policy1 = pd.DataFrame.copy(pd.read_csv("./policy.csv") )
policy2 = pd.DataFrame.copy(pd.read_csv("./policy.csv") )
policy3 = pd.DataFrame.copy(pd.read_csv("./policy.csv") )
name = '_P_'+str(pp)+'_W_'+str(w+1)
if pp == 0:
name = ''
# when relaxing a policy, we keep the date very high (1000) so that the return value is 0 (not implemented post april 21 or april 28)
elif pp == 8:
if w == 0:
name = '_P_8_W_1'
for xx in range(7):
policy1[cols[xx]] = 1000
policy2[cols[xx]] = 1000
policy3[cols[xx]] = 1000
if w == 1:
name = '_P_8_W_2'
for xx in range(7):
policy2[cols[xx]] = 1000
policy3[cols[xx]] = 1000
else:
if w == 0:
policy1[cols[pp-1]] = 1000
policy2[cols[pp-1]] = 1000
policy3[cols[pp-1]] = 1000
elif w==1:
policy2[cols[pp-1]] = 1000
policy3[cols[pp-1]] = 1000
X = []
for j in range(16):
# first week
for t in range(63,70):
c = []
for p in range(7):
c.append(int(policy1[cols[p]].iloc[j] <= t+79))
c.append(trend.iloc[t,j+1])
c.append(weather.iloc[t,j+1])
c.append(PTV.iloc[t,1])
X.append(c)
# second week
for t in range(70,77):
c = []
for p in range(7):
c.append(int(policy2[cols[p]].iloc[j] <= t+79))
c.append(trend.iloc[t,j+1])
c.append(weather.iloc[t,j+1])
c.append(PTV.iloc[t,1])
X.append(c)
# rest of the four weeks
for ww in range(4):
for t in range(77+7*ww,84+7*ww):
c = []
for p in range(7):
c.append(int(policy3[cols[p]].iloc[j] <= t+79))
c.append(trend.iloc[t,j+1])
c.append(weather.iloc[t,j+1])
c.append(PTV.iloc[t,1])
X.append(c)
x = pd.DataFrame(X,columns=cols)
models = RegressionModels()
y_pred = models[0].predict(x)
y_car = models[1].predict(x)
y_train = models[2].predict(x)
for j in range(16):
for t in range(63,63+42):
popularity[j,t,0] = y_pred[42*j+t-63]
popularity[j,t,3] = y_car[42*j+t-63]
popularity[j,t,4] = y_train[42*j+t-63]
wtrain = popularity[:,:,3]
wtrain = (wtrain)/100+1
wcars = popularity[:,:,4]
wcars = (wcars)/100+1
numbee = 63+42
for i in range(16):
car_movement[i] = np.multiply(car_movement[i],wcars[i].reshape([numbee,1])*np.ones([numbee,158]))
train_movement[i] = np.multiply(train_movement[i],wtrain[i].reshape([numbee,1])*np.ones([numbee,158]))
# the files can be saved
#np.save('popularity_germany'+name,popularity)
#np.save('train_movement'+name,train_movement)
#np.save('car_movement'+name,car_movement)
return()
|
def scenario__generation():
popularity_germany = np.load('./popularity_germany.npy')
popularity_germany = np.copy(popularity_germany[:, 0:63, :])
one = np.multiply(np.ones((16, 42, 6)), popularity_germany[:, 62:63, :])
popularity_germany = np.append(popularity_germany, one, axis=1)
bus_movement = np.load('./bus_movement.npy')
truck_movement = np.load('./truck_movement.npy')
flight_movement = np.load('./flight_movement.npy')
car_movement = np.load('./car_movement.npy')
train_movement = np.load('./train_movement.npy')
bus_move = bus_movement[:, 0:63, :]
truck_move = truck_movement[:, 0:63, :]
flight_move = flight_movement[:, 0:63, :]
static_car_move = car_movement[:, 0:63, :]
static_train_move = train_movement[:, 0:63, :]
one = np.multiply(np.ones((16, 42, 158)), bus_move[:, 62:63, :])
bus_move = np.append(bus_move, one, axis=1)
one = np.multiply(np.ones((16, 42, 158)), truck_move[:, 62:63, :])
truck_move = np.append(truck_move, one, axis=1)
one = np.multiply(np.ones((16, 42, 158)), flight_move[:, 62:63, :])
flight_move = np.append(flight_move, one, axis=1)
one = np.multiply(np.ones((16, 42, 158)), static_car_move[:, 62:63, :])
static_car_move = np.append(static_car_move, one, axis=1)
one = np.multiply(np.ones((16, 42, 158)), static_train_move[:, 62:63, :])
static_train_move = np.append(static_train_move, one, axis=1)
for t in range(63, 63 + 42):
truck_move[:, t, :] = truck_move[:, t - 7, :]
popularity_o = np.copy(popularity_germany)
policy_o = pd.read_csv('./policy.csv')
policy_o_life = pd.read_csv('./policy_lift.csv')
cols = ['Border Closure', 'Initial business closure', 'Educational facilities closed', 'Non-essential services closed', 'Stay at home order', 'contact restriction', 'retails closed', 'trend', 'tmax', 'frustration']
policy = pd.read_csv('./policy.csv')
policy_lift = pd.read_csv('./policy_lift.csv')
popularity = np.load('./popularity_germany.npy')
weather = pd.read_csv('./weather_predict.csv')
trend = pd.read_csv('./trend_predict.csv')
ptv = pd.read_csv('./PTV_predict.csv')
for pp in range(9):
popularity = np.copy(popularity_o)
car_movement = np.copy(static_car_move)
train_movement = np.copy(static_train_move)
for w in range(2):
policy1 = pd.DataFrame.copy(pd.read_csv('./policy.csv'))
policy2 = pd.DataFrame.copy(pd.read_csv('./policy.csv'))
policy3 = pd.DataFrame.copy(pd.read_csv('./policy.csv'))
name = '_P_' + str(pp) + '_W_' + str(w + 1)
if pp == 0:
name = ''
elif pp == 8:
if w == 0:
name = '_P_8_W_1'
for xx in range(7):
policy1[cols[xx]] = 1000
policy2[cols[xx]] = 1000
policy3[cols[xx]] = 1000
if w == 1:
name = '_P_8_W_2'
for xx in range(7):
policy2[cols[xx]] = 1000
policy3[cols[xx]] = 1000
elif w == 0:
policy1[cols[pp - 1]] = 1000
policy2[cols[pp - 1]] = 1000
policy3[cols[pp - 1]] = 1000
elif w == 1:
policy2[cols[pp - 1]] = 1000
policy3[cols[pp - 1]] = 1000
x = []
for j in range(16):
for t in range(63, 70):
c = []
for p in range(7):
c.append(int(policy1[cols[p]].iloc[j] <= t + 79))
c.append(trend.iloc[t, j + 1])
c.append(weather.iloc[t, j + 1])
c.append(PTV.iloc[t, 1])
X.append(c)
for t in range(70, 77):
c = []
for p in range(7):
c.append(int(policy2[cols[p]].iloc[j] <= t + 79))
c.append(trend.iloc[t, j + 1])
c.append(weather.iloc[t, j + 1])
c.append(PTV.iloc[t, 1])
X.append(c)
for ww in range(4):
for t in range(77 + 7 * ww, 84 + 7 * ww):
c = []
for p in range(7):
c.append(int(policy3[cols[p]].iloc[j] <= t + 79))
c.append(trend.iloc[t, j + 1])
c.append(weather.iloc[t, j + 1])
c.append(PTV.iloc[t, 1])
X.append(c)
x = pd.DataFrame(X, columns=cols)
models = regression_models()
y_pred = models[0].predict(x)
y_car = models[1].predict(x)
y_train = models[2].predict(x)
for j in range(16):
for t in range(63, 63 + 42):
popularity[j, t, 0] = y_pred[42 * j + t - 63]
popularity[j, t, 3] = y_car[42 * j + t - 63]
popularity[j, t, 4] = y_train[42 * j + t - 63]
wtrain = popularity[:, :, 3]
wtrain = wtrain / 100 + 1
wcars = popularity[:, :, 4]
wcars = wcars / 100 + 1
numbee = 63 + 42
for i in range(16):
car_movement[i] = np.multiply(car_movement[i], wcars[i].reshape([numbee, 1]) * np.ones([numbee, 158]))
train_movement[i] = np.multiply(train_movement[i], wtrain[i].reshape([numbee, 1]) * np.ones([numbee, 158]))
return ()
|
def L1(y_output, y_input):
""" L1 Loss Function calculates the sum of the absolute difference between the predicted and the input"""
return sum(abs(y_input - y_output))
|
def l1(y_output, y_input):
""" L1 Loss Function calculates the sum of the absolute difference between the predicted and the input"""
return sum(abs(y_input - y_output))
|
# loendur dictionary
counter_dict = {}
# loe failist ridade kaupa ja loendab dictionarisse erinevad nimed
with open('/Users/mikksillaste/Downloads/aima-python/nameslist.txt') as f:
line = f.readline()
while line:
line = line.strip()
if line in counter_dict:
counter_dict[line] += 1
else:
counter_dict[line] = 1
line = f.readline()
# loeb failist ridade kaupa ja loendab dictionarisse erinevad kategooriad, mille jaoks on vaja kindlat osa reast [3:-26]
counter_dict2 = {}
with open('/Users/mikksillaste/Downloads/aima-python/Training_01.txt') as f:
line = f.readline()
while line:
line = line[3:-26]
if line in counter_dict2:
counter_dict2[line] += 1
else:
counter_dict2[line] = 1
line = f.readline()
print(counter_dict)
print(counter_dict2)
|
counter_dict = {}
with open('/Users/mikksillaste/Downloads/aima-python/nameslist.txt') as f:
line = f.readline()
while line:
line = line.strip()
if line in counter_dict:
counter_dict[line] += 1
else:
counter_dict[line] = 1
line = f.readline()
counter_dict2 = {}
with open('/Users/mikksillaste/Downloads/aima-python/Training_01.txt') as f:
line = f.readline()
while line:
line = line[3:-26]
if line in counter_dict2:
counter_dict2[line] += 1
else:
counter_dict2[line] = 1
line = f.readline()
print(counter_dict)
print(counter_dict2)
|
def eight_is_great(a, b):
if a == 8 or b == 8:
print(":)")
elif (a + b) == 8:
print(":)")
else:
print(":(")
|
def eight_is_great(a, b):
if a == 8 or b == 8:
print(':)')
elif a + b == 8:
print(':)')
else:
print(':(')
|
#ChangeRenderSetting.py
##This only use in the maya software render , not in arnold
#Three main Node of Maya Render:
# ->defaultRenderGlobals, defaultRenderQuality and defaultResolution
# ->those are separate nodes in maya
'''
import maya.cmds as cmds
#Function : getRenderGlobals()
#Usage : get the Value of Render Globals and print it
def getRenderGlobals() :
render_glob = "defaultRenderGlobals"
list_Attr = cmds.listAttr(render_glob,r = True,s = True)
#loop the list
print 'defaultRenderSetting As follows :'
for attr in list_Attr:
get_attr_name = "%s.%s"%(render_glob, attr)
print "setAttr %s %s"%(get_attr_name, cmds.getAttr(get_attr_name))
#Function : getRenderResolution()
#Usage : get the Value of Render Resolution and print it
def getRenderResolution() :
resolu_list = "defaultResolution"
list_Attr = cmds.listAttr(resolu_list,r = True , s = True)
print 'defaultResolution As follows :'
for attr in list_Attr:
get_attr_name = "%s.%s"%(resolu_list, attr)
print "setAttr %s %s"%(get_attr_name, cmds.getAttr(get_attr_name))
#defaultRenderGlobals.startFrame = 2.0
#Function : startEndFrame
#Usage : to change the Global value(startFrame,endFrame) of the Render
#use for set the render startFrame,endFrame,byframe
#Example : startEndFrame(3.0,7.0)
def startEndFrame(startTime,endTime) :
cmds.setAttr("defaultRenderGlobals.startFrame",startTime)
cmds.setAttr("defaultRenderGlobals.endFrame",endTime)
#Function : setWidthAndHeight
#Usage : to change the Resolution value(width,height) of the Render
#Example : setWidthAndHeight(960,540)
def setWidthAndHeight(width,height) :
cmds.setAttr("defaultResolution.width",width)
cmds.setAttr("defaultResolution.height",height)
'''
|
"""
import maya.cmds as cmds
#Function : getRenderGlobals()
#Usage : get the Value of Render Globals and print it
def getRenderGlobals() :
render_glob = "defaultRenderGlobals"
list_Attr = cmds.listAttr(render_glob,r = True,s = True)
#loop the list
print 'defaultRenderSetting As follows :'
for attr in list_Attr:
get_attr_name = "%s.%s"%(render_glob, attr)
print "setAttr %s %s"%(get_attr_name, cmds.getAttr(get_attr_name))
#Function : getRenderResolution()
#Usage : get the Value of Render Resolution and print it
def getRenderResolution() :
resolu_list = "defaultResolution"
list_Attr = cmds.listAttr(resolu_list,r = True , s = True)
print 'defaultResolution As follows :'
for attr in list_Attr:
get_attr_name = "%s.%s"%(resolu_list, attr)
print "setAttr %s %s"%(get_attr_name, cmds.getAttr(get_attr_name))
#defaultRenderGlobals.startFrame = 2.0
#Function : startEndFrame
#Usage : to change the Global value(startFrame,endFrame) of the Render
#use for set the render startFrame,endFrame,byframe
#Example : startEndFrame(3.0,7.0)
def startEndFrame(startTime,endTime) :
cmds.setAttr("defaultRenderGlobals.startFrame",startTime)
cmds.setAttr("defaultRenderGlobals.endFrame",endTime)
#Function : setWidthAndHeight
#Usage : to change the Resolution value(width,height) of the Render
#Example : setWidthAndHeight(960,540)
def setWidthAndHeight(width,height) :
cmds.setAttr("defaultResolution.width",width)
cmds.setAttr("defaultResolution.height",height)
"""
|
x = int(input())
y = int(input())
if (2 * y + 1 - x) % (y - x + 1) == 0:
print("YES")
else:
print("NO")
|
x = int(input())
y = int(input())
if (2 * y + 1 - x) % (y - x + 1) == 0:
print('YES')
else:
print('NO')
|
# Description
# Count how many nodes in a linked list.
# Example
# Example 1:
# Input: 1->3->5->null
# Output: 3
# Explanation:
# return the length of the list.
# Example 2:
# Input: null
# Output: 0
# Explanation:
# return the length of list.
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: the first node of linked list.
@return: An integer
"""
def countNodes(self, head):
# write your code here
counter = 0
current = head
while current != None:
counter = counter + 1
current = current.next
return counter
|
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: the first node of linked list.
@return: An integer
"""
def count_nodes(self, head):
counter = 0
current = head
while current != None:
counter = counter + 1
current = current.next
return counter
|
class Solution:
def longestPalindrome(self, s: str) -> str:
result = ''
pal_s = set(s)
if len(pal_s) == 1:
return s
for ind_c in range(len(s)):
pal = ''
ind_l = ind_c
ind_r = ind_c + 1
while ind_l > -1 and ind_r < len(s):
if s[ind_l] == s[ind_r]:
pal = s[ind_l] + pal + s[ind_r]
ind_l -= 1
ind_r += 1
else:
break
if len(result) < len(pal):
result = pal
pal = s[ind_c]
ind_l = ind_c - 1
ind_r = ind_c + 1
while ind_l > -1 and ind_r < len(s):
if s[ind_l] == s[ind_r]:
pal = s[ind_l] + pal + s[ind_r]
ind_l -= 1
ind_r += 1
else:
break
if len(result) < len(pal):
result = pal
return result
|
class Solution:
def longest_palindrome(self, s: str) -> str:
result = ''
pal_s = set(s)
if len(pal_s) == 1:
return s
for ind_c in range(len(s)):
pal = ''
ind_l = ind_c
ind_r = ind_c + 1
while ind_l > -1 and ind_r < len(s):
if s[ind_l] == s[ind_r]:
pal = s[ind_l] + pal + s[ind_r]
ind_l -= 1
ind_r += 1
else:
break
if len(result) < len(pal):
result = pal
pal = s[ind_c]
ind_l = ind_c - 1
ind_r = ind_c + 1
while ind_l > -1 and ind_r < len(s):
if s[ind_l] == s[ind_r]:
pal = s[ind_l] + pal + s[ind_r]
ind_l -= 1
ind_r += 1
else:
break
if len(result) < len(pal):
result = pal
return result
|
print("@function from_script:thing")
for i in range(10):
print(f"say {i}")
|
print('@function from_script:thing')
for i in range(10):
print(f'say {i}')
|
nombre = input("Nombre: ")
apellido = input("Apellido: ")
edad_nac = input("Edad de nacimiento: ")
correo1 = nombre[0] + "." + apellido + edad_nac[-2:] + "@uma.es"
correo2 = nombre[:3] + apellido[:3] + edad_nac[-2:] + "@uma.es"
print("Correos:", correo1, "y", correo2)
|
nombre = input('Nombre: ')
apellido = input('Apellido: ')
edad_nac = input('Edad de nacimiento: ')
correo1 = nombre[0] + '.' + apellido + edad_nac[-2:] + '@uma.es'
correo2 = nombre[:3] + apellido[:3] + edad_nac[-2:] + '@uma.es'
print('Correos:', correo1, 'y', correo2)
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a ListNode
def sortList(self, head):
if head is None or head.next is None:
return head
fast, slow = head, head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
slow.next, slow = None, slow.next
slow, fast = self.sortList(head), self.sortList(slow)
return self.merge(slow, fast)
def merge(self, head1, head2):
if head1 is None:
return head2
if head2 is None:
return head1
p = ListNode(0)
res = p
while head1 and head2:
if head1.val < head2.val:
p.next = head1
head1 = head1.next
else:
p.next = head2
head2 = head2.next
p = p.next
if head1:
p.next = head1
elif head2:
p.next = head2
return res.next
|
class Solution:
def sort_list(self, head):
if head is None or head.next is None:
return head
(fast, slow) = (head, head)
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
(slow.next, slow) = (None, slow.next)
(slow, fast) = (self.sortList(head), self.sortList(slow))
return self.merge(slow, fast)
def merge(self, head1, head2):
if head1 is None:
return head2
if head2 is None:
return head1
p = list_node(0)
res = p
while head1 and head2:
if head1.val < head2.val:
p.next = head1
head1 = head1.next
else:
p.next = head2
head2 = head2.next
p = p.next
if head1:
p.next = head1
elif head2:
p.next = head2
return res.next
|
class DiscreteActionWrapper:
def __init__(self, env, n):
self.env = env
self.action_cont = [
# [l + (_+0.5)*(h-l)/n for _ in range(n)]
# [l + _*(h-l)/(n+1) for _ in range(n)]
[l + _*(h-l)/(n-1) for _ in range(n)]
for h, l in zip(self.env.action_space.high, self.env.action_space.low)
]
self.env.action_space.shape = [n] * len(self.env.action_space.high)
delattr(self.env.action_space, "low")
delattr(self.env.action_space, "high")
def step(self, a):
action_cont = [_[i] for _, i in zip(self.action_cont, a)]
return self.env.step(action_cont)
def __getattr__(self, name):
return getattr(self.env, name)
|
class Discreteactionwrapper:
def __init__(self, env, n):
self.env = env
self.action_cont = [[l + _ * (h - l) / (n - 1) for _ in range(n)] for (h, l) in zip(self.env.action_space.high, self.env.action_space.low)]
self.env.action_space.shape = [n] * len(self.env.action_space.high)
delattr(self.env.action_space, 'low')
delattr(self.env.action_space, 'high')
def step(self, a):
action_cont = [_[i] for (_, i) in zip(self.action_cont, a)]
return self.env.step(action_cont)
def __getattr__(self, name):
return getattr(self.env, name)
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def compare(self, lleft, rright):
if (not lleft) and (not rright):
return True
elif (not lleft) or (not rright):
return False
else:
if lleft.val != rright.val:
return False
else:
return self.compare(lleft.left, rright.right) and self.compare(lleft.right, rright.left)
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
else:
return self.compare(root.left, root.right)
|
class Solution:
def compare(self, lleft, rright):
if not lleft and (not rright):
return True
elif not lleft or not rright:
return False
elif lleft.val != rright.val:
return False
else:
return self.compare(lleft.left, rright.right) and self.compare(lleft.right, rright.left)
def is_symmetric(self, root: TreeNode) -> bool:
if not root:
return True
else:
return self.compare(root.left, root.right)
|
class AbstractObserver(object):
"""Abstract Observer"""
def __init__(self):
self.is_stopped = False
def next(self, value):
raise NotImplementedError
def error(self, error):
raise NotImplementedError
def completed(self):
raise NotImplementedError
def on_next(self, value):
"""Notifies the observer of a new element in the sequence.
Keyword arguments:
value -- Next element in the sequence.
"""
if not self.is_stopped:
self.next(value)
def on_error(self, error):
"""Notifies the observer that an exception has occurred.
Keyword arguments:
error -- The error that has occurred.
"""
if not self.is_stopped:
self.is_stopped = True
self.error(error)
def on_completed(self):
"""Notifies the observer of the end of the sequence."""
if not self.is_stopped:
self.is_stopped = True
self.completed()
def dispose(self):
"""Disposes the observer, causing it to transition to the stopped
state."""
self.is_stopped = True
def fail(self, exn):
if not self.is_stopped:
self.is_stopped = True
self.error(exn)
return True
return False
|
class Abstractobserver(object):
"""Abstract Observer"""
def __init__(self):
self.is_stopped = False
def next(self, value):
raise NotImplementedError
def error(self, error):
raise NotImplementedError
def completed(self):
raise NotImplementedError
def on_next(self, value):
"""Notifies the observer of a new element in the sequence.
Keyword arguments:
value -- Next element in the sequence.
"""
if not self.is_stopped:
self.next(value)
def on_error(self, error):
"""Notifies the observer that an exception has occurred.
Keyword arguments:
error -- The error that has occurred.
"""
if not self.is_stopped:
self.is_stopped = True
self.error(error)
def on_completed(self):
"""Notifies the observer of the end of the sequence."""
if not self.is_stopped:
self.is_stopped = True
self.completed()
def dispose(self):
"""Disposes the observer, causing it to transition to the stopped
state."""
self.is_stopped = True
def fail(self, exn):
if not self.is_stopped:
self.is_stopped = True
self.error(exn)
return True
return False
|
# -*- coding: utf-8 -*-
def main():
n = int(input())
if n == 1:
print("Hello World")
else:
a = int(input())
b = int(input())
print(a + b)
if __name__ == '__main__':
main()
|
def main():
n = int(input())
if n == 1:
print('Hello World')
else:
a = int(input())
b = int(input())
print(a + b)
if __name__ == '__main__':
main()
|
class Message:
def __init__(self, response, type_):
self.response = response
self.type = type_
|
class Message:
def __init__(self, response, type_):
self.response = response
self.type = type_
|
#!/usr/bin/python3
MAXIMIZE = 1
MINIMIZE = 2
|
maximize = 1
minimize = 2
|
class StyleMapping:
def __init__(self, opts):
self._opts = opts
def __getitem__(self, key):
return getattr(self._opts, "style_{}".format(key), "").encode().decode("unicode_escape")
def apply_styles(opts, command):
return command.format_map(StyleMapping(opts))
|
class Stylemapping:
def __init__(self, opts):
self._opts = opts
def __getitem__(self, key):
return getattr(self._opts, 'style_{}'.format(key), '').encode().decode('unicode_escape')
def apply_styles(opts, command):
return command.format_map(style_mapping(opts))
|
class Calculation:
def __init__(cls, a, b, op):
cls.a = float(a)
cls.b = float(b)
cls.op = op
def getResult(cls):
return cls.op(cls.a, cls.b)
|
class Calculation:
def __init__(cls, a, b, op):
cls.a = float(a)
cls.b = float(b)
cls.op = op
def get_result(cls):
return cls.op(cls.a, cls.b)
|
"""Find the nth root of a number with the bisection method."""
__author__ = 'Nicola Moretto'
__license__ = "MIT"
def rootBisection(x, power, precision):
'''
Find the nth root of a number with the bisection method.
:param x: Number
:param power: Root
:param precision: Precision
:return: power-th root of x
'''
if power < 1 or precision < 0:
return None
if power == 1:
return x
if x < 0 and power%2 == 0:
return None
low = min(-1, x)
high = max(1, x)
value = (low+high)/2.0
while abs(value**power-x) > precision:
if value**power < x:
low = value
else:
high = value
value = (low+high)/2.0
return value
|
"""Find the nth root of a number with the bisection method."""
__author__ = 'Nicola Moretto'
__license__ = 'MIT'
def root_bisection(x, power, precision):
"""
Find the nth root of a number with the bisection method.
:param x: Number
:param power: Root
:param precision: Precision
:return: power-th root of x
"""
if power < 1 or precision < 0:
return None
if power == 1:
return x
if x < 0 and power % 2 == 0:
return None
low = min(-1, x)
high = max(1, x)
value = (low + high) / 2.0
while abs(value ** power - x) > precision:
if value ** power < x:
low = value
else:
high = value
value = (low + high) / 2.0
return value
|
a = type('a_fyerr', (Exception,), {})
try:
raise a('aa')
except Exception as e:
print(type(e))
|
a = type('a_fyerr', (Exception,), {})
try:
raise a('aa')
except Exception as e:
print(type(e))
|
expected_output = {
"Tunnel0": {
"nhs_ip": {
"111.0.0.100": {
"nhs_state": "E",
"nbma_address": "111.1.1.1",
"priority": 0,
"cluster": 0,
"req_sent": 0,
"req_failed": 0,
"reply_recv": 0,
"current_request_id": 94,
"protection_socket_requested": "FALSE",
}
}
},
"Tunnel100": {
"nhs_ip": {
"100.0.0.100": {
"nhs_state": "RE",
"nbma_address": "101.1.1.1",
"priority": 0,
"cluster": 0,
"req_sent": 105434,
"req_failed": 0,
"reply_recv": 105434,
"receive_time": "00:00:49",
"current_request_id": 35915,
"ack": 35914,
"protection_socket_requested": "FALSE",
}
}
},
"Tunnel111": {
"nhs_ip": {
"111.0.0.100": {
"nhs_state": "E",
"nbma_address": "111.1.1.1",
"priority": 0,
"cluster": 0,
"req_sent": 184399,
"req_failed": 0,
"reply_recv": 0,
"current_request_id": 35916,
}
}
},
"pending_registration_requests": {
"req_id": {
"16248": {
"ret": 64,
"nhs_ip": "111.0.0.100",
"nhs_state": "expired",
"tunnel": "Tu111",
},
"57": {
"ret": 64,
"nhs_ip": "172.16.0.1",
"nhs_state": "expired",
"tunnel": "Tu100",
},
}
},
}
|
expected_output = {'Tunnel0': {'nhs_ip': {'111.0.0.100': {'nhs_state': 'E', 'nbma_address': '111.1.1.1', 'priority': 0, 'cluster': 0, 'req_sent': 0, 'req_failed': 0, 'reply_recv': 0, 'current_request_id': 94, 'protection_socket_requested': 'FALSE'}}}, 'Tunnel100': {'nhs_ip': {'100.0.0.100': {'nhs_state': 'RE', 'nbma_address': '101.1.1.1', 'priority': 0, 'cluster': 0, 'req_sent': 105434, 'req_failed': 0, 'reply_recv': 105434, 'receive_time': '00:00:49', 'current_request_id': 35915, 'ack': 35914, 'protection_socket_requested': 'FALSE'}}}, 'Tunnel111': {'nhs_ip': {'111.0.0.100': {'nhs_state': 'E', 'nbma_address': '111.1.1.1', 'priority': 0, 'cluster': 0, 'req_sent': 184399, 'req_failed': 0, 'reply_recv': 0, 'current_request_id': 35916}}}, 'pending_registration_requests': {'req_id': {'16248': {'ret': 64, 'nhs_ip': '111.0.0.100', 'nhs_state': 'expired', 'tunnel': 'Tu111'}, '57': {'ret': 64, 'nhs_ip': '172.16.0.1', 'nhs_state': 'expired', 'tunnel': 'Tu100'}}}}
|
def main():
with open("emotions.txt", "r") as f:
count = set(f.readlines())
print(count)
print(len(count))
if __name__ == '__main__':
main()
|
def main():
with open('emotions.txt', 'r') as f:
count = set(f.readlines())
print(count)
print(len(count))
if __name__ == '__main__':
main()
|
environmentdefs = {
"local": ["localhost"],
"other": ["localhost"]
}
roledefs = {
"role": ["localhost"]
}
componentdefs = {
"role": ["component"]
}
|
environmentdefs = {'local': ['localhost'], 'other': ['localhost']}
roledefs = {'role': ['localhost']}
componentdefs = {'role': ['component']}
|
class QueryUser:
CREATE_TABLE_USERS: str = """
CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
email TEXT NOT NULL,
phone TEXT NOT NULL,
address TEXT NOT NULL,
country TEXT NOT NULL
);
"""
INSERT_USER: str = """
INSERT INTO users (name, email, phone, address, country) VALUES (?, ?, ?, ?, ?)
"""
GET_USER_BY_ID: str = """
SELECT * FROM users WHERE user_id = ?
"""
GET_USERS: str = """
SELECT * FROM users
"""
UPDATE_USER_BY_ID: str = """
UPDATE users SET name = ?, email = ?, phone = ?, address = ?, country = ? WHERE user_id =?
"""
DELETE_USER_BY_ID: str = """
DELETE from users WHERE user_id = ?
"""
query_user = QueryUser()
|
class Queryuser:
create_table_users: str = '\n CREATE TABLE IF NOT EXISTS users (\n user_id INTEGER PRIMARY KEY NOT NULL,\n name TEXT NOT NULL,\n email TEXT NOT NULL,\n phone TEXT NOT NULL,\n address TEXT NOT NULL,\n country TEXT NOT NULL\n );\n '
insert_user: str = '\n INSERT INTO users (name, email, phone, address, country) VALUES (?, ?, ?, ?, ?)\n '
get_user_by_id: str = '\n SELECT * FROM users WHERE user_id = ?\n '
get_users: str = '\n SELECT * FROM users\n '
update_user_by_id: str = '\n UPDATE users SET name = ?, email = ?, phone = ?, address = ?, country = ? WHERE user_id =?\n '
delete_user_by_id: str = '\n DELETE from users WHERE user_id = ?\n '
query_user = query_user()
|
# https://leetcode.com/problems/palindrome-linked-list/submissions/
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
# p1 = first
# p2 = last -> for storing lst nodes use a stack
# traverse till mid
# check if p1 == p2
# if not break
stack = []
temp = head
# stack to store prev nodes
while(temp):
stack.append(temp.val)
temp = temp.next
# find mid
curr = head
counter = 0
while(curr):
counter += 1
curr = curr.next
mid = counter // 2
# Traverse till mid and compare the first and last nodes
p1 = head
p2 = stack.pop()
while(mid):
if(p1.val != p2):
return False
p1 = p1.next
p2 = stack.pop()
mid -= 1
return True
|
class Solution(object):
def is_palindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
stack = []
temp = head
while temp:
stack.append(temp.val)
temp = temp.next
curr = head
counter = 0
while curr:
counter += 1
curr = curr.next
mid = counter // 2
p1 = head
p2 = stack.pop()
while mid:
if p1.val != p2:
return False
p1 = p1.next
p2 = stack.pop()
mid -= 1
return True
|
class Solution:
def XXX(self, nums: List[int]) -> List[List[int]]:
res = [[]]
for num in nums:
res.append([num])
for temp in res[1:-1]:
res.append(temp+[num])
return res
|
class Solution:
def xxx(self, nums: List[int]) -> List[List[int]]:
res = [[]]
for num in nums:
res.append([num])
for temp in res[1:-1]:
res.append(temp + [num])
return res
|
class LCRecommendation:
TURN_LEFT = -1
TURN_RIGHT = 1
STRAIGHT_AHEAD = 0
CHANGE_TO_EITHER_WAY = 2
change_lane = True
change_to_either_way = False
recommendation = 0
def __init__(self, lane, recommendation):
self.lane = lane
self.recommendation = recommendation
if recommendation == self.TURN_RIGHT:
self.target_lane = lane - 1
elif recommendation == self.TURN_LEFT:
self.target_lane = lane + 1
elif recommendation == self.CHANGE_TO_EITHER_WAY:
self.change_to_either_way = True
elif recommendation == self.STRAIGHT_AHEAD:
self.change_lane = False
|
class Lcrecommendation:
turn_left = -1
turn_right = 1
straight_ahead = 0
change_to_either_way = 2
change_lane = True
change_to_either_way = False
recommendation = 0
def __init__(self, lane, recommendation):
self.lane = lane
self.recommendation = recommendation
if recommendation == self.TURN_RIGHT:
self.target_lane = lane - 1
elif recommendation == self.TURN_LEFT:
self.target_lane = lane + 1
elif recommendation == self.CHANGE_TO_EITHER_WAY:
self.change_to_either_way = True
elif recommendation == self.STRAIGHT_AHEAD:
self.change_lane = False
|
##
## this file autogenerated
## 8.4(6)5
##
jmp_esp_offset = "125.63.32.8"
saferet_offset = "166.11.228.8"
fix_ebp = "72"
pmcheck_bounds = "0.176.88.9"
pmcheck_offset = "96.186.88.9"
pmcheck_code = "85.49.192.137"
admauth_bounds = "0.32.8.8"
admauth_offset = "240.33.8.8"
admauth_code = "85.137.229.87"
# "8.4(6)5" = ["125.63.32.8","166.11.228.8","72","0.176.88.9","96.186.88.9","85.49.192.137","0.32.8.8","240.33.8.8","85.137.229.87"],
|
jmp_esp_offset = '125.63.32.8'
saferet_offset = '166.11.228.8'
fix_ebp = '72'
pmcheck_bounds = '0.176.88.9'
pmcheck_offset = '96.186.88.9'
pmcheck_code = '85.49.192.137'
admauth_bounds = '0.32.8.8'
admauth_offset = '240.33.8.8'
admauth_code = '85.137.229.87'
|
# -*- encoding: utf-8 -*-
"""
KERI
keri.vdr Package
"""
__all__ = ["issuing", "eventing", "registering", "viring", "verifying"]
|
"""
KERI
keri.vdr Package
"""
__all__ = ['issuing', 'eventing', 'registering', 'viring', 'verifying']
|
# class with __init__
class C1:
def __init__(self):
self.x = 1
c1 = C1()
print(type(c1) == C1)
print(c1.x)
class C2:
def __init__(self, x):
self.x = x
c2 = C2(4)
print(type(c2) == C2)
print(c2.x)
|
class C1:
def __init__(self):
self.x = 1
c1 = c1()
print(type(c1) == C1)
print(c1.x)
class C2:
def __init__(self, x):
self.x = x
c2 = c2(4)
print(type(c2) == C2)
print(c2.x)
|
class Fail_AuthUwU(Exception):
"""Thrown when when authentication fails
Attrs: objName
"""
def __init__(self, objName, message='sowwy {self.objName} has failed auwthenication..'):
self.objName = objName
self.message = message
super().__init__(message)
def __str__(self):
return f'{self.objName} -> {self.message}'
class UwUNoAccess(Exception):
"""Thrown when when authentication fails
Attrs: objName
"""
def __init__(self, objName, message='sowwy {self.objName} Can not hit me here..'):
self.objName = objName
self.message = message
super().__init__(message)
def __str__(self):
return f'{self.objName} -> {self.message}'
class UwUMemberAccessException(Exception):
"""Thrown when when authentication fails
Attrs: objName
"""
def __init__(self, objName, message='sowwy {self.objName} does not have access to this..'):
self.objName = objName
self.message = message
super().__init__(message)
def __str__(self):
return f'{self.objName} -> {self.message}'
class UwUPolicies(Exception):
"""Thrown when when authentication fails
Attrs: objName
"""
def __init__(self, objName, message='sowwy {self.objName} our powicies do not permit this..'):
self.objName = objName
self.message = message
super().__init__(message)
def __str__(self):
return f'{self.objName} -> {self.message}'
|
class Fail_Authuwu(Exception):
"""Thrown when when authentication fails
Attrs: objName
"""
def __init__(self, objName, message='sowwy {self.objName} has failed auwthenication..'):
self.objName = objName
self.message = message
super().__init__(message)
def __str__(self):
return f'{self.objName} -> {self.message}'
class Uwunoaccess(Exception):
"""Thrown when when authentication fails
Attrs: objName
"""
def __init__(self, objName, message='sowwy {self.objName} Can not hit me here..'):
self.objName = objName
self.message = message
super().__init__(message)
def __str__(self):
return f'{self.objName} -> {self.message}'
class Uwumemberaccessexception(Exception):
"""Thrown when when authentication fails
Attrs: objName
"""
def __init__(self, objName, message='sowwy {self.objName} does not have access to this..'):
self.objName = objName
self.message = message
super().__init__(message)
def __str__(self):
return f'{self.objName} -> {self.message}'
class Uwupolicies(Exception):
"""Thrown when when authentication fails
Attrs: objName
"""
def __init__(self, objName, message='sowwy {self.objName} our powicies do not permit this..'):
self.objName = objName
self.message = message
super().__init__(message)
def __str__(self):
return f'{self.objName} -> {self.message}'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.