content
stringlengths 7
1.05M
|
---|
"""
zip
"""
list_name = ["郭世鑫", "万忠刚", "赵文杰"]
list_age = [22, 26]
# for 变量 in zip(可迭代对象1,可迭代对象2)
for item in zip(list_name, list_age):
print(item)
# 应用:矩阵转置
map = [
[2, 0, 0, 2],
[4, 2, 0, 2],
[2, 4, 2, 4],
[0, 4, 0, 4]
]
# new_map = []
# for item in zip(map[0],map[1],map[2],map[3]):
# new_map.append(list(item))
# print(new_map)
# new_map = []
# for item in zip(*map):
# new_map.append(list(item))
new_map = [list(item) for item in zip(*map)]
print(new_map)
|
"""Given an array length 1 or more of ints, return the difference between the
largest and smallest values in the array. Note: the built-in min(v1, v2) and max(v1, v2)
functions return the smaller or larger of two values.
big_diff([10, 3, 5, 6]) → 7
big_diff([7, 2, 10, 9]) → 8
big_diff([2, 10, 7, 2]) → 8
"""
def big_diff(arr):
small = min(arr)
big = max(arr)
total = big - small
return total
print(big_diff([1,2,3,4])) |
class ObjectContext:
def __init__(self) -> None:
self.definedTypes = {}
self.definedSymbols = {}
def get_type(self, typeName: str):
return self.definedTypes[typeName]
def type_of(self, symbol: str):
if self.definedSymbols.__contains__(symbol):
return self.definedSymbols[symbol]
def define_symbol(self, symbol: str, sym_type) -> bool:
if not self.definedSymbols.__contains__(symbol):
self.definedSymbols[symbol] = sym_type
return True
return False |
class Scenario:
_requests = None
def __init__(self, requests):
self._requests = requests
def get_requests(self):
return self._requests
|
#Calcular y mostrar la nota final para cada materia, y el promedio general de las tres materias
def calc_matematicas(examen, tarea1, tarea2, tarea3):
valor_examen = examen * 0.9
total_tareas = tarea1 + tarea2 + tarea3
promedio_tareas = total_tareas / 3
valor_tareas = promedio_tareas * 0.1
final_matematicas = round(valor_examen + valor_tareas, 2)
return final_matematicas
def calc_fisica(examen, tarea1, tarea2):
valor_examen = examen * 0.8
total_tareas = tarea1 + tarea2
promedio_tareas = total_tareas / 2
valor_tareas = promedio_tareas * 0.20
final_fisica = round(valor_examen + valor_tareas, 2)
return final_fisica
def calc_quimica(examen, tarea1, tarea2, tarea3):
valor_examen = examen * 0.85
total_tareas = tarea1 + tarea2 + tarea3
promedio_tareas = total_tareas / 3
valor_tareas = promedio_tareas * 0.15
final_quimica = round(valor_examen + valor_tareas, 2)
return final_quimica
examen_matematicas = float(input("Ingrese el resultado del examen de Matematicas: "))
tarea1_matematicas = float(input("Ingrese el valor de la tarea #1 de Matematicas: "))
tarea2_matematicas = float(input("Ingrese el valor de la tarea #2 de Matematicas: "))
tarea3_matematicas = float(input("Ingrese el valor de la tarea #3 de Matematicas: "))
examen_fisica = float(input("Ingrese el resultado del examen de Fisica: "))
tarea1_fisica = float(input("Ingrese el valor de la tarea #1 de Fisica: "))
tarea2_fisica = float(input("Ingrese el valor de la tarea #2 de Fisica: "))
examen_quimica = float(input("Ingrese el resultado del examen de Quimica: "))
tarea1_quimica = float(input("Ingrese el valor de la tarea #1 de Quimica: "))
tarea2_quimica = float(input("Ingrese el valor de la tarea #2 de Quimica: "))
tarea3_quimica = float(input("Ingrese el valor de la tarea #3 de Quimica: "))
promedio_total = round(((calc_matematicas(examen_matematicas, tarea1_matematicas, tarea2_matematicas, tarea3_matematicas) + calc_fisica(examen_fisica, tarea1_fisica, tarea2_fisica) + calc_quimica(examen_quimica, tarea1_quimica, tarea2_quimica, tarea3_quimica)) / 3), 2)
print(f"Si la nota de Matematicas es {calc_matematicas(examen_matematicas, tarea1_matematicas, tarea2_matematicas, tarea3_matematicas)}, la de Fisica es {calc_fisica(examen_fisica, tarea1_fisica, tarea2_fisica)}, y la de Quimica es {calc_quimica(examen_quimica, tarea1_quimica, tarea2_quimica, tarea3_quimica)}. Entonces el promedio de las materias es {promedio_total}")
|
'''
2 - Atribuição aumentada (ex.: x += 5):
x = 10
x = x + 10 # x=20
x += 10 # x=30
x *= 2 # x=60
x = 2
x **= 10 # x=1024
''' |
my_list = [20, 39, 34, 20, 24, 20, 10, 11]
my_set = sorted(set(my_list))
print(my_set)
|
settings = {
'token': 'DISCORD_BOT_TOKEN',
'id': BOT_ID,
'prefix': 'PREFIX',
'embedcolor': EMBED_COLOR_(0x123456),
'author-id': YOUR_ID,
'vk-api-token': 'VK_API_TOKEN',
'bot_avatar_url': 'BOT_AVATAR_URL',
'youtube_apikey': 'YOUTUBE_DATA_API_KEY',
'weather_token': 'OPENWEATHERMAP_TOKEN',
} |
''' ***
*
*** '''
n = int(input())
while n:
n=n-1
num = int(input())
if num<38 or (num%5)<3:
print(num)
else:
print(num+(5-(num%5)))
|
class GlocalMerchantRequest:
def __init__(self, xgl_token_external, payload):
self.xgl_token_external = xgl_token_external
self.payload = payload
def get_payload(self):
return self.payload
def get_xgl_token_external(self):
return self.xgl_token_external
def set_xgl_token_external(self, xgl_token_external):
self.xgl_token_external = xgl_token_external
def set_payload(self, payload):
self.payload = payload
|
DEFAULT_SPECIAL_TOKEN_BOXES = {
"[UNK]": [0, 0, 0, 0],
"[PAD]": [0, 0, 0, 0],
"[CLS]": [0, 0, 0, 0],
"[MASK]": [0, 0, 0, 0],
"[SEP]": [1000, 1000, 1000, 1000],
}
MAX_LINE_PER_PAGE = 200
MAX_TOKENS_PER_LINE = 25
MAX_BLOCK_PER_PAGE = 40
MAX_TOKENS_PER_BLOCK = 100
MAX_2D_POSITION_EMBEDDINGS = 1024 |
# Copyright 2004-2008 Roman Yakovenko.
# Distributed under the Boost Software License, Version 1.0. (See
# accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
"""
This file contains indexing suite v2 code
"""
file_name = "indexing_suite/python_iterator.hpp"
code = """// -*- mode:c++ -*-
//
// Header file python_iterator.hpp
//
// Handy Python iterable iterators
//
// Copyright (c) 2003 Raoul M. Gough
//
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy
// at http://www.boost.org/LICENSE_1_0.txt)
//
// History
// =======
// 2003/ 9/10 rmg File creation
// 2008/12/08 Roman Change indexing suite layout
//
// $Id: python_iterator.hpp,v 1.1.2.5 2003/11/24 16:35:09 raoulgough Exp $
//
// 2008 November 27 Roman Yakovenko
// implementation of the member functions was moved from cpp to header.
// this was done to simplify "installation" procedure.
#ifndef BOOST_PYTHON_INDEXING_PYTHON_ITERATOR_HPP
#define BOOST_PYTHON_INDEXING_PYTHON_ITERATOR_HPP
#include <boost/python/object.hpp>
#include <boost/python/handle.hpp>
namespace boost { namespace python { namespace indexing {
struct /*BOOST_PYTHON_DECL*/ python_iterator
{
python_iterator (boost::python::object obj)
: m_iter_obj (handle<> (PyObject_GetIter (obj.ptr()))),
m_next_method (m_iter_obj.attr ("__next__")),
m_current()
{
}
// Sets a python type exception and calls throw_error_already_set if
// the passed object is not iterable via PyObject_GetIter
bool next ()
{
bool result = true; // Assume success
try
{
m_current = m_next_method ();
}
catch (boost::python::error_already_set const &)
{
if (PyErr_ExceptionMatches (PyExc_StopIteration))
{
// Eat this exception
PyErr_Clear ();
m_current = boost::python::object (); // No current object
result = false; // Report failure via return value only
}
else
{
// Pass it up the line
throw;
}
}
return result;
}
// Get the next item from the iterator, returning true for success
boost::python::object current() const
{ return m_current; }
// Callable only after a successful next()
private:
::boost::python::object m_iter_obj;
::boost::python::object m_next_method;
::boost::python::object m_current;
};
} } }
#endif // BOOST_PYTHON_INDEXING_PYTHON_ITERATOR_HPP
"""
|
#!/usr/bin/env python3
numbers = [42, 9001]
letters = "ace"
try:
print(numbers + letters)
except TypeError as err:
print(err) # can only concatenate list (not "str") to list
words = ["ace", "in", "hole"]
print(numbers + words) # [42, 9001, 'ace', 'in', 'hole']
|
once = 0
res = (0,0)
def calc():
global once, res
if once > 0: return
with open("../stream/input15.txt", "r") as file:
data = [int(y) for y in [x.strip() for x in file.read().splitlines()][0].split(',')]
occurences = {data[i-1]:[i] for i in range(1, len(data)+1)}
current = data[-1]
for i in range(len(data)+1,30000001):
if len(occurences[current]) == 1:
current = 0
if len(occurences[0]) == 2:
occurences[0].remove(occurences[0][0])
occurences[0].append(i)
else:
new = occurences[current][1] - occurences[current][0]
if new in occurences:
if len(occurences[new]) == 2:
occurences[new].remove(occurences[new][0])
occurences[new].append(i)
else:
occurences[new] = [i]
current = new
if i == 2020:
res1 = current
res = (res1,current)
return
def p1():
global once, res
calc()
once = 1
return str(res[0])
def p2():
global once, res
calc()
once = 1
return str(res[1])
if __name__ == '__main__':
print('part 1: ',p1())
print('part 2: ',p2())
exit() |
"""
Implement regular expression matching with support for '.' and '*'.
The matching should cover the entire input string (not partial).
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aa", "a*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
"""
class Solution:
def isMatch(self, text, pattern):
"""
:type text: str
:type pattern: str
:rtype: bool
"""
# SOLUTION 1: RECURSION
# Runtime: Time limit exceeded after running 44/445 test cases
if not pattern:
return not text # If both are empty it's considered a match.
first_match = bool(text) and pattern[0] in {text[0], '.'} # text is not empty and the first char matches
if len(pattern) >= 2 and pattern[1] == '*': # The Kleene star is dealt with separately
return (
(self.isMatch(text, pattern[2:]) # This usually runs until both text and pattern[2:] are empty. This line represents the case when there are 0 occurences of the character with the *.
or first_match and self.isMatch(text[1:], pattern)) # The key is that in this line the second argument is pattern itself. This allows us to match the same character in pattern multiple times as long as the one after it is a star. Note the lack of need of having parenthesis in our statement involving 'or' and 'and'.
)
else:
return first_match and self.isMatch(text[1:], pattern[1:]) # The problem is really easy if no * is involved.
# SOLUTION 2: DYNAMIC PROGRAMMING (DP), TOP-DOWN APPROACH
memo = {} # Will be used to cache intermediate results.
def dp(i, j): # Because calls will only ever be made to match(text[i:], pattern[j:]), we use \text{dp(i, j)}dp(i, j) to handle those calls instead, saving us expensive string-building operations and allowing us to cache the intermediate results
if (i, j) not in memo: # This line is where we are using DP (memoization). (i, j) might already be in the memo because of the statement "dp(i, j+2) or first_match and dp(i+1, j)" below, where we are trying 2 different calls involving dp simultaneously.
if j == len(pattern):
ans = i == len(text) # If we see that both strings have terminated at the same time then the ans for this specific 'char' is true.
else:
first_match = i < len(text) and pattern[j] in {text[i], '.'}
if j + 1 < len(pattern) and pattern[j + 1] == '*':
ans = dp(i, j + 2) or first_match and dp(i + 1, j)
else:
ans = first_match and dp(i + 1, j + 1)
memo[i, j] = ans
return memo[i, j] # memo[i, j] should be true for all i, j for the method to finally return true.
return dp(0, 0) # dp(i, j) represents the question "Do text[i:] and pattern[j:] match?" This is why we call dp(0,0).
# SOLUTION 3: DP, BOTTOM-UP APPROACH
dp = [[False] * (len(pattern) + 1) for _ in range(len(text) + 1)]
dp[-1][-1] = True
for i in range(len(text), -1, -1):
for j in range(len(pattern) - 1, -1, -1):
first_match = i < len(text) and pattern[j] in {text[i], '.'}
if j + 1 < len(pattern) and pattern[j + 1] == '*':
dp[i][j] = dp[i][j + 2] or first_match and dp[i + 1][j]
else:
dp[i][j] = first_match and dp[i + 1][j + 1]
return dp[0][0]
|
n = int(input())
for i in range(n):
c=input()
lst=list(c)
l=len(c)
c2=[]
for i2 in range(l):
if(lst[i2]=='4'):
lst[i2]='3'
c2.append('1')
else:
c2.append('0')
print("".join(lst)+" "+"".join(c2))
|
# Faça um programa que leia a largura e a altura de uma parade em metros,
# calcule a sua área e a quantidade de tinta necessária para pinta-la,
# sabendo que cada litro de tinta, pinta uma área de 2m².
print('This program will tell you, how many liters of paint you will need to paint the area you want.')
h = float(input('Type the height of the wall in meters:\n>>> '))
w = float(input('Type the width of the wall in meters?\n>>> '))
m = h*w
lp = 2
mp = m/lp
print('\nThe area to be painted is {}m². You will need {}m² of paint to paint it.\n'.format(m,mp))
|
def crf_pos_features(sent, i):
word = sent[i][0]
postag = sent[i][1]
features = [
'bias',
'word=' + word, #current word
'word[-4:]=' + word[-4:], #last 4 characters
'word[-3:]=' + word[-3:], #last 3 characters
'word[-2:]=' + word[-2:], #last two characters
'word.isdigit=%s' % word.isdigit(), #is a digit
]
if len(word) > 3:
features.extend([
'word.short=False'
])
if len(word) < 3:
features.extend([
'word.short=True'
])
if i > 0:
word1 = sent[i-1][0]
features.extend([
'-1:word=' + word1, #previous word
])
else:
features.append('BOS')
if i < len(sent)-1:
word1 = sent[i+1][0]
postag1 = sent[i+1][1]
features.extend([
'+1:word=' + word1, #next word
])
else:
features.append('EOS')
return features |
nop = b'\x00\x00'
brk = b'\x00\xA0'
lda = b'\x6A\x02' # Load 0x02 into register VA
ldb = b'\x6D\xDD' # Load 0xDD into register VD
ldx = b'\x8D\xA0' # Load register VA into VD
with open("ldvxvytest.bin", 'wb') as f:
f.write(lda) # 0x0200 <-- Load the byte 0x02 into register VA
f.write(ldb) # 0x0202 <-- Load the byte 0xDD into register VD
f.write(ldx) # 0x0204 <-- Load VA into VD
f.write(brk) # 0x0206 <-- Check to make sure VA and VD are what we expect
|
#!/usr/bin/env python2
#
# Copyright 2020 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
BUNDLE_BUCKET = '${BUNDLE_BUCKET}'
NOREPLY_EMAIL = '${NOREPLY_EMAIL}'
FAILURE_EMAIL = '${FAILURE_EMAIL}'
|
# Push Bullet API Token Here
# https://www.pushbullet.com/#settings/account
login = {
'pushbullet_api_token' : 'ITSASECRET',
'hassio_password' : 'ITSASECRET'
} |
# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
load("@rules_rust//rust:repositories.bzl", "rules_rust_dependencies", "rust_register_toolchains", "rust_repository_set")
load("//third_party/rust/crates:crates.bzl", "raze_fetch_remote_crates")
load("@rules_rust//tools/rust_analyzer/raze:crates.bzl", "rules_rust_tools_rust_analyzer_fetch_remote_crates")
load(
"@safe_ftdi//third_party/rust:deps.bzl",
ftdi_fetch_remote_crates = "fetch_remote_crates",
)
def rust_deps():
rules_rust_dependencies()
rust_register_toolchains(
include_rustc_srcs = True,
edition = "2018",
version = "1.60.0",
)
rust_repository_set(
name = "rust_opentitan_rv32imc",
version = "nightly",
exec_triple = "x86_64-unknown-linux-gnu",
extra_target_triples = ["riscv32imc-unknown-none-elf"],
iso_date = "2022-03-22",
edition = "2021",
)
raze_fetch_remote_crates()
ftdi_fetch_remote_crates()
rules_rust_tools_rust_analyzer_fetch_remote_crates()
|
'''__init__.py'''
__version__ = '21.40.2dev'
version = '21w40b-dev'
|
# Comments are lines that exist in computer programs that are ignored by
# compilers and interpreters.
#
# Including comments in programs makes code more readable
# for humans as it provides some information or explanation
# about what each part of a program is doing.
#
# In general, it is a good idea to write comments
# while you are writing or updating a program as it
# is easy to forget your thought process later on,
# and comments written later may be less useful in the
# long term.
#
# In Python, we use the hash (#) symbol to start writing a comment.
# this line prnints hello universe to the console
# print("Hello Universe!")
# Multi line Comments
# If we have comments that extend multiple lines,
# one way of doing it is to use hash (#) in the beginning of each line.
"""
hello everyone welcome to my channel kindly LIKE | SHARE | SUBSCRIBE
if you like the content
"""
# another way of doin this is """ """
# DocString in python
#
# Docstring is short for documentation string.
#
# It is a string that occurs as
# the first statement in a module, function, class, or method definition.
def add(a,b):
""" This function adds two numbers """
return a+b
print(add(5,4))
print(add.__doc__)
#
#
# Python Indentation
#
# Most of the programming languages like C, C++,
# Java use braces { } to define a block of code. Python uses indentation.
#
# A code block (body of a function, loop etc.)
# starts with indentation and ends with the
# first unindented line. The amount of indentation
# is up to you, but it must be consistent throughout that block.
# Generally four whitespaces are used for indentation
# and is preferred over tabs
# Indentation can be ignored in line continuation.
# But it's a good idea to always indent. It makes the code more readable.
for x in range(10):
print(x)
print(x*2)
print("LAALA")
if True:
print("Data Science")
a = "Dhoni"
if True: print("Machine Learning") ; d = 'dhoni'
# Python Statement
# Instructions that a Python interpreter can execute are called statements.
# Multi-Line Statement
# In Python, end of a statement is marked by a newline character.
# But we can make a statement extend over multiple lines with the line continuation character ().
# \\\\
s = 1+2+3+\
43+5+6+\
7+8+9
print(s)
# ()
f = (1+2+3+
43+5+6+
7+8+91)
print(f)
# ;
a = 'Virat'; b = 'Dhoni'
print(a)
print(b) |
# 9.23
def find_happy_number(num):
# TODO: Write your code here
fastSum, slowSum = num, num
while True:
# currSum = sumOfSqaures(fastSum)
# nextSum = sumOfSqaures(fastSum)
# if currSum == 1 or nextSum == 1:
# return True
fastSum = sumOfSqaures(sumOfSqaures(fastSum))
slowSum = sumOfSqaures(slowSum)
if fastSum == slowSum:
break
return slowSum == 1
# def find_happy_number(num):
# # TODO: Write your code here
# fastSum, slowSum = num, num
# while True:
# nextSum = sumOfSqaures(fastSum)
# if fastSum == 1 or nextSum == 1:
# return True
# fastSum = sumOfSqaures(nextSum)
# slowSum = sumOfSqaures(slowSum)
# if fastSum == slowSum:
# return False
# return False
def sumOfSqaures(number):
store_sum = 0
while number > 0:
last_digit = number % 10
store_sum += last_digit ** 2
# SINGLE DOESNT CUT IT
number //= 10
return store_sum
|
# Given a binary tree, flatten it to a linked list in-place.
# For example, given the following tree:
# 1
# / \
# 2 5
# / \ \
# 3 4 6
# The flattened tree should look like:
# 1
# \
# 2
# \
# 3
# \
# 4
# \
# 5
# \
# 6
# Hints:
# If you notice carefully in the flattened tree,
# each node's right child points to the next node of a pre-order traversal.
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def flatten(self, root):
"""
:type root: TreeNode
:rtype: None Do not return anything, modify root in-place instead.
"""
# https://www.cnblogs.com/grandyang/p/4293853.html
# M1. 递归之一
if not root:
return
if root.left:
self.flatten(root.left)
if root.right:
self.flatten(root.right)
tmp = root.right
root.right = root.left
root.left = None
while root.right:
root = root.right
root.right = tmp
# M2. 迭代
if not root:
return None
s = [root]
while s:
cur = s.pop()
if cur.left:
p = cur.left
while p.right:
p = p.right
p.right = cur.right
cur.right = cur.left
cur.left = None
if cur.right:
s.append(cur.right)
# M3. 非迭代
cur = root
while cur:
if cur.left:
p = cur.left
while p.right:
p = p.right
p.right = cur.right
cur.right = cur.left
cur.left = None
cur = cur.right
|
# MiClase tendrá un constructor alternativo, que usará una lista en lugar de una cadena
class Persona:
def __init__(self, nombre=''):
self.nombre = nombre
@classmethod
def fromList(cls, l):
# Instanciamos un nuevo objeto de la clase
x = cls()
# Lo rellenamos y lo devolvemos
x.nombre = ' '.join([l[0], l[1]])
return x
def __str__(self):
return self.nombre
p = Persona("Pepito Perez")
p2 = Persona.fromList(["Jorge", "Blanco"])
print(p) # Pepito Perez
print(p2) # Jorge Blanco |
INFURA_PROJECT_ID = 'FILL_YOUR_KEY'
# Networks
# Rinkeby
NETWORK = 'rinkeby'
PRIVATE_KEY = 'FILL_YOUR_PRIVATE_KEY'
# ETH mainnet
# NETWORK = 'mainnet'
PRIVATE_KEY = 'FILL_YOUR_PRIVATE_KEY' |
class UnchainedException(Exception):
def __init__(self):
super(UnchainedException, self).__init__(self.message)
class DoesntExist(UnchainedException):
message = "Attempting to get data by a key that doesn't exist"
|
MODELS = [
'ConvLSTM',
'ConvLSTM_REF',
'LSTM'
]
DATASETS = [
'GeneratedSins',
'GeneratedNoise',
'Stocks',
'MovingMNIST',
'KTH',
'BAIR'
]
KTH_CLASSES = [
'boxing',
'handclapping',
'handwaving',
'jogging',
'running',
'walking'
]
OPTS = {
'model': {
'description': 'Model architecture'
},
'dataset': {
'description': 'Dataset'
},
'device': {
'description': 'Device to use',
'default': 'gpu',
'choices': ['gpu', 'cpu'],
},
'num_workers': {
'description': 'Number of dataloader workers',
'default': 4,
'type': int,
},
'num_layers': {
'description': 'Number of specified model architecture layers',
'default': 1,
'type': int,
},
'seq_len': {
'description': 'Total Length of sequence to predict',
'default': 20,
'type': int,
},
'fut_len': {
'description': 'Length of predicted sequence',
'default': 10,
'type': int,
},
'batch_size': {
'description': 'Size of data batches for each step',
'default': 4,
'type': int,
},
'n_val_batches': {
'description': 'Maximum number of batches for validation loop',
'default': 10,
'type': int,
},
'n_test_batches': {
'description': 'Maximum number of batches for testing loop',
'default': 50,
'type': int,
},
'val_interval': {
'description': 'Fraction of train batches to validate between',
'default': 0.5,
'type': float
},
'shuffle': {
'description': 'Whether to shuffle data in dataloader',
'default': True,
'type': bool,
},
'learning_rate': {
'description': 'Learning rate of optimizer',
'default': 0.001,
'type': float,
},
'max_epochs': {
'description': 'Maximum number of epochs to train/test',
'default': 300,
'type': int,
},
'criterion': {
'description': 'Loss function for training',
'default': 'MSELoss',
'choices': ['MSELoss'],
},
'image_interval': {
'description': 'How many steps between image generation',
'default': 500,
'type': int,
},
'kth_classes': {
'description': 'Which classes to use in the KTH dataset training',
'default': KTH_CLASSES,
'nargs': '+',
},
'checkpoint_path': {
'description': 'Path of model checkpoint to resume training or test',
'default': None,
},
'task_id': {
'description': 'Task ID for slurm scheduler array jobs',
'default': None,
},
'results_dir': {
'description': 'Directory to log results',
'default': 'results',
},
'mmnist_num_digits': {
'description': 'Number of digits to use in the MovingMNIST dataset',
'default': 2,
'type': int,
},
'no_images': {
'description': 'Set this value True to negate the creation of any images',
'default': False,
'type': bool,
},
'hid_size': {
'description': 'Hidden size or channel dimension',
'default': 64,
'type': int
}
}
|
# -*- coding: utf-8 -*-
# http://stackoverflow.com/questions/106179/regular-expression-to-match-hostname-or-ip-address
REGEX_IPADDR = "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])"
REGEX_HOSTNAME = "(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])"
REGEX_JID = "([0-9]{20})"
|
# -*- coding: utf-8 -*-
"""
BuzzlogixTextAnalysisAPILib.Configuration
This file was automatically generated for buzzlogix by APIMATIC BETA v2.0 on 12/06/2015
"""
class Configuration :
# The base Uri for API calls
BASE_URI = "https://buzzlogix-text-analysis.p.mashape.com"
|
'''https://leetcode.com/problems/generate-parentheses/'''
#iterative solution
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
res = []
stack = [("(", 1, 0)]
while stack:
x, l, r = stack.pop()
if r>l or l>n or r>n:
continue
if l==n and r==n:
res.append(x)
stack.append((x+"(", l+1, r))
stack.append((x+")", l, r+1))
return res
#recursive solution
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
ans = []
def backtrack(s='', l=0, r=0):
if len(s)==2*n:
ans.append(s)
return
if l<n:
backtrack(s+'(', l+1, r)
if r<l:
backtrack(s+')', l, r+1)
backtrack()
return ans
|
# Ex. 086 +=
matriz = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
for i in range(3):
for j in range(3):
matriz[i][j] = int(input(f"Digite um valor para a posição [{i}, {j}]: "))
print("-" * 30)
for linha in matriz:
for coluna in linha:
print(f"[{coluna:^5}]", end=" ")
print()
|
celsius = [0.7, 2.1, 4.2, 8.2, 12.5, 15.6, 16.9, 16.3, 13.6, 9.5, 4.6, 2.3] #Durschnittstemperaturen Bielefeld
# Liste Umrechnung in Fahrenheit erzeugen (FOR-Schleife)
wertefahrenheit = []
for wertecelsius in celsius:
wertefahrenheit.append(round((wertecelsius*1.8)+32, 2)) # F = C*1.8 + 32 C = (F-32)/1.8
print(wertefahrenheit)
# Liste Umrechnung in Fahrenheit erzeugen (LIST Comprehension)
print('Werte Fahrenheit')
wertefahrenheit = [wertecelsius * 1.8 +32 for wertecelsius in celsius]
print(wertefahrenheit)
# Liste Umrechnung in Fahrenheit mit Temperaturen in Celsius >= 15°C
print('Werte Fahrenheit (Celsius>=15°C)')
wertefahrenheit = [wertecelsius* 1.8 +32 for wertecelsius in celsius if wertecelsius >= 15]
print(wertefahrenheit)
|
"""
Merge two sorted linked lists and return it as a new list. The new list should
be made by splicing together the nodes of the first two lists.
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
No dummy node
"""
res = None
res_end = None
while l1 is not None and l2 is not None:
if l1.val < l2.val:
if res is None:
res = l1
res_end = res
else:
res_end.next = l1
res_end = res_end.next
l1 = l1.next
else:
if res is None:
res = l2
res_end = res
else:
res_end.next = l2
res_end = res_end.next
l2 = l2.next
if l1 is not None:
if res is not None:
res_end.next = l1
else:
res = l1
if l2 is not None:
if res is not None:
res_end.next = l2
else:
res = l2
return res
|
def bumpVersion(file_loc, which="patch", dry_run = False, all_matching_lines = False, write_loc = None):
if which not in ["major", "minor", "patch"]:
print(f"Argument must be one of major, minor, or patch, instead was {which}")
raise ValueError(which)
with open(file_loc, "r") as f:
lines = []
linesAltered = 0
while s:= f.readline():
if s.startswith("version"):
linesAltered += 1
if "'" in s: quote = "'"
if '"' in s: quote = '"'
vers = s.split("=")[1].replace(quote, "").replace(' ', '').replace('\n', '').split('.')
vers = [int(x) for x in vers]
while len(vers) < 3: vers.append(0)
major, minor, patch = vers
if which == "major":
major += 1
minor, patch = 0, 0
elif which == "minor":
minor +=1
patch = 0
elif which == "patch":
patch +=1
lines.append(f'version={quote}{major}.{minor}.{patch}{quote}\n')
else:
lines.append(s)
if dry_run:
[print(line) for line in lines]
elif linesAltered == 0:
print("No changes were made. Do you have a line that starts with 'version' ?")
elif linesAltered > 1:
print("More than one line has been altered, this is unexpected. Set 'all_matching_lines' to True if this is intended.")
else:
with open(write_loc or file_loc, 'w') as f:
f.writelines(lines) |
INTERSECTION_SIZE = 9 # number of pixels; any odd number should work (cars will be VERY thin though)
# very customized functions, may not be perfect for every layout
def make_grid(grid_cols, grid_rows, scale_factor, segment_len=100, margin=20):
margin = margin + segment_len
return {"render_screen_size": (margin * (grid_cols + 1), margin * (grid_rows + 1)),
"render_scale_factor": scale_factor,
"intersections": [(x * (INTERSECTION_SIZE + segment_len) + margin,
y * (INTERSECTION_SIZE + segment_len) + margin)
for y in range(grid_rows) for x in range(grid_cols)],
"segments":
# l → r
[(segment_len, x, "r", (x + 1) if (x + 1) % grid_cols != 0 else (x + 1) - grid_cols, "l")
for x in range(grid_rows * grid_cols)]
+ # r ← l
[(segment_len, (x + 1) if (x + 1) % grid_cols != 0 else (x + 1) - grid_cols, "l", x, "r")
for x in range(grid_rows * grid_cols)]
+ # d ↑ u
[(segment_len, x, "d", (x + grid_cols) if (x + grid_cols) < (grid_cols * grid_rows - 1) else (
(x + grid_cols) % (grid_cols * grid_rows)), "u") for x in range(grid_rows * grid_cols)]
+ # u ↓ d
[(segment_len, (x + grid_cols) if (x + grid_cols) < (grid_cols * grid_rows - 1) else (
(x + grid_cols) % (grid_cols * grid_rows)), "u", x, "d") for x in range(grid_rows * grid_cols)]
}
def make_line(intersections, two_lanes, scale_factor, segment_len=100, margin=20):
margin = margin + segment_len
grid_rows = 1
segments = [(segment_len, x, "r", (x + 1) if (x + 1) % intersections != 0 else (x + 1) - intersections, "l")
for x in range(grid_rows * intersections)]
if two_lanes:
segments += [(segment_len, (x + 1) if (x + 1) % intersections != 0 else (x + 1) - intersections, "l", x, "r")
for x in range(grid_rows * intersections)]
return {"render_screen_size": (margin * (intersections + 1), segment_len // 2),
"render_scale_factor": scale_factor,
"intersections": [(x * (INTERSECTION_SIZE + segment_len) + margin, margin - segment_len) for x in
range(intersections)],
"segments": segments
}
|
# Copyright 2020 Xilinx Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Utility for topologically sorting a list of XLayer objects
"""
def sort_topologically(net):
# type: (List[XLayer]) -> List[XLayer]
""" Topologically sort a list of XLayer objects in O(N^2)"""
top_net = []
bottoms_cache = {X.name: X.bottoms[:] for X in net}
while len(net) > len(top_net):
for X in net:
if X.name in bottoms_cache and bottoms_cache[X.name] == []:
top_net.append(X)
for t in X.tops:
bottoms_cache[t].remove(X.name)
del bottoms_cache[X.name]
return top_net
|
'''
Python program to find the number of zeros at the end of a factorial of a given positive number
'''
def factendzero (n):
factorial = 1
x = n // 5
y = x
if n < 0:
print("Sorry, factorial does not exist for negative numbers")
elif n == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,n + 1):
factorial = factorial*i
print("The factorial of",n,"is",factorial)
while x > 0:
x /= 5
y += int (x)
return y
print (factendzero (5))
print (factendzero (12))
print (factendzero (100))
|
# coding: utf-8
days = '周一 周二 周三 周四 周五 周六 周日'
months = '\n一月\n二月\n三月\n四月\n五月\n六月\n七月\n八月\n九月\n十月\n十一月\n十二月'
print('Here are the days:', days)
print('Here are the months:', months)
print('''
1. 前端
2. 后端
3. 设计
4. 测试
''')
|
class ReplayBuffer(object):
pass
|
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def all_tests(tests, deps, tags = [], shard_count = 1, data = []):
for file in tests:
# TODO(malcon): Skip files not ending as *Test.java
relative_target = file[:-5]
suffix = relative_target.replace("/", ".")
pos = native.package_name().rfind("javatests/") + len("javatests/")
test_class = native.package_name()[pos:].replace("/", ".") + "." + suffix
native.java_test(
name = file[:-5],
srcs = [file],
javacopts = [
"-Xlint:unchecked",
"-source",
"1.8",
"-Xep:FutureReturnValueIgnored:OFF",
],
test_class = test_class,
data = data,
deps = deps + [
# These deps are automatically included with Bazel, but not with the
# internal BUILD system. So add them explicitly here.
"//third_party:guava",
"//third_party:jsr305",
"//third_party:junit",
],
tags = tags,
shard_count = shard_count,
)
|
"""Project Euler problem 7"""
def is_prime(number):
"""Returns True if the specified number is prime"""
if number <= 1:
return False
count = 2
while count ** 2 <= number:
if number % count == 0:
return False
count += 1
return True
def calculate(last_prime):
"""Returns the last_prime-th prime"""
primes = []
count = 0
while len(primes) < last_prime:
match = False
if is_prime(count):
for prime in primes:
if count % prime == 0:
match = True
break
if not match:
primes.append(count)
count += 1
answer = primes[-1]
return answer
if __name__ == "__main__":
print(calculate(10001))
|
shelf = input().split("&")
line = input().split(" | ")
while line[0] != "Done":
command = line[0]
book = line[1] # може и е по-добре да е тук, за да не се повтаря на всякъде
if command == "Add Book":
# for book in line[1:]: излишно e
if book not in shelf:
shelf.insert(0, book)
elif command == "Take Book":
if book in shelf:
shelf.remove(book)
elif command == "Swap Books":
book_2 = line[2]
if book in shelf and book_2 in shelf:
book_idx = shelf.index(book)
book_2_idx = shelf.index(book_2)
shelf[book_idx], shelf[book_2_idx] = shelf[book_2_idx], shelf[book_idx]
elif command == "Insert Book":
# shelf.remove(book) няма как да кажеш remove на нещо, което още не си append-нал :D :D
shelf.append(book)
elif command == "Check Book":
index = int(line[1])
if not index > len(shelf): # If the index is invalid, ignore the command.
print(shelf[index])
line = input().split(" | ")
print(", ".join(shelf)) |
nome = str(input('Qual é o seu nome? '))
if nome == 'Denis':
print('Que nome lindo!')
elif nome == 'Joao' or nome == 'Maria' or nome == 'Paulo':
print('Seu nome é comum demais.')
elif nome in 'Ana, Julia, Mariana, Julia':
print('Seu nome é lindo demais!')
print('Tenha um ótimo dia, {}.'.format(nome)) |
# Description
# The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
# Given two integers x and y, calculate the Hamming distance.
# Example
# Input: x = 1, y = 4
# Output: 2
class Solution:
"""
@param x: an integer
@param y: an integer
@return: return an integer, denote the Hamming Distance between two integers
"""
def hammingDistance(self, x, y):
# write your code here
count = 0
while x or y:
if x&1 != y&1:
count = count + 1
x = x >> 1
y = y >> 1
return count |
def init_lst():
return [i for i in range(0, 256)]
class KnotTier:
def __init__(self):
self.pos = 0
self.skip = 0
def tie_a_knot(self, start, length, lst):
if length < 2:
return
end = (start + length - 1) % len(lst)
lst[start], lst[end] = lst[end], lst[start]
if length == 2:
return
start += 1
start %= len(lst)
self.tie_a_knot(start, length - 2, lst)
def tie_knots(self, lst, lengths):
for length in lengths:
self.tie_a_knot(self.pos, length, lst)
self.pos += length + self.skip
self.pos %= len(lst)
self.skip += 1
|
#
# PySNMP MIB module TPT-ATA-REG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPT-ATA-REG-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:26:14 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)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsIntersection")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
ObjectIdentity, NotificationType, Gauge32, ModuleIdentity, TimeTicks, iso, Bits, Counter64, IpAddress, MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, MibIdentifier, Integer32, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "ObjectIdentity", "NotificationType", "Gauge32", "ModuleIdentity", "TimeTicks", "iso", "Bits", "Counter64", "IpAddress", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "MibIdentifier", "Integer32", "Counter32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
tpt_reg, = mibBuilder.importSymbols("TIPPINGPOINT-REG-MIB", "tpt-reg")
tpt_ata_family = ModuleIdentity((1, 3, 6, 1, 4, 1, 10734, 1, 10)).setLabel("tpt-ata-family")
tpt_ata_family.setRevisions(('2016-05-25 18:54', '2015-07-30 17:35',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: tpt_ata_family.setRevisionsDescriptions(('Updated copyright information. Minor MIB syntax fixes.', 'Initial MIB version.',))
if mibBuilder.loadTexts: tpt_ata_family.setLastUpdated('201605251854Z')
if mibBuilder.loadTexts: tpt_ata_family.setOrganization('Trend Micro, Inc.')
if mibBuilder.loadTexts: tpt_ata_family.setContactInfo('www.trendmicro.com')
if mibBuilder.loadTexts: tpt_ata_family.setDescription("Registration sub-tree for TippingPoint Advanced Threat Application (ATA) products. Copyright (C) 2016 Trend Micro Incorporated. All Rights Reserved. Trend Micro makes no warranty of any kind with regard to this material, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose. Trend Micro shall not be liable for errors contained herein or for incidental or consequential damages in connection with the furnishing, performance, or use of this material. This document contains proprietary information, which is protected by copyright. No part of this document may be photocopied, reproduced, or translated into another language without the prior written consent of Trend Micro. The information is provided 'as is' without warranty of any kind and is subject to change without notice. The only warranties for Trend Micro products and services are set forth in the express warranty statements accompanying such products and services. Nothing herein should be construed as constituting an additional warranty. Trend Micro shall not be liable for technical or editorial errors or omissions contained herein. TippingPoint(R), the TippingPoint logo, and Digital Vaccine(R) are registered trademarks of Trend Micro. All other company and product names may be trademarks of their respective holders. All rights reserved. This document contains confidential information, trade secrets or both, which are the property of Trend Micro. No part of this documentation may be reproduced in any form or by any means or used to make any derivative work (such as translation, transformation, or adaptation) without written permission from Trend Micro or one of its subsidiaries. All other company and product names may be trademarks of their respective holders. ")
tpt_model_ata_network = ObjectIdentity((1, 3, 6, 1, 4, 1, 10734, 1, 10, 1)).setLabel("tpt-model-ata-network")
if mibBuilder.loadTexts: tpt_model_ata_network.setStatus('current')
if mibBuilder.loadTexts: tpt_model_ata_network.setDescription('Registration for TippingPoint ATA Network Appliances.')
tpt_model_ata_mail = ObjectIdentity((1, 3, 6, 1, 4, 1, 10734, 1, 10, 2)).setLabel("tpt-model-ata-mail")
if mibBuilder.loadTexts: tpt_model_ata_mail.setStatus('current')
if mibBuilder.loadTexts: tpt_model_ata_mail.setDescription('Registration for TippingPoint ATA Mail Appliances.')
mibBuilder.exportSymbols("TPT-ATA-REG-MIB", tpt_model_ata_mail=tpt_model_ata_mail, tpt_model_ata_network=tpt_model_ata_network, PYSNMP_MODULE_ID=tpt_ata_family, tpt_ata_family=tpt_ata_family)
|
#!/usr/bin/python3
def test_ternery1(evmtester, branch_results):
evmtester.terneryBranches(1, True, False, False, False)
results = branch_results()
assert [2582, 2583] in results[True]
assert [2610, 2611] in results[False]
evmtester.terneryBranches(1, False, False, False, False)
results = branch_results()
assert [2582, 2583] in results[False]
assert [2610, 2611] in results[True]
def test_ternery2(evmtester, branch_results):
evmtester.terneryBranches(2, False, False, False, False)
results = branch_results()
for i in [2670, 2704, 2709]:
assert [i, i + 1] in results[False]
evmtester.terneryBranches(2, True, False, False, False)
results = branch_results()
assert [2675, 2676] in results[False]
for i in [2670, 2704]:
assert [i, i + 1] in results[True]
evmtester.terneryBranches(2, False, True, False, False)
results = branch_results()
assert [2709, 2710] in results[True]
for i in [2670, 2704]:
assert [i, i + 1] in results[False]
evmtester.terneryBranches(2, True, True, False, False)
results = branch_results()
for i in [2670, 2675, 2704]:
assert [i, i + 1] in results[True]
def test_ternery3(evmtester, branch_results):
evmtester.terneryBranches(3, False, False, False, False)
results = branch_results()
for i in [2771, 2777, 2807]:
assert [i, i + 1] in results[True]
evmtester.terneryBranches(3, True, False, False, False)
results = branch_results()
assert [2813, 2814] in results[True]
for i in [2771, 2807]:
assert [i, i + 1] in results[False]
evmtester.terneryBranches(3, False, True, False, False)
results = branch_results()
assert [2777, 2778] in results[False]
for i in [2771, 2807]:
assert [i, i + 1] in results[True]
evmtester.terneryBranches(3, True, True, False, False)
results = branch_results()
for i in [2771, 2807, 2813]:
assert [i, i + 1] in results[False]
def test_ternery4(evmtester, branch_results):
evmtester.terneryBranches(4, False, False, False, False)
results = branch_results()
for i in [2874, 2913, 2918, 2923]:
assert [i, i + 1] in results[False]
evmtester.terneryBranches(4, True, False, False, False)
results = branch_results()
assert [2879, 2880] in results[False]
for i in [2874, 2913]:
assert [i, i + 1] in results[True]
evmtester.terneryBranches(4, False, True, False, False)
results = branch_results()
assert [2918, 2919] in results[True]
for i in [2874, 2913]:
assert [i, i + 1] in results[False]
evmtester.terneryBranches(4, False, False, True, False)
results = branch_results()
assert [2923, 2924] in results[True]
for i in [2874, 2913, 2918]:
assert [i, i + 1] in results[False]
evmtester.terneryBranches(4, True, True, True, False)
results = branch_results()
for i in [2874, 2879, 2884, 2913]:
assert [i, i + 1] in results[True]
def test_ternery5(evmtester, branch_results):
evmtester.terneryBranches(5, True, True, True, True)
results = branch_results()
for i in [2985, 3027, 3033, 3039]:
assert [i, i + 1] in results[False]
evmtester.terneryBranches(5, False, True, True, True)
results = branch_results()
assert [2991, 2992] in results[False]
for i in [2985, 3027]:
assert [i, i + 1] in results[True]
evmtester.terneryBranches(5, True, False, True, True)
results = branch_results()
assert [3033, 3034] in results[True]
for i in [2985, 3027]:
assert [i, i + 1] in results[False]
evmtester.terneryBranches(5, True, True, False, True)
results = branch_results()
assert [3039, 3040] in results[True]
for i in [2985, 3027, 3033]:
assert [i, i + 1] in results[False]
evmtester.terneryBranches(5, False, False, False, False)
results = branch_results()
for i in [2985, 2991, 2997, 3027]:
assert [i, i + 1] in results[True]
|
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
answer = []
keypad = ['', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']
def helper(prefix, idx):
# reached end of this current backtrack and isn't just ''
if idx == len(digits):
if prefix != '':
answer.append(prefix)
return
for char in keypad[int(digits[idx])]:
helper(prefix + char, idx + 1)
helper('', 0)
return answer
|
class baseparser:
"""
Parser interface.
"""
def parse_file(self, source):
"""
Parses a Graph from an OSM file.
This is the preferred way for parsing when on execution mode.
parse_file(source) -> graph
@type source: string
@param source: OSM file absolute path.
@rtype: graph
@return: parsed graph.
"""
raise NotImplementedError("parse_file: You should have implemented this method!")
def parse_string(self, source):
"""
Parses a Graph from an OSM string.
This is the preferred way for parsing when on profiling mode.
parse_string(source) -> graph
@type source: string
@param source: OSM string
@rtype: graph
@return: parsed graph.
"""
raise NotImplementedError("parse_string: You should have implemented this method!") |
def parse_page_obj(raw_obj):
return {
"wiki_db": raw_obj['wiki_db'],
"event_entity": raw_obj['event_entity'],
"event_type": raw_obj['event_type'],
"event_timestamp": raw_obj['event_timestamp'],
"event_comment": raw_obj['event_comment'],
"event_user": {
"id": raw_obj['event_user_id'],
"text_historical": raw_obj['event_user_text_historical'],
"text": raw_obj['event_user_text'],
"blocks_historical": raw_obj['event_user_blocks_historical'],
"blocks": raw_obj['event_user_blocks'],
"groups_historical": raw_obj['event_user_groups_historical'],
"groups": raw_obj['event_user_groups'],
"is_bot_by_historical": raw_obj['event_user_is_bot_by_historical'],
"is_bot_by": raw_obj['event_user_is_bot_by'],
"is_created_by_self": raw_obj['event_user_is_created_by_self'],
"is_created_by_system": raw_obj['event_user_is_created_by_system'],
"is_created_by_peer": raw_obj['event_user_is_created_by_peer'],
"is_anonymous": raw_obj['event_user_is_anonymous'],
"registration_timestamp": raw_obj['event_user_registration_timestamp'],
"creation_timestamp": raw_obj['event_user_creation_timestamp'],
"first_edit_timestamp": raw_obj['event_user_first_edit_timestamp'],
"revision_count": raw_obj['event_user_revision_count'],
"seconds_since_previous_revision": raw_obj['event_user_seconds_since_previous_revision'],
},
"page": {
"id": raw_obj['page_id'],
"title_historical": raw_obj['page_title_historical'],
"title": raw_obj['page_title'],
"namespace_historical": raw_obj['page_namespace_historical'],
"namespace_is_content_historical": raw_obj['page_namespace_is_content_historical'],
"namespace": raw_obj['page_namespace'],
"namespace_is_content": raw_obj['page_namespace_is_content'],
"is_redirect": raw_obj['page_is_redirect'],
"is_deleted": raw_obj['page_is_deleted'],
"creation_timestamp": raw_obj['page_creation_timestamp'],
"first_edit_timestamp": raw_obj['page_first_edit_timestamp'],
"revision_count": raw_obj['page_revision_count'],
"seconds_since_previous_revision": raw_obj['page_seconds_since_previous_revision'],
}
}
|
while True:
try:
user_input = int(input("Please enter a integer between 0 to 1000: "))
except:
print("Please enter a numeric value")
continue
if user_input < 1:
print("Please enter a positive integer")
continue
break
if (user_input % 2) == 0:
print("That's an even number!")
else:
print("That's odd number!") |
"""
Tangerine Whistle Utility Functions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. contents:: Table of Contents
:backlinks: none
:local:
Introduction
------------
Utility functions used in this tangerine whistle version of specification.
"""
|
"""
1100 : 하얀 칸
URL : https://www.acmicpc.net/problem/1100
Input :
.F.F...F
F...F.F.
...F.F.F
F.F...F.
.F...F..
F...F.F.
.F.F.F.F
..FF..F.
Output :
1
"""
chess = []
for i in range(8):
chess.append(input())
count = 0
for i, row in enumerate(chess):
for j, c in enumerate(row):
if c == 'F':
if ((i % 2) == 0) and ((j % 2) == 0):
count += 1
if ((i % 2) == 1) and ((j % 2) == 1):
count += 1
print(count)
|
run = ['''
<PhysicsModeling>:
name: "physicsmodel"
# canvas.before:
# Color:
# rgb: .2, .2, .2
# Rectangle:
# size: self.size
# source: '/background.png'
# this below is variables in the .py file being assigned to the id's
# below in the .kv file here to allow them to be referenced in the core code
# format below is "[.py variable name]: [id name in .kv file]"
physicsModel: physicsModel
initialConditions: initialConditions
visTechnique: visTechnique
FloatLayout:
Label:
text: "[size=35dp][b]QLGA SIMULATOR[/b][/size] [size=20dp][b]Physics Modeling[/b][/size]"
markup: True
size_hint: (0.75, 0.5)
pos_hint: {'center': (0.5, 0.75)}
halign: 'center'
Label:
text: "Model"
halign: 'center'
pos_hint: {'center': (0.15, .5)}
Spinner:
id: physicsModel
size_hint: (0.3, 0.1)
pos_hint: {'center': (0.35, .5)}
text: 'Click to Select'
halign: 'center'
values: ''',
'''on_text: root.physicsmodel_spinner_clicked(physicsModel.text)
Label:
text: "Initial Conditions "
size_hint: (0.75, 0.5)
pos_hint: {'center': (0.6, 0.50)}
Spinner:
id: initialConditions
size_hint: (0.2, 0.1)
pos_hint: {'center': (0.8, .5)}
text: 'Click to Select'
halign: 'center'
values:''',
'''on_text: root.initialconditions_spinner_clicked(initialConditions.text)
Label:
text: "Visualization"
halign: 'center'
pos_hint: {'center': (0.37, .3)}
Spinner:
id: visTechnique
size_hint: (0.24, 0.1)
pos_hint: {'center': (0.57, .3)}
text: 'Click to Select'
halign: 'center'
values:''',
'''on_text: root.visualization_spinner_clicked(visTechnique.text)
Button:
text: '[size=15dp][b]<-[/b][/size] Go Back'
markup: True
size_hint: (0.15, 0.05)
pos_hint: {'center': (0.15, 0.07)}
on_release:
app.root.current = "runoptions"
root.manager.transition.direction = "right"
Button:
text: 'Next Page [size=15dp][b]->[/b][/size]'
markup: True
halign: 'center'
size_hint: (0.15, 0.05)
pos_hint: {'center': (0.85, 0.07)}
on_press: root.next_button()
on_release:
app.root.current = "kwargOptions"
root.manager.transition.direction = "left"
'''
] |
"""
The dependencies for running the gen_rust_project binary.
"""
load("//tools/rust_analyzer/raze:crates.bzl", "rules_rust_tools_rust_analyzer_fetch_remote_crates")
def rust_analyzer_deps():
rules_rust_tools_rust_analyzer_fetch_remote_crates()
# For legacy support
gen_rust_project_dependencies = rust_analyzer_deps
|
class Solution:
def reachingPoints(self, sx, sy, tx, ty):
"""
:type sx: int
:type sy: int
:type tx: int
:type ty: int
:rtype: bool
"""
while tx >= sx and ty >= sy:
tx, ty = tx % ty, ty % tx
return sx == tx and (ty - sy) % sx == 0 or sy == ty and (tx - sx) % sy == 0
|
# The following function returns by recursion the length L of the longest palindromic substring of a given string s
def lps(s):
n = len(s)
# basic cases: L = 0 if s is an empty substring, L = 1 if s has only one character
if n == 0 or n == 1:
L = n
# the recursion goes as follows: if the first and last character of the string are the same, then it is sufficient to add 2 to the length
# of the longest palindromic substring of the same string deprived of the first and last character, i.e. s[1:-1]; if not, then it is the
# maximum between the length of the longest palindromic substring of s[:-1] and that of s[1:]
else:
if s[0] == s[-1]:
return 2+lps(s[1:-1])
else:
return max(lps(s[:-1]), lps(s[1:]))
return L
# This solution is not optimal because it is very likely to happen that the function lps(s) will be called on the same substring in different branches of the recursion.
# A possible way to improve might be to store the result of each call, so that, instead of calling the function again, everytime we will get a substring that has already appeared
# we just select the value of its longest palindrome substring among the ones that are stored.
|
#Einfügen von "get"- und "set"- Methoden für private Attribute
#Es ist anscheinend besser mit der "get"- und "set"-Funktion zu arbeiten
class Behaelter(object):
def __init__(self, volumen):
self.__volumen = float(volumen)
def setVolumen(self, neues_Volumen):
self.__volumen=float(neues_Volumen)
def getVolumen(self):
return self.__volumen
#volumen=property(setVolumen,getVolumen)
#Beispiel
becher=Behaelter(5)
print(becher.getVolumen())
becher.setVolumen(100)
print(becher.getVolumen())
|
"""Used to single sourcing metadata about caluma."""
__title__ = "caluma"
__description__ = "Caluma Service providing GraphQL API"
__version__ = "2.0.0"
|
f = open('/home/bu807/Downloads/keras-yolo3-master2/keras-yolo3-master2/result/result.txt',encoding='utf8')
s = f.readlines()
result_path ='/home/bu807/Downloads/keras-yolo3-master2/keras-yolo3-master2/mAP-master/input/detection-results/'
for i in range(len(s)): # 中按行存放的检测内容,为列表的形式
r = s[i].split('.jpg ')
file = open(result_path + r[0] + '.txt', 'w')
if len(r[1]) > 5:
t = r[1].split(';')
# print('len(t):',len(t))
if len(t) == 3:
file.write(t[0] + '\n' + t[1] + '\n') # 有两个对象被检测出
elif len(t) == 4:
file.write(t[0] + '\n' + t[1] + '\n' + t[2] + '\n') # 有三个对象被检测出
elif len(t) == 5:
file.write(t[0] + '\n' + t[1] + '\n' + t[2] + '\n' + t[3] + '\n') # 有四个对象被检测出
elif len(t) == 6:
file.write(t[0] + '\n' + t[1] + '\n' + t[2] + '\n' + t[3] + '\n' + t[4] + '\n') # 有五个对象被检测出
elif len(t) == 7:
file.write(t[0] + '\n' + t[1] + '\n' + t[2] + '\n' + t[3] + '\n' + t[4] + '\n' + t[5] + '\n') # 有六个对象被检测出
else:
file.write(t[0] + '\n') # 有一个对象
else:
file.write('') # 没有检测出来对象,创建一个空白的对象 |
#!/usr/bin/python
def displayPathtoPrincess(n, grid):
# print all the moves here
counter = 1
for row in grid:
if 'p' in row:
px = row.index('p') + 1
py = n - counter + 1
if 'm' in row:
mx = row.index('m') + 1
my = n - counter + 1
counter += 1
dx = px - mx
dy = py - my
if dx > 0:
for _ in range(dx):
print('RIGHT')
else:
for i in range(abs(dx)):
print('LEFT')
if dy > 0:
for _ in range(dy):
print('UP')
else:
for _ in range(abs(dy)):
print('DOWN')
m = int(input())
grid = []
for i in range(0, m):
grid.append(input().strip())
displayPathtoPrincess(m, grid)
|
def profile_update(request):
user = request.user
if request.method == 'POST':
form = UpdateProfile(
request.POST, request.FILES or None, instance=request.user,)
if form.is_valid():
username = form.cleaned_data.get('username')
obj = form.save(commit=False)
print(request.POST.get('img'))
if request.POST.get('img'):
image = Image.open(request.FILES['img'].file)
deleteImage(obj.user_face_img_md5)
obj.user_face_img_md5 = uploadImage(image)
else:
print("No image uploaded")
obj.save()
messages.success(
request, f'Account has been updated!')
return redirect('profile')
else:
data = {
'username': user.username,
'email': user.email,
'real_name': user.real_name,
'role': user.role,
}
form = UpdateProfile(initial=data)
return render(request, 'users/profile_update.html', {'form': form, 'img_str': user.user_face_img_md5}) |
try:
error= open("dummy.txt","r")
print(error.read())# perform file operations
finally:
error.close()
|
init_code = """
if not "Friends" in USER_GLOBAL:
raise NotImplementedError("Where is 'Friends'?")
Friends = USER_GLOBAL['Friends']
"""
PASS_CODE = """
RET['code_result'] = True, "Ok"
"""
def prepare_test(middle_code, test_code, show_code, show_answer):
if show_code is None:
show_code = middle_code
return {"test_code": {"python-3": init_code + middle_code + test_code,
"python-27": init_code + middle_code + test_code},
"show": {"python-3": show_code,
"python-27": show_code},
"answer": show_answer}
TESTS = {
"1. Init": [
prepare_test('Friends(({"a", "b"}, {"b", "c"}, {"c", "a"}, {"a", "c"}))\n',
PASS_CODE, None, None),
prepare_test('Friends([{"1", "2"}, {"3", "1"}])\n', PASS_CODE, None, None),
],
"2. Add": [
prepare_test('f = Friends([{"1", "2"}, {"3", "1"}])\n'
'add_result = f.add({"2", "4"})\n',
"RET['code_result'] = add_result is True, str(add_result)",
'f = Friends([{"1", "2"}, {"3", "1"}])\n'
'f.add({"2", "4"})',
"True"
),
prepare_test('f = Friends([{"And", "Or"}, {"For", "And"}])\n'
'add_result = f.add({"It", "Am"})\n',
"RET['code_result'] = add_result is True, str(add_result)",
'f = Friends([{"And", "Or"}, {"For", "And"}])\n'
'f.add({"It", "Am"})\n',
"True"),
prepare_test('f = Friends([{"And", "Or"}, {"For", "And"}])\n'
'add_result = f.add({"Or", "And"})\n',
"RET['code_result'] = add_result is False, str(add_result)",
'f = Friends([{"And", "Or"}, {"For", "And"}])\n'
'f.add({"Or", "And"})\n',
"False")
],
"3. Remove": [
prepare_test('f = Friends([{"1", "2"}, {"3", "1"}])\n'
'remove_result = f.remove({"2", "4"})\n',
"RET['code_result'] = remove_result is False, str(remove_result)",
'f = Friends([{"1", "2"}, {"3", "1"}])\n'
'f.remove({"2", "4"})',
"False"),
prepare_test('f = Friends([{"1", "2"}, {"3", "1"}])\n'
'remove_result = f.remove({"11", "12"})\n',
"RET['code_result'] = remove_result is False, str(remove_result)",
'f = Friends([{"1", "2"}, {"3", "1"}])\n'
'f.remove({"11", "12"})',
"False"),
prepare_test('f = Friends([{"And", "Or"}, {"For", "And"}])\n'
'remove_result = f.remove({"And", "Or"})\n',
"RET['code_result'] = remove_result is True, str(remove_result)",
'f = Friends([{"And", "Or"}, {"For", "And"}])\n'
'f.remove({"And", "Or"})\n',
"True"),
],
"4. Names": [
prepare_test(
'f = Friends(({"nikola", "sophia"}, {"stephen", "robot"}, {"sophia", "pilot"}))\n'
'n = f.names()\n',
'RET["code_result"] = (n == {"nikola", "sophia", "robot", "pilot", "stephen"}, str(n))',
'f = Friends(({"nikola", "sophia"}, {"stephen", "robot"}, {"sophia", "pilot"}))\n'
'f.names()',
'{"nikola", "sophia", "robot", "pilot", "stephen"}'),
prepare_test(
'f = Friends(({"nikola", "sophia"}, {"stephen", "robot"}, {"sophia", "pilot"}))\n'
'f.remove({"stephen", "robot"})\n'
'n = f.names()\n',
'RET["code_result"] = (n == {"nikola", "sophia", "pilot"}, str(n))',
'f = Friends(({"nikola", "sophia"}, {"stephen", "robot"}, {"sophia", "pilot"}))\n'
'f.remove({"stephen", "robot"})\n'
'f.names()',
'{"nikola", "sophia", "pilot"}'),
],
"5. Connected": [
prepare_test(
'f = Friends(({"nikola", "sophia"}, {"stephen", "robot"}, {"sophia", "pilot"}))\n'
'n = f.connected("nikola")\n',
'RET["code_result"] = (n == {"sophia"}, str(n))',
'f = Friends(({"nikola", "sophia"}, {"stephen", "robot"}, {"sophia", "pilot"}))\n'
'f.connected("nikola")',
'{"sophia"}'),
prepare_test(
'f = Friends(({"nikola", "sophia"}, {"stephen", "robot"}, {"sophia", "pilot"}))\n'
'n = f.connected("sophia")\n',
'RET["code_result"] = (n == {"nikola", "pilot"}, str(n))',
'f = Friends(({"nikola", "sophia"}, {"stephen", "robot"}, {"sophia", "pilot"}))\n'
'f.connected("sophia")',
'{"nikola", "pilot"}'),
prepare_test(
'f = Friends(({"nikola", "sophia"}, {"stephen", "robot"}, {"sophia", "pilot"}))\n'
'n = f.connected("DDD")\n',
'RET["code_result"] = (n == set(), str(n))',
'f = Friends(({"nikola", "sophia"}, {"stephen", "robot"}, {"sophia", "pilot"}))\n'
'f.connected("DDD")',
'set()'),
prepare_test(
'f = Friends(({"nikola", "sophia"}, {"stephen", "robot"}, {"sophia", "pilot"}))\n'
'f.add({"sophia", "stephen"})\n'
'f.remove({"sophia", "nikola"})\n'
'n = f.connected("sophia")\n',
'RET["code_result"] = (n == {"stephen", "pilot"}, str(n))',
'f = Friends(({"nikola", "sophia"}, {"stephen", "robot"}, {"sophia", "pilot"}))\n'
'f.add({"sophia", "stephen"})\n'
'f.remove({"sophia", "nikola"})\n'
'f.connected("sophia")\n',
'{"stephen", "pilot"}'),
]
# prepare_test(test="str(Building(1, 1, 2, 2))",
# answer="Building(1, 1, 2, 2, 10)", ),
# prepare_test(test="str(Building(0.2, 1, 2, 2.2, 3.5))",
# answer="Building(0.2, 1, 2, 2.2, 3.5)", ),
# ],
# "3. Corners": [
# prepare_test(test="Building(1, 1, 2, 2).corners()",
# answer={"south-west": [1, 1], "north-west": [3, 1], "north-east": [3, 3],
# "south-east": [1, 3]}),
# prepare_test(test="Building(100.5, 0.5, 24.3, 12.2, 3).corners()",
# answer={"north-east": [112.7, 24.8], "north-west": [112.7, 0.5],
# "south-west": [100.5, 0.5], "south-east": [100.5, 24.8]}),
# ],
# "4. Area, Volume": [
# prepare_test(test="Building(1, 1, 2, 2, 100).area()",
# answer=4),
# prepare_test(test="Building(100, 100, 135.5, 2000.1).area()",
# answer=271013.55),
# prepare_test(test="Building(1, 1, 2, 2, 100).volume()",
# answer=400),
# prepare_test(test="Building(100, 100, 135.5, 2000.1).volume()",
# answer=2710135.5),
# ]
}
|
__author__ = 'Sushant'
class ClusterIndices(object):
@staticmethod
def calculate_EI_index(graph, cluster_nodes, standardize=True):
all_edges = graph.get_edges()
external_connections_strength = 0.0
internal_connections_strength = 0.0
internal_nodes = len(cluster_nodes)
external_nodes = len(graph.get_nodes()) - internal_nodes
for node_id in cluster_nodes:
if node_id in all_edges:
for target_id in all_edges[node_id]:
if target_id in cluster_nodes:
#internal edge
internal_connections_strength += float(all_edges[node_id][target_id].strength)
else:
#external edge
external_connections_strength += float(all_edges[node_id][target_id].strength)
if standardize:
if internal_nodes and external_nodes:
internal_connections_strength /= float(internal_nodes)
external_connections_strength /= float(external_nodes)
if (internal_connections_strength + external_connections_strength):
return (external_connections_strength - internal_connections_strength)/(internal_connections_strength + external_connections_strength)
else:
return None |
num = int(input('Enter a number: '))
x = 0
y = 1
# 0 1 1 2 3 5 7
z = x + y
for i in range(num):
print(z)
x = y
y = z
z = x + y
|
# This is an input class. Do not edit.
class BinaryTree:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
# Solution
# O(n) time / O(h) space
# n - number of nodes in the binary tree
# h - height of the binary tree
class TreeInfo:
def __init__(self, isBalanced, height):
self.isBalanced = isBalanced
self.height = height
def heightBalancedBinaryTree(tree):
treeInfo = getTreeInfo(tree)
return treeInfo.isBalanced
def getTreeInfo(node):
if node is None:
return TreeInfo(True, -1)
leftSubtreeInfo = getTreeInfo(node.left)
rightSubtreeInfo = getTreeInfo(node.right)
isBalanced = (
leftSubtreeInfo.isBalanced
and rightSubtreeInfo.isBalanced
and abs(leftSubtreeInfo.height - rightSubtreeInfo.height) <= 1
)
height = max(leftSubtreeInfo.height, rightSubtreeInfo.height) + 1
return TreeInfo(isBalanced, height)
|
'''
33. Search in Rotated Sorted Array Medium
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
'''
class Solution:
def search(self, nums: List[int], target: int) -> int:
l, r = 0, len(nums)-1
while l <= r:
mid = l + (r-l)//2
if nums[mid] == target:
return mid
# Check if pivot applies
if nums[l] <= nums[mid]:
if nums[l] <= target < nums[mid]:
r = mid - 1
else:
l = mid + 1
else:
if nums[mid] < target <= nums[r]:
l = mid + 1
else:
r = mid - 1
return -1
|
load("@wix_oss_infra//:import_external.bzl", import_external = "safe_wix_scala_maven_import_external")
def dependencies():
import_external(
name = "com_fasterxml_jackson_core_jackson_annotations",
artifact = "com.fasterxml.jackson.core:jackson-annotations:2.9.0",
artifact_sha256 = "45d32ac61ef8a744b464c54c2b3414be571016dd46bfc2bec226761cf7ae457a",
srcjar_sha256 = "eb1e62bc83f4d8e1f0660c9cf2f06d6d196eefb20de265cfff96521015d87020",
)
import_external(
name = "com_fasterxml_jackson_core_jackson_core",
artifact = "com.fasterxml.jackson.core:jackson-core:2.9.6",
artifact_sha256 = "fab8746aedd6427788ee390ea04d438ec141bff7eb3476f8bdd5d9110fb2718a",
srcjar_sha256 = "8aff614c41c49fb02ac7444dc1a9518f1f9fc5b7c744ada59825225858a0336d",
)
import_external(
name = "com_fasterxml_jackson_core_jackson_databind",
artifact = "com.fasterxml.jackson.core:jackson-databind:2.9.6",
artifact_sha256 = "657e3e979446d61f88432b9c50f0ccd9c1fe4f1c822d533f5572e4c0d172a125",
srcjar_sha256 = "0f867b675f1f641d06517c2c2232b1fcc21bc6d81a5d09cb8fc6102b13d7e881",
deps = [
"@com_fasterxml_jackson_core_jackson_annotations",
"@com_fasterxml_jackson_core_jackson_core"
],
# EXCLUDES *:mail
# EXCLUDES *:jline
# EXCLUDES *:jms
# EXCLUDES *:jmxri
# EXCLUDES *:jmxtools
# EXCLUDES *:javax
)
|
uni_cars = set()
while True:
command = input()
if command == 'END':
break
else:
direction, plate = command.split(', ')
if direction == 'IN':
uni_cars.add(plate)
elif direction == 'OUT':
if plate in uni_cars:
uni_cars.remove(plate)
if uni_cars:
[print(x) for x in uni_cars]
else:
print('Parking Lot is Empty')
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
spinMultiplicity = 2
opticalIsomers = 1
energy = {
'CCSD(T)-F12/cc-pVTZ-F12': MolproLog('TS8c_f12.out'),
#'CCSD(T)-F12/cc-pVTZ-F12': -382.9338341073141
}
frequencies = GaussianLog('TSfreq.log')
rotors = [HinderedRotor(scanLog=ScanLog('scan_0.log'), pivots=[6,7], top=[7, 16]),
HinderedRotor(scanLog=ScanLog('scan_1.log'), pivots=[2, 3], top=[3,11,12,13], symmetry=3),
HinderedRotor(scanLog=ScanLog('scan_2.log'), pivots=[1, 2], top=[1,8,9,10], symmetry=3),]
|
def arrayMode(sequence):
count = []
answer = 0
for i in range(10):
count.append(0)
for i in range(len(sequence)):
count[sequence[i] - 1] += 1
if count[sequence[i] - 1] > count[answer]:
answer = sequence[i] - 1
return answer+1
|
# encoding=utf-8
_KANA_LOW = ord('ぁ')
_KANA_HIGH = ord('ゖ')
_KANA_DIFF = ord('ア') - ord('あ')
def lower_kana(ch):
code = ord(ch)
if _KANA_LOW <= code <= _KANA_HIGH:
return chr(code + _KANA_DIFF)
return ch
def lower_kanas(u):
return ''.join([lower_kana(ch) for ch in u])
_FULL_WIDTH_LOW = ord('!')
_FULL_WIDTH_HIGH = ord('~')
_FULL_WIDTH_LOWER_DIFF = _FULL_WIDTH_LOW - ord('!')
_FULL_WIDTH_CAPITAL_LOW = ord('A')
_FULL_WIDTH_CAPITAL_HIGH = ord('Z')
_FULL_WIDTH_CAPITAL_DIFF = _FULL_WIDTH_CAPITAL_LOW - ord('a')
def lower_fullwidth(ch):
code = ord(ch)
if _FULL_WIDTH_CAPITAL_LOW <= code <= _FULL_WIDTH_CAPITAL_HIGH:
return chr(code - _FULL_WIDTH_CAPITAL_DIFF)
if _FULL_WIDTH_LOW <= code <= _FULL_WIDTH_HIGH:
return chr(code - _FULL_WIDTH_LOWER_DIFF)
return ch
def lower_fullwidths(u):
return ''.join([lower_fullwidth(ch) for ch in u])
def ulower(u):
return ''.join([lower_kana(lower_fullwidth(ch)) for ch in u]).lower()
|
async def get_params(request):
method = request.method
if method == 'POST':
params = await request.post()
elif method == 'GET':
params = request.rel_url.query
else:
raise ValueError("Unsupported HTTP method: %s" % method)
return params
|
def maybeBuildTrap(x, y):
hero.moveXY(x, y)
if hero.findNearestEnemy():
hero.buildXY("fire-trap", x, y)
while True:
maybeBuildTrap(20, 34)
maybeBuildTrap(38, 20)
maybeBuildTrap(68, 34)
|
def binary_search(array, x, low, high):
while low < high:
mid = low + (high - low)//2
if array[mid] == x:
return mid
elif array[mid] < x:
low = mid + 1
else:
high = mid - 1
return -1
array = [12, 15, 17, 24, 56, 89, 90]
x = 24
result = binary_search(array, x, 0, len(array)-1)
if result != -1:
print("Element found at index", str(result))
else:
print("Element not found in the array")
|
print ("hola word")
nome = input('Nome: ')
sobrenome = input()
email = input ()
print (nome,"\n Sobrenome:",sobrenome,"\n E-mail:",email) |
# coding: utf-8
n = int(input())
d = [int(i) for i in input().split()]
s, t = [int(i) for i in input().split()]
if s > t:
s, t = t, s
circu = sum(d)
len1 = sum(d[s-1:t-1])
len2 = circu-len1
print(min(len1,len2))
|
#makes a smaller dataset for testing
n = 20000
with open("tests/data/combined_data_3.txt", "r") as f:
lines = f.readlines()
print(len(lines))
with open("tests/data/combined_data_3_small.txt", "w") as f:
for i in range(n):
f.write(lines[i])
|
class WorkflowCommand(object):
def __init__(self, command, arguments):
self._command = command
self._arguments = arguments
def encode(self):
return {'command': self._command, 'arguments': self._arguments}
class SkipPhasesUntilCommand(WorkflowCommand):
COMMAND = 'skip_phases_until'
def __init__(self, until_phase):
super(SkipPhasesUntilCommand, self).__init__(self.COMMAND, {'until_phase': until_phase})
|
#TODO move whole class to IBDT.py
MOVEMENT = {'FIXATION':0,
'SACCADE':1,
'PURSUIT':2,
'NOISE':3,
'UNDEF':4
}
class GazeDataEntry():
"""Helper class
IS a data sample with only 4 values: timestamp, eyetracking quality confidence, X and Y coordinates.
"""
def __init__(self, ts:float, confidence:float, x:float, y:float):
#milliseconds!
self.ts = ts
self.confidence = confidence
self.x = x
self.y = y
self.v = 0.0
self.classification = MOVEMENT['UNDEF']
def isFixation(self) -> bool:
"""
:return:
"""
return self.classification == MOVEMENT['FIXATION']
def isSaccade(self) -> bool:
"""
:return:
"""
return self.classification == MOVEMENT['SACCADE']
def isPursuit(self) -> bool:
"""
:return:
"""
return self.classification == MOVEMENT['PURSUIT']
def isNoise(self) -> bool:
"""
:return:
"""
return self.classification == MOVEMENT['NOISE']
def isUndef(self) -> bool:
"""
:return:
"""
return self.classification == MOVEMENT['UNDEF']
def pause(self) -> None:
"""
:return:
"""
#return int(0)
pass #?
|
# # O(n^2) time | O(n) space
# brute force
class MyClass:
def __init__(self, string:str) -> bool:
self.string = string
def isPalindrome(self):
reversedString = ""
for i in reversed(range(len(self.string))):
reversedString += self.string[i] # creating newString -> increases time
return self.string == reversedString
def main():
stringName = MyClass("abcdcba")
print(stringName.isPalindrome())
example2 = MyClass("abcdcb")
print(example2.isPalindrome())
if __name__ == '__main__':
main()
# recursion
# # O(n) time | O(n) space
def isPalindrome(string):
reversedString = []
for i in reversed(range(len(string))):
reversedString.append(string[i]) # adding directly to newString -> imporving
return string == "".join(reversedString)
# # O(n) time | O(n) space
def isPalindrome(string, i = 0):
j = len(string) - 1 - i
return True if i >= j else string[i] == string[j] and isPalindrome(string, i + 1)
# string[i] = firstIdx
# stringp[j] = lastIdx
# recursion always involve extra memory because of tail recursion
# tail recursion -
# # O(1) time | O(n) space
def isPalindrome(string):
leftIdx = 0 # pointer on firstIdx
rightIdx = len(string) - 1 # # pointer on lastIdx
while leftIdx < rightIdx:
if string[leftIdx] != string[rightIdx]:
return False
leftIdx += 1
rightIdx -= 1
return True
|
#1
def RemoveDuplicates(arr: list) -> list:
if len(arr) <= 1:
return arr
else:
i = 1
n = len(arr)
while i < n :
if arr[i] == arr[i-1]:
arr.pop(i)
n -= 1
continue
i += 1
return arr
print(RemoveDuplicates([1,1,1,1,1,1,1,1,1,2,3,4,5,5,5,6,6,7,8]))
|
def potencia(func):
def wrapper(voltaje, resistencia):
intensidad = func(voltaje, resistencia)
potencia = intensidad*voltaje
print(f"La intensidad es {intensidad} A")
print(f"La potencia es {potencia} W")
return wrapper
@potencia
def corriente(voltaje, resistencia):
return voltaje/resistencia
corriente(10, 10) |
Pi1 ='10.0.0.1'
Pi2 ='10.0.0.2'
Pi3 ='10.0.0.3'
Pi4 ='10.0.0.4'
Pi5 ='10.0.0.5'
Pi6 ='10.0.0.6'
GW1 ='10.0.0.8'
GW2 ='10.0.0.9'
R1=[GW1,Pi1]
R2=[GW1,Pi4]
R3=[Pi1,Pi4]
R4=[Pi1,Pi2]
R5=[Pi4,Pi5]
R6=[Pi2,Pi5]
R7=[Pi3,Pi2]
R8=[Pi6,Pi5]
R9=[Pi3,Pi6]
R10=[GW2,Pi3]
R11=[GW2,Pi6]
N = 10
S1=[R1]
S2=[R2]
S3=[R3,R9]
S4=[R4]
S5=[R5]
S6=[R6]
S7=[R7]
S8=[R8]
S9=[R10]
S10=[R11]
S=[S1,S2,S3,S4,S5,S6,S7,S8,S9,S10]
name1=["R1"]
name2=["R2"]
name3=["R3","R9"]
name4=["R4"]
name5=["R5"]
name6=["R6"]
name7=["R7"]
name8=["R8"]
name9=["R10"]
name10=["R11"]
Name=[name1,name2,name3,name4,name5,name6,name7,name8,name9,name10]
|
BASE_ENS = 'https://www2.agenciatributaria.gob.es/ADUA/internet/es/aeat/dit/adu/aden/'
ADUANET_SERVICES = {
'ens_fork': {
'verbose_name': 'Servicio Solicitud Desvío ENS V5.0',
'wsdl': f'{BASE_ENS}enswsv5/IE323V5.wsdl',
'operation': 'IE323V5',
'port_production': 'IE323V5',
'port_test': 'IE323V5Pruebas',
'service': 'IE323V5Service',
'signed': True,
},
'ens_modification': {
'verbose_name': 'Servicio Modificación ENS V5.0',
'wsdl': f'{BASE_ENS}enswsv5/IE313V5.wsdl',
'operation': 'IE313V5',
'port_production': 'IE313V5',
'port_test': 'IE313V5Pruebas',
'service': 'IE313V5Service',
'signed': True,
},
'ens_presentation': {
'verbose_name': 'Servicio de Presentación ENS V5.0',
'wsdl': f'{BASE_ENS}enswsv5/IE315V5.wsdl',
'operation': 'IE315V5',
'port_production': 'IE315V5',
'port_test': 'IE315V5Pruebas',
'service': 'IE315V5Service',
'signed': True,
},
'exs_common': {
'verbose_name': "Servicio de envío de EXIT Sumary (EXS) v2",
'wsdl': 'https://www2.agenciatributaria.gob.es/ADUA/internet/es/aeat/dit/adu/adrx/ws/IE615V2.wsdl', # NOQA
'operation': 'IE615V2',
'port_production': 'IE615V2',
'port_test': 'IE615V2Pruebas',
'service': 'IE615V2Service',
'signed': True,
},
}
|
def read_data():
with open ('input.txt') as f:
data = f.readlines()
return [d.strip() for d in data]
def write_data(data):
with open('output.txt','w') as f:
for d in data:
f.write(str(d)+'\n')
# the magic function that makes it all work.
# wow, it took forever to get this right.
def recursive_construct(L):
poss = []
if len(L)==1:
for ell in L:
poss.extend(ell)
elif len(L)==2:
for ell in L[0]:
for emm in L[1]:
poss.append(ell+emm)
else:
for ell in L[0]:
for emm in recursive_construct(L[1:]):
poss.append(ell+emm)
return poss
class Seq(object):
"""docstring for Seq"""
def __init__(self, text):
super(Seq, self).__init__()
# print(f'making Seq from {text}')
to_list = lambda x: [int(t) for t in x.split()]
self.sequence = to_list(text)
def __str__(self):
return f'Seq: {self.sequence}'
def __repr__(self):
return str(self)
def construct(self, graph):
poss = [graph[t].construct(graph) for t in self.sequence]
return recursive_construct(poss)
class Option(object):
"""docstring for Rule"""
def __init__(self, text):
super(Option, self).__init__()
# print(f'making Option from {text}')
self.options = [Seq(t) for t in text.split('|')]
def __str__(self):
return f'Option: {self.options}'
def __repr__(self):
return str(self)
# always returns a list
def construct(self, graph):
opts = [op.construct(graph) for op in self.options]
# print(f'opts {self} {opts}')
poss = []
for opt in opts:
poss.extend(opt)
return poss
class Symbol(object):
"""docstring for Symbol"""
def __init__(self, text):
super(Symbol, self).__init__()
# print(f'making Symbol from {text}')
self.symbol = text.strip().strip('"')
# always returns a string
def construct(self, graph):
return [self.symbol]
def __str__(self):
return f'Symbol: {self.symbol}'
def __repr__(self):
return str(self)
def construct_graph(rules):
graph = {}
for r in rules:
loc, val = r.split(':')
loc = int(loc)
if '"' in val:
graph[loc] = Symbol(val)
elif "|" in val:
graph[loc] = Option(val)
else:
graph[loc] = Seq(val)
return graph
def is_matching_word(graph):
return graph[0].construct(graph)
###
def get_rules(data):
rules = []
ii=0
while data[0]:
rules.append(data.pop(0))
data.pop(0) # nuke the leading empty line
return rules
def get_words(data):
return data
def part1():
data = read_data()
rules = get_rules(data)
words = get_words(data)
graph = construct_graph(rules)
strings = graph[0].construct(graph)
# print(graph)
# print('strings',)
c = 0
for w in words:
if w in strings:
c = c+1
return c
###
def part2():
data = read_data()
thing = []
for a in thing:
pass
return
print("part 1: {}".format(part1()))
# print("part 2: {}".format(part2()))
|
def should_discard_line(l):
patterns = ['${PROJECT_NAME}_tests', '${PROJECT_NAME}_cli', '${PROJECT_NAME}_shared', 'CONFIGURATION_DUMMY']
for p in patterns:
if p in l:
return True
return False
f = open('botan/CMakeLists.txt', 'r')
content = f.read()
f.close()
f = open('botan/CMakeLists.txt', 'w')
for l in content.split('\n'):
if not should_discard_line(l):
f.write(l + '\n')
f.close()
|
"""Stores some global constants, mostly to save on a lot of repetitive arguments.
These are mostly of interest for demonstrating different variants of the algorithms as discussed
in the accompanying article."""
# Both marching cube and dual contouring are adaptive, i.e. they select
# the vertex that best describes the underlying function. But for illustrative purposes
# you can turn this off, and simply select the midpoint vertex.
ADAPTIVE = True
# In dual contouring, if true, crudely force the selected vertex to belong in the cell
CLIP = False
# In dual contouring, if true, apply boundaries to the minimization process finding the vertex for each cell
BOUNDARY = True
# In dual contouring, if true, apply extra penalties to encourage the vertex to stay within the cell
BIAS = True
# Strength of the above bias, relative to 1.0 strength for the input gradients
BIAS_STRENGTH = 0.01
# Default bounds to evaluate over
XMIN = -3
XMAX = 3
YMIN = -3
YMAX = 3
ZMIN = -3
ZMAX = 3
|
class phase_cavity_sys:
def __init__(self):
"""Creating all the variables that are common to all phase cavities"""
self.Prog_name = []
self.Cav_Set = [] # Number of pairs of pcavs really two caviy makes up one system
self.Cav_Num = [] # Number of cavities
self.Cav_RF_Freq = [] # Cavity RF frequency
self.Cav_LO_Freq = [] # Electronic LO freq
self.Cav_IF_Freq = [] # Dowmixed IF freq
self.Cav_REF_Freq = [] # VCO frequency for pcav to munipulate
self.Cav_PV_BeamQ_Rb = []
self.Cav_PV_Q_Max = []
self.Cav_PV_BeamQ_setpoint = []
self.Cav_PV_Watchdog = []
self.Cav_PV_Beamf = []
self.Cav_PV_Humidity = []
self.Calc_Fbck_Rate = [] # Feeback rate
self.Calc_Fbck_VCO_Gain = [] # rad in VCO freq per pico second
self.Calc_Fbck_Maxstep = []
self.Calc_Fbck_Q_Thres = []
self.Calc_Fbck_ADC_Thres = []
self.Calc_PV_Time_Ctrl = [] # time control (?) (ps)
self.Calc_PV_DAC_Scale = [] # DAC I/Q scale (V)
self.Calc_PV_Phi_jump_max = [] # limit for RF resync (ps)
self.Calc_PV_Phi_diff = [] # rms(cav1 - cav2)
self.Calc_PV_out_diffs = []
self.Calc_PV_Amp_max = []
self.Calc_Wav_Length = []
self.Calc_Filter_Poles = []
self.Calc_Filter_w = []
self.Calc_Filter_Type = []
self.Calc_Filter_Num = []
self.Calc_Filter_Den = []
self.Calc_Wav_Bckgrnd = []
self.Calc_Wav_Time_Step = []
self.Calc_Wav_Time = []
self.Calc_IF_Sin = []
self.Calc_IF_Cos = []
self.Ele_PV_Resync = []
self.Ele_PV_Ctrl_Time_Q= [] # Pphase shifter #2 I & Q
self.Ele_PV_Ctrl_Time_I= []
self.EVR_Trig_Delay = []
self.EVR_Trig_Ena = []
self.EVR_Trig_Eventcode = []
self.EVR_Trig_Eventcode_Ena = []
self.EVR_PV_Trig_Ena = []
self.EVR_PV_Trig_Eventcode = []
self.EVR_PV_Trig_Eventcode_Ena = []
self.EVR_PV_Status = []
self.EVR_PV_Trig_Delay = []
self.ADC_Chan = [] # Number of ADC channels
self.ADC_Points = [] # ADC waveform points
self.ADC_Clk = [] # ADC clock sampling frequency
self.ADC_PV_Waveform = []
self.ADC_PV_Trig = []
self.ADC_PV_Arm = []
self.ADC_PV_Clk_Sel = []
|
class Solution:
# @param {integer} numRows
# @return {integer[][]}
def generate(self, numRows):
res = []
row = []
for i in range(0,numRows):
n = len(row)
row =[1]+[row[j-1] + (row[j] if j<n else 0) for j in range(1,n+1)]
res.append(row)
return res
|
def main(x):
max_test = 2000
is_negative = False
if (x < 0):
is_negative = True
x = abs(x)
x = round(x, 16)
test = int(x - 1)
for i in range (test, max_test):
for j in range (1, max_test):
if (x == i/j):
if is_negative:
print('-', end='')
print(str(i)+'/' + str(j))
return
print("no solution found with max_test = " + str(max_test))
|
#!/home/jepoy/anaconda3/bin/python
def main():
f = open('lines.txt', 'r') # 'w' write - rewrites over the file # a append add to the end of the file
for line in f:
print(line.rstrip())
f.close()
if __name__ == '__main__':
main() |
class TrackingFieldsMixin:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._old_fields = {}
self._set_old_fields()
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
result = super().save(force_insert, force_update, using, update_fields)
self._set_old_fields()
return result
def _set_old_fields(self):
for field in self._meta.fields:
attname, column = field.get_attname_column()
self._old_fields[attname] = getattr(self, attname)
def get_old_fields(self):
return self._old_fields
# Returns the fields name that have been modified since they are loaded or saved most recently.
def get_dirty_fields(self):
dirty_fields = []
for field in self._old_fields:
if self._old_fields[field] != getattr(self, field):
dirty_fields.append(field)
return dirty_fields
def get_old_field(self, field, default=None):
if field in self._old_fields:
return self._old_fields[field]
return default
def set_old_field(self, field, value):
self._old_fields[field] = value
|
_PAD = "_PAD"
_GO = "_GO"
_EOS = "_EOS"
_UNK = "_UNK"
_START_VOCAB = [_PAD, _GO, _EOS, _UNK]
PAD_ID = 0
GO_ID = 1
EOS_ID = 2
UNK_ID = 3
OP_DICT_IDS = [PAD_ID, GO_ID, EOS_ID, UNK_ID] |
"""Subcommand won't stop complaining about jupyterlab-git."""
# Configuration file for jupyter serverextension.
# ------------------------------------------------------------------------------
# Application(SingletonConfigurable) configuration
# ------------------------------------------------------------------------------
# This is an application.
# The date format used by logging formatters for %(asctime)s
# c.Application.log_datefmt = '%Y-%m-%d %H:%M:%S'
# The Logging format template
# c.Application.log_format = '[%(name)s]%(highlevel)s %(message)s'
# Set the log level by value or name.
# c.Application.log_level = 30
# ------------------------------------------------------------------------------
# JupyterApp(Application) configuration
# ------------------------------------------------------------------------------
# Base class for Jupyter applications
# Answer yes to any prompts.
# c.JupyterApp.answer_yes = False
# Full path of a config file.
# c.JupyterApp.config_file = ''
# Specify a config file to load.
# c.JupyterApp.config_file_name = ''
# Generate default config file.
# c.JupyterApp.generate_config = False
# ------------------------------------------------------------------------------
# BaseExtensionApp(JupyterApp) configuration
# ------------------------------------------------------------------------------
# Base nbextension installer app
# Install from a Python package
# c.BaseExtensionApp.python = False
# Use the sys.prefix as the prefix
# c.BaseExtensionApp.sys_prefix = False
# Whether to do a user install
# c.BaseExtensionApp.user = False
# DEPRECATED: Verbosity level
# c.BaseExtensionApp.verbose = None
# ------------------------------------------------------------------------------
# ServerExtensionApp(BaseExtensionApp) configuration
# ------------------------------------------------------------------------------
# Root level server extension app
|
fp = open('greetings.txt','w')
fp.write("Hello, World!\n")
fp.close()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.