content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Preprocessor:
def __init__(self, title):
self.title = title
def evaluate(self, value):
return value
| class Preprocessor:
def __init__(self, title):
self.title = title
def evaluate(self, value):
return value |
s=input()
li=list(map(int,s.split(' ')))
while(li!=sorted(li)):
n=(len(li)//2)
for i in range(n):
li.pop()
print(li)
| s = input()
li = list(map(int, s.split(' ')))
while li != sorted(li):
n = len(li) // 2
for i in range(n):
li.pop()
print(li) |
#!/usr/bin/env python3
#Take a list, say for example this one: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] and write a program that prints out all the elements of the list that are less than 5.
#Extras:
#Instead of printing the elements one by one, make a new list that has all the elements less than 5 from this list in... | list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
num = int(input('Enter a number for comparison: '))
print('numbers less than %d are: ' % num)
print([element for element in list if element < num]) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 18 11:53:23 2020
@author: chris
"""
__version__ = "0.3.2"
__status__ = "Alpha"
| """
Created on Sat Apr 18 11:53:23 2020
@author: chris
"""
__version__ = '0.3.2'
__status__ = 'Alpha' |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 15 01:38:54 2020
@author: abhi0
"""
class Solution:
def numTimesAllBlue(self, light: List[int]) -> int:
tempLight=sorted(light)
cnt=0
sum1=0
sum2=0
for i in range(len(light)):
sum1=sum1+light[i]
... | """
Created on Tue Sep 15 01:38:54 2020
@author: abhi0
"""
class Solution:
def num_times_all_blue(self, light: List[int]) -> int:
temp_light = sorted(light)
cnt = 0
sum1 = 0
sum2 = 0
for i in range(len(light)):
sum1 = sum1 + light[i]
sum2 = sum2 + t... |
#! /usr/bin/python3
# p76
print("Let's preatice everything.")
print("You\'d need to know \'about escapes with \\ that do \n newlines and \t tabs.")
poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhe... | print("Let's preatice everything.")
print("You'd need to know 'about escapes with \\ that do \n newlines and \t tabs.")
poem = '\n\tThe lovely world\nwith logic so firmly planted\ncannot discern \n the needs of love\nnor comprehend passion from intuition\nand requires an explanation\n\n\t\twhere there is none.\n'
print... |
#
# Example file for working with loops
#
def main():
x = 0
# define a while loop
while (x<5):
print(x)
x+=1
# define a for loop
for i in range(5):
x -= 1
print(x)
# use a for loop over a collection
days = ["Mon","Tue","Wed",\
"Thurs","Fri","Sat","Sun"]
for day in days:
... | def main():
x = 0
while x < 5:
print(x)
x += 1
for i in range(5):
x -= 1
print(x)
days = ['Mon', 'Tue', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun']
for day in days:
print(day)
for day in days:
if day == 'Wed':
continue
if day == 'Fri':... |
def solution(S):
hash1 = dict()
count = 0
ans = -0
ans_final = 0
if(len(S)==1):
print("0")
pass
else:
for i in range(len(S)):
#print(S[i])
if(S[i] in hash1):
#print("T")
value = hash1[S[i]]
hash1[S[i]] = i
if(value > i):
ans = value - i
count = 0
else:
ans = i - va... | def solution(S):
hash1 = dict()
count = 0
ans = -0
ans_final = 0
if len(S) == 1:
print('0')
pass
else:
for i in range(len(S)):
if S[i] in hash1:
value = hash1[S[i]]
hash1[S[i]] = i
if value > i:
... |
Size = (400, 400)
Position = (0, 0)
ScaleFactor = 1.0
ZoomLevel = 50.0
Orientation = 0
Mirror = 0
NominalPixelSize = 0.12237
filename = ''
ImageWindow.Center = None
ImageWindow.ViewportCenter = (1.4121498000000001, 1.2090156)
ImageWindow.crosshair_color = (255, 0, 255)
ImageWindow.boxsize = (0.1, 0.06)
ImageWindow.box_... | size = (400, 400)
position = (0, 0)
scale_factor = 1.0
zoom_level = 50.0
orientation = 0
mirror = 0
nominal_pixel_size = 0.12237
filename = ''
ImageWindow.Center = None
ImageWindow.ViewportCenter = (1.4121498000000001, 1.2090156)
ImageWindow.crosshair_color = (255, 0, 255)
ImageWindow.boxsize = (0.1, 0.06)
ImageWindow.... |
# Project Euler Problem 7- 10001st prime
# https://projecteuler.net/problem=7
# Answer = 104743
def is_prime(num):
for i in range(2, num):
if (num % i) == 0:
return False
return True
def prime_list():
prime_list = []
num = 2
while True:
if is_prime(num):
p... | def is_prime(num):
for i in range(2, num):
if num % i == 0:
return False
return True
def prime_list():
prime_list = []
num = 2
while True:
if is_prime(num):
prime_list.append(num)
if len(prime_list) == 10001:
return prime_list[-1]
... |
# Approach 2 - Greedy with Stack
# Time: O(N)
# Space: O(N)
class Solution:
def removeKdigits(self, num: str, k: int) -> str:
num_stack = []
for digit in num:
while k and num_stack and num_stack[-1] > digit:
num_stack.pop()
k -= 1
... | class Solution:
def remove_kdigits(self, num: str, k: int) -> str:
num_stack = []
for digit in num:
while k and num_stack and (num_stack[-1] > digit):
num_stack.pop()
k -= 1
num_stack.append(digit)
final_stack = num_stack[:-k] if k els... |
def get_keys(filename):
with open(filename) as f:
data = f.read()
doc = data.split("\n")
res = []
li = []
for i in doc:
if i != "":
li.append(i)
else:
res.append(li)
li=[]
return res
if __name__=="__main__":
filename = './input.txt'
input = get_keys(filen... | def get_keys(filename):
with open(filename) as f:
data = f.read()
doc = data.split('\n')
res = []
li = []
for i in doc:
if i != '':
li.append(i)
else:
res.append(li)
li = []
return res
if __name__ == ... |
expected_output = {
"mac_table": {
"vlans": {
"100": {
"mac_addresses": {
"ecbd.1dff.5f92": {
"drop": {"drop": True, "entry_type": "dynamic"},
"mac_address": "ecbd.1dff.5f92",
},
... | expected_output = {'mac_table': {'vlans': {'100': {'mac_addresses': {'ecbd.1dff.5f92': {'drop': {'drop': True, 'entry_type': 'dynamic'}, 'mac_address': 'ecbd.1dff.5f92'}, '3820.56ff.6f75': {'interfaces': {'Port-channel12': {'interface': 'Port-channel12', 'entry_type': 'dynamic'}}, 'mac_address': '3820.56ff.6f75'}, '58b... |
"""
This module contains the default settings that stand unless overridden.
"""
#
## Gateway Daemon Settings
#
# Default port to listen for HTTP uploads on.
GATEWAY_WEB_PORT = 8080
# PUB - Connect
GATEWAY_SENDER_BINDINGS = ["ipc:///tmp/announcer-receiver.sock"]
# If set as a string, this value is used as the salt to ... | """
This module contains the default settings that stand unless overridden.
"""
gateway_web_port = 8080
gateway_sender_bindings = ['ipc:///tmp/announcer-receiver.sock']
gateway_ip_key_salt = None
gateway_zmq_receiver_bindings = ['ipc:///tmp/gateway-zmq-receiver.sock']
gateway_zmq_sender_bindings = ['ipc:///tmp/announce... |
package = FreeDesktopPackage('%{name}', 'pkg-config', '0.27',
configure_flags=["--with-internal-glib"])
if package.profile.name == 'darwin':
package.m64_only = True
| package = free_desktop_package('%{name}', 'pkg-config', '0.27', configure_flags=['--with-internal-glib'])
if package.profile.name == 'darwin':
package.m64_only = True |
def task_format():
return {
"actions": ["black .", "isort ."],
"verbosity": 2,
}
def task_test():
return {
"actions": ["tox -e py39"],
"verbosity": 2,
}
def task_fulltest():
return {
"actions": ["tox --skip-missing-interpreters"],
"verbosity": 2,
... | def task_format():
return {'actions': ['black .', 'isort .'], 'verbosity': 2}
def task_test():
return {'actions': ['tox -e py39'], 'verbosity': 2}
def task_fulltest():
return {'actions': ['tox --skip-missing-interpreters'], 'verbosity': 2}
def task_build():
return {'actions': ['flit build'], 'task_de... |
'''
This class takes a dictionnary as arg
Converts it into a list
This list will contain args that will be given to FileConstructor class
This list allows to build the core of the new file
'''
class RecursivePackager:
'''
arg_dict argument = dictionnary
This dictionnary has to be built by ParseIntoCreate... | """
This class takes a dictionnary as arg
Converts it into a list
This list will contain args that will be given to FileConstructor class
This list allows to build the core of the new file
"""
class Recursivepackager:
"""
arg_dict argument = dictionnary
This dictionnary has to be built by ParseIntoCreate... |
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
firstRowHasZero = not all(matrix[0])
for i in range(1,len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j... | class Solution:
def set_zeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
first_row_has_zero = not all(matrix[0])
for i in range(1, len(matrix)):
for j in range(len(matrix[0])):
if matri... |
# Python Functions
# Three types of functions
# Built in functions
# User-defined functions
# Anonymous functions
# i.e. lambada functions; not declared with def():
# Method vs function
# Method --> function that is part of a class
#can only access said method with an instance or object of said class
# A s... | def straight_switch(item1, item2):
return (item2, item1)
class Switchclass(object):
def method_switch(self, item1, item2):
self.contents = (item2, item1)
return self.contents
instance = switch_class()
print(instance.methodSwitch(1, 2))
stuff = list()
print(dir(stuff)) |
# Copyright (c) OpenMMLab. All rights reserved.
model = dict(
type='DBNet',
backbone=dict(
type='mmdet.ResNet',
depth=18,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=-1,
norm_cfg=dict(type='BN', requires_grad=True),
init_cfg=dict(type='Pretrained... | model = dict(type='DBNet', backbone=dict(type='mmdet.ResNet', depth=18, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=-1, norm_cfg=dict(type='BN', requires_grad=True), init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet18'), norm_eval=False, style='caffe'), neck=dict(type='FPNC', in_channels=[2, 4... |
class HttpRequest:
""" HTTP request class.
Attributes:
method (str): the HTTP method.
request_uri (str): the request URI.
query_string (str): the query string.
http_version (str): the HTTP version.
headers (dict of str: str): a `dict` containing the headers.
... | class Httprequest:
""" HTTP request class.
Attributes:
method (str): the HTTP method.
request_uri (str): the request URI.
query_string (str): the query string.
http_version (str): the HTTP version.
headers (dict of str: str): a `dict` containing the headers.
... |
for i in range(1, 6):
for j in range(1, 6):
if(i == 1 or i == 5):
print(j, end="")
elif(j == 6 - i):
print(6 - i, end="")
else:
print(" ", end="")
print()
| for i in range(1, 6):
for j in range(1, 6):
if i == 1 or i == 5:
print(j, end='')
elif j == 6 - i:
print(6 - i, end='')
else:
print(' ', end='')
print() |
#!/usr/bin/env python3.4
#
# Copyright 2016 - Google
#
# 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 appl... | max_wait_time_connection_state_update = 20
max_wait_time_nw_selection = 120
max_wait_time_call_drop = 60
max_wait_time_callee_ringing = 30
max_wait_time_accept_call_to_offhook_event = 30
max_wait_time_call_idle_event = 60
max_wait_time_call_initiation = 25
max_wait_time_airplanemode_event = 90
max_wait_time_sms_sent_su... |
# Fit image to screen height, optionally stretched horizontally
def fit_to_screen(image, loaded_image, is_full_width):
# Resize to fill height and width
image_w, image_h = loaded_image.size
target_w = image_w
target_h = image_h
image_ratio = float(image_w / image_h)
if target_h > image.height:
target_h ... | def fit_to_screen(image, loaded_image, is_full_width):
(image_w, image_h) = loaded_image.size
target_w = image_w
target_h = image_h
image_ratio = float(image_w / image_h)
if target_h > image.height:
target_h = image.height
target_w = round(image_ratio * target_h)
if is_full_width == ... |
def setup_parser(common_parser, subparsers):
parser = subparsers.add_parser("genotype", parents=[common_parser])
parser.add_argument(
"-i",
"--gram_dir",
help="Directory containing outputs from gramtools `build`",
dest="gram_dir",
type=str,
required=True,
)
... | def setup_parser(common_parser, subparsers):
parser = subparsers.add_parser('genotype', parents=[common_parser])
parser.add_argument('-i', '--gram_dir', help='Directory containing outputs from gramtools `build`', dest='gram_dir', type=str, required=True)
parser.add_argument('-o', '--genotype_dir', help="Dir... |
#coding=utf-8
class Solution:
def longestCommonPrefix(self, strs):
res = ""
strs.sort(key=lambda i: len(i))
# print(strs)
for i in range(len(strs[0])):
tmp = res + strs[0][i]
# print("tmp=",tmp)
for each in strs:
if each.startsw... | class Solution:
def longest_common_prefix(self, strs):
res = ''
strs.sort(key=lambda i: len(i))
for i in range(len(strs[0])):
tmp = res + strs[0][i]
for each in strs:
if each.startswith(tmp) == False:
return res
res = t... |
def da_sort(lst):
count = 0
# replica = [x for x in lst]
result = sorted(array)
for char in lst:
if char != result[0]:
count += 1
else:
result.pop(0)
return count
T = int(input())
for _ in range(T):
k, n = map(int, input().split())
array... | def da_sort(lst):
count = 0
result = sorted(array)
for char in lst:
if char != result[0]:
count += 1
else:
result.pop(0)
return count
t = int(input())
for _ in range(T):
(k, n) = map(int, input().split())
array = []
if n % 10 == 0:
iterange = n... |
def netmiko_config(device, configuration=None, **kwargs):
if configuration:
output = device['nc'].send_config_set(configuration)
else:
output = "No configuration to send."
return output | def netmiko_config(device, configuration=None, **kwargs):
if configuration:
output = device['nc'].send_config_set(configuration)
else:
output = 'No configuration to send.'
return output |
class SmTransferPriorityEnum(basestring):
"""
low|normal
Possible values:
<ul>
<li> "low" ,
<li> "normal"
</ul>
"""
@staticmethod
def get_api_name():
return "sm-transfer-priority-enum"
| class Smtransferpriorityenum(basestring):
"""
low|normal
Possible values:
<ul>
<li> "low" ,
<li> "normal"
</ul>
"""
@staticmethod
def get_api_name():
return 'sm-transfer-priority-enum' |
# x = 5
#
#
# def print_x():
# print(f'Print {x}')
#
#
# print(x)
# print_x()
#
#
# def f1():
# def nested_f1():
# # nonlocal y
# # y += 1
# y = 88
# ll.append(3)
# # ll = [3]
# z = 7
# print('From nested f1')
# print(x)
# print(y)
# ... | def get_my_print():
count = 0
def my_print(x):
nonlocal count
count += 1
print(f'My ({count}): {x}')
return my_print
my_print = get_my_print()
my_print('1')
my_print('Pesho')
my_print('Apples') |
def get_int_value(text):
text = text.strip()
if len(text) > 1 and text[:1] == '0':
second_char = text[1:2]
if second_char == 'x' or second_char == 'X':
# hexa-decimal value
return int(text[2:], 16)
elif second_char == 'b' or second_char == 'B':
# binar... | def get_int_value(text):
text = text.strip()
if len(text) > 1 and text[:1] == '0':
second_char = text[1:2]
if second_char == 'x' or second_char == 'X':
return int(text[2:], 16)
elif second_char == 'b' or second_char == 'B':
return int(text[2:], 2)
else:
... |
class AdvancedArithmetic(object):
def divisorSum(n):
raise NotImplementedError
class Calculator(AdvancedArithmetic):
def getDivisors(self, n):
if n == 1:
return [1]
maximum, num = n, 2
result = [1, n]
while num < maximum:
if not n % num:
... | class Advancedarithmetic(object):
def divisor_sum(n):
raise NotImplementedError
class Calculator(AdvancedArithmetic):
def get_divisors(self, n):
if n == 1:
return [1]
(maximum, num) = (n, 2)
result = [1, n]
while num < maximum:
if not n % num:
... |
class Node:
def __init__(self, item, next=None):
self.value = item
self.next = next
def linked_list_to_array(LList):
item = []
if LList is None:
return []
item = item + [LList.value]
zz = LList
while zz.next is not None:
item = item + [zz.next.value]
zz ... | class Node:
def __init__(self, item, next=None):
self.value = item
self.next = next
def linked_list_to_array(LList):
item = []
if LList is None:
return []
item = item + [LList.value]
zz = LList
while zz.next is not None:
item = item + [zz.next.value]
zz ... |
# /* vim: set tabstop=2 softtabstop=2 shiftwidth=2 expandtab : */
class d:
def __init__(i, tag, txt, nl="", kl=None):
i.tag, i.nl, i.kl, i.txt = tag, nl, kl, txt
def __repr__(i):
s=""
if isinstance(i.txt,(list,tuple)):
s = ''.join([str(x) for x in i.txt])
else:
s = str(i.txt)
kl = ... | class D:
def __init__(i, tag, txt, nl='', kl=None):
(i.tag, i.nl, i.kl, i.txt) = (tag, nl, kl, txt)
def __repr__(i):
s = ''
if isinstance(i.txt, (list, tuple)):
s = ''.join([str(x) for x in i.txt])
else:
s = str(i.txt)
kl = ' class="%s"' % i.kl i... |
students = [
{
"name": "John Doe",
"age": 15,
"sex": "male"
},
{
"name": "Jane Doe",
"age": 12,
"sex": "female"
},
{
"name": "Lockle Rory",
"age": 18,
"sex": "male"
},
{
"name": "Seyi Pedro",
"age": 10,
... | students = [{'name': 'John Doe', 'age': 15, 'sex': 'male'}, {'name': 'Jane Doe', 'age': 12, 'sex': 'female'}, {'name': 'Lockle Rory', 'age': 18, 'sex': 'male'}, {'name': 'Seyi Pedro', 'age': 10, 'sex': 'female'}] |
# 832 SLoC
v = FormValidator(
firstname=Unicode(),
surname=Unicode(required="Please enter your surname"),
age=Int(greaterthan(18, "You must be at least 18 to proceed"), required=False),
)
input_data = {
'firstname': u'Fred',
'surname': u'Jones',
'age': u'21',
}
v.process(input_data) == {'age': 21, 'firstn... | v = form_validator(firstname=unicode(), surname=unicode(required='Please enter your surname'), age=int(greaterthan(18, 'You must be at least 18 to proceed'), required=False))
input_data = {'firstname': u'Fred', 'surname': u'Jones', 'age': u'21'}
v.process(input_data) == {'age': 21, 'firstname': u'Fred', 'surname': u'Jo... |
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... | power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate Leakage': 0.00662954, 'Peak Dynamic': 0.0, 'Runtime Dynamic': 0.0, 'Subthres... |
def most_frequent_days(year):
days=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
if year==2000: return ['Saturday', 'Sunday']
check=2000
if year>check:
day=6
while check<year:
check+=1
day+=2 if leap(check) else 1
if day%7==0:
... | def most_frequent_days(year):
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
if year == 2000:
return ['Saturday', 'Sunday']
check = 2000
if year > check:
day = 6
while check < year:
check += 1
day += 2 if leap(check) ... |
class Solution:
# @param {integer[]} nums
# @return {string}
def largestNumber(self, nums):
nums = sorted(nums, cmp=self.compare)
res, j = '', 0
for i in range(len(nums) - 1):
if nums[i] != 0:
break
else:
j += 1
for k in... | class Solution:
def largest_number(self, nums):
nums = sorted(nums, cmp=self.compare)
(res, j) = ('', 0)
for i in range(len(nums) - 1):
if nums[i] != 0:
break
else:
j += 1
for k in range(j, len(nums)):
res += str(nu... |
n = int(input())
sequence = []
for i in range(n):
sequence.append(int(input()))
print(f"Max number: {max(sequence)}\nMin number: {min(sequence)}")
| n = int(input())
sequence = []
for i in range(n):
sequence.append(int(input()))
print(f'Max number: {max(sequence)}\nMin number: {min(sequence)}') |
#python
evt = lx.args()[0]
if evt == 'onDo':
lx.eval("?kelvin.quickScale")
elif evt == 'onDrop':
pass
| evt = lx.args()[0]
if evt == 'onDo':
lx.eval('?kelvin.quickScale')
elif evt == 'onDrop':
pass |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def largestBSTSubtree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def f... | class Solution(object):
def largest_bst_subtree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def find(root):
if not root:
return (True, 0, None, None)
(l, r) = (find(root.left), find(root.right))
if l[0] and r[0] ... |
"""
An implementation of a very simple Twitter Standard v1.1 API client based on
:mod:`requests`.
See https://developer.twitter.com/en/docs/twitter-api/v1 for more information.
"""
| """
An implementation of a very simple Twitter Standard v1.1 API client based on
:mod:`requests`.
See https://developer.twitter.com/en/docs/twitter-api/v1 for more information.
""" |
class Solution:
def lexicalOrder(self, n: int) -> List[int]:
ans = [1]
while len(ans) < n:
nxt = ans[-1] * 10
while nxt > n:
nxt //= 10
nxt += 1
while nxt % 10 == 0:
nxt //= 10
ans.append(nxt)
... | class Solution:
def lexical_order(self, n: int) -> List[int]:
ans = [1]
while len(ans) < n:
nxt = ans[-1] * 10
while nxt > n:
nxt //= 10
nxt += 1
while nxt % 10 == 0:
nxt //= 10
ans.append(nxt)
... |
# Advent of Code - Day 2
# day_2_advent_2020.py
# 2020.12.02
# Jimmy Taylor
# Reading data from text file, spliting each value as separate lines without line break
input_data = open('inputs/day2.txt').read().splitlines()
# Cleaning up the data in each row to make it easier to parse later as individual rows
modified_da... | input_data = open('inputs/day2.txt').read().splitlines()
modified_data = [line.replace('-', ' ').replace(':', '').replace(' ', ',') for line in input_data]
valid_passwords_part_1 = 0
bad_passwords_part_1 = 0
valid_passwords_part_2 = 0
bad_passwords_part_2 = 0
for row in modified_data:
row = list(row.split(','))
... |
for t in range(int(input())):
G = int(input())
for g in range(G):
I,N,Q = map(int,input().split())
if I == 1 :
if N%2:
heads = N//2
tails = N - N//2
if Q == 1:
print(heads)
else:
... | for t in range(int(input())):
g = int(input())
for g in range(G):
(i, n, q) = map(int, input().split())
if I == 1:
if N % 2:
heads = N // 2
tails = N - N // 2
if Q == 1:
print(heads)
else:
... |
class Tile():
def __init__(self, pos):
self.white = True
self.pos = pos
def flip(self):
self.white = not self.white
def get_new_coord(from_tile, instructions):
curr = [from_tile.pos[0], from_tile.pos[1]]
for instruction in instructions:
if instruction == "ne":
... | class Tile:
def __init__(self, pos):
self.white = True
self.pos = pos
def flip(self):
self.white = not self.white
def get_new_coord(from_tile, instructions):
curr = [from_tile.pos[0], from_tile.pos[1]]
for instruction in instructions:
if instruction == 'ne':
... |
# Example 1:
# Input: digits = "23"
# Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
# Example 2:
# Input: digits = ""
# Output: []
# Example 3:
# Input: digits = "2"
# Output: ["a","b","c"]
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
phone_keyboard = {2: 'abc', 3: 'de... | class Solution:
def letter_combinations(self, digits: str) -> List[str]:
phone_keyboard = {2: 'abc', 3: 'def', 4: 'ghi', 5: 'jkl', 6: 'mno', 7: 'pqrs', 8: 'tuv', 9: 'wxyz'}
answer = [''] if digits else []
for x in digits:
answer = [i + j for i in answer for j in phone_keyboard[i... |
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
res = [1] * (len(nums))
prefix = 1
for i in range(len(nums)):
res[i] = prefix
prefix *= nums[i]
postfix = 1
for ... | class Solution(object):
def product_except_self(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
res = [1] * len(nums)
prefix = 1
for i in range(len(nums)):
res[i] = prefix
prefix *= nums[i]
postfix = 1
for ... |
# Write a program to read through the mbox-short.txt and figure out who has sent
# the greatest number of mail messages. The program looks for 'From ' lines and
# takes the second word of those lines as the person who sent the mail
# The program creates a Python dictionary that maps the sender's mail address to a ' \
#... | md = dict()
name = input('Enter file:')
if len(name) < 1:
name = 'mbox-short.txt'
handle = open(name)
for linem in handle:
if linem.startswith('From '):
key = linem.split()[1]
md[key] = md.get(key, 0) + 1
bigcnt = None
bigwd = None
for (wd, cnt) in md.items():
if bigcnt is None or cnt > bigc... |
#List of Numbers
list1 = [12, -7, 5, 64, -14]
#Iterating each number in the lsit
for i in list1:
#checking the condition
if i >= 0:
print(i, end = " ")
| list1 = [12, -7, 5, 64, -14]
for i in list1:
if i >= 0:
print(i, end=' ') |
def Rotate2DArray(arr):
n = len(arr[0])
for i in range(0, n//2):
for j in range(i, n-i-1):
temp = arr[i][j]
arr[i][j] = arr[n-1-j][i]
arr[n-j-1][i] = arr[n-1-i][n-j-1]
arr[n-i-1][n-j-1] = arr[j][n-i-1]
arr[j][n-i-1] = temp
return ar... | def rotate2_d_array(arr):
n = len(arr[0])
for i in range(0, n // 2):
for j in range(i, n - i - 1):
temp = arr[i][j]
arr[i][j] = arr[n - 1 - j][i]
arr[n - j - 1][i] = arr[n - 1 - i][n - j - 1]
arr[n - i - 1][n - j - 1] = arr[j][n - i - 1]
arr[j]... |
class Scene:
def __init__(self, name="svg", height=400, width=400):
self.name = name
self.items = []
self.height = height
self.width = width
return
def add(self, item): self.items.append(item)
def strarray(self):
var = ["<?xml version=\"1.0\"?>\n",
... | class Scene:
def __init__(self, name='svg', height=400, width=400):
self.name = name
self.items = []
self.height = height
self.width = width
return
def add(self, item):
self.items.append(item)
def strarray(self):
var = ['<?xml version="1.0"?>\n', '<... |
#Leia uma temperatura em graus celsius e apresente-a convertida em fahrenheit.
# A formula da conversao eh: F=C*(9/5)+32,
# sendo F a temperatura em fahrenheit e c a temperatura em celsius.
C=float(input("Informe a temperatura em Celsius: "))
F=C*(9/5)+32
print(f"A temperatura em Fahrenheit eh {round(F,1)}") | c = float(input('Informe a temperatura em Celsius: '))
f = C * (9 / 5) + 32
print(f'A temperatura em Fahrenheit eh {round(F, 1)}') |
def main(j, args, params, tags, tasklet):
page = args.page
action = args.requestContext.params.get('action')
domain = args.requestContext.params.get('domain')
name = args.requestContext.params.get('name')
version = args.requestContext.params.get('version')
nid = args.requestContext.params.get('n... | def main(j, args, params, tags, tasklet):
page = args.page
action = args.requestContext.params.get('action')
domain = args.requestContext.params.get('domain')
name = args.requestContext.params.get('name')
version = args.requestContext.params.get('version')
nid = args.requestContext.params.get('n... |
STATS = [
{
"num_node_expansions": 25,
"plan_length": 20,
"search_time": 0.04,
"total_time": 0.04
},
{
"num_node_expansions": 22,
"plan_length": 18,
"search_time": 0.04,
"total_time": 0.04
},
{
"num_node_expansions": 24,
... | stats = [{'num_node_expansions': 25, 'plan_length': 20, 'search_time': 0.04, 'total_time': 0.04}, {'num_node_expansions': 22, 'plan_length': 18, 'search_time': 0.04, 'total_time': 0.04}, {'num_node_expansions': 24, 'plan_length': 21, 'search_time': 0.33, 'total_time': 0.33}, {'num_node_expansions': 26, 'plan_length': 2... |
def rotate(angle):
"""Rotates the context"""
raise NotImplementedError("rotate() is not implemented")
def translate(x, y):
"""Translates the context by x and y"""
raise NotImplementedError("translate() is not implemented")
def scale(factor):
"""Scales the context by the provided factor"""
r... | def rotate(angle):
"""Rotates the context"""
raise not_implemented_error('rotate() is not implemented')
def translate(x, y):
"""Translates the context by x and y"""
raise not_implemented_error('translate() is not implemented')
def scale(factor):
"""Scales the context by the provided factor"""
... |
print(14514)
for i in range(3, 121):
for j in range(1, i + 1):
print(i, j, -1)
print(i, j, 1) | print(14514)
for i in range(3, 121):
for j in range(1, i + 1):
print(i, j, -1)
print(i, j, 1) |
obj_row, obj_col = 2978, 3083
first_code = 20151125
def generate(obj_row, obj_col):
x_row= obj_row + obj_col - 1
x_n = sum(range(1, x_row + 1)) - (x_row - obj_col)
print(x_n)
previous = first_code
aux = first_code
for i in range(1, x_n) :
aux = (previous * 252533) % 33554393
... | (obj_row, obj_col) = (2978, 3083)
first_code = 20151125
def generate(obj_row, obj_col):
x_row = obj_row + obj_col - 1
x_n = sum(range(1, x_row + 1)) - (x_row - obj_col)
print(x_n)
previous = first_code
aux = first_code
for i in range(1, x_n):
aux = previous * 252533 % 33554393
p... |
def wait(t, c):
while c < t:
c += c
return c
s, t, n = [int(i) for i in raw_input().split()]
d = map(int, raw_input().split())
b = map(int, raw_input().split())
c = map(int, raw_input().split())
time = s
time += d[0]
for i in range(n):
time = wait(time, c[i])
time += b[i]
time += d[i+1]
pri... | def wait(t, c):
while c < t:
c += c
return c
(s, t, n) = [int(i) for i in raw_input().split()]
d = map(int, raw_input().split())
b = map(int, raw_input().split())
c = map(int, raw_input().split())
time = s
time += d[0]
for i in range(n):
time = wait(time, c[i])
time += b[i]
time += d[i + 1]
... |
class Config:
SECRET_KEY = 'a22912297e93845c6cf4776991df63ec'
SQLALCHEMY_DATABASE_URI = 'sqlite:///site.db'
MAIL_SERVER = 'smtp.gmail.com'
MAIL_PORT = 587
MAIL_USE_TLS = True
MAIL_USERNAME = "noreplya006@gmail.com"
MAIL_PASSWORD = "#@1234abcd" | class Config:
secret_key = 'a22912297e93845c6cf4776991df63ec'
sqlalchemy_database_uri = 'sqlite:///site.db'
mail_server = 'smtp.gmail.com'
mail_port = 587
mail_use_tls = True
mail_username = 'noreplya006@gmail.com'
mail_password = '#@1234abcd' |
# https://practice.geeksforgeeks.org/problems/circular-tour-1587115620/1
# 4 6 7 4
# 6 5 3 5
# -2 1 4 -1
class Solution:
def tour(self, lis, n):
sum = 0
j = 0
for i in range(len(lis)):
pair = lis[i]
sum += pair[0]-pair[1]
if sum < 0:
sum =... | class Solution:
def tour(self, lis, n):
sum = 0
j = 0
for i in range(len(lis)):
pair = lis[i]
sum += pair[0] - pair[1]
if sum < 0:
sum = 0
j = i + 1
if j >= n:
return -1
else:
return ... |
MESSAGES = {
# name -> (message send, expected response)
"ping request":
(b'd1:ad2:id20:\x16\x01\xfb\xa7\xca\x18P\x9e\xe5\x1d\xcc\x0e\xf8\xc6Z\x1a\xfe<s\x81e1:q4:ping1:t2:aa1:y1:qe',
b'^d1:t2:aa1:y1:r1:rd2:id20:.{20}ee$'),
"ping request missing id":
(b'd1:ade1:q4:ping1:t2:XX1:y1:qe', b'^d1:t2:X... | messages = {'ping request': (b'd1:ad2:id20:\x16\x01\xfb\xa7\xca\x18P\x9e\xe5\x1d\xcc\x0e\xf8\xc6Z\x1a\xfe<s\x81e1:q4:ping1:t2:aa1:y1:qe', b'^d1:t2:aa1:y1:r1:rd2:id20:.{20}ee$'), 'ping request missing id': (b'd1:ade1:q4:ping1:t2:XX1:y1:qe', b'^d1:t2:XX1:y1:e1:eli203e14:Protocol Erroree$'), 'find_node request': (b'd1:ad2... |
#!/usr/bin/env python
# PoC1.py
junk = "A"*1000
payload = junk
f = open('exploit.plf','w')
f.write(payload)
f.close()
| junk = 'A' * 1000
payload = junk
f = open('exploit.plf', 'w')
f.write(payload)
f.close() |
"""
Misc ASCII art
"""
WARNING = r"""
_mBma
sQf "QL
jW( -$g.
jW' -$m,
.y@' _aa. 4m,
.mD` ]QQWQ. 4Q,
_mP` ]QQQQ ?Q/
_QF )WQQ@ ?Qc
<QF QQQF )Qa
jW( QQQf "QL
jW' ]H... | """
Misc ASCII art
"""
warning = '\n _mBma\n sQf "QL\n jW( -$g.\n jW\' -$m,\n .y@\' _aa. 4m,\n .mD` ]QQWQ. 4Q,\n _mP` ]QQQQ ?Q/\n _QF )WQQ@ ?Qc\n <QF QQQF )Qa\n jW( QQQf "QL\n jW\' ... |
"""
summary: code to be run right after IDAPython initialization
description:
The `idapythonrc.py` file:
* %APPDATA%\Hex-Rays\IDA Pro\idapythonrc.py (on Windows)
* ~/.idapro/idapythonrc.py (on Linux & Mac)
can contain any IDAPython code that will be run as soon as
IDAPython is done successfully initial... | """
summary: code to be run right after IDAPython initialization
description:
The `idapythonrc.py` file:
* %APPDATA%\\Hex-Rays\\IDA Pro\\idapythonrc.py (on Windows)
* ~/.idapro/idapythonrc.py (on Linux & Mac)
can contain any IDAPython code that will be run as soon as
IDAPython is done successfully init... |
'''
Created on 22 Oct 2019
@author: Yvo
'''
name = "Rom Filter";
| """
Created on 22 Oct 2019
@author: Yvo
"""
name = 'Rom Filter' |
class State:
MOTION_STATIONARY = 0
MOTION_WALKING = 1
MOTION_RUNNING = 2
MOTION_DRIVING = 3
MOTION_BIKING = 4
LOCATION_HOME = 0
LOCATION_WORK = 1
LOCATION_OTHER = 2
RINGER_MODE_SILENT = 0
RINGER_MODE_VIBRATE = 1
RINGER_MODE_NORMAL = 2
SCREEN_STATUS_ON = 0
SCREEN_S... | class State:
motion_stationary = 0
motion_walking = 1
motion_running = 2
motion_driving = 3
motion_biking = 4
location_home = 0
location_work = 1
location_other = 2
ringer_mode_silent = 0
ringer_mode_vibrate = 1
ringer_mode_normal = 2
screen_status_on = 0
screen_statu... |
class Shortener():
"""
The shortner API provides three functions, create, retrive and update shortened URL token.
"""
def __init__(self, shortener, store, validator) -> None:
self.__shortener = shortener
self.__store = store
self.__validator = validator
self.__default_pr... | class Shortener:
"""
The shortner API provides three functions, create, retrive and update shortened URL token.
"""
def __init__(self, shortener, store, validator) -> None:
self.__shortener = shortener
self.__store = store
self.__validator = validator
self.__default_prot... |
"""
FILE: read_switches.py
AUTHOR: Ben Simcox
PROJECT: verbose-waffle (github.com/bnsmcx/verbose-waffle)
PURPOSE: Currently simulates reading of switches. This functionality will change when
prototyping moves to hardware but the use of a list of lists to capture the
switch posit... | """
FILE: read_switches.py
AUTHOR: Ben Simcox
PROJECT: verbose-waffle (github.com/bnsmcx/verbose-waffle)
PURPOSE: Currently simulates reading of switches. This functionality will change when
prototyping moves to hardware but the use of a list of lists to capture the
switch posit... |
class LinkParserResult:
uri: str = ""
relationship: str = ""
link_type: str = ""
datetime: str = ""
title: str = ""
link_from: str = ""
link_until: str = ""
def __init__(self, uri: str = "",
relationship: str = "",
link_type: str = "",
... | class Linkparserresult:
uri: str = ''
relationship: str = ''
link_type: str = ''
datetime: str = ''
title: str = ''
link_from: str = ''
link_until: str = ''
def __init__(self, uri: str='', relationship: str='', link_type: str='', datetime: str='', title: str='', link_from: str='', link_... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
p1, p2 = headA, headB
len1, len2 = 1, 1
... | class Solution(object):
def get_intersection_node(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
(p1, p2) = (headA, headB)
(len1, len2) = (1, 1)
while p1 != None and p2 != None:
if p1 == p2:
return p1
else:
... |
class Solution:
def confusingNumberII(self, N: int) -> int:
table = {0:0, 1:1, 6:9, 8:8, 9:6}
keys = [0, 1, 6, 8, 9]
def dfs(num, rotation, base):
count = 0
if num != rotation:
count += 1
for d in keys:
if num == 0 and d == ... | class Solution:
def confusing_number_ii(self, N: int) -> int:
table = {0: 0, 1: 1, 6: 9, 8: 8, 9: 6}
keys = [0, 1, 6, 8, 9]
def dfs(num, rotation, base):
count = 0
if num != rotation:
count += 1
for d in keys:
if num == 0 ... |
# -*- coding: utf-8 -*-
APPLIANCE_SECTION_START = '# BEGIN AUTOGENERATED'
APPLIANCE_SECTION_END = '# END AUTOGENERATED'
class UpScript(object):
"""
Parser and generator for tinc-up scripts.
This is pretty basic:
It assumes that somewhere in the script, there is a section initiated by '# BEGIN AUTOGE... | appliance_section_start = '# BEGIN AUTOGENERATED'
appliance_section_end = '# END AUTOGENERATED'
class Upscript(object):
"""
Parser and generator for tinc-up scripts.
This is pretty basic:
It assumes that somewhere in the script, there is a section initiated by '# BEGIN AUTOGENERATED'
and concluded... |
def or_else(lhs, rhs):
if lhs != None:
return lhs
else:
return rhs
def fold(function, arguments, initializer, accumulator = None):
if len(arguments) == 0:
return accumulator
else:
return fold(
function,
arguments[1:],
initializer,
function(
or_else(accumulator, initializer),
arg... | def or_else(lhs, rhs):
if lhs != None:
return lhs
else:
return rhs
def fold(function, arguments, initializer, accumulator=None):
if len(arguments) == 0:
return accumulator
else:
return fold(function, arguments[1:], initializer, function(or_else(accumulator, initializer),... |
lst = """75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40... | lst = '75\n95 64\n17 47 82\n18 35 87 10\n20 04 82 47 65\n19 01 23 75 03 34\n88 02 77 73 07 63 67\n99 65 04 28 06 16 70 92\n41 41 26 56 83 40 80 70 33\n41 48 72 33 47 32 37 16 94 29\n53 71 44 65 25 43 91 52 97 51 14\n70 11 33 28 77 73 17 78 39 68 17 57\n91 71 52 38 17 14 91 43 58 50 27 29 48\n63 66 04 68 89 53 67 30 73 ... |
## https://leetcode.com/problems/path-sum
# 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 hasPathSum(self, root: Optional[TreeNode], targetSum: int) ->... | class Solution:
def has_path_sum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if root is None:
return False
if root.left is None and root.right is None:
return root.val == targetSum
left = self.hasPathSum(root.left, targetSum - root.val)
right = s... |
class Solution:
def groupAnagrams(self, strs: 'List[str]') -> 'List[List[str]]':
dic = {}
for anagram in strs:
key = ''.join(sorted(anagram))
if key in dic.keys():
dic[key].append(anagram)
else:
dic[key] = [anagram]
result =... | class Solution:
def group_anagrams(self, strs: 'List[str]') -> 'List[List[str]]':
dic = {}
for anagram in strs:
key = ''.join(sorted(anagram))
if key in dic.keys():
dic[key].append(anagram)
else:
dic[key] = [anagram]
result... |
# Stream are lazy linked list
# A stream is a linked list, but the rest of the list is computed on demand
'''
Link- First element is anything
- second element is a Link instance or Link.empty
Stream -First element can be anything
- Second element is a zero-argument function that returns a Stream or Strea... | """
Link- First element is anything
- second element is a Link instance or Link.empty
Stream -First element can be anything
- Second element is a zero-argument function that returns a Stream or Stream.empty
Once Created, the Link and Stream can be used interchangeable
namely first, rest
"""
class Strea... |
#!/usr/bin/env python3
def format_log_level(level):
return [
'DEBUG',
'INFO ',
'WARN ',
'ERROR',
'FATAL',
][level]
def format_log_type(log_type):
return log_type.lstrip('TI')
def format_log_entry(log_entry):
return '{} {} {}:{} {}'.format(
log_entry['lo... | def format_log_level(level):
return ['DEBUG', 'INFO ', 'WARN ', 'ERROR', 'FATAL'][level]
def format_log_type(log_type):
return log_type.lstrip('TI')
def format_log_entry(log_entry):
return '{} {} {}:{} {}'.format(log_entry['log_time'], format_log_level(log_entry['log_level']), log_entry['file_name'], log_... |
def sieve(max):
primes = []
for n in range(2, max + 1):
if any(n % p > 0 for p in primes):
primes.append(n)
return primes
"""
Sieve of Eratosthenes
prime-sieve
Input:
max: A positive int representing an upper bound.
Output:
A list containing all primes up to and including max
... | def sieve(max):
primes = []
for n in range(2, max + 1):
if any((n % p > 0 for p in primes)):
primes.append(n)
return primes
'\nSieve of Eratosthenes\nprime-sieve\n\nInput:\n max: A positive int representing an upper bound.\n\nOutput:\n A list containing all primes up to and includi... |
# app/utils.py
def make_step_iter(step, max_):
num = 0
while True:
yield num
num = (num + step) % max_
| def make_step_iter(step, max_):
num = 0
while True:
yield num
num = (num + step) % max_ |
PASILLO_DID = "A1"
CUARTO_ESTE_DID = "A2"
CUARTO_OESTE_DID = "A4"
SALON_DID = "A5"
HEATER_DID = "C1"
HEATER_PROTOCOL = "X10"
HEATER_API = "http://localhost"
HEATER_USERNAME = "raton"
HEATER_PASSWORD = "xxxx"
HEATER_MARGIN = 0.0
HEATER_INCREMENT = 0.5
AWS_CREDS_PATH = "/etc/aws.keys"
AWS_ZONE = "us-east-1"
MINUTES... | pasillo_did = 'A1'
cuarto_este_did = 'A2'
cuarto_oeste_did = 'A4'
salon_did = 'A5'
heater_did = 'C1'
heater_protocol = 'X10'
heater_api = 'http://localhost'
heater_username = 'raton'
heater_password = 'xxxx'
heater_margin = 0.0
heater_increment = 0.5
aws_creds_path = '/etc/aws.keys'
aws_zone = 'us-east-1'
minutes_after... |
# best solution:
# https://leetcode.com/problems/merge-two-sorted-lists/discuss/9735/Python-solutions-(iteratively-recursively-iteratively-in-place).
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoL... | class Solution:
def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode:
dummy = list_node(0)
tmp = dummy
while l1 and l2:
dummy.next = list_node(min(l1.val, l2.val))
dummy = dummy.next
if l1.val < l2.val:
l1 = l1.next
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Copyright 2021, Yutong Xie, UIUC.
Using for loop to find maximum product of three numbers
'''
class Solution(object):
def maximumProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
min1, min2 = float("inf"... | """
Copyright 2021, Yutong Xie, UIUC.
Using for loop to find maximum product of three numbers
"""
class Solution(object):
def maximum_product(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
(min1, min2) = (float('inf'), float('inf'))
(max1, max2, max3... |
class Article():
def __init__(self, title, description, author, site, link):
"""Init the article model"""
self.title = title
self.description = description
self.author = author
self.site = site
self.link = link | class Article:
def __init__(self, title, description, author, site, link):
"""Init the article model"""
self.title = title
self.description = description
self.author = author
self.site = site
self.link = link |
# Given an array, rotate the array to the right by k steps, where k is non-negative.
# Example 1:
# Input: [1,2,3,4,5,6,7] and k = 3
# Output: [5,6,7,1,2,3,4]
# Explanation:
# rotate 1 steps to the right: [7,1,2,3,4,5,6]
# rotate 2 steps to the right: [6,7,1,2,3,4,5]
# rotate 3 steps to the right: [5,6,7,1,2,3,4]
... | class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
i = 0
while i < k:
a = nums.pop()
nums.insert(0, a)
i += 1 |
include("common.py")
damnScission = [
ruleGMLString("""rule [
ruleID "DAMN Scission"
left [
edge [ source 0 target 10 label "=" ]
edge [ source 10 target 13 label "-" ]
edge [ source 13 target 14 label "-" ]
edge [ source 13 target 15 label "-" ]
]
context [
# DAMN
node [ id 0 label "C" ]
edge [ s... | include('common.py')
damn_scission = [rule_gml_string('rule [\n\truleID "DAMN Scission"\n\tleft [\n\t\tedge [ source 0 target 10 label "=" ]\t\n\t\tedge [ source 10 target 13 label "-" ]\n\t\tedge [ source 13 target 14 label "-" ]\n\t\tedge [ source 13 target 15 label "-" ]\n\t]\n\tcontext [\n\t\t# DAMN\n\t\tnode [ id ... |
# Doris Zdravkovic, March, 2019
# Solution to problem 5.
# python primes.py
# Input of a positive integer
n = int(input("Please enter a positive integer: "))
# Prime number is always greater than 1
# Reference: https://docs.python.org/3/tutorial/controlflow.html
# If entered number is greater than 1, for every numbe... | n = int(input('Please enter a positive integer: '))
if n > 1:
for x in range(2, n):
if n % x == 0:
print('This is not a prime number.')
break
else:
print(n, 'is a prime number.')
else:
print(n, 'is a prime number') |
#!/usr/bin/python
'''
This file is part of SNC
Copyright (c) 2014-2021, Richard Barnett
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 limitati... | """
This file is part of SNC
Copyright (c) 2014-2021, Richard Barnett
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to us... |
#Shape of small l:
def for_l():
"""printing small 'l' using for loop"""
for row in range(6):
for col in range(3):
if col==1 or row==0 and col!=2 or row==5 and col!=0:
print("*",end=" ")
else:
print(" ",end=" ")
print()
def... | def for_l():
"""printing small 'l' using for loop"""
for row in range(6):
for col in range(3):
if col == 1 or (row == 0 and col != 2) or (row == 5 and col != 0):
print('*', end=' ')
else:
print(' ', end=' ')
print()
def while_l():
"""p... |
def get_menu_choice():
def print_menu(): # Your menu design here
print(" _ _ _____ _____ _ _ ")
print("| \ | | ___|_ _| / \ _ __| |_ ")
print("| \| | |_ | | / _ \ | '__| __|")
print("| |\ | _| | | / ___ \| | | |_ ")
print("|_| \_... | def get_menu_choice():
def print_menu():
print(' _ _ _____ _____ _ _ ')
print('| \\ | | ___|_ _| / \\ _ __| |_ ')
print("| \\| | |_ | | / _ \\ | '__| __|")
print('| |\\ | _| | | / ___ \\| | | |_ ')
print('|_| \\_|_| |_| /_/ \\... |
conversion = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
roman_letter_order = dict((letter, ind) for ind, letter in enumerate('IVXLCDM'))
minimal_num_of_letter_needed_for_each_digit = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 2,
'5': 1, '6': 2, '7': 3, '8... | conversion = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
roman_letter_order = dict(((letter, ind) for (ind, letter) in enumerate('IVXLCDM')))
minimal_num_of_letter_needed_for_each_digit = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 2, '5': 1, '6': 2, '7': 3, '8': 4, '9': 2}
def check_order(long_form):
... |
# Write a for loop using range() to print out multiples of 5 up to 30 inclusive
for mult in range(5, 31, 5): # prints out multiples of 5 up to 30 inclusive
print(mult)
| for mult in range(5, 31, 5):
print(mult) |
"""Module for request errors"""
REQUEST_ERROR_DICT = {
'invalid_request': 'Invalid request object',
'not_found': '{} not found',
'invalid_credentials': 'Invalid username or password',
'already_exists': '{0} or {1} already exists',
'exists': '{0} already exists',
'invalid_provided_date': 'Invali... | """Module for request errors"""
request_error_dict = {'invalid_request': 'Invalid request object', 'not_found': '{} not found', 'invalid_credentials': 'Invalid username or password', 'already_exists': '{0} or {1} already exists', 'exists': '{0} already exists', 'invalid_provided_date': 'Invalid date range please, {}.',... |
#
# PySNMP MIB module CISCO-SWITCH-HARDWARE-CAPACITY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-SWITCH-HARDWARE-CAPACITY-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:13:27 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_size_constraint, value_range_constraint, constraints_union, constraints_intersection) ... |
class Solution(object):
def constructRectangle(self, area):
"""
:type area: int
:rtype: List[int]
"""
L = int(math.sqrt(area))
while True:
W = area // L
if W * L == area:
return [W, L]
L -= 1
| class Solution(object):
def construct_rectangle(self, area):
"""
:type area: int
:rtype: List[int]
"""
l = int(math.sqrt(area))
while True:
w = area // L
if W * L == area:
return [W, L]
l -= 1 |
#/usr/bin/env python3
GET_PHOTOS_PATTERN = "https://www.flickr.com/services/rest?method=flickr.people.getPhotos&api_key={}&user_id={}&format=json&page={}&per_page={}"
FIND_USER_BY_NAME_METHOD = "https://www.flickr.com/services/rest?method=flickr.people.findbyusername&api_key={}&username={}&format={}"
GET_PHOTO_COMMENT... | get_photos_pattern = 'https://www.flickr.com/services/rest?method=flickr.people.getPhotos&api_key={}&user_id={}&format=json&page={}&per_page={}'
find_user_by_name_method = 'https://www.flickr.com/services/rest?method=flickr.people.findbyusername&api_key={}&username={}&format={}'
get_photo_comments = 'https://www.flickr... |
class Font(object):
# no doc
@staticmethod
def AvailableFontFaceNames():
""" AvailableFontFaceNames() -> Array[str] """
pass
Bold = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Bold(self: Font) -> bool
"""
FaceName = property... | class Font(object):
@staticmethod
def available_font_face_names():
""" AvailableFontFaceNames() -> Array[str] """
pass
bold = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Get: Bold(self: Font) -> bool\n\n\n\n'
face_name = property(lambda self: object(), ... |
def sayhi():
print("hello")
def chat():
print("This is a calculator")
def exit():
print("Thank you")
def mul(n1,n2):
return n1*n2
def add(n1,n2):
return n1+n2
def sub(n1,n2):
return n1-n2
def div(n1,n2):
return n1/n2
sayhi()
chat()
i = int(input("Enter a number:- "))
j = int(input(... | def sayhi():
print('hello')
def chat():
print('This is a calculator')
def exit():
print('Thank you')
def mul(n1, n2):
return n1 * n2
def add(n1, n2):
return n1 + n2
def sub(n1, n2):
return n1 - n2
def div(n1, n2):
return n1 / n2
sayhi()
chat()
i = int(input('Enter a number:- '))
j = in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.