content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# -*- coding: utf-8 -*-
"""
Event Module - Controllers
"""
module = request.controller
resourcename = request.function
# Options Menu (available in all Functions' Views)
shn_menu(module)
# -----------------------------------------------------------------------------
def index():
""" Module's Home Page """
... | """
Event Module - Controllers
"""
module = request.controller
resourcename = request.function
shn_menu(module)
def index():
""" Module's Home Page """
module_name = deployment_settings.modules[module].name_nice
response.title = module_name
return dict(module_name=module_name)
def create():
""... |
class NonTerminal:
def __init__(self, name, productions):
# Creates an instance of a NonTerminal that represents a set of
# grammar productions for a non-terminal.
#
# Keyword arguments:
# name -- the name of the non-terminal
# productions -- a list whose elements can... | class Nonterminal:
def __init__(self, name, productions):
self.name = name
self.productions = [x.split() if isinstance(x, str) else x for x in productions]
def __repr__(self):
return 'NonTerminal(' + repr(self.name) + ')'
def __str__(self):
return self.name
def string... |
params_scenario = {
"n_agents_arrival": 1,
"p_split_threshold": int(1e10),
"r_t": 100,
"r_f": 100,
"gamma": 0, # 0
}
| params_scenario = {'n_agents_arrival': 1, 'p_split_threshold': int(10000000000.0), 'r_t': 100, 'r_f': 100, 'gamma': 0} |
#
# PySNMP MIB module ENTERASYS-POLICY-PROFILE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ENTERASYS-POLICY-PROFILE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:04:18 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python vers... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, value_size_constraint, constraints_intersection, single_value_constraint) ... |
# -*- coding: utf-8 -*-
"""Top-level package for Scopes."""
__author__ = """Louis Garman"""
__email__ = 'louisgarman@gmail.com'
__version__ = '0.1.1'
| """Top-level package for Scopes."""
__author__ = 'Louis Garman'
__email__ = 'louisgarman@gmail.com'
__version__ = '0.1.1' |
"""
def generate_list_books(filename):
book_list = []
file_in = open(filename, encoding='utf-8', errors='replace')
file_in.readline()
for line in file_in:
line = line.strip().split(",")
line[2] = float(line[2])
line[3] = int(line[3])
line[4] = int(line[4])
lin... | """
def generate_list_books(filename):
book_list = []
file_in = open(filename, encoding='utf-8', errors='replace')
file_in.readline()
for line in file_in:
line = line.strip().split(",")
line[2] = float(line[2])
line[3] = int(line[3])
line[4] = int(line[4])
lin... |
#First Example - try changing the value of phone_balance
phone_balance = 10
bank_balance = 50
if phone_balance < 10:
phone_balance += 10
bank_balance -= 10
print(phone_balance)
print(bank_balance)
#Second Example - try changing the value of number
number = 145
if number % 2 == 0:
print("Number " + str(n... | phone_balance = 10
bank_balance = 50
if phone_balance < 10:
phone_balance += 10
bank_balance -= 10
print(phone_balance)
print(bank_balance)
number = 145
if number % 2 == 0:
print('Number ' + str(number) + ' is even.')
else:
print('Number ' + str(number) + ' is odd.')
age = 35
free_up_to_age = 4
child_up... |
#crie um programa que leia o nome de uma pessoa e diga
#se ela tem "SILVA" no nome.
n=str(input("Digite o seu nome completo: ")).strip()
n=n[0:].upper().count("SILVA")
print(n)
n=str(input("Digite o seu nome completo: ")).strip()
n=n.lower()
print("Seu nome tem \"Silva\"? {}".format("silva" in n))
n=str(input("Digi... | n = str(input('Digite o seu nome completo: ')).strip()
n = n[0:].upper().count('SILVA')
print(n)
n = str(input('Digite o seu nome completo: ')).strip()
n = n.lower()
print('Seu nome tem "Silva"? {}'.format('silva' in n))
n = str(input('Digite o seu nome completo: ')).strip()
print('Seu nome tem "Silva"? {}'.format('sil... |
#
# MIT License
#
# Copyright (c) 2020 Pablo Rodriguez Nava, @pablintino
#
# 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
# t... | class Bracemessage(object):
def __init__(self, fmt, *args, **kwargs):
self.fmt = fmt
self.args = args
self.kwargs = kwargs
def __str__(self):
return self.fmt.format(*self.args, **self.kwargs)
class Caseinsensitivedict(dict):
@classmethod
def _k(cls, key):
retu... |
{
"targets": [
{
"target_name": "tree_sitter_hack_binding",
"include_dirs": [
"<!(node -e \"require('nan')\")",
"src"
],
"sources": [
"src/parser.c",
"bindings/node/binding.cc",
"src/scanner.cc"
],
"cflags_c": [
"-std=c99",
... | {'targets': [{'target_name': 'tree_sitter_hack_binding', 'include_dirs': ['<!(node -e "require(\'nan\')")', 'src'], 'sources': ['src/parser.c', 'bindings/node/binding.cc', 'src/scanner.cc'], 'cflags_c': ['-std=c99', '-Wno-trigraphs'], 'xcode_settings': {'OTHER_CFLAGS': ['-Wno-trigraphs']}}]} |
# -*- encoding: utf-8 -*-
"""
Created by eniocc at 11/10/2020
"""
| """
Created by eniocc at 11/10/2020
""" |
print(f'{(x := "awesome")!r:20}', x)
class A:
locals = 555
print(f'{(y := 666)}')
print(y)
print(f'''L1 -> {f"""L2 -> {f'L3 -> {f"L4 -> {(z := chr(77))!r} <- L4"} <- L3'} <- L2"""} <- L1''')
print(z)
print(f'see -> {"header " + f"{(w := chr(88))}" + " footer"} <- see')
print(w)
print(l... | print(f"{(x := 'awesome')!r:20}", x)
class A:
locals = 555
print(f'{(y := 666)}')
print(y)
print(f'''L1 -> {f"""L2 -> {f"L3 -> {f'L4 -> {(z := chr(77))!r} <- L4'} <- L3"} <- L2"""} <- L1''')
print(z)
print(f"see -> {'header ' + f'{(w := chr(88))}' + ' footer'} <- see")
print(w)
print(lo... |
"""Module to store EnforceTyping exceptions."""
class EnforcedTypingError(TypeError):
"""Class to raise errors relating to static typing decorator."""
| """Module to store EnforceTyping exceptions."""
class Enforcedtypingerror(TypeError):
"""Class to raise errors relating to static typing decorator.""" |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
cur = head
node_list = []
while cur is not None:
node_list.append(cur)
... | class Listnode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def insertion_sort_list(self, head: ListNode) -> ListNode:
cur = head
node_list = []
while cur is not None:
node_list.append(cur)
cur = cur.next
for ind... |
# La funcion calcula sobre un promedio de notas ingresadas de 0 a 100
def nota_quices(codigo: str, nota1: int, nota2: int, nota3: int, nota4: int, nota5: int)-> str:
notasEstudiate=(nota1, nota2, nota3, nota4, nota5)
notaMin= min(notasEstudiate) # Elegir la menor nota para descartar
promedioAcordado= (n... | def nota_quices(codigo: str, nota1: int, nota2: int, nota3: int, nota4: int, nota5: int) -> str:
notas_estudiate = (nota1, nota2, nota3, nota4, nota5)
nota_min = min(notasEstudiate)
promedio_acordado = (nota1 + nota2 + nota3 + nota4 + nota5 - notaMin) / 4
promedio_ajustado = promedioAcordado * 5 / 100
... |
name = "core_pipeline"
version = "2.1.0"
build_command = "python -m rezutil {root}"
private_build_requires = ["rezutil-1"]
_environ = {
"PYTHONPATH": [
"{root}/python",
],
}
def commands():
global env
global this
global system
global expandvars
for key, value in this._environ.it... | name = 'core_pipeline'
version = '2.1.0'
build_command = 'python -m rezutil {root}'
private_build_requires = ['rezutil-1']
_environ = {'PYTHONPATH': ['{root}/python']}
def commands():
global env
global this
global system
global expandvars
for (key, value) in this._environ.items():
if isinst... |
#!/usr/bin/env python3
intList = [1,2,3]
def normalList():
print("initial list: " + str(intList)) # must be str, not list or type
# list items can be reassigned
normalList()
print(intList + [4,5]) # temp print list with more indexes
intList.append(6) # permenently add a 6 to list.
# Using .append METHOD from f... | int_list = [1, 2, 3]
def normal_list():
print('initial list: ' + str(intList))
normal_list()
print(intList + [4, 5])
intList.append(6)
print(len(intList))
intList[1] = 4
print('intList[1] =: ' + str(intList[1]))
print('new list: ' + str(intList))
print('list many times' + str(intList) * 2)
print(intList * 3)
norma... |
try:
aa = 1.0/0
except Exception as e:
print(e)
print(aa)
class Animal():
def __init__(self):
self.age = 1
class Cat(Animal):
def __init__(self):
super().__init__()
self.age = 2
self.name = 'Cat'
c = Cat()
print(c.age)
print(c.name)
class Student():
def fu... | try:
aa = 1.0 / 0
except Exception as e:
print(e)
print(aa)
class Animal:
def __init__(self):
self.age = 1
class Cat(Animal):
def __init__(self):
super().__init__()
self.age = 2
self.name = 'Cat'
c = cat()
print(c.age)
print(c.name)
class Student:
def func(s... |
# optimizer
optimizer = dict(type='SGD', lr=0.003, momentum=0.9, weight_decay=0.0005) #0.0001)
optimizer_config = dict(grad_clip=dict(max_norm=10, norm_type=2))
# learning policy
lr_config = dict(
policy='step',
warmup='linear',
warmup_iters=500,
warmup_ratio=0.001,
step=[16])
total_epochs = 22
| optimizer = dict(type='SGD', lr=0.003, momentum=0.9, weight_decay=0.0005)
optimizer_config = dict(grad_clip=dict(max_norm=10, norm_type=2))
lr_config = dict(policy='step', warmup='linear', warmup_iters=500, warmup_ratio=0.001, step=[16])
total_epochs = 22 |
courses = {}
commands = input()
while not commands == "end":
commands = commands.split(" : ")
if commands[0] not in courses:
courses[commands[0]] = []
courses[commands[0]].append(commands[1])
else:
courses[commands[0]].append(commands[1])
commands = input()
#a = sorted(... | courses = {}
commands = input()
while not commands == 'end':
commands = commands.split(' : ')
if commands[0] not in courses:
courses[commands[0]] = []
courses[commands[0]].append(commands[1])
else:
courses[commands[0]].append(commands[1])
commands = input()
sorted_courses = sorte... |
"""
This file contains different status codes for NetConnection, NetStream and SharedObject.
The source code was taken from the rtmpy project (https://github.com/hydralabs/rtmpy)
https://github.com/hydralabs/rtmpy/blob/master/rtmpy/status/codes.py
"""
# === NetConnection status codes and what they mean. ===
... | """
This file contains different status codes for NetConnection, NetStream and SharedObject.
The source code was taken from the rtmpy project (https://github.com/hydralabs/rtmpy)
https://github.com/hydralabs/rtmpy/blob/master/rtmpy/status/codes.py
"""
nc_call_bad_version = 'NetConnection.Call.BadVersion'
nc_call_faile... |
#
# PySNMP MIB module BENU-DHCP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BENU-DHCP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:37:16 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_union, value_range_constraint, single_value_constraint, constraints_intersection) ... |
'''
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
'''
def prime_sum(n):
if n < 2: return 0
if n == 2: return 2
if n % 2 == 0: n += 1
primes = [True] * n
primes[0],primes[1] = [None] * 2
sum = 0
for ind,val in enumerate(primes):
... | """
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
"""
def prime_sum(n):
if n < 2:
return 0
if n == 2:
return 2
if n % 2 == 0:
n += 1
primes = [True] * n
(primes[0], primes[1]) = [None] * 2
sum = 0
for (ind, v... |
engine_repository = [ ['https://github.com/Relintai/godot.git', 'git@github.com:Relintai/godot.git'], 'engine', '' ]
module_repositories = [
[ ['https://github.com/Relintai/entity_spell_system.git', 'git@github.com:Relintai/entity_spell_system.git'], 'entity_spell_system', '' ],
[ ['https://github.com/Relinta... | engine_repository = [['https://github.com/Relintai/godot.git', 'git@github.com:Relintai/godot.git'], 'engine', '']
module_repositories = [[['https://github.com/Relintai/entity_spell_system.git', 'git@github.com:Relintai/entity_spell_system.git'], 'entity_spell_system', ''], [['https://github.com/Relintai/ui_extensions.... |
# Approach 2 - Optimized
# Time: O(n)
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
l = len(flowerbed)
flowerbed = [0] + flowerbed + [0]
for i in range(1, l+1):
if flowerbed[i] == flowerbed[i-1] == flowerbed[i+1] == 0:
... | class Solution:
def can_place_flowers(self, flowerbed: List[int], n: int) -> bool:
l = len(flowerbed)
flowerbed = [0] + flowerbed + [0]
for i in range(1, l + 1):
if flowerbed[i] == flowerbed[i - 1] == flowerbed[i + 1] == 0:
flowerbed[i] = 1
n -= 1... |
#ENTRADA DE VALORES
lista = list(map(float, input().split()))
#ORGANIZANDO A LISTA PARA QUE O PRIMEIRO ELEMENTO SEJA O MAIOR VALOR
lista.sort(reverse=True)
a, b, c = lista[0], lista[1], lista[2]
if a >= b+c:
print("NAO FORMA TRIANGULO")
elif a**2 == b**2 + c**2:
print("TRIANGULO RETANGULO")
elif a**2 > b**2 + c**... | lista = list(map(float, input().split()))
lista.sort(reverse=True)
(a, b, c) = (lista[0], lista[1], lista[2])
if a >= b + c:
print('NAO FORMA TRIANGULO')
elif a ** 2 == b ** 2 + c ** 2:
print('TRIANGULO RETANGULO')
elif a ** 2 > b ** 2 + c ** 2:
print('TRIANGULO OBTUSANGULO')
elif a ** 2 < b ** 2 + c ** 2:
... |
class Game:
def __init__(self, id, match_up):
self.id = id
self.match_up = match_up
def __unicode__(self):
return '{0} - {1}'.format(self.get_additional_unicode(), self.get_base_unicode())
def get_base_unicode(self):
return 'id: {id} | match up: {match_up}'.format(self.id,... | class Game:
def __init__(self, id, match_up):
self.id = id
self.match_up = match_up
def __unicode__(self):
return '{0} - {1}'.format(self.get_additional_unicode(), self.get_base_unicode())
def get_base_unicode(self):
return 'id: {id} | match up: {match_up}'.format(self.id,... |
#
# PySNMP MIB module OMNI-gx2EDFA-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OMNI-gx2EDFA-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:33:17 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, constraints_intersection, single_value_constraint, value_size_constraint) ... |
class Config(object):
#Google API keys
OAUTH2_SCOPE = 'https://www.googleapis.com/auth/drive'
DRIVE_CLIENT_ID = 'your drive client id'
DRIVE_CLIENT_SECRET = 'your drive client secret'
DRIVE_REDIRECT_URI = 'your redirect uri'
| class Config(object):
oauth2_scope = 'https://www.googleapis.com/auth/drive'
drive_client_id = 'your drive client id'
drive_client_secret = 'your drive client secret'
drive_redirect_uri = 'your redirect uri' |
nome = 'fazenda', 'caro', 'notebook', 'agua', 'helicoptero', 'aviao'
for n in nome:
print(f'\no nome {n} tem as vogais:', end=' ')
for vogal in n:
if vogal.lower() in 'aeiou':
print(vogal, end=' ')
| nome = ('fazenda', 'caro', 'notebook', 'agua', 'helicoptero', 'aviao')
for n in nome:
print(f'\no nome {n} tem as vogais:', end=' ')
for vogal in n:
if vogal.lower() in 'aeiou':
print(vogal, end=' ') |
load("@rules_vulkan//glsl:repositories.bzl", "glsl_repositories")
load("@rules_vulkan//vulkan/platform:windows.bzl", "vulkan_windows")
load("@rules_vulkan//vulkan/platform:linux.bzl", "vulkan_linux")
def vulkan_repositories():
"""Loads the required repositories into the workspace
"""
vulkan_windows(
... | load('@rules_vulkan//glsl:repositories.bzl', 'glsl_repositories')
load('@rules_vulkan//vulkan/platform:windows.bzl', 'vulkan_windows')
load('@rules_vulkan//vulkan/platform:linux.bzl', 'vulkan_linux')
def vulkan_repositories():
"""Loads the required repositories into the workspace
"""
vulkan_windows(name='v... |
#
# PySNMP MIB module RFC1382-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RFC1382-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:32:43 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 0... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, value_size_constraint, value_range_constraint, constraints_intersection) ... |
class ResponseStatusError(Exception):
status: int
def __init__(self, message: str, status: int):
super().__init__(message)
self.status = status
def __reduce__(self): # pragma: no cover
return (type(self), (*self.args, self.status))
class ConfigDependencyError(Exception):
pas... | class Responsestatuserror(Exception):
status: int
def __init__(self, message: str, status: int):
super().__init__(message)
self.status = status
def __reduce__(self):
return (type(self), (*self.args, self.status))
class Configdependencyerror(Exception):
pass
class Xmlloaderror... |
input = [16, 11, 15, 0, 1, 7]
x = input.pop()
seen = {v: i for (i, v) in enumerate(input)}
target = 30000000
for i in range(len(input), target - 1):
s = seen.get(x)
seen[x] = i
x = 0
if s is not None:
x = i - s
print(x)
# 0
# 8
# 14
# 8
# 2
# 165
# 1811
# 15075
# 182867
# 623065
# 0
# 10
#... | input = [16, 11, 15, 0, 1, 7]
x = input.pop()
seen = {v: i for (i, v) in enumerate(input)}
target = 30000000
for i in range(len(input), target - 1):
s = seen.get(x)
seen[x] = i
x = 0
if s is not None:
x = i - s
print(x) |
def ispangram(str):
alphabet = "abcdefghijklmnopqrstuvwxyz"
for char in alphabet:
if char not in str.lower():
return False
return True
str = input("enter a sentence :\n ")
if ispangram(str):
print('contains all alphabets')
else:
print('does not contain all alph... | def ispangram(str):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
for char in alphabet:
if char not in str.lower():
return False
return True
str = input('enter a sentence :\n ')
if ispangram(str):
print('contains all alphabets')
else:
print('does not contain all alphabets') |
def bit_floor(n: int) -> int:
"""Calculate the largest power of two not greater than n.
If zero, returns zero."""
if n:
# see https://stackoverflow.com/a/14267825/17332200
exp = (n // 2).bit_length()
res = 1 << exp
return res
else:
return 0
| def bit_floor(n: int) -> int:
"""Calculate the largest power of two not greater than n.
If zero, returns zero."""
if n:
exp = (n // 2).bit_length()
res = 1 << exp
return res
else:
return 0 |
html = """
<!DOCTYPE html>
<html>
<head>
<script src="qrc:///qtwebchannel/qwebchannel.js"></script>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
#map {
height: 100%;
}
html, body {
height: 100%;
... | html = '\n<!DOCTYPE html>\n<html>\n<head>\n <script src="qrc:///qtwebchannel/qwebchannel.js"></script>\n <meta name="viewport" content="initial-scale=1.0, user-scalable=no">\n <meta charset="utf-8">\n <style>\n #map {\n height: 100%;\n }\n\n html, body {\n height: ... |
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
# take input from the user
choice = int(input("Enter choice(1/2/3/4): "))
# check if choice is one of the four options
if choice in (1, 2, 3, 4):
num1 = float(input("Enter first numb... | print('Select operation.')
print('1.Add')
print('2.Subtract')
print('3.Multiply')
print('4.Divide')
while True:
choice = int(input('Enter choice(1/2/3/4): '))
if choice in (1, 2, 3, 4):
num1 = float(input('Enter first number: '))
num2 = float(input('Enter second number: '))
if choice == ... |
def test_home_retorna_status_code_200(client):
response = client.get("/")
assert response.status_code == 200
def test_home_retorna_texto_ola(client):
response = client.get("/")
assert response.text == "ola"
def test_echo_retorna_status_code_200(client):
response = client.get("/echo")
assert ... | def test_home_retorna_status_code_200(client):
response = client.get('/')
assert response.status_code == 200
def test_home_retorna_texto_ola(client):
response = client.get('/')
assert response.text == 'ola'
def test_echo_retorna_status_code_200(client):
response = client.get('/echo')
assert re... |
#!/usr/bin/python2.4
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | """Builds the test tables. See class comment for more details."""
__author__ = 'bmcquade@google.com (Bryan McQuade)'
class Testtablebuilder(object):
"""Builds a list of test cases based on the public suffix list."""
def __init__(self):
self._test_table = []
def build_test_table(self, rules):
... |
bool_one = 5 != 7
bool_two = 1 + 1 != 2
bool_three = 3 * 3 == 9
print(bool_one) #True
print(bool_two) #False
print(bool_three) #True
my_bool = "true"
print(type(my_bool)) #<class 'str'>
my_bool_two = True
print(type(my_bool_two)) #<class 'bool'>
my_bool_three = 452
print(type(my_bool_three)) #<class 'int'> | bool_one = 5 != 7
bool_two = 1 + 1 != 2
bool_three = 3 * 3 == 9
print(bool_one)
print(bool_two)
print(bool_three)
my_bool = 'true'
print(type(my_bool))
my_bool_two = True
print(type(my_bool_two))
my_bool_three = 452
print(type(my_bool_three)) |
a = int(input())
b = int(input())
range = range(a, b + 1)
list = list(filter(lambda x: x % 3 == 0, range))
print(sum(list) / len(list))
| a = int(input())
b = int(input())
range = range(a, b + 1)
list = list(filter(lambda x: x % 3 == 0, range))
print(sum(list) / len(list)) |
# angle.py: A class describing an angle between three atoms.
class Angle:
atom1 = ""
atom2 = ""
atom3 = ""
angle = 0.0
def __init__(self, atom1, atom2, atom3, angle):
self.atom1 = atom1
self.atom2 = atom2
self.atom3 = atom3
self.angle = angle
| class Angle:
atom1 = ''
atom2 = ''
atom3 = ''
angle = 0.0
def __init__(self, atom1, atom2, atom3, angle):
self.atom1 = atom1
self.atom2 = atom2
self.atom3 = atom3
self.angle = angle |
#!/usr/bin/env python3
# Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2,
# the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci
# sequence whose values do not exceed four million, find the sum of th... | def find_even_sum_fib() -> int:
(a, b) = (1, 2)
result = 0
while b < 4000000.0:
if b % 2 == 0:
result += b
b = a + b
a = b - a
return result
if __name__ == '__main__':
assert find_even_sum_fib() == 4613732 |
def solve(data):
X, Y, N, W, P1, P2 = data
for _ in range(int(input())):
data = [int(num) for num in input().split(" ")]
print(solve(data)) | def solve(data):
(x, y, n, w, p1, p2) = data
for _ in range(int(input())):
data = [int(num) for num in input().split(' ')]
print(solve(data)) |
# -*- coding: utf-8 -*-
def main():
n = int(input())
h = int(input())
w = int(input())
print((n - w + 1) * (n - h + 1))
if __name__ == '__main__':
main()
| def main():
n = int(input())
h = int(input())
w = int(input())
print((n - w + 1) * (n - h + 1))
if __name__ == '__main__':
main() |
class NoInteractionsFound(Exception):
def __init__(self, description: str = None, hint: str = None):
super(NoInteractionsFound, self).__init__('No CellPhoneDB interacions found in this input.')
self.description = description
self.hint = hint
| class Nointeractionsfound(Exception):
def __init__(self, description: str=None, hint: str=None):
super(NoInteractionsFound, self).__init__('No CellPhoneDB interacions found in this input.')
self.description = description
self.hint = hint |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findSecondMinimumValue(self, root: TreeNode) -> int:
small = root.val
res = []
... | class Solution:
def find_second_minimum_value(self, root: TreeNode) -> int:
small = root.val
res = []
def rec(root):
if root:
rec(root.left)
res.append(root.val)
rec(root.right)
rec(root)
res = set(res)
if ... |
#encoding:utf-8
subreddit = 'Genshin_Impact'
t_channel = '@Genshin_Impact_reddit'
def send_post(submission, r2t):
return r2t.send_simple(submission)
| subreddit = 'Genshin_Impact'
t_channel = '@Genshin_Impact_reddit'
def send_post(submission, r2t):
return r2t.send_simple(submission) |
#
# PySNMP MIB module DEC-ATM-SIGNALLING-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DEC-ATM-SIGNALLING-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:37:24 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_intersection, value_range_constraint, single_value_constraint, constraints_union) ... |
#!/usr/bin/python
print("Hello world")
print("GOD LOVES YOU")
print("John 3:16\n")
print("CHRIST JESUS: EMMANUEL...")
print("Full of TRUTH & GRACE")
print("John 1:17\n")
print("Love God: with ALL you are... + the kitchen sink!")
print("Love ya Neighbour: as you already love ya self...")
print("ENJOY THE DISCIPLESHIP... | print('Hello world')
print('GOD LOVES YOU')
print('John 3:16\n')
print('CHRIST JESUS: EMMANUEL...')
print('Full of TRUTH & GRACE')
print('John 1:17\n')
print('Love God: with ALL you are... + the kitchen sink!')
print('Love ya Neighbour: as you already love ya self...')
print('ENJOY THE DISCIPLESHIP PROCESS')
print('HAL... |
class Category:
ANTIQUES_COLLECTABLES = '/for-sale/antiques-collectables/66/'
ANTIQUES_COLLECTABLES__AUTOGRAPHS = '/for-sale/antiques-collectables/autographs/984/'
ANTIQUES_COLLECTABLES__BOTTLES = '/for-sale/antiques-collectables/bottles/985/'
ANTIQUES_COLLECTABLES__CALL_CARDS = '/for-sale/antiques-coll... | class Category:
antiques_collectables = '/for-sale/antiques-collectables/66/'
antiques_collectables__autographs = '/for-sale/antiques-collectables/autographs/984/'
antiques_collectables__bottles = '/for-sale/antiques-collectables/bottles/985/'
antiques_collectables__call_cards = '/for-sale/antiques-coll... |
i = 0
v = "test"
c = 0.1
print("{0} {1} {2}".format(i, c, v))
| i = 0
v = 'test'
c = 0.1
print('{0} {1} {2}'.format(i, c, v)) |
'''def bubbleSort(arr):
n = len(arr)
for i in range(n):
for j in range(0,n-i-1):
if arr[j] > arr[j+1]:
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
arr = [10,9,15,1,5,2,6,3]
bubbleSort(arr)
print('Sorted array: ')
for i in range(len(arr)):
... | """def bubbleSort(arr):
n = len(arr)
for i in range(n):
for j in range(0,n-i-1):
if arr[j] > arr[j+1]:
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
arr = [10,9,15,1,5,2,6,3]
bubbleSort(arr)
print('Sorted array: ')
for i in range(len(arr)):
... |
# Create 2 variables for future operations
x = 0b101001 # Here we create 2 variables with values x = 41, y = 38
y = 0b100110 # We create bit numbers with the "0b" notation.
print(x, y)
# Bitwise AND -- "&"
# It returns 1 if two of the bits 1 and 0 if one of the bits 1 or both 0
z = x & y # which makes z = 0b001... | x = 41
y = 38
print(x, y)
z = x & y
print(bin(z))
z = x | y
print(bin(z))
z = x ^ y
print(bin(z))
z = x << 1
z = x << 4
z = x >> 1
print(bin(z)) |
class Node:
"""Create a Node object"""
def __init__(self, val, next=None):
"""Constructor for the Node object"""
self.val = val
self._next = next
if val is None:
raise TypeError('Must pass a value')
def __repr__(self):
return '{val}'.format(val=self.val)... | class Node:
"""Create a Node object"""
def __init__(self, val, next=None):
"""Constructor for the Node object"""
self.val = val
self._next = next
if val is None:
raise type_error('Must pass a value')
def __repr__(self):
return '{val}'.format(val=self.val... |
def is_same(num):
if (sum(map(int, str(num))) % 3 != 0):
return False
a = set()
for i in range(1,6):
val = str(num * i)
a.add(''.join(sorted(val)))
if (num == 142857):
print(a)
return len(a) == 1
for i in range(1000,10000000):
for j in range(10, 15):
... | def is_same(num):
if sum(map(int, str(num))) % 3 != 0:
return False
a = set()
for i in range(1, 6):
val = str(num * i)
a.add(''.join(sorted(val)))
if num == 142857:
print(a)
return len(a) == 1
for i in range(1000, 10000000):
for j in range(10, 15):
num = i... |
#
# PySNMP MIB module FILTER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FILTER-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:13:49 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_union, value_range_constraint, single_value_constraint, constraints_intersection) ... |
#Passwd file for passwordmanager app
loginpass='windowsADpasswd'
user='domain.name\\username'
passwordReset = 'staticPassword'
new_pass = 'newadpassword'
adServer='adServer.domain.name'
| loginpass = 'windowsADpasswd'
user = 'domain.name\\username'
password_reset = 'staticPassword'
new_pass = 'newadpassword'
ad_server = 'adServer.domain.name' |
#----------------------------------------------------------------------------------------------------------
#
# AUTOMATICALLY GENERATED FILE TO BE USED BY W_HOTBOX
#
# NAME: Bake
# COLOR: #685777
# TEXTCOLOR: #ffffff
#
#----------------------------------------------------------------------------------------------------... | ns = nuke.selectedNodes()
for n in ns:
n.knob('bake').execute() |
"""Given two integers n and k, you need to construct a list which contains n different positive integers ranging from 1
to n and obeys the following requirement: Suppose this list is [a1, a2, a3, ... , an], then the list [|a1 - a2|,
|a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactly k distinct integers.
If there are ... | """Given two integers n and k, you need to construct a list which contains n different positive integers ranging from 1
to n and obeys the following requirement: Suppose this list is [a1, a2, a3, ... , an], then the list [|a1 - a2|,
|a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactly k distinct integers.
If there are ... |
def sayhi(name):
print("Hello "+ name)
sayhi(" vaibhav .")
def data(name,age):
print("Hello " + name +" You are " + str(age)+ ".")
nm=input("Enter the name: ")
age=int(input("Enter the age: "))
data(nm,age)
| def sayhi(name):
print('Hello ' + name)
sayhi(' vaibhav .')
def data(name, age):
print('Hello ' + name + ' You are ' + str(age) + '.')
nm = input('Enter the name: ')
age = int(input('Enter the age: '))
data(nm, age) |
class MemberStore:
members = []
last_id = 1
def get_all(self):
return MemberStore.members
def add(self, member):
member.id = MemberStore.last_id
MemberStore.members.append(member)
MemberStore.last_id += 1
def get_by_id(self, id):
member_list = self.get_al... | class Memberstore:
members = []
last_id = 1
def get_all(self):
return MemberStore.members
def add(self, member):
member.id = MemberStore.last_id
MemberStore.members.append(member)
MemberStore.last_id += 1
def get_by_id(self, id):
member_list = self.get_all(... |
"""Sorting Algorithms In Python
"""
"""
Dutch national flag problem
https://en.wikipedia.org/wiki/Dutch_national_flag_problem
"""
def sort_colors(nums: [int], pivot: int)->[int]:
small = 0
current = 1
big = len(nums)-1
while current < big:
if nums[current] == pivot:
current += 1
... | """Sorting Algorithms In Python
"""
'\nDutch national flag problem\nhttps://en.wikipedia.org/wiki/Dutch_national_flag_problem\n'
def sort_colors(nums: [int], pivot: int) -> [int]:
small = 0
current = 1
big = len(nums) - 1
while current < big:
if nums[current] == pivot:
current += 1
... |
# -*- coding: utf8 -*-
class DogEvent(object):
def __init__(self, event_type, data):
self.event_type = event_type
self.data = data
def get_event(self):
tmp = ""
if isinstance(self.data, dict):
for k in self.data.keys():
tmp += "{}={}~".format(... | class Dogevent(object):
def __init__(self, event_type, data):
self.event_type = event_type
self.data = data
def get_event(self):
tmp = ''
if isinstance(self.data, dict):
for k in self.data.keys():
tmp += '{}={}~'.format(k, str(self.data[k]).replace('... |
# Version of the specification for MDF
MODECI_MDF_VERSION = "0.1"
# Version of the python module. Use MDF version here and just change minor version
__version__ = "%s.3" % MODECI_MDF_VERSION
| modeci_mdf_version = '0.1'
__version__ = '%s.3' % MODECI_MDF_VERSION |
#Write a program that asks the user for an input 'n' and prints a square of n by n asterisks "*".
number = int(input("Give me a number: "))
line = '*'*number
for x in range(0, number):
print (line) | number = int(input('Give me a number: '))
line = '*' * number
for x in range(0, number):
print(line) |
def find_min_idx(i, count, arr, min_element):
min_idx = 0
while i <= count and i < len(arr):
if arr[i] < min_element:
min_element = arr[i]
min_idx = i
i += 1
return min_idx
def find_min_array(arr, k):
min_element = 1_000_000
i = 0
count = k
while ... | def find_min_idx(i, count, arr, min_element):
min_idx = 0
while i <= count and i < len(arr):
if arr[i] < min_element:
min_element = arr[i]
min_idx = i
i += 1
return min_idx
def find_min_array(arr, k):
min_element = 1000000
i = 0
count = k
while k:
... |
"""
The longest common subsequence (LCS) problem is the problem of finding the longest subsequence common to
all sequences in a set of sequences (often just two sequences).
It differs from the longest common substring problem: unlike substrings, subsequences are not required to
occupy consecutive positions within the ... | """
The longest common subsequence (LCS) problem is the problem of finding the longest subsequence common to
all sequences in a set of sequences (often just two sequences).
It differs from the longest common substring problem: unlike substrings, subsequences are not required to
occupy consecutive positions within the ... |
"""Utilities for Java brotli tests."""
_TEST_JVM_FLAGS = [
"-DBROTLI_ENABLE_ASSERTS=true",
]
def brotli_java_test(name, main_class = None, jvm_flags = None, **kwargs):
"""test duplication rule that creates 32/64-bit test pair."""
if jvm_flags == None:
jvm_flags = []
jvm_flags = jvm_flags + _T... | """Utilities for Java brotli tests."""
_test_jvm_flags = ['-DBROTLI_ENABLE_ASSERTS=true']
def brotli_java_test(name, main_class=None, jvm_flags=None, **kwargs):
"""test duplication rule that creates 32/64-bit test pair."""
if jvm_flags == None:
jvm_flags = []
jvm_flags = jvm_flags + _TEST_JVM_FLAGS... |
expected_output = {
'caf_service': 'Not Running',
'ha_service': 'Not Running',
'ioxman_service': 'Not Running',
'sec_storage_service': 'Not Running',
'libvirtd': 'Running',
'dockerd': 'Not Running',
'redundancy_status': 'Non-Redundant'
} | expected_output = {'caf_service': 'Not Running', 'ha_service': 'Not Running', 'ioxman_service': 'Not Running', 'sec_storage_service': 'Not Running', 'libvirtd': 'Running', 'dockerd': 'Not Running', 'redundancy_status': 'Non-Redundant'} |
# The following templates are markdowns
overview = """
## Context
Manufacturing process feature selection and categorization
## Content
Abstract: Data from a semi-conductor manufacturing process
Data Set Characteristics: Multivariate
Number of Instances: 1567
Area: Computer
Attribute Characteristic... | overview = '\n## Context\n\nManufacturing process feature selection and categorization\n\n## Content\n\nAbstract: Data from a semi-conductor manufacturing process\n\n Data Set Characteristics: Multivariate\n Number of Instances: 1567\n Area: Computer\n Attribute Characteristics: Real\n Number of Attribut... |
total = 0
current = 1
prev = 1
while current < 4000000:
temp = current
current = current + prev
prev = temp
if current % 2 == 0:
total += current
print (total) | total = 0
current = 1
prev = 1
while current < 4000000:
temp = current
current = current + prev
prev = temp
if current % 2 == 0:
total += current
print(total) |
f = open("Acc_2021-02-21_231529.txt", "r")
acc = []
for line in f.readlines()[1:]:
aa = line.split()[1:]
bb = line.split()[1:]
for i, a in enumerate(bb):
bb[i] = f"{a}f"
acc.append(bb)
acc = acc[0::8]
dataTowrite = []
dataTowrite.append(f"const float accData[{len(acc)}][3] = {{\n")
fo... | f = open('Acc_2021-02-21_231529.txt', 'r')
acc = []
for line in f.readlines()[1:]:
aa = line.split()[1:]
bb = line.split()[1:]
for (i, a) in enumerate(bb):
bb[i] = f'{a}f'
acc.append(bb)
acc = acc[0::8]
data_towrite = []
dataTowrite.append(f'const float accData[{len(acc)}][3] = {{\n')
for a in a... |
class MarkupFile:
def __init__(self, data):
self.data = data
self.parse()
def parse(self):
raw = self.data.split('\n')
no_comments = []
for line in raw:
line += line.split('#')[0]
in_block_comment = False
no_block_comments = []
... | class Markupfile:
def __init__(self, data):
self.data = data
self.parse()
def parse(self):
raw = self.data.split('\n')
no_comments = []
for line in raw:
line += line.split('#')[0]
in_block_comment = False
no_block_comments = []
for li... |
class Solution:
def binarySearch(self, nums, start, end, target, lower):
ret = -1
while start <= end:
mid = (end + start) // 2
if nums[mid] < target:
start = mid + 1
elif nums[mid] > target:
end = mid - 1
else:
... | class Solution:
def binary_search(self, nums, start, end, target, lower):
ret = -1
while start <= end:
mid = (end + start) // 2
if nums[mid] < target:
start = mid + 1
elif nums[mid] > target:
end = mid - 1
else:
... |
class VnfListNotAvailable(Exception):
"""VNF list is not included in the openmano instance"""
pass
class VmListNotAvailable(Exception):
"""VM list is not included in the VNF record, part of the openmano instance"""
pass
class InstanceNotFound(Exception):
"""Openmano instance not found"""
pas... | class Vnflistnotavailable(Exception):
"""VNF list is not included in the openmano instance"""
pass
class Vmlistnotavailable(Exception):
"""VM list is not included in the VNF record, part of the openmano instance"""
pass
class Instancenotfound(Exception):
"""Openmano instance not found"""
pass
... |
__copyright__ = 'Copyright (C) 2019 rtafds'
__version__ = '0.0.1'
__license__ = 'MIT'
__author__ = 'rtafds'
__author_email__ = 'n.rtafds@gmail.coms'
| __copyright__ = 'Copyright (C) 2019 rtafds'
__version__ = '0.0.1'
__license__ = 'MIT'
__author__ = 'rtafds'
__author_email__ = 'n.rtafds@gmail.coms' |
__all__ = [
'base_controller',
'forms_controller',
'landing_page_controller',
'messages_controller',
'objects_controller',
'tasks_controller',
'transactions_controller',
] | __all__ = ['base_controller', 'forms_controller', 'landing_page_controller', 'messages_controller', 'objects_controller', 'tasks_controller', 'transactions_controller'] |
# from aoc2019.day_six.planetary_composite import CentralMassComposite
class BFSPlanetaryIterator:
"""
This is an implementation of the iterator design pattern. It is applied to
the n-ary tree structure of planetary components. Each returned element is
a binary tuple (component, depth).
"""
de... | class Bfsplanetaryiterator:
"""
This is an implementation of the iterator design pattern. It is applied to
the n-ary tree structure of planetary components. Each returned element is
a binary tuple (component, depth).
"""
def __init__(self, root):
"""Basic initialization method for itera... |
# 1. var names cannot contain whitespaces
# 2. var names cannot start with a number
my_age = 27 # int
price = 0.5 # float
my_name_is_jan = True # bool
my_name_is_peter = False # bool
my_name = "Jan Schaffranek" # str
print(my_age)
print(price)
| my_age = 27
price = 0.5
my_name_is_jan = True
my_name_is_peter = False
my_name = 'Jan Schaffranek'
print(my_age)
print(price) |
def findDecision(obj): #obj[0]: Coupon, obj[1]: Education, obj[2]: Occupation, obj[3]: Distance
# {"feature": "Coupon", "instances": 8147, "metric_value": 0.4744, "depth": 1}
if obj[0]>1:
# {"feature": "Distance", "instances": 5889, "metric_value": 0.4618, "depth": 2}
if obj[3]<=2:
# {"feature": "Occupation", ... | def find_decision(obj):
if obj[0] > 1:
if obj[3] <= 2:
if obj[2] > 0:
if obj[1] > 1:
return 'True'
elif obj[1] <= 1:
return 'True'
else:
return 'True'
elif obj[2] <= 0:
... |
class HandlerMissingException(Exception):
"""Raised when an event handler is missing a handler for a specific event."""
pass
class DataTypeError(Exception):
"""Raised when data type doesn't correspond to the connection's data type."""
pass
class HeaderSizeError(Exception):
"""Raised when the hea... | class Handlermissingexception(Exception):
"""Raised when an event handler is missing a handler for a specific event."""
pass
class Datatypeerror(Exception):
"""Raised when data type doesn't correspond to the connection's data type."""
pass
class Headersizeerror(Exception):
"""Raised when the heade... |
class Hello:
def __init__(self):
while True:
print("Hello!")
| class Hello:
def __init__(self):
while True:
print('Hello!') |
"""
Extends the scitables core to display tables in a browser.
UITable is a rendering independent user API to tables.
DGTable is an API to tables that gets rendered in YUI DataTable
"""
| """
Extends the scitables core to display tables in a browser.
UITable is a rendering independent user API to tables.
DGTable is an API to tables that gets rendered in YUI DataTable
""" |
# In python you have this set of boolean expression
# == to check for equality or 'is'
# === to compare actual objects together
# True and False
# and, or, not
if 1 is 3:
print('What!! is that for real?')
elif 1 > 3:
print('Really????')
else:
print('Yeah that\'s what I know')
| if 1 is 3:
print('What!! is that for real?')
elif 1 > 3:
print('Really????')
else:
print("Yeah that's what I know") |
trainers = get_trainers(env, num_agents, "learner", obs_shape_n, arglist,session)
U.initialize()
obs_n = env.reset()
train_step=0
while True:
#Interaction step
iter_step=0
#Interact with environment to get experience
while True:
# get action
action_n = [agent.action(obs) for agent, obs... | trainers = get_trainers(env, num_agents, 'learner', obs_shape_n, arglist, session)
U.initialize()
obs_n = env.reset()
train_step = 0
while True:
iter_step = 0
while True:
action_n = [agent.action(obs) for (agent, obs) in zip(trainers, obs_n)]
(new_obs_n, rew_n, done_n, info_n) = env.step(action_... |
##----- Class Queue with their Operations -----##
class Queue:
def __init__(self):
print("Queue is all set to work on......\n")
self.Queue = []
def __Insertion__(self):
self.Queue.append((input("Enter Element :: ")))
print("\nElement Inserted Successfully!!!\n")
def __Trave... | class Queue:
def __init__(self):
print('Queue is all set to work on......\n')
self.Queue = []
def ___insertion__(self):
self.Queue.append(input('Enter Element :: '))
print('\nElement Inserted Successfully!!!\n')
def ___traversion__(self):
index = 0
for elem... |
# creating a txt file
write_file = open('sample.txt', 'w')
write_file.write("this is just a sample text\n")
write_file.close()
# reading file
read_file = open('sample.txt' , 'r')
text = read_file.read()
print(text)
| write_file = open('sample.txt', 'w')
write_file.write('this is just a sample text\n')
write_file.close()
read_file = open('sample.txt', 'r')
text = read_file.read()
print(text) |
def countSwaps(a):
n = len(a)
swaps = 0
for i in range(0, n):
for j in range(0, n-1):
if a[j] > a[j+1]:
aux = a[j]
a[j] = a[j+1]
a[j+1] = aux
swaps += 1
print('Array is sorted in',swaps, 'swaps')
print ('First Elem... | def count_swaps(a):
n = len(a)
swaps = 0
for i in range(0, n):
for j in range(0, n - 1):
if a[j] > a[j + 1]:
aux = a[j]
a[j] = a[j + 1]
a[j + 1] = aux
swaps += 1
print('Array is sorted in', swaps, 'swaps')
print('Fir... |
def slices(series, length):
if not series:
raise ValueError("invalid series")
if length <= 0:
raise ValueError("Length must be positive integer")
if length > len(series):
raise ValueError("Length must be less or equal to series length")
return [
series[start : start + len... | def slices(series, length):
if not series:
raise value_error('invalid series')
if length <= 0:
raise value_error('Length must be positive integer')
if length > len(series):
raise value_error('Length must be less or equal to series length')
return [series[start:start + length] for... |
"""
This is a undirected graph
A---C---E
| | |
B---D---|
"""
class createGraph:
def __init__(self, vertices) -> None:
self.vertices = vertices
self.graph_dict = {}
# create blank values for all the vertices
for node in self.vertices:
self.graph_dict[node] = []
d... | """
This is a undirected graph
A---C---E
| | |
B---D---|
"""
class Creategraph:
def __init__(self, vertices) -> None:
self.vertices = vertices
self.graph_dict = {}
for node in self.vertices:
self.graph_dict[node] = []
def add_edges(self, vertices, edges):
self.... |
# RUN: test-ir.sh %s
# IR-LABEL: while.0:
# IR: br i1 %{{[0-9]+}}, label %loop.0, label %endwhile.0
while True:
# IR-LABEL: loop.0:
if True:
# IR-LABEL: then.0:
# IR: br label %endwhile.0
break
# IR-LABEL: endif.0:
# IR: br label %while.0
# IR-LABEL: endwhile.0:
| while True:
if True:
break |
# 4. Convert Meters to Kilometers
# You will be given an integer that will be distance in meters.
# Write a program that converts meters to kilometers formatted to the second decimal point.
meters = int(input())
km = meters/1000
print(f'{km:.2f}') | meters = int(input())
km = meters / 1000
print(f'{km:.2f}') |
"""
PyCrypto has an own secure random function "Crypto.Random.random"
but it does not use a seed value as expected by rule 6
"""
| """
PyCrypto has an own secure random function "Crypto.Random.random"
but it does not use a seed value as expected by rule 6
""" |
"""
This module contains shared functions for testing
As it does not begin with "test", it will not be detected by the
auto-discovery of Pytest.
"""
def assert_pyspark_df_equal(actual_df, expected_df):
"""
Tests if two DataFrames are equal. Adapted from code originally
written by Dave Greasley (ht... | """
This module contains shared functions for testing
As it does not begin with "test", it will not be detected by the
auto-discovery of Pytest.
"""
def assert_pyspark_df_equal(actual_df, expected_df):
"""
Tests if two DataFrames are equal. Adapted from code originally
written by Dave Greasley (ht... |
"""
Put here common independent stuff,
such as utilities, management commands, etc.,
what can not belong to any app.
DO NOT let this package to be dump of ugly code.
Putting code here, you rather make an exception,
than an ordinary core organization.
""" | """
Put here common independent stuff,
such as utilities, management commands, etc.,
what can not belong to any app.
DO NOT let this package to be dump of ugly code.
Putting code here, you rather make an exception,
than an ordinary core organization.
""" |
class input_format():
def __init__(self,format_tag):
self.tag = format_tag
def print_sample_input(self):
if self.tag =='FCC_BCC_Edge_Ternary':
print('''
Sample JSON for using pseudo-ternary predictions of solid solution strength by Curtin edge dislocation model.
--... | class Input_Format:
def __init__(self, format_tag):
self.tag = format_tag
def print_sample_input(self):
if self.tag == 'FCC_BCC_Edge_Ternary':
print('\nSample JSON for using pseudo-ternary predictions of solid solution strength by Curtin edge dislocation model. \n------------------... |
class opcode(object):
nul = 1
hello = 2
rhello = 130
get = 160
rget = 161
| class Opcode(object):
nul = 1
hello = 2
rhello = 130
get = 160
rget = 161 |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 4 21:10:59 2018
@author: User
"""
def username():
first = 'arvind' #input('firstname')
last = 'KARIR' # input('lastname')
(yob) = str(1234) #int( input('yob') )
yob = yob[:3]
last = last[-4:]
print(first[:1].lower()+last.upper()+... | """
Created on Sun Feb 4 21:10:59 2018
@author: User
"""
def username():
first = 'arvind'
last = 'KARIR'
yob = str(1234)
yob = yob[:3]
last = last[-4:]
print(first[:1].lower() + last.upper() + yob[::-1])
username() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.