content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""Module docstring!"""
a = 1
b = 2
@bleh
@blah
def greet(
name: str,
age: int,
*args,
test='oh yeah',
**kwargs
) -> ({a: 1, b: 2}
):
"""Generic short description
Longer description of this function that does nothing
:param arg1: Desc for arg1
:type arg1: arg1_type
:r... | """Module docstring!"""
a = 1
b = 2
@bleh
@blah
def greet(name: str, age: int, *args, test='oh yeah', **kwargs) -> {a: 1, b: 2}:
"""Generic short description
Longer description of this function that does nothing
:param arg1: Desc for arg1
:type arg1: arg1_type
:returns: Desc for return
:rtype... |
class Solution(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
dp = [0] + [2 ** 31 - 1] * amount
for i in xrange(1, amount + 1):
for coin in coins:
if i >= coin and dp[i - c... | class Solution(object):
def coin_change(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
dp = [0] + [2 ** 31 - 1] * amount
for i in xrange(1, amount + 1):
for coin in coins:
if i >= coin and dp[i -... |
# -*- coding: utf-8 -*-
__author__ = 'lundberg'
class EduIDGroupDBError(Exception):
pass
class VersionMismatch(EduIDGroupDBError):
pass
class MultipleReturnedError(EduIDGroupDBError):
pass
class MultipleUsersReturned(MultipleReturnedError):
pass
class MultipleGroupsReturned(MultipleReturnedEr... | __author__ = 'lundberg'
class Eduidgroupdberror(Exception):
pass
class Versionmismatch(EduIDGroupDBError):
pass
class Multiplereturnederror(EduIDGroupDBError):
pass
class Multipleusersreturned(MultipleReturnedError):
pass
class Multiplegroupsreturned(MultipleReturnedError):
pass |
"""
Basic type definitions.
"""
| """
Basic type definitions.
""" |
""" Ingest Package Config """
# The list of entities that will be loaded into the target service. These
# should be class_name values of your target API config's target entity
# classes.
target_service_entities = [
"family",
"participant",
"diagnosis",
"phenotype",
"outcome",
"biospecimen",
... | """ Ingest Package Config """
target_service_entities = ['family', 'participant', 'diagnosis', 'phenotype', 'outcome', 'biospecimen', 'read_group', 'sequencing_experiment', 'genomic_file', 'biospecimen_genomic_file', 'sequencing_experiment_genomic_file', 'read_group_genomic_file']
extract_config_dir = 'extract_configs'... |
string_input = "amazing"
vowels = "aeiou"
answer = [char for char in string_input if char not in vowels]
print(answer)
| string_input = 'amazing'
vowels = 'aeiou'
answer = [char for char in string_input if char not in vowels]
print(answer) |
class Solution(object):
def deleteDuplicates(self, head):
initial = head
while head:
if head.next and head.val == head.next.val:
head.next = head.next.next
else:
head = head.next
head = initial
return head
| class Solution(object):
def delete_duplicates(self, head):
initial = head
while head:
if head.next and head.val == head.next.val:
head.next = head.next.next
else:
head = head.next
head = initial
return head |
# set random number generator
np.random.seed(2020)
# initialize step_end and v
step_end = int(t_max / dt)
v = el
t = 0
with plt.xkcd():
# initialize the figure
plt.figure()
plt.title('$V_m$ with random I(t)')
plt.xlabel('time (s)')
plt.ylabel(r'$V_m$ (V)')
# loop for step_end steps
for step in range(s... | np.random.seed(2020)
step_end = int(t_max / dt)
v = el
t = 0
with plt.xkcd():
plt.figure()
plt.title('$V_m$ with random I(t)')
plt.xlabel('time (s)')
plt.ylabel('$V_m$ (V)')
for step in range(step_end):
t = step * dt
plt.plot(t, v, 'k.')
i = i_mean * (1 + 0.1 * (t_max / dt) *... |
#author SANKALP SAXENA
def arrays(arr):
arr.reverse()
l = numpy.array(arr, float)
return l
| def arrays(arr):
arr.reverse()
l = numpy.array(arr, float)
return l |
def get_ts_struct(ts):
y=ts&0x3f
ts=ts>>6
m=ts&0xf
ts=ts>>4
d=ts&0x1f
ts=ts>>5
hh=ts&0x1f
ts=ts>>5
mm=ts&0x3f
ts=ts>>6
ss=ts&0x3f
ts=ts>>6
wd=ts&0x8
ts=ts>>3
yd=ts&0x1ff
ts=ts>>9
ms=ts&0x3ff
ts=ts>>10
pid=ts&0x3ff
return y,m,d,hh,mm,ss,wd,yd,ms,pid
| def get_ts_struct(ts):
y = ts & 63
ts = ts >> 6
m = ts & 15
ts = ts >> 4
d = ts & 31
ts = ts >> 5
hh = ts & 31
ts = ts >> 5
mm = ts & 63
ts = ts >> 6
ss = ts & 63
ts = ts >> 6
wd = ts & 8
ts = ts >> 3
yd = ts & 511
ts = ts >> 9
ms = ts & 1023
ts = ... |
class DispositivoEntrada:
def __init__(self, marca, tipo_entrada):
self._marca = marca
self.tipo_entrada = tipo_entrada
| class Dispositivoentrada:
def __init__(self, marca, tipo_entrada):
self._marca = marca
self.tipo_entrada = tipo_entrada |
# Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.com/)
#
# 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 appli... | limit_exceeded_error_massage = 'Instance limit exceeded. A new one will be launched as soon as free space will be available.'
limit_exceeded_exit_code = 6
class Abstractinstanceprovider(object):
def run_instance(self, is_spot, bid_price, ins_type, ins_hdd, ins_img, ins_key, run_id, kms_encyr_key_id, num_rep, time... |
c = float(input("Enter Amount Between 0-99 :"))
print(c // 20, "Twenties")
c = c % 20
print(c // 10, "Tens")
c = c % 10
print(c // 5, "Fives")
c = c % 5
print(c // 1, "Ones")
c = c % 1
print(c // 0.25, "Quarters")
c = c % 0.25
print(c // 0.1, "Dimes")
c = c % 0.1
print(c // 0.05, "Nickles")
c = c % 0.05
print(c // 0.01... | c = float(input('Enter Amount Between 0-99 :'))
print(c // 20, 'Twenties')
c = c % 20
print(c // 10, 'Tens')
c = c % 10
print(c // 5, 'Fives')
c = c % 5
print(c // 1, 'Ones')
c = c % 1
print(c // 0.25, 'Quarters')
c = c % 0.25
print(c // 0.1, 'Dimes')
c = c % 0.1
print(c // 0.05, 'Nickles')
c = c % 0.05
print(c // 0.01... |
class Cita:
def __init__(self,id,solicitante,fecha,hora,motivo,estado,doctor):
self.id = id
self.solicitante = solicitante
self.fecha = fecha
self.hora = hora
self.motivo = motivo
self.estado = estado
self.doctor = doctor
def getId(self):
... | class Cita:
def __init__(self, id, solicitante, fecha, hora, motivo, estado, doctor):
self.id = id
self.solicitante = solicitante
self.fecha = fecha
self.hora = hora
self.motivo = motivo
self.estado = estado
self.doctor = doctor
def get_id(self):
... |
#! /usr/bin/env python
# Copyright (c) 2017, Cuichaowen. All rights reserved.
# -*- coding: utf-8 -*-
# ops helper dictionary
class Dictionary(object):
"""
Dictionary for op param which needs to be combined
"""
def __init__(self):
self.__dict__ = {}
def set_attr(self, **kwargs):
... | class Dictionary(object):
"""
Dictionary for op param which needs to be combined
"""
def __init__(self):
self.__dict__ = {}
def set_attr(self, **kwargs):
"""
set dict from kwargs
"""
for key in kwargs.keys():
if type(kwargs[key]) == type(dict()):... |
"""Kata: Find the Duplicated Number in a Consecutive Unsorted List - Finds and returns
the duplicated number from the list
#1 Best Practices Solution by SquishyStrawberry
def find_dup(arr):
return (i for i in arr if arr.count(i) > 1).next()
"""
def find_dup(arr):
"""This will find the duplicated int in the ... | """Kata: Find the Duplicated Number in a Consecutive Unsorted List - Finds and returns
the duplicated number from the list
#1 Best Practices Solution by SquishyStrawberry
def find_dup(arr):
return (i for i in arr if arr.count(i) > 1).next()
"""
def find_dup(arr):
"""This will find the duplicated int in the l... |
class Calculator:
def add(self,a,b):
return a+b
def subtract(self,a,b):
return a-b
def multiply(self,a,b):
return a*b
def divide(self,a,b):
return a/b
| class Calculator:
def add(self, a, b):
return a + b
def subtract(self, a, b):
return a - b
def multiply(self, a, b):
return a * b
def divide(self, a, b):
return a / b |
"""
This package contains modules built specifically for the project in question.
Below are decribed the modules and packages used in the notebooks of this project.
Modules
-----------
polynomials:
| This module groups functions and classes for generating polynomials
| whether fitting data or directly ortogonal ... | """
This package contains modules built specifically for the project in question.
Below are decribed the modules and packages used in the notebooks of this project.
Modules
-----------
polynomials:
| This module groups functions and classes for generating polynomials
| whether fitting data or directly ortogonal ... |
start = '''You wake up one morning and find yourself in a big crisis.
Trouble has arised and your worst fears have come true. Zoom is out to destroy
the world for good. However, a castrophe has happened and now the love of
your life is in danger. Which do you decide to save today?'''
print(start)
done = False
... | start = 'You wake up one morning and find yourself in a big crisis. \nTrouble has arised and your worst fears have come true. Zoom is out to destroy\nthe world for good. However, a castrophe has happened and now the love of \nyour life is in danger. Which do you decide to save today?'
print(start)
done = False
print(" ... |
{'application':{'type':'Application',
'name':'codeEditor',
'backgrounds': [
{'type':'Background',
'name':'bgCodeEditor',
'title':'Code Editor R PythonCard Application',
'size':(400, 300),
'statusBar':1,
'visible':0,
'style':['resizeable'],
... | {'application': {'type': 'Application', 'name': 'codeEditor', 'backgrounds': [{'type': 'Background', 'name': 'bgCodeEditor', 'title': 'Code Editor R PythonCard Application', 'size': (400, 300), 'statusBar': 1, 'visible': 0, 'style': ['resizeable'], 'visible': 0, 'menubar': {'type': 'MenuBar', 'menus': [{'type': 'Menu',... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
class TimexRelativeConvert:
@staticmethod
def convert_timex_to_string_relative(timex):
return ''
| class Timexrelativeconvert:
@staticmethod
def convert_timex_to_string_relative(timex):
return '' |
#!/bin/python3
h = 0
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
if n%2 == 1:
h = 2 ** (int(n/2) + 2) - 2
elif n%2 == 0:
h = 2 ** (int(n/2) + 1) - 1
print(h) | h = 0
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
if n % 2 == 1:
h = 2 ** (int(n / 2) + 2) - 2
elif n % 2 == 0:
h = 2 ** (int(n / 2) + 1) - 1
print(h) |
#print ("Hello World")
#counties=["Arapahoes","Denver","Jefferson"]
#if counties[1]=='Denver':
# print(counties[1])
#counties = ["Arapahoe","Denver","Jefferson"]
#if "El Paso" in counties:
# print("El Paso is in the list of counties.")
#else:
# print("El Paso is not the list of counties.")
#if "Arapahoe" in ... | voting_data = [{'county': 'Arapahoe', 'registered_voters': 422829}, {'county': 'Denver', 'registered_voters': 463353}, {'county': 'Jefferson', 'registered_voters': 432438}]
for (county, voters) in voting_data:
print(f"{'county'} county has {'voters'} registered voters") |
#first exercise
#This code asks the user for hours and rate for hour, calculate total pay and print it.
hrs = input("Enter Hours:")
rate = input("Enter Rate:")
pay = float(hrs) * float(rate)
print("Pay:", pay)
#second exercise
#This code asks the user for hours and rate for hour, calculate total pay and print... | hrs = input('Enter Hours:')
rate = input('Enter Rate:')
pay = float(hrs) * float(rate)
print('Pay:', pay)
hrs = input('Enter Hours:')
rate = input('Enter Rate:')
try:
h = float(hrs)
r = float(rate)
except:
print('Insert numbers')
if h > 40:
p = 40 * r + (h - 40) * 1.5 * r
else:
p = h * r
p = float(p... |
ANGULAR_PACKAGES_CONFIG = [
("@angular/animations", struct(entry_points = ["browser"])),
("@angular/common", struct(entry_points = ["http/testing", "http", "testing"])),
("@angular/compiler", struct(entry_points = ["testing"])),
("@angular/core", struct(entry_points = ["testing"])),
("@angular/forms... | angular_packages_config = [('@angular/animations', struct(entry_points=['browser'])), ('@angular/common', struct(entry_points=['http/testing', 'http', 'testing'])), ('@angular/compiler', struct(entry_points=['testing'])), ('@angular/core', struct(entry_points=['testing'])), ('@angular/forms', struct(entry_points=[])), ... |
# Implement a class to hold room information. This should have name and
# description attributes.
class Room:
def __init__(self, number, world, name, description, enemies, enemyHP, enemy_diff, companion=[], item=[] ,enemy_description=[] ):
self.number = number
self.name = name
self.worl... | class Room:
def __init__(self, number, world, name, description, enemies, enemyHP, enemy_diff, companion=[], item=[], enemy_description=[]):
self.number = number
self.name = name
self.world = world
self.description = description
self.item = item
self.enemies = enemie... |
"""
Utility functions.
"""
def load_tf_names(path):
"""
:param path: the path of the transcription factor list file.
:return: a list of transcription factor names read from the file.
"""
with open(path) as file:
tfs_in_file = [line.strip() for line in file.readlines()]
return tfs_in_... | """
Utility functions.
"""
def load_tf_names(path):
"""
:param path: the path of the transcription factor list file.
:return: a list of transcription factor names read from the file.
"""
with open(path) as file:
tfs_in_file = [line.strip() for line in file.readlines()]
return tfs_in_fil... |
class User:
"""
Class that generates new instances of users.
"""
user_list = []
def __init__(self,tUsername,iUsername,email,sUsername):
self.tUsername=tUsername
self.iUsername=iUsername
self.email=email
self.sUsername=sUsername
def save_user(self):
Us... | class User:
"""
Class that generates new instances of users.
"""
user_list = []
def __init__(self, tUsername, iUsername, email, sUsername):
self.tUsername = tUsername
self.iUsername = iUsername
self.email = email
self.sUsername = sUsername
def save_user(self):
... |
load("//flatbuffers/internal:string_utils.bzl", "capitalize_first_char")
def _include_args_from_depset(includes_depset):
# Always include the workspace root.
include_args = ["-I", "."]
for include in includes_depset.to_list():
include_args.append("-I")
include_args.append(include)
retur... | load('//flatbuffers/internal:string_utils.bzl', 'capitalize_first_char')
def _include_args_from_depset(includes_depset):
include_args = ['-I', '.']
for include in includes_depset.to_list():
include_args.append('-I')
include_args.append(include)
return include_args
def run_flatc(ctx, fbs_to... |
# node class for develping linked list
class Node:
def __init__(self, data=None, pointer=None):
self.data = data
self.pointer = pointer
def set_data(self, data):
self.data = data
def get_data(self):
return self.data
def set_pointer(self, pointer):
... | class Node:
def __init__(self, data=None, pointer=None):
self.data = data
self.pointer = pointer
def set_data(self, data):
self.data = data
def get_data(self):
return self.data
def set_pointer(self, pointer):
self.pointer = pointer
def get_pointer(self):
... |
print("hello")
while True:
print("Infinite loop")
| print('hello')
while True:
print('Infinite loop') |
# This file is automatically generated
__version__ = '0.10.3.2'
__comments__ = """too many spaces :/
Merge pull request #1848 from swryan/work"""
__date__ = '2014-11-15 09:50:34 -0500'
__commit__ = '97c66aaecfad3451bc6a0b1cae1fce4c0595037a'
| __version__ = '0.10.3.2'
__comments__ = 'too many spaces :/\nMerge pull request #1848 from swryan/work'
__date__ = '2014-11-15 09:50:34 -0500'
__commit__ = '97c66aaecfad3451bc6a0b1cae1fce4c0595037a' |
def division(a, b):
b = float(b)
if b == 0:
c = 0
print('Cannot divide by 0.')
return c
else:
a = float(a)
c = round(a / b, 9)
return c
| def division(a, b):
b = float(b)
if b == 0:
c = 0
print('Cannot divide by 0.')
return c
else:
a = float(a)
c = round(a / b, 9)
return c |
wordle = open("Wordle.txt", "r")
wordList = []
for line in wordle:
stripped_line = line.strip()
wordList.append(stripped_line)
mutableList = []
outcomeList = []
def blackLetter(letter, list):
for word in list:
if letter in word:
list.remove(word)
def greenLetter(letter, ... | wordle = open('Wordle.txt', 'r')
word_list = []
for line in wordle:
stripped_line = line.strip()
wordList.append(stripped_line)
mutable_list = []
outcome_list = []
def black_letter(letter, list):
for word in list:
if letter in word:
list.remove(word)
def green_letter(letter, location, ... |
weight = []
diff = 0
n = int(input())
for i in range(n):
q, c = map(int, input().split())
if c == 2:
q *= -1
weight.append(q)
diff += q
min_diff = abs(diff)
for i in range(n):
if abs(diff - 2*weight[i]) < min_diff:
min_diff = abs(diff - 2*weight[i])
for j in range(i+1, n):
... | weight = []
diff = 0
n = int(input())
for i in range(n):
(q, c) = map(int, input().split())
if c == 2:
q *= -1
weight.append(q)
diff += q
min_diff = abs(diff)
for i in range(n):
if abs(diff - 2 * weight[i]) < min_diff:
min_diff = abs(diff - 2 * weight[i])
for j in range(i + 1, n)... |
"""
In HiCal, a meeting is stored as tuples of integers (start_time, end_time). /
These integers represent the number of 30-minute blocks past 9:00am. /
For example: /
(2, 3) # meeting from 10:00 - 10:30 am /
(6, 9) # meeting from 12:00 - 1:30 pm /
Write a function merge_ranges() that /
takes a list of meeting time ran... | """
In HiCal, a meeting is stored as tuples of integers (start_time, end_time). /
These integers represent the number of 30-minute blocks past 9:00am. /
For example: /
(2, 3) # meeting from 10:00 - 10:30 am /
(6, 9) # meeting from 12:00 - 1:30 pm /
Write a function merge_ranges() that /
takes a list of meeting time ran... |
def counting_sort(arr):
# Find min and max values
min_value = min(arr)
max_value = max(arr)
counting_arr = [0]*(max_value-min_value+1)
for num in arr:
counting_arr[num-min_value] += 1
index = 0
for i, count in enumerate(counting_arr):
for _ in range(count):
... | def counting_sort(arr):
min_value = min(arr)
max_value = max(arr)
counting_arr = [0] * (max_value - min_value + 1)
for num in arr:
counting_arr[num - min_value] += 1
index = 0
for (i, count) in enumerate(counting_arr):
for _ in range(count):
arr[index] = min_value + i... |
# [8 kyu] Grasshopper - Terminal Game Move Function
#
# Author: Hsins
# Date: 2019/12/20
def move(position, roll):
return position + 2 * roll
| def move(position, roll):
return position + 2 * roll |
# Go to new line using \n
print('-------------------------------------------------------')
print("My name is\nMaurizio Petrelli")
# Inserting characters using octal values
print('-------------------------------------------------------')
print("\100 \136 \137 \077 \176")
# Inserting characters using hex values
print('... | print('-------------------------------------------------------')
print('My name is\nMaurizio Petrelli')
print('-------------------------------------------------------')
print('@ ^ _ ? ~')
print('-------------------------------------------------------')
print('# $ % & *')
print('-----------------------------------------... |
class RetryOptions:
def __init__(self, firstRetry: int, maxNumber: int):
self.backoffCoefficient: int
self.maxRetryIntervalInMilliseconds: int
self.retryTimeoutInMilliseconds: int
self.firstRetryIntervalInMilliseconds: int = firstRetry
self.maxNumberOfAttempts: int = maxNumb... | class Retryoptions:
def __init__(self, firstRetry: int, maxNumber: int):
self.backoffCoefficient: int
self.maxRetryIntervalInMilliseconds: int
self.retryTimeoutInMilliseconds: int
self.firstRetryIntervalInMilliseconds: int = firstRetry
self.maxNumberOfAttempts: int = maxNumb... |
def rotations(l):
out = []
for i in range(len(l)):
a = shift(l, i)
out += [a]
return out
def shift(l, n):
return l[n:] + l[:n]
if __name__ == '__main__':
l = [0,1,2,3,4]
for x in rotations(l):
print(x) | def rotations(l):
out = []
for i in range(len(l)):
a = shift(l, i)
out += [a]
return out
def shift(l, n):
return l[n:] + l[:n]
if __name__ == '__main__':
l = [0, 1, 2, 3, 4]
for x in rotations(l):
print(x) |
class GitrackException(Exception):
"""
General giTrack's exception
"""
pass
class ConfigException(GitrackException):
"""
Exception related to Config functionality.
"""
pass
class InitializedRepoException(GitrackException):
"""
Raised when user tries to initialized repo that ... | class Gitrackexception(Exception):
"""
General giTrack's exception
"""
pass
class Configexception(GitrackException):
"""
Exception related to Config functionality.
"""
pass
class Initializedrepoexception(GitrackException):
"""
Raised when user tries to initialized repo that has... |
def make_cut(l):
smallest = min(l)
return [
x - smallest
for x
in l
if x - smallest > 0
]
length = int(input())
current = list(
map(
int,
input().split()
)
)
while current:
print(len(current))
current = make_cut(current)
| def make_cut(l):
smallest = min(l)
return [x - smallest for x in l if x - smallest > 0]
length = int(input())
current = list(map(int, input().split()))
while current:
print(len(current))
current = make_cut(current) |
#!/usr/bin/env python3
# https://codeforces.com/problemset/problem/1023/A
def f(ll):
n,k = ll #1e14
f = k//2 + 1
e = min(k-1,n)
return max(0,e-f+1)
l = list(map(int,input().split()))
print(f(l))
| def f(ll):
(n, k) = ll
f = k // 2 + 1
e = min(k - 1, n)
return max(0, e - f + 1)
l = list(map(int, input().split()))
print(f(l)) |
'rfio:///?svcClass=cmscaf&path=/castor/cern.ch/cms/store/data/Commissioning08/Cosmics/ALCARECO/CRAFT_V2P_StreamALCARECOTkAlCosmics0T_v7/0014/80C4285C-779E-DD11-9889-001617E30CA4.root',
'rfio:///?svcClass=cmscaf&path=/castor/cern.ch/cms/store/data/Commissioning08/Cosmics/ALCARECO/CRAFT_V2P_StreamALCARECOTkAlCosmics0T_v7... | ('rfio:///?svcClass=cmscaf&path=/castor/cern.ch/cms/store/data/Commissioning08/Cosmics/ALCARECO/CRAFT_V2P_StreamALCARECOTkAlCosmics0T_v7/0014/80C4285C-779E-DD11-9889-001617E30CA4.root',)
('rfio:///?svcClass=cmscaf&path=/castor/cern.ch/cms/store/data/Commissioning08/Cosmics/ALCARECO/CRAFT_V2P_StreamALCARECOTkAlCosmics0T... |
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def deno_repository():
# Get Deno archive
http_archive(
name = "deno-amd64",
build_file = "//ext/deno:BUILD",
sha256 = "7b883e3c638d21dd1875f0108819f2f13647b866ff24965135e679c743013f46",
type = "zip",
u... | load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
def deno_repository():
http_archive(name='deno-amd64', build_file='//ext/deno:BUILD', sha256='7b883e3c638d21dd1875f0108819f2f13647b866ff24965135e679c743013f46', type='zip', urls=['https://github.com/denoland/deno/releases/download/v1.17.3/deno-x8... |
# 127. Word Ladder
# ttungl@gmail.com
# Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
# Only one letter can be changed at a time.
# Each transformed word must exist in the word list. Note that beginWord i... | class Solution(object):
def ladder_length(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
word_list = set(wordList)
queue = collections.deque([(beginWord, 1)])
while qu... |
class Allergies(object):
ALLERGY_SCORES = {
'eggs': 1,
'peanuts': 2,
'shellfish': 4,
'strawberries': 8,
'tomatoes': 16,
'chocolate': 32,
'pollen': 64,
'cats': 128
}
def __init__(self, score):
if score is None or not isinstance(score, i... | class Allergies(object):
allergy_scores = {'eggs': 1, 'peanuts': 2, 'shellfish': 4, 'strawberries': 8, 'tomatoes': 16, 'chocolate': 32, 'pollen': 64, 'cats': 128}
def __init__(self, score):
if score is None or not isinstance(score, int):
raise type_error('Score must be an integer')
... |
# Do not edit this file directly.
# It was auto-generated by: code/programs/reflexivity/reflexive_refresh
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file")
def libevent():
http_archive(
name = "libevent",
build_fi... | load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_file')
def libevent():
http_archive(name='libevent', build_file='//bazel/deps/libevent:build.BUILD', sha256='9b436b404793be621c6e01cea573e1a06b5db26dad25a11c6a8c6f8526ed264c', strip_prefi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 21 08:20:55 2021
@author: silasjimmy
"""
def count_words(s, n):
s = s.split(' ')
counted_words = [(w, s.count((w))) for w in set(s)]
counted_words.sort(key = lambda x: (-x[1], x[0]))
top_n = counted_words[:n]
return top_n
def t... | """
Created on Thu Jan 21 08:20:55 2021
@author: silasjimmy
"""
def count_words(s, n):
s = s.split(' ')
counted_words = [(w, s.count(w)) for w in set(s)]
counted_words.sort(key=lambda x: (-x[1], x[0]))
top_n = counted_words[:n]
return top_n
def test_run():
print(count_words('cat bat mat cat b... |
# jumlah segitiga
n = 123
# panjang alas sebuah segitiga
alas = 30
# tinggi sebuah segitiga
tinggi = 18
# hitung luas sebuah segitiga
luas = alas * tinggi * 1/2
# hitung luas total
luastotal = n * luas
print('luas total : ', luastotal,'satuan luas') | n = 123
alas = 30
tinggi = 18
luas = alas * tinggi * 1 / 2
luastotal = n * luas
print('luas total : ', luastotal, 'satuan luas') |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Li... | class Partitioner(object):
"""
Base class for a partitioner
"""
def __init__(self, partitions):
"""
Initialize the partitioner
Arguments:
partitions: A list of available partitions (during startup)
"""
self.partitions = partitions
def partition(... |
# http://codingbat.com/prob/p193507
def string_times(str, n):
result = ""
for i in range(0, n):
result += str
return result
| def string_times(str, n):
result = ''
for i in range(0, n):
result += str
return result |
def alternate_case(s):
# Like a Giga Chad
return "".join([char.lower() if char.isupper() else char.upper() for char in s])
# Like a Beta Male
# return s.swapcase()
# EXAMPLE AND TESTING #
input = ["Hello World", "cODEwARS"]
for item in input:
print("\nInput: {0}\nAlternate Case: {1}".format(item,... | def alternate_case(s):
return ''.join([char.lower() if char.isupper() else char.upper() for char in s])
input = ['Hello World', 'cODEwARS']
for item in input:
print('\nInput: {0}\nAlternate Case: {1}'.format(item, alternate_case(item)))
assert alternate_case('Hello World') == 'hELLO wORLD'
assert alternate_case... |
"""A json-like master list of workflows and steps."""
# NOTE: Create a json-like dictionary in the form of:
# WF_STEPS = {
# env1: {
# 1st condition defined in next_steps: {
# 2nd condition defined in next_steps: (Workflow Name, Step Name),
# },
# },
# }
WF_STEPS = {}
| """A json-like master list of workflows and steps."""
wf_steps = {} |
#!/usr/bin/python3
list = ["Armitage", "Backdoor Factory", "BeEF","cisco-auditing-tool",
"cisco-global-exploiter","cisco-ocs","cisco-torch","Commix","crackle",
"exploitdb","jboss-autopwn","Linux Exploit Suggester","Maltego Teeth",
"Metasploit Framework","MSFPC","RouterSploit","SET","ShellNoob","sqlmap",
"THC-IPV6","Ye... | list = ['Armitage', 'Backdoor Factory', 'BeEF', 'cisco-auditing-tool', 'cisco-global-exploiter', 'cisco-ocs', 'cisco-torch', 'Commix', 'crackle', 'exploitdb', 'jboss-autopwn', 'Linux Exploit Suggester', 'Maltego Teeth', 'Metasploit Framework', 'MSFPC', 'RouterSploit', 'SET', 'ShellNoob', 'sqlmap', 'THC-IPV6', 'Yersinia... |
def get_max_coins_helper(matrix, crow, ccol, rows, cols):
cval = matrix[crow][ccol]
if crow == rows - 1 and ccol == cols - 1:
return cval
down, right = cval, cval
if crow < rows - 1:
down += get_max_coins_helper(
matrix, crow + 1, ccol, rows, cols)
if ccol < cols - 1:
... | def get_max_coins_helper(matrix, crow, ccol, rows, cols):
cval = matrix[crow][ccol]
if crow == rows - 1 and ccol == cols - 1:
return cval
(down, right) = (cval, cval)
if crow < rows - 1:
down += get_max_coins_helper(matrix, crow + 1, ccol, rows, cols)
if ccol < cols - 1:
righ... |
class NEC:
def __init__( self ):
self.prompt = '(.*)'
self.timeout = 60
def show(self, *options, **def_args ):
'''Possible Options :[' access-filter ', ' accounting ', ' acknowledgments ', ' auto-config ', ' axrp ', ' cfm ', ' channel-group ', ' clock ', ' config-lock-s... | class Nec:
def __init__(self):
self.prompt = '(.*)'
self.timeout = 60
def show(self, *options, **def_args):
"""Possible Options :[' access-filter ', ' accounting ', ' acknowledgments ', ' auto-config ', ' axrp ', ' cfm ', ' channel-group ', ' clock ', ' config-lock-sta... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = 'CwT'
# document.body.innerHTML += '<form id="dynForm" action="http://example.com/" method="post">
# <input type="hidden" name="q" value="a"></form>';
# document.getElementById("dynForm").submit();
POST_JS = '<form id=\\"dynamicform\\" action=\\"%s\\" met... | post_js = '<form id=\\"dynamicform\\" action=\\"%s\\" method=\\"post\\">%s</form>'
input_js = '<input type=\\"hidden\\" name=\\"%s\\" value=%s>'
execute_js = 'document.body.innerHTML = "%s"; document.getElementById("dynamicform").submit();'
def post_js(url, data):
input = ''
for (key, value) in data.items():
... |
# data hiding - encapsulation
# this can be achieve by making the attribute or method private
# python doesn't have private keyword so precede
# the attribute/method identifier with an underscore or a double
# this is more effective if object in import or used as a module
# it isn't that effective
# no underscore = pu... | class Person:
__name = ''
__age = 0
def __init__(self, name, age):
self.__name = name
self.__age = age
me = person('John Doe', 32)
print(me._Person__name) |
# Instruksi:
# Buatlah komentar di garis pertama,
# Buat variabel bernama jumlah_pacar yang isinya angka (bukan desimal),
# Buat variabel bernama lagi_galau yang isinya boolean,
# Buat variabel dengan nama terserah anda dan gunakan salah satu dari operator matematika yang telah kita pelajari.
#variabel untuk menyimpan... | jumlah_pacar = 1
lagi_galau = False
umur = 20 |
# About: Implementation of the accumulator program
# in python 3 specialization
# ask to enter string
phrase = input("Enter a string: ")
# initialize total variable with zero
tot = 0
# iterate through the string
for char in phrase :
if char != " " :
tot += 1
# print the result
print(tot) | phrase = input('Enter a string: ')
tot = 0
for char in phrase:
if char != ' ':
tot += 1
print(tot) |
class MapHash:
def __init__(self, maxsize=6):
self.maxsize = maxsize # Real scenario 64.
self.hash = [None] * self.maxsize # Will be a 2D list
def _get_hash_key(self, key):
hash = sum(ord(k) for k in key)
return hash % self.maxsize
def add(self, key, value)... | class Maphash:
def __init__(self, maxsize=6):
self.maxsize = maxsize
self.hash = [None] * self.maxsize
def _get_hash_key(self, key):
hash = sum((ord(k) for k in key))
return hash % self.maxsize
def add(self, key, value):
hash_key = self._get_hash_key(key)
h... |
#Refer AlexNet implementation code, returns last fully connected layer
fc7 = AlexNet(resized, feature_extract=True)
shape = (fc7.get_shape().as_list()[-1], 43)
fc8_weight = tf.Variable(tf.truncated_normal(shape, stddev=1e-2))
fc8_b = tf.Variable(tf.zeros(43))
logits = tf.nn.xw_plus_b(fc7, fc8_weight, fc8_b)
probs = tf.... | fc7 = alex_net(resized, feature_extract=True)
shape = (fc7.get_shape().as_list()[-1], 43)
fc8_weight = tf.Variable(tf.truncated_normal(shape, stddev=0.01))
fc8_b = tf.Variable(tf.zeros(43))
logits = tf.nn.xw_plus_b(fc7, fc8_weight, fc8_b)
probs = tf.nn.softmax(logits) |
def isSubsetSum(arr, n, sum):
'''
Returns true if there exists a subset
with given sum in arr[]
'''
# The value of subset[i%2][j] will be true
# if there exists a subset of sum j in
# arr[0, 1, ...., i-1]
subset = [[False for j in range(sum + 1)] for i in range(3)]
for i in range(n... | def is_subset_sum(arr, n, sum):
"""
Returns true if there exists a subset
with given sum in arr[]
"""
subset = [[False for j in range(sum + 1)] for i in range(3)]
for i in range(n + 1):
for j in range(sum + 1):
if j == 0:
subset[i % 2][j] = True
el... |
tup = ('a','b',1,2,3)
print(tup[0])
print(tup[1])
print(tup[2])
print(tup[3])
print(tup[4])
| tup = ('a', 'b', 1, 2, 3)
print(tup[0])
print(tup[1])
print(tup[2])
print(tup[3])
print(tup[4]) |
class Solution:
def XXX(self, nums: List[int]) -> List[List[int]]:
final = list()
# ----------------------------------------------------
if len(nums)==1:
return [[],nums]
if len(nums)==0:
return []
# ----------------------------------------------------... | class Solution:
def xxx(self, nums: List[int]) -> List[List[int]]:
final = list()
if len(nums) == 1:
return [[], nums]
if len(nums) == 0:
return []
def pop(cut):
if not cut:
return
else:
for i in range(... |
# -*- coding: utf-8 -*-
# @Time: 2020/7/3 10:21
# @Author: GraceKoo
# @File: interview_33.py
# @Desc: https://leetcode-cn.com/problems/chou-shu-lcof/
class Solution:
def nthUglyNumber(self, n: int) -> int:
if n <= 0:
return 0
dp, a, b, c = [1] * n, 0, 0, 0
for i in range(1, n):... | class Solution:
def nth_ugly_number(self, n: int) -> int:
if n <= 0:
return 0
(dp, a, b, c) = ([1] * n, 0, 0, 0)
for i in range(1, n):
min_ugly = min(dp[a] * 2, dp[b] * 3, dp[c] * 5)
dp[i] = min_ugly
if min_ugly == dp[a] * 2:
a... |
# Solution for the SafeCracker 50 Puzzle from Creative Crafthouse
# By: Eric Pollinger
# 9/11/2016
#
# Function to handle the addition of a given slice
def add(slice):
if row1Outer[(index1 + slice) % 16] != -1:
valRow1 = row1Outer[(index1 + slice) % 16]
else:
valRow1 = row0Inner[slice]
... | def add(slice):
if row1Outer[(index1 + slice) % 16] != -1:
val_row1 = row1Outer[(index1 + slice) % 16]
else:
val_row1 = row0Inner[slice]
if row2Outer[(index2 + slice) % 16] != -1:
val_row2 = row2Outer[(index2 + slice) % 16]
else:
val_row2 = row1Inner[(index1 + slice) % 16... |
# test __getattr__ on module
# ensure that does_not_exist doesn't exist to start with
this = __import__(__name__)
try:
this.does_not_exist
assert False
except AttributeError:
pass
# define __getattr__
def __getattr__(attr):
if attr == 'does_not_exist':
return False
raise AttributeError
# ... | this = __import__(__name__)
try:
this.does_not_exist
assert False
except AttributeError:
pass
def __getattr__(attr):
if attr == 'does_not_exist':
return False
raise AttributeError
if not hasattr(this, 'does_not_exist'):
print('SKIP')
raise SystemExit
print(this.does_not_exist) |
#Cristian Chitiva
#cychitivav@unal.edu.co
#12/Sept/2018
myList = ['Hi', 5, 6 , 3.4, "i"] #Create the list
myList.append([4, 5]) #Add sublist [4, 5] to myList
myList.insert(2,"f") #Add "f" in the position 2
print(myList)
myList = [1, 3, 4, 5, 23, 4, 3, 222, 454, 6445, 6, 4654, 455]
myList.sort() #So... | my_list = ['Hi', 5, 6, 3.4, 'i']
myList.append([4, 5])
myList.insert(2, 'f')
print(myList)
my_list = [1, 3, 4, 5, 23, 4, 3, 222, 454, 6445, 6, 4654, 455]
myList.sort()
print(myList)
myList.sort(reverse=True)
print(myList)
myList.extend([5, 77])
print(myList)
my_list = []
for value in range(0, 50):
myList.append(val... |
"""
File: largest_digit.py
Name:
----------------------------------
This file recursively prints the biggest digit in
5 different integers, 12345, 281, 6, -111, -9453
If your implementation is correct, you should see
5, 8, 6, 1, 9 on Console.
"""
def main():
print(find_largest_digit(12345)) # 5
print(find_larg... | """
File: largest_digit.py
Name:
----------------------------------
This file recursively prints the biggest digit in
5 different integers, 12345, 281, 6, -111, -9453
If your implementation is correct, you should see
5, 8, 6, 1, 9 on Console.
"""
def main():
print(find_largest_digit(12345))
print(find_largest_... |
sample = ["abc", "xyz", "aba", "1221"]
def stringCounter(items):
amount = 0
for i in items:
if len(i) >= 2 and i[0] == i[-1]:
amount += 1
return amount
print("The amount of string that meet the criteria is:",stringCounter(sample)) | sample = ['abc', 'xyz', 'aba', '1221']
def string_counter(items):
amount = 0
for i in items:
if len(i) >= 2 and i[0] == i[-1]:
amount += 1
return amount
print('The amount of string that meet the criteria is:', string_counter(sample)) |
# Uri Online Judge 1079
N = int(input())
for i in range(0,N):
Numbers = input()
num1 = float(Numbers.split()[0])
num2 = float(Numbers.split()[1])
num3 = float(Numbers.split()[2])
print(((2*num1+3*num2+5*num3)/10).__round__(1)) | n = int(input())
for i in range(0, N):
numbers = input()
num1 = float(Numbers.split()[0])
num2 = float(Numbers.split()[1])
num3 = float(Numbers.split()[2])
print(((2 * num1 + 3 * num2 + 5 * num3) / 10).__round__(1)) |
entity_id = data.get('entity_id')
command = data.get('command')
params = str(data.get('params'))
parsedParams = []
for z in params.replace(' ', '').replace('],[', '|').replace('[', '').replace(']', '').split('|'):
rect = []
for c in z.split(','):
rect.append(int(c))
parsedParams.append(rect)
if co... | entity_id = data.get('entity_id')
command = data.get('command')
params = str(data.get('params'))
parsed_params = []
for z in params.replace(' ', '').replace('],[', '|').replace('[', '').replace(']', '').split('|'):
rect = []
for c in z.split(','):
rect.append(int(c))
parsedParams.append(rect)
if com... |
def rank_filter(func):
def func_filter(local_rank=-1, *args, **kwargs):
if local_rank < 1:
return func(*args, **kwargs)
else:
pass
return func_filter
| def rank_filter(func):
def func_filter(local_rank=-1, *args, **kwargs):
if local_rank < 1:
return func(*args, **kwargs)
else:
pass
return func_filter |
tot=coe=rat=sap=0
for i in range(int(input())):
n,s=input().split()
n=int(n)
tot+=n
if s=='C':coe+=n
elif s=='R':rat+=n
elif s=='S':sap+=n
print(f"Total: {tot} cobaias\nTotal de coelhos: {coe}\nTotal de ratos: {rat}\nTotal de sapos: {sap}")
p=(coe/tot)*100
print("Percentual de coelhos: %.2f"%p,e... | tot = coe = rat = sap = 0
for i in range(int(input())):
(n, s) = input().split()
n = int(n)
tot += n
if s == 'C':
coe += n
elif s == 'R':
rat += n
elif s == 'S':
sap += n
print(f'Total: {tot} cobaias\nTotal de coelhos: {coe}\nTotal de ratos: {rat}\nTotal de sapos: {sap}')... |
[ ## this file was manually modified by jt
{
'functor' : {
'description' : [ "The function always returns a value of the same type than the entry.",
"Take care that for integers the value returned can differ by one unit",
"from \c ceil((a+b)/2.0) o... | [{'functor': {'description': ['The function always returns a value of the same type than the entry.', 'Take care that for integers the value returned can differ by one unit', 'from \\c ceil((a+b)/2.0) or \\c floor((a+b)/2.0), but is always one of', 'the two'], 'module': 'boost', 'arity': '2', 'call_types': [], 'ret_ari... |
def extract_to_m2(filename, annot_triples):
"""
Extracts error detection annotations in m2 file format
Args:
filename: the output m2 file
annot_triples: the annotations of form (sentence, indexes, selections)
"""
with open(filename, 'w+') as m2_file:
for triple in annot_tripl... | def extract_to_m2(filename, annot_triples):
"""
Extracts error detection annotations in m2 file format
Args:
filename: the output m2 file
annot_triples: the annotations of form (sentence, indexes, selections)
"""
with open(filename, 'w+') as m2_file:
for triple in annot_triples... |
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
n = int(input())
start = list(map(int, inpu... | """
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
n = int(input())
start = list(map(int, input().strip().split()))
fi... |
#!/usr/bin/env python3
"""
Source Code of Pdiskuploaderbot
"""
| """
Source Code of Pdiskuploaderbot
""" |
# Audit Event Outcomes
AUDIT_SUCCESS = "0"
AUDIT_MINOR_FAILURE = "4"
AUDIT_SERIOUS_FAILURE = "8"
AUDIT_MAJOR_FAILURE = "12"
| audit_success = '0'
audit_minor_failure = '4'
audit_serious_failure = '8'
audit_major_failure = '12' |
"""All plugging called to check norm for a C file."""
__all__ = [
"columns",
"comma",
"function_line",
"indent",
"libc_func",
"nested_branches",
"number_function",
"parenthesis",
"preprocessor",
"snake_case",
"solo_space",
"statements",
"trailing_newline",
"two_sp... | """All plugging called to check norm for a C file."""
__all__ = ['columns', 'comma', 'function_line', 'indent', 'libc_func', 'nested_branches', 'number_function', 'parenthesis', 'preprocessor', 'snake_case', 'solo_space', 'statements', 'trailing_newline', 'two_space', 'operators', 'newline_at_end_of_file', 'subscriptor... |
#771. Jewels and Stones
class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
# count = 0
# jewl = {}
# for i in jewels:
# if i not in jewl:
# jewl[i] = 0
# for j in stones:
# if j in jewl:
# count += 1
... | class Solution:
def num_jewels_in_stones(self, jewels: str, stones: str) -> int:
count = 0
jewl = set(jewels)
for s in stones:
if s in jewl:
count += 1
return count |
class MaxPQ:
def __init__(self):
self.pq = []
def insert(self, v):
self.pq.append(v)
self.swim(len(self.pq) - 1)
def max(self):
return self.pq[0]
def del_max(self, ):
m = self.pq[0]
self.pq[0], self.pq[-1] = self.pq[-1], self.pq[0]
self.pq = se... | class Maxpq:
def __init__(self):
self.pq = []
def insert(self, v):
self.pq.append(v)
self.swim(len(self.pq) - 1)
def max(self):
return self.pq[0]
def del_max(self):
m = self.pq[0]
(self.pq[0], self.pq[-1]) = (self.pq[-1], self.pq[0])
self.pq = ... |
class Song:
"A class for representing a song"
def __init__(self, name, singer):
"""
Initialize a new song with it's name and singer
:param name: str
:param singer: str
"""
self.name = name
self.singer = singer
self.mood = self.mood()
def text... | class Song:
"""A class for representing a song"""
def __init__(self, name, singer):
"""
Initialize a new song with it's name and singer
:param name: str
:param singer: str
"""
self.name = name
self.singer = singer
self.mood = self.mood()
def ... |
BOT_TOKEN: str = "ODg4MzAyMzkwNTMxNDg1Njk2.YUQuEQ.UO4oyY9Zk4u1W5f-VpPLkkQ70TM"
SPOTIFY_ID: str = ""
SPOTIFY_SECRET: str = ""
BOT_PREFIX = "$"
EMBED_COLOR = 0x4dd4d0 #replace after'0x' with desired hex code ex. '#ff0188' >> '0xff0188'
SUPPORTED_EXTENSIONS = ('.webm', '.mp4', '.mp3', '.avi', '.wav', '.m4v', '.ogg', '... | bot_token: str = 'ODg4MzAyMzkwNTMxNDg1Njk2.YUQuEQ.UO4oyY9Zk4u1W5f-VpPLkkQ70TM'
spotify_id: str = ''
spotify_secret: str = ''
bot_prefix = '$'
embed_color = 5100752
supported_extensions = ('.webm', '.mp4', '.mp3', '.avi', '.wav', '.m4v', '.ogg', '.mov')
max_song_preload = 5
cookie_path = '/config/cookies/cookies.txt'
gl... |
"""
An edge is a bridge if, after removing it count of connected components in graph will
be increased by one. Bridges represent vulnerabilities in a connected network and are
useful for designing reliable networks. For example, in a wired computer network, an
articulation point indicates the critical computers and a b... | """
An edge is a bridge if, after removing it count of connected components in graph will
be increased by one. Bridges represent vulnerabilities in a connected network and are
useful for designing reliable networks. For example, in a wired computer network, an
articulation point indicates the critical computers and a b... |
class BRepBuilderGeometryId(object,IDisposable):
"""
This class is used by the BRepBuilder class to identify objects it creates (faces,edges,etc.).
BRepBuilderGeometryId(other: BRepBuilderGeometryId)
"""
def Dispose(self):
""" Dispose(self: BRepBuilderGeometryId) """
pass
@staticmethod
def Inva... | class Brepbuildergeometryid(object, IDisposable):
"""
This class is used by the BRepBuilder class to identify objects it creates (faces,edges,etc.).
BRepBuilderGeometryId(other: BRepBuilderGeometryId)
"""
def dispose(self):
""" Dispose(self: BRepBuilderGeometryId) """
pass
@staticme... |
class IncompatibleAttribute(Exception):
pass
class IncompatibleDataException(Exception):
pass
class UndefinedROI(Exception):
pass
class InvalidSubscriber(Exception):
pass
class InvalidMessage(Exception):
pass
| class Incompatibleattribute(Exception):
pass
class Incompatibledataexception(Exception):
pass
class Undefinedroi(Exception):
pass
class Invalidsubscriber(Exception):
pass
class Invalidmessage(Exception):
pass |
def create_bag_of_centroids(wordlist, word_centroid_map):
"""
a function to create bags of centroids
"""
# The number of clusters is equal to the highest cluster index in the word / centroid map
num_centroids = max( word_centroid_map.values() ) + 1
# Pre-allocate the bag of centro... | def create_bag_of_centroids(wordlist, word_centroid_map):
"""
a function to create bags of centroids
"""
num_centroids = max(word_centroid_map.values()) + 1
bag_of_centroids = np.zeros(num_centroids, dtype='float32')
for word in wordlist:
if word in word_centroid_map:
ind... |
# Enter script code
message = "kubectl exec -it <cursor> -- bash"
keyboard.send_keys("kubectl exec -it ")
keyboard.send_keys("<shift>+<ctrl>+v")
time.sleep(0.1)
keyboard.send_keys(" -- bash")
| message = 'kubectl exec -it <cursor> -- bash'
keyboard.send_keys('kubectl exec -it ')
keyboard.send_keys('<shift>+<ctrl>+v')
time.sleep(0.1)
keyboard.send_keys(' -- bash') |
'''
Topic : Algorithms
Subtopic : Diagonal Difference
Language : Python
Problem Statement : Given a square matrix, calculate the absolute difference between the sums of its diagonals.
Url : https://www.hackerrank.com/challenges/diagonal-difference/problem
'''
#!/bin/python3
# Complete the 'diagonalD... | """
Topic : Algorithms
Subtopic : Diagonal Difference
Language : Python
Problem Statement : Given a square matrix, calculate the absolute difference between the sums of its diagonals.
Url : https://www.hackerrank.com/challenges/diagonal-difference/problem
"""
def diagonal_difference(arr):
n = l... |
class ParsnipException(Exception):
def __init__(self, msg, webtexter=None):
self.args = (msg, webtexter)
self.msg = msg
self.webtexter = webtexter
def __str__(self):
return repr("[%s] %s - %s" % (self.webtexter.NETWORK_NAME, self.webtexter.phone_number, self.msg))
class LoginError(ParsnipException):pa... | class Parsnipexception(Exception):
def __init__(self, msg, webtexter=None):
self.args = (msg, webtexter)
self.msg = msg
self.webtexter = webtexter
def __str__(self):
return repr('[%s] %s - %s' % (self.webtexter.NETWORK_NAME, self.webtexter.phone_number, self.msg))
class Logine... |
def soma(x,y):
return print(x + y)
def sub(x,y):
return print(x - y)
def mult(x,y):
return print(x * y)
def div(x,y):
return print(x / y)
soma(3,8)
sub(10,5)
mult(3,9)
div(15,7) | def soma(x, y):
return print(x + y)
def sub(x, y):
return print(x - y)
def mult(x, y):
return print(x * y)
def div(x, y):
return print(x / y)
soma(3, 8)
sub(10, 5)
mult(3, 9)
div(15, 7) |
class DeviceLog:
def __init__(self, deviceId, deviceName, temperature, location, recordDate):
self.deviceId = deviceId
self.deviceName = deviceName
self.temperature = temperature
self.location = location
self.recordDate = recordDate
def getStatus(self):
if self.t... | class Devicelog:
def __init__(self, deviceId, deviceName, temperature, location, recordDate):
self.deviceId = deviceId
self.deviceName = deviceName
self.temperature = temperature
self.location = location
self.recordDate = recordDate
def get_status(self):
if self... |
class NeighborResult:
def __init__(self):
self.solutions = []
self.choose_path = []
self.current_num = 0
self.curr_solved_gates = []
| class Neighborresult:
def __init__(self):
self.solutions = []
self.choose_path = []
self.current_num = 0
self.curr_solved_gates = [] |
'''
@brief this class reflect action decision regarding condition
'''
class EventAction():
'''
@brief build event action
@param cond the conditions to perform the action
@param to the target state if any
@param job the job to do if any
'''
def __init__(self, cond="", to=... | """
@brief this class reflect action decision regarding condition
"""
class Eventaction:
"""
@brief build event action
@param cond the conditions to perform the action
@param to the target state if any
@param job the job to do if any
"""
def __init__(self, cond='', to='... |
quedex_public_key = """-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1
mQENBFlPvjsBCACr/UfHzXAezskLqcq9NiiaNFDDT5A+biC8VrOglB0ZSQOYRira
NgQ2Cp8Jd+XU77F+J1012BjB5y87Z+hdnwBDsqF7CjkjeQzsE3PSvm9I+E3cneqx
UcinRaUD1wfwVytbg9Q9rpqQ7CTjVWY1UPYjs6dAo1WAp/ux/VTeOFbpO0R3D7if
ZGY1QeISRpLWiMpcG2YCOALnuazABVCNXLhVqa8Y7tt2I... | quedex_public_key = '-----BEGIN PGP PUBLIC KEY BLOCK-----\nVersion: GnuPG v1\n\nmQENBFlPvjsBCACr/UfHzXAezskLqcq9NiiaNFDDT5A+biC8VrOglB0ZSQOYRira\nNgQ2Cp8Jd+XU77F+J1012BjB5y87Z+hdnwBDsqF7CjkjeQzsE3PSvm9I+E3cneqx\nUcinRaUD1wfwVytbg9Q9rpqQ7CTjVWY1UPYjs6dAo1WAp/ux/VTeOFbpO0R3D7if\nZGY1QeISRpLWiMpcG2YCOALnuazABVCNXLhVqa8Y7t... |
age = int(input("How old are you ?"))
#if age >= 16 and age <= 65:
#if 16 <= age <= 65:
if age in range(16,66):
print ("Have a good day at work.")
elif age > 100 or age <= 0:
print ("Nice Try. This program is not dumb.")
endkey = input ("Press enter to exit")
else:
print (f"Enjoy your free time, ... | age = int(input('How old are you ?'))
if age in range(16, 66):
print('Have a good day at work.')
elif age > 100 or age <= 0:
print('Nice Try. This program is not dumb.')
endkey = input('Press enter to exit')
else:
print(f'Enjoy your free time, you need to work for us after {65 - age} years.')
print('-' ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.