content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class Config: DIR = "arm_now/" kernel = "kernel" dtb = "dtb" rootfs = "rootfs.ext2" arch = "arch" KERNEL = DIR + "kernel" DTB = DIR + "dtb" ROOTFS = DIR + "rootfs.ext2" ARCH = DIR + "arch" DOWNLOAD_CACHE_DIR = "/tmp/arm_now" qemu_options = { "aarch64": ["aarch64", "-M virt -cpu cortex-a57 -smp 1 -kernel {kernel} -append 'root=/dev/vda console=ttyAMA0' -netdev user,id=eth0 -device virtio-net-device,netdev=eth0 -drive file={rootfs},if=none,format=raw,id=hd0 -device virtio-blk-device,drive=hd0"], "armv5-eabi": ["arm", "-M vexpress-a9 -kernel {kernel} -sd {rootfs} -append 'root=/dev/mmcblk0 console=ttyAMA0 rw physmap.enabled=0 noapic'"], # check log "armv6-eabihf": ["arm", "-M vexpress-a9 -kernel {kernel} -sd {rootfs} -append 'root=/dev/mmcblk0 console=ttyAMA0 rw physmap.enabled=0 noapic'"], # check log "armv7-eabihf": ["arm", "-M vexpress-a9 -kernel {kernel} -sd {rootfs} -append 'root=/dev/mmcblk0 console=ttyAMA0 rw physmap.enabled=0 noapic'"], # check log # "bfin":, TODO # "m68k-68xxx":, TODO "m68k-coldfire": ["m68k", "-kernel {kernel} -hda {rootfs} -append 'root=/dev/sda console=ttyS0 rw physmap.enabled=0 noapic'"], # check log "microblazebe": ["microblaze", "-M petalogix-s3adsp1800 -kernel {kernel} -nographic"], # rootfs is inside the kernel file, but we also have a separated rootfs if needed "microblazeel": ["microblazeel", "-kernel {kernel} -hda {rootfs} -append 'root=/dev/sda console=tty0 rw physmap.enabled=0 noapic'"], # check log "mips32": ["mips", "-kernel {kernel} -hda {rootfs} -append 'root=/dev/hda console=ttyS0 rw physmap.enabled=0 noapic'"], # check log "mips32el": ["mipsel", "-kernel {kernel} -hda {rootfs} -append 'root=/dev/hda console=ttyS0 rw physmap.enabled=0 noapic'"], # check log "mips32r5el": ["mipsel", "-machine malta -cpu P5600 -kernel {kernel} -drive file={rootfs},format=raw -append 'root=/dev/hda rw'"], "mips32r6el": ["mipsel", "-M malta -cpu mips32r6-generic -kernel {kernel} -drive file={rootfs},format=raw -append root=/dev/hda -net nic,model=pcnet -net user"], "mips64-n32": ["mips64", "-kernel {kernel} -hda {rootfs} -append 'root=/dev/hda console=ttyS0 rw physmap.enabled=0 noapic'"], # check log "mips64el-n32": ["mips64el", "-kernel {kernel} -hda {rootfs} -append 'root=/dev/hda console=ttyS0 rw physmap.enabled=0 noapic'"], # check log # "mips64r6el-n32":, TODO check log # "mips64r6el-n32": ["mips64el", "-machine malta -kernel {kernel} -drive file={rootfs},format=raw -append 'root=/dev/hda rw console=ttyS0,'"], # check log "nios2": ["nios2", "-kernel {kernel} -hda {rootfs} -append 'root=/dev/sda console=ttyS0 rw physmap.enabled=0 noapic'"], # check log "powerpc64-e5500": ["ppc64", "-kernel {kernel} -hda {rootfs} -append 'root=/dev/sda console=ttyS0 rw physmap.enabled=0 noapic'"], # check log "powerpc64-power8": ["ppc64", "-kernel {kernel} -hda {rootfs} -append 'root=/dev/sda console=ttyS0 rw physmap.enabled=0 noapic'"], # check log "powerpc64le-power8": ["ppc64", "-kernel {kernel} -hda {rootfs} -append 'root=/dev/sda console=ttyS0 rw physmap.enabled=0 noapic'"], # check log "sh-sh4": ["sh4", "-M r2d -serial vc -kernel {kernel} -hda {rootfs} -append 'root=/dev/sda console=ttyS0 rw physmap.enabled=0 noapic'"], # check log # "sparc64":, TODO check log # "sparc64": ["sparc64", "-M sun4u -kernel {kernel} -append 'root=/dev/sda console=ttyS0,115200' -drive file={rootfs},format=raw -net nic,model=e1000 -net user"], # this causes kernel crash # ":sparcv8":, TODO, check log, # "sparcv8": ["sparc", "-machine SS-10 -kernel {kernel} -drive file={rootfs},format=raw -append 'root=/dev/sda console=ttyS0,115200' -net nic,model=lance -net user"], # error # "x86-64-core-i7":["x86_64", "-kernel {kernel} -hda {rootfs} -append 'root=/dev/sda console=ttyS0 rw physmap.enabled=0 noapic'"], # old "x86-64-core-i7" : ["x86_64", "-M pc -kernel {kernel} -drive file={rootfs},if=virtio,format=raw -append 'root=/dev/vda rw console=ttyS0' -net nic,model=virtio -net user"], # "x86-core2" : ["i386", "-kernel {kernel} -hda {rootfs} -append 'root=/dev/sda console=ttyS0 rw physmap.enabled=0 noapic -net nic,model=virtio -net user'"], "x86-core2": ["i386", "-M pc -kernel {kernel} -drive file={rootfs},if=virtio,format=raw -append 'root=/dev/vda rw console=ttyS0' -net nic,model=virtio -net user"], # fix opkg "x86-i686":["i386", "-M pc -kernel {kernel} -drive file={rootfs},if=virtio,format=raw -append 'root=/dev/vda rw console=ttyS0' -net nic,model=virtio -net user"], "xtensa-lx60": ["xtensa", "-M lx60 -cpu dc233c -monitor null -nographic -kernel {kernel} -monitor null"] } """ The final user is not vulnerable to MITM attack, thoose http links are used to preconfigure the package manager. When you do a arm_now start armv5-eabi the image you are downloading already has opkg installed and everything is configured to use https, zero request are made over http. thx lucasduffey """ install_opkg = { "armv5-eabi":"""wget -O - http://pkg.entware.net/binaries/armv5/installer/entware_install.sh | /bin/sh""", "armv7-eabihf":"""wget -O - http://pkg.entware.net/binaries/armv5/installer/entware_install.sh | /bin/sh""", "mips32el":"""wget -O - http://pkg.entware.net/binaries/mipsel/installer/installer.sh | /bin/sh""", "x86-64-core-i7":"""wget -O - http://pkg.entware.net/binaries/x86-64/installer/entware_install.sh | /bin/sh""", "x86-core2":"""wget -O - http://pkg.entware.net/binaries/x86-32/installer/entware_install.sh | /bin/sh""", "x86-i686":"""wget -O - http://pkg.entware.net/binaries/x86-32/installer/entware_install.sh | /bin/sh""", }
class Config: dir = 'arm_now/' kernel = 'kernel' dtb = 'dtb' rootfs = 'rootfs.ext2' arch = 'arch' kernel = DIR + 'kernel' dtb = DIR + 'dtb' rootfs = DIR + 'rootfs.ext2' arch = DIR + 'arch' download_cache_dir = '/tmp/arm_now' qemu_options = {'aarch64': ['aarch64', "-M virt -cpu cortex-a57 -smp 1 -kernel {kernel} -append 'root=/dev/vda console=ttyAMA0' -netdev user,id=eth0 -device virtio-net-device,netdev=eth0 -drive file={rootfs},if=none,format=raw,id=hd0 -device virtio-blk-device,drive=hd0"], 'armv5-eabi': ['arm', "-M vexpress-a9 -kernel {kernel} -sd {rootfs} -append 'root=/dev/mmcblk0 console=ttyAMA0 rw physmap.enabled=0 noapic'"], 'armv6-eabihf': ['arm', "-M vexpress-a9 -kernel {kernel} -sd {rootfs} -append 'root=/dev/mmcblk0 console=ttyAMA0 rw physmap.enabled=0 noapic'"], 'armv7-eabihf': ['arm', "-M vexpress-a9 -kernel {kernel} -sd {rootfs} -append 'root=/dev/mmcblk0 console=ttyAMA0 rw physmap.enabled=0 noapic'"], 'm68k-coldfire': ['m68k', "-kernel {kernel} -hda {rootfs} -append 'root=/dev/sda console=ttyS0 rw physmap.enabled=0 noapic'"], 'microblazebe': ['microblaze', '-M petalogix-s3adsp1800 -kernel {kernel} -nographic'], 'microblazeel': ['microblazeel', "-kernel {kernel} -hda {rootfs} -append 'root=/dev/sda console=tty0 rw physmap.enabled=0 noapic'"], 'mips32': ['mips', "-kernel {kernel} -hda {rootfs} -append 'root=/dev/hda console=ttyS0 rw physmap.enabled=0 noapic'"], 'mips32el': ['mipsel', "-kernel {kernel} -hda {rootfs} -append 'root=/dev/hda console=ttyS0 rw physmap.enabled=0 noapic'"], 'mips32r5el': ['mipsel', "-machine malta -cpu P5600 -kernel {kernel} -drive file={rootfs},format=raw -append 'root=/dev/hda rw'"], 'mips32r6el': ['mipsel', '-M malta -cpu mips32r6-generic -kernel {kernel} -drive file={rootfs},format=raw -append root=/dev/hda -net nic,model=pcnet -net user'], 'mips64-n32': ['mips64', "-kernel {kernel} -hda {rootfs} -append 'root=/dev/hda console=ttyS0 rw physmap.enabled=0 noapic'"], 'mips64el-n32': ['mips64el', "-kernel {kernel} -hda {rootfs} -append 'root=/dev/hda console=ttyS0 rw physmap.enabled=0 noapic'"], 'nios2': ['nios2', "-kernel {kernel} -hda {rootfs} -append 'root=/dev/sda console=ttyS0 rw physmap.enabled=0 noapic'"], 'powerpc64-e5500': ['ppc64', "-kernel {kernel} -hda {rootfs} -append 'root=/dev/sda console=ttyS0 rw physmap.enabled=0 noapic'"], 'powerpc64-power8': ['ppc64', "-kernel {kernel} -hda {rootfs} -append 'root=/dev/sda console=ttyS0 rw physmap.enabled=0 noapic'"], 'powerpc64le-power8': ['ppc64', "-kernel {kernel} -hda {rootfs} -append 'root=/dev/sda console=ttyS0 rw physmap.enabled=0 noapic'"], 'sh-sh4': ['sh4', "-M r2d -serial vc -kernel {kernel} -hda {rootfs} -append 'root=/dev/sda console=ttyS0 rw physmap.enabled=0 noapic'"], 'x86-64-core-i7': ['x86_64', "-M pc -kernel {kernel} -drive file={rootfs},if=virtio,format=raw -append 'root=/dev/vda rw console=ttyS0' -net nic,model=virtio -net user"], 'x86-core2': ['i386', "-M pc -kernel {kernel} -drive file={rootfs},if=virtio,format=raw -append 'root=/dev/vda rw console=ttyS0' -net nic,model=virtio -net user"], 'x86-i686': ['i386', "-M pc -kernel {kernel} -drive file={rootfs},if=virtio,format=raw -append 'root=/dev/vda rw console=ttyS0' -net nic,model=virtio -net user"], 'xtensa-lx60': ['xtensa', '-M lx60 -cpu dc233c -monitor null -nographic -kernel {kernel} -monitor null']} ' The final user is not vulnerable to MITM attack, thoose http links are used to preconfigure the package manager.\nWhen you do a arm_now start armv5-eabi the image you are downloading already has opkg installed and\neverything is configured to use https, zero request are made over http.\nthx lucasduffey\n' install_opkg = {'armv5-eabi': 'wget -O - http://pkg.entware.net/binaries/armv5/installer/entware_install.sh | /bin/sh', 'armv7-eabihf': 'wget -O - http://pkg.entware.net/binaries/armv5/installer/entware_install.sh | /bin/sh', 'mips32el': 'wget -O - http://pkg.entware.net/binaries/mipsel/installer/installer.sh | /bin/sh', 'x86-64-core-i7': 'wget -O - http://pkg.entware.net/binaries/x86-64/installer/entware_install.sh | /bin/sh', 'x86-core2': 'wget -O - http://pkg.entware.net/binaries/x86-32/installer/entware_install.sh | /bin/sh', 'x86-i686': 'wget -O - http://pkg.entware.net/binaries/x86-32/installer/entware_install.sh | /bin/sh'}
def Capital_letter(func): #This function receive another function def Wrapper(text): return func(text).upper() return Wrapper @Capital_letter def message(name): return f'{name}, you have received a message' print(message('Yery'))
def capital_letter(func): def wrapper(text): return func(text).upper() return Wrapper @Capital_letter def message(name): return f'{name}, you have received a message' print(message('Yery'))
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. class Encumbrance: speed_multiplier = 1 to_hit_modifier = 0 @classmethod def get_encumbrance_state(cls, weight, capacity): if weight <= capacity: return Unencumbered elif weight <= 1.5 * capacity: return Burdened elif weight <= 2 * capacity: return Stressed elif weight <= 2.5 * capacity: return Strained elif weight <= 3 * capacity: return Overtaxed else: return Overloaded @classmethod def modify_speed(cls, speed): return speed * cls.speed_multiplier @classmethod def modify_hit(cls, to_hit): return to_hit + cls.to_hit_modifier @classmethod def describe(cls): return cls.__name__.lower() class Unencumbered(Encumbrance): speed_multiplier = 1 to_hit_modifier = 0 class Burdened(Encumbrance): speed_multiplier = 0.75 to_hit_modifier = -1 class Stressed(Encumbrance): speed_multiplier = 0.5 to_hit_modifier = -3 class Strained(Encumbrance): speed_multiplier = 0.25 to_hit_modifier = -5 class Overtaxed(Encumbrance): speed_multiplier = 0.125 to_hit_modifier = -7 class Overloaded(Encumbrance): speed_multiplier = 0 to_hit_modifier = -9
class Encumbrance: speed_multiplier = 1 to_hit_modifier = 0 @classmethod def get_encumbrance_state(cls, weight, capacity): if weight <= capacity: return Unencumbered elif weight <= 1.5 * capacity: return Burdened elif weight <= 2 * capacity: return Stressed elif weight <= 2.5 * capacity: return Strained elif weight <= 3 * capacity: return Overtaxed else: return Overloaded @classmethod def modify_speed(cls, speed): return speed * cls.speed_multiplier @classmethod def modify_hit(cls, to_hit): return to_hit + cls.to_hit_modifier @classmethod def describe(cls): return cls.__name__.lower() class Unencumbered(Encumbrance): speed_multiplier = 1 to_hit_modifier = 0 class Burdened(Encumbrance): speed_multiplier = 0.75 to_hit_modifier = -1 class Stressed(Encumbrance): speed_multiplier = 0.5 to_hit_modifier = -3 class Strained(Encumbrance): speed_multiplier = 0.25 to_hit_modifier = -5 class Overtaxed(Encumbrance): speed_multiplier = 0.125 to_hit_modifier = -7 class Overloaded(Encumbrance): speed_multiplier = 0 to_hit_modifier = -9
_base_ = [ '../_base_/models/r50_multihead.py', '../_base_/datasets/imagenet_color_sz224_4xbs64.py', '../_base_/default_runtime.py', ] # model settings model = dict( backbone=dict(frozen_stages=4), head=dict(num_classes=1000)) # optimizer optimizer = dict( type='SGD', lr=0.01, momentum=0.9, weight_decay=1e-4, nesterov=True, paramwise_options={ '(bn|ln|gn)(\d+)?.(weight|bias)': dict(weight_decay=0.), }, ) # learning policy lr_config = dict(policy='step', step=[30, 60, 90]) # runtime settings runner = dict(type='EpochBasedRunner', max_epochs=90)
_base_ = ['../_base_/models/r50_multihead.py', '../_base_/datasets/imagenet_color_sz224_4xbs64.py', '../_base_/default_runtime.py'] model = dict(backbone=dict(frozen_stages=4), head=dict(num_classes=1000)) optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001, nesterov=True, paramwise_options={'(bn|ln|gn)(\\d+)?.(weight|bias)': dict(weight_decay=0.0)}) lr_config = dict(policy='step', step=[30, 60, 90]) runner = dict(type='EpochBasedRunner', max_epochs=90)
n = int(input()) if n == 2: print(2) else: if n%2 == 0: n -= 1 for i in range(n, 1, -2): flag = True size = int(pow(i,0.5)) for j in range(3, size+1): if i % j == 0: flag = False break if flag: print(i) break
n = int(input()) if n == 2: print(2) else: if n % 2 == 0: n -= 1 for i in range(n, 1, -2): flag = True size = int(pow(i, 0.5)) for j in range(3, size + 1): if i % j == 0: flag = False break if flag: print(i) break
# More conditional structures """- multi-way if (...) : ... elif (...) : ... else : ...""" """- The try/except structures try: ... except: ... (except only runs if try fails)""" '''astr = 'Saul' try: print('123') istr = int(astr) print('456') except: istr = -1 print('using except') print('Done', istr)''' guess = input('Choose a integer number and then press Enter: ') try: number = int(guess) print('Your number is very cool! ', number*'NICE ') # print('Your number is very cool! ', number) except: print('That is not a number, try again!')
"""- multi-way if (...) : ... elif (...) : ... else : ...""" '- The try/except structures\n\ntry:\n ...\nexcept:\n ...\n\n(except only runs if try fails)' "astr = 'Saul'\ntry:\n print('123')\n istr = int(astr)\n print('456')\nexcept:\n istr = -1\n print('using except')\nprint('Done', istr)" guess = input('Choose a integer number and then press Enter: ') try: number = int(guess) print('Your number is very cool! ', number * 'NICE ') except: print('That is not a number, try again!')
height = int(input()) for i in range(height,0,-1): for j in range(i,height): print(end=" ") for j in range(1,i+1): if(i%2 != 0): c = chr(i+64) print(c,end=" ") else: print(i,end=" ") print() # Sample Input :- 5 # Output :- # E E E E E # 4 4 4 4 # C C C # 2 2 # A
height = int(input()) for i in range(height, 0, -1): for j in range(i, height): print(end=' ') for j in range(1, i + 1): if i % 2 != 0: c = chr(i + 64) print(c, end=' ') else: print(i, end=' ') print()
class PysetoError(Exception): """ Base class for all exceptions. """ pass class NotSupportedError(PysetoError): """ An Exception occurred when the function is not supported for the key object. """ pass class EncryptError(PysetoError): """ An Exception occurred when an encryption process failed. """ pass class DecryptError(PysetoError): """ An Exception occurred when an decryption process failed. """ pass class SignError(PysetoError): """ An Exception occurred when a signing process failed. """ pass class VerifyError(PysetoError): """ An Exception occurred when a verification process failed. """ pass
class Pysetoerror(Exception): """ Base class for all exceptions. """ pass class Notsupportederror(PysetoError): """ An Exception occurred when the function is not supported for the key object. """ pass class Encrypterror(PysetoError): """ An Exception occurred when an encryption process failed. """ pass class Decrypterror(PysetoError): """ An Exception occurred when an decryption process failed. """ pass class Signerror(PysetoError): """ An Exception occurred when a signing process failed. """ pass class Verifyerror(PysetoError): """ An Exception occurred when a verification process failed. """ pass
""" Django integration for Salesforce using Heroku Connect. Model classes inheriting from :class:`HerokuConnectModel<heroku_connect.models.HerokuConnectModel>` can easily be registered with `Heroku Connect`_, which then keeps their tables in the Heroku database in sync with Salesforce. .. _`Heroku Connect`: https://devcenter.heroku.com/categories/heroku-connect """ default_app_config = 'heroku_connect.apps.HerokuConnectAppConfig'
""" Django integration for Salesforce using Heroku Connect. Model classes inheriting from :class:`HerokuConnectModel<heroku_connect.models.HerokuConnectModel>` can easily be registered with `Heroku Connect`_, which then keeps their tables in the Heroku database in sync with Salesforce. .. _`Heroku Connect`: https://devcenter.heroku.com/categories/heroku-connect """ default_app_config = 'heroku_connect.apps.HerokuConnectAppConfig'
# ---------------------------------------------------------------------------- # CLASSES: nightly # # Test Case: moveoperators.py # # Tests: plots - Pseudocolor, Mesh, FilledBoundary # operators - Erase, Isosurface, Reflect, Slice, Transform # # Defect ID: '1837 # # Programmer: Brad Whitlock # Date: Thu Apr 17 16:45:46 PST 2003 # # Modifications: # Eric Brugger, Thu May 8 12:57:56 PDT 2003 # Remove a call to ToggleAutoCenterMode since it no longer exists. # # Kathleen Bonnell, Thu Aug 28 14:34:57 PDT 2003 # Remove compound var name from subset plots. # # Kathleen Bonnell, Wed Mar 17 07:33:40 PST 2004 # Set default Slice atts, as these have changed. # # Kathleen Bonnell, Wed May 5 08:13:22 PDT 2004 # Modified Slice atts to get same picture as defaults have changed. # # Brad Whitlock, Tue Jan 17 12:14:21 PDT 2006 # Added runTest4. # # Mark C. Miller, Wed Jan 20 07:37:11 PST 2010 # Added ability to swtich between Silo's HDF5 and PDB data. # # Kathleen Biagas, Thu Jul 11 08:18:42 PDT 2013 # Removed legacy sytle annotation setting. # # Kathleen Biagas, Mon Dec 19 15:45:38 PST 2016 # Use FilledBoundary plot for materials instead of Subset. # # ---------------------------------------------------------------------------- def InitAnnotation(): # Turn off all annotation except for the bounding box. a = AnnotationAttributes() TurnOffAllAnnotations(a) a.axes2D.visible = 1 a.axes2D.xAxis.label.visible = 0 a.axes2D.yAxis.label.visible = 0 a.axes2D.xAxis.title.visible = 0 a.axes2D.yAxis.title.visible = 0 a.axes3D.bboxFlag = 1 SetAnnotationAttributes(a) def InitDefaults(): # Set the default reflect operator attributes. reflect = ReflectAttributes() reflect.SetReflections(1, 1, 0, 0, 0, 0, 0, 0) SetDefaultOperatorOptions(reflect) slice = SliceAttributes() slice.project2d = 0 slice.SetAxisType(slice.XAxis) slice.SetFlip(1) SetDefaultOperatorOptions(slice) def setTheFirstView(): # Set the view v = View3DAttributes() v.viewNormal = (-0.695118, 0.351385, 0.627168) v.focus = (-10, 0, 0) v.viewUp = (0.22962, 0.935229, -0.269484) v.viewAngle = 30 v.parallelScale = 17.3205 v.nearPlane = -70 v.farPlane = 70 v.perspective = 1 SetView3D(v) # # Test operator promotion, demotion, and removal. # def runTest1(): OpenDatabase(silo_data_path("noise.silo")) # Set up a plot with a few operators. AddPlot("Pseudocolor", "hardyglobal") AddOperator("Isosurface") AddOperator("Slice") AddOperator("Reflect") DrawPlots() setTheFirstView() # Take a picture of the initial setup. Test("moveoperator_0") # Move the reflect so that it is before the slice in the pipeline. # The pipeline will be: Isosurface, Reflect, Slice DemoteOperator(2) DrawPlots() Test("moveoperator_1") # Move the reflect operator back so that the pipeline matches the # initial configuration: Isosurface, Slice, Reflect PromoteOperator(1) DrawPlots() Test("moveoperator_2") # Remove the slice operator from the middle, resulting in: # Isosurface, Reflect RemoveOperator(1) DrawPlots() Test("moveoperator_3") # Remove the Isosurface operator, resulting in: Reflect RemoveOperator(0) DrawPlots() Test("moveoperator_4") # Remove the Reflect operator RemoveOperator(0) DrawPlots() Test("moveoperator_5") DeleteAllPlots() # # Test removing an operator from more than one plot at the same time. # def runTest2(): all = 1 # Set up a couple plots of globe OpenDatabase(silo_data_path("globe.silo")) AddPlot("Pseudocolor", "u") AddPlot("Mesh", "mesh1") # Add a reflect operator to both plots. AddOperator("Reflect", all) DrawPlots() Test("moveoperator_6") # Remove the operator from both plots. RemoveOperator(0, all) DrawPlots() Test("moveoperator_7") DeleteAllPlots() # # Test setting attributes for multiple operators of the same type. # def runTest3(): # Set up a couple plots of globe OpenDatabase(silo_data_path("globe.silo")) AddPlot("Pseudocolor", "u") pc = PseudocolorAttributes() pc.SetOpacityType(pc.Constant) pc.opacity = 0.2 SetPlotOptions(pc) AddPlot("FilledBoundary", "mat1") # The subset plot is the active plot, add a couple transform # operators to it. AddOperator("Transform") AddOperator("Transform") # Set the attributes for the *first* transform operator. # This results in a full size globe translated up in Y. t0 = TransformAttributes() t0.doTranslate = 1 t0.translateY = 15 SetOperatorOptions(t0, 0) DrawPlots() Test("moveoperator_8") # Set the attributes for the *second* transform operator. # The plot has been translated, now scale it. Since it has already # been translated, this will also translate it a little in Y. t1 = TransformAttributes() t1.doScale = 1 t1.scaleX = 0.5 t1.scaleY = 0.5 t1.scaleZ = 0.5 SetOperatorOptions(t1, 1) Test("moveoperator_9") # Demote the last operator to reverse the order of the transformations. DemoteOperator(1) # Make the pc plot opaque again SetActivePlots(0) pc.SetOpacityType(pc.FullyOpaque) SetPlotOptions(pc) DrawPlots() Test("moveoperator_10") DeleteAllPlots() # # Test that removing an operator using the RemoveOperator(i) method causes # the vis window to get redrawn. # def runTest4(): OpenDatabase(silo_data_path("curv2d.silo")) AddPlot("Pseudocolor", "d") AddOperator("Isosurface") DrawPlots() Test("moveoperator_11") RemoveOperator(0) Test("moveoperator_12") DeleteAllPlots() # # Set up the environment and run all of the tests. # def runTests(): InitAnnotation() InitDefaults() runTest1() runTest2() runTest3() runTest4() # Run the tests. runTests() Exit()
def init_annotation(): a = annotation_attributes() turn_off_all_annotations(a) a.axes2D.visible = 1 a.axes2D.xAxis.label.visible = 0 a.axes2D.yAxis.label.visible = 0 a.axes2D.xAxis.title.visible = 0 a.axes2D.yAxis.title.visible = 0 a.axes3D.bboxFlag = 1 set_annotation_attributes(a) def init_defaults(): reflect = reflect_attributes() reflect.SetReflections(1, 1, 0, 0, 0, 0, 0, 0) set_default_operator_options(reflect) slice = slice_attributes() slice.project2d = 0 slice.SetAxisType(slice.XAxis) slice.SetFlip(1) set_default_operator_options(slice) def set_the_first_view(): v = view3_d_attributes() v.viewNormal = (-0.695118, 0.351385, 0.627168) v.focus = (-10, 0, 0) v.viewUp = (0.22962, 0.935229, -0.269484) v.viewAngle = 30 v.parallelScale = 17.3205 v.nearPlane = -70 v.farPlane = 70 v.perspective = 1 set_view3_d(v) def run_test1(): open_database(silo_data_path('noise.silo')) add_plot('Pseudocolor', 'hardyglobal') add_operator('Isosurface') add_operator('Slice') add_operator('Reflect') draw_plots() set_the_first_view() test('moveoperator_0') demote_operator(2) draw_plots() test('moveoperator_1') promote_operator(1) draw_plots() test('moveoperator_2') remove_operator(1) draw_plots() test('moveoperator_3') remove_operator(0) draw_plots() test('moveoperator_4') remove_operator(0) draw_plots() test('moveoperator_5') delete_all_plots() def run_test2(): all = 1 open_database(silo_data_path('globe.silo')) add_plot('Pseudocolor', 'u') add_plot('Mesh', 'mesh1') add_operator('Reflect', all) draw_plots() test('moveoperator_6') remove_operator(0, all) draw_plots() test('moveoperator_7') delete_all_plots() def run_test3(): open_database(silo_data_path('globe.silo')) add_plot('Pseudocolor', 'u') pc = pseudocolor_attributes() pc.SetOpacityType(pc.Constant) pc.opacity = 0.2 set_plot_options(pc) add_plot('FilledBoundary', 'mat1') add_operator('Transform') add_operator('Transform') t0 = transform_attributes() t0.doTranslate = 1 t0.translateY = 15 set_operator_options(t0, 0) draw_plots() test('moveoperator_8') t1 = transform_attributes() t1.doScale = 1 t1.scaleX = 0.5 t1.scaleY = 0.5 t1.scaleZ = 0.5 set_operator_options(t1, 1) test('moveoperator_9') demote_operator(1) set_active_plots(0) pc.SetOpacityType(pc.FullyOpaque) set_plot_options(pc) draw_plots() test('moveoperator_10') delete_all_plots() def run_test4(): open_database(silo_data_path('curv2d.silo')) add_plot('Pseudocolor', 'd') add_operator('Isosurface') draw_plots() test('moveoperator_11') remove_operator(0) test('moveoperator_12') delete_all_plots() def run_tests(): init_annotation() init_defaults() run_test1() run_test2() run_test3() run_test4() run_tests() exit()
gibber = input("What's the gibberish?: ") direction = input("Left/Right?: ") retry = int(input("How much do you want to try?: ")) charlist = "abcdefghijklmnopqrstuvwxyz " dictionary = {} index = 0 for e in charlist: dictionary[e] = index index += 1 jump = 1 if direction == "Right": for cycle in range(retry): notsecret = "" for char in gibber: index = dictionary[char] notsecret += charlist[(index - jump) % len(dictionary)] jump += 1 print(notsecret) else: for cycle in range(retry): notsecret = "" for char in gibber: index = dictionary[char] notsecret += charlist[(index + jump) % len(dictionary)] jump += 1 print(notsecret)
gibber = input("What's the gibberish?: ") direction = input('Left/Right?: ') retry = int(input('How much do you want to try?: ')) charlist = 'abcdefghijklmnopqrstuvwxyz ' dictionary = {} index = 0 for e in charlist: dictionary[e] = index index += 1 jump = 1 if direction == 'Right': for cycle in range(retry): notsecret = '' for char in gibber: index = dictionary[char] notsecret += charlist[(index - jump) % len(dictionary)] jump += 1 print(notsecret) else: for cycle in range(retry): notsecret = '' for char in gibber: index = dictionary[char] notsecret += charlist[(index + jump) % len(dictionary)] jump += 1 print(notsecret)
def find(f, df, ddf, a, b, eps): fa = f(a) dfa = df(a) ddfa = ddf(a) fb = f(b) dfb = df(b) ddfb = ddf(b) if not ( (fa * fb < 0) and ((dfa > 0 and dfb > 0) or (dfa < 0 and dfb < 0)) and ((ddfa > 0 and ddfb > 0) or (ddfa < 0 and ddfb < 0)) ): return currx = a if fa * ddfa > 0 else b print(f"X={currx}; F(X)={f(currx)}") shouldStop = False while True: prevx = currx currx = prevx - f(prevx)**2 / (f(prevx + f(prevx)) - f(prevx)) print(f"X={currx}; F(X)={f(currx)}") if abs(currx - prevx) < 2 * eps: if shouldStop: break shouldStop = True
def find(f, df, ddf, a, b, eps): fa = f(a) dfa = df(a) ddfa = ddf(a) fb = f(b) dfb = df(b) ddfb = ddf(b) if not (fa * fb < 0 and (dfa > 0 and dfb > 0 or (dfa < 0 and dfb < 0)) and (ddfa > 0 and ddfb > 0 or (ddfa < 0 and ddfb < 0))): return currx = a if fa * ddfa > 0 else b print(f'X={currx}; F(X)={f(currx)}') should_stop = False while True: prevx = currx currx = prevx - f(prevx) ** 2 / (f(prevx + f(prevx)) - f(prevx)) print(f'X={currx}; F(X)={f(currx)}') if abs(currx - prevx) < 2 * eps: if shouldStop: break should_stop = True
class Card: # Game card. def __init__(self, number, color, ability, wild): # Number on the face of the card self.number = number # Which color is the thing self.color = color # Draw 2 / Reverse etc self.ability = ability # Wild card? self.wild = wild def __eq__(self, other): return (self.number == other.number) and (self.color == other.color) and (self.ability == other.ability) and (self.wild == other.wild) cards = [ Card(0, (255, 0, 0), None, None), Card(1, (255, 0, 0), None, None), Card(2, (255, 0, 0), None, None), Card(3, (255, 0, 0), None, None), Card(4, (255, 0, 0), None, None), Card(5, (255, 0, 0), None, None), Card(6, (255, 0, 0), None, None), Card(7, (255, 0, 0), None, None), Card(8, (255, 0, 0), None, None), Card(9, (255, 0, 0), None, None), Card(1, (255, 0, 0), None, None), Card(2, (255, 0, 0), None, None), Card(3, (255, 0, 0), None, None), Card(4, (255, 0, 0), None, None), Card(5, (255, 0, 0), None, None), Card(6, (255, 0, 0), None, None), Card(7, (255, 0, 0), None, None), Card(8, (255, 0, 0), None, None), Card(9, (255, 0, 0), None, None), # Ability cards Card("d2", (255, 0, 0), "d2", None), Card("d2", (255, 0, 0), "d2", None), Card("skip", (255, 0, 0), "skip", None), Card("skip", (255, 0, 0), "skip", None), Card("rev", (255, 0, 0), "rev", None), Card("rev", (255, 0, 0), "rev", None), #Green Card(0, (0, 255, 0), None, None), Card(1, (0, 255, 0), None, None), Card(2, (0, 255, 0), None, None), Card(3, (0, 255, 0), None, None), Card(4, (0, 255, 0), None, None), Card(5, (0, 255, 0), None, None), Card(6, (0, 255, 0), None, None), Card(7, (0, 255, 0), None, None), Card(8, (0, 255, 0), None, None), Card(9, (0, 255, 0), None, None), Card(1, (0, 255, 0), None, None), Card(2, (0, 255, 0), None, None), Card(3, (0, 255, 0), None, None), Card(4, (0, 255, 0), None, None), Card(5, (0, 255, 0), None, None), Card(6, (0, 255, 0), None, None), Card(7, (0, 255, 0), None, None), Card(8, (0, 255, 0), None, None), Card(9, (0, 255, 0), None, None), # Ability cards Card("d2", (0, 255, 0), "d2", None), Card("d2", (0, 255, 0), "d2", None), Card("skip", (0, 255, 0), "skip", None), Card("skip", (0, 255, 0), "skip", None), Card("rev", (0, 255, 0), "rev", None), Card("rev", (0, 255, 0), "rev", None), # Blue Card(0, (0, 0, 255), None, None), Card(1, (0, 0, 255), None, None), Card(2, (0, 0, 255), None, None), Card(3, (0, 0, 255), None, None), Card(4, (0, 0, 255), None, None), Card(5, (0, 0, 255), None, None), Card(6, (0, 0, 255), None, None), Card(7, (0, 0, 255), None, None), Card(8, (0, 0, 255), None, None), Card(9, (0, 0, 255), None, None), Card(1, (0, 0, 255), None, None), Card(2, (0, 0, 255), None, None), Card(3, (0, 0, 255), None, None), Card(4, (0, 0, 255), None, None), Card(5, (0, 0, 255), None, None), Card(6, (0, 0, 255), None, None), Card(7, (0, 0, 255), None, None), Card(8, (0, 0, 255), None, None), Card(9, (0, 0, 255), None, None), # Ability cards Card("d2", (0, 0, 255), "d2", None), Card("d2", (0, 0, 255), "d2", None), Card("skip", (0, 0, 255), "skip", None), Card("skip", (0, 0, 255), "skip", None), Card("rev", (0, 0, 255), "rev", None), Card("rev", (0, 0, 255), "rev", None), # Yellow Card(0, (250, 192, 32), None, None), Card(1, (250, 192, 32), None, None), Card(2, (250, 192, 32), None, None), Card(3, (250, 192, 32), None, None), Card(4, (250, 192, 32), None, None), Card(5, (250, 192, 32), None, None), Card(6, (250, 192, 32), None, None), Card(7, (250, 192, 32), None, None), Card(8, (250, 192, 32), None, None), Card(9, (250, 192, 32), None, None), Card(1, (250, 192, 32), None, None), Card(2, (250, 192, 32), None, None), Card(3, (250, 192, 32), None, None), Card(4, (250, 192, 32), None, None), Card(5, (250, 192, 32), None, None), Card(6, (250, 192, 32), None, None), Card(7, (250, 192, 32), None, None), Card(8, (250, 192, 32), None, None), Card(9, (250, 192, 32), None, None), # Ability cards Card("d2", (250, 192, 32), "d2", None), Card("d2", (250, 192, 32), "d2", None), Card("skip", (250, 192, 32), "skip", None), Card("skip", (250, 192, 32), "skip", None), Card("rev", (250, 192, 32), "rev", None), Card("rev", (250, 192, 32), "rev", None), ]
class Card: def __init__(self, number, color, ability, wild): self.number = number self.color = color self.ability = ability self.wild = wild def __eq__(self, other): return self.number == other.number and self.color == other.color and (self.ability == other.ability) and (self.wild == other.wild) cards = [card(0, (255, 0, 0), None, None), card(1, (255, 0, 0), None, None), card(2, (255, 0, 0), None, None), card(3, (255, 0, 0), None, None), card(4, (255, 0, 0), None, None), card(5, (255, 0, 0), None, None), card(6, (255, 0, 0), None, None), card(7, (255, 0, 0), None, None), card(8, (255, 0, 0), None, None), card(9, (255, 0, 0), None, None), card(1, (255, 0, 0), None, None), card(2, (255, 0, 0), None, None), card(3, (255, 0, 0), None, None), card(4, (255, 0, 0), None, None), card(5, (255, 0, 0), None, None), card(6, (255, 0, 0), None, None), card(7, (255, 0, 0), None, None), card(8, (255, 0, 0), None, None), card(9, (255, 0, 0), None, None), card('d2', (255, 0, 0), 'd2', None), card('d2', (255, 0, 0), 'd2', None), card('skip', (255, 0, 0), 'skip', None), card('skip', (255, 0, 0), 'skip', None), card('rev', (255, 0, 0), 'rev', None), card('rev', (255, 0, 0), 'rev', None), card(0, (0, 255, 0), None, None), card(1, (0, 255, 0), None, None), card(2, (0, 255, 0), None, None), card(3, (0, 255, 0), None, None), card(4, (0, 255, 0), None, None), card(5, (0, 255, 0), None, None), card(6, (0, 255, 0), None, None), card(7, (0, 255, 0), None, None), card(8, (0, 255, 0), None, None), card(9, (0, 255, 0), None, None), card(1, (0, 255, 0), None, None), card(2, (0, 255, 0), None, None), card(3, (0, 255, 0), None, None), card(4, (0, 255, 0), None, None), card(5, (0, 255, 0), None, None), card(6, (0, 255, 0), None, None), card(7, (0, 255, 0), None, None), card(8, (0, 255, 0), None, None), card(9, (0, 255, 0), None, None), card('d2', (0, 255, 0), 'd2', None), card('d2', (0, 255, 0), 'd2', None), card('skip', (0, 255, 0), 'skip', None), card('skip', (0, 255, 0), 'skip', None), card('rev', (0, 255, 0), 'rev', None), card('rev', (0, 255, 0), 'rev', None), card(0, (0, 0, 255), None, None), card(1, (0, 0, 255), None, None), card(2, (0, 0, 255), None, None), card(3, (0, 0, 255), None, None), card(4, (0, 0, 255), None, None), card(5, (0, 0, 255), None, None), card(6, (0, 0, 255), None, None), card(7, (0, 0, 255), None, None), card(8, (0, 0, 255), None, None), card(9, (0, 0, 255), None, None), card(1, (0, 0, 255), None, None), card(2, (0, 0, 255), None, None), card(3, (0, 0, 255), None, None), card(4, (0, 0, 255), None, None), card(5, (0, 0, 255), None, None), card(6, (0, 0, 255), None, None), card(7, (0, 0, 255), None, None), card(8, (0, 0, 255), None, None), card(9, (0, 0, 255), None, None), card('d2', (0, 0, 255), 'd2', None), card('d2', (0, 0, 255), 'd2', None), card('skip', (0, 0, 255), 'skip', None), card('skip', (0, 0, 255), 'skip', None), card('rev', (0, 0, 255), 'rev', None), card('rev', (0, 0, 255), 'rev', None), card(0, (250, 192, 32), None, None), card(1, (250, 192, 32), None, None), card(2, (250, 192, 32), None, None), card(3, (250, 192, 32), None, None), card(4, (250, 192, 32), None, None), card(5, (250, 192, 32), None, None), card(6, (250, 192, 32), None, None), card(7, (250, 192, 32), None, None), card(8, (250, 192, 32), None, None), card(9, (250, 192, 32), None, None), card(1, (250, 192, 32), None, None), card(2, (250, 192, 32), None, None), card(3, (250, 192, 32), None, None), card(4, (250, 192, 32), None, None), card(5, (250, 192, 32), None, None), card(6, (250, 192, 32), None, None), card(7, (250, 192, 32), None, None), card(8, (250, 192, 32), None, None), card(9, (250, 192, 32), None, None), card('d2', (250, 192, 32), 'd2', None), card('d2', (250, 192, 32), 'd2', None), card('skip', (250, 192, 32), 'skip', None), card('skip', (250, 192, 32), 'skip', None), card('rev', (250, 192, 32), 'rev', None), card('rev', (250, 192, 32), 'rev', None)]
""" This is simply a file to store all of the docstrings for the documentation for CBSim. I place it into a new file so that it doesn't cause clutter for the scripts """ def docs_physics(): """ \n Physics implementation in CBSim =============================== General ------- Following the 2005 paper by Fred Currell and Gerd Fussmann, we consider the following simplifications: 1. The electron beam has a radial top hat profile. The radius prescribed in the configuration file is nearly the same as the Herrmann radius. Inside of this radius is an electron beam of uniform density and energy and outside of the radius is zero charge. 2. For both the electron beam and the ion cloud, we assume that the axial distributiona are uniform along the length of the trap. 3. (currently being implemented) The radial distribution of ions depends on charge state. They follow a Boltzmann distribution. The current implementation of CBSim accounts for the following ionization and recombination mechanisms: - electron impact ionization (EI) - radiative recombination (RR) - charge exchange (CX) For a species in a specified charge state i, the rate equation is written as dNi/dt = + (EI rate of charge state i-i) - (EI rate of charge state i ) + (RR rate of charge state i+1) - (RR rate of charge state i ) + (CX rate of charge state i+1) - (CX rate of charge state i ) - Resc Where Ni is the total number of ions per length in the trap. It's a good idea to look this up. At TITAN we can inject about 10^6 ions per bunch, but we can load up to a total capacity of about 10^8? I'm not sure, but check the Thesis of Annika Lennarz and the section where she discusses the stacked injection scheme. The final term in the equation is accounting for the rate at which ions can escape the trap. This escape occurs either radially or axially when the ion obtains enough kinetic energy to overcome the poitentials of the trap. Electron Impact Ionization -------------------------- EI rates are calculated using formulae of the form: Ri = Je/e * Ni * sigmai * f(e, i) where sigmai is the cross-section and f(e,i) is an electron-ion overlap factor. Je is the current density of electrons. sigmai is calculated using the Lotz formula. Radiative Recombination ----------------------- The RR rates can be calculated using a formula mirroring the EI rates: Ri = Je/e * Ni * sigmai * f(e, i) The cross section is calculated using a time-reversed photonionization cross section. Charge Exchange --------------- The CX rate is calculated as: Ri = vi_avg * N0 * Ni * sigmai where vi_avg is the average speed of the ion based on a Maxwellian speed distribution, N0 is the number density of the background gas, Ni is the number density of ions, and sigma is the cross section. In this implementation the cross section is calculated by the semi-empirical formula of Mueller and Salzborn, published September 1977. sigmai = Ak * Epgas^betak * qi^alphak for k ranging from i=1 to 4. This is the cross section for charge exchange from charge state i to charge state i-k. Epgas is the ionization potential for the background gas, and qi is the charge state of the ion. The constants Ak, betak, and alphak are given for each integer k. Sor far this has only been implemented for k=1. Ion Escape ---------- NOT YET IMPLEMENTED The ion escape rate is written as: Ri = -Ni * Vi * ( exp(-omegai)/omegai - sqrt(omegai)[erf(omegai) - 1] ) where omegai = qi * e * V / kb / Ti. V is the potential trap depth (axially or radially), and Ti is the temperature of the ions. Geometry -------- We only consider the trapping region in the EBIT ===================== Please refer to the 'timestepping' topic of docs for more details. """ return def docs_parameters(): """ Input Parameters ================ This is a more detailed description of the physics-related input parameters that the user can input through the command line or through the .cfg file. beamEnergy ---------- UNITS = eV The electron beam energy is given in units of eV. This simulation assumes a unform beam energy across the radial profile of the beam. Outside of the parameter 'beamRadius', the beam energy is zero. A general rule of thumb is that the beam energy should be between 3-4x the ionization energy to optimize for the charge state that you want. This is simply a result of competition with recombination processes in the trap. breedingTime ------------ UNITS = seconds The full calculation time for the time stepping solver. probeEvery ---------- UNITS = seconds For saving space, the output plot showing the charge state distribution only has as much resolution as is given by 'probeEvery'. Keep in mind that this value does not affect the time stepping size used for calculation population rates, it is purely for display purposes. ionEbeamOverlap --------------- UNITS = unitless This is currently implemented as a value for the amount of spatial overlap between the electron beam and ion cloud. In a future implementation we will use this to calculate the overlap function, f(e, i). beamCurrent ----------- UNITS = amps The total current of the electron beam. Is used with 'beamRadius' to calculate the current density and hence the ionization and recombination cross-sections. beamRadius ---------- UNITS = meters The radius of the electron beam. Current implementation is a hard cutoff for the electron continuum, not a tapered distribution. A top-hat distribution. pressure -------- UNITS = torr The background pressure in the EBIT trap. This is used to determine the charge exchange rates using a background of H2 gas. ionTemperature -------------- UNITS = Kelvin The __initial__ temperature of the ion cloud. It is used to determine the charge exchange rates by estimating the average ion velocity of a Maxwellian distribution at this temperature. A general rule of thumb for setting this value is... populationPercent ----------------- UNITS = fraction A fraction of the total population given for the species. If we start with a single species and populationPercent=1.0, then 100% of the population is this species. The program will renormalize the inputs, therefore if we have two species, each with populationPercent=1.0, then they each garner 50% of the total population. Please note that the current configutation is that the initial population is ALL singly charged ions (SCI). We might make this customizable in the future. """ return def docs_timestepping(): """ Time Stepping in CBSim ====================== Time stepping is using a Runge-Kutte 4 method with an adaptive time step. Because interactions between various populations in the EBIT are accounted for, the overall adapted time step for a single step is limited by any one of the populations. The following illustrates the algorithm: blah blah blah """
""" This is simply a file to store all of the docstrings for the documentation for CBSim. I place it into a new file so that it doesn't cause clutter for the scripts """ def docs_physics(): """ Physics implementation in CBSim =============================== General ------- Following the 2005 paper by Fred Currell and Gerd Fussmann, we consider the following simplifications: 1. The electron beam has a radial top hat profile. The radius prescribed in the configuration file is nearly the same as the Herrmann radius. Inside of this radius is an electron beam of uniform density and energy and outside of the radius is zero charge. 2. For both the electron beam and the ion cloud, we assume that the axial distributiona are uniform along the length of the trap. 3. (currently being implemented) The radial distribution of ions depends on charge state. They follow a Boltzmann distribution. The current implementation of CBSim accounts for the following ionization and recombination mechanisms: - electron impact ionization (EI) - radiative recombination (RR) - charge exchange (CX) For a species in a specified charge state i, the rate equation is written as dNi/dt = + (EI rate of charge state i-i) - (EI rate of charge state i ) + (RR rate of charge state i+1) - (RR rate of charge state i ) + (CX rate of charge state i+1) - (CX rate of charge state i ) - Resc Where Ni is the total number of ions per length in the trap. It's a good idea to look this up. At TITAN we can inject about 10^6 ions per bunch, but we can load up to a total capacity of about 10^8? I'm not sure, but check the Thesis of Annika Lennarz and the section where she discusses the stacked injection scheme. The final term in the equation is accounting for the rate at which ions can escape the trap. This escape occurs either radially or axially when the ion obtains enough kinetic energy to overcome the poitentials of the trap. Electron Impact Ionization -------------------------- EI rates are calculated using formulae of the form: Ri = Je/e * Ni * sigmai * f(e, i) where sigmai is the cross-section and f(e,i) is an electron-ion overlap factor. Je is the current density of electrons. sigmai is calculated using the Lotz formula. Radiative Recombination ----------------------- The RR rates can be calculated using a formula mirroring the EI rates: Ri = Je/e * Ni * sigmai * f(e, i) The cross section is calculated using a time-reversed photonionization cross section. Charge Exchange --------------- The CX rate is calculated as: Ri = vi_avg * N0 * Ni * sigmai where vi_avg is the average speed of the ion based on a Maxwellian speed distribution, N0 is the number density of the background gas, Ni is the number density of ions, and sigma is the cross section. In this implementation the cross section is calculated by the semi-empirical formula of Mueller and Salzborn, published September 1977. sigmai = Ak * Epgas^betak * qi^alphak for k ranging from i=1 to 4. This is the cross section for charge exchange from charge state i to charge state i-k. Epgas is the ionization potential for the background gas, and qi is the charge state of the ion. The constants Ak, betak, and alphak are given for each integer k. Sor far this has only been implemented for k=1. Ion Escape ---------- NOT YET IMPLEMENTED The ion escape rate is written as: Ri = -Ni * Vi * ( exp(-omegai)/omegai - sqrt(omegai)[erf(omegai) - 1] ) where omegai = qi * e * V / kb / Ti. V is the potential trap depth (axially or radially), and Ti is the temperature of the ions. Geometry -------- We only consider the trapping region in the EBIT ===================== Please refer to the 'timestepping' topic of docs for more details. """ return def docs_parameters(): """ Input Parameters ================ This is a more detailed description of the physics-related input parameters that the user can input through the command line or through the .cfg file. beamEnergy ---------- UNITS = eV The electron beam energy is given in units of eV. This simulation assumes a unform beam energy across the radial profile of the beam. Outside of the parameter 'beamRadius', the beam energy is zero. A general rule of thumb is that the beam energy should be between 3-4x the ionization energy to optimize for the charge state that you want. This is simply a result of competition with recombination processes in the trap. breedingTime ------------ UNITS = seconds The full calculation time for the time stepping solver. probeEvery ---------- UNITS = seconds For saving space, the output plot showing the charge state distribution only has as much resolution as is given by 'probeEvery'. Keep in mind that this value does not affect the time stepping size used for calculation population rates, it is purely for display purposes. ionEbeamOverlap --------------- UNITS = unitless This is currently implemented as a value for the amount of spatial overlap between the electron beam and ion cloud. In a future implementation we will use this to calculate the overlap function, f(e, i). beamCurrent ----------- UNITS = amps The total current of the electron beam. Is used with 'beamRadius' to calculate the current density and hence the ionization and recombination cross-sections. beamRadius ---------- UNITS = meters The radius of the electron beam. Current implementation is a hard cutoff for the electron continuum, not a tapered distribution. A top-hat distribution. pressure -------- UNITS = torr The background pressure in the EBIT trap. This is used to determine the charge exchange rates using a background of H2 gas. ionTemperature -------------- UNITS = Kelvin The __initial__ temperature of the ion cloud. It is used to determine the charge exchange rates by estimating the average ion velocity of a Maxwellian distribution at this temperature. A general rule of thumb for setting this value is... populationPercent ----------------- UNITS = fraction A fraction of the total population given for the species. If we start with a single species and populationPercent=1.0, then 100% of the population is this species. The program will renormalize the inputs, therefore if we have two species, each with populationPercent=1.0, then they each garner 50% of the total population. Please note that the current configutation is that the initial population is ALL singly charged ions (SCI). We might make this customizable in the future. """ return def docs_timestepping(): """ Time Stepping in CBSim ====================== Time stepping is using a Runge-Kutte 4 method with an adaptive time step. Because interactions between various populations in the EBIT are accounted for, the overall adapted time step for a single step is limited by any one of the populations. The following illustrates the algorithm: blah blah blah """
#!/usr/bin/env python3 def get_input() -> list[str]: with open('./input', 'r') as f: return [v for v in [v.strip() for v in f.readlines()] if v] def _get_input_raw() -> list[str]: with open('./input', 'r') as f: return [v.strip() for v in f.readlines()] def get_input_by_chunks() -> list[list[str]]: raw_input = _get_input_raw() lists = [list()] for imp in raw_input: if imp: lists[-1].append(imp) else: lists.append(list()) return lists yes_questions_count = 0 for chunk in get_input_by_chunks(): yes_questions = set('abcdefghijklmnopqrstuvwxyz') for line in chunk: yes_questions = yes_questions.intersection(set(line)) yes_questions_count += len(yes_questions) print(yes_questions_count)
def get_input() -> list[str]: with open('./input', 'r') as f: return [v for v in [v.strip() for v in f.readlines()] if v] def _get_input_raw() -> list[str]: with open('./input', 'r') as f: return [v.strip() for v in f.readlines()] def get_input_by_chunks() -> list[list[str]]: raw_input = _get_input_raw() lists = [list()] for imp in raw_input: if imp: lists[-1].append(imp) else: lists.append(list()) return lists yes_questions_count = 0 for chunk in get_input_by_chunks(): yes_questions = set('abcdefghijklmnopqrstuvwxyz') for line in chunk: yes_questions = yes_questions.intersection(set(line)) yes_questions_count += len(yes_questions) print(yes_questions_count)
#Anagram Detection #reads 2 strings st1 = input("Enter a string: ") st2 = input("Enter another string: ") #check if their lengths are equal if len(st1) == len(st2): #create a list n = len(st1)-1 list1 = list() while n >= 0: list1.append(st1[n]) n -= 1 m = len(st2)-1 list2 = list() while m >= 0: list2.append(st2[m]) m -= 1 #sort the list list1.sort() list2.sort() #check if lists are equal and print the result print("Anagram") if list1 == list2 else print("Not an anagram") else: print("Not an anagram")
st1 = input('Enter a string: ') st2 = input('Enter another string: ') if len(st1) == len(st2): n = len(st1) - 1 list1 = list() while n >= 0: list1.append(st1[n]) n -= 1 m = len(st2) - 1 list2 = list() while m >= 0: list2.append(st2[m]) m -= 1 list1.sort() list2.sort() print('Anagram') if list1 == list2 else print('Not an anagram') else: print('Not an anagram')
TURNS = {"R": -1j, "L": 1j} instructions = tuple((inst[0], int(inst[1:])) for inst in open("input").read().strip().split(", ")) position, direction = (0 + 0j), (0 + 1j) visited_locations = set() first_twice_location = 0 + 0j for turn, dist in instructions: direction *= TURNS[turn] for _ in range(dist): visited_locations.add(position) position += direction if not first_twice_location and position in visited_locations: first_twice_location = position print(f"Answer part one: {int(abs(position.real) + abs(position.imag))}") print(f"Answer part two: {int(abs(first_twice_location.real) + abs(first_twice_location.imag))}")
turns = {'R': -1j, 'L': 1j} instructions = tuple(((inst[0], int(inst[1:])) for inst in open('input').read().strip().split(', '))) (position, direction) = (0 + 0j, 0 + 1j) visited_locations = set() first_twice_location = 0 + 0j for (turn, dist) in instructions: direction *= TURNS[turn] for _ in range(dist): visited_locations.add(position) position += direction if not first_twice_location and position in visited_locations: first_twice_location = position print(f'Answer part one: {int(abs(position.real) + abs(position.imag))}') print(f'Answer part two: {int(abs(first_twice_location.real) + abs(first_twice_location.imag))}')
#!/usr/bin/env python3 # Define n n = 5 # Store Outputs sum = 0 facr = 1 # Loop for i in range(1,n+1): sum = sum + i facr = facr * i print(n,sum,facr)
n = 5 sum = 0 facr = 1 for i in range(1, n + 1): sum = sum + i facr = facr * i print(n, sum, facr)
""" 'abba' & 'baab' == true 'abba' & 'bbaa' == true 'abba' & 'abbba' == false 'abba' & 'abca' == false Write function: anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) => ['aabb', 'bbaa'] anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']) => ['carer', 'racer'] anagrams('laser', ['lazing', 'lazy', 'lacer']) => [] """ def anagrams(word_to_match: str, word_list: list) -> list: return [word for word in word_list if sorted(word_to_match) == sorted(word)] print(anagrams("abba", ["aabb", "abcd", "bbaa", "dada"])) print(anagrams("racer", ["crazer", "carer", "racar", "caers", "racer"]))
""" 'abba' & 'baab' == true 'abba' & 'bbaa' == true 'abba' & 'abbba' == false 'abba' & 'abca' == false Write function: anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) => ['aabb', 'bbaa'] anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']) => ['carer', 'racer'] anagrams('laser', ['lazing', 'lazy', 'lacer']) => [] """ def anagrams(word_to_match: str, word_list: list) -> list: return [word for word in word_list if sorted(word_to_match) == sorted(word)] print(anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada'])) print(anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']))
AppLayout(header=header_button, left_sidebar=None, center=center_button, right_sidebar=None, footer=footer_button)
app_layout(header=header_button, left_sidebar=None, center=center_button, right_sidebar=None, footer=footer_button)
class Result: def __init__(self, result: bool, error = None, item = None, list = [], comment = None): self.result = result self.error = error self.item = item self.list = list self.comment = comment
class Result: def __init__(self, result: bool, error=None, item=None, list=[], comment=None): self.result = result self.error = error self.item = item self.list = list self.comment = comment
# Copyright 2019 StreamSets Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Set up batch and record batch = sdc.createBatch() record = sdc.createRecord('bindings test') record.value = {} # Test constants record.value['batchSize'] = sdc.batchSize record.value['numThreads'] = sdc.numThreads record.value['lastOffsets'] = sdc.lastOffsets record.value['params'] = sdc.userParams # Test sdcFunctions record.value['isStopped()'] = sdc.isStopped() record.value['pipelineParameters()'] = sdc.pipelineParameters() record.value['isPreview()'] = sdc.isPreview() record.value['createMap()'] = sdc.createMap(False) record.value['createListMap()'] = sdc.createMap(True) record.value['getFieldNull()-false'] = sdc.getFieldNull(record, '/isStopped()') record.value['getFieldNull()-null'] = sdc.getFieldNull(record, '/not-a-real-fieldpath') records_list = [record] # Error batch.addError(record, 'this is only a test') # Event eventRecord = sdc.createEvent('new test event', 123) batch.addEvent(eventRecord) # Test batch methods record.value['batch.size()'] = batch.size() record.value['batch.errorCount()'] = batch.errorCount() record.value['batch.eventCount()'] = batch.eventCount() # public void add(ScriptRecord scriptRecord) batch.add(record) # public void add(ScriptRecord[] scriptRecords) batch.add(records_list) # Process the batch and commit new offset batch.process('newEntityName', 'newEntityOffset')
batch = sdc.createBatch() record = sdc.createRecord('bindings test') record.value = {} record.value['batchSize'] = sdc.batchSize record.value['numThreads'] = sdc.numThreads record.value['lastOffsets'] = sdc.lastOffsets record.value['params'] = sdc.userParams record.value['isStopped()'] = sdc.isStopped() record.value['pipelineParameters()'] = sdc.pipelineParameters() record.value['isPreview()'] = sdc.isPreview() record.value['createMap()'] = sdc.createMap(False) record.value['createListMap()'] = sdc.createMap(True) record.value['getFieldNull()-false'] = sdc.getFieldNull(record, '/isStopped()') record.value['getFieldNull()-null'] = sdc.getFieldNull(record, '/not-a-real-fieldpath') records_list = [record] batch.addError(record, 'this is only a test') event_record = sdc.createEvent('new test event', 123) batch.addEvent(eventRecord) record.value['batch.size()'] = batch.size() record.value['batch.errorCount()'] = batch.errorCount() record.value['batch.eventCount()'] = batch.eventCount() batch.add(record) batch.add(records_list) batch.process('newEntityName', 'newEntityOffset')
def select_outside(low, high, *values): result = [] for v in values: if (v < low) or (v > high): result.append(v) return result print(select_outside(0, 1.0, 0.3, -0.2, -0.5, 0.4, 1.7))
def select_outside(low, high, *values): result = [] for v in values: if v < low or v > high: result.append(v) return result print(select_outside(0, 1.0, 0.3, -0.2, -0.5, 0.4, 1.7))
""" Escriba un programa que simule un relog usando bucles while -------------------- Algoritmo ------------------------ 1) Crear tres variables de tipo entero que almacenen la hora, los minutos y los segundos e inicalizarlas en 0. 2) Crear un bucle while que recorra la variable hora 24 veces 3) Dentro del bucle que recorre la variable hora crear otro bucle que recorra la variable min 60 veces 4) Dentro del bucle que recorre la variable min crear otro bucle que recorra la variable seg 60 veces 5) Dentro del bucle que recorre la variable seg imprimir por pantalla el valor de todas las variables recorridas 6) Dentro del bucle que recorre la variable seg sumarle uno a la variable seg en cada iteracion. 7) Dentro del bucle que recorre la variable min (pero fuera del bucle que recorre la variable seg) sumarle uno a min en cada interacion y resetrar a cero la variable seg. 8) Dentro del bucle que recorre la variable hora (pero fuera del bucle que recorre la variable min) sumarle uno a hora en cada iteracion y resetear a cero la variable min. Este ejercicio fue propuesto por el profesor David Aeroesti del curso de pensamiento computacional de platzi. """ hora, minu, seg = 0, 0, 0 while hora < 24: while minu < 60: while seg < 60: print(hora, minu, seg) seg += 1 minu += 1 seg = 0 hora += 1 minu = 0
""" Escriba un programa que simule un relog usando bucles while -------------------- Algoritmo ------------------------ 1) Crear tres variables de tipo entero que almacenen la hora, los minutos y los segundos e inicalizarlas en 0. 2) Crear un bucle while que recorra la variable hora 24 veces 3) Dentro del bucle que recorre la variable hora crear otro bucle que recorra la variable min 60 veces 4) Dentro del bucle que recorre la variable min crear otro bucle que recorra la variable seg 60 veces 5) Dentro del bucle que recorre la variable seg imprimir por pantalla el valor de todas las variables recorridas 6) Dentro del bucle que recorre la variable seg sumarle uno a la variable seg en cada iteracion. 7) Dentro del bucle que recorre la variable min (pero fuera del bucle que recorre la variable seg) sumarle uno a min en cada interacion y resetrar a cero la variable seg. 8) Dentro del bucle que recorre la variable hora (pero fuera del bucle que recorre la variable min) sumarle uno a hora en cada iteracion y resetear a cero la variable min. Este ejercicio fue propuesto por el profesor David Aeroesti del curso de pensamiento computacional de platzi. """ (hora, minu, seg) = (0, 0, 0) while hora < 24: while minu < 60: while seg < 60: print(hora, minu, seg) seg += 1 minu += 1 seg = 0 hora += 1 minu = 0
''' Python tuple is a sequence, which can store heterogeneous data types such as integers, floats, strings, lists, and dictionaries. Tuples are written with round brackets and individual objects within the tuple are separated by a comma. The two biggest differences between a tuple and a list are that a tuple is immutable and allows you to embed one tuple inside another. There are many ways to input values into the tuple most of them are not so friendly and here goes the easilest one ''' a=[] n=int(input('Enter size of tuple: ')) for i in range(n): a.append(int(input('Enter Element: '))) print(f'\nElements of the variable are: {a}') print(f'Type of what we created is: {type(a)}') a=tuple(a) print(f'\nElements of the tuple are: {a}') print(f'Type of what we created is: {type(a)}') #other ways to create and print Tuples: tuple1 = () # An empty tuple. tuple2 = (1, 2, 3) # A tuple containing three integer objects. # A tuple containing string objects. tuple3 = ("America", "Israel","Canada", "Japan") # A tuple containing an integer, a string, and a boolean object. tuple4 = (100, "Italy", False) # A tuple containing another tuple. tuple5 = (50, ("America", "Canada", "Japan")) # The extra comma, tells the parentheses are used to hold a singleton tuple. tuple6 = (25,) print(f'\n Empty tuple: {tuple1}') print(f'\n Tuple containing three integer objects: {tuple2}') print(f'\n Tuple containing string objects: {tuple3}') print(f'\n Tuple containing an integer, a string, and a boolean objects: {tuple4}') print(f'\n Tuple containing another tuple: {tuple5}') print(f'\n Tuple containing singleton object: {tuple6}')
""" Python tuple is a sequence, which can store heterogeneous data types such as integers, floats, strings, lists, and dictionaries. Tuples are written with round brackets and individual objects within the tuple are separated by a comma. The two biggest differences between a tuple and a list are that a tuple is immutable and allows you to embed one tuple inside another. There are many ways to input values into the tuple most of them are not so friendly and here goes the easilest one """ a = [] n = int(input('Enter size of tuple: ')) for i in range(n): a.append(int(input('Enter Element: '))) print(f'\nElements of the variable are: {a}') print(f'Type of what we created is: {type(a)}') a = tuple(a) print(f'\nElements of the tuple are: {a}') print(f'Type of what we created is: {type(a)}') tuple1 = () tuple2 = (1, 2, 3) tuple3 = ('America', 'Israel', 'Canada', 'Japan') tuple4 = (100, 'Italy', False) tuple5 = (50, ('America', 'Canada', 'Japan')) tuple6 = (25,) print(f'\n Empty tuple: {tuple1}') print(f'\n Tuple containing three integer objects: {tuple2}') print(f'\n Tuple containing string objects: {tuple3}') print(f'\n Tuple containing an integer, a string, and a boolean objects: {tuple4}') print(f'\n Tuple containing another tuple: {tuple5}') print(f'\n Tuple containing singleton object: {tuple6}')
'''Exceptions. :copyright: 2021, Jeroen van der Heijden <jeroen@cesbit.com> ''' class CompileError(Exception): pass class KeywordError(CompileError): pass class ReKeywordsChangedError(CompileError): pass class NameAssignedError(CompileError): pass class MissingRefError(CompileError): pass class MissingStartError(CompileError): pass class UnusedElementError(CompileError): pass class ParseError(Exception): pass class MaxRecursionError(ParseError): pass
"""Exceptions. :copyright: 2021, Jeroen van der Heijden <jeroen@cesbit.com> """ class Compileerror(Exception): pass class Keyworderror(CompileError): pass class Rekeywordschangederror(CompileError): pass class Nameassignederror(CompileError): pass class Missingreferror(CompileError): pass class Missingstarterror(CompileError): pass class Unusedelementerror(CompileError): pass class Parseerror(Exception): pass class Maxrecursionerror(ParseError): pass
""" According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): Any live cell with fewer than two live neighbors dies, as if caused by under-population. Any live cell with two or three live neighbors lives on to the next generation. Any live cell with more than three live neighbors dies, as if by over-population.. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. Write a function to compute the next state (after one update) of the board given its current state.""" class Solution(object): def gameOfLife(self, board): """ :type board: List[List[int]] :rtype: void Do not return anything, modify board in-place instead. """ dummy = [[0 for _ in range(len(board[0]))] for _ in range(len(board))] for i in range(len(board)): for j in range(len(board[i])): count = self.get_live_neighbors(i, j, len(board), len(board[0], board)) if board[i] == 1: if count < 2 or count > 3: dummy[i][j] = 0 else: dummy[i][j] = 1 else: if count == 3: dummy[i][j] = 1 return dummy def get_live_neighbors(self, r, c, row, col, grid): if r - 1 >= 0 and r + 1 < row and c - 1 >= 0 and c + 1 < col: return grid[r - 1][c - 1] + grid[r - 1][c] + grid[r - 1][c + 1] + grid[r][c + 1] + grid[r + 1][c + 1] + \ grid[r + 1][c] + \ grid[r + 1][c - 1] + grid[r][c - 1] elif r - 1 < 0 and r + 1 < row and c - 1 >= 0 and c + 1 < col: return grid[r][c + 1] + grid[r + 1][c + 1] + grid[r + 1][c] + grid[r + 1][c - 1] + grid[r][c - 1] elif r - 1 >= 0 and r + 1 >= row and c - 1 >= 0 and c + 1 < col: return grid[r - 1][c - 1] + grid[r - 1][c] + grid[r - 1][c + 1] + grid[r][c + 1] + grid[r][c - 1] elif r - 1 >= 0 and r + 1 < row and c - 1 < 0 and c + 1 < col: return grid[r - 1][c] + grid[r - 1][c + 1] + grid[r][c + 1] + grid[r + 1][c + 1] + grid[r + 1][c] elif r - 1 >= 0 and r + 1 < row and c - 1 < 0 and c + 1 >= col: return grid[r - 1][c - 1] + grid[r - 1][c] + grid[r + 1][c] + grid[r + 1][c - 1] + grid[r][c - 1] elif r - 1 < 0 and r + 1 < row and c - 1 < 0 and c + 1 < col: return grid[r][c + 1] + grid[r + 1][c + 1] + grid[r + 1][c] elif r - 1 >= 0 and r + 1 >= row and c - 1 >= 0 and c + 1 >= col: return grid[r - 1][c - 1] + grid[r - 1][c] + grid[r][c - 1] elif r - 1 < 0 and r + 1 >= row and c - 1 >= 0 and c + 1 < col: return grid[r][c + 1] + grid[r][c - 1] elif r - 1 >= 0 and r + 1 < row and c - 1 < 0 and c + 1 >= col: return grid[r - 1][c] + grid[r + 1][c] elif r - 1 < 0 and r + 1 >= row and c - 1 < 0 and c + 1 < col: return grid[r][c + 1] else: return 0
""" According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): Any live cell with fewer than two live neighbors dies, as if caused by under-population. Any live cell with two or three live neighbors lives on to the next generation. Any live cell with more than three live neighbors dies, as if by over-population.. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. Write a function to compute the next state (after one update) of the board given its current state.""" class Solution(object): def game_of_life(self, board): """ :type board: List[List[int]] :rtype: void Do not return anything, modify board in-place instead. """ dummy = [[0 for _ in range(len(board[0]))] for _ in range(len(board))] for i in range(len(board)): for j in range(len(board[i])): count = self.get_live_neighbors(i, j, len(board), len(board[0], board)) if board[i] == 1: if count < 2 or count > 3: dummy[i][j] = 0 else: dummy[i][j] = 1 elif count == 3: dummy[i][j] = 1 return dummy def get_live_neighbors(self, r, c, row, col, grid): if r - 1 >= 0 and r + 1 < row and (c - 1 >= 0) and (c + 1 < col): return grid[r - 1][c - 1] + grid[r - 1][c] + grid[r - 1][c + 1] + grid[r][c + 1] + grid[r + 1][c + 1] + grid[r + 1][c] + grid[r + 1][c - 1] + grid[r][c - 1] elif r - 1 < 0 and r + 1 < row and (c - 1 >= 0) and (c + 1 < col): return grid[r][c + 1] + grid[r + 1][c + 1] + grid[r + 1][c] + grid[r + 1][c - 1] + grid[r][c - 1] elif r - 1 >= 0 and r + 1 >= row and (c - 1 >= 0) and (c + 1 < col): return grid[r - 1][c - 1] + grid[r - 1][c] + grid[r - 1][c + 1] + grid[r][c + 1] + grid[r][c - 1] elif r - 1 >= 0 and r + 1 < row and (c - 1 < 0) and (c + 1 < col): return grid[r - 1][c] + grid[r - 1][c + 1] + grid[r][c + 1] + grid[r + 1][c + 1] + grid[r + 1][c] elif r - 1 >= 0 and r + 1 < row and (c - 1 < 0) and (c + 1 >= col): return grid[r - 1][c - 1] + grid[r - 1][c] + grid[r + 1][c] + grid[r + 1][c - 1] + grid[r][c - 1] elif r - 1 < 0 and r + 1 < row and (c - 1 < 0) and (c + 1 < col): return grid[r][c + 1] + grid[r + 1][c + 1] + grid[r + 1][c] elif r - 1 >= 0 and r + 1 >= row and (c - 1 >= 0) and (c + 1 >= col): return grid[r - 1][c - 1] + grid[r - 1][c] + grid[r][c - 1] elif r - 1 < 0 and r + 1 >= row and (c - 1 >= 0) and (c + 1 < col): return grid[r][c + 1] + grid[r][c - 1] elif r - 1 >= 0 and r + 1 < row and (c - 1 < 0) and (c + 1 >= col): return grid[r - 1][c] + grid[r + 1][c] elif r - 1 < 0 and r + 1 >= row and (c - 1 < 0) and (c + 1 < col): return grid[r][c + 1] else: return 0
class sensorVariables: def __init__(self): self.elevation = None self.vfov = None self.north = None self.roll = None self.range = None self.azimuth = None self.model = None self.fov = None self.type = None self.version = None @classmethod def DroneSensor(cls): cls.elevation = "0.0" cls.vfov = "60" cls.north = "227" cls.roll = "0.0" cls.range = None cls.azimuth = "46" cls.model = "Drone Camera" cls.fov = None cls.type = "r-e" cls.version = "0.6" return cls
class Sensorvariables: def __init__(self): self.elevation = None self.vfov = None self.north = None self.roll = None self.range = None self.azimuth = None self.model = None self.fov = None self.type = None self.version = None @classmethod def drone_sensor(cls): cls.elevation = '0.0' cls.vfov = '60' cls.north = '227' cls.roll = '0.0' cls.range = None cls.azimuth = '46' cls.model = 'Drone Camera' cls.fov = None cls.type = 'r-e' cls.version = '0.6' return cls
"""Holds the base class for the SCIM system""" def _create_error_text(method: str, endpoint: str) -> str: return f"The {method} method is not implemented for {endpoint}" class SCIMSystem: """Represents a system behind the SCIM 2.0 interface. Methods are named according to to RFC7644 section 3.2 and follow the pattern: <HTTP method>_<SCIM endpoint> """ def get_users(self): """GET /Users""" raise NotImplementedError(_create_error_text("GET", "/Users")) def post_users(self): """POST /Users""" raise NotImplementedError(_create_error_text("POST", "/Users")) def put_users(self): """PUT /Users""" raise NotImplementedError(_create_error_text("PUT", "/Users")) def patch_users(self): """PATCH /Users""" raise NotImplementedError(_create_error_text("PATCH", "/Users")) def delete_users(self): """DELETE /Users""" raise NotImplementedError(_create_error_text("DELETE", "/Users")) def get_groups(self): """GET /Groups""" raise NotImplementedError(_create_error_text("GET", "/Groups")) def post_groups(self): """POST /Groups""" raise NotImplementedError(_create_error_text("POST", "/Groups")) def put_groups(self): """PUT /Groups""" raise NotImplementedError(_create_error_text("PUT", "/Groups")) def patch_groups(self): """PATCH /Groups""" raise NotImplementedError(_create_error_text("PATCH", "/Groups")) def delete_groups(self): """DELETE /Groups""" raise NotImplementedError(_create_error_text("DELETE", "/Groups")) def get_me(self): """GET /Me""" raise NotImplementedError(_create_error_text("GET", "/Me")) def post_me(self): """POST /Me""" raise NotImplementedError(_create_error_text("POST", "/Me")) def put_me(self): """PUT /Me""" raise NotImplementedError(_create_error_text("PUT", "/Me")) def patch_me(self): """PATCH /Me""" raise NotImplementedError(_create_error_text("PATCH", "/Me")) def delete_me(self): """DELETE /Me""" raise NotImplementedError("DELETE", "/Me") def get_service_provider_config(self): """GET /ServiceProviderConfig""" raise NotImplementedError("GET", "/ServiceProviderConfig") def get_resource_types(self): """GET /ResourceTypes""" raise NotImplementedError("GET", "/ResourceTypes") def get_schemas(self): """GET /Schemas""" raise NotImplementedError("GET", "/Schemas") def post_bulk(self): """POST /Bulk""" raise NotImplementedError("POST", "/Bulk") def post_search(self): """POST /.search""" raise NotImplementedError("POST", "/.search")
"""Holds the base class for the SCIM system""" def _create_error_text(method: str, endpoint: str) -> str: return f'The {method} method is not implemented for {endpoint}' class Scimsystem: """Represents a system behind the SCIM 2.0 interface. Methods are named according to to RFC7644 section 3.2 and follow the pattern: <HTTP method>_<SCIM endpoint> """ def get_users(self): """GET /Users""" raise not_implemented_error(_create_error_text('GET', '/Users')) def post_users(self): """POST /Users""" raise not_implemented_error(_create_error_text('POST', '/Users')) def put_users(self): """PUT /Users""" raise not_implemented_error(_create_error_text('PUT', '/Users')) def patch_users(self): """PATCH /Users""" raise not_implemented_error(_create_error_text('PATCH', '/Users')) def delete_users(self): """DELETE /Users""" raise not_implemented_error(_create_error_text('DELETE', '/Users')) def get_groups(self): """GET /Groups""" raise not_implemented_error(_create_error_text('GET', '/Groups')) def post_groups(self): """POST /Groups""" raise not_implemented_error(_create_error_text('POST', '/Groups')) def put_groups(self): """PUT /Groups""" raise not_implemented_error(_create_error_text('PUT', '/Groups')) def patch_groups(self): """PATCH /Groups""" raise not_implemented_error(_create_error_text('PATCH', '/Groups')) def delete_groups(self): """DELETE /Groups""" raise not_implemented_error(_create_error_text('DELETE', '/Groups')) def get_me(self): """GET /Me""" raise not_implemented_error(_create_error_text('GET', '/Me')) def post_me(self): """POST /Me""" raise not_implemented_error(_create_error_text('POST', '/Me')) def put_me(self): """PUT /Me""" raise not_implemented_error(_create_error_text('PUT', '/Me')) def patch_me(self): """PATCH /Me""" raise not_implemented_error(_create_error_text('PATCH', '/Me')) def delete_me(self): """DELETE /Me""" raise not_implemented_error('DELETE', '/Me') def get_service_provider_config(self): """GET /ServiceProviderConfig""" raise not_implemented_error('GET', '/ServiceProviderConfig') def get_resource_types(self): """GET /ResourceTypes""" raise not_implemented_error('GET', '/ResourceTypes') def get_schemas(self): """GET /Schemas""" raise not_implemented_error('GET', '/Schemas') def post_bulk(self): """POST /Bulk""" raise not_implemented_error('POST', '/Bulk') def post_search(self): """POST /.search""" raise not_implemented_error('POST', '/.search')
class Handler: """ Base handler for client connections. """ def disconnect(self, code): """ The Consumer's connection was closed. :param code: :return: """ pass def handle(self, content): """ Called when the handler should process some message with a given `topic` from a Consumer. :param content: :return: """ pass
class Handler: """ Base handler for client connections. """ def disconnect(self, code): """ The Consumer's connection was closed. :param code: :return: """ pass def handle(self, content): """ Called when the handler should process some message with a given `topic` from a Consumer. :param content: :return: """ pass
glossary = { 'and' : 'Logical and operator', 'or' : 'Logical or operator', 'False' : 'Boolean false value', 'True' : 'Boolean true value', 'for' : 'To create for loop', } print("and: " + glossary['and'] + "\n") print("or: " + glossary['or'] + "\n") print("False: " + glossary['False'] + "\n") print("True: " + glossary['True'] + "\n") print("for: " + glossary['for'])
glossary = {'and': 'Logical and operator', 'or': 'Logical or operator', 'False': 'Boolean false value', 'True': 'Boolean true value', 'for': 'To create for loop'} print('and: ' + glossary['and'] + '\n') print('or: ' + glossary['or'] + '\n') print('False: ' + glossary['False'] + '\n') print('True: ' + glossary['True'] + '\n') print('for: ' + glossary['for'])
def test_add(): class Number: def __add__(self, other): return 4 + other def __radd__(self, other): return other + 4 a = Number() assert 3 + a == 7 assert a + 3 == 7
def test_add(): class Number: def __add__(self, other): return 4 + other def __radd__(self, other): return other + 4 a = number() assert 3 + a == 7 assert a + 3 == 7
MinZoneNum = 0 MaxZoneNum = 999 UberZoneEntId = 0 LevelMgrEntId = 1000 EditMgrEntId = 1001
min_zone_num = 0 max_zone_num = 999 uber_zone_ent_id = 0 level_mgr_ent_id = 1000 edit_mgr_ent_id = 1001
allwords=[] for category in bag_of_words.keys(): for word in bag_of_words[category].keys(): if word not in allwords: allwords.append(word) freq_term_matrix=[] for category in bag_of_words.keys(): new=[] for column in range(0,len(allwords)): if allwords[column] in bag_of_words[category].keys(): new.append(bag_of_words[category][allwords[column]]) else: new.append(0) freq_term_matrix.append(new) file=open("example.txt","w") array=["can","could","may","might","must","will"] file.write("\t") for x in range(0,len(array)): file.write("\t"+array[x]) tfidf = TfidfTransformer() fitted=tfidf.fit(freq_term_matrix) file.write("\n") x=0 for category in bag_of_words.keys(): file.write(category+"\t") for word in array: file.write(str(freq_term_matrix[x][allwords.index(word)])+"\t") file.write("\n") x+=1 file.close()
allwords = [] for category in bag_of_words.keys(): for word in bag_of_words[category].keys(): if word not in allwords: allwords.append(word) freq_term_matrix = [] for category in bag_of_words.keys(): new = [] for column in range(0, len(allwords)): if allwords[column] in bag_of_words[category].keys(): new.append(bag_of_words[category][allwords[column]]) else: new.append(0) freq_term_matrix.append(new) file = open('example.txt', 'w') array = ['can', 'could', 'may', 'might', 'must', 'will'] file.write('\t') for x in range(0, len(array)): file.write('\t' + array[x]) tfidf = tfidf_transformer() fitted = tfidf.fit(freq_term_matrix) file.write('\n') x = 0 for category in bag_of_words.keys(): file.write(category + '\t') for word in array: file.write(str(freq_term_matrix[x][allwords.index(word)]) + '\t') file.write('\n') x += 1 file.close()
# Copyright (C) 2015-2021 Swift Navigation Inc. # Contact: https://support.swiftnav.com # # This source is subject to the license found in the file 'LICENSE' which must # be be distributed together with this source. All other rights reserved. # # THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, # EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. class NullLogger(object): """ NullLogger The :class:`NullLogger` does not log records. """ def __call__(self, msg, **metadata): pass def __enter__(self): return self def flush(self): pass def read(self, s=None): pass def write(self, s=None): pass def close(self): pass def __exit__(self, *args): pass
class Nulllogger(object): """ NullLogger The :class:`NullLogger` does not log records. """ def __call__(self, msg, **metadata): pass def __enter__(self): return self def flush(self): pass def read(self, s=None): pass def write(self, s=None): pass def close(self): pass def __exit__(self, *args): pass
""" Function: In functions we can pass mutable and immutable parameters Immutable parameter every time when we change its value new object is created and old object is discarded """ def add(x): x += 10 return x x = 5 print("Value of x: ",x) print("ID of x: ",id(x)) x = add(x) print("Value of x: ",x) print("ID of x: ",id(x)) ''' OUTPUT: Value of x: 5 ID of x: 1745579168 Value of x: 15 ID of x: 1745579488 '''
""" Function: In functions we can pass mutable and immutable parameters Immutable parameter every time when we change its value new object is created and old object is discarded """ def add(x): x += 10 return x x = 5 print('Value of x: ', x) print('ID of x: ', id(x)) x = add(x) print('Value of x: ', x) print('ID of x: ', id(x)) '\nOUTPUT:\nValue of x: 5\nID of x: 1745579168\nValue of x: 15\nID of x: 1745579488\n'
fh = open("Headlines", 'r') Word = input("Type your Word Here:") S = " " count = 1 while S: S = fh.readline() L = S.split() if Word in L: print("Line Number:", count, ":", S) count += 1
fh = open('Headlines', 'r') word = input('Type your Word Here:') s = ' ' count = 1 while S: s = fh.readline() l = S.split() if Word in L: print('Line Number:', count, ':', S) count += 1
string = "ugknbfddgicrmopn" string = "aaa" string = "jchzalrnumimnmhp" string = "haegwjzuvuyypxyu" string = "dvszwmarrgswjxmb" def check_vowels(string): vowels = 0 vowels += string.count("a") vowels += string.count("e") vowels += string.count("i") vowels += string.count("o") vowels += string.count("u") return vowels >= 3 def check_doubles(string): for i in range(len(string)-1): if string[i] == string[i+1]: return True return False def check_barred(string): barred = 0 barred += string.count("ab") barred += string.count("cd") barred += string.count("pq") barred += string.count("xy") return barred > 0 nbr_nice = 0 with open("input.txt") as f: string = f.readline().strip() while string != "": nice = check_vowels(string) and check_doubles(string) and not check_barred(string) print(string,"->",nice) if nice: nbr_nice += 1 string = f.readline().strip() print(nbr_nice)
string = 'ugknbfddgicrmopn' string = 'aaa' string = 'jchzalrnumimnmhp' string = 'haegwjzuvuyypxyu' string = 'dvszwmarrgswjxmb' def check_vowels(string): vowels = 0 vowels += string.count('a') vowels += string.count('e') vowels += string.count('i') vowels += string.count('o') vowels += string.count('u') return vowels >= 3 def check_doubles(string): for i in range(len(string) - 1): if string[i] == string[i + 1]: return True return False def check_barred(string): barred = 0 barred += string.count('ab') barred += string.count('cd') barred += string.count('pq') barred += string.count('xy') return barred > 0 nbr_nice = 0 with open('input.txt') as f: string = f.readline().strip() while string != '': nice = check_vowels(string) and check_doubles(string) and (not check_barred(string)) print(string, '->', nice) if nice: nbr_nice += 1 string = f.readline().strip() print(nbr_nice)
def lonely_integer(m): answer = 0 for x in m: answer = answer ^ x return answer a = int(input()) b = map(int, input().strip().split(" ")) print(lonely_integer(b))
def lonely_integer(m): answer = 0 for x in m: answer = answer ^ x return answer a = int(input()) b = map(int, input().strip().split(' ')) print(lonely_integer(b))
# -*- coding: utf-8 -*- """ Module for testing the autodocsumm Just a dummy module with some class definitions """ #: to test if the data is included test_data = None def test_func(): """Test if function is contained in autosummary""" pass class Class_CallTest(object): """A class defining a __call__ method""" def __get__(self, instance, owner): return self def __set__(self, instance, value): """Actually not required. We just implement it to ensure the python "help" function works well""" pass def __call__(self, a, b): """ Caller docstring for class attribute Parameters ---------- a: any dummy parameter b: anything else second dummy parameter""" pass class TestClass(object): """Class test for autosummary""" def __init__(self): #: This is an instance attribute self.instance_attribute = 1 def test_method(self): """Test if the method is included""" pass def test_method_args_kwargs(self, *args, **kwargs): """The stars at args and kwargs should not be escaped""" class InnerClass(object): """A test for an inner class""" #: to test if the class attribute is included test_attr = None class_caller = Class_CallTest() #: data to be included large_data = 'Should be included' #: data to be skipped small_data = 'Should be skipped' class InheritedTestClass(TestClass): """Class test for inherited attributes""" class TestClassWithInlineAutoClassSumm: """Class test for the autodocsummary inline .. autoclasssumm:: TestClassWithInlineAutoClassSumm This is after the summary. """ def test_method_of_inline_test(self): """A test method.""" pass #: data to be skipped large_data = 'Should also be skipped' #: data to be included small_data = 'Should also be included'
""" Module for testing the autodocsumm Just a dummy module with some class definitions """ test_data = None def test_func(): """Test if function is contained in autosummary""" pass class Class_Calltest(object): """A class defining a __call__ method""" def __get__(self, instance, owner): return self def __set__(self, instance, value): """Actually not required. We just implement it to ensure the python "help" function works well""" pass def __call__(self, a, b): """ Caller docstring for class attribute Parameters ---------- a: any dummy parameter b: anything else second dummy parameter""" pass class Testclass(object): """Class test for autosummary""" def __init__(self): self.instance_attribute = 1 def test_method(self): """Test if the method is included""" pass def test_method_args_kwargs(self, *args, **kwargs): """The stars at args and kwargs should not be escaped""" class Innerclass(object): """A test for an inner class""" test_attr = None class_caller = class__call_test() large_data = 'Should be included' small_data = 'Should be skipped' class Inheritedtestclass(TestClass): """Class test for inherited attributes""" class Testclasswithinlineautoclasssumm: """Class test for the autodocsummary inline .. autoclasssumm:: TestClassWithInlineAutoClassSumm This is after the summary. """ def test_method_of_inline_test(self): """A test method.""" pass large_data = 'Should also be skipped' small_data = 'Should also be included'
""" Given an integer array nums, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order. Return the shortest such subarray and output its leftgth. Example 1: Input: nums = [2,6,4,8,10,9,15] Output: 5 Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order. IDEA: split the array into 3 parts: [inc][dec][inc] | | left right 1) finding left boundary: for each segments like 4 / \ / 3 / \ 1 2 | | hist > cur <--- update left with index(hist) """ class Solution581: pass
""" Given an integer array nums, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order. Return the shortest such subarray and output its leftgth. Example 1: Input: nums = [2,6,4,8,10,9,15] Output: 5 Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order. IDEA: split the array into 3 parts: [inc][dec][inc] | | left right 1) finding left boundary: for each segments like 4 / \\ / 3 / 1 2 | | hist > cur <--- update left with index(hist) """ class Solution581: pass
#!/usr/bin/python3 # -*- coding: utf-8 -*- def main(): age = 30 print(age) print(30) # Variable name snake case friend_age = 23 print(friend_age) PI = 3.14159 print(PI) RADIANS_TO_DEGREES = 180/PI print(RADIANS_TO_DEGREES) if __name__ == "__main__": main()
def main(): age = 30 print(age) print(30) friend_age = 23 print(friend_age) pi = 3.14159 print(PI) radians_to_degrees = 180 / PI print(RADIANS_TO_DEGREES) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- # Every time function slice return a new object students = ['Tom', 'Mary', 'Ken', 'Billy', 'Mike'] # Get continuously subset of a range slice1 = students[0:3] print(slice1) slice2 = students[:3] print(slice2) slice3 = students[-3:] # last three print(slice3) slice4 = students[2:4] # 3rd & 4th print(slice4) slice5 = students[:] # copy print(slice5) # Discontinuous subset skipped by a step print(list(range(100)[0:20:2])) print(list(range(100)[::5])) # string can be sliced print('abcde'[0:3])
students = ['Tom', 'Mary', 'Ken', 'Billy', 'Mike'] slice1 = students[0:3] print(slice1) slice2 = students[:3] print(slice2) slice3 = students[-3:] print(slice3) slice4 = students[2:4] print(slice4) slice5 = students[:] print(slice5) print(list(range(100)[0:20:2])) print(list(range(100)[::5])) print('abcde'[0:3])
class LogHolder(): def __init__(self, dirpath, name): self.dirpath = dirpath self.name = name self.reset(suffix='train') def write_to_file(self): with open(self.dirpath + f'{self.name}-metrics-{self.suffix}.txt', 'a') as file: for i in self.metric_holder: file.write(str(i) + ' ') with open(self.dirpath + f'{self.name}-loss-{self.suffix}.txt', 'a') as file: for i in self.loss_holder: file.write(str(i) + ' ') def init_files(self, dirpath, name): metric_file = open(dirpath + f'{name}-metrics-{self.suffix}.txt', 'w') loss_file = open(dirpath + f'{name}-loss-{self.suffix}.txt', 'w') metric_file.close() loss_file.close() return None def write_metric(self, val): if type(val) == list: self.metric_holder.extend(val) else: self.metric_holder.append(val) def write_loss(self, val): self.loss_holder.append(val) def reset(self, suffix): self.metric_holder = [] self.loss_holder = [] self.suffix = suffix self.init_files(self.dirpath, self.name)
class Logholder: def __init__(self, dirpath, name): self.dirpath = dirpath self.name = name self.reset(suffix='train') def write_to_file(self): with open(self.dirpath + f'{self.name}-metrics-{self.suffix}.txt', 'a') as file: for i in self.metric_holder: file.write(str(i) + ' ') with open(self.dirpath + f'{self.name}-loss-{self.suffix}.txt', 'a') as file: for i in self.loss_holder: file.write(str(i) + ' ') def init_files(self, dirpath, name): metric_file = open(dirpath + f'{name}-metrics-{self.suffix}.txt', 'w') loss_file = open(dirpath + f'{name}-loss-{self.suffix}.txt', 'w') metric_file.close() loss_file.close() return None def write_metric(self, val): if type(val) == list: self.metric_holder.extend(val) else: self.metric_holder.append(val) def write_loss(self, val): self.loss_holder.append(val) def reset(self, suffix): self.metric_holder = [] self.loss_holder = [] self.suffix = suffix self.init_files(self.dirpath, self.name)
# This program calculates the sum of a series # of numbers entered by the user. max = 5 # The maximum number # Initialize an accumulator variable. total = 0.0 # Explain what we are doing. print('This program calculates the sum of') print(max, 'numbers you will enter.') # Get the numbers and accumulate them. for counter in range(max): number = int(input('Enter a number: ')) total = total + number # Display the total of the numbers. print('The total is', total)
max = 5 total = 0.0 print('This program calculates the sum of') print(max, 'numbers you will enter.') for counter in range(max): number = int(input('Enter a number: ')) total = total + number print('The total is', total)
class Solution: def maximum69Number (self, num: int) -> int: try: numstr = list(str(num)) numstr[numstr.index('6')]='9' return int("".join(numstr)) except: return num
class Solution: def maximum69_number(self, num: int) -> int: try: numstr = list(str(num)) numstr[numstr.index('6')] = '9' return int(''.join(numstr)) except: return num
class CurvedUniverse(): def __init__(self, shape_or_k = 0): self.shapes = {'o': -1, 'f': 0, 'c': 1} self.set_shape_or_k(shape_or_k) def set_shape_or_k(self, shape_or_k): if type(shape_or_k) == str: self.__dict__['shape'] = shape_or_k self.__dict__['k'] = self.shapes[shape_or_k] else: self.__dict__['k'] = shape_or_k self.__dict__['shape'] = [k for shape, k in self.shapes.items() if k == shape_or_k][0] def __setattr__(self, name, value): if name == 'shape' or name == 'k': self.set_shape_or_k(value) else: self.__dict__[name] = value
class Curveduniverse: def __init__(self, shape_or_k=0): self.shapes = {'o': -1, 'f': 0, 'c': 1} self.set_shape_or_k(shape_or_k) def set_shape_or_k(self, shape_or_k): if type(shape_or_k) == str: self.__dict__['shape'] = shape_or_k self.__dict__['k'] = self.shapes[shape_or_k] else: self.__dict__['k'] = shape_or_k self.__dict__['shape'] = [k for (shape, k) in self.shapes.items() if k == shape_or_k][0] def __setattr__(self, name, value): if name == 'shape' or name == 'k': self.set_shape_or_k(value) else: self.__dict__[name] = value
keep_going = "y" while keep_going.startswith("y"): a_name = input("Enter a name: ").strip() with open("users.txt", "a") as file: file.write(a_name + "; ") keep_going = input("Insert another name? (y/n) ").strip()
keep_going = 'y' while keep_going.startswith('y'): a_name = input('Enter a name: ').strip() with open('users.txt', 'a') as file: file.write(a_name + '; ') keep_going = input('Insert another name? (y/n) ').strip()
# Conditional Statements in Python # If-else statements age = int(input("Input your age: ")) if age > 17: print("You are an adult") else: print("You are a minor") #If-elif-else statements number = int(input("Input a number: ")) if number > 5: print("Is greater than 5") elif number == 5: print("Is equal to 5") else: print("Is less than 5")
age = int(input('Input your age: ')) if age > 17: print('You are an adult') else: print('You are a minor') number = int(input('Input a number: ')) if number > 5: print('Is greater than 5') elif number == 5: print('Is equal to 5') else: print('Is less than 5')
# Your App secret key SECRET_KEY = "TXxWqZHAILwElJF2bKR8" DEFAULT_FEATURE_FLAGS: Dict[str, bool] = { # Note that: RowLevelSecurityFilter is only given by default to the Admin role # and the Admin Role does have the all_datasources security permission. # But, if users create a specific role with access to RowLevelSecurityFilter MVC # and a custom datasource access, the table dropdown will not be correctly filtered # by that custom datasource access. So we are assuming a default security config, # a custom security config could potentially give access to setting filters on # tables that users do not have access to. "ROW_LEVEL_SECURITY": True, } SUPERSET_WEBSERVER_PORT = 8088 FAVICONS = [{"href": "/static/assets/images/favicon.png"}] APP_ICON = "/static/assets/images/superset-logo-horiz.png" APP_ICON_WIDTH = 126 # When using LDAP Auth, setup the LDAP server # AUTH_LDAP_SERVER = "ldap://ldapserver.new" # Uncomment to setup OpenID providers example for OpenID authentication # OPENID_PROVIDERS = [ # { 'name': 'Yahoo', 'url': 'https://open.login.yahoo.com/' }, # { 'name': 'Flickr', 'url': 'https://www.flickr.com/<username>' }, # --------------------------------------------------- # Babel config for translations # --------------------------------------------------- # Setup default language BABEL_DEFAULT_LOCALE = "en" # Your application default translation path BABEL_DEFAULT_FOLDER = "superset/translations" # The allowed translation for you app LANGUAGES = { "en": {"flag": "us", "name": "English"}, "es": {"flag": "es", "name": "Spanish"}, "it": {"flag": "it", "name": "Italian"}, "fr": {"flag": "fr", "name": "French"}, "zh": {"flag": "cn", "name": "Chinese"}, "ja": {"flag": "jp", "name": "Japanese"}, "de": {"flag": "de", "name": "German"}, "pt": {"flag": "pt", "name": "Portuguese"}, "pt_BR": {"flag": "br", "name": "Brazilian Portuguese"}, "ru": {"flag": "ru", "name": "Russian"}, "ko": {"flag": "kr", "name": "Korean"}, } # Turning off i18n by default as translation in most languages are # incomplete and not well maintained. LANGUAGES = {} # Default cache timeout (in seconds), applies to all cache backends unless # specifically overridden in each cache config. CACHE_DEFAULT_TIMEOUT = 60 * 60 * 24 # 1 day # The SQLAlchemy connection string. # SQLALCHEMY_DATABASE_URI = 'mysql://superset:superset@10.10.2.1:3306/superset' # Requires on MySQL # CREATE USER 'superset'@'%' IDENTIFIED BY '8opNioe2ax1ndL'; # GRANT ALL PRIVILEGES ON *.* TO 'superset'@'%' WITH GRANT OPTION;
secret_key = 'TXxWqZHAILwElJF2bKR8' default_feature_flags: Dict[str, bool] = {'ROW_LEVEL_SECURITY': True} superset_webserver_port = 8088 favicons = [{'href': '/static/assets/images/favicon.png'}] app_icon = '/static/assets/images/superset-logo-horiz.png' app_icon_width = 126 babel_default_locale = 'en' babel_default_folder = 'superset/translations' languages = {'en': {'flag': 'us', 'name': 'English'}, 'es': {'flag': 'es', 'name': 'Spanish'}, 'it': {'flag': 'it', 'name': 'Italian'}, 'fr': {'flag': 'fr', 'name': 'French'}, 'zh': {'flag': 'cn', 'name': 'Chinese'}, 'ja': {'flag': 'jp', 'name': 'Japanese'}, 'de': {'flag': 'de', 'name': 'German'}, 'pt': {'flag': 'pt', 'name': 'Portuguese'}, 'pt_BR': {'flag': 'br', 'name': 'Brazilian Portuguese'}, 'ru': {'flag': 'ru', 'name': 'Russian'}, 'ko': {'flag': 'kr', 'name': 'Korean'}} languages = {} cache_default_timeout = 60 * 60 * 24
N, Q = tuple(map(int, input().split())) LRT = [tuple(map(int, input().split())) for _ in range(Q)] A = [0 for _ in range(N)] for left, right, t in LRT: for i in range(left - 1, right): A[i] = t print(*A, sep="\n")
(n, q) = tuple(map(int, input().split())) lrt = [tuple(map(int, input().split())) for _ in range(Q)] a = [0 for _ in range(N)] for (left, right, t) in LRT: for i in range(left - 1, right): A[i] = t print(*A, sep='\n')
""" Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. 4 4 4 4 3 3 0 | | [3,3,5,0,0,3,1,4] | | 0 0 2 2 2 3 3 4 """ class Solution123: pass
""" Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. 4 4 4 4 3 3 0 | | [3,3,5,0,0,3,1,4] | | 0 0 2 2 2 3 3 4 """ class Solution123: pass
# AUTHOR: Dharma Teja # Python3 Concept:sum of digits in given number # GITHUB: https://github.com/dharmateja03 number=int(input()) #enter input l=list(str(number)) nums=list(map(int,l)) print(sum(nums))
number = int(input()) l = list(str(number)) nums = list(map(int, l)) print(sum(nums))
class DataThing: def __init__(self, _x): self.y = int(input("Enter a Y Value: ")) self.x = _x def __str__(self): ret = "{} {}".format(self.x, self.y) return ret def createSome(): x = int(input("Enter a X Value: ")) ret = DataThing(x) return ret ########### Tester ############### a = DataThing(5) print(a) b = createSome() print(b)
class Datathing: def __init__(self, _x): self.y = int(input('Enter a Y Value: ')) self.x = _x def __str__(self): ret = '{} {}'.format(self.x, self.y) return ret def create_some(): x = int(input('Enter a X Value: ')) ret = data_thing(x) return ret a = data_thing(5) print(a) b = create_some() print(b)
class Graph(): def __init__(self, vertices): self.V=vertices self.graph=[[0 for col in range(vertices)] for row in range(vertices)] def printSolution(self, dist): print ("Vertex \tDistance from Source") for node in range(self.V): print (node, "\t\t\t", dist[node]) def minDistance(self, dist, SPT): min = float('inf') min_index=0 for v in range(self.V): if dist[v] < min and SPT[v] == False: min = dist[v] min_index = v return min_index def dijkstra(self,source): dist= [float('inf')] * self.V dist[source]=0 SPT=[False] * self.V for _ in range(self.V): u=self.minDistance(dist, SPT) SPT[u]=True for v in range(self.V): if self.graph[u][v] > 0 and SPT[v] == False and dist[v] > dist[u] + self.graph[u][v]: dist[v] = dist[u] + self.graph[u][v] self.printSolution(dist) g=Graph(6) g.graph=[[0,50,10,0,45,0],[0,0,15,0,10,0],[20,0,0,15,0,0],[0,20,0,0,35,0],[0,0,0,30,0,0],[0,0,0,3,0,0]] g.dijkstra(0)
class Graph: def __init__(self, vertices): self.V = vertices self.graph = [[0 for col in range(vertices)] for row in range(vertices)] def print_solution(self, dist): print('Vertex \tDistance from Source') for node in range(self.V): print(node, '\t\t\t', dist[node]) def min_distance(self, dist, SPT): min = float('inf') min_index = 0 for v in range(self.V): if dist[v] < min and SPT[v] == False: min = dist[v] min_index = v return min_index def dijkstra(self, source): dist = [float('inf')] * self.V dist[source] = 0 spt = [False] * self.V for _ in range(self.V): u = self.minDistance(dist, SPT) SPT[u] = True for v in range(self.V): if self.graph[u][v] > 0 and SPT[v] == False and (dist[v] > dist[u] + self.graph[u][v]): dist[v] = dist[u] + self.graph[u][v] self.printSolution(dist) g = graph(6) g.graph = [[0, 50, 10, 0, 45, 0], [0, 0, 15, 0, 10, 0], [20, 0, 0, 15, 0, 0], [0, 20, 0, 0, 35, 0], [0, 0, 0, 30, 0, 0], [0, 0, 0, 3, 0, 0]] g.dijkstra(0)
""" Problem Link: https://binarysearch.io/problems/Linked-list-delete-last-occurrence-of-value """ # class LLNode: # def __init__(self, val, next=None): # self.val = val # self.next = next class Solution: def solve(self, node, target): # Write your code here latest = None latest_prev = None prev = None if node.val == target: prev = None latest = node current = node while current: if current.val == target: latest_prev = prev latest = current prev = current current = current.next if latest_prev: latest_prev.next = latest.next return node elif node.val == target: node = node.next return node else: return node
""" Problem Link: https://binarysearch.io/problems/Linked-list-delete-last-occurrence-of-value """ class Solution: def solve(self, node, target): latest = None latest_prev = None prev = None if node.val == target: prev = None latest = node current = node while current: if current.val == target: latest_prev = prev latest = current prev = current current = current.next if latest_prev: latest_prev.next = latest.next return node elif node.val == target: node = node.next return node else: return node
#input_column: b,string,VARCHAR(100),100,None,None #input_type: SET #output_column: b,string,VARCHAR(100),100,None,None #output_type: EMITS #!/bin/bash ls -l /tmp
ls - l / tmp
class BaseGenerator: pass class CharGenerator(BaseGenerator): pass
class Basegenerator: pass class Chargenerator(BaseGenerator): pass
# The self keyword is used when you want a method or # attribute to be for a specific object. This means that, # down below, each Tesla object can have different maxSpeed # and colors from each other. class Tesla: def __init__(self, maxSpeed=120, color="red"): self.maxSpeed = maxSpeed self.color = color def change(self, c): self.color = c p1 = Tesla(140, "blue") p2 = Tesla(100, "blue") # Notice how, when we use the self keyword, each object can # have different attributes even though they are from the # same class. p1.change("green") print(p1.color) # prints "green" p2.change("yellow") print(p2.color) # prints "yellow"
class Tesla: def __init__(self, maxSpeed=120, color='red'): self.maxSpeed = maxSpeed self.color = color def change(self, c): self.color = c p1 = tesla(140, 'blue') p2 = tesla(100, 'blue') p1.change('green') print(p1.color) p2.change('yellow') print(p2.color)
### Author: Dag Wieers <dag@wieers.com> class dstat_plugin(dstat): """ Top interrupt Displays the name of the most frequent interrupt """ def __init__(self): self.name = 'most frequent' self.vars = ('interrupt',) self.type = 's' self.width = 20 self.scale = 0 self.intset1 = [ ] self.open('/proc/stat') self.names = self.names() def names(self): ret = {} for line in dopen('/proc/interrupts'): l = line.split() if len(l) <= cpunr: continue l1 = l[0].split(':')[0] ### Cleanup possible names from /proc/interrupts l2 = ' '.join(l[cpunr+3:]) l2 = l2.replace('_hcd:', '/') l2 = re.sub('@pci[:\d+\.]+', '', l2) l2 = re.sub('ahci\[[:\da-z\.]+\]', 'ahci', l2) ret[l1] = l2 return ret def extract(self): self.output = '' self.val['total'] = 0.0 for line in self.splitlines(): if line[0] == 'intr': self.intset2 = [ int(i) for i in line[3:] ] if not self.intset1: self.intset1 = [ 0 for i in self.intset2 ] for i in range(len(self.intset2)): total = (self.intset2[i] - self.intset1[i]) * 1.0 / elapsed ### Put the highest value in self.val if total > self.val['total']: if str(i+1) in self.names: self.val['name'] = self.names[str(i+1)] else: self.val['name'] = 'int ' + str(i+1) self.val['total'] = total if step == op.delay: self.intset1 = self.intset2 if self.val['total'] != 0.0: self.output = '%-15s%s' % (self.val['name'], cprint(self.val['total'], 'd', 5, 1000)) def showcsv(self): return '%s / %f' % (self.val['name'], self.val['total']) # vim:ts=4:sw=4:et
class Dstat_Plugin(dstat): """ Top interrupt Displays the name of the most frequent interrupt """ def __init__(self): self.name = 'most frequent' self.vars = ('interrupt',) self.type = 's' self.width = 20 self.scale = 0 self.intset1 = [] self.open('/proc/stat') self.names = self.names() def names(self): ret = {} for line in dopen('/proc/interrupts'): l = line.split() if len(l) <= cpunr: continue l1 = l[0].split(':')[0] l2 = ' '.join(l[cpunr + 3:]) l2 = l2.replace('_hcd:', '/') l2 = re.sub('@pci[:\\d+\\.]+', '', l2) l2 = re.sub('ahci\\[[:\\da-z\\.]+\\]', 'ahci', l2) ret[l1] = l2 return ret def extract(self): self.output = '' self.val['total'] = 0.0 for line in self.splitlines(): if line[0] == 'intr': self.intset2 = [int(i) for i in line[3:]] if not self.intset1: self.intset1 = [0 for i in self.intset2] for i in range(len(self.intset2)): total = (self.intset2[i] - self.intset1[i]) * 1.0 / elapsed if total > self.val['total']: if str(i + 1) in self.names: self.val['name'] = self.names[str(i + 1)] else: self.val['name'] = 'int ' + str(i + 1) self.val['total'] = total if step == op.delay: self.intset1 = self.intset2 if self.val['total'] != 0.0: self.output = '%-15s%s' % (self.val['name'], cprint(self.val['total'], 'd', 5, 1000)) def showcsv(self): return '%s / %f' % (self.val['name'], self.val['total'])
_DAGGER = """ java_library( name = "dagger", exports = [ ":dagger-api", "@maven//javax/inject:javax_inject", ], exported_plugins = [":plugin"], visibility = ["//visibility:public"], ) raw_jvm_import( name = "dagger-api", jar = "@com_google_dagger_dagger//maven", visibility = ["//visibility:public"], deps = [ "@maven//javax/inject:javax_inject", ], ) java_plugin( name = "plugin", processor_class = "dagger.internal.codegen.ComponentProcessor", generates_api = True, deps = [":dagger-compiler"], ) """ _AUTO_FACTORY = """ java_library( name = "factory", exports = [ "@maven//com/google/auto/factory:auto-factory", ], exported_plugins = [":plugin"], neverlink = True, # this is only needed at compile-time, for code-gen. visibility = ["//visibility:public"], ) raw_jvm_import( name = "auto-factory", jar = "@com_google_auto_factory_auto_factory//maven", visibility = ["//visibility:public"], ) java_plugin( name = "plugin", processor_class = "com.google.auto.factory.processor.AutoFactoryProcessor", generates_api = True, deps = [":auto-factory"], ) """ _AUTO_VALUE = """ java_library( name = "value", exports = [ ":auto-value-annotations", ], exported_plugins = [":plugin"], visibility = ["//visibility:public"], ) raw_jvm_import( name = "auto-value", jar = "@com_google_auto_value_auto_value//maven", visibility = ["@maven//com/ryanharter/auto/value:__subpackages__"], ) java_plugin( name = "plugin", processor_class = "com.google.auto.value.processor.AutoValueProcessor", generates_api = True, deps = [ ":auto-value", "@maven//com/google/auto:auto-common", ], ) """ snippets = struct( AUTO_VALUE = _AUTO_VALUE, AUTO_FACTORY = _AUTO_FACTORY, DAGGER = _DAGGER, )
_dagger = '\njava_library(\n name = "dagger",\n exports = [\n ":dagger-api",\n "@maven//javax/inject:javax_inject",\n ],\n exported_plugins = [":plugin"],\n visibility = ["//visibility:public"],\n)\n\nraw_jvm_import(\n name = "dagger-api",\n jar = "@com_google_dagger_dagger//maven",\n visibility = ["//visibility:public"],\n deps = [\n "@maven//javax/inject:javax_inject",\n ],\n)\n\njava_plugin(\n name = "plugin",\n processor_class = "dagger.internal.codegen.ComponentProcessor",\n generates_api = True,\n deps = [":dagger-compiler"],\n)\n' _auto_factory = '\njava_library(\n name = "factory",\n exports = [\n "@maven//com/google/auto/factory:auto-factory",\n ],\n exported_plugins = [":plugin"],\n neverlink = True, # this is only needed at compile-time, for code-gen.\n visibility = ["//visibility:public"],\n)\n\nraw_jvm_import(\n name = "auto-factory",\n jar = "@com_google_auto_factory_auto_factory//maven",\n visibility = ["//visibility:public"],\n)\n\njava_plugin(\n name = "plugin",\n processor_class = "com.google.auto.factory.processor.AutoFactoryProcessor",\n generates_api = True,\n deps = [":auto-factory"],\n)\n' _auto_value = '\njava_library(\n name = "value",\n exports = [\n ":auto-value-annotations",\n ],\n exported_plugins = [":plugin"],\n visibility = ["//visibility:public"],\n)\n\nraw_jvm_import(\n name = "auto-value",\n jar = "@com_google_auto_value_auto_value//maven",\n visibility = ["@maven//com/ryanharter/auto/value:__subpackages__"],\n)\n\njava_plugin(\n name = "plugin",\n processor_class = "com.google.auto.value.processor.AutoValueProcessor",\n generates_api = True,\n deps = [\n ":auto-value",\n "@maven//com/google/auto:auto-common",\n ],\n)\n' snippets = struct(AUTO_VALUE=_AUTO_VALUE, AUTO_FACTORY=_AUTO_FACTORY, DAGGER=_DAGGER)
algorithm = "fourier" potential = {} potential["potential"] = "x/4" T = 8.5 dt = 0.01 eps = 0.1 f = 2.0 ngn = 4096 basis_size = 4 P = 1.0j Q = 1.0 S = 0.0 parameters = [ (P, Q, S, 1.0, -2.0) ] coefficients = [[(0, 1.0)]] write_nth = 2
algorithm = 'fourier' potential = {} potential['potential'] = 'x/4' t = 8.5 dt = 0.01 eps = 0.1 f = 2.0 ngn = 4096 basis_size = 4 p = 1j q = 1.0 s = 0.0 parameters = [(P, Q, S, 1.0, -2.0)] coefficients = [[(0, 1.0)]] write_nth = 2
""" This file contains the rules on which this abstraction of Robot Challenge is based on. """ SIZE_OF_BOARD = 5 STARTING_POSITION = (0, 0) STARTING_DIRECTION = "NORTH" ROTATE_DIRECTIONS = [ "LEFT", "RIGHT", ] DIRECTIONS = [ "NORTH", "EAST", "SOUTH", "WEST", ] DIRECTION_STEP_MAPPING = { "NORTH": (0, 1), "EAST": (1, 0), "WEST": (-1, 0), "SOUTH": (0, -1), } DIRECTION_ROTATION_MAPPING = { "NORTH": { "LEFT": "WEST", "RIGHT": "EAST", }, "EAST": { "LEFT": "NORTH", "RIGHT": "SOUTH", }, "WEST": { "LEFT": "SOUTH", "RIGHT": "NORTH", }, "SOUTH": { "LEFT": "EAST", "RIGHT": "WEST", }, } COMMANDS = { "PLACE": { "x_coordinate": int, "y_coordinate": int, "direction": str, }, "MOVE": { }, "LEFT": { }, "RIGHT": { }, "REPORT": { }, "OUTPUT": { } }
""" This file contains the rules on which this abstraction of Robot Challenge is based on. """ size_of_board = 5 starting_position = (0, 0) starting_direction = 'NORTH' rotate_directions = ['LEFT', 'RIGHT'] directions = ['NORTH', 'EAST', 'SOUTH', 'WEST'] direction_step_mapping = {'NORTH': (0, 1), 'EAST': (1, 0), 'WEST': (-1, 0), 'SOUTH': (0, -1)} direction_rotation_mapping = {'NORTH': {'LEFT': 'WEST', 'RIGHT': 'EAST'}, 'EAST': {'LEFT': 'NORTH', 'RIGHT': 'SOUTH'}, 'WEST': {'LEFT': 'SOUTH', 'RIGHT': 'NORTH'}, 'SOUTH': {'LEFT': 'EAST', 'RIGHT': 'WEST'}} commands = {'PLACE': {'x_coordinate': int, 'y_coordinate': int, 'direction': str}, 'MOVE': {}, 'LEFT': {}, 'RIGHT': {}, 'REPORT': {}, 'OUTPUT': {}}
class MessageKeyAttributes(object): def __init__(self, remote_jid, from_me, id, participant): self._remote_jid = remote_jid self._from_me = from_me self._id = id self._participant = participant def __str__(self): attrs = [] if self.remote_jid is not None: attrs.append(("remote_jid", self.remote_jid)) if self.from_me is not None: attrs.append(("from_me", self.from_me)) if self.id is not None: attrs.append(("id", self.id)) if self.participant is not None: attrs.append(("participant", self.participant)) return "[%s]" % " ".join((map(lambda item: "%s=%s" % item, attrs))) @property def remote_jid(self): return self._remote_jid @remote_jid.setter def remote_jid(self, value): self._remote_jid = value @property def from_me(self): return self._from_me @from_me.setter def from_me(self, value): self._from_me = value @property def id(self): return self._id @id.setter def id(self, value): self._id = value @property def participant(self): return self._participant @participant.setter def participant(self, value): self._participant = value
class Messagekeyattributes(object): def __init__(self, remote_jid, from_me, id, participant): self._remote_jid = remote_jid self._from_me = from_me self._id = id self._participant = participant def __str__(self): attrs = [] if self.remote_jid is not None: attrs.append(('remote_jid', self.remote_jid)) if self.from_me is not None: attrs.append(('from_me', self.from_me)) if self.id is not None: attrs.append(('id', self.id)) if self.participant is not None: attrs.append(('participant', self.participant)) return '[%s]' % ' '.join(map(lambda item: '%s=%s' % item, attrs)) @property def remote_jid(self): return self._remote_jid @remote_jid.setter def remote_jid(self, value): self._remote_jid = value @property def from_me(self): return self._from_me @from_me.setter def from_me(self, value): self._from_me = value @property def id(self): return self._id @id.setter def id(self, value): self._id = value @property def participant(self): return self._participant @participant.setter def participant(self, value): self._participant = value
amt_torch, ifo_light, amt_max, ifo_count, ifo_dgree = int(input()), [False for a in range(360)], 0, 0, 0 def fill_light(ifo_start, ifo_stop): for each_spot in range(ifo_start, ifo_stop): ifo_light[each_spot] = True for each_torch in range(amt_torch): [ifo_start, ifo_stop] = [int(b) for b in input().split()] if ifo_stop > ifo_start: fill_light(ifo_start, ifo_stop) else: fill_light(ifo_start, 360) fill_light(0, ifo_stop) while (ifo_dgree <= 360 or ifo_light[ifo_dgree%360]) and amt_max < 360: ifo_count = ifo_count + 1 if ifo_light[ifo_dgree%360] else 0 amt_max, ifo_dgree = max(amt_max, ifo_count), ifo_dgree + 1 print(amt_max) # Passed # 100%
(amt_torch, ifo_light, amt_max, ifo_count, ifo_dgree) = (int(input()), [False for a in range(360)], 0, 0, 0) def fill_light(ifo_start, ifo_stop): for each_spot in range(ifo_start, ifo_stop): ifo_light[each_spot] = True for each_torch in range(amt_torch): [ifo_start, ifo_stop] = [int(b) for b in input().split()] if ifo_stop > ifo_start: fill_light(ifo_start, ifo_stop) else: fill_light(ifo_start, 360) fill_light(0, ifo_stop) while (ifo_dgree <= 360 or ifo_light[ifo_dgree % 360]) and amt_max < 360: ifo_count = ifo_count + 1 if ifo_light[ifo_dgree % 360] else 0 (amt_max, ifo_dgree) = (max(amt_max, ifo_count), ifo_dgree + 1) print(amt_max)
# # PySNMP MIB module PHIHONG-PoE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PHIHONG-PoE-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:31:30 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint, ConstraintsIntersection, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsIntersection", "ValueRangeConstraint") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Bits, IpAddress, Counter32, TimeTicks, Unsigned32, Integer32, enterprises, ModuleIdentity, iso, ObjectIdentity, MibIdentifier, Gauge32, Counter64, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "IpAddress", "Counter32", "TimeTicks", "Unsigned32", "Integer32", "enterprises", "ModuleIdentity", "iso", "ObjectIdentity", "MibIdentifier", "Gauge32", "Counter64", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn") DisplayString, TruthValue, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TruthValue", "TextualConvention") phihong = MibIdentifier((1, 3, 6, 1, 4, 1, 24852)) poeProduct = MibIdentifier((1, 3, 6, 1, 4, 1, 24852, 2)) poeProductsPart = MibScalar((1, 3, 6, 1, 4, 1, 24852, 2, 1), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: poeProductsPart.setStatus('current') poeSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 24852, 2, 2)) poeSystemActionHubReset = MibScalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("ready", 0), ("reset", 1)))).setMaxAccess("writeonly") if mibBuilder.loadTexts: poeSystemActionHubReset.setStatus('current') poeSystemActionHubRestoreFactoryDefault = MibScalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("ready", 0), ("restore", 1)))).setMaxAccess("writeonly") if mibBuilder.loadTexts: poeSystemActionHubRestoreFactoryDefault.setStatus('current') poeSystemActionHubSaveConfiguration = MibScalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("ready", 0), ("save", 1)))).setMaxAccess("writeonly") if mibBuilder.loadTexts: poeSystemActionHubSaveConfiguration.setStatus('current') poeSystemAllPortPowerEnable = MibScalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("ready", 0), ("disable", 1), ("enable", 2)))).setMaxAccess("writeonly") if mibBuilder.loadTexts: poeSystemAllPortPowerEnable.setStatus('current') poeSystemHWVersion = MibScalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 6), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: poeSystemHWVersion.setStatus('current') poeSystemNumberOfChannel = MibScalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 7), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: poeSystemNumberOfChannel.setStatus('current') poeSystemProductPartNumber = MibScalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 8), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: poeSystemProductPartNumber.setStatus('current') poeSystemFirmwareVersion = MibScalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 10), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: poeSystemFirmwareVersion.setStatus('current') poeSystemDescription = MibScalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 11), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 10))).setMaxAccess("readwrite") if mibBuilder.loadTexts: poeSystemDescription.setStatus('current') poeSystemConsumptionPower = MibScalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 12), Integer32()).setUnits('Watts').setMaxAccess("readonly") if mibBuilder.loadTexts: poeSystemConsumptionPower.setStatus('current') poeSystemControlACPower = MibScalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 13), Integer32()).setUnits('Watts').setMaxAccess("readwrite") if mibBuilder.loadTexts: poeSystemControlACPower.setStatus('current') poeSystemControlDCPower = MibScalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 14), Integer32()).setUnits('Watts').setMaxAccess("readwrite") if mibBuilder.loadTexts: poeSystemControlDCPower.setStatus('current') poeSystemControlBothPower = MibScalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 15), Integer32()).setUnits('Watts').setMaxAccess("readwrite") if mibBuilder.loadTexts: poeSystemControlBothPower.setStatus('current') poeSystemParameters = MibScalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 16), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(3, 3)).setFixedLength(3)).setMaxAccess("readwrite") if mibBuilder.loadTexts: poeSystemParameters.setStatus('current') poeSystemSnmpVersion = MibScalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 17), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: poeSystemSnmpVersion.setStatus('current') poeSystemPerPortPowerEnable = MibScalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 18), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(48, 48)).setFixedLength(48)).setMaxAccess("readwrite") if mibBuilder.loadTexts: poeSystemPerPortPowerEnable.setStatus('current') poeSystemStatus = MibScalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("normal", 0), ("overheat", 1)))).setMaxAccess("readonly") if mibBuilder.loadTexts: poeSystemStatus.setStatus('current') poePortTable = MibTable((1, 3, 6, 1, 4, 1, 24852, 2, 3), ) if mibBuilder.loadTexts: poePortTable.setStatus('current') poePortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1), ).setIndexNames((0, "PHIHONG-PoE-MIB", "poePortIndex")) if mibBuilder.loadTexts: poePortEntry.setStatus('current') poePortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: poePortIndex.setStatus('current') poePortPowerEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disable", 1), ("enable", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: poePortPowerEnable.setStatus('current') poePortControlMaxPower = MibTableColumn((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 3), Integer32()).setUnits('mWatts').setMaxAccess("readwrite") if mibBuilder.loadTexts: poePortControlMaxPower.setStatus('current') poePortDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 6), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 10))).setMaxAccess("readwrite") if mibBuilder.loadTexts: poePortDescription.setStatus('current') poePortDetectionStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 8, 9))).clone(namedValues=NamedValues(("off", 0), ("discR", 1), ("discC", 2), ("class", 3), ("rampUp", 4), ("ramPOEown", 5), ("sampleI", 8), ("sampleV", 9)))).setMaxAccess("readonly") if mibBuilder.loadTexts: poePortDetectionStatus.setStatus('current') poePortPowerClassifications = MibTableColumn((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("class0", 1), ("class1", 2), ("class2", 3), ("class3", 4), ("class4", 5)))).setMaxAccess("readonly") if mibBuilder.loadTexts: poePortPowerClassifications.setStatus('current') poePortPowerDetectionControl = MibTableColumn((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disabled", 1), ("enabled", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: poePortPowerDetectionControl.setStatus('current') poePortPowerPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("critical", 1), ("high", 2), ("low", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: poePortPowerPriority.setStatus('current') poePortPower = MibTableColumn((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 11), Integer32()).setUnits('mWattes').setMaxAccess("readonly") if mibBuilder.loadTexts: poePortPower.setStatus('current') poePortVoltage = MibTableColumn((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 12), DisplayString()).setUnits('dVoltage').setMaxAccess("readonly") if mibBuilder.loadTexts: poePortVoltage.setStatus('current') poePortCurrent = MibTableColumn((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 13), Integer32()).setUnits('mAmps').setMaxAccess("readonly") if mibBuilder.loadTexts: poePortCurrent.setStatus('current') poePortResistance = MibTableColumn((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 14), Integer32()).setUnits('ohms').setMaxAccess("readonly") if mibBuilder.loadTexts: poePortResistance.setStatus('current') poePortFlags = MibTableColumn((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 15), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(5, 5)).setFixedLength(5)).setMaxAccess("readonly") if mibBuilder.loadTexts: poePortFlags.setStatus('current') poePortBypassFlags = MibTableColumn((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 16), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(4, 4)).setFixedLength(4)).setMaxAccess("readwrite") if mibBuilder.loadTexts: poePortBypassFlags.setStatus('current') poePortUseClassificationforPowerLimit = MibTableColumn((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disabled", 1), ("enabled", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: poePortUseClassificationforPowerLimit.setStatus('current') poePortLegacyDetection = MibTableColumn((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disabled", 1), ("enabled", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: poePortLegacyDetection.setStatus('current') poeTrapsControlTable = MibTable((1, 3, 6, 1, 4, 1, 24852, 2, 4), ) if mibBuilder.loadTexts: poeTrapsControlTable.setStatus('current') poeTrapsControlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 24852, 2, 4, 1), ).setIndexNames((0, "PHIHONG-PoE-MIB", "poeTrapsControlGroupIndex")) if mibBuilder.loadTexts: poeTrapsControlEntry.setStatus('current') poeTrapsControlGroupIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 24852, 2, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))) if mibBuilder.loadTexts: poeTrapsControlGroupIndex.setStatus('current') poeTrapsControlEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 24852, 2, 4, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("trapsDisabled", 1), ("trapsEnabled", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: poeTrapsControlEnable.setStatus('current') poeTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 24852, 2, 5)) poePortHWFailTrap = NotificationType((1, 3, 6, 1, 4, 1, 24852, 2, 5, 1)).setObjects(("PHIHONG-PoE-MIB", "poeTrapsControlGroupIndex"), ("PHIHONG-PoE-MIB", "poePortVoltage")) if mibBuilder.loadTexts: poePortHWFailTrap.setStatus('current') poePortPeakOverCurrentTrap = NotificationType((1, 3, 6, 1, 4, 1, 24852, 2, 5, 2)).setObjects(("PHIHONG-PoE-MIB", "poeTrapsControlGroupIndex"), ("PHIHONG-PoE-MIB", "poePortCurrent")) if mibBuilder.loadTexts: poePortPeakOverCurrentTrap.setStatus('current') poePortOverloadTrap = NotificationType((1, 3, 6, 1, 4, 1, 24852, 2, 5, 3)).setObjects(("PHIHONG-PoE-MIB", "poeTrapsControlGroupIndex"), ("PHIHONG-PoE-MIB", "poePortDetectionStatus")) if mibBuilder.loadTexts: poePortOverloadTrap.setStatus('current') poePortDiscoveryFailTrap = NotificationType((1, 3, 6, 1, 4, 1, 24852, 2, 5, 4)).setObjects(("PHIHONG-PoE-MIB", "poeTrapsControlGroupIndex"), ("PHIHONG-PoE-MIB", "poePortVoltage")) if mibBuilder.loadTexts: poePortDiscoveryFailTrap.setStatus('current') poePortClassificationFailTrap = NotificationType((1, 3, 6, 1, 4, 1, 24852, 2, 5, 5)).setObjects(("PHIHONG-PoE-MIB", "poeTrapsControlGroupIndex"), ("PHIHONG-PoE-MIB", "poePortVoltage")) if mibBuilder.loadTexts: poePortClassificationFailTrap.setStatus('current') poePortDisconnectTrap = NotificationType((1, 3, 6, 1, 4, 1, 24852, 2, 5, 6)).setObjects(("PHIHONG-PoE-MIB", "poeTrapsControlGroupIndex"), ("PHIHONG-PoE-MIB", "poePortDetectionStatus")) if mibBuilder.loadTexts: poePortDisconnectTrap.setStatus('current') poePortVoltageFailTrap = NotificationType((1, 3, 6, 1, 4, 1, 24852, 2, 5, 7)).setObjects(("PHIHONG-PoE-MIB", "poeTrapsControlGroupIndex"), ("PHIHONG-PoE-MIB", "poePortVoltage")) if mibBuilder.loadTexts: poePortVoltageFailTrap.setStatus('current') poeSystemOverheatTrap = NotificationType((1, 3, 6, 1, 4, 1, 24852, 2, 5, 8)).setObjects(("PHIHONG-PoE-MIB", "poeTrapsControlGroupIndex")) if mibBuilder.loadTexts: poeSystemOverheatTrap.setStatus('current') mibBuilder.exportSymbols("PHIHONG-PoE-MIB", poeSystemActionHubRestoreFactoryDefault=poeSystemActionHubRestoreFactoryDefault, poePortClassificationFailTrap=poePortClassificationFailTrap, poePortVoltage=poePortVoltage, poeSystemControlDCPower=poeSystemControlDCPower, poeProduct=poeProduct, poePortPowerPriority=poePortPowerPriority, poePortPeakOverCurrentTrap=poePortPeakOverCurrentTrap, poePortOverloadTrap=poePortOverloadTrap, poePortControlMaxPower=poePortControlMaxPower, poeSystemActionHubReset=poeSystemActionHubReset, poePortPowerDetectionControl=poePortPowerDetectionControl, poePortDiscoveryFailTrap=poePortDiscoveryFailTrap, poePortDescription=poePortDescription, poeProductsPart=poeProductsPart, poePortDisconnectTrap=poePortDisconnectTrap, poeSystemConsumptionPower=poeSystemConsumptionPower, poePortIndex=poePortIndex, poePortFlags=poePortFlags, poeSystemStatus=poeSystemStatus, poePortEntry=poePortEntry, phihong=phihong, poePortPower=poePortPower, poeSystemPerPortPowerEnable=poeSystemPerPortPowerEnable, poeSystemActionHubSaveConfiguration=poeSystemActionHubSaveConfiguration, poeSystemParameters=poeSystemParameters, poePortCurrent=poePortCurrent, poeSystemFirmwareVersion=poeSystemFirmwareVersion, poePortBypassFlags=poePortBypassFlags, poePortUseClassificationforPowerLimit=poePortUseClassificationforPowerLimit, poeSystemProductPartNumber=poeSystemProductPartNumber, poePortVoltageFailTrap=poePortVoltageFailTrap, poeSystemDescription=poeSystemDescription, poePortPowerEnable=poePortPowerEnable, poeSystemAllPortPowerEnable=poeSystemAllPortPowerEnable, poePortTable=poePortTable, poeTraps=poeTraps, poeSystemOverheatTrap=poeSystemOverheatTrap, poeTrapsControlEntry=poeTrapsControlEntry, poeTrapsControlTable=poeTrapsControlTable, poeSystemControlACPower=poeSystemControlACPower, poeTrapsControlEnable=poeTrapsControlEnable, poePortResistance=poePortResistance, poePortLegacyDetection=poePortLegacyDetection, poePortPowerClassifications=poePortPowerClassifications, poeSystemNumberOfChannel=poeSystemNumberOfChannel, poePortHWFailTrap=poePortHWFailTrap, poeSystem=poeSystem, poeTrapsControlGroupIndex=poeTrapsControlGroupIndex, poePortDetectionStatus=poePortDetectionStatus, poeSystemSnmpVersion=poeSystemSnmpVersion, poeSystemControlBothPower=poeSystemControlBothPower, poeSystemHWVersion=poeSystemHWVersion)
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, value_size_constraint, single_value_constraint, constraints_intersection, value_range_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'ValueSizeConstraint', 'SingleValueConstraint', 'ConstraintsIntersection', 'ValueRangeConstraint') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (bits, ip_address, counter32, time_ticks, unsigned32, integer32, enterprises, module_identity, iso, object_identity, mib_identifier, gauge32, counter64, notification_type, mib_scalar, mib_table, mib_table_row, mib_table_column) = mibBuilder.importSymbols('SNMPv2-SMI', 'Bits', 'IpAddress', 'Counter32', 'TimeTicks', 'Unsigned32', 'Integer32', 'enterprises', 'ModuleIdentity', 'iso', 'ObjectIdentity', 'MibIdentifier', 'Gauge32', 'Counter64', 'NotificationType', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn') (display_string, truth_value, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TruthValue', 'TextualConvention') phihong = mib_identifier((1, 3, 6, 1, 4, 1, 24852)) poe_product = mib_identifier((1, 3, 6, 1, 4, 1, 24852, 2)) poe_products_part = mib_scalar((1, 3, 6, 1, 4, 1, 24852, 2, 1), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: poeProductsPart.setStatus('current') poe_system = mib_identifier((1, 3, 6, 1, 4, 1, 24852, 2, 2)) poe_system_action_hub_reset = mib_scalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('ready', 0), ('reset', 1)))).setMaxAccess('writeonly') if mibBuilder.loadTexts: poeSystemActionHubReset.setStatus('current') poe_system_action_hub_restore_factory_default = mib_scalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('ready', 0), ('restore', 1)))).setMaxAccess('writeonly') if mibBuilder.loadTexts: poeSystemActionHubRestoreFactoryDefault.setStatus('current') poe_system_action_hub_save_configuration = mib_scalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('ready', 0), ('save', 1)))).setMaxAccess('writeonly') if mibBuilder.loadTexts: poeSystemActionHubSaveConfiguration.setStatus('current') poe_system_all_port_power_enable = mib_scalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2))).clone(namedValues=named_values(('ready', 0), ('disable', 1), ('enable', 2)))).setMaxAccess('writeonly') if mibBuilder.loadTexts: poeSystemAllPortPowerEnable.setStatus('current') poe_system_hw_version = mib_scalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 6), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: poeSystemHWVersion.setStatus('current') poe_system_number_of_channel = mib_scalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 7), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: poeSystemNumberOfChannel.setStatus('current') poe_system_product_part_number = mib_scalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 8), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: poeSystemProductPartNumber.setStatus('current') poe_system_firmware_version = mib_scalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 10), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: poeSystemFirmwareVersion.setStatus('current') poe_system_description = mib_scalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 11), display_string().subtype(subtypeSpec=value_size_constraint(0, 10))).setMaxAccess('readwrite') if mibBuilder.loadTexts: poeSystemDescription.setStatus('current') poe_system_consumption_power = mib_scalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 12), integer32()).setUnits('Watts').setMaxAccess('readonly') if mibBuilder.loadTexts: poeSystemConsumptionPower.setStatus('current') poe_system_control_ac_power = mib_scalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 13), integer32()).setUnits('Watts').setMaxAccess('readwrite') if mibBuilder.loadTexts: poeSystemControlACPower.setStatus('current') poe_system_control_dc_power = mib_scalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 14), integer32()).setUnits('Watts').setMaxAccess('readwrite') if mibBuilder.loadTexts: poeSystemControlDCPower.setStatus('current') poe_system_control_both_power = mib_scalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 15), integer32()).setUnits('Watts').setMaxAccess('readwrite') if mibBuilder.loadTexts: poeSystemControlBothPower.setStatus('current') poe_system_parameters = mib_scalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 16), display_string().subtype(subtypeSpec=value_size_constraint(3, 3)).setFixedLength(3)).setMaxAccess('readwrite') if mibBuilder.loadTexts: poeSystemParameters.setStatus('current') poe_system_snmp_version = mib_scalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 17), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: poeSystemSnmpVersion.setStatus('current') poe_system_per_port_power_enable = mib_scalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 18), display_string().subtype(subtypeSpec=value_size_constraint(48, 48)).setFixedLength(48)).setMaxAccess('readwrite') if mibBuilder.loadTexts: poeSystemPerPortPowerEnable.setStatus('current') poe_system_status = mib_scalar((1, 3, 6, 1, 4, 1, 24852, 2, 2, 19), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('normal', 0), ('overheat', 1)))).setMaxAccess('readonly') if mibBuilder.loadTexts: poeSystemStatus.setStatus('current') poe_port_table = mib_table((1, 3, 6, 1, 4, 1, 24852, 2, 3)) if mibBuilder.loadTexts: poePortTable.setStatus('current') poe_port_entry = mib_table_row((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1)).setIndexNames((0, 'PHIHONG-PoE-MIB', 'poePortIndex')) if mibBuilder.loadTexts: poePortEntry.setStatus('current') poe_port_index = mib_table_column((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 2147483647))).setMaxAccess('readonly') if mibBuilder.loadTexts: poePortIndex.setStatus('current') poe_port_power_enable = mib_table_column((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('disable', 1), ('enable', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: poePortPowerEnable.setStatus('current') poe_port_control_max_power = mib_table_column((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 3), integer32()).setUnits('mWatts').setMaxAccess('readwrite') if mibBuilder.loadTexts: poePortControlMaxPower.setStatus('current') poe_port_description = mib_table_column((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 6), display_string().subtype(subtypeSpec=value_size_constraint(0, 10))).setMaxAccess('readwrite') if mibBuilder.loadTexts: poePortDescription.setStatus('current') poe_port_detection_status = mib_table_column((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3, 4, 5, 8, 9))).clone(namedValues=named_values(('off', 0), ('discR', 1), ('discC', 2), ('class', 3), ('rampUp', 4), ('ramPOEown', 5), ('sampleI', 8), ('sampleV', 9)))).setMaxAccess('readonly') if mibBuilder.loadTexts: poePortDetectionStatus.setStatus('current') poe_port_power_classifications = mib_table_column((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 8), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5))).clone(namedValues=named_values(('class0', 1), ('class1', 2), ('class2', 3), ('class3', 4), ('class4', 5)))).setMaxAccess('readonly') if mibBuilder.loadTexts: poePortPowerClassifications.setStatus('current') poe_port_power_detection_control = mib_table_column((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 9), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('disabled', 1), ('enabled', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: poePortPowerDetectionControl.setStatus('current') poe_port_power_priority = mib_table_column((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 10), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('critical', 1), ('high', 2), ('low', 3)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: poePortPowerPriority.setStatus('current') poe_port_power = mib_table_column((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 11), integer32()).setUnits('mWattes').setMaxAccess('readonly') if mibBuilder.loadTexts: poePortPower.setStatus('current') poe_port_voltage = mib_table_column((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 12), display_string()).setUnits('dVoltage').setMaxAccess('readonly') if mibBuilder.loadTexts: poePortVoltage.setStatus('current') poe_port_current = mib_table_column((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 13), integer32()).setUnits('mAmps').setMaxAccess('readonly') if mibBuilder.loadTexts: poePortCurrent.setStatus('current') poe_port_resistance = mib_table_column((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 14), integer32()).setUnits('ohms').setMaxAccess('readonly') if mibBuilder.loadTexts: poePortResistance.setStatus('current') poe_port_flags = mib_table_column((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 15), display_string().subtype(subtypeSpec=value_size_constraint(5, 5)).setFixedLength(5)).setMaxAccess('readonly') if mibBuilder.loadTexts: poePortFlags.setStatus('current') poe_port_bypass_flags = mib_table_column((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 16), display_string().subtype(subtypeSpec=value_size_constraint(4, 4)).setFixedLength(4)).setMaxAccess('readwrite') if mibBuilder.loadTexts: poePortBypassFlags.setStatus('current') poe_port_use_classificationfor_power_limit = mib_table_column((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 17), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('disabled', 1), ('enabled', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: poePortUseClassificationforPowerLimit.setStatus('current') poe_port_legacy_detection = mib_table_column((1, 3, 6, 1, 4, 1, 24852, 2, 3, 1, 18), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('disabled', 1), ('enabled', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: poePortLegacyDetection.setStatus('current') poe_traps_control_table = mib_table((1, 3, 6, 1, 4, 1, 24852, 2, 4)) if mibBuilder.loadTexts: poeTrapsControlTable.setStatus('current') poe_traps_control_entry = mib_table_row((1, 3, 6, 1, 4, 1, 24852, 2, 4, 1)).setIndexNames((0, 'PHIHONG-PoE-MIB', 'poeTrapsControlGroupIndex')) if mibBuilder.loadTexts: poeTrapsControlEntry.setStatus('current') poe_traps_control_group_index = mib_table_column((1, 3, 6, 1, 4, 1, 24852, 2, 4, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(0, 65535))) if mibBuilder.loadTexts: poeTrapsControlGroupIndex.setStatus('current') poe_traps_control_enable = mib_table_column((1, 3, 6, 1, 4, 1, 24852, 2, 4, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('trapsDisabled', 1), ('trapsEnabled', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: poeTrapsControlEnable.setStatus('current') poe_traps = mib_identifier((1, 3, 6, 1, 4, 1, 24852, 2, 5)) poe_port_hw_fail_trap = notification_type((1, 3, 6, 1, 4, 1, 24852, 2, 5, 1)).setObjects(('PHIHONG-PoE-MIB', 'poeTrapsControlGroupIndex'), ('PHIHONG-PoE-MIB', 'poePortVoltage')) if mibBuilder.loadTexts: poePortHWFailTrap.setStatus('current') poe_port_peak_over_current_trap = notification_type((1, 3, 6, 1, 4, 1, 24852, 2, 5, 2)).setObjects(('PHIHONG-PoE-MIB', 'poeTrapsControlGroupIndex'), ('PHIHONG-PoE-MIB', 'poePortCurrent')) if mibBuilder.loadTexts: poePortPeakOverCurrentTrap.setStatus('current') poe_port_overload_trap = notification_type((1, 3, 6, 1, 4, 1, 24852, 2, 5, 3)).setObjects(('PHIHONG-PoE-MIB', 'poeTrapsControlGroupIndex'), ('PHIHONG-PoE-MIB', 'poePortDetectionStatus')) if mibBuilder.loadTexts: poePortOverloadTrap.setStatus('current') poe_port_discovery_fail_trap = notification_type((1, 3, 6, 1, 4, 1, 24852, 2, 5, 4)).setObjects(('PHIHONG-PoE-MIB', 'poeTrapsControlGroupIndex'), ('PHIHONG-PoE-MIB', 'poePortVoltage')) if mibBuilder.loadTexts: poePortDiscoveryFailTrap.setStatus('current') poe_port_classification_fail_trap = notification_type((1, 3, 6, 1, 4, 1, 24852, 2, 5, 5)).setObjects(('PHIHONG-PoE-MIB', 'poeTrapsControlGroupIndex'), ('PHIHONG-PoE-MIB', 'poePortVoltage')) if mibBuilder.loadTexts: poePortClassificationFailTrap.setStatus('current') poe_port_disconnect_trap = notification_type((1, 3, 6, 1, 4, 1, 24852, 2, 5, 6)).setObjects(('PHIHONG-PoE-MIB', 'poeTrapsControlGroupIndex'), ('PHIHONG-PoE-MIB', 'poePortDetectionStatus')) if mibBuilder.loadTexts: poePortDisconnectTrap.setStatus('current') poe_port_voltage_fail_trap = notification_type((1, 3, 6, 1, 4, 1, 24852, 2, 5, 7)).setObjects(('PHIHONG-PoE-MIB', 'poeTrapsControlGroupIndex'), ('PHIHONG-PoE-MIB', 'poePortVoltage')) if mibBuilder.loadTexts: poePortVoltageFailTrap.setStatus('current') poe_system_overheat_trap = notification_type((1, 3, 6, 1, 4, 1, 24852, 2, 5, 8)).setObjects(('PHIHONG-PoE-MIB', 'poeTrapsControlGroupIndex')) if mibBuilder.loadTexts: poeSystemOverheatTrap.setStatus('current') mibBuilder.exportSymbols('PHIHONG-PoE-MIB', poeSystemActionHubRestoreFactoryDefault=poeSystemActionHubRestoreFactoryDefault, poePortClassificationFailTrap=poePortClassificationFailTrap, poePortVoltage=poePortVoltage, poeSystemControlDCPower=poeSystemControlDCPower, poeProduct=poeProduct, poePortPowerPriority=poePortPowerPriority, poePortPeakOverCurrentTrap=poePortPeakOverCurrentTrap, poePortOverloadTrap=poePortOverloadTrap, poePortControlMaxPower=poePortControlMaxPower, poeSystemActionHubReset=poeSystemActionHubReset, poePortPowerDetectionControl=poePortPowerDetectionControl, poePortDiscoveryFailTrap=poePortDiscoveryFailTrap, poePortDescription=poePortDescription, poeProductsPart=poeProductsPart, poePortDisconnectTrap=poePortDisconnectTrap, poeSystemConsumptionPower=poeSystemConsumptionPower, poePortIndex=poePortIndex, poePortFlags=poePortFlags, poeSystemStatus=poeSystemStatus, poePortEntry=poePortEntry, phihong=phihong, poePortPower=poePortPower, poeSystemPerPortPowerEnable=poeSystemPerPortPowerEnable, poeSystemActionHubSaveConfiguration=poeSystemActionHubSaveConfiguration, poeSystemParameters=poeSystemParameters, poePortCurrent=poePortCurrent, poeSystemFirmwareVersion=poeSystemFirmwareVersion, poePortBypassFlags=poePortBypassFlags, poePortUseClassificationforPowerLimit=poePortUseClassificationforPowerLimit, poeSystemProductPartNumber=poeSystemProductPartNumber, poePortVoltageFailTrap=poePortVoltageFailTrap, poeSystemDescription=poeSystemDescription, poePortPowerEnable=poePortPowerEnable, poeSystemAllPortPowerEnable=poeSystemAllPortPowerEnable, poePortTable=poePortTable, poeTraps=poeTraps, poeSystemOverheatTrap=poeSystemOverheatTrap, poeTrapsControlEntry=poeTrapsControlEntry, poeTrapsControlTable=poeTrapsControlTable, poeSystemControlACPower=poeSystemControlACPower, poeTrapsControlEnable=poeTrapsControlEnable, poePortResistance=poePortResistance, poePortLegacyDetection=poePortLegacyDetection, poePortPowerClassifications=poePortPowerClassifications, poeSystemNumberOfChannel=poeSystemNumberOfChannel, poePortHWFailTrap=poePortHWFailTrap, poeSystem=poeSystem, poeTrapsControlGroupIndex=poeTrapsControlGroupIndex, poePortDetectionStatus=poePortDetectionStatus, poeSystemSnmpVersion=poeSystemSnmpVersion, poeSystemControlBothPower=poeSystemControlBothPower, poeSystemHWVersion=poeSystemHWVersion)
class InvalidRating(ValueError): pass class AuthRequired(TypeError): pass class CannotChangeVote(Exception): pass class CannotDeleteVote(Exception): pass class IPLimitReached(Exception): pass
class Invalidrating(ValueError): pass class Authrequired(TypeError): pass class Cannotchangevote(Exception): pass class Cannotdeletevote(Exception): pass class Iplimitreached(Exception): pass
''' oneflux.util For license information: see LICENSE file or headers in oneflux.__init__.py General utilities for oneflux @author: Gilberto Pastorello @contact: gzpastorello@lbl.gov @date: 2017-01-31 '''
""" oneflux.util For license information: see LICENSE file or headers in oneflux.__init__.py General utilities for oneflux @author: Gilberto Pastorello @contact: gzpastorello@lbl.gov @date: 2017-01-31 """
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if prices is None or len(prices) == 0: return 0 low = prices[0] res = 0 for i in range(1, len(prices)): res = max(res, prices[i] - low) low = min(low, prices[i]) return res
class Solution(object): def max_profit(self, prices): """ :type prices: List[int] :rtype: int """ if prices is None or len(prices) == 0: return 0 low = prices[0] res = 0 for i in range(1, len(prices)): res = max(res, prices[i] - low) low = min(low, prices[i]) return res
class ParserException(Exception): def __init__(self, message, filename=None, xml_exception=None, xml_element=None): Exception.__init__(self, message) self._message = message self._filename = filename self._xml_exception = xml_exception self._xml_element = xml_element @property def message(self): return self._message @property def filename(self): return self._filename @filename.setter def filename(self, filename): self._filename = filename @property def xml_exception(self): return self._xml_exception @xml_exception.setter def xml_exception(self, xml_exception): self._xml_exception = xml_exception @property def xml_element(self): return self._xml_element @xml_element.setter def xml_element(self, xml_element): self._xml_element = xml_element def format_message(self): msg = self._message if self._filename is not None: msg += " in [%s]" % self._filename if self._xml_exception is not None: if isinstance(self._xml_exception, str): msg += " : " msg += self._xml_exception else: msg += " at [line(%d), column(%d)]" % (self._xml_exception.position[0], self._xml_exception.position[1]) if self._xml_element is not None: if hasattr(self._xml_element, '_end_line_number') and hasattr(self._xml_element, '_end_column_number'): msg += " at [line(%d), column(%d)]" % (self._xml_element._end_line_number, self._xml_element._end_column_number) return msg class DuplicateGrammarException(ParserException): def __init__(self, message, filename=None, xml_exception=None, xml_element=None): ParserException.__init__(self, message, filename=filename, xml_exception=xml_exception, xml_element=xml_element) class MatcherException(Exception): def __init__(self, message): Exception.__init__(self, message) self.message = message
class Parserexception(Exception): def __init__(self, message, filename=None, xml_exception=None, xml_element=None): Exception.__init__(self, message) self._message = message self._filename = filename self._xml_exception = xml_exception self._xml_element = xml_element @property def message(self): return self._message @property def filename(self): return self._filename @filename.setter def filename(self, filename): self._filename = filename @property def xml_exception(self): return self._xml_exception @xml_exception.setter def xml_exception(self, xml_exception): self._xml_exception = xml_exception @property def xml_element(self): return self._xml_element @xml_element.setter def xml_element(self, xml_element): self._xml_element = xml_element def format_message(self): msg = self._message if self._filename is not None: msg += ' in [%s]' % self._filename if self._xml_exception is not None: if isinstance(self._xml_exception, str): msg += ' : ' msg += self._xml_exception else: msg += ' at [line(%d), column(%d)]' % (self._xml_exception.position[0], self._xml_exception.position[1]) if self._xml_element is not None: if hasattr(self._xml_element, '_end_line_number') and hasattr(self._xml_element, '_end_column_number'): msg += ' at [line(%d), column(%d)]' % (self._xml_element._end_line_number, self._xml_element._end_column_number) return msg class Duplicategrammarexception(ParserException): def __init__(self, message, filename=None, xml_exception=None, xml_element=None): ParserException.__init__(self, message, filename=filename, xml_exception=xml_exception, xml_element=xml_element) class Matcherexception(Exception): def __init__(self, message): Exception.__init__(self, message) self.message = message
def main(filepath): ranges = [(int(x),int(y)-1) for x,y in [tuple(x.split(':')) for x in open(filepath,'r').read().replace(' ','').split('\n')]] delay = 0; caught = True severity = sum(depth*(scan_range+1) for depth, scan_range in ranges if depth%(2*scan_range) == 0) while caught: delay += 1 for depth, scan_range in ranges: caught = True if (delay+depth)%(2*scan_range) == 0 else False if caught: break return severity, delay print(main('13.txt'))
def main(filepath): ranges = [(int(x), int(y) - 1) for (x, y) in [tuple(x.split(':')) for x in open(filepath, 'r').read().replace(' ', '').split('\n')]] delay = 0 caught = True severity = sum((depth * (scan_range + 1) for (depth, scan_range) in ranges if depth % (2 * scan_range) == 0)) while caught: delay += 1 for (depth, scan_range) in ranges: caught = True if (delay + depth) % (2 * scan_range) == 0 else False if caught: break return (severity, delay) print(main('13.txt'))
# https://www.coursera.org/learn/competitive-programming-core-skills/lecture/wSCUn/defining-solution-set #input: n items with given weights w, w2, w3 and costs c1, c2 etc # largest total cost of thetems whose total weights doesnt exceed W. store= [] #defaultdict(int) def nested_fors(n,firstfor,x): global store # global w_total, c_total w_total= 0 c_total = 0 n= 3 W=5 w =[3,2,5] c = [2,3,6] if firstfor < n: for x[firstfor] in ['0','1']: # print(x[0]) nested_fors(n,firstfor+1, x) else: # print(x) m = '' if x[0] == '1': w_total += w[0] c_total += c[0] if x[1] == '1': # m=m +'2' w_total += w[1] c_total += c[1] # store[x] = 0 if x[2] == '1': # m=m +'3' w_total += w[2] c_total += c[2] # print(m) # store[x] = 3 store.append(w_total) print(w_total,c_total,store) # # return store if __name__ == '__main__': print(nested_fors(3,0,['']*3)) # def main(n,c,w,W): # return 0 # if __name__ == "__main__": # n= 3 # W=5 # w =[3,2,5] # c = [2,3,6] # print(main(n,c,w,W))
store = [] def nested_fors(n, firstfor, x): global store w_total = 0 c_total = 0 n = 3 w = 5 w = [3, 2, 5] c = [2, 3, 6] if firstfor < n: for x[firstfor] in ['0', '1']: nested_fors(n, firstfor + 1, x) else: m = '' if x[0] == '1': w_total += w[0] c_total += c[0] if x[1] == '1': w_total += w[1] c_total += c[1] if x[2] == '1': w_total += w[2] c_total += c[2] store.append(w_total) print(w_total, c_total, store) if __name__ == '__main__': print(nested_fors(3, 0, [''] * 3))
class TransmissionData(object,IDisposable): """ A class representing information on all external file references in a document. TransmissionData(other: TransmissionData) """ def Dispose(self): """ Dispose(self: TransmissionData) """ pass @staticmethod def DocumentIsNotTransmitted(filePath): """ DocumentIsNotTransmitted(filePath: ModelPath) -> bool Determines whether the document at a given file location is not transmitted. filePath: The path to the document whose transmitted state will be checked. Returns: False if the document is a transmitted file,true otherwise. """ pass def GetAllExternalFileReferenceIds(self): """ GetAllExternalFileReferenceIds(self: TransmissionData) -> ICollection[ElementId] Gets the ids of all ExternalFileReferences. Returns: The ids of all ExternalFileReferences. """ pass def GetDesiredReferenceData(self,elemId): """ GetDesiredReferenceData(self: TransmissionData,elemId: ElementId) -> ExternalFileReference Gets the ExternalFileReference representing path and load status information to be used the next time this TransmissionData's document is loaded. elemId: The ElementId of the Element which the external file reference is a component of. Returns: An ExternalFileReference containing the requested path and load status information for an external file """ pass def GetLastSavedReferenceData(self,elemId): """ GetLastSavedReferenceData(self: TransmissionData,elemId: ElementId) -> ExternalFileReference Gets the ExternalFileReference representing path and load status information concerning the most recent time this TransmissionData's document was opened. elemId: The ElementId of the Element which the external file reference is a component of. Returns: An ExternalFileReference containing the previous path and load status information for an external file """ pass @staticmethod def IsDocumentTransmitted(filePath): """ IsDocumentTransmitted(filePath: ModelPath) -> bool Determines whether the document at a given file location is transmitted. filePath: The path to the document whose transmitted state will be checked. Returns: True if the document is a transmitted file,false otherwise. """ pass @staticmethod def ReadTransmissionData(path): """ ReadTransmissionData(path: ModelPath) -> TransmissionData Reads the TransmissionData associated with the file at the given location. path: A ModelPath indicating the file Revit should read the TransmissionData of. If this ModelPath is a file path,it must be an absolute path. Returns: The TransmissionData containing external file information for the file at the given location. """ pass def ReleaseUnmanagedResources(self,*args): """ ReleaseUnmanagedResources(self: TransmissionData,disposing: bool) """ pass def SetDesiredReferenceData(self,elemId,path,pathType,shouldLoad): """ SetDesiredReferenceData(self: TransmissionData,elemId: ElementId,path: ModelPath,pathType: PathType,shouldLoad: bool) Sets the ExternalFileReference information which Revit should use the next time it opens the document which this TransmissionData belongs to. elemId: The id of the element associated with this reference. path: A ModelPath indicating the location to load the external file reference from. pathType: A PathType value indicating what type of path the ModelPath is. shouldLoad: True if the external file should be loaded the next time Revit opens the document. False if it should be unloaded. """ pass @staticmethod def WriteTransmissionData(path,data): """ WriteTransmissionData(path: ModelPath,data: TransmissionData) Writes the given TransmissionData into the Revit file at the given location. path: A ModelPath indicating the file Revit should write the TransmissionData of. This ModelPath must be a file path and an absolute path. data: The TransmissionData to be written into the document. Note that Revit will not check that the ElementIds in the TransmissionData correspond to real Elements. """ pass def __enter__(self,*args): """ __enter__(self: IDisposable) -> object """ pass def __exit__(self,*args): """ __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """ pass def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass @staticmethod def __new__(self,other): """ __new__(cls: type,other: TransmissionData) """ pass def __repr__(self,*args): """ __repr__(self: object) -> str """ pass IsTransmitted=property(lambda self: object(),lambda self,v: None,lambda self: None) """Determines whether this file has been transmitted or not. Get: IsTransmitted(self: TransmissionData) -> bool Set: IsTransmitted(self: TransmissionData)=value """ IsValidObject=property(lambda self: object(),lambda self,v: None,lambda self: None) """Specifies whether the .NET object represents a valid Revit entity. Get: IsValidObject(self: TransmissionData) -> bool """ UserData=property(lambda self: object(),lambda self,v: None,lambda self: None) """A string which users can store notes in. Get: UserData(self: TransmissionData) -> str Set: UserData(self: TransmissionData)=value """ Version=property(lambda self: object(),lambda self,v: None,lambda self: None) """The format version for TransmissionData Get: Version(self: TransmissionData) -> int """
class Transmissiondata(object, IDisposable): """ A class representing information on all external file references in a document. TransmissionData(other: TransmissionData) """ def dispose(self): """ Dispose(self: TransmissionData) """ pass @staticmethod def document_is_not_transmitted(filePath): """ DocumentIsNotTransmitted(filePath: ModelPath) -> bool Determines whether the document at a given file location is not transmitted. filePath: The path to the document whose transmitted state will be checked. Returns: False if the document is a transmitted file,true otherwise. """ pass def get_all_external_file_reference_ids(self): """ GetAllExternalFileReferenceIds(self: TransmissionData) -> ICollection[ElementId] Gets the ids of all ExternalFileReferences. Returns: The ids of all ExternalFileReferences. """ pass def get_desired_reference_data(self, elemId): """ GetDesiredReferenceData(self: TransmissionData,elemId: ElementId) -> ExternalFileReference Gets the ExternalFileReference representing path and load status information to be used the next time this TransmissionData's document is loaded. elemId: The ElementId of the Element which the external file reference is a component of. Returns: An ExternalFileReference containing the requested path and load status information for an external file """ pass def get_last_saved_reference_data(self, elemId): """ GetLastSavedReferenceData(self: TransmissionData,elemId: ElementId) -> ExternalFileReference Gets the ExternalFileReference representing path and load status information concerning the most recent time this TransmissionData's document was opened. elemId: The ElementId of the Element which the external file reference is a component of. Returns: An ExternalFileReference containing the previous path and load status information for an external file """ pass @staticmethod def is_document_transmitted(filePath): """ IsDocumentTransmitted(filePath: ModelPath) -> bool Determines whether the document at a given file location is transmitted. filePath: The path to the document whose transmitted state will be checked. Returns: True if the document is a transmitted file,false otherwise. """ pass @staticmethod def read_transmission_data(path): """ ReadTransmissionData(path: ModelPath) -> TransmissionData Reads the TransmissionData associated with the file at the given location. path: A ModelPath indicating the file Revit should read the TransmissionData of. If this ModelPath is a file path,it must be an absolute path. Returns: The TransmissionData containing external file information for the file at the given location. """ pass def release_unmanaged_resources(self, *args): """ ReleaseUnmanagedResources(self: TransmissionData,disposing: bool) """ pass def set_desired_reference_data(self, elemId, path, pathType, shouldLoad): """ SetDesiredReferenceData(self: TransmissionData,elemId: ElementId,path: ModelPath,pathType: PathType,shouldLoad: bool) Sets the ExternalFileReference information which Revit should use the next time it opens the document which this TransmissionData belongs to. elemId: The id of the element associated with this reference. path: A ModelPath indicating the location to load the external file reference from. pathType: A PathType value indicating what type of path the ModelPath is. shouldLoad: True if the external file should be loaded the next time Revit opens the document. False if it should be unloaded. """ pass @staticmethod def write_transmission_data(path, data): """ WriteTransmissionData(path: ModelPath,data: TransmissionData) Writes the given TransmissionData into the Revit file at the given location. path: A ModelPath indicating the file Revit should write the TransmissionData of. This ModelPath must be a file path and an absolute path. data: The TransmissionData to be written into the document. Note that Revit will not check that the ElementIds in the TransmissionData correspond to real Elements. """ pass def __enter__(self, *args): """ __enter__(self: IDisposable) -> object """ pass def __exit__(self, *args): """ __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """ pass def __init__(self, *args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass @staticmethod def __new__(self, other): """ __new__(cls: type,other: TransmissionData) """ pass def __repr__(self, *args): """ __repr__(self: object) -> str """ pass is_transmitted = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Determines whether this file has been transmitted or not.\n\n\n\nGet: IsTransmitted(self: TransmissionData) -> bool\n\n\n\nSet: IsTransmitted(self: TransmissionData)=value\n\n' is_valid_object = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Specifies whether the .NET object represents a valid Revit entity.\n\n\n\nGet: IsValidObject(self: TransmissionData) -> bool\n\n\n\n' user_data = property(lambda self: object(), lambda self, v: None, lambda self: None) 'A string which users can store notes in.\n\n\n\nGet: UserData(self: TransmissionData) -> str\n\n\n\nSet: UserData(self: TransmissionData)=value\n\n' version = property(lambda self: object(), lambda self, v: None, lambda self: None) 'The format version for TransmissionData\n\n\n\nGet: Version(self: TransmissionData) -> int\n\n\n\n'
def ScaleGlyph(glyph, scale, r): glyph['advanceWidth'] = r(glyph['advanceWidth'] * scale) if 'advanceHeight' in glyph: glyph['advanceHeight'] = r(glyph['advanceHeight'] * scale) glyph['verticalOrigin'] = r(glyph['verticalOrigin'] * scale) rm = [ 'stemH', 'stemV', 'hintMasks', 'contourMasks', 'instructions' ] for k in rm: if k in glyph: del glyph[k] if 'contours' in glyph: for contour in glyph['contours']: for point in contour: point['x'] = r(point['x'] * scale) point['y'] = r(point['y'] * scale) if 'references' in glyph: for reference in glyph['references']: reference['x'] = r(reference['x'] * scale) reference['y'] = r(reference['y'] * scale) def ScaleMarkToBase(subtable, scale, r): for _, mark in subtable['marks'].items(): mark['x'] = r(mark['x'] * scale) mark['y'] = r(mark['y'] * scale) for _, base in subtable['bases'].items(): for _, klass in base.items(): klass['x'] = r(klass['x'] * scale) klass['y'] = r(klass['y'] * scale) def ScaleMarkToLig(subtable, scale, r): for _, mark in subtable['marks'].items(): mark['x'] = r(mark['x'] * scale) mark['y'] = r(mark['y'] * scale) for _, base in subtable['bases'].items(): for component in base: for _, klass in component.items(): klass['x'] = r(klass['x'] * scale) klass['y'] = r(klass['y'] * scale) def ScaleGposValue(entry, scale, r): optional = lambda d, k: d[k] if k in d else 0 return { k: r(optional(entry, k) * scale) for k in [ 'dx', 'dy', 'dWidth', 'dHeight' ] } def ScaleGposSingle(subtable, scale, r): for k, v in subtable.items(): subtable[k] = ScaleGposValue(v, scale, r) def ScaleGposPair(subtable, scale, r): for row in subtable['matrix']: for j in range(len(row)): if type(row[j]) in [ int, float ]: row[j] = r(row[j] * scale) else: if 'first' in row[j]: row[j]['first'] = ScaleGposValue(row[j]['first'], scale, r) if 'second' in row[j]: row[j]['second'] = ScaleGposValue(row[j]['second'], scale, r) GposScaler = { 'gpos_mark_to_base': ScaleMarkToBase, 'gpos_mark_to_mark': ScaleMarkToBase, 'gpos_mark_to_ligature': ScaleMarkToLig, 'gpos_single': ScaleGposSingle, 'gpos_pair': ScaleGposPair, } def Rebase(font, scale, roundToInt = False): r = round if roundToInt else lambda x: x if scale == 1: return for _, g in font['glyf'].items(): ScaleGlyph(g, scale, r) font['head']['unitsPerEm'] = r(font['head']['unitsPerEm'] * scale) if 'hhea' in font: s = [ 'ascender', 'descender', 'lineGap' ] for k in s: font['hhea'][k] = r(font['hhea'][k] * scale) if 'vhea' in font: s = [ 'ascent', 'descent', 'lineGap' ] for k in s: font['vhea'][k] = r(font['vhea'][k] * scale) if 'OS_2' in font: s = [ 'xAvgCharWidth', 'usWinAscent', 'usWinDescent', 'sTypoAscender', 'sTypoDescender', 'sTypoLineGap', 'sxHeight', 'sCapHeight', 'ySubscriptXSize', 'ySubscriptYSize', 'ySubscriptXOffset', 'ySubscriptYOffset', 'ySupscriptXSize', 'ySupscriptYSize', 'ySupscriptXOffset', 'ySupscriptYOffset', 'yStrikeoutSize', 'yStrikeoutPosition', ] for k in s: font['OS_2'][k] = r(font['OS_2'][k] * scale) if 'post' in font: s = [ 'underlinePosition', 'underlineThickness' ] for k in s: font['post'][k] = r(font['post'][k] * scale) if 'GPOS' in font: for _, lookup in font['GPOS']['lookups'].items(): if lookup['type'] in GposScaler: scaler = GposScaler[lookup['type']] for subtable in lookup['subtables']: scaler(subtable, scale, r)
def scale_glyph(glyph, scale, r): glyph['advanceWidth'] = r(glyph['advanceWidth'] * scale) if 'advanceHeight' in glyph: glyph['advanceHeight'] = r(glyph['advanceHeight'] * scale) glyph['verticalOrigin'] = r(glyph['verticalOrigin'] * scale) rm = ['stemH', 'stemV', 'hintMasks', 'contourMasks', 'instructions'] for k in rm: if k in glyph: del glyph[k] if 'contours' in glyph: for contour in glyph['contours']: for point in contour: point['x'] = r(point['x'] * scale) point['y'] = r(point['y'] * scale) if 'references' in glyph: for reference in glyph['references']: reference['x'] = r(reference['x'] * scale) reference['y'] = r(reference['y'] * scale) def scale_mark_to_base(subtable, scale, r): for (_, mark) in subtable['marks'].items(): mark['x'] = r(mark['x'] * scale) mark['y'] = r(mark['y'] * scale) for (_, base) in subtable['bases'].items(): for (_, klass) in base.items(): klass['x'] = r(klass['x'] * scale) klass['y'] = r(klass['y'] * scale) def scale_mark_to_lig(subtable, scale, r): for (_, mark) in subtable['marks'].items(): mark['x'] = r(mark['x'] * scale) mark['y'] = r(mark['y'] * scale) for (_, base) in subtable['bases'].items(): for component in base: for (_, klass) in component.items(): klass['x'] = r(klass['x'] * scale) klass['y'] = r(klass['y'] * scale) def scale_gpos_value(entry, scale, r): optional = lambda d, k: d[k] if k in d else 0 return {k: r(optional(entry, k) * scale) for k in ['dx', 'dy', 'dWidth', 'dHeight']} def scale_gpos_single(subtable, scale, r): for (k, v) in subtable.items(): subtable[k] = scale_gpos_value(v, scale, r) def scale_gpos_pair(subtable, scale, r): for row in subtable['matrix']: for j in range(len(row)): if type(row[j]) in [int, float]: row[j] = r(row[j] * scale) else: if 'first' in row[j]: row[j]['first'] = scale_gpos_value(row[j]['first'], scale, r) if 'second' in row[j]: row[j]['second'] = scale_gpos_value(row[j]['second'], scale, r) gpos_scaler = {'gpos_mark_to_base': ScaleMarkToBase, 'gpos_mark_to_mark': ScaleMarkToBase, 'gpos_mark_to_ligature': ScaleMarkToLig, 'gpos_single': ScaleGposSingle, 'gpos_pair': ScaleGposPair} def rebase(font, scale, roundToInt=False): r = round if roundToInt else lambda x: x if scale == 1: return for (_, g) in font['glyf'].items(): scale_glyph(g, scale, r) font['head']['unitsPerEm'] = r(font['head']['unitsPerEm'] * scale) if 'hhea' in font: s = ['ascender', 'descender', 'lineGap'] for k in s: font['hhea'][k] = r(font['hhea'][k] * scale) if 'vhea' in font: s = ['ascent', 'descent', 'lineGap'] for k in s: font['vhea'][k] = r(font['vhea'][k] * scale) if 'OS_2' in font: s = ['xAvgCharWidth', 'usWinAscent', 'usWinDescent', 'sTypoAscender', 'sTypoDescender', 'sTypoLineGap', 'sxHeight', 'sCapHeight', 'ySubscriptXSize', 'ySubscriptYSize', 'ySubscriptXOffset', 'ySubscriptYOffset', 'ySupscriptXSize', 'ySupscriptYSize', 'ySupscriptXOffset', 'ySupscriptYOffset', 'yStrikeoutSize', 'yStrikeoutPosition'] for k in s: font['OS_2'][k] = r(font['OS_2'][k] * scale) if 'post' in font: s = ['underlinePosition', 'underlineThickness'] for k in s: font['post'][k] = r(font['post'][k] * scale) if 'GPOS' in font: for (_, lookup) in font['GPOS']['lookups'].items(): if lookup['type'] in GposScaler: scaler = GposScaler[lookup['type']] for subtable in lookup['subtables']: scaler(subtable, scale, r)
test = { 'name': 'Recursion', 'points': 0, 'suites': [ { 'cases': [ { 'code': r""" >>> def f(a, b): ... if a > b: ... return f(a - 3, 2 * b) ... elif a < b: ... return f(b // 2, a) ... else: ... return b >>> f(2, 2) 2 >>> f(7, 4) 4 >>> f(2, 28) 8 >>> f(-1, -3) Infinite """, 'hidden': False, 'locked': False } ], 'scored': False, 'type': 'wwpp' } ] }
test = {'name': 'Recursion', 'points': 0, 'suites': [{'cases': [{'code': '\n >>> def f(a, b):\n ... if a > b:\n ... return f(a - 3, 2 * b)\n ... elif a < b:\n ... return f(b // 2, a)\n ... else:\n ... return b\n >>> f(2, 2)\n 2\n >>> f(7, 4)\n 4\n >>> f(2, 28)\n 8\n >>> f(-1, -3)\n Infinite\n ', 'hidden': False, 'locked': False}], 'scored': False, 'type': 'wwpp'}]}
class Side: BUY = 'BUY' SELL = 'SELL' class TimeInForce: GTC = 'GTC' # Good Til Cancel (default value on BTSE) IOC = 'IOC' # Immediate or Cancel FIVEMIN = 'FIVEMIN' # 5 mins HOUR = 'HOUR' # 1 hour TWELVEHOUR = 'TWELVEHOUR' # 12 hours DAY = 'DAY' # 1 day WEEK = 'WEEK' # 1 week MONTH = 'MONTH' # 1 month class OrderType: LIMIT = 'LIMIT' MARKET = 'MARKET' OCO = 'OCO' class TxType: LIMIT = 'LIMIT' # default value on BTSE STOP = 'STOP' # Stop Loss Orders TRIGGER = 'TRIGGER' # Take Profit orders
class Side: buy = 'BUY' sell = 'SELL' class Timeinforce: gtc = 'GTC' ioc = 'IOC' fivemin = 'FIVEMIN' hour = 'HOUR' twelvehour = 'TWELVEHOUR' day = 'DAY' week = 'WEEK' month = 'MONTH' class Ordertype: limit = 'LIMIT' market = 'MARKET' oco = 'OCO' class Txtype: limit = 'LIMIT' stop = 'STOP' trigger = 'TRIGGER'
""" Profile ../profile-datasets-py/standard54lev_allgas_seaonly/001.py file automaticaly created by prof_gen.py script """ self["ID"] = "../profile-datasets-py/standard54lev_allgas_seaonly/001.py" self["Q"] = numpy.array([ 1.41160700e+00, 2.34372900e+00, 3.53382100e+00, 4.62808600e+00, 5.43775900e+00, 5.97528000e+00, 5.99996400e+00, 5.99996400e+00, 5.92326900e+00, 5.67006500e+00, 5.38217500e+00, 5.03966700e+00, 4.72761900e+00, 4.44221700e+00, 4.17989400e+00, 3.91709500e+00, 3.61858400e+00, 3.37512500e+00, 3.21437800e+00, 2.87882200e+00, 2.70957600e+00, 2.60578300e+00, 2.61201700e+00, 2.77693500e+00, 2.92133500e+00, 3.20136800e+00, 4.28205800e+00, 6.35494800e+00, 9.78675300e+00, 2.59282200e+01, 5.98686600e+01, 1.36090400e+02, 2.65716000e+02, 4.54632500e+02, 7.19331100e+02, 1.08114800e+03, 1.53689800e+03, 2.07953200e+03, 2.86556900e+03, 3.58402700e+03, 4.21295300e+03, 5.88381000e+03, 7.98628100e+03, 1.08544100e+04, 1.38123800e+04, 1.59909200e+04, 1.75331700e+04, 1.89236600e+04, 2.07739600e+04, 2.25048600e+04, 2.40088100e+04, 2.52901300e+04, 2.63525000e+04, 2.71989100e+04]) self["P"] = numpy.array([ 5.00000000e-03, 1.31000000e-02, 3.04000000e-02, 6.44000000e-02, 1.26300000e-01, 2.32400000e-01, 4.05200000e-01, 6.74900000e-01, 1.08010000e+00, 1.66910000e+00, 2.50110000e+00, 3.64620000e+00, 5.18640000e+00, 7.21500000e+00, 9.83680000e+00, 1.31672000e+01, 1.73308000e+01, 2.24601000e+01, 2.86937000e+01, 3.61735000e+01, 4.50430000e+01, 5.54433000e+01, 6.75109000e+01, 8.13744000e+01, 9.71505000e+01, 1.14941500e+02, 1.34831800e+02, 1.56884600e+02, 1.81139400e+02, 2.07609200e+02, 2.36278400e+02, 2.67101200e+02, 3.00000000e+02, 3.34864800e+02, 3.71552900e+02, 4.09889300e+02, 4.49667700e+02, 4.90651600e+02, 5.32576900e+02, 5.75153800e+02, 6.18070600e+02, 6.60996500e+02, 7.03586300e+02, 7.45484100e+02, 7.86327800e+02, 8.25754600e+02, 8.63404700e+02, 8.98927500e+02, 9.31985300e+02, 9.62258700e+02, 9.89451000e+02, 1.01329200e+03, 1.03354400e+03, 1.05000000e+03]) self["CO2"] = numpy.array([ 395.418 , 398.4053, 399.9986, 399.9981, 399.9978, 399.9976, 399.9976, 399.9976, 399.9976, 399.9977, 399.9978, 399.998 , 399.9981, 399.9982, 399.9983, 399.9984, 399.9986, 399.9986, 399.9987, 399.9988, 399.9989, 399.999 , 399.999 , 399.9989, 399.9988, 399.9987, 399.9983, 399.9975, 399.9961, 399.9896, 399.9761, 399.9456, 399.8937, 399.8181, 399.7123, 399.5675, 399.3852, 399.1682, 398.8538, 398.5664, 398.3148, 397.6465, 396.8055, 395.6582, 394.475 , 393.6036, 392.9867, 392.4305, 391.6904, 390.9981, 390.3965, 389.8839, 389.459 , 389.1204]) self["CO"] = numpy.array([ 3.528118 , 1.349907 , 0.4957254 , 0.1792917 , 0.09047629, 0.0705162 , 0.0616322 , 0.05426952, 0.04624126, 0.0391566 , 0.03348209, 0.02905616, 0.02593781, 0.0237077 , 0.02157511, 0.0193842 , 0.01734686, 0.01592859, 0.01434816, 0.01291119, 0.01231997, 0.01319532, 0.01582421, 0.02059935, 0.02612786, 0.03244591, 0.04078717, 0.05074451, 0.06332459, 0.07579109, 0.08618882, 0.0949532 , 0.1029296 , 0.1105079 , 0.117288 , 0.1221284 , 0.1257701 , 0.1284458 , 0.1293593 , 0.1300385 , 0.1304752 , 0.1317349 , 0.1333378 , 0.1351774 , 0.1369916 , 0.1387643 , 0.1404729 , 0.1420133 , 0.143299 , 0.1444181 , 0.1453904 , 0.1462188 , 0.1469057 , 0.1474529 ]) self["T"] = numpy.array([ 178.1742, 188.2529, 205.1321, 221.334 , 237.077 , 252.3965, 261.5169, 267.6492, 269.7398, 263.9926, 257.2797, 251.061 , 245.3975, 240.2603, 235.5384, 231.2017, 227.2464, 223.4022, 219.8331, 216.4919, 212.2492, 207.1632, 202.3874, 198.0815, 195.2696, 198.3492, 204.5386, 210.5458, 216.794 , 222.5243, 228.1523, 233.7824, 239.2519, 244.4527, 249.4698, 254.3639, 259.0342, 263.4607, 267.7589, 271.8353, 275.7137, 279.3804, 282.8149, 285.1086, 286.9082, 289.0168, 291.3232, 293.4089, 295.3068, 296.9916, 298.4603, 299.7152, 300.7582, 301.5907]) self["N2O"] = numpy.array([ 0.00059029, 0.00074285, 0.00093966, 0.00119995, 0.00154214, 0.00204203, 0.00282904, 0.00409476, 0.00829992, 0.01764426, 0.03442835, 0.05677873, 0.08176396, 0.1052391 , 0.1265469 , 0.1451637 , 0.1579998 , 0.1695929 , 0.184075 , 0.1984777 , 0.2137192 , 0.2345192 , 0.2538536 , 0.269111 , 0.2803055 , 0.2890483 , 0.2950976 , 0.3000778 , 0.3046464 , 0.308726 , 0.3126328 , 0.3160383 , 0.3183613 , 0.3194183 , 0.3197079 , 0.319654 , 0.3195082 , 0.3193345 , 0.319083 , 0.3188531 , 0.3186519 , 0.3181172 , 0.3174444 , 0.3165266 , 0.31558 , 0.3148829 , 0.3143894 , 0.3139444 , 0.3133523 , 0.3127984 , 0.3123172 , 0.3119072 , 0.3115672 , 0.3112963 ]) self["O3"] = numpy.array([ 0.4762823 , 0.2995325 , 0.2033826 , 0.349818 , 0.6783378 , 1.08148 , 1.672011 , 2.424862 , 3.298506 , 4.709292 , 6.528208 , 8.194625 , 9.317032 , 9.778838 , 9.629797 , 8.989128 , 7.869709 , 6.25806 , 4.616532 , 3.188293 , 2.038327 , 1.446316 , 0.9139276 , 0.4550941 , 0.2274603 , 0.1406136 , 0.122982 , 0.1045551 , 0.09326144, 0.08055027, 0.06972766, 0.06068888, 0.05390553, 0.04930434, 0.04533284, 0.04315905, 0.041445 , 0.03985632, 0.03840163, 0.03706463, 0.0358538 , 0.03519916, 0.03483486, 0.03409536, 0.03327463, 0.03247094, 0.03169494, 0.03099529, 0.03010872, 0.02928422, 0.02856783, 0.02795748, 0.02745144, 0.02704826]) self["CH4"] = numpy.array([ 0.1649998, 0.1649996, 0.1649994, 0.1649992, 0.1649991, 0.164999 , 0.1785722, 0.2124714, 0.2877765, 0.4155745, 0.5517654, 0.6777804, 0.7811892, 0.8691873, 0.9498073, 1.021687 , 1.081942 , 1.133753 , 1.209854 , 1.328958 , 1.45423 , 1.557607 , 1.631611 , 1.679418 , 1.715104 , 1.745289 , 1.768428 , 1.789355 , 1.80884 , 1.825105 , 1.838105 , 1.848119 , 1.856009 , 1.862013 , 1.864812 , 1.866015 , 1.866366 , 1.866088 , 1.864641 , 1.863298 , 1.862122 , 1.858997 , 1.855066 , 1.849702 , 1.844171 , 1.840097 , 1.837213 , 1.834613 , 1.831153 , 1.827916 , 1.825104 , 1.822707 , 1.820721 , 1.819138 ]) self["CTP"] = 949.0 self["CFRACTION"] = 0.6 self["IDG"] = 1 self["ISH"] = 1 self["ELEVATION"] = 0.0 self["S2M"]["T"] = 298.7 self["S2M"]["Q"] = 24323.6123443 self["S2M"]["O"] = 0.0279921555618 self["S2M"]["P"] = 950.0 self["S2M"]["U"] = 5.0 self["S2M"]["V"] = 2.0 self["S2M"]["WFETC"] = 100000.0 self["SKIN"]["SURFTYPE"] = 1 self["SKIN"]["WATERTYPE"] = 0 self["SKIN"]["T"] = 302.0 self["SKIN"]["SALINITY"] = 35.0 self["SKIN"]["FOAM_FRACTION"] = 0.0 self["SKIN"]["FASTEM"] = numpy.array([ 3. , 5. , 15. , 0.1, 0.3]) self["ZENANGLE"] = 45.0 self["AZANGLE"] = 0.0 self["SUNZENANGLE"] = 40.0 self["SUNAZANGLE"] = 179.0 self["LATITUDE"] = 15.0 self["GAS_UNITS"] = 2 self["BE"] = 0.2 self["COSBK"] = 0.0 self["DATE"] = numpy.array([1949, 1, 1]) self["TIME"] = numpy.array([0, 0, 0])
""" Profile ../profile-datasets-py/standard54lev_allgas_seaonly/001.py file automaticaly created by prof_gen.py script """ self['ID'] = '../profile-datasets-py/standard54lev_allgas_seaonly/001.py' self['Q'] = numpy.array([1.411607, 2.343729, 3.533821, 4.628086, 5.437759, 5.97528, 5.999964, 5.999964, 5.923269, 5.670065, 5.382175, 5.039667, 4.727619, 4.442217, 4.179894, 3.917095, 3.618584, 3.375125, 3.214378, 2.878822, 2.709576, 2.605783, 2.612017, 2.776935, 2.921335, 3.201368, 4.282058, 6.354948, 9.786753, 25.92822, 59.86866, 136.0904, 265.716, 454.6325, 719.3311, 1081.148, 1536.898, 2079.532, 2865.569, 3584.027, 4212.953, 5883.81, 7986.281, 10854.41, 13812.38, 15990.92, 17533.17, 18923.66, 20773.96, 22504.86, 24008.81, 25290.13, 26352.5, 27198.91]) self['P'] = numpy.array([0.005, 0.0131, 0.0304, 0.0644, 0.1263, 0.2324, 0.4052, 0.6749, 1.0801, 1.6691, 2.5011, 3.6462, 5.1864, 7.215, 9.8368, 13.1672, 17.3308, 22.4601, 28.6937, 36.1735, 45.043, 55.4433, 67.5109, 81.3744, 97.1505, 114.9415, 134.8318, 156.8846, 181.1394, 207.6092, 236.2784, 267.1012, 300.0, 334.8648, 371.5529, 409.8893, 449.6677, 490.6516, 532.5769, 575.1538, 618.0706, 660.9965, 703.5863, 745.4841, 786.3278, 825.7546, 863.4047, 898.9275, 931.9853, 962.2587, 989.451, 1013.292, 1033.544, 1050.0]) self['CO2'] = numpy.array([395.418, 398.4053, 399.9986, 399.9981, 399.9978, 399.9976, 399.9976, 399.9976, 399.9976, 399.9977, 399.9978, 399.998, 399.9981, 399.9982, 399.9983, 399.9984, 399.9986, 399.9986, 399.9987, 399.9988, 399.9989, 399.999, 399.999, 399.9989, 399.9988, 399.9987, 399.9983, 399.9975, 399.9961, 399.9896, 399.9761, 399.9456, 399.8937, 399.8181, 399.7123, 399.5675, 399.3852, 399.1682, 398.8538, 398.5664, 398.3148, 397.6465, 396.8055, 395.6582, 394.475, 393.6036, 392.9867, 392.4305, 391.6904, 390.9981, 390.3965, 389.8839, 389.459, 389.1204]) self['CO'] = numpy.array([3.528118, 1.349907, 0.4957254, 0.1792917, 0.09047629, 0.0705162, 0.0616322, 0.05426952, 0.04624126, 0.0391566, 0.03348209, 0.02905616, 0.02593781, 0.0237077, 0.02157511, 0.0193842, 0.01734686, 0.01592859, 0.01434816, 0.01291119, 0.01231997, 0.01319532, 0.01582421, 0.02059935, 0.02612786, 0.03244591, 0.04078717, 0.05074451, 0.06332459, 0.07579109, 0.08618882, 0.0949532, 0.1029296, 0.1105079, 0.117288, 0.1221284, 0.1257701, 0.1284458, 0.1293593, 0.1300385, 0.1304752, 0.1317349, 0.1333378, 0.1351774, 0.1369916, 0.1387643, 0.1404729, 0.1420133, 0.143299, 0.1444181, 0.1453904, 0.1462188, 0.1469057, 0.1474529]) self['T'] = numpy.array([178.1742, 188.2529, 205.1321, 221.334, 237.077, 252.3965, 261.5169, 267.6492, 269.7398, 263.9926, 257.2797, 251.061, 245.3975, 240.2603, 235.5384, 231.2017, 227.2464, 223.4022, 219.8331, 216.4919, 212.2492, 207.1632, 202.3874, 198.0815, 195.2696, 198.3492, 204.5386, 210.5458, 216.794, 222.5243, 228.1523, 233.7824, 239.2519, 244.4527, 249.4698, 254.3639, 259.0342, 263.4607, 267.7589, 271.8353, 275.7137, 279.3804, 282.8149, 285.1086, 286.9082, 289.0168, 291.3232, 293.4089, 295.3068, 296.9916, 298.4603, 299.7152, 300.7582, 301.5907]) self['N2O'] = numpy.array([0.00059029, 0.00074285, 0.00093966, 0.00119995, 0.00154214, 0.00204203, 0.00282904, 0.00409476, 0.00829992, 0.01764426, 0.03442835, 0.05677873, 0.08176396, 0.1052391, 0.1265469, 0.1451637, 0.1579998, 0.1695929, 0.184075, 0.1984777, 0.2137192, 0.2345192, 0.2538536, 0.269111, 0.2803055, 0.2890483, 0.2950976, 0.3000778, 0.3046464, 0.308726, 0.3126328, 0.3160383, 0.3183613, 0.3194183, 0.3197079, 0.319654, 0.3195082, 0.3193345, 0.319083, 0.3188531, 0.3186519, 0.3181172, 0.3174444, 0.3165266, 0.31558, 0.3148829, 0.3143894, 0.3139444, 0.3133523, 0.3127984, 0.3123172, 0.3119072, 0.3115672, 0.3112963]) self['O3'] = numpy.array([0.4762823, 0.2995325, 0.2033826, 0.349818, 0.6783378, 1.08148, 1.672011, 2.424862, 3.298506, 4.709292, 6.528208, 8.194625, 9.317032, 9.778838, 9.629797, 8.989128, 7.869709, 6.25806, 4.616532, 3.188293, 2.038327, 1.446316, 0.9139276, 0.4550941, 0.2274603, 0.1406136, 0.122982, 0.1045551, 0.09326144, 0.08055027, 0.06972766, 0.06068888, 0.05390553, 0.04930434, 0.04533284, 0.04315905, 0.041445, 0.03985632, 0.03840163, 0.03706463, 0.0358538, 0.03519916, 0.03483486, 0.03409536, 0.03327463, 0.03247094, 0.03169494, 0.03099529, 0.03010872, 0.02928422, 0.02856783, 0.02795748, 0.02745144, 0.02704826]) self['CH4'] = numpy.array([0.1649998, 0.1649996, 0.1649994, 0.1649992, 0.1649991, 0.164999, 0.1785722, 0.2124714, 0.2877765, 0.4155745, 0.5517654, 0.6777804, 0.7811892, 0.8691873, 0.9498073, 1.021687, 1.081942, 1.133753, 1.209854, 1.328958, 1.45423, 1.557607, 1.631611, 1.679418, 1.715104, 1.745289, 1.768428, 1.789355, 1.80884, 1.825105, 1.838105, 1.848119, 1.856009, 1.862013, 1.864812, 1.866015, 1.866366, 1.866088, 1.864641, 1.863298, 1.862122, 1.858997, 1.855066, 1.849702, 1.844171, 1.840097, 1.837213, 1.834613, 1.831153, 1.827916, 1.825104, 1.822707, 1.820721, 1.819138]) self['CTP'] = 949.0 self['CFRACTION'] = 0.6 self['IDG'] = 1 self['ISH'] = 1 self['ELEVATION'] = 0.0 self['S2M']['T'] = 298.7 self['S2M']['Q'] = 24323.6123443 self['S2M']['O'] = 0.0279921555618 self['S2M']['P'] = 950.0 self['S2M']['U'] = 5.0 self['S2M']['V'] = 2.0 self['S2M']['WFETC'] = 100000.0 self['SKIN']['SURFTYPE'] = 1 self['SKIN']['WATERTYPE'] = 0 self['SKIN']['T'] = 302.0 self['SKIN']['SALINITY'] = 35.0 self['SKIN']['FOAM_FRACTION'] = 0.0 self['SKIN']['FASTEM'] = numpy.array([3.0, 5.0, 15.0, 0.1, 0.3]) self['ZENANGLE'] = 45.0 self['AZANGLE'] = 0.0 self['SUNZENANGLE'] = 40.0 self['SUNAZANGLE'] = 179.0 self['LATITUDE'] = 15.0 self['GAS_UNITS'] = 2 self['BE'] = 0.2 self['COSBK'] = 0.0 self['DATE'] = numpy.array([1949, 1, 1]) self['TIME'] = numpy.array([0, 0, 0])
dadosPessoas = [] dadoTemporario = [] c = maiorPeso = menorPeso = 0 while True: dadoTemporario.append(str(input('Nome: '))) dadoTemporario.append(float(input('Peso(KG): '))) dadosPessoas.append(dadoTemporario[:]) if c == 0: # Posso usar len(dadoTemporario) para fazer o contador maiorPeso = dadoTemporario[1] menorPeso = dadoTemporario[1] if dadoTemporario[1] > maiorPeso: maiorPeso = dadoTemporario[1] if dadoTemporario[1] < menorPeso: menorPeso = dadoTemporario[1] dadoTemporario.clear() c += 1 r = str(input('Quer continuar [S/N]: ')).upper().strip()[0] if r == 'N': break print('=' * 50) print(f'Foram cadastradas {c} pessoas.') # len(dadosPessoas) pode ser usado no lugar de Contador print(f'O maior peso foi {maiorPeso} KG. Peso de', end=' ') for c, p in enumerate(dadosPessoas): if p[1] == maiorPeso: print(f'{p[0]}...', end=' ') print() print(f'O menor peso foi {menorPeso} KG. Peso de', end=' ') for c, p in enumerate(dadosPessoas): if p[1] == menorPeso: print(f'{p[0]}...', end=' ') print()
dados_pessoas = [] dado_temporario = [] c = maior_peso = menor_peso = 0 while True: dadoTemporario.append(str(input('Nome: '))) dadoTemporario.append(float(input('Peso(KG): '))) dadosPessoas.append(dadoTemporario[:]) if c == 0: maior_peso = dadoTemporario[1] menor_peso = dadoTemporario[1] if dadoTemporario[1] > maiorPeso: maior_peso = dadoTemporario[1] if dadoTemporario[1] < menorPeso: menor_peso = dadoTemporario[1] dadoTemporario.clear() c += 1 r = str(input('Quer continuar [S/N]: ')).upper().strip()[0] if r == 'N': break print('=' * 50) print(f'Foram cadastradas {c} pessoas.') print(f'O maior peso foi {maiorPeso} KG. Peso de', end=' ') for (c, p) in enumerate(dadosPessoas): if p[1] == maiorPeso: print(f'{p[0]}...', end=' ') print() print(f'O menor peso foi {menorPeso} KG. Peso de', end=' ') for (c, p) in enumerate(dadosPessoas): if p[1] == menorPeso: print(f'{p[0]}...', end=' ') print()
string = input() results = [] for i, char in enumerate(string): if i != 0 and char.isupper(): results.append('_') results.append(char.lower()) print("".join(results))
string = input() results = [] for (i, char) in enumerate(string): if i != 0 and char.isupper(): results.append('_') results.append(char.lower()) print(''.join(results))
#!/usr/bin/env python # Copyright Contributors to the Open Shading Language project. # SPDX-License-Identifier: BSD-3-Clause # https://github.com/imageworks/OpenShadingLanguage command = testshade("--groupoutputs -od half -o a a.exr -o b b.exr -o c c.exr -g 64 64 test") outputs = [ "a.exr", "b.exr", "c.exr", "out.txt" ]
command = testshade('--groupoutputs -od half -o a a.exr -o b b.exr -o c c.exr -g 64 64 test') outputs = ['a.exr', 'b.exr', 'c.exr', 'out.txt']
def AssignFare(c,a,d): if d<500: t_fare=(a*200)+(c*(200/2)) elif (d<1000) and (d>=500): t_fare=(a*300)+(c*(300/2)) else: t_fare=(a*500)+(c*(500/2)) return t_fare child=int(input("enter the number of children: ")) adult=int(input("enter the number of adults: ")) distance=float(input("enter he distance travelled: ")) trip_fare=AssignFare(child,adult,distance) print(trip_fare)
def assign_fare(c, a, d): if d < 500: t_fare = a * 200 + c * (200 / 2) elif d < 1000 and d >= 500: t_fare = a * 300 + c * (300 / 2) else: t_fare = a * 500 + c * (500 / 2) return t_fare child = int(input('enter the number of children: ')) adult = int(input('enter the number of adults: ')) distance = float(input('enter he distance travelled: ')) trip_fare = assign_fare(child, adult, distance) print(trip_fare)
def insertion_sort(array): #function to sort array using insertion sort comparison=0 shift=0 for i in range(1,len(array)): j=i-1 val=array[i] while(j>=0 and val<array[j]): shift+=1 comparison+=1 array[j+1]=array[j] array[j]=val j-=1 comparison+=1 print("Array after ",i+1,"th pass is : ",array) print("Array after sorting is : ",array) print(shift," number of shift and",comparison," comparisons") def input_array(): #function for taking input of array attended=[] number_of_attendee=int(input("Enter total : ")) for i in range(number_of_attendee): tep=int(input("Enter number :")) attended.append(tep) return attended if __name__ == '__main__': arr=input_array() insertion_sort(arr) print("Array after sorting using selection sort : ",arr)
def insertion_sort(array): comparison = 0 shift = 0 for i in range(1, len(array)): j = i - 1 val = array[i] while j >= 0 and val < array[j]: shift += 1 comparison += 1 array[j + 1] = array[j] array[j] = val j -= 1 comparison += 1 print('Array after ', i + 1, 'th pass is : ', array) print('Array after sorting is : ', array) print(shift, ' number of shift and', comparison, ' comparisons') def input_array(): attended = [] number_of_attendee = int(input('Enter total : ')) for i in range(number_of_attendee): tep = int(input('Enter number :')) attended.append(tep) return attended if __name__ == '__main__': arr = input_array() insertion_sort(arr) print('Array after sorting using selection sort : ', arr)
# Some more if statements banned_users = ['andrew','carolina','david'] user = 'marie' if user not in banned_users: print(user.title()+", you can post a response if you wish.") car = 'subaru' print("Is car == 'subaru'? I predict True") print(car == 'subaru') print("Is car == 'audi'? I predict false") print(car == 'audi') # Simple if statements age = 20 if age >= 18: print("you are old enough to vote.") # Input age = 17 if age >= 18: print("you are old enough to vote!") print("Have you registered to vote yet!") else: print("Sorry, you are too young to vote.") print("Please register to vote as soon as you turn 18!") # the if-elif-else chain statement age = 12 if age < 4: print("Fees is 0$") elif age < 18: print("Fees is $5") else: print("you admission cost is 10$") # some more elif age = 12 if age <= 14: price = 0 elif age <= 18: price = 5 elif age <= 65: price = 10 else: price = 5 print("Your ticket price is--"+str(price)) # Dictionaries alien_0 = {'color':'green','points':5} print(alien_0) print(alien_0['color']) print(alien_0['points']) alien_0['david'] = 24 alien_0['carolina'] = 30 print(alien_0) alien_0['ankit'] = 23 print(alien_0) # Starting with an empty dictionary alien_1 = {} alien_2 = {'color':'age'} alien_2
banned_users = ['andrew', 'carolina', 'david'] user = 'marie' if user not in banned_users: print(user.title() + ', you can post a response if you wish.') car = 'subaru' print("Is car == 'subaru'? I predict True") print(car == 'subaru') print("Is car == 'audi'? I predict false") print(car == 'audi') age = 20 if age >= 18: print('you are old enough to vote.') age = 17 if age >= 18: print('you are old enough to vote!') print('Have you registered to vote yet!') else: print('Sorry, you are too young to vote.') print('Please register to vote as soon as you turn 18!') age = 12 if age < 4: print('Fees is 0$') elif age < 18: print('Fees is $5') else: print('you admission cost is 10$') age = 12 if age <= 14: price = 0 elif age <= 18: price = 5 elif age <= 65: price = 10 else: price = 5 print('Your ticket price is--' + str(price)) alien_0 = {'color': 'green', 'points': 5} print(alien_0) print(alien_0['color']) print(alien_0['points']) alien_0['david'] = 24 alien_0['carolina'] = 30 print(alien_0) alien_0['ankit'] = 23 print(alien_0) alien_1 = {} alien_2 = {'color': 'age'} alien_2
def extract_pos(doc, pos, return_list = True, lower_case = True): tokens = [t.text for t in doc if t.pos_ == pos] if lower_case == True: tokens = [t.lower() for t in tokens] if return_list == False: tokens = ', '.join(tokens) return tokens
def extract_pos(doc, pos, return_list=True, lower_case=True): tokens = [t.text for t in doc if t.pos_ == pos] if lower_case == True: tokens = [t.lower() for t in tokens] if return_list == False: tokens = ', '.join(tokens) return tokens
class Solution: def countBattleships(self, board): """ :type board: List[List[str]] :rtype: int """ return sum(val == 'X' for i, row in enumerate(board) for j, val in enumerate(row) if (j == 0 or board[i][j - 1] == '.') and (i == 0 or board[i - 1][j] == '.'))
class Solution: def count_battleships(self, board): """ :type board: List[List[str]] :rtype: int """ return sum((val == 'X' for (i, row) in enumerate(board) for (j, val) in enumerate(row) if (j == 0 or board[i][j - 1] == '.') and (i == 0 or board[i - 1][j] == '.')))
class Queue: def __init__(self): self.items=[] def enqueue(self,item): self.items.append(item) def dequeue(self): return self.items.pop(0) def is_empty(self): if self.items==[]: return True return False if __name__=="__main__": q=Queue() q.enqueue("Mitul") q.enqueue("Shahriyar") q.enqueue("3737") while not q.is_empty(): person = q.dequeue() print(person)
class Queue: def __init__(self): self.items = [] def enqueue(self, item): self.items.append(item) def dequeue(self): return self.items.pop(0) def is_empty(self): if self.items == []: return True return False if __name__ == '__main__': q = queue() q.enqueue('Mitul') q.enqueue('Shahriyar') q.enqueue('3737') while not q.is_empty(): person = q.dequeue() print(person)
class Point3f( object, IEquatable[Point3f], IComparable[Point3f], IComparable, IEpsilonFComparable[Point3f], ): """ Represents the three coordinates of a point in three-dimensional space, using System.Single-precision floating point numbers. Point3f(x: Single,y: Single,z: Single) """ def CompareTo(self, other): """ CompareTo(self: Point3f,other: Point3f) -> int Compares this Rhino.Geometry.Point3f with another Rhino.Geometry.Point3f. Component evaluation priority is first X,then Y,then Z. other: The other Rhino.Geometry.Point3d to use in comparison. Returns: 0: if this is identical to other-1: if this.X < other.X-1: if this.X == other.X and this.Y < other.Y-1: if this.X == other.X and this.Y == other.Y and this.Z < other.Z+1: otherwise. """ pass def DistanceTo(self, other): """ DistanceTo(self: Point3f,other: Point3f) -> float Computes the distance between two points. other: Other point for distance measurement. Returns: The length of the line between this and the other point; or 0 if any of the points is not valid. """ pass def EpsilonEquals(self, other, epsilon): """ EpsilonEquals(self: Point3f,other: Point3f,epsilon: Single) -> bool Check that all values in other are withing epsilon of the values in this """ pass def Equals(self, *__args): """ Equals(self: Point3f,point: Point3f) -> bool Determines whether the specified Point3f has the same values as the present point. point: The specified point. Returns: true if point has the same coordinates as this; otherwise false. Equals(self: Point3f,obj: object) -> bool Determines whether the specified System.Object is a Point3f and has the same values as the present point. obj: The specified object. Returns: true if obj is Point3f and has the same coordinates as this; otherwise false. """ pass def GetHashCode(self): """ GetHashCode(self: Point3f) -> int Computes a hash code for the present point. Returns: A non-unique integer that represents this point. """ pass @staticmethod def Subtract(point1, point2): """ Subtract(point1: Point3f,point2: Point3f) -> Vector3f Subtracts a point from another point. (Provided for languages that do not support operator overloading. You can use the - operator otherwise) point1: A point. point2: Another point. Returns: A new vector that is the difference of point minus vector. """ pass def ToString(self): """ ToString(self: Point3f) -> str Constructs the string representation for the current point. Returns: The point representation in the form X,Y,Z. """ pass def Transform(self, xform): """ Transform(self: Point3f,xform: Transform) Transforms the present point in place. The transformation matrix acts on the left of the point. i.e., result=transformation*point xform: Transformation to apply. """ pass def __eq__(self, *args): """ x.__eq__(y) <==> x==y """ pass def __ge__(self, *args): pass def __gt__(self, *args): pass def __init__(self, *args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __le__(self, *args): pass def __lt__(self, *args): pass @staticmethod def __new__(self, x, y, z): """ __new__[Point3f]() -> Point3f __new__(cls: type,x: Single,y: Single,z: Single) """ pass def __ne__(self, *args): pass def __reduce_ex__(self, *args): pass def __repr__(self, *args): """ __repr__(self: object) -> str """ pass def __rsub__(self, *args): """ __rsub__(point1: Point3f,point2: Point3f) -> Vector3f Subtracts a point from another point. point1: A point. point2: Another point. Returns: A new vector that is the difference of point minus vector. """ pass def __str__(self, *args): pass def __sub__(self, *args): """ x.__sub__(y) <==> x-y """ pass IsValid = property(lambda self: object(), lambda self, v: None, lambda self: None) """Each coordinate of the point must pass the Rhino.RhinoMath.IsValidSingle(System.Single) test. Get: IsValid(self: Point3f) -> bool """ X = property(lambda self: object(), lambda self, v: None, lambda self: None) """Gets or sets the X (first) component of the vector. Get: X(self: Point3f) -> Single Set: X(self: Point3f)=value """ Y = property(lambda self: object(), lambda self, v: None, lambda self: None) """Gets or sets the Y (second) component of the vector. Get: Y(self: Point3f) -> Single Set: Y(self: Point3f)=value """ Z = property(lambda self: object(), lambda self, v: None, lambda self: None) """Gets or sets the Z (third) component of the vector. Get: Z(self: Point3f) -> Single Set: Z(self: Point3f)=value """ Origin = None Unset = None
class Point3F(object, IEquatable[Point3f], IComparable[Point3f], IComparable, IEpsilonFComparable[Point3f]): """ Represents the three coordinates of a point in three-dimensional space, using System.Single-precision floating point numbers. Point3f(x: Single,y: Single,z: Single) """ def compare_to(self, other): """ CompareTo(self: Point3f,other: Point3f) -> int Compares this Rhino.Geometry.Point3f with another Rhino.Geometry.Point3f. Component evaluation priority is first X,then Y,then Z. other: The other Rhino.Geometry.Point3d to use in comparison. Returns: 0: if this is identical to other-1: if this.X < other.X-1: if this.X == other.X and this.Y < other.Y-1: if this.X == other.X and this.Y == other.Y and this.Z < other.Z+1: otherwise. """ pass def distance_to(self, other): """ DistanceTo(self: Point3f,other: Point3f) -> float Computes the distance between two points. other: Other point for distance measurement. Returns: The length of the line between this and the other point; or 0 if any of the points is not valid. """ pass def epsilon_equals(self, other, epsilon): """ EpsilonEquals(self: Point3f,other: Point3f,epsilon: Single) -> bool Check that all values in other are withing epsilon of the values in this """ pass def equals(self, *__args): """ Equals(self: Point3f,point: Point3f) -> bool Determines whether the specified Point3f has the same values as the present point. point: The specified point. Returns: true if point has the same coordinates as this; otherwise false. Equals(self: Point3f,obj: object) -> bool Determines whether the specified System.Object is a Point3f and has the same values as the present point. obj: The specified object. Returns: true if obj is Point3f and has the same coordinates as this; otherwise false. """ pass def get_hash_code(self): """ GetHashCode(self: Point3f) -> int Computes a hash code for the present point. Returns: A non-unique integer that represents this point. """ pass @staticmethod def subtract(point1, point2): """ Subtract(point1: Point3f,point2: Point3f) -> Vector3f Subtracts a point from another point. (Provided for languages that do not support operator overloading. You can use the - operator otherwise) point1: A point. point2: Another point. Returns: A new vector that is the difference of point minus vector. """ pass def to_string(self): """ ToString(self: Point3f) -> str Constructs the string representation for the current point. Returns: The point representation in the form X,Y,Z. """ pass def transform(self, xform): """ Transform(self: Point3f,xform: Transform) Transforms the present point in place. The transformation matrix acts on the left of the point. i.e., result=transformation*point xform: Transformation to apply. """ pass def __eq__(self, *args): """ x.__eq__(y) <==> x==y """ pass def __ge__(self, *args): pass def __gt__(self, *args): pass def __init__(self, *args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __le__(self, *args): pass def __lt__(self, *args): pass @staticmethod def __new__(self, x, y, z): """ __new__[Point3f]() -> Point3f __new__(cls: type,x: Single,y: Single,z: Single) """ pass def __ne__(self, *args): pass def __reduce_ex__(self, *args): pass def __repr__(self, *args): """ __repr__(self: object) -> str """ pass def __rsub__(self, *args): """ __rsub__(point1: Point3f,point2: Point3f) -> Vector3f Subtracts a point from another point. point1: A point. point2: Another point. Returns: A new vector that is the difference of point minus vector. """ pass def __str__(self, *args): pass def __sub__(self, *args): """ x.__sub__(y) <==> x-y """ pass is_valid = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Each coordinate of the point must pass the Rhino.RhinoMath.IsValidSingle(System.Single) test.\n\n\n\nGet: IsValid(self: Point3f) -> bool\n\n\n\n' x = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Gets or sets the X (first) component of the vector.\n\n\n\nGet: X(self: Point3f) -> Single\n\n\n\nSet: X(self: Point3f)=value\n\n' y = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Gets or sets the Y (second) component of the vector.\n\n\n\nGet: Y(self: Point3f) -> Single\n\n\n\nSet: Y(self: Point3f)=value\n\n' z = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Gets or sets the Z (third) component of the vector.\n\n\n\nGet: Z(self: Point3f) -> Single\n\n\n\nSet: Z(self: Point3f)=value\n\n' origin = None unset = None
#kaynak https://randomnerdtutorials.com/micropython-esp32-esp8266-access-point-ap/ def web_page(): html = """<html><head><meta name="viewport" content="width=device-width, initial-scale=1"></head> <body><h1>Hello, World!</h1></body></html>""" return html s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 80)) s.listen(5) while True: conn, addr = s.accept() print('Got a connection from %s' % str(addr)) request = conn.recv(1024) print('Content = %s' % str(request)) response = web_page() conn.send(response) conn.close()
def web_page(): html = '<html><head><meta name="viewport" content="width=device-width, initial-scale=1"></head>\n <body><h1>Hello, World!</h1></body></html>' return html s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 80)) s.listen(5) while True: (conn, addr) = s.accept() print('Got a connection from %s' % str(addr)) request = conn.recv(1024) print('Content = %s' % str(request)) response = web_page() conn.send(response) conn.close()
async def execute(client, **kwargs): print("Please wait...") await client.logout() print("Client sucsessfully logged out") return 1 if __name__ == "__main__": pass
async def execute(client, **kwargs): print('Please wait...') await client.logout() print('Client sucsessfully logged out') return 1 if __name__ == '__main__': pass
""" Localisation Settings to conduct Localisation by Clustering before CAE training and DA. """ class LoaderSetting(): def __init__(self, data, pickle, percentage, dim, domain, otherDomain): self.DATA_FP = data self.X_PICKLE = pickle self.PERCENTAGE = percentage self.DIM = dim self.CLUSTERING = True self.CLIC_UNSTRUCTURED = False self.MIN_DIM = 1024 self.THIS_DOMAIN = domain self.OTHER_DOMAINS = otherDomain self.OVERLAPPING_REGIONS = None self.IDX_MESH_TO_IDX_NETWORK = None self.IDX_MESH_TO_IDX_NETWORK_MATCH = None def getDataDir(self): return self.DATA_FP def getPercentOfVertices(self): return self.PERCENTAGE def getDim(self): return self.DIM def getMinDim(self): return self.MIN_DIM def getOtherSubdomainFP(self): path = self.DATA_FP pathDir, _ = path.split("subdomain_") if len(self.OTHER_DOMAINS) != 1: raise NotImplementedError("Not Implemented more than 2 subdomains in Big Data Assimilation") else: fp = pathDir + "subdomain_" + str(self.OTHER_DOMAINS[0]) + "/" fp = fp + "LSBU_0_" + str(self.OTHER_DOMAINS[0]) + ".vtu" return fp def setOverlappingRegions(self, indices): self.OVERLAPPING_REGIONS = indices def setIdxMeshToIdxNetwork(self, idxDict): self.IDX_MESH_TO_IDX_NETWORK = idxDict def setMatchIdxMeshToIdxNetwork(self, idxDict): self.IDX_MESH_TO_IDX_NETWORK_MATCH = idxDict
""" Localisation Settings to conduct Localisation by Clustering before CAE training and DA. """ class Loadersetting: def __init__(self, data, pickle, percentage, dim, domain, otherDomain): self.DATA_FP = data self.X_PICKLE = pickle self.PERCENTAGE = percentage self.DIM = dim self.CLUSTERING = True self.CLIC_UNSTRUCTURED = False self.MIN_DIM = 1024 self.THIS_DOMAIN = domain self.OTHER_DOMAINS = otherDomain self.OVERLAPPING_REGIONS = None self.IDX_MESH_TO_IDX_NETWORK = None self.IDX_MESH_TO_IDX_NETWORK_MATCH = None def get_data_dir(self): return self.DATA_FP def get_percent_of_vertices(self): return self.PERCENTAGE def get_dim(self): return self.DIM def get_min_dim(self): return self.MIN_DIM def get_other_subdomain_fp(self): path = self.DATA_FP (path_dir, _) = path.split('subdomain_') if len(self.OTHER_DOMAINS) != 1: raise not_implemented_error('Not Implemented more than 2 subdomains in Big Data Assimilation') else: fp = pathDir + 'subdomain_' + str(self.OTHER_DOMAINS[0]) + '/' fp = fp + 'LSBU_0_' + str(self.OTHER_DOMAINS[0]) + '.vtu' return fp def set_overlapping_regions(self, indices): self.OVERLAPPING_REGIONS = indices def set_idx_mesh_to_idx_network(self, idxDict): self.IDX_MESH_TO_IDX_NETWORK = idxDict def set_match_idx_mesh_to_idx_network(self, idxDict): self.IDX_MESH_TO_IDX_NETWORK_MATCH = idxDict
class Character: """Represents a single character""" def __init__(self, char, was_guessed=False): self.char = char self.was_guessed = was_guessed def get_char(self): """ Returns the char data""" return self.char def show_char(self): """ Returns the char data if the char was guessed or is a space Returns an underscore if otherwise """ if self.was_guessed or self.char == " ": return self.char else: return "_" def update_guess(self, guess): """ Updates the guess status to True if the guess matches the char """ if guess.lower() == self.char: self.was_guessed = True def reset_guessed(self): """ Resets the char's guess status to False""" self.was_guessed = False
class Character: """Represents a single character""" def __init__(self, char, was_guessed=False): self.char = char self.was_guessed = was_guessed def get_char(self): """ Returns the char data""" return self.char def show_char(self): """ Returns the char data if the char was guessed or is a space Returns an underscore if otherwise """ if self.was_guessed or self.char == ' ': return self.char else: return '_' def update_guess(self, guess): """ Updates the guess status to True if the guess matches the char """ if guess.lower() == self.char: self.was_guessed = True def reset_guessed(self): """ Resets the char's guess status to False""" self.was_guessed = False
suffix = "ack" praefixe = "JKLMNOPQ" for praefix in praefixe: if praefix == "O" or praefix == "Q": print(praefix + "u" + suffix) else: print(praefix + suffix)
suffix = 'ack' praefixe = 'JKLMNOPQ' for praefix in praefixe: if praefix == 'O' or praefix == 'Q': print(praefix + 'u' + suffix) else: print(praefix + suffix)
"""Constants for the Switcher integration.""" DOMAIN = "switcher_kis" CONF_DEVICE_PASSWORD = "device_password" CONF_PHONE_ID = "phone_id" DATA_DEVICE = "device" SIGNAL_SWITCHER_DEVICE_UPDATE = "switcher_device_update" ATTR_AUTO_OFF_SET = "auto_off_set" ATTR_ELECTRIC_CURRENT = "electric_current" ATTR_REMAINING_TIME = "remaining_time" CONF_AUTO_OFF = "auto_off" CONF_TIMER_MINUTES = "timer_minutes" SERVICE_SET_AUTO_OFF_NAME = "set_auto_off" SERVICE_TURN_ON_WITH_TIMER_NAME = "turn_on_with_timer"
"""Constants for the Switcher integration.""" domain = 'switcher_kis' conf_device_password = 'device_password' conf_phone_id = 'phone_id' data_device = 'device' signal_switcher_device_update = 'switcher_device_update' attr_auto_off_set = 'auto_off_set' attr_electric_current = 'electric_current' attr_remaining_time = 'remaining_time' conf_auto_off = 'auto_off' conf_timer_minutes = 'timer_minutes' service_set_auto_off_name = 'set_auto_off' service_turn_on_with_timer_name = 'turn_on_with_timer'
class UknownValueError(ValueError): """Raised when the provided value is unkown or is not in a specified list or dictionary map """ def __init__(self, provided_value=None, known_values=None): if provided_value and known_values: if isinstance(known_values, list): super().__init__("The provided value {} is unknown. Please provide one of the following values: '{}'".format( provided_value, ','.join([x for x in known_values]) )) else: pass
class Uknownvalueerror(ValueError): """Raised when the provided value is unkown or is not in a specified list or dictionary map """ def __init__(self, provided_value=None, known_values=None): if provided_value and known_values: if isinstance(known_values, list): super().__init__("The provided value {} is unknown. Please provide one of the following values: '{}'".format(provided_value, ','.join([x for x in known_values]))) else: pass
def fatorial(p1): f = 1 indice = p1 while indice >= 1: f *= indice indice -= 1 return f def dobro(p1): return p1 * 2 def triplo(p1): return p1 * 3
def fatorial(p1): f = 1 indice = p1 while indice >= 1: f *= indice indice -= 1 return f def dobro(p1): return p1 * 2 def triplo(p1): return p1 * 3
# This program says hello world and asks for my name. print('Hello, world!') print('what is your name?') # ask for the name my_Name = input() print('It is nice to meet you, '+ my_Name) print('The length of your name is:') print(len(my_Name)) print(len(' ')) print('What is your age?') # ask for the age my_Age = input() print('You will be ' + str(int(my_Age) + 1) + ' in a year')
print('Hello, world!') print('what is your name?') my__name = input() print('It is nice to meet you, ' + my_Name) print('The length of your name is:') print(len(my_Name)) print(len(' ')) print('What is your age?') my__age = input() print('You will be ' + str(int(my_Age) + 1) + ' in a year')
class Failsafe: ''' Catches I/O errors. ''' def __init__(self, func): self.function = func def __call__(self, *args): try: self.function(*args) except IOError: print('An I/O error was caught when opening file "{}"'.format(args[0])) @Failsafe def risky_fileopen(filename): open(filename) print('SUCCESS:', filename) risky_fileopen('failsafe.py') risky_fileopen('doesnotexist')
class Failsafe: """ Catches I/O errors. """ def __init__(self, func): self.function = func def __call__(self, *args): try: self.function(*args) except IOError: print('An I/O error was caught when opening file "{}"'.format(args[0])) @Failsafe def risky_fileopen(filename): open(filename) print('SUCCESS:', filename) risky_fileopen('failsafe.py') risky_fileopen('doesnotexist')
# TIMEBOMB: report me a = 1 # TIMEBOMB (jsmith): report me # TIMEBOMB: do not report me (pragma). # no-check-fixmes # TIMEBOMB(jsmith - 2020-04-25): report me a = "TIMEBOMB" # do not report me (within a string) a = "TIMEBOMB" # do not report me (within a string) # TIMEBOMB - FEWTURE-BOOM: report me
a = 1 a = 'TIMEBOMB' a = 'TIMEBOMB'
class Store: # Here will be the instance stored. __instance = None @staticmethod def getInstance(): """ Static access method. """ if Store.__instance == None: Store() return Store.__instance def __init__(self): """ Virtually private constructor. """ if Store.__instance != None: raise Exception("This class is a singleton!") else: Store.__instance = self self.todos = []
class Store: __instance = None @staticmethod def get_instance(): """ Static access method. """ if Store.__instance == None: store() return Store.__instance def __init__(self): """ Virtually private constructor. """ if Store.__instance != None: raise exception('This class is a singleton!') else: Store.__instance = self self.todos = []
class Node: def __init__(self, x: int, next: "Node" = None, random: "Node" = None): self.val = int(x) self.next = next self.random = random class Solution: def copyRandomList(self, head: "Node") -> "Node": if not head: return None node = head new_node = None node_map = {} new_node_map = {} while node: if not new_node: new_node = Node(node.val, None, None) new_head = new_node new_node_map[node] = new_node if node.random in new_node_map: new_node.random = new_node_map[node.random] if node.random not in node_map: node_map[node.random] = [new_node] else: node_map[node.random].append(new_node) if node in node_map: for random_node in node_map[node]: random_node.random = new_node node = node.next if node: new_node.next = Node(node.val, None, None) new_node = new_node.next return new_head
class Node: def __init__(self, x: int, next: 'Node'=None, random: 'Node'=None): self.val = int(x) self.next = next self.random = random class Solution: def copy_random_list(self, head: 'Node') -> 'Node': if not head: return None node = head new_node = None node_map = {} new_node_map = {} while node: if not new_node: new_node = node(node.val, None, None) new_head = new_node new_node_map[node] = new_node if node.random in new_node_map: new_node.random = new_node_map[node.random] if node.random not in node_map: node_map[node.random] = [new_node] else: node_map[node.random].append(new_node) if node in node_map: for random_node in node_map[node]: random_node.random = new_node node = node.next if node: new_node.next = node(node.val, None, None) new_node = new_node.next return new_head