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 ac... |
"""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(' ')
un... |
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>\
... |
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... |
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):
retur... |
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 ... |
"""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.... |
"""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(... |
#!/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 req... |
"""
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):
# m... |
'''
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 enco... |
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:
... |
#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.app... |
# ------------------------------
# 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,... |
"""
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... |
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... |
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:
... |
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 != "f... |
'''
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': "Overvi... |
"""
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 :... |
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 = va... |
'''
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 ... |
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... |
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,
#... |
# 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 di... |
"""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 ... |
# 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/departuredel... |
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 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
... |
#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
... |
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):
... |
#!/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.c... |
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 infor... |
"""
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... |
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_numb... |
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: "))
... |
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):
re... |
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, 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 * ... |
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):
... |
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 d... |
#!/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_ar... |
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.devi... |
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
o... |
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:
... |
# 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^... |
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 {l... |
#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) ... |
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... |
"""
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.
... |
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:
... |
'''
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=""
... |
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('... |
# -*- 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(... |
'''
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... |
"""
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... |
"""
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 ... |
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... |
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.__ini... |
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",
... |
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,
... |
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
... |
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_d... |
# 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(ri... |
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)")
... |
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.... |
# 3. В гравця є 100 одиниць HP (health points). В грі є 3 монстра: скелет, зомбі, павук.
# Кожен з них наносить певний damage (урон) гравцю.
# Перевірити чи помре гравець після 5 ударів зомбі, 1 удару скелету та 2 укусів павука,
# якщо урон скелета = 15, зомбі = 5, павука = 40. Вивести повідомлення “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 ha... |
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 men... |
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.