content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def invert_binary_tree(node):
if node:
node.left, node.right = invert_binary_tree(node.right), invert_binary_tree(node.left)
return node
class BinaryTreeNode(object):
def __init__(self, value, left=None, right=None):
self.value = value
self.left = None
self.right = None... | def invert_binary_tree(node):
if node:
(node.left, node.right) = (invert_binary_tree(node.right), invert_binary_tree(node.left))
return node
class Binarytreenode(object):
def __init__(self, value, left=None, right=None):
self.value = value
self.left = None
self.right = ... |
#!/usr/bin/env python3
def selection_sort(lst):
length = len(lst)
for i in range(length - 1):
least = i
for k in range(i + 1, length):
if lst[k] < lst[least]:
least = k
lst[least], lst[i] = (lst[i], lst[least])
return lst
print(selection_sort([5, 2, 4, ... | def selection_sort(lst):
length = len(lst)
for i in range(length - 1):
least = i
for k in range(i + 1, length):
if lst[k] < lst[least]:
least = k
(lst[least], lst[i]) = (lst[i], lst[least])
return lst
print(selection_sort([5, 2, 4, 6, 1, 3])) |
class EmailTypes(object):
AUTH_WELCOME_EMAIL = "auth__welcome_email"
AUTH_VERIFY_SIGNUP_EMAIL = "auth__verify_signup_email"
EMAILS = {}
EMAILS[EmailTypes.AUTH_WELCOME_EMAIL] = {
"is_active": False,
"html_template": "emails/action-template.html",
"text_template": "emails/action-template.txt",
... | class Emailtypes(object):
auth_welcome_email = 'auth__welcome_email'
auth_verify_signup_email = 'auth__verify_signup_email'
emails = {}
EMAILS[EmailTypes.AUTH_WELCOME_EMAIL] = {'is_active': False, 'html_template': 'emails/action-template.html', 'text_template': 'emails/action-template.txt', 'subject': '', 'send... |
test = {
'name': 'q3_1_8',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
>>> genre_and_distances.labels == ('Genre', 'Distance')
True
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>>... | test = {'name': 'q3_1_8', 'points': 1, 'suites': [{'cases': [{'code': "\n >>> genre_and_distances.labels == ('Genre', 'Distance')\n True\n ", 'hidden': False, 'locked': False}, {'code': '\n >>> genre_and_distances.num_rows == train_movies.num_rows\n True\n ', 'hidde... |
count = input('How many people will be in the dinner group? ')
count = int(count)
if count > 8:
print('You\'ll have to wait for a table.')
else:
print('The table is ready.')
| count = input('How many people will be in the dinner group? ')
count = int(count)
if count > 8:
print("You'll have to wait for a table.")
else:
print('The table is ready.') |
# Automatically generated
# pylint: disable=all
get = [{'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3, 'DefaultVCpus': 1, 'DefaultCores': 1, 'DefaultThreadsPerCore': 1, 'ValidCores': [1], 'ValidThreadsPerCore': [1], 'SizeInMiB': 2048, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supp... | get = [{'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3, 'DefaultVCpus': 1, 'DefaultCores': 1, 'DefaultThreadsPerCore': 1, 'ValidCores': [1], 'ValidThreadsPerCore': [1], 'SizeInMiB': 2048, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': 'Up to 10 Gigabit', ... |
# https://stockmarketmba.com/globalstockexchanges.php
exchanges = {
'USA': None,
'Germany': 'XETR',
'Hong Kong': 'XHKG',
'Japan': 'XTKS',
'France': 'XPAR',
'Canada': 'XTSE',
'United Kingdom': 'XLON',
'Switzerland': 'XSWX',
'Australia': 'XASX',
'South Korea': 'XKRX',
'The Net... | exchanges = {'USA': None, 'Germany': 'XETR', 'Hong Kong': 'XHKG', 'Japan': 'XTKS', 'France': 'XPAR', 'Canada': 'XTSE', 'United Kingdom': 'XLON', 'Switzerland': 'XSWX', 'Australia': 'XASX', 'South Korea': 'XKRX', 'The Netherlands': 'XAMS', 'Spain': 'XMAD', 'Russia': 'MISX', 'Italy': 'XMIL', 'Belgium': 'XBRU', 'Mexiko': ... |
def SC_DFA(y):
N = len(y)
tau = int(np.floor(N/2))
y = y - np.mean(y)
x = np.cumsum(y)
taus = np.arange(5,tau+1)
ntau = len(taus)
F = np.zeros(ntau)
for i in range(ntau):
t = int(taus[i])
x_buff = x[:N - N % t]
x_buff = x_buff.reshape((int(N / t),t))
... | def sc_dfa(y):
n = len(y)
tau = int(np.floor(N / 2))
y = y - np.mean(y)
x = np.cumsum(y)
taus = np.arange(5, tau + 1)
ntau = len(taus)
f = np.zeros(ntau)
for i in range(ntau):
t = int(taus[i])
x_buff = x[:N - N % t]
x_buff = x_buff.reshape((int(N / t), t))
... |
'''
Formula for area of circle
Area = pi * r^2
where pi is constant and r is the radius of the circle
'''
def findarea(r):
PI = 3.142
return PI * (r*r);
print("Area is %.6f" % findarea(5));
| """
Formula for area of circle
Area = pi * r^2
where pi is constant and r is the radius of the circle
"""
def findarea(r):
pi = 3.142
return PI * (r * r)
print('Area is %.6f' % findarea(5)) |
class Take(object):
def __init__(self, stage, unit, entity,
not_found_proc, finished_proc):
self._stage = stage
self._unit = unit
self._entity = entity
self._finished_proc = finished_proc
self._not_found_proc = not_found_proc
def enact(self):
if ... | class Take(object):
def __init__(self, stage, unit, entity, not_found_proc, finished_proc):
self._stage = stage
self._unit = unit
self._entity = entity
self._finished_proc = finished_proc
self._not_found_proc = not_found_proc
def enact(self):
if not self._entity... |
"""
Author: CaptCorpMURICA
Project: 100DaysPython
File: module1_day04_variables.py
Creation Date: 6/2/2019, 8:55 AM
Description: Learn about using variables in python.
"""
# Variables need to start with a letter or an underscore. Numbers can be used in the variable name... | """
Author: CaptCorpMURICA
Project: 100DaysPython
File: module1_day04_variables.py
Creation Date: 6/2/2019, 8:55 AM
Description: Learn about using variables in python.
"""
greeting = 'Hello'
_name = 'General Kenobi.'
greeting = 'There'
_best_line_ep3_ = 'You are a bold o... |
rows = []
with open("C:\\Privat\\advent_of_code20\\puzzle14\\input1.txt") as f:
for line in f:
rows.append(line.strip())
#print(rows)
memory = {}
currentMask = ""
for line in rows:
split = line.split(' = ')
if 'mask' in split[0]:
currentMask = split[1].strip()
else:
# value in... | rows = []
with open('C:\\Privat\\advent_of_code20\\puzzle14\\input1.txt') as f:
for line in f:
rows.append(line.strip())
memory = {}
current_mask = ''
for line in rows:
split = line.split(' = ')
if 'mask' in split[0]:
current_mask = split[1].strip()
else:
bit = format(int(split[1... |
startHTML = '''
<html>
<head>
<style>
table {
border-collapse: collapse;
height: 100%;
width: 100%;
}
table, th, td {
border: 3px solid black;
}
@media print {
table {
page-break-after: always;
... | start_html = '\n <html>\n <head>\n <style>\n table {\n border-collapse: collapse;\n height: 100%;\n width: 100%;\n }\n\n table, th, td {\n border: 3px solid black;\n }\n\n @media print {\n table {\n page-break-after: alw... |
#!/usr/bin/python3
class InstructionNotRecognized(Exception):
''' Exception to throw when an instruction does not have defined conversion code '''
pass
reg_labels = """ .section .tdata
REG_BANK:
.dword 0
.dword 0
.dword 0
.dword 0
.dword 0
.dword 0
... | class Instructionnotrecognized(Exception):
""" Exception to throw when an instruction does not have defined conversion code """
pass
reg_labels = ' .section .tdata\nREG_BANK:\n .dword 0\n .dword 0\n .dword 0\n .dword 0\n .dword 0\n .dword 0\n .dword 0\n ... |
# Copyright 2022, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complianc... | """ Operator code tables
These are mostly used to look up the Python C/API from operations or a wrapper used.
"""
unary_operator_codes = {'UAdd': ('PyNumber_Positive', 1), 'USub': ('PyNumber_Negative', 1), 'Invert': ('PyNumber_Invert', 1), 'Repr': ('PyObject_Repr', 1), 'Not': ('UNARY_NOT', 0)}
rich_comparison_codes =... |
# Use snippet 'summarize_a_survey_module' to output a table and a graph of
# participant counts by response for one question_concept_id
# The snippet assumes that a dataframe containing survey questions and answers already exists
# The snippet also assumes that setup has been run
# Update the next 3 lines
survey_df =... | survey_df = YOUR_DATASET_NAME_survey_df
question_concept_id = 1585940
denominator = None
def summarize_a_question_concept_id(df, question_concept_id, denominator=None):
df = df.loc[df['question_concept_id'] == question_concept_id].copy()
new_df = df.groupby(['answer_concept_id', 'answer'])['person_id'].nunique... |
class LOG:
def info(message):
print("Info: " + message)
def error(message):
print("Error: " + message)
def debug(message):
print("Debug: " + message)
| class Log:
def info(message):
print('Info: ' + message)
def error(message):
print('Error: ' + message)
def debug(message):
print('Debug: ' + message) |
if __name__ == '__main__':
# Fill in the code to do the following
# 1. Set x to be a non-negative integer (no decimals, no negatives)
# 2. If x is divisible by 3, print 'Fizz'
# 3. If x is divisible by 5, print 'Buzz'
# 4. If x is divisible by both 3 and 5, print 'FizzBuzz'
# 5. If x is divisib... | if __name__ == '__main__':
x = 1 |
class Solution:
def rotate(self, matrix) -> None:
result = []
for i in range(0,len(matrix)):
store = []
for j in range(len(matrix)-1,-1,-1):
store.append(matrix[j][i])
result.append(store)
for i in range(0,len(result)):
mat... | class Solution:
def rotate(self, matrix) -> None:
result = []
for i in range(0, len(matrix)):
store = []
for j in range(len(matrix) - 1, -1, -1):
store.append(matrix[j][i])
result.append(store)
for i in range(0, len(result)):
m... |
provinces = [
# ["nunavut", 2],
# ["yukon", 4],
# ["Northwest%20Territories",2],
# ["Prince%20Edward%20Island", 6],
# ["Newfoundland%20and%20Labrador", 12],
# ["New%20Brunswick", 28],
# ["Nova%20Scotia", 36],
# ["Saskatchewan", 34],
# ["Manitoba", 40],
# ["Alberta", 167],
# [... | provinces = [['ontario', 1000]] |
# Copyright 2019 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | """Implementation of `InvalidLaunchFileError` class."""
class Invalidlaunchfileerror(Exception):
"""Exception raised when the given launch file is not valid."""
def __init__(self, extension='', *, likely_errors=None):
"""Constructor."""
self._extension = extension
self._likely_errors =... |
class Estrella:
def __init__(self,galaxia ="none",temperatura = 0,masa = 0):
self.galaxia = galaxia
self.temperatura = temperatura
self.masa = masa
| class Estrella:
def __init__(self, galaxia='none', temperatura=0, masa=0):
self.galaxia = galaxia
self.temperatura = temperatura
self.masa = masa |
L = int(input())
Tot = 0
Med = 0
T = str(input()).upper()
M = [[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,... | l = int(input())
tot = 0
med = 0
t = str(input()).upper()
m = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0... |
#########################
# DO NOT MODIFY
#########################
# SETTINGS.INI
C_MAIN_SETTINGS = 'Main_Settings'
P_DIR_IGNORE = 'IgnoreDirectories'
P_FILE_IGNORE = 'IgnoreFiles'
P_SRC_DIR = 'SourceDirectory'
P_DEST_DIR = 'DestinationDirectories'
P_BATCH_SIZE = 'BatchProcessingGroupSize'
P_FILE_BUFFER = 'FileReadBuf... | c_main_settings = 'Main_Settings'
p_dir_ignore = 'IgnoreDirectories'
p_file_ignore = 'IgnoreFiles'
p_src_dir = 'SourceDirectory'
p_dest_dir = 'DestinationDirectories'
p_batch_size = 'BatchProcessingGroupSize'
p_file_buffer = 'FileReadBuffer'
p_server_ip = 'SFTPServerIP'
p_server_port = 'SFTPServerPort'
h_sha_256 = 'sha... |
def bubble_sort(iterable):
return sorted(iterable)
def selection_sort(iterable):
return sorted(iterable)
def insertion_sort(iterable):
return sorted(iterable)
def merge_sort(iterable):
return sorted(iterable)
def quicksort(iterable):
return sorted(iterable)
| def bubble_sort(iterable):
return sorted(iterable)
def selection_sort(iterable):
return sorted(iterable)
def insertion_sort(iterable):
return sorted(iterable)
def merge_sort(iterable):
return sorted(iterable)
def quicksort(iterable):
return sorted(iterable) |
class Payload:
def __init__(self, host,port, strs):
self.host,self.port,self.strs = host,port,strs
def create(self):
return """
conn = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
conn.connect(('{host}' , int({port})))
from os import walk\nfrom string import ascii_lower as a
for l in a:\n\t... | class Payload:
def __init__(self, host, port, strs):
(self.host, self.port, self.strs) = (host, port, strs)
def create(self):
return '\nconn = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nconn.connect((\'{host}\' , int({port})))\nfrom os import walk\nfrom string import ascii_lower as a\nf... |
class Author:
@property
def surname(self):
return self._surname
@property
def firstname(self):
return self._firstname
@property
def affiliation(self):
return self._affiliation
@property
def identifier(self):
return self._identifier
@firstname.sett... | class Author:
@property
def surname(self):
return self._surname
@property
def firstname(self):
return self._firstname
@property
def affiliation(self):
return self._affiliation
@property
def identifier(self):
return self._identifier
@firstname.sett... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2017, Jon Hawkesworth (@jhawkesworth) <jhawkesworth@protonmail.com>
# Copyright: (c) 2017, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: win_toast
short_descriptio... | documentation = '\n---\nmodule: win_toast\nshort_description: Sends Toast windows notification to logged in users on Windows 10 or later hosts\ndescription:\n - Sends alerts which appear in the Action Center area of the windows desktop.\noptions:\n expire:\n description:\n - How long in seconds before the n... |
VERSION = "1.4.4"
if __name__ == "__main__":
print(VERSION, end="")
| version = '1.4.4'
if __name__ == '__main__':
print(VERSION, end='') |
party_size = int(input())
days = int(input())
total_coins = 0
for day in range (1, days + 1):
if day % 10 == 0:
party_size -= 2
if day % 15 == 0:
party_size += 5
total_coins += (50 - (2 * party_size))
if day % 3 == 0:
total_coins -= (3 * party_size)
if day % 5 == 0:
... | party_size = int(input())
days = int(input())
total_coins = 0
for day in range(1, days + 1):
if day % 10 == 0:
party_size -= 2
if day % 15 == 0:
party_size += 5
total_coins += 50 - 2 * party_size
if day % 3 == 0:
total_coins -= 3 * party_size
if day % 5 == 0:
total_co... |
#break
for i in range(1,10,1):
if(i==5):
continue
print(i) | for i in range(1, 10, 1):
if i == 5:
continue
print(i) |
@bot.on(events.NewMessage(incoming=True))
@bot.on(events.MessageEdited(incoming=True))
async def common_incoming_handler(e):
if SPAM:
db=sqlite3.connect("spam_mute.db")
cursor=db.cursor()
cursor.execute('''SELECT * FROM SPAM''')
all_rows = cursor.fetchall()
for row in all_rows:
i... | @bot.on(events.NewMessage(incoming=True))
@bot.on(events.MessageEdited(incoming=True))
async def common_incoming_handler(e):
if SPAM:
db = sqlite3.connect('spam_mute.db')
cursor = db.cursor()
cursor.execute('SELECT * FROM SPAM')
all_rows = cursor.fetchall()
for row in all_row... |
"""Helper module for bitfields manipulation"""
class BitField(int):
"""Stores an int and converts it to a string corresponding to an enum"""
to_string = lambda self, enum: " ".join([i for i, j in enum._asdict().items() if self & j])
| """Helper module for bitfields manipulation"""
class Bitfield(int):
"""Stores an int and converts it to a string corresponding to an enum"""
to_string = lambda self, enum: ' '.join([i for (i, j) in enum._asdict().items() if self & j]) |
class ElectionFraudDiv2:
def IsFraudulent(self, percentages):
ra, rb = 0, 0
for p in percentages:
a, b = 10001, 0
for i in xrange(10001):
if int(round(i*100.0 / 10000)) == p:
a, b = min(a, i), max(b, i)
if not b:
... | class Electionfrauddiv2:
def is_fraudulent(self, percentages):
(ra, rb) = (0, 0)
for p in percentages:
(a, b) = (10001, 0)
for i in xrange(10001):
if int(round(i * 100.0 / 10000)) == p:
(a, b) = (min(a, i), max(b, i))
if not b:... |
# SPDX-FileCopyrightText: 2020 FoamyGuy for Adafruit Industries
#
# SPDX-License-Identifier: MIT
def wrap_nicely(string, max_chars):
""" From: https://www.richa1.com/RichardAlbritton/circuitpython-word-wrap-for-label-text/
A helper that will return the string with word-break wrapping.
:param str string: Th... | def wrap_nicely(string, max_chars):
""" From: https://www.richa1.com/RichardAlbritton/circuitpython-word-wrap-for-label-text/
A helper that will return the string with word-break wrapping.
:param str string: The text to be wrapped.
:param int max_chars: The maximum number of characters on a line before ... |
"""
1. Clarification
2. Possible solutions
- Recursive
- Iterative
- Morris traversal
3. Coding
4. Tests
"""
# 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
# T=... | """
1. Clarification
2. Possible solutions
- Recursive
- Iterative
- Morris traversal
3. Coding
4. Tests
"""
class Solution:
def inorder_traversal(self, root: TreeNode) -> List[int]:
if not root:
return []
self.ret = []
self.dfs(root)
return self.ret
de... |
class Solution:
def removeStones(self, stones: List[List[int]]) -> int:
graph = collections.defaultdict(list)
n = len(stones)
for i in range(n):
for j in range(n):
if i == j:
continue
if stones[i][0] == stones[j][0] or stones[i]... | class Solution:
def remove_stones(self, stones: List[List[int]]) -> int:
graph = collections.defaultdict(list)
n = len(stones)
for i in range(n):
for j in range(n):
if i == j:
continue
if stones[i][0] == stones[j][0] or stones[... |
'''
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 ... | """
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22,
5
/ 4 8
/ / 11 13 4
/ \\ 7 2 1... |
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
nums_dict = {}
for num in nums:
if num in nums_dict:
nums_dict[num] += 1
else:
nums_dict[num] = 1
return [key for key, value in nums_dict.items() if value > len(nu... | class Solution:
def majority_element(self, nums: List[int]) -> List[int]:
nums_dict = {}
for num in nums:
if num in nums_dict:
nums_dict[num] += 1
else:
nums_dict[num] = 1
return [key for (key, value) in nums_dict.items() if value > le... |
# -*- python -*-
load("@drake//tools/workspace:github.bzl", "github_archive")
def scs_repository(
name,
mirrors = None):
github_archive(
name = name,
repository = "cvxgrp/scs",
# When updating this commit, see drake/tools/workspace/qdldl/README.md.
commit = "v2.1.3"... | load('@drake//tools/workspace:github.bzl', 'github_archive')
def scs_repository(name, mirrors=None):
github_archive(name=name, repository='cvxgrp/scs', commit='v2.1.3', sha256='cb139aa8a53b8f6a7f2bacec4315b449ce366ec80b328e823efbaab56c847d20', build_file='@drake//tools/workspace/scs:package.BUILD.bazel', patches=[... |
while True:
ans = sorted([int(n) for n in input().split()])
if sum(ans) == 0:
break
print(*ans)
| while True:
ans = sorted([int(n) for n in input().split()])
if sum(ans) == 0:
break
print(*ans) |
{
"object_templates":
[
{
"name": "fridge",
"description": ["Fridge desc."],
"container": [10]
},
{
"type_name": "barrel",
"description": ["Barrel desc."],
"interest": [5],
"sound": {
"OPEN": 2
},
"container": [5],
}... | {'object_templates': [{'name': 'fridge', 'description': ['Fridge desc.'], 'container': [10]}, {'type_name': 'barrel', 'description': ['Barrel desc.'], 'interest': [5], 'sound': {'OPEN': 2}, 'container': [5]}, {'type_name': 'stove', 'description': ['device desc.'], 'device': []}]} |
# card_hold_href is the stored href for the CardHold
card_hold = balanced.CardHold.fetch(card_hold_href)
debit = card_hold.capture(
appears_on_statement_as='ShowsUpOnStmt',
description='Some descriptive text for the debit in the dashboard'
) | card_hold = balanced.CardHold.fetch(card_hold_href)
debit = card_hold.capture(appears_on_statement_as='ShowsUpOnStmt', description='Some descriptive text for the debit in the dashboard') |
'''
Given a non-empty array of integers, every element appears
three times except for one, which appears exactly once.
Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
'''
class Solution:
def singleNumber(self, nums: List[i... | """
Given a non-empty array of integers, every element appears
three times except for one, which appears exactly once.
Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
"""
class Solution:
def single_number(self, nums: List[i... |
class Android:
# adb keyevent
KEYCODE_ENTER = "KEYCODE_DPAD_CENTER"
KEYCODE_RIGHT = "KEYCODE_DPAD_RIGHT"
KEYCODE_LEFT = "KEYCODE_DPAD_LEFT"
KEYCODE_DOWN = "KEYCODE_DPAD_DOWN"
KEYCODE_UP = "KEYCODE_DPAD_UP"
KEYCODE_SPACE = "KEYCODE_SPACE"
# adb get property
PROP_LANGUAGE = "persist.s... | class Android:
keycode_enter = 'KEYCODE_DPAD_CENTER'
keycode_right = 'KEYCODE_DPAD_RIGHT'
keycode_left = 'KEYCODE_DPAD_LEFT'
keycode_down = 'KEYCODE_DPAD_DOWN'
keycode_up = 'KEYCODE_DPAD_UP'
keycode_space = 'KEYCODE_SPACE'
prop_language = 'persist.sys.language'
prop_country = 'persist.sy... |
"""CUBRID FIELD_TYPE Constants
These constants represent the various column (field) types that are
supported by CUBRID.
"""
CHAR = 1
VARCHAR = 2
NCHAR = 3
VARNCHAR = 4
BIT = 5
VARBIT = 6
NUMERIC = 7
INT = 8
SMALLINT = 9
MONETARY = 10
BIGINT = 21
FLOAT = 11
DOUBLE = 12
DATE = 13
TIME = 14
T... | """CUBRID FIELD_TYPE Constants
These constants represent the various column (field) types that are
supported by CUBRID.
"""
char = 1
varchar = 2
nchar = 3
varnchar = 4
bit = 5
varbit = 6
numeric = 7
int = 8
smallint = 9
monetary = 10
bigint = 21
float = 11
double = 12
date = 13
time = 14
timestamp = 15
object = 19
se... |
gainGyroAngle = 1156*1.4
gainGyroRate = 146*0.85
gainMotorAngle = 7*1
gainMotorAngularSpeed = 9*0.95
gainMotorAngleErrorAccumulated = 0.6
| gain_gyro_angle = 1156 * 1.4
gain_gyro_rate = 146 * 0.85
gain_motor_angle = 7 * 1
gain_motor_angular_speed = 9 * 0.95
gain_motor_angle_error_accumulated = 0.6 |
# Upper makes a string completely capitalized.
parrot = "norwegian blue"
print ("parrot").upper() | parrot = 'norwegian blue'
print('parrot').upper() |
file = open('binaryBoarding_input.py', 'r')
tickets = file.readlines()
total_rows = 128
total_columns = 8
def find_row(boarding_pass):
min_row = 0
max_row = total_rows - 1
for letter in boarding_pass[:7]:
if letter == 'F':
max_row = max_row - int((max_row - min_row) / 2) - 1
e... | file = open('binaryBoarding_input.py', 'r')
tickets = file.readlines()
total_rows = 128
total_columns = 8
def find_row(boarding_pass):
min_row = 0
max_row = total_rows - 1
for letter in boarding_pass[:7]:
if letter == 'F':
max_row = max_row - int((max_row - min_row) / 2) - 1
eli... |
x = int(input())
y = int(input())
NotMult = 0
if x<y:
for c in range(x, y+1):
if (c%13)!=0:
NotMult += c
if x>y:
for c in range(y, x+1):
if (c%13)!=0:
NotMult += c
print(NotMult)
| x = int(input())
y = int(input())
not_mult = 0
if x < y:
for c in range(x, y + 1):
if c % 13 != 0:
not_mult += c
if x > y:
for c in range(y, x + 1):
if c % 13 != 0:
not_mult += c
print(NotMult) |
# Control all of the game settings.
# Imports
class Settings():
"""Class to store all game settings."""
# Initalize game settings
def __init__(self):
# Screen Settings
self.screen_width = 1200
self.screen_height = 800
self.bgColor = (230,230,230)
# Ship settings
... | class Settings:
"""Class to store all game settings."""
def __init__(self):
self.screen_width = 1200
self.screen_height = 800
self.bgColor = (230, 230, 230)
self.shipSpeedFactor = 1
self.ship_limit = 3
self.bullet_speed_factor = 3
self.bullet_width = 3
... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
def test1():
print('\ntest1')
x = 10
y = 1
result = x if x > y else y
print(result)
def max2(x, y):
return x if x > y else y
def test2():
print('\ntest2')
print(max2(10, 20))
print(max2(2, 1))
def main():
test1()
test2()
... | def test1():
print('\ntest1')
x = 10
y = 1
result = x if x > y else y
print(result)
def max2(x, y):
return x if x > y else y
def test2():
print('\ntest2')
print(max2(10, 20))
print(max2(2, 1))
def main():
test1()
test2()
if __name__ == '__main__':
main() |
"""pytest is unhappy if it finds no tests"""
def test_nothing():
"""An empty test to keep pytest happy"""
| """pytest is unhappy if it finds no tests"""
def test_nothing():
"""An empty test to keep pytest happy""" |
name = input("What is your name?")
quest = input("What is your quest?")
color = input("What is your favorite color?")
print(f"So your name is {name}.\nYou seek to {quest}.\nYour favorite color is {color}.\nYou may cross!")
| name = input('What is your name?')
quest = input('What is your quest?')
color = input('What is your favorite color?')
print(f'So your name is {name}.\nYou seek to {quest}.\nYour favorite color is {color}.\nYou may cross!') |
a = list(map(int,input().split()))
b = list(map(int,input().split()))
for i in range(a[0]):
if b[i] < a[1]:
print(b[i],end='')
print(" ",end='') | a = list(map(int, input().split()))
b = list(map(int, input().split()))
for i in range(a[0]):
if b[i] < a[1]:
print(b[i], end='')
print(' ', end='') |
def main():
n = int(input())
v = list(map(int, input().split()))
m = dict()
res = 0
for i in v:
if i not in m:
m[i] = 0
m[i] += 1
k = v.copy()
for i in range(n - 1, 0, -1):
k[i - 1] = k[i] + k[i - 1]
for i in range(0, n - 1):
res += -(n - i ... | def main():
n = int(input())
v = list(map(int, input().split()))
m = dict()
res = 0
for i in v:
if i not in m:
m[i] = 0
m[i] += 1
k = v.copy()
for i in range(n - 1, 0, -1):
k[i - 1] = k[i] + k[i - 1]
for i in range(0, n - 1):
res += -(n - i - 1... |
expected_output = {
"main": {
"chassis": {
"C9407R": {
"name": "Chassis",
"descr": "Cisco Catalyst 9400 Series 7 Slot Chassis",
"pid": "C9407R",
"vid": "V01",
"sn": "******",
}
},
"TenGiga... | expected_output = {'main': {'chassis': {'C9407R': {'name': 'Chassis', 'descr': 'Cisco Catalyst 9400 Series 7 Slot Chassis', 'pid': 'C9407R', 'vid': 'V01', 'sn': '******'}}, 'TenGigabitEthernet3/0/1': {'SFP-10G-SR': {'name': 'TenGigabitEthernet3/0/1', 'descr': 'SFP 10GBASE-SR', 'pid': 'SFP-10G-SR', 'vid': '01', 'sn': '*... |
a = int(input())
s = list(range(1, a+1))
k = len(s)
while k > 1:
if k & 1:
s = s[::2]
del s[0]
else:
s = s[::2]
k = len(s)
print(s[0])
| a = int(input())
s = list(range(1, a + 1))
k = len(s)
while k > 1:
if k & 1:
s = s[::2]
del s[0]
else:
s = s[::2]
k = len(s)
print(s[0]) |
ANONYMOUS = 'Anonymous User'
PUBLIC_NON_REQUESTER = 'Public User - Non-Requester'
PUBLIC_REQUESTER = 'Public User - Requester'
AGENCY_HELPER = 'Agency Helper'
AGENCY_OFFICER = 'Agency FOIL Officer'
AGENCY_ADMIN = 'Agency Administrator'
POINT_OF_CONTACT = 'point_of_contact'
| anonymous = 'Anonymous User'
public_non_requester = 'Public User - Non-Requester'
public_requester = 'Public User - Requester'
agency_helper = 'Agency Helper'
agency_officer = 'Agency FOIL Officer'
agency_admin = 'Agency Administrator'
point_of_contact = 'point_of_contact' |
class Solution:
def partition(self, head, x):
h1 = l1 = ListNode(0)
h2 = l2 = ListNode(0)
while head:
if head.val < x:
l1.next = head
l1 = l1.next
else:
l2.next = head
l2 = l2.next
head = head... | class Solution:
def partition(self, head, x):
h1 = l1 = list_node(0)
h2 = l2 = list_node(0)
while head:
if head.val < x:
l1.next = head
l1 = l1.next
else:
l2.next = head
l2 = l2.next
head = h... |
# Python 2.7 Coordinate Generation
MYARRAY = []
INCREMENTER = 0
while INCREMENTER < 501:
MYARRAY.append([INCREMENTER, INCREMENTER*2])
INCREMENTER += 1
| myarray = []
incrementer = 0
while INCREMENTER < 501:
MYARRAY.append([INCREMENTER, INCREMENTER * 2])
incrementer += 1 |
#: attr1
attr1: str = ''
#: attr2
attr2: str
#: attr3
attr3 = '' # type: str
class _Descriptor:
def __init__(self, name):
self.__doc__ = "This is {}".format(name)
def __get__(self):
pass
class Int:
"""An integer validator"""
@classmethod
def __call__(cls,x):
return int(x)... | attr1: str = ''
attr2: str
attr3 = ''
class _Descriptor:
def __init__(self, name):
self.__doc__ = 'This is {}'.format(name)
def __get__(self):
pass
class Int:
"""An integer validator"""
@classmethod
def __call__(cls, x):
return int(x)
class Class:
attr1: int = 0
... |
"""
Given a time represented in the format "HH:MM",
form the next closest time by reusing the current digits.
There is no limit on how many times a digit can be reused.
You may assume the given input string is always valid.
For example, "01:34", "12:09" are all valid.
"1:34", "12:9" are all invalid.
Example 1:
Inp... | """
Given a time represented in the format "HH:MM",
form the next closest time by reusing the current digits.
There is no limit on how many times a digit can be reused.
You may assume the given input string is always valid.
For example, "01:34", "12:09" are all valid.
"1:34", "12:9" are all invalid.
Example 1:
Inp... |
class PlayerInfo:
"""
Detail a Granade event
Attributes:
tick (int) : Game tick at time of kill
sec (float) : Seconds since round start
player_id (int) : Player's steamID
player_name (int) : Player's username
player_x_viz (float... | class Playerinfo:
"""
Detail a Granade event
Attributes:
tick (int) : Game tick at time of kill
sec (float) : Seconds since round start
player_id (int) : Player's steamID
player_name (int) : Player's username
player_x_viz (float... |
# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'includes': [
'../../build/common.gypi',
],
'target_defaults': {
'variables': {
'chromium_code': 1,
'version_py_path': '../..... | {'includes': ['../../build/common.gypi'], 'target_defaults': {'variables': {'chromium_code': 1, 'version_py_path': '../../chrome/tools/build/version.py', 'version_path': 'VERSION'}, 'include_dirs': ['../..'], 'libraries': ['userenv.lib'], 'sources': ['win/port_monitor/port_monitor.cc', 'win/port_monitor/port_monitor.h'... |
# -*- coding: utf-8 -*-
'''Snippets for string.
Available functions:
- to_titlecase: Convert the character string to titlecase.
'''
def to_titlecase(s: str) -> str:
'''For example:
>>> 'Hello world'.title()
'Hello World'
Args:
str: String excluding apostrophes in contra... | """Snippets for string.
Available functions:
- to_titlecase: Convert the character string to titlecase.
"""
def to_titlecase(s: str) -> str:
"""For example:
>>> 'Hello world'.title()
'Hello World'
Args:
str: String excluding apostrophes in contractions and possessives
for... |
t = int(input())
for t_itr in range(t):
n = int(input())
count = 0
for i in range(n+1):
if i%2 == 0:
count+=1
else:
count*=2
print(count)
| t = int(input())
for t_itr in range(t):
n = int(input())
count = 0
for i in range(n + 1):
if i % 2 == 0:
count += 1
else:
count *= 2
print(count) |
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
# Copyright (c) 2018 Juniper Networks, Inc.
# All rights reserved.
# Use is subject to license terms.
#
# Author: cklewar
class AMQPMessage(object):
# ------------------------------------------------------------------------
# property: message_ty... | class Amqpmessage(object):
@property
def message_type(self):
"""
:returns: message_type defines action to be done when received through message bus
"""
return self.__message_type
@property
def payload(self):
"""
:returns: data contains message payload
... |
class DaemonEvent(object):
def __init__(self, name, params) -> None:
super().__init__()
self.name = name
self.params = params
@classmethod
def from_json(cls, json):
return DaemonEvent(json["event"], json["params"])
| class Daemonevent(object):
def __init__(self, name, params) -> None:
super().__init__()
self.name = name
self.params = params
@classmethod
def from_json(cls, json):
return daemon_event(json['event'], json['params']) |
# -*- coding: utf-8 -*-
"""
@author: salimt
"""
#Problem 3
#20.0/20.0 points (graded)
#You are creating a song playlist for your next party. You have a collection of songs that can be represented as a list of tuples. Each tuple has the following elements:
#name: the first element, representing the song name ... | """
@author: salimt
"""
def song_playlist(songs, max_size):
"""
songs: list of tuples, ('song_name', song_len, song_size)
max_size: float, maximum size of total songs that you can fit
Start with the song first in the 'songs' list, then pick the next
song to be the one with the lowest file size no... |
#func-with-var-args.py
def addall(*nums):
ttl=0
for num in nums:
ttl=ttl+num
return ttl
total=addall(10,20,50,70)
print ('Total of 4 numbers:',total)
total=addall(11,34,43)
print ('Total of 3 numbers:',total)
| def addall(*nums):
ttl = 0
for num in nums:
ttl = ttl + num
return ttl
total = addall(10, 20, 50, 70)
print('Total of 4 numbers:', total)
total = addall(11, 34, 43)
print('Total of 3 numbers:', total) |
seq=[1,2,3,4,5]
for item in seq:
print (item);
print ("Hello")
i=1
while i<5:
print('i is :{}',format(i)) #i is always smaller than 5
i=i+1 #otherwise inifite loop
for x in seq:
print(x)
for x in range(0,5):
print(x) #short way to do the loop
list(range(10))
x=[1,2,3,4]
out=[]
for num in x:
out... | seq = [1, 2, 3, 4, 5]
for item in seq:
print(item)
print('Hello')
i = 1
while i < 5:
print('i is :{}', format(i))
i = i + 1
for x in seq:
print(x)
for x in range(0, 5):
print(x)
list(range(10))
x = [1, 2, 3, 4]
out = []
for num in x:
out.append(num ** 2)
out = [num ** 2 for num in x]
print(o... |
"""Singly linked list. """
class SinglyLinkedListException(Exception):
""" Base class for linked list module.
This will make it easier for future modifications
"""
class SinglyLinkedListIndexError(SinglyLinkedListException):
""" Invalid/Out of range index"""
def __init__(self, message="linke... | """Singly linked list. """
class Singlylinkedlistexception(Exception):
""" Base class for linked list module.
This will make it easier for future modifications
"""
class Singlylinkedlistindexerror(SinglyLinkedListException):
""" Invalid/Out of range index"""
def __init__(self, message='linked... |
#!/usr/bin/env python
__all__ = ["test_bedgraph", "test_clustal", "test_fasta"]
__author__ = ""
__copyright__ = "Copyright 2007-2020, The Cogent Project"
__credits__ = [
"Rob Knight",
"Gavin Huttley",
"Sandra Smit",
"Marcin Cieslik",
"Jeremy Widmann",
]
__license__ = "BSD-3"
__version__ = "2020.2.7... | __all__ = ['test_bedgraph', 'test_clustal', 'test_fasta']
__author__ = ''
__copyright__ = 'Copyright 2007-2020, The Cogent Project'
__credits__ = ['Rob Knight', 'Gavin Huttley', 'Sandra Smit', 'Marcin Cieslik', 'Jeremy Widmann']
__license__ = 'BSD-3'
__version__ = '2020.2.7a'
__maintainer__ = 'Gavin Huttley'
__email__ ... |
BOT_NAME = 'tabcrawler'
SPIDER_MODULES = ['tabcrawler.spiders']
NEWSPIDER_MODULE = 'tabcrawler.spiders'
DOWNLOAD_DELAY = 3
ITEM_PIPELINES = ['scrapy.contrib.pipeline.images.ImagesPipeline']
IMAGES_STORE = '/Users/jinzemin/Desktop/GuitarFan/tabcrawler/tabs'
# ITEM_PIPELINES = [
# 'tabcrawler.pipelines.ArtistPipeli... | bot_name = 'tabcrawler'
spider_modules = ['tabcrawler.spiders']
newspider_module = 'tabcrawler.spiders'
download_delay = 3
item_pipelines = ['scrapy.contrib.pipeline.images.ImagesPipeline']
images_store = '/Users/jinzemin/Desktop/GuitarFan/tabcrawler/tabs' |
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
counter = 0
for number in my_list:
counter = counter + number
print(counter)
| my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
counter = 0
for number in my_list:
counter = counter + number
print(counter) |
'''
It's Christmas time! To share his Christmas spirit with all his friends, the young Christmas Elf decided to send each of them a Christmas e-mail with a nice Christmas tree. Unfortunately, Internet traffic is very expensive in the North Pole, so instead of sending an actual image he got creative and drew the tree us... | """
It's Christmas time! To share his Christmas spirit with all his friends, the young Christmas Elf decided to send each of them a Christmas e-mail with a nice Christmas tree. Unfortunately, Internet traffic is very expensive in the North Pole, so instead of sending an actual image he got creative and drew the tree us... |
cpicker = lv.cpicker(lv.scr_act(),None)
cpicker.set_size(200, 200)
cpicker.align(None, lv.ALIGN.CENTER, 0, 0)
| cpicker = lv.cpicker(lv.scr_act(), None)
cpicker.set_size(200, 200)
cpicker.align(None, lv.ALIGN.CENTER, 0, 0) |
"""
Python implementation of a Circular Doubly Linked List With Sentinel.
In this version the Node class is hidden hence the usage is much more
similar to a normal list.
"""
class CDLLwS(object):
class Node(object):
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
def __st... | """
Python implementation of a Circular Doubly Linked List With Sentinel.
In this version the Node class is hidden hence the usage is much more
similar to a normal list.
"""
class Cdllws(object):
class Node(object):
def __init__(self, data):
self.data = data
self.prev = None
... |
class WorkflowException(Exception):
pass
class UnsupportedRequirement(WorkflowException):
pass
class ArgumentException(Exception):
"""Mismatched command line arguments provided."""
class GraphTargetMissingException(WorkflowException):
"""When a $graph is encountered and there is no target and no m... | class Workflowexception(Exception):
pass
class Unsupportedrequirement(WorkflowException):
pass
class Argumentexception(Exception):
"""Mismatched command line arguments provided."""
class Graphtargetmissingexception(WorkflowException):
"""When a $graph is encountered and there is no target and no main... |
class Solution:
def partitionLabels(self, s: str) -> List[int]:
# base case if we only have 1 letter
if len(s)<2:
return [1] #change to [len(s)]
response = [] # final response
memory = [] #track
memory.append(s[0])# we already known that we have at least 2 letters
... | class Solution:
def partition_labels(self, s: str) -> List[int]:
if len(s) < 2:
return [1]
response = []
memory = []
memory.append(s[0])
count = 1
i = 1
while i < len(s):
if s[i] in memory:
count += 1
else:
... |
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
b = bin(n)
if b[2] != '1':
return False
for bit in b[3:]:
if bit != '0':
return False
return True
print(Solution().isPowerOfTwo(1))
print(Solution().isPowerOfTwo(16))
print(Solution().... | class Solution:
def is_power_of_two(self, n: int) -> bool:
b = bin(n)
if b[2] != '1':
return False
for bit in b[3:]:
if bit != '0':
return False
return True
print(solution().isPowerOfTwo(1))
print(solution().isPowerOfTwo(16))
print(solution().... |
"""
tool for combining dictionaries.
IndexedValues is a list with a start index. It is for simulating dictionaries of {int: int>0}
"""
def generate_indexed_values(sorted_tuple_list):
"""
:param sorted_tuple_list: may not be empty.\n
[(int, int>0), ...]
"""
start_val, values = make_start_inde... | """
tool for combining dictionaries.
IndexedValues is a list with a start index. It is for simulating dictionaries of {int: int>0}
"""
def generate_indexed_values(sorted_tuple_list):
"""
:param sorted_tuple_list: may not be empty.
[(int, int>0), ...]
"""
(start_val, values) = make_start_inde... |
class _Attribute:
def __init__(self, name, value, deprecated=False):
self.name = name
self.value = value
self.deprecated = deprecated
def get_config(self):
"""Get in config format"""
return ' %s: %s\n' % (self.name, self.value) if self.value else None
def __str_... | class _Attribute:
def __init__(self, name, value, deprecated=False):
self.name = name
self.value = value
self.deprecated = deprecated
def get_config(self):
"""Get in config format"""
return ' %s: %s\n' % (self.name, self.value) if self.value else None
def __str_... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Cisco Systems
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r"""
---
module: external_radius_server
short_description: Resource module for External Radius Server
description:
- Manage operati... | documentation = "\n---\nmodule: external_radius_server\nshort_description: Resource module for External Radius Server\ndescription:\n- Manage operations create, update and delete of the resource External Radius Server.\nversion_added: '1.0.0'\nauthor: Rafael Campos (@racampos)\noptions:\n accountingPort:\n descript... |
"""Bogus module for testing."""
# pylint: disable=missing-docstring,disallowed-name,invalid-name
class ModuleClass:
def __init__(self, x, y):
self.x = x
self.y = y
def a(self):
return self.x + self.y
def module_function(x, y):
return x - y
def kwargs_only_func1(foo, *, bar, ba... | """Bogus module for testing."""
class Moduleclass:
def __init__(self, x, y):
self.x = x
self.y = y
def a(self):
return self.x + self.y
def module_function(x, y):
return x - y
def kwargs_only_func1(foo, *, bar, baz=5):
return foo + bar + baz
def kwargs_only_func2(foo, *, bar... |
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/kalyco/mfp_workspace/src/darknet_ros/darknet_ros_msgs/msg/BoundingBox.msg;/home/kalyco/mfp_workspace/src/darknet_ros/darknet_ros_msgs/msg/BoundingBoxes.msg;/home/kalyco/mfp_workspace/devel/.private/darknet_ros_msgs/share/darknet_ros_msgs/msg/Che... | messages_str = '/home/kalyco/mfp_workspace/src/darknet_ros/darknet_ros_msgs/msg/BoundingBox.msg;/home/kalyco/mfp_workspace/src/darknet_ros/darknet_ros_msgs/msg/BoundingBoxes.msg;/home/kalyco/mfp_workspace/devel/.private/darknet_ros_msgs/share/darknet_ros_msgs/msg/CheckForObjectsAction.msg;/home/kalyco/mfp_workspace/dev... |
# exit from infinite loop v.2
# using flag
prompt = ("\nType 'x' to exit.\nEnter: ")
flag = True
while flag:
msg = input(prompt)
if msg == 'x':
flag = False
else:
print(msg)
| prompt = "\nType 'x' to exit.\nEnter: "
flag = True
while flag:
msg = input(prompt)
if msg == 'x':
flag = False
else:
print(msg) |
text = "".join(input().split())
for index,emoticon in enumerate(text):
if emoticon == ":":
print(f"{emoticon+text[index+1]}")
| text = ''.join(input().split())
for (index, emoticon) in enumerate(text):
if emoticon == ':':
print(f'{emoticon + text[index + 1]}') |
word_size = 4
num_words = 16
words_per_row = 1
local_array_size = 4
output_extended_config = True
output_datasheet_info = True
netlist_only = True
nominal_corner_only = True
| word_size = 4
num_words = 16
words_per_row = 1
local_array_size = 4
output_extended_config = True
output_datasheet_info = True
netlist_only = True
nominal_corner_only = True |
# Intersection Of Sorted Arrays
# https://www.interviewbit.com/problems/intersection-of-sorted-arrays/
#
# Find the intersection of two sorted arrays.
# OR in other words,
# Given 2 sorted arrays, find all the elements which occur in both the arrays.
#
# Example :
#
# Input :
# A : [1 2 3 3 4 5 6]
# B : [3 3 5]... | class Solution:
def intersect(self, A, B):
i = j = 0
res = []
while i < len(A) and j < len(B):
if A[i] == B[j]:
res.append(A[i])
i += 1
j += 1
elif A[i] < B[j]:
i += 1
else:
j... |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# SNMP Error Codes
# ----------------------------------------------------------------------
# Copyright (C) 2007-2017 The NOC Project
# See LICENSE for details
# -------------------------------------------------------------... | no_error = 0
too_big = 1
no_such_name = 2
bad_value = 3
read_only = 4
gen_err = 5
no_access = 6
wrong_type = 7
wrong_length = 8
wrong_encoding = 9
wrong_value = 10
no_creation = 11
inconsistent_value = 12
resource_unavailable = 13
commit_failed = 14
undo_failed = 15
authorization_error = 16
not_writable = 17
inconsiste... |
ACTORS = [
{"id":26073614,"name":"Al Pacino","photo":"https://placebear.com/342/479"},
{"id":77394988,"name":"Anthony Hopkins","photo":"https://placebear.com/305/469"},
{"id":44646271,"name":"Audrey Hepburn","photo":"https://placebear.com/390/442"},
{"id":85626345,"name":"Barbara Stanwyck","photo":"https://placebear.co... | actors = [{'id': 26073614, 'name': 'Al Pacino', 'photo': 'https://placebear.com/342/479'}, {'id': 77394988, 'name': 'Anthony Hopkins', 'photo': 'https://placebear.com/305/469'}, {'id': 44646271, 'name': 'Audrey Hepburn', 'photo': 'https://placebear.com/390/442'}, {'id': 85626345, 'name': 'Barbara Stanwyck', 'photo': 'h... |
class MyRouter(object):
def db_for_read(self, model, **hints):
# if model.__name__ == 'CommonVar':
if model._meta.model_name == 'commontype':
return 'pgsql-ms'
if model._meta.app_label == 'other':
return 'pgsql-ms'
# elif model._meta.app_label in ['auth', 'adm... | class Myrouter(object):
def db_for_read(self, model, **hints):
if model._meta.model_name == 'commontype':
return 'pgsql-ms'
if model._meta.app_label == 'other':
return 'pgsql-ms'
return 'mm-ms'
def db_for_write(self, model, **hints):
if model._meta.model... |
Desc = cellDescClass("RF1R1WX2")
Desc.properties["cell_leakage_power"] = "1118.088198"
Desc.properties["dont_touch"] = "true"
Desc.properties["dont_use"] = "true"
Desc.properties["cell_footprint"] = "regcrw"
Desc.properties["area"] = "33.264000"
Desc.pinOrder = ['IQ', 'IQN', 'RB', 'RW', 'RWN', 'WB', 'WW', 'next']
Desc.... | desc = cell_desc_class('RF1R1WX2')
Desc.properties['cell_leakage_power'] = '1118.088198'
Desc.properties['dont_touch'] = 'true'
Desc.properties['dont_use'] = 'true'
Desc.properties['cell_footprint'] = 'regcrw'
Desc.properties['area'] = '33.264000'
Desc.pinOrder = ['IQ', 'IQN', 'RB', 'RW', 'RWN', 'WB', 'WW', 'next']
Des... |
def compareTriplets(a, b):
alice = 0
bob = 0
for i, j in zip(a, b):
if i > j:
alice += 1
elif i < j:
bob += 1
return alice, bob
| def compare_triplets(a, b):
alice = 0
bob = 0
for (i, j) in zip(a, b):
if i > j:
alice += 1
elif i < j:
bob += 1
return (alice, bob) |
"""
Undirected Graph: There is no direction for Nodes
Directed Graph : Nodes have Connection
One application Example: Facebook Friend Suggestion, Flight Routes
Different from a Tree: In A tree there is only one path between two Nodes
Google maps uses Graphs to guide you to desired place to move to
"""
#Initializing a G... | """
Undirected Graph: There is no direction for Nodes
Directed Graph : Nodes have Connection
One application Example: Facebook Friend Suggestion, Flight Routes
Different from a Tree: In A tree there is only one path between two Nodes
Google maps uses Graphs to guide you to desired place to move to
"""
class Graph:
... |
# a single 3 input neuron
inputs = [1, 2, 3]
weights = [0.2, 0.8, -0.5]
bias = 2
output = (inputs[0] * weights[0] +
inputs[1] * weights[1] +
inputs[2] * weights[2] + bias)
print(output)
| inputs = [1, 2, 3]
weights = [0.2, 0.8, -0.5]
bias = 2
output = inputs[0] * weights[0] + inputs[1] * weights[1] + inputs[2] * weights[2] + bias
print(output) |
''' Adaptable File containing all relevant information
everything that could be used to customise the app for redeployment '''
# file path to log file is '/CA3/sys.log'
def return_local_location() -> str:
''' Return a string of the local city.
To change your local city name change the returned string: ... | """ Adaptable File containing all relevant information
everything that could be used to customise the app for redeployment """
def return_local_location() -> str:
""" Return a string of the local city.
To change your local city name change the returned string: """
return 'Exeter'
def return_html_fil... |
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved.
# Modifications copyright Microsoft
#
# 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/LICENS... | class Horovodinternalerror(RuntimeError):
"""Internal error raised when a Horovod collective operation (e.g., allreduce) fails.
This is handled in elastic mode as a recoverable error, and will result in a reset event.
"""
pass
class Hostsupdatedinterrupt(RuntimeError):
"""Internal interrupt event ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.