content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Tree:
def __init__(self,data):
self.tree = [data, [],[]]
def left_subtree(self,branch):
left_list = self.tree.pop(1)
if len(left_list) > 1:
branch.tree[1]=left_list
self.tree.insert(1,branch.tree)
else:
self.tree.insert(1,bra... | class Tree:
def __init__(self, data):
self.tree = [data, [], []]
def left_subtree(self, branch):
left_list = self.tree.pop(1)
if len(left_list) > 1:
branch.tree[1] = left_list
self.tree.insert(1, branch.tree)
else:
self.tree.insert(1, branch.... |
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"[{self.x},{self.y}]"
class X(Point):
def __init__(self, x, y):
super().__init__(x, y)
def __str__(self):
return "X" + super().__str__()
class O(Point):
def __init__(... | class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f'[{self.x},{self.y}]'
class X(Point):
def __init__(self, x, y):
super().__init__(x, y)
def __str__(self):
return 'X' + super().__str__()
class O(Point):
def __init__... |
def input_dimension():
while True:
dimension = input("Enter your board dimensions: ").split()
len_x1 = 0
len_y1 = 0
if len(dimension) != 2:
print("Invalid dimensions!")
continue
try:
len_x1 = int(dimension[0])
len_y1 =... | def input_dimension():
while True:
dimension = input('Enter your board dimensions: ').split()
len_x1 = 0
len_y1 = 0
if len(dimension) != 2:
print('Invalid dimensions!')
continue
try:
len_x1 = int(dimension[0])
len_y1 = int(dimen... |
"""Mirror of release info
TODO: generate this file from GitHub API"""
# The integrity hashes can be computed with
# shasum -b -a 384 [downloaded file] | awk '{ print $1 }' | xxd -r -p | base64
TOOL_VERSIONS = {
"7.0.1-rc1": {
"darwin_arm64": "sha384-PMTl7GMV01JnwQ0yoURCuEVq+xUUlhayLzBFzqId8ebIBQ8g8aWnbiRX... | """Mirror of release info
TODO: generate this file from GitHub API"""
tool_versions = {'7.0.1-rc1': {'darwin_arm64': 'sha384-PMTl7GMV01JnwQ0yoURCuEVq+xUUlhayLzBFzqId8ebIBQ8g8aWnbiRX0e4xwdY1'}} |
with open("input.txt") as file:
data = file.read()
m = [-1, 0, 1]
def neight(grid, x, y):
for a in m:
for b in m:
if a == b == 0:
continue
xx = x+a
yy = y+b
if 0 <= xx < len(grid) and 0 <= yy < len(grid[xx]):
yield grid[xx]... | with open('input.txt') as file:
data = file.read()
m = [-1, 0, 1]
def neight(grid, x, y):
for a in m:
for b in m:
if a == b == 0:
continue
xx = x + a
yy = y + b
if 0 <= xx < len(grid) and 0 <= yy < len(grid[xx]):
yield grid... |
#
# This file contains the Python code from Program 6.2 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm06_02.txt
#
class StackAsArray(... | class Stackasarray(Stack):
def __init__(self, size=0):
super(StackAsArray, self).__init__()
self._array = array(size)
def purge(self):
while self._count > 0:
self._array[self._count] = None
self._count -= 1 |
n = input()
split =n.split()
limak = int(split[0])
bob = int(split[-1])
years = 0
while True:
limak*=3
bob*=2
years+=1
if limak>bob:
break
print(years)
| n = input()
split = n.split()
limak = int(split[0])
bob = int(split[-1])
years = 0
while True:
limak *= 3
bob *= 2
years += 1
if limak > bob:
break
print(years) |
fizz = 3
buzz = 5
upto = 100
for n in range(1,(upto + 1)):
if n % fizz == 0:
if n % buzz == 0:
print("FizzBuzz")
else:
print("Fizz")
elif n % buzz == 0:
print("Buzz")
else:
print(n)
| fizz = 3
buzz = 5
upto = 100
for n in range(1, upto + 1):
if n % fizz == 0:
if n % buzz == 0:
print('FizzBuzz')
else:
print('Fizz')
elif n % buzz == 0:
print('Buzz')
else:
print(n) |
#!/usr/bin/env python3
def count_combos(coins, total):
len_coins = len(coins)
memo = {}
def count(tot, i):
if tot == 0:
return 1
if i == len_coins:
return 0
subproblem = (tot, i)
try:
return memo[subproblem]
except KeyError:
... | def count_combos(coins, total):
len_coins = len(coins)
memo = {}
def count(tot, i):
if tot == 0:
return 1
if i == len_coins:
return 0
subproblem = (tot, i)
try:
return memo[subproblem]
except KeyError:
j = i + 1
... |
ans = []
n = int(input())
for i in range(n):
a, b = list(map(int, input().split()))
ans.append(a + b)
for i in range(len(ans)):
print("Case #{}: {}".format(i+1, ans[i])) | ans = []
n = int(input())
for i in range(n):
(a, b) = list(map(int, input().split()))
ans.append(a + b)
for i in range(len(ans)):
print('Case #{}: {}'.format(i + 1, ans[i])) |
SYSDIGERR = -1
NOPROCESS = -2
NOFUNCS = -3
NOATTACH = -4
CONSTOP = -5
HSTOPS = -6
HLOGLEN = -7
HNOKILL = -8
HNORUN = -9
CACHE = ".cache"
LIBFILENAME = "libs.out"
LANGFILENAME = ".lang.cache"
BINLISTCACHE = ".binlist.cache"
LIBLISTCACHE = ".liblist.cache"
BINTOLIBCACHE = ".bintolib.cache"
TOOLNAME = "CONF... | sysdigerr = -1
noprocess = -2
nofuncs = -3
noattach = -4
constop = -5
hstops = -6
hloglen = -7
hnokill = -8
hnorun = -9
cache = '.cache'
libfilename = 'libs.out'
langfilename = '.lang.cache'
binlistcache = '.binlist.cache'
liblistcache = '.liblist.cache'
bintolibcache = '.bintolib.cache'
toolname = 'CONFINE'
seccompcpr... |
class ChatObject:
def __init__(self, service, json):
"""Base class for objects emmitted from chat services."""
self.json = json
self.service = service
| class Chatobject:
def __init__(self, service, json):
"""Base class for objects emmitted from chat services."""
self.json = json
self.service = service |
def test_tcp_id(self):
"""
Comprobacion de que el puerto (objeto heredado) coincide con el asociado al Protocolos
Returns:
"""
port = Ports.objects.get(Tag="ssh")
tcp = Tcp.objects.get(id=port)
self.assertEqual(tcp.get_id(), port)
| def test_tcp_id(self):
"""
Comprobacion de que el puerto (objeto heredado) coincide con el asociado al Protocolos
Returns:
"""
port = Ports.objects.get(Tag='ssh')
tcp = Tcp.objects.get(id=port)
self.assertEqual(tcp.get_id(), port) |
class GMHazardError(BaseException):
"""Base GMHazard error"""
def __init__(self, message: str):
self.message = message
class ExceedanceOutOfRangeError(GMHazardError):
"""Raised when the specified exceedance value is out of range when
going from exceedance to IM on the hazard curve"""
def... | class Gmhazarderror(BaseException):
"""Base GMHazard error"""
def __init__(self, message: str):
self.message = message
class Exceedanceoutofrangeerror(GMHazardError):
"""Raised when the specified exceedance value is out of range when
going from exceedance to IM on the hazard curve"""
def ... |
#Given an array nums and a value val, remove all instances of that value in-place and return the new length.
#Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
#The order of elements can be changed. It doesn't matter what you leave beyond the... | class Solution:
def remove_element(self, nums: List[int], val: int) -> int:
result = []
m = 0
for n in range(len(nums)):
if nums[n] != val:
nums[m] = nums[n]
m += 1
return m |
class Button():
LEFT = 0
CENTER = 1
RIGHT = 2
class Key():
""" Key codes for InputEmulation.Keyboard object.
Can be entered directly or concatenated with an existing string, e.g. ``type(Key.TAB)`` """
ENTER = "{ENTER}"
ESC = "{ESC}"
BACKSPACE = "{BACKSPACE}"
DELETE = "{DELET... | class Button:
left = 0
center = 1
right = 2
class Key:
""" Key codes for InputEmulation.Keyboard object.
Can be entered directly or concatenated with an existing string, e.g. ``type(Key.TAB)`` """
enter = '{ENTER}'
esc = '{ESC}'
backspace = '{BACKSPACE}'
delete = '{DELETE}'
f1 ... |
#!/bin/env/python
infileList = []
keyList = []
cList = (
"GBR",
"FIN",
"CHS",
"PUR",
"CLM",
"IBS",
"CEU",
"YRI",
"CHB",
"JPT",
"LWK",
"ASW",
"MXL",
"TSI",
)
for i in range(17,23):
infileList.app... | infile_list = []
key_list = []
c_list = ('GBR', 'FIN', 'CHS', 'PUR', 'CLM', 'IBS', 'CEU', 'YRI', 'CHB', 'JPT', 'LWK', 'ASW', 'MXL', 'TSI')
for i in range(17, 23):
infileList.append('proc_input.chr' + str(i) + '.vcf')
keyList.append('cluster_chr' + str(i))
infileList.append('proc_input.chrX.vcf')
keyList.append(... |
n = int(input())
sumI = 0
for i in range(n):
sumI = sumI + int(input())
o = int(input())
for i in range(o):
sumI = sumI + int(input())
print('{:.3f}'.format((round(sumI*1000/(n+i+1)))/1000))
| n = int(input())
sum_i = 0
for i in range(n):
sum_i = sumI + int(input())
o = int(input())
for i in range(o):
sum_i = sumI + int(input())
print('{:.3f}'.format(round(sumI * 1000 / (n + i + 1)) / 1000)) |
class HeapError(Exception):
pass
class Heap(object):
def __init__(self, iterable=()):
self._heap = []
for value in iterable:
self.push(value)
def _get(self, node):
if not self._heap:
raise HeapError("empty heap")
if node is None:
retur... | class Heaperror(Exception):
pass
class Heap(object):
def __init__(self, iterable=()):
self._heap = []
for value in iterable:
self.push(value)
def _get(self, node):
if not self._heap:
raise heap_error('empty heap')
if node is None:
return... |
# Sum of numbers 3
def get_sum(x, y):
s = 0
if x > y:
for index in range(y, x + 1):
s = s + index
return s
elif x < y:
for index in range(x, y + 1):
s = s + index
return s
else:
return x
print(get_sum(2, 1))
print(get_sum(0, -1))
| def get_sum(x, y):
s = 0
if x > y:
for index in range(y, x + 1):
s = s + index
return s
elif x < y:
for index in range(x, y + 1):
s = s + index
return s
else:
return x
print(get_sum(2, 1))
print(get_sum(0, -1)) |
# EMPTY = "L"
# OCCUPIED = "#"
# FIXED = "."
EMPTY = 0
OCCUPIED = 1
FIXED = -1
def read_input(file_name):
seats = []
with open(file_name) as input_file:
for line in input_file:
line = line.strip()
seats.append( list(map(map_input, line) ))
return seats
# Failed attempt to... | empty = 0
occupied = 1
fixed = -1
def read_input(file_name):
seats = []
with open(file_name) as input_file:
for line in input_file:
line = line.strip()
seats.append(list(map(map_input, line)))
return seats
def map_input(x):
if x == '.':
return FIXED
elif x =... |
# When user enters 'exit', exit program
while (True):
inp = raw_input('> ')
if inp.lower() == 'exit':
break
else:
print(inp)
| while True:
inp = raw_input('> ')
if inp.lower() == 'exit':
break
else:
print(inp) |
"""
Constants for the CLI.
"""
WELCOME_MESSAGE = "Welcome to [bold green]{{cookiecutter.project_slug}}!![/bold green] Your CLI is working!"
| """
Constants for the CLI.
"""
welcome_message = 'Welcome to [bold green]{{cookiecutter.project_slug}}!![/bold green] Your CLI is working!' |
"""Constants for ThermiaGenesis integration."""
KEY_ATTRIBUTES = 'attributes'
KEY_ADDRESS = 'address'
KEY_RANGES = 'ranges'
KEY_SCALE = 'scale'
KEY_REG_TYPE = 'register_type'
KEY_BITS = 'bits'
KEY_DATATYPE = 'datatype'
TYPE_BIT = 'bit'
TYPE_INT = 'int'
TYPE_UINT = 'uint'
TYPE_LONG = 'long'
TYPE_STATUS = 'status'
REG_... | """Constants for ThermiaGenesis integration."""
key_attributes = 'attributes'
key_address = 'address'
key_ranges = 'ranges'
key_scale = 'scale'
key_reg_type = 'register_type'
key_bits = 'bits'
key_datatype = 'datatype'
type_bit = 'bit'
type_int = 'int'
type_uint = 'uint'
type_long = 'long'
type_status = 'status'
reg_co... |
# https://leetcode.com/problems/bulls-and-cows
class Solution:
def getHint(self, secret, guess):
s_used, g_used = set(), set()
bull = 0
for idx, (s_char, g_char) in enumerate(zip(secret, guess)):
if s_char == g_char:
bull += 1
s_used.add(idx)
... | class Solution:
def get_hint(self, secret, guess):
(s_used, g_used) = (set(), set())
bull = 0
for (idx, (s_char, g_char)) in enumerate(zip(secret, guess)):
if s_char == g_char:
bull += 1
s_used.add(idx)
g_used.add(idx)
prin... |
__version__ = '0.2.2'
default_app_config = 'cid.apps.CidAppConfig'
| __version__ = '0.2.2'
default_app_config = 'cid.apps.CidAppConfig' |
# -*- coding: utf-8 -*-
"""FamilySearch Discovery submodule"""
# Python imports
# Magic
class Discovery(object):
"""https://familysearch.org/developers/docs/api/tree/FamilySearch_Collections_resource"""
def __init__(self):
"""https://familysearch.org/developers/docs/api/resources#disc... | """FamilySearch Discovery submodule"""
class Discovery(object):
"""https://familysearch.org/developers/docs/api/tree/FamilySearch_Collections_resource"""
def __init__(self):
"""https://familysearch.org/developers/docs/api/resources#discovery"""
self.root_collection = self.get(self.base + '/.we... |
#
# PySNMP MIB module HH3C-IDS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-IDS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:27:21 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_union, value_range_constraint, constraints_intersection) ... |
class ServerNotRespondingException(BaseException):
"""
Exception raised when the requested server is not responding.
"""
def __init__(self, url):
self.url = url
def __str__(self):
return "Url '%s' is not responding." % self.url
class ExceededRequestsLimitException(BaseException):... | class Servernotrespondingexception(BaseException):
"""
Exception raised when the requested server is not responding.
"""
def __init__(self, url):
self.url = url
def __str__(self):
return "Url '%s' is not responding." % self.url
class Exceededrequestslimitexception(BaseException):
... |
def listens_to_mentions(regex):
"""
Decorator to add function and rule to routing table
Returns Line that triggered the function.
"""
def decorator(func):
func.route_rule = ('mentions', regex)
return func
return decorator
def listens_to_all(regex):
"""
Decorator to add... | def listens_to_mentions(regex):
"""
Decorator to add function and rule to routing table
Returns Line that triggered the function.
"""
def decorator(func):
func.route_rule = ('mentions', regex)
return func
return decorator
def listens_to_all(regex):
"""
Decorator to add... |
class TrieNode():
def __init__(self, letter=''):
self.children = {}
self.is_word = False
def lookup_letter(self, c):
if c in self.children:
return True, self.children[c].is_word
else:
return False, False
class Trie():
def __init__(self):
se... | class Trienode:
def __init__(self, letter=''):
self.children = {}
self.is_word = False
def lookup_letter(self, c):
if c in self.children:
return (True, self.children[c].is_word)
else:
return (False, False)
class Trie:
def __init__(self):
se... |
def calcula_fatorial(n):
resultado = 1
for i in range(1, n+1):
resultado = resultado * i
return resultado
def imprime_numeros(n):
imprimir = ""
for i in range(n, 0, -1):
imprimir += "%d . " %(i)
return imprimir[:len(imprimir) - 3]
numero = int(input("Digite um numero: "))
... | def calcula_fatorial(n):
resultado = 1
for i in range(1, n + 1):
resultado = resultado * i
return resultado
def imprime_numeros(n):
imprimir = ''
for i in range(n, 0, -1):
imprimir += '%d . ' % i
return imprimir[:len(imprimir) - 3]
numero = int(input('Digite um numero: '))
print... |
class Solution:
def minMeetingRooms(self, intervals: List[List[int]]) -> int:
rooms = 0
if not intervals:
return 0
endp = 0
starts = sorted([i[0] for i in intervals])
ends = sorted([i[1] for i in intervals])
for i in ran... | class Solution:
def min_meeting_rooms(self, intervals: List[List[int]]) -> int:
rooms = 0
if not intervals:
return 0
endp = 0
starts = sorted([i[0] for i in intervals])
ends = sorted([i[1] for i in intervals])
for i in range(len(starts)):
if s... |
# Copyright (C) 2021 Intel Corporation
#
# SPDX-License-Identifier: MIT
class PointCloudPath:
BASE_DIR = 'ds0'
ANNNOTATION_DIR = 'ann'
DEFAULT_IMAGE_EXT = '.jpg'
POINT_CLOUD_DIR = 'pointcloud'
RELATED_IMAGES_DIR = 'related_images'
KEY_ID_FILE = 'key_id_map.json'
META_FILE = 'meta.json'
... | class Pointcloudpath:
base_dir = 'ds0'
annnotation_dir = 'ann'
default_image_ext = '.jpg'
point_cloud_dir = 'pointcloud'
related_images_dir = 'related_images'
key_id_file = 'key_id_map.json'
meta_file = 'meta.json'
special_attrs = {'description', 'track_id', 'labelerLogin', 'createdAt', ... |
VIDEO_ELEMENT = 'videoRenderer'
CHANNEL_ELEMENT = 'channelRenderer'
PLAYLIST_ELEMENT = 'playlistRenderer'
SHELF_ELEMENT = 'shelfRenderer'
class ResultMode:
json = 0
dict = 1
class SearchMode:
videos = 'EgIQAQ%3D%3D'
channels = 'EgIQAg%3D%3D'
playlists = 'EgIQAw%3D%3D'
class VideoU... | video_element = 'videoRenderer'
channel_element = 'channelRenderer'
playlist_element = 'playlistRenderer'
shelf_element = 'shelfRenderer'
class Resultmode:
json = 0
dict = 1
class Searchmode:
videos = 'EgIQAQ%3D%3D'
channels = 'EgIQAg%3D%3D'
playlists = 'EgIQAw%3D%3D'
class Videouploaddatefilter:... |
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright SAS Institute
#
# 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... | """ Write python code for creating the SAS model """
def write_input_layer(model_name='sas', layer_name='data', channels='-1', width='-1', height='-1', scale='1.0'):
"""
Generate Python code defining a SAS deep learning input layer
Parameters
----------
model_name : string
Name for deep lea... |
# This package will contain the spiders of your Scrapy project
#
# Please refer to the documentation for information on how to create and manage
# your spiders.
DOUBAN_COOKIE = {
"__gads": "ID=2421173a5ca57aed-228b4c29c5c800c1:T=1621494084:RT=1621494084:S=ALNI_MaJlRkH7cibeVPuRhGgoy4NehQdpw",
"__utma": "8137958... | douban_cookie = {'__gads': 'ID=2421173a5ca57aed-228b4c29c5c800c1:T=1621494084:RT=1621494084:S=ALNI_MaJlRkH7cibeVPuRhGgoy4NehQdpw', '__utma': '81379588.766923198.1621432056.1634626277.1634642692.15', '__utmv': '30149280.23826', '__utmz': '81379588.1634626277.14.8.utmcsr=cn.bing.com|utmccn=(referral)|utmcmd=referral|utmc... |
class Mail:
def __init__(self, prot, *argv):
self.prot = prot(*argv)
def login(self, account, passwd):
self.prot.login(account, passwd)
def send(self, frm, to, subject, content):
self.prot.send(frm, to, subject, content)
def quit(self):
self.prot.quit()
| class Mail:
def __init__(self, prot, *argv):
self.prot = prot(*argv)
def login(self, account, passwd):
self.prot.login(account, passwd)
def send(self, frm, to, subject, content):
self.prot.send(frm, to, subject, content)
def quit(self):
self.prot.quit() |
class BaseError(Exception):
error_id = ""
error_msg = ""
def __repr__(self):
return "<{err_id}>: {err_msg}".format(
err_id=self.error_id,
err_msg=self.error_msg,
)
def render(self):
return dict(
error_id=self.error_id,
error_msg=s... | class Baseerror(Exception):
error_id = ''
error_msg = ''
def __repr__(self):
return '<{err_id}>: {err_msg}'.format(err_id=self.error_id, err_msg=self.error_msg)
def render(self):
return dict(error_id=self.error_id, error_msg=self.error_msg)
class Clienterror(BaseError):
error_id =... |
TOTAL_BUDGET_AUTHORITY = 8361447130497.72
TOTAL_OBLIGATIONS_INCURRED = 4690484214947.31
WEBSITE_AWARD_BINS = {
"<1M": {"lower": None, "upper": 1000000},
"1M..25M": {"lower": 1000000, "upper": 25000000},
"25M..100M": {"lower": 25000000, "upper": 100000000},
"100M..500M": {"lower": 100000000, "upper": 500... | total_budget_authority = 8361447130497.72
total_obligations_incurred = 4690484214947.31
website_award_bins = {'<1M': {'lower': None, 'upper': 1000000}, '1M..25M': {'lower': 1000000, 'upper': 25000000}, '25M..100M': {'lower': 25000000, 'upper': 100000000}, '100M..500M': {'lower': 100000000, 'upper': 500000000}, '>500M':... |
class NotificationData(object):
"""
Class used to represent notification data.
Attributes:
veh_id (int): The vehicle ID.
req_id (int): The request ID.
waiting_duration (str): The waiting duration.
assigned (bool): True if assigned, false if not.
"""
def __init__(self... | class Notificationdata(object):
"""
Class used to represent notification data.
Attributes:
veh_id (int): The vehicle ID.
req_id (int): The request ID.
waiting_duration (str): The waiting duration.
assigned (bool): True if assigned, false if not.
"""
def __init__(sel... |
def f():
x: list[list[i32]]
x = [[1, 2, 3]]
y: list[list[str]]
y = [['a', 'b']]
x = y
| def f():
x: list[list[i32]]
x = [[1, 2, 3]]
y: list[list[str]]
y = [['a', 'b']]
x = y |
permissions = {
"on_permissions": {
"all": "0",
"uids": [],
"badges": {
"broadcaster": "1"
},
"forbid": {
"all": "0",
"uids": [],
"badges": {}
}
},
"on_channel": {
"all": "0",
"uids": [],
... | permissions = {'on_permissions': {'all': '0', 'uids': [], 'badges': {'broadcaster': '1'}, 'forbid': {'all': '0', 'uids': [], 'badges': {}}}, 'on_channel': {'all': '0', 'uids': [], 'badges': {}, 'forbid': {'all': '0', 'uids': [], 'badges': {}}}, 'on_commadd': {'all': '0', 'uids': [], 'badges': {'broadcaster': '1'}, 'for... |
a = 0
def fun1():
print("fun1: a=", a)
def fun2():
a = 10 # By default, the assignment statement creates variables in the local scope
print("fun2: a=", a)
def fun3():
global a # refer global variable
a = 5
print("fun3: a=", a)
fun1()
fun2()
fun1()
fun3()
fun1()
| a = 0
def fun1():
print('fun1: a=', a)
def fun2():
a = 10
print('fun2: a=', a)
def fun3():
global a
a = 5
print('fun3: a=', a)
fun1()
fun2()
fun1()
fun3()
fun1() |
def reverse_string(string):
reversed_letters = list()
index = 1
for letter in string:
reversed_letters.append(string[ len(string) - index ])
index += 1
return "".join(reversed_letters)
word_input = str(input("Input a word: "))
print(f"INPUT: {word_input}")
print("OUTPUT: %s (%d char... | def reverse_string(string):
reversed_letters = list()
index = 1
for letter in string:
reversed_letters.append(string[len(string) - index])
index += 1
return ''.join(reversed_letters)
word_input = str(input('Input a word: '))
print(f'INPUT: {word_input}')
print('OUTPUT: %s (%d characters)... |
def conta_a(palavra):
c = 0
for letra in palavra:
if letra == 'a':
c += 1
return c
s = 'Insper'
r = s[::-2]
print(r)
| def conta_a(palavra):
c = 0
for letra in palavra:
if letra == 'a':
c += 1
return c
s = 'Insper'
r = s[::-2]
print(r) |
#String functions
myStr = 'Hello world!'
#Capitalize
print(myStr.capitalize())
#Swap case
print(myStr.swapcase())
#Get length
print(len(myStr))
#Replace
print(myStr.replace('world', 'everyone'))
#Count
sub = 'l'
print(myStr.count(sub))
#Startswith
print(myStr.startswith('Hello'))
#Endswith
print(myStr.endswith(... | my_str = 'Hello world!'
print(myStr.capitalize())
print(myStr.swapcase())
print(len(myStr))
print(myStr.replace('world', 'everyone'))
sub = 'l'
print(myStr.count(sub))
print(myStr.startswith('Hello'))
print(myStr.endswith('Hello'))
print(myStr.split())
print(myStr.find('world'))
print(myStr.index('world'))
print(myStr.... |
#!/usr/bin/env python
DESCRIPTION = "Variant of djb2 hash in use by Nokoyawa ransomware"
# Type can be either 'unsigned_int' (32bit) or 'unsigned_long' (64bit)
TYPE = 'unsigned_int'
# Test must match the exact has of the string 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
TEST_1 = 3792689168
def ... | description = 'Variant of djb2 hash in use by Nokoyawa ransomware'
type = 'unsigned_int'
test_1 = 3792689168
def hash(data):
generated_hash = 5381
for b in data:
generated_hash = generated_hash * 33 + (b if b < 97 else b - 32) & 4294967295
return generated_hash |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"Scraper": "00_scraper.ipynb",
"Scraper.get_facebook_posts": "00_scraper.ipynb",
"print_something": "00_scraper.ipynb"}
modules = ["scraper.py"]
doc_url = "https://devacto.github.io/talk_l... | __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'Scraper': '00_scraper.ipynb', 'Scraper.get_facebook_posts': '00_scraper.ipynb', 'print_something': '00_scraper.ipynb'}
modules = ['scraper.py']
doc_url = 'https://devacto.github.io/talk_like/'
git_url = 'https://github.com/devacto/talk_like/tree/ma... |
class Solution:
def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]:
FI_A = list()
for row in A:
row = [0 if i else 1 for i in row[::-1]]
FI_A.append(row)
return FI_A
| class Solution:
def flip_and_invert_image(self, A: List[List[int]]) -> List[List[int]]:
fi_a = list()
for row in A:
row = [0 if i else 1 for i in row[::-1]]
FI_A.append(row)
return FI_A |
{{AUTO_GENERATED_NOTICE}}
load("@{{REPO_NAME}}//:rules.bzl", "rescript_compiler")
rescript_compiler(
name = "darwin",
bsc = ":darwin/bsc.exe",
bsb_helper = ":darwin/bsb_helper.exe",
visibility = ["//visibility:public"],
)
rescript_compiler(
name = "linux",
bsc = ":linux/bsc.exe",
bsb_helpe... | {{AUTO_GENERATED_NOTICE}}
load('@{{REPO_NAME}}//:rules.bzl', 'rescript_compiler')
rescript_compiler(name='darwin', bsc=':darwin/bsc.exe', bsb_helper=':darwin/bsb_helper.exe', visibility=['//visibility:public'])
rescript_compiler(name='linux', bsc=':linux/bsc.exe', bsb_helper=':linux/bsb_helper.exe', visibility=['//visi... |
def myFunction():
print('The value of __name__ is ' + __name__)
def main():
myFunction()
if __name__ == '__main__':
main() | def my_function():
print('The value of __name__ is ' + __name__)
def main():
my_function()
if __name__ == '__main__':
main() |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 2 10:39:47 2019
@author: ldh
"""
# __init__.py | """
Created on Tue Apr 2 10:39:47 2019
@author: ldh
""" |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Yue-Wen FANG'
__maintainer__ = "Yue-Wen FANG"
__email__ = 'fyuewen@gmail.com'
__license__ = 'Apache License 2.0'
__creation_date__= 'Dec. 26, 2018'
"""
single inheritance
"""
class Person:
"""
define a CLASS Person with three methods
"""
de... | __author__ = 'Yue-Wen FANG'
__maintainer__ = 'Yue-Wen FANG'
__email__ = 'fyuewen@gmail.com'
__license__ = 'Apache License 2.0'
__creation_date__ = 'Dec. 26, 2018'
'\nsingle inheritance\n'
class Person:
"""
define a CLASS Person with three methods
"""
def speak(self):
print('How are you?')
... |
tokens = {
'ID': r'[A-Za-z][A-Za-z_0-9]*',
'FLOATNUM': r'(([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)([Ee][+-]?[0-9]+)?|[0-9]+[Ee][+-]?[0-9]+)',
'INTNUM': r'[0-9]+',
# Multi-character operators
'==': r'==',
'<=': r'<=',
'>=': r'>=',
'<>': r'<>',
'::': r'::',
}
special_characters = '<>+-*/=(){}... | tokens = {'ID': '[A-Za-z][A-Za-z_0-9]*', 'FLOATNUM': '(([0-9]+\\.[0-9]*|[0-9]*\\.[0-9]+)([Ee][+-]?[0-9]+)?|[0-9]+[Ee][+-]?[0-9]+)', 'INTNUM': '[0-9]+', '==': '==', '<=': '<=', '>=': '>=', '<>': '<>', '::': '::'}
special_characters = '<>+-*/=(){}[];,.:'
reserved_keywords = {'if': 'IF', 'then': 'THEN', 'else': 'ELSE', 'w... |
"""
Range
range(stop)
range(start, stop)
range(start, stop, step)
default start = 0
default step = 1
"""
r = range(5, 10, 2)
print(r.start)
print(r.stop)
print(r.step)
print(type(r))
| """
Range
range(stop)
range(start, stop)
range(start, stop, step)
default start = 0
default step = 1
"""
r = range(5, 10, 2)
print(r.start)
print(r.stop)
print(r.step)
print(type(r)) |
count = 0
maximum = (-10) ** 9
for _ in range(4):
x = int(input())
if x % 2 == 1:
count += 1
if x > maximum:
maximum = x
if count > 0:
print(count)
print(maximum)
else:
print('NO')
| count = 0
maximum = (-10) ** 9
for _ in range(4):
x = int(input())
if x % 2 == 1:
count += 1
if x > maximum:
maximum = x
if count > 0:
print(count)
print(maximum)
else:
print('NO') |
# Neon number --> If the sum of digits of the squared numbers are equal to the orignal number , the number is said to be Neon number. Example 9
ch=int(input("Enter 1 to do it with loop and 2 without loop :\n"))
n= int(input("Enter the number :\n"))
def number(n):
sq= n**2
digisum=0
while sq>0:
r... | ch = int(input('Enter 1 to do it with loop and 2 without loop :\n'))
n = int(input('Enter the number :\n'))
def number(n):
sq = n ** 2
digisum = 0
while sq > 0:
r = sq % 10
digisum = digisum + r
sq = sq // 10
if n == digisum:
print('The number is neon number')
else:
... |
raio = int(input('Raio: '))
format(r,'.2f')
pi = 3.14159
volume = (4/3)*pi*raio**3
print("Volume = ", format(volume,'.3f'))
#Para o URI:
R = float(input())
format(R,'.2f')
pi = 3.14159
v = (4/3)*pi*R**3
print("VOLUME = "+format(v,'.3f')) | raio = int(input('Raio: '))
format(r, '.2f')
pi = 3.14159
volume = 4 / 3 * pi * raio ** 3
print('Volume = ', format(volume, '.3f'))
r = float(input())
format(R, '.2f')
pi = 3.14159
v = 4 / 3 * pi * R ** 3
print('VOLUME = ' + format(v, '.3f')) |
# -*- coding: utf-8 -*-
# @Time: 2020/7/16 11:38
# @Author: GraceKoo
# @File: interview_8.py
# @Desc: https://www.nowcoder.com/practice/8c82a5b80378478f9484d87d1c5f12a4?tpId=13&rp=1&ru=%2Fta%2Fcoding-interviews&qr
# u=%2Fta%2Fcoding-interviews%2Fquestion-ranking
class Solution:
def climbStairs(self, n: int) -> in... | class Solution:
def climb_stairs(self, n: int) -> int:
if 0 <= n <= 2:
return n
dp = [i for i in range(n)]
dp[0] = 1
dp[1] = 2
for i in range(2, n):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[-1]
so = solution()
print(so.climbStairs(3)) |
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
def BackTrack(m, per: list):
if m == n:
if per not in permutation:
permutation.append(per)
return per
for i in range(n):
if not visited[i]:... | class Solution:
def permute_unique(self, nums: List[int]) -> List[List[int]]:
def back_track(m, per: list):
if m == n:
if per not in permutation:
permutation.append(per)
return per
for i in range(n):
if not visited... |
def f(*args):
summ = 0
for i in args:
if isinstance(i, list):
for s in i:
summ += f(s)
elif isinstance(i, tuple):
for s in i:
summ += s
else:
summ += i
return summ
a = [[1, 2, [3]], [1], 3]
b = (1, 2, 3, 4... | def f(*args):
summ = 0
for i in args:
if isinstance(i, list):
for s in i:
summ += f(s)
elif isinstance(i, tuple):
for s in i:
summ += s
else:
summ += i
return summ
a = [[1, 2, [3]], [1], 3]
b = (1, 2, 3, 4, 5)
print(... |
EMPTY_WORDS_PATH = "./palabrasvacias.txt"
# "palabrasvacias.txt"
# "emptywords.txt"
# None
DIRPATH = "/home/agustin/Desktop/Recuperacion/colecciones/RI-tknz-data/"
# "/home/agustin/Desktop/Recuperacion/colecciones/RI-tknz-data/"
# "/home/agustin/Desktop/Recuperacion/colecciones/wiki-small/"
# "/home/agustin/Desktop/Re... | empty_words_path = './palabrasvacias.txt'
dirpath = '/home/agustin/Desktop/Recuperacion/colecciones/RI-tknz-data/'
min_term_length = 3
max_term_length = 25
string_store_criterion = 'MAX'
docnames_size = 50
terms_size = 50
stemming_language = 'spanish'
extract_entities = False
corpus_files_encoding = 'UTF-8'
id_in_docna... |
# loop3
userinput = input("Enter a letter in the range A - C : ")
while (userinput != "A") and (userinput != "a") and (userinput != "B") and (userinput != "b") and (userinput != "C") and (userinput != "c"):
userinput = input("Enter a letter in the range A-C : ")
| userinput = input('Enter a letter in the range A - C : ')
while userinput != 'A' and userinput != 'a' and (userinput != 'B') and (userinput != 'b') and (userinput != 'C') and (userinput != 'c'):
userinput = input('Enter a letter in the range A-C : ') |
class Song:
"""
@brief A Song object, used along with the Songs data source.
This is a convenience class provided for users who wish to use this
data source as part of their application. It provides an API that makes
it easy to access the attributes of this data set.
This object is generally... | class Song:
"""
@brief A Song object, used along with the Songs data source.
This is a convenience class provided for users who wish to use this
data source as part of their application. It provides an API that makes
it easy to access the attributes of this data set.
This object is generally... |
COLOR = {
'ORANGE': (255, 121, 0),
'LIGHT_YELLOW': (255, 230, 130),
'YELLOW': (255, 204, 0),
'LIGHT_BLUE': (148, 228, 228),
'BLUE': (51, 204, 204),
'LIGHT_RED': (255, 136, 106),
'RED': (255, 51, 0),
'LIGHT_GREEN': (206, 255, 60),
'GREEN': (153, 204, 0),
'CYAN': (0, 159, 218),
... | color = {'ORANGE': (255, 121, 0), 'LIGHT_YELLOW': (255, 230, 130), 'YELLOW': (255, 204, 0), 'LIGHT_BLUE': (148, 228, 228), 'BLUE': (51, 204, 204), 'LIGHT_RED': (255, 136, 106), 'RED': (255, 51, 0), 'LIGHT_GREEN': (206, 255, 60), 'GREEN': (153, 204, 0), 'CYAN': (0, 159, 218), 'BLUE_PAUL': (0, 59, 111), 'PURPLE': (161, 6... |
# -*- coding: utf-8 -*-
class Solution:
def minDeletionSize(self, A):
return len([col for col in zip(*A) if col != tuple(sorted(col))])
if __name__ == '__main__':
solution = Solution()
assert 1 == solution.minDeletionSize(['cba', 'daf', 'ghi'])
assert 0 == solution.minDeletionSize(['a', 'b'... | class Solution:
def min_deletion_size(self, A):
return len([col for col in zip(*A) if col != tuple(sorted(col))])
if __name__ == '__main__':
solution = solution()
assert 1 == solution.minDeletionSize(['cba', 'daf', 'ghi'])
assert 0 == solution.minDeletionSize(['a', 'b'])
assert 3 == solutio... |
# https://leetcode.com/problems/simplify-path/
class Solution:
def simplifyPath(self, path: str) -> str:
stack = []
for d in path.split('/'):
if d == '..':
if len(stack) > 0:
stack.pop()
elif d == '.' or d == '':
continue
... | class Solution:
def simplify_path(self, path: str) -> str:
stack = []
for d in path.split('/'):
if d == '..':
if len(stack) > 0:
stack.pop()
elif d == '.' or d == '':
continue
else:
stack.append(... |
# Guess password and output the score
chocolate = 2
playerlives = 1
playername = "Aung"
# this loop clears the screen
for i in range(1, 35):
print()
bonus = 0
numbercorrect = 0
# the player must try to guess the password
print("Now you must ener each letter that you remember ")
print("You will be given 3 times")... | chocolate = 2
playerlives = 1
playername = 'Aung'
for i in range(1, 35):
print()
bonus = 0
numbercorrect = 0
print('Now you must ener each letter that you remember ')
print('You will be given 3 times')
i = 0
while i < 3:
i = i + 1
letter = input('Try number ' + str(i) + ' : ')
if letter == 'A' or letter... |
#!/usr/bin/env python3
def best_stock(data):
return sorted(data.items(), key=lambda x: x[1])[-1][0]
if __name__ == '__main__':
print(best_stock({ "CAL": 42.0, "GOG": 190.5, "DAG": 32.2 }))
assert best_stock({ "CAL": 42.0, "GOG": 190.5, "DAG": 32.2 }) == "GOG"
assert best_stock({ "CAL": 31.4, "GOG": 3... | def best_stock(data):
return sorted(data.items(), key=lambda x: x[1])[-1][0]
if __name__ == '__main__':
print(best_stock({'CAL': 42.0, 'GOG': 190.5, 'DAG': 32.2}))
assert best_stock({'CAL': 42.0, 'GOG': 190.5, 'DAG': 32.2}) == 'GOG'
assert best_stock({'CAL': 31.4, 'GOG': 3.42, 'APL': 170.34}) == 'APL' |
def find_position(matrix, size, symbol):
positions = []
for row in range(size):
for col in range(size):
if matrix[row][col] == symbol:
positions.append([row, col])
return positions
def is_position_valid(row, col, size):
return 0 <= row < size and 0 <= col < size
d... | def find_position(matrix, size, symbol):
positions = []
for row in range(size):
for col in range(size):
if matrix[row][col] == symbol:
positions.append([row, col])
return positions
def is_position_valid(row, col, size):
return 0 <= row < size and 0 <= col < size
def... |
items = {key: {} for key in input().split(", ")}
n = int(input())
for _ in range(n):
line = input().split(" - ")
category, item = line[0], line[1]
items_count = line[2].split(";")
quantity = int(items_count[0].split(":")[1])
quality = int(items_count[1].split(":")[1])
items[category][item] = (... | items = {key: {} for key in input().split(', ')}
n = int(input())
for _ in range(n):
line = input().split(' - ')
(category, item) = (line[0], line[1])
items_count = line[2].split(';')
quantity = int(items_count[0].split(':')[1])
quality = int(items_count[1].split(':')[1])
items[category][item] =... |
cnt = int(input())
for i in range(cnt):
s=input()
a=s.lower()
g=a.count('g')
b=a.count('b')
print(s,"is",end=" ")
if g == b:
print("NEUTRAL")
elif g>b:
print("GOOD")
else:
print("A BADDY") | cnt = int(input())
for i in range(cnt):
s = input()
a = s.lower()
g = a.count('g')
b = a.count('b')
print(s, 'is', end=' ')
if g == b:
print('NEUTRAL')
elif g > b:
print('GOOD')
else:
print('A BADDY') |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
Fenwick tree
jill-jenn vie et christoph durr - 2014-2018
"""
# snip{
class Fenwick:
"""maintains a tree to allow quick updates and queries
"""
def __init__(self, t):
"""stores a table t and allows updates and queries
of prefix sums in log... | """Fenwick tree
jill-jenn vie et christoph durr - 2014-2018
"""
class Fenwick:
"""maintains a tree to allow quick updates and queries
"""
def __init__(self, t):
"""stores a table t and allows updates and queries
of prefix sums in logarithmic time.
:param array t: with numerical va... |
print("Enter a character:\n")
ch=input()
while(len(ch)!=1):
print("\nShould Enter single Character...RETRY!")
ch=input()
print(ord(ch))
| print('Enter a character:\n')
ch = input()
while len(ch) != 1:
print('\nShould Enter single Character...RETRY!')
ch = input()
print(ord(ch)) |
class Solution:
def parseTernary(self, expression: str) -> str:
c, values = expression.split('?', 1)
cnt = 0
p = 0
for i in range(len(values)):
if values[i] == ':':
if cnt > 0:
cnt -= 1
else:
p = i
... | class Solution:
def parse_ternary(self, expression: str) -> str:
(c, values) = expression.split('?', 1)
cnt = 0
p = 0
for i in range(len(values)):
if values[i] == ':':
if cnt > 0:
cnt -= 1
else:
p = ... |
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
# just use a sliding window
np, ns = len(p), len(s)
res = []
if np > ns: return []
map_ = [0] * 26
for i,x in enumerate(p):
map_[ord(x) - 97] -= 1
map_[ord(s[i])-97]... | class Solution:
def find_anagrams(self, s: str, p: str) -> List[int]:
(np, ns) = (len(p), len(s))
res = []
if np > ns:
return []
map_ = [0] * 26
for (i, x) in enumerate(p):
map_[ord(x) - 97] -= 1
map_[ord(s[i]) - 97] += 1
for i in ... |
'''
An N x N board contains only 0s and 1s. In each move, you can swap any 2 rows with each other, or any 2 columns with each other.
What is the minimum number of moves to transform the board into a "chessboard" - a board where no 0s and no 1s are 4-directionally
adjacent? If the task is impossible, return -1.
Examp... | """
An N x N board contains only 0s and 1s. In each move, you can swap any 2 rows with each other, or any 2 columns with each other.
What is the minimum number of moves to transform the board into a "chessboard" - a board where no 0s and no 1s are 4-directionally
adjacent? If the task is impossible, return -1.
Examp... |
memMap = {}
def fibonacci (n):
if (n not in memMap):
if n <= 0:
print("Invalid input")
elif n == 1:
memMap[n] = 0
elif n == 2:
memMap[n] = 1
else:
memMap[n] = fibonacci (n-1) + fibonacci (n-2)
return memMap[n]
def fibonacciSlow (n):
if n <= 0:
print("Invalid inpu... | mem_map = {}
def fibonacci(n):
if n not in memMap:
if n <= 0:
print('Invalid input')
elif n == 1:
memMap[n] = 0
elif n == 2:
memMap[n] = 1
else:
memMap[n] = fibonacci(n - 1) + fibonacci(n - 2)
return memMap[n]
def fibonacci_slow(n... |
class Hashtable:
def __init__(self):
"""
Create an array(self.my dict) w/ a bucket size - derived from load factor.
Load factor --> a measure that decides when to increase the Hashmap capacity to maintain the get() and put() operator complexity of o(1).
Default load factor of hashmap... | class Hashtable:
def __init__(self):
"""
Create an array(self.my dict) w/ a bucket size - derived from load factor.
Load factor --> a measure that decides when to increase the Hashmap capacity to maintain the get() and put() operator complexity of o(1).
Default load factor of hashma... |
def embarque(motorista:str, passageiro:str, saida:dict):
fortwo = {'motorista': motorista, 'passageiro': passageiro}
saida['pessoas'].remove(motorista)
print(f"{fortwo['motorista']} embarcou como motorista")
if passageiro != '':
saida['pessoas'].remove(passageiro)
print(f"{fortwo['passa... | def embarque(motorista: str, passageiro: str, saida: dict):
fortwo = {'motorista': motorista, 'passageiro': passageiro}
saida['pessoas'].remove(motorista)
print(f"{fortwo['motorista']} embarcou como motorista")
if passageiro != '':
saida['pessoas'].remove(passageiro)
print(f"{fortwo['pas... |
class UnfoldingResult:
def __init__(self, solution, error):
self.solution = solution
self.error = error
| class Unfoldingresult:
def __init__(self, solution, error):
self.solution = solution
self.error = error |
# input number of testcases
test=int(input())
for i in range(test):
# input the number of predicted prices for WOT
n=int(input())
# input array of predicted stock price
a=list(map(int,input().split()))
c=0
i=len(a)-1
while(i>=0):
d=a[i]
l=i
p=0
while(a[i]<=d a... | test = int(input())
for i in range(test):
n = int(input())
a = list(map(int, input().split()))
c = 0
i = len(a) - 1
while i >= 0:
d = a[i]
l = i
p = 0
while a[i] <= d and i >= 0:
p += a[i]
i -= 1
c += (l - i) * a[l] - p
continue... |
class node:
def __init__(self,value):
self.data=value
self.next=None
self.prev=None
class DoubleLinkedList:
def __init__(self):
self.head=None
def insertAtBeg(self,value):
newnode = node(value)
if self.head==None:
self.head=newnode
else:
... | class Node:
def __init__(self, value):
self.data = value
self.next = None
self.prev = None
class Doublelinkedlist:
def __init__(self):
self.head = None
def insert_at_beg(self, value):
newnode = node(value)
if self.head == None:
self.head = newn... |
#!usr/bin/python
class Enviroment:
sets = []
banned = [] | class Enviroment:
sets = []
banned = [] |
'''
udata-schema-gouvfr
Integration with schema.data.gouv.fr
'''
__version__ = '1.3.3.dev'
__description__ = 'Integration with schema.data.gouv.fr'
| """
udata-schema-gouvfr
Integration with schema.data.gouv.fr
"""
__version__ = '1.3.3.dev'
__description__ = 'Integration with schema.data.gouv.fr' |
#
# PySNMP MIB module WIENER-CRATE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///home/tin/Dev/mibs.snmplabs.com/asn1/WIENER-CRATE-MIB
# Produced by pysmi-0.3.4 at Fri Jan 31 21:36:11 2020
# On host bier platform Linux version 5.4.0-3-amd64 by user tin
# Using Python version 3.7.6 (default, Jan 19 2020, 22:34:5... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, single_value_constraint, value_range_constraint, value_size_constraint) ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Source code meta data
__author__ = 'Dalwar Hossain'
__email__ = 'dalwar.hossain@protonmail.com'
# Version
__version__ = '1.1'
__release__ = '1.1'
| __author__ = 'Dalwar Hossain'
__email__ = 'dalwar.hossain@protonmail.com'
__version__ = '1.1'
__release__ = '1.1' |
__version__ = '0.12.1'
__prog_name__ = 'DOLfYN'
__version_date__ = 'May-07-2020'
def ver2tuple(ver):
if isinstance(ver, tuple):
return ver
# ### Previously used FLOATS for 'save-format' versioning.
# Version 1.0: underscore ('_') handled inconsistently.
# Version 1.1: '_' and '#' handled consi... | __version__ = '0.12.1'
__prog_name__ = 'DOLfYN'
__version_date__ = 'May-07-2020'
def ver2tuple(ver):
if isinstance(ver, tuple):
return ver
if isinstance(ver, (float, int)):
return (0, int(ver), int(round(10 * (ver % 1))))
out = []
for val in ver.split('.'):
try:
val ... |
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 find_deletions(friends_file_path, new_friends_list):
deleted = ""
f1 = open(friends_file_path, "r")
data2 = new_friends_list
for line in f1:
if data2.find(line) == -1:
print ("--" +line),
deleted += line
f1.close()
return deleted
def find_additions(friends_file_path, new_friends_list):
added = "... | def find_deletions(friends_file_path, new_friends_list):
deleted = ''
f1 = open(friends_file_path, 'r')
data2 = new_friends_list
for line in f1:
if data2.find(line) == -1:
(print('--' + line),)
deleted += line
f1.close()
return deleted
def find_additions(friends_... |
# Copyright 2013 Daniel Stokes, Mitchell Stokes
#
# 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 ... | def get_condition(args):
return CONDITION_LUT[args[0]](*args[1:])
class Alwayscondition:
__slots__ = []
def test(self, data):
return True
class Rangecondition:
__slots__ = ['property', 'min', 'max']
def __init__(self, prop, _min, _max):
self.property = prop
if type(_min) ... |
def sort(list_):
"""
This function is a selection sort algorithm. It will put a list in numerical order.
:param list_: a list
:return: a list ordered by numerial order.
"""
for minimum in range(0, len(list_)):
for c in range(minimum + 1, len(list_)):
if list_[c] < list_[mini... | def sort(list_):
"""
This function is a selection sort algorithm. It will put a list in numerical order.
:param list_: a list
:return: a list ordered by numerial order.
"""
for minimum in range(0, len(list_)):
for c in range(minimum + 1, len(list_)):
if list_[c] < list_[minim... |
__title__ = 'pinecone-backend'
__summary__ = 'Domain.'
__version__ = '0.0.1-dev'
__license__ = 'All rights reserved.'
__uri__ = 'http://vigotech.org/'
__author__ = 'VigoTech'
__email__ = 'alliance@vigotech.org'
| __title__ = 'pinecone-backend'
__summary__ = 'Domain.'
__version__ = '0.0.1-dev'
__license__ = 'All rights reserved.'
__uri__ = 'http://vigotech.org/'
__author__ = 'VigoTech'
__email__ = 'alliance@vigotech.org' |
'''
This problem was asked by Facebook.
Implement regular expression matching with the following special characters:
. (period) which matches any single character
* (asterisk) which matches zero or more of the preceding element
That is, implement a function that takes in a string and a valid regular
expression and r... | """
This problem was asked by Facebook.
Implement regular expression matching with the following special characters:
. (period) which matches any single character
* (asterisk) which matches zero or more of the preceding element
That is, implement a function that takes in a string and a valid regular
expression and r... |
def permutations_with_dups(string):
hash_table = {}
permutations = []
for character in string:
if character in hash_table:
hash_table[character] += 1
else:
hash_table[character] = 1
helper('', hash_table, permutations)
return permutations
def helper(string, ... | def permutations_with_dups(string):
hash_table = {}
permutations = []
for character in string:
if character in hash_table:
hash_table[character] += 1
else:
hash_table[character] = 1
helper('', hash_table, permutations)
return permutations
def helper(string, h... |
"""
Sudoku solver script using a backtracking algorithm.
"""
def find_empty_location(grid):
"""
Looks for the coordinates of the next zero value on the grid,
starting on the upper left corner, from left to right and top to bottom.
Keyword Arguments:
grid {number matrix} -- The matrix to look f... | """
Sudoku solver script using a backtracking algorithm.
"""
def find_empty_location(grid):
"""
Looks for the coordinates of the next zero value on the grid,
starting on the upper left corner, from left to right and top to bottom.
Keyword Arguments:
grid {number matrix} -- The matrix to look f... |
#
# @lc app=leetcode id=1004 lang=python3
#
# [1004] Max Consecutive Ones III
#
# https://leetcode.com/problems/max-consecutive-ones-iii/description/
#
# algorithms
# Medium (61.32%)
# Likes: 2593
# Dislikes: 40
# Total Accepted: 123.4K
# Total Submissions: 202.1K
# Testcase Example: '[1,1,1,0,0,0,1,1,1,1,0]\n2'... | class Solution:
def longest_ones(self, nums: List[int], k: int) -> int:
if not nums or len(nums) == 0:
return 0
(left, right) = (0, 0)
if nums[right] == 0:
k -= 1
n = len(nums)
max_length = 0
for left in range(n):
while right + 1 <... |
SECRET_KEY = "fake-key"
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
}
INSTALLED_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"rest_email_manager",
]
TEMPLATES = [
{
"BACKEND": "django.template.backends.djan... | secret_key = 'fake-key'
databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}}
installed_apps = ['django.contrib.auth', 'django.contrib.contenttypes', 'rest_email_manager']
templates = [{'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True}]
root_urlconf = 'tests... |
"""BaseMetric class."""
class BaseMetric:
"""Base class for all the metrics in SDMetrics.
Attributes:
name (str):
Name to use when reports about this metric are printed.
goal (sdmetrics.goal.Goal):
The goal of this metric.
min_value (Union[float, tuple[float]])... | """BaseMetric class."""
class Basemetric:
"""Base class for all the metrics in SDMetrics.
Attributes:
name (str):
Name to use when reports about this metric are printed.
goal (sdmetrics.goal.Goal):
The goal of this metric.
min_value (Union[float, tuple[float]]):... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.