content stringlengths 7 1.05M |
|---|
#analysis function for three level game
def stat_analysis(c1,c2,c3):
#ask question for viewing analysis of game
analysis=input('\nDo you want to see your game analysis? (Yes/No) ')
if analysis=='Yes':
levels=['Level 1','Level 2','Level 3']
#calculating the score of levels
l... |
# -*- coding: utf-8 -*-
__author__ = """Hendrix Demers"""
__email__ = 'hendrix.demers@mail.mcgill.ca'
__version__ = '0.1.0'
|
#!/usr/bin/env python3
def date_time(time):
months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"]
hour, minute = int(time[11:13]), int(time[14:16])
return f"{int(time[0:2])} {months[int(time[3:5])-1]} {time[6:10]} year {h... |
item1='phone'
item1_price = 100
item1_quantity = 5
item1_price_total = item1_price * item1_quantity
print(type(item1)) # str
print(type(item1_price)) # int
print(type(item1_quantity)) # int
print(type(item1_price_total)) # int
# output:
# <class 'str'>
# <class 'int'>
# ... |
a = int(input())
while a:
for x in range(a-1):
out = '*' + ' ' * (a-x-2) + '*' + ' ' * (a-x-2) + '*'
print(out.center(2*a-1))
print('*' * (2 * a - 1))
for x in range(a-1):
out = '*' + ' ' * x + '*' + ' ' * x + '*'
print(out.center(2*a-1))
a = int(input())
|
class Dataset:
_data = None
_first_text_col = 'text'
_second_text_col = None
_label_col = 'label'
def __init__(self):
self._idx = 0
if self._data is None:
raise Exception('Dataset is not loaded')
def __iter__(self):
return self
def __next__(self):
... |
"Actions for compiling resx files"
load(
"@io_bazel_rules_dotnet//dotnet/private:providers.bzl",
"DotnetResourceInfo",
)
def _make_runner_arglist(dotnet, source, output, resgen):
args = dotnet.actions.args()
if type(source) == "Target":
args.add_all(source.files)
else:
args.add(so... |
class OCDSMergeError(Exception):
"""Base class for exceptions from within this package"""
class MissingDateKeyError(OCDSMergeError, KeyError):
"""Raised when a release is missing a 'date' key"""
def __init__(self, key, message):
self.key = key
self.message = message
def __str__(self)... |
n=int(input("Enter number "))
fact=1
for i in range(1,n+1):
fact=fact*i
print("Factorial is ",fact)
|
# Fractional Knapsack
wt = [40,50,30,10,10,40,30]
pro = [30,20,20,25,5,35,15]
n = len(wt)
data = [ (i,pro[i],wt[i]) for i in range(n) ]
bag = 100
data.sort(key=lambda x: x[1]/x[2], reverse=True)
profit=0
ans=[]
i=0
while i<n:
if data[i][2]<=bag:
bag-=data[i][2]
ans.append(data[i... |
class DeviceSettings:
def __init__(self, settings):
self._id = settings["id"]
self._title = settings["title"]
self._type = settings["type"]["name"]
self._value = settings["value"]
@property
def id(self):
return self._id
@property
def value(self):
ret... |
word = input("Enter a word: ")
if word == "a":
print("one; any")
elif word == "apple":
print("familiar, round fleshy fruit")
elif word == "rhinoceros":
print("large thick-skinned animal with one or two horns on its nose")
else:
print("That word must not exist. This dictionary is very comprehensive.")
|
cnt = int(input())
num = list(map(int, input()))
sum = 0
for i in range(len(num)):
sum = sum + num[i]
print(sum) |
def test_xrange(judge_command):
judge_command(
"XRANGE somestream - +",
{"command": "XRANGE", "key": "somestream", "stream_id": ["-", "+"]},
)
judge_command(
"XRANGE somestream 1526985054069 1526985055069",
{
"command": "XRANGE",
"key": "somestream",
... |
""":mod:`sider.warnings` --- Warning categories
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This module defines several custom warning category classes.
"""
class SiderWarning(Warning):
"""All warning classes used by Sider extend this base class."""
class PerformanceWarning(SiderWarning, RuntimeWarning):
... |
MEDIA_SEARCH = """
query ($search: String, $type: MediaType, $exclude: MediaFormat, $isAdult: Boolean) {
Media(search: $search, type: $type, format_not: $exclude, isAdult: $isAdult) {
id
type
format
title {
english
romaji
native
}
synonyms
status
description
start... |
def decode(word1,word2,code):
if len(word1)==1:
code+=word1+word2
return code
else:
code+=word1[0]+word2[0]
return decode(word1[1:],word2[1:],code)
Alice='Ti rga eoe esg o h ore"ermetsCmuainls'
Bob='hspormdcdsamsaefrtecus Hraina optcoae"'
print(decode(Alice,Bob,''))
|
# constants for configuration parameters of our tensorflow models
LABEL = "label"
IDS = "ids"
# LABEL_PAD_ID is used to pad multi-label training examples.
# It should be < 0 to avoid index out of bounds errors by tf.one_hot.
LABEL_PAD_ID = -1
HIDDEN_LAYERS_SIZES = "hidden_layers_sizes"
SHARE_HIDDEN_LAYERS = "share_hid... |
PROTO = {
'spaceone.monitoring.interface.grpc.v1.data_source': ['DataSource'],
'spaceone.monitoring.interface.grpc.v1.metric': ['Metric'],
'spaceone.monitoring.interface.grpc.v1.project_alert_config': ['ProjectAlertConfig'],
'spaceone.monitoring.interface.grpc.v1.escalation_policy': ['EscalationPolicy']... |
"""Ingredient dto.
"""
class Ingredient():
"""Class to represent an ingredient.
"""
def __init__(self, name, availability_per_month):
self.name = name
self.availability_per_month = availability_per_month
def __repr__(self):
return """{} is the name.""".format(self.name)
|
# -*- coding: utf-8 -*-
class Config(object):
def __init__(self):
self.init_scale = 0.1
self.learning_rate = 1.0
self.max_grad_norm = 5
self.num_layers = 2
self.slice_size = 30
self.hidden_size = 200
self.max_epoch = 13
self.keep_prob = 0.8
se... |
{
'targets': [
{
# have to specify 'liblib' here since gyp will remove the first one :\
'target_name': 'mysql_bindings',
'sources': [
'src/mysql_bindings.cc',
'src/mysql_bindings_connection.cc',
'src/mysql_bindings_result.cc',
'src/mysql_bindings_statement.cc',
... |
# TODO turn prints into actual error raise, they are print for testing
def qSystemInitErrors(init):
def newFunction(obj, **kwargs):
init(obj, **kwargs)
if obj._genericQSys__dimension is None:
className = obj.__class__.__name__
print(className + ' requires a dimension')
... |
""" some math tools """
class MathTools:
""" some math tools """
def add(a, b):
""" add two values """
return a + b
def sub(a, b):
""" subtract two values """
|
def insertion_sort(l):
for i in range(1, len(l)):
j = i - 1
key = l[i]
while (j >= 0) and (l[j] > key):
l[j + 1] = l[j]
j -= 1
l[j + 1] = key
m = int(input().strip())
ar = [int(i) for i in input().strip().split()]
insertion_sort(ar)
print(" ".join(map(str, a... |
age = 24
print("My age is " + str(age) + " years ")
# the above procedure is tedious since we dont really want to include str for every number we encounter
#Method1 Replacement Fields
print("My age is {0} years ".format(age)) # {0} is the actual replacement field, number important for multiple replacement fields
... |
def Euler0001():
max = 1000
sum = 0
for i in range(1, max):
if i%3 == 0 or i%5 == 0:
sum += i
print(sum)
Euler0001() |
"""
0461. Hamming Distance
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
0 ≤ x, y < 231.
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ... |
"""
Person class
"""
# Create a Person class with the following properties
# 1. name
# 2. age
# 3. social security number
class Person:
def __init__(self, name, age, social_number):
self.name = name
self.age = age
self.social = social_number
p1 = Person("John", 36, "111-11-1111")
print... |
"""
Module for higher level SharePoint REST api actions - utilize methods in the api.py module
"""
class Site():
def __init__(self, sp):
self.sp = sp
@property
def info(self):
endpoint = "_api/site"
value = self.sp.get(endpoint).json()
return value
@property
def w... |
# coding: utf8
{
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" é uma expressão opcional como "field1=\'newvalue\'". Não é possível atualizar ou excluir os resultados de uma junção',
'# of International Staff': '# De equipe internacional'... |
# BS mark.1-55
# /* coding: utf-8 */
# BlackSmith plugin
# everywhere_plugin.py
# Coded by: WitcherGeralt (WitcherGeralt@jabber.ru)
# http://witcher-team.ucoz.ru/
def handler_everywhere(type, source, body):
if body:
args = body.split()
if len(args) >= 2:
mtype = args[0].strip().lower()
if mtype == u'чат... |
n = int(input())
conf_set = []
for _ in range(n):
conf_set.append(tuple(map(int, input().split())))
conf_set.sort(key=lambda x : (x[1], x[0]))
# 끝나는 시간을 기준으로 정렬
# 시작과 종료가 같은 경우를 포함하기 위해선, 시작 시간도 오름차순으로 정렬해 줘야 한다
solution_list = [conf_set[0]]
# Greedy Algorithm
for conf in conf_set[1:]:
last_conf = solution... |
# 143. 重排链表
# 给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
# 将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
# 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
# 示例 1:
# 给定链表 1->2->3->4, 重新排列为 1->4->2->3.
# 示例 2:
# 给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# ... |
# Copyright 2019 The TensorFlow Probability Authors.
#
# 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 o... |
class Solution:
# @return a string
def convertToTitle(self, n: int) -> str:
capitals = [chr(x) for x in range(ord('A'), ord('Z')+1)]
result = []
while n > 0:
result.insert(0, capitals[(n-1)%len(capitals)])
n = (n-1) % len(capitals)
# result.reverse()
... |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
# Intermediate target grouping the android tools needed to run native
# unittests and instrumentation test apks.
{
'ta... |
# Factory-like class for mortgage options
class MortgageOptions:
def __init__(self,kind,**inputOptions):
self.set_default_options()
self.set_kind_options(kind = kind)
self.set_input_options(**inputOptions)
def set_default_options(self):
self.optionList = dict()
self.optionList['commonDefaul... |
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
# Copyright 2018 Google LLC
# Copyright 2018-present Open Networking Foundation
# SPDX-License-Identifier: Apache-2.0
"""A portable build system for Stratum P4 switch stack.
To use this, load() this file in a BUILD file, specifying the symbols needed.
The public symbols are the macros:
decorate(path)
sc_cc_lib ... |
__all__ = (
"Role",
)
class Role:
def __init__(self, data):
self.data = data
self._update(data)
def _get_json(self):
return self.data
def __repr__(self):
return (
f"<Role id={self.id} name={self.name}>"
)
def __str__(self):
... |
_Msun_kpc3_to_GeV_cm3_factor = 0.3/8.0e6
def Msun_kpc3_to_GeV_cm3(value):
return value*_Msun_kpc3_to_GeV_cm3_factor
|
class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if not nums: return
n = len(nums)-1
while n > 0 and nums[n-1] >= nums[n]:
n -= 1
t = n... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""recumpiler
Recompile text to be semi-readable memey garbage.
"""
__version__ = (0, 0, 0)
|
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'chromium_code': 1,
'linux_link_kerberos%': 0,
'conditions': [
['chromeos==1 or OS=="android" or OS=="ios"', {
... |
"""
Defines two dictionaries for converting
between text and integer sequences.
"""
char_map_str = """
' 0
<SPACE> 1
ব 2
া 3
ং 4
ল 5
দ 6
ে 7
শ 8
য 9
় 10
ি 11
ত 12
্ 13
ন 14
এ 15
ধ 16
র 17
ণ 18
ক 19
ড 20
হ 21
উ 22
প 23
জ 24
অ 25
থ 26
স 27
ষ 28
ই 29
আ 30
ছ 31
গ 32
ু 33
ো 34
ও 35
ভ 36
ী 37
ট 38
ূ 39
ম 40
ৈ 41
ৃ 42
ঙ 4... |
#Author Theodosis Paidakis
print("Hello World")
hello_list = ["Hello World"]
print(hello_list[0])
for i in hello_list:
print(i) |
# Book04_1.py
class Book:
category = '소설' # Class 멤버
b1 = Book(); print(b1.category)
b2 = b1; print(b2.category)
print(Book.category)
Book.category = '수필'
print(b2.category); print(b1.category) ; print(Book.category)
b2.category = 'IT'
print(b2.category); print(b1.category) ; print(Book.category) |
print('Digite seu nome completo: ')
nome = input().strip().upper()
print('Seu nome tem "Silva"?')
print('SILVA' in nome)
|
dataset_type = 'STVQADATASET'
data_root = '/home/datasets/mix_data/iMIX/'
feature_path = 'data/datasets/stvqa/defaults/features/'
ocr_feature_path = 'data/datasets/stvqa/defaults/ocr_features/'
annotation_path = 'data/datasets/stvqa/defaults/annotations/'
vocab_path = 'data/datasets/stvqa/defaults/extras/vocabs/'
trai... |
""" Module docstring """
def _impl(_ctx):
""" Function docstring """
pass
some_rule = rule(
attrs = {
"attr1": attr.int(
default = 2,
mandatory = False,
),
"attr2": 5,
},
implementation = _impl,
)
|
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: I am
#
# Created: 02/11/2017
# Copyright: (c) I am 2017
# Licence: <your licence>
#-------------------------------------------------------------------------------
def main():
... |
matrix = [list(map(int, input().split())) for _ in range(6)]
max_sum = None
for i in range(4):
for j in range(4):
s = sum(matrix[i][j:j+3]) + matrix[i+1][j+1] + sum(matrix[i+2][j:j+3])
if max_sum is None or s > max_sum:
max_sum = s
print(max_sum)
|
class Bunch(dict):
"""Container object exposing keys as attributes.
Bunch objects are sometimes used as an output for functions and methods.
They extend dictionaries by enabling values to be accessed by key,
`bunch["value_key"]`, or by an attribute, `bunch.value_key`.
Examples
--------
>>>... |
pessoas = {'nomes': "Rafael","sexo":"macho alfa","idade":19}
print(f"o {pessoas['nomes']} que se considera um {pessoas['sexo']} possui {pessoas['idade']}")
print(pessoas.keys())
print(pessoas.values())
print(pessoas.items())
for c in pessoas.keys():
print(c)
for c in pessoas.values():
print(c)
for c, j in pe... |
config = {
"Luminosity": 1000,
"InputDirectory": "results",
"Histograms" : {
"WtMass" : {},
"etmiss" : {},
"lep_n" : {},
"lep_pt" : {},
"lep_eta" : {},
"lep_E" : {},
"lep_phi" : {"y_margin" : 0.6},
"lep_... |
"""
Determine the number of bits required to convert integer A to integer B
Example
Given n = 31, m = 14,return 2
(31)10=(11111)2
(14)10=(01110)2
"""
__author__ = 'Danyang'
class Solution:
def bitSwapRequired(self, a, b):
"""
:param a:
:param b:
:return: int
"""
... |
# Desempacotamento de parametros em funcoes
# somando valores de uma tupla
def soma(*num):
soma = 0
print('Tupla: {}' .format(num))
for i in num:
soma += i
return soma
# Programa principal
print('Resultado: {}\n' .format(soma(1, 2)))
print('Resultado: {}\n' .format(soma(1, 2, 3, 4, 5, 6, 7, 8,... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
temp = head
array = []
while temp:
a... |
DATABASE_OPTIONS = {
'database': 'klazor',
'user': 'root',
'password': '',
'charset': 'utf8mb4',
}
HOSTS = ['127.0.0.1', '67.209.115.211']
|
"""
Django settings.
Generated by 'django-admin startproject' using Django 2.2.4.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
#DEBUG = False
DEBUG = True
SERV... |
def HAHA():
return 1,2,3
a = HAHA()
print(a)
print(a[0])
|
ser = int(input())
mas = list(map(int, input().split()))
mas.sort()
print(*mas)
|
backgroundurl = "https://storage.needpix.com/rsynced_images/colored-background.jpg" # <- Need to be a Image URL!!!
lang = "en" # <- language code
displayset = True # <- Display the Set of the Item
raritytext = True # <- Display the Rarity of the Item
typeconfig = {
"BannerToken": True,
"AthenaBackpack":... |
def get_season_things_price(thing, amount, price):
if thing == 'wheel':
wheel_price = price[thing]['month'] * amount
return f'Стоимость составит {wheel_price}/месяц'
else:
other_thing_price_week = price[thing]['week'] * amount
other_thing_price_month = price[thing]['month'] * a... |
def cube(number):
return number*number*number
digit = input(" the cube of which digit do you want >")
result = cube(int(digit))
print(result)
|
def main(request, response):
headers = [("Content-type", "text/html;charset=shift-jis")]
# Shift-JIS bytes for katakana TE SU TO ('test')
content = chr(0x83) + chr(0x65) + chr(0x83) + chr(0x58) + chr(0x83) + chr(0x67);
return headers, content
|
# Vicfred
# https://atcoder.jp/contests/abc132/tasks/abc132_a
# implementation
S = list(input())
if len(set(S)) == 2:
if S.count(S[0]) == 2:
print("Yes")
quit()
print("No")
|
for _ in range(int(input())):
x, y = list(map(int, input().split()))
flag = 1
for i in range(x, y + 1):
n = i * i + i + 41
for j in range(2, n):
if j * j > n:
break
if n % j == 0:
flag = 0
break
if flag == 0:
break
if flag:
print("OK")
else:
print("Sorry") |
{
'targets': [
{
'target_name': 'hiredis',
'sources': [
'src/hiredis.cc'
, 'src/reader.cc'
],
'include_dirs': ["<!(node -e \"require('nan')\")"],
'dependencies': [
'deps/hiredis.gyp:hiredis-c'
],
'defines': [
'_GNU_SOURCE'
],
... |
class CoinArray(list):
"""
Coin list that is hashable for storage in sets
The 8 entries are [1p count, 2p count, 5p count, ... , 200p count]
"""
def __hash__(self):
"""
Hash this as a string
"""
return hash(" ".join([str(i) for i in self]))
def main():
"""
En... |
# -*- coding: utf-8 -*-
"""
@Time : 2021/10/9 17:51
@Auth : 潇湘
@File :__init__.py.py
@IDE :PyCharm
@QQ : 810400085
""" |
#!/usr/bin/env python3
"""
Build a table of Python / Pydantic to JSON Schema mappings.
Done like this rather than as a raw rst table to make future edits easier.
Please edit this file directly not .tmp_schema_mappings.rst
"""
table = [
[
'bool',
'boolean',
'',
'JSON Schema Core',
... |
# mako/__init__.py
# Copyright (C) 2006-2016 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
__version__ = '1.0.9'
|
def sort(data, time):
tt = False
ft = True
st = False
is_find = True
winers_name = set()
index = 0
while is_find:
index += 1
for key, values in data.items():
if time[0 - index] == int(values[1]) and ft and values[0] not in winers_name:
first_id = k... |
def pick_food(name):
if name == "chima":
return "chicken"
else:
return "dry food"
|
hasGoodCredit = True
price = 1000000
deposit = 0
if hasGoodCredit:
deposit = price/10
else:
deposit = price/5
print(f"Deposit needed: £{deposit}") |
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
#Author:贾江超
def spin_words(sentence):
list1=sentence.split()
l=len(list1)
for i in range(l):
relen = len(sentence.split()[i:][0])
if relen > 5:
list1[i]=list1[i][::-1]
return ' '.join(list1)
'''
注意 在2.x版本可以用len()得到list的长度 3.x版本就不行... |
# Creating a elif chain
alien_color = 'red'
if alien_color == 'green':
print('Congratulations! You won 5 points!')
elif alien_color == 'yellow':
print('Congratulations! You won 10 points!')
elif alien_color == 'red':
print('Congratulations! You won 15 points!')
|
# https://www.codechef.com/START8C/problems/PENALTY
for T in range(int(input())):
n=list(map(int,input().split()))
a=b=0
for i in range(len(n)):
if(n[i]==1):
if(i%2==0): a+=1
else: b+=1
if(a>b): print(1)
elif(b>a): print(2)
else: print(0) |
MATH_BYTECODE = (
"606060405261022e806100126000396000f360606040523615610074576000357c01000000000000"
"000000000000000000000000000000000000000000009004806316216f391461007657806361bc22"
"1a146100995780637cf5dab0146100bc578063a5f3c23b146100e8578063d09de08a1461011d5780"
"63dcf537b11461014057610074565b... |
def modify(y):
return y # returns same reference. No new object is created
x = [1, 2, 3]
y = modify(x)
print("x == y", x == y)
print("x == y", x is y) |
# 1. Create students score dictionary.
students_score = {}
# 2. Input student's name and check if input is correct. (Alphabet, period, and blank only.)
# 2.1 Creat a function that evaluate the validity of name.
def check_name(name):
# 2.1.1 Remove period and blank and check it if the name is comprised with on... |
#$Id$
class Instrumentation:
"""This class is used tocreate object for instrumentation."""
def __init__(self):
"""Initialize parameters for Instrumentation object."""
self.query_execution_time = ''
self.request_handling_time = ''
self.response_write_time = ''
self.page_c... |
load("@rules_jvm_external//:defs.bzl", "artifact")
# For more information see
# - https://github.com/bmuschko/bazel-examples/blob/master/java/junit5-test/BUILD
# - https://github.com/salesforce/bazel-maven-proxy/tree/master/tools/junit5
# - https://github.com/junit-team/junit5-samples/tree/master/junit5-jupiter-starte... |
# This module provides mocked versions of classes and functions provided
# by Carla in our runtime environment.
class Location(object):
""" A mock class for carla.Location. """
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
class Rotation(object):
""" A mock class... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
ee = '\033[1m'
green = '\033[32m'
yellow = '\033[33m'
cyan = '\033[36m'
line = cyan+'-' * 0x2D
print(ee+line)
R,G,B = [float(X) / 0xFF for X in input(f'{yellow}RGB: {green}').split()]
K = 1-max(R,G,B)
C,M,Y = [round(float((1-X-K)/(1-K) * 0x64),1) for X in [R,G,B]]
K = r... |
def selection_sort(A): # O(n^2)
n = len(A)
for i in range(n-1): # percorre a lista
min = i
for j in range(i+1, n): # encontra o menor elemento da lista a partir de i + 1
if A[j] < A[min]:
min = j
A[i], A[min] = A[min], A[i] # insere o elemento na posicao corre... |
tajniBroj = 51
broj = 2
while tajniBroj != broj:
broj = int(input("Pogodite tajni broj: "))
if tajniBroj == broj:
print("Pogodak!")
elif tajniBroj < broj:
print("Tajni broj je manji od tog broja.")
else:
print("Tajni broj je veci od tog broja.")
print("Kraj programa")
|
# Copyright ©2020-2021 The American University in Cairo and the Cloud V Project.
#
# This file is part of the DFFRAM Memory Compiler.
# See https://github.com/Cloud-V/DFFRAM for further info.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Li... |
class CoinbaseResponse:
bid = 0
ask = 0
product_id = None
def set_bid(self, bid):
self.bid = float(bid)
def get_bid(self):
return self.bid
def set_ask(self, ask):
self.ask = float(ask)
def get_ask(self):
return self.ask
def get_product_id(self):
... |
'''
Problem description:
Given a string, determine whether or not the parentheses are balanced
'''
def balanced_parens(str):
'''
runtime: O(n)
space : O(1)
'''
if str is None:
return True
open_count = 0
for char in str:
if char == '(':
open_count += 1
... |
#!/usr/bin/env python3
# Coded by Massimiliano Tomassoli, 2012.
#
# - Thanks to b49P23TIvg for suggesting that I should use a set operation
# instead of repeated membership tests.
# - Thanks to Ian Kelly for pointing out that
# - "minArgs = None" is better than "minArgs = -1",
# - "if args" is better than ... |
greeting = """
--------------- BEGIN SESSION ---------------
You have connected to a chat server. Welcome!
:: About
Chat is a small piece of server software
written by Evan Pratten to allow people to
talk to eachother from any computer as long
as it has an internet connection. (Even an
arduino!). Check out the proje... |
# 13. Join
# it allows to print list a bit better
friends = ['Pythobit','boy','Pythoman']
print(f'My friends are {friends}.') # Output - My friends are ['Pythobit', 'boy', 'Pythoman'].
# So, the Output needs to be a bit clearer.
friends = ['Pythobit','boy','Pythoman']
friend = ', '.join(friends)
print(f'My friend... |
# settings file for builds.
# if you want to have custom builds, copy this file to "localbuildsettings.py" and make changes there.
# possible fields:
# resourceBaseUrl - optional - the URL base for external resources (all resources embedded in standard IITC)
# distUrlBase - optional - the base URL to use for update c... |
class Point3D:
def __init__(self,x,y,z):
self.x = x
self.y = y
self.z = z
'''
Returns the distance between two 3D points
'''
def distance(self, value):
return abs(self.x - value.x) + abs(self.y - value.y) + abs(self.z - value.z)
def __eq__(self, value):
... |
# API keys
# YF_API_KEY = "YRVHVLiFAt3ANYZf00BXr2LHNfZcgKzdWVmsZ9Xi" # yahoo finance api key
TICKER = "TSLA"
INTERVAL = "1m"
PERIOD = "1d"
LOOK_BACK = 30 # hard limit to not reach rate limit of 100 per day |
FILE = r'../src/etc-hosts.txt'
hostnames = []
try:
with open(FILE, encoding='utf-8') as file:
content = file.readlines()
except FileNotFoundError:
print('File does not exist')
except PermissionError:
print('Permission denied')
for line in content:
if line.startswith('#'):
continue
... |
def n_subimissions_per_day( url, headers ):
"""Get the number of submissions we can make per day for the selected challenge.
Parameters
----------
url : {'prize', 'points', 'knowledge' , 'all'}, default='all'
The reward of the challenges for top challengers.
headers : dictionary ,
T... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.