content
stringlengths 7
1.05M
|
|---|
#Oskar Svedlund
#TEINF-20
#2021-09-20
#For i For loop
for i in range(1,10):
for j in range(1,10):
print(i*j, end="\t")
print()
|
#!/usr/bin/env python
'''
Copyright (C) 2019, WAFW00F Developers.
See the LICENSE file for copying permission.
'''
NAME = 'StackPath (StackPath)'
def is_waf(self):
schemes = [
self.matchContent(r"This website is using a security service to protect itself"),
self.matchContent(r'You performed an action that triggered the service and blocked your request')
]
if all(i for i in schemes):
return True
return False
|
"""Advent of Code Day 4 - High-Entropy Passphrases"""
# Open list, read it and split by newline
pass_txt = open('inputs/day_04.txt')
lines = pass_txt.read()
pass_list = lines.split('\n')
def dupe_check(passphrase):
"""Return only if input has no duplicate words in it."""
words = passphrase.split(' ')
unique = set(words)
if words != ['']:
return len(words) == len(unique)
def anagram_check(passphrase):
"""Return only if input has no anagram pairs in it."""
words = passphrase.split(' ')
word_list = []
for word in words:
# Make all words have their letters in alphabetical order
letters = list(word)
ordered = ('').join(sorted(letters))
word_list.append(ordered)
unique = set(word_list)
if words != ['']:
return len(words) == len(unique)
# Answer One
dupeless = 0
for passphrase in pass_list:
if dupe_check(passphrase):
dupeless += 1
print("Number of passwords without duplicates:", dupeless)
# Answer Two
anagramless = 0
for passphrase in pass_list:
if anagram_check(passphrase):
anagramless += 1
print("Number of passwords without anagram pairs:", anagramless)
|
content = '''
<script>
function createimagemodal(path,cap) {
var html = '<div id="modalWindow1" class="modal" data-keyboard="false" data-backdrop="static">\
<span class="close1" onclick=deletemodal("modalWindow1") data-dismiss="modal">×</span>\
<img class="modal-content" id="img01" style="max-height: -webkit-fill-available; width: auto;"></img>\
<div id="caption"></div>\
</div>';
$("#imagemodal").html(html);
$("#modalWindow1").modal();
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
modalImg.src = path;
captionText.innerHTML = cap;
}
</script>
'''
|
a = int(input('Digite o primeiro segmento '))
b = int(input('Digite o segundo segmento: '))
c = int(input('Digite o terceiro segmento '))
if (b - c) < a < (b + c) and (a - c) < b < (a + c) and (a - b) < c < (a + b):
print('Formam um triangulo')
else:
print('Nao formam um triangulo')
|
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class RunNowPhysicalParameters(object):
"""Implementation of the 'RunNowPhysicalParameters' model.
Attributes:
metadata_file_path (string): Specifies metadata file path during
run-now requests for physical file based backups for some specific
host entity. If specified, it will override any default
metadata/directive file path set at the job level for the host.
Also note that if the job default does not specify a
metadata/directive file path for the host, then specifying this
field for that host during run-now request will be rejected.
"""
# Create a mapping from Model property names to API property names
_names = {
"metadata_file_path":'metadataFilePath'
}
def __init__(self,
metadata_file_path=None):
"""Constructor for the RunNowPhysicalParameters class"""
# Initialize members of the class
self.metadata_file_path = metadata_file_path
@classmethod
def from_dictionary(cls,
dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object as
obtained from the deserialization of the server's response. The keys
MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
# Extract variables from the dictionary
metadata_file_path = dictionary.get('metadataFilePath')
# Return an object of this model
return cls(metadata_file_path)
|
SECTION_OFFSET_START = 0x0
SECTION_ADDRESS_START = 0x48
SECTION_SIZE_START = 0x90
BSS_START = 0xD8
BSS_SIZE = 0xDC
TEXT_SECTION_COUNT = 7
DATA_SECTION_COUNT = 11
SECTION_COUNT = TEXT_SECTION_COUNT + DATA_SECTION_COUNT
PATCH_SECTION = 3
ORIGINAL_DOL_END = 0x804DEC00
def word(data, offset):
return sum(data[offset + i] << (24 - i * 8) for i in range(4))
def word_to_bytes(word):
return bytes((word >> (24 - i * 8)) & 0xFF for i in range(4))
def get_dol_end(data):
def get_section_end(index):
address = word(data, SECTION_ADDRESS_START + index * 4)
size = word(data, SECTION_SIZE_START + index * 4)
return address + size
bss_end = word(data, BSS_START) + word(data, BSS_SIZE)
return max(bss_end, *(get_section_end(i) for i in range(SECTION_COUNT)))
def address_to_offset(data, value):
for i in range(0, SECTION_COUNT):
address = word(data, SECTION_ADDRESS_START + i * 4)
size = word(data, SECTION_SIZE_START + i * 4)
if address <= value < address + size:
offset = word(data, SECTION_OFFSET_START + i * 4)
return value - address + offset
def patch_load_imm32(data, address, reg, imm):
lis = 0x3C000000 | (reg << 21) | (imm >> 16)
ori = 0x60000000 | (reg << 21) | (reg << 16) | (imm & 0xFFFF)
offset = address_to_offset(data, address)
data[offset:offset+4] = word_to_bytes(lis)
data[offset+4:offset+8] = word_to_bytes(ori)
def patch_load_imm32_split(data, lis_addr, ori_addr, reg, imm):
lis = 0x3C000000 | (reg << 21) | (imm >> 16)
ori = 0x60000000 | (reg << 21) | (reg << 16) | (imm & 0xFFFF)
lis_offset = address_to_offset(data, lis_addr)
ori_offset = address_to_offset(data, ori_addr)
data[lis_offset:lis_offset+4] = word_to_bytes(lis)
data[ori_offset:ori_offset+4] = word_to_bytes(ori)
def patch_branch(data, address, target):
delta = target - address
if delta < 0:
# Two's complement
delta = ~(-delta) + 1
offset = address_to_offset(data, address)
data[offset:offset+4] = word_to_bytes(0x48000000 | (delta & 0x3FFFFFC))
def patch_stack_and_heap(data):
delta = get_dol_end(data) - ORIGINAL_DOL_END
print(f"DOL virtual size delta: 0x{delta:X} bytes")
patch_load_imm32(data, 0x80343094, 3, 0x804F0C00 + delta)
patch_load_imm32(data, 0x803430CC, 3, 0x804EEC00 + delta)
patch_load_imm32(data, 0x8034AC78, 0, 0x804EEC00 + delta)
patch_load_imm32_split(data, 0x8034AC80, 0x8034AC88, 0, 0x804DEC00 + delta)
patch_load_imm32_split(data, 0x802256D0, 0x802256D8, 3, 0x804DEC00 + delta)
patch_load_imm32_split(data, 0x8022570C, 0x80225714, 4, 0x804EEC00 + delta)
patch_load_imm32_split(data, 0x80225718, 0x80225720, 5, 0x804DEC00 + delta)
# Stack
patch_load_imm32(data, 0x80005340, 1, 0x804EEC00 + delta)
def apply_hooks(data):
hooks_offset = word(data, SECTION_OFFSET_START + PATCH_SECTION * 4)
hooks_address = word(data, SECTION_ADDRESS_START + PATCH_SECTION * 4)
hooks_size = word(data, SECTION_SIZE_START + PATCH_SECTION * 4)
for i in range(hooks_size // 8):
offset = hooks_offset + i * 8
original = word(data, offset)
hook = word(data, offset + 4)
# Replace the patch data with the overwritten instruction + branch back
# to the original
original_offset = address_to_offset(data, original)
data[offset:offset+4] = data[original_offset:original_offset+4]
patch_branch(data, hooks_address + i * 8 + 4, original + 4)
patch_branch(data, original, hook)
print(f"Hook {original:08X} -> {hook:08X}")
def apply_extra_patches(data):
with open("patches") as f:
while True:
line = f.readline()
if not line:
return
if line.find("#") != -1:
line = line[:line.find("#")]
if len(line.split()) == 0:
continue
address, word = [int(x, 16) for x in line.split()]
offset = address_to_offset(data, address)
data[offset:offset+4] = word_to_bytes(word)
print(f"Patch {address:08X} -> {word:08X}")
def main():
with open("bin/sys/main.dol", "rb") as f:
data = bytearray(f.read())
patch_stack_and_heap(data)
apply_hooks(data)
apply_extra_patches(data)
with open("bin/sys/main.dol", "wb") as f:
f.write(data)
if __name__ == "__main__":
main()
|
class MetaSingleton(type):
instance = {}
def __init__(cls, name, bases, attrs, **kwargs):
cls.__copy__ = lambda self: self
cls.__deepcopy__ = lambda self, memo: self
def __call__(cls, *args, **kwargs):
key = cls.__qualname__
if key not in cls.instance:
instance = super().__call__(*args, **kwargs)
cls.instance[key] = instance
else:
instance = cls.instance[key]
instance.__init__(*args, **kwargs)
return instance
class Singleton(metaclass=MetaSingleton):
def __init__(self, *args, **kwargs):
pass
def singleton(name):
cls = type(name, (Singleton,), {})
return cls()
|
"""Ex 015 - Escreva um programa que pergunte a quantidade de Km percorridos por
um carro alugado e a quantidade de dias pelos quais ele foi alugado. Calcule o preço a pagar, sabendo
que o carro custa R$60,00 por dia e R$0,15 por Km rodado."""
print('-' * 15, '>Ex 15<', '-' * 15)
# Criando variaveis e Recebendo dados.
dia_car = int(input('Por quantos dias você alugou o carro: '))
km_rodado = float(input('Quantos KM foram rodados: '))
# Processando dados.
val_dia_car = dia_car * 60
val_km_rodado = km_rodado * 0.15
total_pag = val_dia_car + val_km_rodado
# Imprimindo dados para o usuário.
print('Valor a pagar pelos dias......: R${:.2f}'.format(val_dia_car))
print('Valor a pagar pelos KM rodados: R${:.2f}'.format(val_km_rodado))
print('Valor total a pagar...........: R${:.2f}'.format(total_pag))
|
"""Top-level package for baseline."""
__author__ = """Leon Kozlowski"""
__email__ = "leonkozlowski@gmail.com"
|
#
# This file contains the Python code from Program 15.10 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm15_10.txt
#
class HeapSorter(Sorter):
def __init__(self):
super(HeapSorter, self).__init__()
def percolateDown(self, i, length):
while 2 * i <= length:
j = 2 * i
if j < length and self._array[j + 1] \
> self._array[j]:
j = j + 1
if self._array[i] \
>= self._array[j]:
break
self.swap(i, j)
i = j
# ...
|
#!/usr/bin/python3
# coding=utf-8
# Copyright 2019 getcarrier.io
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Constants
"""
# Legacy
JIRA_FIELD_DO_NOT_USE_VALUE = '!remove'
JIRA_FIELD_USE_DEFAULT_VALUE = '!default'
JIRA_SEVERITIES = {
'Trivial': 4,
'Minor': 3,
'Medium': 2,
'Major': 1,
'Critical': 0,
'Blocker': 0
}
JIRA_ALTERNATIVES = {
'Trivial': ['Low', 'Minor'],
'Minor': ['Low', 'Medium'],
'Medium': ['Major'],
'Major': ['High', 'Critical'],
'Critical': ['Very High', 'Blocker'],
'Blocker': ['Very High', 'Critical']
}
JIRA_OPENED_STATUSES = ['Open', 'In Progress']
JIRA_DESCRIPTION_MAX_SIZE = 61908
# This is jira.text.field.character.limit default value
JIRA_COMMENT_MAX_SIZE = 32767
# Priority/Severity mapping
JIRA_SEVERITY_MAPPING = {
"Critical": "Critical",
"High": "Major",
"Medium": "Medium",
"Low": "Minor",
"Info": "Trivial"
}
|
"""
Draw discontinu form
"""
|
'''
@name -> insertTopStreams
@param (dbConnection) -> db connection object
@param (cursor) -> db cursor object
@param (time) -> a list of 5 integers that means [year, month, day, hour, minute]
@param (topStreams) -> list of 20 dictionary objects
'''
def insertTopStreams(dbConnection, cursor, time, topStreams):
# multidimensional list
# list order: [channel_id, display_name, language, game, created_at, followers, views, viewers, preview_template]
items = []
for stream in topStreams:
item = []
item.append(str(stream['channel']['_id']))
item.append(str(stream['channel']['display_name']))
item.append(str(stream['channel']['language']))
item.append(str(stream['game']))
item.append(str(stream['created_at']))
item.append(str(stream['channel']['followers']))
item.append(str(stream['channel']['views']))
item.append(str(stream['viewers']))
item.append(str(stream['preview']['template']))
items.append(item)
query = 'INSERT INTO top_streams (custom_timestamp, stream_01, stream_02, stream_03, stream_04, stream_05, stream_06, stream_07, stream_08, stream_09, stream_10, stream_11, stream_12, stream_13, stream_14, stream_15, stream_16, stream_17, stream_18, stream_19, stream_20) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'
cursor.execute(
query,
[
time,
items[0], items[1], items[2], items[3], items[4],
items[5], items[6], items[7], items[8], items[9],
items[10], items[11], items[12], items[13], items[14],
items[15], items[16], items[17], items[18], items[19]
]
)
dbConnection.commit()
|
'''
Crie um programa que vai ler varios numeros e colocar em uma lista. Depois disse mostre:
a) Quantos números foram digitados.
b) A lista ordenada em forma decrescente
c) Se o valor 5 foi digitado e se esta ou nao na lista
OBS: Voce digitou {} valores, Os valores em order decrescente são: {}, O valor 5 (não) foi encontrado na lista'''
lista = []
qtd = 0
while True:
num = int(input('Digite um número inteiro qualquer: '))
lista.append(num)
qtd += 1
cont = str(input('Deseja continuar [S]im ou [N]ão ?')).upper()
if cont[:1] == 'N':
break
lista.sort(reverse=True)
print('-='*50)
print(f'Você digitou {qtd} numeros.')
if 5 in lista:
print('O numero 5 foi digitado.')
else:
print('O numero 5 não foi digitado.')
print(lista)
print('-='*50)
print()
|
class BinaryIndexedTree:
def __init__(self, n):
self.sums = [0] * (n + 1)
def update(self, i, delta):
while i < len(self.sums):
self.sums[i] += delta
# add low bit
i += (i & -i)
def prefix_sum(self, i):
ret = 0
while i:
ret += self.sums[i]
i -= (i & -i)
return ret
|
#stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner.
#In stack, a new element is added at one end and an element is removed from that end only.
stack = []
# append() function to push
# element in the stack
stack.append('a')
stack.append('b')
stack.append('c')
stack.append('d')
stack.append('e')
print('Initial stack')
print(stack)
# pop() function to pop element from stack in
# LIFO order
print('\nElements popped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
print('\nStack after elements are popped:')
print(stack)
|
# ------------------------------
# 223. Rectangle Area
#
# Description:
# Find the total area covered by two rectilinear rectangles in a 2D plane.
# Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.
#
# Example:
# Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2
# Output: 45
# Note:
# Assume that the total area is never beyond the maximum possible value of int.
#
# Version: 1.0
# 09/19/18 by Jianfa
# ------------------------------
class Solution(object):
def computeArea(self, A, B, C, D, E, F, G, H):
"""
:type A: int
:type B: int
:type C: int
:type D: int
:type E: int
:type F: int
:type G: int
:type H: int
:rtype: int
"""
left = max(A, E) # left coordinate of overlap area (if exists)
right = max(min(C, G), left) # right coordinate. If no overlap, then right == left (because left >= min(C, G))
top = min(D, H)
bottom = min(max(B, F), top)
return (C - A) * (D - B) + (G - E) * (H - F) - (right - left) * (top - bottom)
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Follow idea from https://leetcode.com/problems/rectangle-area/discuss/62149/Just-another-short-way
|
"""
Goal:
Write a program to calculate the credit card balance after one year
if a person only pays the minimum monthly payment
required by the credit card company each month.
For each month, calculate statements on the monthly payment and remaining balance.
At the end of 12 months, print out the remaining balance.
Be sure to print out no more than two decimal digits of accuracy
Variables
balance - the outstanding balance on the credit card
annualInterestRate - annual interest rate as a decimal
monthlyPaymentRate - minimum monthly payment rate as a decimal
The code you paste into the following box should not specify the values for the variables
balance, annualInterestRate, or monthlyPaymentRate
A summary of the required math is found below:
Monthly interest rate= (Annual interest rate) / 12.0
Minimum monthly payment = (Minimum monthly payment rate) x (Previous balance)
Monthly unpaid balance = (Previous balance) - (Minimum monthly payment)
Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate x Monthly unpaid balance)
# Test case 1
balance = 42
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
# Result Your Code Should Generate Below:
Remaining balance: 31.38
# Test case 2
balance = 484
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
Result Your Code Should Generate Below:
Remaining balance: 361.61
"""
balance = 484
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
i = 1
while i < 13:
min_payment = monthlyPaymentRate * balance
outstanding = balance - min_payment
balance = outstanding * (1. + annualInterestRate / 12.) # outstanding balance + interest due
i += 1
# print(f"Remaining balance: {balance: .2f}")
print("Remaining balance:", round(balance, 2))
|
student = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
a = [1, 2, 6, 7, 13, 15, 11]
b = [3, 4, 6, 8, 12, 13]
c = [6, 7, 8, 9, 14, 15]
t1 = []
t2 = []
t3 = []
t4 = []
for i in range(len(student)):
if student[i] in a and student[i] in b:
t1.append(student[i])
if student[i] in a and student[i] not in b or student[i] in b and student[i] not in a:
t2.append(student[i])
if student[i] not in a and student[i] not in b:
t3.append(student[i])
if student[i] in a and student[i] in c and student[i] not in b:
t4.append(student[i])
print("List of student who play both cricket and badminton :", t1)
print("List of student who play either cricket or badminton but not both:", t2)
print("No. of students who play neither cricket nor badminton :", len(t3))
print("No. of students who play cricket and football but not badminton :", len(t4))
|
async def setupAddSelfrole(plugin, ctx, name, role, roles):
role_id = role.id
name = name.lower()
if role_id in [roles[x] for x in roles] or name in roles:
return await ctx.send(plugin.t(ctx.guild, "already_selfrole", _emote="WARN"))
if role.position >= ctx.guild.me.top_role.position:
return await ctx.send(plugin.t(ctx.guild, "role_too_high", _emote="WARN"))
if role == ctx.guild.default_role:
return await ctx.send(plugin.t(ctx.guild, "default_role_forbidden", _emote="WARN"))
roles[name] = str(role_id)
plugin.db.configs.update(ctx.guild.id, "selfroles", roles)
await ctx.send(plugin.t(ctx.guild, "selfrole_added", _emote="YES", role=role.name, name=name, prefix=plugin.bot.get_guild_prefix(ctx.guild)))
|
code = """/* Disabled External File Drag */
window.addEventListener("dragover",function(e){
if (e.target.type != "file") {
e.preventDefault();
e.dataTransfer.effectAllowed = "none";
e.dataTransfer.dropEffect = "none";
}
},false);
window.addEventListener("dragenter",function(e){
if (e.target.type != "file") {
e.preventDefault();
e.dataTransfer.effectAllowed = "none";
e.dataTransfer.dropEffect = "none";
}
},false);
window.addEventListener("drop",function(e){
if (e.target.type != "file") { // e.target.tagName == "INPUT"
e.preventDefault();
e.dataTransfer.effectAllowed = "none";
e.dataTransfer.dropEffect = "none";
}
},false);
"""
|
'''
LANGUAGE: Python
AUTHOR: Weiyi
GITHUB: https://github.com/weiyi-m
'''
print("Hello World!")
|
"""implements required text elements for the app"""
APP_NAME = "OSCAR"
WELCOME = "Welcome to " + APP_NAME
CREATE_PROJECT = {
'main': "Create ...",
'sub': "New " + APP_NAME + " project"
}
OPEN_PROJECT = {
'main': "Open ...",
'sub': "Existing " + APP_NAME + " project"
}
SECTIONS = {
'over': "Overview",
'energy': "Energy",
'water': "Water",
'food': "Food",
'busi': "Business"
}
|
"""
Useful functions
"""
def singleton(cls):
"""turn a class into a singleton class"""
instances = {}
def get_instance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance
|
hours = 40
pay_rate = 400
no_weeks = 4
monthly_pay = hours * pay_rate *no_weeks
print(monthly_pay)
|
def is_leap(year):
leap = False
# Write your logic here
# thought process
#if year%4==0:
# return True
#elif year%100==0:
# return False
#elif year%400==0:
# return True
# Optimized, Python 3
return ((year%4==0)and(year%100!=0)or(year%400==0))
|
"""Constants for the Ziggo Mediabox Next integration."""
ZIGGO_API = "ziggo_api"
CONF_COUNTRY_CODE = "country_code"
RECORD = "record"
REWIND = "rewind"
FAST_FORWARD = "fast_forward"
|
'''
1. Write a Python program to find three numbers from an array such that the sum of three numbers equal to a given number
Input : [1, 0, -1, 0, -2, 2], 0)
Output : [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
2. Write a Python program to compute and return the square root of a given 'integer'.
Input : 16
Output : 4
Note : The returned value will be an 'integer'
3. Write a Python program to find the single number in a list that doesn't occur twice
Input : [5, 3, 4, 3, 4]
Output : 5
'''
|
def main():
for i in range(10):
print(f"The square of {i} is {square(i)}")
return
def square(n):
return n**2
if __name__ == '__main__':
main()
|
"""
funcio def aplicar(valor1, valor2, operacio)
ef operacio ():
resultat = input( ' Quina operació vols fer?? (multiplicar sumar o restar) \n' )
return resultat
return varo1 operacio valor2
"""
#Definició
def operacionvalores (valor1,valor2,operacion) :
if operacion == "sumar":
resultat = valor1+valor2
elif operacion == "restar":
resultat = valor1-valor2
elif operacion == "multiplicar":
resultat = valor1 * valor2
return resultat
#Execució
if __name__ == "__main__":
resultat = operacionvalores (1,2, "multiplicar")
print(resultat)
|
'''
Created on 11 aug. 2011
.. codeauthor:: wauping <w.auping (at) student (dot) tudelft (dot) nl>
jhkwakkel <j.h.kwakkel (at) tudelft (dot) nl>
To be able to debug the Vensim model, a few steps are needed:
1. The case that gave a bug, needs to be saved in a text file. The entire
case description should be on a single line.
2. Reform and clean your model ( In the Vensim menu: Model, Reform and
Clean). Choose
* Equation Order: Alphabetical by group (not really necessary)
* Equation Format: Terse
3. Save your model as text (File, Save as..., Save as Type: Text Format
Models
4. Run this script
5. If the print in the end is not set([]), but set([array]), the array
gives the values that where not found and changed
5. Run your new model (for example 'new text.mdl')
6. Vensim tells you about your critical mistake
'''
fileSpecifyingError = ""
pathToExistingModel = r"C:\workspace\EMA-workbench\models\salinization\Verzilting_aanpassingen incorrect.mdl"
pathToNewModel = r"C:\workspace\EMA-workbench\models\salinization\Verzilting_aanpassingen correct.mdl"
newModel = open(pathToNewModel, 'w')
# line = open(fileSpecifyingError).read()
line = 'rainfall : 0.154705633188; adaptation time from non irrigated agriculture : 0.915157119079; salt effect multiplier : 1.11965969891; adaptation time to non irrigated agriculture : 0.48434342934; adaptation time to irrigated agriculture : 0.330990830832; water shortage multiplier : 0.984356102036; delay time salt seepage : 6.0; adaptation time : 6.90258192256; births multiplier : 1.14344734715; diffusion lookup : [(0, 8.0), (10, 8.0), (20, 8.0), (30, 8.0), (40, 7.9999999999999005), (50, 4.0), (60, 9.982194802803703e-14), (70, 1.2455526635140464e-27), (80, 1.5541686655435471e-41), (90, 1.9392517969836692e-55)]; salinity effect multiplier : 1.10500381093; technological developments in irrigation : 0.0117979353255; adaptation time from irrigated agriculture : 1.58060947607; food shortage multiplier : 0.955325345996; deaths multiplier : 0.875605669911; '
# we assume the case specification was copied from the logger
splitOne = line.split(';')
variable = {}
for n in range(len(splitOne) - 1):
splitTwo = splitOne[n].split(':')
variableElement = splitTwo[0]
# Delete the spaces and other rubish on the sides of the variable name
variableElement = variableElement.lstrip()
variableElement = variableElement.lstrip("'")
variableElement = variableElement.rstrip()
variableElement = variableElement.rstrip("'")
print(variableElement)
valueElement = splitTwo[1]
valueElement = valueElement.lstrip()
valueElement = valueElement.rstrip()
variable[variableElement] = valueElement
print(variable)
# This generates a new (text-formatted) model
changeNextLine = False
settedValues = []
for line in open(pathToExistingModel):
if line.find("=") != -1:
elements = line.split("=")
value = elements[0]
value = value.strip()
if value in variable:
elements[1] = variable.get(value)
line = elements[0] + " = " + elements[1]
settedValues.append(value)
newModel.write(line)
notSet = set(variable.keys()) - set(settedValues)
print(notSet)
|
class Solution:
def findUnsortedSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
sort_nums = nums.copy()
sort_nums.sort()
nums_order = [nums[i]==sort_nums[i] for i in range(n)]
if all(nums_order):
return 0
else:
invaild_pos = [idx for idx, flag in enumerate(nums_order) if not flag]
return invaild_pos[-1]-invaild_pos[0]+1
|
game = {
'leds': (
# GPIO05 - Pin 29
5,
# GPIO12 - Pin 32
12,
# GPIO17 - Pin 11
17,
# GPIO22 - Pin 15
22,
# GPIO25 - Pin 22
25
),
'switches': (
# GPIO06 - Pin 31
6,
# GPIO13 - Pin 33
13,
# GPIO19 - Pin 35
19,
# GPIO23 - Pin 16
23,
# GPIO24 - Pin 18
24
),
'countdown': 5,
'game_time': 60,
'score_increment': 1
}
|
# Aula de Dicionários
dados = dict()
dados = {'nome': 'Pedro','idade': 23}
print(dados['nome'])
print(dados['idade'])
print(f'O {dados["nome"]} tem {dados["idade"]} anos de idade!')
print(dados.keys())
print(dados.values())
print(dados.items())
for k in dados.keys():
print(k)
del dados['nome']
# Criando um dicionario dentro de uma lista
brasil = []
estado1 = {'uf' : 'Rio de Janeiro', 'sigla' : 'RJ'}
estado2 = {'uf' : 'Minas Gerais', 'sigla' : 'MG'}
brasil.append(estado1)
brasil.append(estado2)
print(brasil)
print(brasil[0]['sigla'])
estado = dict()
ebrasil = []
for c in range(0,3):
estado['uf'] = str(input('Digite o seu estado: '))
estado ['sigla'] = str(input("Digite a Sigla do seu estado: "))
ebrasil.append(estado.copy())
for e in ebrasil:
for k, v in e.items():
print(f'O campo {k} tem valor {v}.')
|
"""See navigate.__doc__."""
room = [
"Crypt Entrance", "Math Room", "English Room", "NCEA Headquaters",
"Fancy Wall"
]
N = [2, 4, 4, 4]
S = [4, 4, 0, 4]
E = [3, 0, 4, 4]
W = [1, 4, 4, 0]
desc = [
"A dull enclosed space with three doors",
"A dull enclosed space with one door",
"A dull enclosed space with one door",
"A dull enclosed space with one door"
]
def navigate(location=0): # noqa: D205
"""Show the user the options for navigation and give them a prompt.
Check that the user has selected a valid target and move their
location to that target.
Show the user the options for navigation by getting their location and
finding possible exits through the NSEW lists. Find the names of the rooms
on the other side of the exits by consulting the room list and the
description list. Give the user a prompt where they answer the room they
want to go to as a number 1-4 corresponding to the number beside the room
shown in the prompt. Make sure the room is not 4 and return the users
updated location.
Args:
location:
Optional; The room the user is currently in, defaults to 0.
Returns:
The location of the user as an int.
"""
user_input = input(f"""
Navigation:
1) North: {room[N[location]]};
2) South: {room[S[location]]};
3) East: {room[E[location]]};
4) West: {room[W[location]]};
[1-4]: """)
if user_input == '1':
if N[location] == 4:
input("""
That wall sure looks like a hidden entrance. You try and activate it,
it doesn't react.""")
return navigate(location)
return N[location]
elif user_input == '2':
if S[location] == 4:
input("""
That wall sure looks like a hidden entrance. You try and activate it,
it doesn't react.""")
return navigate(location)
return S[location]
elif user_input == '3':
if E[location] == 4:
input("""
That wall sure looks like a hidden entrance. You try and activate it,
it doesn't react.""")
return navigate(location)
return E[location]
elif user_input == '4':
if W[location] == 4:
input("""
That wall sure looks like a hidden entrance. You try and activate it,
it doesn't react.""")
return navigate(location)
return W[location]
else:
input("""
When prompted, enter one of the numbers 1, 2, 3, 4.
Each number corresponds to an action printed on screen""")
return navigate(location)
if __name__ == "__main__":
print(navigate(int(input())))
|
# Databricks notebook source
# MAGIC %run ./_utility-methods $lesson="3.1"
# COMMAND ----------
DA.cleanup()
DA.init(create_db=False)
install_dtavod_datasets(reinstall=False)
print()
copy_source_dataset(f"{DA.working_dir_prefix}/source/dtavod/flights/departuredelays.csv", f"{DA.paths.working_dir}/flights/departuredelays.csv", "csv", "flights")
DA.conclude_setup()
|
class CNConfig:
interp_factor = 0.075
sigma = 0.2
lambda_= 0.01
output_sigma_factor=1./16
padding=1
cn_type = 'pyECO'
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ˅
# ˄
class MessageDisplay(object):
# ˅
# ˄
def __init__(self, message):
self.__message = message
# ˅
pass
# ˄
def display_with_hyphens(self):
# ˅
print('-- ' + self.__message + ' --')
# ˄
def display_with_brackets(self):
# ˅
print('[[ ' + self.__message + ' ]]')
# ˄
# ˅
# ˄
# ˅
# ˄
|
def sumLoad(mirror):
"""Returns system sums of active PSLF load as [Pload, Qload]"""
sysPload = 0.0
sysQload = 0.0
# for each area
for area in mirror.Area:
# reset current sums
area.cv['P'] = 0.0
area.cv['Q'] = 0.0
# sum each active load P and Q to area agent
for load in area.Load:
if load.cv['St'] == 1:
area.cv['P'] += load.cv['P']
area.cv['Q'] += load.cv['Q']
# sum area agent totals to system
sysPload += area.cv['P']
sysQload += area.cv['Q']
return [sysPload,sysQload]
|
#A variável 'i' recebe um valor pelo teclado do usuário.
i=int(input(f'Quantos anos você tem?'))
#A variável 'c' recebe um valor do resultado da formula de calculo entre i e 7
c=i*7
#imprime 'Se você fosse um cachorro, você teria {c} anos.'
print(f'Se você fosse um cachorro, você teria {c} anos.')
|
# @Title: 把字符串转换成整数 (把字符串转换成整数 LCOF)
# @Author: 18015528893
# @Date: 2021-02-02 21:12:00
# @Runtime: 44 ms
# @Memory: 14.8 MB
class Solution:
def strToInt(self, str: str) -> int:
s = str.strip()
if s == '':
return 0
if s[0] == '+':
sign = 1
i = 1
elif s[0] == '-':
sign = -1
i = 1
else:
sign = 1
i = 0
res = 0
boundary = (2**31-1) // 10
while i < len(s):
c = s[i]
if not '0' <= c <= '9':
break
int_c = ord(c) - ord('0')
if (res == boundary and int_c > 7) or res > boundary:
return -2147483648 if sign == -1 else 2147483647
else:
res = res * 10 + int_c
i += 1
return sign * res
|
class Solution(object):
def sumOddLengthSubarrays(self, arr):
"""
:type arr: List[int]
:rtype: int
"""
sum_subarr = 0
l = len(arr)
odd_arr_len = 1 # to be increased by 2 after every iteration until equal to or less than l
while(odd_arr_len <= l):
i = 0
while(i + odd_arr_len < l + 1):
sum_subarr += sum(arr[i: i + odd_arr_len])
i += 1
odd_arr_len += 2
return sum_subarr
def main():
arr = [1,4,2,5,3]
# arr = [10,11,12]
# arr = [1,2]
obj = Solution()
return obj.sumOddLengthSubarrays(arr)
if __name__ == '__main__':
print(main())
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Jared
"""
#DB Config File
host='localhost'
port=27017
dummy=True
saveFeatures = True
featureDBFolder = '/Users/Jared/Dropbox/Master Thesis/Data/featureDB2/'
crystalDBFolder = '/Users/Jared/Dropbox/Master Thesis/Data/crystalDB2/'
saveFeaturesFile='junk.csv'
saveFeaturesPath='./data/features/'
|
sortname = {
'bubblesort': f'Bubble Sort O(n\N{SUPERSCRIPT TWO})', 'insertionsort': f'Insertion Sort O(n\N{SUPERSCRIPT TWO})',
'selectionsort': f'Selection Sort O(n\N{SUPERSCRIPT TWO})', 'mergesort': 'Merge Sort O(n log n)',
'quicksort': 'Quick Sort O(n log n)', 'heapsort': 'Heap Sort O(n log n)'
}
|
class Cons():
def __init__(self, data, nxt):
self.data = data
self.nxt = nxt
Nil = None
def new(*elems):
if len(elems) == 0:
return Nil
else:
return Cons(elems[0], new(*elems[1:]))
def printls(xs):
i = xs
while i != Nil:
print(i.data)
i = i.nxt
|
"""Default inputs used in the absence of user making a choice. \n
For information on the physical meaning of each of the constants see scientific background.
Variables:
number_of_models: number of models to compare (int) \n
model_1_inputs: input information for model 1 (dict) \n
model_2_inputs: input information for model 2 (dict)
model_dictionaries:
mX_time: time the model runs for (h) \n
mX_timestep: time step for model calculations (h) \n
mX_continous_dose_amount: |Dose| [ng] \n
mX_instantaneous_dose_amount: |Dose| [ng] \n
mX_dose_times: (t) in Dose(t) [hours] \n
mX_dose_entry: subcutaneous or intravenous bolus \n
mX_number_of_compartments: number of peripheral compartments \n
mX_volume_c: V_c [mL] \n
mX_q_c_initial: q_c(t=0) [ng] \n
mX_CL: CL [mL/hour] \n
mX_volume_1: V_{p1} [mL] \n
mX_q_1_initial: q_{p1}(t=0) [ng] \n
mX_flux_1: Q_{p1} [mL/hour] \n
mX_volume_2: V_{p2} [mL] \n
mX_q_2_initial: q_{p2}(t=0) [ng] \n
mX_flux_2": Q_{p2} [mL/hour] \n
mX_k_a": k_a [/hour] \n
mX_q_0_initial: q_0(t=0) [ng] \n
"""
#Models
number_of_models = 2 # number of models to compare
model_1_inputs = {"m1_time": 1, #time the first model runs for
"m1_timestep": 0.001, #time step for model calculations
"m1_continous_dose_amount": 1, # |Dose| [ng]
"m1_instantaneous_dose_amount": 1, # |Dose| [ng]
"m1_dose_times": [0, 1 / 2, 1], # (t) in Dose(t) [hours]
"m1_dose_entry": 'intravenous', # subcutaneous or intravenous bolus
"m1_number_of_compartments": 2, # number of peripheral compartments
"m1_volume_c": 1, # V_c [mL]
"m1_q_c_initial": 1, # q_c(t=0) [ng]
"m1_CL": 1, # CL [mL/hour]
"m1_volume_1": 1, # V_{p1} [mL]
"m1_q_1_initial": 1, # q_{p1}(t=0) [ng]
"m1_flux_1": 1, # Q_{p1} [mL/hour]
"m1_volume_2": 2, # V_{p2} [mL]
"m1_q_2_initial": 1, # q_{p2}(t=0) [ng]
"m1_flux_2": 2, # Q_{p2} [mL/hour]
"m1_k_a": 1, # k_a [/hour]
"m1_q_0_initial": 1} # q_0(t=0) [ng]
model_2_inputs = {"m2_time": 1, #time the first model runs for
"m2_timestep": 0.001, #time step for model calculations
"m2_continous_dose_amount": 1, # |Dose| [ng]
"m2_instantaneous_dose_amount": 1, # |Dose| [ng]
"m2_dose_times": [0, 1 / 2, 1], #(t) in Dose(t) [hours]
"m2_dose_entry": 'subcutaneous', # subcutaneous or intravenous bolus
"m2_number_of_compartments": 2, # number of peripheral compartments
"m2_volume_c": 1, # V_c [mL]
"m2_q_c_initial": 1, # q_c(t=0) [ng]
"m2_CL": 1, # CL [mL/hour]
"m2_volume_1": 1, # V_{p1} [mL]
"m2_q_1_initial": 1, # q_{p2}(t=0) [ng]
"m2_flux_1": 1, # Q_{p1} [mL/hour]
"m2_volume_2": 2, # V_{p2} [mL]
"m2_q_2_initial": 1, # q_{p2}(t=0) [ng]
"m2_flux_2": 2, # Q_{p2} [mL/hour]
"m2_k_a": 1, # k_a [/hour]
"m2_q_0_initial": 1} # q_0(t=0) [ng]
|
"""
Entradas
lote de naranjas compradas-->int-->X
Precio de naranjas por docena-->float-->Y
Dinero obtenido por la venta de las naranjas-->float-->K
Salidas
Porcentaje de ganancias-->float-->porcentaje
"""
#Entradas
X=int(input("Digite el lote de naranjas compradas: "))
Y=float(input("Digite el precio por docena de las naranjas: "))
K=float(input("Digite el dinero obtenido por la venta de las naranjas: "))
#Caja negra
docenas=X/12
gasto=docenas*Y
ganancias=K-gasto
porcentaje=(ganancias/gasto)*100
#Salidas
print("El porcentaje de ganancias obtenidas es de:",porcentaje,"%")
|
names = ['John', 'Bob', 'Mosh', 'Sarah', 'Mary']
print(names[2])
print(names[-1])
print(names[2:])
# prints from third to end
print(names[2:4])
# prints third to fourth, does not include last one
names[0] = 'Jon'
# Find largest number in list
numbers = [1, 34, 34, 12312, 123, 23, 903, 341093, 34]
max_number = numbers[0]
for item in numbers:
if item > max_number:
max_number = item
print(f"The largest number is {max_number}.")
# 2D Lists
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# matrix[0][1] = 20
# print(matrix[0][1])
# for row in matrix:
# for item in row:
# print(item)
# List Methods
numbers = [5, 2, 1, 7, 4, 5, 5, 5]
numbers.append(20)
numbers.insert(0, 10)
# removes first mention of 5
numbers.remove(5)
# clears entire list
# numbers.clear()
# removes last item
numbers.pop()
print(numbers)
# finds index of first occurence of item
print(numbers.index(5))
# safer version, if not found returns false
print(50 in numbers)
print(numbers.count(5))
numbers.sort()
numbers.reverse()
print(numbers)
numbers2 = numbers.copy()
numbers2.append(10)
print(numbers2)
# Write a program to remove the duplicates in a list
list1 = [1, 3, 5, 5, 7, 9, 9, 9, 1]
checked_number = 0
check_count = 0
for item in list1:
checked_number = item
check_count = 0
for number in list1:
if checked_number == number:
check_count += 1
if check_count > 1:
list1.remove(checked_number)
print(list1)
#Solution
numbers = [2, 2, 4, 6, 3, 4, 6, 1]
uniques = []
for number in numbers:
if number not in uniques:
uniques.append(number)
|
n = int(input("n: "))
a = int(input("a: "))
b = int(input("b: "))
c = int(input("c: "))
while (n <= 0 or n >= 100000) or (a <= 0 or a >= 100000) or (b <= 0 or b >= 100000) or (c <= 0 or c >= 100000):
print("All numbers should be positive between 0 and 100 000!")
n = int(input("n: "))
a = int(input("a: "))
b = int(input("b: "))
c = int(input("c: "))
n+=1
line = [None] * n # None-> empty; 1-> first person dot; 2-> second person dot
#populate the line with dots
i = 0
while i <= (n-1)/a:
line[i*a] = 1
i+=1
i = 0
line[n - 1] = 2
while i <= (n-1)/b:
line[(n - 1) - (i * b)] = 2
i+=1
painted_red_segment_length = 0
i = 0
#calcualte the length of the painted segment
while i < n:
if i == 0:
if (line[i] != line[i + 1]) and (line[i] != None) and (line[i + 1] != None):
painted_red_segment_length += 1
i+=1
elif i == n-1:
if (line[i] != line[i - 1]) and (line[i] != None) and (line[i - 1] != None):
painted_red_segment_length += 1
else:
if (line[i] != line[i - 1]) and (line[i] != None) and (line[i - 1] != None):
painted_red_segment_length += 1
if (line[i] != line[i + 1]) and (line[i] != None) and (line[i + 1] != None):
painted_red_segment_length += 1
i+=1
i+=1
#calculate the length of the segment that is not painted
result = (n-1) - painted_red_segment_length
print("result: " + str(result))
|
def write_empty_line(handle):
handle.write('\n')
def write_title(handle, title, marker = ''):
if marker == '':
line = '{0}\n'.format(title)
else:
line = '{0} {1}\n'.format(marker, title)
handle.write(line)
def write_notes(handle, task):
def is_task_with_notes(task):
result = False
for note in task['notes']:
if note.strip() != '':
result = True
break
return result
if is_task_with_notes(task):
notes = '\n'.join(task['notes'])
handle.write(notes)
write_empty_line(handle)
|
def goodSegement1(badList,l,r):
sortedBadList = sorted(badList)
current =sortedBadList[0]
maxVal = 0
for i in range(len(sortedBadList)):
current = sortedBadList[i]
maxIndex = i+1
# first value
if i == 0 and l<=current<=r:
val = current - l
prev = l
print("first index value")
print("prev, current : ",prev,current)
if(val>maxVal):
maxVal = val
print("1. (s,e)",l,current)
# other middle values
elif l<=current<=r:
prev = sortedBadList[i-1]
val = current - prev
print("prev, current : ",prev,current)
if(val>maxVal):
maxVal = val
print("2. (s,e)",prev,current)
# last value
if maxIndex == len(sortedBadList) and l<=current<=r:
print("last index value")
next = r
val = next - current
if(val>maxVal):
maxVal = val
print("3. (s,e)",current,next)
print("maxVal:",maxVal-1)
pass
goodSegement1([2,5,8,10,3],1,12)
goodSegement1([37,7,22,15,49,60],3,48)
|
l, r = map(int, input().split())
mod = 10 ** 9 + 7
def f(x):
if x == 0:
return 0
res = 1
cnt = 2
f = 1
b_s = 2
e_s = 4
b_f = 3
e_f = 9
x -= 1
while x > 0:
if f:
res += cnt * (b_s + e_s) // 2
b_s = e_s + 2
e_s = e_s + 2 * (4 * cnt)
else:
res += cnt * (b_f + e_f) // 2
b_f = e_f + 2
e_f = e_f + 2 * (4 * cnt)
x -= cnt
if x < 0:
if f:
b_s -= 2
res -= abs(x) * (b_s + b_s - abs(x + 1) * 2) // 2
else:
b_f -= 2
res -= abs(x) * (b_f + b_f - abs(x + 1) * 2) // 2
cnt *= 2
f = 1 - f
return res
print((f(r) - f(l - 1)) % mod)
|
def sum_doubles():
numbers = open('1.txt').readline()
numbers = numbers + numbers[0]
total = 0
for i in range(len(numbers) - 1):
a = int(numbers[i])
b = int(numbers[i+1])
if a == b:
total += a
return total
# print(sum_doubles()) # 1341
def sum_halfway(numbers):
total = 0
delta = int(len(numbers) / 2)
for i in range(len(numbers) - 1):
bi = (i + delta) % len(numbers)
a = int(numbers[i])
b = int(numbers[bi])
if a == b:
total += a
return total
print(sum_halfway(open('1.txt').readline())) # 1348
# print(sum_halfway("12131415"))
|
def reader():
...
|
"""
Entradas
a-->int-->Cantidad de billetes de 50000
b-->int-->Cantidad de billetes de 20000
c-->int-->Cantidad de billetes de 10000
d-->int-->Cantidad de billetes de 5000
e-->int-->Cantidad de billetes de 2000
f-->int-->Cantidad de billetes de 1000
g-->int-->Cantidad de billetes de 500
h-->int-->Cantidad de billetes de 100
Salidas
i-->int-->Cantidad total de dinero
"""
inp=input().split()
q,w,e,r,t,j,u,p=inp
q=int(q)
w=int(w)
e=int(e)
r=int(r)
t=int(t)
j=int(j)
u=int(u)
p=int(p)
#caja negra
i=(q*50000)+(w*20000)+(e*10000)+(r*5000)+(t*2000)+(j*1000)+(u*500)+(p*100)
print("La cantidad total de dinero es "+str(i))
|
#!/usr/bin/env python3
# -*- config: utf-8 -*-
# Напечатать в обратном порядке последовательность чисел, признаком конца которой
# является 0.
def prt():
n = int(input())
if n == 0:
return
prt()
print(n)
prt()
|
def C(x=None, ls=('$', 'A', 'C', 'G', 'T')):
x = "ATATATTAG" if not x else x
x += "$"
dictir = {i: sum([x.count(j) for j in ls[:ls.index(i)]]) for i in ls}
return dictir
def BWT(x, suffix):
x = "ATATATTAG" if not x else x
x += "$"
return ''.join([x[i - 2] for i in suffix])
def suffix_arr(x="ATATATTAG"):
x = x + '$' if '$' not in x else x
shifts = [x]
for i in range(1, len(x)):
shifts.append(x[i:] + x[:i])
shifts.sort()
suffix_arr = [len(shift) - shift.index('$') for shift in shifts]
return shifts, suffix_arr
def main():
x = 'ATATATTAG'
S = [10, 8, 1, 3, 5, 9, 7, 2, 4, 6]
print(C())
print(BWT(x, S))
if __name__ == '__main__':
main()
|
CONTEXT = {'cell_line': 'Cell Line',
'cellline': 'Cell Line',
'cell_type': 'Cell Type',
'celltype': 'Cell Type',
'tissue': 'Tissue',
'interactome': 'Interactome'
}
HIDDEN_FOLDER = '.contnext'
ZENODO_URL = 'https://zenodo.org/record/5831786/files/data.zip?download=1'
|
def diag_diff(matriza):
first_diag = second_diag = 0
razmer = len(matriza)
for i in range(razmer):
first_diag += matriza[i][i]
second_diag += matriza[i][razmer - i - 1]
return first_diag - second_diag
|
description = 'STRESS-SPEC setup with Eulerian cradle'
group = 'basic'
includes = [
'standard', 'sampletable',
]
sysconfig = dict(
datasinks = ['caresssink'],
)
devices = dict(
chis = device('nicos.devices.generic.Axis',
description = 'Simulated CHIS axis',
motor = device('nicos.devices.generic.VirtualMotor',
fmtstr = '%.2f',
unit = 'deg',
abslimits = (-180, 180),
visibility = (),
speed = 2,
),
precision = 0.001,
),
phis = device('nicos.devices.generic.Axis',
description = 'Simulated PHIS axis',
motor = device('nicos.devices.generic.VirtualMotor',
fmtstr = '%.2f',
unit = 'deg',
abslimits = (-720, 720),
visibility = (),
speed = 2,
),
precision = 0.001,
),
)
startupcode = '''
SetDetectors(adet)
'''
|
class Solution:
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
s=0
for i in range(0,len(nums),2):
s+=nums[i]
return s
|
# -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
class AclModeEnum(object):
"""Implementation of the 'AclMode' enum.
ACL mode for this SMB share.
'kNative' specifies native ACL mode supports UNIX-like ACLs and Windows
ACLs. In native mode, because SMB natively supports both ACLs while NFS
only supports UNIX ACLs, ACLs will not be shared between SMB and NFS.
'kShared' shares UNIX-like ACL permissions with the NFS protocol.
In shared mode both protocol ACL permissions are required to match.
When one protocol creates files or modifies permissions, they must comply
with the permission settings of the other protocol.
Attributes:
KSHARED: TODO: type description here.
KNATIVE: TODO: type description here.
"""
KSHARED = 'kShared'
KNATIVE = 'kNative'
|
def Text(Text="", classname="", Type="h1", TextStyle="", Id="0"):
if TextStyle != "":
if classname != "":
return f"""<{Type} id={Id} class='{classname}' style='{TextStyle}'>{Text}</{Type}>"""
else:
return f"""<{Type} id={Id} style='{TextStyle}'>{Text}</{Type}>"""
else:
if classname != "":
return f"""<{Type} id={Id} class='{classname}'>{Text}</{Type}>"""
else:
return f"""<{Type} id={Id} >{Text}</{Type}>"""
|
# Copyright (C) 2017 Ming-Shing Chen
def gf2_mul( a , b ):
return a&b
# gf4 := gf2[x]/x^2+x+1
# 4 and , 3 xor
def gf4_mul( a , b ):
a0 = a&1
a1 = (a>>1)&1
b0 = b&1
b1 = (b>>1)&1
ab0 = a0&b0
ab1 = (a1&b0)^(a0&b1)
ab2 = a1&b1
ab0 ^= ab2
ab1 ^= ab2
ab0 ^= (ab1<<1)
return ab0
# gf16 := gf4[y]/y^2+y+x
# gf16 mul: xor: 18 ,and: 12
def gf16_mul( a , b ):
a0 = a&3
a1 = (a>>2)&3
b0 = b&3
b1 = (b>>2)&3
a0b0 = gf4_mul( a0 , b0 )
a1b1 = gf4_mul( a1 , b1 )
a0a1xb0b1_a0b0 = gf4_mul( a0^a1 , b0^b1 ) ^ a0b0
rd0 = gf4_mul( 2 , a1b1 )
a0b0 ^= rd0
return a0b0|(a0a1xb0b1_a0b0<<2)
# gf256 := gf16[x]/x^2 + x + 0x8
def gf256_mul( a , b ):
a0 = a&15
a1 = (a>>4)&15
b0 = b&15
b1 = (b>>4)&15
ab0 = gf16_mul( a0 , b0 )
ab1 = gf16_mul( a1 , b0 ) ^ gf16_mul( a0 , b1 )
ab2 = gf16_mul( a1 , b1 )
ab0 ^= gf16_mul( ab2 , 8 )
ab1 ^= ab2
ab0 ^= (ab1<<4)
return ab0
#382 bit operations
def gf216_mul( a , b ):
a0 = a&0xff
a1 = (a>>8)&0xff
b0 = b&0xff
b1 = (b>>8)&0xff
a0b0 = gf256_mul( a0 , b0 )
a1b1 = gf256_mul( a1 , b1 )
#a0b1_a1b0 = gf16_mul( a0^a1 , b0^b1 ) ^ a0b0 ^ a1b1 ^a1b1
a0b1_a1b0 = gf256_mul( a0^a1 , b0^b1 ) ^ a0b0
rd0 = gf256_mul( a1b1 , 0x80 )
return (a0b1_a1b0<<8)|(rd0^a0b0)
#gf65536 := gf256[x]/x^2 + x + 0x80
def gf65536_mul( a , b ):
a0 = a&0xff;
a1 = (a>>8)&0xff;
b0 = b&0xff;
b1 = (b>>8)&0xff;
ab0 = gf256_mul( a0 , b0 );
ab2 = gf256_mul( a1 , b1 );
ab1 = gf256_mul( a0^a1 , b0^b1 )^ab0;
return (ab1<<8)^(ab0^gf256_mul(ab2,0x80));
#gf832 := gf65536[x]/x^2 + x + 0x8000
def gf832_mul( a , b ):
a0 = a&0xffff;
a1 = (a>>16)&0xffff;
b0 = b&0xffff;
b1 = (b>>16)&0xffff;
ab0 = gf65536_mul( a0 , b0 );
ab2 = gf65536_mul( a1 , b1 );
ab1 = gf65536_mul( a0^a1 , b0^b1 )^ab0;
return (ab1<<16)^(ab0^gf65536_mul(ab2,0x8000));
def gf832_inv(a) :
r = a
for i in range(2,32):
r = gf832_mul(r,r)
r = gf832_mul(r,a)
return gf832_mul(r,r)
|
lista = []
for c in range (0, 5):
n1 = int(input(f'Digite um valor para a posição {c}: '))
lista.append(n1)
for x in range (0, 5):
if lista [x] == max(lista):
n2 = x
for z in range (0, 5):
if lista [z] == min(lista):
n3 = z
print ('-='*20)
print (f'Voce digitou os valores {lista}')
print (f'O maior valor digitado foi {max(lista)}. Nas posições {lista.index(max(lista))}... {n2}...')
print (f'O menor valor digitado foi {min(lista)}. Nas posições {lista.index(min(lista))}... {n3}...')
|
#Dictionary and Class usage and examples
#cleaning up the input values
def sanitize(time_string):
if '-' in time_string:
splitter = '-'
elif ':' in time_string:
splitter = ':'
else:
return time_string
(mins, secs) = time_string.split(splitter)
return(mins + '.' + secs)
#reading in the coaches data
def get_coach_data(filename):
try:
with open(filename) as f:
data=f.readline()
return(data.strip().split(','))
except IOError as ioerr:
print('File Error' + str(ioerr))
return(None)
#function call to read in sarah's data
sarah = get_coach_data('sarah2.txt')
'''
#function call to read in sarah's data
sarah = get_coach_data('sarah2.txt')
#(sarah_name, sarah_dob) = sarah.pop(0),sarah.pop(0)
print(sarah_name + "'s fastest times are:" + str(sorted(set([sanitize(t) for t in sarah]))[0:3]))
'''
#shortcoming of this code is that it's only written for Sarah, you would still need to alter
#print statements for each runner, easy with 4 runners, difficult with 4000 runners.
#the three pieces of data about sarah are all disjointed or independent of each other
#Enter the Dictionary (Key/Value Pairs), aka mapping a hash or an associative array
#Keys: Name/DOB/Times Values: sarah's data
#can you have an unlimited number of keys?
#The order the data is added to the dict isn't maintained, but the key/value association is maintained
runnersDict={}
runnersDict['name'] = sarah.pop(0)
runnersDict['dob'] = sarah.pop(0)
runnersDict['times'] = sarah
print(runnersDict['name'] + "'s fastest times are:" + str(sorted(set([sanitize(t) for t in sarah]))[0:3]))
|
a1 = 1
a2 = 2
an = a1 + a2
sum_ = a2
print(a1, ',', a2, end=", ")
for n in range(100):
an = a1 + a2
if an > 4000000:
print('\n=== DONE ===')
break
if an % 2 == 0:
sum_ += an
print(an, end=", ")
a1 = a2
a2 = an
print("Even term sum =", sum_)
|
# Difficulty Level: Easy
# Question: Filter the dictionary by removing all items with a value of greater
# than 1.
# d = {"a": 1, "b": 2, "c": 3}
# Expected output:
# {'a': 1}
# Hint 1: Use dictionary comprehension.
# Hint 2: Inside the dictionary comprehension access dictionary items with
# d.items() if you are on Python 3, or dict.iteritems() if you are on Python 2
# Program
# Solution 1
d = {"a": 1, "b": 2, "c": 3}
print({ i:j for i,j in d.items() if j <= 1})
# Solution 2
d = {"a": 1, "b": 2, "c": 3}
d = dict((key, value) for key, value in d.items() if value <= 1)
print(d)
# Output
# shubhamvaishnav:python-bootcamp$ python3 21_dictionary_filtering.py
# {'a': 1}
|
"""
Binary search is a classic recursive algorithm.
It is used to efficiently locate a target value within a sorted sequence of n elements.
"""
def binary_search(data, target, low, high):
"""Binary search implementation, inefficient, O(n)
Return True if target is found in indicated portion of a list.
The search only considers the portion from low to high inclusive.
"""
if low > high:
return False # interval is empty - no match.
else:
mid = (low + high) // 2
if target == data[mid]:
return True
elif target < data[mid]:
return binary_search(data, target, low, mid-1)
else:
return binary_search(data, target, mid+1, high)
def binary_search_iterative(data, target):
"""Return True if target is foudn in the given list."""
low = 0
high = len(data) - 1
while low <= high:
mid = (low + high) // 2
if target == data[mid]: # Found a match.
return True
elif target < data[mid]:
high = mid - 1 # consider values left of mid.
else:
low = mid + 1 # consider values right of mid.
return False
|
def factorial(n):
if n == 0:
return 1
elif n == 1:
return 1
else:
return factorial(n-1) * n
example = int(input())
print(factorial(example))
|
"""
python 快速排序
"""
def quick_sort():
pass
def sort(li):
"""进行一轮比较,给一个基准值找到一个正确位置的下标索引"""
mid = li[0]
l_cur = 1
r_cur = len(li) - 1
while True:
# 左游标遇到比基准值大的停
while li[l_cur] <= mid and r_cur >= l_cur:
l_cur += 1
while li[r_cur] > mid and r_cur >= l_cur:
r_cur -= 1
if r_cur < l_cur:
li[r_cur], li[0] = li[0], li[r_cur]
return li
else:
li[r_cur], li[l_cur] = li[l_cur], li[r_cur]
print(sort([6, 5, 3, 1, 8, 7, 2, 4]))
|
'''
Created on Mar 9, 2019
@author: hzhang0418
'''
|
r=open('all.protein.faa','r')
w=open('context.processed.all.protein.faa','w')
start = True
mem = ""
for line in r:
if '>' in line and not start:
list_char = list(mem.replace('\n',''))
list_context = []
list_context_length_before = 1
list_context_length_after = 1
for i in range(len(list_char)):
tmp=""
for j in range(i-list_context_length_before,i+list_context_length_after+1):
if j < 0 or j>=len(list_char):
tmp=tmp+'-'
else:
tmp=tmp+list_char[j]
list_context.append(tmp)
w.write (" ".join(list_context)+"\n")
mem = ""
else:
if not start:
mem=mem+line
start = False
r.close()
w.close()
|
number = int(input())
dots = ((3 * number) - 1) // 2
print('.' * dots + 'x' + '.' * dots)
print('.' * (dots - 1) + '/' + 'x' + '\\' + '.' * (dots - 1))
print('.' * (dots - 1) + 'x' + '|' + 'x' + '.' * (dots - 1))
ex = number
dots = ((3 * number) - ((ex * 2) + 1)) // 2
for i in range(1, (number // 2) + 2):
print('.' * dots + 'x' * ex + '|' + 'x' * ex + '.' * dots)
dots = dots - 1
ex = ex + 1
ex = ex - 2
dots = dots + 2
for a in range(1, (number // 2) + 1):
print('.' * dots + 'x' * ex + '|' + 'x' * ex + '.' * dots)
dots = dots + 1
ex = ex - 1
dots = ((3 * number) - 1) // 2
print('.' * (dots - 1) + '/' + 'x' + '\\' + '.' * (dots - 1))
print('.' * (dots - 1) + '\\' + 'x' + '/' + '.' * (dots - 1))
ex = number
dots = ((3 * number) - ((ex * 2) + 1)) // 2
for i in range(1, (number // 2) + 2):
print('.' * dots + 'x' * ex + '|' + 'x' * ex + '.' * dots)
dots = dots - 1
ex = ex + 1
ex = ex - 2
dots = dots + 2
for a in range(1, (number // 2) + 1):
print('.' * dots + 'x' * ex + '|' + 'x' * ex + '.' * dots)
dots = dots + 1
ex = ex - 1
dots = ((3 * number) - 1) // 2
print('.' * (dots - 1) + 'x' + '|' + 'x' + '.' * (dots - 1))
print('.' * (dots - 1) + '\\' + 'x' + '/' + '.' * (dots - 1))
print('.' * dots + 'x' + '.' * dots)
|
# -*- coding: utf-8 -*-
def main():
a, b = map(int, input().split())
pins = ['x' for _ in range(10)]
p = list(map(int, input().split()))
for pi in p:
pins[pi - 1] = '.'
if b > 0:
q = list(map(int, input().split()))
for qi in q:
pins[qi - 1] = 'o'
print(' '.join(map(str, pins[6:])))
print(' '.join(map(str, pins[3:6])))
print(' '.join(map(str, pins[1:3])))
print(' '.join(map(str, pins[0])))
if __name__ == '__main__':
main()
|
'''
Macros Calculator
MIT License
Copyright (c) 2018 Casey Chad Salvador
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. '''
## Variable
weight = float(input("Please enter your current weight: "))
## Create Protein Function
def protein(weight):
fitnessLvl0 = .5
fitnessLvl1 = .75
fitnessLvl2 = 1
fitnessLvl3 = 1.25
fitnessLvl = int(input("Please enter your fitness level (i.e. 1 = New to Training, 2 = In Shape, 3 = Competing, 4 = No Training): "))
if fitnessLvl == 4:
pro = fitnessLvl0 * weight
return pro
elif fitnessLvl == 1:
pro = fitnessLvl1 * weight
return pro
elif fitnessLvl == 2:
pro = fitnessLvl2 * weight
return pro
elif fitnessLvl == 3:
pro = fitnessLvl3 * weight
return pro
## Create Fat Function
def fat(weight):
fat1 = .3
fat2 = .35
fat3 = .4
fatLvl = int(input("Please enter your fat level (i.e. 1 = Love Carbs, 2 = Mix, 3 = Love Fat (nuts, peanut butter, etc): "))
if fatLvl == 1:
fats = fat1 * weight
return fats
elif fatLvl == 2:
fats = fat2 * weight
return fats
elif fatLvl == 3:
fats = fat3 * weight
return fats
## Create Calorie Function
def calories(weight):
cal1 = 14
cal2 = 15
cal3 = 16
calLvl = int(input("Please enter your activity level (i.e. 1 = Less Movement, 2 = Moderately Moving, 3 = Actively Moving): "))
if calLvl == 1:
cal = cal1 * weight
return cal
elif calLvl == 2:
cal = cal2 * weight
return cal
elif calLvl == 3:
cal = cal3 * weight
return cal
cals = calories(weight)
protein = round(protein(weight))
fat = round(fat(weight))
## Create New Physique
def physique(cals):
shred = 500
maintain = 0
gain = 500
phyLvl = input(str("Please enter your physique goal (i.e. shred, maintain, gain): "))
if phyLvl == "shred":
phy = cals - shred
return phy
elif phyLvl == "maintain":
phy = cals - maintain
return phy
elif phyLvl == "gain":
phy = cals + gain
return phy
phyCal= physique(cals)
## Create Caloric Intake Function
# 4 x 9 x 4 Rule Applies Here
def cal(phyCal):
calPro = protein * 4
calFat = fat * 9
sumProFat = calPro + calFat
carbCal = phyCal - sumProFat
return carbCal
carbCal = cal(phyCal)
## Create Carbs Function
def carbs(carbCal):
carb = carbCal / 4
return carb
carb = round(carbs(carbCal))
print("")
## Results
print("Macros")
print("Protein: " + str(protein) + "g")
print("Fat: " + str(fat) + "g")
print("Carbohydrate: " + str(carb) + "g")
print("Total Calories per day: " + str(round(phyCal)) + "cal")
|
"""
test
~~~~
Flask-Monitor is a simple extension to Flask allowing you to add
prometheus middleware to add basic but very useful metrics for
your Python Flask app.
:license: MIT, see LICENSE for more details.
"""
|
#!/usr/bin/env python3
def main():
n = int(input())
ab = [list(map(int,input().split())) for _ in range(n)]
a = [ab[i][0] for i in range(n)]
b = [ab[i][1] for i in range(n)]
#A, Bの最小値
minA, minB = min(a), min(b)
#同一人物か判定
workerA = a.index(min(a))
workerB = b.index(min(b))
if workerA != workerB: #別人
print(max(min(a), min(b)))
else: #同一人物
secondMinA = sorted(a)[1]
secondMinB = sorted(b)[1]
if minA + minB <= max(a[workerA], secondMinB): #同一人物に任せた方が速い
print(minA + minB)
elif minA + minB <= max(secondMinA, b[workerB]): #同一人物に任せた方が速い
print(minA + minB)
else: #同一人物に任せた方が遅い
print(min(max(a[workerA], secondMinB), max(secondMinA, b[workerB])))
main()
|
"""
Implement an iterator over a binary search tree (BST). Your iterator will
be initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
Example:
7
/ \
3 15
/ \
9 20
BSTIterator iterator = new BSTIterator(root);
iterator.next(); // return 3
iterator.next(); // return 7
iterator.hasNext(); // return true
iterator.next(); // return 9
iterator.hasNext(); // return true
iterator.next(); // return 15
iterator.hasNext(); // return true
iterator.next(); // return 20
iterator.hasNext(); // return false
Note:
- next() and hasNext() should run in average O(1) time and uses O(h)
memory, where h is the height of the tree.
- You may assume that next() call will always be valid, that is, there
will be at least a next smallest number in the BST when next() is
called.
"""
#Difficulty: Medium
#62 / 62 test cases passed.
#Runtime: 92 ms
#Memory Usage: 20 MB
#Runtime: 92 ms, faster than 38.46% of Python3 online submissions for Binary Search Tree Iterator.
#Memory Usage: 20 MB, less than 97.86% of Python3 online submissions for Binary Search Tree Iterator.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class BSTIterator:
def __init__(self, root: TreeNode):
self.stack = []
self.inorder(root, self.stack)
self.stack.reverse()
def next(self) -> int:
"""
@return the next smallest number
"""
if self.stack:
return self.stack.pop()
def hasNext(self) -> bool:
"""
@return whether we have a next smallest number
"""
return True if self.stack else False
def inorder(self, root, stack):
"""
prepare stack
"""
if not root:
return 0
self.inorder(root.left, stack)
stack.append(root.val)
self.inorder(root.right, stack)
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()
|
JETBRAINS_IDES = {
'androidstudio': 'Android Studio',
'appcode': 'AppCode',
'datagrip': 'DataGrip',
'goland': 'GoLand',
'intellij': 'IntelliJ IDEA',
'pycharm': 'PyCharm',
'rubymine': 'RubyMine',
'webstorm': 'WebStorm'
}
JETBRAINS_IDE_NAMES = list(JETBRAINS_IDES.values())
|
mystr="Python is a multipurpose and simply learning langauge"
for i in mystr:
print(i,end=" ")
print()
print(mystr.find("simply"))
print(mystr[0:11]+ " programming")
|
T1, T2 = map(int, input().split())
n = 1000001
sieve = [True] * n
m = int(n ** 0.5)
for i in range(2, m + 1):
if sieve[i] == True:
for j in range(i + i, n, i):
sieve[j] = False
for i in range(T1, T2 + 1):
if i == 1:
continue
if sieve[i]:
print(i)
|
#
# Copyright 2012 Sonya Huang
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# file that records common things relevant to bea data
use_table_margins = [
"margins", # negative
"rail_margin", "truck_margin", "water_margin", "air_margin",
"pipe_margin", "gaspipe_margin",
"wholesale_margin", "retail_margin"]
FINAL_DEMAND = "f"
VALUE_ADDED = "v"
INTERMEDIATE_OUTPUT = "i"
fd_sectors = {
1972: {"pce": "910000", "imports": "950000", "exports": "940000"},
1977: {"pce": "910000", "imports": "950000", "exports": "940000"},
1982: {"pce": "910000", "imports": "950000", "exports": "940000"},
1987: {"pce": "910000", "imports": "950000", "exports": "940000"},
1992: {"pce": "910000", "imports": "950000", "exports": "940000"},
1997: {"pce": "F01000", "imports": "F05000", "exports": "F04000"},
2002: {"pce": "F01000", "imports": "F05000", "exports": "F04000"},
}
fd_sector_names = {
"total": "All final demand",
"pce": "Personal Consumption Expenditures",
"imports": "Imports",
"exports": "Exports",
}
fd_sector_criteria = {
1972: "SUBSTRING(code FROM 1 FOR 2) IN " + \
"('91', '92', '93', '94', '95', '96', '97', '98', '99')",
1977: "SUBSTRING(code FROM 1 FOR 2) IN " + \
"('91', '92', '93', '94', '95', '96', '97', '98', '99')",
# based on similarity to 1987
1982: "SUBSTRING(code FROM 1 FOR 2) IN " + \
"('91', '92', '93', '94', '95', '96', '97', '98', '99')",
# http://www.bea.gov/scb/pdf/national/inputout/1994/0494ied.pdf (p84)
1987: "SUBSTRING(code FROM 1 FOR 2) IN " + \
"('91', '92', '93', '94', '95', '96', '97', '98', '99')",
# http://www.bea.gov/scb/account_articles/national/1197io/appxB.htm
1992: "SUBSTRING(code FROM 1 FOR 2) IN " + \
"('91', '92', '93', '94', '95', '96', '97', '98', '99')",
1997: "code LIKE 'F%'",
2002: "code LIKE 'F%'",
}
va_sector_criteria = {
1972: "code IN ('880000', '890000', '900000')",
1977: "code IN ('880000', '890000', '900000')",
1982: "code IN ('880000', '890000', '900000')",
# http://www.bea.gov/scb/pdf/national/inputout/1994/0494ied.pdf (p115)
1987: "code IN ('880000', '890000', '900000')",
# http://www.bea.gov/scb/account_articles/national/1197io/appxB.htm
1992: "SUBSTRING(code FROM 1 FOR 2) IN ('88', '89', '90')",
1997: "code LIKE 'V%'",
2002: "code LIKE 'V%'",
}
scrap_used_codes = {
1972: ("810000",),
1977: ("810001", "810002"),
1982: ("810001", "810002"),
1987: ("810001", "810002"),
1992: ("810001", "810002"),
1997: ("S00401", "S00402"),
2002: ("S00401", "S00402"),
}
tourism_adjustment_codes = {
1972: '830000',
1977: '830000',
1982: '830000',
1987: '830001',
1992: '830001',
1997: 'S00600',
2002: 'S00900',
}
nipa_groups = [
"Clothing and footwear",
"Financial services and insurance",
"Food and beverages purchased for off-premises consumption",
"Food services and accommodations",
"Furnishings and durable household equipment",
"Gasoline and other energy goods",
"Gross output of nonprofit institutions",
"Health care",
"Housing and utilities",
#"Less: Receipts from sales of goods and services by nonprofit institutions",
"Motor vehicles and parts",
"Other durable goods",
"Other nondurable goods",
"Other services",
"Recreational goods and vehicles",
"Recreation services",
"Transportation services",
]
short_nipa = {
"Clothing and footwear": "Apparel",
"Financial services and insurance": "Financial services",
"Food and beverages purchased for off-premises consumption": "Food products",
"Food services and accommodations": "Food services",
"Gasoline and other energy goods": "Gasoline",
"Other durable goods": "Other durables",
"Other nondurable goods": "Other nondurables",
"Transportation services": "Transport",
"Housing and utilities": "Utilities",
}
standard_sectors = {
1972: ('540200'),
1977: ('540200'),
1982: ('540200'),
1987: ('540200'),
1992: ('540200'),
1997: ('335222'),
2002: ('335222'),
}
|
class FieldOffsetAttribute(Attribute,_Attribute):
"""
Indicates the physical position of fields within the unmanaged representation of a class or structure.
FieldOffsetAttribute(offset: int)
"""
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,offset):
""" __new__(cls: type,offset: int) """
pass
Value=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the offset from the beginning of the structure to the beginning of the field.
Get: Value(self: FieldOffsetAttribute) -> int
"""
|
config_object = {
"org_id": "",
"client_id": "",
"tech_id": "",
"pathToKey": "",
"secret": "",
"date_limit": 0,
"token": "",
"tokenEndpoint": "https://ims-na1.adobelogin.com/ims/exchange/jwt"
}
header = {"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": "Bearer ",
"x-api-key": ""
}
endpoints = {
"global": 'https://cja.adobe.io'
}
|
INITIAL_HPS = {
'image_classifier': [{
'image_block_1/block_type': 'vanilla',
'image_block_1/normalize': True,
'image_block_1/augment': False,
'image_block_1_vanilla/kernel_size': 3,
'image_block_1_vanilla/num_blocks': 1,
'image_block_1_vanilla/separable': False,
'image_block_1_vanilla/dropout_rate': 0.25,
'image_block_1_vanilla/filters_0_1': 32,
'image_block_1_vanilla/filters_0_2': 64,
'spatial_reduction_1/reduction_type': 'flatten',
'dense_block_1/num_layers': 1,
'dense_block_1/use_batchnorm': False,
'dense_block_1/dropout_rate': 0,
'dense_block_1/units_0': 128,
'classification_head_1/dropout_rate': 0.5,
'optimizer': 'adam'
}, {
'image_block_1/block_type': 'resnet',
'image_block_1/normalize': True,
'image_block_1/augment': True,
'image_block_1_resnet/version': 'v2',
'image_block_1_resnet/pooling': 'avg',
'image_block_1_resnet/conv3_depth': 4,
'image_block_1_resnet/conv4_depth': 6,
'dense_block_1/num_layers': 2,
'dense_block_1/use_batchnorm': False,
'dense_block_1/dropout_rate': 0,
'dense_block_1/units_0': 32,
'dense_block_1/units_1': 32,
'classification_head_1/dropout_rate': 0,
'optimizer': 'adam'
}],
}
|
file = open('names.txt', 'w')
file.write('amirreza\n')
file.write('setayesh\n')
file.write('artin\n')
file.write('iliya\n')
file.write('mohammadjavad\n')
file.close()
|
CAPACITY = 10
class Heap:
def __init__(self):
self.heap_size = 0
self.heap = [0]*CAPACITY
def insert(self, item):
# when heap is full
if self.heap_size == CAPACITY:
return
self.heap[self.heap_size] = item
self.heap_size += 1
# check heap properties
self.fix_heap(self.heap_size-1)
# starting with actual node inserted to root node, compare values for swap operations-> log(N) operations, O(log(N))
def fix_heap(self, index):
# for node with index i, left child has index = 2i+1, right child has index 2i+2
# hence, reverse the eqn-> l = 2i+1, r = 2i+2-> i=l-1/2
parent_index = (index - 1)//2
# now consider all items above til root node, if heap prop is violated then swap parent with child
if index > 0 and self.heap[index] > self.heap[parent_index]:
self.heap[index], self.heap[parent_index] = self.heap[parent_index], self.heap[index]
self.fix_heap(parent_index)
def get_max_item(self):
return self.heap[0]
# return the max element and remove it from the heap
def poll_heap(self):
max_item = self.get_max_item()
# swap the root with the last item
self.heap[0], self.heap[self.heap_size-1] = self.heap[self.heap_size-1], self.heap[0]
self.heap_size -= 1
# now perform heapify operation
self.heapify(0)
return max_item
# start from root node and rearrange heap to make sure heap properties are not violated, O(log(N))
def heapify(self, index):
index_left = 2 * index + 1
index_right = 2 * index + 2
largest_index = index
# look for the largest(parent or left node)
if index_left < self.heap_size and self.heap[index_left] > self.heap[index]:
largest_index = index_left
# if right child > left child, then largest_index = right child
if index_right < self.heap_size and self.heap[index_right] > self.heap[index]:
largest_index = index_right
# If parent larger than child: it is valid heap and we terminate all recursive calls further
if index != largest_index:
self.heap[index], self.heap[largest_index] = self.heap[largest_index], self.heap[index]
self.heapify(largest_index)
# O(Nlog(N)) -> N items and O(logN) for poll_heap operation
def heap_sort(self):
for _ in range(self.heap_size):
max_item = self.poll_heap()
print(max_item)
if __name__ == "__main__":
heap = Heap()
heap.insert(13)
heap.insert(-2)
heap.insert(0)
heap.insert(8)
heap.insert(1)
heap.insert(-5)
heap.insert(99)
heap.insert(100)
print(heap.heap)
print("----------------------------")
heap.heap_sort()
|
src = Split('''
ota_service.c
ota_util.c
ota_update_manifest.c
ota_version.c
''')
component = aos_component('fota', src)
dependencis = Split('''
framework/fota/platform
framework/fota/download
utility/digest_algorithm
utility/cjson
''')
for i in dependencis:
component.add_comp_deps(i)
component.add_global_includes('.')
component.add_global_macros('AOS_FOTA')
|
# Works only with a good seed
# You need the Emperor's gloves to cast "Chain Lightning"
hero.cast("chain-lightning", hero.findNearestEnemy())
|
# 这个代码写的很烂 周末总是不想解决问题 三层嵌套 脑子就不够用了
class Solution:
def addParenthesis(self, str): # 为字符串新增一对括号
b_l = []
for idx, s in enumerate(str):
if s != '(': # 新添加左括号
left_str = str[:idx] + '('
right_str = str[idx:]
for idx_2, s_2 in enumerate(right_str):
if s_2 != ')':
b_l.append(left_str + right_str[:idx_2] + ')' + right_str[idx_2:])
b_l.append(left_str + right_str + ')')
b_l.append(str + '()')
return b_l
def addNewParenthesis(self, pre): # 为列表新增一对括号啊
b_l = []
for i in pre:
b_l += self.addParenthesis(i)
return b_l
def generateParenthesis(self, n): # 新增n 对括号
if n == 0:
return []
if n == 1:
return ["()"]
b_l = ["()"]
n = n - 1
for i in range(n): # 需要新增的n对括号
b_l = self.addNewParenthesis(b_l)
r_l = []
dict = {}
for r in b_l:
if r not in dict:
r_l.append(r)
dict[r] = r
return r_l
slu = Solution()
print(slu.generateParenthesis(3))
|
def main():
rst = bf_cal()
print(f"{rst[0]}^5 + {rst[1]}^5 + {rst[2]}^5 + {rst[3]}^5 = {rst[4]}^5")
def bf_cal():
max_n = 250
pwr_pool = [n ** 5 for n in range(max_n)]
y_pwr_pool = {n ** 5: n for n in range(max_n)}
for x0 in range(1, max_n):
print(f"processing {x0} in (0..250)")
for x1 in range(x0, max_n):
for x2 in range(x1, max_n):
for x3 in range(x2, max_n):
y_pwr5 = sum(pwr_pool[i] for i in (x0, x1, x2, x3))
if y_pwr5 in y_pwr_pool:
y = y_pwr_pool[y_pwr5]
if y not in (x0, x1, x2, x3):
return x0, x1, x2, x3, y
if __name__ == "__main__":
main()
# 27^5 + 84^5 + 110^5 + 133^5 = 144^5
|
sq_sum, sum = 0, 0
for i in range(1, 101):
sq_sum = sq_sum + (i * i)
sum = sum + i
print((sum * sum) - sq_sum)
|
class NotFoundException(Exception):
pass
class BadRequestException(Exception):
pass
class JobExistsException(Exception):
pass
class NoSuchImportableDataset(Exception):
pass
|
class User:
def __init__(self, id, password, github_username, github_obj=None):
self.id = id
self.password = password
self.github_username = github_username
self.github_obj = github_obj
class File:
def __init__(self, fullname, name, last_commit_sha, repo_fullname, sha, github_obj=None, content=None):
self.fullname = fullname
self.name = name
self.last_commit_sha = last_commit_sha
self.repo_fullname = repo_fullname
self.sha = sha
self.github_obj = github_obj
self.content = content # special value (db에 포함되지 않음)
class Repository:
def __init__(self, fullname, name, last_commit_date, last_commit_sha, owner, github_obj=None):
self.fullname = fullname
self.name = name
self.last_commit_date = last_commit_date
self.last_commit_sha = last_commit_sha
self.owner = owner
self.github_obj = github_obj
self.upstream_repo = None
def update_file(self, file: File, title: str, content: str, branch: str):
assert self.github_obj
# 파일 업데이트 실행
result = self.github_obj.update_file(file.fullname, title, content, sha=file.sha, branch=branch)
commit = result['commit']
content_file = result['content']
# 파일 정보 업데이트
file.sha = content_file.sha
file.last_commit_sha = commit.sha
file.content = content
def create_file(self, file_fullname: str, title: str, content: str, branch: str):
assert self.github_obj
# 파일 생성
result = self.github_obj.create_file(file_fullname, title, content, branch=branch)
commit = result['commit']
content_file = result['content']
# 파일 객체 생성
new_file = File(
fullname=file_fullname,
name=content_file.name,
last_commit_sha=commit.sha,
repo_fullname=self.fullname,
sha=content_file.sha,
content=content)
return new_file
class SecretKey:
def __init__(self, y, x, file_fullname, file_commit_sha, content, repo_last_commit_sha=None, pull_num=0, github_obj=None):
self.y = y
self.x = x
self.file_fullname = file_fullname
self.file_commit_sha = file_commit_sha
self.content = content
self.github_obj = github_obj
self.repo_last_commit_sha = repo_last_commit_sha
self.pull_num = pull_num
|
# 3. В гравця є 100 одиниць HP (health points). В грі є 3 монстра: скелет, зомбі, павук.
# Кожен з них наносить певний damage (урон) гравцю.
# Перевірити чи помре гравець після 5 ударів зомбі, 1 удару скелету та 2 укусів павука,
# якщо урон скелета = 15, зомбі = 5, павука = 40. Вивести повідомлення “You die!” якщо гравець помер,
# або “You have only {HP}” якщо він вижив, де HP - залишок здоров’я.
health_points =100
skeleton_damage=15
zombie_damage=5
spider_damage=40
if health_points > (5*zombie_damage+skeleton_damage+2*spider_damage):
print ("You have only ",health_points -(5*zombie_damage+skeleton_damage+2*spider_damage), "{HP}")
else:
print ("You die!")
|
#!/usr/bin/python3
"""
This module provides feedback control for motors
So far a PID controller......
"""
class PIDfeedback():
"""
This class can be used as part of a dc motor controller. It provides feedback control using a PID controller
(https://en.wikipedia.org/wiki/PID_controller)
It handles only the error value, the calling software works out what the error is to allow it to be calculated in
or measured in different ways.
This is a pretty trivial class so far
"""
def __init__(self, timenow, Pfact, Ifact, Dfact):
"""
timenow : timestamp of initial reading / setup
Pfact : Proportion factor
Ifact : Integral factor
Dfact : Derivative (slope) factor
"""
self.timeprev = timenow
self.timestart = timenow
self.errorprev = 0
self.errortotal= 0
self.Pfact = Pfact
self.Ifact = Ifact
self.Dfact = Dfact
def reset(self, timenow, errornow):
"""
simple reset function to save having to discard and recreate an instance
"""
self.timeprev = timenow
self.timestart = timenow
self.errorprev = 0
self.errortotal= 0
def factors(self, Pfact=None, Ifact=None, Dfact=None):
"""
set and return any combination of the factors
Any parameter not None will update that factor to the supplied Value.
return a 3-tuple of the values
"""
if not Pfact is None:
self.Pfact=Pfact
if not Ifact is None:
self.Ifact=Pfact
if not Dfact is None:
self.Dfact=Pfact
return self.Pfact, self.Ifact, self.Dfact
def onefact(self, factor, newvalue):
"""
set and return a single factor
factor : 'P', 'I', or 'D'
value : None to just return the current value, or an integer or float to set and return the new value
"""
assert newvalue is None or isinstance(newvalue,(int, float, str)), 'Value is not a number'
value = float(newvalue) if isinstance(newvalue, str) else newvalue
if factor=='P':
if not value is None:
self.Pfact=value
return self.Pfact
elif factor=='I':
if not value is None:
self.Ifact=value
return self.Ifact
elif factor=='D':
if not value is None:
self.Dfact=='D'
return self.Dfact
else:
raise ValueError('factor should be "P", "I" or "D"; not %S' % str(factor))
def ticker(self, timenow, errornow):
"""
called on a regular basis, this calculates the correction factor to be applied.
as long as ticks are regular we don't need to use the time as part of the slope calculation,
timenow : time at which the position was measured
errornow : the absolute error at that time - note this is the error in position, not the error in velocity
"""
lastinterval = timenow-self.timeprev
slope = errornow-self.errorprev
self.errortotal += errornow
self.errorprev = errornow
self.timeprev = timenow
return self.Pfact*errornow + self.Ifact*self.errortotal + self.Dfact*slope
def odef(self):
return {'className': type(self).__name__, 'Pfact': self.Pfact, 'Ifact': self.Ifact, 'Dfact': self.Dfact}
|
def lin(num=60):
print('_' * num)
def write(txt):
lin()
print(f'{txt:^60}')
lin()
def readInt(txt):
while True:
try:
num = int(input(txt))
except:
print('\033[31mErro! Digite um numero valido\033[m')
else:
break
return num
def menu(lista):
i = 0
write('Menu')
for c in lista:
i += 1
print(f'\033[33m{i} - \033[34m{c}\033[m')
lin()
opc = readInt('\033[33mSua opção:\033[m ')
return opc
|
n = int(input('Enter A Number: '))
def findFactors(num):
arr = []
for x in range(1, n + 1 ,1):
if num % x == 0:
arr.append(x)
return arr
if len(findFactors(n)) == 2: # Array will have 1 and the number itself
print(f"{n} Is Prime.")
else :
print(f"{n} Is Composite")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.