content
stringlengths 7
1.05M
|
---|
#Cristian Chitiva
#cychitivav@unal.edu.co
#12/Sept/2018
myList = ['Hi', 5, 6 , 3.4, "i"] #Create the list
myList.append([4, 5]) #Add sublist [4, 5] to myList
myList.insert(2,"f") #Add "f" in the position 2
print(myList)
myList = [1, 3, 4, 5, 23, 4, 3, 222, 454, 6445, 6, 4654, 455]
myList.sort() #Sort the list from lowest to highest
print(myList)
myList.sort(reverse = True) #Sort the list from highest to lowest
print(myList)
myList.extend([5, 77]) #Add 5 and 77 to myList
print(myList)
#List comprehension
myList = []
for value in range(0, 50):
myList.append(value)
print(myList)
myList = ["f" for value in range(0,20)]
print(myList)
myList = [value for value in range(0,20)]
print(myList)
myList = [value for value in range(0,60,3) if value % 2 == 0]
print(myList) |
"""
File: largest_digit.py
Name:
----------------------------------
This file recursively prints the biggest digit in
5 different integers, 12345, 281, 6, -111, -9453
If your implementation is correct, you should see
5, 8, 6, 1, 9 on Console.
"""
def main():
print(find_largest_digit(12345)) # 5
print(find_largest_digit(281)) # 8
print(find_largest_digit(6)) # 6
print(find_largest_digit(-111)) # 1
print(find_largest_digit(-9453)) # 9
def find_largest_digit(n):
"""
:param n:
:return:
"""
time = 0
bs = 0
return helper(n, time, bs)
def helper(n, time, bs):
if 0 <= n <= 10:
return n
else:
if n < 10 ** (time+1):
if n < 0:
return helper(-n, time, bs)
else:
first = n // (10 ** time)
if first > bs:
return first
else:
return bs
else:
sq = n//(10 ** time) - (n//(10 ** (time + 1))) * 10
if sq > bs:
bs = sq
time += 1
return helper(n, time, bs)
if __name__ == '__main__':
main()
|
sample = ["abc", "xyz", "aba", "1221"]
def stringCounter(items):
amount = 0
for i in items:
if len(i) >= 2 and i[0] == i[-1]:
amount += 1
return amount
print("The amount of string that meet the criteria is:",stringCounter(sample)) |
# Uri Online Judge 1079
N = int(input())
for i in range(0,N):
Numbers = input()
num1 = float(Numbers.split()[0])
num2 = float(Numbers.split()[1])
num3 = float(Numbers.split()[2])
print(((2*num1+3*num2+5*num3)/10).__round__(1)) |
entity_id = data.get('entity_id')
command = data.get('command')
params = str(data.get('params'))
parsedParams = []
for z in params.replace(' ', '').replace('],[', '|').replace('[', '').replace(']', '').split('|'):
rect = []
for c in z.split(','):
rect.append(int(c))
parsedParams.append(rect)
if command in ["app_goto_target", "app_segment_clean"]:
parsedParams = parsedParams[0]
hass.services.call('vacuum', 'send_command',
{'entity_id': entity_id, 'command': command, 'params': parsedParams}, True)
|
def rank_filter(func):
def func_filter(local_rank=-1, *args, **kwargs):
if local_rank < 1:
return func(*args, **kwargs)
else:
pass
return func_filter
|
tot=coe=rat=sap=0
for i in range(int(input())):
n,s=input().split()
n=int(n)
tot+=n
if s=='C':coe+=n
elif s=='R':rat+=n
elif s=='S':sap+=n
print(f"Total: {tot} cobaias\nTotal de coelhos: {coe}\nTotal de ratos: {rat}\nTotal de sapos: {sap}")
p=(coe/tot)*100
print("Percentual de coelhos: %.2f"%p,end="")
print(" %")
p=(rat/tot)*100
print("Percentual de ratos: %.2f"%p,end="")
print(" %")
p=(sap/tot)*100
print("Percentual de sapos: %.2f"%p,end="")
print(" %")
|
[ ## this file was manually modified by jt
{
'functor' : {
'description' : [ "The function always returns a value of the same type than the entry.",
"Take care that for integers the value returned can differ by one unit",
"from \c ceil((a+b)/2.0) or \c floor((a+b)/2.0), but is always one of",
"the two"
],
'module' : 'boost',
'arity' : '2',
'call_types' : [],
'ret_arity' : '0',
'rturn' : {
'default' : 'T',
},
'simd_types' : ['real_'],
'type_defs' : [],
'types' : ['real_', 'signed_int_', 'unsigned_int_'],
},
'info' : 'manually modified',
'unit' : {
'global_header' : {
'first_stamp' : 'modified by jt the 28/11/2010',
'included' : [],
'notes' : ['for integer values average does not,coincide with (a0+a1)/2 by at most one unit.'],
'stamp' : 'modified by jt the 13/12/2010',
},
'ranges' : {
'real_' : [['T(-100)', 'T(100)'], ['T(-100)', 'T(100)']],
'signed_int_' : [['T(-100)', 'T(100)'], ['T(-100)', 'T(100)']],
'unsigned_int_' : [['T(0)', 'T(100)'], ['T(0)', 'T(100)']],
},
'specific_values' : {
'default' : {
},
'real_' : {
'boost::simd::Inf<T>()' : 'boost::simd::Inf<T>()',
'boost::simd::Minf<T>()' : 'boost::simd::Minf<T>()',
'boost::simd::Mone<T>()' : 'boost::simd::Mone<T>()',
'boost::simd::Nan<T>()' : 'boost::simd::Nan<T>()',
'boost::simd::One<T>()' : 'boost::simd::One<T>()',
'boost::simd::Zero<T>()' : 'boost::simd::Zero<T>()',
},
'signed_int_' : {
'boost::simd::Mone<T>()' : 'boost::simd::Mone<T>()',
'boost::simd::One<T>()' : 'boost::simd::One<T>()',
'boost::simd::Zero<T>()' : 'boost::simd::Zero<T>()',
},
'unsigned_int_' : {
'boost::simd::One<T>()' : 'boost::simd::One<T>()',
'boost::simd::Zero<T>()' : 'boost::simd::Zero<T>()',
},
},
'verif_test' : {
'property_call' : {
'default' : ['boost::simd::average(a0,a1)'],
},
'property_value' : {
'default' : ['(a0+a1)/2'],
},
'ulp_thresh' : {
'default' : ['1'],
'real_' : ['0'],
},
},
},
'version' : '0.1',
},
]
|
"""
Exercício Python 5:
Faça um programa que leia um número Inteiro e
mostre na tela o seu sucessor e seu antecessor.
"""
n = int(input('digite um numero inteiro '))
#ant = n-1
#post = n+1
#print('O antecessor de {} é {} e posterior é {}' .format(n, ant, post))
print('{} o antercessor é {} o sucessor é {}'.format(n, (n-1), (n+1)))
|
def extract_to_m2(filename, annot_triples):
"""
Extracts error detection annotations in m2 file format
Args:
filename: the output m2 file
annot_triples: the annotations of form (sentence, indexes, selections)
"""
with open(filename, 'w+') as m2_file:
for triple in annot_triples:
s_line = 'S ' + triple[0] + '\n'
m2_file.write(s_line)
for i in range(len(triple[1])):
if triple[2][i] == 1:
a_line = 'A '
if isinstance(triple[1][i], int):
a_line += str(triple[1][i]) + ' ' + str(triple[1][i] + 1)
else:
a_line += triple[1][i] + ' ' + triple[1][i]
a_line += '|||IG|||IG|||REQUIRED|||-NONE-|||1\n'
m2_file.write(a_line)
m2_file.write('\n') |
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
n = int(input())
start = list(map(int, input().strip().split()))
finish = list(map(int, input().strip().split()))
vertexes = [0] * n
for i, v in enumerate(start):
vertexes[v] = i
parents = [-1] * n
parent = vertexes[0]
for i in range(1, n):
cur = vertexes[i]
if finish[cur] - i > 1:
parents[cur] = parent
parent = cur
else:
parents[cur] = parent
while finish[cur] == finish[parents[cur]]:
cur = parents[cur]
parent = parents[cur]
if parent == vertexes[0]:
break
for i in range(n):
parents[i] += 1
print(*parents)
|
#!/usr/bin/env python3
"""
Source Code of Pdiskuploaderbot
"""
|
'''
author : bcgg
可惜时间爆了
其实写的很好
中间很多可以改进
'''
ans = 0
def merge(arr, l, m, r):
global ans
n1 = m - l + 1
n2 = r - m
L = [0] * (n1)
R = [0] * (n2)
for i in range(0, n1):
L[i] = arr[l + i]
for j in range(0, n2):
R[j] = arr[m + 1 + j]
i = 0
j = 0
k = l
while i < n1 and j < n2:
if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
ans += m - i + 1
k += 1
while i < n1:
arr[k] = L[i]
i += 1
k += 1
while j < n2:
arr[k] = R[j]
j += 1
k += 1
def mergeSort(arr, l, r):
if l < r:
m = int((l + (r - 1)) / 2)
mergeSort(arr, l, m)
mergeSort(arr, m + 1, r)
merge(arr, l, m, r)
if __name__ == '__main__':
arr = list(map(int, input().split(',')))
n = len(arr)
mergeSort(arr, 0, n - 1)
print(ans)
|
# Audit Event Outcomes
AUDIT_SUCCESS = "0"
AUDIT_MINOR_FAILURE = "4"
AUDIT_SERIOUS_FAILURE = "8"
AUDIT_MAJOR_FAILURE = "12"
|
"""All plugging called to check norm for a C file."""
__all__ = [
"columns",
"comma",
"function_line",
"indent",
"libc_func",
"nested_branches",
"number_function",
"parenthesis",
"preprocessor",
"snake_case",
"solo_space",
"statements",
"trailing_newline",
"two_space",
"operators",
"newline_at_end_of_file",
"subscriptor",
"header",
]
PREVIEW = [
"nb_params"
]
|
#771. Jewels and Stones
class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
# count = 0
# jewl = {}
# for i in jewels:
# if i not in jewl:
# jewl[i] = 0
# for j in stones:
# if j in jewl:
# count += 1
# return count
# return sum(s in jewels for s in stones)
count = 0
jewl = set(jewels)
for s in stones:
if s in jewl:
count += 1
return count |
class MaxPQ:
def __init__(self):
self.pq = []
def insert(self, v):
self.pq.append(v)
self.swim(len(self.pq) - 1)
def max(self):
return self.pq[0]
def del_max(self, ):
m = self.pq[0]
self.pq[0], self.pq[-1] = self.pq[-1], self.pq[0]
self.pq = self.pq[:-1]
self.sink(0)
return m
def is_empty(self, ):
return not self.pq
def size(self, ):
return len(self.pq)
def swim(self, k):
while k > 0 and self.pq[(k - 1) // 2] < self.pq[k]:
self.pq[k], self.pq[
(k - 1) // 2] = self.pq[(k - 1) // 2], self.pq[k]
k = k // 2
def sink(self, k):
N = len(self.pq)
while 2 * k + 1 <= N - 1:
j = 2 * k + 1
if j < N - 1 and self.pq[j] < self.pq[j + 1]:
j += 1
if self.pq[k] > self.pq[j]:
break
self.pq[k], self.pq[j] = self.pq[j], self.pq[k]
k = j
|
class Song:
"A class for representing a song"
def __init__(self, name, singer):
"""
Initialize a new song with it's name and singer
:param name: str
:param singer: str
"""
self.name = name
self.singer = singer
self.mood = self.mood()
def text(self):
"""
Returns a text of a song
:return: str
"""
pass
def mood(self):
"""
Returns a mood of a song
:return: str
"""
pass
def theme(self):
"""
Returns a theme of a song
:return: str
"""
pass
def key_words(self):
"""
Returns key words of a song
:return: list
"""
pass
class Singer:
"A class for representing a singer"
def __init__(self, name):
"""
Initialize a new singer with it's name
:param name: str
"""
self.name = name
class Discography:
"A class for representing a discography of a singer. Uses Singer() and Song() instances"
def __init__(self, singer):
"""
Initialize a new discography
:param singer: Singer() instance
"""
self.singer = singer
self.songs = []
def add_song(self, song):
"""
Adds a song to discography (self.songs)
:param song: Song() instance
:return: None
"""
pass
def number_of_songs(self):
"""
Returns a number of songs in this discography
:return: int
"""
pass
def mood(self):
"""
Returns a a dictionary, with moods as keys and number of songs as values
:return: dict
"""
pass
def themes(self):
"""
Returns most popular themes of songs in this discography
:return: list
"""
pass
|
BOT_TOKEN: str = "ODg4MzAyMzkwNTMxNDg1Njk2.YUQuEQ.UO4oyY9Zk4u1W5f-VpPLkkQ70TM"
SPOTIFY_ID: str = ""
SPOTIFY_SECRET: str = ""
BOT_PREFIX = "$"
EMBED_COLOR = 0x4dd4d0 #replace after'0x' with desired hex code ex. '#ff0188' >> '0xff0188'
SUPPORTED_EXTENSIONS = ('.webm', '.mp4', '.mp3', '.avi', '.wav', '.m4v', '.ogg', '.mov')
MAX_SONG_PRELOAD = 5 #maximum of 25
COOKIE_PATH = "/config/cookies/cookies.txt"
GLOBAL_DISABLE_AUTOJOIN_VC = False
VC_TIMEOUT = 600 #seconds
VC_TIMOUT_DEFAULT = True #default template setting for VC timeout true= yes, timeout false= no timeout
ALLOW_VC_TIMEOUT_EDIT = True #allow or disallow editing the vc_timeout guild setting
STARTUP_MESSAGE = "Starting Bot..."
STARTUP_COMPLETE_MESSAGE = "Startup Complete"
NO_GUILD_MESSAGE = 'Error: Please join a voice channel or enter the command in guild chat'
USER_NOT_IN_VC_MESSAGE = "Error: Please join the active voice channel to use commands"
WRONG_CHANNEL_MESSAGE = "Error: Please use configured command channel"
NOT_CONNECTED_MESSAGE = "Error: Bot not connected to any voice channel"
ALREADY_CONNECTED_MESSAGE = "Error: Already connected to a voice channel"
CHANNEL_NOT_FOUND_MESSAGE = "Error: Could not find channel"
DEFAULT_CHANNEL_JOIN_FAILED = "Error: Could not join the default voice channel"
INVALID_INVITE_MESSAGE = "Error: Invalid invitation link"
ADD_MESSAGE= "To add this bot to your own Server, click [here]" #brackets will be the link text
INFO_HISTORY_TITLE = "Songs Played:"
MAX_HISTORY_LENGTH = 10
MAX_TRACKNAME_HISTORY_LENGTH = 15
SONGINFO_UPLOADER = "Uploader: "
SONGINFO_DURATION = "Duration: "
SONGINFO_SECONDS = "s"
SONGINFO_LIKES = "Likes: "
SONGINFO_DISLIKES = "Dislikes: "
SONGINFO_NOW_PLAYING = "Now Playing"
SONGINFO_QUEUE_ADDED = "Added to queue"
SONGINFO_SONGINFO = "Song info"
SONGINFO_UNKNOWN_SITE = "Unknown site :question:"
SONGINFO_PLAYLIST_QUEUED = "Queued playlist :page_with_curl:"
SONGINFO_UNKNOWN_DURATION = "Unknown"
HELP_ADDBOT_SHORT = "Add Bot to another server"
HELP_ADDBOT_LONG = "Gives you the link for adding this bot to another server of yours."
HELP_CONNECT_SHORT = "Connect bot to voicechannel"
HELP_CONNECT_LONG = "Connects the bot to the voice channel you are currently in"
HELP_DISCONNECT_SHORT = "Disonnect bot from voicechannel"
HELP_DISCONNECT_LONG = "Disconnect the bot from the voice channel and stop audio."
HELP_SETTINGS_SHORT = "View and set bot settings"
HELP_SETTINGS_LONG = "View and set bot settings in the server. Usage: {}settings setting_name value".format(BOT_PREFIX)
HELP_HISTORY_SHORT = "Show history of songs"
HELP_HISTORY_LONG = "Shows the " + str(MAX_TRACKNAME_HISTORY_LENGTH) + " last played songs."
HELP_PAUSE_SHORT = "Pause Music"
HELP_PAUSE_LONG = "Pauses the AudioPlayer. Playback can be continued with the resume command."
HELP_VOL_SHORT = "Change volume %"
HELP_VOL_LONG = "Changes the volume of the AudioPlayer. Argument specifies the % to which the volume should be set."
HELP_PREV_SHORT = "Go back one Song"
HELP_PREV_LONG = "Plays the previous song again."
HELP_RESUME_SHORT = "Resume Music"
HELP_RESUME_LONG = "Resumes the AudioPlayer."
HELP_SKIP_SHORT = "Skip a song"
HELP_SKIP_LONG = "Skips the currently playing song and goes to the next item in the queue."
HELP_SONGINFO_SHORT = "Info about current Song"
HELP_SONGINFO_LONG = "Shows details about the song currently being played and posts a link to the song."
HELP_STOP_SHORT = "Stop Music"
HELP_STOP_LONG = "Stops the AudioPlayer and clears the songqueue"
HELP_YT_SHORT = "Play a supported link or search on youtube"
HELP_YT_LONG = ("$p [link/video title/key words/playlist-link/soundcloud link/spotify link/bandcamp link/twitter link]")
HELP_PING_SHORT = "Pong"
HELP_PING_LONG = "Test bot response status"
HELP_CLEAR_SHORT = "Clear the queue."
HELP_CLEAR_LONG = "Clears the queue and skips the current song."
HELP_LOOP_SHORT = "Loops the currently playing song, toggle on/off."
HELP_LOOP_LONG = "Loops the currently playing song and locks the queue. Use the command again to disable loop."
HELP_QUEUE_SHORT = "Shows the songs in queue."
HELP_QUEUE_LONG = "Shows the number of songs in queue, up to 10."
HELP_SHUFFLE_SHORT = "Shuffle the queue"
HELP_SHUFFLE_LONG = "Randomly sort the songs in the current queue"
HELP_CHANGECHANNEL_SHORT = "Change the bot channel"
HELP_CHANGECHANNEL_LONG = "Change the bot channel to the VC you are in"
ABSOLUTE_PATH = '' #do not modify |
"""
An edge is a bridge if, after removing it count of connected components in graph will
be increased by one. Bridges represent vulnerabilities in a connected network and are
useful for designing reliable networks. For example, in a wired computer network, an
articulation point indicates the critical computers and a bridge indicates the critical
wires or connections.
For more details, refer this article:
https://www.geeksforgeeks.org/bridge-in-a-graph/
"""
def __get_demo_graph(index):
return [
{
0: [1, 2],
1: [0, 2],
2: [0, 1, 3, 5],
3: [2, 4],
4: [3],
5: [2, 6, 8],
6: [5, 7],
7: [6, 8],
8: [5, 7],
},
{
0: [6],
1: [9],
2: [4, 5],
3: [4],
4: [2, 3],
5: [2],
6: [0, 7],
7: [6],
8: [],
9: [1],
},
{
0: [4],
1: [6],
2: [],
3: [5, 6, 7],
4: [0, 6],
5: [3, 8, 9],
6: [1, 3, 4, 7],
7: [3, 6, 8, 9],
8: [5, 7],
9: [5, 7],
},
{
0: [1, 3],
1: [0, 2, 4],
2: [1, 3, 4],
3: [0, 2, 4],
4: [1, 2, 3],
},
][index]
def compute_bridges(graph: dict[int, list[int]]) -> list[tuple[int, int]]:
"""
Return the list of undirected graph bridges [(a1, b1), ..., (ak, bk)]; ai <= bi
>>> compute_bridges(__get_demo_graph(0))
[(3, 4), (2, 3), (2, 5)]
>>> compute_bridges(__get_demo_graph(1))
[(6, 7), (0, 6), (1, 9), (3, 4), (2, 4), (2, 5)]
>>> compute_bridges(__get_demo_graph(2))
[(1, 6), (4, 6), (0, 4)]
>>> compute_bridges(__get_demo_graph(3))
[]
>>> compute_bridges({})
[]
"""
id = 0
n = len(graph) # No of vertices in graph
low = [0] * n
visited = [False] * n
def dfs(at, parent, bridges, id):
visited[at] = True
low[at] = id
id += 1
for to in graph[at]:
if to == parent:
pass
elif not visited[to]:
dfs(to, at, bridges, id)
low[at] = min(low[at], low[to])
if id <= low[to]:
bridges.append((at, to) if at < to else (to, at))
else:
# This edge is a back edge and cannot be a bridge
low[at] = min(low[at], low[to])
bridges = []
for i in range(n):
if not visited[i]:
dfs(i, -1, bridges, id)
return bridges
|
class BRepBuilderGeometryId(object,IDisposable):
"""
This class is used by the BRepBuilder class to identify objects it creates (faces,edges,etc.).
BRepBuilderGeometryId(other: BRepBuilderGeometryId)
"""
def Dispose(self):
""" Dispose(self: BRepBuilderGeometryId) """
pass
@staticmethod
def InvalidGeometryId():
"""
InvalidGeometryId() -> BRepBuilderGeometryId
Returns an invalid BRepBuilderGeometryId,used as a return value to indicate an
error.
"""
pass
def ReleaseUnmanagedResources(self,*args):
""" ReleaseUnmanagedResources(self: BRepBuilderGeometryId,disposing: bool) """
pass
def __enter__(self,*args):
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self,*args):
""" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,other):
""" __new__(cls: type,other: BRepBuilderGeometryId) """
pass
def __repr__(self,*args):
""" __repr__(self: object) -> str """
pass
IsValidObject=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Specifies whether the .NET object represents a valid Revit entity.
Get: IsValidObject(self: BRepBuilderGeometryId) -> bool
"""
|
class IncompatibleAttribute(Exception):
pass
class IncompatibleDataException(Exception):
pass
class UndefinedROI(Exception):
pass
class InvalidSubscriber(Exception):
pass
class InvalidMessage(Exception):
pass
|
def create_bag_of_centroids(wordlist, word_centroid_map):
"""
a function to create bags of centroids
"""
# The number of clusters is equal to the highest cluster index in the word / centroid map
num_centroids = max( word_centroid_map.values() ) + 1
# Pre-allocate the bag of centroids vector (for speed)
bag_of_centroids = np.zeros(num_centroids, dtype="float32")
# Loop over the words in the tweet. If the word is in the vocabulary,
# find which cluster it belongs to, and increment that cluster count by one
for word in wordlist:
if word in word_centroid_map:
index = word_centroid_map[word]
bag_of_centroids[index] += 1
# Return numpy array
return bag_of_centroids
|
# Enter script code
message = "kubectl exec -it <cursor> -- bash"
keyboard.send_keys("kubectl exec -it ")
keyboard.send_keys("<shift>+<ctrl>+v")
time.sleep(0.1)
keyboard.send_keys(" -- bash")
|
'''
Topic : Algorithms
Subtopic : Diagonal Difference
Language : Python
Problem Statement : Given a square matrix, calculate the absolute difference between the sums of its diagonals.
Url : https://www.hackerrank.com/challenges/diagonal-difference/problem
'''
#!/bin/python3
# Complete the 'diagonalDifference' function below.
#
# The function is expected to return an INTEGER.
# The function accepts 2D_INTEGER_ARRAY arr as parameter.
#
def diagonalDifference(arr):
# Write your code here
n = len(arr)
d1 = sum(arr[i][i] for i in range(n))
d2 = sum(arr[i][n-i-1] for i in range(n))
return abs(d1 - d2)
assert diagonalDifference([[11,2,4], [4,5,6], [10,8,-12]]) == 15
assert diagonalDifference([[1,2,3], [4,5,6], [9,8,9]]) == 2
assert diagonalDifference([[1,1,1,1], [1,1,1,1], [1,1,1,1], [1,1,1,1]]) == 0
|
#!/usr/bin/env python3
# https://codeforces.com/problemset/problem/702/A
#严格来说不能算DP?
_ = input()
l = list(map(int,input().split())) #https://codeforces.com/blog/entry/71884
maxL = 1
curL = 1
for i in range(1,len(l)):
if l[i]<=l[i-1]:
curL = 1
continue
curL += 1
if curL > maxL: maxL = curL
print(maxL)
|
'''
Quiz 1:
Hacer un programa que lea una temperatura en farenheit y la convierta en celsius y si es mayor
a 100°C imprima "caliente". Si es menor a 0°C imprima "frio"
'''
tempF = int(input("TempF: "))
#(tempF - 32/(5/9))
tempC = (((tempF - 32)*5)/9)
print("\nLa temperatura en Celsius es " + str(tempC))
if tempC >= 100:
print("caliente")
elif tempC < 0:
print("frio") |
class ParsnipException(Exception):
def __init__(self, msg, webtexter=None):
self.args = (msg, webtexter)
self.msg = msg
self.webtexter = webtexter
def __str__(self):
return repr("[%s] %s - %s" % (self.webtexter.NETWORK_NAME, self.webtexter.phone_number, self.msg))
class LoginError(ParsnipException):pass
class MessageSendingError(ParsnipException):pass
class ConnectionError(ParsnipException):pass
class ResourceError(ParsnipException):pass
|
def soma(x,y):
return print(x + y)
def sub(x,y):
return print(x - y)
def mult(x,y):
return print(x * y)
def div(x,y):
return print(x / y)
soma(3,8)
sub(10,5)
mult(3,9)
div(15,7) |
class DeviceLog:
def __init__(self, deviceId, deviceName, temperature, location, recordDate):
self.deviceId = deviceId
self.deviceName = deviceName
self.temperature = temperature
self.location = location
self.recordDate = recordDate
def getStatus(self):
if self.temperature is None:
raise Exception('Invalid Temperature Value Specified!')
if self.temperature < 18:
status = 'COLD'
elif self.temperature >= 18 and self.temperature < 25:
status = 'WARM'
else:
status = 'HOT'
return status
def __str__(self):
return '%s, %s, %s, %s, %s' % (self.deviceId, self.deviceName,
self.temperature, self.location, self.recordDate)
try:
device_log_object = DeviceLog(
'D1001', 'Device-X93984', 24, 'Bangalore', '2022-01-01')
print(device_log_object)
print('Status : %s' % device_log_object.getStatus())
except Exception as error:
print('Error Occurred, Details : %s ' % str(error))
|
class NeighborResult:
def __init__(self):
self.solutions = []
self.choose_path = []
self.current_num = 0
self.curr_solved_gates = []
|
'''
@brief this class reflect action decision regarding condition
'''
class EventAction():
'''
@brief build event action
@param cond the conditions to perform the action
@param to the target state if any
@param job the job to do if any
'''
def __init__(self, cond="", to="", job=""):
self.__to = to
self.__job = job
self.__cond = cond
'''
@brief get action state target
@return state name
'''
def getState(self) :
return self.__to
'''
@brief has transition condition
@return true if not empty
'''
def hasCond(self) :
return ( self.__cond != "" )
'''
@brief get action conditions
@return condition
'''
def getCond(self) :
return self.__cond
'''
@brief get action job
@return job
'''
def getJob(self) :
return self.__job
'''
@brief string represtation for state action
@return the string
'''
def __str__(self):
return "Act( %s, %s, %s )"%(self.__to, self.__job, self.__cond)
'''
@brief this class reflect the output switch on event received regarding condition and action to perform
'''
class EventCase():
'''
@brief build event case
@param event the event title
'''
def __init__(self, event):
self.__event = event
self.__acts = []
'''
@brief get iterator
'''
def __iter__(self):
return iter(self.__acts)
'''
@brief equality implementation
@param other the other element to compare with
'''
def __eq__(self, other):
if isinstance(other, str):
return self.__event == other
if not isinstance(other, EventCase):
return False
if self.__event != other.getEvent():
return False
return True
'''
@brief get action event
@return event
'''
def getEvent(self) :
return self.__event
'''
@brief add action
@param act the new action
'''
def addAct(self, act) :
if act not in self.__acts:
self.__acts.append(act)
'''
@brief string represtation for state action
@return the string
'''
def __str__(self):
output = "Event( %s ) { "%self.__event
if len(self.__acts):
output += "\n"
for act in self.__acts:
output += "%s\n"%str(act)
return output + "}"
'''
@brief this class store all event case for a state
'''
class EventCaseList():
'''
@brief build event case list
'''
def __init__(self):
self.__events = []
'''
@brief get iterator
'''
def __iter__(self):
return iter(self.__events)
'''
@brief append from StateAction
@param act the state action
'''
def append(self, act):
for cond in act.getConds():
evt = None
a = EventAction(cond=cond.getCond(),\
to=act.getState(),\
job=act.getJob())
for e in self.__events:
if e == cond.getEvent():
evt = e
break
if not evt:
evt = EventCase(cond.getEvent())
self.__events.append(evt)
evt.addAct(a)
'''
@brief append from State
@param state the state
'''
def appendState(self, state):
for act in state.getActions():
self.append(act)
'''
@brief string represtation for state action
@return the string
'''
def __str__(self):
output = "{ "
if len(self.__events):
output += "\n"
for e in self.__events:
output += "%s\n"%str(e)
return output + "}" |
quedex_public_key = """-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1
mQENBFlPvjsBCACr/UfHzXAezskLqcq9NiiaNFDDT5A+biC8VrOglB0ZSQOYRira
NgQ2Cp8Jd+XU77F+J1012BjB5y87Z+hdnwBDsqF7CjkjeQzsE3PSvm9I+E3cneqx
UcinRaUD1wfwVytbg9Q9rpqQ7CTjVWY1UPYjs6dAo1WAp/ux/VTeOFbpO0R3D7if
ZGY1QeISRpLWiMpcG2YCOALnuazABVCNXLhVqa8Y7tt2I+cI0uE9tBf41gjGPPtd
KdASPVz1plpOEl2dOpmy8jICqcSzUsT4Sy8vAqW3U1HF+TA2QGRcrrUItL4GjxNL
lcL8wh7mclsjRe5Q5dYnrACC9NWS6vSp/eAPABEBAAG0G1F1ZWRleCA8Y29udGFj
dEBxdWVkZXgubmV0PokBOAQTAQIAIgUCWU++OwIbAwYLCQgHAwIGFQgCCQoLBBYC
AwECHgECF4AACgkQzsLQUmv6vk9Rlwf+LiJA37dhDdGFU/fexNRHZWTUh2TdqBsv
MiNtarf+HlZIioWMCzlHmb3bolVrfFUNUh/GGlPENtlaSmFGuPhMlFcNDGYM+I7k
ufhM95jxmtzy97NYMeMx4xjnaBAu8kFsvi80BR/05ZhCHqyI3K9NpYoXBfsyzss+
j/jX1NHayzMmXNdqQ5JjzuICZj0EY9ryLP/jPAZ6DS9LVwi9Vr2JzZheCx5Q77Ud
HuGTOBu3Azor2f4n4ccELs7lgU7uGrt1cK/oiML9UDmqjelunzTFU/5Q0tp7C3Qm
1wymd+PYTvvX/5htnLar1nIuYmmvtCZb1zyuzPzJWWtCcFFsiV9kerkBDQRZT747
AQgAn/9rwQn4yM7pVYO9rTxNveI60lgp4RLKi1WYpAy6gxwUp3zLE/h59rykb7qM
9QArABsMEGGKt9urq7hjsKu8bM+hVTcAuoDre5qNFEfhZuPBS9LF7wQWDikORZxR
Mk5WIiCt3U2soQ4Lismw1bLDX8uqkv3GFtR+IaKzuwYBEVPwuZ15EOt9G83JR3uV
MKqeUtFW9+z5WEAh2JLU6C357sftJIJeWDEgF2TPtQOzc8isI8rpIFNyl6x1Aiy6
LaSWmOI3d9EQ8SH4LxCXtAgWvnIoPL0JsP5/FWzt6qJR4teu+A2xwG7001va+DUc
34AbSV9Ogqa519OfbKK6HDyFIQARAQABiQEfBBgBAgAJBQJZT747AhsMAAoJEM7C
0FJr+r5PtEUH/0KmXQWbm4qXxOnaXrk+CKLDBxtfY6BaoJ6ekdGfqVMd8YM+UGnL
6d49vex4O80uIhIDSex446gKVlhdwOjIlUFmTCtMgGOa06G2T4sx8a9y2UYK45hN
rj9aVfhJ8nn9yuPj7cBNtLEYJ4VkRKxJO9XX8cfhUsomhB3DQDbOLfikYqfmupm6
mYX84CO/DD8JAXx4qt9Rg+5AUQegq26iZ/og1ZjYZ/tvBjrc45u23XCWvgVHbGhb
wWCNjZijaY1VnTwTe6uZv1AqovZpprqZKWImN5myaJI3AJU2W2FCbI0ezfoVEVO4
zMipOYZzRziJeCz1gX9geNseLvfJ8EtZRKU=
=e4C9
-----END PGP PUBLIC KEY BLOCK-----"""
|
age = int(input("How old are you ?"))
#if age >= 16 and age <= 65:
#if 16 <= age <= 65:
if age in range(16,66):
print ("Have a good day at work.")
elif age > 100 or age <= 0:
print ("Nice Try. This program is not dumb.")
endkey = input ("Press enter to exit")
else:
print (f"Enjoy your free time, you need to work for us after {65 - age} years.")
print ("-"*80)
|
"""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")
|
"""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
|
# OpenWeatherMap API Key
weather_api_key = "f4695ec49ac558195fc591f0d450c34c"
# Google API Key
g_key = "AIzaSyAyIq5hhFN-Y0M16Ltie3YuwpDiKWx8tCk"
|
'''
Faça um programa que leia o nome completo de uma pessoa,
mostrando em seguida o primeiro e o último nome separadamente.
'''
entrada = str(input('Digite um nome completo: ')).strip()
print('Olá {}'.format(entrada))
nome = entrada.split()
print('Seu primeiro nome é: {}'.format(nome[0]))
print('Seu último nome é: {}'.format(nome[len(nome) - 1]))
|
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)"
|
def star_pattern(n):
for i in range(n):
for j in range(i+1):
print("*",end=" ")
print()
star_pattern(5)
'''
star_pattern(5)
*
* *
* * *
* * * *
* * * * *
'''
|
listaNum = list()
contadorde5 = 0
while True:
num = int(input('Digite um número: '))
if num == 5:
contadorde5 += 1
listaNum.append(num)
continuar = str(input('Quer continuar? [ S / N ] ')).strip().upper()
print()
if continuar[0] == 'N':
break
while continuar[0] != 'S' and continuar[0] != 'N':
continuar = str(input('Quer continuar? [ S / N ] ')).strip().upper()
print()
print('=-' * 35)
print(f'Sua lista ficou assim: {listaNum}')
print('=-' * 35)
if len(listaNum) == 1:
print('Você digitou apenas 1 número...')
else:
print(f'Foram digitados {len(listaNum)} números!')
print(f'A lista de forma descrescente se torna {sorted(listaNum, reverse=True)}')
print('=-' * 35)
if 5 in listaNum:
print(f'O valor 5 está sim na lista!\nEncontrei {contadorde5} deles!')
else:
print('Não encontrei nenhum número 5 na lista...')
|
# 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) |
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
|
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")
|
# 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.
|
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
|
"""
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
}
|
"""
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
|
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 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()
|
# 公众号:MarkerJava
# 开发时间:2020/10/5 17:25
scores = {'kobe': 100, 'lebron': 99, 'AD': 88}
# 获取所有key
keys = scores.keys()
print(keys)
print(type(keys))
print(list(keys)) # 将所有key组成的视图转换层列表
# 获取所有的值
value = scores.values()
print(value)
print(type(value)) # 将所有value组成的视图转换层列表
# 获取所有键值对
items = scores.items()
print(items)
print(type(items))
|
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()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2022/2/2 10:08 上午
# @Author : xinming
# @File : ListNode.py
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class MyLinkedList:
def __init__(self):
self.size = 0
self.dummy_head = ListNode(0)
def get(self, index: int) -> int:
"""
Get the value of the i-th node in the linked list.
:param index:
:return:
"""
if index < 0 or index >= self.size:
return -1
curr = self.dummy_head
for i in range(index+1):
curr = curr.next
return curr.val
def print_all(self):
curr = self.dummy_head
while curr:
print(curr.val)
curr=curr.next
def addAtHead(self, val: int) -> None:
self.addAtIndex(0, val)
def addAtTail(self, val: int) -> None:
self.addAtIndex(self.size, val)
def addAtIndex(self, index: int, val: int) -> None:
if index > self.size:
return None
# Make it meaningful
if index < 0:
index= 0
self.size+=1 # update the size.
predecessor = self.dummy_head
for _ in range(index):
predecessor = predecessor.next
to_add = ListNode(val)
to_add.next = predecessor.next
predecessor.next = to_add
def deleteAtIndex(self, index: int) -> None:
# meaningless if index<0 or larger than the size.
if index < 0 or index >= self.size:
return None
# update the size of linked list.
self.size -= 1
predecessor = self.dummy_head
for _ in range(index):
predecessor = predecessor.next
predecessor.next = predecessor.next.next |
#!/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()
|
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 |
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)
|
class FolhaDePagamento:
@staticmethod
def log():
return f'Isso é um log qualquer.'
#folha = FolhaDePagamento()
#print(folha.log())
print(FolhaDePagamento.log()) |
# 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)
|
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()
|
# 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 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]])))
|
#!/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) |
#MaBe
matriz = [[0, 0, 0], [0, 0, 0,], [0, 0, 0]]
for l in range(0, 3):
for c in range(0,3):
matriz[l][c] = int(input(f'Digite o valor da posição {(c, l)}: '))
for obj in range(0, 3):
for i in range(0, 3):
print(f'[{matriz[obj][i]}]', end=' ')
print()
|
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
|
#079_Valores_unicos_em_uma_lista.py
lista = []
print("")
while True:
n = int(input("Adicione valor: "))
if n not in lista:
lista.append(n)
print(f"Valor {n} adicionado com sucesso")
else:
print(f"Valor {n} duplicado NÃO adicionado")
esc = " "
while esc not in "SN":
esc = str(input("Deseja continuar [S/N]? ")).strip().upper()[0]
if esc == "N":
break
if esc == "N":
break
print("")
print(lista)
lista.sort()
print(lista)
print("")
|
#
# @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 TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回二维列表[[1,2],[4,5]]
def Print(self, pRoot):
if pRoot == None:
return []
queue1 = [pRoot]
queue2 = []
ret = []
while queue1 or queue2:
if queue1:
tmpRet = []
while queue1:
tmpNode = queue1.pop(0)
tmpRet.append(tmpNode.val)
if tmpNode.left:
queue2.append(tmpNode.left)
if tmpNode.right:
queue2.append(tmpNode.right)
ret.append(tmpRet)
if queue2:
tmpRet = []
while queue2:
tmpNode = queue2.pop(0)
tmpRet.append(tmpNode.val)
if tmpNode.left:
queue1.append(tmpNode.left)
if tmpNode.right:
queue1.append(tmpNode.right)
ret.append(tmpRet)
return ret
|
# 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/")
|
# (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
|
"""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() |
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)
|
# 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("**********************************************************")
|
# 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 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 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])
|
# 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
----------------------------------------------------
'''
|
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
'''
|
#!/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 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
|
# 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',
],
},
],
}],
],
}
|
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)
|
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))
|
# -*- coding: utf-8 -*-
def main():
n, k = map(int, input().split())
a = list(map(int, input().split()))
mod = 10 ** 9 + 7
ans = 0
# See:
# https://www.youtube.com/watch?v=JTH27weC38k
# https://atcoder.jp/contests/jsc2019-qual/submissions/7107452
# Key Insight
# 2つの整数の順序対(i, j)の選び方
# 同じブロックにある/異なるブロックにある で場合分け
# 同じブロックにある
# Bi > Bjとなる組み合わせを全探索
for i in range(n - 1):
count = 0
for j in range(i + 1, n):
if a[i] > a[j]:
count += 1
# 一つのブロックにある組み合わせのk倍
ans += count * k
ans %= mod
# 別のブロックにある
for i in range(n):
count = 0
for j in range(n):
if a[i] > a[j]:
count += 1
# k個のブロックから2個選ぶ(kC2)
ans += count * (k * (k - 1) // 2)
ans %= mod
print(ans)
if __name__ == '__main__':
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.