content stringlengths 7 1.05M |
|---|
#
# gambit
#
# This file contains the information to make the mesh for a subset of the original point data set.
#
#
# The original data sets are in csv format and are for 6519 observation points.
# 1. `Grav_MeasEs.csv` contains the cartesian coordinates of the observation points (m).
# 2. `Grav_gz.csv` contains the Bouger corrected gravity measurements ( micro m/s^2).
# 3. `Grav_acc.csv` cotains the measurement accuracy (micro m/s^2).
#
big_gravity_data_file = "Grav_gz.csv"
big_acc_data_file = "Grav_acc.csv"
big_obsPts_file = "Grav_MeasEs.csv"
#
# The inversion code has a measurement scale factor so it is not absolutely necessary
# to have the same units for the gravity measurments. The scale factor conversts the
# measurements to m/s^2. It is assumed that the spatial measurements are in m.
#
# The size of the data sets can be reduced. The new arrays contain the first element and
# then in steps of "pick" .
#
pick = 4
#
# The new small data file names
#
gravity_data_file = "Grav_small_gz.csv"
accuracy_data_file = "Grav_small_acc.csv"
obsPts_file = "Grav_small_MeasEs.csv"
#
# Element size at observation points depends on the distance to its nearest neighbour.
# To make the ground variable mesh, the minimum nearest neighbour distance is computed for each observation point
# and recorded in the file
minDist_file = "Grav_small_minDist.csv"
#
#
# GMSH mesh making parameters
#
# A bound for the maximum nearest neighbour distance. This value will be used to compute element size for any point
# that has no nearest neighbour closer.
maxDist = 5000
#
# For each observatio point, element length is, in general
# nearest neighbour distance / spacing0
#
# For nearest neighbour distance < mindist1, element length is,
# nearest neighbour distance / spacing1
#
# For nearest neighbour distance < mindist1, element length is,
# nearest neighbour distance / spacing2
#
mindist1 = 500
mindist2 = 100
spacing0 = 4
spacing1 = 3
spacing2 = 2
#
# The core area is 1.01*span of observation points in the x and y directions.
# Ground level is at 0m and is horizontal. There is a core ground region and core air region.
groundLevel = 0
coreDepth = - 20000
coreAir = 10000
#
# mesh sizes vary.
# Mesh size at the top of the core air region
MCtop = 5000
# Mesh size at the bottom of the core ground region
MCbase = 5000
# mesh size at the core ground region. This is probably over ruled by the mesh size of the observation points.
MCground = 5000
#
# The buffer region has different element lengths.
# Mesh size at the tob of the buffer in the air
MBtop = 20000
# Mesh size at the edge of the buffer region at ground level
MBbase = 20000
# Mesh size at the base of the buffer region.
MBground = 10000
# Name for the geo file.
geo_name = "smallPointMesh.geo"
|
"""
148. Sort List
Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input: 4->2->1->3
Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0
Output: -1->0->3->4->5
"""
class Solution:
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None: return head
def merge(l1, l2):
dummy = ListNode(0)
cur = dummy
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
if l1: cur.next = l1
else: cur.next = l2
return dummy.next
slow = head
fast = head
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
r = slow.next
slow.next = None
return merge(self.sortList(head),self.sortList(r))
class Solution(object):
def merge(self, h1, h2):
dummy = tail = ListNode(None)
while h1 and h2:
if h1.val < h2.val:
tail.next, tail, h1 = h1, h1, h1.next
else:
tail.next, tail, h2 = h2, h2, h2.next
tail.next = h1 or h2
return dummy.next
def sortList(self, head):
if not head or not head.next:
return head
pre, slow, fast = None, head, head
while fast and fast.next:
pre, slow, fast = slow, slow.next, fast.next.next
pre.next = None
return self.merge(*map(self.sortList, (head, slow))) |
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
i = 1
while i < 6:
print(i)
if i == 3:
continue
i += 1
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
|
def config():
return None
def watch():
return None |
"""
This file contains all of the display functions for model management
"""
def display_init_model_root(root):
"""display function for creating new model folder"""
print("Created model directory at %s" % (root))
def display_init_model_db(db_root):
"""display function for initializing the model db"""
print("Created model database at %s" % (db_root))
def display_imported_model(name):
"""display function for importing a model"""
print("Model %s imported successfully" % (name))
|
# Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
load("@bazel_skylib//lib:versions.bzl", _bazel_versions = "versions")
load("@os_info//:os_info.bzl", "is_windows")
def _semver_components(version):
"""Separates a semver into its components.
I.e. separates `MAJOR.MINOR.PATCH-PRERELEASE+BUILD` into
* the version core `MAJOR.MINOR.PATCH`
* the optional `PRERELEASE` identifier, `None` if missing
* the optional `BUILD` identifier, `None` if missing
Returns:
The tuple `(version, prerelease, build)`.
"""
dash_pos = version.find("-")
plus_pos = version.find("+")
if dash_pos != -1:
core_end = dash_pos
elif plus_pos != -1:
core_end = plus_pos
else:
core_end = len(version)
if plus_pos != -1:
prerelease_end = plus_pos
else:
prerelease_end = len(version)
build_end = len(version)
core = version[:core_end]
if dash_pos != -1:
prerelease = version[core_end + 1:prerelease_end]
else:
prerelease = None
if plus_pos != -1:
build = version[prerelease_end + 1:build_end]
else:
build = None
return (core, prerelease, build)
def _extract_git_revision(prerelease):
"""Extracts the git revision from the prerelease identifier.
This is assumed to be the last `.` separated component.
"""
return prerelease.split(".")[-1]
def version_to_name(version):
"""Render a version to a target name or path component.
On Windows snapshot versions are shortened to `MAJOR.MINOR.PATCH-REV`,
where `REV` is the git revision. This is to avoid exceeding the `MAX_PATH`
limit on Windows.
"""
if is_windows:
(core, prerelease, _) = _semver_components(version)
components = [core]
if prerelease != None:
components.append(_extract_git_revision(prerelease))
name = "-".join(components)
else:
name = version
return name
def _cmp(a, b):
if a == b:
return 0
elif a > b:
return 1
else:
return -1
def _cmp_prerelease_part(part1, part2):
if part1.isdigit() and part2.isdigit():
return _cmp(int(part1), int(part2))
elif part1.isdigit():
return False
elif part2.isdigit():
return True
else:
return _cmp(part1, part2)
def _cmp_version(version1, version2):
"""Semver comparison of version1 and version2.
Returns 1 if version1 > version2, 0 if version1 == version2 and -1 if version1 < version2.
"""
# Handle special-cases for 0.0.0 which is always the latest.
if version1 == "0.0.0" and version2 == "0.0.0":
return 0
elif version1 == "0.0.0":
return 1
elif version2 == "0.0.0":
return -1
# No version is 0.0.0 so use a proper semver comparison.
# Note that the comparisons in skylib ignore the prerelease
# so they aren’t suitable if we have one.
(core1, prerelease1, _) = _semver_components(version1)
(core2, prerelease2, _) = _semver_components(version2)
core1_parsed = _bazel_versions.parse(core1)
core2_parsed = _bazel_versions.parse(core2)
# First compare (major, minor, patch) triples
if core1_parsed > core2_parsed:
return 1
elif core1_parsed < core2_parsed:
return -1
elif not prerelease1 and not prerelease2:
return 0
elif not prerelease1:
return 1
elif not prerelease2:
return -1
else:
# Finally compare the prerelease.
parts1 = prerelease1.split(".")
parts2 = prerelease2.split(".")
for a, b in zip(parts1, parts2):
cmp_result = _cmp_prerelease_part(a, b)
if cmp_result != 0:
return cmp_result
return _cmp(len(a), len(b))
def _is_at_least(threshold, version):
"""Check that a version is lower or equals to a threshold.
Args:
threshold: the maximum version string
version: the version string to be compared to the threshold
Returns:
True if version <= threshold.
"""
return _cmp_version(version, threshold) >= 0
def _is_at_most(threshold, version):
"""Check that a version is higher or equals to a threshold.
Args:
threshold: the minimum version string
version: the version string to be compared to the threshold
Returns:
True if version >= threshold.
"""
return _cmp_version(version, threshold) <= 0
versions = struct(
is_at_most = _is_at_most,
is_at_least = _is_at_least,
)
|
"""Class implementation for type name interface.
"""
class TypeNameInterface:
_type_name: str
@property
def type_name(self) -> str:
"""
Get this instance expression's type name.
Returns
-------
type_name : str
This instance expression's type name.
"""
return self._type_name
|
def transposition(key, order, order_name):
new_key = ""
for pos in order:
new_key += key[pos-1]
print("Permuted "+ order_name +" = "+ new_key)
return new_key
def P10(key):
P10_order = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6]
P10_key = transposition(key, P10_order, "P10")
return P10_key
def P8(LS1_key):
P8_order = [6, 3, 7, 4, 8, 5, 10, 9]
P8_key = transposition(LS1_key, P8_order, "P8")
return P8_key
def LS1(P10_key):
P10_key_left = P10_key[:5]
P10_key_right = P10_key[5:]
LS1_key_left = P10_key_left[1:5] + P10_key_left[0]
LS1_key_right = P10_key_right[1:5] + P10_key_right[0]
LS1_key = LS1_key_left+LS1_key_right
#print("LS-1 = " + LS1_key)
return LS1_key
def IP(LS1_key):
IP_order = [2, 6, 3, 1, 4, 8, 5, 7]
IP_key = transposition(LS1_key, IP_order, "IP")
return IP_key
def IP_inv(LS1_key):
IP_inv_order = [4, 1, 3, 5, 7, 2, 8, 6]
IP_inv_key = transposition(LS1_key, IP_inv_order, "IP-1")
return IP_inv_key
def key_gen(key):
LS1_key = LS1(P10(key))
key_1 = P8(LS1_key)
key_2 = P8(LS1(LS1_key))
#print("Key-1:"+ key_1 +"\nKey-2:"+ key_2)
return (key_1,key_2)
def encrypt_plain(plain_text):
enc = IP(plain_text)
dec = IP_inv(enc)
#print("ENC:"+ enc +"\nDEC:"+ dec)
return(enc, dec)
def f_key(enc_plain, SK):
L = enc_plain[:4]
R = enc_plain[4:]
F = F_func(R, SK)
#print(L)
#print(R)
f = A_xor_B(L, SK) + R
#print(f)
return f
def F_func(R, SK):
EP_order = [4, 1, 2, 3, 2, 3, 4, 1]
EP_key = transposition(R, EP_order, "EP")
P = A_xor_B(EP_key, SK)
P4 = s_box(P)
return P4
def A_xor_B(A,B):
bit_xor = ""
for i in range(len(A)):
bit_xor += str ( int(A[i]) ^ int(B[i]) )
#print(bit_xor)
return bit_xor
def s_box(P):
P0 = P[:4]
P1 = P[4:]
S0_order = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]]
S1_order = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]]
P4_order = [2, 4, 3, 1]
S0 = sbox_calc(P0, S0_order)
S1 = sbox_calc(P1, S1_order)
P4 = transposition( S0+S1, P4_order, "P4" )
#print(P4)
return P4
def sbox_calc(P, S):
row = int( (P[0] + P[3]) , 2 )
col = int( (P[1] + P[2]) , 2 )
s_val = bin(S[row][col])[2:].zfill(2)
return(s_val)
def SW(key):
key_new = key[:4] + key[4:]
#print(key_new)
return key_new
option = input("\n1. Encode\n2. Decode\nEnter your option:")
key = input("Enter the key:")
inp = input("Enter the text:")
key_1, key_2 = key_gen(key)
#enc_plain, dec_plain = encrypt_plain(plain_text)
if option == '1':
print()
IP_1 = IP(inp)
fk_1 = f_key(IP_1, key_1)
switch = SW(fk_1)
fk_2 = f_key(switch, key_2)
IP_2 = IP_inv(fk_2)
print("\nEncoded = " + IP_2)
else:
print()
plain_text = inp
IP_1 = IP(plain_text)
fk_2 = f_key(IP_1, key_2)
switch = SW(fk_2)
fk_1 = f_key(switch, key_1)
IP_2 = IP_inv(fk_1)
print("\nDecoded = " + IP_2)
# 1010000010
# 10111101
|
"""
Add a counter at a iterable and return the this
counter .
"""
# teste
fruits = ["apple", "pineapple", "lemon", "watermelon", "grapes"]
enumerate_list = enumerate(fruits)
# print(list(enumerate_list))
for index, element in enumerate_list:
filename = f"file{index}.jpg"
print(filename)
|
class laptop:
brand=[]
year=[]
ram=[]
def __init__(self,brand,year,ram,cost):
self.brand.append(brand)
self.year.append(year)
self.ram.append(ram)
self.cost.append(cost)
|
year_str = input('あなたの生まれ年を西暦4桁で入力してください: ')
year = int(year_str)
number_of_eto = (year + 8) % 12
eto_tuple = ('子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥')
eto_name = eto_tuple[number_of_eto]
print('あなたの干支は', eto_name, 'です。')
|
print('==== SERA QUE O ANO É BISSEXTO ? ====')
ano = int(input('Digite um ano que deseja verificar se é bissexto: '))
if ano % 4 ==0 and ano % 100 != 0 or ano % 400 ==0:
print('O ano é BISSEXTO.')
else:
print('O ano não é BISSEXTO.')
|
"""uVoyeur Application Bus"""
class PublishFailures(Exception):
delimiter = '\n'
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
self._exceptions = list()
def capture_exception(self):
self._exceptions.append(sys.exc_info()[1])
def get_instances(self):
return self._exceptions[:]
def __str__(self):
exception_strings = map(repr, self.get_instances())
return self.delimiter.join(exception_strings)
__repr__ = __str__
def __bool__(self):
return bool(self._exceptions)
__nonzero__ = __bool__
class Bus(object):
def __init__(self):
self.listeners = dict(
[(channel, set()) for channel
in ('main')])
print("Bus() initialized.")
def subscribe(self, channel, callback):
if channel not in self.listeners:
self.listeners[channel] = set()
self.listeners[channel].add(callback)
def unsubscribe(self, channel, callback):
listeners = self.listeners.get(channel)
if listeners and callback in listeners:
listeners.discard(callback)
def publish(self, channel, *args, **kwargs):
"""Return the output of all subscribers in an array."""
if channel not in self.listeners:
return []
exc = PublishFailures()
output = []
listeners = self.listeners.get(channel)
for listener in listeners:
try:
output.append(listener(*args, **kwargs))
except KeyboardInterrupt:
raise
except SystemExit:
# If there were previous (non SystemExit) errors, make sure exit code in non-zero
e = sys.exc_info()[1]
if exc and e.code == 0:
e.code = 1
# propigate SystemExit
raise
except:
exc.capture_exception()
# and continue publishing
if exc:
raise exc
return output
## Local Variables:
## mode: python
## End:
|
# 没想到用dp
# 状态转移方程:=之前的一家不偷,这家偷(dp(i-2) + val(i))和上一家偷了(dp(i-1))的较大值
class Solution:
def rob(self, nums):
if len(nums)==0:
return 0
dp=[0]*len(nums)
dp[0]=nums[0]
if len(nums)>=2:
dp[1]=max(nums[0:2])
for i in range(2,len(nums)):
dp[i]=max(dp[i-2]+nums[i],dp[i-1])
return dp[-1]
if __name__ == "__main__":
s = Solution()
print(s.rob([2,1,3]))
|
dataset_type = 'TextDetDataset'
data_root = 'data/synthtext'
train = dict(
type=dataset_type,
ann_file=f'{data_root}/instances_training.lmdb',
loader=dict(
type='AnnFileLoader',
repeat=1,
file_format='lmdb',
parser=dict(
type='LineJsonParser',
keys=['file_name', 'height', 'width', 'annotations'])),
img_prefix=f'{data_root}/imgs',
pipeline=None)
train_list = [train]
test_list = [train]
|
class Solution:
def judgeSquareSum(self, c: int) -> bool:
left = 0
right = int(c ** 0.5)
while left <= right:
cur = left ** 2 + right ** 2
if cur < c:
left += 1
elif cur > c:
right -= 1
else:
return True
return False
|
#!/usr/bin/env python3
def score_word(word):
score = 0
for letter in word:
# add code here
pass
return score
|
"""
Advent of Code 2021: Day 02 Part 1
tldr: Find two dimensional ending position
"""
input_file = "input.solution"
totals = {
"forward": 0,
"down": 0,
"up": 0,
}
with open(input_file, "r") as file:
for line in file:
direction, magnitude = line.split()
totals[direction] += int(magnitude)
result = (totals["down"] - totals["up"]) * totals["forward"]
print(result)
|
#!/bin/python3
# https://www.hackerrank.com/challenges/alphabet-rangoli/problem
#ll=limitting letter
#sl=starting letter
#df=deduction factor
#cd=character difference
#rl=resulting letter
while True:
ll=ord(input("Enter the limitting letter in the pattern:> "))
sl=65 if ll in range(65,91) else (97 if ll in range(97,123) else None)
if sl: break
print("Enter a valid input.")
print("See the alphabet pattern:>\n")
for df in range(sl-ll,ll-sl+1):
for cd in range(sl-ll,ll-sl+1):
rl=sl+abs(cd)+abs(df)
if(cd==ll-sl):
print(chr(rl) if rl<=ll else '-')
else:
print(chr(rl) if rl<=ll else '-',end="-")
|
# -*- coding:utf-8 -*-
"""
@Author:Charles Van
@E-mail: williananjhon@hotmail.com
@Time:2019-07-26 17:27
@Project:InterView_Book
@Filename:violentEnumeration.py
@description:
暴力枚举法
"""
# S定义股票开盘价数组
S = [10,4,8,7,9,6,2,5,3]
maxProfit = 0
buyDay = 0
sellDay = 0
for i in range(len(S) - 1):
for j in range(i+1,len(S)):
if S[j] - S[i] > maxProfit:
maxProfit = S[j] - S[i]
buyDay = i
sellDay = j
print("应该在第{0}天买入,第{1}天卖出,最大交易利润为:{2}".format(buyDay+1,sellDay+1,maxProfit)) |
# initialize step_end
step_end = 25
with plt.xkcd():
# initialize the figure
plt.figure()
# loop for step_end steps
for step in range(step_end):
t = step * dt
i = i_mean * (1 + np.sin((t * 2 * np.pi) / 0.01))
plt.plot(t, i, 'ko')
plt.title('Synaptic Input $I(t)$')
plt.xlabel('time (s)')
plt.ylabel(r'$I$ (A)')
plt.show() |
S = list(map(str, input()))
for i in range(len(S)):
if S[i] == '6':
S[i] = '9'
elif S[i] == '9':
S[i] = '6'
S = reversed(S)
print("".join(S)) |
global_variable = "global_variable"
print(global_variable + " printed at the module level.")
class GeoPoint():
class_attribute = "class_attribute"
print(class_attribute + " printed at the class level.")
def __init__(self):
global global_variable
print(global_variable + " printed at the method level.")
print(GeoPoint.class_attribute + " printed at the method level.")
print(class_attribute + " printed at the method level without class.")
self.instance_variable = "self.instance_variable"
print(self.instance_variable + " printed at the method level.")
method_local_variable = "method_local_variable"
print(method_local_variable + " printed at the method level.")
def another_method(self):
# No access to method_local_variable here
print(method_local_variable + " printed within another method.")
|
#!/usr/bin/env python3
#!/usr/bin/python
str1 = 'test1'
if str1 == 'test1' or str1 == 'test2':
print('1 or 2')
elif str1 == 'test3' or str1 == 'test4':
print("3 or 4")
else:
print("else")
str1 = ''
if str1:
print(("'%s' is True" % str1))
else:
print(("'%s' is False" % str1))
str1 = ' '
if str1:
print(("'%s' is True" % str1))
else:
print(("'%s' is False" % str1))
|
"""This module handles numbers"""
class NAN(ValueError):
def __init__(self, value):
super().__init__(f"NAN: {value}")
def _eval(value, kind, default=None):
try:
return kind(value)
except (ValueError, TypeError):
# if default is None:
# raise NAN(value)
if isinstance(value, (str, type(None))):
return default
try:
return len(value)
except TypeError:
raise NAN(value)
as_int = lambda x: _eval(x, int)
as_float = lambda x: _eval(x, float)
inty = lambda x: _eval(x, int, x)
floaty = lambda x: _eval(x, float, x)
|
# Python Class 1
# variable <-- Left
# = <-- Assign
# data = int, String, char, boolean, float
name = "McGill University"
age = 10
is_good = False
height = 5.6
print("Name is :" + name)
print("Age is :" + str(age))
print("He is good :" +str(is_good))
|
# -*- coding: utf-8 -*-
"""Utility exception classes."""
# Part of Clockwork MUD Server (https://github.com/whutch/cwmud)
# :copyright: (c) 2008 - 2017 Will Hutcheson
# :license: MIT (https://github.com/whutch/cwmud/blob/master/LICENSE.txt)
class AlreadyExists(Exception):
"""Exception for adding an item to a collection it is already in."""
def __init__(self, key, old, new=None):
self.key = key
self.old = old
self.new = new
class ServerShutdown(Exception):
"""Exception to signal that the server should be shutdown."""
def __init__(self, forced=True):
self.forced = forced
class ServerReboot(Exception):
"""Exception to signal that the server should be rebooted."""
class ServerReload(Exception):
"""Exception to signal that the server should be reloaded."""
def __init__(self, new_pid=None):
self.new_pid = new_pid
|
e,f,c = map(int,input().split())
bottle = (e+f)//c
get = (e+f)%c + bottle
while 1:
if get < c: break
bottle += get//c
get = get//c + get%c
print(bottle) |
TESTING = True
HOST = "127.0.0.1"
PORT = 8000
|
def to_star(word):
vowels = ['a', 'e' ,'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
for char in vowels:
word = word.replace(char,"*")
return word
word = input("Enter a word: ")
print(to_star(word)) |
"""
Constants for 'skills' table
"""
table_ = "skillsScores"
timestamp = "timestamp"
team_num = "teamNum"
skills_type = "type"
skills_type_driving = 1
skills_type_programming = 2
red_balls = "redBalls"
blue_balls = "blueBalls"
owned_goals = "ownedGoals"
score = "score"
stop_time = "stopTime"
referee = "referee"
create_ = "CREATE TABLE IF NOT EXISTS " + table_ + " ( " \
+ timestamp + " INTEGER NOT NULL, " \
+ team_num + " TEXT NOT NULL, " \
+ skills_type + " INTEGER NOT NULL, " \
+ red_balls + " INTEGER NOT NULL, " \
+ blue_balls + " INTEGER NOT NULL, " \
+ owned_goals + " TEXT NOT NULL, " \
+ score + " INTEGER NOT NULL, " \
+ stop_time + " INTEGER NOT NULL, " \
+ referee + " TEXT NOT NULL " \
+ ");"
|
"""
To create a cli command add a new file appended by the command
for example:
if I want to create a command called test:
- I will create a file cmd_test
- create a function cli and run my command
To run command on cli:
with docker: docker-compose exec your-image yourapp your-command
without docker:
- export FLASK_APP='/path/to/flask/app'
- flask run your command
To view optional parameter
- docker: doc
""" |
print ("Welcome to the mad lib generator. Please follow along and type your input to each statement or question.")
print ("Name an object")
obj1 = input()
print ("Name the plural of your previous object")
obj3 = input()
print ("Name a different plural object")
obj2 = input()
print ("Name a color")
color1 = input()
print ("What is the weather today?")
weather = input()
print ("Name an adjective ending in 'ly'")
adj1 = input()
print ("Name a feeling (present tense)")
feeling = input()
print ("Name an adjective ending in 'ly'")
adj2 = input()
print ("Name a verb (past tense)")
verb1 = input()
print ("Name a color")
color2 = input()
print ("Name an adjective")
adj3 = input()
print ("Name a quality or a person or thing")
quality1 = input()
print ("Name a quality or a person or thing")
quality2 = input()
#Print Song Title
print ("\t*O Christmas Tree Mad Lib*")
#Verse 1
print ("\n O Christmas %s," %obj1 )
print ("O Christmas %s," %obj1 )
print ("How lovely are your %s!" %obj2)
print ("O Christmas %s," %obj1 )
print ("O Christmas %s," %obj1 )
print ("How lovely are your %s!" %obj2)
print ("Not only %s in summer's heat," %color1)
print ("But also winter's snow and %s" %weather)
print ("O Christmas %s," %obj1 )
print ("O Christmas %s," %obj1 )
print ("How lovely are your %s!" %obj2)
# Verse 2
print ("\n O Christmas %s," %obj1 )
print ("O Christmas %s," %obj1 )
print ("Of all the %s most %s;" %(obj3, adj1))
print ("O Christmas %s," %obj1 )
print ("O Christmas %s," %obj1 )
print ("Of all the %s most %s;" %(obj3, adj1))
print ("Each year you bring to us %s" %feeling)
print ("With %s shinning Christmas light!" %adj2)
print ("O Christmas %s," %obj1 )
print ("O Christmas %s," %obj1 )
print ("Of all the %s most %s." %(obj1, adj1))
# Verse 3
print ("\n O Christmas %s," %obj1 )
print ("O Christmas %s," %obj1 )
print ("We %s from all your beauty;" %verb1)
print ("O Christmas %s," %obj1 )
print ("O Christmas %s," %obj1 )
print ("We %s from all your beauty;" %verb1)
print ("Your bright %s leaves with %s cheer," %(color2, adj3))
print ("Give %s and %s throughout the year." %(quality1, quality2))
print ("O Christmas %s," %obj1 )
print ("O Christmas %s," %obj1 )
print ("We %s from all your beauty;" %verb1)
print ("\nHappy Holidays! And congratulations on making a new song: 'O Christmas %s!'" %obj1 ) |
students = {
"ivan": 5.50,
"alex": 3.50,
"maria": 5.50,
"georgy": 5.50,
}
for k,v in students.items():
if v > 4.50:
print( "{} - {}".format(k, v) ) |
#!/usr/bin/python
# pylint: disable=W0223
"""
Utilities for formatting html pages
"""
def wrap(headr, data):
"""
Input:
headr -- text of html field
data -- text to be wrapped.
Returns a corresponding portion of an html file.
"""
return '<%s>%s</%s>' % (headr, data, headr)
def fmt_table(tbl_info):
"""
Format a table. tbl_info is a list of lists. Each list in tbl_info
is a line of fields. Wrap the fields in td html blocks and the lines
in tr html blocks
"""
output = []
for tline in tbl_info:
local_line = ''
for field in tline:
local_line += wrap('td', field)
output.append(wrap('tr', local_line))
return '\n'.join(output)
def make_header(header):
"""
header is a list of text fields.
Return a string representing the html text for a table header.
"""
retv = ''
for field in header:
retv += wrap('th', field)
return wrap('tr', retv)
class OutputInterface(object):
"""
Output html file.
"""
def __init__(self, template):
self.out_data = ''
self.filename = ''
with open(template, 'r') as inputstr:
self.template = inputstr.read()
def build_page(self, filename, title, headerl, table_data):
"""
Construct the html file based on the values of the other
three parameters.
"""
header = make_header(headerl)
self.out_data = self.template % title
self.out_data += header
self.out_data += table_data
self.out_data += '\n</table></div></body></html>\n'
self.filename = filename
def output(self):
"""
This routine writes out the data constructed by build_page.
"""
with open(self.filename, 'w') as ofile:
ofile.write(self.out_data)
def inject(self, edits):
"""
Add some text into the html data. Edits is a list of paired entries
consisting of text to add and text to insert this text in front of.
"""
for fix_text in edits:
indx = self.out_data.find(fix_text[1])
firstp = self.out_data[0:indx]
secondp = self.out_data[indx:]
self.out_data = firstp + fix_text[0] + secondp
def get_template(self):
"""
Return saved template value
"""
return self.template
|
#crie um programa que leia varios numeros inteiros pelo teclado, no final
#deve mostrar a média entre todos os valores e qual foi o maior e menor valor digitado
#o programa deve perguntar se deseja continuar ou não digitando valores
resp = 'S'
soma = 0
quantidade = 0
media = 0
menor = 0
maior = 0
while resp != 'N':
n1 = int(input('Digite um número: '))
resp = str(input('Deseja continuar? [S/N]').strip().upper())[0]
quantidade = quantidade + 1
if quantidade == 1:
maior = n1
menor = n1
if n1 > maior:
maior = n1
if n1 < menor:
menor = n1
soma = soma + n1
if resp == 'S':
media = soma / quantidade
print(f'O maior número digitado foi: {maior} e o menor foi {menor}')
print(f'A media entre {soma} é de {media} e a quantidade total de números foi {quantidade}') |
# This script will track two lists through a 3-D printing process
# Source code/inspiration/software
# Python Crash Course by Eric Matthews, Chapter 8, example 8+
# Made with Mu 1.0.3 in October 2021
# Start with a list of unprinted_designs to be 3-D printed
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
for unprinted_design in unprinted_designs:
print("The following model will be printed: " + unprinted_design)
completed_models =[]
print("\n ")
# Track unprinted_designs as they are 3-D printed
while unprinted_designs:
current_design = unprinted_designs.pop()
# Track model in the 3-D print process
print("Printing model: " + current_design)
completed_models.append(current_design)
# Generate a list of printed designs
print("\nThe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
|
# from typing import Counter
# counter={}
words=input().split(" ")
counter ={ x:words.count(x) for x in set(words)}
print('max: ', max(counter))
print('min: ', min(counter))
# a = input().split()
# d = {}
# for x in a:
# try:
# d[x] += 1
# except:
# d[x] = 1
# print('max: ', max(d))
# print('min: ', min(d))
# words = input().split()
# counter={}
# for word in set(words):
# counter[word] = words.count(word)
# print(word)
# print('max: ', max(counter))
# print('min: ', min(counter)) |
fajl=open("egyszamjatek.txt", "r")
#sdkjfhsdkfjh
jatekos=[]
for sor in fajl:
rekord=sor.rstrip().split()
Fszam=len(rekord)-1
for i in range(Fszam):
rekord[i]=int(rekord[i])
jatekos.append(rekord)
fajl.close()
Jszam=len(jatekos)
print("3. feladat: Játékosok száma: ", Jszam)
print("4. feladat: Fordulók száma: ", Fszam)
voltEgyes = False
for i in range(Jszam):
if jatekos[i][0]==1:
voltEgyes=True
break;
if voltEgyes:
print("5. feladat: Az egyes fordulóban volt egyes tipp")
else:
print("5. feladat: Az egyes fordulóban NEM volt egyes tipp")
tippek=[jatekos[i][j] for i in range(Jszam) for j in range(Fszam)]
maxtipp=max(tippek)
print("6. feladat: A legnagyobb tipp a fordulók során: ", maxtipp)
sorszam=input("Kérem a forduló sorszámát [1-"+str(Fszam)+"]")
sorszam=int(sorszam)
sz=100*[0]
for i in range(Jszam):
szam=jatekos[i][sorszam-1]
sz[szam]+=1
nyertesTipp=0
for i in range(1, 100):
if sz[i]==1:
nyertesTipp = i;
break;
if nyertesTipp>0:
print("7. feladat: A nyertes tipp a megadott forduloban: ", nyertesTipp)
else:
print("7. feladat: A megadottt forduloban nem volt nyertes. ")
#8. feladat: a nyertes neve
nyertes=""
for i in range(Jszam):
if jatekos[i][sorszam-1]==nyertesTipp:
nyertes=jatekos[i][10]
if len(nyertes)!=0:
print("8. feladat: A megadott fordulo nyertese: "+ nyertes)
else:
print("A 8. feladat: a megadott forduloban nem volt nyertes. ")
if nyertesTipp>0:
fajl=open("pythonnyertes.txt", "w")
fajl.write("Fordulo sorszama: "+str(sorszam)+"\n")
fajl.write("Nyertes tipp: "+str(nyertesTipp)+"\n")
fajl.write("Nyertes jatekos: "+nyertes+"\n");
fajl.close()
|
# This file is part of the Extra-P software (http://www.scalasca.org/software/extra-p)
#
# Copyright (c) 2020, Technical University of Darmstadt, Germany
#
# This software may be modified and distributed under the terms of a BSD-style license.
# See the LICENSE file in the base directory for details.
class RecoverableError(RuntimeError):
def __init__(self, *args: object) -> None:
super().__init__(*args)
class FileFormatError(RecoverableError):
NAME = 'File Format Error'
def __init__(self, *args: object) -> None:
super().__init__(*args)
class InvalidExperimentError(RecoverableError):
NAME = 'Invalid Experiment Error'
def __init__(self, *args: object) -> None:
super().__init__(*args)
class CancelProcessError(RecoverableError):
NAME = 'Canceled Process'
def __init__(self, *args: object) -> None:
super().__init__(*args)
|
"""
Examples will be published soon ...
"""
|
def greet(first_name, last_name):
print(f"Hi {first_name} {last_name}")
greet("Tom", "Hill")
|
"""
Desafio 005
Problema: Faça um programa que leia um número inteiro e mostre na tela
o seu sucessor e antecessor.
Resolução do problema:
"""
num = int(input('Informe um valor: '))
sucessor = num + 1
antecessor = num - 1
print('Antecessor: {}\nInformado: {}\nSucessor: {}' .format(antecessor, num, sucessor))
|
"""
This script takes two input strings and compare them to check if they are anagrams or not.
"""
def mysort(s): #function that splits the letters
d=sorted(s)
s=''.join(d)
return s
s1=input("enter first word ")
n1=mysort(s1) #function invocation /calling the function
s2=input("enter second word ")
n2=mysort(s2)
if n1.lower()==n2.lower():
print(s1," and ",s2," are anagrams")
else:
print(s1," and ",s2," are not anagrams")
|
# Copyright (c) 2022, INRIA
# Copyright (c) 2022, University of Lille
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
class CPUTopology:
"""
This class stores the necessary information about the CPU topology.
"""
def __init__(self, tdp, freq_bclk, ratio_min, ratio_base, ratio_max):
"""
Create a new CPU topology object.
:param tdp: TDP of the CPU in Watt
:param freq_bclk: Base clock in MHz
:param ratio_min: Maximum efficiency ratio
:param ratio_base: Base frequency ratio
:param ratio_max: Maximum frequency ratio (with Turbo-Boost)
"""
self.tdp = tdp
self.freq_bclk = freq_bclk
self.ratio_min = ratio_min
self.ratio_base = ratio_base
self.ratio_max = ratio_max
def get_min_frequency(self):
"""
Compute and return the CPU max efficiency frequency.
:return: The CPU max efficiency frequency in MHz
"""
return self.freq_bclk * self.ratio_min
def get_base_frequency(self):
"""
Compute and return the CPU base frequency.
:return: The CPU base frequency in MHz
"""
return self.freq_bclk * self.ratio_base
def get_max_frequency(self):
"""
Compute and return the CPU maximum frequency. (Turbo-Boost included)
:return: The CPU maximum frequency in MHz
"""
return self.freq_bclk * self.ratio_max
def get_supported_frequencies(self):
"""
Compute the supported frequencies for this CPU.
:return: A list of supported frequencies in MHz
"""
return list(range(self.get_min_frequency(), self.get_max_frequency() + 1, self.freq_bclk))
|
print()
print("--- Math ---")
print(1+1)
print(1*3)
print(1/2)
print(3**2)
print(4%2)
print(4%2 == 0)
print(type(1))
print(type(1.0)) |
directions = [(-1,0), (0,1), (1,0), (0,-1), (0,0)]
dirs = ["North", "East", "South", "West", "Stay"]
def add(a, b):
return tuple(map(lambda a, b: a + b, a, b))
def sub(a,b):
return tuple(map(lambda a, b: a - b, a, b))
def manhattan_dist(a, b):
return abs(a[0]-b[0]) + abs(a[1]-b[1])
def direction_to_cmd(p):
return dirs[directions.index((p[0],p[1]))]
def cmd_to_direction(c):
return directions[dirs.index(c)]
|
def even_fibo():
a =1
b = 1
even_sum = 0
c =0
while(c<= 4000000):
c = a + b
a = b
b = c
if(c %2 == 0):
even_sum = c + even_sum
print(even_sum)
if __name__ == "__main__":
print("Project Euler Problem 1")
even_fibo()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 24 16:18:39 2018
@author: pamelaanderson
"""
def clean_ad_ev_table(df):
""" This function cleans the adverse event reporting data- correcting for drug labeling information
using CMS database as the 'truth' to correct to """
df['drug_generic_name'] = df['drug_generic_name'].str.lower()
df['drug_brand_name'] = df['drug_brand_name'].str.lower()
# Fix generics names
drug_gen_series = df['drug_generic_name']
drug_gen_series = drug_gen_series.str.replace('hydrochloride', 'hci')
drug_gen_series = drug_gen_series.str.replace('acetaminophen', 'acetaminophen with codeine')
drug_gen_series = drug_gen_series.str.replace('acetaminophen and codeine phosphate', 'acetaminophen with codeine')
drug_gen_series = drug_gen_series.str.replace('acetaminophen with codeine and codeine phosphate', 'acetaminophen with codeine')
drug_gen_series = drug_gen_series.str.replace('acetazolamide sodium', 'acetazolamide')
drug_gen_series = drug_gen_series.str.replace('acyclovir sodium', 'acyclovir')
drug_gen_series = drug_gen_series.str.replace('albuterol', 'albuterol sulfate')
drug_gen_series = drug_gen_series.str.replace('alfuzosin', 'alfuzosin hci')
drug_gen_series = drug_gen_series.str.replace('betaxolol', 'betaxolol hci')
drug_gen_series = drug_gen_series.str.replace('carbidopa and levodopa', 'carbidopa\levodopa')
drug_gen_series = drug_gen_series.str.replace('estradiol,', 'estradiol')
drug_gen_series = drug_gen_series.str.replace('levetiracetam injection', 'levetiracetam')
drug_gen_series = drug_gen_series.str.replace('lisinopril and hydrochlorothiazide', 'lisinopril/hydrochlorothiazide')
drug_gen_series = drug_gen_series.str.replace('pantoprazole', '')
drug_gen_series = drug_gen_series.str.replace('raloxifene', 'raloxifene hci')
drug_gen_series[(df['drug_generic_name'] == 'metoprolol') & (df['drug_manuf_name'] != 'AstraZeneca Pharmaceuticals LP')] = 'metoprolol succinate'
drug_gen_series[(df['drug_generic_name'] == 'montelukast') & (df['drug_manuf_name'] != 'Merck Sharp & Dohme Corp.')] = 'montelukast sodium'
drug_gen_series[(df['drug_generic_name'] == 'pantoprazole') & (df['drug_manuf_name'] == 'Camber Pharmaceuticals, Inc.')] = 'pantoprazole sodium'
drug_gen_series[(df['drug_generic_name'] == 'sertraline') & (df['drug_manuf_name'] != 'Pfizer Laboratories Div Pfizer Inc')] = 'sertraline hci'
# Fix brands names
drug_brand_series = df['drug_brand_name']
drug_brand_series = drug_brand_series.replace('fluoxetine', 'fluoxetine hci')
drug_brand_series = drug_brand_series.replace('hydrochloride', 'hci')
drug_brand_series = drug_brand_series.replace('tylenol regular strength', 'Tylenol-Codeine No.3')
drug_brand_series = drug_brand_series.replace('tylenol with codeine', 'Tylenol-Codeine No.3')
drug_brand_series = drug_brand_series.str.replace('albuterol', 'albuterol sulfate')
drug_brand_series = drug_brand_series.str.replace('alfuzosin hydrochloride', 'alfuzosin hci er')
drug_brand_series = drug_brand_series.str.replace('aloprim', 'allopurinol')
drug_brand_series = drug_brand_series.str.replace('amlodipine besylate 10 mg', 'amlodipine besylate')
drug_brand_series[(df['drug_generic_name'] == 'atenolol') & (df['drug_manuf_name'] != 'AstraZeneca Pharmaceuticals LP')] = 'atenolol'
drug_brand_series = drug_brand_series.str.replace('betaxolol', 'betaxolol hci')
drug_brand_series[(df['drug_generic_name'] == 'casodex') & (df['drug_manuf_name'] != 'AstraZeneca Pharmaceuticals LP')] = 'bicalutamide'
drug_brand_series = drug_brand_series.str.replace('brimonidine', 'brimonidine tartrate')
drug_brand_series[(df['drug_generic_name'] == 'candesartan cilexetil') & (df['drug_manuf_name'] != 'AstraZeneca Pharmaceuticals LP')] = 'candesartan cilexetil'
drug_brand_series[(df['drug_generic_name'] == 'carbamazepine') & (df['drug_manuf_name'] != 'Novartis Pharmaceuticals Corporation')] = 'carbamazepine'
drug_brand_series = drug_brand_series.str.replace('carisoprodol immediate release', 'carisoprodol')
drug_brand_series = drug_brand_series.str.replace('celecoxib 50 mg', 'celecoxib')
drug_brand_series = drug_brand_series.str.replace('cipro hc', 'cipro')
drug_brand_series[(df['drug_generic_name'] == 'clopidogrel bisulfate') & (df['drug_manuf_name'] != 'Bristol-Myers Squibb/Sanofi Pharmaceuticals Partnership')] = 'clopidogrel bisulfate'
drug_brand_series = drug_brand_series.str.replace('diltiazem hci extended release', 'diltiazem hci')
drug_brand_series = drug_brand_series.str.replace('diltiazem hci extended release', 'diltiazem hci')
drug_brand_series = drug_brand_series.str.replace('duloxetine delayed-release', 'duloxetine hci')
drug_brand_series[(df['drug_generic_name'] == 'enoxaparin sodium') & (df['drug_manuf_name'] != 'sanofi-aventis U.S. LLC')] = 'enoxaparin sodium'
drug_brand_series[(df['drug_generic_name'] == 'exemestane') & (df['drug_manuf_name'] != 'Pharmacia and Upjohn Company LLC')] = 'exemestane'
drug_brand_series = drug_brand_series.str.replace('fentanyl - novaplus', 'fentanyl')
drug_brand_series[(df['drug_generic_name'] == 'furosemide') & (df['drug_manuf_name'] != 'Sanofi-Aventis U.S. LLC')] = 'furosemide'
drug_brand_series = drug_brand_series.str.replace('gabapentin kit', 'gabapentin')
drug_brand_series = drug_brand_series.str.replace('gentamicin', 'gentamicin sulfate')
drug_brand_series[(df['drug_generic_name'] == 'glimepiride') & (df['drug_manuf_name'] != 'Sanofi-Aventis U.S. LLC')] = 'glimepiride'
drug_brand_series[(df['drug_generic_name'] == 'irbesartan') & (df['drug_manuf_name'] != 'sanofi-aventis U.S. LLC')] = 'irbesartan'
drug_brand_series[(df['drug_generic_name'] == 'lamotrigine') & (df['drug_manuf_name'] != 'GlaxoSmithKline LLC')] = 'lamotrigine'
drug_brand_series = drug_brand_series.str.replace('health mart lansoprazole', 'lansoprazole')
drug_brand_series= drug_brand_series.str.replace('levetiracetam levetiracetam', 'levetiracetam')
drug_brand_series[(df['drug_generic_name'] == 'levofloxacin') & (df['drug_manuf_name'] != 'Janssen Pharmaceuticals, Inc.')] = 'levofloxacin'
drug_brand_series[(df['drug_generic_name'] == 'lisinopril') & (df['drug_manuf_name'] != 'Merck Sharp & Dohme Corp.')] = 'lisinopril'
drug_brand_series = drug_brand_series.str.replace('acetaminophen and codeine', 'Acetaminophen-Codeine')
drug_brand_series[(df['drug_generic_name'] == 'acyclovir sodium') & (df['drug_manuf_name'] != 'Prestium Pharma, Inc.')] = 'acyclovir'
drug_brand_series[(df['drug_generic_name'] == 'lisinopril') & (df['drug_manuf_name'] != 'LUPIN LIMITED')] = 'lisinopril'
drug_brand_series[(df['drug_generic_name'] == 'lisinopril/hydrochlorothiazide') & (df['drug_manuf_name'] != 'Almatica Pharma Inc.')] = 'lisinopril/hydrochlorothiazide'
drug_brand_series[(df['drug_generic_name'] == 'azacitidine') & (df['drug_manuf_name'] != 'Celgene Corporation')] = 'azacitidine'
drug_brand_series = drug_brand_series.str.replace('methotrexate', 'methotrexate sodium')
drug_brand_series = drug_brand_series.str.replace('montelukast sodium chewable', 'montelukast sodium')
drug_brand_series = drug_brand_series.str.replace('nevirapine extended release', 'nevirapine')
drug_brand_series = drug_brand_series.str.replace('raloxifene', 'raloxifene hci')
drug_brand_series = drug_brand_series.str.replace('being well heartburn relief', 'ranitidine hci')
drug_brand_series = drug_brand_series.str.replace('acid reducer', 'ranitidine hci')
drug_brand_series[(df['drug_generic_name'] == 'meloxicam') & (df['drug_manuf_name'] != 'Boehringer Ingelheim Pharmaceuticals Inc.')] = 'meloxicam'
drug_brand_series[(df['drug_generic_name'] == 'memantine') & (df['drug_manuf_name'] != 'Allergan, Inc.')] = 'memantine'
drug_brand_series[(df['drug_generic_name'] == 'metaxalone') & (df['drug_manuf_name'] != 'Pfizer Laboratories Div Pfizer Inc')] = 'metaxalone'
drug_brand_series[(df['drug_generic_name'] == 'metoprolol') & (df['drug_manuf_name'] != 'AstraZeneca Pharmaceuticals LP')] = 'metoprolol succinate'
drug_brand_series[(df['drug_generic_name'] == 'modafinil') & (df['drug_manuf_name'] != 'Cephalon, Inc.')] = 'modafinil'
drug_brand_series[(df['drug_generic_name'] == 'nateglinide') & (df['drug_manuf_name'] != 'Novartis Pharmaceuticals Corporation')] = 'nateglinide'
drug_brand_series[(df['drug_generic_name'] == 'nitroglycerin') & (df['drug_manuf_name'] != 'Pfizer Laboratories Div Pfizer Inc')] = 'nitroglycerin'
drug_brand_series[(df['drug_generic_name'] == 'oxcarbazepine') & (df['drug_manuf_name'] != 'Novartis Pharmaceuticals Corporation')] = 'oxcarbazepine'
drug_brand_series[(df['drug_generic_name'] == 'oxycodone hci') & (df['drug_manuf_name'] != 'Mallinckrodt ARD Inc.')] = 'oxycodone hci'
drug_brand_series[(df['drug_generic_name'] == 'paclitaxel') & (df['drug_manuf_name'] != 'Celgene Corporation')] = 'paclitaxel'
drug_brand_series[(df['drug_generic_name'] == 'pantoprazole sodium') & (df['drug_manuf_name'] != 'Wyeth Pharmaceuticals LLC, a subsidiary of Pfizer Inc.')] = 'pantoprazole sodium'
drug_brand_series[(df['drug_generic_name'] == 'phenytoin') & (df['drug_manuf_name'] != 'Pfizer Laboratories Div Pfizer Inc')] = 'phenytoin'
drug_brand_series[(df['drug_generic_name'] == 'ranitidine hci') & (df['drug_manuf_name'] != 'GlaxoSmithKline Consumer Healthcare Holdings (US) LLC')] = 'ranitidine hci'
drug_brand_series[(df['drug_generic_name'] == 'sertraline') & (df['drug_manuf_name'] != 'Pfizer Laboratories Div Pfizer Inc')] = 'sertraline hci'
df['drug_generic_name_re'] = drug_gen_series
df['drug_brand_name_re'] = drug_brand_series
return df |
MULTI_ERRORS_HTTP_RESPONSE = {
"errors": [
{
"code": 403,
"message": "access denied, authorization failed"
},
{
"code": 401,
"message": "test error #1"
},
{
"code": 402,
"message": "test error #2"
}
],
"meta": {
"powered_by": "crowdstrike-api-gateway",
"query_time": 0.000654734,
"trace_id": "39f1573c-7a51-4b1a-abaa-92d29f704afd"
}
}
NO_ERRORS_HTTP_RESPONSE = {
"errors": [],
"meta": {
"powered_by": "crowdstrike-api-gateway",
"query_time": 0.000654734,
"trace_id": "39f1573c-7a51-4b1a-abaa-92d29f704afd"
}
}
|
name = 'shell_proc'
version = '1.1.1'
description = 'Continuous shell process'
url = 'https://github.com/justengel/shell_proc'
author = 'Justin Engel'
author_email = 'jtengel08@gmail.com'
|
def open_input():
with open("input.txt") as fd:
array = fd.read().splitlines()
array = list(map(int, array))
return array
def part_one(array):
lenght = len(array)
increased = 0
for i in range(0, lenght - 1):
if array[i] < array[i + 1]:
increased += 1
print("part one:", increased)
def part_two(array):
lenght = len(array)
increased = 0
for i in range(0, lenght - 3):
sum1 = array[i] + array[i + 1] + array[i + 2]
sum2 = array[i + 1] + array[i + 2] + array[i + 3]
if sum1 < sum2:
increased += 1
print("part two:", increased)
if (__name__ == "__main__"):
array = open_input()
part_one(array)
part_two(array)
|
# ===========================================================================
# dictionary.py -----------------------------------------------------------
# ===========================================================================
# function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def update_dict(a, b):
# @todo[comment]:
if a and b and isinstance(a, dict):
a.update(b)
return a
# function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_dict_element(dict_list, field, query):
# @todo[comment]:
for item in dict_list:
if item[field] == query:
return item
return dict()
# function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_dict_elements(dict_list, field, query, update=False):
# @todo[comment]:
if not isinstance(field, list) and isinstance(query, list):
field = [field] * len(query)
result = list() if not update else dict()
if isinstance(field, list) and isinstance(query, list):
for field_item, query_item in zip(field, query):
item = get_dict_element(dict_list, field_item, query_item)
if item:
if not update:
result.append(item)
else:
result.update(item)
return result
|
# selectionsort() method
def selectionSort(arr):
arraySize = len(arr)
for i in range(arraySize):
min = i
for j in range(i+1, arraySize):
if arr[j] < arr[min]:
min = j
#swap values
arr[i], arr[min] = arr[min], arr[i]
# method to print an array
def printList(arr):
for i in range(len(arr)):
print(arr[i],end=" ")
print("\n")
# driver method
if __name__ == '__main__':
arr = [3,4,1,7,6,2,8]
print ("Given array: ", end="\n")
printList(arr)
selectionSort(arr)
print("Sorted array: ", end="\n")
printList(arr) |
# -*- coding: utf-8 -*-
"""Exceptions used in this module"""
class CoincError(Exception):
"""Base Class used to declare other errors for Coinc
Extends:
Exception
"""
pass
class ConfigError(CoincError):
"""Raised when there are invalid value filled in Configuration Sheet
Extends:
CoincError
"""
pass
class QueryError(CoincError):
"""Raised when invalid query were given
Extends:
CoincError
"""
pass
class AppIDError(CoincError):
"""Raised when App ID can not be used
Extends:
CoincError
"""
pass
class ApiError(CoincError):
"""Raised when API is unreachable or return bad response
Extends:
CoincError
"""
pass
class UnknownPythonError(CoincError):
"""Raised when Python runtime version can not be correctly detacted
Extends:
CoincError
"""
pass
|
logo = '''
______ __ __ _ __ __
/ ____/__ __ ___ _____ _____ / /_ / /_ ___ / | / /__ __ ____ ___ / /_ ___ _____
/ / __ / / / // _ \ / ___// ___/ / __// __ \ / _ \ / |/ // / / // __ `__ \ / __ \ / _ \ / ___/
/ /_/ // /_/ // __/(__ )(__ ) / /_ / / / // __/ / /| // /_/ // / / / / // /_/ // __// /
\____/ \__,_/ \___//____//____/ \__//_/ /_/ \___/ /_/ |_/ \__,_//_/ /_/ /_//_.___/ \___//_/
''' |
class AzureBlobUrlModel(object):
def __init__(self, storage_name, container_name, blob_name):
"""
:param storage_name: (str) Azure storage name
:param container_name: (str) Azure container name
:param blob_name: (str) Azure Blob name
"""
self.storage_name = storage_name
self.container_name = container_name
self.blob_name = blob_name
|
'''https://leetcode.com/problems/symmetric-tree/'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isMirror(self, left, right):
if left is None and right is None:
return True
if left is None or right is None:
return False
if left.val==right.val:
return self.isMirror(left.left, right.right) and self.isMirror(left.right, right.left)
else:
return False
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
return self.isMirror(root.left, root.right)
|
def convert_to_bool(string):
"""
Converts string to bool
:param string: String
:str string: str
:return: True or False
"""
if isinstance(string, bool):
return string
return string in ['true', 'True', '1'] |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 27 10:49:39 2020
@author: Arthur Donizeti Rodrigues Dias
"""
class Category:
def __init__(self, categories):
self.ledger=[]
self.categories = categories
self.listaDeposito=[]
self.listaRetirada=[]
self.total_entrada = 0
self.total_saida = 0
def __str__(self):
x = self.categories.center(30,"*")+'\n'
n = 0;
lista_v = []
for i in self.ledger:
for k, v in self.ledger[n].items():
lista_v.append(v)
n+=1
n = 1
for i in self.ledger:
y = str(lista_v[n])
x = x + y[0:23].ljust(23)+str(format(lista_v[n-1], '.2f')).rjust(7)+'\n'
n += 2
x = x + 'Total: '+str(format(self.get_balance(), '.2f'))
return x
def deposit(self, quantia,description=""):
dic ={'amount': quantia, 'description' : description}
self.total_entrada += quantia
self.listaDeposito.append(quantia)
self.listaDeposito.append(description)
self.ledger.append(dic)
def withdraw(self, quantia,description=""):
try:
if self.total_entrada>quantia:
self.total_saida += quantia
dic ={'amount': -quantia, 'description' : description}
self.listaRetirada.append(quantia)
self.listaRetirada.append(description)
self.ledger.append(dic)
return True
else:
return False
except:
return False
def get_balance(self):
return self.total_entrada - self.total_saida
def transfer(self,quantia, beneficiario):
if quantia <= self.total_entrada:
x = f'Transfer to {beneficiario.categories}'
self.withdraw(quantia,x)
beneficiario.deposit(quantia, f'Transfer from {self.categories}' )
return True
else:
return False
def check_funds(self, quantia):
if quantia <= self.get_balance() :
return True
else :
return False
def create_spend_chart(teste):
soma = 0.0
cont = 10
tamanho = 0
lista = []
lista_porcentagem = []
for i in teste:
x = i.categories
if tamanho < len(x):
tamanho = len(x)
soma += i.total_saida
lista.append(x)
for i in teste:
lista_porcentagem.append((i.total_saida/soma)*10)
x = 'Percentage spent by category\n'
while cont >=0:
x += f'{cont*10}|'.rjust(4)
for i in lista_porcentagem:
if i > cont:
x += ' o '
else:
x += ' '
x = x+' \n'
cont -= 1
x += ('--'*len(lista)).rjust(7+len(lista))+'----\n'
aux =0
while tamanho > 0:
x += " "*4
for i in lista:
if len(i)>aux:
x += ' '+i[aux]+' '
else:
x += ' '
if tamanho == 1:
x += " "
else:
x = x+' \n'
aux +=1
tamanho -= 1
return(x)
|
def defaults():
return dict(
actor='mlp',
ac_kwargs={
'pi': {'hidden_sizes': (64, 64),
'activation': 'tanh'},
'val': {'hidden_sizes': (64, 64),
'activation': 'tanh'}
},
adv_estimation_method='gae',
epochs=300, # 9.8M steps
gamma=0.99,
lam_c=0.95,
steps_per_epoch=64 * 1000, # default: 64k
target_kl=0.0001,
use_exploration_noise_anneal=True
)
def locomotion():
"""Default hyper-parameters for Bullet's locomotion environments."""
params = defaults()
params['epochs'] = 312
params['max_ep_len'] = 1000
params['steps_per_epoch'] = 32 * 1000
params['vf_lr'] = 3e-4 # default choice is Adam
return params
# Hack to circumvent kwarg errors with the official PyBullet Envs
def gym_locomotion_envs():
params = locomotion()
return params
def gym_manipulator_envs():
"""Default hyper-parameters for Bullet's manipulation environments."""
params = defaults()
params['epochs'] = 312
params['max_ep_len'] = 150
params['steps_per_epoch'] = 32 * 1000
params['vf_lr'] = 3e-4 # default choice is Adam
return params
|
def ceulcius(x):
return (x - 32)/1.8
x = int(input('Digite uma temperatura em (F°): '))
print(f'A temperatura digitada em {x}F°, é igual a {ceulcius(x):.1f}C°') |
class INestedContainer(IContainer,IDisposable):
""" Provides functionality for nested containers,which logically contain zero or more other components and are owned by a parent component. """
def __enter__(self,*args):
"""
__enter__(self: IDisposable) -> object
Provides the implementation of __enter__ for objects which implement IDisposable.
"""
pass
def __exit__(self,*args):
"""
__exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object)
Provides the implementation of __exit__ for objects which implement IDisposable.
"""
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
Owner=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the owning component for the nested container.
Get: Owner(self: INestedContainer) -> IComponent
"""
|
'''
LeetCode LinkedList Q.876 Middle of the Linked List
Recusion and Slow/Fast Pointer Solution
'''
def middleNode(self, head: ListNode) -> ListNode:
def rec(slow, fast):
if not fast:
return slow
elif not fast.next:
return slow
return rec(slow.next, fast.next.next)
return rec(head, head)
|
class ParameterDefinition(object):
def __init__(self, name, param_type=None, value=None):
self.name = name
self.param_type = param_type
self.value = value
class Parameter(object):
def __init__(self, definition):
self.definition = definition
self.value = definition.value
self.binding = None
|
def check_kwargs(input_kwargs, allowed_kwargs, raise_error=True):
"""Tests if the input `**kwargs` are allowed.
Parameters
----------
input_kwargs : `dict`, `list`
Dictionary or list with the input values.
allowed_kwargs : `list`
List with the allowed keys.
raise_error : `bool`
Raises error if ``True``. If ``False``, it will raise the error listing
the not allowed keys.
"""
not_allowed = [i for i in input_kwargs if i not in allowed_kwargs]
if raise_error:
if len(not_allowed) > 0:
allowed_kwargs.sort()
raise TypeError("function got an unexpected keyword argument {}\n"
"Available kwargs are: {}".format(not_allowed, allowed_kwargs))
else:
return not_allowed
def test_attr(attr, typ, name):
"""Tests attribute.
This function tests if the attribute ``attr`` belongs to the type ``typ``,
if not it gives an error message informing the name of the variable.
"""
try:
return typ(attr)
except:
raise TypeError('"{}" keyword must be a {} object'.format(name, typ))
|
load(":import_external.bzl", import_external = "import_external")
def dependencies():
import_external(
name = "org_apache_httpcomponents_client5_httpclient5",
artifact = "org.apache.httpcomponents.client5:httpclient5:5.1",
artifact_sha256 = "b7a30296763a4d5dbf840f0b79df7439cf3d2341c8990aee4111591b61b50935",
srcjar_sha256 = "d7351329b7720b482766aca78d1c040225a1b4bbd723034c6f686bec538edddd",
deps = [
"@commons_codec_commons_codec",
"@org_apache_httpcomponents_core5_httpcore5",
"@org_apache_httpcomponents_core5_httpcore5_h2",
"@org_slf4j_slf4j_api",
],
)
|
class Solution:
def imageSmoother(self, M: list) -> list:
l = len(M)
if l == 0:
return M
m = len(M[0])
res = []
for i in range(l):
res.append([0] * m)
# print(res)
for x in range(l):
for y in range(m):
summ = 0
count = 0
for i in range(x-1, x+2):
for j in range(y-1, y+2):
if 0 <= i < l and 0 <= j < m:
summ += M[i][j]
count += 1
res[x][y] = int(summ / count)
return res
M = [[1,1,1],
[1,0,1],
[1,1,1]]
s = Solution()
print(s.imageSmoother(M))
|
#!/usr/bin/env python3
# pylint: disable=invalid-name,missing-docstring
def test_get_arns(oa, shared_datadir):
with open("%s/saml_assertion.txt" % shared_datadir) as fh:
assertion = fh.read()
arns = oa.get_arns(assertion)
# Principal
assert arns[0] == 'arn:aws:iam::012345678901:saml-provider/OKTA'
# Role
assert arns[1] == 'arn:aws:iam::012345678901:role/Okta_AdministratorAccess'
|
de = {
"client_id": "Client ID:",
"title": "Titel:",
"details": "Details:",
"state": "Status:",
"buttons": "Buttons:",
"image": "Bild:",
"edit_title": "Titel bearbeiten",
"manage_images": "Bilder verwalten",
"update_rich_presence": "Rich Presence aktualisieren",
"sync_with_apple_music": "Mit Apple Music synchronisieren",
"paused": "Pausiert",
"unknown": "Unbekannt",
"text_1": "Text_1",
"link_1": "Link_1",
"text_2": "Text_2",
"link_2": "Link_2",
"image_name": "Name_des_Bildes",
"error": "Fehler",
"invalid_client_id": "Ungültige Client ID. Bitte überprüfe sie und versuche es erneut.",
"could_not_connect_to_discord": "Konnte keine Verbindung mit Discord herstellen. Überprüfe ob Discord ausgeführt ist und versuche es erneut.",
"invalid_first_link": "Der Link beim ersten Button ist ungültig.",
"invalid_second_link": "Der Link beim zweiten Button ist ungültig.",
"could_not_update": "Rich Presence konnte nicht aktualisiert werden. Überprüfe ob alle informationen korrekt angegeben wurden und ob Discord ausgeführt ist.",
"update_available": "Update verfügbar",
"would_you_like_to_update": "Eine neue Version ist verfübar. Möchtest du sie herunterladen?",
"apple_music_only_macos": "Mit Apple Music synchronisieren ist aktuell nur auf macOS verfügbar.",
"enable_minimized_mode": "Minimierten Modus aktivieren",
"open_program": "Öffnen",
"stop_program": "Beenden",
"minimized_not_linux": "Der minimierte Modus ist aktuell nicht auf Linux verfügbar"
}
|
__all__ = [
"cart_factory",
"cart",
"environment",
"job_factory",
"job",
"location",
"trace",
]
|
TITLE = "The World of Light and Shadow"
ALPHABET = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
ALPHABET += ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
MISC = [",", "!", "#", "$", "%", "&", "*", "(", ")", "-", "_", "+", "=", "`", "~", ".", ";", ":", " ", "?", "@", "[", "]", "{", "}"]
NUMBERS = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
CLEAN_CHARS = ALPHABET + MISC + NUMBERS
ZONE_NAMES = ["harbor"]
# ---------------------------------------------
TILESIZE = 120
TILES_WIDE = 4
TILES_HIGH = 4
WINDOW_WIDTH = TILESIZE * TILES_WIDE
WINDOW_HEIGHT = TILESIZE * TILES_HIGH
# ---------------------------------------------
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
DARKGREY = (40, 40, 40)
LIGHTGREY = (200, 200, 200)
DARK_GREEN = ( 0, 153, 0)
GREEN = (0, 255, 0)
DARK_RED = (204, 0, 0)
RED = (255, 0, 0)
ORANGE = (255, 128, 0)
YELLOW = (255, 255, 0)
BROWN = (106, 55, 5)
AQUA = ( 0, 255, 255)
BLUE = ( 0, 0, 255)
FUCHIA = (255, 0, 255)
GRAY = (128, 128, 128)
LIME = ( 0, 255, 0)
MAROON = (128, 0, 0)
NAVY_BLUE = ( 0, 0, 128)
OLIVE = (128, 128, 0)
PURPLE = (128, 0, 128)
LIGHT_PURBLE = (255, 153, 255)
SILVER = (192, 192, 192)
TEAL = ( 0, 128, 128)
BACKGROUND_COLOR = WHITE
|
class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
def dfs(r, c, val):
grid[r][c] = val
for nr, nc in (r-1, c), (r+1, c), (r, c-1), (r, c+1):
if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] != val:
dfs(nr, nc, val)
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j] == 0 and (i == 0 or i == len(grid) - 1 or j == 0 or j == len(grid[i]) - 1):
dfs(i, j, 1)
count = 0
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j] == 0:
count += 1
dfs(i, j, 1)
return count
|
# you can use print for debugging purposes, e.g.
# print "this is a debug message"
def solution(A):
# write your code in Python 2.7
N = len(A)
counter = []
leader = -1
leader_count = 0
left_leader_count = 0
equi_count = 0
for i in xrange(N):
if not counter:
counter.append((A[i], 1))
elif counter[0][0] == A[i]:
counter[0] = (counter[0][0], counter[0][1]+1)
elif counter[0][1] > 1:
counter[0] = (counter[0][0], counter[0][1]-1)
else:
counter.pop()
if counter:
for i in xrange(N):
if A[i] == counter[0][0]:
leader_count += 1
if leader_count > N/2:
leader = counter[0][0]
else:
return 0
else:
return 0
for i in xrange(N):
if leader == A[i]:
left_leader_count += 1
if left_leader_count > (i+1)/2:
if leader_count - left_leader_count > (N-(i+1))/2:
equi_count += 1
return equi_count
|
# this py file will be strictly dedicated to "Boolean Logic"
# Boolean Logic is best defined as the combination of phrases that can result in printing different values
# define two variables
a = True
b = False
# if-statement... output: True
# the if condition prints, if the "if statement" evaluates to True
if a:
print("True")
else:
print("False")
if b: # output: False
print("True")
else:
print("False")
'''
and: both clauses must be True
or: one of the clauses must be True
'''
# and-statements... output: Neither
if a and b:
print("Both")
else:
print("Neither")
# or-statement... output: Both
if a or b:
print("Both")
else:
print("Neither")
# define new variables to demonstrate truth table
x = True
y = True
# output: True
if x and y:
print("True")
else:
print("False")
# output: True
if (x and y) or x:
print("True")
else:
print("False")
# new reassignment
# x still equals True
y = False
# output: False
if x and y:
print("True")
else:
print("False")
# output: True
if x or y:
print("True")
else:
print("False")
# output: True
if (x or y) and x:
print("True")
else:
print("False")
# output: True
if (x and y) or x:
print("True")
else:
print("False")
# output: False
if not x and not y:
print("True")
else:
print("False") |
class Solution(object):
def robot(self, command, obstacles, x, y):
"""
:type command: str
:type obstacles: List[List[int]]
:type x: int
:type y: int
:rtype: bool
"""
# zb = [0, 0]
# ind = 0
# while True:
# if command[ind] == 'U':
# zb = [zb[0], zb[1]+1]
# elif command[ind] == 'R':
# zb = [zb[0]+1, zb[1]]
# # print(zb)
# if zb == [x, y]:
# return True
# if zb in obstacles:
# return False
# if zb[0] > x or zb[1] > y:
# return False
# if ind < len(command)-1:
# ind += 1
# elif ind == len(command)-1:
# ind = 0
# return False
xi = 0
yi = 0
zb = [0, 0]
for c in command:
if c == 'R':
xi += 1
if c == 'U':
yi += 1
epoch = min(x//xi, y//yi)
x_ = x-epoch*xi
y_ = y-epoch*yi
zb = [0, 0]
is_reach = False
for i in command:
if zb == [x_, y_]:
is_reach = True
if i == 'R':
zb = [zb[0]+1, zb[1]]
if i == 'U':
zb = [zb[0], zb[1]+1]
obstacles_ = []
for item in obstacles:
if item[0]<=x and item[1]<=y:
obstacles_.append(item)
for ob in obstacles_:
cur_epo = min(ob[0]//xi, ob[1]//yi)
cur_x = ob[0]-cur_epo*xi
cur_y = ob[1]-cur_epo*yi
cur_zb = [0, 0]
for cm in command:
print(cur_zb)
if cur_zb == [cur_x, cur_y]:
return False
if cm == 'R':
cur_zb = [cur_zb[0]+1, cur_zb[1]]
if cm == 'U':
cur_zb = [cur_zb[0], cur_zb[1]+1]
return is_reach
|
"""Contains the ItemManager class, used to manage items.txt"""
class ItemManager:
"""A class to manage items.txt."""
def __init__(self):
self.items_file = 'txt_files/items.txt'
def clear_items(self):
with open(self.items_file, 'w') as File:
File.write("Items:\n")
print("Items Cleared!")
def recover_items(self):
try:
with open(self.items_file, 'r') as file: # Try to read the file
read_data = file.readlines()
except FileNotFoundError: # If the file doesn't exist
with open(self.items_file, 'w') as file: # Create the file
file.write("Items:\n")
# Write this line at the start
with open(self.items_file, 'r') as file:
read_data = file.readlines()
read_data = read_data[1:] # Remove first line of file, which is
# "Items:"
if not read_data:
print("No Data Found.")
return None
else:
new_read_data = [] # New read data gets set to the old read
# data, but
# without the newlines at the end of each line.
for line in read_data:
new_read_data.append(line.rstrip("\n"))
read_data = new_read_data
print("Data Found!")
item_data = []
for line in read_data: # Save the old data to this program
item_data.append((str(line[4:]), int(line[:3])))
print("Item data saved!")
return item_data
def add_item(self, item, position):
position = str(position)
for _ in range(0, 3 - len(position)):
position = f"0{position}" # Make positions 3-digit numbers.
# E.g. 12 becomes 012
position += " " # Add a space at the end of position
text = position + item + "\n"
try:
with open(self.items_file, 'a') as file:
file.write(text)
except FileNotFoundError:
with open(self.items_file, 'w') as file:
file.write("Items:\n{text}")
def remove_item(self, item):
newlines = ""
try:
with open(self.items_file, 'r') as file:
old_lines = file.readlines()
except FileNotFoundError:
with open(self.items_file, 'w') as file:
file.write("Items:\n")
print("File Not Found.")
return
for line in old_lines[1:]:
if item not in line:
newlines += line
newlines += "\n"
with open(self.items_file, 'w') as file:
file.write("Items:\n")
with open(self.items_file, 'a') as file:
file.write(newlines)
|
words = set(
(
"scipy",
"Combinatorics",
"rhs",
"lhs",
"df",
"AttributeError",
"Cymru",
"FiniteSet",
"Jupyter",
"LaTeX",
"Modularisation",
"NameError",
"PyCons",
"allclose",
"ax",
"bc",
"boolean",
"docstring",
"dtype",
"dx",
"dy",
"expr",
"frisbee",
"inv",
"ipynb",
"isclose",
"itertools",
"jupyter",
"len",
"nbs",
"nd",
"np",
"numpy",
"solveset",
"sqrt",
"sym",
"sympy",
"th",
)
)
prose_exceptions = {
"assets/nbs/assessment/mock/main.ipynb": set(
(
r"The matrix \\(D\\) is given by \\(D = \begin{pmatrix} a & 2 & 0\\ 3 & 1 & 2\\ 0 & -1 & 1\end{pmatrix}\\) where \\(a\ne 2\\).",
),
),
"assets/nbs/assessment/mock/assignment.ipynb": set(
(
r"The matrix \\(D\\) is given by \\(D = \begin{pmatrix} a & 2 & 0\\ 3 & 1 & 2\\ 0 & -1 & 1\end{pmatrix}\\) where \\(a\ne 2\\).",
)
),
"assets/nbs/assessment/mock/solution.ipynb": set(
(
r"The matrix \\(D\\) is given by \\(D = \begin{pmatrix} a & 2 & 0\\ 3 & 1 & 2\\ 0 & -1 & 1\end{pmatrix}\\) where \\(a\ne 2\\).",
)
),
}
prose_suggestions_to_ignore = {
"assets/nbs/assessment/2020/main.ipynb": set(
("typography.symbols.curly_quotes", "garner.preferred_forms")
),
"assets/nbs/assessment/2020/solution.ipynb": set(
("typography.symbols.curly_quotes", "garner.preferred_forms")
),
"assets/nbs/assessment/mock/main.ipynb": set(
("typography.symbols.curly_quotes", "garner.preferred_forms")
),
"assets/nbs/assessment/mock/assignment.ipynb": set(
("typography.symbols.curly_quotes", "garner.preferred_forms")
),
"assets/nbs/assessment/mock/solution.ipynb": set(
("typography.symbols.curly_quotes", "garner.preferred_forms")
),
"assets/nbs/assessment/example/main.ipynb": set(
(
"typography.symbols.curly_quotes",
"typography.symbols.ellipsis",
"garner.preferred_forms",
)
),
}
|
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
"""
if not intervals: return[]
# 按区间的 start 升序排列
intervals.sort(key=lambda intv : intv[0])
res = []
res.append(intervals[0])
for i in range(1, len(intervals)):
curr = intervals[i]
# res中最后一个元素的引用
last = res[-1]
if curr[0] <= last[1]:
# 找到最大的end
last[1] = max(last[1], curr[1])
else:
# 处理下一个待合并区间
res.append(curr)
return res |
#Booleans are operators that allow you to convey True or False statements
print(True)
print(False)
type(False)
print(1>2)
print(1==1)
b= None #None is used as a placeholder for an object that has not been assigned , so that object unassigned errors can be avoided
type(b)
print(b)
type(True)
|
class ServerState:
"""Class for server state"""
def __init__(self):
self.history = set()
self.requests = 0
def register(self, pickup_line):
self.requests += 1
self.history.add(pickup_line)
def get_status(self):
return "<table> " + \
wrap_in_row("<b>Pickup lines delivered: </b>", str(self.requests)) + \
wrap_in_row("<b>Unique pickup lines delivered: </b>", str(len(self.history))) + \
"</table>" + \
"<h3>Generated pickup lines:</h3>" + \
("<br/>".join(self.history))
def wrap_in_row(input1, input2):
return "<tr>" \
"<td>" + input1 + "</td>" + \
"<td>" + input2 + "</td>" + \
"</tr>"
|
eso_races = {}
eso_desc = {}
eso_passive = {}
eso_alliance = {}
eso_raceimg = {}
eso_allianceinfo = {}
eso_allianceimg = {}
"""
Daggerfall Covenant (Breton, Redguard, Orc)
"""
eso_allianceimg["daggerfall"] = "http://esoacademy.com/wp-content/uploads/2014/12/DC.png"
eso_allianceinfo["daggerfall"] = "Daggerfall Covenant is a Faction in Elder Scrolls Online. The Daggerfall Covenant is a compact between the peoples of \
northwest Tamriel—Bretons, Redguards, and Orcs—that forms an alliance of mutual defense, with a vision of establishing peace and order across Tamriel. \
Indeed, the kings of the Covenant take the Remans as their model, claiming to be the spiritual heirs of the Second Empire.\
So this is the modern Daggerfall Covenant, an alliance of the Redguards of northern Hammerfell, under King Fahara’jad; the Orcs of the mountainous \
northeast, under King Kurog of Orsinium; with the Breton King Emeric of High Rock presiding from his palace in Wayrest. At its best, it is a noble \
alliance of honorable and chivalrous peoples, representing all the best aspects of the First and Second Empires. And from this solid foundation, \
perhaps a third, even mightier Empire shall arise, providing all the peoples of Tamriel the benefits of mutual respect, vigorous trade, and reverence \
for the Divines.\n\
Default races: Breton, Redguard, Orc"
eso_desc["breton"] = "*Breton racial passives have a strong focus on magicka. Increased max magicka, \
increased spell resistance and magicka ability cost reduction makes them a good magicka based race often used on magicka damage dealers and healers.*"
eso_alliance["breton"] = "Daggerfall Coveant"
eso_passive["breton"] = "**Opportunist** – Increases your Alliance Points gained by 1%.\n\
**Gift of Magnus:** Increases your Max Magicka by 2000.\n\
**Spell Attunement:** Gain 2310 Spell Resistance and 100 Magicka Recovery. The Spell Resistance granted by this effect is doubled if you are afflicted \
with Burning, Chilled, or Concussed.\n\
**Magicka Mastery:** Reduces the Magicka cost of your abilities by 7%."
eso_raceimg["breton"] = "https://i1.wp.com/alcasthq.com/wp-content/uploads/2018/09/Breton.jpg"
eso_desc["redguard"] = "*Redguards are the masters of sustain. Their cost reduction passive on all weapon abilities and their Adrenaline Rush passive \
increase your sustain more than any other race. It can also be wise to use a more weapon abilities focused setup as a Redguard to benefit from the cost \
reduction even more. Also do not forget, the cost reduction also affects your weapon ultimates!*"
eso_alliance["redguard"] = "Daggerfall Coveant"
eso_passive["redguard"] = "**Wayfarer** – Increases the duration of eaten food by 15 minutes.\n\
**Martial Training:** Reduces the cost of your Weapon abilities by 8%. Reduces the effectiveness of Snares applied to you by 15%.\n\
**Conditioning:** Increases your Max Stamina by 2000.\n\
**Adrenaline Rush:** When you deal Direct Damage, you restore 950 Stamina. This effect can occur once every 5 seconds."
eso_raceimg["redguard"] = "https://i2.wp.com/alcasthq.com/wp-content/uploads/2018/09/Redguard.jpg"
eso_desc["orc"] = "*Orcs are one of the strongest stamina race both for pve and pvp. 2000 Max Stamina and 256 Weapon Damage both scale up even \
further with modifiers and on top of that they also get a 1000 Health boost, which means they can run Gold sustain Food and still have a decent \
amount of health! Other than that they also benefit from faster running speeds which makes them very fierce in pvp.*"
eso_alliance["orc"] = "Daggerfall Coveant"
eso_passive["orc"] = "**Craftsman** – Increases your crafting Inspiration gained by 10%.\n\
**Brawny:** Increases your Max Stamina by 2000.\n\
**Unflinching:** Grants 1000 Max Health and heals you for up to 600 when you deal damage with a weapon, with a 4 second cooldown.\n\
**Swift Warrior:** Increases your Weapon Damage by 258. Reduces the cost of your Sprint ability by 12% and increases your Movement Speed while Sprinting by 10%."
eso_raceimg["orc"] = "https://i2.wp.com/alcasthq.com/wp-content/uploads/2018/09/Orc.jpg"
"""
Aldmeri Dominion (High Elf, Woodelf, Khajiit)
"""
eso_allianceimg["aldmeri"] = "http://esoacademy.com/wp-content/uploads/2014/12/AD.png"
eso_allianceinfo["aldmeri"] = "Aldmeri Dominion is a Faction in Elder Scrolls Online. When word reached the High Elves of Alinor that the Imperial City had \
fallen under the control of the human supporters of Molag Bal, the Aldmeri Dominion was formed. The High Elves reached out to the neighboring races of \
Wood Elves and Khajiit with a plea that their combined forces might prevent the younger races of Tamriel from bringing disaster to the world, as they \
had so many times in the past. The High Elves were the original settlers of Tamriel and created the common tongue used throughout the continent today. \
They are also naturally proficient with magic. The Wood Elves inhabit the thick, near-impenetrable forests of Valenwood. They are supreme hunters, \
guides, and masters in sneaking and thievery. They are also the most gifted archers in all of Tamriel. The Khajiit, a proud feline race, are fearsome \
warriors, proficient with bladed weapons. They stand proudly at the forefront of every battle. The power and determination of the Aldmeri Dominion \
should not be underestimated.\n\
Default races: Altmer, Bosmer, Khajiit"
eso_desc["altmer"] = "*Altmers (High Elf), are one of the strongest magicka based races. 2000 Max Magicka and 258 Spell Damage also scale further with modifiers. \
Most people do run Gold sustain Food with this race to help with sustain. On top of that it reduces damage taken by 5% while you are using an ability \
with a cast or channel time.*"
eso_alliance["altmer"] = "Aldmeri Dominion"
eso_passive["altmer"] = "**Highborn** – Increases your experience gained by 1%. Increases experience gain with the Destruction Staff Skill line by 15%.\n\
**Spell Recharge:** Restore 645 Magicka or Stamina, based on whichever is lower, after activating a Class Ability. This effect can occur once every 6 seconds. Reduces damage taken by 5% while you are using an ability with a cast or channel time.\n\
**Syrabane’s Boon:** Increases your Max Magicka by 2000.\n\
**Elemental Talent:** Increases your Spell Damage by 258."
eso_raceimg["altmer"] = "https://i1.wp.com/alcasthq.com/wp-content/uploads/2018/09/High-Elf.jpg"
eso_desc["bosmer"] = "*Bosmer (Woodelf) racial passives have a strong focus on stealth based gameplay style. 2000 Max Stamina and 258 Stamina Recovery that can \
be further increased with modifiers. They are also very good at detecting enemies thanks to the increased detection radius. On top of that they also \
gain faster movement speed and increased penetration after a dodge roll, which makes them especially dangerous on stamina Nightblades.*"
eso_alliance["bosmer"] = "Aldmeri Dominion"
eso_passive["bosmer"] = "**Acrobat** – Decreases your fall damage taken by 10%. Increases experience gain with the Bow Skill ine by 15%.\n\
**Y’ffre’s Endurance:** Increases your Stamina Recovery by 258.\n\
**Resist Affliction:** Increases your Max Stamina by 2000 and your Poison Resistance by 2310. You are immune to the poisoned and status effect.\n\
**Hunter’s Eye:** Increases your Stealth detection radius by 3m. After you use Roll Dodge you gain 10% Movement Speed and 1500 Physical and Spell Penetration for 6 seconds."
eso_raceimg["bosmer"] = "https://i0.wp.com/alcasthq.com/wp-content/uploads/2018/09/woodelf.jpg"
eso_desc["khajiit"] = "*Khajiit racial passives are both good for magicka and stamina based setups. Both stamina and magicka benefits from the extra \
Critical Damage buff. On top of that they also get 825 Max Health, Magicka and Stamina. Which is not a lot but again, that way you can run \
Gold sustian Food and get pretty good sustain without having too low health or resources. Khajiit are also the prime race for gankers, as the \
Critical Damage modifier really pushes up the critical hits on enemies. They are also harder to detect than other races due to the detection radius \
reduction by 3m.*"
eso_alliance["khajiit"] = "Aldmeri Dominion"
eso_passive["khajiit"] = "**Cutpurse** – Increases your chance to so successfully pickpocket by 5%. Increases the experience gain with the Medium Armor Skill line by 15%.\n\
**Robustness:** Increases your Health Recovery by 100 and your Stamina and Magicka recovery by 85.\n\
**Lunar Blessings:** Increases your Max Health, Magicka, and Stamina by 825.\n\
**Feline Ambush:** Increases your Critical Damage and Critical Healing by 10%. Reduces your detection radius in Stealth by 3m."
eso_raceimg["khajiit"] = "https://i1.wp.com/alcasthq.com/wp-content/uploads/2018/09/Khajiit.jpg"
"""
Ebonheart Pact (Nord, Dark Elf, Argonian)
"""
eso_allianceimg["ebonheart"] = "http://esoacademy.com/wp-content/uploads/2014/12/EP.png"
eso_allianceinfo["ebonheart"] ="Ebonheart Pact is a Faction in Elder Scrolls Online. Jorunn, of Eastern Skyrim, is acting High King of the Great Moot, \
but he does not rule absolutely. His decisions must be ratified by all three races in a unique form of governance called The Great Moot. He is \
down-to-earth, humorous, and has an iron will to succeed.\n\
Default races: Nord, Dunmer, Argonian"
eso_desc["nord"] = "*Nord racial passives have a strong focus on tanking based passives. Increased Max Stamina and Health, extra Physical and \
Spell Resistance and also more Cold Resistance. On top of that they also get one of the most important passives, extra Ultimate regeneration. \
Ultimate regeneration is always important, be it in PVP or PVE.*"
eso_alliance["nord"] = "Ebonheart Pact"
eso_passive["nord"] = "**Reveler** – Increases experience gain with the Two-Handed Skill line by 15%. Increases the duration of any consumed drink by 15 minutes.\n\
**Stalwart:** Increases your Max Stamina by 1500. When you take damage, you gain 5 Ultimate. This effect can occur once every 10 seconds.\n\
**Resist Frost:** Increases your Max Health by 1000 and your Cold Resistance by 2310. You are immune to the chilled status effect.\n\
**Rugged:** Increases your Physical and Spell Resistance by 3960."
eso_raceimg["nord"] = "https://i0.wp.com/alcasthq.com/wp-content/uploads/2018/09/nord.jpg"
eso_desc["dunmer"] = "*Dunmer racial passives let you play both Stamina or Magicka based setups. They are not really best at playing stamina or magicka, \
but again you can easily swap between each of those without having to race change. If you want to play a hybrid setup, then Dark Elves are a very good \
choice because of the double stats they get. They also get flame resistance, which can be helpful if you are a Vampire.*"
eso_alliance["dunmer"] = "Ebonheart Pact"
eso_passive["dunmer"] = "**Ashlander** – Increases the experience gain with the Dual Wield Skill line by 15%. Reduces your damage taken by environmental lava by 50%.\n\
**Dynamic:** Increases your Max Stamina and Magicka by 1875.\n\
**Resist Flame:** Increases your Flame Resistance by 2310. You are immune to the burning status effect.\n\
**Ruination:** Increases your Weapon and Spell Damage by 258."
eso_raceimg["dunmer"] = "https://i1.wp.com/alcasthq.com/wp-content/uploads/2018/09/Dark-Elf.jpg"
eso_desc["argonian"] = "*Argonian racial passives are focused on healing and tanking. Increased resource return when you drink a potion, increased max \
health, increased disease resistance and increased healing done. Argonians are often used on tank setups due to their passives. The Resourceful \
passive also makes them one of the best races in order to improve sustain tremendously.*"
eso_alliance["argonian"] = "Ebonheart Pact"
eso_passive["argonian"] = "**Amphibian** – Increases your experience gain with Restoration Staff skill line by 15%. Increases swimming speed by 50%.\n\
**Resourceful:** Increases your Max Magicka by 1000. Restore 4000 Health, Magicka, and Stamina when you drink a potion.\n\
**Argonian Resistance:** Increases your Max Health by 1000 and your Disease Resistance by 2310. You are immune to the diseased status effect.\n\
**Life Mender:** Increases your Healing Done by 6%."
eso_raceimg["argonian"] = "https://i0.wp.com/alcasthq.com/wp-content/uploads/2018/09/Argonian.jpg"
"""
IMPERIAL
"""
eso_desc["imperial"] = "*Imperial racial passives are focused on stamina and health. Increased Max Health and Max Stamina gives them a big extra piece of \
resources compared to other races. Having that much Health makes it possible to run Gold sustain Food, which will make resource management easier. \
They also get 3% cost reduction, which applies to everything, including Ultimates.*"
eso_alliance["imperial"] = "Any alliance"
eso_passive["imperial"] = "**Diplomat** – Increasees experience gain with One Handed and Shield Line by 15%. Increases your gold gained by 1%.\n\
**Tough:** Increases your Max Health by 2000.\n\
**Imperial Mettle:** Increases your Max Stamina by 2000.\n\
**Red Diamond:** When you deal Direct Damage, you restore 333 Health, Magicka, and Stamina. This effect has a 5 second cooldown. Grants 3% cost reduction to all abilities."
eso_raceimg["imperial"] = "https://i0.wp.com/alcasthq.com/wp-content/uploads/2018/09/imperial.jpg" |
def for_g():
for row in range(6):
for col in range(3):
if row-col==2 or col-row==1 or row+col==4 or col==2 and row>0 or row==5 and col==1 or row==1 and col==0:
print("*",end=" ")
else:
print(" ",end=" ")
print()
def while_g():
row=0
while row<6:
col=0
while col<3:
if row-col==2 or col-row==1 or row+col==4 or col==2 and row>0 or row==5 and col==1 or row==1 and col==0:
print("*",end=" ")
else:
print(" ",end=" ")
col+=1
row+=1
print()
|
ERR_SVR_NOT_FOUND = 1
ERR_CLSTR_NOT_FOUND = 2
ERR_IMG_NOT_FOUND = 3
ERR_SVR_EXISTS = 4
ERR_CLSTR_EXISTS = 5
ERR_IMG_EXISTS = 6
ERR_IMG_TYPE_INVALID = 7
ERR_OPR_ERROR = 8
ERR_GENERAL_ERROR = 9
ERR_MATCH_KEY_NOT_PRESENT = 10
ERR_MATCH_VALUE_NOT_PRESENT = 11
ERR_INVALID_MATCH_KEY = 12
|
def swap_case(s):
# sWAP cASE in Python - HackerRank Solution START
Output = ''
for char in s:
if(char.isupper()==True):
Output += (char.lower())
elif(char.islower()==True):
Output += (char.upper())
else:
Output += char
return Output |
a=10
b=1.5
c= 'Arpan'
print (c,"is of type",type(c) )
|
nome = input('Qual é seu nome? ')
print('Prazer em te conhecer {}!'.format(nome))
#print('Prazer em te conhecer {:20}!'.format(nome)) exemplo terá 20 espaços vazios
#print('Prazer em te conhecer {:>20}!'.format(nome))exemplo será alinhado à direita
#print('Prazer em te conhecer {:<20}!'.format(nome)) exemplo será alinhado à esquerda
#print('Prazer em te comhecer {:^20}!'.format(nome)) exemplo será centralizado
#print('Prazer em te conhecer {:=^20}!'.format(nome) exemplo será centralizado com sinais de iguais dos lados) |
# Given n non-negative integers representing an elevation map where the width of each bar is 1,
# compute how much water it is able to trap after raining.
# The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1].
# In this case, 6 units of rain water (blue section) are being trapped.
# Thanks Marcos for contributing this image!
# Example:
# Input: [0,1,0,2,1,0,1,3,2,1,2,1]
# Output: 6
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
# M1. 三次线性扫描 O(n)
# 观察整个图形,想办法分解计算水的面积。
# 注意到,每个矩形条上方所能接受的水的高度,是由它左边最高的矩形,和右边最高的矩形决定的。
# 具体地,假设第 i 个矩形条的高度为 height[i],
# 且矩形条左边最高的矩形条的高度为 left_max[i],右边最高的矩形条高度为 right_max[i],
# 则该矩形条上方能接受水的高度为 min(left_max[i], right_max[i]) - height[i]。
# 需要分别从左向右扫描求 left_max,从右向左求 right_max,最后统计答案即可。
# if not height:
# return 0
# left_max = [0 for _ in range(len(height))]
# left_max[0] = height[0]
# for i in range(1, len(height)):
# left_max[i] = max(height[i], left_max[i-1])
# right_max = [0 for _ in range(len(height))]
# right_max[-1] = height[-1]
# for j in range(len(height)-2, -1, -1):
# right_max[j] = max(height[j], right_max[j+1])
# result = 0
# for i in range(1, len(height)-1):
# result += min(left_max[i], right_max[i]) - height[i]
# return result
# M2. 双指针 O(n)
# https://www.bilibili.com/video/av18241289/
left_index = 0
right_index = len(height) - 1
left_max, right_max = 0, 0
result = 0
while left_index < right_index:
if height[left_index] < height[right_index]:
if height[left_index] >= left_max:
left_max = height[left_index]
else:
result += left_max - height[left_index]
else:
if height[right_index] >= right_max:
right_max = height[right_index]
else:
result += right_max - height[right_index]
return result
|
KNOWN_BINARIES = [
"*.avi", # video
"*.bin", # binary
"*.bmp", # image
"*.docx", # ms-word
"*.eot", # font
"*.exe", # binary
"*.gif", # image
"*.gz", # compressed
"*.heic", # image
"*.heif", # image
"*.ico", # image
"*.jpeg", # image
"*.jpg", # image
"*.m1v", # video
"*.m2a", # audio
"*.mov", # video
"*.mp2", # audio
"*.mp3", # audio
"*.mp4", # video
"*.mpa", # video
"*.mpe", # video
"*.mpeg", # video
"*.mpg", # video
"*.opus", # audio
"*.otf", # font
"*.pdf", # pdf
"*.png", # image
"*.pptx", # ms-powerpoint
"*.qt", # video
"*.rar", # compressed
"*.tar", # compressed
"*.tif", # image
"*.tiff", # image
"*.ttf", # font
"*.wasm", # wasm
"*.wav", # audio
"*.webm", # video
"*.wma", # video
"*.wmv", # video
"*.woff", # font
"*.woff2", # font
"*.xlsx", # ms-excel
"*.zip", # compressed
]
|
ecc_fpga_constants_v128 = [
[
# Parameter name
"p192",
# base word size
16,
# extended word size
128,
# number of bits added
9,
# number of words
2,
# prime
6277101735386680763835789423207666416083908700390324961279,
# prime size in bits
192,
# prime+1
6277101735386680763835789423207666416083908700390324961280,
# prime' = -1/prime mod r
340282366920938463444927863358058659841,
# prime plus one number of zeroes
0,
# 2*prime
12554203470773361527671578846415332832167817400780649922558,
# r mod prime
340282366920938463481821351505477763072,
# r^2 mod prime
680564733841876926982089447084665077762,
# value 1
1,
# ECC curve order
6277101735386680763835789423176059013767194773182842284081,
# ECC curve order bit length
192,
# ECC curve constant a in Montgomery domain (*r mod prime)
6277101735386680762814942322444851025638444645873891672063,
# ECC curve constant a^2 in Montgomery domain (*r mod prime)
3062541302288446171336392163549299867648,
# ECC curve constant 3*b in Montgomery domain (*r mod prime)
2146011979814483024655457172515544228634458728892725334932,
# ECC curve constant a original
6277101735386680763835789423207666416083908700390324961276,
# ECC curve constant a^2 original
9,
# ECC curve constant 3*b original
1088364902640150689385092322384688938223415474093248752916,
# ECC curve generator point x original
602046282375688656758213480587526111916698976636884684818,
# ECC curve generator point y original
174050332293622031404857552280219410364023488927386650641,
# ECC curve generator point z original
1,
# ECC stack starting address
1792,
],
[
# Parameter name
"p224",
# base word size
16,
# extended word size
128,
# number of bits added
9,
# number of words
2,
# prime
26959946667150639794667015087019630673557916260026308143510066298881,
# prime size in bits
224,
# prime+1
26959946667150639794667015087019630673557916260026308143510066298882,
# prime' = -1/prime mod r
26959946660873538059280334323183841250350249843923952699046031785983,
# prime plus one number of zeroes
0,
# 2*prime
53919893334301279589334030174039261347115832520052616287020132597762,
# r mod prime
340282366920938463463374607427473244160,
# r^2 mod prime
26959946667150639791744011812698107204071485058075563455699384008705,
# value 1
1,
# ECC curve order
26959946667150639794667015087019625940457807714424391721682722368061,
# ECC curve order bit length
224,
# ECC curve constant a in Montgomery domain (*r mod prime)
26959946667150639794667015085998783572795100869636184321227646566401,
# ECC curve constant a^2 in Montgomery domain (*r mod prime)
3062541302288446171170371466847259197440,
# ECC curve constant 3*b in Montgomery domain (*r mod prime)
13401218465836556856847955134146467949031625748186257869499969637734,
# ECC curve constant a original
26959946667150639794667015087019630673557916260026308143510066298878,
# ECC curve constant a^2 original
9,
# ECC curve constant 3*b original
2954965522398544411891975459442517899398210385985346940341571419930,
# ECC curve generator point x original
19277929113566293071110308034699488026831934219452440156649784352033,
# ECC curve generator point y original
19926808758034470970197974370888749184205991990603949537637343198772,
# ECC curve generator point z original
1,
# ECC stack starting address
1792,
],
[
# Parameter name
"p256",
# base word size
16,
# extended word size
128,
# number of bits added
9,
# number of words
3,
# prime
115792089210356248762697446949407573530086143415290314195533631308867097853951,
# prime size in bits
256,
# prime+1
115792089210356248762697446949407573530086143415290314195533631308867097853952,
# prime' = -1/prime mod r
18347988923648598022536716706971804129709918677350277014173567881887264878223328924289981802626012577529857,
# prime plus one number of zeroes
0,
# 2*prime
231584178420712497525394893898815147060172286830580628391067262617734195707902,
# r mod prime
115792089183396302095546807154740558443747077475653503024948336717809816961022,
# r^2 mod prime
647038720017892456816164052675271495997532319237579337257304618696714,
# value 1
1,
# ECC curve order
115792089210356248762697446949407573529996955224135760342422259061068512044369,
# ECC curve order bit length
256,
# ECC curve constant a in Montgomery domain (*r mod prime)
80879840001451919384001045259017197818910433511755883773171842678787,
# ECC curve constant a^2 in Montgomery domain (*r mod prime)
115792088967716728758341688797404437753034549958559013660265979989351569817590,
# ECC curve constant 3*b in Montgomery domain (*r mod prime)
33495354891368907141352085619905772971337155559618643861777243941875987635246,
# ECC curve constant a original
115792089210356248762697446949407573530086143415290314195533631308867097853948,
# ECC curve constant a^2 original
9,
# ECC curve constant 3*b original
7383001965100177625280942390734231697257179632690862468972137633251304349922,
# ECC curve generator point x original
48439561293906451759052585252797914202762949526041747995844080717082404635286,
# ECC curve generator point y original
36134250956749795798585127919587881956611106672985015071877198253568414405109,
# ECC curve generator point z original
1,
# ECC stack starting address
1792,
],
[
# Parameter name
"p384",
# base word size
16,
# extended word size
128,
# number of bits added
9,
# number of words
4,
# prime
39402006196394479212279040100143613805079739270465446667948293404245721771496870329047266088258938001861606973112319,
# prime size in bits
384,
# prime+1
39402006196394479212279040100143613805079739270465446667948293404245721771496870329047266088258938001861606973112320,
# prime' = -1/prime mod r
13407807648985227524617045814712496250916495602455859132428975829761605269743128573023706335482896061566913845096358773683926276119763782985192138296262657,
# prime plus one number of zeroes
0,
# 2*prime
78804012392788958424558080200287227610159478540930893335896586808491443542993740658094532176517876003723213946224638,
# r mod prime
115792089264276142090721624801893421303298994787994962092745248076792575557632,
# r^2 mod prime
18347988930056559127812830772223728126786819762522737026661065083431152758333894840256060847379628934823936,
# value 1
1,
# ECC curve order
39402006196394479212279040100143613805079739270465446667946905279627659399113263569398956308152294913554433653942643,
# ECC curve order bit length
384,
# ECC curve constant a in Montgomery domain (*r mod prime)
39402006196394479212279040100143613804732363002672618241676128529840041507586973344683281201980702257631229246439423,
# ECC curve constant a^2 in Montgomery domain (*r mod prime)
1042128803378485278816494623217040791729690953091954658834707232691133180018688,
# ECC curve constant 3*b in Montgomery domain (*r mod prime)
26111218080071188457686646591327611440845506966732540570282325137754995868870791235070305575251358638402738321777086,
# ECC curve constant a original
39402006196394479212279040100143613805079739270465446667948293404245721771496870329047266088258938001861606973112316,
# ECC curve constant a^2 original
9,
# ECC curve constant 3*b original
3936568287090159208988955320879916669011239028153812228389535097474624180935841937314250118133359319573105337467087,
# ECC curve generator point x original
26247035095799689268623156744566981891852923491109213387815615900925518854738050089022388053975719786650872476732087,
# ECC curve generator point y original
8325710961489029985546751289520108179287853048861315594709205902480503199884419224438643760392947333078086511627871,
# ECC curve generator point z original
1,
# ECC stack starting address
1792,
],
[
# Parameter name
"p521",
# base word size
16,
# extended word size
128,
# number of bits added
9,
# number of words
5,
# prime
6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151,
# prime size in bits
521,
# prime+1
6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057152,
# prime' = -1/prime mod r
6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057153,
# prime plus one number of zeroes
3,
# 2*prime
13729595320261219429963801598162786434538870600286610818788926918371086366795312104245119281322909109954592622782961716074243975999433287625148056582230114302,
# r mod prime
664613997892457936451903530140172288,
# r^2 mod prime
441711766194596082395824375185729628956870974218904739530401550323154944,
# value 1
1,
# ECC curve order
6864797660130609714981900799081393217269435300143305409394463459185543183397655394245057746333217197532963996371363321113864768612440380340372808892707005449,
# ECC curve order bit length
521,
# ECC curve constant a in Montgomery domain (*r mod prime)
6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858035128146006039270003218317700694540287,
# ECC curve constant a^2 in Montgomery domain (*r mod prime)
5981525981032121428067131771261550592,
# ECC curve constant 3*b in Montgomery domain (*r mod prime)
6454495390007915947061041987725961162904274121557891147018847125712493623674470779573474404800029704056764955388514936956769162135843165244571821404023458019,
# ECC curve constant a original
6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057148,
# ECC curve constant a^2 original
9,
# ECC curve constant 3*b original
3281547114221202823533337172300416709808622796855051246983759183487859348452205048041126212721278869745776396890118939928315357594773038736426982465436957952,
# ECC curve generator point x original
2661740802050217063228768716723360960729859168756973147706671368418802944996427808491545080627771902352094241225065558662157113545570916814161637315895999846,
# ECC curve generator point y original
3757180025770020463545507224491183603594455134769762486694567779615544477440556316691234405012945539562144444537289428522585666729196580810124344277578376784,
# ECC curve generator point z original
1,
# ECC stack starting address
1792,
],
]
|
OpenVZ_EXIT_STATUS = {
'vzctl': {0: 'Command executed successfully',
1: 'Failed to set a UBC parameter',
2: 'Failed to set a fair scheduler parameter',
3: 'Generic system error',
5: 'The running kernel is not an OpenVZ kernel (or some OpenVZ modules are not loaded)',
6: 'Not enough system resources',
7: 'ENV_CREATE ioctl failed',
8: 'Command executed by vzctl exec returned non-zero exit code',
9: 'Container is locked by another vzctl invocation',
10: 'Global OpenVZ configuration file vz.conf(5) not found',
11: 'A vzctl helper script file not found',
12: 'Permission denied',
13: 'Capability setting failed',
14: 'Container configuration file ctid.conf(5) not found',
15: 'Timeout on vzctl exec',
16: 'Error during vzctl chkpnt',
17: 'Error during vzctl restore',
18: 'Error from setluid() syscall',
20: 'Invalid command line parameter',
21: 'Invalid value for command line parameter',
22: 'Container root directory (VE_ROOT) not set',
23: 'Container private directory (VE_PRIVATE) not set',
24: 'Container template directory (TEMPLATE) not set',
28: 'Not all required UBC parameters are set, unable to start container',
29: 'OS template is not specified, unable to create container',
31: 'Container not running',
32: 'Container already running',
33: 'Unable to stop container',
34: 'Unable to add IP address to container',
40: 'Container not mounted',
41: 'Container already mounted',
43: 'Container private area not found',
44: 'Container private area already exists',
46: 'Not enough disk space',
47: 'Bad/broken container (/sbin/init or /bin/sh not found)',
48: 'Unable to create a new container private area',
49: 'Unable to create a new container root area',
50: 'Unable to mount container',
51: 'Unable to unmount container',
52: 'Unable to delete a container',
53: 'Container private area not exist',
60: 'vzquota on failed',
61: 'vzquota init failed',
62: 'vzquota setlimit failed',
63: 'Parameter DISKSPACE not set (or set too high)',
64: 'Parameter DISKINODES not set',
65: 'Error setting in-container disk quotas',
66: 'vzquota off failed',
67: 'ugid quota not initialized',
71: 'Incorrect IP address format',
74: 'Error changing password',
78: 'IP address already in use',
79: 'Container action script returned an error',
82: 'Config file copying error',
86: 'Error setting devices (--devices or --devnodes)',
89: 'IP address not available',
91: 'OS template not found',
99: 'Ploop is not supported by either the running kernel or vzctl.',
100: 'Unable to find container IP address',
104: 'VE_NETDEV ioctl error',
105: 'Container start disabled',
106: 'Unable to set iptables on a running container',
107: 'Distribution-specific configuration file not found',
109: 'Unable to apply a config',
129: 'Unable to set meminfo parameter',
130: 'Error setting veth interface',
131: 'Error setting container name',
133: 'Waiting for container start failed',
139: 'Error saving container configuration file',
148: 'Error setting container IO parameters (ioprio)',
150: 'Ploop image file not found',
151: 'Error creating ploop image',
152: 'Error mounting ploop image',
153: 'Error unmounting ploop image',
154: 'Error resizing ploop image',
155: 'Error converting container to ploop layout',
156: 'Error creating ploop snapshot',
157: 'Error merging ploop snapshot',
158: 'Error deleting ploop snapshot',
159: 'Error switching ploop snapshot',
161: 'Error compacting ploop image'},
'vzquoata': {0: 'Command executed successfully',
1: 'System error',
2: 'Usage error',
3: 'Virtuozzo syscall error',
4: 'Quota file error',
5: 'Quota is already running',
6: 'Quota is not running',
7: 'Can not get lock on this quota id',
8: 'Directory tree crosses mount points',
9: '(Info) Quota is running but user/group quota is inactive',
10: '(Info) Quota is marked as dirty in file',
11: 'Quota file does not exist',
12: 'Internal error',
13: "Can't obtain mount point"},
'ndsend': {0: 'Command executed successfully',
1: 'Usage error',
2: 'System error'},
'arpsend': {0: 'Command executed successfully',
1: 'Usage error',
2: 'System error',
3: 'ARP reply was received'},
'vzmigrate': {0: 'Command executed successfully',
1: 'Bad command line options.',
2: 'Container is stopped.',
4: "Can't connect to destination (source) HN.",
6: 'Container private area copying/moving failed.',
7: "Can't start or restore destination CT.",
8: "Can't stop or checkpoint source CT.",
9: 'Container already exists on destination HN.',
10: 'Container does not exists on source HN.',
12: 'You attempt to migrate CT which IP address(es) are already in use on the destination node.',
13: 'Operation with CT quota failed.',
14: 'OpenVZ is not running, or some required kernel modules are not loaded.',
15: 'Unable to set CT name on destination node.',
16: 'Ploop is not supported by destination node.'},
'vzcfgvalidate': {0: 'Command executed successfully',
1: 'On program execution error.',
2: 'Validation failed.'}
}
|
# -*- coding: utf-8 -*-
""" Parameters """
"""
Annotated transcript filtering
Setting TSL threshold to 1 excludes some Uniprot canonical transcripts, e.g.,
DDP8_HUMAN with the first 18 amino acids.
"""
tsl_threshold = 2 # the transcript levels below which (lower is better) to consider
"""
Stop codon forced translation
This threshold may be set to allow some stop codon transcripts to be translated to Tier 4
"""
ptc_threshold = 0.33 # the PTC slice should be at least this portion of the long slice to be included
"""
Canonical transcript recognition
Canonical can be chosen from the GTF (longest protein coding sequence) alone
which speeds up the analysis or through an API call to Uniprot.
This has the advantage of allowing splice graphs to determine which junctions
map to which transcripts.
However, note that Uniprot has manual annotation on what is the canonical sequence
through prevalence and homology to other species that are not apparent in the GTF file without
calling to other resources like APPRIS (e.g. see DET1_HUMAN).
Because of the prominence of Uniprot in proteomics work
we have chosen to use Uniprot for now.
"""
use_gtf_only = False # use GTF but not Uniprot to get canonical transcripts
uniprot_max_retries = 10 # max number of retries if retrieving sequences from Uniprot
aa_stitch_length = 10 # amino acid joint to stitch to canonical when using aa for joining
|
"""
Provide help messages for command line interface's receipt commands.
"""
RECEIPT_TRANSACTION_IDENTIFIERS_ARGUMENT_HELP_MESSAGE = 'Identifiers to get a list of transaction\'s receipts by.'
|
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/4/16 13:02
# @Author : Yunhao Cao
# @File : exceptions.py
__author__ = 'Yunhao Cao'
__all__ = [
'CrawlerBaseException',
'RuleManyMatchedError',
]
class CrawlerBaseException(Exception):
pass
class RuleManyMatchedError(CrawlerBaseException):
pass
|
"""
A. Football
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals.
Unfortunately he didn't find the overall score of the match; however, he got hold
of a profound description of the match's process. On the whole there are n lines
in that description each of which described one goal. Every goal was marked with
the name of the team that had scored it. Help Vasya, learn the name of the team that won
the finals. It is guaranteed that the match did not end in a tie.
Input
The first line contains an integer n (1 ≤ n ≤ 100) — the number of lines in the description.
Then follow n lines — for each goal the names of the teams that scored it.
The names are non-empty lines consisting of uppercase Latin letters
whose lengths do not exceed 10 symbols. It is guaranteed that the match did not end in
a tie and the description contains no more than two different teams.
Output
Print the name of the winning team. We remind you that in football the team that scores
more goals is considered the winner.
"""
def get_winner(goals):
score = {}
for goal in goals:
if goal not in score:
score[goal] = 1
else:
score[goal] += 1
teams = [*score.keys()]
if len(teams) == 1:
print(teams[0])
else:
print(teams[0] if score[teams[0]] > score[teams[1]] else teams[1])
if __name__ == '__main__':
num_goals = int(input())
goals_ = []
for _ in range(num_goals):
goals_.append(input())
get_winner(goals_)
|
"""
Permutation where the order the way the elements are arranged matters
Using a back tracking we print all the permutations
E.g.
abc
There are total 3! permutations
abc
acb
acb
bac
bca
cab
cba
"""
def calculate_permutations(element_list, result_list, pos, r=None):
n = len(element_list)
if pos == n:
if r:
result_list.append(element_list[:r][:])
else:
result_list.append(element_list[:])
return
index = pos
while pos < n:
element_list[pos], element_list[index] = element_list[index], element_list[pos]
calculate_permutations(element_list, result_list, index+1, r)
# back tracking the element in the list
element_list[pos], element_list[index] = element_list[index], element_list[pos]
pos += 1
def permutations(element_list, r=None):
result_list = []
calculate_permutations(list(element_list), result_list, 0)
return result_list
def main():
for da in permutations("abc", 2):
print(da)
if __name__ == '__main__':
main() |
class Cat:
name = ''
age = 0
color = ''
def __init__(self, name, age=0, color ='White'):
self.name = name
self.age = age
self.color = color
def meow(self):
print(f'{self.name} meow')
def sleep(self):
print(f' {self.name} zzz')
def hungry(self):
for x in range(5):
self.meow()
def description(self):
print(f'{self.name} is a {self.color} color Cat, who is {self.age} years old')
|
"""
Creating a custom error by extending the TypeError class
"""
class MyCustomError(TypeError):
"""
Raising a custom error by extending the TypeError class
"""
def __init__(self, error_message, error_code):
super().__init__(f'Error code: {error_code}, Error Message: {error_message}')
self.message = error_message
self.code = error_code
raise MyCustomError('This is a custom error', 403)
|
######################################################################
#
# File: b2/sync/file.py
#
# Copyright 2018 Backblaze Inc. All Rights Reserved.
#
# License https://www.backblaze.com/using_b2_code.html
#
######################################################################
class File(object):
"""
Holds information about one file in a folder.
The name is relative to the folder in all cases.
Files that have multiple versions (which only happens
in B2, not in local folders) include information about
all of the versions, most recent first.
"""
def __init__(self, name, versions):
self.name = name
self.versions = versions
def latest_version(self):
return self.versions[0]
def __repr__(self):
return 'File(%s, [%s])' % (self.name, ', '.join(repr(v) for v in self.versions))
class FileVersion(object):
"""
Holds information about one version of a file:
id - The B2 file id, or the local full path name
mod_time - modification time, in milliseconds, to avoid rounding issues
with millisecond times from B2
action - "hide" or "upload" (never "start")
"""
def __init__(self, id_, file_name, mod_time, action, size):
self.id_ = id_
self.name = file_name
self.mod_time = mod_time
self.action = action
self.size = size
def __repr__(self):
return 'FileVersion(%s, %s, %s, %s)' % (
repr(self.id_), repr(self.name), repr(self.mod_time), repr(self.action)
)
|
def ascending_order(arr):
if(len(arr) == 1):
return 0
else:
count = 0
for i in range(0, len(arr)-1):
if(arr[i+1]<arr[i]):
diff = arr[i] - arr[i+1]
arr[i+1]+=diff
count+=diff
return count
if __name__=="__main__":
n = int(input())
arr = [int(i) for i in input().split(" ")][:n]
print(ascending_order(arr))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.