content
stringlengths 7
1.05M
|
---|
# -*- coding: utf-8 -*-
"""
Exceptions for Arequests
Created on Tue Nov 13 08:34:14 2018
@author: gfi
"""
class ArequestsError(Exception):
"""Basic exception for errors raised by Arequests"""
pass
class AuthorizationError(ArequestsError):
'''401 error new authentification required'''
pass
class SomeClientError(ArequestsError):
'''4xx client error'''
pass
class SomeServerError(ArequestsError):
'''5xx server error'''
pass
|
def transform_file(infile,outfile,templates):
with open(infile,'r') as fh:
indata = fh.read()
lines = indata.split('\n')
outlines = []
for line in lines:
if '//ATL_BEGIN' in line:
start = line.find('//ATL_BEGIN')
spacing = line[:start]
start = line.find('<') + 1
end = line.find('>')
tkey = line[start:end]
ttxt = templates[tkey]
for tl in ttxt:
outlines.append(spacing + tl)
else:
outlines.append(line)
with open(outfile,'w') as fh:
for line in outlines:
fh.write(line+'\n') |
#!/usr/bin/env python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ************************************************************************************
# YOU NEED TO MODIFY THE FOLLOWING METADATA TO ADAPT THE TRAINER TEMPLATE TO YOUR DATA
# ************************************************************************************
# Task type can be either 'classification', 'regression', or 'custom'
# This is based on the target feature in the dataset, and whether you use a canned or a custom estimator
TASK_TYPE = '' # classification | regression | custom
# A List of all the columns (header) present in the input data file(s) in order to parse it.
# Note that, not all the columns present here will be input features to your model.
HEADER = []
# List of the default values of all the columns present in the input data.
# This helps decoding the data types of the columns.
HEADER_DEFAULTS = []
# List of the feature names of type int or float.
INPUT_NUMERIC_FEATURE_NAMES = []
# Numeric features constructed, if any, in process_features function in input.py module,
# as part of reading data.
CONSTRUCTED_NUMERIC_FEATURE_NAMES = []
# Dictionary of feature names with int values, but to be treated as categorical features.
# In the dictionary, the key is the feature name, and the value is the num_buckets (count of distinct values).
INPUT_CATEGORICAL_FEATURE_NAMES_WITH_IDENTITY = {}
# Categorical features with identity constructed, if any, in process_features function in input.py module,
# as part of reading data. Usually include constructed boolean flags.
CONSTRUCTED_CATEGORICAL_FEATURE_NAMES_WITH_IDENTITY = {}
# Dictionary of categorical features with few nominal values (to be encoded as one-hot indicators).
# In the dictionary, the key is the feature name, and the value is the list of feature vocabulary.
INPUT_CATEGORICAL_FEATURE_NAMES_WITH_VOCABULARY = {}
# Dictionary of categorical features with many values (sparse features).
# In the dictionary, the key is the feature name, and the value is the bucket size.
INPUT_CATEGORICAL_FEATURE_NAMES_WITH_HASH_BUCKET = {}
# List of all the categorical feature names.
# This is programmatically created based on the previous inputs.
INPUT_CATEGORICAL_FEATURE_NAMES = list(INPUT_CATEGORICAL_FEATURE_NAMES_WITH_IDENTITY.keys()) \
+ list(INPUT_CATEGORICAL_FEATURE_NAMES_WITH_VOCABULARY.keys()) \
+ list(INPUT_CATEGORICAL_FEATURE_NAMES_WITH_HASH_BUCKET.keys())
# List of all the input feature names to be used in the model.
# This is programmatically created based on the previous inputs.
INPUT_FEATURE_NAMES = INPUT_NUMERIC_FEATURE_NAMES + INPUT_CATEGORICAL_FEATURE_NAMES
# Column includes the relative weight of each record.
WEIGHT_COLUMN_NAME = None
# Target feature name (response or class variable).
TARGET_NAME = ''
# List of the class values (labels) in a classification dataset.
TARGET_LABELS = []
# List of the columns expected during serving (which is probably different to the header of the training data).
SERVING_COLUMNS = []
# List of the default values of all the columns of the serving data.
# This helps decoding the data types of the columns.
SERVING_DEFAULTS = []
|
#
#
# This is Support for Drawing Bullet Charts
#
#
#
#
#
#
#
'''
This is the return json value to the javascript front end
{ "canvasName":"canvas1","featuredColor":"Green", "featuredMeasure":14.5,
"qualScale1":14.5, "qualScale1Color":"Black","titleText":"Step 1" },
{ "canvasName":"canvas2","featuredColor":"Blue", "featuredMeasure":14.5,
"qualScale1":14.5, "qualScale1Color":"Black","titleText":"Step 2" },
{ "canvasName":"canvas3","featuredColor":"Red", "featuredMeasure":14.5,
"qualScale1":14.5, "qualScale1Color":"Black","titleText":"Step 3" },
'''
class template_support():
def __init__(self , redis_handle, statistics_module):
self.redis_handle = redis_handle
self.statistics_module = statistics_module
def generate_current_canvas_list( self, schedule_name, *args, **kwargs ):
return_value = []
self.schedule_name = schedule_name
data = self.statistics_module.schedule_data[ schedule_name ]
current_data = self.statistics_module.get_current_data( data["step_number"],schedule_name )
limit_values = self.statistics_module.get_current_limit_values( data["step_number"],schedule_name )
for i in range(0,data["step_number"]):
temp = {}
temp["canvasName"] = "canvas1" +str(i+1)
temp["titleText"] = "Step " +str(i+1)
temp["qualScale1Color"] = "Black"
temp["featuredColor"] = "Red"
temp["qualScale1"] = limit_values[i]['limit_avg']
temp["featuredMeasure"] = current_data[i]
temp["limit"] = limit_values[i]['limit_std']
temp["step"] = i
return_value.append(temp)
return return_value
def generate_canvas_list(self, schedule_name, flow_id , *args,**kwargs):
return_value = []
self.schedule_name = schedule_name
data = self.statistics_module.schedule_data[ schedule_name ]
flow_sensors = self.statistics_module.sensor_names
flow_sensor_name = flow_sensors[flow_id]
conversion_rate = self.statistics_module.conversion_rate[flow_id]
flow_data = self.statistics_module.get_average_flow_data( data["step_number"], flow_sensor_name, schedule_name )
limit_values = self.statistics_module.get_flow_limit_values( data["step_number"], flow_sensor_name, schedule_name )
for i in limit_values:
try:
i['limit_avg'] = float(i['limit_avg'])*conversion_rate
i['limit_std'] = float(i['limit_std'])*conversion_rate
except:
pass
corrected_flow = []
for i in flow_data:
temp1 = []
for j in i:
temp1.append( j *conversion_rate)
corrected_flow.append(temp1)
for i in range(0,data["step_number"]):
temp = {}
temp["canvasName"] = "canvas1" +str(i+1)
temp["titleText"] = "Step " +str(i+1)
temp["qualScale1Color"] = "Black"
temp["featuredColor"] = "Red"
try:
temp["qualScale1"] = limit_values[i]['limit_avg']
except:
temp["qualScale1"] = 0
try:
temp["featuredMeasure"] = corrected_flow[i]
except:
temp["featuredMeasure"] = 0
try:
temp["limit"] = limit_values[i]['limit_std']
except:
temp["limit"] = 0
return_value.append(temp)
return return_value
|
declerations_test_text_001 = '''
list1 = [
1,
]
'''
declerations_test_text_002 = '''
list1 = [
1,
2,
]
'''
declerations_test_text_003 = '''
tuple1 = (
1,
)
'''
declerations_test_text_004 = '''
tuple1 = (
1,
2,
)
'''
declerations_test_text_005 = '''
set1 = {
1,
}
'''
declerations_test_text_006 = '''
set1 = {
1,
2,
}
'''
declerations_test_text_007 = '''
dict1 = {
'key': 1,
}
'''
declerations_test_text_008 = '''
dict1 = {
'key1': 1,
'key2': 2,
}
'''
declerations_test_text_009 = '''
return [
1,
]
'''
declerations_test_text_010 = '''
return [
1,
2,
]
'''
declerations_test_text_011 = '''
return (
1,
)
'''
declerations_test_text_012 = '''
return (
1,
2,
)
'''
declerations_test_text_013 = '''
return {
1,
}
'''
declerations_test_text_014 = '''
return {
1,
2,
}
'''
declerations_test_text_015 = '''
return {
'key': 1,
}
'''
declerations_test_text_016 = '''
return {
'key1': 1,
'key2': 2,
}
'''
declerations_test_text_017 = '''
yield [
1,
]
'''
declerations_test_text_018 = '''
yield [
1,
2,
]
'''
declerations_test_text_019 = '''
yield (
1,
)
'''
declerations_test_text_020 = '''
yield (
1,
2,
)
'''
declerations_test_text_021 = '''
yield {
1,
}
'''
declerations_test_text_022 = '''
yield {
1,
2,
}
'''
declerations_test_text_023 = '''
yield {
'key': 1,
}
'''
declerations_test_text_024 = '''
yield {
'key1': 1,
'key2': 2,
}
'''
declerations_test_text_025 = '''
list1 = [
[
1,
],
]
'''
declerations_test_text_026 = '''
list1 = [
[
1,
2,
],
]
'''
declerations_test_text_027 = '''
tuple1 = (
(
1,
),
)
'''
declerations_test_text_028 = '''
tuple1 = (
(
1,
2,
),
)
'''
declerations_test_text_029 = '''
set1 = {
{
1,
},
}
'''
declerations_test_text_030 = '''
set1 = {
{
1,
2,
},
}
'''
declerations_test_text_031 = '''
dict1 = {
'key': {
'key': 1,
},
}
'''
declerations_test_text_032 = '''
dict1 = {
'key1': {
'key1': 1,
'key2': 2,
},
'key2': {
'key1': 1,
'key2': 2,
},
}
'''
declerations_test_text_033 = '''
return [
[
1,
],
]
'''
declerations_test_text_034 = '''
return [
[
1,
2,
],
]
'''
declerations_test_text_035 = '''
return (
(
1,
),
)
'''
declerations_test_text_036 = '''
return (
(
1,
2,
),
)
'''
declerations_test_text_037 = '''
return {
{
1,
},
}
'''
declerations_test_text_038 = '''
return {
{
1,
2,
},
}
'''
declerations_test_text_039 = '''
return {
'key': {
'key': 1,
},
}
'''
declerations_test_text_040 = '''
return {
'key1': {
'key1': 1,
'key2': 2,
},
'key2': {
'key1': 1,
'key2': 2,
},
}
'''
declerations_test_text_041 = '''
yield [
[
1,
],
]
'''
declerations_test_text_042 = '''
yield [
[
1,
2,
],
]
'''
declerations_test_text_043 = '''
yield (
(
1,
),
)
'''
declerations_test_text_044 = '''
yield (
(
1,
2,
),
)
'''
declerations_test_text_045 = '''
yield {
{
1,
},
}
'''
declerations_test_text_046 = '''
yield {
{
1,
2,
},
}
'''
declerations_test_text_047 = '''
yield {
'key': {
'key': 1,
},
}
'''
declerations_test_text_048 = '''
yield {
'key1': {
'key1': 1,
'key2': 2,
},
'key2': {
'key1': 1,
'key2': 2,
},
}
'''
declerations_test_text_049 = '''
list1 = [
[
2,
],
]
'''
declerations_test_text_050 = '''
list_1 = [
[
[
2,
],
],
]
'''
declerations_test_text_051 = '''
list_1 = [
(
2,
),
]
'''
declerations_test_text_052 = '''
list_1 = [
{
'key1': 'value1',
},
]
'''
declerations_test_text_053 = '''
list_1 = [
call(
param1,
),
]
'''
declerations_test_text_054 = '''
entry_1, entry_2 = call()
'''
declerations_test_text_055 = '''
(
entry_1,
entry_2,
) = call()
'''
declerations_test_text_056 = '''
[
1
for a, b in call()
]
'''
declerations_test_text_057 = '''
{
'key': [
'entry_1',
'entry_2',
]
}
'''
declerations_test_text_058 = '''
list_1 = [instance.attribute]
'''
declerations_test_text_059 = '''
list_1 = [1]
'''
declerations_test_text_060 = '''
list_1 = [test]
'''
declerations_test_text_061 = '''
dict_1 = {}
'''
declerations_test_text_062 = '''
list_1 = [term[1]]
'''
declerations_test_text_063 = '''
test = {
'list_of_lists': [
[],
],
}
'''
declerations_test_text_064 = '''
class ClassName:
pass
'''
declerations_test_text_065 = '''
class ClassName(
Class1,
Class2,
):
pass
'''
declerations_test_text_066 = '''
class ClassName():
pass
'''
declerations_test_text_067 = '''
class ClassName(Class1, Class2):
pass
'''
declerations_test_text_068 = '''
class ClassName(
Class1,
Class2
):
pass
'''
declerations_test_text_069 = '''
def function_name():
pass
'''
declerations_test_text_070 = '''
def function_name( ):
pass
'''
declerations_test_text_071 = '''
def function_name(
):
pass
'''
declerations_test_text_072 = '''
def function_name(
):
pass
'''
declerations_test_text_073 = '''
def function_name(
arg1,
arg2,
):
pass
'''
declerations_test_text_074 = '''
def function_name(
arg1,
arg2
):
pass
'''
declerations_test_text_075 = '''
def function_name(arg1):
pass
'''
declerations_test_text_076 = '''
def function_name(
arg1, arg2,
):
pass
'''
declerations_test_text_077 = '''
def function_name(
arg1,
arg2,
):
pass
'''
declerations_test_text_078 = '''
def function_name(
arg1,
**kwargs
):
pass
'''
declerations_test_text_079 = '''
class Class:
def function_name_two(
self,
arg1,
arg2,
):
pass
'''
declerations_test_text_080 = '''
class Class:
@property
def function_name_one(
self,
):
pass
'''
declerations_test_text_081 = '''
def function_name(
*args,
**kwargs
):
pass
'''
declerations_test_text_082 = '''
class A:
def b():
class B:
pass
'''
declerations_test_text_083 = '''
@decorator(
param=1,
)
def function_name(
param_one,
param_two,
):
pass
'''
declerations_test_text_084 = '''
class ClassA:
def function_a():
pass
class TestServerHandler(
http.server.BaseHTTPRequestHandler,
):
pass
'''
declerations_test_text_085 = '''
def function(
param_a,
param_b=[
'test',
],
):
pass
'''
declerations_test_text_086 = '''
@decorator
class DecoratedClass(
ClassBase,
):
pass
'''
declerations_test_text_087 = '''
class ClassName(
object,
):
pass
'''
declerations_test_text_088 = '''
pixel[x,y] = 10
'''
declerations_test_text_089 = '''
@decorator.one
@decorator.two()
class DecoratedClass:
pass
'''
declerations_test_text_090 = '''
@staticmethod
def static_method():
pass
'''
declerations_test_text_091 = '''
@decorator1
@decorator2
def static_method(
param1,
param2,
):
pass
'''
declerations_test_text_092 = '''
@decorator1(
param=1,
)
def method():
pass
'''
declerations_test_text_093 = '''
try:
pass
except Exception:
pass
'''
declerations_test_text_094 = '''
try:
pass
except (
Exception1,
Exception2,
):
pass
'''
declerations_test_text_095 = '''
try:
pass
except Exception as exception:
pass
'''
declerations_test_text_096 = '''
try:
pass
except (
Exception1,
Exception2,
) as exception:
pass
'''
declerations_test_text_097 = '''
try:
pass
except Exception as e:
pass
'''
declerations_test_text_098 = '''
try:
pass
except (
Exception1,
Exception2,
) as e:
pass
'''
declerations_test_text_099 = '''
dict1 = {
'key_one': 1, 'key_two': 2,
}
'''
declerations_test_text_100 = '''
dict1 = {
'key_one': 1,
'key_two': 2,
}
'''
declerations_test_text_101 = '''
dict1 = {
'key_one': 1,
'key_two': 2,
}
'''
declerations_test_text_102 = '''
dict1 = {
'key_one':
1,
}
'''
declerations_test_text_103 = '''
dict_one = {
'list_comp': [
{
'key_one': 'value',
}
for i in range(5)
],
'dict_comp': {
'key_one': i
for i in range(5)
},
'set_comp': {
i
for i in range(5)
},
'generator_comp': (
i
for i in range(5)
),
}
'''
declerations_test_text_104 = '''
dict_one = {
'text_key': 'value',
f'formatted_text_key': 'value',
name_key: 'value',
1: 'value',
dictionary['name']: 'value',
object.attribute: 'value',
}
dict_two = {
'key_text_multiline': \'\'\'
text
\'\'\',
1: 'text',
function(
param=1,
): 'text',
'text'.format(
param=1,
): 'text',
'long_text': (
'first line'
'second line'
),
**other_dict,
}
'''
declerations_test_text_105 = '''
async def function(
param1,
):
pass
'''
declerations_test_text_106 = '''
def no_args_function():
pass
def no_args_function() :
pass
def no_args_function ():
pass
def no_args_function( ):
pass
def no_args_function():
pass
def no_args_function() -> None:
pass
def no_args_function() -> None :
pass
def no_args_function () -> None:
pass
def no_args_function( ) -> None:
pass
def no_args_function() -> None:
pass
'''
declerations_test_text_107 = '''
class Class:
@decorator(
param=1,
)
async def function():
pass
'''
declerations_test_text_108 = '''
list_a = [
\'\'\'
multiline
string
\'\'\',
\'\'\'
multiline
string
\'\'\',
]
'''
declerations_test_text_109 = '''
list_with_empty_tuple = [
(),
]
'''
|
# 지수부 표현
a = 1e9
print(a) # 1000000000.0
a = 7.525e2
print(a) # 752.5
a = 3954e-3
print(a) # 3.954
|
"""
用户身份验证
Version: 0.1
Author: cjp
"""
username = input('请输入用户名: ')
password = input('请输入口令: ')
# 用户名是admin且密码是123456则身份验证成功否则身份验证失败
if username == 'admin' and password == '123456':
print('身份验证成功!')
else:
print('身份验证失败!')
"""
Python中没有用花括号来构造代码块而是使用了缩进的方式来设置代码的层次结构,
如果if条件成立的情况下需要执行多条语句,只要保持多条语句具有相同的缩进就可以了,
换句话说连续的代码如果又保持了相同的缩进那么它们属于同一个代码块,相当于是一个执行的整体。
"""
# 当然如果要构造出更多的分支,可以使用if…elif…else…结构,例如下面的分段函数求值。
"""
分段函数求值
3x - 5 (x > 1)
f(x) = x + 2 (-1 <= x <= 1)
5x + 3 (x < -1)
Version: 0.1
Author: cjp
"""
x = float(input('x = '))
if x > 1:
y = 3 * x - 5
elif x >= -1:
y = x + 2
else:
y = 5 * x + 3
print('f(%.2f) = %.2f' % (x, y))
"""
同理elif和else中也可以再构造新的分支,我们称之为嵌套的分支结构
"""
"""
分段函数求值
3x - 5 (x > 1)
f(x) = x + 2 (-1 <= x <= 1)
5x + 3 (x < -1)
Version: 0.1
Author: cjp
"""
x = float(input('x = '))
if x > 1:
y = 3 * x - 5
else:
if x >= -1:
y = x+2
else:
y = 5 * x + 3
print('f(%.2f) = %.2f' % (x, y))
"""
大家可以自己感受一下这两种写法到底是哪一种更好。
在之前我们提到的Python之禅中有这么一句话“Flat is better than nested.”,
之所以提倡代码“扁平化”是因为嵌套结构的嵌套层次多了之后会严重的影响代码的可读性
,所以能使用扁平化的结构时就不要使用嵌套。
""" |
"""Build rules to create C++ code from an Antlr4 grammar."""
def antlr4_cc_lexer(name, src, namespaces = None, imports = None, deps = None, lib_import = None):
"""Generates the C++ source corresponding to an antlr4 lexer definition.
Args:
name: The name of the package to use for the cc_library.
src: The antlr4 g4 file containing the lexer rules.
namespaces: The namespace used by the generated files. Uses an array to
support nested namespaces. Defaults to [name].
imports: A list of antlr4 source imports to use when building the lexer.
deps: Dependencies for the generated code.
lib_import: Optional target for importing grammar and token files.
"""
namespaces = namespaces or [name]
imports = imports or []
deps = deps or []
if not src.endswith(".g4"):
fail("Grammar must end with .g4", "src")
if (any([not imp.endswith(".g4") for imp in imports])):
fail("Imported files must be Antlr4 grammar ending with .g4", "imports")
file_prefix = src[:-3]
base_file_prefix = _strip_end(file_prefix, "Lexer")
out_files = [
"%sLexer.h" % base_file_prefix,
"%sLexer.cpp" % base_file_prefix,
]
native.java_binary(
name = "antlr_tool",
jvm_flags = ["-Xmx256m"],
main_class = "org.antlr.v4.Tool",
runtime_deps = ["@maven//:org_antlr_antlr4_4_7_1"],
)
command = ";\n".join([
# Use the first namespace, we'll add the others afterwards.
_make_tool_invocation_command(namespaces[0], lib_import),
_make_namespace_adjustment_command(namespaces, out_files),
])
native.genrule(
name = name + "_source",
srcs = [src] + imports,
outs = out_files,
cmd = command,
heuristic_label_expansion = 0,
tools = ["antlr_tool"],
)
native.cc_library(
name = name,
srcs = [f for f in out_files if f.endswith(".cpp")],
hdrs = [f for f in out_files if f.endswith(".h")],
deps = ["@antlr_cc_runtime//:antlr4_runtime"] + deps,
copts = [
"-fexceptions",
],
features = ["-use_header_modules"], # Incompatible with -fexceptions.
)
def antlr4_cc_parser(
name,
src,
namespaces = None,
token_vocab = None,
imports = None,
listener = True,
visitor = False,
deps = None,
lib_import = None):
"""Generates the C++ source corresponding to an antlr4 parser definition.
Args:
name: The name of the package to use for the cc_library.
src: The antlr4 g4 file containing the parser rules.
namespaces: The namespace used by the generated files. Uses an array to
support nested namespaces. Defaults to [name].
token_vocab: The antlr g4 file containing the lexer tokens.
imports: A list of antlr4 source imports to use when building the parser.
listener: Whether or not to include listener generated files.
visitor: Whether or not to include visitor generated files.
deps: Dependencies for the generated code.
lib_import: Optional target for importing grammar and token files.
"""
suffixes = ()
if listener:
suffixes += (
"%sBaseListener.cpp",
"%sListener.cpp",
"%sBaseListener.h",
"%sListener.h",
)
if visitor:
suffixes += (
"%sBaseVisitor.cpp",
"%sVisitor.cpp",
"%sBaseVisitor.h",
"%sVisitor.h",
)
namespaces = namespaces or [name]
imports = imports or []
deps = deps or []
if not src.endswith(".g4"):
fail("Grammar must end with .g4", "src")
if token_vocab != None and not token_vocab.endswith(".g4"):
fail("Token Vocabulary must end with .g4", "token_vocab")
if (any([not imp.endswith(".g4") for imp in imports])):
fail("Imported files must be Antlr4 grammar ending with .g4", "imports")
file_prefix = src[:-3]
base_file_prefix = _strip_end(file_prefix, "Parser")
out_files = [
"%sParser.h" % base_file_prefix,
"%sParser.cpp" % base_file_prefix,
] + _make_outs(file_prefix, suffixes)
if token_vocab:
imports.append(token_vocab)
command = ";\n".join([
# Use the first namespace, we'll add the others afterwardsm thi .
_make_tool_invocation_command(namespaces[0], lib_import, listener, visitor),
_make_namespace_adjustment_command(namespaces, out_files),
])
native.genrule(
name = name + "_source",
srcs = [src] + imports,
outs = out_files,
cmd = command,
heuristic_label_expansion = 0,
tools = [
":antlr_tool",
],
)
native.cc_library(
name = name,
srcs = [f for f in out_files if f.endswith(".cpp")],
hdrs = [f for f in out_files if f.endswith(".h")],
deps = ["@antlr_cc_runtime//:antlr4_runtime"] + deps,
copts = [
"-fexceptions",
# FIXME: antlr generates broken C++ code that attempts to construct
# a std::string from nullptr. It's not clear whether the relevant
# constructs are reachable.
"-Wno-nonnull",
],
features = ["-use_header_modules"], # Incompatible with -fexceptions.
)
def _make_outs(file_prefix, suffixes):
return [file_suffix % file_prefix for file_suffix in suffixes]
def _strip_end(text, suffix):
if not text.endswith(suffix):
return text
return text[:len(text) - len(suffix)]
def _to_c_macro_name(filename):
# Convert the filenames to a format suitable for C preprocessor definitions.
char_list = [filename[i].upper() for i in range(len(filename))]
return "ANTLR4_GEN_" + "".join(
[a if (("A" <= a) and (a <= "Z")) else "_" for a in char_list],
)
def _make_tool_invocation_command(package, lib_import, listener = False, visitor = False):
return "$(location :antlr_tool) " + \
"$(SRCS)" + \
(" -visitor" if visitor else " -no-visitor") + \
(" -listener" if listener else " -no-listener") + \
(" -lib $$(dirname $(location " + lib_import + "))" if lib_import else "") + \
" -Dlanguage=Cpp" + \
" -package " + package + \
" -o $(@D)" + \
" -Xexact-output-dir"
def _make_namespace_adjustment_command(namespaces, out_files):
if len(namespaces) == 1:
return "true"
commands = []
extra_header_namespaces = "\\\n".join(["namespace %s {" % namespace for namespace in namespaces[1:]])
for filepath in out_files:
if filepath.endswith(".h"):
commands.append("sed -i '/namespace %s {/ a%s' $(@D)/%s" % (namespaces[0], extra_header_namespaces, filepath))
for namespace in namespaces[1:]:
commands.append("sed -i '/} \/\/ namespace %s/i} \/\/ namespace %s' $(@D)/%s" % (namespaces[0], namespace, filepath))
else:
commands.append("sed -i 's/using namespace %s;/using namespace %s;/' $(@D)/%s" % (namespaces[0], "::".join(namespaces), filepath))
return ";\n".join(commands)
|
# -*- coding: utf-8 -*-
message_dict = {
'welcome': "Hi! TPO Baba is here to give you updates about TPO portal, set willingness reminders, ppt "\
"reminders, exam date reminders and lot more...:D \n\n"\
"To personalise your experience, I gotta register you. It's simple two step process.\n",
'greetings': "Hello pal :)",
'haalchaal': "hamaar to mauj ahaai guru 🙏, tohaar batawa kaa haal chaal bate?"\
" ;P",
'no_idea': "Oops, didn't get you, Baba is a simple AI bot not Jarvis, don't be so cryptic. 😅\n"\
"Baba has gotta master, Baba will learn this soon. B) \n\n"\
"Ask for help to know what options you have.",
'user_invalid': "You account is Invalid.\n"\
"Contact https://m.me/rishabh.ags/ for help",
'get_email': "Baba needs to know your official IIT email id, drop it as a text message.",
'email_set': "Baba has set your email to {0}",
'not_iit_email': "Oops!, seems like you didn't enter your official email id\n"\
"As I am running on a heroku server, which costs 7$ pm. Don't misuse this. "\
"I cannot afford offering services to others,.\nIf you ain't student of IIT (BHU), please"\
" don't register ,.. Bhawnao ko samjho yaaar 😅",
'get_course': "Baba needs to know your course, select your course among btech, idd or imd, "\
"then drop a text message.",
'course_set': "Baba has set your course to {0}",
'reg_error': "Oops!, you got me wrong, retry entering it correctly..\n\n"\
"And you gotta register first, we'll chat afterwards. :)\n"\
"if you're facing issues contact https://m.me/rishabh.ags",
'email_already_set': "Pal, you already got your email set to {0}",
'invalid_email': "Baba wants a valid email id.\nRetry please.",
'course_already_set': "Pal, you already got your email set to {0}",
'reg_success': "And congratulations! 🎉 you have successfully registered!, your email id "\
"will be verified soon. :) \n\nIf found misleading or wrong, I'll find you and I'll "\
"deregister you ;P \n\n"\
"Ask for features to know what I've got for you in my Jhola B) \n\n"\
"Ask for help to know what options you have. :)",
'features': "Baba is a messenger bot created by a high functioning sociopathic nerd of IIT (BHU) :D\n"\
"\nI have got a simple AI brain powered by Wit and has not been trained too much, "\
"so please don't use too off the track keywords 😅 \n\n",
'features1': "What I currently do:\n"\
"1. Text you whenever a new company opens for your course and department, "\
"you'll get all details of such companies.\n"\
"2. Text you whenever companies your course and department get any changes in their "\
"parameters like willingness deadlines, exam dates, ppt dates, etc.. \n\n",
'features2':"What I plan to do pretty soon:\n"\
"1. Remind you about deadlines of willingness application, ppt dates "\
"and exam dates etc.. B) \n" \
"2. Give replies to your queries about companies...\n\n"\
"P.S. To know why that nerd made me? you are free to ask me :P\n"\
"Ask for help to know what options you have.",
'help': "Baba has got you some help:\n\n"\
"1. You can ask me to unsubscribe/deactivate you from receiving updates .\n"\
"2. You can ask me subscribe/activate your account. from receiving updates.\n",
'deactivate': "Alright pal, It's been a good chat with you, deactivating your account.\n"\
"You can ask me to reactivate it if necessary.",
'activate': "Welcome back!, your account is reactivated",
'wit_error': "Ohho, I'm sick, my brain is not working, Please call my master! 😰 \n"\
"https:/m.me/rishabhags/",
'new_company': "Hola!\nNew Company Open for you! 🎉🎊🎁\n\n"\
"Company Name: {company_name}\n"\
"Open for: {course}\n"\
"Departments: {department}\n"\
"BTech CTC: {btech_ctc}\n"\
"IDD/IMD CTC: {idd_imd_ctc}\n"\
"X cutoff: {x}\n"\
"XII cutoff: {xii}\n"\
"CGPA cutoff: {cgpa}\n"\
"Status: {status}\n\n"\
"Will keep you updated with this company :D.\n"\
"Cya :)",
'updated_company': "Baba has updates to deliver!\n\n"\
"{0} got updated on the portal\n\n"\
"Updated fields are: \n\n"\
"{1}\n"\
"{2}"\
"\n\nThis is it for now.\nCya :)",
#{1} will store update message
'abuse': "You are so abusive, next time, I'll deactivate your account 😡😠😡",
'lol': "Lol, I was kidding,,. 😜😝😂",
'master': "My master made me because TPO developers ko to `सीनेमा` ne barbaad karke rakkha hai.. "\
"and he knows very well, that jab tak iss des me `सीनेमा` hai, tab tak log * "\
"bante rahege ;P \n\n"\
"P.S. This was a joke, it has nothing to do with anything, we respect TPO portal "\
"developers they have made a great portal. \n"\
"Ask for me for help, if you wanna know what you have got to do.",
'idd_imd_4th_year': "Ops!, you are from 4rth year IDD/IMD, I don't wanna disturb you with updates. \n"\
"I'll have to set your account Invalid.\n\n"\
"For further queries contact https://m.me/rishabh.ags/"
}
field_msg_dict = {
'company_profile': 'Company Profile',
'x': 'X',
'xii': 'XII',
'cgpa': 'CGPA',
'course': 'Course',
'purpose': 'Purpose',
'department': 'Department',
'a_backlog': 'Active backlogs allowed',
't_backlog': 'Total backlogs allowed',
'ppt_date': 'PPT date',
'exam_date': 'Exam date',
'status': 'Status',
'branch_issue_dead': 'Branch issue deadline',
'willingness_dead': 'Willingness deadline',
'btech_ctc': 'B.Tech CTC',
'idd_imd_ctc':'IDD/IMD CTC',
# 'jd': 'JD',
}
# "TPO developers ko to `सीनेमा` ne barbaad karke rakkha hai.. ;P\n"
# "So, hum denge aapko sare updates, about new companies listed in the portal,willingness opening "\
# "and closing reminders ppt reminders, exam date reminders aur bhi bahot kuchh..\n"\
# 'invalid_course': "Baba wants valid course name (btech or idd or imd).\n retry please.",
# "Active backlogs allowed: {8}\n"\
# "Total backlogs allowed: {9}\n"\
|
# A 以上 B 以下の整数のうち、回文数となるものの個数を求めてください。
# ただし、回文数とは、先頭に 0 をつけない 10 進表記を文字列として見たとき、
# 前から読んでも後ろから読んでも同じ文字列となるような正の整数のことを指します。
# 文字列を逆順にして、同じ桁数の値をみる
a, b = map(int, input().split())
cnt = 0
for i in range(a, b+1):
s = str(i)
s_r = s[::-1]
n = int(len(str(s))/2)
if s[: n] == s_r[:n]:
cnt += 1
print(cnt)
|
class AnimationException(SystemException,ISerializable,_Exception):
""" The exception that is thrown when an error occurs while animating a property. """
def add_SerializeObjectState(self,*args):
""" add_SerializeObjectState(self: Exception,value: EventHandler[SafeSerializationEventArgs]) """
pass
def remove_SerializeObjectState(self,*args):
""" remove_SerializeObjectState(self: Exception,value: EventHandler[SafeSerializationEventArgs]) """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __reduce_ex__(self,*args):
pass
def __str__(self,*args):
pass
Clock=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the clock that generates the animated values.
Get: Clock(self: AnimationException) -> AnimationClock
"""
Property=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the animated dependency property.
Get: Property(self: AnimationException) -> DependencyProperty
"""
Target=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the animated object.
Get: Target(self: AnimationException) -> IAnimatable
"""
|
file_berita = open("berita.txt", "r")
berita = file_berita.read()
berita = berita.split()
berita = [x.lower() for x in berita]
berita = list(set(berita))
berita = sorted(berita)
print (berita) |
"""
@Fire
https://github.com/fire717
"""
cfg = {
##### Global Setting
'GPU_ID': '0',
"num_workers":8,
"random_seed":42,
"cfg_verbose":True,
"save_dir": "output/",
"num_classes": 17,
"width_mult":1.0,
"img_size": 192,
##### Train Setting
'img_path':"./data/croped/imgs",
'train_label_path':'./data/croped/train2017.json',
'val_label_path':'./data/croped/val2017.json',
'balance_data':False,
'log_interval':10,
'save_best_only': True,
'pin_memory': True,
##### Train Hyperparameters
'learning_rate':0.001,#1.25e-4
'batch_size':64,
'epochs':120,
'optimizer':'Adam', #Adam SGD
'scheduler':'MultiStepLR-70,100-0.1', #default SGDR-5-2 CVPR step-4-0.8 MultiStepLR
'weight_decay' : 5.e-4,#0.0001,
'class_weight': None,#[1., 1., 1., 1., 1., 1., 1., ]
'clip_gradient': 5,#1,
##### Test
'test_img_path':"./data/croped/imgs",
#"../data/eval/imgs",
#"../data/eval/imgs",
#"../data/all/imgs"
#"../data/true/mypc/crop_upper1"
#../data/coco/small_dataset/imgs
#"../data/testimg"
'exam_label_path':'../data/all/data_all_new.json',
'eval_img_path':'../data/eval/imgs',
'eval_label_path':'../data/eval/mypc.json',
}
|
k = float(input("Digite uma distância em quilometros: "))
m = k / 1.61
print("A distância digitada é de {} quilometros, essa distância convertida é {:.2f} milhas" .format(k,m)) |
aluno = {}
aluno['nome'] = str(input('Digite o nome do aluno: '))
aluno['media'] = float(input('Digite a média desse aluno: '))
if aluno['media'] >= 5:
aluno['situação'] = '\033[32mAprovado\033[m'
else:
aluno['situação'] = '\033[31mReprovado\033[m'
for k, v in aluno.items():
print(f'{k} do aluno é {v}') |
rzymskie={'I':1,'II':2,'III':3,'IV':4,'V':5,'VI':6,'VII':7,'VIII':8}
print(rzymskie)
print('Jeden element slownika: \n')
print(rzymskie['I'])
|
H, W = map(int, input().split())
A = [input() for _ in range(H)]
if H + W - 1 == sum(a.count('#') for a in A):
print('Possible')
else:
print('Impossible')
|
"""
Desafio 067
Problema: Faça um programa que mostre a tabuada de vários números,
um de cada vez, para cada valor digitado pelo usuário.
O programa será interrompido quando o número solicitado
for negativo.
Resolução do problema:
"""
print('-' * 20)
print(f'{" Tabuada v3.0 ":~^20}')
print('-' * 20)
while True:
tabuada = int(input('Tabuada desejada: '))
print('-' * 20)
if tabuada < 0:
break
for cont in range(0, 11):
print(f'{tabuada} x {cont:2} = {tabuada * cont:2}')
print('-' * 20)
print(f'{" TABUADA FINALIZADA ":~^30}\nFOI UM PRAZER AJUDA-LO!!!')
|
"""
Crie um programa que leia um a frase qualquer e diga se ela é um palíndromo,
desconsiderando os espaços.
ex:
apos a sopa
a sacada da casa
a torre da derrota
o lobo ama o bolo
anotaram a data da maratona
"""
frase = input('Digite uma frase (sem acentos): ').replace(' ', '').upper()
inverso = ''
for c in range(len(frase) - 1, -1, -1):
inverso += frase[c]
print(f'O inverso de {frase} é {inverso}')
if frase == inverso:
print('A frase digitada é um palíndromo.')
else:
print('A frase digitada não é um Palíndromo')
|
"""
Get an Etree library. Usage::
>>> from anyetree import etree
Returns some etree library. Looks for (in order of decreasing preference):
* ``lxml.etree`` (http://cheeseshop.python.org/pypi/lxml/)
* ``xml.etree.cElementTree`` (built into Python 2.5)
* ``cElementTree`` (http://effbot.org/zone/celementtree.htm)
* ``xml.etree.ElementTree`` (built into Python 2.5)
* ``elementree.ElementTree (http://effbot.org/zone/element-index.htm)
"""
__all__ = ['etree']
SEARCH_PATHS = [
"lxml.etree",
"xml.etree.cElementTree",
"cElementTree",
"xml.etree.ElementTree",
"elementtree.ElementTree",
]
etree = None
for name in SEARCH_PATHS:
try:
etree = __import__(name, '', '', [''])
break
except ImportError:
continue
if etree is None:
raise ImportError("No suitable ElementTree implementation found.") |
# File: etl.py
# Purpose: To do the `Transform` step of an Extract-Transform-Load.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Thursday 22 September 2016, 03:40 PM
def transform(words):
new_words = dict()
for point, letters in words.items():
for letter in letters:
new_words[letter.lower()] = point
return new_words
|
def have(subj, obj):
subj.add(obj)
def change(subj, obj, state):
pass
if __name__ == '__main__':
main() |
# A bot that picks the first action from the list for the first two rounds,
# and then exists with an exception.
# Used only for tests.
game_name = input()
play_as = int(input())
print("ready")
while True:
print("start")
num_actions = 0
while True:
message = input()
if message == "tournament over":
print("tournament over")
sys.exit(0)
if message.startswith("match over"):
print("match over")
break
public_buf, private_buf, *legal_actions = message.split(" ")
should_act = len(legal_actions) > 0
if should_act:
num_actions += 1
print(legal_actions[-1])
else:
print("ponder")
if num_actions > 2:
raise RuntimeError
|
'''
f we want to add a single element to an existing set, we can use the .add() operation.
It adds the element to the set and returns 'None'.
Example
>>> s = set('HackerRank')
>>> s.add('H')
>>> print s
set(['a', 'c', 'e', 'H', 'k', 'n', 'r', 'R'])
>>> print s.add('HackerRank')
None
>>> print s
set(['a', 'c', 'e', 'HackerRank', 'H', 'k', 'n', 'r', 'R'])
The first line contains an integer N, the total number of country stamps.
The next N lines contains the name of the country where the stamp is from.
Output Format
Output the total number of distinct country stamps on a single line.
'''
n = int(input())
countries = set()
for i in range(n):
countries.add(input())
print(len(countries))
|
# 6. Продолжить работу над вторым заданием. Реализуйте механизм валидации вводимых пользователем данных. Например, для
# указания количества принтеров, отправленных на склад, нельзя использовать строковый тип данных.
# Подсказка: постарайтесь по возможности реализовать в проекте «Склад оргтехники» максимум возможностей, изученных на
# уроках по ООП.
class StoreMashines:
def __init__(self, name, price, quantity, number_of_lists, *args):
self.name = name
self.price = price
self.quantity = quantity
self.numb = number_of_lists
self.my_store_full = []
self.my_store = []
self.my_unit = {'Модель устройства': self.name, 'Цена за ед': self.price, 'Количество': self.quantity}
def __str__(self):
return f'{self.name} цена {self.price} количество {self.quantity}'
# @classmethod
# @staticmethod
def reception(self):
# print(f'Для выхода - Q, продолжение - Enter')
# while True:
try:
unit = input(f'Введите наименование ')
unit_p = int(input(f'Введите цену за ед '))
unit_q = int(input(f'Введите количество '))
unique = {'Модель устройства': unit, 'Цена за ед': unit_p, 'Количество': unit_q}
self.my_unit.update(unique)
self.my_store.append(self.my_unit)
print(f'Текущий список -\n {self.my_store}')
except:
return f'Ошибка ввода данных'
print(f'Для выхода - Q, продолжение - Enter')
q = input(f'---> ')
if q == 'Q' or q == 'q':
self.my_store_full.append(self.my_store)
print(f'Весь склад -\n {self.my_store_full}')
return f'Выход'
else:
return StoreMashines.reception(self)
class Printer(StoreMashines):
def to_print(self):
return f'to print smth {self.numb} times'
class Scanner(StoreMashines):
def to_scan(self):
return f'to scan smth {self.numb} times'
class Copier(StoreMashines):
def to_copier(self):
return f'to copier smth {self.numb} times'
unit_1 = Printer('hp', 2000, 5, 10)
unit_2 = Scanner('Canon', 1200, 5, 10)
unit_3 = Copier('Xerox', 1500, 1, 15)
print(unit_1.reception())
print(unit_2.reception())
print(unit_3.reception())
print(unit_1.to_print())
print(unit_3.to_copier())
|
class LeagueGame:
def __init__(self, data):
self.patch = data['patch']
self.win = data['win']
self.side = data['side']
self.opp = data['opp']
self.bans = data['bans']
self.vs_bans = data['vs_bans']
self.picks = data['picks']
self.vs_picks = data['vs_picks']
self.players = data['players']
class LeaguePlayer:
def __init__(self, n_games, n_wins, data):
self.n_games = n_games
self.n_wins = n_wins
self.K = data['K']
self.D = data['D']
self.A = data['A']
self.CS = data['CS']
self.CSM = data['CSM']
self.G = data['G']
self.GM = data['GM']
self.KPAR = data['KPAR']
self.KS = data['KS']
self.GS = data['GS']
class LeagueTeam:
def __init__(self, players, data):
self.players = players
self.region = data['region']
self.season = data['season']
self.WL = data['WL']
self.avg_gm_dur = data['avg_gm_dur']
self.most_banned_by = data['most_banned_by']
self.most_banned_vs = data['most_banned_vs']
self.economy = data['economy']
self.aggression = data['aggression']
self.objectives = data['objectives']
self.vision = data['vision']
|
text1 = '''ABCDEF
GHIJKL
MNOPQRS
TUVWXYZ
'''
text2 = 'ABCDEF\
GHIJKL\
MNOPQRS\
TUVWXYZ'
text3 = 'ABCD\'EF\'GHIJKL'
text4 = 'ABCDEF\nGHIJKL\nMNOPQRS\nTUVWXYZ'
text5 = 'ABCDEF\fGHIJKL\fMNOPQRS\fTUVWXYZ'
print(text1)
print('-' * 25)
print(text2)
print('-' * 25)
print(text3)
print('-' * 25)
print(text4)
print('-' * 25)
print(text5) |
# unihernandez22
# https://atcoder.jp/contests/abc166/tasks/abc166_d
# math, brute force
n = int(input())
for a in range(n):
breaked = True
for b in range(-1000, 1000):
if a**5 - b**5 == n:
print(a, b)
break;
else:
breaked = False
if breaked:
break
|
T = int(input())
P = int(input())
controle = 0 #Uso para guardar o valor maior que o limite
while P != 0:
P = int(input())
if P >= T:
controle = 1 #coloquei 1 so pra ser diferente de 0
if controle == 1:
print("ALARME")
else:
print("O Havai pode dormir tranquilo") |
__all__ = [
"aggregation",
"association",
"composition",
"connection",
"containment",
"dependency",
"includes",
"membership",
"ownership",
"responsibility",
"usage"
] |
class AxisIndex(): #TODO: read this value from config file
LEFT_RIGHT=0
FORWARD_BACKWARDS=1
ROTATE=2
UP_DOWN=3
class ButtonIndex():
TRIGGER = 0
SIDE_BUTTON = 1
HOVERING = 2
EXIT = 10
class ThresHold():
SENDING_TIME = 0.5 |
#!/Users/francischen/opt/anaconda3/bin/python
#pythons sorts are STABLE: order is the same as original in tie.
# sort: key, reverse
q = ['two','twelve','One','3']
#sort q, result being a modified list. nothing is returned
q.sort()
print(q)
q = ['two','twelve','One','3',"this has lots of t's"]
q.sort(reverse=True)
print(q)
def f(x):
return x.count('t')
q.sort(key = f)
print(q)
q = ['twelve','two','One','3',"this has lots of t's"]
q.sort(key=f)
print(q)
#Multiple sorts
q = ['twelve','two','One','3',"this has lots of t's"]
q.sort()
q.sort(key=f)
# sort based on 1,2,and then 3
# sort 3, then sort 2, then sort 1
print(q)
def complicated(x):
return(x.count('t'),len(x),x)
q = ['two','otw','wot','Z','t','tt','longer t']
q.sort(key=complicated)
print(q) |
# buildifier: disable=module-docstring
load(":native_tools_toolchain.bzl", "access_tool")
def get_cmake_data(ctx):
return _access_and_expect_label_copied("@rules_foreign_cc//tools/build_defs:cmake_toolchain", ctx, "cmake")
def get_ninja_data(ctx):
return _access_and_expect_label_copied("@rules_foreign_cc//tools/build_defs:ninja_toolchain", ctx, "ninja")
def get_make_data(ctx):
return _access_and_expect_label_copied("@rules_foreign_cc//tools/build_defs:make_toolchain", ctx, "make")
def _access_and_expect_label_copied(toolchain_type_, ctx, tool_name):
tool_data = access_tool(toolchain_type_, ctx, tool_name)
if tool_data.target:
# This could be made more efficient by changing the
# toolchain to provide the executable as a target
cmd_file = tool_data
for f in tool_data.target.files.to_list():
if f.path.endswith("/" + tool_data.path):
cmd_file = f
break
return struct(
deps = [tool_data.target],
# as the tool will be copied into tools directory
path = "$EXT_BUILD_ROOT/{}".format(cmd_file.path),
)
else:
return struct(
deps = [],
path = tool_data.path,
)
|
fname = input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
list = list()
f = open(fname)
count = 0
for line in f:
line = line.rstrip()
list = line.split()
if list == []: continue
elif list[0].lower() == 'from':
count += 1
print(list[1])
print("There were", count, "lines in the file with From as the first word") |
class FollowupEvent:
def __init__(self, name, data=None):
self.name = name
self.data = data
class Response:
def __init__(self, text=None, followup_event=None):
self.speech = text
self.display_text = text
self.followup_event = followup_event
class UserInput:
def __init__(self, message: str, session_id: str, params: dict, text: str, action: str, intent: str):
self.message = message
self.session_id = session_id
self.params = params
self.raw = text
self.action = action
self.intent = intent
|
# -*- coding: utf-8 -*-
jobwords = [
'nan',
'temps plein', 'temps complet', 'mi temps', 'temps partiel', # Part / Full time
'cherche', # look for
'urgent','rapidement', 'futur',
'job', 'offre', # Job offer
'trice', 'ère', 'eur', 'euse', 're', 'se', 'ème', 'trices', # Female endings
'ères', 'eurs', 'euses', 'res', 'fe', 'fes',# Female endings
've', 'ne', 'iere', 'rice', 'te', 'er', 'ice',
'ves', 'nes', 'ieres', 'rices', "tes", 'ices', # Female endings
'hf', 'fh', # Male/Female, Female/Male
'semaine', 'semaines', 'sem',
'h', 'heure', 'heures', 'hebdo', 'hebdomadaire', # Time (week, hour)
'année', 'mois', 'an', # Year
'jour', 'jours', # Day
'été', 'automne', 'hiver', 'printemps', # summer, winter ...
'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche', # Week day
'janvier', 'février', 'mars', 'avril', 'mai', 'juin', # Month
'juillet', 'aout', 'septembre', 'octobre', 'novembre', 'décembre',
"deux", "trois", "quatre", "cinq", "six", "sept", # Number
"huit", "neuf", "dix", "onze", # Number
"euros", "euro", "dollars", "dollar", # Money
"super", # Pour éviter "super poids lourd"
# To clean
'caces', 'cap', 'bts', 'dea', 'diplôme', 'bac',
"taf", "ref", "poste", "pourvoir", "sein", "profil",
"possible",
'indépendant',
'saisonnier', 'alternance', 'alternant', 'apprenti',
'apprentissage', 'stagiaire', 'étudiant', 'fonctionnaire',
'intermittent', 'élève', 'freelance', "professionnalisation",
'partiel', 'cdd', 'cdi', 'contrat', 'pro',
"fpe", # Fonction publique d'état
'débutant', 'expérimenté', 'junior', 'senior',
'confirmé', 'catégorie',
'trilingue', 'bilingue',
'bi','international', 'france', 'national', 'régional',
'européen', 'emploi', 'non',
'exclusif', 'uniquement',
'permis', 'ssiap', 'bnssa',
]
job_replace_infirst = {
'3 d' : 'troisd',
'3d':'troisd',
'2 d': 'deuxd',
'2d':'deuxd',
'b to b': 'btob'
}
job_lemmas_expr = {
'cours particulier' : 'professeur',
'call center' : 'centre appels',
'vl pl vu' : 'poids lourd',
'front end' : 'informatique',
'back end' : 'informatique',
'homme femme' : '',
'femme homme' : ''
}
job_normalize_map = [
("indu", "industriel"),
("pl","poids lourd"),
("spl","poids lourd"),
("sav","service après vente"),
("unix","informatique"),
("windows","informatique"),
("php","informatique"),
("java","informatique"),
("python","informatique"),
("jee","informatique"),
("sap","informatique"),
("abap","informatique"),
("ntic","informatique"),
# ("c","informatique"),
("rh","ressources humaines"),
("vrd","voirie réseaux divers"),
("super poids lourd","poids lourd"),
("adv","administration des ventes"),
("cvv","chauffage climatisation"),
("agt","agent"),
("ash","agent des services hospitaliers"),
("ibode","infirmier de bloc opératoire"),
("aes","accompagnant éducatif et social"),
("ads","agent de sécurité"),
("amp","aide médico psychologique"),
("asvp","agent de surveillance des voies publiques"),
("cesf","conseiller en économie sociale et familiale"),
("babysitter","baby sitter"),
("babysitting","baby sitter"),
("sitting","sitter"),
("nounou", "nourrice"),
("coaching","coach"),
("webdesigner","web designer"),
("webmarketer","web marketer"),
("helpdesk","help desk"),
("prof","professeur"),
("maths", "mathématiques"),
("géo", "géographie"),
("philo", "philosophie"),
("epr","employe polyvalent de restauration"),
("NTIC","Informatique"),
("SIG","Systèmes d Information Géographique "),
("EPSCP","établissement public à caractère scientifique, culturel et professionnel "),
("NRBC","Nucléaire, Radiologique, Bactériologique, Chimique "),
("SAV","Service après vente"),
("ACIM ","Agent des Cabinets en Imagerie Médicale "),
("ASC","Agent des Services Commerciaux"),
("AEC","Agent d Escale Commerciale"),
("ASEM","Agent spécialisé des écoles maternelles "),
("TIC","Informatique"),
("HSE","Hygiène Sécurité Environnement "),
("ATER","Attaché temporaire d enseignement et de recherche "),
("AVS","Auxiliaire de Vie Sociale "),
("AIS","Auxiliaire d Intégration Scolaire"),
("ASV","Auxiliaire Spécialisé Vétérinaire "),
("AVQ","Auxiliaire Vétérinaire Qualifié"),
("IARD","Incendie, Accidents, Risques Divers "),
("NBC","Nucléaire, Bactériologique et Chimique"),
("PGC","Produits de Grande Consommation "),
("PNT","Personnel Navigant Technique "),
("PAO","Publication Assistée par Ordinateur"),
("TTA","toute arme"),
("VRD","Voiries et Réseaux Divers"),
("CMS","Composants Montés en Surface "),
("VSL","Véhicule Sanitaire Léger"),
("CIP","Conseiller d Insertion et de Probation "),
("CND","Contrôle Non Destructif "),
("MOA","Maîtrise d Ouvrage"),
("OPC","Ordonnancement, Pilotage et Coordination de chantier"),
("SPS","Sécurité, Protection de la Santé "),
("DAF","Directeur administratif et financier"),
("CHU","Centre Hospitalier Universitaire "),
("GSB","Grande Surface de Bricolage "),
("GSS","Grande Surface Spécialisée "),
("DOSI","Directeur de l Organisation et des Systèmes d Information "),
("ESAT","entreprise ou de Service d Aide par le Travail "),
("DRH","Directeur des Ressources Humaines "),
("DSI","Directeur des services informatiques "),
("DSPIP","Directeur des services pénitentiaires d insertion et de probation "),
("EPA","Etablissement Public à caractère Administratif "),
("EPST","Etablissement Public à caractère Scientifique et Technologique "),
("EPCC","Etablissement Public de Coopération Culturelle "),
("EPIC","Etablissement Public et Commercial "),
("IFSI","Institut de formation en soins infirmiers"),
("MAS","Machines à Sous "),
("SCOP","Société Coopérative Ouvrière de Production"),
(" EVS","Employée du Service Après Vente "),
("EVAT","Engagée Volontaire de l Armée de Terre "),
("EV","Engagé Volontaire "),
("GIR","Groupement d Individuels Regroupés "),
("CN","Commande Numérique "),
("SICAV","Société d Investissement à Capital Variable "),
("OPCMV","Organisme de Placement Collectif en Valeurs Mobilières "),
("OPCVM","Organisme de Placement Collectif en Valeurs Mobilières "),
("IADE","Infirmier Anesthésiste Diplômé d Etat "),
("IBODE","Infirmier de bloc opératoire Diplômé d Etat "),
("CTC","contrôle technique de construction "),
("IGREF","Ingénieur du génie rural des eaux et forêts "),
("IAA","Inspecteur d académie adjoint"),
("DSDEN","directeur des services départementaux de l Education nationale "),
("IEN","Inspecteur de l Education Nationale "),
("IET","Inspecteur de l enseignement technique "),
("ISPV","Inspecteur de Santé Publique Vétérinaire "),
("IDEN","Inspecteur départemental de l Education nationale "),
("IIO","Inspecteur d information et d orientation "),
("IGEN","Inspecteur général de l Education nationale "),
("IPR","Inspecteur pédagogique régional"),
("IPET","Inspecteur principal de l enseignement technique "),
("PNC","Personnel Navigant Commercial "),
("MPR","Magasin de Pièces de Rechange "),
("CME","Cellule, Moteur, Electricité "),
("BTP","Bâtiments et Travaux Publics "),
("EIR","Electricité, Instrument de bord, Radio "),
("MAR","Médecin Anesthésiste Réanimateur "),
("PMI","Protection Maternelle et Infantile "),
("MISP","Médecin Inspecteur de Santé Publique "),
("MIRTMO","Médecin Inspecteur Régional du Travail et de la Main d oeuvre "),
("DIM","Documentation et de l Information Médicale"),
("OPL","Officier pilote de ligne "),
("CN","commande numérique "),
("PPM","Patron Plaisance Moteur "),
("PPV","Patron Plaisance Moteur "),
("PhISP","Pharmacien Inspecteur de Santé Publique "),
("PDG","Président Directeur Général "),
("FLE","Français Langue Etrangère "),
("PLP","Professeur de lycée professionnel "),
("EPS","éducation physique et sportive "),
("PEGL","Professeur d enseignement général de lycée "),
("PEGC","Professeur d enseignement général des collèges "),
("INJS","instituts nationaux de jeunes sourds "),
("INJA","instituts nationaux de jeunes aveugles "),
("TZR","titulaire en zone de remplacement "),
("CFAO","Conception de Fabrication Assistée par Ordinateur "),
("SPIP","service pénitentiaire d insertion et de probation "),
("PME","Petite ou Moyenne Entreprise "),
("RRH","Responsable des Ressources Humaines "),
("QSE","Qualité Sécurité Environnement "),
("SASU","Secrétaire d administration scolaire et universitaire "),
("MAG","Metal Active Gas "),
("MIG","Metal Inert Gas "),
("TIG","Tungsten Inert Gas "),
("GED","Gestion électronique de documents"),
("CVM","Circulations Verticales Mécanisées "),
("TISF","Technicien Intervention Sociale et Familiale"),
("MAO","Musique Assistée par Ordinateur"),
# ("Paie","paye"),
# ("paies","paye"),
("ml","mission locale"),
("AS","aide soignant"),
("IDE","infirmier de soins généraux"),
("ERD","études recherche et développement")
]
|
# Problem Name: Suffix Trie Construction
# Problem Description:
# Write a SuffixTrie class for Suffix-Trie-like data structures. The class should have a root property set to be the root node of the trie and should support:
# - Creating the trie from a string; this will be done by calling populateSuffixTrieFrom method upon class instantiation(creation), which should populate the root of the class.
# - Searching for strings in the trie.
# Note that every string added to the trie should end with special endSymbol character: "*".
####################################
# Sample Input (for creation):
# string = "babc"
# Sample Output (for creation):
# The structure below is the root of the trie:
# {
# "c": {"*": true},
# "b": {
# "c": {"*": true},
# "a": {"b": {"c": {"*": true}}},
# },
# "a": {"b": {"c": {"*": true}}},
# }
# Sample Input (for searching in the suffix trie above):
# string = "abc"
# Sample Output (for searching in the suffix trie above):
# True
####################################
"""
Explain the solution:
- Building a suffix-trie-like data structure consists of essentially storing every suffix of a given string in a trie. To do so, iterate through the input string one character at a time, and insert every substring starting at each character and ending at the end of string into the trie.
- To insert a string into the trie, start by adding the first character of the string into the root node of the trie and map it to an empty hash table if it isin't already there. Then, iterate through the rest of the string, inserting each of the remaining characters into the previous character's corresponding node(or hash table) in the trie, making sure to add an endSymbol "*" at the end.
- Searching the trie for a specific string should follow a nearly identical logic to the one used to add a string in the trie.
# Creation: O(n^2) time | O(n^2) space - where n is the length of the input string
# Searching: O(m) time | O(1) space - where m is the length of the input string
##################
Detailed explanation of the Solution:
create a class called SuffixTrie:
initialize function takes in a string:
initialize the class with root as an empty hash table
initialize the class with a endSymbol variable that is set to "*"
create a method called populateSuffixTrieFrom with a parameter of string
# Creation:
initialize function populateSuffixTrieFrom takes in a string:
iterate as i through the string one character at a time:
use Helper function insertSubsStringStartingAt with the parameter of the string and the current character(i)
initialize function insertSubsStringStartingAt takes in a string and a character(i):
create a variable called node that is set to the root of the trie
iterate as j through the string starting at the character(i) and ending at the end of the string:
create a variable called letter that is set to the current string[j]
if the letter is not in the node:
create a new hash table and set it to the node[letter] # this is the first time we've seen this letter
create a variable called node that is set to the node[letter] # this is the node we're currently at
node[self.endSymbol] = True # insert the endSymbol "*" at the end of the string
# Searching:
initialize function contains takes in a string:
create a variable called node that is set to the root of the trie
iterate as letter through the string:
if the letter is not in the node:
return False
create a variable called node that is set to the node[letter]
return self.endSymbol in node # return True if the endSymbol "*" is in the node
"""
####################################
class SuffixTrie:
def __init__(self, string):
self.root = {}
self.endSymbol = "*"
self.populateSuffixTrieFrom(string) #call the populateSuffixTrieFrom function with the string as a parameter
# Creation
def populateSuffixTrieFrom(self, string):
for i in range(len(string)):
self.insertSubstringStartingAt(string, i) #insert the substring starting at each character and ending at the end of string into the trie
def insertSubstringStartingAt(self, string, i):
node = self.root
for j in range(i, len(string)):#iterate through the string starting at the index i
letter = string[j] #get the letter at the index j
if letter not in node:
node[letter] = {} #if the letter is not in the node, add it to the node and map it to an empty hash table
node = node[letter] # this is the node that we are currently at
node[self.endSymbol] = True
# Searching
def contains(self, string):
node = self.root #start at the root node
for letter in string:
if letter not in node: #if the current letter is not in the node, return false
return False
node = node[letter] #move to the next node
return self.endSymbol in node #return True if the endSymbol "*" is in the node
def main():
string = "babc"
trie = SuffixTrie(string)
print(trie.root)
if __name__ == '__main__':
main() |
def test_list_devices(client):
devices = client.devices()
assert len(devices) > 0
assert any(map(lambda device: device.serial == "emulator-5554", devices))
def test_list_devices_by_state(client):
devices = client.devices(client.BOOTLOADER)
assert len(devices) == 0
devices = client.devices(client.OFFLINE)
assert len(devices) == 0
devices = client.devices(client.DEVICE)
assert len(devices) == 1
def test_version(client):
version = client.version()
assert type(version) == int
assert version != 0
def test_list_forward(client, device):
client.killforward_all()
result = client.list_forward()
assert not result
device.forward("tcp:6000", "tcp:6000")
result = client.list_forward()
assert result["emulator-5554"]["tcp:6000"] == "tcp:6000"
client.killforward_all()
result = client.list_forward()
assert not result
def test_features(client):
assert client.features()
|
"""Top-level package for Goldmeister."""
__author__ = """Micah Johnson"""
__email__ = 'micah.johnson150@gmail.com'
__version__ = '0.2.0'
|
n = int(input('Digite um número: '))
if n % 2 == 0 and n % 3 == 0 and n % 5 == 0:
print('{} é um número primo!'.format(n))
else:
print('{} não é um número primo!'.format(n))
|
def si(p,r,t):
n= (p+r+t)//3
return n
|
#!/usr/bin/env python3
# This is gonna be up to you. But basically I envisioned a system where you have a students in a classroom. Where the
# classroom only has information, like who is the teacher, how many students are there. And it's like an online class,
# so students don't know who their peers are, or who their teacher is, but can do things like study, and take test and
# stuff. Etc. But get used to how objects interact with each other and try to call stuff from other places while being
# commanded all in main():
class Student:
def __init__(self, name, laziness=5):
self.name = name
self.preparedness = 0
self._laziness = laziness
def takeTest(self, hardness):
# TODO: return a score that's 100 - difference between hardness and preparedness (score capped at 100)
return 0
def doHomework(self):
# TODO: return a score of either 0 or 100 depending on how lazy they are. Implementation is up to you.
return 0
def study(self):
# TODO: increment preparedness by a random number between 1-10 (prerparedness capped at 100)
pass
class Teacher:
def __init__(self, name):
self.name = name
self.classroom = None
self.test_grades = {}
self.homework_grades = {}
def administerTest(self, students, hardness):
# TODO: Given a hardness of a test and list of students. Make each student take test and log their grades
pass
def giveHomework(self, students):
# TODO: Given homework to student and log in their grades
pass
def giveGrades(self, students):
# TODO: Given all the test scores and homework score in each student, give 30% to HW and 70% to test.
# TODO: Return list of passed students and remove them from classroom. Clear grades for all remaining students
pass
class ClassRoom:
def __init__(self):
self.class_size_limit = 10
self.students = {}
self.teacher = None
def addStudent(self, student):
# TODO: add student to class. Print something if they try to add the same student or go over the limit
pass
def assignTeacherToClass(self, teacher):
# TODO: Assign teacher, also prompt user if they want to switch teacher if one already assigned or same teacher
pass
def getStudents(self):
# TODO: return a list of students
return
if __name__ == '__main__':
classroom = ClassRoom()
teacher = Teacher('Doctor Jones')
mike = Student('Mike')
sally = Student('Sally', laziness=1)
lebron = Student('Lebron', laziness=10)
# TODO: Assign a teacher to the classroom and add the students to the classroom. Then make the students study
# TODO: Make Students to homework, etc, exams, then pass or fail them, etc. Play around with it.
|
print('-'*60)
print('\33[35m[ F ] Feminino\33[m \n\33[32m[ M ] Masculino\33[m \n ')
sexo = str(input('Qual o seu sexo? ')).strip().upper()[0] # só pega a primeira letra
while sexo not in 'MF':
sexo = str(input('\33[31mDados inválidos.\33[m Por favor, informe seu sexo: ')).strip().upper()[0]
print('\nSexo {} registrado com sucesso!'.format(sexo))
print('-'*60) |
# https://github.com/ArtemNikolaev/gb-hw/issues/24
def multiple_of_20_21():
return (i for i in range(20, 241) if i % 20 == 0 or i % 21 == 0)
print(list(multiple_of_20_21()))
|
def cc_resources(name, data):
out_inc = name + ".inc"
cmd = ('echo "static const struct FileToc kPackedFiles[] = {" > $(@); \n' +
"for j in $(SRCS); do\n" +
' echo "{\\"$$(basename "$${j}")\\"," >> $(@);\n' +
' echo "R\\"filecontent($$(< $${j}))filecontent\\"" >> $(@);\n' +
' echo "}," >> $(@);\n' +
"done &&\n" +
'echo "{nullptr, nullptr}};" >> $(@)')
if len(data) == 0:
fail("Empty `data` attribute in `%s`" % name)
native.genrule(
name = name,
outs = [out_inc],
srcs = data,
cmd = cmd,
)
# Returns the generated files directory root.
#
# Note: workaround for https://github.com/bazelbuild/bazel/issues/4463.
def gendir():
if native.repository_name() == "@":
return "$(GENDIR)"
return "$(GENDIR)/external/" + native.repository_name().lstrip("@")
|
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print('Hello, my name is {} and I am {} years old'.format(self.name, self.age))
if __name__ == '__main__':
person = Person('David', 34)
print('Age: {}'.format(person.age))
person.say_hello() |
num= int (input("enter number of rows="))
for i in range (1,num+1):
for j in range(1,num-i+1):
print (" ",end="")
for j in range(2 and 9):
print("2","9")
for i in range(1, 6):
for j in range(1, 10):
if i==5 or i+j==5 or j-i==4:
print("*", end="")
else:
print(end=" ")
print()
|
'''
Problem:-
Given a string s, find the longest palindromic substring in s.
You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
'''
class Solution:
def longestPalindrome(self, s: str) -> str:
res = ""
resLen = 0
for i in range(len(s)):
# odd length
l, r = i, i
while l >= 0 and r < len(s) and s[l] == s[r]:
if (r - l + 1) > resLen:
res = s[l:r + 1]
resLen = r - l + 1
l -= 1
r += 1
# even length
l, r = i, i + 1
while l >= 0 and r < len(s) and s[l] == s[r]:
if (r - l + 1) > resLen:
res = s[l:r + 1]
resLen = r - l + 1
l -= 1
r += 1
return res |
def _doxygen_archive_impl(ctx):
"""Generate a .tar.gz archive containing documentation using Doxygen.
Args:
name: label for the generated rule. The archive will be "%{name}.tar.gz".
doxyfile: configuration file for Doxygen, @@OUTPUT_DIRECTORY@@ will be replaced with the actual output dir
srcs: source files the documentation will be generated from.
"""
doxyfile = ctx.file.doxyfile
out_file = ctx.outputs.out
out_dir_path = out_file.short_path[:-len(".tar.gz")]
commands = [
"mkdir -p %s" % out_dir_path,
"out_dir_path=$(cd %s; pwd)" % out_dir_path,
"pushd %s" % doxyfile.dirname,
"""sed -e \"s:@@OUTPUT_DIRECTORY@@:$out_dir_path/:\" <%s | doxygen -""" % doxyfile.basename,
"popd",
"tar czf %s -C %s ./" % (out_file.path, out_dir_path),
]
ctx.actions.run_shell(
inputs = ctx.files.srcs + [doxyfile],
outputs = [out_file],
use_default_shell_env = True,
command = " && ".join(commands),
)
doxygen_archive = rule(
implementation = _doxygen_archive_impl,
attrs = {
"doxyfile": attr.label(
mandatory = True,
allow_single_file = True,
),
"srcs": attr.label_list(
mandatory = True,
allow_files = True,
),
},
outputs = {
"out": "%{name}.tar.gz",
},
)
def _sphinx_archive_impl(ctx):
"""
Generates a sphinx documentation archive (.tar.gz).
The output is called <name>.tar.gz, where <name> is the
name of the rule.
Args:
config_file: sphinx conf.py file
doxygen_xml_archive: an archive that containing the generated doxygen
xml files to be consumed by the breathe sphinx plugin.
Setting this attribute automatically enables the breathe plugin
srcs: the *.rst files to consume
"""
out_file = ctx.outputs.sphinx
out_dir_path = out_file.short_path[:-len(".tar.gz")]
commands = ["mkdir _static"]
inputs = ctx.files.srcs
if ctx.attr.doxygen_xml_archive != None:
commands = commands + [
"mkdir xml",
"tar -xzf {xml} -C xml --strip-components=2".format(xml = ctx.file.doxygen_xml_archive.path),
]
inputs.append(ctx.file.doxygen_xml_archive)
commands = commands + [
"sphinx-build -M build ./ _build -q -b html -C {settings}".format(
settings = _sphinx_settings(ctx),
out_dir = out_dir_path,
),
]
commands = commands + [
"tar czf %s -C _build/build/ ./" % (out_file.path),
]
ctx.actions.run_shell(
use_default_shell_env = True,
outputs = [out_file],
inputs = inputs,
command = " && ".join(commands),
)
sphinx_archive = rule(
implementation = _sphinx_archive_impl,
attrs = {
"srcs": attr.label_list(
mandatory = True,
allow_files = True,
),
"doxygen_xml_archive": attr.label(
default = None,
allow_single_file = True,
),
"master_doc": attr.string(default = "contents"),
"version": attr.string(
mandatory = True,
),
"project": attr.string(
default = "",
),
"copyright": attr.string(default = ""),
"extensions": attr.string_list(default = [
"sphinx.ext.intersphinx",
"sphinx.ext.todo",
]),
"templates": attr.string_list(default = []),
"source_suffix": attr.string_list(default = [".rst"]),
"exclude_patterns": attr.string_list(default = ["_build", "Thumbs.db", ".DS_Store"]),
"pygments_style": attr.string(default = ""),
"language": attr.string(default = ""),
"html_theme": attr.string(default = "sphinx_rtd_theme"),
"html_theme_options": attr.string_dict(default = {}),
"html_static_path": attr.string_list(default = ["_static"]),
"html_sidebars": attr.string_dict(default = {}),
"intersphinx_mapping": attr.string_dict(default = {}),
},
outputs = {
"sphinx": "%{name}.tar.gz",
},
)
def add_option(settings, setting, value):
if value != None or len(value) == 0:
settings = settings + ["-D {setting}={value}".format(setting = setting, value = value.replace(" ", "\ "))]
return settings
def _sphinx_settings(ctx):
settings = []
extensions = ctx.attr.extensions
settings = add_option(settings, "version", ctx.attr.version)
if ctx.attr.project == "":
settings = add_option(settings, "project", ctx.workspace_name)
else:
settings = add_option(settings, "project", ctx.attr.project)
if ctx.attr.doxygen_xml_archive != None:
extensions = extensions + ["breathe"]
settings = add_option(settings, "breathe_projects." + ctx.workspace_name, "xml")
settings = add_option(settings, "breathe_default_project", ctx.workspace_name)
settings = add_option(settings, "copyright", ctx.attr.copyright)
settings = add_option(settings, "master_doc", ctx.attr.master_doc)
for extension in extensions:
settings = add_option(settings, "extensions", extension)
for template in ctx.attr.templates:
settings = add_option(settings, "templates", template)
for suffix in ctx.attr.source_suffix:
settings = add_option(settings, "source_suffix", suffix)
for pattern in ctx.attr.exclude_patterns:
settings = add_option(settings, "exclude_patterns", pattern)
settings = add_option(settings, "html_theme", ctx.attr.html_theme)
for path in ctx.attr.html_static_path:
settings = add_option(settings, "html_static_path", path)
setting_string = " ".join(settings)
return setting_string |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minDiffInBST(self, root: Optional[TreeNode]) -> int:
output=[]
stack=[root]
while(stack):
cur = stack.pop(0)
output.append(cur.val)
if cur.left:
stack.append(cur.left)
if cur.right:
stack.append(cur.right)
sorted_output=sorted(output)
diff = sorted_output[1]-sorted_output[0]
for i in range(2,len(sorted_output)):
if sorted_output[i]-sorted_output[i-1]<diff:
diff=sorted_output[i]-sorted_output[i-1]
return diff |
PREFIX = "/video/tvkultura"
NAME = "TVKultura.Ru"
ICON = "tvkultura.png"
ART = "tvkultura.jpg"
BASE_URL = "https://tvkultura.ru/"
BRAND_URL = BASE_URL+"brand/"
# Channel initialization
def Start():
ObjectContainer.title1 = NAME
HTTP.Headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0'
# Main menu
@handler(PREFIX, NAME, thumb=ICON, art=ART)
def MainMenu():
brands = SharedCodeService.vgtrk.brand_menu(BRAND_URL)
oc = ObjectContainer(title1=NAME)
for brand in brands.list:
oc.add(DirectoryObject(
key=Callback(BrandMenu, url=brand.href),
title=brand.title,
summary=brand.about + ("\n\n[" + brand.schedule + "]" if brand.schedule else ''),
thumb=Resource.ContentsOfURLWithFallback(url=brand.big_thumb, fallback=brand.small_thumb),
))
return oc
@route(PREFIX+'/brand')
def BrandMenu(url):
brand = SharedCodeService.vgtrk.brand_detail(url)
if brand.video_href:
return VideoViewTypePictureMenu(brand.video_href)
@route(PREFIX+'/video/viewtype-picture')
def VideoViewTypePictureMenu(url, page=1, referer=None, page_title=None, next_title=None):
videos = SharedCodeService.vgtrk.video_menu(url, page=page, referer=referer, page_title=page_title, next_title=next_title)
video_items = videos.view_type('picture')
oc = ObjectContainer(title1=videos.title)
for video in video_items.list:
oc.add(MetadataRecordForItem(video))
next_page = video_items.next_page
if next_page is not None:
oc.add(NextPageObject(
key=Callback(
VideoViewTypePictureMenu,
url=next_page.href,
page=int(page) + 1,
referer=url if referer is None else referer,
page_title=videos.title,
next_title=next_page.title
),
title=next_page.title,
))
return oc
@route(PREFIX+'/video/viewtype-picture/children')
def VideoViewTypePictureChildren(url, referer=None, page_title=None):
video_items = SharedCodeService.vgtrk.video_children(url, referer=referer, page_title=page_title)
oc = ObjectContainer(title1=page_title)
for video in video_items.list:
oc.add(EpisodeObjectForItem(video))
return oc
def MetadataRecordForItem(video):
if video.has_children:
return DirectoryObject(
key=Callback(VideoViewTypePictureChildren, url=video.ajaxurl, referer=video.href, page_title=video.title),
title=video.title,
thumb=video.thumb,
)
return EpisodeObjectForItem(video)
def EpisodeObjectForItem(video):
callback = Callback(MetadataObjectForURL, href=video.href, thumb=video.thumb, title=video.title)
return EpisodeObject(
key=callback,
rating_key=video.href,
title=video.title,
thumb=video.thumb,
items=MediaObjectsForURL(callback),
)
def MetadataObjectForURL(href, thumb, title, **kwargs):
# This is a sort-of replacement for the similar method from the URL Services, just different parameters list.
page = SharedCodeService.vgtrk.video_page(href)
video_clip_object = VideoClipObject(
key=Callback(MetadataObjectForURL, href=href, thumb=thumb, title=title, **kwargs),
rating_key=href,
title=title,
thumb=thumb,
summary=page.full_text,
items=MediaObjectsForURL(
Callback(PlayVideo, href=href)
),
**kwargs
)
return ObjectContainer(
no_cache=True,
objects=[video_clip_object]
)
def MediaObjectsForURL(callback):
# This is a sort-of replacement for the similar method from the URL Services, just different parameters list.
return [
MediaObject(
container=Container.MP4,
video_codec=VideoCodec.H264,
audio_codec=AudioCodec.AAC,
parts=[
PartObject(key=callback)
]
)
]
@indirect
def PlayVideo(href):
page = SharedCodeService.vgtrk.video_page(href)
json = JSON.ObjectFromURL(page.datavideo_href, headers={'Referer': page.video_iframe_href})
medialist = json['data']['playlist']['medialist']
if len(medialist) > 1:
raise RuntimeWarning('More than one media found, each should have been set as a PartObject!')
quality = str(json['data']['playlist']['priority_quality'])
transport = 'http'
if 'sources' not in medialist[0] and medialist[0]['errors']:
raise Ex.PlexNonCriticalError(2005, medialist[0]['errors'])
video_url = medialist[0]['sources'][transport][quality]
Log('Redirecting to video URL: %s' % video_url)
return IndirectResponse(
VideoClipObject,
key=video_url,
http_headers={'Referer': page.video_iframe_href},
metadata_kwargs={'summary': page.full_text}
)
|
class Solution(object):
def connect(self, root):
"""
:type root: TreeLinkNode
:rtype: nothing
"""
if root == None:
return
p = root.next
while p:
if p.left != None:
p = p.left
break
elif p.right != None:
p = p.right
break
p = p.next
if (root.right != None):
root.right.next = p
if(root.left != None):
if root.right != None:
root.left.next = root.right
else:
root.left.next = p
self.connect(root.right)
self.connect(root.left)
|
'''
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
'''
# 2018-6-17
# Valid Parenthese
# 栈
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
pars = [None]
parmap = {')': '(', '}': '{', ']': '['}
for c in s:
print(c,pars)
if c in parmap and parmap[c] == pars[len(pars)-1]:
pars.pop()
else:
pars.append(c)
return len(pars) == 1
# test
s = ")(([])[]{}"
test = Solution()
res = test.isValid(s)
print(res) |
# Tuples
coordinates = (4, 5) # Cant be changed or modified
print(coordinates[1])
# coordinates[1] = 10
# print(coordinates[1])
|
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Compiles trivial C++ program using Goma.
Intended to be used as a very simple litmus test of Goma health on LUCI staging
environment. Linux and OSX only.
"""
DEPS = [
'build/goma',
'recipe_engine/context',
'recipe_engine/file',
'recipe_engine/path',
'recipe_engine/platform',
'recipe_engine/properties',
'recipe_engine/step',
'recipe_engine/time',
]
HELLO_WORLD_CPP = """
#include <iostream>
int get_number();
int main() {
std::cout << "Hello, world!" << std::endl;
std::cout << "Non-static part " << get_number() << std::endl;
return 0;
}
"""
MODULE_CPP = """
int get_number() {
return %(time)d;
}
"""
def RunSteps(api):
root_dir = api.path['tmp_base']
# TODO(vadimsh): We need to somehow pull clang binaries and use them instead
# of system-provided g++. Otherwise Goma may fall back to local execution,
# since system-provided g++ may not be whitelisted in Goma.
# One static object file and one "dynamic", to test cache hit and cache miss.
source_code = {
'hello_world.cpp': HELLO_WORLD_CPP,
'module.cpp': MODULE_CPP % {'time': int(api.time.time())},
}
for name, data in sorted(source_code.items()):
api.file.write_text('write %s' % name, root_dir.join(name), data)
api.goma.ensure_goma(client_type='candidate')
api.goma.start()
gomacc = api.goma.goma_dir.join('gomacc')
out = root_dir.join('compiled_binary')
build_exit_status = None
try:
# We want goma proxy to actually hit the backends, so disable fallback to
# the local compiler.
gomacc_env = {
'GOMA_USE_LOCAL': 'false',
'GOMA_FALLBACK': 'false',
}
with api.context(env=gomacc_env):
objs = []
for name in sorted(source_code):
obj = root_dir.join(name.replace('.cpp', '.o'))
api.step(
'compile %s' % name,
[gomacc, 'g++', '-c', root_dir.join(name), '-o', obj])
objs.append(obj)
api.step('link', [gomacc, 'g++', '-o', out] + objs)
build_exit_status = 0
except api.step.StepFailure as e:
build_exit_status = e.retcode
raise e
finally:
api.goma.stop(build_exit_status=build_exit_status)
api.step('run', [out])
def GenTests(api):
yield (
api.test('linux') +
api.platform.name('linux') +
api.properties.generic(
buildername='test_builder',
mastername='test_master'))
yield (
api.test('linux_fail') +
api.platform.name('linux') +
api.properties.generic(
buildername='test_builder',
mastername='test_master') +
api.step_data('link', retcode=1))
|
# ###########################################################
# ## generate menu
# ###########################################################
_a = request.application
_c = request.controller
_f = request.function
response.title = '%s %s' % (_f, '/'.join(request.args))
response.subtitle = 'admin'
response.menu = [(T('site'), _f == 'site', URL(_a,'default','site'))]
if request.args:
_t = request.args[0]
response.menu.append((T('edit'), _c == 'default' and _f == 'design',
URL(_a,'default','design',args=_t)))
response.menu.append((T('about'), _c == 'default' and _f == 'about',
URL(_a,'default','about',args=_t)))
response.menu.append((T('errors'), _c == 'default' and _f == 'errors',
URL(_a,'default','errors',args=_t)))
response.menu.append((T('versioning'),
_c == 'mercurial' and _f == 'commit',
URL(_a,'mercurial','commit',args=_t)))
if not session.authorized:
response.menu = [(T('login'), True, '')]
else:
response.menu.append((T('logout'), False,
URL(_a,'default',f='logout')))
response.menu.append((T('help'), False, URL('examples','default','index')))
|
__author__ = 'sibirrer'
# this file contains a class to make a Moffat profile
__all__ = ['Moffat']
class Moffat(object):
"""
this class contains functions to evaluate a Moffat surface brightness profile
.. math::
I(r) = I_0 * (1 + (r/\\alpha)^2)^{-\\beta}
with :math:`I_0 = amp`.
"""
def __init__(self):
self.param_names = ['amp', 'alpha', 'beta', 'center_x', 'center_y']
self.lower_limit_default = {'amp': 0, 'alpha': 0, 'beta': 0, 'center_x': -100, 'center_y': -100}
self.upper_limit_default = {'amp': 100, 'alpha': 10, 'beta': 10, 'center_x': 100, 'center_y': 100}
def function(self, x, y, amp, alpha, beta, center_x=0, center_y=0):
"""
2D Moffat profile
:param x: x-position (angle)
:param y: y-position (angle)
:param amp: normalization
:param alpha: scale
:param beta: exponent
:param center_x: x-center
:param center_y: y-center
:return: surface brightness
"""
x_shift = x - center_x
y_shift = y - center_y
return amp * (1. + (x_shift**2+y_shift**2)/alpha**2)**(-beta)
|
tempratures = [10,-20, -289, 100]
def c_to_f(c):
if c<-273.15:
return ""
return c* 9/5 +32
def writeToFile(input):
with open("output.txt","a") as file:
file.write(input)
for temp in tempratures:
writeToFile(str(c_to_f(temp)))
|
class VoiceClient(object):
def __init__(self, base_obj):
self.base_obj = base_obj
self.api_resource = "/voice/v1/{}"
def create(self,
direction,
to,
caller_id,
execution_logic,
reference_logic='',
country_iso2='us',
technology='pstn',
status_callback_uri=''):
api_resource = self.api_resource.format(direction)
return self.base_obj.post(api_resource=api_resource, direction=direction, to=to,
caller_id=caller_id, execution_logic=execution_logic, reference_logic=reference_logic,
country_iso2=country_iso2, technology=technology, status_callback_uri=status_callback_uri)
def update(self, reference_id, execution_logic):
api_resource = self.api_resource.format(reference_id)
return self.base_obj.put(api_resource=api_resource,
execution_logic=execution_logic)
def delete(self, reference_id):
api_resource = self.api_resource.format(reference_id)
return self.base_obj.delete(api_resource=api_resource)
def get_status(self, reference_id):
api_resource = self.api_resource.format(reference_id)
return self.base_obj.get(api_resource=api_resource)
|
class Solution(object):
def _dfs(self,num,res,n):
if num>n:
return
res.append(num)
num=num*10
if num<=n:
for i in xrange(10):
self._dfs(num+i,res,n)
def sovleOn(self,n):
res=[]
cur=1
for i in xrange(1,n+1):
res.append(cur)
if cur*10<=n:
cur=cur*10
# if the num not end with 9,plus 1
# since if 19 the next should 2 not 20
elif cur%10!=9 and cur+1<=n:
cur+=1
else:
# get the 199--2 499--5
while (cur/10)%10==9:
cur/=10
cur=cur/10+1
return res
def lexicalOrder(self, n):
"""
:type n: int
:rtype: List[int]
"""
return self.sovleOn(n)
res=[]
for i in xrange(1,10):
self._dfs(i,res,n)
return res |
expected_output = {
"ospf-statistics-information": {
"ospf-statistics": {
"dbds-retransmit": "203656",
"dbds-retransmit-5seconds": "0",
"flood-queue-depth": "0",
"lsas-acknowledged": "225554974",
"lsas-acknowledged-5seconds": "0",
"lsas-flooded": "66582263",
"lsas-flooded-5seconds": "0",
"lsas-high-prio-flooded": "375568998",
"lsas-high-prio-flooded-5seconds": "0",
"lsas-nbr-transmit": "3423982",
"lsas-nbr-transmit-5seconds": "0",
"lsas-requested": "3517",
"lsas-requested-5seconds": "0",
"lsas-retransmit": "8064643",
"lsas-retransmit-5seconds": "0",
"ospf-errors": {
"subnet-mismatch-error": "12"
},
"packet-statistics": [
{
"ospf-packet-type": "Hello",
"packets-received": "5703920",
"packets-received-5seconds": "3",
"packets-sent": "6202169",
"packets-sent-5seconds": "0"
},
{
"ospf-packet-type": "DbD",
"packets-received": "185459",
"packets-received-5seconds": "0",
"packets-sent": "212983",
"packets-sent-5seconds": "0"
},
{
"ospf-packet-type": "LSReq",
"packets-received": "208",
"packets-received-5seconds": "0",
"packets-sent": "214",
"packets-sent-5seconds": "0"
},
{
"ospf-packet-type": "LSUpdate",
"packets-received": "16742100",
"packets-received-5seconds": "0",
"packets-sent": "15671465",
"packets-sent-5seconds": "0"
},
{
"ospf-packet-type": "LSAck",
"packets-received": "2964236",
"packets-received-5seconds": "0",
"packets-sent": "5229203",
"packets-sent-5seconds": "0"
}
],
"total-database-summaries": "0",
"total-linkstate-request": "0",
"total-retransmits": "0"
}
}
}
|
# coding: gbk
"""
@author: sdy
@email: sdy@epri.sgcc.com.cn
Abstract distribution and generation class
"""
class ADG(object):
def __init__(self, work_path, fmt):
self.work_path = work_path
self.fmt = fmt
self.features = None
self.mode = 'all'
def distribution_assess(self):
raise NotImplementedError
def generate_all(self):
raise NotImplementedError
def choose_samples(self, size):
raise NotImplementedError
def generate_one(self, power, idx, out_path):
raise NotImplementedError
def remove_samples(self):
raise NotImplementedError
def done(self):
raise NotImplementedError
|
"""
This file must be kept up-to-date with Stripe, especially the slugs:
https://manage.stripe.com/plans
"""
PLANS = {}
class Plan(object):
def __init__(self, value, slug, display):
self.value = value
self.slug = slug
self.display = display
PLANS[slug] = self
FREE = Plan(1, 'free', "Free plan")
|
N = int(input())
S = input()
if N % 2 == 1:
print('No')
exit()
if S[:N // 2] == S[N // 2:]:
print('Yes')
else:
print('No')
|
#!/usr/bin/env python
#
# Cloudlet Infrastructure for Mobile Computing
# - Task Assistance
#
# Author: Zhuo Chen <zhuoc@cs.cmu.edu>
#
# Copyright (C) 2011-2013 Carnegie Mellon University
# 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.
#
# If True, configurations are set to process video stream in real-time (use
# with lego_server.py)
# If False, configurations are set to process one independent image (use with
# img.py)
IS_STREAMING = True
RECOGNIZE_ONLY = False
# Port for communication between proxy and task server
TASK_SERVER_PORT = 6090
BEST_ENGINE = "LEGO_FAST"
CHECK_ALGORITHM = "table"
CHECK_LAST_TH = 1
# Port for communication between master and workder proxies
MASTER_SERVER_PORT = 6091
# Whether or not to save the displayed image in a temporary directory
SAVE_IMAGE = False
# Convert all incoming frames to a fixed size to ease processing
IMAGE_HEIGHT = 360
IMAGE_WIDTH = 640
BLUR_KERNEL_SIZE = int(IMAGE_WIDTH // 16 + 1)
# Display
DISPLAY_MAX_PIXEL = 640
DISPLAY_SCALE = 5
DISPLAY_LIST_ALL = ['test', 'input', 'DoB', 'mask_black', 'mask_black_dots',
'board', 'board_border_line', 'board_edge', 'board_grey',
'board_mask_black', 'board_mask_black_dots', 'board_DoB',
'edge_inv',
'edge',
'board_n0', 'board_n1', 'board_n2', 'board_n3', 'board_n4',
'board_n5', 'board_n6',
'lego_u_edge_S', 'lego_u_edge_norm_L', 'lego_u_dots_L',
'lego_full', 'lego', 'lego_only_color',
'lego_correct', 'lego_rect', 'lego_cropped', 'lego_color',
'plot_line', 'lego_syn',
'guidance']
DISPLAY_LIST_TEST = ['input', 'board', 'lego_u_edge_S', 'lego_u_edge_norm_L',
'lego_u_dots_L', 'lego_syn']
DISPLAY_LIST_STREAM = ['input', 'lego_syn']
# DISPLAY_LIST_TASK = ['input', 'board', 'lego_syn', 'guidance']
DISPLAY_LIST_TASK = []
if not IS_STREAMING:
DISPLAY_LIST = DISPLAY_LIST_TEST
else:
if RECOGNIZE_ONLY:
DISPLAY_LIST = DISPLAY_LIST_STREAM
else:
DISPLAY_LIST = DISPLAY_LIST_TASK
DISPLAY_WAIT_TIME = 1 if IS_STREAMING else 500
## Black dots
BD_COUNT_N_ROW = 9
BD_COUNT_N_COL = 16
BD_BLOCK_HEIGHT = IMAGE_HEIGHT // BD_COUNT_N_ROW
BD_BLOCK_WIDTH = IMAGE_WIDTH // BD_COUNT_N_COL
BD_BLOCK_SPAN = max(BD_BLOCK_HEIGHT, BD_BLOCK_WIDTH)
BD_BLOCK_AREA = BD_BLOCK_HEIGHT * BD_BLOCK_WIDTH
BD_COUNT_THRESH = 25
BD_MAX_PERI = (IMAGE_HEIGHT + IMAGE_HEIGHT) // 40
BD_MAX_SPAN = int(BD_MAX_PERI / 4.0 + 0.5)
# Two ways to check black dot size:
# 'simple': check contour length and area
# 'complete": check x & y max span also
CHECK_BD_SIZE = 'simple'
## Color detection
# H: hue, S: saturation, V: value (which means brightness)
# L: lower_bound, U: upper_bound, TH: threshold
# TODO:
BLUE = {'H': 110, 'S_L': 100, 'B_TH': 110} # H: 108
YELLOW = {'H': 30, 'S_L': 100, 'B_TH': 170} # H: 25 B_TH: 180
GREEN = {'H': 70, 'S_L': 100, 'B_TH': 60} # H: 80 B_TH: 75
RED = {'H': 0, 'S_L': 100, 'B_TH': 130}
BLACK = {'S_U': 70, 'V_U': 60}
# WHITE = {'S_U' : 60, 'B_L' : 101, 'B_TH' : 160} # this includes side white,
# too
WHITE = {'S_U': 60, 'V_L': 150}
BD_DOB_MIN_V = 30
# If using a labels to represent color, this is the right color: 0 means
# nothing (background) and 7 means unsure
COLOR_ORDER = ['nothing', 'white', 'green', 'yellow', 'red', 'blue', 'black',
'unsure']
## Board
BOARD_MIN_AREA = BD_BLOCK_AREA * 7
BOARD_MIN_LINE_LENGTH = BD_BLOCK_SPAN
BOARD_MIN_VOTE = BD_BLOCK_SPAN // 2
# Once board is detected, convert it to a perspective-corrected standard size
# for further processing
BOARD_RECONSTRUCT_HEIGHT = 155 * 1
BOARD_RECONSTRUCT_WIDTH = 270 * 1
BOARD_BD_MAX_PERI = (BOARD_RECONSTRUCT_HEIGHT + BOARD_RECONSTRUCT_WIDTH) // 30
BOARD_BD_MAX_SPAN = int(BOARD_BD_MAX_PERI / 4.0 + 1.5)
BOARD_RECONSTRUCT_AREA = BOARD_RECONSTRUCT_HEIGHT * BOARD_RECONSTRUCT_WIDTH
BOARD_RECONSTRUCT_PERI = (
BOARD_RECONSTRUCT_HEIGHT +
BOARD_RECONSTRUCT_WIDTH) * 2
BOARD_RECONSTRUCT_CENTER = (
BOARD_RECONSTRUCT_HEIGHT // 2, BOARD_RECONSTRUCT_WIDTH // 2)
## Bricks
BRICK_HEIGHT = BOARD_RECONSTRUCT_HEIGHT / 12.25 # magic number
BRICK_WIDTH = BOARD_RECONSTRUCT_WIDTH / 26.2 # magic number
BRICK_HEIGHT_THICKNESS_RATIO = 15 / 12.25 # magic number
BLOCK_DETECTION_OFFSET = 2
BRICK_MIN_BM_RATIO = .85
## Optimizations
# If True, performs a second step fine-grained board detection algorithm.
# Depending on the other algorithms, this is usually not needed.
OPT_FINE_BOARD = False
# Treat background pixels differently
OPT_NOTHING = False
BM_WINDOW_MIN_TIME = 0.1
BM_WINDOW_MIN_COUNT = 1
# The percentage of right pixels in each block must be higher than this
# threshold
WORST_RATIO_BLOCK_THRESH = 0.6
# If True, do perspective correction first, then color normalization
# If False, do perspective correction after color has been normalized
# Not used anymore...
PERS_NORM = True
## Consts
ACTION_ADD = 0
ACTION_REMOVE = 1
ACTION_TARGET = 2
ACTION_MOVE = 3
DIRECTION_NONE = 0
DIRECTION_UP = 1
DIRECTION_DOWN = 2
GOOD_WORDS = ["Excellent. ", "Great. ", "Good job. ", "Wonderful. "]
def setup(is_streaming):
global IS_STREAMING, DISPLAY_LIST, DISPLAY_WAIT_TIME, SAVE_IMAGE
IS_STREAMING = is_streaming
if not IS_STREAMING:
DISPLAY_LIST = DISPLAY_LIST_TEST
else:
if RECOGNIZE_ONLY:
DISPLAY_LIST = DISPLAY_LIST_STREAM
else:
DISPLAY_LIST = DISPLAY_LIST_TASK
DISPLAY_WAIT_TIME = 1 if IS_STREAMING else 500
SAVE_IMAGE = not IS_STREAMING
|
class Node():
def __init__(self, value=None):
self.children = []
self.parent = None
self.value = value
def add_child(self, node):
if type(node).__name__ == 'Node':
node.parent = self
self.children.append(node)
else:
raise ValueError
def get_parent(self):
return self.parent.value if self.parent else 'root' |
"""Hamming Distance from Exercism"""
def distance(strand_a, strand_b):
"""Determine the hamming distance between two RNA strings
param: str strand_a
param: str strand_b
return: int calculation of the hamming distance between strand_a and strand_b
"""
if len(strand_a) != len(strand_b):
raise ValueError("Strands must be of equal length.")
distance = 0
for i, _ in enumerate(strand_a):
if strand_a[i] != strand_b[i]:
distance += 1
return distance
|
#def spam():
# eggs = 31337
#spam()
#print(eggs)
"""
def spam():
eggs = 98
bacon()
print(eggs)
def bacon():
ham = 101
eggs = 0
spam()
"""
"""
# Global variables can be read from local scope.
def spam():
print(eggs)
eggs = 42
spam()
print(eggs)
"""
"""
# Local and global variables with the same name.
def spam():
eggs = 'spam local'
print(eggs) # prints 'spam local'
def bacon():
eggs = 'bacon local'
print(eggs) # prints 'bacon local'
spam()
print(eggs) # prints 'bacon local'
eggs = 'global'
bacon()
print(eggs) # prints 'global'
"""
"""
# the global statement
def spam():
global eggs
eggs = 'spam'
eggs = 'it don\'t matter'
spam()
print(eggs)
"""
"""
def spam():
global eggs
eggs = 'spam' # this is the global
def bacon():
eggs = 'bacon' # this is a local
def ham():
print(eggs) # this is the global
eggs = 42 # this is global
spam()
print(eggs)
"""
# Python will not fall back to using the global eggs variable
def spam():
eggs = 'wha??'
print(eggs) # ERROR!
eggs = 'spam local'
eggs = 'global'
spam()
# This error happens because Python sees that there is an assignment statement for eggs in the spam() function and therefore considers eggs to be local. Because print(eggs) is executed before eggs is assigned anything, the local variable eggs doesn't exist.
|
# https://leetcode.com/problems/minimum-moves-to-equal-array-elements/
# Explanation: https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/93817/It-is-a-math-question
# Source: https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/272994/Python-Greedy-Sum-Min*Len
class Solution:
def minMoves(self, nums: List[int]) -> int:
return sum(nums) - min(nums)*len(nums) |
# Given two binary strings, return their sum (also a binary string).
#
# For example,
# a = "11"
# b = "1"
# Return "100".
class Solution:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
la = len(a)
lb = len(b)
if la >= lb:
length = la
else:
length = lb
digits = []
addition = 0
for x in range(1, length + 1):
if x > la:
an = 0
else:
an = int(a[-x])
if x > lb:
bn = 0
else:
bn = int(b[-x])
res = an + bn + addition
if res == 3:
digits.append("1")
addition = 1
elif res == 2:
digits.append("0")
addition = 1
elif res == 1:
digits.append("1")
addition = 0
elif res == 0:
digits.append("0")
addition = 0
if addition != 0:
digits.append(str(addition))
digits.reverse()
return "".join(digits)
s = Solution()
print(s.addBinary("0", "0"))
# print(s.addBinary("11", "1"))
|
# Event: LCCS Python Fundamental Skills Workshop
# Date: Dec 2018
# Author: Joe English, PDST
# eMail: computerscience@pdst.ie
# Purpose: To find (and fix) two syntax errors
# A program to display Green Eggs and Ham (v4)
def showChorus():
print()
print("I do not like green eggs and ham.")
print("I do not like them Sam-I-am.")
print()
def showVerse1():
print("I do not like them here or there.")
print("I do not like them anywhere.")
print("I do not like them in a house")
print("I do not like them with a mouse")
def displayVerse2():
print("I do not like them in a box")
print("I do not like them with a fox")
print("I will not eat them in the rain.")
print("I will not eat them on a train")
# Program execution starts here
showChorus()
displayVerse1() # SYNTAX ERROR 1 - function 'displayVerse1' does not exist
showChorus()
showVerse2() # SYNTAX ERROR 2 - function 'showVerse2' does not exist
showChorus()
|
_base_ = [
'../_base_/models/repdet_repvgg_pafpn.py',
'../_base_/datasets/coco_detection.py',
'../_base_/schedules/schedule_poly.py', '../_base_/default_runtime.py'
]
# model settings
model = dict(
type='RepDet',
pretrained='/data/kartikes/repvgg_models/repvgg_b1g2.pth',
backbone=dict(
type='RepVGG',
arch='B1g2',
out_stages=[1, 2, 3, 4],
activation='ReLU',
last_channel=1024,
deploy=False),
neck=dict(
type='NanoPAN',
in_channels=[128, 256, 512, 1024],
out_channels=256,
num_outs=5,
start_level=1,
add_extra_convs='on_input'),
bbox_head=dict(
type='NanoDetHead',
num_classes=80,
in_channels=256,
stacked_convs=2,
feat_channels=256,
share_cls_reg=True,
reg_max=10,
norm_cfg=dict(type='BN', requires_grad=True),
anchor_generator=dict(
type='AnchorGenerator',
ratios=[1.0],
octave_base_scale=8,
scales_per_octave=1,
strides=[8, 16, 32]),
loss_cls=dict(
type='QualityFocalLoss',
use_sigmoid=True,
beta=2.0,
loss_weight=1.0),
loss_dfl=dict(type='DistributionFocalLoss', loss_weight=0.25),
loss_bbox=dict(type='GIoULoss', loss_weight=2.0))
)
optimizer = dict(type='SGD', lr=0.025, momentum=0.9, weight_decay=0.0001)
data = dict(
samples_per_gpu=4,
workers_per_gpu=2)
find_unused_parameters=True
runner = dict(type='EpochBasedRunner', max_epochs=12)
|
# Holy Stone - Holy Ground at the Snowfield (3rd job)
questIDs = [1431, 1432, 1433, 1435, 1436, 1437, 1439, 1440, 1442, 1443, 1445, 1446, 1447, 1448]
hasQuest = False
for qid in questIDs:
if sm.hasQuest(qid):
hasQuest = True
break
if hasQuest:
if sm.sendAskYesNo("#b(A mysterious energy surrounds this stone. Do you want to investigate?)"):
sm.warpInstanceIn(910540000, 0)
else:
sm.sendSayOkay("#b(A mysterious energy surrounds this stone)#k")
|
class CustomException(Exception):
def __init__(self, *args, **kwargs):
return super().__init__(self, *args, **kwargs)
def __str__(self):
return str(self.args [1])
class DeprecatedException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class DailyLimitException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class InvalidArgumentException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class IdOrAuthEmptyException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class NotFoundException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class NotSupported(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class SessionLimitException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class WrongCredentials(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class PaladinsOnlyException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class SmiteOnlyException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class RealmRoyaleOnlyException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class PlayerNotFoundException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class GetMatchPlayerDetailsException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class UnexpectedException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class RequestErrorException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
|
class solutionLeetcode_3:
def lengthOfLongestSubstring(self, s: str) -> (int, str):
if not s:
return 0
left = 0
lookup = set()
n = len(s)
max_len = 0
cur_len = 0
for i in range(n):
cur_len += 1
while s[i] in lookup:
lookup.remove(s[left])
left += 1
cur_len -= 1
if cur_len > max_len:
max_len = cur_len
lookup.add(s[i])
longestSubstring = s[left:left+max_len+1]
return max_len, longestSubstring
class solutionLeetcode_4:
def findMedianSortedArrays(self, nums1, nums2):
nums1.extend(nums2)
nums1.sort()
if len(nums1) % 2 == 0:
return sum(nums1[[len(nums1)//2]-1:len(nums1)//2+1])/2 # // is int division.
else:
return nums1[(len(nums1)-1)//2]
class solutionLeetcode_5:
def longestPalindrome(self, s):
str_length = len(s)
max_length = 0
start = 0
for i in range(str_length):
if i - max_length >= 1 and s[i - max_length - 1:i + 2] == s[i - max_length - 1:i+2][::-1]:
start = i - max_length - 1
max_length += 2
continue
if i - max_length >= 0 and s[i - max_length:i + 2] == s[i - max_length:i + 2][::-1]:
start = i - max_length
max_length += 1
return s[start:start + max_length + 1]
class solutionLeetcode_6:
def convert(self, s:str, numRows:int) -> list:
if numRows < 2:
return s
res = ["" for _ in range(numRows)] # "" stands for string
i, flag = 0, -1
for c in s:
res[i] += c
if i == 0 or i == numRows - 1:
flag = -flag
i += flag
return "".join(res)
class solutionLeetcode_7:
def reverse(self, x) -> int:
s = str(x)[::-1].strip('-') # use extended slices to reverse a string.
if int(s) < 2**31:
if x >= 0:
return int(s)
else:
return 0 - int(s)
return 0
class solutionLeetcode_8:
def myAtoi(self, str: str) -> int:
validChar = ['-', '+', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
validNumber = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
if len(str) == 0:
return 0
startIndex = -1
endIndex = 0
initialChar = True
lastEntryValid = True
stringChar = ''
for i in range(len(str)):
if str[i] == ' ' and initialChar:
continue
if (str[i] not in validChar) and initialChar:
return 0
if (str[i] in validChar) and initialChar:
initialChar = False
startIndex = i
if i == len(str) - 1:
if str[i] in ['-', '+']:
return 0
else:
return int(str)
if (i < len(str) - 1) and (str[i + 1] not in validNumber):
if str[i] in ['-', '+']:
return 0
else:
return int(str[i])
continue
if (str[i] not in validNumber) and (not initialChar):
endIndex = i
lastEntryValid = False
break
if startIndex == -1:
return 0
if lastEntryValid:
endIndex = len(str)
numberStr = str[startIndex:endIndex]
resultNumber = int(numberStr)
if resultNumber >= 2 ** 31:
return 2 ** 31 - 1
elif resultNumber <= -2 ** 31:
return -2 ** 31
else:
return resultNumber
class solutionLeetcode_10:
def isMatch(self, text: str, pattern: str) -> bool:
if not pattern:
return not text
firstMatch = bool(text) and pattern[0] in {text[0], '.'}
if len(pattern) >= 2 and pattern[1] == '*':
return self.isMatch(text, pattern[2:]) or (firstMatch and self.isMatch(text[1:], pattern))
else:
return firstMatch and self.isMatch(text[1:], pattern[1:])
class solutionLeetcode_11:
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
maxArea = 0
left = 0
right = len(height) - 1
while left < right:
area = (right - left) * min(height[left], height[right])
if maxArea < area:
maxArea = area
if height[left] < height[right]:
left += 1
else:
right -=1
return maxArea
|
# Árvore Huffman
class node:
def __init__(self, freq, symbol, left=None, right=None):
# Frequência do Símbolo
self.freq = freq
# Símbolo (caracter)
self.symbol = symbol
# nó à esquerda do nó atual
self.left = left
# nó à direita do nó atual
self.right = right
# direção da árvore (0/1)
self.huff = ''
# Função utilitária para imprimir
# códigos huffman para todos os símbolos
# na nova árvore huffman que sera criada
def printNodes(node, val=''):
# código huffman para o nó atual
newVal = val + str(node.huff)
# se o nó não pertence á ponta da
# árvore então caminha dentro do mesmo
# até a ponta
if(node.left):
printNodes(node.left, newVal)
if(node.right):
printNodes(node.right, newVal)
# Se o nó estiver na ponta da árore
# então exibe o código huffman
if(not node.left and not node.right):
print(f"{node.symbol} -> {newVal}")
# caracteres para à árvore huffman
chars = ['a', 'b', 'c', 'd', 'e', 'f']
# frequência dos caracteres
freq = [5, 9, 12, 13, 16, 45]
# lista contendo os nós não utilizados
nodes = []
if __name__ == '__main__':
# convertendo caracteres e frequência em
# nós da árvore huffman
for x in range(len(chars)):
nodes.append(node(freq[x], chars[x]))
while len(nodes) > 1:
# Ordena todos os nós de forma ascendente
# baseado em sua frequência
nodes = sorted(nodes, key=lambda x: x.freq)
# Seleciona os dois nós menores
left = nodes[0]
right = nodes[1]
# Atribui um valor direcional à estes nós
# (direita ou esquerda)
left.huff = 0
right.huff = 1
# Combina os 2 nós menores para um novo nó pai
# para eles.
newNode = node(
left.freq +
right.freq,
left.symbol +
right.symbol,
left,
right)
# remove os 2 nós e adiciona o nó pai
# como um novo só sobre os outros
nodes.remove(left)
nodes.remove(right)
nodes.append(newNode)
# Árvore Huffman pronta!
printNodes(nodes[0])
|
#==============================================================================
# Copyright 2011 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#==============================================================================
class BuildError(Exception):
"""
Base exception for errors raised while building
"""
pass
class NoSuchConfigSetError(BuildError):
"""
Exception signifying no config error with specified name exists
"""
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class NoSuchConfigurationError(BuildError):
"""
Exception signifying no config error with specified name exists
"""
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class CircularConfigSetDependencyError(BuildError):
"""
Exception signifying circular dependency in configSets
"""
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class ToolError(BuildError):
"""
Exception raised by Tools when they cannot successfully change reality
Attributes:
msg - a human-readable error message
code - an error code, if applicable
"""
def __init__(self, msg, code=None):
self.msg = msg
self.code = code
def __str__(self):
if (self.code):
return '%s (return code %s)' % (self.msg, self.code)
else:
return self.msg
|
#!/usr/bin/env python
# encoding: utf-8
"""
@Author: yangwenhao
@Contact: 874681044@qq.com
@Software: PyCharm
@File: __init__.py.py
@Time: 2020/3/27 10:43 AM
@Overview:
"""
|
def f(x):
if x <= -2:
f = 1 - (x + 2)**2
return f
if -2 < x <= 2:
f = -(x/2)
return f
if 2 < x:
f = (x - 2)**2 + 1
return f
x = int(input())
print(f(x))
|
dnas = [
['jVXfX<', 37, 64, 24.67, 14, 7, -4.53, {'ott_len': 42, 'ott_percent': 508, 'stop_loss': 263, 'risk_reward': 65, 'chop_rsi_len': 31, 'chop_bandwidth': 83}],
['o:JK9p', 50, 62, 32.74, 37, 8, -0.2, {'ott_len': 45, 'ott_percent': 259, 'stop_loss': 201, 'risk_reward': 41, 'chop_rsi_len': 12, 'chop_bandwidth': 274}],
['tGVME/', 35, 74, 20.06, 20, 10, -4.75, {'ott_len': 48, 'ott_percent': 375, 'stop_loss': 254, 'risk_reward': 43, 'chop_rsi_len': 20, 'chop_bandwidth': 36}],
['a<<sMo', 59, 27, 25.74, 33, 6, -1.06, {'ott_len': 36, 'ott_percent': 277, 'stop_loss': 139, 'risk_reward': 76, 'chop_rsi_len': 24, 'chop_bandwidth': 271}],
['`Ol@gL', 29, 65, 9.47, 25, 8, -2.95, {'ott_len': 36, 'ott_percent': 446, 'stop_loss': 351, 'risk_reward': 31, 'chop_rsi_len': 40, 'chop_bandwidth': 142}],
['SWJi?Y', 36, 73, 32.8, 37, 8, -0.92, {'ott_len': 28, 'ott_percent': 516, 'stop_loss': 201, 'risk_reward': 68, 'chop_rsi_len': 16, 'chop_bandwidth': 190}],
['v@WLkU', 46, 47, 45.51, 20, 10, -4.43, {'ott_len': 49, 'ott_percent': 313, 'stop_loss': 258, 'risk_reward': 42, 'chop_rsi_len': 43, 'chop_bandwidth': 175}],
['lR\\iHN', 38, 62, 35.84, 28, 7, -4.01, {'ott_len': 43, 'ott_percent': 472, 'stop_loss': 280, 'risk_reward': 68, 'chop_rsi_len': 21, 'chop_bandwidth': 149}],
['l7\\gc^', 60, 35, 42.7, 25, 8, -1.2, {'ott_len': 43, 'ott_percent': 233, 'stop_loss': 280, 'risk_reward': 66, 'chop_rsi_len': 38, 'chop_bandwidth': 208}],
['wLXY\\1', 36, 71, 20.85, 14, 7, -4.76, {'ott_len': 50, 'ott_percent': 419, 'stop_loss': 263, 'risk_reward': 53, 'chop_rsi_len': 34, 'chop_bandwidth': 43}],
['i7nMgb', 54, 24, 28.38, 0, 4, -2.04, {'ott_len': 41, 'ott_percent': 233, 'stop_loss': 360, 'risk_reward': 43, 'chop_rsi_len': 40, 'chop_bandwidth': 223}],
['F/0eI[', 40, 154, 33.68, 42, 21, 2.91, {'ott_len': 20, 'ott_percent': 162, 'stop_loss': 85, 'risk_reward': 64, 'chop_rsi_len': 22, 'chop_bandwidth': 197}],
['\\ERgMp', 53, 28, 16.3, 33, 6, -2.59, {'ott_len': 33, 'ott_percent': 357, 'stop_loss': 236, 'risk_reward': 66, 'chop_rsi_len': 24, 'chop_bandwidth': 274}],
['_7@QqN', 44, 87, 28.24, 46, 15, 3.21, {'ott_len': 35, 'ott_percent': 233, 'stop_loss': 156, 'risk_reward': 46, 'chop_rsi_len': 46, 'chop_bandwidth': 149}],
['OEJO,F', 41, 105, 33.62, 20, 10, -4.61, {'ott_len': 25, 'ott_percent': 357, 'stop_loss': 201, 'risk_reward': 45, 'chop_rsi_len': 4, 'chop_bandwidth': 120}],
['5swn)a', 30, 86, 13.25, 8, 12, -6.03, {'ott_len': 9, 'ott_percent': 765, 'stop_loss': 400, 'risk_reward': 72, 'chop_rsi_len': 3, 'chop_bandwidth': 219}],
['4juD3[', 36, 95, 32.91, 14, 7, -3.13, {'ott_len': 8, 'ott_percent': 685, 'stop_loss': 391, 'risk_reward': 35, 'chop_rsi_len': 9, 'chop_bandwidth': 197}],
['91u6iJ', 33, 163, 31.1, 25, 27, -3.59, {'ott_len': 12, 'ott_percent': 180, 'stop_loss': 391, 'risk_reward': 22, 'chop_rsi_len': 41, 'chop_bandwidth': 135}],
['c3rg61', 39, 91, 11.05, 27, 11, -1.18, {'ott_len': 38, 'ott_percent': 197, 'stop_loss': 378, 'risk_reward': 66, 'chop_rsi_len': 11, 'chop_bandwidth': 43}],
['\\BAZGb', 40, 71, 22.33, 36, 11, -3.44, {'ott_len': 33, 'ott_percent': 330, 'stop_loss': 161, 'risk_reward': 54, 'chop_rsi_len': 21, 'chop_bandwidth': 223}],
['H<XF,l', 40, 98, 31.16, 16, 12, -5.22, {'ott_len': 21, 'ott_percent': 277, 'stop_loss': 263, 'risk_reward': 37, 'chop_rsi_len': 4, 'chop_bandwidth': 260}],
['5Bl/TL', 32, 153, 26.35, 28, 21, 0.03, {'ott_len': 9, 'ott_percent': 330, 'stop_loss': 351, 'risk_reward': 16, 'chop_rsi_len': 29, 'chop_bandwidth': 142}],
['DFRlX-', 38, 112, 21.16, 27, 11, -1.95, {'ott_len': 18, 'ott_percent': 366, 'stop_loss': 236, 'risk_reward': 70, 'chop_rsi_len': 31, 'chop_bandwidth': 28}],
['1EkquE', 33, 156, 45.58, 27, 18, -1.61, {'ott_len': 7, 'ott_percent': 357, 'stop_loss': 347, 'risk_reward': 75, 'chop_rsi_len': 49, 'chop_bandwidth': 116}],
['D9YmB.', 35, 139, 12.09, 42, 14, -1.17, {'ott_len': 18, 'ott_percent': 251, 'stop_loss': 267, 'risk_reward': 71, 'chop_rsi_len': 18, 'chop_bandwidth': 32}],
['_(KrZG', 40, 145, 18.09, 28, 21, -4.73, {'ott_len': 35, 'ott_percent': 100, 'stop_loss': 205, 'risk_reward': 76, 'chop_rsi_len': 32, 'chop_bandwidth': 124}],
['1CndgF', 34, 156, 49.82, 41, 17, 2.8, {'ott_len': 7, 'ott_percent': 339, 'stop_loss': 360, 'risk_reward': 63, 'chop_rsi_len': 40, 'chop_bandwidth': 120}],
['tutp,b', 50, 40, 52.45, 0, 5, -5.75, {'ott_len': 48, 'ott_percent': 782, 'stop_loss': 387, 'risk_reward': 74, 'chop_rsi_len': 4, 'chop_bandwidth': 223}],
['07t1iJ', 30, 199, 23.05, 26, 30, -1.64, {'ott_len': 6, 'ott_percent': 233, 'stop_loss': 387, 'risk_reward': 18, 'chop_rsi_len': 41, 'chop_bandwidth': 135}],
['75\\adC', 37, 200, 68.9, 21, 32, -4.78, {'ott_len': 10, 'ott_percent': 215, 'stop_loss': 280, 'risk_reward': 61, 'chop_rsi_len': 38, 'chop_bandwidth': 109}],
]
|
def createArray(dims) :
if len(dims) == 1:
return [0 for _ in range(dims[0])]
return [createArray(dims[1:]) for _ in range(dims[0])]
def f(A, x, y):
m = len(A)
for i in range(m):
if A[i][x] > A[i][y]:
return 0
return 1
class Solution(object):
def minDeletionSize(self, A):
"""
:type A: List[str]
:rtype: int
"""
n = len(A[0])
g = createArray([n, n])
for i in range(n):
for j in range(i+1, n):
g[i][j] = f(A, i, j)
dp = createArray([n])
for i in range(0, n):
dp[i] = 1
for j in range(0, i):
if g[j][i] == 1:
if dp[i] < dp[j] + 1:
dp[i] = dp[j] + 1
return n - max(dp)
|
lista = list(range(0,10001))
for cont in range(0,10001):
print(lista[cont])
for valor in lista:
print(valor) |
cont = 1
while True:
t = int(input('Quer saber a tabuada de que numero ? '))
if t < 0:
break
for c in range (1, 11):
print(f'{t} X {c} = {t * c}')
print('Obrigado!') |
#!/usr/bin/env python3
seq = 'ACGACGCAGGAGGAGAGTTTCAGAGATCACGAATACATCCATATTACCCAGAGAGAG'
w = 11
for i in range(len(seq) - w + 1):
count = 0
for j in range(i, i + w):
if seq[j] == 'G' or seq[j] == 'C':
count += 1
print(f'{i} {seq[i:i+w]} {(count / w) : .4f}')
|
class Rektangel:
def __init__(self, start_x, start_y, bredde, hoyde):
self.start_x = start_x
self.start_y = start_y
self.hoyde = hoyde
self.bredde = bredde
def areal(self):
return self.bredde*self.hoyde
# Endrer høyde og bredde på en slik måte at areal forblir det samme
def strekk(self, multiplikator):
self.bredde *= multiplikator
self.hoyde /= multiplikator
def __str__(self):
return f"Rektangel fra ({self.start_x}, {self.start_y}), " \
f"bredde {self.bredde}, høyde {self.hoyde}"
# Kvadrat som bruker komposisjon og delegering
class Kvadrat:
def __init__(self, start_x, start_y, storrelse):
self.rektanglet = Rektangel(start_x, start_y, storrelse, storrelse)
@property
def bredde(self):
return self.rektanglet.bredde
@property
def hoyde(self):
return self.rektanglet.hoyde
@bredde.setter
def bredde(self, ny_bredde):
self.rektanglet.bredde = ny_bredde
self.rektanglet.hoyde = ny_bredde
@hoyde.setter
def hoyde(self, ny_hoyde):
self.rektanglet.bredde = ny_hoyde
self.rektanglet.hoyde = ny_hoyde
def areal(self):
return self.rektanglet.areal()
if __name__ == "__main__":
rektanglet = Rektangel(5, 5, 10, 5)
print(rektanglet)
print(rektanglet.areal())
rektanglet.strekk(0.5)
print(rektanglet)
print(rektanglet.areal())
kvadrat = Kvadrat(2, 2, 6)
print(kvadrat)
print(kvadrat.areal())
kvadrat.strekk(6)
print(kvadrat)
print(kvadrat.areal())
|
# Tabuada em Python
def tabuada(x):
for i in range(10):
print('{} x {} = {}'.format(x, (i + 1), x * (i + 1)))
print()
if __name__ == '__main__':
print(9
)
nro = int(input('Entre com um número: '))
print(f'\n\033[1;32mTabuada do {nro}'+'\n')
tabuada(nro)
|
# Princess No Damage Skin (30-Days)
success = sm.addDamageSkin(2432803)
if success:
sm.chat("The Princess No Damage Skin (30-Days) has been added to your account's damage skin collection.")
|
class HiddenPeople():
"""Class for holding information on people"""
def __init__(self):
self.people = {
'Paul': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'man', 'hair': 'white', 'hat': False,
'glasses': True, 'moustache': False},
'Richard': {'bald': True, 'beard': True, 'eyes': 'brown', 'gender': 'man', 'hair': 'brown',
'hat': False, 'glasses': False, 'moustache': True},
'George': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'white',
'hat': True, 'glasses': False, 'moustache': False},
'Frans': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'red', 'hat': False,
'glasses': False, 'moustache': False},
'Bernard': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'brown',
'hat': True, 'glasses': True, 'moustache': False},
'Anne': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'girl', 'hair': 'black',
'hat': False, 'glasses': False, 'moustache': False},
'Joe': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'blonde', 'hat': False,
'glasses': True, 'moustache': False},
'Peter': {'bald': False, 'beard': False, 'eyes': 'blue', 'gender': 'boy', 'hair': 'white', 'hat': False,
'glasses': False, 'moustache': False},
'Tom': {'bald': True, 'beard': False, 'eyes': 'blue', 'gender': 'boy', 'hair': 'black', 'hat': False,
'glasses': True, 'moustache': False},
'Susan': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'girl', 'hair': 'blonde',
'hat': False, 'glasses': False, 'moustache': False},
'Sam': {'bald': True, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'white', 'hat': False,
'glasses': True, 'moustache': False},
'Maria': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'girl', 'hair': 'brown',
'hat': True, 'glasses': False, 'moustache': False},
'Robert': {'bald': False, 'beard': False, 'eyes': 'blue', 'gender': 'boy', 'hair': 'brown',
'hat': False, 'glasses': False, 'moustache': False},
'Alex': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'black', 'hat': False,
'glasses': False, 'moustache': True},
'Charles': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'blonde',
'hat': False, 'glasses': False, 'moustache': True},
'Philip': {'bald': False, 'beard': True, 'eyes': 'brown', 'gender': 'boy', 'hair': 'black',
'hat': False, 'glasses': False, 'moustache': False},
'David': {'bald': False, 'beard': True, 'eyes': 'brown', 'gender': 'boy', 'hair': 'blonde',
'hat': False, 'glasses': False, 'moustache': False},
'Eric': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'blonde',
'hat': True, 'glasses': False, 'moustache': False},
'Bill': {'bald': True, 'beard': True, 'eyes': 'brown', 'gender': 'boy', 'hair': 'red',
'hat': False, 'glasses': False, 'moustache': False},
'Alfred': {'bald': False, 'beard': False, 'eyes': 'blue', 'gender': 'boy', 'hair': 'red', 'hat': False,
'glasses': False, 'moustache': True},
'Anita': {'bald': False, 'beard': False, 'eyes': 'blue', 'gender': 'girl', 'hair': 'white',
'hat': False, 'glasses': False, 'moustache': False},
'Max': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'black', 'hat': False,
'glasses': False, 'moustache': True},
'Herman': {'bald': True, 'beard': False, 'eyes': 'brown', 'gender': 'boy', 'hair': 'red', 'hat': False,
'glasses': False, 'moustache': False},
'Claire': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'girl', 'hair': 'red', 'hat': True,
'glasses': True, 'moustache': False}}
def removeperson(self, attribute):
"""Remove a person from listing of people to choose"""
removelist = []
for person in self.people:
if self.people[person][attribute]:
removelist.append(person)
for person in removelist:
del self.people[person]
def printpeople(self):
for person in self.people:
print(person + ": " + str(self.people[person]))
|
list1 = []
list2 = []
list3 = []
cont = 0
while cont < 10:
valor = int(input('Digite um numero na lista 1: '))
list1.append(valor)
valor2 = int(input('Digite um numero na lista 2: '))
list2.append(valor2)
cont = cont + 1
if cont == 10:
for i in list1:
if i in list2:
if i not in list3:
list3.append(i)
print(list1)
print(list2)
print(f'Os númeoros que contem em ambos os vetores são: {list3}')
|
# 1) count = To count how many time a particular word & char. is appearing
x = "Keep grinding keep hustling"
print(x.count("t"))
# 2) index = To get index of letter(gives the lowest index)
x="Keep grinding keep hustling"
print(x.index("t")) # will give the lowest index value of (t)
# 3) find = To get index of letter(gives the lowest index) | Return -1 on failure.
x = "Keep grinding keep hustling"
print(x.find("t"))
'''
NOTE : print(x.index("t",34)) : Search starts from index value 34 including 34
'''
|
# Thinking probabilistically-- Discrete variables!!
# Statistical inference rests upon probability. Because we can very rarely say anything meaningful with absolute certainty from data, we use probabilistic language to make quantitative statements about data. In this chapter, you will learn how to think probabilistically about discrete quantities: those that can only take certain values, like integers.
# Generating random numbers using the np.random module
# We will be hammering the np.random module for the rest of this course and its sequel. Actually, you will probably call functions from this module more than any other while wearing your hacker statistician hat. Let's start by taking its simplest function, np.random.random() for a test spin. The function returns a random number between zero and one. Call np.random.random() a few times in the IPython shell. You should see numbers jumping around between zero and one.
# In this exercise, we'll generate lots of random numbers between zero and one, and then plot a histogram of the results. If the numbers are truly random, all bars in the histogram should be of (close to) equal height.
# You may have noticed that, in the video, Justin generated 4 random numbers by passing the keyword argument size=4 to np.random.random(). Such an approach is more efficient than a for loop: in this exercise, however, you will write a for loop to experience hacker statistics as the practice of repeating an experiment over and over again.
# Seed the random number generator
np.random.seed(42)
# Initialize random numbers: random_numbers
random_numbers = np.empty(100000)
# Generate random numbers by looping over range(100000)
for i in range(100000):
random_numbers[i] = np.random.random()
# Plot a histogram
_ = plt.hist(random_numbers)
# Show the plot
plt.show()
# The np.random module and Bernoulli trials
# You can think of a Bernoulli trial as a flip of a possibly biased coin. Specifically, each coin flip has a probability p of landing heads (success) and probability 1−p of landing tails (failure). In this exercise, you will write a function to perform n Bernoulli trials, perform_bernoulli_trials(n, p), which returns the number of successes out of n Bernoulli trials, each of which has probability p of success. To perform each Bernoulli trial, use the np.random.random() function, which returns a random number between zero and one.
def perform_bernoulli_trials(n, p):
"""Perform n Bernoulli trials with success probability p
and return number of successes."""
# Initialize number of successes: n_success
n_success = 0
# Perform trials
for i in range(n):
# Choose random number between zero and one: random_number
random_number = np.random.random()
# If less than p, it's a success so add one to n_success
if random_number< p:
n_success +=1
return n_success
# How many defaults might we expect?
# Let's say a bank made 100 mortgage loans. It is possible that anywhere between 0 and 100 of the loans will be defaulted upon. You would like to know the probability of getting a given number of defaults, given that the probability of a default is p = 0.05. To investigate this, you will do a simulation. You will perform 100 Bernoulli trials using the perform_bernoulli_trials() function you wrote in the previous exercise and record how many defaults we get. Here, a success is a default. (Remember that the word "success" just means that the Bernoulli trial evaluates to True, i.e., did the loan recipient default?) You will do this for another 100 Bernoulli trials. And again and again until we have tried it 1000 times. Then, you will plot a histogram describing the probability of the number of defaults.
# Seed random number generator
np.random.seed(42)
# Initialize the number of defaults: n_defaults
n_defaults = np.empty(1000)
# Compute the number of defaults
for i in range(1000):
n_defaults[i] = perform_bernoulli_trials(100,0.05)
# Plot the histogram with default number of bins; label your axes
_ = plt.hist(n_defaults, normed= True)
_ = plt.xlabel('number of defaults out of 100 loans')
_ = plt.ylabel('probability')
# Show the plot
plt.show()
# Will the bank fail?
# Plot the number of defaults you got from the previous exercise, in your namespace as n_defaults, as a CDF. The ecdf() function you wrote in the first chapter is available.
# If interest rates are such that the bank will lose money if 10 or more of its loans are defaulted upon, what is the probability that the bank will lose money?
# Compute ECDF: x, y
x, y= ecdf(n_defaults)
# Plot the ECDF with labeled axes
plt.plot(x, y, marker = '.', linestyle ='none')
plt.xlabel('loans')
plt.ylabel('interest')
# Show the plot
plt.show()
# Compute the number of 100-loan simulations with 10 or more defaults: n_lose_money
n_lose_money=sum(n_defaults >=10)
# Compute and print probability of losing money
print('Probability of losing money =', n_lose_money / len(n_defaults))
# Sampling out of the Binomial distribution
# Compute the probability mass function for the number of defaults we would expect for 100 loans as in the last section, but instead of simulating all of the Bernoulli trials, perform the sampling using np.random.binomial(). This is identical to the calculation you did in the last set of exercises using your custom-written perform_bernoulli_trials() function, but far more computationally efficient. Given this extra efficiency, we will take 10,000 samples instead of 1000. After taking the samples, plot the CDF as last time. This CDF that you are plotting is that of the Binomial distribution.
# Note: For this exercise and all going forward, the random number generator is pre-seeded for you (with np.random.seed(42)) to save you typing that each time.
# Take 10,000 samples out of the binomial distribution: n_defaults
n_defaults = np.random.binomial(100,0.05,size = 10000)
# Compute CDF: x, y
x, y = ecdf(n_defaults)
# Plot the CDF with axis labels
plt.plot(x,y, marker ='.', linestyle = 'none')
plt.xlabel("Number of Defaults")
plt.ylabel("CDF")
# Show the plot
plt.show()
# Plotting the Binomial PMF
# As mentioned in the video, plotting a nice looking PMF requires a bit of matplotlib trickery that we will not go into here. Instead, we will plot the PMF of the Binomial distribution as a histogram with skills you have already learned. The trick is setting up the edges of the bins to pass to plt.hist() via the bins keyword argument. We want the bins centered on the integers. So, the edges of the bins should be -0.5, 0.5, 1.5, 2.5, ... up to max(n_defaults) + 1.5. You can generate an array like this using np.arange() and then subtracting 0.5 from the array.
# You have already sampled out of the Binomial distribution during your exercises on loan defaults, and the resulting samples are in the NumPy array n_defaults.
# Compute bin edges: bins
bins = np.arange(0, max(n_defaults) + 1.5) - 0.5
# Generate histogram
plt.hist(n_defaults, normed = True, bins = bins)
# Label axes
plt.xlabel('Defaults')
plt.ylabel('PMF')
# Show the plot
plt.show()
# Relationship between Binomial and Poisson distributions
# You just heard that the Poisson distribution is a limit of the Binomial distribution for rare events. This makes sense if you think about the stories. Say we do a Bernoulli trial every minute for an hour, each with a success probability of 0.1. We would do 60 trials, and the number of successes is Binomially distributed, and we would expect to get about 6 successes. This is just like the Poisson story we discussed in the video, where we get on average 6 hits on a website per hour. So, the Poisson distribution with arrival rate equal to np approximates a Binomial distribution for n Bernoulli trials with probability p of success (with n large and p small). Importantly, the Poisson distribution is often simpler to work with because it has only one parameter instead of two for the Binomial distribution.
# Let's explore these two distributions computationally. You will compute the mean and standard deviation of samples from a Poisson distribution with an arrival rate of 10. Then, you will compute the mean and standard deviation of samples from a Binomial distribution with parameters n and p such that np=10.
# Draw 10,000 samples out of Poisson distribution: samples_poisson
# Print the mean and standard deviation
print('Poisson: ', np.mean(samples_poisson),
np.std(samples_poisson))
# Specify values of n and p to consider for Binomial: n, p
# Draw 10,000 samples for each n,p pair: samples_binomial
for i in range(3):
samples_binomial = ____
# Print results
print('n =', n[i], 'Binom:', np.mean(samples_binomial),
np.std(samples_binomial))
# Was 2015 anomalous?
# 1990 and 2015 featured the most no-hitters of any season of baseball (there were seven). Given that there are on average 251/115 no-hitters per season, what is the probability of having seven or more in a season?
# Draw 10,000 samples out of Poisson distribution: n_nohitters
# Compute number of samples that are seven or greater: n_large
n_large = np.sum(____)
# Compute probability of getting seven or more: p_large
# Print the result
print('Probability of seven or more no-hitters:', p_large)
|
# example of redefinition __repr__ and __str__ of exception
class MyBad(Exception):
def __str__(self):
return 'My mistake!'
class MyBad2(Exception):
def __repr__(self):
return 'Not calable' # because buid-in method has __str__
try:
raise MyBad('spam')
except MyBad as X:
print(X) # My mistake!
print(X.args) # ('spam',)
try:
raise MyBad2('spam')
except MyBad2 as X:
print(X) # spam
print(X.args) # ('spam',)
raise MyBad('spam') # __main__.MyBad2: My mistake!
# raise MyBad2('spam') # __main__.MyBad2: spam |
#Q2
# “If you have an apple and I have an apple and we exchange these apples then
# you and I will still each have one apple. But if you have an idea and I have
# an idea and we exchange these ideas, then each of us will have two ideas.”
# George Bernard Shaw
class Person:
apples = 0
ideas = 0
johanna = Person()
johanna.apples = 1
johanna.ideas = 1
martin = Person()
martin.apples = 2
martin.ideas = 1
def exchange_apples(you, me):
#Here, despite G.B. Shaw's quote, our characters have started with #different amounts of apples so we can better observe the results.
#We're going to have Martin and Johanna exchange ALL their apples with #one another.
#Hint: how would you switch values of variables,
#so that "you" and "me" will exchange ALL their apples with one another?
#Do you need a temporary variable to store one of the values?
#You may need more than one line of code to do that, which is OK.
temp=you.apples
you.apples=me.apples
me.apples=temp
return you.apples, me.apples
def exchange_ideas(you, me):
#"you" and "me" will share our ideas with one another.
#What operations need to be performed, so that each object receives
#the shared number of ideas?
#Hint: how would you assign the total number of ideas to
#each idea attribute? Do you need a temporary variable to store
#the sum of ideas, or can you find another way?
#Use as many lines of code as you need here.
you.ideas =me.ideas+you.ideas
me.ideas =you.ideas
return you.ideas, me.ideas
exchange_apples(johanna, martin)
print("Johanna has {} apples and Martin has {} apples".format(johanna.apples, martin.apples))
exchange_ideas(johanna, martin)
print("Johanna has {} ideas and Martin has {} ideas".format(johanna.ideas, martin.ideas))
#Q3
# define a basic city class
class City:
name = ""
country = ""
elevation = 0
population = 0
# create a new instance of the City class and
# define each attribute
city1 = City()
city1.name = "Cusco"
city1.country = "Peru"
city1.elevation = 3399
city1.population = 358052
# create a new instance of the City class and
# define each attribute
city2 = City()
city2.name = "Sofia"
city2.country = "Bulgaria"
city2.elevation = 2290
city2.population = 1241675
# create a new instance of the City class and
# define each attribute
city3 = City()
city3.name = "Seoul"
city3.country = "South Korea"
city3.elevation = 38
city3.population = 9733509
def max_elevation_city(min_population):
# Initialize the variable that will hold
# the information of the city with
# the highest elevation
highest_elevation=0
return_city =""
# Evaluate the 1st instance to meet the requirements:
# does city #1 have at least min_population and
# is its elevation the highest evaluated so far?
if (city1.population>min_population):
if(highest_elevation<city1.elevation):
highest_elevation=city1.elevation
return_city = ("{}, {}".format(city1.name,city1.country))
# Evaluate the 2nd instance to meet the requirements:
# does city #2 have at least min_population and
# is its elevation the highest evaluated so far?
if(city2.population>min_population):
if (highest_elevation<city2.elevation):
highest_elevation=city2.elevation
return_city = ("{}, {}".format(city2.name,city2.country))
# Evaluate the 3rd instance to meet the requirements:
# does city #3 have at least min_population and
# is its elevation the highest evaluated so far?
if(city3.population>min_population):
if (highest_elevation<city3.elevation):
highest_elevation=city3.elevation
return_city = ("{}, {}".format(city3.name,city3.country))
#Format the return string
if return_city!="":
return return_city
else:
return ""
print(max_elevation_city(100000)) # Should print "Cusco, Peru"
print(max_elevation_city(1000000)) # Should print "Sofia, Bulgaria"
print(max_elevation_city(10000000)) # Should print ""
#Q5
class Furniture:
color = ""
material = ""
table = Furniture()
table.color="brown"
table.material="wood"
couch = Furniture()
couch.color="red"
couch.material="leather"
def describe_furniture(piece):
return ("This piece of furniture is made of {} {}".format(piece.color, piece.material))
print(describe_furniture(table))
# Should be "This piece of furniture is made of brown wood"
print(describe_furniture(couch))
# Should be "This piece of furniture is made of red leather"
|
class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
'''
T: O(n log n) and S: O(1)
'''
n = len(nums)
sorted_nums = sorted(nums)
start, end = n + 1, -1
for i in range(n):
if nums[i] != sorted_nums[i]:
start = min(start, i)
end = max(end, i)
diff = end - start
return diff + 1 if diff > 0 else 0
|
# "javascript" section for javascript. see @app.route('/config.js') in app/views.py
# oauth constants
HOSTNAME = "http://hackathon.chinacloudapp.cn" # host name of the UI site
QQ_OAUTH_STATE = "openhackathon" # todo state should be constant. Actually it should be unguessable to prevent CSFA
HACkATHON_API_ENDPOINT = "http://hackathon.chinacloudapp.cn:15000"
Config = {
"environment": "local",
"login": {
"github": {
"access_token_url": 'https://github.com/login/oauth/access_token?client_id=a10e2290ed907918d5ab&client_secret=5b240a2a1bed6a6cf806fc2f34eb38a33ce03d75&redirect_uri=%s/github&code=' % HOSTNAME,
"user_info_url": 'https://api.github.com/user?access_token=',
"emails_info_url": 'https://api.github.com/user/emails?access_token='
},
"qq": {
"access_token_url": 'https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=101192358&client_secret=d94f8e7baee4f03371f52d21c4400cab&redirect_uri=%s/qq&code=' % HOSTNAME,
"openid_url": 'https://graph.qq.com/oauth2.0/me?access_token=',
"user_info_url": 'https://graph.qq.com/user/get_user_info?access_token=%s&oauth_consumer_key=%s&openid=%s'
},
"gitcafe": {
"access_token_url": 'https://api.gitcafe.com/oauth/token?client_id=25ba4f6f90603bd2f3d310d11c0665d937db8971c8a5db00f6c9b9852547d6b8&client_secret=e3d821e82d15096054abbc7fbf41727d3650cab6404a242373f5c446c0918634&redirect_uri=%s/gitcafe&grant_type=authorization_code&code=' % HOSTNAME
},
"provider_enabled": ["github", "qq", "gitcafe"],
"session_minutes": 60,
"token_expiration_minutes": 60 * 24
},
"hackathon-api": {
"endpoint": HACkATHON_API_ENDPOINT
},
"javascript": {
"renren": {
"clientID": "client_id=7e0932f4c5b34176b0ca1881f5e88562",
"redirect_url": "redirect_uri=%s/renren" % HOSTNAME,
"scope": "scope=read_user_message+read_user_feed+read_user_photo",
"response_type": "response_type=token",
},
"github": {
"clientID": "client_id=a10e2290ed907918d5ab",
"redirect_uri": "redirect_uri=%s/github" % HOSTNAME,
"scope": "scope=user",
},
"google": {
"clientID": "client_id=304944766846-7jt8jbm39f1sj4kf4gtsqspsvtogdmem.apps.googleusercontent.com",
"redirect_url": "redirect_uri=%s/google" % HOSTNAME,
"scope": "scope=https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/userinfo.email",
"response_type": "response_type=token",
},
"qq": {
"clientID": "client_id=101192358",
"redirect_uri": "redirect_uri=%s/qq" % HOSTNAME,
"scope": "scope=get_user_info",
"state": "state=%s" % QQ_OAUTH_STATE,
"response_type": "response_type=code",
},
"gitcafe": {
"clientID": "client_id=25ba4f6f90603bd2f3d310d11c0665d937db8971c8a5db00f6c9b9852547d6b8",
"clientSecret": "client_secret=e3d821e82d15096054abbc7fbf41727d3650cab6404a242373f5c446c0918634",
"redirect_uri": "redirect_uri=http://hackathon.chinacloudapp.cn/gitcafe",
"response_type": "response_type=code",
"scope": "scope=public"
},
"hackathon": {
"name": "open-xml-sdk",
"endpoint": HACkATHON_API_ENDPOINT
}
}
}
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
if not target or not original or not cloned: return None
if target.val == original.val == cloned.val: return cloned
node = self.getTargetCopy(original.left, cloned.left, target)
if node: return node
node = self.getTargetCopy(original.right, cloned.right, target)
if node: return node
return None
|
class City:
name = "city"
size = "default"
draw = -1
danger = -1
population = [] |
def to_weird_case(string):
arr=string.split()
count=0
for i in arr:
tmp=list(i)
for j in range(len(tmp)):
if j%2==0:
tmp[j]=tmp[j].upper()
arr[count] = ''.join(tmp)
count+=1
return ' '.join(arr)
'''
一个比较不错的版本
def to_weird_case(string):
recase = lambda s: "".join([c.upper() if i % 2 == 0 else c.lower() for i, c in enumerate(s)])
return " ".join([recase(word) for word in string.split(" ")])
''' |
# >>> s = set("Hacker")
# >>> print s.difference("Rank")
# set(['c', 'r', 'e', 'H'])
# >>> print s.difference(set(['R', 'a', 'n', 'k']))
# set(['c', 'r', 'e', 'H'])
# >>> print s.difference(['R', 'a', 'n', 'k'])
# set(['c', 'r', 'e', 'H'])
# >>> print s.difference(enumerate(['R', 'a', 'n', 'k']))
# set(['a', 'c', 'r', 'e', 'H', 'k'])
# >>> print s.difference({"Rank":1})
# set(['a', 'c', 'e', 'H', 'k', 'r'])
# >>> s - set("Rank")
# set(['H', 'c', 'r', 'e'])
if __name__ == "__main__":
eng = input()
eng_stu = set(map(int, input().split()))
fre = input()
fre_stu = set(map(int, input().split()))
eng_only = eng_stu - fre_stu
print(len(eng_only))
|
SECRET_KEY = None
DB_HOST = "localhost"
DB_NAME = "kido"
DB_USERNAME = "kido"
DB_PASSWORD = "kido"
COMPRESSOR_DEBUG = False
COMPRESSOR_OFFLINE_COMPRESS = True
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.