content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
---|---|
"""Helpers to subset an extracted dataframe"""
readability_cols = [
"flesch_reading_ease",
"flesch_kincaid_grade",
"smog",
"gunning_fog",
"automated_readability_index",
"coleman_liau_index",
"lix",
"rix",
]
dependency_cols = [
"dependency_distance_mean",
"dependency_distance_std",
"prop_adjacent_dependency_relation_mean",
"prop_adjacent_dependency_relation_std",
]
descriptive_stats_cols = [
"token_length_mean",
"token_length_median",
"token_length_std",
"sentence_length_mean",
"sentence_length_median",
"sentence_length_std",
"syllables_per_token_mean",
"syllables_per_token_median",
"syllables_per_token_std",
"n_tokens",
"n_unique_tokens",
"percent_unique_tokens",
"n_sentences",
"n_characters",
]
| """Helpers to subset an extracted dataframe"""
readability_cols = ['flesch_reading_ease', 'flesch_kincaid_grade', 'smog', 'gunning_fog', 'automated_readability_index', 'coleman_liau_index', 'lix', 'rix']
dependency_cols = ['dependency_distance_mean', 'dependency_distance_std', 'prop_adjacent_dependency_relation_mean', 'prop_adjacent_dependency_relation_std']
descriptive_stats_cols = ['token_length_mean', 'token_length_median', 'token_length_std', 'sentence_length_mean', 'sentence_length_median', 'sentence_length_std', 'syllables_per_token_mean', 'syllables_per_token_median', 'syllables_per_token_std', 'n_tokens', 'n_unique_tokens', 'percent_unique_tokens', 'n_sentences', 'n_characters'] |
class Solution:
def longestPalindrome(self, s: str) -> int:
d = {}
for c in s:
if c not in d:
d[c] = 1
else:
d[c] = d[c] + 1
res = 0
for _, n in d.items():
res += n - (n & 1)
return res + 1 if res < len(s) else res
s = Solution()
s.longestPalindrome("ccd")
| class Solution:
def longest_palindrome(self, s: str) -> int:
d = {}
for c in s:
if c not in d:
d[c] = 1
else:
d[c] = d[c] + 1
res = 0
for (_, n) in d.items():
res += n - (n & 1)
return res + 1 if res < len(s) else res
s = solution()
s.longestPalindrome('ccd') |
"""GCP Storage Constant."""
locations_list = [
"US",
"EU",
"ASIA",
"ASIA1",
"EUR4",
"NAM4",
"NORTHAMERICA-NORTHEAST1",
"NORTHAMERICA-NORTHEAST2",
"US-CENTRAL1",
"US-EAST1",
"US-EAST4",
"US-WEST1",
"US-WEST2",
"US-WEST3",
"US-WEST4",
"SOUTHAMERICA-EAST1",
"EUROPE-CENTRAL2",
"EUROPE-NORTH1",
"EUROPE-WEST1",
"EUROPE-WEST2",
"EUROPE-WEST3",
"EUROPE-WEST4",
"EUROPE-WEST6",
"ASIA-EAST1",
"ASIA-EAST2",
"ASIA-NORTHEAST1",
"ASIA-NORTHEAST2",
"ASIA-NORTHEAST3",
"ASIA-SOUTH1",
"ASIA-SOUTH2",
"ASIA-SOUTHEAST1",
"ASIA-SOUTHEAST2",
"AUSTRALIA-SOUTHEAST1",
"AUSTRALIA-SOUTHEAST2",
]
storage_classes_list = [
"STANDARD",
"NEARLINE",
"COLDLINE",
"ARCHIVE",
]
| """GCP Storage Constant."""
locations_list = ['US', 'EU', 'ASIA', 'ASIA1', 'EUR4', 'NAM4', 'NORTHAMERICA-NORTHEAST1', 'NORTHAMERICA-NORTHEAST2', 'US-CENTRAL1', 'US-EAST1', 'US-EAST4', 'US-WEST1', 'US-WEST2', 'US-WEST3', 'US-WEST4', 'SOUTHAMERICA-EAST1', 'EUROPE-CENTRAL2', 'EUROPE-NORTH1', 'EUROPE-WEST1', 'EUROPE-WEST2', 'EUROPE-WEST3', 'EUROPE-WEST4', 'EUROPE-WEST6', 'ASIA-EAST1', 'ASIA-EAST2', 'ASIA-NORTHEAST1', 'ASIA-NORTHEAST2', 'ASIA-NORTHEAST3', 'ASIA-SOUTH1', 'ASIA-SOUTH2', 'ASIA-SOUTHEAST1', 'ASIA-SOUTHEAST2', 'AUSTRALIA-SOUTHEAST1', 'AUSTRALIA-SOUTHEAST2']
storage_classes_list = ['STANDARD', 'NEARLINE', 'COLDLINE', 'ARCHIVE'] |
class Articles:
def __init__(self,id,name,author, title, description, url, urlToImage,publishedAt):
self.id = id
self.name = name
self.author = author
self.title = title
self.description = description
self.url = url
self.urlToImage = urlToImage
self.publishedAt = publishedAt
class Source:
"""
Source class to define news source object
"""
def __init__(self, id, name, author, title, url, urlToImage, publishedAt):
self.id = id
self.name = name
self.author = author
self.title = title
self.url = url
self.urlToImage = urlToImage
self.publishedAt = publishedAt
| class Articles:
def __init__(self, id, name, author, title, description, url, urlToImage, publishedAt):
self.id = id
self.name = name
self.author = author
self.title = title
self.description = description
self.url = url
self.urlToImage = urlToImage
self.publishedAt = publishedAt
class Source:
"""
Source class to define news source object
"""
def __init__(self, id, name, author, title, url, urlToImage, publishedAt):
self.id = id
self.name = name
self.author = author
self.title = title
self.url = url
self.urlToImage = urlToImage
self.publishedAt = publishedAt |
# OpenWeatherMap API Key
weather_api_key = "f4695ec49ac558195fc591f0d450c34c"
# Google API Key
g_key = "AIzaSyAyIq5hhFN-Y0M16Ltie3YuwpDiKWx8tCk"
| weather_api_key = 'f4695ec49ac558195fc591f0d450c34c'
g_key = 'AIzaSyAyIq5hhFN-Y0M16Ltie3YuwpDiKWx8tCk' |
class ArgumentError(Exception):
def __init__(self, argument_name: str, *args) -> None:
super().__init__(*args)
self.argument_name = argument_name
@property
def argument_name(self) -> str:
return self.__argument_name
@argument_name.setter
def argument_name(self, value: str) -> None:
self.__argument_name = value
def __str__(self) -> str:
return f"{super().__str__()}\nArgument name: {self.argument_name}"
| class Argumenterror(Exception):
def __init__(self, argument_name: str, *args) -> None:
super().__init__(*args)
self.argument_name = argument_name
@property
def argument_name(self) -> str:
return self.__argument_name
@argument_name.setter
def argument_name(self, value: str) -> None:
self.__argument_name = value
def __str__(self) -> str:
return f'{super().__str__()}\nArgument name: {self.argument_name}' |
BOT_NAME = "placement"
SPIDER_MODULES = ["placement.spiders"]
NEWSPIDER_MODULE = "placement.spiders"
ROBOTSTXT_OBEY = True
CONCURRENT_REQUESTS = 16
DUPEFILTER_DEBUG = True
EXTENSIONS = {"spidermon.contrib.scrapy.extensions.Spidermon": 500}
SPIDERMON_ENABLED = True
ITEM_PIPELINES = {"spidermon.contrib.scrapy.pipelines.ItemValidationPipeline": 800}
SPIDERMON_VALIDATION_CERBERUS = ["/home/vipulgupta2048/placement/placement/schema.json"]
USER_AGENT = "Vipul Gupta - placement (vipulgupta2048@gmail.com)"
| bot_name = 'placement'
spider_modules = ['placement.spiders']
newspider_module = 'placement.spiders'
robotstxt_obey = True
concurrent_requests = 16
dupefilter_debug = True
extensions = {'spidermon.contrib.scrapy.extensions.Spidermon': 500}
spidermon_enabled = True
item_pipelines = {'spidermon.contrib.scrapy.pipelines.ItemValidationPipeline': 800}
spidermon_validation_cerberus = ['/home/vipulgupta2048/placement/placement/schema.json']
user_agent = 'Vipul Gupta - placement (vipulgupta2048@gmail.com)' |
def star_pattern(n):
for i in range(n):
for j in range(i+1):
print("*",end=" ")
print()
star_pattern(5)
'''
star_pattern(5)
*
* *
* * *
* * * *
* * * * *
'''
| def star_pattern(n):
for i in range(n):
for j in range(i + 1):
print('*', end=' ')
print()
star_pattern(5)
'\n star_pattern(5)\n *\n * *\n * * *\n * * * *\n * * * * *\n ' |
# 1461. Check If a String Contains All Binary Codes of Size K
# User Accepted:2806
# User Tried:4007
# Total Accepted:2876
# Total Submissions:9725
# Difficulty:Medium
# Given a binary string s and an integer k.
# Return True if any binary code of length k is a substring of s. Otherwise, return False.
# Example 1:
# Input: s = "00110110", k = 2
# Output: true
# Explanation: The binary codes of length 2 are "00", "01", "10" and "11".
# They can be all found as substrings at indicies 0, 1, 3 and 2 respectively.
# Example 2:
# Input: s = "00110", k = 2
# Output: true
# Example 3:
# Input: s = "0110", k = 1
# Output: true
# Explanation: The binary codes of length 1 are "0" and "1", it is clear that both exist as a substring.
# Example 4:
# Input: s = "0110", k = 2
# Output: false
# Explanation: The binary code "00" is of length 2 and doesn't exist in the array.
# Example 5:
# Input: s = "0000000001011100", k = 4
# Output: false
# Constraints:
# 1 <= s.length <= 5 * 10^5
# s consists of 0's and 1's only.
# 1 <= k <= 20
class Solution:
def hasAllCodes(self, s: str, k: int) -> bool:
for i in range(2**k):
tmp = str(bin(i))[2:]
if len(tmp) < k:
tmp = '0' * (k-len(tmp)) + tmp
if tmp in s:
# print('fuck')
continue
else:
return False
return True
# Redo
rec = set()
tmp = 0
for i in range(len(s)):
tmp = tmp * 2 + int(s[i])
if i >= k:
tmp -= int(s[i-k]) << k
if i >= k-1:
rec.add(tmp)
return len(rec) == (1<<k) | class Solution:
def has_all_codes(self, s: str, k: int) -> bool:
for i in range(2 ** k):
tmp = str(bin(i))[2:]
if len(tmp) < k:
tmp = '0' * (k - len(tmp)) + tmp
if tmp in s:
continue
else:
return False
return True
rec = set()
tmp = 0
for i in range(len(s)):
tmp = tmp * 2 + int(s[i])
if i >= k:
tmp -= int(s[i - k]) << k
if i >= k - 1:
rec.add(tmp)
return len(rec) == 1 << k |
n = int(input())
v = []
for i in range(n): v.append(int(input()))
s = sorted(set(v))
for i in s: print(f'{i} aparece {v.count(i)} vez (es)')
| n = int(input())
v = []
for i in range(n):
v.append(int(input()))
s = sorted(set(v))
for i in s:
print(f'{i} aparece {v.count(i)} vez (es)') |
#! /usr/bin/env python
# Copyright (C) 2012-2015, Alphan Ulusoy (alphan@bu.edu)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Environment class
#
class Environment:
def __init__(self, case):
"""Defines regions in the environment.
"""
# Global and local requests
self.global_reqs = dict()
self.local_reqs = dict()
if case == 'case1':
# Static requests (labels are cell coordinates)
self.global_reqs[(3,1)] = {'reqs':{'photo'}, 'color':'green'}
self.global_reqs[(5,10)] = {'reqs':{'upload'}, 'color':'blue'}
self.global_reqs[(9,7)] = {'reqs':{'upload'}, 'color':'blue'}
# Local requests (labels are cell coordinates)
self.local_reqs = dict()
self.local_reqs[(1,7)] = {'reqs':{'unsafe'}, 'on':True, 'color':'yellow'}
self.local_reqs[(2,7)] = {'reqs':{'unsafe'}, 'on':True, 'color':'yellow'}
self.local_reqs[(3,7)] = {'reqs':{'unsafe'}, 'on':True, 'color':'yellow'}
self.local_reqs[(4,7)] = {'reqs':{'unsafe'}, 'on':True, 'color':'yellow'}
self.local_reqs[(5,7)] = {'reqs':{'unsafe'}, 'on':True, 'color':'yellow'}
self.local_reqs[(6,7)] = {'reqs':{'unsafe'}, 'on':True, 'color':'yellow'}
self.local_reqs[(7,7)] = {'reqs':{'unsafe'}, 'on':True, 'color':'yellow'}
self.local_reqs[(9,4)] = {'reqs':{'extinguish'}, 'on':True, 'color':'red'}
self.local_reqs[(9,2)] = {'reqs':{'assist'}, 'on':True, 'color':'cyan'}
elif case == 'case2':
# Static requests (labels are cell coordinates)
self.global_reqs[(3,3)] = {'reqs':{'photo1'}, 'color':'LightGreen'}
self.global_reqs[(19,6)] = {'reqs':{'photo2'}, 'color':'Green'}
self.global_reqs[(11,10)] = {'reqs':{'upload'}, 'color':'blue'}
# Local requests (labels are cell coordinates)
self.local_reqs = dict()
self.local_reqs[(8,8)] = {'reqs':{'pickup'}, 'on':True, 'color':'red'}
self.local_reqs[(6,7)] = {'reqs':{'dropoff'}, 'on':True, 'color':'cyan'}
self.local_reqs[(9,6)] = {'reqs':{'pickup'}, 'on':True, 'color':'red'}
self.local_reqs[(3,5)] = {'reqs':{'dropoff'}, 'on':True, 'color':'cyan'}
elif case == 'case3':
# Static requests (labels are cell coordinates)
self.global_reqs[(3,3)] = {'reqs':{'photo1'}, 'color':'LightGreen'}
self.global_reqs[(19,6)] = {'reqs':{'photo2'}, 'color':'DarkGreen'}
self.global_reqs[(11,10)] = {'reqs':{'upload'}, 'color':'blue'}
# Local requests (labels are cell coordinates)
self.local_reqs = dict()
self.local_reqs[(14,8)] = {'reqs':{'pickup1'}, 'on':True, 'color':'Red'}
self.local_reqs[(12,7)] = {'reqs':{'dropoff1'}, 'on':True, 'color':'Cyan'}
self.local_reqs[(13,4)] = {'reqs':{'pickup2'}, 'on':True, 'color':'DarkRed'}
self.local_reqs[(16,6)] = {'reqs':{'dropoff2'}, 'on':True, 'color':'DarkCyan'}
else:
assert False, 'Case %s is not implemented' % case
| class Environment:
def __init__(self, case):
"""Defines regions in the environment.
"""
self.global_reqs = dict()
self.local_reqs = dict()
if case == 'case1':
self.global_reqs[3, 1] = {'reqs': {'photo'}, 'color': 'green'}
self.global_reqs[5, 10] = {'reqs': {'upload'}, 'color': 'blue'}
self.global_reqs[9, 7] = {'reqs': {'upload'}, 'color': 'blue'}
self.local_reqs = dict()
self.local_reqs[1, 7] = {'reqs': {'unsafe'}, 'on': True, 'color': 'yellow'}
self.local_reqs[2, 7] = {'reqs': {'unsafe'}, 'on': True, 'color': 'yellow'}
self.local_reqs[3, 7] = {'reqs': {'unsafe'}, 'on': True, 'color': 'yellow'}
self.local_reqs[4, 7] = {'reqs': {'unsafe'}, 'on': True, 'color': 'yellow'}
self.local_reqs[5, 7] = {'reqs': {'unsafe'}, 'on': True, 'color': 'yellow'}
self.local_reqs[6, 7] = {'reqs': {'unsafe'}, 'on': True, 'color': 'yellow'}
self.local_reqs[7, 7] = {'reqs': {'unsafe'}, 'on': True, 'color': 'yellow'}
self.local_reqs[9, 4] = {'reqs': {'extinguish'}, 'on': True, 'color': 'red'}
self.local_reqs[9, 2] = {'reqs': {'assist'}, 'on': True, 'color': 'cyan'}
elif case == 'case2':
self.global_reqs[3, 3] = {'reqs': {'photo1'}, 'color': 'LightGreen'}
self.global_reqs[19, 6] = {'reqs': {'photo2'}, 'color': 'Green'}
self.global_reqs[11, 10] = {'reqs': {'upload'}, 'color': 'blue'}
self.local_reqs = dict()
self.local_reqs[8, 8] = {'reqs': {'pickup'}, 'on': True, 'color': 'red'}
self.local_reqs[6, 7] = {'reqs': {'dropoff'}, 'on': True, 'color': 'cyan'}
self.local_reqs[9, 6] = {'reqs': {'pickup'}, 'on': True, 'color': 'red'}
self.local_reqs[3, 5] = {'reqs': {'dropoff'}, 'on': True, 'color': 'cyan'}
elif case == 'case3':
self.global_reqs[3, 3] = {'reqs': {'photo1'}, 'color': 'LightGreen'}
self.global_reqs[19, 6] = {'reqs': {'photo2'}, 'color': 'DarkGreen'}
self.global_reqs[11, 10] = {'reqs': {'upload'}, 'color': 'blue'}
self.local_reqs = dict()
self.local_reqs[14, 8] = {'reqs': {'pickup1'}, 'on': True, 'color': 'Red'}
self.local_reqs[12, 7] = {'reqs': {'dropoff1'}, 'on': True, 'color': 'Cyan'}
self.local_reqs[13, 4] = {'reqs': {'pickup2'}, 'on': True, 'color': 'DarkRed'}
self.local_reqs[16, 6] = {'reqs': {'dropoff2'}, 'on': True, 'color': 'DarkCyan'}
else:
assert False, 'Case %s is not implemented' % case |
expected_output = {
"vrf": {
"VRF1": {
"address_family": {
"ipv4": {
"instance": {
"1": {
"areas": {
"0.0.0.1": {
"sham_links": {
"10.21.33.33 10.151.22.22": {
"cost": 111,
"dcbitless_lsa_count": 1,
"donotage_lsa": "not allowed",
"dead_interval": 13,
"demand_circuit": True,
"hello_interval": 3,
"hello_timer": "00:00:00:772",
"if_index": 2,
"local_id": "10.21.33.33",
"name": "SL0",
"link_state": "up",
"remote_id": "10.151.22.22",
"retransmit_interval": 5,
"state": "point-to-point,",
"transit_area_id": "0.0.0.1",
"transmit_delay": 7,
"wait_interval": 13,
}
}
}
}
}
}
}
}
}
}
}
| expected_output = {'vrf': {'VRF1': {'address_family': {'ipv4': {'instance': {'1': {'areas': {'0.0.0.1': {'sham_links': {'10.21.33.33 10.151.22.22': {'cost': 111, 'dcbitless_lsa_count': 1, 'donotage_lsa': 'not allowed', 'dead_interval': 13, 'demand_circuit': True, 'hello_interval': 3, 'hello_timer': '00:00:00:772', 'if_index': 2, 'local_id': '10.21.33.33', 'name': 'SL0', 'link_state': 'up', 'remote_id': '10.151.22.22', 'retransmit_interval': 5, 'state': 'point-to-point,', 'transit_area_id': '0.0.0.1', 'transmit_delay': 7, 'wait_interval': 13}}}}}}}}}}} |
pkgname = "cargo-bootstrap"
pkgver = "1.60.0"
pkgrel = 0
# satisfy runtime dependencies
hostmakedepends = ["curl"]
depends = ["!cargo"]
pkgdesc = "Bootstrap binaries of Rust package manager"
maintainer = "q66 <q66@chimera-linux.org>"
license = "MIT OR Apache-2.0"
url = "https://rust-lang.org"
source = f"https://ftp.octaforge.org/chimera/distfiles/cargo-{pkgver}-{self.profile().triplet}.tar.xz"
options = ["!strip"]
match self.profile().arch:
case "ppc64le":
sha256 = "29d19c5015d97c862af365cda33339619fb23ae9a2ae2ea5290765604f99e47d"
case "x86_64":
sha256 = "07ab0bdeaf14f31fe07e40f2b3a9a6ae18a4b61579c8b6fa22ecd684054a81af"
case _:
broken = f"not yet built for {self.profile().arch}"
def do_install(self):
self.install_bin("cargo")
self.install_license("LICENSE-APACHE")
self.install_license("LICENSE-MIT")
self.install_license("LICENSE-THIRD-PARTY")
| pkgname = 'cargo-bootstrap'
pkgver = '1.60.0'
pkgrel = 0
hostmakedepends = ['curl']
depends = ['!cargo']
pkgdesc = 'Bootstrap binaries of Rust package manager'
maintainer = 'q66 <q66@chimera-linux.org>'
license = 'MIT OR Apache-2.0'
url = 'https://rust-lang.org'
source = f'https://ftp.octaforge.org/chimera/distfiles/cargo-{pkgver}-{self.profile().triplet}.tar.xz'
options = ['!strip']
match self.profile().arch:
case 'ppc64le':
sha256 = '29d19c5015d97c862af365cda33339619fb23ae9a2ae2ea5290765604f99e47d'
case 'x86_64':
sha256 = '07ab0bdeaf14f31fe07e40f2b3a9a6ae18a4b61579c8b6fa22ecd684054a81af'
case _:
broken = f'not yet built for {self.profile().arch}'
def do_install(self):
self.install_bin('cargo')
self.install_license('LICENSE-APACHE')
self.install_license('LICENSE-MIT')
self.install_license('LICENSE-THIRD-PARTY') |
# m=wrf_hydro_ens_sim.members[0]
# dir(m)
# Change restart frequency to hourly in hydro namelist
att_tuple = ('base_hydro_namelist', 'hydro_nlist', 'rst_dt')
# The values can be a scalar (uniform across the ensemble) or a list of length N (ensemble size).
values = 60
wrf_hydro_ens_sim.set_member_diffs(att_tuple, values)
wrf_hydro_ens_sim.member_diffs # wont report any values uniform across the ensemble
# but this will:
[mm.base_hydro_namelist['hydro_nlist']['rst_dt'] for mm in wrf_hydro_ens_sim.members]
# Change restart frequency to hourly in hrldas namelist
att_tuple = ('base_hrldas_namelist', 'noahlsm_offline', 'restart_frequency_hours')
values = 1
wrf_hydro_ens_sim.set_member_diffs(att_tuple, values)
[mm.base_hrldas_namelist['noahlsm_offline']['restart_frequency_hours'] for mm in wrf_hydro_ens_sim.members]
# There are multiple restart files in the domain and the default is on 2018-06-01
# Change restart frequency to hourly in hydro namelist.
# att_tuple = ('base_hydro_namelist', 'hydro_nlist', 'restart_file')
# values = '/glade/work/jamesmcc/domains/public/croton_NY/Gridded/RESTART/HYDRO_RST.2011-08-26_00:00_DOMAIN1'
# wrf_hydro_ens_sim.set_member_diffs(att_tuple, values)
# att_tuple = ('base_hrldas_namelist', 'noahlsm_offline', 'restart_filename_requested')
# values = '/glade/work/jamesmcc/domains/public/croton_NY/Gridded/RESTART/RESTART.2011082600_DOMAIN1'
# wrf_hydro_ens_sim.set_member_diffs(att_tuple, values)
# Change model advance to 1 hour in hrldas namelist
# This is governed by the configuration namelist setting:
# run_experiment: time: advance_model_hours:
# No other differences across the ensemble, only the FORCING dir for each
# will be set at run time by the noise_model.
# We could to parameter differences here.
| att_tuple = ('base_hydro_namelist', 'hydro_nlist', 'rst_dt')
values = 60
wrf_hydro_ens_sim.set_member_diffs(att_tuple, values)
wrf_hydro_ens_sim.member_diffs
[mm.base_hydro_namelist['hydro_nlist']['rst_dt'] for mm in wrf_hydro_ens_sim.members]
att_tuple = ('base_hrldas_namelist', 'noahlsm_offline', 'restart_frequency_hours')
values = 1
wrf_hydro_ens_sim.set_member_diffs(att_tuple, values)
[mm.base_hrldas_namelist['noahlsm_offline']['restart_frequency_hours'] for mm in wrf_hydro_ens_sim.members] |
def main () :
i = 1
fib = 1
target = 10
temp = 0
while (i < target) :
temp = fib
fib += temp
i+=1
print(fib)
return 0
if __name__ == '__main__':
main()
| def main():
i = 1
fib = 1
target = 10
temp = 0
while i < target:
temp = fib
fib += temp
i += 1
print(fib)
return 0
if __name__ == '__main__':
main() |
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
greed_p = 0
size_p = 0
count = 0
while greed_p < len(g) and size_p < len(s):
if g[greed_p] <= s[size_p]:
count += 1
greed_p += 1
size_p += 1
elif g[greed_p] > s[size_p]:
size_p += 1
return count
| class Solution:
def find_content_children(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
greed_p = 0
size_p = 0
count = 0
while greed_p < len(g) and size_p < len(s):
if g[greed_p] <= s[size_p]:
count += 1
greed_p += 1
size_p += 1
elif g[greed_p] > s[size_p]:
size_p += 1
return count |
"""
This is duplicated from Django 3.0 to avoid
starting an import chain that ends up with
ContentTypes which may not be installed in a
Djangae project.
"""
class BaseBackend:
def authenticate(self, request, **kwargs):
return None
@classmethod
def can_authenticate(cls, request):
"""
This is a pre-check to see if the credentials are
available to try to authenticate.
"""
return True
def get_user(self, user_id):
return None
def get_user_permissions(self, user_obj, obj=None):
return set()
def get_group_permissions(self, user_obj, obj=None):
return set()
def get_all_permissions(self, user_obj, obj=None):
return {
*self.get_user_permissions(user_obj, obj=obj),
*self.get_group_permissions(user_obj, obj=obj),
}
def has_perm(self, user_obj, perm, obj=None):
return perm in self.get_all_permissions(user_obj, obj=obj)
| """
This is duplicated from Django 3.0 to avoid
starting an import chain that ends up with
ContentTypes which may not be installed in a
Djangae project.
"""
class Basebackend:
def authenticate(self, request, **kwargs):
return None
@classmethod
def can_authenticate(cls, request):
"""
This is a pre-check to see if the credentials are
available to try to authenticate.
"""
return True
def get_user(self, user_id):
return None
def get_user_permissions(self, user_obj, obj=None):
return set()
def get_group_permissions(self, user_obj, obj=None):
return set()
def get_all_permissions(self, user_obj, obj=None):
return {*self.get_user_permissions(user_obj, obj=obj), *self.get_group_permissions(user_obj, obj=obj)}
def has_perm(self, user_obj, perm, obj=None):
return perm in self.get_all_permissions(user_obj, obj=obj) |
data = {
"publication-date": {
"year": {
"value": "2020"},
"month": {"value": "01"}},
"short-description": "With a central surface brightness of 29.3 mag arcsec, and half-light radius of r_half=3.1^{+0.9}_{-1.1} kpc, Andromeda XIX (And XIX) is an extremely diffuse satellite of Andromeda.",
"external-ids": {
"external-id": [
{
"external-id-type": "bibcode",
"external-id-value": "2020MNRAS.491.3496C",
"external-id-relationship": "SELF"
},
{
"external-id-type": "doi",
"external-id-value": "10.1093/mnras/stz3252",
"external-id-relationship": "SELF"
},
{
"external-id-type": "arxiv",
"external-id-value": "1910.12879",
"external-id-relationship": "SELF"
}
]
},
"journal-title": {
"value": "Monthly Notices of the Royal Astronomical Society"
},
"type": "JOURNAL_ARTICLE",
"contributors": {
"contributor": [
{
"credit-name": {
"value": "Collins, Michelle L. M."
},
"contributor-attributes": {
"contributor-role": "AUTHOR"
}
},
{
"credit-name": {
"value": "Tollerud, Erik J."
},
"contributor-attributes": {
"contributor-role": "AUTHOR"
}
},
{
"credit-name": {
"value": "Rich, R. Michael"
},
"contributor-attributes": {
"contributor-role": "AUTHOR"
}
},
{
"credit-name": {
"value": "Ibata, Rodrigo A."
},
"contributor-attributes": {
"contributor-role": "AUTHOR"
}
},
{
"credit-name": {
"value": "Martin, Nicolas F."
},
"contributor-attributes": {
"contributor-role": "AUTHOR"
}
},
{
"credit-name": {
"value": "Chapman, Scott C."
},
"contributor-attributes": {
"contributor-role": "AUTHOR"
}
},
{
"credit-name": {
"value": "Gilbert, Karoline M."
},
"contributor-attributes": {
"contributor-role": "AUTHOR"
}
},
{
"credit-name": {
"value": "Preston, Janet"
},
"contributor-attributes": {
"contributor-role": "AUTHOR"
}
}
]
},
"title": {
"title": {
"value": "A detailed study of Andromeda XIX, an extreme local analogue of ultradiffuse galaxies"
}
},
"put-code": 63945135
}
data_noarxiv = {
"publication-date": {
"year": {
"value": "2020"},
"month": {"value": "01"}},
"short-description": "With a central surface brightness of 29.3 mag arcsec, and half-light radius of r_half=3.1^{+0.9}_{-1.1} kpc, Andromeda XIX (And XIX) is an extremely diffuse satellite of Andromeda.",
"external-ids": {
"external-id": [
{
"external-id-type": "bibcode",
"external-id-value": "2020MNRAS.491.3496C",
"external-id-relationship": "SELF"
},
{
"external-id-type": "doi",
"external-id-value": "10.1093/mnras/stz3252",
"external-id-relationship": "SELF"
}
]
},
"journal-title": {
"value": "Monthly Notices of the Royal Astronomical Society"
},
"type": "JOURNAL_ARTICLE",
"contributors": {
"contributor": [
{
"credit-name": {
"value": "Collins, Michelle L. M."
},
"contributor-attributes": {
"contributor-role": "AUTHOR"
}
},
{
"credit-name": {
"value": "Tollerud, Erik J."
},
"contributor-attributes": {
"contributor-role": "AUTHOR"
}
},
{
"credit-name": {
"value": "Rich, R. Michael"
},
"contributor-attributes": {
"contributor-role": "AUTHOR"
}
},
{
"credit-name": {
"value": "Ibata, Rodrigo A."
},
"contributor-attributes": {
"contributor-role": "AUTHOR"
}
},
{
"credit-name": {
"value": "Martin, Nicolas F."
},
"contributor-attributes": {
"contributor-role": "AUTHOR"
}
},
{
"credit-name": {
"value": "Chapman, Scott C."
},
"contributor-attributes": {
"contributor-role": "AUTHOR"
}
},
{
"credit-name": {
"value": "Gilbert, Karoline M."
},
"contributor-attributes": {
"contributor-role": "AUTHOR"
}
},
{
"credit-name": {
"value": "Preston, Janet"
},
"contributor-attributes": {
"contributor-role": "AUTHOR"
}
}
]
},
"title": {
"title": {
"value": "A detailed study of Andromeda XIX, an extreme local analogue of ultradiffuse galaxies"
}
},
"put-code": 63945135
}
| data = {'publication-date': {'year': {'value': '2020'}, 'month': {'value': '01'}}, 'short-description': 'With a central surface brightness of 29.3 mag arcsec, and half-light radius of r_half=3.1^{+0.9}_{-1.1} kpc, Andromeda XIX (And XIX) is an extremely diffuse satellite of Andromeda.', 'external-ids': {'external-id': [{'external-id-type': 'bibcode', 'external-id-value': '2020MNRAS.491.3496C', 'external-id-relationship': 'SELF'}, {'external-id-type': 'doi', 'external-id-value': '10.1093/mnras/stz3252', 'external-id-relationship': 'SELF'}, {'external-id-type': 'arxiv', 'external-id-value': '1910.12879', 'external-id-relationship': 'SELF'}]}, 'journal-title': {'value': 'Monthly Notices of the Royal Astronomical Society'}, 'type': 'JOURNAL_ARTICLE', 'contributors': {'contributor': [{'credit-name': {'value': 'Collins, Michelle L. M.'}, 'contributor-attributes': {'contributor-role': 'AUTHOR'}}, {'credit-name': {'value': 'Tollerud, Erik J.'}, 'contributor-attributes': {'contributor-role': 'AUTHOR'}}, {'credit-name': {'value': 'Rich, R. Michael'}, 'contributor-attributes': {'contributor-role': 'AUTHOR'}}, {'credit-name': {'value': 'Ibata, Rodrigo A.'}, 'contributor-attributes': {'contributor-role': 'AUTHOR'}}, {'credit-name': {'value': 'Martin, Nicolas F.'}, 'contributor-attributes': {'contributor-role': 'AUTHOR'}}, {'credit-name': {'value': 'Chapman, Scott C.'}, 'contributor-attributes': {'contributor-role': 'AUTHOR'}}, {'credit-name': {'value': 'Gilbert, Karoline M.'}, 'contributor-attributes': {'contributor-role': 'AUTHOR'}}, {'credit-name': {'value': 'Preston, Janet'}, 'contributor-attributes': {'contributor-role': 'AUTHOR'}}]}, 'title': {'title': {'value': 'A detailed study of Andromeda XIX, an extreme local analogue of ultradiffuse galaxies'}}, 'put-code': 63945135}
data_noarxiv = {'publication-date': {'year': {'value': '2020'}, 'month': {'value': '01'}}, 'short-description': 'With a central surface brightness of 29.3 mag arcsec, and half-light radius of r_half=3.1^{+0.9}_{-1.1} kpc, Andromeda XIX (And XIX) is an extremely diffuse satellite of Andromeda.', 'external-ids': {'external-id': [{'external-id-type': 'bibcode', 'external-id-value': '2020MNRAS.491.3496C', 'external-id-relationship': 'SELF'}, {'external-id-type': 'doi', 'external-id-value': '10.1093/mnras/stz3252', 'external-id-relationship': 'SELF'}]}, 'journal-title': {'value': 'Monthly Notices of the Royal Astronomical Society'}, 'type': 'JOURNAL_ARTICLE', 'contributors': {'contributor': [{'credit-name': {'value': 'Collins, Michelle L. M.'}, 'contributor-attributes': {'contributor-role': 'AUTHOR'}}, {'credit-name': {'value': 'Tollerud, Erik J.'}, 'contributor-attributes': {'contributor-role': 'AUTHOR'}}, {'credit-name': {'value': 'Rich, R. Michael'}, 'contributor-attributes': {'contributor-role': 'AUTHOR'}}, {'credit-name': {'value': 'Ibata, Rodrigo A.'}, 'contributor-attributes': {'contributor-role': 'AUTHOR'}}, {'credit-name': {'value': 'Martin, Nicolas F.'}, 'contributor-attributes': {'contributor-role': 'AUTHOR'}}, {'credit-name': {'value': 'Chapman, Scott C.'}, 'contributor-attributes': {'contributor-role': 'AUTHOR'}}, {'credit-name': {'value': 'Gilbert, Karoline M.'}, 'contributor-attributes': {'contributor-role': 'AUTHOR'}}, {'credit-name': {'value': 'Preston, Janet'}, 'contributor-attributes': {'contributor-role': 'AUTHOR'}}]}, 'title': {'title': {'value': 'A detailed study of Andromeda XIX, an extreme local analogue of ultradiffuse galaxies'}}, 'put-code': 63945135} |
"""
For an array, we can build a SegmentTree for it, each node stores an extra attribute count to denote the number of
elements in the the array which value is between interval start and end. (The array may not fully filled by elements)
Design a query method with three parameters root, start and end, find the number of elements in the in array's interval
[start, end] by the given root of value SegmentTree.
Have you met this question in a real interview? Yes
Example
For array [0, empty, 2, 3], the corresponding value Segment Tree is:
[0, 3, count=3]
/ \
[0,1,count=1] [2,3,count=2]
/ \ / \
[0,0,count=1] [1,1,count=0] [2,2,count=1], [3,3,count=1]
query(1, 1), return 0
query(1, 2), return 1
query(2, 3), return 2
query(0, 2), return 2
"""
__author__ = 'Daniel'
DEFAULT = 0
f = lambda x, y: x+y
class Solution:
def query(self, root, s, e):
"""
Segment: [s, e]
:param root: The root of segment tree
:param start: start of segment/interval
:param end: end of segment/interval
:return: The count number in the interval [start, end]
"""
if not root:
return DEFAULT
if s <= root.start and e >= root.end:
return root.count
if s > root.end or e < root.start:
return DEFAULT
l = self.query(root.left, s, e)
r = self.query(root.right, s, e)
return f(l, r)
| """
For an array, we can build a SegmentTree for it, each node stores an extra attribute count to denote the number of
elements in the the array which value is between interval start and end. (The array may not fully filled by elements)
Design a query method with three parameters root, start and end, find the number of elements in the in array's interval
[start, end] by the given root of value SegmentTree.
Have you met this question in a real interview? Yes
Example
For array [0, empty, 2, 3], the corresponding value Segment Tree is:
[0, 3, count=3]
/ [0,1,count=1] [2,3,count=2]
/ \\ / [0,0,count=1] [1,1,count=0] [2,2,count=1], [3,3,count=1]
query(1, 1), return 0
query(1, 2), return 1
query(2, 3), return 2
query(0, 2), return 2
"""
__author__ = 'Daniel'
default = 0
f = lambda x, y: x + y
class Solution:
def query(self, root, s, e):
"""
Segment: [s, e]
:param root: The root of segment tree
:param start: start of segment/interval
:param end: end of segment/interval
:return: The count number in the interval [start, end]
"""
if not root:
return DEFAULT
if s <= root.start and e >= root.end:
return root.count
if s > root.end or e < root.start:
return DEFAULT
l = self.query(root.left, s, e)
r = self.query(root.right, s, e)
return f(l, r) |
# This is a sample Python script.
def test_print_hi():
assert True
| def test_print_hi():
assert True |
hours = input('Enter Hours \n')
rate = input('Enter Rate\n')
hours = int(hours)
rate = float(rate)
if (hours <= 40):
pay = rate*hours
else:
extra_time = hours - 40
pay = (rate*hours) + ((rate*extra_time)/2)
print('Pay: ', pay)
| hours = input('Enter Hours \n')
rate = input('Enter Rate\n')
hours = int(hours)
rate = float(rate)
if hours <= 40:
pay = rate * hours
else:
extra_time = hours - 40
pay = rate * hours + rate * extra_time / 2
print('Pay: ', pay) |
def get_schema():
return {
'type': 'object',
'properties': {
'connections': {
'type': 'array',
'items': {
'type': 'object',
'properties': {
'name': {'type': 'string'},
'path': {'type': 'string'},
'driver': {'type': 'string'},
'server': {'type': 'string'},
'database': {'type': 'string'},
'name_col': {'type': 'string'},
'text_col': {'type': 'string'},
}
}
},
'documents': {'type': 'array', 'items': {'$ref': '#/definitions/document'}},
'irr_documents': {'type': 'array', 'items': {'$ref': '#/definitions/document'}},
'labels': {'type': 'array', 'items': {'type': 'string'}},
'highlights': {'type': 'array', 'items': {'type': 'string'}},
'project': {'type': 'string'},
'subproject': {'type': 'string'},
'start_date': {'type': 'string'},
'end_date': {'type': 'string'},
'annotation': {
'type': 'object',
'properties': {
'irr_percent': {'type': 'number'},
'irr_count': {'type': 'integer'},
'annotators': {
'type': 'array',
'items': {
'type': 'object',
'properties': {
'name': {'type': 'string'},
'number': {'type': 'integer'},
'percent': {'type': 'number', 'maximum': 1.0, 'minimum': 0.0},
'documents': {'type': 'array', 'items': {'$ref': '#/definitions/document'}},
},
},
},
},
}
},
'definitions': {
'document': {
'type': 'object',
'properties': {
'name': {'type': 'string'},
'metadata': {'type': 'object'},
'text': {'type': 'string'},
'offsets': {'type': 'array', 'items': {'$ref': '#/definitions/offset'}},
'highlights': {'type': 'array', 'items': {'type': 'string'}},
'expiration_date': {'type': 'string'},
}
},
'offset': {
'type': 'object',
'properties': {
'start': {'type': 'integer', 'minimum': 0},
'end': {'type': 'integer', 'minimum': 0}
}
},
}
} | def get_schema():
return {'type': 'object', 'properties': {'connections': {'type': 'array', 'items': {'type': 'object', 'properties': {'name': {'type': 'string'}, 'path': {'type': 'string'}, 'driver': {'type': 'string'}, 'server': {'type': 'string'}, 'database': {'type': 'string'}, 'name_col': {'type': 'string'}, 'text_col': {'type': 'string'}}}}, 'documents': {'type': 'array', 'items': {'$ref': '#/definitions/document'}}, 'irr_documents': {'type': 'array', 'items': {'$ref': '#/definitions/document'}}, 'labels': {'type': 'array', 'items': {'type': 'string'}}, 'highlights': {'type': 'array', 'items': {'type': 'string'}}, 'project': {'type': 'string'}, 'subproject': {'type': 'string'}, 'start_date': {'type': 'string'}, 'end_date': {'type': 'string'}, 'annotation': {'type': 'object', 'properties': {'irr_percent': {'type': 'number'}, 'irr_count': {'type': 'integer'}, 'annotators': {'type': 'array', 'items': {'type': 'object', 'properties': {'name': {'type': 'string'}, 'number': {'type': 'integer'}, 'percent': {'type': 'number', 'maximum': 1.0, 'minimum': 0.0}, 'documents': {'type': 'array', 'items': {'$ref': '#/definitions/document'}}}}}}}}, 'definitions': {'document': {'type': 'object', 'properties': {'name': {'type': 'string'}, 'metadata': {'type': 'object'}, 'text': {'type': 'string'}, 'offsets': {'type': 'array', 'items': {'$ref': '#/definitions/offset'}}, 'highlights': {'type': 'array', 'items': {'type': 'string'}}, 'expiration_date': {'type': 'string'}}}, 'offset': {'type': 'object', 'properties': {'start': {'type': 'integer', 'minimum': 0}, 'end': {'type': 'integer', 'minimum': 0}}}}} |
def main():
mainFile = open("index.html", 'r', encoding='utf-8')
writeFile = open("index_pasted.html", 'w+', encoding='utf-8')
classId = 'class="internal"'
cssId = '<link rel='
for line in mainFile:
if (classId in line):
pasteScript(line, writeFile)
elif (cssId in line):
pasteCSS(line, writeFile)
else:
writeFile.write(line)
writeFile.close()
def pasteCSS(line, writeFile):
filename = line.split('"')[-2]
importFile = open(filename, 'r', encoding='utf-8')
writeFile.write("<style>\n")
for row in importFile:
writeFile.write(row)
writeFile.write("</style>\n")
def pasteScript(line, writeFile):
filename = line.strip().split(" ")[3].split('"')[1]
importFile = open(filename, 'r', encoding='utf-8')
writeFile.write("<script>\n")
for row in importFile:
writeFile.write(row)
writeFile.write("</script>\n")
main()
| def main():
main_file = open('index.html', 'r', encoding='utf-8')
write_file = open('index_pasted.html', 'w+', encoding='utf-8')
class_id = 'class="internal"'
css_id = '<link rel='
for line in mainFile:
if classId in line:
paste_script(line, writeFile)
elif cssId in line:
paste_css(line, writeFile)
else:
writeFile.write(line)
writeFile.close()
def paste_css(line, writeFile):
filename = line.split('"')[-2]
import_file = open(filename, 'r', encoding='utf-8')
writeFile.write('<style>\n')
for row in importFile:
writeFile.write(row)
writeFile.write('</style>\n')
def paste_script(line, writeFile):
filename = line.strip().split(' ')[3].split('"')[1]
import_file = open(filename, 'r', encoding='utf-8')
writeFile.write('<script>\n')
for row in importFile:
writeFile.write(row)
writeFile.write('</script>\n')
main() |
def main():
seed = 0x1234
e = [0x62d5, 0x7b27, 0xc5d4, 0x11c4, 0x5d67, 0xa356, 0x5f84,
0xbd67, 0xad04, 0x9a64, 0xefa6, 0x94d6, 0x2434, 0x0178]
flag = ""
for index in range(14):
for i in range(0x7f-0x20):
c = chr(0x20+i)
res = encode(c, index, seed)
if res == e[index]:
print(c)
flag += c
seed = encode(c, index, seed)
print("Kosen{%s}" % flag)
def encode(p1, p2, p3):
p1 = ord(p1) & 0xff
p2 = p2 & 0xffffffff
p3 = p3 & 0xffffffff
result = (((p1 >> 4) | (p1 & 0xf) << 4) + 1) ^ ((p2 >> 4) |
(~p2 << 4)) & 0xff | (p3 >> 4) << 8 ^ ((p3 >> 0xc) | (p3 << 4)) << 8
return result & 0xffff
if __name__ == "__main__":
main()
| def main():
seed = 4660
e = [25301, 31527, 50644, 4548, 23911, 41814, 24452, 48487, 44292, 39524, 61350, 38102, 9268, 376]
flag = ''
for index in range(14):
for i in range(127 - 32):
c = chr(32 + i)
res = encode(c, index, seed)
if res == e[index]:
print(c)
flag += c
seed = encode(c, index, seed)
print('Kosen{%s}' % flag)
def encode(p1, p2, p3):
p1 = ord(p1) & 255
p2 = p2 & 4294967295
p3 = p3 & 4294967295
result = (p1 >> 4 | (p1 & 15) << 4) + 1 ^ (p2 >> 4 | ~p2 << 4) & 255 | p3 >> 4 << 8 ^ (p3 >> 12 | p3 << 4) << 8
return result & 65535
if __name__ == '__main__':
main() |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
file1=open('data/u_Lvoid_20.txt',encoding='utf-8')
file2=open('temp2/void.txt','w',encoding='utf-8')
count=0
for line in file1:
count=count+1
if(line[0]=='R'):# 'line' here is a string
line_list=line.split( ) # 'line_list' is a list of small strings=['R41_1_2', 'n1_1620161_481040', n1_1620161_480880, 2.8e-05]
branch=line_list[0].split('-') #branch is a list of string=['R41','1','2']
branch0=branch[0].split('R')#branch is a list of string=['','41']
branch[0]=branch0[1]#now branch is a list of string=['41','1','2'], which is [layer_id, tree_id, branch_id]
for i in range(3):
file2.write(str(branch[i]))
file2.write(' ')
branch1=line_list[1].split('_')
for i in range(2):
file2.write(str(int(branch1[i+1])/1000))
file2.write(' ')
branch3=line_list[3].split('um')
a=float(branch3[0])
file2.write(str(a))
file2.write('\n')
file1.close()
file2.close()
| file1 = open('data/u_Lvoid_20.txt', encoding='utf-8')
file2 = open('temp2/void.txt', 'w', encoding='utf-8')
count = 0
for line in file1:
count = count + 1
if line[0] == 'R':
line_list = line.split()
branch = line_list[0].split('-')
branch0 = branch[0].split('R')
branch[0] = branch0[1]
for i in range(3):
file2.write(str(branch[i]))
file2.write(' ')
branch1 = line_list[1].split('_')
for i in range(2):
file2.write(str(int(branch1[i + 1]) / 1000))
file2.write(' ')
branch3 = line_list[3].split('um')
a = float(branch3[0])
file2.write(str(a))
file2.write('\n')
file1.close()
file2.close() |
def climbingLeaderboard(scores, alice):
scores = list(reversed(sorted(set(scores))))
r, rank = len(scores), []
for a in alice:
while (r > 0) and (a >= scores[r - 1]):
r -= 1
rank.append(r + 1)
return rank | def climbing_leaderboard(scores, alice):
scores = list(reversed(sorted(set(scores))))
(r, rank) = (len(scores), [])
for a in alice:
while r > 0 and a >= scores[r - 1]:
r -= 1
rank.append(r + 1)
return rank |
screen = {
"bg": "blue",
"rows": 0,
"columns": 0,
"columnspan": 4,
"padx": 5,
"pady": 5,
}
input = {
"bg": "blue",
"fg": "red",
"fs": "20px",
}
button = {
"bg": "blue",
"fg": "red",
"fs": "20px",
}
| screen = {'bg': 'blue', 'rows': 0, 'columns': 0, 'columnspan': 4, 'padx': 5, 'pady': 5}
input = {'bg': 'blue', 'fg': 'red', 'fs': '20px'}
button = {'bg': 'blue', 'fg': 'red', 'fs': '20px'} |
# 3. Single layered 4 inputs and 3 outputs(Looping)
mInputs = [3, 4, 1, 2]
mWeights = [[0.2, -0.4, 0.6, 0.4],
[0.4, 0.3, -0.1, 0.8],
[0.7, 0.6, 0.3, -0.3]]
mBias1 = [3, 4, 2]
layer_output = []
for neuron_weights, neuron_bias in zip(mWeights, mBias1):
neuron_output = 0
for n_inputs, n_weights in zip(mInputs, neuron_weights):
neuron_output += n_inputs*n_weights
neuron_output += neuron_bias
layer_output.append(neuron_output)
print(layer_output)
| m_inputs = [3, 4, 1, 2]
m_weights = [[0.2, -0.4, 0.6, 0.4], [0.4, 0.3, -0.1, 0.8], [0.7, 0.6, 0.3, -0.3]]
m_bias1 = [3, 4, 2]
layer_output = []
for (neuron_weights, neuron_bias) in zip(mWeights, mBias1):
neuron_output = 0
for (n_inputs, n_weights) in zip(mInputs, neuron_weights):
neuron_output += n_inputs * n_weights
neuron_output += neuron_bias
layer_output.append(neuron_output)
print(layer_output) |
# reading 2 numbers from the keyboard and printing maximum value
r = int(input("Enter the first number: "))
s = int(input("Enter the second number: "))
x = r if r>s else s
print(x)
| r = int(input('Enter the first number: '))
s = int(input('Enter the second number: '))
x = r if r > s else s
print(x) |
def main():
STRING = "aababbabbaaba"
compressed = compress(STRING)
print(compressed)
decompressed = decompress(compressed)
print(decompressed)
def compress(string):
encode = {} # string -> code
known = ""
count = 0
result = []
for letter in string:
if known + letter in encode:
known += letter
else:
count += 1
encode[known + letter] = count
result.append([encode[known] if known else 0, letter])
known = ""
if known:
result.append([encode[known], ""])
return result
def decompress(compressed):
string = ""
decode = {} # code -> string
known = ""
count = 0
for code, new in compressed:
if not code:
count += 1
decode[count] = new
string += new
elif not new:
string += decode[code]
else:
count += 1
known = decode[code]
decode[count] = known + new
string += known + new
return string
if __name__ == "__main__":
main()
| def main():
string = 'aababbabbaaba'
compressed = compress(STRING)
print(compressed)
decompressed = decompress(compressed)
print(decompressed)
def compress(string):
encode = {}
known = ''
count = 0
result = []
for letter in string:
if known + letter in encode:
known += letter
else:
count += 1
encode[known + letter] = count
result.append([encode[known] if known else 0, letter])
known = ''
if known:
result.append([encode[known], ''])
return result
def decompress(compressed):
string = ''
decode = {}
known = ''
count = 0
for (code, new) in compressed:
if not code:
count += 1
decode[count] = new
string += new
elif not new:
string += decode[code]
else:
count += 1
known = decode[code]
decode[count] = known + new
string += known + new
return string
if __name__ == '__main__':
main() |
# When one class does the work of two, awkwardness results.
class Person:
def __init__(self, name, office_area_code, office_number):
self.name = name
self.office_area_code = office_area_code
self.office_number = office_number
def telephone_number(self):
return "%d-%d" % (self.office_area_code, self.office_number)
if __name__=="__main__":
p = Person("Mario", 51, 966296636)
print(p.name)
print(p.telephone_number()) | class Person:
def __init__(self, name, office_area_code, office_number):
self.name = name
self.office_area_code = office_area_code
self.office_number = office_number
def telephone_number(self):
return '%d-%d' % (self.office_area_code, self.office_number)
if __name__ == '__main__':
p = person('Mario', 51, 966296636)
print(p.name)
print(p.telephone_number()) |
class Solution(object):
def maxCount(self, m, n, ops):
"""
:type m: int
:type n: int
:type ops: List[List[int]]
:rtype: int
"""
return reduce(operator.mul, map(min, zip(*ops + [[m,n]])))
| class Solution(object):
def max_count(self, m, n, ops):
"""
:type m: int
:type n: int
:type ops: List[List[int]]
:rtype: int
"""
return reduce(operator.mul, map(min, zip(*ops + [[m, n]]))) |
#!/usr/bin/python
# -*- coding: utf-8 -*-
class OpenError(StandardError):
def __init__(self, error_code, error, error_info):
self.error_code = error_code
self.error = error
self.error_info = error_info
StandardError.__init__(self, error)
def __str__(self):
return 'Error: %s: %s, request: %s' % (self.error_code, self.error, self.error_info) | class Openerror(StandardError):
def __init__(self, error_code, error, error_info):
self.error_code = error_code
self.error = error
self.error_info = error_info
StandardError.__init__(self, error)
def __str__(self):
return 'Error: %s: %s, request: %s' % (self.error_code, self.error, self.error_info) |
table = 'fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF'
tr = {}
for i in range(58):
tr[table[i]] = i
s = [11, 10, 3, 8, 4, 6]
xor = 177451812
add = 8728348608
def dec(x):
r = 0
for i in range(6):
r += tr[x[s[i]]] * 58**i
return (r - add) ^ xor
def enc(x):
x = (x ^ xor) + add
r = list('BV1 4 1 7 ')
for i in range(6):
r[s[i]] = table[x // 58**i % 58]
return ''.join(r)
print(dec('BV17x411w7KC'))
print(dec('BV1Q541167Qg'))
print(dec('BV1mK4y1C7Bz'))
print(enc(170001))
print(enc(455017605))
print(enc(882584971)) | table = 'fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF'
tr = {}
for i in range(58):
tr[table[i]] = i
s = [11, 10, 3, 8, 4, 6]
xor = 177451812
add = 8728348608
def dec(x):
r = 0
for i in range(6):
r += tr[x[s[i]]] * 58 ** i
return r - add ^ xor
def enc(x):
x = (x ^ xor) + add
r = list('BV1 4 1 7 ')
for i in range(6):
r[s[i]] = table[x // 58 ** i % 58]
return ''.join(r)
print(dec('BV17x411w7KC'))
print(dec('BV1Q541167Qg'))
print(dec('BV1mK4y1C7Bz'))
print(enc(170001))
print(enc(455017605))
print(enc(882584971)) |
class ConfigException(Exception):
"""Configuration exception when an integration that is not available
is called in the `Config` object.
"""
pass
| class Configexception(Exception):
"""Configuration exception when an integration that is not available
is called in the `Config` object.
"""
pass |
#
# @lc app=leetcode id=838 lang=python3
#
# [838] Push Dominoes
#
# @lc code=start
class Solution:
def pushDominoes(self, dominoes: str) -> str:
l = 0
ans = []
dominoes = 'L' + dominoes + 'R'
for r in range(1, len(dominoes)):
if dominoes[r] == '.':
continue
cnt = r - l - 1
if l > 0:
ans.append(dominoes[l])
if dominoes[l] == dominoes[r]:
ans.append(dominoes[l] * cnt)
elif dominoes[l] == 'L' and dominoes[r] == 'R':
ans.append('.' * cnt)
else:
ans.append('R' * (cnt // 2) + '.' * (cnt % 2) + 'L' * (cnt // 2))
l = r
return ''.join(ans)
if __name__ == '__main__':
a = Solution()
b = a.pushDominoes(".L.R...LR..L..")
print(b)
# @lc code=end
| class Solution:
def push_dominoes(self, dominoes: str) -> str:
l = 0
ans = []
dominoes = 'L' + dominoes + 'R'
for r in range(1, len(dominoes)):
if dominoes[r] == '.':
continue
cnt = r - l - 1
if l > 0:
ans.append(dominoes[l])
if dominoes[l] == dominoes[r]:
ans.append(dominoes[l] * cnt)
elif dominoes[l] == 'L' and dominoes[r] == 'R':
ans.append('.' * cnt)
else:
ans.append('R' * (cnt // 2) + '.' * (cnt % 2) + 'L' * (cnt // 2))
l = r
return ''.join(ans)
if __name__ == '__main__':
a = solution()
b = a.pushDominoes('.L.R...LR..L..')
print(b) |
# Copyright 2020 Google LLC
#
# 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
#
# https://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.
def GetSegmentOfUrl(url: str, prefix: str) -> str:
"""
Get the next segment from url following prefix. The return value is a segment without slash.
For example, url = "projects/test-project/global/networks/n1",
and prefix = "networks/", then the return value is "n1".
"""
if not url: return ""
if not prefix: return ""
if not prefix.endswith("/"): prefix += "/"
offset = url.find(prefix)
if offset == -1: return ""
offset += len(prefix)
end = url.find("/", offset)
if end == -1: end = len(url)
return url[offset:end]
def ParseProjectFromUrl(url: str) -> str:
return GetSegmentOfUrl(url, "projects/")
def ParseNetworkFromUrl(url: str) -> str:
return GetSegmentOfUrl(url, "/networks/")
def ParseRegionFromUrl(url: str) -> str:
return GetSegmentOfUrl(url, "/regions/")
def ParseSubnetFromUrl(url: str) -> str:
return GetSegmentOfUrl(url, "/subnetworks/")
def ParseInstanceFromUrl(url: str) -> str:
return GetSegmentOfUrl(url, "/instances/")
| def get_segment_of_url(url: str, prefix: str) -> str:
"""
Get the next segment from url following prefix. The return value is a segment without slash.
For example, url = "projects/test-project/global/networks/n1",
and prefix = "networks/", then the return value is "n1".
"""
if not url:
return ''
if not prefix:
return ''
if not prefix.endswith('/'):
prefix += '/'
offset = url.find(prefix)
if offset == -1:
return ''
offset += len(prefix)
end = url.find('/', offset)
if end == -1:
end = len(url)
return url[offset:end]
def parse_project_from_url(url: str) -> str:
return get_segment_of_url(url, 'projects/')
def parse_network_from_url(url: str) -> str:
return get_segment_of_url(url, '/networks/')
def parse_region_from_url(url: str) -> str:
return get_segment_of_url(url, '/regions/')
def parse_subnet_from_url(url: str) -> str:
return get_segment_of_url(url, '/subnetworks/')
def parse_instance_from_url(url: str) -> str:
return get_segment_of_url(url, '/instances/') |
# (c) Copyright [2017] Hewlett Packard Enterprise Development LP
#
# 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.
""" Module implements exception classes that can be thrown by the DLBS."""
class DLBSError(Exception):
"""Base class for all exceptions."""
pass
class ConfigurationError(DLBSError):
"""This exception is thrown whenever error is found in an input configuration.
Several examples of situations in which this exception gets thrown:
- Cyclic dependency is found during variable expansion.
- Variable cannot be expanded.
- Un-parsable JSON value found in an input configuration.
"""
pass
class LogicError(DLBSError):
"""This exception indicates a bug in a program.
This exception in theory must never be thrown unless there is a bug in the
program.
"""
pass
| """ Module implements exception classes that can be thrown by the DLBS."""
class Dlbserror(Exception):
"""Base class for all exceptions."""
pass
class Configurationerror(DLBSError):
"""This exception is thrown whenever error is found in an input configuration.
Several examples of situations in which this exception gets thrown:
- Cyclic dependency is found during variable expansion.
- Variable cannot be expanded.
- Un-parsable JSON value found in an input configuration.
"""
pass
class Logicerror(DLBSError):
"""This exception indicates a bug in a program.
This exception in theory must never be thrown unless there is a bug in the
program.
"""
pass |
"""A tool for modeling composite beams and aircraft wings.
``Aerodynamics``
This module provides the aerodynamics models used within AeroComBAT
``AircraftParts``
This module provides a full-fledged wing object that can be used to
determine if a design is both statically adequate as well as stable.
``FEM``
This module provides a finite element model object, intended as a
convenient way for a user to create and model composite structures and
potential flow lifting surfaces.
``Structures``
This module provides the structural models used within AeroComBAT.
""" | """A tool for modeling composite beams and aircraft wings.
``Aerodynamics``
This module provides the aerodynamics models used within AeroComBAT
``AircraftParts``
This module provides a full-fledged wing object that can be used to
determine if a design is both statically adequate as well as stable.
``FEM``
This module provides a finite element model object, intended as a
convenient way for a user to create and model composite structures and
potential flow lifting surfaces.
``Structures``
This module provides the structural models used within AeroComBAT.
""" |
# A Text to Morse Code Converter Project
# Notes:
# This Morse code make use of the basic morse code charts which contains 26 alphabets and 10 numerals
# No special characters are currently involved. But can be added in the '.txt ' file based on the requirement.
MORSE_CODE_CHART = "script_texts.txt"
def load_chart():
"""Loads contents of the text file from the directory and returns the output as a Dictionary."""
with open(file=MORSE_CODE_CHART, mode="r", encoding="utf-8") as file:
# using dictionary comprehension
mc_dict = {line.split(" ")[0]: line.split(" ")[1].strip("\n") for line in file.readlines()}
return mc_dict
def take_user_input():
"""Takes an input from the user and returns it as a STR."""
while True:
print("Please enter the text you want to convert:")
raw_input = input("> ").lower()
# make sure something was entered
if raw_input == "":
print("Please enter some text.")
else:
return raw_input
def main():
# load the chart into a dict
morse_chart = load_chart()
print("Welcome to the Morse code converter.\n")
while True:
# get input from the user
input_text = take_user_input()
converted_text = ""
# process characters
for char in input_text:
# only add valid convertible characters, ignore everything else
if char in morse_chart:
# adding a single space after each character for visibility
converted_text += morse_chart[char] + " "
# check for empty output
if len(converted_text) > 0:
print(f"Your input in morse code: {converted_text}")
else:
print("The input did not contain any convertible character.")
# asking the user for a condition to break out of the loop
print("Do you want to convert something else? (y/n)")
if input("> ").lower() == "n":
break
print("Goodbye.")
if __name__ == "__main__":
main() | morse_code_chart = 'script_texts.txt'
def load_chart():
"""Loads contents of the text file from the directory and returns the output as a Dictionary."""
with open(file=MORSE_CODE_CHART, mode='r', encoding='utf-8') as file:
mc_dict = {line.split(' ')[0]: line.split(' ')[1].strip('\n') for line in file.readlines()}
return mc_dict
def take_user_input():
"""Takes an input from the user and returns it as a STR."""
while True:
print('Please enter the text you want to convert:')
raw_input = input('> ').lower()
if raw_input == '':
print('Please enter some text.')
else:
return raw_input
def main():
morse_chart = load_chart()
print('Welcome to the Morse code converter.\n')
while True:
input_text = take_user_input()
converted_text = ''
for char in input_text:
if char in morse_chart:
converted_text += morse_chart[char] + ' '
if len(converted_text) > 0:
print(f'Your input in morse code: {converted_text}')
else:
print('The input did not contain any convertible character.')
print('Do you want to convert something else? (y/n)')
if input('> ').lower() == 'n':
break
print('Goodbye.')
if __name__ == '__main__':
main() |
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def count_univals(node):
if node.right is None and node.left is None:
return node.val, True, 1
l_val, l_is_unival, l_univals = count_univals(node.left)
r_val, r_is_unival, r_univals = count_univals(node.right)
return (
node.val,
l_val == r_val and l_val == node.val and l_is_unival and r_is_unival,
l_univals + r_univals + (l_val == r_val and l_val == node.val and l_is_unival and r_is_unival)
)
if __name__ == "__main__":
root = Node(0,
Node(1),
Node(0,
Node(1,
Node(1,
Node(1), Node(1)
),
Node(1,
Node(0), Node(1)
)
),
Node(0)
)
)
_, _, univals = count_univals(root)
print(f"univals = {univals}")
| class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def count_univals(node):
if node.right is None and node.left is None:
return (node.val, True, 1)
(l_val, l_is_unival, l_univals) = count_univals(node.left)
(r_val, r_is_unival, r_univals) = count_univals(node.right)
return (node.val, l_val == r_val and l_val == node.val and l_is_unival and r_is_unival, l_univals + r_univals + (l_val == r_val and l_val == node.val and l_is_unival and r_is_unival))
if __name__ == '__main__':
root = node(0, node(1), node(0, node(1, node(1, node(1), node(1)), node(1, node(0), node(1))), node(0)))
(_, _, univals) = count_univals(root)
print(f'univals = {univals}') |
def naive(a, b):
c = 0
while a > 0:
c = c + b
a = a - 1
return c
def russian(a, b):
"""
The Russian Peasant Algorithm:
Multiply one integer by the other integer.
Input: a, b: integers
Returns: a*b
"""
c = 0
while a > 0:
if a % 2 == 1:
c = c + b
b = b << 1
a = a >> 1
return c
def rec_russian(a, b):
if a == 0:
return 0
elif a % 2 == 0:
return 2 * rec_russian(a / 2, b)
else:
return b + 2 * rec_russian((a - 1) / 2, b)
| def naive(a, b):
c = 0
while a > 0:
c = c + b
a = a - 1
return c
def russian(a, b):
"""
The Russian Peasant Algorithm:
Multiply one integer by the other integer.
Input: a, b: integers
Returns: a*b
"""
c = 0
while a > 0:
if a % 2 == 1:
c = c + b
b = b << 1
a = a >> 1
return c
def rec_russian(a, b):
if a == 0:
return 0
elif a % 2 == 0:
return 2 * rec_russian(a / 2, b)
else:
return b + 2 * rec_russian((a - 1) / 2, b) |
# Python Tuples
# Ordered, Immutable collection of items which allows Duplicate Members
# We can put the data, which will not change throughout the program, in a Tuple
# Tuples can be called as "Immutable Python Lists" or "Constant Python Lists"
employeeTuple = ("Sam", "Sam" "Mike", "John", "Harry", "Tom", "Sean", "Justin")
# to check the variable type
print(type(employeeTuple))
# to check whether the type is "Tuple" or not
print(isinstance(employeeTuple, tuple))
# to print all the elements in the Tuple
for employeeName in employeeTuple:
print("Employee: " + employeeName)
print("**********************************************************")
# Other functions
# to display an element using index
print(employeeTuple[0])
# to display the length of the Tuple
print(len(employeeTuple))
# employeeTuple[2] = "David" # This will throw a TypeError since Tuple cannot be modified
print(employeeTuple)
print("**********************************************************")
# we can use the tuple() constructor to create a tuple
employeeName2 = tuple(("Richard", "Henry", "Brian"))
print(employeeName2)
# we can also omit the use of brackets to create a tuple
employeeName3 = "David", "Michael", "Shaun"
print(employeeName3)
print(type(employeeName3))
print("**********************************************************")
# Difference between a Tuple and a String
myStr = ("Sam") # This is a String
print(type(myStr))
# This is a Tuple (for a Tuple, comma is mandatory) with one item
myTuple1 = ("Sam",)
print(type(myTuple1))
print(len(myTuple1))
# This is an empty Tuple
myTuple2 = ()
print(type(myTuple2))
print(len(myTuple2))
print("**********************************************************")
# Value Swapping using Tuple
myNumber1 = 2
myNumber2 = 3
myNumber1, myNumber2 = myNumber2, myNumber1
print(myNumber1)
print(myNumber2)
print("**********************************************************")
# Nested Tuples
employeeName4 = employeeName3, ("Raj", "Vinith")
print(employeeName4)
print("**********************************************************")
# Tuple Sequence Packing
packed_tuple = 1, 2, "Python"
print(packed_tuple)
# Tuple Sequence Unpacking
number1, number2, string1 = packed_tuple
print(number1)
print(number2)
print(string1)
print("**********************************************************")
| employee_tuple = ('Sam', 'SamMike', 'John', 'Harry', 'Tom', 'Sean', 'Justin')
print(type(employeeTuple))
print(isinstance(employeeTuple, tuple))
for employee_name in employeeTuple:
print('Employee: ' + employeeName)
print('**********************************************************')
print(employeeTuple[0])
print(len(employeeTuple))
print(employeeTuple)
print('**********************************************************')
employee_name2 = tuple(('Richard', 'Henry', 'Brian'))
print(employeeName2)
employee_name3 = ('David', 'Michael', 'Shaun')
print(employeeName3)
print(type(employeeName3))
print('**********************************************************')
my_str = 'Sam'
print(type(myStr))
my_tuple1 = ('Sam',)
print(type(myTuple1))
print(len(myTuple1))
my_tuple2 = ()
print(type(myTuple2))
print(len(myTuple2))
print('**********************************************************')
my_number1 = 2
my_number2 = 3
(my_number1, my_number2) = (myNumber2, myNumber1)
print(myNumber1)
print(myNumber2)
print('**********************************************************')
employee_name4 = (employeeName3, ('Raj', 'Vinith'))
print(employeeName4)
print('**********************************************************')
packed_tuple = (1, 2, 'Python')
print(packed_tuple)
(number1, number2, string1) = packed_tuple
print(number1)
print(number2)
print(string1)
print('**********************************************************') |
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: tflite
class BuiltinOperator(object):
ADD = 0
AVERAGE_POOL_2D = 1
CONCATENATION = 2
CONV_2D = 3
DEPTHWISE_CONV_2D = 4
EMBEDDING_LOOKUP = 7
FULLY_CONNECTED = 9
HASHTABLE_LOOKUP = 10
L2_NORMALIZATION = 11
L2_POOL_2D = 12
LOCAL_RESPONSE_NORMALIZATION = 13
LOGISTIC = 14
LSH_PROJECTION = 15
LSTM = 16
MAX_POOL_2D = 17
RELU = 19
RELU6 = 21
RESHAPE = 22
RESIZE_BILINEAR = 23
RNN = 24
SOFTMAX = 25
SPACE_TO_DEPTH = 26
SVDF = 27
TANH = 28
CONCAT_EMBEDDINGS = 29
SKIP_GRAM = 30
CALL = 31
CUSTOM = 32
| class Builtinoperator(object):
add = 0
average_pool_2_d = 1
concatenation = 2
conv_2_d = 3
depthwise_conv_2_d = 4
embedding_lookup = 7
fully_connected = 9
hashtable_lookup = 10
l2_normalization = 11
l2_pool_2_d = 12
local_response_normalization = 13
logistic = 14
lsh_projection = 15
lstm = 16
max_pool_2_d = 17
relu = 19
relu6 = 21
reshape = 22
resize_bilinear = 23
rnn = 24
softmax = 25
space_to_depth = 26
svdf = 27
tanh = 28
concat_embeddings = 29
skip_gram = 30
call = 31
custom = 32 |
class Table(object):
def __init__(self, name):
self.name = name
self.columns = []
def createColumn(self, column):
self.columns.append(column)
def readColumn(self, name):
for value in self.columns:
if value.name == name:
return value
def updateColumn(self, name, column):
for i in range(0,len(self.columns)):
if self.columns[i].name == name:
self.columns[i] = column
break
def deleteColumn(self, name):
for i in range(0, len(self.columns)):
if self.columns[i].name == name:
del self.columns[i]
break
| class Table(object):
def __init__(self, name):
self.name = name
self.columns = []
def create_column(self, column):
self.columns.append(column)
def read_column(self, name):
for value in self.columns:
if value.name == name:
return value
def update_column(self, name, column):
for i in range(0, len(self.columns)):
if self.columns[i].name == name:
self.columns[i] = column
break
def delete_column(self, name):
for i in range(0, len(self.columns)):
if self.columns[i].name == name:
del self.columns[i]
break |
class Config:
api_host = "https://api.frame.io"
default_page_size = 50
default_concurrency = 5
| class Config:
api_host = 'https://api.frame.io'
default_page_size = 50
default_concurrency = 5 |
"""
Profile ../profile-datasets-py/div83/073.py
file automaticaly created by prof_gen.py script
"""
self["ID"] = "../profile-datasets-py/div83/073.py"
self["Q"] = numpy.array([ 1.956946, 2.801132, 4.230252, 5.419981, 6.087733,
6.419039, 6.547807, 6.548787, 6.504738, 6.432189,
6.370779, 6.31601 , 6.30854 , 6.30967 , 6.3021 ,
6.284641, 6.249721, 6.198102, 6.145852, 6.099373,
6.058663, 5.986194, 5.884295, 5.747187, 5.574639,
5.373091, 5.135734, 4.845567, 4.50543 , 4.128883,
3.740616, 3.373579, 3.08385 , 2.839622, 2.645253,
2.513544, 2.431584, 2.357084, 2.259045, 2.163875,
2.110346, 2.096796, 2.099166, 2.141685, 2.178575,
2.199215, 2.274125, 2.462204, 2.771892, 3.16592 ,
3.663737, 4.257632, 4.884156, 6.018014, 7.350006,
8.070105, 8.34401 , 8.37078 , 8.312201, 8.323041,
8.553217, 9.130147, 10.2062 , 11.93486 , 14.44259 ,
17.91218 , 22.60939 , 28.81827 , 34.92618 , 38.93378 ,
56.09235 , 71.77225 , 85.79204 , 102.7434 , 118.9449 ,
125.5382 , 132.4874 , 122.411 , 122.1301 , 128.6215 ,
118.193 , 100.195 , 96.30662 , 102.0976 , 123.4148 ,
225.838 , 205.4768 , 199.0024 , 192.8198 , 186.9111 ,
181.2631 , 175.8601 , 170.6889 , 165.7365 , 160.9931 ,
156.4465 , 152.0869 , 147.9041 , 143.8903 , 140.0354 ,
136.3324 ])
self["P"] = numpy.array([ 5.00000000e-03, 1.61000000e-02, 3.84000000e-02,
7.69000000e-02, 1.37000000e-01, 2.24400000e-01,
3.45400000e-01, 5.06400000e-01, 7.14000000e-01,
9.75300000e-01, 1.29720000e+00, 1.68720000e+00,
2.15260000e+00, 2.70090000e+00, 3.33980000e+00,
4.07700000e+00, 4.92040000e+00, 5.87760000e+00,
6.95670000e+00, 8.16550000e+00, 9.51190000e+00,
1.10038000e+01, 1.26492000e+01, 1.44559000e+01,
1.64318000e+01, 1.85847000e+01, 2.09224000e+01,
2.34526000e+01, 2.61829000e+01, 2.91210000e+01,
3.22744000e+01, 3.56505000e+01, 3.92566000e+01,
4.31001000e+01, 4.71882000e+01, 5.15278000e+01,
5.61260000e+01, 6.09895000e+01, 6.61253000e+01,
7.15398000e+01, 7.72396000e+01, 8.32310000e+01,
8.95204000e+01, 9.61138000e+01, 1.03017000e+02,
1.10237000e+02, 1.17778000e+02, 1.25646000e+02,
1.33846000e+02, 1.42385000e+02, 1.51266000e+02,
1.60496000e+02, 1.70078000e+02, 1.80018000e+02,
1.90320000e+02, 2.00989000e+02, 2.12028000e+02,
2.23442000e+02, 2.35234000e+02, 2.47408000e+02,
2.59969000e+02, 2.72919000e+02, 2.86262000e+02,
3.00000000e+02, 3.14137000e+02, 3.28675000e+02,
3.43618000e+02, 3.58966000e+02, 3.74724000e+02,
3.90893000e+02, 4.07474000e+02, 4.24470000e+02,
4.41882000e+02, 4.59712000e+02, 4.77961000e+02,
4.96630000e+02, 5.15720000e+02, 5.35232000e+02,
5.55167000e+02, 5.75525000e+02, 5.96306000e+02,
6.17511000e+02, 6.39140000e+02, 6.61192000e+02,
6.83667000e+02, 7.06565000e+02, 7.29886000e+02,
7.53628000e+02, 7.77790000e+02, 8.02371000e+02,
8.27371000e+02, 8.52788000e+02, 8.78620000e+02,
9.04866000e+02, 9.31524000e+02, 9.58591000e+02,
9.86067000e+02, 1.01395000e+03, 1.04223000e+03,
1.07092000e+03, 1.10000000e+03])
self["CO2"] = numpy.array([ 373.9833, 373.985 , 373.9884, 373.995 , 374.0057, 374.0216,
374.0366, 374.0466, 374.0776, 374.1326, 374.2046, 374.2866,
374.3886, 374.5236, 374.6526, 374.7416, 374.8237, 374.8957,
374.9497, 374.9817, 374.9777, 374.8958, 374.7168, 374.3068,
373.8689, 373.399 , 373.1931, 373.0142, 372.9923, 372.9705,
372.9696, 372.9687, 372.9958, 373.0249, 373.093 , 373.1831,
373.3081, 373.5051, 373.7122, 374.0992, 374.5252, 375.0212,
375.5992, 376.2002, 376.6862, 377.1942, 377.6051, 377.9581,
378.329 , 378.7248, 379.1366, 379.5774, 380.0341, 380.4167,
380.7802, 381.0429, 381.2468, 381.3648, 381.4278, 381.4508,
381.4547, 381.4305, 381.3971, 381.3314, 381.2585, 381.1682,
381.0824, 381.001 , 380.9507, 380.9132, 380.8856, 380.8667,
380.8483, 380.8259, 380.7977, 380.7672, 380.7296, 380.6944,
380.6635, 380.66 , 380.705 , 380.7848, 380.8093, 380.8081,
380.801 , 380.763 , 380.7717, 380.7742, 380.7766, 380.7788,
380.781 , 380.783 , 380.785 , 380.7869, 380.7887, 380.7904,
380.7921, 380.7937, 380.7952, 380.7967, 380.7981])
self["CO"] = numpy.array([ 3.371623 , 3.275051 , 3.089317 , 2.793105 , 2.386455 ,
1.898358 , 1.286632 , 0.6786696 , 0.2446264 , 0.1117883 ,
0.07406993, 0.06797857, 0.06665738, 0.06541499, 0.0627382 ,
0.05708244, 0.05198118, 0.0482764 , 0.04517182, 0.04224734,
0.04012826, 0.03841507, 0.03688128, 0.0355552 , 0.035034 ,
0.03503531, 0.03689901, 0.03936141, 0.0440788 , 0.0492937 ,
0.04925202, 0.04920743, 0.04473116, 0.04025199, 0.0366714 ,
0.03351052, 0.03137962, 0.03123803, 0.03108933, 0.03244993,
0.03412033, 0.03639812, 0.03949292, 0.04300421, 0.0464721 ,
0.05039819, 0.05490918, 0.06008545, 0.06627392, 0.07433206,
0.08375509, 0.0936498 , 0.1051005 , 0.1153623 , 0.1259091 ,
0.1348409 , 0.1428668 , 0.1493407 , 0.1547317 , 0.1586747 ,
0.1618646 , 0.1637585 , 0.1653183 , 0.165877 , 0.1662896 ,
0.166244 , 0.1661372 , 0.1659742 , 0.1657402 , 0.1654906 ,
0.1652257 , 0.1649732 , 0.1647089 , 0.1644201 , 0.1640755 ,
0.1636954 , 0.1632974 , 0.1629001 , 0.1624932 , 0.1620122 ,
0.1613979 , 0.1608719 , 0.1609615 , 0.1616045 , 0.162019 ,
0.1622284 , 0.1622896 , 0.1621097 , 0.1619268 , 0.1617408 ,
0.1615517 , 0.1613596 , 0.1611645 , 0.1609663 , 0.1607661 ,
0.1605619 , 0.1603556 , 0.1601463 , 0.159934 , 0.1597186 ,
0.1595013 ])
self["T"] = numpy.array([ 182.651, 193.018, 211.533, 232.314, 250.519, 264.537,
275.437, 284.487, 292.885, 299.567, 304.326, 304.11 ,
298.775, 290.318, 281.349, 274.469, 269.03 , 262.729,
255.232, 247.095, 239.554, 233.573, 228.85 , 225.016,
221.726, 218.548, 214.604, 211.054, 207.796, 204.77 ,
202.096, 200.364, 198.049, 195.456, 192.937, 190.933,
189.903, 190.14 , 191.564, 193.628, 195.422, 195.904,
194.759, 193.011, 191.99 , 192.292, 193.427, 194.638,
195.439, 196.086, 196.942, 197.885, 198.685, 199.239,
199.659, 200.124, 200.563, 200.928, 201.22 , 201.562,
202.071, 202.831, 203.902, 205.287, 206.924, 208.756,
210.742, 212.832, 214.977, 217.117, 219.157, 221.102,
223.008, 224.906, 226.796, 228.809, 230.866, 232.815,
234.6 , 236.299, 237.853, 239.205, 240.549, 241.851,
242.628, 240.741, 240.155, 240.155, 240.155, 240.155,
240.155, 240.155, 240.155, 240.155, 240.155, 240.155,
240.155, 240.155, 240.155, 240.155, 240.155])
self["N2O"] = numpy.array([ 1.07999800e-03, 8.19997700e-04, 6.29997300e-04,
4.79997400e-04, 3.49997900e-04, 2.49998400e-04,
2.49998400e-04, 4.39997100e-04, 1.14999300e-03,
1.39999100e-03, 3.20998000e-03, 5.38996600e-03,
7.70995100e-03, 9.55994000e-03, 1.17199300e-02,
1.49099100e-02, 1.73398900e-02, 1.84498900e-02,
1.95798800e-02, 2.11198700e-02, 2.25798600e-02,
2.06298800e-02, 1.70899000e-02, 1.36999200e-02,
1.13299400e-02, 9.15995100e-03, 7.07996400e-03,
6.14997000e-03, 5.60997500e-03, 5.08997900e-03,
5.26998000e-03, 8.14997300e-03, 1.09399700e-02,
1.36499600e-02, 1.70299500e-02, 2.36499400e-02,
3.00799300e-02, 3.63299100e-02, 6.36398600e-02,
9.82897900e-02, 1.31219700e-01, 1.68939600e-01,
2.03099600e-01, 2.35689500e-01, 2.62639400e-01,
2.85029400e-01, 3.02059300e-01, 3.12939200e-01,
3.16769100e-01, 3.16769000e-01, 3.16768800e-01,
3.16768700e-01, 3.16768500e-01, 3.16768100e-01,
3.16767700e-01, 3.16767400e-01, 3.16767400e-01,
3.16767300e-01, 3.16767400e-01, 3.16767400e-01,
3.16767300e-01, 3.16767100e-01, 3.16766800e-01,
3.16766200e-01, 3.16765400e-01, 3.16764300e-01,
3.16762800e-01, 3.16760900e-01, 3.16758900e-01,
3.16757700e-01, 3.16752200e-01, 3.16747300e-01,
3.16742800e-01, 3.16737500e-01, 3.16732300e-01,
3.16730200e-01, 3.16728000e-01, 3.16731200e-01,
3.16731300e-01, 3.16729300e-01, 3.16732600e-01,
3.16738300e-01, 3.16739500e-01, 3.16737700e-01,
3.16730900e-01, 3.16698500e-01, 3.16704900e-01,
3.16707000e-01, 3.16708900e-01, 3.16710800e-01,
3.16712600e-01, 3.16714300e-01, 3.16715900e-01,
3.16717500e-01, 3.16719000e-01, 3.16720400e-01,
3.16721800e-01, 3.16723100e-01, 3.16724400e-01,
3.16725600e-01, 3.16726800e-01])
self["O3"] = numpy.array([ 1.092958 , 0.9333394 , 0.7369399 , 0.7964717 , 0.9379673 ,
1.079703 , 1.237282 , 1.401171 , 1.54559 , 1.718999 ,
1.962487 , 2.289906 , 2.740603 , 3.343639 , 4.033965 ,
4.681221 , 5.141878 , 5.436586 , 5.582286 , 5.602026 ,
5.534786 , 5.136629 , 4.572073 , 3.916747 , 3.242732 ,
2.627226 , 2.238409 , 1.97481 , 1.707352 , 1.378664 ,
0.9718754 , 0.4739234 , 0.1691735 , 0.07579148, 0.06013094,
0.06060745, 0.06021215, 0.05955906, 0.06177556, 0.07662733,
0.1108608 , 0.1167128 , 0.07390804, 0.05683548, 0.05512018,
0.06082157, 0.08559211, 0.1410637 , 0.2397043 , 0.2934931 ,
0.3111259 , 0.3108367 , 0.2986955 , 0.2690934 , 0.2461522 ,
0.2268442 , 0.1992463 , 0.1731716 , 0.1505927 , 0.124096 ,
0.09637658, 0.07470752, 0.06088038, 0.05258867, 0.04738112,
0.04395351, 0.04182795, 0.04072743, 0.04045889, 0.0410274 ,
0.0409915 , 0.03975355, 0.03971269, 0.04038045, 0.04089773,
0.04011796, 0.03950926, 0.0416304 , 0.04225274, 0.03989827,
0.03871712, 0.03680791, 0.03578315, 0.03928659, 0.04175655,
0.04199231, 0.0311443 , 0.0311445 , 0.03114469, 0.03114488,
0.03114505, 0.03114522, 0.03114538, 0.03114554, 0.03114568,
0.03114583, 0.03114596, 0.03114609, 0.03114622, 0.03114634,
0.03114645])
self["CH4"] = numpy.array([ 0.0996805, 0.1110867, 0.1195645, 0.1268483, 0.1474111,
0.1701019, 0.1716519, 0.1735449, 0.1782488, 0.1907058,
0.2214456, 0.2588824, 0.2996521, 0.3522618, 0.4052884,
0.4652571, 0.5254507, 0.5900453, 0.652122 , 0.7166726,
0.7781653, 0.834089 , 0.8861858, 0.9360986, 0.9791765,
1.019945 , 1.059185 , 1.097075 , 1.133645 , 1.169365 ,
1.207695 , 1.248736 , 1.292576 , 1.332766 , 1.371486 ,
1.408036 , 1.441656 , 1.471497 , 1.485487 , 1.500237 ,
1.515757 , 1.532077 , 1.549197 , 1.566077 , 1.580627 ,
1.595846 , 1.611256 , 1.627016 , 1.642985 , 1.658145 ,
1.673924 , 1.688113 , 1.702712 , 1.71622 , 1.729587 ,
1.739776 , 1.747785 , 1.752725 , 1.755075 , 1.756095 ,
1.756145 , 1.755794 , 1.755242 , 1.754189 , 1.753005 ,
1.751649 , 1.75037 , 1.74924 , 1.748419 , 1.747772 ,
1.747412 , 1.747125 , 1.74691 , 1.746811 , 1.746822 ,
1.746941 , 1.747158 , 1.747506 , 1.747867 , 1.748135 ,
1.748353 , 1.748495 , 1.748612 , 1.748701 , 1.748684 ,
1.748515 , 1.748561 , 1.748572 , 1.748593 , 1.748603 ,
1.748613 , 1.748622 , 1.748631 , 1.74864 , 1.748648 ,
1.748656 , 1.748664 , 1.748671 , 1.748678 , 1.748685 ,
1.748692 ])
self["CTP"] = 500.0
self["CFRACTION"] = 0.0
self["IDG"] = 0
self["ISH"] = 0
self["ELEVATION"] = 0.0
self["S2M"]["T"] = 240.155
self["S2M"]["Q"] = 136.332410939
self["S2M"]["O"] = 0.03114645315
self["S2M"]["P"] = 717.06042
self["S2M"]["U"] = 0.0
self["S2M"]["V"] = 0.0
self["S2M"]["WFETC"] = 100000.0
self["SKIN"]["SURFTYPE"] = 0
self["SKIN"]["WATERTYPE"] = 1
self["SKIN"]["T"] = 240.155
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"] = 0.0
self["AZANGLE"] = 0.0
self["SUNZENANGLE"] = 0.0
self["SUNAZANGLE"] = 0.0
self["LATITUDE"] = -74.316
self["GAS_UNITS"] = 2
self["BE"] = 0.0
self["COSBK"] = 0.0
self["DATE"] = numpy.array([2006, 10, 20])
self["TIME"] = numpy.array([0, 0, 0])
| """
Profile ../profile-datasets-py/div83/073.py
file automaticaly created by prof_gen.py script
"""
self['ID'] = '../profile-datasets-py/div83/073.py'
self['Q'] = numpy.array([1.956946, 2.801132, 4.230252, 5.419981, 6.087733, 6.419039, 6.547807, 6.548787, 6.504738, 6.432189, 6.370779, 6.31601, 6.30854, 6.30967, 6.3021, 6.284641, 6.249721, 6.198102, 6.145852, 6.099373, 6.058663, 5.986194, 5.884295, 5.747187, 5.574639, 5.373091, 5.135734, 4.845567, 4.50543, 4.128883, 3.740616, 3.373579, 3.08385, 2.839622, 2.645253, 2.513544, 2.431584, 2.357084, 2.259045, 2.163875, 2.110346, 2.096796, 2.099166, 2.141685, 2.178575, 2.199215, 2.274125, 2.462204, 2.771892, 3.16592, 3.663737, 4.257632, 4.884156, 6.018014, 7.350006, 8.070105, 8.34401, 8.37078, 8.312201, 8.323041, 8.553217, 9.130147, 10.2062, 11.93486, 14.44259, 17.91218, 22.60939, 28.81827, 34.92618, 38.93378, 56.09235, 71.77225, 85.79204, 102.7434, 118.9449, 125.5382, 132.4874, 122.411, 122.1301, 128.6215, 118.193, 100.195, 96.30662, 102.0976, 123.4148, 225.838, 205.4768, 199.0024, 192.8198, 186.9111, 181.2631, 175.8601, 170.6889, 165.7365, 160.9931, 156.4465, 152.0869, 147.9041, 143.8903, 140.0354, 136.3324])
self['P'] = numpy.array([0.005, 0.0161, 0.0384, 0.0769, 0.137, 0.2244, 0.3454, 0.5064, 0.714, 0.9753, 1.2972, 1.6872, 2.1526, 2.7009, 3.3398, 4.077, 4.9204, 5.8776, 6.9567, 8.1655, 9.5119, 11.0038, 12.6492, 14.4559, 16.4318, 18.5847, 20.9224, 23.4526, 26.1829, 29.121, 32.2744, 35.6505, 39.2566, 43.1001, 47.1882, 51.5278, 56.126, 60.9895, 66.1253, 71.5398, 77.2396, 83.231, 89.5204, 96.1138, 103.017, 110.237, 117.778, 125.646, 133.846, 142.385, 151.266, 160.496, 170.078, 180.018, 190.32, 200.989, 212.028, 223.442, 235.234, 247.408, 259.969, 272.919, 286.262, 300.0, 314.137, 328.675, 343.618, 358.966, 374.724, 390.893, 407.474, 424.47, 441.882, 459.712, 477.961, 496.63, 515.72, 535.232, 555.167, 575.525, 596.306, 617.511, 639.14, 661.192, 683.667, 706.565, 729.886, 753.628, 777.79, 802.371, 827.371, 852.788, 878.62, 904.866, 931.524, 958.591, 986.067, 1013.95, 1042.23, 1070.92, 1100.0])
self['CO2'] = numpy.array([373.9833, 373.985, 373.9884, 373.995, 374.0057, 374.0216, 374.0366, 374.0466, 374.0776, 374.1326, 374.2046, 374.2866, 374.3886, 374.5236, 374.6526, 374.7416, 374.8237, 374.8957, 374.9497, 374.9817, 374.9777, 374.8958, 374.7168, 374.3068, 373.8689, 373.399, 373.1931, 373.0142, 372.9923, 372.9705, 372.9696, 372.9687, 372.9958, 373.0249, 373.093, 373.1831, 373.3081, 373.5051, 373.7122, 374.0992, 374.5252, 375.0212, 375.5992, 376.2002, 376.6862, 377.1942, 377.6051, 377.9581, 378.329, 378.7248, 379.1366, 379.5774, 380.0341, 380.4167, 380.7802, 381.0429, 381.2468, 381.3648, 381.4278, 381.4508, 381.4547, 381.4305, 381.3971, 381.3314, 381.2585, 381.1682, 381.0824, 381.001, 380.9507, 380.9132, 380.8856, 380.8667, 380.8483, 380.8259, 380.7977, 380.7672, 380.7296, 380.6944, 380.6635, 380.66, 380.705, 380.7848, 380.8093, 380.8081, 380.801, 380.763, 380.7717, 380.7742, 380.7766, 380.7788, 380.781, 380.783, 380.785, 380.7869, 380.7887, 380.7904, 380.7921, 380.7937, 380.7952, 380.7967, 380.7981])
self['CO'] = numpy.array([3.371623, 3.275051, 3.089317, 2.793105, 2.386455, 1.898358, 1.286632, 0.6786696, 0.2446264, 0.1117883, 0.07406993, 0.06797857, 0.06665738, 0.06541499, 0.0627382, 0.05708244, 0.05198118, 0.0482764, 0.04517182, 0.04224734, 0.04012826, 0.03841507, 0.03688128, 0.0355552, 0.035034, 0.03503531, 0.03689901, 0.03936141, 0.0440788, 0.0492937, 0.04925202, 0.04920743, 0.04473116, 0.04025199, 0.0366714, 0.03351052, 0.03137962, 0.03123803, 0.03108933, 0.03244993, 0.03412033, 0.03639812, 0.03949292, 0.04300421, 0.0464721, 0.05039819, 0.05490918, 0.06008545, 0.06627392, 0.07433206, 0.08375509, 0.0936498, 0.1051005, 0.1153623, 0.1259091, 0.1348409, 0.1428668, 0.1493407, 0.1547317, 0.1586747, 0.1618646, 0.1637585, 0.1653183, 0.165877, 0.1662896, 0.166244, 0.1661372, 0.1659742, 0.1657402, 0.1654906, 0.1652257, 0.1649732, 0.1647089, 0.1644201, 0.1640755, 0.1636954, 0.1632974, 0.1629001, 0.1624932, 0.1620122, 0.1613979, 0.1608719, 0.1609615, 0.1616045, 0.162019, 0.1622284, 0.1622896, 0.1621097, 0.1619268, 0.1617408, 0.1615517, 0.1613596, 0.1611645, 0.1609663, 0.1607661, 0.1605619, 0.1603556, 0.1601463, 0.159934, 0.1597186, 0.1595013])
self['T'] = numpy.array([182.651, 193.018, 211.533, 232.314, 250.519, 264.537, 275.437, 284.487, 292.885, 299.567, 304.326, 304.11, 298.775, 290.318, 281.349, 274.469, 269.03, 262.729, 255.232, 247.095, 239.554, 233.573, 228.85, 225.016, 221.726, 218.548, 214.604, 211.054, 207.796, 204.77, 202.096, 200.364, 198.049, 195.456, 192.937, 190.933, 189.903, 190.14, 191.564, 193.628, 195.422, 195.904, 194.759, 193.011, 191.99, 192.292, 193.427, 194.638, 195.439, 196.086, 196.942, 197.885, 198.685, 199.239, 199.659, 200.124, 200.563, 200.928, 201.22, 201.562, 202.071, 202.831, 203.902, 205.287, 206.924, 208.756, 210.742, 212.832, 214.977, 217.117, 219.157, 221.102, 223.008, 224.906, 226.796, 228.809, 230.866, 232.815, 234.6, 236.299, 237.853, 239.205, 240.549, 241.851, 242.628, 240.741, 240.155, 240.155, 240.155, 240.155, 240.155, 240.155, 240.155, 240.155, 240.155, 240.155, 240.155, 240.155, 240.155, 240.155, 240.155])
self['N2O'] = numpy.array([0.001079998, 0.0008199977, 0.0006299973, 0.0004799974, 0.0003499979, 0.0002499984, 0.0002499984, 0.0004399971, 0.001149993, 0.001399991, 0.00320998, 0.005389966, 0.007709951, 0.00955994, 0.01171993, 0.01490991, 0.01733989, 0.01844989, 0.01957988, 0.02111987, 0.02257986, 0.02062988, 0.0170899, 0.01369992, 0.01132994, 0.009159951, 0.007079964, 0.00614997, 0.005609975, 0.005089979, 0.00526998, 0.008149973, 0.01093997, 0.01364996, 0.01702995, 0.02364994, 0.03007993, 0.03632991, 0.06363986, 0.09828979, 0.1312197, 0.1689396, 0.2030996, 0.2356895, 0.2626394, 0.2850294, 0.3020593, 0.3129392, 0.3167691, 0.316769, 0.3167688, 0.3167687, 0.3167685, 0.3167681, 0.3167677, 0.3167674, 0.3167674, 0.3167673, 0.3167674, 0.3167674, 0.3167673, 0.3167671, 0.3167668, 0.3167662, 0.3167654, 0.3167643, 0.3167628, 0.3167609, 0.3167589, 0.3167577, 0.3167522, 0.3167473, 0.3167428, 0.3167375, 0.3167323, 0.3167302, 0.316728, 0.3167312, 0.3167313, 0.3167293, 0.3167326, 0.3167383, 0.3167395, 0.3167377, 0.3167309, 0.3166985, 0.3167049, 0.316707, 0.3167089, 0.3167108, 0.3167126, 0.3167143, 0.3167159, 0.3167175, 0.316719, 0.3167204, 0.3167218, 0.3167231, 0.3167244, 0.3167256, 0.3167268])
self['O3'] = numpy.array([1.092958, 0.9333394, 0.7369399, 0.7964717, 0.9379673, 1.079703, 1.237282, 1.401171, 1.54559, 1.718999, 1.962487, 2.289906, 2.740603, 3.343639, 4.033965, 4.681221, 5.141878, 5.436586, 5.582286, 5.602026, 5.534786, 5.136629, 4.572073, 3.916747, 3.242732, 2.627226, 2.238409, 1.97481, 1.707352, 1.378664, 0.9718754, 0.4739234, 0.1691735, 0.07579148, 0.06013094, 0.06060745, 0.06021215, 0.05955906, 0.06177556, 0.07662733, 0.1108608, 0.1167128, 0.07390804, 0.05683548, 0.05512018, 0.06082157, 0.08559211, 0.1410637, 0.2397043, 0.2934931, 0.3111259, 0.3108367, 0.2986955, 0.2690934, 0.2461522, 0.2268442, 0.1992463, 0.1731716, 0.1505927, 0.124096, 0.09637658, 0.07470752, 0.06088038, 0.05258867, 0.04738112, 0.04395351, 0.04182795, 0.04072743, 0.04045889, 0.0410274, 0.0409915, 0.03975355, 0.03971269, 0.04038045, 0.04089773, 0.04011796, 0.03950926, 0.0416304, 0.04225274, 0.03989827, 0.03871712, 0.03680791, 0.03578315, 0.03928659, 0.04175655, 0.04199231, 0.0311443, 0.0311445, 0.03114469, 0.03114488, 0.03114505, 0.03114522, 0.03114538, 0.03114554, 0.03114568, 0.03114583, 0.03114596, 0.03114609, 0.03114622, 0.03114634, 0.03114645])
self['CH4'] = numpy.array([0.0996805, 0.1110867, 0.1195645, 0.1268483, 0.1474111, 0.1701019, 0.1716519, 0.1735449, 0.1782488, 0.1907058, 0.2214456, 0.2588824, 0.2996521, 0.3522618, 0.4052884, 0.4652571, 0.5254507, 0.5900453, 0.652122, 0.7166726, 0.7781653, 0.834089, 0.8861858, 0.9360986, 0.9791765, 1.019945, 1.059185, 1.097075, 1.133645, 1.169365, 1.207695, 1.248736, 1.292576, 1.332766, 1.371486, 1.408036, 1.441656, 1.471497, 1.485487, 1.500237, 1.515757, 1.532077, 1.549197, 1.566077, 1.580627, 1.595846, 1.611256, 1.627016, 1.642985, 1.658145, 1.673924, 1.688113, 1.702712, 1.71622, 1.729587, 1.739776, 1.747785, 1.752725, 1.755075, 1.756095, 1.756145, 1.755794, 1.755242, 1.754189, 1.753005, 1.751649, 1.75037, 1.74924, 1.748419, 1.747772, 1.747412, 1.747125, 1.74691, 1.746811, 1.746822, 1.746941, 1.747158, 1.747506, 1.747867, 1.748135, 1.748353, 1.748495, 1.748612, 1.748701, 1.748684, 1.748515, 1.748561, 1.748572, 1.748593, 1.748603, 1.748613, 1.748622, 1.748631, 1.74864, 1.748648, 1.748656, 1.748664, 1.748671, 1.748678, 1.748685, 1.748692])
self['CTP'] = 500.0
self['CFRACTION'] = 0.0
self['IDG'] = 0
self['ISH'] = 0
self['ELEVATION'] = 0.0
self['S2M']['T'] = 240.155
self['S2M']['Q'] = 136.332410939
self['S2M']['O'] = 0.03114645315
self['S2M']['P'] = 717.06042
self['S2M']['U'] = 0.0
self['S2M']['V'] = 0.0
self['S2M']['WFETC'] = 100000.0
self['SKIN']['SURFTYPE'] = 0
self['SKIN']['WATERTYPE'] = 1
self['SKIN']['T'] = 240.155
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'] = 0.0
self['AZANGLE'] = 0.0
self['SUNZENANGLE'] = 0.0
self['SUNAZANGLE'] = 0.0
self['LATITUDE'] = -74.316
self['GAS_UNITS'] = 2
self['BE'] = 0.0
self['COSBK'] = 0.0
self['DATE'] = numpy.array([2006, 10, 20])
self['TIME'] = numpy.array([0, 0, 0]) |
# Introductory examples
name = 'Maurizio'
surname = 'Petrelli'
print('-------------------------------------------------')
print('My name is {}'.format(name))
print('-------------------------------------------------')
print('My name is {} and my surname is {}'.format(name, surname))
print('-------------------------------------------------')
# Decimal Number formatting
PI = 3.14159265358979323846
print('----------------------------------------------------')
print("The 2 digit Archimedes' constant is equal to {:.2f}".format(PI))
print("The 3 digit Archimedes' constant is equal to {:.3f}".format(PI))
print("The 4 digit Archimedes' constant is equal to {:.4f}".format(PI))
print("The 5 digit Archimedes' constant is equal to {:.5f}".format(PI))
print('----------------------------------------------------')
'''Results
-------------------------------------------------
My name is Maurizio
-------------------------------------------------
My name is Maurizio and my surname is Petrelli
-------------------------------------------------
----------------------------------------------------
The 2 digit Archimedes' constant is equal to 3.14
The 3 digit Archimedes' constant is equal to 3.142
The 4 digit Archimedes' constant is equal to 3.1416
The 5 digit Archimedes' constant is equal to 3.14159
----------------------------------------------------
'''
| name = 'Maurizio'
surname = 'Petrelli'
print('-------------------------------------------------')
print('My name is {}'.format(name))
print('-------------------------------------------------')
print('My name is {} and my surname is {}'.format(name, surname))
print('-------------------------------------------------')
pi = 3.141592653589793
print('----------------------------------------------------')
print("The 2 digit Archimedes' constant is equal to {:.2f}".format(PI))
print("The 3 digit Archimedes' constant is equal to {:.3f}".format(PI))
print("The 4 digit Archimedes' constant is equal to {:.4f}".format(PI))
print("The 5 digit Archimedes' constant is equal to {:.5f}".format(PI))
print('----------------------------------------------------')
"Results\n-------------------------------------------------\nMy name is Maurizio\n-------------------------------------------------\nMy name is Maurizio and my surname is Petrelli\n-------------------------------------------------\n----------------------------------------------------\nThe 2 digit Archimedes' constant is equal to 3.14\nThe 3 digit Archimedes' constant is equal to 3.142\nThe 4 digit Archimedes' constant is equal to 3.1416\nThe 5 digit Archimedes' constant is equal to 3.14159\n----------------------------------------------------\n" |
class PartialFailure(Exception):
"""
Error indicating either send_messages or delete_messages API call failed partially
"""
def __init__(self, result, *args):
self.success_count = len(result['Successful'])
self.failure_count = len(result['Failed'])
self.result = result
super().__init__(*args)
| class Partialfailure(Exception):
"""
Error indicating either send_messages or delete_messages API call failed partially
"""
def __init__(self, result, *args):
self.success_count = len(result['Successful'])
self.failure_count = len(result['Failed'])
self.result = result
super().__init__(*args) |
'''
Created on Dec 18, 2016
@author: rch
'''
| """
Created on Dec 18, 2016
@author: rch
""" |
#!/usr/bin/env python
# coding=utf-8
class BaseException(Exception):
def __init__(self, code, msg):
self.code = code
self.msg = msg
def __str__(self):
return '<%s %s>' % (self.__class__.__name__, self.code)
| class Baseexception(Exception):
def __init__(self, code, msg):
self.code = code
self.msg = msg
def __str__(self):
return '<%s %s>' % (self.__class__.__name__, self.code) |
class Solution:
def wiggleSort(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
'''
[3,5,2,1,6,4]
[3,5,1,6,2,4]
[4,3,2,1]
[3,4,2,1]
[6,6,5,6,3,8]
'''
def is_correct_order(x, y, isAscending):
return x <= y if isAscending else x >= y
isAscending = True
for i in range(1, len(nums)):
if not is_correct_order(nums[i-1], nums[i], isAscending):
nums[i-1], nums[i] = nums[i], nums[i-1]
isAscending = not isAscending
| class Solution:
def wiggle_sort(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
'\n [3,5,2,1,6,4]\n [3,5,1,6,2,4]\n \n [4,3,2,1]\n [3,4,2,1]\n [6,6,5,6,3,8]\n '
def is_correct_order(x, y, isAscending):
return x <= y if isAscending else x >= y
is_ascending = True
for i in range(1, len(nums)):
if not is_correct_order(nums[i - 1], nums[i], isAscending):
(nums[i - 1], nums[i]) = (nums[i], nums[i - 1])
is_ascending = not isAscending |
# Copyright (c) 2014 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'test_cdecl',
'type': 'loadable_module',
'msvs_settings': {
'VCCLCompilerTool': {
'CallingConvention': 0,
},
},
'sources': [
'calling-convention.cc',
'calling-convention-cdecl.def',
],
},
{
'target_name': 'test_fastcall',
'type': 'loadable_module',
'msvs_settings': {
'VCCLCompilerTool': {
'CallingConvention': 1,
},
},
'sources': [
'calling-convention.cc',
'calling-convention-fastcall.def',
],
},
{
'target_name': 'test_stdcall',
'type': 'loadable_module',
'msvs_settings': {
'VCCLCompilerTool': {
'CallingConvention': 2,
},
},
'sources': [
'calling-convention.cc',
'calling-convention-stdcall.def',
],
},
],
'conditions': [
['MSVS_VERSION[0:4]>="2013"', {
'targets': [
{
'target_name': 'test_vectorcall',
'type': 'loadable_module',
'msvs_settings': {
'VCCLCompilerTool': {
'CallingConvention': 3,
},
},
'sources': [
'calling-convention.cc',
'calling-convention-vectorcall.def',
],
},
],
}],
],
}
| {'targets': [{'target_name': 'test_cdecl', 'type': 'loadable_module', 'msvs_settings': {'VCCLCompilerTool': {'CallingConvention': 0}}, 'sources': ['calling-convention.cc', 'calling-convention-cdecl.def']}, {'target_name': 'test_fastcall', 'type': 'loadable_module', 'msvs_settings': {'VCCLCompilerTool': {'CallingConvention': 1}}, 'sources': ['calling-convention.cc', 'calling-convention-fastcall.def']}, {'target_name': 'test_stdcall', 'type': 'loadable_module', 'msvs_settings': {'VCCLCompilerTool': {'CallingConvention': 2}}, 'sources': ['calling-convention.cc', 'calling-convention-stdcall.def']}], 'conditions': [['MSVS_VERSION[0:4]>="2013"', {'targets': [{'target_name': 'test_vectorcall', 'type': 'loadable_module', 'msvs_settings': {'VCCLCompilerTool': {'CallingConvention': 3}}, 'sources': ['calling-convention.cc', 'calling-convention-vectorcall.def']}]}]]} |
class BaseAgent(object):
"""
Class for the basic agent objects.
"""
def __init__(self,
env,
actor_critic,
storage,
device):
"""
env: (gym.Env) environment following the openAI Gym API
"""
self.env = env
self.actor_critic = actor_critic
self.storage = storage
self.device = device
self.t = 0
def predict(self, obs, hidden_state, done):
"""
Predict the action with the given input
"""
pass
def optimize(self):
"""
Train the neural network model
"""
pass
| class Baseagent(object):
"""
Class for the basic agent objects.
"""
def __init__(self, env, actor_critic, storage, device):
"""
env: (gym.Env) environment following the openAI Gym API
"""
self.env = env
self.actor_critic = actor_critic
self.storage = storage
self.device = device
self.t = 0
def predict(self, obs, hidden_state, done):
"""
Predict the action with the given input
"""
pass
def optimize(self):
"""
Train the neural network model
"""
pass |
#
# PySNMP MIB module RBT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RBT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:18:46 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, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ConstraintsIntersection")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Counter32, TimeTicks, ModuleIdentity, Integer32, MibIdentifier, iso, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, ObjectIdentity, Unsigned32, Bits, NotificationType, enterprises, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "TimeTicks", "ModuleIdentity", "Integer32", "MibIdentifier", "iso", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "ObjectIdentity", "Unsigned32", "Bits", "NotificationType", "enterprises", "Counter64")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
rbt = ModuleIdentity((1, 3, 6, 1, 4, 1, 17163))
rbt.setRevisions(('2009-09-23 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: rbt.setRevisionsDescriptions(('Updated contact information',))
if mibBuilder.loadTexts: rbt.setLastUpdated('200909230000Z')
if mibBuilder.loadTexts: rbt.setOrganization('Riverbed Technology, Inc.')
if mibBuilder.loadTexts: rbt.setContactInfo(' Riverbed Technical Support support@riverbed.com')
if mibBuilder.loadTexts: rbt.setDescription('Riverbed Technology MIB')
products = MibIdentifier((1, 3, 6, 1, 4, 1, 17163, 1))
mibBuilder.exportSymbols("RBT-MIB", products=products, PYSNMP_MODULE_ID=rbt, rbt=rbt)
| (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, single_value_constraint, constraints_union, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'ValueRangeConstraint', 'SingleValueConstraint', 'ConstraintsUnion', 'ConstraintsIntersection')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(counter32, time_ticks, module_identity, integer32, mib_identifier, iso, gauge32, mib_scalar, mib_table, mib_table_row, mib_table_column, ip_address, object_identity, unsigned32, bits, notification_type, enterprises, counter64) = mibBuilder.importSymbols('SNMPv2-SMI', 'Counter32', 'TimeTicks', 'ModuleIdentity', 'Integer32', 'MibIdentifier', 'iso', 'Gauge32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'IpAddress', 'ObjectIdentity', 'Unsigned32', 'Bits', 'NotificationType', 'enterprises', 'Counter64')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
rbt = module_identity((1, 3, 6, 1, 4, 1, 17163))
rbt.setRevisions(('2009-09-23 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts:
rbt.setRevisionsDescriptions(('Updated contact information',))
if mibBuilder.loadTexts:
rbt.setLastUpdated('200909230000Z')
if mibBuilder.loadTexts:
rbt.setOrganization('Riverbed Technology, Inc.')
if mibBuilder.loadTexts:
rbt.setContactInfo(' Riverbed Technical Support support@riverbed.com')
if mibBuilder.loadTexts:
rbt.setDescription('Riverbed Technology MIB')
products = mib_identifier((1, 3, 6, 1, 4, 1, 17163, 1))
mibBuilder.exportSymbols('RBT-MIB', products=products, PYSNMP_MODULE_ID=rbt, rbt=rbt) |
def solution(num):
if num < 0:
raise ValueError
if num == 1:
return 1
k = None
for k in range(num // 2 + 1):
if k ** 2 == num:
return k
elif k ** 2 > num:
return k - 1
return k
def best_solution(num):
if num < 0:
raise ValueError
if num == 1:
return 1
low = 0
high = num // 2 + 1
while low + 1 < high:
mid = low + (high - low) // 2
square = mid ** 2
if square == num:
return mid
elif square < num:
low = mid
else:
high = mid
return low
if __name__ == '__main__':
a = solution(99898)
print(a)
a = best_solution(19)
print(a) | def solution(num):
if num < 0:
raise ValueError
if num == 1:
return 1
k = None
for k in range(num // 2 + 1):
if k ** 2 == num:
return k
elif k ** 2 > num:
return k - 1
return k
def best_solution(num):
if num < 0:
raise ValueError
if num == 1:
return 1
low = 0
high = num // 2 + 1
while low + 1 < high:
mid = low + (high - low) // 2
square = mid ** 2
if square == num:
return mid
elif square < num:
low = mid
else:
high = mid
return low
if __name__ == '__main__':
a = solution(99898)
print(a)
a = best_solution(19)
print(a) |
# Homework #6. Loops
print("--- Task #1. 10 monkeys")
# Task #1. Write a program that output the following string: "1 monkey 2 monkeys ... 10 monkeys".
for x in range(1, 11):
if x == 1:
monkey = f"{x} monkey "
else:
monkey = monkey + f"{x} monkeys "
print(monkey.strip())
print("\n--- Task #2. Countdown timer")
# Task #2. Write a program that output the string that tracks the number of seconds that remain for the roket launching: "10 seconds...9 seconds...8 seconds...7 seconds...6 seconds...5 seconds...4 seconds...3 seconds...2 seconds...1 second"
for x in range(10, 0, -1):
print(str(x) + " seconds...")
print()
print("\n--- Task #3")
# Task #3. Input two numbers k and n. Calculate you own power (k**n) without using power (**) operator but by using repeated multiplication (number is being multiplied by itself).
# Example: 3**4 = 81 is equivalent to 3*3*3*3 = 81.
n = int(input("Please enter any number: "))
k = int(input("Please enter any number for a power: "))
x = 1
s = n
for x in range(1, k):
n = s * n
x += 1
print("k ** n =", n)
m = (str(s) + " * ") * (k-1)
print(f"{m}{s} = {n}")
print("\n--- Task #4")
# Task #4. The first day of training, the athlete ran 5 km. Each next day, he ran 5% more than the day before. How many kilometers will the athlete run on the 10th day?
day = 1
distance = 5
print("The first day distance = ", distance, "km")
distance2 = distance * (1.05**9) # for checking
print(f"The 10th day distance should be {distance} * (1.05 ** 9) =", round(distance2,2), "km")
print()
while day < 10:
distance += distance * 5/100
print(distance)
day += 1
print("On the 10th day, the athlete run ", round(distance,2), "km")
print("\n--- Task #5. ")
# Task #5. The student did not know a single English word at the beginning of the training. On the first day of class, he learned 5 English words. On each next day, he learned 2 more words than the day before. In how many days will the student know at least n English words?
n = int(input("Please enter number of words: "))
day = 0 # d2
words = 5
print(f"The student knew {day} words before training session.")
print(f"The student learned {words} on the first day.")
total = 5
while words <= n:
words = words + 2
day = day + 1
# total = total + words #?
print(f"The student will learn {n} words at the the {day} day, but he may learn {words} words by the end of the {day} day of the traning.")
print("Verify with addition: 5" + " + 2" * day + " = " + str(words) + " words")
print(total) #?
print("\n--- Task #6. ")
# Task #6. Prompt to a user to input the nunber of steps. Get the string that contains stairs made of sharp sign (#).
# #
# #
# #
# #
# #
num = int(input("How many steps in the stairs: "))
stairs = ''
x = 1
while x <= num:
print(" " * x + "#")
x += 1
print(stairs)
print("--- Task #7. ")
# 7. Output stars having the form of a pyramid. With the command input, get the number of levels. Use function for center align the string.
# *
# ***
# *****
# *******
levels = int(input("Please enter any number of levels for pyramid: "))
star = '*'
x = 1
# ver 1
c_point = levels * 2 # -> extra space before pyramid if levels*2+1
for x in range(levels):
star = "*" + x * 2 * "*"
x += 1
print(star.center(c_point))
# ver 2 - in class
# levels = int(input("Please enter any number of levels for pyramid: "))
c_point = levels * 2 - 1
for x in range(1,levels + 1):
stars = x * 2 - 1
print(("*" * stars).center(c_point))
| print('--- Task #1. 10 monkeys')
for x in range(1, 11):
if x == 1:
monkey = f'{x} monkey '
else:
monkey = monkey + f'{x} monkeys '
print(monkey.strip())
print('\n--- Task #2. Countdown timer')
for x in range(10, 0, -1):
print(str(x) + ' seconds...')
print()
print('\n--- Task #3')
n = int(input('Please enter any number: '))
k = int(input('Please enter any number for a power: '))
x = 1
s = n
for x in range(1, k):
n = s * n
x += 1
print('k ** n =', n)
m = (str(s) + ' * ') * (k - 1)
print(f'{m}{s} = {n}')
print('\n--- Task #4')
day = 1
distance = 5
print('The first day distance = ', distance, 'km')
distance2 = distance * 1.05 ** 9
print(f'The 10th day distance should be {distance} * (1.05 ** 9) =', round(distance2, 2), 'km')
print()
while day < 10:
distance += distance * 5 / 100
print(distance)
day += 1
print('On the 10th day, the athlete run ', round(distance, 2), 'km')
print('\n--- Task #5. ')
n = int(input('Please enter number of words: '))
day = 0
words = 5
print(f'The student knew {day} words before training session.')
print(f'The student learned {words} on the first day.')
total = 5
while words <= n:
words = words + 2
day = day + 1
print(f'The student will learn {n} words at the the {day} day, but he may learn {words} words by the end of the {day} day of the traning.')
print('Verify with addition: 5' + ' + 2' * day + ' = ' + str(words) + ' words')
print(total)
print('\n--- Task #6. ')
num = int(input('How many steps in the stairs: '))
stairs = ''
x = 1
while x <= num:
print(' ' * x + '#')
x += 1
print(stairs)
print('--- Task #7. ')
levels = int(input('Please enter any number of levels for pyramid: '))
star = '*'
x = 1
c_point = levels * 2
for x in range(levels):
star = '*' + x * 2 * '*'
x += 1
print(star.center(c_point))
c_point = levels * 2 - 1
for x in range(1, levels + 1):
stars = x * 2 - 1
print(('*' * stars).center(c_point)) |
"""
https://leetcode.com/problems/diameter-of-binary-tree/
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
1
/ \
2 3
/ \
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Note: The length of path between two nodes is represented by the number of edges between them.
"""
# Thanks to the solution provided by the problem.
# time complexity: O(n), space complexity: O(1)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
self.long = 1
self.dfs(root)
return self.long - 1
def dfs(self, root: TreeNode) -> int:
if root is None:
return 0
left = self.dfs(root.left)
right = self.dfs(root.right)
self.long = max(self.long, left + right + 1)
return max(left, right) + 1
| """
https://leetcode.com/problems/diameter-of-binary-tree/
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
1
/ 2 3
/ 4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Note: The length of path between two nodes is represented by the number of edges between them.
"""
class Solution:
def diameter_of_binary_tree(self, root: TreeNode) -> int:
self.long = 1
self.dfs(root)
return self.long - 1
def dfs(self, root: TreeNode) -> int:
if root is None:
return 0
left = self.dfs(root.left)
right = self.dfs(root.right)
self.long = max(self.long, left + right + 1)
return max(left, right) + 1 |
#
# PySNMP MIB module TRANGO-APEX-TRAP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRANGO-APEX-TRAP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:19:34 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, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, NotificationType, IpAddress, Gauge32, Unsigned32, TimeTicks, iso, ModuleIdentity, Bits, Counter32, Integer32, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "NotificationType", "IpAddress", "Gauge32", "Unsigned32", "TimeTicks", "iso", "ModuleIdentity", "Bits", "Counter32", "Integer32", "ObjectIdentity")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
MibScalar, MibTable, MibTableRow, MibTableColumn, apex, NotificationType, Unsigned32, ModuleIdentity, ObjectIdentity = mibBuilder.importSymbols("TRANGO-APEX-MIB", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "apex", "NotificationType", "Unsigned32", "ModuleIdentity", "ObjectIdentity")
class DisplayString(OctetString):
pass
trangotrap = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6))
trapReboot = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 1))
if mibBuilder.loadTexts: trapReboot.setStatus('current')
trapStartUp = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 2))
if mibBuilder.loadTexts: trapStartUp.setStatus('current')
traplock = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 3))
trapModemLock = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 3, 1))
if mibBuilder.loadTexts: trapModemLock.setStatus('current')
trapTimingLock = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 3, 2))
if mibBuilder.loadTexts: trapTimingLock.setStatus('current')
trapInnerCodeLock = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 3, 3))
if mibBuilder.loadTexts: trapInnerCodeLock.setStatus('current')
trapEqualizerLock = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 3, 4))
if mibBuilder.loadTexts: trapEqualizerLock.setStatus('current')
trapFrameSyncLock = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 3, 5))
if mibBuilder.loadTexts: trapFrameSyncLock.setStatus('current')
trapthreshold = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4))
trapmse = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 1))
trapMSEMinThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 1, 1))
if mibBuilder.loadTexts: trapMSEMinThreshold.setStatus('current')
trapMSEMaxThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 1, 2))
if mibBuilder.loadTexts: trapMSEMaxThreshold.setStatus('current')
trapber = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 2))
trapBERMinThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 2, 1))
if mibBuilder.loadTexts: trapBERMinThreshold.setStatus('current')
trapBERMaxThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 2, 2))
if mibBuilder.loadTexts: trapBERMaxThreshold.setStatus('current')
trapfer = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 3))
trapFERMinThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 3, 1))
if mibBuilder.loadTexts: trapFERMinThreshold.setStatus('current')
trapFERMaxThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 3, 2))
if mibBuilder.loadTexts: trapFERMaxThreshold.setStatus('current')
traprssi = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 4))
trapRSSIMinThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 4, 1))
if mibBuilder.loadTexts: trapRSSIMinThreshold.setStatus('current')
trapRSSIMaxThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 4, 2))
if mibBuilder.loadTexts: trapRSSIMaxThreshold.setStatus('current')
trapidutemp = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 5))
trapIDUTempMinThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 5, 1))
if mibBuilder.loadTexts: trapIDUTempMinThreshold.setStatus('current')
trapIDUTempMaxThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 5, 2))
if mibBuilder.loadTexts: trapIDUTempMaxThreshold.setStatus('current')
trapodutemp = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 6))
trapODUTempMinThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 6, 1))
if mibBuilder.loadTexts: trapODUTempMinThreshold.setStatus('current')
trapODUTempMaxThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 6, 2))
if mibBuilder.loadTexts: trapODUTempMaxThreshold.setStatus('current')
trapinport = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 7))
trapInPortUtilMinThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 7, 1))
if mibBuilder.loadTexts: trapInPortUtilMinThreshold.setStatus('current')
trapInPortUtilMaxThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 7, 2))
if mibBuilder.loadTexts: trapInPortUtilMaxThreshold.setStatus('current')
trapoutport = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 8))
trapOutPortUtilMinThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 8, 1))
if mibBuilder.loadTexts: trapOutPortUtilMinThreshold.setStatus('current')
trapOutPortUtilMaxThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 8, 2))
if mibBuilder.loadTexts: trapOutPortUtilMaxThreshold.setStatus('current')
trapstandby = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 5))
trapStandbyLinkDown = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 5, 1))
if mibBuilder.loadTexts: trapStandbyLinkDown.setStatus('current')
trapStandbyLinkUp = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 5, 2))
if mibBuilder.loadTexts: trapStandbyLinkUp.setStatus('current')
trapSwitchover = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 5, 3))
if mibBuilder.loadTexts: trapSwitchover.setStatus('current')
trapeth = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 6))
trapethstatus = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 6, 1))
trapEth1StatusUpdate = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 6, 1, 1))
if mibBuilder.loadTexts: trapEth1StatusUpdate.setStatus('current')
trapEth2StatusUpdate = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 6, 1, 2))
if mibBuilder.loadTexts: trapEth2StatusUpdate.setStatus('current')
trapEth3StatusUpdate = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 6, 1, 3))
if mibBuilder.loadTexts: trapEth3StatusUpdate.setStatus('current')
trapEth4StatusUpdate = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 6, 1, 4))
if mibBuilder.loadTexts: trapEth4StatusUpdate.setStatus('current')
trapDownShift = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 8))
if mibBuilder.loadTexts: trapDownShift.setStatus('current')
trapRapidPortShutdown = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 9))
if mibBuilder.loadTexts: trapRapidPortShutdown.setStatus('current')
trapRPSPortUp = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 10))
if mibBuilder.loadTexts: trapRPSPortUp.setStatus('current')
mibBuilder.exportSymbols("TRANGO-APEX-TRAP-MIB", trapber=trapber, trapEth3StatusUpdate=trapEth3StatusUpdate, DisplayString=DisplayString, trapFERMinThreshold=trapFERMinThreshold, trapStandbyLinkDown=trapStandbyLinkDown, trapInPortUtilMinThreshold=trapInPortUtilMinThreshold, trapMSEMinThreshold=trapMSEMinThreshold, trapRSSIMaxThreshold=trapRSSIMaxThreshold, traprssi=traprssi, trapStandbyLinkUp=trapStandbyLinkUp, trapIDUTempMinThreshold=trapIDUTempMinThreshold, trapRapidPortShutdown=trapRapidPortShutdown, trangotrap=trangotrap, trapStartUp=trapStartUp, trapMSEMaxThreshold=trapMSEMaxThreshold, trapSwitchover=trapSwitchover, traplock=traplock, trapethstatus=trapethstatus, trapEth2StatusUpdate=trapEth2StatusUpdate, trapodutemp=trapodutemp, trapinport=trapinport, trapReboot=trapReboot, trapthreshold=trapthreshold, trapmse=trapmse, trapEth4StatusUpdate=trapEth4StatusUpdate, trapIDUTempMaxThreshold=trapIDUTempMaxThreshold, trapFrameSyncLock=trapFrameSyncLock, trapOutPortUtilMinThreshold=trapOutPortUtilMinThreshold, trapInnerCodeLock=trapInnerCodeLock, trapfer=trapfer, trapTimingLock=trapTimingLock, trapFERMaxThreshold=trapFERMaxThreshold, trapstandby=trapstandby, trapModemLock=trapModemLock, trapInPortUtilMaxThreshold=trapInPortUtilMaxThreshold, trapOutPortUtilMaxThreshold=trapOutPortUtilMaxThreshold, trapoutport=trapoutport, trapODUTempMinThreshold=trapODUTempMinThreshold, trapDownShift=trapDownShift, trapBERMinThreshold=trapBERMinThreshold, trapRPSPortUp=trapRPSPortUp, trapEqualizerLock=trapEqualizerLock, trapeth=trapeth, trapRSSIMinThreshold=trapRSSIMinThreshold, trapEth1StatusUpdate=trapEth1StatusUpdate, trapidutemp=trapidutemp, trapODUTempMaxThreshold=trapODUTempMaxThreshold, trapBERMaxThreshold=trapBERMaxThreshold)
| (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, single_value_constraint, value_range_constraint, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ConstraintsUnion', 'SingleValueConstraint', 'ValueRangeConstraint', 'ValueSizeConstraint')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(counter64, mib_scalar, mib_table, mib_table_row, mib_table_column, mib_identifier, notification_type, ip_address, gauge32, unsigned32, time_ticks, iso, module_identity, bits, counter32, integer32, object_identity) = mibBuilder.importSymbols('SNMPv2-SMI', 'Counter64', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'MibIdentifier', 'NotificationType', 'IpAddress', 'Gauge32', 'Unsigned32', 'TimeTicks', 'iso', 'ModuleIdentity', 'Bits', 'Counter32', 'Integer32', 'ObjectIdentity')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
(mib_scalar, mib_table, mib_table_row, mib_table_column, apex, notification_type, unsigned32, module_identity, object_identity) = mibBuilder.importSymbols('TRANGO-APEX-MIB', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'apex', 'NotificationType', 'Unsigned32', 'ModuleIdentity', 'ObjectIdentity')
class Displaystring(OctetString):
pass
trangotrap = mib_identifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6))
trap_reboot = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 1))
if mibBuilder.loadTexts:
trapReboot.setStatus('current')
trap_start_up = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 2))
if mibBuilder.loadTexts:
trapStartUp.setStatus('current')
traplock = mib_identifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 3))
trap_modem_lock = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 3, 1))
if mibBuilder.loadTexts:
trapModemLock.setStatus('current')
trap_timing_lock = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 3, 2))
if mibBuilder.loadTexts:
trapTimingLock.setStatus('current')
trap_inner_code_lock = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 3, 3))
if mibBuilder.loadTexts:
trapInnerCodeLock.setStatus('current')
trap_equalizer_lock = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 3, 4))
if mibBuilder.loadTexts:
trapEqualizerLock.setStatus('current')
trap_frame_sync_lock = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 3, 5))
if mibBuilder.loadTexts:
trapFrameSyncLock.setStatus('current')
trapthreshold = mib_identifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4))
trapmse = mib_identifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 1))
trap_mse_min_threshold = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 1, 1))
if mibBuilder.loadTexts:
trapMSEMinThreshold.setStatus('current')
trap_mse_max_threshold = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 1, 2))
if mibBuilder.loadTexts:
trapMSEMaxThreshold.setStatus('current')
trapber = mib_identifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 2))
trap_ber_min_threshold = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 2, 1))
if mibBuilder.loadTexts:
trapBERMinThreshold.setStatus('current')
trap_ber_max_threshold = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 2, 2))
if mibBuilder.loadTexts:
trapBERMaxThreshold.setStatus('current')
trapfer = mib_identifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 3))
trap_fer_min_threshold = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 3, 1))
if mibBuilder.loadTexts:
trapFERMinThreshold.setStatus('current')
trap_fer_max_threshold = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 3, 2))
if mibBuilder.loadTexts:
trapFERMaxThreshold.setStatus('current')
traprssi = mib_identifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 4))
trap_rssi_min_threshold = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 4, 1))
if mibBuilder.loadTexts:
trapRSSIMinThreshold.setStatus('current')
trap_rssi_max_threshold = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 4, 2))
if mibBuilder.loadTexts:
trapRSSIMaxThreshold.setStatus('current')
trapidutemp = mib_identifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 5))
trap_idu_temp_min_threshold = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 5, 1))
if mibBuilder.loadTexts:
trapIDUTempMinThreshold.setStatus('current')
trap_idu_temp_max_threshold = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 5, 2))
if mibBuilder.loadTexts:
trapIDUTempMaxThreshold.setStatus('current')
trapodutemp = mib_identifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 6))
trap_odu_temp_min_threshold = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 6, 1))
if mibBuilder.loadTexts:
trapODUTempMinThreshold.setStatus('current')
trap_odu_temp_max_threshold = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 6, 2))
if mibBuilder.loadTexts:
trapODUTempMaxThreshold.setStatus('current')
trapinport = mib_identifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 7))
trap_in_port_util_min_threshold = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 7, 1))
if mibBuilder.loadTexts:
trapInPortUtilMinThreshold.setStatus('current')
trap_in_port_util_max_threshold = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 7, 2))
if mibBuilder.loadTexts:
trapInPortUtilMaxThreshold.setStatus('current')
trapoutport = mib_identifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 8))
trap_out_port_util_min_threshold = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 8, 1))
if mibBuilder.loadTexts:
trapOutPortUtilMinThreshold.setStatus('current')
trap_out_port_util_max_threshold = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 8, 2))
if mibBuilder.loadTexts:
trapOutPortUtilMaxThreshold.setStatus('current')
trapstandby = mib_identifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 5))
trap_standby_link_down = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 5, 1))
if mibBuilder.loadTexts:
trapStandbyLinkDown.setStatus('current')
trap_standby_link_up = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 5, 2))
if mibBuilder.loadTexts:
trapStandbyLinkUp.setStatus('current')
trap_switchover = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 5, 3))
if mibBuilder.loadTexts:
trapSwitchover.setStatus('current')
trapeth = mib_identifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 6))
trapethstatus = mib_identifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 6, 1))
trap_eth1_status_update = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 6, 1, 1))
if mibBuilder.loadTexts:
trapEth1StatusUpdate.setStatus('current')
trap_eth2_status_update = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 6, 1, 2))
if mibBuilder.loadTexts:
trapEth2StatusUpdate.setStatus('current')
trap_eth3_status_update = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 6, 1, 3))
if mibBuilder.loadTexts:
trapEth3StatusUpdate.setStatus('current')
trap_eth4_status_update = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 6, 1, 4))
if mibBuilder.loadTexts:
trapEth4StatusUpdate.setStatus('current')
trap_down_shift = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 8))
if mibBuilder.loadTexts:
trapDownShift.setStatus('current')
trap_rapid_port_shutdown = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 9))
if mibBuilder.loadTexts:
trapRapidPortShutdown.setStatus('current')
trap_rps_port_up = notification_type((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 10))
if mibBuilder.loadTexts:
trapRPSPortUp.setStatus('current')
mibBuilder.exportSymbols('TRANGO-APEX-TRAP-MIB', trapber=trapber, trapEth3StatusUpdate=trapEth3StatusUpdate, DisplayString=DisplayString, trapFERMinThreshold=trapFERMinThreshold, trapStandbyLinkDown=trapStandbyLinkDown, trapInPortUtilMinThreshold=trapInPortUtilMinThreshold, trapMSEMinThreshold=trapMSEMinThreshold, trapRSSIMaxThreshold=trapRSSIMaxThreshold, traprssi=traprssi, trapStandbyLinkUp=trapStandbyLinkUp, trapIDUTempMinThreshold=trapIDUTempMinThreshold, trapRapidPortShutdown=trapRapidPortShutdown, trangotrap=trangotrap, trapStartUp=trapStartUp, trapMSEMaxThreshold=trapMSEMaxThreshold, trapSwitchover=trapSwitchover, traplock=traplock, trapethstatus=trapethstatus, trapEth2StatusUpdate=trapEth2StatusUpdate, trapodutemp=trapodutemp, trapinport=trapinport, trapReboot=trapReboot, trapthreshold=trapthreshold, trapmse=trapmse, trapEth4StatusUpdate=trapEth4StatusUpdate, trapIDUTempMaxThreshold=trapIDUTempMaxThreshold, trapFrameSyncLock=trapFrameSyncLock, trapOutPortUtilMinThreshold=trapOutPortUtilMinThreshold, trapInnerCodeLock=trapInnerCodeLock, trapfer=trapfer, trapTimingLock=trapTimingLock, trapFERMaxThreshold=trapFERMaxThreshold, trapstandby=trapstandby, trapModemLock=trapModemLock, trapInPortUtilMaxThreshold=trapInPortUtilMaxThreshold, trapOutPortUtilMaxThreshold=trapOutPortUtilMaxThreshold, trapoutport=trapoutport, trapODUTempMinThreshold=trapODUTempMinThreshold, trapDownShift=trapDownShift, trapBERMinThreshold=trapBERMinThreshold, trapRPSPortUp=trapRPSPortUp, trapEqualizerLock=trapEqualizerLock, trapeth=trapeth, trapRSSIMinThreshold=trapRSSIMinThreshold, trapEth1StatusUpdate=trapEth1StatusUpdate, trapidutemp=trapidutemp, trapODUTempMaxThreshold=trapODUTempMaxThreshold, trapBERMaxThreshold=trapBERMaxThreshold) |
"""
District Mapping
================
Defines the algorithms that perform the mapping from precincts to districts.
"""
| """
District Mapping
================
Defines the algorithms that perform the mapping from precincts to districts.
""" |
# -*- coding: utf-8 -*-
i = 1
for x in range(60, -1, -5):
print('I={} J={}'.format(i, x))
i += 3
| i = 1
for x in range(60, -1, -5):
print('I={} J={}'.format(i, x))
i += 3 |
def process(N):
temp = str(N)
temp = temp.replace('4','2')
res1 = int(temp)
res2 = N-res1
return res1,res2
T = int(input())
for t in range(T):
N = int(input())
res1,res2 = process(N)
print('Case #{}: {} {}'.format(t+1,res1,res2)) | def process(N):
temp = str(N)
temp = temp.replace('4', '2')
res1 = int(temp)
res2 = N - res1
return (res1, res2)
t = int(input())
for t in range(T):
n = int(input())
(res1, res2) = process(N)
print('Case #{}: {} {}'.format(t + 1, res1, res2)) |
class T:
WORK_REQUEST = 1
WORK_REPLY = 2
REDUCE = 3
BARRIER = 4
TOKEN = 7
class Tally:
total_dirs = 0
total_files = 0
total_filesize = 0
total_stat_filesize = 0
total_symlinks = 0
total_skipped = 0
total_sparse = 0
max_files = 0
total_nlinks = 0
total_nlinked_files = 0
total_0byte_files = 0
devfile_cnt = 0
devfile_sz = 0
spcnt = 0 # stripe cnt account per process
# ZFS
total_blocks = 0
class G:
ZERO = 0
ABORT = -1
WHITE = 50
BLACK = 51
NONE = -99
TERMINATE = -100
MSG = 99
MSG_VALID = True
MSG_INVALID = False
fmt1 = '%(asctime)s - %(levelname)s - %(rank)s:%(filename)s:%(lineno)d - %(message)s'
fmt2 = '%(asctime)s - %(rank)s:%(filename)s:%(lineno)d - %(message)s'
bare_fmt = '%(name)s - %(levelname)s - %(message)s'
mpi_fmt = '%(name)s - %(levelname)s - %(rank)s - %(message)s'
bare_fmt2 = '%(message)s'
str = {WHITE: "white", BLACK: "black", NONE: "not set", TERMINATE: "terminate",
ABORT: "abort", MSG: "message"}
KEY = "key"
VAL = "val"
logger = None
logfile = None
loglevel = "warn"
use_store = False
fix_opt = False
preserve = False
DB_BUFSIZE = 10000
memitem_threshold = 100000
tempdir = None
total_chunks = 0
rid = None
chk_file = None
chk_file_db = None
totalsize = 0
src = None
dest = None
args_src = None
args_dest = None
resume = None
reduce_interval = 30
reduce_enabled = False
verbosity = 0
am_root = False
copytype = 'dir2dir'
# Lustre file system
fs_lustre = None
lfs_bin = None
stripe_threshold = None
b0 = 0
b4k = 4 * 1024
b8k = 8 * 1024
b16k = 16 * 1024
b32k = 32 * 1024
b64k = 64 * 1024
b128k = 128 * 1024
b256k = 256 * 1024
b512k = 512 * 1024
b1m = 1024 * 1024
b2m = 2 * b1m
b4m = 4 * b1m
b8m = 8 * b1m
b16m = 16 * b1m
b32m = 32 * b1m
b64m = 64 * b1m
b128m = 128 * b1m
b256m = 256 * b1m
b512m = 512 * b1m
b1g = 1024 * b1m
b4g = 4 * b1g
b16g = 16 * b1g
b64g = 64 * b1g
b128g = 128 * b1g
b256g = 256 * b1g
b512g = 512 * b1g
b1tb = 1024 * b1g
b4tb = 4 * b1tb
FSZ_BOUND = 64 * b1tb
# 25 bins
bins = [b0, b4k, b8k, b16k, b32k, b64k, b128k, b256k, b512k,
b1m, b2m, b4m, b16m, b32m, b64m, b128m, b256m, b512m,
b1g, b4g, b64g, b128g, b256g, b512g, b1tb, b4tb]
# 17 bins, the last bin is special
# This is error-prone, to be refactored.
# bins_fmt = ["B1_000k_004k", "B1_004k_008k", "B1_008k_016k", "B1_016k_032k", "B1_032k_064k", "B1_064k_256k",
# "B1_256k_512k", "B1_512k_001m",
# "B2_001m_004m", "B2_m004_016m", "B2_016m_512m", "B2_512m_001g",
# "B3_001g_100g", "B3_100g_256g", "B3_256g_512g",
# "B4_512g_001t",
# "B5_001t_up"]
# GPFS
gpfs_block_size = ("256k", "512k", "b1m", "b4m", "b8m", "b16m", "b32m")
gpfs_block_cnt = [0, 0, 0, 0, 0, 0, 0]
gpfs_subs = (b256k/32, b512k/32, b1m/32, b4m/32, b8m/32, b16m/32, b32m/32)
dev_suffixes = [".C", ".CC", ".CU", ".H", ".CPP", ".HPP", ".CXX", ".F", ".I", ".II",
".F90", ".F95", ".F03", ".FOR", ".O", ".A", ".SO", ".S",
".IN", ".M4", ".CACHE", ".PY", ".PYC"]
| class T:
work_request = 1
work_reply = 2
reduce = 3
barrier = 4
token = 7
class Tally:
total_dirs = 0
total_files = 0
total_filesize = 0
total_stat_filesize = 0
total_symlinks = 0
total_skipped = 0
total_sparse = 0
max_files = 0
total_nlinks = 0
total_nlinked_files = 0
total_0byte_files = 0
devfile_cnt = 0
devfile_sz = 0
spcnt = 0
total_blocks = 0
class G:
zero = 0
abort = -1
white = 50
black = 51
none = -99
terminate = -100
msg = 99
msg_valid = True
msg_invalid = False
fmt1 = '%(asctime)s - %(levelname)s - %(rank)s:%(filename)s:%(lineno)d - %(message)s'
fmt2 = '%(asctime)s - %(rank)s:%(filename)s:%(lineno)d - %(message)s'
bare_fmt = '%(name)s - %(levelname)s - %(message)s'
mpi_fmt = '%(name)s - %(levelname)s - %(rank)s - %(message)s'
bare_fmt2 = '%(message)s'
str = {WHITE: 'white', BLACK: 'black', NONE: 'not set', TERMINATE: 'terminate', ABORT: 'abort', MSG: 'message'}
key = 'key'
val = 'val'
logger = None
logfile = None
loglevel = 'warn'
use_store = False
fix_opt = False
preserve = False
db_bufsize = 10000
memitem_threshold = 100000
tempdir = None
total_chunks = 0
rid = None
chk_file = None
chk_file_db = None
totalsize = 0
src = None
dest = None
args_src = None
args_dest = None
resume = None
reduce_interval = 30
reduce_enabled = False
verbosity = 0
am_root = False
copytype = 'dir2dir'
fs_lustre = None
lfs_bin = None
stripe_threshold = None
b0 = 0
b4k = 4 * 1024
b8k = 8 * 1024
b16k = 16 * 1024
b32k = 32 * 1024
b64k = 64 * 1024
b128k = 128 * 1024
b256k = 256 * 1024
b512k = 512 * 1024
b1m = 1024 * 1024
b2m = 2 * b1m
b4m = 4 * b1m
b8m = 8 * b1m
b16m = 16 * b1m
b32m = 32 * b1m
b64m = 64 * b1m
b128m = 128 * b1m
b256m = 256 * b1m
b512m = 512 * b1m
b1g = 1024 * b1m
b4g = 4 * b1g
b16g = 16 * b1g
b64g = 64 * b1g
b128g = 128 * b1g
b256g = 256 * b1g
b512g = 512 * b1g
b1tb = 1024 * b1g
b4tb = 4 * b1tb
fsz_bound = 64 * b1tb
bins = [b0, b4k, b8k, b16k, b32k, b64k, b128k, b256k, b512k, b1m, b2m, b4m, b16m, b32m, b64m, b128m, b256m, b512m, b1g, b4g, b64g, b128g, b256g, b512g, b1tb, b4tb]
gpfs_block_size = ('256k', '512k', 'b1m', 'b4m', 'b8m', 'b16m', 'b32m')
gpfs_block_cnt = [0, 0, 0, 0, 0, 0, 0]
gpfs_subs = (b256k / 32, b512k / 32, b1m / 32, b4m / 32, b8m / 32, b16m / 32, b32m / 32)
dev_suffixes = ['.C', '.CC', '.CU', '.H', '.CPP', '.HPP', '.CXX', '.F', '.I', '.II', '.F90', '.F95', '.F03', '.FOR', '.O', '.A', '.SO', '.S', '.IN', '.M4', '.CACHE', '.PY', '.PYC'] |
# Copyright 2018 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable 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.
"""Implementation of the `swift_c_module` rule."""
load(":swift_common.bzl", "swift_common")
load(":utils.bzl", "merge_runfiles")
def _swift_c_module_impl(ctx):
module_map = ctx.file.module_map
deps = ctx.attr.deps
cc_infos = [dep[CcInfo] for dep in deps]
data_runfiles = [dep[DefaultInfo].data_runfiles for dep in deps]
default_runfiles = [dep[DefaultInfo].default_runfiles for dep in deps]
if cc_infos:
cc_info = cc_common.merge_cc_infos(cc_infos = cc_infos)
compilation_context = cc_info.compilation_context
else:
cc_info = None
compilation_context = cc_common.create_compilation_context()
providers = [
# We must repropagate the dependencies' DefaultInfos, otherwise we
# will lose runtime dependencies that the library expects to be
# there during a test (or a regular `bazel run`).
DefaultInfo(
data_runfiles = merge_runfiles(data_runfiles),
default_runfiles = merge_runfiles(default_runfiles),
files = depset([module_map]),
),
swift_common.create_swift_info(
modules = [
swift_common.create_module(
name = ctx.attr.module_name,
clang = swift_common.create_clang_module(
compilation_context = compilation_context,
module_map = module_map,
# TODO(b/142867898): Precompile the module and place it
# here.
precompiled_module = None,
),
),
],
),
]
if cc_info:
providers.append(cc_info)
return providers
swift_c_module = rule(
attrs = {
"module_map": attr.label(
allow_single_file = True,
doc = """\
The module map file that should be loaded to import the C library dependency
into Swift.
""",
mandatory = True,
),
"module_name": attr.string(
doc = """\
The name of the top-level module in the module map that this target represents.
A single `module.modulemap` file can define multiple top-level modules. When
building with implicit modules, the presence of that module map allows any of
the modules defined in it to be imported. When building explicit modules,
however, there is a one-to-one correspondence between top-level modules and
BUILD targets and the module name must be known without reading the module map
file, so it must be provided directly. Therefore, one may have multiple
`swift_c_module` targets that reference the same `module.modulemap` file but
with different module names and headers.
""",
mandatory = True,
),
"deps": attr.label_list(
allow_empty = False,
doc = """\
A list of C targets (or anything propagating `CcInfo`) that are dependencies of
this target and whose headers may be referenced by the module map.
""",
mandatory = True,
providers = [[CcInfo]],
),
},
doc = """\
Wraps one or more C targets in a new module map that allows it to be imported
into Swift to access its C interfaces.
The `cc_library` rule in Bazel does not produce module maps that are compatible
with Swift. In order to make interop between Swift and C possible, users have
one of two options:
1. **Use an auto-generated module map.** In this case, the `swift_c_module`
rule is not needed. If a `cc_library` is a direct dependency of a
`swift_{binary,library,test}` target, a module map will be automatically
generated for it and the module's name will be derived from the Bazel target
label (in the same fashion that module names for Swift targets are derived).
The module name can be overridden by setting the `swift_module` tag on the
`cc_library`; e.g., `tags = ["swift_module=MyModule"]`.
2. **Use a custom module map.** For finer control over the headers that are
exported by the module, use the `swift_c_module` rule to provide a custom
module map that specifies the name of the module, its headers, and any other
module information. The `cc_library` targets that contain the headers that
you wish to expose to Swift should be listed in the `deps` of your
`swift_c_module` (and by listing multiple targets, you can export multiple
libraries under a single module if desired). Then, your
`swift_{binary,library,test}` targets should depend on the `swift_c_module`
target, not on the underlying `cc_library` target(s).
NOTE: Swift at this time does not support interop directly with C++. Any headers
referenced by a module map that is imported into Swift must have only C features
visible, often by using preprocessor conditions like `#if __cplusplus` to hide
any C++ declarations.
""",
implementation = _swift_c_module_impl,
)
| """Implementation of the `swift_c_module` rule."""
load(':swift_common.bzl', 'swift_common')
load(':utils.bzl', 'merge_runfiles')
def _swift_c_module_impl(ctx):
module_map = ctx.file.module_map
deps = ctx.attr.deps
cc_infos = [dep[CcInfo] for dep in deps]
data_runfiles = [dep[DefaultInfo].data_runfiles for dep in deps]
default_runfiles = [dep[DefaultInfo].default_runfiles for dep in deps]
if cc_infos:
cc_info = cc_common.merge_cc_infos(cc_infos=cc_infos)
compilation_context = cc_info.compilation_context
else:
cc_info = None
compilation_context = cc_common.create_compilation_context()
providers = [default_info(data_runfiles=merge_runfiles(data_runfiles), default_runfiles=merge_runfiles(default_runfiles), files=depset([module_map])), swift_common.create_swift_info(modules=[swift_common.create_module(name=ctx.attr.module_name, clang=swift_common.create_clang_module(compilation_context=compilation_context, module_map=module_map, precompiled_module=None))])]
if cc_info:
providers.append(cc_info)
return providers
swift_c_module = rule(attrs={'module_map': attr.label(allow_single_file=True, doc='The module map file that should be loaded to import the C library dependency\ninto Swift.\n', mandatory=True), 'module_name': attr.string(doc='The name of the top-level module in the module map that this target represents.\n\nA single `module.modulemap` file can define multiple top-level modules. When\nbuilding with implicit modules, the presence of that module map allows any of\nthe modules defined in it to be imported. When building explicit modules,\nhowever, there is a one-to-one correspondence between top-level modules and\nBUILD targets and the module name must be known without reading the module map\nfile, so it must be provided directly. Therefore, one may have multiple\n`swift_c_module` targets that reference the same `module.modulemap` file but\nwith different module names and headers.\n', mandatory=True), 'deps': attr.label_list(allow_empty=False, doc='A list of C targets (or anything propagating `CcInfo`) that are dependencies of\nthis target and whose headers may be referenced by the module map.\n', mandatory=True, providers=[[CcInfo]])}, doc='Wraps one or more C targets in a new module map that allows it to be imported\ninto Swift to access its C interfaces.\n\nThe `cc_library` rule in Bazel does not produce module maps that are compatible\nwith Swift. In order to make interop between Swift and C possible, users have\none of two options:\n\n1. **Use an auto-generated module map.** In this case, the `swift_c_module`\n rule is not needed. If a `cc_library` is a direct dependency of a\n `swift_{binary,library,test}` target, a module map will be automatically\n generated for it and the module\'s name will be derived from the Bazel target\n label (in the same fashion that module names for Swift targets are derived).\n The module name can be overridden by setting the `swift_module` tag on the\n `cc_library`; e.g., `tags = ["swift_module=MyModule"]`.\n\n2. **Use a custom module map.** For finer control over the headers that are\n exported by the module, use the `swift_c_module` rule to provide a custom\n module map that specifies the name of the module, its headers, and any other\n module information. The `cc_library` targets that contain the headers that\n you wish to expose to Swift should be listed in the `deps` of your\n `swift_c_module` (and by listing multiple targets, you can export multiple\n libraries under a single module if desired). Then, your\n `swift_{binary,library,test}` targets should depend on the `swift_c_module`\n target, not on the underlying `cc_library` target(s).\n\nNOTE: Swift at this time does not support interop directly with C++. Any headers\nreferenced by a module map that is imported into Swift must have only C features\nvisible, often by using preprocessor conditions like `#if __cplusplus` to hide\nany C++ declarations.\n', implementation=_swift_c_module_impl) |
class ProgramError(Exception):
"""Generic exception class for errors in this program."""
pass
class PluginError(ProgramError):
pass
class NoOptionError(ProgramError):
pass
class ExtCommandError(ProgramError):
pass
| class Programerror(Exception):
"""Generic exception class for errors in this program."""
pass
class Pluginerror(ProgramError):
pass
class Nooptionerror(ProgramError):
pass
class Extcommanderror(ProgramError):
pass |
# Types
Symbol = str # A Lisp Symbol is implemented as a Python str
List = list # A Lisp List is implemented as a Python list
Number = (int, float) # A Lisp Number is implemented as a Python int or float
# Exp = Union[Symbol, Exp]
def atom(token):
"Numbers become numbers; every other token is a symbol."
try:
return int(token)
except ValueError:
try:
return float(token)
except ValueError:
return Symbol(token)
| symbol = str
list = list
number = (int, float)
def atom(token):
"""Numbers become numbers; every other token is a symbol."""
try:
return int(token)
except ValueError:
try:
return float(token)
except ValueError:
return symbol(token) |
def GetInfoMsg():
infoMsg = "This python snippet is triggered by the 'cmd' property.\r\n"
infoMsg += "Any command line may be triggered with the 'cmd' property.\r\n"
return infoMsg
if __name__ == "__main__":
print(GetInfoMsg()) | def get_info_msg():
info_msg = "This python snippet is triggered by the 'cmd' property.\r\n"
info_msg += "Any command line may be triggered with the 'cmd' property.\r\n"
return infoMsg
if __name__ == '__main__':
print(get_info_msg()) |
def shift_rect(rect, direction, distance=48):
if direction == 'left':
rect.left -= distance
elif direction == 'right':
rect.left += distance
elif direction == 'up':
rect.top -= distance
elif direction == 'down':
rect.top += distance
return rect
| def shift_rect(rect, direction, distance=48):
if direction == 'left':
rect.left -= distance
elif direction == 'right':
rect.left += distance
elif direction == 'up':
rect.top -= distance
elif direction == 'down':
rect.top += distance
return rect |
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 6 17:11:11 2018
@author: Haider Raheem
"""
a= float(input("Type a : "))
b= float(input("Type b : "))
c= float(input("Type c : "))
x= (a*b)+(b*c)+(c*a)
y= (a+b+c)
r= x/y
print( )
print("The result of the calculation is {0:.2f}".format(r)) | """
Created on Sat Oct 6 17:11:11 2018
@author: Haider Raheem
"""
a = float(input('Type a : '))
b = float(input('Type b : '))
c = float(input('Type c : '))
x = a * b + b * c + c * a
y = a + b + c
r = x / y
print()
print('The result of the calculation is {0:.2f}'.format(r)) |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class ObjectStatusEnum(object):
"""Implementation of the 'ObjectStatus' enum.
Specifies the status of an object during a Restore Task.
'kFilesCloned' indicates that the cloning has completed.
'kFetchedEntityInfo' indicates that information about the object was
fetched from the primary source.
'kVMCreated' indicates that the new VM was created.
'kRelocationStarted' indicates that restoring to a different
resource pool has started.
'kFinished' indicates that the Restore Task has finished.
Whether it was successful or not is indicated by the error code that
that is stored with the Restore Task.
'kAborted' indicates that the Restore Task was aborted before
trying to restore this object. This can happen if the
Restore Task encounters a global error.
For example during a 'kCloneVMs' Restore Task, the datastore
could not be mounted. The entire Restore Task is aborted
before trying to create VMs on the primary source.
'kDataCopyStarted' indicates that the disk copy is started.
'kInProgress' captures a generic in-progress state and can be used by
restore
operations that don't track individual states.
Attributes:
KFILESCLONED: TODO: type description here.
KFETCHEDENTITYINFO: TODO: type description here.
KVMCREATED: TODO: type description here.
KRELOCATIONSTARTED: TODO: type description here.
KFINISHED: TODO: type description here.
KABORTED: TODO: type description here.
KDATACOPYSTARTED: TODO: type description here.
KINPROGRESS: TODO: type description here.
"""
KFILESCLONED = 'kFilesCloned'
KFETCHEDENTITYINFO = 'kFetchedEntityInfo'
KVMCREATED = 'kVMCreated'
KRELOCATIONSTARTED = 'kRelocationStarted'
KFINISHED = 'kFinished'
KABORTED = 'kAborted'
KDATACOPYSTARTED = 'kDataCopyStarted'
KINPROGRESS = 'kInProgress'
| class Objectstatusenum(object):
"""Implementation of the 'ObjectStatus' enum.
Specifies the status of an object during a Restore Task.
'kFilesCloned' indicates that the cloning has completed.
'kFetchedEntityInfo' indicates that information about the object was
fetched from the primary source.
'kVMCreated' indicates that the new VM was created.
'kRelocationStarted' indicates that restoring to a different
resource pool has started.
'kFinished' indicates that the Restore Task has finished.
Whether it was successful or not is indicated by the error code that
that is stored with the Restore Task.
'kAborted' indicates that the Restore Task was aborted before
trying to restore this object. This can happen if the
Restore Task encounters a global error.
For example during a 'kCloneVMs' Restore Task, the datastore
could not be mounted. The entire Restore Task is aborted
before trying to create VMs on the primary source.
'kDataCopyStarted' indicates that the disk copy is started.
'kInProgress' captures a generic in-progress state and can be used by
restore
operations that don't track individual states.
Attributes:
KFILESCLONED: TODO: type description here.
KFETCHEDENTITYINFO: TODO: type description here.
KVMCREATED: TODO: type description here.
KRELOCATIONSTARTED: TODO: type description here.
KFINISHED: TODO: type description here.
KABORTED: TODO: type description here.
KDATACOPYSTARTED: TODO: type description here.
KINPROGRESS: TODO: type description here.
"""
kfilescloned = 'kFilesCloned'
kfetchedentityinfo = 'kFetchedEntityInfo'
kvmcreated = 'kVMCreated'
krelocationstarted = 'kRelocationStarted'
kfinished = 'kFinished'
kaborted = 'kAborted'
kdatacopystarted = 'kDataCopyStarted'
kinprogress = 'kInProgress' |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def getLonelyNodes(self, root: TreeNode) -> List[int]:
lonely_nodes = []
def dfs(node, is_lonely):
if node is None:
return
if is_lonely:
lonely_nodes.append(node.val)
if (node.left is None) ^ (node.right is None):
is_lonely = True
else:
is_lonely = False
dfs(node.left, is_lonely)
dfs(node.right, is_lonely)
dfs(root, False)
return lonely_nodes | class Solution:
def get_lonely_nodes(self, root: TreeNode) -> List[int]:
lonely_nodes = []
def dfs(node, is_lonely):
if node is None:
return
if is_lonely:
lonely_nodes.append(node.val)
if (node.left is None) ^ (node.right is None):
is_lonely = True
else:
is_lonely = False
dfs(node.left, is_lonely)
dfs(node.right, is_lonely)
dfs(root, False)
return lonely_nodes |
# -*- coding: utf-8 -*-
__title__ = "flloat"
__description__ = "A Python implementation of the FLLOAT library."
__url__ = "https://github.com/marcofavorito/flloat.git"
__version__ = "1.0.0a0"
__author__ = "Marco Favorito"
__author_email__ = "marco.favorito@gmail.com"
__license__ = "MIT license"
__copyright__ = "2019 Marco Favorito"
| __title__ = 'flloat'
__description__ = 'A Python implementation of the FLLOAT library.'
__url__ = 'https://github.com/marcofavorito/flloat.git'
__version__ = '1.0.0a0'
__author__ = 'Marco Favorito'
__author_email__ = 'marco.favorito@gmail.com'
__license__ = 'MIT license'
__copyright__ = '2019 Marco Favorito' |
class Solution:
def rotatedDigits(self, N: 'int') -> 'int':
result = 0
for nr in range(1, N + 1):
ok = False
for digit in str(nr):
if digit in '347':
break
if digit in '6952':
ok = True
else:
result += int(ok)
return result
| class Solution:
def rotated_digits(self, N: 'int') -> 'int':
result = 0
for nr in range(1, N + 1):
ok = False
for digit in str(nr):
if digit in '347':
break
if digit in '6952':
ok = True
else:
result += int(ok)
return result |
#--------------------------------------------------------------------------------
# SoCaTel - Backend data storage API endpoints docker container
# These tokens are needed for database access.
#--------------------------------------------------------------------------------
#===============================================================================
# SoCaTel Knowledge Base Deployment
#===============================================================================
# The following are the pre-defined names of elasticsearch indices for the SoCaTel project which
# host data shared with the front-end.
elastic_user_index = "so_user"
elastic_group_index = "so_group"
elastic_organisation_index = "so_organisation"
elastic_service_index = "so_service"
elastic_host = "<insert_elastic_host>" # e.g. "127.0.0.1"
elastic_port = "9200" # Default Elasticsearch port, change accordingly
elastic_user = "<insert_elasticsearch_username>"
elastic_passwd = "<insert_elasticsearch_password>"
#===============================================================================
#===============================================================================
# Linked Pipes ETL Configuration
#===============================================================================
# The following correspond to the URLs corresponding to the linked pipes executions,
# which need to be setup beforehand. They are set to localhost, change according to deployment details
path = "http://127.0.0.1:32800/resources/executions"
user_pipeline = "http://127.0.0.1:32800/resources/pipelines/1578586195746"
group_pipeline = "http://127.0.0.1:32800/resources/pipelines/1578586045942"
organisation_pipeline = "http://127.0.0.1:32800/resources/pipelines/1575531753483"
service_pipeline = "http://127.0.0.1:32800/resources/pipelines/1565080262463"
#===============================================================================
| elastic_user_index = 'so_user'
elastic_group_index = 'so_group'
elastic_organisation_index = 'so_organisation'
elastic_service_index = 'so_service'
elastic_host = '<insert_elastic_host>'
elastic_port = '9200'
elastic_user = '<insert_elasticsearch_username>'
elastic_passwd = '<insert_elasticsearch_password>'
path = 'http://127.0.0.1:32800/resources/executions'
user_pipeline = 'http://127.0.0.1:32800/resources/pipelines/1578586195746'
group_pipeline = 'http://127.0.0.1:32800/resources/pipelines/1578586045942'
organisation_pipeline = 'http://127.0.0.1:32800/resources/pipelines/1575531753483'
service_pipeline = 'http://127.0.0.1:32800/resources/pipelines/1565080262463' |
x1 = 1
y1 = 0
x2 = 0
y2 = -2
m1 = (y2 / x1)
x1 = 2
y1 = 2
x2 = 6
y2 = 10
m2 = (y2 - y1 / x2 - x1)
diff = m1 - m2
print(f'Diff of 8 and 9: {diff:.2f}') # 10 | x1 = 1
y1 = 0
x2 = 0
y2 = -2
m1 = y2 / x1
x1 = 2
y1 = 2
x2 = 6
y2 = 10
m2 = y2 - y1 / x2 - x1
diff = m1 - m2
print(f'Diff of 8 and 9: {diff:.2f}') |
# https://www.codechef.com/problems/COPS
for T in range(int(input())):
M,x,y=map(int,input().split())
m,a = list(map(int,input().split())),list(range(1,101))
for i in m:
for j in range(i-x*y,i+1+x*y):
if(j in a): a.remove(j)
print(len(a)) | for t in range(int(input())):
(m, x, y) = map(int, input().split())
(m, a) = (list(map(int, input().split())), list(range(1, 101)))
for i in m:
for j in range(i - x * y, i + 1 + x * y):
if j in a:
a.remove(j)
print(len(a)) |
# -*- coding: utf-8 -*-
"""
wordpress
~~~~
tamper for wordpress
:author: LoRexxar <LoRexxar@gmail.com>
:homepage: https://github.com/LoRexxar/Kunlun-M
:license: MIT, see LICENSE for more details.
:copyright: Copyright (c) 2017 LoRexxar. All rights reserved
"""
wordpress = {
"esc_url": [1000, 10001, 10002],
"esc_js": [1000, 10001, 10002],
"esc_html": [1000, 10001, 10002],
"esc_attr": [1000, 10001, 10002],
"esc_textarea": [1000, 10001, 10002],
"tag_escape": [1000, 10001, 10002],
"esc_sql": [1004, 1005, 1006],
"_real_escape": [1004, 1005, 1006],
}
wordpress_controlled = [] | """
wordpress
~~~~
tamper for wordpress
:author: LoRexxar <LoRexxar@gmail.com>
:homepage: https://github.com/LoRexxar/Kunlun-M
:license: MIT, see LICENSE for more details.
:copyright: Copyright (c) 2017 LoRexxar. All rights reserved
"""
wordpress = {'esc_url': [1000, 10001, 10002], 'esc_js': [1000, 10001, 10002], 'esc_html': [1000, 10001, 10002], 'esc_attr': [1000, 10001, 10002], 'esc_textarea': [1000, 10001, 10002], 'tag_escape': [1000, 10001, 10002], 'esc_sql': [1004, 1005, 1006], '_real_escape': [1004, 1005, 1006]}
wordpress_controlled = [] |
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: a ListNode
@param k: An integer
@return: a ListNode
@ O(n) time | O(1) space
"""
def reverseKGroup(self, head, k):
dummy = jump = ListNode(0)
dummy.next = left = right = head
while True:
count = 0
while right and count < k: # use r to locate the range
right = right.next
count += 1
if count == k: # if size k satisfied, reverse the inner linked list
pre = right
cur = left
for _ in range(k):
cur.next = pre
cur = cur.next
pre = cur # standard reversing
jump.next = pre
jump = left
left = right # connect two k-groups
else:
return dummy.next
'''
def reverseList(self, head):
prev = None
curr = head
while curr:
next = curr.next
curr.next = prev
prev = curr
curr = next
return prev
''' | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: a ListNode
@param k: An integer
@return: a ListNode
@ O(n) time | O(1) space
"""
def reverse_k_group(self, head, k):
dummy = jump = list_node(0)
dummy.next = left = right = head
while True:
count = 0
while right and count < k:
right = right.next
count += 1
if count == k:
pre = right
cur = left
for _ in range(k):
cur.next = pre
cur = cur.next
pre = cur
jump.next = pre
jump = left
left = right
else:
return dummy.next
'\ndef reverseList(self, head):\n prev = None\n curr = head\n\n while curr:\n next = curr.next\n curr.next = prev\n prev = curr\n curr = next\n \n return prev\n' |
# -*- coding: utf-8 -*-
"""
Wrapper class for Bluetooth LE servers returned from calling
:py:meth:`bleak.discover`.
Created on 2018-04-23 by hbldh <henrik.blidh@nedomkull.com>
"""
class BLEDevice(object):
"""A simple wrapper class representing a BLE server detected during
a `discover` call.
- When using Windows backend, `details` attribute is a
`Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisement` object.
- When using Linux backend, `details` attribute is a
string path to the DBus device object.
- When using macOS backend, `details` attribute will be
something else.
"""
def __init__(self, address, name, details=None, uuids=[], manufacturer_data={}):
self.address = address
self.name = name if name else "Unknown"
self.details = details
self.uuids = uuids
self.manufacturer_data = manufacturer_data
def __str__(self):
return "{0}: {1}".format(self.address, self.name)
| """
Wrapper class for Bluetooth LE servers returned from calling
:py:meth:`bleak.discover`.
Created on 2018-04-23 by hbldh <henrik.blidh@nedomkull.com>
"""
class Bledevice(object):
"""A simple wrapper class representing a BLE server detected during
a `discover` call.
- When using Windows backend, `details` attribute is a
`Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisement` object.
- When using Linux backend, `details` attribute is a
string path to the DBus device object.
- When using macOS backend, `details` attribute will be
something else.
"""
def __init__(self, address, name, details=None, uuids=[], manufacturer_data={}):
self.address = address
self.name = name if name else 'Unknown'
self.details = details
self.uuids = uuids
self.manufacturer_data = manufacturer_data
def __str__(self):
return '{0}: {1}'.format(self.address, self.name) |
#
# Hubblemon - Yet another general purpose system monitor
#
# Copyright 2015 NAVER Corp.
#
# 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.
#
class jquery:
def __init__(self):
self.scripts = []
def render(self):
pass
def autocomplete(self, id):
ret = jquery_autocomplete(id)
self.scripts.append(ret)
return ret
def button(self, id):
ret = jquery_button(id)
self.scripts.append(ret)
return ret
def selectable(self, id):
ret = jquery_selectable(id)
self.scripts.append(ret)
return ret
def radio(self, id):
ret = jquery_radio(id)
self.scripts.append(ret)
return ret
class jscript:
def __init__(self, action):
self.action = action
def render(self):
js_template = self.get_js_template()
return js_template % (self.action)
def get_js_template(self):
js_template = '''
<script type="text/javascript">
$(function() {
%s;
});
</script>
'''
return js_template
class jqueryui:
def __init__(self, id):
self.id = id
self.target = None
def val(self, v = None):
if v is None:
return "$('#%s').val()" % (self.id)
else:
return "$('#%s').val(%s)" % (self.id, v)
def val_str(self, v = None):
if v is None:
return "$('#%s').val()" % (self.id)
else:
return "$('#%s').val('%s')" % (self.id, v)
def text(self, v = None):
if v is None:
return "$('#%s').text()" % (self.id)
else:
return "$('#%s').text(%s)" % (self.id, v)
def text_str(self, v = None):
if v is None:
return "$('#%s').text()" % (self.id)
else:
return "$('#%s').text('%s')" % (self.id, v)
class jquery_autocomplete(jqueryui):
def set(self, source, action):
self.source = source
self.action = action
def render(self):
raw_data = self.source.__repr__()
js_template = self.get_js_template()
return js_template % (self.id, raw_data, self.action, self.id)
def source(self, url):
return "$('#%s').autocomplete('option', 'source', %s);" % (self.id, url)
def get_js_template(self):
js_template = '''
<script type="text/javascript">
$(function() {
$('#%s').autocomplete({
source: %s,
minLength: 0,
select: function( event, ui ) {
%s;
return false;
}
}).focus(function(){
$(this).autocomplete('search', $(this).val())});
});
</script>
<input type="text" id="%s">
'''
return js_template
# TODO
class jquery_selectable(jqueryui):
def __init__(self, id):
self.id = id
self.select_list = []
def push_item(self, item):
self.select_list.append(item)
def render(self):
select_list = ''
for item in self.select_list:
select_list += "<li class='ui-widget-content'>%s</li>\n" % item
js_template = self.get_js_template()
id = self.id
return js_template % (id, id, id, id, id, select_list)
def get_js_template(self):
js_template = '''
<style>
#%s .ui-selecting { background: #FECA40; }
#%s .ui-selected { background: #F39814; color: white; }
#%s { list-style-type: none; margin:0; padding:0; }
.ui-widget-content { display:inline; margin: 0 0 0 0; padding: 0 0 0 0; border: 1; }
</style>
<script type="text/javascript">
$(function() {
$('#%s').selectable();
});
</script>
<ul id='%s'>
%s
</ul>
'''
return js_template
class jquery_button(jqueryui):
def __init__(self, id):
self.id = id
self.action = ''
def set_action(self, action):
self.action = action
def render(self):
js_template = self.get_js_template()
return js_template % (self.id, self.action, self.id, self.id)
def get_js_template(self):
js_template = '''
<script type="text/javascript">
$(function() {
$('#%s').button().click(
function() {
%s;
}
);
});
</script>
<button id='%s' float>%s</button>
'''
return js_template
class jquery_radio(jqueryui):
def __init__(self, id):
self.id = id
self.action = ''
self.button_list = []
def push_item(self, item):
self.button_list.append(item)
def set_action(self, action):
self.action = action
def render(self):
button_list = ''
for item in self.button_list:
button_list += "<input type='radio' id='%s' name='radio'><label for='%s'>%s</label>" % (item, item, item)
js_template = self.get_js_template()
id = self.id
return js_template % (id, id, self.action, id, button_list)
def get_js_template(self):
js_template = '''
<script type="text/javascript">
$(function() {
$('#%s').buttonset();
$('#%s :radio').click(function() {
%s;
});
});
</script>
<ul id='%s' style="display:inline">
%s
</ul>
'''
return js_template
| class Jquery:
def __init__(self):
self.scripts = []
def render(self):
pass
def autocomplete(self, id):
ret = jquery_autocomplete(id)
self.scripts.append(ret)
return ret
def button(self, id):
ret = jquery_button(id)
self.scripts.append(ret)
return ret
def selectable(self, id):
ret = jquery_selectable(id)
self.scripts.append(ret)
return ret
def radio(self, id):
ret = jquery_radio(id)
self.scripts.append(ret)
return ret
class Jscript:
def __init__(self, action):
self.action = action
def render(self):
js_template = self.get_js_template()
return js_template % self.action
def get_js_template(self):
js_template = '\n\t\t\t<script type="text/javascript">\n\t\t\t $(function() {\n\t\t\t\t%s;\n\t\t\t });\n\t\t\t</script>\n\t\t'
return js_template
class Jqueryui:
def __init__(self, id):
self.id = id
self.target = None
def val(self, v=None):
if v is None:
return "$('#%s').val()" % self.id
else:
return "$('#%s').val(%s)" % (self.id, v)
def val_str(self, v=None):
if v is None:
return "$('#%s').val()" % self.id
else:
return "$('#%s').val('%s')" % (self.id, v)
def text(self, v=None):
if v is None:
return "$('#%s').text()" % self.id
else:
return "$('#%s').text(%s)" % (self.id, v)
def text_str(self, v=None):
if v is None:
return "$('#%s').text()" % self.id
else:
return "$('#%s').text('%s')" % (self.id, v)
class Jquery_Autocomplete(jqueryui):
def set(self, source, action):
self.source = source
self.action = action
def render(self):
raw_data = self.source.__repr__()
js_template = self.get_js_template()
return js_template % (self.id, raw_data, self.action, self.id)
def source(self, url):
return "$('#%s').autocomplete('option', 'source', %s);" % (self.id, url)
def get_js_template(self):
js_template = '\n\t\t\t<script type="text/javascript">\n\t\t\t $(function() {\n\t\t\t\t$(\'#%s\').autocomplete({\n\t\t\t\t source: %s,\n\t\t\t\t minLength: 0,\n\t\t\t\t select: function( event, ui ) {\n\t\t\t\t\t%s;\n\t\t\t\t\treturn false;\n\t\t\t\t }\n\t\t\t\t}).focus(function(){\n\t\t\t\t $(this).autocomplete(\'search\', $(this).val())});\n\t\t\t });\n\t\t\t</script>\n\n\t\t\t<input type="text" id="%s"> \n\t\t'
return js_template
class Jquery_Selectable(jqueryui):
def __init__(self, id):
self.id = id
self.select_list = []
def push_item(self, item):
self.select_list.append(item)
def render(self):
select_list = ''
for item in self.select_list:
select_list += "<li class='ui-widget-content'>%s</li>\n" % item
js_template = self.get_js_template()
id = self.id
return js_template % (id, id, id, id, id, select_list)
def get_js_template(self):
js_template = '\n\t\t\t<style>\n\t\t\t#%s .ui-selecting { background: #FECA40; }\n\t\t\t#%s .ui-selected { background: #F39814; color: white; }\n\t\t\t#%s { list-style-type: none; margin:0; padding:0; }\n\t\t\t.ui-widget-content { display:inline; margin: 0 0 0 0; padding: 0 0 0 0; border: 1; }\n\t\t\t</style>\n\n\t\t\t<script type="text/javascript">\n\t\t\t $(function() {\n\t\t\t\t$(\'#%s\').selectable();\n\t\t\t });\n\t\t\t</script>\n\n\t\t\t<ul id=\'%s\'>\n\t\t\t\t%s\n\t\t\t</ul>\n\t\t'
return js_template
class Jquery_Button(jqueryui):
def __init__(self, id):
self.id = id
self.action = ''
def set_action(self, action):
self.action = action
def render(self):
js_template = self.get_js_template()
return js_template % (self.id, self.action, self.id, self.id)
def get_js_template(self):
js_template = '\n\t\t\t<script type="text/javascript">\n\t\t\t $(function() {\n\t\t\t\t$(\'#%s\').button().click(\n\t\t\t\t\tfunction() {\n\t\t\t\t\t\t%s;\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t });\n\t\t\t</script>\n\n\t\t\t<button id=\'%s\' float>%s</button>\n\t\t'
return js_template
class Jquery_Radio(jqueryui):
def __init__(self, id):
self.id = id
self.action = ''
self.button_list = []
def push_item(self, item):
self.button_list.append(item)
def set_action(self, action):
self.action = action
def render(self):
button_list = ''
for item in self.button_list:
button_list += "<input type='radio' id='%s' name='radio'><label for='%s'>%s</label>" % (item, item, item)
js_template = self.get_js_template()
id = self.id
return js_template % (id, id, self.action, id, button_list)
def get_js_template(self):
js_template = '\n\t\t\t<script type="text/javascript">\n\t\t\t $(function() {\n\t\t\t\t$(\'#%s\').buttonset();\n\t\t\t\t$(\'#%s :radio\').click(function() {\n\t\t\t\t\t%s;\n\t\t\t\t});\n\t\t\t });\n\t\t\t</script>\n\n\t\t\t<ul id=\'%s\' style="display:inline">\n\t\t\t\t%s\n\t\t\t</ul>\n\t\t'
return js_template |
class DataGridViewCellStateChangedEventArgs(EventArgs):
"""
Provides data for the System.Windows.Forms.DataGridView.CellStateChanged event.
DataGridViewCellStateChangedEventArgs(dataGridViewCell: DataGridViewCell,stateChanged: DataGridViewElementStates)
"""
@staticmethod
def __new__(self, dataGridViewCell, stateChanged):
""" __new__(cls: type,dataGridViewCell: DataGridViewCell,stateChanged: DataGridViewElementStates) """
pass
Cell = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Gets the System.Windows.Forms.DataGridViewCell that has a changed state.
Get: Cell(self: DataGridViewCellStateChangedEventArgs) -> DataGridViewCell
"""
StateChanged = property(
lambda self: object(), lambda self, v: None, lambda self: None
)
"""Gets the state that has changed on the cell.
Get: StateChanged(self: DataGridViewCellStateChangedEventArgs) -> DataGridViewElementStates
"""
| class Datagridviewcellstatechangedeventargs(EventArgs):
"""
Provides data for the System.Windows.Forms.DataGridView.CellStateChanged event.
DataGridViewCellStateChangedEventArgs(dataGridViewCell: DataGridViewCell,stateChanged: DataGridViewElementStates)
"""
@staticmethod
def __new__(self, dataGridViewCell, stateChanged):
""" __new__(cls: type,dataGridViewCell: DataGridViewCell,stateChanged: DataGridViewElementStates) """
pass
cell = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets the System.Windows.Forms.DataGridViewCell that has a changed state.\n\n\n\nGet: Cell(self: DataGridViewCellStateChangedEventArgs) -> DataGridViewCell\n\n\n\n'
state_changed = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets the state that has changed on the cell.\n\n\n\nGet: StateChanged(self: DataGridViewCellStateChangedEventArgs) -> DataGridViewElementStates\n\n\n\n' |
description = 'Verify the user cannot log in if password value is missing'
pages = ['login']
def test(data):
navigate(data.env.url)
send_keys(login.username_input, 'admin')
click(login.login_button)
capture('Verify the correct error message is shown')
verify_text_in_element(login.error_list, 'Password is required')
| description = 'Verify the user cannot log in if password value is missing'
pages = ['login']
def test(data):
navigate(data.env.url)
send_keys(login.username_input, 'admin')
click(login.login_button)
capture('Verify the correct error message is shown')
verify_text_in_element(login.error_list, 'Password is required') |
#######################################################################
# Copyright (C) 2017 Shangtong Zhang(zhangshangtong.cpp@gmail.com) #
# Permission given to modify the code as long as you keep this #
# declaration at the top #
#######################################################################
class ConstantSchedule:
def __init__(self, val):
self.val = val
def __call__(self, steps=1):
return self.val
class LinearSchedule:
def __init__(self, start, end=None, steps=None):
if end is None:
end = start
steps = 1
self.inc = (end - start) / float(steps)
self.current = start
self.end = end
if end > start:
self.bound = min
else:
self.bound = max
def __call__(self, steps=1):
val = self.current
self.current = self.bound(self.current + self.inc * steps, self.end)
return val | class Constantschedule:
def __init__(self, val):
self.val = val
def __call__(self, steps=1):
return self.val
class Linearschedule:
def __init__(self, start, end=None, steps=None):
if end is None:
end = start
steps = 1
self.inc = (end - start) / float(steps)
self.current = start
self.end = end
if end > start:
self.bound = min
else:
self.bound = max
def __call__(self, steps=1):
val = self.current
self.current = self.bound(self.current + self.inc * steps, self.end)
return val |
"""Version details for python-marketman
This file shamelessly taken from the requests library"""
__title__ = 'python-marketman'
__description__ = 'A basic Marketman.com REST API client.'
__url__ = 'https://github.com/LukasKlement/python-marketman'
__version__ = '0.1'
__author__ = 'Lukas Klement'
__author_email__ = 'lukas.klement@me.com'
__license__ = 'Apache 2.0'
__maintainer__ = 'Lukas Klement'
__maintainer_email__ = 'lukas.klement@me.com'
__keywords__ = 'python marketman marketman.com'
| """Version details for python-marketman
This file shamelessly taken from the requests library"""
__title__ = 'python-marketman'
__description__ = 'A basic Marketman.com REST API client.'
__url__ = 'https://github.com/LukasKlement/python-marketman'
__version__ = '0.1'
__author__ = 'Lukas Klement'
__author_email__ = 'lukas.klement@me.com'
__license__ = 'Apache 2.0'
__maintainer__ = 'Lukas Klement'
__maintainer_email__ = 'lukas.klement@me.com'
__keywords__ = 'python marketman marketman.com' |
def forward(w,s,b,y):
Yhat= w * s + b
output = (Yhat-y)**2
return output, Yhat
def derivative_W(x, output, Yhat, y):
return ((2 * output) * (Yhat - y)) * x # w
def derivative_B(b, output, Yhat, y):
return ((2 * output) * (Yhat - y)) * b #bias
def main():
w = 1.0 #weight
x = 2.0 #sample
b = 1.0 #bias
y = 2.0*x #rule
learning = 1e-1
epoch = 3
for i in range(epoch+1):
output, Yhat = forward(w,x,b,y)
print("-----------------------------------------------------------------------------")
print("w:",w)
print("\tw*b:",w*x)
print("x:",x,"\t\tsum:", w*x+b)
print("\tb:",b,"\t\t\tg1:",abs(Yhat-y),"\tg2:",abs(Yhat-y)**2,"\tloss:",output)
print("\t\tY=2*x:", y)
print("-----------------------------------------------------------------------------")
if output == 0.0:
break
gw = derivative_W(x, output, Yhat, y)
gb = derivative_B(b, output, Yhat, y)
w -= learning * gw
b -= learning * gb
if __name__ == '__main__':
main()
| def forward(w, s, b, y):
yhat = w * s + b
output = (Yhat - y) ** 2
return (output, Yhat)
def derivative_w(x, output, Yhat, y):
return 2 * output * (Yhat - y) * x
def derivative_b(b, output, Yhat, y):
return 2 * output * (Yhat - y) * b
def main():
w = 1.0
x = 2.0
b = 1.0
y = 2.0 * x
learning = 0.1
epoch = 3
for i in range(epoch + 1):
(output, yhat) = forward(w, x, b, y)
print('-----------------------------------------------------------------------------')
print('w:', w)
print('\tw*b:', w * x)
print('x:', x, '\t\tsum:', w * x + b)
print('\tb:', b, '\t\t\tg1:', abs(Yhat - y), '\tg2:', abs(Yhat - y) ** 2, '\tloss:', output)
print('\t\tY=2*x:', y)
print('-----------------------------------------------------------------------------')
if output == 0.0:
break
gw = derivative_w(x, output, Yhat, y)
gb = derivative_b(b, output, Yhat, y)
w -= learning * gw
b -= learning * gb
if __name__ == '__main__':
main() |
# -*- coding: utf-8 -*-
"""Top-level package for Test."""
__author__ = """Lana Maidenbaum"""
__email__ = 'lana.maidenbaum@zeel.com'
__version__ = '0.1.1'
| """Top-level package for Test."""
__author__ = 'Lana Maidenbaum'
__email__ = 'lana.maidenbaum@zeel.com'
__version__ = '0.1.1' |
"""
SpEC
~~~~~~~~~~~~~~~~~~~
Sparsity, Explainability, and Communication
:copyright: (c) 2019 by Marcos Treviso
:licence: MIT, see LICENSE for more details
"""
# Generate your own AsciiArt at:
# patorjk.com/software/taag/#f=Calvin%20S&t=SpEC
__banner__ = """
_____ _____ _____
| __|___| __| |
|__ | . | __| --|
|_____| _|_____|_____|
|_|
"""
__prog__ = "spec"
__title__ = 'SpEC'
__summary__ = 'Sparsity, Explainability, and Communication'
__uri__ = 'https://github.com/mtreviso/spec'
__version__ = '0.0.1'
__author__ = 'Marcos V. Treviso and Andre F. T. Martins'
__email__ = 'marcostreviso@gmail.com'
__license__ = 'MIT'
__copyright__ = 'Copyright 2019 Marcos Treviso'
| """
SpEC
~~~~~~~~~~~~~~~~~~~
Sparsity, Explainability, and Communication
:copyright: (c) 2019 by Marcos Treviso
:licence: MIT, see LICENSE for more details
"""
__banner__ = '\n _____ _____ _____\n| __|___| __| |\n|__ | . | __| --|\n|_____| _|_____|_____|\n |_|\n'
__prog__ = 'spec'
__title__ = 'SpEC'
__summary__ = 'Sparsity, Explainability, and Communication'
__uri__ = 'https://github.com/mtreviso/spec'
__version__ = '0.0.1'
__author__ = 'Marcos V. Treviso and Andre F. T. Martins'
__email__ = 'marcostreviso@gmail.com'
__license__ = 'MIT'
__copyright__ = 'Copyright 2019 Marcos Treviso' |
def banner(message, length, header='=', footer='*'):
print()
print(header * length)
print((' ' * (length//2 - len(message)//2)), message)
print(footer * length)
def banner_v2(length, footer='-'):
print(footer * length)
print()
| def banner(message, length, header='=', footer='*'):
print()
print(header * length)
print(' ' * (length // 2 - len(message) // 2), message)
print(footer * length)
def banner_v2(length, footer='-'):
print(footer * length)
print() |
# Soft-serve Damage Skin
success = sm.addDamageSkin(2434951)
if success:
sm.chat("The Soft-serve Damage Skin has been added to your account's damage skin collection.")
| success = sm.addDamageSkin(2434951)
if success:
sm.chat("The Soft-serve Damage Skin has been added to your account's damage skin collection.") |
num1 = 100
num2 = 200
num3 = 300
num4 = 400
num5 = 500
mum6 = 600
num7 = 700
num8 = 800
| num1 = 100
num2 = 200
num3 = 300
num4 = 400
num5 = 500
mum6 = 600
num7 = 700
num8 = 800 |
# Link - https://leetcode.com/problems/implement-strstr/
"""
28. Implement strStr()
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Example 3:
Input: haystack = "", needle = ""
Output: 0
Constraints:
0 <= haystack.length, needle.length <= 5 * 104
haystack and needle consist of only lower-case English characters.
"""
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if len(needle) == 0:
return 0
else:
try:
return haystack.index(needle)
except ValueError:
return -1
| """
28. Implement strStr()
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Example 3:
Input: haystack = "", needle = ""
Output: 0
Constraints:
0 <= haystack.length, needle.length <= 5 * 104
haystack and needle consist of only lower-case English characters.
"""
class Solution:
def str_str(self, haystack: str, needle: str) -> int:
if len(needle) == 0:
return 0
else:
try:
return haystack.index(needle)
except ValueError:
return -1 |
def required_model(name: object, kwargs: object) -> object:
required_fields = kwargs['required_fields'] if 'required_fields' in kwargs else []
task_f = kwargs['required_task_fields'] if 'required_task_fields' in kwargs else []
proc_f = kwargs['required_proc_fields'] if 'required_proc_fields' in kwargs else []
display_name = kwargs['display_name'] if 'display_name' in kwargs else name
def f(klass):
return klass
return f | def required_model(name: object, kwargs: object) -> object:
required_fields = kwargs['required_fields'] if 'required_fields' in kwargs else []
task_f = kwargs['required_task_fields'] if 'required_task_fields' in kwargs else []
proc_f = kwargs['required_proc_fields'] if 'required_proc_fields' in kwargs else []
display_name = kwargs['display_name'] if 'display_name' in kwargs else name
def f(klass):
return klass
return f |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Unit:
def __init__(self, x, y, color, name):
self.x = x
self.y = y
self.color = color
self.name = name
self.taken = False
class OpUnit(Unit):
def __init__(self, x, y, color, name):
super().__init__(x, y, color, name)
self.blue = 0.0 | class Unit:
def __init__(self, x, y, color, name):
self.x = x
self.y = y
self.color = color
self.name = name
self.taken = False
class Opunit(Unit):
def __init__(self, x, y, color, name):
super().__init__(x, y, color, name)
self.blue = 0.0 |
#!/usr/bin/env python
#coding: utf-8
class Node:
def __init__(self, elem=None, next=None):
self.elem = elem
self.next = next
if __name__ == "__main__":
n1 = Node(1, None)
n2 = Node(2, None)
n1.next = n2
| class Node:
def __init__(self, elem=None, next=None):
self.elem = elem
self.next = next
if __name__ == '__main__':
n1 = node(1, None)
n2 = node(2, None)
n1.next = n2 |
def test_check_sanity(client):
resp = client.get('/sanity')
assert resp.status_code == 200
assert 'Sanity check passed.' == resp.data.decode()
# 'list collections' tests
def test_get_api_root(client):
resp = client.get('/', content_type='application/json')
assert resp.status_code == 200
resp_data = resp.get_json()
assert 'keys_url' in resp_data
assert len(resp_data) == 1
assert resp_data['keys_url'][-5:] == '/keys'
def test_delete_api_root_not_allowed(client):
resp = client.delete('/', content_type='application/json')
assert resp.status_code == 405
# 'list keys' tests
def test_get_empty_keys_list(client):
resp = client.get('/keys', content_type='application/json')
assert resp.status_code == 200
resp_data = resp.get_json()
assert len(resp_data) == 0
def test_get_nonempty_keys_list(client, keys, add_to_keys):
add_to_keys({'key': 'babboon', 'value': 'Larry'})
add_to_keys({'key': 'bees', 'value': ['Ann', 'Joe', 'Dee']})
resp = client.get('/keys', content_type='application/json')
assert resp.status_code == 200
resp_data = resp.get_json()
assert isinstance(resp_data, list)
assert len(resp_data) == 2
for doc_idx in (0, 1):
for k in ('key', 'http_url'):
assert k in resp_data[doc_idx]
if resp_data[doc_idx]['key'] == 'babboon':
assert resp_data[doc_idx]['http_url'][-13:] == '/keys/babboon'
else:
assert resp_data[doc_idx]['http_url'][-10:] == '/keys/bees'
def test_delete_on_keys_not_allowed(client):
resp = client.delete('/keys', content_type='application/json')
assert resp.status_code == 405
# 'get a key' tests
def test_get_existing_key(client, keys, add_to_keys):
add_to_keys({'key': 'babboon', 'value': 'Larry'})
add_to_keys({'key': 'bees', 'value': ['Ann', 'Joe', 'Dee']})
resp = client.get('/keys/bees', content_type='application/json')
assert resp.status_code == 200
resp_data = resp.get_json()
assert isinstance(resp_data, dict)
for k in ('key', 'http_url', 'value'):
assert k in resp_data
assert resp_data['key'] == 'bees'
assert resp_data['http_url'][-10:] == '/keys/bees'
assert resp_data['value'] == ['Ann', 'Joe', 'Dee']
def test_get_nonexisting_key(client, keys):
resp = client.get('/keys/bees', content_type='application/json')
assert resp.status_code == 404
def test_post_on_a_key_not_allowed(client):
resp = client.post('/keys/bees', content_type='application/json')
assert resp.status_code == 405
# 'create a key' tests
def test_create_new_key(client, keys):
new_doc = {'key': 'oscillator', 'value': 'Colpitts'}
resp = client.post(
'/keys',
json=new_doc,
content_type='application/json'
)
assert resp.status_code == 201
resp_data = resp.get_json()
assert isinstance(resp_data, dict)
for k in ('key', 'http_url', 'value'):
assert k in resp_data
assert resp_data['key'] == new_doc['key']
assert resp_data['value'] == new_doc['value']
assert resp_data['http_url'][-16:] == '/keys/oscillator'
def test_create_duplicate_key(client, keys, add_to_keys):
new_doc = {'key': 'oscillator', 'value': 'Colpitts'}
add_to_keys(new_doc.copy())
resp = client.post(
'/keys',
json=new_doc,
content_type='application/json'
)
assert resp.status_code == 400
resp_data = resp.get_json()
assert 'error' in resp_data
assert resp_data['error'] == "Can't create duplicate key (oscillator)."
def test_create_new_key_missing_key(client, keys):
new_doc = {'value': 'Colpitts'}
resp = client.post(
'/keys',
json=new_doc,
content_type='application/json'
)
assert resp.status_code == 400
resp_data = resp.get_json()
assert 'error' in resp_data
assert resp_data['error'] == 'Please provide the missing "key" parameter!'
def test_create_new_key_missing_value(client, keys):
new_doc = {'key': 'oscillator'}
resp = client.post(
'/keys',
json=new_doc,
content_type='application/json'
)
assert resp.status_code == 400
resp_data = resp.get_json()
assert 'error' in resp_data
assert resp_data['error'] == 'Please provide the missing "value" ' \
'parameter!'
# 'update a key' tests
def test_update_a_key_existing(client, keys, add_to_keys):
add_to_keys({'key': 'oscillator', 'value': 'Colpitts'})
update_value = {'value': ['Pierce', 'Hartley']}
resp = client.put(
'/keys/oscillator',
json=update_value,
content_type='application/json'
)
assert resp.status_code == 204
def test_update_a_key_nonexisting(client, keys, add_to_keys):
add_to_keys({'key': 'oscillator', 'value': 'Colpitts'})
update_value = {'value': ['Pierce', 'Hartley']}
resp = client.put(
'/keys/gadget',
json=update_value,
content_type='application/json'
)
assert resp.status_code == 400
resp_data = resp.get_json()
assert 'error' in resp_data
assert resp_data['error'] == 'Update failed.'
# 'delete a key' tests
def test_delete_a_key_existing(client, keys, add_to_keys):
add_to_keys({'key': 'oscillator', 'value': 'Colpitts'})
resp = client.delete(
'/keys/oscillator',
content_type='application/json'
)
assert resp.status_code == 204
def test_delete_a_key_nonexisting(client, keys):
resp = client.delete(
'/keys/oscillator',
content_type='application/json'
)
assert resp.status_code == 404
| def test_check_sanity(client):
resp = client.get('/sanity')
assert resp.status_code == 200
assert 'Sanity check passed.' == resp.data.decode()
def test_get_api_root(client):
resp = client.get('/', content_type='application/json')
assert resp.status_code == 200
resp_data = resp.get_json()
assert 'keys_url' in resp_data
assert len(resp_data) == 1
assert resp_data['keys_url'][-5:] == '/keys'
def test_delete_api_root_not_allowed(client):
resp = client.delete('/', content_type='application/json')
assert resp.status_code == 405
def test_get_empty_keys_list(client):
resp = client.get('/keys', content_type='application/json')
assert resp.status_code == 200
resp_data = resp.get_json()
assert len(resp_data) == 0
def test_get_nonempty_keys_list(client, keys, add_to_keys):
add_to_keys({'key': 'babboon', 'value': 'Larry'})
add_to_keys({'key': 'bees', 'value': ['Ann', 'Joe', 'Dee']})
resp = client.get('/keys', content_type='application/json')
assert resp.status_code == 200
resp_data = resp.get_json()
assert isinstance(resp_data, list)
assert len(resp_data) == 2
for doc_idx in (0, 1):
for k in ('key', 'http_url'):
assert k in resp_data[doc_idx]
if resp_data[doc_idx]['key'] == 'babboon':
assert resp_data[doc_idx]['http_url'][-13:] == '/keys/babboon'
else:
assert resp_data[doc_idx]['http_url'][-10:] == '/keys/bees'
def test_delete_on_keys_not_allowed(client):
resp = client.delete('/keys', content_type='application/json')
assert resp.status_code == 405
def test_get_existing_key(client, keys, add_to_keys):
add_to_keys({'key': 'babboon', 'value': 'Larry'})
add_to_keys({'key': 'bees', 'value': ['Ann', 'Joe', 'Dee']})
resp = client.get('/keys/bees', content_type='application/json')
assert resp.status_code == 200
resp_data = resp.get_json()
assert isinstance(resp_data, dict)
for k in ('key', 'http_url', 'value'):
assert k in resp_data
assert resp_data['key'] == 'bees'
assert resp_data['http_url'][-10:] == '/keys/bees'
assert resp_data['value'] == ['Ann', 'Joe', 'Dee']
def test_get_nonexisting_key(client, keys):
resp = client.get('/keys/bees', content_type='application/json')
assert resp.status_code == 404
def test_post_on_a_key_not_allowed(client):
resp = client.post('/keys/bees', content_type='application/json')
assert resp.status_code == 405
def test_create_new_key(client, keys):
new_doc = {'key': 'oscillator', 'value': 'Colpitts'}
resp = client.post('/keys', json=new_doc, content_type='application/json')
assert resp.status_code == 201
resp_data = resp.get_json()
assert isinstance(resp_data, dict)
for k in ('key', 'http_url', 'value'):
assert k in resp_data
assert resp_data['key'] == new_doc['key']
assert resp_data['value'] == new_doc['value']
assert resp_data['http_url'][-16:] == '/keys/oscillator'
def test_create_duplicate_key(client, keys, add_to_keys):
new_doc = {'key': 'oscillator', 'value': 'Colpitts'}
add_to_keys(new_doc.copy())
resp = client.post('/keys', json=new_doc, content_type='application/json')
assert resp.status_code == 400
resp_data = resp.get_json()
assert 'error' in resp_data
assert resp_data['error'] == "Can't create duplicate key (oscillator)."
def test_create_new_key_missing_key(client, keys):
new_doc = {'value': 'Colpitts'}
resp = client.post('/keys', json=new_doc, content_type='application/json')
assert resp.status_code == 400
resp_data = resp.get_json()
assert 'error' in resp_data
assert resp_data['error'] == 'Please provide the missing "key" parameter!'
def test_create_new_key_missing_value(client, keys):
new_doc = {'key': 'oscillator'}
resp = client.post('/keys', json=new_doc, content_type='application/json')
assert resp.status_code == 400
resp_data = resp.get_json()
assert 'error' in resp_data
assert resp_data['error'] == 'Please provide the missing "value" parameter!'
def test_update_a_key_existing(client, keys, add_to_keys):
add_to_keys({'key': 'oscillator', 'value': 'Colpitts'})
update_value = {'value': ['Pierce', 'Hartley']}
resp = client.put('/keys/oscillator', json=update_value, content_type='application/json')
assert resp.status_code == 204
def test_update_a_key_nonexisting(client, keys, add_to_keys):
add_to_keys({'key': 'oscillator', 'value': 'Colpitts'})
update_value = {'value': ['Pierce', 'Hartley']}
resp = client.put('/keys/gadget', json=update_value, content_type='application/json')
assert resp.status_code == 400
resp_data = resp.get_json()
assert 'error' in resp_data
assert resp_data['error'] == 'Update failed.'
def test_delete_a_key_existing(client, keys, add_to_keys):
add_to_keys({'key': 'oscillator', 'value': 'Colpitts'})
resp = client.delete('/keys/oscillator', content_type='application/json')
assert resp.status_code == 204
def test_delete_a_key_nonexisting(client, keys):
resp = client.delete('/keys/oscillator', content_type='application/json')
assert resp.status_code == 404 |
'''
Single perceptron can replicate a NAND gate
https://en.wikipedia.org/wiki/NAND_logic
inputs | output
0 0 1
0 1 1
1 0 1
1 1 0
'''
def dot_product(vec1,vec2):
if (len(vec1) != len(vec2)):
print("input vector lengths are not equal")
print(len(vec1))
print(len(vec2))
reslt=0
for indx in range(len(vec1)):
reslt=reslt+vec1[indx]*vec2[indx]
return reslt
def perceptron(input_binary_vector,weight_vector,bias):
reslt = dot_product(input_binary_vector,weight_vector)
if ( reslt + bias <= 0 ): # aka reslt <= threshold
output=0
else: # reslt > threshold, aka reslt + bias > 0
output=1
return output
def nand(input_binary_vector):
if (len(input_binary_vector) != 2):
print("input vector length is not 2; this is an NAND gate!")
return int(not (input_binary_vector[0] and input_binary_vector[1]))
# weight. Higher value means more important
w = [-2, -2]
bias = 3
for indx in range(4):
# input decision factors; value 0 or 1
if (indx == 0): x = [ 0, 0]
elif (indx == 1): x = [ 1, 0]
elif (indx == 2): x = [ 0, 1]
elif (indx == 3): x = [ 1, 1]
else: print("error in indx")
print("input: "+str(x[0])+", "+str(x[1]))
print("preceptron: "+str(perceptron(x,w,bias)))
print("NAND: "+str(nand(x)))
| """
Single perceptron can replicate a NAND gate
https://en.wikipedia.org/wiki/NAND_logic
inputs | output
0 0 1
0 1 1
1 0 1
1 1 0
"""
def dot_product(vec1, vec2):
if len(vec1) != len(vec2):
print('input vector lengths are not equal')
print(len(vec1))
print(len(vec2))
reslt = 0
for indx in range(len(vec1)):
reslt = reslt + vec1[indx] * vec2[indx]
return reslt
def perceptron(input_binary_vector, weight_vector, bias):
reslt = dot_product(input_binary_vector, weight_vector)
if reslt + bias <= 0:
output = 0
else:
output = 1
return output
def nand(input_binary_vector):
if len(input_binary_vector) != 2:
print('input vector length is not 2; this is an NAND gate!')
return int(not (input_binary_vector[0] and input_binary_vector[1]))
w = [-2, -2]
bias = 3
for indx in range(4):
if indx == 0:
x = [0, 0]
elif indx == 1:
x = [1, 0]
elif indx == 2:
x = [0, 1]
elif indx == 3:
x = [1, 1]
else:
print('error in indx')
print('input: ' + str(x[0]) + ', ' + str(x[1]))
print('preceptron: ' + str(perceptron(x, w, bias)))
print('NAND: ' + str(nand(x))) |
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A):
# write your code in Python 3.6
dictionary = {}
for number in A:
if dictionary.get(number) == None:
dictionary[number] = 1
else:
dictionary[number] += 1
for key in dictionary.keys():
if dictionary.get(key) % 2 == 1:
return key
| def solution(A):
dictionary = {}
for number in A:
if dictionary.get(number) == None:
dictionary[number] = 1
else:
dictionary[number] += 1
for key in dictionary.keys():
if dictionary.get(key) % 2 == 1:
return key |
print(4+3);
print("Hello");
print('Who are you');
print('This is Pradeep\'s python program');
print(r'C:\Users\N51254\Documents\NetBeansProjects');
print("Pradeep "*5); | print(4 + 3)
print('Hello')
print('Who are you')
print("This is Pradeep's python program")
print('C:\\Users\\N51254\\Documents\\NetBeansProjects')
print('Pradeep ' * 5) |
class Bank():
def __init__(self):
pass
def reduce(self, source, to):
return source.reduce(to)
| class Bank:
def __init__(self):
pass
def reduce(self, source, to):
return source.reduce(to) |
"""
Solution to Word in Reverse
"""
if __name__ == '__main__':
while True:
word = input('Enter a word: ')
word = str(word)
i = len(word)
reversed_word = ''
while i > 0:
reversed_word += word[i - 1]
i -= 1
print('{reversed_word}\n'.format(reversed_word=reversed_word))
| """
Solution to Word in Reverse
"""
if __name__ == '__main__':
while True:
word = input('Enter a word: ')
word = str(word)
i = len(word)
reversed_word = ''
while i > 0:
reversed_word += word[i - 1]
i -= 1
print('{reversed_word}\n'.format(reversed_word=reversed_word)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.